Define markdown--syntax-properties before use
[markdown-mode.git] / markdown-mode.el
blob81dfa9ac7cf8bbf5f828f716870525269bcff0a2
1 ;;; markdown-mode.el --- Major mode for Markdown-formatted text -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2007-2017 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
9 ;; Version: 2.4-dev
10 ;; Package-Requires: ((emacs "24") (cl-lib "0.5"))
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/>.
29 ;;; Commentary:
31 ;; See the README.md file for details.
34 ;;; Code:
36 (require 'easymenu)
37 (require 'outline)
38 (require 'thingatpt)
39 (require 'cl-lib)
40 (require 'url-parse)
41 (require 'button)
42 (require 'color)
43 (require 'rx)
45 (defvar jit-lock-start)
46 (defvar jit-lock-end)
47 (defvar flyspell-generic-check-word-predicate)
49 (declare-function eww-open-file "eww")
50 (declare-function url-path-and-query "url-parse")
53 ;;; Constants =================================================================
55 (defconst markdown-mode-version "2.4-dev"
56 "Markdown mode version number.")
58 (defconst markdown-output-buffer-name "*markdown-output*"
59 "Name of temporary buffer for markdown command output.")
62 ;;; Global Variables ==========================================================
64 (defvar markdown-reference-label-history nil
65 "History of used reference labels.")
67 (defvar markdown-live-preview-mode nil
68 "Sentinel variable for command `markdown-live-preview-mode'.")
70 (defvar markdown-gfm-language-history nil
71 "History list of languages used in the current buffer in GFM code blocks.")
74 ;;; Customizable Variables ====================================================
76 (defvar markdown-mode-hook nil
77 "Hook run when entering Markdown mode.")
79 (defvar markdown-before-export-hook nil
80 "Hook run before running Markdown to export XHTML output.
81 The hook may modify the buffer, which will be restored to it's
82 original state after exporting is complete.")
84 (defvar markdown-after-export-hook nil
85 "Hook run after XHTML output has been saved.
86 Any changes to the output buffer made by this hook will be saved.")
88 (defgroup markdown nil
89 "Major mode for editing text files in Markdown format."
90 :prefix "markdown-"
91 :group 'wp
92 :link '(url-link "https://jblevins.org/projects/markdown-mode/"))
94 (defcustom markdown-command "markdown"
95 "Command to run markdown."
96 :group 'markdown
97 :type '(choice (string :tag "Shell command") function))
99 (defcustom markdown-command-needs-filename nil
100 "Set to non-nil if `markdown-command' does not accept input from stdin.
101 Instead, it will be passed a filename as the final command line
102 option. As a result, you will only be able to run Markdown from
103 buffers which are visiting a file."
104 :group 'markdown
105 :type 'boolean)
107 (defcustom markdown-open-command nil
108 "Command used for opening Markdown files directly.
109 For example, a standalone Markdown previewer. This command will
110 be called with a single argument: the filename of the current
111 buffer. It can also be a function, which will be called without
112 arguments."
113 :group 'markdown
114 :type '(choice file function (const :tag "None" nil)))
116 (defcustom markdown-hr-strings
117 '("-------------------------------------------------------------------------------"
118 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
119 "---------------------------------------"
120 "* * * * * * * * * * * * * * * * * * * *"
121 "---------"
122 "* * * * *")
123 "Strings to use when inserting horizontal rules.
124 The first string in the list will be the default when inserting a
125 horizontal rule. Strings should be listed in decreasing order of
126 prominence (as in headings from level one to six) for use with
127 promotion and demotion functions."
128 :group 'markdown
129 :type '(repeat string))
131 (defcustom markdown-bold-underscore nil
132 "Use two underscores when inserting bold text instead of two asterisks."
133 :group 'markdown
134 :type 'boolean)
136 (defcustom markdown-italic-underscore nil
137 "Use underscores when inserting italic text instead of asterisks."
138 :group 'markdown
139 :type 'boolean)
141 (defcustom markdown-marginalize-headers nil
142 "When non-nil, put opening atx header markup in a left margin.
144 This setting goes well with `markdown-asymmetric-header'. But
145 sadly it conflicts with `linum-mode' since they both use the
146 same margin."
147 :group 'markdown
148 :type 'boolean
149 :safe 'booleanp
150 :package-version '(markdown-mode . "2.4"))
152 (defcustom markdown-marginalize-headers-margin-width 6
153 "Character width of margin used for marginalized headers.
154 The default value is based on there being six heading levels
155 defined by Markdown and HTML. Increasing this produces extra
156 whitespace on the left. Decreasing it may be preferred when
157 fewer than six nested heading levels are used."
158 :group 'markdown
159 :type 'natnump
160 :safe 'natnump
161 :package-version '(markdown-mode . "2.4"))
163 (defcustom markdown-asymmetric-header nil
164 "Determines if atx header style will be asymmetric.
165 Set to a non-nil value to use asymmetric header styling, placing
166 header markup only at the beginning of the line. By default,
167 balanced markup will be inserted at the beginning and end of the
168 line around the header title."
169 :group 'markdown
170 :type 'boolean)
172 (defcustom markdown-indent-function 'markdown-indent-line
173 "Function to use to indent."
174 :group 'markdown
175 :type 'function)
177 (defcustom markdown-indent-on-enter t
178 "Determines indentation behavior when pressing \\[newline].
179 Possible settings are nil, t, and 'indent-and-new-item.
181 When non-nil, pressing \\[newline] will call `newline-and-indent'
182 to indent the following line according to the context using
183 `markdown-indent-function'. In this case, note that
184 \\[electric-newline-and-maybe-indent] can still be used to insert
185 a newline without indentation.
187 When set to 'indent-and-new-item and the point is in a list item
188 when \\[newline] is pressed, the list will be continued on the next
189 line, where a new item will be inserted.
191 When set to nil, simply call `newline' as usual. In this case,
192 you can still indent lines using \\[markdown-cycle] and continue
193 lists with \\[markdown-insert-list-item].
195 Note that this assumes the variable `electric-indent-mode' is
196 non-nil (enabled). When it is *disabled*, the behavior of
197 \\[newline] and `\\[electric-newline-and-maybe-indent]' are
198 reversed."
199 :group 'markdown
200 :type '(choice (const :tag "Don't automatically indent" nil)
201 (const :tag "Automatically indent" t)
202 (const :tag "Automatically indent and insert new list items" indent-and-new-item)))
204 (defcustom markdown-enable-wiki-links nil
205 "Syntax highlighting for wiki links.
206 Set this to a non-nil value to turn on wiki link support by default.
207 Support can be toggled later using the `markdown-toggle-wiki-links'
208 function or \\[markdown-toggle-wiki-links]."
209 :group 'markdown
210 :type 'boolean
211 :safe 'booleanp
212 :package-version '(markdown-mode . "2.2"))
214 (defcustom markdown-wiki-link-alias-first t
215 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
216 Otherwise, they will be treated as [[PageName|alias text]]."
217 :group 'markdown
218 :type 'boolean
219 :safe 'booleanp)
221 (defcustom markdown-wiki-link-search-subdirectories nil
222 "When non-nil, search for wiki link targets in subdirectories.
223 This is the default search behavior for GitHub and is
224 automatically set to t in `gfm-mode'."
225 :group 'markdown
226 :type 'boolean
227 :safe 'booleanp
228 :package-version '(markdown-mode . "2.2"))
230 (defcustom markdown-wiki-link-search-parent-directories nil
231 "When non-nil, search for wiki link targets in parent directories.
232 This is the default search behavior of Ikiwiki."
233 :group 'markdown
234 :type 'boolean
235 :safe 'booleanp
236 :package-version '(markdown-mode . "2.2"))
238 (defcustom markdown-wiki-link-fontify-missing nil
239 "When non-nil, change wiki link face according to existence of target files.
240 This is expensive because it requires checking for the file each time the buffer
241 changes or the user switches windows. It is disabled by default because it may
242 cause lag when typing on slower machines."
243 :group 'markdown
244 :type 'boolean
245 :safe 'booleanp
246 :package-version '(markdown-mode . "2.2"))
248 (defcustom markdown-uri-types
249 '("acap" "cid" "data" "dav" "fax" "file" "ftp"
250 "gopher" "http" "https" "imap" "ldap" "mailto"
251 "mid" "message" "modem" "news" "nfs" "nntp"
252 "pop" "prospero" "rtsp" "service" "sip" "tel"
253 "telnet" "tip" "urn" "vemmi" "wais")
254 "Link types for syntax highlighting of URIs."
255 :group 'markdown
256 :type '(repeat (string :tag "URI scheme")))
258 (defcustom markdown-url-compose-char
259 '(?∞ ?… ?⋯ ?# ?★ ?⚓)
260 "Placeholder character for hidden URLs.
261 This may be a single character or a list of characters. In case
262 of a list, the first one that satisfies `char-displayable-p' will
263 be used."
264 :type '(choice
265 (character :tag "Single URL replacement character")
266 (repeat :tag "List of possible URL replacement characters"
267 character))
268 :package-version '(markdown-mode . "2.3"))
270 (defcustom markdown-blockquote-display-char
271 '("▌" "┃" ">")
272 "String to display when hiding blockquote markup.
273 This may be a single string or a list of string. In case of a
274 list, the first one that satisfies `char-displayable-p' will be
275 used."
276 :type 'string
277 :type '(choice
278 (string :tag "Single blockquote display string")
279 (repeat :tag "List of possible blockquote display strings" string))
280 :package-version '(markdown-mode . "2.3"))
282 (defcustom markdown-hr-display-char
283 '(?─ ?━ ?-)
284 "Character for hiding horizontal rule markup.
285 This may be a single character or a list of characters. In case
286 of a list, the first one that satisfies `char-displayable-p' will
287 be used."
288 :group 'markdown
289 :type '(choice
290 (character :tag "Single HR display character")
291 (repeat :tag "List of possible HR display characters" character))
292 :package-version '(markdown-mode . "2.3"))
294 (defcustom markdown-definition-display-char
295 '(?⁘ ?⁙ ?≡ ?⌑ ?◊ ?:)
296 "Character for replacing definition list markup.
297 This may be a single character or a list of characters. In case
298 of a list, the first one that satisfies `char-displayable-p' will
299 be used."
300 :type '(choice
301 (character :tag "Single definition list character")
302 (repeat :tag "List of possible definition list characters" character))
303 :package-version '(markdown-mode . "2.3"))
305 (defcustom markdown-enable-math nil
306 "Syntax highlighting for inline LaTeX and itex expressions.
307 Set this to a non-nil value to turn on math support by default.
308 Math support can be enabled, disabled, or toggled later using
309 `markdown-toggle-math' or \\[markdown-toggle-math]."
310 :group 'markdown
311 :type 'boolean
312 :safe 'booleanp)
313 (make-variable-buffer-local 'markdown-enable-math)
315 (defcustom markdown-enable-html t
316 "Enable font-lock support for HTML tags and attributes."
317 :group 'markdown
318 :type 'boolean
319 :safe 'booleanp
320 :package-version '(markdown-mode . "2.4"))
322 (defcustom markdown-css-paths nil
323 "URL of CSS file to link to in the output XHTML."
324 :group 'markdown
325 :type '(repeat (string :tag "CSS File Path")))
327 (defcustom markdown-content-type ""
328 "Content type string for the http-equiv header in XHTML output.
329 When set to a non-empty string, insert the http-equiv attribute.
330 Otherwise, this attribute is omitted."
331 :group 'markdown
332 :type 'string)
334 (defcustom markdown-coding-system nil
335 "Character set string for the http-equiv header in XHTML output.
336 Defaults to `buffer-file-coding-system' (and falling back to
337 `iso-8859-1' when not available). Common settings are `utf-8'
338 and `iso-latin-1'. Use `list-coding-systems' for more choices."
339 :group 'markdown
340 :type 'coding-system)
342 (defcustom markdown-export-kill-buffer t
343 "Kill output buffer after HTML export.
344 When non-nil, kill the HTML output buffer after
345 exporting with `markdown-export'."
346 :group 'markdown
347 :type 'boolean
348 :safe 'booleanp
349 :package-version '(markdown-mode . "2.4"))
351 (defcustom markdown-xhtml-header-content ""
352 "Additional content to include in the XHTML <head> block."
353 :group 'markdown
354 :type 'string)
356 (defcustom markdown-xhtml-standalone-regexp
357 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
358 "Regexp indicating whether `markdown-command' output is standalone XHTML."
359 :group 'markdown
360 :type 'regexp)
362 (defcustom markdown-link-space-sub-char "_"
363 "Character to use instead of spaces when mapping wiki links to filenames."
364 :group 'markdown
365 :type 'string)
367 (defcustom markdown-reference-location 'header
368 "Position where new reference definitions are inserted in the document."
369 :group 'markdown
370 :type '(choice (const :tag "At the end of the document" end)
371 (const :tag "Immediately after the current block" immediately)
372 (const :tag "At the end of the subtree" subtree)
373 (const :tag "Before next header" header)))
375 (defcustom markdown-footnote-location 'end
376 "Position where new footnotes are inserted in the document."
377 :group 'markdown
378 :type '(choice (const :tag "At the end of the document" end)
379 (const :tag "Immediately after the current block" immediately)
380 (const :tag "At the end of the subtree" subtree)
381 (const :tag "Before next header" header)))
383 (defcustom markdown-footnote-display '((raise 0.2) (height 0.8))
384 "Display specification for footnote markers and inline footnotes.
385 By default, footnote text is reduced in size and raised. Set to
386 nil to disable this."
387 :group 'markdown
388 :type '(choice (sexp :tag "Display specification")
389 (const :tag "Don't set display property" nil))
390 :package-version '(markdown-mode . "2.4"))
392 (defcustom markdown-sub-superscript-display
393 '(((raise -0.3) (height 0.7)) . ((raise 0.3) (height 0.7)))
394 "Display specification for subscript and superscripts.
395 The car is used for subscript, the cdr is used for superscripts."
396 :group 'markdown
397 :type '(cons (choice (sexp :tag "Subscript form")
398 (const :tag "No lowering" nil))
399 (choice (sexp :tag "Superscript form")
400 (const :tag "No raising" nil)))
401 :package-version '(markdown-mode . "2.4"))
403 (defcustom markdown-unordered-list-item-prefix " * "
404 "String inserted before unordered list items."
405 :group 'markdown
406 :type 'string)
408 (defcustom markdown-nested-imenu-heading-index t
409 "Use nested or flat imenu heading index.
410 A nested index may provide more natural browsing from the menu,
411 but a flat list may allow for faster keyboard navigation via tab
412 completion."
413 :group 'markdown
414 :type 'boolean
415 :safe 'booleanp
416 :package-version '(markdown-mode . "2.2"))
418 (defcustom markdown-make-gfm-checkboxes-buttons t
419 "When non-nil, make GFM checkboxes into buttons."
420 :group 'markdown
421 :type 'boolean)
423 (defcustom markdown-use-pandoc-style-yaml-metadata nil
424 "When non-nil, allow YAML metadata anywhere in the document."
425 :group 'markdown
426 :type 'boolean)
428 (defcustom markdown-split-window-direction 'any
429 "Preference for splitting windows for static and live preview.
430 The default value is 'any, which instructs Emacs to use
431 `split-window-sensibly' to automatically choose how to split
432 windows based on the values of `split-width-threshold' and
433 `split-height-threshold' and the available windows. To force
434 vertically split (left and right) windows, set this to 'vertical
435 or 'right. To force horizontally split (top and bottom) windows,
436 set this to 'horizontal or 'below."
437 :group 'markdown
438 :type '(choice (const :tag "Automatic" any)
439 (const :tag "Right (vertical)" right)
440 (const :tag "Below (horizontal)" below))
441 :package-version '(markdown-mode . "2.2"))
443 (defcustom markdown-live-preview-window-function
444 'markdown-live-preview-window-eww
445 "Function to display preview of Markdown output within Emacs.
446 Function must update the buffer containing the preview and return
447 the buffer."
448 :group 'markdown
449 :type 'function)
451 (defcustom markdown-live-preview-delete-export 'delete-on-destroy
452 "Delete exported HTML file when using `markdown-live-preview-export'.
453 If set to 'delete-on-export, delete on every export. When set to
454 'delete-on-destroy delete when quitting from command
455 `markdown-live-preview-mode'. Never delete if set to nil."
456 :group 'markdown
457 :type '(choice
458 (const :tag "Delete on every export" delete-on-export)
459 (const :tag "Delete when quitting live preview" delete-on-destroy)
460 (const :tag "Never delete" nil)))
462 (defcustom markdown-list-indent-width 4
463 "Depth of indentation for markdown lists.
464 Used in `markdown-demote-list-item' and
465 `markdown-promote-list-item'."
466 :group 'markdown
467 :type 'integer)
469 (defcustom markdown-enable-prefix-prompts t
470 "Display prompts for certain prefix commands.
471 Set to nil to disable these prompts."
472 :group 'markdown
473 :type 'boolean
474 :safe 'booleanp
475 :package-version '(markdown-mode . "2.3"))
477 (defcustom markdown-gfm-additional-languages nil
478 "Extra languages made available when inserting GFM code blocks.
479 Language strings must have be trimmed of whitespace and not
480 contain any curly braces. They may be of arbitrary
481 capitalization, though."
482 :group 'markdown
483 :type '(repeat (string :validate markdown-validate-language-string)))
485 (defcustom markdown-gfm-use-electric-backquote t
486 "Use `markdown-electric-backquote' when backquote is hit three times."
487 :group 'markdown
488 :type 'boolean)
490 (defcustom markdown-gfm-downcase-languages t
491 "If non-nil, downcase suggested languages.
492 This applies to insertions done with
493 `markdown-electric-backquote'."
494 :group 'markdown
495 :type 'boolean)
497 (defcustom markdown-edit-code-block-default-mode 'normal-mode
498 "Default mode to use for editing code blocks.
499 This mode is used when automatic detection fails, such as for GFM
500 code blocks with no language specified."
501 :group 'markdown
502 :type 'symbol
503 :package-version '(markdown-mode . "2.4"))
505 (defcustom markdown-gfm-uppercase-checkbox nil
506 "If non-nil, use [X] for completed checkboxes, [x] otherwise."
507 :group 'markdown
508 :type 'boolean
509 :safe 'booleanp)
511 (defcustom markdown-hide-urls nil
512 "Hide URLs of inline links and reference tags of reference links.
513 Such URLs will be replaced by a single customizable
514 character, defined by `markdown-url-compose-char', but are still part
515 of the buffer. Links can be edited interactively with
516 \\[markdown-insert-link] or, for example, by deleting the final
517 parenthesis to remove the invisibility property. You can also
518 hover your mouse pointer over the link text to see the URL.
519 Set this to a non-nil value to turn this feature on by default.
520 You can interactively set the value of this variable by calling
521 `markdown-toggle-url-hiding', pressing \\[markdown-toggle-url-hiding],
522 or from the menu Markdown > Links & Images menu."
523 :group 'markdown
524 :type 'boolean
525 :safe 'booleanp
526 :package-version '(markdown-mode . "2.3"))
527 (make-variable-buffer-local 'markdown-hide-urls)
529 (defcustom markdown-translate-filename-function #'identity
530 "Function to use to translate filenames when following links.
531 \\<markdown-mode-map>\\[markdown-follow-thing-at-point] and \\[markdown-follow-link-at-point]
532 call this function with the filename as only argument whenever
533 they encounter a filename (instead of a URL) to be visited and
534 use its return value instead of the filename in the link. For
535 example, if absolute filenames are actually relative to a server
536 root directory, you can set
537 `markdown-translate-filename-function' to a function that
538 prepends the root directory to the given filename."
539 :group 'markdown
540 :type 'function
541 :risky t
542 :package-version '(markdown-mode . "2.4"))
544 (defcustom markdown-max-image-size nil
545 "Maximum width and height for displayed inline images.
546 This variable may be nil or a cons cell (MAX-WIDTH . MAX-HEIGHT).
547 When nil, use the actual size. Otherwise, use ImageMagick to
548 resize larger images to be of the given maximum dimensions. This
549 requires Emacs to be built with ImageMagick support."
550 :group 'markdown
551 :package-version '(markdown-mode . "2.4")
552 :type '(choice
553 (const :tag "Use actual image width" nil)
554 (cons (choice (sexp :tag "Maximum width in pixels")
555 (const :tag "No maximum width" nil))
556 (choice (sexp :tag "Maximum height in pixels")
557 (const :tag "No maximum height" nil)))))
560 ;;; Markdown-Specific `rx' Macro
562 ;; Based on python-rx from python.el.
563 (eval-and-compile
564 (defconst markdown-rx-constituents
565 `((newline . ,(rx "\n"))
566 (indent . ,(rx (or (repeat 4 " ") "\t")))
567 (block-end . ,(rx (and (or (one-or-more (zero-or-more blank) "\n") line-end))))
568 (numeral . ,(rx (and (one-or-more (any "0-9#")) ".")))
569 (bullet . ,(rx (any "*+:-")))
570 (list-marker . ,(rx (or (and (one-or-more (any "0-9#")) ".")
571 (any "*+:-"))))
572 (checkbox . ,(rx "[" (any " xX") "]")))
573 "Markdown-specific sexps for `markdown-rx'")
575 (defmacro markdown-rx (&rest regexps)
576 "Markdown mode specialized rx macro.
577 This variant of `rx' supports common Markdown named REGEXPS."
578 (let ((rx-constituents (append markdown-rx-constituents rx-constituents)))
579 (cond ((null regexps)
580 (error "No regexp"))
581 ((cdr regexps)
582 (rx-to-string `(and ,@regexps) t))
584 (rx-to-string (car regexps) t))))))
587 ;;; Regular Expressions =======================================================
589 (defconst markdown-regex-comment-start
590 "<!--"
591 "Regular expression matches HTML comment opening.")
593 (defconst markdown-regex-comment-end
594 "--[ \t]*>"
595 "Regular expression matches HTML comment closing.")
597 (defconst markdown-regex-link-inline
598 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)\\((\\)\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?\\()\\)"
599 "Regular expression for a [text](file) or an image link ![text](file).
600 Group 1 matches the leading exclamation point (optional).
601 Group 2 matches the opening square bracket.
602 Group 3 matches the text inside the square brackets.
603 Group 4 matches the closing square bracket.
604 Group 5 matches the opening parenthesis.
605 Group 6 matches the URL.
606 Group 7 matches the title (optional).
607 Group 8 matches the closing parenthesis.")
609 (defconst markdown-regex-link-reference
610 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)[ ]?\\(\\[\\)\\([^]]*?\\)\\(\\]\\)"
611 "Regular expression for a reference link [text][id].
612 Group 1 matches the leading exclamation point (optional).
613 Group 2 matches the opening square bracket for the link text.
614 Group 3 matches the text inside the square brackets.
615 Group 4 matches the closing square bracket for the link text.
616 Group 5 matches the opening square bracket for the reference label.
617 Group 6 matches the reference label.
618 Group 7 matches the closing square bracket for the reference label.")
620 (defconst markdown-regex-reference-definition
621 "^ \\{0,3\\}\\(\\[\\)\\([^]\n]+?\\)\\(\\]\\)\\(:\\)\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
622 "Regular expression for a reference definition.
623 Group 1 matches the opening square bracket.
624 Group 2 matches the reference label.
625 Group 3 matches the closing square bracket.
626 Group 4 matches the colon.
627 Group 5 matches the URL.
628 Group 6 matches the title attribute (optional).")
630 (defconst markdown-regex-footnote
631 "\\(\\[\\^\\)\\(.+?\\)\\(\\]\\)"
632 "Regular expression for a footnote marker [^fn].
633 Group 1 matches the opening square bracket and carat.
634 Group 2 matches only the label, without the surrounding markup.
635 Group 3 matches the closing square bracket.")
637 (defconst markdown-regex-header
638 "^\\(?:\\([^\r\n\t -].*\\)\n\\(?:\\(=+\\)\\|\\(-+\\)\\)\\|\\(#+[ \t]+\\)\\(.*?\\)\\([ \t]*#*\\)\\)$"
639 "Regexp identifying Markdown headings.
640 Group 1 matches the text of a setext heading.
641 Group 2 matches the underline of a level-1 setext heading.
642 Group 3 matches the underline of a level-2 setext heading.
643 Group 4 matches the opening hash marks of an atx heading and whitespace.
644 Group 5 matches the text, without surrounding whitespace, of an atx heading.
645 Group 6 matches the closing whitespace and hash marks of an atx heading.")
647 (defconst markdown-regex-header-setext
648 "^\\([^\r\n\t -].*\\)\n\\(=+\\|-+\\)$"
649 "Regular expression for generic setext-style (underline) headers.")
651 (defconst markdown-regex-header-atx
652 "^\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
653 "Regular expression for generic atx-style (hash mark) headers.")
655 (defconst markdown-regex-hr
656 (rx line-start
657 (group (or (and (repeat 3 (and "*" (? " "))) (* (any "* ")))
658 (and (repeat 3 (and "-" (? " "))) (* (any "- ")))
659 (and (repeat 3 (and "_" (? " "))) (* (any "_ ")))))
660 line-end)
661 "Regular expression for matching Markdown horizontal rules.")
663 (defconst markdown-regex-code
664 "\\(?:\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(?:.\\|\n[^\n]\\)*?[^`]\\)\\(\\2\\)\\)\\(?:[^`]\\|\\'\\)"
665 "Regular expression for matching inline code fragments.
667 Group 1 matches the entire code fragment including the backquotes.
668 Group 2 matches the opening backquotes.
669 Group 3 matches the code fragment itself, without backquotes.
670 Group 4 matches the closing backquotes.
672 The leading, unnumbered group ensures that the leading backquote
673 character is not escaped.
674 The last group, also unnumbered, requires that the character
675 following the code fragment is not a backquote.
676 Note that \\(?:.\\|\n[^\n]\\) matches any character, including newlines,
677 but not two newlines in a row.")
679 (defconst markdown-regex-kbd
680 "\\(<kbd>\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(</kbd>\\)"
681 "Regular expression for matching <kbd> tags.
682 Groups 1 and 3 match the opening and closing tags.
683 Group 2 matches the key sequence.")
685 (defconst markdown-regex-gfm-code-block-open
686 "^[[:blank:]]*\\(```\\)\\([[:blank:]]*{?[[:blank:]]*\\)\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$"
687 "Regular expression matching opening of GFM code blocks.
688 Group 1 matches the opening three backquotes and any following whitespace.
689 Group 2 matches the opening brace (optional) and surrounding whitespace.
690 Group 3 matches the language identifier (optional).
691 Group 4 matches the info string (optional).
692 Group 5 matches the closing brace (optional), whitespace, and newline.
693 Groups need to agree with `markdown-regex-tilde-fence-begin'.")
695 (defconst markdown-regex-gfm-code-block-close
696 "^[[:blank:]]*\\(```\\)\\(\\s *?\\)$"
697 "Regular expression matching closing of GFM code blocks.
698 Group 1 matches the closing three backquotes.
699 Group 2 matches any whitespace and the final newline.")
701 (defconst markdown-regex-pre
702 "^\\( \\|\t\\).*$"
703 "Regular expression for matching preformatted text sections.")
705 (defconst markdown-regex-list
706 (markdown-rx line-start
707 ;; 1. Leading whitespace
708 (group (* blank))
709 ;; 2. List marker: a numeral, bullet, or colon
710 (group list-marker)
711 ;; 3. Trailing whitespace
712 (group (+ blank))
713 ;; 4. Optional checkbox for GFM task list items
714 (opt (group (and checkbox (* blank)))))
715 "Regular expression for matching list items.")
717 (defconst markdown-regex-bold
718 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
719 "Regular expression for matching bold text.
720 Group 1 matches the character before the opening asterisk or
721 underscore, if any, ensuring that it is not a backslash escape.
722 Group 2 matches the entire expression, including delimiters.
723 Groups 3 and 5 matches the opening and closing delimiters.
724 Group 4 matches the text inside the delimiters.")
726 (defconst markdown-regex-italic
727 "\\(?:^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t*]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
728 "Regular expression for matching italic text.
729 The leading unnumbered matches the character before the opening
730 asterisk or underscore, if any, ensuring that it is not a
731 backslash escape.
732 Group 1 matches the entire expression, including delimiters.
733 Groups 2 and 4 matches the opening and closing delimiters.
734 Group 3 matches the text inside the delimiters.")
736 (defconst markdown-regex-strike-through
737 "\\(^\\|[^\\]\\)\\(\\(~~\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(~~\\)\\)"
738 "Regular expression for matching strike-through text.
739 Group 1 matches the character before the opening tilde, if any,
740 ensuring that it is not a backslash escape.
741 Group 2 matches the entire expression, including delimiters.
742 Groups 3 and 5 matches the opening and closing delimiters.
743 Group 4 matches the text inside the delimiters.")
745 (defconst markdown-regex-gfm-italic
746 "\\(?:^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\2\\|[^ ]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
747 "Regular expression for matching italic text in GitHub Flavored Markdown.
748 Underscores in words are not treated as special.
749 Group 1 matches the entire expression, including delimiters.
750 Groups 2 and 4 matches the opening and closing delimiters.
751 Group 3 matches the text inside the delimiters.")
753 (defconst markdown-regex-blockquote
754 "^[ \t]*\\([A-Z]?>\\)\\([ \t]*\\)\\(.*\\)$"
755 "Regular expression for matching blockquote lines.
756 Also accounts for a potential capital letter preceding the angle
757 bracket, for use with Leanpub blocks (asides, warnings, info
758 blocks, etc.).
759 Group 1 matches the leading angle bracket.
760 Group 2 matches the separating whitespace.
761 Group 3 matches the text.")
763 (defconst markdown-regex-line-break
764 "[^ \n\t][ \t]*\\( \\)$"
765 "Regular expression for matching line breaks.")
767 (defconst markdown-regex-wiki-link
768 "\\(?:^\\|[^\\]\\)\\(\\(\\[\\[\\)\\([^]|]+\\)\\(?:\\(|\\)\\([^]]+\\)\\)?\\(\\]\\]\\)\\)"
769 "Regular expression for matching wiki links.
770 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
771 wiki links of the form [[PageName|link text]].
772 The meanings of the first and second components depend
773 on the value of `markdown-wiki-link-alias-first'.
775 Group 1 matches the entire link.
776 Group 2 matches the opening square brackets.
777 Group 3 matches the first component of the wiki link.
778 Group 4 matches the pipe separator, when present.
779 Group 5 matches the second component of the wiki link, when present.
780 Group 6 matches the closing square brackets.")
782 (defconst markdown-regex-uri
783 (concat "\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+\\)")
784 "Regular expression for matching inline URIs.")
786 (defconst markdown-regex-angle-uri
787 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
788 "Regular expression for matching inline URIs in angle brackets.")
790 (defconst markdown-regex-email
791 "<\\(\\(?:\\sw\\|\\s_\\|\\s.\\)+@\\(?:\\sw\\|\\s_\\|\\s.\\)+\\)>"
792 "Regular expression for matching inline email addresses.")
794 (defsubst markdown-make-regex-link-generic ()
795 "Make regular expression for matching any recognized link."
796 (concat "\\(?:" markdown-regex-link-inline
797 (when markdown-enable-wiki-links
798 (concat "\\|" markdown-regex-wiki-link))
799 "\\|" markdown-regex-link-reference
800 "\\|" markdown-regex-angle-uri "\\)"))
802 (defconst markdown-regex-gfm-checkbox
803 " \\(\\[[ xX]\\]\\) "
804 "Regular expression for matching GFM checkboxes.
805 Group 1 matches the text to become a button.")
807 (defconst markdown-regex-blank-line
808 "^[[:blank:]]*$"
809 "Regular expression that matches a blank line.")
811 (defconst markdown-regex-block-separator
812 "\n[\n\t\f ]*\n"
813 "Regular expression for matching block boundaries.")
815 (defconst markdown-regex-block-separator-noindent
816 (concat "\\(\\`\\|\\(" markdown-regex-block-separator "\\)[^\n\t\f ]\\)")
817 "Regexp for block separators before lines with no indentation.")
819 (defconst markdown-regex-math-inline-single
820 "\\(?:^\\|[^\\]\\)\\(\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\)"
821 "Regular expression for itex $..$ math mode expressions.
822 Groups 1 and 3 match the opening and closing dollar signs.
823 Group 2 matches the mathematical expression contained within.")
825 (defconst markdown-regex-math-inline-double
826 "\\(?:^\\|[^\\]\\)\\(\\$\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\$\\)"
827 "Regular expression for itex $$..$$ math mode expressions.
828 Groups 1 and 3 match opening and closing dollar signs.
829 Group 2 matches the mathematical expression contained within.")
831 (defconst markdown-regex-math-display
832 (rx line-start (* blank)
833 (group (group (repeat 1 2 "\\")) "[")
834 (group (*? anything))
835 (group (backref 2) "]")
836 line-end)
837 "Regular expression for \[..\] or \\[..\\] display math.
838 Groups 1 and 4 match the opening and closing markup.
839 Group 3 matches the mathematical expression contained within.
840 Group 2 matches the opening slashes, and is used internally to
841 match the closing slashes.")
843 (defsubst markdown-make-tilde-fence-regex (num-tildes &optional end-of-line)
844 "Return regexp matching a tilde code fence at least NUM-TILDES long.
845 END-OF-LINE is the regexp construct to indicate end of line; $ if
846 missing."
847 (format "%s%d%s%s" "^[[:blank:]]*\\([~]\\{" num-tildes ",\\}\\)"
848 (or end-of-line "$")))
850 (defconst markdown-regex-tilde-fence-begin
851 (markdown-make-tilde-fence-regex
852 3 "\\([[:blank:]]*{?\\)[[:blank:]]*\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$")
853 "Regular expression for matching tilde-fenced code blocks.
854 Group 1 matches the opening tildes.
855 Group 2 matches (optional) opening brace and surrounding whitespace.
856 Group 3 matches the language identifier (optional).
857 Group 4 matches the info string (optional).
858 Group 5 matches the closing brace (optional) and any surrounding whitespace.
859 Groups need to agree with `markdown-regex-gfm-code-block-open'.")
861 (defconst markdown-regex-declarative-metadata
862 "^\\([[:alpha:]][[:alpha:] _-]*?\\)\\([:=][ \t]*\\)\\(.*\\)$"
863 "Regular expression for matching declarative metadata statements.
864 This matches MultiMarkdown metadata as well as YAML and TOML
865 assignments such as the following:
867 variable: value
871 variable = value")
873 (defconst markdown-regex-pandoc-metadata
874 "^\\(%\\)\\([ \t]*\\)\\(.*\\(?:\n[ \t]+.*\\)*\\)"
875 "Regular expression for matching Pandoc metadata.")
877 (defconst markdown-regex-yaml-metadata-border
878 "\\(-\\{3\\}\\)$"
879 "Regular expression for matching YAML metadata.")
881 (defconst markdown-regex-yaml-pandoc-metadata-end-border
882 "^\\(\\.\\{3\\}\\|\\-\\{3\\}\\)$"
883 "Regular expression for matching YAML metadata end borders.")
885 (defsubst markdown-get-yaml-metadata-start-border ()
886 "Return YAML metadata start border depending upon whether Pandoc is used."
887 (concat
888 (if markdown-use-pandoc-style-yaml-metadata "^" "\\`")
889 markdown-regex-yaml-metadata-border))
891 (defsubst markdown-get-yaml-metadata-end-border (_)
892 "Return YAML metadata end border depending upon whether Pandoc is used."
893 (if markdown-use-pandoc-style-yaml-metadata
894 markdown-regex-yaml-pandoc-metadata-end-border
895 markdown-regex-yaml-metadata-border))
897 (defconst markdown-regex-inline-attributes
898 "[ \t]*\\({:?\\)[ \t]*\\(\\(#[[:alpha:]_.:-]+\\|\\.[[:alpha:]_.:-]+\\|\\w+=['\"]?[^\n'\"]*['\"]?\\),?[ \t]*\\)+\\(}\\)[ \t]*$"
899 "Regular expression for matching inline identifiers or attribute lists.
900 Compatible with Pandoc, Python Markdown, PHP Markdown Extra, and Leanpub.")
902 (defconst markdown-regex-leanpub-sections
903 (concat
904 "^\\({\\)\\("
905 (regexp-opt '("frontmatter" "mainmatter" "backmatter" "appendix" "pagebreak"))
906 "\\)\\(}\\)[ \t]*\n")
907 "Regular expression for Leanpub section markers and related syntax.")
909 (defconst markdown-regex-sub-superscript
910 "\\(?:^\\|[^\\~^]\\)\\(\\([~^]\\)\\([[:alnum:]]+\\)\\(\\2\\)\\)"
911 "The regular expression matching a sub- or superscript.
912 The leading un-numbered group matches the character before the
913 opening tilde or carat, if any, ensuring that it is not a
914 backslash escape, carat, or tilde.
915 Group 1 matches the entire expression, including markup.
916 Group 2 matches the opening markup--a tilde or carat.
917 Group 3 matches the text inside the delimiters.
918 Group 4 matches the closing markup--a tilde or carat.")
920 (defconst markdown-regex-include
921 "^\\(<<\\)\\(?:\\(\\[\\)\\(.*\\)\\(\\]\\)\\)?\\(?:\\((\\)\\(.*\\)\\()\\)\\)?\\(?:\\({\\)\\(.*\\)\\(}\\)\\)?$"
922 "Regular expression matching common forms of include syntax.
923 Marked 2, Leanpub, and other processors support some of these forms:
925 <<[sections/section1.md]
926 <<(folder/filename)
927 <<[Code title](folder/filename)
928 <<{folder/raw_file.html}
930 Group 1 matches the opening two angle brackets.
931 Groups 2-4 match the opening square bracket, the text inside,
932 and the closing square bracket, respectively.
933 Groups 5-7 match the opening parenthesis, the text inside, and
934 the closing parenthesis.
935 Groups 8-10 match the opening brace, the text inside, and the brace.")
937 (defconst markdown-regex-pandoc-inline-footnote
938 "\\(\\^\\)\\(\\[\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(\\]\\)"
939 "Regular expression for Pandoc inline footnote^[footnote text].
940 Group 1 matches the opening caret.
941 Group 2 matches the opening square bracket.
942 Group 3 matches the footnote text, without the surrounding markup.
943 Group 4 matches the closing square bracket.")
945 (defconst markdown-regex-html-attr
946 "\\(\\<[[:alpha:]:-]+\\>\\)\\(\\s-*\\(=\\)\\s-*\\(\".*?\"\\|'.*?'\\|[^'\">[:space:]]+\\)?\\)?"
947 "Regular expression for matching HTML attributes and values.
948 Group 1 matches the attribute name.
949 Group 2 matches the following whitespace, equals sign, and value, if any.
950 Group 3 matches the equals sign, if any.
951 Group 4 matches single-, double-, or un-quoted attribute values.")
953 (defconst markdown-regex-html-tag
954 (concat "\\(</?\\)\\(\\w+\\)\\(\\(\\s-+" markdown-regex-html-attr
955 "\\)+\\s-*\\|\\s-*\\)\\(/?>\\)")
956 "Regular expression for matching HTML tags.
957 Groups 1 and 9 match the beginning and ending angle brackets and slashes.
958 Group 2 matches the tag name.
959 Group 3 matches all attributes and whitespace following the tag name.")
961 (defconst markdown-regex-html-entity
962 "\\(&#?[[:alnum:]]+;\\)"
963 "Regular expression for matching HTML entities.")
966 ;;; Syntax ====================================================================
968 (defvar markdown--syntax-properties
969 (list 'markdown-tilde-fence-begin nil
970 'markdown-tilde-fence-end nil
971 'markdown-fenced-code nil
972 'markdown-yaml-metadata-begin nil
973 'markdown-yaml-metadata-end nil
974 'markdown-yaml-metadata-section nil
975 'markdown-gfm-block-begin nil
976 'markdown-gfm-block-end nil
977 'markdown-gfm-code nil
978 'markdown-list-item nil
979 'markdown-pre nil
980 'markdown-blockquote nil
981 'markdown-hr nil
982 'markdown-comment nil
983 'markdown-heading nil
984 'markdown-heading-1-setext nil
985 'markdown-heading-2-setext nil
986 'markdown-heading-1-atx nil
987 'markdown-heading-2-atx nil
988 'markdown-heading-3-atx nil
989 'markdown-heading-4-atx nil
990 'markdown-heading-5-atx nil
991 'markdown-heading-6-atx nil
992 'markdown-metadata-key nil
993 'markdown-metadata-value nil
994 'markdown-metadata-markup nil)
995 "Property list of all Markdown syntactic properties.")
997 (defsubst markdown-in-comment-p (&optional pos)
998 "Return non-nil if POS is in a comment.
999 If POS is not given, use point instead."
1000 (get-text-property (or pos (point)) 'markdown-comment))
1002 (defun markdown-syntax-propertize-extend-region (start end)
1003 "Extend START to END region to include an entire block of text.
1004 This helps improve syntax analysis for block constructs.
1005 Returns a cons (NEW-START . NEW-END) or nil if no adjustment should be made.
1006 Function is called repeatedly until it returns nil. For details, see
1007 `syntax-propertize-extend-region-functions'."
1008 (save-match-data
1009 (save-excursion
1010 (let* ((new-start (progn (goto-char start)
1011 (skip-chars-forward "\n")
1012 (if (re-search-backward "\n\n" nil t)
1013 (min start (match-end 0))
1014 (point-min))))
1015 (new-end (progn (goto-char end)
1016 (skip-chars-backward "\n")
1017 (if (re-search-forward "\n\n" nil t)
1018 (max end (match-beginning 0))
1019 (point-max))))
1020 (code-match (markdown--code-block-at-pos-no-syntax new-start))
1021 (new-start (or (and code-match (cl-first code-match)) new-start))
1022 (code-match (and (< end (point-max))
1023 (markdown--code-block-at-pos-no-syntax end)))
1024 (new-end (or (and code-match (cl-second code-match)) new-end)))
1025 (unless (and (eq new-start start) (eq new-end end))
1026 (cons new-start (min new-end (point-max))))))))
1028 (defun markdown-font-lock-extend-region-function (start end _)
1029 "Used in `jit-lock-after-change-extend-region-functions'.
1030 Delegates to `markdown-syntax-propertize-extend-region'. START
1031 and END are the previous region to refontify."
1032 (let ((res (markdown-syntax-propertize-extend-region start end)))
1033 (when res
1034 ;; syntax-propertize-function is not called when character at
1035 ;; (point-max) is deleted, but font-lock-extend-region-functions
1036 ;; are called. Force a syntax property update in that case.
1037 (when (= end (point-max))
1038 ;; This function is called in a buffer modification hook.
1039 ;; `markdown-syntax-propertize' doesn't save the match data,
1040 ;; so we have to do it here.
1041 (save-match-data
1042 (markdown-syntax-propertize (car res) (cdr res))))
1043 (setq jit-lock-start (car res)
1044 jit-lock-end (cdr res)))))
1046 (defun markdown--cur-list-item-bounds ()
1047 "Return a list describing the list item at point.
1048 Assumes that match data is set for `markdown-regex-list'. See the
1049 documentation for `markdown-cur-list-item-bounds' for the format of
1050 the returned list."
1051 (save-excursion
1052 (let* ((begin (match-beginning 0))
1053 (indent (length (match-string-no-properties 1)))
1054 (nonlist-indent (- (match-end 3) (match-beginning 0)))
1055 (marker (buffer-substring-no-properties
1056 (match-beginning 2) (match-end 3)))
1057 (checkbox (match-string-no-properties 4))
1058 (match (butlast (match-data t)))
1059 (end (markdown-cur-list-item-end nonlist-indent)))
1060 (list begin end indent nonlist-indent marker checkbox match))))
1062 (defun markdown--append-list-item-bounds (marker indent cur-bounds bounds)
1063 "Update list item BOUNDS given list MARKER, block INDENT, and CUR-BOUNDS.
1064 Here, MARKER is a string representing the type of list and INDENT
1065 is an integer giving the indentation, in spaces, of the current
1066 block. CUR-BOUNDS is a list of the form returned by
1067 `markdown-cur-list-item-bounds' and BOUNDS is a list of bounds
1068 values for parent list items. When BOUNDS is nil, it means we are
1069 at baseline (not inside of a nested list)."
1070 (let ((prev-indent (or (cl-third (car bounds)) 0)))
1071 (cond
1072 ;; New list item at baseline.
1073 ((and marker (null bounds))
1074 (list cur-bounds))
1075 ;; List item with greater indentation (four or more spaces).
1076 ;; Increase list level by consing CUR-BOUNDS onto BOUNDS.
1077 ((and marker (>= indent (+ prev-indent 4)))
1078 (cons cur-bounds bounds))
1079 ;; List item with greater or equal indentation (less than four spaces).
1080 ;; Keep list level the same by replacing the car of BOUNDS.
1081 ((and marker (>= indent prev-indent))
1082 (cons cur-bounds (cdr bounds)))
1083 ;; Lesser indentation level.
1084 ;; Pop appropriate number of elements off BOUNDS list (e.g., lesser
1085 ;; indentation could move back more than one list level). Note
1086 ;; that this block need not be the beginning of list item.
1087 ((< indent prev-indent)
1088 (while (and (> (length bounds) 1)
1089 (setq prev-indent (cl-third (cadr bounds)))
1090 (< indent (+ prev-indent 4)))
1091 (setq bounds (cdr bounds)))
1092 (cons cur-bounds bounds))
1093 ;; Otherwise, do nothing.
1094 (t bounds))))
1096 (defun markdown-syntax-propertize-list-items (start end)
1097 "Propertize list items from START to END.
1098 Stores nested list item information in the `markdown-list-item'
1099 text property to make later syntax analysis easier. The value of
1100 this property is a list with elements of the form (begin . end)
1101 giving the bounds of the current and parent list items."
1102 (save-excursion
1103 (goto-char start)
1104 (let (bounds level pre-regexp)
1105 ;; Find a baseline point with zero list indentation
1106 (markdown-search-backward-baseline)
1107 ;; Search for all list items between baseline and END
1108 (while (and (< (point) end)
1109 (re-search-forward markdown-regex-list end t))
1110 ;; Level of list nesting
1111 (setq level (length bounds))
1112 ;; Pre blocks need to be indented one level past the list level
1113 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ level)))
1114 (beginning-of-line)
1115 (cond
1116 ;; Reset at headings, horizontal rules, and top-level blank lines.
1117 ;; Propertize baseline when in range.
1118 ((markdown-new-baseline)
1119 (setq bounds nil))
1120 ;; Make sure this is not a line from a pre block
1121 ((looking-at-p pre-regexp))
1122 ;; If not, then update levels and propertize list item when in range.
1124 (let* ((indent (current-indentation))
1125 (cur-bounds (markdown--cur-list-item-bounds))
1126 (first (cl-first cur-bounds))
1127 (last (cl-second cur-bounds))
1128 (marker (cl-fifth cur-bounds)))
1129 (setq bounds (markdown--append-list-item-bounds
1130 marker indent cur-bounds bounds))
1131 (when (and (<= start (point)) (<= (point) end))
1132 (put-text-property first last 'markdown-list-item bounds)))))
1133 (end-of-line)))))
1135 (defun markdown-syntax-propertize-pre-blocks (start end)
1136 "Match preformatted text blocks from START to END."
1137 (save-excursion
1138 (goto-char start)
1139 (let ((levels (markdown-calculate-list-levels))
1140 indent pre-regexp close-regexp open close)
1141 (while (and (< (point) end) (not close))
1142 ;; Search for a region with sufficient indentation
1143 (if (null levels)
1144 (setq indent 1)
1145 (setq indent (1+ (length levels))))
1146 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1147 (setq close-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1149 (cond
1150 ;; If not at the beginning of a line, move forward
1151 ((not (bolp)) (forward-line))
1152 ;; Move past blank lines
1153 ((markdown-cur-line-blank-p) (forward-line))
1154 ;; At headers and horizontal rules, reset levels
1155 ((markdown-new-baseline) (forward-line) (setq levels nil))
1156 ;; If the current line has sufficient indentation, mark out pre block
1157 ;; The opening should be preceded by a blank line.
1158 ((and (markdown-prev-line-blank) (looking-at pre-regexp))
1159 (setq open (match-beginning 0))
1160 (while (and (or (looking-at-p pre-regexp) (markdown-cur-line-blank-p))
1161 (not (eobp)))
1162 (forward-line))
1163 (skip-syntax-backward "-")
1164 (setq close (point)))
1165 ;; If current line has a list marker, update levels, move to end of block
1166 ((looking-at markdown-regex-list)
1167 (setq levels (markdown-update-list-levels
1168 (match-string 2) (current-indentation) levels))
1169 (markdown-end-of-text-block))
1170 ;; If this is the end of the indentation level, adjust levels accordingly.
1171 ;; Only match end of indentation level if levels is not the empty list.
1172 ((and (car levels) (looking-at-p close-regexp))
1173 (setq levels (markdown-update-list-levels
1174 nil (current-indentation) levels))
1175 (markdown-end-of-text-block))
1176 (t (markdown-end-of-text-block))))
1178 (when (and open close)
1179 ;; Set text property data
1180 (put-text-property open close 'markdown-pre (list open close))
1181 ;; Recursively search again
1182 (markdown-syntax-propertize-pre-blocks (point) end)))))
1184 (defconst markdown-fenced-block-pairs
1185 `(((,markdown-regex-tilde-fence-begin markdown-tilde-fence-begin)
1186 (markdown-make-tilde-fence-regex markdown-tilde-fence-end)
1187 markdown-fenced-code)
1188 ((markdown-get-yaml-metadata-start-border markdown-yaml-metadata-begin)
1189 (markdown-get-yaml-metadata-end-border markdown-yaml-metadata-end)
1190 markdown-yaml-metadata-section)
1191 ((,markdown-regex-gfm-code-block-open markdown-gfm-block-begin)
1192 (,markdown-regex-gfm-code-block-close markdown-gfm-block-end)
1193 markdown-gfm-code))
1194 "Mapping of regular expressions to \"fenced-block\" constructs.
1195 These constructs are distinguished by having a distinctive start
1196 and end pattern, both of which take up an entire line of text,
1197 but no special pattern to identify text within the fenced
1198 blocks (unlike blockquotes and indented-code sections).
1200 Each element within this list takes the form:
1202 ((START-REGEX-OR-FUN START-PROPERTY)
1203 (END-REGEX-OR-FUN END-PROPERTY)
1204 MIDDLE-PROPERTY)
1206 Each *-REGEX-OR-FUN element can be a regular expression as a string, or a
1207 function which evaluates to same. Functions for START-REGEX-OR-FUN accept no
1208 arguments, but functions for END-REGEX-OR-FUN accept a single numerical argument
1209 which is the length of the first group of the START-REGEX-OR-FUN match, which
1210 can be ignored if unnecessary. `markdown-maybe-funcall-regexp' is used to
1211 evaluate these into \"real\" regexps.
1213 The *-PROPERTY elements are the text properties applied to each part of the
1214 block construct when it is matched using
1215 `markdown-syntax-propertize-fenced-block-constructs'. START-PROPERTY is applied
1216 to the text matching START-REGEX-OR-FUN, END-PROPERTY to END-REGEX-OR-FUN, and
1217 MIDDLE-PROPERTY to the text in between the two. The value of *-PROPERTY is the
1218 `match-data' when the regexp was matched to the text. In the case of
1219 MIDDLE-PROPERTY, the value is a false match data of the form '(begin end), with
1220 begin and end set to the edges of the \"middle\" text. This makes fontification
1221 easier.")
1223 (defun markdown-text-property-at-point (prop)
1224 (get-text-property (point) prop))
1226 (defsubst markdown-maybe-funcall-regexp (object &optional arg)
1227 (cond ((functionp object)
1228 (if arg (funcall object arg) (funcall object)))
1229 ((stringp object) object)
1230 (t (error "Object cannot be turned into regex"))))
1232 (defsubst markdown-get-start-fence-regexp ()
1233 "Return regexp to find all \"start\" sections of fenced block constructs.
1234 Which construct is actually contained in the match must be found separately."
1235 (mapconcat
1236 #'identity
1237 (mapcar (lambda (entry) (markdown-maybe-funcall-regexp (caar entry)))
1238 markdown-fenced-block-pairs)
1239 "\\|"))
1241 (defun markdown-get-fenced-block-begin-properties ()
1242 (cl-mapcar (lambda (entry) (cl-cadar entry)) markdown-fenced-block-pairs))
1244 (defun markdown-get-fenced-block-end-properties ()
1245 (cl-mapcar (lambda (entry) (cl-cadadr entry)) markdown-fenced-block-pairs))
1247 (defun markdown-get-fenced-block-middle-properties ()
1248 (cl-mapcar #'cl-third markdown-fenced-block-pairs))
1250 (defun markdown-find-previous-prop (prop &optional lim)
1251 "Find previous place where property PROP is non-nil, up to LIM.
1252 Return a cons of (pos . property). pos is point if point contains
1253 non-nil PROP."
1254 (let ((res
1255 (if (get-text-property (point) prop) (point)
1256 (previous-single-property-change
1257 (point) prop nil (or lim (point-min))))))
1258 (when (and (not (get-text-property res prop))
1259 (> res (point-min))
1260 (get-text-property (1- res) prop))
1261 (cl-decf res))
1262 (when (and res (get-text-property res prop)) (cons res prop))))
1264 (defun markdown-find-next-prop (prop &optional lim)
1265 "Find next place where property PROP is non-nil, up to LIM.
1266 Return a cons of (POS . PROPERTY) where POS is point if point
1267 contains non-nil PROP."
1268 (let ((res
1269 (if (get-text-property (point) prop) (point)
1270 (next-single-property-change
1271 (point) prop nil (or lim (point-max))))))
1272 (when (and res (get-text-property res prop)) (cons res prop))))
1274 (defun markdown-min-of-seq (map-fn seq)
1275 "Apply MAP-FN to SEQ and return element of SEQ with minimum value of MAP-FN."
1276 (cl-loop for el in seq
1277 with min = 1.0e+INF ; infinity
1278 with min-el = nil
1279 do (let ((res (funcall map-fn el)))
1280 (when (< res min)
1281 (setq min res)
1282 (setq min-el el)))
1283 finally return min-el))
1285 (defun markdown-max-of-seq (map-fn seq)
1286 "Apply MAP-FN to SEQ and return element of SEQ with maximum value of MAP-FN."
1287 (cl-loop for el in seq
1288 with max = -1.0e+INF ; negative infinity
1289 with max-el = nil
1290 do (let ((res (funcall map-fn el)))
1291 (when (and res (> res max))
1292 (setq max res)
1293 (setq max-el el)))
1294 finally return max-el))
1296 (defun markdown-find-previous-block ()
1297 "Find previous block.
1298 Detect whether `markdown-syntax-propertize-fenced-block-constructs' was
1299 unable to propertize the entire block, but was able to propertize the beginning
1300 of the block. If so, return a cons of (pos . property) where the beginning of
1301 the block was propertized."
1302 (let ((start-pt (point))
1303 (closest-open
1304 (markdown-max-of-seq
1305 #'car
1306 (cl-remove-if
1307 #'null
1308 (cl-mapcar
1309 #'markdown-find-previous-prop
1310 (markdown-get-fenced-block-begin-properties))))))
1311 (when closest-open
1312 (let* ((length-of-open-match
1313 (let ((match-d
1314 (get-text-property (car closest-open) (cdr closest-open))))
1315 (- (cl-fourth match-d) (cl-third match-d))))
1316 (end-regexp
1317 (markdown-maybe-funcall-regexp
1318 (cl-caadr
1319 (cl-find-if
1320 (lambda (entry) (eq (cl-cadar entry) (cdr closest-open)))
1321 markdown-fenced-block-pairs))
1322 length-of-open-match))
1323 (end-prop-loc
1324 (save-excursion
1325 (save-match-data
1326 (goto-char (car closest-open))
1327 (and (re-search-forward end-regexp start-pt t)
1328 (match-beginning 0))))))
1329 (and (not end-prop-loc) closest-open)))))
1331 (defun markdown-get-fenced-block-from-start (prop)
1332 "Return limits of an enclosing fenced block from its start, using PROP.
1333 Return value is a list usable as `match-data'."
1334 (catch 'no-rest-of-block
1335 (let* ((correct-entry
1336 (cl-find-if
1337 (lambda (entry) (eq (cl-cadar entry) prop))
1338 markdown-fenced-block-pairs))
1339 (begin-of-begin (cl-first (markdown-text-property-at-point prop)))
1340 (middle-prop (cl-third correct-entry))
1341 (end-prop (cl-cadadr correct-entry))
1342 (end-of-end
1343 (save-excursion
1344 (goto-char (match-end 0)) ; end of begin
1345 (unless (eobp) (forward-char))
1346 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
1347 (if (not mid-prop-v) ; no middle
1348 (progn
1349 ;; try to find end by advancing one
1350 (let ((end-prop-v
1351 (markdown-text-property-at-point end-prop)))
1352 (if end-prop-v (cl-second end-prop-v)
1353 (throw 'no-rest-of-block nil))))
1354 (set-match-data mid-prop-v)
1355 (goto-char (match-end 0)) ; end of middle
1356 (beginning-of-line) ; into end
1357 (cl-second (markdown-text-property-at-point end-prop)))))))
1358 (list begin-of-begin end-of-end))))
1360 (defun markdown-get-fenced-block-from-middle (prop)
1361 "Return limits of an enclosing fenced block from its middle, using PROP.
1362 Return value is a list usable as `match-data'."
1363 (let* ((correct-entry
1364 (cl-find-if
1365 (lambda (entry) (eq (cl-third entry) prop))
1366 markdown-fenced-block-pairs))
1367 (begin-prop (cl-cadar correct-entry))
1368 (begin-of-begin
1369 (save-excursion
1370 (goto-char (match-beginning 0))
1371 (unless (bobp) (forward-line -1))
1372 (beginning-of-line)
1373 (cl-first (markdown-text-property-at-point begin-prop))))
1374 (end-prop (cl-cadadr correct-entry))
1375 (end-of-end
1376 (save-excursion
1377 (goto-char (match-end 0))
1378 (beginning-of-line)
1379 (cl-second (markdown-text-property-at-point end-prop)))))
1380 (list begin-of-begin end-of-end)))
1382 (defun markdown-get-fenced-block-from-end (prop)
1383 "Return limits of an enclosing fenced block from its end, using PROP.
1384 Return value is a list usable as `match-data'."
1385 (let* ((correct-entry
1386 (cl-find-if
1387 (lambda (entry) (eq (cl-cadadr entry) prop))
1388 markdown-fenced-block-pairs))
1389 (end-of-end (cl-second (markdown-text-property-at-point prop)))
1390 (middle-prop (cl-third correct-entry))
1391 (begin-prop (cl-cadar correct-entry))
1392 (begin-of-begin
1393 (save-excursion
1394 (goto-char (match-beginning 0)) ; beginning of end
1395 (unless (bobp) (backward-char)) ; into middle
1396 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
1397 (if (not mid-prop-v)
1398 (progn
1399 (beginning-of-line)
1400 (cl-first (markdown-text-property-at-point begin-prop)))
1401 (set-match-data mid-prop-v)
1402 (goto-char (match-beginning 0)) ; beginning of middle
1403 (unless (bobp) (forward-line -1)) ; into beginning
1404 (beginning-of-line)
1405 (cl-first (markdown-text-property-at-point begin-prop)))))))
1406 (list begin-of-begin end-of-end)))
1408 (defun markdown-get-enclosing-fenced-block-construct (&optional pos)
1409 "Get \"fake\" match data for block enclosing POS.
1410 Returns fake match data which encloses the start, middle, and end
1411 of the block construct enclosing POS, if it exists. Used in
1412 `markdown-code-block-at-pos'."
1413 (save-excursion
1414 (when pos (goto-char pos))
1415 (beginning-of-line)
1416 (car
1417 (cl-remove-if
1418 #'null
1419 (cl-mapcar
1420 (lambda (fun-and-prop)
1421 (cl-destructuring-bind (fun prop) fun-and-prop
1422 (when prop
1423 (save-match-data
1424 (set-match-data (markdown-text-property-at-point prop))
1425 (funcall fun prop)))))
1426 `((markdown-get-fenced-block-from-start
1427 ,(cl-find-if
1428 #'markdown-text-property-at-point
1429 (markdown-get-fenced-block-begin-properties)))
1430 (markdown-get-fenced-block-from-middle
1431 ,(cl-find-if
1432 #'markdown-text-property-at-point
1433 (markdown-get-fenced-block-middle-properties)))
1434 (markdown-get-fenced-block-from-end
1435 ,(cl-find-if
1436 #'markdown-text-property-at-point
1437 (markdown-get-fenced-block-end-properties)))))))))
1439 (defun markdown-propertize-end-match (reg end fence-spec middle-begin)
1440 "Get match for REG up to END, if exists, and propertize appropriately.
1441 FENCE-SPEC is an entry in `markdown-fenced-block-pairs' and
1442 MIDDLE-BEGIN is the start of the \"middle\" section of the block."
1443 (when (re-search-forward reg end t)
1444 (let ((close-begin (match-beginning 0)) ; Start of closing line.
1445 (close-end (match-end 0)) ; End of closing line.
1446 (close-data (match-data t))) ; Match data for closing line.
1447 ;; Propertize middle section of fenced block.
1448 (put-text-property middle-begin close-begin
1449 (cl-third fence-spec)
1450 (list middle-begin close-begin))
1451 ;; If the block is a YAML block, propertize the declarations inside
1452 (markdown-syntax-propertize-yaml-metadata middle-begin close-begin)
1453 ;; Propertize closing line of fenced block.
1454 (put-text-property close-begin close-end
1455 (cl-cadadr fence-spec) close-data))))
1457 (defun markdown-syntax-propertize-fenced-block-constructs (start end)
1458 "Propertize according to `markdown-fenced-block-pairs' from START to END.
1459 If unable to propertize an entire block (if the start of a block is within START
1460 and END, but the end of the block is not), propertize the start section of a
1461 block, then in a subsequent call propertize both middle and end by finding the
1462 start which was previously propertized."
1463 (let ((start-reg (markdown-get-start-fence-regexp)))
1464 (save-excursion
1465 (goto-char start)
1466 ;; start from previous unclosed block, if exists
1467 (let ((prev-begin-block (markdown-find-previous-block)))
1468 (when prev-begin-block
1469 (let* ((correct-entry
1470 (cl-find-if (lambda (entry)
1471 (eq (cdr prev-begin-block) (cl-cadar entry)))
1472 markdown-fenced-block-pairs))
1473 (enclosed-text-start (1+ (car prev-begin-block)))
1474 (start-length
1475 (save-excursion
1476 (goto-char (car prev-begin-block))
1477 (string-match
1478 (markdown-maybe-funcall-regexp
1479 (caar correct-entry))
1480 (buffer-substring
1481 (point-at-bol) (point-at-eol)))
1482 (- (match-end 1) (match-beginning 1))))
1483 (end-reg (markdown-maybe-funcall-regexp
1484 (cl-caadr correct-entry) start-length)))
1485 (markdown-propertize-end-match
1486 end-reg end correct-entry enclosed-text-start))))
1487 ;; find all new blocks within region
1488 (while (re-search-forward start-reg end t)
1489 ;; we assume the opening constructs take up (only) an entire line,
1490 ;; so we re-check the current line
1491 (let* ((cur-line (buffer-substring (point-at-bol) (point-at-eol)))
1492 ;; find entry in `markdown-fenced-block-pairs' corresponding
1493 ;; to regex which was matched
1494 (correct-entry
1495 (cl-find-if
1496 (lambda (fenced-pair)
1497 (string-match-p
1498 (markdown-maybe-funcall-regexp (caar fenced-pair))
1499 cur-line))
1500 markdown-fenced-block-pairs))
1501 (enclosed-text-start
1502 (save-excursion (1+ (point-at-eol))))
1503 (end-reg
1504 (markdown-maybe-funcall-regexp
1505 (cl-caadr correct-entry)
1506 (if (and (match-beginning 1) (match-end 1))
1507 (- (match-end 1) (match-beginning 1))
1508 0))))
1509 ;; get correct match data
1510 (save-excursion
1511 (beginning-of-line)
1512 (re-search-forward
1513 (markdown-maybe-funcall-regexp (caar correct-entry))
1514 (point-at-eol)))
1515 ;; mark starting, even if ending is outside of region
1516 (put-text-property (match-beginning 0) (match-end 0)
1517 (cl-cadar correct-entry) (match-data t))
1518 (markdown-propertize-end-match
1519 end-reg end correct-entry enclosed-text-start))))))
1521 (defun markdown-syntax-propertize-blockquotes (start end)
1522 "Match blockquotes from START to END."
1523 (save-excursion
1524 (goto-char start)
1525 (while (and (re-search-forward markdown-regex-blockquote end t)
1526 (not (markdown-code-block-at-pos (match-beginning 0))))
1527 (put-text-property (match-beginning 0) (match-end 0)
1528 'markdown-blockquote
1529 (match-data t)))))
1531 (defun markdown-syntax-propertize-hrs (start end)
1532 "Match horizontal rules from START to END."
1533 (save-excursion
1534 (goto-char start)
1535 (while (re-search-forward markdown-regex-hr end t)
1536 (unless (or (markdown-on-heading-p)
1537 (markdown-code-block-at-point-p))
1538 (put-text-property (match-beginning 0) (match-end 0)
1539 'markdown-hr
1540 (match-data t))))))
1542 (defun markdown-syntax-propertize-yaml-metadata (start end)
1543 "Propertize elements inside YAML metadata blocks from START to END.
1544 Assumes region from START and END is already known to be the interior
1545 region of a YAML metadata block as propertized by
1546 `markdown-syntax-propertize-fenced-block-constructs'."
1547 (save-excursion
1548 (goto-char start)
1549 (cl-loop
1550 while (re-search-forward markdown-regex-declarative-metadata end t)
1551 do (progn
1552 (put-text-property (match-beginning 1) (match-end 1)
1553 'markdown-metadata-key (match-data t))
1554 (put-text-property (match-beginning 2) (match-end 2)
1555 'markdown-metadata-markup (match-data t))
1556 (put-text-property (match-beginning 3) (match-end 3)
1557 'markdown-metadata-value (match-data t))))))
1559 (defun markdown-syntax-propertize-headings (start end)
1560 "Match headings of type SYMBOL with REGEX from START to END."
1561 (goto-char start)
1562 (while (re-search-forward markdown-regex-header end t)
1563 (unless (markdown-code-block-at-pos (match-beginning 0))
1564 (put-text-property
1565 (match-beginning 0) (match-end 0) 'markdown-heading
1566 (match-data t))
1567 (put-text-property
1568 (match-beginning 0) (match-end 0)
1569 (cond ((match-string-no-properties 2) 'markdown-heading-1-setext)
1570 ((match-string-no-properties 3) 'markdown-heading-2-setext)
1571 (t (let ((atx-level (length (markdown-trim-whitespace
1572 (match-string-no-properties 4)))))
1573 (intern (format "markdown-heading-%d-atx" atx-level)))))
1574 (match-data t)))))
1576 (defun markdown-syntax-propertize-comments (start end)
1577 "Match HTML comments from the START to END."
1578 (let* ((in-comment (nth 4 (syntax-ppss))))
1579 (goto-char start)
1580 (cond
1581 ;; Comment start
1582 ((and (not in-comment)
1583 (re-search-forward markdown-regex-comment-start end t)
1584 (not (markdown-inline-code-at-point-p))
1585 (not (markdown-code-block-at-point-p)))
1586 (let ((open-beg (match-beginning 0)))
1587 (put-text-property open-beg (1+ open-beg)
1588 'syntax-table (string-to-syntax "<"))
1589 (markdown-syntax-propertize-comments
1590 (min (1+ (match-end 0)) end (point-max)) end)))
1591 ;; Comment end
1592 ((and in-comment
1593 (re-search-forward markdown-regex-comment-end end t))
1594 (let ((comment-end (match-end 0))
1595 (comment-begin (nth 8 (syntax-ppss))))
1596 (put-text-property (1- comment-end) comment-end
1597 'syntax-table (string-to-syntax ">"))
1598 ;; Remove any other text properties inside the comment
1599 (remove-text-properties comment-begin comment-end
1600 markdown--syntax-properties)
1601 (put-text-property comment-begin comment-end
1602 'markdown-comment (list comment-begin comment-end))
1603 (markdown-syntax-propertize-comments
1604 (min (1+ comment-end) end (point-max)) end)))
1605 ;; Nothing found
1606 (t nil))))
1608 (defun markdown-syntax-propertize (start end)
1609 "Function used as `syntax-propertize-function'.
1610 START and END delimit region to propertize."
1611 (with-silent-modifications
1612 (save-excursion
1613 (remove-text-properties start end markdown--syntax-properties)
1614 (markdown-syntax-propertize-fenced-block-constructs start end)
1615 (markdown-syntax-propertize-list-items start end)
1616 (markdown-syntax-propertize-pre-blocks start end)
1617 (markdown-syntax-propertize-blockquotes start end)
1618 (markdown-syntax-propertize-headings start end)
1619 (markdown-syntax-propertize-hrs start end)
1620 (markdown-syntax-propertize-comments start end))))
1623 ;;; Markup Hiding
1625 (defconst markdown-markup-properties
1626 '(face markdown-markup-face invisible markdown-markup)
1627 "List of properties and values to apply to markup.")
1629 (defconst markdown-language-keyword-properties
1630 '(face markdown-language-keyword-face invisible markdown-markup)
1631 "List of properties and values to apply to code block language names.")
1633 (defconst markdown-language-info-properties
1634 '(face markdown-language-info-face invisible markdown-markup)
1635 "List of properties and values to apply to code block language info strings.")
1637 (defconst markdown-include-title-properties
1638 '(face markdown-link-title-face invisible markdown-markup)
1639 "List of properties and values to apply to included code titles.")
1641 (defcustom markdown-hide-markup nil
1642 "Determines whether markup in the buffer will be hidden.
1643 When set to nil, all markup is displayed in the buffer as it
1644 appears in the file. An exception is when `markdown-hide-urls'
1645 is non-nil.
1646 Set this to a non-nil value to turn this feature on by default.
1647 You can interactively toggle the value of this variable with
1648 `markdown-toggle-markup-hiding', \\[markdown-toggle-markup-hiding],
1649 or from the Markdown > Show & Hide menu.
1651 Markup hiding works by adding text properties to positions in the
1652 buffer---either the `invisible' property or the `display' property
1653 in cases where alternative glyphs are used (e.g., list bullets).
1654 This does not, however, affect printing or other output.
1655 Functions such as `htmlfontify-buffer' and `ps-print-buffer' will
1656 not honor these text properties. For printing, it would be better
1657 to first convert to HTML or PDF (e.g,. using Pandoc)."
1658 :group 'markdown
1659 :type 'boolean
1660 :safe 'booleanp
1661 :package-version '(markdown-mode . "2.3"))
1662 (make-variable-buffer-local 'markdown-hide-markup)
1664 (defun markdown-toggle-markup-hiding (&optional arg)
1665 "Toggle the display or hiding of markup.
1666 With a prefix argument ARG, enable markup hiding if ARG is positive,
1667 and disable it otherwise.
1668 See `markdown-hide-markup' for additional details."
1669 (interactive (list (or current-prefix-arg 'toggle)))
1670 (setq markdown-hide-markup
1671 (if (eq arg 'toggle)
1672 (not markdown-hide-markup)
1673 (> (prefix-numeric-value arg) 0)))
1674 (if markdown-hide-markup
1675 (progn (add-to-invisibility-spec 'markdown-markup)
1676 (message "markdown-mode markup hiding enabled"))
1677 (progn (remove-from-invisibility-spec 'markdown-markup)
1678 (message "markdown-mode markup hiding disabled")))
1679 (markdown-reload-extensions))
1682 ;;; Font Lock =================================================================
1684 (require 'font-lock)
1686 (defvar markdown-italic-face 'markdown-italic-face
1687 "Face name to use for italic text.")
1689 (defvar markdown-bold-face 'markdown-bold-face
1690 "Face name to use for bold text.")
1692 (defvar markdown-strike-through-face 'markdown-strike-through-face
1693 "Face name to use for strike-through text.")
1695 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
1696 "Face name to use as a base for header delimiters.")
1698 (defvar markdown-header-rule-face 'markdown-header-rule-face
1699 "Face name to use as a base for header rules.")
1701 (defvar markdown-header-face 'markdown-header-face
1702 "Face name to use as a base for headers.")
1704 (defvar markdown-header-face-1 'markdown-header-face-1
1705 "Face name to use for level-1 headers.")
1707 (defvar markdown-header-face-2 'markdown-header-face-2
1708 "Face name to use for level-2 headers.")
1710 (defvar markdown-header-face-3 'markdown-header-face-3
1711 "Face name to use for level-3 headers.")
1713 (defvar markdown-header-face-4 'markdown-header-face-4
1714 "Face name to use for level-4 headers.")
1716 (defvar markdown-header-face-5 'markdown-header-face-5
1717 "Face name to use for level-5 headers.")
1719 (defvar markdown-header-face-6 'markdown-header-face-6
1720 "Face name to use for level-6 headers.")
1722 (defvar markdown-inline-code-face 'markdown-inline-code-face
1723 "Face name to use for inline code.")
1725 (defvar markdown-list-face 'markdown-list-face
1726 "Face name to use for list markers.")
1728 (defvar markdown-blockquote-face 'markdown-blockquote-face
1729 "Face name to use for blockquote.")
1731 (defvar markdown-pre-face 'markdown-pre-face
1732 "Face name to use for preformatted text.")
1734 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
1735 "Face name to use for programming language identifiers.")
1737 (defvar markdown-language-info-face 'markdown-language-info-face
1738 "Face name to use for programming info strings.")
1740 (defvar markdown-link-face 'markdown-link-face
1741 "Face name to use for links.")
1743 (defvar markdown-missing-link-face 'markdown-missing-link-face
1744 "Face name to use for links where the linked file does not exist.")
1746 (defvar markdown-reference-face 'markdown-reference-face
1747 "Face name to use for reference.")
1749 (defvar markdown-footnote-marker-face 'markdown-footnote-marker-face
1750 "Face name to use for footnote markers.")
1752 (defvar markdown-url-face 'markdown-url-face
1753 "Face name to use for URLs.")
1755 (defvar markdown-link-title-face 'markdown-link-title-face
1756 "Face name to use for reference link titles.")
1758 (defvar markdown-line-break-face 'markdown-line-break-face
1759 "Face name to use for hard line breaks.")
1761 (defvar markdown-comment-face 'markdown-comment-face
1762 "Face name to use for HTML comments.")
1764 (defvar markdown-math-face 'markdown-math-face
1765 "Face name to use for LaTeX expressions.")
1767 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
1768 "Face name to use for metadata keys.")
1770 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
1771 "Face name to use for metadata values.")
1773 (defvar markdown-gfm-checkbox-face 'markdown-gfm-checkbox-face
1774 "Face name to use for GFM checkboxes.")
1776 (defvar markdown-highlight-face 'markdown-highlight-face
1777 "Face name to use for mouse highlighting.")
1779 (defvar markdown-markup-face 'markdown-markup-face
1780 "Face name to use for markup elements.")
1782 (make-obsolete-variable 'markdown-italic-face "Use face name directly" "v2.4")
1783 (make-obsolete-variable 'markdown-bold-face "Use face name directly" "v2.4")
1784 (make-obsolete-variable 'markdown-strike-through-face "Use face name directly" "v2.4")
1785 (make-obsolete-variable 'markdown-header-delimiter-face "Use face name directly" "v2.4")
1786 (make-obsolete-variable 'markdown-header-rule-face "Use face name directly" "v2.4")
1787 (make-obsolete-variable 'markdown-header-face "Use face name directly" "v2.4")
1788 (make-obsolete-variable 'markdown-header-face-1 "Use face name directly" "v2.4")
1789 (make-obsolete-variable 'markdown-header-face-2 "Use face name directly" "v2.4")
1790 (make-obsolete-variable 'markdown-header-face-3 "Use face name directly" "v2.4")
1791 (make-obsolete-variable 'markdown-header-face-4 "Use face name directly" "v2.4")
1792 (make-obsolete-variable 'markdown-header-face-5 "Use face name directly" "v2.4")
1793 (make-obsolete-variable 'markdown-header-face-6 "Use face name directly" "v2.4")
1794 (make-obsolete-variable 'markdown-inline-code-face "Use face name directly" "v2.4")
1795 (make-obsolete-variable 'markdown-list-face "Use face name directly" "v2.4")
1796 (make-obsolete-variable 'markdown-blockquote-face "Use face name directly" "v2.4")
1797 (make-obsolete-variable 'markdown-pre-face "Use face name directly" "v2.4")
1798 (make-obsolete-variable 'markdown-language-keyword-face "Use face name directly" "v2.4")
1799 (make-obsolete-variable 'markdown-language-info-face "Use face name directly" "v2.4")
1800 (make-obsolete-variable 'markdown-link-face "Use face name directly" "v2.4")
1801 (make-obsolete-variable 'markdown-missing-link-face "Use face name directly" "v2.4")
1802 (make-obsolete-variable 'markdown-reference-face "Use face name directly" "v2.4")
1803 (make-obsolete-variable 'markdown-footnote-marker-face "Use face name directly" "v2.4")
1804 (make-obsolete-variable 'markdown-url-face "Use face name directly" "v2.4")
1805 (make-obsolete-variable 'markdown-link-title-face "Use face name directly" "v2.4")
1806 (make-obsolete-variable 'markdown-line-break-face "Use face name directly" "v2.4")
1807 (make-obsolete-variable 'markdown-comment-face "Use face name directly" "v2.4")
1808 (make-obsolete-variable 'markdown-math-face "Use face name directly" "v2.4")
1809 (make-obsolete-variable 'markdown-metadata-key-face "Use face name directly" "v2.4")
1810 (make-obsolete-variable 'markdown-metadata-value-face "Use face name directly" "v2.4")
1811 (make-obsolete-variable 'markdown-gfm-checkbox-face "Use face name directly" "v2.4")
1812 (make-obsolete-variable 'markdown-highlight-face "Use face name directly" "v2.4")
1813 (make-obsolete-variable 'markdown-markup-face "Use face name directly" "v2.4")
1815 (defgroup markdown-faces nil
1816 "Faces used in Markdown Mode"
1817 :group 'markdown
1818 :group 'faces)
1820 (defface markdown-italic-face
1821 '((t (:inherit italic)))
1822 "Face for italic text."
1823 :group 'markdown-faces)
1825 (defface markdown-bold-face
1826 '((t (:inherit bold)))
1827 "Face for bold text."
1828 :group 'markdown-faces)
1830 (defface markdown-strike-through-face
1831 '((t (:strike-through t)))
1832 "Face for strike-through text."
1833 :group 'markdown-faces)
1835 (defface markdown-markup-face
1836 '((t (:inherit shadow :slant normal :weight normal)))
1837 "Face for markup elements."
1838 :group 'markdown-faces)
1840 (defface markdown-header-rule-face
1841 '((t (:inherit markdown-markup-face)))
1842 "Base face for headers rules."
1843 :group 'markdown-faces)
1845 (defface markdown-header-delimiter-face
1846 '((t (:inherit markdown-markup-face)))
1847 "Base face for headers hash delimiter."
1848 :group 'markdown-faces)
1850 (defface markdown-list-face
1851 '((t (:inherit markdown-markup-face)))
1852 "Face for list item markers."
1853 :group 'markdown-faces)
1855 (defface markdown-blockquote-face
1856 '((t (:inherit font-lock-doc-face)))
1857 "Face for blockquote sections."
1858 :group 'markdown-faces)
1860 (defface markdown-code-face
1861 '((t (:inherit fixed-pitch)))
1862 "Face for inline code, pre blocks, and fenced code blocks.
1863 This may be used, for example, to add a contrasting background to
1864 inline code fragments and code blocks."
1865 :group 'markdown-faces)
1867 (defface markdown-inline-code-face
1868 '((t (:inherit (markdown-code-face font-lock-constant-face))))
1869 "Face for inline code."
1870 :group 'markdown-faces)
1872 (defface markdown-pre-face
1873 '((t (:inherit (markdown-code-face font-lock-constant-face))))
1874 "Face for preformatted text."
1875 :group 'markdown-faces)
1877 (defface markdown-table-face
1878 '((t (:inherit (markdown-code-face))))
1879 "Face for tables."
1880 :group 'markdown-faces)
1882 (defface markdown-language-keyword-face
1883 '((t (:inherit font-lock-type-face)))
1884 "Face for programming language identifiers."
1885 :group 'markdown-faces)
1887 (defface markdown-language-info-face
1888 '((t (:inherit font-lock-string-face)))
1889 "Face for programming language info strings."
1890 :group 'markdown-faces)
1892 (defface markdown-link-face
1893 '((t (:inherit link)))
1894 "Face for links."
1895 :group 'markdown-faces)
1897 (defface markdown-missing-link-face
1898 '((t (:inherit font-lock-warning-face)))
1899 "Face for missing links."
1900 :group 'markdown-faces)
1902 (defface markdown-reference-face
1903 '((t (:inherit markdown-markup-face)))
1904 "Face for link references."
1905 :group 'markdown-faces)
1907 (define-obsolete-face-alias 'markdown-footnote-face
1908 'markdown-footnote-marker-face "v2.3")
1910 (defface markdown-footnote-marker-face
1911 '((t (:inherit markdown-markup-face)))
1912 "Face for footnote markers."
1913 :group 'markdown-faces)
1915 (defface markdown-footnote-text-face
1916 '((t (:inherit font-lock-comment-face)))
1917 "Face for footnote text."
1918 :group 'markdown-faces)
1920 (defface markdown-url-face
1921 '((t (:inherit font-lock-string-face)))
1922 "Face for URLs that are part of markup.
1923 For example, this applies to URLs in inline links:
1924 [link text](http://example.com/)."
1925 :group 'markdown-faces)
1927 (defface markdown-plain-url-face
1928 '((t (:inherit markdown-link-face)))
1929 "Face for URLs that are also links.
1930 For example, this applies to plain angle bracket URLs:
1931 <http://example.com/>."
1932 :group 'markdown-faces)
1934 (defface markdown-link-title-face
1935 '((t (:inherit font-lock-comment-face)))
1936 "Face for reference link titles."
1937 :group 'markdown-faces)
1939 (defface markdown-line-break-face
1940 '((t (:inherit font-lock-constant-face :underline t)))
1941 "Face for hard line breaks."
1942 :group 'markdown-faces)
1944 (defface markdown-comment-face
1945 '((t (:inherit font-lock-comment-face)))
1946 "Face for HTML comments."
1947 :group 'markdown-faces)
1949 (defface markdown-math-face
1950 '((t (:inherit font-lock-string-face)))
1951 "Face for LaTeX expressions."
1952 :group 'markdown-faces)
1954 (defface markdown-metadata-key-face
1955 '((t (:inherit font-lock-variable-name-face)))
1956 "Face for metadata keys."
1957 :group 'markdown-faces)
1959 (defface markdown-metadata-value-face
1960 '((t (:inherit font-lock-string-face)))
1961 "Face for metadata values."
1962 :group 'markdown-faces)
1964 (defface markdown-gfm-checkbox-face
1965 '((t (:inherit font-lock-builtin-face)))
1966 "Face for GFM checkboxes."
1967 :group 'markdown-faces)
1969 (defface markdown-highlight-face
1970 '((t (:inherit highlight)))
1971 "Face for mouse highlighting."
1972 :group 'markdown-faces)
1974 (defface markdown-hr-face
1975 '((t (:inherit markdown-markup-face)))
1976 "Face for horizontal rules."
1977 :group 'markdown-faces)
1979 (defface markdown-html-tag-name-face
1980 '((t (:inherit font-lock-type-face)))
1981 "Face for HTML tag names."
1982 :group 'markdown-faces)
1984 (defface markdown-html-tag-delimiter-face
1985 '((t (:inherit markdown-markup-face)))
1986 "Face for HTML tag delimiters."
1987 :group 'markdown-faces)
1989 (defface markdown-html-attr-name-face
1990 '((t (:inherit font-lock-variable-name-face)))
1991 "Face for HTML attribute names."
1992 :group 'markdown-faces)
1994 (defface markdown-html-attr-value-face
1995 '((t (:inherit font-lock-string-face)))
1996 "Face for HTML attribute values."
1997 :group 'markdown-faces)
1999 (defface markdown-html-entity-face
2000 '((t (:inherit font-lock-variable-name-face)))
2001 "Face for HTML entities."
2002 :group 'markdown-faces)
2004 (defcustom markdown-header-scaling nil
2005 "Whether to use variable-height faces for headers.
2006 When non-nil, `markdown-header-face' will inherit from
2007 `variable-pitch' and the scaling values in
2008 `markdown-header-scaling-values' will be applied to
2009 headers of levels one through six respectively."
2010 :type 'boolean
2011 :initialize 'custom-initialize-default
2012 :set (lambda (symbol value)
2013 (set-default symbol value)
2014 (markdown-update-header-faces value))
2015 :group 'markdown-faces
2016 :package-version '(markdown-mode . "2.2"))
2018 (defcustom markdown-header-scaling-values
2019 '(2.0 1.7 1.4 1.1 1.0 1.0)
2020 "List of scaling values for headers of level one through six.
2021 Used when `markdown-header-scaling' is non-nil."
2022 :type 'list
2023 :initialize 'custom-initialize-default
2024 :set (lambda (symbol value)
2025 (set-default symbol value)
2026 (markdown-update-header-faces markdown-header-scaling value))
2027 :group 'markdown-faces)
2029 (defun markdown-make-header-faces ()
2030 "Build the faces used for Markdown headers."
2031 (let ((inherit-faces '(font-lock-function-name-face)))
2032 (when markdown-header-scaling
2033 (setq inherit-faces (cons 'variable-pitch inherit-faces)))
2034 (defface markdown-header-face
2035 `((t (:inherit ,inherit-faces :weight bold)))
2036 "Base face for headers."
2037 :group 'markdown-faces))
2038 (dotimes (num 6)
2039 (let* ((num1 (1+ num))
2040 (face-name (intern (format "markdown-header-face-%s" num1)))
2041 (scale (if markdown-header-scaling
2042 (float (nth num markdown-header-scaling-values))
2043 1.0)))
2044 (eval
2045 `(defface ,face-name
2046 '((t (:inherit markdown-header-face :height ,scale)))
2047 (format "Face for level %s headers.
2048 You probably don't want to customize this face directly. Instead
2049 you can customize the base face `markdown-header-face' or the
2050 variable-height variable `markdown-header-scaling'." ,num1)
2051 :group 'markdown-faces)))))
2053 (markdown-make-header-faces)
2055 (defun markdown-update-header-faces (&optional scaling scaling-values)
2056 "Update header faces, depending on if header SCALING is desired.
2057 If so, use given list of SCALING-VALUES relative to the baseline
2058 size of `markdown-header-face'."
2059 (dotimes (num 6)
2060 (let* ((face-name (intern (format "markdown-header-face-%s" (1+ num))))
2061 (scale (cond ((not scaling) 1.0)
2062 (scaling-values (float (nth num scaling-values)))
2063 (t (float (nth num markdown-header-scaling-values))))))
2064 (unless (get face-name 'saved-face) ; Don't update customized faces
2065 (set-face-attribute face-name nil :height scale)))))
2067 (defun markdown-syntactic-face (state)
2068 "Return font-lock face for characters with given STATE.
2069 See `font-lock-syntactic-face-function' for details."
2070 (let ((in-comment (nth 4 state)))
2071 (cond
2072 (in-comment 'markdown-comment-face)
2073 (t nil))))
2075 (defcustom markdown-list-item-bullets
2076 '("●" "◎" "○" "◆" "◇" "►" "•")
2077 "List of bullets to use for unordered lists.
2078 It can contain any number of symbols, which will be repeated.
2079 Depending on your font, some reasonable choices are:
2080 ♥ ● ◇ ✚ ✜ ☯ ◆ ♠ ♣ ♦ ❀ ◆ ◖ ▶ ► • ★ ▸."
2081 :group 'markdown
2082 :type '(repeat (string :tag "Bullet character"))
2083 :package-version '(markdown-mode . "2.3"))
2085 (defun markdown--footnote-marker-properties ()
2086 "Return a font-lock facespec expression for footnote marker text."
2087 `(face markdown-footnote-marker-face
2088 ,@(when markdown-hide-markup
2089 `(display ,markdown-footnote-display))))
2091 (defun markdown--pandoc-inline-footnote-properties ()
2092 "Return a font-lock facespec expression for Pandoc inline footnote text."
2093 `(face markdown-footnote-text-face
2094 ,@(when markdown-hide-markup
2095 `(display ,markdown-footnote-display))))
2097 (defvar markdown-mode-font-lock-keywords-basic
2098 `((markdown-match-yaml-metadata-begin . ((1 'markdown-markup-face)))
2099 (markdown-match-yaml-metadata-end . ((1 'markdown-markup-face)))
2100 (markdown-match-yaml-metadata-key . ((1 'markdown-metadata-key-face)
2101 (2 'markdown-markup-face)
2102 (3 'markdown-metadata-value-face)))
2103 (markdown-match-gfm-open-code-blocks . ((1 markdown-markup-properties)
2104 (2 markdown-markup-properties nil t)
2105 (3 markdown-language-keyword-properties nil t)
2106 (4 markdown-language-info-properties nil t)
2107 (5 markdown-markup-properties nil t)))
2108 (markdown-match-gfm-close-code-blocks . ((0 markdown-markup-properties)))
2109 (markdown-fontify-gfm-code-blocks)
2110 (markdown-fontify-tables)
2111 (markdown-match-fenced-start-code-block . ((1 markdown-markup-properties)
2112 (2 markdown-markup-properties nil t)
2113 (3 markdown-language-keyword-properties nil t)
2114 (4 markdown-language-info-properties nil t)
2115 (5 markdown-markup-properties nil t)))
2116 (markdown-match-fenced-end-code-block . ((0 markdown-markup-properties)))
2117 (markdown-fontify-fenced-code-blocks)
2118 (markdown-match-pre-blocks . ((0 'markdown-pre-face)))
2119 (markdown-fontify-headings)
2120 (markdown-match-declarative-metadata . ((1 'markdown-metadata-key-face)
2121 (2 'markdown-markup-face)
2122 (3 'markdown-metadata-value-face)))
2123 (markdown-match-pandoc-metadata . ((1 'markdown-markup-face)
2124 (2 'markdown-markup-face)
2125 (3 'markdown-metadata-value-face)))
2126 (markdown-fontify-hrs)
2127 (markdown-match-code . ((1 markdown-markup-properties prepend)
2128 (2 'markdown-inline-code-face prepend)
2129 (3 markdown-markup-properties prepend)))
2130 (,markdown-regex-kbd . ((1 markdown-markup-properties)
2131 (2 'markdown-inline-code-face)
2132 (3 markdown-markup-properties)))
2133 (markdown-fontify-angle-uris)
2134 (,markdown-regex-email . 'markdown-plain-url-face)
2135 (markdown-match-html-tag . ((1 'markdown-html-tag-delimiter-face t)
2136 (2 'markdown-html-tag-name-face t)
2137 (3 'markdown-html-tag-delimiter-face t)
2138 ;; Anchored matcher for HTML tag attributes
2139 (,markdown-regex-html-attr
2140 ;; Before searching, move past tag
2141 ;; name; set limit at tag close.
2142 (progn
2143 (goto-char (match-end 2)) (match-end 3))
2145 . ((1 'markdown-html-attr-name-face)
2146 (3 'markdown-html-tag-delimiter-face nil t)
2147 (4 'markdown-html-attr-value-face nil t)))))
2148 (,markdown-regex-html-entity . 'markdown-html-entity-face)
2149 (markdown-fontify-list-items)
2150 (,markdown-regex-footnote . ((1 markdown-markup-properties) ; [^
2151 (2 (markdown--footnote-marker-properties)) ; label
2152 (3 markdown-markup-properties))) ; ]
2153 (,markdown-regex-pandoc-inline-footnote . ((1 markdown-markup-properties) ; ^
2154 (2 markdown-markup-properties) ; [
2155 (3 (markdown--pandoc-inline-footnote-properties)) ; text
2156 (4 markdown-markup-properties))) ; ]
2157 (markdown-match-includes . ((1 markdown-markup-properties)
2158 (2 markdown-markup-properties nil t)
2159 (3 markdown-include-title-properties nil t)
2160 (4 markdown-markup-properties nil t)
2161 (5 markdown-markup-properties)
2162 (6 'markdown-url-face)
2163 (7 markdown-markup-properties)))
2164 (markdown-fontify-inline-links)
2165 (markdown-fontify-reference-links)
2166 (,markdown-regex-reference-definition . ((1 'markdown-markup-face) ; [
2167 (2 'markdown-reference-face) ; label
2168 (3 'markdown-markup-face) ; ]
2169 (4 'markdown-markup-face) ; :
2170 (5 'markdown-url-face) ; url
2171 (6 'markdown-link-title-face))) ; "title" (optional)
2172 (markdown-fontify-plain-uris)
2173 ;; Math mode $..$
2174 (markdown-match-math-single . ((1 'markdown-markup-face prepend)
2175 (2 'markdown-math-face append)
2176 (3 'markdown-markup-face prepend)))
2177 ;; Math mode $$..$$
2178 (markdown-match-math-double . ((1 'markdown-markup-face prepend)
2179 (2 'markdown-math-face append)
2180 (3 'markdown-markup-face prepend)))
2181 ;; Math mode \[..\] and \\[..\\]
2182 (markdown-match-math-display . ((1 'markdown-markup-face prepend)
2183 (3 'markdown-math-face append)
2184 (4 'markdown-markup-face prepend)))
2185 (markdown-match-bold . ((1 markdown-markup-properties prepend)
2186 (2 'markdown-bold-face append)
2187 (3 markdown-markup-properties prepend)))
2188 (markdown-match-italic . ((1 markdown-markup-properties prepend)
2189 (2 'markdown-italic-face append)
2190 (3 markdown-markup-properties prepend)))
2191 (,markdown-regex-strike-through . ((3 markdown-markup-properties)
2192 (4 'markdown-strike-through-face)
2193 (5 markdown-markup-properties)))
2194 (,markdown-regex-line-break . (1 'markdown-line-break-face prepend))
2195 (markdown-fontify-sub-superscripts)
2196 (markdown-match-inline-attributes . ((0 markdown-markup-properties prepend)))
2197 (markdown-match-leanpub-sections . ((0 markdown-markup-properties)))
2198 (markdown-fontify-blockquotes)
2199 (markdown-match-wiki-link . ((0 'markdown-link-face prepend))))
2200 "Syntax highlighting for Markdown files.")
2202 (define-obsolete-variable-alias
2203 'markdown-mode-font-lock-keywords-basic
2204 'markdown-mode-font-lock-keywords "v2.4")
2206 ;; Footnotes
2207 (defvar markdown-footnote-counter 0
2208 "Counter for footnote numbers.")
2209 (make-variable-buffer-local 'markdown-footnote-counter)
2211 (defconst markdown-footnote-chars
2212 "[[:alnum:]-]"
2213 "Regular expression matching any character that is allowed in a footnote identifier.")
2215 (defconst markdown-regex-footnote-definition
2216 (concat "^ \\{0,3\\}\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:\\(?:[ \t]+\\|$\\)")
2217 "Regular expression matching a footnote definition, capturing the label.")
2220 ;;; Compatibility =============================================================
2222 (defun markdown-replace-regexp-in-string (regexp rep string)
2223 "Replace ocurrences of REGEXP with REP in STRING.
2224 This is a compatibility wrapper to provide `replace-regexp-in-string'
2225 in XEmacs 21."
2226 (if (featurep 'xemacs)
2227 (replace-in-string string regexp rep)
2228 (replace-regexp-in-string regexp rep string)))
2230 ;; `markdown-use-region-p' is a compatibility function which checks
2231 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
2232 (eval-and-compile
2233 (cond
2234 ;; Emacs 24 and newer
2235 ((fboundp 'use-region-p)
2236 (defalias 'markdown-use-region-p 'use-region-p))
2237 ;; XEmacs
2238 ((fboundp 'region-active-p)
2239 (defalias 'markdown-use-region-p 'region-active-p))))
2241 ;; Use new names for outline-mode functions in Emacs 25 and later.
2242 (eval-and-compile
2243 (defalias 'markdown-hide-sublevels
2244 (if (fboundp 'outline-hide-sublevels)
2245 'outline-hide-sublevels
2246 'hide-sublevels))
2247 (defalias 'markdown-show-all
2248 (if (fboundp 'outline-show-all)
2249 'outline-show-all
2250 'show-all))
2251 (defalias 'markdown-hide-body
2252 (if (fboundp 'outline-hide-body)
2253 'outline-hide-body
2254 'hide-body))
2255 (defalias 'markdown-show-children
2256 (if (fboundp 'outline-show-children)
2257 'outline-show-children
2258 'show-children))
2259 (defalias 'markdown-show-subtree
2260 (if (fboundp 'outline-show-subtree)
2261 'outline-show-subtree
2262 'show-subtree))
2263 (defalias 'markdown-hide-subtree
2264 (if (fboundp 'outline-hide-subtree)
2265 'outline-hide-subtree
2266 'hide-subtree)))
2268 ;; Provide directory-name-p to Emacs 24
2269 (defsubst markdown-directory-name-p (name)
2270 "Return non-nil if NAME ends with a directory separator character.
2271 Taken from `directory-name-p' from Emacs 25 and provided here for
2272 backwards compatibility."
2273 (let ((len (length name))
2274 (lastc ?.))
2275 (if (> len 0)
2276 (setq lastc (aref name (1- len))))
2277 (or (= lastc ?/)
2278 (and (memq system-type '(windows-nt ms-dos))
2279 (= lastc ?\\)))))
2281 ;; Provide a function to find files recursively in Emacs 24.
2282 (defalias 'markdown-directory-files-recursively
2283 (if (fboundp 'directory-files-recursively)
2284 'directory-files-recursively
2285 (lambda (dir regexp)
2286 "Return list of all files under DIR that have file names matching REGEXP.
2287 This function works recursively. Files are returned in \"depth first\"
2288 order, and files from each directory are sorted in alphabetical order.
2289 Each file name appears in the returned list in its absolute form.
2290 Based on `directory-files-recursively' from Emacs 25 and provided
2291 here for backwards compatibility."
2292 (let ((result nil)
2293 (files nil)
2294 ;; When DIR is "/", remote file names like "/method:" could
2295 ;; also be offered. We shall suppress them.
2296 (tramp-mode (and tramp-mode (file-remote-p (expand-file-name dir)))))
2297 (dolist (file (sort (file-name-all-completions "" dir)
2298 'string<))
2299 (unless (member file '("./" "../"))
2300 (if (markdown-directory-name-p file)
2301 (let* ((leaf (substring file 0 (1- (length file))))
2302 (full-file (expand-file-name leaf dir)))
2303 (setq result
2304 (nconc result (markdown-directory-files-recursively
2305 full-file regexp))))
2306 (when (string-match-p regexp file)
2307 (push (expand-file-name file dir) files)))))
2308 (nconc result (nreverse files))))))
2310 (defun markdown-flyspell-check-word-p ()
2311 "Return t if `flyspell' should check word just before point.
2312 Used for `flyspell-generic-check-word-predicate'."
2313 (save-excursion
2314 (goto-char (1- (point)))
2315 (not (or (markdown-code-block-at-point-p)
2316 (markdown-inline-code-at-point-p)
2317 (markdown-in-comment-p)
2318 (let ((faces (get-text-property (point) 'face)))
2319 (if (listp faces)
2320 (or (memq 'markdown-reference-face faces)
2321 (memq 'markdown-markup-face faces)
2322 (memq 'markdown-plain-url-face faces)
2323 (memq 'markdown-inline-code-face faces)
2324 (memq 'markdown-url-face faces))
2325 (memq faces '(markdown-reference-face
2326 markdown-markup-face
2327 markdown-plain-url-face
2328 markdown-inline-code-face
2329 markdown-url-face))))))))
2331 (defun markdown-font-lock-ensure ()
2332 "Provide `font-lock-ensure' in Emacs 24."
2333 (if (fboundp 'font-lock-ensure)
2334 (font-lock-ensure)
2335 (with-no-warnings
2336 ;; Suppress warning about non-interactive use of
2337 ;; `font-lock-fontify-buffer' in Emacs 25.
2338 (font-lock-fontify-buffer))))
2341 ;;; Markdown Parsing Functions ================================================
2343 (define-obsolete-function-alias
2344 'markdown-cur-line-blank 'markdown-cur-line-blank-p "v2.4")
2345 (define-obsolete-function-alias
2346 'markdown-next-line-blank 'markdown-next-line-blank-p "v2.4")
2348 (defun markdown-cur-line-blank-p ()
2349 "Return t if the current line is blank and nil otherwise."
2350 (save-excursion
2351 (beginning-of-line)
2352 (looking-at-p markdown-regex-blank-line)))
2354 (defun markdown-prev-line-blank ()
2355 "Return t if the previous line is blank and nil otherwise.
2356 If we are at the first line, then consider the previous line to be blank."
2357 (or (= (line-beginning-position) (point-min))
2358 (save-excursion
2359 (forward-line -1)
2360 (looking-at markdown-regex-blank-line))))
2362 (defun markdown-prev-line-blank-p ()
2363 "Like `markdown-prev-line-blank', but preserve `match-data'."
2364 (save-match-data (markdown-prev-line-blank)))
2366 (defun markdown-next-line-blank-p ()
2367 "Return t if the next line is blank and nil otherwise.
2368 If we are at the last line, then consider the next line to be blank."
2369 (or (= (line-end-position) (point-max))
2370 (save-excursion
2371 (forward-line 1)
2372 (markdown-cur-line-blank-p))))
2374 (defun markdown-prev-line-indent ()
2375 "Return the number of leading whitespace characters in the previous line.
2376 Return 0 if the current line is the first line in the buffer."
2377 (save-excursion
2378 (if (= (line-beginning-position) (point-min))
2380 (forward-line -1)
2381 (current-indentation))))
2383 (defun markdown-next-line-indent ()
2384 "Return the number of leading whitespace characters in the next line.
2385 Return 0 if line is the last line in the buffer."
2386 (save-excursion
2387 (if (= (line-end-position) (point-max))
2389 (forward-line 1)
2390 (current-indentation))))
2392 (defun markdown-new-baseline ()
2393 "Determine if the current line begins a new baseline level.
2394 Assume point is positioned at beginning of line."
2395 (or (looking-at markdown-regex-header)
2396 (looking-at markdown-regex-hr)
2397 (and (= (current-indentation) 0)
2398 (not (looking-at markdown-regex-list))
2399 (markdown-prev-line-blank))))
2401 (defun markdown-search-backward-baseline ()
2402 "Search backward baseline point with no indentation and not a list item."
2403 (end-of-line)
2404 (let (stop)
2405 (while (not (or stop (bobp)))
2406 (re-search-backward markdown-regex-block-separator-noindent nil t)
2407 (when (match-end 2)
2408 (goto-char (match-end 2))
2409 (cond
2410 ((markdown-new-baseline)
2411 (setq stop t))
2412 ((looking-at-p markdown-regex-list)
2413 (setq stop nil))
2414 (t (setq stop t)))))))
2416 (defun markdown-update-list-levels (marker indent levels)
2417 "Update list levels given list MARKER, block INDENT, and current LEVELS.
2418 Here, MARKER is a string representing the type of list, INDENT is an integer
2419 giving the indentation, in spaces, of the current block, and LEVELS is a
2420 list of the indentation levels of parent list items. When LEVELS is nil,
2421 it means we are at baseline (not inside of a nested list)."
2422 (cond
2423 ;; New list item at baseline.
2424 ((and marker (null levels))
2425 (setq levels (list indent)))
2426 ;; List item with greater indentation (four or more spaces).
2427 ;; Increase list level.
2428 ((and marker (>= indent (+ (car levels) 4)))
2429 (setq levels (cons indent levels)))
2430 ;; List item with greater or equal indentation (less than four spaces).
2431 ;; Do not increase list level.
2432 ((and marker (>= indent (car levels)))
2433 levels)
2434 ;; Lesser indentation level.
2435 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
2436 ;; indentation could move back more than one list level). Note
2437 ;; that this block need not be the beginning of list item.
2438 ((< indent (car levels))
2439 (while (and (> (length levels) 1)
2440 (< indent (+ (cadr levels) 4)))
2441 (setq levels (cdr levels)))
2442 levels)
2443 ;; Otherwise, do nothing.
2444 (t levels)))
2446 (defun markdown-calculate-list-levels ()
2447 "Calculate list levels at point.
2448 Return a list of the form (n1 n2 n3 ...) where n1 is the
2449 indentation of the deepest nested list item in the branch of
2450 the list at the point, n2 is the indentation of the parent
2451 list item, and so on. The depth of the list item is therefore
2452 the length of the returned list. If the point is not at or
2453 immediately after a list item, return nil."
2454 (save-excursion
2455 (let ((first (point)) levels indent pre-regexp)
2456 ;; Find a baseline point with zero list indentation
2457 (markdown-search-backward-baseline)
2458 ;; Search for all list items between baseline and LOC
2459 (while (and (< (point) first)
2460 (re-search-forward markdown-regex-list first t))
2461 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
2462 (beginning-of-line)
2463 (cond
2464 ;; Make sure this is not a header or hr
2465 ((markdown-new-baseline) (setq levels nil))
2466 ;; Make sure this is not a line from a pre block
2467 ((looking-at-p pre-regexp))
2468 ;; If not, then update levels
2470 (setq indent (current-indentation))
2471 (setq levels (markdown-update-list-levels (match-string 2)
2472 indent levels))))
2473 (end-of-line))
2474 levels)))
2476 (defun markdown-prev-list-item (level)
2477 "Search backward from point for a list item with indentation LEVEL.
2478 Set point to the beginning of the item, and return point, or nil
2479 upon failure."
2480 (let (bounds indent prev)
2481 (setq prev (point))
2482 (forward-line -1)
2483 (setq indent (current-indentation))
2484 (while
2485 (cond
2486 ;; List item
2487 ((and (looking-at-p markdown-regex-list)
2488 (setq bounds (markdown-cur-list-item-bounds)))
2489 (cond
2490 ;; Stop and return point at item of equal indentation
2491 ((= (nth 3 bounds) level)
2492 (setq prev (point))
2493 nil)
2494 ;; Stop and return nil at item with lesser indentation
2495 ((< (nth 3 bounds) level)
2496 (setq prev nil)
2497 nil)
2498 ;; Stop at beginning of buffer
2499 ((bobp) (setq prev nil))
2500 ;; Continue at item with greater indentation
2501 ((> (nth 3 bounds) level) t)))
2502 ;; Stop at beginning of buffer
2503 ((bobp) (setq prev nil))
2504 ;; Continue if current line is blank
2505 ((markdown-cur-line-blank-p) t)
2506 ;; Continue while indentation is the same or greater
2507 ((>= indent level) t)
2508 ;; Stop if current indentation is less than list item
2509 ;; and the next is blank
2510 ((and (< indent level)
2511 (markdown-next-line-blank-p))
2512 (setq prev nil))
2513 ;; Stop at a header
2514 ((looking-at-p markdown-regex-header) (setq prev nil))
2515 ;; Stop at a horizontal rule
2516 ((looking-at-p markdown-regex-hr) (setq prev nil))
2517 ;; Otherwise, continue.
2518 (t t))
2519 (forward-line -1)
2520 (setq indent (current-indentation)))
2521 prev))
2523 (defun markdown-next-list-item (level)
2524 "Search forward from point for the next list item with indentation LEVEL.
2525 Set point to the beginning of the item, and return point, or nil
2526 upon failure."
2527 (let (bounds indent next)
2528 (setq next (point))
2529 (if (looking-at markdown-regex-header-setext)
2530 (goto-char (match-end 0)))
2531 (forward-line)
2532 (setq indent (current-indentation))
2533 (while
2534 (cond
2535 ;; Stop at end of the buffer.
2536 ((eobp) nil)
2537 ;; Continue if the current line is blank
2538 ((markdown-cur-line-blank-p) t)
2539 ;; List item
2540 ((and (looking-at-p markdown-regex-list)
2541 (setq bounds (markdown-cur-list-item-bounds)))
2542 (cond
2543 ;; Continue at item with greater indentation
2544 ((> (nth 3 bounds) level) t)
2545 ;; Stop and return point at item of equal indentation
2546 ((= (nth 3 bounds) level)
2547 (setq next (point))
2548 nil)
2549 ;; Stop and return nil at item with lesser indentation
2550 ((< (nth 3 bounds) level)
2551 (setq next nil)
2552 nil)))
2553 ;; Continue while indentation is the same or greater
2554 ((>= indent level) t)
2555 ;; Stop if current indentation is less than list item
2556 ;; and the previous line was blank.
2557 ((and (< indent level)
2558 (markdown-prev-line-blank-p))
2559 (setq next nil))
2560 ;; Stop at a header
2561 ((looking-at-p markdown-regex-header) (setq next nil))
2562 ;; Stop at a horizontal rule
2563 ((looking-at-p markdown-regex-hr) (setq next nil))
2564 ;; Otherwise, continue.
2565 (t t))
2566 (forward-line)
2567 (setq indent (current-indentation)))
2568 next))
2570 (defun markdown-cur-list-item-end (level)
2571 "Move to end of list item with pre-marker indentation LEVEL.
2572 Return the point at the end when a list item was found at the
2573 original point. If the point is not in a list item, do nothing."
2574 (let (indent)
2575 (forward-line)
2576 (setq indent (current-indentation))
2577 (while
2578 (cond
2579 ;; Stop at end of the buffer.
2580 ((eobp) nil)
2581 ;; Continue if the current line is blank
2582 ((looking-at markdown-regex-blank-line) t)
2583 ;; Continue while indentation is the same or greater
2584 ((>= indent level) t)
2585 ;; Stop if current indentation is less than list item
2586 ;; and the previous line was blank.
2587 ((and (< indent level)
2588 (markdown-prev-line-blank))
2589 nil)
2590 ;; Stop at a new list item of the same or lesser indentation
2591 ((looking-at markdown-regex-list) nil)
2592 ;; Stop at a header
2593 ((looking-at markdown-regex-header) nil)
2594 ;; Stop at a horizontal rule
2595 ((looking-at markdown-regex-hr) nil)
2596 ;; Otherwise, continue.
2597 (t t))
2598 (forward-line)
2599 (setq indent (current-indentation)))
2600 ;; Don't skip over whitespace for empty list items (marker and
2601 ;; whitespace only), just move to end of whitespace.
2602 (save-match-data
2603 (if (looking-back (concat markdown-regex-list "\\s-*") (point-at-bol))
2604 (goto-char (match-end 3))
2605 (skip-chars-backward " \t\n")))
2606 (point)))
2608 (defun markdown-cur-list-item-bounds ()
2609 "Return bounds for list item at point.
2610 Return a list of the following form:
2612 (begin end indent nonlist-indent marker checkbox match)
2614 The named components are:
2616 - begin: Position of beginning of list item, including leading indentation.
2617 - end: Position of the end of the list item, including list item text.
2618 - indent: Number of characters of indentation before list marker (an integer).
2619 - nonlist-indent: Number characters of indentation, list
2620 marker, and whitespace following list marker (an integer).
2621 - marker: String containing the list marker and following whitespace
2622 (e.g., \"- \" or \"* \").
2623 - checkbox: String containing the GFM checkbox portion, if any,
2624 including any trailing whitespace before the text
2625 begins (e.g., \"[x] \").
2626 - match: match data for markdown-regex-list
2628 As an example, for the following unordered list item
2630 - item
2632 the returned list would be
2634 (1 14 3 5 \"- \" nil (1 6 1 4 4 5 5 6))
2636 If the point is not inside a list item, return nil."
2637 (car (get-text-property (point-at-bol) 'markdown-list-item)))
2639 (defun markdown-list-item-at-point-p ()
2640 "Return t if there is a list item at the point and nil otherwise."
2641 (save-match-data (markdown-cur-list-item-bounds)))
2643 (defun markdown-prev-list-item-bounds ()
2644 "Return bounds of previous item in the same list of any level.
2645 The return value has the same form as that of
2646 `markdown-cur-list-item-bounds'."
2647 (save-excursion
2648 (let ((cur-bounds (markdown-cur-list-item-bounds))
2649 (beginning-of-list (save-excursion (markdown-beginning-of-list)))
2650 stop)
2651 (when cur-bounds
2652 (goto-char (nth 0 cur-bounds))
2653 (while (and (not stop) (not (bobp))
2654 (re-search-backward markdown-regex-list
2655 beginning-of-list t))
2656 (unless (or (looking-at markdown-regex-hr)
2657 (markdown-code-block-at-point-p))
2658 (setq stop (point))))
2659 (markdown-cur-list-item-bounds)))))
2661 (defun markdown-next-list-item-bounds ()
2662 "Return bounds of next item in the same list of any level.
2663 The return value has the same form as that of
2664 `markdown-cur-list-item-bounds'."
2665 (save-excursion
2666 (let ((cur-bounds (markdown-cur-list-item-bounds))
2667 (end-of-list (save-excursion (markdown-end-of-list)))
2668 stop)
2669 (when cur-bounds
2670 (goto-char (nth 0 cur-bounds))
2671 (end-of-line)
2672 (while (and (not stop) (not (eobp))
2673 (re-search-forward markdown-regex-list
2674 end-of-list t))
2675 (unless (or (looking-at markdown-regex-hr)
2676 (markdown-code-block-at-point-p))
2677 (setq stop (point))))
2678 (when stop
2679 (markdown-cur-list-item-bounds))))))
2681 (defun markdown-beginning-of-list ()
2682 "Move point to beginning of list at point, if any."
2683 (interactive)
2684 (let ((orig-point (point))
2685 (list-begin (save-excursion
2686 (markdown-search-backward-baseline)
2687 ;; Stop at next list item, regardless of the indentation.
2688 (markdown-next-list-item (point-max))
2689 (when (looking-at markdown-regex-list)
2690 (point)))))
2691 (when (and list-begin (<= list-begin orig-point))
2692 (goto-char list-begin))))
2694 (defun markdown-end-of-list ()
2695 "Move point to end of list at point, if any."
2696 (interactive)
2697 (let ((start (point))
2698 (end (save-excursion
2699 (when (markdown-beginning-of-list)
2700 ;; Items can't have nonlist-indent <= 1, so this
2701 ;; moves past all list items.
2702 (markdown-next-list-item 1)
2703 (skip-syntax-backward "-")
2704 (unless (eobp) (forward-char 1))
2705 (point)))))
2706 (when (and end (>= end start))
2707 (goto-char end))))
2709 (defun markdown-up-list ()
2710 "Move point to beginning of parent list item."
2711 (interactive)
2712 (let ((cur-bounds (markdown-cur-list-item-bounds)))
2713 (when cur-bounds
2714 (markdown-prev-list-item (1- (nth 3 cur-bounds)))
2715 (let ((up-bounds (markdown-cur-list-item-bounds)))
2716 (when (and up-bounds (< (nth 3 up-bounds) (nth 3 cur-bounds)))
2717 (point))))))
2719 (defun markdown-bounds-of-thing-at-point (thing)
2720 "Call `bounds-of-thing-at-point' for THING with slight modifications.
2721 Does not include trailing newlines when THING is 'line. Handles the
2722 end of buffer case by setting both endpoints equal to the value of
2723 `point-max', since an empty region will trigger empty markup insertion.
2724 Return bounds of form (beg . end) if THING is found, or nil otherwise."
2725 (let* ((bounds (bounds-of-thing-at-point thing))
2726 (a (car bounds))
2727 (b (cdr bounds)))
2728 (when bounds
2729 (when (eq thing 'line)
2730 (cond ((and (eobp) (markdown-cur-line-blank-p))
2731 (setq a b))
2732 ((char-equal (char-before b) ?\^J)
2733 (setq b (1- b)))))
2734 (cons a b))))
2736 (defun markdown-reference-definition (reference)
2737 "Find out whether Markdown REFERENCE is defined.
2738 REFERENCE should not include the square brackets.
2739 When REFERENCE is defined, return a list of the form (text start end)
2740 containing the definition text itself followed by the start and end
2741 locations of the text. Otherwise, return nil.
2742 Leave match data for `markdown-regex-reference-definition'
2743 intact additional processing."
2744 (let ((reference (downcase reference)))
2745 (save-excursion
2746 (goto-char (point-min))
2747 (catch 'found
2748 (while (re-search-forward markdown-regex-reference-definition nil t)
2749 (when (string= reference (downcase (match-string-no-properties 2)))
2750 (throw 'found
2751 (list (match-string-no-properties 5)
2752 (match-beginning 5) (match-end 5)))))))))
2754 (defun markdown-get-defined-references ()
2755 "Return a list of all defined reference labels (not including square brackets)."
2756 (save-excursion
2757 (goto-char (point-min))
2758 (let (refs)
2759 (while (re-search-forward markdown-regex-reference-definition nil t)
2760 (let ((target (match-string-no-properties 2)))
2761 (cl-pushnew target refs :test #'equal)))
2762 (reverse refs))))
2764 (defun markdown-get-used-uris ()
2765 "Return a list of all used URIs in the buffer."
2766 (save-excursion
2767 (goto-char (point-min))
2768 (let (uris)
2769 (while (re-search-forward
2770 (concat "\\(?:" markdown-regex-link-inline
2771 "\\|" markdown-regex-angle-uri
2772 "\\|" markdown-regex-uri
2773 "\\|" markdown-regex-email
2774 "\\)")
2775 nil t)
2776 (unless (or (markdown-inline-code-at-point-p)
2777 (markdown-code-block-at-point-p))
2778 (cl-pushnew (or (match-string-no-properties 6)
2779 (match-string-no-properties 10)
2780 (match-string-no-properties 12)
2781 (match-string-no-properties 13))
2782 uris :test #'equal)))
2783 (reverse uris))))
2785 (defun markdown-inline-code-at-pos (pos)
2786 "Return non-nil if there is an inline code fragment at POS.
2787 Return nil otherwise. Set match data according to
2788 `markdown-match-code' upon success.
2789 This function searches the block for a code fragment that
2790 contains the point using `markdown-match-code'. We do this
2791 because `thing-at-point-looking-at' does not work reliably with
2792 `markdown-regex-code'.
2794 The match data is set as follows:
2795 Group 1 matches the opening backquotes.
2796 Group 2 matches the code fragment itself, without backquotes.
2797 Group 3 matches the closing backquotes."
2798 (save-excursion
2799 (goto-char pos)
2800 (let ((old-point (point))
2801 (end-of-block (progn (markdown-end-of-text-block) (point)))
2802 found)
2803 (markdown-beginning-of-text-block)
2804 (while (and (markdown-match-code end-of-block)
2805 (setq found t)
2806 (< (match-end 0) old-point)))
2807 (and found ; matched something
2808 (<= (match-beginning 0) old-point) ; match contains old-point
2809 (>= (match-end 0) old-point)))))
2811 (defun markdown-inline-code-at-pos-p (pos)
2812 "Return non-nil if there is an inline code fragment at POS.
2813 Like `markdown-inline-code-at-pos`, but preserves match data."
2814 (save-match-data (markdown-inline-code-at-pos pos)))
2816 (defun markdown-inline-code-at-point ()
2817 "Return non-nil if the point is at an inline code fragment.
2818 See `markdown-inline-code-at-pos' for details."
2819 (markdown-inline-code-at-pos (point)))
2821 (defun markdown-inline-code-at-point-p ()
2822 "Return non-nil if there is inline code at the point.
2823 This is a predicate function counterpart to
2824 `markdown-inline-code-at-point' which does not modify the match
2825 data. See `markdown-code-block-at-point-p' for code blocks."
2826 (save-match-data (markdown-inline-code-at-pos (point))))
2828 (make-obsolete 'markdown-code-at-point-p 'markdown-inline-code-at-point-p "v2.2")
2830 (defun markdown--code-block-at-pos-no-syntax (pos)
2831 "Return match data list if there may be a code block at POS.
2832 This includes pre blocks, tilde-fenced code blocks, and GFM
2833 quoted code blocks. Return nil otherwise. This function does not
2834 use text properties, which have not yet been set during the
2835 syntax propertization phase."
2836 (setq pos (save-excursion (goto-char pos) (point-at-bol)))
2837 (let (match)
2838 (cond
2839 ;; Indented code blocks
2840 ((looking-at markdown-regex-pre)
2841 (let ((start (save-excursion
2842 (markdown-search-backward-baseline) (point)))
2843 (end (save-excursion
2844 (while (and (or (looking-at-p markdown-regex-pre)
2845 (markdown-cur-line-blank-p))
2846 (not (eobp)))
2847 (forward-line))
2848 (point))))
2849 (list start end start start start end end end)))
2850 ;; Fenced code blocks
2851 ((setq match (markdown-get-enclosing-fenced-block-construct pos))
2852 match))))
2854 (defun markdown-code-block-at-pos (pos)
2855 "Return match data list if there is a code block at POS.
2856 This includes pre blocks, tilde-fenced code blocks, and GFM
2857 quoted code blocks. Return nil otherwise. This function uses
2858 cached text properties at the beginning of the line position for
2859 performance reasons, but therefore it must run after the syntax
2860 propertization phase."
2861 (setq pos (save-excursion (goto-char pos) (point-at-bol)))
2862 (or (get-text-property pos 'markdown-pre)
2863 ;;(markdown-get-enclosing-fenced-block-construct pos)
2864 (when (markdown-range-properties-exist
2865 pos pos '(markdown-gfm-block-begin
2866 markdown-gfm-code
2867 markdown-gfm-block-end
2868 markdown-tilde-fence-begin
2869 markdown-fenced-code
2870 markdown-tilde-fence-end
2871 markdown-yaml-metadata-begin
2872 markdown-yaml-metadata-section
2873 markdown-yaml-metadata-end))
2874 (markdown-get-enclosing-fenced-block-construct pos))
2875 ;; polymode removes text properties set by markdown-mode, so
2876 ;; check if `poly-markdown-mode' is active and whether the
2877 ;; `chunkmode' property is non-nil at POS.
2878 (and (bound-and-true-p poly-markdown-mode)
2879 (get-text-property pos 'chunkmode))))
2881 ;; Function was renamed to emphasize that it does not modify match-data.
2882 (defalias 'markdown-code-block-at-point 'markdown-code-block-at-point-p)
2884 (defun markdown-code-block-at-point-p ()
2885 "Return non-nil if there is a code block at the point.
2886 This includes pre blocks, tilde-fenced code blocks, and GFM
2887 quoted code blocks. This function does not modify the match
2888 data. See `markdown-inline-code-at-point-p' for inline code."
2889 (save-match-data (markdown-code-block-at-pos (point))))
2891 (defun markdown-heading-at-point ()
2892 "Return non-nil if there is a heading at the point.
2893 Set match data for `markdown-regex-header'."
2894 (let ((match-data (get-text-property (point) 'markdown-heading)))
2895 (when match-data
2896 (set-match-data match-data)
2897 t)))
2899 (defun markdown-pipe-at-bol-p ()
2900 "Return non-nil if the line begins with a pipe symbol.
2901 This may be useful for tables and Pandoc's line_blocks extension."
2902 (char-equal (char-after (point-at-bol)) ?|))
2905 ;;; Markdown Font Lock Matching Functions =====================================
2907 (defun markdown-range-property-any (begin end prop prop-values)
2908 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
2909 Also returns t if PROP is a list containing one of the PROP-VALUES.
2910 Return nil otherwise."
2911 (let (props)
2912 (catch 'found
2913 (dolist (loc (number-sequence begin end))
2914 (when (setq props (get-text-property loc prop))
2915 (cond ((listp props)
2916 ;; props is a list, check for membership
2917 (dolist (val prop-values)
2918 (when (memq val props) (throw 'found loc))))
2920 ;; props is a scalar, check for equality
2921 (dolist (val prop-values)
2922 (when (eq val props) (throw 'found loc))))))))))
2924 (defun markdown-range-properties-exist (begin end props)
2925 (cl-loop
2926 for loc in (number-sequence begin end)
2927 with result = nil
2928 while (not
2929 (setq result
2930 (cl-some (lambda (prop) (get-text-property loc prop)) props)))
2931 finally return result))
2933 (defun markdown-match-inline-generic (regex last &optional faceless)
2934 "Match inline REGEX from the point to LAST.
2935 When FACELESS is non-nil, do not return matches where faces have been applied."
2936 (when (re-search-forward regex last t)
2937 (let ((bounds (markdown-code-block-at-pos (match-beginning 1)))
2938 (face (and faceless (text-property-not-all
2939 (match-beginning 0) (match-end 0) 'face nil))))
2940 (cond
2941 ;; In code block: move past it and recursively search again
2942 (bounds
2943 (when (< (goto-char (cl-second bounds)) last)
2944 (markdown-match-inline-generic regex last faceless)))
2945 ;; When faces are found in the match range, skip over the match and
2946 ;; recursively search again.
2947 (face
2948 (when (< (goto-char (match-end 0)) last)
2949 (markdown-match-inline-generic regex last faceless)))
2950 ;; Keep match data and return t when in bounds.
2952 (<= (match-end 0) last))))))
2954 (defun markdown-match-code (last)
2955 "Match inline code fragments from point to LAST."
2956 (unless (bobp)
2957 (backward-char 1))
2958 (when (markdown-search-until-condition
2959 (lambda ()
2960 (and
2961 ;; Advance point in case of failure, but without exceeding last.
2962 (goto-char (min (1+ (match-beginning 1)) last))
2963 (not (markdown-in-comment-p (match-beginning 1)))
2964 (not (markdown-in-comment-p (match-end 1)))
2965 (not (markdown-code-block-at-pos (match-beginning 1)))))
2966 markdown-regex-code last t)
2967 (set-match-data (list (match-beginning 1) (match-end 1)
2968 (match-beginning 2) (match-end 2)
2969 (match-beginning 3) (match-end 3)
2970 (match-beginning 4) (match-end 4)))
2971 (goto-char (min (1+ (match-end 0)) last (point-max)))
2974 (defun markdown-match-bold (last)
2975 "Match inline bold from the point to LAST."
2976 (when (markdown-match-inline-generic markdown-regex-bold last)
2977 (let ((begin (match-beginning 2))
2978 (end (match-end 2)))
2979 (if (or (markdown-inline-code-at-pos-p begin)
2980 (markdown-inline-code-at-pos-p end)
2981 (markdown-in-comment-p)
2982 (markdown-range-property-any
2983 begin begin 'face '(markdown-url-face
2984 markdown-plain-url-face))
2985 (markdown-range-property-any
2986 begin end 'face '(markdown-hr-face
2987 markdown-math-face)))
2988 (progn (goto-char (min (1+ begin) last))
2989 (when (< (point) last)
2990 (markdown-match-italic last)))
2991 (set-match-data (list (match-beginning 2) (match-end 2)
2992 (match-beginning 3) (match-end 3)
2993 (match-beginning 4) (match-end 4)
2994 (match-beginning 5) (match-end 5)))
2995 t))))
2997 (defun markdown-match-italic (last)
2998 "Match inline italics from the point to LAST."
2999 (let ((regex (if (memq major-mode '(gfm-mode gfm-view-mode))
3000 markdown-regex-gfm-italic markdown-regex-italic)))
3001 (when (markdown-match-inline-generic regex last)
3002 (let ((begin (match-beginning 1))
3003 (end (match-end 1)))
3004 (if (or (markdown-inline-code-at-pos-p begin)
3005 (markdown-inline-code-at-pos-p end)
3006 (markdown-in-comment-p)
3007 (markdown-range-property-any
3008 begin begin 'face '(markdown-url-face
3009 markdown-plain-url-face))
3010 (markdown-range-property-any
3011 begin end 'face '(markdown-bold-face
3012 markdown-list-face
3013 markdown-hr-face
3014 markdown-math-face)))
3015 (progn (goto-char (min (1+ begin) last))
3016 (when (< (point) last)
3017 (markdown-match-italic last)))
3018 (set-match-data (list (match-beginning 1) (match-end 1)
3019 (match-beginning 2) (match-end 2)
3020 (match-beginning 3) (match-end 3)
3021 (match-beginning 4) (match-end 4)))
3022 t)))))
3024 (defun markdown-match-math-generic (regex last)
3025 "Match REGEX from point to LAST.
3026 REGEX is either `markdown-regex-math-inline-single' for matching
3027 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
3028 (when (and markdown-enable-math (markdown-match-inline-generic regex last))
3029 (let ((begin (match-beginning 1)) (end (match-end 1)))
3030 (prog1
3031 (if (or (markdown-range-property-any
3032 begin end 'face
3033 '(markdown-inline-code-face markdown-bold-face))
3034 (markdown-range-properties-exist
3035 begin end
3036 (markdown-get-fenced-block-middle-properties)))
3037 (markdown-match-math-generic regex last)
3039 (goto-char (1+ (match-end 0)))))))
3041 (defun markdown-match-list-items (last)
3042 "Match list items from point to LAST."
3043 (let* ((first (point))
3044 (pos first)
3045 (prop 'markdown-list-item)
3046 (bounds (car (get-text-property pos prop))))
3047 (while
3048 (and (or (null (setq bounds (car (get-text-property pos prop))))
3049 (< (cl-first bounds) pos))
3050 (< (point) last)
3051 (setq pos (next-single-char-property-change pos prop nil last))
3052 (goto-char pos)))
3053 (when bounds
3054 (set-match-data (cl-seventh bounds))
3055 ;; Step at least one character beyond point. Otherwise
3056 ;; `font-lock-fontify-keywords-region' infloops.
3057 (goto-char (min (1+ (max (point-at-eol) first))
3058 (point-max)))
3059 t)))
3061 (defun markdown-match-math-single (last)
3062 "Match single quoted $..$ math from point to LAST."
3063 (markdown-match-math-generic markdown-regex-math-inline-single last))
3065 (defun markdown-match-math-double (last)
3066 "Match double quoted $$..$$ math from point to LAST."
3067 (markdown-match-math-generic markdown-regex-math-inline-double last))
3069 (defun markdown-match-math-display (last)
3070 "Match bracketed display math \[..\] and \\[..\\] from point to LAST."
3071 (markdown-match-math-generic markdown-regex-math-display last))
3073 (defun markdown-match-propertized-text (property last)
3074 "Match text with PROPERTY from point to LAST.
3075 Restore match data previously stored in PROPERTY."
3076 (let ((saved (get-text-property (point) property))
3077 pos)
3078 (unless saved
3079 (setq pos (next-single-char-property-change (point) property nil last))
3080 (setq saved (get-text-property pos property)))
3081 (when saved
3082 (set-match-data saved)
3083 ;; Step at least one character beyond point. Otherwise
3084 ;; `font-lock-fontify-keywords-region' infloops.
3085 (goto-char (min (1+ (max (match-end 0) (point)))
3086 (point-max)))
3087 saved)))
3089 (defun markdown-match-pre-blocks (last)
3090 "Match preformatted blocks from point to LAST.
3091 Use data stored in 'markdown-pre text property during syntax
3092 analysis."
3093 (markdown-match-propertized-text 'markdown-pre last))
3095 (defun markdown-match-gfm-code-blocks (last)
3096 "Match GFM quoted code blocks from point to LAST.
3097 Use data stored in 'markdown-gfm-code text property during syntax
3098 analysis."
3099 (markdown-match-propertized-text 'markdown-gfm-code last))
3101 (defun markdown-match-gfm-open-code-blocks (last)
3102 (markdown-match-propertized-text 'markdown-gfm-block-begin last))
3104 (defun markdown-match-gfm-close-code-blocks (last)
3105 (markdown-match-propertized-text 'markdown-gfm-block-end last))
3107 (defun markdown-match-fenced-code-blocks (last)
3108 "Match fenced code blocks from the point to LAST."
3109 (markdown-match-propertized-text 'markdown-fenced-code last))
3111 (defun markdown-match-fenced-start-code-block (last)
3112 (markdown-match-propertized-text 'markdown-tilde-fence-begin last))
3114 (defun markdown-match-fenced-end-code-block (last)
3115 (markdown-match-propertized-text 'markdown-tilde-fence-end last))
3117 (defun markdown-match-blockquotes (last)
3118 "Match blockquotes from point to LAST.
3119 Use data stored in 'markdown-blockquote text property during syntax
3120 analysis."
3121 (markdown-match-propertized-text 'markdown-blockquote last))
3123 (defun markdown-match-hr (last)
3124 "Match horizontal rules comments from the point to LAST."
3125 (markdown-match-propertized-text 'markdown-hr last))
3127 (defun markdown-match-comments (last)
3128 "Match HTML comments from the point to LAST."
3129 (when (and (skip-syntax-forward "^<" last))
3130 (let ((beg (point)))
3131 (when (and (skip-syntax-forward "^>" last) (< (point) last))
3132 (forward-char)
3133 (set-match-data (list beg (point)))
3134 t))))
3136 (defun markdown-match-generic-links (last ref)
3137 "Match inline links from point to LAST.
3138 When REF is non-nil, match reference links instead of standard
3139 links with URLs."
3140 ;; Search for the next potential link (not in a code block).
3141 (while (and (progn
3142 ;; Clear match data to test for a match after functions returns.
3143 (set-match-data nil)
3144 ;; Preliminary regular expression search so we can return
3145 ;; quickly upon failure. This doesn't handle malformed links
3146 ;; or nested square brackets well, so if it passes we back up
3147 ;; continue with a more precise search.
3148 (re-search-forward
3149 (if ref
3150 markdown-regex-link-reference
3151 markdown-regex-link-inline)
3152 last 'limit))
3153 ;; Keep searching if this is in a code block, inline
3154 ;; code, or a comment, or if it is include syntax.
3155 (or (markdown-code-block-at-point-p)
3156 (markdown-inline-code-at-pos-p (match-beginning 0))
3157 (markdown-inline-code-at-pos-p (match-end 0))
3158 (markdown-in-comment-p)
3159 (and (char-equal (char-after (point-at-bol)) ?<)
3160 (char-equal (char-after (1+ (point-at-bol))) ?<)))
3161 (< (point) last)))
3162 ;; Match opening exclamation point (optional) and left bracket.
3163 (when (match-beginning 2)
3164 (let* ((bang (match-beginning 1))
3165 (first-begin (match-beginning 2))
3166 ;; Find end of block to prevent matching across blocks.
3167 (end-of-block (save-excursion
3168 (progn
3169 (goto-char (match-beginning 2))
3170 (markdown-end-of-text-block)
3171 (point))))
3172 ;; Move over balanced expressions to closing right bracket.
3173 ;; Catch unbalanced expression errors and return nil.
3174 (first-end (condition-case nil
3175 (and (goto-char first-begin)
3176 (scan-sexps (point) 1))
3177 (error nil)))
3178 ;; Continue with point at CONT-POINT upon failure.
3179 (cont-point (min (1+ first-begin) last))
3180 second-begin second-end url-begin url-end
3181 title-begin title-end)
3182 ;; When bracket found, in range, and followed by a left paren/bracket...
3183 (when (and first-end (< first-end end-of-block) (goto-char first-end)
3184 (char-equal (char-after (point)) (if ref ?\[ ?\()))
3185 ;; Scan across balanced expressions for closing parenthesis/bracket.
3186 (setq second-begin (point)
3187 second-end (condition-case nil
3188 (scan-sexps (point) 1)
3189 (error nil)))
3190 ;; Check that closing parenthesis/bracket is in range.
3191 (if (and second-end (<= second-end end-of-block) (<= second-end last))
3192 (progn
3193 ;; Search for (optional) title inside closing parenthesis
3194 (when (and (not ref) (search-forward "\"" second-end t))
3195 (setq title-begin (1- (point))
3196 title-end (and (goto-char second-end)
3197 (search-backward "\"" (1+ title-begin) t))
3198 title-end (and title-end (1+ title-end))))
3199 ;; Store URL/reference range
3200 (setq url-begin (1+ second-begin)
3201 url-end (1- (or title-begin second-end)))
3202 ;; Set match data, move point beyond link, and return
3203 (set-match-data
3204 (list (or bang first-begin) second-end ; 0 - all
3205 bang (and bang (1+ bang)) ; 1 - bang
3206 first-begin (1+ first-begin) ; 2 - markup
3207 (1+ first-begin) (1- first-end) ; 3 - link text
3208 (1- first-end) first-end ; 4 - markup
3209 second-begin (1+ second-begin) ; 5 - markup
3210 url-begin url-end ; 6 - url/reference
3211 title-begin title-end ; 7 - title
3212 (1- second-end) second-end)) ; 8 - markup
3213 ;; Nullify cont-point and leave point at end and
3214 (setq cont-point nil)
3215 (goto-char second-end))
3216 ;; If no closing parenthesis in range, update continuation point
3217 (setq cont-point (min end-of-block second-begin))))
3218 (cond
3219 ;; On failure, continue searching at cont-point
3220 ((and cont-point (< cont-point last))
3221 (goto-char cont-point)
3222 (markdown-match-generic-links last ref))
3223 ;; No more text, return nil
3224 ((and cont-point (= cont-point last))
3225 nil)
3226 ;; Return t if a match occurred
3227 (t t)))))
3229 (defun markdown-match-inline-links (last)
3230 "Match standard inline links from point to LAST."
3231 (markdown-match-generic-links last nil))
3233 (defun markdown-match-reference-links (last)
3234 "Match inline reference links from point to LAST."
3235 (markdown-match-generic-links last t))
3237 (defun markdown-match-angle-uris (last)
3238 "Match angle bracket URIs from point to LAST."
3239 (when (markdown-match-inline-generic markdown-regex-angle-uri last)
3240 (goto-char (1+ (match-end 0)))))
3242 (defun markdown-match-plain-uris (last)
3243 "Match plain URIs from point to LAST."
3244 (when (markdown-match-inline-generic markdown-regex-uri last t)
3245 (goto-char (1+ (match-end 0)))))
3247 (defvar markdown-conditional-search-function #'re-search-forward
3248 "Conditional search function used in `markdown-search-until-condition'.
3249 Made into a variable to allow for dynamic let-binding.")
3251 (defun markdown-search-until-condition (condition &rest args)
3252 (let (ret)
3253 (while (and (not ret) (apply markdown-conditional-search-function args))
3254 (setq ret (funcall condition)))
3255 ret))
3257 (defun markdown-match-generic-metadata (regexp last)
3258 "Match metadata declarations specified by REGEXP from point to LAST.
3259 These declarations must appear inside a metadata block that begins at
3260 the beginning of the buffer and ends with a blank line (or the end of
3261 the buffer)."
3262 (let* ((first (point))
3263 (end-re "\n[ \t]*\n\\|\n\\'\\|\\'")
3264 (block-begin (goto-char 1))
3265 (block-end (re-search-forward end-re nil t)))
3266 (if (and block-end (> first block-end))
3267 ;; Don't match declarations if there is no metadata block or if
3268 ;; the point is beyond the block. Move point to point-max to
3269 ;; prevent additional searches and return return nil since nothing
3270 ;; was found.
3271 (progn (goto-char (point-max)) nil)
3272 ;; If a block was found that begins before LAST and ends after
3273 ;; point, search for declarations inside it. If the starting is
3274 ;; before the beginning of the block, start there. Otherwise,
3275 ;; move back to FIRST.
3276 (goto-char (if (< first block-begin) block-begin first))
3277 (if (re-search-forward regexp (min last block-end) t)
3278 ;; If a metadata declaration is found, set match-data and return t.
3279 (let ((key-beginning (match-beginning 1))
3280 (key-end (match-end 1))
3281 (markup-begin (match-beginning 2))
3282 (markup-end (match-end 2))
3283 (value-beginning (match-beginning 3)))
3284 (set-match-data (list key-beginning (point) ; complete metadata
3285 key-beginning key-end ; key
3286 markup-begin markup-end ; markup
3287 value-beginning (point))) ; value
3289 ;; Otherwise, move the point to last and return nil
3290 (goto-char last)
3291 nil))))
3293 (defun markdown-match-declarative-metadata (last)
3294 "Match declarative metadata from the point to LAST."
3295 (markdown-match-generic-metadata markdown-regex-declarative-metadata last))
3297 (defun markdown-match-pandoc-metadata (last)
3298 "Match Pandoc metadata from the point to LAST."
3299 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
3301 (defun markdown-match-yaml-metadata-begin (last)
3302 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last))
3304 (defun markdown-match-yaml-metadata-end (last)
3305 (markdown-match-propertized-text 'markdown-yaml-metadata-end last))
3307 (defun markdown-match-yaml-metadata-key (last)
3308 (markdown-match-propertized-text 'markdown-metadata-key last))
3310 (defun markdown-match-wiki-link (last)
3311 "Match wiki links from point to LAST."
3312 (when (and markdown-enable-wiki-links
3313 (not markdown-wiki-link-fontify-missing)
3314 (markdown-match-inline-generic markdown-regex-wiki-link last))
3315 (let ((begin (match-beginning 1)) (end (match-end 1)))
3316 (if (or (markdown-in-comment-p begin)
3317 (markdown-in-comment-p end)
3318 (markdown-inline-code-at-pos-p begin)
3319 (markdown-inline-code-at-pos-p end)
3320 (markdown-code-block-at-pos begin))
3321 (progn (goto-char (min (1+ begin) last))
3322 (when (< (point) last)
3323 (markdown-match-wiki-link last)))
3324 (set-match-data (list begin end))
3325 t))))
3327 (defun markdown-match-inline-attributes (last)
3328 "Match inline attributes from point to LAST."
3329 (when (markdown-match-inline-generic markdown-regex-inline-attributes last)
3330 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
3331 (markdown-inline-code-at-pos-p (match-end 0))
3332 (markdown-in-comment-p))
3333 t)))
3335 (defun markdown-match-leanpub-sections (last)
3336 "Match Leanpub section markers from point to LAST."
3337 (when (markdown-match-inline-generic markdown-regex-leanpub-sections last)
3338 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
3339 (markdown-inline-code-at-pos-p (match-end 0))
3340 (markdown-in-comment-p))
3341 t)))
3343 (defun markdown-match-includes (last)
3344 "Match include statements from point to LAST.
3345 Sets match data for the following seven groups:
3346 Group 1: opening two angle brackets
3347 Group 2: opening title delimiter (optional)
3348 Group 3: title text (optional)
3349 Group 4: closing title delimiter (optional)
3350 Group 5: opening filename delimiter
3351 Group 6: filename
3352 Group 7: closing filename delimiter"
3353 (when (markdown-match-inline-generic markdown-regex-include last)
3354 (let ((valid (not (or (markdown-in-comment-p (match-beginning 0))
3355 (markdown-in-comment-p (match-end 0))
3356 (markdown-code-block-at-pos (match-beginning 0))))))
3357 (cond
3358 ;; Parentheses and maybe square brackets, but no curly braces:
3359 ;; match optional title in square brackets and file in parentheses.
3360 ((and valid (match-beginning 5)
3361 (not (match-beginning 8)))
3362 (set-match-data (list (match-beginning 1) (match-end 7)
3363 (match-beginning 1) (match-end 1)
3364 (match-beginning 2) (match-end 2)
3365 (match-beginning 3) (match-end 3)
3366 (match-beginning 4) (match-end 4)
3367 (match-beginning 5) (match-end 5)
3368 (match-beginning 6) (match-end 6)
3369 (match-beginning 7) (match-end 7))))
3370 ;; Only square brackets present: match file in square brackets.
3371 ((and valid (match-beginning 2)
3372 (not (match-beginning 5))
3373 (not (match-beginning 7)))
3374 (set-match-data (list (match-beginning 1) (match-end 4)
3375 (match-beginning 1) (match-end 1)
3376 nil nil
3377 nil nil
3378 nil nil
3379 (match-beginning 2) (match-end 2)
3380 (match-beginning 3) (match-end 3)
3381 (match-beginning 4) (match-end 4))))
3382 ;; Only curly braces present: match file in curly braces.
3383 ((and valid (match-beginning 8)
3384 (not (match-beginning 2))
3385 (not (match-beginning 5)))
3386 (set-match-data (list (match-beginning 1) (match-end 10)
3387 (match-beginning 1) (match-end 1)
3388 nil nil
3389 nil nil
3390 nil nil
3391 (match-beginning 8) (match-end 8)
3392 (match-beginning 9) (match-end 9)
3393 (match-beginning 10) (match-end 10))))
3395 ;; Not a valid match, move to next line and search again.
3396 (forward-line)
3397 (when (< (point) last)
3398 (setq valid (markdown-match-includes last)))))
3399 valid)))
3401 (defun markdown-match-html-tag (last)
3402 "Match HTML tags from point to LAST."
3403 (when (and markdown-enable-html
3404 (markdown-match-inline-generic markdown-regex-html-tag last t))
3405 (set-match-data (list (match-beginning 0) (match-end 0)
3406 (match-beginning 1) (match-end 1)
3407 (match-beginning 2) (match-end 2)
3408 (match-beginning 9) (match-end 9)))
3412 ;;; Markdown Font Fontification Functions =====================================
3414 (defun markdown--first-displayable (seq)
3415 "Return the first displayable character or string in SEQ.
3416 SEQ may be an atom or a sequence."
3417 (let ((seq (if (listp seq) seq (list seq))))
3418 (cond ((stringp (car seq))
3419 (cl-find-if
3420 (lambda (str)
3421 (and (mapcar #'char-displayable-p (string-to-list str))))
3422 seq))
3423 ((characterp (car seq))
3424 (cl-find-if #'char-displayable-p seq)))))
3426 (defun markdown--marginalize-string (level)
3427 "Generate atx markup string of given LEVEL for left margin."
3428 (let ((margin-left-space-count
3429 (- markdown-marginalize-headers-margin-width level)))
3430 (concat (make-string margin-left-space-count ? )
3431 (make-string level ?#))))
3433 (defun markdown-marginalize-update-current ()
3434 "Update the window configuration to create a left margin."
3435 ;; Emacs 25 or later is needed for window-font-width and default-font-width.
3436 (if (and (fboundp 'window-font-width) (fboundp 'default-font-width))
3437 (let* ((header-delimiter-font-width
3438 (window-font-width nil 'markdown-header-delimiter-face))
3439 (margin-pixel-width (* markdown-marginalize-headers-margin-width
3440 header-delimiter-font-width))
3441 (margin-char-width (/ margin-pixel-width (default-font-width))))
3442 (set-window-margins nil margin-char-width))
3443 ;; As a fallback, simply set margin based on character count.
3444 (set-window-margins nil markdown-marginalize-headers-margin-width)))
3446 (defun markdown-fontify-headings (last)
3447 "Add text properties to headings from point to LAST."
3448 (when (markdown-match-propertized-text 'markdown-heading last)
3449 (let* ((level (markdown-outline-level))
3450 (heading-face
3451 (intern (format "markdown-header-face-%d" level)))
3452 (heading-props `(face ,heading-face))
3453 (left-markup-props
3454 `(face markdown-header-delimiter-face
3455 ,@(cond
3456 (markdown-hide-markup
3457 `(display ""))
3458 (markdown-marginalize-headers
3459 `(display ((margin left-margin)
3460 ,(markdown--marginalize-string level)))))))
3461 (right-markup-props
3462 `(face markdown-header-delimiter-face
3463 ,@(when markdown-hide-markup `(display ""))))
3464 (rule-props `(face markdown-header-rule-face
3465 ,@(when markdown-hide-markup `(display "")))))
3466 (if (match-end 1)
3467 ;; Setext heading
3468 (progn (add-text-properties
3469 (match-beginning 1) (match-end 1) heading-props)
3470 (if (= level 1)
3471 (add-text-properties
3472 (match-beginning 2) (match-end 2) rule-props)
3473 (add-text-properties
3474 (match-beginning 3) (match-end 3) rule-props)))
3475 ;; atx heading
3476 (add-text-properties
3477 (match-beginning 4) (match-end 4) left-markup-props)
3478 (add-text-properties
3479 (match-beginning 5) (match-end 5) heading-props)
3480 (when (match-end 6)
3481 (add-text-properties
3482 (match-beginning 6) (match-end 6) right-markup-props))))
3485 (defun markdown-fontify-tables (last)
3486 (when (and (re-search-forward "|" last t)
3487 (markdown-table-at-point-p))
3488 (font-lock-append-text-property
3489 (line-beginning-position) (min (1+ (line-end-position)) (point-max))
3490 'face 'markdown-table-face)
3491 (forward-line 1)
3494 (defun markdown-fontify-blockquotes (last)
3495 "Apply font-lock properties to blockquotes from point to LAST."
3496 (when (markdown-match-blockquotes last)
3497 (let ((display-string
3498 (markdown--first-displayable markdown-blockquote-display-char)))
3499 (add-text-properties
3500 (match-beginning 1) (match-end 1)
3501 (if markdown-hide-markup
3502 `(face markdown-blockquote-face display ,display-string)
3503 `(face markdown-markup-face)))
3504 (font-lock-append-text-property
3505 (match-beginning 0) (match-end 0) 'face 'markdown-blockquote-face)
3506 t)))
3508 (defun markdown-fontify-list-items (last)
3509 "Apply font-lock properties to list markers from point to LAST."
3510 (when (markdown-match-list-items last)
3511 (let* ((indent (length (match-string-no-properties 1)))
3512 (level (/ indent 4)) ;; level = 0, 1, 2, ...
3513 (bullet (nth (mod level (length markdown-list-item-bullets))
3514 markdown-list-item-bullets)))
3515 (add-text-properties
3516 (match-beginning 2) (match-end 2) '(face markdown-list-face))
3517 (when markdown-hide-markup
3518 (cond
3519 ;; Unordered lists
3520 ((string-match-p "[\\*\\+-]" (match-string 2))
3521 (add-text-properties
3522 (match-beginning 2) (match-end 2) `(display ,bullet)))
3523 ;; Definition lists
3524 ((string-equal ":" (match-string 2))
3525 (let ((display-string
3526 (char-to-string (markdown--first-displayable
3527 markdown-definition-display-char))))
3528 (add-text-properties (match-beginning 2) (match-end 2)
3529 `(display ,display-string)))))))
3532 (defun markdown-fontify-hrs (last)
3533 "Add text properties to horizontal rules from point to LAST."
3534 (when (markdown-match-hr last)
3535 (let ((hr-char (markdown--first-displayable markdown-hr-display-char)))
3536 (add-text-properties
3537 (match-beginning 0) (match-end 0)
3538 `(face markdown-hr-face
3539 font-lock-multiline t
3540 ,@(when (and markdown-hide-markup hr-char)
3541 `(display ,(make-string
3542 (window-body-width) hr-char)))))
3543 t)))
3545 (defun markdown-fontify-sub-superscripts (last)
3546 "Apply text properties to sub- and superscripts from point to LAST."
3547 (when (markdown-search-until-condition
3548 (lambda () (and (not (markdown-code-block-at-point-p))
3549 (not (markdown-inline-code-at-point-p))
3550 (not (markdown-in-comment-p))))
3551 markdown-regex-sub-superscript last t)
3552 (let* ((subscript-p (string= (match-string 2) "~"))
3553 (props
3554 (if subscript-p
3555 (car markdown-sub-superscript-display)
3556 (cdr markdown-sub-superscript-display)))
3557 (mp (list 'face 'markdown-markup-face
3558 'invisible 'markdown-markup)))
3559 (when markdown-hide-markup
3560 (put-text-property (match-beginning 3) (match-end 3)
3561 'display props))
3562 (add-text-properties (match-beginning 2) (match-end 2) mp)
3563 (add-text-properties (match-beginning 4) (match-end 4) mp)
3564 t)))
3567 ;;; Syntax Table ==============================================================
3569 (defvar markdown-mode-syntax-table
3570 (let ((tab (make-syntax-table text-mode-syntax-table)))
3571 (modify-syntax-entry ?\" "." tab)
3572 tab)
3573 "Syntax table for `markdown-mode'.")
3576 ;;; Element Insertion =========================================================
3578 (defun markdown-ensure-blank-line-before ()
3579 "If previous line is not already blank, insert a blank line before point."
3580 (unless (bolp) (insert "\n"))
3581 (unless (or (bobp) (looking-back "\n\\s-*\n" nil)) (insert "\n")))
3583 (defun markdown-ensure-blank-line-after ()
3584 "If following line is not already blank, insert a blank line after point.
3585 Return the point where it was originally."
3586 (save-excursion
3587 (unless (eolp) (insert "\n"))
3588 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
3590 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
3591 "Insert the strings S1 and S2, wrapping around region or THING.
3592 If a region is specified by the optional BEG and END arguments,
3593 wrap the strings S1 and S2 around that region.
3594 If there is an active region, wrap the strings S1 and S2 around
3595 the region. If there is not an active region but the point is at
3596 THING, wrap that thing (which defaults to word). Otherwise, just
3597 insert S1 and S2 and place the point in between. Return the
3598 bounds of the entire wrapped string, or nil if nothing was wrapped
3599 and S1 and S2 were only inserted."
3600 (let (a b bounds new-point)
3601 (cond
3602 ;; Given region
3603 ((and beg end)
3604 (setq a beg
3605 b end
3606 new-point (+ (point) (length s1))))
3607 ;; Active region
3608 ((markdown-use-region-p)
3609 (setq a (region-beginning)
3610 b (region-end)
3611 new-point (+ (point) (length s1))))
3612 ;; Thing (word) at point
3613 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
3614 (setq a (car bounds)
3615 b (cdr bounds)
3616 new-point (+ (point) (length s1))))
3617 ;; No active region and no word
3619 (setq a (point)
3620 b (point))))
3621 (goto-char b)
3622 (insert s2)
3623 (goto-char a)
3624 (insert s1)
3625 (when new-point (goto-char new-point))
3626 (if (= a b)
3628 (setq b (+ b (length s1) (length s2)))
3629 (cons a b))))
3631 (defun markdown-point-after-unwrap (cur prefix suffix)
3632 "Return desired position of point after an unwrapping operation.
3633 CUR gives the position of the point before the operation.
3634 Additionally, two cons cells must be provided. PREFIX gives the
3635 bounds of the prefix string and SUFFIX gives the bounds of the
3636 suffix string."
3637 (cond ((< cur (cdr prefix)) (car prefix))
3638 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
3639 ((<= cur (cdr suffix))
3640 (- cur (+ (- (cdr prefix) (car prefix))
3641 (- cur (car suffix)))))
3642 (t cur)))
3644 (defun markdown-unwrap-thing-at-point (regexp all text)
3645 "Remove prefix and suffix of thing at point and reposition the point.
3646 When the thing at point matches REGEXP, replace the subexpression
3647 ALL with the string in subexpression TEXT. Reposition the point
3648 in an appropriate location accounting for the removal of prefix
3649 and suffix strings. Return new bounds of string from group TEXT.
3650 When REGEXP is nil, assumes match data is already set."
3651 (when (or (null regexp)
3652 (thing-at-point-looking-at regexp))
3653 (let ((cur (point))
3654 (prefix (cons (match-beginning all) (match-beginning text)))
3655 (suffix (cons (match-end text) (match-end all)))
3656 (bounds (cons (match-beginning text) (match-end text))))
3657 ;; Replace the thing at point
3658 (replace-match (match-string text) t t nil all)
3659 ;; Reposition the point
3660 (goto-char (markdown-point-after-unwrap cur prefix suffix))
3661 ;; Adjust bounds
3662 (setq bounds (cons (car prefix)
3663 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
3665 (defun markdown-unwrap-things-in-region (beg end regexp all text)
3666 "Remove prefix and suffix of all things in region from BEG to END.
3667 When a thing in the region matches REGEXP, replace the
3668 subexpression ALL with the string in subexpression TEXT.
3669 Return a cons cell containing updated bounds for the region."
3670 (save-excursion
3671 (goto-char beg)
3672 (let ((removed 0) len-all len-text)
3673 (while (re-search-forward regexp (- end removed) t)
3674 (setq len-all (length (match-string-no-properties all)))
3675 (setq len-text (length (match-string-no-properties text)))
3676 (setq removed (+ removed (- len-all len-text)))
3677 (replace-match (match-string text) t t nil all))
3678 (cons beg (- end removed)))))
3680 (defun markdown-insert-hr (arg)
3681 "Insert or replace a horizonal rule.
3682 By default, use the first element of `markdown-hr-strings'. When
3683 ARG is non-nil, as when given a prefix, select a different
3684 element as follows. When prefixed with \\[universal-argument],
3685 use the last element of `markdown-hr-strings' instead. When
3686 prefixed with an integer from 1 to the length of
3687 `markdown-hr-strings', use the element in that position instead."
3688 (interactive "*P")
3689 (when (thing-at-point-looking-at markdown-regex-hr)
3690 (delete-region (match-beginning 0) (match-end 0)))
3691 (markdown-ensure-blank-line-before)
3692 (cond ((equal arg '(4))
3693 (insert (car (reverse markdown-hr-strings))))
3694 ((and (integerp arg) (> arg 0)
3695 (<= arg (length markdown-hr-strings)))
3696 (insert (nth (1- arg) markdown-hr-strings)))
3698 (insert (car markdown-hr-strings))))
3699 (markdown-ensure-blank-line-after))
3701 (defun markdown-insert-bold ()
3702 "Insert markup to make a region or word bold.
3703 If there is an active region, make the region bold. If the point
3704 is at a non-bold word, make the word bold. If the point is at a
3705 bold word or phrase, remove the bold markup. Otherwise, simply
3706 insert bold delimiters and place the point in between them."
3707 (interactive)
3708 (let ((delim (if markdown-bold-underscore "__" "**")))
3709 (if (markdown-use-region-p)
3710 ;; Active region
3711 (let ((bounds (markdown-unwrap-things-in-region
3712 (region-beginning) (region-end)
3713 markdown-regex-bold 2 4)))
3714 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3715 ;; Bold markup removal, bold word at point, or empty markup insertion
3716 (if (thing-at-point-looking-at markdown-regex-bold)
3717 (markdown-unwrap-thing-at-point nil 2 4)
3718 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3720 (defun markdown-insert-italic ()
3721 "Insert markup to make a region or word italic.
3722 If there is an active region, make the region italic. If the point
3723 is at a non-italic word, make the word italic. If the point is at an
3724 italic word or phrase, remove the italic markup. Otherwise, simply
3725 insert italic delimiters and place the point in between them."
3726 (interactive)
3727 (let ((delim (if markdown-italic-underscore "_" "*")))
3728 (if (markdown-use-region-p)
3729 ;; Active region
3730 (let ((bounds (markdown-unwrap-things-in-region
3731 (region-beginning) (region-end)
3732 markdown-regex-italic 1 3)))
3733 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3734 ;; Italic markup removal, italic word at point, or empty markup insertion
3735 (if (thing-at-point-looking-at markdown-regex-italic)
3736 (markdown-unwrap-thing-at-point nil 1 3)
3737 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3739 (defun markdown-insert-strike-through ()
3740 "Insert markup to make a region or word strikethrough.
3741 If there is an active region, make the region strikethrough. If the point
3742 is at a non-bold word, make the word strikethrough. If the point is at a
3743 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
3744 simply insert bold delimiters and place the point in between them."
3745 (interactive)
3746 (let ((delim "~~"))
3747 (if (markdown-use-region-p)
3748 ;; Active region
3749 (let ((bounds (markdown-unwrap-things-in-region
3750 (region-beginning) (region-end)
3751 markdown-regex-strike-through 2 4)))
3752 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3753 ;; Strikethrough markup removal, strikethrough word at point, or empty markup insertion
3754 (if (thing-at-point-looking-at markdown-regex-strike-through)
3755 (markdown-unwrap-thing-at-point nil 2 4)
3756 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3758 (defun markdown-insert-code ()
3759 "Insert markup to make a region or word an inline code fragment.
3760 If there is an active region, make the region an inline code
3761 fragment. If the point is at a word, make the word an inline
3762 code fragment. Otherwise, simply insert code delimiters and
3763 place the point in between them."
3764 (interactive)
3765 (if (markdown-use-region-p)
3766 ;; Active region
3767 (let ((bounds (markdown-unwrap-things-in-region
3768 (region-beginning) (region-end)
3769 markdown-regex-code 1 3)))
3770 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
3771 ;; Code markup removal, code markup for word, or empty markup insertion
3772 (if (markdown-inline-code-at-point)
3773 (markdown-unwrap-thing-at-point nil 0 2)
3774 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
3776 (defun markdown-insert-kbd ()
3777 "Insert markup to wrap region or word in <kbd> tags.
3778 If there is an active region, use the region. If the point is at
3779 a word, use the word. Otherwise, simply insert <kbd> tags and
3780 place the point in between them."
3781 (interactive)
3782 (if (markdown-use-region-p)
3783 ;; Active region
3784 (let ((bounds (markdown-unwrap-things-in-region
3785 (region-beginning) (region-end)
3786 markdown-regex-kbd 0 2)))
3787 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil (car bounds) (cdr bounds)))
3788 ;; Markup removal, markup for word, or empty markup insertion
3789 (if (thing-at-point-looking-at markdown-regex-kbd)
3790 (markdown-unwrap-thing-at-point nil 0 2)
3791 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil))))
3793 (defun markdown-insert-inline-link (text url &optional title)
3794 "Insert an inline link with TEXT pointing to URL.
3795 Optionally, the user can provide a TITLE."
3796 (let ((cur (point)))
3797 (setq title (and title (concat " \"" title "\"")))
3798 (insert (concat "[" text "](" url title ")"))
3799 (cond ((not text) (goto-char (+ 1 cur)))
3800 ((not url) (goto-char (+ 3 (length text) cur))))))
3802 (defun markdown-insert-inline-image (text url &optional title)
3803 "Insert an inline link with alt TEXT pointing to URL.
3804 Optionally, also provide a TITLE."
3805 (let ((cur (point)))
3806 (setq title (and title (concat " \"" title "\"")))
3807 (insert (concat "![" text "](" url title ")"))
3808 (cond ((not text) (goto-char (+ 2 cur)))
3809 ((not url) (goto-char (+ 4 (length text) cur))))))
3811 (defun markdown-insert-reference-link (text label &optional url title)
3812 "Insert a reference link and, optionally, a reference definition.
3813 The link TEXT will be inserted followed by the optional LABEL.
3814 If a URL is given, also insert a definition for the reference
3815 LABEL according to `markdown-reference-location'. If a TITLE is
3816 given, it will be added to the end of the reference definition
3817 and will be used to populate the title attribute when converted
3818 to XHTML. If URL is nil, insert only the link portion (for
3819 example, when a reference label is already defined)."
3820 (insert (concat "[" text "][" label "]"))
3821 (when url
3822 (markdown-insert-reference-definition
3823 (if (string-equal label "") text label)
3824 url title)))
3826 (defun markdown-insert-reference-image (text label &optional url title)
3827 "Insert a reference image and, optionally, a reference definition.
3828 The alt TEXT will be inserted followed by the optional LABEL.
3829 If a URL is given, also insert a definition for the reference
3830 LABEL according to `markdown-reference-location'. If a TITLE is
3831 given, it will be added to the end of the reference definition
3832 and will be used to populate the title attribute when converted
3833 to XHTML. If URL is nil, insert only the link portion (for
3834 example, when a reference label is already defined)."
3835 (insert (concat "![" text "][" label "]"))
3836 (when url
3837 (markdown-insert-reference-definition
3838 (if (string-equal label "") text label)
3839 url title)))
3841 (defun markdown-insert-reference-definition (label &optional url title)
3842 "Add definition for reference LABEL with URL and TITLE.
3843 LABEL is a Markdown reference label without square brackets.
3844 URL and TITLE are optional. When given, the TITLE will
3845 be used to populate the title attribute when converted to XHTML."
3846 ;; END specifies where to leave the point upon return
3847 (let ((end (point)))
3848 (cl-case markdown-reference-location
3849 (end (goto-char (point-max)))
3850 (immediately (markdown-end-of-text-block))
3851 (subtree (markdown-end-of-subtree))
3852 (header (markdown-end-of-defun)))
3853 ;; Skip backwards over local variables. This logic is similar to the one
3854 ;; used in ‘hack-local-variables’.
3855 (when (and enable-local-variables (eobp))
3856 (search-backward "\n\f" (max (- (point) 3000) (point-min)) :move)
3857 (when (let ((case-fold-search t))
3858 (search-forward "Local Variables:" nil :move))
3859 (beginning-of-line 0)
3860 (when (eq (char-before) ?\n) (backward-char))))
3861 (unless (or (markdown-cur-line-blank-p)
3862 (thing-at-point-looking-at markdown-regex-reference-definition))
3863 (insert "\n"))
3864 (insert "\n[" label "]: ")
3865 (if url
3866 (insert url)
3867 ;; When no URL is given, leave point at END following the colon
3868 (setq end (point)))
3869 (when (> (length title) 0)
3870 (insert " \"" title "\""))
3871 (unless (looking-at-p "\n")
3872 (insert "\n"))
3873 (goto-char end)
3874 (when url
3875 (message
3876 (markdown--substitute-command-keys
3877 "Reference [%s] was defined, press \\[markdown-do] to jump there")
3878 label))))
3880 (define-obsolete-function-alias
3881 'markdown-insert-inline-link-dwim 'markdown-insert-link "v2.3")
3882 (define-obsolete-function-alias
3883 'markdown-insert-reference-link-dwim 'markdown-insert-link "v2.3")
3885 (defun markdown--insert-link-or-image (image)
3886 "Interactively insert new or update an existing link or image.
3887 When IMAGE is non-nil, insert an image. Otherwise, insert a link.
3888 This is an internal function called by
3889 `markdown-insert-link' and `markdown-insert-image'."
3890 (cl-multiple-value-bind (begin end text uri ref title)
3891 (if (markdown-use-region-p)
3892 ;; Use region as either link text or URL as appropriate.
3893 (let ((region (buffer-substring-no-properties
3894 (region-beginning) (region-end))))
3895 (if (string-match markdown-regex-uri region)
3896 ;; Region contains a URL; use it as such.
3897 (list (region-beginning) (region-end)
3898 nil (match-string 0 region) nil nil)
3899 ;; Region doesn't contain a URL, so use it as text.
3900 (list (region-beginning) (region-end)
3901 region nil nil nil)))
3902 ;; Extract and use properties of existing link, if any.
3903 (markdown-link-at-pos (point)))
3904 (let* ((ref (when ref (concat "[" ref "]")))
3905 (defined-refs (append
3906 (mapcar (lambda (ref) (concat "[" ref "]"))
3907 (markdown-get-defined-references))))
3908 (used-uris (markdown-get-used-uris))
3909 (uri-or-ref (completing-read
3910 "URL or [reference]: "
3911 (append defined-refs used-uris)
3912 nil nil (or uri ref)))
3913 (ref (cond ((string-match "\\`\\[\\(.*\\)\\]\\'" uri-or-ref)
3914 (match-string 1 uri-or-ref))
3915 ((string-equal "" uri-or-ref)
3916 "")))
3917 (uri (unless ref uri-or-ref))
3918 (text-prompt (if image
3919 "Alt text: "
3920 (if ref
3921 "Link text: "
3922 "Link text (blank for plain URL): ")))
3923 (text (read-string text-prompt text))
3924 (text (if (= (length text) 0) nil text))
3925 (plainp (and uri (not text)))
3926 (implicitp (string-equal ref ""))
3927 (ref (if implicitp text ref))
3928 (definedp (and ref (markdown-reference-definition ref)))
3929 (ref-url (unless (or uri definedp)
3930 (completing-read "Reference URL: " used-uris)))
3931 (title (unless (or plainp definedp)
3932 (read-string "Title (tooltip text, optional): " title)))
3933 (title (if (= (length title) 0) nil title)))
3934 (when (and image implicitp)
3935 (user-error "Reference required: implicit image references are invalid"))
3936 (when (and begin end)
3937 (delete-region begin end))
3938 (cond
3939 ((and (not image) uri text)
3940 (markdown-insert-inline-link text uri title))
3941 ((and image uri text)
3942 (markdown-insert-inline-image text uri title))
3943 ((and ref text)
3944 (if image
3945 (markdown-insert-reference-image text (unless implicitp ref) nil title)
3946 (markdown-insert-reference-link text (unless implicitp ref) nil title))
3947 (unless definedp
3948 (markdown-insert-reference-definition ref ref-url title)))
3949 ((and (not image) uri)
3950 (markdown-insert-uri uri))))))
3952 (defun markdown-insert-link ()
3953 "Insert new or update an existing link, with interactive prompts.
3954 If the point is at an existing link or URL, update the link text,
3955 URL, reference label, and/or title. Otherwise, insert a new link.
3956 The type of link inserted (inline, reference, or plain URL)
3957 depends on which values are provided:
3959 * If a URL and TEXT are given, insert an inline link: [TEXT](URL).
3960 * If [REF] and TEXT are given, insert a reference link: [TEXT][REF].
3961 * If only TEXT is given, insert an implicit reference link: [TEXT][].
3962 * If only a URL is given, insert a plain link: <URL>.
3964 In other words, to create an implicit reference link, leave the
3965 URL prompt empty and to create a plain URL link, leave the link
3966 text empty.
3968 If there is an active region, use the text as the default URL, if
3969 it seems to be a URL, or link text value otherwise.
3971 If a given reference is not defined, this function will
3972 additionally prompt for the URL and optional title. In this case,
3973 the reference definition is placed at the location determined by
3974 `markdown-reference-location'.
3976 Through updating the link, this function can be used to convert a
3977 link of one type (inline, reference, or plain) to another type by
3978 selectively adding or removing information via the prompts."
3979 (interactive)
3980 (markdown--insert-link-or-image nil))
3982 (defun markdown-insert-image ()
3983 "Insert new or update an existing image, with interactive prompts.
3984 If the point is at an existing image, update the alt text, URL,
3985 reference label, and/or title. Otherwise, insert a new image.
3986 The type of image inserted (inline or reference) depends on which
3987 values are provided:
3989 * If a URL and ALT-TEXT are given, insert an inline image:
3990 ![ALT-TEXT](URL).
3991 * If [REF] and ALT-TEXT are given, insert a reference image:
3992 ![ALT-TEXT][REF].
3994 If there is an active region, use the text as the default URL, if
3995 it seems to be a URL, or alt text value otherwise.
3997 If a given reference is not defined, this function will
3998 additionally prompt for the URL and optional title. In this case,
3999 the reference definition is placed at the location determined by
4000 `markdown-reference-location'.
4002 Through updating the image, this function can be used to convert an
4003 image of one type (inline or reference) to another type by
4004 selectively adding or removing information via the prompts."
4005 (interactive)
4006 (markdown--insert-link-or-image t))
4008 (defun markdown-insert-uri (&optional uri)
4009 "Insert markup for an inline URI.
4010 If there is an active region, use it as the URI. If the point is
4011 at a URI, wrap it with angle brackets. If the point is at an
4012 inline URI, remove the angle brackets. Otherwise, simply insert
4013 angle brackets place the point between them."
4014 (interactive)
4015 (if (markdown-use-region-p)
4016 ;; Active region
4017 (let ((bounds (markdown-unwrap-things-in-region
4018 (region-beginning) (region-end)
4019 markdown-regex-angle-uri 0 2)))
4020 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
4021 ;; Markup removal, URI at point, new URI, or empty markup insertion
4022 (if (thing-at-point-looking-at markdown-regex-angle-uri)
4023 (markdown-unwrap-thing-at-point nil 0 2)
4024 (if uri
4025 (insert "<" uri ">")
4026 (markdown-wrap-or-insert "<" ">" 'url nil nil)))))
4028 (defun markdown-insert-wiki-link ()
4029 "Insert a wiki link of the form [[WikiLink]].
4030 If there is an active region, use the region as the link text.
4031 If the point is at a word, use the word as the link text. If
4032 there is no active region and the point is not at word, simply
4033 insert link markup."
4034 (interactive)
4035 (if (markdown-use-region-p)
4036 ;; Active region
4037 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
4038 ;; Markup removal, wiki link at at point, or empty markup insertion
4039 (if (thing-at-point-looking-at markdown-regex-wiki-link)
4040 (if (or markdown-wiki-link-alias-first
4041 (null (match-string 5)))
4042 (markdown-unwrap-thing-at-point nil 1 3)
4043 (markdown-unwrap-thing-at-point nil 1 5))
4044 (markdown-wrap-or-insert "[[" "]]"))))
4046 (defun markdown-remove-header ()
4047 "Remove header markup if point is at a header.
4048 Return bounds of remaining header text if a header was removed
4049 and nil otherwise."
4050 (interactive "*")
4051 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
4052 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
4054 (defun markdown-insert-header (&optional level text setext)
4055 "Insert or replace header markup.
4056 The level of the header is specified by LEVEL and header text is
4057 given by TEXT. LEVEL must be an integer from 1 and 6, and the
4058 default value is 1.
4059 When TEXT is nil, the header text is obtained as follows.
4060 If there is an active region, it is used as the header text.
4061 Otherwise, the current line will be used as the header text.
4062 If there is not an active region and the point is at a header,
4063 remove the header markup and replace with level N header.
4064 Otherwise, insert empty header markup and place the point in
4065 between.
4066 The style of the header will be atx (hash marks) unless
4067 SETEXT is non-nil, in which case a setext-style (underlined)
4068 header will be inserted."
4069 (interactive "p\nsHeader text: ")
4070 (setq level (min (max (or level 1) 1) (if setext 2 6)))
4071 ;; Determine header text if not given
4072 (when (null text)
4073 (if (markdown-use-region-p)
4074 ;; Active region
4075 (setq text (delete-and-extract-region (region-beginning) (region-end)))
4076 ;; No active region
4077 (markdown-remove-header)
4078 (setq text (delete-and-extract-region
4079 (line-beginning-position) (line-end-position)))
4080 (when (and setext (string-match-p "^[ \t]*$" text))
4081 (setq text (read-string "Header text: "))))
4082 (setq text (markdown-compress-whitespace-string text)))
4083 ;; Insertion with given text
4084 (markdown-ensure-blank-line-before)
4085 (let (hdr)
4086 (cond (setext
4087 (setq hdr (make-string (string-width text) (if (= level 2) ?- ?=)))
4088 (insert text "\n" hdr))
4090 (setq hdr (make-string level ?#))
4091 (insert hdr " " text)
4092 (when (null markdown-asymmetric-header) (insert " " hdr)))))
4093 (markdown-ensure-blank-line-after)
4094 ;; Leave point at end of text
4095 (cond (setext
4096 (backward-char (1+ (string-width text))))
4097 ((null markdown-asymmetric-header)
4098 (backward-char (1+ level)))))
4100 (defun markdown-insert-header-dwim (&optional arg setext)
4101 "Insert or replace header markup.
4102 The level and type of the header are determined automatically by
4103 the type and level of the previous header, unless a prefix
4104 argument is given via ARG.
4105 With a numeric prefix valued 1 to 6, insert a header of the given
4106 level, with the type being determined automatically (note that
4107 only level 1 or 2 setext headers are possible).
4109 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
4110 promote the heading by one level.
4111 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
4112 demote the heading by one level.
4113 When SETEXT is non-nil, prefer setext-style headers when
4114 possible (levels one and two).
4116 When there is an active region, use it for the header text. When
4117 the point is at an existing header, change the type and level
4118 according to the rules above.
4119 Otherwise, if the line is not empty, create a header using the
4120 text on the current line as the header text.
4121 Finally, if the point is on a blank line, insert empty header
4122 markup (atx) or prompt for text (setext).
4123 See `markdown-insert-header' for more details about how the
4124 header text is determined."
4125 (interactive "*P")
4126 (let (level)
4127 (save-excursion
4128 (when (or (thing-at-point-looking-at markdown-regex-header)
4129 (re-search-backward markdown-regex-header nil t))
4130 ;; level of current or previous header
4131 (setq level (markdown-outline-level))
4132 ;; match group 1 indicates a setext header
4133 (setq setext (match-end 1))))
4134 ;; check prefix argument
4135 (cond
4136 ((and (equal arg '(4)) level (> level 1)) ;; C-u
4137 (cl-decf level))
4138 ((and (equal arg '(16)) level (< level 6)) ;; C-u C-u
4139 (cl-incf level))
4140 (arg ;; numeric prefix
4141 (setq level (prefix-numeric-value arg))))
4142 ;; setext headers must be level one or two
4143 (and level (setq setext (and setext (<= level 2))))
4144 ;; insert the heading
4145 (markdown-insert-header level nil setext)))
4147 (defun markdown-insert-header-setext-dwim (&optional arg)
4148 "Insert or replace header markup, with preference for setext.
4149 See `markdown-insert-header-dwim' for details, including how ARG is handled."
4150 (interactive "*P")
4151 (markdown-insert-header-dwim arg t))
4153 (defun markdown-insert-header-atx-1 ()
4154 "Insert a first level atx-style (hash mark) header.
4155 See `markdown-insert-header'."
4156 (interactive "*")
4157 (markdown-insert-header 1 nil nil))
4159 (defun markdown-insert-header-atx-2 ()
4160 "Insert a level two atx-style (hash mark) header.
4161 See `markdown-insert-header'."
4162 (interactive "*")
4163 (markdown-insert-header 2 nil nil))
4165 (defun markdown-insert-header-atx-3 ()
4166 "Insert a level three atx-style (hash mark) header.
4167 See `markdown-insert-header'."
4168 (interactive "*")
4169 (markdown-insert-header 3 nil nil))
4171 (defun markdown-insert-header-atx-4 ()
4172 "Insert a level four atx-style (hash mark) header.
4173 See `markdown-insert-header'."
4174 (interactive "*")
4175 (markdown-insert-header 4 nil nil))
4177 (defun markdown-insert-header-atx-5 ()
4178 "Insert a level five atx-style (hash mark) header.
4179 See `markdown-insert-header'."
4180 (interactive "*")
4181 (markdown-insert-header 5 nil nil))
4183 (defun markdown-insert-header-atx-6 ()
4184 "Insert a sixth level atx-style (hash mark) header.
4185 See `markdown-insert-header'."
4186 (interactive "*")
4187 (markdown-insert-header 6 nil nil))
4189 (defun markdown-insert-header-setext-1 ()
4190 "Insert a setext-style (underlined) first-level header.
4191 See `markdown-insert-header'."
4192 (interactive "*")
4193 (markdown-insert-header 1 nil t))
4195 (defun markdown-insert-header-setext-2 ()
4196 "Insert a setext-style (underlined) second-level header.
4197 See `markdown-insert-header'."
4198 (interactive "*")
4199 (markdown-insert-header 2 nil t))
4201 (defun markdown-blockquote-indentation (loc)
4202 "Return string containing necessary indentation for a blockquote at LOC.
4203 Also see `markdown-pre-indentation'."
4204 (save-excursion
4205 (goto-char loc)
4206 (let* ((list-level (length (markdown-calculate-list-levels)))
4207 (indent ""))
4208 (dotimes (_ list-level indent)
4209 (setq indent (concat indent " "))))))
4211 (defun markdown-insert-blockquote ()
4212 "Start a blockquote section (or blockquote the region).
4213 If Transient Mark mode is on and a region is active, it is used as
4214 the blockquote text."
4215 (interactive)
4216 (if (markdown-use-region-p)
4217 (markdown-blockquote-region (region-beginning) (region-end))
4218 (markdown-ensure-blank-line-before)
4219 (insert (markdown-blockquote-indentation (point)) "> ")
4220 (markdown-ensure-blank-line-after)))
4222 (defun markdown-block-region (beg end prefix)
4223 "Format the region using a block prefix.
4224 Arguments BEG and END specify the beginning and end of the
4225 region. The characters PREFIX will appear at the beginning
4226 of each line."
4227 (save-excursion
4228 (let* ((end-marker (make-marker))
4229 (beg-marker (make-marker))
4230 (prefix-without-trailing-whitespace
4231 (replace-regexp-in-string (rx (+ blank) eos) "" prefix)))
4232 ;; Ensure blank line after and remove extra whitespace
4233 (goto-char end)
4234 (skip-syntax-backward "-")
4235 (set-marker end-marker (point))
4236 (delete-horizontal-space)
4237 (markdown-ensure-blank-line-after)
4238 ;; Ensure blank line before and remove extra whitespace
4239 (goto-char beg)
4240 (skip-syntax-forward "-")
4241 (delete-horizontal-space)
4242 (markdown-ensure-blank-line-before)
4243 (set-marker beg-marker (point))
4244 ;; Insert PREFIX before each line
4245 (goto-char beg-marker)
4246 (while (and (< (line-beginning-position) end-marker)
4247 (not (eobp)))
4248 ;; Don’t insert trailing whitespace.
4249 (insert (if (eolp) prefix-without-trailing-whitespace prefix))
4250 (forward-line)))))
4252 (defun markdown-blockquote-region (beg end)
4253 "Blockquote the region.
4254 Arguments BEG and END specify the beginning and end of the region."
4255 (interactive "*r")
4256 (markdown-block-region
4257 beg end (concat (markdown-blockquote-indentation
4258 (max (point-min) (1- beg))) "> ")))
4260 (defun markdown-pre-indentation (loc)
4261 "Return string containing necessary whitespace for a pre block at LOC.
4262 Also see `markdown-blockquote-indentation'."
4263 (save-excursion
4264 (goto-char loc)
4265 (let* ((list-level (length (markdown-calculate-list-levels)))
4266 indent)
4267 (dotimes (_ (1+ list-level) indent)
4268 (setq indent (concat indent " "))))))
4270 (defun markdown-insert-pre ()
4271 "Start a preformatted section (or apply to the region).
4272 If Transient Mark mode is on and a region is active, it is marked
4273 as preformatted text."
4274 (interactive)
4275 (if (markdown-use-region-p)
4276 (markdown-pre-region (region-beginning) (region-end))
4277 (markdown-ensure-blank-line-before)
4278 (insert (markdown-pre-indentation (point)))
4279 (markdown-ensure-blank-line-after)))
4281 (defun markdown-pre-region (beg end)
4282 "Format the region as preformatted text.
4283 Arguments BEG and END specify the beginning and end of the region."
4284 (interactive "*r")
4285 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
4286 (markdown-block-region beg end indent)))
4288 (defun markdown-electric-backquote (arg)
4289 "Insert a backquote.
4290 The numeric prefix argument ARG says how many times to repeat the insertion.
4291 Call `markdown-insert-gfm-code-block' interactively
4292 if three backquotes inserted at the beginning of line."
4293 (interactive "*P")
4294 (self-insert-command (prefix-numeric-value arg))
4295 (when (and markdown-gfm-use-electric-backquote (looking-back "^```" nil))
4296 (replace-match "")
4297 (call-interactively #'markdown-insert-gfm-code-block)))
4299 (defconst markdown-gfm-recognized-languages
4300 ;; To reproduce/update, evaluate the let-form in
4301 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
4302 ;; but with appropriate use of a keyboard macro, indenting and filling it
4303 ;; properly is pretty fast.
4304 '("1C-Enterprise" "ABAP" "ABNF" "AGS-Script" "AMPL" "ANTLR"
4305 "API-Blueprint" "APL" "ASN.1" "ASP" "ATS" "ActionScript" "Ada" "Agda"
4306 "Alloy" "Alpine-Abuild" "Ant-Build-System" "ApacheConf" "Apex"
4307 "Apollo-Guidance-Computer" "AppleScript" "Arc" "Arduino" "AsciiDoc"
4308 "AspectJ" "Assembly" "Augeas" "AutoHotkey" "AutoIt" "Awk" "Batchfile"
4309 "Befunge" "Bison" "BitBake" "Blade" "BlitzBasic" "BlitzMax" "Bluespec"
4310 "Boo" "Brainfuck" "Brightscript" "Bro" "C#" "C++" "C-ObjDump"
4311 "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "COLLADA" "CSON" "CSS" "CSV"
4312 "CWeb" "Cap'n-Proto" "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK"
4313 "Cirru" "Clarion" "Clean" "Click" "Clojure" "Closure-Templates"
4314 "CoffeeScript" "ColdFusion" "ColdFusion-CFC" "Common-Lisp"
4315 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal"
4316 "Csound" "Csound-Document" "Csound-Score" "Cuda" "Cycript" "Cython"
4317 "D-ObjDump" "DIGITAL-Command-Language" "DM" "DNS-Zone" "DTrace"
4318 "Darcs-Patch" "Dart" "Diff" "Dockerfile" "Dogescript" "Dylan" "EBNF"
4319 "ECL" "ECLiPSe" "EJS" "EQ" "Eagle" "Ecere-Projects" "Eiffel" "Elixir"
4320 "Elm" "Emacs-Lisp" "EmberScript" "Erlang" "F#" "FLUX" "Factor" "Fancy"
4321 "Fantom" "Filebench-WML" "Filterscript" "Formatted" "Forth" "Fortran"
4322 "FreeMarker" "Frege" "G-code" "GAMS" "GAP" "GCC-Machine-Description"
4323 "GDB" "GDScript" "GLSL" "GN" "Game-Maker-Language" "Genie" "Genshi"
4324 "Gentoo-Ebuild" "Gentoo-Eclass" "Gettext-Catalog" "Gherkin" "Glyph"
4325 "Gnuplot" "Go" "Golo" "Gosu" "Grace" "Gradle" "Grammatical-Framework"
4326 "Graph-Modeling-Language" "GraphQL" "Graphviz-(DOT)" "Groovy"
4327 "Groovy-Server-Pages" "HCL" "HLSL" "HTML" "HTML+Django" "HTML+ECR"
4328 "HTML+EEX" "HTML+ERB" "HTML+PHP" "HTTP" "Hack" "Haml" "Handlebars"
4329 "Harbour" "Haskell" "Haxe" "Hy" "HyPhy" "IDL" "IGOR-Pro" "INI"
4330 "IRC-log" "Idris" "Inform-7" "Inno-Setup" "Io" "Ioke" "Isabelle"
4331 "Isabelle-ROOT" "JFlex" "JSON" "JSON5" "JSONLD" "JSONiq" "JSX"
4332 "Jasmin" "Java" "Java-Server-Pages" "JavaScript" "Jison" "Jison-Lex"
4333 "Jolie" "Julia" "Jupyter-Notebook" "KRL" "KiCad" "Kit" "Kotlin" "LFE"
4334 "LLVM" "LOLCODE" "LSL" "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex"
4335 "LilyPond" "Limbo" "Linker-Script" "Linux-Kernel-Module" "Liquid"
4336 "Literate-Agda" "Literate-CoffeeScript" "Literate-Haskell"
4337 "LiveScript" "Logos" "Logtalk" "LookML" "LoomScript" "Lua" "M4"
4338 "M4Sugar" "MAXScript" "MQL4" "MQL5" "MTML" "MUF" "Makefile" "Mako"
4339 "Markdown" "Marko" "Mask" "Mathematica" "Matlab" "Maven-POM" "Max"
4340 "MediaWiki" "Mercury" "Meson" "Metal" "MiniD" "Mirah" "Modelica"
4341 "Modula-2" "Module-Management-System" "Monkey" "Moocode" "MoonScript"
4342 "Myghty" "NCL" "NL" "NSIS" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo"
4343 "NewLisp" "Nginx" "Nim" "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml"
4344 "ObjDump" "Objective-C" "Objective-C++" "Objective-J" "Omgrofl" "Opa"
4345 "Opal" "OpenCL" "OpenEdge-ABL" "OpenRC-runscript" "OpenSCAD"
4346 "OpenType-Feature-File" "Org" "Ox" "Oxygene" "Oz" "P4" "PAWN" "PHP"
4347 "PLSQL" "PLpgSQL" "POV-Ray-SDL" "Pan" "Papyrus" "Parrot"
4348 "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal" "Pep8"
4349 "Perl" "Perl6" "Pic" "Pickle" "PicoLisp" "PigLatin" "Pike" "Pod"
4350 "PogoScript" "Pony" "PostScript" "PowerBuilder" "PowerShell"
4351 "Processing" "Prolog" "Propeller-Spin" "Protocol-Buffer" "Public-Key"
4352 "Pug" "Puppet" "Pure-Data" "PureBasic" "PureScript" "Python"
4353 "Python-console" "Python-traceback" "QML" "QMake" "RAML" "RDoc"
4354 "REALbasic" "REXX" "RHTML" "RMarkdown" "RPM-Spec" "RUNOFF" "Racket"
4355 "Ragel" "Rascal" "Raw-token-data" "Reason" "Rebol" "Red" "Redcode"
4356 "Regular-Expression" "Ren'Py" "RenderScript" "RobotFramework" "Roff"
4357 "Rouge" "Ruby" "Rust" "SAS" "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL"
4358 "SRecode-Template" "STON" "SVG" "Sage" "SaltStack" "Sass" "Scala"
4359 "Scaml" "Scheme" "Scilab" "Self" "ShaderLab" "Shell" "ShellSession"
4360 "Shen" "Slash" "Slim" "Smali" "Smalltalk" "Smarty" "SourcePawn"
4361 "Spline-Font-Database" "Squirrel" "Stan" "Standard-ML" "Stata"
4362 "Stylus" "SubRip-Text" "Sublime-Text-Config" "SuperCollider" "Swift"
4363 "SystemVerilog" "TI-Program" "TLA" "TOML" "TXL" "Tcl" "Tcsh" "TeX"
4364 "Tea" "Terra" "Text" "Textile" "Thrift" "Turing" "Turtle" "Twig"
4365 "Type-Language" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset"
4366 "Unix-Assembly" "Uno" "UnrealScript" "UrWeb" "VCL" "VHDL" "Vala"
4367 "Verilog" "Vim-script" "Visual-Basic" "Volt" "Vue"
4368 "Wavefront-Material" "Wavefront-Object" "Web-Ontology-Language"
4369 "WebAssembly" "WebIDL" "World-of-Warcraft-Addon-Data" "X10" "XC"
4370 "XCompose" "XML" "XPages" "XProc" "XQuery" "XS" "XSLT" "Xojo" "Xtend"
4371 "YAML" "YANG" "Yacc" "Zephir" "Zimpl" "desktop" "eC" "edn" "fish"
4372 "mupad" "nesC" "ooc" "reStructuredText" "wisp" "xBase")
4373 "Language specifiers recognized by GitHub's syntax highlighting features.")
4375 (defvar markdown-gfm-used-languages nil
4376 "Language names used in GFM code blocks.")
4377 (make-variable-buffer-local 'markdown-gfm-used-languages)
4379 (defun markdown-trim-whitespace (str)
4380 (markdown-replace-regexp-in-string
4381 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str))
4383 (defun markdown-clean-language-string (str)
4384 (markdown-replace-regexp-in-string
4385 "{\\.?\\|}" "" (markdown-trim-whitespace str)))
4387 (defun markdown-validate-language-string (widget)
4388 (let ((str (widget-value widget)))
4389 (unless (string= str (markdown-clean-language-string str))
4390 (widget-put widget :error (format "Invalid language spec: '%s'" str))
4391 widget)))
4393 (defun markdown-gfm-get-corpus ()
4394 "Create corpus of recognized GFM code block languages for the given buffer."
4395 (let ((given-corpus (append markdown-gfm-additional-languages
4396 markdown-gfm-recognized-languages)))
4397 (append
4398 markdown-gfm-used-languages
4399 (if markdown-gfm-downcase-languages (cl-mapcar #'downcase given-corpus)
4400 given-corpus))))
4402 (defun markdown-gfm-add-used-language (lang)
4403 "Clean LANG and add to list of used languages."
4404 (setq markdown-gfm-used-languages
4405 (cons lang (remove lang markdown-gfm-used-languages))))
4407 (defcustom markdown-spaces-after-code-fence 1
4408 "Number of space characters to insert after a code fence.
4409 \\<gfm-mode-map>\\[markdown-insert-gfm-code-block] inserts this many spaces between an
4410 opening code fence and an info string."
4411 :group 'markdown
4412 :type 'integer
4413 :safe #'natnump
4414 :package-version '(markdown-mode . "2.3"))
4416 (defun markdown-insert-gfm-code-block (&optional lang edit)
4417 "Insert GFM code block for language LANG.
4418 If LANG is nil, the language will be queried from user. If a
4419 region is active, wrap this region with the markup instead. If
4420 the region boundaries are not on empty lines, these are added
4421 automatically in order to have the correct markup. When EDIT is
4422 non-nil (e.g., when \\[universal-argument] is given), edit the
4423 code block in an indirect buffer after insertion."
4424 (interactive
4425 (list (let ((completion-ignore-case nil))
4426 (condition-case nil
4427 (markdown-clean-language-string
4428 (completing-read
4429 "Programming language: "
4430 (markdown-gfm-get-corpus)
4431 nil 'confirm (car markdown-gfm-used-languages)
4432 'markdown-gfm-language-history))
4433 (quit "")))
4434 current-prefix-arg))
4435 (unless (string= lang "") (markdown-gfm-add-used-language lang))
4436 (when (> (length lang) 0)
4437 (setq lang (concat (make-string markdown-spaces-after-code-fence ?\s)
4438 lang)))
4439 (if (markdown-use-region-p)
4440 (let* ((b (region-beginning)) (e (region-end)) end
4441 (indent (progn (goto-char b) (current-indentation))))
4442 (goto-char e)
4443 ;; if we're on a blank line, don't newline, otherwise the ```
4444 ;; should go on its own line
4445 (unless (looking-back "\n" nil)
4446 (newline))
4447 (indent-to indent)
4448 (insert "```")
4449 (markdown-ensure-blank-line-after)
4450 (setq end (point))
4451 (goto-char b)
4452 ;; if we're on a blank line, insert the quotes here, otherwise
4453 ;; add a new line first
4454 (unless (looking-at-p "\n")
4455 (newline)
4456 (forward-line -1))
4457 (markdown-ensure-blank-line-before)
4458 (indent-to indent)
4459 (insert "```" lang)
4460 (markdown-syntax-propertize-fenced-block-constructs (point-at-bol) end))
4461 (let ((indent (current-indentation)) start-bol)
4462 (delete-horizontal-space :backward-only)
4463 (markdown-ensure-blank-line-before)
4464 (indent-to indent)
4465 (setq start-bol (point-at-bol))
4466 (insert "```" lang "\n")
4467 (indent-to indent)
4468 (unless edit (insert ?\n))
4469 (indent-to indent)
4470 (insert "```")
4471 (markdown-ensure-blank-line-after)
4472 (markdown-syntax-propertize-fenced-block-constructs start-bol (point)))
4473 (end-of-line 0)
4474 (when edit (markdown-edit-code-block))))
4476 (defun markdown-code-block-lang (&optional pos-prop)
4477 "Return the language name for a GFM or tilde fenced code block.
4478 The beginning of the block may be described by POS-PROP,
4479 a cons of (pos . prop) giving the position and property
4480 at the beginning of the block."
4481 (or pos-prop
4482 (setq pos-prop
4483 (markdown-max-of-seq
4484 #'car
4485 (cl-remove-if
4486 #'null
4487 (cl-mapcar
4488 #'markdown-find-previous-prop
4489 (markdown-get-fenced-block-begin-properties))))))
4490 (when pos-prop
4491 (goto-char (car pos-prop))
4492 (set-match-data (get-text-property (point) (cdr pos-prop)))
4493 ;; Note: Hard-coded group number assumes tilde
4494 ;; and GFM fenced code regexp groups agree.
4495 (let ((begin (match-beginning 3))
4496 (end (match-end 3)))
4497 (when (and begin end)
4498 ;; Fix language strings beginning with periods, like ".ruby".
4499 (when (eq (char-after begin) ?.)
4500 (setq begin (1+ begin)))
4501 (buffer-substring-no-properties begin end)))))
4503 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer)
4504 (with-current-buffer (or buffer (current-buffer))
4505 (save-excursion
4506 (goto-char (point-min))
4507 (cl-loop
4508 with prop = 'markdown-gfm-block-begin
4509 for pos-prop = (markdown-find-next-prop prop)
4510 while pos-prop
4511 for lang = (markdown-code-block-lang pos-prop)
4512 do (progn (when lang (markdown-gfm-add-used-language lang))
4513 (goto-char (next-single-property-change (point) prop)))))))
4516 ;;; Footnotes ==================================================================
4518 (defun markdown-footnote-counter-inc ()
4519 "Increment `markdown-footnote-counter' and return the new value."
4520 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
4521 (save-excursion
4522 (goto-char (point-min))
4523 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
4524 (point-max) t)
4525 (let ((fn (string-to-number (match-string 1))))
4526 (when (> fn markdown-footnote-counter)
4527 (setq markdown-footnote-counter fn))))))
4528 (cl-incf markdown-footnote-counter))
4530 (defun markdown-insert-footnote ()
4531 "Insert footnote with a new number and move point to footnote definition."
4532 (interactive)
4533 (let ((fn (markdown-footnote-counter-inc)))
4534 (insert (format "[^%d]" fn))
4535 (markdown-footnote-text-find-new-location)
4536 (markdown-ensure-blank-line-before)
4537 (unless (markdown-cur-line-blank-p)
4538 (insert "\n"))
4539 (insert (format "[^%d]: " fn))
4540 (markdown-ensure-blank-line-after)))
4542 (defun markdown-footnote-text-find-new-location ()
4543 "Position the point at the proper location for a new footnote text."
4544 (cond
4545 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
4546 ((eq markdown-footnote-location 'immediately) (markdown-end-of-text-block))
4547 ((eq markdown-footnote-location 'subtree) (markdown-end-of-subtree))
4548 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
4550 (defun markdown-footnote-kill ()
4551 "Kill the footnote at point.
4552 The footnote text is killed (and added to the kill ring), the
4553 footnote marker is deleted. Point has to be either at the
4554 footnote marker or in the footnote text."
4555 (interactive)
4556 (let ((marker-pos nil)
4557 (skip-deleting-marker nil)
4558 (starting-footnote-text-positions
4559 (markdown-footnote-text-positions)))
4560 (when starting-footnote-text-positions
4561 ;; We're starting in footnote text, so mark our return position and jump
4562 ;; to the marker if possible.
4563 (let ((marker-pos (markdown-footnote-find-marker
4564 (cl-first starting-footnote-text-positions))))
4565 (if marker-pos
4566 (goto-char (1- marker-pos))
4567 ;; If there isn't a marker, we still want to kill the text.
4568 (setq skip-deleting-marker t))))
4569 ;; Either we didn't start in the text, or we started in the text and jumped
4570 ;; to the marker. We want to assume we're at the marker now and error if
4571 ;; we're not.
4572 (unless skip-deleting-marker
4573 (let ((marker (markdown-footnote-delete-marker)))
4574 (unless marker
4575 (error "Not at a footnote"))
4576 ;; Even if we knew the text position before, it changed when we deleted
4577 ;; the label.
4578 (setq marker-pos (cl-second marker))
4579 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker))))
4580 (unless new-text-pos
4581 (error "No text for footnote `%s'" (cl-first marker)))
4582 (goto-char new-text-pos))))
4583 (let ((pos (markdown-footnote-kill-text)))
4584 (goto-char (if starting-footnote-text-positions
4586 marker-pos)))))
4588 (defun markdown-footnote-delete-marker ()
4589 "Delete a footnote marker at point.
4590 Returns a list (ID START) containing the footnote ID and the
4591 start position of the marker before deletion. If no footnote
4592 marker was deleted, this function returns NIL."
4593 (let ((marker (markdown-footnote-marker-positions)))
4594 (when marker
4595 (delete-region (cl-second marker) (cl-third marker))
4596 (butlast marker))))
4598 (defun markdown-footnote-kill-text ()
4599 "Kill footnote text at point.
4600 Returns the start position of the footnote text before deletion,
4601 or NIL if point was not inside a footnote text.
4603 The killed text is placed in the kill ring (without the footnote
4604 number)."
4605 (let ((fn (markdown-footnote-text-positions)))
4606 (when fn
4607 (let ((text (delete-and-extract-region (cl-second fn) (cl-third fn))))
4608 (string-match (concat "\\[\\" (cl-first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
4609 (kill-new (match-string 1 text))
4610 (when (and (markdown-cur-line-blank-p)
4611 (markdown-prev-line-blank-p)
4612 (not (bobp)))
4613 (delete-region (1- (point)) (point)))
4614 (cl-second fn)))))
4616 (defun markdown-footnote-goto-text ()
4617 "Jump to the text of the footnote at point."
4618 (interactive)
4619 (let ((fn (car (markdown-footnote-marker-positions))))
4620 (unless fn
4621 (user-error "Not at a footnote marker"))
4622 (let ((new-pos (markdown-footnote-find-text fn)))
4623 (unless new-pos
4624 (error "No definition found for footnote `%s'" fn))
4625 (goto-char new-pos))))
4627 (defun markdown-footnote-return ()
4628 "Return from a footnote to its footnote number in the main text."
4629 (interactive)
4630 (let ((fn (save-excursion
4631 (car (markdown-footnote-text-positions)))))
4632 (unless fn
4633 (user-error "Not in a footnote"))
4634 (let ((new-pos (markdown-footnote-find-marker fn)))
4635 (unless new-pos
4636 (error "Footnote marker `%s' not found" fn))
4637 (goto-char new-pos))))
4639 (defun markdown-footnote-find-marker (id)
4640 "Find the location of the footnote marker with ID.
4641 The actual buffer position returned is the position directly
4642 following the marker's closing bracket. If no marker is found,
4643 NIL is returned."
4644 (save-excursion
4645 (goto-char (point-min))
4646 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
4647 (skip-chars-backward "^]")
4648 (point))))
4650 (defun markdown-footnote-find-text (id)
4651 "Find the location of the text of footnote ID.
4652 The actual buffer position returned is the position of the first
4653 character of the text, after the footnote's identifier. If no
4654 footnote text is found, NIL is returned."
4655 (save-excursion
4656 (goto-char (point-min))
4657 (when (re-search-forward (concat "^ \\{0,3\\}\\[" id "\\]:") nil t)
4658 (skip-chars-forward "[ \t]")
4659 (point))))
4661 (defun markdown-footnote-marker-positions ()
4662 "Return the position and ID of the footnote marker point is on.
4663 The return value is a list (ID START END). If point is not on a
4664 footnote, NIL is returned."
4665 ;; first make sure we're at a footnote marker
4666 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
4667 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
4668 (save-excursion
4669 ;; move point between [ and ^:
4670 (if (looking-at-p "\\[")
4671 (forward-char 1)
4672 (skip-chars-backward "^["))
4673 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
4674 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
4676 (defun markdown-footnote-text-positions ()
4677 "Return the start and end positions of the footnote text point is in.
4678 The exact return value is a list of three elements: (ID START END).
4679 The start position is the position of the opening bracket
4680 of the footnote id. The end position is directly after the
4681 newline that ends the footnote. If point is not in a footnote,
4682 NIL is returned instead."
4683 (save-excursion
4684 (let (result)
4685 (move-beginning-of-line 1)
4686 ;; Try to find the label. If we haven't found the label and we're at a blank
4687 ;; or indented line, back up if possible.
4688 (while (and
4689 (not (and (looking-at markdown-regex-footnote-definition)
4690 (setq result (list (match-string 1) (point)))))
4691 (and (not (bobp))
4692 (or (markdown-cur-line-blank-p)
4693 (>= (current-indentation) 4))))
4694 (forward-line -1))
4695 (when result
4696 ;; Advance if there is a next line that is either blank or indented.
4697 ;; (Need to check if we're on the last line, because
4698 ;; markdown-next-line-blank-p returns true for last line in buffer.)
4699 (while (and (/= (line-end-position) (point-max))
4700 (or (markdown-next-line-blank-p)
4701 (>= (markdown-next-line-indent) 4)))
4702 (forward-line))
4703 ;; Move back while the current line is blank.
4704 (while (markdown-cur-line-blank-p)
4705 (forward-line -1))
4706 ;; Advance to capture this line and a single trailing newline (if there
4707 ;; is one).
4708 (forward-line)
4709 (append result (list (point)))))))
4712 ;;; Element Removal ===========================================================
4714 (defun markdown-kill-thing-at-point ()
4715 "Kill thing at point and add important text, without markup, to kill ring.
4716 Possible things to kill include (roughly in order of precedence):
4717 inline code, headers, horizonal rules, links (add link text to
4718 kill ring), images (add alt text to kill ring), angle uri, email
4719 addresses, bold, italics, reference definition (add URI to kill
4720 ring), footnote markers and text (kill both marker and text, add
4721 text to kill ring), and list items."
4722 (interactive "*")
4723 (let (val)
4724 (cond
4725 ;; Inline code
4726 ((markdown-inline-code-at-point)
4727 (kill-new (match-string 2))
4728 (delete-region (match-beginning 0) (match-end 0)))
4729 ;; ATX header
4730 ((thing-at-point-looking-at markdown-regex-header-atx)
4731 (kill-new (match-string 2))
4732 (delete-region (match-beginning 0) (match-end 0)))
4733 ;; Setext header
4734 ((thing-at-point-looking-at markdown-regex-header-setext)
4735 (kill-new (match-string 1))
4736 (delete-region (match-beginning 0) (match-end 0)))
4737 ;; Horizonal rule
4738 ((thing-at-point-looking-at markdown-regex-hr)
4739 (kill-new (match-string 0))
4740 (delete-region (match-beginning 0) (match-end 0)))
4741 ;; Inline link or image (add link or alt text to kill ring)
4742 ((thing-at-point-looking-at markdown-regex-link-inline)
4743 (kill-new (match-string 3))
4744 (delete-region (match-beginning 0) (match-end 0)))
4745 ;; Reference link or image (add link or alt text to kill ring)
4746 ((thing-at-point-looking-at markdown-regex-link-reference)
4747 (kill-new (match-string 3))
4748 (delete-region (match-beginning 0) (match-end 0)))
4749 ;; Angle URI (add URL to kill ring)
4750 ((thing-at-point-looking-at markdown-regex-angle-uri)
4751 (kill-new (match-string 2))
4752 (delete-region (match-beginning 0) (match-end 0)))
4753 ;; Email address in angle brackets (add email address to kill ring)
4754 ((thing-at-point-looking-at markdown-regex-email)
4755 (kill-new (match-string 1))
4756 (delete-region (match-beginning 0) (match-end 0)))
4757 ;; Wiki link (add alias text to kill ring)
4758 ((and markdown-enable-wiki-links
4759 (thing-at-point-looking-at markdown-regex-wiki-link))
4760 (kill-new (markdown-wiki-link-alias))
4761 (delete-region (match-beginning 1) (match-end 1)))
4762 ;; Bold
4763 ((thing-at-point-looking-at markdown-regex-bold)
4764 (kill-new (match-string 4))
4765 (delete-region (match-beginning 2) (match-end 2)))
4766 ;; Italics
4767 ((thing-at-point-looking-at markdown-regex-italic)
4768 (kill-new (match-string 3))
4769 (delete-region (match-beginning 1) (match-end 1)))
4770 ;; Strikethrough
4771 ((thing-at-point-looking-at markdown-regex-strike-through)
4772 (kill-new (match-string 4))
4773 (delete-region (match-beginning 2) (match-end 2)))
4774 ;; Footnote marker (add footnote text to kill ring)
4775 ((thing-at-point-looking-at markdown-regex-footnote)
4776 (markdown-footnote-kill))
4777 ;; Footnote text (add footnote text to kill ring)
4778 ((setq val (markdown-footnote-text-positions))
4779 (markdown-footnote-kill))
4780 ;; Reference definition (add URL to kill ring)
4781 ((thing-at-point-looking-at markdown-regex-reference-definition)
4782 (kill-new (match-string 5))
4783 (delete-region (match-beginning 0) (match-end 0)))
4784 ;; List item
4785 ((setq val (markdown-cur-list-item-bounds))
4786 (kill-new (delete-and-extract-region (cl-first val) (cl-second val))))
4788 (user-error "Nothing found at point to kill")))))
4791 ;;; Indentation ====================================================================
4793 (defun markdown-indent-find-next-position (cur-pos positions)
4794 "Return the position after the index of CUR-POS in POSITIONS.
4795 Positions are calculated by `markdown-calc-indents'."
4796 (while (and positions
4797 (not (equal cur-pos (car positions))))
4798 (setq positions (cdr positions)))
4799 (or (cadr positions) 0))
4801 (define-obsolete-function-alias 'markdown-exdent-find-next-position
4802 'markdown-outdent-find-next-position "v2.3")
4804 (defun markdown-outdent-find-next-position (cur-pos positions)
4805 "Return the maximal element that precedes CUR-POS from POSITIONS.
4806 Positions are calculated by `markdown-calc-indents'."
4807 (let ((result 0))
4808 (dolist (i positions)
4809 (when (< i cur-pos)
4810 (setq result (max result i))))
4811 result))
4813 (defun markdown-indent-line ()
4814 "Indent the current line using some heuristics.
4815 If the _previous_ command was either `markdown-enter-key' or
4816 `markdown-cycle', then we should cycle to the next
4817 reasonable indentation position. Otherwise, we could have been
4818 called directly by `markdown-enter-key', by an initial call of
4819 `markdown-cycle', or indirectly by `auto-fill-mode'. In
4820 these cases, indent to the default position.
4821 Positions are calculated by `markdown-calc-indents'."
4822 (interactive)
4823 (let ((positions (markdown-calc-indents))
4824 (point-pos (current-column))
4825 (_ (back-to-indentation))
4826 (cur-pos (current-column)))
4827 (if (not (equal this-command 'markdown-cycle))
4828 (indent-line-to (car positions))
4829 (setq positions (sort (delete-dups positions) '<))
4830 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions))
4831 (new-point-pos (max (+ point-pos (- next-pos cur-pos)) 0)))
4832 (indent-line-to next-pos)
4833 (move-to-column new-point-pos)))))
4835 (defun markdown-calc-indents ()
4836 "Return a list of indentation columns to cycle through.
4837 The first element in the returned list should be considered the
4838 default indentation level. This function does not worry about
4839 duplicate positions, which are handled up by calling functions."
4840 (let (pos prev-line-pos positions)
4842 ;; Indentation of previous line
4843 (setq prev-line-pos (markdown-prev-line-indent))
4844 (setq positions (cons prev-line-pos positions))
4846 ;; Indentation of previous non-list-marker text
4847 (when (setq pos (save-excursion
4848 (forward-line -1)
4849 (when (looking-at markdown-regex-list)
4850 (- (match-end 3) (match-beginning 0)))))
4851 (setq positions (cons pos positions)))
4853 ;; Indentation required for a pre block in current context
4854 (setq pos (length (markdown-pre-indentation (point))))
4855 (setq positions (cons pos positions))
4857 ;; Indentation of the previous line + tab-width
4858 (if prev-line-pos
4859 (setq positions (cons (+ prev-line-pos tab-width) positions))
4860 (setq positions (cons tab-width positions)))
4862 ;; Indentation of the previous line - tab-width
4863 (if (and prev-line-pos (> prev-line-pos tab-width))
4864 (setq positions (cons (- prev-line-pos tab-width) positions)))
4866 ;; Indentation of all preceeding list markers (when in a list)
4867 (when (setq pos (markdown-calculate-list-levels))
4868 (setq positions (append pos positions)))
4870 ;; First column
4871 (setq positions (cons 0 positions))
4873 ;; Return reversed list
4874 (reverse positions)))
4876 (defun markdown-enter-key ()
4877 "Handle RET depending on the context.
4878 If the point is at a table, move to the next row. Otherwise,
4879 indent according to value of `markdown-indent-on-enter'.
4880 When it is nil, simply call `newline'. Otherwise, indent the next line
4881 following RET using `markdown-indent-line'. Furthermore, when it
4882 is set to 'indent-and-new-item and the point is in a list item,
4883 start a new item with the same indentation. If the point is in an
4884 empty list item, remove it (so that pressing RET twice when in a
4885 list simply adds a blank line)."
4886 (interactive)
4887 (cond
4888 ;; Table
4889 ((markdown-table-at-point-p)
4890 (call-interactively #'markdown-table-next-row))
4891 ;; Indent non-table text
4892 (markdown-indent-on-enter
4893 (let (bounds)
4894 (if (and (memq markdown-indent-on-enter '(indent-and-new-item))
4895 (setq bounds (markdown-cur-list-item-bounds)))
4896 (let ((beg (cl-first bounds))
4897 (end (cl-second bounds))
4898 (length (cl-fourth bounds)))
4899 ;; Point is in a list item
4900 (if (= (- end beg) length)
4901 ;; Delete blank list
4902 (progn
4903 (delete-region beg end)
4904 (newline)
4905 (markdown-indent-line))
4906 (call-interactively #'markdown-insert-list-item)))
4907 ;; Point is not in a list
4908 (newline)
4909 (markdown-indent-line))))
4910 ;; Insert a raw newline
4911 (t (newline))))
4913 (define-obsolete-function-alias 'markdown-exdent-or-delete
4914 'markdown-outdent-or-delete "v2.3")
4916 (defun markdown-outdent-or-delete (arg)
4917 "Handle BACKSPACE by cycling through indentation points.
4918 When BACKSPACE is pressed, if there is only whitespace
4919 before the current point, then outdent the line one level.
4920 Otherwise, do normal delete by repeating
4921 `backward-delete-char-untabify' ARG times."
4922 (interactive "*p")
4923 (if (use-region-p)
4924 (backward-delete-char-untabify arg)
4925 (let ((cur-pos (current-column))
4926 (start-of-indention (save-excursion
4927 (back-to-indentation)
4928 (current-column)))
4929 (positions (markdown-calc-indents)))
4930 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
4931 (indent-line-to (markdown-outdent-find-next-position cur-pos positions))
4932 (backward-delete-char-untabify arg)))))
4934 (defun markdown-find-leftmost-column (beg end)
4935 "Find the leftmost column in the region from BEG to END."
4936 (let ((mincol 1000))
4937 (save-excursion
4938 (goto-char beg)
4939 (while (< (point) end)
4940 (back-to-indentation)
4941 (unless (looking-at-p "[ \t]*$")
4942 (setq mincol (min mincol (current-column))))
4943 (forward-line 1)
4945 mincol))
4947 (defun markdown-indent-region (beg end arg)
4948 "Indent the region from BEG to END using some heuristics.
4949 When ARG is non-nil, outdent the region instead.
4950 See `markdown-indent-line' and `markdown-indent-line'."
4951 (interactive "*r\nP")
4952 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
4953 (leftmostcol (markdown-find-leftmost-column beg end))
4954 (next-pos (if arg
4955 (markdown-outdent-find-next-position leftmostcol positions)
4956 (markdown-indent-find-next-position leftmostcol positions))))
4957 (indent-rigidly beg end (- next-pos leftmostcol))
4958 (setq deactivate-mark nil)))
4960 (define-obsolete-function-alias 'markdown-exdent-region
4961 'markdown-outdent-region "v2.3")
4963 (defun markdown-outdent-region (beg end)
4964 "Call `markdown-indent-region' on region from BEG to END with prefix."
4965 (interactive "*r")
4966 (markdown-indent-region beg end t))
4969 ;;; Markup Completion =========================================================
4971 (defconst markdown-complete-alist
4972 '((markdown-regex-header-atx . markdown-complete-atx)
4973 (markdown-regex-header-setext . markdown-complete-setext)
4974 (markdown-regex-hr . markdown-complete-hr))
4975 "Association list of form (regexp . function) for markup completion.")
4977 (defun markdown-incomplete-atx-p ()
4978 "Return t if ATX header markup is incomplete and nil otherwise.
4979 Assumes match data is available for `markdown-regex-header-atx'.
4980 Checks that the number of trailing hash marks equals the number of leading
4981 hash marks, that there is only a single space before and after the text,
4982 and that there is no extraneous whitespace in the text."
4984 ;; Number of starting and ending hash marks differs
4985 (not (= (length (match-string 1)) (length (match-string 3))))
4986 ;; When the header text is not empty...
4987 (and (> (length (match-string 2)) 0)
4988 ;; ...if there are extra leading, trailing, or interior spaces
4989 (or (not (= (match-beginning 2) (1+ (match-end 1))))
4990 (not (= (match-beginning 3) (1+ (match-end 2))))
4991 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
4992 ;; When the header text is empty...
4993 (and (= (length (match-string 2)) 0)
4994 ;; ...if there are too many or too few spaces
4995 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
4997 (defun markdown-complete-atx ()
4998 "Complete and normalize ATX headers.
4999 Add or remove hash marks to the end of the header to match the
5000 beginning. Ensure that there is only a single space between hash
5001 marks and header text. Removes extraneous whitespace from header text.
5002 Assumes match data is available for `markdown-regex-header-atx'.
5003 Return nil if markup was complete and non-nil if markup was completed."
5004 (when (markdown-incomplete-atx-p)
5005 (let* ((new-marker (make-marker))
5006 (new-marker (set-marker new-marker (match-end 2))))
5007 ;; Hash marks and spacing at end
5008 (goto-char (match-end 2))
5009 (delete-region (match-end 2) (match-end 3))
5010 (insert " " (match-string 1))
5011 ;; Remove extraneous whitespace from title
5012 (replace-match (markdown-compress-whitespace-string (match-string 2))
5013 t t nil 2)
5014 ;; Spacing at beginning
5015 (goto-char (match-end 1))
5016 (delete-region (match-end 1) (match-beginning 2))
5017 (insert " ")
5018 ;; Leave point at end of text
5019 (goto-char new-marker))))
5021 (defun markdown-incomplete-setext-p ()
5022 "Return t if setext header markup is incomplete and nil otherwise.
5023 Assumes match data is available for `markdown-regex-header-setext'.
5024 Checks that length of underline matches text and that there is no
5025 extraneous whitespace in the text."
5026 (or (not (= (length (match-string 1)) (length (match-string 2))))
5027 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
5029 (defun markdown-complete-setext ()
5030 "Complete and normalize setext headers.
5031 Add or remove underline characters to match length of header
5032 text. Removes extraneous whitespace from header text. Assumes
5033 match data is available for `markdown-regex-header-setext'.
5034 Return nil if markup was complete and non-nil if markup was completed."
5035 (when (markdown-incomplete-setext-p)
5036 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
5037 (char (char-after (match-beginning 2)))
5038 (level (if (char-equal char ?-) 2 1)))
5039 (goto-char (match-beginning 0))
5040 (delete-region (match-beginning 0) (match-end 0))
5041 (markdown-insert-header level text t)
5042 t)))
5044 (defun markdown-incomplete-hr-p ()
5045 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
5046 Assumes match data is available for `markdown-regex-hr'."
5047 (not (member (match-string 0) markdown-hr-strings)))
5049 (defun markdown-complete-hr ()
5050 "Complete horizontal rules.
5051 If horizontal rule string is a member of `markdown-hr-strings',
5052 do nothing. Otherwise, replace with the car of
5053 `markdown-hr-strings'.
5054 Assumes match data is available for `markdown-regex-hr'.
5055 Return nil if markup was complete and non-nil if markup was completed."
5056 (when (markdown-incomplete-hr-p)
5057 (replace-match (car markdown-hr-strings))
5060 (defun markdown-complete ()
5061 "Complete markup of object near point or in region when active.
5062 Handle all objects in `markdown-complete-alist', in order.
5063 See `markdown-complete-at-point' and `markdown-complete-region'."
5064 (interactive "*")
5065 (if (markdown-use-region-p)
5066 (markdown-complete-region (region-beginning) (region-end))
5067 (markdown-complete-at-point)))
5069 (defun markdown-complete-at-point ()
5070 "Complete markup of object near point.
5071 Handle all elements of `markdown-complete-alist' in order."
5072 (interactive "*")
5073 (let ((list markdown-complete-alist) found changed)
5074 (while list
5075 (let ((regexp (eval (caar list)))
5076 (function (cdar list)))
5077 (setq list (cdr list))
5078 (when (thing-at-point-looking-at regexp)
5079 (setq found t)
5080 (setq changed (funcall function))
5081 (setq list nil))))
5082 (if found
5083 (or changed (user-error "Markup at point is complete"))
5084 (user-error "Nothing to complete at point"))))
5086 (defun markdown-complete-region (beg end)
5087 "Complete markup of objects in region from BEG to END.
5088 Handle all objects in `markdown-complete-alist', in order. Each
5089 match is checked to ensure that a previous regexp does not also
5090 match."
5091 (interactive "*r")
5092 (let ((end-marker (set-marker (make-marker) end))
5093 previous)
5094 (dolist (element markdown-complete-alist)
5095 (let ((regexp (eval (car element)))
5096 (function (cdr element)))
5097 (goto-char beg)
5098 (while (re-search-forward regexp end-marker 'limit)
5099 (when (match-string 0)
5100 ;; Make sure this is not a match for any of the preceding regexps.
5101 ;; This prevents mistaking an HR for a Setext subheading.
5102 (let (match)
5103 (save-match-data
5104 (dolist (prev-regexp previous)
5105 (or match (setq match (looking-back prev-regexp nil)))))
5106 (unless match
5107 (save-excursion (funcall function))))))
5108 (cl-pushnew regexp previous :test #'equal)))
5109 previous))
5111 (defun markdown-complete-buffer ()
5112 "Complete markup for all objects in the current buffer."
5113 (interactive "*")
5114 (markdown-complete-region (point-min) (point-max)))
5117 ;;; Markup Cycling ============================================================
5119 (defun markdown-cycle-atx (arg &optional remove)
5120 "Cycle ATX header markup.
5121 Promote header (decrease level) when ARG is 1 and demote
5122 header (increase level) if arg is -1. When REMOVE is non-nil,
5123 remove the header when the level reaches zero and stop cycling
5124 when it reaches six. Otherwise, perform a proper cycling through
5125 levels one through six. Assumes match data is available for
5126 `markdown-regex-header-atx'."
5127 (let* ((old-level (length (match-string 1)))
5128 (new-level (+ old-level arg))
5129 (text (match-string 2)))
5130 (when (not remove)
5131 (setq new-level (% new-level 6))
5132 (setq new-level (cond ((= new-level 0) 6)
5133 ((< new-level 0) (+ new-level 6))
5134 (t new-level))))
5135 (cond
5136 ((= new-level 0)
5137 (markdown-unwrap-thing-at-point nil 0 2))
5138 ((<= new-level 6)
5139 (goto-char (match-beginning 0))
5140 (delete-region (match-beginning 0) (match-end 0))
5141 (markdown-insert-header new-level text nil)))))
5143 (defun markdown-cycle-setext (arg &optional remove)
5144 "Cycle setext header markup.
5145 Promote header (increase level) when ARG is 1 and demote
5146 header (decrease level or remove) if arg is -1. When demoting a
5147 level-two setext header, replace with a level-three atx header.
5148 When REMOVE is non-nil, remove the header when the level reaches
5149 zero. Otherwise, cycle back to a level six atx header. Assumes
5150 match data is available for `markdown-regex-header-setext'."
5151 (let* ((char (char-after (match-beginning 2)))
5152 (old-level (if (char-equal char ?=) 1 2))
5153 (new-level (+ old-level arg)))
5154 (when (and (not remove) (= new-level 0))
5155 (setq new-level 6))
5156 (cond
5157 ((= new-level 0)
5158 (markdown-unwrap-thing-at-point nil 0 1))
5159 ((<= new-level 2)
5160 (markdown-insert-header new-level nil t))
5161 ((<= new-level 6)
5162 (markdown-insert-header new-level nil nil)))))
5164 (defun markdown-cycle-hr (arg &optional remove)
5165 "Cycle string used for horizontal rule from `markdown-hr-strings'.
5166 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
5167 backwards (promote). When REMOVE is non-nil, remove the hr instead
5168 of cycling when the end of the list is reached.
5169 Assumes match data is available for `markdown-regex-hr'."
5170 (let* ((strings (if (= arg -1)
5171 (reverse markdown-hr-strings)
5172 markdown-hr-strings))
5173 (tail (member (match-string 0) strings))
5174 (new (or (cadr tail)
5175 (if remove
5176 (if (= arg 1)
5178 (car tail))
5179 (car strings)))))
5180 (replace-match new)))
5182 (defun markdown-cycle-bold ()
5183 "Cycle bold markup between underscores and asterisks.
5184 Assumes match data is available for `markdown-regex-bold'."
5185 (save-excursion
5186 (let* ((old-delim (match-string 3))
5187 (new-delim (if (string-equal old-delim "**") "__" "**")))
5188 (replace-match new-delim t t nil 3)
5189 (replace-match new-delim t t nil 5))))
5191 (defun markdown-cycle-italic ()
5192 "Cycle italic markup between underscores and asterisks.
5193 Assumes match data is available for `markdown-regex-italic'."
5194 (save-excursion
5195 (let* ((old-delim (match-string 2))
5196 (new-delim (if (string-equal old-delim "*") "_" "*")))
5197 (replace-match new-delim t t nil 2)
5198 (replace-match new-delim t t nil 4))))
5201 ;;; Keymap ====================================================================
5203 (defun markdown--style-map-prompt ()
5204 "Return a formatted prompt for Markdown markup insertion."
5205 (when markdown-enable-prefix-prompts
5206 (concat
5207 "Markdown: "
5208 (propertize "bold" 'face 'markdown-bold-face) ", "
5209 (propertize "italic" 'face 'markdown-italic-face) ", "
5210 (propertize "code" 'face 'markdown-inline-code-face) ", "
5211 (propertize "C = GFM code" 'face 'markdown-code-face) ", "
5212 (propertize "pre" 'face 'markdown-pre-face) ", "
5213 (propertize "footnote" 'face 'markdown-footnote-text-face) ", "
5214 (propertize "q = blockquote" 'face 'markdown-blockquote-face) ", "
5215 (propertize "h & 1-6 = heading" 'face 'markdown-header-face) ", "
5216 (propertize "- = hr" 'face 'markdown-hr-face) ", "
5217 "C-h = more")))
5219 (defun markdown--command-map-prompt ()
5220 "Return prompt for Markdown buffer-wide commands."
5221 (when markdown-enable-prefix-prompts
5222 (concat
5223 "Command: "
5224 (propertize "m" 'face 'markdown-bold-face) "arkdown, "
5225 (propertize "p" 'face 'markdown-bold-face) "review, "
5226 (propertize "o" 'face 'markdown-bold-face) "pen, "
5227 (propertize "e" 'face 'markdown-bold-face) "xport, "
5228 "export & pre" (propertize "v" 'face 'markdown-bold-face) "iew, "
5229 (propertize "c" 'face 'markdown-bold-face) "heck refs, "
5230 "C-h = more")))
5232 (defvar markdown-mode-style-map
5233 (let ((map (make-keymap (markdown--style-map-prompt))))
5234 (define-key map (kbd "1") 'markdown-insert-header-atx-1)
5235 (define-key map (kbd "2") 'markdown-insert-header-atx-2)
5236 (define-key map (kbd "3") 'markdown-insert-header-atx-3)
5237 (define-key map (kbd "4") 'markdown-insert-header-atx-4)
5238 (define-key map (kbd "5") 'markdown-insert-header-atx-5)
5239 (define-key map (kbd "6") 'markdown-insert-header-atx-6)
5240 (define-key map (kbd "!") 'markdown-insert-header-setext-1)
5241 (define-key map (kbd "@") 'markdown-insert-header-setext-2)
5242 (define-key map (kbd "b") 'markdown-insert-bold)
5243 (define-key map (kbd "c") 'markdown-insert-code)
5244 (define-key map (kbd "C") 'markdown-insert-gfm-code-block)
5245 (define-key map (kbd "f") 'markdown-insert-footnote)
5246 (define-key map (kbd "h") 'markdown-insert-header-dwim)
5247 (define-key map (kbd "H") 'markdown-insert-header-setext-dwim)
5248 (define-key map (kbd "i") 'markdown-insert-italic)
5249 (define-key map (kbd "k") 'markdown-insert-kbd)
5250 (define-key map (kbd "l") 'markdown-insert-link)
5251 (define-key map (kbd "p") 'markdown-insert-pre)
5252 (define-key map (kbd "P") 'markdown-pre-region)
5253 (define-key map (kbd "q") 'markdown-insert-blockquote)
5254 (define-key map (kbd "s") 'markdown-insert-strike-through)
5255 (define-key map (kbd "Q") 'markdown-blockquote-region)
5256 (define-key map (kbd "w") 'markdown-insert-wiki-link)
5257 (define-key map (kbd "-") 'markdown-insert-hr)
5258 (define-key map (kbd "[") 'markdown-insert-gfm-checkbox)
5259 ;; Deprecated keys that may be removed in a future version
5260 (define-key map (kbd "e") 'markdown-insert-italic)
5261 map)
5262 "Keymap for Markdown text styling commands.")
5264 (defvar markdown-mode-command-map
5265 (let ((map (make-keymap (markdown--command-map-prompt))))
5266 (define-key map (kbd "m") 'markdown-other-window)
5267 (define-key map (kbd "p") 'markdown-preview)
5268 (define-key map (kbd "e") 'markdown-export)
5269 (define-key map (kbd "v") 'markdown-export-and-preview)
5270 (define-key map (kbd "o") 'markdown-open)
5271 (define-key map (kbd "l") 'markdown-live-preview-mode)
5272 (define-key map (kbd "w") 'markdown-kill-ring-save)
5273 (define-key map (kbd "c") 'markdown-check-refs)
5274 (define-key map (kbd "n") 'markdown-cleanup-list-numbers)
5275 (define-key map (kbd "]") 'markdown-complete-buffer)
5276 (define-key map (kbd "^") 'markdown-table-sort-lines)
5277 (define-key map (kbd "|") 'markdown-table-convert-region)
5278 (define-key map (kbd "t") 'markdown-table-transpose)
5279 map)
5280 "Keymap for Markdown buffer-wide commands.")
5282 (defvar markdown-mode-map
5283 (let ((map (make-keymap)))
5284 ;; Markup insertion & removal
5285 (define-key map (kbd "C-c C-s") markdown-mode-style-map)
5286 (define-key map (kbd "C-c C-l") 'markdown-insert-link)
5287 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
5288 ;; Promotion, demotion, and cycling
5289 (define-key map (kbd "C-c C--") 'markdown-promote)
5290 (define-key map (kbd "C-c C-=") 'markdown-demote)
5291 (define-key map (kbd "C-c C-]") 'markdown-complete)
5292 ;; Following and doing things
5293 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
5294 (define-key map (kbd "C-c C-d") 'markdown-do)
5295 (define-key map (kbd "C-c '") 'markdown-edit-code-block)
5296 ;; Indentation
5297 (define-key map (kbd "C-m") 'markdown-enter-key)
5298 (define-key map (kbd "DEL") 'markdown-outdent-or-delete)
5299 (define-key map (kbd "C-c >") 'markdown-indent-region)
5300 (define-key map (kbd "C-c <") 'markdown-outdent-region)
5301 ;; Visibility cycling
5302 (define-key map (kbd "TAB") 'markdown-cycle)
5303 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
5304 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
5305 (define-key map (kbd "<backtab>") 'markdown-shifttab)
5306 ;; Heading and list navigation
5307 (define-key map (kbd "C-c C-n") 'markdown-outline-next)
5308 (define-key map (kbd "C-c C-p") 'markdown-outline-previous)
5309 (define-key map (kbd "C-c C-f") 'markdown-outline-next-same-level)
5310 (define-key map (kbd "C-c C-b") 'markdown-outline-previous-same-level)
5311 (define-key map (kbd "C-c C-u") 'markdown-outline-up)
5312 ;; Buffer-wide commands
5313 (define-key map (kbd "C-c C-c") markdown-mode-command-map)
5314 ;; Subtree, list, and table editing
5315 (define-key map (kbd "C-c <up>") 'markdown-move-up)
5316 (define-key map (kbd "C-c <down>") 'markdown-move-down)
5317 (define-key map (kbd "C-c <left>") 'markdown-promote)
5318 (define-key map (kbd "C-c <right>") 'markdown-demote)
5319 (define-key map (kbd "C-c S-<up>") 'markdown-table-delete-row)
5320 (define-key map (kbd "C-c S-<down>") 'markdown-table-insert-row)
5321 (define-key map (kbd "C-c S-<left>") 'markdown-table-delete-column)
5322 (define-key map (kbd "C-c S-<right>") 'markdown-table-insert-column)
5323 (define-key map (kbd "C-c C-M-h") 'markdown-mark-subtree)
5324 (define-key map (kbd "C-x n s") 'markdown-narrow-to-subtree)
5325 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
5326 (define-key map (kbd "C-c C-j") 'markdown-insert-list-item)
5327 ;; Paragraphs (Markdown context aware)
5328 (define-key map [remap backward-paragraph] 'markdown-backward-paragraph)
5329 (define-key map [remap forward-paragraph] 'markdown-forward-paragraph)
5330 (define-key map [remap mark-paragraph] 'markdown-mark-paragraph)
5331 ;; Blocks (one or more paragraphs)
5332 (define-key map (kbd "C-M-{") 'markdown-backward-block)
5333 (define-key map (kbd "C-M-}") 'markdown-forward-block)
5334 (define-key map (kbd "C-c M-h") 'markdown-mark-block)
5335 (define-key map (kbd "C-x n b") 'markdown-narrow-to-block)
5336 ;; Pages (top-level sections)
5337 (define-key map [remap backward-page] 'markdown-backward-page)
5338 (define-key map [remap forward-page] 'markdown-forward-page)
5339 (define-key map [remap mark-page] 'markdown-mark-page)
5340 (define-key map [remap narrow-to-page] 'markdown-narrow-to-page)
5341 ;; Link Movement
5342 (define-key map (kbd "M-n") 'markdown-next-link)
5343 (define-key map (kbd "M-p") 'markdown-previous-link)
5344 ;; Toggling functionality
5345 (define-key map (kbd "C-c C-x C-e") 'markdown-toggle-math)
5346 (define-key map (kbd "C-c C-x C-f") 'markdown-toggle-fontify-code-blocks-natively)
5347 (define-key map (kbd "C-c C-x C-i") 'markdown-toggle-inline-images)
5348 (define-key map (kbd "C-c C-x C-l") 'markdown-toggle-url-hiding)
5349 (define-key map (kbd "C-c C-x C-m") 'markdown-toggle-markup-hiding)
5350 ;; Alternative keys (in case of problems with the arrow keys)
5351 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
5352 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
5353 (define-key map (kbd "C-c C-x l") 'markdown-promote)
5354 (define-key map (kbd "C-c C-x r") 'markdown-demote)
5355 ;; Deprecated keys that may be removed in a future version
5356 (define-key map (kbd "C-c C-a L") 'markdown-insert-link) ;; C-c C-l
5357 (define-key map (kbd "C-c C-a l") 'markdown-insert-link) ;; C-c C-l
5358 (define-key map (kbd "C-c C-a r") 'markdown-insert-link) ;; C-c C-l
5359 (define-key map (kbd "C-c C-a u") 'markdown-insert-uri) ;; C-c C-l
5360 (define-key map (kbd "C-c C-a f") 'markdown-insert-footnote)
5361 (define-key map (kbd "C-c C-a w") 'markdown-insert-wiki-link)
5362 (define-key map (kbd "C-c C-t 1") 'markdown-insert-header-atx-1)
5363 (define-key map (kbd "C-c C-t 2") 'markdown-insert-header-atx-2)
5364 (define-key map (kbd "C-c C-t 3") 'markdown-insert-header-atx-3)
5365 (define-key map (kbd "C-c C-t 4") 'markdown-insert-header-atx-4)
5366 (define-key map (kbd "C-c C-t 5") 'markdown-insert-header-atx-5)
5367 (define-key map (kbd "C-c C-t 6") 'markdown-insert-header-atx-6)
5368 (define-key map (kbd "C-c C-t !") 'markdown-insert-header-setext-1)
5369 (define-key map (kbd "C-c C-t @") 'markdown-insert-header-setext-2)
5370 (define-key map (kbd "C-c C-t h") 'markdown-insert-header-dwim)
5371 (define-key map (kbd "C-c C-t H") 'markdown-insert-header-setext-dwim)
5372 (define-key map (kbd "C-c C-t s") 'markdown-insert-header-setext-2)
5373 (define-key map (kbd "C-c C-t t") 'markdown-insert-header-setext-1)
5374 (define-key map (kbd "C-c C-i") 'markdown-insert-image)
5375 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item) ;; C-c C-j
5376 (define-key map (kbd "C-c C-x C-x") 'markdown-toggle-gfm-checkbox) ;; C-c C-d
5377 (define-key map (kbd "C-c -") 'markdown-insert-hr)
5378 map)
5379 "Keymap for Markdown major mode.")
5381 (defvar markdown-mode-mouse-map
5382 (let ((map (make-sparse-keymap)))
5383 (define-key map [follow-link] 'mouse-face)
5384 (define-key map [mouse-2] 'markdown-follow-link-at-point)
5385 map)
5386 "Keymap for following links with mouse.")
5388 (defvar gfm-mode-map
5389 (let ((map (make-sparse-keymap)))
5390 (set-keymap-parent map markdown-mode-map)
5391 (define-key map (kbd "C-c C-s d") 'markdown-insert-strike-through)
5392 (define-key map "`" 'markdown-electric-backquote)
5393 map)
5394 "Keymap for `gfm-mode'.
5395 See also `markdown-mode-map'.")
5398 ;;; Menu ==================================================================
5400 (easy-menu-define markdown-mode-menu markdown-mode-map
5401 "Menu for Markdown mode"
5402 '("Markdown"
5403 "---"
5404 ("Movement"
5405 ["Jump" markdown-do]
5406 ["Follow Link" markdown-follow-thing-at-point]
5407 ["Next Link" markdown-next-link]
5408 ["Previous Link" markdown-previous-link]
5409 "---"
5410 ["Next Heading or List Item" markdown-outline-next]
5411 ["Previous Heading or List Item" markdown-outline-previous]
5412 ["Next at Same Level" markdown-outline-next-same-level]
5413 ["Previous at Same Level" markdown-outline-previous-same-level]
5414 ["Up to Parent" markdown-outline-up]
5415 "---"
5416 ["Forward Paragraph" markdown-forward-paragraph]
5417 ["Backward Paragraph" markdown-backward-paragraph]
5418 ["Forward Block" markdown-forward-block]
5419 ["Backward Block" markdown-backward-block])
5420 ("Show & Hide"
5421 ["Cycle Heading Visibility" markdown-cycle (markdown-on-heading-p)]
5422 ["Cycle Heading Visibility (Global)" markdown-shifttab]
5423 "---"
5424 ["Narrow to Region" narrow-to-region]
5425 ["Narrow to Block" markdown-narrow-to-block]
5426 ["Narrow to Section" narrow-to-defun]
5427 ["Narrow to Subtree" markdown-narrow-to-subtree]
5428 ["Widen" widen (buffer-narrowed-p)]
5429 "---"
5430 ["Toggle Markup Hiding" markdown-toggle-markup-hiding
5431 :keys "C-c C-x C-m"
5432 :style radio
5433 :selected markdown-hide-markup])
5434 "---"
5435 ("Headings & Structure"
5436 ["Automatic Heading" markdown-insert-header-dwim :keys "C-c C-s h"]
5437 ["Automatic Heading (Setext)" markdown-insert-header-setext-dwim :keys "C-c C-s H"]
5438 ("Specific Heading (atx)"
5439 ["First Level atx" markdown-insert-header-atx-1 :keys "C-c C-s 1"]
5440 ["Second Level atx" markdown-insert-header-atx-2 :keys "C-c C-s 2"]
5441 ["Third Level atx" markdown-insert-header-atx-3 :keys "C-c C-s 3"]
5442 ["Fourth Level atx" markdown-insert-header-atx-4 :keys "C-c C-s 4"]
5443 ["Fifth Level atx" markdown-insert-header-atx-5 :keys "C-c C-s 5"]
5444 ["Sixth Level atx" markdown-insert-header-atx-6 :keys "C-c C-s 6"])
5445 ("Specific Heading (Setext)"
5446 ["First Level Setext" markdown-insert-header-setext-1 :keys "C-c C-s !"]
5447 ["Second Level Setext" markdown-insert-header-setext-2 :keys "C-c C-s @"])
5448 ["Horizontal Rule" markdown-insert-hr :keys "C-c C-s -"]
5449 "---"
5450 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
5451 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
5452 ["Promote Subtree" markdown-promote :keys "C-c <left>"]
5453 ["Demote Subtree" markdown-demote :keys "C-c <right>"])
5454 ("Region & Mark"
5455 ["Indent Region" markdown-indent-region]
5456 ["Outdent Region" markdown-outdent-region]
5457 "--"
5458 ["Mark Paragraph" mark-paragraph]
5459 ["Mark Block" markdown-mark-block]
5460 ["Mark Section" mark-defun]
5461 ["Mark Subtree" markdown-mark-subtree])
5462 ("Lists"
5463 ["Insert List Item" markdown-insert-list-item]
5464 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
5465 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
5466 ["Indent Subtree" markdown-demote :keys "C-c <right>"]
5467 ["Outdent Subtree" markdown-promote :keys "C-c <left>"]
5468 ["Renumber List" markdown-cleanup-list-numbers]
5469 ["Insert Task List Item" markdown-insert-gfm-checkbox :keys "C-c C-x ["]
5470 ["Toggle Task List Item" markdown-toggle-gfm-checkbox (markdown-gfm-task-list-item-at-point) :keys "C-c C-d"])
5471 ("Links & Images"
5472 ["Insert Link" markdown-insert-link]
5473 ["Insert Image" markdown-insert-image]
5474 ["Insert Footnote" markdown-insert-footnote :keys "C-c C-s f"]
5475 ["Insert Wiki Link" markdown-insert-wiki-link :keys "C-c C-s w"]
5476 "---"
5477 ["Check References" markdown-check-refs]
5478 ["Toggle URL Hiding" markdown-toggle-url-hiding
5479 :style radio
5480 :selected markdown-hide-urls]
5481 ["Toggle Inline Images" markdown-toggle-inline-images
5482 :keys "C-c C-x C-i"
5483 :style radio
5484 :selected markdown-inline-image-overlays]
5485 ["Toggle Wiki Links" markdown-toggle-wiki-links
5486 :style radio
5487 :selected markdown-enable-wiki-links])
5488 ("Styles"
5489 ["Bold" markdown-insert-bold]
5490 ["Italic" markdown-insert-italic]
5491 ["Code" markdown-insert-code]
5492 ["Strikethrough" markdown-insert-strike-through]
5493 ["Keyboard" markdown-insert-kbd]
5494 "---"
5495 ["Blockquote" markdown-insert-blockquote]
5496 ["Preformatted" markdown-insert-pre]
5497 ["GFM Code Block" markdown-insert-gfm-code-block]
5498 ["Edit Code Block" markdown-edit-code-block (markdown-code-block-at-point-p)]
5499 "---"
5500 ["Blockquote Region" markdown-blockquote-region]
5501 ["Preformatted Region" markdown-pre-region]
5502 "---"
5503 ["Fontify Code Blocks Natively" markdown-toggle-fontify-code-blocks-natively
5504 :style radio
5505 :selected markdown-fontify-code-blocks-natively]
5506 ["LaTeX Math Support" markdown-toggle-math
5507 :style radio
5508 :selected markdown-enable-math])
5509 "---"
5510 ("Preview & Export"
5511 ["Compile" markdown-other-window]
5512 ["Preview" markdown-preview]
5513 ["Export" markdown-export]
5514 ["Export & View" markdown-export-and-preview]
5515 ["Open" markdown-open]
5516 ["Live Export" markdown-live-preview-mode
5517 :style radio
5518 :selected markdown-live-preview-mode]
5519 ["Kill ring save" markdown-kill-ring-save])
5520 ("Markup Completion and Cycling"
5521 ["Complete Markup" markdown-complete]
5522 ["Promote Element" markdown-promote :keys "C-c C--"]
5523 ["Demote Element" markdown-demote :keys "C-c C-="])
5524 "---"
5525 ["Kill Element" markdown-kill-thing-at-point]
5526 "---"
5527 ("Documentation"
5528 ["Version" markdown-show-version]
5529 ["Homepage" markdown-mode-info]
5530 ["Describe Mode" (describe-function 'markdown-mode)]
5531 ["Guide" (browse-url "https://leanpub.com/markdown-mode")])))
5534 ;;; imenu =====================================================================
5536 (defun markdown-imenu-create-nested-index ()
5537 "Create and return a nested imenu index alist for the current buffer.
5538 See `imenu-create-index-function' and `imenu--index-alist' for details."
5539 (let* ((root '(nil . nil))
5540 cur-alist
5541 (cur-level 0)
5542 (empty-heading "-")
5543 (self-heading ".")
5544 hashes pos level heading)
5545 (save-excursion
5546 (goto-char (point-min))
5547 (while (re-search-forward markdown-regex-header (point-max) t)
5548 (unless (markdown-code-block-at-point-p)
5549 (cond
5550 ((match-string-no-properties 2) ;; level 1 setext
5551 (setq heading (match-string-no-properties 1))
5552 (setq pos (match-beginning 1)
5553 level 1))
5554 ((match-string-no-properties 3) ;; level 2 setext
5555 (setq heading (match-string-no-properties 1))
5556 (setq pos (match-beginning 1)
5557 level 2))
5558 ((setq hashes (markdown-trim-whitespace
5559 (match-string-no-properties 4)))
5560 (setq heading (match-string-no-properties 5)
5561 pos (match-beginning 4)
5562 level (length hashes))))
5563 (let ((alist (list (cons heading pos))))
5564 (cond
5565 ((= cur-level level) ; new sibling
5566 (setcdr cur-alist alist)
5567 (setq cur-alist alist))
5568 ((< cur-level level) ; first child
5569 (dotimes (_ (- level cur-level 1))
5570 (setq alist (list (cons empty-heading alist))))
5571 (if cur-alist
5572 (let* ((parent (car cur-alist))
5573 (self-pos (cdr parent)))
5574 (setcdr parent (cons (cons self-heading self-pos) alist)))
5575 (setcdr root alist)) ; primogenitor
5576 (setq cur-alist alist)
5577 (setq cur-level level))
5578 (t ; new sibling of an ancestor
5579 (let ((sibling-alist (last (cdr root))))
5580 (dotimes (_ (1- level))
5581 (setq sibling-alist (last (cdar sibling-alist))))
5582 (setcdr sibling-alist alist)
5583 (setq cur-alist alist))
5584 (setq cur-level level))))))
5585 (cdr root))))
5587 (defun markdown-imenu-create-flat-index ()
5588 "Create and return a flat imenu index alist for the current buffer.
5589 See `imenu-create-index-function' and `imenu--index-alist' for details."
5590 (let* ((empty-heading "-") index heading pos)
5591 (save-excursion
5592 (goto-char (point-min))
5593 (while (re-search-forward markdown-regex-header (point-max) t)
5594 (when (and (not (markdown-code-block-at-point-p))
5595 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin)))
5596 (cond
5597 ((setq heading (match-string-no-properties 1))
5598 (setq pos (match-beginning 1)))
5599 ((setq heading (match-string-no-properties 5))
5600 (setq pos (match-beginning 4))))
5601 (or (> (length heading) 0)
5602 (setq heading empty-heading))
5603 (setq index (append index (list (cons heading pos))))))
5604 index)))
5607 ;;; References ================================================================
5609 (defun markdown-reference-goto-definition ()
5610 "Jump to the definition of the reference at point or create it."
5611 (interactive)
5612 (when (thing-at-point-looking-at markdown-regex-link-reference)
5613 (let* ((text (match-string-no-properties 3))
5614 (reference (match-string-no-properties 6))
5615 (target (downcase (if (string= reference "") text reference)))
5616 (loc (cadr (save-match-data (markdown-reference-definition target)))))
5617 (if loc
5618 (goto-char loc)
5619 (goto-char (match-beginning 0))
5620 (markdown-insert-reference-definition target)))))
5622 (defun markdown-reference-find-links (reference)
5623 "Return a list of all links for REFERENCE.
5624 REFERENCE should not include the surrounding square brackets.
5625 Elements of the list have the form (text start line), where
5626 text is the link text, start is the location at the beginning of
5627 the link, and line is the line number on which the link appears."
5628 (let* ((ref-quote (regexp-quote reference))
5629 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
5630 ref-quote ref-quote))
5631 links)
5632 (save-excursion
5633 (goto-char (point-min))
5634 (while (re-search-forward regexp nil t)
5635 (let* ((text (or (match-string-no-properties 1)
5636 (match-string-no-properties 2)))
5637 (start (match-beginning 0))
5638 (line (markdown-line-number-at-pos)))
5639 (cl-pushnew (list text start line) links :test #'equal))))
5640 links))
5642 (defun markdown-get-undefined-refs ()
5643 "Return a list of undefined Markdown references.
5644 Result is an alist of pairs (reference . occurrences), where
5645 occurrences is itself another alist of pairs (label . line-number).
5646 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
5647 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
5648 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
5649 (let ((missing))
5650 (save-excursion
5651 (goto-char (point-min))
5652 (while
5653 (re-search-forward markdown-regex-link-reference nil t)
5654 (let* ((text (match-string-no-properties 3))
5655 (reference (match-string-no-properties 6))
5656 (target (downcase (if (string= reference "") text reference))))
5657 (unless (markdown-reference-definition target)
5658 (let ((entry (assoc target missing)))
5659 (if (not entry)
5660 (cl-pushnew
5661 (cons target (list (cons text (markdown-line-number-at-pos))))
5662 missing :test #'equal)
5663 (setcdr entry
5664 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
5665 (reverse missing))))
5667 (defconst markdown-reference-check-buffer
5668 "*Undefined references for %buffer%*"
5669 "Pattern for name of buffer for listing undefined references.
5670 The string %buffer% will be replaced by the corresponding
5671 `markdown-mode' buffer name.")
5673 (defun markdown-reference-check-buffer (&optional buffer-name)
5674 "Name and return buffer for reference checking.
5675 BUFFER-NAME is the name of the main buffer being visited."
5676 (or buffer-name (setq buffer-name (buffer-name)))
5677 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
5678 "%buffer%" buffer-name
5679 markdown-reference-check-buffer))))
5680 (with-current-buffer refbuf
5681 (when view-mode
5682 (View-exit-and-edit))
5683 (use-local-map button-buffer-map)
5684 (erase-buffer))
5685 refbuf))
5687 (defconst markdown-reference-links-buffer
5688 "*Reference links for %buffer%*"
5689 "Pattern for name of buffer for listing references.
5690 The string %buffer% will be replaced by the corresponding buffer name.")
5692 (defun markdown-reference-links-buffer (&optional buffer-name)
5693 "Name, setup, and return a buffer for listing links.
5694 BUFFER-NAME is the name of the main buffer being visited."
5695 (or buffer-name (setq buffer-name (buffer-name)))
5696 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
5697 "%buffer%" buffer-name
5698 markdown-reference-links-buffer))))
5699 (with-current-buffer linkbuf
5700 (when view-mode
5701 (View-exit-and-edit))
5702 (use-local-map button-buffer-map)
5703 (erase-buffer))
5704 linkbuf))
5706 ;; Add an empty Markdown reference definition to buffer
5707 ;; specified in the 'target-buffer property. The reference name is
5708 ;; the button's label.
5709 (define-button-type 'markdown-undefined-reference-button
5710 'help-echo "mouse-1, RET: create definition for undefined reference"
5711 'follow-link t
5712 'face 'bold
5713 'action (lambda (b)
5714 (let ((buffer (button-get b 'target-buffer))
5715 (line (button-get b 'target-line))
5716 (label (button-label b)))
5717 (switch-to-buffer-other-window buffer)
5718 (goto-char (point-min))
5719 (forward-line line)
5720 (markdown-insert-reference-definition label)
5721 (markdown-check-refs t))))
5723 ;; Jump to line in buffer specified by 'target-buffer property.
5724 ;; Line number is button's 'line property.
5725 (define-button-type 'markdown-goto-line-button
5726 'help-echo "mouse-1, RET: go to line"
5727 'follow-link t
5728 'face 'italic
5729 'action (lambda (b)
5730 (message (button-get b 'buffer))
5731 (switch-to-buffer-other-window (button-get b 'target-buffer))
5732 ;; use call-interactively to silence compiler
5733 (let ((current-prefix-arg (button-get b 'target-line)))
5734 (call-interactively 'goto-line))))
5736 ;; Jumps to a particular link at location given by 'target-char
5737 ;; property in buffer given by 'target-buffer property.
5738 (define-button-type 'markdown-location-button
5739 'help-echo "mouse-1, RET: jump to location of link"
5740 'follow-link t
5741 'face 'bold
5742 'action (lambda (b)
5743 (let ((target (button-get b 'target-buffer))
5744 (loc (button-get b 'target-char)))
5745 (kill-buffer-and-window)
5746 (switch-to-buffer target)
5747 (goto-char loc))))
5749 (defun markdown-insert-undefined-reference-button (reference oldbuf)
5750 "Insert a button for creating REFERENCE in buffer OLDBUF.
5751 REFERENCE should be a list of the form (reference . occurrences),
5752 as by `markdown-get-undefined-refs'."
5753 (let ((label (car reference)))
5754 ;; Create a reference button
5755 (insert-button label
5756 :type 'markdown-undefined-reference-button
5757 'target-buffer oldbuf
5758 'target-line (cdr (car (cdr reference))))
5759 (insert " (")
5760 (dolist (occurrence (cdr reference))
5761 (let ((line (cdr occurrence)))
5762 ;; Create a line number button
5763 (insert-button (number-to-string line)
5764 :type 'markdown-goto-line-button
5765 'target-buffer oldbuf
5766 'target-line line)
5767 (insert " ")))
5768 (delete-char -1)
5769 (insert ")")
5770 (newline)))
5772 (defun markdown-insert-link-button (link oldbuf)
5773 "Insert a button for jumping to LINK in buffer OLDBUF.
5774 LINK should be a list of the form (text char line) containing
5775 the link text, location, and line number."
5776 (let ((label (cl-first link))
5777 (char (cl-second link))
5778 (line (cl-third link)))
5779 ;; Create a reference button
5780 (insert-button label
5781 :type 'markdown-location-button
5782 'target-buffer oldbuf
5783 'target-char char)
5784 (insert (format " (line %d)\n" line))))
5786 (defun markdown-reference-goto-link (&optional reference)
5787 "Jump to the location of the first use of REFERENCE."
5788 (interactive)
5789 (unless reference
5790 (if (thing-at-point-looking-at markdown-regex-reference-definition)
5791 (setq reference (match-string-no-properties 2))
5792 (user-error "No reference definition at point")))
5793 (let ((links (markdown-reference-find-links reference)))
5794 (cond ((= (length links) 1)
5795 (goto-char (cadr (car links))))
5796 ((> (length links) 1)
5797 (let ((oldbuf (current-buffer))
5798 (linkbuf (markdown-reference-links-buffer)))
5799 (with-current-buffer linkbuf
5800 (insert "Links using reference " reference ":\n\n")
5801 (dolist (link (reverse links))
5802 (markdown-insert-link-button link oldbuf)))
5803 (view-buffer-other-window linkbuf)
5804 (goto-char (point-min))
5805 (forward-line 2)))
5807 (error "No links for reference %s" reference)))))
5809 (defun markdown-check-refs (&optional silent)
5810 "Show all undefined Markdown references in current `markdown-mode' buffer.
5811 If SILENT is non-nil, do not message anything when no undefined
5812 references found.
5813 Links which have empty reference definitions are considered to be
5814 defined."
5815 (interactive "P")
5816 (when (not (eq major-mode 'markdown-mode))
5817 (user-error "Not available in current mode"))
5818 (let ((oldbuf (current-buffer))
5819 (refs (markdown-get-undefined-refs))
5820 (refbuf (markdown-reference-check-buffer)))
5821 (if (null refs)
5822 (progn
5823 (when (not silent)
5824 (message "No undefined references found"))
5825 (kill-buffer refbuf))
5826 (with-current-buffer refbuf
5827 (insert "The following references are undefined:\n\n")
5828 (dolist (ref refs)
5829 (markdown-insert-undefined-reference-button ref oldbuf))
5830 (view-buffer-other-window refbuf)
5831 (goto-char (point-min))
5832 (forward-line 2)))))
5835 ;;; Lists =====================================================================
5837 (defun markdown-insert-list-item (&optional arg)
5838 "Insert a new list item.
5839 If the point is inside unordered list, insert a bullet mark. If
5840 the point is inside ordered list, insert the next number followed
5841 by a period. Use the previous list item to determine the amount
5842 of whitespace to place before and after list markers.
5844 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
5845 decrease the indentation by one level.
5847 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
5848 increase the indentation by one level."
5849 (interactive "p")
5850 (let (bounds cur-indent marker indent new-indent new-loc)
5851 (save-match-data
5852 ;; Look for a list item on current or previous non-blank line
5853 (save-excursion
5854 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
5855 (not (bobp))
5856 (markdown-cur-line-blank-p))
5857 (forward-line -1)))
5858 (when bounds
5859 (cond ((save-excursion
5860 (skip-chars-backward " \t")
5861 (looking-at-p markdown-regex-list))
5862 (beginning-of-line)
5863 (insert "\n")
5864 (forward-line -1))
5865 ((not (markdown-cur-line-blank-p))
5866 (newline)))
5867 (setq new-loc (point)))
5868 ;; Look ahead for a list item on next non-blank line
5869 (unless bounds
5870 (save-excursion
5871 (while (and (null bounds)
5872 (not (eobp))
5873 (markdown-cur-line-blank-p))
5874 (forward-line)
5875 (setq bounds (markdown-cur-list-item-bounds))))
5876 (when bounds
5877 (setq new-loc (point))
5878 (unless (markdown-cur-line-blank-p)
5879 (newline))))
5880 (if (not bounds)
5881 ;; When not in a list, start a new unordered one
5882 (progn
5883 (unless (markdown-cur-line-blank-p)
5884 (insert "\n"))
5885 (insert markdown-unordered-list-item-prefix))
5886 ;; Compute indentation and marker for new list item
5887 (setq cur-indent (nth 2 bounds))
5888 (setq marker (nth 4 bounds))
5889 ;; If current item is a GFM checkbox, insert new unchecked checkbox.
5890 (when (nth 5 bounds)
5891 (setq marker
5892 (concat marker
5893 (replace-regexp-in-string "[Xx]" " " (nth 5 bounds)))))
5894 (cond
5895 ;; Dedent: decrement indentation, find previous marker.
5896 ((= arg 4)
5897 (setq indent (max (- cur-indent 4) 0))
5898 (let ((prev-bounds
5899 (save-excursion
5900 (goto-char (nth 0 bounds))
5901 (when (markdown-up-list)
5902 (markdown-cur-list-item-bounds)))))
5903 (when prev-bounds
5904 (setq marker (nth 4 prev-bounds)))))
5905 ;; Indent: increment indentation by 4, use same marker.
5906 ((= arg 16) (setq indent (+ cur-indent 4)))
5907 ;; Same level: keep current indentation and marker.
5908 (t (setq indent cur-indent)))
5909 (setq new-indent (make-string indent 32))
5910 (goto-char new-loc)
5911 (cond
5912 ;; Ordered list
5913 ((string-match-p "[0-9]" marker)
5914 (if (= arg 16) ;; starting a new column indented one more level
5915 (insert (concat new-indent "1. "))
5916 ;; Don't use previous match-data
5917 (set-match-data nil)
5918 ;; travel up to the last item and pick the correct number. If
5919 ;; the argument was nil, "new-indent = cur-indent" is the same,
5920 ;; so we don't need special treatment. Neat.
5921 (save-excursion
5922 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
5923 (>= (forward-line -1) 0))))
5924 (let* ((old-prefix (match-string 1))
5925 (old-spacing (match-string 2))
5926 (new-prefix (if old-prefix
5927 (int-to-string (1+ (string-to-number old-prefix)))
5928 "1"))
5929 (space-adjust (- (length old-prefix) (length new-prefix)))
5930 (new-spacing (if (and (match-string 2)
5931 (not (string-match-p "\t" old-spacing))
5932 (< space-adjust 0)
5933 (> space-adjust (- 1 (length (match-string 2)))))
5934 (substring (match-string 2) 0 space-adjust)
5935 (or old-spacing ". "))))
5936 (insert (concat new-indent new-prefix new-spacing)))))
5937 ;; Unordered list, GFM task list, or ordered list with hash mark
5938 ((string-match-p "[\\*\\+-]\\|#\\." marker)
5939 (insert new-indent marker))))
5940 ;; Propertize the newly inserted list item now
5941 (markdown-syntax-propertize-list-items (point-at-bol) (point-at-eol)))))
5943 (defun markdown-move-list-item-up ()
5944 "Move the current list item up in the list when possible.
5945 In nested lists, move child items with the parent item."
5946 (interactive)
5947 (let (cur prev old)
5948 (when (setq cur (markdown-cur-list-item-bounds))
5949 (setq old (point))
5950 (goto-char (nth 0 cur))
5951 (if (markdown-prev-list-item (nth 3 cur))
5952 (progn
5953 (setq prev (markdown-cur-list-item-bounds))
5954 (condition-case nil
5955 (progn
5956 (transpose-regions (nth 0 prev) (nth 1 prev)
5957 (nth 0 cur) (nth 1 cur) t)
5958 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
5959 ;; Catch error in case regions overlap.
5960 (error (goto-char old))))
5961 (goto-char old)))))
5963 (defun markdown-move-list-item-down ()
5964 "Move the current list item down in the list when possible.
5965 In nested lists, move child items with the parent item."
5966 (interactive)
5967 (let (cur next old)
5968 (when (setq cur (markdown-cur-list-item-bounds))
5969 (setq old (point))
5970 (if (markdown-next-list-item (nth 3 cur))
5971 (progn
5972 (setq next (markdown-cur-list-item-bounds))
5973 (condition-case nil
5974 (progn
5975 (transpose-regions (nth 0 cur) (nth 1 cur)
5976 (nth 0 next) (nth 1 next) nil)
5977 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
5978 ;; Catch error in case regions overlap.
5979 (error (goto-char old))))
5980 (goto-char old)))))
5982 (defun markdown-demote-list-item (&optional bounds)
5983 "Indent (or demote) the current list item.
5984 Optionally, BOUNDS of the current list item may be provided if available.
5985 In nested lists, demote child items as well."
5986 (interactive)
5987 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
5988 (save-excursion
5989 (let* ((item-start (set-marker (make-marker) (nth 0 bounds)))
5990 (item-end (set-marker (make-marker) (nth 1 bounds)))
5991 (list-start (progn (markdown-beginning-of-list)
5992 (set-marker (make-marker) (point))))
5993 (list-end (progn (markdown-end-of-list)
5994 (set-marker (make-marker) (point)))))
5995 (goto-char item-start)
5996 (while (< (point) item-end)
5997 (unless (markdown-cur-line-blank-p)
5998 (insert (make-string markdown-list-indent-width ? )))
5999 (forward-line))
6000 (markdown-syntax-propertize-list-items list-start list-end)))))
6002 (defun markdown-promote-list-item (&optional bounds)
6003 "Unindent (or promote) the current list item.
6004 Optionally, BOUNDS of the current list item may be provided if available.
6005 In nested lists, demote child items as well."
6006 (interactive)
6007 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6008 (save-excursion
6009 (save-match-data
6010 (let ((item-start (set-marker (make-marker) (nth 0 bounds)))
6011 (item-end (set-marker (make-marker) (nth 1 bounds)))
6012 (list-start (progn (markdown-beginning-of-list)
6013 (set-marker (make-marker) (point))))
6014 (list-end (progn (markdown-end-of-list)
6015 (set-marker (make-marker) (point))))
6016 num regexp)
6017 (goto-char item-start)
6018 (when (looking-at (format "^[ ]\\{1,%d\\}"
6019 markdown-list-indent-width))
6020 (setq num (- (match-end 0) (match-beginning 0)))
6021 (setq regexp (format "^[ ]\\{1,%d\\}" num))
6022 (while (and (< (point) item-end)
6023 (re-search-forward regexp item-end t))
6024 (replace-match "" nil nil)
6025 (forward-line))
6026 (markdown-syntax-propertize-list-items list-start list-end)))))))
6028 (defun markdown-cleanup-list-numbers-level (&optional pfx)
6029 "Update the numbering for level PFX (as a string of spaces).
6031 Assume that the previously found match was for a numbered item in
6032 a list."
6033 (let ((cpfx pfx)
6034 (idx 0)
6035 (continue t)
6036 (step t)
6037 (sep nil))
6038 (while (and continue (not (eobp)))
6039 (setq step t)
6040 (cond
6041 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
6042 (setq cpfx (match-string-no-properties 1))
6043 (cond
6044 ((string= cpfx pfx)
6045 (save-excursion
6046 (replace-match
6047 (concat pfx (number-to-string (setq idx (1+ idx))) ". ")))
6048 (setq sep nil))
6049 ;; indented a level
6050 ((string< pfx cpfx)
6051 (setq sep (markdown-cleanup-list-numbers-level cpfx))
6052 (setq step nil))
6053 ;; exit the loop
6055 (setq step nil)
6056 (setq continue nil))))
6058 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
6059 (setq cpfx (match-string-no-properties 1))
6060 (cond
6061 ;; reset if separated before
6062 ((string= cpfx pfx) (when sep (setq idx 0)))
6063 ((string< cpfx pfx)
6064 (setq step nil)
6065 (setq continue nil))))
6066 (t (setq sep t)))
6068 (when step
6069 (beginning-of-line)
6070 (setq continue (= (forward-line) 0))))
6071 sep))
6073 (defun markdown-cleanup-list-numbers ()
6074 "Update the numbering of ordered lists."
6075 (interactive)
6076 (save-excursion
6077 (goto-char (point-min))
6078 (markdown-cleanup-list-numbers-level "")))
6081 ;;; Movement ==================================================================
6083 (defun markdown-beginning-of-defun (&optional arg)
6084 "`beginning-of-defun-function' for Markdown.
6085 This is used to find the beginning of the defun and should behave
6086 like ‘beginning-of-defun’, returning non-nil if it found the
6087 beginning of a defun. It moves the point backward, right before a
6088 heading which defines a defun. When ARG is non-nil, repeat that
6089 many times. When ARG is negative, move forward to the ARG-th
6090 following section."
6091 (or arg (setq arg 1))
6092 (when (< arg 0) (end-of-line))
6093 ;; Adjust position for setext headings.
6094 (when (and (thing-at-point-looking-at markdown-regex-header-setext)
6095 (not (= (point) (match-beginning 0)))
6096 (not (markdown-code-block-at-point-p)))
6097 (goto-char (match-end 0)))
6098 (let (found)
6099 ;; Move backward with positive argument.
6100 (while (and (not (bobp)) (> arg 0))
6101 (setq found nil)
6102 (while (and (not found)
6103 (not (bobp))
6104 (re-search-backward markdown-regex-header nil 'move))
6105 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6106 (setq found (match-beginning 0)))
6107 (setq arg (1- arg)))
6108 ;; Move forward with negative argument.
6109 (while (and (not (eobp)) (< arg 0))
6110 (setq found nil)
6111 (while (and (not found)
6112 (not (eobp))
6113 (re-search-forward markdown-regex-header nil 'move))
6114 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6115 (setq found (match-beginning 0)))
6116 (setq arg (1+ arg)))
6117 (when found
6118 (beginning-of-line)
6119 t)))
6121 (defun markdown-end-of-defun ()
6122 "`end-of-defun-function’ for Markdown.
6123 This is used to find the end of the defun at point.
6124 It is called with no argument, right after calling ‘beginning-of-defun-raw’,
6125 so it can assume that point is at the beginning of the defun body.
6126 It should move point to the first position after the defun."
6127 (or (eobp) (forward-char 1))
6128 (let (found)
6129 (while (and (not found)
6130 (not (eobp))
6131 (re-search-forward markdown-regex-header nil 'move))
6132 (when (not (markdown-code-block-at-pos (match-beginning 0)))
6133 (setq found (match-beginning 0))))
6134 (when found
6135 (goto-char found)
6136 (skip-syntax-backward "-"))))
6138 (make-obsolete 'markdown-beginning-of-block 'markdown-beginning-of-text-block "v2.2")
6140 (defun markdown-beginning-of-text-block ()
6141 "Move backward to previous beginning of a plain text block.
6142 This function simply looks for blank lines without considering
6143 the surrounding context in light of Markdown syntax. For that, see
6144 `markdown-backward-block'."
6145 (interactive)
6146 (let ((start (point)))
6147 (if (re-search-backward markdown-regex-block-separator nil t)
6148 (goto-char (match-end 0))
6149 (goto-char (point-min)))
6150 (when (and (= start (point)) (not (bobp)))
6151 (forward-line -1)
6152 (if (re-search-backward markdown-regex-block-separator nil t)
6153 (goto-char (match-end 0))
6154 (goto-char (point-min))))))
6156 (make-obsolete 'markdown-end-of-block 'markdown-end-of-text-block "v2.2")
6158 (defun markdown-end-of-text-block ()
6159 "Move forward to next beginning of a plain text block.
6160 This function simply looks for blank lines without considering
6161 the surrounding context in light of Markdown syntax. For that, see
6162 `markdown-forward-block'."
6163 (interactive)
6164 (beginning-of-line)
6165 (skip-chars-forward " \t\n")
6166 (when (= (point) (point-min))
6167 (forward-char))
6168 (if (re-search-forward markdown-regex-block-separator nil t)
6169 (goto-char (match-end 0))
6170 (goto-char (point-max)))
6171 (skip-chars-backward " \t\n")
6172 (forward-line))
6174 (defun markdown-backward-paragraph (&optional arg)
6175 "Move the point to the start of the current paragraph.
6176 With argument ARG, do it ARG times; a negative argument ARG = -N
6177 means move forward N blocks."
6178 (interactive "^p")
6179 (or arg (setq arg 1))
6180 (if (< arg 0)
6181 (markdown-forward-paragraph (- arg))
6182 (dotimes (_ arg)
6183 ;; Skip over whitespace in between paragraphs when moving backward.
6184 (skip-chars-backward " \t\n")
6185 (beginning-of-line)
6186 ;; Skip over code block endings.
6187 (when (markdown-range-properties-exist
6188 (point-at-bol) (point-at-eol)
6189 '(markdown-gfm-block-end
6190 markdown-tilde-fence-end))
6191 (forward-line -1))
6192 ;; Skip over blank lines inside blockquotes.
6193 (while (and (not (eobp))
6194 (looking-at markdown-regex-blockquote)
6195 (= (length (match-string 3)) 0))
6196 (forward-line -1))
6197 ;; Proceed forward based on the type of block of paragraph.
6198 (let (bounds skip)
6199 (cond
6200 ;; Blockquotes
6201 ((looking-at markdown-regex-blockquote)
6202 (while (and (not (bobp))
6203 (looking-at markdown-regex-blockquote)
6204 (> (length (match-string 3)) 0)) ;; not blank
6205 (forward-line -1))
6206 (forward-line))
6207 ;; List items
6208 ((setq bounds (markdown-cur-list-item-bounds))
6209 (goto-char (nth 0 bounds)))
6210 ;; Other
6212 (while (and (not (bobp))
6213 (not skip)
6214 (not (markdown-cur-line-blank-p))
6215 (not (looking-at markdown-regex-blockquote))
6216 (not (markdown-range-properties-exist
6217 (point-at-bol) (point-at-eol)
6218 '(markdown-gfm-block-end
6219 markdown-tilde-fence-end))))
6220 (setq skip (markdown-range-properties-exist
6221 (point-at-bol) (point-at-eol)
6222 '(markdown-gfm-block-begin
6223 markdown-tilde-fence-begin)))
6224 (forward-line -1))
6225 (unless (bobp)
6226 (forward-line 1))))))))
6228 (defun markdown-forward-paragraph (&optional arg)
6229 "Move forward to the next end of a paragraph.
6230 With argument ARG, do it ARG times; a negative argument ARG = -N
6231 means move backward N blocks."
6232 (interactive "^p")
6233 (or arg (setq arg 1))
6234 (if (< arg 0)
6235 (markdown-backward-paragraph (- arg))
6236 (dotimes (_ arg)
6237 ;; Skip whitespace in between paragraphs.
6238 (when (markdown-cur-line-blank-p)
6239 (skip-syntax-forward "-")
6240 (beginning-of-line))
6241 ;; Proceed forward based on the type of block.
6242 (let (bounds skip)
6243 (cond
6244 ;; Blockquotes
6245 ((looking-at markdown-regex-blockquote)
6246 ;; Skip over blank lines inside blockquotes.
6247 (while (and (not (eobp))
6248 (looking-at markdown-regex-blockquote)
6249 (= (length (match-string 3)) 0))
6250 (forward-line))
6251 ;; Move to end of quoted text block
6252 (while (and (not (eobp))
6253 (looking-at markdown-regex-blockquote)
6254 (> (length (match-string 3)) 0)) ;; not blank
6255 (forward-line)))
6256 ;; List items
6257 ((and (markdown-cur-list-item-bounds)
6258 (setq bounds (markdown-next-list-item-bounds)))
6259 (goto-char (nth 0 bounds)))
6260 ;; Other
6262 (forward-line)
6263 (while (and (not (eobp))
6264 (not skip)
6265 (not (markdown-cur-line-blank-p))
6266 (not (looking-at markdown-regex-blockquote))
6267 (not (markdown-range-properties-exist
6268 (point-at-bol) (point-at-eol)
6269 '(markdown-gfm-block-begin
6270 markdown-tilde-fence-begin))))
6271 (setq skip (markdown-range-properties-exist
6272 (point-at-bol) (point-at-eol)
6273 '(markdown-gfm-block-end
6274 markdown-tilde-fence-end)))
6275 (forward-line))))))))
6277 (defun markdown-backward-block (&optional arg)
6278 "Move the point to the start of the current Markdown block.
6279 Moves across complete code blocks, list items, and blockquotes,
6280 but otherwise stops at blank lines, headers, and horizontal
6281 rules. With argument ARG, do it ARG times; a negative argument
6282 ARG = -N means move forward N blocks."
6283 (interactive "^p")
6284 (or arg (setq arg 1))
6285 (if (< arg 0)
6286 (markdown-forward-block (- arg))
6287 (dotimes (_ arg)
6288 ;; Skip over whitespace in between blocks when moving backward,
6289 ;; unless at a block boundary with no whitespace.
6290 (skip-syntax-backward "-")
6291 (beginning-of-line)
6292 ;; Proceed forward based on the type of block.
6293 (cond
6294 ;; Code blocks
6295 ((and (markdown-code-block-at-pos (point)) ;; this line
6296 (markdown-code-block-at-pos (point-at-bol 0))) ;; previous line
6297 (forward-line -1)
6298 (while (and (markdown-code-block-at-point-p) (not (bobp)))
6299 (forward-line -1))
6300 (forward-line))
6301 ;; Headings
6302 ((markdown-heading-at-point)
6303 (goto-char (match-beginning 0)))
6304 ;; Horizontal rules
6305 ((looking-at markdown-regex-hr))
6306 ;; Blockquotes
6307 ((looking-at markdown-regex-blockquote)
6308 (forward-line -1)
6309 (while (and (looking-at markdown-regex-blockquote)
6310 (not (bobp)))
6311 (forward-line -1))
6312 (forward-line))
6313 ;; List items
6314 ((markdown-cur-list-item-bounds)
6315 (markdown-beginning-of-list))
6316 ;; Other
6318 ;; Move forward in case it is a one line regular paragraph.
6319 (unless (markdown-next-line-blank-p)
6320 (forward-line))
6321 (unless (markdown-prev-line-blank-p)
6322 (markdown-backward-paragraph)))))))
6324 (defun markdown-forward-block (&optional arg)
6325 "Move forward to the next end of a Markdown block.
6326 Moves across complete code blocks, list items, and blockquotes,
6327 but otherwise stops at blank lines, headers, and horizontal
6328 rules. With argument ARG, do it ARG times; a negative argument
6329 ARG = -N means move backward N blocks."
6330 (interactive "^p")
6331 (or arg (setq arg 1))
6332 (if (< arg 0)
6333 (markdown-backward-block (- arg))
6334 (dotimes (_ arg)
6335 ;; Skip over whitespace in between blocks when moving forward.
6336 (if (markdown-cur-line-blank-p)
6337 (skip-syntax-forward "-")
6338 (beginning-of-line))
6339 ;; Proceed forward based on the type of block.
6340 (cond
6341 ;; Code blocks
6342 ((markdown-code-block-at-point-p)
6343 (forward-line)
6344 (while (and (markdown-code-block-at-point-p) (not (eobp)))
6345 (forward-line)))
6346 ;; Headings
6347 ((looking-at markdown-regex-header)
6348 (goto-char (or (match-end 4) (match-end 2) (match-end 3)))
6349 (forward-line))
6350 ;; Horizontal rules
6351 ((looking-at markdown-regex-hr)
6352 (forward-line))
6353 ;; Blockquotes
6354 ((looking-at markdown-regex-blockquote)
6355 (forward-line)
6356 (while (and (looking-at markdown-regex-blockquote) (not (eobp)))
6357 (forward-line)))
6358 ;; List items
6359 ((markdown-cur-list-item-bounds)
6360 (markdown-end-of-list)
6361 (forward-line))
6362 ;; Other
6363 (t (markdown-forward-paragraph))))
6364 (skip-syntax-backward "-")
6365 (unless (eobp)
6366 (forward-char 1))))
6368 (defun markdown-backward-page (&optional count)
6369 "Move backward to boundary of the current toplevel section.
6370 With COUNT, repeat, or go forward if negative."
6371 (interactive "p")
6372 (or count (setq count 1))
6373 (if (< count 0)
6374 (markdown-forward-page (- count))
6375 (skip-syntax-backward "-")
6376 (or (markdown-back-to-heading-over-code-block t t)
6377 (goto-char (point-min)))
6378 (when (looking-at markdown-regex-header)
6379 (let ((level (markdown-outline-level)))
6380 (when (> level 1) (markdown-up-heading level))
6381 (when (> count 1)
6382 (condition-case nil
6383 (markdown-backward-same-level (1- count))
6384 (error (goto-char (point-min)))))))))
6386 (defun markdown-forward-page (&optional count)
6387 "Move forward to boundary of the current toplevel section.
6388 With COUNT, repeat, or go backward if negative."
6389 (interactive "p")
6390 (or count (setq count 1))
6391 (if (< count 0)
6392 (markdown-backward-page (- count))
6393 (if (markdown-back-to-heading-over-code-block t t)
6394 (let ((level (markdown-outline-level)))
6395 (when (> level 1) (markdown-up-heading level))
6396 (condition-case nil
6397 (markdown-forward-same-level count)
6398 (error (goto-char (point-max)))))
6399 (markdown-next-visible-heading 1))))
6401 (defun markdown-next-link ()
6402 "Jump to next inline, reference, or wiki link.
6403 If successful, return point. Otherwise, return nil.
6404 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
6405 (interactive)
6406 (let ((opoint (point)))
6407 (when (or (markdown-link-p) (markdown-wiki-link-p))
6408 ;; At a link already, move past it.
6409 (goto-char (+ (match-end 0) 1)))
6410 ;; Search for the next wiki link and move to the beginning.
6411 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t)
6412 (markdown-code-block-at-point-p)
6413 (< (point) (point-max))))
6414 (if (and (not (eq (point) opoint))
6415 (or (markdown-link-p) (markdown-wiki-link-p)))
6416 ;; Group 1 will move past non-escape character in wiki link regexp.
6417 ;; Go to beginning of group zero for all other link types.
6418 (goto-char (or (match-beginning 1) (match-beginning 0)))
6419 (goto-char opoint)
6420 nil)))
6422 (defun markdown-previous-link ()
6423 "Jump to previous wiki link.
6424 If successful, return point. Otherwise, return nil.
6425 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
6426 (interactive)
6427 (let ((opoint (point)))
6428 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t)
6429 (markdown-code-block-at-point-p)
6430 (> (point) (point-min))))
6431 (if (and (not (eq (point) opoint))
6432 (or (markdown-link-p) (markdown-wiki-link-p)))
6433 (goto-char (or (match-beginning 1) (match-beginning 0)))
6434 (goto-char opoint)
6435 nil)))
6438 ;;; Outline ===================================================================
6440 (defun markdown-move-heading-common (move-fn &optional arg adjust)
6441 "Wrapper for `outline-mode' functions to skip false positives.
6442 MOVE-FN is a function and ARG is its argument. For example,
6443 headings inside preformatted code blocks may match
6444 `outline-regexp' but should not be considered as headings.
6445 When ADJUST is non-nil, adjust the point for interactive calls
6446 to avoid leaving the point at invisible markup. This adjustment
6447 generally should only be done for interactive calls, since other
6448 functions may expect the point to be at the beginning of the
6449 regular expression."
6450 (let ((prev -1) (start (point)))
6451 (if arg (funcall move-fn arg) (funcall move-fn))
6452 (while (and (/= prev (point)) (markdown-code-block-at-point-p))
6453 (setq prev (point))
6454 (if arg (funcall move-fn arg) (funcall move-fn)))
6455 ;; Adjust point for setext headings and invisible text.
6456 (save-match-data
6457 (when (and adjust (thing-at-point-looking-at markdown-regex-header))
6458 (if markdown-hide-markup
6459 ;; Move to beginning of heading text if markup is hidden.
6460 (goto-char (or (match-beginning 1) (match-beginning 5)))
6461 ;; Move to beginning of markup otherwise.
6462 (goto-char (or (match-beginning 1) (match-beginning 4))))))
6463 (if (= (point) start) nil (point))))
6465 (defun markdown-next-visible-heading (arg)
6466 "Move to the next visible heading line of any level.
6467 With argument, repeats or can move backward if negative. ARG is
6468 passed to `outline-next-visible-heading'."
6469 (interactive "p")
6470 (markdown-move-heading-common #'outline-next-visible-heading arg 'adjust))
6472 (defun markdown-previous-visible-heading (arg)
6473 "Move to the previous visible heading line of any level.
6474 With argument, repeats or can move backward if negative. ARG is
6475 passed to `outline-previous-visible-heading'."
6476 (interactive "p")
6477 (markdown-move-heading-common #'outline-previous-visible-heading arg 'adjust))
6479 (defun markdown-next-heading ()
6480 "Move to the next heading line of any level."
6481 (markdown-move-heading-common #'outline-next-heading))
6483 (defun markdown-previous-heading ()
6484 "Move to the previous heading line of any level."
6485 (markdown-move-heading-common #'outline-previous-heading))
6487 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok no-error)
6488 "Move back to the beginning of the previous heading.
6489 Returns t if the point is at a heading, the location if a heading
6490 was found, and nil otherwise.
6491 Only visible heading lines are considered, unless INVISIBLE-OK is
6492 non-nil. Throw an error if there is no previous heading unless
6493 NO-ERROR is non-nil.
6494 Leaves match data intact for `markdown-regex-header'."
6495 (beginning-of-line)
6496 (or (and (markdown-heading-at-point)
6497 (not (markdown-code-block-at-point-p)))
6498 (let (found)
6499 (save-excursion
6500 (while (and (not found)
6501 (re-search-backward markdown-regex-header nil t))
6502 (when (and (or invisible-ok (not (outline-invisible-p)))
6503 (not (markdown-code-block-at-point-p)))
6504 (setq found (point))))
6505 (if (not found)
6506 (unless no-error (user-error "Before first heading"))
6507 (setq found (point))))
6508 (when found (goto-char found)))))
6510 (defun markdown-forward-same-level (arg)
6511 "Move forward to the ARG'th heading at same level as this one.
6512 Stop at the first and last headings of a superior heading."
6513 (interactive "p")
6514 (markdown-back-to-heading-over-code-block)
6515 (markdown-move-heading-common #'outline-forward-same-level arg 'adjust))
6517 (defun markdown-backward-same-level (arg)
6518 "Move backward to the ARG'th heading at same level as this one.
6519 Stop at the first and last headings of a superior heading."
6520 (interactive "p")
6521 (markdown-back-to-heading-over-code-block)
6522 (while (> arg 0)
6523 (let ((point-to-move-to
6524 (save-excursion
6525 (markdown-move-heading-common #'outline-get-last-sibling nil 'adjust))))
6526 (if point-to-move-to
6527 (progn
6528 (goto-char point-to-move-to)
6529 (setq arg (1- arg)))
6530 (user-error "No previous same-level heading")))))
6532 (defun markdown-up-heading (arg)
6533 "Move to the visible heading line of which the present line is a subheading.
6534 With argument, move up ARG levels."
6535 (interactive "p")
6536 (and (called-interactively-p 'any)
6537 (not (eq last-command 'markdown-up-heading)) (push-mark))
6538 (markdown-move-heading-common #'outline-up-heading arg 'adjust))
6540 (defun markdown-back-to-heading (&optional invisible-ok)
6541 "Move to previous heading line, or beg of this line if it's a heading.
6542 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
6543 (markdown-move-heading-common #'outline-back-to-heading invisible-ok))
6545 (defalias 'markdown-end-of-heading 'outline-end-of-heading)
6547 (defun markdown-on-heading-p ()
6548 "Return non-nil if point is on a heading line."
6549 (get-text-property (point-at-bol) 'markdown-heading))
6551 (defun markdown-end-of-subtree (&optional invisible-OK)
6552 "Move to the end of the current subtree.
6553 Only visible heading lines are considered, unless INVISIBLE-OK is
6554 non-nil.
6555 Derived from `org-end-of-subtree'."
6556 (markdown-back-to-heading invisible-OK)
6557 (let ((first t)
6558 (level (markdown-outline-level)))
6559 (while (and (not (eobp))
6560 (or first (> (markdown-outline-level) level)))
6561 (setq first nil)
6562 (markdown-next-heading))
6563 (if (memq (preceding-char) '(?\n ?\^M))
6564 (progn
6565 ;; Go to end of line before heading
6566 (forward-char -1)
6567 (if (memq (preceding-char) '(?\n ?\^M))
6568 ;; leave blank line before heading
6569 (forward-char -1)))))
6570 (point))
6572 (defun markdown-outline-fix-visibility ()
6573 "Hide any false positive headings that should not be shown.
6574 For example, headings inside preformatted code blocks may match
6575 `outline-regexp' but should not be shown as headings when cycling.
6576 Also, the ending --- line in metadata blocks appears to be a
6577 setext header, but should not be folded."
6578 (save-excursion
6579 (goto-char (point-min))
6580 ;; Unhide any false positives in metadata blocks
6581 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin)
6582 (let ((body (progn (forward-line)
6583 (markdown-text-property-at-point
6584 'markdown-yaml-metadata-section))))
6585 (when body
6586 (let ((end (progn (goto-char (cl-second body))
6587 (markdown-text-property-at-point
6588 'markdown-yaml-metadata-end))))
6589 (outline-flag-region (point-min) (1+ (cl-second end)) nil)))))
6590 ;; Hide any false positives in code blocks
6591 (unless (outline-on-heading-p)
6592 (outline-next-visible-heading 1))
6593 (while (< (point) (point-max))
6594 (when (markdown-code-block-at-point-p)
6595 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t))
6596 (outline-next-visible-heading 1))))
6598 (defvar markdown-cycle-global-status 1)
6599 (defvar markdown-cycle-subtree-status nil)
6601 (defun markdown-next-preface ()
6602 (let (finish)
6603 (while (and (not finish) (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
6604 nil 'move))
6605 (unless (markdown-code-block-at-point-p)
6606 (goto-char (match-beginning 0))
6607 (setq finish t))))
6608 (when (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
6609 (forward-char -1)))
6611 (defun markdown-show-entry ()
6612 (save-excursion
6613 (outline-back-to-heading t)
6614 (outline-flag-region (1- (point))
6615 (progn
6616 (markdown-next-preface)
6617 (if (= 1 (- (point-max) (point)))
6618 (point-max)
6619 (point)))
6620 nil)))
6622 ;; This function was originally derived from `org-cycle' from org.el.
6623 (defun markdown-cycle (&optional arg)
6624 "Visibility cycling for Markdown mode.
6625 If ARG is t, perform global visibility cycling. If the point is
6626 at an atx-style header, cycle visibility of the corresponding
6627 subtree. Otherwise, indent the current line or insert a tab,
6628 as appropriate, by calling `indent-for-tab-command'."
6629 (interactive "P")
6630 (cond
6632 ;; Global cycling
6633 ((eq arg t)
6634 (cond
6635 ;; Move from overview to contents
6636 ((and (eq last-command this-command)
6637 (eq markdown-cycle-global-status 2))
6638 (markdown-hide-sublevels 1)
6639 (message "CONTENTS")
6640 (setq markdown-cycle-global-status 3)
6641 (markdown-outline-fix-visibility))
6642 ;; Move from contents to all
6643 ((and (eq last-command this-command)
6644 (eq markdown-cycle-global-status 3))
6645 (markdown-show-all)
6646 (message "SHOW ALL")
6647 (setq markdown-cycle-global-status 1))
6648 ;; Defaults to overview
6650 (markdown-hide-body)
6651 (message "OVERVIEW")
6652 (setq markdown-cycle-global-status 2)
6653 (markdown-outline-fix-visibility))))
6655 ;; At a heading: rotate between three different views
6656 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
6657 (markdown-back-to-heading)
6658 (let ((goal-column 0) eoh eol eos)
6659 ;; Determine boundaries
6660 (save-excursion
6661 (markdown-back-to-heading)
6662 (save-excursion
6663 (beginning-of-line 2)
6664 (while (and (not (eobp)) ;; this is like `next-line'
6665 (get-char-property (1- (point)) 'invisible))
6666 (beginning-of-line 2)) (setq eol (point)))
6667 (markdown-end-of-heading) (setq eoh (point))
6668 (markdown-end-of-subtree t)
6669 (skip-chars-forward " \t\n")
6670 (beginning-of-line 1) ; in case this is an item
6671 (setq eos (1- (point))))
6672 ;; Find out what to do next and set `this-command'
6673 (cond
6674 ;; Nothing is hidden behind this heading
6675 ((= eos eoh)
6676 (message "EMPTY ENTRY")
6677 (setq markdown-cycle-subtree-status nil))
6678 ;; Entire subtree is hidden in one line: open it
6679 ((>= eol eos)
6680 (markdown-show-entry)
6681 (markdown-show-children)
6682 (message "CHILDREN")
6683 (setq markdown-cycle-subtree-status 'children))
6684 ;; We just showed the children, now show everything.
6685 ((and (eq last-command this-command)
6686 (eq markdown-cycle-subtree-status 'children))
6687 (markdown-show-subtree)
6688 (message "SUBTREE")
6689 (setq markdown-cycle-subtree-status 'subtree))
6690 ;; Default action: hide the subtree.
6692 (markdown-hide-subtree)
6693 (message "FOLDED")
6694 (setq markdown-cycle-subtree-status 'folded)))))
6696 ;; In a table, move forward by one cell
6697 ((markdown-table-at-point-p)
6698 (call-interactively #'markdown-table-forward-cell))
6700 ;; Otherwise, indent as appropriate
6702 (indent-for-tab-command))))
6704 (defun markdown-shifttab ()
6705 "Handle S-TAB keybinding based on context.
6706 When in a table, move backward one cell.
6707 Otherwise, cycle global heading visibility by calling
6708 `markdown-cycle' with argument t."
6709 (interactive)
6710 (cond ((markdown-table-at-point-p)
6711 (call-interactively #'markdown-table-backward-cell))
6712 (t (markdown-cycle t))))
6714 (defun markdown-outline-level ()
6715 "Return the depth to which a statement is nested in the outline."
6716 (cond
6717 ((and (match-beginning 0)
6718 (markdown-code-block-at-pos (match-beginning 0)))
6719 7) ;; Only 6 header levels are defined.
6720 ((match-end 2) 1)
6721 ((match-end 3) 2)
6722 ((match-end 4)
6723 (length (markdown-trim-whitespace (match-string-no-properties 4))))))
6725 (defun markdown-promote-subtree (&optional arg)
6726 "Promote the current subtree of ATX headings.
6727 Note that Markdown does not support heading levels higher than
6728 six and therefore level-six headings will not be promoted
6729 further. If ARG is non-nil promote the heading, otherwise
6730 demote."
6731 (interactive "*P")
6732 (save-excursion
6733 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
6734 (re-search-backward markdown-regex-header-atx nil t))
6735 (not (markdown-code-block-at-point-p)))
6736 (let ((level (length (match-string 1)))
6737 (promote-or-demote (if arg 1 -1))
6738 (remove 't))
6739 (markdown-cycle-atx promote-or-demote remove)
6740 (catch 'end-of-subtree
6741 (while (and (markdown-next-heading)
6742 (looking-at markdown-regex-header-atx))
6743 ;; Exit if this not a higher level heading; promote otherwise.
6744 (if (and (looking-at markdown-regex-header-atx)
6745 (<= (length (match-string-no-properties 1)) level))
6746 (throw 'end-of-subtree nil)
6747 (markdown-cycle-atx promote-or-demote remove))))))))
6749 (defun markdown-demote-subtree ()
6750 "Demote the current subtree of ATX headings."
6751 (interactive)
6752 (markdown-promote-subtree t))
6754 (defun markdown-move-subtree-up ()
6755 "Move the current subtree of ATX headings up."
6756 (interactive)
6757 (outline-move-subtree-up 1))
6759 (defun markdown-move-subtree-down ()
6760 "Move the current subtree of ATX headings down."
6761 (interactive)
6762 (outline-move-subtree-down 1))
6764 (defun markdown-outline-next ()
6765 "Move to next list item, when in a list, or next visible heading."
6766 (interactive)
6767 (let ((bounds (markdown-next-list-item-bounds)))
6768 (if bounds
6769 (goto-char (nth 0 bounds))
6770 (markdown-next-visible-heading 1))))
6772 (defun markdown-outline-previous ()
6773 "Move to previous list item, when in a list, or previous visible heading."
6774 (interactive)
6775 (let ((bounds (markdown-prev-list-item-bounds)))
6776 (if bounds
6777 (goto-char (nth 0 bounds))
6778 (markdown-previous-visible-heading 1))))
6780 (defun markdown-outline-next-same-level ()
6781 "Move to next list item or heading of same level."
6782 (interactive)
6783 (let ((bounds (markdown-cur-list-item-bounds)))
6784 (if bounds
6785 (markdown-next-list-item (nth 3 bounds))
6786 (markdown-forward-same-level 1))))
6788 (defun markdown-outline-previous-same-level ()
6789 "Move to previous list item or heading of same level."
6790 (interactive)
6791 (let ((bounds (markdown-cur-list-item-bounds)))
6792 (if bounds
6793 (markdown-prev-list-item (nth 3 bounds))
6794 (markdown-backward-same-level 1))))
6796 (defun markdown-outline-up ()
6797 "Move to previous list item, when in a list, or next heading."
6798 (interactive)
6799 (unless (markdown-up-list)
6800 (markdown-up-heading 1)))
6803 ;;; Marking and Narrowing =====================================================
6805 (defun markdown-mark-paragraph ()
6806 "Put mark at end of this block, point at beginning.
6807 The block marked is the one that contains point or follows point.
6809 Interactively, if this command is repeated or (in Transient Mark
6810 mode) if the mark is active, it marks the next block after the
6811 ones already marked."
6812 (interactive)
6813 (if (or (and (eq last-command this-command) (mark t))
6814 (and transient-mark-mode mark-active))
6815 (set-mark
6816 (save-excursion
6817 (goto-char (mark))
6818 (markdown-forward-paragraph)
6819 (point)))
6820 (let ((beginning-of-defun-function 'markdown-backward-paragraph)
6821 (end-of-defun-function 'markdown-forward-paragraph))
6822 (mark-defun))))
6824 (defun markdown-mark-block ()
6825 "Put mark at end of this block, point at beginning.
6826 The block marked is the one that contains point or follows point.
6828 Interactively, if this command is repeated or (in Transient Mark
6829 mode) if the mark is active, it marks the next block after the
6830 ones already marked."
6831 (interactive)
6832 (if (or (and (eq last-command this-command) (mark t))
6833 (and transient-mark-mode mark-active))
6834 (set-mark
6835 (save-excursion
6836 (goto-char (mark))
6837 (markdown-forward-block)
6838 (point)))
6839 (let ((beginning-of-defun-function 'markdown-backward-block)
6840 (end-of-defun-function 'markdown-forward-block))
6841 (mark-defun))))
6843 (defun markdown-narrow-to-block ()
6844 "Make text outside current block invisible.
6845 The current block is the one that contains point or follows point."
6846 (interactive)
6847 (let ((beginning-of-defun-function 'markdown-backward-block)
6848 (end-of-defun-function 'markdown-forward-block))
6849 (narrow-to-defun)))
6851 (defun markdown-mark-text-block ()
6852 "Put mark at end of this plain text block, point at beginning.
6853 The block marked is the one that contains point or follows point.
6855 Interactively, if this command is repeated or (in Transient Mark
6856 mode) if the mark is active, it marks the next block after the
6857 ones already marked."
6858 (interactive)
6859 (if (or (and (eq last-command this-command) (mark t))
6860 (and transient-mark-mode mark-active))
6861 (set-mark
6862 (save-excursion
6863 (goto-char (mark))
6864 (markdown-end-of-text-block)
6865 (point)))
6866 (let ((beginning-of-defun-function 'markdown-beginning-of-text-block)
6867 (end-of-defun-function 'markdown-end-of-text-block))
6868 (mark-defun))))
6870 (defun markdown-mark-page ()
6871 "Put mark at end of this top level section, point at beginning.
6872 The top level section marked is the one that contains point or
6873 follows point.
6875 Interactively, if this command is repeated or (in Transient Mark
6876 mode) if the mark is active, it marks the next page after the
6877 ones already marked."
6878 (interactive)
6879 (if (or (and (eq last-command this-command) (mark t))
6880 (and transient-mark-mode mark-active))
6881 (set-mark
6882 (save-excursion
6883 (goto-char (mark))
6884 (markdown-forward-page)
6885 (point)))
6886 (let ((beginning-of-defun-function 'markdown-backward-page)
6887 (end-of-defun-function 'markdown-forward-page))
6888 (mark-defun))))
6890 (defun markdown-narrow-to-page ()
6891 "Make text outside current top level section invisible.
6892 The current section is the one that contains point or follows point."
6893 (interactive)
6894 (let ((beginning-of-defun-function 'markdown-backward-page)
6895 (end-of-defun-function 'markdown-forward-page))
6896 (narrow-to-defun)))
6898 (defun markdown-mark-subtree ()
6899 "Mark the current subtree.
6900 This puts point at the start of the current subtree, and mark at the end."
6901 (interactive)
6902 (let ((beg))
6903 (if (markdown-heading-at-point)
6904 (beginning-of-line)
6905 (markdown-previous-visible-heading 1))
6906 (setq beg (point))
6907 (markdown-end-of-subtree)
6908 (push-mark (point) nil t)
6909 (goto-char beg)))
6911 (defun markdown-narrow-to-subtree ()
6912 "Narrow buffer to the current subtree."
6913 (interactive)
6914 (save-excursion
6915 (save-match-data
6916 (narrow-to-region
6917 (progn (markdown-back-to-heading-over-code-block t) (point))
6918 (progn (markdown-end-of-subtree)
6919 (if (and (markdown-heading-at-point) (not (eobp)))
6920 (backward-char 1))
6921 (point))))))
6924 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
6926 (defun markdown-move-up ()
6927 "Move thing at point up.
6928 When in a list item, call `markdown-move-list-item-up'.
6929 When in a table, call `markdown-table-move-row-up'.
6930 Otherwise, move the current heading subtree up with
6931 `markdown-move-subtree-up'."
6932 (interactive)
6933 (cond
6934 ((markdown-list-item-at-point-p)
6935 (call-interactively #'markdown-move-list-item-up))
6936 ((markdown-table-at-point-p)
6937 (call-interactively #'markdown-table-move-row-up))
6939 (call-interactively #'markdown-move-subtree-up))))
6941 (defun markdown-move-down ()
6942 "Move thing at point down.
6943 When in a list item, call `markdown-move-list-item-down'.
6944 Otherwise, move the current heading subtree up with
6945 `markdown-move-subtree-down'."
6946 (interactive)
6947 (cond
6948 ((markdown-list-item-at-point-p)
6949 (call-interactively #'markdown-move-list-item-down))
6950 ((markdown-table-at-point-p)
6951 (call-interactively #'markdown-table-move-row-down))
6953 (call-interactively #'markdown-move-subtree-down))))
6955 (defun markdown-promote ()
6956 "Promote or move element at point to the left.
6957 Depending on the context, this function will promote a heading or
6958 list item at the point, move a table column to the left, or cycle
6959 markup."
6960 (interactive)
6961 (let (bounds)
6962 (cond
6963 ;; Promote atx heading subtree
6964 ((thing-at-point-looking-at markdown-regex-header-atx)
6965 (markdown-promote-subtree))
6966 ;; Promote setext heading
6967 ((thing-at-point-looking-at markdown-regex-header-setext)
6968 (markdown-cycle-setext -1))
6969 ;; Promote horizonal rule
6970 ((thing-at-point-looking-at markdown-regex-hr)
6971 (markdown-cycle-hr -1))
6972 ;; Promote list item
6973 ((setq bounds (markdown-cur-list-item-bounds))
6974 (markdown-promote-list-item bounds))
6975 ;; Move table column to the left
6976 ((markdown-table-at-point-p)
6977 (call-interactively #'markdown-table-move-column-left))
6978 ;; Promote bold
6979 ((thing-at-point-looking-at markdown-regex-bold)
6980 (markdown-cycle-bold))
6981 ;; Promote italic
6982 ((thing-at-point-looking-at markdown-regex-italic)
6983 (markdown-cycle-italic))
6985 (user-error "Nothing to promote at point")))))
6987 (defun markdown-demote ()
6988 "Demote or move element at point to the right.
6989 Depending on the context, this function will demote a heading or
6990 list item at the point, move a table column to the right, or cycle
6991 or remove markup."
6992 (interactive)
6993 (let (bounds)
6994 (cond
6995 ;; Demote atx heading subtree
6996 ((thing-at-point-looking-at markdown-regex-header-atx)
6997 (markdown-demote-subtree))
6998 ;; Demote setext heading
6999 ((thing-at-point-looking-at markdown-regex-header-setext)
7000 (markdown-cycle-setext 1))
7001 ;; Demote horizonal rule
7002 ((thing-at-point-looking-at markdown-regex-hr)
7003 (markdown-cycle-hr 1))
7004 ;; Demote list item
7005 ((setq bounds (markdown-cur-list-item-bounds))
7006 (markdown-demote-list-item bounds))
7007 ;; Move table column to the right
7008 ((markdown-table-at-point-p)
7009 (call-interactively #'markdown-table-move-column-right))
7010 ;; Demote bold
7011 ((thing-at-point-looking-at markdown-regex-bold)
7012 (markdown-cycle-bold))
7013 ;; Demote italic
7014 ((thing-at-point-looking-at markdown-regex-italic)
7015 (markdown-cycle-italic))
7017 (user-error "Nothing to demote at point")))))
7020 ;;; Commands ==================================================================
7022 (defun markdown (&optional output-buffer-name)
7023 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
7024 The output buffer name defaults to `markdown-output-buffer-name'.
7025 Return the name of the output buffer used."
7026 (interactive)
7027 (save-window-excursion
7028 (let ((begin-region)
7029 (end-region))
7030 (if (markdown-use-region-p)
7031 (setq begin-region (region-beginning)
7032 end-region (region-end))
7033 (setq begin-region (point-min)
7034 end-region (point-max)))
7036 (unless output-buffer-name
7037 (setq output-buffer-name markdown-output-buffer-name))
7038 (cond
7039 ;; Handle case when `markdown-command' does not read from stdin
7040 ((and (stringp markdown-command) markdown-command-needs-filename)
7041 (if (not buffer-file-name)
7042 (user-error "Must be visiting a file")
7043 (shell-command (concat markdown-command " "
7044 (shell-quote-argument buffer-file-name))
7045 output-buffer-name)))
7046 ;; Pass region to `markdown-command' via stdin
7048 (let ((buf (get-buffer-create output-buffer-name)))
7049 (with-current-buffer buf
7050 (setq buffer-read-only nil)
7051 (erase-buffer))
7052 (if (stringp markdown-command)
7053 (call-process-region begin-region end-region
7054 shell-file-name nil buf nil
7055 shell-command-switch markdown-command)
7056 (funcall markdown-command begin-region end-region buf))))))
7057 output-buffer-name))
7059 (defun markdown-standalone (&optional output-buffer-name)
7060 "Special function to provide standalone HTML output.
7061 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
7062 (interactive)
7063 (setq output-buffer-name (markdown output-buffer-name))
7064 (with-current-buffer output-buffer-name
7065 (set-buffer output-buffer-name)
7066 (unless (markdown-output-standalone-p)
7067 (markdown-add-xhtml-header-and-footer output-buffer-name))
7068 (goto-char (point-min))
7069 (html-mode))
7070 output-buffer-name)
7072 (defun markdown-other-window (&optional output-buffer-name)
7073 "Run `markdown-command' on current buffer and display in other window.
7074 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7075 that name."
7076 (interactive)
7077 (markdown-display-buffer-other-window
7078 (markdown-standalone output-buffer-name)))
7080 (defun markdown-output-standalone-p ()
7081 "Determine whether `markdown-command' output is standalone XHTML.
7082 Standalone XHTML output is identified by an occurrence of
7083 `markdown-xhtml-standalone-regexp' in the first five lines of output."
7084 (save-excursion
7085 (goto-char (point-min))
7086 (save-match-data
7087 (re-search-forward
7088 markdown-xhtml-standalone-regexp
7089 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
7090 t))))
7092 (defun markdown-stylesheet-link-string (stylesheet-path)
7093 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
7094 stylesheet-path
7095 "\" />"))
7097 (defun markdown-add-xhtml-header-and-footer (title)
7098 "Wrap XHTML header and footer with given TITLE around current buffer."
7099 (goto-char (point-min))
7100 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
7101 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
7102 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
7103 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
7104 "<head>\n<title>")
7105 (insert title)
7106 (insert "</title>\n")
7107 (when (> (length markdown-content-type) 0)
7108 (insert
7109 (format
7110 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
7111 markdown-content-type
7112 (or (and markdown-coding-system
7113 (fboundp 'coding-system-get)
7114 (coding-system-get markdown-coding-system
7115 'mime-charset))
7116 (and (fboundp 'coding-system-get)
7117 (coding-system-get buffer-file-coding-system
7118 'mime-charset))
7119 "iso-8859-1"))))
7120 (if (> (length markdown-css-paths) 0)
7121 (insert (mapconcat #'markdown-stylesheet-link-string
7122 markdown-css-paths "\n")))
7123 (when (> (length markdown-xhtml-header-content) 0)
7124 (insert markdown-xhtml-header-content))
7125 (insert "\n</head>\n\n"
7126 "<body>\n\n")
7127 (goto-char (point-max))
7128 (insert "\n"
7129 "</body>\n"
7130 "</html>\n"))
7132 (defun markdown-preview (&optional output-buffer-name)
7133 "Run `markdown-command' on the current buffer and view output in browser.
7134 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7135 that name."
7136 (interactive)
7137 (browse-url-of-buffer
7138 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
7140 (defun markdown-export-file-name (&optional extension)
7141 "Attempt to generate a filename for Markdown output.
7142 The file extension will be EXTENSION if given, or .html by default.
7143 If the current buffer is visiting a file, we construct a new
7144 output filename based on that filename. Otherwise, return nil."
7145 (when (buffer-file-name)
7146 (unless extension
7147 (setq extension ".html"))
7148 (let ((candidate
7149 (concat
7150 (cond
7151 ((buffer-file-name)
7152 (file-name-sans-extension (buffer-file-name)))
7153 (t (buffer-name)))
7154 extension)))
7155 (cond
7156 ((equal candidate (buffer-file-name))
7157 (concat candidate extension))
7159 candidate)))))
7161 (defun markdown-export (&optional output-file)
7162 "Run Markdown on the current buffer, save to file, and return the filename.
7163 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
7164 generated by `markdown-export-file-name', which will be constructed using the
7165 current filename, but with the extension removed and replaced with .html."
7166 (interactive)
7167 (unless output-file
7168 (setq output-file (markdown-export-file-name ".html")))
7169 (when output-file
7170 (let* ((init-buf (current-buffer))
7171 (init-point (point))
7172 (init-buf-string (buffer-string))
7173 (output-buffer (find-file-noselect output-file))
7174 (output-buffer-name (buffer-name output-buffer)))
7175 (run-hooks 'markdown-before-export-hook)
7176 (markdown-standalone output-buffer-name)
7177 (with-current-buffer output-buffer
7178 (run-hooks 'markdown-after-export-hook)
7179 (save-buffer)
7180 (when markdown-export-kill-buffer (kill-buffer)))
7181 ;; if modified, restore initial buffer
7182 (when (buffer-modified-p init-buf)
7183 (erase-buffer)
7184 (insert init-buf-string)
7185 (save-buffer)
7186 (goto-char init-point))
7187 output-file)))
7189 (defun markdown-export-and-preview ()
7190 "Export to XHTML using `markdown-export' and browse the resulting file."
7191 (interactive)
7192 (browse-url-of-file (markdown-export)))
7194 (defvar markdown-live-preview-buffer nil
7195 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
7196 (make-variable-buffer-local 'markdown-live-preview-buffer)
7198 (defvar markdown-live-preview-source-buffer nil
7199 "Source buffer from which current buffer was generated.
7200 This is the inverse of `markdown-live-preview-buffer'.")
7201 (make-variable-buffer-local 'markdown-live-preview-source-buffer)
7203 (defvar markdown-live-preview-currently-exporting nil)
7205 (defun markdown-live-preview-get-filename ()
7206 "Standardize the filename exported by `markdown-live-preview-export'."
7207 (markdown-export-file-name ".html"))
7209 (defun markdown-live-preview-window-eww (file)
7210 "Preview FILE with eww.
7211 To be used with `markdown-live-preview-window-function'."
7212 (if (require 'eww nil t)
7213 (progn
7214 (eww-open-file file)
7215 (get-buffer "*eww*"))
7216 (error "EWW is not present or not loaded on this version of Emacs")))
7218 (defun markdown-visual-lines-between-points (beg end)
7219 (save-excursion
7220 (goto-char beg)
7221 (cl-loop with count = 0
7222 while (progn (end-of-visual-line)
7223 (and (< (point) end) (line-move-visual 1 t)))
7224 do (cl-incf count)
7225 finally return count)))
7227 (defun markdown-live-preview-window-serialize (buf)
7228 "Get window point and scroll data for all windows displaying BUF."
7229 (when (buffer-live-p buf)
7230 (with-current-buffer buf
7231 (mapcar
7232 (lambda (win)
7233 (with-selected-window win
7234 (let* ((start (window-start))
7235 (pt (window-point))
7236 (pt-or-sym (cond ((= pt (point-min)) 'min)
7237 ((= pt (point-max)) 'max)
7238 (t pt)))
7239 (diff (markdown-visual-lines-between-points
7240 start pt)))
7241 (list win pt-or-sym diff))))
7242 (get-buffer-window-list buf)))))
7244 (defun markdown-get-point-back-lines (pt num-lines)
7245 (save-excursion
7246 (goto-char pt)
7247 (line-move-visual (- num-lines) t)
7248 ;; in testing, can occasionally overshoot the number of lines to traverse
7249 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
7250 (when (> actual-num-lines num-lines)
7251 (line-move-visual (- actual-num-lines num-lines) t)))
7252 (point)))
7254 (defun markdown-live-preview-window-deserialize (window-posns)
7255 "Apply window point and scroll data from WINDOW-POSNS.
7256 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
7257 (cl-destructuring-bind (win pt-or-sym diff) window-posns
7258 (when (window-live-p win)
7259 (with-current-buffer markdown-live-preview-buffer
7260 (set-window-buffer win (current-buffer))
7261 (cl-destructuring-bind (actual-pt actual-diff)
7262 (cl-case pt-or-sym
7263 (min (list (point-min) 0))
7264 (max (list (point-max) diff))
7265 (t (list pt-or-sym diff)))
7266 (set-window-start
7267 win (markdown-get-point-back-lines actual-pt actual-diff))
7268 (set-window-point win actual-pt))))))
7270 (defun markdown-live-preview-export ()
7271 "Export to XHTML using `markdown-export'.
7272 Browse the resulting file within Emacs using
7273 `markdown-live-preview-window-function' Return the buffer
7274 displaying the rendered output."
7275 (interactive)
7276 (let ((filename (markdown-live-preview-get-filename)))
7277 (when filename
7278 (let* ((markdown-live-preview-currently-exporting t)
7279 (cur-buf (current-buffer))
7280 (export-file (markdown-export filename))
7281 ;; get positions in all windows currently displaying output buffer
7282 (window-data
7283 (markdown-live-preview-window-serialize
7284 markdown-live-preview-buffer)))
7285 (save-window-excursion
7286 (let ((output-buffer
7287 (funcall markdown-live-preview-window-function export-file)))
7288 (with-current-buffer output-buffer
7289 (setq markdown-live-preview-source-buffer cur-buf)
7290 (add-hook 'kill-buffer-hook
7291 #'markdown-live-preview-remove-on-kill t t))
7292 (with-current-buffer cur-buf
7293 (setq markdown-live-preview-buffer output-buffer))))
7294 (with-current-buffer cur-buf
7295 ;; reset all windows displaying output buffer to where they were,
7296 ;; now with the new output
7297 (mapc #'markdown-live-preview-window-deserialize window-data)
7298 ;; delete html editing buffer
7299 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
7300 (when (and export-file (file-exists-p export-file)
7301 (eq markdown-live-preview-delete-export
7302 'delete-on-export))
7303 (delete-file export-file))
7304 markdown-live-preview-buffer)))))
7306 (defun markdown-live-preview-remove ()
7307 (when (buffer-live-p markdown-live-preview-buffer)
7308 (kill-buffer markdown-live-preview-buffer))
7309 (setq markdown-live-preview-buffer nil)
7310 ;; if set to 'delete-on-export, the output has already been deleted
7311 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
7312 (let ((outfile-name (markdown-live-preview-get-filename)))
7313 (when (and outfile-name (file-exists-p outfile-name))
7314 (delete-file outfile-name)))))
7316 (defun markdown-get-other-window ()
7317 "Find another window to display preview or output content."
7318 (cond
7319 ((memq markdown-split-window-direction '(vertical below))
7320 (or (window-in-direction 'below) (split-window-vertically)))
7321 ((memq markdown-split-window-direction '(horizontal right))
7322 (or (window-in-direction 'right) (split-window-horizontally)))
7323 (t (split-window-sensibly (get-buffer-window)))))
7325 (defun markdown-display-buffer-other-window (buf)
7326 "Display preview or output buffer BUF in another window."
7327 (let ((cur-buf (current-buffer))
7328 (window (markdown-get-other-window)))
7329 (set-window-buffer window buf)
7330 (set-buffer cur-buf)))
7332 (defun markdown-live-preview-if-markdown ()
7333 (when (and (derived-mode-p 'markdown-mode)
7334 markdown-live-preview-mode)
7335 (unless markdown-live-preview-currently-exporting
7336 (if (buffer-live-p markdown-live-preview-buffer)
7337 (markdown-live-preview-export)
7338 (markdown-display-buffer-other-window
7339 (markdown-live-preview-export))))))
7341 (defun markdown-live-preview-remove-on-kill ()
7342 (cond ((and (derived-mode-p 'markdown-mode)
7343 markdown-live-preview-mode)
7344 (markdown-live-preview-remove))
7345 (markdown-live-preview-source-buffer
7346 (with-current-buffer markdown-live-preview-source-buffer
7347 (setq markdown-live-preview-buffer nil))
7348 (setq markdown-live-preview-source-buffer nil))))
7350 (defun markdown-live-preview-switch-to-output ()
7351 "Switch to output buffer."
7352 (interactive)
7353 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
7354 output buffer in another window."
7355 (if markdown-live-preview-mode
7356 (markdown-display-buffer-other-window (markdown-live-preview-export)))
7357 (markdown-live-preview-mode))
7359 (defun markdown-live-preview-re-export ()
7360 "Re export source buffer."
7361 (interactive)
7362 "If the current buffer is a buffer displaying the exported version of a
7363 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
7364 update this buffer's contents."
7365 (when markdown-live-preview-source-buffer
7366 (with-current-buffer markdown-live-preview-source-buffer
7367 (markdown-live-preview-export))))
7369 (defun markdown-open ()
7370 "Open file for the current buffer with `markdown-open-command'."
7371 (interactive)
7372 (unless markdown-open-command
7373 (user-error "Variable `markdown-open-command' must be set"))
7374 (if (stringp markdown-open-command)
7375 (if (not buffer-file-name)
7376 (user-error "Must be visiting a file")
7377 (save-buffer)
7378 (call-process markdown-open-command nil 0 nil buffer-file-name))
7379 (funcall markdown-open-command))
7380 nil)
7382 (defun markdown-kill-ring-save ()
7383 "Run Markdown on file and store output in the kill ring."
7384 (interactive)
7385 (save-window-excursion
7386 (markdown)
7387 (with-current-buffer markdown-output-buffer-name
7388 (kill-ring-save (point-min) (point-max)))))
7391 ;;; Links =====================================================================
7393 (defun markdown-link-p ()
7394 "Return non-nil when `point' is at a non-wiki link.
7395 See `markdown-wiki-link-p' for more information."
7396 (let ((case-fold-search nil))
7397 (and (not (markdown-wiki-link-p))
7398 (not (markdown-code-block-at-point-p))
7399 (or (thing-at-point-looking-at markdown-regex-link-inline)
7400 (thing-at-point-looking-at markdown-regex-link-reference)
7401 (thing-at-point-looking-at markdown-regex-uri)
7402 (thing-at-point-looking-at markdown-regex-angle-uri)))))
7404 (make-obsolete 'markdown-link-link 'markdown-link-url "v2.3")
7406 (defun markdown-link-at-pos (pos)
7407 "Return properties of link or image at position POS.
7408 Value is a list of elements describing the link:
7409 0. beginning position
7410 1. end position
7411 2. link text
7412 3. URL
7413 4. reference label
7414 5. title text
7415 6. bang (nil or \"!\")"
7416 (save-excursion
7417 (goto-char pos)
7418 (let (begin end text url reference title bang)
7419 (cond
7420 ;; Inline or reference image or link at point.
7421 ((or (thing-at-point-looking-at markdown-regex-link-inline)
7422 (thing-at-point-looking-at markdown-regex-link-reference))
7423 (setq bang (match-string-no-properties 1)
7424 begin (match-beginning 0)
7425 end (match-end 0)
7426 text (match-string-no-properties 3))
7427 (if (char-equal (char-after (match-beginning 5)) ?\[)
7428 ;; Reference link
7429 (setq reference (match-string-no-properties 6))
7430 ;; Inline link
7431 (setq url (match-string-no-properties 6))
7432 (when (match-end 7)
7433 (setq title (substring (match-string-no-properties 7) 1 -1)))))
7434 ;; Angle bracket URI at point.
7435 ((thing-at-point-looking-at markdown-regex-angle-uri)
7436 (setq begin (match-beginning 0)
7437 end (match-end 0)
7438 url (match-string-no-properties 2)))
7439 ;; Plain URI at point.
7440 ((thing-at-point-looking-at markdown-regex-uri)
7441 (setq begin (match-beginning 0)
7442 end (match-end 0)
7443 url (match-string-no-properties 1))))
7444 (list begin end text url reference title bang))))
7446 (defun markdown-link-url ()
7447 "Return the URL part of the regular (non-wiki) link at point.
7448 Works with both inline and reference style links, and with images.
7449 If point is not at a link or the link reference is not defined
7450 returns nil."
7451 (let* ((values (markdown-link-at-pos (point)))
7452 (text (nth 2 values))
7453 (url (nth 3 values))
7454 (ref (nth 4 values)))
7455 (or url (and ref (car (markdown-reference-definition
7456 (downcase (if (string= ref "") text ref))))))))
7458 (defun markdown-follow-link-at-point ()
7459 "Open the current non-wiki link.
7460 If the link is a complete URL, open in browser with `browse-url'.
7461 Otherwise, open with `find-file' after stripping anchor and/or query string.
7462 Translate filenames using `markdown-filename-translate-function'."
7463 (interactive)
7464 (if (markdown-link-p)
7465 (let* ((url (markdown-link-url))
7466 (struct (url-generic-parse-url url))
7467 (full (url-fullness struct))
7468 (file url))
7469 ;; Parse URL, determine fullness, strip query string
7470 (if (fboundp 'url-path-and-query)
7471 (setq file (car (url-path-and-query struct)))
7472 (when (and (setq file (url-filename struct))
7473 (string-match "\\?" file))
7474 (setq file (substring file 0 (match-beginning 0)))))
7475 ;; Open full URLs in browser, files in Emacs
7476 (if full
7477 (browse-url url)
7478 (when (and file (> (length file) 0))
7479 (find-file (funcall markdown-translate-filename-function file)))))
7480 (user-error "Point is not at a Markdown link or URL")))
7482 (defun markdown-fontify-inline-links (last)
7483 "Add text properties to next inline link from point to LAST."
7484 (when (markdown-match-generic-links last nil)
7485 (let* ((link-start (match-beginning 3))
7486 (link-end (match-end 3))
7487 (url-start (match-beginning 6))
7488 (url-end (match-end 6))
7489 (url (match-string-no-properties 6))
7490 (title-start (match-beginning 7))
7491 (title-end (match-end 7))
7492 (title (match-string-no-properties 7))
7493 ;; Markup part
7494 (mp (list 'face 'markdown-markup-face
7495 'invisible 'markdown-markup
7496 'rear-nonsticky t
7497 'font-lock-multiline t))
7498 ;; Link part
7499 (lp (list 'keymap markdown-mode-mouse-map
7500 'face 'markdown-link-face
7501 'mouse-face 'markdown-highlight-face
7502 'font-lock-multiline t
7503 'help-echo (if title (concat title "\n" url) url)))
7504 ;; URL part
7505 (up (list 'keymap markdown-mode-mouse-map
7506 'face 'markdown-url-face
7507 'invisible 'markdown-markup
7508 'mouse-face 'markdown-highlight-face
7509 'font-lock-multiline t))
7510 ;; URL composition character
7511 (url-char (markdown--first-displayable markdown-url-compose-char))
7512 ;; Title part
7513 (tp (list 'face 'markdown-link-title-face
7514 'invisible 'markdown-markup
7515 'font-lock-multiline t)))
7516 (dolist (g '(1 2 4 5 8))
7517 (when (match-end g)
7518 (add-text-properties (match-beginning g) (match-end g) mp)))
7519 (when link-start (add-text-properties link-start link-end lp))
7520 (when url-start (add-text-properties url-start url-end up))
7521 (when title-start (add-text-properties url-end title-end tp))
7522 (when (and markdown-hide-urls url-start)
7523 (compose-region url-start (or title-end url-end) url-char))
7524 t)))
7526 (defun markdown-fontify-reference-links (last)
7527 "Add text properties to next reference link from point to LAST."
7528 (when (markdown-match-generic-links last t)
7529 (let* ((link-start (match-beginning 3))
7530 (link-end (match-end 3))
7531 (ref-start (match-beginning 6))
7532 (ref-end (match-end 6))
7533 ;; Markup part
7534 (mp (list 'face 'markdown-markup-face
7535 'invisible 'markdown-markup
7536 'rear-nonsticky t
7537 'font-lock-multiline t))
7538 ;; Link part
7539 (lp (list 'keymap markdown-mode-mouse-map
7540 'face 'markdown-link-face
7541 'mouse-face 'markdown-highlight-face
7542 'font-lock-multiline t
7543 'help-echo (lambda (_ __ pos)
7544 (save-match-data
7545 (save-excursion
7546 (goto-char pos)
7547 (or (markdown-link-url)
7548 "Undefined reference"))))))
7549 ;; URL composition character
7550 (url-char (markdown--first-displayable markdown-url-compose-char))
7551 ;; Reference part
7552 (rp (list 'face 'markdown-reference-face
7553 'invisible 'markdown-markup
7554 'font-lock-multiline t)))
7555 (dolist (g '(1 2 4 5 8))
7556 (when (match-end g)
7557 (add-text-properties (match-beginning g) (match-end g) mp)))
7558 (when link-start (add-text-properties link-start link-end lp))
7559 (when ref-start (add-text-properties ref-start ref-end rp)
7560 (when (and markdown-hide-urls (> (- ref-end ref-start) 2))
7561 (compose-region ref-start ref-end url-char)))
7562 t)))
7564 (defun markdown-fontify-angle-uris (last)
7565 "Add text properties to angle URIs from point to LAST."
7566 (when (markdown-match-angle-uris last)
7567 (let* ((url-start (match-beginning 2))
7568 (url-end (match-end 2))
7569 ;; Markup part
7570 (mp (list 'face 'markdown-markup-face
7571 'invisible 'markdown-markup
7572 'rear-nonsticky t
7573 'font-lock-multiline t))
7574 ;; URI part
7575 (up (list 'keymap markdown-mode-mouse-map
7576 'face 'markdown-plain-url-face
7577 'mouse-face 'markdown-highlight-face
7578 'font-lock-multiline t)))
7579 (dolist (g '(1 3))
7580 (add-text-properties (match-beginning g) (match-end g) mp))
7581 (add-text-properties url-start url-end up)
7582 t)))
7584 (defun markdown-fontify-plain-uris (last)
7585 "Add text properties to plain URLs from point to LAST."
7586 (when (markdown-match-plain-uris last)
7587 (let* ((start (match-beginning 0))
7588 (end (match-end 0))
7589 (props (list 'keymap markdown-mode-mouse-map
7590 'face 'markdown-plain-url-face
7591 'mouse-face 'markdown-highlight-face
7592 'rear-nonsticky t
7593 'font-lock-multiline t)))
7594 (add-text-properties start end props)
7595 t)))
7597 (defun markdown-toggle-url-hiding (&optional arg)
7598 "Toggle the display or hiding of URLs.
7599 With a prefix argument ARG, enable URL hiding if ARG is positive,
7600 and disable it otherwise."
7601 (interactive (list (or current-prefix-arg 'toggle)))
7602 (setq markdown-hide-urls
7603 (if (eq arg 'toggle)
7604 (not markdown-hide-urls)
7605 (> (prefix-numeric-value arg) 0)))
7606 (if markdown-hide-urls
7607 (message "markdown-mode URL hiding enabled")
7608 (message "markdown-mode URL hiding disabled"))
7609 (markdown-reload-extensions))
7612 ;;; WikiLink Following/Markup =================================================
7614 (defun markdown-wiki-link-p ()
7615 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
7616 A true wiki link name matches `markdown-regex-wiki-link' but does
7617 not match the current file name after conversion. This modifies
7618 the data returned by `match-data'. Note that the potential wiki
7619 link name must be available via `match-string'."
7620 (when markdown-enable-wiki-links
7621 (let ((case-fold-search nil))
7622 (and (thing-at-point-looking-at markdown-regex-wiki-link)
7623 (not (markdown-code-block-at-point-p))
7624 (or (not buffer-file-name)
7625 (not (string-equal (buffer-file-name)
7626 (markdown-convert-wiki-link-to-filename
7627 (markdown-wiki-link-link)))))))))
7629 (defun markdown-wiki-link-link ()
7630 "Return the link part of the wiki link using current match data.
7631 The location of the link component depends on the value of
7632 `markdown-wiki-link-alias-first'."
7633 (if markdown-wiki-link-alias-first
7634 (or (match-string-no-properties 5) (match-string-no-properties 3))
7635 (match-string-no-properties 3)))
7637 (defun markdown-wiki-link-alias ()
7638 "Return the alias or text part of the wiki link using current match data.
7639 The location of the alias component depends on the value of
7640 `markdown-wiki-link-alias-first'."
7641 (if markdown-wiki-link-alias-first
7642 (match-string-no-properties 3)
7643 (or (match-string-no-properties 5) (match-string-no-properties 3))))
7645 (defun markdown-convert-wiki-link-to-filename (name)
7646 "Generate a filename from the wiki link NAME.
7647 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
7648 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
7649 and [[test test]] both map to Test-test.ext. Look in the current
7650 directory first, then in subdirectories if
7651 `markdown-wiki-link-search-subdirectories' is non-nil, and then
7652 in parent directories if
7653 `markdown-wiki-link-search-parent-directories' is non-nil."
7654 (let* ((basename (markdown-replace-regexp-in-string
7655 "[[:space:]\n]" markdown-link-space-sub-char name))
7656 (basename (if (eq major-mode '(gfm-mode gfm-view-mode))
7657 (concat (upcase (substring basename 0 1))
7658 (downcase (substring basename 1 nil)))
7659 basename))
7660 directory extension default candidates dir)
7661 (when buffer-file-name
7662 (setq directory (file-name-directory buffer-file-name)
7663 extension (file-name-extension buffer-file-name)))
7664 (setq default (concat basename
7665 (when extension (concat "." extension))))
7666 (cond
7667 ;; Look in current directory first.
7668 ((or (null buffer-file-name)
7669 (file-exists-p default))
7670 default)
7671 ;; Possibly search in subdirectories, next.
7672 ((and markdown-wiki-link-search-subdirectories
7673 (setq candidates
7674 (markdown-directory-files-recursively
7675 directory (concat "^" default "$"))))
7676 (car candidates))
7677 ;; Possibly search in parent directories as a last resort.
7678 ((and markdown-wiki-link-search-parent-directories
7679 (setq dir (locate-dominating-file directory default)))
7680 (concat dir default))
7681 ;; If nothing is found, return default in current directory.
7682 (t default))))
7684 (defun markdown-follow-wiki-link (name &optional other)
7685 "Follow the wiki link NAME.
7686 Convert the name to a file name and call `find-file'. Ensure that
7687 the new buffer remains in `markdown-mode'. Open the link in another
7688 window when OTHER is non-nil."
7689 (let ((filename (markdown-convert-wiki-link-to-filename name))
7690 (wp (when buffer-file-name
7691 (file-name-directory buffer-file-name))))
7692 (if (not wp)
7693 (user-error "Must be visiting a file")
7694 (when other (other-window 1))
7695 (let ((default-directory wp))
7696 (find-file filename)))
7697 (when (not (eq major-mode 'markdown-mode))
7698 (markdown-mode))))
7700 (defun markdown-follow-wiki-link-at-point (&optional arg)
7701 "Find Wiki Link at point.
7702 With prefix argument ARG, open the file in other window.
7703 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
7704 (interactive "P")
7705 (if (markdown-wiki-link-p)
7706 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
7707 (user-error "Point is not at a Wiki Link")))
7709 (defun markdown-highlight-wiki-link (from to face)
7710 "Highlight the wiki link in the region between FROM and TO using FACE."
7711 (put-text-property from to 'font-lock-face face))
7713 (defun markdown-unfontify-region-wiki-links (from to)
7714 "Remove wiki link faces from the region specified by FROM and TO."
7715 (interactive "*r")
7716 (let ((modified (buffer-modified-p)))
7717 (remove-text-properties from to '(font-lock-face markdown-link-face))
7718 (remove-text-properties from to '(font-lock-face markdown-missing-link-face))
7719 ;; remove-text-properties marks the buffer modified in emacs 24.3,
7720 ;; undo that if it wasn't originally marked modified
7721 (set-buffer-modified-p modified)))
7723 (defun markdown-fontify-region-wiki-links (from to)
7724 "Search region given by FROM and TO for wiki links and fontify them.
7725 If a wiki link is found check to see if the backing file exists
7726 and highlight accordingly."
7727 (goto-char from)
7728 (save-match-data
7729 (while (re-search-forward markdown-regex-wiki-link to t)
7730 (when (not (markdown-code-block-at-point-p))
7731 (let ((highlight-beginning (match-beginning 1))
7732 (highlight-end (match-end 1))
7733 (file-name
7734 (markdown-convert-wiki-link-to-filename
7735 (markdown-wiki-link-link))))
7736 (if (condition-case nil (file-exists-p file-name) (error nil))
7737 (markdown-highlight-wiki-link
7738 highlight-beginning highlight-end 'markdown-link-face)
7739 (markdown-highlight-wiki-link
7740 highlight-beginning highlight-end 'markdown-missing-link-face)))))))
7742 (defun markdown-extend-changed-region (from to)
7743 "Extend region given by FROM and TO so that we can fontify all links.
7744 The region is extended to the first newline before and the first
7745 newline after."
7746 ;; start looking for the first new line before 'from
7747 (goto-char from)
7748 (re-search-backward "\n" nil t)
7749 (let ((new-from (point-min))
7750 (new-to (point-max)))
7751 (if (not (= (point) from))
7752 (setq new-from (point)))
7753 ;; do the same thing for the first new line after 'to
7754 (goto-char to)
7755 (re-search-forward "\n" nil t)
7756 (if (not (= (point) to))
7757 (setq new-to (point)))
7758 (cl-values new-from new-to)))
7760 (defun markdown-check-change-for-wiki-link (from to)
7761 "Check region between FROM and TO for wiki links and re-fontify as needed."
7762 (interactive "*r")
7763 (let* ((modified (buffer-modified-p))
7764 (buffer-undo-list t)
7765 (inhibit-read-only t)
7766 (inhibit-point-motion-hooks t)
7767 deactivate-mark
7768 buffer-file-truename)
7769 (unwind-protect
7770 (save-excursion
7771 (save-match-data
7772 (save-restriction
7773 ;; Extend the region to fontify so that it starts
7774 ;; and ends at safe places.
7775 (cl-multiple-value-bind (new-from new-to)
7776 (markdown-extend-changed-region from to)
7777 (goto-char new-from)
7778 ;; Only refontify when the range contains text with a
7779 ;; wiki link face or if the wiki link regexp matches.
7780 (when (or (markdown-range-property-any
7781 new-from new-to 'font-lock-face
7782 '(markdown-link-face markdown-missing-link-face))
7783 (re-search-forward
7784 markdown-regex-wiki-link new-to t))
7785 ;; Unfontify existing fontification (start from scratch)
7786 (markdown-unfontify-region-wiki-links new-from new-to)
7787 ;; Now do the fontification.
7788 (markdown-fontify-region-wiki-links new-from new-to))))))
7789 (and (not modified)
7790 (buffer-modified-p)
7791 (set-buffer-modified-p nil)))))
7793 (defun markdown-check-change-for-wiki-link-after-change (from to _)
7794 "Check region between FROM and TO for wiki links and re-fontify as needed.
7795 Designed to be used with the `after-change-functions' hook."
7796 (markdown-check-change-for-wiki-link from to))
7798 (defun markdown-fontify-buffer-wiki-links ()
7799 "Refontify all wiki links in the buffer."
7800 (interactive)
7801 (markdown-check-change-for-wiki-link (point-min) (point-max)))
7804 ;;; Following & Doing =========================================================
7806 (defun markdown-follow-thing-at-point (arg)
7807 "Follow thing at point if possible, such as a reference link or wiki link.
7808 Opens inline and reference links in a browser. Opens wiki links
7809 to other files in the current window, or the another window if
7810 ARG is non-nil.
7811 See `markdown-follow-link-at-point' and
7812 `markdown-follow-wiki-link-at-point'."
7813 (interactive "P")
7814 (cond ((markdown-link-p)
7815 (markdown-follow-link-at-point))
7816 ((markdown-wiki-link-p)
7817 (markdown-follow-wiki-link-at-point arg))
7819 (user-error "Nothing to follow at point"))))
7821 (make-obsolete 'markdown-jump 'markdown-do "v2.3")
7823 (defun markdown-do ()
7824 "Do something sensible based on context at point.
7825 Jumps between reference links and definitions; between footnote
7826 markers and footnote text."
7827 (interactive)
7828 (cond
7829 ;; Footnote definition
7830 ((markdown-footnote-text-positions)
7831 (markdown-footnote-return))
7832 ;; Footnote marker
7833 ((markdown-footnote-marker-positions)
7834 (markdown-footnote-goto-text))
7835 ;; Reference link
7836 ((thing-at-point-looking-at markdown-regex-link-reference)
7837 (markdown-reference-goto-definition))
7838 ;; Reference definition
7839 ((thing-at-point-looking-at markdown-regex-reference-definition)
7840 (markdown-reference-goto-link (match-string-no-properties 2)))
7841 ;; GFM task list item
7842 ((markdown-gfm-task-list-item-at-point)
7843 (markdown-toggle-gfm-checkbox))
7844 ;; Align table
7845 ((markdown-table-at-point-p)
7846 (call-interactively #'markdown-table-align))
7847 ;; Otherwise
7849 (markdown-insert-gfm-checkbox))))
7852 ;;; Miscellaneous =============================================================
7854 (defun markdown-compress-whitespace-string (str)
7855 "Compress whitespace in STR and return result.
7856 Leading and trailing whitespace is removed. Sequences of multiple
7857 spaces, tabs, and newlines are replaced with single spaces."
7858 (markdown-replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
7859 (markdown-replace-regexp-in-string "[ \t\n]+" " " str)))
7861 (defun markdown--substitute-command-keys (string)
7862 "Like `substitute-command-keys' but, but prefers control characters.
7863 First pass STRING to `substitute-command-keys' and then
7864 substitute `C-i` for `TAB` and `C-m` for `RET`."
7865 (replace-regexp-in-string
7866 "\\<TAB\\>" "C-i"
7867 (replace-regexp-in-string
7868 "\\<RET\\>" "C-m" (substitute-command-keys string) t) t))
7870 (defun markdown-line-number-at-pos (&optional pos)
7871 "Return (narrowed) buffer line number at position POS.
7872 If POS is nil, use current buffer location.
7873 This is an exact copy of `line-number-at-pos' for use in emacs21."
7874 (let ((opoint (or pos (point))) start)
7875 (save-excursion
7876 (goto-char (point-min))
7877 (setq start (point))
7878 (goto-char opoint)
7879 (forward-line 0)
7880 (1+ (count-lines start (point))))))
7882 (defun markdown-inside-link-p ()
7883 "Return t if point is within a link."
7884 (save-match-data
7885 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
7887 (defun markdown-line-is-reference-definition-p ()
7888 "Return whether the current line is a (non-footnote) reference defition."
7889 (save-excursion
7890 (move-beginning-of-line 1)
7891 (and (looking-at-p markdown-regex-reference-definition)
7892 (not (looking-at-p "[ \t]*\\[^")))))
7894 (defun markdown-adaptive-fill-function ()
7895 "Return prefix for filling paragraph or nil if not determined."
7896 (cond
7897 ;; List item inside blockquote
7898 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
7899 (markdown-replace-regexp-in-string
7900 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
7901 ;; Blockquote
7902 ((looking-at markdown-regex-blockquote)
7903 (buffer-substring-no-properties (match-beginning 0) (match-end 2)))
7904 ;; List items
7905 ((looking-at markdown-regex-list)
7906 (match-string-no-properties 0))
7907 ;; Footnote definition
7908 ((looking-at-p markdown-regex-footnote-definition)
7909 " ") ; four spaces
7910 ;; No match
7911 (t nil)))
7913 (defun markdown-fill-paragraph (&optional justify)
7914 "Fill paragraph at or after point.
7915 This function is like \\[fill-paragraph], but it skips Markdown
7916 code blocks. If the point is in a code block, or just before one,
7917 do not fill. Otherwise, call `fill-paragraph' as usual. If
7918 JUSTIFY is non-nil, justify text as well. Since this function
7919 handles filling itself, it always returns t so that
7920 `fill-paragraph' doesn't run."
7921 (interactive "P")
7922 (unless (or (markdown-code-block-at-point-p)
7923 (save-excursion
7924 (back-to-indentation)
7925 (skip-syntax-forward "-")
7926 (markdown-code-block-at-point-p)))
7927 (fill-paragraph justify))
7930 (make-obsolete 'markdown-fill-forward-paragraph-function
7931 'markdown-fill-forward-paragraph "v2.3")
7933 (defun markdown-fill-forward-paragraph (&optional arg)
7934 "Function used by `fill-paragraph' to move over ARG paragraphs.
7935 This is a `fill-forward-paragraph-function' for `markdown-mode'.
7936 It is called with a single argument specifying the number of
7937 paragraphs to move. Just like `forward-paragraph', it should
7938 return the number of paragraphs left to move."
7939 (or arg (setq arg 1))
7940 (if (> arg 0)
7941 ;; With positive ARG, move across ARG non-code-block paragraphs,
7942 ;; one at a time. When passing a code block, don't decrement ARG.
7943 (while (and (not (eobp))
7944 (> arg 0)
7945 (= (forward-paragraph 1) 0)
7946 (or (markdown-code-block-at-pos (point-at-bol 0))
7947 (setq arg (1- arg)))))
7948 ;; Move backward by one paragraph with negative ARG (always -1).
7949 (let ((start (point)))
7950 (setq arg (forward-paragraph arg))
7951 (while (and (not (eobp))
7952 (progn (move-to-left-margin) (not (eobp)))
7953 (looking-at-p paragraph-separate))
7954 (forward-line 1))
7955 (cond
7956 ;; Move point past whitespace following list marker.
7957 ((looking-at markdown-regex-list)
7958 (goto-char (match-end 0)))
7959 ;; Move point past whitespace following pipe at beginning of line
7960 ;; to handle Pandoc line blocks.
7961 ((looking-at "^|\\s-*")
7962 (goto-char (match-end 0)))
7963 ;; Return point if the paragraph passed was a code block.
7964 ((markdown-code-block-at-pos (point-at-bol 2))
7965 (goto-char start)))))
7966 arg)
7968 (defun markdown--inhibit-electric-quote ()
7969 "Function added to `electric-quote-inhibit-functions'.
7970 Return non-nil if the quote has been inserted inside a code block
7971 or span."
7972 (let ((pos (1- (point))))
7973 (or (markdown-inline-code-at-pos pos)
7974 (markdown-code-block-at-pos pos))))
7977 ;;; Extension Framework =======================================================
7979 (defun markdown-reload-extensions ()
7980 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
7981 (interactive)
7982 (when (member major-mode
7983 '(markdown-mode markdown-view-mode gfm-mode gfm-view-mode))
7984 ;; Refontify buffer
7985 (if (eval-when-compile (fboundp 'font-lock-flush))
7986 ;; Use font-lock-flush in Emacs >= 25.1
7987 (font-lock-flush)
7988 ;; Backwards compatibility for Emacs 24.3-24.5
7989 (when (and font-lock-mode (fboundp 'font-lock-refresh-defaults))
7990 (font-lock-refresh-defaults)))
7991 ;; Add or remove hooks related to extensions
7992 (markdown-setup-wiki-link-hooks)))
7994 (defun markdown-handle-local-variables ()
7995 "Run in `hack-local-variables-hook' to update font lock rules.
7996 Checks to see if there is actually a ‘markdown-mode’ file local variable
7997 before regenerating font-lock rules for extensions."
7998 (when (and (boundp 'file-local-variables-alist)
7999 (or (assoc 'markdown-enable-wiki-links file-local-variables-alist)
8000 (assoc 'markdown-enable-math file-local-variables-alist)))
8001 (when (assoc 'markdown-enable-math file-local-variables-alist)
8002 (markdown-toggle-math markdown-enable-math))
8003 (markdown-reload-extensions)))
8006 ;;; Wiki Links ================================================================
8008 (defun markdown-toggle-wiki-links (&optional arg)
8009 "Toggle support for wiki links.
8010 With a prefix argument ARG, enable wiki link support if ARG is positive,
8011 and disable it otherwise."
8012 (interactive (list (or current-prefix-arg 'toggle)))
8013 (setq markdown-enable-wiki-links
8014 (if (eq arg 'toggle)
8015 (not markdown-enable-wiki-links)
8016 (> (prefix-numeric-value arg) 0)))
8017 (if markdown-enable-wiki-links
8018 (message "markdown-mode wiki link support enabled")
8019 (message "markdown-mode wiki link support disabled"))
8020 (markdown-reload-extensions))
8022 (defun markdown-setup-wiki-link-hooks ()
8023 "Add or remove hooks for fontifying wiki links.
8024 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
8025 ;; Anytime text changes make sure it gets fontified correctly
8026 (if (and markdown-enable-wiki-links
8027 markdown-wiki-link-fontify-missing)
8028 (add-hook 'after-change-functions
8029 'markdown-check-change-for-wiki-link-after-change t t)
8030 (remove-hook 'after-change-functions
8031 'markdown-check-change-for-wiki-link-after-change t))
8032 ;; If we left the buffer there is a really good chance we were
8033 ;; creating one of the wiki link documents. Make sure we get
8034 ;; refontified when we come back.
8035 (if (and markdown-enable-wiki-links
8036 markdown-wiki-link-fontify-missing)
8037 (progn
8038 (add-hook 'window-configuration-change-hook
8039 'markdown-fontify-buffer-wiki-links t t)
8040 (markdown-fontify-buffer-wiki-links))
8041 (remove-hook 'window-configuration-change-hook
8042 'markdown-fontify-buffer-wiki-links t)
8043 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
8046 ;;; Math Support ==============================================================
8048 (make-obsolete 'markdown-enable-math 'markdown-toggle-math "v2.1")
8050 (defconst markdown-mode-font-lock-keywords-math
8051 (list
8052 ;; Equation reference (eq:foo)
8053 '("\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" . ((1 markdown-markup-face)
8054 (2 markdown-reference-face)
8055 (3 markdown-markup-face)))
8056 ;; Equation reference \eqref{foo}
8057 '("\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" . ((1 markdown-markup-face)
8058 (2 markdown-reference-face)
8059 (3 markdown-markup-face))))
8060 "Font lock keywords to add and remove when toggling math support.")
8062 (defun markdown-toggle-math (&optional arg)
8063 "Toggle support for inline and display LaTeX math expressions.
8064 With a prefix argument ARG, enable math mode if ARG is positive,
8065 and disable it otherwise. If called from Lisp, enable the mode
8066 if ARG is omitted or nil."
8067 (interactive (list (or current-prefix-arg 'toggle)))
8068 (setq markdown-enable-math
8069 (if (eq arg 'toggle)
8070 (not markdown-enable-math)
8071 (> (prefix-numeric-value arg) 0)))
8072 (if markdown-enable-math
8073 (progn
8074 (font-lock-add-keywords
8075 'markdown-mode markdown-mode-font-lock-keywords-math)
8076 (message "markdown-mode math support enabled"))
8077 (font-lock-remove-keywords
8078 'markdown-mode markdown-mode-font-lock-keywords-math)
8079 (message "markdown-mode math support disabled"))
8080 (markdown-reload-extensions))
8083 ;;; GFM Checkboxes ============================================================
8085 (define-button-type 'markdown-gfm-checkbox-button
8086 'follow-link t
8087 'face 'markdown-gfm-checkbox-face
8088 'mouse-face 'markdown-highlight-face
8089 'action #'markdown-toggle-gfm-checkbox-button)
8091 (defun markdown-gfm-task-list-item-at-point (&optional bounds)
8092 "Return non-nil if there is a GFM task list item at the point.
8093 Optionally, the list item BOUNDS may be given if available, as
8094 returned by `markdown-cur-list-item-bounds'. When a task list item
8095 is found, the return value is the same value returned by
8096 `markdown-cur-list-item-bounds'."
8097 (unless bounds
8098 (setq bounds (markdown-cur-list-item-bounds)))
8099 (> (length (nth 5 bounds)) 0))
8101 (defun markdown-insert-gfm-checkbox ()
8102 "Add GFM checkbox at point.
8103 Returns t if added.
8104 Returns nil if non-applicable."
8105 (interactive)
8106 (let ((bounds (markdown-cur-list-item-bounds)))
8107 (if bounds
8108 (unless (cl-sixth bounds)
8109 (let ((pos (+ (cl-first bounds) (cl-fourth bounds)))
8110 (markup "[ ] "))
8111 (if (< pos (point))
8112 (save-excursion
8113 (goto-char pos)
8114 (insert markup))
8115 (goto-char pos)
8116 (insert markup))
8117 (syntax-propertize (+ (cl-second bounds) 4))
8119 (unless (save-excursion
8120 (back-to-indentation)
8121 (or (markdown-list-item-at-point-p)
8122 (markdown-heading-at-point)
8123 (markdown-in-comment-p)
8124 (markdown-code-block-at-point-p)))
8125 (let ((pos (save-excursion
8126 (back-to-indentation)
8127 (point)))
8128 (markup (concat (or (save-excursion
8129 (beginning-of-line 0)
8130 (cl-fifth (markdown-cur-list-item-bounds)))
8131 markdown-unordered-list-item-prefix)
8132 "[ ] ")))
8133 (if (< pos (point))
8134 (save-excursion
8135 (goto-char pos)
8136 (insert markup))
8137 (goto-char pos)
8138 (insert markup))
8139 (syntax-propertize (point-at-eol))
8140 t)))))
8142 (defun markdown-toggle-gfm-checkbox ()
8143 "Toggle GFM checkbox at point.
8144 Returns the resulting status as a string, either \"[x]\" or \"[ ]\".
8145 Returns nil if there is no task list item at the point."
8146 (interactive)
8147 (save-match-data
8148 (save-excursion
8149 (let ((bounds (markdown-cur-list-item-bounds)))
8150 (when bounds
8151 ;; Move to beginning of task list item
8152 (goto-char (cl-first bounds))
8153 ;; Advance to column of first non-whitespace after marker
8154 (forward-char (cl-fourth bounds))
8155 (cond ((looking-at "\\[ \\]")
8156 (replace-match
8157 (if markdown-gfm-uppercase-checkbox "[X]" "[x]")
8158 nil t)
8159 (match-string-no-properties 0))
8160 ((looking-at "\\[[xX]\\]")
8161 (replace-match "[ ]" nil t)
8162 (match-string-no-properties 0))))))))
8164 (defun markdown-toggle-gfm-checkbox-button (button)
8165 "Toggle GFM checkbox BUTTON on click."
8166 (save-match-data
8167 (save-excursion
8168 (goto-char (button-start button))
8169 (markdown-toggle-gfm-checkbox))))
8171 (defun markdown-make-gfm-checkboxes-buttons (start end)
8172 "Make GFM checkboxes buttons in region between START and END."
8173 (save-excursion
8174 (goto-char start)
8175 (let ((case-fold-search t))
8176 (save-excursion
8177 (while (re-search-forward markdown-regex-gfm-checkbox end t)
8178 (make-button (match-beginning 1) (match-end 1)
8179 :type 'markdown-gfm-checkbox-button))))))
8181 ;; Called when any modification is made to buffer text.
8182 (defun markdown-gfm-checkbox-after-change-function (beg end _)
8183 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
8184 BEG and END are the limits of scanned region."
8185 (save-excursion
8186 (save-match-data
8187 ;; Rescan between start of line from `beg' and start of line after `end'.
8188 (markdown-make-gfm-checkboxes-buttons
8189 (progn (goto-char beg) (beginning-of-line) (point))
8190 (progn (goto-char end) (forward-line 1) (point))))))
8192 (defun markdown-remove-gfm-checkbox-overlays ()
8193 "Remove all GFM checkbox overlays in buffer."
8194 (save-excursion
8195 (save-restriction
8196 (widen)
8197 (remove-overlays nil nil 'face 'markdown-gfm-checkbox-face))))
8200 ;;; Display inline image =================================================
8202 (defvar markdown-inline-image-overlays nil)
8203 (make-variable-buffer-local 'markdown-inline-image-overlays)
8205 (defun markdown-remove-inline-images ()
8206 "Remove inline image overlays from image links in the buffer.
8207 This can be toggled with `markdown-toggle-inline-images'
8208 or \\[markdown-toggle-inline-images]."
8209 (interactive)
8210 (mapc #'delete-overlay markdown-inline-image-overlays)
8211 (setq markdown-inline-image-overlays nil))
8213 (defun markdown-display-inline-images ()
8214 "Add inline image overlays to image links in the buffer.
8215 This can be toggled with `markdown-toggle-inline-images'
8216 or \\[markdown-toggle-inline-images]."
8217 (interactive)
8218 (unless (display-images-p)
8219 (error "Cannot show images"))
8220 (save-excursion
8221 (save-restriction
8222 (widen)
8223 (goto-char (point-min))
8224 (while (re-search-forward markdown-regex-link-inline nil t)
8225 (let ((start (match-beginning 0))
8226 (end (match-end 0))
8227 (file (match-string-no-properties 6)))
8228 (when (file-exists-p file)
8229 (let* ((abspath (if (file-name-absolute-p file)
8230 file
8231 (concat default-directory file)))
8232 (image
8233 (if (and markdown-max-image-size
8234 (image-type-available-p 'imagemagick))
8235 (create-image
8236 abspath 'imagemagick nil
8237 :max-width (car markdown-max-image-size)
8238 :max-height (cdr markdown-max-image-size))
8239 (create-image abspath))))
8240 (when image
8241 (let ((ov (make-overlay start end)))
8242 (overlay-put ov 'display image)
8243 (overlay-put ov 'face 'default)
8244 (push ov markdown-inline-image-overlays))))))))))
8246 (defun markdown-toggle-inline-images ()
8247 "Toggle inline image overlays in the buffer."
8248 (interactive)
8249 (if markdown-inline-image-overlays
8250 (markdown-remove-inline-images)
8251 (markdown-display-inline-images)))
8254 ;;; GFM Code Block Fontification ==============================================
8256 (defcustom markdown-fontify-code-blocks-natively nil
8257 "When non-nil, fontify code in code blocks using the native major mode.
8258 This only works for fenced code blocks where the language is
8259 specified where we can automatically determine the appropriate
8260 mode to use. The language to mode mapping may be customized by
8261 setting the variable `markdown-code-lang-modes'."
8262 :group 'markdown
8263 :type 'boolean
8264 :safe 'booleanp
8265 :package-version '(markdown-mode . "2.3"))
8267 (defun markdown-toggle-fontify-code-blocks-natively (&optional arg)
8268 "Toggle the native fontification of code blocks.
8269 With a prefix argument ARG, enable if ARG is positive,
8270 and disable otherwise."
8271 (interactive (list (or current-prefix-arg 'toggle)))
8272 (setq markdown-fontify-code-blocks-natively
8273 (if (eq arg 'toggle)
8274 (not markdown-fontify-code-blocks-natively)
8275 (> (prefix-numeric-value arg) 0)))
8276 (if markdown-fontify-code-blocks-natively
8277 (message "markdown-mode native code block fontification enabled")
8278 (message "markdown-mode native code block fontification disabled"))
8279 (markdown-reload-extensions))
8281 ;; This is based on `org-src-lang-modes' from org-src.el
8282 (defcustom markdown-code-lang-modes
8283 '(("ocaml" . tuareg-mode) ("elisp" . emacs-lisp-mode) ("ditaa" . artist-mode)
8284 ("asymptote" . asy-mode) ("dot" . fundamental-mode) ("sqlite" . sql-mode)
8285 ("calc" . fundamental-mode) ("C" . c-mode) ("cpp" . c++-mode)
8286 ("C++" . c++-mode) ("screen" . shell-script-mode) ("shell" . sh-mode)
8287 ("bash" . sh-mode))
8288 "Alist mapping languages to their major mode.
8289 The key is the language name, the value is the major mode. For
8290 many languages this is simple, but for language where this is not
8291 the case, this variable provides a way to simplify things on the
8292 user side. For example, there is no ocaml-mode in Emacs, but the
8293 mode to use is `tuareg-mode'."
8294 :group 'markdown
8295 :type '(repeat
8296 (cons
8297 (string "Language name")
8298 (symbol "Major mode")))
8299 :package-version '(markdown-mode . "2.3"))
8301 (defun markdown-get-lang-mode (lang)
8302 "Return major mode that should be used for LANG.
8303 LANG is a string, and the returned major mode is a symbol."
8304 (cl-find-if
8305 'fboundp
8306 (list (cdr (assoc lang markdown-code-lang-modes))
8307 (cdr (assoc (downcase lang) markdown-code-lang-modes))
8308 (intern (concat lang "-mode"))
8309 (intern (concat (downcase lang) "-mode")))))
8311 (defun markdown-fontify-code-blocks-generic (matcher last)
8312 "Add text properties to next code block from point to LAST.
8313 Use matching function MATCHER."
8314 (when (funcall matcher last)
8315 (save-excursion
8316 (save-match-data
8317 (let* ((start (match-beginning 0))
8318 (end (match-end 0))
8319 ;; Find positions outside opening and closing backquotes.
8320 (bol-prev (progn (goto-char start)
8321 (if (bolp) (point-at-bol 0) (point-at-bol))))
8322 (eol-next (progn (goto-char end)
8323 (if (bolp) (point-at-bol 2) (point-at-bol 3))))
8324 lang)
8325 (if (and markdown-fontify-code-blocks-natively
8326 (setq lang (markdown-code-block-lang)))
8327 (markdown-fontify-code-block-natively lang start end)
8328 (add-text-properties start end '(face markdown-pre-face)))
8329 ;; Set background for block as well as opening and closing lines.
8330 (font-lock-append-text-property
8331 bol-prev eol-next 'face 'markdown-code-face)
8332 ;; Set invisible property for lines before and after, including newline.
8333 (add-text-properties bol-prev start '(invisible markdown-markup))
8334 (add-text-properties end eol-next '(invisible markdown-markup)))))
8337 (defun markdown-fontify-gfm-code-blocks (last)
8338 "Add text properties to next GFM code block from point to LAST."
8339 (markdown-fontify-code-blocks-generic 'markdown-match-gfm-code-blocks last))
8341 (defun markdown-fontify-fenced-code-blocks (last)
8342 "Add text properties to next tilde fenced code block from point to LAST."
8343 (markdown-fontify-code-blocks-generic 'markdown-match-fenced-code-blocks last))
8345 ;; Based on `org-src-font-lock-fontify-block' from org-src.el.
8346 (defun markdown-fontify-code-block-natively (lang start end)
8347 "Fontify given GFM or fenced code block.
8348 This function is called by Emacs for automatic fontification when
8349 `markdown-fontify-code-blocks-natively' is non-nil. LANG is the
8350 language used in the block. START and END specify the block
8351 position."
8352 (let ((lang-mode (markdown-get-lang-mode lang)))
8353 (when (fboundp lang-mode)
8354 (let ((string (buffer-substring-no-properties start end))
8355 (modified (buffer-modified-p))
8356 (markdown-buffer (current-buffer)) pos next)
8357 (remove-text-properties start end '(face nil))
8358 (with-current-buffer
8359 (get-buffer-create
8360 (concat " markdown-code-fontification:" (symbol-name lang-mode)))
8361 ;; Make sure that modification hooks are not inhibited in
8362 ;; the org-src-fontification buffer in case we're called
8363 ;; from `jit-lock-function' (Bug#25132).
8364 (let ((inhibit-modification-hooks nil))
8365 (delete-region (point-min) (point-max))
8366 (insert string " ")) ;; so there's a final property change
8367 (unless (eq major-mode lang-mode) (funcall lang-mode))
8368 (markdown-font-lock-ensure)
8369 (setq pos (point-min))
8370 (while (setq next (next-single-property-change pos 'face))
8371 (let ((val (get-text-property pos 'face)))
8372 (when val
8373 (put-text-property
8374 (+ start (1- pos)) (1- (+ start next)) 'face
8375 val markdown-buffer)))
8376 (setq pos next)))
8377 (add-text-properties
8378 start end
8379 '(font-lock-fontified t fontified t font-lock-multiline t))
8380 (set-buffer-modified-p modified)))))
8382 (require 'edit-indirect nil t)
8383 (defvar edit-indirect-guess-mode-function)
8384 (defvar edit-indirect-after-commit-functions)
8386 (defun markdown--edit-indirect-after-commit-function (_beg end)
8387 "Ensure trailing newlines at the END of code blocks."
8388 (goto-char end)
8389 (unless (eq (char-before) ?\n)
8390 (insert "\n")))
8392 (defun markdown-edit-code-block ()
8393 "Edit Markdown code block in an indirect buffer."
8394 (interactive)
8395 (save-excursion
8396 (if (fboundp 'edit-indirect-region)
8397 (let* ((bounds (markdown-get-enclosing-fenced-block-construct))
8398 (begin (and bounds (goto-char (nth 0 bounds)) (point-at-bol 2)))
8399 (end (and bounds (goto-char (nth 1 bounds)) (point-at-bol 1))))
8400 (if (and begin end)
8401 (let* ((lang (markdown-code-block-lang))
8402 (mode (or (and lang (markdown-get-lang-mode lang))
8403 markdown-edit-code-block-default-mode))
8404 (edit-indirect-guess-mode-function
8405 (lambda (_parent-buffer _beg _end)
8406 (funcall mode))))
8407 (edit-indirect-region begin end 'display-buffer))
8408 (user-error "Not inside a GFM or tilde fenced code block")))
8409 (when (y-or-n-p "Package edit-indirect needed to edit code blocks. Install it now? ")
8410 (progn (package-refresh-contents)
8411 (package-install 'edit-indirect)
8412 (markdown-edit-code-block))))))
8415 ;;; Table Editing
8417 ;; These functions were originally adapted from `org-table.el'.
8419 ;; General helper functions
8421 (defmacro markdown--with-gensyms (symbols &rest body)
8422 (declare (debug (sexp body)) (indent 1))
8423 `(let ,(mapcar (lambda (s)
8424 `(,s (make-symbol (concat "--" (symbol-name ',s)))))
8425 symbols)
8426 ,@body))
8428 (defun markdown--split-string (string &optional separators)
8429 "Splits STRING into substrings at SEPARATORS.
8430 SEPARATORS is a regular expression. If nil it defaults to
8431 `split-string-default-separators'. This version returns no empty
8432 strings if there are matches at the beginning and end of string."
8433 (let ((start 0) notfirst list)
8434 (while (and (string-match
8435 (or separators split-string-default-separators)
8436 string
8437 (if (and notfirst
8438 (= start (match-beginning 0))
8439 (< start (length string)))
8440 (1+ start) start))
8441 (< (match-beginning 0) (length string)))
8442 (setq notfirst t)
8443 (or (eq (match-beginning 0) 0)
8444 (and (eq (match-beginning 0) (match-end 0))
8445 (eq (match-beginning 0) start))
8446 (push (substring string start (match-beginning 0)) list))
8447 (setq start (match-end 0)))
8448 (or (eq start (length string))
8449 (push (substring string start) list))
8450 (nreverse list)))
8452 (defun markdown--string-width (s)
8453 "Return width of string S.
8454 This version ignores characters with invisibility property
8455 `markdown-markup'."
8456 (let (b)
8457 (when (or (eq t buffer-invisibility-spec)
8458 (member 'markdown-markup buffer-invisibility-spec))
8459 (while (setq b (text-property-any
8460 0 (length s)
8461 'invisible 'markdown-markup s))
8462 (setq s (concat
8463 (substring s 0 b)
8464 (substring s (or (next-single-property-change
8465 b 'invisible s)
8466 (length s))))))))
8467 (string-width s))
8469 (defun markdown--remove-invisible-markup (s)
8470 "Remove Markdown markup from string S.
8471 This version removes characters with invisibility property
8472 `markdown-markup'."
8473 (let (b)
8474 (while (setq b (text-property-any
8475 0 (length s)
8476 'invisible 'markdown-markup s))
8477 (setq s (concat
8478 (substring s 0 b)
8479 (substring s (or (next-single-property-change
8480 b 'invisible s)
8481 (length s)))))))
8484 ;; Functions for maintaining tables
8486 (defvar markdown-table-at-point-p-function nil
8487 "Function to decide if point is inside a table.
8489 The indirection serves to differentiate between standard markdown
8490 tables and gfm tables which are less strict about the markup.")
8492 (defconst markdown-table-line-regexp "^[ \t]*|"
8493 "Regexp matching any line inside a table.")
8495 (defconst markdown-table-hline-regexp "^[ \t]*|[-:]"
8496 "Regexp matching hline inside a table.")
8498 (defconst markdown-table-dline-regexp "^[ \t]*|[^-:]"
8499 "Regexp matching dline inside a table.")
8501 (defun markdown-table-at-point-p ()
8502 "Return non-nil when point is inside a table."
8503 (if (functionp markdown-table-at-point-p-function)
8504 (funcall markdown-table-at-point-p-function)
8505 (markdown--table-at-point-p)))
8507 (defun markdown--table-at-point-p ()
8508 "Return non-nil when point is inside a table."
8509 (save-excursion
8510 (beginning-of-line)
8511 (and (looking-at-p markdown-table-line-regexp)
8512 (not (markdown-code-block-at-point-p)))))
8514 (defconst gfm-table-line-regexp "^.?*|"
8515 "Regexp matching any line inside a table.")
8517 (defconst gfm-table-hline-regexp "^-+\\(|-\\)+"
8518 "Regexp matching hline inside a table.")
8520 ;; GFM simplified tables syntax is as follows:
8521 ;; - A header line for the column names, this is any text
8522 ;; separated by `|'.
8523 ;; - Followed by a string -|-|- ..., the number of dashes is optional
8524 ;; but must be higher than 1. The number of separators should match
8525 ;; the number of columns.
8526 ;; - Followed by the rows of data, which has the same format as the
8527 ;; header line.
8528 ;; Example:
8530 ;; foo | bar
8531 ;; ------|---------
8532 ;; bar | baz
8533 ;; bar | baz
8534 (defun gfm--table-at-point-p ()
8535 "Return non-nil when point is inside a gfm-compatible table."
8536 (or (markdown--table-at-point-p)
8537 (save-excursion
8538 (beginning-of-line)
8539 (when (looking-at-p gfm-table-line-regexp)
8540 ;; we might be at the first line of the table, check if the
8541 ;; line below is the hline
8542 (or (save-excursion
8543 (forward-line 1)
8544 (looking-at-p gfm-table-hline-regexp))
8545 ;; go up to find the header
8546 (catch 'done
8547 (while (looking-at-p gfm-table-line-regexp)
8548 (cond
8549 ((looking-at-p gfm-table-hline-regexp)
8550 (throw 'done t))
8551 ((bobp)
8552 (throw 'done nil)))
8553 (forward-line -1))
8554 nil))))))
8556 (defun markdown-table-hline-at-point-p ()
8557 "Return non-nil when point is on a hline in a table.
8558 This function assumes point is on a table."
8559 (save-excursion
8560 (beginning-of-line)
8561 (looking-at-p markdown-table-hline-regexp)))
8563 (defun markdown-table-begin ()
8564 "Find the beginning of the table and return its position.
8565 This function assumes point is on a table."
8566 (save-excursion
8567 (while (and (not (bobp))
8568 (markdown-table-at-point-p))
8569 (forward-line -1))
8570 (unless (eobp)
8571 (forward-line 1))
8572 (point)))
8574 (defun markdown-table-end ()
8575 "Find the end of the table and return its position.
8576 This function assumes point is on a table."
8577 (save-excursion
8578 (while (and (not (eobp))
8579 (markdown-table-at-point-p))
8580 (forward-line 1))
8581 (point)))
8583 (defun markdown-table-get-dline ()
8584 "Return index of the table data line at point.
8585 This function assumes point is on a table."
8586 (let ((pos (point)) (end (markdown-table-end)) (cnt 0))
8587 (save-excursion
8588 (goto-char (markdown-table-begin))
8589 (while (and (re-search-forward
8590 markdown-table-dline-regexp end t)
8591 (setq cnt (1+ cnt))
8592 (< (point-at-eol) pos))))
8593 cnt))
8595 (defun markdown-table-get-column ()
8596 "Return table column at point.
8597 This function assumes point is on a table."
8598 (let ((pos (point)) (cnt 0))
8599 (save-excursion
8600 (beginning-of-line)
8601 (while (search-forward "|" pos t) (setq cnt (1+ cnt))))
8602 cnt))
8604 (defun markdown-table-get-cell (&optional n)
8605 "Return the content of the cell in column N of current row.
8606 N defaults to column at point. This function assumes point is on
8607 a table."
8608 (and n (markdown-table-goto-column n))
8609 (skip-chars-backward "^|\n") (backward-char 1)
8610 (if (looking-at "|[^|\r\n]*")
8611 (let* ((pos (match-beginning 0))
8612 (val (buffer-substring (1+ pos) (match-end 0))))
8613 (goto-char (min (point-at-eol) (+ 2 pos)))
8614 ;; Trim whitespaces
8615 (setq val (replace-regexp-in-string "\\`[ \t]+" "" val)
8616 val (replace-regexp-in-string "[ \t]+\\'" "" val)))
8617 (forward-char 1) ""))
8619 (defun markdown-table-goto-dline (n)
8620 "Go to the Nth data line in the table at point.
8621 Return t when the line exists, nil otherwise. This function
8622 assumes point is on a table."
8623 (goto-char (markdown-table-begin))
8624 (let ((end (markdown-table-end)) (cnt 0))
8625 (while (and (re-search-forward
8626 markdown-table-dline-regexp end t)
8627 (< (setq cnt (1+ cnt)) n)))
8628 (= cnt n)))
8630 (defun markdown-table-goto-column (n &optional on-delim)
8631 "Go to the Nth column in the table line at point.
8632 With optional argument ON-DELIM, stop with point before the left
8633 delimiter of the cell. If there are less than N cells, just go
8634 beyond the last delimiter. This function assumes point is on a
8635 table."
8636 (beginning-of-line 1)
8637 (when (> n 0)
8638 (while (and (> (setq n (1- n)) -1)
8639 (search-forward "|" (point-at-eol) t)))
8640 (if on-delim
8641 (backward-char 1)
8642 (when (looking-at " ") (forward-char 1)))))
8644 (defmacro markdown-table-save-cell (&rest body)
8645 "Save cell at point, execute BODY and restore cell.
8646 This function assumes point is on a table."
8647 (declare (debug (body)))
8648 (markdown--with-gensyms (line column)
8649 `(let ((,line (copy-marker (line-beginning-position)))
8650 (,column (markdown-table-get-column)))
8651 (unwind-protect
8652 (progn ,@body)
8653 (goto-char ,line)
8654 (markdown-table-goto-column ,column)
8655 (set-marker ,line nil)))))
8657 (defun markdown-table-blank-line (s)
8658 "Convert a table line S into a line with blank cells."
8659 (if (string-match "^[ \t]*|-" s)
8660 (setq s (mapconcat
8661 (lambda (x) (if (member x '(?| ?+)) "|" " "))
8662 s ""))
8663 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
8664 (setq s (replace-match
8665 (concat "|" (make-string (length (match-string 1 s)) ?\ ) "|")
8666 t t s)))
8669 (defun markdown-table-colfmt (fmtspec)
8670 "Process column alignment specifier FMTSPEC for tables."
8671 (when (stringp fmtspec)
8672 (mapcar (lambda (x)
8673 (cond ((string-match-p "^:.*:$" x) 'c)
8674 ((string-match-p "^:" x) 'l)
8675 ((string-match-p ":$" x) 'r)
8676 (t 'd)))
8677 (markdown--split-string fmtspec "\\s-*|\\s-*"))))
8679 (defun markdown-table-align ()
8680 "Align table at point.
8681 This function assumes point is on a table."
8682 (interactive)
8683 (let ((begin (markdown-table-begin))
8684 (end (copy-marker (markdown-table-end))))
8685 (markdown-table-save-cell
8686 (goto-char begin)
8687 (let* (fmtspec
8688 ;; Store table indent
8689 (indent (progn (looking-at "[ \t]*") (match-string 0)))
8690 ;; Split table in lines and save column format specifier
8691 (lines (mapcar (lambda (l)
8692 (if (string-match-p "\\`[ \t]*|[-:]" l)
8693 (progn (setq fmtspec (or fmtspec l)) nil) l))
8694 (markdown--split-string (buffer-substring begin end) "\n")))
8695 ;; Split lines in cells
8696 (cells (mapcar (lambda (l) (markdown--split-string l "\\s-*|\\s-*"))
8697 (remq nil lines)))
8698 ;; Calculate maximum number of cells in a line
8699 (maxcells (if cells
8700 (apply #'max (mapcar #'length cells))
8701 (user-error "Empty table")))
8702 ;; Empty cells to fill short lines
8703 (emptycells (make-list maxcells "")) maxwidths)
8704 ;; Calculate maximum width for each column
8705 (dotimes (i maxcells)
8706 (let ((column (mapcar (lambda (x) (or (nth i x) "")) cells)))
8707 (push (apply #'max 1 (mapcar #'markdown--string-width column))
8708 maxwidths)))
8709 (setq maxwidths (nreverse maxwidths))
8710 ;; Process column format specifier
8711 (setq fmtspec (markdown-table-colfmt fmtspec))
8712 ;; Compute formats needed for output of table lines
8713 (let ((hfmt (concat indent "|"))
8714 (rfmt (concat indent "|"))
8715 hfmt1 rfmt1 fmt)
8716 (dolist (width maxwidths (setq hfmt (concat (substring hfmt 0 -1) "|")))
8717 (setq fmt (pop fmtspec))
8718 (cond ((equal fmt 'l) (setq hfmt1 ":%s-|" rfmt1 " %%-%ds |"))
8719 ((equal fmt 'r) (setq hfmt1 "-%s:|" rfmt1 " %%%ds |"))
8720 ((equal fmt 'c) (setq hfmt1 ":%s:|" rfmt1 " %%-%ds |"))
8721 (t (setq hfmt1 "-%s-|" rfmt1 " %%-%ds |")))
8722 (setq rfmt (concat rfmt (format rfmt1 width)))
8723 (setq hfmt (concat hfmt (format hfmt1 (make-string width ?-)))))
8724 ;; Replace modified lines only
8725 (dolist (line lines)
8726 (let ((line (if line
8727 (apply #'format rfmt (append (pop cells) emptycells))
8728 hfmt))
8729 (previous (buffer-substring (point) (line-end-position))))
8730 (if (equal previous line)
8731 (forward-line)
8732 (insert line "\n")
8733 (delete-region (point) (line-beginning-position 2))))))
8734 (set-marker end nil)))))
8736 (defun markdown-table-insert-row (&optional arg)
8737 "Insert a new row above the row at point into the table.
8738 With optional argument ARG, insert below the current row."
8739 (interactive "P")
8740 (unless (markdown-table-at-point-p)
8741 (user-error "Not at a table"))
8742 (let* ((line (buffer-substring
8743 (line-beginning-position) (line-end-position)))
8744 (new (markdown-table-blank-line line)))
8745 (beginning-of-line (if arg 2 1))
8746 (unless (bolp) (insert "\n"))
8747 (insert-before-markers new "\n")
8748 (beginning-of-line 0)
8749 (re-search-forward "| ?" (line-end-position) t)))
8751 (defun markdown-table-delete-row ()
8752 "Delete row or horizontal line at point from the table."
8753 (interactive)
8754 (unless (markdown-table-at-point-p)
8755 (user-error "Not at a table"))
8756 (let ((col (current-column)))
8757 (kill-region (point-at-bol)
8758 (min (1+ (point-at-eol)) (point-max)))
8759 (unless (markdown-table-at-point-p) (beginning-of-line 0))
8760 (move-to-column col)))
8762 (defun markdown-table-move-row (&optional up)
8763 "Move table line at point down.
8764 With optional argument UP, move it up."
8765 (interactive "P")
8766 (unless (markdown-table-at-point-p)
8767 (user-error "Not at a table"))
8768 (let* ((col (current-column)) (pos (point))
8769 (tonew (if up 0 2)) txt)
8770 (beginning-of-line tonew)
8771 (unless (markdown-table-at-point-p)
8772 (goto-char pos) (user-error "Cannot move row further"))
8773 (goto-char pos) (beginning-of-line 1) (setq pos (point))
8774 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8775 (delete-region (point) (1+ (point-at-eol)))
8776 (beginning-of-line tonew)
8777 (insert txt) (beginning-of-line 0)
8778 (move-to-column col)))
8780 (defun markdown-table-move-row-up ()
8781 "Move table row at point up."
8782 (interactive)
8783 (markdown-table-move-row 'up))
8785 (defun markdown-table-move-row-down ()
8786 "Move table row at point down."
8787 (interactive)
8788 (markdown-table-move-row nil))
8790 (defun markdown-table-insert-column ()
8791 "Insert a new table column."
8792 (interactive)
8793 (unless (markdown-table-at-point-p)
8794 (user-error "Not at a table"))
8795 (let* ((col (max 1 (markdown-table-get-column)))
8796 (begin (markdown-table-begin))
8797 (end (copy-marker (markdown-table-end))))
8798 (markdown-table-save-cell
8799 (goto-char begin)
8800 (while (< (point) end)
8801 (markdown-table-goto-column col t)
8802 (if (markdown-table-hline-at-point-p)
8803 (insert "|---")
8804 (insert "| "))
8805 (forward-line)))
8806 (set-marker end nil)
8807 (markdown-table-align)))
8809 (defun markdown-table-delete-column ()
8810 "Delete column at point from table."
8811 (interactive)
8812 (unless (markdown-table-at-point-p)
8813 (user-error "Not at a table"))
8814 (let ((col (markdown-table-get-column))
8815 (begin (markdown-table-begin))
8816 (end (copy-marker (markdown-table-end))))
8817 (markdown-table-save-cell
8818 (goto-char begin)
8819 (while (< (point) end)
8820 (markdown-table-goto-column col t)
8821 (and (looking-at "|[^|\n]+|")
8822 (replace-match "|"))
8823 (forward-line)))
8824 (set-marker end nil)
8825 (markdown-table-goto-column (max 1 (1- col)))
8826 (markdown-table-align)))
8828 (defun markdown-table-move-column (&optional left)
8829 "Move table column at point to the right.
8830 With optional argument LEFT, move it to the left."
8831 (interactive "P")
8832 (unless (markdown-table-at-point-p)
8833 (user-error "Not at a table"))
8834 (let* ((col (markdown-table-get-column))
8835 (col1 (if left (1- col) col))
8836 (colpos (if left (1- col) (1+ col)))
8837 (begin (markdown-table-begin))
8838 (end (copy-marker (markdown-table-end))))
8839 (when (and left (= col 1))
8840 (user-error "Cannot move column further left"))
8841 (when (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8842 (user-error "Cannot move column further right"))
8843 (markdown-table-save-cell
8844 (goto-char begin)
8845 (while (< (point) end)
8846 (markdown-table-goto-column col1 t)
8847 (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8848 (replace-match "|\\2|\\1|"))
8849 (forward-line)))
8850 (set-marker end nil)
8851 (markdown-table-goto-column colpos)
8852 (markdown-table-align)))
8854 (defun markdown-table-move-column-left ()
8855 "Move table column at point to the left."
8856 (interactive)
8857 (markdown-table-move-column 'left))
8859 (defun markdown-table-move-column-right ()
8860 "Move table column at point to the right."
8861 (interactive)
8862 (markdown-table-move-column nil))
8864 (defun markdown-table-next-row ()
8865 "Go to the next row (same column) in the table.
8866 Create new table lines if required."
8867 (interactive)
8868 (unless (markdown-table-at-point-p)
8869 (user-error "Not at a table"))
8870 (if (or (looking-at "[ \t]*$")
8871 (save-excursion (skip-chars-backward " \t") (bolp)))
8872 (newline)
8873 (markdown-table-align)
8874 (let ((col (markdown-table-get-column)))
8875 (beginning-of-line 2)
8876 (if (or (not (markdown-table-at-point-p))
8877 (markdown-table-hline-at-point-p))
8878 (progn
8879 (beginning-of-line 0)
8880 (markdown-table-insert-row 'below)))
8881 (markdown-table-goto-column col)
8882 (skip-chars-backward "^|\n\r")
8883 (when (looking-at " ") (forward-char 1)))))
8885 (defun markdown-table-forward-cell ()
8886 "Go to the next cell in the table.
8887 Create new table lines if required."
8888 (interactive)
8889 (unless (markdown-table-at-point-p)
8890 (user-error "Not at a table"))
8891 (markdown-table-align)
8892 (let ((end (markdown-table-end)))
8893 (when (markdown-table-hline-at-point-p) (end-of-line 1))
8894 (condition-case nil
8895 (progn
8896 (re-search-forward "|" end)
8897 (if (looking-at "[ \t]*$")
8898 (re-search-forward "|" end))
8899 (if (and (looking-at "[-:]")
8900 (re-search-forward "^[ \t]*|\\([^-:]\\)" end t))
8901 (goto-char (match-beginning 1)))
8902 (if (looking-at "[-:]")
8903 (progn
8904 (beginning-of-line 0)
8905 (markdown-table-insert-row 'below))
8906 (when (looking-at " ") (forward-char 1))))
8907 (error (markdown-table-insert-row 'below)))))
8909 (defun markdown-table-backward-cell ()
8910 "Go to the previous cell in the table."
8911 (interactive)
8912 (unless (markdown-table-at-point-p)
8913 (user-error "Not at a table"))
8914 (markdown-table-align)
8915 (when (markdown-table-hline-at-point-p) (end-of-line 1))
8916 (condition-case nil
8917 (progn
8918 (re-search-backward "|" (markdown-table-begin))
8919 (re-search-backward "|" (markdown-table-begin)))
8920 (error (user-error "Cannot move to previous table cell")))
8921 (while (looking-at "|\\([-:]\\|[ \t]*$\\)")
8922 (re-search-backward "|" (markdown-table-begin)))
8923 (when (looking-at "| ?") (goto-char (match-end 0))))
8925 (defun markdown-table-transpose ()
8926 "Transpose table at point.
8927 Horizontal separator lines will be eliminated."
8928 (interactive)
8929 (unless (markdown-table-at-point-p)
8930 (user-error "Not at a table"))
8931 (let* ((table (buffer-substring-no-properties
8932 (markdown-table-begin) (markdown-table-end)))
8933 ;; Convert table to a Lisp structure
8934 (table (delq nil
8935 (mapcar
8936 (lambda (x)
8937 (unless (string-match-p
8938 markdown-table-hline-regexp x)
8939 (markdown--split-string x "\\s-*|\\s-*")))
8940 (markdown--split-string table "[ \t]*\n[ \t]*"))))
8941 (dline_old (markdown-table-get-dline))
8942 (col_old (markdown-table-get-column))
8943 (contents (mapcar (lambda (_)
8944 (let ((tp table))
8945 (mapcar
8946 (lambda (_)
8947 (prog1
8948 (pop (car tp))
8949 (setq tp (cdr tp))))
8950 table)))
8951 (car table))))
8952 (goto-char (markdown-table-begin))
8953 (re-search-forward "|") (backward-char)
8954 (delete-region (point) (markdown-table-end))
8955 (insert (mapconcat
8956 (lambda(x)
8957 (concat "| " (mapconcat 'identity x " | " ) " |\n"))
8958 contents ""))
8959 (markdown-table-goto-dline col_old)
8960 (markdown-table-goto-column dline_old))
8961 (markdown-table-align))
8963 (defun markdown-table-sort-lines (&optional sorting-type)
8964 "Sort table lines according to the column at point.
8966 The position of point indicates the column to be used for
8967 sorting, and the range of lines is the range between the nearest
8968 horizontal separator lines, or the entire table of no such lines
8969 exist. If point is before the first column, user will be prompted
8970 for the sorting column. If there is an active region, the mark
8971 specifies the first line and the sorting column, while point
8972 should be in the last line to be included into the sorting.
8974 The command then prompts for the sorting type which can be
8975 alphabetically or numerically. Sorting in reverse order is also
8976 possible.
8978 If SORTING-TYPE is specified when this function is called from a
8979 Lisp program, no prompting will take place. SORTING-TYPE must be
8980 a character, any of (?a ?A ?n ?N) where the capital letters
8981 indicate that sorting should be done in reverse order."
8982 (interactive)
8983 (unless (markdown-table-at-point-p)
8984 (user-error "Not at a table"))
8985 ;; Set sorting type and column used for sorting
8986 (let ((column (let ((c (markdown-table-get-column)))
8987 (cond ((> c 0) c)
8988 ((called-interactively-p 'any)
8989 (read-number "Use column N for sorting: "))
8990 (t 1))))
8991 (sorting-type
8992 (or sorting-type
8993 (read-char-exclusive
8994 "Sort type: [a]lpha [n]umeric (A/N means reversed): "))))
8995 (save-restriction
8996 ;; Narrow buffer to appropriate sorting area
8997 (if (region-active-p)
8998 (narrow-to-region
8999 (save-excursion
9000 (progn
9001 (goto-char (region-beginning)) (line-beginning-position)))
9002 (save-excursion
9003 (progn
9004 (goto-char (region-end)) (line-end-position))))
9005 (let ((start (markdown-table-begin))
9006 (end (markdown-table-end)))
9007 (narrow-to-region
9008 (save-excursion
9009 (if (re-search-backward
9010 markdown-table-hline-regexp start t)
9011 (line-beginning-position 2)
9012 start))
9013 (if (save-excursion (re-search-forward
9014 markdown-table-hline-regexp end t))
9015 (match-beginning 0)
9016 end))))
9017 ;; Determine arguments for `sort-subr'
9018 (let* ((extract-key-from-cell
9019 (cl-case sorting-type
9020 ((?a ?A) #'markdown--remove-invisible-markup) ;; #'identity)
9021 ((?n ?N) #'string-to-number)
9022 (t (user-error "Invalid sorting type: %c" sorting-type))))
9023 (predicate
9024 (cl-case sorting-type
9025 ((?n ?N) #'<)
9026 ((?a ?A) #'string<))))
9027 ;; Sort selected area
9028 (goto-char (point-min))
9029 (sort-subr (memq sorting-type '(?A ?N))
9030 (lambda ()
9031 (forward-line)
9032 (while (and (not (eobp))
9033 (not (looking-at
9034 markdown-table-dline-regexp)))
9035 (forward-line)))
9036 #'end-of-line
9037 (lambda ()
9038 (funcall extract-key-from-cell
9039 (markdown-table-get-cell column)))
9041 predicate)
9042 (goto-char (point-min))))))
9044 (defun markdown-table-convert-region (begin end &optional separator)
9045 "Convert region from BEGIN to END to table with SEPARATOR.
9047 If every line contains at least one TAB character, the function
9048 assumes that the material is tab separated (TSV). If every line
9049 contains a comma, comma-separated values (CSV) are assumed. If
9050 not, lines are split at whitespace into cells.
9052 You can use a prefix argument to force a specific separator:
9053 \\[universal-argument] once forces CSV, \\[universal-argument]
9054 twice forces TAB, and \\[universal-argument] three times will
9055 prompt for a regular expression to match the separator, and a
9056 numeric argument N indicates that at least N consecutive
9057 spaces, or alternatively a TAB should be used as the separator."
9059 (interactive "r\nP")
9060 (let* ((begin (min begin end)) (end (max begin end)) re)
9061 (goto-char begin) (beginning-of-line 1)
9062 (setq begin (point-marker))
9063 (goto-char end)
9064 (if (bolp) (backward-char 1) (end-of-line 1))
9065 (setq end (point-marker))
9066 (when (equal separator '(64))
9067 (setq separator (read-regexp "Regexp for cell separator: ")))
9068 (unless separator
9069 ;; Get the right cell separator
9070 (goto-char begin)
9071 (setq separator
9072 (cond
9073 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
9074 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
9075 (t 1))))
9076 (goto-char begin)
9077 (if (equal separator '(4))
9078 ;; Parse CSV
9079 (while (< (point) end)
9080 (cond
9081 ((looking-at "^") (insert "| "))
9082 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
9083 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
9084 (replace-match "\\1") (if (looking-at "\"") (insert "\"")))
9085 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
9086 ((looking-at "[ \t]*,") (replace-match " | "))
9087 (t (beginning-of-line 2))))
9088 (setq re
9089 (cond
9090 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
9091 ((equal separator '(16)) "^\\|\t")
9092 ((integerp separator)
9093 (if (< separator 1)
9094 (user-error "Cell separator must contain one or more spaces")
9095 (format "^ *\\| *\t *\\| \\{%d,\\}" separator)))
9096 ((stringp separator) (format "^ *\\|%s" separator))
9097 (t (error "Invalid cell separator"))))
9098 (while (re-search-forward re end t) (replace-match "| " t t)))
9099 (goto-char begin)
9100 (markdown-table-align)))
9103 ;;; ElDoc Support
9105 (defun markdown-eldoc-function ()
9106 "Return a helpful string when appropriate based on context.
9107 * Report URL when point is at a hidden URL.
9108 * Report language name when point is a code block with hidden markup."
9109 (cond
9110 ;; Hidden URL or reference for inline link
9111 ((and (or (thing-at-point-looking-at markdown-regex-link-inline)
9112 (thing-at-point-looking-at markdown-regex-link-reference))
9113 (or markdown-hide-urls markdown-hide-markup))
9114 (let* ((imagep (string-equal (match-string 1) "!"))
9115 (edit-keys (markdown--substitute-command-keys
9116 (if imagep
9117 "\\[markdown-insert-image]"
9118 "\\[markdown-insert-link]")))
9119 (edit-str (propertize edit-keys 'face 'font-lock-constant-face))
9120 (referencep (string-equal (match-string 5) "["))
9121 (object (if referencep "reference" "URL")))
9122 (format "Hidden %s (%s to edit): %s" object edit-str
9123 (if referencep
9124 (concat
9125 (propertize "[" 'face 'markdown-markup-face)
9126 (propertize (match-string-no-properties 6)
9127 'face 'markdown-reference-face)
9128 (propertize "]" 'face 'markdown-markup-face))
9129 (propertize (match-string-no-properties 6)
9130 'face 'markdown-url-face)))))
9131 ;; Hidden language name for fenced code blocks
9132 ((and (markdown-code-block-at-point-p)
9133 (not (get-text-property (point) 'markdown-pre))
9134 markdown-hide-markup)
9135 (let ((lang (save-excursion (markdown-code-block-lang))))
9136 (unless lang (setq lang "[unspecified]"))
9137 (format "Hidden code block language: %s (%s to toggle markup)"
9138 (propertize lang 'face 'markdown-language-keyword-face)
9139 (markdown--substitute-command-keys
9140 "\\[markdown-toggle-markup-hiding]"))))))
9143 ;;; Mode Definition ==========================================================
9145 (defun markdown-show-version ()
9146 "Show the version number in the minibuffer."
9147 (interactive)
9148 (message "markdown-mode, version %s" markdown-mode-version))
9150 (defun markdown-mode-info ()
9151 "Open the `markdown-mode' homepage."
9152 (interactive)
9153 (browse-url "https://jblevins.org/projects/markdown-mode/"))
9155 ;;;###autoload
9156 (define-derived-mode markdown-mode text-mode "Markdown"
9157 "Major mode for editing Markdown files."
9158 ;; Natural Markdown tab width
9159 (setq tab-width 4)
9160 ;; Comments
9161 (setq-local comment-start "<!-- ")
9162 (setq-local comment-end " -->")
9163 (setq-local comment-start-skip "<!--[ \t]*")
9164 (setq-local comment-column 0)
9165 (setq-local comment-auto-fill-only-comments nil)
9166 (setq-local comment-use-syntax t)
9167 ;; Syntax
9168 (add-hook 'syntax-propertize-extend-region-functions
9169 #'markdown-syntax-propertize-extend-region)
9170 (add-hook 'jit-lock-after-change-extend-region-functions
9171 #'markdown-font-lock-extend-region-function t t)
9172 (setq-local syntax-propertize-function #'markdown-syntax-propertize)
9173 (syntax-propertize (point-max)) ;; Propertize before hooks run, etc.
9174 ;; Font lock.
9175 (setq font-lock-defaults
9176 '(markdown-mode-font-lock-keywords
9177 nil nil nil nil
9178 (font-lock-multiline . t)
9179 (font-lock-syntactic-face-function . markdown-syntactic-face)
9180 (font-lock-extra-managed-props . '(composition display invisible))))
9181 (if markdown-hide-markup
9182 (add-to-invisibility-spec 'markdown-markup)
9183 (remove-from-invisibility-spec 'markdown-markup))
9184 ;; Wiki links
9185 (markdown-setup-wiki-link-hooks)
9186 ;; Math mode
9187 (when markdown-enable-math (markdown-toggle-math t))
9188 ;; Add a buffer-local hook to reload after file-local variables are read
9189 (add-hook 'hack-local-variables-hook #'markdown-handle-local-variables nil t)
9190 ;; For imenu support
9191 (setq imenu-create-index-function
9192 (if markdown-nested-imenu-heading-index
9193 #'markdown-imenu-create-nested-index
9194 #'markdown-imenu-create-flat-index))
9195 ;; For menu support in XEmacs
9196 (easy-menu-add markdown-mode-menu markdown-mode-map)
9197 ;; Defun movement
9198 (setq-local beginning-of-defun-function #'markdown-beginning-of-defun)
9199 (setq-local end-of-defun-function #'markdown-end-of-defun)
9200 ;; Paragraph filling
9201 (setq-local fill-paragraph-function #'markdown-fill-paragraph)
9202 (setq-local paragraph-start
9203 ;; Should match start of lines that start or separate paragraphs
9204 (mapconcat #'identity
9206 "\f" ; starts with a literal line-feed
9207 "[ \t\f]*$" ; space-only line
9208 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9209 "[ \t]*[*+-][ \t]+" ; unordered list item
9210 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
9211 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
9212 "[ \t]*:[ \t]+" ; definition
9213 "^|" ; table or Pandoc line block
9215 "\\|"))
9216 (setq-local paragraph-separate
9217 ;; Should match lines that separate paragraphs without being
9218 ;; part of any paragraph:
9219 (mapconcat #'identity
9220 '("[ \t\f]*$" ; space-only line
9221 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9222 ;; The following is not ideal, but the Fill customization
9223 ;; options really only handle paragraph-starting prefixes,
9224 ;; not paragraph-ending suffixes:
9225 ".* $" ; line ending in two spaces
9226 "^#+"
9227 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
9228 "\\|"))
9229 (setq-local adaptive-fill-first-line-regexp "\\`[ \t]*[A-Z]?>[ \t]*?\\'")
9230 (setq-local adaptive-fill-regexp "\\s-*")
9231 (setq-local adaptive-fill-function #'markdown-adaptive-fill-function)
9232 (setq-local fill-forward-paragraph-function #'markdown-fill-forward-paragraph)
9233 ;; Outline mode
9234 (setq-local outline-regexp markdown-regex-header)
9235 (setq-local outline-level #'markdown-outline-level)
9236 ;; Cause use of ellipses for invisible text.
9237 (add-to-invisibility-spec '(outline . t))
9238 ;; ElDoc support
9239 (if (eval-when-compile (fboundp 'add-function))
9240 (add-function :before-until (local 'eldoc-documentation-function)
9241 #'markdown-eldoc-function)
9242 (setq-local eldoc-documentation-function #'markdown-eldoc-function))
9243 ;; Inhibiting line-breaking:
9244 ;; Separating out each condition into a separate function so that users can
9245 ;; override if desired (with remove-hook)
9246 (add-hook 'fill-nobreak-predicate
9247 #'markdown-line-is-reference-definition-p nil t)
9248 (add-hook 'fill-nobreak-predicate
9249 #'markdown-pipe-at-bol-p nil t)
9251 ;; Indentation
9252 (setq-local indent-line-function markdown-indent-function)
9254 ;; Flyspell
9255 (setq-local flyspell-generic-check-word-predicate
9256 #'markdown-flyspell-check-word-p)
9258 ;; Electric quoting
9259 (add-hook 'electric-quote-inhibit-functions
9260 #'markdown--inhibit-electric-quote nil :local)
9262 ;; Backwards compatibility with markdown-css-path
9263 (when (boundp 'markdown-css-path)
9264 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
9265 (add-to-list 'markdown-css-paths markdown-css-path))
9267 ;; Prepare hooks for XEmacs compatibility
9268 (when (featurep 'xemacs)
9269 (make-local-hook 'after-change-functions)
9270 (make-local-hook 'font-lock-extend-region-functions)
9271 (make-local-hook 'window-configuration-change-hook))
9273 ;; Make checkboxes buttons
9274 (when markdown-make-gfm-checkboxes-buttons
9275 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
9276 (add-hook 'after-change-functions #'markdown-gfm-checkbox-after-change-function t t)
9277 (add-hook 'change-major-mode-hook #'markdown-remove-gfm-checkbox-overlays t t))
9279 ;; edit-indirect
9280 (add-hook 'edit-indirect-after-commit-functions
9281 #'markdown--edit-indirect-after-commit-function
9282 nil 'local)
9284 ;; Marginalized headings
9285 (when markdown-marginalize-headers
9286 (add-hook 'window-configuration-change-hook
9287 #'markdown-marginalize-update-current nil t))
9289 ;; add live preview export hook
9290 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
9291 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
9293 ;;;###autoload
9294 (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode) t)
9295 ;;;###autoload
9296 (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode) t)
9299 ;;; GitHub Flavored Markdown Mode ============================================
9301 (defvar gfm-mode-hook nil
9302 "Hook run when entering GFM mode.")
9304 ;;;###autoload
9305 (define-derived-mode gfm-mode markdown-mode "GFM"
9306 "Major mode for editing GitHub Flavored Markdown files."
9307 (setq markdown-link-space-sub-char "-")
9308 (setq markdown-wiki-link-search-subdirectories t)
9309 (setq-local markdown-table-at-point-p-function 'gfm--table-at-point-p)
9310 (markdown-gfm-parse-buffer-for-languages))
9312 (define-obsolete-variable-alias
9313 'gfm-font-lock-keywords
9314 'markdown-mode-font-lock-keywords "v2.4")
9317 ;;; Viewing modes
9319 (defcustom markdown-hide-markup-in-view-modes t
9320 "Enable hidden markup mode in `markdown-view-mode' and `gfm-view-mode'."
9321 :group 'markdown
9322 :type 'boolean
9323 :safe 'booleanp)
9325 (defvar markdown-view-mode-map
9326 (let ((map (make-sparse-keymap)))
9327 (define-key map (kbd "p") #'markdown-outline-previous)
9328 (define-key map (kbd "n") #'markdown-outline-next)
9329 (define-key map (kbd "f") #'markdown-outline-next-same-level)
9330 (define-key map (kbd "b") #'markdown-outline-previous-same-level)
9331 (define-key map (kbd "u") #'markdown-outline-up)
9332 (define-key map (kbd "DEL") #'scroll-down-command)
9333 (define-key map (kbd "SPC") #'scroll-up-command)
9334 (define-key map (kbd ">") #'end-of-buffer)
9335 (define-key map (kbd "<") #'beginning-of-buffer)
9336 (define-key map (kbd "q") #'kill-this-buffer)
9337 (define-key map (kbd "?") #'describe-mode)
9338 map)
9339 "Keymap for `markdown-view-mode'.")
9341 (define-derived-mode markdown-view-mode markdown-mode "Markdown-View"
9342 "Major mode for viewing Markdown content."
9343 (setq-local markdown-hide-markup markdown-hide-markup-in-view-modes)
9344 (read-only-mode 1))
9346 (defvar gfm-view-mode-map
9347 markdown-view-mode-map
9348 "Keymap for `gfm-view-mode'.")
9350 (define-derived-mode gfm-view-mode gfm-mode "GFM-View"
9351 "Major mode for viewing GitHub Flavored Markdown content."
9352 (setq-local markdown-hide-markup markdown-hide-markup-in-view-modes)
9353 (read-only-mode 1))
9356 ;;; Live Preview Mode ============================================
9357 (define-minor-mode markdown-live-preview-mode
9358 "Toggle native previewing on save for a specific markdown file."
9359 :lighter " MD-Preview"
9360 (if markdown-live-preview-mode
9361 (if (markdown-live-preview-get-filename)
9362 (markdown-display-buffer-other-window (markdown-live-preview-export))
9363 (markdown-live-preview-mode -1)
9364 (user-error "Buffer %s does not visit a file" (current-buffer)))
9365 (markdown-live-preview-remove)))
9368 (provide 'markdown-mode)
9370 ;; Local Variables:
9371 ;; indent-tabs-mode: nil
9372 ;; coding: utf-8
9373 ;; End:
9374 ;;; markdown-mode.el ends here