This repository has been archived by the owner on Jan 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 318
/
MDoc.m
1353 lines (1160 loc) · 45 KB
/
MDoc.m
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
function varargout = MDoc(varargin)
%MDOC mexopencv documentation utility
%
% MDoc()
% MDoc(action)
% MDoc(topic)
% MDoc(..., 'OptionName',optionValue, ...)
% filename = MDoc(...)
%
% ## Input
% * __action__ Special targets (default `-all`). One of:
% * `-clean`: delete all generated docs.
% * `-wiki`: generate HTML wiki files.
% * `-all`: generate full documentation for all mexopencv functions.
% * `-index`: only generate table of contents.
% * `-indexcat`: only generate table of contents (grouped by modules).
% * `-contents`: generate Contents.m file.
% * `-helptoc`: generate helpfuncbycat.xml file (TOC function reference).
% * __topic__ generate docs for specified mexopencv function.
%
% ## Output
% * __filename__ optional, generated HTML file path.
%
% ## Options
% * __Force__ Unconditionally re-create HTML output files. default true
% * __MarkdownRender__ Process markdown. default true
% * __MarkdownBackend__ Markdown parser implementation to use. The
% following backends are available to choose from:
% * 'CommonMark-Java' (https://github.com/atlassian/commonmark-java/)
% * 'MarkdownPapers' (https://github.com/lruiz/MarkdownPapers/)
% * 'pegdown' (https://github.com/sirthias/pegdown/)
% * 'MarkdownJ' (https://github.com/myabc/markdownj/)
% * 'Markdown4j' (https://github.com/jdcasey/markdown4j/)
% * 'Txtmark' (https://github.com/rjeschke/txtmark/)
% * __AutoLinking__ search for "http://" in text and convert them into
% hyperlinks. default false
% * __AutoLinkingDeep__ search for "www." in text and convert them into
% hyperlinks. default false
% * __AutoLinkingCV__ search for "cv.*" functions in text, and convert
% them into hyperlinks. default true
% * __SyntaxHighlighting__ syntax highlighted code. default true
% * __PrettifyLang__ language of syntax highlighting. default 'lang-matlab'
% * __TableSorting__ sortable HTML tables (used in index.html).
% default true
% * __NoExternals__ download all CSS/JS external resources locally.
% default true
%
% ## Options (batch mode)
% * __IndexGroups__ group by OpenCV module in index. default true
% * __IgnoreHandleClass__ skip generating redundant docs for methods
% inherited from "handle" base class. default true
% * __Verbose__ Display info messages. default true
% * __Progress__ Show progress bar. default true
%
% This function generates simple MATLAB HTML documentation using
% MATLAB's internal utility help2html.
%
% See also: doc, help, help2html, publish
%
% validate input arguments
nargoutchk(0, 1);
opts = parse_options(varargin{:});
% initialize Java dependencies
init_jsoup(opts);
init_markdown(opts);
if strcmp(opts.topic, '-clean')
% clean all docs
if isdir(opts.DIR)
if opts.Verbose, fprintf('Cleaning %s\n', opts.DIR); end
rmdir(opts.DIR, 's');
end
return;
elseif ~any(strcmp(opts.topic, {'-wiki', '-contents', '-helptoc'}))
if ~isdir(opts.DIR)
% prepare output directory and CSS stylesheets
if opts.Verbose, fprintf('Creating %s\n', opts.DIR); end
mkdir(opts.DIR);
copy_stylesheets(opts);
end
end
% generate docs
[filename, isbatch, needed] = get_output_filename(opts, opts.topic);
if needed
switch opts.topic
case '-wiki'
download_wiki(opts);
generate_wiki(opts);
case '-all'
generate_all_docs(opts);
case {'-index', '-indexcat'}
txt = generate_index(opts, opts.topic);
case '-contents'
txt = generate_contents_m(opts);
case '-helptoc'
txt = generate_helptoc_xml(opts);
otherwise
txt = generate_doc(opts, opts.topic);
end
if ~isbatch
% write to file
assert(~isempty(txt), 'No doc generated');
filewrite(filename, txt);
end
end
% return/show result
if nargout > 0
% return output filename
varargout{1} = filename;
else
if ~isbatch
% open documentation in embedded browser or editor
[~,~,ext] = fileparts(filename);
if strcmp(ext, '.html')
web(filename, '-new');
else
edit(filename);
end
else
% show output directory
if ispc()
winopen(filename);
else
disp(filename);
end
end
end
end
function opts = parse_options(varargin)
%PARSE_OPTIONS Parse function input argument
% helper function to validate true/false arguments
isbool = @(x) isscalar(x) && (islogical(x) || isnumeric(x));
% parse input arguments
p = inputParser();
p.addOptional('topic', '-all', @ischar);
p.addParameter('Force', true, isbool);
p.addParameter('MarkdownRender', true, isbool);
p.addParameter('MarkdownBackend', 'commonmark-java', @ischar);
p.addParameter('AutoLinking', false, isbool);
p.addParameter('AutoLinkingDeep', false, isbool);
p.addParameter('AutoLinkingCV', true, isbool);
p.addParameter('SyntaxHighlighting', true, isbool);
p.addParameter('PrettifyLang', 'lang-matlab', @ischar);
p.addParameter('TableSorting', true, isbool);
p.addParameter('NoExternals', true, isbool);
p.addParameter('IndexGroups', true, isbool);
p.addParameter('IgnoreHandleClass', true, isbool);
p.addParameter('Verbose', true, isbool);
p.addParameter('Progress', true, isbool);
% options struct
p.parse(varargin{:});
opts = p.Results;
% documentation output directory
opts.DIR = fullfile(mexopencv.root(), 'doc', 'matlab');
% validate topic/action
if strncmp(opts.topic, '-', 1)
opts.topic = validatestring(opts.topic, ...
{'-clean', '-wiki', '-all', '-index', '-indexcat', '-contents', '-helptoc'});
elseif ~strncmp(opts.topic, 'cv.', 3)
% prepend "cv." prefix to topic name if necessary
opts.topic = ['cv.' opts.topic];
end
% list of recognized backends
backends = {
'commonmark-java'
'MarkdownPapers'
'pegdown'
'markdownj'
'markdown4j'
'txtmark'
};
opts.MarkdownBackend = validatestring(opts.MarkdownBackend, backends);
opts.Ignore = {};
if opts.IgnoreHandleClass
% methods/properties/events inherited from "handle"
opts.Ignore = union(opts.Ignore, methods('handle'));
opts.Ignore = union(opts.Ignore, properties('handle'));
opts.Ignore = union(opts.Ignore, events('handle'));
opts.Ignore = setdiff(opts.Ignore, 'delete'); % exclude dtor
end
end
function init_jsoup(opts)
%INIT_JSOUP Download and setup the jsoup Java library
persistent initialized
if isempty(initialized), initialized = false; end
if ~initialized
% download if it doesn't exist
dname = fullfile(mexopencv.root(), 'utils', 'jars', 'jsoup');
if ~isdir(dname)
MavenDownload('org.jsoup', 'jsoup', 'OutDir',dname, ...
'Verbose',opts.Verbose);
end
% add all JAR files to classpath
if opts.Verbose, disp('Initializing jsoup'); end
JavaAddJarDir(dname);
% mark as initialized
initialized = true;
end
end
function init_markdown(opts)
%INIT_MARKDOWN Download and setup backend Markdown Java libraries
persistent initialized
if isempty(initialized), initialized = {}; end
if ~ismember(opts.MarkdownBackend, initialized)
% download if it doesn't exist
dname = fullfile(mexopencv.root(), 'utils', 'jars', opts.MarkdownBackend);
if ~isdir(dname)
% group and artifact ids
switch opts.MarkdownBackend
case 'commonmark-java'
groupId = 'com.atlassian.commonmark';
artifactId = 'commonmark';
case 'MarkdownPapers'
groupId = 'org.tautua.markdownpapers';
artifactId = 'markdownpapers-core';
case 'pegdown'
groupId = 'org.pegdown';
artifactId = 'pegdown';
case 'markdownj'
groupId = 'org.markdownj';
artifactId = 'markdownj-core';
case 'markdown4j'
groupId = 'org.commonjava.googlecode.markdown4j';
artifactId = 'markdown4j';
case 'txtmark'
groupId = 'com.github.rjeschke';
artifactId = 'txtmark';
otherwise
error('Unrecognized Markdown backend')
end
MavenDownload(groupId, artifactId, 'OutDir',dname, ...
'Verbose',opts.Verbose);
end
% add all JAR files to classpath
if opts.Verbose, fprintf('Initializing %s\n', opts.MarkdownBackend); end
JavaAddJarDir(dname);
% mark as initialized
initialized = union(initialized, opts.MarkdownBackend);
end
end
function JavaAddJarDir(dname)
%JAVAADDJARDIR Add all jar files inside a directory to Java class path
% list of JAR files inside directory
jars = dir(fullfile(dname, '*.jar'));
jars = {jars.name};
% only keep those not already on the Java class path
jcp = javaclasspath();
idx = cellfun(@(j) all(cellfun(@isempty, strfind(jcp, j))), jars);
jars = jars(idx);
% put remaining jars on classpath
if ~isempty(jars)
jars = cellfun(@(j) fullfile(dname, j), jars, 'UniformOutput',false);
javaaddpath(jars);
end
end
function copy_stylesheets(opts)
%COPY_STYLESHEETS Copy CSS stylesheets to output directory
% copy default stylesheet locally
CSS = fullfile(toolboxdir('matlab'), 'helptools', 'private', 'helpwin.css');
copyfile(CSS, opts.DIR);
% copy second stylesheet with customization
CSS = fullfile(fileparts(mfilename('fullpath')), 'helpwin_custom.css');
copyfile(CSS, opts.DIR);
end
function [filename, isbatch, needed] = get_output_filename(opts, topic, fname)
%GET_OUTPUT_FILENAME Output filename according to action
isbatch = false;
switch topic
case '-wiki'
if nargin > 2
[~,fname,~] = fileparts(fname);
filename = [strrep(lower(fname), '-', '_') '.html'];
filename = fullfile(mexopencv.root(), 'doc', 'wiki', filename);
else
filename = fullfile(mexopencv.root(), 'doc', 'wiki');
isbatch = true;
end
case '-all'
filename = opts.DIR;
isbatch = true;
case '-index'
filename = fullfile(opts.DIR, 'index.html');
case '-indexcat'
filename = fullfile(opts.DIR, 'index_cat.html');
case '-contents'
filename = fullfile(mexopencv.root(), 'Contents.m');
case '-helptoc'
filename = fullfile(mexopencv.root(), 'doc', 'helpfuncbycat.xml');
otherwise
filename = fullfile(opts.DIR, [topic '.html']);
end
% checks if file already exists
needed = isbatch || opts.Force || exist(filename, 'file') ~= 2;
end
function files = download_wiki(opts)
%DOWNLOAD_WIKI Download wiki files from GitHub
% list of Wiki files
dname = get_output_filename(opts, '-wiki');
files = {
'README.md'
'Home.md'
'Getting-Started.md'
'Developing-a-new-MEX-function.md'
'Gotchas.md'
'Installation-(Windows,-MATLAB,-OpenCV-3).md'
'Installation-(Windows,-Octave,-OpenCV-3).md'
'Installation-(Linux,-MATLAB,-OpenCV-3).md'
'Installation-(Linux,-Octave,-OpenCV-3).md'
'Installation-(Windows,-MATLAB,-OpenCV-2).md'
'Troubleshooting-(Windows).md'
'Troubleshooting-(UNIX).md'
};
% download from GitHub
% (git clone https://github.com/kyamagu/mexopencv.wiki.git)
url = 'https://rawgit.com/wiki/kyamagu/mexopencv/';
if ~isdir(dname), mkdir(dname); end
copyfile(fullfile(mexopencv.root(), 'README.markdown'), fullfile(dname, files{1}));
for i=2:numel(files)
fname = fullfile(dname, files{i});
if exist(fname, 'file') ~= 2 % || opts.Force
if opts.Verbose, fprintf('Downloading %s...\n', files{i}); end
urlwrite([url files{i}], fname);
end
end
end
function generate_wiki(opts)
%GENERATE_WIKI Generate HTML docs from Wiki files
% process markdown files
dname = get_output_filename(opts, '-wiki');
files = dir(fullfile(dname, '*.md'));
for i=1:numel(files)
% convert and save as HTML
fname = fullfile(dname, files(i).name);
[filename, ~, needed] = get_output_filename(opts, '-wiki', fname);
if needed
txt = wiki_md2html(opts, fname);
assert(~isempty(txt), 'Failed to convert Markdown');
filewrite(filename, txt);
end
end
end
function generate_all_docs(opts)
%GENERATE_ALL_DOCS Generate full docs for all functions
% create index.html
[filename, ~, needed] = get_output_filename(opts, '-index');
if needed
if opts.Verbose, disp('Creating index...'); end
txt = generate_index(opts, '-index');
assert(~isempty(txt), 'Failed to generate index');
filewrite(filename, txt);
end
% create index_cat.html
[filename, ~, needed] = get_output_filename(opts, '-indexcat');
if needed
if opts.Verbose, disp('Creating index...'); end
txt = generate_index(opts, '-indexcat');
assert(~isempty(txt), 'Failed to generate index');
filewrite(filename, txt);
end
% get a list of functions/classes
list = enumerate_mexopencv_members(opts);
% show progress
if opts.Progress
hWait = waitbar(0, 'Generating docs...', 'Name',mfilename(), ...
'CreateCancelBtn','setappdata(gcbf,''cancel'',true)');
setappdata(hWait, 'cancel',false);
wbCleanObj = onCleanup(@() delete(hWait));
end
% process all functions
if opts.Verbose, disp('Creating docs...'); end
for i=1:numel(list)
% next topic to process
topic = list{i};
if opts.Progress
waitbar(i/numel(list), hWait, strrep(topic, '_', '\_'));
if getappdata(hWait, 'cancel'), break; end
end
% generate HTML doc file
[filename, ~, needed] = get_output_filename(opts, topic);
if needed
txt = generate_doc(opts, topic);
if ~isempty(txt)
filewrite(filename, txt);
status = 'DONE';
else
% non-existant cv function
% (doc/help/help2html cannot process hidden and private methods)
%TODO: it seems thats no longer the case in recent versions,
% we need to filter them in enumerate_mexopencv_members
status = 'MISSING';
end
if opts.Verbose, fprintf('[%s] %s\n', status, topic); end
end
end
end
function txt = generate_doc(opts, topic)
%GENERATE_DOC Generate HTML docs for a function, class method/member, etc.
% convert M-help into parsed HTML document
jdoc = parse_help2html(opts, topic);
if isempty(jdoc)
txt = '';
return;
end
% convert document back to HTML string
txt = char(jdoc.toString());
end
function txt = generate_index(opts, topic)
%GENERATE_INDEX Create index.html/index_cat.html containing list of all functions
% HTML doc of cv package function/class names and their H1-lines
opts.MarkdownRender = false; % turn off markdown processing for index
jdoc = parse_help2html(opts, 'cv');
if isempty(jdoc)
txt = '';
return;
end
% replace title near the top
div = jdoc.select('div.title').empty().first();
assert(~isempty(div), '<div> not found');
a = div.appendElement('a');
a.text('mexopencv').attr('href', 'https://github.com/kyamagu/mexopencv');
% append description after it
p = jdoc.createElement('p').addClass('h1line');
p.appendText('Collection and development kit of MATLAB MEX functions for ');
p.appendElement('a').text('OpenCV').attr('href', 'https://opencv.org/');
p.appendText(' library.');
div.after(p);
% extract listing of cv package function/class names and their H1-lines
pre = jdoc.select('div.helptext > pre').first();
assert(~isempty(pre), '<pre> not found');
txt = char(pre.text());
t = create_files_table(opts, txt);
% format it as HTML table(s)
switch topic
case '-index'
% one big table
txt = table_to_index_html(opts, t);
case '-indexcat'
% one table per module
txt = table_to_index_cat_html(opts, t);
otherwise
txt = '';
end
% insert table(s)
div = pre.parent();
assert(~isempty(div), '<div> not found');
div.removeClass('helptext').addClass('helpcontent');
div.html(txt);
% style table(s)
tabl = div.select('table');
assert(~isempty(tabl), '<table> not found');
tabl.addClass('table');
if opts.TableSorting
tabl.addClass('sortable'); % enable_sortable_tables
end
% convert document back to HTML string
txt = char(jdoc.toString());
end
function txt = generate_contents_m(opts)
%GENERATE_CONTENTS_M Create Contents.m containing list of all functions
% cv package function/class names and their H1-lines
txt = help('cv');
if isempty(txt)
return;
end
% parse text into table
t = create_files_table(opts, txt);
% format table as contents.m file
txt = table_to_contents_m(opts, t);
end
function txt = generate_helptoc_xml(opts)
%GENERATE_HELPTOC_XML Create helpfuncbycat.xml containing list of all functions
% cv package function/class names and their H1-lines
txt = help('cv');
if isempty(txt)
return;
end
% parse text into table
t = create_files_table(opts, txt);
% format table as helpfuncbycat.xml file
txt = table_to_helptoc_xml(opts, t);
end
function t = create_files_table(opts, txt)
%CREATE_FILES_TABLE Build table containing list of all mexopencv files
% split by lines
C = textscan(txt, '%s', 'Delimiter','\n');
C = C{1};
C(cellfun(@isempty, C)) = [];
% remove section headers
str = 'Contents of ';
C(strncmp(C, str, numel(str))) = [];
% remove simcoverage entry cv.schema
str = 'schema ';
C(strncmp(C, str, numel(str))) = [];
% split each line: "name - description"
C = regexp(C, ' - ', 'split', 'once');
C = strtrim(cat(1, C{:}));
% add cv. prefix to name
C(:,1) = strcat('cv.', C(:,1));
% create table
t = cell2table(C, 'VariableNames',{'names','descriptions'});
if opts.IndexGroups
% extract OpenCV module names for each mexopencv function
tt = enumerate_mexopencv_files(opts);
% join the two tables by name
t = innerjoin(t, tt, 'Keys','names');
% sort table
t = sortrows(t, {'repos', 'modules', 'names'});
end
end
function txt = table_to_index_html(opts, t)
%TABLE_TO_INDEX_HTML Format table of mexopencv files as HTML table
if opts.IndexGroups
linkify = @(p) strrep(strrep(p, mexopencv.root(), ...
'https://github.com/kyamagu/mexopencv/blob/master'), '\', '/');
txt = strcat('<tr>', ...
'<td><a href="', t.names, '.html">', t.names, '</a></td>', ...
'<td>', t.modules, '</td>', ...
'<td>', t.repos, '</td>', ...
'<td>', t.descriptions, '</td>', ...
'<td><a href="', linkify(t.cppfiles), '">C</a> ', ...
'<a href="', linkify(t.mfiles), '">M</a> ', ...
'<a href="', linkify(t.tfiles), '">T</a></td>', ...
'</tr>');
txt = strjoin({
'<table>'
'<thead><tr><th>Name</th><th>Module</th><th>Repo</th>'
'<th>Description</th><th>Source Files</th></tr></thead>'
'<tbody>'
strjoin(txt, '\n')
'</tbody>'
'</table>'
}, '\n');
else
txt = strcat(...
'<tr><td><a href="', t.names, '.html">', t.names, '</a></td>', ...
'<td>', t.descriptions, '</td></tr>');
txt = strjoin({
'<table>'
'<thead><tr><th>Name</th><th>Description</th></tr></thead>'
'<tbody>'
strjoin(txt, '\n')
'</tbody>'
'</table>'
}, '\n');
end
end
function txt = table_to_index_cat_html(opts, t)
%TABLE_TO_INDEX_CAT_HTML Format table of mexopencv files as HTML tables
opts.IndexGroups = false; % for the table_to_index_html calls below
% format list of files as HTML tables, one per module
txt = {};
[repos,~,rid] = unique(t.repos);
for r=1:max(rid)
tt = t(rid == r,:);
[modules,~,mid] = unique(tt.modules);
txt{end+1} = sprintf('<h1 id="%s">%s</h1>', repos{r}, repos{r});
for m=1:max(mid)
ttt = tt(mid == m,:);
txt{end+1} = sprintf('<h4 id="%s">%s</h4>', modules{m}, modules{m});
txt{end+1} = table_to_index_html(opts, ttt);
end
end
txt = strjoin(txt, '\n');
end
function txt = table_to_contents_m(opts, t)
%TABLE_TO_CONTENTS_M Format table of mexopencv files as contents.m file
% formatting string for each entry
maxlen = max(cellfun(@length, t.names));
frmt = ['%% %-' int2str(maxlen) 's - %s\n'];
% format list of files as Contents.m text
if opts.IndexGroups
txt = {};
[repos,~,rid] = unique(t.repos);
for r=1:max(rid)
tt = t(rid == r,:);
[modules,~,mid] = unique(tt.modules);
txt{end+1} = ['%% ' repos{r} ':'];
txt{end+1} = '%';
for m=1:max(mid)
ttt = tt(mid == m,:);
C = [ttt.names, ttt.descriptions]';
txt{end+1} = ['% ' modules{m} ':'];
txt{end+1} = [sprintf(frmt, C{:}) '%'];
end
end
txt = strjoin(txt, '\n');
else
C = [t.names, t.descriptions]';
txt = [sprintf(frmt, C{:}) '%'];
end
% add header
txt = strjoin({
'% mexopencv'
sprintf('%% Version %s (R%s) %s', cv.Utils.version(), ...
version('-release'), datestr(now(), 'dd-mmmm-yyyy'))
'%'
txt
''
}, '\n');
end
function txt = table_to_helptoc_xml(opts, t)
%TABLE_TO_HELPTOC_XML Format table of mexopencv files as helpfuncbycat.xml file
%HACK: description should not be included in R2014b and up
% (only supported in older help browser "doc -classic")
withPurpose = verLessThan('matlab','8.4');
% format list of files as functions reference for helptoc.xml/helpfuncbycat.xml
txt = {};
txt{end+1} = '<?xml version="1.0" encoding="utf-8"?>';
txt{end+1} = '<toc version="2.0">';
txt{end+1} = ' <tocitem image="HelpIcon.FUNCTION" target="matlab/index.html">Functions';
if opts.IndexGroups
[repos,~,rid] = unique(t.repos);
for r=1:max(rid)
tt = t(rid == r,:);
[modules,~,mid] = unique(tt.modules);
txt{end+1} = sprintf(...
' <tocitem target="matlab/index_cat.html#%s">%s', ...
repos{r}, repos{r});
for m=1:max(mid)
ttt = tt(mid == m,:);
if withPurpose
C = strcat(...
' <tocitem image="HelpIcon.FUNCTION" target="matlab/', ...
ttt.names, '.html"><name>', ttt.names, '</name><purpose>', ...
xml_escape(ttt.descriptions), '</purpose></tocitem>');
else
C = strcat(...
' <tocitem image="HelpIcon.FUNCTION" target="matlab/', ...
ttt.names, '.html">', ttt.names, '</tocitem>');
end
txt{end+1} = sprintf(...
' <tocitem target="matlab/index_cat.html#%s">%s', ...
modules{m}, modules{m});
txt{end+1} = strjoin(C, '\n');
txt{end+1} = ' </tocitem>';
end
txt{end+1} = ' </tocitem>';
end
else
if withPurpose
C = strcat(...
' <tocitem image="HelpIcon.FUNCTION" target="matlab/', ...
t.names, '.html"><name>', t.names, '</name><purpose>', ...
xml_escape(t.descriptions), '</purpose></tocitem>');
else
C = strcat(...
' <tocitem image="HelpIcon.FUNCTION" target="matlab/', ...
t.names, '.html">', t.names, '</tocitem>');
end
txt{end+1} = strjoin(C, '\n');
end
txt{end+1} = ' </tocitem>';
txt{end+1} = '</toc>';
txt{end+1} = '';
txt = strjoin(txt, '\n');
end
function txt = wiki_md2html(opts, mdFile)
%WIKI_MD2HTML Convert Wiki Markdown file to HTML
% read and convert Markdown to HTML
txt = fileread(mdFile);
txt = MarkdownProcess(txt, opts.MarkdownBackend);
% full HMTL page from fragment
[~,name] = fileparts(mdFile);
C = {
'<!DOCTYPE html>'
'<html>'
'<head>'
'<meta charset="utf-8">'
['<title>' strrep(name, '-', ' ') '</title>']
'<link rel="stylesheet" type="text/css" href="../matlab/helpwin.css">'
'<link rel="stylesheet" type="text/css" href="../matlab/helpwin_custom.css">'
};
if opts.SyntaxHighlighting
C = [
C
'<link rel="stylesheet" type="text/css" href="../matlab/matlab.min.css">'
'</head>'
'<body onload="onReady();">'
txt
'<script type="text/javascript" src="../matlab/prettify.js"></script>'
'<script type="text/javascript" src="../matlab/lang-matlab.min.js"></script>'
'<script type="text/javascript">'
'function onReady() {'
' var list = document.getElementsByTagName("pre");'
' for (var i = 0; i < list.length; ++i) {'
' if (list[i].classList)'
' list[i].classList.add("prettyprint");'
' else'
' list[i].className += " prettyprint";'
' }'
' PR.prettyPrint();'
'}'
'</script>'
'</body>'
'</html>'
];
else
C = [
C
'</head>'
'<body>'
txt
'</body>'
'</html>'
];
end
C{end+1} = '';
txt = strjoin(C, '\n');
end
function jdoc = parse_help2html(opts, topic)
%PARSE_HELP2HTML Parse HELP2HTML output and perform common filtering
% convert M-help into HTML document
[txt, found] = help2html(topic);
if ~found
jdoc = [];
return;
end
% parse HTML string
jdoc = javaMethod('parse', 'org.jsoup.Jsoup', txt);
jdoc.outputSettings.prettyPrint(false); % for proper markdown parsing
% replace CSS stylesheet with our local version (relative URI)
jdoc.select('link[href$=helpwin.css]').attr('href', 'helpwin.css');
% add another sytlesheet for customization (relative URI)
inject_css_file(jdoc, 'helpwin_custom.css');
% change title
txt = char(jdoc.title());
txt = strrep(txt, 'MATLAB File Help: ', '');
txt = strrep(txt, ' - MATLAB File Help', '');
jdoc.title([txt ' - mexopencv']);
% add generator meta tag
mt = append_element(jdoc.head(), 'meta');
mt.attr('name', 'generator').attr('content', ['MATLAB ' version()]);
% remove highlighting of function names
% (turn <span class="helptopic">func</span> into func)
jdoc.select('span.helptopic').unwrap();
% rewrite <a href="matlab:..">..</a> hyperlinks (mainly in header/footer)
rewrite_hyperlinks(opts, jdoc);
if opts.MarkdownRender
% render Markdown
render_markdown(opts, jdoc);
% mark the first paragraph which corresponds to H1-line
p = jdoc.select('div.helpcontent > p:first-child').first();
if ~isempty(p)
p.addClass('h1line');
% add description meta tag (using H1-line description)
desc = [topic ' - ' char(p.text())];
mt = append_element(jdoc.head(), 'meta');
mt.attr('name', 'description').attr('content', desc);
end
end
% set external links to open in new tabs
jdoc.select('a[href^=http]').attr('target', '_blank');
% enable syntax highlighting of code blocks using google-code-prettify
if opts.SyntaxHighlighting && ~strcmp(topic, 'cv')
enable_syntax_highlighting(opts, jdoc);
end
% enable sorting tables (only used in index.html)
if opts.TableSorting && strcmp(topic, 'cv')
enable_sortable_tables(opts, jdoc);
end
end
function rewrite_hyperlinks(opts, jdoc)
%REWRITE_HYPERLINKS Rewrite hyperlinks for offline use
% replace "matlab:helpwin" (i.e "Default Topics") with index link
jdoc.select('a[href=matlab:helpwin]').html('Index').attr('href', 'index.html');
% process rest of "matlab:(helpwin|doc) cv.fcn" links
links = jdoc.select('a[href^=matlab:helpwin], a[href^=matlab:doc]');
it = links.iterator(); % iterate over links as ArrayList<Element>
while it.hasNext()
% get href
a = it.next();
topic = char(a.attr('href'));
% remove "matlab:(helpwin|doc)" prefix
topic = regexprep(topic, 'matlab:(helpwin|doc)\s*', '', 'once');
% remove enclosing parens/quotes in case of function syntax
% "matlab:helpwin('x')" vs. command syntax "matlab:helpwin x"
topic = regexprep(topic, '^\(''', '', 'once');
topic = regexprep(topic, '''\);?$', '', 'once');
% fix class methods (i.e: cv.Class/method -> cv.Class.method)
topic = strrep(topic, '/', '.');
% check if link to another cv function
if strncmp(topic, 'cv.', 3)
if is_handle_member(opts, topic)
% replace link to handle.* methods
url = 'https://www.mathworks.com/help/matlab/ref/handle-class.html';
a.attr('href', url);
else
% replace link with a relative "fcn.html" link
a.attr('href', [topic '.html']);
end
else
% check if link to an official TMW function
url = is_mathworks_function(opts, topic);
if ~isempty(url)
a.attr('href', url);
end
end
end
% remove some raw-code links ("matlab:open .." and "matlab:edit ..")
jdoc.select('a[href~=matlab:(open|edit)]').remove();
% turn any remaning "matlab:" links to plain text
jdoc.select('a[href^=matlab:]').unwrap();
end
function render_markdown(opts, jdoc)
%RENDER_MARKDOWN Convert help text from Markdown to HTML + autolinking
% extract markdown text
pre = jdoc.select('div.helptext > pre').first();
assert(~isempty(pre), '<pre> not found');
%NOTE: this also undoes http:// autolinking done by help2html
txt = char(pre.text());
%HACK: for correct Markdown indentation, we remove two leading spaces:
% - first one inserted by help2html for some reason
% - second one is part of when we write a comment (e.g "% some text")
% being the space between the % symbol and the first character
txt = regexprep(txt, '^ ', '', 'lineanchors');
% remove redundant function name at the beginning (exclude property docs)
if jdoc.select('div.sectiontitle:containsOwn(Property Details)').isEmpty()
txt = regexprep(txt, '^\w+\s+', '', 'once');
end
% autolink "http://" and "www." text
% (before rendering MD so that we dont later double-link <a href=""> links)
if opts.AutoLinking
txt = auto_link_http(opts, txt);
end
if opts.AutoLinkingDeep
txt = auto_link_www(opts, txt);
end
% convert Markdown to HTML
txt = MarkdownProcess(txt, opts.MarkdownBackend);
% autolink "cv." functions text
% (after rendering MD so that we dont break indented code with cv. calls)
if opts.AutoLinkingCV
txt = auto_link_cv(opts, txt);
end
% replace the "helptext" part with the rendered Markdown
div = jdoc.select('div.helptext').first();
assert(~isempty(div), '<div> not found');
div.removeClass('helptext').addClass('helpcontent');
div.html(txt);
end
function klass = enable_syntax_highlighting(opts, jdoc)
%ENABLE_SYNTAX_HIGHLIGHTING Add syntax highlighting using google-code-prettify
% add prettyprint CSS class to pre+code blocks
klass = 'prettyprint';
jdoc.select('pre:has(code)').addClass(klass);
% set language hint (only if one is not already present, which could be
% specified in case MD backend supports fenced code blocks "```lang")
if ~isempty(opts.PrettifyLang)
jdoc.select('pre:has(code:not([class]))').addClass(opts.PrettifyLang);
end
% append code-prettify matlab theme CSS stylesheet
url = 'https://cdn.rawgit.com/amroamroamro/prettify-matlab/master/dist/css/matlab.min.css';
inject_css_file(jdoc, get_resource(opts, url));
% append code-prettify JavaScript
url = 'https://cdn.rawgit.com/google/code-prettify/master/loader/prettify.js';
inject_js_file(jdoc, get_resource(opts, url));
% append lang-matlab extension for code-prettify JavaScript
url = 'https://cdn.rawgit.com/amroamroamro/prettify-matlab/master/dist/js/full/lang-matlab.min.js';
inject_js_file(jdoc, get_resource(opts, url));
% execute JavaScript when page is ready
jdoc.body().attr('onload', 'PR.prettyPrint();');
end
function klass = enable_sortable_tables(opts, jdoc)
%ENABLE_SORTABLE_TABLES Adds ability to sort tables by clicking on headers
% set CSS class to tables with header
klass = 'sortable';
jdoc.select('table:has(thead)').addClass(klass);
% append sorttable JavaScript library
url = 'https://cdn.jsdelivr.net/sorttable/2/sorttable.min.js';
inject_js_file(jdoc, get_resource(opts, url));
end