blib/lib/Tk/Markdown.pm

filter: Statementstmt 100% 11 / 11 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 4 / 4 Podpod n/a totaltotal 100% 15 / 15 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
↑ Summary
1 package Tk::Markdown;
2
3 1 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use warnings FATAL => 'all';
Subroutine BEGIN: called CC=1 SCAR=0.0
6
7 =head1 NAME
8
9 Tk::Markdown - display Markdown in a Text
10
11 =cut
12
13 our $VERSION = '0.09';
14
15 1 ▶use base qw(Tk::Derived Tk::Text);
Subroutine BEGIN: called CC=1 SCAR=0.0
16 use Tk::Font;
17 #use Tk::Carp qw/fatalsToDialog warningsToDialog tkDeathsNonFatal/;
18 ## commented out Tk::carp because it is not available in ppm.
19
20 Construct Tk::Widget 'Markdown';
21
22
23 =head1 SYNOPSIS
24
25 use Tk;
26 use Tk::Markdown;
27
28 my $mw = Tk::MainWindow->new();
29 my $mdt = $mw->Markdown();
30
31 my $markdown = q~# Heading 1
32 ## Heading 2
33 ### Heading 3
34 #### Heading 4
35 ##### Heading 5
36 ###### Heading 6
37
38 * list 1
39 ** list 2
40 *** list 3
41 **** list 4
42 ***** list 5
43 ****** list 6
44
45 Source shown in monofont
46 another line of source code here
47 ~;
48
49 $mdt->insert('0.0', $markdown);
50
51
52 =head1 DESCRIPTION
53
54 Tk::Markdown is a widget to render L<Markdown|https://en.wikipedia.org/wiki/Markdown> in a L<Tk::Text> widget.
55
56
57 =head1 METHODS
58
59 =head2 insert
60
61 Whenever insert is called on the Markdown widget, some translation is done on the text in order to display it nicely as Markdown.
62 Tables are reformatted (if the line starts with a bar) and headers are tagged with different fonts.
63
64 This module has very basic support for Markdown and there is still plenty to do, e.g. links, images, etc.
65
66 =cut
67
68 ### add the processing functionality to the insert method
69 sub insert {
70 my ($self,$index,$content) = @_;
71 my $res = $self->SUPER::insert($index,FormatMarkdown($content));
72 if(! $self->{inserting}) { ### don't allow recursion...
73 $self->{inserting} = 1;
74 $self->PaintMarkdown();
75 # $self->TransformTk();
76 $self->see("1.0");
77 $self->{inserting} = 0;
78 }
79 return $res;
80 }
81
82
83
84 ### these few subs are taken directly from ROText...
85
86 =head2 defaultStyles
87
88 Called internally. You can access the styles like this:
89
90 use Data::Dumper;
91 print Dumper $o->{styles};
92
93 To set styles, use C<$o-E<gt>setStyles>
94
95 =cut
96
97 ### named styles, used in _rules_ below.
98 sub defaultStyles {
99 my $self = shift;
100 my @sans = qw/-family Helvetica -size/;
101 my @serif = qw/-family Times -size/;
102 my @mono = qw/-family Courier -size/;
103 my @bold = qw/-weight bold/;
104 my @italic = qw/-slant italic/;
105 my @under = qw/-underline 1/;
106 my @over = qw/-overstrike 1/;
107 my %ss = (
108 body => ['black',@serif,12],
109 h1 => ['navy',@sans,18,@bold,@italic],
110 h2 => ['firebrick',@sans,18,@bold],
111 h3 => ['darkgreen',@sans,16,@bold,@italic],
112 h4 => ['brown',@sans,16,@bold],
113 h5 => ['seagreen',@sans,14,@bold,@italic],
114 h6 => ['darkslateblue',@sans,14,@bold],
115 code => ['DarkSlateGray',@mono,10],
116 list => ['black', @sans, 10],
117 );
118 #foreach(keys %ss){
119 # print @{$ss{$_}} % 2, "\n";
120 #}
121 $self->{'styles'} = \%ss;
122 $self->setStyles(%ss);
123 }
124
125
126 =head2 setStyles
127
128 The argument is a hash of styles. The keys are predefined names, currently:
129
130 =over
131
132 =item body
133
134 =item h1
135
136 =item h2
137
138 =item h3
139
140 =item h4
141
142 =item h5
143
144 =item h6
145
146 =item code
147
148 =item list
149
150 =back
151
152 And the values are listrefs, in which the first element is the C<-foreground> color, and the remainder are options for the L<Tk::Font> object.
153 For example:
154
155 $o->setStyles(
156 'h1' => [ qw/ red -family Times -weight bold -size 32 / ],
157 )
158
159 =cut
160
161
162 ### add styles as tags to the text
163 sub setStyles {
164 my ($self,%styles) = @_;
165 %{$self->{styles}} = (%{$self->{styles}},%styles);
166 foreach (keys %styles) {
167 my ($color,@font) = @{$styles{$_}};
168 $self->tagConfigure($_, -foreground=>$color, -font=>$self->Font(@font));
169 }
170 my ($color,@font) = @{$styles{body}};
171 $self->configure(-font=>$self->Font(@font),-foreground=>$color);
172 }
173
174
175 =head2 FormatMarkdown
176
177 This is called internally. It prettifies Markdown prior to insertion.
178
179 Document content is treated as text, never as Perl code. Tags such as
180 C<< <% ... %> >> and C<< <%= ... %> >> are preserved literally. Applications
181 that generate Markdown dynamically should do so before calling this formatter.
182
183 This guarantee applies to Tk::Markdown. The separate Tk::MarkdownTk module
184 adds its own scripting features and must not be used with untrusted documents.
185
186 =cut
187
188 ### reformat the text of certain Markdown components to make them prettier...
189 sub FormatMarkdown {
190 my $markdown = shift;
191
192 my @lines = split /\n/, $markdown;
193 my $i = 0;
194 while($i < @lines) {
195 if($lines[$i] =~ /^\|/){ # tables!
196 my $j = $i;
197 while($lines[$j+1] =~ /^\||^-+$/){ $j++; }
198 @lines[$i..$j] = FormatMarkdownTable(@lines[$i..$j]);
199 $i = $j;
200 }
201 $i++;
202 }
203 $markdown = join("\n", @lines);
204 return $markdown;
205 }
206
207
208 =head2 FormatMarkdownTable
209
210 This is called internally. It prettifies Markdown tables.
211
212 =cut
213
214 ### reformat the text of tables to make them prettier...
215 sub FormatMarkdownTable {
216 s/\s*\|\s*/|/g foreach @_;
217 s/^\s*\|\s*// foreach @_;
218 s/\s*\|\s*$// foreach @_;
219 my @colwidths = map {0} split /\|/, $_[0];
220 foreach my $row (@_) {
221 next if $row =~ /^-+$/;
222 my @row = split /\|/, $row;
223 @colwidths = map {$colwidths[$_] > length($row[$_]) ? $colwidths[$_] : length($row[$_])} 0..$#row;
224 }
225 my $sum = 0;
226 foreach (@colwidths) {
227 $sum += $_;
228 $sum += 3;
229 }
230 my $hr = '-' x $sum;
231 my @table;
232 foreach my $row (@_) {
233 if($row =~ /^-+$/){
234 push @table, $hr;
235 next;
236 }
237 my @row = split /\|/, $row;
238 foreach my $j(0..$#row) {
239 my $diff = $colwidths[$j] - length($row[$j]);
240 my $spaces = ' ' x $diff;
241 # if a number...
242 if($row[$j] =~ /^[-+]?(?:0[bx]|)\d+\.?\d*[fe][+-]?\d*$/){
243 $row[$j] = $spaces . $row[$j];
244 }
245 else {
246 $row[$j] .= $spaces;
247 }
248 $row[$j] = " $row[$j] ";
249 }
250 push @table, "|".join('|', @row)."|";
251 }
252 return @table;
253 }
254
255
256 =head2 PaintMarkdown
257
258 This is called internally. It applies the styles.
259
260 =cut
261
262 ### Add tags and substitute some characters to format the Markdown.
263 sub PaintMarkdown {
264 my $self = shift;
265 my @rules = (
266 ### HEADERS
267 [qr/^#[^#].*$/m, 'h1', qr/^#\s*(?=[^#])/m ,''],
268 [qr/^##[^#].*$/m, 'h2', qr/^##\s*(?=[^#])/m, ''],
269 [qr/^###[^#].*$/m, 'h3', qr/^###\s*(?=[^#])/m, ''],
270 [qr/^####[^#].*$/m, 'h4', qr/^####\s*(?=[^#])/m, ''],
271 [qr/^#####[^#].*$/m, 'h5', qr/^#####\s*(?=[^#])/m, ''],
272 [qr/^######[^#].*$/m, 'h6', qr/^######\s*(?=[^#])/m, ''],
273
274 ### TABLES
275 [qr/^\|.*\|$|^-+$|^\s\s\s\s/m, 'code', '', ''],
276
277 ### LISTS
278 [qr/^\*[^*].*$/m, 'list', qr/^\*(?=[^*])/, " \x{2022} "],
279 [qr/^\*\*[^*].*$/m, 'list', qr/^\*\*(?=[^*])/, " \x{25E6} "],
280 [qr/^\*\*\*[^*].*$/m, 'list', qr/^\*\*\*(?=[^*])/, " \x{2022} "],
281 [qr/^\*\*\*\*[^*].*$/m, 'list', qr/^\*\*\*\*(?=[^*])/, " \x{25E6} "],
282 [qr/^\*\*\*\*\*[^*].*$/m, 'list', qr/^\*\*\*\*\*(?=[^*])/, " \x{2022} "],
283 [qr/^\*\*\*\*\*\*[^*].*$/m, 'list', qr/^\*\*\*\*\*\*(?=[^*])/, " \x{25E6} "],
284
285 ### CODE
286 [qr/^\s\s\s\s.*$/m, 'code', '', ''],
287 );
288
289 foreach(@rules) {
290 my ($re,$tag,$search,$replace) = @$_;
291 $self->FindAll('-regexp','-case', $re );
292 my @i = $self->tagRanges('sel');
293 $self->tagAdd($tag,@i) if @i;
294 if($search){
295 #print "$search\n";
296 $self->FindAndReplaceAll('-regexp','-case', $search, $replace);
297 }
298 }
299 }
300
301
302 =head2 clipEvents
303
304 This copied directly from L<Tk::ROText>.
305
306 =cut
307
308 sub clipEvents {
309 return qw[Copy];
310 }
311
312
313 =head2 ClassInit
314
315 This is copied directly from L<Tk::ROText>.
316
317 =cut
318
319 sub ClassInit {
320 my ($class,$mw) = @_;
321 my $val = $class->bindRdOnly($mw);
322 my $cb = $mw->bind($class,'<Next>');
323 $mw->bind($class,'<space>',$cb) if (defined $cb);
324 $cb = $mw->bind($class,'<Prior>');
325 $mw->bind($class,'<BackSpace>', $cb) if (defined $cb);
326 $class->clipboardOperations($mw,'Copy');
327 return $val;
328 }
329
330
331 =head2 Populate
332
333 This is copied and modified from L<Tk::ROText>. The modification is the addition of a call to C<setDefaultStyles>. That's all.
334
335 =cut
336
337 sub Populate {
338 my ($self,$args) = @_;
339 $self->SUPER::Populate($args);
340 my $m = $self->menu->entrycget($self->menu->index('Search'), '-menu');
341 $m->delete($m->index('Replace'));
342 $self->ConfigSpecs(-background=>['SELF'], -foreground=>['SELF'],);
343 $self->defaultStyles(); ### Jimi added this line... does a bit more setup.
344 }
345
346
347 =head2 Tk::Widget::ScrlMarkdown
348
349 Copied and adapted from L<Tk::ROText>.
350
351 =cut
352
353 sub Tk::Widget::ScrlMarkdown { shift->Scrolled('Markdown' => @_) }
354
355
356 =head1 SEE ALSO
357
358 L<Tk::MarkdownTk>, L<Tk::Text>
359
360
361 =head1 AUTHOR
362
363 Jimi Wills.
364
365 Currently maintained by Alexander Becker.
366
367 =head1 BUGS
368
369 Known issue: Tables do not work.
370
371 Please report any bugs or feature requests via GitHub: L<https://github.com/asb-capfan/Tk-Markdown>
372
373
374
375
376 =head1 SUPPORT
377
378 You can find documentation for this module with the perldoc command.
379
380 perldoc Tk::Markdown
381
382
383 You can also look for information at:
384
385 =over 4
386
387 =item * GitHub (report bugs here):
388
389 L<https://github.com/asb-capfan/Tk-Markdown>
390
391 =back
392
393
394 =head1 LICENSE AND COPYRIGHT
395
396 Copyright 2013 JimiWills.
397
398 This program is free software; you can redistribute it and/or modify it
399 under the terms of the the Artistic License (2.0). You may obtain a
400 copy of the full license at:
401
402 L<http://www.perlfoundation.org/artistic_license_2_0>
403
404 Any use, modification, and distribution of the Standard or Modified
405 Versions is governed by this Artistic License. By using, modifying or
406 distributing the Package, you accept this license. Do not use, modify,
407 or distribute the Package, if you do not accept this license.
408
409 If your Modified Version has been derived from a Modified Version made
410 by someone other than you, you are nevertheless required to ensure that
411 your Modified Version complies with the requirements of this license.
412
413 This license does not grant you the right to use any trademark, service
414 mark, tradename, or logo of the Copyright Holder.
415
416 This license includes the non-exclusive, worldwide, free-of-charge
417 patent license to make, have made, use, offer to sell, sell, import and
418 otherwise transfer the Package with respect to any patent claims
419 licensable by the Copyright Holder that are necessarily infringed by the
420 Package. If you institute patent litigation (including a cross-claim or
421 counterclaim) against any party alleging that the Package constitutes
422 direct or contributory patent infringement, then this Artistic License
423 to you shall terminate on the date that such litigation is filed.
424
425 Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER
426 AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
427 THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
428 PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY
429 YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
430 CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR
431 CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE,
432 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
433
434
435 =cut
436
437 1; # End of Tk::Markdown
↑ Summary