File: publish.m

package info (click to toggle)
octave 9.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 144,300 kB
  • sloc: cpp: 332,784; ansic: 77,239; fortran: 20,963; objc: 9,396; sh: 8,213; yacc: 4,925; lex: 4,389; perl: 1,544; java: 1,366; awk: 1,259; makefile: 648; xml: 189
file content (1136 lines) | stat: -rw-r--r-- 37,095 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
########################################################################
##
## Copyright (C) 2010-2024 The Octave Project Developers
##
## See the file COPYRIGHT.md in the top-level directory of this
## distribution or <https://octave.org/copyright/>.
##
## This file is part of Octave.
##
## Octave is free software: you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## Octave is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Octave; see the file COPYING.  If not, see
## <https://www.gnu.org/licenses/>.
##
########################################################################

## -*- texinfo -*-
## @deftypefn  {} {} publish (@var{file})
## @deftypefnx {} {} publish (@var{file}, @var{output_format})
## @deftypefnx {} {} publish (@var{file}, @var{option1}, @var{value1}, @dots{})
## @deftypefnx {} {} publish (@var{file}, @var{options})
## @deftypefnx {} {@var{output_file} =} publish (@var{file}, @dots{})
##
## Generate a report from the Octave script file @var{file} in one of several
## output formats.
##
## The generated reports interpret Publishing Markup in section comments, which
## is explained in detail in the GNU Octave manual.  Section comments are
## comment blocks that start with a line with double comment character.
##
## Assume the following example, using some Publishing Markup, to be the
## contents of the script file @file{pub_example.m}:
##
## @example
## @group
## ## Headline title
## #
## # Some *bold*, _italic_, or |monospaced| Text with
## # a <https://www.octave.org link to *GNU Octave*>.
## ##
##
## # "Real" Octave commands to be evaluated
## sombrero ()
##
## %% @sc{matlab} comment style ('%') is supported as well
## %
## % * Bulleted list item 1
## % * Bulleted list item 2
## %
## % # Numbered list item 1
## % # Numbered list item 2
## @end group
## @end example
##
## To publish this script file, type @code{publish ("pub_example.m")}.
##
## When called with one input argument, a HTML report is generated in a
## subdirectory @file{html} relative to the current working directory.  Any
## Octave commands in @file{pub_example.m} are evaluated in a separate context
## and any figures created while executing the script file are included in the
## report.
##
## Using @code{publish (@var{file}, @var{output_format})} is equivalent to the
## function call using a structure
##
## @example
## @group
## @var{options}.format = @var{output_format};
## publish (@var{file}, @var{options})
## @end group
## @end example
##
## @noindent
## which is described below.  The same holds for using option/value pairs
##
## @example
## @group
## @var{options}.@var{option1} = @var{value1};
## publish (@var{file}, @var{options})
## @end group
## @end example
##
## The structure @var{options} can have the following field names.  If a field
## name is not specified, the default value is used:
##
## @itemize @bullet
## @item
## @samp{format} --- Output format of the published script file, one of
##
## @samp{html} (default), @samp{doc}, @samp{latex}, @samp{ppt},
## @samp{pdf}, or @samp{xml}.
##
## The output formats @samp{doc}, @samp{ppt}, and @samp{xml} are not currently
## supported.  To generate a @samp{doc} report, open a generated @samp{html}
## report with your office suite.
##
## In Octave custom formats are supported by implementing all callback
## subfunctions in a function file named
## @samp{__publish_<custom format>_output__.m}.  To obtain a template for the
## HTML format type:
##
## @example
## @group
## edit (fullfile (fileparts (which ("publish")), ...
##       "private", "__publish_html_output__.m"))
## @end group
## @end example
##
## @item
## @samp{outputDir} --- Full path of the directory where the generated report
## will be located.  If no directory is given, the report is generated in a
## subdirectory @file{html} relative to the current working directory.
##
## @item
## @samp{stylesheet} --- Not supported, only for @sc{matlab} compatibility.
##
## @item
## @samp{createThumbnail} --- Not supported, only for @sc{matlab}
## compatibility.
##
## @item
## @samp{figureSnapMethod} --- Not supported, only for @sc{matlab}
## compatibility.
##
## @item
## @samp{imageFormat} --- Desired format for any images produced while
## evaluating the code.  The allowed image formats depend on the output format:
##
## @itemize @bullet
## @item @samp{html}, @samp{xml} --- @samp{png} (default), any image format
## supported by Octave
##
## @item @samp{latex} --- @samp{epsc2} (default), any image format supported by
## Octave
##
## @item @samp{pdf} --- @samp{jpg} (default) or @samp{bmp}, note @sc{matlab}
## uses  @samp{bmp} as default
##
## @item @samp{doc} or @samp{ppt} --- @samp{png} (default), @samp{jpg},
## @samp{bmp}, or @samp{tiff}
## @end itemize
##
## @item
## @samp{maxWidth} and @samp{maxHeight} --- Maximum width (height) of the
## produced images in pixels.  An empty value means no restriction.  Both
## values must be set in order for the option to work properly.
##
## @samp{[]} (default), integer value @geq{} 0
##
## @item
## @samp{useNewFigure} --- Use a new figure window for figures created by the
## evaluated code.  This avoids side effects with already opened figure
## windows.
##
## @samp{true} (default) or @samp{false}
##
## @item
## @samp{evalCode} --- Evaluate code of the Octave source file
##
## @samp{true} (default) or @samp{false}
##
## @item
## @samp{catchError} --- Catch errors while evaluating code and continue
##
## @samp{true} (default) or @samp{false}
##
## @item
## @samp{codeToEvaluate} --- Octave commands that should be evaluated prior to
## publishing the script file.  These Octave commands do not appear in the
## generated report.
##
## @item
## @samp{maxOutputLines} --- Maximum number of output lines from code
## evaluation which are included in output.
##
## @samp{Inf} (default) or integer value > 0
##
## @item
## @samp{showCode} --- Show the evaluated Octave commands in the generated
## report
##
## @samp{true} (default) or @samp{false}
## @end itemize
##
## The option output @var{output_file} is a string with path and file name
## of the generated report.
##
## @seealso{grabcode}
## @end deftypefn

