-
Notifications
You must be signed in to change notification settings - Fork 35
/
markdown-mode.el
9695 lines (8816 loc) · 397 KB
/
markdown-mode.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
;;; markdown-mode.el --- Major mode for Markdown-formatted text -*- lexical-binding: t; -*-
;; Copyright (C) 2007-2017 Jason R. Blevins and markdown-mode
;; contributors (see the commit log for details).
;; Author: Jason R. Blevins <[email protected]>
;; Maintainer: Jason R. Blevins <[email protected]>
;; Created: May 24, 2007
;; Version: 2.4-dev
;; Package-Requires: ((emacs "24.4") (cl-lib "0.5"))
;; Keywords: Markdown, GitHub Flavored Markdown, itex
;; URL: https://jblevins.org/projects/markdown-mode/
;; This file is not part of GNU Emacs.
;; This program 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.
;; This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; See the README.md file for details.
;;; Code:
(require 'easymenu)
(require 'outline)
(require 'thingatpt)
(require 'cl-lib)
(require 'url-parse)
(require 'button)
(require 'color)
(require 'rx)
(defvar jit-lock-start)
(defvar jit-lock-end)
(defvar flyspell-generic-check-word-predicate)
(declare-function eww-open-file "eww")
(declare-function url-path-and-query "url-parse")
;;; Constants =================================================================
(defconst markdown-mode-version "2.4-dev"
"Markdown mode version number.")
(defconst markdown-output-buffer-name "*markdown-output*"
"Name of temporary buffer for markdown command output.")
;;; Global Variables ==========================================================
(defvar markdown-reference-label-history nil
"History of used reference labels.")
(defvar markdown-live-preview-mode nil
"Sentinel variable for command `markdown-live-preview-mode'.")
(defvar markdown-gfm-language-history nil
"History list of languages used in the current buffer in GFM code blocks.")
;;; Customizable Variables ====================================================
(defvar markdown-mode-hook nil
"Hook run when entering Markdown mode.")
(defvar markdown-before-export-hook nil
"Hook run before running Markdown to export XHTML output.
The hook may modify the buffer, which will be restored to it's
original state after exporting is complete.")
(defvar markdown-after-export-hook nil
"Hook run after XHTML output has been saved.
Any changes to the output buffer made by this hook will be saved.")
(defgroup markdown nil
"Major mode for editing text files in Markdown format."
:prefix "markdown-"
:group 'text
:link '(url-link "https://jblevins.org/projects/markdown-mode/"))
(defcustom markdown-command "markdown"
"Command to run markdown."
:group 'markdown
:type '(choice (string :tag "Shell command") function))
(defcustom markdown-command-needs-filename nil
"Set to non-nil if `markdown-command' does not accept input from stdin.
Instead, it will be passed a filename as the final command line
option. As a result, you will only be able to run Markdown from
buffers which are visiting a file."
:group 'markdown
:type 'boolean)
(defcustom markdown-open-command nil
"Command used for opening Markdown files directly.
For example, a standalone Markdown previewer. This command will
be called with a single argument: the filename of the current
buffer. It can also be a function, which will be called without
arguments."
:group 'markdown
:type '(choice file function (const :tag "None" nil)))
(defcustom markdown-hr-strings
'("-------------------------------------------------------------------------------"
"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
"---------------------------------------"
"* * * * * * * * * * * * * * * * * * * *"
"---------"
"* * * * *")
"Strings to use when inserting horizontal rules.
The first string in the list will be the default when inserting a
horizontal rule. Strings should be listed in decreasing order of
prominence (as in headings from level one to six) for use with
promotion and demotion functions."
:group 'markdown
:type '(repeat string))
(defcustom markdown-bold-underscore nil
"Use two underscores when inserting bold text instead of two asterisks."
:group 'markdown
:type 'boolean)
(defcustom markdown-italic-underscore nil
"Use underscores when inserting italic text instead of asterisks."
:group 'markdown
:type 'boolean)
(defcustom markdown-marginalize-headers nil
"When non-nil, put opening atx header markup in a left margin.
This setting goes well with `markdown-asymmetric-header'. But
sadly it conflicts with `linum-mode' since they both use the
same margin."
:group 'markdown
:type 'boolean
:safe 'booleanp
:package-version '(markdown-mode . "2.4"))
(defcustom markdown-marginalize-headers-margin-width 6
"Character width of margin used for marginalized headers.
The default value is based on there being six heading levels
defined by Markdown and HTML. Increasing this produces extra
whitespace on the left. Decreasing it may be preferred when
fewer than six nested heading levels are used."
:group 'markdown
:type 'natnump
:safe 'natnump
:package-version '(markdown-mode . "2.4"))
(defcustom markdown-asymmetric-header nil
"Determines if atx header style will be asymmetric.
Set to a non-nil value to use asymmetric header styling, placing
header markup only at the beginning of the line. By default,
balanced markup will be inserted at the beginning and end of the
line around the header title."
:group 'markdown
:type 'boolean)
(defcustom markdown-indent-function 'markdown-indent-line
"Function to use to indent."
:group 'markdown
:type 'function)
(defcustom markdown-indent-on-enter t
"Determines indentation behavior when pressing \\[newline].
Possible settings are nil, t, and 'indent-and-new-item.
When non-nil, pressing \\[newline] will call `newline-and-indent'
to indent the following line according to the context using
`markdown-indent-function'. In this case, note that
\\[electric-newline-and-maybe-indent] can still be used to insert
a newline without indentation.
When set to 'indent-and-new-item and the point is in a list item
when \\[newline] is pressed, the list will be continued on the next
line, where a new item will be inserted.
When set to nil, simply call `newline' as usual. In this case,
you can still indent lines using \\[markdown-cycle] and continue
lists with \\[markdown-insert-list-item].
Note that this assumes the variable `electric-indent-mode' is
non-nil (enabled). When it is *disabled*, the behavior of
\\[newline] and `\\[electric-newline-and-maybe-indent]' are
reversed."
:group 'markdown
:type '(choice (const :tag "Don't automatically indent" nil)
(const :tag "Automatically indent" t)
(const :tag "Automatically indent and insert new list items" indent-and-new-item)))
(defcustom markdown-enable-wiki-links nil
"Syntax highlighting for wiki links.
Set this to a non-nil value to turn on wiki link support by default.
Support can be toggled later using the `markdown-toggle-wiki-links'
function or \\[markdown-toggle-wiki-links]."
:group 'markdown
:type 'boolean
:safe 'booleanp
:package-version '(markdown-mode . "2.2"))
(defcustom markdown-wiki-link-alias-first t
"When non-nil, treat aliased wiki links like [[alias text|PageName]].
Otherwise, they will be treated as [[PageName|alias text]]."
:group 'markdown
:type 'boolean
:safe 'booleanp)
(defcustom markdown-wiki-link-search-subdirectories nil
"When non-nil, search for wiki link targets in subdirectories.
This is the default search behavior for GitHub and is
automatically set to t in `gfm-mode'."
:group 'markdown
:type 'boolean
:safe 'booleanp
:package-version '(markdown-mode . "2.2"))
(defcustom markdown-wiki-link-search-parent-directories nil
"When non-nil, search for wiki link targets in parent directories.
This is the default search behavior of Ikiwiki."
:group 'markdown
:type 'boolean
:safe 'booleanp
:package-version '(markdown-mode . "2.2"))
(defcustom markdown-wiki-link-fontify-missing nil
"When non-nil, change wiki link face according to existence of target files.
This is expensive because it requires checking for the file each time the buffer
changes or the user switches windows. It is disabled by default because it may
cause lag when typing on slower machines."
:group 'markdown
:type 'boolean
:safe 'booleanp
:package-version '(markdown-mode . "2.2"))
(defcustom markdown-uri-types
'("acap" "cid" "data" "dav" "fax" "file" "ftp"
"gopher" "http" "https" "imap" "ldap" "mailto"
"mid" "message" "modem" "news" "nfs" "nntp"
"pop" "prospero" "rtsp" "service" "sip" "tel"
"telnet" "tip" "urn" "vemmi" "wais")
"Link types for syntax highlighting of URIs."
:group 'markdown
:type '(repeat (string :tag "URI scheme")))
(defcustom markdown-url-compose-char
'(?∞ ?… ?⋯ ?# ?★ ?⚓)
"Placeholder character for hidden URLs.
This may be a single character or a list of characters. In case
of a list, the first one that satisfies `char-displayable-p' will
be used."
:type '(choice
(character :tag "Single URL replacement character")
(repeat :tag "List of possible URL replacement characters"
character))
:package-version '(markdown-mode . "2.3"))
(defcustom markdown-blockquote-display-char
'("▌" "┃" ">")
"String to display when hiding blockquote markup.
This may be a single string or a list of string. In case of a
list, the first one that satisfies `char-displayable-p' will be
used."
:type 'string
:type '(choice
(string :tag "Single blockquote display string")
(repeat :tag "List of possible blockquote display strings" string))
:package-version '(markdown-mode . "2.3"))
(defcustom markdown-hr-display-char
'(?─ ?━ ?-)
"Character for hiding horizontal rule markup.
This may be a single character or a list of characters. In case
of a list, the first one that satisfies `char-displayable-p' will
be used."
:group 'markdown
:type '(choice
(character :tag "Single HR display character")
(repeat :tag "List of possible HR display characters" character))
:package-version '(markdown-mode . "2.3"))
(defcustom markdown-definition-display-char
'(?⁘ ?⁙ ?≡ ?⌑ ?◊ ?:)
"Character for replacing definition list markup.
This may be a single character or a list of characters. In case
of a list, the first one that satisfies `char-displayable-p' will
be used."
:type '(choice
(character :tag "Single definition list character")
(repeat :tag "List of possible definition list characters" character))
:package-version '(markdown-mode . "2.3"))
(defcustom markdown-enable-math nil
"Syntax highlighting for inline LaTeX and itex expressions.
Set this to a non-nil value to turn on math support by default.
Math support can be enabled, disabled, or toggled later using
`markdown-toggle-math' or \\[markdown-toggle-math]."
:group 'markdown
:type 'boolean
:safe 'booleanp)
(make-variable-buffer-local 'markdown-enable-math)
(defcustom markdown-enable-html t
"Enable font-lock support for HTML tags and attributes."
:group 'markdown
:type 'boolean
:safe 'booleanp
:package-version '(markdown-mode . "2.4"))
(defcustom markdown-css-paths nil
"URL of CSS file to link to in the output XHTML."
:group 'markdown
:type '(repeat (string :tag "CSS File Path")))
(defcustom markdown-content-type "text/html"
"Content type string for the http-equiv header in XHTML output.
When set to an empty string, this attribute is omitted. Defaults to
`text/html'."
:group 'markdown
:type 'string)
(defcustom markdown-coding-system nil
"Character set string for the http-equiv header in XHTML output.
Defaults to `buffer-file-coding-system' (and falling back to
`utf-8' when not available). Common settings are `iso-8859-1'
and `iso-latin-1'. Use `list-coding-systems' for more choices."
:group 'markdown
:type 'coding-system)
(defcustom markdown-export-kill-buffer t
"Kill output buffer after HTML export.
When non-nil, kill the HTML output buffer after
exporting with `markdown-export'."
:group 'markdown
:type 'boolean
:safe 'booleanp
:package-version '(markdown-mode . "2.4"))
(defcustom markdown-xhtml-header-content ""
"Additional content to include in the XHTML <head> block."
:group 'markdown
:type 'string)
(defcustom markdown-xhtml-body-preamble ""
"Content to include in the XHTML <body> block, before the output."
:group 'markdown
:type 'string
:safe 'stringp
:package-version '(markdown-mode . "2.4"))
(defcustom markdown-xhtml-body-epilogue ""
"Content to include in the XHTML <body> block, after the output."
:group 'markdown
:type 'string
:safe 'stringp
:package-version '(markdown-mode . "2.4"))
(defcustom markdown-xhtml-standalone-regexp
"^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
"Regexp indicating whether `markdown-command' output is standalone XHTML."
:group 'markdown
:type 'regexp)
(defcustom markdown-link-space-sub-char "_"
"Character to use instead of spaces when mapping wiki links to filenames."
:group 'markdown
:type 'string)
(defcustom markdown-reference-location 'header
"Position where new reference definitions are inserted in the document."
:group 'markdown
:type '(choice (const :tag "At the end of the document" end)
(const :tag "Immediately after the current block" immediately)
(const :tag "At the end of the subtree" subtree)
(const :tag "Before next header" header)))
(defcustom markdown-footnote-location 'end
"Position where new footnotes are inserted in the document."
:group 'markdown
:type '(choice (const :tag "At the end of the document" end)
(const :tag "Immediately after the current block" immediately)
(const :tag "At the end of the subtree" subtree)
(const :tag "Before next header" header)))
(defcustom markdown-footnote-display '((raise 0.2) (height 0.8))
"Display specification for footnote markers and inline footnotes.
By default, footnote text is reduced in size and raised. Set to
nil to disable this."
:group 'markdown
:type '(choice (sexp :tag "Display specification")
(const :tag "Don't set display property" nil))
:package-version '(markdown-mode . "2.4"))
(defcustom markdown-sub-superscript-display
'(((raise -0.3) (height 0.7)) . ((raise 0.3) (height 0.7)))
"Display specification for subscript and superscripts.
The car is used for subscript, the cdr is used for superscripts."
:group 'markdown
:type '(cons (choice (sexp :tag "Subscript form")
(const :tag "No lowering" nil))
(choice (sexp :tag "Superscript form")
(const :tag "No raising" nil)))
:package-version '(markdown-mode . "2.4"))
(defcustom markdown-unordered-list-item-prefix " * "
"String inserted before unordered list items."
:group 'markdown
:type 'string)
(defcustom markdown-nested-imenu-heading-index t
"Use nested or flat imenu heading index.
A nested index may provide more natural browsing from the menu,
but a flat list may allow for faster keyboard navigation via tab
completion."
:group 'markdown
:type 'boolean
:safe 'booleanp
:package-version '(markdown-mode . "2.2"))
(defcustom markdown-add-footnotes-to-imenu t
"Add footnotes to end of imenu heading index."
:group 'markdown
:type 'boolean
:safe 'booleanp
:package-version '(markdown-mode . "2.4"))
(defcustom markdown-make-gfm-checkboxes-buttons t
"When non-nil, make GFM checkboxes into buttons."
:group 'markdown
:type 'boolean)
(defcustom markdown-use-pandoc-style-yaml-metadata nil
"When non-nil, allow YAML metadata anywhere in the document."
:group 'markdown
:type 'boolean)
(defcustom markdown-split-window-direction 'any
"Preference for splitting windows for static and live preview.
The default value is 'any, which instructs Emacs to use
`split-window-sensibly' to automatically choose how to split
windows based on the values of `split-width-threshold' and
`split-height-threshold' and the available windows. To force
vertically split (left and right) windows, set this to 'vertical
or 'right. To force horizontally split (top and bottom) windows,
set this to 'horizontal or 'below."
:group 'markdown
:type '(choice (const :tag "Automatic" any)
(const :tag "Right (vertical)" right)
(const :tag "Below (horizontal)" below))
:package-version '(markdown-mode . "2.2"))
(defcustom markdown-live-preview-window-function
'markdown-live-preview-window-eww
"Function to display preview of Markdown output within Emacs.
Function must update the buffer containing the preview and return
the buffer."
:group 'markdown
:type 'function)
(defcustom markdown-live-preview-delete-export 'delete-on-destroy
"Delete exported HTML file when using `markdown-live-preview-export'.
If set to 'delete-on-export, delete on every export. When set to
'delete-on-destroy delete when quitting from command
`markdown-live-preview-mode'. Never delete if set to nil."
:group 'markdown
:type '(choice
(const :tag "Delete on every export" delete-on-export)
(const :tag "Delete when quitting live preview" delete-on-destroy)
(const :tag "Never delete" nil)))
(defcustom markdown-list-indent-width 4
"Depth of indentation for markdown lists.
Used in `markdown-demote-list-item' and
`markdown-promote-list-item'."
:group 'markdown
:type 'integer)
(defcustom markdown-enable-prefix-prompts t
"Display prompts for certain prefix commands.
Set to nil to disable these prompts."
:group 'markdown
:type 'boolean
:safe 'booleanp
:package-version '(markdown-mode . "2.3"))
(defcustom markdown-gfm-additional-languages nil
"Extra languages made available when inserting GFM code blocks.
Language strings must have be trimmed of whitespace and not
contain any curly braces. They may be of arbitrary
capitalization, though."
:group 'markdown
:type '(repeat (string :validate markdown-validate-language-string)))
(defcustom markdown-gfm-use-electric-backquote t
"Use `markdown-electric-backquote' when backquote is hit three times."
:group 'markdown
:type 'boolean)
(defcustom markdown-gfm-downcase-languages t
"If non-nil, downcase suggested languages.
This applies to insertions done with
`markdown-electric-backquote'."
:group 'markdown
:type 'boolean)
(defcustom markdown-edit-code-block-default-mode 'normal-mode
"Default mode to use for editing code blocks.
This mode is used when automatic detection fails, such as for GFM
code blocks with no language specified."
:group 'markdown
:type '(choice function (const :tag "None" nil))
:package-version '(markdown-mode . "2.4"))
(defcustom markdown-gfm-uppercase-checkbox nil
"If non-nil, use [X] for completed checkboxes, [x] otherwise."
:group 'markdown
:type 'boolean
:safe 'booleanp)
(defcustom markdown-hide-urls nil
"Hide URLs of inline links and reference tags of reference links.
Such URLs will be replaced by a single customizable
character, defined by `markdown-url-compose-char', but are still part
of the buffer. Links can be edited interactively with
\\[markdown-insert-link] or, for example, by deleting the final
parenthesis to remove the invisibility property. You can also
hover your mouse pointer over the link text to see the URL.
Set this to a non-nil value to turn this feature on by default.
You can interactively set the value of this variable by calling
`markdown-toggle-url-hiding', pressing \\[markdown-toggle-url-hiding],
or from the menu Markdown > Links & Images menu."
:group 'markdown
:type 'boolean
:safe 'booleanp
:package-version '(markdown-mode . "2.3"))
(make-variable-buffer-local 'markdown-hide-urls)
(defcustom markdown-translate-filename-function #'identity
"Function to use to translate filenames when following links.
\\<markdown-mode-map>\\[markdown-follow-thing-at-point] and \\[markdown-follow-link-at-point]
call this function with the filename as only argument whenever
they encounter a filename (instead of a URL) to be visited and
use its return value instead of the filename in the link. For
example, if absolute filenames are actually relative to a server
root directory, you can set
`markdown-translate-filename-function' to a function that
prepends the root directory to the given filename."
:group 'markdown
:type 'function
:risky t
:package-version '(markdown-mode . "2.4"))
(defcustom markdown-max-image-size nil
"Maximum width and height for displayed inline images.
This variable may be nil or a cons cell (MAX-WIDTH . MAX-HEIGHT).
When nil, use the actual size. Otherwise, use ImageMagick to
resize larger images to be of the given maximum dimensions. This
requires Emacs to be built with ImageMagick support."
:group 'markdown
:package-version '(markdown-mode . "2.4")
:type '(choice
(const :tag "Use actual image width" nil)
(cons (choice (sexp :tag "Maximum width in pixels")
(const :tag "No maximum width" nil))
(choice (sexp :tag "Maximum height in pixels")
(const :tag "No maximum height" nil)))))
;;; Markdown-Specific `rx' Macro ==============================================
;; Based on python-rx from python.el.
(eval-and-compile
(defconst markdown-rx-constituents
`((newline . ,(rx "\n"))
(indent . ,(rx (or (repeat 4 " ") "\t")))
(block-end . ,(rx (and (or (one-or-more (zero-or-more blank) "\n") line-end))))
(numeral . ,(rx (and (one-or-more (any "0-9#")) ".")))
(bullet . ,(rx (any "*+:-")))
(list-marker . ,(rx (or (and (one-or-more (any "0-9#")) ".")
(any "*+:-"))))
(checkbox . ,(rx "[" (any " xX") "]")))
"Markdown-specific sexps for `markdown-rx'")
(defun markdown-rx-to-string (form &optional no-group)
"Markdown mode specialized `rx-to-string' function.
This variant supports named Markdown expressions in FORM.
NO-GROUP non-nil means don't put shy groups around the result."
(let ((rx-constituents (append markdown-rx-constituents rx-constituents)))
(rx-to-string form no-group)))
(defmacro markdown-rx (&rest regexps)
"Markdown mode specialized rx macro.
This variant of `rx' supports common Markdown named REGEXPS."
(cond ((null regexps)
(error "No regexp"))
((cdr regexps)
(markdown-rx-to-string `(and ,@regexps) t))
(t
(markdown-rx-to-string (car regexps) t)))))
;;; Regular Expressions =======================================================
(defconst markdown-regex-comment-start
"<!--"
"Regular expression matches HTML comment opening.")
(defconst markdown-regex-comment-end
"--[ \t]*>"
"Regular expression matches HTML comment closing.")
(defconst markdown-regex-link-inline
"\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)\\((\\)\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?\\()\\)"
"Regular expression for a [text](file) or an image link ![text](file).
Group 1 matches the leading exclamation point (optional).
Group 2 matches the opening square bracket.
Group 3 matches the text inside the square brackets.
Group 4 matches the closing square bracket.
Group 5 matches the opening parenthesis.
Group 6 matches the URL.
Group 7 matches the title (optional).
Group 8 matches the closing parenthesis.")
(defconst markdown-regex-link-reference
"\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)[ ]?\\(\\[\\)\\([^]]*?\\)\\(\\]\\)"
"Regular expression for a reference link [text][id].
Group 1 matches the leading exclamation point (optional).
Group 2 matches the opening square bracket for the link text.
Group 3 matches the text inside the square brackets.
Group 4 matches the closing square bracket for the link text.
Group 5 matches the opening square bracket for the reference label.
Group 6 matches the reference label.
Group 7 matches the closing square bracket for the reference label.")
(defconst markdown-regex-reference-definition
"^ \\{0,3\\}\\(\\[\\)\\([^]\n]+?\\)\\(\\]\\)\\(:\\)\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
"Regular expression for a reference definition.
Group 1 matches the opening square bracket.
Group 2 matches the reference label.
Group 3 matches the closing square bracket.
Group 4 matches the colon.
Group 5 matches the URL.
Group 6 matches the title attribute (optional).")
(defconst markdown-regex-footnote
"\\(\\[\\^\\)\\(.+?\\)\\(\\]\\)"
"Regular expression for a footnote marker [^fn].
Group 1 matches the opening square bracket and carat.
Group 2 matches only the label, without the surrounding markup.
Group 3 matches the closing square bracket.")
(defconst markdown-regex-header
"^\\(?:\\([^\r\n\t -].*\\)\n\\(?:\\(=+\\)\\|\\(-+\\)\\)\\|\\(#+[ \t]+\\)\\(.*?\\)\\([ \t]*#*\\)\\)$"
"Regexp identifying Markdown headings.
Group 1 matches the text of a setext heading.
Group 2 matches the underline of a level-1 setext heading.
Group 3 matches the underline of a level-2 setext heading.
Group 4 matches the opening hash marks of an atx heading and whitespace.
Group 5 matches the text, without surrounding whitespace, of an atx heading.
Group 6 matches the closing whitespace and hash marks of an atx heading.")
(defconst markdown-regex-header-setext
"^\\([^\r\n\t -].*\\)\n\\(=+\\|-+\\)$"
"Regular expression for generic setext-style (underline) headers.")
(defconst markdown-regex-header-atx
"^\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
"Regular expression for generic atx-style (hash mark) headers.")
(defconst markdown-regex-hr
(rx line-start
(group (or (and (repeat 3 (and "*" (? " "))) (* (any "* ")))
(and (repeat 3 (and "-" (? " "))) (* (any "- ")))
(and (repeat 3 (and "_" (? " "))) (* (any "_ ")))))
line-end)
"Regular expression for matching Markdown horizontal rules.")
(defconst markdown-regex-code
"\\(?:\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(?:.\\|\n[^\n]\\)*?[^`]\\)\\(\\2\\)\\)\\(?:[^`]\\|\\'\\)"
"Regular expression for matching inline code fragments.
Group 1 matches the entire code fragment including the backquotes.
Group 2 matches the opening backquotes.
Group 3 matches the code fragment itself, without backquotes.
Group 4 matches the closing backquotes.
The leading, unnumbered group ensures that the leading backquote
character is not escaped.
The last group, also unnumbered, requires that the character
following the code fragment is not a backquote.
Note that \\(?:.\\|\n[^\n]\\) matches any character, including newlines,
but not two newlines in a row.")
(defconst markdown-regex-kbd
"\\(<kbd>\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(</kbd>\\)"
"Regular expression for matching <kbd> tags.
Groups 1 and 3 match the opening and closing tags.
Group 2 matches the key sequence.")
(defconst markdown-regex-gfm-code-block-open
"^[[:blank:]]*\\(```\\)\\([[:blank:]]*{?[[:blank:]]*\\)\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$"
"Regular expression matching opening of GFM code blocks.
Group 1 matches the opening three backquotes and any following whitespace.
Group 2 matches the opening brace (optional) and surrounding whitespace.
Group 3 matches the language identifier (optional).
Group 4 matches the info string (optional).
Group 5 matches the closing brace (optional), whitespace, and newline.
Groups need to agree with `markdown-regex-tilde-fence-begin'.")
(defconst markdown-regex-gfm-code-block-close
"^[[:blank:]]*\\(```\\)\\(\\s *?\\)$"
"Regular expression matching closing of GFM code blocks.
Group 1 matches the closing three backquotes.
Group 2 matches any whitespace and the final newline.")
(defconst markdown-regex-pre
"^\\( \\|\t\\).*$"
"Regular expression for matching preformatted text sections.")
(defconst markdown-regex-list
(markdown-rx line-start
;; 1. Leading whitespace
(group (* blank))
;; 2. List marker: a numeral, bullet, or colon
(group list-marker)
;; 3. Trailing whitespace
(group (+ blank))
;; 4. Optional checkbox for GFM task list items
(opt (group (and checkbox (* blank)))))
"Regular expression for matching list items.")
(defconst markdown-regex-bold
"\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
"Regular expression for matching bold text.
Group 1 matches the character before the opening asterisk or
underscore, if any, ensuring that it is not a backslash escape.
Group 2 matches the entire expression, including delimiters.
Groups 3 and 5 matches the opening and closing delimiters.
Group 4 matches the text inside the delimiters.")
(defconst markdown-regex-italic
"\\(?:^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t*]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
"Regular expression for matching italic text.
The leading unnumbered matches the character before the opening
asterisk or underscore, if any, ensuring that it is not a
backslash escape.
Group 1 matches the entire expression, including delimiters.
Groups 2 and 4 matches the opening and closing delimiters.
Group 3 matches the text inside the delimiters.")
(defconst markdown-regex-strike-through
"\\(^\\|[^\\]\\)\\(\\(~~\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(~~\\)\\)"
"Regular expression for matching strike-through text.
Group 1 matches the character before the opening tilde, if any,
ensuring that it is not a backslash escape.
Group 2 matches the entire expression, including delimiters.
Groups 3 and 5 matches the opening and closing delimiters.
Group 4 matches the text inside the delimiters.")
(defconst markdown-regex-gfm-italic
"\\(?:^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\2\\|[^ ]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
"Regular expression for matching italic text in GitHub Flavored Markdown.
Underscores in words are not treated as special.
Group 1 matches the entire expression, including delimiters.
Groups 2 and 4 matches the opening and closing delimiters.
Group 3 matches the text inside the delimiters.")
(defconst markdown-regex-blockquote
"^[ \t]*\\([A-Z]?>\\)\\([ \t]*\\)\\(.*\\)$"
"Regular expression for matching blockquote lines.
Also accounts for a potential capital letter preceding the angle
bracket, for use with Leanpub blocks (asides, warnings, info
blocks, etc.).
Group 1 matches the leading angle bracket.
Group 2 matches the separating whitespace.
Group 3 matches the text.")
(defconst markdown-regex-line-break
"[^ \n\t][ \t]*\\( \\)$"
"Regular expression for matching line breaks.")
(defconst markdown-regex-wiki-link
"\\(?:^\\|[^\\]\\)\\(\\(\\[\\[\\)\\([^]|]+\\)\\(?:\\(|\\)\\([^]]+\\)\\)?\\(\\]\\]\\)\\)"
"Regular expression for matching wiki links.
This matches typical bracketed [[WikiLinks]] as well as 'aliased'
wiki links of the form [[PageName|link text]].
The meanings of the first and second components depend
on the value of `markdown-wiki-link-alias-first'.
Group 1 matches the entire link.
Group 2 matches the opening square brackets.
Group 3 matches the first component of the wiki link.
Group 4 matches the pipe separator, when present.
Group 5 matches the second component of the wiki link, when present.
Group 6 matches the closing square brackets.")
(defconst markdown-regex-uri
(concat "\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+\\)")
"Regular expression for matching inline URIs.")
(defconst markdown-regex-angle-uri
(concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
"Regular expression for matching inline URIs in angle brackets.")
(defconst markdown-regex-email
"<\\(\\(?:\\sw\\|\\s_\\|\\s.\\)+@\\(?:\\sw\\|\\s_\\|\\s.\\)+\\)>"
"Regular expression for matching inline email addresses.")
(defsubst markdown-make-regex-link-generic ()
"Make regular expression for matching any recognized link."
(concat "\\(?:" markdown-regex-link-inline
(when markdown-enable-wiki-links
(concat "\\|" markdown-regex-wiki-link))
"\\|" markdown-regex-link-reference
"\\|" markdown-regex-angle-uri "\\)"))
(defconst markdown-regex-gfm-checkbox
" \\(\\[[ xX]\\]\\) "
"Regular expression for matching GFM checkboxes.
Group 1 matches the text to become a button.")
(defconst markdown-regex-blank-line
"^[[:blank:]]*$"
"Regular expression that matches a blank line.")
(defconst markdown-regex-block-separator
"\n[\n\t\f ]*\n"
"Regular expression for matching block boundaries.")
(defconst markdown-regex-block-separator-noindent
(concat "\\(\\`\\|\\(" markdown-regex-block-separator "\\)[^\n\t\f ]\\)")
"Regexp for block separators before lines with no indentation.")
(defconst markdown-regex-math-inline-single
"\\(?:^\\|[^\\]\\)\\(\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\)"
"Regular expression for itex $..$ math mode expressions.
Groups 1 and 3 match the opening and closing dollar signs.
Group 2 matches the mathematical expression contained within.")
(defconst markdown-regex-math-inline-double
"\\(?:^\\|[^\\]\\)\\(\\$\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\$\\)"
"Regular expression for itex $$..$$ math mode expressions.
Groups 1 and 3 match opening and closing dollar signs.
Group 2 matches the mathematical expression contained within.")
(defconst markdown-regex-math-display
(rx line-start (* blank)
(group (group (repeat 1 2 "\\")) "[")
(group (*? anything))
(group (backref 2) "]")
line-end)
"Regular expression for \[..\] or \\[..\\] display math.
Groups 1 and 4 match the opening and closing markup.
Group 3 matches the mathematical expression contained within.
Group 2 matches the opening slashes, and is used internally to
match the closing slashes.")
(defsubst markdown-make-tilde-fence-regex (num-tildes &optional end-of-line)
"Return regexp matching a tilde code fence at least NUM-TILDES long.
END-OF-LINE is the regexp construct to indicate end of line; $ if
missing."
(format "%s%d%s%s" "^[[:blank:]]*\\([~]\\{" num-tildes ",\\}\\)"
(or end-of-line "$")))
(defconst markdown-regex-tilde-fence-begin
(markdown-make-tilde-fence-regex
3 "\\([[:blank:]]*{?\\)[[:blank:]]*\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$")
"Regular expression for matching tilde-fenced code blocks.
Group 1 matches the opening tildes.
Group 2 matches (optional) opening brace and surrounding whitespace.
Group 3 matches the language identifier (optional).
Group 4 matches the info string (optional).
Group 5 matches the closing brace (optional) and any surrounding whitespace.
Groups need to agree with `markdown-regex-gfm-code-block-open'.")
(defconst markdown-regex-declarative-metadata
"^\\([[:alpha:]][[:alpha:] _-]*?\\)\\([:=][ \t]*\\)\\(.*\\)$"
"Regular expression for matching declarative metadata statements.
This matches MultiMarkdown metadata as well as YAML and TOML
assignments such as the following:
variable: value
or
variable = value")
(defconst markdown-regex-pandoc-metadata
"^\\(%\\)\\([ \t]*\\)\\(.*\\(?:\n[ \t]+.*\\)*\\)"
"Regular expression for matching Pandoc metadata.")
(defconst markdown-regex-yaml-metadata-border
"\\(-\\{3\\}\\)$"
"Regular expression for matching YAML metadata.")
(defconst markdown-regex-yaml-pandoc-metadata-end-border
"^\\(\\.\\{3\\}\\|\\-\\{3\\}\\)$"
"Regular expression for matching YAML metadata end borders.")
(defsubst markdown-get-yaml-metadata-start-border ()
"Return YAML metadata start border depending upon whether Pandoc is used."
(concat
(if markdown-use-pandoc-style-yaml-metadata "^" "\\`")
markdown-regex-yaml-metadata-border))
(defsubst markdown-get-yaml-metadata-end-border (_)
"Return YAML metadata end border depending upon whether Pandoc is used."
(if markdown-use-pandoc-style-yaml-metadata
markdown-regex-yaml-pandoc-metadata-end-border
markdown-regex-yaml-metadata-border))
(defconst markdown-regex-inline-attributes
"[ \t]*\\({:?\\)[ \t]*\\(\\(#[[:alpha:]_.:-]+\\|\\.[[:alpha:]_.:-]+\\|\\w+=['\"]?[^\n'\"]*['\"]?\\),?[ \t]*\\)+\\(}\\)[ \t]*$"
"Regular expression for matching inline identifiers or attribute lists.
Compatible with Pandoc, Python Markdown, PHP Markdown Extra, and Leanpub.")
(defconst markdown-regex-leanpub-sections
(concat
"^\\({\\)\\("
(regexp-opt '("frontmatter" "mainmatter" "backmatter" "appendix" "pagebreak"))
"\\)\\(}\\)[ \t]*\n")
"Regular expression for Leanpub section markers and related syntax.")
(defconst markdown-regex-sub-superscript
"\\(?:^\\|[^\\~^]\\)\\(\\([~^]\\)\\([[:alnum:]]+\\)\\(\\2\\)\\)"
"The regular expression matching a sub- or superscript.
The leading un-numbered group matches the character before the
opening tilde or carat, if any, ensuring that it is not a
backslash escape, carat, or tilde.
Group 1 matches the entire expression, including markup.
Group 2 matches the opening markup--a tilde or carat.
Group 3 matches the text inside the delimiters.
Group 4 matches the closing markup--a tilde or carat.")
(defconst markdown-regex-include
"^\\(<<\\)\\(?:\\(\\[\\)\\(.*\\)\\(\\]\\)\\)?\\(?:\\((\\)\\(.*\\)\\()\\)\\)?\\(?:\\({\\)\\(.*\\)\\(}\\)\\)?$"
"Regular expression matching common forms of include syntax.
Marked 2, Leanpub, and other processors support some of these forms:
<<[sections/section1.md]
<<(folder/filename)
<<[Code title](folder/filename)
<<{folder/raw_file.html}
Group 1 matches the opening two angle brackets.
Groups 2-4 match the opening square bracket, the text inside,
and the closing square bracket, respectively.
Groups 5-7 match the opening parenthesis, the text inside, and
the closing parenthesis.
Groups 8-10 match the opening brace, the text inside, and the brace.")
(defconst markdown-regex-pandoc-inline-footnote
"\\(\\^\\)\\(\\[\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(\\]\\)"
"Regular expression for Pandoc inline footnote^[footnote text].
Group 1 matches the opening caret.
Group 2 matches the opening square bracket.
Group 3 matches the footnote text, without the surrounding markup.
Group 4 matches the closing square bracket.")
(defconst markdown-regex-html-attr
"\\(\\<[[:alpha:]:-]+\\>\\)\\(\\s-*\\(=\\)\\s-*\\(\".*?\"\\|'.*?'\\|[^'\">[:space:]]+\\)?\\)?"
"Regular expression for matching HTML attributes and values.
Group 1 matches the attribute name.
Group 2 matches the following whitespace, equals sign, and value, if any.
Group 3 matches the equals sign, if any.
Group 4 matches single-, double-, or un-quoted attribute values.")
(defconst markdown-regex-html-tag
(concat "\\(</?\\)\\(\\w+\\)\\(\\(\\s-+" markdown-regex-html-attr
"\\)+\\s-*\\|\\s-*\\)\\(/?>\\)")
"Regular expression for matching HTML tags.
Groups 1 and 9 match the beginning and ending angle brackets and slashes.
Group 2 matches the tag name.
Group 3 matches all attributes and whitespace following the tag name.")
(defconst markdown-regex-html-entity
"\\(&#?[[:alnum:]]+;\\)"
"Regular expression for matching HTML entities.")
;;; Syntax ====================================================================
(defvar markdown--syntax-properties
(list 'markdown-tilde-fence-begin nil
'markdown-tilde-fence-end nil
'markdown-fenced-code nil
'markdown-yaml-metadata-begin nil
'markdown-yaml-metadata-end nil