From 2cd9c91e98b1a1f64d1e11ee75d8d079167d7674 Mon Sep 17 00:00:00 2001 From: Nick Treleaven Date: Mon, 4 Apr 2022 16:13:24 +0100 Subject: [PATCH] vdoc: highlight terminal examples for `-comments -color` (#13937) --- cmd/tools/vdoc/utils.v | 3 +++ cmd/tools/vdoc/vdoc.v | 28 ++++++++++++++++++++++------ vlib/builtin/string.v | 1 + 3 files changed, 26 insertions(+), 6 deletions(-) diff --git a/cmd/tools/vdoc/utils.v b/cmd/tools/vdoc/utils.v index cbfe3238fe..9bde83b5d9 100644 --- a/cmd/tools/vdoc/utils.v +++ b/cmd/tools/vdoc/utils.v @@ -161,6 +161,9 @@ fn color_highlight(code string, tb &ast.Table) string { .char { lit = term.yellow('`$tok.lit`') } + .comment { + lit = if tok.lit[0] == 1 { '//${tok.lit[1..]}' } else { '//$tok.lit' } + } .keyword { lit = term.bright_blue(tok.lit) } diff --git a/cmd/tools/vdoc/vdoc.v b/cmd/tools/vdoc/vdoc.v index 728a1d63da..bdc02589bc 100644 --- a/cmd/tools/vdoc/vdoc.v +++ b/cmd/tools/vdoc/vdoc.v @@ -104,13 +104,17 @@ fn (vd VDoc) gen_plaintext(d doc.Doc) string { d.head.merge_comments_without_examples() } if comments.trim_space().len > 0 { - pw.writeln(comments.split_into_lines().map(' ' + it).join('\n')) + pw.writeln(indent(comments)) } } vd.write_plaintext_content(d.contents.arr(), mut pw) return pw.str() } +fn indent(s string) string { + return ' ' + s.replace('\n', '\n ') +} + fn (vd VDoc) write_plaintext_content(contents []doc.DocNode, mut pw strings.Builder) { cfg := vd.cfg for cn in contents { @@ -121,12 +125,24 @@ fn (vd VDoc) write_plaintext_content(contents []doc.DocNode, mut pw strings.Buil pw.writeln(cn.content) } if cn.comments.len > 0 && cfg.include_comments { - comments := if cfg.include_examples { - cn.merge_comments() - } else { - cn.merge_comments_without_examples() + comments := cn.merge_comments_without_examples() + pw.writeln(indent(comments.trim_space())) + if cfg.include_examples { + examples := cn.examples() + for ex in examples { + pw.write_string(' Example: ') + mut fex := ex + if ex.index_byte(`\n`) >= 0 { + // multi-line example + pw.write_byte(`\n`) + fex = indent(ex) + } + if cfg.is_color { + fex = color_highlight(fex, vd.docs[0].table) + } + pw.writeln(fex) + } } - pw.writeln(comments.trim_space().split_into_lines().map(' ' + it).join('\n')) } if cfg.show_loc { pw.writeln('Location: $cn.file_path:${cn.pos.line_nr + 1}\n') diff --git a/vlib/builtin/string.v b/vlib/builtin/string.v index c1a8f81ab2..f1252149f3 100644 --- a/vlib/builtin/string.v +++ b/vlib/builtin/string.v @@ -1098,6 +1098,7 @@ pub fn (s string) count(substr string) int { } // contains returns `true` if the string contains `substr`. +// See also: [`string.index`](#string.index) pub fn (s string) contains(substr string) bool { if substr.len == 0 { return true