function output_file = publish (file, varargin)

  if (nargin < 1)
    print_usage ();
  endif

  if (exist (file, "file") != 2)
    error ("publish: FILE does not exist");
  endif

  ## Check file to be in Octave's load path
  [file_path, file_name, file_ext] = fileparts (file);
  if (isempty (file_path))
    file_path = pwd ();
  endif
  if (exist ([file_name, file_ext]) != 2)
    error (["publish: " file " is not in the load path"]);
  endif

  ## Check file extension and that file is an Octave script
  file_info = __which__ (file_name);
  if (! strcmp (file_ext, ".m") || ! strcmp (file_info.type, "script"))
    error ("publish: only script files can be published");
  endif

  ## Check file to be parsable
  __parse_file__ (file);

  ## Get structure with necessary options
  options = struct ();
  if (numel (varargin) == 1)
    ## Call: publish (file, format)
    if (ischar (varargin{1}))
      options.format = varargin{1};
    ## Call: publish (file, options)
    elseif (isstruct (varargin{1}))
      options = varargin{1};
    else
      error ("publish: second argument must be OUTPUT_FORMAT or OPTIONS");
    endif
  ## Call: publish (file, Name1, Value1, Name2, Value2, ...)
  elseif (rem (numel (varargin), 2) == 0
          && all (cellfun (@ischar, varargin(1:2:end))))
    options = cell2struct (varargin(2:2:end), varargin(1:2:end), 2);
  else
    error ("publish: invalid arguments");
  endif

  ## Validate options struct

  ## Options for the output
  if (! isfield (options, "format"))
    options.format = "html";
  else
    ## FIXME: Implement remaining formats
    if (any (strcmpi (options.format, {"doc", "ppt", "xml"})))
      error ('publish: Output format "%s" is not yet supported',
             options.format);
    endif
    ## Supported or custom output format
    supported_formats = {"html", "doc", "latex", "ppt", "xml", "pdf"};
    if (! any (strcmpi (options.format, supported_formats)))
      ## Check existence of custom formatter
      custom_formatter = ["__publish_", options.format, "_output__"];
      if (! exist (custom_formatter, "file"))
        error (['publish: Custom output format "%s" requires the ', ...
                "formatter function:\n\n\t%s\n\n\t", ...
                'See "help publish" for more information.'],
                options.format, custom_formatter);
      endif
    else
      options.format = validatestring (options.format, supported_formats);
    endif
  endif

  if (! isfield (options, "outputDir"))
    ## Matlab R2016a doc says default is "", but specifies to create a
    ## subdirectory named "html" in the current working directory.
    options.outputDir = fullfile (file_path, "html");
  elseif (! ischar (options.outputDir))
    error ("publish: OUTPUTDIR must be a string");
  endif

  if (! isfield (options, "stylesheet"))
    options.stylesheet = "";
  elseif (! ischar (options.stylesheet))
    error ("publish: STYLESHEET must be a string");
  endif

  ## Options for the figures
  if (! isfield (options, "createThumbnail"))
    options.createThumbnail = true;
  elseif (! isscalar (options.createThumbnail)
          || ! isreal (options.createThumbnail))
    error ("publish: CREATETHUMBNAIL must be TRUE or FALSE");
  endif

  if (! isfield (options, "figureSnapMethod"))
    options.figureSnapMethod = "entireGUIWindow";
  else
    options.figureSnapMethod = validatestring (options.figureSnapMethod, ...
      {"entireGUIWindow", "print", "getframe", "entireFigureWindow"});
    ## FIXME: implement other SnapMethods
    warning ("publish: option FIGURESNAPMETHOD currently not supported");
  endif

  if (! isfield (options, "imageFormat"))
    switch (options.format)
      case "latex"
        options.imageFormat = "epsc2";
      case "pdf"
        ## Note: Matlab R2016a uses bmp as default
        options.imageFormat = "jpg";
      otherwise
        options.imageFormat = "png";
    endswitch
  elseif (! ischar (options.imageFormat))
    error ("publish: IMAGEFORMAT must be a string");
  else
    ## Check valid imageFormat for chosen format
    ##   html, latex, and xml accept any imageFormat
    switch (options.format)
      case {"doc", "ppt"}
        options.imageFormat = validatestring (options.imageFormat,
                                              {"png", "jpg", "bmp", "tiff"});
      case "pdf"
        options.imageFormat = validatestring (options.imageFormat,
                                              {"bmp", "jpg"});
    endswitch
  endif

  if (! isfield (options, "maxHeight"))
    options.maxHeight = [];
  elseif (! isscalar (options.maxHeight) || options.maxHeight < 1)
    error ("publish: MAXHEIGHT must be a positive integer");
  else
    options.maxHeight = uint64 (options.maxHeight);
  endif

  if (! isfield (options, "maxWidth"))
    options.maxWidth = [];
  elseif (! isscalar (options.maxWidth) || options.maxWidth < 1)
    error ("publish: MAXWIDTH must be a positive integer");
  else
    options.maxWidth = uint64 (options.maxWidth);
  endif

  if (! isfield (options, "useNewFigure"))
    options.useNewFigure = true;
  elseif (! isscalar (options.useNewFigure) || ! isreal (options.useNewFigure))
    error ("publish: USENEWFIGURE must be TRUE or FALSE");
  endif

  ## Options for the code
  if (! isfield (options, "evalCode"))
    options.evalCode = true;
  elseif (! isscalar (options.evalCode) || ! isreal (options.evalCode))
    error ("publish: EVALCODE must be TRUE or FALSE");
  endif

  if (! isfield (options, "catchError"))
    options.catchError = true;
  elseif (! isscalar (options.catchError) || ! isreal (options.catchError))
    error ("publish: CATCHERROR must be TRUE or FALSE");
  endif

  if (! isfield (options, "codeToEvaluate"))
    options.codeToEvaluate = "";
  elseif (! ischar (options.codeToEvaluate))
    error ("publish: CODETOEVALUTE must be a string");
  endif

  if (! isfield (options, "maxOutputLines"))
    options.maxOutputLines = Inf;
  elseif (! isscalar (options.maxOutputLines) || options.maxOutputLines < 0)
    error ("publish: MAXOUTPUTLINES must be an integer >= 0");
  else
    options.maxOutputLines = uint64 (options.maxOutputLines);
  endif

  if (! isfield (options, "showCode"))
    options.showCode = true;
  elseif (! isscalar (options.showCode) || ! isreal (options.showCode))
    error ("publish: SHOWCODE must be TRUE or FALSE");
  endif

  doc.title = "";
  doc.intro = "";
  doc.body = cell ();
  doc.m_source = deblank (read_file_to_cellstr (file));
  doc.m_source_file_name = file;

  ## Split code and paragraphs, find formatting
  doc = parse_m_source (doc);

  ## Create output directory
  [status, msg] = mkdir (options.outputDir);
  if (status != 1)
    error ("publish: cannot create output directory: %s", msg);
  endif

  if (options.evalCode)
    doc = eval_code (doc, options);
    eval_context ("clear");
  endif

  output_file = create_output (doc, options);

