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 (line-beginning-position) (line-end-position)))
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 (line-beginning-position) (line-end-position)))
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+ (line-end-position))))
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
))
1654 (line-end-position)))
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--pandoc-reference-p ()
2241 (let ((bounds (bounds-of-thing-at-point 'word
)))
2242 (when (and bounds
(char-before (car bounds
)))
2243 (= (char-before (car bounds
)) ?
@))))
2245 (defun markdown-flyspell-check-word-p ()
2246 "Return t if `flyspell' should check word just before point.
2247 Used for `flyspell-generic-check-word-predicate'."
2249 (goto-char (1- (point)))
2250 ;; https://github.com/jrblevin/markdown-mode/issues/560
2251 ;; enable spell check YAML meta data
2252 (if (or (and (markdown-code-block-at-point-p)
2253 (not (markdown-text-property-at-point 'markdown-yaml-metadata-section
)))
2254 (markdown-inline-code-at-point-p)
2255 (markdown-in-comment-p)
2256 (markdown--face-p (point) '(markdown-reference-face
2257 markdown-markup-face
2258 markdown-plain-url-face
2259 markdown-inline-code-face
2261 (markdown--pandoc-reference-p))
2263 ;; If flyspell overlay is put, then remove it
2264 (let ((bounds (bounds-of-thing-at-point 'word
)))
2266 (cl-loop for ov in
(overlays-in (car bounds
) (cdr bounds
))
2267 when
(overlay-get ov
'flyspell-overlay
)
2269 (delete-overlay ov
)))))
2273 ;;; Markdown Parsing Functions ================================================
2275 (defun markdown-cur-line-blank-p ()
2276 "Return t if the current line is blank and nil otherwise."
2279 (looking-at-p markdown-regex-blank-line
)))
2281 (defun markdown-prev-line-blank ()
2282 "Return t if the previous line is blank and nil otherwise.
2283 If we are at the first line, then consider the previous line to be blank."
2284 (or (= (line-beginning-position) (point-min))
2287 (looking-at markdown-regex-blank-line
))))
2289 (defun markdown-prev-line-blank-p ()
2290 "Like `markdown-prev-line-blank', but preserve `match-data'."
2291 (save-match-data (markdown-prev-line-blank)))
2293 (defun markdown-next-line-blank-p ()
2294 "Return t if the next line is blank and nil otherwise.
2295 If we are at the last line, then consider the next line to be blank."
2296 (or (= (line-end-position) (point-max))
2299 (markdown-cur-line-blank-p))))
2301 (defun markdown-prev-line-indent ()
2302 "Return the number of leading whitespace characters in the previous line.
2303 Return 0 if the current line is the first line in the buffer."
2305 (if (= (line-beginning-position) (point-min))
2308 (current-indentation))))
2310 (defun markdown-next-line-indent ()
2311 "Return the number of leading whitespace characters in the next line.
2312 Return 0 if line is the last line in the buffer."
2314 (if (= (line-end-position) (point-max))
2317 (current-indentation))))
2319 (defun markdown-new-baseline ()
2320 "Determine if the current line begins a new baseline level.
2321 Assume point is positioned at beginning of line."
2322 (or (looking-at markdown-regex-header
)
2323 (looking-at markdown-regex-hr
)
2324 (and (= (current-indentation) 0)
2325 (not (looking-at markdown-regex-list
))
2326 (markdown-prev-line-blank))))
2328 (defun markdown-search-backward-baseline ()
2329 "Search backward baseline point with no indentation and not a list item."
2332 (while (not (or stop
(bobp)))
2333 (re-search-backward markdown-regex-block-separator-noindent nil t
)
2335 (goto-char (match-end 2))
2337 ((markdown-new-baseline)
2339 ((looking-at-p markdown-regex-list
)
2341 (t (setq stop t
)))))))
2343 (defun markdown-update-list-levels (marker indent levels
)
2344 "Update list levels given list MARKER, block INDENT, and current LEVELS.
2345 Here, MARKER is a string representing the type of list, INDENT is an integer
2346 giving the indentation, in spaces, of the current block, and LEVELS is a
2347 list of the indentation levels of parent list items. When LEVELS is nil,
2348 it means we are at baseline (not inside of a nested list)."
2350 ;; New list item at baseline.
2351 ((and marker
(null levels
))
2352 (setq levels
(list indent
)))
2353 ;; List item with greater indentation (four or more spaces).
2354 ;; Increase list level.
2355 ((and marker
(>= indent
(+ (car levels
) markdown-list-indent-width
)))
2356 (setq levels
(cons indent levels
)))
2357 ;; List item with greater or equal indentation (less than four spaces).
2358 ;; Do not increase list level.
2359 ((and marker
(>= indent
(car levels
)))
2361 ;; Lesser indentation level.
2362 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
2363 ;; indentation could move back more than one list level). Note
2364 ;; that this block need not be the beginning of list item.
2365 ((< indent
(car levels
))
2366 (while (and (> (length levels
) 1)
2367 (< indent
(+ (cadr levels
) markdown-list-indent-width
)))
2368 (setq levels
(cdr levels
)))
2370 ;; Otherwise, do nothing.
2373 (defun markdown-calculate-list-levels ()
2374 "Calculate list levels at point.
2375 Return a list of the form (n1 n2 n3 ...) where n1 is the
2376 indentation of the deepest nested list item in the branch of
2377 the list at the point, n2 is the indentation of the parent
2378 list item, and so on. The depth of the list item is therefore
2379 the length of the returned list. If the point is not at or
2380 immediately after a list item, return nil."
2382 (let ((first (point)) levels indent pre-regexp
)
2383 ;; Find a baseline point with zero list indentation
2384 (markdown-search-backward-baseline)
2385 ;; Search for all list items between baseline and LOC
2386 (while (and (< (point) first
)
2387 (re-search-forward markdown-regex-list first t
))
2388 (setq pre-regexp
(format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels
))))
2391 ;; Make sure this is not a header or hr
2392 ((markdown-new-baseline) (setq levels nil
))
2393 ;; Make sure this is not a line from a pre block
2394 ((looking-at-p pre-regexp
))
2395 ;; If not, then update levels
2397 (setq indent
(current-indentation))
2398 (setq levels
(markdown-update-list-levels (match-string 2)
2403 (defun markdown-prev-list-item (level)
2404 "Search backward from point for a list item with indentation LEVEL.
2405 Set point to the beginning of the item, and return point, or nil
2407 (let (bounds indent prev
)
2410 (setq indent
(current-indentation))
2414 ((and (looking-at-p markdown-regex-list
)
2415 (setq bounds
(markdown-cur-list-item-bounds)))
2417 ;; Stop and return point at item of equal indentation
2418 ((= (nth 3 bounds
) level
)
2421 ;; Stop and return nil at item with lesser indentation
2422 ((< (nth 3 bounds
) level
)
2425 ;; Stop at beginning of buffer
2426 ((bobp) (setq prev nil
))
2427 ;; Continue at item with greater indentation
2428 ((> (nth 3 bounds
) level
) t
)))
2429 ;; Stop at beginning of buffer
2430 ((bobp) (setq prev nil
))
2431 ;; Continue if current line is blank
2432 ((markdown-cur-line-blank-p) t
)
2433 ;; Continue while indentation is the same or greater
2434 ((>= indent level
) t
)
2435 ;; Stop if current indentation is less than list item
2436 ;; and the next is blank
2437 ((and (< indent level
)
2438 (markdown-next-line-blank-p))
2441 ((looking-at-p markdown-regex-header
) (setq prev nil
))
2442 ;; Stop at a horizontal rule
2443 ((looking-at-p markdown-regex-hr
) (setq prev nil
))
2444 ;; Otherwise, continue.
2447 (setq indent
(current-indentation)))
2450 (defun markdown-next-list-item (level)
2451 "Search forward from point for the next list item with indentation LEVEL.
2452 Set point to the beginning of the item, and return point, or nil
2454 (let (bounds indent next
)
2456 (if (looking-at markdown-regex-header-setext
)
2457 (goto-char (match-end 0)))
2459 (setq indent
(current-indentation))
2462 ;; Stop at end of the buffer.
2464 ;; Continue if the current line is blank
2465 ((markdown-cur-line-blank-p) t
)
2467 ((and (looking-at-p markdown-regex-list
)
2468 (setq bounds
(markdown-cur-list-item-bounds)))
2470 ;; Continue at item with greater indentation
2471 ((> (nth 3 bounds
) level
) t
)
2472 ;; Stop and return point at item of equal indentation
2473 ((= (nth 3 bounds
) level
)
2476 ;; Stop and return nil at item with lesser indentation
2477 ((< (nth 3 bounds
) level
)
2480 ;; Continue while indentation is the same or greater
2481 ((>= indent level
) t
)
2482 ;; Stop if current indentation is less than list item
2483 ;; and the previous line was blank.
2484 ((and (< indent level
)
2485 (markdown-prev-line-blank-p))
2488 ((looking-at-p markdown-regex-header
) (setq next nil
))
2489 ;; Stop at a horizontal rule
2490 ((looking-at-p markdown-regex-hr
) (setq next nil
))
2491 ;; Otherwise, continue.
2494 (setq indent
(current-indentation)))
2497 (defun markdown-cur-list-item-end (level)
2498 "Move to end of list item with pre-marker indentation LEVEL.
2499 Return the point at the end when a list item was found at the
2500 original point. If the point is not in a list item, do nothing."
2503 (setq indent
(current-indentation))
2506 ;; Stop at end of the buffer.
2508 ;; Continue while indentation is the same or greater
2509 ((>= indent level
) t
)
2510 ;; Continue if the current line is blank
2511 ((looking-at markdown-regex-blank-line
) t
)
2512 ;; Stop if current indentation is less than list item
2513 ;; and the previous line was blank.
2514 ((and (< indent level
)
2515 (markdown-prev-line-blank))
2517 ;; Stop at a new list items of the same or lesser
2518 ;; indentation, headings, and horizontal rules.
2519 ((looking-at (concat "\\(?:" markdown-regex-list
2520 "\\|" markdown-regex-header
2521 "\\|" markdown-regex-hr
"\\)"))
2523 ;; Otherwise, continue.
2526 (setq indent
(current-indentation)))
2527 ;; Don't skip over whitespace for empty list items (marker and
2528 ;; whitespace only), just move to end of whitespace.
2531 (looking-at (concat markdown-regex-list
"[ \t]*$")))
2532 (goto-char (match-end 3))
2533 (skip-chars-backward " \t\n"))
2537 (defun markdown-cur-list-item-bounds ()
2538 "Return bounds for list item at point.
2539 Return a list of the following form:
2541 (begin end indent nonlist-indent marker checkbox match)
2543 The named components are:
2545 - begin: Position of beginning of list item, including leading indentation.
2546 - end: Position of the end of the list item, including list item text.
2547 - indent: Number of characters of indentation before list marker (an integer).
2548 - nonlist-indent: Number characters of indentation, list
2549 marker, and whitespace following list marker (an integer).
2550 - marker: String containing the list marker and following whitespace
2551 (e.g., \"- \" or \"* \").
2552 - checkbox: String containing the GFM checkbox portion, if any,
2553 including any trailing whitespace before the text
2554 begins (e.g., \"[x] \").
2555 - match: match data for markdown-regex-list
2557 As an example, for the following unordered list item
2561 the returned list would be
2563 (1 14 3 5 \"- \" nil (1 6 1 4 4 5 5 6))
2565 If the point is not inside a list item, return nil."
2566 (car (get-text-property (line-beginning-position) 'markdown-list-item
)))
2568 (defun markdown-list-item-at-point-p ()
2569 "Return t if there is a list item at the point and nil otherwise."
2570 (save-match-data (markdown-cur-list-item-bounds)))
2572 (defun markdown-prev-list-item-bounds ()
2573 "Return bounds of previous item in the same list of any level.
2574 The return value has the same form as that of
2575 `markdown-cur-list-item-bounds'."
2577 (let ((cur-bounds (markdown-cur-list-item-bounds))
2578 (beginning-of-list (save-excursion (markdown-beginning-of-list)))
2581 (goto-char (nth 0 cur-bounds
))
2582 (while (and (not stop
) (not (bobp))
2583 (re-search-backward markdown-regex-list
2584 beginning-of-list t
))
2585 (unless (or (looking-at markdown-regex-hr
)
2586 (markdown-code-block-at-point-p))
2587 (setq stop
(point))))
2588 (markdown-cur-list-item-bounds)))))
2590 (defun markdown-next-list-item-bounds ()
2591 "Return bounds of next item in the same list of any level.
2592 The return value has the same form as that of
2593 `markdown-cur-list-item-bounds'."
2595 (let ((cur-bounds (markdown-cur-list-item-bounds))
2596 (end-of-list (save-excursion (markdown-end-of-list)))
2599 (goto-char (nth 0 cur-bounds
))
2601 (while (and (not stop
) (not (eobp))
2602 (re-search-forward markdown-regex-list
2604 (unless (or (looking-at markdown-regex-hr
)
2605 (markdown-code-block-at-point-p))
2606 (setq stop
(point))))
2608 (markdown-cur-list-item-bounds))))))
2610 (defun markdown-beginning-of-list ()
2611 "Move point to beginning of list at point, if any."
2613 (let ((orig-point (point))
2614 (list-begin (save-excursion
2615 (markdown-search-backward-baseline)
2616 ;; Stop at next list item, regardless of the indentation.
2617 (markdown-next-list-item (point-max))
2618 (when (looking-at markdown-regex-list
)
2620 (when (and list-begin
(<= list-begin orig-point
))
2621 (goto-char list-begin
))))
2623 (defun markdown-end-of-list ()
2624 "Move point to end of list at point, if any."
2626 (let ((start (point))
2627 (end (save-excursion
2628 (when (markdown-beginning-of-list)
2629 ;; Items can't have nonlist-indent <= 1, so this
2630 ;; moves past all list items.
2631 (markdown-next-list-item 1)
2632 (skip-syntax-backward "-")
2633 (unless (eobp) (forward-char 1))
2635 (when (and end
(>= end start
))
2638 (defun markdown-up-list ()
2639 "Move point to beginning of parent list item."
2641 (let ((cur-bounds (markdown-cur-list-item-bounds)))
2643 (markdown-prev-list-item (1- (nth 3 cur-bounds
)))
2644 (let ((up-bounds (markdown-cur-list-item-bounds)))
2645 (when (and up-bounds
(< (nth 3 up-bounds
) (nth 3 cur-bounds
)))
2648 (defun markdown-bounds-of-thing-at-point (thing)
2649 "Call `bounds-of-thing-at-point' for THING with slight modifications.
2650 Does not include trailing newlines when THING is \\='line. Handles the
2651 end of buffer case by setting both endpoints equal to the value of
2652 `point-max', since an empty region will trigger empty markup insertion.
2653 Return bounds of form (beg . end) if THING is found, or nil otherwise."
2654 (let* ((bounds (bounds-of-thing-at-point thing
))
2658 (when (eq thing
'line
)
2659 (cond ((and (eobp) (markdown-cur-line-blank-p))
2661 ((char-equal (char-before b
) ?\^J
)
2665 (defun markdown-reference-definition (reference)
2666 "Find out whether Markdown REFERENCE is defined.
2667 REFERENCE should not include the square brackets.
2668 When REFERENCE is defined, return a list of the form (text start end)
2669 containing the definition text itself followed by the start and end
2670 locations of the text. Otherwise, return nil.
2671 Leave match data for `markdown-regex-reference-definition'
2672 intact additional processing."
2673 (let ((reference (downcase reference
)))
2675 (goto-char (point-min))
2677 (while (re-search-forward markdown-regex-reference-definition nil t
)
2678 (when (string= reference
(downcase (match-string-no-properties 2)))
2680 (list (match-string-no-properties 5)
2681 (match-beginning 5) (match-end 5)))))))))
2683 (defun markdown-get-defined-references ()
2684 "Return all defined reference labels and their line numbers.
2685 They does not include square brackets)."
2687 (goto-char (point-min))
2689 (while (re-search-forward markdown-regex-reference-definition nil t
)
2690 (let ((target (match-string-no-properties 2)))
2692 (cons (downcase target
)
2693 (markdown-line-number-at-pos (match-beginning 2)))
2694 refs
:test
#'equal
:key
#'car
)))
2697 (defun markdown-get-used-uris ()
2698 "Return a list of all used URIs in the buffer."
2700 (goto-char (point-min))
2702 (while (re-search-forward
2703 (concat "\\(?:" markdown-regex-link-inline
2704 "\\|" markdown-regex-angle-uri
2705 "\\|" markdown-regex-uri
2706 "\\|" markdown-regex-email
2709 (unless (or (markdown-inline-code-at-point-p)
2710 (markdown-code-block-at-point-p))
2711 (cl-pushnew (or (match-string-no-properties 6)
2712 (match-string-no-properties 10)
2713 (match-string-no-properties 12)
2714 (match-string-no-properties 13))
2715 uris
:test
#'equal
)))
2718 (defun markdown-inline-code-at-pos (pos)
2719 "Return non-nil if there is an inline code fragment at POS.
2720 Return nil otherwise. Set match data according to
2721 `markdown-match-code' upon success.
2722 This function searches the block for a code fragment that
2723 contains the point using `markdown-match-code'. We do this
2724 because `thing-at-point-looking-at' does not work reliably with
2725 `markdown-regex-code'.
2727 The match data is set as follows:
2728 Group 1 matches the opening backquotes.
2729 Group 2 matches the code fragment itself, without backquotes.
2730 Group 3 matches the closing backquotes."
2733 (let ((old-point (point))
2734 (end-of-block (progn (markdown-end-of-text-block) (point)))
2736 (markdown-beginning-of-text-block)
2737 (while (and (markdown-match-code end-of-block
)
2739 (< (match-end 0) old-point
)))
2740 (let ((match-group (if (eq (char-after (match-beginning 0)) ?
`) 0 1)))
2741 (and found
; matched something
2742 (<= (match-beginning match-group
) old-point
) ; match contains old-point
2743 (> (match-end 0) old-point
))))))
2745 (defun markdown-inline-code-at-pos-p (pos)
2746 "Return non-nil if there is an inline code fragment at POS.
2747 Like `markdown-inline-code-at-pos`, but preserves match data."
2748 (save-match-data (markdown-inline-code-at-pos pos
)))
2750 (defun markdown-inline-code-at-point ()
2751 "Return non-nil if the point is at an inline code fragment.
2752 See `markdown-inline-code-at-pos' for details."
2753 (markdown-inline-code-at-pos (point)))
2755 (defun markdown-inline-code-at-point-p (&optional pos
)
2756 "Return non-nil if there is inline code at the POS.
2757 This is a predicate function counterpart to
2758 `markdown-inline-code-at-point' which does not modify the match
2759 data. See `markdown-code-block-at-point-p' for code blocks."
2760 (save-match-data (markdown-inline-code-at-pos (or pos
(point)))))
2762 (defun markdown-code-block-at-pos (pos)
2763 "Return match data list if there is a code block at POS.
2764 Uses text properties at the beginning of the line position.
2765 This includes pre blocks, tilde-fenced code blocks, and GFM
2766 quoted code blocks. Return nil otherwise."
2767 (let ((bol (save-excursion (goto-char pos
) (line-beginning-position))))
2768 (or (get-text-property bol
'markdown-pre
)
2769 (let* ((bounds (markdown-get-enclosing-fenced-block-construct pos
))
2770 (second (cl-second bounds
)))
2772 ;; chunks are right open
2773 (when (< pos second
)
2777 ;; Function was renamed to emphasize that it does not modify match-data.
2778 (defalias 'markdown-code-block-at-point
'markdown-code-block-at-point-p
)
2780 (defun markdown-code-block-at-point-p (&optional pos
)
2781 "Return non-nil if there is a code block at the POS.
2782 This includes pre blocks, tilde-fenced code blocks, and GFM
2783 quoted code blocks. This function does not modify the match
2784 data. See `markdown-inline-code-at-point-p' for inline code."
2785 (save-match-data (markdown-code-block-at-pos (or pos
(point)))))
2787 (defun markdown-heading-at-point (&optional pos
)
2788 "Return non-nil if there is a heading at the POS.
2789 Set match data for `markdown-regex-header'."
2790 (let ((match-data (get-text-property (or pos
(point)) 'markdown-heading
)))
2792 (set-match-data match-data
)
2795 (defun markdown-pipe-at-bol-p ()
2796 "Return non-nil if the line begins with a pipe symbol.
2797 This may be useful for tables and Pandoc's line_blocks extension."
2798 (char-equal (char-after (line-beginning-position)) ?|
))
2801 ;;; Markdown Font Lock Matching Functions =====================================
2803 (defun markdown-range-property-any (begin end prop prop-values
)
2804 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
2805 Also returns t if PROP is a list containing one of the PROP-VALUES.
2806 Return nil otherwise."
2809 (dolist (loc (number-sequence begin end
))
2810 (when (setq props
(get-text-property loc prop
))
2811 (cond ((listp props
)
2812 ;; props is a list, check for membership
2813 (dolist (val prop-values
)
2814 (when (memq val props
) (throw 'found loc
))))
2816 ;; props is a scalar, check for equality
2817 (dolist (val prop-values
)
2818 (when (eq val props
) (throw 'found loc
))))))))))
2820 (defun markdown-range-properties-exist (begin end props
)
2822 for loc in
(number-sequence begin end
)
2826 (cl-some (lambda (prop) (get-text-property loc prop
)) props
)))
2827 finally return result
))
2829 (defun markdown-match-inline-generic (regex last
&optional faceless
)
2830 "Match inline REGEX from the point to LAST.
2831 When FACELESS is non-nil, do not return matches where faces have been applied."
2832 (when (re-search-forward regex last t
)
2833 (let ((bounds (markdown-code-block-at-pos (match-beginning 1)))
2834 (face (and faceless
(text-property-not-all
2835 (match-beginning 0) (match-end 0) 'face nil
))))
2837 ;; In code block: move past it and recursively search again
2839 (when (< (goto-char (cl-second bounds
)) last
)
2840 (markdown-match-inline-generic regex last faceless
)))
2841 ;; When faces are found in the match range, skip over the match and
2842 ;; recursively search again.
2844 (when (< (goto-char (match-end 0)) last
)
2845 (markdown-match-inline-generic regex last faceless
)))
2846 ;; Keep match data and return t when in bounds.
2848 (<= (match-end 0) last
))))))
2850 (defun markdown-match-code (last)
2851 "Match inline code fragments from point to LAST."
2854 (when (markdown-search-until-condition
2857 ;; Advance point in case of failure, but without exceeding last.
2858 (goto-char (min (1+ (match-beginning 1)) last
))
2859 (not (markdown-in-comment-p (match-beginning 1)))
2860 (not (markdown-in-comment-p (match-end 1)))
2861 (not (markdown-code-block-at-pos (match-beginning 1)))))
2862 markdown-regex-code last t
)
2863 (set-match-data (list (match-beginning 1) (match-end 1)
2864 (match-beginning 2) (match-end 2)
2865 (match-beginning 3) (match-end 3)
2866 (match-beginning 4) (match-end 4)))
2867 (goto-char (min (1+ (match-end 0)) last
(point-max)))
2870 (defun markdown--gfm-markup-underscore-p (begin end
)
2871 (let ((is-underscore (eql (char-after begin
) ?_
)))
2872 (if (not is-underscore
)
2877 (and (looking-back "\\(?:^\\|[[:blank:][:punct:]]\\)" (1- begin
))
2880 (looking-at-p "\\(?:[[:blank:][:punct:]]\\|$\\)"))))))))
2882 (defun markdown-match-bold (last)
2883 "Match inline bold from the point to LAST."
2884 (when (markdown-match-inline-generic markdown-regex-bold last
)
2885 (let ((is-gfm (derived-mode-p 'gfm-mode
))
2886 (begin (match-beginning 2))
2887 (end (match-end 2)))
2888 (if (or (markdown-inline-code-at-pos-p begin
)
2889 (markdown-inline-code-at-pos-p end
)
2890 (markdown-in-comment-p)
2891 (markdown-range-property-any
2892 begin begin
'face
'(markdown-url-face
2893 markdown-plain-url-face
))
2894 (markdown-range-property-any
2895 begin end
'face
'(markdown-hr-face
2896 markdown-math-face
))
2897 (and is-gfm
(not (markdown--gfm-markup-underscore-p begin end
))))
2898 (progn (goto-char (min (1+ begin
) last
))
2899 (when (< (point) last
)
2900 (markdown-match-bold last
)))
2901 (set-match-data (list (match-beginning 2) (match-end 2)
2902 (match-beginning 3) (match-end 3)
2903 (match-beginning 4) (match-end 4)
2904 (match-beginning 5) (match-end 5)))
2907 (defun markdown-match-italic (last)
2908 "Match inline italics from the point to LAST."
2909 (let* ((is-gfm (derived-mode-p 'gfm-mode
))
2911 markdown-regex-gfm-italic
2912 markdown-regex-italic
)))
2913 (when (and (markdown-match-inline-generic regex last
)
2914 (not (markdown--face-p
2916 '(markdown-html-attr-name-face markdown-html-attr-value-face
))))
2917 (let ((begin (match-beginning 1))
2919 (close-end (match-end 4)))
2920 (if (or (eql (char-before begin
) (char-after begin
))
2921 (markdown-inline-code-at-pos-p begin
)
2922 (markdown-inline-code-at-pos-p (1- end
))
2923 (markdown-in-comment-p)
2924 (markdown-range-property-any
2925 begin begin
'face
'(markdown-url-face
2926 markdown-plain-url-face
2927 markdown-markup-face
))
2928 (markdown-range-property-any
2929 begin end
'face
'(markdown-bold-face
2932 markdown-math-face
))
2934 (or (char-equal (char-after begin
) (char-after (1+ begin
))) ;; check bold case
2935 (not (markdown--gfm-markup-underscore-p begin close-end
)))))
2936 (progn (goto-char (min (1+ begin
) last
))
2937 (when (< (point) last
)
2938 (markdown-match-italic last
)))
2939 (set-match-data (list (match-beginning 1) (match-end 1)
2940 (match-beginning 2) (match-end 2)
2941 (match-beginning 3) (match-end 3)
2942 (match-beginning 4) (match-end 4)))
2945 (defun markdown--match-highlighting (last)
2946 (when markdown-enable-highlighting-syntax
2947 (re-search-forward markdown-regex-highlighting last t
)))
2949 (defun markdown-match-math-generic (regex last
)
2950 "Match REGEX from point to LAST.
2951 REGEX is either `markdown-regex-math-inline-single' for matching
2952 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
2953 (when (markdown-match-inline-generic regex last
)
2954 (let ((begin (match-beginning 1)) (end (match-end 1)))
2956 (if (or (markdown-range-property-any
2958 '(markdown-inline-code-face markdown-bold-face
))
2959 (markdown-range-properties-exist
2961 (markdown-get-fenced-block-middle-properties)))
2962 (markdown-match-math-generic regex last
)
2964 (goto-char (1+ (match-end 0)))))))
2966 (defun markdown-match-list-items (last)
2967 "Match list items from point to LAST."
2968 (let* ((first (point))
2970 (prop 'markdown-list-item
)
2971 (bounds (car (get-text-property pos prop
))))
2973 (and (or (null (setq bounds
(car (get-text-property pos prop
))))
2974 (< (cl-first bounds
) pos
))
2976 (setq pos
(next-single-property-change pos prop nil last
))
2979 (set-match-data (cl-seventh bounds
))
2980 ;; Step at least one character beyond point. Otherwise
2981 ;; `font-lock-fontify-keywords-region' infloops.
2982 (goto-char (min (1+ (max (line-end-position) first
))
2986 (defun markdown-match-math-single (last)
2987 "Match single quoted $..$ math from point to LAST."
2988 (when markdown-enable-math
2989 (when (and (char-equal (char-after) ?$
)
2991 (not (char-equal (char-before) ?
\\))
2992 (not (char-equal (char-before) ?$
)))
2994 (markdown-match-math-generic markdown-regex-math-inline-single last
)))
2996 (defun markdown-match-math-double (last)
2997 "Match double quoted $$..$$ math from point to LAST."
2998 (when markdown-enable-math
2999 (when (and (< (1+ (point)) (point-max))
3000 (char-equal (char-after) ?$
)
3001 (char-equal (char-after (1+ (point))) ?$
)
3003 (not (char-equal (char-before) ?
\\))
3004 (not (char-equal (char-before) ?$
)))
3006 (markdown-match-math-generic markdown-regex-math-inline-double last
)))
3008 (defun markdown-match-math-display (last)
3009 "Match bracketed display math \[..\] and \\[..\\] from point to LAST."
3010 (when markdown-enable-math
3011 (markdown-match-math-generic markdown-regex-math-display last
)))
3013 (defun markdown-match-propertized-text (property last
)
3014 "Match text with PROPERTY from point to LAST.
3015 Restore match data previously stored in PROPERTY."
3016 (let ((saved (get-text-property (point) property
))
3019 (setq pos
(next-single-property-change (point) property nil last
))
3020 (unless (= pos last
)
3021 (setq saved
(get-text-property pos property
))))
3023 (set-match-data saved
)
3024 ;; Step at least one character beyond point. Otherwise
3025 ;; `font-lock-fontify-keywords-region' infloops.
3026 (goto-char (min (1+ (max (match-end 0) (point)))
3030 (defun markdown-match-pre-blocks (last)
3031 "Match preformatted blocks from point to LAST.
3032 Use data stored in \\='markdown-pre text property during syntax
3034 (markdown-match-propertized-text 'markdown-pre last
))
3036 (defun markdown-match-gfm-code-blocks (last)
3037 "Match GFM quoted code blocks from point to LAST.
3038 Use data stored in \\='markdown-gfm-code text property during syntax
3040 (markdown-match-propertized-text 'markdown-gfm-code last
))
3042 (defun markdown-match-gfm-open-code-blocks (last)
3043 (markdown-match-propertized-text 'markdown-gfm-block-begin last
))
3045 (defun markdown-match-gfm-close-code-blocks (last)
3046 (markdown-match-propertized-text 'markdown-gfm-block-end last
))
3048 (defun markdown-match-fenced-code-blocks (last)
3049 "Match fenced code blocks from the point to LAST."
3050 (markdown-match-propertized-text 'markdown-fenced-code last
))
3052 (defun markdown-match-fenced-start-code-block (last)
3053 (markdown-match-propertized-text 'markdown-tilde-fence-begin last
))
3055 (defun markdown-match-fenced-end-code-block (last)
3056 (markdown-match-propertized-text 'markdown-tilde-fence-end last
))
3058 (defun markdown-match-blockquotes (last)
3059 "Match blockquotes from point to LAST.
3060 Use data stored in \\='markdown-blockquote text property during syntax
3062 (markdown-match-propertized-text 'markdown-blockquote last
))
3064 (defun markdown-match-hr (last)
3065 "Match horizontal rules comments from the point to LAST."
3066 (markdown-match-propertized-text 'markdown-hr last
))
3068 (defun markdown-match-comments (last)
3069 "Match HTML comments from the point to LAST."
3070 (when (and (skip-syntax-forward "^<" last
))
3071 (let ((beg (point)))
3072 (when (and (skip-syntax-forward "^>" last
) (< (point) last
))
3074 (set-match-data (list beg
(point)))
3077 (defun markdown-match-generic-links (last ref
)
3078 "Match inline links from point to LAST.
3079 When REF is non-nil, match reference links instead of standard
3081 This function should only be used during font-lock, as it
3082 determines syntax based on the presence of faces for previously
3083 processed elements."
3084 ;; Search for the next potential link (not in a code block).
3085 (let ((prohibited-faces '(markdown-pre-face
3087 markdown-inline-code-face
3088 markdown-comment-face
))
3091 (and (not found
) (< (point) last
)
3093 ;; Clear match data to test for a match after functions returns.
3094 (set-match-data nil
)
3095 ;; Preliminary regular expression search so we can return
3096 ;; quickly upon failure. This doesn't handle malformed links
3097 ;; or nested square brackets well, so if it passes we back up
3098 ;; continue with a more precise search.
3101 markdown-regex-link-reference
3102 markdown-regex-link-inline
)
3104 ;; Keep searching if this is in a code block, inline code, or a
3105 ;; comment, or if it is include syntax. The link text portion
3106 ;; (group 3) may contain inline code or comments, but the
3107 ;; markup, URL, and title should not be part of such elements.
3108 (if (or (markdown-range-property-any
3109 (match-beginning 0) (match-end 2) 'face prohibited-faces
)
3110 (markdown-range-property-any
3111 (match-beginning 4) (match-end 0) 'face prohibited-faces
)
3112 (and (char-equal (char-after (line-beginning-position)) ?
<)
3113 (char-equal (char-after (1+ (line-beginning-position))) ?
<)))
3114 (set-match-data nil
)
3116 ;; Match opening exclamation point (optional) and left bracket.
3117 (when (match-beginning 2)
3118 (let* ((bang (match-beginning 1))
3119 (first-begin (match-beginning 2))
3120 ;; Find end of block to prevent matching across blocks.
3121 (end-of-block (save-excursion
3123 (goto-char (match-beginning 2))
3124 (markdown-end-of-text-block)
3126 ;; Move over balanced expressions to closing right bracket.
3127 ;; Catch unbalanced expression errors and return nil.
3128 (first-end (condition-case nil
3129 (and (goto-char first-begin
)
3130 (scan-sexps (point) 1))
3132 ;; Continue with point at CONT-POINT upon failure.
3133 (cont-point (min (1+ first-begin
) last
))
3134 second-begin second-end url-begin url-end
3135 title-begin title-end
)
3136 ;; When bracket found, in range, and followed by a left paren/bracket...
3137 (when (and first-end
(< first-end end-of-block
) (goto-char first-end
)
3138 (char-equal (char-after (point)) (if ref ?\
[ ?\
()))
3139 ;; Scan across balanced expressions for closing parenthesis/bracket.
3140 (setq second-begin
(point)
3141 second-end
(condition-case nil
3142 (scan-sexps (point) 1)
3144 ;; Check that closing parenthesis/bracket is in range.
3145 (if (and second-end
(<= second-end end-of-block
) (<= second-end last
))
3147 ;; Search for (optional) title inside closing parenthesis
3148 (when (and (not ref
) (search-forward "\"" second-end t
))
3149 (setq title-begin
(1- (point))
3150 title-end
(and (goto-char second-end
)
3151 (search-backward "\"" (1+ title-begin
) t
))
3152 title-end
(and title-end
(1+ title-end
))))
3153 ;; Store URL/reference range
3154 (setq url-begin
(1+ second-begin
)
3155 url-end
(1- (or title-begin second-end
)))
3156 ;; Set match data, move point beyond link, and return
3158 (list (or bang first-begin
) second-end
; 0 - all
3159 bang
(and bang
(1+ bang
)) ; 1 - bang
3160 first-begin
(1+ first-begin
) ; 2 - markup
3161 (1+ first-begin
) (1- first-end
) ; 3 - link text
3162 (1- first-end
) first-end
; 4 - markup
3163 second-begin
(1+ second-begin
) ; 5 - markup
3164 url-begin url-end
; 6 - url/reference
3165 title-begin title-end
; 7 - title
3166 (1- second-end
) second-end
)) ; 8 - markup
3167 ;; Nullify cont-point and leave point at end and
3168 (setq cont-point nil
)
3169 (goto-char second-end
))
3170 ;; If no closing parenthesis in range, update continuation point
3171 (setq cont-point
(min end-of-block second-begin
))))
3173 ;; On failure, continue searching at cont-point
3174 ((and cont-point
(< cont-point last
))
3175 (goto-char cont-point
)
3176 (markdown-match-generic-links last ref
))
3177 ;; No more text, return nil
3178 ((and cont-point
(= cont-point last
))
3180 ;; Return t if a match occurred
3183 (defun markdown-match-angle-uris (last)
3184 "Match angle bracket URIs from point to LAST."
3185 (when (markdown-match-inline-generic markdown-regex-angle-uri last
)
3186 (goto-char (1+ (match-end 0)))))
3188 (defun markdown-match-plain-uris (last)
3189 "Match plain URIs from point to LAST."
3190 (when (markdown-match-inline-generic markdown-regex-uri last t
)
3191 (goto-char (1+ (match-end 0)))))
3193 (defvar markdown-conditional-search-function
#'re-search-forward
3194 "Conditional search function used in `markdown-search-until-condition'.
3195 Made into a variable to allow for dynamic let-binding.")
3197 (defun markdown-search-until-condition (condition &rest args
)
3199 (while (and (not ret
) (apply markdown-conditional-search-function args
))
3200 (setq ret
(funcall condition
)))
3203 (defun markdown-metadata-line-p (pos regexp
)
3205 (or (= (line-number-at-pos pos
) 1)
3208 ;; skip multi-line metadata
3209 (while (and (looking-at-p "^\\s-+[[:alpha:]]")
3210 (> (line-number-at-pos (point)) 1))
3212 (looking-at-p regexp
)))))
3214 (defun markdown-match-generic-metadata (regexp last
)
3215 "Match metadata declarations specified by REGEXP from point to LAST.
3216 These declarations must appear inside a metadata block that begins at
3217 the beginning of the buffer and ends with a blank line (or the end of
3219 (let* ((first (point))
3220 (end-re "\n[ \t]*\n\\|\n\\'\\|\\'")
3221 (block-begin (goto-char 1))
3222 (block-end (re-search-forward end-re nil t
)))
3223 (if (and block-end
(> first block-end
))
3224 ;; Don't match declarations if there is no metadata block or if
3225 ;; the point is beyond the block. Move point to point-max to
3226 ;; prevent additional searches and return return nil since nothing
3228 (progn (goto-char (point-max)) nil
)
3229 ;; If a block was found that begins before LAST and ends after
3230 ;; point, search for declarations inside it. If the starting is
3231 ;; before the beginning of the block, start there. Otherwise,
3232 ;; move back to FIRST.
3233 (goto-char (if (< first block-begin
) block-begin first
))
3234 (if (and (re-search-forward regexp
(min last block-end
) t
)
3235 (markdown-metadata-line-p (point) regexp
))
3236 ;; If a metadata declaration is found, set match-data and return t.
3237 (let ((key-beginning (match-beginning 1))
3238 (key-end (match-end 1))
3239 (markup-begin (match-beginning 2))
3240 (markup-end (match-end 2))
3241 (value-beginning (match-beginning 3)))
3242 (set-match-data (list key-beginning
(point) ; complete metadata
3243 key-beginning key-end
; key
3244 markup-begin markup-end
; markup
3245 value-beginning
(point))) ; value
3247 ;; Otherwise, move the point to last and return nil
3251 (defun markdown-match-declarative-metadata (last)
3252 "Match declarative metadata from the point to LAST."
3253 (markdown-match-generic-metadata markdown-regex-declarative-metadata last
))
3255 (defun markdown-match-pandoc-metadata (last)
3256 "Match Pandoc metadata from the point to LAST."
3257 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last
))
3259 (defun markdown-match-yaml-metadata-begin (last)
3260 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last
))
3262 (defun markdown-match-yaml-metadata-end (last)
3263 (markdown-match-propertized-text 'markdown-yaml-metadata-end last
))
3265 (defun markdown-match-yaml-metadata-key (last)
3266 (markdown-match-propertized-text 'markdown-metadata-key last
))
3268 (defun markdown-match-wiki-link (last)
3269 "Match wiki links from point to LAST."
3270 (when (and markdown-enable-wiki-links
3271 (not markdown-wiki-link-fontify-missing
)
3272 (markdown-match-inline-generic markdown-regex-wiki-link last
))
3273 (let ((begin (match-beginning 1)) (end (match-end 1)))
3274 (if (or (markdown-in-comment-p begin
)
3275 (markdown-in-comment-p end
)
3276 (markdown-inline-code-at-pos-p begin
)
3277 (markdown-inline-code-at-pos-p end
)
3278 (markdown-code-block-at-pos begin
))
3279 (progn (goto-char (min (1+ begin
) last
))
3280 (when (< (point) last
)
3281 (markdown-match-wiki-link last
)))
3282 (set-match-data (list begin end
))
3285 (defun markdown-match-inline-attributes (last)
3286 "Match inline attributes from point to LAST."
3287 ;; #428 re-search-forward markdown-regex-inline-attributes is very slow.
3288 ;; So use simple regex for re-search-forward and use markdown-regex-inline-attributes
3289 ;; against matched string.
3290 (when (markdown-match-inline-generic "[ \t]*\\({\\)\\([^\n]*\\)}[ \t]*$" last
)
3291 (if (not (string-match-p markdown-regex-inline-attributes
(match-string 0)))
3292 (markdown-match-inline-attributes last
)
3293 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
3294 (markdown-inline-code-at-pos-p (match-end 0))
3295 (markdown-in-comment-p))
3298 (defun markdown-match-leanpub-sections (last)
3299 "Match Leanpub section markers from point to LAST."
3300 (when (markdown-match-inline-generic markdown-regex-leanpub-sections last
)
3301 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
3302 (markdown-inline-code-at-pos-p (match-end 0))
3303 (markdown-in-comment-p))
3306 (defun markdown-match-includes (last)
3307 "Match include statements from point to LAST.
3308 Sets match data for the following seven groups:
3309 Group 1: opening two angle brackets
3310 Group 2: opening title delimiter (optional)
3311 Group 3: title text (optional)
3312 Group 4: closing title delimiter (optional)
3313 Group 5: opening filename delimiter
3315 Group 7: closing filename delimiter"
3316 (when (markdown-match-inline-generic markdown-regex-include last
)
3317 (let ((valid (not (or (markdown-in-comment-p (match-beginning 0))
3318 (markdown-in-comment-p (match-end 0))
3319 (markdown-code-block-at-pos (match-beginning 0))))))
3321 ;; Parentheses and maybe square brackets, but no curly braces:
3322 ;; match optional title in square brackets and file in parentheses.
3323 ((and valid
(match-beginning 5)
3324 (not (match-beginning 8)))
3325 (set-match-data (list (match-beginning 1) (match-end 7)
3326 (match-beginning 1) (match-end 1)
3327 (match-beginning 2) (match-end 2)
3328 (match-beginning 3) (match-end 3)
3329 (match-beginning 4) (match-end 4)
3330 (match-beginning 5) (match-end 5)
3331 (match-beginning 6) (match-end 6)
3332 (match-beginning 7) (match-end 7))))
3333 ;; Only square brackets present: match file in square brackets.
3334 ((and valid
(match-beginning 2)
3335 (not (match-beginning 5))
3336 (not (match-beginning 7)))
3337 (set-match-data (list (match-beginning 1) (match-end 4)
3338 (match-beginning 1) (match-end 1)
3342 (match-beginning 2) (match-end 2)
3343 (match-beginning 3) (match-end 3)
3344 (match-beginning 4) (match-end 4))))
3345 ;; Only curly braces present: match file in curly braces.
3346 ((and valid
(match-beginning 8)
3347 (not (match-beginning 2))
3348 (not (match-beginning 5)))
3349 (set-match-data (list (match-beginning 1) (match-end 10)
3350 (match-beginning 1) (match-end 1)
3354 (match-beginning 8) (match-end 8)
3355 (match-beginning 9) (match-end 9)
3356 (match-beginning 10) (match-end 10))))
3358 ;; Not a valid match, move to next line and search again.
3360 (when (< (point) last
)
3361 (setq valid
(markdown-match-includes last
)))))
3364 (defun markdown-match-html-tag (last)
3365 "Match HTML tags from point to LAST."
3366 (when (and markdown-enable-html
3367 (markdown-match-inline-generic markdown-regex-html-tag last t
))
3368 (set-match-data (list (match-beginning 0) (match-end 0)
3369 (match-beginning 1) (match-end 1)
3370 (match-beginning 2) (match-end 2)
3371 (match-beginning 9) (match-end 9)))
3375 ;;; Markdown Font Fontification Functions =====================================
3377 (defvar markdown--first-displayable-cache
(make-hash-table :test
#'equal
))
3379 (defun markdown--first-displayable (seq)
3380 "Return the first displayable character or string in SEQ.
3381 SEQ may be an atom or a sequence."
3382 (let ((c (gethash seq markdown--first-displayable-cache t
)))
3386 (let ((seq (if (listp seq
) seq
(list seq
))))
3387 (cond ((stringp (car seq
))
3390 (and (mapcar #'char-displayable-p
(string-to-list str
))))
3392 ((characterp (car seq
))
3393 (cl-find-if #'char-displayable-p seq
))))
3394 markdown--first-displayable-cache
))))
3396 (defun markdown--marginalize-string (level)
3397 "Generate atx markup string of given LEVEL for left margin."
3398 (let ((margin-left-space-count
3399 (- markdown-marginalize-headers-margin-width level
)))
3400 (concat (make-string margin-left-space-count ?
)
3401 (make-string level ?
#))))
3403 (defun markdown-marginalize-update-current ()
3404 "Update the window configuration to create a left margin."
3406 (let* ((header-delimiter-font-width
3407 (window-font-width nil
'markdown-header-delimiter-face
))
3408 (margin-pixel-width (* markdown-marginalize-headers-margin-width
3409 header-delimiter-font-width
))
3410 (margin-char-width (/ margin-pixel-width
(default-font-width))))
3411 (set-window-margins nil margin-char-width
))
3412 ;; As a fallback, simply set margin based on character count.
3413 (set-window-margins nil
(1+ markdown-marginalize-headers-margin-width
))))
3415 (defun markdown-fontify-headings (last)
3416 "Add text properties to headings from point to LAST."
3417 (when (markdown-match-propertized-text 'markdown-heading last
)
3418 (let* ((level (markdown-outline-level))
3420 (intern (format "markdown-header-face-%d" level
)))
3421 (heading-props `(face ,heading-face
))
3423 `(face markdown-header-delimiter-face
3425 (markdown-hide-markup
3427 (markdown-marginalize-headers
3428 `(display ((margin left-margin
)
3429 ,(markdown--marginalize-string level
)))))))
3431 `(face markdown-header-delimiter-face
3432 ,@(when markdown-hide-markup
`(display ""))))
3433 (rule-props `(face markdown-header-rule-face
3434 ,@(when markdown-hide-markup
`(display "")))))
3437 (progn (add-text-properties
3438 (match-beginning 1) (match-end 1) heading-props
)
3440 (add-text-properties
3441 (match-beginning 2) (match-end 2) rule-props
)
3442 (add-text-properties
3443 (match-beginning 3) (match-end 3) rule-props
)))
3445 (if markdown-fontify-whole-heading-line
3446 (let ((header-end (min (point-max) (1+ (match-end 0)))))
3447 (add-text-properties
3448 (match-beginning 0) header-end heading-props
))
3449 (add-text-properties
3450 (match-beginning 4) (match-end 4) left-markup-props
)
3451 (add-text-properties
3452 (match-beginning 5) (match-end 5) heading-props
)
3454 (add-text-properties
3455 (match-beginning 6) (match-end 6) right-markup-props
)))))
3458 (defun markdown-fontify-tables (last)
3459 (when (re-search-forward "|" last t
)
3460 (when (markdown-table-at-point-p)
3461 (font-lock-append-text-property
3462 (line-beginning-position) (min (1+ (line-end-position)) (point-max))
3463 'face
'markdown-table-face
))
3467 (defun markdown-fontify-blockquotes (last)
3468 "Apply font-lock properties to blockquotes from point to LAST."
3469 (when (markdown-match-blockquotes last
)
3470 (let ((display-string
3471 (markdown--first-displayable markdown-blockquote-display-char
)))
3472 (add-text-properties
3473 (match-beginning 1) (match-end 1)
3474 (if markdown-hide-markup
3475 `(face markdown-blockquote-face display
,display-string
)
3476 `(face markdown-markup-face
)))
3477 (font-lock-append-text-property
3478 (match-beginning 0) (match-end 0) 'face
'markdown-blockquote-face
)
3481 (defun markdown-fontify-list-items (last)
3482 "Apply font-lock properties to list markers from point to LAST."
3483 (when (markdown-match-list-items last
)
3484 (when (not (markdown-code-block-at-point-p (match-beginning 2)))
3485 (let* ((indent (length (match-string-no-properties 1)))
3486 (level (/ indent markdown-list-indent-width
)) ;; level = 0, 1, 2, ...
3487 (bullet (nth (mod level
(length markdown-list-item-bullets
))
3488 markdown-list-item-bullets
)))
3489 (add-text-properties
3490 (match-beginning 2) (match-end 2) '(face markdown-list-face
))
3491 (when markdown-hide-markup
3494 ((string-match-p "[\\*\\+-]" (match-string 2))
3495 (add-text-properties
3496 (match-beginning 2) (match-end 2) `(display ,bullet
)))
3498 ((string-equal ":" (match-string 2))
3499 (let ((display-string
3500 (char-to-string (markdown--first-displayable
3501 markdown-definition-display-char
))))
3502 (add-text-properties (match-beginning 2) (match-end 2)
3503 `(display ,display-string
))))))))
3506 (defun markdown-fontify-hrs (last)
3507 "Add text properties to horizontal rules from point to LAST."
3508 (when (markdown-match-hr last
)
3509 (let ((hr-char (markdown--first-displayable markdown-hr-display-char
)))
3510 (add-text-properties
3511 (match-beginning 0) (match-end 0)
3512 `(face markdown-hr-face
3513 font-lock-multiline t
3514 ,@(when (and markdown-hide-markup hr-char
)
3515 `(display ,(make-string
3516 (1- (window-body-width)) hr-char
)))))
3519 (defun markdown-fontify-sub-superscripts (last)
3520 "Apply text properties to sub- and superscripts from point to LAST."
3521 (when (markdown-search-until-condition
3522 (lambda () (and (not (markdown-code-block-at-point-p))
3523 (not (markdown-inline-code-at-point-p))
3524 (not (markdown-in-comment-p))))
3525 markdown-regex-sub-superscript last t
)
3526 (let* ((subscript-p (string= (match-string 2) "~"))
3529 (car markdown-sub-superscript-display
)
3530 (cdr markdown-sub-superscript-display
)))
3531 (mp (list 'face
'markdown-markup-face
3532 'invisible
'markdown-markup
)))
3533 (when markdown-hide-markup
3534 (put-text-property (match-beginning 3) (match-end 3)
3536 (add-text-properties (match-beginning 2) (match-end 2) mp
)
3537 (add-text-properties (match-beginning 4) (match-end 4) mp
)
3541 ;;; Syntax Table ==============================================================
3543 (defvar markdown-mode-syntax-table
3544 (let ((tab (make-syntax-table text-mode-syntax-table
)))
3545 (modify-syntax-entry ?
\" "." tab
)
3547 "Syntax table for `markdown-mode'.")
3550 ;;; Element Insertion =========================================================
3552 (defun markdown-ensure-blank-line-before ()
3553 "If previous line is not already blank, insert a blank line before point."
3554 (unless (bolp) (insert "\n"))
3555 (unless (or (bobp) (looking-back "\n\\s-*\n" nil
)) (insert "\n")))
3557 (defun markdown-ensure-blank-line-after ()
3558 "If following line is not already blank, insert a blank line after point.
3559 Return the point where it was originally."
3561 (unless (eolp) (insert "\n"))
3562 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
3564 (defun markdown-wrap-or-insert (s1 s2
&optional thing beg end
)
3565 "Insert the strings S1 and S2, wrapping around region or THING.
3566 If a region is specified by the optional BEG and END arguments,
3567 wrap the strings S1 and S2 around that region.
3568 If there is an active region, wrap the strings S1 and S2 around
3569 the region. If there is not an active region but the point is at
3570 THING, wrap that thing (which defaults to word). Otherwise, just
3571 insert S1 and S2 and place the point in between. Return the
3572 bounds of the entire wrapped string, or nil if nothing was wrapped
3573 and S1 and S2 were only inserted."
3574 (let (a b bounds new-point
)
3580 new-point
(+ (point) (length s1
))))
3583 (setq a
(region-beginning)
3585 new-point
(+ (point) (length s1
))))
3586 ;; Thing (word) at point
3587 ((setq bounds
(markdown-bounds-of-thing-at-point (or thing
'word
)))
3588 (setq a
(car bounds
)
3590 new-point
(+ (point) (length s1
))))
3591 ;; No active region and no word
3599 (when new-point
(goto-char new-point
))
3602 (setq b
(+ b
(length s1
) (length s2
)))
3605 (defun markdown-point-after-unwrap (cur prefix suffix
)
3606 "Return desired position of point after an unwrapping operation.
3607 CUR gives the position of the point before the operation.
3608 Additionally, two cons cells must be provided. PREFIX gives the
3609 bounds of the prefix string and SUFFIX gives the bounds of the
3611 (cond ((< cur
(cdr prefix
)) (car prefix
))
3612 ((< cur
(car suffix
)) (- cur
(- (cdr prefix
) (car prefix
))))
3613 ((<= cur
(cdr suffix
))
3614 (- cur
(+ (- (cdr prefix
) (car prefix
))
3615 (- cur
(car suffix
)))))
3618 (defun markdown-unwrap-thing-at-point (regexp all text
)
3619 "Remove prefix and suffix of thing at point and reposition the point.
3620 When the thing at point matches REGEXP, replace the subexpression
3621 ALL with the string in subexpression TEXT. Reposition the point
3622 in an appropriate location accounting for the removal of prefix
3623 and suffix strings. Return new bounds of string from group TEXT.
3624 When REGEXP is nil, assumes match data is already set."
3625 (when (or (null regexp
)
3626 (thing-at-point-looking-at regexp
))
3628 (prefix (cons (match-beginning all
) (match-beginning text
)))
3629 (suffix (cons (match-end text
) (match-end all
)))
3630 (bounds (cons (match-beginning text
) (match-end text
))))
3631 ;; Replace the thing at point
3632 (replace-match (match-string text
) t t nil all
)
3633 ;; Reposition the point
3634 (goto-char (markdown-point-after-unwrap cur prefix suffix
))
3636 (setq bounds
(cons (car prefix
)
3637 (- (cdr bounds
) (- (cdr prefix
) (car prefix
))))))))
3639 (defun markdown-unwrap-things-in-region (beg end regexp all text
)
3640 "Remove prefix and suffix of all things in region from BEG to END.
3641 When a thing in the region matches REGEXP, replace the
3642 subexpression ALL with the string in subexpression TEXT.
3643 Return a cons cell containing updated bounds for the region."
3646 (let ((removed 0) len-all len-text
)
3647 (while (re-search-forward regexp
(- end removed
) t
)
3648 (setq len-all
(length (match-string-no-properties all
)))
3649 (setq len-text
(length (match-string-no-properties text
)))
3650 (setq removed
(+ removed
(- len-all len-text
)))
3651 (replace-match (match-string text
) t t nil all
))
3652 (cons beg
(- end removed
)))))
3654 (defun markdown-insert-hr (arg)
3655 "Insert or replace a horizontal rule.
3656 By default, use the first element of `markdown-hr-strings'. When
3657 ARG is non-nil, as when given a prefix, select a different
3658 element as follows. When prefixed with \\[universal-argument],
3659 use the last element of `markdown-hr-strings' instead. When
3660 prefixed with an integer from 1 to the length of
3661 `markdown-hr-strings', use the element in that position instead."
3663 (when (thing-at-point-looking-at markdown-regex-hr
)
3664 (delete-region (match-beginning 0) (match-end 0)))
3665 (markdown-ensure-blank-line-before)
3666 (cond ((equal arg
'(4))
3667 (insert (car (reverse markdown-hr-strings
))))
3668 ((and (integerp arg
) (> arg
0)
3669 (<= arg
(length markdown-hr-strings
)))
3670 (insert (nth (1- arg
) markdown-hr-strings
)))
3672 (insert (car markdown-hr-strings
))))
3673 (markdown-ensure-blank-line-after))
3675 (defun markdown--insert-common (start-delim end-delim regex start-group end-group face
3676 &optional skip-space
)
3679 (let* ((bounds (markdown-unwrap-things-in-region
3680 (region-beginning) (region-end)
3681 regex start-group end-group
))
3684 (when (and beg skip-space
)
3687 (skip-chars-forward "[ \t]")
3688 (setq beg
(point))))
3689 (when (and end skip-space
)
3692 (skip-chars-backward "[ \t]")
3693 (setq end
(point))))
3694 (markdown-wrap-or-insert start-delim end-delim nil beg end
))
3695 (if (markdown--face-p (point) (list face
))
3697 (while (and (markdown--face-p (point) (list face
)) (not (bobp)))
3699 (forward-char (- (1- (length start-delim
)))) ;; for delimiter
3702 (when (looking-at regex
)
3703 (markdown-unwrap-thing-at-point nil start-group end-group
)))
3704 (if (thing-at-point-looking-at regex
)
3705 (markdown-unwrap-thing-at-point nil start-group end-group
)
3706 (markdown-wrap-or-insert start-delim end-delim
'word nil nil
)))))
3708 (defun markdown-insert-bold ()
3709 "Insert markup to make a region or word bold.
3710 If there is an active region, make the region bold. If the point
3711 is at a non-bold word, make the word bold. If the point is at a
3712 bold word or phrase, remove the bold markup. Otherwise, simply
3713 insert bold delimiters and place the point in between them."
3715 (let ((delim (if markdown-bold-underscore
"__" "**")))
3716 (markdown--insert-common delim delim markdown-regex-bold
2 4 'markdown-bold-face t
)))
3718 (defun markdown-insert-italic ()
3719 "Insert markup to make a region or word italic.
3720 If there is an active region, make the region italic. If the point
3721 is at a non-italic word, make the word italic. If the point is at an
3722 italic word or phrase, remove the italic markup. Otherwise, simply
3723 insert italic delimiters and place the point in between them."
3725 (let ((delim (if markdown-italic-underscore
"_" "*")))
3726 (markdown--insert-common delim delim markdown-regex-italic
1 3 'markdown-italic-face t
)))
3728 (defun markdown-insert-strike-through ()
3729 "Insert markup to make a region or word strikethrough.
3730 If there is an active region, make the region strikethrough. If the point
3731 is at a non-bold word, make the word strikethrough. If the point is at a
3732 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
3733 simply insert bold delimiters and place the point in between them."
3735 (markdown--insert-common
3736 "~~" "~~" markdown-regex-strike-through
2 4 'markdown-strike-through-face t
))
3738 (defun markdown-insert-code ()
3739 "Insert markup to make a region or word an inline code fragment.
3740 If there is an active region, make the region an inline code
3741 fragment. If the point is at a word, make the word an inline
3742 code fragment. Otherwise, simply insert code delimiters and
3743 place the point in between them."
3747 (let ((bounds (markdown-unwrap-things-in-region
3748 (region-beginning) (region-end)
3749 markdown-regex-code
1 3)))
3750 (markdown-wrap-or-insert "`" "`" nil
(car bounds
) (cdr bounds
)))
3751 ;; Code markup removal, code markup for word, or empty markup insertion
3752 (if (markdown-inline-code-at-point)
3753 (markdown-unwrap-thing-at-point nil
0 2)
3754 (markdown-wrap-or-insert "`" "`" 'word nil nil
))))
3756 (defun markdown-insert-kbd ()
3757 "Insert markup to wrap region or word in <kbd> tags.
3758 If there is an active region, use the region. If the point is at
3759 a word, use the word. Otherwise, simply insert <kbd> tags and
3760 place the point in between them."
3764 (let ((bounds (markdown-unwrap-things-in-region
3765 (region-beginning) (region-end)
3766 markdown-regex-kbd
0 2)))
3767 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil
(car bounds
) (cdr bounds
)))
3768 ;; Markup removal, markup for word, or empty markup insertion
3769 (if (thing-at-point-looking-at markdown-regex-kbd
)
3770 (markdown-unwrap-thing-at-point nil
0 2)
3771 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil
))))
3773 (defun markdown-insert-inline-link (text url
&optional title
)
3774 "Insert an inline link with TEXT pointing to URL.
3775 Optionally, the user can provide a TITLE."
3776 (let ((cur (point)))
3777 (setq title
(and title
(concat " \"" title
"\"")))
3778 (insert (concat "[" text
"](" url title
")"))
3779 (cond ((not text
) (goto-char (+ 1 cur
)))
3780 ((not url
) (goto-char (+ 3 (length text
) cur
))))))
3782 (defun markdown-insert-inline-image (text url
&optional title
)
3783 "Insert an inline link with alt TEXT pointing to URL.
3784 Optionally, also provide a TITLE."
3785 (let ((cur (point)))
3786 (setq title
(and title
(concat " \"" title
"\"")))
3787 (insert (concat "![" text
"](" url title
")"))
3788 (cond ((not text
) (goto-char (+ 2 cur
)))
3789 ((not url
) (goto-char (+ 4 (length text
) cur
))))))
3791 (defun markdown-insert-reference-link (text label
&optional url title
)
3792 "Insert a reference link and, optionally, a reference definition.
3793 The link TEXT will be inserted followed by the optional LABEL.
3794 If a URL is given, also insert a definition for the reference
3795 LABEL according to `markdown-reference-location'. If a TITLE is
3796 given, it will be added to the end of the reference definition
3797 and will be used to populate the title attribute when converted
3798 to XHTML. If URL is nil, insert only the link portion (for
3799 example, when a reference label is already defined)."
3800 (insert (concat "[" text
"][" label
"]"))
3802 (markdown-insert-reference-definition
3803 (if (string-equal label
"") text label
)
3806 (defun markdown-insert-reference-image (text label
&optional url title
)
3807 "Insert a reference image and, optionally, a reference definition.
3808 The alt TEXT will be inserted followed by the optional LABEL.
3809 If a URL is given, also insert a definition for the reference
3810 LABEL according to `markdown-reference-location'. If a TITLE is
3811 given, it will be added to the end of the reference definition
3812 and will be used to populate the title attribute when converted
3813 to XHTML. If URL is nil, insert only the link portion (for
3814 example, when a reference label is already defined)."
3815 (insert (concat "![" text
"][" label
"]"))
3817 (markdown-insert-reference-definition
3818 (if (string-equal label
"") text label
)
3821 (defun markdown-insert-reference-definition (label &optional url title
)
3822 "Add definition for reference LABEL with URL and TITLE.
3823 LABEL is a Markdown reference label without square brackets.
3824 URL and TITLE are optional. When given, the TITLE will
3825 be used to populate the title attribute when converted to XHTML."
3826 ;; END specifies where to leave the point upon return
3827 (let ((end (point)))
3828 (cl-case markdown-reference-location
3829 (end (goto-char (point-max)))
3830 (immediately (markdown-end-of-text-block))
3831 (subtree (markdown-end-of-subtree))
3832 (header (markdown-end-of-defun)))
3833 ;; Skip backwards over local variables. This logic is similar to the one
3834 ;; used in ‘hack-local-variables’.
3835 (when (and enable-local-variables
(eobp))
3836 (search-backward "\n\f" (max (- (point) 3000) (point-min)) :move
)
3837 (when (let ((case-fold-search t
))
3838 (search-forward "Local Variables:" nil
:move
))
3839 (beginning-of-line 0)
3840 (when (eq (char-before) ?
\n) (backward-char))))
3841 (unless (or (markdown-cur-line-blank-p)
3842 (thing-at-point-looking-at markdown-regex-reference-definition
))
3844 (insert "\n[" label
"]: ")
3847 ;; When no URL is given, leave point at END following the colon
3849 (when (> (length title
) 0)
3850 (insert " \"" title
"\""))
3851 (unless (looking-at-p "\n")
3856 (markdown--substitute-command-keys
3857 "Reference [%s] was defined, press \\[markdown-do] to jump there")
3860 (defcustom markdown-link-make-text-function nil
3861 "Function that automatically generates a link text for a URL.
3863 If non-nil, this function will be called by
3864 `markdown--insert-link-or-image' and the result will be the
3865 default link text. The function should receive exactly one
3866 argument that corresponds to the link URL."
3869 :package-version
'(markdown-mode .
"2.5"))
3871 (defcustom markdown-disable-tooltip-prompt nil
3872 "Disable prompt for tooltip when inserting a link or image.
3874 If non-nil, `markdown-insert-link' and `markdown-insert-link'
3875 will not prompt the user to insert a tooltip text for the given
3880 :package-version
'(markdown-mode .
"2.5"))
3882 (defun markdown--insert-link-or-image (image)
3883 "Interactively insert new or update an existing link or image.
3884 When IMAGE is non-nil, insert an image. Otherwise, insert a link.
3885 This is an internal function called by
3886 `markdown-insert-link' and `markdown-insert-image'."
3887 (cl-multiple-value-bind (begin end text uri ref title
)
3889 ;; Use region as either link text or URL as appropriate.
3890 (let ((region (buffer-substring-no-properties
3891 (region-beginning) (region-end))))
3892 (if (string-match markdown-regex-uri region
)
3893 ;; Region contains a URL; use it as such.
3894 (list (region-beginning) (region-end)
3895 nil
(match-string 0 region
) nil nil
)
3896 ;; Region doesn't contain a URL, so use it as text.
3897 (list (region-beginning) (region-end)
3898 region nil nil nil
)))
3899 ;; Extract and use properties of existing link, if any.
3900 (markdown-link-at-pos (point)))
3901 (let* ((ref (when ref
(concat "[" ref
"]")))
3902 (defined-refs (mapcar #'car
(markdown-get-defined-references)))
3903 (defined-ref-cands (mapcar (lambda (ref) (concat "[" ref
"]")) defined-refs
))
3904 (used-uris (markdown-get-used-uris))
3905 (uri-or-ref (completing-read
3906 "URL or [reference]: "
3907 (append defined-ref-cands used-uris
)
3908 nil nil
(or uri ref
)))
3909 (ref (cond ((string-match "\\`\\[\\(.*\\)\\]\\'" uri-or-ref
)
3910 (match-string 1 uri-or-ref
))
3911 ((string-equal "" uri-or-ref
)
3913 (uri (unless ref uri-or-ref
))
3914 (text-prompt (if image
3918 "Link text (blank for plain URL): ")))
3919 (text (or text
(and markdown-link-make-text-function uri
3920 (funcall markdown-link-make-text-function uri
))))
3921 (text (completing-read text-prompt defined-refs nil nil text
))
3922 (text (if (= (length text
) 0) nil text
))
3923 (plainp (and uri
(not text
)))
3924 (implicitp (string-equal ref
""))
3925 (ref (if implicitp text ref
))
3926 (definedp (and ref
(markdown-reference-definition ref
)))
3927 (ref-url (unless (or uri definedp
)
3928 (completing-read "Reference URL: " used-uris
)))
3929 (title (unless (or plainp definedp markdown-disable-tooltip-prompt
)
3930 (read-string "Title (tooltip text, optional): " title
)))
3931 (title (if (= (length title
) 0) nil title
)))
3932 (when (and image implicitp
)
3933 (user-error "Reference required: implicit image references are invalid"))
3934 (when (and begin end
)
3935 (delete-region begin end
))
3937 ((and (not image
) uri text
)
3938 (markdown-insert-inline-link text uri title
))
3939 ((and image uri text
)
3940 (markdown-insert-inline-image text uri title
))
3943 (markdown-insert-reference-image text
(unless implicitp ref
) nil title
)
3944 (markdown-insert-reference-link text
(unless implicitp ref
) nil title
))
3946 (markdown-insert-reference-definition ref ref-url title
)))
3947 ((and (not image
) uri
)
3948 (markdown-insert-uri uri
))))))
3950 (defun markdown-insert-link ()
3951 "Insert new or update an existing link, with interactive prompt.
3952 If the point is at an existing link or URL, update the link text,
3953 URL, reference label, and/or title. Otherwise, insert a new link.
3954 The type of link inserted (inline, reference, or plain URL)
3955 depends on which values are provided:
3957 * If a URL and TEXT are given, insert an inline link: [TEXT](URL).
3958 * If [REF] and TEXT are given, insert a reference link: [TEXT][REF].
3959 * If only TEXT is given, insert an implicit reference link: [TEXT][].
3960 * If only a URL is given, insert a plain link: <URL>.
3962 In other words, to create an implicit reference link, leave the
3963 URL prompt empty and to create a plain URL link, leave the link
3966 If there is an active region, use the text as the default URL, if
3967 it seems to be a URL, or link text value otherwise.
3969 If a given reference is not defined, this function will
3970 additionally prompt for the URL and optional title. In this case,
3971 the reference definition is placed at the location determined by
3972 `markdown-reference-location'. In addition, it is possible to
3973 have the `markdown-link-make-text-function' function, if non-nil,
3974 define the default link text before prompting the user for it.
3976 If `markdown-disable-tooltip-prompt' is non-nil, the user will
3977 not be prompted to add or modify a tooltip text.
3979 Through updating the link, this function can be used to convert a
3980 link of one type (inline, reference, or plain) to another type by
3981 selectively adding or removing information via the prompts."
3983 (markdown--insert-link-or-image nil
))
3985 (defun markdown-insert-image ()
3986 "Insert new or update an existing image, with interactive prompt.
3987 If the point is at an existing image, update the alt text, URL,
3988 reference label, and/or title. Otherwise, insert a new image.
3989 The type of image inserted (inline or reference) depends on which
3990 values are provided:
3992 * If a URL and ALT-TEXT are given, insert an inline image:
3994 * If [REF] and ALT-TEXT are given, insert a reference image:
3997 If there is an active region, use the text as the default URL, if
3998 it seems to be a URL, or alt text value otherwise.
4000 If a given reference is not defined, this function will
4001 additionally prompt for the URL and optional title. In this case,
4002 the reference definition is placed at the location determined by
4003 `markdown-reference-location'.
4005 Through updating the image, this function can be used to convert an
4006 image of one type (inline or reference) to another type by
4007 selectively adding or removing information via the prompts."
4009 (markdown--insert-link-or-image t
))
4011 (defun markdown-insert-uri (&optional uri
)
4012 "Insert markup for an inline URI.
4013 If there is an active region, use it as the URI. If the point is
4014 at a URI, wrap it with angle brackets. If the point is at an
4015 inline URI, remove the angle brackets. Otherwise, simply insert
4016 angle brackets place the point between them."
4020 (let ((bounds (markdown-unwrap-things-in-region
4021 (region-beginning) (region-end)
4022 markdown-regex-angle-uri
0 2)))
4023 (markdown-wrap-or-insert "<" ">" nil
(car bounds
) (cdr bounds
)))
4024 ;; Markup removal, URI at point, new URI, or empty markup insertion
4025 (if (thing-at-point-looking-at markdown-regex-angle-uri
)
4026 (markdown-unwrap-thing-at-point nil
0 2)
4028 (insert "<" uri
">")
4029 (markdown-wrap-or-insert "<" ">" 'url nil nil
)))))
4031 (defun markdown-insert-wiki-link ()
4032 "Insert a wiki link of the form [[WikiLink]].
4033 If there is an active region, use the region as the link text.
4034 If the point is at a word, use the word as the link text. If
4035 there is no active region and the point is not at word, simply
4036 insert link markup."
4040 (markdown-wrap-or-insert "[[" "]]" nil
(region-beginning) (region-end))
4041 ;; Markup removal, wiki link at at point, or empty markup insertion
4042 (if (thing-at-point-looking-at markdown-regex-wiki-link
)
4043 (if (or markdown-wiki-link-alias-first
4044 (null (match-string 5)))
4045 (markdown-unwrap-thing-at-point nil
1 3)
4046 (markdown-unwrap-thing-at-point nil
1 5))
4047 (markdown-wrap-or-insert "[[" "]]"))))
4049 (defun markdown-remove-header ()
4050 "Remove header markup if point is at a header.
4051 Return bounds of remaining header text if a header was removed
4054 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx
0 2)
4055 (markdown-unwrap-thing-at-point markdown-regex-header-setext
0 1)))
4057 (defun markdown-insert-header (&optional level text setext
)
4058 "Insert or replace header markup.
4059 The level of the header is specified by LEVEL and header text is
4060 given by TEXT. LEVEL must be an integer from 1 and 6, and the
4062 When TEXT is nil, the header text is obtained as follows.
4063 If there is an active region, it is used as the header text.
4064 Otherwise, the current line will be used as the header text.
4065 If there is not an active region and the point is at a header,
4066 remove the header markup and replace with level N header.
4067 Otherwise, insert empty header markup and place the point in
4069 The style of the header will be atx (hash marks) unless
4070 SETEXT is non-nil, in which case a setext-style (underlined)
4071 header will be inserted."
4072 (interactive "p\nsHeader text: ")
4073 (setq level
(min (max (or level
1) 1) (if setext
2 6)))
4074 ;; Determine header text if not given
4078 (setq text
(delete-and-extract-region (region-beginning) (region-end)))
4080 (markdown-remove-header)
4081 (setq text
(delete-and-extract-region
4082 (line-beginning-position) (line-end-position)))
4083 (when (and setext
(string-match-p "^[ \t]*$" text
))
4084 (setq text
(read-string "Header text: "))))
4085 (setq text
(markdown-compress-whitespace-string text
)))
4086 ;; Insertion with given text
4087 (markdown-ensure-blank-line-before)
4090 (setq hdr
(make-string (string-width text
) (if (= level
2) ?- ?
=)))
4091 (insert text
"\n" hdr
))
4093 (setq hdr
(make-string level ?
#))
4094 (insert hdr
" " text
)
4095 (when (null markdown-asymmetric-header
) (insert " " hdr
)))))
4096 (markdown-ensure-blank-line-after)
4097 ;; Leave point at end of text
4099 (backward-char (1+ (string-width text
))))
4100 ((null markdown-asymmetric-header
)
4101 (backward-char (1+ level
)))))
4103 (defun markdown-insert-header-dwim (&optional arg setext
)
4104 "Insert or replace header markup.
4105 The level and type of the header are determined automatically by
4106 the type and level of the previous header, unless a prefix
4107 argument is given via ARG.
4108 With a numeric prefix valued 1 to 6, insert a header of the given
4109 level, with the type being determined automatically (note that
4110 only level 1 or 2 setext headers are possible).
4112 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
4113 promote the heading by one level.
4114 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
4115 demote the heading by one level.
4116 When SETEXT is non-nil, prefer setext-style headers when
4117 possible (levels one and two).
4119 When there is an active region, use it for the header text. When
4120 the point is at an existing header, change the type and level
4121 according to the rules above.
4122 Otherwise, if the line is not empty, create a header using the
4123 text on the current line as the header text.
4124 Finally, if the point is on a blank line, insert empty header
4125 markup (atx) or prompt for text (setext).
4126 See `markdown-insert-header' for more details about how the
4127 header text is determined."
4131 (when (or (thing-at-point-looking-at markdown-regex-header
)
4132 (re-search-backward markdown-regex-header nil t
))
4133 ;; level of current or previous header
4134 (setq level
(markdown-outline-level))
4135 ;; match group 1 indicates a setext header
4136 (setq setext
(match-end 1))))
4137 ;; check prefix argument
4139 ((and (equal arg
'(4)) level
(> level
1)) ;; C-u
4141 ((and (equal arg
'(16)) level
(< level
6)) ;; C-u C-u
4143 (arg ;; numeric prefix
4144 (setq level
(prefix-numeric-value arg
))))
4145 ;; setext headers must be level one or two
4146 (and level
(setq setext
(and setext
(<= level
2))))
4147 ;; insert the heading
4148 (markdown-insert-header level nil setext
)))
4150 (defun markdown-insert-header-setext-dwim (&optional arg
)
4151 "Insert or replace header markup, with preference for setext.
4152 See `markdown-insert-header-dwim' for details, including how ARG is handled."
4154 (markdown-insert-header-dwim arg t
))
4156 (defun markdown-insert-header-atx-1 ()
4157 "Insert a first level atx-style (hash mark) header.
4158 See `markdown-insert-header'."
4160 (markdown-insert-header 1 nil nil
))
4162 (defun markdown-insert-header-atx-2 ()
4163 "Insert a level two atx-style (hash mark) header.
4164 See `markdown-insert-header'."
4166 (markdown-insert-header 2 nil nil
))
4168 (defun markdown-insert-header-atx-3 ()
4169 "Insert a level three atx-style (hash mark) header.
4170 See `markdown-insert-header'."
4172 (markdown-insert-header 3 nil nil
))
4174 (defun markdown-insert-header-atx-4 ()
4175 "Insert a level four atx-style (hash mark) header.
4176 See `markdown-insert-header'."
4178 (markdown-insert-header 4 nil nil
))
4180 (defun markdown-insert-header-atx-5 ()
4181 "Insert a level five atx-style (hash mark) header.
4182 See `markdown-insert-header'."
4184 (markdown-insert-header 5 nil nil
))
4186 (defun markdown-insert-header-atx-6 ()
4187 "Insert a sixth level atx-style (hash mark) header.
4188 See `markdown-insert-header'."
4190 (markdown-insert-header 6 nil nil
))
4192 (defun markdown-insert-header-setext-1 ()
4193 "Insert a setext-style (underlined) first-level header.
4194 See `markdown-insert-header'."
4196 (markdown-insert-header 1 nil t
))
4198 (defun markdown-insert-header-setext-2 ()
4199 "Insert a setext-style (underlined) second-level header.
4200 See `markdown-insert-header'."
4202 (markdown-insert-header 2 nil t
))
4204 (defun markdown-blockquote-indentation (loc)
4205 "Return string containing necessary indentation for a blockquote at LOC.
4206 Also see `markdown-pre-indentation'."
4209 (let* ((list-level (length (markdown-calculate-list-levels)))
4211 (dotimes (_ list-level indent
)
4212 (setq indent
(concat indent
" "))))))
4214 (defun markdown-insert-blockquote ()
4215 "Start a blockquote section (or blockquote the region).
4216 If Transient Mark mode is on and a region is active, it is used as
4217 the blockquote text."
4220 (markdown-blockquote-region (region-beginning) (region-end))
4221 (markdown-ensure-blank-line-before)
4222 (insert (markdown-blockquote-indentation (point)) "> ")
4223 (markdown-ensure-blank-line-after)))
4225 (defun markdown-block-region (beg end prefix
)
4226 "Format the region using a block prefix.
4227 Arguments BEG and END specify the beginning and end of the
4228 region. The characters PREFIX will appear at the beginning
4231 (let* ((end-marker (make-marker))
4232 (beg-marker (make-marker))
4233 (prefix-without-trailing-whitespace
4234 (replace-regexp-in-string (rx (+ blank
) eos
) "" prefix
)))
4235 ;; Ensure blank line after and remove extra whitespace
4237 (skip-syntax-backward "-")
4238 (set-marker end-marker
(point))
4239 (delete-horizontal-space)
4240 (markdown-ensure-blank-line-after)
4241 ;; Ensure blank line before and remove extra whitespace
4243 (skip-syntax-forward "-")
4244 (delete-horizontal-space)
4245 (markdown-ensure-blank-line-before)
4246 (set-marker beg-marker
(point))
4247 ;; Insert PREFIX before each line
4248 (goto-char beg-marker
)
4249 (while (and (< (line-beginning-position) end-marker
)
4251 ;; Don’t insert trailing whitespace.
4252 (insert (if (eolp) prefix-without-trailing-whitespace prefix
))
4255 (defun markdown-blockquote-region (beg end
)
4256 "Blockquote the region.
4257 Arguments BEG and END specify the beginning and end of the region."
4259 (markdown-block-region
4260 beg end
(concat (markdown-blockquote-indentation
4261 (max (point-min) (1- beg
))) "> ")))
4263 (defun markdown-pre-indentation (loc)
4264 "Return string containing necessary whitespace for a pre block at LOC.
4265 Also see `markdown-blockquote-indentation'."
4268 (let* ((list-level (length (markdown-calculate-list-levels)))
4270 (dotimes (_ (1+ list-level
) indent
)
4271 (setq indent
(concat indent
" "))))))
4273 (defun markdown-insert-pre ()
4274 "Start a preformatted section (or apply to the region).
4275 If Transient Mark mode is on and a region is active, it is marked
4276 as preformatted text."
4279 (markdown-pre-region (region-beginning) (region-end))
4280 (markdown-ensure-blank-line-before)
4281 (insert (markdown-pre-indentation (point)))
4282 (markdown-ensure-blank-line-after)))
4284 (defun markdown-pre-region (beg end
)
4285 "Format the region as preformatted text.
4286 Arguments BEG and END specify the beginning and end of the region."
4288 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg
)))))
4289 (markdown-block-region beg end indent
)))
4291 (defun markdown-electric-backquote (arg)
4292 "Insert a backquote.
4293 The numeric prefix argument ARG says how many times to repeat the insertion.
4294 Call `markdown-insert-gfm-code-block' interactively
4295 if three backquotes inserted at the beginning of line."
4297 (self-insert-command (prefix-numeric-value arg
))
4298 (when (and markdown-gfm-use-electric-backquote
(looking-back "^```" nil
))
4300 (call-interactively #'markdown-insert-gfm-code-block
)))
4302 (defconst markdown-gfm-recognized-languages
4303 ;; To reproduce/update, evaluate the let-form in
4304 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
4305 ;; but with appropriate use of a keyboard macro, indenting and filling it
4306 ;; properly is pretty fast.
4307 '("1C-Enterprise" "4D" "ABAP" "ABNF" "AGS-Script" "AMPL" "ANTLR"
4308 "API-Blueprint" "APL" "ASN.1" "ASP" "ATS" "ActionScript" "Ada"
4309 "Adobe-Font-Metrics" "Agda" "Alloy" "Alpine-Abuild" "Altium-Designer"
4310 "AngelScript" "Ant-Build-System" "ApacheConf" "Apex"
4311 "Apollo-Guidance-Computer" "AppleScript" "Arc" "AsciiDoc" "AspectJ" "Assembly"
4312 "Asymptote" "Augeas" "AutoHotkey" "AutoIt" "Awk" "Ballerina" "Batchfile"
4313 "Befunge" "BibTeX" "Bison" "BitBake" "Blade" "BlitzBasic" "BlitzMax"
4314 "Bluespec" "Boo" "Brainfuck" "Brightscript" "C#" "C++" "C-ObjDump"
4315 "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "COLLADA" "CSON" "CSS" "CSV" "CWeb"
4316 "Cabal-Config" "Cap'n-Proto" "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK"
4317 "Cirru" "Clarion" "Clean" "Click" "Clojure" "Closure-Templates"
4318 "Cloud-Firestore-Security-Rules" "CoNLL-U" "CodeQL" "CoffeeScript"
4319 "ColdFusion" "ColdFusion-CFC" "Common-Lisp" "Common-Workflow-Language"
4320 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal" "Csound"
4321 "Csound-Document" "Csound-Score" "Cuda" "Cycript" "Cython" "D-ObjDump"
4322 "DIGITAL-Command-Language" "DM" "DNS-Zone" "DTrace" "Dafny" "Darcs-Patch"
4323 "Dart" "DataWeave" "Dhall" "Diff" "DirectX-3D-File" "Dockerfile" "Dogescript"
4324 "Dylan" "EBNF" "ECL" "ECLiPSe" "EJS" "EML" "EQ" "Eagle" "Easybuild"
4325 "Ecere-Projects" "EditorConfig" "Edje-Data-Collection" "Eiffel" "Elixir" "Elm"
4326 "Emacs-Lisp" "EmberScript" "Erlang" "F#" "F*" "FIGlet-Font" "FLUX" "Factor"
4327 "Fancy" "Fantom" "Faust" "Filebench-WML" "Filterscript" "Formatted" "Forth"
4328 "Fortran" "Fortran-Free-Form" "FreeMarker" "Frege" "G-code" "GAML" "GAMS"
4329 "GAP" "GCC-Machine-Description" "GDB" "GDScript" "GEDCOM" "GLSL" "GN"
4330 "Game-Maker-Language" "Genie" "Genshi" "Gentoo-Ebuild" "Gentoo-Eclass"
4331 "Gerber-Image" "Gettext-Catalog" "Gherkin" "Git-Attributes" "Git-Config"
4332 "Glyph" "Glyph-Bitmap-Distribution-Format" "Gnuplot" "Go" "Golo" "Gosu"
4333 "Grace" "Gradle" "Grammatical-Framework" "Graph-Modeling-Language" "GraphQL"
4334 "Graphviz-(DOT)" "Groovy" "Groovy-Server-Pages" "HAProxy" "HCL" "HLSL" "HTML"
4335 "HTML+Django" "HTML+ECR" "HTML+EEX" "HTML+ERB" "HTML+PHP" "HTML+Razor" "HTTP"
4336 "HXML" "Hack" "Haml" "Handlebars" "Harbour" "Haskell" "Haxe" "HiveQL" "HolyC"
4337 "Hy" "HyPhy" "IDL" "IGOR-Pro" "INI" "IRC-log" "Idris" "Ignore-List" "Inform-7"
4338 "Inno-Setup" "Io" "Ioke" "Isabelle" "Isabelle-ROOT" "JFlex" "JSON"
4339 "JSON-with-Comments" "JSON5" "JSONLD" "JSONiq" "JSX" "Jasmin" "Java"
4340 "Java-Properties" "Java-Server-Pages" "JavaScript" "JavaScript+ERB" "Jison"
4341 "Jison-Lex" "Jolie" "Jsonnet" "Julia" "Jupyter-Notebook" "KRL" "KiCad-Layout"
4342 "KiCad-Legacy-Layout" "KiCad-Schematic" "Kit" "Kotlin" "LFE" "LLVM" "LOLCODE"
4343 "LSL" "LTspice-Symbol" "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex"
4344 "LilyPond" "Limbo" "Linker-Script" "Linux-Kernel-Module" "Liquid"
4345 "Literate-Agda" "Literate-CoffeeScript" "Literate-Haskell" "LiveScript"
4346 "Logos" "Logtalk" "LookML" "LoomScript" "Lua" "M4" "M4Sugar" "MATLAB"
4347 "MAXScript" "MLIR" "MQL4" "MQL5" "MTML" "MUF" "Macaulay2" "Makefile" "Mako"
4348 "Markdown" "Marko" "Mask" "Mathematica" "Maven-POM" "Max" "MediaWiki"
4349 "Mercury" "Meson" "Metal" "Microsoft-Developer-Studio-Project" "MiniD" "Mirah"
4350 "Modelica" "Modula-2" "Modula-3" "Module-Management-System" "Monkey" "Moocode"
4351 "MoonScript" "Motorola-68K-Assembly" "Muse" "Myghty" "NASL" "NCL" "NEON" "NL"
4352 "NPM-Config" "NSIS" "Nearley" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo"
4353 "NewLisp" "Nextflow" "Nginx" "Nim" "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml"
4354 "ObjDump" "Object-Data-Instance-Notation" "ObjectScript" "Objective-C"
4355 "Objective-C++" "Objective-J" "Odin" "Omgrofl" "Opa" "Opal"
4356 "Open-Policy-Agent" "OpenCL" "OpenEdge-ABL" "OpenQASM" "OpenRC-runscript"
4357 "OpenSCAD" "OpenStep-Property-List" "OpenType-Feature-File" "Org" "Ox"
4358 "Oxygene" "Oz" "P4" "PHP" "PLSQL" "PLpgSQL" "POV-Ray-SDL" "Pan" "Papyrus"
4359 "Parrot" "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal" "Pawn"
4360 "Pep8" "Perl" "Pic" "Pickle" "PicoLisp" "PigLatin" "Pike" "PlantUML" "Pod"
4361 "Pod-6" "PogoScript" "Pony" "PostCSS" "PostScript" "PowerBuilder" "PowerShell"
4362 "Prisma" "Processing" "Proguard" "Prolog" "Propeller-Spin" "Protocol-Buffer"
4363 "Public-Key" "Pug" "Puppet" "Pure-Data" "PureBasic" "PureScript" "Python"
4364 "Python-console" "Python-traceback" "QML" "QMake" "Quake" "RAML" "RDoc"
4365 "REALbasic" "REXX" "RHTML" "RMarkdown" "RPC" "RPM-Spec" "RUNOFF" "Racket"
4366 "Ragel" "Raku" "Rascal" "Raw-token-data" "Readline-Config" "Reason" "Rebol"
4367 "Red" "Redcode" "Regular-Expression" "Ren'Py" "RenderScript"
4368 "Rich-Text-Format" "Ring" "Riot" "RobotFramework" "Roff" "Roff-Manpage"
4369 "Rouge" "Ruby" "Rust" "SAS" "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL"
4370 "SRecode-Template" "SSH-Config" "STON" "SVG" "SWIG" "Sage" "SaltStack" "Sass"
4371 "Scala" "Scaml" "Scheme" "Scilab" "Self" "ShaderLab" "Shell" "ShellSession"
4372 "Shen" "Slash" "Slice" "Slim" "SmPL" "Smali" "Smalltalk" "Smarty" "Solidity"
4373 "SourcePawn" "Spline-Font-Database" "Squirrel" "Stan" "Standard-ML" "Starlark"
4374 "Stata" "Stylus" "SubRip-Text" "SugarSS" "SuperCollider" "Svelte" "Swift"
4375 "SystemVerilog" "TI-Program" "TLA" "TOML" "TSQL" "TSX" "TXL" "Tcl" "Tcsh"
4376 "TeX" "Tea" "Terra" "Texinfo" "Text" "Textile" "Thrift" "Turing" "Turtle"
4377 "Twig" "Type-Language" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset"
4378 "Unix-Assembly" "Uno" "UnrealScript" "UrWeb" "VBA" "VBScript" "VCL" "VHDL"
4379 "Vala" "Verilog" "Vim-Snippet" "Vim-script" "Visual-Basic-.NET" "Volt" "Vue"
4380 "Wavefront-Material" "Wavefront-Object" "Web-Ontology-Language" "WebAssembly"
4381 "WebIDL" "WebVTT" "Wget-Config" "Windows-Registry-Entries" "Wollok"
4382 "World-of-Warcraft-Addon-Data" "X-BitMap" "X-Font-Directory-Index" "X-PixMap"
4383 "X10" "XC" "XCompose" "XML" "XML-Property-List" "XPages" "XProc" "XQuery" "XS"
4384 "XSLT" "Xojo" "Xtend" "YAML" "YANG" "YARA" "YASnippet" "Yacc" "ZAP" "ZIL"
4385 "Zeek" "ZenScript" "Zephir" "Zig" "Zimpl" "cURL-Config" "desktop" "dircolors"
4386 "eC" "edn" "fish" "mIRC-Script" "mcfunction" "mupad" "nanorc" "nesC" "ooc"
4387 "reStructuredText" "sed" "wdl" "wisp" "xBase")
4388 "Language specifiers recognized by GitHub's syntax highlighting features.")
4390 (defvar-local markdown-gfm-used-languages nil
4391 "Language names used in GFM code blocks.")
4393 (defun markdown-trim-whitespace (str)
4394 (replace-regexp-in-string
4395 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str
))
4397 (defun markdown-clean-language-string (str)
4398 (replace-regexp-in-string
4399 "{\\.?\\|}" "" (markdown-trim-whitespace str
)))
4401 (defun markdown-validate-language-string (widget)
4402 (let ((str (widget-value widget
)))
4403 (unless (string= str
(markdown-clean-language-string str
))
4404 (widget-put widget
:error
(format "Invalid language spec: '%s'" str
))
4407 (defun markdown-gfm-get-corpus ()
4408 "Create corpus of recognized GFM code block languages for the given buffer."
4409 (let ((given-corpus (append markdown-gfm-additional-languages
4410 markdown-gfm-recognized-languages
)))
4412 markdown-gfm-used-languages
4413 (if markdown-gfm-downcase-languages
(cl-mapcar #'downcase given-corpus
)
4416 (defun markdown-gfm-add-used-language (lang)
4417 "Clean LANG and add to list of used languages."
4418 (setq markdown-gfm-used-languages
4419 (cons lang
(remove lang markdown-gfm-used-languages
))))
4421 (defcustom markdown-spaces-after-code-fence
1
4422 "Number of space characters to insert after a code fence.
4423 \\<gfm-mode-map>\\[markdown-insert-gfm-code-block] inserts this many spaces between an
4424 opening code fence and an info string."
4428 :package-version
'(markdown-mode .
"2.3"))
4430 (defcustom markdown-code-block-braces nil
4431 "When non-nil, automatically insert braces for GFM code blocks."
4435 (defun markdown-insert-gfm-code-block (&optional lang edit
)
4436 "Insert GFM code block for language LANG.
4437 If LANG is nil, the language will be queried from user. If a
4438 region is active, wrap this region with the markup instead. If
4439 the region boundaries are not on empty lines, these are added
4440 automatically in order to have the correct markup. When EDIT is
4441 non-nil (e.g., when \\[universal-argument] is given), edit the
4442 code block in an indirect buffer after insertion."
4444 (list (let ((completion-ignore-case nil
))
4446 (markdown-clean-language-string
4448 "Programming language: "
4449 (markdown-gfm-get-corpus)
4450 nil
'confirm
(car markdown-gfm-used-languages
)
4451 'markdown-gfm-language-history
))
4453 current-prefix-arg
))
4454 (unless (string= lang
"") (markdown-gfm-add-used-language lang
))
4455 (when (and (> (length lang
) 0)
4456 (not markdown-code-block-braces
))
4457 (setq lang
(concat (make-string markdown-spaces-after-code-fence ?\s
)
4459 (let ((gfm-open-brace (if markdown-code-block-braces
"{" ""))
4460 (gfm-close-brace (if markdown-code-block-braces
"}" "")))
4462 (let* ((b (region-beginning)) (e (region-end)) end
4463 (indent (progn (goto-char b
) (current-indentation))))
4465 ;; if we're on a blank line, don't newline, otherwise the ```
4466 ;; should go on its own line
4467 (unless (looking-back "\n" nil
)
4471 (markdown-ensure-blank-line-after)
4474 ;; if we're on a blank line, insert the quotes here, otherwise
4475 ;; add a new line first
4476 (unless (looking-at-p "\n")
4479 (markdown-ensure-blank-line-before)
4481 (insert "```" gfm-open-brace lang gfm-close-brace
)
4482 (markdown-syntax-propertize-fenced-block-constructs (line-beginning-position) end
))
4483 (let ((indent (current-indentation))
4485 (delete-horizontal-space :backward-only
)
4486 (markdown-ensure-blank-line-before)
4488 (setq start-bol
(line-beginning-position))
4489 (insert "```" gfm-open-brace lang gfm-close-brace
"\n")
4491 (unless edit
(insert ?
\n))
4494 (markdown-ensure-blank-line-after)
4495 (markdown-syntax-propertize-fenced-block-constructs start-bol
(point)))
4497 (when edit
(markdown-edit-code-block)))))
4499 (defun markdown-code-block-lang (&optional pos-prop
)
4500 "Return the language name for a GFM or tilde fenced code block.
4501 The beginning of the block may be described by POS-PROP,
4502 a cons of (pos . prop) giving the position and property
4503 at the beginning of the block."
4506 (markdown-max-of-seq
4511 #'markdown-find-previous-prop
4512 (markdown-get-fenced-block-begin-properties))))))
4514 (goto-char (car pos-prop
))
4515 (set-match-data (get-text-property (point) (cdr pos-prop
)))
4516 ;; Note: Hard-coded group number assumes tilde
4517 ;; and GFM fenced code regexp groups agree.
4518 (let ((begin (match-beginning 3))
4519 (end (match-end 3)))
4520 (when (and begin end
)
4521 ;; Fix language strings beginning with periods, like ".ruby".
4522 (when (eq (char-after begin
) ?.
)
4523 (setq begin
(1+ begin
)))
4524 (buffer-substring-no-properties begin end
)))))
4526 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer
)
4527 (with-current-buffer (or buffer
(current-buffer))
4529 (goto-char (point-min))
4531 with prop
= 'markdown-gfm-block-begin
4532 for pos-prop
= (markdown-find-next-prop prop
)
4534 for lang
= (markdown-code-block-lang pos-prop
)
4535 do
(progn (when lang
(markdown-gfm-add-used-language lang
))
4536 (goto-char (next-single-property-change (point) prop
)))))))
4538 (defun markdown-insert-foldable-block ()
4539 "Insert details disclosure element to make content foldable.
4540 If a region is active, wrap this region with the disclosure
4541 element. More detais here https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details."
4543 (let ((details-open-tag "<details>")
4544 (details-close-tag "</details>")
4545 (summary-open-tag "<summary>")
4546 (summary-close-tag " </summary>"))
4548 (let* ((b (region-beginning))
4550 (indent (progn (goto-char b
) (current-indentation))))
4552 ;; if we're on a blank line, don't newline, otherwise the tags
4553 ;; should go on its own line
4554 (unless (looking-back "\n" nil
)
4557 (insert details-close-tag
)
4558 (markdown-ensure-blank-line-after)
4560 ;; if we're on a blank line, insert the quotes here, otherwise
4561 ;; add a new line first
4562 (unless (looking-at-p "\n")
4565 (markdown-ensure-blank-line-before)
4567 (insert details-open-tag
"\n")
4568 (insert summary-open-tag summary-close-tag
)
4569 (search-backward summary-close-tag
))
4570 (let ((indent (current-indentation)))
4571 (delete-horizontal-space :backward-only
)
4572 (markdown-ensure-blank-line-before)
4574 (insert details-open-tag
"\n")
4575 (insert summary-open-tag summary-close-tag
"\n")
4576 (insert details-close-tag
)
4578 (markdown-ensure-blank-line-after)
4579 (search-backward summary-close-tag
)))))
4582 ;;; Footnotes =================================================================
4584 (defun markdown-footnote-counter-inc ()
4585 "Increment `markdown-footnote-counter' and return the new value."
4586 (when (= markdown-footnote-counter
0) ; hasn't been updated in this buffer yet.
4588 (goto-char (point-min))
4589 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars
"*?\\)\\]:")
4591 (let ((fn (string-to-number (match-string 1))))
4592 (when (> fn markdown-footnote-counter
)
4593 (setq markdown-footnote-counter fn
))))))
4594 (cl-incf markdown-footnote-counter
))
4596 (defun markdown-insert-footnote ()
4597 "Insert footnote with a new number and move point to footnote definition."
4599 (let ((fn (markdown-footnote-counter-inc)))
4600 (insert (format "[^%d]" fn
))
4601 (markdown-footnote-text-find-new-location)
4602 (markdown-ensure-blank-line-before)
4603 (unless (markdown-cur-line-blank-p)
4605 (insert (format "[^%d]: " fn
))
4606 (markdown-ensure-blank-line-after)))
4608 (defun markdown-footnote-text-find-new-location ()
4609 "Position the point at the proper location for a new footnote text."
4611 ((eq markdown-footnote-location
'end
) (goto-char (point-max)))
4612 ((eq markdown-footnote-location
'immediately
) (markdown-end-of-text-block))
4613 ((eq markdown-footnote-location
'subtree
) (markdown-end-of-subtree))
4614 ((eq markdown-footnote-location
'header
) (markdown-end-of-defun))))
4616 (defun markdown-footnote-kill ()
4617 "Kill the footnote at point.
4618 The footnote text is killed (and added to the kill ring), the
4619 footnote marker is deleted. Point has to be either at the
4620 footnote marker or in the footnote text."
4622 (let ((marker-pos nil
)
4623 (skip-deleting-marker nil
)
4624 (starting-footnote-text-positions
4625 (markdown-footnote-text-positions)))
4626 (when starting-footnote-text-positions
4627 ;; We're starting in footnote text, so mark our return position and jump
4628 ;; to the marker if possible.
4629 (let ((marker-pos (markdown-footnote-find-marker
4630 (cl-first starting-footnote-text-positions
))))
4632 (goto-char (1- marker-pos
))
4633 ;; If there isn't a marker, we still want to kill the text.
4634 (setq skip-deleting-marker t
))))
4635 ;; Either we didn't start in the text, or we started in the text and jumped
4636 ;; to the marker. We want to assume we're at the marker now and error if
4638 (unless skip-deleting-marker
4639 (let ((marker (markdown-footnote-delete-marker)))
4641 (error "Not at a footnote"))
4642 ;; Even if we knew the text position before, it changed when we deleted
4644 (setq marker-pos
(cl-second marker
))
4645 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker
))))
4646 (unless new-text-pos
4647 (error "No text for footnote `%s'" (cl-first marker
)))
4648 (goto-char new-text-pos
))))
4649 (let ((pos (markdown-footnote-kill-text)))
4650 (goto-char (if starting-footnote-text-positions
4654 (defun markdown-footnote-delete-marker ()
4655 "Delete a footnote marker at point.
4656 Returns a list (ID START) containing the footnote ID and the
4657 start position of the marker before deletion. If no footnote
4658 marker was deleted, this function returns NIL."
4659 (let ((marker (markdown-footnote-marker-positions)))
4661 (delete-region (cl-second marker
) (cl-third marker
))
4664 (defun markdown-footnote-kill-text ()
4665 "Kill footnote text at point.
4666 Returns the start position of the footnote text before deletion,
4667 or NIL if point was not inside a footnote text.
4669 The killed text is placed in the kill ring (without the footnote
4671 (let ((fn (markdown-footnote-text-positions)))
4673 (let ((text (delete-and-extract-region (cl-second fn
) (cl-third fn
))))
4674 (string-match (concat "\\[\\" (cl-first fn
) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text
)
4675 (kill-new (match-string 1 text
))
4676 (when (and (markdown-cur-line-blank-p)
4677 (markdown-prev-line-blank-p)
4679 (delete-region (1- (point)) (point)))
4682 (defun markdown-footnote-goto-text ()
4683 "Jump to the text of the footnote at point."
4685 (let ((fn (car (markdown-footnote-marker-positions))))
4687 (user-error "Not at a footnote marker"))
4688 (let ((new-pos (markdown-footnote-find-text fn
)))
4690 (error "No definition found for footnote `%s'" fn
))
4691 (goto-char new-pos
))))
4693 (defun markdown-footnote-return ()
4694 "Return from a footnote to its footnote number in the main text."
4696 (let ((fn (save-excursion
4697 (car (markdown-footnote-text-positions)))))
4699 (user-error "Not in a footnote"))
4700 (let ((new-pos (markdown-footnote-find-marker fn
)))
4702 (error "Footnote marker `%s' not found" fn
))
4703 (goto-char new-pos
))))
4705 (defun markdown-footnote-find-marker (id)
4706 "Find the location of the footnote marker with ID.
4707 The actual buffer position returned is the position directly
4708 following the marker's closing bracket. If no marker is found,
4711 (goto-char (point-min))
4712 (when (re-search-forward (concat "\\[" id
"\\]\\([^:]\\|\\'\\)") nil t
)
4713 (skip-chars-backward "^]")
4716 (defun markdown-footnote-find-text (id)
4717 "Find the location of the text of footnote ID.
4718 The actual buffer position returned is the position of the first
4719 character of the text, after the footnote's identifier. If no
4720 footnote text is found, NIL is returned."
4722 (goto-char (point-min))
4723 (when (re-search-forward (concat "^ \\{0,3\\}\\[" id
"\\]:") nil t
)
4724 (skip-chars-forward "[ \t]")
4727 (defun markdown-footnote-marker-positions ()
4728 "Return the position and ID of the footnote marker point is on.
4729 The return value is a list (ID START END). If point is not on a
4730 footnote, NIL is returned."
4731 ;; first make sure we're at a footnote marker
4732 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars
"*\\]?") (line-beginning-position))
4733 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars
"*?\\]")))
4735 ;; move point between [ and ^:
4736 (if (looking-at-p "\\[")
4738 (skip-chars-backward "^["))
4739 (looking-at (concat "\\(\\^" markdown-footnote-chars
"*?\\)\\]"))
4740 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
4742 (defun markdown-footnote-text-positions ()
4743 "Return the start and end positions of the footnote text point is in.
4744 The exact return value is a list of three elements: (ID START END).
4745 The start position is the position of the opening bracket
4746 of the footnote id. The end position is directly after the
4747 newline that ends the footnote. If point is not in a footnote,
4748 NIL is returned instead."
4751 (move-beginning-of-line 1)
4752 ;; Try to find the label. If we haven't found the label and we're at a blank
4753 ;; or indented line, back up if possible.
4755 (not (and (looking-at markdown-regex-footnote-definition
)
4756 (setq result
(list (match-string 1) (point)))))
4758 (or (markdown-cur-line-blank-p)
4759 (>= (current-indentation) 4))))
4762 ;; Advance if there is a next line that is either blank or indented.
4763 ;; (Need to check if we're on the last line, because
4764 ;; markdown-next-line-blank-p returns true for last line in buffer.)
4765 (while (and (/= (line-end-position) (point-max))
4766 (or (markdown-next-line-blank-p)
4767 (>= (markdown-next-line-indent) 4)))
4769 ;; Move back while the current line is blank.
4770 (while (markdown-cur-line-blank-p)
4772 ;; Advance to capture this line and a single trailing newline (if there
4775 (append result
(list (point)))))))
4777 (defun markdown-get-defined-footnotes ()
4778 "Return a list of all defined footnotes.
4779 Result is an alist of pairs (MARKER . LINE), where MARKER is the
4780 footnote marker, a string, and LINE is the line number containing
4781 the footnote definition.
4783 For example, suppose the following footnotes are defined at positions
4786 \[^1]: First footnote here.
4787 \[^marker]: Second footnote.
4789 Then the returned list is: ((\"^1\" . 478) (\"^marker\" . 475))"
4791 (goto-char (point-min))
4793 (while (markdown-search-until-condition
4794 (lambda () (and (not (markdown-code-block-at-point-p))
4795 (not (markdown-inline-code-at-point-p))
4796 (not (markdown-in-comment-p))))
4797 markdown-regex-footnote-definition nil t
)
4798 (let ((marker (match-string-no-properties 1))
4799 (pos (match-beginning 0)))
4800 (unless (zerop (length marker
))
4801 (cl-pushnew (cons marker pos
) footnotes
:test
#'equal
))))
4802 (reverse footnotes
))))
4805 ;;; Element Removal ===========================================================
4807 (defun markdown-kill-thing-at-point ()
4808 "Kill thing at point and add important text, without markup, to kill ring.
4809 Possible things to kill include (roughly in order of precedence):
4810 inline code, headers, horizontal rules, links (add link text to
4811 kill ring), images (add alt text to kill ring), angle uri, email
4812 addresses, bold, italics, reference definition (add URI to kill
4813 ring), footnote markers and text (kill both marker and text, add
4814 text to kill ring), and list items."
4819 ((markdown-inline-code-at-point)
4820 (kill-new (match-string 2))
4821 (delete-region (match-beginning 0) (match-end 0)))
4823 ((thing-at-point-looking-at markdown-regex-header-atx
)
4824 (kill-new (match-string 2))
4825 (delete-region (match-beginning 0) (match-end 0)))
4827 ((thing-at-point-looking-at markdown-regex-header-setext
)
4828 (kill-new (match-string 1))
4829 (delete-region (match-beginning 0) (match-end 0)))
4831 ((thing-at-point-looking-at markdown-regex-hr
)
4832 (kill-new (match-string 0))
4833 (delete-region (match-beginning 0) (match-end 0)))
4834 ;; Inline link or image (add link or alt text to kill ring)
4835 ((thing-at-point-looking-at markdown-regex-link-inline
)
4836 (kill-new (match-string 3))
4837 (delete-region (match-beginning 0) (match-end 0)))
4838 ;; Reference link or image (add link or alt text to kill ring)
4839 ((thing-at-point-looking-at markdown-regex-link-reference
)
4840 (kill-new (match-string 3))
4841 (delete-region (match-beginning 0) (match-end 0)))
4842 ;; Angle URI (add URL to kill ring)
4843 ((thing-at-point-looking-at markdown-regex-angle-uri
)
4844 (kill-new (match-string 2))
4845 (delete-region (match-beginning 0) (match-end 0)))
4846 ;; Email address in angle brackets (add email address to kill ring)
4847 ((thing-at-point-looking-at markdown-regex-email
)
4848 (kill-new (match-string 1))
4849 (delete-region (match-beginning 0) (match-end 0)))
4850 ;; Wiki link (add alias text to kill ring)
4851 ((and markdown-enable-wiki-links
4852 (thing-at-point-looking-at markdown-regex-wiki-link
))
4853 (kill-new (markdown-wiki-link-alias))
4854 (delete-region (match-beginning 1) (match-end 1)))
4856 ((thing-at-point-looking-at markdown-regex-bold
)
4857 (kill-new (match-string 4))
4858 (delete-region (match-beginning 2) (match-end 2)))
4860 ((thing-at-point-looking-at markdown-regex-italic
)
4861 (kill-new (match-string 3))
4862 (delete-region (match-beginning 1) (match-end 1)))
4864 ((thing-at-point-looking-at markdown-regex-strike-through
)
4865 (kill-new (match-string 4))
4866 (delete-region (match-beginning 2) (match-end 2)))
4867 ;; Footnote marker (add footnote text to kill ring)
4868 ((thing-at-point-looking-at markdown-regex-footnote
)
4869 (markdown-footnote-kill))
4870 ;; Footnote text (add footnote text to kill ring)
4871 ((setq val
(markdown-footnote-text-positions))
4872 (markdown-footnote-kill))
4873 ;; Reference definition (add URL to kill ring)
4874 ((thing-at-point-looking-at markdown-regex-reference-definition
)
4875 (kill-new (match-string 5))
4876 (delete-region (match-beginning 0) (match-end 0)))
4878 ((setq val
(markdown-cur-list-item-bounds))
4879 (kill-new (delete-and-extract-region (cl-first val
) (cl-second val
))))
4881 (user-error "Nothing found at point to kill")))))
4883 (defun markdown-kill-outline ()
4884 "Kill visible heading and add it to `kill-ring'."
4887 (markdown-outline-previous)
4888 (kill-region (point) (progn (markdown-outline-next) (point)))))
4890 (defun markdown-kill-block ()
4891 "Kill visible code block, list item, or blockquote and add it to `kill-ring'."
4894 (markdown-backward-block)
4895 (kill-region (point) (progn (markdown-forward-block) (point)))))
4898 ;;; Indentation ===============================================================
4900 (defun markdown-indent-find-next-position (cur-pos positions
)
4901 "Return the position after the index of CUR-POS in POSITIONS.
4902 Positions are calculated by `markdown-calc-indents'."
4903 (while (and positions
4904 (not (equal cur-pos
(car positions
))))
4905 (setq positions
(cdr positions
)))
4906 (or (cadr positions
) 0))
4908 (defun markdown-outdent-find-next-position (cur-pos positions
)
4909 "Return the maximal element that precedes CUR-POS from POSITIONS.
4910 Positions are calculated by `markdown-calc-indents'."
4912 (dolist (i positions
)
4914 (setq result
(max result i
))))
4917 (defun markdown-indent-line ()
4918 "Indent the current line using some heuristics.
4919 If the _previous_ command was either `markdown-enter-key' or
4920 `markdown-cycle', then we should cycle to the next
4921 reasonable indentation position. Otherwise, we could have been
4922 called directly by `markdown-enter-key', by an initial call of
4923 `markdown-cycle', or indirectly by `auto-fill-mode'. In
4924 these cases, indent to the default position.
4925 Positions are calculated by `markdown-calc-indents'."
4927 (let ((positions (markdown-calc-indents))
4928 (point-pos (current-column))
4929 (_ (back-to-indentation))
4930 (cur-pos (current-column)))
4931 (if (not (equal this-command
'markdown-cycle
))
4932 (indent-line-to (car positions
))
4933 (setq positions
(sort (delete-dups positions
) '<))
4934 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions
))
4935 (new-point-pos (max (+ point-pos
(- next-pos cur-pos
)) 0)))
4936 (indent-line-to next-pos
)
4937 (move-to-column new-point-pos
)))))
4939 (defun markdown-calc-indents ()
4940 "Return a list of indentation columns to cycle through.
4941 The first element in the returned list should be considered the
4942 default indentation level. This function does not worry about
4943 duplicate positions, which are handled up by calling functions."
4944 (let (pos prev-line-pos positions
)
4946 ;; Indentation of previous line
4947 (setq prev-line-pos
(markdown-prev-line-indent))
4948 (setq positions
(cons prev-line-pos positions
))
4950 ;; Indentation of previous non-list-marker text
4951 (when (setq pos
(save-excursion
4953 (when (looking-at markdown-regex-list
)
4954 (- (match-end 3) (match-beginning 0)))))
4955 (setq positions
(cons pos positions
)))
4957 ;; Indentation required for a pre block in current context
4958 (setq pos
(length (markdown-pre-indentation (point))))
4959 (setq positions
(cons pos positions
))
4961 ;; Indentation of the previous line + tab-width
4963 (setq positions
(cons (+ prev-line-pos tab-width
) positions
))
4964 (setq positions
(cons tab-width positions
)))
4966 ;; Indentation of the previous line - tab-width
4967 (if (and prev-line-pos
(> prev-line-pos tab-width
))
4968 (setq positions
(cons (- prev-line-pos tab-width
) positions
)))
4970 ;; Indentation of all preceding list markers (when in a list)
4971 (when (setq pos
(markdown-calculate-list-levels))
4972 (setq positions
(append pos positions
)))
4975 (setq positions
(cons 0 positions
))
4977 ;; Return reversed list
4978 (reverse positions
)))
4980 (defun markdown-enter-key () ;FIXME: Partly obsoleted by electric-indent
4981 "Handle RET depending on the context.
4982 If the point is at a table, move to the next row. Otherwise,
4983 indent according to value of `markdown-indent-on-enter'.
4984 When it is nil, simply call `newline'. Otherwise, indent the next line
4985 following RET using `markdown-indent-line'. Furthermore, when it
4986 is set to \\='indent-and-new-item and the point is in a list item,
4987 start a new item with the same indentation. If the point is in an
4988 empty list item, remove it (so that pressing RET twice when in a
4989 list simply adds a blank line)."
4993 ((markdown-table-at-point-p)
4994 (call-interactively #'markdown-table-next-row
))
4995 ;; Indent non-table text
4996 (markdown-indent-on-enter
4998 (if (and (memq markdown-indent-on-enter
'(indent-and-new-item))
4999 (setq bounds
(markdown-cur-list-item-bounds)))
5000 (let ((beg (cl-first bounds
))
5001 (end (cl-second bounds
))
5002 (length (cl-fourth bounds
)))
5003 ;; Point is in a list item
5004 (if (= (- end beg
) length
)
5005 ;; Delete blank list
5007 (delete-region beg end
)
5009 (markdown-indent-line))
5010 (call-interactively #'markdown-insert-list-item
)))
5011 ;; Point is not in a list
5013 (markdown-indent-line))))
5014 ;; Insert a raw newline
5017 (defun markdown-outdent-or-delete (arg)
5018 "Handle BACKSPACE by cycling through indentation points.
5019 When BACKSPACE is pressed, if there is only whitespace
5020 before the current point, then outdent the line one level.
5021 Otherwise, do normal delete by repeating
5022 `backward-delete-char-untabify' ARG times."
5025 (backward-delete-char-untabify arg
)
5026 (let ((cur-pos (current-column))
5027 (start-of-indention (save-excursion
5028 (back-to-indentation)
5030 (positions (markdown-calc-indents)))
5031 (if (and (> cur-pos
0) (= cur-pos start-of-indention
))
5032 (indent-line-to (markdown-outdent-find-next-position cur-pos positions
))
5033 (backward-delete-char-untabify arg
)))))
5035 (defun markdown-find-leftmost-column (beg end
)
5036 "Find the leftmost column in the region from BEG to END."
5037 (let ((mincol 1000))
5040 (while (< (point) end
)
5041 (back-to-indentation)
5042 (unless (looking-at-p "[ \t]*$")
5043 (setq mincol
(min mincol
(current-column))))
5048 (defun markdown-indent-region (beg end arg
)
5049 "Indent the region from BEG to END using some heuristics.
5050 When ARG is non-nil, outdent the region instead.
5051 See `markdown-indent-line' and `markdown-indent-line'."
5052 (interactive "*r\nP")
5053 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
5054 (leftmostcol (markdown-find-leftmost-column beg end
))
5056 (markdown-outdent-find-next-position leftmostcol positions
)
5057 (markdown-indent-find-next-position leftmostcol positions
))))
5058 (indent-rigidly beg end
(- next-pos leftmostcol
))
5059 (setq deactivate-mark nil
)))
5061 (defun markdown-outdent-region (beg end
)
5062 "Call `markdown-indent-region' on region from BEG to END with prefix."
5064 (markdown-indent-region beg end t
))
5066 (defun markdown--indent-region (start end
)
5067 (let ((deactivate-mark nil
))
5070 (setq end
(point-marker))
5074 (while (< (point) end
)
5075 (unless (or (markdown-code-block-at-point-p) (and (bolp) (eolp)))
5076 (indent-according-to-mode))
5078 (move-marker end nil
))))
5081 ;;; Markup Completion =========================================================
5083 (defconst markdown-complete-alist
5084 '((markdown-regex-header-atx . markdown-complete-atx
)
5085 (markdown-regex-header-setext . markdown-complete-setext
)
5086 (markdown-regex-hr . markdown-complete-hr
))
5087 "Association list of form (regexp . function) for markup completion.")
5089 (defun markdown-incomplete-atx-p ()
5090 "Return t if ATX header markup is incomplete and nil otherwise.
5091 Assumes match data is available for `markdown-regex-header-atx'.
5092 Checks that the number of trailing hash marks equals the number of leading
5093 hash marks, that there is only a single space before and after the text,
5094 and that there is no extraneous whitespace in the text."
5096 ;; Number of starting and ending hash marks differs
5097 (not (= (length (match-string 1)) (length (match-string 3))))
5098 ;; When the header text is not empty...
5099 (and (> (length (match-string 2)) 0)
5100 ;; ...if there are extra leading, trailing, or interior spaces
5101 (or (not (= (match-beginning 2) (1+ (match-end 1))))
5102 (not (= (match-beginning 3) (1+ (match-end 2))))
5103 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
5104 ;; When the header text is empty...
5105 (and (= (length (match-string 2)) 0)
5106 ;; ...if there are too many or too few spaces
5107 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
5109 (defun markdown-complete-atx ()
5110 "Complete and normalize ATX headers.
5111 Add or remove hash marks to the end of the header to match the
5112 beginning. Ensure that there is only a single space between hash
5113 marks and header text. Removes extraneous whitespace from header text.
5114 Assumes match data is available for `markdown-regex-header-atx'.
5115 Return nil if markup was complete and non-nil if markup was completed."
5116 (when (markdown-incomplete-atx-p)
5117 (let* ((new-marker (make-marker))
5118 (new-marker (set-marker new-marker
(match-end 2))))
5119 ;; Hash marks and spacing at end
5120 (goto-char (match-end 2))
5121 (delete-region (match-end 2) (match-end 3))
5122 (insert " " (match-string 1))
5123 ;; Remove extraneous whitespace from title
5124 (replace-match (markdown-compress-whitespace-string (match-string 2))
5126 ;; Spacing at beginning
5127 (goto-char (match-end 1))
5128 (delete-region (match-end 1) (match-beginning 2))
5130 ;; Leave point at end of text
5131 (goto-char new-marker
))))
5133 (defun markdown-incomplete-setext-p ()
5134 "Return t if setext header markup is incomplete and nil otherwise.
5135 Assumes match data is available for `markdown-regex-header-setext'.
5136 Checks that length of underline matches text and that there is no
5137 extraneous whitespace in the text."
5138 (or (not (= (length (match-string 1)) (length (match-string 2))))
5139 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
5141 (defun markdown-complete-setext ()
5142 "Complete and normalize setext headers.
5143 Add or remove underline characters to match length of header
5144 text. Removes extraneous whitespace from header text. Assumes
5145 match data is available for `markdown-regex-header-setext'.
5146 Return nil if markup was complete and non-nil if markup was completed."
5147 (when (markdown-incomplete-setext-p)
5148 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
5149 (char (char-after (match-beginning 2)))
5150 (level (if (char-equal char ?-
) 2 1)))
5151 (goto-char (match-beginning 0))
5152 (delete-region (match-beginning 0) (match-end 0))
5153 (markdown-insert-header level text t
)
5156 (defun markdown-incomplete-hr-p ()
5157 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
5158 Assumes match data is available for `markdown-regex-hr'."
5159 (not (member (match-string 0) markdown-hr-strings
)))
5161 (defun markdown-complete-hr ()
5162 "Complete horizontal rules.
5163 If horizontal rule string is a member of `markdown-hr-strings',
5164 do nothing. Otherwise, replace with the car of
5165 `markdown-hr-strings'.
5166 Assumes match data is available for `markdown-regex-hr'.
5167 Return nil if markup was complete and non-nil if markup was completed."
5168 (when (markdown-incomplete-hr-p)
5169 (replace-match (car markdown-hr-strings
))
5172 (defun markdown-complete ()
5173 "Complete markup of object near point or in region when active.
5174 Handle all objects in `markdown-complete-alist', in order.
5175 See `markdown-complete-at-point' and `markdown-complete-region'."
5178 (markdown-complete-region (region-beginning) (region-end))
5179 (markdown-complete-at-point)))
5181 (defun markdown-complete-at-point ()
5182 "Complete markup of object near point.
5183 Handle all elements of `markdown-complete-alist' in order."
5185 (let ((list markdown-complete-alist
) found changed
)
5187 (let ((regexp (eval (caar list
) t
)) ;FIXME: Why `eval'?
5188 (function (cdar list
)))
5189 (setq list
(cdr list
))
5190 (when (thing-at-point-looking-at regexp
)
5192 (setq changed
(funcall function
))
5195 (or changed
(user-error "Markup at point is complete"))
5196 (user-error "Nothing to complete at point"))))
5198 (defun markdown-complete-region (beg end
)
5199 "Complete markup of objects in region from BEG to END.
5200 Handle all objects in `markdown-complete-alist', in order. Each
5201 match is checked to ensure that a previous regexp does not also
5204 (let ((end-marker (set-marker (make-marker) end
))
5206 (dolist (element markdown-complete-alist
)
5207 (let ((regexp (eval (car element
) t
)) ;FIXME: Why `eval'?
5208 (function (cdr element
)))
5210 (while (re-search-forward regexp end-marker
'limit
)
5211 (when (match-string 0)
5212 ;; Make sure this is not a match for any of the preceding regexps.
5213 ;; This prevents mistaking an HR for a Setext subheading.
5216 (dolist (prev-regexp previous
)
5217 (or match
(setq match
(looking-back prev-regexp nil
)))))
5219 (save-excursion (funcall function
))))))
5220 (cl-pushnew regexp previous
:test
#'equal
)))
5223 (defun markdown-complete-buffer ()
5224 "Complete markup for all objects in the current buffer."
5226 (markdown-complete-region (point-min) (point-max)))
5229 ;;; Markup Cycling ============================================================
5231 (defun markdown-cycle-atx (arg &optional remove
)
5232 "Cycle ATX header markup.
5233 Promote header (decrease level) when ARG is 1 and demote
5234 header (increase level) if arg is -1. When REMOVE is non-nil,
5235 remove the header when the level reaches zero and stop cycling
5236 when it reaches six. Otherwise, perform a proper cycling through
5237 levels one through six. Assumes match data is available for
5238 `markdown-regex-header-atx'."
5239 (let* ((old-level (length (match-string 1)))
5240 (new-level (+ old-level arg
))
5241 (text (match-string 2)))
5243 (setq new-level
(% new-level
6))
5244 (setq new-level
(cond ((= new-level
0) 6)
5245 ((< new-level
0) (+ new-level
6))
5249 (markdown-unwrap-thing-at-point nil
0 2))
5251 (goto-char (match-beginning 0))
5252 (delete-region (match-beginning 0) (match-end 0))
5253 (markdown-insert-header new-level text nil
)))))
5255 (defun markdown-cycle-setext (arg &optional remove
)
5256 "Cycle setext header markup.
5257 Promote header (increase level) when ARG is 1 and demote
5258 header (decrease level or remove) if arg is -1. When demoting a
5259 level-two setext header, replace with a level-three atx header.
5260 When REMOVE is non-nil, remove the header when the level reaches
5261 zero. Otherwise, cycle back to a level six atx header. Assumes
5262 match data is available for `markdown-regex-header-setext'."
5263 (let* ((char (char-after (match-beginning 2)))
5264 (old-level (if (char-equal char ?
=) 1 2))
5265 (new-level (+ old-level arg
)))
5266 (when (and (not remove
) (= new-level
0))
5270 (markdown-unwrap-thing-at-point nil
0 1))
5272 (markdown-insert-header new-level nil t
))
5274 (markdown-insert-header new-level nil nil
)))))
5276 (defun markdown-cycle-hr (arg &optional remove
)
5277 "Cycle string used for horizontal rule from `markdown-hr-strings'.
5278 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
5279 backwards (promote). When REMOVE is non-nil, remove the hr instead
5280 of cycling when the end of the list is reached.
5281 Assumes match data is available for `markdown-regex-hr'."
5282 (let* ((strings (if (= arg -
1)
5283 (reverse markdown-hr-strings
)
5284 markdown-hr-strings
))
5285 (tail (member (match-string 0) strings
))
5286 (new (or (cadr tail
)
5292 (replace-match new
)))
5294 (defun markdown-cycle-bold ()
5295 "Cycle bold markup between underscores and asterisks.
5296 Assumes match data is available for `markdown-regex-bold'."
5298 (let* ((old-delim (match-string 3))
5299 (new-delim (if (string-equal old-delim
"**") "__" "**")))
5300 (replace-match new-delim t t nil
3)
5301 (replace-match new-delim t t nil
5))))
5303 (defun markdown-cycle-italic ()
5304 "Cycle italic markup between underscores and asterisks.
5305 Assumes match data is available for `markdown-regex-italic'."
5307 (let* ((old-delim (match-string 2))
5308 (new-delim (if (string-equal old-delim
"*") "_" "*")))
5309 (replace-match new-delim t t nil
2)
5310 (replace-match new-delim t t nil
4))))
5313 ;;; Keymap ====================================================================
5315 (defun markdown--style-map-prompt ()
5316 "Return a formatted prompt for Markdown markup insertion."
5317 (when markdown-enable-prefix-prompts
5320 (propertize "bold" 'face
'markdown-bold-face
) ", "
5321 (propertize "italic" 'face
'markdown-italic-face
) ", "
5322 (propertize "code" 'face
'markdown-inline-code-face
) ", "
5323 (propertize "C = GFM code" 'face
'markdown-code-face
) ", "
5324 (propertize "pre" 'face
'markdown-pre-face
) ", "
5325 (propertize "footnote" 'face
'markdown-footnote-text-face
) ", "
5326 (propertize "F = foldable" 'face
'markdown-bold-face
) ", "
5327 (propertize "q = blockquote" 'face
'markdown-blockquote-face
) ", "
5328 (propertize "h & 1-6 = heading" 'face
'markdown-header-face
) ", "
5329 (propertize "- = hr" 'face
'markdown-hr-face
) ", "
5332 (defun markdown--command-map-prompt ()
5333 "Return prompt for Markdown buffer-wide commands."
5334 (when markdown-enable-prefix-prompts
5337 (propertize "m" 'face
'markdown-bold-face
) "arkdown, "
5338 (propertize "p" 'face
'markdown-bold-face
) "review, "
5339 (propertize "o" 'face
'markdown-bold-face
) "pen, "
5340 (propertize "e" 'face
'markdown-bold-face
) "xport, "
5341 "export & pre" (propertize "v" 'face
'markdown-bold-face
) "iew, "
5342 (propertize "c" 'face
'markdown-bold-face
) "heck refs, "
5343 (propertize "u" 'face
'markdown-bold-face
) "nused refs, "
5346 (defvar markdown-mode-style-map
5347 (let ((map (make-keymap (markdown--style-map-prompt))))
5348 (define-key map
(kbd "1") 'markdown-insert-header-atx-1
)
5349 (define-key map
(kbd "2") 'markdown-insert-header-atx-2
)
5350 (define-key map
(kbd "3") 'markdown-insert-header-atx-3
)
5351 (define-key map
(kbd "4") 'markdown-insert-header-atx-4
)
5352 (define-key map
(kbd "5") 'markdown-insert-header-atx-5
)
5353 (define-key map
(kbd "6") 'markdown-insert-header-atx-6
)
5354 (define-key map
(kbd "!") 'markdown-insert-header-setext-1
)
5355 (define-key map
(kbd "@") 'markdown-insert-header-setext-2
)
5356 (define-key map
(kbd "b") 'markdown-insert-bold
)
5357 (define-key map
(kbd "c") 'markdown-insert-code
)
5358 (define-key map
(kbd "C") 'markdown-insert-gfm-code-block
)
5359 (define-key map
(kbd "f") 'markdown-insert-footnote
)
5360 (define-key map
(kbd "F") 'markdown-insert-foldable-block
)
5361 (define-key map
(kbd "h") 'markdown-insert-header-dwim
)
5362 (define-key map
(kbd "H") 'markdown-insert-header-setext-dwim
)
5363 (define-key map
(kbd "i") 'markdown-insert-italic
)
5364 (define-key map
(kbd "k") 'markdown-insert-kbd
)
5365 (define-key map
(kbd "l") 'markdown-insert-link
)
5366 (define-key map
(kbd "p") 'markdown-insert-pre
)
5367 (define-key map
(kbd "P") 'markdown-pre-region
)
5368 (define-key map
(kbd "q") 'markdown-insert-blockquote
)
5369 (define-key map
(kbd "s") 'markdown-insert-strike-through
)
5370 (define-key map
(kbd "t") 'markdown-insert-table
)
5371 (define-key map
(kbd "Q") 'markdown-blockquote-region
)
5372 (define-key map
(kbd "w") 'markdown-insert-wiki-link
)
5373 (define-key map
(kbd "-") 'markdown-insert-hr
)
5374 (define-key map
(kbd "[") 'markdown-insert-gfm-checkbox
)
5375 ;; Deprecated keys that may be removed in a future version
5376 (define-key map
(kbd "e") 'markdown-insert-italic
)
5378 "Keymap for Markdown text styling commands.")
5380 (defvar markdown-mode-command-map
5381 (let ((map (make-keymap (markdown--command-map-prompt))))
5382 (define-key map
(kbd "m") 'markdown-other-window
)
5383 (define-key map
(kbd "p") 'markdown-preview
)
5384 (define-key map
(kbd "e") 'markdown-export
)
5385 (define-key map
(kbd "v") 'markdown-export-and-preview
)
5386 (define-key map
(kbd "o") 'markdown-open
)
5387 (define-key map
(kbd "l") 'markdown-live-preview-mode
)
5388 (define-key map
(kbd "w") 'markdown-kill-ring-save
)
5389 (define-key map
(kbd "c") 'markdown-check-refs
)
5390 (define-key map
(kbd "u") 'markdown-unused-refs
)
5391 (define-key map
(kbd "n") 'markdown-cleanup-list-numbers
)
5392 (define-key map
(kbd "]") 'markdown-complete-buffer
)
5393 (define-key map
(kbd "^") 'markdown-table-sort-lines
)
5394 (define-key map
(kbd "|") 'markdown-table-convert-region
)
5395 (define-key map
(kbd "t") 'markdown-table-transpose
)
5397 "Keymap for Markdown buffer-wide commands.")
5399 (defvar markdown-mode-map
5400 (let ((map (make-keymap)))
5401 ;; Markup insertion & removal
5402 (define-key map
(kbd "C-c C-s") markdown-mode-style-map
)
5403 (define-key map
(kbd "C-c C-l") 'markdown-insert-link
)
5404 (define-key map
(kbd "C-c C-k") 'markdown-kill-thing-at-point
)
5405 ;; Promotion, demotion, and cycling
5406 (define-key map
(kbd "C-c C--") 'markdown-promote
)
5407 (define-key map
(kbd "C-c C-=") 'markdown-demote
)
5408 (define-key map
(kbd "C-c C-]") 'markdown-complete
)
5409 ;; Following and doing things
5410 (define-key map
(kbd "C-c C-o") 'markdown-follow-thing-at-point
)
5411 (define-key map
(kbd "C-c C-d") 'markdown-do
)
5412 (define-key map
(kbd "C-c '") 'markdown-edit-code-block
)
5414 (define-key map
(kbd "RET") 'markdown-enter-key
)
5415 (define-key map
(kbd "DEL") 'markdown-outdent-or-delete
)
5416 (define-key map
(kbd "C-c >") 'markdown-indent-region
)
5417 (define-key map
(kbd "C-c <") 'markdown-outdent-region
)
5418 ;; Visibility cycling
5419 (define-key map
(kbd "TAB") 'markdown-cycle
)
5420 ;; S-iso-lefttab and S-tab should both be mapped to `backtab' by
5421 ;; (local-)function-key-map.
5422 ;;(define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
5423 ;;(define-key map (kbd "<S-tab>") 'markdown-shifttab)
5424 (define-key map
(kbd "<backtab>") 'markdown-shifttab
)
5425 ;; Heading and list navigation
5426 (define-key map
(kbd "C-c C-n") 'markdown-outline-next
)
5427 (define-key map
(kbd "C-c C-p") 'markdown-outline-previous
)
5428 (define-key map
(kbd "C-c C-f") 'markdown-outline-next-same-level
)
5429 (define-key map
(kbd "C-c C-b") 'markdown-outline-previous-same-level
)
5430 (define-key map
(kbd "C-c C-u") 'markdown-outline-up
)
5431 ;; Buffer-wide commands
5432 (define-key map
(kbd "C-c C-c") markdown-mode-command-map
)
5433 ;; Subtree, list, and table editing
5434 (define-key map
(kbd "C-c <up>") 'markdown-move-up
)
5435 (define-key map
(kbd "C-c <down>") 'markdown-move-down
)
5436 (define-key map
(kbd "C-c <left>") 'markdown-promote
)
5437 (define-key map
(kbd "C-c <right>") 'markdown-demote
)
5438 (define-key map
(kbd "C-c S-<up>") 'markdown-table-delete-row
)
5439 (define-key map
(kbd "C-c S-<down>") 'markdown-table-insert-row
)
5440 (define-key map
(kbd "C-c S-<left>") 'markdown-table-delete-column
)
5441 (define-key map
(kbd "C-c S-<right>") 'markdown-table-insert-column
)
5442 (define-key map
(kbd "C-c C-M-h") 'markdown-mark-subtree
)
5443 (define-key map
(kbd "C-x n s") 'markdown-narrow-to-subtree
)
5444 (define-key map
(kbd "M-RET") 'markdown-insert-list-item
)
5445 (define-key map
(kbd "C-c C-j") 'markdown-insert-list-item
)
5446 ;; Paragraphs (Markdown context aware)
5447 (define-key map
[remap backward-paragraph
] 'markdown-backward-paragraph
)
5448 (define-key map
[remap forward-paragraph
] 'markdown-forward-paragraph
)
5449 (define-key map
[remap mark-paragraph
] 'markdown-mark-paragraph
)
5450 ;; Blocks (one or more paragraphs)
5451 (define-key map
(kbd "C-M-{") 'markdown-backward-block
)
5452 (define-key map
(kbd "C-M-}") 'markdown-forward-block
)
5453 (define-key map
(kbd "C-c M-h") 'markdown-mark-block
)
5454 (define-key map
(kbd "C-x n b") 'markdown-narrow-to-block
)
5455 ;; Pages (top-level sections)
5456 (define-key map
[remap backward-page
] 'markdown-backward-page
)
5457 (define-key map
[remap forward-page
] 'markdown-forward-page
)
5458 (define-key map
[remap mark-page
] 'markdown-mark-page
)
5459 (define-key map
[remap narrow-to-page
] 'markdown-narrow-to-page
)
5461 (define-key map
(kbd "M-n") 'markdown-next-link
)
5462 (define-key map
(kbd "M-p") 'markdown-previous-link
)
5463 ;; Toggling functionality
5464 (define-key map
(kbd "C-c C-x C-e") 'markdown-toggle-math
)
5465 (define-key map
(kbd "C-c C-x C-f") 'markdown-toggle-fontify-code-blocks-natively
)
5466 (define-key map
(kbd "C-c C-x C-i") 'markdown-toggle-inline-images
)
5467 (define-key map
(kbd "C-c C-x C-l") 'markdown-toggle-url-hiding
)
5468 (define-key map
(kbd "C-c C-x C-m") 'markdown-toggle-markup-hiding
)
5469 ;; Alternative keys (in case of problems with the arrow keys)
5470 (define-key map
(kbd "C-c C-x u") 'markdown-move-up
)
5471 (define-key map
(kbd "C-c C-x d") 'markdown-move-down
)
5472 (define-key map
(kbd "C-c C-x l") 'markdown-promote
)
5473 (define-key map
(kbd "C-c C-x r") 'markdown-demote
)
5474 ;; Deprecated keys that may be removed in a future version
5475 (define-key map
(kbd "C-c C-a L") 'markdown-insert-link
) ;; C-c C-l
5476 (define-key map
(kbd "C-c C-a l") 'markdown-insert-link
) ;; C-c C-l
5477 (define-key map
(kbd "C-c C-a r") 'markdown-insert-link
) ;; C-c C-l
5478 (define-key map
(kbd "C-c C-a u") 'markdown-insert-uri
) ;; C-c C-l
5479 (define-key map
(kbd "C-c C-a f") 'markdown-insert-footnote
)
5480 (define-key map
(kbd "C-c C-a w") 'markdown-insert-wiki-link
)
5481 (define-key map
(kbd "C-c C-t 1") 'markdown-insert-header-atx-1
)
5482 (define-key map
(kbd "C-c C-t 2") 'markdown-insert-header-atx-2
)
5483 (define-key map
(kbd "C-c C-t 3") 'markdown-insert-header-atx-3
)
5484 (define-key map
(kbd "C-c C-t 4") 'markdown-insert-header-atx-4
)
5485 (define-key map
(kbd "C-c C-t 5") 'markdown-insert-header-atx-5
)
5486 (define-key map
(kbd "C-c C-t 6") 'markdown-insert-header-atx-6
)
5487 (define-key map
(kbd "C-c C-t !") 'markdown-insert-header-setext-1
)
5488 (define-key map
(kbd "C-c C-t @") 'markdown-insert-header-setext-2
)
5489 (define-key map
(kbd "C-c C-t h") 'markdown-insert-header-dwim
)
5490 (define-key map
(kbd "C-c C-t H") 'markdown-insert-header-setext-dwim
)
5491 (define-key map
(kbd "C-c C-t s") 'markdown-insert-header-setext-2
)
5492 (define-key map
(kbd "C-c C-t t") 'markdown-insert-header-setext-1
)
5493 (define-key map
(kbd "C-c C-i") 'markdown-insert-image
)
5494 (define-key map
(kbd "C-c C-x m") 'markdown-insert-list-item
) ;; C-c C-j
5495 (define-key map
(kbd "C-c C-x C-x") 'markdown-toggle-gfm-checkbox
) ;; C-c C-d
5496 (define-key map
(kbd "C-c -") 'markdown-insert-hr
)
5498 "Keymap for Markdown major mode.")
5500 (defvar markdown-mode-mouse-map
5501 (when markdown-mouse-follow-link
5502 (let ((map (make-sparse-keymap)))
5503 (define-key map
[follow-link
] 'mouse-face
)
5504 (define-key map
[mouse-2
] #'markdown-follow-thing-at-point
)
5506 "Keymap for following links with mouse.")
5508 (defvar gfm-mode-map
5509 (let ((map (make-sparse-keymap)))
5510 (set-keymap-parent map markdown-mode-map
)
5511 (define-key map
(kbd "C-c C-s d") 'markdown-insert-strike-through
)
5512 (define-key map
"`" 'markdown-electric-backquote
)
5514 "Keymap for `gfm-mode'.
5515 See also `markdown-mode-map'.")
5518 ;;; Menu ======================================================================
5520 (easy-menu-define markdown-mode-menu markdown-mode-map
5521 "Menu for Markdown mode."
5525 ["Jump" markdown-do
]
5526 ["Follow Link" markdown-follow-thing-at-point
]
5527 ["Next Link" markdown-next-link
]
5528 ["Previous Link" markdown-previous-link
]
5530 ["Next Heading or List Item" markdown-outline-next
]
5531 ["Previous Heading or List Item" markdown-outline-previous
]
5532 ["Next at Same Level" markdown-outline-next-same-level
]
5533 ["Previous at Same Level" markdown-outline-previous-same-level
]
5534 ["Up to Parent" markdown-outline-up
]
5536 ["Forward Paragraph" markdown-forward-paragraph
]
5537 ["Backward Paragraph" markdown-backward-paragraph
]
5538 ["Forward Block" markdown-forward-block
]
5539 ["Backward Block" markdown-backward-block
])
5541 ["Cycle Heading Visibility" markdown-cycle
5542 :enable
(markdown-on-heading-p)]
5543 ["Cycle Heading Visibility (Global)" markdown-shifttab
]
5545 ["Narrow to Region" narrow-to-region
]
5546 ["Narrow to Block" markdown-narrow-to-block
]
5547 ["Narrow to Section" narrow-to-defun
]
5548 ["Narrow to Subtree" markdown-narrow-to-subtree
]
5549 ["Widen" widen
(buffer-narrowed-p)]
5551 ["Toggle Markup Hiding" markdown-toggle-markup-hiding
5554 :selected markdown-hide-markup
])
5556 ("Headings & Structure"
5557 ["Automatic Heading" markdown-insert-header-dwim
5559 ["Automatic Heading (Setext)" markdown-insert-header-setext-dwim
5561 ("Specific Heading (atx)"
5562 ["First Level atx" markdown-insert-header-atx-1
5564 ["Second Level atx" markdown-insert-header-atx-2
5566 ["Third Level atx" markdown-insert-header-atx-3
5568 ["Fourth Level atx" markdown-insert-header-atx-4
5570 ["Fifth Level atx" markdown-insert-header-atx-5
5572 ["Sixth Level atx" markdown-insert-header-atx-6
5574 ("Specific Heading (Setext)"
5575 ["First Level Setext" markdown-insert-header-setext-1
5577 ["Second Level Setext" markdown-insert-header-setext-2
5579 ["Horizontal Rule" markdown-insert-hr
5582 ["Move Subtree Up" markdown-move-up
5584 ["Move Subtree Down" markdown-move-down
5586 ["Promote Subtree" markdown-promote
5588 ["Demote Subtree" markdown-demote
5589 :keys
"C-c <right>"])
5591 ["Indent Region" markdown-indent-region
]
5592 ["Outdent Region" markdown-outdent-region
]
5594 ["Mark Paragraph" mark-paragraph
]
5595 ["Mark Block" markdown-mark-block
]
5596 ["Mark Section" mark-defun
]
5597 ["Mark Subtree" markdown-mark-subtree
])
5599 ["Move Row Up" markdown-move-up
5600 :enable
(markdown-table-at-point-p)
5602 ["Move Row Down" markdown-move-down
5603 :enable
(markdown-table-at-point-p)
5605 ["Move Column Left" markdown-promote
5606 :enable
(markdown-table-at-point-p)
5608 ["Move Column Right" markdown-demote
5609 :enable
(markdown-table-at-point-p)
5610 :keys
"C-c <right>"]
5611 ["Delete Row" markdown-table-delete-row
5612 :enable
(markdown-table-at-point-p)]
5613 ["Insert Row" markdown-table-insert-row
5614 :enable
(markdown-table-at-point-p)]
5615 ["Delete Column" markdown-table-delete-column
5616 :enable
(markdown-table-at-point-p)]
5617 ["Insert Column" markdown-table-insert-column
5618 :enable
(markdown-table-at-point-p)]
5619 ["Insert Table" markdown-insert-table
]
5621 ["Convert Region to Table" markdown-table-convert-region
]
5622 ["Sort Table Lines" markdown-table-sort-lines
5623 :enable
(markdown-table-at-point-p)]
5624 ["Transpose Table" markdown-table-transpose
5625 :enable
(markdown-table-at-point-p)])
5627 ["Insert List Item" markdown-insert-list-item
]
5628 ["Move Subtree Up" markdown-move-up
5630 ["Move Subtree Down" markdown-move-down
5632 ["Indent Subtree" markdown-demote
5633 :keys
"C-c <right>"]
5634 ["Outdent Subtree" markdown-promote
5636 ["Renumber List" markdown-cleanup-list-numbers
]
5637 ["Insert Task List Item" markdown-insert-gfm-checkbox
5639 ["Toggle Task List Item" markdown-toggle-gfm-checkbox
5640 :enable
(markdown-gfm-task-list-item-at-point)
5643 ["Insert Link" markdown-insert-link
]
5644 ["Insert Image" markdown-insert-image
]
5645 ["Insert Footnote" markdown-insert-footnote
5647 ["Insert Wiki Link" markdown-insert-wiki-link
5650 ["Check References" markdown-check-refs
]
5651 ["Find Unused References" markdown-unused-refs
]
5652 ["Toggle URL Hiding" markdown-toggle-url-hiding
5654 :selected markdown-hide-urls
]
5655 ["Toggle Inline Images" markdown-toggle-inline-images
5658 :selected markdown-inline-image-overlays
]
5659 ["Toggle Wiki Links" markdown-toggle-wiki-links
5661 :selected markdown-enable-wiki-links
])
5663 ["Bold" markdown-insert-bold
]
5664 ["Italic" markdown-insert-italic
]
5665 ["Code" markdown-insert-code
]
5666 ["Strikethrough" markdown-insert-strike-through
]
5667 ["Keyboard" markdown-insert-kbd
]
5669 ["Blockquote" markdown-insert-blockquote
]
5670 ["Preformatted" markdown-insert-pre
]
5671 ["GFM Code Block" markdown-insert-gfm-code-block
]
5672 ["Edit Code Block" markdown-edit-code-block
5673 :enable
(markdown-code-block-at-point-p)]
5674 ["Foldable Block" markdown-insert-foldable-block
]
5676 ["Blockquote Region" markdown-blockquote-region
]
5677 ["Preformatted Region" markdown-pre-region
]
5679 ["Fontify Code Blocks Natively"
5680 markdown-toggle-fontify-code-blocks-natively
5682 :selected markdown-fontify-code-blocks-natively
]
5683 ["LaTeX Math Support" markdown-toggle-math
5685 :selected markdown-enable-math
])
5688 ["Compile" markdown-other-window
]
5689 ["Preview" markdown-preview
]
5690 ["Export" markdown-export
]
5691 ["Export & View" markdown-export-and-preview
]
5692 ["Open" markdown-open
]
5693 ["Live Export" markdown-live-preview-mode
5695 :selected markdown-live-preview-mode
]
5696 ["Kill ring save" markdown-kill-ring-save
])
5697 ("Markup Completion and Cycling"
5698 ["Complete Markup" markdown-complete
]
5699 ["Promote Element" markdown-promote
5701 ["Demote Element" markdown-demote
5704 ["Kill Element" markdown-kill-thing-at-point
]
5707 ["Version" markdown-show-version
]
5708 ["Homepage" markdown-mode-info
]
5709 ["Describe Mode" (describe-function 'markdown-mode
)]
5710 ["Guide" (browse-url "https://leanpub.com/markdown-mode")])))
5713 ;;; imenu =====================================================================
5715 (defun markdown-imenu-create-nested-index ()
5716 "Create and return a nested imenu index alist for the current buffer.
5717 See `imenu-create-index-function' and `imenu--index-alist' for details."
5718 (let* ((root '(nil . nil
))
5723 (goto-char (point-min))
5724 (while (re-search-forward markdown-regex-header
(point-max) t
)
5725 (unless (or (markdown-code-block-at-point-p)
5726 (and (match-beginning 3)
5727 (get-text-property (match-beginning 3) 'markdown-yaml-metadata-end
)))
5729 ((match-string-no-properties 2) ;; level 1 setext
5731 (push (list :heading
(match-string-no-properties 1)
5732 :point
(match-beginning 1)
5734 ((match-string-no-properties 3) ;; level 2 setext
5735 (setq min-level
(min min-level
2))
5736 (push (list :heading
(match-string-no-properties 1)
5737 :point
(match-beginning 1)
5738 :level
(- 2 (1- min-level
))) headers
))
5739 ((setq hashes
(markdown-trim-whitespace
5740 (match-string-no-properties 4)))
5741 (setq min-level
(min min-level
(length hashes
)))
5742 (push (list :heading
(match-string-no-properties 5)
5743 :point
(match-beginning 4)
5744 :level
(- (length hashes
) (1- min-level
))) headers
)))))
5745 (cl-loop with cur-level
= 0
5746 with cur-alist
= nil
5747 with empty-heading
= "-"
5748 with self-heading
= "."
5749 for header in
(reverse headers
)
5750 for level
= (plist-get header
:level
)
5752 (let ((alist (list (cons (plist-get header
:heading
) (plist-get header
:point
)))))
5754 ((= cur-level level
) ; new sibling
5755 (setcdr cur-alist alist
)
5756 (setq cur-alist alist
))
5757 ((< cur-level level
) ; first child
5758 (dotimes (_ (- level cur-level
1))
5759 (setq alist
(list (cons empty-heading alist
))))
5761 (let* ((parent (car cur-alist
))
5762 (self-pos (cdr parent
)))
5763 (setcdr parent
(cons (cons self-heading self-pos
) alist
)))
5764 (setcdr root alist
)) ; primogenitor
5765 (setq cur-alist alist
)
5766 (setq cur-level level
))
5767 (t ; new sibling of an ancestor
5768 (let ((sibling-alist (last (cdr root
))))
5769 (dotimes (_ (1- level
))
5770 (setq sibling-alist
(last (cdar sibling-alist
))))
5771 (setcdr sibling-alist alist
)
5772 (setq cur-alist alist
))
5773 (setq cur-level level
)))))
5774 (setq root
(copy-tree root
))
5776 (let ((fn (markdown-get-defined-footnotes)))
5777 (if (or (zerop (length fn
))
5778 (null markdown-add-footnotes-to-imenu
))
5780 (nconc (cdr root
) (list (cons "Footnotes" fn
))))))))
5782 (defun markdown-imenu-create-flat-index ()
5783 "Create and return a flat imenu index alist for the current buffer.
5784 See `imenu-create-index-function' and `imenu--index-alist' for details."
5785 (let* ((empty-heading "-") index heading pos
)
5788 (goto-char (point-min))
5789 (while (re-search-forward markdown-regex-header
(point-max) t
)
5790 (when (and (not (markdown-code-block-at-point-p (line-beginning-position)))
5791 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin
)))
5793 ((setq heading
(match-string-no-properties 1))
5794 (setq pos
(match-beginning 1)))
5795 ((setq heading
(match-string-no-properties 5))
5796 (setq pos
(match-beginning 4))))
5797 (or (> (length heading
) 0)
5798 (setq heading empty-heading
))
5799 (setq index
(append index
(list (cons heading pos
))))))
5801 (when markdown-add-footnotes-to-imenu
5802 (nconc index
(markdown-get-defined-footnotes)))
5806 ;;; References ================================================================
5808 (defun markdown-reference-goto-definition ()
5809 "Jump to the definition of the reference at point or create it."
5811 (when (thing-at-point-looking-at markdown-regex-link-reference
)
5812 (let* ((text (match-string-no-properties 3))
5813 (reference (match-string-no-properties 6))
5814 (target (downcase (if (string= reference
"") text reference
)))
5815 (loc (cadr (save-match-data (markdown-reference-definition target
)))))
5818 (goto-char (match-beginning 0))
5819 (markdown-insert-reference-definition target
)))))
5821 (defun markdown-reference-find-links (reference)
5822 "Return a list of all links for REFERENCE.
5823 REFERENCE should not include the surrounding square brackets.
5824 Elements of the list have the form (text start line), where
5825 text is the link text, start is the location at the beginning of
5826 the link, and line is the line number on which the link appears."
5827 (let* ((ref-quote (regexp-quote reference
))
5828 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
5829 ref-quote ref-quote
))
5832 (goto-char (point-min))
5833 (while (re-search-forward regexp nil t
)
5834 (let* ((text (or (match-string-no-properties 1)
5835 (match-string-no-properties 2)))
5836 (start (match-beginning 0))
5837 (line (markdown-line-number-at-pos)))
5838 (cl-pushnew (list text start line
) links
:test
#'equal
))))
5841 (defmacro markdown-for-all-refs
(f)
5844 (goto-char (point-min))
5846 (re-search-forward markdown-regex-link-reference nil t
)
5847 (let* ((text (match-string-no-properties 3))
5848 (reference (match-string-no-properties 6))
5849 (target (downcase (if (string= reference
"") text reference
))))
5850 (,f text target result
))))
5853 (defmacro markdown-collect-always
(_ target result
)
5854 `(cl-pushnew ,target
,result
:test
#'equal
))
5856 (defmacro markdown-collect-undefined
(text target result
)
5857 `(unless (markdown-reference-definition target
)
5858 (let ((entry (assoc ,target
,result
)))
5861 (cons ,target
(list (cons ,text
(markdown-line-number-at-pos))))
5862 ,result
:test
#'equal
)
5864 (append (cdr entry
) (list (cons ,text
(markdown-line-number-at-pos)))))))))
5866 (defun markdown-get-all-refs ()
5867 "Return a list of all Markdown references."
5868 (markdown-for-all-refs markdown-collect-always
))
5870 (defun markdown-get-undefined-refs ()
5871 "Return a list of undefined Markdown references.
5872 Result is an alist of pairs (reference . occurrences), where
5873 occurrences is itself another alist of pairs (label . line-number).
5874 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
5875 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
5876 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
5877 (markdown-for-all-refs markdown-collect-undefined
))
5879 (defun markdown-get-unused-refs ()
5882 (markdown-get-defined-references) (markdown-get-all-refs)
5883 :test
(lambda (e1 e2
) (equal (car e1
) e2
)))
5886 (defmacro defun-markdown-buffer
(name docstring
)
5887 "Define a function to name and return a buffer.
5889 By convention, NAME must be a name of a string constant with
5890 %buffer% placeholder used to name the buffer, and will also be
5891 used as a name of the function defined.
5893 DOCSTRING will be used as the first part of the docstring."
5894 `(defun ,name
(&optional buffer-name
)
5895 ,(concat docstring
"\n\nBUFFER-NAME is the name of the main buffer being visited.")
5896 (or buffer-name
(setq buffer-name
(buffer-name)))
5897 (let ((refbuf (get-buffer-create (replace-regexp-in-string
5898 "%buffer%" buffer-name
5900 (with-current-buffer refbuf
5902 (View-exit-and-edit))
5903 (use-local-map button-buffer-map
)
5907 (defconst markdown-reference-check-buffer
5908 "*Undefined references for %buffer%*"
5909 "Pattern for name of buffer for listing undefined references.
5910 The string %buffer% will be replaced by the corresponding
5911 `markdown-mode' buffer name.")
5913 (defun-markdown-buffer
5914 markdown-reference-check-buffer
5915 "Name and return buffer for reference checking.")
5917 (defconst markdown-unused-references-buffer
5918 "*Unused references for %buffer%*"
5919 "Pattern for name of buffer for listing unused references.
5920 The string %buffer% will be replaced by the corresponding
5921 `markdown-mode' buffer name.")
5923 (defun-markdown-buffer
5924 markdown-unused-references-buffer
5925 "Name and return buffer for unused reference checking.")
5927 (defconst markdown-reference-links-buffer
5928 "*Reference links for %buffer%*"
5929 "Pattern for name of buffer for listing references.
5930 The string %buffer% will be replaced by the corresponding buffer name.")
5932 (defun-markdown-buffer
5933 markdown-reference-links-buffer
5934 "Name, setup, and return a buffer for listing links.")
5936 ;; Add an empty Markdown reference definition to buffer
5937 ;; specified in the 'target-buffer property. The reference name is
5938 ;; the button's label.
5939 (define-button-type 'markdown-undefined-reference-button
5940 'help-echo
"mouse-1, RET: create definition for undefined reference"
5944 (let ((buffer (button-get b
'target-buffer
))
5945 (line (button-get b
'target-line
))
5946 (label (button-label b
)))
5947 (switch-to-buffer-other-window buffer
)
5948 (goto-char (point-min))
5950 (markdown-insert-reference-definition label
)
5951 (markdown-check-refs t
))))
5953 ;; Jump to line in buffer specified by 'target-buffer property.
5954 ;; Line number is button's 'target-line property.
5955 (define-button-type 'markdown-goto-line-button
5956 'help-echo
"mouse-1, RET: go to line"
5960 (switch-to-buffer-other-window (button-get b
'target-buffer
))
5961 ;; use call-interactively to silence compiler
5962 (let ((current-prefix-arg (button-get b
'target-line
)))
5963 (call-interactively 'goto-line
))))
5965 ;; Kill a line in buffer specified by 'target-buffer property.
5966 ;; Line number is button's 'target-line property.
5967 (define-button-type 'markdown-kill-line-button
5968 'help-echo
"mouse-1, RET: kill line"
5972 (switch-to-buffer-other-window (button-get b
'target-buffer
))
5973 ;; use call-interactively to silence compiler
5974 (let ((current-prefix-arg (button-get b
'target-line
)))
5975 (call-interactively 'goto-line
))
5977 (markdown-unused-refs t
)))
5979 ;; Jumps to a particular link at location given by 'target-char
5980 ;; property in buffer given by 'target-buffer property.
5981 (define-button-type 'markdown-location-button
5982 'help-echo
"mouse-1, RET: jump to location of link"
5986 (let ((target (button-get b
'target-buffer
))
5987 (loc (button-get b
'target-char
)))
5988 (kill-buffer-and-window)
5989 (switch-to-buffer target
)
5992 (defun markdown-insert-undefined-reference-button (reference oldbuf
)
5993 "Insert a button for creating REFERENCE in buffer OLDBUF.
5994 REFERENCE should be a list of the form (reference . occurrences),
5995 as returned by `markdown-get-undefined-refs'."
5996 (let ((label (car reference
)))
5997 ;; Create a reference button
5998 (insert-button label
5999 :type
'markdown-undefined-reference-button
6000 'target-buffer oldbuf
6001 'target-line
(cdr (car (cdr reference
))))
6003 (dolist (occurrence (cdr reference
))
6004 (let ((line (cdr occurrence
)))
6005 ;; Create a line number button
6006 (insert-button (number-to-string line
)
6007 :type
'markdown-goto-line-button
6008 'target-buffer oldbuf
6015 (defun markdown-insert-unused-reference-button (reference oldbuf
)
6016 "Insert a button for creating REFERENCE in buffer OLDBUF.
6017 REFERENCE must be a pair of (ref . line-number)."
6018 (let ((label (car reference
))
6019 (line (cdr reference
)))
6020 ;; Create a reference button
6021 (insert-button label
6022 :type
'markdown-goto-line-button
6024 'target-buffer oldbuf
6026 (insert (format " (%d) [" line
))
6028 :type
'markdown-kill-line-button
6030 'target-buffer oldbuf
6035 (defun markdown-insert-link-button (link oldbuf
)
6036 "Insert a button for jumping to LINK in buffer OLDBUF.
6037 LINK should be a list of the form (text char line) containing
6038 the link text, location, and line number."
6039 (let ((label (cl-first link
))
6040 (char (cl-second link
))
6041 (line (cl-third link
)))
6042 ;; Create a reference button
6043 (insert-button label
6044 :type
'markdown-location-button
6045 'target-buffer oldbuf
6047 (insert (format " (line %d)\n" line
))))
6049 (defun markdown-reference-goto-link (&optional reference
)
6050 "Jump to the location of the first use of REFERENCE."
6053 (if (thing-at-point-looking-at markdown-regex-reference-definition
)
6054 (setq reference
(match-string-no-properties 2))
6055 (user-error "No reference definition at point")))
6056 (let ((links (markdown-reference-find-links reference
)))
6057 (cond ((= (length links
) 1)
6058 (goto-char (cadr (car links
))))
6059 ((> (length links
) 1)
6060 (let ((oldbuf (current-buffer))
6061 (linkbuf (markdown-reference-links-buffer)))
6062 (with-current-buffer linkbuf
6063 (insert "Links using reference " reference
":\n\n")
6064 (dolist (link (reverse links
))
6065 (markdown-insert-link-button link oldbuf
)))
6066 (view-buffer-other-window linkbuf
)
6067 (goto-char (point-min))
6070 (error "No links for reference %s" reference
)))))
6072 (defmacro defun-markdown-ref-checker
6073 (name docstring checker-function buffer-function none-message buffer-header insert-reference
)
6074 "Define a function NAME acting on result of CHECKER-FUNCTION.
6076 DOCSTRING is used as a docstring for the defined function.
6078 BUFFER-FUNCTION should name and return an auxiliary buffer to put
6081 NONE-MESSAGE is used when CHECKER-FUNCTION returns no results.
6083 BUFFER-HEADER is put into the auxiliary buffer first, followed by
6084 calling INSERT-REFERENCE for each element in the list returned by
6086 `(defun ,name
(&optional silent
)
6089 "\n\nIf SILENT is non-nil, do not message anything when no
6090 such references found.")
6092 (unless (derived-mode-p 'markdown-mode
)
6093 (user-error "Not available in current mode"))
6094 (let ((oldbuf (current-buffer))
6095 (refs (,checker-function
))
6096 (refbuf (,buffer-function
)))
6100 (message ,none-message
))
6101 (kill-buffer refbuf
))
6102 (with-current-buffer refbuf
6103 (insert ,buffer-header
)
6105 (,insert-reference ref oldbuf
))
6106 (view-buffer-other-window refbuf
)
6107 (goto-char (point-min))
6108 (forward-line 2))))))
6110 (defun-markdown-ref-checker
6112 "Show all undefined Markdown references in current `markdown-mode' buffer.
6114 Links which have empty reference definitions are considered to be
6116 markdown-get-undefined-refs
6117 markdown-reference-check-buffer
6118 "No undefined references found"
6119 "The following references are undefined:\n\n"
6120 markdown-insert-undefined-reference-button
)
6123 (defun-markdown-ref-checker
6124 markdown-unused-refs
6125 "Show all unused Markdown references in current `markdown-mode' buffer."
6126 markdown-get-unused-refs
6127 markdown-unused-references-buffer
6128 "No unused references found"
6129 "The following references are unused:\n\n"
6130 markdown-insert-unused-reference-button
)
6134 ;;; Lists =====================================================================
6136 (defun markdown-insert-list-item (&optional arg
)
6137 "Insert a new list item.
6138 If the point is inside unordered list, insert a bullet mark. If
6139 the point is inside ordered list, insert the next number followed
6140 by a period. Use the previous list item to determine the amount
6141 of whitespace to place before and after list markers.
6143 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
6144 decrease the indentation by one level.
6146 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
6147 increase the indentation by one level."
6149 (let (bounds cur-indent marker indent new-indent new-loc
)
6151 ;; Look for a list item on current or previous non-blank line
6153 (while (and (not (setq bounds
(markdown-cur-list-item-bounds)))
6155 (markdown-cur-line-blank-p))
6158 (cond ((save-excursion
6159 (skip-chars-backward " \t")
6160 (looking-at-p markdown-regex-list
))
6164 ((not (markdown-cur-line-blank-p))
6166 (setq new-loc
(point)))
6167 ;; Look ahead for a list item on next non-blank line
6170 (while (and (null bounds
)
6172 (markdown-cur-line-blank-p))
6174 (setq bounds
(markdown-cur-list-item-bounds))))
6176 (setq new-loc
(point))
6177 (unless (markdown-cur-line-blank-p)
6180 ;; When not in a list, start a new unordered one
6182 (unless (markdown-cur-line-blank-p)
6184 (insert markdown-unordered-list-item-prefix
))
6185 ;; Compute indentation and marker for new list item
6186 (setq cur-indent
(nth 2 bounds
))
6187 (setq marker
(nth 4 bounds
))
6188 ;; If current item is a GFM checkbox, insert new unchecked checkbox.
6189 (when (nth 5 bounds
)
6192 (replace-regexp-in-string "[Xx]" " " (nth 5 bounds
)))))
6194 ;; Dedent: decrement indentation, find previous marker.
6196 (setq indent
(max (- cur-indent markdown-list-indent-width
) 0))
6199 (goto-char (nth 0 bounds
))
6200 (when (markdown-up-list)
6201 (markdown-cur-list-item-bounds)))))
6203 (setq marker
(nth 4 prev-bounds
)))))
6204 ;; Indent: increment indentation by 4, use same marker.
6205 ((= arg
16) (setq indent
(+ cur-indent markdown-list-indent-width
)))
6206 ;; Same level: keep current indentation and marker.
6207 (t (setq indent cur-indent
)))
6208 (setq new-indent
(make-string indent
32))
6212 ((string-match-p "[0-9]" marker
)
6213 (if (= arg
16) ;; starting a new column indented one more level
6214 (insert (concat new-indent
"1. "))
6215 ;; Don't use previous match-data
6216 (set-match-data nil
)
6217 ;; travel up to the last item and pick the correct number. If
6218 ;; the argument was nil, "new-indent = cur-indent" is the same,
6219 ;; so we don't need special treatment. Neat.
6221 (while (and (not (looking-at (concat new-indent
"\\([0-9]+\\)\\(\\.[ \t]*\\)")))
6222 (>= (forward-line -
1) 0))))
6223 (let* ((old-prefix (match-string 1))
6224 (old-spacing (match-string 2))
6225 (new-prefix (if (and old-prefix markdown-ordered-list-enumeration
)
6226 (int-to-string (1+ (string-to-number old-prefix
)))
6228 (space-adjust (- (length old-prefix
) (length new-prefix
)))
6229 (new-spacing (if (and (match-string 2)
6230 (not (string-match-p "\t" old-spacing
))
6232 (> space-adjust
(- 1 (length (match-string 2)))))
6233 (substring (match-string 2) 0 space-adjust
)
6234 (or old-spacing
". "))))
6235 (insert (concat new-indent new-prefix new-spacing
)))))
6236 ;; Unordered list, GFM task list, or ordered list with hash mark
6237 ((string-match-p "[\\*\\+-]\\|#\\." marker
)
6238 (insert new-indent marker
))))
6239 ;; Propertize the newly inserted list item now
6240 (markdown-syntax-propertize-list-items (line-beginning-position) (line-end-position)))))
6242 (defun markdown-move-list-item-up ()
6243 "Move the current list item up in the list when possible.
6244 In nested lists, move child items with the parent item."
6247 (when (setq cur
(markdown-cur-list-item-bounds))
6249 (goto-char (nth 0 cur
))
6250 (if (markdown-prev-list-item (nth 3 cur
))
6252 (setq prev
(markdown-cur-list-item-bounds))
6255 (transpose-regions (nth 0 prev
) (nth 1 prev
)
6256 (nth 0 cur
) (nth 1 cur
) t
)
6257 (goto-char (+ (nth 0 prev
) (- old
(nth 0 cur
)))))
6258 ;; Catch error in case regions overlap.
6259 (error (goto-char old
))))
6262 (defun markdown-move-list-item-down ()
6263 "Move the current list item down in the list when possible.
6264 In nested lists, move child items with the parent item."
6267 (when (setq cur
(markdown-cur-list-item-bounds))
6269 (if (markdown-next-list-item (nth 3 cur
))
6271 (setq next
(markdown-cur-list-item-bounds))
6274 (transpose-regions (nth 0 cur
) (nth 1 cur
)
6275 (nth 0 next
) (nth 1 next
) nil
)
6276 (goto-char (+ old
(- (nth 1 next
) (nth 1 cur
)))))
6277 ;; Catch error in case regions overlap.
6278 (error (goto-char old
))))
6281 (defun markdown-demote-list-item (&optional bounds
)
6282 "Indent (or demote) the current list item.
6283 Optionally, BOUNDS of the current list item may be provided if available.
6284 In nested lists, demote child items as well."
6286 (when (or bounds
(setq bounds
(markdown-cur-list-item-bounds)))
6288 (let* ((item-start (set-marker (make-marker) (nth 0 bounds
)))
6289 (item-end (set-marker (make-marker) (nth 1 bounds
)))
6290 (list-start (progn (markdown-beginning-of-list)
6291 (set-marker (make-marker) (point))))
6292 (list-end (progn (markdown-end-of-list)
6293 (set-marker (make-marker) (point)))))
6294 (goto-char item-start
)
6295 (while (< (point) item-end
)
6296 (unless (markdown-cur-line-blank-p)
6297 (insert (make-string markdown-list-indent-width ?
)))
6299 (markdown-syntax-propertize-list-items list-start list-end
)))))
6301 (defun markdown-promote-list-item (&optional bounds
)
6302 "Unindent (or promote) the current list item.
6303 Optionally, BOUNDS of the current list item may be provided if available.
6304 In nested lists, demote child items as well."
6306 (when (or bounds
(setq bounds
(markdown-cur-list-item-bounds)))
6309 (let ((item-start (set-marker (make-marker) (nth 0 bounds
)))
6310 (item-end (set-marker (make-marker) (nth 1 bounds
)))
6311 (list-start (progn (markdown-beginning-of-list)
6312 (set-marker (make-marker) (point))))
6313 (list-end (progn (markdown-end-of-list)
6314 (set-marker (make-marker) (point))))
6316 (goto-char item-start
)
6317 (when (looking-at (format "^[ ]\\{1,%d\\}"
6318 markdown-list-indent-width
))
6319 (setq num
(- (match-end 0) (match-beginning 0)))
6320 (setq regexp
(format "^[ ]\\{1,%d\\}" num
))
6321 (while (and (< (point) item-end
)
6322 (re-search-forward regexp item-end t
))
6323 (replace-match "" nil nil
)
6325 (markdown-syntax-propertize-list-items list-start list-end
)))))))
6327 (defun markdown-cleanup-list-numbers-level (&optional pfx prev-item
)
6328 "Update the numbering for level PFX (as a string of spaces) and PREV-ITEM.
6329 PREV-ITEM is width of previous-indentation and list number
6331 Assume that the previously found match was for a numbered item in
6339 (while (and continue
(not (eobp)))
6342 ((looking-at "^\\(\\([\s-]*\\)[0-9]+\\)\\. ")
6343 (setq cpfx
(match-string-no-properties 2))
6344 (setq cur-item
(match-string-no-properties 1)) ;; indentation and list marker
6346 ((or (= (length cpfx
) (length pfx
))
6347 (= (length cur-item
) (length prev-item
)))
6350 (if (not markdown-ordered-list-enumeration
)
6353 (concat pfx
(number-to-string idx
) ". "))))
6356 ((< (length pfx
) (length cpfx
))
6357 (setq sep
(markdown-cleanup-list-numbers-level cpfx cur-item
))
6362 (setq continue nil
))))
6364 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
6365 (setq cpfx
(match-string-no-properties 1))
6367 ;; reset if separated before
6368 ((string= cpfx pfx
) (when sep
(setq idx
0)))
6371 (setq continue nil
))))
6376 (setq continue
(= (forward-line) 0))))
6379 (defun markdown-cleanup-list-numbers ()
6380 "Update the numbering of ordered lists."
6383 (goto-char (point-min))
6384 (markdown-cleanup-list-numbers-level "")))
6387 ;;; Movement ==================================================================
6389 (defun markdown-beginning-of-defun (&optional arg
)
6390 "`beginning-of-defun-function' for Markdown.
6391 This is used to find the beginning of the defun and should behave
6392 like ‘beginning-of-defun’, returning non-nil if it found the
6393 beginning of a defun. It moves the point backward, right before a
6394 heading which defines a defun. When ARG is non-nil, repeat that
6395 many times. When ARG is negative, move forward to the ARG-th
6397 (or arg
(setq arg
1))
6398 (when (< arg
0) (end-of-line))
6399 ;; Adjust position for setext headings.
6400 (when (and (thing-at-point-looking-at markdown-regex-header-setext
)
6401 (not (= (point) (match-beginning 0)))
6402 (not (markdown-code-block-at-point-p)))
6403 (goto-char (match-end 0)))
6405 ;; Move backward with positive argument.
6406 (while (and (not (bobp)) (> arg
0))
6408 (while (and (not found
)
6410 (re-search-backward markdown-regex-header nil
'move
))
6411 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6412 (setq found
(match-beginning 0)))
6413 (setq arg
(1- arg
)))
6414 ;; Move forward with negative argument.
6415 (while (and (not (eobp)) (< arg
0))
6417 (while (and (not found
)
6419 (re-search-forward markdown-regex-header nil
'move
))
6420 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6421 (setq found
(match-beginning 0)))
6422 (setq arg
(1+ arg
)))
6427 (defun markdown-end-of-defun ()
6428 "`end-of-defun-function’ for Markdown.
6429 This is used to find the end of the defun at point.
6430 It is called with no argument, right after calling ‘beginning-of-defun-raw’,
6431 so it can assume that point is at the beginning of the defun body.
6432 It should move point to the first position after the defun."
6433 (or (eobp) (forward-char 1))
6435 (while (and (not found
)
6437 (re-search-forward markdown-regex-header nil
'move
))
6438 (when (not (markdown-code-block-at-pos (match-beginning 0)))
6439 (setq found
(match-beginning 0))))
6442 (skip-syntax-backward "-"))))
6444 (defun markdown-beginning-of-text-block ()
6445 "Move backward to previous beginning of a plain text block.
6446 This function simply looks for blank lines without considering
6447 the surrounding context in light of Markdown syntax. For that, see
6448 `markdown-backward-block'."
6450 (let ((start (point)))
6451 (if (re-search-backward markdown-regex-block-separator nil t
)
6452 (goto-char (match-end 0))
6453 (goto-char (point-min)))
6454 (when (and (= start
(point)) (not (bobp)))
6456 (if (re-search-backward markdown-regex-block-separator nil t
)
6457 (goto-char (match-end 0))
6458 (goto-char (point-min))))))
6460 (defun markdown-end-of-text-block ()
6461 "Move forward to next beginning of a plain text block.
6462 This function simply looks for blank lines without considering
6463 the surrounding context in light of Markdown syntax. For that, see
6464 `markdown-forward-block'."
6467 (skip-chars-forward " \t\n")
6468 (when (= (point) (point-min))
6470 (if (re-search-forward markdown-regex-block-separator nil t
)
6471 (goto-char (match-end 0))
6472 (goto-char (point-max)))
6473 (skip-chars-backward " \t\n")
6476 (defun markdown-backward-paragraph (&optional arg
)
6477 "Move the point to the start of the current paragraph.
6478 With argument ARG, do it ARG times; a negative argument ARG = -N
6479 means move forward N blocks."
6481 (or arg
(setq arg
1))
6483 (markdown-forward-paragraph (- arg
))
6485 ;; Skip over whitespace in between paragraphs when moving backward.
6486 (skip-chars-backward " \t\n")
6488 ;; Skip over code block endings.
6489 (when (markdown-range-properties-exist
6490 (line-beginning-position) (line-end-position)
6491 '(markdown-gfm-block-end
6492 markdown-tilde-fence-end
))
6494 ;; Skip over blank lines inside blockquotes.
6495 (while (and (not (eobp))
6496 (looking-at markdown-regex-blockquote
)
6497 (= (length (match-string 3)) 0))
6499 ;; Proceed forward based on the type of block of paragraph.
6503 ((looking-at markdown-regex-blockquote
)
6504 (while (and (not (bobp))
6505 (looking-at markdown-regex-blockquote
)
6506 (> (length (match-string 3)) 0)) ;; not blank
6510 ((setq bounds
(markdown-cur-list-item-bounds))
6511 (goto-char (nth 0 bounds
)))
6514 (while (and (not (bobp))
6516 (not (markdown-cur-line-blank-p))
6517 (not (looking-at markdown-regex-blockquote
))
6518 (not (markdown-range-properties-exist
6519 (line-beginning-position) (line-end-position)
6520 '(markdown-gfm-block-end
6521 markdown-tilde-fence-end
))))
6522 (setq skip
(markdown-range-properties-exist
6523 (line-beginning-position) (line-end-position)
6524 '(markdown-gfm-block-begin
6525 markdown-tilde-fence-begin
)))
6528 (forward-line 1))))))))
6530 (defun markdown-forward-paragraph (&optional arg
)
6531 "Move forward to the next end of a paragraph.
6532 With argument ARG, do it ARG times; a negative argument ARG = -N
6533 means move backward N blocks."
6535 (or arg
(setq arg
1))
6537 (markdown-backward-paragraph (- arg
))
6539 ;; Skip whitespace in between paragraphs.
6540 (when (markdown-cur-line-blank-p)
6541 (skip-syntax-forward "-")
6542 (beginning-of-line))
6543 ;; Proceed forward based on the type of block.
6547 ((looking-at markdown-regex-blockquote
)
6548 ;; Skip over blank lines inside blockquotes.
6549 (while (and (not (eobp))
6550 (looking-at markdown-regex-blockquote
)
6551 (= (length (match-string 3)) 0))
6553 ;; Move to end of quoted text block
6554 (while (and (not (eobp))
6555 (looking-at markdown-regex-blockquote
)
6556 (> (length (match-string 3)) 0)) ;; not blank
6559 ((and (markdown-cur-list-item-bounds)
6560 (setq bounds
(markdown-next-list-item-bounds)))
6561 (goto-char (nth 0 bounds
)))
6565 (while (and (not (eobp))
6567 (not (markdown-cur-line-blank-p))
6568 (not (looking-at markdown-regex-blockquote
))
6569 (not (markdown-range-properties-exist
6570 (line-beginning-position) (line-end-position)
6571 '(markdown-gfm-block-begin
6572 markdown-tilde-fence-begin
))))
6573 (setq skip
(markdown-range-properties-exist
6574 (line-beginning-position) (line-end-position)
6575 '(markdown-gfm-block-end
6576 markdown-tilde-fence-end
)))
6577 (forward-line))))))))
6579 (defun markdown-backward-block (&optional arg
)
6580 "Move the point to the start of the current Markdown block.
6581 Moves across complete code blocks, list items, and blockquotes,
6582 but otherwise stops at blank lines, headers, and horizontal
6583 rules. With argument ARG, do it ARG times; a negative argument
6584 ARG = -N means move forward N blocks."
6586 (or arg
(setq arg
1))
6588 (markdown-forward-block (- arg
))
6590 ;; Skip over whitespace in between blocks when moving backward,
6591 ;; unless at a block boundary with no whitespace.
6592 (skip-syntax-backward "-")
6594 ;; Proceed forward based on the type of block.
6597 ((and (markdown-code-block-at-pos (point)) ;; this line
6598 (markdown-code-block-at-pos (line-beginning-position 0))) ;; previous line
6600 (while (and (markdown-code-block-at-point-p) (not (bobp)))
6604 ((markdown-heading-at-point)
6605 (goto-char (match-beginning 0)))
6607 ((looking-at markdown-regex-hr
))
6609 ((looking-at markdown-regex-blockquote
)
6611 (while (and (looking-at markdown-regex-blockquote
)
6616 ((markdown-cur-list-item-bounds)
6617 (markdown-beginning-of-list))
6620 ;; Move forward in case it is a one line regular paragraph.
6621 (unless (markdown-next-line-blank-p)
6623 (unless (markdown-prev-line-blank-p)
6624 (markdown-backward-paragraph)))))))
6626 (defun markdown-forward-block (&optional arg
)
6627 "Move forward to the next end of a Markdown block.
6628 Moves across complete code blocks, list items, and blockquotes,
6629 but otherwise stops at blank lines, headers, and horizontal
6630 rules. With argument ARG, do it ARG times; a negative argument
6631 ARG = -N means move backward N blocks."
6633 (or arg
(setq arg
1))
6635 (markdown-backward-block (- arg
))
6637 ;; Skip over whitespace in between blocks when moving forward.
6638 (if (markdown-cur-line-blank-p)
6639 (skip-syntax-forward "-")
6640 (beginning-of-line))
6641 ;; Proceed forward based on the type of block.
6644 ((markdown-code-block-at-point-p)
6646 (while (and (markdown-code-block-at-point-p) (not (eobp)))
6649 ((looking-at markdown-regex-header
)
6650 (goto-char (or (match-end 4) (match-end 2) (match-end 3)))
6653 ((looking-at markdown-regex-hr
)
6656 ((looking-at markdown-regex-blockquote
)
6658 (while (and (looking-at markdown-regex-blockquote
) (not (eobp)))
6661 ((markdown-cur-list-item-bounds)
6662 (markdown-end-of-list)
6665 (t (markdown-forward-paragraph))))
6666 (skip-syntax-backward "-")
6670 (defun markdown-backward-page (&optional count
)
6671 "Move backward to boundary of the current toplevel section.
6672 With COUNT, repeat, or go forward if negative."
6674 (or count
(setq count
1))
6676 (markdown-forward-page (- count
))
6677 (skip-syntax-backward "-")
6678 (or (markdown-back-to-heading-over-code-block t t
)
6679 (goto-char (point-min)))
6680 (when (looking-at markdown-regex-header
)
6681 (let ((level (markdown-outline-level)))
6682 (when (> level
1) (markdown-up-heading level
))
6685 (markdown-backward-same-level (1- count
))
6686 (error (goto-char (point-min)))))))))
6688 (defun markdown-forward-page (&optional count
)
6689 "Move forward to boundary of the current toplevel section.
6690 With COUNT, repeat, or go backward if negative."
6692 (or count
(setq count
1))
6694 (markdown-backward-page (- count
))
6695 (if (markdown-back-to-heading-over-code-block t t
)
6696 (let ((level (markdown-outline-level)))
6697 (when (> level
1) (markdown-up-heading level
))
6699 (markdown-forward-same-level count
)
6700 (error (goto-char (point-max)))))
6701 (markdown-next-visible-heading 1))))
6703 (defun markdown-next-link ()
6704 "Jump to next inline, reference, or wiki link.
6705 If successful, return point. Otherwise, return nil.
6706 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
6708 (let ((opoint (point)))
6709 (when (or (markdown-link-p) (markdown-wiki-link-p))
6710 ;; At a link already, move past it.
6711 (goto-char (+ (match-end 0) 1)))
6712 ;; Search for the next wiki link and move to the beginning.
6713 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t
)
6714 (markdown-code-block-at-point-p)
6715 (< (point) (point-max))))
6716 (if (and (not (eq (point) opoint
))
6717 (or (markdown-link-p) (markdown-wiki-link-p)))
6718 ;; Group 1 will move past non-escape character in wiki link regexp.
6719 ;; Go to beginning of group zero for all other link types.
6720 (goto-char (or (match-beginning 1) (match-beginning 0)))
6724 (defun markdown-previous-link ()
6725 "Jump to previous wiki link.
6726 If successful, return point. Otherwise, return nil.
6727 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
6729 (let ((opoint (point)))
6730 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t
)
6731 (markdown-code-block-at-point-p)
6732 (> (point) (point-min))))
6733 (if (and (not (eq (point) opoint
))
6734 (or (markdown-link-p) (markdown-wiki-link-p)))
6735 (goto-char (or (match-beginning 1) (match-beginning 0)))
6740 ;;; Outline ===================================================================
6742 (defun markdown-move-heading-common (move-fn &optional arg adjust
)
6743 "Wrapper for `outline-mode' functions to skip false positives.
6744 MOVE-FN is a function and ARG is its argument. For example,
6745 headings inside preformatted code blocks may match
6746 `outline-regexp' but should not be considered as headings.
6747 When ADJUST is non-nil, adjust the point for interactive calls
6748 to avoid leaving the point at invisible markup. This adjustment
6749 generally should only be done for interactive calls, since other
6750 functions may expect the point to be at the beginning of the
6751 regular expression."
6752 (let ((prev -
1) (start (point)))
6753 (if arg
(funcall move-fn arg
) (funcall move-fn
))
6754 (while (and (/= prev
(point)) (markdown-code-block-at-point-p))
6756 (if arg
(funcall move-fn arg
) (funcall move-fn
)))
6757 ;; Adjust point for setext headings and invisible text.
6759 (when (and adjust
(thing-at-point-looking-at markdown-regex-header
))
6760 (if markdown-hide-markup
6761 ;; Move to beginning of heading text if markup is hidden.
6762 (goto-char (or (match-beginning 1) (match-beginning 5)))
6763 ;; Move to beginning of markup otherwise.
6764 (goto-char (or (match-beginning 1) (match-beginning 4))))))
6765 (if (= (point) start
) nil
(point))))
6767 (defun markdown-next-visible-heading (arg)
6768 "Move to the next visible heading line of any level.
6769 With argument, repeats or can move backward if negative. ARG is
6770 passed to `outline-next-visible-heading'."
6772 (markdown-move-heading-common #'outline-next-visible-heading arg
'adjust
))
6774 (defun markdown-previous-visible-heading (arg)
6775 "Move to the previous visible heading line of any level.
6776 With argument, repeats or can move backward if negative. ARG is
6777 passed to `outline-previous-visible-heading'."
6779 (markdown-move-heading-common #'outline-previous-visible-heading arg
'adjust
))
6781 (defun markdown-next-heading ()
6782 "Move to the next heading line of any level."
6783 (markdown-move-heading-common #'outline-next-heading
))
6785 (defun markdown-previous-heading ()
6786 "Move to the previous heading line of any level."
6787 (markdown-move-heading-common #'outline-previous-heading
))
6789 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok no-error
)
6790 "Move back to the beginning of the previous heading.
6791 Returns t if the point is at a heading, the location if a heading
6792 was found, and nil otherwise.
6793 Only visible heading lines are considered, unless INVISIBLE-OK is
6794 non-nil. Throw an error if there is no previous heading unless
6795 NO-ERROR is non-nil.
6796 Leaves match data intact for `markdown-regex-header'."
6798 (or (and (markdown-heading-at-point)
6799 (not (markdown-code-block-at-point-p)))
6802 (while (and (not found
)
6803 (re-search-backward markdown-regex-header nil t
))
6804 (when (and (or invisible-ok
(not (outline-invisible-p)))
6805 (not (markdown-code-block-at-point-p)))
6806 (setq found
(point))))
6808 (unless no-error
(user-error "Before first heading"))
6809 (setq found
(point))))
6810 (when found
(goto-char found
)))))
6812 (defun markdown-forward-same-level (arg)
6813 "Move forward 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)
6817 (markdown-move-heading-common #'outline-forward-same-level arg
'adjust
))
6819 (defun markdown-backward-same-level (arg)
6820 "Move backward to the ARG'th heading at same level as this one.
6821 Stop at the first and last headings of a superior heading."
6823 (markdown-back-to-heading-over-code-block)
6825 (let ((point-to-move-to
6827 (markdown-move-heading-common #'outline-get-last-sibling nil
'adjust
))))
6828 (if point-to-move-to
6830 (goto-char point-to-move-to
)
6831 (setq arg
(1- arg
)))
6832 (user-error "No previous same-level heading")))))
6834 (defun markdown-up-heading (arg &optional interactive
)
6835 "Move to the visible heading line of which the present line is a subheading.
6836 With argument, move up ARG levels. When called interactively (or
6837 INTERACTIVE is non-nil), also push the mark."
6838 (interactive "p\np")
6839 (and interactive
(not (eq last-command
'markdown-up-heading
))
6841 (markdown-move-heading-common #'outline-up-heading arg
'adjust
))
6843 (defun markdown-back-to-heading (&optional invisible-ok
)
6844 "Move to previous heading line, or beg of this line if it's a heading.
6845 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
6847 (markdown-move-heading-common #'outline-back-to-heading invisible-ok
))
6849 (defalias 'markdown-end-of-heading
'outline-end-of-heading
)
6851 (defun markdown-on-heading-p ()
6852 "Return non-nil if point is on a heading line."
6853 (get-text-property (line-beginning-position) 'markdown-heading
))
6855 (defun markdown-end-of-subtree (&optional invisible-OK
)
6856 "Move to the end of the current subtree.
6857 Only visible heading lines are considered, unless INVISIBLE-OK is
6859 Derived from `org-end-of-subtree'."
6860 (markdown-back-to-heading invisible-OK
)
6862 (level (markdown-outline-level)))
6863 (while (and (not (eobp))
6864 (or first
(> (markdown-outline-level) level
)))
6866 (markdown-next-heading))
6867 (if (memq (preceding-char) '(?
\n ?\^M
))
6869 ;; Go to end of line before heading
6871 (if (memq (preceding-char) '(?
\n ?\^M
))
6872 ;; leave blank line before heading
6873 (forward-char -
1)))))
6876 (defun markdown-outline-fix-visibility ()
6877 "Hide any false positive headings that should not be shown.
6878 For example, headings inside preformatted code blocks may match
6879 `outline-regexp' but should not be shown as headings when cycling.
6880 Also, the ending --- line in metadata blocks appears to be a
6881 setext header, but should not be folded."
6883 (goto-char (point-min))
6884 ;; Unhide any false positives in metadata blocks
6885 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin
)
6886 (let ((body (progn (forward-line)
6887 (markdown-text-property-at-point
6888 'markdown-yaml-metadata-section
))))
6890 (let ((end (progn (goto-char (cl-second body
))
6891 (markdown-text-property-at-point
6892 'markdown-yaml-metadata-end
))))
6893 (outline-flag-region (point-min) (1+ (cl-second end
)) nil
)))))
6894 ;; Hide any false positives in code blocks
6895 (unless (outline-on-heading-p)
6896 (outline-next-visible-heading 1))
6897 (while (< (point) (point-max))
6898 (when (markdown-code-block-at-point-p)
6899 (outline-flag-region (1- (line-beginning-position)) (line-end-position) t
))
6900 (outline-next-visible-heading 1))))
6902 (defvar markdown-cycle-global-status
1)
6903 (defvar markdown-cycle-subtree-status nil
)
6905 (defun markdown-next-preface ()
6907 (while (and (not finish
) (re-search-forward (concat "\n\\(?:" outline-regexp
"\\)")
6909 (unless (markdown-code-block-at-point-p)
6910 (goto-char (match-beginning 0))
6912 (when (and (bolp) (or outline-blank-line
(eobp)) (not (bobp)))
6915 (defun markdown-show-entry ()
6917 (outline-back-to-heading t
)
6918 (outline-flag-region (1- (point))
6920 (markdown-next-preface)
6921 (if (= 1 (- (point-max) (point)))
6926 ;; This function was originally derived from `org-cycle' from org.el.
6927 (defun markdown-cycle (&optional arg
)
6928 "Visibility cycling for Markdown mode.
6929 This function is called with a `\\[universal-argument]' or if ARG is t, perform
6930 global visibility cycling. If the point is at an atx-style header, cycle
6931 visibility of the corresponding subtree. Otherwise, indent the current line
6932 or insert a tab, as appropriate, by calling `indent-for-tab-command'."
6939 ;; Move from overview to contents
6940 ((and (eq last-command this-command
)
6941 (eq markdown-cycle-global-status
2))
6942 (outline-hide-sublevels 1)
6943 (message "CONTENTS")
6944 (setq markdown-cycle-global-status
3)
6945 (markdown-outline-fix-visibility))
6946 ;; Move from contents to all
6947 ((and (eq last-command this-command
)
6948 (eq markdown-cycle-global-status
3))
6950 (message "SHOW ALL")
6951 (setq markdown-cycle-global-status
1))
6952 ;; Defaults to overview
6955 (message "OVERVIEW")
6956 (setq markdown-cycle-global-status
2)
6957 (markdown-outline-fix-visibility))))
6959 ;; At a heading: rotate between three different views
6960 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
6961 (markdown-back-to-heading)
6962 (let ((goal-column 0) eoh eol eos
)
6963 ;; Determine boundaries
6965 (markdown-back-to-heading)
6967 (beginning-of-line 2)
6968 (while (and (not (eobp)) ;; this is like `next-line'
6969 (get-char-property (1- (point)) 'invisible
))
6970 (beginning-of-line 2)) (setq eol
(point)))
6971 (markdown-end-of-heading) (setq eoh
(point))
6972 (markdown-end-of-subtree t
)
6973 (skip-chars-forward " \t\n")
6974 (beginning-of-line 1) ; in case this is an item
6975 (setq eos
(1- (point))))
6976 ;; Find out what to do next and set `this-command'
6978 ;; Nothing is hidden behind this heading
6980 (message "EMPTY ENTRY")
6981 (setq markdown-cycle-subtree-status nil
))
6982 ;; Entire subtree is hidden in one line: open it
6984 (markdown-show-entry)
6985 (outline-show-children)
6986 (message "CHILDREN")
6987 (setq markdown-cycle-subtree-status
'children
))
6988 ;; We just showed the children, now show everything.
6989 ((and (eq last-command this-command
)
6990 (eq markdown-cycle-subtree-status
'children
))
6991 (outline-show-subtree)
6993 (setq markdown-cycle-subtree-status
'subtree
))
6994 ;; Default action: hide the subtree.
6996 (outline-hide-subtree)
6998 (setq markdown-cycle-subtree-status
'folded
)))))
7000 ;; In a table, move forward by one cell
7001 ((markdown-table-at-point-p)
7002 (call-interactively #'markdown-table-forward-cell
))
7004 ;; Otherwise, indent as appropriate
7006 (indent-for-tab-command))))
7008 (defun markdown-shifttab ()
7009 "Handle S-TAB keybinding based on context.
7010 When in a table, move backward one cell.
7011 Otherwise, cycle global heading visibility by calling
7012 `markdown-cycle' with argument t."
7014 (cond ((markdown-table-at-point-p)
7015 (call-interactively #'markdown-table-backward-cell
))
7016 (t (markdown-cycle t
))))
7018 (defun markdown-outline-level ()
7019 "Return the depth to which a statement is nested in the outline."
7021 ((and (match-beginning 0)
7022 (markdown-code-block-at-pos (match-beginning 0)))
7023 7) ;; Only 6 header levels are defined.
7027 (length (markdown-trim-whitespace (match-string-no-properties 4))))))
7029 (defun markdown-promote-subtree (&optional arg
)
7030 "Promote the current subtree of ATX headings.
7031 Note that Markdown does not support heading levels higher than
7032 six and therefore level-six headings will not be promoted
7033 further. If ARG is non-nil promote the heading, otherwise
7037 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx
)
7038 (re-search-backward markdown-regex-header-atx nil t
))
7039 (not (markdown-code-block-at-point-p)))
7040 (let ((level (length (match-string 1)))
7041 (promote-or-demote (if arg
1 -
1))
7043 (markdown-cycle-atx promote-or-demote remove
)
7044 (catch 'end-of-subtree
7045 (while (and (markdown-next-heading)
7046 (looking-at markdown-regex-header-atx
))
7047 ;; Exit if this not a higher level heading; promote otherwise.
7048 (if (and (looking-at markdown-regex-header-atx
)
7049 (<= (length (match-string-no-properties 1)) level
))
7050 (throw 'end-of-subtree nil
)
7051 (markdown-cycle-atx promote-or-demote remove
))))))))
7053 (defun markdown-demote-subtree ()
7054 "Demote the current subtree of ATX headings."
7056 (markdown-promote-subtree t
))
7058 (defun markdown-move-subtree-up ()
7059 "Move the current subtree of ATX headings up."
7061 (outline-move-subtree-up 1))
7063 (defun markdown-move-subtree-down ()
7064 "Move the current subtree of ATX headings down."
7066 (outline-move-subtree-down 1))
7068 (defun markdown-outline-next ()
7069 "Move to next list item, when in a list, or next visible heading."
7071 (let ((bounds (markdown-next-list-item-bounds)))
7073 (goto-char (nth 0 bounds
))
7074 (markdown-next-visible-heading 1))))
7076 (defun markdown-outline-previous ()
7077 "Move to previous list item, when in a list, or previous visible heading."
7079 (let ((bounds (markdown-prev-list-item-bounds)))
7081 (goto-char (nth 0 bounds
))
7082 (markdown-previous-visible-heading 1))))
7084 (defun markdown-outline-next-same-level ()
7085 "Move to next list item or heading of same level."
7087 (let ((bounds (markdown-cur-list-item-bounds)))
7089 (markdown-next-list-item (nth 3 bounds
))
7090 (markdown-forward-same-level 1))))
7092 (defun markdown-outline-previous-same-level ()
7093 "Move to previous list item or heading of same level."
7095 (let ((bounds (markdown-cur-list-item-bounds)))
7097 (markdown-prev-list-item (nth 3 bounds
))
7098 (markdown-backward-same-level 1))))
7100 (defun markdown-outline-up ()
7101 "Move to previous list item, when in a list, or previous heading."
7103 (unless (markdown-up-list)
7104 (markdown-up-heading 1)))
7107 ;;; Marking and Narrowing =====================================================
7109 (defun markdown-mark-paragraph ()
7110 "Put mark at end of this block, point at beginning.
7111 The block marked is the one that contains point or follows point.
7113 Interactively, if this command is repeated or (in Transient Mark
7114 mode) if the mark is active, it marks the next block after the
7115 ones already marked."
7117 (if (or (and (eq last-command this-command
) (mark t
))
7118 (and transient-mark-mode mark-active
))
7122 (markdown-forward-paragraph)
7124 (let ((beginning-of-defun-function #'markdown-backward-paragraph
)
7125 (end-of-defun-function #'markdown-forward-paragraph
))
7128 (defun markdown-mark-block ()
7129 "Put mark at end of this block, point at beginning.
7130 The block marked is the one that contains point or follows point.
7132 Interactively, if this command is repeated or (in Transient Mark
7133 mode) if the mark is active, it marks the next block after the
7134 ones already marked."
7136 (if (or (and (eq last-command this-command
) (mark t
))
7137 (and transient-mark-mode mark-active
))
7141 (markdown-forward-block)
7143 (let ((beginning-of-defun-function #'markdown-backward-block
)
7144 (end-of-defun-function #'markdown-forward-block
))
7147 (defun markdown-narrow-to-block ()
7148 "Make text outside current block invisible.
7149 The current block is the one that contains point or follows point."
7151 (let ((beginning-of-defun-function #'markdown-backward-block
)
7152 (end-of-defun-function #'markdown-forward-block
))
7155 (defun markdown-mark-text-block ()
7156 "Put mark at end of this plain text block, point at beginning.
7157 The block marked is the one that contains point or follows point.
7159 Interactively, if this command is repeated or (in Transient Mark
7160 mode) if the mark is active, it marks the next block after the
7161 ones already marked."
7163 (if (or (and (eq last-command this-command
) (mark t
))
7164 (and transient-mark-mode mark-active
))
7168 (markdown-end-of-text-block)
7170 (let ((beginning-of-defun-function #'markdown-beginning-of-text-block
)
7171 (end-of-defun-function #'markdown-end-of-text-block
))
7174 (defun markdown-mark-page ()
7175 "Put mark at end of this top level section, point at beginning.
7176 The top level section marked is the one that contains point or
7179 Interactively, if this command is repeated or (in Transient Mark
7180 mode) if the mark is active, it marks the next page after the
7181 ones already marked."
7183 (if (or (and (eq last-command this-command
) (mark t
))
7184 (and transient-mark-mode mark-active
))
7188 (markdown-forward-page)
7190 (let ((beginning-of-defun-function #'markdown-backward-page
)
7191 (end-of-defun-function #'markdown-forward-page
))
7194 (defun markdown-narrow-to-page ()
7195 "Make text outside current top level section invisible.
7196 The current section is the one that contains point or follows point."
7198 (let ((beginning-of-defun-function #'markdown-backward-page
)
7199 (end-of-defun-function #'markdown-forward-page
))
7202 (defun markdown-mark-subtree ()
7203 "Mark the current subtree.
7204 This puts point at the start of the current subtree, and mark at the end."
7207 (if (markdown-heading-at-point)
7209 (markdown-previous-visible-heading 1))
7211 (markdown-end-of-subtree)
7212 (push-mark (point) nil t
)
7215 (defun markdown-narrow-to-subtree ()
7216 "Narrow buffer to the current subtree."
7221 (progn (markdown-back-to-heading-over-code-block t
) (point))
7222 (progn (markdown-end-of-subtree)
7223 (if (and (markdown-heading-at-point) (not (eobp)))
7228 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
7230 (defun markdown-move-up ()
7231 "Move thing at point up.
7232 When in a list item, call `markdown-move-list-item-up'.
7233 When in a table, call `markdown-table-move-row-up'.
7234 Otherwise, move the current heading subtree up with
7235 `markdown-move-subtree-up'."
7238 ((markdown-list-item-at-point-p)
7239 (call-interactively #'markdown-move-list-item-up
))
7240 ((markdown-table-at-point-p)
7241 (call-interactively #'markdown-table-move-row-up
))
7243 (call-interactively #'markdown-move-subtree-up
))))
7245 (defun markdown-move-down ()
7246 "Move thing at point down.
7247 When in a list item, call `markdown-move-list-item-down'.
7248 Otherwise, move the current heading subtree up with
7249 `markdown-move-subtree-down'."
7252 ((markdown-list-item-at-point-p)
7253 (call-interactively #'markdown-move-list-item-down
))
7254 ((markdown-table-at-point-p)
7255 (call-interactively #'markdown-table-move-row-down
))
7257 (call-interactively #'markdown-move-subtree-down
))))
7259 (defun markdown-promote ()
7260 "Promote or move element at point to the left.
7261 Depending on the context, this function will promote a heading or
7262 list item at the point, move a table column to the left, or cycle
7267 ;; Promote atx heading subtree
7268 ((thing-at-point-looking-at markdown-regex-header-atx
)
7269 (markdown-promote-subtree))
7270 ;; Promote setext heading
7271 ((thing-at-point-looking-at markdown-regex-header-setext
)
7272 (markdown-cycle-setext -
1))
7273 ;; Promote horizontal rule
7274 ((thing-at-point-looking-at markdown-regex-hr
)
7275 (markdown-cycle-hr -
1))
7276 ;; Promote list item
7277 ((setq bounds
(markdown-cur-list-item-bounds))
7278 (markdown-promote-list-item bounds
))
7279 ;; Move table column to the left
7280 ((markdown-table-at-point-p)
7281 (call-interactively #'markdown-table-move-column-left
))
7283 ((thing-at-point-looking-at markdown-regex-bold
)
7284 (markdown-cycle-bold))
7286 ((thing-at-point-looking-at markdown-regex-italic
)
7287 (markdown-cycle-italic))
7289 (user-error "Nothing to promote at point")))))
7291 (defun markdown-demote ()
7292 "Demote or move element at point to the right.
7293 Depending on the context, this function will demote a heading or
7294 list item at the point, move a table column to the right, or cycle
7299 ;; Demote atx heading subtree
7300 ((thing-at-point-looking-at markdown-regex-header-atx
)
7301 (markdown-demote-subtree))
7302 ;; Demote setext heading
7303 ((thing-at-point-looking-at markdown-regex-header-setext
)
7304 (markdown-cycle-setext 1))
7305 ;; Demote horizontal rule
7306 ((thing-at-point-looking-at markdown-regex-hr
)
7307 (markdown-cycle-hr 1))
7309 ((setq bounds
(markdown-cur-list-item-bounds))
7310 (markdown-demote-list-item bounds
))
7311 ;; Move table column to the right
7312 ((markdown-table-at-point-p)
7313 (call-interactively #'markdown-table-move-column-right
))
7315 ((thing-at-point-looking-at markdown-regex-bold
)
7316 (markdown-cycle-bold))
7318 ((thing-at-point-looking-at markdown-regex-italic
)
7319 (markdown-cycle-italic))
7321 (user-error "Nothing to demote at point")))))
7324 ;;; Commands ==================================================================
7326 (defun markdown (&optional output-buffer-name
)
7327 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
7328 The output buffer name defaults to `markdown-output-buffer-name'.
7329 Return the name of the output buffer used."
7331 (save-window-excursion
7332 (let* ((commands (cond ((stringp markdown-command
) (split-string markdown-command
))
7333 ((listp markdown-command
) markdown-command
)))
7334 (command (car-safe commands
))
7335 (command-args (cdr-safe commands
))
7336 begin-region end-region
)
7338 (setq begin-region
(region-beginning)
7339 end-region
(region-end))
7340 (setq begin-region
(point-min)
7341 end-region
(point-max)))
7343 (unless output-buffer-name
7344 (setq output-buffer-name markdown-output-buffer-name
))
7345 (when (and (stringp command
) (not (executable-find command
)))
7346 (user-error "Markdown command %s is not found" command
))
7349 ;; Handle case when `markdown-command' does not read from stdin
7350 ((and (stringp command
) markdown-command-needs-filename
)
7351 (if (not buffer-file-name
)
7352 (user-error "Must be visiting a file")
7353 ;; Don’t use ‘shell-command’ because it’s not guaranteed to
7354 ;; return the exit code of the process.
7355 (let ((command (if (listp markdown-command
)
7356 (string-join markdown-command
" ")
7358 (shell-command-on-region
7359 ;; Pass an empty region so that stdin is empty.
7362 (shell-quote-argument buffer-file-name
))
7363 output-buffer-name
))))
7364 ;; Pass region to `markdown-command' via stdin
7366 (let ((buf (get-buffer-create output-buffer-name
)))
7367 (with-current-buffer buf
7368 (setq buffer-read-only nil
)
7370 (if (stringp command
)
7371 (if (not (null command-args
))
7372 (apply #'call-process-region begin-region end-region command nil buf nil command-args
)
7373 (call-process-region begin-region end-region command nil buf
))
7374 (if markdown-command-needs-filename
7375 (if (not buffer-file-name
)
7376 (user-error "Must be visiting a file")
7377 (funcall markdown-command begin-region end-region buf buffer-file-name
))
7378 (funcall markdown-command begin-region end-region buf
))
7379 ;; If the ‘markdown-command’ function didn’t signal an
7380 ;; error, assume it succeeded by binding ‘exit-code’ to 0.
7382 ;; The exit code can be a signal description string, so don’t use ‘=’
7384 (unless (eq exit-code
0)
7385 (user-error "%s failed with exit code %s"
7386 markdown-command exit-code
))))
7387 output-buffer-name
))
7389 (defun markdown-standalone (&optional output-buffer-name
)
7390 "Special function to provide standalone HTML output.
7391 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
7393 (setq output-buffer-name
(markdown output-buffer-name
))
7394 (with-current-buffer output-buffer-name
7395 (set-buffer output-buffer-name
)
7396 (unless (markdown-output-standalone-p)
7397 (markdown-add-xhtml-header-and-footer output-buffer-name
))
7398 (goto-char (point-min))
7402 (defun markdown-other-window (&optional output-buffer-name
)
7403 "Run `markdown-command' on current buffer and display in other window.
7404 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7407 (markdown-display-buffer-other-window
7408 (markdown-standalone output-buffer-name
)))
7410 (defun markdown-output-standalone-p ()
7411 "Determine whether `markdown-command' output is standalone XHTML.
7412 Standalone XHTML output is identified by an occurrence of
7413 `markdown-xhtml-standalone-regexp' in the first five lines of output."
7415 (goto-char (point-min))
7418 markdown-xhtml-standalone-regexp
7419 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
7422 (defun markdown-stylesheet-link-string (stylesheet-path)
7423 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
7424 (or (and (string-prefix-p "~" stylesheet-path
)
7425 (expand-file-name stylesheet-path
))
7429 (defun markdown-add-xhtml-header-and-footer (title)
7430 "Wrap XHTML header and footer with given TITLE around current buffer."
7431 (goto-char (point-min))
7432 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
7433 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
7434 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
7435 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
7438 (insert "</title>\n")
7439 (unless (= (length markdown-content-type
) 0)
7442 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
7443 markdown-content-type
7444 (or (and markdown-coding-system
7445 (coding-system-get markdown-coding-system
7447 (coding-system-get buffer-file-coding-system
7450 (if (> (length markdown-css-paths
) 0)
7451 (insert (mapconcat #'markdown-stylesheet-link-string
7452 markdown-css-paths
"\n")))
7453 (when (> (length markdown-xhtml-header-content
) 0)
7454 (insert markdown-xhtml-header-content
))
7455 (insert "\n</head>\n\n"
7457 (when (> (length markdown-xhtml-body-preamble
) 0)
7458 (insert markdown-xhtml-body-preamble
"\n"))
7459 (goto-char (point-max))
7460 (when (> (length markdown-xhtml-body-epilogue
) 0)
7461 (insert "\n" markdown-xhtml-body-epilogue
))
7466 (defun markdown-preview (&optional output-buffer-name
)
7467 "Run `markdown-command' on the current buffer and view output in browser.
7468 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7471 (browse-url-of-buffer
7472 (markdown-standalone (or output-buffer-name markdown-output-buffer-name
))))
7474 (defun markdown-export-file-name (&optional extension
)
7475 "Attempt to generate a filename for Markdown output.
7476 The file extension will be EXTENSION if given, or .html by default.
7477 If the current buffer is visiting a file, we construct a new
7478 output filename based on that filename. Otherwise, return nil."
7479 (when (buffer-file-name)
7481 (setq extension
".html"))
7486 (file-name-sans-extension (buffer-file-name)))
7490 ((equal candidate
(buffer-file-name))
7491 (concat candidate extension
))
7495 (defun markdown-export (&optional output-file
)
7496 "Run Markdown on the current buffer, save to file, and return the filename.
7497 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
7498 generated by `markdown-export-file-name', which will be constructed using the
7499 current filename, but with the extension removed and replaced with .html."
7502 (setq output-file
(markdown-export-file-name ".html")))
7504 (let* ((init-buf (current-buffer))
7505 (init-point (point))
7506 (init-buf-string (buffer-string))
7507 (output-buffer (find-file-noselect output-file
))
7508 (output-buffer-name (buffer-name output-buffer
)))
7509 (run-hooks 'markdown-before-export-hook
)
7510 (markdown-standalone output-buffer-name
)
7511 (with-current-buffer output-buffer
7512 (run-hooks 'markdown-after-export-hook
)
7514 (when markdown-export-kill-buffer
(kill-buffer)))
7515 ;; if modified, restore initial buffer
7516 (when (buffer-modified-p init-buf
)
7518 (insert init-buf-string
)
7520 (goto-char init-point
))
7523 (defun markdown-export-and-preview ()
7524 "Export to XHTML using `markdown-export' and browse the resulting file."
7526 (browse-url-of-file (markdown-export)))
7528 (defvar-local markdown-live-preview-buffer nil
7529 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
7531 (defvar-local markdown-live-preview-source-buffer nil
7532 "Source buffer from which current buffer was generated.
7533 This is the inverse of `markdown-live-preview-buffer'.")
7535 (defvar markdown-live-preview-currently-exporting nil
)
7537 (defun markdown-live-preview-get-filename ()
7538 "Standardize the filename exported by `markdown-live-preview-export'."
7539 (markdown-export-file-name ".html"))
7541 (defun markdown-live-preview-window-eww (file)
7542 "Preview FILE with eww.
7543 To be used with `markdown-live-preview-window-function'."
7544 (eww-open-file file
)
7545 (get-buffer "*eww*"))
7547 (defun markdown-visual-lines-between-points (beg end
)
7550 (cl-loop with count
= 0
7551 while
(progn (end-of-visual-line)
7552 (and (< (point) end
) (line-move-visual 1 t
)))
7554 finally return count
)))
7556 (defun markdown-live-preview-window-serialize (buf)
7557 "Get window point and scroll data for all windows displaying BUF."
7558 (when (buffer-live-p buf
)
7559 (with-current-buffer buf
7562 (with-selected-window win
7563 (let* ((start (window-start))
7565 (pt-or-sym (cond ((= pt
(point-min)) 'min
)
7566 ((= pt
(point-max)) 'max
)
7568 (diff (markdown-visual-lines-between-points
7570 (list win pt-or-sym diff
))))
7571 (get-buffer-window-list buf
)))))
7573 (defun markdown-get-point-back-lines (pt num-lines
)
7576 (line-move-visual (- num-lines
) t
)
7577 ;; in testing, can occasionally overshoot the number of lines to traverse
7578 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt
)))
7579 (when (> actual-num-lines num-lines
)
7580 (line-move-visual (- actual-num-lines num-lines
) t
)))
7583 (defun markdown-live-preview-window-deserialize (window-posns)
7584 "Apply window point and scroll data from WINDOW-POSNS.
7585 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
7586 (cl-destructuring-bind (win pt-or-sym diff
) window-posns
7587 (when (window-live-p win
)
7588 (with-current-buffer markdown-live-preview-buffer
7589 (set-window-buffer win
(current-buffer))
7590 (cl-destructuring-bind (actual-pt actual-diff
)
7592 (min (list (point-min) 0))
7593 (max (list (point-max) diff
))
7594 (t (list pt-or-sym diff
)))
7596 win
(markdown-get-point-back-lines actual-pt actual-diff
))
7597 (set-window-point win actual-pt
))))))
7599 (defun markdown-live-preview-export ()
7600 "Export to XHTML using `markdown-export'.
7601 Browse the resulting file within Emacs using
7602 `markdown-live-preview-window-function' Return the buffer
7603 displaying the rendered output."
7605 (let ((filename (markdown-live-preview-get-filename)))
7607 (let* ((markdown-live-preview-currently-exporting t
)
7608 (cur-buf (current-buffer))
7609 (export-file (markdown-export filename
))
7610 ;; get positions in all windows currently displaying output buffer
7612 (markdown-live-preview-window-serialize
7613 markdown-live-preview-buffer
)))
7614 (save-window-excursion
7615 (let ((output-buffer
7616 (funcall markdown-live-preview-window-function export-file
)))
7617 (with-current-buffer output-buffer
7618 (setq markdown-live-preview-source-buffer cur-buf
)
7619 (add-hook 'kill-buffer-hook
7620 #'markdown-live-preview-remove-on-kill t t
))
7621 (with-current-buffer cur-buf
7622 (setq markdown-live-preview-buffer output-buffer
))))
7623 (with-current-buffer cur-buf
7624 ;; reset all windows displaying output buffer to where they were,
7625 ;; now with the new output
7626 (mapc #'markdown-live-preview-window-deserialize window-data
)
7627 ;; delete html editing buffer
7628 (let ((buf (get-file-buffer export-file
))) (when buf
(kill-buffer buf
)))
7629 (when (and export-file
(file-exists-p export-file
)
7630 (eq markdown-live-preview-delete-export
7632 (delete-file export-file
))
7633 markdown-live-preview-buffer
)))))
7635 (defun markdown-live-preview-remove ()
7636 (when (buffer-live-p markdown-live-preview-buffer
)
7637 (kill-buffer markdown-live-preview-buffer
))
7638 (setq markdown-live-preview-buffer nil
)
7639 ;; if set to 'delete-on-export, the output has already been deleted
7640 (when (eq markdown-live-preview-delete-export
'delete-on-destroy
)
7641 (let ((outfile-name (markdown-live-preview-get-filename)))
7642 (when (and outfile-name
(file-exists-p outfile-name
))
7643 (delete-file outfile-name
)))))
7645 (defun markdown-get-other-window ()
7646 "Find another window to display preview or output content."
7648 ((memq markdown-split-window-direction
'(vertical below
))
7649 (or (window-in-direction 'below
) (split-window-vertically)))
7650 ((memq markdown-split-window-direction
'(horizontal right
))
7651 (or (window-in-direction 'right
) (split-window-horizontally)))
7652 (t (split-window-sensibly (get-buffer-window)))))
7654 (defun markdown-display-buffer-other-window (buf)
7655 "Display preview or output buffer BUF in another window."
7656 (if (and display-buffer-alist
(eq markdown-split-window-direction
'any
))
7657 (display-buffer buf
)
7658 (let ((cur-buf (current-buffer))
7659 (window (markdown-get-other-window)))
7660 (set-window-buffer window buf
)
7661 (set-buffer cur-buf
))))
7663 (defun markdown-live-preview-if-markdown ()
7664 (when (and (derived-mode-p 'markdown-mode
)
7665 markdown-live-preview-mode
)
7666 (unless markdown-live-preview-currently-exporting
7667 (if (buffer-live-p markdown-live-preview-buffer
)
7668 (markdown-live-preview-export)
7669 (markdown-display-buffer-other-window
7670 (markdown-live-preview-export))))))
7672 (defun markdown-live-preview-remove-on-kill ()
7673 (cond ((and (derived-mode-p 'markdown-mode
)
7674 markdown-live-preview-mode
)
7675 (markdown-live-preview-remove))
7676 (markdown-live-preview-source-buffer
7677 (with-current-buffer markdown-live-preview-source-buffer
7678 (setq markdown-live-preview-buffer nil
))
7679 (setq markdown-live-preview-source-buffer nil
))))
7681 (defun markdown-live-preview-switch-to-output ()
7682 "Turn on `markdown-live-preview-mode' and switch to output buffer.
7683 The output buffer is opened in another window."
7685 (if markdown-live-preview-mode
7686 (markdown-display-buffer-other-window (markdown-live-preview-export)))
7687 (markdown-live-preview-mode))
7689 (defun markdown-live-preview-re-export ()
7690 "Re-export the current live previewed content.
7691 If the current buffer is a buffer displaying the exported version of a
7692 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
7693 update this buffer's contents."
7695 (when markdown-live-preview-source-buffer
7696 (with-current-buffer markdown-live-preview-source-buffer
7697 (markdown-live-preview-export))))
7699 (defun markdown-open ()
7700 "Open file for the current buffer with `markdown-open-command'."
7702 (unless markdown-open-command
7703 (user-error "Variable `markdown-open-command' must be set"))
7704 (if (stringp markdown-open-command
)
7705 (if (not buffer-file-name
)
7706 (user-error "Must be visiting a file")
7708 (let ((exit-code (call-process markdown-open-command nil nil nil
7710 ;; The exit code can be a signal description string, so don’t use ‘=’
7712 (unless (eq exit-code
0)
7713 (user-error "%s failed with exit code %s"
7714 markdown-open-command exit-code
))))
7715 (funcall markdown-open-command
))
7718 (defun markdown-kill-ring-save ()
7719 "Run Markdown on file and store output in the kill ring."
7721 (save-window-excursion
7723 (with-current-buffer markdown-output-buffer-name
7724 (kill-ring-save (point-min) (point-max)))))
7727 ;;; Links =====================================================================
7729 (defun markdown-backward-to-link-start ()
7730 "Backward link start position if current position is in link title."
7732 (when (eq (get-text-property (point) 'face
) 'markdown-link-face
)
7733 (skip-chars-backward "^[")
7736 (defun markdown-link-p ()
7737 "Return non-nil when `point' is at a non-wiki link.
7738 See `markdown-wiki-link-p' for more information."
7740 (let ((case-fold-search nil
))
7741 (when (and (not (markdown-wiki-link-p)) (not (markdown-code-block-at-point-p)))
7742 (markdown-backward-to-link-start)
7743 (or (thing-at-point-looking-at markdown-regex-link-inline
)
7744 (thing-at-point-looking-at markdown-regex-link-reference
)
7745 (thing-at-point-looking-at markdown-regex-uri
)
7746 (thing-at-point-looking-at markdown-regex-angle-uri
))))))
7748 (defun markdown-link-at-pos (pos)
7749 "Return properties of link or image at position POS.
7750 Value is a list of elements describing the link:
7751 0. beginning position
7757 6. bang (nil or \"!\")"
7760 (markdown-backward-to-link-start)
7761 (let (begin end text url reference title bang
)
7763 ;; Inline image or link at point.
7764 ((thing-at-point-looking-at markdown-regex-link-inline
)
7765 (setq bang
(match-string-no-properties 1)
7766 begin
(match-beginning 0)
7768 text
(match-string-no-properties 3)
7769 url
(match-string-no-properties 6))
7771 (setq title
(substring (match-string-no-properties 7) 1 -
1))
7772 ;; #408 URL contains close parenthesis case
7773 (goto-char (match-beginning 5))
7774 (let ((paren-end (scan-sexps (point) 1)))
7775 (when (and paren-end
(< end paren-end
))
7776 (setq url
(buffer-substring (match-beginning 6) (1- paren-end
)))))))
7777 ;; Reference link at point.
7778 ((or (thing-at-point-looking-at markdown-regex-link-inline
)
7779 (thing-at-point-looking-at markdown-regex-link-reference
))
7780 (setq bang
(match-string-no-properties 1)
7781 begin
(match-beginning 0)
7783 text
(match-string-no-properties 3))
7784 (when (char-equal (char-after (match-beginning 5)) ?\
[)
7785 (setq reference
(match-string-no-properties 6))))
7786 ;; Angle bracket URI at point.
7787 ((thing-at-point-looking-at markdown-regex-angle-uri
)
7788 (setq begin
(match-beginning 0)
7790 url
(match-string-no-properties 2)))
7791 ;; Plain URI at point.
7792 ((thing-at-point-looking-at markdown-regex-uri
)
7793 (setq begin
(match-beginning 0)
7795 url
(match-string-no-properties 1))))
7796 (list begin end text url reference title bang
))))
7798 (defun markdown-link-url ()
7799 "Return the URL part of the regular (non-wiki) link at point.
7800 Works with both inline and reference style links, and with images.
7801 If point is not at a link or the link reference is not defined
7803 (let* ((values (markdown-link-at-pos (point)))
7804 (text (nth 2 values
))
7805 (url (nth 3 values
))
7806 (ref (nth 4 values
)))
7807 (or url
(and ref
(car (markdown-reference-definition
7808 (downcase (if (string= ref
"") text ref
))))))))
7810 (defun markdown--browse-url (url)
7811 (let* ((struct (url-generic-parse-url url
))
7812 (full (url-fullness struct
))
7814 ;; Parse URL, determine fullness, strip query string
7815 (setq file
(car (url-path-and-query struct
)))
7816 ;; Open full URLs in browser, files in Emacs
7819 (when (and file
(> (length file
) 0))
7820 (let ((link-file (funcall markdown-translate-filename-function file
)))
7821 (if (and markdown-open-image-command
(string-match-p (image-file-name-regexp) link-file
))
7822 (if (functionp markdown-open-image-command
)
7823 (funcall markdown-open-image-command link-file
)
7824 (process-file markdown-open-image-command nil nil nil link-file
))
7825 (find-file link-file
)))))))
7827 (defun markdown-follow-link-at-point (&optional event
)
7828 "Open the non-wiki link at point or EVENT.
7829 If the link is a complete URL, open in browser with `browse-url'.
7830 Otherwise, open with `find-file' after stripping anchor and/or query string.
7831 Translate filenames using `markdown-filename-translate-function'."
7832 (interactive (list last-command-event
))
7834 (if event
(posn-set-point (event-start event
)))
7835 (if (markdown-link-p)
7836 (markdown--browse-url (markdown-link-url))
7837 (user-error "Point is not at a Markdown link or URL"))))
7839 (defun markdown-fontify-inline-links (last)
7840 "Add text properties to next inline link from point to LAST."
7841 (when (markdown-match-generic-links last nil
)
7842 (let* ((link-start (match-beginning 3))
7843 (link-end (match-end 3))
7844 (url-start (match-beginning 6))
7845 (url-end (match-end 6))
7846 (url (match-string-no-properties 6))
7847 (title-start (match-beginning 7))
7848 (title-end (match-end 7))
7849 (title (match-string-no-properties 7))
7851 (mp (list 'invisible
'markdown-markup
7853 'font-lock-multiline t
))
7854 ;; Link part (without face)
7855 (lp (list 'keymap markdown-mode-mouse-map
7856 'mouse-face
'markdown-highlight-face
7857 'font-lock-multiline t
7858 'help-echo
(if title
(concat title
"\n" url
) url
)))
7860 (up (list 'keymap markdown-mode-mouse-map
7861 'invisible
'markdown-markup
7862 'mouse-face
'markdown-highlight-face
7863 'font-lock-multiline t
))
7864 ;; URL composition character
7865 (url-char (markdown--first-displayable markdown-url-compose-char
))
7867 (tp (list 'invisible
'markdown-markup
7868 'font-lock-multiline t
)))
7869 (dolist (g '(1 2 4 5 8))
7871 (add-text-properties (match-beginning g
) (match-end g
) mp
)
7872 (add-face-text-property (match-beginning g
) (match-end g
) 'markdown-markup-face
)))
7873 ;; Preserve existing faces applied to link part (e.g., inline code)
7875 (add-text-properties link-start link-end lp
)
7876 (add-face-text-property link-start link-end
'markdown-link-face
))
7878 (add-text-properties url-start url-end up
)
7879 (add-face-text-property url-start url-end
'markdown-url-face
))
7881 (add-text-properties url-end title-end tp
)
7882 (add-face-text-property url-end title-end
'markdown-link-title-face
))
7883 (when (and markdown-hide-urls url-start
)
7884 (compose-region url-start
(or title-end url-end
) url-char
))
7887 (defun markdown-fontify-reference-links (last)
7888 "Add text properties to next reference link from point to LAST."
7889 (when (markdown-match-generic-links last t
)
7890 (let* ((link-start (match-beginning 3))
7891 (link-end (match-end 3))
7892 (ref-start (match-beginning 6))
7893 (ref-end (match-end 6))
7895 (mp (list 'invisible
'markdown-markup
7897 'font-lock-multiline t
))
7899 (lp (list 'keymap markdown-mode-mouse-map
7900 'mouse-face
'markdown-highlight-face
7901 'font-lock-multiline t
7902 'help-echo
(lambda (_ __ pos
)
7906 (or (markdown-link-url)
7907 "Undefined reference"))))))
7908 ;; URL composition character
7909 (url-char (markdown--first-displayable markdown-url-compose-char
))
7911 (rp (list 'invisible
'markdown-markup
7912 'font-lock-multiline t
)))
7913 (dolist (g '(1 2 4 5 8))
7915 (add-text-properties (match-beginning g
) (match-end g
) mp
)
7916 (add-face-text-property (match-beginning g
) (match-end g
) 'markdown-markup-face
)))
7918 (add-text-properties link-start link-end lp
)
7919 (add-face-text-property link-start link-end
'markdown-link-face
))
7921 (add-text-properties ref-start ref-end rp
)
7922 (add-face-text-property ref-start ref-end
'markdown-reference-face
)
7923 (when (and markdown-hide-urls
(> (- ref-end ref-start
) 2))
7924 (compose-region ref-start ref-end url-char
)))
7927 (defun markdown-fontify-angle-uris (last)
7928 "Add text properties to angle URIs from point to LAST."
7929 (when (markdown-match-angle-uris last
)
7930 (let* ((url-start (match-beginning 2))
7931 (url-end (match-end 2))
7933 (mp (list 'face
'markdown-markup-face
7934 'invisible
'markdown-markup
7936 'font-lock-multiline t
))
7938 (up (list 'keymap markdown-mode-mouse-map
7939 'face
'markdown-plain-url-face
7940 'mouse-face
'markdown-highlight-face
7941 'font-lock-multiline t
)))
7943 (add-text-properties (match-beginning g
) (match-end g
) mp
))
7944 (add-text-properties url-start url-end up
)
7947 (defun markdown-fontify-plain-uris (last)
7948 "Add text properties to plain URLs from point to LAST."
7949 (when (markdown-match-plain-uris last
)
7950 (let* ((start (match-beginning 0))
7952 (props (list 'keymap markdown-mode-mouse-map
7953 'face
'markdown-plain-url-face
7954 'mouse-face
'markdown-highlight-face
7956 'font-lock-multiline t
)))
7957 (add-text-properties start end props
)
7960 (defun markdown-toggle-url-hiding (&optional arg
)
7961 "Toggle the display or hiding of URLs.
7962 With a prefix argument ARG, enable URL hiding if ARG is positive,
7963 and disable it otherwise."
7964 (interactive (list (or current-prefix-arg
'toggle
)))
7965 (setq markdown-hide-urls
7966 (if (eq arg
'toggle
)
7967 (not markdown-hide-urls
)
7968 (> (prefix-numeric-value arg
) 0)))
7969 (if markdown-hide-urls
7970 (message "markdown-mode URL hiding enabled")
7971 (message "markdown-mode URL hiding disabled"))
7972 (markdown-reload-extensions))
7975 ;;; Wiki Links ================================================================
7977 (defun markdown-wiki-link-p ()
7978 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
7979 A true wiki link name matches `markdown-regex-wiki-link' but does
7980 not match the current file name after conversion. This modifies
7981 the data returned by `match-data'. Note that the potential wiki
7982 link name must be available via `match-string'."
7983 (when markdown-enable-wiki-links
7984 (let ((case-fold-search nil
))
7985 (and (thing-at-point-looking-at markdown-regex-wiki-link
)
7986 (not (markdown-code-block-at-point-p))
7987 (or (not buffer-file-name
)
7988 (not (string-equal (buffer-file-name)
7989 (markdown-convert-wiki-link-to-filename
7990 (markdown-wiki-link-link)))))))))
7992 (defun markdown-wiki-link-link ()
7993 "Return the link part of the wiki link using current match data.
7994 The location of the link component depends on the value of
7995 `markdown-wiki-link-alias-first'."
7996 (if markdown-wiki-link-alias-first
7997 (or (match-string-no-properties 5) (match-string-no-properties 3))
7998 (match-string-no-properties 3)))
8000 (defun markdown-wiki-link-alias ()
8001 "Return the alias or text part of the wiki link using current match data.
8002 The location of the alias component depends on the value of
8003 `markdown-wiki-link-alias-first'."
8004 (if markdown-wiki-link-alias-first
8005 (match-string-no-properties 3)
8006 (or (match-string-no-properties 5) (match-string-no-properties 3))))
8008 (defun markdown--wiki-link-search-types ()
8009 (let ((ret (and markdown-wiki-link-search-type
8010 (cl-copy-list markdown-wiki-link-search-type
))))
8011 (when (and markdown-wiki-link-search-subdirectories
8012 (not (memq 'sub-directories markdown-wiki-link-search-type
)))
8013 (push 'sub-directories ret
))
8014 (when (and markdown-wiki-link-search-parent-directories
8015 (not (memq 'parent-directories markdown-wiki-link-search-type
)))
8016 (push 'parent-directories ret
))
8019 (defun markdown--project-root ()
8020 (or (cl-loop for dir in
'(".git" ".hg" ".svn")
8021 when
(locate-dominating-file default-directory dir
)
8025 (let ((project (project-current t
)))
8027 (if (fboundp 'project-root
)
8028 (project-root project
)
8029 (car (project-roots project
))))))))
8031 (defun markdown-convert-wiki-link-to-filename (name)
8032 "Generate a filename from the wiki link NAME.
8033 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
8034 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
8035 and [[test test]] both map to Test-test.ext. Look in the current
8036 directory first, then in subdirectories if
8037 `markdown-wiki-link-search-subdirectories' is non-nil, and then
8038 in parent directories if
8039 `markdown-wiki-link-search-parent-directories' is non-nil."
8041 ;; This function must not overwrite match data(PR #590)
8042 (let* ((basename (replace-regexp-in-string
8043 "[[:space:]\n]" markdown-link-space-sub-char name
))
8044 (basename (if (derived-mode-p 'gfm-mode
)
8045 (concat (upcase (substring basename
0 1))
8046 (downcase (substring basename
1 nil
)))
8048 (search-types (markdown--wiki-link-search-types))
8049 directory extension default candidates dir
)
8050 (when buffer-file-name
8051 (setq directory
(file-name-directory buffer-file-name
)
8052 extension
(file-name-extension buffer-file-name
)))
8053 (setq default
(concat basename
8054 (when extension
(concat "." extension
))))
8056 ;; Look in current directory first.
8057 ((or (null buffer-file-name
)
8058 (file-exists-p default
))
8060 ;; Possibly search in subdirectories, next.
8061 ((and (memq 'sub-directories search-types
)
8063 (directory-files-recursively
8064 directory
(concat "^" default
"$"))))
8066 ;; Possibly search in parent directories as a last resort.
8067 ((and (memq 'parent-directories search-types
)
8068 (setq dir
(locate-dominating-file directory default
)))
8069 (concat dir default
))
8070 ((and (memq 'project search-types
)
8072 (directory-files-recursively
8073 (markdown--project-root) (concat "^" default
"$"))))
8075 ;; If nothing is found, return default in current directory.
8078 (defun markdown-follow-wiki-link (name &optional other
)
8079 "Follow the wiki link NAME.
8080 Convert the name to a file name and call `find-file'. Ensure that
8081 the new buffer remains in `markdown-mode'. Open the link in another
8082 window when OTHER is non-nil."
8083 (let ((filename (markdown-convert-wiki-link-to-filename name
))
8084 (wp (when buffer-file-name
8085 (file-name-directory buffer-file-name
))))
8087 (user-error "Must be visiting a file")
8088 (when other
(other-window 1))
8089 (let ((default-directory wp
))
8090 (find-file filename
)))
8091 (unless (derived-mode-p 'markdown-mode
)
8094 (defun markdown-follow-wiki-link-at-point (&optional arg
)
8095 "Find Wiki Link at point.
8096 With prefix argument ARG, open the file in other window.
8097 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
8099 (if (markdown-wiki-link-p)
8100 (markdown-follow-wiki-link (markdown-wiki-link-link) arg
)
8101 (user-error "Point is not at a Wiki Link")))
8103 (defun markdown-highlight-wiki-link (from to face
)
8104 "Highlight the wiki link in the region between FROM and TO using FACE."
8105 (put-text-property from to
'font-lock-face face
))
8107 (defun markdown-unfontify-region-wiki-links (from to
)
8108 "Remove wiki link faces from the region specified by FROM and TO."
8110 (let ((modified (buffer-modified-p)))
8111 (remove-text-properties from to
'(font-lock-face markdown-link-face
))
8112 (remove-text-properties from to
'(font-lock-face markdown-missing-link-face
))
8113 ;; remove-text-properties marks the buffer modified in emacs 24.3,
8114 ;; undo that if it wasn't originally marked modified
8115 (set-buffer-modified-p modified
)))
8117 (defun markdown-fontify-region-wiki-links (from to
)
8118 "Search region given by FROM and TO for wiki links and fontify them.
8119 If a wiki link is found check to see if the backing file exists
8120 and highlight accordingly."
8123 (while (re-search-forward markdown-regex-wiki-link to t
)
8124 (when (not (markdown-code-block-at-point-p))
8125 (let ((highlight-beginning (match-beginning 1))
8126 (highlight-end (match-end 1))
8128 (markdown-convert-wiki-link-to-filename
8129 (markdown-wiki-link-link))))
8130 (if (condition-case nil
(file-exists-p file-name
) (error nil
))
8131 (markdown-highlight-wiki-link
8132 highlight-beginning highlight-end
'markdown-link-face
)
8133 (markdown-highlight-wiki-link
8134 highlight-beginning highlight-end
'markdown-missing-link-face
)))))))
8136 (defun markdown-extend-changed-region (from to
)
8137 "Extend region given by FROM and TO so that we can fontify all links.
8138 The region is extended to the first newline before and the first
8140 ;; start looking for the first new line before 'from
8142 (re-search-backward "\n" nil t
)
8143 (let ((new-from (point-min))
8144 (new-to (point-max)))
8145 (if (not (= (point) from
))
8146 (setq new-from
(point)))
8147 ;; do the same thing for the first new line after 'to
8149 (re-search-forward "\n" nil t
)
8150 (if (not (= (point) to
))
8151 (setq new-to
(point)))
8152 (cl-values new-from new-to
)))
8154 (defun markdown-check-change-for-wiki-link (from to
)
8155 "Check region between FROM and TO for wiki links and re-fontify as needed."
8157 (let* ((modified (buffer-modified-p))
8158 (buffer-undo-list t
)
8159 (inhibit-read-only t
)
8161 buffer-file-truename
)
8166 (cursor-intangible-mode +1) ;; inhibit-point-motion-hooks is obsoleted since Emacs 29
8167 ;; Extend the region to fontify so that it starts
8168 ;; and ends at safe places.
8169 (cl-multiple-value-bind (new-from new-to
)
8170 (markdown-extend-changed-region from to
)
8171 (goto-char new-from
)
8172 ;; Only refontify when the range contains text with a
8173 ;; wiki link face or if the wiki link regexp matches.
8174 (when (or (markdown-range-property-any
8175 new-from new-to
'font-lock-face
8176 '(markdown-link-face markdown-missing-link-face
))
8178 markdown-regex-wiki-link new-to t
))
8179 ;; Unfontify existing fontification (start from scratch)
8180 (markdown-unfontify-region-wiki-links new-from new-to
)
8181 ;; Now do the fontification.
8182 (markdown-fontify-region-wiki-links new-from new-to
))))))
8183 (cursor-intangible-mode -
1)
8186 (set-buffer-modified-p nil
)))))
8188 (defun markdown-check-change-for-wiki-link-after-change (from to _
)
8189 "Check region between FROM and TO for wiki links and re-fontify as needed.
8190 Designed to be used with the `after-change-functions' hook."
8191 (markdown-check-change-for-wiki-link from to
))
8193 (defun markdown-fontify-buffer-wiki-links ()
8194 "Refontify all wiki links in the buffer."
8196 (markdown-check-change-for-wiki-link (point-min) (point-max)))
8198 (defun markdown-toggle-wiki-links (&optional arg
)
8199 "Toggle support for wiki links.
8200 With a prefix argument ARG, enable wiki link support if ARG is positive,
8201 and disable it otherwise."
8202 (interactive (list (or current-prefix-arg
'toggle
)))
8203 (setq markdown-enable-wiki-links
8204 (if (eq arg
'toggle
)
8205 (not markdown-enable-wiki-links
)
8206 (> (prefix-numeric-value arg
) 0)))
8207 (if markdown-enable-wiki-links
8208 (message "markdown-mode wiki link support enabled")
8209 (message "markdown-mode wiki link support disabled"))
8210 (markdown-reload-extensions))
8212 (defun markdown-setup-wiki-link-hooks ()
8213 "Add or remove hooks for fontifying wiki links.
8214 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
8215 ;; Anytime text changes make sure it gets fontified correctly
8216 (if (and markdown-enable-wiki-links
8217 markdown-wiki-link-fontify-missing
)
8218 (add-hook 'after-change-functions
8219 #'markdown-check-change-for-wiki-link-after-change t t
)
8220 (remove-hook 'after-change-functions
8221 #'markdown-check-change-for-wiki-link-after-change t
))
8222 ;; If we left the buffer there is a really good chance we were
8223 ;; creating one of the wiki link documents. Make sure we get
8224 ;; refontified when we come back.
8225 (if (and markdown-enable-wiki-links
8226 markdown-wiki-link-fontify-missing
)
8228 (add-hook 'window-configuration-change-hook
8229 #'markdown-fontify-buffer-wiki-links t t
)
8230 (markdown-fontify-buffer-wiki-links))
8231 (remove-hook 'window-configuration-change-hook
8232 #'markdown-fontify-buffer-wiki-links t
)
8233 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
8236 ;;; Following & Doing =========================================================
8238 (defun markdown-follow-thing-at-point (arg)
8239 "Follow thing at point if possible, such as a reference link or wiki link.
8240 Opens inline and reference links in a browser. Opens wiki links
8241 to other files in the current window, or the another window if
8243 See `markdown-follow-link-at-point' and
8244 `markdown-follow-wiki-link-at-point'."
8246 (cond ((markdown-link-p)
8247 (markdown--browse-url (markdown-link-url)))
8248 ((markdown-wiki-link-p)
8249 (markdown-follow-wiki-link-at-point arg
))
8251 (let* ((values (markdown-link-at-pos (point)))
8252 (url (nth 3 values
)))
8254 (user-error "Nothing to follow at point"))
8255 (markdown--browse-url url
)))))
8257 (defun markdown-do ()
8258 "Do something sensible based on context at point.
8259 Jumps between reference links and definitions; between footnote
8260 markers and footnote text."
8263 ;; Footnote definition
8264 ((markdown-footnote-text-positions)
8265 (markdown-footnote-return))
8267 ((markdown-footnote-marker-positions)
8268 (markdown-footnote-goto-text))
8270 ((thing-at-point-looking-at markdown-regex-link-reference
)
8271 (markdown-reference-goto-definition))
8272 ;; Reference definition
8273 ((thing-at-point-looking-at markdown-regex-reference-definition
)
8274 (markdown-reference-goto-link (match-string-no-properties 2)))
8276 ((or (markdown-link-p) (markdown-wiki-link-p))
8277 (markdown-follow-thing-at-point nil
))
8278 ;; GFM task list item
8279 ((markdown-gfm-task-list-item-at-point)
8280 (markdown-toggle-gfm-checkbox))
8282 ((markdown-table-at-point-p)
8283 (call-interactively #'markdown-table-align
))
8286 (markdown-insert-gfm-checkbox))))
8289 ;;; Miscellaneous =============================================================
8291 (defun markdown-compress-whitespace-string (str)
8292 "Compress whitespace in STR and return result.
8293 Leading and trailing whitespace is removed. Sequences of multiple
8294 spaces, tabs, and newlines are replaced with single spaces."
8295 (replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
8296 (replace-regexp-in-string "[ \t\n]+" " " str
)))
8298 (defun markdown--substitute-command-keys (string)
8299 "Like `substitute-command-keys' but, but prefers control characters.
8300 First pass STRING to `substitute-command-keys' and then
8301 substitute `C-i` for `TAB` and `C-m` for `RET`."
8302 (replace-regexp-in-string
8304 (replace-regexp-in-string
8305 "\\<RET\\>" "C-m" (substitute-command-keys string
) t
) t
))
8307 (defun markdown-line-number-at-pos (&optional pos
)
8308 "Return (narrowed) buffer line number at position POS.
8309 If POS is nil, use current buffer location.
8310 This is an exact copy of `line-number-at-pos' for use in emacs21."
8311 (let ((opoint (or pos
(point))) start
)
8313 (goto-char (point-min))
8314 (setq start
(point))
8317 (1+ (count-lines start
(point))))))
8319 (defun markdown-inside-link-p ()
8320 "Return t if point is within a link."
8322 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
8324 (defun markdown-line-is-reference-definition-p ()
8325 "Return whether the current line is a (non-footnote) reference definition."
8327 (move-beginning-of-line 1)
8328 (and (looking-at-p markdown-regex-reference-definition
)
8329 (not (looking-at-p "[ \t]*\\[^")))))
8331 (defun markdown-adaptive-fill-function ()
8332 "Return prefix for filling paragraph or nil if not determined."
8334 ;; List item inside blockquote
8335 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
8336 (replace-regexp-in-string
8337 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
8339 ((looking-at markdown-regex-blockquote
)
8340 (buffer-substring-no-properties (match-beginning 0) (match-end 2)))
8342 ((looking-at markdown-regex-list
)
8343 (match-string-no-properties 0))
8344 ;; Footnote definition
8345 ((looking-at-p markdown-regex-footnote-definition
)
8350 (defun markdown-fill-paragraph (&optional justify
)
8351 "Fill paragraph at or after point.
8352 This function is like \\[fill-paragraph], but it skips Markdown
8353 code blocks. If the point is in a code block, or just before one,
8354 do not fill. Otherwise, call `fill-paragraph' as usual. If
8355 JUSTIFY is non-nil, justify text as well. Since this function
8356 handles filling itself, it always returns t so that
8357 `fill-paragraph' doesn't run."
8359 (unless (or (markdown-code-block-at-point-p)
8361 (back-to-indentation)
8362 (skip-syntax-forward "-")
8363 (markdown-code-block-at-point-p)))
8364 (let ((fill-prefix (save-excursion
8365 (goto-char (line-beginning-position))
8366 (when (looking-at "\\([ \t]*>[ \t]*\\(?:>[ \t]*\\)+\\)")
8367 (match-string-no-properties 1)))))
8368 (fill-paragraph justify
)))
8371 (defun markdown-fill-forward-paragraph (&optional arg
)
8372 "Function used by `fill-paragraph' to move over ARG paragraphs.
8373 This is a `fill-forward-paragraph-function' for `markdown-mode'.
8374 It is called with a single argument specifying the number of
8375 paragraphs to move. Just like `forward-paragraph', it should
8376 return the number of paragraphs left to move."
8377 (or arg
(setq arg
1))
8379 ;; With positive ARG, move across ARG non-code-block paragraphs,
8380 ;; one at a time. When passing a code block, don't decrement ARG.
8381 (while (and (not (eobp))
8383 (= (forward-paragraph 1) 0)
8384 (or (markdown-code-block-at-pos (line-beginning-position 0))
8385 (setq arg
(1- arg
)))))
8386 ;; Move backward by one paragraph with negative ARG (always -1).
8387 (let ((start (point)))
8388 (setq arg
(forward-paragraph arg
))
8389 (while (and (not (eobp))
8390 (progn (move-to-left-margin) (not (eobp)))
8391 (looking-at-p paragraph-separate
))
8394 ;; Move point past whitespace following list marker.
8395 ((looking-at markdown-regex-list
)
8396 (goto-char (match-end 0)))
8397 ;; Move point past whitespace following pipe at beginning of line
8398 ;; to handle Pandoc line blocks.
8399 ((looking-at "^|\\s-*")
8400 (goto-char (match-end 0)))
8401 ;; Return point if the paragraph passed was a code block.
8402 ((markdown-code-block-at-pos (line-beginning-position 2))
8403 (goto-char start
)))))
8406 (defun markdown--inhibit-electric-quote ()
8407 "Function added to `electric-quote-inhibit-functions'.
8408 Return non-nil if the quote has been inserted inside a code block
8410 (let ((pos (1- (point))))
8411 (or (markdown-inline-code-at-pos pos
)
8412 (markdown-code-block-at-pos pos
))))
8415 ;;; Extension Framework =======================================================
8417 (defun markdown-reload-extensions ()
8418 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
8420 (when (derived-mode-p 'markdown-mode
)
8423 ;; Add or remove hooks related to extensions
8424 (markdown-setup-wiki-link-hooks)))
8426 (defun markdown-handle-local-variables ()
8427 "Run in `hack-local-variables-hook' to update font lock rules.
8428 Checks to see if there is actually a ‘markdown-mode’ file local variable
8429 before regenerating font-lock rules for extensions."
8430 (when (or (assoc 'markdown-enable-wiki-links file-local-variables-alist
)
8431 (assoc 'markdown-enable-math file-local-variables-alist
))
8432 (when (assoc 'markdown-enable-math file-local-variables-alist
)
8433 (markdown-toggle-math markdown-enable-math
))
8434 (markdown-reload-extensions)))
8437 ;;; Math Support ==============================================================
8439 (defconst markdown-mode-font-lock-keywords-math
8441 ;; Equation reference (eq:foo)
8442 '("\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" .
((1 markdown-markup-face
)
8443 (2 markdown-reference-face
)
8444 (3 markdown-markup-face
)))
8445 ;; Equation reference \eqref{foo}
8446 '("\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" .
((1 markdown-markup-face
)
8447 (2 markdown-reference-face
)
8448 (3 markdown-markup-face
))))
8449 "Font lock keywords to add and remove when toggling math support.")
8451 (defun markdown-toggle-math (&optional arg
)
8452 "Toggle support for inline and display LaTeX math expressions.
8453 With a prefix argument ARG, enable math mode if ARG is positive,
8454 and disable it otherwise. If called from Lisp, enable the mode
8455 if ARG is omitted or nil."
8456 (interactive (list (or current-prefix-arg
'toggle
)))
8457 (setq markdown-enable-math
8458 (if (eq arg
'toggle
)
8459 (not markdown-enable-math
)
8460 (> (prefix-numeric-value arg
) 0)))
8461 (if markdown-enable-math
8463 (font-lock-add-keywords
8464 'markdown-mode markdown-mode-font-lock-keywords-math
)
8465 (message "markdown-mode math support enabled"))
8466 (font-lock-remove-keywords
8467 'markdown-mode markdown-mode-font-lock-keywords-math
)
8468 (message "markdown-mode math support disabled"))
8469 (markdown-reload-extensions))
8472 ;;; GFM Checkboxes ============================================================
8474 (define-button-type 'markdown-gfm-checkbox-button
8476 'face
'markdown-gfm-checkbox-face
8477 'mouse-face
'markdown-highlight-face
8478 'action
#'markdown-toggle-gfm-checkbox-button
)
8480 (defun markdown-gfm-task-list-item-at-point (&optional bounds
)
8481 "Return non-nil if there is a GFM task list item at the point.
8482 Optionally, the list item BOUNDS may be given if available, as
8483 returned by `markdown-cur-list-item-bounds'. When a task list item
8484 is found, the return value is the same value returned by
8485 `markdown-cur-list-item-bounds'."
8487 (setq bounds
(markdown-cur-list-item-bounds)))
8488 (> (length (nth 5 bounds
)) 0))
8490 (defun markdown-insert-gfm-checkbox ()
8491 "Add GFM checkbox at point.
8493 Returns nil if non-applicable."
8495 (let ((bounds (markdown-cur-list-item-bounds)))
8497 (unless (cl-sixth bounds
)
8498 (let ((pos (+ (cl-first bounds
) (cl-fourth bounds
)))
8506 (syntax-propertize (+ (cl-second bounds
) 4))
8508 (unless (save-excursion
8509 (back-to-indentation)
8510 (or (markdown-list-item-at-point-p)
8511 (markdown-heading-at-point)
8512 (markdown-in-comment-p)
8513 (markdown-code-block-at-point-p)))
8514 (let ((pos (save-excursion
8515 (back-to-indentation)
8517 (markup (concat (or (save-excursion
8518 (beginning-of-line 0)
8519 (cl-fifth (markdown-cur-list-item-bounds)))
8520 markdown-unordered-list-item-prefix
)
8528 (syntax-propertize (line-end-position))
8531 (defun markdown-toggle-gfm-checkbox ()
8532 "Toggle GFM checkbox at point.
8533 Returns the resulting status as a string, either \"[x]\" or \"[ ]\".
8534 Returns nil if there is no task list item at the point."
8538 (let ((bounds (markdown-cur-list-item-bounds)))
8540 ;; Move to beginning of task list item
8541 (goto-char (cl-first bounds
))
8542 ;; Advance to column of first non-whitespace after marker
8543 (forward-char (cl-fourth bounds
))
8544 (cond ((looking-at "\\[ \\]")
8546 (if markdown-gfm-uppercase-checkbox
"[X]" "[x]")
8548 (match-string-no-properties 0))
8549 ((looking-at "\\[[xX]\\]")
8550 (replace-match "[ ]" nil t
)
8551 (match-string-no-properties 0))))))))
8553 (defun markdown-toggle-gfm-checkbox-button (button)
8554 "Toggle GFM checkbox BUTTON on click."
8557 (goto-char (button-start button
))
8558 (markdown-toggle-gfm-checkbox))))
8560 (defun markdown-make-gfm-checkboxes-buttons (start end
)
8561 "Make GFM checkboxes buttons in region between START and END."
8564 (let ((case-fold-search t
))
8566 (while (re-search-forward markdown-regex-gfm-checkbox end t
)
8567 (make-button (match-beginning 1) (match-end 1)
8568 :type
'markdown-gfm-checkbox-button
))))))
8570 ;; Called when any modification is made to buffer text.
8571 (defun markdown-gfm-checkbox-after-change-function (beg end _
)
8572 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
8573 BEG and END are the limits of scanned region."
8576 ;; Rescan between start of line from `beg' and start of line after `end'.
8577 (markdown-make-gfm-checkboxes-buttons
8578 (progn (goto-char beg
) (beginning-of-line) (point))
8579 (progn (goto-char end
) (forward-line 1) (point))))))
8581 (defun markdown-remove-gfm-checkbox-overlays ()
8582 "Remove all GFM checkbox overlays in buffer."
8586 (remove-overlays nil nil
'face
'markdown-gfm-checkbox-face
))))
8589 ;;; Display inline image ======================================================
8591 (defvar-local markdown-inline-image-overlays nil
)
8593 (defun markdown-remove-inline-images ()
8594 "Remove inline image overlays from image links in the buffer.
8595 This can be toggled with `markdown-toggle-inline-images'
8596 or \\[markdown-toggle-inline-images]."
8598 (mapc #'delete-overlay markdown-inline-image-overlays
)
8599 (setq markdown-inline-image-overlays nil
))
8601 (defcustom markdown-display-remote-images nil
8602 "If non-nil, download and display remote images.
8603 See also `markdown-inline-image-overlays'.
8605 Only image URLs specified with a protocol listed in
8606 `markdown-remote-image-protocols' are displayed."
8610 (defcustom markdown-remote-image-protocols
'("https")
8611 "List of protocols to use to download remote images.
8612 See also `markdown-display-remote-images'."
8614 :type
'(repeat string
))
8616 (defvar markdown--remote-image-cache
8617 (make-hash-table :test
'equal
)
8618 "A map from URLs to image paths.")
8620 (defun markdown--get-remote-image (url)
8621 "Retrieve the image path for a given URL."
8622 (or (gethash url markdown--remote-image-cache
)
8623 (let ((dl-path (make-temp-file "markdown-mode--image")))
8625 (url-copy-file url dl-path t
)
8626 (puthash url dl-path markdown--remote-image-cache
))))
8628 (defun markdown-display-inline-images ()
8629 "Add inline image overlays to image links in the buffer.
8630 This can be toggled with `markdown-toggle-inline-images'
8631 or \\[markdown-toggle-inline-images]."
8633 (unless (display-images-p)
8634 (error "Cannot show images"))
8638 (goto-char (point-min))
8639 (while (re-search-forward markdown-regex-link-inline nil t
)
8640 (let* ((start (match-beginning 0))
8641 (imagep (match-beginning 1))
8643 (file (match-string-no-properties 6)))
8645 (not (zerop (length file
))))
8646 (unless (file-exists-p file
)
8647 (let* ((download-file (funcall markdown-translate-filename-function file
))
8648 (valid-url (ignore-errors
8649 (member (downcase (url-type (url-generic-parse-url download-file
)))
8650 markdown-remote-image-protocols
))))
8651 (if (and markdown-display-remote-images valid-url
)
8652 (setq file
(markdown--get-remote-image download-file
))
8653 (when (not valid-url
)
8654 ;; strip query parameter
8655 (setq file
(replace-regexp-in-string "?.+\\'" "" file
))
8656 (unless (file-exists-p file
)
8657 (setq file
(url-unhex-string file
)))))))
8658 (when (file-exists-p file
)
8659 (let* ((abspath (if (file-name-absolute-p file
)
8661 (concat default-directory file
)))
8663 (cond ((and markdown-max-image-size
8664 (image-type-available-p 'imagemagick
))
8666 abspath
'imagemagick nil
8667 :max-width
(car markdown-max-image-size
)
8668 :max-height
(cdr markdown-max-image-size
)))
8669 (markdown-max-image-size
8670 (create-image abspath nil nil
8671 :max-width
(car markdown-max-image-size
)
8672 :max-height
(cdr markdown-max-image-size
)))
8673 (t (create-image abspath
)))))
8675 (let ((ov (make-overlay start end
)))
8676 (overlay-put ov
'display image
)
8677 (overlay-put ov
'face
'default
)
8678 (push ov markdown-inline-image-overlays
)))))))))))
8680 (defun markdown-toggle-inline-images ()
8681 "Toggle inline image overlays in the buffer."
8683 (if markdown-inline-image-overlays
8684 (markdown-remove-inline-images)
8685 (markdown-display-inline-images)))
8688 ;;; GFM Code Block Fontification ==============================================
8690 (defcustom markdown-fontify-code-blocks-natively nil
8691 "When non-nil, fontify code in code blocks using the native major mode.
8692 This only works for fenced code blocks where the language is
8693 specified where we can automatically determine the appropriate
8694 mode to use. The language to mode mapping may be customized by
8695 setting the variable `markdown-code-lang-modes'."
8699 :package-version
'(markdown-mode .
"2.3"))
8701 (defcustom markdown-fontify-code-block-default-mode nil
8702 "Default mode to use to fontify code blocks.
8703 This mode is used when automatic detection fails, such as for GFM
8704 code blocks with no language specified."
8706 :type
'(choice function
(const :tag
"None" nil
))
8707 :package-version
'(markdown-mode .
"2.4"))
8709 (defun markdown-toggle-fontify-code-blocks-natively (&optional arg
)
8710 "Toggle the native fontification of code blocks.
8711 With a prefix argument ARG, enable if ARG is positive,
8712 and disable otherwise."
8713 (interactive (list (or current-prefix-arg
'toggle
)))
8714 (setq markdown-fontify-code-blocks-natively
8715 (if (eq arg
'toggle
)
8716 (not markdown-fontify-code-blocks-natively
)
8717 (> (prefix-numeric-value arg
) 0)))
8718 (if markdown-fontify-code-blocks-natively
8719 (message "markdown-mode native code block fontification enabled")
8720 (message "markdown-mode native code block fontification disabled"))
8721 (markdown-reload-extensions))
8723 ;; This is based on `org-src-lang-modes' from org-src.el
8724 (defcustom markdown-code-lang-modes
8725 '(("ocaml" . tuareg-mode
) ("elisp" . emacs-lisp-mode
) ("ditaa" . artist-mode
)
8726 ("asymptote" . asy-mode
) ("dot" . fundamental-mode
) ("sqlite" . sql-mode
)
8727 ("calc" . fundamental-mode
) ("C" . c-mode
) ("cpp" . c
++-mode
)
8728 ("C++" . c
++-mode
) ("screen" . shell-script-mode
) ("shell" . sh-mode
)
8730 "Alist mapping languages to their major mode.
8731 The key is the language name, the value is the major mode. For
8732 many languages this is simple, but for language where this is not
8733 the case, this variable provides a way to simplify things on the
8734 user side. For example, there is no ocaml-mode in Emacs, but the
8735 mode to use is `tuareg-mode'."
8739 (string "Language name")
8740 (symbol "Major mode")))
8741 :package-version
'(markdown-mode .
"2.3"))
8743 (defun markdown-get-lang-mode (lang)
8744 "Return major mode that should be used for LANG.
8745 LANG is a string, and the returned major mode is a symbol."
8748 (list (cdr (assoc lang markdown-code-lang-modes
))
8749 (cdr (assoc (downcase lang
) markdown-code-lang-modes
))
8750 (intern (concat lang
"-mode"))
8751 (intern (concat (downcase lang
) "-mode")))))
8753 (defun markdown-fontify-code-blocks-generic (matcher last
)
8754 "Add text properties to next code block from point to LAST.
8755 Use matching function MATCHER."
8756 (when (funcall matcher last
)
8759 (let* ((start (match-beginning 0))
8761 ;; Find positions outside opening and closing backquotes.
8762 (bol-prev (progn (goto-char start
)
8763 (if (bolp) (line-beginning-position 0) (line-beginning-position))))
8764 (eol-next (progn (goto-char end
)
8765 (if (bolp) (line-beginning-position 2) (line-beginning-position 3))))
8767 (if (and markdown-fontify-code-blocks-natively
8768 (or (setq lang
(markdown-code-block-lang))
8769 markdown-fontify-code-block-default-mode
))
8770 (markdown-fontify-code-block-natively lang start end
)
8771 (add-text-properties start end
'(face markdown-pre-face
)))
8772 ;; Set background for block as well as opening and closing lines.
8773 (font-lock-append-text-property
8774 bol-prev eol-next
'face
'markdown-code-face
)
8775 ;; Set invisible property for lines before and after, including newline.
8776 (add-text-properties bol-prev start
'(invisible markdown-markup
))
8777 (add-text-properties end eol-next
'(invisible markdown-markup
)))))
8780 (defun markdown-fontify-gfm-code-blocks (last)
8781 "Add text properties to next GFM code block from point to LAST."
8782 (markdown-fontify-code-blocks-generic 'markdown-match-gfm-code-blocks last
))
8784 (defun markdown-fontify-fenced-code-blocks (last)
8785 "Add text properties to next tilde fenced code block from point to LAST."
8786 (markdown-fontify-code-blocks-generic 'markdown-match-fenced-code-blocks last
))
8788 ;; Based on `org-src-font-lock-fontify-block' from org-src.el.
8789 (defun markdown-fontify-code-block-natively (lang start end
)
8790 "Fontify given GFM or fenced code block.
8791 This function is called by Emacs for automatic fontification when
8792 `markdown-fontify-code-blocks-natively' is non-nil. LANG is the
8793 language used in the block. START and END specify the block
8795 (let ((lang-mode (if lang
(markdown-get-lang-mode lang
)
8796 markdown-fontify-code-block-default-mode
)))
8797 (when (fboundp lang-mode
)
8798 (let ((string (buffer-substring-no-properties start end
))
8799 (modified (buffer-modified-p))
8800 (markdown-buffer (current-buffer)) pos next
)
8801 (remove-text-properties start end
'(face nil
))
8802 (with-current-buffer
8804 (concat " markdown-code-fontification:" (symbol-name lang-mode
)))
8805 ;; Make sure that modification hooks are not inhibited in
8806 ;; the org-src-fontification buffer in case we're called
8807 ;; from `jit-lock-function' (Bug#25132).
8808 (let ((inhibit-modification-hooks nil
))
8809 (delete-region (point-min) (point-max))
8810 (insert string
" ")) ;; so there's a final property change
8811 (unless (eq major-mode lang-mode
) (funcall lang-mode
))
8813 (setq pos
(point-min))
8814 (while (setq next
(next-single-property-change pos
'face
))
8815 (let ((val (get-text-property pos
'face
)))
8818 (+ start
(1- pos
)) (1- (+ start next
)) 'face
8819 val markdown-buffer
)))
8821 (add-text-properties
8823 '(font-lock-fontified t fontified t font-lock-multiline t
))
8824 (set-buffer-modified-p modified
)))))
8826 (require 'edit-indirect nil t
)
8827 (defvar edit-indirect-guess-mode-function
)
8828 (defvar edit-indirect-after-commit-functions
)
8830 (defun markdown--edit-indirect-after-commit-function (beg end
)
8831 "Corrective logic run on code block content from lines BEG to END.
8832 Restores code block indentation from BEG to END, and ensures trailing newlines
8833 at the END of code blocks."
8834 ;; ensure trailing newlines
8836 (unless (eq (char-before) ?
\n)
8838 ;; restore code block indentation
8839 (goto-char (- beg
1))
8840 (let ((block-indentation (current-indentation)))
8841 (when (> block-indentation
0)
8842 (indent-rigidly beg end block-indentation
)))
8845 (defun markdown-edit-code-block ()
8846 "Edit Markdown code block in an indirect buffer."
8849 (if (fboundp 'edit-indirect-region
)
8850 (let* ((bounds (markdown-get-enclosing-fenced-block-construct))
8851 (begin (and bounds
(not (null (nth 0 bounds
))) (goto-char (nth 0 bounds
)) (line-beginning-position 2)))
8852 (end (and bounds
(not (null (nth 1 bounds
))) (goto-char (nth 1 bounds
)) (line-beginning-position 1))))
8854 (let* ((indentation (and (goto-char (nth 0 bounds
)) (current-indentation)))
8855 (lang (markdown-code-block-lang))
8856 (mode (or (and lang
(markdown-get-lang-mode lang
))
8857 markdown-edit-code-block-default-mode
))
8858 (edit-indirect-guess-mode-function
8859 (lambda (_parent-buffer _beg _end
)
8861 (indirect-buf (edit-indirect-region begin end
'display-buffer
)))
8862 ;; reset `sh-shell' when indirect buffer
8863 (when (and (not (member system-type
'(ms-dos windows-nt
)))
8864 (member mode
'(shell-script-mode sh-mode
))
8865 (member lang
(append
8866 (mapcar (lambda (e) (symbol-name (car e
)))
8868 '("csh" "rc" "sh"))))
8869 (with-current-buffer indirect-buf
8870 (sh-set-shell lang
)))
8871 (when (> indentation
0) ;; un-indent in edit-indirect buffer
8872 (with-current-buffer indirect-buf
8873 (indent-rigidly (point-min) (point-max) (- indentation
)))))
8874 (user-error "Not inside a GFM or tilde fenced code block")))
8875 (when (y-or-n-p "Package edit-indirect needed to edit code blocks. Install it now? ")
8876 (progn (package-refresh-contents)
8877 (package-install 'edit-indirect
)
8878 (markdown-edit-code-block))))))
8881 ;;; Table Editing =============================================================
8883 ;; These functions were originally adapted from `org-table.el'.
8885 ;; General helper functions
8887 (defmacro markdown--with-gensyms
(symbols &rest body
)
8888 (declare (debug (sexp body
)) (indent 1))
8889 `(let ,(mapcar (lambda (s)
8890 `(,s
(make-symbol (concat "--" (symbol-name ',s
)))))
8894 (defun markdown--split-string (string &optional separators
)
8895 "Splits STRING into substrings at SEPARATORS.
8896 SEPARATORS is a regular expression. If nil it defaults to
8897 `split-string-default-separators'. This version returns no empty
8898 strings if there are matches at the beginning and end of string."
8899 (let ((start 0) notfirst list
)
8900 (while (and (string-match
8901 (or separators split-string-default-separators
)
8904 (= start
(match-beginning 0))
8905 (< start
(length string
)))
8907 (< (match-beginning 0) (length string
)))
8909 (or (eq (match-beginning 0) 0)
8910 (and (eq (match-beginning 0) (match-end 0))
8911 (eq (match-beginning 0) start
))
8912 (push (substring string start
(match-beginning 0)) list
))
8913 (setq start
(match-end 0)))
8914 (or (eq start
(length string
))
8915 (push (substring string start
) list
))
8918 (defun markdown--string-width (s)
8919 "Return width of string S.
8920 This version ignores characters with invisibility property
8923 (when (or (eq t buffer-invisibility-spec
)
8924 (member 'markdown-markup buffer-invisibility-spec
))
8925 (while (setq b
(text-property-any
8927 'invisible
'markdown-markup s
))
8930 (substring s
(or (next-single-property-change
8935 (defun markdown--remove-invisible-markup (s)
8936 "Remove Markdown markup from string S.
8937 This version removes characters with invisibility property
8940 (while (setq b
(text-property-any
8942 'invisible
'markdown-markup s
))
8945 (substring s
(or (next-single-property-change
8950 ;; Functions for maintaining tables
8952 (defvar markdown-table-at-point-p-function
#'markdown--table-at-point-p
8953 "Function to decide if point is inside a table.
8955 The indirection serves to differentiate between standard markdown
8956 tables and gfm tables which are less strict about the markup.")
8958 (defconst markdown-table-line-regexp
"^[ \t]*|"
8959 "Regexp matching any line inside a table.")
8961 (defconst markdown-table-hline-regexp
"^[ \t]*|[-:]"
8962 "Regexp matching hline inside a table.")
8964 (defconst markdown-table-dline-regexp
"^[ \t]*|[^-:]"
8965 "Regexp matching dline inside a table.")
8967 (defun markdown-table-at-point-p ()
8968 "Return non-nil when point is inside a table."
8969 (funcall markdown-table-at-point-p-function
))
8971 (defun markdown--table-at-point-p ()
8972 "Return non-nil when point is inside a table."
8975 (and (looking-at-p markdown-table-line-regexp
)
8976 (not (markdown-code-block-at-point-p)))))
8978 (defconst gfm-table-line-regexp
"^.?*|"
8979 "Regexp matching any line inside a table.")
8981 (defconst gfm-table-hline-regexp
"^-+\\(|-\\)+"
8982 "Regexp matching hline inside a table.")
8984 ;; GFM simplified tables syntax is as follows:
8985 ;; - A header line for the column names, this is any text
8986 ;; separated by `|'.
8987 ;; - Followed by a string -|-|- ..., the number of dashes is optional
8988 ;; but must be higher than 1. The number of separators should match
8989 ;; the number of columns.
8990 ;; - Followed by the rows of data, which has the same format as the
8998 (defun gfm--table-at-point-p ()
8999 "Return non-nil when point is inside a gfm-compatible table."
9000 (or (markdown--table-at-point-p)
9003 (when (looking-at-p gfm-table-line-regexp
)
9004 ;; we might be at the first line of the table, check if the
9005 ;; line below is the hline
9008 (looking-at-p gfm-table-hline-regexp
))
9009 ;; go up to find the header
9011 (while (looking-at-p gfm-table-line-regexp
)
9013 ((looking-at-p gfm-table-hline-regexp
)
9020 (defun markdown-table-hline-at-point-p ()
9021 "Return non-nil when point is on a hline in a table.
9022 This function assumes point is on a table."
9025 (looking-at-p markdown-table-hline-regexp
)))
9027 (defun markdown-table-begin ()
9028 "Find the beginning of the table and return its position.
9029 This function assumes point is on a table."
9031 (while (and (not (bobp))
9032 (markdown-table-at-point-p))
9035 (markdown-table-at-point-p))
9039 (defun markdown-table-end ()
9040 "Find the end of the table and return its position.
9041 This function assumes point is on a table."
9043 (while (and (not (eobp))
9044 (markdown-table-at-point-p))
9048 (defun markdown-table-get-dline ()
9049 "Return index of the table data line at point.
9050 This function assumes point is on a table."
9051 (let ((pos (point)) (end (markdown-table-end)) (cnt 0))
9053 (goto-char (markdown-table-begin))
9054 (while (and (re-search-forward
9055 markdown-table-dline-regexp end t
)
9057 (< (line-end-position) pos
))))
9060 (defun markdown--thing-at-wiki-link (pos)
9061 (when markdown-enable-wiki-links
9065 (thing-at-point-looking-at markdown-regex-wiki-link
)))))
9067 (defun markdown-table-get-column ()
9068 "Return table column at point.
9069 This function assumes point is on a table."
9070 (let ((pos (point)) (cnt 0))
9073 (while (search-forward "|" pos t
)
9074 (when (and (not (looking-back "\\\\|" (line-beginning-position)))
9075 (not (markdown--thing-at-wiki-link (match-beginning 0))))
9076 (setq cnt
(1+ cnt
)))))
9079 (defun markdown-table-get-cell (&optional n
)
9080 "Return the content of the cell in column N of current row.
9081 N defaults to column at point. This function assumes point is on
9083 (and n
(markdown-table-goto-column n
))
9084 (skip-chars-backward "^|\n") (backward-char 1)
9085 (if (looking-at "|[^|\r\n]*")
9086 (let* ((pos (match-beginning 0))
9087 (val (buffer-substring (1+ pos
) (match-end 0))))
9088 (goto-char (min (line-end-position) (+ 2 pos
)))
9090 (setq val
(replace-regexp-in-string "\\`[ \t]+" "" val
)
9091 val
(replace-regexp-in-string "[ \t]+\\'" "" val
)))
9092 (forward-char 1) ""))
9094 (defun markdown-table-goto-dline (n)
9095 "Go to the Nth data line in the table at point.
9096 Return t when the line exists, nil otherwise. This function
9097 assumes point is on a table."
9098 (goto-char (markdown-table-begin))
9099 (let ((end (markdown-table-end)) (cnt 0))
9100 (while (and (re-search-forward
9101 markdown-table-dline-regexp end t
)
9102 (< (setq cnt
(1+ cnt
)) n
)))
9105 (defun markdown-table-goto-column (n &optional on-delim
)
9106 "Go to the Nth column in the table line at point.
9107 With optional argument ON-DELIM, stop with point before the left
9108 delimiter of the cell. If there are less than N cells, just go
9109 beyond the last delimiter. This function assumes point is on a
9111 (beginning-of-line 1)
9113 (while (and (> n
0) (search-forward "|" (line-end-position) t
))
9114 (when (and (not (looking-back "\\\\|" (line-beginning-position)))
9115 (not (markdown--thing-at-wiki-link (match-beginning 0))))
9119 (when (looking-at " ") (forward-char 1)))))
9121 (defmacro markdown-table-save-cell
(&rest body
)
9122 "Save cell at point, execute BODY and restore cell.
9123 This function assumes point is on a table."
9124 (declare (debug (body)))
9125 (markdown--with-gensyms (line column
)
9126 `(let ((,line
(copy-marker (line-beginning-position)))
9127 (,column
(markdown-table-get-column)))
9131 (markdown-table-goto-column ,column
)
9132 (set-marker ,line nil
)))))
9134 (defun markdown-table-blank-line (s)
9135 "Convert a table line S into a line with blank cells."
9136 (if (string-match "^[ \t]*|-" s
)
9138 (lambda (x) (if (member x
'(?| ?
+)) "|" " "))
9142 (goto-char (point-min))
9143 (when (re-search-forward "|" nil t
)
9146 (while (re-search-forward "|" nil t
)
9147 (when (and (not (eql (char-before (match-beginning 0)) ?
\\))
9148 (not (markdown--thing-at-wiki-link (match-beginning 0))))
9149 (push (make-string (- (match-beginning 0) cur
) ?
) ret
)
9150 (setq cur
(match-end 0))))
9151 (format "|%s|" (string-join (nreverse ret
) "|")))))))
9153 (defun markdown-table-colfmt (fmtspec)
9154 "Process column alignment specifier FMTSPEC for tables."
9155 (when (stringp fmtspec
)
9157 (cond ((string-match-p "^:.*:$" x
) 'c
)
9158 ((string-match-p "^:" x
) 'l
)
9159 ((string-match-p ":$" x
) 'r
)
9161 (markdown--split-string fmtspec
"\\s-*|\\s-*"))))
9163 (defun markdown--first-column-p (bar-pos)
9167 (looking-back "^\\s-*" (line-beginning-position)))))
9169 (defun markdown--table-line-to-columns (line)
9172 (goto-char (point-min))
9175 (while (re-search-forward "\\s-*\\(|\\)\\s-*" nil t
)
9176 (if (markdown--first-column-p (match-beginning 1))
9177 (setq cur
(match-end 0))
9178 (cond ((eql (char-before (match-beginning 1)) ?
\\)
9180 (goto-char (match-end 1)))
9181 ((markdown--thing-at-wiki-link (match-beginning 1))) ;; do nothing
9183 (push (buffer-substring-no-properties cur
(match-beginning 0)) ret
)
9184 (setq cur
(match-end 0))))))
9185 (when (< cur
(length line
))
9186 (push (buffer-substring-no-properties cur
(point-max)) ret
))
9189 (defun markdown-table-align ()
9190 "Align table at point.
9191 This function assumes point is on a table."
9193 (let ((begin (markdown-table-begin))
9194 (end (copy-marker (markdown-table-end))))
9195 (markdown-table-save-cell
9198 ;; Store table indent
9199 (indent (progn (looking-at "[ \t]*") (match-string 0)))
9200 ;; Split table in lines and save column format specifier
9201 (lines (mapcar (lambda (l)
9202 (if (string-match-p "\\`[ \t]*|[ \t]*[-:]" l
)
9203 (progn (setq fmtspec
(or fmtspec l
)) nil
) l
))
9204 (markdown--split-string (buffer-substring begin end
) "\n")))
9205 ;; Split lines in cells
9206 (cells (mapcar (lambda (l) (markdown--table-line-to-columns l
))
9208 ;; Calculate maximum number of cells in a line
9210 (apply #'max
(mapcar #'length cells
))
9211 (user-error "Empty table")))
9212 ;; Empty cells to fill short lines
9213 (emptycells (make-list maxcells
""))
9215 ;; Calculate maximum width for each column
9216 (dotimes (i maxcells
)
9217 (let ((column (mapcar (lambda (x) (or (nth i x
) "")) cells
)))
9218 (push (apply #'max
1 (mapcar #'markdown--string-width column
))
9220 (setq maxwidths
(nreverse maxwidths
))
9221 ;; Process column format specifier
9222 (setq fmtspec
(markdown-table-colfmt fmtspec
))
9223 ;; Compute formats needed for output of table lines
9224 (let ((hfmt (concat indent
"|"))
9225 (rfmt (concat indent
"|"))
9227 (dolist (width maxwidths
(setq hfmt
(concat (substring hfmt
0 -
1) "|")))
9228 (setq fmt
(pop fmtspec
))
9229 (cond ((equal fmt
'l
) (setq hfmt1
":%s-|" rfmt1
" %%-%ds |"))
9230 ((equal fmt
'r
) (setq hfmt1
"-%s:|" rfmt1
" %%%ds |"))
9231 ((equal fmt
'c
) (setq hfmt1
":%s:|" rfmt1
" %%-%ds |"))
9232 (t (setq hfmt1
"-%s-|" rfmt1
" %%-%ds |")))
9233 (setq rfmt
(concat rfmt
(format rfmt1 width
)))
9234 (setq hfmt
(concat hfmt
(format hfmt1
(make-string width ?-
)))))
9235 ;; Replace modified lines only
9236 (dolist (line lines
)
9237 (let ((line (if line
9238 (apply #'format rfmt
(append (pop cells
) emptycells
))
9240 (previous (buffer-substring (point) (line-end-position))))
9241 (if (equal previous line
)
9244 (delete-region (point) (line-beginning-position 2))))))
9245 (set-marker end nil
)))))
9247 (defun markdown-table-insert-row (&optional arg
)
9248 "Insert a new row above the row at point into the table.
9249 With optional argument ARG, insert below the current row."
9251 (unless (markdown-table-at-point-p)
9252 (user-error "Not at a table"))
9253 (let* ((line (buffer-substring
9254 (line-beginning-position) (line-end-position)))
9255 (new (markdown-table-blank-line line
)))
9256 (beginning-of-line (if arg
2 1))
9257 (unless (bolp) (insert "\n"))
9258 (insert-before-markers new
"\n")
9259 (beginning-of-line 0)
9260 (re-search-forward "| ?" (line-end-position) t
)))
9262 (defun markdown-table-delete-row ()
9263 "Delete row or horizontal line at point from the table."
9265 (unless (markdown-table-at-point-p)
9266 (user-error "Not at a table"))
9267 (let ((col (current-column)))
9268 (kill-region (line-beginning-position)
9269 (min (1+ (line-end-position)) (point-max)))
9270 (unless (markdown-table-at-point-p) (beginning-of-line 0))
9271 (move-to-column col
)))
9273 (defun markdown-table-move-row (&optional up
)
9274 "Move table line at point down.
9275 With optional argument UP, move it up."
9277 (unless (markdown-table-at-point-p)
9278 (user-error "Not at a table"))
9279 (let* ((col (current-column)) (pos (point))
9280 (tonew (if up
0 2)) txt
)
9281 (beginning-of-line tonew
)
9282 (unless (markdown-table-at-point-p)
9283 (goto-char pos
) (user-error "Cannot move row further"))
9284 (goto-char pos
) (beginning-of-line 1) (setq pos
(point))
9285 (setq txt
(buffer-substring (point) (1+ (line-end-position))))
9286 (delete-region (point) (1+ (line-end-position)))
9287 (beginning-of-line tonew
)
9288 (insert txt
) (beginning-of-line 0)
9289 (move-to-column col
)))
9291 (defun markdown-table-move-row-up ()
9292 "Move table row at point up."
9294 (markdown-table-move-row 'up
))
9296 (defun markdown-table-move-row-down ()
9297 "Move table row at point down."
9299 (markdown-table-move-row nil
))
9301 (defun markdown-table-insert-column ()
9302 "Insert a new table column."
9304 (unless (markdown-table-at-point-p)
9305 (user-error "Not at a table"))
9306 (let* ((col (max 1 (markdown-table-get-column)))
9307 (begin (markdown-table-begin))
9308 (end (copy-marker (markdown-table-end))))
9309 (markdown-table-save-cell
9311 (while (< (point) end
)
9312 (markdown-table-goto-column col t
)
9313 (if (markdown-table-hline-at-point-p)
9317 (set-marker end nil
)
9318 (when markdown-table-align-p
9319 (markdown-table-align))))
9321 (defun markdown-table-delete-column ()
9322 "Delete column at point from table."
9324 (unless (markdown-table-at-point-p)
9325 (user-error "Not at a table"))
9326 (let ((col (markdown-table-get-column))
9327 (begin (markdown-table-begin))
9328 (end (copy-marker (markdown-table-end))))
9329 (markdown-table-save-cell
9331 (while (< (point) end
)
9332 (markdown-table-goto-column col t
)
9333 (and (looking-at "|\\(?:\\\\|\\|[^|\n]\\)+|")
9334 (replace-match "|"))
9336 (set-marker end nil
)
9337 (markdown-table-goto-column (max 1 (1- col
)))
9338 (when markdown-table-align-p
9339 (markdown-table-align))))
9341 (defun markdown-table-move-column (&optional left
)
9342 "Move table column at point to the right.
9343 With optional argument LEFT, move it to the left."
9345 (unless (markdown-table-at-point-p)
9346 (user-error "Not at a table"))
9347 (let* ((col (markdown-table-get-column))
9348 (col1 (if left
(1- col
) col
))
9349 (colpos (if left
(1- col
) (1+ col
)))
9350 (begin (markdown-table-begin))
9351 (end (copy-marker (markdown-table-end))))
9352 (when (and left
(= col
1))
9353 (user-error "Cannot move column further left"))
9354 (when (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
9355 (user-error "Cannot move column further right"))
9356 (markdown-table-save-cell
9358 (while (< (point) end
)
9359 (markdown-table-goto-column col1 t
)
9360 (when (looking-at "|\\(\\(?:\\\\|\\|[^|\n]\\|\\)+\\)|\\(\\(?:\\\\|\\|[^|\n]\\|\\)+\\)|")
9361 (replace-match "|\\2|\\1|"))
9363 (set-marker end nil
)
9364 (markdown-table-goto-column colpos
)
9365 (when markdown-table-align-p
9366 (markdown-table-align))))
9368 (defun markdown-table-move-column-left ()
9369 "Move table column at point to the left."
9371 (markdown-table-move-column 'left
))
9373 (defun markdown-table-move-column-right ()
9374 "Move table column at point to the right."
9376 (markdown-table-move-column nil
))
9378 (defun markdown-table-next-row ()
9379 "Go to the next row (same column) in the table.
9380 Create new table lines if required."
9382 (unless (markdown-table-at-point-p)
9383 (user-error "Not at a table"))
9384 (if (or (looking-at "[ \t]*$")
9385 (save-excursion (skip-chars-backward " \t") (bolp)))
9387 (when markdown-table-align-p
9388 (markdown-table-align))
9389 (let ((col (markdown-table-get-column)))
9390 (beginning-of-line 2)
9391 (if (or (not (markdown-table-at-point-p))
9392 (markdown-table-hline-at-point-p))
9394 (beginning-of-line 0)
9395 (markdown-table-insert-row 'below
)))
9396 (markdown-table-goto-column col
)
9397 (skip-chars-backward "^|\n\r")
9398 (when (looking-at " ") (forward-char 1)))))
9400 (defun markdown-table-forward-cell ()
9401 "Go to the next cell in the table.
9402 Create new table lines if required."
9404 (unless (markdown-table-at-point-p)
9405 (user-error "Not at a table"))
9406 (when markdown-table-align-p
9407 (markdown-table-align))
9408 (let ((end (markdown-table-end)))
9409 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9412 (re-search-forward "\\(?:^\\|[^\\]\\)|" end
)
9413 (when (looking-at "[ \t]*$")
9414 (re-search-forward "\\(?:^\\|[^\\]:\\)|" end
))
9415 (when (and (looking-at "[-:]")
9416 (re-search-forward "^\\(?:[ \t]*\\|[^\\]\\)|\\([^-:]\\)" end t
))
9417 (goto-char (match-beginning 1)))
9418 (if (looking-at "[-:]")
9420 (beginning-of-line 0)
9421 (markdown-table-insert-row 'below
))
9422 (when (looking-at " ") (forward-char 1))))
9423 (error (markdown-table-insert-row 'below
)))))
9425 (defun markdown-table-backward-cell ()
9426 "Go to the previous cell in the table."
9428 (unless (markdown-table-at-point-p)
9429 (user-error "Not at a table"))
9430 (when markdown-table-align-p
9431 (markdown-table-align))
9432 (when (markdown-table-hline-at-point-p) (beginning-of-line 1))
9435 (re-search-backward "\\(?:^\\|[^\\]\\)|" (markdown-table-begin))
9436 ;; When this function is called while in the first cell in a
9437 ;; table, the point will now be at the beginning of a line. In
9438 ;; this case, we need to move past one additional table
9439 ;; boundary, the end of the table on the previous line.
9440 (when (= (point) (line-beginning-position))
9441 (re-search-backward "\\(?:^\\|[^\\]\\)|" (markdown-table-begin)))
9442 (re-search-backward "\\(?:^\\|[^\\]\\)|" (markdown-table-begin)))
9443 (error (user-error "Cannot move to previous table cell")))
9444 (when (looking-at "\\(?:^\\|[^\\]\\)| ?") (goto-char (match-end 0)))
9446 ;; This may have dropped point on the hline.
9447 (when (markdown-table-hline-at-point-p)
9448 (markdown-table-backward-cell)))
9450 (defun markdown-table-transpose ()
9451 "Transpose table at point.
9452 Horizontal separator lines will be eliminated."
9454 (unless (markdown-table-at-point-p)
9455 (user-error "Not at a table"))
9456 (let* ((table (buffer-substring-no-properties
9457 (markdown-table-begin) (markdown-table-end)))
9458 ;; Convert table to Lisp structure
9462 (unless (string-match-p
9463 markdown-table-hline-regexp x
)
9464 (markdown--table-line-to-columns x
)))
9465 (markdown--split-string table
"[ \t]*\n[ \t]*"))))
9466 (dline_old (markdown-table-get-dline))
9467 (col_old (markdown-table-get-column))
9468 (contents (mapcar (lambda (_)
9474 (setq tp
(cdr tp
))))
9477 (goto-char (markdown-table-begin))
9479 (re-search-forward "|") (backward-char)
9480 (delete-region (point) (markdown-table-end))
9483 (concat "| " (mapconcat 'identity x
" | " ) " |\n"))
9485 (markdown-table-goto-dline col_old
)
9486 (markdown-table-goto-column dline_old
))
9487 (when markdown-table-align-p
9488 (markdown-table-align)))
9490 (defun markdown-table-sort-lines (&optional sorting-type
)
9491 "Sort table lines according to the column at point.
9493 The position of point indicates the column to be used for
9494 sorting, and the range of lines is the range between the nearest
9495 horizontal separator lines, or the entire table of no such lines
9496 exist. If point is before the first column, user will be prompted
9497 for the sorting column. If there is an active region, the mark
9498 specifies the first line and the sorting column, while point
9499 should be in the last line to be included into the sorting.
9501 The command then prompts for the sorting type which can be
9502 alphabetically or numerically. Sorting in reverse order is also
9505 If SORTING-TYPE is specified when this function is called from a
9506 Lisp program, no prompting will take place. SORTING-TYPE must be
9507 a character, any of (?a ?A ?n ?N) where the capital letters
9508 indicate that sorting should be done in reverse order."
9510 (unless (markdown-table-at-point-p)
9511 (user-error "Not at a table"))
9512 ;; Set sorting type and column used for sorting
9513 (let ((column (let ((c (markdown-table-get-column)))
9515 ((called-interactively-p 'any
)
9516 (read-number "Use column N for sorting: "))
9522 ;; Emacs < 28 hides prompt message by another message. This erases it.
9524 (read-char-exclusive
9525 "Sort type: [a]lpha [n]umeric (A/N means reversed): ")))))
9527 ;; Narrow buffer to appropriate sorting area
9528 (if (region-active-p)
9532 (goto-char (region-beginning)) (line-beginning-position)))
9535 (goto-char (region-end)) (line-end-position))))
9536 (let ((start (markdown-table-begin))
9537 (end (markdown-table-end)))
9540 (if (re-search-backward
9541 markdown-table-hline-regexp start t
)
9542 (line-beginning-position 2)
9544 (if (save-excursion (re-search-forward
9545 markdown-table-hline-regexp end t
))
9548 ;; Determine arguments for `sort-subr'
9549 (let* ((extract-key-from-cell
9550 (cl-case sorting-type
9551 ((?a ?A
) #'markdown--remove-invisible-markup
) ;; #'identity)
9552 ((?n ?N
) #'string-to-number
)
9553 (t (user-error "Invalid sorting type: %c" sorting-type
))))
9555 (cl-case sorting-type
9557 ((?a ?A
) #'string
<))))
9558 ;; Sort selected area
9559 (goto-char (point-min))
9560 (sort-subr (memq sorting-type
'(?A ?N
))
9563 (while (and (not (eobp))
9565 markdown-table-dline-regexp
)))
9569 (funcall extract-key-from-cell
9570 (markdown-table-get-cell column
)))
9573 (goto-char (point-min))))))
9575 (defun markdown-table-convert-region (begin end
&optional separator
)
9576 "Convert region from BEGIN to END to table with SEPARATOR.
9578 If every line contains at least one TAB character, the function
9579 assumes that the material is tab separated (TSV). If every line
9580 contains a comma, comma-separated values (CSV) are assumed. If
9581 not, lines are split at whitespace into cells.
9583 You can use a prefix argument to force a specific separator:
9584 \\[universal-argument] once forces CSV, \\[universal-argument]
9585 twice forces TAB, and \\[universal-argument] three times will
9586 prompt for a regular expression to match the separator, and a
9587 numeric argument N indicates that at least N consecutive
9588 spaces, or alternatively a TAB should be used as the separator."
9590 (interactive "r\nP")
9591 (let* ((begin (min begin end
)) (end (max begin end
)) re
)
9592 (goto-char begin
) (beginning-of-line 1)
9593 (setq begin
(point-marker))
9595 (if (bolp) (backward-char 1) (end-of-line 1))
9596 (setq end
(point-marker))
9597 (when (equal separator
'(64))
9598 (setq separator
(read-regexp "Regexp for cell separator: ")))
9600 ;; Get the right cell separator
9604 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
9605 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
9608 (if (equal separator
'(4))
9610 (while (< (point) end
)
9612 ((looking-at "^") (insert "| "))
9613 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
9614 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
9615 (replace-match "\\1") (if (looking-at "\"") (insert "\"")))
9616 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
9617 ((looking-at "[ \t]*,") (replace-match " | "))
9618 (t (beginning-of-line 2))))
9621 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
9622 ((equal separator
'(16)) "^\\|\t")
9623 ((integerp separator
)
9625 (user-error "Cell separator must contain one or more spaces")
9626 (format "^ *\\| *\t *\\| \\{%d,\\}\\|$" separator
)))
9627 ((stringp separator
) (format "^ *\\|%s" separator
))
9628 (t (error "Invalid cell separator"))))
9630 (while (and (not finish
) (re-search-forward re end t
))
9633 (replace-match "|" t t
)
9637 (replace-match "| " t t
)))))
9639 (when markdown-table-align-p
9640 (markdown-table-align))))
9642 (defun markdown-insert-table (&optional rows columns align
)
9643 "Insert an empty pipe table.
9644 Optional arguments ROWS, COLUMNS, and ALIGN specify number of
9645 rows and columns and the column alignment."
9647 (let* ((rows (or rows
(string-to-number (read-string "Row size: "))))
9648 (columns (or columns
(string-to-number (read-string "Column size: "))))
9649 (align (or align
(read-string "Alignment ([l]eft, [r]ight, [c]enter, or RET for default): ")))
9650 (align (cond ((equal align
"l") ":--")
9651 ((equal align
"r") "--:")
9652 ((equal align
"c") ":-:")
9655 (indent (make-string (current-column) ?\
))
9657 (apply 'concat indent
"|"
9658 (make-list columns
" |")) "\n"))
9659 (hline (apply 'concat indent
"|"
9660 (make-list columns
(concat align
"|")))))
9662 "^[ \t]*$" (buffer-substring-no-properties
9663 (line-beginning-position) (point)))
9664 (beginning-of-line 1)
9666 (dotimes (_ rows
) (insert line
))
9670 (end-of-line 1) (insert (concat "\n" hline
)) (goto-char pos
)))
9671 (markdown-table-forward-cell)))
9674 ;;; ElDoc Support =============================================================
9676 (defun markdown-eldoc-function (&rest _ignored
)
9677 "Return a helpful string when appropriate based on context.
9678 * Report URL when point is at a hidden URL.
9679 * Report language name when point is a code block with hidden markup."
9681 ;; Hidden URL or reference for inline link
9682 ((and (or (thing-at-point-looking-at markdown-regex-link-inline
)
9683 (thing-at-point-looking-at markdown-regex-link-reference
))
9684 (or markdown-hide-urls markdown-hide-markup
))
9685 (let* ((imagep (string-equal (match-string 1) "!"))
9686 (referencep (string-equal (match-string 5) "["))
9687 (link (match-string-no-properties 6))
9688 (edit-keys (markdown--substitute-command-keys
9690 "\\[markdown-insert-image]"
9691 "\\[markdown-insert-link]")))
9692 (edit-str (propertize edit-keys
'face
'font-lock-constant-face
))
9693 (object (if referencep
"reference" "URL")))
9694 (format "Hidden %s (%s to edit): %s" object edit-str
9697 (propertize "[" 'face
'markdown-markup-face
)
9698 (propertize link
'face
'markdown-reference-face
)
9699 (propertize "]" 'face
'markdown-markup-face
))
9700 (propertize link
'face
'markdown-url-face
)))))
9701 ;; Hidden language name for fenced code blocks
9702 ((and (markdown-code-block-at-point-p)
9703 (not (get-text-property (point) 'markdown-pre
))
9704 markdown-hide-markup
)
9705 (let ((lang (save-excursion (markdown-code-block-lang))))
9706 (unless lang
(setq lang
"[unspecified]"))
9707 (format "Hidden code block language: %s (%s to toggle markup)"
9708 (propertize lang
'face
'markdown-language-keyword-face
)
9709 (markdown--substitute-command-keys
9710 "\\[markdown-toggle-markup-hiding]"))))))
9713 ;;; Mode Definition ==========================================================
9715 (defun markdown-show-version ()
9716 "Show the version number in the minibuffer."
9718 (message "markdown-mode, version %s" markdown-mode-version
))
9720 (defun markdown-mode-info ()
9721 "Open the `markdown-mode' homepage."
9723 (browse-url "https://jblevins.org/projects/markdown-mode/"))
9726 (define-derived-mode markdown-mode text-mode
"Markdown"
9727 "Major mode for editing Markdown files."
9728 (when buffer-read-only
9729 (when (or (not (buffer-file-name)) (file-writable-p (buffer-file-name)))
9730 (setq-local buffer-read-only nil
)))
9731 ;; Natural Markdown tab width
9734 (setq-local comment-start
"<!-- ")
9735 (setq-local comment-end
" -->")
9736 (setq-local comment-start-skip
"<!--[ \t]*")
9737 (setq-local comment-column
0)
9738 (setq-local comment-auto-fill-only-comments nil
)
9739 (setq-local comment-use-syntax t
)
9741 (setq-local sentence-end-base
"[.?!…‽][]\"'”’)}»›*_`~]*")
9743 (add-hook 'syntax-propertize-extend-region-functions
9744 #'markdown-syntax-propertize-extend-region nil t
)
9745 (add-hook 'jit-lock-after-change-extend-region-functions
9746 #'markdown-font-lock-extend-region-function t t
)
9747 (setq-local syntax-propertize-function
#'markdown-syntax-propertize
)
9748 (syntax-propertize (point-max)) ;; Propertize before hooks run, etc.
9750 (setq font-lock-defaults
9751 '(markdown-mode-font-lock-keywords
9753 (font-lock-multiline . t
)
9754 (font-lock-syntactic-face-function . markdown-syntactic-face
)
9755 (font-lock-extra-managed-props
9756 .
(composition display invisible rear-nonsticky
9757 keymap help-echo mouse-face
))))
9758 (if markdown-hide-markup
9759 (add-to-invisibility-spec 'markdown-markup
)
9760 (remove-from-invisibility-spec 'markdown-markup
))
9762 (markdown-setup-wiki-link-hooks)
9764 (when markdown-enable-math
(markdown-toggle-math t
))
9765 ;; Add a buffer-local hook to reload after file-local variables are read
9766 (add-hook 'hack-local-variables-hook
#'markdown-handle-local-variables nil t
)
9767 ;; For imenu support
9768 (setq imenu-create-index-function
9769 (if markdown-nested-imenu-heading-index
9770 #'markdown-imenu-create-nested-index
9771 #'markdown-imenu-create-flat-index
))
9774 (setq-local beginning-of-defun-function
#'markdown-beginning-of-defun
)
9775 (setq-local end-of-defun-function
#'markdown-end-of-defun
)
9776 ;; Paragraph filling
9777 (setq-local fill-paragraph-function
#'markdown-fill-paragraph
)
9778 (setq-local paragraph-start
9779 ;; Should match start of lines that start or separate paragraphs
9780 (mapconcat #'identity
9782 "\f" ; starts with a literal line-feed
9783 "[ \t\f]*$" ; space-only line
9784 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9785 "[ \t]*[*+-][ \t]+" ; unordered list item
9786 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
9787 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
9788 "[ \t]*:[ \t]+" ; definition
9789 "^|" ; table or Pandoc line block
9792 (setq-local paragraph-separate
9793 ;; Should match lines that separate paragraphs without being
9794 ;; part of any paragraph:
9795 (mapconcat #'identity
9796 '("[ \t\f]*$" ; space-only line
9797 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9798 ;; The following is not ideal, but the Fill customization
9799 ;; options really only handle paragraph-starting prefixes,
9800 ;; not paragraph-ending suffixes:
9801 ".* $" ; line ending in two spaces
9803 "^\\(?: \\)?[-=]+[ \t]*$" ;; setext
9804 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
9806 (setq-local adaptive-fill-first-line-regexp
"\\`[ \t]*[A-Z]?>[ \t]*?\\'")
9807 (setq-local adaptive-fill-regexp
"\\s-*")
9808 (setq-local adaptive-fill-function
#'markdown-adaptive-fill-function
)
9809 (setq-local fill-forward-paragraph-function
#'markdown-fill-forward-paragraph
)
9811 (setq-local outline-regexp markdown-regex-header
)
9812 (setq-local outline-level
#'markdown-outline-level
)
9813 ;; Cause use of ellipses for invisible text.
9814 (add-to-invisibility-spec '(outline . t
))
9816 (if (boundp 'eldoc-documentation-functions
)
9817 (add-hook 'eldoc-documentation-functions
#'markdown-eldoc-function nil t
)
9818 (add-function :before-until
(local 'eldoc-documentation-function
)
9819 #'markdown-eldoc-function
))
9820 ;; Inhibiting line-breaking:
9821 ;; Separating out each condition into a separate function so that users can
9822 ;; override if desired (with remove-hook)
9823 (add-hook 'fill-nobreak-predicate
9824 #'markdown-line-is-reference-definition-p nil t
)
9825 (add-hook 'fill-nobreak-predicate
9826 #'markdown-pipe-at-bol-p nil t
)
9829 (setq-local indent-line-function markdown-indent-function
)
9830 (setq-local indent-region-function
#'markdown--indent-region
)
9833 (setq-local flyspell-generic-check-word-predicate
9834 #'markdown-flyspell-check-word-p
)
9837 (add-hook 'electric-quote-inhibit-functions
9838 #'markdown--inhibit-electric-quote nil
:local
)
9840 ;; Make checkboxes buttons
9841 (when markdown-make-gfm-checkboxes-buttons
9842 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
9843 (add-hook 'after-change-functions
#'markdown-gfm-checkbox-after-change-function t t
)
9844 (add-hook 'change-major-mode-hook
#'markdown-remove-gfm-checkbox-overlays t t
))
9847 (add-hook 'edit-indirect-after-commit-functions
9848 #'markdown--edit-indirect-after-commit-function
9851 ;; Marginalized headings
9852 (when markdown-marginalize-headers
9853 (add-hook 'window-configuration-change-hook
9854 #'markdown-marginalize-update-current nil t
))
9856 ;; add live preview export hook
9857 (add-hook 'after-save-hook
#'markdown-live-preview-if-markdown t t
)
9858 (add-hook 'kill-buffer-hook
#'markdown-live-preview-remove-on-kill t t
))
9861 (add-to-list 'auto-mode-alist
9862 '("\\.\\(?:md\\|markdown\\|mkd\\|mdown\\|mkdn\\|mdwn\\)\\'" . markdown-mode
))
9865 ;;; GitHub Flavored Markdown Mode ============================================
9867 (defun gfm--electric-pair-fence-code-block ()
9868 (when (and electric-pair-mode
9869 (not markdown-gfm-use-electric-backquote
)
9870 (eql last-command-event ?
`)
9872 (while (eql (char-before (- (point) count
)) ?
`)
9875 (eql (char-after) ?
`))
9876 (save-excursion (insert (make-string 2 ?
`)))))
9878 (defvar gfm-mode-hook nil
9879 "Hook run when entering GFM mode.")
9882 (define-derived-mode gfm-mode markdown-mode
"GFM"
9883 "Major mode for editing GitHub Flavored Markdown files."
9884 (setq markdown-link-space-sub-char
"-")
9885 (setq markdown-wiki-link-search-subdirectories t
)
9886 (setq-local markdown-table-at-point-p-function
#'gfm--table-at-point-p
)
9887 (add-hook 'post-self-insert-hook
#'gfm--electric-pair-fence-code-block
'append t
)
9888 (markdown-gfm-parse-buffer-for-languages))
9891 ;;; Viewing modes =============================================================
9893 (defcustom markdown-hide-markup-in-view-modes t
9894 "Enable hidden markup mode in `markdown-view-mode' and `gfm-view-mode'."
9899 (defvar markdown-view-mode-map
9900 (let ((map (make-sparse-keymap)))
9901 (define-key map
(kbd "p") #'markdown-outline-previous
)
9902 (define-key map
(kbd "n") #'markdown-outline-next
)
9903 (define-key map
(kbd "f") #'markdown-outline-next-same-level
)
9904 (define-key map
(kbd "b") #'markdown-outline-previous-same-level
)
9905 (define-key map
(kbd "u") #'markdown-outline-up
)
9906 (define-key map
(kbd "DEL") #'scroll-down-command
)
9907 (define-key map
(kbd "SPC") #'scroll-up-command
)
9908 (define-key map
(kbd ">") #'end-of-buffer
)
9909 (define-key map
(kbd "<") #'beginning-of-buffer
)
9910 (define-key map
(kbd "q") #'kill-this-buffer
)
9911 (define-key map
(kbd "?") #'describe-mode
)
9913 "Keymap for `markdown-view-mode'.")
9915 (defun markdown--filter-visible (beg end
&optional delete
)
9917 (invisible-faces '(markdown-header-delimiter-face markdown-header-rule-face
)))
9919 (when (markdown--face-p beg invisible-faces
)
9921 (while (and (markdown--face-p beg invisible-faces
) (< beg end
))
9923 (let ((next (next-single-char-property-change beg
'invisible
)))
9924 (unless (get-char-property beg
'invisible
)
9925 (setq result
(concat result
(buffer-substring beg
(min end next
)))))
9929 (let ((inhibit-read-only t
))
9930 (delete-region beg end
))))))
9933 (define-derived-mode markdown-view-mode markdown-mode
"Markdown-View"
9934 "Major mode for viewing Markdown content."
9935 (setq-local markdown-hide-markup markdown-hide-markup-in-view-modes
)
9936 (add-to-invisibility-spec 'markdown-markup
)
9937 (setq-local filter-buffer-substring-function
#'markdown--filter-visible
)
9940 (defvar gfm-view-mode-map
9941 markdown-view-mode-map
9942 "Keymap for `gfm-view-mode'.")
9945 (define-derived-mode gfm-view-mode gfm-mode
"GFM-View"
9946 "Major mode for viewing GitHub Flavored Markdown content."
9947 (setq-local markdown-hide-markup markdown-hide-markup-in-view-modes
)
9948 (setq-local markdown-fontify-code-blocks-natively t
)
9949 (setq-local filter-buffer-substring-function
#'markdown--filter-visible
)
9950 (add-to-invisibility-spec 'markdown-markup
)
9954 ;;; Live Preview Mode ========================================================
9956 (define-minor-mode markdown-live-preview-mode
9957 "Toggle native previewing on save for a specific markdown file."
9958 :lighter
" MD-Preview"
9959 (if markdown-live-preview-mode
9960 (if (markdown-live-preview-get-filename)
9961 (markdown-display-buffer-other-window (markdown-live-preview-export))
9962 (markdown-live-preview-mode -
1)
9963 (user-error "Buffer %s does not visit a file" (current-buffer)))
9964 (markdown-live-preview-remove)))
9967 (provide 'markdown-mode
)
9970 ;; indent-tabs-mode: nil
9973 ;;; markdown-mode.el ends here