blib/lib/App/Greple/md.pm

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