endfunction


function doc = parse_m_source (doc)

  ## PARSE_M_SOURCE First parsing level
  ##   This function extracts the overall structure (paragraphs and code
  ##   sections) given in doc.m_source.
  ##
  ##   The result is written to doc.body, which then contains a cell
  ##   vector of structs, either of
  ##
  ##     a) {struct ("type", "code", ...
  ##                 "lines", [a, b], ...
  ##                 "output", [])}
  ##     b) {struct ("type", "section", ...
  ##                 "content", title_str)}
  ##
  ##   Second parsing level is invoked for the paragraph contents, resulting
  ##   in more elements for doc.body.

  if (isempty (doc.m_source))
    return;  # Nothing to parse
  endif

  ## Parsing helper functions
  ##
  ## Checks line to have N "%" or "#" lines
  ## followed either by a space or end of string
  function r = is_publish_markup (cstr, N)

    str = char (cstr);

    r = any (strncmp (str, {"%%%", "##"}, N));
    if (r)
      len = length (str);
      if (len == N)
        r = true;
      elseif (len > N && str(N+1) == " ")
        r = true;
      else
        r = false;
      endif
    endif

    return;

  endfunction
  ## Checks line of cellstring to be a paragraph line
  is_paragraph = @(cstr) is_publish_markup (cstr, 1);
  ## Checks line of cellstring to be a section headline
  is_head = @(cstr) is_publish_markup (cstr, 2);
  ## Checks line of cellstring to be a headline without section break, using
  ## the cell mode in Matlab (for compatibility), just treated as a new head.
  is_no_break_head = @(cstr) is_publish_markup (cstr, 3);

  ## Find the indices of paragraphs starting with "%%", "##", or "%%%"
  par_start_idx = find (cellfun (is_head, doc.m_source)
                        | cellfun (is_no_break_head, doc.m_source));

  ## If the whole document is code
  if (isempty (par_start_idx))
    doc.body{end+1}.type = "code";
    doc.body{end}.content = strtrim (strjoin (doc.m_source, "\n"));
    doc.body{end}.lines = [1, length(doc.m_source)];
    doc.body{end}.output = {};
    return;
  endif

  ## Determine continuous range of paragraphs
  par_end_idx = [par_start_idx(2:end) - 1, length(doc.m_source)];
  for i = 1:numel (par_end_idx)
    idx = find (! cellfun (is_paragraph,
                           doc.m_source(par_start_idx(i) + 1:par_end_idx(i))));
    if (! isempty (idx))
      par_end_idx(i) = par_start_idx(i) + idx(1) - 1;
    endif
  endfor
  ## Code sections between paragraphs
  code_start_idx = par_end_idx(1:end-1) + 1;
  code_end_idx = par_start_idx(2:end) - 1;
  ## Code at the beginning?
  if (par_start_idx(1) > 1)
    code_start_idx = [1, code_start_idx];
    code_end_idx = [par_start_idx(1) - 1, code_end_idx];
  endif
  ## Code at the end?
  if (par_end_idx(end) < length (doc.m_source))
    code_start_idx = [code_start_idx, par_end_idx(end) + 1];
    code_end_idx = [code_end_idx, length(doc.m_source)];
  endif
  ## Remove overlaps
  idx = code_start_idx > code_end_idx;
  code_start_idx(idx) = [];
  code_end_idx(idx) = [];
  ## Remove empty code blocks
  idx = [];
  for i = 1:numel (code_start_idx)
    if (all (cellfun (@(cstr) isempty (char (cstr)),
                      doc.m_source(code_start_idx(i):code_end_idx(i)))))
      idx = [idx, i];
    endif
  endfor
  code_start_idx(idx) = [];
  code_end_idx(idx) = [];

  ## Try to find a document title and introduction text
  ##   1. First paragraph must start in first line
  ##   2. Second paragraph must start before any code
  title_offset = 0;
  if (is_head (doc.m_source{1})
      && ! isempty (par_start_idx)
      && par_start_idx(1) == 1
      && (isempty (code_start_idx)
          || (length (par_start_idx) > 1
              && par_start_idx(2) < code_start_idx(1))))
    doc.title = doc.m_source{1};
    doc.title = doc.title(4:end);
    content = doc.m_source(2:par_end_idx(1));
    ## Strip leading "# "
    content = cellfun (@(c) cellstr (c(3:end)), content);
    doc.intro = parse_paragraph_content (content);
    title_offset = 1;
  endif

  ## Add non-empty paragraphs and code to doc
  j = 1;
  i = (1 + title_offset);
  while (i <= numel (par_start_idx) || j <= numel (code_start_idx))
    ## Add code while there is code left
    ##   and code is before the next paragraph or there are no more paragraphs
    while (j <= numel (code_start_idx)
           && (i > numel (par_start_idx)
               || par_start_idx(i) > code_start_idx(j)))
      doc.body{end+1}.type = "code";
      lines = [code_start_idx(j), code_end_idx(j)];
      doc.body{end}.content = ...
        strtrim (strjoin (doc.m_source(lines(1):lines(2)), "\n"));
      doc.body{end}.lines = lines;
      doc.body{end}.output = {};
      j++;
    endwhile

    if (i <= numel (par_start_idx))
      type_str = "section";
      title_str = doc.m_source{par_start_idx(i)};
      if (is_head (doc.m_source(par_start_idx(i))))
        title_str = title_str(4:end);
      else
        title_str = title_str(5:end);
      endif
      ## Append, if paragraph title is given
      if (! isempty (title_str))
        doc.body{end+1}.type = type_str;
        doc.body{end}.content = title_str;
      endif

      content = doc.m_source(par_start_idx(i) + 1:par_end_idx(i));
      ## Strip leading "# "
      content = cellfun (@(c) cellstr (c(3:end)), content);
      doc.body = [doc.body, parse_paragraph_content(content)];
      i++;
    endif
  endwhile

