-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpantcl.tcl
executable file
·1515 lines (1447 loc) · 56.1 KB
/
pantcl.tcl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env tclsh
# pantcl - standalone application and pandoc filter
# for literate programming
# Author: Detlef Groth, Schwielowsee, Germany
# Version: 0.9.12 - 2023-04-17
# Version: 0.9.13 - 2023-09-07
# Version: 0.9.14 - 2024-11-27
# Version: 0.10.0 - 2024-11-29
# Version: 0.10.1 - 2024-12-19
# Version: 0.10.2 - 2024-12-24
package provide pantcl 0.10.2
namespace eval ::pantcl { }
if {[llength $argv] > 0 && ([lsearch -exact $argv -v] >= 0 || [lsearch -exact $argv --version] >= 0)} {
puts "[package present pantcl]"
exit 0
}
set HELPFILTER {
Usage (filter): pandoc \[pandoc arguments\] --filter $argv0 \[pandoc arguments\]
This is the pandoc Tcl filter which should be run as filter for the pandoc document
converter with a syntax like shown above. This filter allows you to embed Tcl code
and other tools code within Markdown and other Text format documents.
For a list of filters which are available see below.
}
set FILTERS {
Available Filters:
- ```{.abc} ABC music notation code```
- ```{.cmd} Command line application code```
- ```{.dot} GraphViz dot/neato code```
- ```{.emf} MicroEmacs macro code```
- ```{.eqn} EQN equations```
- ```{.julia} Julia code```
- ```{.mmd} Mermaid diagram code```
- ```{.mtex} LaTeX equations```
- ```{.pic} PIC diagram code```
- ```{.pik} Pikchr diagram code```
- ```{.pipe} Embed Python, R or Octave code```
- ```{.puml} PlantUML diagram code```
- ```{.rplot} R plot code```
- ```{.sqlite} SQLite3 code code```
- ```{.tcl} Tcl code```
- ```{.tcrd} Songs with embedded chords```
- ```{.tdot} Tcl package tdot code```
- ```{.tsvg} Tcl package tsvg code```
}
set HELPSTANDALONE {
Usage (standalone):
$argv0 \[arguments\] infile outfile \[options\] \[--no-pandoc\]
Converting the given infile to outfile.
If infile is a source code file ending with `.tcl`, `.R` or `.py,
it is assumed that it contains mkdoc documentation.
This is embedded Markdown markup after a #' comment.
In case pandoc is installed the pantcl application will will be used
as filter afterwards.
To set the default for the evaluation of filters to TRUE you can run the
application like this:
FILTEREVAL=1 $argv0 \[arguments\] infile \[outfile\] \[options\] \[--no-pandoc\]
Hint: The --no-pandoc option is not required for the pantcl.mbin application as
this can be only used standalone, but not as a pandoc filter.
Arguments:
--help - display this help page
--version - display the pantcl version
--gui - start the graphical user interace, in this case outfile can
be omitted
infile - the input filename, can be Markdown, Tcl, R,
Python etc with embedded Makrdown behind #' comments
outfile - the output file either Markdown (.md) or HTML (.html) or
source code files if the outfile has a extension like `.tcl`
or `.R` etc.
Options:
--base64 BOOL - should local image and css files being included using base64 encoding
creating standalone HTML files
--javascript LIB|FILE - should the online Javascript library LIB or the file FILE being included
in the header section, possible LIB is highlightjs
--no-pandoc - do not work as a pandoc filter, but as a standalone application
--mathjax BOOL - should mathjax library being included to display formulas, default: false
--refresh INT - should a refresh header included into the HTML output to refresh the page
automatically every N seconds
--tangle CHUNK - exteact all code from chunk type CHUNK
Examples:
$argv0 --version - display the version
$argv0 infile outfile --no-pandoc - use the standalone converter
$argv0 infile outfile --tangle .tcl - extract all code from .tcl chunks
$argv0 infile outfile --mathjax true - render equations within the document
$argv0 infile outfile --javascript highlightjs --no-pandoc
- support highlighting source code
$argv0 infile outfile --refresh 10 --no-pandoc
- support HTML refreshing every N seconds
Usage (GUI): $argv0 --gui \[infile\]
Supported infiles: abc, dot, eqn, mmd, mtex, pic, pik, puml, rplot, tdot, tsvg\n"
Examples:
$argv0 pantcl.tcl pantcl.html --css mini.css
will extract the documentation from the file pantcl.tcl itself
and create a HTML file executing all filters available.
All usual pandoc options can be passed after the output file name
Version: [package present pantcl]
Homepage: https://github.com/mittelmark/pantcl
Author: Detlef Groth, University of Potsdam, Germany
License: MIT
Readme: http://htmlpreview.github.io/?https://github.com/mittelmark/pantcl/blob/master/pantcl/Readme.html
}
# allow loading Tcl packages and filters
set appdir [file dirname [info script]]
if {[file exists [file join $appdir lib]]} {
lappend auto_path [file normalize [file join $appdir lib]]
package require tsvg
}
if {[llength $argv] > 0 && ([lsearch -regex $argv {-h$}] >= 0 || [lsearch -regex $argv {--help$}] >= 0)} {
if {![catch {package require rl_json}]} {
puts [subst $HELPFILTER]
}
puts [subst $HELPSTANDALONE]
puts $FILTERS
exit 0
}
set css {
html {
overflow-y: scroll;
}
body {
color: #444;
font-family: Georgia, Palatino, 'Palatino Linotype', Times, 'Times New Roman', serif;
line-height: 1.2;
padding: 1em;
margin: auto;
max-width: 1100px;
}
h1, h2, h3, h4, h5, h6 {
color: #111;
line-height: 115%;
margin-top: 1em;
font-weight: normal;
}
h1 {
text-align: center;
}
h2.author, h2.date {
text-align: center;
}
a {
color: #0645ad;
text-decoration: none;
}
a:visited { color: #0b0080; }
a:hover { color: #06e; }
a:active { color: #faa700; }
a:focus { outline: thin dotted; }
p { margin: 0.5em 0; }
p.author, p.date {
font-size: 110%;
text-align: center;
}
img { max-width: 100%; }
figure { text-align: center ; }
pre, blockquote pre {
border-top: 0.1em #9ac solid;
background: #e9f6ff;
padding: 10px;
border-bottom: 0.1em #9ac solid;
}
pre, code, kbd, samp {
color: #000;
font-family: Monaco, 'courier new', monospace;
font-size: 90%;
}
pre code.tclinn {
color: #ff2222;
}
pre code.tclout {
color: #3366ff;
}
code.r {
color: #770000;
}
pre.pipeout {
background: #ffefef;
}
pre {
white-space: pre;
white-space: pre-wrap;
word-wrap: break-word;
}
code span.kw { color: #007020; font-weight: normal; }
pre.sourceCode { background: #fff6f6; }
blockquote {
margin: 0;
padding-left: 3em;
}
hr {
display: block;
height: 2px;
border: 0;
border-top: 1px solid #aaa;
border-bottom: 1px solid #eee;
margin: 1em 0;
padding: 0;
}
table {
border-collapse: collapse;
border-bottom: 2px solid;
}
table thead tr th {
background-color: #fde9d9;
text-align: left;
padding: 10px;
border-top: 2px solid;
border-bottom: 2px solid;
}
table td {
background-color: #fff9e9;
text-align: left;
padding: 10px;
}
.left {
display: flex;
justify-content: flex-start;
}
}
# some helper functions
# some generic helper functions
proc ::pantcl::luniq {L} {
# removes duplicates without sorting the input list
set t {}
foreach i $L {if {[lsearch -exact $t $i]==-1} {lappend t $i}}
return $t
}
proc ::pantcl::getCacheDir {} {
if {[info exists ::env(HOME)]} {
set path [file join $::env(HOME) .cache pantcl]
} elseif {[info exists ::env(APPDATALOCAL)]} {
set path [file join $::env(APPDATALOCAL) pantcl]
} else {
set path pantcl
}
if {![file exists $path]} {
file mkdir $path
}
return $path
}
# interp create mdi
#
# mdi eval "set auto_path \[list [luniq $auto_path]\]"
catch {
# if available load filters
package require tclfilters
}
# load other tcl based filters
foreach file [glob -nocomplain [file join [file dirname [info script]] filter filter*.tcl]] {
catch {
source $file
}
}
if {[lsearch $argv --pantcl-filter] >= 0} {
# TODO: check if this works in standalone mode
# should not work in pandoc mode (yet)
set index [lsearch $argv --pantcl-filter]
incr index
if {![file exists [lindex $argv $index]]} {
puts "Error: File [lindex $argv $index] does not exists!"
exit 0
} else {
set fname [lindex $argv $index]
source $fname
set argv [lreplace $argv [expr {$index-1}] $index]
}
}
proc ::pantcl::debug {jsonData} {
puts [::rl_json::json keys $jsonData]
}
proc ::pantcl::tangle {args} {
set outfile [lindex $args 0]
set idx 0
set infile ""
set outfile ""
set type ""
foreach arg $args {
if {[lindex $args $idx] eq "--tangle"} {
# nop
} elseif {$infile eq ""} {
set infile [lindex $args $idx]
} elseif {$outfile eq ""} {
set outfile [lindex $args $idx]
} elseif {$type eq ""} {
set type [lindex $args $idx]
}
incr idx
}
if {$type eq ""} {
set type [string range [string tolower [file extension $outfile]] 1 end]
} else {
set type [regsub -- {^\.} $type ""]
}
if {$outfile ni [list stdout -]} {
set out [open $outfile w 0600]
} else {
set out stdout
}
if [catch {open $infile r} infh] {
return -code error "Cannot open $infile: $infh"
} else {
set flag false
while {[gets $infh line] >= 0} {
set line [regsub {^\s*#' } $line ""]
if {[regexp "^\[> \]{0,2}```\{\.?$type\[^a-zA-Z\]" $line]} {
set flag true
continue
} elseif {$flag && [regexp {^[> ]{0,2}```} $line]} {
set flag false
continue
} elseif {$flag} {
puts $out $line
}
}
close $infh
if {$outfile ni [list stdout -]} {
close $out
}
}
}
set lineFilter false
proc ::pantcl::lineFilter {argv} {
global lineFilter
set lineFilter true
if {[info exists ::env(FILTEREVAL)]} {
set evalvar $::env(FILTEREVAL)
} else {
set evalvar false
}
set args [split $argv " "]
set infile [lindex $args 0]
set outfile [lindex $args 1]
set mode md
set yamldict [dict create]
if {![regexp {.+\.[a-zA-Z]*md$} $outfile] && ![regexp -nocase {.+\.html} $outfile]} {
error "Error: currently only conversion from Markdown to Markdown or to HTML is possible!"
}
if {[regexp -nocase {.+\.html} $outfile]} {
set mode html
set outfile [regsub {\.html} $outfile "-out.md"]
}
if {![file exists $infile]} {
error "Error: $infile does not exists"
}
if {[lsearch $argv "--metadata-file"] > -1} {
set idx [lsearch $argv "--metadata-file"]
incr idx
#puts "metafile $idx"
if {[file exists [lindex $argv $idx]]} {
set metafile [lindex $argv $idx]
set fin [open $metafile r]
set txt [read $fin]
close $fin
#puts $txt
set yamldict [yaml::yaml2dict $txt]
}
}
if [catch {open $infile r} infh] {
error "Cannot open $infile: $infh"
} else {
set out [open $outfile w 0600]
set i 0
set n 0
set flag false
set yamlflag false
set yamltext ""
set filt "xxx"
set ind ""
# TODO: should be default false??
set ddef [dict create echo true results show eval $evalvar]
set pre false
while {[gets $infh line] >= 0} {
incr n
if {$n < 5 && !$yamlflag && [regexp {^---} $line]} {
set yamlflag true
} elseif {$yamlflag && [regexp {^---} $line]} {
set yamldict [dict merge [yaml::yaml2dict $yamltext] $yamldict]
set yamlflag false
set yamltext ""
dict for {key val} $yamldict {
if {[dict exists $yamldict $key filter]} {
set fname [dict get $yamldict $key filter]
if {[file exists $fname]} {
source $fname
} else {
puts stderr "Error: File `$fname` does not exists!"
}
}
}
if {[dict exists $yamldict bibliography]} {
package require citer
citer::bibliography [dict get $yamldict bibliography]
}
} elseif {$yamlflag} {
foreach key [list title author date] {
if {[regexp "^${key}:" $line]} {
if {[dict exists $yamldict $key]} {
if {$key eq "date" && [dict exists $yamldict date] && \
[regexp {^[0-9]{10,}} [dict get $yamldict date]]} {
dict set yamldict date [clock format [dict get $yamldict date] -format "%Y-%m-%d"]
}
set line "${key}: [dict get $yamldict $key]"
}
}
}
append yamltext "$line\n"
}
if {!$pre && [regexp @ $line]} {
if {[regexp {\[@references ([^ ]+)\]} $line -> bibfile]} {
set line [lindex [filter-tcl "bibliography $bibfile\n" {eval true results asis}] 0]
} else {
set line [regsub {\[@references ([^ ]+)\]} $line "tcl bibliography \\1"]
set line [regsub -all {\[@([-A-Z0-9a-z]+)\]} $line "`tcl cite \\1`"]
set line [regsub -all {\[@([-A-Z0-9a-z]+);([-A-Z0-9a-z]+)\]} $line "`tcl cite \\1 \\2`"]
set line [regsub -all {\[@([-A-Z0-9a-z]+)\s*;\s*([-A-Z0-9a-z]+)\s*;\s*([-A-Z0-9a-z]+) \]} $line "`tcl cite \\1 \\2 \\3`"]
}
}
set x 0
while {!$pre && [regexp {`(r|py) +([^`]+)`} $line -> lang code]} {
if {$lang eq "r"} { set lang R }
if {$lang eq "py"} { set lang python }
set res [filter-pipe $code [dict create pipe $lang eval true]]
set res [regsub {.*>>>} [lindex $res 0] ""]
set res [string range $res [expr {[string length $code]+1}] end]
set res [regsub {.*\[1\] } $res ""]
set res [string trim $res]
#set res [regsub {^ +} $res ""]
#set res [regsub { +$} $res ""]
set line [regsub {`(r|py) +([^`]+)`} $line $res]
# to avoid endless loops
if {[incr x] > 10} {
break
}
}
# translate r-chunks into pipe chunks
if {[regexp {``` ?\{.*\}} $line]} {
set line [regsub {\{r(.*)\}} $line "{.pipe pipe=\"R\"\\1}"]
set line [regsub {\{py(.*)\}} $line "{.pipe pipe=\"python\"\\1}"]
set line [regsub {\{oc(.*)\}} $line "{.pipe pipe=\"octave\"\\1}"]
set line [regsub -all {TRUE} $line true]
set line [regsub -all {FALSE} $line false]
set line [regsub -all {,} $line " "]
}
# TODO: simple YAML parsing
if {[regexp {^>? ?\s{0,2}```} $line]} {
if {$pre} {
set pre false
} else {
set pre true
}
}
if {[regexp {^>? ?\s{0,2}``` ?\{\.} $line]} {
set dchunk [dict create]
set dchunk [dict merge $ddef $dchunk]
set ind ""
if {[regexp {^> } $line]} {
set ind "> "
}
regexp {``` ?\{\.([a-zA-Z0-9]+)\s*(.*).*\}.*} $line -> filt options
if {[dict exists $yamldict $filt]} {
set dchunk [dict merge $dchunk [dict get $yamldict $filt]]
}
# enable as well options with comma instead of space:
# like results="show",wait=1
set options [regsub {,([^ ])} $options " \\1"]
foreach {op} [split $options " "] {
foreach {key val} [split $op "="] {
set val [regsub -all {"} $val ""] ;#"
dict set dchunk $key $val
}
}
set flag true
set cont ""
} elseif {$flag && [regexp {^>? ?\s{0,2}```} $line]} {
set flag false
if {[info command filter-$filt] ne ""} {
set res [filter-$filt $cont $dchunk]
if {[dict get $dchunk echo]} {
# TODO: indentation adding if was there"
puts $out "$ind```${filt}inn\n$cont$ind```"
}
if {[lindex $res 0] ne ""} {
if {[dict get $dchunk results] eq "show"} {
# TODO: indentation adding if was there"
# remove trailing newline as we add our own
set r [regsub {\n$} [lindex $res 0] ""]
set r [string map {&gt; >} $r] ;#BUG in markdown lib?
puts $out "\n$ind```${filt}out\n$r\n$ind```"
} elseif {[dict get $dchunk results] eq "asis"} {
set ores [regsub {^```} [lindex $res 0] "\n"]
puts $out "$ores\n"
}
}
if {[lindex $res 1] ne ""} {
set title ""
if {[dict exists $dchunk title]} {
set title [dict get $dchunk title]
}
puts $out "\n!\[$title\]([lindex $res 1])"
}
}
set cont ""
} elseif {$flag} {
append cont "$line\n"
} else {
# TODO: more than one inline code per line
if {!$pre} {
while {[regexp {`\.?[A-Za-z]{1,4} .+`} $line]} {
set cont false
set eval false
set pipe python
set filt [regsub {.*?`\.?([A-Za-z]{1,4}) [^`]+`.*$} $line "\\1"]
if {$filt in [list "r" "R"]} {
set filt pipe
set pipe R
}
if {$filt in [list "py"]} {
set filt pipe
set pipe python
}
if {[dict exists $yamldict $filt eval]} {
if {[dict get $yamldict $filt eval]} {
set eval true
}
}
if {[info command filter-$filt] eq "filter-$filt" && $eval} {
set code [regsub {.*?`\.?[A-Za-z]{1,4} ([^`]+)`.*$} $line "\\1"]
if {[dict exists $yamldict $filt]} {
if {[dict exists $yamldict $filt]} {
set d [dict create {*}[dict get $yamldict $filt]]
dict set d pipe $pipe
dict set d terminal false
if {[dict exists $d eval] && [dict get $d eval]} {
set res [lindex [filter-$filt $code $d] 0]
set res [regsub -all "\n" $res " "]
set res [regsub {.+ ([^\s]+) ?$} $res "\\1"]
set line [regsub {(.*?)`\.?[A-Za-z]{1,4} ([^`]+)`(.+)} $line "\\1$res\\3"]
set cont true
}
}
}
}
if {!$cont} {
break
}
}
}
puts $out $line
}
}
close $infh
}
close $out
if {$mode eq "html"} {
if {![lsearch -glob $argv *-mathjax] > -1} {
if {[dict exists $yamldict mathjax] && [dict get $yamldict mathjax]} {
lappend argv -mathjax
lappend argv true
}
}
if {![lsearch -glob $argv *-base64] > -1} {
if {[dict exists $yamldict base64] && [dict get $yamldict base64]} {
lappend argv -base64
lappend argv true
}
}
if {![lsearch -glob $argv *-javascript] > -1} {
if {[dict exists $yamldict javascript] && [dict get $yamldict javascript] ne ""} {
lappend argv --javascript
lappend argv [dict get $yamldict javascript]
}
}
#puts $argv
if {![lsearch -glob $argv *-refresh] > -1} {
if {[dict exists $yamldict refresh] && [dict get $yamldict refresh]} {
lappend argv -refresh
lappend argv [dict get $yamldict refresh]
}
}
mkdoc::mkdoc $outfile [regsub -- {-out.md} $outfile ".html"] {*}[lrange $argv 2 end]
file delete $outfile
}
}
set runGui false
proc ::pantcl::runGui {argv} {
package require fview
fview::gui
set file false
foreach arg $argv {
if {[file exists $arg]} {
set ext [string range [file extension $arg] 1 end]
#puts $ext
fview::fileOpen $arg
fview::fileSave $arg
set file true
break
}
}
if {!$file} {
set ftemp [file temp].tsvg
set out [open $ftemp w 0600]
puts $out {package require tsvg
tsvg set code "" ;
tsvg set width 400
tsvg set height 400
tsvg rect -x 10 -y 10 -width 380 -height 380 \
-fill cornsilk
tsvg circle -cx 200 -cy 200 -r 120 -stroke black -stroke-width 2 -fill #eeffee
tsvg text -x 155 -y 180 "Hello TSVG"
tsvg text -x 135 -y 220 "Filter View World!"
}
close $out
fview::fileOpen $ftemp
fview::fileSave $ftemp
file delete $ftemp
}
}
# Gui mode
if {[llength $argv] > 0 && [lsearch $argv --gui] > -1} {
::pantcl::runGui $argv
set runGui true
}
# Standalone processing
# calling pandoc eventually itself
if {[catch {package require rl_json}]} {
if {[lsearch $argv --no-pandoc] < 0} {
lappend argv --no-pandoc
}
if {[llength $argv] == 1} {
puts "Usage: $argv0 \[arguments\] infile outfile \[options\]"
puts " Arguments are for instance --help or --version\n for options see --help"
exit
}
}
if {[info exists argv] && [llength $argv] > 1 && [file exists [lindex $argv 0]]} {
set pandoc true
if {[lsearch $argv --tangle] >= 0} {
pantcl::tangle {*}$argv
return
}
if {[lsearch $argv --no-pandoc] > 1 || [auto_execok pandoc] eq ""} {
package require yaml
package require mkdoc::mkdoc
set idx [lsearch $argv --no-pandoc]
if {$idx > 0} {
set argv [lsearch -inline -all -not -exact $argv --no-pandoc]
}
set pandoc false
}
if {[file extension [lindex $argv 1]] eq ".html" && [lsearch [lrange $argv 1 end] --css] == -1} {
if {![file exists pantcl.css]} {
set out [open pantcl.css w 0600]
puts $out $css
close $out
}
lappend argv --css
lappend argv pantcl.css
}
if {[file extension [lindex $argv 0]] in [list .tcl .tm .py .R .r .c .cxx .cpp .m .pl .pm .h .hpp .hxx]} {
set tempfile [file tempfile].md
set filename [lindex $argv 0]
set infile [lindex $argv 0]
set out [open $tempfile w 0600]
if [catch {open $filename r} infh] {
puts stderr "Cannot open $filename: $infh"
exit
} else {
while {[gets $infh line] >= 0} {
if {[regexp {^\s*#' ?} $line]} {
set line [regsub {^\s*#' ?} $line ""]
puts $out $line
}
}
close $infh
}
close $out
if {$pandoc} {
exec pandoc $tempfile --filter $argv0 -o {*}[lrange $argv 1 end]
} else {
set argv [lset argv 0 $tempfile]
pantcl::lineFilter $argv
}
file delete $tempfile
puts "converting $infile to [lindex $argv 1] done"
exit 0
} else {
if {$pandoc} {
exec pandoc [lindex $argv 0] --filter $argv0 -o {*}[lrange $argv 1 end]
} else {
pantcl::lineFilter $argv
}
#puts "converting [lindex $argv 0] to [lindex $argv 1] done"
}
exit 0
}
#' ---
#' title: pantcl filter documentation - 0.10.2
#' author: Detlef Groth, Schwielowsee, Germany
#' date: 2024-12-24
#' tcl:
#' echo: "true"
#' results: show
#' eval: 1
#' ---
#'
#' ------
#'
#' ```{.tcl results="asis" echo=false}
#' include header.md
#' ```
#' ------
#'
#' ## NAME
#'
#' _pantcl.tcl_ - filter application for the pandoc command line
#' application to convert Markdown files into other formats. The filter allows you to embed Tcl code into your Markdown
#' documentation and offers a plugin architecture to add other command line filters easily using Tcl
#' and the `exec` command. As examples are given in the filter folder of the project:
#'
#' * Tcl filter {.tcl}: `filter-tcl.tcl` [filter/filter-tcl.html](filter/filter-tcl.html)
#' * ABC music filter {.abc}: `filter-abc.tcl` [filter/filter-abc.html](filter/filter-abc.html)
#' * command line application filter {.cmd}: `filter-cmd.tcl` [filter/filter-abc.html](filter/filter-cmd.html)
#' * Graphviz dot filter {.dot}: `filter-dot.tcl` [filter/filter-dot.html](filter/filter-dot.html)
#' * EQN filter plugin for equations written in the EQN language {.eqn}: `filter-eqn` [filter/filter-eqn.html](filter/filter-eqn.html)
#' * Julia filter plugin for Julia clode {.julia}: `filter-julia` [filter/filter-julia.html](filter/filter-julia.html)
#' * Math TeX filter for single line equations {.mtex}: `filter-mtex.tcl` [filter/filter-mtex.html](filter/filter-mtex.html)
#' * Mermaid filter for diagrams {.mmd}: `filter-mmd.tcl` [filter/filter-mmd.html](filter/filter-mmd.html)
#' * Pikchr filter plugin for diagram creation {.pikchr}: `filter-pik.tcl` [filter/filter-pik.html](filter/filter-pik.html)
#' * PIC filter plugin for diagram creation (older version) {.pic}: `filter-pic.tcl` [filter/filter-pic.html](filter/filter-pic.html)
#' * pipe filter for R, Python and Octave {.pipe}: `filter-pipe.tcl` [filter/filter-pipe.html](filter/filter-pipe.html)
#' * PlantUMLfilter plugin for diagram creation {.puml}: `filter-puml.tcl` [filter/filter-puml.html](filter/filter-puml.html)
#' * R plot filter plugin for displaying plots in the R statistical language {.rplot}: `filter-rplot.tcl` [filter/filter-rplot.html](filter/filter-rplot.html)
#' * sqlite3 filter plugin to evaluate SQL code {.sqlite}: `filter-sqlite.tcl` [filter/filter-sqlite.html](filter/filter-sqlite.html)
#' * tcrd filter for music songs with chords {.tcrd}: `filter-tcrd.tcl` [filter/filter-tcrd.html](filter/filter-tcrd.html)
#' * tdot package filter {.tsvg}: `filter-tdot.tcl` [filter/filter-tdot.html](filter/filter-tdot.html)
#' * tsvg package filter {.tsvg}: `filter-tsvg.tcl` [filter/filter-tsvg.html](filter/filter-tsvg.html)
#'
#' ## SYNOPSIS
#'
#' We assume that you renamed the standalone file `pantcl.tapp` to `pantcl` and
#' that this file is in your path.
#'
#' ```
#' # standalone application
#' pantcl infile outfile ?options? --no-pandoc
#' # same with default eval=true for all code chunks
#' FILTEREVAL=1 pantcl infile outfile ?options? --no-pandoc
#' # as filter for pandoc
#' pandoc infile --filter pantcl ?options?
#' # using graphics user interface
#' pantcl --gui [filename]
#' ```
#'
#' Where options for the filter and the standalone mode
#' are the usual pandoc options. For HTML conversion you should use for instance:
#'
#' ```
#' pantcl infile.md outfile.html --css style.css -s --toc
#' ```
#'
#' Please note, that you can rename as well the file `pantcl.tapp` into other names like
#' `pantcl.bin`, however the basename `pantcl` must stay the same.
#'
#' ## Code embedding
#'
#' Embed code either inline or in form of code chunks like here (triple ticks):
#'
#' ```
#' ```{.tcl}
#' set x 4
#' incr x
#' set x
#' ```
#'
#' Hello this is Tcl `tcl package provide Tcl`!
#' ```
#'
#' ## Filter Overview
#'
#' The markers for the other filters are:
#'
#' `{.abc}, `{.dot}`, `{.eqn}`, `{.julia}`, `{.mmd}`, `{.mtex}`, `{.pic}`,
#' `{.pikchr}, `{.puml}`, `{.rplot}`,`{.sqlite}` and `{.tsvg}`.
#'
#' For details on how to use them have a look at the manual page links on top.
#'
#' You can combine all filters in one document just by using the appropiate markers.
#'
#' Here an overview about the required tools to use a filter:
#'
#' <center>
#'
#' | filter | tool | svg | png | pdf | comment |
#' | ------ | ----- | ---- | ---- | ---- | ---- |
#' | .tcl | tclsh | tsvg | cairosvg | cairosvg | programming |
#' | .abc | abcm2ps | abcm2ps | cairosvg | cairosvg | music |
#' | .dot | dot | native | native | native | diagrams |
#' | .emf | jasspa microemacs | no | no | no | editor |
#' | .eqn | eqn2graph | no | convert | no | math |
#' | .julia | julia | native | native | native | statistics |
#' | .mmd | mermaid-cli (mmdc) | native | native | native | diagrams |
#' | .mtex | latex | dvisgm | dvipng | dvipdfm | math, diagrams, games |
#' | .pic | pic2graph | no | convert | no | diagrams |
#' | .pik | fossil | native | cairosvg | cairosvg | diagrams |
#' | .pipe | R / python / octave | native | native | native | Statistics, Programming |
#' | .puml | plantuml | native | native | native | diagrams |
#' | .rplot | R | native | native | native | statistics, graphics |
#' | .tcrd | tclsh | no | no | no | music, songs with chords |
#' | .tdot | tclsh/dot | native | native | native | diagrams |
#' | .tsvg | tclsh | native | cairosvg | cairosvg | graphics |
#'
#' </center>
#'
#' The Markdown document within this file could be extracted and converted as follows:
#'
#' ```
#' pantcl pantcl.tcl pantcl.html \
#' --css mini.css -s
#' ```
#'
#' ## Example Tcl Filter
#'
#' #### Tcl-filter
#'
#' ```
#' ```{.tcl}
#' set x 1
#' puts $x
#' ```
#' ```
#'
#' And here the output:
#'
#' ```{.tcl}
#' set x 1
#' puts $x
#' ```
#'
#' Does indented code blocks works as well?
#'
#' > ```{.tcl}
#' set x 2
#' puts $x
#' > ```
#'
#' > Yes, since version 0.7.0!!
#'
#' There is as well the possibility to inline Tcl code like here:
#'
#' ```
#' This document was processed using Tcl `tcl set tcl_patchLevel`!
#' ```
#'
#' will produce:
#'
#' This document was processed using Tcl `tcl set tcl_patchLevel`!
#'
#' This works as well in nested structures like lists or quotes.
#'
#' > This document was processed using Tcl `tcl set tcl_patchLevel`!
#'
#' > - This document was processed using Tcl `tcl set tcl_patchLevel`!
#'
#' ## Filter - Plugins
#'
#' The pantcl.tcl application allows to create custom filters for other
#' command line application quite easily. The Tcl files has to be named `filter-NAME.tcl`
#' where NAME hast to match the code chunk marker. Below an example:
#'
#' ```
#' ` ``{.dot label=dotgraph}
#' digraph G {
#' main -> parse -> execute;
#' main -> init;
#' main -> cleanup;
#' execute -> make_string;
#' execute -> printf
#' init -> make_string;
#' main -> printf;
#' execute -> compare;
#' }
#'
#' ![](dotgraph.svg)
#' ` ``
#' ```
#'
#' The main script `pantcl.tcl` evaluates if in the same folder as the script is,
#' if there any other files named `filter/filter-NAME.tcl` and sources them. In case of the dot
#' filter the file is named `filter-dot.tcl` and its filter function `filter-dot` is
#' executed. Below is the simplified code: of this file `filter-dot.tcl`:
#'
#' ```{.tcl eval=false results="hide"}
#' # a simple pandoc filter using Tcl
#' # the script pantcl.tcl
#' # must be in the same filter directoy of the pantcl.tcl file
#' proc filter-dot {cont dict} {
#' global n
#' incr n
#' set def [dict create app dot results show eval true fig true
#' label null ext svg width 400 height 400 \
#' include true imagepath images]
#' # fuse code chunk options with defaults
#' set dict [dict merge $def $dict]
#' set ret ""
#' if {[dict get $dict label] eq "null"} {
#' set fname dot-$n
#' } else {
#' set fname [dict get $dict label]
#' }
#' # save dot file
#' set out [open $fname.dot w 0600]
#' puts $out $cont
#' close $out
#' # TODO: error catching
#' set res [exec [dict get $dict app] -Tsvg $fname.dot -o $fname.svg]
#' if {[dict get $dict results] eq "show"} {
#' # should be usually empty
#' set res $res
#' } else {
#' set res ""
#' }
#' set img ""
#' if {[dict get $dict fig]} {
#' if {[dict get $dict include]} {
#' set img $fname.svg
#' }
#' }
#' return [list $res $img]
#' }
#' ```
#'
#' Using the label and the option `include=false` we could create an image link manually using Markdown syntax. The
#' The image filename should be then images/label.svg for instance.
#'
#' ## Dot Example
#'
#' Here a longer dot-example where the code is include in
#'
#' ```{.dot}
#' digraph G {
#' margin=0.1;
#' node[fontname="Linux Libertine";fontsize=18];
#' node[shape=box,style=filled;fillcolor=skyblue,width=1.2,height=0.9];
#' { rank=same; Rst[group=g0,fillcolor=salmon] ;
#' Docx [group=g1,fillcolor=salmon]
#' }
#' { rank=same; Md[group=g0,fillcolor=salmon] ;
#' pandoc ; AST1 ; filter[fillcolor=cornsilk] ; AST2 ; pandoc2;
#' Html[group=g1,fillcolor=salmon]
#' }
#' { rank=same; Tex[group=g0,fillcolor=salmon] ;
#' Pdf[group=g1,fillcolor=salmon]; filters[fillcolor=cornsilk];