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-alpha"
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 "geo" "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-escape
866 "Regular expression for matching escape sequences.")
868 (defconst markdown-regex-wiki-link
869 "\\(?:^\\|[^\\]\\)\\(?1:\\(?2:\\[\\[\\)\\(?3:[^]|]+\\)\\(?:\\(?4:|\\)\\(?5:[^]]+\\)\\)?\\(?6:\\]\\]\\)\\)"
870 "Regular expression for matching wiki links.
871 This matches typical bracketed [[WikiLinks]] as well as \\='aliased
872 wiki links of the form [[PageName|link text]].
873 The meanings of the first and second components depend
874 on the value of `markdown-wiki-link-alias-first'.
876 Group 1 matches the entire link.
877 Group 2 matches the opening square brackets.
878 Group 3 matches the first component of the wiki link.
879 Group 4 matches the pipe separator, when present.
880 Group 5 matches the second component of the wiki link, when present.
881 Group 6 matches the closing square brackets.")
883 (defconst markdown-regex-uri
884 (concat "\\(" (regexp-opt markdown-uri-types
) ":[^]\t\n\r<>; ]+\\)")
885 "Regular expression for matching inline URIs.")
887 ;; CommanMark specification says scheme length is 2-32 characters
888 (defconst markdown-regex-angle-uri
889 (concat "\\(<\\)\\([a-z][a-z0-9.+-]\\{1,31\\}:[^]\t\n\r<>,;()]+\\)\\(>\\)")
890 "Regular expression for matching inline URIs in angle brackets.")
892 (defconst markdown-regex-email
893 "<\\(\\(?:\\sw\\|\\s_\\|\\s.\\)+@\\(?:\\sw\\|\\s_\\|\\s.\\)+\\)>"
894 "Regular expression for matching inline email addresses.")
896 (defsubst markdown-make-regex-link-generic
()
897 "Make regular expression for matching any recognized link."
898 (concat "\\(?:" markdown-regex-link-inline
899 (when markdown-enable-wiki-links
900 (concat "\\|" markdown-regex-wiki-link
))
901 "\\|" markdown-regex-link-reference
902 "\\|" markdown-regex-angle-uri
"\\)"))
904 (defconst markdown-regex-gfm-checkbox
905 " \\(\\[[ xX]\\]\\) "
906 "Regular expression for matching GFM checkboxes.
907 Group 1 matches the text to become a button.")
909 (defconst markdown-regex-blank-line
911 "Regular expression that matches a blank line.")
913 (defconst markdown-regex-block-separator
915 "Regular expression for matching block boundaries.")
917 (defconst markdown-regex-block-separator-noindent
918 (concat "\\(\\`\\|\\(" markdown-regex-block-separator
"\\)[^\n\t\f ]\\)")
919 "Regexp for block separators before lines with no indentation.")
921 (defconst markdown-regex-math-inline-single
922 "\\(?:^\\|[^\\]\\)\\(?1:\\$\\)\\(?2:\\(?:[^\\$]\\|\\\\.\\)*\\)\\(?3:\\$\\)"
923 "Regular expression for itex $..$ math mode expressions.
924 Groups 1 and 3 match the opening and closing dollar signs.
925 Group 2 matches the mathematical expression contained within.")
927 (defconst markdown-regex-math-inline-double
928 "\\(?:^\\|[^\\]\\)\\(?1:\\$\\$\\)\\(?2:\\(?:[^\\$]\\|\\\\.\\)*\\)\\(?3:\\$\\$\\)"
929 "Regular expression for itex $$..$$ math mode expressions.
930 Groups 1 and 3 match opening and closing dollar signs.
931 Group 2 matches the mathematical expression contained within.")
933 (defconst markdown-regex-math-display
934 (rx line-start
(* blank
)
935 (group (group (repeat 1 2 "\\")) "[")
936 (group (*? anything
))
937 (group (backref 2) "]")
939 "Regular expression for \[..\] or \\[..\\] display math.
940 Groups 1 and 4 match the opening and closing markup.
941 Group 3 matches the mathematical expression contained within.
942 Group 2 matches the opening slashes, and is used internally to
943 match the closing slashes.")
945 (defsubst markdown-make-tilde-fence-regex
(num-tildes &optional end-of-line
)
946 "Return regexp matching a tilde code fence at least NUM-TILDES long.
947 END-OF-LINE is the regexp construct to indicate end of line; $ if
949 (format "%s%d%s%s" "^[[:blank:]]*\\([~]\\{" num-tildes
",\\}\\)"
950 (or end-of-line
"$")))
952 (defconst markdown-regex-tilde-fence-begin
953 (markdown-make-tilde-fence-regex
954 3 "\\([[:blank:]]*{?\\)[[:blank:]]*\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$")
955 "Regular expression for matching tilde-fenced code blocks.
956 Group 1 matches the opening tildes.
957 Group 2 matches (optional) opening brace and surrounding whitespace.
958 Group 3 matches the language identifier (optional).
959 Group 4 matches the info string (optional).
960 Group 5 matches the closing brace (optional) and any surrounding whitespace.
961 Groups need to agree with `markdown-regex-gfm-code-block-open'.")
963 (defconst markdown-regex-declarative-metadata
964 "^[ \t]*\\(?:-[ \t]*\\)?\\([[:alpha:]][[:alpha:] _-]*?\\)\\([:=][ \t]*\\)\\(.*\\)$"
965 "Regular expression for matching declarative metadata statements.
966 This matches MultiMarkdown metadata as well as YAML and TOML
967 assignments such as the following:
975 (defconst markdown-regex-pandoc-metadata
976 "^\\(%\\)\\([ \t]*\\)\\(.*\\(?:\n[ \t]+.*\\)*\\)"
977 "Regular expression for matching Pandoc metadata.")
979 (defconst markdown-regex-yaml-metadata-border
981 "Regular expression for matching YAML metadata.")
983 (defconst markdown-regex-yaml-pandoc-metadata-end-border
984 "^\\(\\.\\{3\\}\\|\\-\\{3\\}\\)$"
985 "Regular expression for matching YAML metadata end borders.")
987 (defsubst markdown-get-yaml-metadata-start-border
()
988 "Return YAML metadata start border depending upon whether Pandoc is used."
990 (if markdown-use-pandoc-style-yaml-metadata
"^" "\\`")
991 markdown-regex-yaml-metadata-border
))
993 (defsubst markdown-get-yaml-metadata-end-border
(_)
994 "Return YAML metadata end border depending upon whether Pandoc is used."
995 (if markdown-use-pandoc-style-yaml-metadata
996 markdown-regex-yaml-pandoc-metadata-end-border
997 markdown-regex-yaml-metadata-border
))
999 (defconst markdown-regex-inline-attributes
1000 "[ \t]*\\(?:{:?\\)[ \t]*\\(?:\\(?:#[[:alpha:]_.:-]+\\|\\.[[:alpha:]_.:-]+\\|\\w+=['\"]?[^\n'\"}]*['\"]?\\),?[ \t]*\\)+\\(?:}\\)[ \t]*$"
1001 "Regular expression for matching inline identifiers or attribute lists.
1002 Compatible with Pandoc, Python Markdown, PHP Markdown Extra, and Leanpub.")
1004 (defconst markdown-regex-leanpub-sections
1007 (regexp-opt '("frontmatter" "mainmatter" "backmatter" "appendix" "pagebreak"))
1008 "\\)\\(}\\)[ \t]*\n")
1009 "Regular expression for Leanpub section markers and related syntax.")
1011 (defconst markdown-regex-sub-superscript
1012 "\\(?:^\\|[^\\~^]\\)\\(?1:\\(?2:[~^]\\)\\(?3:[+-\u2212]?[[:alnum:]]+\\)\\(?4:\\2\\)\\)"
1013 "The regular expression matching a sub- or superscript.
1014 The leading un-numbered group matches the character before the
1015 opening tilde or carat, if any, ensuring that it is not a
1016 backslash escape, carat, or tilde.
1017 Group 1 matches the entire expression, including markup.
1018 Group 2 matches the opening markup--a tilde or carat.
1019 Group 3 matches the text inside the delimiters.
1020 Group 4 matches the closing markup--a tilde or carat.")
1022 (defconst markdown-regex-include
1023 "^\\(?1:<<\\)\\(?:\\(?2:\\[\\)\\(?3:.*\\)\\(?4:\\]\\)\\)?\\(?:\\(?5:(\\)\\(?6:.*\\)\\(?7:)\\)\\)?\\(?:\\(?8:{\\)\\(?9:.*\\)\\(?10:}\\)\\)?$"
1024 "Regular expression matching common forms of include syntax.
1025 Marked 2, Leanpub, and other processors support some of these forms:
1027 <<[sections/section1.md]
1029 <<[Code title](folder/filename)
1030 <<{folder/raw_file.html}
1032 Group 1 matches the opening two angle brackets.
1033 Groups 2-4 match the opening square bracket, the text inside,
1034 and the closing square bracket, respectively.
1035 Groups 5-7 match the opening parenthesis, the text inside, and
1036 the closing parenthesis.
1037 Groups 8-10 match the opening brace, the text inside, and the brace.")
1039 (defconst markdown-regex-pandoc-inline-footnote
1040 "\\(?1:\\^\\)\\(?2:\\[\\)\\(?3:\\(?:.\\|\n[^\n]\\)*?\\)\\(?4:\\]\\)"
1041 "Regular expression for Pandoc inline footnote^[footnote text].
1042 Group 1 matches the opening caret.
1043 Group 2 matches the opening square bracket.
1044 Group 3 matches the footnote text, without the surrounding markup.
1045 Group 4 matches the closing square bracket.")
1047 (defconst markdown-regex-html-attr
1048 "\\(\\<[[:alpha:]:-]+\\>\\)\\(\\s-*\\(=\\)\\s-*\\(\".*?\"\\|'.*?'\\|[^'\">[:space:]]+\\)?\\)?"
1049 "Regular expression for matching HTML attributes and values.
1050 Group 1 matches the attribute name.
1051 Group 2 matches the following whitespace, equals sign, and value, if any.
1052 Group 3 matches the equals sign, if any.
1053 Group 4 matches single-, double-, or un-quoted attribute values.")
1055 (defconst markdown-regex-html-tag
1056 (concat "\\(</?\\)\\(\\w+\\)\\(\\(\\s-+" markdown-regex-html-attr
1057 "\\)+\\s-*\\|\\s-*\\)\\(/?>\\)")
1058 "Regular expression for matching HTML tags.
1059 Groups 1 and 9 match the beginning and ending angle brackets and slashes.
1060 Group 2 matches the tag name.
1061 Group 3 matches all attributes and whitespace following the tag name.")
1063 (defconst markdown-regex-html-entity
1064 "\\(&#?[[:alnum:]]+;\\)"
1065 "Regular expression for matching HTML entities.")
1067 (defconst markdown-regex-highlighting
1068 "\\(?1:^\\|[^\\]\\)\\(?2:\\(?3:==\\)\\(?4:[^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(?5:==\\)\\)"
1069 "Regular expression for matching highlighting text.
1070 Group 1 matches the character before the opening equal, if any,
1071 ensuring that it is not a backslash escape.
1072 Group 2 matches the entire expression, including delimiters.
1073 Groups 3 and 5 matches the opening and closing delimiters.
1074 Group 4 matches the text inside the delimiters.")
1077 ;;; Syntax ====================================================================
1079 (defvar markdown--syntax-properties
1080 (list 'markdown-tilde-fence-begin nil
1081 'markdown-tilde-fence-end nil
1082 'markdown-fenced-code nil
1083 'markdown-yaml-metadata-begin nil
1084 'markdown-yaml-metadata-end nil
1085 'markdown-yaml-metadata-section nil
1086 'markdown-gfm-block-begin nil
1087 'markdown-gfm-block-end nil
1088 'markdown-gfm-code nil
1089 'markdown-list-item nil
1091 'markdown-blockquote nil
1093 'markdown-comment nil
1094 'markdown-heading nil
1095 'markdown-heading-1-setext nil
1096 'markdown-heading-2-setext nil
1097 'markdown-heading-1-atx nil
1098 'markdown-heading-2-atx nil
1099 'markdown-heading-3-atx nil
1100 'markdown-heading-4-atx nil
1101 'markdown-heading-5-atx nil
1102 'markdown-heading-6-atx nil
1103 'markdown-metadata-key nil
1104 'markdown-metadata-value nil
1105 'markdown-metadata-markup nil
)
1106 "Property list of all Markdown syntactic properties.")
1108 (defsubst markdown-in-comment-p
(&optional pos
)
1109 "Return non-nil if POS is in a comment.
1110 If POS is not given, use point instead."
1111 (get-text-property (or pos
(point)) 'markdown-comment
))
1113 (defun markdown--face-p (pos faces
)
1114 "Return non-nil if face of POS contain FACES."
1115 (let ((face-prop (get-text-property pos
'face
)))
1116 (if (listp face-prop
)
1117 (cl-loop for face in face-prop
1118 thereis
(memq face faces
))
1119 (memq face-prop faces
))))
1121 (defun markdown-syntax-propertize-extend-region (start end
)
1122 "Extend START to END region to include an entire block of text.
1123 This helps improve syntax analysis for block constructs.
1124 Returns a cons (NEW-START . NEW-END) or nil if no adjustment should be made.
1125 Function is called repeatedly until it returns nil. For details, see
1126 `syntax-propertize-extend-region-functions'."
1129 (let* ((new-start (progn (goto-char start
)
1130 (skip-chars-forward "\n")
1131 (if (re-search-backward "\n\n" nil t
)
1132 (min start
(match-end 0))
1134 (new-end (progn (goto-char end
)
1135 (skip-chars-backward "\n")
1136 (if (re-search-forward "\n\n" nil t
)
1137 (max end
(match-beginning 0))
1139 (code-match (markdown-code-block-at-pos new-start
))
1140 ;; FIXME: The `code-match' can return bogus values
1141 ;; when text has been inserted/deleted!
1142 (new-start (min (or (and code-match
(cl-first code-match
))
1145 (code-match (and (< end
(point-max))
1146 (markdown-code-block-at-pos end
)))
1147 (new-end (max (or (and code-match
(cl-second code-match
)) 0)
1150 (unless (and (eq new-start start
) (eq new-end end
))
1151 (cons new-start
(min new-end
(point-max))))))))
1153 (defun markdown-font-lock-extend-region-function (start end _
)
1154 "Used in `jit-lock-after-change-extend-region-functions'.
1155 Delegates to `markdown-syntax-propertize-extend-region'. START
1156 and END are the previous region to refontify."
1157 (let ((res (markdown-syntax-propertize-extend-region start end
)))
1159 ;; syntax-propertize-function is not called when character at
1160 ;; (point-max) is deleted, but font-lock-extend-region-functions
1161 ;; are called. Force a syntax property update in that case.
1162 (when (= end
(point-max))
1163 ;; This function is called in a buffer modification hook.
1164 ;; `markdown-syntax-propertize' doesn't save the match data,
1165 ;; so we have to do it here.
1167 (markdown-syntax-propertize (car res
) (cdr res
))))
1168 (setq jit-lock-start
(car res
)
1169 jit-lock-end
(cdr res
)))))
1171 (defun markdown--cur-list-item-bounds ()
1172 "Return a list describing the list item at point.
1173 Assumes that match data is set for `markdown-regex-list'. See the
1174 documentation for `markdown-cur-list-item-bounds' for the format of
1177 (let* ((begin (match-beginning 0))
1178 (indent (length (match-string-no-properties 1)))
1179 (nonlist-indent (- (match-end 3) (match-beginning 0)))
1180 (marker (buffer-substring-no-properties
1181 (match-beginning 2) (match-end 3)))
1182 (checkbox (match-string-no-properties 4))
1183 (match (butlast (match-data t
)))
1184 (end (markdown-cur-list-item-end nonlist-indent
)))
1185 (list begin end indent nonlist-indent marker checkbox match
))))
1187 (defun markdown--append-list-item-bounds (marker indent cur-bounds bounds
)
1188 "Update list item BOUNDS given list MARKER, block INDENT, and CUR-BOUNDS.
1189 Here, MARKER is a string representing the type of list and INDENT
1190 is an integer giving the indentation, in spaces, of the current
1191 block. CUR-BOUNDS is a list of the form returned by
1192 `markdown-cur-list-item-bounds' and BOUNDS is a list of bounds
1193 values for parent list items. When BOUNDS is nil, it means we are
1194 at baseline (not inside of a nested list)."
1195 (let ((prev-indent (or (cl-third (car bounds
)) 0)))
1197 ;; New list item at baseline.
1198 ((and marker
(null bounds
))
1200 ;; List item with greater indentation (four or more spaces).
1201 ;; Increase list level by consing CUR-BOUNDS onto BOUNDS.
1202 ((and marker
(>= indent
(+ prev-indent markdown-list-indent-width
)))
1203 (cons cur-bounds bounds
))
1204 ;; List item with greater or equal indentation (less than four spaces).
1205 ;; Keep list level the same by replacing the car of BOUNDS.
1206 ((and marker
(>= indent prev-indent
))
1207 (cons cur-bounds
(cdr bounds
)))
1208 ;; Lesser indentation level.
1209 ;; Pop appropriate number of elements off BOUNDS list (e.g., lesser
1210 ;; indentation could move back more than one list level). Note
1211 ;; that this block need not be the beginning of list item.
1212 ((< indent prev-indent
)
1213 (while (and (> (length bounds
) 1)
1214 (setq prev-indent
(cl-third (cadr bounds
)))
1215 (< indent
(+ prev-indent markdown-list-indent-width
)))
1216 (setq bounds
(cdr bounds
)))
1217 (cons cur-bounds bounds
))
1218 ;; Otherwise, do nothing.
1221 (defun markdown-syntax-propertize-list-items (start end
)
1222 "Propertize list items from START to END.
1223 Stores nested list item information in the `markdown-list-item'
1224 text property to make later syntax analysis easier. The value of
1225 this property is a list with elements of the form (begin . end)
1226 giving the bounds of the current and parent list items."
1229 (let ((prev-list-line -
100)
1230 bounds level pre-regexp
)
1231 ;; Find a baseline point with zero list indentation
1232 (markdown-search-backward-baseline)
1233 ;; Search for all list items between baseline and END
1234 (while (and (< (point) end
)
1235 (re-search-forward markdown-regex-list end
'limit
))
1236 ;; Level of list nesting
1237 (setq level
(length bounds
))
1238 ;; Pre blocks need to be indented one level past the list level
1239 (setq pre-regexp
(format "^\\( \\|\t\\)\\{%d\\}" (1+ level
)))
1242 ;; Reset at headings, horizontal rules, and top-level blank lines.
1243 ;; Propertize baseline when in range.
1244 ((markdown-new-baseline)
1246 ;; Make sure this is not a line from a pre block
1247 ((and (looking-at-p pre-regexp
)
1248 ;; too indented line is also treated as list if previous line is list
1249 (>= (- (line-number-at-pos) prev-list-line
) 2)))
1250 ;; If not, then update levels and propertize list item when in range.
1252 (let* ((indent (current-indentation))
1253 (cur-bounds (markdown--cur-list-item-bounds))
1254 (first (cl-first cur-bounds
))
1255 (last (cl-second cur-bounds
))
1256 (marker (cl-fifth cur-bounds
)))
1257 (setq bounds
(markdown--append-list-item-bounds
1258 marker indent cur-bounds bounds
))
1259 (when (and (<= start
(point)) (<= (point) end
))
1260 (setq prev-list-line
(line-number-at-pos first
))
1261 (put-text-property first last
'markdown-list-item bounds
)))))
1264 (defun markdown-syntax-propertize-pre-blocks (start end
)
1265 "Match preformatted text blocks from START to END."
1269 ;; Use loop for avoiding too many recursive calls
1270 ;; https://github.com/jrblevin/markdown-mode/issues/512
1272 (let ((levels (markdown-calculate-list-levels))
1273 indent pre-regexp close-regexp open close
)
1274 (while (and (< (point) end
) (not close
))
1275 ;; Search for a region with sufficient indentation
1278 (setq indent
(1+ (length levels
))))
1279 (setq pre-regexp
(format "^\\( \\|\t\\)\\{%d\\}" indent
))
1280 (setq close-regexp
(format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent
)))
1283 ;; If not at the beginning of a line, move forward
1284 ((not (bolp)) (forward-line))
1285 ;; Move past blank lines
1286 ((markdown-cur-line-blank-p) (forward-line))
1287 ;; At headers and horizontal rules, reset levels
1288 ((markdown-new-baseline) (forward-line) (setq levels nil
))
1289 ;; If the current line has sufficient indentation, mark out pre block
1290 ;; The opening should be preceded by a blank line.
1291 ((and (markdown-prev-line-blank) (looking-at pre-regexp
))
1292 (setq open
(match-beginning 0))
1293 (while (and (or (looking-at-p pre-regexp
) (markdown-cur-line-blank-p))
1296 (skip-syntax-backward "-")
1297 (setq close
(point)))
1298 ;; If current line has a list marker, update levels, move to end of block
1299 ((looking-at markdown-regex-list
)
1300 (setq levels
(markdown-update-list-levels
1301 (match-string 2) (current-indentation) levels
))
1302 (markdown-end-of-text-block))
1303 ;; If this is the end of the indentation level, adjust levels accordingly.
1304 ;; Only match end of indentation level if levels is not the empty list.
1305 ((and (car levels
) (looking-at-p close-regexp
))
1306 (setq levels
(markdown-update-list-levels
1307 nil
(current-indentation) levels
))
1308 (markdown-end-of-text-block))
1309 (t (markdown-end-of-text-block))))
1311 (if (and open close
)
1312 ;; Set text property data and continue to search
1313 (put-text-property open close
'markdown-pre
(list open close
))
1317 (defconst markdown-fenced-block-pairs
1318 `(((,markdown-regex-tilde-fence-begin markdown-tilde-fence-begin
)
1319 (markdown-make-tilde-fence-regex markdown-tilde-fence-end
)
1320 markdown-fenced-code
)
1321 ((markdown-get-yaml-metadata-start-border markdown-yaml-metadata-begin
)
1322 (markdown-get-yaml-metadata-end-border markdown-yaml-metadata-end
)
1323 markdown-yaml-metadata-section
)
1324 ((,markdown-regex-gfm-code-block-open markdown-gfm-block-begin
)
1325 (,markdown-regex-gfm-code-block-close markdown-gfm-block-end
)
1327 "Mapping of regular expressions to \"fenced-block\" constructs.
1328 These constructs are distinguished by having a distinctive start
1329 and end pattern, both of which take up an entire line of text,
1330 but no special pattern to identify text within the fenced
1331 blocks (unlike blockquotes and indented-code sections).
1333 Each element within this list takes the form:
1335 ((START-REGEX-OR-FUN START-PROPERTY)
1336 (END-REGEX-OR-FUN END-PROPERTY)
1339 Each *-REGEX-OR-FUN element can be a regular expression as a string, or a
1340 function which evaluates to same. Functions for START-REGEX-OR-FUN accept no
1341 arguments, but functions for END-REGEX-OR-FUN accept a single numerical argument
1342 which is the length of the first group of the START-REGEX-OR-FUN match, which
1343 can be ignored if unnecessary. `markdown-maybe-funcall-regexp' is used to
1344 evaluate these into \"real\" regexps.
1346 The *-PROPERTY elements are the text properties applied to each part of the
1347 block construct when it is matched using
1348 `markdown-syntax-propertize-fenced-block-constructs'. START-PROPERTY is applied
1349 to the text matching START-REGEX-OR-FUN, END-PROPERTY to END-REGEX-OR-FUN, and
1350 MIDDLE-PROPERTY to the text in between the two. The value of *-PROPERTY is the
1351 `match-data' when the regexp was matched to the text. In the case of
1352 MIDDLE-PROPERTY, the value is a false match data of the form \\='(begin end), with
1353 begin and end set to the edges of the \"middle\" text. This makes fontification
1356 (defun markdown-text-property-at-point (prop)
1357 (get-text-property (point) prop
))
1359 (defsubst markdown-maybe-funcall-regexp
(object &optional arg
)
1360 (cond ((functionp object
)
1361 (if arg
(funcall object arg
) (funcall object
)))
1362 ((stringp object
) object
)
1363 (t (error "Object cannot be turned into regex"))))
1365 (defsubst markdown-get-start-fence-regexp
()
1366 "Return regexp to find all \"start\" sections of fenced block constructs.
1367 Which construct is actually contained in the match must be found separately."
1370 (mapcar (lambda (entry) (markdown-maybe-funcall-regexp (caar entry
)))
1371 markdown-fenced-block-pairs
)
1374 (defun markdown-get-fenced-block-begin-properties ()
1375 (cl-mapcar (lambda (entry) (cl-cadar entry
)) markdown-fenced-block-pairs
))
1377 (defun markdown-get-fenced-block-end-properties ()
1378 (cl-mapcar (lambda (entry) (cl-cadadr entry
)) markdown-fenced-block-pairs
))
1380 (defun markdown-get-fenced-block-middle-properties ()
1381 (cl-mapcar #'cl-third markdown-fenced-block-pairs
))
1383 (defun markdown-find-previous-prop (prop &optional lim
)
1384 "Find previous place where property PROP is non-nil, up to LIM.
1385 Return a cons of (pos . property). pos is point if point contains
1388 (if (get-text-property (point) prop
) (point)
1389 (previous-single-property-change
1390 (point) prop nil
(or lim
(point-min))))))
1391 (when (and (not (get-text-property res prop
))
1393 (get-text-property (1- res
) prop
))
1395 (when (and res
(get-text-property res prop
)) (cons res prop
))))
1397 (defun markdown-find-next-prop (prop &optional lim
)
1398 "Find next place where property PROP is non-nil, up to LIM.
1399 Return a cons of (POS . PROPERTY) where POS is point if point
1400 contains non-nil PROP."
1402 (if (get-text-property (point) prop
) (point)
1403 (next-single-property-change
1404 (point) prop nil
(or lim
(point-max))))))
1405 (when (and res
(get-text-property res prop
)) (cons res prop
))))
1407 (defun markdown-min-of-seq (map-fn seq
)
1408 "Apply MAP-FN to SEQ and return element of SEQ with minimum value of MAP-FN."
1409 (cl-loop for el in seq
1410 with min
= 1.0e
+INF
; infinity
1412 do
(let ((res (funcall map-fn el
)))
1416 finally return min-el
))
1418 (defun markdown-max-of-seq (map-fn seq
)
1419 "Apply MAP-FN to SEQ and return element of SEQ with maximum value of MAP-FN."
1420 (cl-loop for el in seq
1421 with max
= -
1.0e
+INF
; negative infinity
1423 do
(let ((res (funcall map-fn el
)))
1424 (when (and res
(> res max
))
1427 finally return max-el
))
1429 (defun markdown-find-previous-block ()
1430 "Find previous block.
1431 Detect whether `markdown-syntax-propertize-fenced-block-constructs' was
1432 unable to propertize the entire block, but was able to propertize the beginning
1433 of the block. If so, return a cons of (pos . property) where the beginning of
1434 the block was propertized."
1435 (let ((start-pt (point))
1437 (markdown-max-of-seq
1442 #'markdown-find-previous-prop
1443 (markdown-get-fenced-block-begin-properties))))))
1445 (let* ((length-of-open-match
1447 (get-text-property (car closest-open
) (cdr closest-open
))))
1448 (- (cl-fourth match-d
) (cl-third match-d
))))
1450 (markdown-maybe-funcall-regexp
1453 (lambda (entry) (eq (cl-cadar entry
) (cdr closest-open
)))
1454 markdown-fenced-block-pairs
))
1455 length-of-open-match
))
1459 (goto-char (car closest-open
))
1460 (and (re-search-forward end-regexp start-pt t
)
1461 (match-beginning 0))))))
1462 (and (not end-prop-loc
) closest-open
)))))
1464 (defun markdown-get-fenced-block-from-start (prop)
1465 "Return limits of an enclosing fenced block from its start, using PROP.
1466 Return value is a list usable as `match-data'."
1467 (catch 'no-rest-of-block
1468 (let* ((correct-entry
1470 (lambda (entry) (eq (cl-cadar entry
) prop
))
1471 markdown-fenced-block-pairs
))
1472 (begin-of-begin (cl-first (markdown-text-property-at-point prop
)))
1473 (middle-prop (cl-third correct-entry
))
1474 (end-prop (cl-cadadr correct-entry
))
1477 (goto-char (match-end 0)) ; end of begin
1478 (unless (eobp) (forward-char))
1479 (let ((mid-prop-v (markdown-text-property-at-point middle-prop
)))
1480 (if (not mid-prop-v
) ; no middle
1482 ;; try to find end by advancing one
1484 (markdown-text-property-at-point end-prop
)))
1485 (if end-prop-v
(cl-second end-prop-v
)
1486 (throw 'no-rest-of-block nil
))))
1487 (set-match-data mid-prop-v
)
1488 (goto-char (match-end 0)) ; end of middle
1489 (beginning-of-line) ; into end
1490 (cl-second (markdown-text-property-at-point end-prop
)))))))
1491 (list begin-of-begin end-of-end
))))
1493 (defun markdown-get-fenced-block-from-middle (prop)
1494 "Return limits of an enclosing fenced block from its middle, using PROP.
1495 Return value is a list usable as `match-data'."
1496 (let* ((correct-entry
1498 (lambda (entry) (eq (cl-third entry
) prop
))
1499 markdown-fenced-block-pairs
))
1500 (begin-prop (cl-cadar correct-entry
))
1503 (goto-char (match-beginning 0))
1504 (unless (bobp) (forward-line -
1))
1506 (cl-first (markdown-text-property-at-point begin-prop
))))
1507 (end-prop (cl-cadadr correct-entry
))
1510 (goto-char (match-end 0))
1512 (cl-second (markdown-text-property-at-point end-prop
)))))
1513 (list begin-of-begin end-of-end
)))
1515 (defun markdown-get-fenced-block-from-end (prop)
1516 "Return limits of an enclosing fenced block from its end, using PROP.
1517 Return value is a list usable as `match-data'."
1518 (let* ((correct-entry
1520 (lambda (entry) (eq (cl-cadadr entry
) prop
))
1521 markdown-fenced-block-pairs
))
1522 (end-of-end (cl-second (markdown-text-property-at-point prop
)))
1523 (middle-prop (cl-third correct-entry
))
1524 (begin-prop (cl-cadar correct-entry
))
1527 (goto-char (match-beginning 0)) ; beginning of end
1528 (unless (bobp) (backward-char)) ; into middle
1529 (let ((mid-prop-v (markdown-text-property-at-point middle-prop
)))
1530 (if (not mid-prop-v
)
1533 (cl-first (markdown-text-property-at-point begin-prop
)))
1534 (set-match-data mid-prop-v
)
1535 (goto-char (match-beginning 0)) ; beginning of middle
1536 (unless (bobp) (forward-line -
1)) ; into beginning
1538 (cl-first (markdown-text-property-at-point begin-prop
)))))))
1539 (list begin-of-begin end-of-end
)))
1541 (defun markdown-get-enclosing-fenced-block-construct (&optional pos
)
1542 "Get \"fake\" match data for block enclosing POS.
1543 Returns fake match data which encloses the start, middle, and end
1544 of the block construct enclosing POS, if it exists. Used in
1545 `markdown-code-block-at-pos'."
1547 (when pos
(goto-char pos
))
1553 (lambda (fun-and-prop)
1554 (cl-destructuring-bind (fun prop
) fun-and-prop
1557 (set-match-data (markdown-text-property-at-point prop
))
1558 (funcall fun prop
)))))
1559 `((markdown-get-fenced-block-from-start
1561 #'markdown-text-property-at-point
1562 (markdown-get-fenced-block-begin-properties)))
1563 (markdown-get-fenced-block-from-middle
1565 #'markdown-text-property-at-point
1566 (markdown-get-fenced-block-middle-properties)))
1567 (markdown-get-fenced-block-from-end
1569 #'markdown-text-property-at-point
1570 (markdown-get-fenced-block-end-properties)))))))))
1572 (defun markdown-propertize-end-match (reg end fence-spec middle-begin
)
1573 "Get match for REG up to END, if exists, and propertize appropriately.
1574 FENCE-SPEC is an entry in `markdown-fenced-block-pairs' and
1575 MIDDLE-BEGIN is the start of the \"middle\" section of the block."
1576 (when (re-search-forward reg end t
)
1577 (let ((close-begin (match-beginning 0)) ; Start of closing line.
1578 (close-end (match-end 0)) ; End of closing line.
1579 (close-data (match-data t
))) ; Match data for closing line.
1580 ;; Propertize middle section of fenced block.
1581 (put-text-property middle-begin close-begin
1582 (cl-third fence-spec
)
1583 (list middle-begin close-begin
))
1584 ;; If the block is a YAML block, propertize the declarations inside
1585 (when (< middle-begin close-begin
) ;; workaround #634
1586 (markdown-syntax-propertize-yaml-metadata middle-begin close-begin
))
1587 ;; Propertize closing line of fenced block.
1588 (put-text-property close-begin close-end
1589 (cl-cadadr fence-spec
) close-data
))))
1591 (defun markdown--triple-quote-single-line-p (begin)
1595 (and (search-forward "```" nil t
)
1596 (search-forward "```" (line-end-position) t
)))))
1598 (defun markdown-syntax-propertize-fenced-block-constructs (start end
)
1599 "Propertize according to `markdown-fenced-block-pairs' from START to END.
1600 If unable to propertize an entire block (if the start of a block is within START
1601 and END, but the end of the block is not), propertize the start section of a
1602 block, then in a subsequent call propertize both middle and end by finding the
1603 start which was previously propertized."
1604 (let ((start-reg (markdown-get-start-fence-regexp)))
1607 ;; start from previous unclosed block, if exists
1608 (let ((prev-begin-block (markdown-find-previous-block)))
1609 (when prev-begin-block
1610 (let* ((correct-entry
1611 (cl-find-if (lambda (entry)
1612 (eq (cdr prev-begin-block
) (cl-cadar entry
)))
1613 markdown-fenced-block-pairs
))
1614 (enclosed-text-start (1+ (car prev-begin-block
)))
1617 (goto-char (car prev-begin-block
))
1619 (markdown-maybe-funcall-regexp
1620 (caar correct-entry
))
1622 (line-beginning-position) (line-end-position)))
1623 (- (match-end 1) (match-beginning 1))))
1624 (end-reg (markdown-maybe-funcall-regexp
1625 (cl-caadr correct-entry
) start-length
)))
1626 (markdown-propertize-end-match
1627 end-reg end correct-entry enclosed-text-start
))))
1628 ;; find all new blocks within region
1629 (while (re-search-forward start-reg end t
)
1630 ;; we assume the opening constructs take up (only) an entire line,
1631 ;; so we re-check the current line
1632 (let* ((block-start (match-beginning 0))
1633 (cur-line (buffer-substring (line-beginning-position) (line-end-position)))
1634 ;; find entry in `markdown-fenced-block-pairs' corresponding
1635 ;; to regex which was matched
1638 (lambda (fenced-pair)
1640 (markdown-maybe-funcall-regexp (caar fenced-pair
))
1642 markdown-fenced-block-pairs
))
1643 (enclosed-text-start
1644 (save-excursion (1+ (line-end-position))))
1646 (markdown-maybe-funcall-regexp
1647 (cl-caadr correct-entry
)
1648 (if (and (match-beginning 1) (match-end 1))
1649 (- (match-end 1) (match-beginning 1))
1651 (prop (cl-cadar correct-entry
)))
1652 (when (or (not (eq prop
'markdown-gfm-block-begin
))
1653 (not (markdown--triple-quote-single-line-p block-start
)))
1654 ;; get correct match data
1658 (markdown-maybe-funcall-regexp (caar correct-entry
))
1659 (line-end-position)))
1660 ;; mark starting, even if ending is outside of region
1661 (put-text-property (match-beginning 0) (match-end 0) prop
(match-data t
))
1662 (markdown-propertize-end-match
1663 end-reg end correct-entry enclosed-text-start
)))))))
1665 (defun markdown-syntax-propertize-blockquotes (start end
)
1666 "Match blockquotes from START to END."
1669 (while (and (re-search-forward markdown-regex-blockquote end t
)
1670 (not (markdown-code-block-at-pos (match-beginning 0))))
1671 (put-text-property (match-beginning 0) (match-end 0)
1672 'markdown-blockquote
1675 (defun markdown-syntax-propertize-hrs (start end
)
1676 "Match horizontal rules from START to END."
1679 (while (re-search-forward markdown-regex-hr end t
)
1680 (let ((beg (match-beginning 0))
1681 (end (match-end 0)))
1683 (unless (or (markdown-on-heading-p)
1684 (markdown-code-block-at-point-p))
1685 (put-text-property beg end
'markdown-hr
(match-data t
)))
1688 (defun markdown-syntax-propertize-yaml-metadata (start end
)
1689 "Propertize elements inside YAML metadata blocks from START to END.
1690 Assumes region from START and END is already known to be the interior
1691 region of a YAML metadata block as propertized by
1692 `markdown-syntax-propertize-fenced-block-constructs'."
1696 while
(re-search-forward markdown-regex-declarative-metadata end t
)
1698 (put-text-property (match-beginning 1) (match-end 1)
1699 'markdown-metadata-key
(match-data t
))
1700 (put-text-property (match-beginning 2) (match-end 2)
1701 'markdown-metadata-markup
(match-data t
))
1702 (put-text-property (match-beginning 3) (match-end 3)
1703 'markdown-metadata-value
(match-data t
))))))
1705 (defun markdown-syntax-propertize-headings (start end
)
1706 "Match headings of type SYMBOL with REGEX from START to END."
1708 (while (re-search-forward markdown-regex-header end t
)
1709 (unless (markdown-code-block-at-pos (match-beginning 0))
1711 (match-beginning 0) (match-end 0) 'markdown-heading
1714 (match-beginning 0) (match-end 0)
1715 (cond ((match-string-no-properties 2) 'markdown-heading-1-setext
)
1716 ((match-string-no-properties 3) 'markdown-heading-2-setext
)
1717 (t (let ((atx-level (length (markdown-trim-whitespace
1718 (match-string-no-properties 4)))))
1719 (intern (format "markdown-heading-%d-atx" atx-level
)))))
1722 (defun markdown-syntax-propertize-comments (start end
)
1723 "Match HTML comments from the START to END."
1724 ;; Implement by loop instead of recursive call for avoiding
1725 ;; exceed max-lisp-eval-depth issue
1726 ;; https://github.com/jrblevin/markdown-mode/issues/536
1730 (let* ((in-comment (nth 4 (syntax-ppss)))
1731 (comment-begin (nth 8 (syntax-ppss))))
1734 ((and (not in-comment
)
1735 (re-search-forward markdown-regex-comment-start end t
)
1736 (not (markdown-inline-code-at-point-p))
1737 (not (markdown-code-block-at-point-p)))
1738 (let ((open-beg (match-beginning 0)))
1739 (put-text-property open-beg
(1+ open-beg
)
1740 'syntax-table
(string-to-syntax "<"))
1741 (goto-char (min (1+ (match-end 0)) end
(point-max)))))
1743 ((and in-comment comment-begin
1744 (re-search-forward markdown-regex-comment-end end t
))
1745 (let ((comment-end (match-end 0)))
1746 (put-text-property (1- comment-end
) comment-end
1747 'syntax-table
(string-to-syntax ">"))
1748 ;; Remove any other text properties inside the comment
1749 (remove-text-properties comment-begin comment-end
1750 markdown--syntax-properties
)
1751 (put-text-property comment-begin comment-end
1752 'markdown-comment
(list comment-begin comment-end
))
1753 (goto-char (min comment-end end
(point-max)))))
1755 (t (setq finish t
)))))
1758 (defun markdown-syntax-propertize (start end
)
1759 "Function used as `syntax-propertize-function'.
1760 START and END delimit region to propertize."
1761 (with-silent-modifications
1763 (remove-text-properties start end markdown--syntax-properties
)
1764 (markdown-syntax-propertize-fenced-block-constructs start end
)
1765 (markdown-syntax-propertize-list-items start end
)
1766 (markdown-syntax-propertize-pre-blocks start end
)
1767 (markdown-syntax-propertize-blockquotes start end
)
1768 (markdown-syntax-propertize-headings start end
)
1769 (markdown-syntax-propertize-hrs start end
)
1770 (markdown-syntax-propertize-comments start end
))))
1773 ;;; Markup Hiding =============================================================
1775 (defconst markdown-markup-properties
1776 '(face markdown-markup-face invisible markdown-markup
)
1777 "List of properties and values to apply to markup.")
1779 (defconst markdown-language-keyword-properties
1780 '(face markdown-language-keyword-face invisible markdown-markup
)
1781 "List of properties and values to apply to code block language names.")
1783 (defconst markdown-language-info-properties
1784 '(face markdown-language-info-face invisible markdown-markup
)
1785 "List of properties and values to apply to code block language info strings.")
1787 (defconst markdown-include-title-properties
1788 '(face markdown-link-title-face invisible markdown-markup
)
1789 "List of properties and values to apply to included code titles.")
1791 (defcustom markdown-hide-markup nil
1792 "Determines whether markup in the buffer will be hidden.
1793 When set to nil, all markup is displayed in the buffer as it
1794 appears in the file. An exception is when `markdown-hide-urls'
1796 Set this to a non-nil value to turn this feature on by default.
1797 You can interactively toggle the value of this variable with
1798 `markdown-toggle-markup-hiding', \\[markdown-toggle-markup-hiding],
1799 or from the Markdown > Show & Hide menu.
1801 Markup hiding works by adding text properties to positions in the
1802 buffer---either the `invisible' property or the `display' property
1803 in cases where alternative glyphs are used (e.g., list bullets).
1804 This does not, however, affect printing or other output.
1805 Functions such as `htmlfontify-buffer' and `ps-print-buffer' will
1806 not honor these text properties. For printing, it would be better
1807 to first convert to HTML or PDF (e.g,. using Pandoc)."
1811 :package-version
'(markdown-mode .
"2.3"))
1812 (make-variable-buffer-local 'markdown-hide-markup
)
1814 (defun markdown-toggle-markup-hiding (&optional arg
)
1815 "Toggle the display or hiding of markup.
1816 With a prefix argument ARG, enable markup hiding if ARG is positive,
1817 and disable it otherwise.
1818 See `markdown-hide-markup' for additional details."
1819 (interactive (list (or current-prefix-arg
'toggle
)))
1820 (setq markdown-hide-markup
1821 (if (eq arg
'toggle
)
1822 (not markdown-hide-markup
)
1823 (> (prefix-numeric-value arg
) 0)))
1824 (if markdown-hide-markup
1825 (progn (add-to-invisibility-spec 'markdown-markup
)
1826 (message "markdown-mode markup hiding enabled"))
1827 (progn (remove-from-invisibility-spec 'markdown-markup
)
1828 (message "markdown-mode markup hiding disabled")))
1829 (markdown-reload-extensions))
1832 ;;; Font Lock =================================================================
1834 (require 'font-lock
)
1836 (defgroup markdown-faces nil
1837 "Faces used in Markdown Mode."
1841 (defface markdown-italic-face
1842 '((t (:inherit italic
)))
1843 "Face for italic text."
1844 :group
'markdown-faces
)
1846 (defface markdown-bold-face
1847 '((t (:inherit bold
)))
1848 "Face for bold text."
1849 :group
'markdown-faces
)
1851 (defface markdown-strike-through-face
1852 '((t (:strike-through t
)))
1853 "Face for strike-through text."
1854 :group
'markdown-faces
)
1856 (defface markdown-markup-face
1857 '((t (:inherit shadow
:slant normal
:weight normal
)))
1858 "Face for markup elements."
1859 :group
'markdown-faces
)
1861 (defface markdown-header-rule-face
1862 '((t (:inherit markdown-markup-face
)))
1863 "Base face for headers rules."
1864 :group
'markdown-faces
)
1866 (defface markdown-header-delimiter-face
1867 '((t (:inherit markdown-markup-face
)))
1868 "Base face for headers hash delimiter."
1869 :group
'markdown-faces
)
1871 (defface markdown-list-face
1872 '((t (:inherit markdown-markup-face
)))
1873 "Face for list item markers."
1874 :group
'markdown-faces
)
1876 (defface markdown-blockquote-face
1877 '((t (:inherit font-lock-doc-face
)))
1878 "Face for blockquote sections."
1879 :group
'markdown-faces
)
1881 (defface markdown-code-face
1882 '((t (:inherit fixed-pitch
)))
1883 "Face for inline code, pre blocks, and fenced code blocks.
1884 This may be used, for example, to add a contrasting background to
1885 inline code fragments and code blocks."
1886 :group
'markdown-faces
)
1888 (defface markdown-inline-code-face
1889 '((t (:inherit
(markdown-code-face font-lock-constant-face
))))
1890 "Face for inline code."
1891 :group
'markdown-faces
)
1893 (defface markdown-pre-face
1894 '((t (:inherit
(markdown-code-face font-lock-constant-face
))))
1895 "Face for preformatted text."
1896 :group
'markdown-faces
)
1898 (defface markdown-table-face
1899 '((t (:inherit
(markdown-code-face))))
1901 :group
'markdown-faces
)
1903 (defface markdown-language-keyword-face
1904 '((t (:inherit font-lock-type-face
)))
1905 "Face for programming language identifiers."
1906 :group
'markdown-faces
)
1908 (defface markdown-language-info-face
1909 '((t (:inherit font-lock-string-face
)))
1910 "Face for programming language info strings."
1911 :group
'markdown-faces
)
1913 (defface markdown-link-face
1914 '((t (:inherit link
)))
1916 :group
'markdown-faces
)
1918 (defface markdown-missing-link-face
1919 '((t (:inherit font-lock-warning-face
)))
1920 "Face for missing links."
1921 :group
'markdown-faces
)
1923 (defface markdown-reference-face
1924 '((t (:inherit markdown-markup-face
)))
1925 "Face for link references."
1926 :group
'markdown-faces
)
1928 (defface markdown-footnote-marker-face
1929 '((t (:inherit markdown-markup-face
)))
1930 "Face for footnote markers."
1931 :group
'markdown-faces
)
1933 (defface markdown-footnote-text-face
1934 '((t (:inherit font-lock-comment-face
)))
1935 "Face for footnote text."
1936 :group
'markdown-faces
)
1938 (defface markdown-url-face
1939 '((t (:inherit font-lock-string-face
)))
1940 "Face for URLs that are part of markup.
1941 For example, this applies to URLs in inline links:
1942 [link text](http://example.com/)."
1943 :group
'markdown-faces
)
1945 (defface markdown-plain-url-face
1946 '((t (:inherit markdown-link-face
)))
1947 "Face for URLs that are also links.
1948 For example, this applies to plain angle bracket URLs:
1949 <http://example.com/>."
1950 :group
'markdown-faces
)
1952 (defface markdown-link-title-face
1953 '((t (:inherit font-lock-comment-face
)))
1954 "Face for reference link titles."
1955 :group
'markdown-faces
)
1957 (defface markdown-line-break-face
1958 '((t (:inherit font-lock-constant-face
:underline t
)))
1959 "Face for hard line breaks."
1960 :group
'markdown-faces
)
1962 (defface markdown-comment-face
1963 '((t (:inherit font-lock-comment-face
)))
1964 "Face for HTML comments."
1965 :group
'markdown-faces
)
1967 (defface markdown-math-face
1968 '((t (:inherit font-lock-string-face
)))
1969 "Face for LaTeX expressions."
1970 :group
'markdown-faces
)
1972 (defface markdown-metadata-key-face
1973 '((t (:inherit font-lock-variable-name-face
)))
1974 "Face for metadata keys."
1975 :group
'markdown-faces
)
1977 (defface markdown-metadata-value-face
1978 '((t (:inherit font-lock-string-face
)))
1979 "Face for metadata values."
1980 :group
'markdown-faces
)
1982 (defface markdown-gfm-checkbox-face
1983 '((t (:inherit font-lock-builtin-face
)))
1984 "Face for GFM checkboxes."
1985 :group
'markdown-faces
)
1987 (defface markdown-highlight-face
1988 '((t (:inherit highlight
)))
1989 "Face for mouse highlighting."
1990 :group
'markdown-faces
)
1992 (defface markdown-hr-face
1993 '((t (:inherit markdown-markup-face
)))
1994 "Face for horizontal rules."
1995 :group
'markdown-faces
)
1997 (defface markdown-html-tag-name-face
1998 '((t (:inherit font-lock-type-face
)))
1999 "Face for HTML tag names."
2000 :group
'markdown-faces
)
2002 (defface markdown-html-tag-delimiter-face
2003 '((t (:inherit markdown-markup-face
)))
2004 "Face for HTML tag delimiters."
2005 :group
'markdown-faces
)
2007 (defface markdown-html-attr-name-face
2008 '((t (:inherit font-lock-variable-name-face
)))
2009 "Face for HTML attribute names."
2010 :group
'markdown-faces
)
2012 (defface markdown-html-attr-value-face
2013 '((t (:inherit font-lock-string-face
)))
2014 "Face for HTML attribute values."
2015 :group
'markdown-faces
)
2017 (defface markdown-html-entity-face
2018 '((t (:inherit font-lock-variable-name-face
)))
2019 "Face for HTML entities."
2020 :group
'markdown-faces
)
2022 (defface markdown-highlighting-face
2023 '((t (:background
"yellow" :foreground
"black")))
2024 "Face for highlighting."
2025 :group
'markdown-faces
)
2027 (defcustom markdown-header-scaling nil
2028 "Whether to use variable-height faces for headers.
2029 When non-nil, `markdown-header-face' will inherit from
2030 `variable-pitch' and the scaling values in
2031 `markdown-header-scaling-values' will be applied to
2032 headers of levels one through six respectively."
2034 :initialize
#'custom-initialize-default
2035 :set
(lambda (symbol value
)
2036 (set-default symbol value
)
2037 (markdown-update-header-faces value
))
2038 :group
'markdown-faces
2039 :package-version
'(markdown-mode .
"2.2"))
2041 (defcustom markdown-header-scaling-values
2042 '(2.0
1.7 1.4 1.1 1.0 1.0)
2043 "List of scaling values for headers of level one through six.
2044 Used when `markdown-header-scaling' is non-nil."
2046 :initialize
#'custom-initialize-default
2047 :set
(lambda (symbol value
)
2048 (set-default symbol value
)
2049 (markdown-update-header-faces markdown-header-scaling value
)))
2051 (defmacro markdown--dotimes-when-compile
(i-n body
)
2052 (declare (indent 1) (debug ((symbolp form
) form
)))
2053 (let ((var (car i-n
))
2056 (dotimes (i (eval n t
))
2057 (push (eval body
`((,var .
,i
))) code
))
2058 `(progn ,@(nreverse code
))))
2060 (defface markdown-header-face
2061 `((t (:inherit
(,@(when markdown-header-scaling
'(variable-pitch))
2062 font-lock-function-name-face
)
2064 "Base face for headers.")
2066 (markdown--dotimes-when-compile (num 6)
2067 (let* ((num1 (1+ num
))
2068 (face-name (intern (format "markdown-header-face-%s" num1
))))
2069 `(defface ,face-name
2070 (,'\
` ((t (:inherit markdown-header-face
2072 (,'\
, (if markdown-header-scaling
2073 (float (nth ,num markdown-header-scaling-values
))
2075 (format "Face for level %s headers.
2076 You probably don't want to customize this face directly. Instead
2077 you can customize the base face `markdown-header-face' or the
2078 variable-height variable `markdown-header-scaling'." ,num1
))))
2080 (defun markdown-update-header-faces (&optional scaling scaling-values
)
2081 "Update header faces, depending on if header SCALING is desired.
2082 If so, use given list of SCALING-VALUES relative to the baseline
2083 size of `markdown-header-face'."
2085 (let* ((face-name (intern (format "markdown-header-face-%s" (1+ num
))))
2086 (scale (cond ((not scaling
) 1.0)
2087 (scaling-values (float (nth num scaling-values
)))
2088 (t (float (nth num markdown-header-scaling-values
))))))
2089 (unless (get face-name
'saved-face
) ; Don't update customized faces
2090 (set-face-attribute face-name nil
:height scale
)))))
2092 (defun markdown-syntactic-face (state)
2093 "Return font-lock face for characters with given STATE.
2094 See `font-lock-syntactic-face-function' for details."
2095 (let ((in-comment (nth 4 state
)))
2097 (in-comment 'markdown-comment-face
)
2100 (defcustom markdown-list-item-bullets
2101 '("●" "◎" "○" "◆" "◇" "►" "•")
2102 "List of bullets to use for unordered lists.
2103 It can contain any number of symbols, which will be repeated.
2104 Depending on your font, some reasonable choices are:
2105 ♥ ● ◇ ✚ ✜ ☯ ◆ ♠ ♣ ♦ ❀ ◆ ◖ ▶ ► • ★ ▸."
2107 :type
'(repeat (string :tag
"Bullet character"))
2108 :package-version
'(markdown-mode .
"2.3"))
2110 (defun markdown--footnote-marker-properties ()
2111 "Return a font-lock facespec expression for footnote marker text."
2112 `(face markdown-footnote-marker-face
2113 ,@(when markdown-hide-markup
2114 `(display ,markdown-footnote-display
))))
2116 (defun markdown--pandoc-inline-footnote-properties ()
2117 "Return a font-lock facespec expression for Pandoc inline footnote text."
2118 `(face markdown-footnote-text-face
2119 ,@(when markdown-hide-markup
2120 `(display ,markdown-footnote-display
))))
2122 (defvar markdown-mode-font-lock-keywords
2123 `((markdown-match-yaml-metadata-begin .
((1 'markdown-markup-face
)))
2124 (markdown-match-yaml-metadata-end .
((1 'markdown-markup-face
)))
2125 (markdown-match-yaml-metadata-key .
((1 'markdown-metadata-key-face
)
2126 (2 'markdown-markup-face
)
2127 (3 'markdown-metadata-value-face
)))
2128 (markdown-match-gfm-open-code-blocks .
((1 markdown-markup-properties
)
2129 (2 markdown-markup-properties nil t
)
2130 (3 markdown-language-keyword-properties nil t
)
2131 (4 markdown-language-info-properties nil t
)
2132 (5 markdown-markup-properties nil t
)))
2133 (markdown-match-gfm-close-code-blocks .
((0 markdown-markup-properties
)))
2134 (markdown-fontify-gfm-code-blocks)
2135 (markdown-fontify-tables)
2136 (markdown-match-fenced-start-code-block .
((1 markdown-markup-properties
)
2137 (2 markdown-markup-properties nil t
)
2138 (3 markdown-language-keyword-properties nil t
)
2139 (4 markdown-language-info-properties nil t
)
2140 (5 markdown-markup-properties nil t
)))
2141 (markdown-match-fenced-end-code-block .
((0 markdown-markup-properties
)))
2142 (markdown-fontify-fenced-code-blocks)
2143 (markdown-match-pre-blocks .
((0 'markdown-pre-face
)))
2144 (markdown-fontify-headings)
2145 (markdown-match-declarative-metadata .
((1 'markdown-metadata-key-face
)
2146 (2 'markdown-markup-face
)
2147 (3 'markdown-metadata-value-face
)))
2148 (markdown-match-pandoc-metadata .
((1 'markdown-markup-face
)
2149 (2 'markdown-markup-face
)
2150 (3 'markdown-metadata-value-face
)))
2151 (markdown-fontify-hrs)
2152 (markdown-match-code .
((1 markdown-markup-properties prepend
)
2153 (2 'markdown-inline-code-face prepend
)
2154 (3 markdown-markup-properties prepend
)))
2155 (,markdown-regex-kbd .
((1 markdown-markup-properties
)
2156 (2 'markdown-inline-code-face
)
2157 (3 markdown-markup-properties
)))
2158 (markdown-fontify-angle-uris)
2159 (,markdown-regex-email .
'markdown-plain-url-face
)
2160 (markdown-match-html-tag .
((1 'markdown-html-tag-delimiter-face t
)
2161 (2 'markdown-html-tag-name-face t
)
2162 (3 'markdown-html-tag-delimiter-face t
)
2163 ;; Anchored matcher for HTML tag attributes
2164 (,markdown-regex-html-attr
2165 ;; Before searching, move past tag
2166 ;; name; set limit at tag close.
2168 (goto-char (match-end 2)) (match-end 3))
2170 .
((1 'markdown-html-attr-name-face
)
2171 (3 'markdown-html-tag-delimiter-face nil t
)
2172 (4 'markdown-html-attr-value-face nil t
)))))
2173 (,markdown-regex-html-entity .
'markdown-html-entity-face
)
2174 (markdown-fontify-list-items)
2175 (,markdown-regex-footnote .
((1 markdown-markup-properties
) ; [^
2176 (2 (markdown--footnote-marker-properties)) ; label
2177 (3 markdown-markup-properties
))) ; ]
2178 (,markdown-regex-pandoc-inline-footnote .
((1 markdown-markup-properties
) ; ^
2179 (2 markdown-markup-properties
) ; [
2180 (3 (markdown--pandoc-inline-footnote-properties)) ; text
2181 (4 markdown-markup-properties
))) ; ]
2182 (markdown-match-includes .
((1 markdown-markup-properties
)
2183 (2 markdown-markup-properties nil t
)
2184 (3 markdown-include-title-properties nil t
)
2185 (4 markdown-markup-properties nil t
)
2186 (5 markdown-markup-properties
)
2187 (6 'markdown-url-face
)
2188 (7 markdown-markup-properties
)))
2189 (markdown-fontify-inline-links)
2190 (markdown-fontify-reference-links)
2191 (,markdown-regex-reference-definition .
((1 'markdown-markup-face
) ; [
2192 (2 'markdown-reference-face
) ; label
2193 (3 'markdown-markup-face
) ; ]
2194 (4 'markdown-markup-face
) ; :
2195 (5 'markdown-url-face
) ; url
2196 (6 'markdown-link-title-face
))) ; "title" (optional)
2197 (markdown-fontify-plain-uris)
2199 (markdown-match-math-single .
((1 'markdown-markup-face prepend
)
2200 (2 'markdown-math-face append
)
2201 (3 'markdown-markup-face prepend
)))
2203 (markdown-match-math-double .
((1 'markdown-markup-face prepend
)
2204 (2 'markdown-math-face append
)
2205 (3 'markdown-markup-face prepend
)))
2206 ;; Math mode \[..\] and \\[..\\]
2207 (markdown-match-math-display .
((1 'markdown-markup-face prepend
)
2208 (3 'markdown-math-face append
)
2209 (4 'markdown-markup-face prepend
)))
2210 (markdown-match-bold .
((1 markdown-markup-properties prepend
)
2211 (2 'markdown-bold-face append
)
2212 (3 markdown-markup-properties prepend
)))
2213 (markdown-match-italic .
((1 markdown-markup-properties prepend
)
2214 (2 'markdown-italic-face append
)
2215 (3 markdown-markup-properties prepend
)))
2216 (,markdown-regex-strike-through .
((3 markdown-markup-properties
)
2217 (4 'markdown-strike-through-face
)
2218 (5 markdown-markup-properties
)))
2219 (markdown--match-highlighting .
((3 markdown-markup-properties
)
2220 (4 'markdown-highlighting-face
)
2221 (5 markdown-markup-properties
)))
2222 (,markdown-regex-line-break .
(1 'markdown-line-break-face prepend
))
2223 (,markdown-regex-escape .
((1 markdown-markup-properties prepend
)))
2224 (markdown-fontify-sub-superscripts)
2225 (markdown-match-inline-attributes .
((0 markdown-markup-properties prepend
)))
2226 (markdown-match-leanpub-sections .
((0 markdown-markup-properties
)))
2227 (markdown-fontify-blockquotes)
2228 (markdown-match-wiki-link .
((0 'markdown-link-face prepend
))))
2229 "Syntax highlighting for Markdown files.")
2232 (defvar-local markdown-footnote-counter
0
2233 "Counter for footnote numbers.")
2235 (defconst markdown-footnote-chars
2237 "Regular expression matching any character for a footnote identifier.")
2239 (defconst markdown-regex-footnote-definition
2240 (concat "^ \\{0,3\\}\\[\\(\\^" markdown-footnote-chars
"*?\\)\\]:\\(?:[ \t]+\\|$\\)")
2241 "Regular expression matching a footnote definition, capturing the label.")
2244 ;;; Compatibility =============================================================
2246 (defun markdown--pandoc-reference-p ()
2247 (let ((bounds (bounds-of-thing-at-point 'word
)))
2248 (when (and bounds
(char-before (car bounds
)))
2249 (= (char-before (car bounds
)) ?
@))))
2251 (defun markdown-flyspell-check-word-p ()
2252 "Return t if `flyspell' should check word just before point.
2253 Used for `flyspell-generic-check-word-predicate'."
2255 (goto-char (1- (point)))
2256 ;; https://github.com/jrblevin/markdown-mode/issues/560
2257 ;; enable spell check YAML meta data
2258 (if (or (and (markdown-code-block-at-point-p)
2259 (not (markdown-text-property-at-point 'markdown-yaml-metadata-section
)))
2260 (markdown-inline-code-at-point-p)
2261 (markdown-in-comment-p)
2262 (markdown--face-p (point) '(markdown-reference-face
2263 markdown-markup-face
2264 markdown-plain-url-face
2265 markdown-inline-code-face
2267 (markdown--pandoc-reference-p))
2269 ;; If flyspell overlay is put, then remove it
2270 (let ((bounds (bounds-of-thing-at-point 'word
)))
2272 (cl-loop for ov in
(overlays-in (car bounds
) (cdr bounds
))
2273 when
(overlay-get ov
'flyspell-overlay
)
2275 (delete-overlay ov
)))))
2279 ;;; Markdown Parsing Functions ================================================
2281 (defun markdown-cur-line-blank-p ()
2282 "Return t if the current line is blank and nil otherwise."
2285 (looking-at-p markdown-regex-blank-line
)))
2287 (defun markdown-prev-line-blank ()
2288 "Return t if the previous line is blank and nil otherwise.
2289 If we are at the first line, then consider the previous line to be blank."
2290 (or (= (line-beginning-position) (point-min))
2293 (looking-at markdown-regex-blank-line
))))
2295 (defun markdown-prev-line-blank-p ()
2296 "Like `markdown-prev-line-blank', but preserve `match-data'."
2297 (save-match-data (markdown-prev-line-blank)))
2299 (defun markdown-next-line-blank-p ()
2300 "Return t if the next line is blank and nil otherwise.
2301 If we are at the last line, then consider the next line to be blank."
2302 (or (= (line-end-position) (point-max))
2305 (markdown-cur-line-blank-p))))
2307 (defun markdown-prev-line-indent ()
2308 "Return the number of leading whitespace characters in the previous line.
2309 Return 0 if the current line is the first line in the buffer."
2311 (if (= (line-beginning-position) (point-min))
2314 (current-indentation))))
2316 (defun markdown-next-line-indent ()
2317 "Return the number of leading whitespace characters in the next line.
2318 Return 0 if line is the last line in the buffer."
2320 (if (= (line-end-position) (point-max))
2323 (current-indentation))))
2325 (defun markdown-new-baseline ()
2326 "Determine if the current line begins a new baseline level.
2327 Assume point is positioned at beginning of line."
2328 (or (looking-at markdown-regex-header
)
2329 (looking-at markdown-regex-hr
)
2330 (and (= (current-indentation) 0)
2331 (not (looking-at markdown-regex-list
))
2332 (markdown-prev-line-blank))))
2334 (defun markdown-search-backward-baseline ()
2335 "Search backward baseline point with no indentation and not a list item."
2338 (while (not (or stop
(bobp)))
2339 (re-search-backward markdown-regex-block-separator-noindent nil t
)
2341 (goto-char (match-end 2))
2343 ((markdown-new-baseline)
2345 ((looking-at-p markdown-regex-list
)
2347 (t (setq stop t
)))))))
2349 (defun markdown-update-list-levels (marker indent levels
)
2350 "Update list levels given list MARKER, block INDENT, and current LEVELS.
2351 Here, MARKER is a string representing the type of list, INDENT is an integer
2352 giving the indentation, in spaces, of the current block, and LEVELS is a
2353 list of the indentation levels of parent list items. When LEVELS is nil,
2354 it means we are at baseline (not inside of a nested list)."
2356 ;; New list item at baseline.
2357 ((and marker
(null levels
))
2358 (setq levels
(list indent
)))
2359 ;; List item with greater indentation (four or more spaces).
2360 ;; Increase list level.
2361 ((and marker
(>= indent
(+ (car levels
) markdown-list-indent-width
)))
2362 (setq levels
(cons indent levels
)))
2363 ;; List item with greater or equal indentation (less than four spaces).
2364 ;; Do not increase list level.
2365 ((and marker
(>= indent
(car levels
)))
2367 ;; Lesser indentation level.
2368 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
2369 ;; indentation could move back more than one list level). Note
2370 ;; that this block need not be the beginning of list item.
2371 ((< indent
(car levels
))
2372 (while (and (> (length levels
) 1)
2373 (< indent
(+ (cadr levels
) markdown-list-indent-width
)))
2374 (setq levels
(cdr levels
)))
2376 ;; Otherwise, do nothing.
2379 (defun markdown-calculate-list-levels ()
2380 "Calculate list levels at point.
2381 Return a list of the form (n1 n2 n3 ...) where n1 is the
2382 indentation of the deepest nested list item in the branch of
2383 the list at the point, n2 is the indentation of the parent
2384 list item, and so on. The depth of the list item is therefore
2385 the length of the returned list. If the point is not at or
2386 immediately after a list item, return nil."
2388 (let ((first (point)) levels indent pre-regexp
)
2389 ;; Find a baseline point with zero list indentation
2390 (markdown-search-backward-baseline)
2391 ;; Search for all list items between baseline and LOC
2392 (while (and (< (point) first
)
2393 (re-search-forward markdown-regex-list first t
))
2394 (setq pre-regexp
(format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels
))))
2397 ;; Make sure this is not a header or hr
2398 ((markdown-new-baseline) (setq levels nil
))
2399 ;; Make sure this is not a line from a pre block
2400 ((looking-at-p pre-regexp
))
2401 ;; If not, then update levels
2403 (setq indent
(current-indentation))
2404 (setq levels
(markdown-update-list-levels (match-string 2)
2409 (defun markdown-prev-list-item (level)
2410 "Search backward from point for a list item with indentation LEVEL.
2411 Set point to the beginning of the item, and return point, or nil
2413 (let (bounds indent prev
)
2416 (setq indent
(current-indentation))
2420 ((and (looking-at-p markdown-regex-list
)
2421 (setq bounds
(markdown-cur-list-item-bounds)))
2423 ;; Stop and return point at item of equal indentation
2424 ((= (nth 3 bounds
) level
)
2427 ;; Stop and return nil at item with lesser indentation
2428 ((< (nth 3 bounds
) level
)
2431 ;; Stop at beginning of buffer
2432 ((bobp) (setq prev nil
))
2433 ;; Continue at item with greater indentation
2434 ((> (nth 3 bounds
) level
) t
)))
2435 ;; Stop at beginning of buffer
2436 ((bobp) (setq prev nil
))
2437 ;; Continue if current line is blank
2438 ((markdown-cur-line-blank-p) t
)
2439 ;; Continue while indentation is the same or greater
2440 ((>= indent level
) t
)
2441 ;; Stop if current indentation is less than list item
2442 ;; and the next is blank
2443 ((and (< indent level
)
2444 (markdown-next-line-blank-p))
2447 ((looking-at-p markdown-regex-header
) (setq prev nil
))
2448 ;; Stop at a horizontal rule
2449 ((looking-at-p markdown-regex-hr
) (setq prev nil
))
2450 ;; Otherwise, continue.
2453 (setq indent
(current-indentation)))
2456 (defun markdown-next-list-item (level)
2457 "Search forward from point for the next list item with indentation LEVEL.
2458 Set point to the beginning of the item, and return point, or nil
2460 (let (bounds indent next
)
2462 (if (looking-at markdown-regex-header-setext
)
2463 (goto-char (match-end 0)))
2465 (setq indent
(current-indentation))
2468 ;; Stop at end of the buffer.
2470 ;; Continue if the current line is blank
2471 ((markdown-cur-line-blank-p) t
)
2473 ((and (looking-at-p markdown-regex-list
)
2474 (setq bounds
(markdown-cur-list-item-bounds)))
2476 ;; Continue at item with greater indentation
2477 ((> (nth 3 bounds
) level
) t
)
2478 ;; Stop and return point at item of equal indentation
2479 ((= (nth 3 bounds
) level
)
2482 ;; Stop and return nil at item with lesser indentation
2483 ((< (nth 3 bounds
) level
)
2486 ;; Continue while indentation is the same or greater
2487 ((>= indent level
) t
)
2488 ;; Stop if current indentation is less than list item
2489 ;; and the previous line was blank.
2490 ((and (< indent level
)
2491 (markdown-prev-line-blank-p))
2494 ((looking-at-p markdown-regex-header
) (setq next nil
))
2495 ;; Stop at a horizontal rule
2496 ((looking-at-p markdown-regex-hr
) (setq next nil
))
2497 ;; Otherwise, continue.
2500 (setq indent
(current-indentation)))
2503 (defun markdown-cur-list-item-end (level)
2504 "Move to end of list item with pre-marker indentation LEVEL.
2505 Return the point at the end when a list item was found at the
2506 original point. If the point is not in a list item, do nothing."
2509 (setq indent
(current-indentation))
2512 ;; Stop at end of the buffer.
2514 ;; Continue while indentation is the same or greater
2515 ((>= indent level
) t
)
2516 ;; Continue if the current line is blank
2517 ((looking-at markdown-regex-blank-line
) t
)
2518 ;; Stop if current indentation is less than list item
2519 ;; and the previous line was blank.
2520 ((and (< indent level
)
2521 (markdown-prev-line-blank))
2523 ;; Stop at a new list items of the same or lesser
2524 ;; indentation, headings, and horizontal rules.
2525 ((looking-at (concat "\\(?:" markdown-regex-list
2526 "\\|" markdown-regex-header
2527 "\\|" markdown-regex-hr
"\\)"))
2529 ;; Otherwise, continue.
2532 (setq indent
(current-indentation)))
2533 ;; Don't skip over whitespace for empty list items (marker and
2534 ;; whitespace only), just move to end of whitespace.
2537 (looking-at (concat markdown-regex-list
"[ \t]*$")))
2538 (goto-char (match-end 3))
2539 (skip-chars-backward " \t\n"))
2543 (defun markdown-cur-list-item-bounds ()
2544 "Return bounds for list item at point.
2545 Return a list of the following form:
2547 (begin end indent nonlist-indent marker checkbox match)
2549 The named components are:
2551 - begin: Position of beginning of list item, including leading indentation.
2552 - end: Position of the end of the list item, including list item text.
2553 - indent: Number of characters of indentation before list marker (an integer).
2554 - nonlist-indent: Number characters of indentation, list
2555 marker, and whitespace following list marker (an integer).
2556 - marker: String containing the list marker and following whitespace
2557 (e.g., \"- \" or \"* \").
2558 - checkbox: String containing the GFM checkbox portion, if any,
2559 including any trailing whitespace before the text
2560 begins (e.g., \"[x] \").
2561 - match: match data for markdown-regex-list
2563 As an example, for the following unordered list item
2567 the returned list would be
2569 (1 14 3 5 \"- \" nil (1 6 1 4 4 5 5 6))
2571 If the point is not inside a list item, return nil."
2572 (car (get-text-property (line-beginning-position) 'markdown-list-item
)))
2574 (defun markdown-list-item-at-point-p ()
2575 "Return t if there is a list item at the point and nil otherwise."
2576 (save-match-data (markdown-cur-list-item-bounds)))
2578 (defun markdown-prev-list-item-bounds ()
2579 "Return bounds of previous item in the same list of any level.
2580 The return value has the same form as that of
2581 `markdown-cur-list-item-bounds'."
2583 (let ((cur-bounds (markdown-cur-list-item-bounds))
2584 (beginning-of-list (save-excursion (markdown-beginning-of-list)))
2587 (goto-char (nth 0 cur-bounds
))
2588 (while (and (not stop
) (not (bobp))
2589 (re-search-backward markdown-regex-list
2590 beginning-of-list t
))
2591 (unless (or (looking-at markdown-regex-hr
)
2592 (markdown-code-block-at-point-p))
2593 (setq stop
(point))))
2594 (markdown-cur-list-item-bounds)))))
2596 (defun markdown-next-list-item-bounds ()
2597 "Return bounds of next item in the same list of any level.
2598 The return value has the same form as that of
2599 `markdown-cur-list-item-bounds'."
2601 (let ((cur-bounds (markdown-cur-list-item-bounds))
2602 (end-of-list (save-excursion (markdown-end-of-list)))
2605 (goto-char (nth 0 cur-bounds
))
2607 (while (and (not stop
) (not (eobp))
2608 (re-search-forward markdown-regex-list
2610 (unless (or (looking-at markdown-regex-hr
)
2611 (markdown-code-block-at-point-p))
2612 (setq stop
(point))))
2614 (markdown-cur-list-item-bounds))))))
2616 (defun markdown-beginning-of-list ()
2617 "Move point to beginning of list at point, if any."
2619 (let ((orig-point (point))
2620 (list-begin (save-excursion
2621 (markdown-search-backward-baseline)
2622 ;; Stop at next list item, regardless of the indentation.
2623 (markdown-next-list-item (point-max))
2624 (when (looking-at markdown-regex-list
)
2626 (when (and list-begin
(<= list-begin orig-point
))
2627 (goto-char list-begin
))))
2629 (defun markdown-end-of-list ()
2630 "Move point to end of list at point, if any."
2632 (let ((start (point))
2633 (end (save-excursion
2634 (when (markdown-beginning-of-list)
2635 ;; Items can't have nonlist-indent <= 1, so this
2636 ;; moves past all list items.
2637 (markdown-next-list-item 1)
2638 (skip-syntax-backward "-")
2639 (unless (eobp) (forward-char 1))
2641 (when (and end
(>= end start
))
2644 (defun markdown-up-list ()
2645 "Move point to beginning of parent list item."
2647 (let ((cur-bounds (markdown-cur-list-item-bounds)))
2649 (markdown-prev-list-item (1- (nth 3 cur-bounds
)))
2650 (let ((up-bounds (markdown-cur-list-item-bounds)))
2651 (when (and up-bounds
(< (nth 3 up-bounds
) (nth 3 cur-bounds
)))
2654 (defun markdown-bounds-of-thing-at-point (thing)
2655 "Call `bounds-of-thing-at-point' for THING with slight modifications.
2656 Does not include trailing newlines when THING is \\='line. Handles the
2657 end of buffer case by setting both endpoints equal to the value of
2658 `point-max', since an empty region will trigger empty markup insertion.
2659 Return bounds of form (beg . end) if THING is found, or nil otherwise."
2660 (let* ((bounds (bounds-of-thing-at-point thing
))
2664 (when (eq thing
'line
)
2665 (cond ((and (eobp) (markdown-cur-line-blank-p))
2667 ((char-equal (char-before b
) ?\^J
)
2671 (defun markdown-reference-definition (reference)
2672 "Find out whether Markdown REFERENCE is defined.
2673 REFERENCE should not include the square brackets.
2674 When REFERENCE is defined, return a list of the form (text start end)
2675 containing the definition text itself followed by the start and end
2676 locations of the text. Otherwise, return nil.
2677 Leave match data for `markdown-regex-reference-definition'
2678 intact additional processing."
2679 (let ((reference (downcase reference
)))
2681 (goto-char (point-min))
2683 (while (re-search-forward markdown-regex-reference-definition nil t
)
2684 (when (string= reference
(downcase (match-string-no-properties 2)))
2686 (list (match-string-no-properties 5)
2687 (match-beginning 5) (match-end 5)))))))))
2689 (defun markdown-get-defined-references ()
2690 "Return all defined reference labels and their line numbers.
2691 They does not include square brackets)."
2693 (goto-char (point-min))
2695 (while (re-search-forward markdown-regex-reference-definition nil t
)
2696 (let ((target (match-string-no-properties 2)))
2698 (cons (downcase target
)
2699 (markdown-line-number-at-pos (match-beginning 2)))
2700 refs
:test
#'equal
:key
#'car
)))
2703 (defun markdown-get-used-uris ()
2704 "Return a list of all used URIs in the buffer."
2706 (goto-char (point-min))
2708 (while (re-search-forward
2709 (concat "\\(?:" markdown-regex-link-inline
2710 "\\|" markdown-regex-angle-uri
2711 "\\|" markdown-regex-uri
2712 "\\|" markdown-regex-email
2715 (unless (or (markdown-inline-code-at-point-p)
2716 (markdown-code-block-at-point-p))
2717 (cl-pushnew (or (match-string-no-properties 6)
2718 (match-string-no-properties 10)
2719 (match-string-no-properties 12)
2720 (match-string-no-properties 13))
2721 uris
:test
#'equal
)))
2724 (defun markdown-inline-code-at-pos (pos)
2725 "Return non-nil if there is an inline code fragment at POS.
2726 Return nil otherwise. Set match data according to
2727 `markdown-match-code' upon success.
2728 This function searches the block for a code fragment that
2729 contains the point using `markdown-match-code'. We do this
2730 because `thing-at-point-looking-at' does not work reliably with
2731 `markdown-regex-code'.
2733 The match data is set as follows:
2734 Group 1 matches the opening backquotes.
2735 Group 2 matches the code fragment itself, without backquotes.
2736 Group 3 matches the closing backquotes."
2739 (let ((old-point (point))
2740 (end-of-block (progn (markdown-end-of-text-block) (point)))
2742 (markdown-beginning-of-text-block)
2743 (while (and (markdown-match-code end-of-block
)
2745 (< (match-end 0) old-point
)))
2746 (let ((match-group (if (eq (char-after (match-beginning 0)) ?
`) 0 1)))
2747 (and found
; matched something
2748 (<= (match-beginning match-group
) old-point
) ; match contains old-point
2749 (> (match-end 0) old-point
))))))
2751 (defun markdown-inline-code-at-pos-p (pos)
2752 "Return non-nil if there is an inline code fragment at POS.
2753 Like `markdown-inline-code-at-pos`, but preserves match data."
2754 (save-match-data (markdown-inline-code-at-pos pos
)))
2756 (defun markdown-inline-code-at-point ()
2757 "Return non-nil if the point is at an inline code fragment.
2758 See `markdown-inline-code-at-pos' for details."
2759 (markdown-inline-code-at-pos (point)))
2761 (defun markdown-inline-code-at-point-p (&optional pos
)
2762 "Return non-nil if there is inline code at the POS.
2763 This is a predicate function counterpart to
2764 `markdown-inline-code-at-point' which does not modify the match
2765 data. See `markdown-code-block-at-point-p' for code blocks."
2766 (save-match-data (markdown-inline-code-at-pos (or pos
(point)))))
2768 (defun markdown-code-block-at-pos (pos)
2769 "Return match data list if there is a code block at POS.
2770 Uses text properties at the beginning of the line position.
2771 This includes pre blocks, tilde-fenced code blocks, and GFM
2772 quoted code blocks. Return nil otherwise."
2773 (let ((bol (save-excursion (goto-char pos
) (line-beginning-position))))
2774 (or (get-text-property bol
'markdown-pre
)
2775 (let* ((bounds (markdown-get-enclosing-fenced-block-construct pos
))
2776 (second (cl-second bounds
)))
2778 ;; chunks are right open
2779 (when (< pos second
)
2783 ;; Function was renamed to emphasize that it does not modify match-data.
2784 (defalias 'markdown-code-block-at-point
'markdown-code-block-at-point-p
)
2786 (defun markdown-code-block-at-point-p (&optional pos
)
2787 "Return non-nil if there is a code block at the POS.
2788 This includes pre blocks, tilde-fenced code blocks, and GFM
2789 quoted code blocks. This function does not modify the match
2790 data. See `markdown-inline-code-at-point-p' for inline code."
2791 (save-match-data (markdown-code-block-at-pos (or pos
(point)))))
2793 (defun markdown-heading-at-point (&optional pos
)
2794 "Return non-nil if there is a heading at the POS.
2795 Set match data for `markdown-regex-header'."
2796 (let ((match-data (get-text-property (or pos
(point)) 'markdown-heading
)))
2798 (set-match-data match-data
)
2801 (defun markdown-pipe-at-bol-p ()
2802 "Return non-nil if the line begins with a pipe symbol.
2803 This may be useful for tables and Pandoc's line_blocks extension."
2804 (char-equal (char-after (line-beginning-position)) ?|
))
2807 ;;; Markdown Font Lock Matching Functions =====================================
2809 (defun markdown-range-property-any (begin end prop prop-values
)
2810 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
2811 Also returns t if PROP is a list containing one of the PROP-VALUES.
2812 Return nil otherwise."
2815 (dolist (loc (number-sequence begin end
))
2816 (when (setq props
(get-text-property loc prop
))
2817 (cond ((listp props
)
2818 ;; props is a list, check for membership
2819 (dolist (val prop-values
)
2820 (when (memq val props
) (throw 'found loc
))))
2822 ;; props is a scalar, check for equality
2823 (dolist (val prop-values
)
2824 (when (eq val props
) (throw 'found loc
))))))))))
2826 (defun markdown-range-properties-exist (begin end props
)
2828 for loc in
(number-sequence begin end
)
2832 (cl-some (lambda (prop) (get-text-property loc prop
)) props
)))
2833 finally return result
))
2835 (defun markdown-match-inline-generic (regex last
&optional faceless
)
2836 "Match inline REGEX from the point to LAST.
2837 When FACELESS is non-nil, do not return matches where faces have been applied."
2838 (when (re-search-forward regex last t
)
2839 (let ((bounds (markdown-code-block-at-pos (match-beginning 1)))
2840 (face (and faceless
(text-property-not-all
2841 (match-beginning 0) (match-end 0) 'face nil
))))
2843 ;; In code block: move past it and recursively search again
2845 (when (< (goto-char (cl-second bounds
)) last
)
2846 (markdown-match-inline-generic regex last faceless
)))
2847 ;; When faces are found in the match range, skip over the match and
2848 ;; recursively search again.
2850 (when (< (goto-char (match-end 0)) last
)
2851 (markdown-match-inline-generic regex last faceless
)))
2852 ;; Keep match data and return t when in bounds.
2854 (<= (match-end 0) last
))))))
2856 (defun markdown-match-code (last)
2857 "Match inline code fragments from point to LAST."
2860 (when (markdown-search-until-condition
2863 ;; Advance point in case of failure, but without exceeding last.
2864 (goto-char (min (1+ (match-beginning 1)) last
))
2865 (not (markdown-in-comment-p (match-beginning 1)))
2866 (not (markdown-in-comment-p (match-end 1)))
2867 (not (markdown-code-block-at-pos (match-beginning 1)))))
2868 markdown-regex-code last t
)
2869 (set-match-data (list (match-beginning 1) (match-end 1)
2870 (match-beginning 2) (match-end 2)
2871 (match-beginning 3) (match-end 3)
2872 (match-beginning 4) (match-end 4)))
2873 (goto-char (min (1+ (match-end 0)) last
(point-max)))
2876 (defun markdown--gfm-markup-underscore-p (begin end
)
2877 (let ((is-underscore (eql (char-after begin
) ?_
)))
2878 (if (not is-underscore
)
2883 (and (looking-back "\\(?:^\\|[[:blank:][:punct:]]\\)" (1- begin
))
2886 (looking-at-p "\\(?:[[:blank:][:punct:]]\\|$\\)"))))))))
2888 (defun markdown-match-bold (last)
2889 "Match inline bold from the point to LAST."
2890 (when (markdown-match-inline-generic markdown-regex-bold last
)
2891 (let ((is-gfm (derived-mode-p 'gfm-mode
))
2892 (begin (match-beginning 2))
2893 (end (match-end 2)))
2894 (if (or (markdown-inline-code-at-pos-p begin
)
2895 (markdown-inline-code-at-pos-p end
)
2896 (markdown-in-comment-p)
2897 (markdown-range-property-any
2898 begin begin
'face
'(markdown-url-face
2899 markdown-plain-url-face
))
2900 (markdown-range-property-any
2901 begin end
'face
'(markdown-hr-face
2902 markdown-math-face
))
2903 (and is-gfm
(not (markdown--gfm-markup-underscore-p begin end
))))
2904 (progn (goto-char (min (1+ begin
) last
))
2905 (when (< (point) last
)
2906 (markdown-match-bold last
)))
2907 (set-match-data (list (match-beginning 2) (match-end 2)
2908 (match-beginning 3) (match-end 3)
2909 (match-beginning 4) (match-end 4)
2910 (match-beginning 5) (match-end 5)))
2913 (defun markdown-match-italic (last)
2914 "Match inline italics from the point to LAST."
2915 (let* ((is-gfm (derived-mode-p 'gfm-mode
))
2917 markdown-regex-gfm-italic
2918 markdown-regex-italic
)))
2919 (when (and (markdown-match-inline-generic regex last
)
2920 (not (markdown--face-p
2922 '(markdown-html-attr-name-face markdown-html-attr-value-face
))))
2923 (let ((begin (match-beginning 1))
2925 (close-end (match-end 4)))
2926 (if (or (eql (char-before begin
) (char-after begin
))
2927 (markdown-inline-code-at-pos-p begin
)
2928 (markdown-inline-code-at-pos-p (1- end
))
2929 (markdown-in-comment-p)
2930 (markdown-range-property-any
2931 begin begin
'face
'(markdown-url-face
2932 markdown-plain-url-face
2933 markdown-markup-face
))
2934 (markdown-range-property-any
2935 begin end
'face
'(markdown-bold-face
2938 markdown-math-face
))
2940 (or (char-equal (char-after begin
) (char-after (1+ begin
))) ;; check bold case
2941 (not (markdown--gfm-markup-underscore-p begin close-end
)))))
2942 (progn (goto-char (min (1+ begin
) last
))
2943 (when (< (point) last
)
2944 (markdown-match-italic last
)))
2945 (set-match-data (list (match-beginning 1) (match-end 1)
2946 (match-beginning 2) (match-end 2)
2947 (match-beginning 3) (match-end 3)
2948 (match-beginning 4) (match-end 4)))
2951 (defun markdown--match-highlighting (last)
2952 (when markdown-enable-highlighting-syntax
2953 (re-search-forward markdown-regex-highlighting last t
)))
2955 (defun markdown-match-math-generic (regex last
)
2956 "Match REGEX from point to LAST.
2957 REGEX is either `markdown-regex-math-inline-single' for matching
2958 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
2959 (when (markdown-match-inline-generic regex last
)
2960 (let ((begin (match-beginning 1)) (end (match-end 1)))
2962 (if (or (markdown-range-property-any
2964 '(markdown-inline-code-face markdown-bold-face
))
2965 (markdown-range-properties-exist
2967 (markdown-get-fenced-block-middle-properties)))
2968 (markdown-match-math-generic regex last
)
2970 (goto-char (1+ (match-end 0)))))))
2972 (defun markdown-match-list-items (last)
2973 "Match list items from point to LAST."
2974 (let* ((first (point))
2976 (prop 'markdown-list-item
)
2977 (bounds (car (get-text-property pos prop
))))
2979 (and (or (null (setq bounds
(car (get-text-property pos prop
))))
2980 (< (cl-first bounds
) pos
))
2982 (setq pos
(next-single-property-change pos prop nil last
))
2985 (set-match-data (cl-seventh bounds
))
2986 ;; Step at least one character beyond point. Otherwise
2987 ;; `font-lock-fontify-keywords-region' infloops.
2988 (goto-char (min (1+ (max (line-end-position) first
))
2992 (defun markdown-match-math-single (last)
2993 "Match single quoted $..$ math from point to LAST."
2994 (when markdown-enable-math
2995 (when (and (char-equal (char-after) ?$
)
2997 (not (char-equal (char-before) ?
\\))
2998 (not (char-equal (char-before) ?$
)))
3000 (markdown-match-math-generic markdown-regex-math-inline-single last
)))
3002 (defun markdown-match-math-double (last)
3003 "Match double quoted $$..$$ math from point to LAST."
3004 (when markdown-enable-math
3005 (when (and (< (1+ (point)) (point-max))
3006 (char-equal (char-after) ?$
)
3007 (char-equal (char-after (1+ (point))) ?$
)
3009 (not (char-equal (char-before) ?
\\))
3010 (not (char-equal (char-before) ?$
)))
3012 (markdown-match-math-generic markdown-regex-math-inline-double last
)))
3014 (defun markdown-match-math-display (last)
3015 "Match bracketed display math \[..\] and \\[..\\] from point to LAST."
3016 (when markdown-enable-math
3017 (markdown-match-math-generic markdown-regex-math-display last
)))
3019 (defun markdown-match-propertized-text (property last
)
3020 "Match text with PROPERTY from point to LAST.
3021 Restore match data previously stored in PROPERTY."
3022 (let ((saved (get-text-property (point) property
))
3025 (setq pos
(next-single-property-change (point) property nil last
))
3026 (unless (= pos last
)
3027 (setq saved
(get-text-property pos property
))))
3029 (set-match-data saved
)
3030 ;; Step at least one character beyond point. Otherwise
3031 ;; `font-lock-fontify-keywords-region' infloops.
3032 (goto-char (min (1+ (max (match-end 0) (point)))
3036 (defun markdown-match-pre-blocks (last)
3037 "Match preformatted blocks from point to LAST.
3038 Use data stored in \\='markdown-pre text property during syntax
3040 (markdown-match-propertized-text 'markdown-pre last
))
3042 (defun markdown-match-gfm-code-blocks (last)
3043 "Match GFM quoted code blocks from point to LAST.
3044 Use data stored in \\='markdown-gfm-code text property during syntax
3046 (markdown-match-propertized-text 'markdown-gfm-code last
))
3048 (defun markdown-match-gfm-open-code-blocks (last)
3049 (markdown-match-propertized-text 'markdown-gfm-block-begin last
))
3051 (defun markdown-match-gfm-close-code-blocks (last)
3052 (markdown-match-propertized-text 'markdown-gfm-block-end last
))
3054 (defun markdown-match-fenced-code-blocks (last)
3055 "Match fenced code blocks from the point to LAST."
3056 (markdown-match-propertized-text 'markdown-fenced-code last
))
3058 (defun markdown-match-fenced-start-code-block (last)
3059 (markdown-match-propertized-text 'markdown-tilde-fence-begin last
))
3061 (defun markdown-match-fenced-end-code-block (last)
3062 (markdown-match-propertized-text 'markdown-tilde-fence-end last
))
3064 (defun markdown-match-blockquotes (last)
3065 "Match blockquotes from point to LAST.
3066 Use data stored in \\='markdown-blockquote text property during syntax
3068 (markdown-match-propertized-text 'markdown-blockquote last
))
3070 (defun markdown-match-hr (last)
3071 "Match horizontal rules comments from the point to LAST."
3072 (markdown-match-propertized-text 'markdown-hr last
))
3074 (defun markdown-match-comments (last)
3075 "Match HTML comments from the point to LAST."
3076 (when (and (skip-syntax-forward "^<" last
))
3077 (let ((beg (point)))
3078 (when (and (skip-syntax-forward "^>" last
) (< (point) last
))
3080 (set-match-data (list beg
(point)))
3083 (defun markdown-match-generic-links (last ref
)
3084 "Match inline links from point to LAST.
3085 When REF is non-nil, match reference links instead of standard
3087 This function should only be used during font-lock, as it
3088 determines syntax based on the presence of faces for previously
3089 processed elements."
3090 ;; Search for the next potential link (not in a code block).
3091 (let ((prohibited-faces '(markdown-pre-face
3093 markdown-inline-code-face
3094 markdown-comment-face
))
3097 (and (not found
) (< (point) last
)
3099 ;; Clear match data to test for a match after functions returns.
3100 (set-match-data nil
)
3101 ;; Preliminary regular expression search so we can return
3102 ;; quickly upon failure. This doesn't handle malformed links
3103 ;; or nested square brackets well, so if it passes we back up
3104 ;; continue with a more precise search.
3107 markdown-regex-link-reference
3108 markdown-regex-link-inline
)
3110 ;; Keep searching if this is in a code block, inline code, or a
3111 ;; comment, or if it is include syntax. The link text portion
3112 ;; (group 3) may contain inline code or comments, but the
3113 ;; markup, URL, and title should not be part of such elements.
3114 (if (or (markdown-range-property-any
3115 (match-beginning 0) (match-end 2) 'face prohibited-faces
)
3116 (markdown-range-property-any
3117 (match-beginning 4) (match-end 0) 'face prohibited-faces
)
3118 (and (char-equal (char-after (line-beginning-position)) ?
<)
3119 (char-equal (char-after (1+ (line-beginning-position))) ?
<)))
3120 (set-match-data nil
)
3122 ;; Match opening exclamation point (optional) and left bracket.
3123 (when (match-beginning 2)
3124 (let* ((bang (match-beginning 1))
3125 (first-begin (match-beginning 2))
3126 ;; Find end of block to prevent matching across blocks.
3127 (end-of-block (save-excursion
3129 (goto-char (match-beginning 2))
3130 (markdown-end-of-text-block)
3132 ;; Move over balanced expressions to closing right bracket.
3133 ;; Catch unbalanced expression errors and return nil.
3134 (first-end (condition-case nil
3135 (and (goto-char first-begin
)
3136 (scan-sexps (point) 1))
3138 ;; Continue with point at CONT-POINT upon failure.
3139 (cont-point (min (1+ first-begin
) last
))
3140 second-begin second-end url-begin url-end
3141 title-begin title-end
)
3142 ;; When bracket found, in range, and followed by a left paren/bracket...
3143 (when (and first-end
(< first-end end-of-block
) (goto-char first-end
)
3144 (char-equal (char-after (point)) (if ref ?\
[ ?\
()))
3145 ;; Scan across balanced expressions for closing parenthesis/bracket.
3146 (setq second-begin
(point)
3147 second-end
(condition-case nil
3148 (scan-sexps (point) 1)
3150 ;; Check that closing parenthesis/bracket is in range.
3151 (if (and second-end
(<= second-end end-of-block
) (<= second-end last
))
3153 ;; Search for (optional) title inside closing parenthesis
3154 (when (and (not ref
) (search-forward "\"" second-end t
))
3155 (setq title-begin
(1- (point))
3156 title-end
(and (goto-char second-end
)
3157 (search-backward "\"" (1+ title-begin
) t
))
3158 title-end
(and title-end
(1+ title-end
))))
3159 ;; Store URL/reference range
3160 (setq url-begin
(1+ second-begin
)
3161 url-end
(1- (or title-begin second-end
)))
3162 ;; Set match data, move point beyond link, and return
3164 (list (or bang first-begin
) second-end
; 0 - all
3165 bang
(and bang
(1+ bang
)) ; 1 - bang
3166 first-begin
(1+ first-begin
) ; 2 - markup
3167 (1+ first-begin
) (1- first-end
) ; 3 - link text
3168 (1- first-end
) first-end
; 4 - markup
3169 second-begin
(1+ second-begin
) ; 5 - markup
3170 url-begin url-end
; 6 - url/reference
3171 title-begin title-end
; 7 - title
3172 (1- second-end
) second-end
)) ; 8 - markup
3173 ;; Nullify cont-point and leave point at end and
3174 (setq cont-point nil
)
3175 (goto-char second-end
))
3176 ;; If no closing parenthesis in range, update continuation point
3177 (setq cont-point
(min end-of-block second-begin
))))
3179 ;; On failure, continue searching at cont-point
3180 ((and cont-point
(< cont-point last
))
3181 (goto-char cont-point
)
3182 (markdown-match-generic-links last ref
))
3183 ;; No more text, return nil
3184 ((and cont-point
(= cont-point last
))
3186 ;; Return t if a match occurred
3189 (defun markdown-match-angle-uris (last)
3190 "Match angle bracket URIs from point to LAST."
3191 (when (markdown-match-inline-generic markdown-regex-angle-uri last
)
3192 (goto-char (1+ (match-end 0)))))
3194 (defun markdown-match-plain-uris (last)
3195 "Match plain URIs from point to LAST."
3196 (when (markdown-match-inline-generic markdown-regex-uri last t
)
3197 (goto-char (1+ (match-end 0)))))
3199 (defvar markdown-conditional-search-function
#'re-search-forward
3200 "Conditional search function used in `markdown-search-until-condition'.
3201 Made into a variable to allow for dynamic let-binding.")
3203 (defun markdown-search-until-condition (condition &rest args
)
3205 (while (and (not ret
) (apply markdown-conditional-search-function args
))
3206 (setq ret
(funcall condition
)))
3209 (defun markdown-metadata-line-p (pos regexp
)
3211 (or (= (line-number-at-pos pos
) 1)
3214 ;; skip multi-line metadata
3215 (while (and (looking-at-p "^\\s-+[[:alpha:]]")
3216 (> (line-number-at-pos (point)) 1))
3218 (looking-at-p regexp
)))))
3220 (defun markdown-match-generic-metadata (regexp last
)
3221 "Match metadata declarations specified by REGEXP from point to LAST.
3222 These declarations must appear inside a metadata block that begins at
3223 the beginning of the buffer and ends with a blank line (or the end of
3225 (let* ((first (point))
3226 (end-re "\n[ \t]*\n\\|\n\\'\\|\\'")
3227 (block-begin (goto-char 1))
3228 (block-end (re-search-forward end-re nil t
)))
3229 (if (and block-end
(> first block-end
))
3230 ;; Don't match declarations if there is no metadata block or if
3231 ;; the point is beyond the block. Move point to point-max to
3232 ;; prevent additional searches and return return nil since nothing
3234 (progn (goto-char (point-max)) nil
)
3235 ;; If a block was found that begins before LAST and ends after
3236 ;; point, search for declarations inside it. If the starting is
3237 ;; before the beginning of the block, start there. Otherwise,
3238 ;; move back to FIRST.
3239 (goto-char (if (< first block-begin
) block-begin first
))
3240 (if (and (re-search-forward regexp
(min last block-end
) t
)
3241 (markdown-metadata-line-p (point) regexp
))
3242 ;; If a metadata declaration is found, set match-data and return t.
3243 (let ((key-beginning (match-beginning 1))
3244 (key-end (match-end 1))
3245 (markup-begin (match-beginning 2))
3246 (markup-end (match-end 2))
3247 (value-beginning (match-beginning 3)))
3248 (set-match-data (list key-beginning
(point) ; complete metadata
3249 key-beginning key-end
; key
3250 markup-begin markup-end
; markup
3251 value-beginning
(point))) ; value
3253 ;; Otherwise, move the point to last and return nil
3257 (defun markdown-match-declarative-metadata (last)
3258 "Match declarative metadata from the point to LAST."
3259 (markdown-match-generic-metadata markdown-regex-declarative-metadata last
))
3261 (defun markdown-match-pandoc-metadata (last)
3262 "Match Pandoc metadata from the point to LAST."
3263 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last
))
3265 (defun markdown-match-yaml-metadata-begin (last)
3266 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last
))
3268 (defun markdown-match-yaml-metadata-end (last)
3269 (markdown-match-propertized-text 'markdown-yaml-metadata-end last
))
3271 (defun markdown-match-yaml-metadata-key (last)
3272 (markdown-match-propertized-text 'markdown-metadata-key last
))
3274 (defun markdown-match-wiki-link (last)
3275 "Match wiki links from point to LAST."
3276 (when (and markdown-enable-wiki-links
3277 (not markdown-wiki-link-fontify-missing
)
3278 (markdown-match-inline-generic markdown-regex-wiki-link last
))
3279 (let ((begin (match-beginning 1)) (end (match-end 1)))
3280 (if (or (markdown-in-comment-p begin
)
3281 (markdown-in-comment-p end
)
3282 (markdown-inline-code-at-pos-p begin
)
3283 (markdown-inline-code-at-pos-p end
)
3284 (markdown-code-block-at-pos begin
))
3285 (progn (goto-char (min (1+ begin
) last
))
3286 (when (< (point) last
)
3287 (markdown-match-wiki-link last
)))
3288 (set-match-data (list begin end
))
3291 (defun markdown-match-inline-attributes (last)
3292 "Match inline attributes from point to LAST."
3293 ;; #428 re-search-forward markdown-regex-inline-attributes is very slow.
3294 ;; So use simple regex for re-search-forward and use markdown-regex-inline-attributes
3295 ;; against matched string.
3296 (when (markdown-match-inline-generic "[ \t]*\\({\\)\\([^\n]*\\)}[ \t]*$" last
)
3297 (if (not (string-match-p markdown-regex-inline-attributes
(match-string 0)))
3298 (markdown-match-inline-attributes last
)
3299 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
3300 (markdown-inline-code-at-pos-p (match-end 0))
3301 (markdown-in-comment-p))
3304 (defun markdown-match-leanpub-sections (last)
3305 "Match Leanpub section markers from point to LAST."
3306 (when (markdown-match-inline-generic markdown-regex-leanpub-sections last
)
3307 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
3308 (markdown-inline-code-at-pos-p (match-end 0))
3309 (markdown-in-comment-p))
3312 (defun markdown-match-includes (last)
3313 "Match include statements from point to LAST.
3314 Sets match data for the following seven groups:
3315 Group 1: opening two angle brackets
3316 Group 2: opening title delimiter (optional)
3317 Group 3: title text (optional)
3318 Group 4: closing title delimiter (optional)
3319 Group 5: opening filename delimiter
3321 Group 7: closing filename delimiter"
3322 (when (markdown-match-inline-generic markdown-regex-include last
)
3323 (let ((valid (not (or (markdown-in-comment-p (match-beginning 0))
3324 (markdown-in-comment-p (match-end 0))
3325 (markdown-code-block-at-pos (match-beginning 0))))))
3327 ;; Parentheses and maybe square brackets, but no curly braces:
3328 ;; match optional title in square brackets and file in parentheses.
3329 ((and valid
(match-beginning 5)
3330 (not (match-beginning 8)))
3331 (set-match-data (list (match-beginning 1) (match-end 7)
3332 (match-beginning 1) (match-end 1)
3333 (match-beginning 2) (match-end 2)
3334 (match-beginning 3) (match-end 3)
3335 (match-beginning 4) (match-end 4)
3336 (match-beginning 5) (match-end 5)
3337 (match-beginning 6) (match-end 6)
3338 (match-beginning 7) (match-end 7))))
3339 ;; Only square brackets present: match file in square brackets.
3340 ((and valid
(match-beginning 2)
3341 (not (match-beginning 5))
3342 (not (match-beginning 7)))
3343 (set-match-data (list (match-beginning 1) (match-end 4)
3344 (match-beginning 1) (match-end 1)
3348 (match-beginning 2) (match-end 2)
3349 (match-beginning 3) (match-end 3)
3350 (match-beginning 4) (match-end 4))))
3351 ;; Only curly braces present: match file in curly braces.
3352 ((and valid
(match-beginning 8)
3353 (not (match-beginning 2))
3354 (not (match-beginning 5)))
3355 (set-match-data (list (match-beginning 1) (match-end 10)
3356 (match-beginning 1) (match-end 1)
3360 (match-beginning 8) (match-end 8)
3361 (match-beginning 9) (match-end 9)
3362 (match-beginning 10) (match-end 10))))
3364 ;; Not a valid match, move to next line and search again.
3366 (when (< (point) last
)
3367 (setq valid
(markdown-match-includes last
)))))
3370 (defun markdown-match-html-tag (last)
3371 "Match HTML tags from point to LAST."
3372 (when (and markdown-enable-html
3373 (markdown-match-inline-generic markdown-regex-html-tag last t
))
3374 (set-match-data (list (match-beginning 0) (match-end 0)
3375 (match-beginning 1) (match-end 1)
3376 (match-beginning 2) (match-end 2)
3377 (match-beginning 9) (match-end 9)))
3381 ;;; Markdown Font Fontification Functions =====================================
3383 (defvar markdown--first-displayable-cache
(make-hash-table :test
#'equal
))
3385 (defun markdown--first-displayable (seq)
3386 "Return the first displayable character or string in SEQ.
3387 SEQ may be an atom or a sequence."
3388 (let ((c (gethash seq markdown--first-displayable-cache t
)))
3392 (let ((seq (if (listp seq
) seq
(list seq
))))
3393 (cond ((stringp (car seq
))
3396 (and (mapcar #'char-displayable-p
(string-to-list str
))))
3398 ((characterp (car seq
))
3399 (cl-find-if #'char-displayable-p seq
))))
3400 markdown--first-displayable-cache
))))
3402 (defun markdown--marginalize-string (level)
3403 "Generate atx markup string of given LEVEL for left margin."
3404 (let ((margin-left-space-count
3405 (- markdown-marginalize-headers-margin-width level
)))
3406 (concat (make-string margin-left-space-count ?
)
3407 (make-string level ?
#))))
3409 (defun markdown-marginalize-update-current ()
3410 "Update the window configuration to create a left margin."
3412 (let* ((header-delimiter-font-width
3413 (window-font-width nil
'markdown-header-delimiter-face
))
3414 (margin-pixel-width (* markdown-marginalize-headers-margin-width
3415 header-delimiter-font-width
))
3416 (margin-char-width (/ margin-pixel-width
(default-font-width))))
3417 (set-window-margins nil margin-char-width
))
3418 ;; As a fallback, simply set margin based on character count.
3419 (set-window-margins nil
(1+ markdown-marginalize-headers-margin-width
))))
3421 (defun markdown-fontify-headings (last)
3422 "Add text properties to headings from point to LAST."
3423 (when (markdown-match-propertized-text 'markdown-heading last
)
3424 (let* ((level (markdown-outline-level))
3426 (intern (format "markdown-header-face-%d" level
)))
3427 (heading-props `(face ,heading-face
))
3429 `(face markdown-header-delimiter-face
3431 (markdown-hide-markup
3433 (markdown-marginalize-headers
3434 `(display ((margin left-margin
)
3435 ,(markdown--marginalize-string level
)))))))
3437 `(face markdown-header-delimiter-face
3438 ,@(when markdown-hide-markup
`(display ""))))
3439 (rule-props `(face markdown-header-rule-face
3440 ,@(when markdown-hide-markup
`(display "")))))
3443 (progn (add-text-properties
3444 (match-beginning 1) (match-end 1) heading-props
)
3446 (add-text-properties
3447 (match-beginning 2) (match-end 2) rule-props
)
3448 (add-text-properties
3449 (match-beginning 3) (match-end 3) rule-props
)))
3451 (if markdown-fontify-whole-heading-line
3452 (let ((header-end (min (point-max) (1+ (match-end 0)))))
3453 (add-text-properties
3454 (match-beginning 0) header-end heading-props
))
3455 (add-text-properties
3456 (match-beginning 4) (match-end 4) left-markup-props
)
3457 (add-text-properties
3458 (match-beginning 5) (match-end 5) heading-props
)
3460 (add-text-properties
3461 (match-beginning 6) (match-end 6) right-markup-props
)))))
3464 (defun markdown-fontify-tables (last)
3465 (when (re-search-forward "|" last t
)
3466 (when (markdown-table-at-point-p)
3467 (font-lock-append-text-property
3468 (line-beginning-position) (min (1+ (line-end-position)) (point-max))
3469 'face
'markdown-table-face
))
3473 (defun markdown-fontify-blockquotes (last)
3474 "Apply font-lock properties to blockquotes from point to LAST."
3475 (when (markdown-match-blockquotes last
)
3476 (let ((display-string
3477 (markdown--first-displayable markdown-blockquote-display-char
)))
3478 (add-text-properties
3479 (match-beginning 1) (match-end 1)
3480 (if markdown-hide-markup
3481 `(face markdown-blockquote-face display
,display-string
)
3482 `(face markdown-markup-face
)))
3483 (font-lock-append-text-property
3484 (match-beginning 0) (match-end 0) 'face
'markdown-blockquote-face
)
3487 (defun markdown-fontify-list-items (last)
3488 "Apply font-lock properties to list markers from point to LAST."
3489 (when (markdown-match-list-items last
)
3490 (when (not (markdown-code-block-at-point-p (match-beginning 2)))
3491 (let* ((indent (length (match-string-no-properties 1)))
3492 (level (/ indent markdown-list-indent-width
)) ;; level = 0, 1, 2, ...
3493 (bullet (nth (mod level
(length markdown-list-item-bullets
))
3494 markdown-list-item-bullets
)))
3495 (add-text-properties
3496 (match-beginning 2) (match-end 2) '(face markdown-list-face
))
3497 (when markdown-hide-markup
3500 ((string-match-p "[\\*\\+-]" (match-string 2))
3501 (add-text-properties
3502 (match-beginning 2) (match-end 2) `(display ,bullet
)))
3504 ((string-equal ":" (match-string 2))
3505 (let ((display-string
3506 (char-to-string (markdown--first-displayable
3507 markdown-definition-display-char
))))
3508 (add-text-properties (match-beginning 2) (match-end 2)
3509 `(display ,display-string
))))))))
3512 (defun markdown--fontify-hrs-view-mode (hr-char)
3513 (if (and hr-char
(display-supports-face-attributes-p '(:extend t
)))
3514 (add-text-properties
3515 (match-beginning 0) (match-end 0)
3517 (:inherit markdown-hr-face
:underline t
:extend t
)
3518 font-lock-multiline t
3520 (let ((hr-len (and hr-char
(/ (1- (window-body-width)) (char-width hr-char
)))))
3521 (add-text-properties
3522 (match-beginning 0) (match-end 0)
3524 markdown-hr-face font-lock-multiline t
3525 display
,(make-string hr-len hr-char
))))))
3527 (defun markdown-fontify-hrs (last)
3528 "Add text properties to horizontal rules from point to LAST."
3529 (when (markdown-match-hr last
)
3530 (let ((hr-char (markdown--first-displayable markdown-hr-display-char
)))
3531 (if (and markdown-hide-markup hr-char
)
3532 (markdown--fontify-hrs-view-mode hr-char
)
3533 (add-text-properties
3534 (match-beginning 0) (match-end 0)
3535 `(face markdown-hr-face font-lock-multiline t
)))
3538 (defun markdown-fontify-sub-superscripts (last)
3539 "Apply text properties to sub- and superscripts from point to LAST."
3540 (when (markdown-search-until-condition
3541 (lambda () (and (not (markdown-code-block-at-point-p))
3542 (not (markdown-inline-code-at-point-p))
3543 (not (markdown-in-comment-p))))
3544 markdown-regex-sub-superscript last t
)
3545 (let* ((subscript-p (string= (match-string 2) "~"))
3548 (car markdown-sub-superscript-display
)
3549 (cdr markdown-sub-superscript-display
)))
3550 (mp (list 'face
'markdown-markup-face
3551 'invisible
'markdown-markup
)))
3552 (when markdown-hide-markup
3553 (put-text-property (match-beginning 3) (match-end 3)
3555 (add-text-properties (match-beginning 2) (match-end 2) mp
)
3556 (add-text-properties (match-beginning 4) (match-end 4) mp
)
3560 ;;; Syntax Table ==============================================================
3562 (defvar markdown-mode-syntax-table
3563 (let ((tab (make-syntax-table text-mode-syntax-table
)))
3564 (modify-syntax-entry ?
\" "." tab
)
3566 "Syntax table for `markdown-mode'.")
3569 ;;; Element Insertion =========================================================
3571 (defun markdown-ensure-blank-line-before ()
3572 "If previous line is not already blank, insert a blank line before point."
3573 (unless (bolp) (insert "\n"))
3574 (unless (or (bobp) (looking-back "\n\\s-*\n" nil
)) (insert "\n")))
3576 (defun markdown-ensure-blank-line-after ()
3577 "If following line is not already blank, insert a blank line after point.
3578 Return the point where it was originally."
3580 (unless (eolp) (insert "\n"))
3581 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
3583 (defun markdown-wrap-or-insert (s1 s2
&optional thing beg end
)
3584 "Insert the strings S1 and S2, wrapping around region or THING.
3585 If a region is specified by the optional BEG and END arguments,
3586 wrap the strings S1 and S2 around that region.
3587 If there is an active region, wrap the strings S1 and S2 around
3588 the region. If there is not an active region but the point is at
3589 THING, wrap that thing (which defaults to word). Otherwise, just
3590 insert S1 and S2 and place the point in between. Return the
3591 bounds of the entire wrapped string, or nil if nothing was wrapped
3592 and S1 and S2 were only inserted."
3593 (let (a b bounds new-point
)
3599 new-point
(+ (point) (length s1
))))
3602 (setq a
(region-beginning)
3604 new-point
(+ (point) (length s1
))))
3605 ;; Thing (word) at point
3606 ((setq bounds
(markdown-bounds-of-thing-at-point (or thing
'word
)))
3607 (setq a
(car bounds
)
3609 new-point
(+ (point) (length s1
))))
3610 ;; No active region and no word
3618 (when new-point
(goto-char new-point
))
3621 (setq b
(+ b
(length s1
) (length s2
)))
3624 (defun markdown-point-after-unwrap (cur prefix suffix
)
3625 "Return desired position of point after an unwrapping operation.
3626 CUR gives the position of the point before the operation.
3627 Additionally, two cons cells must be provided. PREFIX gives the
3628 bounds of the prefix string and SUFFIX gives the bounds of the
3630 (cond ((< cur
(cdr prefix
)) (car prefix
))
3631 ((< cur
(car suffix
)) (- cur
(- (cdr prefix
) (car prefix
))))
3632 ((<= cur
(cdr suffix
))
3633 (- cur
(+ (- (cdr prefix
) (car prefix
))
3634 (- cur
(car suffix
)))))
3637 (defun markdown-unwrap-thing-at-point (regexp all text
)
3638 "Remove prefix and suffix of thing at point and reposition the point.
3639 When the thing at point matches REGEXP, replace the subexpression
3640 ALL with the string in subexpression TEXT. Reposition the point
3641 in an appropriate location accounting for the removal of prefix
3642 and suffix strings. Return new bounds of string from group TEXT.
3643 When REGEXP is nil, assumes match data is already set."
3644 (when (or (null regexp
)
3645 (thing-at-point-looking-at regexp
))
3647 (prefix (cons (match-beginning all
) (match-beginning text
)))
3648 (suffix (cons (match-end text
) (match-end all
)))
3649 (bounds (cons (match-beginning text
) (match-end text
))))
3650 ;; Replace the thing at point
3651 (replace-match (match-string text
) t t nil all
)
3652 ;; Reposition the point
3653 (goto-char (markdown-point-after-unwrap cur prefix suffix
))
3655 (setq bounds
(cons (car prefix
)
3656 (- (cdr bounds
) (- (cdr prefix
) (car prefix
))))))))
3658 (defun markdown-unwrap-things-in-region (beg end regexp all text
)
3659 "Remove prefix and suffix of all things in region from BEG to END.
3660 When a thing in the region matches REGEXP, replace the
3661 subexpression ALL with the string in subexpression TEXT.
3662 Return a cons cell containing updated bounds for the region."
3665 (let ((removed 0) len-all len-text
)
3666 (while (re-search-forward regexp
(- end removed
) t
)
3667 (setq len-all
(length (match-string-no-properties all
)))
3668 (setq len-text
(length (match-string-no-properties text
)))
3669 (setq removed
(+ removed
(- len-all len-text
)))
3670 (replace-match (match-string text
) t t nil all
))
3671 (cons beg
(- end removed
)))))
3673 (defun markdown-insert-hr (arg)
3674 "Insert or replace a horizontal rule.
3675 By default, use the first element of `markdown-hr-strings'. When
3676 ARG is non-nil, as when given a prefix, select a different
3677 element as follows. When prefixed with \\[universal-argument],
3678 use the last element of `markdown-hr-strings' instead. When
3679 prefixed with an integer from 1 to the length of
3680 `markdown-hr-strings', use the element in that position instead."
3682 (when (thing-at-point-looking-at markdown-regex-hr
)
3683 (delete-region (match-beginning 0) (match-end 0)))
3684 (markdown-ensure-blank-line-before)
3685 (cond ((equal arg
'(4))
3686 (insert (car (reverse markdown-hr-strings
))))
3687 ((and (integerp arg
) (> arg
0)
3688 (<= arg
(length markdown-hr-strings
)))
3689 (insert (nth (1- arg
) markdown-hr-strings
)))
3691 (insert (car markdown-hr-strings
))))
3692 (markdown-ensure-blank-line-after))
3694 (defun markdown--insert-common (start-delim end-delim regex start-group end-group face
3695 &optional skip-space
)
3698 (let* ((bounds (markdown-unwrap-things-in-region
3699 (region-beginning) (region-end)
3700 regex start-group end-group
))
3703 (when (and beg skip-space
)
3706 (skip-chars-forward "[ \t]")
3707 (setq beg
(point))))
3708 (when (and end skip-space
)
3711 (skip-chars-backward "[ \t]")
3712 (setq end
(point))))
3713 (markdown-wrap-or-insert start-delim end-delim nil beg end
))
3714 (if (markdown--face-p (point) (list face
))
3716 (while (and (markdown--face-p (point) (list face
)) (not (bobp)))
3718 (forward-char (- (1- (length start-delim
)))) ;; for delimiter
3721 (when (looking-at regex
)
3722 (markdown-unwrap-thing-at-point nil start-group end-group
)))
3723 (if (thing-at-point-looking-at regex
)
3724 (markdown-unwrap-thing-at-point nil start-group end-group
)
3725 (markdown-wrap-or-insert start-delim end-delim
'word nil nil
)))))
3727 (defun markdown-insert-bold ()
3728 "Insert markup to make a region or word bold.
3729 If there is an active region, make the region bold. If the point
3730 is at a non-bold word, make the word bold. If the point is at a
3731 bold word or phrase, remove the bold markup. Otherwise, simply
3732 insert bold delimiters and place the point in between them."
3734 (let ((delim (if markdown-bold-underscore
"__" "**")))
3735 (markdown--insert-common delim delim markdown-regex-bold
2 4 'markdown-bold-face t
)))
3737 (defun markdown-insert-italic ()
3738 "Insert markup to make a region or word italic.
3739 If there is an active region, make the region italic. If the point
3740 is at a non-italic word, make the word italic. If the point is at an
3741 italic word or phrase, remove the italic markup. Otherwise, simply
3742 insert italic delimiters and place the point in between them."
3744 (let ((delim (if markdown-italic-underscore
"_" "*")))
3745 (markdown--insert-common delim delim markdown-regex-italic
1 3 'markdown-italic-face t
)))
3747 (defun markdown-insert-strike-through ()
3748 "Insert markup to make a region or word strikethrough.
3749 If there is an active region, make the region strikethrough. If the point
3750 is at a non-bold word, make the word strikethrough. If the point is at a
3751 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
3752 simply insert bold delimiters and place the point in between them."
3754 (markdown--insert-common
3755 "~~" "~~" markdown-regex-strike-through
2 4 'markdown-strike-through-face t
))
3757 (defun markdown-insert-code ()
3758 "Insert markup to make a region or word an inline code fragment.
3759 If there is an active region, make the region an inline code
3760 fragment. If the point is at a word, make the word an inline
3761 code fragment. Otherwise, simply insert code delimiters and
3762 place the point in between them."
3766 (let ((bounds (markdown-unwrap-things-in-region
3767 (region-beginning) (region-end)
3768 markdown-regex-code
1 3)))
3769 (markdown-wrap-or-insert "`" "`" nil
(car bounds
) (cdr bounds
)))
3770 ;; Code markup removal, code markup for word, or empty markup insertion
3771 (if (markdown-inline-code-at-point)
3772 (markdown-unwrap-thing-at-point nil
0 2)
3773 (markdown-wrap-or-insert "`" "`" 'word nil nil
))))
3775 (defun markdown-insert-kbd ()
3776 "Insert markup to wrap region or word in <kbd> tags.
3777 If there is an active region, use the region. If the point is at
3778 a word, use the word. Otherwise, simply insert <kbd> tags and
3779 place the point in between them."
3783 (let ((bounds (markdown-unwrap-things-in-region
3784 (region-beginning) (region-end)
3785 markdown-regex-kbd
0 2)))
3786 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil
(car bounds
) (cdr bounds
)))
3787 ;; Markup removal, markup for word, or empty markup insertion
3788 (if (thing-at-point-looking-at markdown-regex-kbd
)
3789 (markdown-unwrap-thing-at-point nil
0 2)
3790 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil
))))
3792 (defun markdown-insert-inline-link (text url
&optional title
)
3793 "Insert an inline link with TEXT pointing to URL.
3794 Optionally, the user can provide a TITLE."
3795 (let ((cur (point)))
3796 (setq title
(and title
(concat " \"" title
"\"")))
3797 (insert (concat "[" text
"](" url title
")"))
3798 (cond ((not text
) (goto-char (+ 1 cur
)))
3799 ((not url
) (goto-char (+ 3 (length text
) cur
))))))
3801 (defun markdown-insert-inline-image (text url
&optional title
)
3802 "Insert an inline link with alt TEXT pointing to URL.
3803 Optionally, also provide a TITLE."
3804 (let ((cur (point)))
3805 (setq title
(and title
(concat " \"" title
"\"")))
3806 (insert (concat "![" text
"](" url title
")"))
3807 (cond ((not text
) (goto-char (+ 2 cur
)))
3808 ((not url
) (goto-char (+ 4 (length text
) cur
))))))
3810 (defun markdown-insert-reference-link (text label
&optional url title
)
3811 "Insert a reference link and, optionally, a reference definition.
3812 The link TEXT will be inserted followed by the optional LABEL.
3813 If a URL is given, also insert a definition for the reference
3814 LABEL according to `markdown-reference-location'. If a TITLE is
3815 given, it will be added to the end of the reference definition
3816 and will be used to populate the title attribute when converted
3817 to XHTML. If URL is nil, insert only the link portion (for
3818 example, when a reference label is already defined)."
3819 (insert (concat "[" text
"][" label
"]"))
3821 (markdown-insert-reference-definition
3822 (if (string-equal label
"") text label
)
3825 (defun markdown-insert-reference-image (text label
&optional url title
)
3826 "Insert a reference image and, optionally, a reference definition.
3827 The alt TEXT will be inserted followed by the optional LABEL.
3828 If a URL is given, also insert a definition for the reference
3829 LABEL according to `markdown-reference-location'. If a TITLE is
3830 given, it will be added to the end of the reference definition
3831 and will be used to populate the title attribute when converted
3832 to XHTML. If URL is nil, insert only the link portion (for
3833 example, when a reference label is already defined)."
3834 (insert (concat "![" text
"][" label
"]"))
3836 (markdown-insert-reference-definition
3837 (if (string-equal label
"") text label
)
3840 (defun markdown-insert-reference-definition (label &optional url title
)
3841 "Add definition for reference LABEL with URL and TITLE.
3842 LABEL is a Markdown reference label without square brackets.
3843 URL and TITLE are optional. When given, the TITLE will
3844 be used to populate the title attribute when converted to XHTML."
3845 ;; END specifies where to leave the point upon return
3846 (let ((end (point)))
3847 (cl-case markdown-reference-location
3848 (end (goto-char (point-max)))
3849 (immediately (markdown-end-of-text-block))
3850 (subtree (markdown-end-of-subtree))
3851 (header (markdown-end-of-defun)))
3852 ;; Skip backwards over local variables. This logic is similar to the one
3853 ;; used in ‘hack-local-variables’.
3854 (when (and enable-local-variables
(eobp))
3855 (search-backward "\n\f" (max (- (point) 3000) (point-min)) :move
)
3856 (when (let ((case-fold-search t
))
3857 (search-forward "Local Variables:" nil
:move
))
3858 (beginning-of-line 0)
3859 (when (eq (char-before) ?
\n) (backward-char))))
3860 (unless (or (markdown-cur-line-blank-p)
3861 (thing-at-point-looking-at markdown-regex-reference-definition
))
3863 (insert "\n[" label
"]: ")
3866 ;; When no URL is given, leave point at END following the colon
3868 (when (> (length title
) 0)
3869 (insert " \"" title
"\""))
3870 (unless (looking-at-p "\n")
3875 (markdown--substitute-command-keys
3876 "Reference [%s] was defined, press \\[markdown-do] to jump there")
3879 (defcustom markdown-link-make-text-function nil
3880 "Function that automatically generates a link text for a URL.
3882 If non-nil, this function will be called by
3883 `markdown--insert-link-or-image' and the result will be the
3884 default link text. The function should receive exactly one
3885 argument that corresponds to the link URL."
3888 :package-version
'(markdown-mode .
"2.5"))
3890 (defcustom markdown-disable-tooltip-prompt nil
3891 "Disable prompt for tooltip when inserting a link or image.
3893 If non-nil, `markdown-insert-link' and `markdown-insert-link'
3894 will not prompt the user to insert a tooltip text for the given
3899 :package-version
'(markdown-mode .
"2.5"))
3901 (defun markdown--insert-link-or-image (image)
3902 "Interactively insert new or update an existing link or image.
3903 When IMAGE is non-nil, insert an image. Otherwise, insert a link.
3904 This is an internal function called by
3905 `markdown-insert-link' and `markdown-insert-image'."
3906 (cl-multiple-value-bind (begin end text uri ref title
)
3908 ;; Use region as either link text or URL as appropriate.
3909 (let ((region (buffer-substring-no-properties
3910 (region-beginning) (region-end))))
3911 (if (string-match markdown-regex-uri region
)
3912 ;; Region contains a URL; use it as such.
3913 (list (region-beginning) (region-end)
3914 nil
(match-string 0 region
) nil nil
)
3915 ;; Region doesn't contain a URL, so use it as text.
3916 (list (region-beginning) (region-end)
3917 region nil nil nil
)))
3918 ;; Extract and use properties of existing link, if any.
3919 (markdown-link-at-pos (point)))
3920 (let* ((ref (when ref
(concat "[" ref
"]")))
3921 (defined-refs (mapcar #'car
(markdown-get-defined-references)))
3922 (defined-ref-cands (mapcar (lambda (ref) (concat "[" ref
"]")) defined-refs
))
3923 (used-uris (markdown-get-used-uris))
3924 (uri-or-ref (completing-read
3925 "URL or [reference]: "
3926 (append defined-ref-cands used-uris
)
3927 nil nil
(or uri ref
)))
3928 (ref (cond ((string-match "\\`\\[\\(.*\\)\\]\\'" uri-or-ref
)
3929 (match-string 1 uri-or-ref
))
3930 ((string-equal "" uri-or-ref
)
3932 (uri (unless ref uri-or-ref
))
3933 (text-prompt (if image
3937 "Link text (blank for plain URL): ")))
3938 (text (or text
(and markdown-link-make-text-function uri
3939 (funcall markdown-link-make-text-function uri
))))
3940 (text (completing-read text-prompt defined-refs nil nil text
))
3941 (text (if (= (length text
) 0) nil text
))
3942 (plainp (and uri
(not text
)))
3943 (implicitp (string-equal ref
""))
3944 (ref (if implicitp text ref
))
3945 (definedp (and ref
(markdown-reference-definition ref
)))
3946 (ref-url (unless (or uri definedp
)
3947 (completing-read "Reference URL: " used-uris
)))
3948 (title (unless (or plainp definedp markdown-disable-tooltip-prompt
)
3949 (read-string "Title (tooltip text, optional): " title
)))
3950 (title (if (= (length title
) 0) nil title
)))
3951 (when (and image implicitp
)
3952 (user-error "Reference required: implicit image references are invalid"))
3953 (when (and begin end
)
3954 (delete-region begin end
))
3956 ((and (not image
) uri text
)
3957 (markdown-insert-inline-link text uri title
))
3958 ((and image uri text
)
3959 (markdown-insert-inline-image text uri title
))
3962 (markdown-insert-reference-image text
(unless implicitp ref
) nil title
)
3963 (markdown-insert-reference-link text
(unless implicitp ref
) nil title
))
3965 (markdown-insert-reference-definition ref ref-url title
)))
3966 ((and (not image
) uri
)
3967 (markdown-insert-uri uri
))))))
3969 (defun markdown-insert-link ()
3970 "Insert new or update an existing link, with interactive prompt.
3971 If the point is at an existing link or URL, update the link text,
3972 URL, reference label, and/or title. Otherwise, insert a new link.
3973 The type of link inserted (inline, reference, or plain URL)
3974 depends on which values are provided:
3976 * If a URL and TEXT are given, insert an inline link: [TEXT](URL).
3977 * If [REF] and TEXT are given, insert a reference link: [TEXT][REF].
3978 * If only TEXT is given, insert an implicit reference link: [TEXT][].
3979 * If only a URL is given, insert a plain link: <URL>.
3981 In other words, to create an implicit reference link, leave the
3982 URL prompt empty and to create a plain URL link, leave the link
3985 If there is an active region, use the text as the default URL, if
3986 it seems to be a URL, or link text value otherwise.
3988 If a given reference is not defined, this function will
3989 additionally prompt for the URL and optional title. In this case,
3990 the reference definition is placed at the location determined by
3991 `markdown-reference-location'. In addition, it is possible to
3992 have the `markdown-link-make-text-function' function, if non-nil,
3993 define the default link text before prompting the user for it.
3995 If `markdown-disable-tooltip-prompt' is non-nil, the user will
3996 not be prompted to add or modify a tooltip text.
3998 Through updating the link, this function can be used to convert a
3999 link of one type (inline, reference, or plain) to another type by
4000 selectively adding or removing information via the prompts."
4002 (markdown--insert-link-or-image nil
))
4004 (defun markdown-insert-image ()
4005 "Insert new or update an existing image, with interactive prompt.
4006 If the point is at an existing image, update the alt text, URL,
4007 reference label, and/or title. Otherwise, insert a new image.
4008 The type of image inserted (inline or reference) depends on which
4009 values are provided:
4011 * If a URL and ALT-TEXT are given, insert an inline image:
4013 * If [REF] and ALT-TEXT are given, insert a reference image:
4016 If there is an active region, use the text as the default URL, if
4017 it seems to be a URL, or alt text value otherwise.
4019 If a given reference is not defined, this function will
4020 additionally prompt for the URL and optional title. In this case,
4021 the reference definition is placed at the location determined by
4022 `markdown-reference-location'.
4024 Through updating the image, this function can be used to convert an
4025 image of one type (inline or reference) to another type by
4026 selectively adding or removing information via the prompts."
4028 (markdown--insert-link-or-image t
))
4030 (defun markdown-insert-uri (&optional uri
)
4031 "Insert markup for an inline URI.
4032 If there is an active region, use it as the URI. If the point is
4033 at a URI, wrap it with angle brackets. If the point is at an
4034 inline URI, remove the angle brackets. Otherwise, simply insert
4035 angle brackets place the point between them."
4039 (let ((bounds (markdown-unwrap-things-in-region
4040 (region-beginning) (region-end)
4041 markdown-regex-angle-uri
0 2)))
4042 (markdown-wrap-or-insert "<" ">" nil
(car bounds
) (cdr bounds
)))
4043 ;; Markup removal, URI at point, new URI, or empty markup insertion
4044 (if (thing-at-point-looking-at markdown-regex-angle-uri
)
4045 (markdown-unwrap-thing-at-point nil
0 2)
4047 (insert "<" uri
">")
4048 (markdown-wrap-or-insert "<" ">" 'url nil nil
)))))
4050 (defun markdown-insert-wiki-link ()
4051 "Insert a wiki link of the form [[WikiLink]].
4052 If there is an active region, use the region as the link text.
4053 If the point is at a word, use the word as the link text. If
4054 there is no active region and the point is not at word, simply
4055 insert link markup."
4059 (markdown-wrap-or-insert "[[" "]]" nil
(region-beginning) (region-end))
4060 ;; Markup removal, wiki link at at point, or empty markup insertion
4061 (if (thing-at-point-looking-at markdown-regex-wiki-link
)
4062 (if (or markdown-wiki-link-alias-first
4063 (null (match-string 5)))
4064 (markdown-unwrap-thing-at-point nil
1 3)
4065 (markdown-unwrap-thing-at-point nil
1 5))
4066 (markdown-wrap-or-insert "[[" "]]"))))
4068 (defun markdown-remove-header ()
4069 "Remove header markup if point is at a header.
4070 Return bounds of remaining header text if a header was removed
4073 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx
0 2)
4074 (markdown-unwrap-thing-at-point markdown-regex-header-setext
0 1)))
4076 (defun markdown-insert-header (&optional level text setext
)
4077 "Insert or replace header markup.
4078 The level of the header is specified by LEVEL and header text is
4079 given by TEXT. LEVEL must be an integer from 1 and 6, and the
4081 When TEXT is nil, the header text is obtained as follows.
4082 If there is an active region, it is used as the header text.
4083 Otherwise, the current line will be used as the header text.
4084 If there is not an active region and the point is at a header,
4085 remove the header markup and replace with level N header.
4086 Otherwise, insert empty header markup and place the point in
4088 The style of the header will be atx (hash marks) unless
4089 SETEXT is non-nil, in which case a setext-style (underlined)
4090 header will be inserted."
4091 (interactive "p\nsHeader text: ")
4092 (setq level
(min (max (or level
1) 1) (if setext
2 6)))
4093 ;; Determine header text if not given
4097 (setq text
(delete-and-extract-region (region-beginning) (region-end)))
4099 (markdown-remove-header)
4100 (setq text
(delete-and-extract-region
4101 (line-beginning-position) (line-end-position)))
4102 (when (and setext
(string-match-p "^[ \t]*$" text
))
4103 (setq text
(read-string "Header text: "))))
4104 (setq text
(markdown-compress-whitespace-string text
)))
4105 ;; Insertion with given text
4106 (markdown-ensure-blank-line-before)
4109 (setq hdr
(make-string (string-width text
) (if (= level
2) ?- ?
=)))
4110 (insert text
"\n" hdr
))
4112 (setq hdr
(make-string level ?
#))
4113 (insert hdr
" " text
)
4114 (when (null markdown-asymmetric-header
) (insert " " hdr
)))))
4115 (markdown-ensure-blank-line-after)
4116 ;; Leave point at end of text
4118 (backward-char (1+ (string-width text
))))
4119 ((null markdown-asymmetric-header
)
4120 (backward-char (1+ level
)))))
4122 (defun markdown-insert-header-dwim (&optional arg setext
)
4123 "Insert or replace header markup.
4124 The level and type of the header are determined automatically by
4125 the type and level of the previous header, unless a prefix
4126 argument is given via ARG.
4127 With a numeric prefix valued 1 to 6, insert a header of the given
4128 level, with the type being determined automatically (note that
4129 only level 1 or 2 setext headers are possible).
4131 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
4132 promote the heading by one level.
4133 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
4134 demote the heading by one level.
4135 When SETEXT is non-nil, prefer setext-style headers when
4136 possible (levels one and two).
4138 When there is an active region, use it for the header text. When
4139 the point is at an existing header, change the type and level
4140 according to the rules above.
4141 Otherwise, if the line is not empty, create a header using the
4142 text on the current line as the header text.
4143 Finally, if the point is on a blank line, insert empty header
4144 markup (atx) or prompt for text (setext).
4145 See `markdown-insert-header' for more details about how the
4146 header text is determined."
4150 (when (or (thing-at-point-looking-at markdown-regex-header
)
4151 (re-search-backward markdown-regex-header nil t
))
4152 ;; level of current or previous header
4153 (setq level
(markdown-outline-level))
4154 ;; match group 1 indicates a setext header
4155 (setq setext
(match-end 1))))
4156 ;; check prefix argument
4158 ((and (equal arg
'(4)) level
(> level
1)) ;; C-u
4160 ((and (equal arg
'(16)) level
(< level
6)) ;; C-u C-u
4162 (arg ;; numeric prefix
4163 (setq level
(prefix-numeric-value arg
))))
4164 ;; setext headers must be level one or two
4165 (and level
(setq setext
(and setext
(<= level
2))))
4166 ;; insert the heading
4167 (markdown-insert-header level nil setext
)))
4169 (defun markdown-insert-header-setext-dwim (&optional arg
)
4170 "Insert or replace header markup, with preference for setext.
4171 See `markdown-insert-header-dwim' for details, including how ARG is handled."
4173 (markdown-insert-header-dwim arg t
))
4175 (defun markdown-insert-header-atx-1 ()
4176 "Insert a first level atx-style (hash mark) header.
4177 See `markdown-insert-header'."
4179 (markdown-insert-header 1 nil nil
))
4181 (defun markdown-insert-header-atx-2 ()
4182 "Insert a level two atx-style (hash mark) header.
4183 See `markdown-insert-header'."
4185 (markdown-insert-header 2 nil nil
))
4187 (defun markdown-insert-header-atx-3 ()
4188 "Insert a level three atx-style (hash mark) header.
4189 See `markdown-insert-header'."
4191 (markdown-insert-header 3 nil nil
))
4193 (defun markdown-insert-header-atx-4 ()
4194 "Insert a level four atx-style (hash mark) header.
4195 See `markdown-insert-header'."
4197 (markdown-insert-header 4 nil nil
))
4199 (defun markdown-insert-header-atx-5 ()
4200 "Insert a level five atx-style (hash mark) header.
4201 See `markdown-insert-header'."
4203 (markdown-insert-header 5 nil nil
))
4205 (defun markdown-insert-header-atx-6 ()
4206 "Insert a sixth level atx-style (hash mark) header.
4207 See `markdown-insert-header'."
4209 (markdown-insert-header 6 nil nil
))
4211 (defun markdown-insert-header-setext-1 ()
4212 "Insert a setext-style (underlined) first-level header.
4213 See `markdown-insert-header'."
4215 (markdown-insert-header 1 nil t
))
4217 (defun markdown-insert-header-setext-2 ()
4218 "Insert a setext-style (underlined) second-level header.
4219 See `markdown-insert-header'."
4221 (markdown-insert-header 2 nil t
))
4223 (defun markdown-blockquote-indentation (loc)
4224 "Return string containing necessary indentation for a blockquote at LOC.
4225 Also see `markdown-pre-indentation'."
4228 (let* ((list-level (length (markdown-calculate-list-levels)))
4230 (dotimes (_ list-level indent
)
4231 (setq indent
(concat indent
" "))))))
4233 (defun markdown-insert-blockquote ()
4234 "Start a blockquote section (or blockquote the region).
4235 If Transient Mark mode is on and a region is active, it is used as
4236 the blockquote text."
4239 (markdown-blockquote-region (region-beginning) (region-end))
4240 (markdown-ensure-blank-line-before)
4241 (insert (markdown-blockquote-indentation (point)) "> ")
4242 (markdown-ensure-blank-line-after)))
4244 (defun markdown-block-region (beg end prefix
)
4245 "Format the region using a block prefix.
4246 Arguments BEG and END specify the beginning and end of the
4247 region. The characters PREFIX will appear at the beginning
4250 (let* ((end-marker (make-marker))
4251 (beg-marker (make-marker))
4252 (prefix-without-trailing-whitespace
4253 (replace-regexp-in-string (rx (+ blank
) eos
) "" prefix
)))
4254 ;; Ensure blank line after and remove extra whitespace
4256 (skip-syntax-backward "-")
4257 (set-marker end-marker
(point))
4258 (delete-horizontal-space)
4259 (markdown-ensure-blank-line-after)
4260 ;; Ensure blank line before and remove extra whitespace
4262 (skip-syntax-forward "-")
4263 (delete-horizontal-space)
4264 (markdown-ensure-blank-line-before)
4265 (set-marker beg-marker
(point))
4266 ;; Insert PREFIX before each line
4267 (goto-char beg-marker
)
4268 (while (and (< (line-beginning-position) end-marker
)
4270 ;; Don’t insert trailing whitespace.
4271 (insert (if (eolp) prefix-without-trailing-whitespace prefix
))
4274 (defun markdown-blockquote-region (beg end
)
4275 "Blockquote the region.
4276 Arguments BEG and END specify the beginning and end of the region."
4278 (markdown-block-region
4279 beg end
(concat (markdown-blockquote-indentation
4280 (max (point-min) (1- beg
))) "> ")))
4282 (defun markdown-pre-indentation (loc)
4283 "Return string containing necessary whitespace for a pre block at LOC.
4284 Also see `markdown-blockquote-indentation'."
4287 (let* ((list-level (length (markdown-calculate-list-levels)))
4289 (dotimes (_ (1+ list-level
) indent
)
4290 (setq indent
(concat indent
" "))))))
4292 (defun markdown-insert-pre ()
4293 "Start a preformatted section (or apply to the region).
4294 If Transient Mark mode is on and a region is active, it is marked
4295 as preformatted text."
4298 (markdown-pre-region (region-beginning) (region-end))
4299 (markdown-ensure-blank-line-before)
4300 (insert (markdown-pre-indentation (point)))
4301 (markdown-ensure-blank-line-after)))
4303 (defun markdown-pre-region (beg end
)
4304 "Format the region as preformatted text.
4305 Arguments BEG and END specify the beginning and end of the region."
4307 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg
)))))
4308 (markdown-block-region beg end indent
)))
4310 (defun markdown-electric-backquote (arg)
4311 "Insert a backquote.
4312 The numeric prefix argument ARG says how many times to repeat the insertion.
4313 Call `markdown-insert-gfm-code-block' interactively
4314 if three backquotes inserted at the beginning of line."
4316 (self-insert-command (prefix-numeric-value arg
))
4317 (when (and markdown-gfm-use-electric-backquote
(looking-back "^```" nil
))
4319 (call-interactively #'markdown-insert-gfm-code-block
)))
4321 (defconst markdown-gfm-recognized-languages
4322 ;; To reproduce/update, evaluate the let-form in
4323 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
4324 ;; but with appropriate use of a keyboard macro, indenting and filling it
4325 ;; properly is pretty fast.
4326 '("1C-Enterprise" "4D" "ABAP" "ABNF" "AGS-Script" "AMPL" "ANTLR"
4327 "API-Blueprint" "APL" "ASN.1" "ASP" "ATS" "ActionScript" "Ada"
4328 "Adobe-Font-Metrics" "Agda" "Alloy" "Alpine-Abuild" "Altium-Designer"
4329 "AngelScript" "Ant-Build-System" "ApacheConf" "Apex"
4330 "Apollo-Guidance-Computer" "AppleScript" "Arc" "AsciiDoc" "AspectJ" "Assembly"
4331 "Asymptote" "Augeas" "AutoHotkey" "AutoIt" "Awk" "Ballerina" "Batchfile"
4332 "Befunge" "BibTeX" "Bison" "BitBake" "Blade" "BlitzBasic" "BlitzMax"
4333 "Bluespec" "Boo" "Brainfuck" "Brightscript" "C#" "C++" "C-ObjDump"
4334 "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "COLLADA" "CSON" "CSS" "CSV" "CWeb"
4335 "Cabal-Config" "Cap'n-Proto" "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK"
4336 "Cirru" "Clarion" "Clean" "Click" "Clojure" "Closure-Templates"
4337 "Cloud-Firestore-Security-Rules" "CoNLL-U" "CodeQL" "CoffeeScript"
4338 "ColdFusion" "ColdFusion-CFC" "Common-Lisp" "Common-Workflow-Language"
4339 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal" "Csound"
4340 "Csound-Document" "Csound-Score" "Cuda" "Cycript" "Cython" "D-ObjDump"
4341 "DIGITAL-Command-Language" "DM" "DNS-Zone" "DTrace" "Dafny" "Darcs-Patch"
4342 "Dart" "DataWeave" "Dhall" "Diff" "DirectX-3D-File" "Dockerfile" "Dogescript"
4343 "Dylan" "EBNF" "ECL" "ECLiPSe" "EJS" "EML" "EQ" "Eagle" "Easybuild"
4344 "Ecere-Projects" "EditorConfig" "Edje-Data-Collection" "Eiffel" "Elixir" "Elm"
4345 "Emacs-Lisp" "EmberScript" "Erlang" "F#" "F*" "FIGlet-Font" "FLUX" "Factor"
4346 "Fancy" "Fantom" "Faust" "Filebench-WML" "Filterscript" "Formatted" "Forth"
4347 "Fortran" "Fortran-Free-Form" "FreeMarker" "Frege" "G-code" "GAML" "GAMS"
4348 "GAP" "GCC-Machine-Description" "GDB" "GDScript" "GEDCOM" "GLSL" "GN"
4349 "Game-Maker-Language" "Genie" "Genshi" "Gentoo-Ebuild" "Gentoo-Eclass"
4350 "Gerber-Image" "Gettext-Catalog" "Gherkin" "Git-Attributes" "Git-Config"
4351 "Glyph" "Glyph-Bitmap-Distribution-Format" "Gnuplot" "Go" "Golo" "Gosu"
4352 "Grace" "Gradle" "Grammatical-Framework" "Graph-Modeling-Language" "GraphQL"
4353 "Graphviz-(DOT)" "Groovy" "Groovy-Server-Pages" "HAProxy" "HCL" "HLSL" "HTML"
4354 "HTML+Django" "HTML+ECR" "HTML+EEX" "HTML+ERB" "HTML+PHP" "HTML+Razor" "HTTP"
4355 "HXML" "Hack" "Haml" "Handlebars" "Harbour" "Haskell" "Haxe" "HiveQL" "HolyC"
4356 "Hy" "HyPhy" "IDL" "IGOR-Pro" "INI" "IRC-log" "Idris" "Ignore-List" "Inform-7"
4357 "Inno-Setup" "Io" "Ioke" "Isabelle" "Isabelle-ROOT" "JFlex" "JSON"
4358 "JSON-with-Comments" "JSON5" "JSONLD" "JSONiq" "JSX" "Jasmin" "Java"
4359 "Java-Properties" "Java-Server-Pages" "JavaScript" "JavaScript+ERB" "Jison"
4360 "Jison-Lex" "Jolie" "Jsonnet" "Julia" "Jupyter-Notebook" "KRL" "KiCad-Layout"
4361 "KiCad-Legacy-Layout" "KiCad-Schematic" "Kit" "Kotlin" "LFE" "LLVM" "LOLCODE"
4362 "LSL" "LTspice-Symbol" "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex"
4363 "LilyPond" "Limbo" "Linker-Script" "Linux-Kernel-Module" "Liquid"
4364 "Literate-Agda" "Literate-CoffeeScript" "Literate-Haskell" "LiveScript"
4365 "Logos" "Logtalk" "LookML" "LoomScript" "Lua" "M4" "M4Sugar" "MATLAB"
4366 "MAXScript" "MLIR" "MQL4" "MQL5" "MTML" "MUF" "Macaulay2" "Makefile" "Mako"
4367 "Markdown" "Marko" "Mask" "Mathematica" "Maven-POM" "Max" "MediaWiki"
4368 "Mercury" "Meson" "Metal" "Microsoft-Developer-Studio-Project" "MiniD" "Mirah"
4369 "Modelica" "Modula-2" "Modula-3" "Module-Management-System" "Monkey" "Moocode"
4370 "MoonScript" "Motorola-68K-Assembly" "Muse" "Myghty" "NASL" "NCL" "NEON" "NL"
4371 "NPM-Config" "NSIS" "Nearley" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo"
4372 "NewLisp" "Nextflow" "Nginx" "Nim" "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml"
4373 "ObjDump" "Object-Data-Instance-Notation" "ObjectScript" "Objective-C"
4374 "Objective-C++" "Objective-J" "Odin" "Omgrofl" "Opa" "Opal"
4375 "Open-Policy-Agent" "OpenCL" "OpenEdge-ABL" "OpenQASM" "OpenRC-runscript"
4376 "OpenSCAD" "OpenStep-Property-List" "OpenType-Feature-File" "Org" "Ox"
4377 "Oxygene" "Oz" "P4" "PHP" "PLSQL" "PLpgSQL" "POV-Ray-SDL" "Pan" "Papyrus"
4378 "Parrot" "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal" "Pawn"
4379 "Pep8" "Perl" "Pic" "Pickle" "PicoLisp" "PigLatin" "Pike" "PlantUML" "Pod"
4380 "Pod-6" "PogoScript" "Pony" "PostCSS" "PostScript" "PowerBuilder" "PowerShell"
4381 "Prisma" "Processing" "Proguard" "Prolog" "Propeller-Spin" "Protocol-Buffer"
4382 "Public-Key" "Pug" "Puppet" "Pure-Data" "PureBasic" "PureScript" "Python"
4383 "Python-console" "Python-traceback" "QML" "QMake" "Quake" "RAML" "RDoc"
4384 "REALbasic" "REXX" "RHTML" "RMarkdown" "RPC" "RPM-Spec" "RUNOFF" "Racket"
4385 "Ragel" "Raku" "Rascal" "Raw-token-data" "Readline-Config" "Reason" "Rebol"
4386 "Red" "Redcode" "Regular-Expression" "Ren'Py" "RenderScript"
4387 "Rich-Text-Format" "Ring" "Riot" "RobotFramework" "Roff" "Roff-Manpage"
4388 "Rouge" "Ruby" "Rust" "SAS" "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL"
4389 "SRecode-Template" "SSH-Config" "STON" "SVG" "SWIG" "Sage" "SaltStack" "Sass"
4390 "Scala" "Scaml" "Scheme" "Scilab" "Self" "ShaderLab" "Shell" "ShellSession"
4391 "Shen" "Slash" "Slice" "Slim" "SmPL" "Smali" "Smalltalk" "Smarty" "Solidity"
4392 "SourcePawn" "Spline-Font-Database" "Squirrel" "Stan" "Standard-ML" "Starlark"
4393 "Stata" "Stylus" "SubRip-Text" "SugarSS" "SuperCollider" "Svelte" "Swift"
4394 "SystemVerilog" "TI-Program" "TLA" "TOML" "TSQL" "TSX" "TXL" "Tcl" "Tcsh"
4395 "TeX" "Tea" "Terra" "Texinfo" "Text" "Textile" "Thrift" "Turing" "Turtle"
4396 "Twig" "Type-Language" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset"
4397 "Unix-Assembly" "Uno" "UnrealScript" "UrWeb" "VBA" "VBScript" "VCL" "VHDL"
4398 "Vala" "Verilog" "Vim-Snippet" "Vim-script" "Visual-Basic-.NET" "Volt" "Vue"
4399 "Wavefront-Material" "Wavefront-Object" "Web-Ontology-Language" "WebAssembly"
4400 "WebIDL" "WebVTT" "Wget-Config" "Windows-Registry-Entries" "Wollok"
4401 "World-of-Warcraft-Addon-Data" "X-BitMap" "X-Font-Directory-Index" "X-PixMap"
4402 "X10" "XC" "XCompose" "XML" "XML-Property-List" "XPages" "XProc" "XQuery" "XS"
4403 "XSLT" "Xojo" "Xtend" "YAML" "YANG" "YARA" "YASnippet" "Yacc" "ZAP" "ZIL"
4404 "Zeek" "ZenScript" "Zephir" "Zig" "Zimpl" "cURL-Config" "desktop" "dircolors"
4405 "eC" "edn" "fish" "mIRC-Script" "mcfunction" "mupad" "nanorc" "nesC" "ooc"
4406 "reStructuredText" "sed" "wdl" "wisp" "xBase")
4407 "Language specifiers recognized by GitHub's syntax highlighting features.")
4409 (defvar-local markdown-gfm-used-languages nil
4410 "Language names used in GFM code blocks.")
4412 (defun markdown-trim-whitespace (str)
4413 (replace-regexp-in-string
4414 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str
))
4416 (defun markdown-clean-language-string (str)
4417 (replace-regexp-in-string
4418 "{\\.?\\|}" "" (markdown-trim-whitespace str
)))
4420 (defun markdown-validate-language-string (widget)
4421 (let ((str (widget-value widget
)))
4422 (unless (string= str
(markdown-clean-language-string str
))
4423 (widget-put widget
:error
(format "Invalid language spec: '%s'" str
))
4426 (defun markdown-gfm-get-corpus ()
4427 "Create corpus of recognized GFM code block languages for the given buffer."
4428 (let ((given-corpus (append markdown-gfm-additional-languages
4429 markdown-gfm-recognized-languages
)))
4431 markdown-gfm-used-languages
4432 (if markdown-gfm-downcase-languages
(cl-mapcar #'downcase given-corpus
)
4435 (defun markdown-gfm-add-used-language (lang)
4436 "Clean LANG and add to list of used languages."
4437 (setq markdown-gfm-used-languages
4438 (cons lang
(remove lang markdown-gfm-used-languages
))))
4440 (defcustom markdown-spaces-after-code-fence
1
4441 "Number of space characters to insert after a code fence.
4442 \\<gfm-mode-map>\\[markdown-insert-gfm-code-block] inserts this many spaces between an
4443 opening code fence and an info string."
4447 :package-version
'(markdown-mode .
"2.3"))
4449 (defcustom markdown-code-block-braces nil
4450 "When non-nil, automatically insert braces for GFM code blocks."
4454 (defun markdown-insert-gfm-code-block (&optional lang edit
)
4455 "Insert GFM code block for language LANG.
4456 If LANG is nil, the language will be queried from user. If a
4457 region is active, wrap this region with the markup instead. If
4458 the region boundaries are not on empty lines, these are added
4459 automatically in order to have the correct markup. When EDIT is
4460 non-nil (e.g., when \\[universal-argument] is given), edit the
4461 code block in an indirect buffer after insertion."
4463 (list (let ((completion-ignore-case nil
))
4465 (markdown-clean-language-string
4467 "Programming language: "
4468 (markdown-gfm-get-corpus)
4469 nil
'confirm
(car markdown-gfm-used-languages
)
4470 'markdown-gfm-language-history
))
4472 current-prefix-arg
))
4473 (unless (string= lang
"") (markdown-gfm-add-used-language lang
))
4474 (when (and (> (length lang
) 0)
4475 (not markdown-code-block-braces
))
4476 (setq lang
(concat (make-string markdown-spaces-after-code-fence ?\s
)
4478 (let ((gfm-open-brace (if markdown-code-block-braces
"{" ""))
4479 (gfm-close-brace (if markdown-code-block-braces
"}" "")))
4481 (let* ((b (region-beginning)) (e (region-end)) end
4482 (indent (progn (goto-char b
) (current-indentation))))
4484 ;; if we're on a blank line, don't newline, otherwise the ```
4485 ;; should go on its own line
4486 (unless (looking-back "\n" nil
)
4490 (markdown-ensure-blank-line-after)
4493 ;; if we're on a blank line, insert the quotes here, otherwise
4494 ;; add a new line first
4495 (unless (looking-at-p "\n")
4498 (markdown-ensure-blank-line-before)
4500 (insert "```" gfm-open-brace lang gfm-close-brace
)
4501 (markdown-syntax-propertize-fenced-block-constructs (line-beginning-position) end
))
4502 (let ((indent (current-indentation))
4504 (delete-horizontal-space :backward-only
)
4505 (markdown-ensure-blank-line-before)
4507 (setq start-bol
(line-beginning-position))
4508 (insert "```" gfm-open-brace lang gfm-close-brace
"\n")
4510 (unless edit
(insert ?
\n))
4513 (markdown-ensure-blank-line-after)
4514 (markdown-syntax-propertize-fenced-block-constructs start-bol
(point)))
4516 (when edit
(markdown-edit-code-block)))))
4518 (defun markdown-code-block-lang (&optional pos-prop
)
4519 "Return the language name for a GFM or tilde fenced code block.
4520 The beginning of the block may be described by POS-PROP,
4521 a cons of (pos . prop) giving the position and property
4522 at the beginning of the block."
4525 (markdown-max-of-seq
4530 #'markdown-find-previous-prop
4531 (markdown-get-fenced-block-begin-properties))))))
4533 (goto-char (car pos-prop
))
4534 (set-match-data (get-text-property (point) (cdr pos-prop
)))
4535 ;; Note: Hard-coded group number assumes tilde
4536 ;; and GFM fenced code regexp groups agree.
4537 (let ((begin (match-beginning 3))
4538 (end (match-end 3)))
4539 (when (and begin end
)
4540 ;; Fix language strings beginning with periods, like ".ruby".
4541 (when (eq (char-after begin
) ?.
)
4542 (setq begin
(1+ begin
)))
4543 (buffer-substring-no-properties begin end
)))))
4545 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer
)
4546 (with-current-buffer (or buffer
(current-buffer))
4548 (goto-char (point-min))
4550 with prop
= 'markdown-gfm-block-begin
4551 for pos-prop
= (markdown-find-next-prop prop
)
4553 for lang
= (markdown-code-block-lang pos-prop
)
4554 do
(progn (when lang
(markdown-gfm-add-used-language lang
))
4555 (goto-char (next-single-property-change (point) prop
)))))))
4557 (defun markdown-insert-foldable-block ()
4558 "Insert details disclosure element to make content foldable.
4559 If a region is active, wrap this region with the disclosure
4560 element. More detais here https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details."
4562 (let ((details-open-tag "<details>")
4563 (details-close-tag "</details>")
4564 (summary-open-tag "<summary>")
4565 (summary-close-tag " </summary>"))
4567 (let* ((b (region-beginning))
4569 (indent (progn (goto-char b
) (current-indentation))))
4571 ;; if we're on a blank line, don't newline, otherwise the tags
4572 ;; should go on its own line
4573 (unless (looking-back "\n" nil
)
4576 (insert details-close-tag
)
4577 (markdown-ensure-blank-line-after)
4579 ;; if we're on a blank line, insert the quotes here, otherwise
4580 ;; add a new line first
4581 (unless (looking-at-p "\n")
4584 (markdown-ensure-blank-line-before)
4586 (insert details-open-tag
"\n")
4587 (insert summary-open-tag summary-close-tag
)
4588 (search-backward summary-close-tag
))
4589 (let ((indent (current-indentation)))
4590 (delete-horizontal-space :backward-only
)
4591 (markdown-ensure-blank-line-before)
4593 (insert details-open-tag
"\n")
4594 (insert summary-open-tag summary-close-tag
"\n")
4595 (insert details-close-tag
)
4597 (markdown-ensure-blank-line-after)
4598 (search-backward summary-close-tag
)))))
4601 ;;; Footnotes =================================================================
4603 (defun markdown-footnote-counter-inc ()
4604 "Increment `markdown-footnote-counter' and return the new value."
4605 (when (= markdown-footnote-counter
0) ; hasn't been updated in this buffer yet.
4607 (goto-char (point-min))
4608 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars
"*?\\)\\]:")
4610 (let ((fn (string-to-number (match-string 1))))
4611 (when (> fn markdown-footnote-counter
)
4612 (setq markdown-footnote-counter fn
))))))
4613 (cl-incf markdown-footnote-counter
))
4615 (defun markdown-insert-footnote ()
4616 "Insert footnote with a new number and move point to footnote definition."
4618 (let ((fn (markdown-footnote-counter-inc)))
4619 (insert (format "[^%d]" fn
))
4620 (markdown-footnote-text-find-new-location)
4621 (markdown-ensure-blank-line-before)
4622 (unless (markdown-cur-line-blank-p)
4624 (insert (format "[^%d]: " fn
))
4625 (markdown-ensure-blank-line-after)))
4627 (defun markdown-footnote-text-find-new-location ()
4628 "Position the point at the proper location for a new footnote text."
4630 ((eq markdown-footnote-location
'end
) (goto-char (point-max)))
4631 ((eq markdown-footnote-location
'immediately
) (markdown-end-of-text-block))
4632 ((eq markdown-footnote-location
'subtree
) (markdown-end-of-subtree))
4633 ((eq markdown-footnote-location
'header
) (markdown-end-of-defun))))
4635 (defun markdown-footnote-kill ()
4636 "Kill the footnote at point.
4637 The footnote text is killed (and added to the kill ring), the
4638 footnote marker is deleted. Point has to be either at the
4639 footnote marker or in the footnote text."
4641 (let ((marker-pos nil
)
4642 (skip-deleting-marker nil
)
4643 (starting-footnote-text-positions
4644 (markdown-footnote-text-positions)))
4645 (when starting-footnote-text-positions
4646 ;; We're starting in footnote text, so mark our return position and jump
4647 ;; to the marker if possible.
4648 (let ((marker-pos (markdown-footnote-find-marker
4649 (cl-first starting-footnote-text-positions
))))
4651 (goto-char (1- marker-pos
))
4652 ;; If there isn't a marker, we still want to kill the text.
4653 (setq skip-deleting-marker t
))))
4654 ;; Either we didn't start in the text, or we started in the text and jumped
4655 ;; to the marker. We want to assume we're at the marker now and error if
4657 (unless skip-deleting-marker
4658 (let ((marker (markdown-footnote-delete-marker)))
4660 (error "Not at a footnote"))
4661 ;; Even if we knew the text position before, it changed when we deleted
4663 (setq marker-pos
(cl-second marker
))
4664 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker
))))
4665 (unless new-text-pos
4666 (error "No text for footnote `%s'" (cl-first marker
)))
4667 (goto-char new-text-pos
))))
4668 (let ((pos (markdown-footnote-kill-text)))
4669 (goto-char (if starting-footnote-text-positions
4673 (defun markdown-footnote-delete-marker ()
4674 "Delete a footnote marker at point.
4675 Returns a list (ID START) containing the footnote ID and the
4676 start position of the marker before deletion. If no footnote
4677 marker was deleted, this function returns NIL."
4678 (let ((marker (markdown-footnote-marker-positions)))
4680 (delete-region (cl-second marker
) (cl-third marker
))
4683 (defun markdown-footnote-kill-text ()
4684 "Kill footnote text at point.
4685 Returns the start position of the footnote text before deletion,
4686 or NIL if point was not inside a footnote text.
4688 The killed text is placed in the kill ring (without the footnote
4690 (let ((fn (markdown-footnote-text-positions)))
4692 (let ((text (delete-and-extract-region (cl-second fn
) (cl-third fn
))))
4693 (string-match (concat "\\[\\" (cl-first fn
) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text
)
4694 (kill-new (match-string 1 text
))
4695 (when (and (markdown-cur-line-blank-p)
4696 (markdown-prev-line-blank-p)
4698 (delete-region (1- (point)) (point)))
4701 (defun markdown-footnote-goto-text ()
4702 "Jump to the text of the footnote at point."
4704 (let ((fn (car (markdown-footnote-marker-positions))))
4706 (user-error "Not at a footnote marker"))
4707 (let ((new-pos (markdown-footnote-find-text fn
)))
4709 (error "No definition found for footnote `%s'" fn
))
4710 (goto-char new-pos
))))
4712 (defun markdown-footnote-return ()
4713 "Return from a footnote to its footnote number in the main text."
4715 (let ((fn (save-excursion
4716 (car (markdown-footnote-text-positions)))))
4718 (user-error "Not in a footnote"))
4719 (let ((new-pos (markdown-footnote-find-marker fn
)))
4721 (error "Footnote marker `%s' not found" fn
))
4722 (goto-char new-pos
))))
4724 (defun markdown-footnote-find-marker (id)
4725 "Find the location of the footnote marker with ID.
4726 The actual buffer position returned is the position directly
4727 following the marker's closing bracket. If no marker is found,
4730 (goto-char (point-min))
4731 (when (re-search-forward (concat "\\[" id
"\\]\\([^:]\\|\\'\\)") nil t
)
4732 (skip-chars-backward "^]")
4735 (defun markdown-footnote-find-text (id)
4736 "Find the location of the text of footnote ID.
4737 The actual buffer position returned is the position of the first
4738 character of the text, after the footnote's identifier. If no
4739 footnote text is found, NIL is returned."
4741 (goto-char (point-min))
4742 (when (re-search-forward (concat "^ \\{0,3\\}\\[" id
"\\]:") nil t
)
4743 (skip-chars-forward "[ \t]")
4746 (defun markdown-footnote-marker-positions ()
4747 "Return the position and ID of the footnote marker point is on.
4748 The return value is a list (ID START END). If point is not on a
4749 footnote, NIL is returned."
4750 ;; first make sure we're at a footnote marker
4751 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars
"*\\]?") (line-beginning-position))
4752 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars
"*?\\]")))
4754 ;; move point between [ and ^:
4755 (if (looking-at-p "\\[")
4757 (skip-chars-backward "^["))
4758 (looking-at (concat "\\(\\^" markdown-footnote-chars
"*?\\)\\]"))
4759 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
4761 (defun markdown-footnote-text-positions ()
4762 "Return the start and end positions of the footnote text point is in.
4763 The exact return value is a list of three elements: (ID START END).
4764 The start position is the position of the opening bracket
4765 of the footnote id. The end position is directly after the
4766 newline that ends the footnote. If point is not in a footnote,
4767 NIL is returned instead."
4770 (move-beginning-of-line 1)
4771 ;; Try to find the label. If we haven't found the label and we're at a blank
4772 ;; or indented line, back up if possible.
4774 (not (and (looking-at markdown-regex-footnote-definition
)
4775 (setq result
(list (match-string 1) (point)))))
4777 (or (markdown-cur-line-blank-p)
4778 (>= (current-indentation) 4))))
4781 ;; Advance if there is a next line that is either blank or indented.
4782 ;; (Need to check if we're on the last line, because
4783 ;; markdown-next-line-blank-p returns true for last line in buffer.)
4784 (while (and (/= (line-end-position) (point-max))
4785 (or (markdown-next-line-blank-p)
4786 (>= (markdown-next-line-indent) 4)))
4788 ;; Move back while the current line is blank.
4789 (while (markdown-cur-line-blank-p)
4791 ;; Advance to capture this line and a single trailing newline (if there
4794 (append result
(list (point)))))))
4796 (defun markdown-get-defined-footnotes ()
4797 "Return a list of all defined footnotes.
4798 Result is an alist of pairs (MARKER . LINE), where MARKER is the
4799 footnote marker, a string, and LINE is the line number containing
4800 the footnote definition.
4802 For example, suppose the following footnotes are defined at positions
4805 \[^1]: First footnote here.
4806 \[^marker]: Second footnote.
4808 Then the returned list is: ((\"^1\" . 478) (\"^marker\" . 475))"
4810 (goto-char (point-min))
4812 (while (markdown-search-until-condition
4813 (lambda () (and (not (markdown-code-block-at-point-p))
4814 (not (markdown-inline-code-at-point-p))
4815 (not (markdown-in-comment-p))))
4816 markdown-regex-footnote-definition nil t
)
4817 (let ((marker (match-string-no-properties 1))
4818 (pos (match-beginning 0)))
4819 (unless (zerop (length marker
))
4820 (cl-pushnew (cons marker pos
) footnotes
:test
#'equal
))))
4821 (reverse footnotes
))))
4824 ;;; Element Removal ===========================================================
4826 (defun markdown-kill-thing-at-point ()
4827 "Kill thing at point and add important text, without markup, to kill ring.
4828 Possible things to kill include (roughly in order of precedence):
4829 inline code, headers, horizontal rules, links (add link text to
4830 kill ring), images (add alt text to kill ring), angle uri, email
4831 addresses, bold, italics, reference definition (add URI to kill
4832 ring), footnote markers and text (kill both marker and text, add
4833 text to kill ring), and list items."
4838 ((markdown-inline-code-at-point)
4839 (kill-new (match-string 2))
4840 (delete-region (match-beginning 0) (match-end 0)))
4842 ((thing-at-point-looking-at markdown-regex-header-atx
)
4843 (kill-new (match-string 2))
4844 (delete-region (match-beginning 0) (match-end 0)))
4846 ((thing-at-point-looking-at markdown-regex-header-setext
)
4847 (kill-new (match-string 1))
4848 (delete-region (match-beginning 0) (match-end 0)))
4850 ((thing-at-point-looking-at markdown-regex-hr
)
4851 (kill-new (match-string 0))
4852 (delete-region (match-beginning 0) (match-end 0)))
4853 ;; Inline link or image (add link or alt text to kill ring)
4854 ((thing-at-point-looking-at markdown-regex-link-inline
)
4855 (kill-new (match-string 3))
4856 (delete-region (match-beginning 0) (match-end 0)))
4857 ;; Reference link or image (add link or alt text to kill ring)
4858 ((thing-at-point-looking-at markdown-regex-link-reference
)
4859 (kill-new (match-string 3))
4860 (delete-region (match-beginning 0) (match-end 0)))
4861 ;; Angle URI (add URL to kill ring)
4862 ((thing-at-point-looking-at markdown-regex-angle-uri
)
4863 (kill-new (match-string 2))
4864 (delete-region (match-beginning 0) (match-end 0)))
4865 ;; Email address in angle brackets (add email address to kill ring)
4866 ((thing-at-point-looking-at markdown-regex-email
)
4867 (kill-new (match-string 1))
4868 (delete-region (match-beginning 0) (match-end 0)))
4869 ;; Wiki link (add alias text to kill ring)
4870 ((and markdown-enable-wiki-links
4871 (thing-at-point-looking-at markdown-regex-wiki-link
))
4872 (kill-new (markdown-wiki-link-alias))
4873 (delete-region (match-beginning 1) (match-end 1)))
4875 ((thing-at-point-looking-at markdown-regex-bold
)
4876 (kill-new (match-string 4))
4877 (delete-region (match-beginning 2) (match-end 2)))
4879 ((thing-at-point-looking-at markdown-regex-italic
)
4880 (kill-new (match-string 3))
4881 (delete-region (match-beginning 1) (match-end 1)))
4883 ((thing-at-point-looking-at markdown-regex-strike-through
)
4884 (kill-new (match-string 4))
4885 (delete-region (match-beginning 2) (match-end 2)))
4886 ;; Footnote marker (add footnote text to kill ring)
4887 ((thing-at-point-looking-at markdown-regex-footnote
)
4888 (markdown-footnote-kill))
4889 ;; Footnote text (add footnote text to kill ring)
4890 ((setq val
(markdown-footnote-text-positions))
4891 (markdown-footnote-kill))
4892 ;; Reference definition (add URL to kill ring)
4893 ((thing-at-point-looking-at markdown-regex-reference-definition
)
4894 (kill-new (match-string 5))
4895 (delete-region (match-beginning 0) (match-end 0)))
4897 ((setq val
(markdown-cur-list-item-bounds))
4898 (kill-new (delete-and-extract-region (cl-first val
) (cl-second val
))))
4900 (user-error "Nothing found at point to kill")))))
4902 (defun markdown-kill-outline ()
4903 "Kill visible heading and add it to `kill-ring'."
4906 (markdown-outline-previous)
4907 (kill-region (point) (progn (markdown-outline-next) (point)))))
4909 (defun markdown-kill-block ()
4910 "Kill visible code block, list item, or blockquote and add it to `kill-ring'."
4913 (markdown-backward-block)
4914 (kill-region (point) (progn (markdown-forward-block) (point)))))
4917 ;;; Indentation ===============================================================
4919 (defun markdown-indent-find-next-position (cur-pos positions
)
4920 "Return the position after the index of CUR-POS in POSITIONS.
4921 Positions are calculated by `markdown-calc-indents'."
4922 (while (and positions
4923 (not (equal cur-pos
(car positions
))))
4924 (setq positions
(cdr positions
)))
4925 (or (cadr positions
) 0))
4927 (defun markdown-outdent-find-next-position (cur-pos positions
)
4928 "Return the maximal element that precedes CUR-POS from POSITIONS.
4929 Positions are calculated by `markdown-calc-indents'."
4931 (dolist (i positions
)
4933 (setq result
(max result i
))))
4936 (defun markdown-indent-line ()
4937 "Indent the current line using some heuristics.
4938 If the _previous_ command was either `markdown-enter-key' or
4939 `markdown-cycle', then we should cycle to the next
4940 reasonable indentation position. Otherwise, we could have been
4941 called directly by `markdown-enter-key', by an initial call of
4942 `markdown-cycle', or indirectly by `auto-fill-mode'. In
4943 these cases, indent to the default position.
4944 Positions are calculated by `markdown-calc-indents'."
4946 (let ((positions (markdown-calc-indents))
4947 (point-pos (current-column))
4948 (_ (back-to-indentation))
4949 (cur-pos (current-column)))
4950 (if (not (equal this-command
'markdown-cycle
))
4951 (indent-line-to (car positions
))
4952 (setq positions
(sort (delete-dups positions
) '<))
4953 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions
))
4954 (new-point-pos (max (+ point-pos
(- next-pos cur-pos
)) 0)))
4955 (indent-line-to next-pos
)
4956 (move-to-column new-point-pos
)))))
4958 (defun markdown-calc-indents ()
4959 "Return a list of indentation columns to cycle through.
4960 The first element in the returned list should be considered the
4961 default indentation level. This function does not worry about
4962 duplicate positions, which are handled up by calling functions."
4963 (let (pos prev-line-pos positions
)
4965 ;; Indentation of previous line
4966 (setq prev-line-pos
(markdown-prev-line-indent))
4967 (setq positions
(cons prev-line-pos positions
))
4969 ;; Indentation of previous non-list-marker text
4970 (when (setq pos
(save-excursion
4972 (when (looking-at markdown-regex-list
)
4973 (- (match-end 3) (match-beginning 0)))))
4974 (setq positions
(cons pos positions
)))
4976 ;; Indentation required for a pre block in current context
4977 (setq pos
(length (markdown-pre-indentation (point))))
4978 (setq positions
(cons pos positions
))
4980 ;; Indentation of the previous line + tab-width
4982 (setq positions
(cons (+ prev-line-pos tab-width
) positions
))
4983 (setq positions
(cons tab-width positions
)))
4985 ;; Indentation of the previous line - tab-width
4986 (if (and prev-line-pos
(> prev-line-pos tab-width
))
4987 (setq positions
(cons (- prev-line-pos tab-width
) positions
)))
4989 ;; Indentation of all preceding list markers (when in a list)
4990 (when (setq pos
(markdown-calculate-list-levels))
4991 (setq positions
(append pos positions
)))
4994 (setq positions
(cons 0 positions
))
4996 ;; Return reversed list
4997 (reverse positions
)))
4999 (defun markdown-enter-key () ;FIXME: Partly obsoleted by electric-indent
5000 "Handle RET depending on the context.
5001 If the point is at a table, move to the next row. Otherwise,
5002 indent according to value of `markdown-indent-on-enter'.
5003 When it is nil, simply call `newline'. Otherwise, indent the next line
5004 following RET using `markdown-indent-line'. Furthermore, when it
5005 is set to \\='indent-and-new-item and the point is in a list item,
5006 start a new item with the same indentation. If the point is in an
5007 empty list item, remove it (so that pressing RET twice when in a
5008 list simply adds a blank line)."
5012 ((markdown-table-at-point-p)
5013 (call-interactively #'markdown-table-next-row
))
5014 ;; Indent non-table text
5015 (markdown-indent-on-enter
5017 (if (and (memq markdown-indent-on-enter
'(indent-and-new-item))
5018 (setq bounds
(markdown-cur-list-item-bounds)))
5019 (let ((beg (cl-first bounds
))
5020 (end (cl-second bounds
))
5021 (length (cl-fourth bounds
)))
5022 ;; Point is in a list item
5023 (if (= (- end beg
) length
)
5024 ;; Delete blank list
5026 (delete-region beg end
)
5028 (markdown-indent-line))
5029 (call-interactively #'markdown-insert-list-item
)))
5030 ;; Point is not in a list
5032 (markdown-indent-line))))
5033 ;; Insert a raw newline
5036 (defun markdown-outdent-or-delete (arg)
5037 "Handle BACKSPACE by cycling through indentation points.
5038 When BACKSPACE is pressed, if there is only whitespace
5039 before the current point, then outdent the line one level.
5040 Otherwise, do normal delete by repeating
5041 `backward-delete-char-untabify' ARG times."
5044 (backward-delete-char-untabify arg
)
5045 (let ((cur-pos (current-column))
5046 (start-of-indention (save-excursion
5047 (back-to-indentation)
5049 (positions (markdown-calc-indents)))
5050 (if (and (> cur-pos
0) (= cur-pos start-of-indention
))
5051 (indent-line-to (markdown-outdent-find-next-position cur-pos positions
))
5052 (backward-delete-char-untabify arg
)))))
5054 (defun markdown-find-leftmost-column (beg end
)
5055 "Find the leftmost column in the region from BEG to END."
5056 (let ((mincol 1000))
5059 (while (< (point) end
)
5060 (back-to-indentation)
5061 (unless (looking-at-p "[ \t]*$")
5062 (setq mincol
(min mincol
(current-column))))
5067 (defun markdown-indent-region (beg end arg
)
5068 "Indent the region from BEG to END using some heuristics.
5069 When ARG is non-nil, outdent the region instead.
5070 See `markdown-indent-line' and `markdown-indent-line'."
5071 (interactive "*r\nP")
5072 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
5073 (leftmostcol (markdown-find-leftmost-column beg end
))
5075 (markdown-outdent-find-next-position leftmostcol positions
)
5076 (markdown-indent-find-next-position leftmostcol positions
))))
5077 (indent-rigidly beg end
(- next-pos leftmostcol
))
5078 (setq deactivate-mark nil
)))
5080 (defun markdown-outdent-region (beg end
)
5081 "Call `markdown-indent-region' on region from BEG to END with prefix."
5083 (markdown-indent-region beg end t
))
5085 (defun markdown--indent-region (start end
)
5086 (let ((deactivate-mark nil
))
5089 (setq end
(point-marker))
5093 (while (< (point) end
)
5094 (unless (or (markdown-code-block-at-point-p) (and (bolp) (eolp)))
5095 (indent-according-to-mode))
5097 (move-marker end nil
))))
5100 ;;; Markup Completion =========================================================
5102 (defconst markdown-complete-alist
5103 '((markdown-regex-header-atx . markdown-complete-atx
)
5104 (markdown-regex-header-setext . markdown-complete-setext
)
5105 (markdown-regex-hr . markdown-complete-hr
))
5106 "Association list of form (regexp . function) for markup completion.")
5108 (defun markdown-incomplete-atx-p ()
5109 "Return t if ATX header markup is incomplete and nil otherwise.
5110 Assumes match data is available for `markdown-regex-header-atx'.
5111 Checks that the number of trailing hash marks equals the number of leading
5112 hash marks, that there is only a single space before and after the text,
5113 and that there is no extraneous whitespace in the text."
5115 ;; Number of starting and ending hash marks differs
5116 (not (= (length (match-string 1)) (length (match-string 3))))
5117 ;; When the header text is not empty...
5118 (and (> (length (match-string 2)) 0)
5119 ;; ...if there are extra leading, trailing, or interior spaces
5120 (or (not (= (match-beginning 2) (1+ (match-end 1))))
5121 (not (= (match-beginning 3) (1+ (match-end 2))))
5122 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
5123 ;; When the header text is empty...
5124 (and (= (length (match-string 2)) 0)
5125 ;; ...if there are too many or too few spaces
5126 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
5128 (defun markdown-complete-atx ()
5129 "Complete and normalize ATX headers.
5130 Add or remove hash marks to the end of the header to match the
5131 beginning. Ensure that there is only a single space between hash
5132 marks and header text. Removes extraneous whitespace from header text.
5133 Assumes match data is available for `markdown-regex-header-atx'.
5134 Return nil if markup was complete and non-nil if markup was completed."
5135 (when (markdown-incomplete-atx-p)
5136 (let* ((new-marker (make-marker))
5137 (new-marker (set-marker new-marker
(match-end 2))))
5138 ;; Hash marks and spacing at end
5139 (goto-char (match-end 2))
5140 (delete-region (match-end 2) (match-end 3))
5141 (insert " " (match-string 1))
5142 ;; Remove extraneous whitespace from title
5143 (replace-match (markdown-compress-whitespace-string (match-string 2))
5145 ;; Spacing at beginning
5146 (goto-char (match-end 1))
5147 (delete-region (match-end 1) (match-beginning 2))
5149 ;; Leave point at end of text
5150 (goto-char new-marker
))))
5152 (defun markdown-incomplete-setext-p ()
5153 "Return t if setext header markup is incomplete and nil otherwise.
5154 Assumes match data is available for `markdown-regex-header-setext'.
5155 Checks that length of underline matches text and that there is no
5156 extraneous whitespace in the text."
5157 (or (not (= (length (match-string 1)) (length (match-string 2))))
5158 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
5160 (defun markdown-complete-setext ()
5161 "Complete and normalize setext headers.
5162 Add or remove underline characters to match length of header
5163 text. Removes extraneous whitespace from header text. Assumes
5164 match data is available for `markdown-regex-header-setext'.
5165 Return nil if markup was complete and non-nil if markup was completed."
5166 (when (markdown-incomplete-setext-p)
5167 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
5168 (char (char-after (match-beginning 2)))
5169 (level (if (char-equal char ?-
) 2 1)))
5170 (goto-char (match-beginning 0))
5171 (delete-region (match-beginning 0) (match-end 0))
5172 (markdown-insert-header level text t
)
5175 (defun markdown-incomplete-hr-p ()
5176 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
5177 Assumes match data is available for `markdown-regex-hr'."
5178 (not (member (match-string 0) markdown-hr-strings
)))
5180 (defun markdown-complete-hr ()
5181 "Complete horizontal rules.
5182 If horizontal rule string is a member of `markdown-hr-strings',
5183 do nothing. Otherwise, replace with the car of
5184 `markdown-hr-strings'.
5185 Assumes match data is available for `markdown-regex-hr'.
5186 Return nil if markup was complete and non-nil if markup was completed."
5187 (when (markdown-incomplete-hr-p)
5188 (replace-match (car markdown-hr-strings
))
5191 (defun markdown-complete ()
5192 "Complete markup of object near point or in region when active.
5193 Handle all objects in `markdown-complete-alist', in order.
5194 See `markdown-complete-at-point' and `markdown-complete-region'."
5197 (markdown-complete-region (region-beginning) (region-end))
5198 (markdown-complete-at-point)))
5200 (defun markdown-complete-at-point ()
5201 "Complete markup of object near point.
5202 Handle all elements of `markdown-complete-alist' in order."
5204 (let ((list markdown-complete-alist
) found changed
)
5206 (let ((regexp (eval (caar list
) t
)) ;FIXME: Why `eval'?
5207 (function (cdar list
)))
5208 (setq list
(cdr list
))
5209 (when (thing-at-point-looking-at regexp
)
5211 (setq changed
(funcall function
))
5214 (or changed
(user-error "Markup at point is complete"))
5215 (user-error "Nothing to complete at point"))))
5217 (defun markdown-complete-region (beg end
)
5218 "Complete markup of objects in region from BEG to END.
5219 Handle all objects in `markdown-complete-alist', in order. Each
5220 match is checked to ensure that a previous regexp does not also
5223 (let ((end-marker (set-marker (make-marker) end
))
5225 (dolist (element markdown-complete-alist
)
5226 (let ((regexp (eval (car element
) t
)) ;FIXME: Why `eval'?
5227 (function (cdr element
)))
5229 (while (re-search-forward regexp end-marker
'limit
)
5230 (when (match-string 0)
5231 ;; Make sure this is not a match for any of the preceding regexps.
5232 ;; This prevents mistaking an HR for a Setext subheading.
5235 (dolist (prev-regexp previous
)
5236 (or match
(setq match
(looking-back prev-regexp nil
)))))
5238 (save-excursion (funcall function
))))))
5239 (cl-pushnew regexp previous
:test
#'equal
)))
5242 (defun markdown-complete-buffer ()
5243 "Complete markup for all objects in the current buffer."
5245 (markdown-complete-region (point-min) (point-max)))
5248 ;;; Markup Cycling ============================================================
5250 (defun markdown-cycle-atx (arg &optional remove
)
5251 "Cycle ATX header markup.
5252 Promote header (decrease level) when ARG is 1 and demote
5253 header (increase level) if arg is -1. When REMOVE is non-nil,
5254 remove the header when the level reaches zero and stop cycling
5255 when it reaches six. Otherwise, perform a proper cycling through
5256 levels one through six. Assumes match data is available for
5257 `markdown-regex-header-atx'."
5258 (let* ((old-level (length (match-string 1)))
5259 (new-level (+ old-level arg
))
5260 (text (match-string 2)))
5262 (setq new-level
(% new-level
6))
5263 (setq new-level
(cond ((= new-level
0) 6)
5264 ((< new-level
0) (+ new-level
6))
5268 (markdown-unwrap-thing-at-point nil
0 2))
5270 (goto-char (match-beginning 0))
5271 (delete-region (match-beginning 0) (match-end 0))
5272 (markdown-insert-header new-level text nil
)))))
5274 (defun markdown-cycle-setext (arg &optional remove
)
5275 "Cycle setext header markup.
5276 Promote header (increase level) when ARG is 1 and demote
5277 header (decrease level or remove) if arg is -1. When demoting a
5278 level-two setext header, replace with a level-three atx header.
5279 When REMOVE is non-nil, remove the header when the level reaches
5280 zero. Otherwise, cycle back to a level six atx header. Assumes
5281 match data is available for `markdown-regex-header-setext'."
5282 (let* ((char (char-after (match-beginning 2)))
5283 (old-level (if (char-equal char ?
=) 1 2))
5284 (new-level (+ old-level arg
)))
5285 (when (and (not remove
) (= new-level
0))
5289 (markdown-unwrap-thing-at-point nil
0 1))
5291 (markdown-insert-header new-level nil t
))
5293 (markdown-insert-header new-level nil nil
)))))
5295 (defun markdown-cycle-hr (arg &optional remove
)
5296 "Cycle string used for horizontal rule from `markdown-hr-strings'.
5297 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
5298 backwards (promote). When REMOVE is non-nil, remove the hr instead
5299 of cycling when the end of the list is reached.
5300 Assumes match data is available for `markdown-regex-hr'."
5301 (let* ((strings (if (= arg -
1)
5302 (reverse markdown-hr-strings
)
5303 markdown-hr-strings
))
5304 (tail (member (match-string 0) strings
))
5305 (new (or (cadr tail
)
5311 (replace-match new
)))
5313 (defun markdown-cycle-bold ()
5314 "Cycle bold markup between underscores and asterisks.
5315 Assumes match data is available for `markdown-regex-bold'."
5317 (let* ((old-delim (match-string 3))
5318 (new-delim (if (string-equal old-delim
"**") "__" "**")))
5319 (replace-match new-delim t t nil
3)
5320 (replace-match new-delim t t nil
5))))
5322 (defun markdown-cycle-italic ()
5323 "Cycle italic markup between underscores and asterisks.
5324 Assumes match data is available for `markdown-regex-italic'."
5326 (let* ((old-delim (match-string 2))
5327 (new-delim (if (string-equal old-delim
"*") "_" "*")))
5328 (replace-match new-delim t t nil
2)
5329 (replace-match new-delim t t nil
4))))
5332 ;;; Keymap ====================================================================
5334 (defun markdown--style-map-prompt ()
5335 "Return a formatted prompt for Markdown markup insertion."
5336 (when markdown-enable-prefix-prompts
5339 (propertize "bold" 'face
'markdown-bold-face
) ", "
5340 (propertize "italic" 'face
'markdown-italic-face
) ", "
5341 (propertize "code" 'face
'markdown-inline-code-face
) ", "
5342 (propertize "C = GFM code" 'face
'markdown-code-face
) ", "
5343 (propertize "pre" 'face
'markdown-pre-face
) ", "
5344 (propertize "footnote" 'face
'markdown-footnote-text-face
) ", "
5345 (propertize "F = foldable" 'face
'markdown-bold-face
) ", "
5346 (propertize "q = blockquote" 'face
'markdown-blockquote-face
) ", "
5347 (propertize "h & 1-6 = heading" 'face
'markdown-header-face
) ", "
5348 (propertize "- = hr" 'face
'markdown-hr-face
) ", "
5351 (defun markdown--command-map-prompt ()
5352 "Return prompt for Markdown buffer-wide commands."
5353 (when markdown-enable-prefix-prompts
5356 (propertize "m" 'face
'markdown-bold-face
) "arkdown, "
5357 (propertize "p" 'face
'markdown-bold-face
) "review, "
5358 (propertize "o" 'face
'markdown-bold-face
) "pen, "
5359 (propertize "e" 'face
'markdown-bold-face
) "xport, "
5360 "export & pre" (propertize "v" 'face
'markdown-bold-face
) "iew, "
5361 (propertize "c" 'face
'markdown-bold-face
) "heck refs, "
5362 (propertize "u" 'face
'markdown-bold-face
) "nused refs, "
5365 (defvar markdown-mode-style-map
5366 (let ((map (make-keymap (markdown--style-map-prompt))))
5367 (define-key map
(kbd "1") 'markdown-insert-header-atx-1
)
5368 (define-key map
(kbd "2") 'markdown-insert-header-atx-2
)
5369 (define-key map
(kbd "3") 'markdown-insert-header-atx-3
)
5370 (define-key map
(kbd "4") 'markdown-insert-header-atx-4
)
5371 (define-key map
(kbd "5") 'markdown-insert-header-atx-5
)
5372 (define-key map
(kbd "6") 'markdown-insert-header-atx-6
)
5373 (define-key map
(kbd "!") 'markdown-insert-header-setext-1
)
5374 (define-key map
(kbd "@") 'markdown-insert-header-setext-2
)
5375 (define-key map
(kbd "b") 'markdown-insert-bold
)
5376 (define-key map
(kbd "c") 'markdown-insert-code
)
5377 (define-key map
(kbd "C") 'markdown-insert-gfm-code-block
)
5378 (define-key map
(kbd "f") 'markdown-insert-footnote
)
5379 (define-key map
(kbd "F") 'markdown-insert-foldable-block
)
5380 (define-key map
(kbd "h") 'markdown-insert-header-dwim
)
5381 (define-key map
(kbd "H") 'markdown-insert-header-setext-dwim
)
5382 (define-key map
(kbd "i") 'markdown-insert-italic
)
5383 (define-key map
(kbd "k") 'markdown-insert-kbd
)
5384 (define-key map
(kbd "l") 'markdown-insert-link
)
5385 (define-key map
(kbd "p") 'markdown-insert-pre
)
5386 (define-key map
(kbd "P") 'markdown-pre-region
)
5387 (define-key map
(kbd "q") 'markdown-insert-blockquote
)
5388 (define-key map
(kbd "s") 'markdown-insert-strike-through
)
5389 (define-key map
(kbd "t") 'markdown-insert-table
)
5390 (define-key map
(kbd "Q") 'markdown-blockquote-region
)
5391 (define-key map
(kbd "w") 'markdown-insert-wiki-link
)
5392 (define-key map
(kbd "-") 'markdown-insert-hr
)
5393 (define-key map
(kbd "[") 'markdown-insert-gfm-checkbox
)
5394 ;; Deprecated keys that may be removed in a future version
5395 (define-key map
(kbd "e") 'markdown-insert-italic
)
5397 "Keymap for Markdown text styling commands.")
5399 (defvar markdown-mode-command-map
5400 (let ((map (make-keymap (markdown--command-map-prompt))))
5401 (define-key map
(kbd "m") 'markdown-other-window
)
5402 (define-key map
(kbd "p") 'markdown-preview
)
5403 (define-key map
(kbd "e") 'markdown-export
)
5404 (define-key map
(kbd "v") 'markdown-export-and-preview
)
5405 (define-key map
(kbd "o") 'markdown-open
)
5406 (define-key map
(kbd "l") 'markdown-live-preview-mode
)
5407 (define-key map
(kbd "w") 'markdown-kill-ring-save
)
5408 (define-key map
(kbd "c") 'markdown-check-refs
)
5409 (define-key map
(kbd "u") 'markdown-unused-refs
)
5410 (define-key map
(kbd "n") 'markdown-cleanup-list-numbers
)
5411 (define-key map
(kbd "]") 'markdown-complete-buffer
)
5412 (define-key map
(kbd "^") 'markdown-table-sort-lines
)
5413 (define-key map
(kbd "|") 'markdown-table-convert-region
)
5414 (define-key map
(kbd "t") 'markdown-table-transpose
)
5416 "Keymap for Markdown buffer-wide commands.")
5418 (defvar markdown-mode-map
5419 (let ((map (make-keymap)))
5420 ;; Markup insertion & removal
5421 (define-key map
(kbd "C-c C-s") markdown-mode-style-map
)
5422 (define-key map
(kbd "C-c C-l") 'markdown-insert-link
)
5423 (define-key map
(kbd "C-c C-k") 'markdown-kill-thing-at-point
)
5424 ;; Promotion, demotion, and cycling
5425 (define-key map
(kbd "C-c C--") 'markdown-promote
)
5426 (define-key map
(kbd "C-c C-=") 'markdown-demote
)
5427 (define-key map
(kbd "C-c C-]") 'markdown-complete
)
5428 ;; Following and doing things
5429 (define-key map
(kbd "C-c C-o") 'markdown-follow-thing-at-point
)
5430 (define-key map
(kbd "C-c C-d") 'markdown-do
)
5431 (define-key map
(kbd "C-c '") 'markdown-edit-code-block
)
5433 (define-key map
(kbd "RET") 'markdown-enter-key
)
5434 (define-key map
(kbd "DEL") 'markdown-outdent-or-delete
)
5435 (define-key map
(kbd "C-c >") 'markdown-indent-region
)
5436 (define-key map
(kbd "C-c <") 'markdown-outdent-region
)
5437 ;; Visibility cycling
5438 (define-key map
(kbd "TAB") 'markdown-cycle
)
5439 ;; S-iso-lefttab and S-tab should both be mapped to `backtab' by
5440 ;; (local-)function-key-map.
5441 ;;(define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
5442 ;;(define-key map (kbd "<S-tab>") 'markdown-shifttab)
5443 (define-key map
(kbd "<backtab>") 'markdown-shifttab
)
5444 ;; Heading and list navigation
5445 (define-key map
(kbd "C-c C-n") 'markdown-outline-next
)
5446 (define-key map
(kbd "C-c C-p") 'markdown-outline-previous
)
5447 (define-key map
(kbd "C-c C-f") 'markdown-outline-next-same-level
)
5448 (define-key map
(kbd "C-c C-b") 'markdown-outline-previous-same-level
)
5449 (define-key map
(kbd "C-c C-u") 'markdown-outline-up
)
5450 ;; Buffer-wide commands
5451 (define-key map
(kbd "C-c C-c") markdown-mode-command-map
)
5452 ;; Subtree, list, and table editing
5453 (define-key map
(kbd "C-c <up>") 'markdown-move-up
)
5454 (define-key map
(kbd "C-c <down>") 'markdown-move-down
)
5455 (define-key map
(kbd "C-c <left>") 'markdown-promote
)
5456 (define-key map
(kbd "C-c <right>") 'markdown-demote
)
5457 (define-key map
(kbd "C-c S-<up>") 'markdown-table-delete-row
)
5458 (define-key map
(kbd "C-c S-<down>") 'markdown-table-insert-row
)
5459 (define-key map
(kbd "C-c S-<left>") 'markdown-table-delete-column
)
5460 (define-key map
(kbd "C-c S-<right>") 'markdown-table-insert-column
)
5461 (define-key map
(kbd "C-c C-M-h") 'markdown-mark-subtree
)
5462 (define-key map
(kbd "C-x n s") 'markdown-narrow-to-subtree
)
5463 (define-key map
(kbd "M-RET") 'markdown-insert-list-item
)
5464 (define-key map
(kbd "C-c C-j") 'markdown-insert-list-item
)
5465 ;; Paragraphs (Markdown context aware)
5466 (define-key map
[remap backward-paragraph
] 'markdown-backward-paragraph
)
5467 (define-key map
[remap forward-paragraph
] 'markdown-forward-paragraph
)
5468 (define-key map
[remap mark-paragraph
] 'markdown-mark-paragraph
)
5469 ;; Blocks (one or more paragraphs)
5470 (define-key map
(kbd "C-M-{") 'markdown-backward-block
)
5471 (define-key map
(kbd "C-M-}") 'markdown-forward-block
)
5472 (define-key map
(kbd "C-c M-h") 'markdown-mark-block
)
5473 (define-key map
(kbd "C-x n b") 'markdown-narrow-to-block
)
5474 ;; Pages (top-level sections)
5475 (define-key map
[remap backward-page
] 'markdown-backward-page
)
5476 (define-key map
[remap forward-page
] 'markdown-forward-page
)
5477 (define-key map
[remap mark-page
] 'markdown-mark-page
)
5478 (define-key map
[remap narrow-to-page
] 'markdown-narrow-to-page
)
5480 (define-key map
(kbd "M-n") 'markdown-next-link
)
5481 (define-key map
(kbd "M-p") 'markdown-previous-link
)
5482 ;; Toggling functionality
5483 (define-key map
(kbd "C-c C-x C-e") 'markdown-toggle-math
)
5484 (define-key map
(kbd "C-c C-x C-f") 'markdown-toggle-fontify-code-blocks-natively
)
5485 (define-key map
(kbd "C-c C-x C-i") 'markdown-toggle-inline-images
)
5486 (define-key map
(kbd "C-c C-x C-l") 'markdown-toggle-url-hiding
)
5487 (define-key map
(kbd "C-c C-x C-m") 'markdown-toggle-markup-hiding
)
5488 ;; Alternative keys (in case of problems with the arrow keys)
5489 (define-key map
(kbd "C-c C-x u") 'markdown-move-up
)
5490 (define-key map
(kbd "C-c C-x d") 'markdown-move-down
)
5491 (define-key map
(kbd "C-c C-x l") 'markdown-promote
)
5492 (define-key map
(kbd "C-c C-x r") 'markdown-demote
)
5493 ;; Deprecated keys that may be removed in a future version
5494 (define-key map
(kbd "C-c C-a L") 'markdown-insert-link
) ;; C-c C-l
5495 (define-key map
(kbd "C-c C-a l") 'markdown-insert-link
) ;; C-c C-l
5496 (define-key map
(kbd "C-c C-a r") 'markdown-insert-link
) ;; C-c C-l
5497 (define-key map
(kbd "C-c C-a u") 'markdown-insert-uri
) ;; C-c C-l
5498 (define-key map
(kbd "C-c C-a f") 'markdown-insert-footnote
)
5499 (define-key map
(kbd "C-c C-a w") 'markdown-insert-wiki-link
)
5500 (define-key map
(kbd "C-c C-t 1") 'markdown-insert-header-atx-1
)
5501 (define-key map
(kbd "C-c C-t 2") 'markdown-insert-header-atx-2
)
5502 (define-key map
(kbd "C-c C-t 3") 'markdown-insert-header-atx-3
)
5503 (define-key map
(kbd "C-c C-t 4") 'markdown-insert-header-atx-4
)
5504 (define-key map
(kbd "C-c C-t 5") 'markdown-insert-header-atx-5
)
5505 (define-key map
(kbd "C-c C-t 6") 'markdown-insert-header-atx-6
)
5506 (define-key map
(kbd "C-c C-t !") 'markdown-insert-header-setext-1
)
5507 (define-key map
(kbd "C-c C-t @") 'markdown-insert-header-setext-2
)
5508 (define-key map
(kbd "C-c C-t h") 'markdown-insert-header-dwim
)
5509 (define-key map
(kbd "C-c C-t H") 'markdown-insert-header-setext-dwim
)
5510 (define-key map
(kbd "C-c C-t s") 'markdown-insert-header-setext-2
)
5511 (define-key map
(kbd "C-c C-t t") 'markdown-insert-header-setext-1
)
5512 (define-key map
(kbd "C-c C-i") 'markdown-insert-image
)
5513 (define-key map
(kbd "C-c C-x m") 'markdown-insert-list-item
) ;; C-c C-j
5514 (define-key map
(kbd "C-c C-x C-x") 'markdown-toggle-gfm-checkbox
) ;; C-c C-d
5515 (define-key map
(kbd "C-c -") 'markdown-insert-hr
)
5517 "Keymap for Markdown major mode.")
5519 (defvar markdown-mode-mouse-map
5520 (when markdown-mouse-follow-link
5521 (let ((map (make-sparse-keymap)))
5522 (define-key map
[follow-link
] 'mouse-face
)
5523 (define-key map
[mouse-2
] #'markdown-follow-thing-at-point
)
5525 "Keymap for following links with mouse.")
5527 (defvar gfm-mode-map
5528 (let ((map (make-sparse-keymap)))
5529 (set-keymap-parent map markdown-mode-map
)
5530 (define-key map
(kbd "C-c C-s d") 'markdown-insert-strike-through
)
5531 (define-key map
"`" 'markdown-electric-backquote
)
5533 "Keymap for `gfm-mode'.
5534 See also `markdown-mode-map'.")
5537 ;;; Menu ======================================================================
5539 (easy-menu-define markdown-mode-menu markdown-mode-map
5540 "Menu for Markdown mode."
5544 ["Jump" markdown-do
]
5545 ["Follow Link" markdown-follow-thing-at-point
]
5546 ["Next Link" markdown-next-link
]
5547 ["Previous Link" markdown-previous-link
]
5549 ["Next Heading or List Item" markdown-outline-next
]
5550 ["Previous Heading or List Item" markdown-outline-previous
]
5551 ["Next at Same Level" markdown-outline-next-same-level
]
5552 ["Previous at Same Level" markdown-outline-previous-same-level
]
5553 ["Up to Parent" markdown-outline-up
]
5555 ["Forward Paragraph" markdown-forward-paragraph
]
5556 ["Backward Paragraph" markdown-backward-paragraph
]
5557 ["Forward Block" markdown-forward-block
]
5558 ["Backward Block" markdown-backward-block
])
5560 ["Cycle Heading Visibility" markdown-cycle
5561 :enable
(markdown-on-heading-p)]
5562 ["Cycle Heading Visibility (Global)" markdown-shifttab
]
5564 ["Narrow to Region" narrow-to-region
]
5565 ["Narrow to Block" markdown-narrow-to-block
]
5566 ["Narrow to Section" narrow-to-defun
]
5567 ["Narrow to Subtree" markdown-narrow-to-subtree
]
5568 ["Widen" widen
(buffer-narrowed-p)]
5570 ["Toggle Markup Hiding" markdown-toggle-markup-hiding
5573 :selected markdown-hide-markup
])
5575 ("Headings & Structure"
5576 ["Automatic Heading" markdown-insert-header-dwim
5578 ["Automatic Heading (Setext)" markdown-insert-header-setext-dwim
5580 ("Specific Heading (atx)"
5581 ["First Level atx" markdown-insert-header-atx-1
5583 ["Second Level atx" markdown-insert-header-atx-2
5585 ["Third Level atx" markdown-insert-header-atx-3
5587 ["Fourth Level atx" markdown-insert-header-atx-4
5589 ["Fifth Level atx" markdown-insert-header-atx-5
5591 ["Sixth Level atx" markdown-insert-header-atx-6
5593 ("Specific Heading (Setext)"
5594 ["First Level Setext" markdown-insert-header-setext-1
5596 ["Second Level Setext" markdown-insert-header-setext-2
5598 ["Horizontal Rule" markdown-insert-hr
5601 ["Move Subtree Up" markdown-move-up
5603 ["Move Subtree Down" markdown-move-down
5605 ["Promote Subtree" markdown-promote
5607 ["Demote Subtree" markdown-demote
5608 :keys
"C-c <right>"])
5610 ["Indent Region" markdown-indent-region
]
5611 ["Outdent Region" markdown-outdent-region
]
5613 ["Mark Paragraph" mark-paragraph
]
5614 ["Mark Block" markdown-mark-block
]
5615 ["Mark Section" mark-defun
]
5616 ["Mark Subtree" markdown-mark-subtree
])
5618 ["Move Row Up" markdown-move-up
5619 :enable
(markdown-table-at-point-p)
5621 ["Move Row Down" markdown-move-down
5622 :enable
(markdown-table-at-point-p)
5624 ["Move Column Left" markdown-promote
5625 :enable
(markdown-table-at-point-p)
5627 ["Move Column Right" markdown-demote
5628 :enable
(markdown-table-at-point-p)
5629 :keys
"C-c <right>"]
5630 ["Delete Row" markdown-table-delete-row
5631 :enable
(markdown-table-at-point-p)]
5632 ["Insert Row" markdown-table-insert-row
5633 :enable
(markdown-table-at-point-p)]
5634 ["Delete Column" markdown-table-delete-column
5635 :enable
(markdown-table-at-point-p)]
5636 ["Insert Column" markdown-table-insert-column
5637 :enable
(markdown-table-at-point-p)]
5638 ["Insert Table" markdown-insert-table
]
5640 ["Convert Region to Table" markdown-table-convert-region
]
5641 ["Sort Table Lines" markdown-table-sort-lines
5642 :enable
(markdown-table-at-point-p)]
5643 ["Transpose Table" markdown-table-transpose
5644 :enable
(markdown-table-at-point-p)])
5646 ["Insert List Item" markdown-insert-list-item
]
5647 ["Move Subtree Up" markdown-move-up
5649 ["Move Subtree Down" markdown-move-down
5651 ["Indent Subtree" markdown-demote
5652 :keys
"C-c <right>"]
5653 ["Outdent Subtree" markdown-promote
5655 ["Renumber List" markdown-cleanup-list-numbers
]
5656 ["Insert Task List Item" markdown-insert-gfm-checkbox
5658 ["Toggle Task List Item" markdown-toggle-gfm-checkbox
5659 :enable
(markdown-gfm-task-list-item-at-point)
5662 ["Insert Link" markdown-insert-link
]
5663 ["Insert Image" markdown-insert-image
]
5664 ["Insert Footnote" markdown-insert-footnote
5666 ["Insert Wiki Link" markdown-insert-wiki-link
5669 ["Check References" markdown-check-refs
]
5670 ["Find Unused References" markdown-unused-refs
]
5671 ["Toggle URL Hiding" markdown-toggle-url-hiding
5673 :selected markdown-hide-urls
]
5674 ["Toggle Inline Images" markdown-toggle-inline-images
5677 :selected markdown-inline-image-overlays
]
5678 ["Toggle Wiki Links" markdown-toggle-wiki-links
5680 :selected markdown-enable-wiki-links
])
5682 ["Bold" markdown-insert-bold
]
5683 ["Italic" markdown-insert-italic
]
5684 ["Code" markdown-insert-code
]
5685 ["Strikethrough" markdown-insert-strike-through
]
5686 ["Keyboard" markdown-insert-kbd
]
5688 ["Blockquote" markdown-insert-blockquote
]
5689 ["Preformatted" markdown-insert-pre
]
5690 ["GFM Code Block" markdown-insert-gfm-code-block
]
5691 ["Edit Code Block" markdown-edit-code-block
5692 :enable
(markdown-code-block-at-point-p)]
5693 ["Foldable Block" markdown-insert-foldable-block
]
5695 ["Blockquote Region" markdown-blockquote-region
]
5696 ["Preformatted Region" markdown-pre-region
]
5698 ["Fontify Code Blocks Natively"
5699 markdown-toggle-fontify-code-blocks-natively
5701 :selected markdown-fontify-code-blocks-natively
]
5702 ["LaTeX Math Support" markdown-toggle-math
5704 :selected markdown-enable-math
])
5707 ["Compile" markdown-other-window
]
5708 ["Preview" markdown-preview
]
5709 ["Export" markdown-export
]
5710 ["Export & View" markdown-export-and-preview
]
5711 ["Open" markdown-open
]
5712 ["Live Export" markdown-live-preview-mode
5714 :selected markdown-live-preview-mode
]
5715 ["Kill ring save" markdown-kill-ring-save
])
5716 ("Markup Completion and Cycling"
5717 ["Complete Markup" markdown-complete
]
5718 ["Promote Element" markdown-promote
5720 ["Demote Element" markdown-demote
5723 ["Kill Element" markdown-kill-thing-at-point
]
5726 ["Version" markdown-show-version
]
5727 ["Homepage" markdown-mode-info
]
5728 ["Describe Mode" (describe-function 'markdown-mode
)]
5729 ["Guide" (browse-url "https://leanpub.com/markdown-mode")])))
5732 ;;; imenu =====================================================================
5734 (defun markdown-imenu-create-nested-index ()
5735 "Create and return a nested imenu index alist for the current buffer.
5736 See `imenu-create-index-function' and `imenu--index-alist' for details."
5737 (let* ((root '(nil . nil
))
5742 (goto-char (point-min))
5743 (while (re-search-forward markdown-regex-header
(point-max) t
)
5744 (unless (or (markdown-code-block-at-point-p)
5745 (and (match-beginning 3)
5746 (get-text-property (match-beginning 3) 'markdown-yaml-metadata-end
)))
5748 ((match-string-no-properties 2) ;; level 1 setext
5750 (push (list :heading
(match-string-no-properties 1)
5751 :point
(match-beginning 1)
5753 ((match-string-no-properties 3) ;; level 2 setext
5754 (setq min-level
(min min-level
2))
5755 (push (list :heading
(match-string-no-properties 1)
5756 :point
(match-beginning 1)
5757 :level
(- 2 (1- min-level
))) headers
))
5758 ((setq hashes
(markdown-trim-whitespace
5759 (match-string-no-properties 4)))
5760 (setq min-level
(min min-level
(length hashes
)))
5761 (push (list :heading
(match-string-no-properties 5)
5762 :point
(match-beginning 4)
5763 :level
(- (length hashes
) (1- min-level
))) headers
)))))
5764 (cl-loop with cur-level
= 0
5765 with cur-alist
= nil
5766 with empty-heading
= "-"
5767 with self-heading
= "."
5768 for header in
(reverse headers
)
5769 for level
= (plist-get header
:level
)
5771 (let ((alist (list (cons (plist-get header
:heading
) (plist-get header
:point
)))))
5773 ((= cur-level level
) ; new sibling
5774 (setcdr cur-alist alist
)
5775 (setq cur-alist alist
))
5776 ((< cur-level level
) ; first child
5777 (dotimes (_ (- level cur-level
1))
5778 (setq alist
(list (cons empty-heading alist
))))
5780 (let* ((parent (car cur-alist
))
5781 (self-pos (cdr parent
)))
5782 (setcdr parent
(cons (cons self-heading self-pos
) alist
)))
5783 (setcdr root alist
)) ; primogenitor
5784 (setq cur-alist alist
)
5785 (setq cur-level level
))
5786 (t ; new sibling of an ancestor
5787 (let ((sibling-alist (last (cdr root
))))
5788 (dotimes (_ (1- level
))
5789 (setq sibling-alist
(last (cdar sibling-alist
))))
5790 (setcdr sibling-alist alist
)
5791 (setq cur-alist alist
))
5792 (setq cur-level level
)))))
5793 (setq root
(copy-tree root
))
5795 (let ((fn (markdown-get-defined-footnotes)))
5796 (if (or (zerop (length fn
))
5797 (null markdown-add-footnotes-to-imenu
))
5799 (nconc (cdr root
) (list (cons "Footnotes" fn
))))))))
5801 (defun markdown-imenu-create-flat-index ()
5802 "Create and return a flat imenu index alist for the current buffer.
5803 See `imenu-create-index-function' and `imenu--index-alist' for details."
5804 (let* ((empty-heading "-") index heading pos
)
5807 (goto-char (point-min))
5808 (while (re-search-forward markdown-regex-header
(point-max) t
)
5809 (when (and (not (markdown-code-block-at-point-p (line-beginning-position)))
5810 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin
)))
5812 ((setq heading
(match-string-no-properties 1))
5813 (setq pos
(match-beginning 1)))
5814 ((setq heading
(match-string-no-properties 5))
5815 (setq pos
(match-beginning 4))))
5816 (or (> (length heading
) 0)
5817 (setq heading empty-heading
))
5818 (setq index
(append index
(list (cons heading pos
))))))
5820 (when markdown-add-footnotes-to-imenu
5821 (nconc index
(markdown-get-defined-footnotes)))
5825 ;;; References ================================================================
5827 (defun markdown-reference-goto-definition ()
5828 "Jump to the definition of the reference at point or create it."
5830 (when (thing-at-point-looking-at markdown-regex-link-reference
)
5831 (let* ((text (match-string-no-properties 3))
5832 (reference (match-string-no-properties 6))
5833 (target (downcase (if (string= reference
"") text reference
)))
5834 (loc (cadr (save-match-data (markdown-reference-definition target
)))))
5837 (goto-char (match-beginning 0))
5838 (markdown-insert-reference-definition target
)))))
5840 (defun markdown-reference-find-links (reference)
5841 "Return a list of all links for REFERENCE.
5842 REFERENCE should not include the surrounding square brackets.
5843 Elements of the list have the form (text start line), where
5844 text is the link text, start is the location at the beginning of
5845 the link, and line is the line number on which the link appears."
5846 (let* ((ref-quote (regexp-quote reference
))
5847 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
5848 ref-quote ref-quote
))
5851 (goto-char (point-min))
5852 (while (re-search-forward regexp nil t
)
5853 (let* ((text (or (match-string-no-properties 1)
5854 (match-string-no-properties 2)))
5855 (start (match-beginning 0))
5856 (line (markdown-line-number-at-pos)))
5857 (cl-pushnew (list text start line
) links
:test
#'equal
))))
5860 (defmacro markdown-for-all-refs
(f)
5863 (goto-char (point-min))
5865 (re-search-forward markdown-regex-link-reference nil t
)
5866 (let* ((text (match-string-no-properties 3))
5867 (reference (match-string-no-properties 6))
5868 (target (downcase (if (string= reference
"") text reference
))))
5869 (,f text target result
))))
5872 (defmacro markdown-collect-always
(_ target result
)
5873 `(cl-pushnew ,target
,result
:test
#'equal
))
5875 (defmacro markdown-collect-undefined
(text target result
)
5876 `(unless (markdown-reference-definition target
)
5877 (let ((entry (assoc ,target
,result
)))
5880 (cons ,target
(list (cons ,text
(markdown-line-number-at-pos))))
5881 ,result
:test
#'equal
)
5883 (append (cdr entry
) (list (cons ,text
(markdown-line-number-at-pos)))))))))
5885 (defun markdown-get-all-refs ()
5886 "Return a list of all Markdown references."
5887 (markdown-for-all-refs markdown-collect-always
))
5889 (defun markdown-get-undefined-refs ()
5890 "Return a list of undefined Markdown references.
5891 Result is an alist of pairs (reference . occurrences), where
5892 occurrences is itself another alist of pairs (label . line-number).
5893 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
5894 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
5895 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
5896 (markdown-for-all-refs markdown-collect-undefined
))
5898 (defun markdown-get-unused-refs ()
5901 (markdown-get-defined-references) (markdown-get-all-refs)
5902 :test
(lambda (e1 e2
) (equal (car e1
) e2
)))
5905 (defmacro defun-markdown-buffer
(name docstring
)
5906 "Define a function to name and return a buffer.
5908 By convention, NAME must be a name of a string constant with
5909 %buffer% placeholder used to name the buffer, and will also be
5910 used as a name of the function defined.
5912 DOCSTRING will be used as the first part of the docstring."
5913 `(defun ,name
(&optional buffer-name
)
5914 ,(concat docstring
"\n\nBUFFER-NAME is the name of the main buffer being visited.")
5915 (or buffer-name
(setq buffer-name
(buffer-name)))
5916 (let ((refbuf (get-buffer-create (replace-regexp-in-string
5917 "%buffer%" buffer-name
5919 (with-current-buffer refbuf
5921 (View-exit-and-edit))
5922 (use-local-map button-buffer-map
)
5926 (defconst markdown-reference-check-buffer
5927 "*Undefined references for %buffer%*"
5928 "Pattern for name of buffer for listing undefined references.
5929 The string %buffer% will be replaced by the corresponding
5930 `markdown-mode' buffer name.")
5932 (defun-markdown-buffer
5933 markdown-reference-check-buffer
5934 "Name and return buffer for reference checking.")
5936 (defconst markdown-unused-references-buffer
5937 "*Unused references for %buffer%*"
5938 "Pattern for name of buffer for listing unused references.
5939 The string %buffer% will be replaced by the corresponding
5940 `markdown-mode' buffer name.")
5942 (defun-markdown-buffer
5943 markdown-unused-references-buffer
5944 "Name and return buffer for unused reference checking.")
5946 (defconst markdown-reference-links-buffer
5947 "*Reference links for %buffer%*"
5948 "Pattern for name of buffer for listing references.
5949 The string %buffer% will be replaced by the corresponding buffer name.")
5951 (defun-markdown-buffer
5952 markdown-reference-links-buffer
5953 "Name, setup, and return a buffer for listing links.")
5955 ;; Add an empty Markdown reference definition to buffer
5956 ;; specified in the 'target-buffer property. The reference name is
5957 ;; the button's label.
5958 (define-button-type 'markdown-undefined-reference-button
5959 'help-echo
"mouse-1, RET: create definition for undefined reference"
5963 (let ((buffer (button-get b
'target-buffer
))
5964 (line (button-get b
'target-line
))
5965 (label (button-label b
)))
5966 (switch-to-buffer-other-window buffer
)
5967 (goto-char (point-min))
5969 (markdown-insert-reference-definition label
)
5970 (markdown-check-refs t
))))
5972 ;; Jump to line in buffer specified by 'target-buffer property.
5973 ;; Line number is button's 'target-line property.
5974 (define-button-type 'markdown-goto-line-button
5975 'help-echo
"mouse-1, RET: go to line"
5979 (switch-to-buffer-other-window (button-get b
'target-buffer
))
5980 ;; use call-interactively to silence compiler
5981 (let ((current-prefix-arg (button-get b
'target-line
)))
5982 (call-interactively 'goto-line
))))
5984 ;; Kill a line in buffer specified by 'target-buffer property.
5985 ;; Line number is button's 'target-line property.
5986 (define-button-type 'markdown-kill-line-button
5987 'help-echo
"mouse-1, RET: kill line"
5991 (switch-to-buffer-other-window (button-get b
'target-buffer
))
5992 ;; use call-interactively to silence compiler
5993 (let ((current-prefix-arg (button-get b
'target-line
)))
5994 (call-interactively 'goto-line
))
5996 (markdown-unused-refs t
)))
5998 ;; Jumps to a particular link at location given by 'target-char
5999 ;; property in buffer given by 'target-buffer property.
6000 (define-button-type 'markdown-location-button
6001 'help-echo
"mouse-1, RET: jump to location of link"
6005 (let ((target (button-get b
'target-buffer
))
6006 (loc (button-get b
'target-char
)))
6007 (kill-buffer-and-window)
6008 (switch-to-buffer target
)
6011 (defun markdown-insert-undefined-reference-button (reference oldbuf
)
6012 "Insert a button for creating REFERENCE in buffer OLDBUF.
6013 REFERENCE should be a list of the form (reference . occurrences),
6014 as returned by `markdown-get-undefined-refs'."
6015 (let ((label (car reference
)))
6016 ;; Create a reference button
6017 (insert-button label
6018 :type
'markdown-undefined-reference-button
6019 'target-buffer oldbuf
6020 'target-line
(cdr (car (cdr reference
))))
6022 (dolist (occurrence (cdr reference
))
6023 (let ((line (cdr occurrence
)))
6024 ;; Create a line number button
6025 (insert-button (number-to-string line
)
6026 :type
'markdown-goto-line-button
6027 'target-buffer oldbuf
6034 (defun markdown-insert-unused-reference-button (reference oldbuf
)
6035 "Insert a button for creating REFERENCE in buffer OLDBUF.
6036 REFERENCE must be a pair of (ref . line-number)."
6037 (let ((label (car reference
))
6038 (line (cdr reference
)))
6039 ;; Create a reference button
6040 (insert-button label
6041 :type
'markdown-goto-line-button
6043 'target-buffer oldbuf
6045 (insert (format " (%d) [" line
))
6047 :type
'markdown-kill-line-button
6049 'target-buffer oldbuf
6054 (defun markdown-insert-link-button (link oldbuf
)
6055 "Insert a button for jumping to LINK in buffer OLDBUF.
6056 LINK should be a list of the form (text char line) containing
6057 the link text, location, and line number."
6058 (let ((label (cl-first link
))
6059 (char (cl-second link
))
6060 (line (cl-third link
)))
6061 ;; Create a reference button
6062 (insert-button label
6063 :type
'markdown-location-button
6064 'target-buffer oldbuf
6066 (insert (format " (line %d)\n" line
))))
6068 (defun markdown-reference-goto-link (&optional reference
)
6069 "Jump to the location of the first use of REFERENCE."
6072 (if (thing-at-point-looking-at markdown-regex-reference-definition
)
6073 (setq reference
(match-string-no-properties 2))
6074 (user-error "No reference definition at point")))
6075 (let ((links (markdown-reference-find-links reference
)))
6076 (cond ((= (length links
) 1)
6077 (goto-char (cadr (car links
))))
6078 ((> (length links
) 1)
6079 (let ((oldbuf (current-buffer))
6080 (linkbuf (markdown-reference-links-buffer)))
6081 (with-current-buffer linkbuf
6082 (insert "Links using reference " reference
":\n\n")
6083 (dolist (link (reverse links
))
6084 (markdown-insert-link-button link oldbuf
)))
6085 (view-buffer-other-window linkbuf
)
6086 (goto-char (point-min))
6089 (error "No links for reference %s" reference
)))))
6091 (defmacro defun-markdown-ref-checker
6092 (name docstring checker-function buffer-function none-message buffer-header insert-reference
)
6093 "Define a function NAME acting on result of CHECKER-FUNCTION.
6095 DOCSTRING is used as a docstring for the defined function.
6097 BUFFER-FUNCTION should name and return an auxiliary buffer to put
6100 NONE-MESSAGE is used when CHECKER-FUNCTION returns no results.
6102 BUFFER-HEADER is put into the auxiliary buffer first, followed by
6103 calling INSERT-REFERENCE for each element in the list returned by
6105 `(defun ,name
(&optional silent
)
6108 "\n\nIf SILENT is non-nil, do not message anything when no
6109 such references found.")
6111 (unless (derived-mode-p 'markdown-mode
)
6112 (user-error "Not available in current mode"))
6113 (let ((oldbuf (current-buffer))
6114 (refs (,checker-function
))
6115 (refbuf (,buffer-function
)))
6119 (message ,none-message
))
6120 (kill-buffer refbuf
))
6121 (with-current-buffer refbuf
6122 (insert ,buffer-header
)
6124 (,insert-reference ref oldbuf
))
6125 (view-buffer-other-window refbuf
)
6126 (goto-char (point-min))
6127 (forward-line 2))))))
6129 (defun-markdown-ref-checker
6131 "Show all undefined Markdown references in current `markdown-mode' buffer.
6133 Links which have empty reference definitions are considered to be
6135 markdown-get-undefined-refs
6136 markdown-reference-check-buffer
6137 "No undefined references found"
6138 "The following references are undefined:\n\n"
6139 markdown-insert-undefined-reference-button
)
6142 (defun-markdown-ref-checker
6143 markdown-unused-refs
6144 "Show all unused Markdown references in current `markdown-mode' buffer."
6145 markdown-get-unused-refs
6146 markdown-unused-references-buffer
6147 "No unused references found"
6148 "The following references are unused:\n\n"
6149 markdown-insert-unused-reference-button
)
6153 ;;; Lists =====================================================================
6155 (defun markdown-insert-list-item (&optional arg
)
6156 "Insert a new list item.
6157 If the point is inside unordered list, insert a bullet mark. If
6158 the point is inside ordered list, insert the next number followed
6159 by a period. Use the previous list item to determine the amount
6160 of whitespace to place before and after list markers.
6162 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
6163 decrease the indentation by one level.
6165 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
6166 increase the indentation by one level."
6168 (let (bounds cur-indent marker indent new-indent new-loc
)
6170 ;; Look for a list item on current or previous non-blank line
6172 (while (and (not (setq bounds
(markdown-cur-list-item-bounds)))
6174 (markdown-cur-line-blank-p))
6177 (cond ((save-excursion
6178 (skip-chars-backward " \t")
6179 (looking-at-p markdown-regex-list
))
6183 ((not (markdown-cur-line-blank-p))
6185 (setq new-loc
(point)))
6186 ;; Look ahead for a list item on next non-blank line
6189 (while (and (null bounds
)
6191 (markdown-cur-line-blank-p))
6193 (setq bounds
(markdown-cur-list-item-bounds))))
6195 (setq new-loc
(point))
6196 (unless (markdown-cur-line-blank-p)
6199 ;; When not in a list, start a new unordered one
6201 (unless (markdown-cur-line-blank-p)
6203 (insert markdown-unordered-list-item-prefix
))
6204 ;; Compute indentation and marker for new list item
6205 (setq cur-indent
(nth 2 bounds
))
6206 (setq marker
(nth 4 bounds
))
6207 ;; If current item is a GFM checkbox, insert new unchecked checkbox.
6208 (when (nth 5 bounds
)
6211 (replace-regexp-in-string "[Xx]" " " (nth 5 bounds
)))))
6213 ;; Dedent: decrement indentation, find previous marker.
6215 (setq indent
(max (- cur-indent markdown-list-indent-width
) 0))
6218 (goto-char (nth 0 bounds
))
6219 (when (markdown-up-list)
6220 (markdown-cur-list-item-bounds)))))
6222 (setq marker
(nth 4 prev-bounds
)))))
6223 ;; Indent: increment indentation by 4, use same marker.
6224 ((= arg
16) (setq indent
(+ cur-indent markdown-list-indent-width
)))
6225 ;; Same level: keep current indentation and marker.
6226 (t (setq indent cur-indent
)))
6227 (setq new-indent
(make-string indent
32))
6231 ((string-match-p "[0-9]" marker
)
6232 (if (= arg
16) ;; starting a new column indented one more level
6233 (insert (concat new-indent
"1. "))
6234 ;; Don't use previous match-data
6235 (set-match-data nil
)
6236 ;; travel up to the last item and pick the correct number. If
6237 ;; the argument was nil, "new-indent = cur-indent" is the same,
6238 ;; so we don't need special treatment. Neat.
6240 (while (and (not (looking-at (concat new-indent
"\\([0-9]+\\)\\(\\.[ \t]*\\)")))
6241 (>= (forward-line -
1) 0))))
6242 (let* ((old-prefix (match-string 1))
6243 (old-spacing (match-string 2))
6244 (new-prefix (if (and old-prefix markdown-ordered-list-enumeration
)
6245 (int-to-string (1+ (string-to-number old-prefix
)))
6247 (space-adjust (- (length old-prefix
) (length new-prefix
)))
6248 (new-spacing (if (and (match-string 2)
6249 (not (string-match-p "\t" old-spacing
))
6251 (> space-adjust
(- 1 (length (match-string 2)))))
6252 (substring (match-string 2) 0 space-adjust
)
6253 (or old-spacing
". "))))
6254 (insert (concat new-indent new-prefix new-spacing
)))))
6255 ;; Unordered list, GFM task list, or ordered list with hash mark
6256 ((string-match-p "[\\*\\+-]\\|#\\." marker
)
6257 (insert new-indent marker
))))
6258 ;; Propertize the newly inserted list item now
6259 (markdown-syntax-propertize-list-items (line-beginning-position) (line-end-position)))))
6261 (defun markdown-move-list-item-up ()
6262 "Move the current list item up in the list when possible.
6263 In nested lists, move child items with the parent item."
6266 (when (setq cur
(markdown-cur-list-item-bounds))
6268 (goto-char (nth 0 cur
))
6269 (if (markdown-prev-list-item (nth 3 cur
))
6271 (setq prev
(markdown-cur-list-item-bounds))
6274 (transpose-regions (nth 0 prev
) (nth 1 prev
)
6275 (nth 0 cur
) (nth 1 cur
) t
)
6276 (goto-char (+ (nth 0 prev
) (- old
(nth 0 cur
)))))
6277 ;; Catch error in case regions overlap.
6278 (error (goto-char old
))))
6281 (defun markdown-move-list-item-down ()
6282 "Move the current list item down in the list when possible.
6283 In nested lists, move child items with the parent item."
6286 (when (setq cur
(markdown-cur-list-item-bounds))
6288 (if (markdown-next-list-item (nth 3 cur
))
6290 (setq next
(markdown-cur-list-item-bounds))
6293 (transpose-regions (nth 0 cur
) (nth 1 cur
)
6294 (nth 0 next
) (nth 1 next
) nil
)
6295 (goto-char (+ old
(- (nth 1 next
) (nth 1 cur
)))))
6296 ;; Catch error in case regions overlap.
6297 (error (goto-char old
))))
6300 (defun markdown-demote-list-item (&optional bounds
)
6301 "Indent (or demote) the current list item.
6302 Optionally, BOUNDS of the current list item may be provided if available.
6303 In nested lists, demote child items as well."
6305 (when (or bounds
(setq bounds
(markdown-cur-list-item-bounds)))
6307 (let* ((item-start (set-marker (make-marker) (nth 0 bounds
)))
6308 (item-end (set-marker (make-marker) (nth 1 bounds
)))
6309 (list-start (progn (markdown-beginning-of-list)
6310 (set-marker (make-marker) (point))))
6311 (list-end (progn (markdown-end-of-list)
6312 (set-marker (make-marker) (point)))))
6313 (goto-char item-start
)
6314 (while (< (point) item-end
)
6315 (unless (markdown-cur-line-blank-p)
6316 (insert (make-string markdown-list-indent-width ?
)))
6318 (markdown-syntax-propertize-list-items list-start list-end
)))))
6320 (defun markdown-promote-list-item (&optional bounds
)
6321 "Unindent (or promote) the current list item.
6322 Optionally, BOUNDS of the current list item may be provided if available.
6323 In nested lists, demote child items as well."
6325 (when (or bounds
(setq bounds
(markdown-cur-list-item-bounds)))
6328 (let ((item-start (set-marker (make-marker) (nth 0 bounds
)))
6329 (item-end (set-marker (make-marker) (nth 1 bounds
)))
6330 (list-start (progn (markdown-beginning-of-list)
6331 (set-marker (make-marker) (point))))
6332 (list-end (progn (markdown-end-of-list)
6333 (set-marker (make-marker) (point))))
6335 (goto-char item-start
)
6336 (when (looking-at (format "^[ ]\\{1,%d\\}"
6337 markdown-list-indent-width
))
6338 (setq num
(- (match-end 0) (match-beginning 0)))
6339 (setq regexp
(format "^[ ]\\{1,%d\\}" num
))
6340 (while (and (< (point) item-end
)
6341 (re-search-forward regexp item-end t
))
6342 (replace-match "" nil nil
)
6344 (markdown-syntax-propertize-list-items list-start list-end
)))))))
6346 (defun markdown-cleanup-list-numbers-level (&optional pfx prev-item
)
6347 "Update the numbering for level PFX (as a string of spaces) and PREV-ITEM.
6348 PREV-ITEM is width of previous-indentation and list number
6350 Assume that the previously found match was for a numbered item in
6358 (while (and continue
(not (eobp)))
6361 ((looking-at "^\\(\\([\s-]*\\)[0-9]+\\)\\. ")
6362 (setq cpfx
(match-string-no-properties 2))
6363 (setq cur-item
(match-string-no-properties 1)) ;; indentation and list marker
6365 ((or (= (length cpfx
) (length pfx
))
6366 (= (length cur-item
) (length prev-item
)))
6369 (if (not markdown-ordered-list-enumeration
)
6372 (concat pfx
(number-to-string idx
) ". "))))
6375 ((< (length pfx
) (length cpfx
))
6376 (setq sep
(markdown-cleanup-list-numbers-level cpfx cur-item
))
6381 (setq continue nil
))))
6383 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
6384 (setq cpfx
(match-string-no-properties 1))
6386 ;; reset if separated before
6387 ((string= cpfx pfx
) (when sep
(setq idx
0)))
6390 (setq continue nil
))))
6395 (setq continue
(= (forward-line) 0))))
6398 (defun markdown-cleanup-list-numbers ()
6399 "Update the numbering of ordered lists."
6402 (goto-char (point-min))
6403 (markdown-cleanup-list-numbers-level "")))
6406 ;;; Movement ==================================================================
6408 (defun markdown-beginning-of-defun (&optional arg
)
6409 "`beginning-of-defun-function' for Markdown.
6410 This is used to find the beginning of the defun and should behave
6411 like ‘beginning-of-defun’, returning non-nil if it found the
6412 beginning of a defun. It moves the point backward, right before a
6413 heading which defines a defun. When ARG is non-nil, repeat that
6414 many times. When ARG is negative, move forward to the ARG-th
6416 (or arg
(setq arg
1))
6417 (when (< arg
0) (end-of-line))
6418 ;; Adjust position for setext headings.
6419 (when (and (thing-at-point-looking-at markdown-regex-header-setext
)
6420 (not (= (point) (match-beginning 0)))
6421 (not (markdown-code-block-at-point-p)))
6422 (goto-char (match-end 0)))
6424 ;; Move backward with positive argument.
6425 (while (and (not (bobp)) (> arg
0))
6427 (while (and (not found
)
6429 (re-search-backward markdown-regex-header nil
'move
))
6430 (markdown-code-block-at-pos (match-beginning 0))
6431 (setq found
(match-beginning 0)))
6432 (setq arg
(1- arg
)))
6433 ;; Move forward with negative argument.
6434 (while (and (not (eobp)) (< arg
0))
6436 (while (and (not found
)
6438 (re-search-forward markdown-regex-header nil
'move
))
6439 (markdown-code-block-at-pos (match-beginning 0))
6440 (setq found
(match-beginning 0)))
6441 (setq arg
(1+ arg
)))
6446 (defun markdown-end-of-defun ()
6447 "`end-of-defun-function’ for Markdown.
6448 This is used to find the end of the defun at point.
6449 It is called with no argument, right after calling ‘beginning-of-defun-raw’,
6450 so it can assume that point is at the beginning of the defun body.
6451 It should move point to the first position after the defun."
6452 (or (eobp) (forward-char 1))
6454 (while (and (not found
)
6456 (re-search-forward markdown-regex-header nil
'move
))
6457 (when (not (markdown-code-block-at-pos (match-beginning 0)))
6458 (setq found
(match-beginning 0))))
6461 (skip-syntax-backward "-"))))
6463 (defun markdown-beginning-of-text-block ()
6464 "Move backward to previous beginning of a plain text block.
6465 This function simply looks for blank lines without considering
6466 the surrounding context in light of Markdown syntax. For that, see
6467 `markdown-backward-block'."
6469 (let ((start (point)))
6470 (if (re-search-backward markdown-regex-block-separator nil t
)
6471 (goto-char (match-end 0))
6472 (goto-char (point-min)))
6473 (when (and (= start
(point)) (not (bobp)))
6475 (if (re-search-backward markdown-regex-block-separator nil t
)
6476 (goto-char (match-end 0))
6477 (goto-char (point-min))))))
6479 (defun markdown-end-of-text-block ()
6480 "Move forward to next beginning of a plain text block.
6481 This function simply looks for blank lines without considering
6482 the surrounding context in light of Markdown syntax. For that, see
6483 `markdown-forward-block'."
6486 (skip-chars-forward " \t\n")
6487 (when (= (point) (point-min))
6489 (if (re-search-forward markdown-regex-block-separator nil t
)
6490 (goto-char (match-end 0))
6491 (goto-char (point-max)))
6492 (skip-chars-backward " \t\n")
6495 (defun markdown-backward-paragraph (&optional arg
)
6496 "Move the point to the start of the current paragraph.
6497 With argument ARG, do it ARG times; a negative argument ARG = -N
6498 means move forward N blocks."
6500 (or arg
(setq arg
1))
6502 (markdown-forward-paragraph (- arg
))
6504 ;; Skip over whitespace in between paragraphs when moving backward.
6505 (skip-chars-backward " \t\n")
6507 ;; Skip over code block endings.
6508 (when (markdown-range-properties-exist
6509 (line-beginning-position) (line-end-position)
6510 '(markdown-gfm-block-end
6511 markdown-tilde-fence-end
))
6513 ;; Skip over blank lines inside blockquotes.
6514 (while (and (not (eobp))
6515 (looking-at markdown-regex-blockquote
)
6516 (= (length (match-string 3)) 0))
6518 ;; Proceed forward based on the type of block of paragraph.
6522 ((looking-at markdown-regex-blockquote
)
6523 (while (and (not (bobp))
6524 (looking-at markdown-regex-blockquote
)
6525 (> (length (match-string 3)) 0)) ;; not blank
6529 ((setq bounds
(markdown-cur-list-item-bounds))
6530 (goto-char (nth 0 bounds
)))
6533 (while (and (not (bobp))
6535 (not (markdown-cur-line-blank-p))
6536 (not (looking-at markdown-regex-blockquote
))
6537 (not (markdown-range-properties-exist
6538 (line-beginning-position) (line-end-position)
6539 '(markdown-gfm-block-end
6540 markdown-tilde-fence-end
))))
6541 (setq skip
(markdown-range-properties-exist
6542 (line-beginning-position) (line-end-position)
6543 '(markdown-gfm-block-begin
6544 markdown-tilde-fence-begin
)))
6547 (forward-line 1))))))))
6549 (defun markdown-forward-paragraph (&optional arg
)
6550 "Move forward to the next end of a paragraph.
6551 With argument ARG, do it ARG times; a negative argument ARG = -N
6552 means move backward N blocks."
6554 (or arg
(setq arg
1))
6556 (markdown-backward-paragraph (- arg
))
6558 ;; Skip whitespace in between paragraphs.
6559 (when (markdown-cur-line-blank-p)
6560 (skip-syntax-forward "-")
6561 (beginning-of-line))
6562 ;; Proceed forward based on the type of block.
6566 ((looking-at markdown-regex-blockquote
)
6567 ;; Skip over blank lines inside blockquotes.
6568 (while (and (not (eobp))
6569 (looking-at markdown-regex-blockquote
)
6570 (= (length (match-string 3)) 0))
6572 ;; Move to end of quoted text block
6573 (while (and (not (eobp))
6574 (looking-at markdown-regex-blockquote
)
6575 (> (length (match-string 3)) 0)) ;; not blank
6578 ((and (markdown-cur-list-item-bounds)
6579 (setq bounds
(markdown-next-list-item-bounds)))
6580 (goto-char (nth 0 bounds
)))
6584 (while (and (not (eobp))
6586 (not (markdown-cur-line-blank-p))
6587 (not (looking-at markdown-regex-blockquote
))
6588 (not (markdown-range-properties-exist
6589 (line-beginning-position) (line-end-position)
6590 '(markdown-gfm-block-begin
6591 markdown-tilde-fence-begin
))))
6592 (setq skip
(markdown-range-properties-exist
6593 (line-beginning-position) (line-end-position)
6594 '(markdown-gfm-block-end
6595 markdown-tilde-fence-end
)))
6596 (forward-line))))))))
6598 (defun markdown-backward-block (&optional arg
)
6599 "Move the point to the start of the current Markdown block.
6600 Moves across complete code blocks, list items, and blockquotes,
6601 but otherwise stops at blank lines, headers, and horizontal
6602 rules. With argument ARG, do it ARG times; a negative argument
6603 ARG = -N means move forward N blocks."
6605 (or arg
(setq arg
1))
6607 (markdown-forward-block (- arg
))
6609 ;; Skip over whitespace in between blocks when moving backward,
6610 ;; unless at a block boundary with no whitespace.
6611 (skip-syntax-backward "-")
6613 ;; Proceed forward based on the type of block.
6616 ((and (markdown-code-block-at-pos (point)) ;; this line
6617 (markdown-code-block-at-pos (line-beginning-position 0))) ;; previous line
6619 (while (and (markdown-code-block-at-point-p) (not (bobp)))
6623 ((markdown-heading-at-point)
6624 (goto-char (match-beginning 0)))
6626 ((looking-at markdown-regex-hr
))
6628 ((looking-at markdown-regex-blockquote
)
6630 (while (and (looking-at markdown-regex-blockquote
)
6635 ((markdown-cur-list-item-bounds)
6636 (markdown-beginning-of-list))
6639 ;; Move forward in case it is a one line regular paragraph.
6640 (unless (markdown-next-line-blank-p)
6642 (unless (markdown-prev-line-blank-p)
6643 (markdown-backward-paragraph)))))))
6645 (defun markdown-forward-block (&optional arg
)
6646 "Move forward to the next end of a Markdown block.
6647 Moves across complete code blocks, list items, and blockquotes,
6648 but otherwise stops at blank lines, headers, and horizontal
6649 rules. With argument ARG, do it ARG times; a negative argument
6650 ARG = -N means move backward N blocks."
6652 (or arg
(setq arg
1))
6654 (markdown-backward-block (- arg
))
6656 ;; Skip over whitespace in between blocks when moving forward.
6657 (if (markdown-cur-line-blank-p)
6658 (skip-syntax-forward "-")
6659 (beginning-of-line))
6660 ;; Proceed forward based on the type of block.
6663 ((markdown-code-block-at-point-p)
6665 (while (and (markdown-code-block-at-point-p) (not (eobp)))
6668 ((looking-at markdown-regex-header
)
6669 (goto-char (or (match-end 4) (match-end 2) (match-end 3)))
6672 ((looking-at markdown-regex-hr
)
6675 ((looking-at markdown-regex-blockquote
)
6677 (while (and (looking-at markdown-regex-blockquote
) (not (eobp)))
6680 ((markdown-cur-list-item-bounds)
6681 (markdown-end-of-list)
6684 (t (markdown-forward-paragraph))))
6685 (skip-syntax-backward "-")
6689 (defun markdown-backward-page (&optional count
)
6690 "Move backward to boundary of the current toplevel section.
6691 With COUNT, repeat, or go forward if negative."
6693 (or count
(setq count
1))
6695 (markdown-forward-page (- count
))
6696 (skip-syntax-backward "-")
6697 (or (markdown-back-to-heading-over-code-block t t
)
6698 (goto-char (point-min)))
6699 (when (looking-at markdown-regex-header
)
6700 (let ((level (markdown-outline-level)))
6701 (when (> level
1) (markdown-up-heading level
))
6704 (markdown-backward-same-level (1- count
))
6705 (error (goto-char (point-min)))))))))
6707 (defun markdown-forward-page (&optional count
)
6708 "Move forward to boundary of the current toplevel section.
6709 With COUNT, repeat, or go backward if negative."
6711 (or count
(setq count
1))
6713 (markdown-backward-page (- count
))
6714 (if (markdown-back-to-heading-over-code-block t t
)
6715 (let ((level (markdown-outline-level)))
6716 (when (> level
1) (markdown-up-heading level
))
6718 (markdown-forward-same-level count
)
6719 (error (goto-char (point-max)))))
6720 (markdown-next-visible-heading 1))))
6722 (defun markdown-next-link ()
6723 "Jump to next inline, reference, or wiki link.
6724 If successful, return point. Otherwise, return nil.
6725 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
6727 (let ((opoint (point)))
6728 (when (or (markdown-link-p) (markdown-wiki-link-p))
6729 ;; At a link already, move past it.
6730 (goto-char (+ (match-end 0) 1)))
6731 ;; Search for the next wiki link and move to the beginning.
6732 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t
)
6733 (markdown-code-block-at-point-p)
6734 (< (point) (point-max))))
6735 (if (and (not (eq (point) opoint
))
6736 (or (markdown-link-p) (markdown-wiki-link-p)))
6737 ;; Group 1 will move past non-escape character in wiki link regexp.
6738 ;; Go to beginning of group zero for all other link types.
6739 (goto-char (or (match-beginning 1) (match-beginning 0)))
6743 (defun markdown-previous-link ()
6744 "Jump to previous wiki link.
6745 If successful, return point. Otherwise, return nil.
6746 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
6748 (let ((opoint (point)))
6749 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t
)
6750 (markdown-code-block-at-point-p)
6751 (> (point) (point-min))))
6752 (if (and (not (eq (point) opoint
))
6753 (or (markdown-link-p) (markdown-wiki-link-p)))
6754 (goto-char (or (match-beginning 1) (match-beginning 0)))
6759 ;;; Outline ===================================================================
6761 (defun markdown-move-heading-common (move-fn &optional arg adjust
)
6762 "Wrapper for `outline-mode' functions to skip false positives.
6763 MOVE-FN is a function and ARG is its argument. For example,
6764 headings inside preformatted code blocks may match
6765 `outline-regexp' but should not be considered as headings.
6766 When ADJUST is non-nil, adjust the point for interactive calls
6767 to avoid leaving the point at invisible markup. This adjustment
6768 generally should only be done for interactive calls, since other
6769 functions may expect the point to be at the beginning of the
6770 regular expression."
6771 (let ((prev -
1) (start (point)))
6772 (if arg
(funcall move-fn arg
) (funcall move-fn
))
6773 (while (and (/= prev
(point)) (markdown-code-block-at-point-p))
6775 (if arg
(funcall move-fn arg
) (funcall move-fn
)))
6776 ;; Adjust point for setext headings and invisible text.
6778 (when (and adjust
(thing-at-point-looking-at markdown-regex-header
))
6779 (if markdown-hide-markup
6780 ;; Move to beginning of heading text if markup is hidden.
6781 (goto-char (or (match-beginning 1) (match-beginning 5)))
6782 ;; Move to beginning of markup otherwise.
6783 (goto-char (or (match-beginning 1) (match-beginning 4))))))
6784 (if (= (point) start
) nil
(point))))
6786 (defun markdown-next-visible-heading (arg)
6787 "Move to the next visible heading line of any level.
6788 With argument, repeats or can move backward if negative. ARG is
6789 passed to `outline-next-visible-heading'."
6791 (markdown-move-heading-common #'outline-next-visible-heading arg
'adjust
))
6793 (defun markdown-previous-visible-heading (arg)
6794 "Move to the previous visible heading line of any level.
6795 With argument, repeats or can move backward if negative. ARG is
6796 passed to `outline-previous-visible-heading'."
6798 (markdown-move-heading-common #'outline-previous-visible-heading arg
'adjust
))
6800 (defun markdown-next-heading ()
6801 "Move to the next heading line of any level."
6802 (markdown-move-heading-common #'outline-next-heading
))
6804 (defun markdown-previous-heading ()
6805 "Move to the previous heading line of any level."
6806 (markdown-move-heading-common #'outline-previous-heading
))
6808 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok no-error
)
6809 "Move back to the beginning of the previous heading.
6810 Returns t if the point is at a heading, the location if a heading
6811 was found, and nil otherwise.
6812 Only visible heading lines are considered, unless INVISIBLE-OK is
6813 non-nil. Throw an error if there is no previous heading unless
6814 NO-ERROR is non-nil.
6815 Leaves match data intact for `markdown-regex-header'."
6817 (or (and (markdown-heading-at-point)
6818 (not (markdown-code-block-at-point-p)))
6821 (while (and (not found
)
6822 (re-search-backward markdown-regex-header nil t
))
6823 (when (and (or invisible-ok
(not (outline-invisible-p)))
6824 (not (markdown-code-block-at-point-p)))
6825 (setq found
(point))))
6827 (unless no-error
(user-error "Before first heading"))
6828 (setq found
(point))))
6829 (when found
(goto-char found
)))))
6831 (defun markdown-forward-same-level (arg)
6832 "Move forward to the ARG'th heading at same level as this one.
6833 Stop at the first and last headings of a superior heading."
6835 (markdown-back-to-heading-over-code-block)
6836 (markdown-move-heading-common #'outline-forward-same-level arg
'adjust
))
6838 (defun markdown-backward-same-level (arg)
6839 "Move backward to the ARG'th heading at same level as this one.
6840 Stop at the first and last headings of a superior heading."
6842 (markdown-back-to-heading-over-code-block)
6844 (let ((point-to-move-to
6846 (markdown-move-heading-common #'outline-get-last-sibling nil
'adjust
))))
6847 (if point-to-move-to
6849 (goto-char point-to-move-to
)
6850 (setq arg
(1- arg
)))
6851 (user-error "No previous same-level heading")))))
6853 (defun markdown-up-heading (arg &optional interactive
)
6854 "Move to the visible heading line of which the present line is a subheading.
6855 With argument, move up ARG levels. When called interactively (or
6856 INTERACTIVE is non-nil), also push the mark."
6857 (interactive "p\np")
6858 (and interactive
(not (eq last-command
'markdown-up-heading
))
6860 (markdown-move-heading-common #'outline-up-heading arg
'adjust
))
6862 (defun markdown-back-to-heading (&optional invisible-ok
)
6863 "Move to previous heading line, or beg of this line if it's a heading.
6864 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
6866 (markdown-move-heading-common #'outline-back-to-heading invisible-ok
))
6868 (defalias 'markdown-end-of-heading
'outline-end-of-heading
)
6870 (defun markdown-on-heading-p ()
6871 "Return non-nil if point is on a heading line."
6872 (get-text-property (line-beginning-position) 'markdown-heading
))
6874 (defun markdown-end-of-subtree (&optional invisible-OK
)
6875 "Move to the end of the current subtree.
6876 Only visible heading lines are considered, unless INVISIBLE-OK is
6878 Derived from `org-end-of-subtree'."
6879 (markdown-back-to-heading invisible-OK
)
6881 (level (markdown-outline-level)))
6882 (while (and (not (eobp))
6883 (or first
(> (markdown-outline-level) level
)))
6885 (markdown-next-heading))
6886 (if (memq (preceding-char) '(?
\n ?\^M
))
6888 ;; Go to end of line before heading
6890 (if (memq (preceding-char) '(?
\n ?\^M
))
6891 ;; leave blank line before heading
6892 (forward-char -
1)))))
6895 (defun markdown-outline-fix-visibility ()
6896 "Hide any false positive headings that should not be shown.
6897 For example, headings inside preformatted code blocks may match
6898 `outline-regexp' but should not be shown as headings when cycling.
6899 Also, the ending --- line in metadata blocks appears to be a
6900 setext header, but should not be folded."
6902 (goto-char (point-min))
6903 ;; Unhide any false positives in metadata blocks
6904 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin
)
6905 (let ((body (progn (forward-line)
6906 (markdown-text-property-at-point
6907 'markdown-yaml-metadata-section
))))
6909 (let ((end (progn (goto-char (cl-second body
))
6910 (markdown-text-property-at-point
6911 'markdown-yaml-metadata-end
))))
6912 (outline-flag-region (point-min) (1+ (cl-second end
)) nil
)))))
6913 ;; Hide any false positives in code blocks
6914 (unless (outline-on-heading-p)
6915 (outline-next-visible-heading 1))
6916 (while (< (point) (point-max))
6917 (when (markdown-code-block-at-point-p)
6918 (outline-flag-region (1- (line-beginning-position)) (line-end-position) t
))
6919 (outline-next-visible-heading 1))))
6921 (defvar markdown-cycle-global-status
1)
6922 (defvar markdown-cycle-subtree-status nil
)
6924 (defun markdown-next-preface ()
6926 (while (and (not finish
) (re-search-forward (concat "\n\\(?:" outline-regexp
"\\)")
6928 (unless (markdown-code-block-at-point-p)
6929 (goto-char (match-beginning 0))
6931 (when (and (bolp) (or outline-blank-line
(eobp)) (not (bobp)))
6934 (defun markdown-show-entry ()
6936 (outline-back-to-heading t
)
6937 (outline-flag-region (1- (point))
6939 (markdown-next-preface)
6940 (if (= 1 (- (point-max) (point)))
6945 ;; This function was originally derived from `org-cycle' from org.el.
6946 (defun markdown-cycle (&optional arg
)
6947 "Visibility cycling for Markdown mode.
6948 This function is called with a `\\[universal-argument]' or if ARG is t, perform
6949 global visibility cycling. If the point is at an atx-style header, cycle
6950 visibility of the corresponding subtree. Otherwise, indent the current line
6951 or insert a tab, as appropriate, by calling `indent-for-tab-command'."
6958 ;; Move from overview to contents
6959 ((and (eq last-command this-command
)
6960 (eq markdown-cycle-global-status
2))
6961 (outline-hide-sublevels 1)
6962 (message "CONTENTS")
6963 (setq markdown-cycle-global-status
3)
6964 (markdown-outline-fix-visibility))
6965 ;; Move from contents to all
6966 ((and (eq last-command this-command
)
6967 (eq markdown-cycle-global-status
3))
6969 (message "SHOW ALL")
6970 (setq markdown-cycle-global-status
1))
6971 ;; Defaults to overview
6974 (message "OVERVIEW")
6975 (setq markdown-cycle-global-status
2)
6976 (markdown-outline-fix-visibility))))
6978 ;; At a heading: rotate between three different views
6979 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
6980 (markdown-back-to-heading)
6981 (let ((goal-column 0) eoh eol eos
)
6982 ;; Determine boundaries
6984 (markdown-back-to-heading)
6986 (beginning-of-line 2)
6987 (while (and (not (eobp)) ;; this is like `next-line'
6988 (get-char-property (1- (point)) 'invisible
))
6989 (beginning-of-line 2)) (setq eol
(point)))
6990 (markdown-end-of-heading) (setq eoh
(point))
6991 (markdown-end-of-subtree t
)
6992 (skip-chars-forward " \t\n")
6993 (beginning-of-line 1) ; in case this is an item
6994 (setq eos
(1- (point))))
6995 ;; Find out what to do next and set `this-command'
6997 ;; Nothing is hidden behind this heading
6999 (message "EMPTY ENTRY")
7000 (setq markdown-cycle-subtree-status nil
))
7001 ;; Entire subtree is hidden in one line: open it
7003 (markdown-show-entry)
7004 (outline-show-children)
7005 (message "CHILDREN")
7006 (setq markdown-cycle-subtree-status
'children
))
7007 ;; We just showed the children, now show everything.
7008 ((and (eq last-command this-command
)
7009 (eq markdown-cycle-subtree-status
'children
))
7010 (outline-show-subtree)
7012 (setq markdown-cycle-subtree-status
'subtree
))
7013 ;; Default action: hide the subtree.
7015 (outline-hide-subtree)
7017 (setq markdown-cycle-subtree-status
'folded
)))))
7019 ;; In a table, move forward by one cell
7020 ((markdown-table-at-point-p)
7021 (call-interactively #'markdown-table-forward-cell
))
7023 ;; Otherwise, indent as appropriate
7025 (indent-for-tab-command))))
7027 (defun markdown-shifttab ()
7028 "Handle S-TAB keybinding based on context.
7029 When in a table, move backward one cell.
7030 Otherwise, cycle global heading visibility by calling
7031 `markdown-cycle' with argument t."
7033 (cond ((markdown-table-at-point-p)
7034 (call-interactively #'markdown-table-backward-cell
))
7035 (t (markdown-cycle t
))))
7037 (defun markdown-outline-level ()
7038 "Return the depth to which a statement is nested in the outline."
7040 ((and (match-beginning 0)
7041 (markdown-code-block-at-pos (match-beginning 0)))
7042 7) ;; Only 6 header levels are defined.
7046 (length (markdown-trim-whitespace (match-string-no-properties 4))))))
7048 (defun markdown-promote-subtree (&optional arg
)
7049 "Promote the current subtree of ATX headings.
7050 Note that Markdown does not support heading levels higher than
7051 six and therefore level-six headings will not be promoted
7052 further. If ARG is non-nil promote the heading, otherwise
7056 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx
)
7057 (re-search-backward markdown-regex-header-atx nil t
))
7058 (not (markdown-code-block-at-point-p)))
7059 (let ((level (length (match-string 1)))
7060 (promote-or-demote (if arg
1 -
1))
7062 (markdown-cycle-atx promote-or-demote remove
)
7063 (catch 'end-of-subtree
7064 (while (and (markdown-next-heading)
7065 (looking-at markdown-regex-header-atx
))
7066 ;; Exit if this not a higher level heading; promote otherwise.
7067 (if (and (looking-at markdown-regex-header-atx
)
7068 (<= (length (match-string-no-properties 1)) level
))
7069 (throw 'end-of-subtree nil
)
7070 (markdown-cycle-atx promote-or-demote remove
))))))))
7072 (defun markdown-demote-subtree ()
7073 "Demote the current subtree of ATX headings."
7075 (markdown-promote-subtree t
))
7077 (defun markdown-move-subtree-up ()
7078 "Move the current subtree of ATX headings up."
7080 (outline-move-subtree-up 1))
7082 (defun markdown-move-subtree-down ()
7083 "Move the current subtree of ATX headings down."
7085 (outline-move-subtree-down 1))
7087 (defun markdown-outline-next ()
7088 "Move to next list item, when in a list, or next visible heading."
7090 (let ((bounds (markdown-next-list-item-bounds)))
7092 (goto-char (nth 0 bounds
))
7093 (markdown-next-visible-heading 1))))
7095 (defun markdown-outline-previous ()
7096 "Move to previous list item, when in a list, or previous visible heading."
7098 (let ((bounds (markdown-prev-list-item-bounds)))
7100 (goto-char (nth 0 bounds
))
7101 (markdown-previous-visible-heading 1))))
7103 (defun markdown-outline-next-same-level ()
7104 "Move to next list item or heading of same level."
7106 (let ((bounds (markdown-cur-list-item-bounds)))
7108 (markdown-next-list-item (nth 3 bounds
))
7109 (markdown-forward-same-level 1))))
7111 (defun markdown-outline-previous-same-level ()
7112 "Move to previous list item or heading of same level."
7114 (let ((bounds (markdown-cur-list-item-bounds)))
7116 (markdown-prev-list-item (nth 3 bounds
))
7117 (markdown-backward-same-level 1))))
7119 (defun markdown-outline-up ()
7120 "Move to previous list item, when in a list, or previous heading."
7122 (unless (markdown-up-list)
7123 (markdown-up-heading 1)))
7126 ;;; Marking and Narrowing =====================================================
7128 (defun markdown-mark-paragraph ()
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-paragraph)
7143 (let ((beginning-of-defun-function #'markdown-backward-paragraph
)
7144 (end-of-defun-function #'markdown-forward-paragraph
))
7147 (defun markdown-mark-block ()
7148 "Put mark at end of this block, point at beginning.
7149 The block marked is the one that contains point or follows point.
7151 Interactively, if this command is repeated or (in Transient Mark
7152 mode) if the mark is active, it marks the next block after the
7153 ones already marked."
7155 (if (or (and (eq last-command this-command
) (mark t
))
7156 (and transient-mark-mode mark-active
))
7160 (markdown-forward-block)
7162 (let ((beginning-of-defun-function #'markdown-backward-block
)
7163 (end-of-defun-function #'markdown-forward-block
))
7166 (defun markdown-narrow-to-block ()
7167 "Make text outside current block invisible.
7168 The current block is the one that contains point or follows point."
7170 (let ((beginning-of-defun-function #'markdown-backward-block
)
7171 (end-of-defun-function #'markdown-forward-block
))
7174 (defun markdown-mark-text-block ()
7175 "Put mark at end of this plain text block, point at beginning.
7176 The block marked is the one that contains point or follows point.
7178 Interactively, if this command is repeated or (in Transient Mark
7179 mode) if the mark is active, it marks the next block after the
7180 ones already marked."
7182 (if (or (and (eq last-command this-command
) (mark t
))
7183 (and transient-mark-mode mark-active
))
7187 (markdown-end-of-text-block)
7189 (let ((beginning-of-defun-function #'markdown-beginning-of-text-block
)
7190 (end-of-defun-function #'markdown-end-of-text-block
))
7193 (defun markdown-mark-page ()
7194 "Put mark at end of this top level section, point at beginning.
7195 The top level section marked is the one that contains point or
7198 Interactively, if this command is repeated or (in Transient Mark
7199 mode) if the mark is active, it marks the next page after the
7200 ones already marked."
7202 (if (or (and (eq last-command this-command
) (mark t
))
7203 (and transient-mark-mode mark-active
))
7207 (markdown-forward-page)
7209 (let ((beginning-of-defun-function #'markdown-backward-page
)
7210 (end-of-defun-function #'markdown-forward-page
))
7213 (defun markdown-narrow-to-page ()
7214 "Make text outside current top level section invisible.
7215 The current section is the one that contains point or follows point."
7217 (let ((beginning-of-defun-function #'markdown-backward-page
)
7218 (end-of-defun-function #'markdown-forward-page
))
7221 (defun markdown-mark-subtree ()
7222 "Mark the current subtree.
7223 This puts point at the start of the current subtree, and mark at the end."
7226 (if (markdown-heading-at-point)
7228 (markdown-previous-visible-heading 1))
7230 (markdown-end-of-subtree)
7231 (push-mark (point) nil t
)
7234 (defun markdown-narrow-to-subtree ()
7235 "Narrow buffer to the current subtree."
7240 (progn (markdown-back-to-heading-over-code-block t
) (point))
7241 (progn (markdown-end-of-subtree)
7242 (if (and (markdown-heading-at-point) (not (eobp)))
7247 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
7249 (defun markdown-move-up ()
7250 "Move thing at point up.
7251 When in a list item, call `markdown-move-list-item-up'.
7252 When in a table, call `markdown-table-move-row-up'.
7253 Otherwise, move the current heading subtree up with
7254 `markdown-move-subtree-up'."
7257 ((markdown-list-item-at-point-p)
7258 (call-interactively #'markdown-move-list-item-up
))
7259 ((markdown-table-at-point-p)
7260 (call-interactively #'markdown-table-move-row-up
))
7262 (call-interactively #'markdown-move-subtree-up
))))
7264 (defun markdown-move-down ()
7265 "Move thing at point down.
7266 When in a list item, call `markdown-move-list-item-down'.
7267 Otherwise, move the current heading subtree up with
7268 `markdown-move-subtree-down'."
7271 ((markdown-list-item-at-point-p)
7272 (call-interactively #'markdown-move-list-item-down
))
7273 ((markdown-table-at-point-p)
7274 (call-interactively #'markdown-table-move-row-down
))
7276 (call-interactively #'markdown-move-subtree-down
))))
7278 (defun markdown-promote ()
7279 "Promote or move element at point to the left.
7280 Depending on the context, this function will promote a heading or
7281 list item at the point, move a table column to the left, or cycle
7286 ;; Promote atx heading subtree
7287 ((thing-at-point-looking-at markdown-regex-header-atx
)
7288 (markdown-promote-subtree))
7289 ;; Promote setext heading
7290 ((thing-at-point-looking-at markdown-regex-header-setext
)
7291 (markdown-cycle-setext -
1))
7292 ;; Promote horizontal rule
7293 ((thing-at-point-looking-at markdown-regex-hr
)
7294 (markdown-cycle-hr -
1))
7295 ;; Promote list item
7296 ((setq bounds
(markdown-cur-list-item-bounds))
7297 (markdown-promote-list-item bounds
))
7298 ;; Move table column to the left
7299 ((markdown-table-at-point-p)
7300 (call-interactively #'markdown-table-move-column-left
))
7302 ((thing-at-point-looking-at markdown-regex-bold
)
7303 (markdown-cycle-bold))
7305 ((thing-at-point-looking-at markdown-regex-italic
)
7306 (markdown-cycle-italic))
7308 (user-error "Nothing to promote at point")))))
7310 (defun markdown-demote ()
7311 "Demote or move element at point to the right.
7312 Depending on the context, this function will demote a heading or
7313 list item at the point, move a table column to the right, or cycle
7318 ;; Demote atx heading subtree
7319 ((thing-at-point-looking-at markdown-regex-header-atx
)
7320 (markdown-demote-subtree))
7321 ;; Demote setext heading
7322 ((thing-at-point-looking-at markdown-regex-header-setext
)
7323 (markdown-cycle-setext 1))
7324 ;; Demote horizontal rule
7325 ((thing-at-point-looking-at markdown-regex-hr
)
7326 (markdown-cycle-hr 1))
7328 ((setq bounds
(markdown-cur-list-item-bounds))
7329 (markdown-demote-list-item bounds
))
7330 ;; Move table column to the right
7331 ((markdown-table-at-point-p)
7332 (call-interactively #'markdown-table-move-column-right
))
7334 ((thing-at-point-looking-at markdown-regex-bold
)
7335 (markdown-cycle-bold))
7337 ((thing-at-point-looking-at markdown-regex-italic
)
7338 (markdown-cycle-italic))
7340 (user-error "Nothing to demote at point")))))
7343 ;;; Commands ==================================================================
7345 (defun markdown (&optional output-buffer-name
)
7346 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
7347 The output buffer name defaults to `markdown-output-buffer-name'.
7348 Return the name of the output buffer used."
7350 (save-window-excursion
7351 (let* ((commands (cond ((stringp markdown-command
) (split-string markdown-command
))
7352 ((listp markdown-command
) markdown-command
)))
7353 (command (car-safe commands
))
7354 (command-args (cdr-safe commands
))
7355 begin-region end-region
)
7357 (setq begin-region
(region-beginning)
7358 end-region
(region-end))
7359 (setq begin-region
(point-min)
7360 end-region
(point-max)))
7362 (unless output-buffer-name
7363 (setq output-buffer-name markdown-output-buffer-name
))
7364 (when (and (stringp command
) (not (executable-find command
)))
7365 (user-error "Markdown command %s is not found" command
))
7368 ;; Handle case when `markdown-command' does not read from stdin
7369 ((and (stringp command
) markdown-command-needs-filename
)
7370 (if (not buffer-file-name
)
7371 (user-error "Must be visiting a file")
7372 ;; Don’t use ‘shell-command’ because it’s not guaranteed to
7373 ;; return the exit code of the process.
7374 (let ((command (if (listp markdown-command
)
7375 (string-join markdown-command
" ")
7377 (shell-command-on-region
7378 ;; Pass an empty region so that stdin is empty.
7381 (shell-quote-argument buffer-file-name
))
7382 output-buffer-name
))))
7383 ;; Pass region to `markdown-command' via stdin
7385 (let ((buf (get-buffer-create output-buffer-name
)))
7386 (with-current-buffer buf
7387 (setq buffer-read-only nil
)
7389 (if (stringp command
)
7390 (if (not (null command-args
))
7391 (apply #'call-process-region begin-region end-region command nil buf nil command-args
)
7392 (call-process-region begin-region end-region command nil buf
))
7393 (if markdown-command-needs-filename
7394 (if (not buffer-file-name
)
7395 (user-error "Must be visiting a file")
7396 (funcall markdown-command begin-region end-region buf buffer-file-name
))
7397 (funcall markdown-command begin-region end-region buf
))
7398 ;; If the ‘markdown-command’ function didn’t signal an
7399 ;; error, assume it succeeded by binding ‘exit-code’ to 0.
7401 ;; The exit code can be a signal description string, so don’t use ‘=’
7403 (unless (eq exit-code
0)
7404 (user-error "%s failed with exit code %s"
7405 markdown-command exit-code
))))
7406 output-buffer-name
))
7408 (defun markdown-standalone (&optional output-buffer-name
)
7409 "Special function to provide standalone HTML output.
7410 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
7412 (setq output-buffer-name
(markdown output-buffer-name
))
7413 (with-current-buffer output-buffer-name
7414 (set-buffer output-buffer-name
)
7415 (unless (markdown-output-standalone-p)
7416 (markdown-add-xhtml-header-and-footer output-buffer-name
))
7417 (goto-char (point-min))
7421 (defun markdown-other-window (&optional output-buffer-name
)
7422 "Run `markdown-command' on current buffer and display in other window.
7423 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7426 (markdown-display-buffer-other-window
7427 (markdown-standalone output-buffer-name
)))
7429 (defun markdown-output-standalone-p ()
7430 "Determine whether `markdown-command' output is standalone XHTML.
7431 Standalone XHTML output is identified by an occurrence of
7432 `markdown-xhtml-standalone-regexp' in the first five lines of output."
7434 (goto-char (point-min))
7437 markdown-xhtml-standalone-regexp
7438 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
7441 (defun markdown-stylesheet-link-string (stylesheet-path)
7442 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
7443 (or (and (string-prefix-p "~" stylesheet-path
)
7444 (expand-file-name stylesheet-path
))
7448 (defun markdown-escape-title (title)
7449 "Escape a minimum set of characters in TITLE so they don't clash with html."
7450 (replace-regexp-in-string ">" ">"
7451 (replace-regexp-in-string "<" "<"
7452 (replace-regexp-in-string "&" "&" title
))))
7454 (defun markdown-add-xhtml-header-and-footer (title)
7455 "Wrap XHTML header and footer with given TITLE around current buffer."
7456 (goto-char (point-min))
7457 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
7458 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
7459 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
7460 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
7462 (insert (markdown-escape-title title
))
7463 (insert "</title>\n")
7464 (unless (= (length markdown-content-type
) 0)
7467 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
7468 markdown-content-type
7469 (or (and markdown-coding-system
7470 (coding-system-get markdown-coding-system
7472 (coding-system-get buffer-file-coding-system
7475 (if (> (length markdown-css-paths
) 0)
7476 (insert (mapconcat #'markdown-stylesheet-link-string
7477 markdown-css-paths
"\n")))
7478 (when (> (length markdown-xhtml-header-content
) 0)
7479 (insert markdown-xhtml-header-content
))
7480 (insert "\n</head>\n\n"
7482 (when (> (length markdown-xhtml-body-preamble
) 0)
7483 (insert markdown-xhtml-body-preamble
"\n"))
7484 (goto-char (point-max))
7485 (when (> (length markdown-xhtml-body-epilogue
) 0)
7486 (insert "\n" markdown-xhtml-body-epilogue
))
7491 (defun markdown-preview (&optional output-buffer-name
)
7492 "Run `markdown-command' on the current buffer and view output in browser.
7493 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7496 (browse-url-of-buffer
7497 (markdown-standalone (or output-buffer-name markdown-output-buffer-name
))))
7499 (defun markdown-export-file-name (&optional extension
)
7500 "Attempt to generate a filename for Markdown output.
7501 The file extension will be EXTENSION if given, or .html by default.
7502 If the current buffer is visiting a file, we construct a new
7503 output filename based on that filename. Otherwise, return nil."
7504 (when (buffer-file-name)
7506 (setq extension
".html"))
7511 (file-name-sans-extension (buffer-file-name)))
7515 ((equal candidate
(buffer-file-name))
7516 (concat candidate extension
))
7520 (defun markdown-export (&optional output-file
)
7521 "Run Markdown on the current buffer, save to file, and return the filename.
7522 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
7523 generated by `markdown-export-file-name', which will be constructed using the
7524 current filename, but with the extension removed and replaced with .html."
7527 (setq output-file
(markdown-export-file-name ".html")))
7529 (let* ((init-buf (current-buffer))
7530 (init-point (point))
7531 (init-buf-string (buffer-string))
7532 (output-buffer (find-file-noselect output-file
))
7533 (output-buffer-name (buffer-name output-buffer
)))
7534 (run-hooks 'markdown-before-export-hook
)
7535 (markdown-standalone output-buffer-name
)
7536 (with-current-buffer output-buffer
7537 (run-hooks 'markdown-after-export-hook
)
7539 (when markdown-export-kill-buffer
(kill-buffer)))
7540 ;; if modified, restore initial buffer
7541 (when (buffer-modified-p init-buf
)
7543 (insert init-buf-string
)
7545 (goto-char init-point
))
7548 (defun markdown-export-and-preview ()
7549 "Export to XHTML using `markdown-export' and browse the resulting file."
7551 (browse-url-of-file (markdown-export)))
7553 (defvar-local markdown-live-preview-buffer nil
7554 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
7556 (defvar-local markdown-live-preview-source-buffer nil
7557 "Source buffer from which current buffer was generated.
7558 This is the inverse of `markdown-live-preview-buffer'.")
7560 (defvar markdown-live-preview-currently-exporting nil
)
7562 (defun markdown-live-preview-get-filename ()
7563 "Standardize the filename exported by `markdown-live-preview-export'."
7564 (markdown-export-file-name ".html"))
7566 (defun markdown-live-preview-window-eww (file)
7567 "Preview FILE with eww.
7568 To be used with `markdown-live-preview-window-function'."
7569 (when (and (bound-and-true-p eww-auto-rename-buffer
)
7570 markdown-live-preview-buffer
)
7571 (kill-buffer markdown-live-preview-buffer
))
7572 (eww-open-file file
)
7573 ;; #737 if `eww-auto-rename-buffer' is non-nil, the buffer name is not "*eww*"
7574 ;; Try to find the buffer whose name ends with "eww*"
7575 (if (bound-and-true-p eww-auto-rename-buffer
)
7576 (cl-loop for buf in
(buffer-list)
7577 when
(string-match-p "eww\\*\\'" (buffer-name buf
))
7579 (get-buffer "*eww*")))
7581 (defun markdown-visual-lines-between-points (beg end
)
7584 (cl-loop with count
= 0
7585 while
(progn (end-of-visual-line)
7586 (and (< (point) end
) (line-move-visual 1 t
)))
7588 finally return count
)))
7590 (defun markdown-live-preview-window-serialize (buf)
7591 "Get window point and scroll data for all windows displaying BUF."
7592 (when (buffer-live-p buf
)
7593 (with-current-buffer buf
7596 (with-selected-window win
7597 (let* ((start (window-start))
7599 (pt-or-sym (cond ((= pt
(point-min)) 'min
)
7600 ((= pt
(point-max)) 'max
)
7602 (diff (markdown-visual-lines-between-points
7604 (list win pt-or-sym diff
))))
7605 (get-buffer-window-list buf
)))))
7607 (defun markdown-get-point-back-lines (pt num-lines
)
7610 (line-move-visual (- num-lines
) t
)
7611 ;; in testing, can occasionally overshoot the number of lines to traverse
7612 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt
)))
7613 (when (> actual-num-lines num-lines
)
7614 (line-move-visual (- actual-num-lines num-lines
) t
)))
7617 (defun markdown-live-preview-window-deserialize (window-posns)
7618 "Apply window point and scroll data from WINDOW-POSNS.
7619 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
7620 (cl-destructuring-bind (win pt-or-sym diff
) window-posns
7621 (when (window-live-p win
)
7622 (with-current-buffer markdown-live-preview-buffer
7623 (set-window-buffer win
(current-buffer))
7624 (cl-destructuring-bind (actual-pt actual-diff
)
7626 (min (list (point-min) 0))
7627 (max (list (point-max) diff
))
7628 (t (list pt-or-sym diff
)))
7630 win
(markdown-get-point-back-lines actual-pt actual-diff
))
7631 (set-window-point win actual-pt
))))))
7633 (defun markdown-live-preview-export ()
7634 "Export to XHTML using `markdown-export'.
7635 Browse the resulting file within Emacs using
7636 `markdown-live-preview-window-function' Return the buffer
7637 displaying the rendered output."
7639 (let ((filename (markdown-live-preview-get-filename)))
7641 (let* ((markdown-live-preview-currently-exporting t
)
7642 (cur-buf (current-buffer))
7643 (export-file (markdown-export filename
))
7644 ;; get positions in all windows currently displaying output buffer
7646 (markdown-live-preview-window-serialize
7647 markdown-live-preview-buffer
)))
7648 (save-window-excursion
7649 (let ((output-buffer
7650 (funcall markdown-live-preview-window-function export-file
)))
7651 (with-current-buffer output-buffer
7652 (setq markdown-live-preview-source-buffer cur-buf
)
7653 (add-hook 'kill-buffer-hook
7654 #'markdown-live-preview-remove-on-kill t t
))
7655 (with-current-buffer cur-buf
7656 (setq markdown-live-preview-buffer output-buffer
))))
7657 (with-current-buffer cur-buf
7658 ;; reset all windows displaying output buffer to where they were,
7659 ;; now with the new output
7660 (mapc #'markdown-live-preview-window-deserialize window-data
)
7661 ;; delete html editing buffer
7662 (let ((buf (get-file-buffer export-file
))) (when buf
(kill-buffer buf
)))
7663 (when (and export-file
(file-exists-p export-file
)
7664 (eq markdown-live-preview-delete-export
7666 (delete-file export-file
))
7667 markdown-live-preview-buffer
)))))
7669 (defun markdown-live-preview-remove ()
7670 (when (buffer-live-p markdown-live-preview-buffer
)
7671 (kill-buffer markdown-live-preview-buffer
))
7672 (setq markdown-live-preview-buffer nil
)
7673 ;; if set to 'delete-on-export, the output has already been deleted
7674 (when (eq markdown-live-preview-delete-export
'delete-on-destroy
)
7675 (let ((outfile-name (markdown-live-preview-get-filename)))
7676 (when (and outfile-name
(file-exists-p outfile-name
))
7677 (delete-file outfile-name
)))))
7679 (defun markdown-get-other-window ()
7680 "Find another window to display preview or output content."
7682 ((memq markdown-split-window-direction
'(vertical below
))
7683 (or (window-in-direction 'below
) (split-window-vertically)))
7684 ((memq markdown-split-window-direction
'(horizontal right
))
7685 (or (window-in-direction 'right
) (split-window-horizontally)))
7686 (t (split-window-sensibly (get-buffer-window)))))
7688 (defun markdown-display-buffer-other-window (buf)
7689 "Display preview or output buffer BUF in another window."
7690 (if (and display-buffer-alist
(eq markdown-split-window-direction
'any
))
7691 (display-buffer buf
)
7692 (let ((cur-buf (current-buffer))
7693 (window (markdown-get-other-window)))
7694 (set-window-buffer window buf
)
7695 (set-buffer cur-buf
))))
7697 (defun markdown-live-preview-if-markdown ()
7698 (when (and (derived-mode-p 'markdown-mode
)
7699 markdown-live-preview-mode
)
7700 (unless markdown-live-preview-currently-exporting
7701 (if (buffer-live-p markdown-live-preview-buffer
)
7702 (markdown-live-preview-export)
7703 (markdown-display-buffer-other-window
7704 (markdown-live-preview-export))))))
7706 (defun markdown-live-preview-remove-on-kill ()
7707 (cond ((and (derived-mode-p 'markdown-mode
)
7708 markdown-live-preview-mode
)
7709 (markdown-live-preview-remove))
7710 (markdown-live-preview-source-buffer
7711 (with-current-buffer markdown-live-preview-source-buffer
7712 (setq markdown-live-preview-buffer nil
))
7713 (setq markdown-live-preview-source-buffer nil
))))
7715 (defun markdown-live-preview-switch-to-output ()
7716 "Turn on `markdown-live-preview-mode' and switch to output buffer.
7717 The output buffer is opened in another window."
7719 (if markdown-live-preview-mode
7720 (markdown-display-buffer-other-window (markdown-live-preview-export)))
7721 (markdown-live-preview-mode))
7723 (defun markdown-live-preview-re-export ()
7724 "Re-export the current live previewed content.
7725 If the current buffer is a buffer displaying the exported version of a
7726 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
7727 update this buffer's contents."
7729 (when markdown-live-preview-source-buffer
7730 (with-current-buffer markdown-live-preview-source-buffer
7731 (markdown-live-preview-export))))
7733 (defun markdown-open ()
7734 "Open file for the current buffer with `markdown-open-command'."
7736 (unless markdown-open-command
7737 (user-error "Variable `markdown-open-command' must be set"))
7738 (if (stringp markdown-open-command
)
7739 (if (not buffer-file-name
)
7740 (user-error "Must be visiting a file")
7742 (let ((exit-code (call-process markdown-open-command nil nil nil
7744 ;; The exit code can be a signal description string, so don’t use ‘=’
7746 (unless (eq exit-code
0)
7747 (user-error "%s failed with exit code %s"
7748 markdown-open-command exit-code
))))
7749 (funcall markdown-open-command
))
7752 (defun markdown-kill-ring-save ()
7753 "Run Markdown on file and store output in the kill ring."
7755 (save-window-excursion
7757 (with-current-buffer markdown-output-buffer-name
7758 (kill-ring-save (point-min) (point-max)))))
7761 ;;; Links =====================================================================
7763 (defun markdown-backward-to-link-start ()
7764 "Backward link start position if current position is in link title."
7766 (when (eq (get-text-property (point) 'face
) 'markdown-link-face
)
7767 (skip-chars-backward "^[")
7770 (defun markdown-link-p ()
7771 "Return non-nil when `point' is at a non-wiki link.
7772 See `markdown-wiki-link-p' for more information."
7774 (let ((case-fold-search nil
))
7775 (when (and (not (markdown-wiki-link-p)) (not (markdown-code-block-at-point-p)))
7776 (markdown-backward-to-link-start)
7777 (or (thing-at-point-looking-at markdown-regex-link-inline
)
7778 (thing-at-point-looking-at markdown-regex-link-reference
)
7779 (thing-at-point-looking-at markdown-regex-uri
)
7780 (thing-at-point-looking-at markdown-regex-angle-uri
))))))
7782 (defun markdown-link-at-pos (pos)
7783 "Return properties of link or image at position POS.
7784 Value is a list of elements describing the link:
7785 0. beginning position
7791 6. bang (nil or \"!\")"
7794 (markdown-backward-to-link-start)
7795 (let (begin end text url reference title bang
)
7797 ;; Inline image or link at point.
7798 ((thing-at-point-looking-at markdown-regex-link-inline
)
7799 (setq bang
(match-string-no-properties 1)
7800 begin
(match-beginning 0)
7802 text
(match-string-no-properties 3)
7803 url
(match-string-no-properties 6))
7805 (setq title
(substring (match-string-no-properties 7) 1 -
1))
7806 ;; #408 URL contains close parenthesis case
7807 (goto-char (match-beginning 5))
7808 (let ((paren-end (scan-sexps (point) 1)))
7809 (when (and paren-end
(< end paren-end
))
7810 (setq url
(buffer-substring (match-beginning 6) (1- paren-end
)))))))
7811 ;; Reference link at point.
7812 ((or (thing-at-point-looking-at markdown-regex-link-inline
)
7813 (thing-at-point-looking-at markdown-regex-link-reference
))
7814 (setq bang
(match-string-no-properties 1)
7815 begin
(match-beginning 0)
7817 text
(match-string-no-properties 3))
7818 (when (char-equal (char-after (match-beginning 5)) ?\
[)
7819 (setq reference
(match-string-no-properties 6))))
7820 ;; Angle bracket URI at point.
7821 ((thing-at-point-looking-at markdown-regex-angle-uri
)
7822 (setq begin
(match-beginning 0)
7824 url
(match-string-no-properties 2)))
7825 ;; Plain URI at point.
7826 ((thing-at-point-looking-at markdown-regex-uri
)
7827 (setq begin
(match-beginning 0)
7829 url
(match-string-no-properties 1))))
7830 (list begin end text url reference title bang
))))
7832 (defun markdown-link-url ()
7833 "Return the URL part of the regular (non-wiki) link at point.
7834 Works with both inline and reference style links, and with images.
7835 If point is not at a link or the link reference is not defined
7837 (let* ((values (markdown-link-at-pos (point)))
7838 (text (nth 2 values
))
7839 (url (nth 3 values
))
7840 (ref (nth 4 values
)))
7841 (or url
(and ref
(car (markdown-reference-definition
7842 (downcase (if (string= ref
"") text ref
))))))))
7844 (defun markdown--browse-url (url)
7845 (let* ((struct (url-generic-parse-url url
))
7846 (full (url-fullness struct
))
7848 ;; Parse URL, determine fullness, strip query string
7849 (setq file
(car (url-path-and-query struct
)))
7850 ;; Open full URLs in browser, files in Emacs
7853 (when (and file
(> (length file
) 0))
7854 (let ((link-file (funcall markdown-translate-filename-function file
)))
7855 (if (and markdown-open-image-command
(string-match-p (image-file-name-regexp) link-file
))
7856 (if (functionp markdown-open-image-command
)
7857 (funcall markdown-open-image-command link-file
)
7858 (process-file markdown-open-image-command nil nil nil link-file
))
7859 (find-file link-file
)))))))
7861 (defun markdown-follow-link-at-point (&optional event
)
7862 "Open the non-wiki link at point or EVENT.
7863 If the link is a complete URL, open in browser with `browse-url'.
7864 Otherwise, open with `find-file' after stripping anchor and/or query string.
7865 Translate filenames using `markdown-filename-translate-function'."
7866 (interactive (list last-command-event
))
7868 (if event
(posn-set-point (event-start event
)))
7869 (if (markdown-link-p)
7870 (markdown--browse-url (markdown-link-url))
7871 (user-error "Point is not at a Markdown link or URL"))))
7873 (defun markdown-fontify-inline-links (last)
7874 "Add text properties to next inline link from point to LAST."
7875 (when (markdown-match-generic-links last nil
)
7876 (let* ((link-start (match-beginning 3))
7877 (link-end (match-end 3))
7878 (url-start (match-beginning 6))
7879 (url-end (match-end 6))
7880 (url (match-string-no-properties 6))
7881 (title-start (match-beginning 7))
7882 (title-end (match-end 7))
7883 (title (match-string-no-properties 7))
7885 (mp (list 'invisible
'markdown-markup
7887 'font-lock-multiline t
))
7888 ;; Link part (without face)
7889 (lp (list 'keymap markdown-mode-mouse-map
7890 'mouse-face
'markdown-highlight-face
7891 'font-lock-multiline t
7892 'help-echo
(if title
(concat title
"\n" url
) url
)))
7894 (up (list 'keymap markdown-mode-mouse-map
7895 'invisible
'markdown-markup
7896 'mouse-face
'markdown-highlight-face
7897 'font-lock-multiline t
))
7898 ;; URL composition character
7899 (url-char (markdown--first-displayable markdown-url-compose-char
))
7901 (tp (list 'invisible
'markdown-markup
7902 'font-lock-multiline t
)))
7903 (dolist (g '(1 2 4 5 8))
7905 (add-text-properties (match-beginning g
) (match-end g
) mp
)
7906 (add-face-text-property (match-beginning g
) (match-end g
) 'markdown-markup-face
)))
7907 ;; Preserve existing faces applied to link part (e.g., inline code)
7909 (add-text-properties link-start link-end lp
)
7910 (add-face-text-property link-start link-end
'markdown-link-face
))
7912 (add-text-properties url-start url-end up
)
7913 (add-face-text-property url-start url-end
'markdown-url-face
))
7915 (add-text-properties url-end title-end tp
)
7916 (add-face-text-property url-end title-end
'markdown-link-title-face
))
7917 (when (and markdown-hide-urls url-start
)
7918 (compose-region url-start
(or title-end url-end
) url-char
))
7921 (defun markdown-fontify-reference-links (last)
7922 "Add text properties to next reference link from point to LAST."
7923 (when (markdown-match-generic-links last t
)
7924 (let* ((link-start (match-beginning 3))
7925 (link-end (match-end 3))
7926 (ref-start (match-beginning 6))
7927 (ref-end (match-end 6))
7929 (mp (list 'invisible
'markdown-markup
7931 'font-lock-multiline t
))
7933 (lp (list 'keymap markdown-mode-mouse-map
7934 'mouse-face
'markdown-highlight-face
7935 'font-lock-multiline t
7936 'help-echo
(lambda (_ __ pos
)
7940 (or (markdown-link-url)
7941 "Undefined reference"))))))
7942 ;; URL composition character
7943 (url-char (markdown--first-displayable markdown-url-compose-char
))
7945 (rp (list 'invisible
'markdown-markup
7946 'font-lock-multiline t
)))
7947 (dolist (g '(1 2 4 5 8))
7949 (add-text-properties (match-beginning g
) (match-end g
) mp
)
7950 (add-face-text-property (match-beginning g
) (match-end g
) 'markdown-markup-face
)))
7952 (add-text-properties link-start link-end lp
)
7953 (add-face-text-property link-start link-end
'markdown-link-face
))
7955 (add-text-properties ref-start ref-end rp
)
7956 (add-face-text-property ref-start ref-end
'markdown-reference-face
)
7957 (when (and markdown-hide-urls
(> (- ref-end ref-start
) 2))
7958 (compose-region ref-start ref-end url-char
)))
7961 (defun markdown-fontify-angle-uris (last)
7962 "Add text properties to angle URIs from point to LAST."
7963 (when (markdown-match-angle-uris last
)
7964 (let* ((url-start (match-beginning 2))
7965 (url-end (match-end 2))
7967 (mp (list 'face
'markdown-markup-face
7968 'invisible
'markdown-markup
7970 'font-lock-multiline t
))
7972 (up (list 'keymap markdown-mode-mouse-map
7973 'face
'markdown-plain-url-face
7974 'mouse-face
'markdown-highlight-face
7975 'font-lock-multiline t
)))
7977 (add-text-properties (match-beginning g
) (match-end g
) mp
))
7978 (add-text-properties url-start url-end up
)
7981 (defun markdown-fontify-plain-uris (last)
7982 "Add text properties to plain URLs from point to LAST."
7983 (when (markdown-match-plain-uris last
)
7984 (let* ((start (match-beginning 0))
7986 (props (list 'keymap markdown-mode-mouse-map
7987 'face
'markdown-plain-url-face
7988 'mouse-face
'markdown-highlight-face
7990 'font-lock-multiline t
)))
7991 (add-text-properties start end props
)
7994 (defun markdown-toggle-url-hiding (&optional arg
)
7995 "Toggle the display or hiding of URLs.
7996 With a prefix argument ARG, enable URL hiding if ARG is positive,
7997 and disable it otherwise."
7998 (interactive (list (or current-prefix-arg
'toggle
)))
7999 (setq markdown-hide-urls
8000 (if (eq arg
'toggle
)
8001 (not markdown-hide-urls
)
8002 (> (prefix-numeric-value arg
) 0)))
8003 (if markdown-hide-urls
8004 (message "markdown-mode URL hiding enabled")
8005 (message "markdown-mode URL hiding disabled"))
8006 (markdown-reload-extensions))
8009 ;;; Wiki Links ================================================================
8011 (defun markdown-wiki-link-p ()
8012 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
8013 A true wiki link name matches `markdown-regex-wiki-link' but does
8014 not match the current file name after conversion. This modifies
8015 the data returned by `match-data'. Note that the potential wiki
8016 link name must be available via `match-string'."
8017 (when markdown-enable-wiki-links
8018 (let ((case-fold-search nil
))
8019 (and (thing-at-point-looking-at markdown-regex-wiki-link
)
8020 (not (markdown-code-block-at-point-p))
8021 (or (not buffer-file-name
)
8022 (not (string-equal (buffer-file-name)
8023 (markdown-convert-wiki-link-to-filename
8024 (markdown-wiki-link-link)))))))))
8026 (defun markdown-wiki-link-link ()
8027 "Return the link part of the wiki link using current match data.
8028 The location of the link component depends on the value of
8029 `markdown-wiki-link-alias-first'."
8030 (if markdown-wiki-link-alias-first
8031 (or (match-string-no-properties 5) (match-string-no-properties 3))
8032 (match-string-no-properties 3)))
8034 (defun markdown-wiki-link-alias ()
8035 "Return the alias or text part of the wiki link using current match data.
8036 The location of the alias component depends on the value of
8037 `markdown-wiki-link-alias-first'."
8038 (if markdown-wiki-link-alias-first
8039 (match-string-no-properties 3)
8040 (or (match-string-no-properties 5) (match-string-no-properties 3))))
8042 (defun markdown--wiki-link-search-types ()
8043 (let ((ret (and markdown-wiki-link-search-type
8044 (cl-copy-list markdown-wiki-link-search-type
))))
8045 (when (and markdown-wiki-link-search-subdirectories
8046 (not (memq 'sub-directories markdown-wiki-link-search-type
)))
8047 (push 'sub-directories ret
))
8048 (when (and markdown-wiki-link-search-parent-directories
8049 (not (memq 'parent-directories markdown-wiki-link-search-type
)))
8050 (push 'parent-directories ret
))
8053 (defun markdown--project-root ()
8054 (or (cl-loop for dir in
'(".git" ".hg" ".svn")
8055 when
(locate-dominating-file default-directory dir
)
8059 (let ((project (project-current t
)))
8061 (if (fboundp 'project-root
)
8062 (project-root project
)
8063 (car (project-roots project
))))))))
8065 (defun markdown-convert-wiki-link-to-filename (name)
8066 "Generate a filename from the wiki link NAME.
8067 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
8068 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
8069 and [[test test]] both map to Test-test.ext. Look in the current
8070 directory first, then in subdirectories if
8071 `markdown-wiki-link-search-subdirectories' is non-nil, and then
8072 in parent directories if
8073 `markdown-wiki-link-search-parent-directories' is non-nil."
8075 ;; This function must not overwrite match data(PR #590)
8076 (let* ((basename (replace-regexp-in-string
8077 "[[:space:]\n]" markdown-link-space-sub-char name
))
8078 (basename (if (derived-mode-p 'gfm-mode
)
8079 (concat (upcase (substring basename
0 1))
8080 (downcase (substring basename
1 nil
)))
8082 (search-types (markdown--wiki-link-search-types))
8083 directory extension default candidates dir
)
8084 (when buffer-file-name
8085 (setq directory
(file-name-directory buffer-file-name
)
8086 extension
(file-name-extension buffer-file-name
)))
8087 (setq default
(concat basename
8088 (when extension
(concat "." extension
))))
8090 ;; Look in current directory first.
8091 ((or (null buffer-file-name
)
8092 (file-exists-p default
))
8094 ;; Possibly search in subdirectories, next.
8095 ((and (memq 'sub-directories search-types
)
8097 (directory-files-recursively
8098 directory
(concat "^" default
"$"))))
8100 ;; Possibly search in parent directories as a last resort.
8101 ((and (memq 'parent-directories search-types
)
8102 (setq dir
(locate-dominating-file directory default
)))
8103 (concat dir default
))
8104 ((and (memq 'project search-types
)
8106 (directory-files-recursively
8107 (markdown--project-root) (concat "^" default
"$"))))
8109 ;; If nothing is found, return default in current directory.
8112 (defun markdown-follow-wiki-link (name &optional other
)
8113 "Follow the wiki link NAME.
8114 Convert the name to a file name and call `find-file'. Ensure that
8115 the new buffer remains in `markdown-mode'. Open the link in another
8116 window when OTHER is non-nil."
8117 (let ((filename (markdown-convert-wiki-link-to-filename name
))
8118 (wp (when buffer-file-name
8119 (file-name-directory buffer-file-name
))))
8121 (user-error "Must be visiting a file")
8122 (when other
(other-window 1))
8123 (let ((default-directory wp
))
8124 (find-file filename
)))
8125 (unless (derived-mode-p 'markdown-mode
)
8128 (defun markdown-follow-wiki-link-at-point (&optional arg
)
8129 "Find Wiki Link at point.
8130 With prefix argument ARG, open the file in other window.
8131 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
8133 (if (markdown-wiki-link-p)
8134 (markdown-follow-wiki-link (markdown-wiki-link-link) arg
)
8135 (user-error "Point is not at a Wiki Link")))
8137 (defun markdown-highlight-wiki-link (from to face
)
8138 "Highlight the wiki link in the region between FROM and TO using FACE."
8139 (put-text-property from to
'font-lock-face face
))
8141 (defun markdown-unfontify-region-wiki-links (from to
)
8142 "Remove wiki link faces from the region specified by FROM and TO."
8144 (let ((modified (buffer-modified-p)))
8145 (remove-text-properties from to
'(font-lock-face markdown-link-face
))
8146 (remove-text-properties from to
'(font-lock-face markdown-missing-link-face
))
8147 ;; remove-text-properties marks the buffer modified in emacs 24.3,
8148 ;; undo that if it wasn't originally marked modified
8149 (set-buffer-modified-p modified
)))
8151 (defun markdown-fontify-region-wiki-links (from to
)
8152 "Search region given by FROM and TO for wiki links and fontify them.
8153 If a wiki link is found check to see if the backing file exists
8154 and highlight accordingly."
8157 (while (re-search-forward markdown-regex-wiki-link to t
)
8158 (when (not (markdown-code-block-at-point-p))
8159 (let ((highlight-beginning (match-beginning 1))
8160 (highlight-end (match-end 1))
8162 (markdown-convert-wiki-link-to-filename
8163 (markdown-wiki-link-link))))
8164 (if (condition-case nil
(file-exists-p file-name
) (error nil
))
8165 (markdown-highlight-wiki-link
8166 highlight-beginning highlight-end
'markdown-link-face
)
8167 (markdown-highlight-wiki-link
8168 highlight-beginning highlight-end
'markdown-missing-link-face
)))))))
8170 (defun markdown-extend-changed-region (from to
)
8171 "Extend region given by FROM and TO so that we can fontify all links.
8172 The region is extended to the first newline before and the first
8174 ;; start looking for the first new line before 'from
8176 (re-search-backward "\n" nil t
)
8177 (let ((new-from (point-min))
8178 (new-to (point-max)))
8179 (if (not (= (point) from
))
8180 (setq new-from
(point)))
8181 ;; do the same thing for the first new line after 'to
8183 (re-search-forward "\n" nil t
)
8184 (if (not (= (point) to
))
8185 (setq new-to
(point)))
8186 (cl-values new-from new-to
)))
8188 (defun markdown-check-change-for-wiki-link (from to
)
8189 "Check region between FROM and TO for wiki links and re-fontify as needed."
8191 (let* ((modified (buffer-modified-p))
8192 (buffer-undo-list t
)
8193 (inhibit-read-only t
)
8195 buffer-file-truename
)
8200 (cursor-intangible-mode +1) ;; inhibit-point-motion-hooks is obsoleted since Emacs 29
8201 ;; Extend the region to fontify so that it starts
8202 ;; and ends at safe places.
8203 (cl-multiple-value-bind (new-from new-to
)
8204 (markdown-extend-changed-region from to
)
8205 (goto-char new-from
)
8206 ;; Only refontify when the range contains text with a
8207 ;; wiki link face or if the wiki link regexp matches.
8208 (when (or (markdown-range-property-any
8209 new-from new-to
'font-lock-face
8210 '(markdown-link-face markdown-missing-link-face
))
8212 markdown-regex-wiki-link new-to t
))
8213 ;; Unfontify existing fontification (start from scratch)
8214 (markdown-unfontify-region-wiki-links new-from new-to
)
8215 ;; Now do the fontification.
8216 (markdown-fontify-region-wiki-links new-from new-to
))))))
8217 (cursor-intangible-mode -
1)
8220 (set-buffer-modified-p nil
)))))
8222 (defun markdown-check-change-for-wiki-link-after-change (from to _
)
8223 "Check region between FROM and TO for wiki links and re-fontify as needed.
8224 Designed to be used with the `after-change-functions' hook."
8225 (markdown-check-change-for-wiki-link from to
))
8227 (defun markdown-fontify-buffer-wiki-links ()
8228 "Refontify all wiki links in the buffer."
8230 (markdown-check-change-for-wiki-link (point-min) (point-max)))
8232 (defun markdown-toggle-wiki-links (&optional arg
)
8233 "Toggle support for wiki links.
8234 With a prefix argument ARG, enable wiki link support if ARG is positive,
8235 and disable it otherwise."
8236 (interactive (list (or current-prefix-arg
'toggle
)))
8237 (setq markdown-enable-wiki-links
8238 (if (eq arg
'toggle
)
8239 (not markdown-enable-wiki-links
)
8240 (> (prefix-numeric-value arg
) 0)))
8241 (if markdown-enable-wiki-links
8242 (message "markdown-mode wiki link support enabled")
8243 (message "markdown-mode wiki link support disabled"))
8244 (markdown-reload-extensions))
8246 (defun markdown-setup-wiki-link-hooks ()
8247 "Add or remove hooks for fontifying wiki links.
8248 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
8249 ;; Anytime text changes make sure it gets fontified correctly
8250 (if (and markdown-enable-wiki-links
8251 markdown-wiki-link-fontify-missing
)
8252 (add-hook 'after-change-functions
8253 #'markdown-check-change-for-wiki-link-after-change t t
)
8254 (remove-hook 'after-change-functions
8255 #'markdown-check-change-for-wiki-link-after-change t
))
8256 ;; If we left the buffer there is a really good chance we were
8257 ;; creating one of the wiki link documents. Make sure we get
8258 ;; refontified when we come back.
8259 (if (and markdown-enable-wiki-links
8260 markdown-wiki-link-fontify-missing
)
8262 (add-hook 'window-configuration-change-hook
8263 #'markdown-fontify-buffer-wiki-links t t
)
8264 (markdown-fontify-buffer-wiki-links))
8265 (remove-hook 'window-configuration-change-hook
8266 #'markdown-fontify-buffer-wiki-links t
)
8267 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
8270 ;;; Following & Doing =========================================================
8272 (defun markdown-follow-thing-at-point (arg)
8273 "Follow thing at point if possible, such as a reference link or wiki link.
8274 Opens inline and reference links in a browser. Opens wiki links
8275 to other files in the current window, or the another window if
8277 See `markdown-follow-link-at-point' and
8278 `markdown-follow-wiki-link-at-point'."
8280 (cond ((markdown-link-p)
8281 (markdown--browse-url (markdown-link-url)))
8282 ((markdown-wiki-link-p)
8283 (markdown-follow-wiki-link-at-point arg
))
8285 (let* ((values (markdown-link-at-pos (point)))
8286 (url (nth 3 values
)))
8288 (user-error "Nothing to follow at point"))
8289 (markdown--browse-url url
)))))
8291 (defun markdown-do ()
8292 "Do something sensible based on context at point.
8293 Jumps between reference links and definitions; between footnote
8294 markers and footnote text."
8297 ;; Footnote definition
8298 ((markdown-footnote-text-positions)
8299 (markdown-footnote-return))
8301 ((markdown-footnote-marker-positions)
8302 (markdown-footnote-goto-text))
8304 ((thing-at-point-looking-at markdown-regex-link-reference
)
8305 (markdown-reference-goto-definition))
8306 ;; Reference definition
8307 ((thing-at-point-looking-at markdown-regex-reference-definition
)
8308 (markdown-reference-goto-link (match-string-no-properties 2)))
8310 ((or (markdown-link-p) (markdown-wiki-link-p))
8311 (markdown-follow-thing-at-point nil
))
8312 ;; GFM task list item
8313 ((markdown-gfm-task-list-item-at-point)
8314 (markdown-toggle-gfm-checkbox))
8316 ((markdown-table-at-point-p)
8317 (call-interactively #'markdown-table-align
))
8320 (markdown-insert-gfm-checkbox))))
8323 ;;; Miscellaneous =============================================================
8325 (defun markdown-compress-whitespace-string (str)
8326 "Compress whitespace in STR and return result.
8327 Leading and trailing whitespace is removed. Sequences of multiple
8328 spaces, tabs, and newlines are replaced with single spaces."
8329 (replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
8330 (replace-regexp-in-string "[ \t\n]+" " " str
)))
8332 (defun markdown--substitute-command-keys (string)
8333 "Like `substitute-command-keys' but, but prefers control characters.
8334 First pass STRING to `substitute-command-keys' and then
8335 substitute `C-i` for `TAB` and `C-m` for `RET`."
8336 (replace-regexp-in-string
8338 (replace-regexp-in-string
8339 "\\<RET\\>" "C-m" (substitute-command-keys string
) t
) t
))
8341 (defun markdown-line-number-at-pos (&optional pos
)
8342 "Return (narrowed) buffer line number at position POS.
8343 If POS is nil, use current buffer location.
8344 This is an exact copy of `line-number-at-pos' for use in emacs21."
8345 (let ((opoint (or pos
(point))) start
)
8347 (goto-char (point-min))
8348 (setq start
(point))
8351 (1+ (count-lines start
(point))))))
8353 (defun markdown-inside-link-p ()
8354 "Return t if point is within a link."
8356 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
8358 (defun markdown-line-is-reference-definition-p ()
8359 "Return whether the current line is a (non-footnote) reference definition."
8361 (move-beginning-of-line 1)
8362 (and (looking-at-p markdown-regex-reference-definition
)
8363 (not (looking-at-p "[ \t]*\\[^")))))
8365 (defun markdown-adaptive-fill-function ()
8366 "Return prefix for filling paragraph or nil if not determined."
8368 ;; List item inside blockquote
8369 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
8370 (replace-regexp-in-string
8371 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
8373 ((looking-at markdown-regex-blockquote
)
8374 (buffer-substring-no-properties (match-beginning 0) (match-end 2)))
8376 ((looking-at markdown-regex-list
)
8377 (match-string-no-properties 0))
8378 ;; Footnote definition
8379 ((looking-at-p markdown-regex-footnote-definition
)
8384 (defun markdown-fill-paragraph (&optional justify
)
8385 "Fill paragraph at or after point.
8386 This function is like \\[fill-paragraph], but it skips Markdown
8387 code blocks. If the point is in a code block, or just before one,
8388 do not fill. Otherwise, call `fill-paragraph' as usual. If
8389 JUSTIFY is non-nil, justify text as well. Since this function
8390 handles filling itself, it always returns t so that
8391 `fill-paragraph' doesn't run."
8393 (unless (or (markdown-code-block-at-point-p)
8395 (back-to-indentation)
8396 (skip-syntax-forward "-")
8397 (markdown-code-block-at-point-p)))
8398 (let ((fill-prefix (save-excursion
8399 (goto-char (line-beginning-position))
8400 (when (looking-at "\\([ \t]*>[ \t]*\\(?:>[ \t]*\\)+\\)")
8401 (match-string-no-properties 1)))))
8402 (fill-paragraph justify
)))
8405 (defun markdown-fill-forward-paragraph (&optional arg
)
8406 "Function used by `fill-paragraph' to move over ARG paragraphs.
8407 This is a `fill-forward-paragraph-function' for `markdown-mode'.
8408 It is called with a single argument specifying the number of
8409 paragraphs to move. Just like `forward-paragraph', it should
8410 return the number of paragraphs left to move."
8411 (or arg
(setq arg
1))
8413 ;; With positive ARG, move across ARG non-code-block paragraphs,
8414 ;; one at a time. When passing a code block, don't decrement ARG.
8415 (while (and (not (eobp))
8417 (= (forward-paragraph 1) 0)
8418 (or (markdown-code-block-at-pos (line-beginning-position 0))
8419 (setq arg
(1- arg
)))))
8420 ;; Move backward by one paragraph with negative ARG (always -1).
8421 (let ((start (point)))
8422 (setq arg
(forward-paragraph arg
))
8423 (while (and (not (eobp))
8424 (progn (move-to-left-margin) (not (eobp)))
8425 (looking-at-p paragraph-separate
))
8428 ;; Move point past whitespace following list marker.
8429 ((looking-at markdown-regex-list
)
8430 (goto-char (match-end 0)))
8431 ;; Move point past whitespace following pipe at beginning of line
8432 ;; to handle Pandoc line blocks.
8433 ((looking-at "^|\\s-*")
8434 (goto-char (match-end 0)))
8435 ;; Return point if the paragraph passed was a code block.
8436 ((markdown-code-block-at-pos (line-beginning-position 2))
8437 (goto-char start
)))))
8440 (defun markdown--inhibit-electric-quote ()
8441 "Function added to `electric-quote-inhibit-functions'.
8442 Return non-nil if the quote has been inserted inside a code block
8444 (let ((pos (1- (point))))
8445 (or (markdown-inline-code-at-pos pos
)
8446 (markdown-code-block-at-pos pos
))))
8449 ;;; Extension Framework =======================================================
8451 (defun markdown-reload-extensions ()
8452 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
8454 (when (derived-mode-p 'markdown-mode
)
8457 ;; Add or remove hooks related to extensions
8458 (markdown-setup-wiki-link-hooks)))
8460 (defun markdown-handle-local-variables ()
8461 "Run in `hack-local-variables-hook' to update font lock rules.
8462 Checks to see if there is actually a ‘markdown-mode’ file local variable
8463 before regenerating font-lock rules for extensions."
8464 (when (or (assoc 'markdown-enable-wiki-links file-local-variables-alist
)
8465 (assoc 'markdown-enable-math file-local-variables-alist
))
8466 (when (assoc 'markdown-enable-math file-local-variables-alist
)
8467 (markdown-toggle-math markdown-enable-math
))
8468 (markdown-reload-extensions)))
8471 ;;; Math Support ==============================================================
8473 (defconst markdown-mode-font-lock-keywords-math
8475 ;; Equation reference (eq:foo)
8476 '("\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" .
((1 markdown-markup-face
)
8477 (2 markdown-reference-face
)
8478 (3 markdown-markup-face
)))
8479 ;; Equation reference \eqref{foo}
8480 '("\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" .
((1 markdown-markup-face
)
8481 (2 markdown-reference-face
)
8482 (3 markdown-markup-face
))))
8483 "Font lock keywords to add and remove when toggling math support.")
8485 (defun markdown-toggle-math (&optional arg
)
8486 "Toggle support for inline and display LaTeX math expressions.
8487 With a prefix argument ARG, enable math mode if ARG is positive,
8488 and disable it otherwise. If called from Lisp, enable the mode
8489 if ARG is omitted or nil."
8490 (interactive (list (or current-prefix-arg
'toggle
)))
8491 (setq markdown-enable-math
8492 (if (eq arg
'toggle
)
8493 (not markdown-enable-math
)
8494 (> (prefix-numeric-value arg
) 0)))
8495 (if markdown-enable-math
8497 (font-lock-add-keywords
8498 'markdown-mode markdown-mode-font-lock-keywords-math
)
8499 (message "markdown-mode math support enabled"))
8500 (font-lock-remove-keywords
8501 'markdown-mode markdown-mode-font-lock-keywords-math
)
8502 (message "markdown-mode math support disabled"))
8503 (markdown-reload-extensions))
8506 ;;; GFM Checkboxes ============================================================
8508 (define-button-type 'markdown-gfm-checkbox-button
8510 'face
'markdown-gfm-checkbox-face
8511 'mouse-face
'markdown-highlight-face
8512 'action
#'markdown-toggle-gfm-checkbox-button
)
8514 (defun markdown-gfm-task-list-item-at-point (&optional bounds
)
8515 "Return non-nil if there is a GFM task list item at the point.
8516 Optionally, the list item BOUNDS may be given if available, as
8517 returned by `markdown-cur-list-item-bounds'. When a task list item
8518 is found, the return value is the same value returned by
8519 `markdown-cur-list-item-bounds'."
8521 (setq bounds
(markdown-cur-list-item-bounds)))
8522 (> (length (nth 5 bounds
)) 0))
8524 (defun markdown-insert-gfm-checkbox ()
8525 "Add GFM checkbox at point.
8527 Returns nil if non-applicable."
8529 (let ((bounds (markdown-cur-list-item-bounds)))
8531 (unless (cl-sixth bounds
)
8532 (let ((pos (+ (cl-first bounds
) (cl-fourth bounds
)))
8540 (syntax-propertize (+ (cl-second bounds
) 4))
8542 (unless (save-excursion
8543 (back-to-indentation)
8544 (or (markdown-list-item-at-point-p)
8545 (markdown-heading-at-point)
8546 (markdown-in-comment-p)
8547 (markdown-code-block-at-point-p)))
8548 (let ((pos (save-excursion
8549 (back-to-indentation)
8551 (markup (concat (or (save-excursion
8552 (beginning-of-line 0)
8553 (cl-fifth (markdown-cur-list-item-bounds)))
8554 markdown-unordered-list-item-prefix
)
8562 (syntax-propertize (line-end-position))
8565 (defun markdown-toggle-gfm-checkbox ()
8566 "Toggle GFM checkbox at point.
8567 Returns the resulting status as a string, either \"[x]\" or \"[ ]\".
8568 Returns nil if there is no task list item at the point."
8572 (let ((bounds (markdown-cur-list-item-bounds)))
8574 ;; Move to beginning of task list item
8575 (goto-char (cl-first bounds
))
8576 ;; Advance to column of first non-whitespace after marker
8577 (forward-char (cl-fourth bounds
))
8578 (cond ((looking-at "\\[ \\]")
8580 (if markdown-gfm-uppercase-checkbox
"[X]" "[x]")
8582 (match-string-no-properties 0))
8583 ((looking-at "\\[[xX]\\]")
8584 (replace-match "[ ]" nil t
)
8585 (match-string-no-properties 0))))))))
8587 (defun markdown-toggle-gfm-checkbox-button (button)
8588 "Toggle GFM checkbox BUTTON on click."
8591 (goto-char (button-start button
))
8592 (markdown-toggle-gfm-checkbox))))
8594 (defun markdown-make-gfm-checkboxes-buttons (start end
)
8595 "Make GFM checkboxes buttons in region between START and END."
8598 (let ((case-fold-search t
))
8600 (while (re-search-forward markdown-regex-gfm-checkbox end t
)
8601 (make-button (match-beginning 1) (match-end 1)
8602 :type
'markdown-gfm-checkbox-button
))))))
8604 ;; Called when any modification is made to buffer text.
8605 (defun markdown-gfm-checkbox-after-change-function (beg end _
)
8606 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
8607 BEG and END are the limits of scanned region."
8610 ;; Rescan between start of line from `beg' and start of line after `end'.
8611 (markdown-make-gfm-checkboxes-buttons
8612 (progn (goto-char beg
) (beginning-of-line) (point))
8613 (progn (goto-char end
) (forward-line 1) (point))))))
8615 (defun markdown-remove-gfm-checkbox-overlays ()
8616 "Remove all GFM checkbox overlays in buffer."
8620 (remove-overlays nil nil
'face
'markdown-gfm-checkbox-face
))))
8623 ;;; Display inline image ======================================================
8625 (defvar-local markdown-inline-image-overlays nil
)
8627 (defun markdown-remove-inline-images ()
8628 "Remove inline image overlays from image links in the buffer.
8629 This can be toggled with `markdown-toggle-inline-images'
8630 or \\[markdown-toggle-inline-images]."
8632 (mapc #'delete-overlay markdown-inline-image-overlays
)
8633 (setq markdown-inline-image-overlays nil
)
8634 (when (fboundp 'clear-image-cache
) (clear-image-cache)))
8636 (defcustom markdown-display-remote-images nil
8637 "If non-nil, download and display remote images.
8638 See also `markdown-inline-image-overlays'.
8640 Only image URLs specified with a protocol listed in
8641 `markdown-remote-image-protocols' are displayed."
8645 (defcustom markdown-remote-image-protocols
'("https")
8646 "List of protocols to use to download remote images.
8647 See also `markdown-display-remote-images'."
8649 :type
'(repeat string
))
8651 (defvar markdown--remote-image-cache
8652 (make-hash-table :test
'equal
)
8653 "A map from URLs to image paths.")
8655 (defun markdown--get-remote-image (url)
8656 "Retrieve the image path for a given URL."
8657 (or (gethash url markdown--remote-image-cache
)
8658 (let ((dl-path (make-temp-file "markdown-mode--image")))
8660 (url-copy-file url dl-path t
)
8661 (puthash url dl-path markdown--remote-image-cache
))))
8663 (defun markdown-display-inline-images ()
8664 "Add inline image overlays to image links in the buffer.
8665 This can be toggled with `markdown-toggle-inline-images'
8666 or \\[markdown-toggle-inline-images]."
8668 (unless (display-images-p)
8669 (error "Cannot show images"))
8673 (goto-char (point-min))
8674 (while (re-search-forward markdown-regex-link-inline nil t
)
8675 (let* ((start (match-beginning 0))
8676 (imagep (match-beginning 1))
8678 (file (match-string-no-properties 6)))
8680 (not (zerop (length file
))))
8681 (unless (file-exists-p file
)
8682 (let* ((download-file (funcall markdown-translate-filename-function file
))
8683 (valid-url (ignore-errors
8684 (member (downcase (url-type (url-generic-parse-url download-file
)))
8685 markdown-remote-image-protocols
))))
8686 (if (and markdown-display-remote-images valid-url
)
8687 (setq file
(markdown--get-remote-image download-file
))
8688 (when (not valid-url
)
8689 ;; strip query parameter
8690 (setq file
(replace-regexp-in-string "?.+\\'" "" file
))
8691 (unless (file-exists-p file
)
8692 (setq file
(url-unhex-string file
)))))))
8693 (when (file-exists-p file
)
8694 (let* ((abspath (if (file-name-absolute-p file
)
8696 (concat default-directory file
)))
8698 (cond ((and markdown-max-image-size
8699 (image-type-available-p 'imagemagick
))
8701 abspath
'imagemagick nil
8702 :max-width
(car markdown-max-image-size
)
8703 :max-height
(cdr markdown-max-image-size
)))
8704 (markdown-max-image-size
8705 (create-image abspath nil nil
8706 :max-width
(car markdown-max-image-size
)
8707 :max-height
(cdr markdown-max-image-size
)))
8708 (t (create-image abspath
)))))
8710 (let ((ov (make-overlay start end
)))
8711 (overlay-put ov
'display image
)
8712 (overlay-put ov
'face
'default
)
8713 (push ov markdown-inline-image-overlays
)))))))))))
8715 (defun markdown-toggle-inline-images ()
8716 "Toggle inline image overlays in the buffer."
8718 (if markdown-inline-image-overlays
8719 (markdown-remove-inline-images)
8720 (markdown-display-inline-images)))
8723 ;;; GFM Code Block Fontification ==============================================
8725 (defcustom markdown-fontify-code-blocks-natively nil
8726 "When non-nil, fontify code in code blocks using the native major mode.
8727 This only works for fenced code blocks where the language is
8728 specified where we can automatically determine the appropriate
8729 mode to use. The language to mode mapping may be customized by
8730 setting the variable `markdown-code-lang-modes'."
8734 :package-version
'(markdown-mode .
"2.3"))
8736 (defcustom markdown-fontify-code-block-default-mode nil
8737 "Default mode to use to fontify code blocks.
8738 This mode is used when automatic detection fails, such as for GFM
8739 code blocks with no language specified."
8741 :type
'(choice function
(const :tag
"None" nil
))
8742 :package-version
'(markdown-mode .
"2.4"))
8744 (defun markdown-toggle-fontify-code-blocks-natively (&optional arg
)
8745 "Toggle the native fontification of code blocks.
8746 With a prefix argument ARG, enable if ARG is positive,
8747 and disable otherwise."
8748 (interactive (list (or current-prefix-arg
'toggle
)))
8749 (setq markdown-fontify-code-blocks-natively
8750 (if (eq arg
'toggle
)
8751 (not markdown-fontify-code-blocks-natively
)
8752 (> (prefix-numeric-value arg
) 0)))
8753 (if markdown-fontify-code-blocks-natively
8754 (message "markdown-mode native code block fontification enabled")
8755 (message "markdown-mode native code block fontification disabled"))
8756 (markdown-reload-extensions))
8758 ;; This is based on `org-src-lang-modes' from org-src.el
8759 (defcustom markdown-code-lang-modes
8760 '(("ocaml" . tuareg-mode
) ("elisp" . emacs-lisp-mode
) ("ditaa" . artist-mode
)
8761 ("asymptote" . asy-mode
) ("dot" . fundamental-mode
) ("sqlite" . sql-mode
)
8762 ("calc" . fundamental-mode
) ("C" . c-mode
) ("cpp" . c
++-mode
)
8763 ("C++" . c
++-mode
) ("screen" . shell-script-mode
) ("shell" . sh-mode
)
8765 "Alist mapping languages to their major mode.
8766 The key is the language name, the value is the major mode. For
8767 many languages this is simple, but for language where this is not
8768 the case, this variable provides a way to simplify things on the
8769 user side. For example, there is no ocaml-mode in Emacs, but the
8770 mode to use is `tuareg-mode'."
8774 (string "Language name")
8775 (symbol "Major mode")))
8776 :package-version
'(markdown-mode .
"2.3"))
8778 (defun markdown-get-lang-mode (lang)
8779 "Return major mode that should be used for LANG.
8780 LANG is a string, and the returned major mode is a symbol."
8783 (nconc (list (cdr (assoc lang markdown-code-lang-modes
))
8784 (cdr (assoc (downcase lang
) markdown-code-lang-modes
)))
8785 (and (fboundp 'treesit-language-available-p
)
8786 (list (and (treesit-language-available-p (intern lang
))
8787 (intern (concat lang
"-ts-mode")))
8788 (and (treesit-language-available-p (intern (downcase lang
)))
8789 (intern (concat (downcase lang
) "-ts-mode")))))
8791 (intern (concat lang
"-mode"))
8792 (intern (concat (downcase lang
) "-mode"))))))
8794 (defun markdown-fontify-code-blocks-generic (matcher last
)
8795 "Add text properties to next code block from point to LAST.
8796 Use matching function MATCHER."
8797 (when (funcall matcher last
)
8800 (let* ((start (match-beginning 0))
8802 ;; Find positions outside opening and closing backquotes.
8803 (bol-prev (progn (goto-char start
)
8804 (if (bolp) (line-beginning-position 0) (line-beginning-position))))
8805 (eol-next (progn (goto-char end
)
8806 (if (bolp) (line-beginning-position 2) (line-beginning-position 3))))
8808 (if (and markdown-fontify-code-blocks-natively
8809 (or (setq lang
(markdown-code-block-lang))
8810 markdown-fontify-code-block-default-mode
))
8811 (markdown-fontify-code-block-natively lang start end
)
8812 (add-text-properties start end
'(face markdown-pre-face
)))
8813 ;; Set background for block as well as opening and closing lines.
8814 (font-lock-append-text-property
8815 bol-prev eol-next
'face
'markdown-code-face
)
8816 ;; Set invisible property for lines before and after, including newline.
8817 (add-text-properties bol-prev start
'(invisible markdown-markup
))
8818 (add-text-properties end eol-next
'(invisible markdown-markup
)))))
8821 (defun markdown-fontify-gfm-code-blocks (last)
8822 "Add text properties to next GFM code block from point to LAST."
8823 (markdown-fontify-code-blocks-generic 'markdown-match-gfm-code-blocks last
))
8825 (defun markdown-fontify-fenced-code-blocks (last)
8826 "Add text properties to next tilde fenced code block from point to LAST."
8827 (markdown-fontify-code-blocks-generic 'markdown-match-fenced-code-blocks last
))
8829 ;; Based on `org-src-font-lock-fontify-block' from org-src.el.
8830 (defun markdown-fontify-code-block-natively (lang start end
)
8831 "Fontify given GFM or fenced code block.
8832 This function is called by Emacs for automatic fontification when
8833 `markdown-fontify-code-blocks-natively' is non-nil. LANG is the
8834 language used in the block. START and END specify the block
8836 (let ((lang-mode (if lang
(markdown-get-lang-mode lang
)
8837 markdown-fontify-code-block-default-mode
)))
8838 (when (fboundp lang-mode
)
8839 (let ((string (buffer-substring-no-properties start end
))
8840 (modified (buffer-modified-p))
8841 (markdown-buffer (current-buffer)) pos next
)
8842 (remove-text-properties start end
'(face nil
))
8843 (with-current-buffer
8845 (concat " markdown-code-fontification:" (symbol-name lang-mode
)))
8846 ;; Make sure that modification hooks are not inhibited in
8847 ;; the org-src-fontification buffer in case we're called
8848 ;; from `jit-lock-function' (Bug#25132).
8849 (let ((inhibit-modification-hooks nil
))
8850 (delete-region (point-min) (point-max))
8851 (insert string
" ")) ;; so there's a final property change
8852 (unless (eq major-mode lang-mode
) (funcall lang-mode
))
8854 (setq pos
(point-min))
8855 (while (setq next
(next-single-property-change pos
'face
))
8856 (let ((val (get-text-property pos
'face
)))
8859 (+ start
(1- pos
)) (1- (+ start next
)) 'face
8860 val markdown-buffer
)))
8862 (add-text-properties
8864 '(font-lock-fontified t fontified t font-lock-multiline t
))
8865 (set-buffer-modified-p modified
)))))
8867 (require 'edit-indirect nil t
)
8868 (defvar edit-indirect-guess-mode-function
)
8869 (defvar edit-indirect-after-commit-functions
)
8871 (defun markdown--edit-indirect-after-commit-function (beg end
)
8872 "Corrective logic run on code block content from lines BEG to END.
8873 Restores code block indentation from BEG to END, and ensures trailing newlines
8874 at the END of code blocks."
8875 ;; ensure trailing newlines
8877 (unless (eq (char-before) ?
\n)
8879 ;; restore code block indentation
8880 (goto-char (- beg
1))
8881 (let ((block-indentation (current-indentation)))
8882 (when (> block-indentation
0)
8883 (indent-rigidly beg end block-indentation
)))
8886 (defun markdown-edit-code-block ()
8887 "Edit Markdown code block in an indirect buffer."
8890 (if (fboundp 'edit-indirect-region
)
8891 (let* ((bounds (markdown-get-enclosing-fenced-block-construct))
8892 (begin (and bounds
(not (null (nth 0 bounds
))) (goto-char (nth 0 bounds
)) (line-beginning-position 2)))
8893 (end (and bounds
(not (null (nth 1 bounds
))) (goto-char (nth 1 bounds
)) (line-beginning-position 1))))
8895 (let* ((indentation (and (goto-char (nth 0 bounds
)) (current-indentation)))
8896 (lang (markdown-code-block-lang))
8897 (mode (or (and lang
(markdown-get-lang-mode lang
))
8898 markdown-edit-code-block-default-mode
))
8899 (edit-indirect-guess-mode-function
8900 (lambda (_parent-buffer _beg _end
)
8902 (indirect-buf (edit-indirect-region begin end
'display-buffer
)))
8903 ;; reset `sh-shell' when indirect buffer
8904 (when (and (not (member system-type
'(ms-dos windows-nt
)))
8905 (member mode
'(shell-script-mode sh-mode
))
8906 (member lang
(append
8907 (mapcar (lambda (e) (symbol-name (car e
)))
8909 '("csh" "rc" "sh"))))
8910 (with-current-buffer indirect-buf
8911 (sh-set-shell lang
)))
8912 (when (> indentation
0) ;; un-indent in edit-indirect buffer
8913 (with-current-buffer indirect-buf
8914 (indent-rigidly (point-min) (point-max) (- indentation
)))))
8915 (user-error "Not inside a GFM or tilde fenced code block")))
8916 (when (y-or-n-p "Package edit-indirect needed to edit code blocks. Install it now? ")
8917 (progn (package-refresh-contents)
8918 (package-install 'edit-indirect
)
8919 (markdown-edit-code-block))))))
8922 ;;; Table Editing =============================================================
8924 ;; These functions were originally adapted from `org-table.el'.
8926 ;; General helper functions
8928 (defmacro markdown--with-gensyms
(symbols &rest body
)
8929 (declare (debug (sexp body
)) (indent 1))
8930 `(let ,(mapcar (lambda (s)
8931 `(,s
(make-symbol (concat "--" (symbol-name ',s
)))))
8935 (defun markdown--split-string (string &optional separators
)
8936 "Splits STRING into substrings at SEPARATORS.
8937 SEPARATORS is a regular expression. If nil it defaults to
8938 `split-string-default-separators'. This version returns no empty
8939 strings if there are matches at the beginning and end of string."
8940 (let ((start 0) notfirst list
)
8941 (while (and (string-match
8942 (or separators split-string-default-separators
)
8945 (= start
(match-beginning 0))
8946 (< start
(length string
)))
8948 (< (match-beginning 0) (length string
)))
8950 (or (eq (match-beginning 0) 0)
8951 (and (eq (match-beginning 0) (match-end 0))
8952 (eq (match-beginning 0) start
))
8953 (push (substring string start
(match-beginning 0)) list
))
8954 (setq start
(match-end 0)))
8955 (or (eq start
(length string
))
8956 (push (substring string start
) list
))
8959 (defun markdown--string-width (s)
8960 "Return width of string S.
8961 This version ignores characters with invisibility property
8964 (when (or (eq t buffer-invisibility-spec
)
8965 (member 'markdown-markup buffer-invisibility-spec
))
8966 (while (setq b
(text-property-any
8968 'invisible
'markdown-markup s
))
8971 (substring s
(or (next-single-property-change
8976 (defun markdown--remove-invisible-markup (s)
8977 "Remove Markdown markup from string S.
8978 This version removes characters with invisibility property
8981 (while (setq b
(text-property-any
8983 'invisible
'markdown-markup s
))
8986 (substring s
(or (next-single-property-change
8991 ;; Functions for maintaining tables
8993 (defvar markdown-table-at-point-p-function
#'markdown--table-at-point-p
8994 "Function to decide if point is inside a table.
8996 The indirection serves to differentiate between standard markdown
8997 tables and gfm tables which are less strict about the markup.")
8999 (defconst markdown-table-line-regexp
"^[ \t]*|"
9000 "Regexp matching any line inside a table.")
9002 (defconst markdown-table-hline-regexp
"^[ \t]*|[-:]"
9003 "Regexp matching hline inside a table.")
9005 (defconst markdown-table-dline-regexp
"^[ \t]*|[^-:]"
9006 "Regexp matching dline inside a table.")
9008 (defun markdown-table-at-point-p ()
9009 "Return non-nil when point is inside a table."
9010 (funcall markdown-table-at-point-p-function
))
9012 (defun markdown--table-at-point-p ()
9013 "Return non-nil when point is inside a table."
9016 (and (looking-at-p markdown-table-line-regexp
)
9017 (not (markdown-code-block-at-point-p)))))
9019 (defconst gfm-table-line-regexp
"^.?*|"
9020 "Regexp matching any line inside a table.")
9022 (defconst gfm-table-hline-regexp
"^-+\\(|-\\)+"
9023 "Regexp matching hline inside a table.")
9025 ;; GFM simplified tables syntax is as follows:
9026 ;; - A header line for the column names, this is any text
9027 ;; separated by `|'.
9028 ;; - Followed by a string -|-|- ..., the number of dashes is optional
9029 ;; but must be higher than 1. The number of separators should match
9030 ;; the number of columns.
9031 ;; - Followed by the rows of data, which has the same format as the
9039 (defun gfm--table-at-point-p ()
9040 "Return non-nil when point is inside a gfm-compatible table."
9041 (or (markdown--table-at-point-p)
9044 (when (looking-at-p gfm-table-line-regexp
)
9045 ;; we might be at the first line of the table, check if the
9046 ;; line below is the hline
9049 (looking-at-p gfm-table-hline-regexp
))
9050 ;; go up to find the header
9052 (while (looking-at-p gfm-table-line-regexp
)
9054 ((looking-at-p gfm-table-hline-regexp
)
9061 (defun markdown-table-hline-at-point-p ()
9062 "Return non-nil when point is on a hline in a table.
9063 This function assumes point is on a table."
9066 (looking-at-p markdown-table-hline-regexp
)))
9068 (defun markdown-table-begin ()
9069 "Find the beginning of the table and return its position.
9070 This function assumes point is on a table."
9072 (while (and (not (bobp))
9073 (markdown-table-at-point-p))
9076 (markdown-table-at-point-p))
9080 (defun markdown-table-end ()
9081 "Find the end of the table and return its position.
9082 This function assumes point is on a table."
9084 (while (and (not (eobp))
9085 (markdown-table-at-point-p))
9089 (defun markdown-table-get-dline ()
9090 "Return index of the table data line at point.
9091 This function assumes point is on a table."
9092 (let ((pos (point)) (end (markdown-table-end)) (cnt 0))
9094 (goto-char (markdown-table-begin))
9095 (while (and (re-search-forward
9096 markdown-table-dline-regexp end t
)
9098 (< (line-end-position) pos
))))
9101 (defun markdown--thing-at-wiki-link (pos)
9102 (when markdown-enable-wiki-links
9106 (thing-at-point-looking-at markdown-regex-wiki-link
)))))
9108 (defun markdown-table-get-column ()
9109 "Return table column at point.
9110 This function assumes point is on a table."
9111 (let ((pos (point)) (cnt 0))
9114 (while (search-forward "|" pos t
)
9115 (when (and (not (looking-back "\\\\|" (line-beginning-position)))
9116 (not (markdown--thing-at-wiki-link (match-beginning 0))))
9117 (setq cnt
(1+ cnt
)))))
9120 (defun markdown-table-get-cell (&optional n
)
9121 "Return the content of the cell in column N of current row.
9122 N defaults to column at point. This function assumes point is on
9124 (and n
(markdown-table-goto-column n
))
9125 (skip-chars-backward "^|\n") (backward-char 1)
9126 (if (looking-at "|[^|\r\n]*")
9127 (let* ((pos (match-beginning 0))
9128 (val (buffer-substring (1+ pos
) (match-end 0))))
9129 (goto-char (min (line-end-position) (+ 2 pos
)))
9131 (setq val
(replace-regexp-in-string "\\`[ \t]+" "" val
)
9132 val
(replace-regexp-in-string "[ \t]+\\'" "" val
)))
9133 (forward-char 1) ""))
9135 (defun markdown-table-goto-dline (n)
9136 "Go to the Nth data line in the table at point.
9137 Return t when the line exists, nil otherwise. This function
9138 assumes point is on a table."
9139 (goto-char (markdown-table-begin))
9140 (let ((end (markdown-table-end)) (cnt 0))
9141 (while (and (re-search-forward
9142 markdown-table-dline-regexp end t
)
9143 (< (setq cnt
(1+ cnt
)) n
)))
9146 (defun markdown-table-goto-column (n &optional on-delim
)
9147 "Go to the Nth column in the table line at point.
9148 With optional argument ON-DELIM, stop with point before the left
9149 delimiter of the cell. If there are less than N cells, just go
9150 beyond the last delimiter. This function assumes point is on a
9152 (beginning-of-line 1)
9154 (while (and (> n
0) (search-forward "|" (line-end-position) t
))
9155 (when (and (not (looking-back "\\\\|" (line-beginning-position)))
9156 (not (markdown--thing-at-wiki-link (match-beginning 0))))
9160 (when (looking-at " ") (forward-char 1)))))
9162 (defmacro markdown-table-save-cell
(&rest body
)
9163 "Save cell at point, execute BODY and restore cell.
9164 This function assumes point is on a table."
9165 (declare (debug (body)))
9166 (markdown--with-gensyms (line column
)
9167 `(let ((,line
(copy-marker (line-beginning-position)))
9168 (,column
(markdown-table-get-column)))
9172 (markdown-table-goto-column ,column
)
9173 (set-marker ,line nil
)))))
9175 (defun markdown-table-blank-line (s)
9176 "Convert a table line S into a line with blank cells."
9177 (if (string-match "^[ \t]*|-" s
)
9179 (lambda (x) (if (member x
'(?| ?
+)) "|" " "))
9183 (goto-char (point-min))
9184 (when (re-search-forward "|" nil t
)
9187 (while (re-search-forward "|" nil t
)
9188 (when (and (not (eql (char-before (match-beginning 0)) ?
\\))
9189 (not (markdown--thing-at-wiki-link (match-beginning 0))))
9190 (push (make-string (- (match-beginning 0) cur
) ?
) ret
)
9191 (setq cur
(match-end 0))))
9192 (format "|%s|" (string-join (nreverse ret
) "|")))))))
9194 (defun markdown-table-colfmt (fmtspec)
9195 "Process column alignment specifier FMTSPEC for tables."
9196 (when (stringp fmtspec
)
9198 (cond ((string-match-p "^:.*:$" x
) 'c
)
9199 ((string-match-p "^:" x
) 'l
)
9200 ((string-match-p ":$" x
) 'r
)
9202 (markdown--split-string fmtspec
"\\s-*|\\s-*"))))
9204 (defun markdown--first-column-p (bar-pos)
9208 (looking-back "^\\s-*" (line-beginning-position)))))
9210 (defun markdown--table-line-to-columns (line)
9213 (goto-char (point-min))
9216 (while (re-search-forward "\\s-*\\(|\\)\\s-*" nil t
)
9217 (if (markdown--first-column-p (match-beginning 1))
9218 (setq cur
(match-end 0))
9219 (cond ((eql (char-before (match-beginning 1)) ?
\\)
9221 (goto-char (match-end 1)))
9222 ((markdown--thing-at-wiki-link (match-beginning 1))) ;; do nothing
9224 (push (buffer-substring-no-properties cur
(match-beginning 0)) ret
)
9225 (setq cur
(match-end 0))))))
9226 (when (< cur
(length line
))
9227 (push (buffer-substring-no-properties cur
(point-max)) ret
))
9230 (defsubst markdown--is-delimiter-row
(line)
9231 (and (string-match-p "\\`[ \t]*|[ \t]*[-:]" line
)
9232 (cl-loop for c across line
9233 always
(member c
'(?| ?- ?
: ?
\t ?
)))))
9235 (defun markdown-table-align ()
9236 "Align table at point.
9237 This function assumes point is on a table."
9239 (let ((begin (markdown-table-begin))
9240 (end (copy-marker (markdown-table-end))))
9241 (markdown-table-save-cell
9244 ;; Store table indent
9245 (indent (progn (looking-at "[ \t]*") (match-string 0)))
9246 ;; Split table in lines and save column format specifier
9247 (lines (mapcar (lambda (line)
9248 (if (markdown--is-delimiter-row line
)
9249 (progn (setq fmtspec
(or fmtspec line
)) nil
)
9251 (markdown--split-string (buffer-substring begin end
) "\n")))
9252 ;; Split lines in cells
9253 (cells (mapcar (lambda (l) (markdown--table-line-to-columns l
))
9255 ;; Calculate maximum number of cells in a line
9257 (apply #'max
(mapcar #'length cells
))
9258 (user-error "Empty table")))
9259 ;; Empty cells to fill short lines
9260 (emptycells (make-list maxcells
""))
9262 ;; Calculate maximum width for each column
9263 (dotimes (i maxcells
)
9264 (let ((column (mapcar (lambda (x) (or (nth i x
) "")) cells
)))
9265 (push (apply #'max
1 (mapcar #'markdown--string-width column
))
9267 (setq maxwidths
(nreverse maxwidths
))
9268 ;; Process column format specifier
9269 (setq fmtspec
(markdown-table-colfmt fmtspec
))
9270 ;; Compute formats needed for output of table lines
9271 (let ((hfmt (concat indent
"|"))
9272 (rfmt (concat indent
"|"))
9274 (dolist (width maxwidths
(setq hfmt
(concat (substring hfmt
0 -
1) "|")))
9275 (setq fmt
(pop fmtspec
))
9276 (cond ((equal fmt
'l
) (setq hfmt1
":%s-|" rfmt1
" %%-%ds |"))
9277 ((equal fmt
'r
) (setq hfmt1
"-%s:|" rfmt1
" %%%ds |"))
9278 ((equal fmt
'c
) (setq hfmt1
":%s:|" rfmt1
" %%-%ds |"))
9279 (t (setq hfmt1
"-%s-|" rfmt1
" %%-%ds |")))
9280 (setq rfmt
(concat rfmt
(format rfmt1 width
)))
9281 (setq hfmt
(concat hfmt
(format hfmt1
(make-string width ?-
)))))
9282 ;; Replace modified lines only
9283 (dolist (line lines
)
9284 (let ((line (if line
9285 (apply #'format rfmt
(append (pop cells
) emptycells
))
9287 (previous (buffer-substring (point) (line-end-position))))
9288 (if (equal previous line
)
9291 (delete-region (point) (line-beginning-position 2))))))
9292 (set-marker end nil
)))))
9294 (defun markdown-table-insert-row (&optional arg
)
9295 "Insert a new row above the row at point into the table.
9296 With optional argument ARG, insert below the current row."
9298 (unless (markdown-table-at-point-p)
9299 (user-error "Not at a table"))
9300 (let* ((line (buffer-substring
9301 (line-beginning-position) (line-end-position)))
9302 (new (markdown-table-blank-line line
)))
9303 (beginning-of-line (if arg
2 1))
9304 (unless (bolp) (insert "\n"))
9305 (insert-before-markers new
"\n")
9306 (beginning-of-line 0)
9307 (re-search-forward "| ?" (line-end-position) t
)))
9309 (defun markdown-table-delete-row ()
9310 "Delete row or horizontal line at point from the table."
9312 (unless (markdown-table-at-point-p)
9313 (user-error "Not at a table"))
9314 (let ((col (current-column)))
9315 (kill-region (line-beginning-position)
9316 (min (1+ (line-end-position)) (point-max)))
9317 (unless (markdown-table-at-point-p) (beginning-of-line 0))
9318 (move-to-column col
)))
9320 (defun markdown-table-move-row (&optional up
)
9321 "Move table line at point down.
9322 With optional argument UP, move it up."
9324 (unless (markdown-table-at-point-p)
9325 (user-error "Not at a table"))
9326 (let* ((col (current-column)) (pos (point))
9327 (tonew (if up
0 2)) txt
)
9328 (beginning-of-line tonew
)
9329 (unless (markdown-table-at-point-p)
9330 (goto-char pos
) (user-error "Cannot move row further"))
9331 (goto-char pos
) (beginning-of-line 1) (setq pos
(point))
9332 (setq txt
(buffer-substring (point) (1+ (line-end-position))))
9333 (delete-region (point) (1+ (line-end-position)))
9334 (beginning-of-line tonew
)
9335 (insert txt
) (beginning-of-line 0)
9336 (move-to-column col
)))
9338 (defun markdown-table-move-row-up ()
9339 "Move table row at point up."
9341 (markdown-table-move-row 'up
))
9343 (defun markdown-table-move-row-down ()
9344 "Move table row at point down."
9346 (markdown-table-move-row nil
))
9348 (defun markdown-table-insert-column ()
9349 "Insert a new table column."
9351 (unless (markdown-table-at-point-p)
9352 (user-error "Not at a table"))
9353 (let* ((col (max 1 (markdown-table-get-column)))
9354 (begin (markdown-table-begin))
9355 (end (copy-marker (markdown-table-end))))
9356 (markdown-table-save-cell
9358 (while (< (point) end
)
9359 (markdown-table-goto-column col t
)
9360 (if (markdown-table-hline-at-point-p)
9364 (set-marker end nil
)
9365 (when markdown-table-align-p
9366 (markdown-table-align))))
9368 (defun markdown-table-delete-column ()
9369 "Delete column at point from table."
9371 (unless (markdown-table-at-point-p)
9372 (user-error "Not at a table"))
9373 (let ((col (markdown-table-get-column))
9374 (begin (markdown-table-begin))
9375 (end (copy-marker (markdown-table-end))))
9376 (markdown-table-save-cell
9378 (while (< (point) end
)
9379 (markdown-table-goto-column col t
)
9380 (and (looking-at "|\\(?:\\\\|\\|[^|\n]\\)+|")
9381 (replace-match "|"))
9383 (set-marker end nil
)
9384 (markdown-table-goto-column (max 1 (1- col
)))
9385 (when markdown-table-align-p
9386 (markdown-table-align))))
9388 (defun markdown-table-move-column (&optional left
)
9389 "Move table column at point to the right.
9390 With optional argument LEFT, move it to the left."
9392 (unless (markdown-table-at-point-p)
9393 (user-error "Not at a table"))
9394 (let* ((col (markdown-table-get-column))
9395 (col1 (if left
(1- col
) col
))
9396 (colpos (if left
(1- col
) (1+ col
)))
9397 (begin (markdown-table-begin))
9398 (end (copy-marker (markdown-table-end))))
9399 (when (and left
(= col
1))
9400 (user-error "Cannot move column further left"))
9401 (when (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
9402 (user-error "Cannot move column further right"))
9403 (markdown-table-save-cell
9405 (while (< (point) end
)
9406 (markdown-table-goto-column col1 t
)
9407 (when (looking-at "|\\(\\(?:\\\\|\\|[^|\n]\\|\\)+\\)|\\(\\(?:\\\\|\\|[^|\n]\\|\\)+\\)|")
9408 (replace-match "|\\2|\\1|"))
9410 (set-marker end nil
)
9411 (markdown-table-goto-column colpos
)
9412 (when markdown-table-align-p
9413 (markdown-table-align))))
9415 (defun markdown-table-move-column-left ()
9416 "Move table column at point to the left."
9418 (markdown-table-move-column 'left
))
9420 (defun markdown-table-move-column-right ()
9421 "Move table column at point to the right."
9423 (markdown-table-move-column nil
))
9425 (defun markdown-table-next-row ()
9426 "Go to the next row (same column) in the table.
9427 Create new table lines if required."
9429 (unless (markdown-table-at-point-p)
9430 (user-error "Not at a table"))
9431 (if (or (looking-at "[ \t]*$")
9432 (save-excursion (skip-chars-backward " \t") (bolp)))
9434 (when markdown-table-align-p
9435 (markdown-table-align))
9436 (let ((col (markdown-table-get-column)))
9437 (beginning-of-line 2)
9438 (if (or (not (markdown-table-at-point-p))
9439 (markdown-table-hline-at-point-p))
9441 (beginning-of-line 0)
9442 (markdown-table-insert-row 'below
)))
9443 (markdown-table-goto-column col
)
9444 (skip-chars-backward "^|\n\r")
9445 (when (looking-at " ") (forward-char 1)))))
9447 (defun markdown-table-forward-cell ()
9448 "Go to the next cell in the table.
9449 Create new table lines if required."
9451 (unless (markdown-table-at-point-p)
9452 (user-error "Not at a table"))
9453 (when markdown-table-align-p
9454 (markdown-table-align))
9455 (let ((end (markdown-table-end)))
9456 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9459 (re-search-forward "\\(?:^\\|[^\\]\\)|" end
)
9460 (when (looking-at "[ \t]*$")
9461 (re-search-forward "\\(?:^\\|[^\\]:\\)|" end
))
9462 (when (and (looking-at "[-:]")
9463 (re-search-forward "^\\(?:[ \t]*\\|[^\\]\\)|\\([^-:]\\)" end t
))
9464 (goto-char (match-beginning 1)))
9465 (if (looking-at "[-:]")
9467 (beginning-of-line 0)
9468 (markdown-table-insert-row 'below
))
9469 (when (looking-at " ") (forward-char 1))))
9470 (error (markdown-table-insert-row 'below
)))))
9472 (defun markdown-table-backward-cell ()
9473 "Go to the previous cell in the table."
9475 (unless (markdown-table-at-point-p)
9476 (user-error "Not at a table"))
9477 (when markdown-table-align-p
9478 (markdown-table-align))
9479 (when (markdown-table-hline-at-point-p) (beginning-of-line 1))
9482 (re-search-backward "\\(?:^\\|[^\\]\\)|" (markdown-table-begin))
9483 ;; When this function is called while in the first cell in a
9484 ;; table, the point will now be at the beginning of a line. In
9485 ;; this case, we need to move past one additional table
9486 ;; boundary, the end of the table on the previous line.
9487 (when (= (point) (line-beginning-position))
9488 (re-search-backward "\\(?:^\\|[^\\]\\)|" (markdown-table-begin)))
9489 (re-search-backward "\\(?:^\\|[^\\]\\)|" (markdown-table-begin)))
9490 (error (user-error "Cannot move to previous table cell")))
9491 (when (looking-at "\\(?:^\\|[^\\]\\)| ?") (goto-char (match-end 0)))
9493 ;; This may have dropped point on the hline.
9494 (when (markdown-table-hline-at-point-p)
9495 (markdown-table-backward-cell)))
9497 (defun markdown-table-transpose ()
9498 "Transpose table at point.
9499 Horizontal separator lines will be eliminated."
9501 (unless (markdown-table-at-point-p)
9502 (user-error "Not at a table"))
9503 (let* ((table (buffer-substring-no-properties
9504 (markdown-table-begin) (markdown-table-end)))
9505 ;; Convert table to Lisp structure
9509 (unless (string-match-p
9510 markdown-table-hline-regexp x
)
9511 (markdown--table-line-to-columns x
)))
9512 (markdown--split-string table
"[ \t]*\n[ \t]*"))))
9513 (dline_old (markdown-table-get-dline))
9514 (col_old (markdown-table-get-column))
9515 (contents (mapcar (lambda (_)
9521 (setq tp
(cdr tp
))))
9524 (goto-char (markdown-table-begin))
9526 (re-search-forward "|") (backward-char)
9527 (delete-region (point) (markdown-table-end))
9530 (concat "| " (mapconcat 'identity x
" | " ) " |\n"))
9532 (markdown-table-goto-dline col_old
)
9533 (markdown-table-goto-column dline_old
))
9534 (when markdown-table-align-p
9535 (markdown-table-align)))
9537 (defun markdown-table-sort-lines (&optional sorting-type
)
9538 "Sort table lines according to the column at point.
9540 The position of point indicates the column to be used for
9541 sorting, and the range of lines is the range between the nearest
9542 horizontal separator lines, or the entire table of no such lines
9543 exist. If point is before the first column, user will be prompted
9544 for the sorting column. If there is an active region, the mark
9545 specifies the first line and the sorting column, while point
9546 should be in the last line to be included into the sorting.
9548 The command then prompts for the sorting type which can be
9549 alphabetically or numerically. Sorting in reverse order is also
9552 If SORTING-TYPE is specified when this function is called from a
9553 Lisp program, no prompting will take place. SORTING-TYPE must be
9554 a character, any of (?a ?A ?n ?N) where the capital letters
9555 indicate that sorting should be done in reverse order."
9557 (unless (markdown-table-at-point-p)
9558 (user-error "Not at a table"))
9559 ;; Set sorting type and column used for sorting
9560 (let ((column (let ((c (markdown-table-get-column)))
9562 ((called-interactively-p 'any
)
9563 (read-number "Use column N for sorting: "))
9569 ;; Emacs < 28 hides prompt message by another message. This erases it.
9571 (read-char-exclusive
9572 "Sort type: [a]lpha [n]umeric (A/N means reversed): ")))))
9574 ;; Narrow buffer to appropriate sorting area
9575 (if (region-active-p)
9579 (goto-char (region-beginning)) (line-beginning-position)))
9582 (goto-char (region-end)) (line-end-position))))
9583 (let ((start (markdown-table-begin))
9584 (end (markdown-table-end)))
9587 (if (re-search-backward
9588 markdown-table-hline-regexp start t
)
9589 (line-beginning-position 2)
9591 (if (save-excursion (re-search-forward
9592 markdown-table-hline-regexp end t
))
9595 ;; Determine arguments for `sort-subr'
9596 (let* ((extract-key-from-cell
9597 (cl-case sorting-type
9598 ((?a ?A
) #'markdown--remove-invisible-markup
) ;; #'identity)
9599 ((?n ?N
) #'string-to-number
)
9600 (t (user-error "Invalid sorting type: %c" sorting-type
))))
9602 (cl-case sorting-type
9604 ((?a ?A
) #'string
<))))
9605 ;; Sort selected area
9606 (goto-char (point-min))
9607 (sort-subr (memq sorting-type
'(?A ?N
))
9610 (while (and (not (eobp))
9612 markdown-table-dline-regexp
)))
9616 (funcall extract-key-from-cell
9617 (markdown-table-get-cell column
)))
9620 (goto-char (point-min))))))
9622 (defun markdown-table-convert-region (begin end
&optional separator
)
9623 "Convert region from BEGIN to END to table with SEPARATOR.
9625 If every line contains at least one TAB character, the function
9626 assumes that the material is tab separated (TSV). If every line
9627 contains a comma, comma-separated values (CSV) are assumed. If
9628 not, lines are split at whitespace into cells.
9630 You can use a prefix argument to force a specific separator:
9631 \\[universal-argument] once forces CSV, \\[universal-argument]
9632 twice forces TAB, and \\[universal-argument] three times will
9633 prompt for a regular expression to match the separator, and a
9634 numeric argument N indicates that at least N consecutive
9635 spaces, or alternatively a TAB should be used as the separator."
9637 (interactive "r\nP")
9638 (let* ((begin (min begin end
)) (end (max begin end
)) re
)
9639 (goto-char begin
) (beginning-of-line 1)
9640 (setq begin
(point-marker))
9642 (if (bolp) (backward-char 1) (end-of-line 1))
9643 (setq end
(point-marker))
9644 (when (equal separator
'(64))
9645 (setq separator
(read-regexp "Regexp for cell separator: ")))
9647 ;; Get the right cell separator
9651 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
9652 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
9655 (if (equal separator
'(4))
9657 (while (< (point) end
)
9659 ((looking-at "^") (insert "| "))
9660 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
9661 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
9662 (replace-match "\\1") (if (looking-at "\"") (insert "\"")))
9663 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
9664 ((looking-at "[ \t]*,") (replace-match " | "))
9665 (t (beginning-of-line 2))))
9668 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
9669 ((equal separator
'(16)) "^\\|\t")
9670 ((integerp separator
)
9672 (user-error "Cell separator must contain one or more spaces")
9673 (format "^ *\\| *\t *\\| \\{%d,\\}\\|$" separator
)))
9674 ((stringp separator
) (format "^ *\\|%s" separator
))
9675 (t (error "Invalid cell separator"))))
9677 (while (and (not finish
) (re-search-forward re end t
))
9680 (replace-match "|" t t
)
9684 (replace-match "| " t t
)))))
9686 (when markdown-table-align-p
9687 (markdown-table-align))))
9689 (defun markdown-insert-table (&optional rows columns align
)
9690 "Insert an empty pipe table.
9691 Optional arguments ROWS, COLUMNS, and ALIGN specify number of
9692 rows and columns and the column alignment."
9694 (let* ((rows (or rows
(string-to-number (read-string "Row size: "))))
9695 (columns (or columns
(string-to-number (read-string "Column size: "))))
9696 (align (or align
(read-string "Alignment ([l]eft, [r]ight, [c]enter, or RET for default): ")))
9697 (align (cond ((equal align
"l") ":--")
9698 ((equal align
"r") "--:")
9699 ((equal align
"c") ":-:")
9702 (indent (make-string (current-column) ?\
))
9704 (apply 'concat indent
"|"
9705 (make-list columns
" |")) "\n"))
9706 (hline (apply 'concat indent
"|"
9707 (make-list columns
(concat align
"|")))))
9709 "^[ \t]*$" (buffer-substring-no-properties
9710 (line-beginning-position) (point)))
9711 (beginning-of-line 1)
9713 (dotimes (_ rows
) (insert line
))
9717 (end-of-line 1) (insert (concat "\n" hline
)) (goto-char pos
)))
9718 (markdown-table-forward-cell)))
9721 ;;; ElDoc Support =============================================================
9723 (defun markdown-eldoc-function (&rest _ignored
)
9724 "Return a helpful string when appropriate based on context.
9725 * Report URL when point is at a hidden URL.
9726 * Report language name when point is a code block with hidden markup."
9728 ;; Hidden URL or reference for inline link
9729 ((and (or (thing-at-point-looking-at markdown-regex-link-inline
)
9730 (thing-at-point-looking-at markdown-regex-link-reference
))
9731 (or markdown-hide-urls markdown-hide-markup
))
9732 (let* ((imagep (string-equal (match-string 1) "!"))
9733 (referencep (string-equal (match-string 5) "["))
9734 (link (match-string-no-properties 6))
9735 (edit-keys (markdown--substitute-command-keys
9737 "\\[markdown-insert-image]"
9738 "\\[markdown-insert-link]")))
9739 (edit-str (propertize edit-keys
'face
'font-lock-constant-face
))
9740 (object (if referencep
"reference" "URL")))
9741 (format "Hidden %s (%s to edit): %s" object edit-str
9744 (propertize "[" 'face
'markdown-markup-face
)
9745 (propertize link
'face
'markdown-reference-face
)
9746 (propertize "]" 'face
'markdown-markup-face
))
9747 (propertize link
'face
'markdown-url-face
)))))
9748 ;; Hidden language name for fenced code blocks
9749 ((and (markdown-code-block-at-point-p)
9750 (not (get-text-property (point) 'markdown-pre
))
9751 markdown-hide-markup
)
9752 (let ((lang (save-excursion (markdown-code-block-lang))))
9753 (unless lang
(setq lang
"[unspecified]"))
9754 (format "Hidden code block language: %s (%s to toggle markup)"
9755 (propertize lang
'face
'markdown-language-keyword-face
)
9756 (markdown--substitute-command-keys
9757 "\\[markdown-toggle-markup-hiding]"))))))
9760 ;;; Mode Definition ==========================================================
9762 (defun markdown-show-version ()
9763 "Show the version number in the minibuffer."
9765 (message "markdown-mode, version %s" markdown-mode-version
))
9767 (defun markdown-mode-info ()
9768 "Open the `markdown-mode' homepage."
9770 (browse-url "https://jblevins.org/projects/markdown-mode/"))
9773 (define-derived-mode markdown-mode text-mode
"Markdown"
9774 "Major mode for editing Markdown files."
9775 (when buffer-read-only
9776 (when (or (not (buffer-file-name)) (file-writable-p (buffer-file-name)))
9777 (setq-local buffer-read-only nil
)))
9778 ;; Natural Markdown tab width
9781 (setq-local comment-start
"<!-- ")
9782 (setq-local comment-end
" -->")
9783 (setq-local comment-start-skip
"<!--[ \t]*")
9784 (setq-local comment-column
0)
9785 (setq-local comment-auto-fill-only-comments nil
)
9786 (setq-local comment-use-syntax t
)
9788 (setq-local sentence-end-base
"[.?!…‽][]\"'”’)}»›*_`~]*")
9790 (add-hook 'syntax-propertize-extend-region-functions
9791 #'markdown-syntax-propertize-extend-region nil t
)
9792 (add-hook 'jit-lock-after-change-extend-region-functions
9793 #'markdown-font-lock-extend-region-function t t
)
9794 (setq-local syntax-propertize-function
#'markdown-syntax-propertize
)
9795 (syntax-propertize (point-max)) ;; Propertize before hooks run, etc.
9797 (setq font-lock-defaults
9798 '(markdown-mode-font-lock-keywords
9800 (font-lock-multiline . t
)
9801 (font-lock-syntactic-face-function . markdown-syntactic-face
)
9802 (font-lock-extra-managed-props
9803 .
(composition display invisible rear-nonsticky
9804 keymap help-echo mouse-face
))))
9805 (if markdown-hide-markup
9806 (add-to-invisibility-spec 'markdown-markup
)
9807 (remove-from-invisibility-spec 'markdown-markup
))
9809 (markdown-setup-wiki-link-hooks)
9811 (when markdown-enable-math
(markdown-toggle-math t
))
9812 ;; Add a buffer-local hook to reload after file-local variables are read
9813 (add-hook 'hack-local-variables-hook
#'markdown-handle-local-variables nil t
)
9814 ;; For imenu support
9815 (setq imenu-create-index-function
9816 (if markdown-nested-imenu-heading-index
9817 #'markdown-imenu-create-nested-index
9818 #'markdown-imenu-create-flat-index
))
9821 (setq-local beginning-of-defun-function
#'markdown-beginning-of-defun
)
9822 (setq-local end-of-defun-function
#'markdown-end-of-defun
)
9823 ;; Paragraph filling
9824 (setq-local fill-paragraph-function
#'markdown-fill-paragraph
)
9825 (setq-local paragraph-start
9826 ;; Should match start of lines that start or separate paragraphs
9827 (mapconcat #'identity
9829 "\f" ; starts with a literal line-feed
9830 "[ \t\f]*$" ; space-only line
9831 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9832 "[ \t]*[*+-][ \t]+" ; unordered list item
9833 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
9834 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
9835 "[ \t]*:[ \t]+" ; definition
9836 "^|" ; table or Pandoc line block
9839 (setq-local paragraph-separate
9840 ;; Should match lines that separate paragraphs without being
9841 ;; part of any paragraph:
9842 (mapconcat #'identity
9843 '("[ \t\f]*$" ; space-only line
9844 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9845 ;; The following is not ideal, but the Fill customization
9846 ;; options really only handle paragraph-starting prefixes,
9847 ;; not paragraph-ending suffixes:
9848 ".* $" ; line ending in two spaces
9850 "^\\(?: \\)?[-=]+[ \t]*$" ;; setext
9851 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
9853 (setq-local adaptive-fill-first-line-regexp
"\\`[ \t]*[A-Z]?>[ \t]*?\\'")
9854 (setq-local adaptive-fill-regexp
"\\s-*")
9855 (setq-local adaptive-fill-function
#'markdown-adaptive-fill-function
)
9856 (setq-local fill-forward-paragraph-function
#'markdown-fill-forward-paragraph
)
9858 (setq-local outline-regexp markdown-regex-header
)
9859 (setq-local outline-level
#'markdown-outline-level
)
9860 ;; Cause use of ellipses for invisible text.
9861 (add-to-invisibility-spec '(outline . t
))
9863 (if (boundp 'eldoc-documentation-functions
)
9864 (add-hook 'eldoc-documentation-functions
#'markdown-eldoc-function nil t
)
9865 (add-function :before-until
(local 'eldoc-documentation-function
)
9866 #'markdown-eldoc-function
))
9867 ;; Inhibiting line-breaking:
9868 ;; Separating out each condition into a separate function so that users can
9869 ;; override if desired (with remove-hook)
9870 (add-hook 'fill-nobreak-predicate
9871 #'markdown-line-is-reference-definition-p nil t
)
9872 (add-hook 'fill-nobreak-predicate
9873 #'markdown-pipe-at-bol-p nil t
)
9876 (setq-local indent-line-function markdown-indent-function
)
9877 (setq-local indent-region-function
#'markdown--indent-region
)
9880 (setq-local flyspell-generic-check-word-predicate
9881 #'markdown-flyspell-check-word-p
)
9884 (add-hook 'electric-quote-inhibit-functions
9885 #'markdown--inhibit-electric-quote nil
:local
)
9887 ;; Make checkboxes buttons
9888 (when markdown-make-gfm-checkboxes-buttons
9889 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
9890 (add-hook 'after-change-functions
#'markdown-gfm-checkbox-after-change-function t t
)
9891 (add-hook 'change-major-mode-hook
#'markdown-remove-gfm-checkbox-overlays t t
))
9894 (add-hook 'edit-indirect-after-commit-functions
9895 #'markdown--edit-indirect-after-commit-function
9898 ;; Marginalized headings
9899 (when markdown-marginalize-headers
9900 (add-hook 'window-configuration-change-hook
9901 #'markdown-marginalize-update-current nil t
))
9903 ;; add live preview export hook
9904 (add-hook 'after-save-hook
#'markdown-live-preview-if-markdown t t
)
9905 (add-hook 'kill-buffer-hook
#'markdown-live-preview-remove-on-kill t t
))
9908 (add-to-list 'auto-mode-alist
9909 '("\\.\\(?:md\\|markdown\\|mkd\\|mdown\\|mkdn\\|mdwn\\)\\'" . markdown-mode
))
9912 ;;; GitHub Flavored Markdown Mode ============================================
9914 (defun gfm--electric-pair-fence-code-block ()
9915 (when (and electric-pair-mode
9916 (not markdown-gfm-use-electric-backquote
)
9917 (eql last-command-event ?
`)
9919 (while (eql (char-before (- (point) count
)) ?
`)
9922 (eql (char-after) ?
`))
9923 (save-excursion (insert (make-string 2 ?
`)))))
9925 (defvar gfm-mode-hook nil
9926 "Hook run when entering GFM mode.")
9929 (define-derived-mode gfm-mode markdown-mode
"GFM"
9930 "Major mode for editing GitHub Flavored Markdown files."
9931 (setq markdown-link-space-sub-char
"-")
9932 (setq markdown-wiki-link-search-subdirectories t
)
9933 (setq-local markdown-table-at-point-p-function
#'gfm--table-at-point-p
)
9934 (add-hook 'post-self-insert-hook
#'gfm--electric-pair-fence-code-block
'append t
)
9935 (markdown-gfm-parse-buffer-for-languages))
9938 ;;; Viewing modes =============================================================
9940 (defcustom markdown-hide-markup-in-view-modes t
9941 "Enable hidden markup mode in `markdown-view-mode' and `gfm-view-mode'."
9946 (defvar markdown-view-mode-map
9947 (let ((map (make-sparse-keymap)))
9948 (define-key map
(kbd "p") #'markdown-outline-previous
)
9949 (define-key map
(kbd "n") #'markdown-outline-next
)
9950 (define-key map
(kbd "f") #'markdown-outline-next-same-level
)
9951 (define-key map
(kbd "b") #'markdown-outline-previous-same-level
)
9952 (define-key map
(kbd "u") #'markdown-outline-up
)
9953 (define-key map
(kbd "DEL") #'scroll-down-command
)
9954 (define-key map
(kbd "SPC") #'scroll-up-command
)
9955 (define-key map
(kbd ">") #'end-of-buffer
)
9956 (define-key map
(kbd "<") #'beginning-of-buffer
)
9957 (define-key map
(kbd "q") #'kill-this-buffer
)
9958 (define-key map
(kbd "?") #'describe-mode
)
9960 "Keymap for `markdown-view-mode'.")
9962 (defun markdown--filter-visible (beg end
&optional delete
)
9964 (invisible-faces '(markdown-header-delimiter-face markdown-header-rule-face
)))
9966 (when (markdown--face-p beg invisible-faces
)
9968 (while (and (markdown--face-p beg invisible-faces
) (< beg end
))
9970 (let ((next (next-single-char-property-change beg
'invisible
)))
9971 (unless (get-char-property beg
'invisible
)
9972 (setq result
(concat result
(buffer-substring beg
(min end next
)))))
9976 (let ((inhibit-read-only t
))
9977 (delete-region beg end
))))))
9980 (define-derived-mode markdown-view-mode markdown-mode
"Markdown-View"
9981 "Major mode for viewing Markdown content."
9982 (setq-local markdown-hide-markup markdown-hide-markup-in-view-modes
)
9983 (add-to-invisibility-spec 'markdown-markup
)
9984 (setq-local filter-buffer-substring-function
#'markdown--filter-visible
)
9987 (defvar gfm-view-mode-map
9988 markdown-view-mode-map
9989 "Keymap for `gfm-view-mode'.")
9992 (define-derived-mode gfm-view-mode gfm-mode
"GFM-View"
9993 "Major mode for viewing GitHub Flavored Markdown content."
9994 (setq-local markdown-hide-markup markdown-hide-markup-in-view-modes
)
9995 (setq-local markdown-fontify-code-blocks-natively t
)
9996 (setq-local filter-buffer-substring-function
#'markdown--filter-visible
)
9997 (add-to-invisibility-spec 'markdown-markup
)
10001 ;;; Live Preview Mode ========================================================
10003 (define-minor-mode markdown-live-preview-mode
10004 "Toggle native previewing on save for a specific markdown file."
10005 :lighter
" MD-Preview"
10006 (if markdown-live-preview-mode
10007 (if (markdown-live-preview-get-filename)
10008 (markdown-display-buffer-other-window (markdown-live-preview-export))
10009 (markdown-live-preview-mode -
1)
10010 (user-error "Buffer %s does not visit a file" (current-buffer)))
10011 (markdown-live-preview-remove)))
10014 (provide 'markdown-mode
)
10016 ;; Local Variables:
10017 ;; indent-tabs-mode: nil
10020 ;;; markdown-mode.el ends here