endfunction


function p_content = parse_paragraph_content (content)

  ## PARSE_PARAGRAPH_CONTENT second parsing level
  ##
  ##   Parses the content of a paragraph (without potential title) and
  ##   returns a cell vector of structs, that can be appended to doc.body,
  ##   either of
  ##
  ##     a) {struct ("type", "preformatted_code", ...
  ##                 "content", code_str)}
  ##     b) {struct ("type", "preformatted_text", ...
  ##                 "content", text_str)}
  ##     c) {struct ("type", "bulleted_list", ...
  ##                 "content", {"item1", "item2", ..})}
  ##     d) {struct ("type", "numbered_list", ...
  ##                 "content", {"item1", "item2", ..})}
  ##     e) {struct ("type", "include", ...
  ##                 "content", file_str)}
  ##     f) {struct ("type", "graphic", ...
  ##                 "content", file_str)}
  ##     g) {struct ("type", "html", ...
  ##                 "content", html_str)}
  ##     h) {struct ("type", "latex", ...
  ##                 "content", latex_str)}
  ##     i) {struct ("type", "text", ...
  ##                 "content", text_str)}
  ##
  ##   Option i) might contain:
  ##
  ##     * Italic "_", bold "*", and monospaced "|" text
  ##     * Inline "$" and block "$$" LaTeX math
  ##     * Links
  ##     * Trademark symbols

  p_content = cell ();

  if (isempty (content))
    return;
  endif

  ## Extract <html> and <latex> blocks recursively.
  content_str = strjoin (content, "\n");
  tags = {"html", "latex"};
  for i = 1:length (tags)
    tok = regexp (content_str, ...
      ['(.*?)(^|\n\n)(<', tags{i}, '>)\n(.*?)\n(<\/', ...
        tags{i}, '>)($|\n\n)(.*)'], "tokens", "once");
    if (! isempty (tok))
      ## If there was some text before that block --> recursion
      if (! strcmpi (tok{1}, ["<", tags{i}, ">"]))
        p_content = parse_paragraph_content (strsplit (tok{1}, "\n"));
        tok(1:2) = [];
      endif
      ## Extract the block content
      p_content{end+1}.type = tags{i};
      p_content{end}.content = tok{2};
      ## If there was some text after that block --> recursion
      if (length (tok) == 5)
        p_content = [p_content, ...
          parse_paragraph_content(strsplit (tok{5}, "\n"))];
      endif
      return;
    endif
  endfor

  ## Split into blocks separated by empty lines
  idx = [0, find(cellfun (@isempty, content)), length(content) + 1];

  ## For each block
  for i = find (diff (idx) > 1)
    block = content(idx(i) + 1:idx(i+1) - 1);

    ## Octave code (two leading spaces)
    if (all (cellfun (@(c) strncmp (char (c), "  ", 2), block)))
      p_content{end+1}.type = "preformatted_code";
      block = cellfun (@(c) cellstr (c(3:end)), block);
      p_content{end}.content = strjoin (block, "\n");
      continue;
    endif

    ## Preformatted text (one leading space)
    if (all (cellfun (@(c) strncmp (char (c), " ", 1), block)))
      p_content{end+1}.type = "preformatted_text";
      block = cellfun (@(c) cellstr (c(2:end)), block);
      p_content{end}.content = strjoin (block, "\n");
      continue;
    endif

    ## Bulleted list starts with "* "
    if (strncmp (block{1}, "* ", 2))
      p_content{end+1}.type = "bulleted_list";
      tmpstr = strjoin (block, "\n");
      ## Remove first "* "
      tmpstr = tmpstr(3:end);
      ## Split items
      p_content{end}.content = strsplit (tmpstr, "\n* ");
      continue;
    endif

    ## Numbered list starts with "# "
    if (strncmp (block{1}, "# ", 2))
      p_content{end+1}.type = "numbered_list";
      tmpstr = strjoin (block, "\n");
      ## Remove first "# "
      tmpstr = tmpstr(3:end);
      ## Split items
      p_content{end}.content = strsplit (tmpstr, "\n# ");
      continue;
    endif

    ## Include <include>fname.m</include>
    if (! isempty (fname = regexpi (strjoin (block, ""),
                                    '^<include>(.*)</include>$',
                                    "tokens")))
      ## Includes result in preformatted code
      p_content{end+1}.type = "preformatted_code";
      include_code = read_file_to_cellstr (strtrim ((fname{1}){1}));
      p_content{end}.content = strjoin (include_code, "\n");

      continue;
    endif

    ## Graphic <<myGraphic.png>>
    if (! isempty (fname = regexpi (strjoin (block, ""),
                                    '^<<(.*)>>$',
                                    "tokens")))
      p_content{end+1}.type = "graphic";
      p_content{end}.content = strtrim ((fname{1}){1});
      continue;
    endif

    ## Now it can be only normal text or markups belonging to normal text
    ## that are handled while output generation:
    ##
    ## * Italic "_", bold "*", and monospaced "|" text
    ## * Inline "$" and block "$$" LaTeX math
    ## * Links
    ## * Trademark symbols
    p_content{end+1}.type = "text";
    p_content{end}.content = strjoin (block, "\n");
  endfor

