blib/lib/App/Greple/md.pm

filter: Statementstmt 93.0% 429 / 461 Branchbran 85.1% 143 / 168 Conditioncond 72.1% 57 / 79 MC/DCmcdc 54.5% 24 / 44 Subroutinesub 96.9% 64 / 66 Podpod 0.0% 0 / 32 totaltotal 84.3% 717 / 850 CC 130 SCAR 20.2
CC
130
Cov
89%
default_theme
30.0
setup_colors
18.1
format_table
17.0
CRAP 7.5
« blib/lib/App/Greple/md/Blocks.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 165 ▶use 5.026;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 165 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 165 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 165 our $VERSION = "1.21";
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<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>.
138  
139 greple -Mmd --no-table -- file.md
140  
141 =head2 B<--[no-]rule>
142  
143 Enable or disable Unicode box-drawing characters for table borders.
144 When enabled (default), ASCII pipe characters (C<|>) are replaced
145 with vertical lines (C<E<0x2502>>), and separator row dashes become
146 horizontal rules (C<E<0x2500>>) with corner pieces (C<E<0x251C>>,
147 C<E<0x2524>>, C<E<0x253C>>).
148  
149 greple -Mmd --no-rule -- file.md
150  
151 =head2 B<--colormap> I<LABEL>=I<SPEC>, B<--cm> I<LABEL>=I<SPEC>
152  
153 Override the color for a specific element. I<LABEL> is one of
154 the color labels listed in L</COLOR LABELS>. I<SPEC> follows
155 L<Term::ANSIColor::Concise> format and supports C<sub{...}>
156 function specs via L<Getopt::EX::Colormap>.
157  
158 greple -Mmd --cm h1=RD -- file.md
159 greple -Mmd --cm bold='${base}D' -- file.md
160  
161 B<greple> has an option of the same name. Before C<-->, C<--cm> belongs
162 to this module and takes the labels above. After C<-->, or when there
163 is no C<-->, it is the option of B<greple>, which colors the matched
164 text and its own labels such as C<FILE>, and complains about the labels
165 of this module:
166  
167 greple -Mmd --cm h1=RD -- --cm B -E foo file.md # h1 is red, foo blue
168 greple -Mmd --cm h1=RD file.md # h1: Unknown label
169  
170 =head2 B<--begin> I<FUNCTION>
171  
172 Call I<FUNCTION> on the whole text of each file, in C<$_>, before this
173 module does anything to it, so that the tables and the folded lines
174 follow the change. I<FUNCTION> is a C<sub{...}> or the name of a
175 function, as C<&func(key=value)> or C<&Package::func(key=value)>. A
176 name without a package is looked for in C<main>, and then in the module
177 C<App::Greple::md::func>, named after the function. The package is
178 loaded if the function is not defined yet. A function that is not found
179 is reported with a warning and skipped. The option can be repeated.
180  
181 greple -Mmd --begin 'sub{ s/\(C\)/\x{A9}/g }' -- file.md
182  
183 Unlike the C<--begin> of B<greple> after C<-->, which runs after this
184 module, this one runs before it. In a configuration file or a theme of
185 L<mdee>, it is given as C<pass_md+=(--begin '...')>.
186  
187 L<App::Greple::md::widen> has such a function, C<&widen>.
188  
189 =head2 B<--heading-markup>[=I<STEPS>], B<--hm>[=I<STEPS>]
190  
191 Control inline markup processing inside headings. By default,
192 headings are rendered with uniform heading color without processing
193 bold, italic, strikethrough, or inline code inside them. Links
194 are always processed as OSC 8 hyperlinks regardless of this option.
195  
196 Without an argument, all inline formatting becomes visible within
197 headings using cumulative coloring. With an argument, only the
198 specified steps are processed inside headings. Steps are separated
199 by colons.
200  
201 Available steps: C<inline_code>, C<horizontal_rules>, C<bold>,
202 C<italic>, C<strike>.
203  
204 greple -Mmd --hm -- file.md # all markup
205 greple -Mmd --hm=bold -- file.md # bold only
206 greple -Mmd --hm=bold:italic -- file.md # bold and italic
207  
208 =head2 B<--hashed> I<LEVEL>=I<VALUE>
209  
210 Append closing hashes to headings. For example, C<### Title>
211 becomes C<### Title ###>. Set per heading level:
212  
213 greple -Mmd --hashed h3=1 --hashed h4=1 -- file.md
214  
215 =head2 B<--show> I<LABEL>[=I<VALUE>]
216  
217 Control which elements are highlighted. This is useful for
218 focusing on specific elements or disabling unwanted highlighting.
219  
220 greple -Mmd --show bold=0 -- file.md # disable bold
221 greple -Mmd --show all= --show h1 -- file.md # only h1
222  
223 C<--show LABEL=0> or C<--show LABEL=> disables the label.
224 C<--show LABEL> or C<--show LABEL=1> enables it.
225 C<all> is a special key that sets all labels at once.
226  
227 Controllable labels: C<bold>, C<italic>, C<strike>, C<code_inline>,
228 C<header> (h1-h6), C<horizontal_rule>, C<blockquote>.
229  
230 The following elements are always processed and cannot be disabled:
231 C<comment>, C<code_block> (C<code_mark>, C<code_info>),
232 C<link>, C<image>, C<image_link>.
233 Use C<--cm LABEL=> to remove their color without disabling processing.
234  
235 =head1 CONFIGURATION
236  
237 Module parameters can also be set using the C<config()> function
238 in the C<-M> declaration:
239  
240 greple -Mmd::config(mode=dark,base_color=Crimson) file.md
241  
242 Nested hash parameters use dot notation:
243  
244 greple -Mmd::config(hashed.h3=1,hashed.h4=1) file.md
245  
246 Available parameters:
247  
248 mode light or dark (default: light)
249 base_color base color override
250 colorize syntax highlighting (default: 1)
251 fold text folding (default: 0)
252 fold_width fold width in columns (default: 80)
253 fold_runin run-in width in folded lines (default: 4)
254 fold_runout run-out width in folded lines (default: 4)
255 refill join the lines of paragraphs (default: 0)
256 refill_parser cmark (the CommonMark module), mdperl (Markdown::Perl)
257 or pandoc (default: the first that is there, in
258 that order)
259 front_matter show TOML and YAML front matter as a code block
260 and leave it alone with refill (default: 1)
261 table table formatting (default: 1)
262 table_trim trim cell whitespace (default: 1)
263 table_width table width in columns; cells of over-wide
264 columns are wrapped (default: 0 = off)
265 table_cell per-column widths passed to ansicolumn --cell,
266 colon separated (e.g. 0:10:<20)
267 table_wrap_mark string put at the start of continuation lines
268 of wrapped cells (default: none)
269 table_cell_mark string put at the start of the first line of
270 every body cell in a column that has a wrapped
271 cell (default: none)
272 table_runin run-in width in wrapped cells (default: 2)
273 table_runout run-out width in wrapped cells (default: 2)
274 table_boundary fold boundary in wrapped cells (default: word)
275 table_linebreak line break mode in wrapped cells: none, runin,
276 runout or all (default: all)
277 table_style lattice: column separators (default; pipe is
278 another name); 3line: columns separated by spaces,
279 a rule above and below the table and per column
280 below the header; simple: columns separated by
281 spaces, a rule per column below the header and
282 below the table
283 rule box-drawing characters (default: 1)
284 osc8 OSC 8 hyperlinks (default: 1)
285 heading_markup inline markup in headings (default: 0)
286 0=off, 1/all=all, or colon-separated steps
287 cjk_friendly markdown-cjk-friendly rules for * and **
288 emphasis (default: 0)
289 tick_open inline code open marker (default: `)
290 tick_close inline code close marker (default: ´)
291 nofork nofork+raw mode for code ref calls (default: 1)
292 highlight syntax highlight of fenced code: 1, the name
293 of a highlighter, or 0 (default: 1)
294 hashed.h1-h6 closing hashes per level (default: 0)
295  
296 =head2 Paragraph Refill
297  
298 With C<refill=1>, the lines of every paragraph, block quote, list
299 item and definition are joined into one line before the text is
300 colorized. Which lines belong together is decided by a Markdown
301 parser (L<App::Greple::md::Blocks>): the L<CommonMark> module, an
302 interface to libcmark, when it is installed, otherwise
303 L<Markdown::Perl>, which is pure Perl and always installed with this
304 module, or L<pandoc|https://pandoc.org> (2.11.3 or later) run with the
305 C<sourcepos> extension; C<refill_parser> chooses one. The module
306 joins the lines of the original text and changes nothing else. Hard
307 line breaks are kept, and so is the break before a list marker, a
308 horizontal rule, a table row or a definition (C<: >). When folding
309 is enabled, the joined lines are folded too.
310  
311 Front matter (see L</Front Matter>) is left as it is.
312  
313 greple -Mmd::config(refill=1) file.md
314 greple -Mmd::config(refill=1,refill_parser=pandoc) file.md
315  
316 =head2 Front Matter
317  
318 Front matter at the top of the file is shown as a code block: the
319 body in C<meta_block> and the delimiter lines in C<meta_mark>, with
320 no other markup, and it is not folded or joined.
321 TOML front matter is between C<+++> lines, and YAML front matter goes
322 from a C<---> line to a C<---> or C<...> line, as pandoc takes it (the
323 opening line is not followed by a blank line).
324  
325 Front matter is not part of CommonMark. pandoc and L<Markdown::Perl>
326 take YAML front matter as metadata, while libcmark reads it as a rule,
327 paragraphs and list items. C<front_matter=0> takes the lines as
328 Markdown, as libcmark does.
329  
330 =head2 Syntax Highlight of Code
331  
332 The code in a fenced code block is shown in the colors of its
333 language, the first word after the opening fence, inside the
334 C<code_block> color. The colors are those of a highlighter of
335 L<Text::ANSI::Highlight>: C<highlight=1> is its default, C<pandoc>,
336 and C<highlight=sourcehighlight> (C<gnu>) or C<highlight=skylighting>
337 (C<sky>) is the one of the name. All the blocks of a file are given
338 to the highlighter at once, and each is colored by itself.
339  
340 A block is shown as it is when it has no language, when the
341 highlighter does not know the language, and when the module, the
342 highlighter or its command (C<pandoc>, C<source-highlight>,
343 C<skylighting>) is not installed. C<highlight=0> turns it off.
344  
345 =head2 OSC 8 Hyperlinks
346  
347 Links are converted to clickable OSC 8 terminal hyperlinks in
348 supported terminals (iTerm2, Kitty, WezTerm, Ghostty, etc.).
349 Disable with:
350  
351 greple -Mmd::config(osc8=0) file.md
352  
353 =head2 Settings of the User
354  
355 The module runs B<ansifold> and B<ansicolumn> for folding and tables.
356 They are run as functions in the greple process, or as separate
357 processes with C<nofork=0>, and either way they do not read the rc
358 files of the user, F<~/.ansifoldrc> and F<~/.ansicolumnrc>: the
359 module puts their names in the environment variable
360 C<GETOPTEX_NO_USER_SETTINGS> (see L<Getopt::EX::Long>), so that the
361 output does not change by the settings made for them on the command
362 line.
363  
364 =head1 COLOR LABELS
365  
366 The following labels identify colorizable elements. Use them
367 with C<--colormap> (C<--cm>) to customize colors or C<--show> to control
368 visibility. Default values are shown as C<light / dark>.
369 Colors follow L<Term::ANSIColor::Concise> format.
370  
371 =head2 Headings
372  
373 LABEL LIGHT DARK
374 h1 L25D/${base};E L00D/${base};E
375 h2 L25D/${base}+y20;E L00D/${base}-y15;E
376 h3 L25DN/${base}+y20 L00DN/${base}-y15
377 h4 ${base}UD ${base}UD
378 h5 ${base}UD ${base}UD
379 h6 ${base}D ${base}D
380  
381 =head2 Inline Formatting
382  
383 LABEL LIGHT DARK
384 bold D
385 italic I
386 strike X
387 emphasis_mark L18 L10
388 bold_mark - -
389 italic_mark - -
390 strike_mark - -
391  
392 Emphasis markers (C<**>, C<*>, C<__>, C<_>, C<~~>) are colored with
393 C<emphasis_mark>, separately from the content text. C<bold_mark>,
394 C<italic_mark>, C<strike_mark> are undefined by default and fall back
395 to C<emphasis_mark>. Define them via C<--cm> to override per type:
396  
397 greple -Mmd --cm emphasis_mark=R -- file.md # all markers red
398 greple -Mmd --cm bold_mark=G -- file.md # bold markers green
399  
400 C<*> and C<**> start and end emphasis as in CommonMark: a delimiter
401 next to a letter on one side and punctuation on the other does not
402 count, so C<L*=50, a*=68> is not italic. In Japanese text this also
403 rejects C<日本語の*「強調」*です> and C<日本語の**強調。**です>, as the
404 commonmark and gfm readers of pandoc do. With C<cjk_friendly=1>,
405 the rules of
406 L<markdown-cjk-friendly|https://github.com/tats-u/markdown-cjk-friendly>
407 are used instead, and these are emphasis.
408  
409 =head2 Code
410  
411 LABEL LIGHT DARK
412 code_mark L20 L10
413 code_tick L15/L23 L15/L05
414 code_info ${base_name}=y70 L10
415 code_block /L24;E /L05;E
416 code_inline L00/L23 L25/L05
417 meta_mark L15/L10E L10/L15E
418 meta_block L25/L12E L00/L13E
419  
420 Inline code backticks are displayed as C<`contentE<0xb4>> using
421 C<code_tick> color. Multi-backtick delimiters are collapsed to a
422 single pair with optional surrounding spaces stripped (per CommonMark).
423 The open/close markers can be customized via C<tick_open>/C<tick_close>
424 config parameters.
425  
426 C<meta_mark> and C<meta_block> color the delimiter lines and the
427 body of front matter (see L</Front Matter>), the delimiter lines in
428 the background of the file name and the body a little apart from it.
429 When they are set to empty, C<meta_block> falls back to C<code_block>,
430 and the delimiter lines are in C<code_mark> inside the color of the
431 body.
432  
433 =head2 Block Elements
434  
435 LABEL LIGHT / DARK
436 blockquote ${base}
437 horizontal_rule L15
438 comment ${base}+r60
439  
440 =head2 Links
441  
442 LABEL LIGHT / DARK
443 link I
444 image I
445 image_link I
446 link_mark - -
447  
448 C<link_mark> colors the brackets (C<[>, C<]>) around link and image
449 text. Undefined by default, falls back to C<emphasis_mark>.
450 The C<!> prefix for images uses the C<image> or C<image_link>
451 color. Hide brackets with C<--cm 'link_mark=sub{""}'> (used by
452 the C<nomark> theme).
453  
454 =head1 SEE ALSO
455  
456 =over 4
457  
458 =item L<App::mdee>
459  
460 Markdown viewer command with line folding, table formatting,
461 multi-column layout, and themes. Uses this module for syntax
462 highlighting.
463  
464 =item L<App::Greple>
465  
466 General-purpose extensible grep tool that hosts this module.
467  
468 =item L<Term::ANSIColor::Concise>
469  
470 Concise ANSI color specification format used for color labels.
471  
472 =item L<App::ansicolumn>
473  
474 ANSI-aware column formatting used for table alignment.
475  
476 =item L<App::ansifold>
477  
478 ANSI-aware text folding used for line wrapping in list items.
479  
480 =item L<App::Greple::md::widen>
481  
482 A function for B<--begin>, for characters that terminals draw over two
483 columns.
484  
485 =item L<App::Greple::md::Blocks>
486  
487 Finds the paragraphs for C<refill=1> with L<CommonMark>,
488 L<Markdown::Perl> or L<pandoc|https://pandoc.org>.
489  
490 =item L<CommonMark Spec 0.31.2, Emphasis and strong emphasis|https://spec.commonmark.org/0.31.2/#emphasis-and-strong-emphasis>
491  
492 The rules that C<*> and C<**> follow by default.
493  
494 =item L<CommonMark CJK-friendly Amendments|https://github.com/tats-u/markdown-cjk-friendly/blob/main/specification.md>
495  
496 The rules that C<cjk_friendly=1> follows. The proposal comes from
497 L<commonmark-spec issue #650, Emphasis with CJK punctuation|https://github.com/commonmark/commonmark-spec/issues/650>,
498 open since 2020.
499  
500 =back
501  
502 =head1 AUTHOR
503  
504 Kazumasa Utashiro
505  
506 =head1 LICENSE
507  
508 Copyright © 2025-2026 Kazumasa Utashiro.
509  
510 This library is free software; you can redistribute it and/or modify
511 it under the same terms as Perl itself.
512  
513 =cut
514  
515 165 ▶use URI::Escape;
Subroutine BEGIN: called CC=1 SCAR=0.0
516 165 ▶use Text::ANSI::Fold qw($csi_re $osc_re);
Subroutine BEGIN: called CC=1 SCAR=0.0
517 165 ▶use Text::ANSI::Fold::Util qw(ansi_width);
Subroutine BEGIN: called CC=1 SCAR=0.0
518 165 ▶use Getopt::EX::Config;
Subroutine BEGIN: called CC=1 SCAR=0.0
519 165 ▶use Getopt::EX::Colormap;
Subroutine BEGIN: called CC=1 SCAR=0.0
520 165 ▶use Getopt::EX::Func qw(parse_func);
Subroutine BEGIN: called CC=1 SCAR=0.0
521 165 ▶use App::Greple::Common qw(FILELABEL);
Subroutine BEGIN: called CC=1 SCAR=0.0
522 165 ▶use App::Greple::Regions qw(match_regions);
Subroutine BEGIN: called CC=1 SCAR=0.0
523 165 ▶use App::Greple::md::Blocks qw(blocks);
Subroutine BEGIN: called CC=1 SCAR=0.0
524  
525 165 my @color_labels = qw(
526 code_mark code_tick code_info code_block code_inline
527 meta_mark meta_block
528 comment link image image_link
529 h1 h2 h3 h4 h5 h6
530 bold italic strike emphasis_mark
531 bold_mark italic_mark strike_mark link_mark
532 blockquote horizontal_rule
533 );
534  
535 my $config = Getopt::EX::Config->new(
536 mode => '', # light / dark
537 osc8 => 1, # OSC 8 hyperlinks
538 base_color => '', # override base color
539 colorize => 1, # syntax highlighting
540 fold => 0, # text folding
541 refill => 0, # join the lines of paragraphs
542 refill_parser => '', # cmark (CommonMark module), mdperl (Markdown::Perl) or pandoc; '' = whichever is there
543 front_matter => 1, # front matter (+++ TOML, --- YAML) at the top is a code block
544 fold_width => 80, # fold width
545 fold_runin => 4, # run-in width in folded lines (ansifold default)
546 fold_runout => 4, # run-out width in folded lines (ansifold default)
547 table => 1, # table formatting
548 table_trim => 1, # trim cell content whitespace
549 table_width => 0, # table width; wrap over-wide cells (0 = off)
550 table_cell => '', # per-column widths for ansicolumn --cell (colon separated)
551 table_wrap_mark => '', # mark for continuation lines of wrapped cells
552 table_cell_mark => '', # mark for the first line of cells in wrapped columns
553 table_runin => 2, # run-in width in wrapped cells
554 table_runout => 2, # run-out width in wrapped cells
555 table_boundary => 'word', # fold boundary in wrapped cells
556 table_linebreak => 'all', # line break (kinsoku) mode in wrapped cells
557 rule => 1, # box-drawing characters for tables
558 table_style => 'lattice', # lattice (or pipe): column separators; 3line, simple: spaces and rules only
559 nofork => 1, # use nofork+raw for code ref calls
560 highlight => 1, # syntax highlight of fenced code: 1, the name of a highlighter, or 0
561 heading_markup => 0, # inline formatting in headings
562 cjk_friendly => 0, # markdown-cjk-friendly rules for * and ** emphasis
563 tick_open => '`', # inline code open marker
564 tick_close => "\x{b4}", # inline code close marker (´)
565 hashed => { h1 => 0, h2 => 0, h3 => 0, h4 => 0, h5 => 0, h6 => 0 },
566 165 (map { $_ => undef } @color_labels), # color labels (undef = not set)
567 );
568  
569 #
570 # Color definitions
571 #
572  
573 165 my %base_color = (
574 light => '<RoyalBlue>=y25',
575 dark => '<RoyalBlue>=y80',
576 );
577  
578 165 my %default_colors = (
579 code_mark => 'L20',
580 code_tick => 'L15/L23',
581 code_info => '${base_name}=y70',
582 code_block => '/L24;E',
583 code_inline => 'L00/L23',
584 meta_mark => 'L15/L10E',
585 meta_block => 'L25/L12E',
586 comment => '${base}+r60',
587 link => 'I',
588 image => 'I',
589 image_link => 'I',
590 h1 => 'L25D/${base};E',
591 h2 => 'L25D/${base}+y20;E',
592 h3 => 'L25DN/${base}+y20',
593 h4 => '${base}UD',
594 h5 => '${base}UD',
595 h6 => '${base}D',
596 bold => 'D',
597 italic => 'I',
598 strike => 'X',
599 emphasis_mark => 'L18',
600 blockquote => '${base}',
601 horizontal_rule => 'L15',
602 );
603  
604 165 my %dark_overrides = (
605 code_mark => 'L10',
606 code_tick => 'L15/L05',
607 code_info => 'L10',
608 code_block => '/L05;E',
609 code_inline => 'L25/L05',
610 meta_mark => 'L10/L15E',
611 meta_block => 'L00/L13E',
612 h1 => 'L00D/${base};E',
613 h2 => 'L00D/${base}-y15;E',
614 h3 => 'L00DN/${base}-y15',
615 h4 => '${base}UD',
616 h5 => '${base}UD',
617 h6 => '${base}D',
618 emphasis_mark => 'L10',
619 );
620  
621 0 ▶sub default_theme {
Subroutine default_theme: not called CC=5 SCAR=34.0
Pod undocumented
622 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
623 0 my %colors = %default_colors;
624 0 ▶ if ($mode eq 'dark') {
Branch: 1 branch
BranchTrueFalseTotal
if ($mode eq "dark") 0 0 0
625 0 @colors{keys %dark_overrides} = values %dark_overrides;
626 }
627 0 $colors{base} = $base_color{$mode};
628 0 ▶ if (defined wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined wantarray) { } 0 0 0
629 0 %colors;
630 } else {
631 # Print as bash array assignments: theme_MODE[key]='value'
632 0 for my $key (sort keys %colors) {
633 0 (my $val = $colors{$key}) =~ s/'/'\\''/g;
634 0 printf "theme_%s[%s]='%s'\n", $mode, $key, $val;
635 }
636 }
637 }
638  
639 165 my $cm;
640 my @opt_cm;
641 165 my @opt_begin;
642 165 my %show;
643  
644 159 ▶sub finalize {
Subroutine finalize: called CC=5 SCAR=16.7
Pod undocumented
645 159 my($mod, $argv) = @_;
646 159 no_user_settings(qw(ansicolumn ansifold));
647 159 $config->deal_with($argv,
648 "mode|m=s", "base_color|B=s",
649 "colorize!", "nofork!", "fold!", "refill!", "refill_parser=s", "front_matter!", "fold_width=i", "fold_runin=i", "fold_runout=i",
650 "table!", "table_trim!",
651 "table_width=i", "table_cell=s", "table_wrap_mark=s", "table_cell_mark=s", "rule!", "table_style=s",
652 "table_runin=i", "table_runout=i", "table_boundary=s", "table_linebreak=s",
653 "heading_markup|hm:s", "cjk_friendly!", "tick_open=s", "tick_close=s",
654 "hashed=s%",
655 "colormap|cm=s" => \@opt_cm,
656 "begin=s" => \@opt_begin,
657 "show=s%" => \%show);
658 # --hm with no argument gives "": treat as "all"
659 159 my $hm = $config->{heading_markup};
660 159 ▶ if (defined $hm && $hm eq '') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $hm and $hm eq "") 0 159 159
Condition33%1/3
defined $hm and $hm eq ""
!ll&&!rl&&r
01590
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
661 0 $config->{heading_markup} = 'all';
662 }
663 159 ▶ if (my $w = $config->{fold_width}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $w = $config->{"fold_width"}) 159 0 159
664 159 my $fold = join ' ', '--fold-by', $w, @{$config}{qw(fold_runin fold_runout)};
665 159 $mod->setopt('--fold', $fold);
666 159 ▶ if ($config->{fold}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($config->{"fold"}) 62 97 159
667 62 my @default = $mod->default;
668 62 $mod->setopt('default', @default, $fold);
669 }
670 }
671 }
672  
673 # ansicolumn and ansifold are called as functions in this process
674 # (Command::Run), or as separate processes by the tee module in fork
675 # mode. Either way they must not read the rc files of the user, so
676 # their names go into GETOPTEX_NO_USER_SETTINGS (Getopt::EX >= 3.05),
677 # which Getopt::EX::Long reads when the program first runs. Names
678 # already there are kept, and 1 or * (all programs) is left as it is.
679 165 ▶sub no_user_settings {
Subroutine no_user_settings: called CC=4 SCAR=13.9
Pod undocumented
680 165 my @names = @_;
681 165 ▶ my $env = $ENV{GETOPTEX_NO_USER_SETTINGS} // '';
Condition100%2/2
$ENV{"GETOPTEX_NO_USER_SETTINGS"} // ""
l!l
5160
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
682 165 ▶ return if $env eq '1' or $env eq '*';
Branch: 1 branch
BranchTrueFalseTotal
if $env eq 1 or $env eq "*" 2 163 165
Condition100%3/3
$env eq 1 or $env eq "*"
l!l&&r!l&&!r
11163
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
683 163 my %have = map { $_ => 1 } split /[\s,]+/, $env;
684 $ENV{GETOPTEX_NO_USER_SETTINGS} =
685 163 join ' ', grep { length } $env, grep { !$have{$_}++ } @names;
686 }
687  
688 87 ▶sub setup_colors {
Subroutine setup_colors: called CC=13 SCAR=29.0
Pod undocumented
689 87 ▶ my $mode = $config->{mode} || 'light';
Condition100%2/2
$config->{'mode'} || 'light'
l!l
4938
MC/DC100%1/1
$config->{'mode'} || 'light'
$config->{'mode'}
Truth table100%2/2
A
A= $config->{'mode'}
Aresult
11
00
690 87 my %colors = %default_colors;
691 87 ▶ if ($mode eq 'dark') {
Branch: 1 branch
BranchTrueFalseTotal
if ($mode eq "dark") 2 85 87
692 2 @colors{keys %dark_overrides} = values %dark_overrides;
693 }
694 # Determine base color
695 87 my $base = $config->{base_color};
696 87 ▶ if ($base) {
Branch: 1 branch
BranchTrueFalseTotal
if ($base) { } 0 87 87
697 # Color names get automatic luminance adjustment
698 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
699 if $base =~ /^[A-Za-z]\w*$/;
700 } else {
701 87 ▶ $base = $base_color{$mode} || $base_color{light};
Condition33%1/3
$base_color{$mode} || $base_color{'light'}
l!l&&r!l&&!r
8700
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
702 }
703 # Override with config params (e.g., config(h1=RD))
704 87 for my $key (@color_labels) {
705 2349 my $val = $config->{$key};
706 2349 ▶ if (defined $val) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $val) 11 2338 2349
707 11 $colors{$key} = $val;
708 }
709 }
710 # ${base_name}: color without luminance (e.g., '<RoyalBlue>')
711 87 (my $base_name = $base) =~ s/=y\d+$//;
712 # Expand placeholders
713 87 for my $key (keys %colors) {
714 2001 $colors{$key} =~ s/\$\{base_name\}/$base_name/g;
715 2001 $colors{$key} =~ s/\$\{base\}/$base/g;
716 }
717 # Handle + prefix: prepend current color value before load_params
718 # (load_params' built-in + doesn't work correctly with sub{...})
719 87 my @final_cm;
720 87 for my $entry (@opt_cm) {
721 193 my $expanded = $entry =~ s/\$\{base_name\}/$base_name/gr
722 =~ s/\$\{base\}/$base/gr;
723 193 ▶ if ($expanded =~ /^(\w+)=\+(.*)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expanded =~ /^(\w+)=\+(.*)/u) { } 0 193 193
724 0 my ($label, $append) = ($1, $2);
725 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
726 0 push @final_cm, "$label=$current$append";
727 } else {
728 193 push @final_cm, $expanded;
729 }
730 }
731  
732 87 $cm = Getopt::EX::Colormap->new(
733 HASH => \%colors,
734 NEWLABEL => 1,
735 );
736 87 $cm->load_params(@final_cm);
737 }
738  
739 1206 ▶sub active {
Subroutine active: called CC=4 SCAR=13.9
Pod undocumented
740 1206 my $label = shift;
741 1206 ▶ return 0 if exists $show{$label} && !$show{$label};
Branch: 1 branch
BranchTrueFalseTotal
if exists $show{$label} and not $show{$label} 17 1189 1206
Condition100%3/3
exists $show{$label} and not $show{$label}
!ll&&!rl&&r
1187217
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
742 1189 ▶ return 1 unless exists $cm->{HASH}{$label};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $cm->{"HASH"}{$label} 85 1104 1189
743 1104 $cm->{HASH}{$label} ne '';
744 }
745  
746 #
747 # Apply color by label
748 #
749  
750 7289 ▶sub md_color {
Subroutine md_color: called CC=1 SCAR=0.0
Pod undocumented
751 7289 my($label, $text) = @_;
752 7289 $cm->color($label, $text);
753 }
754  
755 17 ▶sub defined_color {
Subroutine defined_color: called CC=2 SCAR=7.2
Pod undocumented
756 17 my $label = shift;
757 17 ▶ exists $cm->{HASH}{$label} && $cm->{HASH}{$label} ne '';
Branch: 1 branch
BranchTrueFalseTotal
exists $cm->{"HASH"}{$label} and $cm->{"HASH"}{$label} ne "" 17 0 17
758 }
759  
760 # The color of $label, or of $fallback when $label is not defined
761 11 ▶sub fallback_color {
Subroutine fallback_color: called CC=2 SCAR=6.9
Pod undocumented
762 11 my($label, $fallback, $text) = @_;
763 11 ▶ $label = $fallback unless defined_color($label);
Branch: 1 branch
BranchTrueFalseTotal
unless defined_color($label) 3 8 11
764 11 md_color($label, $text);
765 }
766  
767 1752 ▶sub mark_color {
Subroutine mark_color: called CC=3 SCAR=11.0
Pod undocumented
768 1752 my($type, $text) = @_;
769 1752 my $label = "${type}_mark";
770 $label = 'emphasis_mark' unless exists $cm->{HASH}{$label}
771 1752 ▶ && $cm->{HASH}{$label} ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless exists $cm->{"HASH"}{$label} and $cm->{"HASH"}{$label} ne "" 1388 364 1752
Condition66%2/3
exists $cm->{"HASH"}{$label} and $cm->{"HASH"}{$label} ne ""
!ll&&!rl&&r
13880364
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
772 1752 md_color($label, $text);
773 }
774  
775 #
776 # Protection mechanism
777 #
778 # SGR 256 placeholders protect processed regions (inline code,
779 # comments, links) from being matched by later patterns.
780 #
781  
782 165 my @protected;
783 165 my($PS, $PE) = ("\e[256m", "\e[m"); # protect start/end markers
784 165 my $PR = qr/\e\[256m(\d+)\e\[m/; # protect restore pattern
785 165 my($OS, $OE) = ("\e]8;;", "\e\\"); # OSC 8 start/end markers
786  
787 2191 ▶sub protect {
Subroutine protect: called CC=1 SCAR=0.0
Pod undocumented
788 2191 my $text = shift;
789 2191 push @protected, $text;
790 2191 $PS . $#protected . $PE;
791 }
792  
793 943 ▶sub restore {
Subroutine restore: called CC=3 SCAR=11.0
Pod undocumented
794 943 my $s = shift;
795 943 ▶ 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 { '???' } 161 943 1104
Condition50%1/2
$protected[$1] // die("restore failed: index $1")
l!l
21910
MC/DC0%0/1
$protected[$1] // die("restore failed: index $1")
$protected[$1]
Truth table50%1/2
A
A= $protected[$1]
Aresult
11
00
796 943 $s;
797 }
798  
799 #
800 # OSC 8 hyperlink generation
801 #
802  
803 340 ▶sub osc8 {
Subroutine osc8: called CC=2 SCAR=7.0
Pod undocumented
804 340 ▶ return $_[1] unless $config->{osc8};
Branch: 1 branch
BranchTrueFalseTotal
unless $config->{"osc8"} 0 340 340
805 340 my($url, $text) = @_;
806 340 my $escaped = uri_escape_utf8($url, "^\\x20-\\x7e");
807 340 "${OS}${escaped}${OE}${text}${OS}${OE}";
808 }
809  
810 #
811 # Link text inner pattern: backtick spans, backslash escapes, normal chars
812 #
813  
814 165 my $LT = qr/(?:`[^`\n]*+`|\\.|[^`\\\n\]]++)+/;
815  
816 # Code span pattern (both single and multi-backtick).
817 # Captures: _bt (backtick delimiter), _content (code body).
818 # Used directly in inline_code step and as basis for $SKIP_CODE.
819 165 my $CODE = qr{(?x)
820 (?<_bt> `++ ) # opening backtick(s)
821 (?<_content>
822 (?: (?! \g{_bt} ) . )+? # content (not containing same-length backticks)
823 )
824 \g{_bt} # closing backtick(s) matching opener
825 };
826  
827 # Skip code spans in link/image patterns.
828 # Used as the first alternative in s{$SKIP_CODE|<link pattern>}{...}ge
829 # so that code spans are matched and skipped, preventing link/image
830 # patterns from matching inside them.
831 165 my $SKIP_CODE = qr{$CODE (*SKIP)(*FAIL)}x;
832  
833 # Delimiters of * and ** emphasis (CommonMark 0.31.2, 6.2): an opener
834 # must be left-flanking and a closer right-flanking, so that
835 # "L*=50, a*=68" is not italic. Punctuation is Unicode punctuation and
836 # symbols. An opener after $tight (neither a space nor punctuation)
837 # cannot have punctuation after it, and a closer before $tight cannot
838 # have punctuation before it.
839 #
840 # With cjk_friendly=1 the amendments of markdown-cjk-friendly apply:
841 # CJK punctuation does not count, and a CJK character is as good as a
842 # space on the other side, so that "日本語の*「強調」*です" is italic.
843 # See CLAUDE.md.
844 165 ▶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
1650
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
845 165 my $CJK = qr/(?:(?!$EMOJI)[\p{EA=W}\p{EA=F}\p{EA=H}]|\p{Hangul})/;
846  
847 169 ▶sub flanking {
Subroutine flanking: called CC=2 SCAR=6.9
Pod undocumented
848 169 my $d = quotemeta shift;
849 my($punct, $tight) = $config->{cjk_friendly}
850 169 ▶ ? (qr/(?!$CJK)[\p{P}\p{S}]/, qr/(?!$CJK)[^\s\p{P}\p{S}]/)
Branch: 1 branch
BranchTrueFalseTotal
$config->{'cjk_friendly'} ? : 2 167 169
851 : (qr/[\p{P}\p{S}]/, qr/[^\s\p{P}\p{S}]/);
852 # A link or a code span is a protect() placeholder by now; its
853 # ends stand for the punctuation that delimits it in the text.
854 169 my($ps, $pe) = (qr/\e\[256m/, qr/\e\[m/);
855 169 (qr/(?:(?<!$tight)|(?<=$pe)|(?!$d(?:$punct|$ps)))$d(?=\S)/,
856 qr/(?<=\S)(?:(?<!$punct)(?<!$pe)|(?!$d(?!$ps)$tight))$d/);
857 }
858  
859 #
860 # colorize() - the main function
861 #
862 # Receives entire file content in $_ (--begin with -G --filter).
863 # Processes all patterns with multiline regexes.
864 #
865  
866 #
867 # Pipeline step class
868 #
869  
870 165 package App::Greple::md::Step {
871 2310 ▶ sub new {
Subroutine new: called CC=1 SCAR=0.0
872 2310 my($class, %args) = @_;
873 2310 bless \%args, $class;
874 }
875 0 ▶ sub label { $_[0]->{label} }
Subroutine label: not called CC=1 SCAR=6.9
876 1218 ▶ 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"}) 522 696 1218
877 1201 ▶ sub run { $_[0]->{code}->() }
Subroutine run: called CC=1 SCAR=0.0
878 }
879  
880 2310 ▶sub Step {
Subroutine Step: called CC=1 SCAR=0.0
Pod undocumented
881 2310 my $code = pop;
882 2310 my $label = shift;
883 2310 App::Greple::md::Step->new(label => $label, code => $code);
884 }
885  
886 #
887 # Pipeline steps: Step(sub{}) = always active, Step(label => sub{}) = controllable
888 #
889  
890 my %colorize = (
891  
892 87 ▶ front_matter => Step(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
893 87 ▶ my $front = front_matter($_) // return;
Condition100%2/2
front_matter($_) // (return)
l!l
681
MC/DC100%1/1
front_matter($_) // (return)
front_matter($_)
Truth table100%2/2
A
A= front_matter($_)
Aresult
11
00
894 6 my($open, @body) = split /(?<=\n)/, $front;
895 6 my $close = pop @body;
896 6 chomp $open;
897 6 ▶ my $block = sub { fallback_color('meta_block', 'code_block', $_[0]) };
Subroutine __ANON__: called CC=1 SCAR=0.0
898 # A delimiter line is in meta_mark alone when it is defined, and
899 # otherwise in code_mark inside the block color, so that the
900 # background of the block runs over it
901 my $mark = defined_color('meta_mark')
902 10 ▶ ? sub { md_color('meta_mark', $_[0]) }
Subroutine __ANON__: called CC=1 SCAR=0.0
903 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
904 substr($_, 0, length $front) = protect(join '',
905 $mark->($open), "\n",
906 6 (map { $block->($_) } @body),
907 $mark->($close));
908 }),
909  
910 87 ▶ code_blocks => Step(sub {
Subroutine __ANON__: called CC=7 SCAR=19.5
911 # closing fence: the same character, at least as long (CommonMark)
912 87 my $block = qr{^( {0,3})((`|~)\3{2,})(.*)\n((?s:.*?))^( {0,3})(\2\3*)(\h*)$}m;
913 # the code of all the blocks, in the colors of their languages
914 87 my @highlight;
915 87 ▶ if ($config->{highlight}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($config->{"highlight"}) 86 1 87
916 86 my @code;
917 86 ▶ while (/$block/g) {
Branch: 1 branch
BranchTrueFalseTotal
if (/$block/gu) 229 86 315
918 229 my($info, $body) = ($4, $5);
919 229 ▶ push @code, [ $info =~ /^\h*([\w+#.-]+)/ ? $1 : '', $body ];
Branch: 1 branch
BranchTrueFalseTotal
$info =~ /^\h*([\w+#.-]+)/u ? : 223 6 229
920 }
921 86 @highlight = highlight_code(@code);
922 }
923 s{$block}{
924 230 my($oi, $fence, $lang, $body, $ci, $close, $trail) = ($1, $2, $4, $5, $6, $7, $8);
925 230 ▶ $body = shift(@highlight) // $body;
Condition66%2/3
shift @highlight // $body
l!l&&r!l&&!r
102200
MC/DC0%0/2
shift @highlight // $body
shift @highlight $body
Truth table66%2/3
A // B
A= shift @highlightB= $body
ABresult
1X1
011
000
926 230 my $result = md_color('code_mark', "$oi$fence");
927 230 ▶ $result .= md_color('code_info', $lang) if length($lang);
Branch: 1 branch
BranchTrueFalseTotal
if length $lang 224 6 230
928 230 $result .= "\n";
929 230 ▶ if (length($body)) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $body) 229 1 230
930 229 $result .= join '', map { md_color('code_block', $_) }
931 split /(?<=\n)/, $body;
932 }
933 230 $result .= md_color('code_mark', "$ci$close") . $trail;
934 230 protect($result)
935 87 }mge;
936 }),
937  
938 87 ▶ comments => Step(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
939 87 s/(^<!--(?![->])(?s:.*?)-->)/protect(md_color('comment', $1))/mge;
940 }),
941  
942 87 ▶ image_links => Step(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
943 87 s{$SKIP_CODE|\[!\[(?<text>$LT)\]\((?<img>[^)\n]+)\)\]\(<?(?<url>[^>)\s\n]+)>?\)}{
944 protect(
945 osc8($+{img}, md_color('image_link', "!"))
946 42 . osc8($+{url}, mark_color('link', "[") . md_color('image_link', $+{text}) . mark_color('link', "]"))
947 )
948 }ge;
949 }),
950  
951 87 ▶ images => Step(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
952 87 s{$SKIP_CODE|!\[(?<text>$LT)\]\(<?(?<url>[^>)\s\n]+)>?\)}{
953 42 protect(osc8($+{url}, md_color('image', "!") . mark_color('link', "[") . md_color('image', $+{text}) . mark_color('link', "]")))
954 }ge;
955 }),
956  
957 87 ▶ links => Step(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
958 87 s{$SKIP_CODE|(?<![!\e])\[(?<text>$LT)\]\(<?(?<url>[^>)\s\n]+)>?\)}{
959 214 protect(osc8($+{url}, mark_color('link', "[") . md_color('link', $+{text}) . mark_color('link', "]")))
960 }ge;
961 }),
962  
963 85 ▶ inline_code => Step(code_inline => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
964 85 state $to = $config->{tick_open};
965 85 state $tc = $config->{tick_close};
966 85 s{$CODE}{
967 551 my $content = $+{_content};
968 # Strip optional leading/trailing space for multi-backtick (CommonMark)
969 551 ▶ $content =~ s/^ (.+) $/$1/ if length($+{_bt}) >= 2;
Branch: 1 branch
BranchTrueFalseTotal
if length $+{"_bt"} >= 2 80 471 551
970 551 protect(md_color('code_tick', $to) . md_color('code_inline', $content) . md_color('code_tick', $tc))
971 }ge;
972 }),
973  
974 85 ▶ headings => Step(header => sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
975 85 my $hashed = $config->{hashed};
976 85 for my $n (reverse 1..6) {
977 510 ▶ next unless active("h$n");
Branch: 1 branch
BranchTrueFalseTotal
unless active("h$n") 0 510 510
978 510 my $hdr = '#' x $n;
979 # up to 3 spaces of indentation; empty headings ("#") too (CommonMark)
980 510 s{^( {0,3}$hdr(?:\h+.*)?)$}{
981 856 my $line = $1;
982 $line .= " $hdr"
983 856 ▶ if $hashed->{"h$n"} && $line !~ /\#$/;
Branch: 1 branch
BranchTrueFalseTotal
if $$hashed{"h$n"} and not $line =~ /\#$/u 130 726 856
Condition100%3/3
$$hashed{"h$n"} and not $line =~ /\#$/u
!ll&&!rl&&r
70026130
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
984 856 protect(md_color("h$n", restore($line)));
985 }mge;
986 }
987 }),
988  
989 85 ▶ horizontal_rules => Step(horizontal_rule => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
990 85 s/^([ ]{0,3}(?:[-*_][ ]*){3,})$/protect(md_color('horizontal_rule', $1))/mge;
991 }),
992  
993 85 ▶ bold_italic => Step(bold => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
994 85 s{$SKIP_CODE|(?<!\\)(?<m>\*\*\*)(?<t>.*?)(?<!\\)\g{m}}{
995 40 protect(mark_color('bold', $+{m}) . md_color('bold', md_color('italic', $+{t})) . mark_color('bold', $+{m}))
996 }gep;
997 85 s{$SKIP_CODE|(?<![\\\w])(?<m>___)(?<t>.*?)(?<!\\)\g{m}(?!\w)}{
998 40 protect(mark_color('bold', $+{m}) . md_color('bold', md_color('italic', $+{t})) . mark_color('bold', $+{m}))
999 }gep;
1000 }),
1001  
1002 85 ▶ bold => Step(bold => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1003 85 my($open, $close) = flanking('**');
1004 # no opener inside, so that a closer pairs with the nearest opener
1005 85 s{$SKIP_CODE|(?<!\\)(?<m>$open)(?<t>(?:(?!$open).)*?)(?<!\\)$close}{
1006 mark_color('bold', $+{m}) . md_color('bold', $+{t}) . mark_color('bold', $+{m})
1007 291 }gep;
1008 85 s{$SKIP_CODE|(?<![\\\w])(?<m>__)(?<t>.*?)(?<!\\)\g{m}(?!\w)}{
1009 mark_color('bold', $+{m}) . md_color('bold', $+{t}) . mark_color('bold', $+{m})
1010 40 }gep;
1011 }),
1012  
1013 84 ▶ italic => Step(italic => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1014 84 my($open, $close) = flanking('*');
1015 84 s{$SKIP_CODE|(?<![\\\w])(?<m>_)(?<t>(?:(?!_).)+)(?<!\\)\g{m}(?!\w)}{
1016 mark_color('italic', $+{m}) . md_color('italic', $+{t}) . mark_color('italic', $+{m})
1017 78 }gep;
1018 84 s{$SKIP_CODE|(?<![\\*])(?<m>$open)(?<t>(?:(?!\*).)+)(?<!\\)$close(?!\*)}{
1019 mark_color('italic', $+{m}) . md_color('italic', $+{t}) . mark_color('italic', $+{m})
1020 49 }gep;
1021 }),
1022  
1023 85 ▶ strike => Step(strike => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1024 85 s{$SKIP_CODE|(?<!\\)(?<m>~~)(?<t>.+?)(?<!\\)\g{m}}{
1025 mark_color('strike', $+{m}) . md_color('strike', $+{t}) . mark_color('strike', $+{m})
1026 40 }gep;
1027 }),
1028  
1029 85 ▶ blockquotes => Step(blockquote => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1030 85 s/^( {0,3})((?:>\h?)+)(.*)$/$1 . md_color('blockquote', $2) . $3/mge;
1031 165 }),
1032 );
1033  
1034 #
1035 # Pipeline configuration
1036 #
1037  
1038 # Always before headings (protection + links)
1039 165 my @protect_steps = qw(front_matter code_blocks comments image_links images links);
1040  
1041 # Inline steps controlled by heading_markup
1042 165 my @inline_steps = qw(inline_code horizontal_rules bold_italic bold italic strike);
1043  
1044 # Always last
1045 165 my @final_steps = qw(blockquotes);
1046  
1047 87 ▶sub build_pipeline {
Subroutine build_pipeline: called CC=4 SCAR=25.8
Pod undocumented
1048 87 my $hm = $config->{heading_markup};
1049  
1050 # heading_markup disabled: headings before all inline steps
1051 87 ▶ if (!$hm) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($hm) 87 0 87
1052 87 return (@protect_steps, 'headings', @inline_steps, @final_steps);
1053 }
1054  
1055 # "all" or "1": all inline steps before headings
1056 0 my %before;
1057 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
1058 0 %before = map { $_ => 1 } @inline_steps;
1059 } else {
1060 # "bold:italic" → collect word tokens, filter to valid inline steps
1061 0 my %valid = map { $_ => 1 } @inline_steps;
1062 0 %before = map { $_ => 1 } grep { $valid{$_} } ($hm =~ /(\w+)/g);
1063 }
1064  
1065 0 my @before_h = grep { $before{$_} } @inline_steps;
1066 0 my @after_h = grep { !$before{$_} } @inline_steps;
1067  
1068 0 return (@protect_steps, @before_h, 'headings', @after_h, @final_steps);
1069 }
1070  
1071 87 ▶sub colorize {
Subroutine colorize: called CC=3 SCAR=11.0
Pod undocumented
1072 87 setup_colors();
1073 87 @protected = ();
1074  
1075 87 for my $name (build_pipeline()) {
1076 1218 my $step = $colorize{$name};
1077 1218 ▶ $step->run if $step->active;
Branch: 1 branch
BranchTrueFalseTotal
if $step->active 1201 17 1218
1078 }
1079  
1080 87 $_ = restore($_);
1081 87 $_;
1082 }
1083  
1084 #
1085 # Table formatting
1086 #
1087  
1088 # Regions of formatted tables, used by --fold-by as --exclude so that
1089 # ansifold does not fold them again: three or more lines that contain a
1090 # column separator, in a block that has a separator row. A line may
1091 # start with a border or rule character, a dash, whitespace, or one of
1092 # the configured marks (a wrapped first column's continuation line starts
1093 # with the wrap mark, and its body rows with the cell mark), so the
1094 # pattern is built from the config at run time rather than in __DATA__.
1095 63 ▶sub table_regions {
Subroutine table_regions: called CC=1 SCAR=0.0
Pod undocumented
1096 63 my %arg = @_;
1097 63 delete $arg{&FILELABEL};
1098 39 my $marks = join '', map { quotemeta substr $_, 0, 1 }
1099 63 grep { length } @{$config}{qw(table_wrap_mark table_cell_mark)};
1100 63 my $bar = "\x{2502}|"; # column separator │ |
1101 63 my $cross = "\x{253C}"; # rule crossing ┼
1102 63 my $rule = "\x{2500}\x{251C}\x{2524}"; # rule line ─ ├ ┤
1103 63 my $row = qr{
1104 ^ [ $bar \x{251C} \x{2500} $marks \h - ] # border, rule, mark, pad, or dash
1105 [^\n]* [ $bar $cross ] [^\n]* \n # ... with a separator somewhere
1106 }xxm;
1107 63 my $sep = qr{ (?= [^\n]* [ $cross | ] ) [ $rule $cross | - ]+ \n }xx;
1108 63 match_regions(pattern => qr/ (?= (?:$row)*? $sep ) (?:$row){3,} /x);
1109 }
1110  
1111 #
1112 # Paragraph refill
1113 #
1114  
1115 # Join the lines of one paragraph (or list item, quote, definition)
1116 # into a single line. The rules are those of ansifold's fill_up: the
1117 # line break after a fullwidth punctuation character and between two
1118 # characters of a script written without spaces (CJK) is simply
1119 # removed, any other becomes one space. A line is left as it is, as
1120 # the start of a new line, when the line before it ends in a hard
1121 # break (two or more spaces, or a backslash), or when it starts with
1122 # a list marker, is a horizontal rule, which pandoc may report as
1123 # part of the paragraph (a "#." list, "Text\n***"), or when either
1124 # line looks like a table row: GFM does not let a table interrupt a
1125 # paragraph, but format_table takes three such lines as a table.
1126 # From the second line on, up to $depth quote markers and the
1127 # indentation are removed before joining. A CR before the line
1128 # break (CRLF file) goes with the line break.
1129 #
1130 # The character properties are defined as subroutines in App::ansifold
1131 # and looked up when the pattern is compiled, so the patterns are
1132 # built here, after the module is loaded, not at compile time.
1133 73 ▶sub refill_block {
Subroutine refill_block: called CC=13 SCAR=25.7
Pod undocumented
1134 73 my($lines, $depth) = @_;
1135 73 state $punct = do {
1136 18 require App::ansifold;
1137 18 my $p = "App::ansifold::InFullwidthPunctuation";
1138 18 qr/\p{$p}/;
1139 };
1140 73 state $concat = do {
1141 18 my $p = "App::ansifold::InConcatScript";
1142 18 qr/\p{$p}/;
1143 };
1144 73 my $prefix = qr/^\h*(?:>\h?){0,$depth}\h*/;
1145 73 my $marker = qr/^\h*(?:[*+-]|(?:\d+|#)[.)])\h+/;
1146 73 my $hr = qr/^ {0,3}(?:[-*_][ ]*){3,}\r?$/;
1147 73 my $row = qr/^ {0,3}\|.+\|\h*\r?$/;
1148 73 my $def = qr/^\h*:\h/;
1149 73 my $note = qr/$prefix\[\^[^\]\s]+\]:/;
1150 73 my $hard = qr/(?:(?<!\\)(?:\\\\)*\\|(?<! ) {2,})\r?$/; # odd number of backslashes, or two spaces (the lookbehinds keep it linear)
1151 73 my @out;
1152 73 for my $line (@$lines) {
1153 187 ▶ 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) 124 63 187
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
121363
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
118366
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
113569
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
112174
not @out or $out[-1] =~ /$hard/u or $out[-1] =~ /$row/u or $line =~ /$marker/u
l!l&&r!l&&!r
111175
not @out or $out[-1] =~ /$hard/u or $out[-1] =~ /$row/u
l!l&&r!l&&!r
773476
not @out or $out[-1] =~ /$hard/u
l!l&&r!l&&!r
734110
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
1154 or $line =~ $marker or $line =~ $hr or $line =~ $row
1155 or $line =~ $def or $line =~ $note) {
1156 124 push @out, $line;
1157 124 next;
1158 }
1159 63 my $text = $line =~ s/$prefix//r;
1160 63 $out[-1] =~ s/\r\z//;
1161 63 ▶ if ($out[-1] =~ /$punct$/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($out[-1] =~ /$punct$/u) { } 1 62 63
elsif ($out[-1] =~ /$concat$/u and $text =~ /^$concat/u) { } 2 60 62
1162 1 $out[-1] .= $text;
1163 ▶ } elsif ($out[-1] =~ /$concat$/ and $text =~ /^$concat/) {
Condition66%2/3
$out[-1] =~ /$concat$/u and $text =~ /^$concat/u
!ll&&!rl&&r
6002
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
1164 2 $out[-1] .= $text;
1165 } else {
1166 60 $out[-1] =~ s/ +$//;
1167 60 $text =~ s/^ +//;
1168 60 $out[-1] .= " $text";
1169 }
1170 }
1171 73 @out;
1172 }
1173  
1174 # The line ranges that refill() joined, as [first, last] in the text
1175 # after joining, and the formatted tables, as [first line, lines added],
1176 # both for the current file. refill_regions() turns them into the
1177 # regions that --fold-by folds.
1178 165 our @refill_lines;
1179 165 our @table_shift;
1180  
1181 # Front matter at the top of the text: TOML (+++ ... +++) or YAML
1182 # (--- ... --- or ...). It is not part of CommonMark: pandoc takes TOML
1183 # as a paragraph and YAML as metadata, Markdown::Perl takes YAML as
1184 # metadata, and libcmark takes YAML as paragraphs and list items. As
1185 # in pandoc, a blank line right after the opening --- makes it a rule.
1186 # Returns the front matter without the line break after its last line,
1187 # or an empty list. $front_lines is its number of lines, set by
1188 # begin() before the text is changed, for refill and the fold regions.
1189 165 our $front_lines = 0;
1190 245 ▶sub front_matter {
Subroutine front_matter: called CC=3 SCAR=11.0
Pod undocumented
1191 245 ▶ $config->{front_matter} or return;
Branch: 1 branch
BranchTrueFalseTotal
$config->{"front_matter"} or return 242 3 245
1192 242 ▶ $_[0] =~ m{
Branch: 1 branch
BranchTrueFalseTotal
$_[0] =~ / \A (?: \+\+\+ \r?\n (?:[^\n]*\n)*? \+\+\+ | --- \r?\n (?!\r?\n) (?:[^\n]*\n)*? (?:---|\.\.\.) ) \h* \r? (?=\n|\z) /pux ? : 17 225 242
1193 \A (?: \+\+\+ \r?\n (?:[^\n]*\n)*? \+\+\+
1194 | --- \r?\n (?!\r?\n) (?:[^\n]*\n)*? (?:---|\.\.\.) )
1195 \h* \r? (?=\n|\z)
1196 }px ? ${^MATCH} : ();
1197 }
1198  
1199 # The region of the front matter, used by --fold-by as --exclude. The
1200 # text is colored by then, so the region is found by its line count.
1201 63 ▶sub front_matter_region {
Subroutine front_matter_region: called CC=4 SCAR=14.3
Pod undocumented
1202 63 my %arg = @_;
1203 63 delete $arg{&FILELABEL};
1204 63 ▶ $front_lines or return ();
Branch: 1 branch
BranchTrueFalseTotal
$App::Greple::md::front_lines or return () 1 62 63
1205 1 my $pos = 0;
1206 1 for (1 .. $front_lines) {
1207 1 $pos = index($_, "\n", $pos);
1208 1 ▶ $pos < 0 and return [ 0, length ];
Branch: 1 branch
BranchTrueFalseTotal
$pos < 0 and return [0, length $_] 1 0 1
1209 0 $pos++;
1210 }
1211 0 [ 0, $pos ];
1212 }
1213  
1214 # Join the lines of every paragraph (Para) and tight list item or
1215 # definition (Plain) in $_, from the bottom up so that the line numbers
1216 # of the blocks above stay valid, and remember where the joined lines
1217 # are in the result.
1218 18 ▶sub refill {
Subroutine refill: called CC=7 SCAR=19.5
Pod undocumented
1219 18 @refill_lines = ();
1220 18 my @lines = split /\n/, $_, -1;
1221 18 my @done;
1222 18 my $limit = @lines + 1;
1223 18 my $front = $front_lines;
1224 18 for my $b (sort { $b->{first} <=> $a->{first} }
1225 49 ▶ grep { $_->{type} eq 'Para' or $_->{type} eq 'Plain' }
Condition33%1/3
$_->{'type'} eq 'Para' || $_->{'type'} eq 'Plain'
l!l&&r!l&&!r
4900
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
1226 blocks($_, parser => $config->{refill_parser})) {
1227 49 my($first, $last) = @{$b}{qw(first last)};
1228 # libcmark runs a paragraph on past a closing "..."
1229 49 ▶ $first = $front + 1 if $first <= $front;
Branch: 1 branch
BranchTrueFalseTotal
if $first <= $front 1 48 49
1230 49 ▶ next if $last < $first or $last >= $limit;
Branch: 1 branch
BranchTrueFalseTotal
if $last < $first or $last >= $limit 1 48 49
Condition66%2/3
$last < $first or $last >= $limit
l!l&&r!l&&!r
1048
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
1231 48 $limit = $first;
1232 48 my @joined = refill_block([ @lines[$first-1 .. $last-1] ], $b->{depth});
1233 48 splice @lines, $first-1, $last-$first+1, @joined;
1234 48 unshift @done, [ $first, scalar @joined, $last - $first + 1 - @joined ];
1235 }
1236 18 my $shift = 0;
1237 18 for my $d (@done) {
1238 48 my($first, $count, $removed) = @$d;
1239 48 push @refill_lines, [ $first - $shift, $first - $shift + $count - 1 ];
1240 48 $shift += $removed;
1241 }
1242 18 $_ = join "\n", @lines;
1243 }
1244  
1245 # The lines that refill() joined, one region per line including its
1246 # newline, for --fold-by. The text has been through colorize(), which
1247 # keeps the number of lines, and format_table(), which does not: the
1248 # tables above a range have added the lines in @table_shift.
1249 63 ▶sub refill_regions {
Subroutine refill_regions: called CC=9 SCAR=22.1
Pod undocumented
1250 63 my %arg = @_;
1251 63 delete $arg{&FILELABEL};
1252 63 ▶ return () unless @refill_lines;
Branch: 1 branch
BranchTrueFalseTotal
unless @App::Greple::md::refill_lines 52 11 63
1253 11 my @start = (0);
1254 11 my $pos = 0;
1255 11 ▶ while (($pos = index($_, "\n", $pos)) >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (($pos = index($_, " ", $pos)) >= 0) 99 11 110
1256 99 push @start, ++$pos;
1257 }
1258 11 my $end = length $_;
1259 11 my @regions;
1260 11 for my $range (@refill_lines) {
1261 29 for my $line ($range->[0] .. $range->[1]) {
1262 53 my $shift = 0;
1263 53 for my $t (@table_shift) {
1264 33 ▶ $shift += $t->[1] if $t->[0] < $line;
Branch: 1 branch
BranchTrueFalseTotal
if $t->[0] < $line 24 9 33
1265 }
1266 53 my $n = $line + $shift;
1267 53 ▶ last if $n > @start;
Branch: 1 branch
BranchTrueFalseTotal
if $n > @start 0 53 53
1268 53 ▶ push @regions, [ $start[$n-1], $start[$n] // $end ];
Condition33%1/3
$start[$n] // $end
l!l&&r!l&&!r
5300
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
1269 }
1270 }
1271 11 @regions;
1272 }
1273  
1274  
1275 # What a file must not send to the terminal: everything but colors, and the
1276 # mark of protect(), which would bring back or look for protected text.
1277 165 my $STRING = qr{
1278 (?: \e [PX^_] | [\x90\x98\x9e\x9f] ) # DCS, SOS, PM, APC
1279 (?: [^\x00-\x07\x0e-\x1f\x7f-\x9f]*+ (?: \e\\ | \x9c | \a ) )?
1280 }x;
1281 165 my $CONTROLS = qr{
1282 \e \[ (?! 256m ) [0-9:;]* m (*SKIP)(*FAIL)
1283 |
1284 $osc_re
1285 |
1286 $STRING
1287 |
1288 $csi_re
1289 |
1290 \e [\x20-\x2f]* [\x30-\x7e]
1291 |
1292 [\x00-\x08\x0b\x0e-\x1f\x7f-\x9f]
1293 }x;
1294  
1295 187 ▶sub remove_controls {
Subroutine remove_controls: called CC=1 SCAR=0.0
Pod undocumented
1296 187 s/$CONTROLS//g;
1297 }
1298  
1299 # Find the function of a --begin option and load its package, so that a
1300 # module does not have to be given with -M ahead of this one. A name without
1301 # a package is looked for in main, and then as the function name of the
1302 # module App::Greple::md::name. Returns the option with the full name. A
1303 # function that does not exist is only reported, and the text is shown
1304 # without it; a module that exists and does not compile is an error.
1305 21 ▶sub resolve_function {
Subroutine resolve_function: called CC=6 SCAR=17.9
Pod undocumented
1306 21 my $spec = shift;
1307 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
1308 15 my($name, $arg) = @+{qw(name arg)};
1309 15 ▶ my @candidate = $name =~ /::/ ? $name : ("main::$name", "App::Greple::md::${name}::$name");
Branch: 1 branch
BranchTrueFalseTotal
$name =~ /::/u ? : 8 7 15
1310 165 ▶ no strict q(refs);
Subroutine BEGIN: called CC=1 SCAR=0.0
1311 15 for my $func (@candidate) {
1312 21 ▶ load_package($func =~ s/::\w+$//r) unless defined &$func;
Branch: 1 branch
BranchTrueFalseTotal
unless defined &$func 19 2 21
1313 18 ▶ return "&$func$arg" if defined &$func;
Branch: 1 branch
BranchTrueFalseTotal
if defined &$func 6 12 18
1314 }
1315 6 warn "--begin: $name: function not found\n";
1316 6 return;
1317 }
1318  
1319 19 ▶sub load_package {
Subroutine load_package: called CC=4 SCAR=13.9
Pod undocumented
1320 19 my $package = shift;
1321 19 ▶ return if $package eq q(main);
Branch: 1 branch
BranchTrueFalseTotal
if $package eq "main" 7 12 19
1322 12 my $file = $package =~ s{::}{/}gr . q(.pm);
1323 12 ▶ return if eval { require $file; 1 };
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { require $file; 1 } } 5 7 12
1324 7 ▶ die $@ unless $@ =~ /^Can't locate \Q$file\E /;
Branch: 1 branch
BranchTrueFalseTotal
unless $@ =~ /^Can't locate \Q$file\E /u 3 4 7
1325 }
1326  
1327 # The functions of --begin, parsed once. The names belong to main, as
1328 # with the --begin of greple.
1329 162 ▶sub begin_functions {
Subroutine begin_functions: called CC=3 SCAR=11.0
Pod undocumented
1330 state $func = [ map {
1331 162 ▶ 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
1332 21 my $spec = resolve_function($_);
1333 18 ▶ defined $spec ? parse_func({ PACKAGE => 'main' }, $spec) : ();
Branch: 1 branch
BranchTrueFalseTotal
defined $spec ? : 12 6 18
1334 } @opt_begin ];
1335 158 @$func;
1336 }
1337  
1338 162 ▶sub begin {
Subroutine begin: called CC=6 SCAR=17.9
Pod undocumented
1339 162 remove_controls();
1340 162 @refill_lines = @table_shift = ();
1341 162 for my $func (begin_functions()) {
1342 14 $func->call(@_);
1343 }
1344 158 ▶ $front_lines = do { my $f = front_matter($_); defined $f ? ($f =~ tr/\n//) + 1 : 0 };
Branch: 1 branch
BranchTrueFalseTotal
defined $f ? : 11 147 158
1345 158 ▶ refill() if $config->{refill};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"refill"} 18 140 158
1346 158 ▶ colorize() if $config->{colorize};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"colorize"} 87 71 158
1347 158 ▶ format_table() if $config->{table};
Branch: 1 branch
BranchTrueFalseTotal
if $config->{"table"} 142 16 158
1348 }
1349  
1350 142 ▶sub format_table {
Subroutine format_table: called CC=17 SCAR=28.3
Pod undocumented
1351 # lattice (or pipe) has column separators. 3line and simple have
1352 # none and a header rule per column: 3line adds a full-width rule
1353 # above and below, simple the header rule below. They are formatted
1354 # as in rule mode and the separators are blanked.
1355 142 my $style = $config->{table_style};
1356 142 ▶ my $open = $style eq '3line' || $style eq 'simple';
Condition100%3/3
$style eq '3line' || $style eq 'simple'
l!l&&r!l&&!r
44134
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
1357 142 ▶ my $sep = ($config->{rule} || $open) ? "\x{2502}" : '|'; # │ or |
Branch: 1 branch
BranchTrueFalseTotal
$config->{'rule'} || $open ? : 141 1 142
Condition100%3/3
$config->{"rule"} or $open
l!l&&r!l&&!r
13921
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
1358  
1359 # A row may have spaces after the last pipe (GFM ignores them); they
1360 # are allowed in the block and removed, so that every row ends in
1361 # the same column for ansicolumn.
1362 142 s{(^ {0,3}\|.+\|\h*\n){3,}}{
1363 242 my $block = $& =~ s/\h+$//mgr;
1364 242 my $line = 1 + (substr($_, 0, $-[0]) =~ tr/\n//);
1365 242 my $lines = $& =~ tr/\n//;
1366 242 my($right, $center) = parse_separator(\$block);
1367 242 my @sep_opt;
1368 # An escaped pipe (\|) is not a column separator (GFM). It is
1369 # left as written: backslash escapes are not processed yet.
1370 242 ▶ if ($config->{table_trim}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($config->{'table_trim'}) { } 238 4 242
1371 238 @sep_opt = ('-rs', '\s*(?<!\\\\)\|\s*', '--item-format= %s ', '--table-remove=1,-0', '--padding');
1372 } else {
1373 4 $_++ for @$right, @$center;
1374 4 @sep_opt = ('-rs', '(?<!\\\\)\|');
1375 }
1376 242 ▶ my @align = (
Branch: 2 branches
BranchTrueFalseTotal
@$right ? : 47 195 242
@$center ? : 47 195 242
1377 @$right ? ('--table-right=' . join(',', @$right)) : (),
1378 @$center ? ('--table-center=' . join(',', @$center)) : (),
1379 );
1380 # Fit table into table_width and/or per-column widths (table_cell).
1381 # table_cell entries are colon separated because comma separates
1382 # config parameters; non-trim mode has a phantom first column.
1383 242 my @fit;
1384 242 ▶ if ($config->{table_width} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($config->{"table_width"} > 0) 121 121 242
1385 121 push @fit, '-w', $config->{table_width};
1386 }
1387 242 ▶ if ((my $cell = $config->{table_cell}) ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ((my $cell = $config->{"table_cell"}) ne "") 3 239 242
1388 3 $cell =~ tr/:/,/;
1389 3 ▶ $cell = "0,$cell" unless $config->{table_trim};
Branch: 1 branch
BranchTrueFalseTotal
unless $config->{"table_trim"} 1 2 3
1390 3 push @fit, '--cell', $cell;
1391 }
1392 242 ▶ if ((my $mark = $config->{table_wrap_mark}) ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ((my $mark = $config->{"table_wrap_mark"}) ne "") 4 238 242
1393 4 push @fit, '--table-wrap-mark', $mark;
1394 }
1395 242 ▶ if ((my $mark = $config->{table_cell_mark}) ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ((my $mark = $config->{"table_cell_mark"}) ne "") 107 135 242
1396 # the header row and the separator row (to ansicolumn a row of
1397 # "-" cells) are the two header rows and get no mark
1398 107 push @fit, '--table-cell-mark', $mark, '--table-head', 2;
1399 }
1400 # How cells are wrapped is given explicitly, so that it does not
1401 # change with the user's ~/.ansicolumnrc
1402 242 my @wrap = map { "--$_=" . $config->{"table_$_"} } qw(runin runout boundary linebreak);
1403 242 my $formatted = call_ansicolumn($block, @sep_opt, '-o', $sep, '-t', '--cu=1', @align, @fit, @wrap);
1404 242 my $table = fix_separator($formatted, $sep);
1405 242 ▶ if ($open) {
Branch: 1 branch
BranchTrueFalseTotal
if ($open) 20 222 242
1406 # blank the column separators and add the rules
1407 20 $table =~ tr/\x{2502}\x{253C}\x{251C}\x{2524}/ /;
1408 20 ▶ if ($style eq '3line') {
Branch: 1 branch
BranchTrueFalseTotal
if ($style eq '3line') { } 10 10 20
1409 10 my($first) = $table =~ /^(.*)$/m;
1410 10 my $rule = "\x{2500}" x ansi_width($first);
1411 10 $table = "$rule\n$table$rule\n";
1412 } else {
1413 10 my($rule) = $table =~ /^([\x{2500} ]+)$/m;
1414 10 ▶ $table .= "$rule\n" if defined $rule;
Branch: 1 branch
BranchTrueFalseTotal
if defined $rule 10 0 10
1415 }
1416 20 ▶ $table =~ s{^[\x{2500} ]+$}{ $& =~ tr/\x{2500}/-/r }mge unless $config->{rule};
Branch: 1 branch
BranchTrueFalseTotal
unless $config->{"rule"} 8 12 20
1417 }
1418 242 push @table_shift, [ $line, ($table =~ tr/\n//) - $lines ];
1419 242 $table;
1420 }mge;
1421 }
1422  
1423 249 ▶sub parse_separator {
Subroutine parse_separator: called CC=3 SCAR=11.0
Pod undocumented
1424 249 my $blockref = shift;
1425 249 my $SEP = qr/^\h*+\|(\h*+:?+-++:?+\h*+\|)++\h*+$/mn;
1426 249 my ($sep_line) = $$blockref =~ /($SEP)/;
1427 249 ▶ return ([], []) unless defined $sep_line;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $sep_line 1 248 249
1428 248 my @cells = split /\|/, $sep_line, -1;
1429 248 shift @cells; pop @cells;
1430 248 s/^\h+|\h+$//g for @cells;
1431 248 my @right = grep { $cells[$_-1] =~ /^-+:$/ } 1..@cells;
1432 248 my @center = grep { $cells[$_-1] =~ /^:-+:$/ } 1..@cells;
1433 # Minimize dashes so separator width doesn't inflate column widths
1434 248 $$blockref =~ s{$SEP}{ ${^MATCH} =~ s/:?-+:?/-/gr }mpe;
1435 248 (\@right, \@center);
1436 }
1437  
1438 # Color the code of fenced code blocks by a highlighter of
1439 # Text::ANSI::Highlight: the one of the name in the config highlight,
1440 # or its default for 1. Takes [ language, code ] of each block, and
1441 # returns as many: the code in colors, or undef for a block which is
1442 # not colored, as one with no language or with one the highlighter
1443 # does not know. All are undef when the module, the highlighter or
1444 # its command is not there, and the blocks are shown as they are.
1445 #
1446 # All the blocks are given at once, and each is colored by itself.
1447 # What comes back is the code which was given, with colors, so the
1448 # lines are those of the file.
1449 86 ▶sub highlight_code {
Subroutine highlight_code: called CC=5 SCAR=16.1
Pod undocumented
1450 86 my @code = @_;
1451 86 my @none = (undef) x @code;
1452 86 ▶ @code or return @none;
Branch: 1 branch
BranchTrueFalseTotal
@code or return @none 58 28 86
1453 58 my $name = $config->{highlight};
1454 58 ▶ my $hl = eval {
Branch: 1 branch
BranchTrueFalseTotal
my $hl = eval { do { require Text::ANSI::Highlight; "Text::ANSI::Highlight"->new($name eq 1 ? () : $name) } } or return @none 57 1 58
1455 58 require Text::ANSI::Highlight;
1456 58 ▶ Text::ANSI::Highlight->new($name eq '1' ? () : $name);
Branch: 1 branch
BranchTrueFalseTotal
$name eq '1' ? : 54 4 58
1457 } or return @none;
1458 57 my @color = eval { $hl->highlight(@code) };
1459 57 ▶ @color == @code ? @color : @none;
Branch: 1 branch
BranchTrueFalseTotal
@color == @code ? : 57 0 57
1460 }
1461  
1462 242 ▶sub call_ansicolumn {
Subroutine call_ansicolumn: called CC=3 SCAR=11.0
Pod undocumented
1463 242 my ($text, @args) = @_;
1464 242 require Command::Run;
1465 242 require App::ansicolumn;
1466 Command::Run->new
1467 ->command(\&App::ansicolumn::ansicolumn, @args)
1468 ->with(stdin => $text,
1469 242 ▶ $config->{nofork} ? (nofork => 1, raw => 1) : ())
Branch: 1 branch
BranchTrueFalseTotal
$config->{'nofork'} ? : 238 4 242
Condition50%1/2
"Command::Run"->new->command(\&App::ansicolumn::ansicolumn, @args)->with("stdin", $text, $config->{"nofork"} ? ("nofork", 1, "raw", 1) : ())->update->data // ""
l!l
2420
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
1470 ->update
1471 ->data // '';
1472 }
1473  
1474 242 ▶sub fix_separator {
Subroutine fix_separator: called CC=7 SCAR=19.5
Pod undocumented
1475 242 my ($text, $sep) = @_;
1476 242 ▶ my $sep_re = $sep eq "\x{2502}" ? "\x{2502}" : '\\|';
Branch: 1 branch
BranchTrueFalseTotal
$sep eq "\x{2502}" ? : 238 4 242
1477 242 $text =~ s{^(\h*?)($sep_re)?((?:\h*-+\h*$sep_re)*\h*-+\h*)($sep_re)?(\h*?)$}{
1478 242 my($pre, $left, $mid, $right, $post) = ($1, $2, $3, $4, $5);
1479 242 ▶ if ($sep eq "\x{2502}") {
Branch: 1 branch
BranchTrueFalseTotal
if ($sep eq "\x{2502}") { } 238 4 242
1480 238 ▶ ($pre =~ tr[ ][\x{2500}]r)
Branch: 2 branches
BranchTrueFalseTotal
defined $left ? : 4 234 238
defined $right ? : 4 234 238
1481 . (defined $left ? "\x{251C}" : '')
1482 . ($mid =~ tr[\x{2502} -][\x{253C}\x{2500}\x{2500}]r)
1483 . (defined $right ? "\x{2524}" : '')
1484 . ($post =~ tr[ ][\x{2500}]r)
1485 } else {
1486 4 ▶ ($pre =~ tr[ ][-]r)
Branch: 2 branches
BranchTrueFalseTotal
defined $left ? : 0 4 4
defined $right ? : 0 4 4
1487 . (defined $left ? '|' : '')
1488 . ($mid =~ tr[ ][-]r)
1489 . (defined $right ? '|' : '')
1490 . ($post =~ tr[ ][-]r)
1491 }
1492 }xmeg;
1493 242 $text;
1494 }
1495  
1496 165 1;
1497  
1498 __DATA__
« blib/lib/App/Greple/md/Blocks.pm ↑ Summary blib/lib/App/Greple/md/widen.pm »