vdoc: highlight terminal examples for `-comments -color` (#13937)

pull/13942/head
Nick Treleaven 2022-04-04 16:13:24 +01:00 committed by GitHub
parent aa9e2ebb25
commit 2cd9c91e98
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 26 additions and 6 deletions

View File

@ -161,6 +161,9 @@ fn color_highlight(code string, tb &ast.Table) string {
.char { .char {
lit = term.yellow('`$tok.lit`') lit = term.yellow('`$tok.lit`')
} }
.comment {
lit = if tok.lit[0] == 1 { '//${tok.lit[1..]}' } else { '//$tok.lit' }
}
.keyword { .keyword {
lit = term.bright_blue(tok.lit) lit = term.bright_blue(tok.lit)
} }

View File

@ -104,13 +104,17 @@ fn (vd VDoc) gen_plaintext(d doc.Doc) string {
d.head.merge_comments_without_examples() d.head.merge_comments_without_examples()
} }
if comments.trim_space().len > 0 { 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) vd.write_plaintext_content(d.contents.arr(), mut pw)
return pw.str() 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) { fn (vd VDoc) write_plaintext_content(contents []doc.DocNode, mut pw strings.Builder) {
cfg := vd.cfg cfg := vd.cfg
for cn in contents { 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) pw.writeln(cn.content)
} }
if cn.comments.len > 0 && cfg.include_comments { if cn.comments.len > 0 && cfg.include_comments {
comments := if cfg.include_examples { comments := cn.merge_comments_without_examples()
cn.merge_comments() pw.writeln(indent(comments.trim_space()))
} else { if cfg.include_examples {
cn.merge_comments_without_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 { if cfg.show_loc {
pw.writeln('Location: $cn.file_path:${cn.pos.line_nr + 1}\n') pw.writeln('Location: $cn.file_path:${cn.pos.line_nr + 1}\n')

View File

@ -1098,6 +1098,7 @@ pub fn (s string) count(substr string) int {
} }
// contains returns `true` if the string contains `substr`. // contains returns `true` if the string contains `substr`.
// See also: [`string.index`](#string.index)
pub fn (s string) contains(substr string) bool { pub fn (s string) contains(substr string) bool {
if substr.len == 0 { if substr.len == 0 {
return true return true