endfunction


function m_source = read_file_to_cellstr (file)

  ## READ_FILE_TO_CELLSTR reads a given file line by line into a cellstring
  fid = fopen (file, "r");
  i = 0;
  do
    m_source{++i} = fgetl (fid);
  until (! ischar (m_source{i}))
  fclose (fid);
  m_source = m_source(1:end-1);  # No EOL

endfunction


function ofile = create_output (doc, options)

  ## CREATE_OUTPUT creates the desired output file
  formatter = [];
  switch (options.format)
    case "html"
      formatter = @__publish_html_output__;
    case {"latex", "pdf"}
      formatter = @__publish_latex_output__;
    otherwise
      ## Custom formatter
      formatter = eval (["@__publish_", options.format, "_output__"]);
  endswitch

  ## Use title, or if not given, the m-file name
  title_str = doc.title;
  if (isempty (title_str))
    [~, title_str] = fileparts (doc.m_source_file_name);
  endif

  content = formatter ("header",
                       formatter ("escape_special_chars", title_str),
                       format_output (doc.intro, formatter, options),
                       get_toc (doc.body, formatter));
  content = [content, format_output(doc.body, formatter, options)];
  content = [content, formatter("footer", strjoin (doc.m_source, "\n"))];

  ## Write file
  [~, ofile] = fileparts (doc.m_source_file_name);
  ofile_name = [ofile, formatter("output_file_extension")];
  ofile = fullfile (options.outputDir, ofile_name);
  fid = fopen (ofile, "w");
  fputs (fid, content);
  fclose (fid);

  ## Compile LaTeX, if compiler found
  if (strcmp (options.format, "pdf"))
    status = system ("pdflatex --version");
    if (status == 0)
      for i = 1:2
        ## FIXME: This looks very likely to break when switching OS
        system (["cd ", options.outputDir," && pdflatex ", ofile_name]);
      endfor
    endif
  endif

