1 ;;; markdown-mode.el --- Major mode for Markdown-formatted text -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2007-2022 Jason R. Blevins and markdown-mode
4 ;; contributors (see the commit log for details).
6 ;; Author: Jason R. Blevins <jblevins@xbeta.org>
7 ;; Maintainer: Jason R. Blevins <jblevins@xbeta.org>
8 ;; Created: May 24, 2007
10 ;; Package-Requires: ((emacs "26.1"))
11 ;; Keywords: Markdown, GitHub Flavored Markdown, itex
12 ;; URL: https://jblevins.org/projects/markdown-mode/
14 ;; This file is not part of GNU Emacs.
16 ;; This program is free software; you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
21 ;; This program is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
31 ;; See the README.md file for details.
46 (defvar jit-lock-start
)
48 (defvar flyspell-generic-check-word-predicate
)
49 (defvar electric-pair-pairs
)
50 (defvar sh-ancestor-alist
)
52 (declare-function project-roots
"project")
53 (declare-function sh-set-shell
"sh-script")
56 ;;; Constants =================================================================
58 (defconst markdown-mode-version
"2.6-dev"
59 "Markdown mode version number.")
61 (defconst markdown-output-buffer-name
"*markdown-output*"
62 "Name of temporary buffer for markdown command output.")
65 ;;; Global Variables ==========================================================
67 (defvar markdown-reference-label-history nil
68 "History of used reference labels.")
70 (defvar markdown-live-preview-mode nil
71 "Sentinel variable for command `markdown-live-preview-mode'.")
73 (defvar markdown-gfm-language-history nil
74 "History list of languages used in the current buffer in GFM code blocks.")
77 ;;; Customizable Variables ====================================================
79 (defvar markdown-mode-hook nil
80 "Hook run when entering Markdown mode.")
82 (defvar markdown-before-export-hook nil
83 "Hook run before running Markdown to export XHTML output.
84 The hook may modify the buffer, which will be restored to it's
85 original state after exporting is complete.")
87 (defvar markdown-after-export-hook nil
88 "Hook run after XHTML output has been saved.
89 Any changes to the output buffer made by this hook will be saved.")
91 (defgroup markdown nil
92 "Major mode for editing text files in Markdown format."
95 :link
'(url-link "https://jblevins.org/projects/markdown-mode/"))
97 (defcustom markdown-command
(let ((command (cl-loop for cmd in
'("markdown" "pandoc" "markdown_py")
98 when
(executable-find cmd
)
99 return
(file-name-nondirectory it
))))
100 (or command
"markdown"))
101 "Command to run markdown."
103 :type
'(choice (string :tag
"Shell command") (repeat (string)) function
))
105 (defcustom markdown-command-needs-filename nil
106 "Set to non-nil if `markdown-command' does not accept input from stdin.
107 Instead, it will be passed a filename as the final command line
108 option. As a result, you will only be able to run Markdown from
109 buffers which are visiting a file."
113 (defcustom markdown-open-command nil
114 "Command used for opening Markdown files directly.
115 For example, a standalone Markdown previewer. This command will
116 be called with a single argument: the filename of the current
117 buffer. It can also be a function, which will be called without
120 :type
'(choice file function
(const :tag
"None" nil
)))
122 (defcustom markdown-open-image-command nil
123 "Command used for opening image files directly.
124 This is used at `markdown-follow-link-at-point'."
126 :type
'(choice file function
(const :tag
"None" nil
)))
128 (defcustom markdown-hr-strings
129 '("-------------------------------------------------------------------------------"
130 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
131 "---------------------------------------"
132 "* * * * * * * * * * * * * * * * * * * *"
135 "Strings to use when inserting horizontal rules.
136 The first string in the list will be the default when inserting a
137 horizontal rule. Strings should be listed in decreasing order of
138 prominence (as in headings from level one to six) for use with
139 promotion and demotion functions."
141 :type
'(repeat string
))
143 (defcustom markdown-bold-underscore nil
144 "Use two underscores when inserting bold text instead of two asterisks."
148 (defcustom markdown-italic-underscore nil
149 "Use underscores when inserting italic text instead of asterisks."
153 (defcustom markdown-marginalize-headers nil
154 "When non-nil, put opening atx header markup in a left margin.
156 This setting goes well with `markdown-asymmetric-header'. But
157 sadly it conflicts with `linum-mode' since they both use the
162 :package-version
'(markdown-mode .
"2.4"))
164 (defcustom markdown-marginalize-headers-margin-width
6
165 "Character width of margin used for marginalized headers.
166 The default value is based on there being six heading levels
167 defined by Markdown and HTML. Increasing this produces extra
168 whitespace on the left. Decreasing it may be preferred when
169 fewer than six nested heading levels are used."
173 :package-version
'(markdown-mode .
"2.4"))
175 (defcustom markdown-asymmetric-header nil
176 "Determines if atx header style will be asymmetric.
177 Set to a non-nil value to use asymmetric header styling, placing
178 header markup only at the beginning of the line. By default,
179 balanced markup will be inserted at the beginning and end of the
180 line around the header title."
184 (defcustom markdown-indent-function
'markdown-indent-line
185 "Function to use to indent."
189 (defcustom markdown-indent-on-enter t
190 "Determines indentation behavior when pressing \\[newline].
191 Possible settings are nil, t, and 'indent-and-new-item.
193 When non-nil, pressing \\[newline] will call `newline-and-indent'
194 to indent the following line according to the context using
195 `markdown-indent-function'. In this case, note that
196 \\[electric-newline-and-maybe-indent] can still be used to insert
197 a newline without indentation.
199 When set to 'indent-and-new-item and the point is in a list item
200 when \\[newline] is pressed, the list will be continued on the next
201 line, where a new item will be inserted.
203 When set to nil, simply call `newline' as usual. In this case,
204 you can still indent lines using \\[markdown-cycle] and continue
205 lists with \\[markdown-insert-list-item].
207 Note that this assumes the variable `electric-indent-mode' is
208 non-nil (enabled). When it is *disabled*, the behavior of
209 \\[newline] and `\\[electric-newline-and-maybe-indent]' are
212 :type
'(choice (const :tag
"Don't automatically indent" nil
)
213 (const :tag
"Automatically indent" t
)
214 (const :tag
"Automatically indent and insert new list items" indent-and-new-item
)))
216 (defcustom markdown-enable-wiki-links nil
217 "Syntax highlighting for wiki links.
218 Set this to a non-nil value to turn on wiki link support by default.
219 Support can be toggled later using the `markdown-toggle-wiki-links'
220 function or \\[markdown-toggle-wiki-links]."
224 :package-version
'(markdown-mode .
"2.2"))
226 (defcustom markdown-wiki-link-alias-first t
227 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
228 Otherwise, they will be treated as [[PageName|alias text]]."
233 (defcustom markdown-wiki-link-search-subdirectories nil
234 "When non-nil, search for wiki link targets in subdirectories.
235 This is the default search behavior for GitHub and is
236 automatically set to t in `gfm-mode'."
240 :package-version
'(markdown-mode .
"2.2"))
242 (defcustom markdown-wiki-link-search-parent-directories nil
243 "When non-nil, search for wiki link targets in parent directories.
244 This is the default search behavior of Ikiwiki."
248 :package-version
'(markdown-mode .
"2.2"))
250 (defcustom markdown-wiki-link-search-type nil
251 "Searching type for markdown wiki link.
253 sub-directories: search for wiki link targets in sub directories
254 parent-directories: search for wiki link targets in parent directories
255 project: search for wiki link targets under project root"
258 (const :tag
"search wiki link from subdirectories" sub-directories
)
259 (const :tag
"search wiki link from parent directories" parent-directories
)
260 (const :tag
"search wiki link under project root" project
))
261 :package-version
'(markdown-mode .
"2.5"))
263 (make-obsolete-variable 'markdown-wiki-link-search-subdirectories
'markdown-wiki-link-search-type
"2.5")
264 (make-obsolete-variable 'markdown-wiki-link-search-parent-directories
'markdown-wiki-link-search-type
"2.5")
266 (defcustom markdown-wiki-link-fontify-missing nil
267 "When non-nil, change wiki link face according to existence of target files.
268 This is expensive because it requires checking for the file each time the buffer
269 changes or the user switches windows. It is disabled by default because it may
270 cause lag when typing on slower machines."
274 :package-version
'(markdown-mode .
"2.2"))
276 (defcustom markdown-uri-types
277 '("acap" "cid" "data" "dav" "fax" "file" "ftp"
278 "gopher" "http" "https" "imap" "ldap" "mailto"
279 "mid" "message" "modem" "news" "nfs" "nntp"
280 "pop" "prospero" "rtsp" "service" "sip" "tel"
281 "telnet" "tip" "urn" "vemmi" "wais")
282 "Link types for syntax highlighting of URIs."
284 :type
'(repeat (string :tag
"URI scheme")))
286 (defcustom markdown-url-compose-char
288 "Placeholder character for hidden URLs.
289 This may be a single character or a list of characters. In case
290 of a list, the first one that satisfies `char-displayable-p' will
293 (character :tag
"Single URL replacement character")
294 (repeat :tag
"List of possible URL replacement characters"
296 :package-version
'(markdown-mode .
"2.3"))
298 (defcustom markdown-blockquote-display-char
300 "String to display when hiding blockquote markup.
301 This may be a single string or a list of string. In case of a
302 list, the first one that satisfies `char-displayable-p' will be
306 (string :tag
"Single blockquote display string")
307 (repeat :tag
"List of possible blockquote display strings" string
))
308 :package-version
'(markdown-mode .
"2.3"))
310 (defcustom markdown-hr-display-char
312 "Character for hiding horizontal rule markup.
313 This may be a single character or a list of characters. In case
314 of a list, the first one that satisfies `char-displayable-p' will
318 (character :tag
"Single HR display character")
319 (repeat :tag
"List of possible HR display characters" character
))
320 :package-version
'(markdown-mode .
"2.3"))
322 (defcustom markdown-definition-display-char
324 "Character for replacing definition list markup.
325 This may be a single character or a list of characters. In case
326 of a list, the first one that satisfies `char-displayable-p' will
329 (character :tag
"Single definition list character")
330 (repeat :tag
"List of possible definition list characters" character
))
331 :package-version
'(markdown-mode .
"2.3"))
333 (defcustom markdown-enable-math nil
334 "Syntax highlighting for inline LaTeX and itex expressions.
335 Set this to a non-nil value to turn on math support by default.
336 Math support can be enabled, disabled, or toggled later using
337 `markdown-toggle-math' or \\[markdown-toggle-math]."
341 (make-variable-buffer-local 'markdown-enable-math
)
343 (defcustom markdown-enable-html t
344 "Enable font-lock support for HTML tags and attributes."
348 :package-version
'(markdown-mode .
"2.4"))
350 (defcustom markdown-enable-highlighting-syntax nil
351 "Enable highlighting syntax."
355 :package-version
'(markdown-mode .
"2.5"))
357 (defcustom markdown-css-paths nil
358 "List of URLs of CSS files to link to in the output XHTML."
360 :type
'(repeat (string :tag
"CSS File Path")))
362 (defcustom markdown-content-type
"text/html"
363 "Content type string for the http-equiv header in XHTML output.
364 When set to an empty string, this attribute is omitted. Defaults to
369 (defcustom markdown-coding-system nil
370 "Character set string for the http-equiv header in XHTML output.
371 Defaults to `buffer-file-coding-system' (and falling back to
372 `utf-8' when not available). Common settings are `iso-8859-1'
373 and `iso-latin-1'. Use `list-coding-systems' for more choices."
375 :type
'coding-system
)
377 (defcustom markdown-export-kill-buffer t
378 "Kill output buffer after HTML export.
379 When non-nil, kill the HTML output buffer after
380 exporting with `markdown-export'."
384 :package-version
'(markdown-mode .
"2.4"))
386 (defcustom markdown-xhtml-header-content
""
387 "Additional content to include in the XHTML <head> block."
391 (defcustom markdown-xhtml-body-preamble
""
392 "Content to include in the XHTML <body> block, before the output."
396 :package-version
'(markdown-mode .
"2.4"))
398 (defcustom markdown-xhtml-body-epilogue
""
399 "Content to include in the XHTML <body> block, after the output."
403 :package-version
'(markdown-mode .
"2.4"))
405 (defcustom markdown-xhtml-standalone-regexp
406 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
407 "Regexp indicating whether `markdown-command' output is standalone XHTML."
411 (defcustom markdown-link-space-sub-char
"_"
412 "Character to use instead of spaces when mapping wiki links to filenames."
416 (defcustom markdown-reference-location
'header
417 "Position where new reference definitions are inserted in the document."
419 :type
'(choice (const :tag
"At the end of the document" end
)
420 (const :tag
"Immediately after the current block" immediately
)
421 (const :tag
"At the end of the subtree" subtree
)
422 (const :tag
"Before next header" header
)))
424 (defcustom markdown-footnote-location
'end
425 "Position where new footnotes are inserted in the document."
427 :type
'(choice (const :tag
"At the end of the document" end
)
428 (const :tag
"Immediately after the current block" immediately
)
429 (const :tag
"At the end of the subtree" subtree
)
430 (const :tag
"Before next header" header
)))
432 (defcustom markdown-footnote-display
'((raise 0.2) (height 0.8))
433 "Display specification for footnote markers and inline footnotes.
434 By default, footnote text is reduced in size and raised. Set to
435 nil to disable this."
437 :type
'(choice (sexp :tag
"Display specification")
438 (const :tag
"Don't set display property" nil
))
439 :package-version
'(markdown-mode .
"2.4"))
441 (defcustom markdown-sub-superscript-display
442 '(((raise -
0.3) (height 0.7)) .
((raise 0.3) (height 0.7)))
443 "Display specification for subscript and superscripts.
444 The car is used for subscript, the cdr is used for superscripts."
446 :type
'(cons (choice (sexp :tag
"Subscript form")
447 (const :tag
"No lowering" nil
))
448 (choice (sexp :tag
"Superscript form")
449 (const :tag
"No raising" nil
)))
450 :package-version
'(markdown-mode .
"2.4"))
452 (defcustom markdown-unordered-list-item-prefix
" * "
453 "String inserted before unordered list items."
457 (defcustom markdown-ordered-list-enumeration t
458 "When non-nil, use enumerated numbers(1. 2. 3. etc.) for ordered list marker.
459 While nil, always uses '1.' for the marker"
462 :package-version
'(markdown-mode .
"2.5"))
464 (defcustom markdown-nested-imenu-heading-index t
465 "Use nested or flat imenu heading index.
466 A nested index may provide more natural browsing from the menu,
467 but a flat list may allow for faster keyboard navigation via tab
472 :package-version
'(markdown-mode .
"2.2"))
474 (defcustom markdown-add-footnotes-to-imenu t
475 "Add footnotes to end of imenu heading index."
479 :package-version
'(markdown-mode .
"2.4"))
481 (defcustom markdown-make-gfm-checkboxes-buttons t
482 "When non-nil, make GFM checkboxes into buttons."
486 (defcustom markdown-use-pandoc-style-yaml-metadata nil
487 "When non-nil, allow YAML metadata anywhere in the document."
491 (defcustom markdown-split-window-direction
'any
492 "Preference for splitting windows for static and live preview.
493 The default value is 'any, which instructs Emacs to use
494 `split-window-sensibly' to automatically choose how to split
495 windows based on the values of `split-width-threshold' and
496 `split-height-threshold' and the available windows. To force
497 vertically split (left and right) windows, set this to 'vertical
498 or 'right. To force horizontally split (top and bottom) windows,
499 set this to 'horizontal or 'below.
501 If this value is 'any and `display-buffer-alist' is set then
502 `display-buffer' is used for open buffer function"
504 :type
'(choice (const :tag
"Automatic" any
)
505 (const :tag
"Right (vertical)" right
)
506 (const :tag
"Below (horizontal)" below
))
507 :package-version
'(markdown-mode .
"2.2"))
509 (defcustom markdown-live-preview-window-function
510 #'markdown-live-preview-window-eww
511 "Function to display preview of Markdown output within Emacs.
512 Function must update the buffer containing the preview and return
517 (defcustom markdown-live-preview-delete-export
'delete-on-destroy
518 "Delete exported HTML file when using `markdown-live-preview-export'.
519 If set to 'delete-on-export, delete on every export. When set to
520 'delete-on-destroy delete when quitting from command
521 `markdown-live-preview-mode'. Never delete if set to nil."
524 (const :tag
"Delete on every export" delete-on-export
)
525 (const :tag
"Delete when quitting live preview" delete-on-destroy
)
526 (const :tag
"Never delete" nil
)))
528 (defcustom markdown-list-indent-width
4
529 "Depth of indentation for markdown lists.
530 Used in `markdown-demote-list-item' and
531 `markdown-promote-list-item'."
535 (defcustom markdown-enable-prefix-prompts t
536 "Display prompts for certain prefix commands.
537 Set to nil to disable these prompts."
541 :package-version
'(markdown-mode .
"2.3"))
543 (defcustom markdown-gfm-additional-languages nil
544 "Extra languages made available when inserting GFM code blocks.
545 Language strings must have be trimmed of whitespace and not
546 contain any curly braces. They may be of arbitrary
547 capitalization, though."
549 :type
'(repeat (string :validate markdown-validate-language-string
)))
551 (defcustom markdown-gfm-use-electric-backquote t
552 "Use `markdown-electric-backquote' when backquote is hit three times."
556 (defcustom markdown-gfm-downcase-languages t
557 "If non-nil, downcase suggested languages.
558 This applies to insertions done with
559 `markdown-electric-backquote'."
563 (defcustom markdown-edit-code-block-default-mode
'normal-mode
564 "Default mode to use for editing code blocks.
565 This mode is used when automatic detection fails, such as for GFM
566 code blocks with no language specified."
568 :type
'(choice function
(const :tag
"None" nil
))
569 :package-version
'(markdown-mode .
"2.4"))
571 (defcustom markdown-gfm-uppercase-checkbox nil
572 "If non-nil, use [X] for completed checkboxes, [x] otherwise."
577 (defcustom markdown-hide-urls nil
578 "Hide URLs of inline links and reference tags of reference links.
579 Such URLs will be replaced by a single customizable
580 character, defined by `markdown-url-compose-char', but are still part
581 of the buffer. Links can be edited interactively with
582 \\[markdown-insert-link] or, for example, by deleting the final
583 parenthesis to remove the invisibility property. You can also
584 hover your mouse pointer over the link text to see the URL.
585 Set this to a non-nil value to turn this feature on by default.
586 You can interactively set the value of this variable by calling
587 `markdown-toggle-url-hiding', pressing \\[markdown-toggle-url-hiding],
588 or from the menu Markdown > Links & Images menu."
592 :package-version
'(markdown-mode .
"2.3"))
593 (make-variable-buffer-local 'markdown-hide-urls
)
595 (defcustom markdown-translate-filename-function
#'identity
596 "Function to use to translate filenames when following links.
597 \\<markdown-mode-map>\\[markdown-follow-thing-at-point] and \\[markdown-follow-link-at-point]
598 call this function with the filename as only argument whenever
599 they encounter a filename (instead of a URL) to be visited and
600 use its return value instead of the filename in the link. For
601 example, if absolute filenames are actually relative to a server
602 root directory, you can set
603 `markdown-translate-filename-function' to a function that
604 prepends the root directory to the given filename."
608 :package-version
'(markdown-mode .
"2.4"))
610 (defcustom markdown-max-image-size nil
611 "Maximum width and height for displayed inline images.
612 This variable may be nil or a cons cell (MAX-WIDTH . MAX-HEIGHT).
613 When nil, use the actual size. Otherwise, use ImageMagick to
614 resize larger images to be of the given maximum dimensions. This
615 requires Emacs to be built with ImageMagick support."
617 :package-version
'(markdown-mode .
"2.4")
619 (const :tag
"Use actual image width" nil
)
620 (cons (choice (sexp :tag
"Maximum width in pixels")
621 (const :tag
"No maximum width" nil
))
622 (choice (sexp :tag
"Maximum height in pixels")
623 (const :tag
"No maximum height" nil
)))))
625 (defcustom markdown-mouse-follow-link t
626 "Non-nil means mouse on a link will follow the link.
627 This variable must be set before loading markdown-mode."
631 :package-version
'(markdown-mode .
"2.5"))
633 (defcustom markdown-table-align-p t
634 "Non-nil means that table is aligned after table operation."
638 :package-version
'(markdown-mode .
"2.5"))
640 (defcustom markdown-fontify-whole-heading-line nil
641 "Non-nil means fontify the whole line for headings.
642 This is useful when setting a background color for the
643 markdown-header-face-* faces."
647 :package-version
'(markdown-mode .
"2.5"))
650 ;;; Markdown-Specific `rx' Macro ==============================================
652 ;; Based on python-rx from python.el.
654 (defconst markdown-rx-constituents
655 `((newline .
,(rx "\n"))
656 ;; Note: #405 not consider markdown-list-indent-width however this is never used
657 (indent .
,(rx (or (repeat 4 " ") "\t")))
658 (block-end .
,(rx (and (or (one-or-more (zero-or-more blank
) "\n") line-end
))))
659 (numeral .
,(rx (and (one-or-more (any "0-9#")) ".")))
660 (bullet .
,(rx (any "*+:-")))
661 (list-marker .
,(rx (or (and (one-or-more (any "0-9#")) ".")
663 (checkbox .
,(rx "[" (any " xX") "]")))
664 "Markdown-specific sexps for `markdown-rx'")
666 (defun markdown-rx-to-string (form &optional no-group
)
667 "Markdown mode specialized `rx-to-string' function.
668 This variant supports named Markdown expressions in FORM.
669 NO-GROUP non-nil means don't put shy groups around the result."
670 (let ((rx-constituents (append markdown-rx-constituents rx-constituents
)))
671 (rx-to-string form no-group
)))
673 (defmacro markdown-rx
(&rest regexps
)
674 "Markdown mode specialized rx macro.
675 This variant of `rx' supports common Markdown named REGEXPS."
676 (cond ((null regexps
)
679 (markdown-rx-to-string `(and ,@regexps
) t
))
681 (markdown-rx-to-string (car regexps
) t
)))))
684 ;;; Regular Expressions =======================================================
686 (defconst markdown-regex-comment-start
688 "Regular expression matches HTML comment opening.")
690 (defconst markdown-regex-comment-end
692 "Regular expression matches HTML comment closing.")
694 (defconst markdown-regex-link-inline
695 "\\(?1:!\\)?\\(?2:\\[\\)\\(?3:\\^?\\(?:\\\\\\]\\|[^]]\\)*\\|\\)\\(?4:\\]\\)\\(?5:(\\)\\s-*\\(?6:[^)]*?\\)\\(?:\\s-+\\(?7:\"[^\"]*\"\\)\\)?\\s-*\\(?8:)\\)"
696 "Regular expression for a [text](file) or an image link ![text](file).
697 Group 1 matches the leading exclamation point (optional).
698 Group 2 matches the opening square bracket.
699 Group 3 matches the text inside the square brackets.
700 Group 4 matches the closing square bracket.
701 Group 5 matches the opening parenthesis.
702 Group 6 matches the URL.
703 Group 7 matches the title (optional).
704 Group 8 matches the closing parenthesis.")
706 (defconst markdown-regex-link-reference
707 "\\(?1:!\\)?\\(?2:\\[\\)\\(?3:[^]^][^]]*\\|\\)\\(?4:\\]\\)[ ]?\\(?5:\\[\\)\\(?6:[^]]*?\\)\\(?7:\\]\\)"
708 "Regular expression for a reference link [text][id].
709 Group 1 matches the leading exclamation point (optional).
710 Group 2 matches the opening square bracket for the link text.
711 Group 3 matches the text inside the square brackets.
712 Group 4 matches the closing square bracket for the link text.
713 Group 5 matches the opening square bracket for the reference label.
714 Group 6 matches the reference label.
715 Group 7 matches the closing square bracket for the reference label.")
717 (defconst markdown-regex-reference-definition
718 "^ \\{0,3\\}\\(?1:\\[\\)\\(?2:[^]\n]+?\\)\\(?3:\\]\\)\\(?4::\\)\\s *\\(?5:.*?\\)\\s *\\(?6: \"[^\"]*\"$\\|$\\)"
719 "Regular expression for a reference definition.
720 Group 1 matches the opening square bracket.
721 Group 2 matches the reference label.
722 Group 3 matches the closing square bracket.
723 Group 4 matches the colon.
724 Group 5 matches the URL.
725 Group 6 matches the title attribute (optional).")
727 (defconst markdown-regex-footnote
728 "\\(?1:\\[\\^\\)\\(?2:.+?\\)\\(?3:\\]\\)"
729 "Regular expression for a footnote marker [^fn].
730 Group 1 matches the opening square bracket and carat.
731 Group 2 matches only the label, without the surrounding markup.
732 Group 3 matches the closing square bracket.")
734 (defconst markdown-regex-header
735 "^\\(?:\\(?1:[^\r\n\t -].*\\)\n\\(?:\\(?2:=+\\)\\|\\(?3:-+\\)\\)\\|\\(?4:#+[ \t]+\\)\\(?5:.*?\\)\\(?6:[ \t]*#*\\)\\)$"
736 "Regexp identifying Markdown headings.
737 Group 1 matches the text of a setext heading.
738 Group 2 matches the underline of a level-1 setext heading.
739 Group 3 matches the underline of a level-2 setext heading.
740 Group 4 matches the opening hash marks of an atx heading and whitespace.
741 Group 5 matches the text, without surrounding whitespace, of an atx heading.
742 Group 6 matches the closing whitespace and hash marks of an atx heading.")
744 (defconst markdown-regex-header-setext
745 "^\\([^\r\n\t -].*\\)\n\\(=+\\|-+\\)$"
746 "Regular expression for generic setext-style (underline) headers.")
748 (defconst markdown-regex-header-atx
749 "^\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
750 "Regular expression for generic atx-style (hash mark) headers.")
752 (defconst markdown-regex-hr
754 (group (or (and (repeat 3 (and "*" (?
" "))) (* (any "* ")))
755 (and (repeat 3 (and "-" (?
" "))) (* (any "- ")))
756 (and (repeat 3 (and "_" (?
" "))) (* (any "_ ")))))
758 "Regular expression for matching Markdown horizontal rules.")
760 (defconst markdown-regex-code
761 "\\(?:\\`\\|[^\\]\\)\\(?1:\\(?2:`+\\)\\(?3:\\(?:.\\|\n[^\n]\\)*?[^`]\\)\\(?4:\\2\\)\\)\\(?:[^`]\\|\\'\\)"
762 "Regular expression for matching inline code fragments.
764 Group 1 matches the entire code fragment including the backquotes.
765 Group 2 matches the opening backquotes.
766 Group 3 matches the code fragment itself, without backquotes.
767 Group 4 matches the closing backquotes.
769 The leading, unnumbered group ensures that the leading backquote
770 character is not escaped.
771 The last group, also unnumbered, requires that the character
772 following the code fragment is not a backquote.
773 Note that \\(?:.\\|\n[^\n]\\) matches any character, including newlines,
774 but not two newlines in a row.")
776 (defconst markdown-regex-kbd
777 "\\(?1:<kbd>\\)\\(?2:\\(?:.\\|\n[^\n]\\)*?\\)\\(?3:</kbd>\\)"
778 "Regular expression for matching <kbd> tags.
779 Groups 1 and 3 match the opening and closing tags.
780 Group 2 matches the key sequence.")
782 (defconst markdown-regex-gfm-code-block-open
783 "^[[:blank:]]*\\(?1:```\\)\\(?2:[[:blank:]]*{?[[:blank:]]*\\)\\(?3:[^`[:space:]]+?\\)?\\(?:[[:blank:]]+\\(?4:.+?\\)\\)?\\(?5:[[:blank:]]*}?[[:blank:]]*\\)$"
784 "Regular expression matching opening of GFM code blocks.
785 Group 1 matches the opening three backquotes and any following whitespace.
786 Group 2 matches the opening brace (optional) and surrounding whitespace.
787 Group 3 matches the language identifier (optional).
788 Group 4 matches the info string (optional).
789 Group 5 matches the closing brace (optional), whitespace, and newline.
790 Groups need to agree with `markdown-regex-tilde-fence-begin'.")
792 (defconst markdown-regex-gfm-code-block-close
793 "^[[:blank:]]*\\(?1:```\\)\\(?2:\\s *?\\)$"
794 "Regular expression matching closing of GFM code blocks.
795 Group 1 matches the closing three backquotes.
796 Group 2 matches any whitespace and the final newline.")
798 (defconst markdown-regex-pre
800 "Regular expression for matching preformatted text sections.")
802 (defconst markdown-regex-list
803 (markdown-rx line-start
804 ;; 1. Leading whitespace
806 ;; 2. List marker: a numeral, bullet, or colon
808 ;; 3. Trailing whitespace
810 ;; 4. Optional checkbox for GFM task list items
811 (opt (group (and checkbox
(* blank
)))))
812 "Regular expression for matching list items.")
814 (defconst markdown-regex-bold
815 "\\(?1:^\\|[^\\]\\)\\(?2:\\(?3:\\*\\*\\|__\\)\\(?4:[^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(?5:\\3\\)\\)"
816 "Regular expression for matching bold text.
817 Group 1 matches the character before the opening asterisk or
818 underscore, if any, ensuring that it is not a backslash escape.
819 Group 2 matches the entire expression, including delimiters.
820 Groups 3 and 5 matches the opening and closing delimiters.
821 Group 4 matches the text inside the delimiters.")
823 (defconst markdown-regex-italic
824 "\\(?:^\\|[^\\]\\)\\(?1:\\(?2:[*_]\\)\\(?3:[^ \n\t\\]\\|[^ \n\t*]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(?4:\\2\\)\\)"
825 "Regular expression for matching italic text.
826 The leading unnumbered matches the character before the opening
827 asterisk or underscore, if any, ensuring that it is not a
829 Group 1 matches the entire expression, including delimiters.
830 Groups 2 and 4 matches the opening and closing delimiters.
831 Group 3 matches the text inside the delimiters.")
833 (defconst markdown-regex-strike-through
834 "\\(?1:^\\|[^\\]\\)\\(?2:\\(?3:~~\\)\\(?4:[^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(?5:~~\\)\\)"
835 "Regular expression for matching strike-through text.
836 Group 1 matches the character before the opening tilde, if any,
837 ensuring that it is not a backslash escape.
838 Group 2 matches the entire expression, including delimiters.
839 Groups 3 and 5 matches the opening and closing delimiters.
840 Group 4 matches the text inside the delimiters.")
842 (defconst markdown-regex-gfm-italic
843 "\\(?:^\\|[^\\]\\)\\(?1:\\(?2:[*_]\\)\\(?3:[^ \\]\\2\\|[^ ]\\(?:.\\|\n[^\n]\\)*?\\)\\(?4:\\2\\)\\)"
844 "Regular expression for matching italic text in GitHub Flavored Markdown.
845 Underscores in words are not treated as special.
846 Group 1 matches the entire expression, including delimiters.
847 Groups 2 and 4 matches the opening and closing delimiters.
848 Group 3 matches the text inside the delimiters.")
850 (defconst markdown-regex-blockquote
851 "^[ \t]*\\(?1:[A-Z]?>\\)\\(?2:[ \t]*\\)\\(?3:.*\\)$"
852 "Regular expression for matching blockquote lines.
853 Also accounts for a potential capital letter preceding the angle
854 bracket, for use with Leanpub blocks (asides, warnings, info
856 Group 1 matches the leading angle bracket.
857 Group 2 matches the separating whitespace.
858 Group 3 matches the text.")
860 (defconst markdown-regex-line-break
861 "[^ \n\t][ \t]*\\( \\)\n"
862 "Regular expression for matching line breaks.")
864 (defconst markdown-regex-wiki-link
865 "\\(?:^\\|[^\\]\\)\\(?1:\\(?2:\\[\\[\\)\\(?3:[^]|]+\\)\\(?:\\(?4:|\\)\\(?5:[^]]+\\)\\)?\\(?6:\\]\\]\\)\\)"
866 "Regular expression for matching wiki links.
867 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
868 wiki links of the form [[PageName|link text]].
869 The meanings of the first and second components depend
870 on the value of `markdown-wiki-link-alias-first'.
872 Group 1 matches the entire link.
873 Group 2 matches the opening square brackets.
874 Group 3 matches the first component of the wiki link.
875 Group 4 matches the pipe separator, when present.
876 Group 5 matches the second component of the wiki link, when present.
877 Group 6 matches the closing square brackets.")
879 (defconst markdown-regex-uri
880 (concat "\\(" (regexp-opt markdown-uri-types
) ":[^]\t\n\r<>; ]+\\)")
881 "Regular expression for matching inline URIs.")
883 (defconst markdown-regex-angle-uri
884 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types
) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
885 "Regular expression for matching inline URIs in angle brackets.")
887 (defconst markdown-regex-email
888 "<\\(\\(?:\\sw\\|\\s_\\|\\s.\\)+@\\(?:\\sw\\|\\s_\\|\\s.\\)+\\)>"
889 "Regular expression for matching inline email addresses.")
891 (defsubst markdown-make-regex-link-generic
()
892 "Make regular expression for matching any recognized link."
893 (concat "\\(?:" markdown-regex-link-inline
894 (when markdown-enable-wiki-links
895 (concat "\\|" markdown-regex-wiki-link
))
896 "\\|" markdown-regex-link-reference
897 "\\|" markdown-regex-angle-uri
"\\)"))
899 (defconst markdown-regex-gfm-checkbox
900 " \\(\\[[ xX]\\]\\) "
901 "Regular expression for matching GFM checkboxes.
902 Group 1 matches the text to become a button.")
904 (defconst markdown-regex-blank-line
906 "Regular expression that matches a blank line.")
908 (defconst markdown-regex-block-separator
910 "Regular expression for matching block boundaries.")
912 (defconst markdown-regex-block-separator-noindent
913 (concat "\\(\\`\\|\\(" markdown-regex-block-separator
"\\)[^\n\t\f ]\\)")
914 "Regexp for block separators before lines with no indentation.")
916 (defconst markdown-regex-math-inline-single
917 "\\(?:^\\|[^\\]\\)\\(?1:\\$\\)\\(?2:\\(?:[^\\$]\\|\\\\.\\)*\\)\\(?3:\\$\\)"
918 "Regular expression for itex $..$ math mode expressions.
919 Groups 1 and 3 match the opening and closing dollar signs.
920 Group 2 matches the mathematical expression contained within.")
922 (defconst markdown-regex-math-inline-double
923 "\\(?:^\\|[^\\]\\)\\(?1:\\$\\$\\)\\(?2:\\(?:[^\\$]\\|\\\\.\\)*\\)\\(?3:\\$\\$\\)"
924 "Regular expression for itex $$..$$ math mode expressions.
925 Groups 1 and 3 match opening and closing dollar signs.
926 Group 2 matches the mathematical expression contained within.")
928 (defconst markdown-regex-math-display
929 (rx line-start
(* blank
)
930 (group (group (repeat 1 2 "\\")) "[")
931 (group (*? anything
))
932 (group (backref 2) "]")
934 "Regular expression for \[..\] or \\[..\\] display math.
935 Groups 1 and 4 match the opening and closing markup.
936 Group 3 matches the mathematical expression contained within.
937 Group 2 matches the opening slashes, and is used internally to
938 match the closing slashes.")
940 (defsubst markdown-make-tilde-fence-regex
(num-tildes &optional end-of-line
)
941 "Return regexp matching a tilde code fence at least NUM-TILDES long.
942 END-OF-LINE is the regexp construct to indicate end of line; $ if
944 (format "%s%d%s%s" "^[[:blank:]]*\\([~]\\{" num-tildes
",\\}\\)"
945 (or end-of-line
"$")))
947 (defconst markdown-regex-tilde-fence-begin
948 (markdown-make-tilde-fence-regex
949 3 "\\([[:blank:]]*{?\\)[[:blank:]]*\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$")
950 "Regular expression for matching tilde-fenced code blocks.
951 Group 1 matches the opening tildes.
952 Group 2 matches (optional) opening brace and surrounding whitespace.
953 Group 3 matches the language identifier (optional).
954 Group 4 matches the info string (optional).
955 Group 5 matches the closing brace (optional) and any surrounding whitespace.
956 Groups need to agree with `markdown-regex-gfm-code-block-open'.")
958 (defconst markdown-regex-declarative-metadata
959 "^[ \t]*\\(?:-[ \t]*\\)?\\([[:alpha:]][[:alpha:] _-]*?\\)\\([:=][ \t]*\\)\\(.*\\)$"
960 "Regular expression for matching declarative metadata statements.
961 This matches MultiMarkdown metadata as well as YAML and TOML
962 assignments such as the following:
970 (defconst markdown-regex-pandoc-metadata
971 "^\\(%\\)\\([ \t]*\\)\\(.*\\(?:\n[ \t]+.*\\)*\\)"
972 "Regular expression for matching Pandoc metadata.")
974 (defconst markdown-regex-yaml-metadata-border
976 "Regular expression for matching YAML metadata.")
978 (defconst markdown-regex-yaml-pandoc-metadata-end-border
979 "^\\(\\.\\{3\\}\\|\\-\\{3\\}\\)$"
980 "Regular expression for matching YAML metadata end borders.")
982 (defsubst markdown-get-yaml-metadata-start-border
()
983 "Return YAML metadata start border depending upon whether Pandoc is used."
985 (if markdown-use-pandoc-style-yaml-metadata
"^" "\\`")
986 markdown-regex-yaml-metadata-border
))
988 (defsubst markdown-get-yaml-metadata-end-border
(_)
989 "Return YAML metadata end border depending upon whether Pandoc is used."
990 (if markdown-use-pandoc-style-yaml-metadata
991 markdown-regex-yaml-pandoc-metadata-end-border
992 markdown-regex-yaml-metadata-border
))
994 (defconst markdown-regex-inline-attributes
995 "[ \t]*\\(?:{:?\\)[ \t]*\\(?:\\(?:#[[:alpha:]_.:-]+\\|\\.[[:alpha:]_.:-]+\\|\\w+=['\"]?[^\n'\"}]*['\"]?\\),?[ \t]*\\)+\\(?:}\\)[ \t]*$"
996 "Regular expression for matching inline identifiers or attribute lists.
997 Compatible with Pandoc, Python Markdown, PHP Markdown Extra, and Leanpub.")
999 (defconst markdown-regex-leanpub-sections
1002 (regexp-opt '("frontmatter" "mainmatter" "backmatter" "appendix" "pagebreak"))
1003 "\\)\\(}\\)[ \t]*\n")
1004 "Regular expression for Leanpub section markers and related syntax.")
1006 (defconst markdown-regex-sub-superscript
1007 "\\(?:^\\|[^\\~^]\\)\\(?1:\\(?2:[~^]\\)\\(?3:[+-\u2212]?[[:alnum:]]+\\)\\(?4:\\2\\)\\)"
1008 "The regular expression matching a sub- or superscript.
1009 The leading un-numbered group matches the character before the
1010 opening tilde or carat, if any, ensuring that it is not a
1011 backslash escape, carat, or tilde.
1012 Group 1 matches the entire expression, including markup.
1013 Group 2 matches the opening markup--a tilde or carat.
1014 Group 3 matches the text inside the delimiters.
1015 Group 4 matches the closing markup--a tilde or carat.")
1017 (defconst markdown-regex-include
1018 "^\\(?1:<<\\)\\(?:\\(?2:\\[\\)\\(?3:.*\\)\\(?4:\\]\\)\\)?\\(?:\\(?5:(\\)\\(?6:.*\\)\\(?7:)\\)\\)?\\(?:\\(?8:{\\)\\(?9:.*\\)\\(?10:}\\)\\)?$"
1019 "Regular expression matching common forms of include syntax.
1020 Marked 2, Leanpub, and other processors support some of these forms:
1022 <<[sections/section1.md]
1024 <<[Code title](folder/filename)
1025 <<{folder/raw_file.html}
1027 Group 1 matches the opening two angle brackets.
1028 Groups 2-4 match the opening square bracket, the text inside,
1029 and the closing square bracket, respectively.
1030 Groups 5-7 match the opening parenthesis, the text inside, and
1031 the closing parenthesis.
1032 Groups 8-10 match the opening brace, the text inside, and the brace.")
1034 (defconst markdown-regex-pandoc-inline-footnote
1035 "\\(?1:\\^\\)\\(?2:\\[\\)\\(?3:\\(?:.\\|\n[^\n]\\)*?\\)\\(?4:\\]\\)"
1036 "Regular expression for Pandoc inline footnote^[footnote text].
1037 Group 1 matches the opening caret.
1038 Group 2 matches the opening square bracket.
1039 Group 3 matches the footnote text, without the surrounding markup.
1040 Group 4 matches the closing square bracket.")
1042 (defconst markdown-regex-html-attr
1043 "\\(\\<[[:alpha:]:-]+\\>\\)\\(\\s-*\\(=\\)\\s-*\\(\".*?\"\\|'.*?'\\|[^'\">[:space:]]+\\)?\\)?"
1044 "Regular expression for matching HTML attributes and values.
1045 Group 1 matches the attribute name.
1046 Group 2 matches the following whitespace, equals sign, and value, if any.
1047 Group 3 matches the equals sign, if any.
1048 Group 4 matches single-, double-, or un-quoted attribute values.")
1050 (defconst markdown-regex-html-tag
1051 (concat "\\(</?\\)\\(\\w+\\)\\(\\(\\s-+" markdown-regex-html-attr
1052 "\\)+\\s-*\\|\\s-*\\)\\(/?>\\)")
1053 "Regular expression for matching HTML tags.
1054 Groups 1 and 9 match the beginning and ending angle brackets and slashes.
1055 Group 2 matches the tag name.
1056 Group 3 matches all attributes and whitespace following the tag name.")
1058 (defconst markdown-regex-html-entity
1059 "\\(&#?[[:alnum:]]+;\\)"
1060 "Regular expression for matching HTML entities.")
1062 (defconst markdown-regex-highlighting
1063 "\\(?1:^\\|[^\\]\\)\\(?2:\\(?3:==\\)\\(?4:[^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(?5:==\\)\\)"
1064 "Regular expression for matching highlighting text.
1065 Group 1 matches the character before the opening equal, if any,
1066 ensuring that it is not a backslash escape.
1067 Group 2 matches the entire expression, including delimiters.
1068 Groups 3 and 5 matches the opening and closing delimiters.
1069 Group 4 matches the text inside the delimiters.")
1072 ;;; Syntax ====================================================================
1074 (defvar markdown--syntax-properties
1075 (list 'markdown-tilde-fence-begin nil
1076 'markdown-tilde-fence-end nil
1077 'markdown-fenced-code nil
1078 'markdown-yaml-metadata-begin nil
1079 'markdown-yaml-metadata-end nil
1080 'markdown-yaml-metadata-section nil
1081 'markdown-gfm-block-begin nil
1082 'markdown-gfm-block-end nil
1083 'markdown-gfm-code nil
1084 'markdown-list-item nil
1086 'markdown-blockquote nil
1088 'markdown-comment nil
1089 'markdown-heading nil
1090 'markdown-heading-1-setext nil
1091 'markdown-heading-2-setext nil
1092 'markdown-heading-1-atx nil
1093 'markdown-heading-2-atx nil
1094 'markdown-heading-3-atx nil
1095 'markdown-heading-4-atx nil
1096 'markdown-heading-5-atx nil
1097 'markdown-heading-6-atx nil
1098 'markdown-metadata-key nil
1099 'markdown-metadata-value nil
1100 'markdown-metadata-markup nil
)
1101 "Property list of all Markdown syntactic properties.")
1103 (defsubst markdown-in-comment-p
(&optional pos
)
1104 "Return non-nil if POS is in a comment.
1105 If POS is not given, use point instead."
1106 (get-text-property (or pos
(point)) 'markdown-comment
))
1108 (defun markdown--face-p (pos faces
)
1109 "Return non-nil if face of POS contain FACES."
1110 (let ((face-prop (get-text-property pos
'face
)))
1111 (if (listp face-prop
)
1112 (cl-loop for face in face-prop
1113 thereis
(memq face faces
))
1114 (memq face-prop faces
))))
1116 (defun markdown-syntax-propertize-extend-region (start end
)
1117 "Extend START to END region to include an entire block of text.
1118 This helps improve syntax analysis for block constructs.
1119 Returns a cons (NEW-START . NEW-END) or nil if no adjustment should be made.
1120 Function is called repeatedly until it returns nil. For details, see
1121 `syntax-propertize-extend-region-functions'."
1124 (let* ((new-start (progn (goto-char start
)
1125 (skip-chars-forward "\n")
1126 (if (re-search-backward "\n\n" nil t
)
1127 (min start
(match-end 0))
1129 (new-end (progn (goto-char end
)
1130 (skip-chars-backward "\n")
1131 (if (re-search-forward "\n\n" nil t
)
1132 (max end
(match-beginning 0))
1134 (code-match (markdown-code-block-at-pos new-start
))
1135 ;; FIXME: The `code-match' can return bogus values
1136 ;; when text has been inserted/deleted!
1137 (new-start (min (or (and code-match
(cl-first code-match
))
1140 (code-match (and (< end
(point-max))
1141 (markdown-code-block-at-pos end
)))
1142 (new-end (max (or (and code-match
(cl-second code-match
)) 0)
1145 (unless (and (eq new-start start
) (eq new-end end
))
1146 (cons new-start
(min new-end
(point-max))))))))
1148 (defun markdown-font-lock-extend-region-function (start end _
)
1149 "Used in `jit-lock-after-change-extend-region-functions'.
1150 Delegates to `markdown-syntax-propertize-extend-region'. START
1151 and END are the previous region to refontify."
1152 (let ((res (markdown-syntax-propertize-extend-region start end
)))
1154 ;; syntax-propertize-function is not called when character at
1155 ;; (point-max) is deleted, but font-lock-extend-region-functions
1156 ;; are called. Force a syntax property update in that case.
1157 (when (= end
(point-max))
1158 ;; This function is called in a buffer modification hook.
1159 ;; `markdown-syntax-propertize' doesn't save the match data,
1160 ;; so we have to do it here.
1162 (markdown-syntax-propertize (car res
) (cdr res
))))
1163 (setq jit-lock-start
(car res
)
1164 jit-lock-end
(cdr res
)))))
1166 (defun markdown--cur-list-item-bounds ()
1167 "Return a list describing the list item at point.
1168 Assumes that match data is set for `markdown-regex-list'. See the
1169 documentation for `markdown-cur-list-item-bounds' for the format of
1172 (let* ((begin (match-beginning 0))
1173 (indent (length (match-string-no-properties 1)))
1174 (nonlist-indent (- (match-end 3) (match-beginning 0)))
1175 (marker (buffer-substring-no-properties
1176 (match-beginning 2) (match-end 3)))
1177 (checkbox (match-string-no-properties 4))
1178 (match (butlast (match-data t
)))
1179 (end (markdown-cur-list-item-end nonlist-indent
)))
1180 (list begin end indent nonlist-indent marker checkbox match
))))
1182 (defun markdown--append-list-item-bounds (marker indent cur-bounds bounds
)
1183 "Update list item BOUNDS given list MARKER, block INDENT, and CUR-BOUNDS.
1184 Here, MARKER is a string representing the type of list and INDENT
1185 is an integer giving the indentation, in spaces, of the current
1186 block. CUR-BOUNDS is a list of the form returned by
1187 `markdown-cur-list-item-bounds' and BOUNDS is a list of bounds
1188 values for parent list items. When BOUNDS is nil, it means we are
1189 at baseline (not inside of a nested list)."
1190 (let ((prev-indent (or (cl-third (car bounds
)) 0)))
1192 ;; New list item at baseline.
1193 ((and marker
(null bounds
))
1195 ;; List item with greater indentation (four or more spaces).
1196 ;; Increase list level by consing CUR-BOUNDS onto BOUNDS.
1197 ((and marker
(>= indent
(+ prev-indent markdown-list-indent-width
)))
1198 (cons cur-bounds bounds
))
1199 ;; List item with greater or equal indentation (less than four spaces).
1200 ;; Keep list level the same by replacing the car of BOUNDS.
1201 ((and marker
(>= indent prev-indent
))
1202 (cons cur-bounds
(cdr bounds
)))
1203 ;; Lesser indentation level.
1204 ;; Pop appropriate number of elements off BOUNDS list (e.g., lesser
1205 ;; indentation could move back more than one list level). Note
1206 ;; that this block need not be the beginning of list item.
1207 ((< indent prev-indent
)
1208 (while (and (> (length bounds
) 1)
1209 (setq prev-indent
(cl-third (cadr bounds
)))
1210 (< indent
(+ prev-indent markdown-list-indent-width
)))
1211 (setq bounds
(cdr bounds
)))
1212 (cons cur-bounds bounds
))
1213 ;; Otherwise, do nothing.
1216 (defun markdown-syntax-propertize-list-items (start end
)
1217 "Propertize list items from START to END.
1218 Stores nested list item information in the `markdown-list-item'
1219 text property to make later syntax analysis easier. The value of
1220 this property is a list with elements of the form (begin . end)
1221 giving the bounds of the current and parent list items."
1224 (let ((prev-list-line -
100)
1225 bounds level pre-regexp
)
1226 ;; Find a baseline point with zero list indentation
1227 (markdown-search-backward-baseline)
1228 ;; Search for all list items between baseline and END
1229 (while (and (< (point) end
)
1230 (re-search-forward markdown-regex-list end
'limit
))
1231 ;; Level of list nesting
1232 (setq level
(length bounds
))
1233 ;; Pre blocks need to be indented one level past the list level
1234 (setq pre-regexp
(format "^\\( \\|\t\\)\\{%d\\}" (1+ level
)))
1237 ;; Reset at headings, horizontal rules, and top-level blank lines.
1238 ;; Propertize baseline when in range.
1239 ((markdown-new-baseline)
1241 ;; Make sure this is not a line from a pre block
1242 ((and (looking-at-p pre-regexp
)
1243 ;; too indented line is also treated as list if previous line is list
1244 (>= (- (line-number-at-pos) prev-list-line
) 2)))
1245 ;; If not, then update levels and propertize list item when in range.
1247 (let* ((indent (current-indentation))
1248 (cur-bounds (markdown--cur-list-item-bounds))
1249 (first (cl-first cur-bounds
))
1250 (last (cl-second cur-bounds
))
1251 (marker (cl-fifth cur-bounds
)))
1252 (setq bounds
(markdown--append-list-item-bounds
1253 marker indent cur-bounds bounds
))
1254 (when (and (<= start
(point)) (<= (point) end
))
1255 (setq prev-list-line
(line-number-at-pos first
))
1256 (put-text-property first last
'markdown-list-item bounds
)))))
1259 (defun markdown-syntax-propertize-pre-blocks (start end
)
1260 "Match preformatted text blocks from START to END."
1264 ;; Use loop for avoiding too many recursive calls
1265 ;; https://github.com/jrblevin/markdown-mode/issues/512
1267 (let ((levels (markdown-calculate-list-levels))
1268 indent pre-regexp close-regexp open close
)
1269 (while (and (< (point) end
) (not close
))
1270 ;; Search for a region with sufficient indentation
1273 (setq indent
(1+ (length levels
))))
1274 (setq pre-regexp
(format "^\\( \\|\t\\)\\{%d\\}" indent
))
1275 (setq close-regexp
(format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent
)))
1278 ;; If not at the beginning of a line, move forward
1279 ((not (bolp)) (forward-line))
1280 ;; Move past blank lines
1281 ((markdown-cur-line-blank-p) (forward-line))
1282 ;; At headers and horizontal rules, reset levels
1283 ((markdown-new-baseline) (forward-line) (setq levels nil
))
1284 ;; If the current line has sufficient indentation, mark out pre block
1285 ;; The opening should be preceded by a blank line.
1286 ((and (markdown-prev-line-blank) (looking-at pre-regexp
))
1287 (setq open
(match-beginning 0))
1288 (while (and (or (looking-at-p pre-regexp
) (markdown-cur-line-blank-p))
1291 (skip-syntax-backward "-")
1292 (setq close
(point)))
1293 ;; If current line has a list marker, update levels, move to end of block
1294 ((looking-at markdown-regex-list
)
1295 (setq levels
(markdown-update-list-levels
1296 (match-string 2) (current-indentation) levels
))
1297 (markdown-end-of-text-block))
1298 ;; If this is the end of the indentation level, adjust levels accordingly.
1299 ;; Only match end of indentation level if levels is not the empty list.
1300 ((and (car levels
) (looking-at-p close-regexp
))
1301 (setq levels
(markdown-update-list-levels
1302 nil
(current-indentation) levels
))
1303 (markdown-end-of-text-block))
1304 (t (markdown-end-of-text-block))))
1306 (if (and open close
)
1307 ;; Set text property data and continue to search
1308 (put-text-property open close
'markdown-pre
(list open close
))
1312 (defconst markdown-fenced-block-pairs
1313 `(((,markdown-regex-tilde-fence-begin markdown-tilde-fence-begin
)
1314 (markdown-make-tilde-fence-regex markdown-tilde-fence-end
)
1315 markdown-fenced-code
)
1316 ((markdown-get-yaml-metadata-start-border markdown-yaml-metadata-begin
)
1317 (markdown-get-yaml-metadata-end-border markdown-yaml-metadata-end
)
1318 markdown-yaml-metadata-section
)
1319 ((,markdown-regex-gfm-code-block-open markdown-gfm-block-begin
)
1320 (,markdown-regex-gfm-code-block-close markdown-gfm-block-end
)
1322 "Mapping of regular expressions to \"fenced-block\" constructs.
1323 These constructs are distinguished by having a distinctive start
1324 and end pattern, both of which take up an entire line of text,
1325 but no special pattern to identify text within the fenced
1326 blocks (unlike blockquotes and indented-code sections).
1328 Each element within this list takes the form:
1330 ((START-REGEX-OR-FUN START-PROPERTY)
1331 (END-REGEX-OR-FUN END-PROPERTY)
1334 Each *-REGEX-OR-FUN element can be a regular expression as a string, or a
1335 function which evaluates to same. Functions for START-REGEX-OR-FUN accept no
1336 arguments, but functions for END-REGEX-OR-FUN accept a single numerical argument
1337 which is the length of the first group of the START-REGEX-OR-FUN match, which
1338 can be ignored if unnecessary. `markdown-maybe-funcall-regexp' is used to
1339 evaluate these into \"real\" regexps.
1341 The *-PROPERTY elements are the text properties applied to each part of the
1342 block construct when it is matched using
1343 `markdown-syntax-propertize-fenced-block-constructs'. START-PROPERTY is applied
1344 to the text matching START-REGEX-OR-FUN, END-PROPERTY to END-REGEX-OR-FUN, and
1345 MIDDLE-PROPERTY to the text in between the two. The value of *-PROPERTY is the
1346 `match-data' when the regexp was matched to the text. In the case of
1347 MIDDLE-PROPERTY, the value is a false match data of the form '(begin end), with
1348 begin and end set to the edges of the \"middle\" text. This makes fontification
1351 (defun markdown-text-property-at-point (prop)
1352 (get-text-property (point) prop
))
1354 (defsubst markdown-maybe-funcall-regexp
(object &optional arg
)
1355 (cond ((functionp object
)
1356 (if arg
(funcall object arg
) (funcall object
)))
1357 ((stringp object
) object
)
1358 (t (error "Object cannot be turned into regex"))))
1360 (defsubst markdown-get-start-fence-regexp
()
1361 "Return regexp to find all \"start\" sections of fenced block constructs.
1362 Which construct is actually contained in the match must be found separately."
1365 (mapcar (lambda (entry) (markdown-maybe-funcall-regexp (caar entry
)))
1366 markdown-fenced-block-pairs
)
1369 (defun markdown-get-fenced-block-begin-properties ()
1370 (cl-mapcar (lambda (entry) (cl-cadar entry
)) markdown-fenced-block-pairs
))
1372 (defun markdown-get-fenced-block-end-properties ()
1373 (cl-mapcar (lambda (entry) (cl-cadadr entry
)) markdown-fenced-block-pairs
))
1375 (defun markdown-get-fenced-block-middle-properties ()
1376 (cl-mapcar #'cl-third markdown-fenced-block-pairs
))
1378 (defun markdown-find-previous-prop (prop &optional lim
)
1379 "Find previous place where property PROP is non-nil, up to LIM.
1380 Return a cons of (pos . property). pos is point if point contains
1383 (if (get-text-property (point) prop
) (point)
1384 (previous-single-property-change
1385 (point) prop nil
(or lim
(point-min))))))
1386 (when (and (not (get-text-property res prop
))
1388 (get-text-property (1- res
) prop
))
1390 (when (and res
(get-text-property res prop
)) (cons res prop
))))
1392 (defun markdown-find-next-prop (prop &optional lim
)
1393 "Find next place where property PROP is non-nil, up to LIM.
1394 Return a cons of (POS . PROPERTY) where POS is point if point
1395 contains non-nil PROP."
1397 (if (get-text-property (point) prop
) (point)
1398 (next-single-property-change
1399 (point) prop nil
(or lim
(point-max))))))
1400 (when (and res
(get-text-property res prop
)) (cons res prop
))))
1402 (defun markdown-min-of-seq (map-fn seq
)
1403 "Apply MAP-FN to SEQ and return element of SEQ with minimum value of MAP-FN."
1404 (cl-loop for el in seq
1405 with min
= 1.0e
+INF
; infinity
1407 do
(let ((res (funcall map-fn el
)))
1411 finally return min-el
))
1413 (defun markdown-max-of-seq (map-fn seq
)
1414 "Apply MAP-FN to SEQ and return element of SEQ with maximum value of MAP-FN."
1415 (cl-loop for el in seq
1416 with max
= -
1.0e
+INF
; negative infinity
1418 do
(let ((res (funcall map-fn el
)))
1419 (when (and res
(> res max
))
1422 finally return max-el
))
1424 (defun markdown-find-previous-block ()
1425 "Find previous block.
1426 Detect whether `markdown-syntax-propertize-fenced-block-constructs' was
1427 unable to propertize the entire block, but was able to propertize the beginning
1428 of the block. If so, return a cons of (pos . property) where the beginning of
1429 the block was propertized."
1430 (let ((start-pt (point))
1432 (markdown-max-of-seq
1437 #'markdown-find-previous-prop
1438 (markdown-get-fenced-block-begin-properties))))))
1440 (let* ((length-of-open-match
1442 (get-text-property (car closest-open
) (cdr closest-open
))))
1443 (- (cl-fourth match-d
) (cl-third match-d
))))
1445 (markdown-maybe-funcall-regexp
1448 (lambda (entry) (eq (cl-cadar entry
) (cdr closest-open
)))
1449 markdown-fenced-block-pairs
))
1450 length-of-open-match
))
1454 (goto-char (car closest-open
))
1455 (and (re-search-forward end-regexp start-pt t
)
1456 (match-beginning 0))))))
1457 (and (not end-prop-loc
) closest-open
)))))
1459 (defun markdown-get-fenced-block-from-start (prop)
1460 "Return limits of an enclosing fenced block from its start, using PROP.
1461 Return value is a list usable as `match-data'."
1462 (catch 'no-rest-of-block
1463 (let* ((correct-entry
1465 (lambda (entry) (eq (cl-cadar entry
) prop
))
1466 markdown-fenced-block-pairs
))
1467 (begin-of-begin (cl-first (markdown-text-property-at-point prop
)))
1468 (middle-prop (cl-third correct-entry
))
1469 (end-prop (cl-cadadr correct-entry
))
1472 (goto-char (match-end 0)) ; end of begin
1473 (unless (eobp) (forward-char))
1474 (let ((mid-prop-v (markdown-text-property-at-point middle-prop
)))
1475 (if (not mid-prop-v
) ; no middle
1477 ;; try to find end by advancing one
1479 (markdown-text-property-at-point end-prop
)))
1480 (if end-prop-v
(cl-second end-prop-v
)
1481 (throw 'no-rest-of-block nil
))))
1482 (set-match-data mid-prop-v
)
1483 (goto-char (match-end 0)) ; end of middle
1484 (beginning-of-line) ; into end
1485 (cl-second (markdown-text-property-at-point end-prop
)))))))
1486 (list begin-of-begin end-of-end
))))
1488 (defun markdown-get-fenced-block-from-middle (prop)
1489 "Return limits of an enclosing fenced block from its middle, using PROP.
1490 Return value is a list usable as `match-data'."
1491 (let* ((correct-entry
1493 (lambda (entry) (eq (cl-third entry
) prop
))
1494 markdown-fenced-block-pairs
))
1495 (begin-prop (cl-cadar correct-entry
))
1498 (goto-char (match-beginning 0))
1499 (unless (bobp) (forward-line -
1))
1501 (cl-first (markdown-text-property-at-point begin-prop
))))
1502 (end-prop (cl-cadadr correct-entry
))
1505 (goto-char (match-end 0))
1507 (cl-second (markdown-text-property-at-point end-prop
)))))
1508 (list begin-of-begin end-of-end
)))
1510 (defun markdown-get-fenced-block-from-end (prop)
1511 "Return limits of an enclosing fenced block from its end, using PROP.
1512 Return value is a list usable as `match-data'."
1513 (let* ((correct-entry
1515 (lambda (entry) (eq (cl-cadadr entry
) prop
))
1516 markdown-fenced-block-pairs
))
1517 (end-of-end (cl-second (markdown-text-property-at-point prop
)))
1518 (middle-prop (cl-third correct-entry
))
1519 (begin-prop (cl-cadar correct-entry
))
1522 (goto-char (match-beginning 0)) ; beginning of end
1523 (unless (bobp) (backward-char)) ; into middle
1524 (let ((mid-prop-v (markdown-text-property-at-point middle-prop
)))
1525 (if (not mid-prop-v
)
1528 (cl-first (markdown-text-property-at-point begin-prop
)))
1529 (set-match-data mid-prop-v
)
1530 (goto-char (match-beginning 0)) ; beginning of middle
1531 (unless (bobp) (forward-line -
1)) ; into beginning
1533 (cl-first (markdown-text-property-at-point begin-prop
)))))))
1534 (list begin-of-begin end-of-end
)))
1536 (defun markdown-get-enclosing-fenced-block-construct (&optional pos
)
1537 "Get \"fake\" match data for block enclosing POS.
1538 Returns fake match data which encloses the start, middle, and end
1539 of the block construct enclosing POS, if it exists. Used in
1540 `markdown-code-block-at-pos'."
1542 (when pos
(goto-char pos
))
1548 (lambda (fun-and-prop)
1549 (cl-destructuring-bind (fun prop
) fun-and-prop
1552 (set-match-data (markdown-text-property-at-point prop
))
1553 (funcall fun prop
)))))
1554 `((markdown-get-fenced-block-from-start
1556 #'markdown-text-property-at-point
1557 (markdown-get-fenced-block-begin-properties)))
1558 (markdown-get-fenced-block-from-middle
1560 #'markdown-text-property-at-point
1561 (markdown-get-fenced-block-middle-properties)))
1562 (markdown-get-fenced-block-from-end
1564 #'markdown-text-property-at-point
1565 (markdown-get-fenced-block-end-properties)))))))))
1567 (defun markdown-propertize-end-match (reg end fence-spec middle-begin
)
1568 "Get match for REG up to END, if exists, and propertize appropriately.
1569 FENCE-SPEC is an entry in `markdown-fenced-block-pairs' and
1570 MIDDLE-BEGIN is the start of the \"middle\" section of the block."
1571 (when (re-search-forward reg end t
)
1572 (let ((close-begin (match-beginning 0)) ; Start of closing line.
1573 (close-end (match-end 0)) ; End of closing line.
1574 (close-data (match-data t
))) ; Match data for closing line.
1575 ;; Propertize middle section of fenced block.
1576 (put-text-property middle-begin close-begin
1577 (cl-third fence-spec
)
1578 (list middle-begin close-begin
))
1579 ;; If the block is a YAML block, propertize the declarations inside
1580 (when (< middle-begin close-begin
) ;; workaround #634
1581 (markdown-syntax-propertize-yaml-metadata middle-begin close-begin
))
1582 ;; Propertize closing line of fenced block.
1583 (put-text-property close-begin close-end
1584 (cl-cadadr fence-spec
) close-data
))))
1586 (defun markdown--triple-quote-single-line-p (begin)
1590 (and (search-forward "```" nil t
)
1591 (search-forward "```" (line-end-position) t
)))))
1593 (defun markdown-syntax-propertize-fenced-block-constructs (start end
)
1594 "Propertize according to `markdown-fenced-block-pairs' from START to END.
1595 If unable to propertize an entire block (if the start of a block is within START
1596 and END, but the end of the block is not), propertize the start section of a
1597 block, then in a subsequent call propertize both middle and end by finding the
1598 start which was previously propertized."
1599 (let ((start-reg (markdown-get-start-fence-regexp)))
1602 ;; start from previous unclosed block, if exists
1603 (let ((prev-begin-block (markdown-find-previous-block)))
1604 (when prev-begin-block
1605 (let* ((correct-entry
1606 (cl-find-if (lambda (entry)
1607 (eq (cdr prev-begin-block
) (cl-cadar entry
)))
1608 markdown-fenced-block-pairs
))
1609 (enclosed-text-start (1+ (car prev-begin-block
)))
1612 (goto-char (car prev-begin-block
))
1614 (markdown-maybe-funcall-regexp
1615 (caar correct-entry
))
1617 (point-at-bol) (point-at-eol)))
1618 (- (match-end 1) (match-beginning 1))))
1619 (end-reg (markdown-maybe-funcall-regexp
1620 (cl-caadr correct-entry
) start-length
)))
1621 (markdown-propertize-end-match
1622 end-reg end correct-entry enclosed-text-start
))))
1623 ;; find all new blocks within region
1624 (while (re-search-forward start-reg end t
)
1625 ;; we assume the opening constructs take up (only) an entire line,
1626 ;; so we re-check the current line
1627 (let* ((block-start (match-beginning 0))
1628 (cur-line (buffer-substring (point-at-bol) (point-at-eol)))
1629 ;; find entry in `markdown-fenced-block-pairs' corresponding
1630 ;; to regex which was matched
1633 (lambda (fenced-pair)
1635 (markdown-maybe-funcall-regexp (caar fenced-pair
))
1637 markdown-fenced-block-pairs
))
1638 (enclosed-text-start
1639 (save-excursion (1+ (point-at-eol))))
1641 (markdown-maybe-funcall-regexp
1642 (cl-caadr correct-entry
)
1643 (if (and (match-beginning 1) (match-end 1))
1644 (- (match-end 1) (match-beginning 1))
1646 (prop (cl-cadar correct-entry
)))
1647 (when (or (not (eq prop
'markdown-gfm-block-begin
))
1648 (not (markdown--triple-quote-single-line-p block-start
)))
1649 ;; get correct match data
1653 (markdown-maybe-funcall-regexp (caar correct-entry
))
1655 ;; mark starting, even if ending is outside of region
1656 (put-text-property (match-beginning 0) (match-end 0) prop
(match-data t
))
1657 (markdown-propertize-end-match
1658 end-reg end correct-entry enclosed-text-start
)))))))
1660 (defun markdown-syntax-propertize-blockquotes (start end
)
1661 "Match blockquotes from START to END."
1664 (while (and (re-search-forward markdown-regex-blockquote end t
)
1665 (not (markdown-code-block-at-pos (match-beginning 0))))
1666 (put-text-property (match-beginning 0) (match-end 0)
1667 'markdown-blockquote
1670 (defun markdown-syntax-propertize-hrs (start end
)
1671 "Match horizontal rules from START to END."
1674 (while (re-search-forward markdown-regex-hr end t
)
1675 (let ((beg (match-beginning 0))
1676 (end (match-end 0)))
1678 (unless (or (markdown-on-heading-p)
1679 (markdown-code-block-at-point-p))
1680 (put-text-property beg end
'markdown-hr
(match-data t
)))
1683 (defun markdown-syntax-propertize-yaml-metadata (start end
)
1684 "Propertize elements inside YAML metadata blocks from START to END.
1685 Assumes region from START and END is already known to be the interior
1686 region of a YAML metadata block as propertized by
1687 `markdown-syntax-propertize-fenced-block-constructs'."
1691 while
(re-search-forward markdown-regex-declarative-metadata end t
)
1693 (put-text-property (match-beginning 1) (match-end 1)
1694 'markdown-metadata-key
(match-data t
))
1695 (put-text-property (match-beginning 2) (match-end 2)
1696 'markdown-metadata-markup
(match-data t
))
1697 (put-text-property (match-beginning 3) (match-end 3)
1698 'markdown-metadata-value
(match-data t
))))))
1700 (defun markdown-syntax-propertize-headings (start end
)
1701 "Match headings of type SYMBOL with REGEX from START to END."
1703 (while (re-search-forward markdown-regex-header end t
)
1704 (unless (markdown-code-block-at-pos (match-beginning 0))
1706 (match-beginning 0) (match-end 0) 'markdown-heading
1709 (match-beginning 0) (match-end 0)
1710 (cond ((match-string-no-properties 2) 'markdown-heading-1-setext
)
1711 ((match-string-no-properties 3) 'markdown-heading-2-setext
)
1712 (t (let ((atx-level (length (markdown-trim-whitespace
1713 (match-string-no-properties 4)))))
1714 (intern (format "markdown-heading-%d-atx" atx-level
)))))
1717 (defun markdown-syntax-propertize-comments (start end
)
1718 "Match HTML comments from the START to END."
1719 ;; Implement by loop instead of recursive call for avoiding
1720 ;; exceed max-lisp-eval-depth issue
1721 ;; https://github.com/jrblevin/markdown-mode/issues/536
1725 (let* ((in-comment (nth 4 (syntax-ppss)))
1726 (comment-begin (nth 8 (syntax-ppss))))
1729 ((and (not in-comment
)
1730 (re-search-forward markdown-regex-comment-start end t
)
1731 (not (markdown-inline-code-at-point-p))
1732 (not (markdown-code-block-at-point-p)))
1733 (let ((open-beg (match-beginning 0)))
1734 (put-text-property open-beg
(1+ open-beg
)
1735 'syntax-table
(string-to-syntax "<"))
1736 (goto-char (min (1+ (match-end 0)) end
(point-max)))))
1738 ((and in-comment comment-begin
1739 (re-search-forward markdown-regex-comment-end end t
))
1740 (let ((comment-end (match-end 0)))
1741 (put-text-property (1- comment-end
) comment-end
1742 'syntax-table
(string-to-syntax ">"))
1743 ;; Remove any other text properties inside the comment
1744 (remove-text-properties comment-begin comment-end
1745 markdown--syntax-properties
)
1746 (put-text-property comment-begin comment-end
1747 'markdown-comment
(list comment-begin comment-end
))
1748 (goto-char (min comment-end end
(point-max)))))
1750 (t (setq finish t
)))))
1753 (defun markdown-syntax-propertize (start end
)
1754 "Function used as `syntax-propertize-function'.
1755 START and END delimit region to propertize."
1756 (with-silent-modifications
1758 (remove-text-properties start end markdown--syntax-properties
)
1759 (markdown-syntax-propertize-fenced-block-constructs start end
)
1760 (markdown-syntax-propertize-list-items start end
)
1761 (markdown-syntax-propertize-pre-blocks start end
)
1762 (markdown-syntax-propertize-blockquotes start end
)
1763 (markdown-syntax-propertize-headings start end
)
1764 (markdown-syntax-propertize-hrs start end
)
1765 (markdown-syntax-propertize-comments start end
))))
1768 ;;; Markup Hiding =============================================================
1770 (defconst markdown-markup-properties
1771 '(face markdown-markup-face invisible markdown-markup
)
1772 "List of properties and values to apply to markup.")
1774 (defconst markdown-language-keyword-properties
1775 '(face markdown-language-keyword-face invisible markdown-markup
)
1776 "List of properties and values to apply to code block language names.")
1778 (defconst markdown-language-info-properties
1779 '(face markdown-language-info-face invisible markdown-markup
)
1780 "List of properties and values to apply to code block language info strings.")
1782 (defconst markdown-include-title-properties
1783 '(face markdown-link-title-face invisible markdown-markup
)
1784 "List of properties and values to apply to included code titles.")
1786 (defcustom markdown-hide-markup nil
1787 "Determines whether markup in the buffer will be hidden.
1788 When set to nil, all markup is displayed in the buffer as it
1789 appears in the file. An exception is when `markdown-hide-urls'
1791 Set this to a non-nil value to turn this feature on by default.
1792 You can interactively toggle the value of this variable with
1793 `markdown-toggle-markup-hiding', \\[markdown-toggle-markup-hiding],
1794 or from the Markdown > Show & Hide menu.
1796 Markup hiding works by adding text properties to positions in the
1797 buffer---either the `invisible' property or the `display' property
1798 in cases where alternative glyphs are used (e.g., list bullets).
1799 This does not, however, affect printing or other output.
1800 Functions such as `htmlfontify-buffer' and `ps-print-buffer' will
1801 not honor these text properties. For printing, it would be better
1802 to first convert to HTML or PDF (e.g,. using Pandoc)."
1806 :package-version
'(markdown-mode .
"2.3"))
1807 (make-variable-buffer-local 'markdown-hide-markup
)
1809 (defun markdown-toggle-markup-hiding (&optional arg
)
1810 "Toggle the display or hiding of markup.
1811 With a prefix argument ARG, enable markup hiding if ARG is positive,
1812 and disable it otherwise.
1813 See `markdown-hide-markup' for additional details."
1814 (interactive (list (or current-prefix-arg
'toggle
)))
1815 (setq markdown-hide-markup
1816 (if (eq arg
'toggle
)
1817 (not markdown-hide-markup
)
1818 (> (prefix-numeric-value arg
) 0)))
1819 (if markdown-hide-markup
1820 (progn (add-to-invisibility-spec 'markdown-markup
)
1821 (message "markdown-mode markup hiding enabled"))
1822 (progn (remove-from-invisibility-spec 'markdown-markup
)
1823 (message "markdown-mode markup hiding disabled")))
1824 (markdown-reload-extensions))
1827 ;;; Font Lock =================================================================
1829 (require 'font-lock
)
1831 (defgroup markdown-faces nil
1832 "Faces used in Markdown Mode."
1836 (defface markdown-italic-face
1837 '((t (:inherit italic
)))
1838 "Face for italic text."
1839 :group
'markdown-faces
)
1841 (defface markdown-bold-face
1842 '((t (:inherit bold
)))
1843 "Face for bold text."
1844 :group
'markdown-faces
)
1846 (defface markdown-strike-through-face
1847 '((t (:strike-through t
)))
1848 "Face for strike-through text."
1849 :group
'markdown-faces
)
1851 (defface markdown-markup-face
1852 '((t (:inherit shadow
:slant normal
:weight normal
)))
1853 "Face for markup elements."
1854 :group
'markdown-faces
)
1856 (defface markdown-header-rule-face
1857 '((t (:inherit markdown-markup-face
)))
1858 "Base face for headers rules."
1859 :group
'markdown-faces
)
1861 (defface markdown-header-delimiter-face
1862 '((t (:inherit markdown-markup-face
)))
1863 "Base face for headers hash delimiter."
1864 :group
'markdown-faces
)
1866 (defface markdown-list-face
1867 '((t (:inherit markdown-markup-face
)))
1868 "Face for list item markers."
1869 :group
'markdown-faces
)
1871 (defface markdown-blockquote-face
1872 '((t (:inherit font-lock-doc-face
)))
1873 "Face for blockquote sections."
1874 :group
'markdown-faces
)
1876 (defface markdown-code-face
1877 '((t (:inherit fixed-pitch
)))
1878 "Face for inline code, pre blocks, and fenced code blocks.
1879 This may be used, for example, to add a contrasting background to
1880 inline code fragments and code blocks."
1881 :group
'markdown-faces
)
1883 (defface markdown-inline-code-face
1884 '((t (:inherit
(markdown-code-face font-lock-constant-face
))))
1885 "Face for inline code."
1886 :group
'markdown-faces
)
1888 (defface markdown-pre-face
1889 '((t (:inherit
(markdown-code-face font-lock-constant-face
))))
1890 "Face for preformatted text."
1891 :group
'markdown-faces
)
1893 (defface markdown-table-face
1894 '((t (:inherit
(markdown-code-face))))
1896 :group
'markdown-faces
)
1898 (defface markdown-language-keyword-face
1899 '((t (:inherit font-lock-type-face
)))
1900 "Face for programming language identifiers."
1901 :group
'markdown-faces
)
1903 (defface markdown-language-info-face
1904 '((t (:inherit font-lock-string-face
)))
1905 "Face for programming language info strings."
1906 :group
'markdown-faces
)
1908 (defface markdown-link-face
1909 '((t (:inherit link
)))
1911 :group
'markdown-faces
)
1913 (defface markdown-missing-link-face
1914 '((t (:inherit font-lock-warning-face
)))
1915 "Face for missing links."
1916 :group
'markdown-faces
)
1918 (defface markdown-reference-face
1919 '((t (:inherit markdown-markup-face
)))
1920 "Face for link references."
1921 :group
'markdown-faces
)
1923 (defface markdown-footnote-marker-face
1924 '((t (:inherit markdown-markup-face
)))
1925 "Face for footnote markers."
1926 :group
'markdown-faces
)
1928 (defface markdown-footnote-text-face
1929 '((t (:inherit font-lock-comment-face
)))
1930 "Face for footnote text."
1931 :group
'markdown-faces
)
1933 (defface markdown-url-face
1934 '((t (:inherit font-lock-string-face
)))
1935 "Face for URLs that are part of markup.
1936 For example, this applies to URLs in inline links:
1937 [link text](http://example.com/)."
1938 :group
'markdown-faces
)
1940 (defface markdown-plain-url-face
1941 '((t (:inherit markdown-link-face
)))
1942 "Face for URLs that are also links.
1943 For example, this applies to plain angle bracket URLs:
1944 <http://example.com/>."
1945 :group
'markdown-faces
)
1947 (defface markdown-link-title-face
1948 '((t (:inherit font-lock-comment-face
)))
1949 "Face for reference link titles."
1950 :group
'markdown-faces
)
1952 (defface markdown-line-break-face
1953 '((t (:inherit font-lock-constant-face
:underline t
)))
1954 "Face for hard line breaks."
1955 :group
'markdown-faces
)
1957 (defface markdown-comment-face
1958 '((t (:inherit font-lock-comment-face
)))
1959 "Face for HTML comments."
1960 :group
'markdown-faces
)
1962 (defface markdown-math-face
1963 '((t (:inherit font-lock-string-face
)))
1964 "Face for LaTeX expressions."
1965 :group
'markdown-faces
)
1967 (defface markdown-metadata-key-face
1968 '((t (:inherit font-lock-variable-name-face
)))
1969 "Face for metadata keys."
1970 :group
'markdown-faces
)
1972 (defface markdown-metadata-value-face
1973 '((t (:inherit font-lock-string-face
)))
1974 "Face for metadata values."
1975 :group
'markdown-faces
)
1977 (defface markdown-gfm-checkbox-face
1978 '((t (:inherit font-lock-builtin-face
)))
1979 "Face for GFM checkboxes."
1980 :group
'markdown-faces
)
1982 (defface markdown-highlight-face
1983 '((t (:inherit highlight
)))
1984 "Face for mouse highlighting."
1985 :group
'markdown-faces
)
1987 (defface markdown-hr-face
1988 '((t (:inherit markdown-markup-face
)))
1989 "Face for horizontal rules."
1990 :group
'markdown-faces
)
1992 (defface markdown-html-tag-name-face
1993 '((t (:inherit font-lock-type-face
)))
1994 "Face for HTML tag names."
1995 :group
'markdown-faces
)
1997 (defface markdown-html-tag-delimiter-face
1998 '((t (:inherit markdown-markup-face
)))
1999 "Face for HTML tag delimiters."
2000 :group
'markdown-faces
)
2002 (defface markdown-html-attr-name-face
2003 '((t (:inherit font-lock-variable-name-face
)))
2004 "Face for HTML attribute names."
2005 :group
'markdown-faces
)
2007 (defface markdown-html-attr-value-face
2008 '((t (:inherit font-lock-string-face
)))
2009 "Face for HTML attribute values."
2010 :group
'markdown-faces
)
2012 (defface markdown-html-entity-face
2013 '((t (:inherit font-lock-variable-name-face
)))
2014 "Face for HTML entities."
2015 :group
'markdown-faces
)
2017 (defface markdown-highlighting-face
2018 '((t (:background
"yellow" :foreground
"black")))
2019 "Face for highlighting."
2020 :group
'markdown-faces
)
2022 (defcustom markdown-header-scaling nil
2023 "Whether to use variable-height faces for headers.
2024 When non-nil, `markdown-header-face' will inherit from
2025 `variable-pitch' and the scaling values in
2026 `markdown-header-scaling-values' will be applied to
2027 headers of levels one through six respectively."
2029 :initialize
#'custom-initialize-default
2030 :set
(lambda (symbol value
)
2031 (set-default symbol value
)
2032 (markdown-update-header-faces value
))
2033 :group
'markdown-faces
2034 :package-version
'(markdown-mode .
"2.2"))
2036 (defcustom markdown-header-scaling-values
2037 '(2.0
1.7 1.4 1.1 1.0 1.0)
2038 "List of scaling values for headers of level one through six.
2039 Used when `markdown-header-scaling' is non-nil."
2041 :initialize
#'custom-initialize-default
2042 :set
(lambda (symbol value
)
2043 (set-default symbol value
)
2044 (markdown-update-header-faces markdown-header-scaling value
)))
2046 (defmacro markdown--dotimes-when-compile
(i-n body
)
2047 (declare (indent 1) (debug ((symbolp form
) form
)))
2048 (let ((var (car i-n
))
2051 (dotimes (i (eval n t
))
2052 (push (eval body
`((,var .
,i
))) code
))
2053 `(progn ,@(nreverse code
))))
2055 (defface markdown-header-face
2056 `((t (:inherit
(,@(when markdown-header-scaling
'(variable-pitch))
2057 font-lock-function-name-face
)
2059 "Base face for headers.")
2061 (markdown--dotimes-when-compile (num 6)
2062 (let* ((num1 (1+ num
))
2063 (face-name (intern (format "markdown-header-face-%s" num1
))))
2064 `(defface ,face-name
2065 (,'\
` ((t (:inherit markdown-header-face
2067 (,'\
, (if markdown-header-scaling
2068 (float (nth ,num markdown-header-scaling-values
))
2070 (format "Face for level %s headers.
2071 You probably don't want to customize this face directly. Instead
2072 you can customize the base face `markdown-header-face' or the
2073 variable-height variable `markdown-header-scaling'." ,num1
))))
2075 (defun markdown-update-header-faces (&optional scaling scaling-values
)
2076 "Update header faces, depending on if header SCALING is desired.
2077 If so, use given list of SCALING-VALUES relative to the baseline
2078 size of `markdown-header-face'."
2080 (let* ((face-name (intern (format "markdown-header-face-%s" (1+ num
))))
2081 (scale (cond ((not scaling
) 1.0)
2082 (scaling-values (float (nth num scaling-values
)))
2083 (t (float (nth num markdown-header-scaling-values
))))))
2084 (unless (get face-name
'saved-face
) ; Don't update customized faces
2085 (set-face-attribute face-name nil
:height scale
)))))
2087 (defun markdown-syntactic-face (state)
2088 "Return font-lock face for characters with given STATE.
2089 See `font-lock-syntactic-face-function' for details."
2090 (let ((in-comment (nth 4 state
)))
2092 (in-comment 'markdown-comment-face
)
2095 (defcustom markdown-list-item-bullets
2096 '("●" "◎" "○" "◆" "◇" "►" "•")
2097 "List of bullets to use for unordered lists.
2098 It can contain any number of symbols, which will be repeated.
2099 Depending on your font, some reasonable choices are:
2100 ♥ ● ◇ ✚ ✜ ☯ ◆ ♠ ♣ ♦ ❀ ◆ ◖ ▶ ► • ★ ▸."
2102 :type
'(repeat (string :tag
"Bullet character"))
2103 :package-version
'(markdown-mode .
"2.3"))
2105 (defun markdown--footnote-marker-properties ()
2106 "Return a font-lock facespec expression for footnote marker text."
2107 `(face markdown-footnote-marker-face
2108 ,@(when markdown-hide-markup
2109 `(display ,markdown-footnote-display
))))
2111 (defun markdown--pandoc-inline-footnote-properties ()
2112 "Return a font-lock facespec expression for Pandoc inline footnote text."
2113 `(face markdown-footnote-text-face
2114 ,@(when markdown-hide-markup
2115 `(display ,markdown-footnote-display
))))
2117 (defvar markdown-mode-font-lock-keywords
2118 `((markdown-match-yaml-metadata-begin .
((1 'markdown-markup-face
)))
2119 (markdown-match-yaml-metadata-end .
((1 'markdown-markup-face
)))
2120 (markdown-match-yaml-metadata-key .
((1 'markdown-metadata-key-face
)
2121 (2 'markdown-markup-face
)
2122 (3 'markdown-metadata-value-face
)))
2123 (markdown-match-gfm-open-code-blocks .
((1 markdown-markup-properties
)
2124 (2 markdown-markup-properties nil t
)
2125 (3 markdown-language-keyword-properties nil t
)
2126 (4 markdown-language-info-properties nil t
)
2127 (5 markdown-markup-properties nil t
)))
2128 (markdown-match-gfm-close-code-blocks .
((0 markdown-markup-properties
)))
2129 (markdown-fontify-gfm-code-blocks)
2130 (markdown-fontify-tables)
2131 (markdown-match-fenced-start-code-block .
((1 markdown-markup-properties
)
2132 (2 markdown-markup-properties nil t
)
2133 (3 markdown-language-keyword-properties nil t
)
2134 (4 markdown-language-info-properties nil t
)
2135 (5 markdown-markup-properties nil t
)))
2136 (markdown-match-fenced-end-code-block .
((0 markdown-markup-properties
)))
2137 (markdown-fontify-fenced-code-blocks)
2138 (markdown-match-pre-blocks .
((0 'markdown-pre-face
)))
2139 (markdown-fontify-headings)
2140 (markdown-match-declarative-metadata .
((1 'markdown-metadata-key-face
)
2141 (2 'markdown-markup-face
)
2142 (3 'markdown-metadata-value-face
)))
2143 (markdown-match-pandoc-metadata .
((1 'markdown-markup-face
)
2144 (2 'markdown-markup-face
)
2145 (3 'markdown-metadata-value-face
)))
2146 (markdown-fontify-hrs)
2147 (markdown-match-code .
((1 markdown-markup-properties prepend
)
2148 (2 'markdown-inline-code-face prepend
)
2149 (3 markdown-markup-properties prepend
)))
2150 (,markdown-regex-kbd .
((1 markdown-markup-properties
)
2151 (2 'markdown-inline-code-face
)
2152 (3 markdown-markup-properties
)))
2153 (markdown-fontify-angle-uris)
2154 (,markdown-regex-email .
'markdown-plain-url-face
)
2155 (markdown-match-html-tag .
((1 'markdown-html-tag-delimiter-face t
)
2156 (2 'markdown-html-tag-name-face t
)
2157 (3 'markdown-html-tag-delimiter-face t
)
2158 ;; Anchored matcher for HTML tag attributes
2159 (,markdown-regex-html-attr
2160 ;; Before searching, move past tag
2161 ;; name; set limit at tag close.
2163 (goto-char (match-end 2)) (match-end 3))
2165 .
((1 'markdown-html-attr-name-face
)
2166 (3 'markdown-html-tag-delimiter-face nil t
)
2167 (4 'markdown-html-attr-value-face nil t
)))))
2168 (,markdown-regex-html-entity .
'markdown-html-entity-face
)
2169 (markdown-fontify-list-items)
2170 (,markdown-regex-footnote .
((1 markdown-markup-properties
) ; [^
2171 (2 (markdown--footnote-marker-properties)) ; label
2172 (3 markdown-markup-properties
))) ; ]
2173 (,markdown-regex-pandoc-inline-footnote .
((1 markdown-markup-properties
) ; ^
2174 (2 markdown-markup-properties
) ; [
2175 (3 (markdown--pandoc-inline-footnote-properties)) ; text
2176 (4 markdown-markup-properties
))) ; ]
2177 (markdown-match-includes .
((1 markdown-markup-properties
)
2178 (2 markdown-markup-properties nil t
)
2179 (3 markdown-include-title-properties nil t
)
2180 (4 markdown-markup-properties nil t
)
2181 (5 markdown-markup-properties
)
2182 (6 'markdown-url-face
)
2183 (7 markdown-markup-properties
)))
2184 (markdown-fontify-inline-links)
2185 (markdown-fontify-reference-links)
2186 (,markdown-regex-reference-definition .
((1 'markdown-markup-face
) ; [
2187 (2 'markdown-reference-face
) ; label
2188 (3 'markdown-markup-face
) ; ]
2189 (4 'markdown-markup-face
) ; :
2190 (5 'markdown-url-face
) ; url
2191 (6 'markdown-link-title-face
))) ; "title" (optional)
2192 (markdown-fontify-plain-uris)
2194 (markdown-match-math-single .
((1 'markdown-markup-face prepend
)
2195 (2 'markdown-math-face append
)
2196 (3 'markdown-markup-face prepend
)))
2198 (markdown-match-math-double .
((1 'markdown-markup-face prepend
)
2199 (2 'markdown-math-face append
)
2200 (3 'markdown-markup-face prepend
)))
2201 ;; Math mode \[..\] and \\[..\\]
2202 (markdown-match-math-display .
((1 'markdown-markup-face prepend
)
2203 (3 'markdown-math-face append
)
2204 (4 'markdown-markup-face prepend
)))
2205 (markdown-match-bold .
((1 markdown-markup-properties prepend
)
2206 (2 'markdown-bold-face append
)
2207 (3 markdown-markup-properties prepend
)))
2208 (markdown-match-italic .
((1 markdown-markup-properties prepend
)
2209 (2 'markdown-italic-face append
)
2210 (3 markdown-markup-properties prepend
)))
2211 (,markdown-regex-strike-through .
((3 markdown-markup-properties
)
2212 (4 'markdown-strike-through-face
)
2213 (5 markdown-markup-properties
)))
2214 (markdown--match-highlighting .
((3 markdown-markup-properties
)
2215 (4 'markdown-highlighting-face
)
2216 (5 markdown-markup-properties
)))
2217 (,markdown-regex-line-break .
(1 'markdown-line-break-face prepend
))
2218 (markdown-fontify-sub-superscripts)
2219 (markdown-match-inline-attributes .
((0 markdown-markup-properties prepend
)))
2220 (markdown-match-leanpub-sections .
((0 markdown-markup-properties
)))
2221 (markdown-fontify-blockquotes)
2222 (markdown-match-wiki-link .
((0 'markdown-link-face prepend
))))
2223 "Syntax highlighting for Markdown files.")
2226 (defvar-local markdown-footnote-counter
0
2227 "Counter for footnote numbers.")
2229 (defconst markdown-footnote-chars
2231 "Regular expression matching any character for a footnote identifier.")
2233 (defconst markdown-regex-footnote-definition
2234 (concat "^ \\{0,3\\}\\[\\(\\^" markdown-footnote-chars
"*?\\)\\]:\\(?:[ \t]+\\|$\\)")
2235 "Regular expression matching a footnote definition, capturing the label.")
2238 ;;; Compatibility =============================================================
2240 (defun markdown-flyspell-check-word-p ()
2241 "Return t if `flyspell' should check word just before point.
2242 Used for `flyspell-generic-check-word-predicate'."
2244 (goto-char (1- (point)))
2245 ;; https://github.com/jrblevin/markdown-mode/issues/560
2246 ;; enable spell check YAML meta data
2247 (if (or (and (markdown-code-block-at-point-p)
2248 (not (markdown-text-property-at-point 'markdown-yaml-metadata-section
)))
2249 (markdown-inline-code-at-point-p)
2250 (markdown-in-comment-p)
2251 (markdown--face-p (point) '(markdown-reference-face
2252 markdown-markup-face
2253 markdown-plain-url-face
2254 markdown-inline-code-face
2255 markdown-url-face
)))
2257 ;; If flyspell overlay is put, then remove it
2258 (let ((bounds (bounds-of-thing-at-point 'word
)))
2260 (cl-loop for ov in
(overlays-in (car bounds
) (cdr bounds
))
2261 when
(overlay-get ov
'flyspell-overlay
)
2263 (delete-overlay ov
)))))
2267 ;;; Markdown Parsing Functions ================================================
2269 (defun markdown-cur-line-blank-p ()
2270 "Return t if the current line is blank and nil otherwise."
2273 (looking-at-p markdown-regex-blank-line
)))
2275 (defun markdown-prev-line-blank ()
2276 "Return t if the previous line is blank and nil otherwise.
2277 If we are at the first line, then consider the previous line to be blank."
2278 (or (= (line-beginning-position) (point-min))
2281 (looking-at markdown-regex-blank-line
))))
2283 (defun markdown-prev-line-blank-p ()
2284 "Like `markdown-prev-line-blank', but preserve `match-data'."
2285 (save-match-data (markdown-prev-line-blank)))
2287 (defun markdown-next-line-blank-p ()
2288 "Return t if the next line is blank and nil otherwise.
2289 If we are at the last line, then consider the next line to be blank."
2290 (or (= (line-end-position) (point-max))
2293 (markdown-cur-line-blank-p))))
2295 (defun markdown-prev-line-indent ()
2296 "Return the number of leading whitespace characters in the previous line.
2297 Return 0 if the current line is the first line in the buffer."
2299 (if (= (line-beginning-position) (point-min))
2302 (current-indentation))))
2304 (defun markdown-next-line-indent ()
2305 "Return the number of leading whitespace characters in the next line.
2306 Return 0 if line is the last line in the buffer."
2308 (if (= (line-end-position) (point-max))
2311 (current-indentation))))
2313 (defun markdown-new-baseline ()
2314 "Determine if the current line begins a new baseline level.
2315 Assume point is positioned at beginning of line."
2316 (or (looking-at markdown-regex-header
)
2317 (looking-at markdown-regex-hr
)
2318 (and (= (current-indentation) 0)
2319 (not (looking-at markdown-regex-list
))
2320 (markdown-prev-line-blank))))
2322 (defun markdown-search-backward-baseline ()
2323 "Search backward baseline point with no indentation and not a list item."
2326 (while (not (or stop
(bobp)))
2327 (re-search-backward markdown-regex-block-separator-noindent nil t
)
2329 (goto-char (match-end 2))
2331 ((markdown-new-baseline)
2333 ((looking-at-p markdown-regex-list
)
2335 (t (setq stop t
)))))))
2337 (defun markdown-update-list-levels (marker indent levels
)
2338 "Update list levels given list MARKER, block INDENT, and current LEVELS.
2339 Here, MARKER is a string representing the type of list, INDENT is an integer
2340 giving the indentation, in spaces, of the current block, and LEVELS is a
2341 list of the indentation levels of parent list items. When LEVELS is nil,
2342 it means we are at baseline (not inside of a nested list)."
2344 ;; New list item at baseline.
2345 ((and marker
(null levels
))
2346 (setq levels
(list indent
)))
2347 ;; List item with greater indentation (four or more spaces).
2348 ;; Increase list level.
2349 ((and marker
(>= indent
(+ (car levels
) markdown-list-indent-width
)))
2350 (setq levels
(cons indent levels
)))
2351 ;; List item with greater or equal indentation (less than four spaces).
2352 ;; Do not increase list level.
2353 ((and marker
(>= indent
(car levels
)))
2355 ;; Lesser indentation level.
2356 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
2357 ;; indentation could move back more than one list level). Note
2358 ;; that this block need not be the beginning of list item.
2359 ((< indent
(car levels
))
2360 (while (and (> (length levels
) 1)
2361 (< indent
(+ (cadr levels
) markdown-list-indent-width
)))
2362 (setq levels
(cdr levels
)))
2364 ;; Otherwise, do nothing.
2367 (defun markdown-calculate-list-levels ()
2368 "Calculate list levels at point.
2369 Return a list of the form (n1 n2 n3 ...) where n1 is the
2370 indentation of the deepest nested list item in the branch of
2371 the list at the point, n2 is the indentation of the parent
2372 list item, and so on. The depth of the list item is therefore
2373 the length of the returned list. If the point is not at or
2374 immediately after a list item, return nil."
2376 (let ((first (point)) levels indent pre-regexp
)
2377 ;; Find a baseline point with zero list indentation
2378 (markdown-search-backward-baseline)
2379 ;; Search for all list items between baseline and LOC
2380 (while (and (< (point) first
)
2381 (re-search-forward markdown-regex-list first t
))
2382 (setq pre-regexp
(format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels
))))
2385 ;; Make sure this is not a header or hr
2386 ((markdown-new-baseline) (setq levels nil
))
2387 ;; Make sure this is not a line from a pre block
2388 ((looking-at-p pre-regexp
))
2389 ;; If not, then update levels
2391 (setq indent
(current-indentation))
2392 (setq levels
(markdown-update-list-levels (match-string 2)
2397 (defun markdown-prev-list-item (level)
2398 "Search backward from point for a list item with indentation LEVEL.
2399 Set point to the beginning of the item, and return point, or nil
2401 (let (bounds indent prev
)
2404 (setq indent
(current-indentation))
2408 ((and (looking-at-p markdown-regex-list
)
2409 (setq bounds
(markdown-cur-list-item-bounds)))
2411 ;; Stop and return point at item of equal indentation
2412 ((= (nth 3 bounds
) level
)
2415 ;; Stop and return nil at item with lesser indentation
2416 ((< (nth 3 bounds
) level
)
2419 ;; Stop at beginning of buffer
2420 ((bobp) (setq prev nil
))
2421 ;; Continue at item with greater indentation
2422 ((> (nth 3 bounds
) level
) t
)))
2423 ;; Stop at beginning of buffer
2424 ((bobp) (setq prev nil
))
2425 ;; Continue if current line is blank
2426 ((markdown-cur-line-blank-p) t
)
2427 ;; Continue while indentation is the same or greater
2428 ((>= indent level
) t
)
2429 ;; Stop if current indentation is less than list item
2430 ;; and the next is blank
2431 ((and (< indent level
)
2432 (markdown-next-line-blank-p))
2435 ((looking-at-p markdown-regex-header
) (setq prev nil
))
2436 ;; Stop at a horizontal rule
2437 ((looking-at-p markdown-regex-hr
) (setq prev nil
))
2438 ;; Otherwise, continue.
2441 (setq indent
(current-indentation)))
2444 (defun markdown-next-list-item (level)
2445 "Search forward from point for the next list item with indentation LEVEL.
2446 Set point to the beginning of the item, and return point, or nil
2448 (let (bounds indent next
)
2450 (if (looking-at markdown-regex-header-setext
)
2451 (goto-char (match-end 0)))
2453 (setq indent
(current-indentation))
2456 ;; Stop at end of the buffer.
2458 ;; Continue if the current line is blank
2459 ((markdown-cur-line-blank-p) t
)
2461 ((and (looking-at-p markdown-regex-list
)
2462 (setq bounds
(markdown-cur-list-item-bounds)))
2464 ;; Continue at item with greater indentation
2465 ((> (nth 3 bounds
) level
) t
)
2466 ;; Stop and return point at item of equal indentation
2467 ((= (nth 3 bounds
) level
)
2470 ;; Stop and return nil at item with lesser indentation
2471 ((< (nth 3 bounds
) level
)
2474 ;; Continue while indentation is the same or greater
2475 ((>= indent level
) t
)
2476 ;; Stop if current indentation is less than list item
2477 ;; and the previous line was blank.
2478 ((and (< indent level
)
2479 (markdown-prev-line-blank-p))
2482 ((looking-at-p markdown-regex-header
) (setq next nil
))
2483 ;; Stop at a horizontal rule
2484 ((looking-at-p markdown-regex-hr
) (setq next nil
))
2485 ;; Otherwise, continue.
2488 (setq indent
(current-indentation)))
2491 (defun markdown-cur-list-item-end (level)
2492 "Move to end of list item with pre-marker indentation LEVEL.
2493 Return the point at the end when a list item was found at the
2494 original point. If the point is not in a list item, do nothing."
2497 (setq indent
(current-indentation))
2500 ;; Stop at end of the buffer.
2502 ;; Continue while indentation is the same or greater
2503 ((>= indent level
) t
)
2504 ;; Continue if the current line is blank
2505 ((looking-at markdown-regex-blank-line
) t
)
2506 ;; Stop if current indentation is less than list item
2507 ;; and the previous line was blank.
2508 ((and (< indent level
)
2509 (markdown-prev-line-blank))
2511 ;; Stop at a new list items of the same or lesser
2512 ;; indentation, headings, and horizontal rules.
2513 ((looking-at (concat "\\(?:" markdown-regex-list
2514 "\\|" markdown-regex-header
2515 "\\|" markdown-regex-hr
"\\)"))
2517 ;; Otherwise, continue.
2520 (setq indent
(current-indentation)))
2521 ;; Don't skip over whitespace for empty list items (marker and
2522 ;; whitespace only), just move to end of whitespace.
2525 (looking-at (concat markdown-regex-list
"[ \t]*$")))
2526 (goto-char (match-end 3))
2527 (skip-chars-backward " \t\n"))
2531 (defun markdown-cur-list-item-bounds ()
2532 "Return bounds for list item at point.
2533 Return a list of the following form:
2535 (begin end indent nonlist-indent marker checkbox match)
2537 The named components are:
2539 - begin: Position of beginning of list item, including leading indentation.
2540 - end: Position of the end of the list item, including list item text.
2541 - indent: Number of characters of indentation before list marker (an integer).
2542 - nonlist-indent: Number characters of indentation, list
2543 marker, and whitespace following list marker (an integer).
2544 - marker: String containing the list marker and following whitespace
2545 (e.g., \"- \" or \"* \").
2546 - checkbox: String containing the GFM checkbox portion, if any,
2547 including any trailing whitespace before the text
2548 begins (e.g., \"[x] \").
2549 - match: match data for markdown-regex-list
2551 As an example, for the following unordered list item
2555 the returned list would be
2557 (1 14 3 5 \"- \" nil (1 6 1 4 4 5 5 6))
2559 If the point is not inside a list item, return nil."
2560 (car (get-text-property (point-at-bol) 'markdown-list-item
)))
2562 (defun markdown-list-item-at-point-p ()
2563 "Return t if there is a list item at the point and nil otherwise."
2564 (save-match-data (markdown-cur-list-item-bounds)))
2566 (defun markdown-prev-list-item-bounds ()
2567 "Return bounds of previous item in the same list of any level.
2568 The return value has the same form as that of
2569 `markdown-cur-list-item-bounds'."
2571 (let ((cur-bounds (markdown-cur-list-item-bounds))
2572 (beginning-of-list (save-excursion (markdown-beginning-of-list)))
2575 (goto-char (nth 0 cur-bounds
))
2576 (while (and (not stop
) (not (bobp))
2577 (re-search-backward markdown-regex-list
2578 beginning-of-list t
))
2579 (unless (or (looking-at markdown-regex-hr
)
2580 (markdown-code-block-at-point-p))
2581 (setq stop
(point))))
2582 (markdown-cur-list-item-bounds)))))
2584 (defun markdown-next-list-item-bounds ()
2585 "Return bounds of next item in the same list of any level.
2586 The return value has the same form as that of
2587 `markdown-cur-list-item-bounds'."
2589 (let ((cur-bounds (markdown-cur-list-item-bounds))
2590 (end-of-list (save-excursion (markdown-end-of-list)))
2593 (goto-char (nth 0 cur-bounds
))
2595 (while (and (not stop
) (not (eobp))
2596 (re-search-forward markdown-regex-list
2598 (unless (or (looking-at markdown-regex-hr
)
2599 (markdown-code-block-at-point-p))
2600 (setq stop
(point))))
2602 (markdown-cur-list-item-bounds))))))
2604 (defun markdown-beginning-of-list ()
2605 "Move point to beginning of list at point, if any."
2607 (let ((orig-point (point))
2608 (list-begin (save-excursion
2609 (markdown-search-backward-baseline)
2610 ;; Stop at next list item, regardless of the indentation.
2611 (markdown-next-list-item (point-max))
2612 (when (looking-at markdown-regex-list
)
2614 (when (and list-begin
(<= list-begin orig-point
))
2615 (goto-char list-begin
))))
2617 (defun markdown-end-of-list ()
2618 "Move point to end of list at point, if any."
2620 (let ((start (point))
2621 (end (save-excursion
2622 (when (markdown-beginning-of-list)
2623 ;; Items can't have nonlist-indent <= 1, so this
2624 ;; moves past all list items.
2625 (markdown-next-list-item 1)
2626 (skip-syntax-backward "-")
2627 (unless (eobp) (forward-char 1))
2629 (when (and end
(>= end start
))
2632 (defun markdown-up-list ()
2633 "Move point to beginning of parent list item."
2635 (let ((cur-bounds (markdown-cur-list-item-bounds)))
2637 (markdown-prev-list-item (1- (nth 3 cur-bounds
)))
2638 (let ((up-bounds (markdown-cur-list-item-bounds)))
2639 (when (and up-bounds
(< (nth 3 up-bounds
) (nth 3 cur-bounds
)))
2642 (defun markdown-bounds-of-thing-at-point (thing)
2643 "Call `bounds-of-thing-at-point' for THING with slight modifications.
2644 Does not include trailing newlines when THING is 'line. Handles the
2645 end of buffer case by setting both endpoints equal to the value of
2646 `point-max', since an empty region will trigger empty markup insertion.
2647 Return bounds of form (beg . end) if THING is found, or nil otherwise."
2648 (let* ((bounds (bounds-of-thing-at-point thing
))
2652 (when (eq thing
'line
)
2653 (cond ((and (eobp) (markdown-cur-line-blank-p))
2655 ((char-equal (char-before b
) ?\^J
)
2659 (defun markdown-reference-definition (reference)
2660 "Find out whether Markdown REFERENCE is defined.
2661 REFERENCE should not include the square brackets.
2662 When REFERENCE is defined, return a list of the form (text start end)
2663 containing the definition text itself followed by the start and end
2664 locations of the text. Otherwise, return nil.
2665 Leave match data for `markdown-regex-reference-definition'
2666 intact additional processing."
2667 (let ((reference (downcase reference
)))
2669 (goto-char (point-min))
2671 (while (re-search-forward markdown-regex-reference-definition nil t
)
2672 (when (string= reference
(downcase (match-string-no-properties 2)))
2674 (list (match-string-no-properties 5)
2675 (match-beginning 5) (match-end 5)))))))))
2677 (defun markdown-get-defined-references ()
2678 "Return all defined reference labels and their line numbers.
2679 They does not include square brackets)."
2681 (goto-char (point-min))
2683 (while (re-search-forward markdown-regex-reference-definition nil t
)
2684 (let ((target (match-string-no-properties 2)))
2686 (cons (downcase target
)
2687 (markdown-line-number-at-pos (match-beginning 2)))
2688 refs
:test
#'equal
:key
#'car
)))
2691 (defun markdown-get-used-uris ()
2692 "Return a list of all used URIs in the buffer."
2694 (goto-char (point-min))
2696 (while (re-search-forward
2697 (concat "\\(?:" markdown-regex-link-inline
2698 "\\|" markdown-regex-angle-uri
2699 "\\|" markdown-regex-uri
2700 "\\|" markdown-regex-email
2703 (unless (or (markdown-inline-code-at-point-p)
2704 (markdown-code-block-at-point-p))
2705 (cl-pushnew (or (match-string-no-properties 6)
2706 (match-string-no-properties 10)
2707 (match-string-no-properties 12)
2708 (match-string-no-properties 13))
2709 uris
:test
#'equal
)))
2712 (defun markdown-inline-code-at-pos (pos)
2713 "Return non-nil if there is an inline code fragment at POS.
2714 Return nil otherwise. Set match data according to
2715 `markdown-match-code' upon success.
2716 This function searches the block for a code fragment that
2717 contains the point using `markdown-match-code'. We do this
2718 because `thing-at-point-looking-at' does not work reliably with
2719 `markdown-regex-code'.
2721 The match data is set as follows:
2722 Group 1 matches the opening backquotes.
2723 Group 2 matches the code fragment itself, without backquotes.
2724 Group 3 matches the closing backquotes."
2727 (let ((old-point (point))
2728 (end-of-block (progn (markdown-end-of-text-block) (point)))
2730 (markdown-beginning-of-text-block)
2731 (while (and (markdown-match-code end-of-block
)
2733 (< (match-end 0) old-point
)))
2734 (let ((match-group (if (eq (char-after (match-beginning 0)) ?
`) 0 1)))
2735 (and found
; matched something
2736 (<= (match-beginning match-group
) old-point
) ; match contains old-point
2737 (> (match-end 0) old-point
))))))
2739 (defun markdown-inline-code-at-pos-p (pos)
2740 "Return non-nil if there is an inline code fragment at POS.
2741 Like `markdown-inline-code-at-pos`, but preserves match data."
2742 (save-match-data (markdown-inline-code-at-pos pos
)))
2744 (defun markdown-inline-code-at-point ()
2745 "Return non-nil if the point is at an inline code fragment.
2746 See `markdown-inline-code-at-pos' for details."
2747 (markdown-inline-code-at-pos (point)))
2749 (defun markdown-inline-code-at-point-p (&optional pos
)
2750 "Return non-nil if there is inline code at the POS.
2751 This is a predicate function counterpart to
2752 `markdown-inline-code-at-point' which does not modify the match
2753 data. See `markdown-code-block-at-point-p' for code blocks."
2754 (save-match-data (markdown-inline-code-at-pos (or pos
(point)))))
2756 (defun markdown-code-block-at-pos (pos)
2757 "Return match data list if there is a code block at POS.
2758 Uses text properties at the beginning of the line position.
2759 This includes pre blocks, tilde-fenced code blocks, and GFM
2760 quoted code blocks. Return nil otherwise."
2761 (let ((bol (save-excursion (goto-char pos
) (point-at-bol))))
2762 (or (get-text-property bol
'markdown-pre
)
2763 (let* ((bounds (markdown-get-enclosing-fenced-block-construct pos
))
2764 (second (cl-second bounds
)))
2766 ;; chunks are right open
2767 (when (< pos second
)
2771 ;; Function was renamed to emphasize that it does not modify match-data.
2772 (defalias 'markdown-code-block-at-point
'markdown-code-block-at-point-p
)
2774 (defun markdown-code-block-at-point-p (&optional pos
)
2775 "Return non-nil if there is a code block at the POS.
2776 This includes pre blocks, tilde-fenced code blocks, and GFM
2777 quoted code blocks. This function does not modify the match
2778 data. See `markdown-inline-code-at-point-p' for inline code."
2779 (save-match-data (markdown-code-block-at-pos (or pos
(point)))))
2781 (defun markdown-heading-at-point (&optional pos
)
2782 "Return non-nil if there is a heading at the POS.
2783 Set match data for `markdown-regex-header'."
2784 (let ((match-data (get-text-property (or pos
(point)) 'markdown-heading
)))
2786 (set-match-data match-data
)
2789 (defun markdown-pipe-at-bol-p ()
2790 "Return non-nil if the line begins with a pipe symbol.
2791 This may be useful for tables and Pandoc's line_blocks extension."
2792 (char-equal (char-after (point-at-bol)) ?|
))
2795 ;;; Markdown Font Lock Matching Functions =====================================
2797 (defun markdown-range-property-any (begin end prop prop-values
)
2798 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
2799 Also returns t if PROP is a list containing one of the PROP-VALUES.
2800 Return nil otherwise."
2803 (dolist (loc (number-sequence begin end
))
2804 (when (setq props
(get-text-property loc prop
))
2805 (cond ((listp props
)
2806 ;; props is a list, check for membership
2807 (dolist (val prop-values
)
2808 (when (memq val props
) (throw 'found loc
))))
2810 ;; props is a scalar, check for equality
2811 (dolist (val prop-values
)
2812 (when (eq val props
) (throw 'found loc
))))))))))
2814 (defun markdown-range-properties-exist (begin end props
)
2816 for loc in
(number-sequence begin end
)
2820 (cl-some (lambda (prop) (get-text-property loc prop
)) props
)))
2821 finally return result
))
2823 (defun markdown-match-inline-generic (regex last
&optional faceless
)
2824 "Match inline REGEX from the point to LAST.
2825 When FACELESS is non-nil, do not return matches where faces have been applied."
2826 (when (re-search-forward regex last t
)
2827 (let ((bounds (markdown-code-block-at-pos (match-beginning 1)))
2828 (face (and faceless
(text-property-not-all
2829 (match-beginning 0) (match-end 0) 'face nil
))))
2831 ;; In code block: move past it and recursively search again
2833 (when (< (goto-char (cl-second bounds
)) last
)
2834 (markdown-match-inline-generic regex last faceless
)))
2835 ;; When faces are found in the match range, skip over the match and
2836 ;; recursively search again.
2838 (when (< (goto-char (match-end 0)) last
)
2839 (markdown-match-inline-generic regex last faceless
)))
2840 ;; Keep match data and return t when in bounds.
2842 (<= (match-end 0) last
))))))
2844 (defun markdown-match-code (last)
2845 "Match inline code fragments from point to LAST."
2848 (when (markdown-search-until-condition
2851 ;; Advance point in case of failure, but without exceeding last.
2852 (goto-char (min (1+ (match-beginning 1)) last
))
2853 (not (markdown-in-comment-p (match-beginning 1)))
2854 (not (markdown-in-comment-p (match-end 1)))
2855 (not (markdown-code-block-at-pos (match-beginning 1)))))
2856 markdown-regex-code last t
)
2857 (set-match-data (list (match-beginning 1) (match-end 1)
2858 (match-beginning 2) (match-end 2)
2859 (match-beginning 3) (match-end 3)
2860 (match-beginning 4) (match-end 4)))
2861 (goto-char (min (1+ (match-end 0)) last
(point-max)))
2864 (defun markdown--gfm-markup-underscore-p (begin end
)
2865 (let ((is-underscore (eql (char-after begin
) ?_
)))
2866 (if (not is-underscore
)
2871 (and (looking-back "\\(?:^\\|[[:blank:][:punct:]]\\)" (1- begin
))
2874 (looking-at-p "\\(?:[[:blank:][:punct:]]\\|$\\)"))))))))
2876 (defun markdown-match-bold (last)
2877 "Match inline bold from the point to LAST."
2878 (when (markdown-match-inline-generic markdown-regex-bold last
)
2879 (let ((is-gfm (derived-mode-p 'gfm-mode
))
2880 (begin (match-beginning 2))
2881 (end (match-end 2)))
2882 (if (or (markdown-inline-code-at-pos-p begin
)
2883 (markdown-inline-code-at-pos-p end
)
2884 (markdown-in-comment-p)
2885 (markdown-range-property-any
2886 begin begin
'face
'(markdown-url-face
2887 markdown-plain-url-face
))
2888 (markdown-range-property-any
2889 begin end
'face
'(markdown-hr-face
2890 markdown-math-face
))
2891 (and is-gfm
(not (markdown--gfm-markup-underscore-p begin end
))))
2892 (progn (goto-char (min (1+ begin
) last
))
2893 (when (< (point) last
)
2894 (markdown-match-bold last
)))
2895 (set-match-data (list (match-beginning 2) (match-end 2)
2896 (match-beginning 3) (match-end 3)
2897 (match-beginning 4) (match-end 4)
2898 (match-beginning 5) (match-end 5)))
2901 (defun markdown-match-italic (last)
2902 "Match inline italics from the point to LAST."
2903 (let* ((is-gfm (derived-mode-p 'gfm-mode
))
2905 markdown-regex-gfm-italic
2906 markdown-regex-italic
)))
2907 (when (and (markdown-match-inline-generic regex last
)
2908 (not (markdown--face-p
2910 '(markdown-html-attr-name-face markdown-html-attr-value-face
))))
2911 (let ((begin (match-beginning 1))
2913 (close-end (match-end 4)))
2914 (if (or (eql (char-before begin
) (char-after begin
))
2915 (markdown-inline-code-at-pos-p begin
)
2916 (markdown-inline-code-at-pos-p (1- end
))
2917 (markdown-in-comment-p)
2918 (markdown-range-property-any
2919 begin begin
'face
'(markdown-url-face
2920 markdown-plain-url-face
))
2921 (markdown-range-property-any
2922 begin end
'face
'(markdown-bold-face
2925 markdown-math-face
))
2927 (or (char-equal (char-after begin
) (char-after (1+ begin
))) ;; check bold case
2928 (not (markdown--gfm-markup-underscore-p begin close-end
)))))
2929 (progn (goto-char (min (1+ begin
) last
))
2930 (when (< (point) last
)
2931 (markdown-match-italic last
)))
2932 (set-match-data (list (match-beginning 1) (match-end 1)
2933 (match-beginning 2) (match-end 2)
2934 (match-beginning 3) (match-end 3)
2935 (match-beginning 4) (match-end 4)))
2938 (defun markdown--match-highlighting (last)
2939 (when markdown-enable-highlighting-syntax
2940 (re-search-forward markdown-regex-highlighting last t
)))
2942 (defun markdown-match-math-generic (regex last
)
2943 "Match REGEX from point to LAST.
2944 REGEX is either `markdown-regex-math-inline-single' for matching
2945 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
2946 (when (markdown-match-inline-generic regex last
)
2947 (let ((begin (match-beginning 1)) (end (match-end 1)))
2949 (if (or (markdown-range-property-any
2951 '(markdown-inline-code-face markdown-bold-face
))
2952 (markdown-range-properties-exist
2954 (markdown-get-fenced-block-middle-properties)))
2955 (markdown-match-math-generic regex last
)
2957 (goto-char (1+ (match-end 0)))))))
2959 (defun markdown-match-list-items (last)
2960 "Match list items from point to LAST."
2961 (let* ((first (point))
2963 (prop 'markdown-list-item
)
2964 (bounds (car (get-text-property pos prop
))))
2966 (and (or (null (setq bounds
(car (get-text-property pos prop
))))
2967 (< (cl-first bounds
) pos
))
2969 (setq pos
(next-single-property-change pos prop nil last
))
2972 (set-match-data (cl-seventh bounds
))
2973 ;; Step at least one character beyond point. Otherwise
2974 ;; `font-lock-fontify-keywords-region' infloops.
2975 (goto-char (min (1+ (max (point-at-eol) first
))
2979 (defun markdown-match-math-single (last)
2980 "Match single quoted $..$ math from point to LAST."
2981 (when markdown-enable-math
2982 (when (and (char-equal (char-after) ?$
)
2984 (not (char-equal (char-before) ?
\\))
2985 (not (char-equal (char-before) ?$
)))
2987 (markdown-match-math-generic markdown-regex-math-inline-single last
)))
2989 (defun markdown-match-math-double (last)
2990 "Match double quoted $$..$$ math from point to LAST."
2991 (when markdown-enable-math
2992 (when (and (< (1+ (point)) (point-max))
2993 (char-equal (char-after) ?$
)
2994 (char-equal (char-after (1+ (point))) ?$
)
2996 (not (char-equal (char-before) ?
\\))
2997 (not (char-equal (char-before) ?$
)))
2999 (markdown-match-math-generic markdown-regex-math-inline-double last
)))
3001 (defun markdown-match-math-display (last)
3002 "Match bracketed display math \[..\] and \\[..\\] from point to LAST."
3003 (when markdown-enable-math
3004 (markdown-match-math-generic markdown-regex-math-display last
)))
3006 (defun markdown-match-propertized-text (property last
)
3007 "Match text with PROPERTY from point to LAST.
3008 Restore match data previously stored in PROPERTY."
3009 (let ((saved (get-text-property (point) property
))
3012 (setq pos
(next-single-property-change (point) property nil last
))
3013 (unless (= pos last
)
3014 (setq saved
(get-text-property pos property
))))
3016 (set-match-data saved
)
3017 ;; Step at least one character beyond point. Otherwise
3018 ;; `font-lock-fontify-keywords-region' infloops.
3019 (goto-char (min (1+ (max (match-end 0) (point)))
3023 (defun markdown-match-pre-blocks (last)
3024 "Match preformatted blocks from point to LAST.
3025 Use data stored in 'markdown-pre text property during syntax
3027 (markdown-match-propertized-text 'markdown-pre last
))
3029 (defun markdown-match-gfm-code-blocks (last)
3030 "Match GFM quoted code blocks from point to LAST.
3031 Use data stored in 'markdown-gfm-code text property during syntax
3033 (markdown-match-propertized-text 'markdown-gfm-code last
))
3035 (defun markdown-match-gfm-open-code-blocks (last)
3036 (markdown-match-propertized-text 'markdown-gfm-block-begin last
))
3038 (defun markdown-match-gfm-close-code-blocks (last)
3039 (markdown-match-propertized-text 'markdown-gfm-block-end last
))
3041 (defun markdown-match-fenced-code-blocks (last)
3042 "Match fenced code blocks from the point to LAST."
3043 (markdown-match-propertized-text 'markdown-fenced-code last
))
3045 (defun markdown-match-fenced-start-code-block (last)
3046 (markdown-match-propertized-text 'markdown-tilde-fence-begin last
))
3048 (defun markdown-match-fenced-end-code-block (last)
3049 (markdown-match-propertized-text 'markdown-tilde-fence-end last
))
3051 (defun markdown-match-blockquotes (last)
3052 "Match blockquotes from point to LAST.
3053 Use data stored in 'markdown-blockquote text property during syntax
3055 (markdown-match-propertized-text 'markdown-blockquote last
))
3057 (defun markdown-match-hr (last)
3058 "Match horizontal rules comments from the point to LAST."
3059 (markdown-match-propertized-text 'markdown-hr last
))
3061 (defun markdown-match-comments (last)
3062 "Match HTML comments from the point to LAST."
3063 (when (and (skip-syntax-forward "^<" last
))
3064 (let ((beg (point)))
3065 (when (and (skip-syntax-forward "^>" last
) (< (point) last
))
3067 (set-match-data (list beg
(point)))
3070 (defun markdown-match-generic-links (last ref
)
3071 "Match inline links from point to LAST.
3072 When REF is non-nil, match reference links instead of standard
3074 This function should only be used during font-lock, as it
3075 determines syntax based on the presence of faces for previously
3076 processed elements."
3077 ;; Search for the next potential link (not in a code block).
3078 (let ((prohibited-faces '(markdown-pre-face
3080 markdown-inline-code-face
3081 markdown-comment-face
))
3084 (and (not found
) (< (point) last
)
3086 ;; Clear match data to test for a match after functions returns.
3087 (set-match-data nil
)
3088 ;; Preliminary regular expression search so we can return
3089 ;; quickly upon failure. This doesn't handle malformed links
3090 ;; or nested square brackets well, so if it passes we back up
3091 ;; continue with a more precise search.
3094 markdown-regex-link-reference
3095 markdown-regex-link-inline
)
3097 ;; Keep searching if this is in a code block, inline code, or a
3098 ;; comment, or if it is include syntax. The link text portion
3099 ;; (group 3) may contain inline code or comments, but the
3100 ;; markup, URL, and title should not be part of such elements.
3101 (if (or (markdown-range-property-any
3102 (match-beginning 0) (match-end 2) 'face prohibited-faces
)
3103 (markdown-range-property-any
3104 (match-beginning 4) (match-end 0) 'face prohibited-faces
)
3105 (and (char-equal (char-after (point-at-bol)) ?
<)
3106 (char-equal (char-after (1+ (point-at-bol))) ?
<)))
3107 (set-match-data nil
)
3109 ;; Match opening exclamation point (optional) and left bracket.
3110 (when (match-beginning 2)
3111 (let* ((bang (match-beginning 1))
3112 (first-begin (match-beginning 2))
3113 ;; Find end of block to prevent matching across blocks.
3114 (end-of-block (save-excursion
3116 (goto-char (match-beginning 2))
3117 (markdown-end-of-text-block)
3119 ;; Move over balanced expressions to closing right bracket.
3120 ;; Catch unbalanced expression errors and return nil.
3121 (first-end (condition-case nil
3122 (and (goto-char first-begin
)
3123 (scan-sexps (point) 1))
3125 ;; Continue with point at CONT-POINT upon failure.
3126 (cont-point (min (1+ first-begin
) last
))
3127 second-begin second-end url-begin url-end
3128 title-begin title-end
)
3129 ;; When bracket found, in range, and followed by a left paren/bracket...
3130 (when (and first-end
(< first-end end-of-block
) (goto-char first-end
)
3131 (char-equal (char-after (point)) (if ref ?\
[ ?\
()))
3132 ;; Scan across balanced expressions for closing parenthesis/bracket.
3133 (setq second-begin
(point)
3134 second-end
(condition-case nil
3135 (scan-sexps (point) 1)
3137 ;; Check that closing parenthesis/bracket is in range.
3138 (if (and second-end
(<= second-end end-of-block
) (<= second-end last
))
3140 ;; Search for (optional) title inside closing parenthesis
3141 (when (and (not ref
) (search-forward "\"" second-end t
))
3142 (setq title-begin
(1- (point))
3143 title-end
(and (goto-char second-end
)
3144 (search-backward "\"" (1+ title-begin
) t
))
3145 title-end
(and title-end
(1+ title-end
))))
3146 ;; Store URL/reference range
3147 (setq url-begin
(1+ second-begin
)
3148 url-end
(1- (or title-begin second-end
)))
3149 ;; Set match data, move point beyond link, and return
3151 (list (or bang first-begin
) second-end
; 0 - all
3152 bang
(and bang
(1+ bang
)) ; 1 - bang
3153 first-begin
(1+ first-begin
) ; 2 - markup
3154 (1+ first-begin
) (1- first-end
) ; 3 - link text
3155 (1- first-end
) first-end
; 4 - markup
3156 second-begin
(1+ second-begin
) ; 5 - markup
3157 url-begin url-end
; 6 - url/reference
3158 title-begin title-end
; 7 - title
3159 (1- second-end
) second-end
)) ; 8 - markup
3160 ;; Nullify cont-point and leave point at end and
3161 (setq cont-point nil
)
3162 (goto-char second-end
))
3163 ;; If no closing parenthesis in range, update continuation point
3164 (setq cont-point
(min end-of-block second-begin
))))
3166 ;; On failure, continue searching at cont-point
3167 ((and cont-point
(< cont-point last
))
3168 (goto-char cont-point
)
3169 (markdown-match-generic-links last ref
))
3170 ;; No more text, return nil
3171 ((and cont-point
(= cont-point last
))
3173 ;; Return t if a match occurred
3176 (defun markdown-match-angle-uris (last)
3177 "Match angle bracket URIs from point to LAST."
3178 (when (markdown-match-inline-generic markdown-regex-angle-uri last
)
3179 (goto-char (1+ (match-end 0)))))
3181 (defun markdown-match-plain-uris (last)
3182 "Match plain URIs from point to LAST."
3183 (when (markdown-match-inline-generic markdown-regex-uri last t
)
3184 (goto-char (1+ (match-end 0)))))
3186 (defvar markdown-conditional-search-function
#'re-search-forward
3187 "Conditional search function used in `markdown-search-until-condition'.
3188 Made into a variable to allow for dynamic let-binding.")
3190 (defun markdown-search-until-condition (condition &rest args
)
3192 (while (and (not ret
) (apply markdown-conditional-search-function args
))
3193 (setq ret
(funcall condition
)))
3196 (defun markdown-metadata-line-p (pos regexp
)
3198 (or (= (line-number-at-pos pos
) 1)
3201 ;; skip multi-line metadata
3202 (while (and (looking-at-p "^\\s-+[[:alpha:]]")
3203 (> (line-number-at-pos (point)) 1))
3205 (looking-at-p regexp
)))))
3207 (defun markdown-match-generic-metadata (regexp last
)
3208 "Match metadata declarations specified by REGEXP from point to LAST.
3209 These declarations must appear inside a metadata block that begins at
3210 the beginning of the buffer and ends with a blank line (or the end of
3212 (let* ((first (point))
3213 (end-re "\n[ \t]*\n\\|\n\\'\\|\\'")
3214 (block-begin (goto-char 1))
3215 (block-end (re-search-forward end-re nil t
)))
3216 (if (and block-end
(> first block-end
))
3217 ;; Don't match declarations if there is no metadata block or if
3218 ;; the point is beyond the block. Move point to point-max to
3219 ;; prevent additional searches and return return nil since nothing
3221 (progn (goto-char (point-max)) nil
)
3222 ;; If a block was found that begins before LAST and ends after
3223 ;; point, search for declarations inside it. If the starting is
3224 ;; before the beginning of the block, start there. Otherwise,
3225 ;; move back to FIRST.
3226 (goto-char (if (< first block-begin
) block-begin first
))
3227 (if (and (re-search-forward regexp
(min last block-end
) t
)
3228 (markdown-metadata-line-p (point) regexp
))
3229 ;; If a metadata declaration is found, set match-data and return t.
3230 (let ((key-beginning (match-beginning 1))
3231 (key-end (match-end 1))
3232 (markup-begin (match-beginning 2))
3233 (markup-end (match-end 2))
3234 (value-beginning (match-beginning 3)))
3235 (set-match-data (list key-beginning
(point) ; complete metadata
3236 key-beginning key-end
; key
3237 markup-begin markup-end
; markup
3238 value-beginning
(point))) ; value
3240 ;; Otherwise, move the point to last and return nil
3244 (defun markdown-match-declarative-metadata (last)
3245 "Match declarative metadata from the point to LAST."
3246 (markdown-match-generic-metadata markdown-regex-declarative-metadata last
))
3248 (defun markdown-match-pandoc-metadata (last)
3249 "Match Pandoc metadata from the point to LAST."
3250 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last
))
3252 (defun markdown-match-yaml-metadata-begin (last)
3253 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last
))
3255 (defun markdown-match-yaml-metadata-end (last)
3256 (markdown-match-propertized-text 'markdown-yaml-metadata-end last
))
3258 (defun markdown-match-yaml-metadata-key (last)
3259 (markdown-match-propertized-text 'markdown-metadata-key last
))
3261 (defun markdown-match-wiki-link (last)
3262 "Match wiki links from point to LAST."
3263 (when (and markdown-enable-wiki-links
3264 (not markdown-wiki-link-fontify-missing
)
3265 (markdown-match-inline-generic markdown-regex-wiki-link last
))
3266 (let ((begin (match-beginning 1)) (end (match-end 1)))
3267 (if (or (markdown-in-comment-p begin
)
3268 (markdown-in-comment-p end
)
3269 (markdown-inline-code-at-pos-p begin
)
3270 (markdown-inline-code-at-pos-p end
)
3271 (markdown-code-block-at-pos begin
))
3272 (progn (goto-char (min (1+ begin
) last
))
3273 (when (< (point) last
)
3274 (markdown-match-wiki-link last
)))
3275 (set-match-data (list begin end
))
3278 (defun markdown-match-inline-attributes (last)
3279 "Match inline attributes from point to LAST."
3280 ;; #428 re-search-forward markdown-regex-inline-attributes is very slow.
3281 ;; So use simple regex for re-search-forward and use markdown-regex-inline-attributes
3282 ;; against matched string.
3283 (when (markdown-match-inline-generic "[ \t]*\\({\\)\\([^\n]*\\)}[ \t]*$" last
)
3284 (if (not (string-match-p markdown-regex-inline-attributes
(match-string 0)))
3285 (markdown-match-inline-attributes last
)
3286 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
3287 (markdown-inline-code-at-pos-p (match-end 0))
3288 (markdown-in-comment-p))
3291 (defun markdown-match-leanpub-sections (last)
3292 "Match Leanpub section markers from point to LAST."
3293 (when (markdown-match-inline-generic markdown-regex-leanpub-sections last
)
3294 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
3295 (markdown-inline-code-at-pos-p (match-end 0))
3296 (markdown-in-comment-p))
3299 (defun markdown-match-includes (last)
3300 "Match include statements from point to LAST.
3301 Sets match data for the following seven groups:
3302 Group 1: opening two angle brackets
3303 Group 2: opening title delimiter (optional)
3304 Group 3: title text (optional)
3305 Group 4: closing title delimiter (optional)
3306 Group 5: opening filename delimiter
3308 Group 7: closing filename delimiter"
3309 (when (markdown-match-inline-generic markdown-regex-include last
)
3310 (let ((valid (not (or (markdown-in-comment-p (match-beginning 0))
3311 (markdown-in-comment-p (match-end 0))
3312 (markdown-code-block-at-pos (match-beginning 0))))))
3314 ;; Parentheses and maybe square brackets, but no curly braces:
3315 ;; match optional title in square brackets and file in parentheses.
3316 ((and valid
(match-beginning 5)
3317 (not (match-beginning 8)))
3318 (set-match-data (list (match-beginning 1) (match-end 7)
3319 (match-beginning 1) (match-end 1)
3320 (match-beginning 2) (match-end 2)
3321 (match-beginning 3) (match-end 3)
3322 (match-beginning 4) (match-end 4)
3323 (match-beginning 5) (match-end 5)
3324 (match-beginning 6) (match-end 6)
3325 (match-beginning 7) (match-end 7))))
3326 ;; Only square brackets present: match file in square brackets.
3327 ((and valid
(match-beginning 2)
3328 (not (match-beginning 5))
3329 (not (match-beginning 7)))
3330 (set-match-data (list (match-beginning 1) (match-end 4)
3331 (match-beginning 1) (match-end 1)
3335 (match-beginning 2) (match-end 2)
3336 (match-beginning 3) (match-end 3)
3337 (match-beginning 4) (match-end 4))))
3338 ;; Only curly braces present: match file in curly braces.
3339 ((and valid
(match-beginning 8)
3340 (not (match-beginning 2))
3341 (not (match-beginning 5)))
3342 (set-match-data (list (match-beginning 1) (match-end 10)
3343 (match-beginning 1) (match-end 1)
3347 (match-beginning 8) (match-end 8)
3348 (match-beginning 9) (match-end 9)
3349 (match-beginning 10) (match-end 10))))
3351 ;; Not a valid match, move to next line and search again.
3353 (when (< (point) last
)
3354 (setq valid
(markdown-match-includes last
)))))
3357 (defun markdown-match-html-tag (last)
3358 "Match HTML tags from point to LAST."
3359 (when (and markdown-enable-html
3360 (markdown-match-inline-generic markdown-regex-html-tag last t
))
3361 (set-match-data (list (match-beginning 0) (match-end 0)
3362 (match-beginning 1) (match-end 1)
3363 (match-beginning 2) (match-end 2)
3364 (match-beginning 9) (match-end 9)))
3368 ;;; Markdown Font Fontification Functions =====================================
3370 (defvar markdown--first-displayable-cache
(make-hash-table :test
#'equal
))
3372 (defun markdown--first-displayable (seq)
3373 "Return the first displayable character or string in SEQ.
3374 SEQ may be an atom or a sequence."
3375 (let ((c (gethash seq markdown--first-displayable-cache t
)))
3379 (let ((seq (if (listp seq
) seq
(list seq
))))
3380 (cond ((stringp (car seq
))
3383 (and (mapcar #'char-displayable-p
(string-to-list str
))))
3385 ((characterp (car seq
))
3386 (cl-find-if #'char-displayable-p seq
))))
3387 markdown--first-displayable-cache
))))
3389 (defun markdown--marginalize-string (level)
3390 "Generate atx markup string of given LEVEL for left margin."
3391 (let ((margin-left-space-count
3392 (- markdown-marginalize-headers-margin-width level
)))
3393 (concat (make-string margin-left-space-count ?
)
3394 (make-string level ?
#))))
3396 (defun markdown-marginalize-update-current ()
3397 "Update the window configuration to create a left margin."
3399 (let* ((header-delimiter-font-width
3400 (window-font-width nil
'markdown-header-delimiter-face
))
3401 (margin-pixel-width (* markdown-marginalize-headers-margin-width
3402 header-delimiter-font-width
))
3403 (margin-char-width (/ margin-pixel-width
(default-font-width))))
3404 (set-window-margins nil margin-char-width
))
3405 ;; As a fallback, simply set margin based on character count.
3406 (set-window-margins nil
(1+ markdown-marginalize-headers-margin-width
))))
3408 (defun markdown-fontify-headings (last)
3409 "Add text properties to headings from point to LAST."
3410 (when (markdown-match-propertized-text 'markdown-heading last
)
3411 (let* ((level (markdown-outline-level))
3413 (intern (format "markdown-header-face-%d" level
)))
3414 (heading-props `(face ,heading-face
))
3416 `(face markdown-header-delimiter-face
3418 (markdown-hide-markup
3420 (markdown-marginalize-headers
3421 `(display ((margin left-margin
)
3422 ,(markdown--marginalize-string level
)))))))
3424 `(face markdown-header-delimiter-face
3425 ,@(when markdown-hide-markup
`(display ""))))
3426 (rule-props `(face markdown-header-rule-face
3427 ,@(when markdown-hide-markup
`(display "")))))
3430 (progn (add-text-properties
3431 (match-beginning 1) (match-end 1) heading-props
)
3433 (add-text-properties
3434 (match-beginning 2) (match-end 2) rule-props
)
3435 (add-text-properties
3436 (match-beginning 3) (match-end 3) rule-props
)))
3438 (if markdown-fontify-whole-heading-line
3439 (let ((header-end (min (point-max) (1+ (match-end 0)))))
3440 (add-text-properties
3441 (match-beginning 0) header-end heading-props
))
3442 (add-text-properties
3443 (match-beginning 4) (match-end 4) left-markup-props
)
3444 (add-text-properties
3445 (match-beginning 5) (match-end 5) heading-props
)
3447 (add-text-properties
3448 (match-beginning 6) (match-end 6) right-markup-props
)))))
3451 (defun markdown-fontify-tables (last)
3452 (when (re-search-forward "|" last t
)
3453 (when (markdown-table-at-point-p)
3454 (font-lock-append-text-property
3455 (line-beginning-position) (min (1+ (line-end-position)) (point-max))
3456 'face
'markdown-table-face
))
3460 (defun markdown-fontify-blockquotes (last)
3461 "Apply font-lock properties to blockquotes from point to LAST."
3462 (when (markdown-match-blockquotes last
)
3463 (let ((display-string
3464 (markdown--first-displayable markdown-blockquote-display-char
)))
3465 (add-text-properties
3466 (match-beginning 1) (match-end 1)
3467 (if markdown-hide-markup
3468 `(face markdown-blockquote-face display
,display-string
)
3469 `(face markdown-markup-face
)))
3470 (font-lock-append-text-property
3471 (match-beginning 0) (match-end 0) 'face
'markdown-blockquote-face
)
3474 (defun markdown-fontify-list-items (last)
3475 "Apply font-lock properties to list markers from point to LAST."
3476 (when (markdown-match-list-items last
)
3477 (when (not (markdown-code-block-at-point-p (match-beginning 2)))
3478 (let* ((indent (length (match-string-no-properties 1)))
3479 (level (/ indent markdown-list-indent-width
)) ;; level = 0, 1, 2, ...
3480 (bullet (nth (mod level
(length markdown-list-item-bullets
))
3481 markdown-list-item-bullets
)))
3482 (add-text-properties
3483 (match-beginning 2) (match-end 2) '(face markdown-list-face
))
3484 (when markdown-hide-markup
3487 ((string-match-p "[\\*\\+-]" (match-string 2))
3488 (add-text-properties
3489 (match-beginning 2) (match-end 2) `(display ,bullet
)))
3491 ((string-equal ":" (match-string 2))
3492 (let ((display-string
3493 (char-to-string (markdown--first-displayable
3494 markdown-definition-display-char
))))
3495 (add-text-properties (match-beginning 2) (match-end 2)
3496 `(display ,display-string
))))))))
3499 (defun markdown-fontify-hrs (last)
3500 "Add text properties to horizontal rules from point to LAST."
3501 (when (markdown-match-hr last
)
3502 (let ((hr-char (markdown--first-displayable markdown-hr-display-char
)))
3503 (add-text-properties
3504 (match-beginning 0) (match-end 0)
3505 `(face markdown-hr-face
3506 font-lock-multiline t
3507 ,@(when (and markdown-hide-markup hr-char
)
3508 `(display ,(make-string
3509 (1- (window-body-width)) hr-char
)))))
3512 (defun markdown-fontify-sub-superscripts (last)
3513 "Apply text properties to sub- and superscripts from point to LAST."
3514 (when (markdown-search-until-condition
3515 (lambda () (and (not (markdown-code-block-at-point-p))
3516 (not (markdown-inline-code-at-point-p))
3517 (not (markdown-in-comment-p))))
3518 markdown-regex-sub-superscript last t
)
3519 (let* ((subscript-p (string= (match-string 2) "~"))
3522 (car markdown-sub-superscript-display
)
3523 (cdr markdown-sub-superscript-display
)))
3524 (mp (list 'face
'markdown-markup-face
3525 'invisible
'markdown-markup
)))
3526 (when markdown-hide-markup
3527 (put-text-property (match-beginning 3) (match-end 3)
3529 (add-text-properties (match-beginning 2) (match-end 2) mp
)
3530 (add-text-properties (match-beginning 4) (match-end 4) mp
)
3534 ;;; Syntax Table ==============================================================
3536 (defvar markdown-mode-syntax-table
3537 (let ((tab (make-syntax-table text-mode-syntax-table
)))
3538 (modify-syntax-entry ?
\" "." tab
)
3540 "Syntax table for `markdown-mode'.")
3543 ;;; Element Insertion =========================================================
3545 (defun markdown-ensure-blank-line-before ()
3546 "If previous line is not already blank, insert a blank line before point."
3547 (unless (bolp) (insert "\n"))
3548 (unless (or (bobp) (looking-back "\n\\s-*\n" nil
)) (insert "\n")))
3550 (defun markdown-ensure-blank-line-after ()
3551 "If following line is not already blank, insert a blank line after point.
3552 Return the point where it was originally."
3554 (unless (eolp) (insert "\n"))
3555 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
3557 (defun markdown-wrap-or-insert (s1 s2
&optional thing beg end
)
3558 "Insert the strings S1 and S2, wrapping around region or THING.
3559 If a region is specified by the optional BEG and END arguments,
3560 wrap the strings S1 and S2 around that region.
3561 If there is an active region, wrap the strings S1 and S2 around
3562 the region. If there is not an active region but the point is at
3563 THING, wrap that thing (which defaults to word). Otherwise, just
3564 insert S1 and S2 and place the point in between. Return the
3565 bounds of the entire wrapped string, or nil if nothing was wrapped
3566 and S1 and S2 were only inserted."
3567 (let (a b bounds new-point
)
3573 new-point
(+ (point) (length s1
))))
3576 (setq a
(region-beginning)
3578 new-point
(+ (point) (length s1
))))
3579 ;; Thing (word) at point
3580 ((setq bounds
(markdown-bounds-of-thing-at-point (or thing
'word
)))
3581 (setq a
(car bounds
)
3583 new-point
(+ (point) (length s1
))))
3584 ;; No active region and no word
3592 (when new-point
(goto-char new-point
))
3595 (setq b
(+ b
(length s1
) (length s2
)))
3598 (defun markdown-point-after-unwrap (cur prefix suffix
)
3599 "Return desired position of point after an unwrapping operation.
3600 CUR gives the position of the point before the operation.
3601 Additionally, two cons cells must be provided. PREFIX gives the
3602 bounds of the prefix string and SUFFIX gives the bounds of the
3604 (cond ((< cur
(cdr prefix
)) (car prefix
))
3605 ((< cur
(car suffix
)) (- cur
(- (cdr prefix
) (car prefix
))))
3606 ((<= cur
(cdr suffix
))
3607 (- cur
(+ (- (cdr prefix
) (car prefix
))
3608 (- cur
(car suffix
)))))
3611 (defun markdown-unwrap-thing-at-point (regexp all text
)
3612 "Remove prefix and suffix of thing at point and reposition the point.
3613 When the thing at point matches REGEXP, replace the subexpression
3614 ALL with the string in subexpression TEXT. Reposition the point
3615 in an appropriate location accounting for the removal of prefix
3616 and suffix strings. Return new bounds of string from group TEXT.
3617 When REGEXP is nil, assumes match data is already set."
3618 (when (or (null regexp
)
3619 (thing-at-point-looking-at regexp
))
3621 (prefix (cons (match-beginning all
) (match-beginning text
)))
3622 (suffix (cons (match-end text
) (match-end all
)))
3623 (bounds (cons (match-beginning text
) (match-end text
))))
3624 ;; Replace the thing at point
3625 (replace-match (match-string text
) t t nil all
)
3626 ;; Reposition the point
3627 (goto-char (markdown-point-after-unwrap cur prefix suffix
))
3629 (setq bounds
(cons (car prefix
)
3630 (- (cdr bounds
) (- (cdr prefix
) (car prefix
))))))))
3632 (defun markdown-unwrap-things-in-region (beg end regexp all text
)
3633 "Remove prefix and suffix of all things in region from BEG to END.
3634 When a thing in the region matches REGEXP, replace the
3635 subexpression ALL with the string in subexpression TEXT.
3636 Return a cons cell containing updated bounds for the region."
3639 (let ((removed 0) len-all len-text
)
3640 (while (re-search-forward regexp
(- end removed
) t
)
3641 (setq len-all
(length (match-string-no-properties all
)))
3642 (setq len-text
(length (match-string-no-properties text
)))
3643 (setq removed
(+ removed
(- len-all len-text
)))
3644 (replace-match (match-string text
) t t nil all
))
3645 (cons beg
(- end removed
)))))
3647 (defun markdown-insert-hr (arg)
3648 "Insert or replace a horizontal rule.
3649 By default, use the first element of `markdown-hr-strings'. When
3650 ARG is non-nil, as when given a prefix, select a different
3651 element as follows. When prefixed with \\[universal-argument],
3652 use the last element of `markdown-hr-strings' instead. When
3653 prefixed with an integer from 1 to the length of
3654 `markdown-hr-strings', use the element in that position instead."
3656 (when (thing-at-point-looking-at markdown-regex-hr
)
3657 (delete-region (match-beginning 0) (match-end 0)))
3658 (markdown-ensure-blank-line-before)
3659 (cond ((equal arg
'(4))
3660 (insert (car (reverse markdown-hr-strings
))))
3661 ((and (integerp arg
) (> arg
0)
3662 (<= arg
(length markdown-hr-strings
)))
3663 (insert (nth (1- arg
) markdown-hr-strings
)))
3665 (insert (car markdown-hr-strings
))))
3666 (markdown-ensure-blank-line-after))
3668 (defun markdown--insert-common (start-delim end-delim regex start-group end-group face
3669 &optional skip-space
)
3672 (let* ((bounds (markdown-unwrap-things-in-region
3673 (region-beginning) (region-end)
3674 regex start-group end-group
))
3677 (when (and beg skip-space
)
3680 (skip-chars-forward "[ \t]")
3681 (setq beg
(point))))
3682 (when (and end skip-space
)
3685 (skip-chars-backward "[ \t]")
3686 (setq end
(point))))
3687 (markdown-wrap-or-insert start-delim end-delim nil beg end
))
3688 (if (markdown--face-p (point) (list face
))
3690 (while (and (markdown--face-p (point) (list face
)) (not (bobp)))
3692 (forward-char (- (1- (length start-delim
)))) ;; for delimiter
3695 (when (looking-at regex
)
3696 (markdown-unwrap-thing-at-point nil start-group end-group
)))
3697 (if (thing-at-point-looking-at regex
)
3698 (markdown-unwrap-thing-at-point nil start-group end-group
)
3699 (markdown-wrap-or-insert start-delim end-delim
'word nil nil
)))))
3701 (defun markdown-insert-bold ()
3702 "Insert markup to make a region or word bold.
3703 If there is an active region, make the region bold. If the point
3704 is at a non-bold word, make the word bold. If the point is at a
3705 bold word or phrase, remove the bold markup. Otherwise, simply
3706 insert bold delimiters and place the point in between them."
3708 (let ((delim (if markdown-bold-underscore
"__" "**")))
3709 (markdown--insert-common delim delim markdown-regex-bold
2 4 'markdown-bold-face t
)))
3711 (defun markdown-insert-italic ()
3712 "Insert markup to make a region or word italic.
3713 If there is an active region, make the region italic. If the point
3714 is at a non-italic word, make the word italic. If the point is at an
3715 italic word or phrase, remove the italic markup. Otherwise, simply
3716 insert italic delimiters and place the point in between them."
3718 (let ((delim (if markdown-italic-underscore
"_" "*")))
3719 (markdown--insert-common delim delim markdown-regex-italic
1 3 'markdown-italic-face t
)))
3721 (defun markdown-insert-strike-through ()
3722 "Insert markup to make a region or word strikethrough.
3723 If there is an active region, make the region strikethrough. If the point
3724 is at a non-bold word, make the word strikethrough. If the point is at a
3725 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
3726 simply insert bold delimiters and place the point in between them."
3728 (markdown--insert-common
3729 "~~" "~~" markdown-regex-strike-through
2 4 'markdown-strike-through-face t
))
3731 (defun markdown-insert-code ()
3732 "Insert markup to make a region or word an inline code fragment.
3733 If there is an active region, make the region an inline code
3734 fragment. If the point is at a word, make the word an inline
3735 code fragment. Otherwise, simply insert code delimiters and
3736 place the point in between them."
3740 (let ((bounds (markdown-unwrap-things-in-region
3741 (region-beginning) (region-end)
3742 markdown-regex-code
1 3)))
3743 (markdown-wrap-or-insert "`" "`" nil
(car bounds
) (cdr bounds
)))
3744 ;; Code markup removal, code markup for word, or empty markup insertion
3745 (if (markdown-inline-code-at-point)
3746 (markdown-unwrap-thing-at-point nil
0 2)
3747 (markdown-wrap-or-insert "`" "`" 'word nil nil
))))
3749 (defun markdown-insert-kbd ()
3750 "Insert markup to wrap region or word in <kbd> tags.
3751 If there is an active region, use the region. If the point is at
3752 a word, use the word. Otherwise, simply insert <kbd> tags and
3753 place the point in between them."
3757 (let ((bounds (markdown-unwrap-things-in-region
3758 (region-beginning) (region-end)
3759 markdown-regex-kbd
0 2)))
3760 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil
(car bounds
) (cdr bounds
)))
3761 ;; Markup removal, markup for word, or empty markup insertion
3762 (if (thing-at-point-looking-at markdown-regex-kbd
)
3763 (markdown-unwrap-thing-at-point nil
0 2)
3764 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil
))))
3766 (defun markdown-insert-inline-link (text url
&optional title
)
3767 "Insert an inline link with TEXT pointing to URL.
3768 Optionally, the user can provide a TITLE."
3769 (let ((cur (point)))
3770 (setq title
(and title
(concat " \"" title
"\"")))
3771 (insert (concat "[" text
"](" url title
")"))
3772 (cond ((not text
) (goto-char (+ 1 cur
)))
3773 ((not url
) (goto-char (+ 3 (length text
) cur
))))))
3775 (defun markdown-insert-inline-image (text url
&optional title
)
3776 "Insert an inline link with alt TEXT pointing to URL.
3777 Optionally, also provide a TITLE."
3778 (let ((cur (point)))
3779 (setq title
(and title
(concat " \"" title
"\"")))
3780 (insert (concat "![" text
"](" url title
")"))
3781 (cond ((not text
) (goto-char (+ 2 cur
)))
3782 ((not url
) (goto-char (+ 4 (length text
) cur
))))))
3784 (defun markdown-insert-reference-link (text label
&optional url title
)
3785 "Insert a reference link and, optionally, a reference definition.
3786 The link TEXT will be inserted followed by the optional LABEL.
3787 If a URL is given, also insert a definition for the reference
3788 LABEL according to `markdown-reference-location'. If a TITLE is
3789 given, it will be added to the end of the reference definition
3790 and will be used to populate the title attribute when converted
3791 to XHTML. If URL is nil, insert only the link portion (for
3792 example, when a reference label is already defined)."
3793 (insert (concat "[" text
"][" label
"]"))
3795 (markdown-insert-reference-definition
3796 (if (string-equal label
"") text label
)
3799 (defun markdown-insert-reference-image (text label
&optional url title
)
3800 "Insert a reference image and, optionally, a reference definition.
3801 The alt TEXT will be inserted followed by the optional LABEL.
3802 If a URL is given, also insert a definition for the reference
3803 LABEL according to `markdown-reference-location'. If a TITLE is
3804 given, it will be added to the end of the reference definition
3805 and will be used to populate the title attribute when converted
3806 to XHTML. If URL is nil, insert only the link portion (for
3807 example, when a reference label is already defined)."
3808 (insert (concat "![" text
"][" label
"]"))
3810 (markdown-insert-reference-definition
3811 (if (string-equal label
"") text label
)
3814 (defun markdown-insert-reference-definition (label &optional url title
)
3815 "Add definition for reference LABEL with URL and TITLE.
3816 LABEL is a Markdown reference label without square brackets.
3817 URL and TITLE are optional. When given, the TITLE will
3818 be used to populate the title attribute when converted to XHTML."
3819 ;; END specifies where to leave the point upon return
3820 (let ((end (point)))
3821 (cl-case markdown-reference-location
3822 (end (goto-char (point-max)))
3823 (immediately (markdown-end-of-text-block))
3824 (subtree (markdown-end-of-subtree))
3825 (header (markdown-end-of-defun)))
3826 ;; Skip backwards over local variables. This logic is similar to the one
3827 ;; used in ‘hack-local-variables’.
3828 (when (and enable-local-variables
(eobp))
3829 (search-backward "\n\f" (max (- (point) 3000) (point-min)) :move
)
3830 (when (let ((case-fold-search t
))
3831 (search-forward "Local Variables:" nil
:move
))
3832 (beginning-of-line 0)
3833 (when (eq (char-before) ?
\n) (backward-char))))
3834 (unless (or (markdown-cur-line-blank-p)
3835 (thing-at-point-looking-at markdown-regex-reference-definition
))
3837 (insert "\n[" label
"]: ")
3840 ;; When no URL is given, leave point at END following the colon
3842 (when (> (length title
) 0)
3843 (insert " \"" title
"\""))
3844 (unless (looking-at-p "\n")
3849 (markdown--substitute-command-keys
3850 "Reference [%s] was defined, press \\[markdown-do] to jump there")
3853 (defcustom markdown-link-make-text-function nil
3854 "Function that automatically generates a link text for a URL.
3856 If non-nil, this function will be called by
3857 `markdown--insert-link-or-image' and the result will be the
3858 default link text. The function should receive exactly one
3859 argument that corresponds to the link URL."
3862 :package-version
'(markdown-mode .
"2.5"))
3864 (defcustom markdown-disable-tooltip-prompt nil
3865 "Disable prompt for tooltip when inserting a link or image.
3867 If non-nil, `markdown-insert-link' and `markdown-insert-link'
3868 will not prompt the user to insert a tooltip text for the given
3873 :package-version
'(markdown-mode .
"2.5"))
3875 (defun markdown--insert-link-or-image (image)
3876 "Interactively insert new or update an existing link or image.
3877 When IMAGE is non-nil, insert an image. Otherwise, insert a link.
3878 This is an internal function called by
3879 `markdown-insert-link' and `markdown-insert-image'."
3880 (cl-multiple-value-bind (begin end text uri ref title
)
3882 ;; Use region as either link text or URL as appropriate.
3883 (let ((region (buffer-substring-no-properties
3884 (region-beginning) (region-end))))
3885 (if (string-match markdown-regex-uri region
)
3886 ;; Region contains a URL; use it as such.
3887 (list (region-beginning) (region-end)
3888 nil
(match-string 0 region
) nil nil
)
3889 ;; Region doesn't contain a URL, so use it as text.
3890 (list (region-beginning) (region-end)
3891 region nil nil nil
)))
3892 ;; Extract and use properties of existing link, if any.
3893 (markdown-link-at-pos (point)))
3894 (let* ((ref (when ref
(concat "[" ref
"]")))
3895 (defined-refs (mapcar #'car
(markdown-get-defined-references)))
3896 (defined-ref-cands (mapcar (lambda (ref) (concat "[" ref
"]")) defined-refs
))
3897 (used-uris (markdown-get-used-uris))
3898 (uri-or-ref (completing-read
3899 "URL or [reference]: "
3900 (append defined-ref-cands used-uris
)
3901 nil nil
(or uri ref
)))
3902 (ref (cond ((string-match "\\`\\[\\(.*\\)\\]\\'" uri-or-ref
)
3903 (match-string 1 uri-or-ref
))
3904 ((string-equal "" uri-or-ref
)
3906 (uri (unless ref uri-or-ref
))
3907 (text-prompt (if image
3911 "Link text (blank for plain URL): ")))
3912 (text (or text
(and markdown-link-make-text-function uri
3913 (funcall markdown-link-make-text-function uri
))))
3914 (text (completing-read text-prompt defined-refs nil nil text
))
3915 (text (if (= (length text
) 0) nil text
))
3916 (plainp (and uri
(not text
)))
3917 (implicitp (string-equal ref
""))
3918 (ref (if implicitp text ref
))
3919 (definedp (and ref
(markdown-reference-definition ref
)))
3920 (ref-url (unless (or uri definedp
)
3921 (completing-read "Reference URL: " used-uris
)))
3922 (title (unless (or plainp definedp markdown-disable-tooltip-prompt
)
3923 (read-string "Title (tooltip text, optional): " title
)))
3924 (title (if (= (length title
) 0) nil title
)))
3925 (when (and image implicitp
)
3926 (user-error "Reference required: implicit image references are invalid"))
3927 (when (and begin end
)
3928 (delete-region begin end
))
3930 ((and (not image
) uri text
)
3931 (markdown-insert-inline-link text uri title
))
3932 ((and image uri text
)
3933 (markdown-insert-inline-image text uri title
))
3936 (markdown-insert-reference-image text
(unless implicitp ref
) nil title
)
3937 (markdown-insert-reference-link text
(unless implicitp ref
) nil title
))
3939 (markdown-insert-reference-definition ref ref-url title
)))
3940 ((and (not image
) uri
)
3941 (markdown-insert-uri uri
))))))
3943 (defun markdown-insert-link ()
3944 "Insert new or update an existing link, with interactive prompt.
3945 If the point is at an existing link or URL, update the link text,
3946 URL, reference label, and/or title. Otherwise, insert a new link.
3947 The type of link inserted (inline, reference, or plain URL)
3948 depends on which values are provided:
3950 * If a URL and TEXT are given, insert an inline link: [TEXT](URL).
3951 * If [REF] and TEXT are given, insert a reference link: [TEXT][REF].
3952 * If only TEXT is given, insert an implicit reference link: [TEXT][].
3953 * If only a URL is given, insert a plain link: <URL>.
3955 In other words, to create an implicit reference link, leave the
3956 URL prompt empty and to create a plain URL link, leave the link
3959 If there is an active region, use the text as the default URL, if
3960 it seems to be a URL, or link text value otherwise.
3962 If a given reference is not defined, this function will
3963 additionally prompt for the URL and optional title. In this case,
3964 the reference definition is placed at the location determined by
3965 `markdown-reference-location'. In addition, it is possible to
3966 have the `markdown-link-make-text-function' function, if non-nil,
3967 define the default link text before prompting the user for it.
3969 If `markdown-disable-tooltip-prompt' is non-nil, the user will
3970 not be prompted to add or modify a tooltip text.
3972 Through updating the link, this function can be used to convert a
3973 link of one type (inline, reference, or plain) to another type by
3974 selectively adding or removing information via the prompts."
3976 (markdown--insert-link-or-image nil
))
3978 (defun markdown-insert-image ()
3979 "Insert new or update an existing image, with interactive prompt.
3980 If the point is at an existing image, update the alt text, URL,
3981 reference label, and/or title. Otherwise, insert a new image.
3982 The type of image inserted (inline or reference) depends on which
3983 values are provided:
3985 * If a URL and ALT-TEXT are given, insert an inline image:
3987 * If [REF] and ALT-TEXT are given, insert a reference image:
3990 If there is an active region, use the text as the default URL, if
3991 it seems to be a URL, or alt text value otherwise.
3993 If a given reference is not defined, this function will
3994 additionally prompt for the URL and optional title. In this case,
3995 the reference definition is placed at the location determined by
3996 `markdown-reference-location'.
3998 Through updating the image, this function can be used to convert an
3999 image of one type (inline or reference) to another type by
4000 selectively adding or removing information via the prompts."
4002 (markdown--insert-link-or-image t
))
4004 (defun markdown-insert-uri (&optional uri
)
4005 "Insert markup for an inline URI.
4006 If there is an active region, use it as the URI. If the point is
4007 at a URI, wrap it with angle brackets. If the point is at an
4008 inline URI, remove the angle brackets. Otherwise, simply insert
4009 angle brackets place the point between them."
4013 (let ((bounds (markdown-unwrap-things-in-region
4014 (region-beginning) (region-end)
4015 markdown-regex-angle-uri
0 2)))
4016 (markdown-wrap-or-insert "<" ">" nil
(car bounds
) (cdr bounds
)))
4017 ;; Markup removal, URI at point, new URI, or empty markup insertion
4018 (if (thing-at-point-looking-at markdown-regex-angle-uri
)
4019 (markdown-unwrap-thing-at-point nil
0 2)
4021 (insert "<" uri
">")
4022 (markdown-wrap-or-insert "<" ">" 'url nil nil
)))))
4024 (defun markdown-insert-wiki-link ()
4025 "Insert a wiki link of the form [[WikiLink]].
4026 If there is an active region, use the region as the link text.
4027 If the point is at a word, use the word as the link text. If
4028 there is no active region and the point is not at word, simply
4029 insert link markup."
4033 (markdown-wrap-or-insert "[[" "]]" nil
(region-beginning) (region-end))
4034 ;; Markup removal, wiki link at at point, or empty markup insertion
4035 (if (thing-at-point-looking-at markdown-regex-wiki-link
)
4036 (if (or markdown-wiki-link-alias-first
4037 (null (match-string 5)))
4038 (markdown-unwrap-thing-at-point nil
1 3)
4039 (markdown-unwrap-thing-at-point nil
1 5))
4040 (markdown-wrap-or-insert "[[" "]]"))))
4042 (defun markdown-remove-header ()
4043 "Remove header markup if point is at a header.
4044 Return bounds of remaining header text if a header was removed
4047 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx
0 2)
4048 (markdown-unwrap-thing-at-point markdown-regex-header-setext
0 1)))
4050 (defun markdown-insert-header (&optional level text setext
)
4051 "Insert or replace header markup.
4052 The level of the header is specified by LEVEL and header text is
4053 given by TEXT. LEVEL must be an integer from 1 and 6, and the
4055 When TEXT is nil, the header text is obtained as follows.
4056 If there is an active region, it is used as the header text.
4057 Otherwise, the current line will be used as the header text.
4058 If there is not an active region and the point is at a header,
4059 remove the header markup and replace with level N header.
4060 Otherwise, insert empty header markup and place the point in
4062 The style of the header will be atx (hash marks) unless
4063 SETEXT is non-nil, in which case a setext-style (underlined)
4064 header will be inserted."
4065 (interactive "p\nsHeader text: ")
4066 (setq level
(min (max (or level
1) 1) (if setext
2 6)))
4067 ;; Determine header text if not given
4071 (setq text
(delete-and-extract-region (region-beginning) (region-end)))
4073 (markdown-remove-header)
4074 (setq text
(delete-and-extract-region
4075 (line-beginning-position) (line-end-position)))
4076 (when (and setext
(string-match-p "^[ \t]*$" text
))
4077 (setq text
(read-string "Header text: "))))
4078 (setq text
(markdown-compress-whitespace-string text
)))
4079 ;; Insertion with given text
4080 (markdown-ensure-blank-line-before)
4083 (setq hdr
(make-string (string-width text
) (if (= level
2) ?- ?
=)))
4084 (insert text
"\n" hdr
))
4086 (setq hdr
(make-string level ?
#))
4087 (insert hdr
" " text
)
4088 (when (null markdown-asymmetric-header
) (insert " " hdr
)))))
4089 (markdown-ensure-blank-line-after)
4090 ;; Leave point at end of text
4092 (backward-char (1+ (string-width text
))))
4093 ((null markdown-asymmetric-header
)
4094 (backward-char (1+ level
)))))
4096 (defun markdown-insert-header-dwim (&optional arg setext
)
4097 "Insert or replace header markup.
4098 The level and type of the header are determined automatically by
4099 the type and level of the previous header, unless a prefix
4100 argument is given via ARG.
4101 With a numeric prefix valued 1 to 6, insert a header of the given
4102 level, with the type being determined automatically (note that
4103 only level 1 or 2 setext headers are possible).
4105 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
4106 promote the heading by one level.
4107 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
4108 demote the heading by one level.
4109 When SETEXT is non-nil, prefer setext-style headers when
4110 possible (levels one and two).
4112 When there is an active region, use it for the header text. When
4113 the point is at an existing header, change the type and level
4114 according to the rules above.
4115 Otherwise, if the line is not empty, create a header using the
4116 text on the current line as the header text.
4117 Finally, if the point is on a blank line, insert empty header
4118 markup (atx) or prompt for text (setext).
4119 See `markdown-insert-header' for more details about how the
4120 header text is determined."
4124 (when (or (thing-at-point-looking-at markdown-regex-header
)
4125 (re-search-backward markdown-regex-header nil t
))
4126 ;; level of current or previous header
4127 (setq level
(markdown-outline-level))
4128 ;; match group 1 indicates a setext header
4129 (setq setext
(match-end 1))))
4130 ;; check prefix argument
4132 ((and (equal arg
'(4)) level
(> level
1)) ;; C-u
4134 ((and (equal arg
'(16)) level
(< level
6)) ;; C-u C-u
4136 (arg ;; numeric prefix
4137 (setq level
(prefix-numeric-value arg
))))
4138 ;; setext headers must be level one or two
4139 (and level
(setq setext
(and setext
(<= level
2))))
4140 ;; insert the heading
4141 (markdown-insert-header level nil setext
)))
4143 (defun markdown-insert-header-setext-dwim (&optional arg
)
4144 "Insert or replace header markup, with preference for setext.
4145 See `markdown-insert-header-dwim' for details, including how ARG is handled."
4147 (markdown-insert-header-dwim arg t
))
4149 (defun markdown-insert-header-atx-1 ()
4150 "Insert a first level atx-style (hash mark) header.
4151 See `markdown-insert-header'."
4153 (markdown-insert-header 1 nil nil
))
4155 (defun markdown-insert-header-atx-2 ()
4156 "Insert a level two atx-style (hash mark) header.
4157 See `markdown-insert-header'."
4159 (markdown-insert-header 2 nil nil
))
4161 (defun markdown-insert-header-atx-3 ()
4162 "Insert a level three atx-style (hash mark) header.
4163 See `markdown-insert-header'."
4165 (markdown-insert-header 3 nil nil
))
4167 (defun markdown-insert-header-atx-4 ()
4168 "Insert a level four atx-style (hash mark) header.
4169 See `markdown-insert-header'."
4171 (markdown-insert-header 4 nil nil
))
4173 (defun markdown-insert-header-atx-5 ()
4174 "Insert a level five atx-style (hash mark) header.
4175 See `markdown-insert-header'."
4177 (markdown-insert-header 5 nil nil
))
4179 (defun markdown-insert-header-atx-6 ()
4180 "Insert a sixth level atx-style (hash mark) header.
4181 See `markdown-insert-header'."
4183 (markdown-insert-header 6 nil nil
))
4185 (defun markdown-insert-header-setext-1 ()
4186 "Insert a setext-style (underlined) first-level header.
4187 See `markdown-insert-header'."
4189 (markdown-insert-header 1 nil t
))
4191 (defun markdown-insert-header-setext-2 ()
4192 "Insert a setext-style (underlined) second-level header.
4193 See `markdown-insert-header'."
4195 (markdown-insert-header 2 nil t
))
4197 (defun markdown-blockquote-indentation (loc)
4198 "Return string containing necessary indentation for a blockquote at LOC.
4199 Also see `markdown-pre-indentation'."
4202 (let* ((list-level (length (markdown-calculate-list-levels)))
4204 (dotimes (_ list-level indent
)
4205 (setq indent
(concat indent
" "))))))
4207 (defun markdown-insert-blockquote ()
4208 "Start a blockquote section (or blockquote the region).
4209 If Transient Mark mode is on and a region is active, it is used as
4210 the blockquote text."
4213 (markdown-blockquote-region (region-beginning) (region-end))
4214 (markdown-ensure-blank-line-before)
4215 (insert (markdown-blockquote-indentation (point)) "> ")
4216 (markdown-ensure-blank-line-after)))
4218 (defun markdown-block-region (beg end prefix
)
4219 "Format the region using a block prefix.
4220 Arguments BEG and END specify the beginning and end of the
4221 region. The characters PREFIX will appear at the beginning
4224 (let* ((end-marker (make-marker))
4225 (beg-marker (make-marker))
4226 (prefix-without-trailing-whitespace
4227 (replace-regexp-in-string (rx (+ blank
) eos
) "" prefix
)))
4228 ;; Ensure blank line after and remove extra whitespace
4230 (skip-syntax-backward "-")
4231 (set-marker end-marker
(point))
4232 (delete-horizontal-space)
4233 (markdown-ensure-blank-line-after)
4234 ;; Ensure blank line before and remove extra whitespace
4236 (skip-syntax-forward "-")
4237 (delete-horizontal-space)
4238 (markdown-ensure-blank-line-before)
4239 (set-marker beg-marker
(point))
4240 ;; Insert PREFIX before each line
4241 (goto-char beg-marker
)
4242 (while (and (< (line-beginning-position) end-marker
)
4244 ;; Don’t insert trailing whitespace.
4245 (insert (if (eolp) prefix-without-trailing-whitespace prefix
))
4248 (defun markdown-blockquote-region (beg end
)
4249 "Blockquote the region.
4250 Arguments BEG and END specify the beginning and end of the region."
4252 (markdown-block-region
4253 beg end
(concat (markdown-blockquote-indentation
4254 (max (point-min) (1- beg
))) "> ")))
4256 (defun markdown-pre-indentation (loc)
4257 "Return string containing necessary whitespace for a pre block at LOC.
4258 Also see `markdown-blockquote-indentation'."
4261 (let* ((list-level (length (markdown-calculate-list-levels)))
4263 (dotimes (_ (1+ list-level
) indent
)
4264 (setq indent
(concat indent
" "))))))
4266 (defun markdown-insert-pre ()
4267 "Start a preformatted section (or apply to the region).
4268 If Transient Mark mode is on and a region is active, it is marked
4269 as preformatted text."
4272 (markdown-pre-region (region-beginning) (region-end))
4273 (markdown-ensure-blank-line-before)
4274 (insert (markdown-pre-indentation (point)))
4275 (markdown-ensure-blank-line-after)))
4277 (defun markdown-pre-region (beg end
)
4278 "Format the region as preformatted text.
4279 Arguments BEG and END specify the beginning and end of the region."
4281 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg
)))))
4282 (markdown-block-region beg end indent
)))
4284 (defun markdown-electric-backquote (arg)
4285 "Insert a backquote.
4286 The numeric prefix argument ARG says how many times to repeat the insertion.
4287 Call `markdown-insert-gfm-code-block' interactively
4288 if three backquotes inserted at the beginning of line."
4290 (self-insert-command (prefix-numeric-value arg
))
4291 (when (and markdown-gfm-use-electric-backquote
(looking-back "^```" nil
))
4293 (call-interactively #'markdown-insert-gfm-code-block
)))
4295 (defconst markdown-gfm-recognized-languages
4296 ;; To reproduce/update, evaluate the let-form in
4297 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
4298 ;; but with appropriate use of a keyboard macro, indenting and filling it
4299 ;; properly is pretty fast.
4300 '("1C-Enterprise" "4D" "ABAP" "ABNF" "AGS-Script" "AMPL" "ANTLR"
4301 "API-Blueprint" "APL" "ASN.1" "ASP" "ATS" "ActionScript" "Ada"
4302 "Adobe-Font-Metrics" "Agda" "Alloy" "Alpine-Abuild" "Altium-Designer"
4303 "AngelScript" "Ant-Build-System" "ApacheConf" "Apex"
4304 "Apollo-Guidance-Computer" "AppleScript" "Arc" "AsciiDoc" "AspectJ" "Assembly"
4305 "Asymptote" "Augeas" "AutoHotkey" "AutoIt" "Awk" "Ballerina" "Batchfile"
4306 "Befunge" "BibTeX" "Bison" "BitBake" "Blade" "BlitzBasic" "BlitzMax"
4307 "Bluespec" "Boo" "Brainfuck" "Brightscript" "C#" "C++" "C-ObjDump"
4308 "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "COLLADA" "CSON" "CSS" "CSV" "CWeb"
4309 "Cabal-Config" "Cap'n-Proto" "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK"
4310 "Cirru" "Clarion" "Clean" "Click" "Clojure" "Closure-Templates"
4311 "Cloud-Firestore-Security-Rules" "CoNLL-U" "CodeQL" "CoffeeScript"
4312 "ColdFusion" "ColdFusion-CFC" "Common-Lisp" "Common-Workflow-Language"
4313 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal" "Csound"
4314 "Csound-Document" "Csound-Score" "Cuda" "Cycript" "Cython" "D-ObjDump"
4315 "DIGITAL-Command-Language" "DM" "DNS-Zone" "DTrace" "Dafny" "Darcs-Patch"
4316 "Dart" "DataWeave" "Dhall" "Diff" "DirectX-3D-File" "Dockerfile" "Dogescript"
4317 "Dylan" "EBNF" "ECL" "ECLiPSe" "EJS" "EML" "EQ" "Eagle" "Easybuild"
4318 "Ecere-Projects" "EditorConfig" "Edje-Data-Collection" "Eiffel" "Elixir" "Elm"
4319 "Emacs-Lisp" "EmberScript" "Erlang" "F#" "F*" "FIGlet-Font" "FLUX" "Factor"
4320 "Fancy" "Fantom" "Faust" "Filebench-WML" "Filterscript" "Formatted" "Forth"
4321 "Fortran" "Fortran-Free-Form" "FreeMarker" "Frege" "G-code" "GAML" "GAMS"
4322 "GAP" "GCC-Machine-Description" "GDB" "GDScript" "GEDCOM" "GLSL" "GN"
4323 "Game-Maker-Language" "Genie" "Genshi" "Gentoo-Ebuild" "Gentoo-Eclass"
4324 "Gerber-Image" "Gettext-Catalog" "Gherkin" "Git-Attributes" "Git-Config"
4325 "Glyph" "Glyph-Bitmap-Distribution-Format" "Gnuplot" "Go" "Golo" "Gosu"
4326 "Grace" "Gradle" "Grammatical-Framework" "Graph-Modeling-Language" "GraphQL"
4327 "Graphviz-(DOT)" "Groovy" "Groovy-Server-Pages" "HAProxy" "HCL" "HLSL" "HTML"
4328 "HTML+Django" "HTML+ECR" "HTML+EEX" "HTML+ERB" "HTML+PHP" "HTML+Razor" "HTTP"
4329 "HXML" "Hack" "Haml" "Handlebars" "Harbour" "Haskell" "Haxe" "HiveQL" "HolyC"
4330 "Hy" "HyPhy" "IDL" "IGOR-Pro" "INI" "IRC-log" "Idris" "Ignore-List" "Inform-7"
4331 "Inno-Setup" "Io" "Ioke" "Isabelle" "Isabelle-ROOT" "JFlex" "JSON"
4332 "JSON-with-Comments" "JSON5" "JSONLD" "JSONiq" "JSX" "Jasmin" "Java"
4333 "Java-Properties" "Java-Server-Pages" "JavaScript" "JavaScript+ERB" "Jison"
4334 "Jison-Lex" "Jolie" "Jsonnet" "Julia" "Jupyter-Notebook" "KRL" "KiCad-Layout"
4335 "KiCad-Legacy-Layout" "KiCad-Schematic" "Kit" "Kotlin" "LFE" "LLVM" "LOLCODE"
4336 "LSL" "LTspice-Symbol" "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex"
4337 "LilyPond" "Limbo" "Linker-Script" "Linux-Kernel-Module" "Liquid"
4338 "Literate-Agda" "Literate-CoffeeScript" "Literate-Haskell" "LiveScript"
4339 "Logos" "Logtalk" "LookML" "LoomScript" "Lua" "M4" "M4Sugar" "MATLAB"
4340 "MAXScript" "MLIR" "MQL4" "MQL5" "MTML" "MUF" "Macaulay2" "Makefile" "Mako"
4341 "Markdown" "Marko" "Mask" "Mathematica" "Maven-POM" "Max" "MediaWiki"
4342 "Mercury" "Meson" "Metal" "Microsoft-Developer-Studio-Project" "MiniD" "Mirah"
4343 "Modelica" "Modula-2" "Modula-3" "Module-Management-System" "Monkey" "Moocode"
4344 "MoonScript" "Motorola-68K-Assembly" "Muse" "Myghty" "NASL" "NCL" "NEON" "NL"
4345 "NPM-Config" "NSIS" "Nearley" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo"
4346 "NewLisp" "Nextflow" "Nginx" "Nim" "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml"
4347 "ObjDump" "Object-Data-Instance-Notation" "ObjectScript" "Objective-C"
4348 "Objective-C++" "Objective-J" "Odin" "Omgrofl" "Opa" "Opal"
4349 "Open-Policy-Agent" "OpenCL" "OpenEdge-ABL" "OpenQASM" "OpenRC-runscript"
4350 "OpenSCAD" "OpenStep-Property-List" "OpenType-Feature-File" "Org" "Ox"
4351 "Oxygene" "Oz" "P4" "PHP" "PLSQL" "PLpgSQL" "POV-Ray-SDL" "Pan" "Papyrus"
4352 "Parrot" "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal" "Pawn"
4353 "Pep8" "Perl" "Pic" "Pickle" "PicoLisp" "PigLatin" "Pike" "PlantUML" "Pod"
4354 "Pod-6" "PogoScript" "Pony" "PostCSS" "PostScript" "PowerBuilder" "PowerShell"
4355 "Prisma" "Processing" "Proguard" "Prolog" "Propeller-Spin" "Protocol-Buffer"
4356 "Public-Key" "Pug" "Puppet" "Pure-Data" "PureBasic" "PureScript" "Python"
4357 "Python-console" "Python-traceback" "QML" "QMake" "Quake" "RAML" "RDoc"
4358 "REALbasic" "REXX" "RHTML" "RMarkdown" "RPC" "RPM-Spec" "RUNOFF" "Racket"
4359 "Ragel" "Raku" "Rascal" "Raw-token-data" "Readline-Config" "Reason" "Rebol"
4360 "Red" "Redcode" "Regular-Expression" "Ren'Py" "RenderScript"
4361 "Rich-Text-Format" "Ring" "Riot" "RobotFramework" "Roff" "Roff-Manpage"
4362 "Rouge" "Ruby" "Rust" "SAS" "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL"
4363 "SRecode-Template" "SSH-Config" "STON" "SVG" "SWIG" "Sage" "SaltStack" "Sass"
4364 "Scala" "Scaml" "Scheme" "Scilab" "Self" "ShaderLab" "Shell" "ShellSession"
4365 "Shen" "Slash" "Slice" "Slim" "SmPL" "Smali" "Smalltalk" "Smarty" "Solidity"
4366 "SourcePawn" "Spline-Font-Database" "Squirrel" "Stan" "Standard-ML" "Starlark"
4367 "Stata" "Stylus" "SubRip-Text" "SugarSS" "SuperCollider" "Svelte" "Swift"
4368 "SystemVerilog" "TI-Program" "TLA" "TOML" "TSQL" "TSX" "TXL" "Tcl" "Tcsh"
4369 "TeX" "Tea" "Terra" "Texinfo" "Text" "Textile" "Thrift" "Turing" "Turtle"
4370 "Twig" "Type-Language" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset"
4371 "Unix-Assembly" "Uno" "UnrealScript" "UrWeb" "VBA" "VBScript" "VCL" "VHDL"
4372 "Vala" "Verilog" "Vim-Snippet" "Vim-script" "Visual-Basic-.NET" "Volt" "Vue"
4373 "Wavefront-Material" "Wavefront-Object" "Web-Ontology-Language" "WebAssembly"
4374 "WebIDL" "WebVTT" "Wget-Config" "Windows-Registry-Entries" "Wollok"
4375 "World-of-Warcraft-Addon-Data" "X-BitMap" "X-Font-Directory-Index" "X-PixMap"
4376 "X10" "XC" "XCompose" "XML" "XML-Property-List" "XPages" "XProc" "XQuery" "XS"
4377 "XSLT" "Xojo" "Xtend" "YAML" "YANG" "YARA" "YASnippet" "Yacc" "ZAP" "ZIL"
4378 "Zeek" "ZenScript" "Zephir" "Zig" "Zimpl" "cURL-Config" "desktop" "dircolors"
4379 "eC" "edn" "fish" "mIRC-Script" "mcfunction" "mupad" "nanorc" "nesC" "ooc"
4380 "reStructuredText" "sed" "wdl" "wisp" "xBase")
4381 "Language specifiers recognized by GitHub's syntax highlighting features.")
4383 (defvar-local markdown-gfm-used-languages nil
4384 "Language names used in GFM code blocks.")
4386 (defun markdown-trim-whitespace (str)
4387 (replace-regexp-in-string
4388 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str
))
4390 (defun markdown-clean-language-string (str)
4391 (replace-regexp-in-string
4392 "{\\.?\\|}" "" (markdown-trim-whitespace str
)))
4394 (defun markdown-validate-language-string (widget)
4395 (let ((str (widget-value widget
)))
4396 (unless (string= str
(markdown-clean-language-string str
))
4397 (widget-put widget
:error
(format "Invalid language spec: '%s'" str
))
4400 (defun markdown-gfm-get-corpus ()
4401 "Create corpus of recognized GFM code block languages for the given buffer."
4402 (let ((given-corpus (append markdown-gfm-additional-languages
4403 markdown-gfm-recognized-languages
)))
4405 markdown-gfm-used-languages
4406 (if markdown-gfm-downcase-languages
(cl-mapcar #'downcase given-corpus
)
4409 (defun markdown-gfm-add-used-language (lang)
4410 "Clean LANG and add to list of used languages."
4411 (setq markdown-gfm-used-languages
4412 (cons lang
(remove lang markdown-gfm-used-languages
))))
4414 (defcustom markdown-spaces-after-code-fence
1
4415 "Number of space characters to insert after a code fence.
4416 \\<gfm-mode-map>\\[markdown-insert-gfm-code-block] inserts this many spaces between an
4417 opening code fence and an info string."
4421 :package-version
'(markdown-mode .
"2.3"))
4423 (defcustom markdown-code-block-braces nil
4424 "When non-nil, automatically insert braces for GFM code blocks."
4428 (defun markdown-insert-gfm-code-block (&optional lang edit
)
4429 "Insert GFM code block for language LANG.
4430 If LANG is nil, the language will be queried from user. If a
4431 region is active, wrap this region with the markup instead. If
4432 the region boundaries are not on empty lines, these are added
4433 automatically in order to have the correct markup. When EDIT is
4434 non-nil (e.g., when \\[universal-argument] is given), edit the
4435 code block in an indirect buffer after insertion."
4437 (list (let ((completion-ignore-case nil
))
4439 (markdown-clean-language-string
4441 "Programming language: "
4442 (markdown-gfm-get-corpus)
4443 nil
'confirm
(car markdown-gfm-used-languages
)
4444 'markdown-gfm-language-history
))
4446 current-prefix-arg
))
4447 (unless (string= lang
"") (markdown-gfm-add-used-language lang
))
4448 (when (and (> (length lang
) 0)
4449 (not markdown-code-block-braces
))
4450 (setq lang
(concat (make-string markdown-spaces-after-code-fence ?\s
)
4452 (let ((gfm-open-brace (if markdown-code-block-braces
"{" ""))
4453 (gfm-close-brace (if markdown-code-block-braces
"}" "")))
4455 (let* ((b (region-beginning)) (e (region-end)) end
4456 (indent (progn (goto-char b
) (current-indentation))))
4458 ;; if we're on a blank line, don't newline, otherwise the ```
4459 ;; should go on its own line
4460 (unless (looking-back "\n" nil
)
4464 (markdown-ensure-blank-line-after)
4467 ;; if we're on a blank line, insert the quotes here, otherwise
4468 ;; add a new line first
4469 (unless (looking-at-p "\n")
4472 (markdown-ensure-blank-line-before)
4474 (insert "```" gfm-open-brace lang gfm-close-brace
)
4475 (markdown-syntax-propertize-fenced-block-constructs (point-at-bol) end
))
4476 (let ((indent (current-indentation))
4478 (delete-horizontal-space :backward-only
)
4479 (markdown-ensure-blank-line-before)
4481 (setq start-bol
(point-at-bol))
4482 (insert "```" gfm-open-brace lang gfm-close-brace
"\n")
4484 (unless edit
(insert ?
\n))
4487 (markdown-ensure-blank-line-after)
4488 (markdown-syntax-propertize-fenced-block-constructs start-bol
(point)))
4490 (when edit
(markdown-edit-code-block)))))
4492 (defun markdown-code-block-lang (&optional pos-prop
)
4493 "Return the language name for a GFM or tilde fenced code block.
4494 The beginning of the block may be described by POS-PROP,
4495 a cons of (pos . prop) giving the position and property
4496 at the beginning of the block."
4499 (markdown-max-of-seq
4504 #'markdown-find-previous-prop
4505 (markdown-get-fenced-block-begin-properties))))))
4507 (goto-char (car pos-prop
))
4508 (set-match-data (get-text-property (point) (cdr pos-prop
)))
4509 ;; Note: Hard-coded group number assumes tilde
4510 ;; and GFM fenced code regexp groups agree.
4511 (let ((begin (match-beginning 3))
4512 (end (match-end 3)))
4513 (when (and begin end
)
4514 ;; Fix language strings beginning with periods, like ".ruby".
4515 (when (eq (char-after begin
) ?.
)
4516 (setq begin
(1+ begin
)))
4517 (buffer-substring-no-properties begin end
)))))
4519 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer
)
4520 (with-current-buffer (or buffer
(current-buffer))
4522 (goto-char (point-min))
4524 with prop
= 'markdown-gfm-block-begin
4525 for pos-prop
= (markdown-find-next-prop prop
)
4527 for lang
= (markdown-code-block-lang pos-prop
)
4528 do
(progn (when lang
(markdown-gfm-add-used-language lang
))
4529 (goto-char (next-single-property-change (point) prop
)))))))
4531 (defun markdown-insert-foldable-block ()
4532 "Insert details disclosure element to make content foldable.
4533 If a region is active, wrap this region with the disclosure
4534 element. More detais here 'https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details'."
4536 (let ((details-open-tag "<details>")
4537 (details-close-tag "</details>")
4538 (summary-open-tag "<summary>")
4539 (summary-close-tag " </summary>"))
4541 (let* ((b (region-beginning))
4543 (indent (progn (goto-char b
) (current-indentation))))
4545 ;; if we're on a blank line, don't newline, otherwise the tags
4546 ;; should go on its own line
4547 (unless (looking-back "\n" nil
)
4550 (insert details-close-tag
)
4551 (markdown-ensure-blank-line-after)
4553 ;; if we're on a blank line, insert the quotes here, otherwise
4554 ;; add a new line first
4555 (unless (looking-at-p "\n")
4558 (markdown-ensure-blank-line-before)
4560 (insert details-open-tag
"\n")
4561 (insert summary-open-tag summary-close-tag
)
4562 (search-backward summary-close-tag
))
4563 (let ((indent (current-indentation)))
4564 (delete-horizontal-space :backward-only
)
4565 (markdown-ensure-blank-line-before)
4567 (insert details-open-tag
"\n")
4568 (insert summary-open-tag summary-close-tag
"\n")
4569 (insert details-close-tag
)
4571 (markdown-ensure-blank-line-after)
4572 (search-backward summary-close-tag
)))))
4575 ;;; Footnotes =================================================================
4577 (defun markdown-footnote-counter-inc ()
4578 "Increment `markdown-footnote-counter' and return the new value."
4579 (when (= markdown-footnote-counter
0) ; hasn't been updated in this buffer yet.
4581 (goto-char (point-min))
4582 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars
"*?\\)\\]:")
4584 (let ((fn (string-to-number (match-string 1))))
4585 (when (> fn markdown-footnote-counter
)
4586 (setq markdown-footnote-counter fn
))))))
4587 (cl-incf markdown-footnote-counter
))
4589 (defun markdown-insert-footnote ()
4590 "Insert footnote with a new number and move point to footnote definition."
4592 (let ((fn (markdown-footnote-counter-inc)))
4593 (insert (format "[^%d]" fn
))
4594 (markdown-footnote-text-find-new-location)
4595 (markdown-ensure-blank-line-before)
4596 (unless (markdown-cur-line-blank-p)
4598 (insert (format "[^%d]: " fn
))
4599 (markdown-ensure-blank-line-after)))
4601 (defun markdown-footnote-text-find-new-location ()
4602 "Position the point at the proper location for a new footnote text."
4604 ((eq markdown-footnote-location
'end
) (goto-char (point-max)))
4605 ((eq markdown-footnote-location
'immediately
) (markdown-end-of-text-block))
4606 ((eq markdown-footnote-location
'subtree
) (markdown-end-of-subtree))
4607 ((eq markdown-footnote-location
'header
) (markdown-end-of-defun))))
4609 (defun markdown-footnote-kill ()
4610 "Kill the footnote at point.
4611 The footnote text is killed (and added to the kill ring), the
4612 footnote marker is deleted. Point has to be either at the
4613 footnote marker or in the footnote text."
4615 (let ((marker-pos nil
)
4616 (skip-deleting-marker nil
)
4617 (starting-footnote-text-positions
4618 (markdown-footnote-text-positions)))
4619 (when starting-footnote-text-positions
4620 ;; We're starting in footnote text, so mark our return position and jump
4621 ;; to the marker if possible.
4622 (let ((marker-pos (markdown-footnote-find-marker
4623 (cl-first starting-footnote-text-positions
))))
4625 (goto-char (1- marker-pos
))
4626 ;; If there isn't a marker, we still want to kill the text.
4627 (setq skip-deleting-marker t
))))
4628 ;; Either we didn't start in the text, or we started in the text and jumped
4629 ;; to the marker. We want to assume we're at the marker now and error if
4631 (unless skip-deleting-marker
4632 (let ((marker (markdown-footnote-delete-marker)))
4634 (error "Not at a footnote"))
4635 ;; Even if we knew the text position before, it changed when we deleted
4637 (setq marker-pos
(cl-second marker
))
4638 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker
))))
4639 (unless new-text-pos
4640 (error "No text for footnote `%s'" (cl-first marker
)))
4641 (goto-char new-text-pos
))))
4642 (let ((pos (markdown-footnote-kill-text)))
4643 (goto-char (if starting-footnote-text-positions
4647 (defun markdown-footnote-delete-marker ()
4648 "Delete a footnote marker at point.
4649 Returns a list (ID START) containing the footnote ID and the
4650 start position of the marker before deletion. If no footnote
4651 marker was deleted, this function returns NIL."
4652 (let ((marker (markdown-footnote-marker-positions)))
4654 (delete-region (cl-second marker
) (cl-third marker
))
4657 (defun markdown-footnote-kill-text ()
4658 "Kill footnote text at point.
4659 Returns the start position of the footnote text before deletion,
4660 or NIL if point was not inside a footnote text.
4662 The killed text is placed in the kill ring (without the footnote
4664 (let ((fn (markdown-footnote-text-positions)))
4666 (let ((text (delete-and-extract-region (cl-second fn
) (cl-third fn
))))
4667 (string-match (concat "\\[\\" (cl-first fn
) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text
)
4668 (kill-new (match-string 1 text
))
4669 (when (and (markdown-cur-line-blank-p)
4670 (markdown-prev-line-blank-p)
4672 (delete-region (1- (point)) (point)))
4675 (defun markdown-footnote-goto-text ()
4676 "Jump to the text of the footnote at point."
4678 (let ((fn (car (markdown-footnote-marker-positions))))
4680 (user-error "Not at a footnote marker"))
4681 (let ((new-pos (markdown-footnote-find-text fn
)))
4683 (error "No definition found for footnote `%s'" fn
))
4684 (goto-char new-pos
))))
4686 (defun markdown-footnote-return ()
4687 "Return from a footnote to its footnote number in the main text."
4689 (let ((fn (save-excursion
4690 (car (markdown-footnote-text-positions)))))
4692 (user-error "Not in a footnote"))
4693 (let ((new-pos (markdown-footnote-find-marker fn
)))
4695 (error "Footnote marker `%s' not found" fn
))
4696 (goto-char new-pos
))))
4698 (defun markdown-footnote-find-marker (id)
4699 "Find the location of the footnote marker with ID.
4700 The actual buffer position returned is the position directly
4701 following the marker's closing bracket. If no marker is found,
4704 (goto-char (point-min))
4705 (when (re-search-forward (concat "\\[" id
"\\]\\([^:]\\|\\'\\)") nil t
)
4706 (skip-chars-backward "^]")
4709 (defun markdown-footnote-find-text (id)
4710 "Find the location of the text of footnote ID.
4711 The actual buffer position returned is the position of the first
4712 character of the text, after the footnote's identifier. If no
4713 footnote text is found, NIL is returned."
4715 (goto-char (point-min))
4716 (when (re-search-forward (concat "^ \\{0,3\\}\\[" id
"\\]:") nil t
)
4717 (skip-chars-forward "[ \t]")
4720 (defun markdown-footnote-marker-positions ()
4721 "Return the position and ID of the footnote marker point is on.
4722 The return value is a list (ID START END). If point is not on a
4723 footnote, NIL is returned."
4724 ;; first make sure we're at a footnote marker
4725 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars
"*\\]?") (line-beginning-position))
4726 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars
"*?\\]")))
4728 ;; move point between [ and ^:
4729 (if (looking-at-p "\\[")
4731 (skip-chars-backward "^["))
4732 (looking-at (concat "\\(\\^" markdown-footnote-chars
"*?\\)\\]"))
4733 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
4735 (defun markdown-footnote-text-positions ()
4736 "Return the start and end positions of the footnote text point is in.
4737 The exact return value is a list of three elements: (ID START END).
4738 The start position is the position of the opening bracket
4739 of the footnote id. The end position is directly after the
4740 newline that ends the footnote. If point is not in a footnote,
4741 NIL is returned instead."
4744 (move-beginning-of-line 1)
4745 ;; Try to find the label. If we haven't found the label and we're at a blank
4746 ;; or indented line, back up if possible.
4748 (not (and (looking-at markdown-regex-footnote-definition
)
4749 (setq result
(list (match-string 1) (point)))))
4751 (or (markdown-cur-line-blank-p)
4752 (>= (current-indentation) 4))))
4755 ;; Advance if there is a next line that is either blank or indented.
4756 ;; (Need to check if we're on the last line, because
4757 ;; markdown-next-line-blank-p returns true for last line in buffer.)
4758 (while (and (/= (line-end-position) (point-max))
4759 (or (markdown-next-line-blank-p)
4760 (>= (markdown-next-line-indent) 4)))
4762 ;; Move back while the current line is blank.
4763 (while (markdown-cur-line-blank-p)
4765 ;; Advance to capture this line and a single trailing newline (if there
4768 (append result
(list (point)))))))
4770 (defun markdown-get-defined-footnotes ()
4771 "Return a list of all defined footnotes.
4772 Result is an alist of pairs (MARKER . LINE), where MARKER is the
4773 footnote marker, a string, and LINE is the line number containing
4774 the footnote definition.
4776 For example, suppose the following footnotes are defined at positions
4779 \[^1]: First footnote here.
4780 \[^marker]: Second footnote.
4782 Then the returned list is: ((\"^1\" . 478) (\"^marker\" . 475))"
4784 (goto-char (point-min))
4786 (while (markdown-search-until-condition
4787 (lambda () (and (not (markdown-code-block-at-point-p))
4788 (not (markdown-inline-code-at-point-p))
4789 (not (markdown-in-comment-p))))
4790 markdown-regex-footnote-definition nil t
)
4791 (let ((marker (match-string-no-properties 1))
4792 (pos (match-beginning 0)))
4793 (unless (zerop (length marker
))
4794 (cl-pushnew (cons marker pos
) footnotes
:test
#'equal
))))
4795 (reverse footnotes
))))
4798 ;;; Element Removal ===========================================================
4800 (defun markdown-kill-thing-at-point ()
4801 "Kill thing at point and add important text, without markup, to kill ring.
4802 Possible things to kill include (roughly in order of precedence):
4803 inline code, headers, horizontal rules, links (add link text to
4804 kill ring), images (add alt text to kill ring), angle uri, email
4805 addresses, bold, italics, reference definition (add URI to kill
4806 ring), footnote markers and text (kill both marker and text, add
4807 text to kill ring), and list items."
4812 ((markdown-inline-code-at-point)
4813 (kill-new (match-string 2))
4814 (delete-region (match-beginning 0) (match-end 0)))
4816 ((thing-at-point-looking-at markdown-regex-header-atx
)
4817 (kill-new (match-string 2))
4818 (delete-region (match-beginning 0) (match-end 0)))
4820 ((thing-at-point-looking-at markdown-regex-header-setext
)
4821 (kill-new (match-string 1))
4822 (delete-region (match-beginning 0) (match-end 0)))
4824 ((thing-at-point-looking-at markdown-regex-hr
)
4825 (kill-new (match-string 0))
4826 (delete-region (match-beginning 0) (match-end 0)))
4827 ;; Inline link or image (add link or alt text to kill ring)
4828 ((thing-at-point-looking-at markdown-regex-link-inline
)
4829 (kill-new (match-string 3))
4830 (delete-region (match-beginning 0) (match-end 0)))
4831 ;; Reference link or image (add link or alt text to kill ring)
4832 ((thing-at-point-looking-at markdown-regex-link-reference
)
4833 (kill-new (match-string 3))
4834 (delete-region (match-beginning 0) (match-end 0)))
4835 ;; Angle URI (add URL to kill ring)
4836 ((thing-at-point-looking-at markdown-regex-angle-uri
)
4837 (kill-new (match-string 2))
4838 (delete-region (match-beginning 0) (match-end 0)))
4839 ;; Email address in angle brackets (add email address to kill ring)
4840 ((thing-at-point-looking-at markdown-regex-email
)
4841 (kill-new (match-string 1))
4842 (delete-region (match-beginning 0) (match-end 0)))
4843 ;; Wiki link (add alias text to kill ring)
4844 ((and markdown-enable-wiki-links
4845 (thing-at-point-looking-at markdown-regex-wiki-link
))
4846 (kill-new (markdown-wiki-link-alias))
4847 (delete-region (match-beginning 1) (match-end 1)))
4849 ((thing-at-point-looking-at markdown-regex-bold
)
4850 (kill-new (match-string 4))
4851 (delete-region (match-beginning 2) (match-end 2)))
4853 ((thing-at-point-looking-at markdown-regex-italic
)
4854 (kill-new (match-string 3))
4855 (delete-region (match-beginning 1) (match-end 1)))
4857 ((thing-at-point-looking-at markdown-regex-strike-through
)
4858 (kill-new (match-string 4))
4859 (delete-region (match-beginning 2) (match-end 2)))
4860 ;; Footnote marker (add footnote text to kill ring)
4861 ((thing-at-point-looking-at markdown-regex-footnote
)
4862 (markdown-footnote-kill))
4863 ;; Footnote text (add footnote text to kill ring)
4864 ((setq val
(markdown-footnote-text-positions))
4865 (markdown-footnote-kill))
4866 ;; Reference definition (add URL to kill ring)
4867 ((thing-at-point-looking-at markdown-regex-reference-definition
)
4868 (kill-new (match-string 5))
4869 (delete-region (match-beginning 0) (match-end 0)))
4871 ((setq val
(markdown-cur-list-item-bounds))
4872 (kill-new (delete-and-extract-region (cl-first val
) (cl-second val
))))
4874 (user-error "Nothing found at point to kill")))))
4876 (defun markdown-kill-outline ()
4877 "Kill visible heading and add it to `kill-ring'."
4880 (markdown-outline-previous)
4881 (kill-region (point) (progn (markdown-outline-next) (point)))))
4883 (defun markdown-kill-block ()
4884 "Kill visible code block, list item, or blockquote and add it to `kill-ring'."
4887 (markdown-backward-block)
4888 (kill-region (point) (progn (markdown-forward-block) (point)))))
4891 ;;; Indentation ===============================================================
4893 (defun markdown-indent-find-next-position (cur-pos positions
)
4894 "Return the position after the index of CUR-POS in POSITIONS.
4895 Positions are calculated by `markdown-calc-indents'."
4896 (while (and positions
4897 (not (equal cur-pos
(car positions
))))
4898 (setq positions
(cdr positions
)))
4899 (or (cadr positions
) 0))
4901 (defun markdown-outdent-find-next-position (cur-pos positions
)
4902 "Return the maximal element that precedes CUR-POS from POSITIONS.
4903 Positions are calculated by `markdown-calc-indents'."
4905 (dolist (i positions
)
4907 (setq result
(max result i
))))
4910 (defun markdown-indent-line ()
4911 "Indent the current line using some heuristics.
4912 If the _previous_ command was either `markdown-enter-key' or
4913 `markdown-cycle', then we should cycle to the next
4914 reasonable indentation position. Otherwise, we could have been
4915 called directly by `markdown-enter-key', by an initial call of
4916 `markdown-cycle', or indirectly by `auto-fill-mode'. In
4917 these cases, indent to the default position.
4918 Positions are calculated by `markdown-calc-indents'."
4920 (let ((positions (markdown-calc-indents))
4921 (point-pos (current-column))
4922 (_ (back-to-indentation))
4923 (cur-pos (current-column)))
4924 (if (not (equal this-command
'markdown-cycle
))
4925 (indent-line-to (car positions
))
4926 (setq positions
(sort (delete-dups positions
) '<))
4927 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions
))
4928 (new-point-pos (max (+ point-pos
(- next-pos cur-pos
)) 0)))
4929 (indent-line-to next-pos
)
4930 (move-to-column new-point-pos
)))))
4932 (defun markdown-calc-indents ()
4933 "Return a list of indentation columns to cycle through.
4934 The first element in the returned list should be considered the
4935 default indentation level. This function does not worry about
4936 duplicate positions, which are handled up by calling functions."
4937 (let (pos prev-line-pos positions
)
4939 ;; Indentation of previous line
4940 (setq prev-line-pos
(markdown-prev-line-indent))
4941 (setq positions
(cons prev-line-pos positions
))
4943 ;; Indentation of previous non-list-marker text
4944 (when (setq pos
(save-excursion
4946 (when (looking-at markdown-regex-list
)
4947 (- (match-end 3) (match-beginning 0)))))
4948 (setq positions
(cons pos positions
)))
4950 ;; Indentation required for a pre block in current context
4951 (setq pos
(length (markdown-pre-indentation (point))))
4952 (setq positions
(cons pos positions
))
4954 ;; Indentation of the previous line + tab-width
4956 (setq positions
(cons (+ prev-line-pos tab-width
) positions
))
4957 (setq positions
(cons tab-width positions
)))
4959 ;; Indentation of the previous line - tab-width
4960 (if (and prev-line-pos
(> prev-line-pos tab-width
))
4961 (setq positions
(cons (- prev-line-pos tab-width
) positions
)))
4963 ;; Indentation of all preceding list markers (when in a list)
4964 (when (setq pos
(markdown-calculate-list-levels))
4965 (setq positions
(append pos positions
)))
4968 (setq positions
(cons 0 positions
))
4970 ;; Return reversed list
4971 (reverse positions
)))
4973 (defun markdown-enter-key () ;FIXME: Partly obsoleted by electric-indent
4974 "Handle RET depending on the context.
4975 If the point is at a table, move to the next row. Otherwise,
4976 indent according to value of `markdown-indent-on-enter'.
4977 When it is nil, simply call `newline'. Otherwise, indent the next line
4978 following RET using `markdown-indent-line'. Furthermore, when it
4979 is set to 'indent-and-new-item and the point is in a list item,
4980 start a new item with the same indentation. If the point is in an
4981 empty list item, remove it (so that pressing RET twice when in a
4982 list simply adds a blank line)."
4986 ((markdown-table-at-point-p)
4987 (call-interactively #'markdown-table-next-row
))
4988 ;; Indent non-table text
4989 (markdown-indent-on-enter
4991 (if (and (memq markdown-indent-on-enter
'(indent-and-new-item))
4992 (setq bounds
(markdown-cur-list-item-bounds)))
4993 (let ((beg (cl-first bounds
))
4994 (end (cl-second bounds
))
4995 (length (cl-fourth bounds
)))
4996 ;; Point is in a list item
4997 (if (= (- end beg
) length
)
4998 ;; Delete blank list
5000 (delete-region beg end
)
5002 (markdown-indent-line))
5003 (call-interactively #'markdown-insert-list-item
)))
5004 ;; Point is not in a list
5006 (markdown-indent-line))))
5007 ;; Insert a raw newline
5010 (defun markdown-outdent-or-delete (arg)
5011 "Handle BACKSPACE by cycling through indentation points.
5012 When BACKSPACE is pressed, if there is only whitespace
5013 before the current point, then outdent the line one level.
5014 Otherwise, do normal delete by repeating
5015 `backward-delete-char-untabify' ARG times."
5018 (backward-delete-char-untabify arg
)
5019 (let ((cur-pos (current-column))
5020 (start-of-indention (save-excursion
5021 (back-to-indentation)
5023 (positions (markdown-calc-indents)))
5024 (if (and (> cur-pos
0) (= cur-pos start-of-indention
))
5025 (indent-line-to (markdown-outdent-find-next-position cur-pos positions
))
5026 (backward-delete-char-untabify arg
)))))
5028 (defun markdown-find-leftmost-column (beg end
)
5029 "Find the leftmost column in the region from BEG to END."
5030 (let ((mincol 1000))
5033 (while (< (point) end
)
5034 (back-to-indentation)
5035 (unless (looking-at-p "[ \t]*$")
5036 (setq mincol
(min mincol
(current-column))))
5041 (defun markdown-indent-region (beg end arg
)
5042 "Indent the region from BEG to END using some heuristics.
5043 When ARG is non-nil, outdent the region instead.
5044 See `markdown-indent-line' and `markdown-indent-line'."
5045 (interactive "*r\nP")
5046 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
5047 (leftmostcol (markdown-find-leftmost-column beg end
))
5049 (markdown-outdent-find-next-position leftmostcol positions
)
5050 (markdown-indent-find-next-position leftmostcol positions
))))
5051 (indent-rigidly beg end
(- next-pos leftmostcol
))
5052 (setq deactivate-mark nil
)))
5054 (defun markdown-outdent-region (beg end
)
5055 "Call `markdown-indent-region' on region from BEG to END with prefix."
5057 (markdown-indent-region beg end t
))
5059 (defun markdown--indent-region (start end
)
5060 (let ((deactivate-mark nil
))
5063 (setq end
(point-marker))
5067 (while (< (point) end
)
5068 (unless (or (markdown-code-block-at-point-p) (and (bolp) (eolp)))
5069 (indent-according-to-mode))
5071 (move-marker end nil
))))
5074 ;;; Markup Completion =========================================================
5076 (defconst markdown-complete-alist
5077 '((markdown-regex-header-atx . markdown-complete-atx
)
5078 (markdown-regex-header-setext . markdown-complete-setext
)
5079 (markdown-regex-hr . markdown-complete-hr
))
5080 "Association list of form (regexp . function) for markup completion.")
5082 (defun markdown-incomplete-atx-p ()
5083 "Return t if ATX header markup is incomplete and nil otherwise.
5084 Assumes match data is available for `markdown-regex-header-atx'.
5085 Checks that the number of trailing hash marks equals the number of leading
5086 hash marks, that there is only a single space before and after the text,
5087 and that there is no extraneous whitespace in the text."
5089 ;; Number of starting and ending hash marks differs
5090 (not (= (length (match-string 1)) (length (match-string 3))))
5091 ;; When the header text is not empty...
5092 (and (> (length (match-string 2)) 0)
5093 ;; ...if there are extra leading, trailing, or interior spaces
5094 (or (not (= (match-beginning 2) (1+ (match-end 1))))
5095 (not (= (match-beginning 3) (1+ (match-end 2))))
5096 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
5097 ;; When the header text is empty...
5098 (and (= (length (match-string 2)) 0)
5099 ;; ...if there are too many or too few spaces
5100 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
5102 (defun markdown-complete-atx ()
5103 "Complete and normalize ATX headers.
5104 Add or remove hash marks to the end of the header to match the
5105 beginning. Ensure that there is only a single space between hash
5106 marks and header text. Removes extraneous whitespace from header text.
5107 Assumes match data is available for `markdown-regex-header-atx'.
5108 Return nil if markup was complete and non-nil if markup was completed."
5109 (when (markdown-incomplete-atx-p)
5110 (let* ((new-marker (make-marker))
5111 (new-marker (set-marker new-marker
(match-end 2))))
5112 ;; Hash marks and spacing at end
5113 (goto-char (match-end 2))
5114 (delete-region (match-end 2) (match-end 3))
5115 (insert " " (match-string 1))
5116 ;; Remove extraneous whitespace from title
5117 (replace-match (markdown-compress-whitespace-string (match-string 2))
5119 ;; Spacing at beginning
5120 (goto-char (match-end 1))
5121 (delete-region (match-end 1) (match-beginning 2))
5123 ;; Leave point at end of text
5124 (goto-char new-marker
))))
5126 (defun markdown-incomplete-setext-p ()
5127 "Return t if setext header markup is incomplete and nil otherwise.
5128 Assumes match data is available for `markdown-regex-header-setext'.
5129 Checks that length of underline matches text and that there is no
5130 extraneous whitespace in the text."
5131 (or (not (= (length (match-string 1)) (length (match-string 2))))
5132 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
5134 (defun markdown-complete-setext ()
5135 "Complete and normalize setext headers.
5136 Add or remove underline characters to match length of header
5137 text. Removes extraneous whitespace from header text. Assumes
5138 match data is available for `markdown-regex-header-setext'.
5139 Return nil if markup was complete and non-nil if markup was completed."
5140 (when (markdown-incomplete-setext-p)
5141 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
5142 (char (char-after (match-beginning 2)))
5143 (level (if (char-equal char ?-
) 2 1)))
5144 (goto-char (match-beginning 0))
5145 (delete-region (match-beginning 0) (match-end 0))
5146 (markdown-insert-header level text t
)
5149 (defun markdown-incomplete-hr-p ()
5150 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
5151 Assumes match data is available for `markdown-regex-hr'."
5152 (not (member (match-string 0) markdown-hr-strings
)))
5154 (defun markdown-complete-hr ()
5155 "Complete horizontal rules.
5156 If horizontal rule string is a member of `markdown-hr-strings',
5157 do nothing. Otherwise, replace with the car of
5158 `markdown-hr-strings'.
5159 Assumes match data is available for `markdown-regex-hr'.
5160 Return nil if markup was complete and non-nil if markup was completed."
5161 (when (markdown-incomplete-hr-p)
5162 (replace-match (car markdown-hr-strings
))
5165 (defun markdown-complete ()
5166 "Complete markup of object near point or in region when active.
5167 Handle all objects in `markdown-complete-alist', in order.
5168 See `markdown-complete-at-point' and `markdown-complete-region'."
5171 (markdown-complete-region (region-beginning) (region-end))
5172 (markdown-complete-at-point)))
5174 (defun markdown-complete-at-point ()
5175 "Complete markup of object near point.
5176 Handle all elements of `markdown-complete-alist' in order."
5178 (let ((list markdown-complete-alist
) found changed
)
5180 (let ((regexp (eval (caar list
) t
)) ;FIXME: Why `eval'?
5181 (function (cdar list
)))
5182 (setq list
(cdr list
))
5183 (when (thing-at-point-looking-at regexp
)
5185 (setq changed
(funcall function
))
5188 (or changed
(user-error "Markup at point is complete"))
5189 (user-error "Nothing to complete at point"))))
5191 (defun markdown-complete-region (beg end
)
5192 "Complete markup of objects in region from BEG to END.
5193 Handle all objects in `markdown-complete-alist', in order. Each
5194 match is checked to ensure that a previous regexp does not also
5197 (let ((end-marker (set-marker (make-marker) end
))
5199 (dolist (element markdown-complete-alist
)
5200 (let ((regexp (eval (car element
) t
)) ;FIXME: Why `eval'?
5201 (function (cdr element
)))
5203 (while (re-search-forward regexp end-marker
'limit
)
5204 (when (match-string 0)
5205 ;; Make sure this is not a match for any of the preceding regexps.
5206 ;; This prevents mistaking an HR for a Setext subheading.
5209 (dolist (prev-regexp previous
)
5210 (or match
(setq match
(looking-back prev-regexp nil
)))))
5212 (save-excursion (funcall function
))))))
5213 (cl-pushnew regexp previous
:test
#'equal
)))
5216 (defun markdown-complete-buffer ()
5217 "Complete markup for all objects in the current buffer."
5219 (markdown-complete-region (point-min) (point-max)))
5222 ;;; Markup Cycling ============================================================
5224 (defun markdown-cycle-atx (arg &optional remove
)
5225 "Cycle ATX header markup.
5226 Promote header (decrease level) when ARG is 1 and demote
5227 header (increase level) if arg is -1. When REMOVE is non-nil,
5228 remove the header when the level reaches zero and stop cycling
5229 when it reaches six. Otherwise, perform a proper cycling through
5230 levels one through six. Assumes match data is available for
5231 `markdown-regex-header-atx'."
5232 (let* ((old-level (length (match-string 1)))
5233 (new-level (+ old-level arg
))
5234 (text (match-string 2)))
5236 (setq new-level
(% new-level
6))
5237 (setq new-level
(cond ((= new-level
0) 6)
5238 ((< new-level
0) (+ new-level
6))
5242 (markdown-unwrap-thing-at-point nil
0 2))
5244 (goto-char (match-beginning 0))
5245 (delete-region (match-beginning 0) (match-end 0))
5246 (markdown-insert-header new-level text nil
)))))
5248 (defun markdown-cycle-setext (arg &optional remove
)
5249 "Cycle setext header markup.
5250 Promote header (increase level) when ARG is 1 and demote
5251 header (decrease level or remove) if arg is -1. When demoting a
5252 level-two setext header, replace with a level-three atx header.
5253 When REMOVE is non-nil, remove the header when the level reaches
5254 zero. Otherwise, cycle back to a level six atx header. Assumes
5255 match data is available for `markdown-regex-header-setext'."
5256 (let* ((char (char-after (match-beginning 2)))
5257 (old-level (if (char-equal char ?
=) 1 2))
5258 (new-level (+ old-level arg
)))
5259 (when (and (not remove
) (= new-level
0))
5263 (markdown-unwrap-thing-at-point nil
0 1))
5265 (markdown-insert-header new-level nil t
))
5267 (markdown-insert-header new-level nil nil
)))))
5269 (defun markdown-cycle-hr (arg &optional remove
)
5270 "Cycle string used for horizontal rule from `markdown-hr-strings'.
5271 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
5272 backwards (promote). When REMOVE is non-nil, remove the hr instead
5273 of cycling when the end of the list is reached.
5274 Assumes match data is available for `markdown-regex-hr'."
5275 (let* ((strings (if (= arg -
1)
5276 (reverse markdown-hr-strings
)
5277 markdown-hr-strings
))
5278 (tail (member (match-string 0) strings
))
5279 (new (or (cadr tail
)
5285 (replace-match new
)))
5287 (defun markdown-cycle-bold ()
5288 "Cycle bold markup between underscores and asterisks.
5289 Assumes match data is available for `markdown-regex-bold'."
5291 (let* ((old-delim (match-string 3))
5292 (new-delim (if (string-equal old-delim
"**") "__" "**")))
5293 (replace-match new-delim t t nil
3)
5294 (replace-match new-delim t t nil
5))))
5296 (defun markdown-cycle-italic ()
5297 "Cycle italic markup between underscores and asterisks.
5298 Assumes match data is available for `markdown-regex-italic'."
5300 (let* ((old-delim (match-string 2))
5301 (new-delim (if (string-equal old-delim
"*") "_" "*")))
5302 (replace-match new-delim t t nil
2)
5303 (replace-match new-delim t t nil
4))))
5306 ;;; Keymap ====================================================================
5308 (defun markdown--style-map-prompt ()
5309 "Return a formatted prompt for Markdown markup insertion."
5310 (when markdown-enable-prefix-prompts
5313 (propertize "bold" 'face
'markdown-bold-face
) ", "
5314 (propertize "italic" 'face
'markdown-italic-face
) ", "
5315 (propertize "code" 'face
'markdown-inline-code-face
) ", "
5316 (propertize "C = GFM code" 'face
'markdown-code-face
) ", "
5317 (propertize "pre" 'face
'markdown-pre-face
) ", "
5318 (propertize "footnote" 'face
'markdown-footnote-text-face
) ", "
5319 (propertize "F = foldable" 'face
'markdown-bold-face
) ", "
5320 (propertize "q = blockquote" 'face
'markdown-blockquote-face
) ", "
5321 (propertize "h & 1-6 = heading" 'face
'markdown-header-face
) ", "
5322 (propertize "- = hr" 'face
'markdown-hr-face
) ", "
5325 (defun markdown--command-map-prompt ()
5326 "Return prompt for Markdown buffer-wide commands."
5327 (when markdown-enable-prefix-prompts
5330 (propertize "m" 'face
'markdown-bold-face
) "arkdown, "
5331 (propertize "p" 'face
'markdown-bold-face
) "review, "
5332 (propertize "o" 'face
'markdown-bold-face
) "pen, "
5333 (propertize "e" 'face
'markdown-bold-face
) "xport, "
5334 "export & pre" (propertize "v" 'face
'markdown-bold-face
) "iew, "
5335 (propertize "c" 'face
'markdown-bold-face
) "heck refs, "
5336 (propertize "u" 'face
'markdown-bold-face
) "nused refs, "
5339 (defvar markdown-mode-style-map
5340 (let ((map (make-keymap (markdown--style-map-prompt))))
5341 (define-key map
(kbd "1") 'markdown-insert-header-atx-1
)
5342 (define-key map
(kbd "2") 'markdown-insert-header-atx-2
)
5343 (define-key map
(kbd "3") 'markdown-insert-header-atx-3
)
5344 (define-key map
(kbd "4") 'markdown-insert-header-atx-4
)
5345 (define-key map
(kbd "5") 'markdown-insert-header-atx-5
)
5346 (define-key map
(kbd "6") 'markdown-insert-header-atx-6
)
5347 (define-key map
(kbd "!") 'markdown-insert-header-setext-1
)
5348 (define-key map
(kbd "@") 'markdown-insert-header-setext-2
)
5349 (define-key map
(kbd "b") 'markdown-insert-bold
)
5350 (define-key map
(kbd "c") 'markdown-insert-code
)
5351 (define-key map
(kbd "C") 'markdown-insert-gfm-code-block
)
5352 (define-key map
(kbd "f") 'markdown-insert-footnote
)
5353 (define-key map
(kbd "F") 'markdown-insert-foldable-block
)
5354 (define-key map
(kbd "h") 'markdown-insert-header-dwim
)
5355 (define-key map
(kbd "H") 'markdown-insert-header-setext-dwim
)
5356 (define-key map
(kbd "i") 'markdown-insert-italic
)
5357 (define-key map
(kbd "k") 'markdown-insert-kbd
)
5358 (define-key map
(kbd "l") 'markdown-insert-link
)
5359 (define-key map
(kbd "p") 'markdown-insert-pre
)
5360 (define-key map
(kbd "P") 'markdown-pre-region
)
5361 (define-key map
(kbd "q") 'markdown-insert-blockquote
)
5362 (define-key map
(kbd "s") 'markdown-insert-strike-through
)
5363 (define-key map
(kbd "t") 'markdown-insert-table
)
5364 (define-key map
(kbd "Q") 'markdown-blockquote-region
)
5365 (define-key map
(kbd "w") 'markdown-insert-wiki-link
)
5366 (define-key map
(kbd "-") 'markdown-insert-hr
)
5367 (define-key map
(kbd "[") 'markdown-insert-gfm-checkbox
)
5368 ;; Deprecated keys that may be removed in a future version
5369 (define-key map
(kbd "e") 'markdown-insert-italic
)
5371 "Keymap for Markdown text styling commands.")
5373 (defvar markdown-mode-command-map
5374 (let ((map (make-keymap (markdown--command-map-prompt))))
5375 (define-key map
(kbd "m") 'markdown-other-window
)
5376 (define-key map
(kbd "p") 'markdown-preview
)
5377 (define-key map
(kbd "e") 'markdown-export
)
5378 (define-key map
(kbd "v") 'markdown-export-and-preview
)
5379 (define-key map
(kbd "o") 'markdown-open
)
5380 (define-key map
(kbd "l") 'markdown-live-preview-mode
)
5381 (define-key map
(kbd "w") 'markdown-kill-ring-save
)
5382 (define-key map
(kbd "c") 'markdown-check-refs
)
5383 (define-key map
(kbd "u") 'markdown-unused-refs
)
5384 (define-key map
(kbd "n") 'markdown-cleanup-list-numbers
)
5385 (define-key map
(kbd "]") 'markdown-complete-buffer
)
5386 (define-key map
(kbd "^") 'markdown-table-sort-lines
)
5387 (define-key map
(kbd "|") 'markdown-table-convert-region
)
5388 (define-key map
(kbd "t") 'markdown-table-transpose
)
5390 "Keymap for Markdown buffer-wide commands.")
5392 (defvar markdown-mode-map
5393 (let ((map (make-keymap)))
5394 ;; Markup insertion & removal
5395 (define-key map
(kbd "C-c C-s") markdown-mode-style-map
)
5396 (define-key map
(kbd "C-c C-l") 'markdown-insert-link
)
5397 (define-key map
(kbd "C-c C-k") 'markdown-kill-thing-at-point
)
5398 ;; Promotion, demotion, and cycling
5399 (define-key map
(kbd "C-c C--") 'markdown-promote
)
5400 (define-key map
(kbd "C-c C-=") 'markdown-demote
)
5401 (define-key map
(kbd "C-c C-]") 'markdown-complete
)
5402 ;; Following and doing things
5403 (define-key map
(kbd "C-c C-o") 'markdown-follow-thing-at-point
)
5404 (define-key map
(kbd "C-c C-d") 'markdown-do
)
5405 (define-key map
(kbd "C-c '") 'markdown-edit-code-block
)
5407 (define-key map
(kbd "RET") 'markdown-enter-key
)
5408 (define-key map
(kbd "DEL") 'markdown-outdent-or-delete
)
5409 (define-key map
(kbd "C-c >") 'markdown-indent-region
)
5410 (define-key map
(kbd "C-c <") 'markdown-outdent-region
)
5411 ;; Visibility cycling
5412 (define-key map
(kbd "TAB") 'markdown-cycle
)
5413 ;; S-iso-lefttab and S-tab should both be mapped to `backtab' by
5414 ;; (local-)function-key-map.
5415 ;;(define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
5416 ;;(define-key map (kbd "<S-tab>") 'markdown-shifttab)
5417 (define-key map
(kbd "<backtab>") 'markdown-shifttab
)
5418 ;; Heading and list navigation
5419 (define-key map
(kbd "C-c C-n") 'markdown-outline-next
)
5420 (define-key map
(kbd "C-c C-p") 'markdown-outline-previous
)
5421 (define-key map
(kbd "C-c C-f") 'markdown-outline-next-same-level
)
5422 (define-key map
(kbd "C-c C-b") 'markdown-outline-previous-same-level
)
5423 (define-key map
(kbd "C-c C-u") 'markdown-outline-up
)
5424 ;; Buffer-wide commands
5425 (define-key map
(kbd "C-c C-c") markdown-mode-command-map
)
5426 ;; Subtree, list, and table editing
5427 (define-key map
(kbd "C-c <up>") 'markdown-move-up
)
5428 (define-key map
(kbd "C-c <down>") 'markdown-move-down
)
5429 (define-key map
(kbd "C-c <left>") 'markdown-promote
)
5430 (define-key map
(kbd "C-c <right>") 'markdown-demote
)
5431 (define-key map
(kbd "C-c S-<up>") 'markdown-table-delete-row
)
5432 (define-key map
(kbd "C-c S-<down>") 'markdown-table-insert-row
)
5433 (define-key map
(kbd "C-c S-<left>") 'markdown-table-delete-column
)
5434 (define-key map
(kbd "C-c S-<right>") 'markdown-table-insert-column
)
5435 (define-key map
(kbd "C-c C-M-h") 'markdown-mark-subtree
)
5436 (define-key map
(kbd "C-x n s") 'markdown-narrow-to-subtree
)
5437 (define-key map
(kbd "M-RET") 'markdown-insert-list-item
)
5438 (define-key map
(kbd "C-c C-j") 'markdown-insert-list-item
)
5439 ;; Paragraphs (Markdown context aware)
5440 (define-key map
[remap backward-paragraph
] 'markdown-backward-paragraph
)
5441 (define-key map
[remap forward-paragraph
] 'markdown-forward-paragraph
)
5442 (define-key map
[remap mark-paragraph
] 'markdown-mark-paragraph
)
5443 ;; Blocks (one or more paragraphs)
5444 (define-key map
(kbd "C-M-{") 'markdown-backward-block
)
5445 (define-key map
(kbd "C-M-}") 'markdown-forward-block
)
5446 (define-key map
(kbd "C-c M-h") 'markdown-mark-block
)
5447 (define-key map
(kbd "C-x n b") 'markdown-narrow-to-block
)
5448 ;; Pages (top-level sections)
5449 (define-key map
[remap backward-page
] 'markdown-backward-page
)
5450 (define-key map
[remap forward-page
] 'markdown-forward-page
)
5451 (define-key map
[remap mark-page
] 'markdown-mark-page
)
5452 (define-key map
[remap narrow-to-page
] 'markdown-narrow-to-page
)
5454 (define-key map
(kbd "M-n") 'markdown-next-link
)
5455 (define-key map
(kbd "M-p") 'markdown-previous-link
)
5456 ;; Toggling functionality
5457 (define-key map
(kbd "C-c C-x C-e") 'markdown-toggle-math
)
5458 (define-key map
(kbd "C-c C-x C-f") 'markdown-toggle-fontify-code-blocks-natively
)
5459 (define-key map
(kbd "C-c C-x C-i") 'markdown-toggle-inline-images
)
5460 (define-key map
(kbd "C-c C-x C-l") 'markdown-toggle-url-hiding
)
5461 (define-key map
(kbd "C-c C-x C-m") 'markdown-toggle-markup-hiding
)
5462 ;; Alternative keys (in case of problems with the arrow keys)
5463 (define-key map
(kbd "C-c C-x u") 'markdown-move-up
)
5464 (define-key map
(kbd "C-c C-x d") 'markdown-move-down
)
5465 (define-key map
(kbd "C-c C-x l") 'markdown-promote
)
5466 (define-key map
(kbd "C-c C-x r") 'markdown-demote
)
5467 ;; Deprecated keys that may be removed in a future version
5468 (define-key map
(kbd "C-c C-a L") 'markdown-insert-link
) ;; C-c C-l
5469 (define-key map
(kbd "C-c C-a l") 'markdown-insert-link
) ;; C-c C-l
5470 (define-key map
(kbd "C-c C-a r") 'markdown-insert-link
) ;; C-c C-l
5471 (define-key map
(kbd "C-c C-a u") 'markdown-insert-uri
) ;; C-c C-l
5472 (define-key map
(kbd "C-c C-a f") 'markdown-insert-footnote
)
5473 (define-key map
(kbd "C-c C-a w") 'markdown-insert-wiki-link
)
5474 (define-key map
(kbd "C-c C-t 1") 'markdown-insert-header-atx-1
)
5475 (define-key map
(kbd "C-c C-t 2") 'markdown-insert-header-atx-2
)
5476 (define-key map
(kbd "C-c C-t 3") 'markdown-insert-header-atx-3
)
5477 (define-key map
(kbd "C-c C-t 4") 'markdown-insert-header-atx-4
)
5478 (define-key map
(kbd "C-c C-t 5") 'markdown-insert-header-atx-5
)
5479 (define-key map
(kbd "C-c C-t 6") 'markdown-insert-header-atx-6
)
5480 (define-key map
(kbd "C-c C-t !") 'markdown-insert-header-setext-1
)
5481 (define-key map
(kbd "C-c C-t @") 'markdown-insert-header-setext-2
)
5482 (define-key map
(kbd "C-c C-t h") 'markdown-insert-header-dwim
)
5483 (define-key map
(kbd "C-c C-t H") 'markdown-insert-header-setext-dwim
)
5484 (define-key map
(kbd "C-c C-t s") 'markdown-insert-header-setext-2
)
5485 (define-key map
(kbd "C-c C-t t") 'markdown-insert-header-setext-1
)
5486 (define-key map
(kbd "C-c C-i") 'markdown-insert-image
)
5487 (define-key map
(kbd "C-c C-x m") 'markdown-insert-list-item
) ;; C-c C-j
5488 (define-key map
(kbd "C-c C-x C-x") 'markdown-toggle-gfm-checkbox
) ;; C-c C-d
5489 (define-key map
(kbd "C-c -") 'markdown-insert-hr
)
5491 "Keymap for Markdown major mode.")
5493 (defvar markdown-mode-mouse-map
5494 (when markdown-mouse-follow-link
5495 (let ((map (make-sparse-keymap)))
5496 (define-key map
[follow-link
] 'mouse-face
)
5497 (define-key map
[mouse-2
] #'markdown-follow-thing-at-point
)
5499 "Keymap for following links with mouse.")
5501 (defvar gfm-mode-map
5502 (let ((map (make-sparse-keymap)))
5503 (set-keymap-parent map markdown-mode-map
)
5504 (define-key map
(kbd "C-c C-s d") 'markdown-insert-strike-through
)
5505 (define-key map
"`" 'markdown-electric-backquote
)
5507 "Keymap for `gfm-mode'.
5508 See also `markdown-mode-map'.")
5511 ;;; Menu ======================================================================
5513 (easy-menu-define markdown-mode-menu markdown-mode-map
5514 "Menu for Markdown mode."
5518 ["Jump" markdown-do
]
5519 ["Follow Link" markdown-follow-thing-at-point
]
5520 ["Next Link" markdown-next-link
]
5521 ["Previous Link" markdown-previous-link
]
5523 ["Next Heading or List Item" markdown-outline-next
]
5524 ["Previous Heading or List Item" markdown-outline-previous
]
5525 ["Next at Same Level" markdown-outline-next-same-level
]
5526 ["Previous at Same Level" markdown-outline-previous-same-level
]
5527 ["Up to Parent" markdown-outline-up
]
5529 ["Forward Paragraph" markdown-forward-paragraph
]
5530 ["Backward Paragraph" markdown-backward-paragraph
]
5531 ["Forward Block" markdown-forward-block
]
5532 ["Backward Block" markdown-backward-block
])
5534 ["Cycle Heading Visibility" markdown-cycle
5535 :enable
(markdown-on-heading-p)]
5536 ["Cycle Heading Visibility (Global)" markdown-shifttab
]
5538 ["Narrow to Region" narrow-to-region
]
5539 ["Narrow to Block" markdown-narrow-to-block
]
5540 ["Narrow to Section" narrow-to-defun
]
5541 ["Narrow to Subtree" markdown-narrow-to-subtree
]
5542 ["Widen" widen
(buffer-narrowed-p)]
5544 ["Toggle Markup Hiding" markdown-toggle-markup-hiding
5547 :selected markdown-hide-markup
])
5549 ("Headings & Structure"
5550 ["Automatic Heading" markdown-insert-header-dwim
5552 ["Automatic Heading (Setext)" markdown-insert-header-setext-dwim
5554 ("Specific Heading (atx)"
5555 ["First Level atx" markdown-insert-header-atx-1
5557 ["Second Level atx" markdown-insert-header-atx-2
5559 ["Third Level atx" markdown-insert-header-atx-3
5561 ["Fourth Level atx" markdown-insert-header-atx-4
5563 ["Fifth Level atx" markdown-insert-header-atx-5
5565 ["Sixth Level atx" markdown-insert-header-atx-6
5567 ("Specific Heading (Setext)"
5568 ["First Level Setext" markdown-insert-header-setext-1
5570 ["Second Level Setext" markdown-insert-header-setext-2
5572 ["Horizontal Rule" markdown-insert-hr
5575 ["Move Subtree Up" markdown-move-up
5577 ["Move Subtree Down" markdown-move-down
5579 ["Promote Subtree" markdown-promote
5581 ["Demote Subtree" markdown-demote
5582 :keys
"C-c <right>"])
5584 ["Indent Region" markdown-indent-region
]
5585 ["Outdent Region" markdown-outdent-region
]
5587 ["Mark Paragraph" mark-paragraph
]
5588 ["Mark Block" markdown-mark-block
]
5589 ["Mark Section" mark-defun
]
5590 ["Mark Subtree" markdown-mark-subtree
])
5592 ["Move Row Up" markdown-move-up
5593 :enable
(markdown-table-at-point-p)
5595 ["Move Row Down" markdown-move-down
5596 :enable
(markdown-table-at-point-p)
5598 ["Move Column Left" markdown-promote
5599 :enable
(markdown-table-at-point-p)
5601 ["Move Column Right" markdown-demote
5602 :enable
(markdown-table-at-point-p)
5603 :keys
"C-c <right>"]
5604 ["Delete Row" markdown-table-delete-row
5605 :enable
(markdown-table-at-point-p)]
5606 ["Insert Row" markdown-table-insert-row
5607 :enable
(markdown-table-at-point-p)]
5608 ["Delete Column" markdown-table-delete-column
5609 :enable
(markdown-table-at-point-p)]
5610 ["Insert Column" markdown-table-insert-column
5611 :enable
(markdown-table-at-point-p)]
5612 ["Insert Table" markdown-insert-table
]
5614 ["Convert Region to Table" markdown-table-convert-region
]
5615 ["Sort Table Lines" markdown-table-sort-lines
5616 :enable
(markdown-table-at-point-p)]
5617 ["Transpose Table" markdown-table-transpose
5618 :enable
(markdown-table-at-point-p)])
5620 ["Insert List Item" markdown-insert-list-item
]
5621 ["Move Subtree Up" markdown-move-up
5623 ["Move Subtree Down" markdown-move-down
5625 ["Indent Subtree" markdown-demote
5626 :keys
"C-c <right>"]
5627 ["Outdent Subtree" markdown-promote
5629 ["Renumber List" markdown-cleanup-list-numbers
]
5630 ["Insert Task List Item" markdown-insert-gfm-checkbox
5632 ["Toggle Task List Item" markdown-toggle-gfm-checkbox
5633 :enable
(markdown-gfm-task-list-item-at-point)
5636 ["Insert Link" markdown-insert-link
]
5637 ["Insert Image" markdown-insert-image
]
5638 ["Insert Footnote" markdown-insert-footnote
5640 ["Insert Wiki Link" markdown-insert-wiki-link
5643 ["Check References" markdown-check-refs
]
5644 ["Find Unused References" markdown-unused-refs
]
5645 ["Toggle URL Hiding" markdown-toggle-url-hiding
5647 :selected markdown-hide-urls
]
5648 ["Toggle Inline Images" markdown-toggle-inline-images
5651 :selected markdown-inline-image-overlays
]
5652 ["Toggle Wiki Links" markdown-toggle-wiki-links
5654 :selected markdown-enable-wiki-links
])
5656 ["Bold" markdown-insert-bold
]
5657 ["Italic" markdown-insert-italic
]
5658 ["Code" markdown-insert-code
]
5659 ["Strikethrough" markdown-insert-strike-through
]
5660 ["Keyboard" markdown-insert-kbd
]
5662 ["Blockquote" markdown-insert-blockquote
]
5663 ["Preformatted" markdown-insert-pre
]
5664 ["GFM Code Block" markdown-insert-gfm-code-block
]
5665 ["Edit Code Block" markdown-edit-code-block
5666 :enable
(markdown-code-block-at-point-p)]
5667 ["Foldable Block" markdown-insert-foldable-block
]
5669 ["Blockquote Region" markdown-blockquote-region
]
5670 ["Preformatted Region" markdown-pre-region
]
5672 ["Fontify Code Blocks Natively"
5673 markdown-toggle-fontify-code-blocks-natively
5675 :selected markdown-fontify-code-blocks-natively
]
5676 ["LaTeX Math Support" markdown-toggle-math
5678 :selected markdown-enable-math
])
5681 ["Compile" markdown-other-window
]
5682 ["Preview" markdown-preview
]
5683 ["Export" markdown-export
]
5684 ["Export & View" markdown-export-and-preview
]
5685 ["Open" markdown-open
]
5686 ["Live Export" markdown-live-preview-mode
5688 :selected markdown-live-preview-mode
]
5689 ["Kill ring save" markdown-kill-ring-save
])
5690 ("Markup Completion and Cycling"
5691 ["Complete Markup" markdown-complete
]
5692 ["Promote Element" markdown-promote
5694 ["Demote Element" markdown-demote
5697 ["Kill Element" markdown-kill-thing-at-point
]
5700 ["Version" markdown-show-version
]
5701 ["Homepage" markdown-mode-info
]
5702 ["Describe Mode" (describe-function 'markdown-mode
)]
5703 ["Guide" (browse-url "https://leanpub.com/markdown-mode")])))
5706 ;;; imenu =====================================================================
5708 (defun markdown-imenu-create-nested-index ()
5709 "Create and return a nested imenu index alist for the current buffer.
5710 See `imenu-create-index-function' and `imenu--index-alist' for details."
5711 (let* ((root '(nil . nil
))
5716 (goto-char (point-min))
5717 (while (re-search-forward markdown-regex-header
(point-max) t
)
5718 (unless (or (markdown-code-block-at-point-p)
5719 (and (match-beginning 3)
5720 (get-text-property (match-beginning 3) 'markdown-yaml-metadata-end
)))
5722 ((match-string-no-properties 2) ;; level 1 setext
5724 (push (list :heading
(match-string-no-properties 1)
5725 :point
(match-beginning 1)
5727 ((match-string-no-properties 3) ;; level 2 setext
5728 (setq min-level
(min min-level
2))
5729 (push (list :heading
(match-string-no-properties 1)
5730 :point
(match-beginning 1)
5731 :level
(- 2 (1- min-level
))) headers
))
5732 ((setq hashes
(markdown-trim-whitespace
5733 (match-string-no-properties 4)))
5734 (setq min-level
(min min-level
(length hashes
)))
5735 (push (list :heading
(match-string-no-properties 5)
5736 :point
(match-beginning 4)
5737 :level
(- (length hashes
) (1- min-level
))) headers
)))))
5738 (cl-loop with cur-level
= 0
5739 with cur-alist
= nil
5740 with empty-heading
= "-"
5741 with self-heading
= "."
5742 for header in
(reverse headers
)
5743 for level
= (plist-get header
:level
)
5745 (let ((alist (list (cons (plist-get header
:heading
) (plist-get header
:point
)))))
5747 ((= cur-level level
) ; new sibling
5748 (setcdr cur-alist alist
)
5749 (setq cur-alist alist
))
5750 ((< cur-level level
) ; first child
5751 (dotimes (_ (- level cur-level
1))
5752 (setq alist
(list (cons empty-heading alist
))))
5754 (let* ((parent (car cur-alist
))
5755 (self-pos (cdr parent
)))
5756 (setcdr parent
(cons (cons self-heading self-pos
) alist
)))
5757 (setcdr root alist
)) ; primogenitor
5758 (setq cur-alist alist
)
5759 (setq cur-level level
))
5760 (t ; new sibling of an ancestor
5761 (let ((sibling-alist (last (cdr root
))))
5762 (dotimes (_ (1- level
))
5763 (setq sibling-alist
(last (cdar sibling-alist
))))
5764 (setcdr sibling-alist alist
)
5765 (setq cur-alist alist
))
5766 (setq cur-level level
)))))
5767 (setq root
(copy-tree root
))
5769 (let ((fn (markdown-get-defined-footnotes)))
5770 (if (or (zerop (length fn
))
5771 (null markdown-add-footnotes-to-imenu
))
5773 (nconc (cdr root
) (list (cons "Footnotes" fn
))))))))
5775 (defun markdown-imenu-create-flat-index ()
5776 "Create and return a flat imenu index alist for the current buffer.
5777 See `imenu-create-index-function' and `imenu--index-alist' for details."
5778 (let* ((empty-heading "-") index heading pos
)
5781 (goto-char (point-min))
5782 (while (re-search-forward markdown-regex-header
(point-max) t
)
5783 (when (and (not (markdown-code-block-at-point-p (point-at-bol)))
5784 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin
)))
5786 ((setq heading
(match-string-no-properties 1))
5787 (setq pos
(match-beginning 1)))
5788 ((setq heading
(match-string-no-properties 5))
5789 (setq pos
(match-beginning 4))))
5790 (or (> (length heading
) 0)
5791 (setq heading empty-heading
))
5792 (setq index
(append index
(list (cons heading pos
))))))
5794 (when markdown-add-footnotes-to-imenu
5795 (nconc index
(markdown-get-defined-footnotes)))
5799 ;;; References ================================================================
5801 (defun markdown-reference-goto-definition ()
5802 "Jump to the definition of the reference at point or create it."
5804 (when (thing-at-point-looking-at markdown-regex-link-reference
)
5805 (let* ((text (match-string-no-properties 3))
5806 (reference (match-string-no-properties 6))
5807 (target (downcase (if (string= reference
"") text reference
)))
5808 (loc (cadr (save-match-data (markdown-reference-definition target
)))))
5811 (goto-char (match-beginning 0))
5812 (markdown-insert-reference-definition target
)))))
5814 (defun markdown-reference-find-links (reference)
5815 "Return a list of all links for REFERENCE.
5816 REFERENCE should not include the surrounding square brackets.
5817 Elements of the list have the form (text start line), where
5818 text is the link text, start is the location at the beginning of
5819 the link, and line is the line number on which the link appears."
5820 (let* ((ref-quote (regexp-quote reference
))
5821 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
5822 ref-quote ref-quote
))
5825 (goto-char (point-min))
5826 (while (re-search-forward regexp nil t
)
5827 (let* ((text (or (match-string-no-properties 1)
5828 (match-string-no-properties 2)))
5829 (start (match-beginning 0))
5830 (line (markdown-line-number-at-pos)))
5831 (cl-pushnew (list text start line
) links
:test
#'equal
))))
5834 (defmacro markdown-for-all-refs
(f)
5837 (goto-char (point-min))
5839 (re-search-forward markdown-regex-link-reference nil t
)
5840 (let* ((text (match-string-no-properties 3))
5841 (reference (match-string-no-properties 6))
5842 (target (downcase (if (string= reference
"") text reference
))))
5843 (,f text target result
))))
5846 (defmacro markdown-collect-always
(_ target result
)
5847 `(cl-pushnew ,target
,result
:test
#'equal
))
5849 (defmacro markdown-collect-undefined
(text target result
)
5850 `(unless (markdown-reference-definition target
)
5851 (let ((entry (assoc ,target
,result
)))
5854 (cons ,target
(list (cons ,text
(markdown-line-number-at-pos))))
5855 ,result
:test
#'equal
)
5857 (append (cdr entry
) (list (cons ,text
(markdown-line-number-at-pos)))))))))
5859 (defun markdown-get-all-refs ()
5860 "Return a list of all Markdown references."
5861 (markdown-for-all-refs markdown-collect-always
))
5863 (defun markdown-get-undefined-refs ()
5864 "Return a list of undefined Markdown references.
5865 Result is an alist of pairs (reference . occurrences), where
5866 occurrences is itself another alist of pairs (label . line-number).
5867 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
5868 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
5869 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
5870 (markdown-for-all-refs markdown-collect-undefined
))
5872 (defun markdown-get-unused-refs ()
5875 (markdown-get-defined-references) (markdown-get-all-refs)
5876 :test
(lambda (e1 e2
) (equal (car e1
) e2
)))
5879 (defmacro defun-markdown-buffer
(name docstring
)
5880 "Define a function to name and return a buffer.
5882 By convention, NAME must be a name of a string constant with
5883 %buffer% placeholder used to name the buffer, and will also be
5884 used as a name of the function defined.
5886 DOCSTRING will be used as the first part of the docstring."
5887 `(defun ,name
(&optional buffer-name
)
5888 ,(concat docstring
"\n\nBUFFER-NAME is the name of the main buffer being visited.")
5889 (or buffer-name
(setq buffer-name
(buffer-name)))
5890 (let ((refbuf (get-buffer-create (replace-regexp-in-string
5891 "%buffer%" buffer-name
5893 (with-current-buffer refbuf
5895 (View-exit-and-edit))
5896 (use-local-map button-buffer-map
)
5900 (defconst markdown-reference-check-buffer
5901 "*Undefined references for %buffer%*"
5902 "Pattern for name of buffer for listing undefined references.
5903 The string %buffer% will be replaced by the corresponding
5904 `markdown-mode' buffer name.")
5906 (defun-markdown-buffer
5907 markdown-reference-check-buffer
5908 "Name and return buffer for reference checking.")
5910 (defconst markdown-unused-references-buffer
5911 "*Unused references for %buffer%*"
5912 "Pattern for name of buffer for listing unused references.
5913 The string %buffer% will be replaced by the corresponding
5914 `markdown-mode' buffer name.")
5916 (defun-markdown-buffer
5917 markdown-unused-references-buffer
5918 "Name and return buffer for unused reference checking.")
5920 (defconst markdown-reference-links-buffer
5921 "*Reference links for %buffer%*"
5922 "Pattern for name of buffer for listing references.
5923 The string %buffer% will be replaced by the corresponding buffer name.")
5925 (defun-markdown-buffer
5926 markdown-reference-links-buffer
5927 "Name, setup, and return a buffer for listing links.")
5929 ;; Add an empty Markdown reference definition to buffer
5930 ;; specified in the 'target-buffer property. The reference name is
5931 ;; the button's label.
5932 (define-button-type 'markdown-undefined-reference-button
5933 'help-echo
"mouse-1, RET: create definition for undefined reference"
5937 (let ((buffer (button-get b
'target-buffer
))
5938 (line (button-get b
'target-line
))
5939 (label (button-label b
)))
5940 (switch-to-buffer-other-window buffer
)
5941 (goto-char (point-min))
5943 (markdown-insert-reference-definition label
)
5944 (markdown-check-refs t
))))
5946 ;; Jump to line in buffer specified by 'target-buffer property.
5947 ;; Line number is button's 'target-line property.
5948 (define-button-type 'markdown-goto-line-button
5949 'help-echo
"mouse-1, RET: go to line"
5953 (switch-to-buffer-other-window (button-get b
'target-buffer
))
5954 ;; use call-interactively to silence compiler
5955 (let ((current-prefix-arg (button-get b
'target-line
)))
5956 (call-interactively 'goto-line
))))
5958 ;; Kill a line in buffer specified by 'target-buffer property.
5959 ;; Line number is button's 'target-line property.
5960 (define-button-type 'markdown-kill-line-button
5961 'help-echo
"mouse-1, RET: kill line"
5965 (switch-to-buffer-other-window (button-get b
'target-buffer
))
5966 ;; use call-interactively to silence compiler
5967 (let ((current-prefix-arg (button-get b
'target-line
)))
5968 (call-interactively 'goto-line
))
5970 (markdown-unused-refs t
)))
5972 ;; Jumps to a particular link at location given by 'target-char
5973 ;; property in buffer given by 'target-buffer property.
5974 (define-button-type 'markdown-location-button
5975 'help-echo
"mouse-1, RET: jump to location of link"
5979 (let ((target (button-get b
'target-buffer
))
5980 (loc (button-get b
'target-char
)))
5981 (kill-buffer-and-window)
5982 (switch-to-buffer target
)
5985 (defun markdown-insert-undefined-reference-button (reference oldbuf
)
5986 "Insert a button for creating REFERENCE in buffer OLDBUF.
5987 REFERENCE should be a list of the form (reference . occurrences),
5988 as returned by `markdown-get-undefined-refs'."
5989 (let ((label (car reference
)))
5990 ;; Create a reference button
5991 (insert-button label
5992 :type
'markdown-undefined-reference-button
5993 'target-buffer oldbuf
5994 'target-line
(cdr (car (cdr reference
))))
5996 (dolist (occurrence (cdr reference
))
5997 (let ((line (cdr occurrence
)))
5998 ;; Create a line number button
5999 (insert-button (number-to-string line
)
6000 :type
'markdown-goto-line-button
6001 'target-buffer oldbuf
6008 (defun markdown-insert-unused-reference-button (reference oldbuf
)
6009 "Insert a button for creating REFERENCE in buffer OLDBUF.
6010 REFERENCE must be a pair of (ref . line-number)."
6011 (let ((label (car reference
))
6012 (line (cdr reference
)))
6013 ;; Create a reference button
6014 (insert-button label
6015 :type
'markdown-goto-line-button
6017 'target-buffer oldbuf
6019 (insert (format " (%d) [" line
))
6021 :type
'markdown-kill-line-button
6023 'target-buffer oldbuf
6028 (defun markdown-insert-link-button (link oldbuf
)
6029 "Insert a button for jumping to LINK in buffer OLDBUF.
6030 LINK should be a list of the form (text char line) containing
6031 the link text, location, and line number."
6032 (let ((label (cl-first link
))
6033 (char (cl-second link
))
6034 (line (cl-third link
)))
6035 ;; Create a reference button
6036 (insert-button label
6037 :type
'markdown-location-button
6038 'target-buffer oldbuf
6040 (insert (format " (line %d)\n" line
))))
6042 (defun markdown-reference-goto-link (&optional reference
)
6043 "Jump to the location of the first use of REFERENCE."
6046 (if (thing-at-point-looking-at markdown-regex-reference-definition
)
6047 (setq reference
(match-string-no-properties 2))
6048 (user-error "No reference definition at point")))
6049 (let ((links (markdown-reference-find-links reference
)))
6050 (cond ((= (length links
) 1)
6051 (goto-char (cadr (car links
))))
6052 ((> (length links
) 1)
6053 (let ((oldbuf (current-buffer))
6054 (linkbuf (markdown-reference-links-buffer)))
6055 (with-current-buffer linkbuf
6056 (insert "Links using reference " reference
":\n\n")
6057 (dolist (link (reverse links
))
6058 (markdown-insert-link-button link oldbuf
)))
6059 (view-buffer-other-window linkbuf
)
6060 (goto-char (point-min))
6063 (error "No links for reference %s" reference
)))))
6065 (defmacro defun-markdown-ref-checker
6066 (name docstring checker-function buffer-function none-message buffer-header insert-reference
)
6067 "Define a function NAME acting on result of CHECKER-FUNCTION.
6069 DOCSTRING is used as a docstring for the defined function.
6071 BUFFER-FUNCTION should name and return an auxiliary buffer to put
6074 NONE-MESSAGE is used when CHECKER-FUNCTION returns no results.
6076 BUFFER-HEADER is put into the auxiliary buffer first, followed by
6077 calling INSERT-REFERENCE for each element in the list returned by
6079 `(defun ,name
(&optional silent
)
6082 "\n\nIf SILENT is non-nil, do not message anything when no
6083 such references found.")
6085 (unless (derived-mode-p 'markdown-mode
)
6086 (user-error "Not available in current mode"))
6087 (let ((oldbuf (current-buffer))
6088 (refs (,checker-function
))
6089 (refbuf (,buffer-function
)))
6093 (message ,none-message
))
6094 (kill-buffer refbuf
))
6095 (with-current-buffer refbuf
6096 (insert ,buffer-header
)
6098 (,insert-reference ref oldbuf
))
6099 (view-buffer-other-window refbuf
)
6100 (goto-char (point-min))
6101 (forward-line 2))))))
6103 (defun-markdown-ref-checker
6105 "Show all undefined Markdown references in current `markdown-mode' buffer.
6107 Links which have empty reference definitions are considered to be
6109 markdown-get-undefined-refs
6110 markdown-reference-check-buffer
6111 "No undefined references found"
6112 "The following references are undefined:\n\n"
6113 markdown-insert-undefined-reference-button
)
6116 (defun-markdown-ref-checker
6117 markdown-unused-refs
6118 "Show all unused Markdown references in current `markdown-mode' buffer."
6119 markdown-get-unused-refs
6120 markdown-unused-references-buffer
6121 "No unused references found"
6122 "The following references are unused:\n\n"
6123 markdown-insert-unused-reference-button
)
6127 ;;; Lists =====================================================================
6129 (defun markdown-insert-list-item (&optional arg
)
6130 "Insert a new list item.
6131 If the point is inside unordered list, insert a bullet mark. If
6132 the point is inside ordered list, insert the next number followed
6133 by a period. Use the previous list item to determine the amount
6134 of whitespace to place before and after list markers.
6136 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
6137 decrease the indentation by one level.
6139 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
6140 increase the indentation by one level."
6142 (let (bounds cur-indent marker indent new-indent new-loc
)
6144 ;; Look for a list item on current or previous non-blank line
6146 (while (and (not (setq bounds
(markdown-cur-list-item-bounds)))
6148 (markdown-cur-line-blank-p))
6151 (cond ((save-excursion
6152 (skip-chars-backward " \t")
6153 (looking-at-p markdown-regex-list
))
6157 ((not (markdown-cur-line-blank-p))
6159 (setq new-loc
(point)))
6160 ;; Look ahead for a list item on next non-blank line
6163 (while (and (null bounds
)
6165 (markdown-cur-line-blank-p))
6167 (setq bounds
(markdown-cur-list-item-bounds))))
6169 (setq new-loc
(point))
6170 (unless (markdown-cur-line-blank-p)
6173 ;; When not in a list, start a new unordered one
6175 (unless (markdown-cur-line-blank-p)
6177 (insert markdown-unordered-list-item-prefix
))
6178 ;; Compute indentation and marker for new list item
6179 (setq cur-indent
(nth 2 bounds
))
6180 (setq marker
(nth 4 bounds
))
6181 ;; If current item is a GFM checkbox, insert new unchecked checkbox.
6182 (when (nth 5 bounds
)
6185 (replace-regexp-in-string "[Xx]" " " (nth 5 bounds
)))))
6187 ;; Dedent: decrement indentation, find previous marker.
6189 (setq indent
(max (- cur-indent markdown-list-indent-width
) 0))
6192 (goto-char (nth 0 bounds
))
6193 (when (markdown-up-list)
6194 (markdown-cur-list-item-bounds)))))
6196 (setq marker
(nth 4 prev-bounds
)))))
6197 ;; Indent: increment indentation by 4, use same marker.
6198 ((= arg
16) (setq indent
(+ cur-indent markdown-list-indent-width
)))
6199 ;; Same level: keep current indentation and marker.
6200 (t (setq indent cur-indent
)))
6201 (setq new-indent
(make-string indent
32))
6205 ((string-match-p "[0-9]" marker
)
6206 (if (= arg
16) ;; starting a new column indented one more level
6207 (insert (concat new-indent
"1. "))
6208 ;; Don't use previous match-data
6209 (set-match-data nil
)
6210 ;; travel up to the last item and pick the correct number. If
6211 ;; the argument was nil, "new-indent = cur-indent" is the same,
6212 ;; so we don't need special treatment. Neat.
6214 (while (and (not (looking-at (concat new-indent
"\\([0-9]+\\)\\(\\.[ \t]*\\)")))
6215 (>= (forward-line -
1) 0))))
6216 (let* ((old-prefix (match-string 1))
6217 (old-spacing (match-string 2))
6218 (new-prefix (if (and old-prefix markdown-ordered-list-enumeration
)
6219 (int-to-string (1+ (string-to-number old-prefix
)))
6221 (space-adjust (- (length old-prefix
) (length new-prefix
)))
6222 (new-spacing (if (and (match-string 2)
6223 (not (string-match-p "\t" old-spacing
))
6225 (> space-adjust
(- 1 (length (match-string 2)))))
6226 (substring (match-string 2) 0 space-adjust
)
6227 (or old-spacing
". "))))
6228 (insert (concat new-indent new-prefix new-spacing
)))))
6229 ;; Unordered list, GFM task list, or ordered list with hash mark
6230 ((string-match-p "[\\*\\+-]\\|#\\." marker
)
6231 (insert new-indent marker
))))
6232 ;; Propertize the newly inserted list item now
6233 (markdown-syntax-propertize-list-items (point-at-bol) (point-at-eol)))))
6235 (defun markdown-move-list-item-up ()
6236 "Move the current list item up in the list when possible.
6237 In nested lists, move child items with the parent item."
6240 (when (setq cur
(markdown-cur-list-item-bounds))
6242 (goto-char (nth 0 cur
))
6243 (if (markdown-prev-list-item (nth 3 cur
))
6245 (setq prev
(markdown-cur-list-item-bounds))
6248 (transpose-regions (nth 0 prev
) (nth 1 prev
)
6249 (nth 0 cur
) (nth 1 cur
) t
)
6250 (goto-char (+ (nth 0 prev
) (- old
(nth 0 cur
)))))
6251 ;; Catch error in case regions overlap.
6252 (error (goto-char old
))))
6255 (defun markdown-move-list-item-down ()
6256 "Move the current list item down in the list when possible.
6257 In nested lists, move child items with the parent item."
6260 (when (setq cur
(markdown-cur-list-item-bounds))
6262 (if (markdown-next-list-item (nth 3 cur
))
6264 (setq next
(markdown-cur-list-item-bounds))
6267 (transpose-regions (nth 0 cur
) (nth 1 cur
)
6268 (nth 0 next
) (nth 1 next
) nil
)
6269 (goto-char (+ old
(- (nth 1 next
) (nth 1 cur
)))))
6270 ;; Catch error in case regions overlap.
6271 (error (goto-char old
))))
6274 (defun markdown-demote-list-item (&optional bounds
)
6275 "Indent (or demote) the current list item.
6276 Optionally, BOUNDS of the current list item may be provided if available.
6277 In nested lists, demote child items as well."
6279 (when (or bounds
(setq bounds
(markdown-cur-list-item-bounds)))
6281 (let* ((item-start (set-marker (make-marker) (nth 0 bounds
)))
6282 (item-end (set-marker (make-marker) (nth 1 bounds
)))
6283 (list-start (progn (markdown-beginning-of-list)
6284 (set-marker (make-marker) (point))))
6285 (list-end (progn (markdown-end-of-list)
6286 (set-marker (make-marker) (point)))))
6287 (goto-char item-start
)
6288 (while (< (point) item-end
)
6289 (unless (markdown-cur-line-blank-p)
6290 (insert (make-string markdown-list-indent-width ?
)))
6292 (markdown-syntax-propertize-list-items list-start list-end
)))))
6294 (defun markdown-promote-list-item (&optional bounds
)
6295 "Unindent (or promote) the current list item.
6296 Optionally, BOUNDS of the current list item may be provided if available.
6297 In nested lists, demote child items as well."
6299 (when (or bounds
(setq bounds
(markdown-cur-list-item-bounds)))
6302 (let ((item-start (set-marker (make-marker) (nth 0 bounds
)))
6303 (item-end (set-marker (make-marker) (nth 1 bounds
)))
6304 (list-start (progn (markdown-beginning-of-list)
6305 (set-marker (make-marker) (point))))
6306 (list-end (progn (markdown-end-of-list)
6307 (set-marker (make-marker) (point))))
6309 (goto-char item-start
)
6310 (when (looking-at (format "^[ ]\\{1,%d\\}"
6311 markdown-list-indent-width
))
6312 (setq num
(- (match-end 0) (match-beginning 0)))
6313 (setq regexp
(format "^[ ]\\{1,%d\\}" num
))
6314 (while (and (< (point) item-end
)
6315 (re-search-forward regexp item-end t
))
6316 (replace-match "" nil nil
)
6318 (markdown-syntax-propertize-list-items list-start list-end
)))))))
6320 (defun markdown-cleanup-list-numbers-level (&optional pfx prev-item
)
6321 "Update the numbering for level PFX (as a string of spaces) and PREV-ITEM.
6322 PREV-ITEM is width of previous-indentation and list number
6324 Assume that the previously found match was for a numbered item in
6332 (while (and continue
(not (eobp)))
6335 ((looking-at "^\\(\\([\s-]*\\)[0-9]+\\)\\. ")
6336 (setq cpfx
(match-string-no-properties 2))
6337 (setq cur-item
(match-string-no-properties 1)) ;; indentation and list marker
6339 ((or (= (length cpfx
) (length pfx
))
6340 (= (length cur-item
) (length prev-item
)))
6343 (if (not markdown-ordered-list-enumeration
)
6346 (concat pfx
(number-to-string idx
) ". "))))
6349 ((< (length pfx
) (length cpfx
))
6350 (setq sep
(markdown-cleanup-list-numbers-level cpfx cur-item
))
6355 (setq continue nil
))))
6357 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
6358 (setq cpfx
(match-string-no-properties 1))
6360 ;; reset if separated before
6361 ((string= cpfx pfx
) (when sep
(setq idx
0)))
6364 (setq continue nil
))))
6369 (setq continue
(= (forward-line) 0))))
6372 (defun markdown-cleanup-list-numbers ()
6373 "Update the numbering of ordered lists."
6376 (goto-char (point-min))
6377 (markdown-cleanup-list-numbers-level "")))
6380 ;;; Movement ==================================================================
6382 (defun markdown-beginning-of-defun (&optional arg
)
6383 "`beginning-of-defun-function' for Markdown.
6384 This is used to find the beginning of the defun and should behave
6385 like ‘beginning-of-defun’, returning non-nil if it found the
6386 beginning of a defun. It moves the point backward, right before a
6387 heading which defines a defun. When ARG is non-nil, repeat that
6388 many times. When ARG is negative, move forward to the ARG-th
6390 (or arg
(setq arg
1))
6391 (when (< arg
0) (end-of-line))
6392 ;; Adjust position for setext headings.
6393 (when (and (thing-at-point-looking-at markdown-regex-header-setext
)
6394 (not (= (point) (match-beginning 0)))
6395 (not (markdown-code-block-at-point-p)))
6396 (goto-char (match-end 0)))
6398 ;; Move backward with positive argument.
6399 (while (and (not (bobp)) (> arg
0))
6401 (while (and (not found
)
6403 (re-search-backward markdown-regex-header nil
'move
))
6404 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6405 (setq found
(match-beginning 0)))
6406 (setq arg
(1- arg
)))
6407 ;; Move forward with negative argument.
6408 (while (and (not (eobp)) (< arg
0))
6410 (while (and (not found
)
6412 (re-search-forward markdown-regex-header nil
'move
))
6413 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6414 (setq found
(match-beginning 0)))
6415 (setq arg
(1+ arg
)))
6420 (defun markdown-end-of-defun ()
6421 "`end-of-defun-function’ for Markdown.
6422 This is used to find the end of the defun at point.
6423 It is called with no argument, right after calling ‘beginning-of-defun-raw’,
6424 so it can assume that point is at the beginning of the defun body.
6425 It should move point to the first position after the defun."
6426 (or (eobp) (forward-char 1))
6428 (while (and (not found
)
6430 (re-search-forward markdown-regex-header nil
'move
))
6431 (when (not (markdown-code-block-at-pos (match-beginning 0)))
6432 (setq found
(match-beginning 0))))
6435 (skip-syntax-backward "-"))))
6437 (defun markdown-beginning-of-text-block ()
6438 "Move backward to previous beginning of a plain text block.
6439 This function simply looks for blank lines without considering
6440 the surrounding context in light of Markdown syntax. For that, see
6441 `markdown-backward-block'."
6443 (let ((start (point)))
6444 (if (re-search-backward markdown-regex-block-separator nil t
)
6445 (goto-char (match-end 0))
6446 (goto-char (point-min)))
6447 (when (and (= start
(point)) (not (bobp)))
6449 (if (re-search-backward markdown-regex-block-separator nil t
)
6450 (goto-char (match-end 0))
6451 (goto-char (point-min))))))
6453 (defun markdown-end-of-text-block ()
6454 "Move forward to next beginning of a plain text block.
6455 This function simply looks for blank lines without considering
6456 the surrounding context in light of Markdown syntax. For that, see
6457 `markdown-forward-block'."
6460 (skip-chars-forward " \t\n")
6461 (when (= (point) (point-min))
6463 (if (re-search-forward markdown-regex-block-separator nil t
)
6464 (goto-char (match-end 0))
6465 (goto-char (point-max)))
6466 (skip-chars-backward " \t\n")
6469 (defun markdown-backward-paragraph (&optional arg
)
6470 "Move the point to the start of the current paragraph.
6471 With argument ARG, do it ARG times; a negative argument ARG = -N
6472 means move forward N blocks."
6474 (or arg
(setq arg
1))
6476 (markdown-forward-paragraph (- arg
))
6478 ;; Skip over whitespace in between paragraphs when moving backward.
6479 (skip-chars-backward " \t\n")
6481 ;; Skip over code block endings.
6482 (when (markdown-range-properties-exist
6483 (point-at-bol) (point-at-eol)
6484 '(markdown-gfm-block-end
6485 markdown-tilde-fence-end
))
6487 ;; Skip over blank lines inside blockquotes.
6488 (while (and (not (eobp))
6489 (looking-at markdown-regex-blockquote
)
6490 (= (length (match-string 3)) 0))
6492 ;; Proceed forward based on the type of block of paragraph.
6496 ((looking-at markdown-regex-blockquote
)
6497 (while (and (not (bobp))
6498 (looking-at markdown-regex-blockquote
)
6499 (> (length (match-string 3)) 0)) ;; not blank
6503 ((setq bounds
(markdown-cur-list-item-bounds))
6504 (goto-char (nth 0 bounds
)))
6507 (while (and (not (bobp))
6509 (not (markdown-cur-line-blank-p))
6510 (not (looking-at markdown-regex-blockquote
))
6511 (not (markdown-range-properties-exist
6512 (point-at-bol) (point-at-eol)
6513 '(markdown-gfm-block-end
6514 markdown-tilde-fence-end
))))
6515 (setq skip
(markdown-range-properties-exist
6516 (point-at-bol) (point-at-eol)
6517 '(markdown-gfm-block-begin
6518 markdown-tilde-fence-begin
)))
6521 (forward-line 1))))))))
6523 (defun markdown-forward-paragraph (&optional arg
)
6524 "Move forward to the next end of a paragraph.
6525 With argument ARG, do it ARG times; a negative argument ARG = -N
6526 means move backward N blocks."
6528 (or arg
(setq arg
1))
6530 (markdown-backward-paragraph (- arg
))
6532 ;; Skip whitespace in between paragraphs.
6533 (when (markdown-cur-line-blank-p)
6534 (skip-syntax-forward "-")
6535 (beginning-of-line))
6536 ;; Proceed forward based on the type of block.
6540 ((looking-at markdown-regex-blockquote
)
6541 ;; Skip over blank lines inside blockquotes.
6542 (while (and (not (eobp))
6543 (looking-at markdown-regex-blockquote
)
6544 (= (length (match-string 3)) 0))
6546 ;; Move to end of quoted text block
6547 (while (and (not (eobp))
6548 (looking-at markdown-regex-blockquote
)
6549 (> (length (match-string 3)) 0)) ;; not blank
6552 ((and (markdown-cur-list-item-bounds)
6553 (setq bounds
(markdown-next-list-item-bounds)))
6554 (goto-char (nth 0 bounds
)))
6558 (while (and (not (eobp))
6560 (not (markdown-cur-line-blank-p))
6561 (not (looking-at markdown-regex-blockquote
))
6562 (not (markdown-range-properties-exist
6563 (point-at-bol) (point-at-eol)
6564 '(markdown-gfm-block-begin
6565 markdown-tilde-fence-begin
))))
6566 (setq skip
(markdown-range-properties-exist
6567 (point-at-bol) (point-at-eol)
6568 '(markdown-gfm-block-end
6569 markdown-tilde-fence-end
)))
6570 (forward-line))))))))
6572 (defun markdown-backward-block (&optional arg
)
6573 "Move the point to the start of the current Markdown block.
6574 Moves across complete code blocks, list items, and blockquotes,
6575 but otherwise stops at blank lines, headers, and horizontal
6576 rules. With argument ARG, do it ARG times; a negative argument
6577 ARG = -N means move forward N blocks."
6579 (or arg
(setq arg
1))
6581 (markdown-forward-block (- arg
))
6583 ;; Skip over whitespace in between blocks when moving backward,
6584 ;; unless at a block boundary with no whitespace.
6585 (skip-syntax-backward "-")
6587 ;; Proceed forward based on the type of block.
6590 ((and (markdown-code-block-at-pos (point)) ;; this line
6591 (markdown-code-block-at-pos (point-at-bol 0))) ;; previous line
6593 (while (and (markdown-code-block-at-point-p) (not (bobp)))
6597 ((markdown-heading-at-point)
6598 (goto-char (match-beginning 0)))
6600 ((looking-at markdown-regex-hr
))
6602 ((looking-at markdown-regex-blockquote
)
6604 (while (and (looking-at markdown-regex-blockquote
)
6609 ((markdown-cur-list-item-bounds)
6610 (markdown-beginning-of-list))
6613 ;; Move forward in case it is a one line regular paragraph.
6614 (unless (markdown-next-line-blank-p)
6616 (unless (markdown-prev-line-blank-p)
6617 (markdown-backward-paragraph)))))))
6619 (defun markdown-forward-block (&optional arg
)
6620 "Move forward to the next end of a Markdown block.
6621 Moves across complete code blocks, list items, and blockquotes,
6622 but otherwise stops at blank lines, headers, and horizontal
6623 rules. With argument ARG, do it ARG times; a negative argument
6624 ARG = -N means move backward N blocks."
6626 (or arg
(setq arg
1))
6628 (markdown-backward-block (- arg
))
6630 ;; Skip over whitespace in between blocks when moving forward.
6631 (if (markdown-cur-line-blank-p)
6632 (skip-syntax-forward "-")
6633 (beginning-of-line))
6634 ;; Proceed forward based on the type of block.
6637 ((markdown-code-block-at-point-p)
6639 (while (and (markdown-code-block-at-point-p) (not (eobp)))
6642 ((looking-at markdown-regex-header
)
6643 (goto-char (or (match-end 4) (match-end 2) (match-end 3)))
6646 ((looking-at markdown-regex-hr
)
6649 ((looking-at markdown-regex-blockquote
)
6651 (while (and (looking-at markdown-regex-blockquote
) (not (eobp)))
6654 ((markdown-cur-list-item-bounds)
6655 (markdown-end-of-list)
6658 (t (markdown-forward-paragraph))))
6659 (skip-syntax-backward "-")
6663 (defun markdown-backward-page (&optional count
)
6664 "Move backward to boundary of the current toplevel section.
6665 With COUNT, repeat, or go forward if negative."
6667 (or count
(setq count
1))
6669 (markdown-forward-page (- count
))
6670 (skip-syntax-backward "-")
6671 (or (markdown-back-to-heading-over-code-block t t
)
6672 (goto-char (point-min)))
6673 (when (looking-at markdown-regex-header
)
6674 (let ((level (markdown-outline-level)))
6675 (when (> level
1) (markdown-up-heading level
))
6678 (markdown-backward-same-level (1- count
))
6679 (error (goto-char (point-min)))))))))
6681 (defun markdown-forward-page (&optional count
)
6682 "Move forward to boundary of the current toplevel section.
6683 With COUNT, repeat, or go backward if negative."
6685 (or count
(setq count
1))
6687 (markdown-backward-page (- count
))
6688 (if (markdown-back-to-heading-over-code-block t t
)
6689 (let ((level (markdown-outline-level)))
6690 (when (> level
1) (markdown-up-heading level
))
6692 (markdown-forward-same-level count
)
6693 (error (goto-char (point-max)))))
6694 (markdown-next-visible-heading 1))))
6696 (defun markdown-next-link ()
6697 "Jump to next inline, reference, or wiki link.
6698 If successful, return point. Otherwise, return nil.
6699 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
6701 (let ((opoint (point)))
6702 (when (or (markdown-link-p) (markdown-wiki-link-p))
6703 ;; At a link already, move past it.
6704 (goto-char (+ (match-end 0) 1)))
6705 ;; Search for the next wiki link and move to the beginning.
6706 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t
)
6707 (markdown-code-block-at-point-p)
6708 (< (point) (point-max))))
6709 (if (and (not (eq (point) opoint
))
6710 (or (markdown-link-p) (markdown-wiki-link-p)))
6711 ;; Group 1 will move past non-escape character in wiki link regexp.
6712 ;; Go to beginning of group zero for all other link types.
6713 (goto-char (or (match-beginning 1) (match-beginning 0)))
6717 (defun markdown-previous-link ()
6718 "Jump to previous wiki link.
6719 If successful, return point. Otherwise, return nil.
6720 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
6722 (let ((opoint (point)))
6723 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t
)
6724 (markdown-code-block-at-point-p)
6725 (> (point) (point-min))))
6726 (if (and (not (eq (point) opoint
))
6727 (or (markdown-link-p) (markdown-wiki-link-p)))
6728 (goto-char (or (match-beginning 1) (match-beginning 0)))
6733 ;;; Outline ===================================================================
6735 (defun markdown-move-heading-common (move-fn &optional arg adjust
)
6736 "Wrapper for `outline-mode' functions to skip false positives.
6737 MOVE-FN is a function and ARG is its argument. For example,
6738 headings inside preformatted code blocks may match
6739 `outline-regexp' but should not be considered as headings.
6740 When ADJUST is non-nil, adjust the point for interactive calls
6741 to avoid leaving the point at invisible markup. This adjustment
6742 generally should only be done for interactive calls, since other
6743 functions may expect the point to be at the beginning of the
6744 regular expression."
6745 (let ((prev -
1) (start (point)))
6746 (if arg
(funcall move-fn arg
) (funcall move-fn
))
6747 (while (and (/= prev
(point)) (markdown-code-block-at-point-p))
6749 (if arg
(funcall move-fn arg
) (funcall move-fn
)))
6750 ;; Adjust point for setext headings and invisible text.
6752 (when (and adjust
(thing-at-point-looking-at markdown-regex-header
))
6753 (if markdown-hide-markup
6754 ;; Move to beginning of heading text if markup is hidden.
6755 (goto-char (or (match-beginning 1) (match-beginning 5)))
6756 ;; Move to beginning of markup otherwise.
6757 (goto-char (or (match-beginning 1) (match-beginning 4))))))
6758 (if (= (point) start
) nil
(point))))
6760 (defun markdown-next-visible-heading (arg)
6761 "Move to the next visible heading line of any level.
6762 With argument, repeats or can move backward if negative. ARG is
6763 passed to `outline-next-visible-heading'."
6765 (markdown-move-heading-common #'outline-next-visible-heading arg
'adjust
))
6767 (defun markdown-previous-visible-heading (arg)
6768 "Move to the previous visible heading line of any level.
6769 With argument, repeats or can move backward if negative. ARG is
6770 passed to `outline-previous-visible-heading'."
6772 (markdown-move-heading-common #'outline-previous-visible-heading arg
'adjust
))
6774 (defun markdown-next-heading ()
6775 "Move to the next heading line of any level."
6776 (markdown-move-heading-common #'outline-next-heading
))
6778 (defun markdown-previous-heading ()
6779 "Move to the previous heading line of any level."
6780 (markdown-move-heading-common #'outline-previous-heading
))
6782 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok no-error
)
6783 "Move back to the beginning of the previous heading.
6784 Returns t if the point is at a heading, the location if a heading
6785 was found, and nil otherwise.
6786 Only visible heading lines are considered, unless INVISIBLE-OK is
6787 non-nil. Throw an error if there is no previous heading unless
6788 NO-ERROR is non-nil.
6789 Leaves match data intact for `markdown-regex-header'."
6791 (or (and (markdown-heading-at-point)
6792 (not (markdown-code-block-at-point-p)))
6795 (while (and (not found
)
6796 (re-search-backward markdown-regex-header nil t
))
6797 (when (and (or invisible-ok
(not (outline-invisible-p)))
6798 (not (markdown-code-block-at-point-p)))
6799 (setq found
(point))))
6801 (unless no-error
(user-error "Before first heading"))
6802 (setq found
(point))))
6803 (when found
(goto-char found
)))))
6805 (defun markdown-forward-same-level (arg)
6806 "Move forward to the ARG'th heading at same level as this one.
6807 Stop at the first and last headings of a superior heading."
6809 (markdown-back-to-heading-over-code-block)
6810 (markdown-move-heading-common #'outline-forward-same-level arg
'adjust
))
6812 (defun markdown-backward-same-level (arg)
6813 "Move backward to the ARG'th heading at same level as this one.
6814 Stop at the first and last headings of a superior heading."
6816 (markdown-back-to-heading-over-code-block)
6818 (let ((point-to-move-to
6820 (markdown-move-heading-common #'outline-get-last-sibling nil
'adjust
))))
6821 (if point-to-move-to
6823 (goto-char point-to-move-to
)
6824 (setq arg
(1- arg
)))
6825 (user-error "No previous same-level heading")))))
6827 (defun markdown-up-heading (arg &optional interactive
)
6828 "Move to the visible heading line of which the present line is a subheading.
6829 With argument, move up ARG levels. When called interactively (or
6830 INTERACTIVE is non-nil), also push the mark."
6831 (interactive "p\np")
6832 (and interactive
(not (eq last-command
'markdown-up-heading
))
6834 (markdown-move-heading-common #'outline-up-heading arg
'adjust
))
6836 (defun markdown-back-to-heading (&optional invisible-ok
)
6837 "Move to previous heading line, or beg of this line if it's a heading.
6838 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
6840 (markdown-move-heading-common #'outline-back-to-heading invisible-ok
))
6842 (defalias 'markdown-end-of-heading
'outline-end-of-heading
)
6844 (defun markdown-on-heading-p ()
6845 "Return non-nil if point is on a heading line."
6846 (get-text-property (point-at-bol) 'markdown-heading
))
6848 (defun markdown-end-of-subtree (&optional invisible-OK
)
6849 "Move to the end of the current subtree.
6850 Only visible heading lines are considered, unless INVISIBLE-OK is
6852 Derived from `org-end-of-subtree'."
6853 (markdown-back-to-heading invisible-OK
)
6855 (level (markdown-outline-level)))
6856 (while (and (not (eobp))
6857 (or first
(> (markdown-outline-level) level
)))
6859 (markdown-next-heading))
6860 (if (memq (preceding-char) '(?
\n ?\^M
))
6862 ;; Go to end of line before heading
6864 (if (memq (preceding-char) '(?
\n ?\^M
))
6865 ;; leave blank line before heading
6866 (forward-char -
1)))))
6869 (defun markdown-outline-fix-visibility ()
6870 "Hide any false positive headings that should not be shown.
6871 For example, headings inside preformatted code blocks may match
6872 `outline-regexp' but should not be shown as headings when cycling.
6873 Also, the ending --- line in metadata blocks appears to be a
6874 setext header, but should not be folded."
6876 (goto-char (point-min))
6877 ;; Unhide any false positives in metadata blocks
6878 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin
)
6879 (let ((body (progn (forward-line)
6880 (markdown-text-property-at-point
6881 'markdown-yaml-metadata-section
))))
6883 (let ((end (progn (goto-char (cl-second body
))
6884 (markdown-text-property-at-point
6885 'markdown-yaml-metadata-end
))))
6886 (outline-flag-region (point-min) (1+ (cl-second end
)) nil
)))))
6887 ;; Hide any false positives in code blocks
6888 (unless (outline-on-heading-p)
6889 (outline-next-visible-heading 1))
6890 (while (< (point) (point-max))
6891 (when (markdown-code-block-at-point-p)
6892 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t
))
6893 (outline-next-visible-heading 1))))
6895 (defvar markdown-cycle-global-status
1)
6896 (defvar markdown-cycle-subtree-status nil
)
6898 (defun markdown-next-preface ()
6900 (while (and (not finish
) (re-search-forward (concat "\n\\(?:" outline-regexp
"\\)")
6902 (unless (markdown-code-block-at-point-p)
6903 (goto-char (match-beginning 0))
6905 (when (and (bolp) (or outline-blank-line
(eobp)) (not (bobp)))
6908 (defun markdown-show-entry ()
6910 (outline-back-to-heading t
)
6911 (outline-flag-region (1- (point))
6913 (markdown-next-preface)
6914 (if (= 1 (- (point-max) (point)))
6919 ;; This function was originally derived from `org-cycle' from org.el.
6920 (defun markdown-cycle (&optional arg
)
6921 "Visibility cycling for Markdown mode.
6922 This function is called with a `\\[universal-argument]' or if ARG is t, perform
6923 global visibility cycling. If the point is at an atx-style header, cycle
6924 visibility of the corresponding subtree. Otherwise, indent the current line
6925 or insert a tab, as appropriate, by calling `indent-for-tab-command'."
6932 ;; Move from overview to contents
6933 ((and (eq last-command this-command
)
6934 (eq markdown-cycle-global-status
2))
6935 (outline-hide-sublevels 1)
6936 (message "CONTENTS")
6937 (setq markdown-cycle-global-status
3)
6938 (markdown-outline-fix-visibility))
6939 ;; Move from contents to all
6940 ((and (eq last-command this-command
)
6941 (eq markdown-cycle-global-status
3))
6943 (message "SHOW ALL")
6944 (setq markdown-cycle-global-status
1))
6945 ;; Defaults to overview
6948 (message "OVERVIEW")
6949 (setq markdown-cycle-global-status
2)
6950 (markdown-outline-fix-visibility))))
6952 ;; At a heading: rotate between three different views
6953 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
6954 (markdown-back-to-heading)
6955 (let ((goal-column 0) eoh eol eos
)
6956 ;; Determine boundaries
6958 (markdown-back-to-heading)
6960 (beginning-of-line 2)
6961 (while (and (not (eobp)) ;; this is like `next-line'
6962 (get-char-property (1- (point)) 'invisible
))
6963 (beginning-of-line 2)) (setq eol
(point)))
6964 (markdown-end-of-heading) (setq eoh
(point))
6965 (markdown-end-of-subtree t
)
6966 (skip-chars-forward " \t\n")
6967 (beginning-of-line 1) ; in case this is an item
6968 (setq eos
(1- (point))))
6969 ;; Find out what to do next and set `this-command'
6971 ;; Nothing is hidden behind this heading
6973 (message "EMPTY ENTRY")
6974 (setq markdown-cycle-subtree-status nil
))
6975 ;; Entire subtree is hidden in one line: open it
6977 (markdown-show-entry)
6978 (outline-show-children)
6979 (message "CHILDREN")
6980 (setq markdown-cycle-subtree-status
'children
))
6981 ;; We just showed the children, now show everything.
6982 ((and (eq last-command this-command
)
6983 (eq markdown-cycle-subtree-status
'children
))
6984 (outline-show-subtree)
6986 (setq markdown-cycle-subtree-status
'subtree
))
6987 ;; Default action: hide the subtree.
6989 (outline-hide-subtree)
6991 (setq markdown-cycle-subtree-status
'folded
)))))
6993 ;; In a table, move forward by one cell
6994 ((markdown-table-at-point-p)
6995 (call-interactively #'markdown-table-forward-cell
))
6997 ;; Otherwise, indent as appropriate
6999 (indent-for-tab-command))))
7001 (defun markdown-shifttab ()
7002 "Handle S-TAB keybinding based on context.
7003 When in a table, move backward one cell.
7004 Otherwise, cycle global heading visibility by calling
7005 `markdown-cycle' with argument t."
7007 (cond ((markdown-table-at-point-p)
7008 (call-interactively #'markdown-table-backward-cell
))
7009 (t (markdown-cycle t
))))
7011 (defun markdown-outline-level ()
7012 "Return the depth to which a statement is nested in the outline."
7014 ((and (match-beginning 0)
7015 (markdown-code-block-at-pos (match-beginning 0)))
7016 7) ;; Only 6 header levels are defined.
7020 (length (markdown-trim-whitespace (match-string-no-properties 4))))))
7022 (defun markdown-promote-subtree (&optional arg
)
7023 "Promote the current subtree of ATX headings.
7024 Note that Markdown does not support heading levels higher than
7025 six and therefore level-six headings will not be promoted
7026 further. If ARG is non-nil promote the heading, otherwise
7030 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx
)
7031 (re-search-backward markdown-regex-header-atx nil t
))
7032 (not (markdown-code-block-at-point-p)))
7033 (let ((level (length (match-string 1)))
7034 (promote-or-demote (if arg
1 -
1))
7036 (markdown-cycle-atx promote-or-demote remove
)
7037 (catch 'end-of-subtree
7038 (while (and (markdown-next-heading)
7039 (looking-at markdown-regex-header-atx
))
7040 ;; Exit if this not a higher level heading; promote otherwise.
7041 (if (and (looking-at markdown-regex-header-atx
)
7042 (<= (length (match-string-no-properties 1)) level
))
7043 (throw 'end-of-subtree nil
)
7044 (markdown-cycle-atx promote-or-demote remove
))))))))
7046 (defun markdown-demote-subtree ()
7047 "Demote the current subtree of ATX headings."
7049 (markdown-promote-subtree t
))
7051 (defun markdown-move-subtree-up ()
7052 "Move the current subtree of ATX headings up."
7054 (outline-move-subtree-up 1))
7056 (defun markdown-move-subtree-down ()
7057 "Move the current subtree of ATX headings down."
7059 (outline-move-subtree-down 1))
7061 (defun markdown-outline-next ()
7062 "Move to next list item, when in a list, or next visible heading."
7064 (let ((bounds (markdown-next-list-item-bounds)))
7066 (goto-char (nth 0 bounds
))
7067 (markdown-next-visible-heading 1))))
7069 (defun markdown-outline-previous ()
7070 "Move to previous list item, when in a list, or previous visible heading."
7072 (let ((bounds (markdown-prev-list-item-bounds)))
7074 (goto-char (nth 0 bounds
))
7075 (markdown-previous-visible-heading 1))))
7077 (defun markdown-outline-next-same-level ()
7078 "Move to next list item or heading of same level."
7080 (let ((bounds (markdown-cur-list-item-bounds)))
7082 (markdown-next-list-item (nth 3 bounds
))
7083 (markdown-forward-same-level 1))))
7085 (defun markdown-outline-previous-same-level ()
7086 "Move to previous list item or heading of same level."
7088 (let ((bounds (markdown-cur-list-item-bounds)))
7090 (markdown-prev-list-item (nth 3 bounds
))
7091 (markdown-backward-same-level 1))))
7093 (defun markdown-outline-up ()
7094 "Move to previous list item, when in a list, or previous heading."
7096 (unless (markdown-up-list)
7097 (markdown-up-heading 1)))
7100 ;;; Marking and Narrowing =====================================================
7102 (defun markdown-mark-paragraph ()
7103 "Put mark at end of this block, point at beginning.
7104 The block marked is the one that contains point or follows point.
7106 Interactively, if this command is repeated or (in Transient Mark
7107 mode) if the mark is active, it marks the next block after the
7108 ones already marked."
7110 (if (or (and (eq last-command this-command
) (mark t
))
7111 (and transient-mark-mode mark-active
))
7115 (markdown-forward-paragraph)
7117 (let ((beginning-of-defun-function #'markdown-backward-paragraph
)
7118 (end-of-defun-function #'markdown-forward-paragraph
))
7121 (defun markdown-mark-block ()
7122 "Put mark at end of this block, point at beginning.
7123 The block marked is the one that contains point or follows point.
7125 Interactively, if this command is repeated or (in Transient Mark
7126 mode) if the mark is active, it marks the next block after the
7127 ones already marked."
7129 (if (or (and (eq last-command this-command
) (mark t
))
7130 (and transient-mark-mode mark-active
))
7134 (markdown-forward-block)
7136 (let ((beginning-of-defun-function #'markdown-backward-block
)
7137 (end-of-defun-function #'markdown-forward-block
))
7140 (defun markdown-narrow-to-block ()
7141 "Make text outside current block invisible.
7142 The current block is the one that contains point or follows point."
7144 (let ((beginning-of-defun-function #'markdown-backward-block
)
7145 (end-of-defun-function #'markdown-forward-block
))
7148 (defun markdown-mark-text-block ()
7149 "Put mark at end of this plain text block, point at beginning.
7150 The block marked is the one that contains point or follows point.
7152 Interactively, if this command is repeated or (in Transient Mark
7153 mode) if the mark is active, it marks the next block after the
7154 ones already marked."
7156 (if (or (and (eq last-command this-command
) (mark t
))
7157 (and transient-mark-mode mark-active
))
7161 (markdown-end-of-text-block)
7163 (let ((beginning-of-defun-function #'markdown-beginning-of-text-block
)
7164 (end-of-defun-function #'markdown-end-of-text-block
))
7167 (defun markdown-mark-page ()
7168 "Put mark at end of this top level section, point at beginning.
7169 The top level section marked is the one that contains point or
7172 Interactively, if this command is repeated or (in Transient Mark
7173 mode) if the mark is active, it marks the next page after the
7174 ones already marked."
7176 (if (or (and (eq last-command this-command
) (mark t
))
7177 (and transient-mark-mode mark-active
))
7181 (markdown-forward-page)
7183 (let ((beginning-of-defun-function #'markdown-backward-page
)
7184 (end-of-defun-function #'markdown-forward-page
))
7187 (defun markdown-narrow-to-page ()
7188 "Make text outside current top level section invisible.
7189 The current section is the one that contains point or follows point."
7191 (let ((beginning-of-defun-function #'markdown-backward-page
)
7192 (end-of-defun-function #'markdown-forward-page
))
7195 (defun markdown-mark-subtree ()
7196 "Mark the current subtree.
7197 This puts point at the start of the current subtree, and mark at the end."
7200 (if (markdown-heading-at-point)
7202 (markdown-previous-visible-heading 1))
7204 (markdown-end-of-subtree)
7205 (push-mark (point) nil t
)
7208 (defun markdown-narrow-to-subtree ()
7209 "Narrow buffer to the current subtree."
7214 (progn (markdown-back-to-heading-over-code-block t
) (point))
7215 (progn (markdown-end-of-subtree)
7216 (if (and (markdown-heading-at-point) (not (eobp)))
7221 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
7223 (defun markdown-move-up ()
7224 "Move thing at point up.
7225 When in a list item, call `markdown-move-list-item-up'.
7226 When in a table, call `markdown-table-move-row-up'.
7227 Otherwise, move the current heading subtree up with
7228 `markdown-move-subtree-up'."
7231 ((markdown-list-item-at-point-p)
7232 (call-interactively #'markdown-move-list-item-up
))
7233 ((markdown-table-at-point-p)
7234 (call-interactively #'markdown-table-move-row-up
))
7236 (call-interactively #'markdown-move-subtree-up
))))
7238 (defun markdown-move-down ()
7239 "Move thing at point down.
7240 When in a list item, call `markdown-move-list-item-down'.
7241 Otherwise, move the current heading subtree up with
7242 `markdown-move-subtree-down'."
7245 ((markdown-list-item-at-point-p)
7246 (call-interactively #'markdown-move-list-item-down
))
7247 ((markdown-table-at-point-p)
7248 (call-interactively #'markdown-table-move-row-down
))
7250 (call-interactively #'markdown-move-subtree-down
))))
7252 (defun markdown-promote ()
7253 "Promote or move element at point to the left.
7254 Depending on the context, this function will promote a heading or
7255 list item at the point, move a table column to the left, or cycle
7260 ;; Promote atx heading subtree
7261 ((thing-at-point-looking-at markdown-regex-header-atx
)
7262 (markdown-promote-subtree))
7263 ;; Promote setext heading
7264 ((thing-at-point-looking-at markdown-regex-header-setext
)
7265 (markdown-cycle-setext -
1))
7266 ;; Promote horizontal rule
7267 ((thing-at-point-looking-at markdown-regex-hr
)
7268 (markdown-cycle-hr -
1))
7269 ;; Promote list item
7270 ((setq bounds
(markdown-cur-list-item-bounds))
7271 (markdown-promote-list-item bounds
))
7272 ;; Move table column to the left
7273 ((markdown-table-at-point-p)
7274 (call-interactively #'markdown-table-move-column-left
))
7276 ((thing-at-point-looking-at markdown-regex-bold
)
7277 (markdown-cycle-bold))
7279 ((thing-at-point-looking-at markdown-regex-italic
)
7280 (markdown-cycle-italic))
7282 (user-error "Nothing to promote at point")))))
7284 (defun markdown-demote ()
7285 "Demote or move element at point to the right.
7286 Depending on the context, this function will demote a heading or
7287 list item at the point, move a table column to the right, or cycle
7292 ;; Demote atx heading subtree
7293 ((thing-at-point-looking-at markdown-regex-header-atx
)
7294 (markdown-demote-subtree))
7295 ;; Demote setext heading
7296 ((thing-at-point-looking-at markdown-regex-header-setext
)
7297 (markdown-cycle-setext 1))
7298 ;; Demote horizontal rule
7299 ((thing-at-point-looking-at markdown-regex-hr
)
7300 (markdown-cycle-hr 1))
7302 ((setq bounds
(markdown-cur-list-item-bounds))
7303 (markdown-demote-list-item bounds
))
7304 ;; Move table column to the right
7305 ((markdown-table-at-point-p)
7306 (call-interactively #'markdown-table-move-column-right
))
7308 ((thing-at-point-looking-at markdown-regex-bold
)
7309 (markdown-cycle-bold))
7311 ((thing-at-point-looking-at markdown-regex-italic
)
7312 (markdown-cycle-italic))
7314 (user-error "Nothing to demote at point")))))
7317 ;;; Commands ==================================================================
7319 (defun markdown (&optional output-buffer-name
)
7320 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
7321 The output buffer name defaults to `markdown-output-buffer-name'.
7322 Return the name of the output buffer used."
7324 (save-window-excursion
7325 (let* ((commands (cond ((stringp markdown-command
) (split-string markdown-command
))
7326 ((listp markdown-command
) markdown-command
)))
7327 (command (car-safe commands
))
7328 (command-args (cdr-safe commands
))
7329 begin-region end-region
)
7331 (setq begin-region
(region-beginning)
7332 end-region
(region-end))
7333 (setq begin-region
(point-min)
7334 end-region
(point-max)))
7336 (unless output-buffer-name
7337 (setq output-buffer-name markdown-output-buffer-name
))
7338 (when (and (stringp command
) (not (executable-find command
)))
7339 (user-error "Markdown command %s is not found" command
))
7342 ;; Handle case when `markdown-command' does not read from stdin
7343 ((and (stringp command
) markdown-command-needs-filename
)
7344 (if (not buffer-file-name
)
7345 (user-error "Must be visiting a file")
7346 ;; Don’t use ‘shell-command’ because it’s not guaranteed to
7347 ;; return the exit code of the process.
7348 (let ((command (if (listp markdown-command
)
7349 (string-join markdown-command
" ")
7351 (shell-command-on-region
7352 ;; Pass an empty region so that stdin is empty.
7355 (shell-quote-argument buffer-file-name
))
7356 output-buffer-name
))))
7357 ;; Pass region to `markdown-command' via stdin
7359 (let ((buf (get-buffer-create output-buffer-name
)))
7360 (with-current-buffer buf
7361 (setq buffer-read-only nil
)
7363 (if (stringp command
)
7364 (if (not (null command-args
))
7365 (apply #'call-process-region begin-region end-region command nil buf nil command-args
)
7366 (call-process-region begin-region end-region command nil buf
))
7367 (if markdown-command-needs-filename
7368 (if (not buffer-file-name
)
7369 (user-error "Must be visiting a file")
7370 (funcall markdown-command begin-region end-region buf buffer-file-name
))
7371 (funcall markdown-command begin-region end-region buf
))
7372 ;; If the ‘markdown-command’ function didn’t signal an
7373 ;; error, assume it succeeded by binding ‘exit-code’ to 0.
7375 ;; The exit code can be a signal description string, so don’t use ‘=’
7377 (unless (eq exit-code
0)
7378 (user-error "%s failed with exit code %s"
7379 markdown-command exit-code
))))
7380 output-buffer-name
))
7382 (defun markdown-standalone (&optional output-buffer-name
)
7383 "Special function to provide standalone HTML output.
7384 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
7386 (setq output-buffer-name
(markdown output-buffer-name
))
7387 (with-current-buffer output-buffer-name
7388 (set-buffer output-buffer-name
)
7389 (unless (markdown-output-standalone-p)
7390 (markdown-add-xhtml-header-and-footer output-buffer-name
))
7391 (goto-char (point-min))
7395 (defun markdown-other-window (&optional output-buffer-name
)
7396 "Run `markdown-command' on current buffer and display in other window.
7397 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7400 (markdown-display-buffer-other-window
7401 (markdown-standalone output-buffer-name
)))
7403 (defun markdown-output-standalone-p ()
7404 "Determine whether `markdown-command' output is standalone XHTML.
7405 Standalone XHTML output is identified by an occurrence of
7406 `markdown-xhtml-standalone-regexp' in the first five lines of output."
7408 (goto-char (point-min))
7411 markdown-xhtml-standalone-regexp
7412 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
7415 (defun markdown-stylesheet-link-string (stylesheet-path)
7416 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
7417 (or (and (string-prefix-p "~" stylesheet-path
)
7418 (expand-file-name stylesheet-path
))
7422 (defun markdown-add-xhtml-header-and-footer (title)
7423 "Wrap XHTML header and footer with given TITLE around current buffer."
7424 (goto-char (point-min))
7425 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
7426 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
7427 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
7428 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
7431 (insert "</title>\n")
7432 (unless (= (length markdown-content-type
) 0)
7435 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
7436 markdown-content-type
7437 (or (and markdown-coding-system
7438 (coding-system-get markdown-coding-system
7440 (coding-system-get buffer-file-coding-system
7443 (if (> (length markdown-css-paths
) 0)
7444 (insert (mapconcat #'markdown-stylesheet-link-string
7445 markdown-css-paths
"\n")))
7446 (when (> (length markdown-xhtml-header-content
) 0)
7447 (insert markdown-xhtml-header-content
))
7448 (insert "\n</head>\n\n"
7450 (when (> (length markdown-xhtml-body-preamble
) 0)
7451 (insert markdown-xhtml-body-preamble
"\n"))
7452 (goto-char (point-max))
7453 (when (> (length markdown-xhtml-body-epilogue
) 0)
7454 (insert "\n" markdown-xhtml-body-epilogue
))
7459 (defun markdown-preview (&optional output-buffer-name
)
7460 "Run `markdown-command' on the current buffer and view output in browser.
7461 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7464 (browse-url-of-buffer
7465 (markdown-standalone (or output-buffer-name markdown-output-buffer-name
))))
7467 (defun markdown-export-file-name (&optional extension
)
7468 "Attempt to generate a filename for Markdown output.
7469 The file extension will be EXTENSION if given, or .html by default.
7470 If the current buffer is visiting a file, we construct a new
7471 output filename based on that filename. Otherwise, return nil."
7472 (when (buffer-file-name)
7474 (setq extension
".html"))
7479 (file-name-sans-extension (buffer-file-name)))
7483 ((equal candidate
(buffer-file-name))
7484 (concat candidate extension
))
7488 (defun markdown-export (&optional output-file
)
7489 "Run Markdown on the current buffer, save to file, and return the filename.
7490 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
7491 generated by `markdown-export-file-name', which will be constructed using the
7492 current filename, but with the extension removed and replaced with .html."
7495 (setq output-file
(markdown-export-file-name ".html")))
7497 (let* ((init-buf (current-buffer))
7498 (init-point (point))
7499 (init-buf-string (buffer-string))
7500 (output-buffer (find-file-noselect output-file
))
7501 (output-buffer-name (buffer-name output-buffer
)))
7502 (run-hooks 'markdown-before-export-hook
)
7503 (markdown-standalone output-buffer-name
)
7504 (with-current-buffer output-buffer
7505 (run-hooks 'markdown-after-export-hook
)
7507 (when markdown-export-kill-buffer
(kill-buffer)))
7508 ;; if modified, restore initial buffer
7509 (when (buffer-modified-p init-buf
)
7511 (insert init-buf-string
)
7513 (goto-char init-point
))
7516 (defun markdown-export-and-preview ()
7517 "Export to XHTML using `markdown-export' and browse the resulting file."
7519 (browse-url-of-file (markdown-export)))
7521 (defvar-local markdown-live-preview-buffer nil
7522 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
7524 (defvar-local markdown-live-preview-source-buffer nil
7525 "Source buffer from which current buffer was generated.
7526 This is the inverse of `markdown-live-preview-buffer'.")
7528 (defvar markdown-live-preview-currently-exporting nil
)
7530 (defun markdown-live-preview-get-filename ()
7531 "Standardize the filename exported by `markdown-live-preview-export'."
7532 (markdown-export-file-name ".html"))
7534 (defun markdown-live-preview-window-eww (file)
7535 "Preview FILE with eww.
7536 To be used with `markdown-live-preview-window-function'."
7537 (eww-open-file file
)
7538 (get-buffer "*eww*"))
7540 (defun markdown-visual-lines-between-points (beg end
)
7543 (cl-loop with count
= 0
7544 while
(progn (end-of-visual-line)
7545 (and (< (point) end
) (line-move-visual 1 t
)))
7547 finally return count
)))
7549 (defun markdown-live-preview-window-serialize (buf)
7550 "Get window point and scroll data for all windows displaying BUF."
7551 (when (buffer-live-p buf
)
7552 (with-current-buffer buf
7555 (with-selected-window win
7556 (let* ((start (window-start))
7558 (pt-or-sym (cond ((= pt
(point-min)) 'min
)
7559 ((= pt
(point-max)) 'max
)
7561 (diff (markdown-visual-lines-between-points
7563 (list win pt-or-sym diff
))))
7564 (get-buffer-window-list buf
)))))
7566 (defun markdown-get-point-back-lines (pt num-lines
)
7569 (line-move-visual (- num-lines
) t
)
7570 ;; in testing, can occasionally overshoot the number of lines to traverse
7571 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt
)))
7572 (when (> actual-num-lines num-lines
)
7573 (line-move-visual (- actual-num-lines num-lines
) t
)))
7576 (defun markdown-live-preview-window-deserialize (window-posns)
7577 "Apply window point and scroll data from WINDOW-POSNS.
7578 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
7579 (cl-destructuring-bind (win pt-or-sym diff
) window-posns
7580 (when (window-live-p win
)
7581 (with-current-buffer markdown-live-preview-buffer
7582 (set-window-buffer win
(current-buffer))
7583 (cl-destructuring-bind (actual-pt actual-diff
)
7585 (min (list (point-min) 0))
7586 (max (list (point-max) diff
))
7587 (t (list pt-or-sym diff
)))
7589 win
(markdown-get-point-back-lines actual-pt actual-diff
))
7590 (set-window-point win actual-pt
))))))
7592 (defun markdown-live-preview-export ()
7593 "Export to XHTML using `markdown-export'.
7594 Browse the resulting file within Emacs using
7595 `markdown-live-preview-window-function' Return the buffer
7596 displaying the rendered output."
7598 (let ((filename (markdown-live-preview-get-filename)))
7600 (let* ((markdown-live-preview-currently-exporting t
)
7601 (cur-buf (current-buffer))
7602 (export-file (markdown-export filename
))
7603 ;; get positions in all windows currently displaying output buffer
7605 (markdown-live-preview-window-serialize
7606 markdown-live-preview-buffer
)))
7607 (save-window-excursion
7608 (let ((output-buffer
7609 (funcall markdown-live-preview-window-function export-file
)))
7610 (with-current-buffer output-buffer
7611 (setq markdown-live-preview-source-buffer cur-buf
)
7612 (add-hook 'kill-buffer-hook
7613 #'markdown-live-preview-remove-on-kill t t
))
7614 (with-current-buffer cur-buf
7615 (setq markdown-live-preview-buffer output-buffer
))))
7616 (with-current-buffer cur-buf
7617 ;; reset all windows displaying output buffer to where they were,
7618 ;; now with the new output
7619 (mapc #'markdown-live-preview-window-deserialize window-data
)
7620 ;; delete html editing buffer
7621 (let ((buf (get-file-buffer export-file
))) (when buf
(kill-buffer buf
)))
7622 (when (and export-file
(file-exists-p export-file
)
7623 (eq markdown-live-preview-delete-export
7625 (delete-file export-file
))
7626 markdown-live-preview-buffer
)))))
7628 (defun markdown-live-preview-remove ()
7629 (when (buffer-live-p markdown-live-preview-buffer
)
7630 (kill-buffer markdown-live-preview-buffer
))
7631 (setq markdown-live-preview-buffer nil
)
7632 ;; if set to 'delete-on-export, the output has already been deleted
7633 (when (eq markdown-live-preview-delete-export
'delete-on-destroy
)
7634 (let ((outfile-name (markdown-live-preview-get-filename)))
7635 (when (and outfile-name
(file-exists-p outfile-name
))
7636 (delete-file outfile-name
)))))
7638 (defun markdown-get-other-window ()
7639 "Find another window to display preview or output content."
7641 ((memq markdown-split-window-direction
'(vertical below
))
7642 (or (window-in-direction 'below
) (split-window-vertically)))
7643 ((memq markdown-split-window-direction
'(horizontal right
))
7644 (or (window-in-direction 'right
) (split-window-horizontally)))
7645 (t (split-window-sensibly (get-buffer-window)))))
7647 (defun markdown-display-buffer-other-window (buf)
7648 "Display preview or output buffer BUF in another window."
7649 (if (and display-buffer-alist
(eq markdown-split-window-direction
'any
))
7650 (display-buffer buf
)
7651 (let ((cur-buf (current-buffer))
7652 (window (markdown-get-other-window)))
7653 (set-window-buffer window buf
)
7654 (set-buffer cur-buf
))))
7656 (defun markdown-live-preview-if-markdown ()
7657 (when (and (derived-mode-p 'markdown-mode
)
7658 markdown-live-preview-mode
)
7659 (unless markdown-live-preview-currently-exporting
7660 (if (buffer-live-p markdown-live-preview-buffer
)
7661 (markdown-live-preview-export)
7662 (markdown-display-buffer-other-window
7663 (markdown-live-preview-export))))))
7665 (defun markdown-live-preview-remove-on-kill ()
7666 (cond ((and (derived-mode-p 'markdown-mode
)
7667 markdown-live-preview-mode
)
7668 (markdown-live-preview-remove))
7669 (markdown-live-preview-source-buffer
7670 (with-current-buffer markdown-live-preview-source-buffer
7671 (setq markdown-live-preview-buffer nil
))
7672 (setq markdown-live-preview-source-buffer nil
))))
7674 (defun markdown-live-preview-switch-to-output ()
7675 "Switch to output buffer."
7677 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
7678 output buffer in another window."
7679 (if markdown-live-preview-mode
7680 (markdown-display-buffer-other-window (markdown-live-preview-export)))
7681 (markdown-live-preview-mode))
7683 (defun markdown-live-preview-re-export ()
7684 "Re export source buffer."
7686 "If the current buffer is a buffer displaying the exported version of a
7687 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
7688 update this buffer's contents."
7689 (when markdown-live-preview-source-buffer
7690 (with-current-buffer markdown-live-preview-source-buffer
7691 (markdown-live-preview-export))))
7693 (defun markdown-open ()
7694 "Open file for the current buffer with `markdown-open-command'."
7696 (unless markdown-open-command
7697 (user-error "Variable `markdown-open-command' must be set"))
7698 (if (stringp markdown-open-command
)
7699 (if (not buffer-file-name
)
7700 (user-error "Must be visiting a file")
7702 (let ((exit-code (call-process markdown-open-command nil nil nil
7704 ;; The exit code can be a signal description string, so don’t use ‘=’
7706 (unless (eq exit-code
0)
7707 (user-error "%s failed with exit code %s"
7708 markdown-open-command exit-code
))))
7709 (funcall markdown-open-command
))
7712 (defun markdown-kill-ring-save ()
7713 "Run Markdown on file and store output in the kill ring."
7715 (save-window-excursion
7717 (with-current-buffer markdown-output-buffer-name
7718 (kill-ring-save (point-min) (point-max)))))
7721 ;;; Links =====================================================================
7723 (defun markdown-backward-to-link-start ()
7724 "Backward link start position if current position is in link title."
7726 (when (eq (get-text-property (point) 'face
) 'markdown-link-face
)
7727 (skip-chars-backward "^[")
7730 (defun markdown-link-p ()
7731 "Return non-nil when `point' is at a non-wiki link.
7732 See `markdown-wiki-link-p' for more information."
7734 (let ((case-fold-search nil
))
7735 (when (and (not (markdown-wiki-link-p)) (not (markdown-code-block-at-point-p)))
7736 (markdown-backward-to-link-start)
7737 (or (thing-at-point-looking-at markdown-regex-link-inline
)
7738 (thing-at-point-looking-at markdown-regex-link-reference
)
7739 (thing-at-point-looking-at markdown-regex-uri
)
7740 (thing-at-point-looking-at markdown-regex-angle-uri
))))))
7742 (defun markdown-link-at-pos (pos)
7743 "Return properties of link or image at position POS.
7744 Value is a list of elements describing the link:
7745 0. beginning position
7751 6. bang (nil or \"!\")"
7754 (markdown-backward-to-link-start)
7755 (let (begin end text url reference title bang
)
7757 ;; Inline image or link at point.
7758 ((thing-at-point-looking-at markdown-regex-link-inline
)
7759 (setq bang
(match-string-no-properties 1)
7760 begin
(match-beginning 0)
7762 text
(match-string-no-properties 3)
7763 url
(match-string-no-properties 6))
7765 (setq title
(substring (match-string-no-properties 7) 1 -
1))
7766 ;; #408 URL contains close parenthesis case
7767 (goto-char (match-beginning 5))
7768 (let ((paren-end (scan-sexps (point) 1)))
7769 (when (and paren-end
(< end paren-end
))
7770 (setq url
(buffer-substring (match-beginning 6) (1- paren-end
)))))))
7771 ;; Reference link at point.
7772 ((or (thing-at-point-looking-at markdown-regex-link-inline
)
7773 (thing-at-point-looking-at markdown-regex-link-reference
))
7774 (setq bang
(match-string-no-properties 1)
7775 begin
(match-beginning 0)
7777 text
(match-string-no-properties 3))
7778 (when (char-equal (char-after (match-beginning 5)) ?\
[)
7779 (setq reference
(match-string-no-properties 6))))
7780 ;; Angle bracket URI at point.
7781 ((thing-at-point-looking-at markdown-regex-angle-uri
)
7782 (setq begin
(match-beginning 0)
7784 url
(match-string-no-properties 2)))
7785 ;; Plain URI at point.
7786 ((thing-at-point-looking-at markdown-regex-uri
)
7787 (setq begin
(match-beginning 0)
7789 url
(match-string-no-properties 1))))
7790 (list begin end text url reference title bang
))))
7792 (defun markdown-link-url ()
7793 "Return the URL part of the regular (non-wiki) link at point.
7794 Works with both inline and reference style links, and with images.
7795 If point is not at a link or the link reference is not defined
7797 (let* ((values (markdown-link-at-pos (point)))
7798 (text (nth 2 values
))
7799 (url (nth 3 values
))
7800 (ref (nth 4 values
)))
7801 (or url
(and ref
(car (markdown-reference-definition
7802 (downcase (if (string= ref
"") text ref
))))))))
7804 (defun markdown--browse-url (url)
7805 (let* ((struct (url-generic-parse-url url
))
7806 (full (url-fullness struct
))
7808 ;; Parse URL, determine fullness, strip query string
7809 (setq file
(car (url-path-and-query struct
)))
7810 ;; Open full URLs in browser, files in Emacs
7813 (when (and file
(> (length file
) 0))
7814 (let ((link-file (funcall markdown-translate-filename-function file
)))
7815 (if (and markdown-open-image-command
(string-match-p (image-file-name-regexp) link-file
))
7816 (if (functionp markdown-open-image-command
)
7817 (funcall markdown-open-image-command link-file
)
7818 (process-file markdown-open-image-command nil nil nil link-file
))
7819 (find-file link-file
)))))))
7821 (defun markdown-follow-link-at-point (&optional event
)
7822 "Open the non-wiki link at point or EVENT.
7823 If the link is a complete URL, open in browser with `browse-url'.
7824 Otherwise, open with `find-file' after stripping anchor and/or query string.
7825 Translate filenames using `markdown-filename-translate-function'."
7826 (interactive (list last-command-event
))
7828 (if event
(posn-set-point (event-start event
)))
7829 (if (markdown-link-p)
7830 (markdown--browse-url (markdown-link-url))
7831 (user-error "Point is not at a Markdown link or URL"))))
7833 (defun markdown-fontify-inline-links (last)
7834 "Add text properties to next inline link from point to LAST."
7835 (when (markdown-match-generic-links last nil
)
7836 (let* ((link-start (match-beginning 3))
7837 (link-end (match-end 3))
7838 (url-start (match-beginning 6))
7839 (url-end (match-end 6))
7840 (url (match-string-no-properties 6))
7841 (title-start (match-beginning 7))
7842 (title-end (match-end 7))
7843 (title (match-string-no-properties 7))
7845 (mp (list 'face
'markdown-markup-face
7846 'invisible
'markdown-markup
7848 'font-lock-multiline t
))
7849 ;; Link part (without face)
7850 (lp (list 'keymap markdown-mode-mouse-map
7851 'mouse-face
'markdown-highlight-face
7852 'font-lock-multiline t
7853 'help-echo
(if title
(concat title
"\n" url
) url
)))
7855 (up (list 'keymap markdown-mode-mouse-map
7856 'face
'markdown-url-face
7857 'invisible
'markdown-markup
7858 'mouse-face
'markdown-highlight-face
7859 'font-lock-multiline t
))
7860 ;; URL composition character
7861 (url-char (markdown--first-displayable markdown-url-compose-char
))
7863 (tp (list 'face
'markdown-link-title-face
7864 'invisible
'markdown-markup
7865 'font-lock-multiline t
)))
7866 (dolist (g '(1 2 4 5 8))
7868 (add-text-properties (match-beginning g
) (match-end g
) mp
)))
7869 ;; Preserve existing faces applied to link part (e.g., inline code)
7871 (add-text-properties link-start link-end lp
)
7872 (add-face-text-property link-start link-end
7873 'markdown-link-face
'append
))
7874 (when url-start
(add-text-properties url-start url-end up
))
7875 (when title-start
(add-text-properties url-end title-end tp
))
7876 (when (and markdown-hide-urls url-start
)
7877 (compose-region url-start
(or title-end url-end
) url-char
))
7880 (defun markdown-fontify-reference-links (last)
7881 "Add text properties to next reference link from point to LAST."
7882 (when (markdown-match-generic-links last t
)
7883 (let* ((link-start (match-beginning 3))
7884 (link-end (match-end 3))
7885 (ref-start (match-beginning 6))
7886 (ref-end (match-end 6))
7888 (mp (list 'face
'markdown-markup-face
7889 'invisible
'markdown-markup
7891 'font-lock-multiline t
))
7893 (lp (list 'keymap markdown-mode-mouse-map
7894 'face
'markdown-link-face
7895 'mouse-face
'markdown-highlight-face
7896 'font-lock-multiline t
7897 'help-echo
(lambda (_ __ pos
)
7901 (or (markdown-link-url)
7902 "Undefined reference"))))))
7903 ;; URL composition character
7904 (url-char (markdown--first-displayable markdown-url-compose-char
))
7906 (rp (list 'face
'markdown-reference-face
7907 'invisible
'markdown-markup
7908 'font-lock-multiline t
)))
7909 (dolist (g '(1 2 4 5 8))
7911 (add-text-properties (match-beginning g
) (match-end g
) mp
)))
7912 (when link-start
(add-text-properties link-start link-end lp
))
7913 (when ref-start
(add-text-properties ref-start ref-end rp
)
7914 (when (and markdown-hide-urls
(> (- ref-end ref-start
) 2))
7915 (compose-region ref-start ref-end url-char
)))
7918 (defun markdown-fontify-angle-uris (last)
7919 "Add text properties to angle URIs from point to LAST."
7920 (when (markdown-match-angle-uris last
)
7921 (let* ((url-start (match-beginning 2))
7922 (url-end (match-end 2))
7924 (mp (list 'face
'markdown-markup-face
7925 'invisible
'markdown-markup
7927 'font-lock-multiline t
))
7929 (up (list 'keymap markdown-mode-mouse-map
7930 'face
'markdown-plain-url-face
7931 'mouse-face
'markdown-highlight-face
7932 'font-lock-multiline t
)))
7934 (add-text-properties (match-beginning g
) (match-end g
) mp
))
7935 (add-text-properties url-start url-end up
)
7938 (defun markdown-fontify-plain-uris (last)
7939 "Add text properties to plain URLs from point to LAST."
7940 (when (markdown-match-plain-uris last
)
7941 (let* ((start (match-beginning 0))
7943 (props (list 'keymap markdown-mode-mouse-map
7944 'face
'markdown-plain-url-face
7945 'mouse-face
'markdown-highlight-face
7947 'font-lock-multiline t
)))
7948 (add-text-properties start end props
)
7951 (defun markdown-toggle-url-hiding (&optional arg
)
7952 "Toggle the display or hiding of URLs.
7953 With a prefix argument ARG, enable URL hiding if ARG is positive,
7954 and disable it otherwise."
7955 (interactive (list (or current-prefix-arg
'toggle
)))
7956 (setq markdown-hide-urls
7957 (if (eq arg
'toggle
)
7958 (not markdown-hide-urls
)
7959 (> (prefix-numeric-value arg
) 0)))
7960 (if markdown-hide-urls
7961 (message "markdown-mode URL hiding enabled")
7962 (message "markdown-mode URL hiding disabled"))
7963 (markdown-reload-extensions))
7966 ;;; Wiki Links ================================================================
7968 (defun markdown-wiki-link-p ()
7969 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
7970 A true wiki link name matches `markdown-regex-wiki-link' but does
7971 not match the current file name after conversion. This modifies
7972 the data returned by `match-data'. Note that the potential wiki
7973 link name must be available via `match-string'."
7974 (when markdown-enable-wiki-links
7975 (let ((case-fold-search nil
))
7976 (and (thing-at-point-looking-at markdown-regex-wiki-link
)
7977 (not (markdown-code-block-at-point-p))
7978 (or (not buffer-file-name
)
7979 (not (string-equal (buffer-file-name)
7980 (markdown-convert-wiki-link-to-filename
7981 (markdown-wiki-link-link)))))))))
7983 (defun markdown-wiki-link-link ()
7984 "Return the link part of the wiki link using current match data.
7985 The location of the link component depends on the value of
7986 `markdown-wiki-link-alias-first'."
7987 (if markdown-wiki-link-alias-first
7988 (or (match-string-no-properties 5) (match-string-no-properties 3))
7989 (match-string-no-properties 3)))
7991 (defun markdown-wiki-link-alias ()
7992 "Return the alias or text part of the wiki link using current match data.
7993 The location of the alias component depends on the value of
7994 `markdown-wiki-link-alias-first'."
7995 (if markdown-wiki-link-alias-first
7996 (match-string-no-properties 3)
7997 (or (match-string-no-properties 5) (match-string-no-properties 3))))
7999 (defun markdown--wiki-link-search-types ()
8000 (let ((ret (and markdown-wiki-link-search-type
8001 (cl-copy-list markdown-wiki-link-search-type
))))
8002 (when (and markdown-wiki-link-search-subdirectories
8003 (not (memq 'sub-directories markdown-wiki-link-search-type
)))
8004 (push 'sub-directories ret
))
8005 (when (and markdown-wiki-link-search-parent-directories
8006 (not (memq 'parent-directories markdown-wiki-link-search-type
)))
8007 (push 'parent-directories ret
))
8010 (defun markdown--project-root ()
8011 (or (cl-loop for dir in
'(".git" ".hg" ".svn")
8012 when
(locate-dominating-file default-directory dir
)
8016 (let ((project (project-current t
)))
8018 (if (fboundp 'project-root
)
8019 (project-root project
)
8020 (car (project-roots project
))))))))
8022 (defun markdown-convert-wiki-link-to-filename (name)
8023 "Generate a filename from the wiki link NAME.
8024 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
8025 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
8026 and [[test test]] both map to Test-test.ext. Look in the current
8027 directory first, then in subdirectories if
8028 `markdown-wiki-link-search-subdirectories' is non-nil, and then
8029 in parent directories if
8030 `markdown-wiki-link-search-parent-directories' is non-nil."
8032 ;; This function must not overwrite match data(PR #590)
8033 (let* ((basename (replace-regexp-in-string
8034 "[[:space:]\n]" markdown-link-space-sub-char name
))
8035 (basename (if (derived-mode-p 'gfm-mode
)
8036 (concat (upcase (substring basename
0 1))
8037 (downcase (substring basename
1 nil
)))
8039 (search-types (markdown--wiki-link-search-types))
8040 directory extension default candidates dir
)
8041 (when buffer-file-name
8042 (setq directory
(file-name-directory buffer-file-name
)
8043 extension
(file-name-extension buffer-file-name
)))
8044 (setq default
(concat basename
8045 (when extension
(concat "." extension
))))
8047 ;; Look in current directory first.
8048 ((or (null buffer-file-name
)
8049 (file-exists-p default
))
8051 ;; Possibly search in subdirectories, next.
8052 ((and (memq 'sub-directories search-types
)
8054 (directory-files-recursively
8055 directory
(concat "^" default
"$"))))
8057 ;; Possibly search in parent directories as a last resort.
8058 ((and (memq 'parent-directories search-types
)
8059 (setq dir
(locate-dominating-file directory default
)))
8060 (concat dir default
))
8061 ((and (memq 'project search-types
)
8063 (directory-files-recursively
8064 (markdown--project-root) (concat "^" default
"$"))))
8066 ;; If nothing is found, return default in current directory.
8069 (defun markdown-follow-wiki-link (name &optional other
)
8070 "Follow the wiki link NAME.
8071 Convert the name to a file name and call `find-file'. Ensure that
8072 the new buffer remains in `markdown-mode'. Open the link in another
8073 window when OTHER is non-nil."
8074 (let ((filename (markdown-convert-wiki-link-to-filename name
))
8075 (wp (when buffer-file-name
8076 (file-name-directory buffer-file-name
))))
8078 (user-error "Must be visiting a file")
8079 (when other
(other-window 1))
8080 (let ((default-directory wp
))
8081 (find-file filename
)))
8082 (unless (derived-mode-p 'markdown-mode
)
8085 (defun markdown-follow-wiki-link-at-point (&optional arg
)
8086 "Find Wiki Link at point.
8087 With prefix argument ARG, open the file in other window.
8088 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
8090 (if (markdown-wiki-link-p)
8091 (markdown-follow-wiki-link (markdown-wiki-link-link) arg
)
8092 (user-error "Point is not at a Wiki Link")))
8094 (defun markdown-highlight-wiki-link (from to face
)
8095 "Highlight the wiki link in the region between FROM and TO using FACE."
8096 (put-text-property from to
'font-lock-face face
))
8098 (defun markdown-unfontify-region-wiki-links (from to
)
8099 "Remove wiki link faces from the region specified by FROM and TO."
8101 (let ((modified (buffer-modified-p)))
8102 (remove-text-properties from to
'(font-lock-face markdown-link-face
))
8103 (remove-text-properties from to
'(font-lock-face markdown-missing-link-face
))
8104 ;; remove-text-properties marks the buffer modified in emacs 24.3,
8105 ;; undo that if it wasn't originally marked modified
8106 (set-buffer-modified-p modified
)))
8108 (defun markdown-fontify-region-wiki-links (from to
)
8109 "Search region given by FROM and TO for wiki links and fontify them.
8110 If a wiki link is found check to see if the backing file exists
8111 and highlight accordingly."
8114 (while (re-search-forward markdown-regex-wiki-link to t
)
8115 (when (not (markdown-code-block-at-point-p))
8116 (let ((highlight-beginning (match-beginning 1))
8117 (highlight-end (match-end 1))
8119 (markdown-convert-wiki-link-to-filename
8120 (markdown-wiki-link-link))))
8121 (if (condition-case nil
(file-exists-p file-name
) (error nil
))
8122 (markdown-highlight-wiki-link
8123 highlight-beginning highlight-end
'markdown-link-face
)
8124 (markdown-highlight-wiki-link
8125 highlight-beginning highlight-end
'markdown-missing-link-face
)))))))
8127 (defun markdown-extend-changed-region (from to
)
8128 "Extend region given by FROM and TO so that we can fontify all links.
8129 The region is extended to the first newline before and the first
8131 ;; start looking for the first new line before 'from
8133 (re-search-backward "\n" nil t
)
8134 (let ((new-from (point-min))
8135 (new-to (point-max)))
8136 (if (not (= (point) from
))
8137 (setq new-from
(point)))
8138 ;; do the same thing for the first new line after 'to
8140 (re-search-forward "\n" nil t
)
8141 (if (not (= (point) to
))
8142 (setq new-to
(point)))
8143 (cl-values new-from new-to
)))
8145 (defun markdown-check-change-for-wiki-link (from to
)
8146 "Check region between FROM and TO for wiki links and re-fontify as needed."
8148 (let* ((modified (buffer-modified-p))
8149 (buffer-undo-list t
)
8150 (inhibit-read-only t
)
8151 (inhibit-point-motion-hooks t
)
8153 buffer-file-truename
)
8158 ;; Extend the region to fontify so that it starts
8159 ;; and ends at safe places.
8160 (cl-multiple-value-bind (new-from new-to
)
8161 (markdown-extend-changed-region from to
)
8162 (goto-char new-from
)
8163 ;; Only refontify when the range contains text with a
8164 ;; wiki link face or if the wiki link regexp matches.
8165 (when (or (markdown-range-property-any
8166 new-from new-to
'font-lock-face
8167 '(markdown-link-face markdown-missing-link-face
))
8169 markdown-regex-wiki-link new-to t
))
8170 ;; Unfontify existing fontification (start from scratch)
8171 (markdown-unfontify-region-wiki-links new-from new-to
)
8172 ;; Now do the fontification.
8173 (markdown-fontify-region-wiki-links new-from new-to
))))))
8176 (set-buffer-modified-p nil
)))))
8178 (defun markdown-check-change-for-wiki-link-after-change (from to _
)
8179 "Check region between FROM and TO for wiki links and re-fontify as needed.
8180 Designed to be used with the `after-change-functions' hook."
8181 (markdown-check-change-for-wiki-link from to
))
8183 (defun markdown-fontify-buffer-wiki-links ()
8184 "Refontify all wiki links in the buffer."
8186 (markdown-check-change-for-wiki-link (point-min) (point-max)))
8188 (defun markdown-toggle-wiki-links (&optional arg
)
8189 "Toggle support for wiki links.
8190 With a prefix argument ARG, enable wiki link support if ARG is positive,
8191 and disable it otherwise."
8192 (interactive (list (or current-prefix-arg
'toggle
)))
8193 (setq markdown-enable-wiki-links
8194 (if (eq arg
'toggle
)
8195 (not markdown-enable-wiki-links
)
8196 (> (prefix-numeric-value arg
) 0)))
8197 (if markdown-enable-wiki-links
8198 (message "markdown-mode wiki link support enabled")
8199 (message "markdown-mode wiki link support disabled"))
8200 (markdown-reload-extensions))
8202 (defun markdown-setup-wiki-link-hooks ()
8203 "Add or remove hooks for fontifying wiki links.
8204 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
8205 ;; Anytime text changes make sure it gets fontified correctly
8206 (if (and markdown-enable-wiki-links
8207 markdown-wiki-link-fontify-missing
)
8208 (add-hook 'after-change-functions
8209 #'markdown-check-change-for-wiki-link-after-change t t
)
8210 (remove-hook 'after-change-functions
8211 #'markdown-check-change-for-wiki-link-after-change t
))
8212 ;; If we left the buffer there is a really good chance we were
8213 ;; creating one of the wiki link documents. Make sure we get
8214 ;; refontified when we come back.
8215 (if (and markdown-enable-wiki-links
8216 markdown-wiki-link-fontify-missing
)
8218 (add-hook 'window-configuration-change-hook
8219 #'markdown-fontify-buffer-wiki-links t t
)
8220 (markdown-fontify-buffer-wiki-links))
8221 (remove-hook 'window-configuration-change-hook
8222 #'markdown-fontify-buffer-wiki-links t
)
8223 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
8226 ;;; Following & Doing =========================================================
8228 (defun markdown-follow-thing-at-point (arg)
8229 "Follow thing at point if possible, such as a reference link or wiki link.
8230 Opens inline and reference links in a browser. Opens wiki links
8231 to other files in the current window, or the another window if
8233 See `markdown-follow-link-at-point' and
8234 `markdown-follow-wiki-link-at-point'."
8236 (cond ((markdown-link-p)
8237 (markdown--browse-url (markdown-link-url)))
8238 ((markdown-wiki-link-p)
8239 (markdown-follow-wiki-link-at-point arg
))
8241 (let* ((values (markdown-link-at-pos (point)))
8242 (url (nth 3 values
)))
8244 (user-error "Nothing to follow at point"))
8245 (markdown--browse-url url
)))))
8247 (defun markdown-do ()
8248 "Do something sensible based on context at point.
8249 Jumps between reference links and definitions; between footnote
8250 markers and footnote text."
8253 ;; Footnote definition
8254 ((markdown-footnote-text-positions)
8255 (markdown-footnote-return))
8257 ((markdown-footnote-marker-positions)
8258 (markdown-footnote-goto-text))
8260 ((thing-at-point-looking-at markdown-regex-link-reference
)
8261 (markdown-reference-goto-definition))
8262 ;; Reference definition
8263 ((thing-at-point-looking-at markdown-regex-reference-definition
)
8264 (markdown-reference-goto-link (match-string-no-properties 2)))
8266 ((or (markdown-link-p) (markdown-wiki-link-p))
8267 (markdown-follow-thing-at-point nil
))
8268 ;; GFM task list item
8269 ((markdown-gfm-task-list-item-at-point)
8270 (markdown-toggle-gfm-checkbox))
8272 ((markdown-table-at-point-p)
8273 (call-interactively #'markdown-table-align
))
8276 (markdown-insert-gfm-checkbox))))
8279 ;;; Miscellaneous =============================================================
8281 (defun markdown-compress-whitespace-string (str)
8282 "Compress whitespace in STR and return result.
8283 Leading and trailing whitespace is removed. Sequences of multiple
8284 spaces, tabs, and newlines are replaced with single spaces."
8285 (replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
8286 (replace-regexp-in-string "[ \t\n]+" " " str
)))
8288 (defun markdown--substitute-command-keys (string)
8289 "Like `substitute-command-keys' but, but prefers control characters.
8290 First pass STRING to `substitute-command-keys' and then
8291 substitute `C-i` for `TAB` and `C-m` for `RET`."
8292 (replace-regexp-in-string
8294 (replace-regexp-in-string
8295 "\\<RET\\>" "C-m" (substitute-command-keys string
) t
) t
))
8297 (defun markdown-line-number-at-pos (&optional pos
)
8298 "Return (narrowed) buffer line number at position POS.
8299 If POS is nil, use current buffer location.
8300 This is an exact copy of `line-number-at-pos' for use in emacs21."
8301 (let ((opoint (or pos
(point))) start
)
8303 (goto-char (point-min))
8304 (setq start
(point))
8307 (1+ (count-lines start
(point))))))
8309 (defun markdown-inside-link-p ()
8310 "Return t if point is within a link."
8312 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
8314 (defun markdown-line-is-reference-definition-p ()
8315 "Return whether the current line is a (non-footnote) reference definition."
8317 (move-beginning-of-line 1)
8318 (and (looking-at-p markdown-regex-reference-definition
)
8319 (not (looking-at-p "[ \t]*\\[^")))))
8321 (defun markdown-adaptive-fill-function ()
8322 "Return prefix for filling paragraph or nil if not determined."
8324 ;; List item inside blockquote
8325 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
8326 (replace-regexp-in-string
8327 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
8329 ((looking-at markdown-regex-blockquote
)
8330 (buffer-substring-no-properties (match-beginning 0) (match-end 2)))
8332 ((looking-at markdown-regex-list
)
8333 (match-string-no-properties 0))
8334 ;; Footnote definition
8335 ((looking-at-p markdown-regex-footnote-definition
)
8340 (defun markdown-fill-paragraph (&optional justify
)
8341 "Fill paragraph at or after point.
8342 This function is like \\[fill-paragraph], but it skips Markdown
8343 code blocks. If the point is in a code block, or just before one,
8344 do not fill. Otherwise, call `fill-paragraph' as usual. If
8345 JUSTIFY is non-nil, justify text as well. Since this function
8346 handles filling itself, it always returns t so that
8347 `fill-paragraph' doesn't run."
8349 (unless (or (markdown-code-block-at-point-p)
8351 (back-to-indentation)
8352 (skip-syntax-forward "-")
8353 (markdown-code-block-at-point-p)))
8354 (let ((fill-prefix (save-excursion
8355 (goto-char (line-beginning-position))
8356 (when (looking-at "\\([ \t]*>[ \t]*\\(?:>[ \t]*\\)+\\)")
8357 (match-string-no-properties 1)))))
8358 (fill-paragraph justify
)))
8361 (defun markdown-fill-forward-paragraph (&optional arg
)
8362 "Function used by `fill-paragraph' to move over ARG paragraphs.
8363 This is a `fill-forward-paragraph-function' for `markdown-mode'.
8364 It is called with a single argument specifying the number of
8365 paragraphs to move. Just like `forward-paragraph', it should
8366 return the number of paragraphs left to move."
8367 (or arg
(setq arg
1))
8369 ;; With positive ARG, move across ARG non-code-block paragraphs,
8370 ;; one at a time. When passing a code block, don't decrement ARG.
8371 (while (and (not (eobp))
8373 (= (forward-paragraph 1) 0)
8374 (or (markdown-code-block-at-pos (point-at-bol 0))
8375 (setq arg
(1- arg
)))))
8376 ;; Move backward by one paragraph with negative ARG (always -1).
8377 (let ((start (point)))
8378 (setq arg
(forward-paragraph arg
))
8379 (while (and (not (eobp))
8380 (progn (move-to-left-margin) (not (eobp)))
8381 (looking-at-p paragraph-separate
))
8384 ;; Move point past whitespace following list marker.
8385 ((looking-at markdown-regex-list
)
8386 (goto-char (match-end 0)))
8387 ;; Move point past whitespace following pipe at beginning of line
8388 ;; to handle Pandoc line blocks.
8389 ((looking-at "^|\\s-*")
8390 (goto-char (match-end 0)))
8391 ;; Return point if the paragraph passed was a code block.
8392 ((markdown-code-block-at-pos (point-at-bol 2))
8393 (goto-char start
)))))
8396 (defun markdown--inhibit-electric-quote ()
8397 "Function added to `electric-quote-inhibit-functions'.
8398 Return non-nil if the quote has been inserted inside a code block
8400 (let ((pos (1- (point))))
8401 (or (markdown-inline-code-at-pos pos
)
8402 (markdown-code-block-at-pos pos
))))
8405 ;;; Extension Framework =======================================================
8407 (defun markdown-reload-extensions ()
8408 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
8410 (when (derived-mode-p 'markdown-mode
)
8413 ;; Add or remove hooks related to extensions
8414 (markdown-setup-wiki-link-hooks)))
8416 (defun markdown-handle-local-variables ()
8417 "Run in `hack-local-variables-hook' to update font lock rules.
8418 Checks to see if there is actually a ‘markdown-mode’ file local variable
8419 before regenerating font-lock rules for extensions."
8420 (when (or (assoc 'markdown-enable-wiki-links file-local-variables-alist
)
8421 (assoc 'markdown-enable-math file-local-variables-alist
))
8422 (when (assoc 'markdown-enable-math file-local-variables-alist
)
8423 (markdown-toggle-math markdown-enable-math
))
8424 (markdown-reload-extensions)))
8427 ;;; Math Support ==============================================================
8429 (defconst markdown-mode-font-lock-keywords-math
8431 ;; Equation reference (eq:foo)
8432 '("\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" .
((1 markdown-markup-face
)
8433 (2 markdown-reference-face
)
8434 (3 markdown-markup-face
)))
8435 ;; Equation reference \eqref{foo}
8436 '("\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" .
((1 markdown-markup-face
)
8437 (2 markdown-reference-face
)
8438 (3 markdown-markup-face
))))
8439 "Font lock keywords to add and remove when toggling math support.")
8441 (defun markdown-toggle-math (&optional arg
)
8442 "Toggle support for inline and display LaTeX math expressions.
8443 With a prefix argument ARG, enable math mode if ARG is positive,
8444 and disable it otherwise. If called from Lisp, enable the mode
8445 if ARG is omitted or nil."
8446 (interactive (list (or current-prefix-arg
'toggle
)))
8447 (setq markdown-enable-math
8448 (if (eq arg
'toggle
)
8449 (not markdown-enable-math
)
8450 (> (prefix-numeric-value arg
) 0)))
8451 (if markdown-enable-math
8453 (font-lock-add-keywords
8454 'markdown-mode markdown-mode-font-lock-keywords-math
)
8455 (message "markdown-mode math support enabled"))
8456 (font-lock-remove-keywords
8457 'markdown-mode markdown-mode-font-lock-keywords-math
)
8458 (message "markdown-mode math support disabled"))
8459 (markdown-reload-extensions))
8462 ;;; GFM Checkboxes ============================================================
8464 (define-button-type 'markdown-gfm-checkbox-button
8466 'face
'markdown-gfm-checkbox-face
8467 'mouse-face
'markdown-highlight-face
8468 'action
#'markdown-toggle-gfm-checkbox-button
)
8470 (defun markdown-gfm-task-list-item-at-point (&optional bounds
)
8471 "Return non-nil if there is a GFM task list item at the point.
8472 Optionally, the list item BOUNDS may be given if available, as
8473 returned by `markdown-cur-list-item-bounds'. When a task list item
8474 is found, the return value is the same value returned by
8475 `markdown-cur-list-item-bounds'."
8477 (setq bounds
(markdown-cur-list-item-bounds)))
8478 (> (length (nth 5 bounds
)) 0))
8480 (defun markdown-insert-gfm-checkbox ()
8481 "Add GFM checkbox at point.
8483 Returns nil if non-applicable."
8485 (let ((bounds (markdown-cur-list-item-bounds)))
8487 (unless (cl-sixth bounds
)
8488 (let ((pos (+ (cl-first bounds
) (cl-fourth bounds
)))
8496 (syntax-propertize (+ (cl-second bounds
) 4))
8498 (unless (save-excursion
8499 (back-to-indentation)
8500 (or (markdown-list-item-at-point-p)
8501 (markdown-heading-at-point)
8502 (markdown-in-comment-p)
8503 (markdown-code-block-at-point-p)))
8504 (let ((pos (save-excursion
8505 (back-to-indentation)
8507 (markup (concat (or (save-excursion
8508 (beginning-of-line 0)
8509 (cl-fifth (markdown-cur-list-item-bounds)))
8510 markdown-unordered-list-item-prefix
)
8518 (syntax-propertize (point-at-eol))
8521 (defun markdown-toggle-gfm-checkbox ()
8522 "Toggle GFM checkbox at point.
8523 Returns the resulting status as a string, either \"[x]\" or \"[ ]\".
8524 Returns nil if there is no task list item at the point."
8528 (let ((bounds (markdown-cur-list-item-bounds)))
8530 ;; Move to beginning of task list item
8531 (goto-char (cl-first bounds
))
8532 ;; Advance to column of first non-whitespace after marker
8533 (forward-char (cl-fourth bounds
))
8534 (cond ((looking-at "\\[ \\]")
8536 (if markdown-gfm-uppercase-checkbox
"[X]" "[x]")
8538 (match-string-no-properties 0))
8539 ((looking-at "\\[[xX]\\]")
8540 (replace-match "[ ]" nil t
)
8541 (match-string-no-properties 0))))))))
8543 (defun markdown-toggle-gfm-checkbox-button (button)
8544 "Toggle GFM checkbox BUTTON on click."
8547 (goto-char (button-start button
))
8548 (markdown-toggle-gfm-checkbox))))
8550 (defun markdown-make-gfm-checkboxes-buttons (start end
)
8551 "Make GFM checkboxes buttons in region between START and END."
8554 (let ((case-fold-search t
))
8556 (while (re-search-forward markdown-regex-gfm-checkbox end t
)
8557 (make-button (match-beginning 1) (match-end 1)
8558 :type
'markdown-gfm-checkbox-button
))))))
8560 ;; Called when any modification is made to buffer text.
8561 (defun markdown-gfm-checkbox-after-change-function (beg end _
)
8562 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
8563 BEG and END are the limits of scanned region."
8566 ;; Rescan between start of line from `beg' and start of line after `end'.
8567 (markdown-make-gfm-checkboxes-buttons
8568 (progn (goto-char beg
) (beginning-of-line) (point))
8569 (progn (goto-char end
) (forward-line 1) (point))))))
8571 (defun markdown-remove-gfm-checkbox-overlays ()
8572 "Remove all GFM checkbox overlays in buffer."
8576 (remove-overlays nil nil
'face
'markdown-gfm-checkbox-face
))))
8579 ;;; Display inline image ======================================================
8581 (defvar-local markdown-inline-image-overlays nil
)
8583 (defun markdown-remove-inline-images ()
8584 "Remove inline image overlays from image links in the buffer.
8585 This can be toggled with `markdown-toggle-inline-images'
8586 or \\[markdown-toggle-inline-images]."
8588 (mapc #'delete-overlay markdown-inline-image-overlays
)
8589 (setq markdown-inline-image-overlays nil
))
8591 (defcustom markdown-display-remote-images nil
8592 "If non-nil, download and display remote images.
8593 See also `markdown-inline-image-overlays'.
8595 Only image URLs specified with a protocol listed in
8596 `markdown-remote-image-protocols' are displayed."
8600 (defcustom markdown-remote-image-protocols
'("https")
8601 "List of protocols to use to download remote images.
8602 See also `markdown-display-remote-images'."
8604 :type
'(repeat string
))
8606 (defvar markdown--remote-image-cache
8607 (make-hash-table :test
'equal
)
8608 "A map from URLs to image paths.")
8610 (defun markdown--get-remote-image (url)
8611 "Retrieve the image path for a given URL."
8612 (or (gethash url markdown--remote-image-cache
)
8613 (let ((dl-path (make-temp-file "markdown-mode--image")))
8615 (url-copy-file url dl-path t
)
8616 (puthash url dl-path markdown--remote-image-cache
))))
8618 (defun markdown-display-inline-images ()
8619 "Add inline image overlays to image links in the buffer.
8620 This can be toggled with `markdown-toggle-inline-images'
8621 or \\[markdown-toggle-inline-images]."
8623 (unless (display-images-p)
8624 (error "Cannot show images"))
8628 (goto-char (point-min))
8629 (while (re-search-forward markdown-regex-link-inline nil t
)
8630 (let* ((start (match-beginning 0))
8631 (imagep (match-beginning 1))
8633 (file (match-string-no-properties 6)))
8635 (not (zerop (length file
))))
8636 (unless (file-exists-p file
)
8637 (let* ((download-file (funcall markdown-translate-filename-function file
))
8638 (valid-url (ignore-errors
8639 (member (downcase (url-type (url-generic-parse-url download-file
)))
8640 markdown-remote-image-protocols
))))
8641 (if (and markdown-display-remote-images valid-url
)
8642 (setq file
(markdown--get-remote-image download-file
))
8643 (when (not valid-url
)
8644 ;; strip query parameter
8645 (setq file
(replace-regexp-in-string "?.+\\'" "" file
))
8646 (unless (file-exists-p file
)
8647 (setq file
(url-unhex-string file
)))))))
8648 (when (file-exists-p file
)
8649 (let* ((abspath (if (file-name-absolute-p file
)
8651 (concat default-directory file
)))
8653 (cond ((and markdown-max-image-size
8654 (image-type-available-p 'imagemagick
))
8656 abspath
'imagemagick nil
8657 :max-width
(car markdown-max-image-size
)
8658 :max-height
(cdr markdown-max-image-size
)))
8659 (markdown-max-image-size
8660 (create-image abspath nil nil
8661 :max-width
(car markdown-max-image-size
)
8662 :max-height
(cdr markdown-max-image-size
)))
8663 (t (create-image abspath
)))))
8665 (let ((ov (make-overlay start end
)))
8666 (overlay-put ov
'display image
)
8667 (overlay-put ov
'face
'default
)
8668 (push ov markdown-inline-image-overlays
)))))))))))
8670 (defun markdown-toggle-inline-images ()
8671 "Toggle inline image overlays in the buffer."
8673 (if markdown-inline-image-overlays
8674 (markdown-remove-inline-images)
8675 (markdown-display-inline-images)))
8678 ;;; GFM Code Block Fontification ==============================================
8680 (defcustom markdown-fontify-code-blocks-natively nil
8681 "When non-nil, fontify code in code blocks using the native major mode.
8682 This only works for fenced code blocks where the language is
8683 specified where we can automatically determine the appropriate
8684 mode to use. The language to mode mapping may be customized by
8685 setting the variable `markdown-code-lang-modes'."
8689 :package-version
'(markdown-mode .
"2.3"))
8691 (defcustom markdown-fontify-code-block-default-mode nil
8692 "Default mode to use to fontify code blocks.
8693 This mode is used when automatic detection fails, such as for GFM
8694 code blocks with no language specified."
8696 :type
'(choice function
(const :tag
"None" nil
))
8697 :package-version
'(markdown-mode .
"2.4"))
8699 (defun markdown-toggle-fontify-code-blocks-natively (&optional arg
)
8700 "Toggle the native fontification of code blocks.
8701 With a prefix argument ARG, enable if ARG is positive,
8702 and disable otherwise."
8703 (interactive (list (or current-prefix-arg
'toggle
)))
8704 (setq markdown-fontify-code-blocks-natively
8705 (if (eq arg
'toggle
)
8706 (not markdown-fontify-code-blocks-natively
)
8707 (> (prefix-numeric-value arg
) 0)))
8708 (if markdown-fontify-code-blocks-natively
8709 (message "markdown-mode native code block fontification enabled")
8710 (message "markdown-mode native code block fontification disabled"))
8711 (markdown-reload-extensions))
8713 ;; This is based on `org-src-lang-modes' from org-src.el
8714 (defcustom markdown-code-lang-modes
8715 '(("ocaml" . tuareg-mode
) ("elisp" . emacs-lisp-mode
) ("ditaa" . artist-mode
)
8716 ("asymptote" . asy-mode
) ("dot" . fundamental-mode
) ("sqlite" . sql-mode
)
8717 ("calc" . fundamental-mode
) ("C" . c-mode
) ("cpp" . c
++-mode
)
8718 ("C++" . c
++-mode
) ("screen" . shell-script-mode
) ("shell" . sh-mode
)
8720 "Alist mapping languages to their major mode.
8721 The key is the language name, the value is the major mode. For
8722 many languages this is simple, but for language where this is not
8723 the case, this variable provides a way to simplify things on the
8724 user side. For example, there is no ocaml-mode in Emacs, but the
8725 mode to use is `tuareg-mode'."
8729 (string "Language name")
8730 (symbol "Major mode")))
8731 :package-version
'(markdown-mode .
"2.3"))
8733 (defun markdown-get-lang-mode (lang)
8734 "Return major mode that should be used for LANG.
8735 LANG is a string, and the returned major mode is a symbol."
8738 (list (cdr (assoc lang markdown-code-lang-modes
))
8739 (cdr (assoc (downcase lang
) markdown-code-lang-modes
))
8740 (intern (concat lang
"-mode"))
8741 (intern (concat (downcase lang
) "-mode")))))
8743 (defun markdown-fontify-code-blocks-generic (matcher last
)
8744 "Add text properties to next code block from point to LAST.
8745 Use matching function MATCHER."
8746 (when (funcall matcher last
)
8749 (let* ((start (match-beginning 0))
8751 ;; Find positions outside opening and closing backquotes.
8752 (bol-prev (progn (goto-char start
)
8753 (if (bolp) (point-at-bol 0) (point-at-bol))))
8754 (eol-next (progn (goto-char end
)
8755 (if (bolp) (point-at-bol 2) (point-at-bol 3))))
8757 (if (and markdown-fontify-code-blocks-natively
8758 (or (setq lang
(markdown-code-block-lang))
8759 markdown-fontify-code-block-default-mode
))
8760 (markdown-fontify-code-block-natively lang start end
)
8761 (add-text-properties start end
'(face markdown-pre-face
)))
8762 ;; Set background for block as well as opening and closing lines.
8763 (font-lock-append-text-property
8764 bol-prev eol-next
'face
'markdown-code-face
)
8765 ;; Set invisible property for lines before and after, including newline.
8766 (add-text-properties bol-prev start
'(invisible markdown-markup
))
8767 (add-text-properties end eol-next
'(invisible markdown-markup
)))))
8770 (defun markdown-fontify-gfm-code-blocks (last)
8771 "Add text properties to next GFM code block from point to LAST."
8772 (markdown-fontify-code-blocks-generic 'markdown-match-gfm-code-blocks last
))
8774 (defun markdown-fontify-fenced-code-blocks (last)
8775 "Add text properties to next tilde fenced code block from point to LAST."
8776 (markdown-fontify-code-blocks-generic 'markdown-match-fenced-code-blocks last
))
8778 ;; Based on `org-src-font-lock-fontify-block' from org-src.el.
8779 (defun markdown-fontify-code-block-natively (lang start end
)
8780 "Fontify given GFM or fenced code block.
8781 This function is called by Emacs for automatic fontification when
8782 `markdown-fontify-code-blocks-natively' is non-nil. LANG is the
8783 language used in the block. START and END specify the block
8785 (let ((lang-mode (if lang
(markdown-get-lang-mode lang
)
8786 markdown-fontify-code-block-default-mode
)))
8787 (when (fboundp lang-mode
)
8788 (let ((string (buffer-substring-no-properties start end
))
8789 (modified (buffer-modified-p))
8790 (markdown-buffer (current-buffer)) pos next
)
8791 (remove-text-properties start end
'(face nil
))
8792 (with-current-buffer
8794 (concat " markdown-code-fontification:" (symbol-name lang-mode
)))
8795 ;; Make sure that modification hooks are not inhibited in
8796 ;; the org-src-fontification buffer in case we're called
8797 ;; from `jit-lock-function' (Bug#25132).
8798 (let ((inhibit-modification-hooks nil
))
8799 (delete-region (point-min) (point-max))
8800 (insert string
" ")) ;; so there's a final property change
8801 (unless (eq major-mode lang-mode
) (funcall lang-mode
))
8803 (setq pos
(point-min))
8804 (while (setq next
(next-single-property-change pos
'face
))
8805 (let ((val (get-text-property pos
'face
)))
8808 (+ start
(1- pos
)) (1- (+ start next
)) 'face
8809 val markdown-buffer
)))
8811 (add-text-properties
8813 '(font-lock-fontified t fontified t font-lock-multiline t
))
8814 (set-buffer-modified-p modified
)))))
8816 (require 'edit-indirect nil t
)
8817 (defvar edit-indirect-guess-mode-function
)
8818 (defvar edit-indirect-after-commit-functions
)
8820 (defun markdown--edit-indirect-after-commit-function (beg end
)
8821 "Corrective logic run on code block content from lines BEG to END.
8822 Restores code block indentation from BEG to END, and ensures trailing newlines
8823 at the END of code blocks."
8824 ;; ensure trailing newlines
8826 (unless (eq (char-before) ?
\n)
8828 ;; restore code block indentation
8829 (goto-char (- beg
1))
8830 (let ((block-indentation (current-indentation)))
8831 (when (> block-indentation
0)
8832 (indent-rigidly beg end block-indentation
)))
8835 (defun markdown-edit-code-block ()
8836 "Edit Markdown code block in an indirect buffer."
8839 (if (fboundp 'edit-indirect-region
)
8840 (let* ((bounds (markdown-get-enclosing-fenced-block-construct))
8841 (begin (and bounds
(not (null (nth 0 bounds
))) (goto-char (nth 0 bounds
)) (point-at-bol 2)))
8842 (end (and bounds
(not (null (nth 1 bounds
))) (goto-char (nth 1 bounds
)) (point-at-bol 1))))
8844 (let* ((indentation (and (goto-char (nth 0 bounds
)) (current-indentation)))
8845 (lang (markdown-code-block-lang))
8846 (mode (or (and lang
(markdown-get-lang-mode lang
))
8847 markdown-edit-code-block-default-mode
))
8848 (edit-indirect-guess-mode-function
8849 (lambda (_parent-buffer _beg _end
)
8851 (indirect-buf (edit-indirect-region begin end
'display-buffer
)))
8852 ;; reset `sh-shell' when indirect buffer
8853 (when (and (not (member system-type
'(ms-dos windows-nt
)))
8854 (member mode
'(shell-script-mode sh-mode
))
8855 (member lang
(append
8856 (mapcar (lambda (e) (symbol-name (car e
)))
8858 '("csh" "rc" "sh"))))
8859 (with-current-buffer indirect-buf
8860 (sh-set-shell lang
)))
8861 (when (> indentation
0) ;; un-indent in edit-indirect buffer
8862 (with-current-buffer indirect-buf
8863 (indent-rigidly (point-min) (point-max) (- indentation
)))))
8864 (user-error "Not inside a GFM or tilde fenced code block")))
8865 (when (y-or-n-p "Package edit-indirect needed to edit code blocks. Install it now? ")
8866 (progn (package-refresh-contents)
8867 (package-install 'edit-indirect
)
8868 (markdown-edit-code-block))))))
8871 ;;; Table Editing =============================================================
8873 ;; These functions were originally adapted from `org-table.el'.
8875 ;; General helper functions
8877 (defmacro markdown--with-gensyms
(symbols &rest body
)
8878 (declare (debug (sexp body
)) (indent 1))
8879 `(let ,(mapcar (lambda (s)
8880 `(,s
(make-symbol (concat "--" (symbol-name ',s
)))))
8884 (defun markdown--split-string (string &optional separators
)
8885 "Splits STRING into substrings at SEPARATORS.
8886 SEPARATORS is a regular expression. If nil it defaults to
8887 `split-string-default-separators'. This version returns no empty
8888 strings if there are matches at the beginning and end of string."
8889 (let ((start 0) notfirst list
)
8890 (while (and (string-match
8891 (or separators split-string-default-separators
)
8894 (= start
(match-beginning 0))
8895 (< start
(length string
)))
8897 (< (match-beginning 0) (length string
)))
8899 (or (eq (match-beginning 0) 0)
8900 (and (eq (match-beginning 0) (match-end 0))
8901 (eq (match-beginning 0) start
))
8902 (push (substring string start
(match-beginning 0)) list
))
8903 (setq start
(match-end 0)))
8904 (or (eq start
(length string
))
8905 (push (substring string start
) list
))
8908 (defun markdown--string-width (s)
8909 "Return width of string S.
8910 This version ignores characters with invisibility property
8913 (when (or (eq t buffer-invisibility-spec
)
8914 (member 'markdown-markup buffer-invisibility-spec
))
8915 (while (setq b
(text-property-any
8917 'invisible
'markdown-markup s
))
8920 (substring s
(or (next-single-property-change
8925 (defun markdown--remove-invisible-markup (s)
8926 "Remove Markdown markup from string S.
8927 This version removes characters with invisibility property
8930 (while (setq b
(text-property-any
8932 'invisible
'markdown-markup s
))
8935 (substring s
(or (next-single-property-change
8940 ;; Functions for maintaining tables
8942 (defvar markdown-table-at-point-p-function
#'markdown--table-at-point-p
8943 "Function to decide if point is inside a table.
8945 The indirection serves to differentiate between standard markdown
8946 tables and gfm tables which are less strict about the markup.")
8948 (defconst markdown-table-line-regexp
"^[ \t]*|"
8949 "Regexp matching any line inside a table.")
8951 (defconst markdown-table-hline-regexp
"^[ \t]*|[-:]"
8952 "Regexp matching hline inside a table.")
8954 (defconst markdown-table-dline-regexp
"^[ \t]*|[^-:]"
8955 "Regexp matching dline inside a table.")
8957 (defun markdown-table-at-point-p ()
8958 "Return non-nil when point is inside a table."
8959 (funcall markdown-table-at-point-p-function
))
8961 (defun markdown--table-at-point-p ()
8962 "Return non-nil when point is inside a table."
8965 (and (looking-at-p markdown-table-line-regexp
)
8966 (not (markdown-code-block-at-point-p)))))
8968 (defconst gfm-table-line-regexp
"^.?*|"
8969 "Regexp matching any line inside a table.")
8971 (defconst gfm-table-hline-regexp
"^-+\\(|-\\)+"
8972 "Regexp matching hline inside a table.")
8974 ;; GFM simplified tables syntax is as follows:
8975 ;; - A header line for the column names, this is any text
8976 ;; separated by `|'.
8977 ;; - Followed by a string -|-|- ..., the number of dashes is optional
8978 ;; but must be higher than 1. The number of separators should match
8979 ;; the number of columns.
8980 ;; - Followed by the rows of data, which has the same format as the
8988 (defun gfm--table-at-point-p ()
8989 "Return non-nil when point is inside a gfm-compatible table."
8990 (or (markdown--table-at-point-p)
8993 (when (looking-at-p gfm-table-line-regexp
)
8994 ;; we might be at the first line of the table, check if the
8995 ;; line below is the hline
8998 (looking-at-p gfm-table-hline-regexp
))
8999 ;; go up to find the header
9001 (while (looking-at-p gfm-table-line-regexp
)
9003 ((looking-at-p gfm-table-hline-regexp
)
9010 (defun markdown-table-hline-at-point-p ()
9011 "Return non-nil when point is on a hline in a table.
9012 This function assumes point is on a table."
9015 (looking-at-p markdown-table-hline-regexp
)))
9017 (defun markdown-table-begin ()
9018 "Find the beginning of the table and return its position.
9019 This function assumes point is on a table."
9021 (while (and (not (bobp))
9022 (markdown-table-at-point-p))
9025 (markdown-table-at-point-p))
9029 (defun markdown-table-end ()
9030 "Find the end of the table and return its position.
9031 This function assumes point is on a table."
9033 (while (and (not (eobp))
9034 (markdown-table-at-point-p))
9038 (defun markdown-table-get-dline ()
9039 "Return index of the table data line at point.
9040 This function assumes point is on a table."
9041 (let ((pos (point)) (end (markdown-table-end)) (cnt 0))
9043 (goto-char (markdown-table-begin))
9044 (while (and (re-search-forward
9045 markdown-table-dline-regexp end t
)
9047 (< (point-at-eol) pos
))))
9050 (defun markdown--thing-at-wiki-link (pos)
9051 (when markdown-enable-wiki-links
9055 (thing-at-point-looking-at markdown-regex-wiki-link
)))))
9057 (defun markdown-table-get-column ()
9058 "Return table column at point.
9059 This function assumes point is on a table."
9060 (let ((pos (point)) (cnt 0))
9063 (while (search-forward "|" pos t
)
9064 (when (and (not (looking-back "\\\\|" (line-beginning-position)))
9065 (not (markdown--thing-at-wiki-link (match-beginning 0))))
9066 (setq cnt
(1+ cnt
)))))
9069 (defun markdown-table-get-cell (&optional n
)
9070 "Return the content of the cell in column N of current row.
9071 N defaults to column at point. This function assumes point is on
9073 (and n
(markdown-table-goto-column n
))
9074 (skip-chars-backward "^|\n") (backward-char 1)
9075 (if (looking-at "|[^|\r\n]*")
9076 (let* ((pos (match-beginning 0))
9077 (val (buffer-substring (1+ pos
) (match-end 0))))
9078 (goto-char (min (point-at-eol) (+ 2 pos
)))
9080 (setq val
(replace-regexp-in-string "\\`[ \t]+" "" val
)
9081 val
(replace-regexp-in-string "[ \t]+\\'" "" val
)))
9082 (forward-char 1) ""))
9084 (defun markdown-table-goto-dline (n)
9085 "Go to the Nth data line in the table at point.
9086 Return t when the line exists, nil otherwise. This function
9087 assumes point is on a table."
9088 (goto-char (markdown-table-begin))
9089 (let ((end (markdown-table-end)) (cnt 0))
9090 (while (and (re-search-forward
9091 markdown-table-dline-regexp end t
)
9092 (< (setq cnt
(1+ cnt
)) n
)))
9095 (defun markdown-table-goto-column (n &optional on-delim
)
9096 "Go to the Nth column in the table line at point.
9097 With optional argument ON-DELIM, stop with point before the left
9098 delimiter of the cell. If there are less than N cells, just go
9099 beyond the last delimiter. This function assumes point is on a
9101 (beginning-of-line 1)
9103 (while (and (> n
0) (search-forward "|" (point-at-eol) t
))
9104 (when (and (not (looking-back "\\\\|" (line-beginning-position)))
9105 (not (markdown--thing-at-wiki-link (match-beginning 0))))
9109 (when (looking-at " ") (forward-char 1)))))
9111 (defmacro markdown-table-save-cell
(&rest body
)
9112 "Save cell at point, execute BODY and restore cell.
9113 This function assumes point is on a table."
9114 (declare (debug (body)))
9115 (markdown--with-gensyms (line column
)
9116 `(let ((,line
(copy-marker (line-beginning-position)))
9117 (,column
(markdown-table-get-column)))
9121 (markdown-table-goto-column ,column
)
9122 (set-marker ,line nil
)))))
9124 (defun markdown-table-blank-line (s)
9125 "Convert a table line S into a line with blank cells."
9126 (if (string-match "^[ \t]*|-" s
)
9128 (lambda (x) (if (member x
'(?| ?
+)) "|" " "))
9132 (goto-char (point-min))
9133 (when (re-search-forward "|" nil t
)
9136 (while (re-search-forward "|" nil t
)
9137 (when (and (not (eql (char-before (match-beginning 0)) ?
\\))
9138 (not (markdown--thing-at-wiki-link (match-beginning 0))))
9139 (push (make-string (- (match-beginning 0) cur
) ?
) ret
)
9140 (setq cur
(match-end 0))))
9141 (format "|%s|" (string-join (nreverse ret
) "|")))))))
9143 (defun markdown-table-colfmt (fmtspec)
9144 "Process column alignment specifier FMTSPEC for tables."
9145 (when (stringp fmtspec
)
9147 (cond ((string-match-p "^:.*:$" x
) 'c
)
9148 ((string-match-p "^:" x
) 'l
)
9149 ((string-match-p ":$" x
) 'r
)
9151 (markdown--split-string fmtspec
"\\s-*|\\s-*"))))
9153 (defun markdown--first-column-p (bar-pos)
9157 (looking-back "^\\s-*" (line-beginning-position)))))
9159 (defun markdown--table-line-to-columns (line)
9162 (goto-char (point-min))
9165 (while (re-search-forward "\\s-*\\(|\\)\\s-*" nil t
)
9166 (if (markdown--first-column-p (match-beginning 1))
9167 (setq cur
(match-end 0))
9168 (cond ((eql (char-before (match-beginning 1)) ?
\\)
9170 (goto-char (match-end 1)))
9171 ((markdown--thing-at-wiki-link (match-beginning 1))) ;; do nothing
9173 (push (buffer-substring-no-properties cur
(match-beginning 0)) ret
)
9174 (setq cur
(match-end 0))))))
9175 (when (< cur
(length line
))
9176 (push (buffer-substring-no-properties cur
(point-max)) ret
))
9179 (defun markdown-table-align ()
9180 "Align table at point.
9181 This function assumes point is on a table."
9183 (let ((begin (markdown-table-begin))
9184 (end (copy-marker (markdown-table-end))))
9185 (markdown-table-save-cell
9188 ;; Store table indent
9189 (indent (progn (looking-at "[ \t]*") (match-string 0)))
9190 ;; Split table in lines and save column format specifier
9191 (lines (mapcar (lambda (l)
9192 (if (string-match-p "\\`[ \t]*|[ \t]*[-:]" l
)
9193 (progn (setq fmtspec
(or fmtspec l
)) nil
) l
))
9194 (markdown--split-string (buffer-substring begin end
) "\n")))
9195 ;; Split lines in cells
9196 (cells (mapcar (lambda (l) (markdown--table-line-to-columns l
))
9198 ;; Calculate maximum number of cells in a line
9200 (apply #'max
(mapcar #'length cells
))
9201 (user-error "Empty table")))
9202 ;; Empty cells to fill short lines
9203 (emptycells (make-list maxcells
""))
9205 ;; Calculate maximum width for each column
9206 (dotimes (i maxcells
)
9207 (let ((column (mapcar (lambda (x) (or (nth i x
) "")) cells
)))
9208 (push (apply #'max
1 (mapcar #'markdown--string-width column
))
9210 (setq maxwidths
(nreverse maxwidths
))
9211 ;; Process column format specifier
9212 (setq fmtspec
(markdown-table-colfmt fmtspec
))
9213 ;; Compute formats needed for output of table lines
9214 (let ((hfmt (concat indent
"|"))
9215 (rfmt (concat indent
"|"))
9217 (dolist (width maxwidths
(setq hfmt
(concat (substring hfmt
0 -
1) "|")))
9218 (setq fmt
(pop fmtspec
))
9219 (cond ((equal fmt
'l
) (setq hfmt1
":%s-|" rfmt1
" %%-%ds |"))
9220 ((equal fmt
'r
) (setq hfmt1
"-%s:|" rfmt1
" %%%ds |"))
9221 ((equal fmt
'c
) (setq hfmt1
":%s:|" rfmt1
" %%-%ds |"))
9222 (t (setq hfmt1
"-%s-|" rfmt1
" %%-%ds |")))
9223 (setq rfmt
(concat rfmt
(format rfmt1 width
)))
9224 (setq hfmt
(concat hfmt
(format hfmt1
(make-string width ?-
)))))
9225 ;; Replace modified lines only
9226 (dolist (line lines
)
9227 (let ((line (if line
9228 (apply #'format rfmt
(append (pop cells
) emptycells
))
9230 (previous (buffer-substring (point) (line-end-position))))
9231 (if (equal previous line
)
9234 (delete-region (point) (line-beginning-position 2))))))
9235 (set-marker end nil
)))))
9237 (defun markdown-table-insert-row (&optional arg
)
9238 "Insert a new row above the row at point into the table.
9239 With optional argument ARG, insert below the current row."
9241 (unless (markdown-table-at-point-p)
9242 (user-error "Not at a table"))
9243 (let* ((line (buffer-substring
9244 (line-beginning-position) (line-end-position)))
9245 (new (markdown-table-blank-line line
)))
9246 (beginning-of-line (if arg
2 1))
9247 (unless (bolp) (insert "\n"))
9248 (insert-before-markers new
"\n")
9249 (beginning-of-line 0)
9250 (re-search-forward "| ?" (line-end-position) t
)))
9252 (defun markdown-table-delete-row ()
9253 "Delete row or horizontal line at point from the table."
9255 (unless (markdown-table-at-point-p)
9256 (user-error "Not at a table"))
9257 (let ((col (current-column)))
9258 (kill-region (point-at-bol)
9259 (min (1+ (point-at-eol)) (point-max)))
9260 (unless (markdown-table-at-point-p) (beginning-of-line 0))
9261 (move-to-column col
)))
9263 (defun markdown-table-move-row (&optional up
)
9264 "Move table line at point down.
9265 With optional argument UP, move it up."
9267 (unless (markdown-table-at-point-p)
9268 (user-error "Not at a table"))
9269 (let* ((col (current-column)) (pos (point))
9270 (tonew (if up
0 2)) txt
)
9271 (beginning-of-line tonew
)
9272 (unless (markdown-table-at-point-p)
9273 (goto-char pos
) (user-error "Cannot move row further"))
9274 (goto-char pos
) (beginning-of-line 1) (setq pos
(point))
9275 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
9276 (delete-region (point) (1+ (point-at-eol)))
9277 (beginning-of-line tonew
)
9278 (insert txt
) (beginning-of-line 0)
9279 (move-to-column col
)))
9281 (defun markdown-table-move-row-up ()
9282 "Move table row at point up."
9284 (markdown-table-move-row 'up
))
9286 (defun markdown-table-move-row-down ()
9287 "Move table row at point down."
9289 (markdown-table-move-row nil
))
9291 (defun markdown-table-insert-column ()
9292 "Insert a new table column."
9294 (unless (markdown-table-at-point-p)
9295 (user-error "Not at a table"))
9296 (let* ((col (max 1 (markdown-table-get-column)))
9297 (begin (markdown-table-begin))
9298 (end (copy-marker (markdown-table-end))))
9299 (markdown-table-save-cell
9301 (while (< (point) end
)
9302 (markdown-table-goto-column col t
)
9303 (if (markdown-table-hline-at-point-p)
9307 (set-marker end nil
)
9308 (when markdown-table-align-p
9309 (markdown-table-align))))
9311 (defun markdown-table-delete-column ()
9312 "Delete column at point from table."
9314 (unless (markdown-table-at-point-p)
9315 (user-error "Not at a table"))
9316 (let ((col (markdown-table-get-column))
9317 (begin (markdown-table-begin))
9318 (end (copy-marker (markdown-table-end))))
9319 (markdown-table-save-cell
9321 (while (< (point) end
)
9322 (markdown-table-goto-column col t
)
9323 (and (looking-at "|\\(?:\\\\|\\|[^|\n]\\)+|")
9324 (replace-match "|"))
9326 (set-marker end nil
)
9327 (markdown-table-goto-column (max 1 (1- col
)))
9328 (when markdown-table-align-p
9329 (markdown-table-align))))
9331 (defun markdown-table-move-column (&optional left
)
9332 "Move table column at point to the right.
9333 With optional argument LEFT, move it to the left."
9335 (unless (markdown-table-at-point-p)
9336 (user-error "Not at a table"))
9337 (let* ((col (markdown-table-get-column))
9338 (col1 (if left
(1- col
) col
))
9339 (colpos (if left
(1- col
) (1+ col
)))
9340 (begin (markdown-table-begin))
9341 (end (copy-marker (markdown-table-end))))
9342 (when (and left
(= col
1))
9343 (user-error "Cannot move column further left"))
9344 (when (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
9345 (user-error "Cannot move column further right"))
9346 (markdown-table-save-cell
9348 (while (< (point) end
)
9349 (markdown-table-goto-column col1 t
)
9350 (when (looking-at "|\\(\\(?:\\\\|\\|[^|\n]\\|\\)+\\)|\\(\\(?:\\\\|\\|[^|\n]\\|\\)+\\)|")
9351 (replace-match "|\\2|\\1|"))
9353 (set-marker end nil
)
9354 (markdown-table-goto-column colpos
)
9355 (when markdown-table-align-p
9356 (markdown-table-align))))
9358 (defun markdown-table-move-column-left ()
9359 "Move table column at point to the left."
9361 (markdown-table-move-column 'left
))
9363 (defun markdown-table-move-column-right ()
9364 "Move table column at point to the right."
9366 (markdown-table-move-column nil
))
9368 (defun markdown-table-next-row ()
9369 "Go to the next row (same column) in the table.
9370 Create new table lines if required."
9372 (unless (markdown-table-at-point-p)
9373 (user-error "Not at a table"))
9374 (if (or (looking-at "[ \t]*$")
9375 (save-excursion (skip-chars-backward " \t") (bolp)))
9377 (when markdown-table-align-p
9378 (markdown-table-align))
9379 (let ((col (markdown-table-get-column)))
9380 (beginning-of-line 2)
9381 (if (or (not (markdown-table-at-point-p))
9382 (markdown-table-hline-at-point-p))
9384 (beginning-of-line 0)
9385 (markdown-table-insert-row 'below
)))
9386 (markdown-table-goto-column col
)
9387 (skip-chars-backward "^|\n\r")
9388 (when (looking-at " ") (forward-char 1)))))
9390 (defun markdown-table-forward-cell ()
9391 "Go to the next cell in the table.
9392 Create new table lines if required."
9394 (unless (markdown-table-at-point-p)
9395 (user-error "Not at a table"))
9396 (when markdown-table-align-p
9397 (markdown-table-align))
9398 (let ((end (markdown-table-end)))
9399 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9402 (re-search-forward "\\(?:^\\|[^\\]\\)|" end
)
9403 (when (looking-at "[ \t]*$")
9404 (re-search-forward "\\(?:^\\|[^\\]:\\)|" end
))
9405 (when (and (looking-at "[-:]")
9406 (re-search-forward "^\\(?:[ \t]*\\|[^\\]\\)|\\([^-:]\\)" end t
))
9407 (goto-char (match-beginning 1)))
9408 (if (looking-at "[-:]")
9410 (beginning-of-line 0)
9411 (markdown-table-insert-row 'below
))
9412 (when (looking-at " ") (forward-char 1))))
9413 (error (markdown-table-insert-row 'below
)))))
9415 (defun markdown-table-backward-cell ()
9416 "Go to the previous cell in the table."
9418 (unless (markdown-table-at-point-p)
9419 (user-error "Not at a table"))
9420 (when markdown-table-align-p
9421 (markdown-table-align))
9422 (when (markdown-table-hline-at-point-p) (beginning-of-line 1))
9425 (re-search-backward "\\(?:^\\|[^\\]\\)|" (markdown-table-begin))
9426 ;; When this function is called while in the first cell in a
9427 ;; table, the point will now be at the beginning of a line. In
9428 ;; this case, we need to move past one additional table
9429 ;; boundary, the end of the table on the previous line.
9430 (when (= (point) (line-beginning-position))
9431 (re-search-backward "\\(?:^\\|[^\\]\\)|" (markdown-table-begin)))
9432 (re-search-backward "\\(?:^\\|[^\\]\\)|" (markdown-table-begin)))
9433 (error (user-error "Cannot move to previous table cell")))
9434 (when (looking-at "\\(?:^\\|[^\\]\\)| ?") (goto-char (match-end 0)))
9436 ;; This may have dropped point on the hline.
9437 (when (markdown-table-hline-at-point-p)
9438 (markdown-table-backward-cell)))
9440 (defun markdown-table-transpose ()
9441 "Transpose table at point.
9442 Horizontal separator lines will be eliminated."
9444 (unless (markdown-table-at-point-p)
9445 (user-error "Not at a table"))
9446 (let* ((table (buffer-substring-no-properties
9447 (markdown-table-begin) (markdown-table-end)))
9448 ;; Convert table to Lisp structure
9452 (unless (string-match-p
9453 markdown-table-hline-regexp x
)
9454 (markdown--table-line-to-columns x
)))
9455 (markdown--split-string table
"[ \t]*\n[ \t]*"))))
9456 (dline_old (markdown-table-get-dline))
9457 (col_old (markdown-table-get-column))
9458 (contents (mapcar (lambda (_)
9464 (setq tp
(cdr tp
))))
9467 (goto-char (markdown-table-begin))
9469 (re-search-forward "|") (backward-char)
9470 (delete-region (point) (markdown-table-end))
9473 (concat "| " (mapconcat 'identity x
" | " ) " |\n"))
9475 (markdown-table-goto-dline col_old
)
9476 (markdown-table-goto-column dline_old
))
9477 (when markdown-table-align-p
9478 (markdown-table-align)))
9480 (defun markdown-table-sort-lines (&optional sorting-type
)
9481 "Sort table lines according to the column at point.
9483 The position of point indicates the column to be used for
9484 sorting, and the range of lines is the range between the nearest
9485 horizontal separator lines, or the entire table of no such lines
9486 exist. If point is before the first column, user will be prompted
9487 for the sorting column. If there is an active region, the mark
9488 specifies the first line and the sorting column, while point
9489 should be in the last line to be included into the sorting.
9491 The command then prompts for the sorting type which can be
9492 alphabetically or numerically. Sorting in reverse order is also
9495 If SORTING-TYPE is specified when this function is called from a
9496 Lisp program, no prompting will take place. SORTING-TYPE must be
9497 a character, any of (?a ?A ?n ?N) where the capital letters
9498 indicate that sorting should be done in reverse order."
9500 (unless (markdown-table-at-point-p)
9501 (user-error "Not at a table"))
9502 ;; Set sorting type and column used for sorting
9503 (let ((column (let ((c (markdown-table-get-column)))
9505 ((called-interactively-p 'any
)
9506 (read-number "Use column N for sorting: "))
9512 ;; Emacs < 28 hides prompt message by another message. This erases it.
9514 (read-char-exclusive
9515 "Sort type: [a]lpha [n]umeric (A/N means reversed): ")))))
9517 ;; Narrow buffer to appropriate sorting area
9518 (if (region-active-p)
9522 (goto-char (region-beginning)) (line-beginning-position)))
9525 (goto-char (region-end)) (line-end-position))))
9526 (let ((start (markdown-table-begin))
9527 (end (markdown-table-end)))
9530 (if (re-search-backward
9531 markdown-table-hline-regexp start t
)
9532 (line-beginning-position 2)
9534 (if (save-excursion (re-search-forward
9535 markdown-table-hline-regexp end t
))
9538 ;; Determine arguments for `sort-subr'
9539 (let* ((extract-key-from-cell
9540 (cl-case sorting-type
9541 ((?a ?A
) #'markdown--remove-invisible-markup
) ;; #'identity)
9542 ((?n ?N
) #'string-to-number
)
9543 (t (user-error "Invalid sorting type: %c" sorting-type
))))
9545 (cl-case sorting-type
9547 ((?a ?A
) #'string
<))))
9548 ;; Sort selected area
9549 (goto-char (point-min))
9550 (sort-subr (memq sorting-type
'(?A ?N
))
9553 (while (and (not (eobp))
9555 markdown-table-dline-regexp
)))
9559 (funcall extract-key-from-cell
9560 (markdown-table-get-cell column
)))
9563 (goto-char (point-min))))))
9565 (defun markdown-table-convert-region (begin end
&optional separator
)
9566 "Convert region from BEGIN to END to table with SEPARATOR.
9568 If every line contains at least one TAB character, the function
9569 assumes that the material is tab separated (TSV). If every line
9570 contains a comma, comma-separated values (CSV) are assumed. If
9571 not, lines are split at whitespace into cells.
9573 You can use a prefix argument to force a specific separator:
9574 \\[universal-argument] once forces CSV, \\[universal-argument]
9575 twice forces TAB, and \\[universal-argument] three times will
9576 prompt for a regular expression to match the separator, and a
9577 numeric argument N indicates that at least N consecutive
9578 spaces, or alternatively a TAB should be used as the separator."
9580 (interactive "r\nP")
9581 (let* ((begin (min begin end
)) (end (max begin end
)) re
)
9582 (goto-char begin
) (beginning-of-line 1)
9583 (setq begin
(point-marker))
9585 (if (bolp) (backward-char 1) (end-of-line 1))
9586 (setq end
(point-marker))
9587 (when (equal separator
'(64))
9588 (setq separator
(read-regexp "Regexp for cell separator: ")))
9590 ;; Get the right cell separator
9594 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
9595 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
9598 (if (equal separator
'(4))
9600 (while (< (point) end
)
9602 ((looking-at "^") (insert "| "))
9603 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
9604 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
9605 (replace-match "\\1") (if (looking-at "\"") (insert "\"")))
9606 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
9607 ((looking-at "[ \t]*,") (replace-match " | "))
9608 (t (beginning-of-line 2))))
9611 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
9612 ((equal separator
'(16)) "^\\|\t")
9613 ((integerp separator
)
9615 (user-error "Cell separator must contain one or more spaces")
9616 (format "^ *\\| *\t *\\| \\{%d,\\}\\|$" separator
)))
9617 ((stringp separator
) (format "^ *\\|%s" separator
))
9618 (t (error "Invalid cell separator"))))
9620 (while (and (not finish
) (re-search-forward re end t
))
9623 (replace-match "|" t t
)
9627 (replace-match "| " t t
)))))
9629 (when markdown-table-align-p
9630 (markdown-table-align))))
9632 (defun markdown-insert-table (&optional rows columns align
)
9633 "Insert an empty pipe table.
9634 Optional arguments ROWS, COLUMNS, and ALIGN specify number of
9635 rows and columns and the column alignment."
9637 (let* ((rows (or rows
(string-to-number (read-string "Row size: "))))
9638 (columns (or columns
(string-to-number (read-string "Column size: "))))
9639 (align (or align
(read-string "Alignment ([l]eft, [r]ight, [c]enter, or RET for default): ")))
9640 (align (cond ((equal align
"l") ":--")
9641 ((equal align
"r") "--:")
9642 ((equal align
"c") ":-:")
9645 (indent (make-string (current-column) ?\
))
9647 (apply 'concat indent
"|"
9648 (make-list columns
" |")) "\n"))
9649 (hline (apply 'concat indent
"|"
9650 (make-list columns
(concat align
"|")))))
9652 "^[ \t]*$" (buffer-substring-no-properties
9653 (point-at-bol) (point)))
9654 (beginning-of-line 1)
9656 (dotimes (_ rows
) (insert line
))
9660 (end-of-line 1) (insert (concat "\n" hline
)) (goto-char pos
)))
9661 (markdown-table-forward-cell)))
9664 ;;; ElDoc Support =============================================================
9666 (defun markdown-eldoc-function ()
9667 "Return a helpful string when appropriate based on context.
9668 * Report URL when point is at a hidden URL.
9669 * Report language name when point is a code block with hidden markup."
9671 ;; Hidden URL or reference for inline link
9672 ((and (or (thing-at-point-looking-at markdown-regex-link-inline
)
9673 (thing-at-point-looking-at markdown-regex-link-reference
))
9674 (or markdown-hide-urls markdown-hide-markup
))
9675 (let* ((imagep (string-equal (match-string 1) "!"))
9676 (referencep (string-equal (match-string 5) "["))
9677 (link (match-string-no-properties 6))
9678 (edit-keys (markdown--substitute-command-keys
9680 "\\[markdown-insert-image]"
9681 "\\[markdown-insert-link]")))
9682 (edit-str (propertize edit-keys
'face
'font-lock-constant-face
))
9683 (object (if referencep
"reference" "URL")))
9684 (format "Hidden %s (%s to edit): %s" object edit-str
9687 (propertize "[" 'face
'markdown-markup-face
)
9688 (propertize link
'face
'markdown-reference-face
)
9689 (propertize "]" 'face
'markdown-markup-face
))
9690 (propertize link
'face
'markdown-url-face
)))))
9691 ;; Hidden language name for fenced code blocks
9692 ((and (markdown-code-block-at-point-p)
9693 (not (get-text-property (point) 'markdown-pre
))
9694 markdown-hide-markup
)
9695 (let ((lang (save-excursion (markdown-code-block-lang))))
9696 (unless lang
(setq lang
"[unspecified]"))
9697 (format "Hidden code block language: %s (%s to toggle markup)"
9698 (propertize lang
'face
'markdown-language-keyword-face
)
9699 (markdown--substitute-command-keys
9700 "\\[markdown-toggle-markup-hiding]"))))))
9703 ;;; Mode Definition ==========================================================
9705 (defun markdown-show-version ()
9706 "Show the version number in the minibuffer."
9708 (message "markdown-mode, version %s" markdown-mode-version
))
9710 (defun markdown-mode-info ()
9711 "Open the `markdown-mode' homepage."
9713 (browse-url "https://jblevins.org/projects/markdown-mode/"))
9716 (define-derived-mode markdown-mode text-mode
"Markdown"
9717 "Major mode for editing Markdown files."
9718 (when buffer-read-only
9719 (when (or (not (buffer-file-name)) (file-writable-p (buffer-file-name)))
9720 (setq-local buffer-read-only nil
)))
9721 ;; Natural Markdown tab width
9724 (setq-local comment-start
"<!-- ")
9725 (setq-local comment-end
" -->")
9726 (setq-local comment-start-skip
"<!--[ \t]*")
9727 (setq-local comment-column
0)
9728 (setq-local comment-auto-fill-only-comments nil
)
9729 (setq-local comment-use-syntax t
)
9731 (setq-local sentence-end-base
"[.?!…‽][]\"'”’)}»›*_`~]*")
9733 (add-hook 'syntax-propertize-extend-region-functions
9734 #'markdown-syntax-propertize-extend-region nil t
)
9735 (add-hook 'jit-lock-after-change-extend-region-functions
9736 #'markdown-font-lock-extend-region-function t t
)
9737 (setq-local syntax-propertize-function
#'markdown-syntax-propertize
)
9738 (syntax-propertize (point-max)) ;; Propertize before hooks run, etc.
9740 (setq font-lock-defaults
9741 '(markdown-mode-font-lock-keywords
9743 (font-lock-multiline . t
)
9744 (font-lock-syntactic-face-function . markdown-syntactic-face
)
9745 (font-lock-extra-managed-props
9746 .
(composition display invisible rear-nonsticky
9747 keymap help-echo mouse-face
))))
9748 (if markdown-hide-markup
9749 (add-to-invisibility-spec 'markdown-markup
)
9750 (remove-from-invisibility-spec 'markdown-markup
))
9752 (markdown-setup-wiki-link-hooks)
9754 (when markdown-enable-math
(markdown-toggle-math t
))
9755 ;; Add a buffer-local hook to reload after file-local variables are read
9756 (add-hook 'hack-local-variables-hook
#'markdown-handle-local-variables nil t
)
9757 ;; For imenu support
9758 (setq imenu-create-index-function
9759 (if markdown-nested-imenu-heading-index
9760 #'markdown-imenu-create-nested-index
9761 #'markdown-imenu-create-flat-index
))
9764 (setq-local beginning-of-defun-function
#'markdown-beginning-of-defun
)
9765 (setq-local end-of-defun-function
#'markdown-end-of-defun
)
9766 ;; Paragraph filling
9767 (setq-local fill-paragraph-function
#'markdown-fill-paragraph
)
9768 (setq-local paragraph-start
9769 ;; Should match start of lines that start or separate paragraphs
9770 (mapconcat #'identity
9772 "\f" ; starts with a literal line-feed
9773 "[ \t\f]*$" ; space-only line
9774 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9775 "[ \t]*[*+-][ \t]+" ; unordered list item
9776 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
9777 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
9778 "[ \t]*:[ \t]+" ; definition
9779 "^|" ; table or Pandoc line block
9782 (setq-local paragraph-separate
9783 ;; Should match lines that separate paragraphs without being
9784 ;; part of any paragraph:
9785 (mapconcat #'identity
9786 '("[ \t\f]*$" ; space-only line
9787 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9788 ;; The following is not ideal, but the Fill customization
9789 ;; options really only handle paragraph-starting prefixes,
9790 ;; not paragraph-ending suffixes:
9791 ".* $" ; line ending in two spaces
9793 "^\\(?: \\)?[-=]+[ \t]*$" ;; setext
9794 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
9796 (setq-local adaptive-fill-first-line-regexp
"\\`[ \t]*[A-Z]?>[ \t]*?\\'")
9797 (setq-local adaptive-fill-regexp
"\\s-*")
9798 (setq-local adaptive-fill-function
#'markdown-adaptive-fill-function
)
9799 (setq-local fill-forward-paragraph-function
#'markdown-fill-forward-paragraph
)
9801 (setq-local outline-regexp markdown-regex-header
)
9802 (setq-local outline-level
#'markdown-outline-level
)
9803 ;; Cause use of ellipses for invisible text.
9804 (add-to-invisibility-spec '(outline . t
))
9806 (add-function :before-until
(local 'eldoc-documentation-function
)
9807 #'markdown-eldoc-function
)
9808 ;; Inhibiting line-breaking:
9809 ;; Separating out each condition into a separate function so that users can
9810 ;; override if desired (with remove-hook)
9811 (add-hook 'fill-nobreak-predicate
9812 #'markdown-line-is-reference-definition-p nil t
)
9813 (add-hook 'fill-nobreak-predicate
9814 #'markdown-pipe-at-bol-p nil t
)
9817 (setq-local indent-line-function markdown-indent-function
)
9818 (setq-local indent-region-function
#'markdown--indent-region
)
9821 (setq-local flyspell-generic-check-word-predicate
9822 #'markdown-flyspell-check-word-p
)
9825 (add-hook 'electric-quote-inhibit-functions
9826 #'markdown--inhibit-electric-quote nil
:local
)
9828 ;; Make checkboxes buttons
9829 (when markdown-make-gfm-checkboxes-buttons
9830 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
9831 (add-hook 'after-change-functions
#'markdown-gfm-checkbox-after-change-function t t
)
9832 (add-hook 'change-major-mode-hook
#'markdown-remove-gfm-checkbox-overlays t t
))
9835 (add-hook 'edit-indirect-after-commit-functions
9836 #'markdown--edit-indirect-after-commit-function
9839 ;; Marginalized headings
9840 (when markdown-marginalize-headers
9841 (add-hook 'window-configuration-change-hook
9842 #'markdown-marginalize-update-current nil t
))
9844 ;; add live preview export hook
9845 (add-hook 'after-save-hook
#'markdown-live-preview-if-markdown t t
)
9846 (add-hook 'kill-buffer-hook
#'markdown-live-preview-remove-on-kill t t
))
9849 (add-to-list 'auto-mode-alist
9850 '("\\.\\(?:md\\|markdown\\|mkd\\|mdown\\|mkdn\\|mdwn\\)\\'" . markdown-mode
))
9853 ;;; GitHub Flavored Markdown Mode ============================================
9855 (defun gfm--electric-pair-fence-code-block ()
9856 (when (and electric-pair-mode
9857 (not markdown-gfm-use-electric-backquote
)
9858 (eql last-command-event ?
`)
9860 (while (eql (char-before (- (point) count
)) ?
`)
9863 (eql (char-after) ?
`))
9864 (save-excursion (insert (make-string 2 ?
`)))))
9866 (defvar gfm-mode-hook nil
9867 "Hook run when entering GFM mode.")
9870 (define-derived-mode gfm-mode markdown-mode
"GFM"
9871 "Major mode for editing GitHub Flavored Markdown files."
9872 (setq markdown-link-space-sub-char
"-")
9873 (setq markdown-wiki-link-search-subdirectories t
)
9874 (setq-local markdown-table-at-point-p-function
#'gfm--table-at-point-p
)
9875 (add-hook 'post-self-insert-hook
#'gfm--electric-pair-fence-code-block
'append t
)
9876 (markdown-gfm-parse-buffer-for-languages))
9879 ;;; Viewing modes =============================================================
9881 (defcustom markdown-hide-markup-in-view-modes t
9882 "Enable hidden markup mode in `markdown-view-mode' and `gfm-view-mode'."
9887 (defvar markdown-view-mode-map
9888 (let ((map (make-sparse-keymap)))
9889 (define-key map
(kbd "p") #'markdown-outline-previous
)
9890 (define-key map
(kbd "n") #'markdown-outline-next
)
9891 (define-key map
(kbd "f") #'markdown-outline-next-same-level
)
9892 (define-key map
(kbd "b") #'markdown-outline-previous-same-level
)
9893 (define-key map
(kbd "u") #'markdown-outline-up
)
9894 (define-key map
(kbd "DEL") #'scroll-down-command
)
9895 (define-key map
(kbd "SPC") #'scroll-up-command
)
9896 (define-key map
(kbd ">") #'end-of-buffer
)
9897 (define-key map
(kbd "<") #'beginning-of-buffer
)
9898 (define-key map
(kbd "q") #'kill-this-buffer
)
9899 (define-key map
(kbd "?") #'describe-mode
)
9901 "Keymap for `markdown-view-mode'.")
9903 (defun markdown--filter-visible (beg end
&optional delete
)
9905 (invisible-faces '(markdown-header-delimiter-face markdown-header-rule-face
)))
9907 (when (markdown--face-p beg invisible-faces
)
9909 (while (and (markdown--face-p beg invisible-faces
) (< beg end
))
9911 (let ((next (next-single-char-property-change beg
'invisible
)))
9912 (unless (get-char-property beg
'invisible
)
9913 (setq result
(concat result
(buffer-substring beg
(min end next
)))))
9917 (let ((inhibit-read-only t
))
9918 (delete-region beg end
))))))
9921 (define-derived-mode markdown-view-mode markdown-mode
"Markdown-View"
9922 "Major mode for viewing Markdown content."
9923 (setq-local markdown-hide-markup markdown-hide-markup-in-view-modes
)
9924 (add-to-invisibility-spec 'markdown-markup
)
9925 (setq-local filter-buffer-substring-function
#'markdown--filter-visible
)
9928 (defvar gfm-view-mode-map
9929 markdown-view-mode-map
9930 "Keymap for `gfm-view-mode'.")
9933 (define-derived-mode gfm-view-mode gfm-mode
"GFM-View"
9934 "Major mode for viewing GitHub Flavored Markdown content."
9935 (setq-local markdown-hide-markup markdown-hide-markup-in-view-modes
)
9936 (setq-local markdown-fontify-code-blocks-natively t
)
9937 (setq-local filter-buffer-substring-function
#'markdown--filter-visible
)
9938 (add-to-invisibility-spec 'markdown-markup
)
9942 ;;; Live Preview Mode ========================================================
9944 (define-minor-mode markdown-live-preview-mode
9945 "Toggle native previewing on save for a specific markdown file."
9946 :lighter
" MD-Preview"
9947 (if markdown-live-preview-mode
9948 (if (markdown-live-preview-get-filename)
9949 (markdown-display-buffer-other-window (markdown-live-preview-export))
9950 (markdown-live-preview-mode -
1)
9951 (user-error "Buffer %s does not visit a file" (current-buffer)))
9952 (markdown-live-preview-remove)))
9955 (provide 'markdown-mode
)
9958 ;; indent-tabs-mode: nil
9961 ;;; markdown-mode.el ends here