-
Notifications
You must be signed in to change notification settings - Fork 130
/
ox-blackfriday.el
1672 lines (1465 loc) · 72.1 KB
/
ox-blackfriday.el
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
;;; ox-blackfriday.el --- Blackfriday Markdown Back-End for Org Export Engine -*- lexical-binding: t -*-
;; Authors: Matt Price <[email protected]>
;; Kaushal Modi <[email protected]>
;; URL: https://ox-hugo.scripter.co
;; Package-Requires: ((emacs "24.5"))
;; Version: 0.1
;;; Commentary:
;; This library implements a Markdown back-end (Blackfriday flavor
;; (https://github.com/russross/blackfriday)) for Org exporter, based
;; on the ox-md exporter.
;; It started off as a clone of Lars Tveito's GitHub Flavored Markdown
;; exporter (https://github.com/larstvei/ox-gfm).
;;; Code:
(require 'org)
(require 'ox-md)
(require 'ox-publish)
(require 'table) ;To support tables written in table.el format
(require 'subr-x) ;For `string-remove-suffix'
;;; Variables
(defvar org-blackfriday-width-cookies nil)
(defvar org-blackfriday-width-cookies-table nil)
(defconst org-blackfriday-table-left-border "")
(defconst org-blackfriday-table-right-border " ")
(defconst org-blackfriday-table-separator "| ")
(defconst org-blackfriday-html5-inline-elements
'(;; "a" ;Use Org [[link]] syntax instead
"abbr" "audio"
;; "b" ;Use Org *bold* syntax instead
"bdi" "bdo"
;; "br" ;Use "\\" or "#+options: \n:t" instead
"button"
"canvas" "cite"
;; "code" ;Use Org =code= or ~code~ instead
"data" "datalist" "del" "dfn"
;; "em" ;Use Org /italics/ syntax instead
"embed"
;; "i" ;Use Org /italics/ syntax instead
"iframe"
;; "img" ;Use Org image insertion syntax instead
"input" "ins"
"kbd"
"label"
"map" "mark" "meter"
"noscript"
"object" "output"
"picture" "progress"
"q"
"ruby"
"s" "samp" "script" "select" "slot" "small" "span"
;; "strong" ;Use Org *bold* syntax instead
;; "sub" ;Use Org abc_{subscript} syntax instead
;; "sup" ;Use Org abc^{superscript} syntax instead
"svg"
"template" "textarea" "time"
"u"
"var" "video")
"HTML 5 inline elements.
https://developer.mozilla.org/en-US/docs/Web/HTML/Inline_elements#list_of_inline_elements.")
(defvar org-blackfriday--hrule-inserted nil
"State variable to track if the horizontal rule was inserted.
This check is specifically track if that horizontal rule was
inserted after the first row of the table.")
(defvar org-blackfriday--code-block-num-backticks-default 3
"Variable to store the default number of backticks for code block.
Note that this variable is *only* for internal use.")
(defvar org-blackfriday--code-block-num-backticks org-blackfriday--code-block-num-backticks-default
"Variable to store the number of backticks for code block.
By default, it stays at 3. This number is incremented for few
corner cases.
Note that this variable is *only* for internal use.")
(defvar org-blackfriday--org-element-string '((src-block . "Code Snippet")
(table . "Table")
(figure . "Figure")) ;Note that `figure' is not an actual Org element
"Alist of strings used to represent various Org elements.")
(defvar org-blackfriday--ltximg-directory "ltximg/"
"Sub directory created inside the site's static directory for LaTeX images.
This sub directory is created when an export option like
`tex:dvisvgm' is used.")
;;; User-Configurable Variables
(defgroup org-export-blackfriday nil
"Options for exporting Org mode files to Blackfriday Markdown."
:tag "Org Export Blackfriday"
:group 'org-export)
(defcustom org-blackfriday-syntax-highlighting-langs
'(("ipython" . "python")
("jupyter-python" . "python")
("conf-toml" . "toml")
("conf-space" . "cfg")
("conf" . "cfg"))
"Alist mapping src block languages to their syntax highlighting languages.
The key is the src block language name. The value is the
language name to be used in the exported Markdown. The value
language name would be one that Hugo's Chroma syntax highlighter
would understand.
For most src languages, this variable will not need to be
customized. But there are some src block \"languages\" like
`ipython' and `jupyter-python' for which, the exported language
tag needs to be `python'."
:group 'org-export-blackfriday
:type '(repeat
(cons
(string "Src Block language")
(string "Syntax highlighting language"))))
;;; Define Back-End
(org-export-define-derived-backend 'blackfriday 'md
:filters-alist '((:filter-parse-tree . org-blackfriday-separate-elements))
;; Do not clutter the *Org Exporter Dispatch* menu.
;; :menu-entry
;; '(?b "Export to Blackfriday Flavored Markdown"
;; ((?B "To temporary buffer"
;; (lambda (a s v b) (org-blackfriday-export-as-markdown a s v)))
;; (?b "To file" (lambda (a s v b) (org-blackfriday-export-to-markdown a s v)))
;; (?o "To file and open"
;; (lambda (a s v b)
;; (if a (org-blackfriday-export-to-markdown t s v)
;; (org-open-file (org-blackfriday-export-to-markdown nil s v)))))))
:translate-alist '((center-block . org-blackfriday-center-block)
(example-block . org-blackfriday-example-block)
(fixed-width . org-blackfriday-fixed-width) ;Org Babel Results
(footnote-reference . org-blackfriday-footnote-reference)
(inner-template . org-blackfriday-inner-template)
(italic . org-blackfriday-italic)
(item . org-blackfriday-item)
(latex-environment . org-blackfriday-latex-environment)
(latex-fragment . org-blackfriday-latex-fragment)
(line-break . org-html-line-break) ;"\\" at EOL forces a line break
(plain-list . org-blackfriday-plain-list)
(plain-text . org-blackfriday-plain-text)
(quote-block . org-blackfriday-quote-block)
(radio-target . org-blackfriday-radio-target)
(special-block . org-blackfriday-special-block)
(src-block . org-blackfriday-src-block)
(strike-through . org-blackfriday-strike-through)
(table-cell . org-blackfriday-table-cell)
(table-row . org-blackfriday-table-row)
(table . org-blackfriday-table)
(target . org-blackfriday-target)
(verse-block . org-blackfriday-verse-block)))
;;; Miscellaneous Helper Functions
;;;; Check if a boolean plist value is non-nil
(defun org-blackfriday--plist-get-true-p (info key)
"Return non-nil if KEY in INFO is non-nil.
Return nil if the value of KEY in INFO is nil, \"nil\" or \"\".
This is a special version of `plist-get' used only for keys that
are expected to hold a boolean value.
INFO is a plist used as a communication channel."
(let ((value (plist-get info key)))
(cond
((or (equal t value)
(equal nil value))
value)
((and (stringp value)
(string= value "nil"))
nil)
(t
;; "" -> nil
;; "t" -> "t"
;; "anything else" -> "anything else"
;; 123 -> nil
(org-string-nw-p value)))))
;;;; Table of contents
(defun org-blackfriday-format-toc (heading info)
"Return an appropriate table of contents entry for HEADING.
INFO is a plist used as a communication channel."
(let* ((title (org-export-data (org-export-get-alt-title heading info) info))
(level (1- (org-element-property :level heading)))
(indent (concat (make-string (* level 2) ? )))
(anchor (or (org-element-property :CUSTOM_ID heading)
(org-export-get-reference heading info))))
(concat indent "- [" title "]" "(#" anchor ")")))
;;;; Extra div hack
(defun org-blackfriday--extra-div-hack (info &optional tag)
"Return string for the \"extra div hack\".
The empty HTML element tags like \"<div></div>\" is a hack to get
around a Blackfriday limitation.
See https://github.com/kaushalmodi/ox-hugo/issues/93.
INFO is a plist used as a communication channel.
If TAG is not specified, it defaults to \"div\"."
(let ((tag (or tag "div")))
(if (org-blackfriday--plist-get-true-p info :hugo-goldmark)
""
(format "\n <%s></%s>" tag tag))))
(defun org-blackfriday--get-ref-prefix (symbol)
"Return the prefix string for SYMBOL which can be an Org element type.
Returns nil if the SYMBOL's prefix string isn't defined."
(let ((prefix-alist '((figure . "figure--")
(radio . "org-radio--")
(src-block . "code-snippet--")
(table . "table--")
(target . "org-target--"))))
(cdr (assoc symbol prefix-alist))))
;;;; Footnote section
(defun org-blackfriday-footnote-section (info &optional is-cjk)
"Format the footnote section.
INFO is a plist used as a communication channel.
IS-CJK should be set to non-nil if the language is Chinese,
Japanese or Korean."
(let ((fn-alist (org-export-collect-footnote-definitions info))
;; Fri Jul 21 14:33:25 EDT 2017 - kmodi
;; TODO: Need to learn using cl-loop
;; Below form from ox-md did not work.
;; (fn-alist-stripped
;; (cl-loop for (n raw) in fn-alist collect
;; (cons n (org-trim (org-export-data raw info)))))
fn-alist-stripped)
(let ((n 1)
def)
(dolist (fn fn-alist)
;; (message "fn: %S" fn)
;; (message "fn: %s" (org-export-data fn info)) ;This gives error
;; (message "fn nth 2 car: %s" (org-export-data (nth 2 fn) info))
(setq def (org-trim (org-export-data (nth 2 fn) info)))
(if (org-blackfriday--plist-get-true-p info :hugo-goldmark)
(progn ;Goldmark
;; Goldmark's "PHP Markdown Extra: Footnotes" extension
;; supports multi-line footnotes --
;; https://github.com/yuin/goldmark/#footnotes-extension.
;; 2nd and further lines in a multi-line footnote need to
;; be indented by 4 spaces.
(setq def (replace-regexp-in-string "\n" "\n " def)))
(progn ;Blackfriday
;; Support multi-line footnote definitions by folding all
;; footnote definition lines into a single line as Blackfriday
;; does not support that.
(setq def (if is-cjk
(replace-regexp-in-string
"\n" " " ;If the footnote still has newlines, replace them with spaces
(replace-regexp-in-string
;; Do not insert spaces when joining newlines for
;; CJK languages.
"\\([[:multibyte:]]\\)[[:blank:]]*\n[[:blank:]]*\\([[:multibyte:]]\\)" "\\1\\2"
def))
(replace-regexp-in-string "\n" " " def)))
;; Replace multiple consecutive spaces with a single space.
(setq def (replace-regexp-in-string "[[:blank:]]+" " " def))))
(push (cons n def) fn-alist-stripped)
(setq n (1+ n))))
(when fn-alist-stripped
(mapconcat (lambda (fn)
;; (message "dbg: fn: %0d -- %s" (car fn) (cdr fn))
(format "[^fn:%d]: %s"
(car fn) ;footnote number
(cdr fn))) ;footnote definition
(nreverse fn-alist-stripped)
"\n"))))
;;;; Table-Common
(defun org-blackfriday-table-col-width (table column info)
"Return width of TABLE at given COLUMN using INFO.
INFO is a plist used as communication channel. Width of a column
is determined either by inquiring `org-blackfriday-width-cookies'
in the column, or by the maximum cell with in the column."
(let ((cookie (when (hash-table-p org-blackfriday-width-cookies)
(gethash column org-blackfriday-width-cookies))))
(if (and (eq table org-blackfriday-width-cookies-table)
(not (eq nil cookie)))
cookie
(unless (and (eq table org-blackfriday-width-cookies-table)
(hash-table-p org-blackfriday-width-cookies))
(setq org-blackfriday-width-cookies (make-hash-table))
(setq org-blackfriday-width-cookies-table table))
(let ((max-width 0)
(specialp (org-export-table-has-special-column-p table)))
(org-element-map
table
'table-row
(lambda (row)
(setq max-width
(max (length
(org-export-data
(org-element-contents
(elt (if specialp
(car (org-element-contents row))
(org-element-contents row))
column))
info))
max-width)))
info)
(puthash column max-width org-blackfriday-width-cookies)))))
;;;; Plain List Helper
(defun org-blackfriday--export-ordered-list-as-html-p (plain-list)
"Return non-nil if the PLAIN-LIST needs to be exported as HTML.
The PLAIN-LIST is exported as HTML if the list is an ordered list
and a custom counter is used on second or later item in the list.
Returns nil otherwise."
(let ((type (org-element-property :type plain-list))
has-custom-counter)
(when (eq 'ordered type)
(let ((list-contents (org-element-contents plain-list))
(item-num 1))
(setq has-custom-counter
(catch 'break
(dolist (el list-contents)
(when (eq 'item (car el))
(let* ((item-plist (car (cdr el)))
(counter (plist-get item-plist :counter)))
;; (message "dbg: item num: %d counter: %S" item-num counter)
;; Make special provision for the custom counter
;; notation [@N] only if it's present on second
;; or later items.
(when (and (> item-num 1)
counter)
(throw 'break t))))
(cl-incf item-num))))))
;; (message "dbg: has custom counter: %S" has-custom-counter)
has-custom-counter))
;;;; Table Cell Alignment
;; Below function is heavily adapted from
;; `org-export-table-cell-alignment' from ox.el. The main difference
;; is that the below variation can return a `default' value too.
(defun org-blackfriday-table-cell-alignment (table-cell info)
"Return TABLE-CELL contents alignment.
INFO is a plist used as the communication channel.
Return alignment as specified by the last alignment cookie in the
same column as TABLE-CELL. If no such cookie is found, return
`default'. Possible values are `default', `left', `right' and
`center'."
(let* ((row (org-export-get-parent table-cell))
(table (org-export-get-parent row))
(cells (org-element-contents row))
(columns (length cells))
(column (- columns (length (memq table-cell cells))))
(cache (or (plist-get info :table-cell-alignment-cache)
(let ((table (make-hash-table :test #'eq)))
(plist-put info :table-cell-alignment-cache table)
table)))
(align-vector (or (gethash table cache)
(puthash table (make-vector columns nil) cache))))
(or (aref align-vector column)
(let (cookie-align)
(dolist (row (org-element-contents (org-export-get-parent row)))
(cond
;; In a special row, try to find an alignment cookie at
;; COLUMN.
((org-export-table-row-is-special-p row info)
(let ((value (org-element-contents
(elt (org-element-contents row) column))))
;; Since VALUE is a secondary string, the following
;; checks avoid useless expansion through
;; `org-export-data'.
(when (and value
(not (cdr value))
(stringp (car value))
(string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)?>\\'"
(car value))
(match-string 1 (car value)))
(setq cookie-align (match-string 1 (car value))))))
;; Ignore table rules.
((eq (org-element-property :type row) 'rule))))
;; Return value. Alignment specified by cookies has
;; precedence over alignment deduced from cell's contents.
(aset align-vector
column
(cond ((equal cookie-align "l") 'left)
((equal cookie-align "r") 'right)
((equal cookie-align "c") 'center)
(t 'default)))))))
;;;; Escape certain characters inside equations (Blackfriday bug workaround)
(defun org-blackfriday-escape-chars-in-equation (str)
"Escape few characters in STR so that Blackfriday doesn't parse them.
Do not interpret underscores, asterisks and backquotes in equations as
Markdown formatting
characters (https://gohugo.io/content-management/formats#solution):
\"_\" -> \"\\=\\_\"
\"*\" -> \"\\=\\*\"
\"`\" -> \"\\=\\`\"
https://github.com/kaushalmodi/ox-hugo/issues/104
Blackfriday converts \"(r)\" to Registered Trademark symbol,
\"(c)\" to Copyright symbol, and \"(tm)\" to Trademark symbol if
the SmartyPants extension is enabled (and there is no way to
disable just this). So insert an extra space after the opening
parentheses in those strings to trick Blackfriday/smartParens
from activating inside equations. That extra space anyways
doesn't matter in equations.
\"(c)\" -> \"( c)\"
\"(r)\" -> \"( r)\"
\"(tm)\" -> \"( tm)\"
https://gohugo.io/content-management/formats#solution
https://github.com/kaushalmodi/ox-hugo/issues/138
Need to escape the backslash before any ASCII punctuation character:
!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~
For example:
\"\\(\" -> \"\\\\(\"
\"\\)\" -> \"\\\\)\"
\"\\\\=[\" -> \"\\\\\\=[\"
\"\\\\=]\" -> \"\\\\\\=]\"
\"\\\\={\" -> \"\\\\\\={\"
\"\\\\=}\" -> \"\\\\\\=}\"
\"\\|\" -> \"\\\\|\"
\"](\" -> \"\\]\\(\"
Also escape the backslash at the end of the line, otherwise
it will be interpreted as a hard line break."
(let* (
;; Escape the backslash before punctuation characters, e.g.,
;; \( -> \\(, \) -> \\), \[ -> \\[, \] -> \\], \{ -> \\{, \} -> \\}, \| -> \\|
(escaped-str (replace-regexp-in-string "\\(\\\\[][(){}!\"#$%&'*+,./:;<=>?@\\^_`|~-]\\)" "\\\\\\1" str))
;; _ -> \_, * -> \*, ` -> \`
(escaped-str (replace-regexp-in-string "[_*`]" "\\\\\\&" escaped-str))
;; (c) -> ( c), (r) -> ( r), (tm) -> ( tm)
(escaped-str (replace-regexp-in-string "(\\(c\\|r\\|tm\\))" "( \\1)" escaped-str))
;; ]( -> \]\(
(escaped-str (replace-regexp-in-string "](" "\\\\]\\\\(" escaped-str))
;; Replace "\" at EOL with "\\"
(escaped-str (replace-regexp-in-string "\\\\[[:blank:]]*$" "\\\\\\\\" escaped-str)))
escaped-str))
;;;; Reset org-blackfriday--code-block-num-backticks
(defun org-blackfriday--reset-org-blackfriday--code-block-num-backticks (_backend)
"Reset `org-blackfriday--code-block-num-backticks' to its default value."
(setq org-blackfriday--code-block-num-backticks org-blackfriday--code-block-num-backticks-default))
(add-hook 'org-export-before-processing-hook #'org-blackfriday--reset-org-blackfriday--code-block-num-backticks)
;;;; Make CSS property string
(defun org-blackfriday--make-css-property-string (props)
"Return a list of CSS properties, as a string.
PROPS is a plist where values are either strings or nil. A prop
with a nil value will be omitted from the result.
This function is adapted from `org-html--make-attribute-string'."
(let (ret)
(dolist (item props (mapconcat #'identity (nreverse ret) " "))
(cond ((null item)
(pop ret))
((symbolp item)
(push (substring (symbol-name item) 1) ret))
(t
(let ((key (car ret))
(value (replace-regexp-in-string
"\"" """ (org-html-encode-plain-text item))))
(setcar ret (format "%s: %s; " key value))))))))
;;;; Get CSS string
(defun org-blackfriday--get-style-str (elem)
"Get HTML style tag string for ELEM.
If #+attr_html is used to specify one or more classes for ELEM
and if #+attr_css is also used, then an inline style string is
returned such that it applies the specified CSS to the first of
those specified classes.
Returns an empty string if either #+attr_html or #+attr_css are
not used, or if a class name is not specified in #+attr_html."
(let* ((html-attr (org-export-read-attribute :attr_html elem))
(class (plist-get html-attr :class))
(first-class (when (stringp class)
(car (split-string class))))
(style-str ""))
(when first-class
(let* ((css-props (org-export-read-attribute :attr_css elem))
(css-props-str (org-blackfriday--make-css-property-string css-props)))
(when (org-string-nw-p css-props-str)
(setq style-str (format "<style>.%s { %s }</style>\n\n"
first-class css-props-str)))))
style-str))
;;;; Wrap with HTML attributes
(defun org-blackfriday--div-wrap-maybe (elem contents info)
"Wrap the CONTENTS with HTML div tags.
INFO is a plist used as a communication channel.
The div wrapping is done only if HTML attributes are set for the
ELEM Org element using #+attr_html.
If #+attr_css is also used, and if one or more classes are
specified in #+attr_html, then an inline style is also inserted
that applies the specified CSS to the first of those specified
classes.
If CONTENTS is nil, and #+attr_css is used, return only the HTML
style tag."
(let* ((elem-type (org-element-type elem))
(html-attr (let ((attr1 (org-export-read-attribute :attr_html elem)))
(when (equal elem-type 'paragraph)
;; Remove "target" and "rel" attributes from the
;; list of a paragraph's HTML attributes as they
;; would be meant for links inside the paragraph
;; instead of the paragraph itself.
(plist-put attr1 :target nil)
(plist-put attr1 :rel nil)
;; Remove other attributes from the list of a
;; paragraph's HTML attributes which would be meant
;; for the inline images inside that paragraph.
(plist-put attr1 :src nil)
(plist-put attr1 :alt nil)
(plist-put attr1 :height nil)
(plist-put attr1 :width nil))
attr1))
(html-attr-str (org-blackfriday--make-attribute-string html-attr))
(ret contents))
(when (org-string-nw-p html-attr-str)
(setq ret (concat (org-blackfriday--get-style-str elem)
(if contents
(format "<div %s>%s\n\n%s\n</div>"
html-attr-str (org-blackfriday--extra-div-hack info) contents))
"")))
ret))
;;;; Sanitize URL
(defun org-blackfriday--url-sanitize-maybe (info url)
"Sanitize the URL by replace certain characters with their hex encoding.
INFO is a plist used as a communication channel.
Replaces \"_\" with \"%5F\" only if :hugo-goldmark is nil.
Workaround for Blackfriday bug https://github.com/russross/blackfriday/issues/278."
(if (not (org-blackfriday--plist-get-true-p info :hugo-goldmark))
(replace-regexp-in-string "_" "%5F" url)
url))
;;;; Blackfriday Issue 239 Workaround
(defun org-blackfriday--issue-239-workaround (code parent-type)
"Prefix Markdown list characters with zero width space.
CODE is the content of the source or example block. PARENT-TYPE
is the type of the Org element wrapping that source or example
block.
Hack to avert the Blackfriday bug:
https://github.com/russross/blackfriday/issues/239. Remove this
hack once that issue is resolved.
Prefix the ASTERISK (0x2a), PLUS SIGN (0x2b) and HYPHEN-MINUS
\(0x2d) characters with ZERO WIDTH SPACE (0x200b), if they
appear at BOL (following optional spaces).
Details: https://github.com/kaushalmodi/ox-hugo/issues/57."
;; (message "[ox-bf bfissue 239 DBG] parent type: %S" parent-type)
(if (equal 'item parent-type)
(setq code (replace-regexp-in-string "^\\s-*[-+*] " "\\&" code))
;; There's a ZERO WIDTH SPACE char (0x200b) here ^^,
;; (after «"», but before «\\&"» above)
;; It's not visible (because zero width), but it's there.
code))
;;;; Get Reference
(defun org-blackfriday--get-reference (elem)
"Return a reference for ELEM using its \"#+name\" if available.
If the ELEM has its `name' defined, the anchor is derived from it:
- If the `name' begins with \"code__\", \"tab__\", \"table__\",
\"img__\", \"fig__\" or \"figure__\", that prefix is removed as
this function adds its own appropriate prefix.
- Underscores and forward slashes in the `name' get replaced with
hyphens.
This conditioned `name' is then appended to the
code/table/figure-appropriate prefix, and returned.
Else, return nil.
The return value, if non-nil, is a string."
(let ((name (org-element-property :name elem))) ;Value of #+name
;; Reference cannot be created if #+name does not exist.
;; (message "[ox-bf ref DBG] name: %S" name)
(when name
(let* ((elem-type (org-element-type elem))
(prefix (or (org-blackfriday--get-ref-prefix elem-type)
(format "org-%s--" (symbol-name elem-type))))
(name1 (let* ((tmp name)
;; Remove commonly used code/table/figure
;; prefixes in the #+name itself.
(tmp (replace-regexp-in-string "\\`\\(code\\|tab\\|table\\|img\\|fig\\|figure\\|\\)__" "" tmp))
;; Prefer to use hyphens instead of
;; underscores in anchors. Also replace /
;; chars with hyphens.
(tmp (replace-regexp-in-string "[_/]" "-" tmp)))
tmp)))
(format "%s%s" prefix name1)))))
;;;; Translate
(defun org-blackfriday--translate (type info &optional str)
"Return translated string for element TYPE to the lang set by \"#+language\".
TYPE is the Org element type.
INFO is a plist holding contextual information.
If TYPE is `src-block' and if \"Listing\" translates to
\"Listing\", translate the string associated with `src-block'
from `org-blackfriday--org-element-string'.
Else if TYPE key exists in `org-blackfriday--org-element-string',
return the translated version of of the string associated in that
alist.
Else if TYPE key does not exist in
`org-blackfriday--org-element-string', or if TYPE is nil, but STR
is non-nil, return the translation of STR directly.
Else return an empty string."
(let ((elem-str (cdr (assoc type org-blackfriday--org-element-string))))
(if elem-str
(cond
((equal 'src-block type)
(let ((listing-tr (org-html--translate "Listing" info)))
(if (string= "Listing" listing-tr)
(org-html--translate elem-str info)
listing-tr)))
(t
(org-html--translate elem-str info)))
(if (stringp str)
(org-html--translate str info)
""))))
;;;; Convert string to a valid anchor name
(defun org-blackfriday--valid-html-anchor-name (str)
"Turn STR into a valid HTML anchor name.
Replaces invalid characters with \"-\". The returned anchor name
will also never begin or end with \"-\".
"
(or (and (stringp str)
(string-trim
(replace-regexp-in-string "[^a-zA-Z0-9_-.]" "-" str)
"-"))
""))
;; Return HTML span tags for link targets.
(defun org-blackfriday--link-target (attr &optional desc)
"Format a link target in HTML.
ATTR is a string representing the attributes of the target HTML tag.
DESC is either nil or the description string of the target."
(format "<span%s>%s</span>" (or attr "") (or desc "")))
(defun org-blackfriday--make-attribute-string (attributes)
"Return a list of attributes, as a string.
ATTRIBUTES is a plist where values are either strings or nil.
An attribute with a nil value will be omitted from the result.
An attribute with a \"t\" value will be added as a key-only or
boolean attribute.
This function is mostly a copy of
`org-html--make-attribute-string', except that it parses `:foo
\"t\"' as setting a boolean \"foo\" attribute."
(let (output)
(dolist (item attributes (mapconcat 'identity (nreverse output) " "))
(cond ((null item)
(pop output))
((symbolp item)
(push (substring (symbol-name item) 1) output))
((and (stringp item)
(string= item "t")) ;Example: (:control "t") -> "control"
;; Do nothing
)
(t
(let ((key (car output))
(value (replace-regexp-in-string
"\"" """ (org-html-encode-plain-text item))))
(setcar output (format "%s=\"%s\"" key value))))))))
;;;; Convert Org string to HTML
(defun org-blackfriday--org-contents-to-html (el)
"Convert Org contents in EL element to HTML."
(let* ((org-str (org-element-interpret-data (org-element-contents el)))
(html-str (org-export-string-as org-str 'html :body-only)))
html-str))
;;; Filter Functions
;; This function is adapted from `org-md-separate-elements'.
(defun org-blackfriday-separate-elements (tree _backend info)
"Fix blank lines between elements.
TREE is the parse tree being exported.
INFO is a plist used as a communication channel.
Enforce a blank line between elements. There are 3 exceptions
to this rule:
1. Preserve blank lines between sibling items in a plain list,
2. In an item, remove any blank line before the very first
paragraph and the next sub-list when the latter ends the
current item.
3. In an item, if a paragraph is immediately followed by an src
or example block, don't add a blank line after the paragraph.
4. In an item, if an src or example block doesn't have a caption
and is immediately followed by a paragraph, don't add a blank
line after that src or example block."
(org-element-map tree (remq 'item org-element-all-elements) ;Exception 1 in the doc-string
(lambda (el)
(let ((post-blank (cond
;; Exception 2 in the doc-string.
((and (eq (org-element-type el) 'paragraph)
(eq (org-element-type (org-element-property :parent el)) 'item)
(org-export-first-sibling-p el info)
(let ((next-el (org-export-get-next-element el info)))
(and (eq (org-element-type next-el) 'plain-list)
(not (org-export-get-next-element next-el info)))))
0)
;; Exception 3 in the doc-string (paragraph -> src-block).
((and (eq (org-element-type el) 'paragraph)
(eq (org-element-type (org-element-property :parent el)) 'item)
(let ((next-el (org-export-get-next-element el info)))
(memq (org-element-type next-el) '(src-block example-block))))
0)
;; Exception 4 in the doc-string (caption-less src-block -> paragraph).
;; If an src or example block has a caption,
;; that caption will be wrapped in an HTML
;; div block. In that case, we *do* need to
;; leave a blank line after the div block (CommonMark).
((and (memq (org-element-type el) '(src-block example-block))
(eq (org-element-type (org-element-property :parent el)) 'item)
(null (org-element-property :caption el)) ;<-- "no caption" check
(let ((next-el (org-export-get-next-element el info)))
(memq (org-element-type next-el) '(paragraph))))
0)
(t
1))))
(org-element-put-property el :post-blank post-blank)
;; (message "[org-blackfriday-separate-elements DBG] %S post-blank: %d"
;; (org-element-type el)
;; (org-element-property :post-blank el))
)))
;; Return updated tree.
tree)
;;; Transcode Functions
;;;; Center Block
(defun org-blackfriday-center-block (_center-block contents info)
"Center-align the text in CONTENTS using CSS.
INFO is a plist used as a communication channel."
(let* ((class "org-center")
(style (format ".%s { margin-left: auto; margin-right: auto; text-align: center; }" class)))
(format "<style>%s</style>\n\n<div class=\"%s\">%s\n\n%s\n</div>"
style class (org-blackfriday--extra-div-hack info) contents)))
;;;; Example Block
(defun org-blackfriday-example-block (example-block _contents info)
"Transcode an EXAMPLE-BLOCK element into Blackfriday Markdown format.
CONTENTS is nil. INFO is a plist holding contextual
information."
(let* ((parent-element (org-export-get-parent example-block))
(parent-type (car parent-element))
(backticks (make-string org-blackfriday--code-block-num-backticks ?`))
(example (or (plist-get info :md-code) ;if set in `org-hugo-example-block'
(org-export-format-code-default example-block info)))
(code-attr (if (plist-get info :md-code-attr) ;if set in `org-hugo-example-block'
(format " { %s }" (plist-get info :md-code-attr))
""))
ret)
;; (message "[ox-bf example-block DBG] parent type: %S" parent-type)
(setq ret (org-blackfriday--issue-239-workaround example parent-type))
(setq ret (format "%stext%s\n%s%s" backticks code-attr ret backticks))
(setq ret (org-blackfriday--div-wrap-maybe example-block ret info))
(when (equal 'quote-block parent-type)
;; If the current example block is inside a quote block, future
;; example/code blocks (especially the ones outside this quote
;; block) will require higher number of backticks. Workaround
;; for https://github.com/russross/blackfriday/issues/407.
(setq org-blackfriday--code-block-num-backticks
(1+ org-blackfriday--code-block-num-backticks)))
;; Reset the temp info in the `info' plist.
(plist-put info :md-code nil)
(plist-put info :md-code-attr nil)
ret))
;;;; Fixed Width
(defun org-blackfriday-fixed-width (fixed-width _contents info)
"Transcode a FIXED-WIDTH element into Blackfriday Markdown format.
CONTENTS is nil. INFO is a plist holding contextual
information."
(let* ((parent-element (org-export-get-parent fixed-width))
(parent-type (car parent-element))
(backticks (make-string org-blackfriday--code-block-num-backticks ?`)))
(prog1
(org-blackfriday--div-wrap-maybe
fixed-width
(format "%stext\n%s%s"
backticks
(let ((org-src-preserve-indentation t))
;; Preserve leading whitespace in the Org Babel Results
;; blocks.
(org-export-format-code-default fixed-width info))
backticks)
info)
(when (equal 'quote-block parent-type)
;; If the current example block is inside a quote block,
;; future example/code blocks (especially the ones outside
;; this quote block) will require higher number of backticks.
;; Workaround for
;; https://github.com/russross/blackfriday/issues/407.
(setq org-blackfriday--code-block-num-backticks
(1+ org-blackfriday--code-block-num-backticks))))))
;;;; Footnote Reference
(defun org-blackfriday-footnote-reference (footnote-reference _contents info)
"Transcode a FOOTNOTE-REFERENCE element into Blackfriday Markdown format.
CONTENTS is nil. INFO is a plist holding contextual information."
;; (message "footref: %s" footnote-reference)
(concat
;; Insert separator between two footnotes in a row.
(let ((prev (org-export-get-previous-element footnote-reference info)))
(and (eq (org-element-type prev) 'footnote-reference)
(plist-get info :html-footnote-separator)))
(format "[^fn:%d]" (org-export-get-footnote-number footnote-reference info))))
;;;; Inner Template
(defun org-blackfriday-inner-template (contents info)
"Return body of document after converting it to Markdown syntax.
CONTENTS is the transcoded contents string. INFO is a plist
holding export options."
(let* ((depth (plist-get info :with-toc))
(headings (and depth (org-export-collect-headlines info depth)))
(toc-tail (if headings "\n\n" ""))
(toc-string ""))
(when headings
(dolist (heading headings)
(setq toc-string (concat toc-string
(org-blackfriday-format-toc heading info)
"\n"))))
(concat toc-string toc-tail contents "\n"
(org-blackfriday-footnote-section info))))
;;;; Italic
(defun org-blackfriday-italic (_italic contents _info)
"Transcode ITALIC object into Markdown format.
CONTENTS is the text within italic markup. INFO is a plist used
as a communication channel."
;; (format "*%s*" contents)
;; While above also works in almost all cases, it fails in cases
;; like "*This is in italic, **and this is in bold-italics**, and
;; back to just italic.*".
;; As `org-md-bold' uses ** to mark bold text, switching to using
;; underscores only for italics.
(format "_%s_" contents))
;;;; Item (list item)
(defun org-blackfriday-item (item contents info)
"Transcode an ITEM element into Blackfriday Markdown format.
CONTENTS holds the contents of the item. INFO is a plist holding
contextual information.
Special note about descriptive lists:
Blackfriday style descriptive list syntax is used if that list is
not nested in another list.
Term1
: Description of term 1
If that list is nested, `ox-md' style descriptive list is
exported instead:
- **Term1:** Description of term 1."
(let ((parent-list (org-export-get-parent item)))
;; If this item is in an ordered list and if this or any other
;; item in this list is using a custom counter, export this list
;; item in HTML.
(if (org-blackfriday--export-ordered-list-as-html-p parent-list)
(org-html-format-list-item contents 'ordered nil info
(org-element-property :counter item))
(let* ((parent-list (org-export-get-parent item))
(parent-list-type (org-element-property :type parent-list))
(desc-list? (eq parent-list-type 'descriptive))
(grandparent (when desc-list?
(org-export-get-parent parent-list)))
(grandparent-type (when desc-list?
(org-element-type grandparent)))
(list-is-nested (eq 'item grandparent-type))
;; Export the descriptive list items like that in
;; ox-md.el if this descriptive list is nested in some
;; other list, because the Blackfriday style descriptive
;; list syntax seems to work only at top level (i.e. not
;; when that list is nested).
(ox-md-style-desc-list (and desc-list? list-is-nested))
(bf-style-desc-list (and desc-list? (not list-is-nested)))
(struct (org-element-property :structure item))
(item-num (car (last (org-list-get-item-number
(org-element-property :begin item)
struct
(org-list-prevs-alist struct)
(org-list-parents-alist struct)))))
(bullet (cond
((or (eq parent-list-type 'unordered)
ox-md-style-desc-list)
"-")
((eq parent-list-type 'ordered)
(format "%d. " item-num))
(t ;Non-nested descriptive list item
(when (> item-num 1)
"\n")))) ;Newline between each descriptive list item
(padding (when (and (not bf-style-desc-list)
(<= (length bullet) 3))
(make-string (- 4 (length bullet)) ? )))
(tag (when desc-list?
(let* ((tag1 (org-element-property :tag item))
(tag1-str (org-export-data tag1 info)))
(when tag1
(if ox-md-style-desc-list
(format "**%s:** " tag1-str)
(format "%s\n: " tag1-str)))))))
(concat bullet
padding
(pcase (org-element-property :checkbox item)
(`on "[X] ")
(`trans "[-] ")
(`off "[ ] "))
tag
(and contents
(org-trim (replace-regexp-in-string "^" " " contents))))))))
;;;; Latex Environment
(defun org-blackfriday--update-ltximg-path (html-str)
"Update the path in HTML-STR to latex exported images directory.
For example, this function converts
<img src=\"foo/bar/xyz.svg\" ..
to
<img src=\"/ltximg/xyz.svg\" ..
where \"ltximg/\" is the default value of