endfunction


function toc_cstr = get_toc (cstr, formatter)

  ## GET_TOC extracts the table of contents from a cellstring (e.g., doc.body)
  ## with each section headline as a cell in a returned cellstring.
  toc_cstr = cell ();
  for i = 1:numel (cstr)
    if (strcmp (cstr{i}.type, "section"))
      toc_cstr{end+1} = format_text (cstr{i}.content, formatter);
    endif
  endfor

endfunction


function str = format_output (cstr, formatter, options)

  ## FORMAT_OUTPUT steps through all blocks (doc.intro or doc.body) in cstr and
  ## produces a single result string with the source code in the desired output
  ## format.
  ##
  ##   formatter has the only knowledge how to enforce the target format
  ##   and produces for each block the necessary target format source string.
  str = "";
  for i = 1:numel (cstr)
    switch (cstr{i}.type)
      case "code"
        if (options.showCode)
          str = [str, formatter("code", cstr{i}.content)];
        endif
        if ((options.evalCode) && (! isempty (cstr{i}.output)))
          str = [str, formatter("code_output", cstr{i}.output)];
        endif
      case {"text", "section"}
        str = [str, formatter(cstr{i}.type, ...
                              format_text (cstr{i}.content, formatter))];
      case {"bulleted_list", "numbered_list"}
        items = cellfun (@(str) format_text(str, formatter), ...
                         cstr{i}.content, "UniformOutput", false);
        str = [str, formatter(cstr{i}.type, items)];
      otherwise
        str = [str, formatter(cstr{i}.type, cstr{i}.content)];
    endswitch
  endfor

endfunction


