blib/lib/App/Greple/md.pm

filter: Statementstmt 94.8% 602 / 635 Branchbran 89.6% 260 / 290 Conditioncond 73.0% 133 / 182 MC/DCmcdc 51.4% 52 / 101 Subroutinesub 97.6% 84 / 86 Podpod 0.0% 0 / 44 totaltotal 84.5% 1131 / 1338 CC 236 SCAR 25.4
CC
236
Cov
90%
__ANON__
37.2
format_table
31.0
default_theme
30.0
CRAP 12.7
« blib/lib/App/Greple/md/Mermaid.pm ↑ Summary blib/lib/App/Greple/md/Image.pm »
1 # -*- mode: perl; coding: utf-8 -*-
2 # vim: set fileencoding=utf-8 filetype=perl :
3 package App::Greple::md;
4  
5 341 ▶use 5.026;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 341 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 341 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 341 our $VERSION = "1.33";
10  
11 =encoding utf-8
12  
13 =head1 NAME
14  
15 App::Greple::md - Greple module for Markdown syntax highlighting
16  
17 =head1 SYNOPSIS
18  
19 greple -Mmd file.md
20  
21 greple -Mmd --mode=dark -- file.md
22  
23 greple -Mmd --base-color=Crimson -- file.md
24  
25 greple -Mmd --cm h1=RD -- file.md
26  
27 greple -Mmd --no-table -- file.md
28  
29 greple -Mmd --fold -- file.md
30  
31 greple -Mmd -- --fold file.md
32  
33 greple -Mmd --refill -- file.md
34  
35 =head1 DESCRIPTION
36  
37 B<App::Greple::md> is a L<greple|App::Greple> module for viewing
38 Markdown files in the terminal with syntax highlighting.
39  
40 It colorizes headings, bold, italic, strikethrough, inline code,
41 fenced code blocks, front matter, HTML comments, blockquotes, horizontal rules,
42 links, and images. Tables are formatted with aligned columns and
43 optional Unicode box-drawing borders. Long lines in list items can
44 be folded with proper indentation. Links become clickable via OSC 8
45 terminal hyperlinks in supported terminals.
46  
47 Nested elements are handled with cumulative coloring: for example,
48 a link inside a heading retains both its link color and the heading
49 background color.
50  
51 For a complete Markdown viewing experience with line folding,
52 multi-column output, and themes, see L<App::mdee>, which uses this
53 module as its highlighting engine.
54  
55 Control characters and escape sequences in the file, which could change
56 the title or the clipboard or clear the screen, are removed before
57 anything else, and so are not shown. Colors stay.
58  
59 =head1 COMMAND OPTIONS
60  
61 The following options are defined as greple command options
62 (specified after C<-->).
63  
64 =head2 B<--fold>
65  
66 Enable text folding for list items, definition lists, block quotes
67 and the paragraphs joined by C<--refill>. Long lines are wrapped
68 with proper indentation using L<ansifold(1)|App::ansifold> via
69 L<App::Greple::tee>; the continuation lines of a block quote start with
70 the quote marker again.
71 Code blocks, front matter, HTML comments, and tables are
72 excluded from folding. The fold width is controlled by the
73 C<fold_width> config parameter (default: 80), and the run-in and
74 run-out widths for line breaking (kinsoku) by C<fold_runin> and
75 C<fold_runout> (default: 4, as in ansifold).
76  
77 greple -Mmd -- --fold file.md
78 greple -Mmd::config(fold_width=60) -- --fold file.md
79  
80 Supported list markers: C<*>, C<+>, C<->, C<1.>, C<1)>, C<#.>, C<#)>.
81  
82 The module option C<--fold> (before C<-->) enables the same folding
83 through the config.
84  
85 =head1 MODULE OPTIONS
86  
87 Module options are specified before C<--> to separate them from
88 greple's own options:
89  
90 greple -Mmd --mode=dark --cm h1=RD -- file.md
91  
92 =head2 B<-m> I<MODE>, B<--mode>=I<MODE>
93  
94 Set color mode. Available modes are C<light> (default) and C<dark>.
95  
96 greple -Mmd -m dark -- file.md
97  
98 =head2 B<-B> I<COLOR>, B<--base-color>=I<COLOR>
99  
100 Override the base color used for headings, bold, links, and other
101 elements. Accepts a named color (e.g., C<Crimson>, C<DarkCyan>) or a
102 L<Term::ANSIColor::Concise> color spec.
103  
104 greple -Mmd -B Crimson -- file.md
105  
106 =head2 B<--[no-]colorize>
107  
108 Enable or disable syntax highlighting. Enabled by default.
109 When disabled, no color is applied to Markdown elements.
110  
111 greple -Mmd --no-colorize -- file.md
112  
113 =head2 B<--[no-]fold>
114  
115 Enable or disable text folding (config C<fold>). Disabled by default.
116 When enabled, long lines in list items, definition lists, block
117 quotes and the paragraphs joined by C<--refill> are wrapped with
118 proper indentation.
119 The fold width is controlled by the C<fold_width> config parameter
120 (default: 80).
121  
122 greple -Mmd --fold -- file.md
123 greple -Mmd::config(fold=1,fold_width=60) file.md
124  
125 The greple command option of the same name, C<--fold> after C<-->,
126 folds the same lines once without setting the config.
127  
128 =head2 B<--[no-]refill>
129  
130 Join the lines of paragraphs into one line each (see L</Paragraph
131 Refill>). Disabled by default.
132  
133 =head2 B<--[no-]table>
134  
135 Enable or disable table formatting. When enabled (default),
136 Markdown tables (3 or more consecutive pipe-delimited rows) are
137 formatted with aligned columns using L<App::ansicolumn>. A C<< <br> >>
138 (or C<< <br/> >>, C<< <br /> >>) in a cell breaks the cell into lines
139 after it, and is colored with C<br_mark> (see L</Line Breaks in
140 Tables>); one in a code span, or escaped as C<< \<br> >>, does not. This needs an L<App::ansicolumn> which takes
141 a LINE SEPARATOR (U+2028) as a line break in a cell.
142  
143 greple -Mmd --no-table -- file.md
144  
145 =head2 B<--[no-]rule>
146  
147 Enable or disable Unicode box-drawing characters for table borders.
148 When enabled (default), ASCII pipe characters (C<|>) are replaced
149 with vertical lines (C<E<0x2502>>), and separator row dashes become
150 horizontal rules (C<E<0x2500>>) with corner pieces (C<E<0x251C>>,
151 C<E<0x2524>>, C<E<0x253C>>).
152  
153 greple -Mmd --no-rule -- file.md
154  
155 =head2 B<--colormap> I<LABEL>=I<SPEC>, B<--cm> I<LABEL>=I<SPEC>
156  
157 Override the color for a specific element. I<LABEL> is one of
158 the color labels listed in L</COLOR LABELS>. I<SPEC> follows
159 L<Term::ANSIColor::Concise> format and supports C<sub{...}>
160 function specs via L<Getopt::EX::Colormap>.
161  
162 greple -Mmd --cm h1=RD -- file.md
163 greple -Mmd --cm bold='${base}D' -- file.md
164  
165 B<greple> has an option of the same name. Before C<-->, C<--cm> belongs
166 to this module and takes the labels above. After C<-->, or when there
167 is no C<-->, it is the option of B<greple>, which colors the matched
168 text and its own labels such as C<FILE>, and complains about the labels
169 of this module:
170  
171 greple -Mmd --cm h1=RD -- --cm B -E foo file.md # h1 is red, foo blue
172 greple -Mmd --cm h1=RD file.md # h1: Unknown label
173  
174 =head2 B<--begin> I<FUNCTION>
175  
176 Call I<FUNCTION> on the whole text of each file, in C<$_>, before this
177 module does anything to it, so that the tables and the folded lines
178 follow the change. I<FUNCTION> is a C<sub{...}> or the name of a
179 function, as C<&func(key=value)> or C<&Package::func(key=value)>. A
180 name without a package is looked for in C<main>, and then in the module
181 C<App::Greple::md::func>, named after the function. The package is
182 loaded if the function is not defined yet. A function that is not found
183 is reported with a warning and skipped. The option can be repeated.
184  
185 greple -Mmd --begin 'sub{ s/\(C\)/\x{A9}/g }' -- file.md
186  
187 Unlike the C<--begin> of B<greple> after C<-->, which runs after this
188 module, this one runs before it. In a configuration file or a theme of
189 L<mdee>, it is given as C<pass_md+=(--begin '...')>.
190  
191 L<App::Greple::md::widen> has such a function, C<&widen>.
192  
193 =head2 B<--heading-markup>[=I<STEPS>], B<--hm>[=I<STEPS>]
194  
195 Control inline markup processing inside headings. By default,
196 headings are rendered with uniform heading color without processing
197 bold, italic, strikethrough, or inline code inside them. Links
198 are always processed as OSC 8 hyperlinks regardless of this option.
199  
200 Without an argument, all inline formatting becomes visible within
201 headings using cumulative coloring. With an argument, only the
202 specified steps are processed inside headings. Steps are separated
203 by colons.
204  
205 Available steps: C<inline_code>, C<horizontal_rules>, C<bold>,
206 C<italic>, C<strike>.
207  
208 greple -Mmd --hm -- file.md # all markup
209 greple -Mmd --hm=bold -- file.md # bold only
210 greple -Mmd --hm=bold:italic -- file.md # bold and italic
211  
212 =head2 B<--hashed> I<LEVEL>=I<VALUE>
213  
214 Append closing hashes to headings. For example, C<### Title>
215 becomes C<### Title ###>. Set per heading level:
216  
217 greple -Mmd --hashed h3=1 --hashed h4=1 -- file.md
218  
219 =head2 B<--show> I<LABEL>[=I<VALUE>]
220  
221 Control which elements are highlighted. This is useful for
222 focusing on specific elements or disabling unwanted highlighting.
223  
224 greple -Mmd --show bold=0 -- file.md # disable bold
225 greple -Mmd --show all= --show h1 -- file.md # only h1
226  
227 C<--show LABEL=0> or C<--show LABEL=> disables the label.
228 C<--show LABEL> or C<--show LABEL=1> enables it.
229 C<all> is a special key that sets all labels at once.
230  
231 Controllable labels: C<bold>, C<italic>, C<strike>, C<code_inline>,
232 C<header> (h1-h6), C<horizontal_rule>, C<blockquote>.
233  
234 The following elements are always processed and cannot be disabled:
235 C<comment>, C<code_block> (C<code_mark>, C<code_info>),
236 C<link>, C<image>, C<image_link>, C<image_missing>, C<message>.
237 Use C<--cm LABEL=> to remove their color without disabling processing.
238  
239 =head1 CONFIGURATION
240  
241 Module parameters can also be set using the C<config()> function
242 in the C<-M> declaration:
243  
244 greple -Mmd::config(mode=dark,base_color=Crimson) file.md
245  
246 Nested hash parameters use dot notation:
247  
248 greple -Mmd::config(hashed.h3=1,hashed.h4=1) file.md
249  
250 Available parameters:
251  
252 mode light or dark (default: light)
253 base_color base color override
254 colorize syntax highlighting (default: 1)
255 fold text folding (default: 0)
256 fold_width fold width in columns (default: 80)
257 fold_runin run-in width in folded lines (default: 4)
258 fold_runout run-out width in folded lines (default: 4)
259 refill join the lines of paragraphs (default: 0)
260 refill_parser cmark (the CommonMark module), mdperl (Markdown::Perl)
261 or pandoc (default: the first that is there, in
262 that order)
263 front_matter show TOML and YAML front matter as a code block
264 and leave it alone with refill (default: 1)
265 table table formatting (default: 1)
266 table_trim trim cell whitespace (default: 1)
267 table_width table width in columns; cells of over-wide
268 columns are wrapped (default: 0 = off)
269 table_cell per-column widths passed to ansicolumn --cell,
270 colon separated (e.g. 0:10:<20)
271 table_wrap_mark string put at the start of continuation lines
272 of wrapped cells (default: none)
273 table_cell_mark string put at the start of the first line of
274 every body cell in a column that has a wrapped
275 cell (default: none)
276 table_runin run-in width in wrapped cells (default: 2)
277 table_runout run-out width in wrapped cells (default: 2)
278 table_boundary fold boundary in wrapped cells (default: word)
279 table_linebreak line break mode in wrapped cells: none, runin,
280 runout or all (default: all)
281 intact parts to be kept intact by ansicolumn --intact,
282 separated by colons (default: none): "table"
283 joins the lines of a formatted table by US;
284 "image" joins an image line and the rows of its
285 image by GS, to keep them in one pane
286 keep.TYPE what of a block of the TYPE is kept in one pane,
287 joined by GS; keep.table, with intact=table:
288 none, row (the lines of a row), head (also the
289 header, its rule and the first row) or all
290 (default: head)
291 image_types types of images to show, separated by colons:
292 png, jpeg and gif; the rows of an image are put
293 below a line which is an image, and its data is
294 sent to the terminal (default: none, no images);
295 see Text::ANSI::Image; mermaid draws the diagrams
296 of fenced code blocks of mermaid below them
297 (App::Greple::md::Mermaid)
298 image_rows maximum rows of an image (default: 0, the
299 terminal height minus four lines)
300 image_term size of the terminal as COLSxROWS:WxH, the
301 columns and rows and the width and height of a
302 cell in pixels (default: read from /dev/tty)
303 image_tty file to send the image data to (default: /dev/tty)
304 image_osc 1: each row of an image tells its file by a private
305 OSC, for ansi2pdf, which draws the image itself
306 (default: 0)
307 image_resend a file to which the sequences that send the images
308 again by the paths of their files are appended, for
309 less to send after it switches to the alternate
310 screen (LESS_TERMCAP_ti), where kitty and Ghostty
311 do not show those sent before (default: none)
312 image_align left or center: where an image is put in the fold
313 width, or the terminal width (default: center)
314 mermaid_command command which draws Mermaid diagrams: mmdc of
315 mermaid-cli, mmdr of mermaid-rs-renderer, or
316 mermaidx of PyPI, by the start of its name; mmdc
317 for any other (default: mmdc, or mmdr when only
318 that is found in PATH)
319 mermaid_theme theme of Mermaid: default, dark, forest or neutral
320 (default: dark in the dark mode, or default)
321 mermaid_background background of the diagrams, a color of CSS or
322 transparent (default: #0d1117 in the dark mode,
323 or white, as GitHub shows them)
324 mermaid_scale scale of the diagrams; a larger one takes more
325 cells, up to the fold width (default: 1.5)
326 table_style lattice: column separators (default; pipe is
327 another name); 3line: columns separated by spaces,
328 a rule above and below the table and per column
329 below the header; simple: columns separated by
330 spaces, a rule per column below the header and
331 below the table
332 table_gap columns between a cell and the mark place of the
333 next column, the column separator included
334 (default: 1)
335 rule box-drawing characters (default: 1)
336 osc8 OSC 8 hyperlinks (default: 1)
337 heading_markup inline markup in headings (default: 0)
338 0=off, 1/all=all, or colon-separated steps
339 cjk_friendly markdown-cjk-friendly rules for * and **
340 emphasis (default: 0)
341 tick_open inline code open marker (default: `)
342 tick_close inline code close marker (default: ´)
343 nofork nofork+raw mode for code ref calls (default: 1)
344 highlight syntax highlight of fenced code: 1, the name
345 of a highlighter, or 0 (default: 1)
346 hashed.h1-h6 closing hashes per level (default: 0)
347  
348 =head2 Paragraph Refill
349  
350 With C<refill=1>, the lines of every paragraph, block quote, list
351 item and definition are joined into one line before the text is
352 colorized. Which lines belong together is decided by a Markdown
353 parser (L<App::Greple::md::Blocks>): the L<CommonMark> module, an
354 interface to libcmark, when it is installed, otherwise
355 L<Markdown::Perl>, which is pure Perl and always installed with this
356 module, or L<pandoc|https://pandoc.org> (2.11.3 or later) run with the
357 C<sourcepos> extension; C<refill_parser> chooses one. The module
358 joins the lines of the original text and changes nothing else. Hard
359 line breaks are kept, and so is the break before a list marker, a
360 horizontal rule, a table row or a definition (C<: >). When folding
361 is enabled, the joined lines are folded too.
362  
363 Front matter (see L</Front Matter>) is left as it is.
364  
365 greple -Mmd::config(refill=1) file.md
366 greple -Mmd::config(refill=1,refill_parser=pandoc) file.md
367  
368 =head2 Front Matter
369  
370 Front matter at the top of the file is shown as a code block: the
371 body in C<meta_block> and the delimiter lines in C<meta_mark>, with
372 no other markup, and it is not folded or joined.
373 TOML front matter is between C<+++> lines, and YAML front matter goes
374 from a C<---> line to a C<---> or C<...> line, as pandoc takes it (the
375 opening line is not followed by a blank line).
376  
377 Front matter is not part of CommonMark. pandoc and L<Markdown::Perl>
378 take YAML front matter as metadata, while libcmark reads it as a rule,
379 paragraphs and list items. C<front_matter=0> takes the lines as
380 Markdown, as libcmark does.
381  
382 =head2 Syntax Highlight of Code
383  
384 The code in a fenced code block is shown in the colors of its
385 language, the first word after the opening fence, inside the
386 C<code_block> color. The colors are those of a highlighter of
387 L<Text::ANSI::Highlight>: C<highlight=1> is its default, C<pandoc>,
388 and C<highlight=sourcehighlight> (C<gnu>) or C<highlight=skylighting>
389 (C<sky>) is the one of the name. All the blocks of a file are given
390 to the highlighter at once, and each is colored by itself.
391  
392 C<highlight=1> is C<pandoc> in its own style in the light mode, and in
393 the style C<breezedark> in the dark mode. A style of the highlighter
394 can be named after a colon (C<highlight=pandoc:haddock>), and a
395 highlighter which is named is as it is named in both modes. The
396 background colors of a style are not used: the background is that of
397 the code block.
398  
399 The language is also the first class in braces, as pandoc takes it
400 (C<```{.perl .numberLines}>).
401  
402 A block which has parts is colored part by part, when
403 L<Text::ANSI::Highlight> has a module for it. A block of
404 L<pandoc-embedz|https://github.com/tecolicom/pandoc-embedz>
405 (C<```embedz>, C<```{.embedz data=file.csv}>) has a configuration in
406 YAML, a template of Jinja2 and data: they are colored by their
407 languages, in the backgrounds of C<code_config>, C<code_block> and
408 C<code_data>, and the lines of C<---> between them have no color.
409 The lines of a part labelled I<NAME> by the module are in the color
410 C<code_I<NAME>>, and in C<code_block> when it is not defined.
411  
412 A block is shown as it is when it has no language, when the
413 highlighter does not know the language, and when the module, the
414 highlighter or its command (C<pandoc>, C<source-highlight>,
415 C<skylighting>) is not installed. C<highlight=0> turns it off.
416  
417 =head2 OSC 8 Hyperlinks
418  
419 Links are converted to clickable OSC 8 terminal hyperlinks in
420 supported terminals (iTerm2, Kitty, WezTerm, Ghostty, etc.).
421 Disable with:
422  
423 greple -Mmd::config(osc8=0) file.md
424  
425 =head2 Settings of the User
426  
427 The module runs B<ansifold> and B<ansicolumn> for folding and tables.
428 They are run as functions in the greple process, or as separate
429 processes with C<nofork=0>, and either way they do not read the rc
430 files of the user, F<~/.ansifoldrc> and F<~/.ansicolumnrc>: the
431 module puts their names in the environment variable
432 C<GETOPTEX_NO_USER_SETTINGS> (see L<Getopt::EX::Long>), so that the
433 output does not change by the settings made for them on the command
434 line.
435  
436 =head1 COLOR LABELS
437  
438 The following labels identify colorizable elements. Use them
439 with C<--colormap> (C<--cm>) to customize colors or C<--show> to control
440 visibility. Default values are shown as C<light / dark>.
441 Colors follow L<Term::ANSIColor::Concise> format.
442  
443 =head2 Headings
444  
445 LABEL LIGHT DARK
446 h1 L25D/${base};E L00D/${base};E
447 h2 L25D/${base}+y20;E L00D/${base}-y15;E
448 h3 L25DN/${base}+y20 L00DN/${base}-y15
449 h4 ${base}UD ${base}UD
450 h5 ${base}UD ${base}UD
451 h6 ${base}D ${base}D
452  
453 =head2 Inline Formatting
454  
455 LABEL LIGHT DARK
456 bold D
457 italic I
458 strike X
459 emphasis_mark L18 L10
460 bold_mark - -
461 italic_mark - -
462 strike_mark - -
463  
464 Emphasis markers (C<**>, C<*>, C<__>, C<_>, C<~~>) are colored with
465 C<emphasis_mark>, separately from the content text. C<bold_mark>,
466 C<italic_mark>, C<strike_mark> are undefined by default and fall back
467 to C<emphasis_mark>. Define them via C<--cm> to override per type:
468  
469 greple -Mmd --cm emphasis_mark=R -- file.md # all markers red
470 greple -Mmd --cm bold_mark=G -- file.md # bold markers green
471  
472 C<*> and C<**> start and end emphasis as in CommonMark: a delimiter
473 next to a letter on one side and punctuation on the other does not
474 count, so C<L*=50, a*=68> is not italic. In Japanese text this also
475 rejects C<日本語の*「強調」*です> and C<日本語の**強調。**です>, as the
476 commonmark and gfm readers of pandoc do. With C<cjk_friendly=1>,
477 the rules of
478 L<markdown-cjk-friendly|https://github.com/tats-u/markdown-cjk-friendly>
479 are used instead, and these are emphasis.
480  
481 =head2 Code
482  
483 LABEL LIGHT DARK
484 code_mark L20 L10
485 code_tick L15/L23 L15/L05
486 code_info ${base_name}=y70 L10
487 code_block /L24;E /L03;E
488 code_config /#ECE9F7;E /#1C1B24;E
489 code_data /#E3F1EA;E /#181E1A;E
490 code_inline L00/L23 L25/L05
491 meta_mark L15/L10E L10/L15E
492 meta_block L25/L12E L00/L13E
493  
494 Inline code backticks are displayed as C<`contentE<0xb4>> using
495 C<code_tick> color. Multi-backtick delimiters are collapsed to a
496 single pair with optional surrounding spaces stripped (per CommonMark).
497 The open/close markers can be customized via C<tick_open>/C<tick_close>
498 config parameters.
499  
500 C<code_config> and C<code_data> are the backgrounds of the
501 configuration and the data in a block of pandoc-embedz (see
502 L</Syntax Highlight of Code>).
503  
504 C<meta_mark> and C<meta_block> color the delimiter lines and the
505 body of front matter (see L</Front Matter>), the delimiter lines in
506 the background of the file name and the body a little apart from it.
507 When they are set to empty, C<meta_block> falls back to C<code_block>,
508 and the delimiter lines are in C<code_mark> inside the color of the
509 body.
510  
511 =head2 Block Elements
512  
513 LABEL LIGHT / DARK
514 blockquote ${base}
515 horizontal_rule L15
516 comment ${base}+r60
517  
518 =head2 Links
519  
520 LABEL LIGHT / DARK
521 link I
522 image I
523 image_link I
524 image_missing RI
525 link_mark - -
526  
527 C<link_mark> colors the brackets (C<[>, C<]>) around link and image
528 text. Undefined by default, falls back to C<emphasis_mark>.
529 The C<!> prefix for images uses the C<image> or C<image_link>
530 color. An image whose file is not found, by a path relative to the
531 file being shown, is in the C<image_missing> color instead, for the
532 author to see; a URL and the standard input are not looked at.
533 Hide brackets with C<--cm 'link_mark=sub{""}'> (used by the
534 C<nomark> theme).
535  
536 =head2 Messages
537  
538 LABEL LIGHT / DARK
539 message R
540  
541 A message from a command that the module runs, which is not a part of
542 the text, is put below the part it is about in a shadow box of
543 L<ansicolumn(1)|App::ansicolumn>, as wide as the fold width (or the
544 terminal), with the name of the command on its top, in the
545 C<message> color; a long line is folded in the box, and the box is
546 kept in one pane, as an image is (C<intact=image>). Only a command
547 that fails with something written to the standard error has one; a
548 command that is not installed has none. The message of B<mmdr>,
549 when a Mermaid diagram cannot be drawn, goes below the closing
550 fence, in place of the diagram:
551  
552 ```mermaid
553 flowchat LR
554 A --> B
555 ```
556 ┌─ mmdr ──────────────────────────────────────────────┐
557 │ error: unknown or missing Mermaid diagram header ▐▌
558 └▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▟▌
559  
560 =head2 Line Breaks in Tables
561  
562 LABEL LIGHT / DARK
563 br_mark - -
564  
565 C<br_mark> colors a C<< <br> >> which breaks a table cell into lines
566 (see B<--[no-]table>). Undefined by default, falls back to
567 C<emphasis_mark>. Hide it with C<--cm 'br_mark=sub{""}'> (used by
568 the C<nomark> theme): the line break is left, and the tag is not
569 shown.
570  
571 =head1 SEE ALSO
572  
573 =over 4
574  
575 =item L<App::mdee>
576  
577 Markdown viewer command with line folding, table formatting,
578 multi-column layout, and themes. Uses this module for syntax
579 highlighting.
580  
581 =item L<App::Greple>
582  
583 General-purpose extensible grep tool that hosts this module.
584  
585 =item L<Term::ANSIColor::Concise>
586  
587 Concise ANSI color specification format used for color labels.
588  
589 =item L<App::ansicolumn>
590  
591 ANSI-aware column formatting used for table alignment.
592  
593 =item L<App::ansifold>
594  
595 ANSI-aware text folding used for line wrapping in list items.
596  
597 =item L<App::Greple::md::widen>
598  
599 A function for B<--begin>, for characters that terminals draw over two
600 columns.
601  
602 =item L<App::Greple::md::Blocks>
603  
604 Finds the paragraphs for C<refill=1> with L<CommonMark>,
605 L<Markdown::Perl> or L<pandoc|https://pandoc.org>.
606  
607 =item L<Text::ANSI::Image>
608  
609 Shows the images for C<image_types>, with the Unicode placeholders
610 of the kitty graphics protocol. L<App::Greple::md::Image> finds
611 their files.
612  
613 =item L<CommonMark Spec 0.31.2, Emphasis and strong emphasis|https://spec.commonmark.org/0.31.2/#emphasis-and-strong-emphasis>
614  
615 The rules that C<*> and C<**> follow by default.
616  
617 =item L<CommonMark CJK-friendly Amendments|https://github.com/tats-u/markdown-cjk-friendly/blob/main/specification.md>
618  
619 The rules that C<cjk_friendly=1> follows. The proposal comes from
620 L<commonmark-spec issue #650, Emphasis with CJK punctuation|https://github.com/commonmark/commonmark-spec/issues/650>,
621 open since 2020.
622  
623 =back
624  
625 =head1 AUTHOR
626  
627 Kazumasa Utashiro
628  
629 =head1 LICENSE
630  
631 Copyright © 2025-2026 Kazumasa Utashiro.
632  
633 This library is free software; you can redistribute it and/or modify
634 it under the same terms as Perl itself.
635  
636 =cut
637  
638 341 ▶use URI::Escape;
Subroutine BEGIN: called CC=1 SCAR=0.0
639 341 ▶use List::Util qw(min);
Subroutine BEGIN: called CC=1 SCAR=0.0
640 341 ▶use Text::ANSI::Fold qw($csi_re $osc_re);
Subroutine BEGIN: called CC=1 SCAR=0.0
641 341 ▶use Text::ANSI::Fold::Util qw(ansi_width);
Subroutine BEGIN: called CC=1 SCAR=0.0
642 341 ▶use Getopt::EX::Config;
Subroutine BEGIN: called CC=1 SCAR=0.0
643 341 ▶use Getopt::EX::Colormap;
Subroutine BEGIN: called CC=1 SCAR=0.0
644 341 ▶use Getopt::EX::Func qw(parse_func);
Subroutine BEGIN: called CC=1 SCAR=0.0
645 341 ▶use App::Greple::Common qw(FILELABEL);
Subroutine BEGIN: called CC=1 SCAR=0.0
646 341 ▶use App::Greple::Regions qw(match_regions);
Subroutine BEGIN: called CC=1 SCAR=0.0
647 341 ▶use App::Greple::md::Blocks qw(blocks);
Subroutine BEGIN: called CC=1 SCAR=0.0
648 341 ▶use App::Greple::md::Image qw(local_path);
Subroutine BEGIN: called CC=1 SCAR=0.0
649 341 ▶use App::Greple::md::Mermaid qw(diagram_files);
Subroutine BEGIN: called CC=1 SCAR=0.0
650 341 ▶use Text::ANSI::Image;
Subroutine BEGIN: called CC=1 SCAR=0.0
651  
652 341 my @color_labels = qw(
653 code_mark code_tick code_info code_block code_inline
654 code_config code_template code_data
655 meta_mark meta_block
656 comment link image image_link image_missing message
657 h1 h2 h3 h4 h5 h6
658 bold italic strike emphasis_mark
659 bold_mark italic_mark strike_mark link_mark br_mark
660 blockquote horizontal_rule
661 );
662  
663 my $config = Getopt::EX::Config->new(
664 mode => '', # light / dark
665 osc8 => 1, # OSC 8 hyperlinks
666 base_color => '', # override base color
667 colorize => 1, # syntax highlighting
668 fold => 0, # text folding
669 refill => 0, # join the lines of paragraphs
670 refill_parser => '', # cmark (CommonMark module), mdperl (Markdown::Perl) or pandoc; '' = whichever is there
671 front_matter => 1, # front matter (+++ TOML, --- YAML) at the top is a code block
672 fold_width => 80, # fold width
673 fold_runin => 4, # run-in width in folded lines (ansifold default)
674 fold_runout => 4, # run-out width in folded lines (ansifold default)
675 table => 1, # table formatting
676 table_trim => 1, # trim cell content whitespace
677 table_width => 0, # table width; wrap over-wide cells (0 = off)
678 table_cell => '', # per-column widths for ansicolumn --cell (colon separated)
679 table_wrap_mark => '', # mark for continuation lines of wrapped cells
680 table_cell_mark => '', # mark for the first line of cells in wrapped columns
681 table_runin => 2, # run-in width in wrapped cells
682 table_runout => 2, # run-out width in wrapped cells
683 table_boundary => 'word', # fold boundary in wrapped cells
684 table_linebreak => 'all', # line break (kinsoku) mode in wrapped cells
685 intact => '', # parts kept intact by ansicolumn --intact (table, image)
686 keep => { table => 'head' }, # what is kept in one pane, per type of block
687 image_types => '', # types of images shown, colon separated (png:jpeg:gif)
688 image_rows => 0, # rows that an image may take (0: those of the terminal but four)
689 image_term => '', # size of the terminal, COLSxROWS:WxH (default: of /dev/tty)
690 image_tty => '', # where the data of the images goes (default: /dev/tty)
691 image_osc => 0, # tell the file of each image in its rows, for ansi2pdf
692 image_resend => '', # file for the sequences which send the images again by their files
693 image_align => 'center', # where an image is put: left or center
694 mermaid_command => '', # command which draws Mermaid diagrams (default: mmdc, or mmdr when only that is found)
695 mermaid_theme => '', # theme of Mermaid (default: dark in the dark mode, or default)
696 mermaid_background => '', # background of the diagrams, a color of CSS (default: #0d1117 in the dark mode, or white)
697 mermaid_scale => 0, # scale of the diagrams (default: 1.5)
698 rule => 1, # box-drawing characters for tables
699 table_style => 'lattice', # lattice (or pipe): column separators; 3line, simple: spaces and rules only
700 table_gap => 1, # columns from a cell to the mark place of the next column
701 nofork => 1, # use nofork+raw for code ref calls
702 highlight => 1, # syntax highlight of fenced code: 1, the name of a highlighter, or 0
703 heading_markup => 0, # inline formatting in headings
704 cjk_friendly => 0, # markdown-cjk-friendly rules for * and ** emphasis
705 tick_open => '`', # inline code open marker
706 tick_close => "\x{b4}", # inline code close marker (´)
707 hashed => { h1 => 0, h2 => 0, h3 => 0, h4 => 0, h5 => 0, h6 => 0 },
708 341 (map { $_ => undef } @color_labels), # color labels (undef = not set)
709 );
710  
711 #
712 # Color definitions
713 #
714  
715 341 my %base_color = (
716 light => '<RoyalBlue>=y25',
717 dark => '<RoyalBlue>=y80',
718 );
719  
720 341 my %default_colors = (
721 code_mark => 'L20',
722 code_tick => 'L15/L23',
723 code_info => '${base_name}=y70',
724 code_block => '/L24;E',
725 code_config => '/#ECE9F7;E',
726 code_data => '/#E3F1EA;E',
727 code_inline => 'L00/L23',
728 meta_mark => 'L15/L10E',
729 meta_block => 'L25/L12E',
730 comment => '${base}+r60',
731 link => 'I',
732 image => 'I',
733 image_link => 'I',
734 image_missing => 'RI',
735 message => 'R',
736 h1 => 'L25D/${base};E',
737 h2 => 'L25D/${base}+y20;E',
738 h3 => 'L25DN/${base}+y20',
739 h4 => '${base}UD',
740 h5 => '${base}UD',
741 h6 => '${base}D',
742 bold => 'D',
743 italic => 'I',
744 strike => 'X',
745 emphasis_mark => 'L18',
746 blockquote => '${base}',
747 horizontal_rule => 'L15',
748 );
749  
750 341 my %dark_overrides = (
751 code_mark => 'L10',
752 code_tick => 'L15/L05',
753 code_info => 'L10',
754 code_block => '/L03;E',
755 code_config => '/#1C1B24;E',
756 code_data => '/#181E1A;E',
757 code_inline => 'L25/L05',
758 meta_mark => 'L10/L15E',
759 meta_block => 'L00/L13E',
760 h1 => 'L00D/${base};E',
761 h2 => 'L00D/${base}-y15;E',
762 h3 => 'L00DN/${base}-y15',
763 h4 => '${base}UD',
764 h5 => '${base}UD',
765 h6 => '${base}D',
766 emphasis_mark => 'L10',
767 );
768  
769 0 ▶sub default_theme {
Subroutine default_theme: not called CC=5 SCAR=34.0
Pod undocumented
770 0 ▶ my $mode = shift // 'light';
Condition0%0/2
shift() // "light"
l!l
00
MC/DC0%0/1
shift() // "light"
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
771 0 my %colors = %default_colors;
772 0 ▶ if ($mode eq 'dark') {
Branch: 1 branch
BranchTrueFalseTotal
if ($mode eq "dark") 0 0 0
773 0 @colors{keys %dark_overrides} = values %dark_overrides;
774 }
775 0 $colors{base} = $base_color{$mode};
776 0 ▶ if (defined wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined wantarray) { } 0 0 0
777 0 %colors;
778 } else {
779 # Print as bash array assignments: theme_MODE[key]='value'
780 0 for my $key (sort keys %colors) {
781 0 (my $val = $colors{$key}) =~ s/'/'\\''/g;
782 0 printf "theme_%s[%s]='%s'\n", $mode, $key, $val;
783 }
784 }
785 }
786  
787 341 my $cm;
788 my @opt_cm;
789 341 my @opt_begin;
790 341 my %show;
791  
792 333 ▶sub finalize {
Subroutine finalize: called CC=5 SCAR=16.7
Pod undocumented
793 333 my($mod, $argv) = @_;
794 333 no_user_settings(qw(ansicolumn ansifold));
795 333 $config->deal_with($argv,
796 "mode|m=s", "base_color|B=s",
797 "colorize!", "nofork!", "fold!", "refill!", "refill_parser=s", "front_matter!", "fold_width=i", "fold_runin=i", "fold_runout=i",
798 "table!", "table_trim!",
799 "table_width=i", "table_cell=s", "table_wrap_mark=s", "table_cell_mark=s", "rule!", "table_style=s", "table_gap=i",
800 "table_runin=i", "table_runout=i", "table_boundary=s", "table_linebreak=s", "intact=s", "keep=s%", "image_types=s", "image_rows=i", "image_term=s", "image_tty=s", "image_osc=i", "image_resend=s", "image_align=s", "mermaid_command=s", "mermaid_theme=s", "mermaid_background=s", "mermaid_scale=f",
801 "heading_markup|hm:s", "cjk_friendly!", "tick_open=s", "tick_close=s",
802 "hashed=s%",
803 "colormap|cm=s" => \@opt_cm,
804 "begin=s" => \@opt_begin,
805 "show=s%" => \%show);
806 # --hm with no argument gives "": treat as "all"
807 333 my $hm = $config->{heading_markup};
808 333 ▶ if (defined $hm && $hm eq '') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $hm and $hm eq "") 0 333 333
Condition33%1/3
defined $hm and $hm eq ""
!ll&&!rl&&r
03330
MC/DC0%0/2
defined $hm and $hm eq ""
defined $hm $hm eq ""
Truth table33%1/3
A and B
A= defined $hmB= $hm eq ""
ABresult
0X0
100
111
809 0 $config->{heading_markup} = 'all';
810 }
811 333 ▶ if (my $w = $config->{fold_width}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $w = $config->{"fold_width"}) 333 0 333
812 333 my $fold = join ' ', '--fold-by', $w, @{$config}{qw(fold_runin fold_runout)};
813 333 $mod->setopt('--fold', $fold);
814 333 ▶ if ($config->{fold}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($config->{"fold"}) 92 241 333
815 92 my @default = $mod->default;
816 92 $mod->setopt('default', @default, $fold);
817 }
818 }
819 }
820  
821 # ansicolumn and ansifold are called as functions in this process
822 # (Command::Run), or as separate processes by the tee module in fork
823 # mode. Either way they must not read the rc files of the user, so
824 # their names go into GETOPTEX_NO_USER_SETTINGS (Getopt::EX >= 3.05),
825 # which Getopt::EX::Long reads when the program first runs. Names
826 # already there are kept, and 1 or * (all programs) is left as it is.
827 339 ▶sub no_user_settings {
Subroutine no_user_settings: called CC=4 SCAR=13.9
Pod undocumented
828 339 my @names = @_;
829 339 ▶ my $env = $ENV{GETOPTEX_NO_USER_SETTINGS} // '';
Condition100%2/2
$ENV{"GETOPTEX_NO_USER_SETTINGS"} // ""
l!l
5334
MC/DC100%1/1
$ENV{"GETOPTEX_NO_USER_SETTINGS"} // ""
$ENV{"GETOPTEX_NO_USER_SETTINGS"}
Truth table100%2/2
A
A= $ENV{"GETOPTEX_NO_USER_SETTINGS"}
Aresult
11
00
830 339 ▶ return if $env eq '1' or $env eq '*';
Branch: 1 branch
BranchTrueFalseTotal
if $env eq 1 or $env eq "*" 2 337 339
Condition100%3/3
$env eq 1 or $env eq "*"
l!l&&r!l&&!r
11337
MC/DC100%2/2
$env eq 1 or $env eq "*"
$env eq 1 $env eq "*"
Truth table100%3/3
A or B
A= $env eq 1B= $env eq "*"
ABresult
1X1
011
000
831 337 my %have = map { $_ => 1 } split /[\s,]+/, $env;
832 $ENV{GETOPTEX_NO_USER_SETTINGS} =
833 337 join ' ', grep { length } $env, grep { !$have{$_}++ } @names;
834 }
835  
836 228 ▶sub setup_colors {
Subroutine setup_colors: called CC=13 SCAR=29.0
Pod undocumented
837 228 ▶ my $mode = $config->{mode} || 'light';
Condition100%2/2
$config->{'mode'} || 'light'
l!l
18048
MC/DC100%1/1
$config->{'mode'} || 'light'
$config->{'mode'}
Truth table100%2/2
A
A= $config->{'mode'}
Aresult
11
00
838 228 my %colors = %default_colors;
839 228 ▶ if ($mode eq 'dark') {
Branch: 1 branch
BranchTrueFalseTotal
if ($mode eq "dark") 12 216 228
840 12 @colors{keys %dark_overrides} = values %dark_overrides;
841 }
842 # Determine base color
843 228 my $base = $config->{base_color};
844 228 ▶ if ($base) {
Branch: 1 branch
BranchTrueFalseTotal
if ($base) { } 0 228 228
845 # Color names get automatic luminance adjustment
846 0 ▶ $base = "<$base>" . ($mode eq 'dark' ? '=y80' : '=y25')
Branch: 2 branches
BranchTrueFalseTotal
if $base =~ /^[A-Za-z]\w*$/u 0 0 0
$mode eq 'dark' ? : 0 0 0
847 if $base =~ /^[A-Za-z]\w*$/;
848 } else {
849 228 ▶ $base = $base_color{$mode} || $base_color{light};
Condition33%1/3
$base_color{$mode} || $base_color{'light'}
l!l&&r!l&&!r
22800
MC/DC0%0/2
$base_color{$mode} || $base_color{'light'}
$base_color{$mode} $base_color{'light'}
Truth table33%1/3
A || B
A= $base_color{$mode}B= $base_color{'light'}
ABresult
1X1
011
000
850 }
851 # Override with config params (e.g., config(h1=RD))
852 228 for my $key (@color_labels) {
853 7524 my $val = $config->{$key};
854 7524 ▶ if (defined $val) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $val) 15 7509 7524
855 15 $colors{$key} = $val;
856 }
857 }
858 # ${base_name}: color without luminance (e.g., '<RoyalBlue>')
859 228 (my $base_name = $base) =~ s/=y\d+$//;
860 # Expand placeholders
861 228 for my $key (keys %colors) {
862 6156 $colors{$key} =~ s/\$\{base_name\}/$base_name/g;
863 6156 $colors{$key} =~ s/\$\{base\}/$base/g;
864 }
865 # Handle + prefix: prepend current color value before load_params
866 # (load_params' built-in + doesn't work correctly with sub{...})
867 228 my @final_cm;
868 228 for my $entry (@opt_cm) {
869 280 my $expanded = $entry =~ s/\$\{base_name\}/$base_name/gr
870 =~ s/\$\{base\}/$base/gr;
871 280 ▶ if ($expanded =~ /^(\w+)=\+(.*)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expanded =~ /^(\w+)=\+(.*)/u) { } 0 280 280
872 0 my ($label, $append) = ($1, $2);
873 0 ▶ my $current = $colors{$label} // '';
Condition0%0/2
$colors{$label} // ""
l!l
00
MC/DC0%0/1
$colors{$label} // ""
$colors{$label}
Truth table0%0/2
A
A= $colors{$label}
Aresult
11
00
874 0 push @final_cm, "$label=$current$append";
875 } else {
876 280 push @final_cm, $expanded;
877 }
878 }
879  
880 228 $cm = Getopt::EX::Colormap->new(
881 HASH => \%colors,
882 NEWLABEL => 1,
883 );
884 228 $cm->load_params(@final_cm);
885 }
886  
887 2298 ▶sub active {
Subroutine active: called CC=4 SCAR=13.9
Pod undocumented
888 2298 my $label = shift;
889 2298 ▶ return 0 if exists $show{$label} && !$show{$label};
Branch: 1 branch
BranchTrueFalseTotal
if exists $show{$label} and not $show{$label} 17 2281 2298
Condition100%3/3
exists $show{$label} and not $show{$label}
!ll&&!rl&&r
2279217
MC/DC100%2/2
exists $show{$label} and not $show{$label}
exists $show{$label} not $show{$label}
Truth table100%3/3
A and not(B)
A= exists $show{$label}B= not $show{$label}
ABresult
0X0
100
111
890 2281 ▶ return 1 unless exists $cm->{HASH}{$label};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $cm->{"HASH"}{$label} 163 2118 2281
891 2118 $cm->{HASH}{$label} ne '';
892 }
893  
894 #
895 # Apply color by label
896 #
897  
898 7945 ▶sub md_color {
Subroutine md_color: called CC=1 SCAR=0.0
Pod undocumented
899 7945 my($label, $text) = @_;
900 7945 $cm->color($label, $text);
901 }
902  
903 23 ▶sub defined_color {
Subroutine defined_color: called CC=2 SCAR=6.9
Pod undocumented
904 23 my $label = shift;
905 23 ▶ exists $cm->{HASH}{$label} && $cm->{HASH}{$label} ne '';
Branch: 1 branch
BranchTrueFalseTotal
exists $cm->{"HASH"}{$label} and $cm->{"HASH"}{$label} ne "" 21 2 23
906 }
907  
908 # The color of $label, or of $fallback when $label is not defined
909 17 ▶sub fallback_color {
Subroutine fallback_color: called CC=2 SCAR=6.9
Pod undocumented
910 17 my($label, $fallback, $text) = @_;
911 17 ▶ $label = $fallback unless defined_color($label);
Branch: 1 branch
BranchTrueFalseTotal
unless defined_color($label) 5 12 17
912 17 md_color($label, $text);
913 }
914  
915 1824 ▶sub mark_color {
Subroutine mark_color: called CC=3 SCAR=11.0
Pod undocumented
916 1824 my($type, $text) = @_;
917 1824 my $label = "${type}_mark";
918 $label = 'emphasis_mark' unless exists $cm->{HASH}{$label}
919 1824 ▶ && $cm->{HASH}{$label} ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless exists $cm->{"HASH"}{$label} and $cm->{"HASH"}{$label} ne "" 1450 374 1824
Condition66%2/3
exists $cm->{"HASH"}{$label} and $cm->{"HASH"}{$label} ne ""
!ll&&!rl&&r
14500374
MC/DC50%1/2
exists $cm->{"HASH"}{$label} and $cm->{"HASH"}{$label} ne ""
exists $cm->{"HASH"}{$label} $cm->{"HASH"}{$label} ne ""
Truth table66%2/3
A and B
A= exists $cm->{"HASH"}{$label}B= $cm->{"HASH"}{$label} ne ""
ABresult
0X0
100
111
920 1824 md_color($label, $text);
921 }
922  
923 #
924 # Protection mechanism
925 #
926 # SGR 256 placeholders protect processed regions (inline code,
927 # comments, links) from being matched by later patterns.
928 #
929  
930 341 my @protected;
931 341 my($PS, $PE) = ("\e[256m", "\e[m"); # protect start/end markers
932 341 my $PR = qr/\e\[256m(\d+)\e\[m/; # protect restore pattern
933 341 my($OS, $OE) = ("\e]8;;", "\e\\"); # OSC 8 start/end markers
934  
935 2436 ▶sub protect {
Subroutine protect: called CC=1 SCAR=0.0
Pod undocumented
936 2436 my $text = shift;
937 2436 push @protected, $text;
938 2436 $PS . $#protected . $PE;
939 }
940  
941 1049 ▶sub restore {
Subroutine restore: called CC=3 SCAR=11.0
Pod undocumented
942 1049 my $s = shift;
943 1049 ▶ 1 while $s =~ s{$PR}{$protected[$1] // die "restore failed: index $1"}ge;
Branch: 1 branch
BranchTrueFalseTotal
$s =~ s[$PR][$protected[$1] // die("restore failed: index $1");]egu and do { '???' } 238 1049 1287
Condition50%1/2
$protected[$1] // die("restore failed: index $1")
l!l
24370
MC/DC0%0/1
$protected[$1] // die("restore failed: index $1")
$protected[$1]
Truth table50%1/2
A
A= $protected[$1]
Aresult
11
00
944 1049 $s;
945 }
946  
947 #
948 # OSC 8 hyperlink generation
949 #
950  
951 370 ▶sub osc8 {
Subroutine osc8: called CC=2 SCAR=7.0
Pod undocumented
952 370 ▶ return $_[1] unless $config->{osc8};
Branch: 1 branch
BranchTrueFalseTotal
unless $config->{"osc8"} 0 370 370
953 370 my($url, $text) = @_;
954 370 my $escaped = uri_escape_utf8($url, "^\\x20-\\x7e");
955 370 "${OS}${escaped}${OE}${text}${OS}${OE}";
956 }
957  
958 #
959 # Link text inner pattern: backtick spans, backslash escapes, normal chars
960 #
961  
962 341 my $LT = qr/(?:`[^`\n]*+`|\\.|[^`\\\n\]]++)+/;
963  
964 # Code span pattern (both single and multi-backtick).
965 # Captures: _bt (backtick delimiter), _content (code body).
966 # Used directly in inline_code step and as basis for $SKIP_CODE.
967 341 my $CODE = qr{(?x)
968 (?<_bt> `++ ) # opening backtick(s)
969 (?<_content>
970 (?: (?! \g{_bt} ) . )+? # content (not containing same-length backticks)
971 )
972 \g{_bt} # closing backtick(s) matching opener
973 };
974  
975 # Skip code spans in link/image patterns.
976 # Used as the first alternative in s{$SKIP_CODE|<link pattern>}{...}ge
977 # so that code spans are matched and skipped, preventing link/image
978 # patterns from matching inside them.
979 341 my $SKIP_CODE = qr{$CODE (*SKIP)(*FAIL)}x;
980  
981 # Delimiters of * and ** emphasis (CommonMark 0.31.2, 6.2): an opener
982 # must be left-flanking and a closer right-flanking, so that
983 # "L*=50, a*=68" is not italic. Punctuation is Unicode punctuation and
984 # symbols. An opener after $tight (neither a space nor punctuation)
985 # cannot have punctuation after it, and a closer before $tight cannot
986 # have punctuation before it.
987 #
988 # With cjk_friendly=1 the amendments of markdown-cjk-friendly apply:
989 # CJK punctuation does not count, and a CJK character is as good as a
990 # space on the other side, so that "日本語の*「強調」*です" is italic.
991 # See CLAUDE.md.
992 341 ▶my $EMOJI = eval q{ qr/\p{Emoji_Presentation}/ } // qr/(?!)/; # not in old perl
Condition50%1/2
eval " qr/\p{Emoji_Presentation}/ " // qr/(?!)/u
l!l
3410
MC/DC0%0/1
eval " qr/\p{Emoji_Presentation}/ " // qr/(?!)/u
eval " qr/\p{Emoji_Presentation}/ "
Truth table50%1/2
A
A= eval " qr/\p{Emoji_Presentation}/ "
Aresult
11
00
993 341 my $CJK = qr/(?:(?!$EMOJI)[\p{EA=W}\p{EA=F}\p{EA=H}]|\p{Hangul})/;
994  
995 325 ▶sub flanking {
Subroutine flanking: called CC=2 SCAR=6.9
Pod undocumented
996 325 my $d = quotemeta shift;
997 my($punct, $tight) = $config->{cjk_friendly}
998 325 ▶ ? (qr/(?!$CJK)[\p{P}\p{S}]/, qr/(?!$CJK)[^\s\p{P}\p{S}]/)
Branch: 1 branch
BranchTrueFalseTotal
$config->{'cjk_friendly'} ? : 2 323 325
999 : (qr/[\p{P}\p{S}]/, qr/[^\s\p{P}\p{S}]/);
1000 # A link or a code span is a protect() placeholder by now; its
1001 # ends stand for the punctuation that delimits it in the text.
1002 325 my($ps, $pe) = (qr/\e\[256m/, qr/\e\[m/);
1003 325 (qr/(?:(?<!$tight)|(?<=$pe)|(?!$d(?:$punct|$ps)))$d(?=\S)/,
1004 qr/(?<=\S)(?:(?<!$punct)(?<!$pe)|(?!$d(?!$ps)$tight))$d/);
1005 }
1006  
1007 #
1008 # colorize() - the main function
1009 #
1010 # Receives entire file content in $_ (--begin with -G --filter).
1011 # Processes all patterns with multiline regexes.
1012 #
1013  
1014 #
1015 # Pipeline step class
1016 #
1017  
1018 341 package App::Greple::md::Step {
1019 5115 ▶ sub new {
Subroutine new: called CC=1 SCAR=0.0
1020 5115 my($class, %args) = @_;
1021 5115 bless \%args, $class;
1022 }
1023 0 ▶ sub label { $_[0]->{label} }
Subroutine label: not called CC=1 SCAR=6.9
1024 2603 ▶ sub active { !$_[0]->{label} || App::Greple::md::active($_[0]->{label}) }
Subroutine active: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
not $_[0]{"label"} or App::Greple::md::active($_[0]{"label"}) 1283 1320 2603
1025 2586 ▶ sub run { $_[0]->{code}->() }
Subroutine run: called CC=1 SCAR=0.0
1026 }
1027  
1028 5115 ▶sub Step {
Subroutine Step: called CC=1 SCAR=0.0
Pod undocumented
1029 5115 my $code = pop;
1030 5115 my $label = shift;
1031 5115 App::Greple::md::Step->new(label => $label, code => $code);
1032 }
1033  
1034 #
1035 # Pipeline steps: Step(sub{}) = always active, Step(label => sub{}) = controllable
1036 #
1037  
1038 # the file being shown, for the paths of its images (begin)
1039 341 our $current_file;
1040  
1041 # The object which makes the rows of images of the types, and sends
1042 # their data to the terminal by flush
1043 59 ▶sub image_object {
Subroutine image_object: called CC=3 SCAR=11.0
Pod undocumented
1044 59 my $types = shift;
1045 Text::ANSI::Image->new(
1046 method => 'kitty',
1047 types => $types,
1048 term => $config->{image_term},
1049 tty => $config->{image_tty} || '/dev/tty',
1050 osc => $config->{image_osc},
1051 59 ▶ $config->{image_resend} ? (resend => $config->{image_resend}) : (),
Branch: 1 branch
BranchTrueFalseTotal
$config->{'image_resend'} ? : 2 57 59
Condition100%2/2
$config->{'image_tty'} || '/dev/tty'
l!l
581
MC/DC100%1/1
$config->{'image_tty'} || '/dev/tty'
$config->{'image_tty'}
Truth table100%2/2
A
A= $config->{'image_tty'}
Aresult
11
00
1052 );
1053 }
1054  
1055 # The rows of an image, put in the middle of the width (the fold width,
1056 # or that of the terminal) with image_align=center. An image is as
1057 # wide as the placeholders of a row.
1058 93 ▶sub align_rows {
Subroutine align_rows: called CC=7 SCAR=19.6
Pod undocumented
1059 93 my($img, $width, @rows) = @_;
1060 93 ▶ my $align = $config->{image_align} || 'center';
Condition50%1/2
$config->{'image_align'} || 'center'
l!l
930
MC/DC0%0/1
$config->{'image_align'} || 'center'
$config->{'image_align'}
Truth table50%1/2
A
A= $config->{'image_align'}
Aresult
11
00
1061 93 ▶ $align =~ /^(?:left|center)$/
Branch: 1 branch
BranchTrueFalseTotal
$align =~ /^(?:left|center)$/u or die "image_align: left or center expected: $align\n" 92 1 93
1062 or die "image_align: left or center expected: $align\n";
1063 92 ▶ @rows and $align eq 'center' or return @rows;
Branch: 1 branch
BranchTrueFalseTotal
@rows and $align eq "center" or return @rows 9 83 92
Condition100%3/3
@rows and $align eq "center"
!ll&&!rl&&r
22619
MC/DC100%2/2
@rows and $align eq "center"
@rows $align eq "center"
Truth table100%3/3
A and B
A= @rowsB= $align eq "center"
ABresult
0X0
100
111
1064 9 ▶ $width ||= ($img->terminal)[0] or return @rows;
Branch: 1 branch
BranchTrueFalseTotal
$width ||= ($img->terminal)[0] or return @rows 9 0 9
Condition66%2/3
$width ||= ($img->terminal)[0]
l!l&&r!l&&!r
450
MC/DC0%0/2
$width ||= ($img->terminal)[0]
$width ($img->terminal)[0]
Truth table66%2/3
A ||= B
A= $widthB= ($img->terminal)[0]
ABresult
1X1
011
000
1065 9 my $cols = () = $rows[0] =~ /\x{10EEEE}/g;
1066 9 my $pad = ' ' x (($width - $cols) / 2);
1067 9 map { $pad . $_ } @rows;
1068 }
1069  
1070 # The directory of the file being shown, where the paths of its images
1071 # start
1072 69 ▶sub image_dir {
Subroutine image_dir: called CC=3 SCAR=14.2
Pod undocumented
1073 69 ▶ defined $current_file && $current_file =~ m{^(.*)/} ? $1 : ".";
Branch: 1 branch
BranchTrueFalseTotal
defined $App::Greple::md::current_file && $App::Greple::md::current_file =~ m[^(.*)/]u ? : 69 0 69
Condition33%1/3
defined $App::Greple::md::current_file and $App::Greple::md::current_file =~ m[^(.*)/]u
!ll&&!rl&&r
0069
MC/DC0%0/2
defined $App::Greple::md::current_file and $App::Greple::md::current_file =~ m[^(.*)/]u
defined $App::Greple::md::current_file $App::Greple::md::current_file =~ m[^(.*)/]u
Truth table33%1/3
A and B
A= defined $App::Greple::md::current_fileB= $App::Greple::md::current_file =~ m[^(.*)/]u
ABresult
0X0
100
111
1074 }
1075  
1076 # An image whose file, a path in the Markdown text, is not found, for
1077 # the author to see: a URL is not looked at, and nor is the text from
1078 # the standard input, which has no directory. A path with %XX is
1079 # found in either form.
1080 224 ▶sub missing_image {
Subroutine missing_image: called CC=7 SCAR=20.2
Pod undocumented
1081 224 my $url = shift;
1082 224 ▶ defined $current_file and $current_file ne '-' or return 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $App::Greple::md::current_file and $App::Greple::md::current_file ne "-" or return 0 222 2 224
Condition66%2/3
defined $App::Greple::md::current_file and $App::Greple::md::current_file ne "-"
!ll&&!rl&&r
02222
MC/DC50%1/2
defined $App::Greple::md::current_file and $App::Greple::md::current_file ne "-"
defined $App::Greple::md::current_file $App::Greple::md::current_file ne "-"
Truth table66%2/3
A and B
A= defined $App::Greple::md::current_fileB= $App::Greple::md::current_file ne "-"
ABresult
0X0
100
111
1083 222 ▶ $url =~ m{^(?:[a-z][a-z0-9+.-]*:|#)}i and return 0;
Branch: 1 branch
BranchTrueFalseTotal
$url =~ /^(?:[a-z][a-z0-9+.-]*:|#)/iu and return 0 178 44 222
1084 44 $url =~ s/[?#].*//s;
1085 44 ▶ length $url or return 0;
Branch: 1 branch
BranchTrueFalseTotal
length $url or return 0 44 0 44
1086 44 ▶ my $path = local_path($url, image_dir()) // return 0;
Condition50%1/2
local_path($url, image_dir()) // (return 0)
l!l
440
MC/DC0%0/1
local_path($url, image_dir()) // (return 0)
local_path($url, image_dir())
Truth table50%1/2
A
A= local_path($url, image_dir())
Aresult
11
00
1087 0 ▶ not (-e $path or -e ($path =~ s/%([0-9A-Fa-f]{2})/chr hex $1/ger));
Condition66%2/3
-e $path || -e $path =~ s/%([0-9A-Fa-f]{2})/chr hex $1;/egru
l!l&&r!l&&!r
32012
MC/DC50%1/2
-e $path || -e $path =~ s/%([0-9A-Fa-f]{2})/chr hex $1;/egru
-e $path -e $path =~ s/%([0-9A-Fa-f]{2})/chr hex $1;/egru
Truth table66%2/3
A || B
A= -e $pathB= -e $path =~ s/%([0-9A-Fa-f]{2})/chr hex $1;/egru
ABresult
1X1
011
000
1088 }
1089  
1090 # The color of the image of the URL: image_missing when its file is
1091 # not found
1092 224 ▶sub image_color {
Subroutine image_color: called CC=2 SCAR=6.9
Pod undocumented
1093 224 my($label, $url, $text) = @_;
1094 224 ▶ md_color(missing_image($url) ? 'image_missing' : $label, $text);
Branch: 1 branch
BranchTrueFalseTotal
missing_image($url) ? : 12 212 224
1095 }
1096  
1097 # The lines of a box drawn by ansicolumn around the lines given, which
1098 # are folded in it:
1099 #
1100 # border the border style of ansicolumn (default: box)
1101 # label a label on the top border, at the left
1102 # color a color label of the module, for the whole box
1103 # width the width, the margins included (default: the terminal)
1104 # fill 1: as wide as the width; 0: as the longest line, in the
1105 # width
1106 # margin columns left out of the box at the left and the right;
1107 # spaces are put at the left
1108 13 ▶sub box_lines {
Subroutine box_lines: called CC=11 SCAR=24.0
Pod undocumented
1109 13 my($lines, %opt) = @_;
1110 13 ▶ my $margin = $opt{margin} // 0;
Condition100%2/2
$opt{"margin"} // 0
l!l
112
MC/DC100%1/1
$opt{"margin"} // 0
$opt{"margin"}
Truth table100%2/2
A
A= $opt{"margin"}
Aresult
11
00
1111 13 ▶ my $width = ($opt{width} || (image_object(['png'])->terminal)[0] || 80) - 2 * $margin;
Condition60%3/5
$opt{'width'} || (image_object(['png'])->terminal)[0] || 80
l!l
130
$opt{"width"} or (image_object(["png"])->terminal)[0]
l!l&&r!l&&!r
760
MC/DC0%0/2
$opt{'width'} || (image_object(['png'])->terminal)[0] || 80
$opt{"width"} (image_object(["png"])->terminal)[0]
Truth table66%2/3
A or B
A= $opt{"width"}B= (image_object(["png"])->terminal)[0]
ABresult
1X1
011
000
1112 13 ▶ my $label = $opt{label} // '';
Condition100%2/2
$opt{"label"} // ""
l!l
85
MC/DC100%1/1
$opt{"label"} // ""
$opt{"label"}
Truth table100%2/2
A
A= $opt{"label"}
Aresult
11
00
1113 17 ▶ my $draw = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1114 17 my($w, @fold) = @_;
1115 26 ▶ call_ansicolumn(join('', map { "$_\n" } @$lines),
Branch: 1 branch
BranchTrueFalseTotal
length $label ? : 9 8 17
Condition100%2/2
$opt{'border'} || 'box'
l!l
98
MC/DC100%1/1
$opt{'border'} || 'box'
$opt{'border'}
Truth table100%2/2
A
A= $opt{'border'}
Aresult
11
00
1116 '-C1', '-S', $w, @fold,
1117 17 '--border', '--border-style=' . ($opt{border} || 'box'),
1118 length $label ? ('--label', "NW=$label") : ());
1119 13 };
1120 # Without the document mode a line is not folded: the box is
1121 # right when its lines are as wide as one another, and the longest
1122 # line has a space before the right border, which some styles do
1123 # not have of their own. The columns of a border depend on its
1124 # style, so the narrowest box is searched for.
1125 13 my($long) = sort { ansi_width($b) <=> ansi_width($a) } @$lines;
1126 15 ▶ my $fit = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1127 15 my $box = $draw->(shift);
1128 15 my %w = map { ansi_width($_) => 1 } split /\n/, $box;
1129 15 ▶ keys %w == 1 && $box !~ /\Q$long\E(?! )/ ? $box : undef;
Branch: 1 branch
BranchTrueFalseTotal
keys %w == 1 && !($box =~ /\Q$long\E(?! )/u) ? : 11 4 15
Condition100%3/3
keys %w == 1 and not $box =~ /\Q$long\E(?! )/u
!ll&&!rl&&r
3111
MC/DC100%2/2
keys %w == 1 and not $box =~ /\Q$long\E(?! )/u
keys %w == 1 not $box =~ /\Q$long\E(?! )/u
Truth table100%3/3
A and not(B)
A= keys %w == 1B= not $box =~ /\Q$long\E(?! )/u
ABresult
0X0
100
111
1130 13 };
1131 13 my $box;
1132 13 ▶ if (not $opt{fill}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opt{"fill"}) 3 10 13
1133 3 my $text = List::Util::max(ansi_width($label) + 2, ansi_width($long));
1134 3 for my $w ($text + 2 .. List::Util::min($text + 8, $width)) {
1135 4 ▶ last if defined($box = $fit->($w));
Branch: 1 branch
BranchTrueFalseTotal
if defined($box = &$fit($w)) 2 2 4
1136 }
1137 }
1138 # In the whole width, folded as a document only when a line does
1139 # not fit, because the document mode folds before the end; at
1140 # spaces, so that a word in quotes stays whole.
1141 13 ▶ $box //= $fit->($width) // $draw->($width, '--document', '--boundary=space');
Condition66%4/6
$box //= &$fit($width) // &$draw($width, "--document", "--boundary=space")
l!l&&r!l&&!r
2110
&$fit($width) // &$draw($width, "--document", "--boundary=space")
l!l&&r!l&&!r
920
MC/DC0%0/3
$box //= &$fit($width) // &$draw($width, "--document", "--boundary=space")
$box &$fit($width) &$draw($width, "--document", "--boundary=space")
Truth table0%0/4
A //= B // C
A= $boxB= &$fit($width)C= &$draw($width, "--document", "--boundary=space")
ABCresult
1XX1
01X1
0011
0000
1142 13 my $pad = ' ' x $margin;
1143 13 ▶ map { $pad . ($opt{color} ? md_color($opt{color}, $_) : $_) } split /\n/, $box;
Branch: 1 branch
BranchTrueFalseTotal
$opt{'color'} ? : 33 21 54
1144 }
1145  
1146 # The lines of a message from a command which mdee runs, not a part of
1147 # the text: in a shadow box as wide as the width (the fold width, or
1148 # that of the terminal), with the name of the command on its top, in
1149 # the color of message
1150 7 ▶sub message_lines {
Subroutine message_lines: called CC=1 SCAR=0.0
Pod undocumented
1151 7 my($width, $name, @lines) = @_;
1152 7 box_lines(\@lines, border => 'shadow-box', label => " $name ",
1153 color => 'message', width => $width, fill => 1);
1154 }
1155  
1156 # The lines joined by refill() below the rows of an image go down by
1157 # the rows: [ the line above the rows, the number of rows ], ...
1158 190 ▶sub shift_refill_lines {
Subroutine shift_refill_lines: called CC=5 SCAR=16.1
Pod undocumented
1159 190 my @added = @_;
1160 190 for my $r (@App::Greple::md::refill_lines) {
1161 28 my $shift = 0;
1162 28 ▶ $_->[0] < $r->[0] and $shift += $_->[1] for @added;
Branch: 1 branch
BranchTrueFalseTotal
$_->[0] < $r->[0] and $shift += $_->[1] 8 4 12
1163 28 $_ += $shift for @$r;
1164 }
1165 }
1166  
1167 my %colorize = (
1168  
1169 228 ▶ front_matter => Step(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1170 228 ▶ my $front = front_matter($_) // return;
Condition100%2/2
front_matter($_) // (return)
l!l
6222
MC/DC100%1/1
front_matter($_) // (return)
front_matter($_)
Truth table100%2/2
A
A= front_matter($_)
Aresult
11
00
1171 6 my($open, @body) = split /(?<=\n)/, $front;
1172 6 my $close = pop @body;
1173 6 chomp $open;
1174 6 ▶ my $block = sub { fallback_color('meta_block', 'code_block', $_[0]) };
Subroutine __ANON__: called CC=1 SCAR=0.0
1175 # A delimiter line is in meta_mark alone when it is defined, and
1176 # otherwise in code_mark inside the block color, so that the
1177 # background of the block runs over it
1178 my $mark = defined_color('meta_mark')
1179 10 ▶ ? sub { md_color('meta_mark', $_[0]) }
Subroutine __ANON__: called CC=1 SCAR=0.0
1180 6 ▶ : sub { $block->(md_color('code_mark', $_[0])) };
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
defined_color('meta_mark') ? : 5 1 6
1181 substr($_, 0, length $front) = protect(join '',
1182 $mark->($open), "\n",
1183 6 (map { $block->($_) } @body),
1184 $mark->($close));
1185 }),
1186  
1187 228 ▶ code_blocks => Step(sub {
Subroutine __ANON__: called CC=37 SCAR=36.2
1188 # closing fence: the same character, at least as long (CommonMark)
1189 228 my $block = qr{^( {0,3})((`|~)\3{2,})(.*)\n((?s:.*?))^( {0,3})(\2\3*)(\h*)$}m;
1190 # the code of all the blocks, in the colors of their languages
1191 228 my @highlight;
1192 228 ▶ if ($config->{highlight}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($config->{"highlight"}) 226 2 228
1193 226 my @code;
1194 226 ▶ while (/$block/g) {
Branch: 1 branch
BranchTrueFalseTotal
if (/$block/gu) 479 226 705
1195 479 my($info, $body) = ($4, $5);
1196 479 push @code, [ $info, $body ];
1197 }
1198 226 @highlight = highlight_code(@code);
1199 }
1200 # the images of the Mermaid diagrams (image_types has mermaid),
1201 # all drawn at once
1202 228 my(@diagram, @error, $img, @added, $diagram);
1203 228 ▶ if (grep { $_ eq 'mermaid' } split /:/, $config->{image_types} // '') {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {$_ eq "mermaid";} split(/:/u, $config->{"image_types"} // "", 0)) 102 126 228
Condition50%1/2
$config->{"image_types"} // ""
l!l
2280
MC/DC0%0/1
$config->{"image_types"} // ""
$config->{"image_types"}
Truth table50%1/2
A
A= $config->{"image_types"}
Aresult
11
00
1204 # A block of mermaid, by the info string "mermaid", or by
1205 # the class .mermaid in the attributes of pandoc
1206 # ({.mermaid caption="..." #fig:x}, as pandoc-plot takes
1207 # it), not inside an HTML comment, which the
1208 # comments step takes later. The comments are looked for
1209 # as that step sees them, with the code blocks out of the
1210 # way: a <!-- inside a code block starts no comment.
1211 102 my @comment;
1212 102 my $text = s{$block}{ ' ' x length ${^MATCH} }gepr;
1213 102 ▶ while ($text =~ /^<!--(?![->])(?s:.*?)-->/mg) {
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ /^<!--(?![->])(?s:.*?)-->/gmu) 6 102 108
1214 6 push @comment, [ $-[0], $+[0] ];
1215 }
1216 308 ▶ $diagram = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
1217 308 my($info, $pos) = @_;
1218 # the values in quotes are out of the way of the class
1219 ($info =~ /^\h*mermaid(?:\h|$)/i
1220 or $info =~ s/"[^"]*"|'[^']*'//gr
1221 =~ /^\h*\{[^}]*(?<![\w-])\.mermaid(?![\w-])[^}]*\}\h*$/i)
1222 308 ▶ and not grep { $_->[0] <= $pos and $pos < $_->[1] } @comment;
Branch: 1 branch
BranchTrueFalseTotal
$info =~ /^\h*mermaid(?:\h|$)/iu || ($info =~ s/"[^"]*"|'[^']*'//gru) =~ /^\h*\{[^}]*(?<![\w-])\.mermaid(?![\w-])[^}]*\}\h*$/iu and not grep({$_->[0] <= $pos and $pos < $_->[1];} @comment) 251 57 308
Condition83%5/6
$info =~ /^\h*mermaid(?:\h|$)/iu or ($info =~ s/"[^"]*"|'[^']*'//gru) =~ /^\h*\{[^}]*(?<![\w-])\.mermaid(?![\w-])[^}]*\}\h*$/iu
l!l&&r!l&&!r
2391257
$_->[0] <= $pos && $pos < $_->[1]
!ll&&!rl&&r
401
MC/DC100%2/2
$info =~ /^\h*mermaid(?:\h|$)/iu or ($info =~ s/"[^"]*"|'[^']*'//gru) =~ /^\h*\{[^}]*(?<![\w-])\.mermaid(?![\w-])[^}]*\}\h*$/iu
$info =~ /^\h*mermaid(?:\h|$)/iu ($info =~ s/"[^"]*"|'[^']*'//gru) =~ /^\h*\{[^}]*(?<![\w-])\.mermaid(?![\w-])[^}]*\}\h*$/iu
MC/DC50%1/2
$_->[0] <= $pos && $pos < $_->[1]
$_->[0] <= $pos $pos < $_->[1]
Truth table100%3/3
A or B
A= $info =~ /^\h*mermaid(?:\h|$)/iuB= ($info =~ s/"[^"]*"|'[^']*'//gru) =~ /^\h*\{[^}]*(?<![\w-])\.mermaid(?![\w-])[^}]*\}\h*$/iu
ABresult
1X1
011
000
Truth table66%2/3
A && B
A= $_->[0] <= $posB= $pos < $_->[1]
ABresult
0X0
100
111
1223 102 };
1224 102 my @code;
1225 102 ▶ while (/$block/g) {
Branch: 1 branch
BranchTrueFalseTotal
if (/$block/gu) 239 102 341
1226 239 my($info, $body, $pos) = ($4, $5, $-[0]);
1227 239 ▶ push @code, $body if $diagram->($info, $pos);
Branch: 1 branch
BranchTrueFalseTotal
if &$diagram($info, $pos) 190 49 239
1228 }
1229 102 ▶ if (@code) {
Branch: 1 branch
BranchTrueFalseTotal
if (@code) 97 5 102
1230 @diagram = diagram_files(
1231 codes => \@code,
1232 command => $config->{mermaid_command},
1233 # as GitHub shows them: the default theme on white,
1234 # and the dark theme on its dark background
1235 theme => $config->{mermaid_theme}
1236 || (($config->{mode} // '') eq 'dark' ? 'dark' : 'default'),
1237 background => $config->{mermaid_background}
1238 || (($config->{mode} // '') eq 'dark' ? '#0d1117' : 'white'),
1239 scale => $config->{mermaid_scale},
1240 97 ▶ errors => \@error,
Branch: 2 branches
BranchTrueFalseTotal
($config->{'mode'} // '') eq 'dark' ? : 7 85 92
($config->{'mode'} // '') eq 'dark' ? : 7 85 92
Condition60%6/10
$config->{'mermaid_theme'} || (($config->{'mode'} // '') eq 'dark' ? 'dark' : 'default')
l!l&&r!l&&!r
5920
$config->{"mode"} // ""
l!l
920
$config->{'mermaid_background'} || (($config->{'mode'} // '') eq 'dark' ? '#0d1117' : 'white')
l!l&&r!l&&!r
5920
$config->{"mode"} // ""
l!l
920
MC/DC0%0/2
$config->{'mermaid_theme'} || (($config->{'mode'} // '') eq 'dark' ? 'dark' : 'default')
$config->{'mermaid_theme'} $config->{"mode"}
MC/DC0%0/2
$config->{'mermaid_background'} || (($config->{'mode'} // '') eq 'dark' ? '#0d1117' : 'white')
$config->{'mermaid_background'} $config->{"mode"}
Truth table66%2/3
A || B
A= $config->{'mermaid_theme'}B= $config->{"mode"}
ABresult
1X1
011
000
Truth table66%2/3
A || B
A= $config->{'mermaid_background'}B= $config->{"mode"}
ABresult
1X1
011
000
1241 );
1242 35 ▶ $img = image_object(['png']) if grep { defined } @diagram;
Branch: 1 branch
BranchTrueFalseTotal
if grep {defined $_;} @diagram 28 7 35
1243 }
1244 }
1245 166 ▶ my $width = $config->{fold} ? $config->{fold_width} : 0;
Branch: 1 branch
BranchTrueFalseTotal
$config->{'fold'} ? : 53 113 166
1246 166 s{$block}{
1247 319 my($oi, $fence, $lang, $body, $ci, $close, $trail) = ($1, $2, $4, $5, $6, $7, $8);
1248 # the place of the block, before any other match is made
1249 319 my($start, $end) = ($-[0], $+[0]);
1250 # the rows of the image of a diagram go below the closing fence
1251 # or what the command said when it could not draw it
1252 319 my(@rows, @message);
1253 319 ▶ if (@diagram and $diagram->($lang, $start)) {
Branch: 1 branch
BranchTrueFalseTotal
if (@diagram and &$diagram($lang, $start)) 60 259 319
Condition100%3/3
@diagram and &$diagram($lang, $start)
!ll&&!rl&&r
250960
MC/DC100%2/2
@diagram and &$diagram($lang, $start)
@diagram &$diagram($lang, $start)
Truth table100%3/3
A and B
A= @diagramB= &$diagram($lang, $start)
ABresult
0X0
100
111
1254 60 my $file = shift @diagram;
1255 60 my $error = shift @error;
1256 @rows = $img->rows($file, width => $width, rows => $config->{image_rows})
1257 60 ▶ if $img and $file;
Branch: 1 branch
BranchTrueFalseTotal
if $img and $file 49 11 60
Condition100%3/3
$img and $file
!ll&&!rl&&r
7449
MC/DC100%2/2
$img and $file
$img $file
Truth table100%3/3
A and B
A= $imgB= $file
ABresult
0X0
100
111
1258 60 @rows = align_rows($img, $width, @rows);
1259 60 ▶ @message = message_lines($width, @$error) if $error and not @rows;
Branch: 1 branch
BranchTrueFalseTotal
if $error and not @rows 7 53 60
Condition66%2/3
$error and not @rows
!ll&&!rl&&r
5307
MC/DC50%1/2
$error and not @rows
$error not @rows
Truth table66%2/3
A and not(B)
A= $errorB= not @rows
ABresult
0X0
100
111
1260 }
1261 # the line of the closing fence, in the text before protect(),
1262 # for the lines joined by refill() below it
1263 319 ▶ my $at = (@rows || @message) && @App::Greple::md::refill_lines
Branch: 1 branch
BranchTrueFalseTotal
(@rows || @message) && @App::Greple::md::refill_lines ? : 3 316 319
Condition100%6/6
@rows || @message and @App::Greple::md::refill_lines
!ll&&!rl&&r
263533
@rows or @message
l!l&&r!l&&!r
497263
MC/DC100%3/3
@rows || @message and @App::Greple::md::refill_lines
@rows @message @App::Greple::md::refill_lines
Truth table100%5/5
A or B and C
A= @rowsB= @messageC= @App::Greple::md::refill_lines
ABCresult
00X0
1X00
0100
1X11
0111
1264 ? restore(substr($_, 0, $end)) =~ tr/\n// + 1 : 0;
1265 319 ▶ my @label = $config->{highlight} ? code_labels($lang, $body) : ();
Branch: 1 branch
BranchTrueFalseTotal
$config->{'highlight'} ? : 317 2 319
1266 319 ▶ $body = shift(@highlight) // $body;
Condition66%2/3
shift @highlight // $body
l!l&&r!l&&!r
153040
MC/DC0%0/2
shift @highlight // $body
shift @highlight $body
Truth table66%2/3
A // B
A= shift @highlightB= $body
ABresult
1X1
011
000
1267 319 my $result = md_color('code_mark', "$oi$fence");
1268 319 ▶ $result .= md_color('code_info', $lang) if length($lang);
Branch: 1 branch
BranchTrueFalseTotal
if length $lang 311 8 319
1269 319 $result .= "\n";
1270 319 ▶ if (length($body)) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $body) 318 1 319
1271 $result .= join '', map {
1272 318 my $label = shift @label;
1273 875 ▶ !defined $label ? md_color('code_block', $_)
Branch: 2 branches
BranchTrueFalseTotal
!defined($label) ? : 866 9 875
$label eq '' ? : 3 6 9
1274 : $label eq '' ? $_
1275 : fallback_color("code_$label", 'code_block', $_);
1276 } split /(?<=\n)/, $body;
1277 }
1278 319 $result .= md_color('code_mark', "$ci$close") . $trail;
1279 # the rows, or the lines of the message in place of them
1280 319 ▶ if (my @below = @rows ? @rows : @message) {
Branch: 2 branches
BranchTrueFalseTotal
if (my(@below) = @rows ? @rows : @message) { } 56 263 319
@rows ? : 49 270 319
1281 # Kept in one pane, the lines are one, joined by GS.
1282 # They start on the next line, so that the closing
1283 # fence stays a line of its own, which ends the code
1284 # block for the --exclude of --fold-by.
1285 56 my $keep = intact("image");
1286 56 ▶ push @added, [ $at, $keep ? 1 : scalar @below ];
Branch: 1 branch
BranchTrueFalseTotal
$keep ? : 5 51 56
1287 56 ▶ my $sep = $keep ? "\x1D" : "\n";
Branch: 1 branch
BranchTrueFalseTotal
$keep ? : 5 51 56
1288 56 protect($result) . "\n" . protect(join $sep, @below);
1289 } else {
1290 263 protect($result)
1291 }
1292 }mge;
1293 166 ▶ $img->flush if $img;
Branch: 1 branch
BranchTrueFalseTotal
if $img 28 138 166
1294 166 shift_refill_lines(@added);
1295 }),
1296  
1297 166 ▶ comments => Step(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1298 166 s/(^<!--(?![->])(?s:.*?)-->)/protect(md_color('comment', $1))/mge;
1299 }),
1300  
1301 165 ▶ image_links => Step(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1302 165 s{$SKIP_CODE|\[!\[(?<text>$LT)\]\((?<img>[^)\n]+)\)\]\(<?(?<url>[^>)\s\n]+)>?\)}{
1303 protect(
1304 osc8($+{img}, image_color('image_link', $+{img}, "!"))
1305 44 . osc8($+{url}, mark_color('link', "[") . image_color('image_link', $+{img}, $+{text}) . mark_color('link', "]"))
1306 )
1307 }ge;
1308 }),
1309  
1310 # A line which is an image and nothing else is followed by the rows
1311 # of the image (Text::ANSI::Image, the kitty method). The rows are
1312 # protected, so that no other step takes them, and are joined with
1313 # the line by GS when they are to be kept in one pane (intact=image),
1314 # as the rows of a table are joined by US.
1315 166 ▶ image_blocks => Step(sub {
Subroutine __ANON__: called CC=11 SCAR=24.0
1316 166 ▶ my @types = grep { $_ ne 'mermaid' } split /:/, $config->{image_types} // '';
Condition50%1/2
$config->{"image_types"} // ""
l!l
1660
MC/DC0%0/1
$config->{"image_types"} // ""
$config->{"image_types"}
Truth table50%1/2
A
A= $config->{"image_types"}
Aresult
11
00
1317 166 ▶ @types or return;
Branch: 1 branch
BranchTrueFalseTotal
@types or return 25 141 166
1318 25 my $img = image_object(\@types);
1319 25 my @added;
1320 25 my $dir = image_dir();
1321 25 ▶ my $width = $config->{fold} ? $config->{fold_width} : 0;
Branch: 1 branch
BranchTrueFalseTotal
$config->{'fold'} ? : 7 18 25
1322 # A Markdown image, alone or as a link, or an HTML <img> with
1323 # only <p>, <div>, <a> or <center> around it (README files made
1324 # from POD have one for the logo).
1325 25 s{^(?<line>\h*+
1326 (?: \[?!\[(?:$LT)?\]\(<?(?<url>[^>)\s\n]+)>?\)(?:\]\([^)\n]*\))?
1327 | (?:<(?:p|div|a|center)\b[^>\n]*>\h*)*
1328 <img\b(?<attr>[^>\n]*)>
1329 (?:\h*</(?:p|div|a|center)>)*
1330 )\h*+)\n
1331 }{
1332 # the line number, before any other match is made, in the
1333 # text before protect(), which made a code block one line
1334 33 ▶ my $at = @App::Greple::md::refill_lines
Branch: 1 branch
BranchTrueFalseTotal
@App::Greple::md::refill_lines ? : 2 31 33
1335 ? 1 + (restore(substr($_, 0, $-[0])) =~ tr/\n//) : 0;
1336 33 my($line, $url, $attr) = @+{qw(line url attr)};
1337 33 ▶ if (defined $attr) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $attr) 3 30 33
1338 3 ($url) = $attr =~ m{\bsrc\h*=\h*(?|"([^"]*)"|'([^']*)'|([^\s"'>]+))}i;
1339 }
1340 33 ▶ my $file = defined $url ? local_path($url, $dir) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $url ? : 33 0 33
1341 my @rows = $file ? $img->rows($file,
1342 width => $width,
1343 rows => $config->{image_rows},
1344 33 ▶ ) : ();
Branch: 1 branch
BranchTrueFalseTotal
$file ? : 28 5 33
1345 33 @rows = align_rows($img, $width, @rows);
1346 32 ▶ if (@rows) {
Branch: 1 branch
BranchTrueFalseTotal
if (@rows) { } 21 11 32
1347 # the line of a shown image is markup only, the Markdown
1348 # or the HTML tags: it is put as it is in code_info, as the
1349 # info string of a code fence is
1350 21 my($indent, $tags) = $line =~ /^(\h*)(.*?)\h*$/;
1351 21 $line = $indent . protect(md_color('code_info', $tags));
1352 21 my $keep = intact("image");
1353 # kept in one pane, the line of the image goes with its rows
1354 21 ▶ push @added, [ $at, $keep ? 0 : scalar @rows ];
Branch: 1 branch
BranchTrueFalseTotal
$keep ? : 1 20 21
1355 21 ▶ my $sep = $keep ? "\x1D" : "\n";
Branch: 1 branch
BranchTrueFalseTotal
$keep ? : 1 20 21
1356 21 $line . $sep . protect(join $sep, @rows) . "\n";
1357 } else {
1358 11 "$line\n";
1359 }
1360 }mgex;
1361 24 $img->flush;
1362 24 shift_refill_lines(@added);
1363 }),
1364  
1365 165 ▶ images => Step(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1366 165 s{$SKIP_CODE|!\[(?<text>$LT)\]\(<?(?<url>[^>)\s\n]+)>?\)}{
1367 68 protect(osc8($+{url}, image_color('image', $+{url}, "!") . mark_color('link', "[") . image_color('image', $+{url}, $+{text}) . mark_color('link', "]")))
1368 }ge;
1369 }),
1370  
1371 165 ▶ links => Step(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1372 165 s{$SKIP_CODE|(?<![!\e])\[(?<text>$LT)\]\(<?(?<url>[^>)\s\n]+)>?\)}{
1373 214 protect(osc8($+{url}, mark_color('link', "[") . md_color('link', $+{text}) . mark_color('link', "]")))
1374 }ge;
1375 }),
1376  
1377 163 ▶ inline_code => Step(code_inline => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1378 163 state $to = $config->{tick_open};
1379 163 state $tc = $config->{tick_close};
1380 163 s{$CODE}{
1381 556 my $content = $+{_content};
1382 # Strip optional leading/trailing space for multi-backtick (CommonMark)
1383 556 ▶ $content =~ s/^ (.+) $/$1/ if length($+{_bt}) >= 2;
Branch: 1 branch
BranchTrueFalseTotal
if length $+{"_bt"} >= 2 80 476 556
1384 556 protect(md_color('code_tick', $to) . md_color('code_inline', $content) . md_color('code_tick', $tc))
1385 }ge;
1386 }),
1387  
1388 163 ▶ headings => Step(header => sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
1389 163 my $hashed = $config->{hashed};
1390 163 for my $n (reverse 1..6) {
1391 978 ▶ next unless active("h$n");
Branch: 1 branch
BranchTrueFalseTotal
unless active("h$n") 0 978 978
1392 978 my $hdr = '#' x $n;
1393 # up to 3 spaces of indentation; empty headings ("#") too (CommonMark)
1394 978 s{^( {0,3}$hdr(?:\h+.*)?)$}{
1395 879 my $line = $1;
1396 $line .= " $hdr"
1397 879 ▶ if $hashed->{"h$n"} && $line !~ /\#$/;
Branch: 1 branch
BranchTrueFalseTotal
if $$hashed{"h$n"} and not $line =~ /\#$/u 130 749 879
Condition100%3/3
$$hashed{"h$n"} and not $line =~ /\#$/u
!ll&&!rl&&r
72326130
MC/DC100%2/2
$$hashed{"h$n"} and not $line =~ /\#$/u
$$hashed{"h$n"} not $line =~ /\#$/u
Truth table100%3/3
A and not(B)
A= $$hashed{"h$n"}B= not $line =~ /\#$/u
ABresult
0X0
100
111
1398 879 protect(md_color("h$n", restore($line)));
1399 }mge;
1400 }
1401 }),
1402  
1403 163 ▶ horizontal_rules => Step(horizontal_rule => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1404 163 s/^([ ]{0,3}(?:[-*_][ ]*){3,})$/protect(md_color('horizontal_rule', $1))/mge;
1405 }),
1406  
1407 163 ▶ bold_italic => Step(bold => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1408 163 s{$SKIP_CODE|(?<!\\)(?<m>\*\*\*)(?<t>.*?)(?<!\\)\g{m}}{
1409 40 protect(mark_color('bold', $+{m}) . md_color('bold', md_color('italic', $+{t})) . mark_color('bold', $+{m}))
1410 }gep;
1411 163 s{$SKIP_CODE|(?<![\\\w])(?<m>___)(?<t>.*?)(?<!\\)\g{m}(?!\w)}{
1412 40 protect(mark_color('bold', $+{m}) . md_color('bold', md_color('italic', $+{t})) . mark_color('bold', $+{m}))
1413 }gep;
1414 }),
1415  
1416 163 ▶ bold => Step(bold => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1417 163 my($open, $close) = flanking('**');
1418 # no opener inside, so that a closer pairs with the nearest opener
1419 163 s{$SKIP_CODE|(?<!\\)(?<m>$open)(?<t>(?:(?!$open).)*?)(?<!\\)$close}{
1420 mark_color('bold', $+{m}) . md_color('bold', $+{t}) . mark_color('bold', $+{m})
1421 292 }gep;
1422 163 s{$SKIP_CODE|(?<![\\\w])(?<m>__)(?<t>.*?)(?<!\\)\g{m}(?!\w)}{
1423 mark_color('bold', $+{m}) . md_color('bold', $+{t}) . mark_color('bold', $+{m})
1424 40 }gep;
1425 }),
1426  
1427 162 ▶ italic => Step(italic => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1428 162 my($open, $close) = flanking('*');
1429 162 s{$SKIP_CODE|(?<![\\\w])(?<m>_)(?<t>(?:(?!_).)+)(?<!\\)\g{m}(?!\w)}{
1430 mark_color('italic', $+{m}) . md_color('italic', $+{t}) . mark_color('italic', $+{m})
1431 78 }gep;
1432 162 s{$SKIP_CODE|(?<![\\*])(?<m>$open)(?<t>(?:(?!\*).)+)(?<!\\)$close(?!\*)}{
1433 mark_color('italic', $+{m}) . md_color('italic', $+{t}) . mark_color('italic', $+{m})
1434 49 }gep;
1435 }),
1436  
1437 163 ▶ strike => Step(strike => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1438 163 s{$SKIP_CODE|(?<!\\)(?<m>~~)(?<t>.+?)(?<!\\)\g{m}}{
1439 mark_color('strike', $+{m}) . md_color('strike', $+{t}) . mark_color('strike', $+{m})
1440 40 }gep;
1441 }),
1442  
1443 163 ▶ blockquotes => Step(blockquote => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1444 163 s/^( {0,3})((?:>\h?)+)(.*)$/$1 . md_color('blockquote', $2) . $3/mge;
1445 341 }),
1446 );
1447  
1448 #
1449 # Pipeline configuration
1450 #
1451  
1452 # Always before headings (protection + links)
1453 341 my @protect_steps = qw(front_matter code_blocks comments image_blocks image_links images links);
1454  
1455 # Inline steps controlled by heading_markup
1456 341 my @inline_steps = qw(inline_code horizontal_rules bold_italic bold italic strike);
1457  
1458 # Always last
1459 341 my @final_steps = qw(blockquotes);
1460  
1461 228 ▶sub build_pipeline {
Subroutine build_pipeline: called CC=4 SCAR=25.8
Pod undocumented
1462 228 my $hm = $config->{heading_markup};
1463  
1464 # heading_markup disabled: headings before all inline steps
1465 228 ▶ if (!$hm) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($hm) 228 0 228
1466 228 return (@protect_steps, 'headings', @inline_steps, @final_steps);
1467 }
1468  
1469 # "all" or "1": all inline steps before headings
1470 0 my %before;
1471 0 ▶ if ($hm eq '1' || $hm =~ /^all$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hm eq '1' or $hm =~ /^all$/iu) { } 0 0 0
Condition0%0/3
$hm eq 1 or $hm =~ /^all$/iu
l!l&&r!l&&!r
000
MC/DC0%0/2
$hm eq 1 or $hm =~ /^all$/iu
$hm eq 1 $hm =~ /^all$/iu
Truth table0%0/3
A or B
A= $hm eq 1B= $hm =~ /^all$/iu
ABresult
1X1
011
000
1472 0 %before = map { $_ => 1 } @inline_steps;
1473 } else {
1474 # "bold:italic" → collect word tokens, filter to valid inline steps
1475 0 my %valid = map { $_ => 1 } @inline_steps;
1476 0 %before = map { $_ => 1 } grep { $valid{$_} } ($hm =~ /(\w+)/g);
1477 }
1478  
1479 0 my @before_h = grep { $before{$_} } @inline_steps;
1480 0 my @after_h = grep { !$before{$_} } @inline_steps;
1481  
1482 0 return (@protect_steps, @before_h, 'headings', @after_h, @final_steps);
1483 }
1484  
1485 228 ▶sub colorize {
Subroutine colorize: called CC=3 SCAR=11.0
Pod undocumented
1486 228 setup_colors();
1487 228 @protected = ();
1488  
1489 228 for my $name (build_pipeline()) {
1490 2603 my $step = $colorize{$name};
1491 2603 ▶ $step->run if $step->active;
Branch: 1 branch
BranchTrueFalseTotal
if $step->active 2586 17 2603
1492 }
1493  
1494 165 $_ = restore($_);
1495 165 $_;
1496 }
1497  
1498 #
1499 # Table formatting
1500 #
1501  
1502 # What joins the lines of a part kept intact (config intact) into one
1503 # line, as ansicolumn --intact takes it
1504 341 my $INTACT_SEP = "\x1F";
1505 # What joins lines kept in one pane, the rows of an image or the lines
1506 # of a row of a table
1507 341 my $GROUP_SEP = "\x1D";
1508  
1509 # Whether the part ("table") is kept intact
1510 726 ▶sub intact {
Subroutine intact: called CC=2 SCAR=7.1
Pod undocumented
1511 726 my $part = shift;
1512 726 ▶ grep { $_ eq $part } split /:/, $config->{intact} // '';
Condition50%1/2
$config->{"intact"} // ""
l!l
7260
MC/DC0%0/1
$config->{"intact"} // ""
$config->{"intact"}
Truth table50%1/2
A
A= $config->{"intact"}
Aresult
11
00
1513 }
1514  
1515 # Regions of formatted tables, used by --fold-by as --exclude so that
1516 # ansifold does not fold them again: three or more lines that contain a
1517 # column separator, in a block that has a separator row. A line may
1518 # start with a border or rule character, a dash, whitespace, or one of
1519 # the configured marks (a wrapped first column's continuation line starts
1520 # with the wrap mark, and its body rows with the cell mark), so the
1521 # pattern is built from the config at run time rather than in __DATA__.
1522 90 ▶sub table_regions {
Subroutine table_regions: called CC=2 SCAR=6.9
Pod undocumented
1523 90 my %arg = @_;
1524 90 delete $arg{&FILELABEL};
1525 43 my $marks = join '', map { quotemeta substr $_, 0, 1 }
1526 90 grep { length } @{$config}{qw(table_wrap_mark table_cell_mark)};
1527 90 my $bar = "\x{2502}|"; # column separator │ |
1528 90 my $cross = "\x{253C}"; # rule crossing ┼
1529 90 my $rule = "\x{2500}\x{251C}\x{2524}"; # rule line ─ ├ ┤
1530 90 my $row = qr{
1531 ^ [ $bar \x{251C} \x{2500} $marks \h - ] # border, rule, mark, pad, or dash
1532 [^\n]* [ $bar $cross ] [^\n]* \n # ... with a separator somewhere
1533 }xxm;
1534 90 my $sep = qr{ (?= [^\n]* [ $cross | ] ) [ $rule $cross | - ]+ \n }xx;
1535 # a table kept intact is a line with UNIT SEPARATORs, or GROUP
1536 # SEPARATORs alone when it has one row, which come from nowhere else
1537 # but the rows of an image: remove_controls() takes them out of the
1538 # text
1539 90 ▶ return match_regions(pattern => qr/^[^\n]*[$INTACT_SEP$GROUP_SEP][^\n]*\n/m) if intact('table');
Branch: 1 branch
BranchTrueFalseTotal
if intact("table") 13 77 90
1540 77 match_regions(pattern => qr/ (?= (?:$row)*? $sep ) (?:$row){3,} /x);
1541 }
1542  
1543 #
1544 # Paragraph refill
1545 #
1546  
1547 # Join the lines of one paragraph (or list item, quote, definition)
1548 # into a single line. The rules are those of ansifold's fill_up: the
1549 # line break after a fullwidth punctuation character and between two
1550 # characters of a script written without spaces (CJK) is simply
1551 # removed, any other becomes one space. A line is left as it is, as
1552 # the start of a new line, when the line before it ends in a hard
1553 # break (two or more spaces, or a backslash), or when it starts with
1554 # a list marker, is a horizontal rule, which pandoc may report as
1555 # part of the paragraph (a "#." list, "Text\n***"), or when either
1556 # line looks like a table row: GFM does not let a table interrupt a
1557 # paragraph, but format_table takes three such lines as a table.
1558 # From the second line on, up to $depth quote markers and the
1559 # indentation are removed before joining. A CR before the line
1560 # break (CRLF file) goes with the line break.
1561 #
1562 # The character properties are defined as subroutines in App::ansifold
1563 # and looked up when the pattern is compiled, so the patterns are
1564 # built here, after the module is loaded, not at compile time.
1565 103 ▶sub refill_block {
Subroutine refill_block: called CC=13 SCAR=25.7
Pod undocumented
1566 103 my($lines, $depth) = @_;
1567 103 state $punct = do {
1568 30 require App::ansifold;
1569 30 my $p = "App::ansifold::InFullwidthPunctuation";
1570 30 qr/\p{$p}/;
1571 };
1572 103 state $concat = do {
1573 30 my $p = "App::ansifold::InConcatScript";
1574 30 qr/\p{$p}/;
1575 };
1576 103 my $prefix = qr/^\h*(?:>\h?){0,$depth}\h*/;
1577 103 my $marker = qr/^\h*(?:[*+-]|(?:\d+|#)[.)])\h+/;
1578 103 my $hr = qr/^ {0,3}(?:[-*_][ ]*){3,}\r?$/;
1579 103 my $row = qr/^ {0,3}\|.+\|\h*\r?$/;
1580 103 my $def = qr/^\h*:\h/;
1581 103 my $note = qr/$prefix\[\^[^\]\s]+\]:/;
1582 103 my $hard = qr/(?:(?<!\\)(?:\\\\)*\\|(?<! ) {2,})\r?$/; # odd number of backslashes, or two spaces (the lookbehinds keep it linear)
1583 103 my @out;
1584 103 for my $line (@$lines) {
1585 248 ▶ if (!@out or $out[-1] =~ $hard or $out[-1] =~ $row
Branch: 1 branch
BranchTrueFalseTotal
if (not @out or $out[-1] =~ /$hard/u or $out[-1] =~ /$row/u or $line =~ /$marker/u or $line =~ /$hr/u or $line =~ /$row/u or $line =~ /$def/u or $line =~ /$note/u) 170 78 248
Condition100%21/21
not @out or $out[-1] =~ /$hard/u or $out[-1] =~ /$row/u or $line =~ /$marker/u or $line =~ /$hr/u or $line =~ /$row/u or $line =~ /$def/u or $line =~ /$note/u
l!l&&r!l&&!r
167378
not @out or $out[-1] =~ /$hard/u or $out[-1] =~ /$row/u or $line =~ /$marker/u or $line =~ /$hr/u or $line =~ /$row/u or $line =~ /$def/u
l!l&&r!l&&!r
164381
not @out or $out[-1] =~ /$hard/u or $out[-1] =~ /$row/u or $line =~ /$marker/u or $line =~ /$hr/u or $line =~ /$row/u
l!l&&r!l&&!r
159584
not @out or $out[-1] =~ /$hard/u or $out[-1] =~ /$row/u or $line =~ /$marker/u or $line =~ /$hr/u
l!l&&r!l&&!r
158189
not @out or $out[-1] =~ /$hard/u or $out[-1] =~ /$row/u or $line =~ /$marker/u
l!l&&r!l&&!r
157190
not @out or $out[-1] =~ /$hard/u or $out[-1] =~ /$row/u
l!l&&r!l&&!r
1094891
not @out or $out[-1] =~ /$hard/u
l!l&&r!l&&!r
1036139
MC/DC100%8/8
not @out or $out[-1] =~ /$hard/u or $out[-1] =~ /$row/u or $line =~ /$marker/u or $line =~ /$hr/u or $line =~ /$row/u or $line =~ /$def/u or $line =~ /$note/u
not @out $out[-1] =~ /$hard/u $out[-1] =~ /$row/u $line =~ /$marker/u $line =~ /$hr/u $line =~ /$row/u $line =~ /$def/u $line =~ /$note/u
Truth table100%9/9
not(A) or B or C or D or E or F or G or H
A= not @outB= $out[-1] =~ /$hard/uC= $out[-1] =~ /$row/uD= $line =~ /$marker/uE= $line =~ /$hr/uF= $line =~ /$row/uG= $line =~ /$def/uH= $line =~ /$note/u
ABCDEFGHresult
1XXXXXXX1
01XXXXXX1
001XXXXX1
0001XXXX1
00001XXX1
000001XX1
0000001X1
000000011
000000000
1586 or $line =~ $marker or $line =~ $hr or $line =~ $row
1587 or $line =~ $def or $line =~ $note) {
1588 170 push @out, $line;
1589 170 next;
1590 }
1591 78 my $text = $line =~ s/$prefix//r;
1592 78 $out[-1] =~ s/\r\z//;
1593 78 ▶ if ($out[-1] =~ /$punct$/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($out[-1] =~ /$punct$/u) { } 1 77 78
elsif ($out[-1] =~ /$concat$/u and $text =~ /^$concat/u) { } 2 75 77
1594 1 $out[-1] .= $text;
1595 ▶ } elsif ($out[-1] =~ /$concat$/ and $text =~ /^$concat/) {
Condition66%2/3
$out[-1] =~ /$concat$/u and $text =~ /^$concat/u
!ll&&!rl&&r
7502
MC/DC50%1/2
$out[-1] =~ /$concat$/u and $text =~ /^$concat/u
$out[-1] =~ /$concat$/u $text =~ /^$concat/u
Truth table66%2/3
A and B
A= $out[-1] =~ /$concat$/uB= $text =~ /^$concat/u
ABresult
0X0
100
111
1596 2 $out[-1] .= $text;
1597 } else {
1598 75 $out[-1] =~ s/ +$//;
1599 75 $text =~ s/^ +//;
1600 75 $out[-1] .= " $text";
1601 }
1602 }
1603 103 @out;
1604 }
1605  
1606 # The line ranges that refill() joined, as [first, last] in the text
1607 # after joining, and the formatted tables, as [first line, lines added,
1608 # lines before formatting],
1609 # both for the current file. refill_regions() turns them into the
1610 # regions that --fold-by folds.
1611 341 our @refill_lines;
1612 341 our @table_shift;
1613  
1614 # Front matter at the top of the text: TOML (+++ ... +++) or YAML
1615 # (--- ... --- or ...). It is not part of CommonMark: pandoc takes TOML
1616 # as a paragraph and YAML as metadata, Markdown::Perl takes YAML as
1617 # metadata, and libcmark takes YAML as paragraphs and list items. As
1618 # in pandoc, a blank line right after the opening --- makes it a rule.
1619 # Returns the front matter without the line break after its last line,
1620 # or an empty list. $front_lines is its number of lines, set by
1621 # begin() before the text is changed, for refill and the fold regions.
1622 341 our $front_lines = 0;
1623 560 ▶sub front_matter {
Subroutine front_matter: called CC=3 SCAR=11.0
Pod undocumented
1624 560 ▶ $config->{front_matter} or return;
Branch: 1 branch
BranchTrueFalseTotal
$config->{"front_matter"} or return 557 3 560
1625 557 ▶ $_[0] =~ m{
Branch: 1 branch
BranchTrueFalseTotal
$_[0] =~ / \A (?: \+\+\+ \r?\n (?:[^\n]*\n)*? \+\+\+ | --- \r?\n (?!\r?\n) (?:[^\n]*\n)*? (?:---|\.\.\.) ) \h* \r? (?=\n|\z) /pux ? : 17 540 557
1626 \A (?: \+\+\+ \r?\n (?:[^\n]*\n)*? \+\+\+
1627 | --- \r?\n (?!\r?\n) (?:[^\n]*\n)*? (?:---|\.\.\.) )
1628 \h* \r? (?=\n|\z)
1629 }px ? ${^MATCH} : ();
1630 }
1631  
1632 # The region of the front matter, used by --fold-by as --exclude. The
1633 # text is colored by then, so the region is found by its line count.
1634 90 ▶sub front_matter_region {
Subroutine front_matter_region: called CC=4 SCAR=14.3
Pod undocumented
1635 90 my %arg = @_;
1636 90 delete $arg{&FILELABEL};
1637 90 ▶ $front_lines or return ();
Branch: 1 branch
BranchTrueFalseTotal
$App::Greple::md::front_lines or return () 1 89 90
1638 1 my $pos = 0;
1639 1 for (1 .. $front_lines) {
1640 1 $pos = index($_, "\n", $pos);
1641 1 ▶ $pos < 0 and return [ 0, length ];
Branch: 1 branch
BranchTrueFalseTotal
$pos < 0 and return [0, length $_] 1 0 1
1642 0 $pos++;
1643 }
1644 0 [ 0, $pos ];
1645 }
1646  
1647 # Join the lines of every paragraph (Para) and tight list item or
1648 # definition (Plain) in $_, from the bottom up so that the line numbers
1649 # of the blocks above stay valid, and remember where the joined lines
1650 # are in the result.
1651 30 ▶sub refill {
Subroutine refill: called CC=7 SCAR=19.5
Pod undocumented
1652 30 @refill_lines = ();
1653 30 my @lines = split /\n/, $_, -1;
1654 30 my @done;
1655 30 my $limit = @lines + 1;
1656 30 my $front = $front_lines;
1657 30 for my $b (sort { $b->{first} <=> $a->{first} }
1658 79 ▶ grep { $_->{type} eq 'Para' or $_->{type} eq 'Plain' }
Condition33%1/3
$_->{'type'} eq 'Para' || $_->{'type'} eq 'Plain'
l!l&&r!l&&!r
7900
MC/DC0%0/2
$_->{'type'} eq 'Para' || $_->{'type'} eq 'Plain'
$_->{'type'} eq 'Para' $_->{'type'} eq 'Plain'
Truth table33%1/3
A || B
A= $_->{'type'} eq 'Para'B= $_->{'type'} eq 'Plain'
ABresult
1X1
011
000
1659 blocks($_, parser => $config->{refill_parser})) {
1660 79 my($first, $last) = @{$b}{qw(first last)};
1661 # libcmark runs a paragraph on past a closing "..."
1662 79 ▶ $first = $front + 1 if $first <= $front;
Branch: 1 branch
BranchTrueFalseTotal
if $first <= $front 1 78 79
1663 79 ▶ next if $last < $first or $last >= $limit;
Branch: 1 branch
BranchTrueFalseTotal
if $last < $first or $last >= $limit 1 78 79
Condition66%2/3
$last < $first or $last >= $limit
l!l&&r!l&&!r
1078
MC/DC50%1/2
$last < $first or $last >= $limit
$last < $first $last >= $limit
Truth table66%2/3
A or B
A= $last < $firstB= $last >= $limit
ABresult
1X1
011
000
1664 78 $limit = $first;
1665 78 my @joined = refill_block([ @lines[$first-1 .. $last-1] ], $b->{depth});
1666 78 splice @lines, $first-1, $last-$first+1, @joined;
1667 78 unshift @done, [ $first, scalar @joined, $last - $first + 1 - @joined ];
1668 }
1669 30 my $shift = 0;
1670 30 for my $d (@done) {
1671 78 my($first, $count, $removed) = @$d;
1672 78 push @refill_lines, [ $first - $shift, $first - $shift + $count - 1 ];
1673 78 $shift += $removed;
1674 }
1675 30 $_ = join "\n", @lines;
1676 }
1677  
1678 # The lines that refill() joined, one region per line including its
1679 # newline, for --fold-by. The text has been through colorize(), which
1680 # keeps the number of lines, and format_table(), which does not: the
1681 # tables above a range have added the lines in @table_shift.
1682 90 ▶sub refill_regions {
Subroutine refill_regions: called CC=13 SCAR=26.0
Pod undocumented
1683 90 my %arg = @_;
1684 90 delete $arg{&FILELABEL};
1685 90 ▶ return () unless @refill_lines;
Branch: 1 branch
BranchTrueFalseTotal
unless @App::Greple::md::refill_lines 69 21 90
1686 21 my @start = (0);
1687 21 my $pos = 0;
1688 21 ▶ while (($pos = index($_, "\n", $pos)) >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (($pos = index($_, " ", $pos)) >= 0) 192 21 213
1689 192 push @start, ++$pos;
1690 }
1691 21 my $end = length $_;
1692 21 my @regions;
1693 21 for my $range (@refill_lines) {
1694 55 LINE: for my $line ($range->[0] .. $range->[1]) {
1695 95 my $shift = 0;
1696 95 for my $t (@table_shift) {
1697 # A line of a table is not folded. A parser without
1698 # tables (libcmark) reports a table as a paragraph, and
1699 # its lines after the first are not lines any more when
1700 # the table is joined into one (intact=table).
1701 63 ▶ next LINE if $t->[0] <= $line and $line < $t->[0] + $t->[2];
Branch: 1 branch
BranchTrueFalseTotal
if $t->[0] <= $line and $line < $t->[0] + $t->[2] 45 18 63
Condition100%3/3
$t->[0] <= $line and $line < $t->[0] + $t->[2]
!ll&&!rl&&r
81045
MC/DC100%2/2
$t->[0] <= $line and $line < $t->[0] + $t->[2]
$t->[0] <= $line $line < $t->[0] + $t->[2]
Truth table100%3/3
A and B
A= $t->[0] <= $lineB= $line < $t->[0] + $t->[2]
ABresult
0X0
100
111
1702 18 ▶ $shift += $t->[1] if $t->[0] < $line;
Branch: 1 branch
BranchTrueFalseTotal
if $t->[0] < $line 10 8 18
1703 }
1704 50 my $n = $line + $shift;
1705 50 ▶ last if $n > @start;
Branch: 1 branch
BranchTrueFalseTotal
if $n > @start 0 50 50
1706 # a line which holds the rows of an image is not folded
1707 50 ▶ next if substr($_, $start[$n-1], ($start[$n] // $end) - $start[$n-1]) =~ /[\x1D\x{10EEEE}]/;
Branch: 1 branch
BranchTrueFalseTotal
if substr($_, $start[$n - 1], ($start[$n] // $end) - $start[$n - 1]) =~ /[\x1D\x{10EEEE}]/u 0 50 50
Condition33%1/3
$start[$n] // $end
l!l&&r!l&&!r
5000
MC/DC0%0/2
$start[$n] // $end
$start[$n] $end
Truth table33%1/3
A // B
A= $start[$n]B= $end
ABresult
1X1
011
000
1708 50 ▶ push @regions, [ $start[$n-1], $start[$n] // $end ];
Condition33%1/3
$start[$n] // $end
l!l&&r!l&&!r
5000
MC/DC0%0/2
$start[$n] // $end
$start[$n] $end
Truth table33%1/3
A // B
A= $start[$n]B= $end
ABresult
1X1
011
000
1709 }
1710 }
1711 21 @regions;
1712 }
1713  
1714  
1715 # What a file must not send to the terminal: everything but colors, and the
1716 # mark of protect(), which would bring back or look for protected text.
1717 341 my $STRING = qr{
1718 (?: \e [PX^_] | [\x90\x98\x9e\x9f] ) # DCS, SOS, PM, APC
1719 (?: [^\x00-\x07\x0e-\x1f\x7f-\x9f]*+ (?: \e\\ | \x9c | \a ) )?
1720 }x;
1721 341 my $CONTROLS = qr{
1722 \e \[ (?! 256m ) [0-9:;]* m (*SKIP)(*FAIL)
1723 |
1724 $osc_re
1725 |
1726 $STRING
1727 |
1728 $csi_re
1729 |
1730 \e [\x20-\x2f]* [\x30-\x7e]
1731 |
1732 [\x00-\x08\x0b\x0e-\x1f\x7f-\x9f]
1733 }x;
1734  
1735 361 ▶sub remove_controls {
Subroutine remove_controls: called CC=1 SCAR=0.0
Pod undocumented
1736 361 s/$CONTROLS//g;
1737 }
1738  
1739 # Find the function of a --begin option and load its package, so that a
1740 # module does not have to be given with -M ahead of this one. A name without
1741 # a package is looked for in main, and then as the function name of the
1742 # module App::Greple::md::name. Returns the option with the full name. A
1743 # function that does not exist is only reported, and the text is shown
1744 # without it; a module that exists and does not compile is an error.
1745 21 ▶sub resolve_function {
Subroutine resolve_function: called CC=6 SCAR=17.9
Pod undocumented
1746 21 my $spec = shift;
1747 21 ▶ $spec =~ m{ ^ &? (?<name> \w+ (?: :: \w+ )* ) (?<arg> (?= [(=] | $ ) .* ) }xs or return $spec;
Branch: 1 branch
BranchTrueFalseTotal
$spec =~ / ^ &? (?<name> \w+ (?: :: \w+ )* ) (?<arg> (?= [(=] | $ ) .* ) /sux or return $spec 15 6 21
1748 15 my($name, $arg) = @+{qw(name arg)};
1749 15 ▶ my @candidate = $name =~ /::/ ? $name : ("main::$name", "App::Greple::md::${name}::$name");
Branch: 1 branch
BranchTrueFalseTotal
$name =~ /::/u ? : 8 7 15
1750 341 ▶ no strict q(refs);
Subroutine BEGIN: called CC=1 SCAR=0.0
1751 15 for my $func (@candidate) {
1752 21 ▶ load_package($func =~ s/::\w+$//r) unless defined &$func;
Branch: 1 branch
BranchTrueFalseTotal
unless defined &$func 19 2 21
1753 18 ▶ return "&$func$arg" if defined &$func;
Branch: 1 branch
BranchTrueFalseTotal
if defined &$func 6 12 18
1754 }
1755 6 warn "--begin: $name: function not found\n";
1756 6 return;
1757 }
1758  
1759 19 ▶sub load_package {
Subroutine load_package: called CC=4 SCAR=13.9
Pod undocumented
1760 19 my $package = shift;
1761 19 ▶ return if $package eq q(main);
Branch: 1 branch
BranchTrueFalseTotal
if $package eq "main" 7 12 19
1762 12 my $file = $package =~ s{::}{/}gr . q(.pm);
1763 12 ▶ return if eval { require $file; 1 };
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { require $file; 1 } } 5 7 12
1764 7 ▶ die $@ unless $@ =~ /^Can't locate \Q$file\E /;
Branch: 1 branch
BranchTrueFalseTotal
unless $@ =~ /^Can't locate \Q$file\E /u 3 4 7
1765 }
1766  
1767 # The functions of --begin, parsed once. The names belong to main, as
1768 # with the --begin of greple.
1769 336 ▶sub begin_functions {
Subroutine begin_functions: called CC=3 SCAR=11.0
Pod undocumented
1770 state $func = [ map {
1771 336 ▶ parse_func({ PACKAGE => 'main' }, $_) or die "$_: function format error\n";
Branch: 1 branch
BranchTrueFalseTotal
parse_func({"PACKAGE", "main"}, $_) or die "${_}: function format error\n" 21 0 21
1772 21 my $spec = resolve_function($_);
1773 18 ▶ defined $spec ? parse_func({ PACKAGE => 'main' }, $spec) : ();
Branch: 1 branch
BranchTrueFalseTotal
defined $spec ? : 12 6 18
1774 } @opt_begin ];
1775 332 @$func;
1776 }
1777  
1778 336 ▶sub begin {
Subroutine begin: called CC=7 SCAR=19.5
Pod undocumented
1779 336 remove_controls();
1780 336 $current_file = { @_ }->{&FILELABEL};
1781 336 @refill_lines = @table_shift = ();
1782 336 for my $func (begin_functions()) {
1783 14 $func->call(@_);
1784 }
1785 332 ▶ $front_lines = do { my $f = front_matter($_); defined $f ? ($f =~ tr/\n//) + 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
defined $f ? : 11 321 332
1786 332 ▶ refill() if $config->{refill};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"refill"} 30 302 332
1787 332 ▶ mark_line_breaks() if $config->{table};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"table"} 315 17 332
1788 332 ▶ colorize() if $config->{colorize};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"colorize"} 228 104 332
1789 269 ▶ format_table() if $config->{table};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"table"} 252 17 269
1790 }
1791  
1792 # A <br> in a table row breaks the cell: a LINE SEPARATOR (U+2028)
1793 # is put after it, which ansicolumn takes as a line break in a cell.
1794 # The <br> stays, as the text is shown as written. It is done before
1795 # colorize(), while a code span still has its backticks: a <br> in a
1796 # code span, and an escaped one (\<br>), break nothing, nor does one at
1797 # the end of a cell, which would leave an empty line. The lines are
1798 # those format_table() takes as a table; a separator left in lines it
1799 # does not format after all (in a code block, say) is taken out there.
1800 315 ▶sub mark_line_breaks {
Subroutine mark_line_breaks: called CC=1 SCAR=0.0
Pod undocumented
1801 315 s{(^ {0,3}\|.+\|\h*\n){3,}}{
1802 280 ${^MATCH} =~ s{$CODE(*SKIP)(*FAIL)|(?<!\\)<br\h*/?>\K(?!\h*\|)}{\x{2028}}gir
1803 }mgep;
1804 }
1805  
1806 252 ▶sub format_table {
Subroutine format_table: called CC=31 SCAR=34.4
Pod undocumented
1807 # lattice (or pipe) has column separators. 3line and simple have
1808 # none and a header rule per column: 3line adds a full-width rule
1809 # above and below, simple the header rule below. They are formatted
1810 # as in rule mode and the separators are blanked.
1811 252 my $style = $config->{table_style};
1812 252 ▶ my $open = $style eq '3line' || $style eq 'simple';
Condition100%3/3
$style eq '3line' || $style eq 'simple'
l!l&&r!l&&!r
129231
MC/DC100%2/2
$style eq '3line' || $style eq 'simple'
$style eq '3line' $style eq 'simple'
Truth table100%3/3
A || B
A= $style eq '3line'B= $style eq 'simple'
ABresult
1X1
011
000
1813 252 ▶ my $sep = ($config->{rule} || $open) ? "\x{2502}" : '|'; # │ or |
Branch: 1 branch
BranchTrueFalseTotal
$config->{'rule'} || $open ? : 251 1 252
Condition100%3/3
$config->{"rule"} or $open
l!l&&r!l&&!r
24921
MC/DC100%2/2
$config->{"rule"} or $open
$config->{"rule"} $open
Truth table100%3/3
A or B
A= $config->{"rule"}B= $open
ABresult
1X1
011
000
1814  
1815 # A row may have spaces after the last pipe (GFM ignores them); they
1816 # are allowed in the block and removed, so that every row ends in
1817 # the same column for ansicolumn.
1818 252 s{(^ {0,3}\|.+\|\h*\n){3,}}{
1819 # The line of the table and the number of its lines, taken
1820 # before any other match is made: one made below would give
1821 # its own ${^MATCH} and $-[0].
1822 280 my $line = 1 + (substr($_, 0, $-[0]) =~ tr/\n//);
1823 280 my $lines = ${^MATCH} =~ tr/\n//;
1824 280 my $block = ${^MATCH} =~ s/\h+$//mgr;
1825 # a <br> which breaks a cell (see mark_line_breaks) has the
1826 # color of br_mark, which the nomark theme makes empty
1827 14 $block =~ s{<br\h*/?>(?=\x{2028})}{mark_color('br', ${^MATCH})}giep
1828 280 ▶ if $config->{colorize};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"colorize"} 167 113 280
1829 280 my($right, $center) = parse_separator(\$block);
1830 280 my @sep_opt;
1831 # An escaped pipe (\|) is not a column separator (GFM). It is
1832 # left as written: backslash escapes are not processed yet.
1833 280 ▶ if ($config->{table_trim}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($config->{'table_trim'}) { } 275 5 280
1834 # A cell has a space at its left, where the marks are put,
1835 # and table_gap columns to that place of the next column:
1836 # the last of them is the column separator (a space in
1837 # 3line and simple). With table_gap of 2 or more, the
1838 # spaces at the right end go when the table does not fit
1839 # the width with them (ansicolumn 1.70).
1840 275 ▶ my $pad = ' ' x (($config->{table_gap} || 1) - 1);
Condition50%1/2
$config->{'table_gap'} || 1
l!l
2750
MC/DC0%0/1
$config->{'table_gap'} || 1
$config->{'table_gap'}
Truth table50%1/2
A
A= $config->{'table_gap'}
Aresult
11
00
1841 275 @sep_opt = ('-rs', '\s*(?<!\\\\)\|\s*', "--item-format= %s$pad", '--table-remove=1,-0', '--padding');
1842 } else {
1843 5 $_++ for @$right, @$center;
1844 5 @sep_opt = ('-rs', '(?<!\\\\)\|');
1845 }
1846 280 ▶ my @align = (
Branch: 2 branches
BranchTrueFalseTotal
@$right ? : 47 233 280
@$center ? : 47 233 280
1847 @$right ? ('--table-right=' . join(',', @$right)) : (),
1848 @$center ? ('--table-center=' . join(',', @$center)) : (),
1849 );
1850 # Fit table into table_width and/or per-column widths (table_cell).
1851 # table_cell entries are colon separated because comma separates
1852 # config parameters; non-trim mode has a phantom first column.
1853 280 my @fit;
1854 280 ▶ if ($config->{table_width} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($config->{"table_width"} > 0) 146 134 280
1855 146 push @fit, '-w', $config->{table_width};
1856 }
1857 280 ▶ if ((my $cell = $config->{table_cell}) ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ((my $cell = $config->{"table_cell"}) ne "") 3 277 280
1858 3 $cell =~ tr/:/,/;
1859 3 ▶ $cell = "0,$cell" unless $config->{table_trim};
Branch: 1 branch
BranchTrueFalseTotal
unless $config->{"table_trim"} 1 2 3
1860 3 push @fit, '--cell', $cell;
1861 }
1862 280 ▶ if ((my $mark = $config->{table_wrap_mark}) ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ((my $mark = $config->{"table_wrap_mark"}) ne "") 4 276 280
1863 4 push @fit, '--table-wrap-mark', $mark;
1864 }
1865 280 ▶ if ((my $mark = $config->{table_cell_mark}) ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ((my $mark = $config->{"table_cell_mark"}) ne "") 109 171 280
1866 # the header row and the separator row (to ansicolumn a row of
1867 # "-" cells) are the two header rows and get no mark
1868 109 push @fit, '--table-cell-mark', $mark, '--table-head', 2;
1869 }
1870 # How cells are wrapped is given explicitly, so that it does not
1871 # change with the user's ~/.ansicolumnrc
1872 280 my @wrap = map { "--$_=" . $config->{"table_$_"} } qw(runin runout boundary linebreak);
1873 # kept intact, the lines of a row come joined by GS (see below)
1874 280 ▶ push @wrap, '--table-group' if intact('table') and table_keep() ne 'none';
Branch: 1 branch
BranchTrueFalseTotal
if intact("table") and table_keep() ne "none" 12 267 279
Condition100%3/3
intact("table") and table_keep() ne "none"
!ll&&!rl&&r
266212
MC/DC100%2/2
intact("table") and table_keep() ne "none"
intact("table") table_keep() ne "none"
Truth table100%3/3
A and B
A= intact("table")B= table_keep() ne "none"
ABresult
0X0
100
111
1875 279 my $formatted = call_ansicolumn($block, @sep_opt, '-o', $sep, '-t', '--cu=1', @align, @fit, @wrap);
1876 279 my $table = fix_separator($formatted, $sep);
1877 279 ▶ if ($open) {
Branch: 1 branch
BranchTrueFalseTotal
if ($open) 33 246 279
1878 # blank the column separators and add the rules
1879 33 $table =~ tr/\x{2502}\x{253C}\x{251C}\x{2524}/ /;
1880 33 ▶ if ($style eq '3line') {
Branch: 1 branch
BranchTrueFalseTotal
if ($style eq '3line') { } 18 15 33
1881 18 my($first) = $table =~ /^([^\n$GROUP_SEP]*)/;
1882 18 my $rule = "\x{2500}" x ansi_width($first);
1883 18 $table = "$rule\n$table$rule\n";
1884 } else {
1885 15 my($rule) = $table =~ /^([\x{2500} ]+)$/m;
1886 15 ▶ $table .= "$rule\n" if defined $rule;
Branch: 1 branch
BranchTrueFalseTotal
if defined $rule 15 0 15
1887 }
1888 33 ▶ $table =~ s{^[\x{2500} ]+$}{ ${^MATCH} =~ tr/\x{2500}/-/r }mgep unless $config->{rule};
Branch: 1 branch
BranchTrueFalseTotal
unless $config->{"rule"} 8 25 33
1889 }
1890 # A table is kept intact: its lines joined into one by UNIT
1891 # SEPARATOR, the last newline kept, for ansicolumn --intact,
1892 # which lays them out without folding them. Nothing after this
1893 # takes a table by its lines but table_regions().
1894 #
1895 # What is kept in one pane is joined by GROUP SEPARATOR, which
1896 # --intact keeps together (keep.table): with "row", the lines of
1897 # a row, which come from ansicolumn so (--table-group); with
1898 # "head", also the header, the rule below it and the first
1899 # row, and a rule below the table (3line, simple) with the last
1900 # row; with "all", the whole table; with "none", nothing.
1901 279 ▶ if (intact('table')) {
Branch: 1 branch
BranchTrueFalseTotal
if (intact("table")) 13 266 279
1902 13 my @rows = split /\n/, $table;
1903 # the rule below the header: the first rule after a line
1904 # which is not one (3line has one above the header)
1905 13 my $head;
1906 13 for my $i (1 .. $#rows) {
1907 16 ▶ $rows[$i] =~ /^[\x{2500}\x{253C}\x{251C}\x{2524}|\- ]+$/ or next;
Branch: 1 branch
BranchTrueFalseTotal
$rows[$i] =~ /^[\x{2500}\x{253C}\x{251C}\x{2524}|\- ]+$/u or next 13 3 16
1908 13 $head = $i;
1909 13 last;
1910 }
1911 13 my $keep = table_keep();
1912 13 ▶ my %glue = map { $_ => 1 }
Branch: 2 branches
BranchTrueFalseTotal
$keep eq 'all' ? : 1 12 13
$keep eq 'head' ? : 9 3 12
Condition50%1/2
$head // 0
l!l
90
MC/DC0%0/1
$head // 0
$head
Truth table50%1/2
A
A= $head
Aresult
11
00
1913 $keep eq 'all' ? 1 .. $#rows
1914 : $keep eq 'head' ? 1 .. min(($head // 0) + 1, $#rows)
1915 : ();
1916 13 ▶ $glue{$#rows} = 1 if $keep eq 'head' and $open and @rows > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $keep eq "head" and $open and @rows > 1 2 11 13
Condition83%5/6
$keep eq "head" and $open and @rows > 1
!ll&&!rl&&r
1102
$keep eq "head" and $open
!ll&&!rl&&r
472
MC/DC66%2/3
$keep eq "head" and $open and @rows > 1
$keep eq "head" $open @rows > 1
Truth table75%3/4
A and B and C
A= $keep eq "head"B= $openC= @rows > 1
ABCresult
0XX0
10X0
1100
1111
1917 $table = $rows[0] . join('', map {
1918 13 ▶ ($glue{$_} ? $GROUP_SEP : $INTACT_SEP) . $rows[$_]
Branch: 1 branch
BranchTrueFalseTotal
$glue{$_} ? : 27 44 71
1919 } 1 .. $#rows) . "\n";
1920 }
1921 279 push @table_shift, [ $line, ($table =~ tr/\n//) - $lines, $lines ];
1922 279 $table;
1923 }mgep;
1924 # the separators of mark_line_breaks() left out of the tables
1925 251 s{<br\h*/?>\K\x{2028}}{}gi;
1926 }
1927  
1928 # What of a table kept intact is kept in one pane (keep.table): none,
1929 # row, head or all
1930 27 ▶sub table_keep {
Subroutine table_keep: called CC=3 SCAR=11.1
Pod undocumented
1931 27 ▶ my $keep = $config->{keep}{table} || 'head';
Condition50%1/2
$config->{'keep'}{'table'} || 'head'
l!l
270
MC/DC0%0/1
$config->{'keep'}{'table'} || 'head'
$config->{'keep'}{'table'}
Truth table50%1/2
A
A= $config->{'keep'}{'table'}
Aresult
11
00
1932 27 ▶ $keep =~ /^(?:none|row|head|all)$/
Branch: 1 branch
BranchTrueFalseTotal
$keep =~ /^(?:none|row|head|all)$/u or die "keep.table: none, row, head or all expected, not '${keep}'\n" 26 1 27
1933 or die "keep.table: none, row, head or all expected, not '$keep'\n";
1934 26 $keep;
1935 }
1936  
1937 287 ▶sub parse_separator {
Subroutine parse_separator: called CC=3 SCAR=11.0
Pod undocumented
1938 287 my $blockref = shift;
1939 287 my $SEP = qr/^\h*+\|(\h*+:?+-++:?+\h*+\|)++\h*+$/mn;
1940 287 my ($sep_line) = $$blockref =~ /($SEP)/;
1941 287 ▶ return ([], []) unless defined $sep_line;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $sep_line 1 286 287
1942 286 my @cells = split /\|/, $sep_line, -1;
1943 286 shift @cells; pop @cells;
1944 286 s/^\h+|\h+$//g for @cells;
1945 286 my @right = grep { $cells[$_-1] =~ /^-+:$/ } 1..@cells;
1946 286 my @center = grep { $cells[$_-1] =~ /^:-+:$/ } 1..@cells;
1947 # Minimize dashes so separator width doesn't inflate column widths
1948 286 $$blockref =~ s{$SEP}{ ${^MATCH} =~ s/:?-+:?/-/gr }mpe;
1949 286 (\@right, \@center);
1950 }
1951  
1952 # Color the code of fenced code blocks by a highlighter of
1953 # Text::ANSI::Highlight: the one of the name in the config highlight,
1954 # or its default for 1. Takes [ language, code ] of each block, and
1955 # returns as many: the code in colors, or undef for a block which is
1956 # not colored, as one with no language or with one the highlighter
1957 # does not know. All are undef when the module, the highlighter or
1958 # its command is not there, and the blocks are shown as they are.
1959 #
1960 # All the blocks are given at once, and each is colored by itself.
1961 # What comes back is the code which was given, with colors, so the
1962 # lines are those of the file.
1963 # The labels of the lines of a code block, when it has parts: a block
1964 # of pandoc-embedz has config, template and data. A line of a part
1965 # labelled NAME is in the color code_NAME, when it is defined.
1966 317 ▶sub code_labels {
Subroutine code_labels: called CC=4 SCAR=13.9
Pod undocumented
1967 317 my($info, $body) = @_;
1968 317 ▶ my @part = eval {
Branch: 1 branch
BranchTrueFalseTotal
my(@part) = eval { do { require Text::ANSI::Highlight; "Text::ANSI::Highlight"->parts($info, $body) } } or return () 317 0 317
1969 317 require Text::ANSI::Highlight;
1970 317 Text::ANSI::Highlight->parts($info, $body);
1971 } or return ();
1972 # in a block with labelled parts, the lines of the others, which
1973 # are between them, have no color
1974 317 ▶ (grep { defined $_->[2] } @part) or return ();
Branch: 1 branch
BranchTrueFalseTotal
grep {defined $_->[2];} @part or return () 3 314 317
1975 3 ▶ map { my @line = split /(?<=\n)/, $_->[1]; ($_->[2] // '') x @line } @part;
Condition100%2/2
$_->[2] // ""
l!l
53
MC/DC100%1/1
$_->[2] // ""
$_->[2]
Truth table100%2/2
A
A= $_->[2]
Aresult
11
00
1976 }
1977  
1978 # the highlighter in the dark mode, when none is named
1979 341 our $DARK_HIGHLIGHT = 'pandoc:breezedark';
1980  
1981 226 ▶sub highlight_code {
Subroutine highlight_code: called CC=7 SCAR=19.5
Pod undocumented
1982 226 my @code = @_;
1983 226 my @none = (undef) x @code;
1984 226 ▶ @code or return @none;
Branch: 1 branch
BranchTrueFalseTotal
@code or return @none 168 58 226
1985 168 my $name = $config->{highlight};
1986 # the default is pandoc, in a style for a dark screen in the dark
1987 # mode
1988 my @with = $name ne '1' ? $name
1989 168 ▶ : ($config->{mode} // '') eq 'dark' ? $DARK_HIGHLIGHT : ();
Branch: 2 branches
BranchTrueFalseTotal
$name ne '1' ? : 6 162 168
($config->{'mode'} // '') eq 'dark' ? : 10 152 162
Condition50%1/2
$config->{"mode"} // ""
l!l
1620
MC/DC0%0/1
$config->{"mode"} // ""
$config->{"mode"}
Truth table50%1/2
A
A= $config->{"mode"}
Aresult
11
00
1990 168 ▶ my $hl = eval {
Branch: 1 branch
BranchTrueFalseTotal
my $hl = eval { do { require Text::ANSI::Highlight; "Text::ANSI::Highlight"->new(@with, "background", 0) } } or return @none 167 1 168
1991 168 require Text::ANSI::Highlight;
1992 # the background is that of the code block: a style for a
1993 # dark screen has its own
1994 168 Text::ANSI::Highlight->new(@with, background => 0);
1995 } or return @none;
1996 167 my @color = eval { $hl->highlight(@code) };
1997 167 ▶ @color == @code ? @color : @none;
Branch: 1 branch
BranchTrueFalseTotal
@color == @code ? : 167 0 167
1998 }
1999  
2000 297 ▶sub call_ansicolumn {
Subroutine call_ansicolumn: called CC=3 SCAR=11.0
Pod undocumented
2001 297 my ($text, @args) = @_;
2002 297 require Command::Run;
2003 297 require App::ansicolumn;
2004 Command::Run->new
2005 ->command(\&App::ansicolumn::ansicolumn, @args)
2006 ->with(stdin => $text,
2007 297 ▶ $config->{nofork} ? (nofork => 1, raw => 1) : ())
Branch: 1 branch
BranchTrueFalseTotal
$config->{'nofork'} ? : 293 4 297
Condition50%1/2
"Command::Run"->new->command(\&App::ansicolumn::ansicolumn, @args)->with("stdin", $text, $config->{"nofork"} ? ("nofork", 1, "raw", 1) : ())->update->data // ""
l!l
2970
MC/DC0%0/1
"Command::Run"->new->command(\&App::ansicolumn::ansicolumn, @args)->with("stdin", $text, $config->{"nofork"} ? ("nofork", 1, "raw", 1) : ())->update->data // ""
"Command::Run"->new->command(\&App::ansicolumn::ansicolumn, @args)->with("stdin", $text, $config->{"nofork"} ? ("nofork", 1, "raw", 1) : ())->update->data
Truth table50%1/2
A
A= "Command::Run"->new->command(\&App::ansicolumn::ansicolumn, @args)->with("stdin", $text, $config->{"nofork"} ? ("nofork", 1, "raw", 1) : ())->update->data
Aresult
11
00
2008 ->update
2009 ->data // '';
2010 }
2011  
2012 279 ▶sub fix_separator {
Subroutine fix_separator: called CC=7 SCAR=19.5
Pod undocumented
2013 279 my ($text, $sep) = @_;
2014 279 ▶ my $sep_re = $sep eq "\x{2502}" ? "\x{2502}" : '\\|';
Branch: 1 branch
BranchTrueFalseTotal
$sep eq "\x{2502}" ? : 275 4 279
2015 279 $text =~ s{^(\h*?)($sep_re)?((?:\h*-+\h*$sep_re)*\h*-+\h*)($sep_re)?(\h*?)$}{
2016 279 my($pre, $left, $mid, $right, $post) = ($1, $2, $3, $4, $5);
2017 279 ▶ if ($sep eq "\x{2502}") {
Branch: 1 branch
BranchTrueFalseTotal
if ($sep eq "\x{2502}") { } 275 4 279
2018 275 ▶ ($pre =~ tr[ ][\x{2500}]r)
Branch: 2 branches
BranchTrueFalseTotal
defined $left ? : 5 270 275
defined $right ? : 5 270 275
2019 . (defined $left ? "\x{251C}" : '')
2020 . ($mid =~ tr[\x{2502} -][\x{253C}\x{2500}\x{2500}]r)
2021 . (defined $right ? "\x{2524}" : '')
2022 . ($post =~ tr[ ][\x{2500}]r)
2023 } else {
2024 4 ▶ ($pre =~ tr[ ][-]r)
Branch: 2 branches
BranchTrueFalseTotal
defined $left ? : 0 4 4
defined $right ? : 0 4 4
2025 . (defined $left ? '|' : '')
2026 . ($mid =~ tr[ ][-]r)
2027 . (defined $right ? '|' : '')
2028 . ($post =~ tr[ ][-]r)
2029 }
2030 }xmeg;
2031 279 $text;
2032 }
2033  
2034 341 1;
2035  
2036 __DATA__
« blib/lib/App/Greple/md/Mermaid.pm ↑ Summary blib/lib/App/Greple/md/Image.pm »