blib/lib/App/Greple/md.pm

filter: Statementstmt 94.0% 507 / 539 Branchbran 87.1% 190 / 218 Conditioncond 69.5% 73 / 105 MC/DCmcdc 49.1% 29 / 59 Subroutinesub 97.2% 71 / 73 Podpod 0.0% 0 / 35 totaltotal 84.5% 870 / 1029 CC 170 SCAR 22.9
CC
170
Cov
89%
default_theme
30.0
format_table
27.0
setup_colors
18.1
CRAP 9.9
« blib/lib/App/Greple/md/Image.pm ↑ Summary blib/lib/App/Greple/md/widen.pm »
1 # -*- mode: perl; coding: utf-8 -*-
2 # vim: set fileencoding=utf-8 filetype=perl :
3 package App::Greple::md;
4  
5 221 ▶use 5.026;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 221 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 221 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 221 our $VERSION = "1.29";
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>.
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 image_types types of images to show, separated by colons:
287 png, jpeg and gif; the rows of an image are put
288 below a line which is an image, and its data is
289 sent to the terminal (default: none, no images);
290 see Text::ANSI::Image
291 image_rows maximum rows of an image (default: 0, the
292 terminal height minus four lines)
293 image_term size of the terminal as COLSxROWS:WxH, the
294 columns and rows and the width and height of a
295 cell in pixels (default: read from /dev/tty)
296 image_tty file to send the image data to (default: /dev/tty)
297 image_osc 1: each row of an image tells its file by a private
298 OSC, for ansi2pdf, which draws the image itself
299 (default: 0)
300 table_style lattice: column separators (default; pipe is
301 another name); 3line: columns separated by spaces,
302 a rule above and below the table and per column
303 below the header; simple: columns separated by
304 spaces, a rule per column below the header and
305 below the table
306 table_gap columns between a cell and the mark place of the
307 next column, the column separator included
308 (default: 1)
309 rule box-drawing characters (default: 1)
310 osc8 OSC 8 hyperlinks (default: 1)
311 heading_markup inline markup in headings (default: 0)
312 0=off, 1/all=all, or colon-separated steps
313 cjk_friendly markdown-cjk-friendly rules for * and **
314 emphasis (default: 0)
315 tick_open inline code open marker (default: `)
316 tick_close inline code close marker (default: ´)
317 nofork nofork+raw mode for code ref calls (default: 1)
318 highlight syntax highlight of fenced code: 1, the name
319 of a highlighter, or 0 (default: 1)
320 hashed.h1-h6 closing hashes per level (default: 0)
321  
322 =head2 Paragraph Refill
323  
324 With C<refill=1>, the lines of every paragraph, block quote, list
325 item and definition are joined into one line before the text is
326 colorized. Which lines belong together is decided by a Markdown
327 parser (L<App::Greple::md::Blocks>): the L<CommonMark> module, an
328 interface to libcmark, when it is installed, otherwise
329 L<Markdown::Perl>, which is pure Perl and always installed with this
330 module, or L<pandoc|https://pandoc.org> (2.11.3 or later) run with the
331 C<sourcepos> extension; C<refill_parser> chooses one. The module
332 joins the lines of the original text and changes nothing else. Hard
333 line breaks are kept, and so is the break before a list marker, a
334 horizontal rule, a table row or a definition (C<: >). When folding
335 is enabled, the joined lines are folded too.
336  
337 Front matter (see L</Front Matter>) is left as it is.
338  
339 greple -Mmd::config(refill=1) file.md
340 greple -Mmd::config(refill=1,refill_parser=pandoc) file.md
341  
342 =head2 Front Matter
343  
344 Front matter at the top of the file is shown as a code block: the
345 body in C<meta_block> and the delimiter lines in C<meta_mark>, with
346 no other markup, and it is not folded or joined.
347 TOML front matter is between C<+++> lines, and YAML front matter goes
348 from a C<---> line to a C<---> or C<...> line, as pandoc takes it (the
349 opening line is not followed by a blank line).
350  
351 Front matter is not part of CommonMark. pandoc and L<Markdown::Perl>
352 take YAML front matter as metadata, while libcmark reads it as a rule,
353 paragraphs and list items. C<front_matter=0> takes the lines as
354 Markdown, as libcmark does.
355  
356 =head2 Syntax Highlight of Code
357  
358 The code in a fenced code block is shown in the colors of its
359 language, the first word after the opening fence, inside the
360 C<code_block> color. The colors are those of a highlighter of
361 L<Text::ANSI::Highlight>: C<highlight=1> is its default, C<pandoc>,
362 and C<highlight=sourcehighlight> (C<gnu>) or C<highlight=skylighting>
363 (C<sky>) is the one of the name. All the blocks of a file are given
364 to the highlighter at once, and each is colored by itself.
365  
366 C<highlight=1> is C<pandoc> in its own style in the light mode, and in
367 the style C<breezedark> in the dark mode. A style of the highlighter
368 can be named after a colon (C<highlight=pandoc:haddock>), and a
369 highlighter which is named is as it is named in both modes. The
370 background colors of a style are not used: the background is that of
371 the code block.
372  
373 The language is also the first class in braces, as pandoc takes it
374 (C<```{.perl .numberLines}>).
375  
376 A block which has parts is colored part by part, when
377 L<Text::ANSI::Highlight> has a module for it. A block of
378 L<pandoc-embedz|https://github.com/tecolicom/pandoc-embedz>
379 (C<```embedz>, C<```{.embedz data=file.csv}>) has a configuration in
380 YAML, a template of Jinja2 and data: they are colored by their
381 languages, in the backgrounds of C<code_config>, C<code_block> and
382 C<code_data>, and the lines of C<---> between them have no color.
383 The lines of a part labelled I<NAME> by the module are in the color
384 C<code_I<NAME>>, and in C<code_block> when it is not defined.
385  
386 A block is shown as it is when it has no language, when the
387 highlighter does not know the language, and when the module, the
388 highlighter or its command (C<pandoc>, C<source-highlight>,
389 C<skylighting>) is not installed. C<highlight=0> turns it off.
390  
391 =head2 OSC 8 Hyperlinks
392  
393 Links are converted to clickable OSC 8 terminal hyperlinks in
394 supported terminals (iTerm2, Kitty, WezTerm, Ghostty, etc.).
395 Disable with:
396  
397 greple -Mmd::config(osc8=0) file.md
398  
399 =head2 Settings of the User
400  
401 The module runs B<ansifold> and B<ansicolumn> for folding and tables.
402 They are run as functions in the greple process, or as separate
403 processes with C<nofork=0>, and either way they do not read the rc
404 files of the user, F<~/.ansifoldrc> and F<~/.ansicolumnrc>: the
405 module puts their names in the environment variable
406 C<GETOPTEX_NO_USER_SETTINGS> (see L<Getopt::EX::Long>), so that the
407 output does not change by the settings made for them on the command
408 line.
409  
410 =head1 COLOR LABELS
411  
412 The following labels identify colorizable elements. Use them
413 with C<--colormap> (C<--cm>) to customize colors or C<--show> to control
414 visibility. Default values are shown as C<light / dark>.
415 Colors follow L<Term::ANSIColor::Concise> format.
416  
417 =head2 Headings
418  
419 LABEL LIGHT DARK
420 h1 L25D/${base};E L00D/${base};E
421 h2 L25D/${base}+y20;E L00D/${base}-y15;E
422 h3 L25DN/${base}+y20 L00DN/${base}-y15
423 h4 ${base}UD ${base}UD
424 h5 ${base}UD ${base}UD
425 h6 ${base}D ${base}D
426  
427 =head2 Inline Formatting
428  
429 LABEL LIGHT DARK
430 bold D
431 italic I
432 strike X
433 emphasis_mark L18 L10
434 bold_mark - -
435 italic_mark - -
436 strike_mark - -
437  
438 Emphasis markers (C<**>, C<*>, C<__>, C<_>, C<~~>) are colored with
439 C<emphasis_mark>, separately from the content text. C<bold_mark>,
440 C<italic_mark>, C<strike_mark> are undefined by default and fall back
441 to C<emphasis_mark>. Define them via C<--cm> to override per type:
442  
443 greple -Mmd --cm emphasis_mark=R -- file.md # all markers red
444 greple -Mmd --cm bold_mark=G -- file.md # bold markers green
445  
446 C<*> and C<**> start and end emphasis as in CommonMark: a delimiter
447 next to a letter on one side and punctuation on the other does not
448 count, so C<L*=50, a*=68> is not italic. In Japanese text this also
449 rejects C<日本語の*「強調」*です> and C<日本語の**強調。**です>, as the
450 commonmark and gfm readers of pandoc do. With C<cjk_friendly=1>,
451 the rules of
452 L<markdown-cjk-friendly|https://github.com/tats-u/markdown-cjk-friendly>
453 are used instead, and these are emphasis.
454  
455 =head2 Code
456  
457 LABEL LIGHT DARK
458 code_mark L20 L10
459 code_tick L15/L23 L15/L05
460 code_info ${base_name}=y70 L10
461 code_block /L24;E /L03;E
462 code_config /#ECE9F7;E /#1C1B24;E
463 code_data /#E3F1EA;E /#181E1A;E
464 code_inline L00/L23 L25/L05
465 meta_mark L15/L10E L10/L15E
466 meta_block L25/L12E L00/L13E
467  
468 Inline code backticks are displayed as C<`contentE<0xb4>> using
469 C<code_tick> color. Multi-backtick delimiters are collapsed to a
470 single pair with optional surrounding spaces stripped (per CommonMark).
471 The open/close markers can be customized via C<tick_open>/C<tick_close>
472 config parameters.
473  
474 C<code_config> and C<code_data> are the backgrounds of the
475 configuration and the data in a block of pandoc-embedz (see
476 L</Syntax Highlight of Code>).
477  
478 C<meta_mark> and C<meta_block> color the delimiter lines and the
479 body of front matter (see L</Front Matter>), the delimiter lines in
480 the background of the file name and the body a little apart from it.
481 When they are set to empty, C<meta_block> falls back to C<code_block>,
482 and the delimiter lines are in C<code_mark> inside the color of the
483 body.
484  
485 =head2 Block Elements
486  
487 LABEL LIGHT / DARK
488 blockquote ${base}
489 horizontal_rule L15
490 comment ${base}+r60
491  
492 =head2 Links
493  
494 LABEL LIGHT / DARK
495 link I
496 image I
497 image_link I
498 link_mark - -
499  
500 C<link_mark> colors the brackets (C<[>, C<]>) around link and image
501 text. Undefined by default, falls back to C<emphasis_mark>.
502 The C<!> prefix for images uses the C<image> or C<image_link>
503 color. Hide brackets with C<--cm 'link_mark=sub{""}'> (used by
504 the C<nomark> theme).
505  
506 =head2 Line Breaks in Tables
507  
508 LABEL LIGHT / DARK
509 br_mark - -
510  
511 C<br_mark> colors a C<< <br> >> which breaks a table cell into lines
512 (see B<--[no-]table>). Undefined by default, falls back to
513 C<emphasis_mark>. Hide it with C<--cm 'br_mark=sub{""}'> (used by
514 the C<nomark> theme): the line break is left, and the tag is not
515 shown.
516  
517 =head1 SEE ALSO
518  
519 =over 4
520  
521 =item L<App::mdee>
522  
523 Markdown viewer command with line folding, table formatting,
524 multi-column layout, and themes. Uses this module for syntax
525 highlighting.
526  
527 =item L<App::Greple>
528  
529 General-purpose extensible grep tool that hosts this module.
530  
531 =item L<Term::ANSIColor::Concise>
532  
533 Concise ANSI color specification format used for color labels.
534  
535 =item L<App::ansicolumn>
536  
537 ANSI-aware column formatting used for table alignment.
538  
539 =item L<App::ansifold>
540  
541 ANSI-aware text folding used for line wrapping in list items.
542  
543 =item L<App::Greple::md::widen>
544  
545 A function for B<--begin>, for characters that terminals draw over two
546 columns.
547  
548 =item L<App::Greple::md::Blocks>
549  
550 Finds the paragraphs for C<refill=1> with L<CommonMark>,
551 L<Markdown::Perl> or L<pandoc|https://pandoc.org>.
552  
553 =item L<Text::ANSI::Image>
554  
555 Shows the images for C<image_types>, with the Unicode placeholders
556 of the kitty graphics protocol. L<App::Greple::md::Image> finds
557 their files.
558  
559 =item L<CommonMark Spec 0.31.2, Emphasis and strong emphasis|https://spec.commonmark.org/0.31.2/#emphasis-and-strong-emphasis>
560  
561 The rules that C<*> and C<**> follow by default.
562  
563 =item L<CommonMark CJK-friendly Amendments|https://github.com/tats-u/markdown-cjk-friendly/blob/main/specification.md>
564  
565 The rules that C<cjk_friendly=1> follows. The proposal comes from
566 L<commonmark-spec issue #650, Emphasis with CJK punctuation|https://github.com/commonmark/commonmark-spec/issues/650>,
567 open since 2020.
568  
569 =back
570  
571 =head1 AUTHOR
572  
573 Kazumasa Utashiro
574  
575 =head1 LICENSE
576  
577 Copyright © 2025-2026 Kazumasa Utashiro.
578  
579 This library is free software; you can redistribute it and/or modify
580 it under the same terms as Perl itself.
581  
582 =cut
583  
584 221 ▶use URI::Escape;
Subroutine BEGIN: called CC=1 SCAR=0.0
585 221 ▶use List::Util qw(min);
Subroutine BEGIN: called CC=1 SCAR=0.0
586 221 ▶use Text::ANSI::Fold qw($csi_re $osc_re);
Subroutine BEGIN: called CC=1 SCAR=0.0
587 221 ▶use Text::ANSI::Fold::Util qw(ansi_width);
Subroutine BEGIN: called CC=1 SCAR=0.0
588 221 ▶use Getopt::EX::Config;
Subroutine BEGIN: called CC=1 SCAR=0.0
589 221 ▶use Getopt::EX::Colormap;
Subroutine BEGIN: called CC=1 SCAR=0.0
590 221 ▶use Getopt::EX::Func qw(parse_func);
Subroutine BEGIN: called CC=1 SCAR=0.0
591 221 ▶use App::Greple::Common qw(FILELABEL);
Subroutine BEGIN: called CC=1 SCAR=0.0
592 221 ▶use App::Greple::Regions qw(match_regions);
Subroutine BEGIN: called CC=1 SCAR=0.0
593 221 ▶use App::Greple::md::Blocks qw(blocks);
Subroutine BEGIN: called CC=1 SCAR=0.0
594 221 ▶use App::Greple::md::Image qw(local_path);
Subroutine BEGIN: called CC=1 SCAR=0.0
595 221 ▶use Text::ANSI::Image;
Subroutine BEGIN: called CC=1 SCAR=0.0
596  
597 221 my @color_labels = qw(
598 code_mark code_tick code_info code_block code_inline
599 code_config code_template code_data
600 meta_mark meta_block
601 comment link image image_link
602 h1 h2 h3 h4 h5 h6
603 bold italic strike emphasis_mark
604 bold_mark italic_mark strike_mark link_mark br_mark
605 blockquote horizontal_rule
606 );
607  
608 my $config = Getopt::EX::Config->new(
609 mode => '', # light / dark
610 osc8 => 1, # OSC 8 hyperlinks
611 base_color => '', # override base color
612 colorize => 1, # syntax highlighting
613 fold => 0, # text folding
614 refill => 0, # join the lines of paragraphs
615 refill_parser => '', # cmark (CommonMark module), mdperl (Markdown::Perl) or pandoc; '' = whichever is there
616 front_matter => 1, # front matter (+++ TOML, --- YAML) at the top is a code block
617 fold_width => 80, # fold width
618 fold_runin => 4, # run-in width in folded lines (ansifold default)
619 fold_runout => 4, # run-out width in folded lines (ansifold default)
620 table => 1, # table formatting
621 table_trim => 1, # trim cell content whitespace
622 table_width => 0, # table width; wrap over-wide cells (0 = off)
623 table_cell => '', # per-column widths for ansicolumn --cell (colon separated)
624 table_wrap_mark => '', # mark for continuation lines of wrapped cells
625 table_cell_mark => '', # mark for the first line of cells in wrapped columns
626 table_runin => 2, # run-in width in wrapped cells
627 table_runout => 2, # run-out width in wrapped cells
628 table_boundary => 'word', # fold boundary in wrapped cells
629 table_linebreak => 'all', # line break (kinsoku) mode in wrapped cells
630 intact => '', # parts kept intact by ansicolumn --intact (table, image)
631 image_types => '', # types of images shown, colon separated (png:jpeg:gif)
632 image_rows => 0, # rows that an image may take (0: those of the terminal but four)
633 image_term => '', # size of the terminal, COLSxROWS:WxH (default: of /dev/tty)
634 image_tty => '', # where the data of the images goes (default: /dev/tty)
635 image_osc => 0, # tell the file of each image in its rows, for ansi2pdf
636 rule => 1, # box-drawing characters for tables
637 table_style => 'lattice', # lattice (or pipe): column separators; 3line, simple: spaces and rules only
638 table_gap => 1, # columns from a cell to the mark place of the next column
639 nofork => 1, # use nofork+raw for code ref calls
640 highlight => 1, # syntax highlight of fenced code: 1, the name of a highlighter, or 0
641 heading_markup => 0, # inline formatting in headings
642 cjk_friendly => 0, # markdown-cjk-friendly rules for * and ** emphasis
643 tick_open => '`', # inline code open marker
644 tick_close => "\x{b4}", # inline code close marker (´)
645 hashed => { h1 => 0, h2 => 0, h3 => 0, h4 => 0, h5 => 0, h6 => 0 },
646 221 (map { $_ => undef } @color_labels), # color labels (undef = not set)
647 );
648  
649 #
650 # Color definitions
651 #
652  
653 221 my %base_color = (
654 light => '<RoyalBlue>=y25',
655 dark => '<RoyalBlue>=y80',
656 );
657  
658 221 my %default_colors = (
659 code_mark => 'L20',
660 code_tick => 'L15/L23',
661 code_info => '${base_name}=y70',
662 code_block => '/L24;E',
663 code_config => '/#ECE9F7;E',
664 code_data => '/#E3F1EA;E',
665 code_inline => 'L00/L23',
666 meta_mark => 'L15/L10E',
667 meta_block => 'L25/L12E',
668 comment => '${base}+r60',
669 link => 'I',
670 image => 'I',
671 image_link => 'I',
672 h1 => 'L25D/${base};E',
673 h2 => 'L25D/${base}+y20;E',
674 h3 => 'L25DN/${base}+y20',
675 h4 => '${base}UD',
676 h5 => '${base}UD',
677 h6 => '${base}D',
678 bold => 'D',
679 italic => 'I',
680 strike => 'X',
681 emphasis_mark => 'L18',
682 blockquote => '${base}',
683 horizontal_rule => 'L15',
684 );
685  
686 221 my %dark_overrides = (
687 code_mark => 'L10',
688 code_tick => 'L15/L05',
689 code_info => 'L10',
690 code_block => '/L03;E',
691 code_config => '/#1C1B24;E',
692 code_data => '/#181E1A;E',
693 code_inline => 'L25/L05',
694 meta_mark => 'L10/L15E',
695 meta_block => 'L00/L13E',
696 h1 => 'L00D/${base};E',
697 h2 => 'L00D/${base}-y15;E',
698 h3 => 'L00DN/${base}-y15',
699 h4 => '${base}UD',
700 h5 => '${base}UD',
701 h6 => '${base}D',
702 emphasis_mark => 'L10',
703 );
704  
705 0 ▶sub default_theme {
Subroutine default_theme: not called CC=5 SCAR=34.0
Pod undocumented
706 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
707 0 my %colors = %default_colors;
708 0 ▶ if ($mode eq 'dark') {
Branch: 1 branch
BranchTrueFalseTotal
if ($mode eq "dark") 0 0 0
709 0 @colors{keys %dark_overrides} = values %dark_overrides;
710 }
711 0 $colors{base} = $base_color{$mode};
712 0 ▶ if (defined wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined wantarray) { } 0 0 0
713 0 %colors;
714 } else {
715 # Print as bash array assignments: theme_MODE[key]='value'
716 0 for my $key (sort keys %colors) {
717 0 (my $val = $colors{$key}) =~ s/'/'\\''/g;
718 0 printf "theme_%s[%s]='%s'\n", $mode, $key, $val;
719 }
720 }
721 }
722  
723 221 my $cm;
724 my @opt_cm;
725 221 my @opt_begin;
726 221 my %show;
727  
728 214 ▶sub finalize {
Subroutine finalize: called CC=5 SCAR=16.7
Pod undocumented
729 214 my($mod, $argv) = @_;
730 214 no_user_settings(qw(ansicolumn ansifold));
731 214 $config->deal_with($argv,
732 "mode|m=s", "base_color|B=s",
733 "colorize!", "nofork!", "fold!", "refill!", "refill_parser=s", "front_matter!", "fold_width=i", "fold_runin=i", "fold_runout=i",
734 "table!", "table_trim!",
735 "table_width=i", "table_cell=s", "table_wrap_mark=s", "table_cell_mark=s", "rule!", "table_style=s", "table_gap=i",
736 "table_runin=i", "table_runout=i", "table_boundary=s", "table_linebreak=s", "intact=s", "image_types=s", "image_rows=i", "image_term=s", "image_tty=s", "image_osc=i",
737 "heading_markup|hm:s", "cjk_friendly!", "tick_open=s", "tick_close=s",
738 "hashed=s%",
739 "colormap|cm=s" => \@opt_cm,
740 "begin=s" => \@opt_begin,
741 "show=s%" => \%show);
742 # --hm with no argument gives "": treat as "all"
743 214 my $hm = $config->{heading_markup};
744 214 ▶ if (defined $hm && $hm eq '') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $hm and $hm eq "") 0 214 214
Condition33%1/3
defined $hm and $hm eq ""
!ll&&!rl&&r
02140
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
745 0 $config->{heading_markup} = 'all';
746 }
747 214 ▶ if (my $w = $config->{fold_width}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $w = $config->{"fold_width"}) 214 0 214
748 214 my $fold = join ' ', '--fold-by', $w, @{$config}{qw(fold_runin fold_runout)};
749 214 $mod->setopt('--fold', $fold);
750 214 ▶ if ($config->{fold}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($config->{"fold"}) 73 141 214
751 73 my @default = $mod->default;
752 73 $mod->setopt('default', @default, $fold);
753 }
754 }
755 }
756  
757 # ansicolumn and ansifold are called as functions in this process
758 # (Command::Run), or as separate processes by the tee module in fork
759 # mode. Either way they must not read the rc files of the user, so
760 # their names go into GETOPTEX_NO_USER_SETTINGS (Getopt::EX >= 3.05),
761 # which Getopt::EX::Long reads when the program first runs. Names
762 # already there are kept, and 1 or * (all programs) is left as it is.
763 220 ▶sub no_user_settings {
Subroutine no_user_settings: called CC=4 SCAR=13.9
Pod undocumented
764 220 my @names = @_;
765 220 ▶ my $env = $ENV{GETOPTEX_NO_USER_SETTINGS} // '';
Condition100%2/2
$ENV{"GETOPTEX_NO_USER_SETTINGS"} // ""
l!l
5215
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
766 220 ▶ return if $env eq '1' or $env eq '*';
Branch: 1 branch
BranchTrueFalseTotal
if $env eq 1 or $env eq "*" 2 218 220
Condition100%3/3
$env eq 1 or $env eq "*"
l!l&&r!l&&!r
11218
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
767 218 my %have = map { $_ => 1 } split /[\s,]+/, $env;
768 $ENV{GETOPTEX_NO_USER_SETTINGS} =
769 218 join ' ', grep { length } $env, grep { !$have{$_}++ } @names;
770 }
771  
772 117 ▶sub setup_colors {
Subroutine setup_colors: called CC=13 SCAR=29.0
Pod undocumented
773 117 ▶ my $mode = $config->{mode} || 'light';
Condition100%2/2
$config->{'mode'} || 'light'
l!l
6948
MC/DC100%1/1
$config->{'mode'} || 'light'
$config->{'mode'}
Truth table100%2/2
A
A= $config->{'mode'}
Aresult
11
00
774 117 my %colors = %default_colors;
775 117 ▶ if ($mode eq 'dark') {
Branch: 1 branch
BranchTrueFalseTotal
if ($mode eq "dark") 5 112 117
776 5 @colors{keys %dark_overrides} = values %dark_overrides;
777 }
778 # Determine base color
779 117 my $base = $config->{base_color};
780 117 ▶ if ($base) {
Branch: 1 branch
BranchTrueFalseTotal
if ($base) { } 0 117 117
781 # Color names get automatic luminance adjustment
782 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
783 if $base =~ /^[A-Za-z]\w*$/;
784 } else {
785 117 ▶ $base = $base_color{$mode} || $base_color{light};
Condition33%1/3
$base_color{$mode} || $base_color{'light'}
l!l&&r!l&&!r
11700
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
786 }
787 # Override with config params (e.g., config(h1=RD))
788 117 for my $key (@color_labels) {
789 3627 my $val = $config->{$key};
790 3627 ▶ if (defined $val) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $val) 11 3616 3627
791 11 $colors{$key} = $val;
792 }
793 }
794 # ${base_name}: color without luminance (e.g., '<RoyalBlue>')
795 117 (my $base_name = $base) =~ s/=y\d+$//;
796 # Expand placeholders
797 117 for my $key (keys %colors) {
798 2925 $colors{$key} =~ s/\$\{base_name\}/$base_name/g;
799 2925 $colors{$key} =~ s/\$\{base\}/$base/g;
800 }
801 # Handle + prefix: prepend current color value before load_params
802 # (load_params' built-in + doesn't work correctly with sub{...})
803 117 my @final_cm;
804 117 for my $entry (@opt_cm) {
805 264 my $expanded = $entry =~ s/\$\{base_name\}/$base_name/gr
806 =~ s/\$\{base\}/$base/gr;
807 264 ▶ if ($expanded =~ /^(\w+)=\+(.*)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expanded =~ /^(\w+)=\+(.*)/u) { } 0 264 264
808 0 my ($label, $append) = ($1, $2);
809 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
810 0 push @final_cm, "$label=$current$append";
811 } else {
812 264 push @final_cm, $expanded;
813 }
814 }
815  
816 117 $cm = Getopt::EX::Colormap->new(
817 HASH => \%colors,
818 NEWLABEL => 1,
819 );
820 117 $cm->load_params(@final_cm);
821 }
822  
823 1626 ▶sub active {
Subroutine active: called CC=4 SCAR=13.9
Pod undocumented
824 1626 my $label = shift;
825 1626 ▶ return 0 if exists $show{$label} && !$show{$label};
Branch: 1 branch
BranchTrueFalseTotal
if exists $show{$label} and not $show{$label} 17 1609 1626
Condition100%3/3
exists $show{$label} and not $show{$label}
!ll&&!rl&&r
1607217
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
826 1609 ▶ return 1 unless exists $cm->{HASH}{$label};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $cm->{"HASH"}{$label} 115 1494 1609
827 1494 $cm->{HASH}{$label} ne '';
828 }
829  
830 #
831 # Apply color by label
832 #
833  
834 7462 ▶sub md_color {
Subroutine md_color: called CC=1 SCAR=0.0
Pod undocumented
835 7462 my($label, $text) = @_;
836 7462 $cm->color($label, $text);
837 }
838  
839 23 ▶sub defined_color {
Subroutine defined_color: called CC=2 SCAR=6.9
Pod undocumented
840 23 my $label = shift;
841 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
842 }
843  
844 # The color of $label, or of $fallback when $label is not defined
845 17 ▶sub fallback_color {
Subroutine fallback_color: called CC=2 SCAR=6.9
Pod undocumented
846 17 my($label, $fallback, $text) = @_;
847 17 ▶ $label = $fallback unless defined_color($label);
Branch: 1 branch
BranchTrueFalseTotal
unless defined_color($label) 5 12 17
848 17 md_color($label, $text);
849 }
850  
851 1798 ▶sub mark_color {
Subroutine mark_color: called CC=3 SCAR=11.0
Pod undocumented
852 1798 my($type, $text) = @_;
853 1798 my $label = "${type}_mark";
854 $label = 'emphasis_mark' unless exists $cm->{HASH}{$label}
855 1798 ▶ && $cm->{HASH}{$label} ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless exists $cm->{"HASH"}{$label} and $cm->{"HASH"}{$label} ne "" 1426 372 1798
Condition66%2/3
exists $cm->{"HASH"}{$label} and $cm->{"HASH"}{$label} ne ""
!ll&&!rl&&r
14260372
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
856 1798 md_color($label, $text);
857 }
858  
859 #
860 # Protection mechanism
861 #
862 # SGR 256 placeholders protect processed regions (inline code,
863 # comments, links) from being matched by later patterns.
864 #
865  
866 221 my @protected;
867 221 my($PS, $PE) = ("\e[256m", "\e[m"); # protect start/end markers
868 221 my $PR = qr/\e\[256m(\d+)\e\[m/; # protect restore pattern
869 221 my($OS, $OE) = ("\e]8;;", "\e\\"); # OSC 8 start/end markers
870  
871 2258 ▶sub protect {
Subroutine protect: called CC=1 SCAR=0.0
Pod undocumented
872 2258 my $text = shift;
873 2258 push @protected, $text;
874 2258 $PS . $#protected . $PE;
875 }
876  
877 982 ▶sub restore {
Subroutine restore: called CC=3 SCAR=11.0
Pod undocumented
878 982 my $s = shift;
879 982 ▶ 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 { '???' } 188 982 1170
Condition50%1/2
$protected[$1] // die("restore failed: index $1")
l!l
22580
MC/DC0%0/1
$protected[$1] // die("restore failed: index $1")
$protected[$1]
Truth table50%1/2
A
A= $protected[$1]
Aresult
11
00
880 982 $s;
881 }
882  
883 #
884 # OSC 8 hyperlink generation
885 #
886  
887 355 ▶sub osc8 {
Subroutine osc8: called CC=2 SCAR=7.0
Pod undocumented
888 355 ▶ return $_[1] unless $config->{osc8};
Branch: 1 branch
BranchTrueFalseTotal
unless $config->{"osc8"} 0 355 355
889 355 my($url, $text) = @_;
890 355 my $escaped = uri_escape_utf8($url, "^\\x20-\\x7e");
891 355 "${OS}${escaped}${OE}${text}${OS}${OE}";
892 }
893  
894 #
895 # Link text inner pattern: backtick spans, backslash escapes, normal chars
896 #
897  
898 221 my $LT = qr/(?:`[^`\n]*+`|\\.|[^`\\\n\]]++)+/;
899  
900 # Code span pattern (both single and multi-backtick).
901 # Captures: _bt (backtick delimiter), _content (code body).
902 # Used directly in inline_code step and as basis for $SKIP_CODE.
903 221 my $CODE = qr{(?x)
904 (?<_bt> `++ ) # opening backtick(s)
905 (?<_content>
906 (?: (?! \g{_bt} ) . )+? # content (not containing same-length backticks)
907 )
908 \g{_bt} # closing backtick(s) matching opener
909 };
910  
911 # Skip code spans in link/image patterns.
912 # Used as the first alternative in s{$SKIP_CODE|<link pattern>}{...}ge
913 # so that code spans are matched and skipped, preventing link/image
914 # patterns from matching inside them.
915 221 my $SKIP_CODE = qr{$CODE (*SKIP)(*FAIL)}x;
916  
917 # Delimiters of * and ** emphasis (CommonMark 0.31.2, 6.2): an opener
918 # must be left-flanking and a closer right-flanking, so that
919 # "L*=50, a*=68" is not italic. Punctuation is Unicode punctuation and
920 # symbols. An opener after $tight (neither a space nor punctuation)
921 # cannot have punctuation after it, and a closer before $tight cannot
922 # have punctuation before it.
923 #
924 # With cjk_friendly=1 the amendments of markdown-cjk-friendly apply:
925 # CJK punctuation does not count, and a CJK character is as good as a
926 # space on the other side, so that "日本語の*「強調」*です" is italic.
927 # See CLAUDE.md.
928 221 ▶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
2210
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
929 221 my $CJK = qr/(?:(?!$EMOJI)[\p{EA=W}\p{EA=F}\p{EA=H}]|\p{Hangul})/;
930  
931 229 ▶sub flanking {
Subroutine flanking: called CC=2 SCAR=6.9
Pod undocumented
932 229 my $d = quotemeta shift;
933 my($punct, $tight) = $config->{cjk_friendly}
934 229 ▶ ? (qr/(?!$CJK)[\p{P}\p{S}]/, qr/(?!$CJK)[^\s\p{P}\p{S}]/)
Branch: 1 branch
BranchTrueFalseTotal
$config->{'cjk_friendly'} ? : 2 227 229
935 : (qr/[\p{P}\p{S}]/, qr/[^\s\p{P}\p{S}]/);
936 # A link or a code span is a protect() placeholder by now; its
937 # ends stand for the punctuation that delimits it in the text.
938 229 my($ps, $pe) = (qr/\e\[256m/, qr/\e\[m/);
939 229 (qr/(?:(?<!$tight)|(?<=$pe)|(?!$d(?:$punct|$ps)))$d(?=\S)/,
940 qr/(?<=\S)(?:(?<!$punct)(?<!$pe)|(?!$d(?!$ps)$tight))$d/);
941 }
942  
943 #
944 # colorize() - the main function
945 #
946 # Receives entire file content in $_ (--begin with -G --filter).
947 # Processes all patterns with multiline regexes.
948 #
949  
950 #
951 # Pipeline step class
952 #
953  
954 221 package App::Greple::md::Step {
955 3315 ▶ sub new {
Subroutine new: called CC=1 SCAR=0.0
956 3315 my($class, %args) = @_;
957 3315 bless \%args, $class;
958 }
959 0 ▶ sub label { $_[0]->{label} }
Subroutine label: not called CC=1 SCAR=6.9
960 1755 ▶ 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"}) 819 936 1755
961 1738 ▶ sub run { $_[0]->{code}->() }
Subroutine run: called CC=1 SCAR=0.0
962 }
963  
964 3315 ▶sub Step {
Subroutine Step: called CC=1 SCAR=0.0
Pod undocumented
965 3315 my $code = pop;
966 3315 my $label = shift;
967 3315 App::Greple::md::Step->new(label => $label, code => $code);
968 }
969  
970 #
971 # Pipeline steps: Step(sub{}) = always active, Step(label => sub{}) = controllable
972 #
973  
974 # the file being shown, for the paths of its images (begin)
975 221 our $current_file;
976  
977 my %colorize = (
978  
979 117 ▶ front_matter => Step(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
980 117 ▶ my $front = front_matter($_) // return;
Condition100%2/2
front_matter($_) // (return)
l!l
6111
MC/DC100%1/1
front_matter($_) // (return)
front_matter($_)
Truth table100%2/2
A
A= front_matter($_)
Aresult
11
00
981 6 my($open, @body) = split /(?<=\n)/, $front;
982 6 my $close = pop @body;
983 6 chomp $open;
984 6 ▶ my $block = sub { fallback_color('meta_block', 'code_block', $_[0]) };
Subroutine __ANON__: called CC=1 SCAR=0.0
985 # A delimiter line is in meta_mark alone when it is defined, and
986 # otherwise in code_mark inside the block color, so that the
987 # background of the block runs over it
988 my $mark = defined_color('meta_mark')
989 10 ▶ ? sub { md_color('meta_mark', $_[0]) }
Subroutine __ANON__: called CC=1 SCAR=0.0
990 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
991 substr($_, 0, length $front) = protect(join '',
992 $mark->($open), "\n",
993 6 (map { $block->($_) } @body),
994 $mark->($close));
995 }),
996  
997 117 ▶ code_blocks => Step(sub {
Subroutine __ANON__: called CC=9 SCAR=22.0
998 # closing fence: the same character, at least as long (CommonMark)
999 117 my $block = qr{^( {0,3})((`|~)\3{2,})(.*)\n((?s:.*?))^( {0,3})(\2\3*)(\h*)$}m;
1000 # the code of all the blocks, in the colors of their languages
1001 117 my @highlight;
1002 117 ▶ if ($config->{highlight}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($config->{"highlight"}) 115 2 117
1003 115 my @code;
1004 115 ▶ while (/$block/g) {
Branch: 1 branch
BranchTrueFalseTotal
if (/$block/gu) 240 115 355
1005 240 my($info, $body) = ($4, $5);
1006 240 push @code, [ $info, $body ];
1007 }
1008 115 @highlight = highlight_code(@code);
1009 }
1010 s{$block}{
1011 242 my($oi, $fence, $lang, $body, $ci, $close, $trail) = ($1, $2, $4, $5, $6, $7, $8);
1012 242 ▶ my @label = $config->{highlight} ? code_labels($lang, $body) : ();
Branch: 1 branch
BranchTrueFalseTotal
$config->{'highlight'} ? : 240 2 242
1013 242 ▶ $body = shift(@highlight) // $body;
Condition66%2/3
shift @highlight // $body
l!l&&r!l&&!r
152270
MC/DC0%0/2
shift @highlight // $body
shift @highlight $body
Truth table66%2/3
A // B
A= shift @highlightB= $body
ABresult
1X1
011
000
1014 242 my $result = md_color('code_mark', "$oi$fence");
1015 242 ▶ $result .= md_color('code_info', $lang) if length($lang);
Branch: 1 branch
BranchTrueFalseTotal
if length $lang 235 7 242
1016 242 $result .= "\n";
1017 242 ▶ if (length($body)) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $body) 241 1 242
1018 $result .= join '', map {
1019 241 my $label = shift @label;
1020 736 ▶ !defined $label ? md_color('code_block', $_)
Branch: 2 branches
BranchTrueFalseTotal
!defined($label) ? : 727 9 736
$label eq '' ? : 3 6 9
1021 : $label eq '' ? $_
1022 : fallback_color("code_$label", 'code_block', $_);
1023 } split /(?<=\n)/, $body;
1024 }
1025 242 $result .= md_color('code_mark', "$ci$close") . $trail;
1026 242 protect($result)
1027 117 }mge;
1028 }),
1029  
1030 117 ▶ comments => Step(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1031 117 s/(^<!--(?![->])(?s:.*?)-->)/protect(md_color('comment', $1))/mge;
1032 }),
1033  
1034 117 ▶ image_links => Step(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1035 117 s{$SKIP_CODE|\[!\[(?<text>$LT)\]\((?<img>[^)\n]+)\)\]\(<?(?<url>[^>)\s\n]+)>?\)}{
1036 protect(
1037 osc8($+{img}, md_color('image_link', "!"))
1038 42 . osc8($+{url}, mark_color('link', "[") . md_color('image_link', $+{text}) . mark_color('link', "]"))
1039 )
1040 }ge;
1041 }),
1042  
1043 # A line which is an image and nothing else is followed by the rows
1044 # of the image (Text::ANSI::Image, the kitty method). The rows are
1045 # protected, so that no other step takes them, and are joined with
1046 # the line by GS when they are to be kept in one pane (intact=image),
1047 # as the rows of a table are joined by US.
1048 117 ▶ image_blocks => Step(sub {
Subroutine __ANON__: called CC=17 SCAR=28.5
1049 117 ▶ my @types = split /:/, $config->{image_types} // '';
Condition50%1/2
$config->{"image_types"} // ""
l!l
1170
MC/DC0%0/1
$config->{"image_types"} // ""
$config->{"image_types"}
Truth table50%1/2
A
A= $config->{"image_types"}
Aresult
11
00
1050 117 ▶ @types or return;
Branch: 1 branch
BranchTrueFalseTotal
@types or return 15 102 117
1051 my $img = Text::ANSI::Image->new(
1052 method => 'kitty',
1053 types => \@types,
1054 term => $config->{image_term},
1055 tty => $config->{image_tty} || '/dev/tty',
1056 osc => $config->{image_osc},
1057 15 ▶ );
Condition100%2/2
$config->{'image_tty'} || '/dev/tty'
l!l
141
MC/DC100%1/1
$config->{'image_tty'} || '/dev/tty'
$config->{'image_tty'}
Truth table100%2/2
A
A= $config->{'image_tty'}
Aresult
11
00
1058 15 my @added;
1059 15 ▶ my $dir = defined $current_file && $current_file =~ m{^(.*)/} ? $1 : ".";
Branch: 1 branch
BranchTrueFalseTotal
defined $App::Greple::md::current_file && $App::Greple::md::current_file =~ m[^(.*)/]u ? : 15 0 15
Condition33%1/3
defined $App::Greple::md::current_file and $App::Greple::md::current_file =~ m[^(.*)/]u
!ll&&!rl&&r
0015
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
1060 15 ▶ my $width = $config->{fold} ? $config->{fold_width} : 0;
Branch: 1 branch
BranchTrueFalseTotal
$config->{'fold'} ? : 2 13 15
1061 # A Markdown image, alone or as a link, or an HTML <img> with
1062 # only <p>, <div>, <a> or <center> around it (README files made
1063 # from POD have one for the logo).
1064 15 s{^(?<line>\h*+
1065 (?: \[?!\[(?:$LT)?\]\(<?(?<url>[^>)\s\n]+)>?\)(?:\]\([^)\n]*\))?
1066 | (?:<(?:p|div|a|center)\b[^>\n]*>\h*)*
1067 <img\b(?<attr>[^>\n]*)>
1068 (?:\h*</(?:p|div|a|center)>)*
1069 )\h*+)\n
1070 }{
1071 # the line number, before any other match is made
1072 24 my $at = 1 + (substr($_, 0, $-[0]) =~ tr/\n//);
1073 24 my($line, $url, $attr) = @+{qw(line url attr)};
1074 24 ▶ if (defined $attr) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $attr) 3 21 24
1075 3 ($url) = $attr =~ m{\bsrc\h*=\h*(?|"([^"]*)"|'([^']*)'|([^\s"'>]+))}i;
1076 }
1077 24 ▶ my $file = defined $url ? local_path($url, $dir) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $url ? : 24 0 24
1078 my @rows = $file ? $img->rows($file,
1079 width => $width,
1080 rows => $config->{image_rows},
1081 24 ▶ ) : ();
Branch: 1 branch
BranchTrueFalseTotal
$file ? : 19 5 24
1082 24 ▶ if (@rows) {
Branch: 1 branch
BranchTrueFalseTotal
if (@rows) { } 14 10 24
1083 # the line of a shown image is markup only, the Markdown
1084 # or the HTML tags: it is put as it is in code_info, as the
1085 # info string of a code fence is
1086 14 my($indent, $tags) = $line =~ /^(\h*)(.*?)\h*$/;
1087 14 $line = $indent . protect(md_color('code_info', $tags));
1088 14 my $keep = intact("image");
1089 # kept in one pane, the line of the image goes with its rows
1090 14 ▶ push @added, [ $at, $keep ? 0 : scalar @rows ];
Branch: 1 branch
BranchTrueFalseTotal
$keep ? : 1 13 14
1091 14 ▶ my $sep = $keep ? "\x1D" : "\n";
Branch: 1 branch
BranchTrueFalseTotal
$keep ? : 1 13 14
1092 14 $line . $sep . protect(join $sep, @rows) . "\n";
1093 } else {
1094 10 "$line\n";
1095 }
1096 }mgex;
1097 15 $img->flush;
1098 # the lines joined by refill() below an image go down
1099 15 for my $r (@App::Greple::md::refill_lines) {
1100 3 my $shift = 0;
1101 3 ▶ $_->[0] < $r->[0] and $shift += $_->[1] for @added;
Branch: 1 branch
BranchTrueFalseTotal
$_->[0] < $r->[0] and $shift += $_->[1] 2 1 3
1102 3 $_ += $shift for @$r;
1103 }
1104 }),
1105  
1106 117 ▶ images => Step(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1107 117 s{$SKIP_CODE|!\[(?<text>$LT)\]\(<?(?<url>[^>)\s\n]+)>?\)}{
1108 57 protect(osc8($+{url}, md_color('image', "!") . mark_color('link', "[") . md_color('image', $+{text}) . mark_color('link', "]")))
1109 }ge;
1110 }),
1111  
1112 117 ▶ links => Step(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1113 117 s{$SKIP_CODE|(?<![!\e])\[(?<text>$LT)\]\(<?(?<url>[^>)\s\n]+)>?\)}{
1114 214 protect(osc8($+{url}, mark_color('link', "[") . md_color('link', $+{text}) . mark_color('link', "]")))
1115 }ge;
1116 }),
1117  
1118 115 ▶ inline_code => Step(code_inline => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1119 115 state $to = $config->{tick_open};
1120 115 state $tc = $config->{tick_close};
1121 115 s{$CODE}{
1122 554 my $content = $+{_content};
1123 # Strip optional leading/trailing space for multi-backtick (CommonMark)
1124 554 ▶ $content =~ s/^ (.+) $/$1/ if length($+{_bt}) >= 2;
Branch: 1 branch
BranchTrueFalseTotal
if length $+{"_bt"} >= 2 80 474 554
1125 554 protect(md_color('code_tick', $to) . md_color('code_inline', $content) . md_color('code_tick', $tc))
1126 }ge;
1127 }),
1128  
1129 115 ▶ headings => Step(header => sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
1130 115 my $hashed = $config->{hashed};
1131 115 for my $n (reverse 1..6) {
1132 690 ▶ next unless active("h$n");
Branch: 1 branch
BranchTrueFalseTotal
unless active("h$n") 0 690 690
1133 690 my $hdr = '#' x $n;
1134 # up to 3 spaces of indentation; empty headings ("#") too (CommonMark)
1135 690 s{^( {0,3}$hdr(?:\h+.*)?)$}{
1136 865 my $line = $1;
1137 $line .= " $hdr"
1138 865 ▶ if $hashed->{"h$n"} && $line !~ /\#$/;
Branch: 1 branch
BranchTrueFalseTotal
if $$hashed{"h$n"} and not $line =~ /\#$/u 130 735 865
Condition100%3/3
$$hashed{"h$n"} and not $line =~ /\#$/u
!ll&&!rl&&r
70926130
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
1139 865 protect(md_color("h$n", restore($line)));
1140 }mge;
1141 }
1142 }),
1143  
1144 115 ▶ horizontal_rules => Step(horizontal_rule => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1145 115 s/^([ ]{0,3}(?:[-*_][ ]*){3,})$/protect(md_color('horizontal_rule', $1))/mge;
1146 }),
1147  
1148 115 ▶ bold_italic => Step(bold => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1149 115 s{$SKIP_CODE|(?<!\\)(?<m>\*\*\*)(?<t>.*?)(?<!\\)\g{m}}{
1150 40 protect(mark_color('bold', $+{m}) . md_color('bold', md_color('italic', $+{t})) . mark_color('bold', $+{m}))
1151 }gep;
1152 115 s{$SKIP_CODE|(?<![\\\w])(?<m>___)(?<t>.*?)(?<!\\)\g{m}(?!\w)}{
1153 40 protect(mark_color('bold', $+{m}) . md_color('bold', md_color('italic', $+{t})) . mark_color('bold', $+{m}))
1154 }gep;
1155 }),
1156  
1157 115 ▶ bold => Step(bold => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1158 115 my($open, $close) = flanking('**');
1159 # no opener inside, so that a closer pairs with the nearest opener
1160 115 s{$SKIP_CODE|(?<!\\)(?<m>$open)(?<t>(?:(?!$open).)*?)(?<!\\)$close}{
1161 mark_color('bold', $+{m}) . md_color('bold', $+{t}) . mark_color('bold', $+{m})
1162 292 }gep;
1163 115 s{$SKIP_CODE|(?<![\\\w])(?<m>__)(?<t>.*?)(?<!\\)\g{m}(?!\w)}{
1164 mark_color('bold', $+{m}) . md_color('bold', $+{t}) . mark_color('bold', $+{m})
1165 40 }gep;
1166 }),
1167  
1168 114 ▶ italic => Step(italic => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1169 114 my($open, $close) = flanking('*');
1170 114 s{$SKIP_CODE|(?<![\\\w])(?<m>_)(?<t>(?:(?!_).)+)(?<!\\)\g{m}(?!\w)}{
1171 mark_color('italic', $+{m}) . md_color('italic', $+{t}) . mark_color('italic', $+{m})
1172 78 }gep;
1173 114 s{$SKIP_CODE|(?<![\\*])(?<m>$open)(?<t>(?:(?!\*).)+)(?<!\\)$close(?!\*)}{
1174 mark_color('italic', $+{m}) . md_color('italic', $+{t}) . mark_color('italic', $+{m})
1175 49 }gep;
1176 }),
1177  
1178 115 ▶ strike => Step(strike => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1179 115 s{$SKIP_CODE|(?<!\\)(?<m>~~)(?<t>.+?)(?<!\\)\g{m}}{
1180 mark_color('strike', $+{m}) . md_color('strike', $+{t}) . mark_color('strike', $+{m})
1181 40 }gep;
1182 }),
1183  
1184 115 ▶ blockquotes => Step(blockquote => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1185 115 s/^( {0,3})((?:>\h?)+)(.*)$/$1 . md_color('blockquote', $2) . $3/mge;
1186 221 }),
1187 );
1188  
1189 #
1190 # Pipeline configuration
1191 #
1192  
1193 # Always before headings (protection + links)
1194 221 my @protect_steps = qw(front_matter code_blocks comments image_blocks image_links images links);
1195  
1196 # Inline steps controlled by heading_markup
1197 221 my @inline_steps = qw(inline_code horizontal_rules bold_italic bold italic strike);
1198  
1199 # Always last
1200 221 my @final_steps = qw(blockquotes);
1201  
1202 117 ▶sub build_pipeline {
Subroutine build_pipeline: called CC=4 SCAR=25.8
Pod undocumented
1203 117 my $hm = $config->{heading_markup};
1204  
1205 # heading_markup disabled: headings before all inline steps
1206 117 ▶ if (!$hm) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($hm) 117 0 117
1207 117 return (@protect_steps, 'headings', @inline_steps, @final_steps);
1208 }
1209  
1210 # "all" or "1": all inline steps before headings
1211 0 my %before;
1212 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
1213 0 %before = map { $_ => 1 } @inline_steps;
1214 } else {
1215 # "bold:italic" → collect word tokens, filter to valid inline steps
1216 0 my %valid = map { $_ => 1 } @inline_steps;
1217 0 %before = map { $_ => 1 } grep { $valid{$_} } ($hm =~ /(\w+)/g);
1218 }
1219  
1220 0 my @before_h = grep { $before{$_} } @inline_steps;
1221 0 my @after_h = grep { !$before{$_} } @inline_steps;
1222  
1223 0 return (@protect_steps, @before_h, 'headings', @after_h, @final_steps);
1224 }
1225  
1226 117 ▶sub colorize {
Subroutine colorize: called CC=3 SCAR=11.0
Pod undocumented
1227 117 setup_colors();
1228 117 @protected = ();
1229  
1230 117 for my $name (build_pipeline()) {
1231 1755 my $step = $colorize{$name};
1232 1755 ▶ $step->run if $step->active;
Branch: 1 branch
BranchTrueFalseTotal
if $step->active 1738 17 1755
1233 }
1234  
1235 117 $_ = restore($_);
1236 117 $_;
1237 }
1238  
1239 #
1240 # Table formatting
1241 #
1242  
1243 # What joins the lines of a part kept intact (config intact) into one
1244 # line, as ansicolumn --intact takes it
1245 221 my $INTACT_SEP = "\x1F";
1246 # What joins lines kept in one pane, the rows of an image or the lines
1247 # of a row of a table
1248 221 my $GROUP_SEP = "\x1D";
1249  
1250 # Whether the part ("table") is kept intact
1251 632 ▶sub intact {
Subroutine intact: called CC=2 SCAR=7.1
Pod undocumented
1252 632 my $part = shift;
1253 632 ▶ grep { $_ eq $part } split /:/, $config->{intact} // '';
Condition50%1/2
$config->{"intact"} // ""
l!l
6320
MC/DC0%0/1
$config->{"intact"} // ""
$config->{"intact"}
Truth table50%1/2
A
A= $config->{"intact"}
Aresult
11
00
1254 }
1255  
1256 # Regions of formatted tables, used by --fold-by as --exclude so that
1257 # ansifold does not fold them again: three or more lines that contain a
1258 # column separator, in a block that has a separator row. A line may
1259 # start with a border or rule character, a dash, whitespace, or one of
1260 # the configured marks (a wrapped first column's continuation line starts
1261 # with the wrap mark, and its body rows with the cell mark), so the
1262 # pattern is built from the config at run time rather than in __DATA__.
1263 74 ▶sub table_regions {
Subroutine table_regions: called CC=2 SCAR=6.9
Pod undocumented
1264 74 my %arg = @_;
1265 74 delete $arg{&FILELABEL};
1266 39 my $marks = join '', map { quotemeta substr $_, 0, 1 }
1267 74 grep { length } @{$config}{qw(table_wrap_mark table_cell_mark)};
1268 74 my $bar = "\x{2502}|"; # column separator │ |
1269 74 my $cross = "\x{253C}"; # rule crossing ┼
1270 74 my $rule = "\x{2500}\x{251C}\x{2524}"; # rule line ─ ├ ┤
1271 74 my $row = qr{
1272 ^ [ $bar \x{251C} \x{2500} $marks \h - ] # border, rule, mark, pad, or dash
1273 [^\n]* [ $bar $cross ] [^\n]* \n # ... with a separator somewhere
1274 }xxm;
1275 74 my $sep = qr{ (?= [^\n]* [ $cross | ] ) [ $rule $cross | - ]+ \n }xx;
1276 # a table kept intact is a line with UNIT SEPARATORs, or GROUP
1277 # SEPARATORs alone when it has one row, which come from nowhere else
1278 # but the rows of an image: remove_controls() takes them out of the
1279 # text
1280 74 ▶ return match_regions(pattern => qr/^[^\n]*[$INTACT_SEP$GROUP_SEP][^\n]*\n/m) if intact('table');
Branch: 1 branch
BranchTrueFalseTotal
if intact("table") 6 68 74
1281 68 match_regions(pattern => qr/ (?= (?:$row)*? $sep ) (?:$row){3,} /x);
1282 }
1283  
1284 #
1285 # Paragraph refill
1286 #
1287  
1288 # Join the lines of one paragraph (or list item, quote, definition)
1289 # into a single line. The rules are those of ansifold's fill_up: the
1290 # line break after a fullwidth punctuation character and between two
1291 # characters of a script written without spaces (CJK) is simply
1292 # removed, any other becomes one space. A line is left as it is, as
1293 # the start of a new line, when the line before it ends in a hard
1294 # break (two or more spaces, or a backslash), or when it starts with
1295 # a list marker, is a horizontal rule, which pandoc may report as
1296 # part of the paragraph (a "#." list, "Text\n***"), or when either
1297 # line looks like a table row: GFM does not let a table interrupt a
1298 # paragraph, but format_table takes three such lines as a table.
1299 # From the second line on, up to $depth quote markers and the
1300 # indentation are removed before joining. A CR before the line
1301 # break (CRLF file) goes with the line break.
1302 #
1303 # The character properties are defined as subroutines in App::ansifold
1304 # and looked up when the pattern is compiled, so the patterns are
1305 # built here, after the module is loaded, not at compile time.
1306 90 ▶sub refill_block {
Subroutine refill_block: called CC=13 SCAR=25.7
Pod undocumented
1307 90 my($lines, $depth) = @_;
1308 90 state $punct = do {
1309 24 require App::ansifold;
1310 24 my $p = "App::ansifold::InFullwidthPunctuation";
1311 24 qr/\p{$p}/;
1312 };
1313 90 state $concat = do {
1314 24 my $p = "App::ansifold::InConcatScript";
1315 24 qr/\p{$p}/;
1316 };
1317 90 my $prefix = qr/^\h*(?:>\h?){0,$depth}\h*/;
1318 90 my $marker = qr/^\h*(?:[*+-]|(?:\d+|#)[.)])\h+/;
1319 90 my $hr = qr/^ {0,3}(?:[-*_][ ]*){3,}\r?$/;
1320 90 my $row = qr/^ {0,3}\|.+\|\h*\r?$/;
1321 90 my $def = qr/^\h*:\h/;
1322 90 my $note = qr/$prefix\[\^[^\]\s]+\]:/;
1323 90 my $hard = qr/(?:(?<!\\)(?:\\\\)*\\|(?<! ) {2,})\r?$/; # odd number of backslashes, or two spaces (the lookbehinds keep it linear)
1324 90 my @out;
1325 90 for my $line (@$lines) {
1326 229 ▶ 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) 157 72 229
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
154372
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
151375
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
146578
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
145183
not @out or $out[-1] =~ /$hard/u or $out[-1] =~ /$row/u or $line =~ /$marker/u
l!l&&r!l&&!r
144184
not @out or $out[-1] =~ /$hard/u or $out[-1] =~ /$row/u
l!l&&r!l&&!r
964885
not @out or $out[-1] =~ /$hard/u
l!l&&r!l&&!r
906133
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
1327 or $line =~ $marker or $line =~ $hr or $line =~ $row
1328 or $line =~ $def or $line =~ $note) {
1329 157 push @out, $line;
1330 157 next;
1331 }
1332 72 my $text = $line =~ s/$prefix//r;
1333 72 $out[-1] =~ s/\r\z//;
1334 72 ▶ if ($out[-1] =~ /$punct$/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($out[-1] =~ /$punct$/u) { } 1 71 72
elsif ($out[-1] =~ /$concat$/u and $text =~ /^$concat/u) { } 2 69 71
1335 1 $out[-1] .= $text;
1336 ▶ } elsif ($out[-1] =~ /$concat$/ and $text =~ /^$concat/) {
Condition66%2/3
$out[-1] =~ /$concat$/u and $text =~ /^$concat/u
!ll&&!rl&&r
6902
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
1337 2 $out[-1] .= $text;
1338 } else {
1339 69 $out[-1] =~ s/ +$//;
1340 69 $text =~ s/^ +//;
1341 69 $out[-1] .= " $text";
1342 }
1343 }
1344 90 @out;
1345 }
1346  
1347 # The line ranges that refill() joined, as [first, last] in the text
1348 # after joining, and the formatted tables, as [first line, lines added,
1349 # lines before formatting],
1350 # both for the current file. refill_regions() turns them into the
1351 # regions that --fold-by folds.
1352 221 our @refill_lines;
1353 221 our @table_shift;
1354  
1355 # Front matter at the top of the text: TOML (+++ ... +++) or YAML
1356 # (--- ... --- or ...). It is not part of CommonMark: pandoc takes TOML
1357 # as a paragraph and YAML as metadata, Markdown::Perl takes YAML as
1358 # metadata, and libcmark takes YAML as paragraphs and list items. As
1359 # in pandoc, a blank line right after the opening --- makes it a rule.
1360 # Returns the front matter without the line break after its last line,
1361 # or an empty list. $front_lines is its number of lines, set by
1362 # begin() before the text is changed, for refill and the fold regions.
1363 221 our $front_lines = 0;
1364 330 ▶sub front_matter {
Subroutine front_matter: called CC=3 SCAR=11.0
Pod undocumented
1365 330 ▶ $config->{front_matter} or return;
Branch: 1 branch
BranchTrueFalseTotal
$config->{"front_matter"} or return 327 3 330
1366 327 ▶ $_[0] =~ m{
Branch: 1 branch
BranchTrueFalseTotal
$_[0] =~ / \A (?: \+\+\+ \r?\n (?:[^\n]*\n)*? \+\+\+ | --- \r?\n (?!\r?\n) (?:[^\n]*\n)*? (?:---|\.\.\.) ) \h* \r? (?=\n|\z) /pux ? : 17 310 327
1367 \A (?: \+\+\+ \r?\n (?:[^\n]*\n)*? \+\+\+
1368 | --- \r?\n (?!\r?\n) (?:[^\n]*\n)*? (?:---|\.\.\.) )
1369 \h* \r? (?=\n|\z)
1370 }px ? ${^MATCH} : ();
1371 }
1372  
1373 # The region of the front matter, used by --fold-by as --exclude. The
1374 # text is colored by then, so the region is found by its line count.
1375 74 ▶sub front_matter_region {
Subroutine front_matter_region: called CC=4 SCAR=14.3
Pod undocumented
1376 74 my %arg = @_;
1377 74 delete $arg{&FILELABEL};
1378 74 ▶ $front_lines or return ();
Branch: 1 branch
BranchTrueFalseTotal
$App::Greple::md::front_lines or return () 1 73 74
1379 1 my $pos = 0;
1380 1 for (1 .. $front_lines) {
1381 1 $pos = index($_, "\n", $pos);
1382 1 ▶ $pos < 0 and return [ 0, length ];
Branch: 1 branch
BranchTrueFalseTotal
$pos < 0 and return [0, length $_] 1 0 1
1383 0 $pos++;
1384 }
1385 0 [ 0, $pos ];
1386 }
1387  
1388 # Join the lines of every paragraph (Para) and tight list item or
1389 # definition (Plain) in $_, from the bottom up so that the line numbers
1390 # of the blocks above stay valid, and remember where the joined lines
1391 # are in the result.
1392 24 ▶sub refill {
Subroutine refill: called CC=7 SCAR=19.5
Pod undocumented
1393 24 @refill_lines = ();
1394 24 my @lines = split /\n/, $_, -1;
1395 24 my @done;
1396 24 my $limit = @lines + 1;
1397 24 my $front = $front_lines;
1398 24 for my $b (sort { $b->{first} <=> $a->{first} }
1399 66 ▶ grep { $_->{type} eq 'Para' or $_->{type} eq 'Plain' }
Condition33%1/3
$_->{'type'} eq 'Para' || $_->{'type'} eq 'Plain'
l!l&&r!l&&!r
6600
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
1400 blocks($_, parser => $config->{refill_parser})) {
1401 66 my($first, $last) = @{$b}{qw(first last)};
1402 # libcmark runs a paragraph on past a closing "..."
1403 66 ▶ $first = $front + 1 if $first <= $front;
Branch: 1 branch
BranchTrueFalseTotal
if $first <= $front 1 65 66
1404 66 ▶ next if $last < $first or $last >= $limit;
Branch: 1 branch
BranchTrueFalseTotal
if $last < $first or $last >= $limit 1 65 66
Condition66%2/3
$last < $first or $last >= $limit
l!l&&r!l&&!r
1065
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
1405 65 $limit = $first;
1406 65 my @joined = refill_block([ @lines[$first-1 .. $last-1] ], $b->{depth});
1407 65 splice @lines, $first-1, $last-$first+1, @joined;
1408 65 unshift @done, [ $first, scalar @joined, $last - $first + 1 - @joined ];
1409 }
1410 24 my $shift = 0;
1411 24 for my $d (@done) {
1412 65 my($first, $count, $removed) = @$d;
1413 65 push @refill_lines, [ $first - $shift, $first - $shift + $count - 1 ];
1414 65 $shift += $removed;
1415 }
1416 24 $_ = join "\n", @lines;
1417 }
1418  
1419 # The lines that refill() joined, one region per line including its
1420 # newline, for --fold-by. The text has been through colorize(), which
1421 # keeps the number of lines, and format_table(), which does not: the
1422 # tables above a range have added the lines in @table_shift.
1423 74 ▶sub refill_regions {
Subroutine refill_regions: called CC=13 SCAR=26.0
Pod undocumented
1424 74 my %arg = @_;
1425 74 delete $arg{&FILELABEL};
1426 74 ▶ return () unless @refill_lines;
Branch: 1 branch
BranchTrueFalseTotal
unless @App::Greple::md::refill_lines 57 17 74
1427 17 my @start = (0);
1428 17 my $pos = 0;
1429 17 ▶ while (($pos = index($_, "\n", $pos)) >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (($pos = index($_, " ", $pos)) >= 0) 133 17 150
1430 133 push @start, ++$pos;
1431 }
1432 17 my $end = length $_;
1433 17 my @regions;
1434 17 for my $range (@refill_lines) {
1435 46 LINE: for my $line ($range->[0] .. $range->[1]) {
1436 86 my $shift = 0;
1437 86 for my $t (@table_shift) {
1438 # A line of a table is not folded. A parser without
1439 # tables (libcmark) reports a table as a paragraph, and
1440 # its lines after the first are not lines any more when
1441 # the table is joined into one (intact=table).
1442 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
1443 18 ▶ $shift += $t->[1] if $t->[0] < $line;
Branch: 1 branch
BranchTrueFalseTotal
if $t->[0] < $line 10 8 18
1444 }
1445 41 my $n = $line + $shift;
1446 41 ▶ last if $n > @start;
Branch: 1 branch
BranchTrueFalseTotal
if $n > @start 0 41 41
1447 # a line which holds the rows of an image is not folded
1448 41 ▶ 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 41 41
Condition33%1/3
$start[$n] // $end
l!l&&r!l&&!r
4100
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
1449 41 ▶ push @regions, [ $start[$n-1], $start[$n] // $end ];
Condition33%1/3
$start[$n] // $end
l!l&&r!l&&!r
4100
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
1450 }
1451 }
1452 17 @regions;
1453 }
1454  
1455  
1456 # What a file must not send to the terminal: everything but colors, and the
1457 # mark of protect(), which would bring back or look for protected text.
1458 221 my $STRING = qr{
1459 (?: \e [PX^_] | [\x90\x98\x9e\x9f] ) # DCS, SOS, PM, APC
1460 (?: [^\x00-\x07\x0e-\x1f\x7f-\x9f]*+ (?: \e\\ | \x9c | \a ) )?
1461 }x;
1462 221 my $CONTROLS = qr{
1463 \e \[ (?! 256m ) [0-9:;]* m (*SKIP)(*FAIL)
1464 |
1465 $osc_re
1466 |
1467 $STRING
1468 |
1469 $csi_re
1470 |
1471 \e [\x20-\x2f]* [\x30-\x7e]
1472 |
1473 [\x00-\x08\x0b\x0e-\x1f\x7f-\x9f]
1474 }x;
1475  
1476 242 ▶sub remove_controls {
Subroutine remove_controls: called CC=1 SCAR=0.0
Pod undocumented
1477 242 s/$CONTROLS//g;
1478 }
1479  
1480 # Find the function of a --begin option and load its package, so that a
1481 # module does not have to be given with -M ahead of this one. A name without
1482 # a package is looked for in main, and then as the function name of the
1483 # module App::Greple::md::name. Returns the option with the full name. A
1484 # function that does not exist is only reported, and the text is shown
1485 # without it; a module that exists and does not compile is an error.
1486 21 ▶sub resolve_function {
Subroutine resolve_function: called CC=6 SCAR=17.9
Pod undocumented
1487 21 my $spec = shift;
1488 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
1489 15 my($name, $arg) = @+{qw(name arg)};
1490 15 ▶ my @candidate = $name =~ /::/ ? $name : ("main::$name", "App::Greple::md::${name}::$name");
Branch: 1 branch
BranchTrueFalseTotal
$name =~ /::/u ? : 8 7 15
1491 221 ▶ no strict q(refs);
Subroutine BEGIN: called CC=1 SCAR=0.0
1492 15 for my $func (@candidate) {
1493 21 ▶ load_package($func =~ s/::\w+$//r) unless defined &$func;
Branch: 1 branch
BranchTrueFalseTotal
unless defined &$func 19 2 21
1494 18 ▶ return "&$func$arg" if defined &$func;
Branch: 1 branch
BranchTrueFalseTotal
if defined &$func 6 12 18
1495 }
1496 6 warn "--begin: $name: function not found\n";
1497 6 return;
1498 }
1499  
1500 19 ▶sub load_package {
Subroutine load_package: called CC=4 SCAR=13.9
Pod undocumented
1501 19 my $package = shift;
1502 19 ▶ return if $package eq q(main);
Branch: 1 branch
BranchTrueFalseTotal
if $package eq "main" 7 12 19
1503 12 my $file = $package =~ s{::}{/}gr . q(.pm);
1504 12 ▶ return if eval { require $file; 1 };
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { require $file; 1 } } 5 7 12
1505 7 ▶ die $@ unless $@ =~ /^Can't locate \Q$file\E /;
Branch: 1 branch
BranchTrueFalseTotal
unless $@ =~ /^Can't locate \Q$file\E /u 3 4 7
1506 }
1507  
1508 # The functions of --begin, parsed once. The names belong to main, as
1509 # with the --begin of greple.
1510 217 ▶sub begin_functions {
Subroutine begin_functions: called CC=3 SCAR=11.0
Pod undocumented
1511 state $func = [ map {
1512 217 ▶ 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
1513 21 my $spec = resolve_function($_);
1514 18 ▶ defined $spec ? parse_func({ PACKAGE => 'main' }, $spec) : ();
Branch: 1 branch
BranchTrueFalseTotal
defined $spec ? : 12 6 18
1515 } @opt_begin ];
1516 213 @$func;
1517 }
1518  
1519 217 ▶sub begin {
Subroutine begin: called CC=7 SCAR=19.5
Pod undocumented
1520 217 remove_controls();
1521 217 $current_file = { @_ }->{&FILELABEL};
1522 217 @refill_lines = @table_shift = ();
1523 217 for my $func (begin_functions()) {
1524 14 $func->call(@_);
1525 }
1526 213 ▶ $front_lines = do { my $f = front_matter($_); defined $f ? ($f =~ tr/\n//) + 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
defined $f ? : 11 202 213
1527 213 ▶ refill() if $config->{refill};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"refill"} 24 189 213
1528 213 ▶ mark_line_breaks() if $config->{table};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"table"} 196 17 213
1529 213 ▶ colorize() if $config->{colorize};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"colorize"} 117 96 213
1530 213 ▶ format_table() if $config->{table};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"table"} 196 17 213
1531 }
1532  
1533 # A <br> in a table row breaks the cell: a LINE SEPARATOR (U+2028)
1534 # is put after it, which ansicolumn takes as a line break in a cell.
1535 # The <br> stays, as the text is shown as written. It is done before
1536 # colorize(), while a code span still has its backticks: a <br> in a
1537 # code span, and an escaped one (\<br>), break nothing, nor does one at
1538 # the end of a cell, which would leave an empty line. The lines are
1539 # those format_table() takes as a table; a separator left in lines it
1540 # does not format after all (in a code block, say) is taken out there.
1541 196 ▶sub mark_line_breaks {
Subroutine mark_line_breaks: called CC=1 SCAR=0.0
Pod undocumented
1542 196 s{(^ {0,3}\|.+\|\h*\n){3,}}{
1543 272 ${^MATCH} =~ s{$CODE(*SKIP)(*FAIL)|(?<!\\)<br\h*/?>\K(?!\h*\|)}{\x{2028}}gir
1544 }mgep;
1545 }
1546  
1547 196 ▶sub format_table {
Subroutine format_table: called CC=27 SCAR=33.0
Pod undocumented
1548 # lattice (or pipe) has column separators. 3line and simple have
1549 # none and a header rule per column: 3line adds a full-width rule
1550 # above and below, simple the header rule below. They are formatted
1551 # as in rule mode and the separators are blanked.
1552 196 my $style = $config->{table_style};
1553 196 ▶ my $open = $style eq '3line' || $style eq 'simple';
Condition100%3/3
$style eq '3line' || $style eq 'simple'
l!l&&r!l&&!r
109177
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
1554 196 ▶ my $sep = ($config->{rule} || $open) ? "\x{2502}" : '|'; # │ or |
Branch: 1 branch
BranchTrueFalseTotal
$config->{'rule'} || $open ? : 195 1 196
Condition100%3/3
$config->{"rule"} or $open
l!l&&r!l&&!r
19321
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
1555  
1556 # A row may have spaces after the last pipe (GFM ignores them); they
1557 # are allowed in the block and removed, so that every row ends in
1558 # the same column for ansicolumn.
1559 196 s{(^ {0,3}\|.+\|\h*\n){3,}}{
1560 # The line of the table and the number of its lines, taken
1561 # before any other match is made: one made below would give
1562 # its own ${^MATCH} and $-[0].
1563 272 my $line = 1 + (substr($_, 0, $-[0]) =~ tr/\n//);
1564 272 my $lines = ${^MATCH} =~ tr/\n//;
1565 272 my $block = ${^MATCH} =~ s/\h+$//mgr;
1566 # a <br> which breaks a cell (see mark_line_breaks) has the
1567 # color of br_mark, which the nomark theme makes empty
1568 14 $block =~ s{<br\h*/?>(?=\x{2028})}{mark_color('br', ${^MATCH})}giep
1569 272 ▶ if $config->{colorize};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"colorize"} 167 105 272
1570 272 my($right, $center) = parse_separator(\$block);
1571 272 my @sep_opt;
1572 # An escaped pipe (\|) is not a column separator (GFM). It is
1573 # left as written: backslash escapes are not processed yet.
1574 272 ▶ if ($config->{table_trim}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($config->{'table_trim'}) { } 267 5 272
1575 # A cell has a space at its left, where the marks are put,
1576 # and table_gap columns to that place of the next column:
1577 # the last of them is the column separator (a space in
1578 # 3line and simple). With table_gap of 2 or more, the
1579 # spaces at the right end go when the table does not fit
1580 # the width with them (ansicolumn 1.70).
1581 267 ▶ my $pad = ' ' x (($config->{table_gap} || 1) - 1);
Condition50%1/2
$config->{'table_gap'} || 1
l!l
2670
MC/DC0%0/1
$config->{'table_gap'} || 1
$config->{'table_gap'}
Truth table50%1/2
A
A= $config->{'table_gap'}
Aresult
11
00
1582 267 @sep_opt = ('-rs', '\s*(?<!\\\\)\|\s*', "--item-format= %s$pad", '--table-remove=1,-0', '--padding');
1583 } else {
1584 5 $_++ for @$right, @$center;
1585 5 @sep_opt = ('-rs', '(?<!\\\\)\|');
1586 }
1587 272 ▶ my @align = (
Branch: 2 branches
BranchTrueFalseTotal
@$right ? : 47 225 272
@$center ? : 47 225 272
1588 @$right ? ('--table-right=' . join(',', @$right)) : (),
1589 @$center ? ('--table-center=' . join(',', @$center)) : (),
1590 );
1591 # Fit table into table_width and/or per-column widths (table_cell).
1592 # table_cell entries are colon separated because comma separates
1593 # config parameters; non-trim mode has a phantom first column.
1594 272 my @fit;
1595 272 ▶ if ($config->{table_width} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($config->{"table_width"} > 0) 138 134 272
1596 138 push @fit, '-w', $config->{table_width};
1597 }
1598 272 ▶ if ((my $cell = $config->{table_cell}) ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ((my $cell = $config->{"table_cell"}) ne "") 3 269 272
1599 3 $cell =~ tr/:/,/;
1600 3 ▶ $cell = "0,$cell" unless $config->{table_trim};
Branch: 1 branch
BranchTrueFalseTotal
unless $config->{"table_trim"} 1 2 3
1601 3 push @fit, '--cell', $cell;
1602 }
1603 272 ▶ if ((my $mark = $config->{table_wrap_mark}) ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ((my $mark = $config->{"table_wrap_mark"}) ne "") 4 268 272
1604 4 push @fit, '--table-wrap-mark', $mark;
1605 }
1606 272 ▶ if ((my $mark = $config->{table_cell_mark}) ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ((my $mark = $config->{"table_cell_mark"}) ne "") 109 163 272
1607 # the header row and the separator row (to ansicolumn a row of
1608 # "-" cells) are the two header rows and get no mark
1609 109 push @fit, '--table-cell-mark', $mark, '--table-head', 2;
1610 }
1611 # How cells are wrapped is given explicitly, so that it does not
1612 # change with the user's ~/.ansicolumnrc
1613 272 my @wrap = map { "--$_=" . $config->{"table_$_"} } qw(runin runout boundary linebreak);
1614 # kept intact, the lines of a row come joined by GS (see below)
1615 272 ▶ push @wrap, '--table-group' if intact('table');
Branch: 1 branch
BranchTrueFalseTotal
if intact("table") 6 266 272
1616 272 my $formatted = call_ansicolumn($block, @sep_opt, '-o', $sep, '-t', '--cu=1', @align, @fit, @wrap);
1617 272 my $table = fix_separator($formatted, $sep);
1618 272 ▶ if ($open) {
Branch: 1 branch
BranchTrueFalseTotal
if ($open) 31 241 272
1619 # blank the column separators and add the rules
1620 31 $table =~ tr/\x{2502}\x{253C}\x{251C}\x{2524}/ /;
1621 31 ▶ if ($style eq '3line') {
Branch: 1 branch
BranchTrueFalseTotal
if ($style eq '3line') { } 16 15 31
1622 16 my($first) = $table =~ /^([^\n$GROUP_SEP]*)/;
1623 16 my $rule = "\x{2500}" x ansi_width($first);
1624 16 $table = "$rule\n$table$rule\n";
1625 } else {
1626 15 my($rule) = $table =~ /^([\x{2500} ]+)$/m;
1627 15 ▶ $table .= "$rule\n" if defined $rule;
Branch: 1 branch
BranchTrueFalseTotal
if defined $rule 15 0 15
1628 }
1629 31 ▶ $table =~ s{^[\x{2500} ]+$}{ ${^MATCH} =~ tr/\x{2500}/-/r }mgep unless $config->{rule};
Branch: 1 branch
BranchTrueFalseTotal
unless $config->{"rule"} 8 23 31
1630 }
1631 # A table is kept intact: its lines joined into one by UNIT
1632 # SEPARATOR, the last newline kept, for ansicolumn --intact,
1633 # which lays them out without folding them. Nothing after this
1634 # takes a table by its lines but table_regions().
1635 #
1636 # The lines of a row come from ansicolumn joined by GROUP
1637 # SEPARATOR (--table-group), which --intact keeps in one pane.
1638 # The header, the rule below it and the first row are joined
1639 # so too, and so is a rule below the table (3line, simple) with
1640 # the last row: a pane does not end between them.
1641 272 ▶ if (intact('table')) {
Branch: 1 branch
BranchTrueFalseTotal
if (intact("table")) 6 266 272
1642 6 my @rows = split /\n/, $table;
1643 # the rule below the header: the first rule after a line
1644 # which is not one (3line has one above the header)
1645 6 my $head;
1646 6 for my $i (1 .. $#rows) {
1647 7 ▶ $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 6 1 7
1648 6 $head = $i;
1649 6 last;
1650 }
1651 6 ▶ my %glue = map { $_ => 1 } 1 .. min(($head // 0) + 1, $#rows);
Condition50%1/2
$head // 0
l!l
60
MC/DC0%0/1
$head // 0
$head
Truth table50%1/2
A
A= $head
Aresult
11
00
1652 6 ▶ $glue{$#rows} = 1 if $open and @rows > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $open and @rows > 1 1 5 6
Condition66%2/3
$open and @rows > 1
!ll&&!rl&&r
501
MC/DC50%1/2
$open and @rows > 1
$open @rows > 1
Truth table66%2/3
A and B
A= $openB= @rows > 1
ABresult
0X0
100
111
1653 $table = $rows[0] . join('', map {
1654 6 ▶ ($glue{$_} ? $GROUP_SEP : $INTACT_SEP) . $rows[$_]
Branch: 1 branch
BranchTrueFalseTotal
$glue{$_} ? : 14 10 24
1655 } 1 .. $#rows) . "\n";
1656 }
1657 272 push @table_shift, [ $line, ($table =~ tr/\n//) - $lines, $lines ];
1658 272 $table;
1659 }mgep;
1660 # the separators of mark_line_breaks() left out of the tables
1661 196 s{<br\h*/?>\K\x{2028}}{}gi;
1662 }
1663  
1664 279 ▶sub parse_separator {
Subroutine parse_separator: called CC=3 SCAR=11.0
Pod undocumented
1665 279 my $blockref = shift;
1666 279 my $SEP = qr/^\h*+\|(\h*+:?+-++:?+\h*+\|)++\h*+$/mn;
1667 279 my ($sep_line) = $$blockref =~ /($SEP)/;
1668 279 ▶ return ([], []) unless defined $sep_line;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $sep_line 1 278 279
1669 278 my @cells = split /\|/, $sep_line, -1;
1670 278 shift @cells; pop @cells;
1671 278 s/^\h+|\h+$//g for @cells;
1672 278 my @right = grep { $cells[$_-1] =~ /^-+:$/ } 1..@cells;
1673 278 my @center = grep { $cells[$_-1] =~ /^:-+:$/ } 1..@cells;
1674 # Minimize dashes so separator width doesn't inflate column widths
1675 278 $$blockref =~ s{$SEP}{ ${^MATCH} =~ s/:?-+:?/-/gr }mpe;
1676 278 (\@right, \@center);
1677 }
1678  
1679 # Color the code of fenced code blocks by a highlighter of
1680 # Text::ANSI::Highlight: the one of the name in the config highlight,
1681 # or its default for 1. Takes [ language, code ] of each block, and
1682 # returns as many: the code in colors, or undef for a block which is
1683 # not colored, as one with no language or with one the highlighter
1684 # does not know. All are undef when the module, the highlighter or
1685 # its command is not there, and the blocks are shown as they are.
1686 #
1687 # All the blocks are given at once, and each is colored by itself.
1688 # What comes back is the code which was given, with colors, so the
1689 # lines are those of the file.
1690 # The labels of the lines of a code block, when it has parts: a block
1691 # of pandoc-embedz has config, template and data. A line of a part
1692 # labelled NAME is in the color code_NAME, when it is defined.
1693 240 ▶sub code_labels {
Subroutine code_labels: called CC=4 SCAR=13.9
Pod undocumented
1694 240 my($info, $body) = @_;
1695 240 ▶ my @part = eval {
Branch: 1 branch
BranchTrueFalseTotal
my(@part) = eval { do { require Text::ANSI::Highlight; "Text::ANSI::Highlight"->parts($info, $body) } } or return () 240 0 240
1696 240 require Text::ANSI::Highlight;
1697 240 Text::ANSI::Highlight->parts($info, $body);
1698 } or return ();
1699 # in a block with labelled parts, the lines of the others, which
1700 # are between them, have no color
1701 240 ▶ (grep { defined $_->[2] } @part) or return ();
Branch: 1 branch
BranchTrueFalseTotal
grep {defined $_->[2];} @part or return () 3 237 240
1702 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
1703 }
1704  
1705 # the highlighter in the dark mode, when none is named
1706 221 our $DARK_HIGHLIGHT = 'pandoc:breezedark';
1707  
1708 115 ▶sub highlight_code {
Subroutine highlight_code: called CC=7 SCAR=19.5
Pod undocumented
1709 115 my @code = @_;
1710 115 my @none = (undef) x @code;
1711 115 ▶ @code or return @none;
Branch: 1 branch
BranchTrueFalseTotal
@code or return @none 68 47 115
1712 68 my $name = $config->{highlight};
1713 # the default is pandoc, in a style for a dark screen in the dark
1714 # mode
1715 my @with = $name ne '1' ? $name
1716 68 ▶ : ($config->{mode} // '') eq 'dark' ? $DARK_HIGHLIGHT : ();
Branch: 2 branches
BranchTrueFalseTotal
$name ne '1' ? : 6 62 68
($config->{'mode'} // '') eq 'dark' ? : 3 59 62
Condition50%1/2
$config->{"mode"} // ""
l!l
620
MC/DC0%0/1
$config->{"mode"} // ""
$config->{"mode"}
Truth table50%1/2
A
A= $config->{"mode"}
Aresult
11
00
1717 68 ▶ 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 67 1 68
1718 68 require Text::ANSI::Highlight;
1719 # the background is that of the code block: a style for a
1720 # dark screen has its own
1721 68 Text::ANSI::Highlight->new(@with, background => 0);
1722 } or return @none;
1723 67 my @color = eval { $hl->highlight(@code) };
1724 67 ▶ @color == @code ? @color : @none;
Branch: 1 branch
BranchTrueFalseTotal
@color == @code ? : 67 0 67
1725 }
1726  
1727 273 ▶sub call_ansicolumn {
Subroutine call_ansicolumn: called CC=3 SCAR=11.0
Pod undocumented
1728 273 my ($text, @args) = @_;
1729 273 require Command::Run;
1730 273 require App::ansicolumn;
1731 Command::Run->new
1732 ->command(\&App::ansicolumn::ansicolumn, @args)
1733 ->with(stdin => $text,
1734 273 ▶ $config->{nofork} ? (nofork => 1, raw => 1) : ())
Branch: 1 branch
BranchTrueFalseTotal
$config->{'nofork'} ? : 269 4 273
Condition50%1/2
"Command::Run"->new->command(\&App::ansicolumn::ansicolumn, @args)->with("stdin", $text, $config->{"nofork"} ? ("nofork", 1, "raw", 1) : ())->update->data // ""
l!l
2730
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
1735 ->update
1736 ->data // '';
1737 }
1738  
1739 272 ▶sub fix_separator {
Subroutine fix_separator: called CC=7 SCAR=19.5
Pod undocumented
1740 272 my ($text, $sep) = @_;
1741 272 ▶ my $sep_re = $sep eq "\x{2502}" ? "\x{2502}" : '\\|';
Branch: 1 branch
BranchTrueFalseTotal
$sep eq "\x{2502}" ? : 268 4 272
1742 272 $text =~ s{^(\h*?)($sep_re)?((?:\h*-+\h*$sep_re)*\h*-+\h*)($sep_re)?(\h*?)$}{
1743 272 my($pre, $left, $mid, $right, $post) = ($1, $2, $3, $4, $5);
1744 272 ▶ if ($sep eq "\x{2502}") {
Branch: 1 branch
BranchTrueFalseTotal
if ($sep eq "\x{2502}") { } 268 4 272
1745 268 ▶ ($pre =~ tr[ ][\x{2500}]r)
Branch: 2 branches
BranchTrueFalseTotal
defined $left ? : 5 263 268
defined $right ? : 5 263 268
1746 . (defined $left ? "\x{251C}" : '')
1747 . ($mid =~ tr[\x{2502} -][\x{253C}\x{2500}\x{2500}]r)
1748 . (defined $right ? "\x{2524}" : '')
1749 . ($post =~ tr[ ][\x{2500}]r)
1750 } else {
1751 4 ▶ ($pre =~ tr[ ][-]r)
Branch: 2 branches
BranchTrueFalseTotal
defined $left ? : 0 4 4
defined $right ? : 0 4 4
1752 . (defined $left ? '|' : '')
1753 . ($mid =~ tr[ ][-]r)
1754 . (defined $right ? '|' : '')
1755 . ($post =~ tr[ ][-]r)
1756 }
1757 }xmeg;
1758 272 $text;
1759 }
1760  
1761 221 1;
1762  
1763 __DATA__
« blib/lib/App/Greple/md/Image.pm ↑ Summary blib/lib/App/Greple/md/widen.pm »