function str = format_text (str, formatter)

  ## FORMAT_TEXT formats inline formats in strings.
  ##   These are: links, block/inline math, bold, italic, monospaced, (TM), (R)

  ## Helper to clarify the following regular expressions.  It is suitable for
  ## inline formatting, that is delimited literally at start and end by
  ## 'delim'.  'term' is an indicating character for the end delimiter.
  ##
  ## Best explained by example ('^' start and '$' end of input):
  ##
  ##  Positive matches:
  ##
  ##    ^*bold*$
  ##    ^*bold*.$
  ##    ^(*bold*)$
  ##    ^ *bold* $
  ##    ^Text *bold* text$
  ##    ^*bold text*$
  ##
  ##  Negative matches:
  ##
  ##    ^Text*bold*text$
  ##    ^*bold *$
  ##    ^* bold* $
  ##    ^*bold text *$
  ##
  regex_helper = @(delim, term) ['(^|(?<=\s)|(?=\W))', delim, ...
    '(?!\s)[^', term, ']*(?<!\s)', delim, '($|(?=\s)|(?=\W))'];

  ## Regular expressions for the formats:
  ##
  ## 1) Links "<https://www.someurl.com>"
  ## 2) Links "<octave:Function SOME TEXT>"
  ## 3) Links "<https://www.someurl.com SOME TEXT>"
  ## 4) LaTeX block math "$$x^2$$"
  ## 5) LaTeX inline math "$x^2$"
  ## 6) Bold *text*
  ## 7) Italic _text_
  ## 8) Monospaced |text|
  ## 9) (TM) or (R)
  regexes = {'<\S{3,}[^\s<>]*>', ...
             '<octave:[^\s<>]* *[^<>$]*>', ...
             '<\S{3,}[^\s<>]* *[^<>$]*>', ...
             regex_helper('\$\$', '$'), ...
             regex_helper('\$', '$'), ...
             regex_helper('\*', '*'), ...
             regex_helper('_', '_'), ...
             regex_helper('\|', '|'), ...
             '\((TM|R)\)'};

  ## Function to escape some special characters for the GNU Octave manual,
  ## see https://www.gnu.org/software/texinfo/manual/texinfo/html_node/HTML-Xref-Node-Name-Expansion.html
  texinfo_esc = @(str) strrep (strrep (str, "-", "_002d"), "_", "_005f");

  ## Substitute all occurrences with placeholders
  placeholder_cstr = {};
  plh = 0;
  for i = 1:numel (regexes)
    cstr = regexp (str, regexes{i}, "match");
    for j = 1:numel (cstr)
      plh += 1;
      str = regexprep (str, regexes{i}, ["PUBLISHPLACEHOLDER" num2str(plh)],
                       "once");
      switch (i)
        case 1
          ## Links "<https://www.someurl.com>"
          url = cstr{j};
          cstr{j} = formatter ("link", url(2:end-1), url(2:end-1));
        case 2
          ## Links "<octave:Function SOME TEXT>"
          idx = strfind (cstr{j}, " ")(1);
          url = cstr{j};
          url = texinfo_esc (url(9:idx-1));
          v = version ();
          if (v(end) != '0')  # No official release
            v = "latest";
          else
            v = ["v" v];  # "v6.4.0" etc.
          endif
          url = sprintf ("https://octave.org/doc/%s/XREF%s.html", v, url);
          txt = cstr{j};
          txt = format_text (txt(idx+1:end-1), formatter);
          cstr{j} = formatter ("link", url, txt);
        case 3
          ## Links "<https://www.someurl.com SOME TEXT>"
          idx = strfind (cstr{j}, " ")(1);
          url = cstr{j};
          url = url(2:idx-1);
          txt = cstr{j};
          txt = format_text (txt(idx+1:end-1), formatter);
          cstr{j} = formatter ("link", url, txt);
        case 4
          ## LaTeX block math "$$"
          txt = cstr{j};
          cstr{j} = formatter ("blockmath", txt(3:end-2));
        case 5
          ## LaTeX inline math "$"
          txt = cstr{j};
          cstr{j} = formatter ("inlinemath", txt(2:end-1));
        case 6
          ## Bold
          txt = cstr{j};
          cstr{j} = formatter ("bold", format_text (txt(2:end-1), formatter));
        case 7
          ## Italic
          txt = cstr{j};
          cstr{j} = formatter ("italic", format_text (txt(2:end-1), formatter));
        case 8
          ## Monospaced
          txt = cstr{j};
          cstr{j} = formatter ("monospaced", format_text (txt(2:end-1), ...
                               formatter));
        case 9
          ## (TM) or (R)
          txt = cstr{j};
          cstr{j} = formatter (txt(2:end-1));
      endswitch
    endfor
    placeholder_cstr = [placeholder_cstr, cstr];
  endfor

  ## Replace special symbols
  str = formatter ("escape_special_chars", str);

  ## Restore placeholders
  for i = plh:-1:1
    str = strrep (str, ["PUBLISHPLACEHOLDER" sprintf("%d", i)],
                       placeholder_cstr{i});
  endfor

endfunction


function doc = eval_code (doc, options)

  ## EVAL_CODE Third level parsing
  ##
  ##   Generates the output of the script code and takes care of generated
  ##   figures.

  ## Necessary as the code does not run interactively
  page_screen_output (false, "local");

  ## Remember previously opened figures
  fig_ids = findall (0, "type", "figure");
  [~, fig_name] = fileparts (doc.m_source_file_name);
  fig_num = 1;
  fig_list = struct ();

  ## Evaluate code, that does not appear in the output.
  eval_code_helper (options.codeToEvaluate);

  ## Create a new figure, if there are existing plots
  if (! isempty (fig_ids) && options.useNewFigure)
    figure ();
  endif

  for i = 1:numel (doc.body)
    if (strcmp (doc.body{i}.type, "code"))
      r = doc.body{i}.lines;
      code_str = strjoin (doc.m_source(r(1):r(2)), "\n");
      if (options.catchError)
        try
          doc.body{i}.output = eval_code_helper (code_str);
         catch err
          doc.body{i}.output = cellstr (["error: ", err.message, ...
                                                 "\n\tin:\n\n", code_str]);
        end_try_catch
      else
        doc.body{i}.output = eval_code_helper (code_str);
      endif

      ## Check for newly created figures ...
      fig_ids_new = setdiff (findall (0, "type", "figure"), fig_ids);
      ## ... and save them
      for j = 1:numel (fig_ids_new)
        drawnow ();
        if (isempty (get (fig_ids_new(j), "children")))
          continue;
        endif
        fname = [fig_name, "-", sprintf("%d", fig_num)];
        if (strncmp (options.imageFormat, "eps", 3))
          fname = [fname ".eps"];
        else
          fname = [fname "." options.imageFormat];
        endif
        print_opts = {fig_ids_new(j), ...
                      fullfile(options.outputDir, fname), ...
                      ["-d" options.imageFormat], "-color"};
        if (! isempty (options.maxWidth) && ! isempty (options.maxHeight))
          print_opts{end+1} = sprintf ("-S%d,%d", options.maxWidth,
                                                  options.maxHeight);
        elseif (! isempty (options.maxWidth) || ! isempty (options.maxHeight))
          warning (["publish: specify both options.maxWidth ", ...
                              "and options.maxHeight"]);
        endif
        print (print_opts{:});
        fig_num++;
        delete (fig_ids_new(j));
        fig_elem = cell ();
        fig_elem{1} = struct ("type", "graphic", "content", fname);
        if (isfield (fig_list, num2str (i)))
          fig_elem = [getfield(fig_list, sprintf ("%d", i)), fig_elem];
        endif
        fig_list = setfield (fig_list, sprintf ("%d", i), fig_elem);
        ## Create a new figure, if there are existing plots
        if (isempty (setdiff (findall (0, "type", "figure"), fig_ids)) ...
            && ! isempty (fig_ids) && options.useNewFigure)
          figure ();
        endif
      endfor

      ## Truncate output to desired length
      if (options.maxOutputLines < length (doc.body{i}.output))
        doc.body{i}.output = doc.body{i}.output(1:options.maxOutputLines);
      endif
      doc.body{i}.output = strjoin (doc.body{i}.output, "\n");
    endif
  endfor

  ## Close any figures opened by publish function
  delete (setdiff (findall (0, "type", "figure"), fig_ids));

  ## Insert figures to document
  fig_code_blocks = fieldnames (fig_list);
  body_offset = 0;
  for i = 1:numel (fig_code_blocks)
    elems = getfield (fig_list, fig_code_blocks{i});
    ## Compute index where the figure(s) has to be inserted
    j = str2double (fig_code_blocks{i}) + body_offset;
    doc.body = [doc.body(1:j), elems, doc.body(j+1:end)];
    body_offset = body_offset + numel (elems);
  endfor

endfunction


function cstr = eval_code_helper (__code__)

  ## EVAL_CODE_HELPER evaluates a given string with Octave code in an extra
  ## temporary context and returns a cellstring with the eval output.

  if (isempty (__code__))
    return;
  endif

  eval_context ("load");
  cstr = evalc (__code__);
  ## Split string by lines and preserve blank lines.
  cstr = strsplit (strrep (cstr, "\n\n", "\n \n"), "\n");
  eval_context ("save");

endfunction


function cstr = eval_context (op)

  ## EVAL_CONTEXT temporary evaluation context.
  persistent ctext;

  ## Variable cstr in "eval_code_helper" is newly created anyways.
  forbidden_var_names = {"__code__"};

  switch (op)
    case "save"
      ## Clear previous context
      ctext = containers.Map;
      ## Get variable names
      var_names = evalin ("caller", "whos");
      var_names = {var_names.name};
      ## Store all variables to context
      for i = 1:length (var_names)
        if (! any (strcmp (var_names{i}, forbidden_var_names)))
          ctext(var_names{i}) = evalin ("caller", var_names{i});
        endif
      endfor

    case "load"
      if (! isempty (ctext))
        keys = ctext.keys ();
        for i = 1:length (keys)
          assignin ("caller", keys{i}, ctext(keys{i}));
        endfor
      endif

    case "clear"
      ## Clear any context
      ctext = [];

    otherwise
      ## Do nothing

  endswitch

endfunction


## Note: Functional BIST tests are located in the 'test/publish' directory.

## Test input validation
%!error <Invalid call> publish ()
%!error publish (1)
%!error <FILE does not exist> publish ("%%_non_existent_file_%%.m")
%!error <only script files can be published> publish ("publish.m")
%!error publish ("test_script.m", "format", "html", "showCode")