Downcase reference labels in markdown-get-defined-references
[markdown-mode.git] / markdown-mode.el
blobfda415ac981b7219371a44f51086bcbe5ab39e40
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.4") (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-body-preamble ""
357 "Content to include in the XHTML <body> block, before the output."
358 :group 'markdown
359 :type 'string
360 :safe 'stringp
361 :package-version '(markdown-mode . "2.4"))
363 (defcustom markdown-xhtml-body-epilogue ""
364 "Content to include in the XHTML <body> block, after the output."
365 :group 'markdown
366 :type 'string
367 :safe 'stringp
368 :package-version '(markdown-mode . "2.4"))
370 (defcustom markdown-xhtml-standalone-regexp
371 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
372 "Regexp indicating whether `markdown-command' output is standalone XHTML."
373 :group 'markdown
374 :type 'regexp)
376 (defcustom markdown-link-space-sub-char "_"
377 "Character to use instead of spaces when mapping wiki links to filenames."
378 :group 'markdown
379 :type 'string)
381 (defcustom markdown-reference-location 'header
382 "Position where new reference definitions are inserted in the document."
383 :group 'markdown
384 :type '(choice (const :tag "At the end of the document" end)
385 (const :tag "Immediately after the current block" immediately)
386 (const :tag "At the end of the subtree" subtree)
387 (const :tag "Before next header" header)))
389 (defcustom markdown-footnote-location 'end
390 "Position where new footnotes are inserted in the document."
391 :group 'markdown
392 :type '(choice (const :tag "At the end of the document" end)
393 (const :tag "Immediately after the current block" immediately)
394 (const :tag "At the end of the subtree" subtree)
395 (const :tag "Before next header" header)))
397 (defcustom markdown-footnote-display '((raise 0.2) (height 0.8))
398 "Display specification for footnote markers and inline footnotes.
399 By default, footnote text is reduced in size and raised. Set to
400 nil to disable this."
401 :group 'markdown
402 :type '(choice (sexp :tag "Display specification")
403 (const :tag "Don't set display property" nil))
404 :package-version '(markdown-mode . "2.4"))
406 (defcustom markdown-sub-superscript-display
407 '(((raise -0.3) (height 0.7)) . ((raise 0.3) (height 0.7)))
408 "Display specification for subscript and superscripts.
409 The car is used for subscript, the cdr is used for superscripts."
410 :group 'markdown
411 :type '(cons (choice (sexp :tag "Subscript form")
412 (const :tag "No lowering" nil))
413 (choice (sexp :tag "Superscript form")
414 (const :tag "No raising" nil)))
415 :package-version '(markdown-mode . "2.4"))
417 (defcustom markdown-unordered-list-item-prefix " * "
418 "String inserted before unordered list items."
419 :group 'markdown
420 :type 'string)
422 (defcustom markdown-nested-imenu-heading-index t
423 "Use nested or flat imenu heading index.
424 A nested index may provide more natural browsing from the menu,
425 but a flat list may allow for faster keyboard navigation via tab
426 completion."
427 :group 'markdown
428 :type 'boolean
429 :safe 'booleanp
430 :package-version '(markdown-mode . "2.2"))
432 (defcustom markdown-add-footnotes-to-imenu t
433 "Add footnotes to end of imenu heading index."
434 :group 'markdown
435 :type 'boolean
436 :safe 'booleanp
437 :package-version '(markdown-mode . "2.4"))
439 (defcustom markdown-make-gfm-checkboxes-buttons t
440 "When non-nil, make GFM checkboxes into buttons."
441 :group 'markdown
442 :type 'boolean)
444 (defcustom markdown-use-pandoc-style-yaml-metadata nil
445 "When non-nil, allow YAML metadata anywhere in the document."
446 :group 'markdown
447 :type 'boolean)
449 (defcustom markdown-split-window-direction 'any
450 "Preference for splitting windows for static and live preview.
451 The default value is 'any, which instructs Emacs to use
452 `split-window-sensibly' to automatically choose how to split
453 windows based on the values of `split-width-threshold' and
454 `split-height-threshold' and the available windows. To force
455 vertically split (left and right) windows, set this to 'vertical
456 or 'right. To force horizontally split (top and bottom) windows,
457 set this to 'horizontal or 'below."
458 :group 'markdown
459 :type '(choice (const :tag "Automatic" any)
460 (const :tag "Right (vertical)" right)
461 (const :tag "Below (horizontal)" below))
462 :package-version '(markdown-mode . "2.2"))
464 (defcustom markdown-live-preview-window-function
465 'markdown-live-preview-window-eww
466 "Function to display preview of Markdown output within Emacs.
467 Function must update the buffer containing the preview and return
468 the buffer."
469 :group 'markdown
470 :type 'function)
472 (defcustom markdown-live-preview-delete-export 'delete-on-destroy
473 "Delete exported HTML file when using `markdown-live-preview-export'.
474 If set to 'delete-on-export, delete on every export. When set to
475 'delete-on-destroy delete when quitting from command
476 `markdown-live-preview-mode'. Never delete if set to nil."
477 :group 'markdown
478 :type '(choice
479 (const :tag "Delete on every export" delete-on-export)
480 (const :tag "Delete when quitting live preview" delete-on-destroy)
481 (const :tag "Never delete" nil)))
483 (defcustom markdown-list-indent-width 4
484 "Depth of indentation for markdown lists.
485 Used in `markdown-demote-list-item' and
486 `markdown-promote-list-item'."
487 :group 'markdown
488 :type 'integer)
490 (defcustom markdown-enable-prefix-prompts t
491 "Display prompts for certain prefix commands.
492 Set to nil to disable these prompts."
493 :group 'markdown
494 :type 'boolean
495 :safe 'booleanp
496 :package-version '(markdown-mode . "2.3"))
498 (defcustom markdown-gfm-additional-languages nil
499 "Extra languages made available when inserting GFM code blocks.
500 Language strings must have be trimmed of whitespace and not
501 contain any curly braces. They may be of arbitrary
502 capitalization, though."
503 :group 'markdown
504 :type '(repeat (string :validate markdown-validate-language-string)))
506 (defcustom markdown-gfm-use-electric-backquote t
507 "Use `markdown-electric-backquote' when backquote is hit three times."
508 :group 'markdown
509 :type 'boolean)
511 (defcustom markdown-gfm-downcase-languages t
512 "If non-nil, downcase suggested languages.
513 This applies to insertions done with
514 `markdown-electric-backquote'."
515 :group 'markdown
516 :type 'boolean)
518 (defcustom markdown-edit-code-block-default-mode 'normal-mode
519 "Default mode to use for editing code blocks.
520 This mode is used when automatic detection fails, such as for GFM
521 code blocks with no language specified."
522 :group 'markdown
523 :type '(choice function (const :tag "None" nil))
524 :package-version '(markdown-mode . "2.4"))
526 (defcustom markdown-gfm-uppercase-checkbox nil
527 "If non-nil, use [X] for completed checkboxes, [x] otherwise."
528 :group 'markdown
529 :type 'boolean
530 :safe 'booleanp)
532 (defcustom markdown-hide-urls nil
533 "Hide URLs of inline links and reference tags of reference links.
534 Such URLs will be replaced by a single customizable
535 character, defined by `markdown-url-compose-char', but are still part
536 of the buffer. Links can be edited interactively with
537 \\[markdown-insert-link] or, for example, by deleting the final
538 parenthesis to remove the invisibility property. You can also
539 hover your mouse pointer over the link text to see the URL.
540 Set this to a non-nil value to turn this feature on by default.
541 You can interactively set the value of this variable by calling
542 `markdown-toggle-url-hiding', pressing \\[markdown-toggle-url-hiding],
543 or from the menu Markdown > Links & Images menu."
544 :group 'markdown
545 :type 'boolean
546 :safe 'booleanp
547 :package-version '(markdown-mode . "2.3"))
548 (make-variable-buffer-local 'markdown-hide-urls)
550 (defcustom markdown-translate-filename-function #'identity
551 "Function to use to translate filenames when following links.
552 \\<markdown-mode-map>\\[markdown-follow-thing-at-point] and \\[markdown-follow-link-at-point]
553 call this function with the filename as only argument whenever
554 they encounter a filename (instead of a URL) to be visited and
555 use its return value instead of the filename in the link. For
556 example, if absolute filenames are actually relative to a server
557 root directory, you can set
558 `markdown-translate-filename-function' to a function that
559 prepends the root directory to the given filename."
560 :group 'markdown
561 :type 'function
562 :risky t
563 :package-version '(markdown-mode . "2.4"))
565 (defcustom markdown-max-image-size nil
566 "Maximum width and height for displayed inline images.
567 This variable may be nil or a cons cell (MAX-WIDTH . MAX-HEIGHT).
568 When nil, use the actual size. Otherwise, use ImageMagick to
569 resize larger images to be of the given maximum dimensions. This
570 requires Emacs to be built with ImageMagick support."
571 :group 'markdown
572 :package-version '(markdown-mode . "2.4")
573 :type '(choice
574 (const :tag "Use actual image width" nil)
575 (cons (choice (sexp :tag "Maximum width in pixels")
576 (const :tag "No maximum width" nil))
577 (choice (sexp :tag "Maximum height in pixels")
578 (const :tag "No maximum height" nil)))))
581 ;;; Markdown-Specific `rx' Macro
583 ;; Based on python-rx from python.el.
584 (eval-and-compile
585 (defconst markdown-rx-constituents
586 `((newline . ,(rx "\n"))
587 (indent . ,(rx (or (repeat 4 " ") "\t")))
588 (block-end . ,(rx (and (or (one-or-more (zero-or-more blank) "\n") line-end))))
589 (numeral . ,(rx (and (one-or-more (any "0-9#")) ".")))
590 (bullet . ,(rx (any "*+:-")))
591 (list-marker . ,(rx (or (and (one-or-more (any "0-9#")) ".")
592 (any "*+:-"))))
593 (checkbox . ,(rx "[" (any " xX") "]")))
594 "Markdown-specific sexps for `markdown-rx'")
596 (defun markdown-rx-to-string (form &optional no-group)
597 "Markdown mode specialized `rx-to-string' function.
598 This variant supports named Markdown expressions in FORM.
599 NO-GROUP non-nil means don't put shy groups around the result."
600 (let ((rx-constituents (append markdown-rx-constituents rx-constituents)))
601 (rx-to-string form no-group)))
603 (defmacro markdown-rx (&rest regexps)
604 "Markdown mode specialized rx macro.
605 This variant of `rx' supports common Markdown named REGEXPS."
606 (cond ((null regexps)
607 (error "No regexp"))
608 ((cdr regexps)
609 (markdown-rx-to-string `(and ,@regexps) t))
611 (markdown-rx-to-string (car regexps) t)))))
614 ;;; Regular Expressions =======================================================
616 (defconst markdown-regex-comment-start
617 "<!--"
618 "Regular expression matches HTML comment opening.")
620 (defconst markdown-regex-comment-end
621 "--[ \t]*>"
622 "Regular expression matches HTML comment closing.")
624 (defconst markdown-regex-link-inline
625 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)\\((\\)\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?\\()\\)"
626 "Regular expression for a [text](file) or an image link ![text](file).
627 Group 1 matches the leading exclamation point (optional).
628 Group 2 matches the opening square bracket.
629 Group 3 matches the text inside the square brackets.
630 Group 4 matches the closing square bracket.
631 Group 5 matches the opening parenthesis.
632 Group 6 matches the URL.
633 Group 7 matches the title (optional).
634 Group 8 matches the closing parenthesis.")
636 (defconst markdown-regex-link-reference
637 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)[ ]?\\(\\[\\)\\([^]]*?\\)\\(\\]\\)"
638 "Regular expression for a reference link [text][id].
639 Group 1 matches the leading exclamation point (optional).
640 Group 2 matches the opening square bracket for the link text.
641 Group 3 matches the text inside the square brackets.
642 Group 4 matches the closing square bracket for the link text.
643 Group 5 matches the opening square bracket for the reference label.
644 Group 6 matches the reference label.
645 Group 7 matches the closing square bracket for the reference label.")
647 (defconst markdown-regex-reference-definition
648 "^ \\{0,3\\}\\(\\[\\)\\([^]\n]+?\\)\\(\\]\\)\\(:\\)\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
649 "Regular expression for a reference definition.
650 Group 1 matches the opening square bracket.
651 Group 2 matches the reference label.
652 Group 3 matches the closing square bracket.
653 Group 4 matches the colon.
654 Group 5 matches the URL.
655 Group 6 matches the title attribute (optional).")
657 (defconst markdown-regex-footnote
658 "\\(\\[\\^\\)\\(.+?\\)\\(\\]\\)"
659 "Regular expression for a footnote marker [^fn].
660 Group 1 matches the opening square bracket and carat.
661 Group 2 matches only the label, without the surrounding markup.
662 Group 3 matches the closing square bracket.")
664 (defconst markdown-regex-header
665 "^\\(?:\\([^\r\n\t -].*\\)\n\\(?:\\(=+\\)\\|\\(-+\\)\\)\\|\\(#+[ \t]+\\)\\(.*?\\)\\([ \t]*#*\\)\\)$"
666 "Regexp identifying Markdown headings.
667 Group 1 matches the text of a setext heading.
668 Group 2 matches the underline of a level-1 setext heading.
669 Group 3 matches the underline of a level-2 setext heading.
670 Group 4 matches the opening hash marks of an atx heading and whitespace.
671 Group 5 matches the text, without surrounding whitespace, of an atx heading.
672 Group 6 matches the closing whitespace and hash marks of an atx heading.")
674 (defconst markdown-regex-header-setext
675 "^\\([^\r\n\t -].*\\)\n\\(=+\\|-+\\)$"
676 "Regular expression for generic setext-style (underline) headers.")
678 (defconst markdown-regex-header-atx
679 "^\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
680 "Regular expression for generic atx-style (hash mark) headers.")
682 (defconst markdown-regex-hr
683 (rx line-start
684 (group (or (and (repeat 3 (and "*" (? " "))) (* (any "* ")))
685 (and (repeat 3 (and "-" (? " "))) (* (any "- ")))
686 (and (repeat 3 (and "_" (? " "))) (* (any "_ ")))))
687 line-end)
688 "Regular expression for matching Markdown horizontal rules.")
690 (defconst markdown-regex-code
691 "\\(?:\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(?:.\\|\n[^\n]\\)*?[^`]\\)\\(\\2\\)\\)\\(?:[^`]\\|\\'\\)"
692 "Regular expression for matching inline code fragments.
694 Group 1 matches the entire code fragment including the backquotes.
695 Group 2 matches the opening backquotes.
696 Group 3 matches the code fragment itself, without backquotes.
697 Group 4 matches the closing backquotes.
699 The leading, unnumbered group ensures that the leading backquote
700 character is not escaped.
701 The last group, also unnumbered, requires that the character
702 following the code fragment is not a backquote.
703 Note that \\(?:.\\|\n[^\n]\\) matches any character, including newlines,
704 but not two newlines in a row.")
706 (defconst markdown-regex-kbd
707 "\\(<kbd>\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(</kbd>\\)"
708 "Regular expression for matching <kbd> tags.
709 Groups 1 and 3 match the opening and closing tags.
710 Group 2 matches the key sequence.")
712 (defconst markdown-regex-gfm-code-block-open
713 "^[[:blank:]]*\\(```\\)\\([[:blank:]]*{?[[:blank:]]*\\)\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$"
714 "Regular expression matching opening of GFM code blocks.
715 Group 1 matches the opening three backquotes and any following whitespace.
716 Group 2 matches the opening brace (optional) and surrounding whitespace.
717 Group 3 matches the language identifier (optional).
718 Group 4 matches the info string (optional).
719 Group 5 matches the closing brace (optional), whitespace, and newline.
720 Groups need to agree with `markdown-regex-tilde-fence-begin'.")
722 (defconst markdown-regex-gfm-code-block-close
723 "^[[:blank:]]*\\(```\\)\\(\\s *?\\)$"
724 "Regular expression matching closing of GFM code blocks.
725 Group 1 matches the closing three backquotes.
726 Group 2 matches any whitespace and the final newline.")
728 (defconst markdown-regex-pre
729 "^\\( \\|\t\\).*$"
730 "Regular expression for matching preformatted text sections.")
732 (defconst markdown-regex-list
733 (markdown-rx line-start
734 ;; 1. Leading whitespace
735 (group (* blank))
736 ;; 2. List marker: a numeral, bullet, or colon
737 (group list-marker)
738 ;; 3. Trailing whitespace
739 (group (+ blank))
740 ;; 4. Optional checkbox for GFM task list items
741 (opt (group (and checkbox (* blank)))))
742 "Regular expression for matching list items.")
744 (defconst markdown-regex-bold
745 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
746 "Regular expression for matching bold text.
747 Group 1 matches the character before the opening asterisk or
748 underscore, if any, ensuring that it is not a backslash escape.
749 Group 2 matches the entire expression, including delimiters.
750 Groups 3 and 5 matches the opening and closing delimiters.
751 Group 4 matches the text inside the delimiters.")
753 (defconst markdown-regex-italic
754 "\\(?:^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t*]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
755 "Regular expression for matching italic text.
756 The leading unnumbered matches the character before the opening
757 asterisk or underscore, if any, ensuring that it is not a
758 backslash escape.
759 Group 1 matches the entire expression, including delimiters.
760 Groups 2 and 4 matches the opening and closing delimiters.
761 Group 3 matches the text inside the delimiters.")
763 (defconst markdown-regex-strike-through
764 "\\(^\\|[^\\]\\)\\(\\(~~\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(~~\\)\\)"
765 "Regular expression for matching strike-through text.
766 Group 1 matches the character before the opening tilde, if any,
767 ensuring that it is not a backslash escape.
768 Group 2 matches the entire expression, including delimiters.
769 Groups 3 and 5 matches the opening and closing delimiters.
770 Group 4 matches the text inside the delimiters.")
772 (defconst markdown-regex-gfm-italic
773 "\\(?:^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\2\\|[^ ]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
774 "Regular expression for matching italic text in GitHub Flavored Markdown.
775 Underscores in words are not treated as special.
776 Group 1 matches the entire expression, including delimiters.
777 Groups 2 and 4 matches the opening and closing delimiters.
778 Group 3 matches the text inside the delimiters.")
780 (defconst markdown-regex-blockquote
781 "^[ \t]*\\([A-Z]?>\\)\\([ \t]*\\)\\(.*\\)$"
782 "Regular expression for matching blockquote lines.
783 Also accounts for a potential capital letter preceding the angle
784 bracket, for use with Leanpub blocks (asides, warnings, info
785 blocks, etc.).
786 Group 1 matches the leading angle bracket.
787 Group 2 matches the separating whitespace.
788 Group 3 matches the text.")
790 (defconst markdown-regex-line-break
791 "[^ \n\t][ \t]*\\( \\)$"
792 "Regular expression for matching line breaks.")
794 (defconst markdown-regex-wiki-link
795 "\\(?:^\\|[^\\]\\)\\(\\(\\[\\[\\)\\([^]|]+\\)\\(?:\\(|\\)\\([^]]+\\)\\)?\\(\\]\\]\\)\\)"
796 "Regular expression for matching wiki links.
797 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
798 wiki links of the form [[PageName|link text]].
799 The meanings of the first and second components depend
800 on the value of `markdown-wiki-link-alias-first'.
802 Group 1 matches the entire link.
803 Group 2 matches the opening square brackets.
804 Group 3 matches the first component of the wiki link.
805 Group 4 matches the pipe separator, when present.
806 Group 5 matches the second component of the wiki link, when present.
807 Group 6 matches the closing square brackets.")
809 (defconst markdown-regex-uri
810 (concat "\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+\\)")
811 "Regular expression for matching inline URIs.")
813 (defconst markdown-regex-angle-uri
814 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
815 "Regular expression for matching inline URIs in angle brackets.")
817 (defconst markdown-regex-email
818 "<\\(\\(?:\\sw\\|\\s_\\|\\s.\\)+@\\(?:\\sw\\|\\s_\\|\\s.\\)+\\)>"
819 "Regular expression for matching inline email addresses.")
821 (defsubst markdown-make-regex-link-generic ()
822 "Make regular expression for matching any recognized link."
823 (concat "\\(?:" markdown-regex-link-inline
824 (when markdown-enable-wiki-links
825 (concat "\\|" markdown-regex-wiki-link))
826 "\\|" markdown-regex-link-reference
827 "\\|" markdown-regex-angle-uri "\\)"))
829 (defconst markdown-regex-gfm-checkbox
830 " \\(\\[[ xX]\\]\\) "
831 "Regular expression for matching GFM checkboxes.
832 Group 1 matches the text to become a button.")
834 (defconst markdown-regex-blank-line
835 "^[[:blank:]]*$"
836 "Regular expression that matches a blank line.")
838 (defconst markdown-regex-block-separator
839 "\n[\n\t\f ]*\n"
840 "Regular expression for matching block boundaries.")
842 (defconst markdown-regex-block-separator-noindent
843 (concat "\\(\\`\\|\\(" markdown-regex-block-separator "\\)[^\n\t\f ]\\)")
844 "Regexp for block separators before lines with no indentation.")
846 (defconst markdown-regex-math-inline-single
847 "\\(?:^\\|[^\\]\\)\\(\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\)"
848 "Regular expression for itex $..$ math mode expressions.
849 Groups 1 and 3 match the opening and closing dollar signs.
850 Group 2 matches the mathematical expression contained within.")
852 (defconst markdown-regex-math-inline-double
853 "\\(?:^\\|[^\\]\\)\\(\\$\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\$\\)"
854 "Regular expression for itex $$..$$ math mode expressions.
855 Groups 1 and 3 match opening and closing dollar signs.
856 Group 2 matches the mathematical expression contained within.")
858 (defconst markdown-regex-math-display
859 (rx line-start (* blank)
860 (group (group (repeat 1 2 "\\")) "[")
861 (group (*? anything))
862 (group (backref 2) "]")
863 line-end)
864 "Regular expression for \[..\] or \\[..\\] display math.
865 Groups 1 and 4 match the opening and closing markup.
866 Group 3 matches the mathematical expression contained within.
867 Group 2 matches the opening slashes, and is used internally to
868 match the closing slashes.")
870 (defsubst markdown-make-tilde-fence-regex (num-tildes &optional end-of-line)
871 "Return regexp matching a tilde code fence at least NUM-TILDES long.
872 END-OF-LINE is the regexp construct to indicate end of line; $ if
873 missing."
874 (format "%s%d%s%s" "^[[:blank:]]*\\([~]\\{" num-tildes ",\\}\\)"
875 (or end-of-line "$")))
877 (defconst markdown-regex-tilde-fence-begin
878 (markdown-make-tilde-fence-regex
879 3 "\\([[:blank:]]*{?\\)[[:blank:]]*\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$")
880 "Regular expression for matching tilde-fenced code blocks.
881 Group 1 matches the opening tildes.
882 Group 2 matches (optional) opening brace and surrounding whitespace.
883 Group 3 matches the language identifier (optional).
884 Group 4 matches the info string (optional).
885 Group 5 matches the closing brace (optional) and any surrounding whitespace.
886 Groups need to agree with `markdown-regex-gfm-code-block-open'.")
888 (defconst markdown-regex-declarative-metadata
889 "^\\([[:alpha:]][[:alpha:] _-]*?\\)\\([:=][ \t]*\\)\\(.*\\)$"
890 "Regular expression for matching declarative metadata statements.
891 This matches MultiMarkdown metadata as well as YAML and TOML
892 assignments such as the following:
894 variable: value
898 variable = value")
900 (defconst markdown-regex-pandoc-metadata
901 "^\\(%\\)\\([ \t]*\\)\\(.*\\(?:\n[ \t]+.*\\)*\\)"
902 "Regular expression for matching Pandoc metadata.")
904 (defconst markdown-regex-yaml-metadata-border
905 "\\(-\\{3\\}\\)$"
906 "Regular expression for matching YAML metadata.")
908 (defconst markdown-regex-yaml-pandoc-metadata-end-border
909 "^\\(\\.\\{3\\}\\|\\-\\{3\\}\\)$"
910 "Regular expression for matching YAML metadata end borders.")
912 (defsubst markdown-get-yaml-metadata-start-border ()
913 "Return YAML metadata start border depending upon whether Pandoc is used."
914 (concat
915 (if markdown-use-pandoc-style-yaml-metadata "^" "\\`")
916 markdown-regex-yaml-metadata-border))
918 (defsubst markdown-get-yaml-metadata-end-border (_)
919 "Return YAML metadata end border depending upon whether Pandoc is used."
920 (if markdown-use-pandoc-style-yaml-metadata
921 markdown-regex-yaml-pandoc-metadata-end-border
922 markdown-regex-yaml-metadata-border))
924 (defconst markdown-regex-inline-attributes
925 "[ \t]*\\({:?\\)[ \t]*\\(\\(#[[:alpha:]_.:-]+\\|\\.[[:alpha:]_.:-]+\\|\\w+=['\"]?[^\n'\"]*['\"]?\\),?[ \t]*\\)+\\(}\\)[ \t]*$"
926 "Regular expression for matching inline identifiers or attribute lists.
927 Compatible with Pandoc, Python Markdown, PHP Markdown Extra, and Leanpub.")
929 (defconst markdown-regex-leanpub-sections
930 (concat
931 "^\\({\\)\\("
932 (regexp-opt '("frontmatter" "mainmatter" "backmatter" "appendix" "pagebreak"))
933 "\\)\\(}\\)[ \t]*\n")
934 "Regular expression for Leanpub section markers and related syntax.")
936 (defconst markdown-regex-sub-superscript
937 "\\(?:^\\|[^\\~^]\\)\\(\\([~^]\\)\\([[:alnum:]]+\\)\\(\\2\\)\\)"
938 "The regular expression matching a sub- or superscript.
939 The leading un-numbered group matches the character before the
940 opening tilde or carat, if any, ensuring that it is not a
941 backslash escape, carat, or tilde.
942 Group 1 matches the entire expression, including markup.
943 Group 2 matches the opening markup--a tilde or carat.
944 Group 3 matches the text inside the delimiters.
945 Group 4 matches the closing markup--a tilde or carat.")
947 (defconst markdown-regex-include
948 "^\\(<<\\)\\(?:\\(\\[\\)\\(.*\\)\\(\\]\\)\\)?\\(?:\\((\\)\\(.*\\)\\()\\)\\)?\\(?:\\({\\)\\(.*\\)\\(}\\)\\)?$"
949 "Regular expression matching common forms of include syntax.
950 Marked 2, Leanpub, and other processors support some of these forms:
952 <<[sections/section1.md]
953 <<(folder/filename)
954 <<[Code title](folder/filename)
955 <<{folder/raw_file.html}
957 Group 1 matches the opening two angle brackets.
958 Groups 2-4 match the opening square bracket, the text inside,
959 and the closing square bracket, respectively.
960 Groups 5-7 match the opening parenthesis, the text inside, and
961 the closing parenthesis.
962 Groups 8-10 match the opening brace, the text inside, and the brace.")
964 (defconst markdown-regex-pandoc-inline-footnote
965 "\\(\\^\\)\\(\\[\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(\\]\\)"
966 "Regular expression for Pandoc inline footnote^[footnote text].
967 Group 1 matches the opening caret.
968 Group 2 matches the opening square bracket.
969 Group 3 matches the footnote text, without the surrounding markup.
970 Group 4 matches the closing square bracket.")
972 (defconst markdown-regex-html-attr
973 "\\(\\<[[:alpha:]:-]+\\>\\)\\(\\s-*\\(=\\)\\s-*\\(\".*?\"\\|'.*?'\\|[^'\">[:space:]]+\\)?\\)?"
974 "Regular expression for matching HTML attributes and values.
975 Group 1 matches the attribute name.
976 Group 2 matches the following whitespace, equals sign, and value, if any.
977 Group 3 matches the equals sign, if any.
978 Group 4 matches single-, double-, or un-quoted attribute values.")
980 (defconst markdown-regex-html-tag
981 (concat "\\(</?\\)\\(\\w+\\)\\(\\(\\s-+" markdown-regex-html-attr
982 "\\)+\\s-*\\|\\s-*\\)\\(/?>\\)")
983 "Regular expression for matching HTML tags.
984 Groups 1 and 9 match the beginning and ending angle brackets and slashes.
985 Group 2 matches the tag name.
986 Group 3 matches all attributes and whitespace following the tag name.")
988 (defconst markdown-regex-html-entity
989 "\\(&#?[[:alnum:]]+;\\)"
990 "Regular expression for matching HTML entities.")
993 ;;; Syntax ====================================================================
995 (defvar markdown--syntax-properties
996 (list 'markdown-tilde-fence-begin nil
997 'markdown-tilde-fence-end nil
998 'markdown-fenced-code nil
999 'markdown-yaml-metadata-begin nil
1000 'markdown-yaml-metadata-end nil
1001 'markdown-yaml-metadata-section nil
1002 'markdown-gfm-block-begin nil
1003 'markdown-gfm-block-end nil
1004 'markdown-gfm-code nil
1005 'markdown-list-item nil
1006 'markdown-pre nil
1007 'markdown-blockquote nil
1008 'markdown-hr nil
1009 'markdown-comment nil
1010 'markdown-heading nil
1011 'markdown-heading-1-setext nil
1012 'markdown-heading-2-setext nil
1013 'markdown-heading-1-atx nil
1014 'markdown-heading-2-atx nil
1015 'markdown-heading-3-atx nil
1016 'markdown-heading-4-atx nil
1017 'markdown-heading-5-atx nil
1018 'markdown-heading-6-atx nil
1019 'markdown-metadata-key nil
1020 'markdown-metadata-value nil
1021 'markdown-metadata-markup nil)
1022 "Property list of all Markdown syntactic properties.")
1024 (defsubst markdown-in-comment-p (&optional pos)
1025 "Return non-nil if POS is in a comment.
1026 If POS is not given, use point instead."
1027 (get-text-property (or pos (point)) 'markdown-comment))
1029 (defun markdown-syntax-propertize-extend-region (start end)
1030 "Extend START to END region to include an entire block of text.
1031 This helps improve syntax analysis for block constructs.
1032 Returns a cons (NEW-START . NEW-END) or nil if no adjustment should be made.
1033 Function is called repeatedly until it returns nil. For details, see
1034 `syntax-propertize-extend-region-functions'."
1035 (save-match-data
1036 (save-excursion
1037 (let* ((new-start (progn (goto-char start)
1038 (skip-chars-forward "\n")
1039 (if (re-search-backward "\n\n" nil t)
1040 (min start (match-end 0))
1041 (point-min))))
1042 (new-end (progn (goto-char end)
1043 (skip-chars-backward "\n")
1044 (if (re-search-forward "\n\n" nil t)
1045 (max end (match-beginning 0))
1046 (point-max))))
1047 (code-match (markdown--code-block-at-pos-no-syntax new-start))
1048 (new-start (or (and code-match (cl-first code-match)) new-start))
1049 (code-match (and (< end (point-max))
1050 (markdown--code-block-at-pos-no-syntax end)))
1051 (new-end (or (and code-match (cl-second code-match)) new-end)))
1052 (unless (and (eq new-start start) (eq new-end end))
1053 (cons new-start (min new-end (point-max))))))))
1055 (defun markdown-font-lock-extend-region-function (start end _)
1056 "Used in `jit-lock-after-change-extend-region-functions'.
1057 Delegates to `markdown-syntax-propertize-extend-region'. START
1058 and END are the previous region to refontify."
1059 (let ((res (markdown-syntax-propertize-extend-region start end)))
1060 (when res
1061 ;; syntax-propertize-function is not called when character at
1062 ;; (point-max) is deleted, but font-lock-extend-region-functions
1063 ;; are called. Force a syntax property update in that case.
1064 (when (= end (point-max))
1065 ;; This function is called in a buffer modification hook.
1066 ;; `markdown-syntax-propertize' doesn't save the match data,
1067 ;; so we have to do it here.
1068 (save-match-data
1069 (markdown-syntax-propertize (car res) (cdr res))))
1070 (setq jit-lock-start (car res)
1071 jit-lock-end (cdr res)))))
1073 (defun markdown--cur-list-item-bounds ()
1074 "Return a list describing the list item at point.
1075 Assumes that match data is set for `markdown-regex-list'. See the
1076 documentation for `markdown-cur-list-item-bounds' for the format of
1077 the returned list."
1078 (save-excursion
1079 (let* ((begin (match-beginning 0))
1080 (indent (length (match-string-no-properties 1)))
1081 (nonlist-indent (- (match-end 3) (match-beginning 0)))
1082 (marker (buffer-substring-no-properties
1083 (match-beginning 2) (match-end 3)))
1084 (checkbox (match-string-no-properties 4))
1085 (match (butlast (match-data t)))
1086 (end (markdown-cur-list-item-end nonlist-indent)))
1087 (list begin end indent nonlist-indent marker checkbox match))))
1089 (defun markdown--append-list-item-bounds (marker indent cur-bounds bounds)
1090 "Update list item BOUNDS given list MARKER, block INDENT, and CUR-BOUNDS.
1091 Here, MARKER is a string representing the type of list and INDENT
1092 is an integer giving the indentation, in spaces, of the current
1093 block. CUR-BOUNDS is a list of the form returned by
1094 `markdown-cur-list-item-bounds' and BOUNDS is a list of bounds
1095 values for parent list items. When BOUNDS is nil, it means we are
1096 at baseline (not inside of a nested list)."
1097 (let ((prev-indent (or (cl-third (car bounds)) 0)))
1098 (cond
1099 ;; New list item at baseline.
1100 ((and marker (null bounds))
1101 (list cur-bounds))
1102 ;; List item with greater indentation (four or more spaces).
1103 ;; Increase list level by consing CUR-BOUNDS onto BOUNDS.
1104 ((and marker (>= indent (+ prev-indent 4)))
1105 (cons cur-bounds bounds))
1106 ;; List item with greater or equal indentation (less than four spaces).
1107 ;; Keep list level the same by replacing the car of BOUNDS.
1108 ((and marker (>= indent prev-indent))
1109 (cons cur-bounds (cdr bounds)))
1110 ;; Lesser indentation level.
1111 ;; Pop appropriate number of elements off BOUNDS list (e.g., lesser
1112 ;; indentation could move back more than one list level). Note
1113 ;; that this block need not be the beginning of list item.
1114 ((< indent prev-indent)
1115 (while (and (> (length bounds) 1)
1116 (setq prev-indent (cl-third (cadr bounds)))
1117 (< indent (+ prev-indent 4)))
1118 (setq bounds (cdr bounds)))
1119 (cons cur-bounds bounds))
1120 ;; Otherwise, do nothing.
1121 (t bounds))))
1123 (defun markdown-syntax-propertize-list-items (start end)
1124 "Propertize list items from START to END.
1125 Stores nested list item information in the `markdown-list-item'
1126 text property to make later syntax analysis easier. The value of
1127 this property is a list with elements of the form (begin . end)
1128 giving the bounds of the current and parent list items."
1129 (save-excursion
1130 (goto-char start)
1131 (let (bounds level pre-regexp)
1132 ;; Find a baseline point with zero list indentation
1133 (markdown-search-backward-baseline)
1134 ;; Search for all list items between baseline and END
1135 (while (and (< (point) end)
1136 (re-search-forward markdown-regex-list end 'limit))
1137 ;; Level of list nesting
1138 (setq level (length bounds))
1139 ;; Pre blocks need to be indented one level past the list level
1140 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ level)))
1141 (beginning-of-line)
1142 (cond
1143 ;; Reset at headings, horizontal rules, and top-level blank lines.
1144 ;; Propertize baseline when in range.
1145 ((markdown-new-baseline)
1146 (setq bounds nil))
1147 ;; Make sure this is not a line from a pre block
1148 ((looking-at-p pre-regexp))
1149 ;; If not, then update levels and propertize list item when in range.
1151 (let* ((indent (current-indentation))
1152 (cur-bounds (markdown--cur-list-item-bounds))
1153 (first (cl-first cur-bounds))
1154 (last (cl-second cur-bounds))
1155 (marker (cl-fifth cur-bounds)))
1156 (setq bounds (markdown--append-list-item-bounds
1157 marker indent cur-bounds bounds))
1158 (when (and (<= start (point)) (<= (point) end))
1159 (put-text-property first last 'markdown-list-item bounds)))))
1160 (end-of-line)))))
1162 (defun markdown-syntax-propertize-pre-blocks (start end)
1163 "Match preformatted text blocks from START to END."
1164 (save-excursion
1165 (goto-char start)
1166 (let ((levels (markdown-calculate-list-levels))
1167 indent pre-regexp close-regexp open close)
1168 (while (and (< (point) end) (not close))
1169 ;; Search for a region with sufficient indentation
1170 (if (null levels)
1171 (setq indent 1)
1172 (setq indent (1+ (length levels))))
1173 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1174 (setq close-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1176 (cond
1177 ;; If not at the beginning of a line, move forward
1178 ((not (bolp)) (forward-line))
1179 ;; Move past blank lines
1180 ((markdown-cur-line-blank-p) (forward-line))
1181 ;; At headers and horizontal rules, reset levels
1182 ((markdown-new-baseline) (forward-line) (setq levels nil))
1183 ;; If the current line has sufficient indentation, mark out pre block
1184 ;; The opening should be preceded by a blank line.
1185 ((and (markdown-prev-line-blank) (looking-at pre-regexp))
1186 (setq open (match-beginning 0))
1187 (while (and (or (looking-at-p pre-regexp) (markdown-cur-line-blank-p))
1188 (not (eobp)))
1189 (forward-line))
1190 (skip-syntax-backward "-")
1191 (setq close (point)))
1192 ;; If current line has a list marker, update levels, move to end of block
1193 ((looking-at markdown-regex-list)
1194 (setq levels (markdown-update-list-levels
1195 (match-string 2) (current-indentation) levels))
1196 (markdown-end-of-text-block))
1197 ;; If this is the end of the indentation level, adjust levels accordingly.
1198 ;; Only match end of indentation level if levels is not the empty list.
1199 ((and (car levels) (looking-at-p close-regexp))
1200 (setq levels (markdown-update-list-levels
1201 nil (current-indentation) levels))
1202 (markdown-end-of-text-block))
1203 (t (markdown-end-of-text-block))))
1205 (when (and open close)
1206 ;; Set text property data
1207 (put-text-property open close 'markdown-pre (list open close))
1208 ;; Recursively search again
1209 (markdown-syntax-propertize-pre-blocks (point) end)))))
1211 (defconst markdown-fenced-block-pairs
1212 `(((,markdown-regex-tilde-fence-begin markdown-tilde-fence-begin)
1213 (markdown-make-tilde-fence-regex markdown-tilde-fence-end)
1214 markdown-fenced-code)
1215 ((markdown-get-yaml-metadata-start-border markdown-yaml-metadata-begin)
1216 (markdown-get-yaml-metadata-end-border markdown-yaml-metadata-end)
1217 markdown-yaml-metadata-section)
1218 ((,markdown-regex-gfm-code-block-open markdown-gfm-block-begin)
1219 (,markdown-regex-gfm-code-block-close markdown-gfm-block-end)
1220 markdown-gfm-code))
1221 "Mapping of regular expressions to \"fenced-block\" constructs.
1222 These constructs are distinguished by having a distinctive start
1223 and end pattern, both of which take up an entire line of text,
1224 but no special pattern to identify text within the fenced
1225 blocks (unlike blockquotes and indented-code sections).
1227 Each element within this list takes the form:
1229 ((START-REGEX-OR-FUN START-PROPERTY)
1230 (END-REGEX-OR-FUN END-PROPERTY)
1231 MIDDLE-PROPERTY)
1233 Each *-REGEX-OR-FUN element can be a regular expression as a string, or a
1234 function which evaluates to same. Functions for START-REGEX-OR-FUN accept no
1235 arguments, but functions for END-REGEX-OR-FUN accept a single numerical argument
1236 which is the length of the first group of the START-REGEX-OR-FUN match, which
1237 can be ignored if unnecessary. `markdown-maybe-funcall-regexp' is used to
1238 evaluate these into \"real\" regexps.
1240 The *-PROPERTY elements are the text properties applied to each part of the
1241 block construct when it is matched using
1242 `markdown-syntax-propertize-fenced-block-constructs'. START-PROPERTY is applied
1243 to the text matching START-REGEX-OR-FUN, END-PROPERTY to END-REGEX-OR-FUN, and
1244 MIDDLE-PROPERTY to the text in between the two. The value of *-PROPERTY is the
1245 `match-data' when the regexp was matched to the text. In the case of
1246 MIDDLE-PROPERTY, the value is a false match data of the form '(begin end), with
1247 begin and end set to the edges of the \"middle\" text. This makes fontification
1248 easier.")
1250 (defun markdown-text-property-at-point (prop)
1251 (get-text-property (point) prop))
1253 (defsubst markdown-maybe-funcall-regexp (object &optional arg)
1254 (cond ((functionp object)
1255 (if arg (funcall object arg) (funcall object)))
1256 ((stringp object) object)
1257 (t (error "Object cannot be turned into regex"))))
1259 (defsubst markdown-get-start-fence-regexp ()
1260 "Return regexp to find all \"start\" sections of fenced block constructs.
1261 Which construct is actually contained in the match must be found separately."
1262 (mapconcat
1263 #'identity
1264 (mapcar (lambda (entry) (markdown-maybe-funcall-regexp (caar entry)))
1265 markdown-fenced-block-pairs)
1266 "\\|"))
1268 (defun markdown-get-fenced-block-begin-properties ()
1269 (cl-mapcar (lambda (entry) (cl-cadar entry)) markdown-fenced-block-pairs))
1271 (defun markdown-get-fenced-block-end-properties ()
1272 (cl-mapcar (lambda (entry) (cl-cadadr entry)) markdown-fenced-block-pairs))
1274 (defun markdown-get-fenced-block-middle-properties ()
1275 (cl-mapcar #'cl-third markdown-fenced-block-pairs))
1277 (defun markdown-find-previous-prop (prop &optional lim)
1278 "Find previous place where property PROP is non-nil, up to LIM.
1279 Return a cons of (pos . property). pos is point if point contains
1280 non-nil PROP."
1281 (let ((res
1282 (if (get-text-property (point) prop) (point)
1283 (previous-single-property-change
1284 (point) prop nil (or lim (point-min))))))
1285 (when (and (not (get-text-property res prop))
1286 (> res (point-min))
1287 (get-text-property (1- res) prop))
1288 (cl-decf res))
1289 (when (and res (get-text-property res prop)) (cons res prop))))
1291 (defun markdown-find-next-prop (prop &optional lim)
1292 "Find next place where property PROP is non-nil, up to LIM.
1293 Return a cons of (POS . PROPERTY) where POS is point if point
1294 contains non-nil PROP."
1295 (let ((res
1296 (if (get-text-property (point) prop) (point)
1297 (next-single-property-change
1298 (point) prop nil (or lim (point-max))))))
1299 (when (and res (get-text-property res prop)) (cons res prop))))
1301 (defun markdown-min-of-seq (map-fn seq)
1302 "Apply MAP-FN to SEQ and return element of SEQ with minimum value of MAP-FN."
1303 (cl-loop for el in seq
1304 with min = 1.0e+INF ; infinity
1305 with min-el = nil
1306 do (let ((res (funcall map-fn el)))
1307 (when (< res min)
1308 (setq min res)
1309 (setq min-el el)))
1310 finally return min-el))
1312 (defun markdown-max-of-seq (map-fn seq)
1313 "Apply MAP-FN to SEQ and return element of SEQ with maximum value of MAP-FN."
1314 (cl-loop for el in seq
1315 with max = -1.0e+INF ; negative infinity
1316 with max-el = nil
1317 do (let ((res (funcall map-fn el)))
1318 (when (and res (> res max))
1319 (setq max res)
1320 (setq max-el el)))
1321 finally return max-el))
1323 (defun markdown-find-previous-block ()
1324 "Find previous block.
1325 Detect whether `markdown-syntax-propertize-fenced-block-constructs' was
1326 unable to propertize the entire block, but was able to propertize the beginning
1327 of the block. If so, return a cons of (pos . property) where the beginning of
1328 the block was propertized."
1329 (let ((start-pt (point))
1330 (closest-open
1331 (markdown-max-of-seq
1332 #'car
1333 (cl-remove-if
1334 #'null
1335 (cl-mapcar
1336 #'markdown-find-previous-prop
1337 (markdown-get-fenced-block-begin-properties))))))
1338 (when closest-open
1339 (let* ((length-of-open-match
1340 (let ((match-d
1341 (get-text-property (car closest-open) (cdr closest-open))))
1342 (- (cl-fourth match-d) (cl-third match-d))))
1343 (end-regexp
1344 (markdown-maybe-funcall-regexp
1345 (cl-caadr
1346 (cl-find-if
1347 (lambda (entry) (eq (cl-cadar entry) (cdr closest-open)))
1348 markdown-fenced-block-pairs))
1349 length-of-open-match))
1350 (end-prop-loc
1351 (save-excursion
1352 (save-match-data
1353 (goto-char (car closest-open))
1354 (and (re-search-forward end-regexp start-pt t)
1355 (match-beginning 0))))))
1356 (and (not end-prop-loc) closest-open)))))
1358 (defun markdown-get-fenced-block-from-start (prop)
1359 "Return limits of an enclosing fenced block from its start, using PROP.
1360 Return value is a list usable as `match-data'."
1361 (catch 'no-rest-of-block
1362 (let* ((correct-entry
1363 (cl-find-if
1364 (lambda (entry) (eq (cl-cadar entry) prop))
1365 markdown-fenced-block-pairs))
1366 (begin-of-begin (cl-first (markdown-text-property-at-point prop)))
1367 (middle-prop (cl-third correct-entry))
1368 (end-prop (cl-cadadr correct-entry))
1369 (end-of-end
1370 (save-excursion
1371 (goto-char (match-end 0)) ; end of begin
1372 (unless (eobp) (forward-char))
1373 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
1374 (if (not mid-prop-v) ; no middle
1375 (progn
1376 ;; try to find end by advancing one
1377 (let ((end-prop-v
1378 (markdown-text-property-at-point end-prop)))
1379 (if end-prop-v (cl-second end-prop-v)
1380 (throw 'no-rest-of-block nil))))
1381 (set-match-data mid-prop-v)
1382 (goto-char (match-end 0)) ; end of middle
1383 (beginning-of-line) ; into end
1384 (cl-second (markdown-text-property-at-point end-prop)))))))
1385 (list begin-of-begin end-of-end))))
1387 (defun markdown-get-fenced-block-from-middle (prop)
1388 "Return limits of an enclosing fenced block from its middle, using PROP.
1389 Return value is a list usable as `match-data'."
1390 (let* ((correct-entry
1391 (cl-find-if
1392 (lambda (entry) (eq (cl-third entry) prop))
1393 markdown-fenced-block-pairs))
1394 (begin-prop (cl-cadar correct-entry))
1395 (begin-of-begin
1396 (save-excursion
1397 (goto-char (match-beginning 0))
1398 (unless (bobp) (forward-line -1))
1399 (beginning-of-line)
1400 (cl-first (markdown-text-property-at-point begin-prop))))
1401 (end-prop (cl-cadadr correct-entry))
1402 (end-of-end
1403 (save-excursion
1404 (goto-char (match-end 0))
1405 (beginning-of-line)
1406 (cl-second (markdown-text-property-at-point end-prop)))))
1407 (list begin-of-begin end-of-end)))
1409 (defun markdown-get-fenced-block-from-end (prop)
1410 "Return limits of an enclosing fenced block from its end, using PROP.
1411 Return value is a list usable as `match-data'."
1412 (let* ((correct-entry
1413 (cl-find-if
1414 (lambda (entry) (eq (cl-cadadr entry) prop))
1415 markdown-fenced-block-pairs))
1416 (end-of-end (cl-second (markdown-text-property-at-point prop)))
1417 (middle-prop (cl-third correct-entry))
1418 (begin-prop (cl-cadar correct-entry))
1419 (begin-of-begin
1420 (save-excursion
1421 (goto-char (match-beginning 0)) ; beginning of end
1422 (unless (bobp) (backward-char)) ; into middle
1423 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
1424 (if (not mid-prop-v)
1425 (progn
1426 (beginning-of-line)
1427 (cl-first (markdown-text-property-at-point begin-prop)))
1428 (set-match-data mid-prop-v)
1429 (goto-char (match-beginning 0)) ; beginning of middle
1430 (unless (bobp) (forward-line -1)) ; into beginning
1431 (beginning-of-line)
1432 (cl-first (markdown-text-property-at-point begin-prop)))))))
1433 (list begin-of-begin end-of-end)))
1435 (defun markdown-get-enclosing-fenced-block-construct (&optional pos)
1436 "Get \"fake\" match data for block enclosing POS.
1437 Returns fake match data which encloses the start, middle, and end
1438 of the block construct enclosing POS, if it exists. Used in
1439 `markdown-code-block-at-pos'."
1440 (save-excursion
1441 (when pos (goto-char pos))
1442 (beginning-of-line)
1443 (car
1444 (cl-remove-if
1445 #'null
1446 (cl-mapcar
1447 (lambda (fun-and-prop)
1448 (cl-destructuring-bind (fun prop) fun-and-prop
1449 (when prop
1450 (save-match-data
1451 (set-match-data (markdown-text-property-at-point prop))
1452 (funcall fun prop)))))
1453 `((markdown-get-fenced-block-from-start
1454 ,(cl-find-if
1455 #'markdown-text-property-at-point
1456 (markdown-get-fenced-block-begin-properties)))
1457 (markdown-get-fenced-block-from-middle
1458 ,(cl-find-if
1459 #'markdown-text-property-at-point
1460 (markdown-get-fenced-block-middle-properties)))
1461 (markdown-get-fenced-block-from-end
1462 ,(cl-find-if
1463 #'markdown-text-property-at-point
1464 (markdown-get-fenced-block-end-properties)))))))))
1466 (defun markdown-propertize-end-match (reg end fence-spec middle-begin)
1467 "Get match for REG up to END, if exists, and propertize appropriately.
1468 FENCE-SPEC is an entry in `markdown-fenced-block-pairs' and
1469 MIDDLE-BEGIN is the start of the \"middle\" section of the block."
1470 (when (re-search-forward reg end t)
1471 (let ((close-begin (match-beginning 0)) ; Start of closing line.
1472 (close-end (match-end 0)) ; End of closing line.
1473 (close-data (match-data t))) ; Match data for closing line.
1474 ;; Propertize middle section of fenced block.
1475 (put-text-property middle-begin close-begin
1476 (cl-third fence-spec)
1477 (list middle-begin close-begin))
1478 ;; If the block is a YAML block, propertize the declarations inside
1479 (markdown-syntax-propertize-yaml-metadata middle-begin close-begin)
1480 ;; Propertize closing line of fenced block.
1481 (put-text-property close-begin close-end
1482 (cl-cadadr fence-spec) close-data))))
1484 (defun markdown-syntax-propertize-fenced-block-constructs (start end)
1485 "Propertize according to `markdown-fenced-block-pairs' from START to END.
1486 If unable to propertize an entire block (if the start of a block is within START
1487 and END, but the end of the block is not), propertize the start section of a
1488 block, then in a subsequent call propertize both middle and end by finding the
1489 start which was previously propertized."
1490 (let ((start-reg (markdown-get-start-fence-regexp)))
1491 (save-excursion
1492 (goto-char start)
1493 ;; start from previous unclosed block, if exists
1494 (let ((prev-begin-block (markdown-find-previous-block)))
1495 (when prev-begin-block
1496 (let* ((correct-entry
1497 (cl-find-if (lambda (entry)
1498 (eq (cdr prev-begin-block) (cl-cadar entry)))
1499 markdown-fenced-block-pairs))
1500 (enclosed-text-start (1+ (car prev-begin-block)))
1501 (start-length
1502 (save-excursion
1503 (goto-char (car prev-begin-block))
1504 (string-match
1505 (markdown-maybe-funcall-regexp
1506 (caar correct-entry))
1507 (buffer-substring
1508 (point-at-bol) (point-at-eol)))
1509 (- (match-end 1) (match-beginning 1))))
1510 (end-reg (markdown-maybe-funcall-regexp
1511 (cl-caadr correct-entry) start-length)))
1512 (markdown-propertize-end-match
1513 end-reg end correct-entry enclosed-text-start))))
1514 ;; find all new blocks within region
1515 (while (re-search-forward start-reg end t)
1516 ;; we assume the opening constructs take up (only) an entire line,
1517 ;; so we re-check the current line
1518 (let* ((cur-line (buffer-substring (point-at-bol) (point-at-eol)))
1519 ;; find entry in `markdown-fenced-block-pairs' corresponding
1520 ;; to regex which was matched
1521 (correct-entry
1522 (cl-find-if
1523 (lambda (fenced-pair)
1524 (string-match-p
1525 (markdown-maybe-funcall-regexp (caar fenced-pair))
1526 cur-line))
1527 markdown-fenced-block-pairs))
1528 (enclosed-text-start
1529 (save-excursion (1+ (point-at-eol))))
1530 (end-reg
1531 (markdown-maybe-funcall-regexp
1532 (cl-caadr correct-entry)
1533 (if (and (match-beginning 1) (match-end 1))
1534 (- (match-end 1) (match-beginning 1))
1535 0))))
1536 ;; get correct match data
1537 (save-excursion
1538 (beginning-of-line)
1539 (re-search-forward
1540 (markdown-maybe-funcall-regexp (caar correct-entry))
1541 (point-at-eol)))
1542 ;; mark starting, even if ending is outside of region
1543 (put-text-property (match-beginning 0) (match-end 0)
1544 (cl-cadar correct-entry) (match-data t))
1545 (markdown-propertize-end-match
1546 end-reg end correct-entry enclosed-text-start))))))
1548 (defun markdown-syntax-propertize-blockquotes (start end)
1549 "Match blockquotes from START to END."
1550 (save-excursion
1551 (goto-char start)
1552 (while (and (re-search-forward markdown-regex-blockquote end t)
1553 (not (markdown-code-block-at-pos (match-beginning 0))))
1554 (put-text-property (match-beginning 0) (match-end 0)
1555 'markdown-blockquote
1556 (match-data t)))))
1558 (defun markdown-syntax-propertize-hrs (start end)
1559 "Match horizontal rules from START to END."
1560 (save-excursion
1561 (goto-char start)
1562 (while (re-search-forward markdown-regex-hr end t)
1563 (unless (or (markdown-on-heading-p)
1564 (markdown-code-block-at-point-p))
1565 (put-text-property (match-beginning 0) (match-end 0)
1566 'markdown-hr
1567 (match-data t))))))
1569 (defun markdown-syntax-propertize-yaml-metadata (start end)
1570 "Propertize elements inside YAML metadata blocks from START to END.
1571 Assumes region from START and END is already known to be the interior
1572 region of a YAML metadata block as propertized by
1573 `markdown-syntax-propertize-fenced-block-constructs'."
1574 (save-excursion
1575 (goto-char start)
1576 (cl-loop
1577 while (re-search-forward markdown-regex-declarative-metadata end t)
1578 do (progn
1579 (put-text-property (match-beginning 1) (match-end 1)
1580 'markdown-metadata-key (match-data t))
1581 (put-text-property (match-beginning 2) (match-end 2)
1582 'markdown-metadata-markup (match-data t))
1583 (put-text-property (match-beginning 3) (match-end 3)
1584 'markdown-metadata-value (match-data t))))))
1586 (defun markdown-syntax-propertize-headings (start end)
1587 "Match headings of type SYMBOL with REGEX from START to END."
1588 (goto-char start)
1589 (while (re-search-forward markdown-regex-header end t)
1590 (unless (markdown-code-block-at-pos (match-beginning 0))
1591 (put-text-property
1592 (match-beginning 0) (match-end 0) 'markdown-heading
1593 (match-data t))
1594 (put-text-property
1595 (match-beginning 0) (match-end 0)
1596 (cond ((match-string-no-properties 2) 'markdown-heading-1-setext)
1597 ((match-string-no-properties 3) 'markdown-heading-2-setext)
1598 (t (let ((atx-level (length (markdown-trim-whitespace
1599 (match-string-no-properties 4)))))
1600 (intern (format "markdown-heading-%d-atx" atx-level)))))
1601 (match-data t)))))
1603 (defun markdown-syntax-propertize-comments (start end)
1604 "Match HTML comments from the START to END."
1605 (let* ((in-comment (nth 4 (syntax-ppss))))
1606 (goto-char start)
1607 (cond
1608 ;; Comment start
1609 ((and (not in-comment)
1610 (re-search-forward markdown-regex-comment-start end t)
1611 (not (markdown-inline-code-at-point-p))
1612 (not (markdown-code-block-at-point-p)))
1613 (let ((open-beg (match-beginning 0)))
1614 (put-text-property open-beg (1+ open-beg)
1615 'syntax-table (string-to-syntax "<"))
1616 (markdown-syntax-propertize-comments
1617 (min (1+ (match-end 0)) end (point-max)) end)))
1618 ;; Comment end
1619 ((and in-comment
1620 (re-search-forward markdown-regex-comment-end end t))
1621 (let ((comment-end (match-end 0))
1622 (comment-begin (nth 8 (syntax-ppss))))
1623 (put-text-property (1- comment-end) comment-end
1624 'syntax-table (string-to-syntax ">"))
1625 ;; Remove any other text properties inside the comment
1626 (remove-text-properties comment-begin comment-end
1627 markdown--syntax-properties)
1628 (put-text-property comment-begin comment-end
1629 'markdown-comment (list comment-begin comment-end))
1630 (markdown-syntax-propertize-comments
1631 (min (1+ comment-end) end (point-max)) end)))
1632 ;; Nothing found
1633 (t nil))))
1635 (defun markdown-syntax-propertize (start end)
1636 "Function used as `syntax-propertize-function'.
1637 START and END delimit region to propertize."
1638 (with-silent-modifications
1639 (save-excursion
1640 (remove-text-properties start end markdown--syntax-properties)
1641 (markdown-syntax-propertize-fenced-block-constructs start end)
1642 (markdown-syntax-propertize-list-items start end)
1643 (markdown-syntax-propertize-pre-blocks start end)
1644 (markdown-syntax-propertize-blockquotes start end)
1645 (markdown-syntax-propertize-headings start end)
1646 (markdown-syntax-propertize-hrs start end)
1647 (markdown-syntax-propertize-comments start end))))
1650 ;;; Markup Hiding
1652 (defconst markdown-markup-properties
1653 '(face markdown-markup-face invisible markdown-markup)
1654 "List of properties and values to apply to markup.")
1656 (defconst markdown-language-keyword-properties
1657 '(face markdown-language-keyword-face invisible markdown-markup)
1658 "List of properties and values to apply to code block language names.")
1660 (defconst markdown-language-info-properties
1661 '(face markdown-language-info-face invisible markdown-markup)
1662 "List of properties and values to apply to code block language info strings.")
1664 (defconst markdown-include-title-properties
1665 '(face markdown-link-title-face invisible markdown-markup)
1666 "List of properties and values to apply to included code titles.")
1668 (defcustom markdown-hide-markup nil
1669 "Determines whether markup in the buffer will be hidden.
1670 When set to nil, all markup is displayed in the buffer as it
1671 appears in the file. An exception is when `markdown-hide-urls'
1672 is non-nil.
1673 Set this to a non-nil value to turn this feature on by default.
1674 You can interactively toggle the value of this variable with
1675 `markdown-toggle-markup-hiding', \\[markdown-toggle-markup-hiding],
1676 or from the Markdown > Show & Hide menu.
1678 Markup hiding works by adding text properties to positions in the
1679 buffer---either the `invisible' property or the `display' property
1680 in cases where alternative glyphs are used (e.g., list bullets).
1681 This does not, however, affect printing or other output.
1682 Functions such as `htmlfontify-buffer' and `ps-print-buffer' will
1683 not honor these text properties. For printing, it would be better
1684 to first convert to HTML or PDF (e.g,. using Pandoc)."
1685 :group 'markdown
1686 :type 'boolean
1687 :safe 'booleanp
1688 :package-version '(markdown-mode . "2.3"))
1689 (make-variable-buffer-local 'markdown-hide-markup)
1691 (defun markdown-toggle-markup-hiding (&optional arg)
1692 "Toggle the display or hiding of markup.
1693 With a prefix argument ARG, enable markup hiding if ARG is positive,
1694 and disable it otherwise.
1695 See `markdown-hide-markup' for additional details."
1696 (interactive (list (or current-prefix-arg 'toggle)))
1697 (setq markdown-hide-markup
1698 (if (eq arg 'toggle)
1699 (not markdown-hide-markup)
1700 (> (prefix-numeric-value arg) 0)))
1701 (if markdown-hide-markup
1702 (progn (add-to-invisibility-spec 'markdown-markup)
1703 (message "markdown-mode markup hiding enabled"))
1704 (progn (remove-from-invisibility-spec 'markdown-markup)
1705 (message "markdown-mode markup hiding disabled")))
1706 (markdown-reload-extensions))
1709 ;;; Font Lock =================================================================
1711 (require 'font-lock)
1713 (defvar markdown-italic-face 'markdown-italic-face
1714 "Face name to use for italic text.")
1716 (defvar markdown-bold-face 'markdown-bold-face
1717 "Face name to use for bold text.")
1719 (defvar markdown-strike-through-face 'markdown-strike-through-face
1720 "Face name to use for strike-through text.")
1722 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
1723 "Face name to use as a base for header delimiters.")
1725 (defvar markdown-header-rule-face 'markdown-header-rule-face
1726 "Face name to use as a base for header rules.")
1728 (defvar markdown-header-face 'markdown-header-face
1729 "Face name to use as a base for headers.")
1731 (defvar markdown-header-face-1 'markdown-header-face-1
1732 "Face name to use for level-1 headers.")
1734 (defvar markdown-header-face-2 'markdown-header-face-2
1735 "Face name to use for level-2 headers.")
1737 (defvar markdown-header-face-3 'markdown-header-face-3
1738 "Face name to use for level-3 headers.")
1740 (defvar markdown-header-face-4 'markdown-header-face-4
1741 "Face name to use for level-4 headers.")
1743 (defvar markdown-header-face-5 'markdown-header-face-5
1744 "Face name to use for level-5 headers.")
1746 (defvar markdown-header-face-6 'markdown-header-face-6
1747 "Face name to use for level-6 headers.")
1749 (defvar markdown-inline-code-face 'markdown-inline-code-face
1750 "Face name to use for inline code.")
1752 (defvar markdown-list-face 'markdown-list-face
1753 "Face name to use for list markers.")
1755 (defvar markdown-blockquote-face 'markdown-blockquote-face
1756 "Face name to use for blockquote.")
1758 (defvar markdown-pre-face 'markdown-pre-face
1759 "Face name to use for preformatted text.")
1761 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
1762 "Face name to use for programming language identifiers.")
1764 (defvar markdown-language-info-face 'markdown-language-info-face
1765 "Face name to use for programming info strings.")
1767 (defvar markdown-link-face 'markdown-link-face
1768 "Face name to use for links.")
1770 (defvar markdown-missing-link-face 'markdown-missing-link-face
1771 "Face name to use for links where the linked file does not exist.")
1773 (defvar markdown-reference-face 'markdown-reference-face
1774 "Face name to use for reference.")
1776 (defvar markdown-footnote-marker-face 'markdown-footnote-marker-face
1777 "Face name to use for footnote markers.")
1779 (defvar markdown-url-face 'markdown-url-face
1780 "Face name to use for URLs.")
1782 (defvar markdown-link-title-face 'markdown-link-title-face
1783 "Face name to use for reference link titles.")
1785 (defvar markdown-line-break-face 'markdown-line-break-face
1786 "Face name to use for hard line breaks.")
1788 (defvar markdown-comment-face 'markdown-comment-face
1789 "Face name to use for HTML comments.")
1791 (defvar markdown-math-face 'markdown-math-face
1792 "Face name to use for LaTeX expressions.")
1794 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
1795 "Face name to use for metadata keys.")
1797 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
1798 "Face name to use for metadata values.")
1800 (defvar markdown-gfm-checkbox-face 'markdown-gfm-checkbox-face
1801 "Face name to use for GFM checkboxes.")
1803 (defvar markdown-highlight-face 'markdown-highlight-face
1804 "Face name to use for mouse highlighting.")
1806 (defvar markdown-markup-face 'markdown-markup-face
1807 "Face name to use for markup elements.")
1809 (make-obsolete-variable 'markdown-italic-face "Use face name directly" "v2.4")
1810 (make-obsolete-variable 'markdown-bold-face "Use face name directly" "v2.4")
1811 (make-obsolete-variable 'markdown-strike-through-face "Use face name directly" "v2.4")
1812 (make-obsolete-variable 'markdown-header-delimiter-face "Use face name directly" "v2.4")
1813 (make-obsolete-variable 'markdown-header-rule-face "Use face name directly" "v2.4")
1814 (make-obsolete-variable 'markdown-header-face "Use face name directly" "v2.4")
1815 (make-obsolete-variable 'markdown-header-face-1 "Use face name directly" "v2.4")
1816 (make-obsolete-variable 'markdown-header-face-2 "Use face name directly" "v2.4")
1817 (make-obsolete-variable 'markdown-header-face-3 "Use face name directly" "v2.4")
1818 (make-obsolete-variable 'markdown-header-face-4 "Use face name directly" "v2.4")
1819 (make-obsolete-variable 'markdown-header-face-5 "Use face name directly" "v2.4")
1820 (make-obsolete-variable 'markdown-header-face-6 "Use face name directly" "v2.4")
1821 (make-obsolete-variable 'markdown-inline-code-face "Use face name directly" "v2.4")
1822 (make-obsolete-variable 'markdown-list-face "Use face name directly" "v2.4")
1823 (make-obsolete-variable 'markdown-blockquote-face "Use face name directly" "v2.4")
1824 (make-obsolete-variable 'markdown-pre-face "Use face name directly" "v2.4")
1825 (make-obsolete-variable 'markdown-language-keyword-face "Use face name directly" "v2.4")
1826 (make-obsolete-variable 'markdown-language-info-face "Use face name directly" "v2.4")
1827 (make-obsolete-variable 'markdown-link-face "Use face name directly" "v2.4")
1828 (make-obsolete-variable 'markdown-missing-link-face "Use face name directly" "v2.4")
1829 (make-obsolete-variable 'markdown-reference-face "Use face name directly" "v2.4")
1830 (make-obsolete-variable 'markdown-footnote-marker-face "Use face name directly" "v2.4")
1831 (make-obsolete-variable 'markdown-url-face "Use face name directly" "v2.4")
1832 (make-obsolete-variable 'markdown-link-title-face "Use face name directly" "v2.4")
1833 (make-obsolete-variable 'markdown-line-break-face "Use face name directly" "v2.4")
1834 (make-obsolete-variable 'markdown-comment-face "Use face name directly" "v2.4")
1835 (make-obsolete-variable 'markdown-math-face "Use face name directly" "v2.4")
1836 (make-obsolete-variable 'markdown-metadata-key-face "Use face name directly" "v2.4")
1837 (make-obsolete-variable 'markdown-metadata-value-face "Use face name directly" "v2.4")
1838 (make-obsolete-variable 'markdown-gfm-checkbox-face "Use face name directly" "v2.4")
1839 (make-obsolete-variable 'markdown-highlight-face "Use face name directly" "v2.4")
1840 (make-obsolete-variable 'markdown-markup-face "Use face name directly" "v2.4")
1842 (defgroup markdown-faces nil
1843 "Faces used in Markdown Mode"
1844 :group 'markdown
1845 :group 'faces)
1847 (defface markdown-italic-face
1848 '((t (:inherit italic)))
1849 "Face for italic text."
1850 :group 'markdown-faces)
1852 (defface markdown-bold-face
1853 '((t (:inherit bold)))
1854 "Face for bold text."
1855 :group 'markdown-faces)
1857 (defface markdown-strike-through-face
1858 '((t (:strike-through t)))
1859 "Face for strike-through text."
1860 :group 'markdown-faces)
1862 (defface markdown-markup-face
1863 '((t (:inherit shadow :slant normal :weight normal)))
1864 "Face for markup elements."
1865 :group 'markdown-faces)
1867 (defface markdown-header-rule-face
1868 '((t (:inherit markdown-markup-face)))
1869 "Base face for headers rules."
1870 :group 'markdown-faces)
1872 (defface markdown-header-delimiter-face
1873 '((t (:inherit markdown-markup-face)))
1874 "Base face for headers hash delimiter."
1875 :group 'markdown-faces)
1877 (defface markdown-list-face
1878 '((t (:inherit markdown-markup-face)))
1879 "Face for list item markers."
1880 :group 'markdown-faces)
1882 (defface markdown-blockquote-face
1883 '((t (:inherit font-lock-doc-face)))
1884 "Face for blockquote sections."
1885 :group 'markdown-faces)
1887 (defface markdown-code-face
1888 '((t (:inherit fixed-pitch)))
1889 "Face for inline code, pre blocks, and fenced code blocks.
1890 This may be used, for example, to add a contrasting background to
1891 inline code fragments and code blocks."
1892 :group 'markdown-faces)
1894 (defface markdown-inline-code-face
1895 '((t (:inherit (markdown-code-face font-lock-constant-face))))
1896 "Face for inline code."
1897 :group 'markdown-faces)
1899 (defface markdown-pre-face
1900 '((t (:inherit (markdown-code-face font-lock-constant-face))))
1901 "Face for preformatted text."
1902 :group 'markdown-faces)
1904 (defface markdown-table-face
1905 '((t (:inherit (markdown-code-face))))
1906 "Face for tables."
1907 :group 'markdown-faces)
1909 (defface markdown-language-keyword-face
1910 '((t (:inherit font-lock-type-face)))
1911 "Face for programming language identifiers."
1912 :group 'markdown-faces)
1914 (defface markdown-language-info-face
1915 '((t (:inherit font-lock-string-face)))
1916 "Face for programming language info strings."
1917 :group 'markdown-faces)
1919 (defface markdown-link-face
1920 '((t (:inherit link)))
1921 "Face for links."
1922 :group 'markdown-faces)
1924 (defface markdown-missing-link-face
1925 '((t (:inherit font-lock-warning-face)))
1926 "Face for missing links."
1927 :group 'markdown-faces)
1929 (defface markdown-reference-face
1930 '((t (:inherit markdown-markup-face)))
1931 "Face for link references."
1932 :group 'markdown-faces)
1934 (define-obsolete-face-alias 'markdown-footnote-face
1935 'markdown-footnote-marker-face "v2.3")
1937 (defface markdown-footnote-marker-face
1938 '((t (:inherit markdown-markup-face)))
1939 "Face for footnote markers."
1940 :group 'markdown-faces)
1942 (defface markdown-footnote-text-face
1943 '((t (:inherit font-lock-comment-face)))
1944 "Face for footnote text."
1945 :group 'markdown-faces)
1947 (defface markdown-url-face
1948 '((t (:inherit font-lock-string-face)))
1949 "Face for URLs that are part of markup.
1950 For example, this applies to URLs in inline links:
1951 [link text](http://example.com/)."
1952 :group 'markdown-faces)
1954 (defface markdown-plain-url-face
1955 '((t (:inherit markdown-link-face)))
1956 "Face for URLs that are also links.
1957 For example, this applies to plain angle bracket URLs:
1958 <http://example.com/>."
1959 :group 'markdown-faces)
1961 (defface markdown-link-title-face
1962 '((t (:inherit font-lock-comment-face)))
1963 "Face for reference link titles."
1964 :group 'markdown-faces)
1966 (defface markdown-line-break-face
1967 '((t (:inherit font-lock-constant-face :underline t)))
1968 "Face for hard line breaks."
1969 :group 'markdown-faces)
1971 (defface markdown-comment-face
1972 '((t (:inherit font-lock-comment-face)))
1973 "Face for HTML comments."
1974 :group 'markdown-faces)
1976 (defface markdown-math-face
1977 '((t (:inherit font-lock-string-face)))
1978 "Face for LaTeX expressions."
1979 :group 'markdown-faces)
1981 (defface markdown-metadata-key-face
1982 '((t (:inherit font-lock-variable-name-face)))
1983 "Face for metadata keys."
1984 :group 'markdown-faces)
1986 (defface markdown-metadata-value-face
1987 '((t (:inherit font-lock-string-face)))
1988 "Face for metadata values."
1989 :group 'markdown-faces)
1991 (defface markdown-gfm-checkbox-face
1992 '((t (:inherit font-lock-builtin-face)))
1993 "Face for GFM checkboxes."
1994 :group 'markdown-faces)
1996 (defface markdown-highlight-face
1997 '((t (:inherit highlight)))
1998 "Face for mouse highlighting."
1999 :group 'markdown-faces)
2001 (defface markdown-hr-face
2002 '((t (:inherit markdown-markup-face)))
2003 "Face for horizontal rules."
2004 :group 'markdown-faces)
2006 (defface markdown-html-tag-name-face
2007 '((t (:inherit font-lock-type-face)))
2008 "Face for HTML tag names."
2009 :group 'markdown-faces)
2011 (defface markdown-html-tag-delimiter-face
2012 '((t (:inherit markdown-markup-face)))
2013 "Face for HTML tag delimiters."
2014 :group 'markdown-faces)
2016 (defface markdown-html-attr-name-face
2017 '((t (:inherit font-lock-variable-name-face)))
2018 "Face for HTML attribute names."
2019 :group 'markdown-faces)
2021 (defface markdown-html-attr-value-face
2022 '((t (:inherit font-lock-string-face)))
2023 "Face for HTML attribute values."
2024 :group 'markdown-faces)
2026 (defface markdown-html-entity-face
2027 '((t (:inherit font-lock-variable-name-face)))
2028 "Face for HTML entities."
2029 :group 'markdown-faces)
2031 (defcustom markdown-header-scaling nil
2032 "Whether to use variable-height faces for headers.
2033 When non-nil, `markdown-header-face' will inherit from
2034 `variable-pitch' and the scaling values in
2035 `markdown-header-scaling-values' will be applied to
2036 headers of levels one through six respectively."
2037 :type 'boolean
2038 :initialize 'custom-initialize-default
2039 :set (lambda (symbol value)
2040 (set-default symbol value)
2041 (markdown-update-header-faces value))
2042 :group 'markdown-faces
2043 :package-version '(markdown-mode . "2.2"))
2045 (defcustom markdown-header-scaling-values
2046 '(2.0 1.7 1.4 1.1 1.0 1.0)
2047 "List of scaling values for headers of level one through six.
2048 Used when `markdown-header-scaling' is non-nil."
2049 :type 'list
2050 :initialize 'custom-initialize-default
2051 :set (lambda (symbol value)
2052 (set-default symbol value)
2053 (markdown-update-header-faces markdown-header-scaling value))
2054 :group 'markdown-faces)
2056 (defun markdown-make-header-faces ()
2057 "Build the faces used for Markdown headers."
2058 (let ((inherit-faces '(font-lock-function-name-face)))
2059 (when markdown-header-scaling
2060 (setq inherit-faces (cons 'variable-pitch inherit-faces)))
2061 (defface markdown-header-face
2062 `((t (:inherit ,inherit-faces :weight bold)))
2063 "Base face for headers."
2064 :group 'markdown-faces))
2065 (dotimes (num 6)
2066 (let* ((num1 (1+ num))
2067 (face-name (intern (format "markdown-header-face-%s" num1)))
2068 (scale (if markdown-header-scaling
2069 (float (nth num markdown-header-scaling-values))
2070 1.0)))
2071 (eval
2072 `(defface ,face-name
2073 '((t (:inherit markdown-header-face :height ,scale)))
2074 (format "Face for level %s headers.
2075 You probably don't want to customize this face directly. Instead
2076 you can customize the base face `markdown-header-face' or the
2077 variable-height variable `markdown-header-scaling'." ,num1)
2078 :group 'markdown-faces)))))
2080 (markdown-make-header-faces)
2082 (defun markdown-update-header-faces (&optional scaling scaling-values)
2083 "Update header faces, depending on if header SCALING is desired.
2084 If so, use given list of SCALING-VALUES relative to the baseline
2085 size of `markdown-header-face'."
2086 (dotimes (num 6)
2087 (let* ((face-name (intern (format "markdown-header-face-%s" (1+ num))))
2088 (scale (cond ((not scaling) 1.0)
2089 (scaling-values (float (nth num scaling-values)))
2090 (t (float (nth num markdown-header-scaling-values))))))
2091 (unless (get face-name 'saved-face) ; Don't update customized faces
2092 (set-face-attribute face-name nil :height scale)))))
2094 (defun markdown-syntactic-face (state)
2095 "Return font-lock face for characters with given STATE.
2096 See `font-lock-syntactic-face-function' for details."
2097 (let ((in-comment (nth 4 state)))
2098 (cond
2099 (in-comment 'markdown-comment-face)
2100 (t nil))))
2102 (defcustom markdown-list-item-bullets
2103 '("●" "◎" "○" "◆" "◇" "►" "•")
2104 "List of bullets to use for unordered lists.
2105 It can contain any number of symbols, which will be repeated.
2106 Depending on your font, some reasonable choices are:
2107 ♥ ● ◇ ✚ ✜ ☯ ◆ ♠ ♣ ♦ ❀ ◆ ◖ ▶ ► • ★ ▸."
2108 :group 'markdown
2109 :type '(repeat (string :tag "Bullet character"))
2110 :package-version '(markdown-mode . "2.3"))
2112 (defun markdown--footnote-marker-properties ()
2113 "Return a font-lock facespec expression for footnote marker text."
2114 `(face markdown-footnote-marker-face
2115 ,@(when markdown-hide-markup
2116 `(display ,markdown-footnote-display))))
2118 (defun markdown--pandoc-inline-footnote-properties ()
2119 "Return a font-lock facespec expression for Pandoc inline footnote text."
2120 `(face markdown-footnote-text-face
2121 ,@(when markdown-hide-markup
2122 `(display ,markdown-footnote-display))))
2124 (defvar markdown-mode-font-lock-keywords
2125 `((markdown-match-yaml-metadata-begin . ((1 'markdown-markup-face)))
2126 (markdown-match-yaml-metadata-end . ((1 'markdown-markup-face)))
2127 (markdown-match-yaml-metadata-key . ((1 'markdown-metadata-key-face)
2128 (2 'markdown-markup-face)
2129 (3 'markdown-metadata-value-face)))
2130 (markdown-match-gfm-open-code-blocks . ((1 markdown-markup-properties)
2131 (2 markdown-markup-properties nil t)
2132 (3 markdown-language-keyword-properties nil t)
2133 (4 markdown-language-info-properties nil t)
2134 (5 markdown-markup-properties nil t)))
2135 (markdown-match-gfm-close-code-blocks . ((0 markdown-markup-properties)))
2136 (markdown-fontify-gfm-code-blocks)
2137 (markdown-fontify-tables)
2138 (markdown-match-fenced-start-code-block . ((1 markdown-markup-properties)
2139 (2 markdown-markup-properties nil t)
2140 (3 markdown-language-keyword-properties nil t)
2141 (4 markdown-language-info-properties nil t)
2142 (5 markdown-markup-properties nil t)))
2143 (markdown-match-fenced-end-code-block . ((0 markdown-markup-properties)))
2144 (markdown-fontify-fenced-code-blocks)
2145 (markdown-match-pre-blocks . ((0 'markdown-pre-face)))
2146 (markdown-fontify-headings)
2147 (markdown-match-declarative-metadata . ((1 'markdown-metadata-key-face)
2148 (2 'markdown-markup-face)
2149 (3 'markdown-metadata-value-face)))
2150 (markdown-match-pandoc-metadata . ((1 'markdown-markup-face)
2151 (2 'markdown-markup-face)
2152 (3 'markdown-metadata-value-face)))
2153 (markdown-fontify-hrs)
2154 (markdown-match-code . ((1 markdown-markup-properties prepend)
2155 (2 'markdown-inline-code-face prepend)
2156 (3 markdown-markup-properties prepend)))
2157 (,markdown-regex-kbd . ((1 markdown-markup-properties)
2158 (2 'markdown-inline-code-face)
2159 (3 markdown-markup-properties)))
2160 (markdown-fontify-angle-uris)
2161 (,markdown-regex-email . 'markdown-plain-url-face)
2162 (markdown-match-html-tag . ((1 'markdown-html-tag-delimiter-face t)
2163 (2 'markdown-html-tag-name-face t)
2164 (3 'markdown-html-tag-delimiter-face t)
2165 ;; Anchored matcher for HTML tag attributes
2166 (,markdown-regex-html-attr
2167 ;; Before searching, move past tag
2168 ;; name; set limit at tag close.
2169 (progn
2170 (goto-char (match-end 2)) (match-end 3))
2172 . ((1 'markdown-html-attr-name-face)
2173 (3 'markdown-html-tag-delimiter-face nil t)
2174 (4 'markdown-html-attr-value-face nil t)))))
2175 (,markdown-regex-html-entity . 'markdown-html-entity-face)
2176 (markdown-fontify-list-items)
2177 (,markdown-regex-footnote . ((1 markdown-markup-properties) ; [^
2178 (2 (markdown--footnote-marker-properties)) ; label
2179 (3 markdown-markup-properties))) ; ]
2180 (,markdown-regex-pandoc-inline-footnote . ((1 markdown-markup-properties) ; ^
2181 (2 markdown-markup-properties) ; [
2182 (3 (markdown--pandoc-inline-footnote-properties)) ; text
2183 (4 markdown-markup-properties))) ; ]
2184 (markdown-match-includes . ((1 markdown-markup-properties)
2185 (2 markdown-markup-properties nil t)
2186 (3 markdown-include-title-properties nil t)
2187 (4 markdown-markup-properties nil t)
2188 (5 markdown-markup-properties)
2189 (6 'markdown-url-face)
2190 (7 markdown-markup-properties)))
2191 (markdown-fontify-inline-links)
2192 (markdown-fontify-reference-links)
2193 (,markdown-regex-reference-definition . ((1 'markdown-markup-face) ; [
2194 (2 'markdown-reference-face) ; label
2195 (3 'markdown-markup-face) ; ]
2196 (4 'markdown-markup-face) ; :
2197 (5 'markdown-url-face) ; url
2198 (6 'markdown-link-title-face))) ; "title" (optional)
2199 (markdown-fontify-plain-uris)
2200 ;; Math mode $..$
2201 (markdown-match-math-single . ((1 'markdown-markup-face prepend)
2202 (2 'markdown-math-face append)
2203 (3 'markdown-markup-face prepend)))
2204 ;; Math mode $$..$$
2205 (markdown-match-math-double . ((1 'markdown-markup-face prepend)
2206 (2 'markdown-math-face append)
2207 (3 'markdown-markup-face prepend)))
2208 ;; Math mode \[..\] and \\[..\\]
2209 (markdown-match-math-display . ((1 'markdown-markup-face prepend)
2210 (3 'markdown-math-face append)
2211 (4 'markdown-markup-face prepend)))
2212 (markdown-match-bold . ((1 markdown-markup-properties prepend)
2213 (2 'markdown-bold-face append)
2214 (3 markdown-markup-properties prepend)))
2215 (markdown-match-italic . ((1 markdown-markup-properties prepend)
2216 (2 'markdown-italic-face append)
2217 (3 markdown-markup-properties prepend)))
2218 (,markdown-regex-strike-through . ((3 markdown-markup-properties)
2219 (4 'markdown-strike-through-face)
2220 (5 markdown-markup-properties)))
2221 (,markdown-regex-line-break . (1 'markdown-line-break-face prepend))
2222 (markdown-fontify-sub-superscripts)
2223 (markdown-match-inline-attributes . ((0 markdown-markup-properties prepend)))
2224 (markdown-match-leanpub-sections . ((0 markdown-markup-properties)))
2225 (markdown-fontify-blockquotes)
2226 (markdown-match-wiki-link . ((0 'markdown-link-face prepend))))
2227 "Syntax highlighting for Markdown files.")
2229 (define-obsolete-variable-alias
2230 'markdown-mode-font-lock-keywords-basic
2231 'markdown-mode-font-lock-keywords "v2.4")
2233 ;; Footnotes
2234 (defvar markdown-footnote-counter 0
2235 "Counter for footnote numbers.")
2236 (make-variable-buffer-local 'markdown-footnote-counter)
2238 (defconst markdown-footnote-chars
2239 "[[:alnum:]-]"
2240 "Regular expression matching any character that is allowed in a footnote identifier.")
2242 (defconst markdown-regex-footnote-definition
2243 (concat "^ \\{0,3\\}\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:\\(?:[ \t]+\\|$\\)")
2244 "Regular expression matching a footnote definition, capturing the label.")
2247 ;;; Compatibility =============================================================
2249 (defun markdown-replace-regexp-in-string (regexp rep string)
2250 "Replace ocurrences of REGEXP with REP in STRING.
2251 This is a compatibility wrapper to provide `replace-regexp-in-string'
2252 in XEmacs 21."
2253 (if (featurep 'xemacs)
2254 (replace-in-string string regexp rep)
2255 (replace-regexp-in-string regexp rep string)))
2257 ;; `markdown-use-region-p' is a compatibility function which checks
2258 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
2259 (eval-and-compile
2260 (cond
2261 ;; Emacs 24 and newer
2262 ((fboundp 'use-region-p)
2263 (defalias 'markdown-use-region-p 'use-region-p))
2264 ;; XEmacs
2265 ((fboundp 'region-active-p)
2266 (defalias 'markdown-use-region-p 'region-active-p))))
2268 ;; Use new names for outline-mode functions in Emacs 25 and later.
2269 (eval-and-compile
2270 (defalias 'markdown-hide-sublevels
2271 (if (fboundp 'outline-hide-sublevels)
2272 'outline-hide-sublevels
2273 'hide-sublevels))
2274 (defalias 'markdown-show-all
2275 (if (fboundp 'outline-show-all)
2276 'outline-show-all
2277 'show-all))
2278 (defalias 'markdown-hide-body
2279 (if (fboundp 'outline-hide-body)
2280 'outline-hide-body
2281 'hide-body))
2282 (defalias 'markdown-show-children
2283 (if (fboundp 'outline-show-children)
2284 'outline-show-children
2285 'show-children))
2286 (defalias 'markdown-show-subtree
2287 (if (fboundp 'outline-show-subtree)
2288 'outline-show-subtree
2289 'show-subtree))
2290 (defalias 'markdown-hide-subtree
2291 (if (fboundp 'outline-hide-subtree)
2292 'outline-hide-subtree
2293 'hide-subtree)))
2295 ;; Provide directory-name-p to Emacs 24
2296 (defsubst markdown-directory-name-p (name)
2297 "Return non-nil if NAME ends with a directory separator character.
2298 Taken from `directory-name-p' from Emacs 25 and provided here for
2299 backwards compatibility."
2300 (let ((len (length name))
2301 (lastc ?.))
2302 (if (> len 0)
2303 (setq lastc (aref name (1- len))))
2304 (or (= lastc ?/)
2305 (and (memq system-type '(windows-nt ms-dos))
2306 (= lastc ?\\)))))
2308 ;; Provide a function to find files recursively in Emacs 24.
2309 (defalias 'markdown-directory-files-recursively
2310 (if (fboundp 'directory-files-recursively)
2311 'directory-files-recursively
2312 (lambda (dir regexp)
2313 "Return list of all files under DIR that have file names matching REGEXP.
2314 This function works recursively. Files are returned in \"depth first\"
2315 order, and files from each directory are sorted in alphabetical order.
2316 Each file name appears in the returned list in its absolute form.
2317 Based on `directory-files-recursively' from Emacs 25 and provided
2318 here for backwards compatibility."
2319 (let ((result nil)
2320 (files nil)
2321 ;; When DIR is "/", remote file names like "/method:" could
2322 ;; also be offered. We shall suppress them.
2323 (tramp-mode (and tramp-mode (file-remote-p (expand-file-name dir)))))
2324 (dolist (file (sort (file-name-all-completions "" dir)
2325 'string<))
2326 (unless (member file '("./" "../"))
2327 (if (markdown-directory-name-p file)
2328 (let* ((leaf (substring file 0 (1- (length file))))
2329 (full-file (expand-file-name leaf dir)))
2330 (setq result
2331 (nconc result (markdown-directory-files-recursively
2332 full-file regexp))))
2333 (when (string-match-p regexp file)
2334 (push (expand-file-name file dir) files)))))
2335 (nconc result (nreverse files))))))
2337 (defun markdown-flyspell-check-word-p ()
2338 "Return t if `flyspell' should check word just before point.
2339 Used for `flyspell-generic-check-word-predicate'."
2340 (save-excursion
2341 (goto-char (1- (point)))
2342 (not (or (markdown-code-block-at-point-p)
2343 (markdown-inline-code-at-point-p)
2344 (markdown-in-comment-p)
2345 (let ((faces (get-text-property (point) 'face)))
2346 (if (listp faces)
2347 (or (memq 'markdown-reference-face faces)
2348 (memq 'markdown-markup-face faces)
2349 (memq 'markdown-plain-url-face faces)
2350 (memq 'markdown-inline-code-face faces)
2351 (memq 'markdown-url-face faces))
2352 (memq faces '(markdown-reference-face
2353 markdown-markup-face
2354 markdown-plain-url-face
2355 markdown-inline-code-face
2356 markdown-url-face))))))))
2358 (defun markdown-font-lock-ensure ()
2359 "Provide `font-lock-ensure' in Emacs 24."
2360 (if (fboundp 'font-lock-ensure)
2361 (font-lock-ensure)
2362 (with-no-warnings
2363 ;; Suppress warning about non-interactive use of
2364 ;; `font-lock-fontify-buffer' in Emacs 25.
2365 (font-lock-fontify-buffer))))
2368 ;;; Markdown Parsing Functions ================================================
2370 (define-obsolete-function-alias
2371 'markdown-cur-line-blank 'markdown-cur-line-blank-p "v2.4")
2372 (define-obsolete-function-alias
2373 'markdown-next-line-blank 'markdown-next-line-blank-p "v2.4")
2375 (defun markdown-cur-line-blank-p ()
2376 "Return t if the current line is blank and nil otherwise."
2377 (save-excursion
2378 (beginning-of-line)
2379 (looking-at-p markdown-regex-blank-line)))
2381 (defun markdown-prev-line-blank ()
2382 "Return t if the previous line is blank and nil otherwise.
2383 If we are at the first line, then consider the previous line to be blank."
2384 (or (= (line-beginning-position) (point-min))
2385 (save-excursion
2386 (forward-line -1)
2387 (looking-at markdown-regex-blank-line))))
2389 (defun markdown-prev-line-blank-p ()
2390 "Like `markdown-prev-line-blank', but preserve `match-data'."
2391 (save-match-data (markdown-prev-line-blank)))
2393 (defun markdown-next-line-blank-p ()
2394 "Return t if the next line is blank and nil otherwise.
2395 If we are at the last line, then consider the next line to be blank."
2396 (or (= (line-end-position) (point-max))
2397 (save-excursion
2398 (forward-line 1)
2399 (markdown-cur-line-blank-p))))
2401 (defun markdown-prev-line-indent ()
2402 "Return the number of leading whitespace characters in the previous line.
2403 Return 0 if the current line is the first line in the buffer."
2404 (save-excursion
2405 (if (= (line-beginning-position) (point-min))
2407 (forward-line -1)
2408 (current-indentation))))
2410 (defun markdown-next-line-indent ()
2411 "Return the number of leading whitespace characters in the next line.
2412 Return 0 if line is the last line in the buffer."
2413 (save-excursion
2414 (if (= (line-end-position) (point-max))
2416 (forward-line 1)
2417 (current-indentation))))
2419 (defun markdown-new-baseline ()
2420 "Determine if the current line begins a new baseline level.
2421 Assume point is positioned at beginning of line."
2422 (or (looking-at markdown-regex-header)
2423 (looking-at markdown-regex-hr)
2424 (and (= (current-indentation) 0)
2425 (not (looking-at markdown-regex-list))
2426 (markdown-prev-line-blank))))
2428 (defun markdown-search-backward-baseline ()
2429 "Search backward baseline point with no indentation and not a list item."
2430 (end-of-line)
2431 (let (stop)
2432 (while (not (or stop (bobp)))
2433 (re-search-backward markdown-regex-block-separator-noindent nil t)
2434 (when (match-end 2)
2435 (goto-char (match-end 2))
2436 (cond
2437 ((markdown-new-baseline)
2438 (setq stop t))
2439 ((looking-at-p markdown-regex-list)
2440 (setq stop nil))
2441 (t (setq stop t)))))))
2443 (defun markdown-update-list-levels (marker indent levels)
2444 "Update list levels given list MARKER, block INDENT, and current LEVELS.
2445 Here, MARKER is a string representing the type of list, INDENT is an integer
2446 giving the indentation, in spaces, of the current block, and LEVELS is a
2447 list of the indentation levels of parent list items. When LEVELS is nil,
2448 it means we are at baseline (not inside of a nested list)."
2449 (cond
2450 ;; New list item at baseline.
2451 ((and marker (null levels))
2452 (setq levels (list indent)))
2453 ;; List item with greater indentation (four or more spaces).
2454 ;; Increase list level.
2455 ((and marker (>= indent (+ (car levels) 4)))
2456 (setq levels (cons indent levels)))
2457 ;; List item with greater or equal indentation (less than four spaces).
2458 ;; Do not increase list level.
2459 ((and marker (>= indent (car levels)))
2460 levels)
2461 ;; Lesser indentation level.
2462 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
2463 ;; indentation could move back more than one list level). Note
2464 ;; that this block need not be the beginning of list item.
2465 ((< indent (car levels))
2466 (while (and (> (length levels) 1)
2467 (< indent (+ (cadr levels) 4)))
2468 (setq levels (cdr levels)))
2469 levels)
2470 ;; Otherwise, do nothing.
2471 (t levels)))
2473 (defun markdown-calculate-list-levels ()
2474 "Calculate list levels at point.
2475 Return a list of the form (n1 n2 n3 ...) where n1 is the
2476 indentation of the deepest nested list item in the branch of
2477 the list at the point, n2 is the indentation of the parent
2478 list item, and so on. The depth of the list item is therefore
2479 the length of the returned list. If the point is not at or
2480 immediately after a list item, return nil."
2481 (save-excursion
2482 (let ((first (point)) levels indent pre-regexp)
2483 ;; Find a baseline point with zero list indentation
2484 (markdown-search-backward-baseline)
2485 ;; Search for all list items between baseline and LOC
2486 (while (and (< (point) first)
2487 (re-search-forward markdown-regex-list first t))
2488 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
2489 (beginning-of-line)
2490 (cond
2491 ;; Make sure this is not a header or hr
2492 ((markdown-new-baseline) (setq levels nil))
2493 ;; Make sure this is not a line from a pre block
2494 ((looking-at-p pre-regexp))
2495 ;; If not, then update levels
2497 (setq indent (current-indentation))
2498 (setq levels (markdown-update-list-levels (match-string 2)
2499 indent levels))))
2500 (end-of-line))
2501 levels)))
2503 (defun markdown-prev-list-item (level)
2504 "Search backward from point for a list item with indentation LEVEL.
2505 Set point to the beginning of the item, and return point, or nil
2506 upon failure."
2507 (let (bounds indent prev)
2508 (setq prev (point))
2509 (forward-line -1)
2510 (setq indent (current-indentation))
2511 (while
2512 (cond
2513 ;; List item
2514 ((and (looking-at-p markdown-regex-list)
2515 (setq bounds (markdown-cur-list-item-bounds)))
2516 (cond
2517 ;; Stop and return point at item of equal indentation
2518 ((= (nth 3 bounds) level)
2519 (setq prev (point))
2520 nil)
2521 ;; Stop and return nil at item with lesser indentation
2522 ((< (nth 3 bounds) level)
2523 (setq prev nil)
2524 nil)
2525 ;; Stop at beginning of buffer
2526 ((bobp) (setq prev nil))
2527 ;; Continue at item with greater indentation
2528 ((> (nth 3 bounds) level) t)))
2529 ;; Stop at beginning of buffer
2530 ((bobp) (setq prev nil))
2531 ;; Continue if current line is blank
2532 ((markdown-cur-line-blank-p) t)
2533 ;; Continue while indentation is the same or greater
2534 ((>= indent level) t)
2535 ;; Stop if current indentation is less than list item
2536 ;; and the next is blank
2537 ((and (< indent level)
2538 (markdown-next-line-blank-p))
2539 (setq prev nil))
2540 ;; Stop at a header
2541 ((looking-at-p markdown-regex-header) (setq prev nil))
2542 ;; Stop at a horizontal rule
2543 ((looking-at-p markdown-regex-hr) (setq prev nil))
2544 ;; Otherwise, continue.
2545 (t t))
2546 (forward-line -1)
2547 (setq indent (current-indentation)))
2548 prev))
2550 (defun markdown-next-list-item (level)
2551 "Search forward from point for the next list item with indentation LEVEL.
2552 Set point to the beginning of the item, and return point, or nil
2553 upon failure."
2554 (let (bounds indent next)
2555 (setq next (point))
2556 (if (looking-at markdown-regex-header-setext)
2557 (goto-char (match-end 0)))
2558 (forward-line)
2559 (setq indent (current-indentation))
2560 (while
2561 (cond
2562 ;; Stop at end of the buffer.
2563 ((eobp) nil)
2564 ;; Continue if the current line is blank
2565 ((markdown-cur-line-blank-p) t)
2566 ;; List item
2567 ((and (looking-at-p markdown-regex-list)
2568 (setq bounds (markdown-cur-list-item-bounds)))
2569 (cond
2570 ;; Continue at item with greater indentation
2571 ((> (nth 3 bounds) level) t)
2572 ;; Stop and return point at item of equal indentation
2573 ((= (nth 3 bounds) level)
2574 (setq next (point))
2575 nil)
2576 ;; Stop and return nil at item with lesser indentation
2577 ((< (nth 3 bounds) level)
2578 (setq next nil)
2579 nil)))
2580 ;; Continue while indentation is the same or greater
2581 ((>= indent level) t)
2582 ;; Stop if current indentation is less than list item
2583 ;; and the previous line was blank.
2584 ((and (< indent level)
2585 (markdown-prev-line-blank-p))
2586 (setq next nil))
2587 ;; Stop at a header
2588 ((looking-at-p markdown-regex-header) (setq next nil))
2589 ;; Stop at a horizontal rule
2590 ((looking-at-p markdown-regex-hr) (setq next nil))
2591 ;; Otherwise, continue.
2592 (t t))
2593 (forward-line)
2594 (setq indent (current-indentation)))
2595 next))
2597 (defun markdown-cur-list-item-end (level)
2598 "Move to end of list item with pre-marker indentation LEVEL.
2599 Return the point at the end when a list item was found at the
2600 original point. If the point is not in a list item, do nothing."
2601 (let (indent)
2602 (forward-line)
2603 (setq indent (current-indentation))
2604 (while
2605 (cond
2606 ;; Stop at end of the buffer.
2607 ((eobp) nil)
2608 ;; Continue while indentation is the same or greater
2609 ((>= indent level) t)
2610 ;; Continue if the current line is blank
2611 ((looking-at markdown-regex-blank-line) t)
2612 ;; Stop if current indentation is less than list item
2613 ;; and the previous line was blank.
2614 ((and (< indent level)
2615 (markdown-prev-line-blank))
2616 nil)
2617 ;; Stop at a new list items of the same or lesser
2618 ;; indentation, headings, and horizontal rules.
2619 ((looking-at (concat "\\(?:" markdown-regex-list
2620 "\\|" markdown-regex-header
2621 "\\|" markdown-regex-hr "\\)"))
2622 nil)
2623 ;; Otherwise, continue.
2624 (t t))
2625 (forward-line)
2626 (setq indent (current-indentation)))
2627 ;; Don't skip over whitespace for empty list items (marker and
2628 ;; whitespace only), just move to end of whitespace.
2629 (if (save-excursion
2630 (beginning-of-line)
2631 (looking-at (concat markdown-regex-list "[ \t]*$")))
2632 (goto-char (match-end 3))
2633 (skip-chars-backward " \t\n"))
2634 (end-of-line)
2635 (point)))
2637 (defun markdown-cur-list-item-bounds ()
2638 "Return bounds for list item at point.
2639 Return a list of the following form:
2641 (begin end indent nonlist-indent marker checkbox match)
2643 The named components are:
2645 - begin: Position of beginning of list item, including leading indentation.
2646 - end: Position of the end of the list item, including list item text.
2647 - indent: Number of characters of indentation before list marker (an integer).
2648 - nonlist-indent: Number characters of indentation, list
2649 marker, and whitespace following list marker (an integer).
2650 - marker: String containing the list marker and following whitespace
2651 (e.g., \"- \" or \"* \").
2652 - checkbox: String containing the GFM checkbox portion, if any,
2653 including any trailing whitespace before the text
2654 begins (e.g., \"[x] \").
2655 - match: match data for markdown-regex-list
2657 As an example, for the following unordered list item
2659 - item
2661 the returned list would be
2663 (1 14 3 5 \"- \" nil (1 6 1 4 4 5 5 6))
2665 If the point is not inside a list item, return nil."
2666 (car (get-text-property (point-at-bol) 'markdown-list-item)))
2668 (defun markdown-list-item-at-point-p ()
2669 "Return t if there is a list item at the point and nil otherwise."
2670 (save-match-data (markdown-cur-list-item-bounds)))
2672 (defun markdown-prev-list-item-bounds ()
2673 "Return bounds of previous item in the same list of any level.
2674 The return value has the same form as that of
2675 `markdown-cur-list-item-bounds'."
2676 (save-excursion
2677 (let ((cur-bounds (markdown-cur-list-item-bounds))
2678 (beginning-of-list (save-excursion (markdown-beginning-of-list)))
2679 stop)
2680 (when cur-bounds
2681 (goto-char (nth 0 cur-bounds))
2682 (while (and (not stop) (not (bobp))
2683 (re-search-backward markdown-regex-list
2684 beginning-of-list t))
2685 (unless (or (looking-at markdown-regex-hr)
2686 (markdown-code-block-at-point-p))
2687 (setq stop (point))))
2688 (markdown-cur-list-item-bounds)))))
2690 (defun markdown-next-list-item-bounds ()
2691 "Return bounds of next item in the same list of any level.
2692 The return value has the same form as that of
2693 `markdown-cur-list-item-bounds'."
2694 (save-excursion
2695 (let ((cur-bounds (markdown-cur-list-item-bounds))
2696 (end-of-list (save-excursion (markdown-end-of-list)))
2697 stop)
2698 (when cur-bounds
2699 (goto-char (nth 0 cur-bounds))
2700 (end-of-line)
2701 (while (and (not stop) (not (eobp))
2702 (re-search-forward markdown-regex-list
2703 end-of-list t))
2704 (unless (or (looking-at markdown-regex-hr)
2705 (markdown-code-block-at-point-p))
2706 (setq stop (point))))
2707 (when stop
2708 (markdown-cur-list-item-bounds))))))
2710 (defun markdown-beginning-of-list ()
2711 "Move point to beginning of list at point, if any."
2712 (interactive)
2713 (let ((orig-point (point))
2714 (list-begin (save-excursion
2715 (markdown-search-backward-baseline)
2716 ;; Stop at next list item, regardless of the indentation.
2717 (markdown-next-list-item (point-max))
2718 (when (looking-at markdown-regex-list)
2719 (point)))))
2720 (when (and list-begin (<= list-begin orig-point))
2721 (goto-char list-begin))))
2723 (defun markdown-end-of-list ()
2724 "Move point to end of list at point, if any."
2725 (interactive)
2726 (let ((start (point))
2727 (end (save-excursion
2728 (when (markdown-beginning-of-list)
2729 ;; Items can't have nonlist-indent <= 1, so this
2730 ;; moves past all list items.
2731 (markdown-next-list-item 1)
2732 (skip-syntax-backward "-")
2733 (unless (eobp) (forward-char 1))
2734 (point)))))
2735 (when (and end (>= end start))
2736 (goto-char end))))
2738 (defun markdown-up-list ()
2739 "Move point to beginning of parent list item."
2740 (interactive)
2741 (let ((cur-bounds (markdown-cur-list-item-bounds)))
2742 (when cur-bounds
2743 (markdown-prev-list-item (1- (nth 3 cur-bounds)))
2744 (let ((up-bounds (markdown-cur-list-item-bounds)))
2745 (when (and up-bounds (< (nth 3 up-bounds) (nth 3 cur-bounds)))
2746 (point))))))
2748 (defun markdown-bounds-of-thing-at-point (thing)
2749 "Call `bounds-of-thing-at-point' for THING with slight modifications.
2750 Does not include trailing newlines when THING is 'line. Handles the
2751 end of buffer case by setting both endpoints equal to the value of
2752 `point-max', since an empty region will trigger empty markup insertion.
2753 Return bounds of form (beg . end) if THING is found, or nil otherwise."
2754 (let* ((bounds (bounds-of-thing-at-point thing))
2755 (a (car bounds))
2756 (b (cdr bounds)))
2757 (when bounds
2758 (when (eq thing 'line)
2759 (cond ((and (eobp) (markdown-cur-line-blank-p))
2760 (setq a b))
2761 ((char-equal (char-before b) ?\^J)
2762 (setq b (1- b)))))
2763 (cons a b))))
2765 (defun markdown-reference-definition (reference)
2766 "Find out whether Markdown REFERENCE is defined.
2767 REFERENCE should not include the square brackets.
2768 When REFERENCE is defined, return a list of the form (text start end)
2769 containing the definition text itself followed by the start and end
2770 locations of the text. Otherwise, return nil.
2771 Leave match data for `markdown-regex-reference-definition'
2772 intact additional processing."
2773 (let ((reference (downcase reference)))
2774 (save-excursion
2775 (goto-char (point-min))
2776 (catch 'found
2777 (while (re-search-forward markdown-regex-reference-definition nil t)
2778 (when (string= reference (downcase (match-string-no-properties 2)))
2779 (throw 'found
2780 (list (match-string-no-properties 5)
2781 (match-beginning 5) (match-end 5)))))))))
2783 (defun markdown-get-defined-references ()
2784 "Return all defined reference labels and their line numbers (not including square brackets)."
2785 (save-excursion
2786 (goto-char (point-min))
2787 (let (refs)
2788 (while (re-search-forward markdown-regex-reference-definition nil t)
2789 (let ((target (match-string-no-properties 2)))
2790 (cl-pushnew
2791 (cons (downcase target)
2792 (markdown-line-number-at-pos (match-beginning 2)))
2793 refs :test #'equal :key #'car)))
2794 (reverse refs))))
2796 (defun markdown-get-used-uris ()
2797 "Return a list of all used URIs in the buffer."
2798 (save-excursion
2799 (goto-char (point-min))
2800 (let (uris)
2801 (while (re-search-forward
2802 (concat "\\(?:" markdown-regex-link-inline
2803 "\\|" markdown-regex-angle-uri
2804 "\\|" markdown-regex-uri
2805 "\\|" markdown-regex-email
2806 "\\)")
2807 nil t)
2808 (unless (or (markdown-inline-code-at-point-p)
2809 (markdown-code-block-at-point-p))
2810 (cl-pushnew (or (match-string-no-properties 6)
2811 (match-string-no-properties 10)
2812 (match-string-no-properties 12)
2813 (match-string-no-properties 13))
2814 uris :test #'equal)))
2815 (reverse uris))))
2817 (defun markdown-inline-code-at-pos (pos)
2818 "Return non-nil if there is an inline code fragment at POS.
2819 Return nil otherwise. Set match data according to
2820 `markdown-match-code' upon success.
2821 This function searches the block for a code fragment that
2822 contains the point using `markdown-match-code'. We do this
2823 because `thing-at-point-looking-at' does not work reliably with
2824 `markdown-regex-code'.
2826 The match data is set as follows:
2827 Group 1 matches the opening backquotes.
2828 Group 2 matches the code fragment itself, without backquotes.
2829 Group 3 matches the closing backquotes."
2830 (save-excursion
2831 (goto-char pos)
2832 (let ((old-point (point))
2833 (end-of-block (progn (markdown-end-of-text-block) (point)))
2834 found)
2835 (markdown-beginning-of-text-block)
2836 (while (and (markdown-match-code end-of-block)
2837 (setq found t)
2838 (< (match-end 0) old-point)))
2839 (and found ; matched something
2840 (<= (match-beginning 0) old-point) ; match contains old-point
2841 (>= (match-end 0) old-point)))))
2843 (defun markdown-inline-code-at-pos-p (pos)
2844 "Return non-nil if there is an inline code fragment at POS.
2845 Like `markdown-inline-code-at-pos`, but preserves match data."
2846 (save-match-data (markdown-inline-code-at-pos pos)))
2848 (defun markdown-inline-code-at-point ()
2849 "Return non-nil if the point is at an inline code fragment.
2850 See `markdown-inline-code-at-pos' for details."
2851 (markdown-inline-code-at-pos (point)))
2853 (defun markdown-inline-code-at-point-p ()
2854 "Return non-nil if there is inline code at the point.
2855 This is a predicate function counterpart to
2856 `markdown-inline-code-at-point' which does not modify the match
2857 data. See `markdown-code-block-at-point-p' for code blocks."
2858 (save-match-data (markdown-inline-code-at-pos (point))))
2860 (make-obsolete 'markdown-code-at-point-p 'markdown-inline-code-at-point-p "v2.2")
2862 (defun markdown--code-block-at-pos-no-syntax (pos)
2863 "Return match data list if there may be a code block at POS.
2864 This includes pre blocks, tilde-fenced code blocks, and GFM
2865 quoted code blocks. Return nil otherwise. This function does not
2866 use text properties, which have not yet been set during the
2867 syntax propertization phase."
2868 (setq pos (save-excursion (goto-char pos) (point-at-bol)))
2869 (let (match)
2870 (cond
2871 ;; Indented code blocks
2872 ((looking-at markdown-regex-pre)
2873 (let ((start (save-excursion
2874 (markdown-search-backward-baseline) (point)))
2875 (end (save-excursion
2876 (while (and (or (looking-at-p markdown-regex-pre)
2877 (markdown-cur-line-blank-p))
2878 (not (eobp)))
2879 (forward-line))
2880 (point))))
2881 (list start end start start start end end end)))
2882 ;; Fenced code blocks
2883 ((setq match (markdown-get-enclosing-fenced-block-construct pos))
2884 match))))
2886 (defun markdown-code-block-at-pos (pos)
2887 "Return match data list if there is a code block at POS.
2888 This includes pre blocks, tilde-fenced code blocks, and GFM
2889 quoted code blocks. Return nil otherwise. This function uses
2890 cached text properties at the beginning of the line position for
2891 performance reasons, but therefore it must run after the syntax
2892 propertization phase."
2893 (setq pos (save-excursion (goto-char pos) (point-at-bol)))
2894 (or (get-text-property pos 'markdown-pre)
2895 ;;(markdown-get-enclosing-fenced-block-construct pos)
2896 (when (markdown-range-properties-exist
2897 pos pos '(markdown-gfm-block-begin
2898 markdown-gfm-code
2899 markdown-gfm-block-end
2900 markdown-tilde-fence-begin
2901 markdown-fenced-code
2902 markdown-tilde-fence-end
2903 markdown-yaml-metadata-begin
2904 markdown-yaml-metadata-section
2905 markdown-yaml-metadata-end))
2906 (markdown-get-enclosing-fenced-block-construct pos))
2907 ;; polymode removes text properties set by markdown-mode, so
2908 ;; check if `poly-markdown-mode' is active and whether the
2909 ;; `chunkmode' property is non-nil at POS.
2910 (and (bound-and-true-p poly-markdown-mode)
2911 (get-text-property pos 'chunkmode))))
2913 ;; Function was renamed to emphasize that it does not modify match-data.
2914 (defalias 'markdown-code-block-at-point 'markdown-code-block-at-point-p)
2916 (defun markdown-code-block-at-point-p ()
2917 "Return non-nil if there is a code block at the point.
2918 This includes pre blocks, tilde-fenced code blocks, and GFM
2919 quoted code blocks. This function does not modify the match
2920 data. See `markdown-inline-code-at-point-p' for inline code."
2921 (save-match-data (markdown-code-block-at-pos (point))))
2923 (defun markdown-heading-at-point ()
2924 "Return non-nil if there is a heading at the point.
2925 Set match data for `markdown-regex-header'."
2926 (let ((match-data (get-text-property (point) 'markdown-heading)))
2927 (when match-data
2928 (set-match-data match-data)
2929 t)))
2931 (defun markdown-pipe-at-bol-p ()
2932 "Return non-nil if the line begins with a pipe symbol.
2933 This may be useful for tables and Pandoc's line_blocks extension."
2934 (char-equal (char-after (point-at-bol)) ?|))
2937 ;;; Markdown Font Lock Matching Functions =====================================
2939 (defun markdown-range-property-any (begin end prop prop-values)
2940 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
2941 Also returns t if PROP is a list containing one of the PROP-VALUES.
2942 Return nil otherwise."
2943 (let (props)
2944 (catch 'found
2945 (dolist (loc (number-sequence begin end))
2946 (when (setq props (get-text-property loc prop))
2947 (cond ((listp props)
2948 ;; props is a list, check for membership
2949 (dolist (val prop-values)
2950 (when (memq val props) (throw 'found loc))))
2952 ;; props is a scalar, check for equality
2953 (dolist (val prop-values)
2954 (when (eq val props) (throw 'found loc))))))))))
2956 (defun markdown-range-properties-exist (begin end props)
2957 (cl-loop
2958 for loc in (number-sequence begin end)
2959 with result = nil
2960 while (not
2961 (setq result
2962 (cl-some (lambda (prop) (get-text-property loc prop)) props)))
2963 finally return result))
2965 (defun markdown-match-inline-generic (regex last &optional faceless)
2966 "Match inline REGEX from the point to LAST.
2967 When FACELESS is non-nil, do not return matches where faces have been applied."
2968 (when (re-search-forward regex last t)
2969 (let ((bounds (markdown-code-block-at-pos (match-beginning 1)))
2970 (face (and faceless (text-property-not-all
2971 (match-beginning 0) (match-end 0) 'face nil))))
2972 (cond
2973 ;; In code block: move past it and recursively search again
2974 (bounds
2975 (when (< (goto-char (cl-second bounds)) last)
2976 (markdown-match-inline-generic regex last faceless)))
2977 ;; When faces are found in the match range, skip over the match and
2978 ;; recursively search again.
2979 (face
2980 (when (< (goto-char (match-end 0)) last)
2981 (markdown-match-inline-generic regex last faceless)))
2982 ;; Keep match data and return t when in bounds.
2984 (<= (match-end 0) last))))))
2986 (defun markdown-match-code (last)
2987 "Match inline code fragments from point to LAST."
2988 (unless (bobp)
2989 (backward-char 1))
2990 (when (markdown-search-until-condition
2991 (lambda ()
2992 (and
2993 ;; Advance point in case of failure, but without exceeding last.
2994 (goto-char (min (1+ (match-beginning 1)) last))
2995 (not (markdown-in-comment-p (match-beginning 1)))
2996 (not (markdown-in-comment-p (match-end 1)))
2997 (not (markdown-code-block-at-pos (match-beginning 1)))))
2998 markdown-regex-code last t)
2999 (set-match-data (list (match-beginning 1) (match-end 1)
3000 (match-beginning 2) (match-end 2)
3001 (match-beginning 3) (match-end 3)
3002 (match-beginning 4) (match-end 4)))
3003 (goto-char (min (1+ (match-end 0)) last (point-max)))
3006 (defun markdown-match-bold (last)
3007 "Match inline bold from the point to LAST."
3008 (when (markdown-match-inline-generic markdown-regex-bold last)
3009 (let ((begin (match-beginning 2))
3010 (end (match-end 2)))
3011 (if (or (markdown-inline-code-at-pos-p begin)
3012 (markdown-inline-code-at-pos-p end)
3013 (markdown-in-comment-p)
3014 (markdown-range-property-any
3015 begin begin 'face '(markdown-url-face
3016 markdown-plain-url-face))
3017 (markdown-range-property-any
3018 begin end 'face '(markdown-hr-face
3019 markdown-math-face)))
3020 (progn (goto-char (min (1+ begin) last))
3021 (when (< (point) last)
3022 (markdown-match-italic last)))
3023 (set-match-data (list (match-beginning 2) (match-end 2)
3024 (match-beginning 3) (match-end 3)
3025 (match-beginning 4) (match-end 4)
3026 (match-beginning 5) (match-end 5)))
3027 t))))
3029 (defun markdown-match-italic (last)
3030 "Match inline italics from the point to LAST."
3031 (let ((regex (if (memq major-mode '(gfm-mode gfm-view-mode))
3032 markdown-regex-gfm-italic markdown-regex-italic)))
3033 (when (markdown-match-inline-generic regex last)
3034 (let ((begin (match-beginning 1))
3035 (end (match-end 1)))
3036 (if (or (markdown-inline-code-at-pos-p begin)
3037 (markdown-inline-code-at-pos-p end)
3038 (markdown-in-comment-p)
3039 (markdown-range-property-any
3040 begin begin 'face '(markdown-url-face
3041 markdown-plain-url-face))
3042 (markdown-range-property-any
3043 begin end 'face '(markdown-bold-face
3044 markdown-list-face
3045 markdown-hr-face
3046 markdown-math-face)))
3047 (progn (goto-char (min (1+ begin) last))
3048 (when (< (point) last)
3049 (markdown-match-italic last)))
3050 (set-match-data (list (match-beginning 1) (match-end 1)
3051 (match-beginning 2) (match-end 2)
3052 (match-beginning 3) (match-end 3)
3053 (match-beginning 4) (match-end 4)))
3054 t)))))
3056 (defun markdown-match-math-generic (regex last)
3057 "Match REGEX from point to LAST.
3058 REGEX is either `markdown-regex-math-inline-single' for matching
3059 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
3060 (when (and markdown-enable-math (markdown-match-inline-generic regex last))
3061 (let ((begin (match-beginning 1)) (end (match-end 1)))
3062 (prog1
3063 (if (or (markdown-range-property-any
3064 begin end 'face
3065 '(markdown-inline-code-face markdown-bold-face))
3066 (markdown-range-properties-exist
3067 begin end
3068 (markdown-get-fenced-block-middle-properties)))
3069 (markdown-match-math-generic regex last)
3071 (goto-char (1+ (match-end 0)))))))
3073 (defun markdown-match-list-items (last)
3074 "Match list items from point to LAST."
3075 (let* ((first (point))
3076 (pos first)
3077 (prop 'markdown-list-item)
3078 (bounds (car (get-text-property pos prop))))
3079 (while
3080 (and (or (null (setq bounds (car (get-text-property pos prop))))
3081 (< (cl-first bounds) pos))
3082 (< (point) last)
3083 (setq pos (next-single-property-change pos prop nil last))
3084 (goto-char pos)))
3085 (when bounds
3086 (set-match-data (cl-seventh bounds))
3087 ;; Step at least one character beyond point. Otherwise
3088 ;; `font-lock-fontify-keywords-region' infloops.
3089 (goto-char (min (1+ (max (point-at-eol) first))
3090 (point-max)))
3091 t)))
3093 (defun markdown-match-math-single (last)
3094 "Match single quoted $..$ math from point to LAST."
3095 (markdown-match-math-generic markdown-regex-math-inline-single last))
3097 (defun markdown-match-math-double (last)
3098 "Match double quoted $$..$$ math from point to LAST."
3099 (markdown-match-math-generic markdown-regex-math-inline-double last))
3101 (defun markdown-match-math-display (last)
3102 "Match bracketed display math \[..\] and \\[..\\] from point to LAST."
3103 (markdown-match-math-generic markdown-regex-math-display last))
3105 (defun markdown-match-propertized-text (property last)
3106 "Match text with PROPERTY from point to LAST.
3107 Restore match data previously stored in PROPERTY."
3108 (let ((saved (get-text-property (point) property))
3109 pos)
3110 (unless saved
3111 (setq pos (next-single-property-change (point) property nil last))
3112 (setq saved (get-text-property pos property)))
3113 (when saved
3114 (set-match-data saved)
3115 ;; Step at least one character beyond point. Otherwise
3116 ;; `font-lock-fontify-keywords-region' infloops.
3117 (goto-char (min (1+ (max (match-end 0) (point)))
3118 (point-max)))
3119 saved)))
3121 (defun markdown-match-pre-blocks (last)
3122 "Match preformatted blocks from point to LAST.
3123 Use data stored in 'markdown-pre text property during syntax
3124 analysis."
3125 (markdown-match-propertized-text 'markdown-pre last))
3127 (defun markdown-match-gfm-code-blocks (last)
3128 "Match GFM quoted code blocks from point to LAST.
3129 Use data stored in 'markdown-gfm-code text property during syntax
3130 analysis."
3131 (markdown-match-propertized-text 'markdown-gfm-code last))
3133 (defun markdown-match-gfm-open-code-blocks (last)
3134 (markdown-match-propertized-text 'markdown-gfm-block-begin last))
3136 (defun markdown-match-gfm-close-code-blocks (last)
3137 (markdown-match-propertized-text 'markdown-gfm-block-end last))
3139 (defun markdown-match-fenced-code-blocks (last)
3140 "Match fenced code blocks from the point to LAST."
3141 (markdown-match-propertized-text 'markdown-fenced-code last))
3143 (defun markdown-match-fenced-start-code-block (last)
3144 (markdown-match-propertized-text 'markdown-tilde-fence-begin last))
3146 (defun markdown-match-fenced-end-code-block (last)
3147 (markdown-match-propertized-text 'markdown-tilde-fence-end last))
3149 (defun markdown-match-blockquotes (last)
3150 "Match blockquotes from point to LAST.
3151 Use data stored in 'markdown-blockquote text property during syntax
3152 analysis."
3153 (markdown-match-propertized-text 'markdown-blockquote last))
3155 (defun markdown-match-hr (last)
3156 "Match horizontal rules comments from the point to LAST."
3157 (markdown-match-propertized-text 'markdown-hr last))
3159 (defun markdown-match-comments (last)
3160 "Match HTML comments from the point to LAST."
3161 (when (and (skip-syntax-forward "^<" last))
3162 (let ((beg (point)))
3163 (when (and (skip-syntax-forward "^>" last) (< (point) last))
3164 (forward-char)
3165 (set-match-data (list beg (point)))
3166 t))))
3168 (defun markdown-match-generic-links (last ref)
3169 "Match inline links from point to LAST.
3170 When REF is non-nil, match reference links instead of standard
3171 links with URLs.
3172 This function should only be used during font-lock, as it
3173 determines syntax based on the presence of faces for previously
3174 processed elements."
3175 ;; Search for the next potential link (not in a code block).
3176 (let ((prohibited-faces '(markdown-pre-face
3177 markdown-code-face
3178 markdown-inline-code-face
3179 markdown-comment-face))
3180 found)
3181 (while
3182 (and (not found) (< (point) last)
3183 (progn
3184 ;; Clear match data to test for a match after functions returns.
3185 (set-match-data nil)
3186 ;; Preliminary regular expression search so we can return
3187 ;; quickly upon failure. This doesn't handle malformed links
3188 ;; or nested square brackets well, so if it passes we back up
3189 ;; continue with a more precise search.
3190 (re-search-forward
3191 (if ref
3192 markdown-regex-link-reference
3193 markdown-regex-link-inline)
3194 last 'limit)))
3195 ;; Keep searching if this is in a code block, inline code, or a
3196 ;; comment, or if it is include syntax. The link text portion
3197 ;; (group 3) may contain inline code or comments, but the
3198 ;; markup, URL, and title should not be part of such elements.
3199 (if (or (markdown-range-property-any
3200 (match-beginning 0) (match-end 2) 'face prohibited-faces)
3201 (markdown-range-property-any
3202 (match-beginning 4) (match-end 0) 'face prohibited-faces)
3203 (and (char-equal (char-after (point-at-bol)) ?<)
3204 (char-equal (char-after (1+ (point-at-bol))) ?<)))
3205 (set-match-data nil)
3206 (setq found t))))
3207 ;; Match opening exclamation point (optional) and left bracket.
3208 (when (match-beginning 2)
3209 (let* ((bang (match-beginning 1))
3210 (first-begin (match-beginning 2))
3211 ;; Find end of block to prevent matching across blocks.
3212 (end-of-block (save-excursion
3213 (progn
3214 (goto-char (match-beginning 2))
3215 (markdown-end-of-text-block)
3216 (point))))
3217 ;; Move over balanced expressions to closing right bracket.
3218 ;; Catch unbalanced expression errors and return nil.
3219 (first-end (condition-case nil
3220 (and (goto-char first-begin)
3221 (scan-sexps (point) 1))
3222 (error nil)))
3223 ;; Continue with point at CONT-POINT upon failure.
3224 (cont-point (min (1+ first-begin) last))
3225 second-begin second-end url-begin url-end
3226 title-begin title-end)
3227 ;; When bracket found, in range, and followed by a left paren/bracket...
3228 (when (and first-end (< first-end end-of-block) (goto-char first-end)
3229 (char-equal (char-after (point)) (if ref ?\[ ?\()))
3230 ;; Scan across balanced expressions for closing parenthesis/bracket.
3231 (setq second-begin (point)
3232 second-end (condition-case nil
3233 (scan-sexps (point) 1)
3234 (error nil)))
3235 ;; Check that closing parenthesis/bracket is in range.
3236 (if (and second-end (<= second-end end-of-block) (<= second-end last))
3237 (progn
3238 ;; Search for (optional) title inside closing parenthesis
3239 (when (and (not ref) (search-forward "\"" second-end t))
3240 (setq title-begin (1- (point))
3241 title-end (and (goto-char second-end)
3242 (search-backward "\"" (1+ title-begin) t))
3243 title-end (and title-end (1+ title-end))))
3244 ;; Store URL/reference range
3245 (setq url-begin (1+ second-begin)
3246 url-end (1- (or title-begin second-end)))
3247 ;; Set match data, move point beyond link, and return
3248 (set-match-data
3249 (list (or bang first-begin) second-end ; 0 - all
3250 bang (and bang (1+ bang)) ; 1 - bang
3251 first-begin (1+ first-begin) ; 2 - markup
3252 (1+ first-begin) (1- first-end) ; 3 - link text
3253 (1- first-end) first-end ; 4 - markup
3254 second-begin (1+ second-begin) ; 5 - markup
3255 url-begin url-end ; 6 - url/reference
3256 title-begin title-end ; 7 - title
3257 (1- second-end) second-end)) ; 8 - markup
3258 ;; Nullify cont-point and leave point at end and
3259 (setq cont-point nil)
3260 (goto-char second-end))
3261 ;; If no closing parenthesis in range, update continuation point
3262 (setq cont-point (min end-of-block second-begin))))
3263 (cond
3264 ;; On failure, continue searching at cont-point
3265 ((and cont-point (< cont-point last))
3266 (goto-char cont-point)
3267 (markdown-match-generic-links last ref))
3268 ;; No more text, return nil
3269 ((and cont-point (= cont-point last))
3270 nil)
3271 ;; Return t if a match occurred
3272 (t t)))))
3274 (defun markdown-match-angle-uris (last)
3275 "Match angle bracket URIs from point to LAST."
3276 (when (markdown-match-inline-generic markdown-regex-angle-uri last)
3277 (goto-char (1+ (match-end 0)))))
3279 (defun markdown-match-plain-uris (last)
3280 "Match plain URIs from point to LAST."
3281 (when (markdown-match-inline-generic markdown-regex-uri last t)
3282 (goto-char (1+ (match-end 0)))))
3284 (defvar markdown-conditional-search-function #'re-search-forward
3285 "Conditional search function used in `markdown-search-until-condition'.
3286 Made into a variable to allow for dynamic let-binding.")
3288 (defun markdown-search-until-condition (condition &rest args)
3289 (let (ret)
3290 (while (and (not ret) (apply markdown-conditional-search-function args))
3291 (setq ret (funcall condition)))
3292 ret))
3294 (defun markdown-match-generic-metadata (regexp last)
3295 "Match metadata declarations specified by REGEXP from point to LAST.
3296 These declarations must appear inside a metadata block that begins at
3297 the beginning of the buffer and ends with a blank line (or the end of
3298 the buffer)."
3299 (let* ((first (point))
3300 (end-re "\n[ \t]*\n\\|\n\\'\\|\\'")
3301 (block-begin (goto-char 1))
3302 (block-end (re-search-forward end-re nil t)))
3303 (if (and block-end (> first block-end))
3304 ;; Don't match declarations if there is no metadata block or if
3305 ;; the point is beyond the block. Move point to point-max to
3306 ;; prevent additional searches and return return nil since nothing
3307 ;; was found.
3308 (progn (goto-char (point-max)) nil)
3309 ;; If a block was found that begins before LAST and ends after
3310 ;; point, search for declarations inside it. If the starting is
3311 ;; before the beginning of the block, start there. Otherwise,
3312 ;; move back to FIRST.
3313 (goto-char (if (< first block-begin) block-begin first))
3314 (if (re-search-forward regexp (min last block-end) t)
3315 ;; If a metadata declaration is found, set match-data and return t.
3316 (let ((key-beginning (match-beginning 1))
3317 (key-end (match-end 1))
3318 (markup-begin (match-beginning 2))
3319 (markup-end (match-end 2))
3320 (value-beginning (match-beginning 3)))
3321 (set-match-data (list key-beginning (point) ; complete metadata
3322 key-beginning key-end ; key
3323 markup-begin markup-end ; markup
3324 value-beginning (point))) ; value
3326 ;; Otherwise, move the point to last and return nil
3327 (goto-char last)
3328 nil))))
3330 (defun markdown-match-declarative-metadata (last)
3331 "Match declarative metadata from the point to LAST."
3332 (markdown-match-generic-metadata markdown-regex-declarative-metadata last))
3334 (defun markdown-match-pandoc-metadata (last)
3335 "Match Pandoc metadata from the point to LAST."
3336 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
3338 (defun markdown-match-yaml-metadata-begin (last)
3339 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last))
3341 (defun markdown-match-yaml-metadata-end (last)
3342 (markdown-match-propertized-text 'markdown-yaml-metadata-end last))
3344 (defun markdown-match-yaml-metadata-key (last)
3345 (markdown-match-propertized-text 'markdown-metadata-key last))
3347 (defun markdown-match-wiki-link (last)
3348 "Match wiki links from point to LAST."
3349 (when (and markdown-enable-wiki-links
3350 (not markdown-wiki-link-fontify-missing)
3351 (markdown-match-inline-generic markdown-regex-wiki-link last))
3352 (let ((begin (match-beginning 1)) (end (match-end 1)))
3353 (if (or (markdown-in-comment-p begin)
3354 (markdown-in-comment-p end)
3355 (markdown-inline-code-at-pos-p begin)
3356 (markdown-inline-code-at-pos-p end)
3357 (markdown-code-block-at-pos begin))
3358 (progn (goto-char (min (1+ begin) last))
3359 (when (< (point) last)
3360 (markdown-match-wiki-link last)))
3361 (set-match-data (list begin end))
3362 t))))
3364 (defun markdown-match-inline-attributes (last)
3365 "Match inline attributes from point to LAST."
3366 (when (markdown-match-inline-generic markdown-regex-inline-attributes last)
3367 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
3368 (markdown-inline-code-at-pos-p (match-end 0))
3369 (markdown-in-comment-p))
3370 t)))
3372 (defun markdown-match-leanpub-sections (last)
3373 "Match Leanpub section markers from point to LAST."
3374 (when (markdown-match-inline-generic markdown-regex-leanpub-sections last)
3375 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
3376 (markdown-inline-code-at-pos-p (match-end 0))
3377 (markdown-in-comment-p))
3378 t)))
3380 (defun markdown-match-includes (last)
3381 "Match include statements from point to LAST.
3382 Sets match data for the following seven groups:
3383 Group 1: opening two angle brackets
3384 Group 2: opening title delimiter (optional)
3385 Group 3: title text (optional)
3386 Group 4: closing title delimiter (optional)
3387 Group 5: opening filename delimiter
3388 Group 6: filename
3389 Group 7: closing filename delimiter"
3390 (when (markdown-match-inline-generic markdown-regex-include last)
3391 (let ((valid (not (or (markdown-in-comment-p (match-beginning 0))
3392 (markdown-in-comment-p (match-end 0))
3393 (markdown-code-block-at-pos (match-beginning 0))))))
3394 (cond
3395 ;; Parentheses and maybe square brackets, but no curly braces:
3396 ;; match optional title in square brackets and file in parentheses.
3397 ((and valid (match-beginning 5)
3398 (not (match-beginning 8)))
3399 (set-match-data (list (match-beginning 1) (match-end 7)
3400 (match-beginning 1) (match-end 1)
3401 (match-beginning 2) (match-end 2)
3402 (match-beginning 3) (match-end 3)
3403 (match-beginning 4) (match-end 4)
3404 (match-beginning 5) (match-end 5)
3405 (match-beginning 6) (match-end 6)
3406 (match-beginning 7) (match-end 7))))
3407 ;; Only square brackets present: match file in square brackets.
3408 ((and valid (match-beginning 2)
3409 (not (match-beginning 5))
3410 (not (match-beginning 7)))
3411 (set-match-data (list (match-beginning 1) (match-end 4)
3412 (match-beginning 1) (match-end 1)
3413 nil nil
3414 nil nil
3415 nil nil
3416 (match-beginning 2) (match-end 2)
3417 (match-beginning 3) (match-end 3)
3418 (match-beginning 4) (match-end 4))))
3419 ;; Only curly braces present: match file in curly braces.
3420 ((and valid (match-beginning 8)
3421 (not (match-beginning 2))
3422 (not (match-beginning 5)))
3423 (set-match-data (list (match-beginning 1) (match-end 10)
3424 (match-beginning 1) (match-end 1)
3425 nil nil
3426 nil nil
3427 nil nil
3428 (match-beginning 8) (match-end 8)
3429 (match-beginning 9) (match-end 9)
3430 (match-beginning 10) (match-end 10))))
3432 ;; Not a valid match, move to next line and search again.
3433 (forward-line)
3434 (when (< (point) last)
3435 (setq valid (markdown-match-includes last)))))
3436 valid)))
3438 (defun markdown-match-html-tag (last)
3439 "Match HTML tags from point to LAST."
3440 (when (and markdown-enable-html
3441 (markdown-match-inline-generic markdown-regex-html-tag last t))
3442 (set-match-data (list (match-beginning 0) (match-end 0)
3443 (match-beginning 1) (match-end 1)
3444 (match-beginning 2) (match-end 2)
3445 (match-beginning 9) (match-end 9)))
3449 ;;; Markdown Font Fontification Functions =====================================
3451 (defun markdown--first-displayable (seq)
3452 "Return the first displayable character or string in SEQ.
3453 SEQ may be an atom or a sequence."
3454 (let ((seq (if (listp seq) seq (list seq))))
3455 (cond ((stringp (car seq))
3456 (cl-find-if
3457 (lambda (str)
3458 (and (mapcar #'char-displayable-p (string-to-list str))))
3459 seq))
3460 ((characterp (car seq))
3461 (cl-find-if #'char-displayable-p seq)))))
3463 (defun markdown--marginalize-string (level)
3464 "Generate atx markup string of given LEVEL for left margin."
3465 (let ((margin-left-space-count
3466 (- markdown-marginalize-headers-margin-width level)))
3467 (concat (make-string margin-left-space-count ? )
3468 (make-string level ?#))))
3470 (defun markdown-marginalize-update-current ()
3471 "Update the window configuration to create a left margin."
3472 ;; Emacs 25 or later is needed for window-font-width and default-font-width.
3473 (if (and (fboundp 'window-font-width) (fboundp 'default-font-width))
3474 (let* ((header-delimiter-font-width
3475 (window-font-width nil 'markdown-header-delimiter-face))
3476 (margin-pixel-width (* markdown-marginalize-headers-margin-width
3477 header-delimiter-font-width))
3478 (margin-char-width (/ margin-pixel-width (default-font-width))))
3479 (set-window-margins nil margin-char-width))
3480 ;; As a fallback, simply set margin based on character count.
3481 (set-window-margins nil markdown-marginalize-headers-margin-width)))
3483 (defun markdown-fontify-headings (last)
3484 "Add text properties to headings from point to LAST."
3485 (when (markdown-match-propertized-text 'markdown-heading last)
3486 (let* ((level (markdown-outline-level))
3487 (heading-face
3488 (intern (format "markdown-header-face-%d" level)))
3489 (heading-props `(face ,heading-face))
3490 (left-markup-props
3491 `(face markdown-header-delimiter-face
3492 ,@(cond
3493 (markdown-hide-markup
3494 `(display ""))
3495 (markdown-marginalize-headers
3496 `(display ((margin left-margin)
3497 ,(markdown--marginalize-string level)))))))
3498 (right-markup-props
3499 `(face markdown-header-delimiter-face
3500 ,@(when markdown-hide-markup `(display ""))))
3501 (rule-props `(face markdown-header-rule-face
3502 ,@(when markdown-hide-markup `(display "")))))
3503 (if (match-end 1)
3504 ;; Setext heading
3505 (progn (add-text-properties
3506 (match-beginning 1) (match-end 1) heading-props)
3507 (if (= level 1)
3508 (add-text-properties
3509 (match-beginning 2) (match-end 2) rule-props)
3510 (add-text-properties
3511 (match-beginning 3) (match-end 3) rule-props)))
3512 ;; atx heading
3513 (add-text-properties
3514 (match-beginning 4) (match-end 4) left-markup-props)
3515 (add-text-properties
3516 (match-beginning 5) (match-end 5) heading-props)
3517 (when (match-end 6)
3518 (add-text-properties
3519 (match-beginning 6) (match-end 6) right-markup-props))))
3522 (defun markdown-fontify-tables (last)
3523 (when (and (re-search-forward "|" last t)
3524 (markdown-table-at-point-p))
3525 (font-lock-append-text-property
3526 (line-beginning-position) (min (1+ (line-end-position)) (point-max))
3527 'face 'markdown-table-face)
3528 (forward-line 1)
3531 (defun markdown-fontify-blockquotes (last)
3532 "Apply font-lock properties to blockquotes from point to LAST."
3533 (when (markdown-match-blockquotes last)
3534 (let ((display-string
3535 (markdown--first-displayable markdown-blockquote-display-char)))
3536 (add-text-properties
3537 (match-beginning 1) (match-end 1)
3538 (if markdown-hide-markup
3539 `(face markdown-blockquote-face display ,display-string)
3540 `(face markdown-markup-face)))
3541 (font-lock-append-text-property
3542 (match-beginning 0) (match-end 0) 'face 'markdown-blockquote-face)
3543 t)))
3545 (defun markdown-fontify-list-items (last)
3546 "Apply font-lock properties to list markers from point to LAST."
3547 (when (markdown-match-list-items last)
3548 (let* ((indent (length (match-string-no-properties 1)))
3549 (level (/ indent 4)) ;; level = 0, 1, 2, ...
3550 (bullet (nth (mod level (length markdown-list-item-bullets))
3551 markdown-list-item-bullets)))
3552 (add-text-properties
3553 (match-beginning 2) (match-end 2) '(face markdown-list-face))
3554 (when markdown-hide-markup
3555 (cond
3556 ;; Unordered lists
3557 ((string-match-p "[\\*\\+-]" (match-string 2))
3558 (add-text-properties
3559 (match-beginning 2) (match-end 2) `(display ,bullet)))
3560 ;; Definition lists
3561 ((string-equal ":" (match-string 2))
3562 (let ((display-string
3563 (char-to-string (markdown--first-displayable
3564 markdown-definition-display-char))))
3565 (add-text-properties (match-beginning 2) (match-end 2)
3566 `(display ,display-string)))))))
3569 (defun markdown-fontify-hrs (last)
3570 "Add text properties to horizontal rules from point to LAST."
3571 (when (markdown-match-hr last)
3572 (let ((hr-char (markdown--first-displayable markdown-hr-display-char)))
3573 (add-text-properties
3574 (match-beginning 0) (match-end 0)
3575 `(face markdown-hr-face
3576 font-lock-multiline t
3577 ,@(when (and markdown-hide-markup hr-char)
3578 `(display ,(make-string
3579 (window-body-width) hr-char)))))
3580 t)))
3582 (defun markdown-fontify-sub-superscripts (last)
3583 "Apply text properties to sub- and superscripts from point to LAST."
3584 (when (markdown-search-until-condition
3585 (lambda () (and (not (markdown-code-block-at-point-p))
3586 (not (markdown-inline-code-at-point-p))
3587 (not (markdown-in-comment-p))))
3588 markdown-regex-sub-superscript last t)
3589 (let* ((subscript-p (string= (match-string 2) "~"))
3590 (props
3591 (if subscript-p
3592 (car markdown-sub-superscript-display)
3593 (cdr markdown-sub-superscript-display)))
3594 (mp (list 'face 'markdown-markup-face
3595 'invisible 'markdown-markup)))
3596 (when markdown-hide-markup
3597 (put-text-property (match-beginning 3) (match-end 3)
3598 'display props))
3599 (add-text-properties (match-beginning 2) (match-end 2) mp)
3600 (add-text-properties (match-beginning 4) (match-end 4) mp)
3601 t)))
3604 ;;; Syntax Table ==============================================================
3606 (defvar markdown-mode-syntax-table
3607 (let ((tab (make-syntax-table text-mode-syntax-table)))
3608 (modify-syntax-entry ?\" "." tab)
3609 tab)
3610 "Syntax table for `markdown-mode'.")
3613 ;;; Element Insertion =========================================================
3615 (defun markdown-ensure-blank-line-before ()
3616 "If previous line is not already blank, insert a blank line before point."
3617 (unless (bolp) (insert "\n"))
3618 (unless (or (bobp) (looking-back "\n\\s-*\n" nil)) (insert "\n")))
3620 (defun markdown-ensure-blank-line-after ()
3621 "If following line is not already blank, insert a blank line after point.
3622 Return the point where it was originally."
3623 (save-excursion
3624 (unless (eolp) (insert "\n"))
3625 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
3627 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
3628 "Insert the strings S1 and S2, wrapping around region or THING.
3629 If a region is specified by the optional BEG and END arguments,
3630 wrap the strings S1 and S2 around that region.
3631 If there is an active region, wrap the strings S1 and S2 around
3632 the region. If there is not an active region but the point is at
3633 THING, wrap that thing (which defaults to word). Otherwise, just
3634 insert S1 and S2 and place the point in between. Return the
3635 bounds of the entire wrapped string, or nil if nothing was wrapped
3636 and S1 and S2 were only inserted."
3637 (let (a b bounds new-point)
3638 (cond
3639 ;; Given region
3640 ((and beg end)
3641 (setq a beg
3642 b end
3643 new-point (+ (point) (length s1))))
3644 ;; Active region
3645 ((markdown-use-region-p)
3646 (setq a (region-beginning)
3647 b (region-end)
3648 new-point (+ (point) (length s1))))
3649 ;; Thing (word) at point
3650 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
3651 (setq a (car bounds)
3652 b (cdr bounds)
3653 new-point (+ (point) (length s1))))
3654 ;; No active region and no word
3656 (setq a (point)
3657 b (point))))
3658 (goto-char b)
3659 (insert s2)
3660 (goto-char a)
3661 (insert s1)
3662 (when new-point (goto-char new-point))
3663 (if (= a b)
3665 (setq b (+ b (length s1) (length s2)))
3666 (cons a b))))
3668 (defun markdown-point-after-unwrap (cur prefix suffix)
3669 "Return desired position of point after an unwrapping operation.
3670 CUR gives the position of the point before the operation.
3671 Additionally, two cons cells must be provided. PREFIX gives the
3672 bounds of the prefix string and SUFFIX gives the bounds of the
3673 suffix string."
3674 (cond ((< cur (cdr prefix)) (car prefix))
3675 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
3676 ((<= cur (cdr suffix))
3677 (- cur (+ (- (cdr prefix) (car prefix))
3678 (- cur (car suffix)))))
3679 (t cur)))
3681 (defun markdown-unwrap-thing-at-point (regexp all text)
3682 "Remove prefix and suffix of thing at point and reposition the point.
3683 When the thing at point matches REGEXP, replace the subexpression
3684 ALL with the string in subexpression TEXT. Reposition the point
3685 in an appropriate location accounting for the removal of prefix
3686 and suffix strings. Return new bounds of string from group TEXT.
3687 When REGEXP is nil, assumes match data is already set."
3688 (when (or (null regexp)
3689 (thing-at-point-looking-at regexp))
3690 (let ((cur (point))
3691 (prefix (cons (match-beginning all) (match-beginning text)))
3692 (suffix (cons (match-end text) (match-end all)))
3693 (bounds (cons (match-beginning text) (match-end text))))
3694 ;; Replace the thing at point
3695 (replace-match (match-string text) t t nil all)
3696 ;; Reposition the point
3697 (goto-char (markdown-point-after-unwrap cur prefix suffix))
3698 ;; Adjust bounds
3699 (setq bounds (cons (car prefix)
3700 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
3702 (defun markdown-unwrap-things-in-region (beg end regexp all text)
3703 "Remove prefix and suffix of all things in region from BEG to END.
3704 When a thing in the region matches REGEXP, replace the
3705 subexpression ALL with the string in subexpression TEXT.
3706 Return a cons cell containing updated bounds for the region."
3707 (save-excursion
3708 (goto-char beg)
3709 (let ((removed 0) len-all len-text)
3710 (while (re-search-forward regexp (- end removed) t)
3711 (setq len-all (length (match-string-no-properties all)))
3712 (setq len-text (length (match-string-no-properties text)))
3713 (setq removed (+ removed (- len-all len-text)))
3714 (replace-match (match-string text) t t nil all))
3715 (cons beg (- end removed)))))
3717 (defun markdown-insert-hr (arg)
3718 "Insert or replace a horizonal rule.
3719 By default, use the first element of `markdown-hr-strings'. When
3720 ARG is non-nil, as when given a prefix, select a different
3721 element as follows. When prefixed with \\[universal-argument],
3722 use the last element of `markdown-hr-strings' instead. When
3723 prefixed with an integer from 1 to the length of
3724 `markdown-hr-strings', use the element in that position instead."
3725 (interactive "*P")
3726 (when (thing-at-point-looking-at markdown-regex-hr)
3727 (delete-region (match-beginning 0) (match-end 0)))
3728 (markdown-ensure-blank-line-before)
3729 (cond ((equal arg '(4))
3730 (insert (car (reverse markdown-hr-strings))))
3731 ((and (integerp arg) (> arg 0)
3732 (<= arg (length markdown-hr-strings)))
3733 (insert (nth (1- arg) markdown-hr-strings)))
3735 (insert (car markdown-hr-strings))))
3736 (markdown-ensure-blank-line-after))
3738 (defun markdown-insert-bold ()
3739 "Insert markup to make a region or word bold.
3740 If there is an active region, make the region bold. If the point
3741 is at a non-bold word, make the word bold. If the point is at a
3742 bold word or phrase, remove the bold markup. Otherwise, simply
3743 insert bold delimiters and place the point in between them."
3744 (interactive)
3745 (let ((delim (if markdown-bold-underscore "__" "**")))
3746 (if (markdown-use-region-p)
3747 ;; Active region
3748 (let ((bounds (markdown-unwrap-things-in-region
3749 (region-beginning) (region-end)
3750 markdown-regex-bold 2 4)))
3751 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3752 ;; Bold markup removal, bold word at point, or empty markup insertion
3753 (if (thing-at-point-looking-at markdown-regex-bold)
3754 (markdown-unwrap-thing-at-point nil 2 4)
3755 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3757 (defun markdown-insert-italic ()
3758 "Insert markup to make a region or word italic.
3759 If there is an active region, make the region italic. If the point
3760 is at a non-italic word, make the word italic. If the point is at an
3761 italic word or phrase, remove the italic markup. Otherwise, simply
3762 insert italic delimiters and place the point in between them."
3763 (interactive)
3764 (let ((delim (if markdown-italic-underscore "_" "*")))
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-italic 1 3)))
3770 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3771 ;; Italic markup removal, italic word at point, or empty markup insertion
3772 (if (thing-at-point-looking-at markdown-regex-italic)
3773 (markdown-unwrap-thing-at-point nil 1 3)
3774 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3776 (defun markdown-insert-strike-through ()
3777 "Insert markup to make a region or word strikethrough.
3778 If there is an active region, make the region strikethrough. If the point
3779 is at a non-bold word, make the word strikethrough. If the point is at a
3780 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
3781 simply insert bold delimiters and place the point in between them."
3782 (interactive)
3783 (let ((delim "~~"))
3784 (if (markdown-use-region-p)
3785 ;; Active region
3786 (let ((bounds (markdown-unwrap-things-in-region
3787 (region-beginning) (region-end)
3788 markdown-regex-strike-through 2 4)))
3789 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3790 ;; Strikethrough markup removal, strikethrough word at point, or empty markup insertion
3791 (if (thing-at-point-looking-at markdown-regex-strike-through)
3792 (markdown-unwrap-thing-at-point nil 2 4)
3793 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3795 (defun markdown-insert-code ()
3796 "Insert markup to make a region or word an inline code fragment.
3797 If there is an active region, make the region an inline code
3798 fragment. If the point is at a word, make the word an inline
3799 code fragment. Otherwise, simply insert code delimiters and
3800 place the point in between them."
3801 (interactive)
3802 (if (markdown-use-region-p)
3803 ;; Active region
3804 (let ((bounds (markdown-unwrap-things-in-region
3805 (region-beginning) (region-end)
3806 markdown-regex-code 1 3)))
3807 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
3808 ;; Code markup removal, code markup for word, or empty markup insertion
3809 (if (markdown-inline-code-at-point)
3810 (markdown-unwrap-thing-at-point nil 0 2)
3811 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
3813 (defun markdown-insert-kbd ()
3814 "Insert markup to wrap region or word in <kbd> tags.
3815 If there is an active region, use the region. If the point is at
3816 a word, use the word. Otherwise, simply insert <kbd> tags and
3817 place the point in between them."
3818 (interactive)
3819 (if (markdown-use-region-p)
3820 ;; Active region
3821 (let ((bounds (markdown-unwrap-things-in-region
3822 (region-beginning) (region-end)
3823 markdown-regex-kbd 0 2)))
3824 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil (car bounds) (cdr bounds)))
3825 ;; Markup removal, markup for word, or empty markup insertion
3826 (if (thing-at-point-looking-at markdown-regex-kbd)
3827 (markdown-unwrap-thing-at-point nil 0 2)
3828 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil))))
3830 (defun markdown-insert-inline-link (text url &optional title)
3831 "Insert an inline link with TEXT pointing to URL.
3832 Optionally, the user can provide a TITLE."
3833 (let ((cur (point)))
3834 (setq title (and title (concat " \"" title "\"")))
3835 (insert (concat "[" text "](" url title ")"))
3836 (cond ((not text) (goto-char (+ 1 cur)))
3837 ((not url) (goto-char (+ 3 (length text) cur))))))
3839 (defun markdown-insert-inline-image (text url &optional title)
3840 "Insert an inline link with alt TEXT pointing to URL.
3841 Optionally, also provide a TITLE."
3842 (let ((cur (point)))
3843 (setq title (and title (concat " \"" title "\"")))
3844 (insert (concat "![" text "](" url title ")"))
3845 (cond ((not text) (goto-char (+ 2 cur)))
3846 ((not url) (goto-char (+ 4 (length text) cur))))))
3848 (defun markdown-insert-reference-link (text label &optional url title)
3849 "Insert a reference link and, optionally, a reference definition.
3850 The link TEXT will be inserted followed by the optional LABEL.
3851 If a URL is given, also insert a definition for the reference
3852 LABEL according to `markdown-reference-location'. If a TITLE is
3853 given, it will be added to the end of the reference definition
3854 and will be used to populate the title attribute when converted
3855 to XHTML. If URL is nil, insert only the link portion (for
3856 example, when a reference label is already defined)."
3857 (insert (concat "[" text "][" label "]"))
3858 (when url
3859 (markdown-insert-reference-definition
3860 (if (string-equal label "") text label)
3861 url title)))
3863 (defun markdown-insert-reference-image (text label &optional url title)
3864 "Insert a reference image and, optionally, a reference definition.
3865 The alt TEXT will be inserted followed by the optional LABEL.
3866 If a URL is given, also insert a definition for the reference
3867 LABEL according to `markdown-reference-location'. If a TITLE is
3868 given, it will be added to the end of the reference definition
3869 and will be used to populate the title attribute when converted
3870 to XHTML. If URL is nil, insert only the link portion (for
3871 example, when a reference label is already defined)."
3872 (insert (concat "![" text "][" label "]"))
3873 (when url
3874 (markdown-insert-reference-definition
3875 (if (string-equal label "") text label)
3876 url title)))
3878 (defun markdown-insert-reference-definition (label &optional url title)
3879 "Add definition for reference LABEL with URL and TITLE.
3880 LABEL is a Markdown reference label without square brackets.
3881 URL and TITLE are optional. When given, the TITLE will
3882 be used to populate the title attribute when converted to XHTML."
3883 ;; END specifies where to leave the point upon return
3884 (let ((end (point)))
3885 (cl-case markdown-reference-location
3886 (end (goto-char (point-max)))
3887 (immediately (markdown-end-of-text-block))
3888 (subtree (markdown-end-of-subtree))
3889 (header (markdown-end-of-defun)))
3890 ;; Skip backwards over local variables. This logic is similar to the one
3891 ;; used in ‘hack-local-variables’.
3892 (when (and enable-local-variables (eobp))
3893 (search-backward "\n\f" (max (- (point) 3000) (point-min)) :move)
3894 (when (let ((case-fold-search t))
3895 (search-forward "Local Variables:" nil :move))
3896 (beginning-of-line 0)
3897 (when (eq (char-before) ?\n) (backward-char))))
3898 (unless (or (markdown-cur-line-blank-p)
3899 (thing-at-point-looking-at markdown-regex-reference-definition))
3900 (insert "\n"))
3901 (insert "\n[" label "]: ")
3902 (if url
3903 (insert url)
3904 ;; When no URL is given, leave point at END following the colon
3905 (setq end (point)))
3906 (when (> (length title) 0)
3907 (insert " \"" title "\""))
3908 (unless (looking-at-p "\n")
3909 (insert "\n"))
3910 (goto-char end)
3911 (when url
3912 (message
3913 (markdown--substitute-command-keys
3914 "Reference [%s] was defined, press \\[markdown-do] to jump there")
3915 label))))
3917 (define-obsolete-function-alias
3918 'markdown-insert-inline-link-dwim 'markdown-insert-link "v2.3")
3919 (define-obsolete-function-alias
3920 'markdown-insert-reference-link-dwim 'markdown-insert-link "v2.3")
3922 (defun markdown--insert-link-or-image (image)
3923 "Interactively insert new or update an existing link or image.
3924 When IMAGE is non-nil, insert an image. Otherwise, insert a link.
3925 This is an internal function called by
3926 `markdown-insert-link' and `markdown-insert-image'."
3927 (cl-multiple-value-bind (begin end text uri ref title)
3928 (if (markdown-use-region-p)
3929 ;; Use region as either link text or URL as appropriate.
3930 (let ((region (buffer-substring-no-properties
3931 (region-beginning) (region-end))))
3932 (if (string-match markdown-regex-uri region)
3933 ;; Region contains a URL; use it as such.
3934 (list (region-beginning) (region-end)
3935 nil (match-string 0 region) nil nil)
3936 ;; Region doesn't contain a URL, so use it as text.
3937 (list (region-beginning) (region-end)
3938 region nil nil nil)))
3939 ;; Extract and use properties of existing link, if any.
3940 (markdown-link-at-pos (point)))
3941 (let* ((ref (when ref (concat "[" ref "]")))
3942 (defined-refs (append
3943 (mapcar (lambda (ref) (concat "[" ref "]"))
3944 (mapcar #'car (markdown-get-defined-references)))))
3945 (used-uris (markdown-get-used-uris))
3946 (uri-or-ref (completing-read
3947 "URL or [reference]: "
3948 (append defined-refs used-uris)
3949 nil nil (or uri ref)))
3950 (ref (cond ((string-match "\\`\\[\\(.*\\)\\]\\'" uri-or-ref)
3951 (match-string 1 uri-or-ref))
3952 ((string-equal "" uri-or-ref)
3953 "")))
3954 (uri (unless ref uri-or-ref))
3955 (text-prompt (if image
3956 "Alt text: "
3957 (if ref
3958 "Link text: "
3959 "Link text (blank for plain URL): ")))
3960 (text (read-string text-prompt text))
3961 (text (if (= (length text) 0) nil text))
3962 (plainp (and uri (not text)))
3963 (implicitp (string-equal ref ""))
3964 (ref (if implicitp text ref))
3965 (definedp (and ref (markdown-reference-definition ref)))
3966 (ref-url (unless (or uri definedp)
3967 (completing-read "Reference URL: " used-uris)))
3968 (title (unless (or plainp definedp)
3969 (read-string "Title (tooltip text, optional): " title)))
3970 (title (if (= (length title) 0) nil title)))
3971 (when (and image implicitp)
3972 (user-error "Reference required: implicit image references are invalid"))
3973 (when (and begin end)
3974 (delete-region begin end))
3975 (cond
3976 ((and (not image) uri text)
3977 (markdown-insert-inline-link text uri title))
3978 ((and image uri text)
3979 (markdown-insert-inline-image text uri title))
3980 ((and ref text)
3981 (if image
3982 (markdown-insert-reference-image text (unless implicitp ref) nil title)
3983 (markdown-insert-reference-link text (unless implicitp ref) nil title))
3984 (unless definedp
3985 (markdown-insert-reference-definition ref ref-url title)))
3986 ((and (not image) uri)
3987 (markdown-insert-uri uri))))))
3989 (defun markdown-insert-link ()
3990 "Insert new or update an existing link, with interactive prompts.
3991 If the point is at an existing link or URL, update the link text,
3992 URL, reference label, and/or title. Otherwise, insert a new link.
3993 The type of link inserted (inline, reference, or plain URL)
3994 depends on which values are provided:
3996 * If a URL and TEXT are given, insert an inline link: [TEXT](URL).
3997 * If [REF] and TEXT are given, insert a reference link: [TEXT][REF].
3998 * If only TEXT is given, insert an implicit reference link: [TEXT][].
3999 * If only a URL is given, insert a plain link: <URL>.
4001 In other words, to create an implicit reference link, leave the
4002 URL prompt empty and to create a plain URL link, leave the link
4003 text empty.
4005 If there is an active region, use the text as the default URL, if
4006 it seems to be a URL, or link text value otherwise.
4008 If a given reference is not defined, this function will
4009 additionally prompt for the URL and optional title. In this case,
4010 the reference definition is placed at the location determined by
4011 `markdown-reference-location'.
4013 Through updating the link, this function can be used to convert a
4014 link of one type (inline, reference, or plain) to another type by
4015 selectively adding or removing information via the prompts."
4016 (interactive)
4017 (markdown--insert-link-or-image nil))
4019 (defun markdown-insert-image ()
4020 "Insert new or update an existing image, with interactive prompts.
4021 If the point is at an existing image, update the alt text, URL,
4022 reference label, and/or title. Otherwise, insert a new image.
4023 The type of image inserted (inline or reference) depends on which
4024 values are provided:
4026 * If a URL and ALT-TEXT are given, insert an inline image:
4027 ![ALT-TEXT](URL).
4028 * If [REF] and ALT-TEXT are given, insert a reference image:
4029 ![ALT-TEXT][REF].
4031 If there is an active region, use the text as the default URL, if
4032 it seems to be a URL, or alt text value otherwise.
4034 If a given reference is not defined, this function will
4035 additionally prompt for the URL and optional title. In this case,
4036 the reference definition is placed at the location determined by
4037 `markdown-reference-location'.
4039 Through updating the image, this function can be used to convert an
4040 image of one type (inline or reference) to another type by
4041 selectively adding or removing information via the prompts."
4042 (interactive)
4043 (markdown--insert-link-or-image t))
4045 (defun markdown-insert-uri (&optional uri)
4046 "Insert markup for an inline URI.
4047 If there is an active region, use it as the URI. If the point is
4048 at a URI, wrap it with angle brackets. If the point is at an
4049 inline URI, remove the angle brackets. Otherwise, simply insert
4050 angle brackets place the point between them."
4051 (interactive)
4052 (if (markdown-use-region-p)
4053 ;; Active region
4054 (let ((bounds (markdown-unwrap-things-in-region
4055 (region-beginning) (region-end)
4056 markdown-regex-angle-uri 0 2)))
4057 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
4058 ;; Markup removal, URI at point, new URI, or empty markup insertion
4059 (if (thing-at-point-looking-at markdown-regex-angle-uri)
4060 (markdown-unwrap-thing-at-point nil 0 2)
4061 (if uri
4062 (insert "<" uri ">")
4063 (markdown-wrap-or-insert "<" ">" 'url nil nil)))))
4065 (defun markdown-insert-wiki-link ()
4066 "Insert a wiki link of the form [[WikiLink]].
4067 If there is an active region, use the region as the link text.
4068 If the point is at a word, use the word as the link text. If
4069 there is no active region and the point is not at word, simply
4070 insert link markup."
4071 (interactive)
4072 (if (markdown-use-region-p)
4073 ;; Active region
4074 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
4075 ;; Markup removal, wiki link at at point, or empty markup insertion
4076 (if (thing-at-point-looking-at markdown-regex-wiki-link)
4077 (if (or markdown-wiki-link-alias-first
4078 (null (match-string 5)))
4079 (markdown-unwrap-thing-at-point nil 1 3)
4080 (markdown-unwrap-thing-at-point nil 1 5))
4081 (markdown-wrap-or-insert "[[" "]]"))))
4083 (defun markdown-remove-header ()
4084 "Remove header markup if point is at a header.
4085 Return bounds of remaining header text if a header was removed
4086 and nil otherwise."
4087 (interactive "*")
4088 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
4089 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
4091 (defun markdown-insert-header (&optional level text setext)
4092 "Insert or replace header markup.
4093 The level of the header is specified by LEVEL and header text is
4094 given by TEXT. LEVEL must be an integer from 1 and 6, and the
4095 default value is 1.
4096 When TEXT is nil, the header text is obtained as follows.
4097 If there is an active region, it is used as the header text.
4098 Otherwise, the current line will be used as the header text.
4099 If there is not an active region and the point is at a header,
4100 remove the header markup and replace with level N header.
4101 Otherwise, insert empty header markup and place the point in
4102 between.
4103 The style of the header will be atx (hash marks) unless
4104 SETEXT is non-nil, in which case a setext-style (underlined)
4105 header will be inserted."
4106 (interactive "p\nsHeader text: ")
4107 (setq level (min (max (or level 1) 1) (if setext 2 6)))
4108 ;; Determine header text if not given
4109 (when (null text)
4110 (if (markdown-use-region-p)
4111 ;; Active region
4112 (setq text (delete-and-extract-region (region-beginning) (region-end)))
4113 ;; No active region
4114 (markdown-remove-header)
4115 (setq text (delete-and-extract-region
4116 (line-beginning-position) (line-end-position)))
4117 (when (and setext (string-match-p "^[ \t]*$" text))
4118 (setq text (read-string "Header text: "))))
4119 (setq text (markdown-compress-whitespace-string text)))
4120 ;; Insertion with given text
4121 (markdown-ensure-blank-line-before)
4122 (let (hdr)
4123 (cond (setext
4124 (setq hdr (make-string (string-width text) (if (= level 2) ?- ?=)))
4125 (insert text "\n" hdr))
4127 (setq hdr (make-string level ?#))
4128 (insert hdr " " text)
4129 (when (null markdown-asymmetric-header) (insert " " hdr)))))
4130 (markdown-ensure-blank-line-after)
4131 ;; Leave point at end of text
4132 (cond (setext
4133 (backward-char (1+ (string-width text))))
4134 ((null markdown-asymmetric-header)
4135 (backward-char (1+ level)))))
4137 (defun markdown-insert-header-dwim (&optional arg setext)
4138 "Insert or replace header markup.
4139 The level and type of the header are determined automatically by
4140 the type and level of the previous header, unless a prefix
4141 argument is given via ARG.
4142 With a numeric prefix valued 1 to 6, insert a header of the given
4143 level, with the type being determined automatically (note that
4144 only level 1 or 2 setext headers are possible).
4146 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
4147 promote the heading by one level.
4148 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
4149 demote the heading by one level.
4150 When SETEXT is non-nil, prefer setext-style headers when
4151 possible (levels one and two).
4153 When there is an active region, use it for the header text. When
4154 the point is at an existing header, change the type and level
4155 according to the rules above.
4156 Otherwise, if the line is not empty, create a header using the
4157 text on the current line as the header text.
4158 Finally, if the point is on a blank line, insert empty header
4159 markup (atx) or prompt for text (setext).
4160 See `markdown-insert-header' for more details about how the
4161 header text is determined."
4162 (interactive "*P")
4163 (let (level)
4164 (save-excursion
4165 (when (or (thing-at-point-looking-at markdown-regex-header)
4166 (re-search-backward markdown-regex-header nil t))
4167 ;; level of current or previous header
4168 (setq level (markdown-outline-level))
4169 ;; match group 1 indicates a setext header
4170 (setq setext (match-end 1))))
4171 ;; check prefix argument
4172 (cond
4173 ((and (equal arg '(4)) level (> level 1)) ;; C-u
4174 (cl-decf level))
4175 ((and (equal arg '(16)) level (< level 6)) ;; C-u C-u
4176 (cl-incf level))
4177 (arg ;; numeric prefix
4178 (setq level (prefix-numeric-value arg))))
4179 ;; setext headers must be level one or two
4180 (and level (setq setext (and setext (<= level 2))))
4181 ;; insert the heading
4182 (markdown-insert-header level nil setext)))
4184 (defun markdown-insert-header-setext-dwim (&optional arg)
4185 "Insert or replace header markup, with preference for setext.
4186 See `markdown-insert-header-dwim' for details, including how ARG is handled."
4187 (interactive "*P")
4188 (markdown-insert-header-dwim arg t))
4190 (defun markdown-insert-header-atx-1 ()
4191 "Insert a first level atx-style (hash mark) header.
4192 See `markdown-insert-header'."
4193 (interactive "*")
4194 (markdown-insert-header 1 nil nil))
4196 (defun markdown-insert-header-atx-2 ()
4197 "Insert a level two atx-style (hash mark) header.
4198 See `markdown-insert-header'."
4199 (interactive "*")
4200 (markdown-insert-header 2 nil nil))
4202 (defun markdown-insert-header-atx-3 ()
4203 "Insert a level three atx-style (hash mark) header.
4204 See `markdown-insert-header'."
4205 (interactive "*")
4206 (markdown-insert-header 3 nil nil))
4208 (defun markdown-insert-header-atx-4 ()
4209 "Insert a level four atx-style (hash mark) header.
4210 See `markdown-insert-header'."
4211 (interactive "*")
4212 (markdown-insert-header 4 nil nil))
4214 (defun markdown-insert-header-atx-5 ()
4215 "Insert a level five atx-style (hash mark) header.
4216 See `markdown-insert-header'."
4217 (interactive "*")
4218 (markdown-insert-header 5 nil nil))
4220 (defun markdown-insert-header-atx-6 ()
4221 "Insert a sixth level atx-style (hash mark) header.
4222 See `markdown-insert-header'."
4223 (interactive "*")
4224 (markdown-insert-header 6 nil nil))
4226 (defun markdown-insert-header-setext-1 ()
4227 "Insert a setext-style (underlined) first-level header.
4228 See `markdown-insert-header'."
4229 (interactive "*")
4230 (markdown-insert-header 1 nil t))
4232 (defun markdown-insert-header-setext-2 ()
4233 "Insert a setext-style (underlined) second-level header.
4234 See `markdown-insert-header'."
4235 (interactive "*")
4236 (markdown-insert-header 2 nil t))
4238 (defun markdown-blockquote-indentation (loc)
4239 "Return string containing necessary indentation for a blockquote at LOC.
4240 Also see `markdown-pre-indentation'."
4241 (save-excursion
4242 (goto-char loc)
4243 (let* ((list-level (length (markdown-calculate-list-levels)))
4244 (indent ""))
4245 (dotimes (_ list-level indent)
4246 (setq indent (concat indent " "))))))
4248 (defun markdown-insert-blockquote ()
4249 "Start a blockquote section (or blockquote the region).
4250 If Transient Mark mode is on and a region is active, it is used as
4251 the blockquote text."
4252 (interactive)
4253 (if (markdown-use-region-p)
4254 (markdown-blockquote-region (region-beginning) (region-end))
4255 (markdown-ensure-blank-line-before)
4256 (insert (markdown-blockquote-indentation (point)) "> ")
4257 (markdown-ensure-blank-line-after)))
4259 (defun markdown-block-region (beg end prefix)
4260 "Format the region using a block prefix.
4261 Arguments BEG and END specify the beginning and end of the
4262 region. The characters PREFIX will appear at the beginning
4263 of each line."
4264 (save-excursion
4265 (let* ((end-marker (make-marker))
4266 (beg-marker (make-marker))
4267 (prefix-without-trailing-whitespace
4268 (replace-regexp-in-string (rx (+ blank) eos) "" prefix)))
4269 ;; Ensure blank line after and remove extra whitespace
4270 (goto-char end)
4271 (skip-syntax-backward "-")
4272 (set-marker end-marker (point))
4273 (delete-horizontal-space)
4274 (markdown-ensure-blank-line-after)
4275 ;; Ensure blank line before and remove extra whitespace
4276 (goto-char beg)
4277 (skip-syntax-forward "-")
4278 (delete-horizontal-space)
4279 (markdown-ensure-blank-line-before)
4280 (set-marker beg-marker (point))
4281 ;; Insert PREFIX before each line
4282 (goto-char beg-marker)
4283 (while (and (< (line-beginning-position) end-marker)
4284 (not (eobp)))
4285 ;; Don’t insert trailing whitespace.
4286 (insert (if (eolp) prefix-without-trailing-whitespace prefix))
4287 (forward-line)))))
4289 (defun markdown-blockquote-region (beg end)
4290 "Blockquote the region.
4291 Arguments BEG and END specify the beginning and end of the region."
4292 (interactive "*r")
4293 (markdown-block-region
4294 beg end (concat (markdown-blockquote-indentation
4295 (max (point-min) (1- beg))) "> ")))
4297 (defun markdown-pre-indentation (loc)
4298 "Return string containing necessary whitespace for a pre block at LOC.
4299 Also see `markdown-blockquote-indentation'."
4300 (save-excursion
4301 (goto-char loc)
4302 (let* ((list-level (length (markdown-calculate-list-levels)))
4303 indent)
4304 (dotimes (_ (1+ list-level) indent)
4305 (setq indent (concat indent " "))))))
4307 (defun markdown-insert-pre ()
4308 "Start a preformatted section (or apply to the region).
4309 If Transient Mark mode is on and a region is active, it is marked
4310 as preformatted text."
4311 (interactive)
4312 (if (markdown-use-region-p)
4313 (markdown-pre-region (region-beginning) (region-end))
4314 (markdown-ensure-blank-line-before)
4315 (insert (markdown-pre-indentation (point)))
4316 (markdown-ensure-blank-line-after)))
4318 (defun markdown-pre-region (beg end)
4319 "Format the region as preformatted text.
4320 Arguments BEG and END specify the beginning and end of the region."
4321 (interactive "*r")
4322 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
4323 (markdown-block-region beg end indent)))
4325 (defun markdown-electric-backquote (arg)
4326 "Insert a backquote.
4327 The numeric prefix argument ARG says how many times to repeat the insertion.
4328 Call `markdown-insert-gfm-code-block' interactively
4329 if three backquotes inserted at the beginning of line."
4330 (interactive "*P")
4331 (self-insert-command (prefix-numeric-value arg))
4332 (when (and markdown-gfm-use-electric-backquote (looking-back "^```" nil))
4333 (replace-match "")
4334 (call-interactively #'markdown-insert-gfm-code-block)))
4336 (defconst markdown-gfm-recognized-languages
4337 ;; To reproduce/update, evaluate the let-form in
4338 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
4339 ;; but with appropriate use of a keyboard macro, indenting and filling it
4340 ;; properly is pretty fast.
4341 '("1C-Enterprise" "ABAP" "ABNF" "AGS-Script" "AMPL" "ANTLR"
4342 "API-Blueprint" "APL" "ASN.1" "ASP" "ATS" "ActionScript" "Ada" "Agda"
4343 "Alloy" "Alpine-Abuild" "Ant-Build-System" "ApacheConf" "Apex"
4344 "Apollo-Guidance-Computer" "AppleScript" "Arc" "Arduino" "AsciiDoc"
4345 "AspectJ" "Assembly" "Augeas" "AutoHotkey" "AutoIt" "Awk" "Batchfile"
4346 "Befunge" "Bison" "BitBake" "Blade" "BlitzBasic" "BlitzMax" "Bluespec"
4347 "Boo" "Brainfuck" "Brightscript" "Bro" "C#" "C++" "C-ObjDump"
4348 "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "COLLADA" "CSON" "CSS" "CSV"
4349 "CWeb" "Cap'n-Proto" "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK"
4350 "Cirru" "Clarion" "Clean" "Click" "Clojure" "Closure-Templates"
4351 "CoffeeScript" "ColdFusion" "ColdFusion-CFC" "Common-Lisp"
4352 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal"
4353 "Csound" "Csound-Document" "Csound-Score" "Cuda" "Cycript" "Cython"
4354 "D-ObjDump" "DIGITAL-Command-Language" "DM" "DNS-Zone" "DTrace"
4355 "Darcs-Patch" "Dart" "Diff" "Dockerfile" "Dogescript" "Dylan" "EBNF"
4356 "ECL" "ECLiPSe" "EJS" "EQ" "Eagle" "Ecere-Projects" "Eiffel" "Elixir"
4357 "Elm" "Emacs-Lisp" "EmberScript" "Erlang" "F#" "FLUX" "Factor" "Fancy"
4358 "Fantom" "Filebench-WML" "Filterscript" "Formatted" "Forth" "Fortran"
4359 "FreeMarker" "Frege" "G-code" "GAMS" "GAP" "GCC-Machine-Description"
4360 "GDB" "GDScript" "GLSL" "GN" "Game-Maker-Language" "Genie" "Genshi"
4361 "Gentoo-Ebuild" "Gentoo-Eclass" "Gettext-Catalog" "Gherkin" "Glyph"
4362 "Gnuplot" "Go" "Golo" "Gosu" "Grace" "Gradle" "Grammatical-Framework"
4363 "Graph-Modeling-Language" "GraphQL" "Graphviz-(DOT)" "Groovy"
4364 "Groovy-Server-Pages" "HCL" "HLSL" "HTML" "HTML+Django" "HTML+ECR"
4365 "HTML+EEX" "HTML+ERB" "HTML+PHP" "HTTP" "Hack" "Haml" "Handlebars"
4366 "Harbour" "Haskell" "Haxe" "Hy" "HyPhy" "IDL" "IGOR-Pro" "INI"
4367 "IRC-log" "Idris" "Inform-7" "Inno-Setup" "Io" "Ioke" "Isabelle"
4368 "Isabelle-ROOT" "JFlex" "JSON" "JSON5" "JSONLD" "JSONiq" "JSX"
4369 "Jasmin" "Java" "Java-Server-Pages" "JavaScript" "Jison" "Jison-Lex"
4370 "Jolie" "Julia" "Jupyter-Notebook" "KRL" "KiCad" "Kit" "Kotlin" "LFE"
4371 "LLVM" "LOLCODE" "LSL" "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex"
4372 "LilyPond" "Limbo" "Linker-Script" "Linux-Kernel-Module" "Liquid"
4373 "Literate-Agda" "Literate-CoffeeScript" "Literate-Haskell"
4374 "LiveScript" "Logos" "Logtalk" "LookML" "LoomScript" "Lua" "M4"
4375 "M4Sugar" "MAXScript" "MQL4" "MQL5" "MTML" "MUF" "Makefile" "Mako"
4376 "Markdown" "Marko" "Mask" "Mathematica" "Matlab" "Maven-POM" "Max"
4377 "MediaWiki" "Mercury" "Meson" "Metal" "MiniD" "Mirah" "Modelica"
4378 "Modula-2" "Module-Management-System" "Monkey" "Moocode" "MoonScript"
4379 "Myghty" "NCL" "NL" "NSIS" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo"
4380 "NewLisp" "Nginx" "Nim" "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml"
4381 "ObjDump" "Objective-C" "Objective-C++" "Objective-J" "Omgrofl" "Opa"
4382 "Opal" "OpenCL" "OpenEdge-ABL" "OpenRC-runscript" "OpenSCAD"
4383 "OpenType-Feature-File" "Org" "Ox" "Oxygene" "Oz" "P4" "PAWN" "PHP"
4384 "PLSQL" "PLpgSQL" "POV-Ray-SDL" "Pan" "Papyrus" "Parrot"
4385 "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal" "Pep8"
4386 "Perl" "Perl6" "Pic" "Pickle" "PicoLisp" "PigLatin" "Pike" "Pod"
4387 "PogoScript" "Pony" "PostScript" "PowerBuilder" "PowerShell"
4388 "Processing" "Prolog" "Propeller-Spin" "Protocol-Buffer" "Public-Key"
4389 "Pug" "Puppet" "Pure-Data" "PureBasic" "PureScript" "Python"
4390 "Python-console" "Python-traceback" "QML" "QMake" "RAML" "RDoc"
4391 "REALbasic" "REXX" "RHTML" "RMarkdown" "RPM-Spec" "RUNOFF" "Racket"
4392 "Ragel" "Rascal" "Raw-token-data" "Reason" "Rebol" "Red" "Redcode"
4393 "Regular-Expression" "Ren'Py" "RenderScript" "RobotFramework" "Roff"
4394 "Rouge" "Ruby" "Rust" "SAS" "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL"
4395 "SRecode-Template" "STON" "SVG" "Sage" "SaltStack" "Sass" "Scala"
4396 "Scaml" "Scheme" "Scilab" "Self" "ShaderLab" "Shell" "ShellSession"
4397 "Shen" "Slash" "Slim" "Smali" "Smalltalk" "Smarty" "SourcePawn"
4398 "Spline-Font-Database" "Squirrel" "Stan" "Standard-ML" "Stata"
4399 "Stylus" "SubRip-Text" "Sublime-Text-Config" "SuperCollider" "Swift"
4400 "SystemVerilog" "TI-Program" "TLA" "TOML" "TXL" "Tcl" "Tcsh" "TeX"
4401 "Tea" "Terra" "Text" "Textile" "Thrift" "Turing" "Turtle" "Twig"
4402 "Type-Language" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset"
4403 "Unix-Assembly" "Uno" "UnrealScript" "UrWeb" "VCL" "VHDL" "Vala"
4404 "Verilog" "Vim-script" "Visual-Basic" "Volt" "Vue"
4405 "Wavefront-Material" "Wavefront-Object" "Web-Ontology-Language"
4406 "WebAssembly" "WebIDL" "World-of-Warcraft-Addon-Data" "X10" "XC"
4407 "XCompose" "XML" "XPages" "XProc" "XQuery" "XS" "XSLT" "Xojo" "Xtend"
4408 "YAML" "YANG" "Yacc" "Zephir" "Zimpl" "desktop" "eC" "edn" "fish"
4409 "mupad" "nesC" "ooc" "reStructuredText" "wisp" "xBase")
4410 "Language specifiers recognized by GitHub's syntax highlighting features.")
4412 (defvar markdown-gfm-used-languages nil
4413 "Language names used in GFM code blocks.")
4414 (make-variable-buffer-local 'markdown-gfm-used-languages)
4416 (defun markdown-trim-whitespace (str)
4417 (markdown-replace-regexp-in-string
4418 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str))
4420 (defun markdown-clean-language-string (str)
4421 (markdown-replace-regexp-in-string
4422 "{\\.?\\|}" "" (markdown-trim-whitespace str)))
4424 (defun markdown-validate-language-string (widget)
4425 (let ((str (widget-value widget)))
4426 (unless (string= str (markdown-clean-language-string str))
4427 (widget-put widget :error (format "Invalid language spec: '%s'" str))
4428 widget)))
4430 (defun markdown-gfm-get-corpus ()
4431 "Create corpus of recognized GFM code block languages for the given buffer."
4432 (let ((given-corpus (append markdown-gfm-additional-languages
4433 markdown-gfm-recognized-languages)))
4434 (append
4435 markdown-gfm-used-languages
4436 (if markdown-gfm-downcase-languages (cl-mapcar #'downcase given-corpus)
4437 given-corpus))))
4439 (defun markdown-gfm-add-used-language (lang)
4440 "Clean LANG and add to list of used languages."
4441 (setq markdown-gfm-used-languages
4442 (cons lang (remove lang markdown-gfm-used-languages))))
4444 (defcustom markdown-spaces-after-code-fence 1
4445 "Number of space characters to insert after a code fence.
4446 \\<gfm-mode-map>\\[markdown-insert-gfm-code-block] inserts this many spaces between an
4447 opening code fence and an info string."
4448 :group 'markdown
4449 :type 'integer
4450 :safe #'natnump
4451 :package-version '(markdown-mode . "2.3"))
4453 (defun markdown-insert-gfm-code-block (&optional lang edit)
4454 "Insert GFM code block for language LANG.
4455 If LANG is nil, the language will be queried from user. If a
4456 region is active, wrap this region with the markup instead. If
4457 the region boundaries are not on empty lines, these are added
4458 automatically in order to have the correct markup. When EDIT is
4459 non-nil (e.g., when \\[universal-argument] is given), edit the
4460 code block in an indirect buffer after insertion."
4461 (interactive
4462 (list (let ((completion-ignore-case nil))
4463 (condition-case nil
4464 (markdown-clean-language-string
4465 (completing-read
4466 "Programming language: "
4467 (markdown-gfm-get-corpus)
4468 nil 'confirm (car markdown-gfm-used-languages)
4469 'markdown-gfm-language-history))
4470 (quit "")))
4471 current-prefix-arg))
4472 (unless (string= lang "") (markdown-gfm-add-used-language lang))
4473 (when (> (length lang) 0)
4474 (setq lang (concat (make-string markdown-spaces-after-code-fence ?\s)
4475 lang)))
4476 (if (markdown-use-region-p)
4477 (let* ((b (region-beginning)) (e (region-end)) end
4478 (indent (progn (goto-char b) (current-indentation))))
4479 (goto-char e)
4480 ;; if we're on a blank line, don't newline, otherwise the ```
4481 ;; should go on its own line
4482 (unless (looking-back "\n" nil)
4483 (newline))
4484 (indent-to indent)
4485 (insert "```")
4486 (markdown-ensure-blank-line-after)
4487 (setq end (point))
4488 (goto-char b)
4489 ;; if we're on a blank line, insert the quotes here, otherwise
4490 ;; add a new line first
4491 (unless (looking-at-p "\n")
4492 (newline)
4493 (forward-line -1))
4494 (markdown-ensure-blank-line-before)
4495 (indent-to indent)
4496 (insert "```" lang)
4497 (markdown-syntax-propertize-fenced-block-constructs (point-at-bol) end))
4498 (let ((indent (current-indentation)) start-bol)
4499 (delete-horizontal-space :backward-only)
4500 (markdown-ensure-blank-line-before)
4501 (indent-to indent)
4502 (setq start-bol (point-at-bol))
4503 (insert "```" lang "\n")
4504 (indent-to indent)
4505 (unless edit (insert ?\n))
4506 (indent-to indent)
4507 (insert "```")
4508 (markdown-ensure-blank-line-after)
4509 (markdown-syntax-propertize-fenced-block-constructs start-bol (point)))
4510 (end-of-line 0)
4511 (when edit (markdown-edit-code-block))))
4513 (defun markdown-code-block-lang (&optional pos-prop)
4514 "Return the language name for a GFM or tilde fenced code block.
4515 The beginning of the block may be described by POS-PROP,
4516 a cons of (pos . prop) giving the position and property
4517 at the beginning of the block."
4518 (or pos-prop
4519 (setq pos-prop
4520 (markdown-max-of-seq
4521 #'car
4522 (cl-remove-if
4523 #'null
4524 (cl-mapcar
4525 #'markdown-find-previous-prop
4526 (markdown-get-fenced-block-begin-properties))))))
4527 (when pos-prop
4528 (goto-char (car pos-prop))
4529 (set-match-data (get-text-property (point) (cdr pos-prop)))
4530 ;; Note: Hard-coded group number assumes tilde
4531 ;; and GFM fenced code regexp groups agree.
4532 (let ((begin (match-beginning 3))
4533 (end (match-end 3)))
4534 (when (and begin end)
4535 ;; Fix language strings beginning with periods, like ".ruby".
4536 (when (eq (char-after begin) ?.)
4537 (setq begin (1+ begin)))
4538 (buffer-substring-no-properties begin end)))))
4540 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer)
4541 (with-current-buffer (or buffer (current-buffer))
4542 (save-excursion
4543 (goto-char (point-min))
4544 (cl-loop
4545 with prop = 'markdown-gfm-block-begin
4546 for pos-prop = (markdown-find-next-prop prop)
4547 while pos-prop
4548 for lang = (markdown-code-block-lang pos-prop)
4549 do (progn (when lang (markdown-gfm-add-used-language lang))
4550 (goto-char (next-single-property-change (point) prop)))))))
4553 ;;; Footnotes ==================================================================
4555 (defun markdown-footnote-counter-inc ()
4556 "Increment `markdown-footnote-counter' and return the new value."
4557 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
4558 (save-excursion
4559 (goto-char (point-min))
4560 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
4561 (point-max) t)
4562 (let ((fn (string-to-number (match-string 1))))
4563 (when (> fn markdown-footnote-counter)
4564 (setq markdown-footnote-counter fn))))))
4565 (cl-incf markdown-footnote-counter))
4567 (defun markdown-insert-footnote ()
4568 "Insert footnote with a new number and move point to footnote definition."
4569 (interactive)
4570 (let ((fn (markdown-footnote-counter-inc)))
4571 (insert (format "[^%d]" fn))
4572 (markdown-footnote-text-find-new-location)
4573 (markdown-ensure-blank-line-before)
4574 (unless (markdown-cur-line-blank-p)
4575 (insert "\n"))
4576 (insert (format "[^%d]: " fn))
4577 (markdown-ensure-blank-line-after)))
4579 (defun markdown-footnote-text-find-new-location ()
4580 "Position the point at the proper location for a new footnote text."
4581 (cond
4582 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
4583 ((eq markdown-footnote-location 'immediately) (markdown-end-of-text-block))
4584 ((eq markdown-footnote-location 'subtree) (markdown-end-of-subtree))
4585 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
4587 (defun markdown-footnote-kill ()
4588 "Kill the footnote at point.
4589 The footnote text is killed (and added to the kill ring), the
4590 footnote marker is deleted. Point has to be either at the
4591 footnote marker or in the footnote text."
4592 (interactive)
4593 (let ((marker-pos nil)
4594 (skip-deleting-marker nil)
4595 (starting-footnote-text-positions
4596 (markdown-footnote-text-positions)))
4597 (when starting-footnote-text-positions
4598 ;; We're starting in footnote text, so mark our return position and jump
4599 ;; to the marker if possible.
4600 (let ((marker-pos (markdown-footnote-find-marker
4601 (cl-first starting-footnote-text-positions))))
4602 (if marker-pos
4603 (goto-char (1- marker-pos))
4604 ;; If there isn't a marker, we still want to kill the text.
4605 (setq skip-deleting-marker t))))
4606 ;; Either we didn't start in the text, or we started in the text and jumped
4607 ;; to the marker. We want to assume we're at the marker now and error if
4608 ;; we're not.
4609 (unless skip-deleting-marker
4610 (let ((marker (markdown-footnote-delete-marker)))
4611 (unless marker
4612 (error "Not at a footnote"))
4613 ;; Even if we knew the text position before, it changed when we deleted
4614 ;; the label.
4615 (setq marker-pos (cl-second marker))
4616 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker))))
4617 (unless new-text-pos
4618 (error "No text for footnote `%s'" (cl-first marker)))
4619 (goto-char new-text-pos))))
4620 (let ((pos (markdown-footnote-kill-text)))
4621 (goto-char (if starting-footnote-text-positions
4623 marker-pos)))))
4625 (defun markdown-footnote-delete-marker ()
4626 "Delete a footnote marker at point.
4627 Returns a list (ID START) containing the footnote ID and the
4628 start position of the marker before deletion. If no footnote
4629 marker was deleted, this function returns NIL."
4630 (let ((marker (markdown-footnote-marker-positions)))
4631 (when marker
4632 (delete-region (cl-second marker) (cl-third marker))
4633 (butlast marker))))
4635 (defun markdown-footnote-kill-text ()
4636 "Kill footnote text at point.
4637 Returns the start position of the footnote text before deletion,
4638 or NIL if point was not inside a footnote text.
4640 The killed text is placed in the kill ring (without the footnote
4641 number)."
4642 (let ((fn (markdown-footnote-text-positions)))
4643 (when fn
4644 (let ((text (delete-and-extract-region (cl-second fn) (cl-third fn))))
4645 (string-match (concat "\\[\\" (cl-first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
4646 (kill-new (match-string 1 text))
4647 (when (and (markdown-cur-line-blank-p)
4648 (markdown-prev-line-blank-p)
4649 (not (bobp)))
4650 (delete-region (1- (point)) (point)))
4651 (cl-second fn)))))
4653 (defun markdown-footnote-goto-text ()
4654 "Jump to the text of the footnote at point."
4655 (interactive)
4656 (let ((fn (car (markdown-footnote-marker-positions))))
4657 (unless fn
4658 (user-error "Not at a footnote marker"))
4659 (let ((new-pos (markdown-footnote-find-text fn)))
4660 (unless new-pos
4661 (error "No definition found for footnote `%s'" fn))
4662 (goto-char new-pos))))
4664 (defun markdown-footnote-return ()
4665 "Return from a footnote to its footnote number in the main text."
4666 (interactive)
4667 (let ((fn (save-excursion
4668 (car (markdown-footnote-text-positions)))))
4669 (unless fn
4670 (user-error "Not in a footnote"))
4671 (let ((new-pos (markdown-footnote-find-marker fn)))
4672 (unless new-pos
4673 (error "Footnote marker `%s' not found" fn))
4674 (goto-char new-pos))))
4676 (defun markdown-footnote-find-marker (id)
4677 "Find the location of the footnote marker with ID.
4678 The actual buffer position returned is the position directly
4679 following the marker's closing bracket. If no marker is found,
4680 NIL is returned."
4681 (save-excursion
4682 (goto-char (point-min))
4683 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
4684 (skip-chars-backward "^]")
4685 (point))))
4687 (defun markdown-footnote-find-text (id)
4688 "Find the location of the text of footnote ID.
4689 The actual buffer position returned is the position of the first
4690 character of the text, after the footnote's identifier. If no
4691 footnote text is found, NIL is returned."
4692 (save-excursion
4693 (goto-char (point-min))
4694 (when (re-search-forward (concat "^ \\{0,3\\}\\[" id "\\]:") nil t)
4695 (skip-chars-forward "[ \t]")
4696 (point))))
4698 (defun markdown-footnote-marker-positions ()
4699 "Return the position and ID of the footnote marker point is on.
4700 The return value is a list (ID START END). If point is not on a
4701 footnote, NIL is returned."
4702 ;; first make sure we're at a footnote marker
4703 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
4704 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
4705 (save-excursion
4706 ;; move point between [ and ^:
4707 (if (looking-at-p "\\[")
4708 (forward-char 1)
4709 (skip-chars-backward "^["))
4710 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
4711 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
4713 (defun markdown-footnote-text-positions ()
4714 "Return the start and end positions of the footnote text point is in.
4715 The exact return value is a list of three elements: (ID START END).
4716 The start position is the position of the opening bracket
4717 of the footnote id. The end position is directly after the
4718 newline that ends the footnote. If point is not in a footnote,
4719 NIL is returned instead."
4720 (save-excursion
4721 (let (result)
4722 (move-beginning-of-line 1)
4723 ;; Try to find the label. If we haven't found the label and we're at a blank
4724 ;; or indented line, back up if possible.
4725 (while (and
4726 (not (and (looking-at markdown-regex-footnote-definition)
4727 (setq result (list (match-string 1) (point)))))
4728 (and (not (bobp))
4729 (or (markdown-cur-line-blank-p)
4730 (>= (current-indentation) 4))))
4731 (forward-line -1))
4732 (when result
4733 ;; Advance if there is a next line that is either blank or indented.
4734 ;; (Need to check if we're on the last line, because
4735 ;; markdown-next-line-blank-p returns true for last line in buffer.)
4736 (while (and (/= (line-end-position) (point-max))
4737 (or (markdown-next-line-blank-p)
4738 (>= (markdown-next-line-indent) 4)))
4739 (forward-line))
4740 ;; Move back while the current line is blank.
4741 (while (markdown-cur-line-blank-p)
4742 (forward-line -1))
4743 ;; Advance to capture this line and a single trailing newline (if there
4744 ;; is one).
4745 (forward-line)
4746 (append result (list (point)))))))
4748 (defun markdown-get-defined-footnotes ()
4749 "Return a list of all defined footnotes.
4750 Result is an alist of pairs (MARKER . LINE), where MARKER is the
4751 footnote marker, a string, and LINE is the line number containing
4752 the footnote definition.
4754 For example, suppose the following footnotes are defined at positions
4755 448 and 475:
4757 \[^1]: First footnote here.
4758 \[^marker]: Second footnote.
4760 Then the returned list is: ((\"^1\" . 478) (\"^marker\" . 475))"
4761 (save-excursion
4762 (goto-char (point-min))
4763 (let (footnotes)
4764 (while (markdown-search-until-condition
4765 (lambda () (and (not (markdown-code-block-at-point-p))
4766 (not (markdown-inline-code-at-point-p))
4767 (not (markdown-in-comment-p))))
4768 markdown-regex-footnote-definition nil t)
4769 (let ((marker (match-string-no-properties 1))
4770 (pos (match-beginning 0)))
4771 (unless (zerop (length marker))
4772 (cl-pushnew (cons marker pos) footnotes :test #'equal))))
4773 (reverse footnotes))))
4776 ;;; Element Removal ===========================================================
4778 (defun markdown-kill-thing-at-point ()
4779 "Kill thing at point and add important text, without markup, to kill ring.
4780 Possible things to kill include (roughly in order of precedence):
4781 inline code, headers, horizonal rules, links (add link text to
4782 kill ring), images (add alt text to kill ring), angle uri, email
4783 addresses, bold, italics, reference definition (add URI to kill
4784 ring), footnote markers and text (kill both marker and text, add
4785 text to kill ring), and list items."
4786 (interactive "*")
4787 (let (val)
4788 (cond
4789 ;; Inline code
4790 ((markdown-inline-code-at-point)
4791 (kill-new (match-string 2))
4792 (delete-region (match-beginning 0) (match-end 0)))
4793 ;; ATX header
4794 ((thing-at-point-looking-at markdown-regex-header-atx)
4795 (kill-new (match-string 2))
4796 (delete-region (match-beginning 0) (match-end 0)))
4797 ;; Setext header
4798 ((thing-at-point-looking-at markdown-regex-header-setext)
4799 (kill-new (match-string 1))
4800 (delete-region (match-beginning 0) (match-end 0)))
4801 ;; Horizonal rule
4802 ((thing-at-point-looking-at markdown-regex-hr)
4803 (kill-new (match-string 0))
4804 (delete-region (match-beginning 0) (match-end 0)))
4805 ;; Inline link or image (add link or alt text to kill ring)
4806 ((thing-at-point-looking-at markdown-regex-link-inline)
4807 (kill-new (match-string 3))
4808 (delete-region (match-beginning 0) (match-end 0)))
4809 ;; Reference link or image (add link or alt text to kill ring)
4810 ((thing-at-point-looking-at markdown-regex-link-reference)
4811 (kill-new (match-string 3))
4812 (delete-region (match-beginning 0) (match-end 0)))
4813 ;; Angle URI (add URL to kill ring)
4814 ((thing-at-point-looking-at markdown-regex-angle-uri)
4815 (kill-new (match-string 2))
4816 (delete-region (match-beginning 0) (match-end 0)))
4817 ;; Email address in angle brackets (add email address to kill ring)
4818 ((thing-at-point-looking-at markdown-regex-email)
4819 (kill-new (match-string 1))
4820 (delete-region (match-beginning 0) (match-end 0)))
4821 ;; Wiki link (add alias text to kill ring)
4822 ((and markdown-enable-wiki-links
4823 (thing-at-point-looking-at markdown-regex-wiki-link))
4824 (kill-new (markdown-wiki-link-alias))
4825 (delete-region (match-beginning 1) (match-end 1)))
4826 ;; Bold
4827 ((thing-at-point-looking-at markdown-regex-bold)
4828 (kill-new (match-string 4))
4829 (delete-region (match-beginning 2) (match-end 2)))
4830 ;; Italics
4831 ((thing-at-point-looking-at markdown-regex-italic)
4832 (kill-new (match-string 3))
4833 (delete-region (match-beginning 1) (match-end 1)))
4834 ;; Strikethrough
4835 ((thing-at-point-looking-at markdown-regex-strike-through)
4836 (kill-new (match-string 4))
4837 (delete-region (match-beginning 2) (match-end 2)))
4838 ;; Footnote marker (add footnote text to kill ring)
4839 ((thing-at-point-looking-at markdown-regex-footnote)
4840 (markdown-footnote-kill))
4841 ;; Footnote text (add footnote text to kill ring)
4842 ((setq val (markdown-footnote-text-positions))
4843 (markdown-footnote-kill))
4844 ;; Reference definition (add URL to kill ring)
4845 ((thing-at-point-looking-at markdown-regex-reference-definition)
4846 (kill-new (match-string 5))
4847 (delete-region (match-beginning 0) (match-end 0)))
4848 ;; List item
4849 ((setq val (markdown-cur-list-item-bounds))
4850 (kill-new (delete-and-extract-region (cl-first val) (cl-second val))))
4852 (user-error "Nothing found at point to kill")))))
4855 ;;; Indentation ====================================================================
4857 (defun markdown-indent-find-next-position (cur-pos positions)
4858 "Return the position after the index of CUR-POS in POSITIONS.
4859 Positions are calculated by `markdown-calc-indents'."
4860 (while (and positions
4861 (not (equal cur-pos (car positions))))
4862 (setq positions (cdr positions)))
4863 (or (cadr positions) 0))
4865 (define-obsolete-function-alias 'markdown-exdent-find-next-position
4866 'markdown-outdent-find-next-position "v2.3")
4868 (defun markdown-outdent-find-next-position (cur-pos positions)
4869 "Return the maximal element that precedes CUR-POS from POSITIONS.
4870 Positions are calculated by `markdown-calc-indents'."
4871 (let ((result 0))
4872 (dolist (i positions)
4873 (when (< i cur-pos)
4874 (setq result (max result i))))
4875 result))
4877 (defun markdown-indent-line ()
4878 "Indent the current line using some heuristics.
4879 If the _previous_ command was either `markdown-enter-key' or
4880 `markdown-cycle', then we should cycle to the next
4881 reasonable indentation position. Otherwise, we could have been
4882 called directly by `markdown-enter-key', by an initial call of
4883 `markdown-cycle', or indirectly by `auto-fill-mode'. In
4884 these cases, indent to the default position.
4885 Positions are calculated by `markdown-calc-indents'."
4886 (interactive)
4887 (let ((positions (markdown-calc-indents))
4888 (point-pos (current-column))
4889 (_ (back-to-indentation))
4890 (cur-pos (current-column)))
4891 (if (not (equal this-command 'markdown-cycle))
4892 (indent-line-to (car positions))
4893 (setq positions (sort (delete-dups positions) '<))
4894 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions))
4895 (new-point-pos (max (+ point-pos (- next-pos cur-pos)) 0)))
4896 (indent-line-to next-pos)
4897 (move-to-column new-point-pos)))))
4899 (defun markdown-calc-indents ()
4900 "Return a list of indentation columns to cycle through.
4901 The first element in the returned list should be considered the
4902 default indentation level. This function does not worry about
4903 duplicate positions, which are handled up by calling functions."
4904 (let (pos prev-line-pos positions)
4906 ;; Indentation of previous line
4907 (setq prev-line-pos (markdown-prev-line-indent))
4908 (setq positions (cons prev-line-pos positions))
4910 ;; Indentation of previous non-list-marker text
4911 (when (setq pos (save-excursion
4912 (forward-line -1)
4913 (when (looking-at markdown-regex-list)
4914 (- (match-end 3) (match-beginning 0)))))
4915 (setq positions (cons pos positions)))
4917 ;; Indentation required for a pre block in current context
4918 (setq pos (length (markdown-pre-indentation (point))))
4919 (setq positions (cons pos positions))
4921 ;; Indentation of the previous line + tab-width
4922 (if prev-line-pos
4923 (setq positions (cons (+ prev-line-pos tab-width) positions))
4924 (setq positions (cons tab-width positions)))
4926 ;; Indentation of the previous line - tab-width
4927 (if (and prev-line-pos (> prev-line-pos tab-width))
4928 (setq positions (cons (- prev-line-pos tab-width) positions)))
4930 ;; Indentation of all preceeding list markers (when in a list)
4931 (when (setq pos (markdown-calculate-list-levels))
4932 (setq positions (append pos positions)))
4934 ;; First column
4935 (setq positions (cons 0 positions))
4937 ;; Return reversed list
4938 (reverse positions)))
4940 (defun markdown-enter-key ()
4941 "Handle RET depending on the context.
4942 If the point is at a table, move to the next row. Otherwise,
4943 indent according to value of `markdown-indent-on-enter'.
4944 When it is nil, simply call `newline'. Otherwise, indent the next line
4945 following RET using `markdown-indent-line'. Furthermore, when it
4946 is set to 'indent-and-new-item and the point is in a list item,
4947 start a new item with the same indentation. If the point is in an
4948 empty list item, remove it (so that pressing RET twice when in a
4949 list simply adds a blank line)."
4950 (interactive)
4951 (cond
4952 ;; Table
4953 ((markdown-table-at-point-p)
4954 (call-interactively #'markdown-table-next-row))
4955 ;; Indent non-table text
4956 (markdown-indent-on-enter
4957 (let (bounds)
4958 (if (and (memq markdown-indent-on-enter '(indent-and-new-item))
4959 (setq bounds (markdown-cur-list-item-bounds)))
4960 (let ((beg (cl-first bounds))
4961 (end (cl-second bounds))
4962 (length (cl-fourth bounds)))
4963 ;; Point is in a list item
4964 (if (= (- end beg) length)
4965 ;; Delete blank list
4966 (progn
4967 (delete-region beg end)
4968 (newline)
4969 (markdown-indent-line))
4970 (call-interactively #'markdown-insert-list-item)))
4971 ;; Point is not in a list
4972 (newline)
4973 (markdown-indent-line))))
4974 ;; Insert a raw newline
4975 (t (newline))))
4977 (define-obsolete-function-alias 'markdown-exdent-or-delete
4978 'markdown-outdent-or-delete "v2.3")
4980 (defun markdown-outdent-or-delete (arg)
4981 "Handle BACKSPACE by cycling through indentation points.
4982 When BACKSPACE is pressed, if there is only whitespace
4983 before the current point, then outdent the line one level.
4984 Otherwise, do normal delete by repeating
4985 `backward-delete-char-untabify' ARG times."
4986 (interactive "*p")
4987 (if (use-region-p)
4988 (backward-delete-char-untabify arg)
4989 (let ((cur-pos (current-column))
4990 (start-of-indention (save-excursion
4991 (back-to-indentation)
4992 (current-column)))
4993 (positions (markdown-calc-indents)))
4994 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
4995 (indent-line-to (markdown-outdent-find-next-position cur-pos positions))
4996 (backward-delete-char-untabify arg)))))
4998 (defun markdown-find-leftmost-column (beg end)
4999 "Find the leftmost column in the region from BEG to END."
5000 (let ((mincol 1000))
5001 (save-excursion
5002 (goto-char beg)
5003 (while (< (point) end)
5004 (back-to-indentation)
5005 (unless (looking-at-p "[ \t]*$")
5006 (setq mincol (min mincol (current-column))))
5007 (forward-line 1)
5009 mincol))
5011 (defun markdown-indent-region (beg end arg)
5012 "Indent the region from BEG to END using some heuristics.
5013 When ARG is non-nil, outdent the region instead.
5014 See `markdown-indent-line' and `markdown-indent-line'."
5015 (interactive "*r\nP")
5016 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
5017 (leftmostcol (markdown-find-leftmost-column beg end))
5018 (next-pos (if arg
5019 (markdown-outdent-find-next-position leftmostcol positions)
5020 (markdown-indent-find-next-position leftmostcol positions))))
5021 (indent-rigidly beg end (- next-pos leftmostcol))
5022 (setq deactivate-mark nil)))
5024 (define-obsolete-function-alias 'markdown-exdent-region
5025 'markdown-outdent-region "v2.3")
5027 (defun markdown-outdent-region (beg end)
5028 "Call `markdown-indent-region' on region from BEG to END with prefix."
5029 (interactive "*r")
5030 (markdown-indent-region beg end t))
5033 ;;; Markup Completion =========================================================
5035 (defconst markdown-complete-alist
5036 '((markdown-regex-header-atx . markdown-complete-atx)
5037 (markdown-regex-header-setext . markdown-complete-setext)
5038 (markdown-regex-hr . markdown-complete-hr))
5039 "Association list of form (regexp . function) for markup completion.")
5041 (defun markdown-incomplete-atx-p ()
5042 "Return t if ATX header markup is incomplete and nil otherwise.
5043 Assumes match data is available for `markdown-regex-header-atx'.
5044 Checks that the number of trailing hash marks equals the number of leading
5045 hash marks, that there is only a single space before and after the text,
5046 and that there is no extraneous whitespace in the text."
5048 ;; Number of starting and ending hash marks differs
5049 (not (= (length (match-string 1)) (length (match-string 3))))
5050 ;; When the header text is not empty...
5051 (and (> (length (match-string 2)) 0)
5052 ;; ...if there are extra leading, trailing, or interior spaces
5053 (or (not (= (match-beginning 2) (1+ (match-end 1))))
5054 (not (= (match-beginning 3) (1+ (match-end 2))))
5055 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
5056 ;; When the header text is empty...
5057 (and (= (length (match-string 2)) 0)
5058 ;; ...if there are too many or too few spaces
5059 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
5061 (defun markdown-complete-atx ()
5062 "Complete and normalize ATX headers.
5063 Add or remove hash marks to the end of the header to match the
5064 beginning. Ensure that there is only a single space between hash
5065 marks and header text. Removes extraneous whitespace from header text.
5066 Assumes match data is available for `markdown-regex-header-atx'.
5067 Return nil if markup was complete and non-nil if markup was completed."
5068 (when (markdown-incomplete-atx-p)
5069 (let* ((new-marker (make-marker))
5070 (new-marker (set-marker new-marker (match-end 2))))
5071 ;; Hash marks and spacing at end
5072 (goto-char (match-end 2))
5073 (delete-region (match-end 2) (match-end 3))
5074 (insert " " (match-string 1))
5075 ;; Remove extraneous whitespace from title
5076 (replace-match (markdown-compress-whitespace-string (match-string 2))
5077 t t nil 2)
5078 ;; Spacing at beginning
5079 (goto-char (match-end 1))
5080 (delete-region (match-end 1) (match-beginning 2))
5081 (insert " ")
5082 ;; Leave point at end of text
5083 (goto-char new-marker))))
5085 (defun markdown-incomplete-setext-p ()
5086 "Return t if setext header markup is incomplete and nil otherwise.
5087 Assumes match data is available for `markdown-regex-header-setext'.
5088 Checks that length of underline matches text and that there is no
5089 extraneous whitespace in the text."
5090 (or (not (= (length (match-string 1)) (length (match-string 2))))
5091 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
5093 (defun markdown-complete-setext ()
5094 "Complete and normalize setext headers.
5095 Add or remove underline characters to match length of header
5096 text. Removes extraneous whitespace from header text. Assumes
5097 match data is available for `markdown-regex-header-setext'.
5098 Return nil if markup was complete and non-nil if markup was completed."
5099 (when (markdown-incomplete-setext-p)
5100 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
5101 (char (char-after (match-beginning 2)))
5102 (level (if (char-equal char ?-) 2 1)))
5103 (goto-char (match-beginning 0))
5104 (delete-region (match-beginning 0) (match-end 0))
5105 (markdown-insert-header level text t)
5106 t)))
5108 (defun markdown-incomplete-hr-p ()
5109 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
5110 Assumes match data is available for `markdown-regex-hr'."
5111 (not (member (match-string 0) markdown-hr-strings)))
5113 (defun markdown-complete-hr ()
5114 "Complete horizontal rules.
5115 If horizontal rule string is a member of `markdown-hr-strings',
5116 do nothing. Otherwise, replace with the car of
5117 `markdown-hr-strings'.
5118 Assumes match data is available for `markdown-regex-hr'.
5119 Return nil if markup was complete and non-nil if markup was completed."
5120 (when (markdown-incomplete-hr-p)
5121 (replace-match (car markdown-hr-strings))
5124 (defun markdown-complete ()
5125 "Complete markup of object near point or in region when active.
5126 Handle all objects in `markdown-complete-alist', in order.
5127 See `markdown-complete-at-point' and `markdown-complete-region'."
5128 (interactive "*")
5129 (if (markdown-use-region-p)
5130 (markdown-complete-region (region-beginning) (region-end))
5131 (markdown-complete-at-point)))
5133 (defun markdown-complete-at-point ()
5134 "Complete markup of object near point.
5135 Handle all elements of `markdown-complete-alist' in order."
5136 (interactive "*")
5137 (let ((list markdown-complete-alist) found changed)
5138 (while list
5139 (let ((regexp (eval (caar list)))
5140 (function (cdar list)))
5141 (setq list (cdr list))
5142 (when (thing-at-point-looking-at regexp)
5143 (setq found t)
5144 (setq changed (funcall function))
5145 (setq list nil))))
5146 (if found
5147 (or changed (user-error "Markup at point is complete"))
5148 (user-error "Nothing to complete at point"))))
5150 (defun markdown-complete-region (beg end)
5151 "Complete markup of objects in region from BEG to END.
5152 Handle all objects in `markdown-complete-alist', in order. Each
5153 match is checked to ensure that a previous regexp does not also
5154 match."
5155 (interactive "*r")
5156 (let ((end-marker (set-marker (make-marker) end))
5157 previous)
5158 (dolist (element markdown-complete-alist)
5159 (let ((regexp (eval (car element)))
5160 (function (cdr element)))
5161 (goto-char beg)
5162 (while (re-search-forward regexp end-marker 'limit)
5163 (when (match-string 0)
5164 ;; Make sure this is not a match for any of the preceding regexps.
5165 ;; This prevents mistaking an HR for a Setext subheading.
5166 (let (match)
5167 (save-match-data
5168 (dolist (prev-regexp previous)
5169 (or match (setq match (looking-back prev-regexp nil)))))
5170 (unless match
5171 (save-excursion (funcall function))))))
5172 (cl-pushnew regexp previous :test #'equal)))
5173 previous))
5175 (defun markdown-complete-buffer ()
5176 "Complete markup for all objects in the current buffer."
5177 (interactive "*")
5178 (markdown-complete-region (point-min) (point-max)))
5181 ;;; Markup Cycling ============================================================
5183 (defun markdown-cycle-atx (arg &optional remove)
5184 "Cycle ATX header markup.
5185 Promote header (decrease level) when ARG is 1 and demote
5186 header (increase level) if arg is -1. When REMOVE is non-nil,
5187 remove the header when the level reaches zero and stop cycling
5188 when it reaches six. Otherwise, perform a proper cycling through
5189 levels one through six. Assumes match data is available for
5190 `markdown-regex-header-atx'."
5191 (let* ((old-level (length (match-string 1)))
5192 (new-level (+ old-level arg))
5193 (text (match-string 2)))
5194 (when (not remove)
5195 (setq new-level (% new-level 6))
5196 (setq new-level (cond ((= new-level 0) 6)
5197 ((< new-level 0) (+ new-level 6))
5198 (t new-level))))
5199 (cond
5200 ((= new-level 0)
5201 (markdown-unwrap-thing-at-point nil 0 2))
5202 ((<= new-level 6)
5203 (goto-char (match-beginning 0))
5204 (delete-region (match-beginning 0) (match-end 0))
5205 (markdown-insert-header new-level text nil)))))
5207 (defun markdown-cycle-setext (arg &optional remove)
5208 "Cycle setext header markup.
5209 Promote header (increase level) when ARG is 1 and demote
5210 header (decrease level or remove) if arg is -1. When demoting a
5211 level-two setext header, replace with a level-three atx header.
5212 When REMOVE is non-nil, remove the header when the level reaches
5213 zero. Otherwise, cycle back to a level six atx header. Assumes
5214 match data is available for `markdown-regex-header-setext'."
5215 (let* ((char (char-after (match-beginning 2)))
5216 (old-level (if (char-equal char ?=) 1 2))
5217 (new-level (+ old-level arg)))
5218 (when (and (not remove) (= new-level 0))
5219 (setq new-level 6))
5220 (cond
5221 ((= new-level 0)
5222 (markdown-unwrap-thing-at-point nil 0 1))
5223 ((<= new-level 2)
5224 (markdown-insert-header new-level nil t))
5225 ((<= new-level 6)
5226 (markdown-insert-header new-level nil nil)))))
5228 (defun markdown-cycle-hr (arg &optional remove)
5229 "Cycle string used for horizontal rule from `markdown-hr-strings'.
5230 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
5231 backwards (promote). When REMOVE is non-nil, remove the hr instead
5232 of cycling when the end of the list is reached.
5233 Assumes match data is available for `markdown-regex-hr'."
5234 (let* ((strings (if (= arg -1)
5235 (reverse markdown-hr-strings)
5236 markdown-hr-strings))
5237 (tail (member (match-string 0) strings))
5238 (new (or (cadr tail)
5239 (if remove
5240 (if (= arg 1)
5242 (car tail))
5243 (car strings)))))
5244 (replace-match new)))
5246 (defun markdown-cycle-bold ()
5247 "Cycle bold markup between underscores and asterisks.
5248 Assumes match data is available for `markdown-regex-bold'."
5249 (save-excursion
5250 (let* ((old-delim (match-string 3))
5251 (new-delim (if (string-equal old-delim "**") "__" "**")))
5252 (replace-match new-delim t t nil 3)
5253 (replace-match new-delim t t nil 5))))
5255 (defun markdown-cycle-italic ()
5256 "Cycle italic markup between underscores and asterisks.
5257 Assumes match data is available for `markdown-regex-italic'."
5258 (save-excursion
5259 (let* ((old-delim (match-string 2))
5260 (new-delim (if (string-equal old-delim "*") "_" "*")))
5261 (replace-match new-delim t t nil 2)
5262 (replace-match new-delim t t nil 4))))
5265 ;;; Keymap ====================================================================
5267 (defun markdown--style-map-prompt ()
5268 "Return a formatted prompt for Markdown markup insertion."
5269 (when markdown-enable-prefix-prompts
5270 (concat
5271 "Markdown: "
5272 (propertize "bold" 'face 'markdown-bold-face) ", "
5273 (propertize "italic" 'face 'markdown-italic-face) ", "
5274 (propertize "code" 'face 'markdown-inline-code-face) ", "
5275 (propertize "C = GFM code" 'face 'markdown-code-face) ", "
5276 (propertize "pre" 'face 'markdown-pre-face) ", "
5277 (propertize "footnote" 'face 'markdown-footnote-text-face) ", "
5278 (propertize "q = blockquote" 'face 'markdown-blockquote-face) ", "
5279 (propertize "h & 1-6 = heading" 'face 'markdown-header-face) ", "
5280 (propertize "- = hr" 'face 'markdown-hr-face) ", "
5281 "C-h = more")))
5283 (defun markdown--command-map-prompt ()
5284 "Return prompt for Markdown buffer-wide commands."
5285 (when markdown-enable-prefix-prompts
5286 (concat
5287 "Command: "
5288 (propertize "m" 'face 'markdown-bold-face) "arkdown, "
5289 (propertize "p" 'face 'markdown-bold-face) "review, "
5290 (propertize "o" 'face 'markdown-bold-face) "pen, "
5291 (propertize "e" 'face 'markdown-bold-face) "xport, "
5292 "export & pre" (propertize "v" 'face 'markdown-bold-face) "iew, "
5293 (propertize "c" 'face 'markdown-bold-face) "heck refs, "
5294 (propertize "u" 'face 'markdown-bold-face) "nused refs, "
5295 "C-h = more")))
5297 (defvar markdown-mode-style-map
5298 (let ((map (make-keymap (markdown--style-map-prompt))))
5299 (define-key map (kbd "1") 'markdown-insert-header-atx-1)
5300 (define-key map (kbd "2") 'markdown-insert-header-atx-2)
5301 (define-key map (kbd "3") 'markdown-insert-header-atx-3)
5302 (define-key map (kbd "4") 'markdown-insert-header-atx-4)
5303 (define-key map (kbd "5") 'markdown-insert-header-atx-5)
5304 (define-key map (kbd "6") 'markdown-insert-header-atx-6)
5305 (define-key map (kbd "!") 'markdown-insert-header-setext-1)
5306 (define-key map (kbd "@") 'markdown-insert-header-setext-2)
5307 (define-key map (kbd "b") 'markdown-insert-bold)
5308 (define-key map (kbd "c") 'markdown-insert-code)
5309 (define-key map (kbd "C") 'markdown-insert-gfm-code-block)
5310 (define-key map (kbd "f") 'markdown-insert-footnote)
5311 (define-key map (kbd "h") 'markdown-insert-header-dwim)
5312 (define-key map (kbd "H") 'markdown-insert-header-setext-dwim)
5313 (define-key map (kbd "i") 'markdown-insert-italic)
5314 (define-key map (kbd "k") 'markdown-insert-kbd)
5315 (define-key map (kbd "l") 'markdown-insert-link)
5316 (define-key map (kbd "p") 'markdown-insert-pre)
5317 (define-key map (kbd "P") 'markdown-pre-region)
5318 (define-key map (kbd "q") 'markdown-insert-blockquote)
5319 (define-key map (kbd "s") 'markdown-insert-strike-through)
5320 (define-key map (kbd "Q") 'markdown-blockquote-region)
5321 (define-key map (kbd "w") 'markdown-insert-wiki-link)
5322 (define-key map (kbd "-") 'markdown-insert-hr)
5323 (define-key map (kbd "[") 'markdown-insert-gfm-checkbox)
5324 ;; Deprecated keys that may be removed in a future version
5325 (define-key map (kbd "e") 'markdown-insert-italic)
5326 map)
5327 "Keymap for Markdown text styling commands.")
5329 (defvar markdown-mode-command-map
5330 (let ((map (make-keymap (markdown--command-map-prompt))))
5331 (define-key map (kbd "m") 'markdown-other-window)
5332 (define-key map (kbd "p") 'markdown-preview)
5333 (define-key map (kbd "e") 'markdown-export)
5334 (define-key map (kbd "v") 'markdown-export-and-preview)
5335 (define-key map (kbd "o") 'markdown-open)
5336 (define-key map (kbd "l") 'markdown-live-preview-mode)
5337 (define-key map (kbd "w") 'markdown-kill-ring-save)
5338 (define-key map (kbd "c") 'markdown-check-refs)
5339 (define-key map (kbd "u") 'markdown-unused-refs)
5340 (define-key map (kbd "n") 'markdown-cleanup-list-numbers)
5341 (define-key map (kbd "]") 'markdown-complete-buffer)
5342 (define-key map (kbd "^") 'markdown-table-sort-lines)
5343 (define-key map (kbd "|") 'markdown-table-convert-region)
5344 (define-key map (kbd "t") 'markdown-table-transpose)
5345 map)
5346 "Keymap for Markdown buffer-wide commands.")
5348 (defvar markdown-mode-map
5349 (let ((map (make-keymap)))
5350 ;; Markup insertion & removal
5351 (define-key map (kbd "C-c C-s") markdown-mode-style-map)
5352 (define-key map (kbd "C-c C-l") 'markdown-insert-link)
5353 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
5354 ;; Promotion, demotion, and cycling
5355 (define-key map (kbd "C-c C--") 'markdown-promote)
5356 (define-key map (kbd "C-c C-=") 'markdown-demote)
5357 (define-key map (kbd "C-c C-]") 'markdown-complete)
5358 ;; Following and doing things
5359 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
5360 (define-key map (kbd "C-c C-d") 'markdown-do)
5361 (define-key map (kbd "C-c '") 'markdown-edit-code-block)
5362 ;; Indentation
5363 (define-key map (kbd "C-m") 'markdown-enter-key)
5364 (define-key map (kbd "DEL") 'markdown-outdent-or-delete)
5365 (define-key map (kbd "C-c >") 'markdown-indent-region)
5366 (define-key map (kbd "C-c <") 'markdown-outdent-region)
5367 ;; Visibility cycling
5368 (define-key map (kbd "TAB") 'markdown-cycle)
5369 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
5370 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
5371 (define-key map (kbd "<backtab>") 'markdown-shifttab)
5372 ;; Heading and list navigation
5373 (define-key map (kbd "C-c C-n") 'markdown-outline-next)
5374 (define-key map (kbd "C-c C-p") 'markdown-outline-previous)
5375 (define-key map (kbd "C-c C-f") 'markdown-outline-next-same-level)
5376 (define-key map (kbd "C-c C-b") 'markdown-outline-previous-same-level)
5377 (define-key map (kbd "C-c C-u") 'markdown-outline-up)
5378 ;; Buffer-wide commands
5379 (define-key map (kbd "C-c C-c") markdown-mode-command-map)
5380 ;; Subtree, list, and table editing
5381 (define-key map (kbd "C-c <up>") 'markdown-move-up)
5382 (define-key map (kbd "C-c <down>") 'markdown-move-down)
5383 (define-key map (kbd "C-c <left>") 'markdown-promote)
5384 (define-key map (kbd "C-c <right>") 'markdown-demote)
5385 (define-key map (kbd "C-c S-<up>") 'markdown-table-delete-row)
5386 (define-key map (kbd "C-c S-<down>") 'markdown-table-insert-row)
5387 (define-key map (kbd "C-c S-<left>") 'markdown-table-delete-column)
5388 (define-key map (kbd "C-c S-<right>") 'markdown-table-insert-column)
5389 (define-key map (kbd "C-c C-M-h") 'markdown-mark-subtree)
5390 (define-key map (kbd "C-x n s") 'markdown-narrow-to-subtree)
5391 (define-key map (kbd "M-RET") 'markdown-insert-list-item)
5392 (define-key map (kbd "C-c C-j") 'markdown-insert-list-item)
5393 ;; Paragraphs (Markdown context aware)
5394 (define-key map [remap backward-paragraph] 'markdown-backward-paragraph)
5395 (define-key map [remap forward-paragraph] 'markdown-forward-paragraph)
5396 (define-key map [remap mark-paragraph] 'markdown-mark-paragraph)
5397 ;; Blocks (one or more paragraphs)
5398 (define-key map (kbd "C-M-{") 'markdown-backward-block)
5399 (define-key map (kbd "C-M-}") 'markdown-forward-block)
5400 (define-key map (kbd "C-c M-h") 'markdown-mark-block)
5401 (define-key map (kbd "C-x n b") 'markdown-narrow-to-block)
5402 ;; Pages (top-level sections)
5403 (define-key map [remap backward-page] 'markdown-backward-page)
5404 (define-key map [remap forward-page] 'markdown-forward-page)
5405 (define-key map [remap mark-page] 'markdown-mark-page)
5406 (define-key map [remap narrow-to-page] 'markdown-narrow-to-page)
5407 ;; Link Movement
5408 (define-key map (kbd "M-n") 'markdown-next-link)
5409 (define-key map (kbd "M-p") 'markdown-previous-link)
5410 ;; Toggling functionality
5411 (define-key map (kbd "C-c C-x C-e") 'markdown-toggle-math)
5412 (define-key map (kbd "C-c C-x C-f") 'markdown-toggle-fontify-code-blocks-natively)
5413 (define-key map (kbd "C-c C-x C-i") 'markdown-toggle-inline-images)
5414 (define-key map (kbd "C-c C-x C-l") 'markdown-toggle-url-hiding)
5415 (define-key map (kbd "C-c C-x C-m") 'markdown-toggle-markup-hiding)
5416 ;; Alternative keys (in case of problems with the arrow keys)
5417 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
5418 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
5419 (define-key map (kbd "C-c C-x l") 'markdown-promote)
5420 (define-key map (kbd "C-c C-x r") 'markdown-demote)
5421 ;; Deprecated keys that may be removed in a future version
5422 (define-key map (kbd "C-c C-a L") 'markdown-insert-link) ;; C-c C-l
5423 (define-key map (kbd "C-c C-a l") 'markdown-insert-link) ;; C-c C-l
5424 (define-key map (kbd "C-c C-a r") 'markdown-insert-link) ;; C-c C-l
5425 (define-key map (kbd "C-c C-a u") 'markdown-insert-uri) ;; C-c C-l
5426 (define-key map (kbd "C-c C-a f") 'markdown-insert-footnote)
5427 (define-key map (kbd "C-c C-a w") 'markdown-insert-wiki-link)
5428 (define-key map (kbd "C-c C-t 1") 'markdown-insert-header-atx-1)
5429 (define-key map (kbd "C-c C-t 2") 'markdown-insert-header-atx-2)
5430 (define-key map (kbd "C-c C-t 3") 'markdown-insert-header-atx-3)
5431 (define-key map (kbd "C-c C-t 4") 'markdown-insert-header-atx-4)
5432 (define-key map (kbd "C-c C-t 5") 'markdown-insert-header-atx-5)
5433 (define-key map (kbd "C-c C-t 6") 'markdown-insert-header-atx-6)
5434 (define-key map (kbd "C-c C-t !") 'markdown-insert-header-setext-1)
5435 (define-key map (kbd "C-c C-t @") 'markdown-insert-header-setext-2)
5436 (define-key map (kbd "C-c C-t h") 'markdown-insert-header-dwim)
5437 (define-key map (kbd "C-c C-t H") 'markdown-insert-header-setext-dwim)
5438 (define-key map (kbd "C-c C-t s") 'markdown-insert-header-setext-2)
5439 (define-key map (kbd "C-c C-t t") 'markdown-insert-header-setext-1)
5440 (define-key map (kbd "C-c C-i") 'markdown-insert-image)
5441 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item) ;; C-c C-j
5442 (define-key map (kbd "C-c C-x C-x") 'markdown-toggle-gfm-checkbox) ;; C-c C-d
5443 (define-key map (kbd "C-c -") 'markdown-insert-hr)
5444 map)
5445 "Keymap for Markdown major mode.")
5447 (defvar markdown-mode-mouse-map
5448 (let ((map (make-sparse-keymap)))
5449 (define-key map [follow-link] 'mouse-face)
5450 (define-key map [mouse-2] 'markdown-follow-link-at-point)
5451 map)
5452 "Keymap for following links with mouse.")
5454 (defvar gfm-mode-map
5455 (let ((map (make-sparse-keymap)))
5456 (set-keymap-parent map markdown-mode-map)
5457 (define-key map (kbd "C-c C-s d") 'markdown-insert-strike-through)
5458 (define-key map "`" 'markdown-electric-backquote)
5459 map)
5460 "Keymap for `gfm-mode'.
5461 See also `markdown-mode-map'.")
5464 ;;; Menu ==================================================================
5466 (easy-menu-define markdown-mode-menu markdown-mode-map
5467 "Menu for Markdown mode"
5468 '("Markdown"
5469 "---"
5470 ("Movement"
5471 ["Jump" markdown-do]
5472 ["Follow Link" markdown-follow-thing-at-point]
5473 ["Next Link" markdown-next-link]
5474 ["Previous Link" markdown-previous-link]
5475 "---"
5476 ["Next Heading or List Item" markdown-outline-next]
5477 ["Previous Heading or List Item" markdown-outline-previous]
5478 ["Next at Same Level" markdown-outline-next-same-level]
5479 ["Previous at Same Level" markdown-outline-previous-same-level]
5480 ["Up to Parent" markdown-outline-up]
5481 "---"
5482 ["Forward Paragraph" markdown-forward-paragraph]
5483 ["Backward Paragraph" markdown-backward-paragraph]
5484 ["Forward Block" markdown-forward-block]
5485 ["Backward Block" markdown-backward-block])
5486 ("Show & Hide"
5487 ["Cycle Heading Visibility" markdown-cycle
5488 :enable (markdown-on-heading-p)]
5489 ["Cycle Heading Visibility (Global)" markdown-shifttab]
5490 "---"
5491 ["Narrow to Region" narrow-to-region]
5492 ["Narrow to Block" markdown-narrow-to-block]
5493 ["Narrow to Section" narrow-to-defun]
5494 ["Narrow to Subtree" markdown-narrow-to-subtree]
5495 ["Widen" widen (buffer-narrowed-p)]
5496 "---"
5497 ["Toggle Markup Hiding" markdown-toggle-markup-hiding
5498 :keys "C-c C-x C-m"
5499 :style radio
5500 :selected markdown-hide-markup])
5501 "---"
5502 ("Headings & Structure"
5503 ["Automatic Heading" markdown-insert-header-dwim
5504 :keys "C-c C-s h"]
5505 ["Automatic Heading (Setext)" markdown-insert-header-setext-dwim
5506 :keys "C-c C-s H"]
5507 ("Specific Heading (atx)"
5508 ["First Level atx" markdown-insert-header-atx-1
5509 :keys "C-c C-s 1"]
5510 ["Second Level atx" markdown-insert-header-atx-2
5511 :keys "C-c C-s 2"]
5512 ["Third Level atx" markdown-insert-header-atx-3
5513 :keys "C-c C-s 3"]
5514 ["Fourth Level atx" markdown-insert-header-atx-4
5515 :keys "C-c C-s 4"]
5516 ["Fifth Level atx" markdown-insert-header-atx-5
5517 :keys "C-c C-s 5"]
5518 ["Sixth Level atx" markdown-insert-header-atx-6
5519 :keys "C-c C-s 6"])
5520 ("Specific Heading (Setext)"
5521 ["First Level Setext" markdown-insert-header-setext-1
5522 :keys "C-c C-s !"]
5523 ["Second Level Setext" markdown-insert-header-setext-2
5524 :keys "C-c C-s @"])
5525 ["Horizontal Rule" markdown-insert-hr
5526 :keys "C-c C-s -"]
5527 "---"
5528 ["Move Subtree Up" markdown-move-up
5529 :keys "C-c <up>"]
5530 ["Move Subtree Down" markdown-move-down
5531 :keys "C-c <down>"]
5532 ["Promote Subtree" markdown-promote
5533 :keys "C-c <left>"]
5534 ["Demote Subtree" markdown-demote
5535 :keys "C-c <right>"])
5536 ("Region & Mark"
5537 ["Indent Region" markdown-indent-region]
5538 ["Outdent Region" markdown-outdent-region]
5539 "--"
5540 ["Mark Paragraph" mark-paragraph]
5541 ["Mark Block" markdown-mark-block]
5542 ["Mark Section" mark-defun]
5543 ["Mark Subtree" markdown-mark-subtree])
5544 ("Tables"
5545 ["Move Row Up" markdown-move-up
5546 :enable (markdown-table-at-point-p)
5547 :keys "C-c <up>"]
5548 ["Move Row Down" markdown-move-down
5549 :enable (markdown-table-at-point-p)
5550 :keys "C-c <down>"]
5551 ["Move Column Left" markdown-demote
5552 :enable (markdown-table-at-point-p)
5553 :keys "C-c <left>"]
5554 ["Move Column Right" markdown-promote
5555 :enable (markdown-table-at-point-p)
5556 :keys "C-c <right>"]
5557 ["Delete Row" markdown-table-delete-row
5558 :enable (markdown-table-at-point-p)]
5559 ["Insert Row" markdown-table-insert-row
5560 :enable (markdown-table-at-point-p)]
5561 ["Delete Column" markdown-table-delete-column
5562 :enable (markdown-table-at-point-p)]
5563 ["Insert Column" markdown-table-insert-column
5564 :enable (markdown-table-at-point-p)]
5565 "--"
5566 ["Convert Region to Table" markdown-table-convert-region]
5567 ["Sort Table Lines" markdown-table-sort-lines
5568 :enable (markdown-table-at-point-p)]
5569 ["Transpose Table" markdown-table-transpose
5570 :enable (markdown-table-at-point-p)])
5571 ("Lists"
5572 ["Insert List Item" markdown-insert-list-item]
5573 ["Move Subtree Up" markdown-move-up
5574 :keys "C-c <up>"]
5575 ["Move Subtree Down" markdown-move-down
5576 :keys "C-c <down>"]
5577 ["Indent Subtree" markdown-demote
5578 :keys "C-c <right>"]
5579 ["Outdent Subtree" markdown-promote
5580 :keys "C-c <left>"]
5581 ["Renumber List" markdown-cleanup-list-numbers]
5582 ["Insert Task List Item" markdown-insert-gfm-checkbox
5583 :keys "C-c C-x ["]
5584 ["Toggle Task List Item" markdown-toggle-gfm-checkbox
5585 :enable (markdown-gfm-task-list-item-at-point)
5586 :keys "C-c C-d"])
5587 ("Links & Images"
5588 ["Insert Link" markdown-insert-link]
5589 ["Insert Image" markdown-insert-image]
5590 ["Insert Footnote" markdown-insert-footnote
5591 :keys "C-c C-s f"]
5592 ["Insert Wiki Link" markdown-insert-wiki-link
5593 :keys "C-c C-s w"]
5594 "---"
5595 ["Check References" markdown-check-refs]
5596 ["Find Unused References" markdown-unused-refs]
5597 ["Toggle URL Hiding" markdown-toggle-url-hiding
5598 :style radio
5599 :selected markdown-hide-urls]
5600 ["Toggle Inline Images" markdown-toggle-inline-images
5601 :keys "C-c C-x C-i"
5602 :style radio
5603 :selected markdown-inline-image-overlays]
5604 ["Toggle Wiki Links" markdown-toggle-wiki-links
5605 :style radio
5606 :selected markdown-enable-wiki-links])
5607 ("Styles"
5608 ["Bold" markdown-insert-bold]
5609 ["Italic" markdown-insert-italic]
5610 ["Code" markdown-insert-code]
5611 ["Strikethrough" markdown-insert-strike-through]
5612 ["Keyboard" markdown-insert-kbd]
5613 "---"
5614 ["Blockquote" markdown-insert-blockquote]
5615 ["Preformatted" markdown-insert-pre]
5616 ["GFM Code Block" markdown-insert-gfm-code-block]
5617 ["Edit Code Block" markdown-edit-code-block
5618 :enable (markdown-code-block-at-point-p)]
5619 "---"
5620 ["Blockquote Region" markdown-blockquote-region]
5621 ["Preformatted Region" markdown-pre-region]
5622 "---"
5623 ["Fontify Code Blocks Natively"
5624 markdown-toggle-fontify-code-blocks-natively
5625 :style radio
5626 :selected markdown-fontify-code-blocks-natively]
5627 ["LaTeX Math Support" markdown-toggle-math
5628 :style radio
5629 :selected markdown-enable-math])
5630 "---"
5631 ("Preview & Export"
5632 ["Compile" markdown-other-window]
5633 ["Preview" markdown-preview]
5634 ["Export" markdown-export]
5635 ["Export & View" markdown-export-and-preview]
5636 ["Open" markdown-open]
5637 ["Live Export" markdown-live-preview-mode
5638 :style radio
5639 :selected markdown-live-preview-mode]
5640 ["Kill ring save" markdown-kill-ring-save])
5641 ("Markup Completion and Cycling"
5642 ["Complete Markup" markdown-complete]
5643 ["Promote Element" markdown-promote
5644 :keys "C-c C--"]
5645 ["Demote Element" markdown-demote
5646 :keys "C-c C-="])
5647 "---"
5648 ["Kill Element" markdown-kill-thing-at-point]
5649 "---"
5650 ("Documentation"
5651 ["Version" markdown-show-version]
5652 ["Homepage" markdown-mode-info]
5653 ["Describe Mode" (describe-function 'markdown-mode)]
5654 ["Guide" (browse-url "https://leanpub.com/markdown-mode")])))
5657 ;;; imenu =====================================================================
5659 (defun markdown-imenu-create-nested-index ()
5660 "Create and return a nested imenu index alist for the current buffer.
5661 See `imenu-create-index-function' and `imenu--index-alist' for details."
5662 (let* ((root '(nil . nil))
5663 cur-alist
5664 (cur-level 0)
5665 (empty-heading "-")
5666 (self-heading ".")
5667 hashes pos level heading)
5668 (save-excursion
5669 ;; Headings
5670 (goto-char (point-min))
5671 (while (re-search-forward markdown-regex-header (point-max) t)
5672 (unless (markdown-code-block-at-point-p)
5673 (cond
5674 ((match-string-no-properties 2) ;; level 1 setext
5675 (setq heading (match-string-no-properties 1))
5676 (setq pos (match-beginning 1)
5677 level 1))
5678 ((match-string-no-properties 3) ;; level 2 setext
5679 (setq heading (match-string-no-properties 1))
5680 (setq pos (match-beginning 1)
5681 level 2))
5682 ((setq hashes (markdown-trim-whitespace
5683 (match-string-no-properties 4)))
5684 (setq heading (match-string-no-properties 5)
5685 pos (match-beginning 4)
5686 level (length hashes))))
5687 (let ((alist (list (cons heading pos))))
5688 (cond
5689 ((= cur-level level) ; new sibling
5690 (setcdr cur-alist alist)
5691 (setq cur-alist alist))
5692 ((< cur-level level) ; first child
5693 (dotimes (_ (- level cur-level 1))
5694 (setq alist (list (cons empty-heading alist))))
5695 (if cur-alist
5696 (let* ((parent (car cur-alist))
5697 (self-pos (cdr parent)))
5698 (setcdr parent (cons (cons self-heading self-pos) alist)))
5699 (setcdr root alist)) ; primogenitor
5700 (setq cur-alist alist)
5701 (setq cur-level level))
5702 (t ; new sibling of an ancestor
5703 (let ((sibling-alist (last (cdr root))))
5704 (dotimes (_ (1- level))
5705 (setq sibling-alist (last (cdar sibling-alist))))
5706 (setcdr sibling-alist alist)
5707 (setq cur-alist alist))
5708 (setq cur-level level))))))
5709 ;; Footnotes
5710 (let ((fn (markdown-get-defined-footnotes)))
5711 (if (or (zerop (length fn))
5712 (null markdown-add-footnotes-to-imenu))
5713 (cdr root)
5714 (nconc (cdr root) (list (cons "Footnotes" fn))))))))
5716 (defun markdown-imenu-create-flat-index ()
5717 "Create and return a flat imenu index alist for the current buffer.
5718 See `imenu-create-index-function' and `imenu--index-alist' for details."
5719 (let* ((empty-heading "-") index heading pos)
5720 (save-excursion
5721 ;; Headings
5722 (goto-char (point-min))
5723 (while (re-search-forward markdown-regex-header (point-max) t)
5724 (when (and (not (markdown-code-block-at-point-p))
5725 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin)))
5726 (cond
5727 ((setq heading (match-string-no-properties 1))
5728 (setq pos (match-beginning 1)))
5729 ((setq heading (match-string-no-properties 5))
5730 (setq pos (match-beginning 4))))
5731 (or (> (length heading) 0)
5732 (setq heading empty-heading))
5733 (setq index (append index (list (cons heading pos))))))
5734 ;; Footnotes
5735 (when markdown-add-footnotes-to-imenu
5736 (nconc index (markdown-get-defined-footnotes)))
5737 index)))
5740 ;;; References ================================================================
5742 (defun markdown-reference-goto-definition ()
5743 "Jump to the definition of the reference at point or create it."
5744 (interactive)
5745 (when (thing-at-point-looking-at markdown-regex-link-reference)
5746 (let* ((text (match-string-no-properties 3))
5747 (reference (match-string-no-properties 6))
5748 (target (downcase (if (string= reference "") text reference)))
5749 (loc (cadr (save-match-data (markdown-reference-definition target)))))
5750 (if loc
5751 (goto-char loc)
5752 (goto-char (match-beginning 0))
5753 (markdown-insert-reference-definition target)))))
5755 (defun markdown-reference-find-links (reference)
5756 "Return a list of all links for REFERENCE.
5757 REFERENCE should not include the surrounding square brackets.
5758 Elements of the list have the form (text start line), where
5759 text is the link text, start is the location at the beginning of
5760 the link, and line is the line number on which the link appears."
5761 (let* ((ref-quote (regexp-quote reference))
5762 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
5763 ref-quote ref-quote))
5764 links)
5765 (save-excursion
5766 (goto-char (point-min))
5767 (while (re-search-forward regexp nil t)
5768 (let* ((text (or (match-string-no-properties 1)
5769 (match-string-no-properties 2)))
5770 (start (match-beginning 0))
5771 (line (markdown-line-number-at-pos)))
5772 (cl-pushnew (list text start line) links :test #'equal))))
5773 links))
5775 (defmacro markdown-for-all-refs (f)
5776 `(let ((result))
5777 (save-excursion
5778 (goto-char (point-min))
5779 (while
5780 (re-search-forward markdown-regex-link-reference nil t)
5781 (let* ((text (match-string-no-properties 3))
5782 (reference (match-string-no-properties 6))
5783 (target (downcase (if (string= reference "") text reference))))
5784 (,f text target result))))
5785 (reverse result)))
5787 (defmacro markdown-collect-always (_ target result)
5788 `(cl-pushnew ,target ,result :test #'equal))
5790 (defmacro markdown-collect-undefined (text target result)
5791 `(unless (markdown-reference-definition target)
5792 (let ((entry (assoc ,target ,result)))
5793 (if (not entry)
5794 (cl-pushnew
5795 (cons ,target (list (cons ,text (markdown-line-number-at-pos))))
5796 ,result :test #'equal)
5797 (setcdr entry
5798 (append (cdr entry) (list (cons ,text (markdown-line-number-at-pos)))))))))
5800 (defun markdown-get-all-refs ()
5801 "Return a list of all Markdown references."
5802 (markdown-for-all-refs markdown-collect-always))
5804 (defun markdown-get-undefined-refs ()
5805 "Return a list of undefined Markdown references.
5806 Result is an alist of pairs (reference . occurrences), where
5807 occurrences is itself another alist of pairs (label . line-number).
5808 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
5809 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
5810 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
5811 (markdown-for-all-refs markdown-collect-undefined))
5813 (defun markdown-get-unused-refs ()
5814 (cl-set-difference
5815 (markdown-get-defined-references) (markdown-get-all-refs)
5816 :test (lambda (e1 e2) (equal (car e1) e2))))
5818 (defconst markdown-unused-references-buffer
5819 "*Unused references for %buffer%*"
5820 "Pattern for name of buffer for listing unused references.
5821 The string %buffer% will be replaced by the corresponding
5822 `markdown-mode' buffer name.")
5824 (defun markdown-unused-references-buffer (&optional buffer-name)
5825 "Name and return buffer for unused reference checking.
5826 BUFFER-NAME is the name of the main buffer being visited."
5827 (or buffer-name (setq buffer-name (buffer-name)))
5828 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
5829 "%buffer%" buffer-name
5830 markdown-unused-references-buffer))))
5831 (with-current-buffer refbuf
5832 (when view-mode
5833 (View-exit-and-edit))
5834 (use-local-map button-buffer-map)
5835 (erase-buffer))
5836 refbuf))
5838 (defconst markdown-reference-check-buffer
5839 "*Undefined references for %buffer%*"
5840 "Pattern for name of buffer for listing undefined references.
5841 The string %buffer% will be replaced by the corresponding
5842 `markdown-mode' buffer name.")
5844 (defun markdown-reference-check-buffer (&optional buffer-name)
5845 "Name and return buffer for reference checking.
5846 BUFFER-NAME is the name of the main buffer being visited."
5847 (or buffer-name (setq buffer-name (buffer-name)))
5848 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
5849 "%buffer%" buffer-name
5850 markdown-reference-check-buffer))))
5851 (with-current-buffer refbuf
5852 (when view-mode
5853 (View-exit-and-edit))
5854 (use-local-map button-buffer-map)
5855 (erase-buffer))
5856 refbuf))
5858 (defconst markdown-reference-links-buffer
5859 "*Reference links for %buffer%*"
5860 "Pattern for name of buffer for listing references.
5861 The string %buffer% will be replaced by the corresponding buffer name.")
5863 (defun markdown-reference-links-buffer (&optional buffer-name)
5864 "Name, setup, and return a buffer for listing links.
5865 BUFFER-NAME is the name of the main buffer being visited."
5866 (or buffer-name (setq buffer-name (buffer-name)))
5867 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
5868 "%buffer%" buffer-name
5869 markdown-reference-links-buffer))))
5870 (with-current-buffer linkbuf
5871 (when view-mode
5872 (View-exit-and-edit))
5873 (use-local-map button-buffer-map)
5874 (erase-buffer))
5875 linkbuf))
5877 ;; Add an empty Markdown reference definition to buffer
5878 ;; specified in the 'target-buffer property. The reference name is
5879 ;; the button's label.
5880 (define-button-type 'markdown-undefined-reference-button
5881 'help-echo "mouse-1, RET: create definition for undefined reference"
5882 'follow-link t
5883 'face 'bold
5884 'action (lambda (b)
5885 (let ((buffer (button-get b 'target-buffer))
5886 (line (button-get b 'target-line))
5887 (label (button-label b)))
5888 (switch-to-buffer-other-window buffer)
5889 (goto-char (point-min))
5890 (forward-line line)
5891 (markdown-insert-reference-definition label)
5892 (markdown-check-refs t))))
5894 ;; Jump to line in buffer specified by 'target-buffer property.
5895 ;; Line number is button's 'line property.
5896 (define-button-type 'markdown-goto-line-button
5897 'help-echo "mouse-1, RET: go to line"
5898 'follow-link t
5899 'face 'italic
5900 'action (lambda (b)
5901 (message (button-get b 'buffer))
5902 (switch-to-buffer-other-window (button-get b 'target-buffer))
5903 ;; use call-interactively to silence compiler
5904 (let ((current-prefix-arg (button-get b 'target-line)))
5905 (call-interactively 'goto-line))))
5907 ;; Jumps to a particular link at location given by 'target-char
5908 ;; property in buffer given by 'target-buffer property.
5909 (define-button-type 'markdown-location-button
5910 'help-echo "mouse-1, RET: jump to location of link"
5911 'follow-link t
5912 'face 'bold
5913 'action (lambda (b)
5914 (let ((target (button-get b 'target-buffer))
5915 (loc (button-get b 'target-char)))
5916 (kill-buffer-and-window)
5917 (switch-to-buffer target)
5918 (goto-char loc))))
5920 (defun markdown-insert-undefined-reference-button (reference oldbuf)
5921 "Insert a button for creating REFERENCE in buffer OLDBUF.
5922 REFERENCE should be a list of the form (reference . occurrences),
5923 as by `markdown-get-undefined-refs'."
5924 (let ((label (car reference)))
5925 ;; Create a reference button
5926 (insert-button label
5927 :type 'markdown-undefined-reference-button
5928 'target-buffer oldbuf
5929 'target-line (cdr (car (cdr reference))))
5930 (insert " (")
5931 (dolist (occurrence (cdr reference))
5932 (let ((line (cdr occurrence)))
5933 ;; Create a line number button
5934 (insert-button (number-to-string line)
5935 :type 'markdown-goto-line-button
5936 'target-buffer oldbuf
5937 'target-line line)
5938 (insert " ")))
5939 (delete-char -1)
5940 (insert ")")
5941 (newline)))
5943 (defun markdown-insert-unused-reference-button (reference oldbuf)
5944 "Insert a button for creating REFERENCE in buffer OLDBUF.
5945 REFERENCE must be a pair of (ref . line-number)."
5946 (let ((label (car reference)))
5947 ;; Create a reference button
5948 (insert-button label
5949 :type 'markdown-goto-line-button
5950 'target-buffer oldbuf
5951 'target-line (cdr reference))
5952 (insert (format " (%d)\n" (cdr reference)))))
5954 (defun markdown-insert-link-button (link oldbuf)
5955 "Insert a button for jumping to LINK in buffer OLDBUF.
5956 LINK should be a list of the form (text char line) containing
5957 the link text, location, and line number."
5958 (let ((label (cl-first link))
5959 (char (cl-second link))
5960 (line (cl-third link)))
5961 ;; Create a reference button
5962 (insert-button label
5963 :type 'markdown-location-button
5964 'target-buffer oldbuf
5965 'target-char char)
5966 (insert (format " (line %d)\n" line))))
5968 (defun markdown-reference-goto-link (&optional reference)
5969 "Jump to the location of the first use of REFERENCE."
5970 (interactive)
5971 (unless reference
5972 (if (thing-at-point-looking-at markdown-regex-reference-definition)
5973 (setq reference (match-string-no-properties 2))
5974 (user-error "No reference definition at point")))
5975 (let ((links (markdown-reference-find-links reference)))
5976 (cond ((= (length links) 1)
5977 (goto-char (cadr (car links))))
5978 ((> (length links) 1)
5979 (let ((oldbuf (current-buffer))
5980 (linkbuf (markdown-reference-links-buffer)))
5981 (with-current-buffer linkbuf
5982 (insert "Links using reference " reference ":\n\n")
5983 (dolist (link (reverse links))
5984 (markdown-insert-link-button link oldbuf)))
5985 (view-buffer-other-window linkbuf)
5986 (goto-char (point-min))
5987 (forward-line 2)))
5989 (error "No links for reference %s" reference)))))
5991 (defun markdown-check-refs (&optional silent)
5992 "Show all undefined Markdown references in current `markdown-mode' buffer.
5993 If SILENT is non-nil, do not message anything when no undefined
5994 references found.
5995 Links which have empty reference definitions are considered to be
5996 defined."
5997 (interactive "P")
5998 (when (not (memq major-mode '(markdown-mode gfm-mode)))
5999 (user-error "Not available in current mode"))
6000 (let ((oldbuf (current-buffer))
6001 (refs (markdown-get-undefined-refs))
6002 (refbuf (markdown-reference-check-buffer)))
6003 (if (null refs)
6004 (progn
6005 (when (not silent)
6006 (message "No undefined references found"))
6007 (kill-buffer refbuf))
6008 (with-current-buffer refbuf
6009 (insert "The following references are undefined:\n\n")
6010 (dolist (ref refs)
6011 (markdown-insert-undefined-reference-button ref oldbuf))
6012 (view-buffer-other-window refbuf)
6013 (goto-char (point-min))
6014 (forward-line 2)))))
6016 (defun markdown-unused-refs (&optional silent)
6017 "Show all unused Markdown references in current `markdown-mode' buffer.
6018 If SILENT is non-nil, do not message anything when no unused
6019 references found."
6020 (interactive "P")
6021 (when (not (memq major-mode '(markdown-mode gfm-mode)))
6022 (user-error "Not available in current mode"))
6023 (let ((oldbuf (current-buffer))
6024 (refs (markdown-get-unused-refs))
6025 (refbuf (markdown-unused-references-buffer)))
6026 (if (null refs)
6027 (progn
6028 (when (not silent)
6029 (message "No unused references found"))
6030 (kill-buffer refbuf))
6031 (with-current-buffer refbuf
6032 (insert "The following references are not used:\n\n")
6033 (dolist (ref refs)
6034 (markdown-insert-unused-reference-button ref oldbuf))
6035 (view-buffer-other-window refbuf)
6036 (goto-char (point-min))
6037 (forward-line 2)))))
6040 ;;; Lists =====================================================================
6042 (defun markdown-insert-list-item (&optional arg)
6043 "Insert a new list item.
6044 If the point is inside unordered list, insert a bullet mark. If
6045 the point is inside ordered list, insert the next number followed
6046 by a period. Use the previous list item to determine the amount
6047 of whitespace to place before and after list markers.
6049 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
6050 decrease the indentation by one level.
6052 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
6053 increase the indentation by one level."
6054 (interactive "p")
6055 (let (bounds cur-indent marker indent new-indent new-loc)
6056 (save-match-data
6057 ;; Look for a list item on current or previous non-blank line
6058 (save-excursion
6059 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
6060 (not (bobp))
6061 (markdown-cur-line-blank-p))
6062 (forward-line -1)))
6063 (when bounds
6064 (cond ((save-excursion
6065 (skip-chars-backward " \t")
6066 (looking-at-p markdown-regex-list))
6067 (beginning-of-line)
6068 (insert "\n")
6069 (forward-line -1))
6070 ((not (markdown-cur-line-blank-p))
6071 (newline)))
6072 (setq new-loc (point)))
6073 ;; Look ahead for a list item on next non-blank line
6074 (unless bounds
6075 (save-excursion
6076 (while (and (null bounds)
6077 (not (eobp))
6078 (markdown-cur-line-blank-p))
6079 (forward-line)
6080 (setq bounds (markdown-cur-list-item-bounds))))
6081 (when bounds
6082 (setq new-loc (point))
6083 (unless (markdown-cur-line-blank-p)
6084 (newline))))
6085 (if (not bounds)
6086 ;; When not in a list, start a new unordered one
6087 (progn
6088 (unless (markdown-cur-line-blank-p)
6089 (insert "\n"))
6090 (insert markdown-unordered-list-item-prefix))
6091 ;; Compute indentation and marker for new list item
6092 (setq cur-indent (nth 2 bounds))
6093 (setq marker (nth 4 bounds))
6094 ;; If current item is a GFM checkbox, insert new unchecked checkbox.
6095 (when (nth 5 bounds)
6096 (setq marker
6097 (concat marker
6098 (replace-regexp-in-string "[Xx]" " " (nth 5 bounds)))))
6099 (cond
6100 ;; Dedent: decrement indentation, find previous marker.
6101 ((= arg 4)
6102 (setq indent (max (- cur-indent 4) 0))
6103 (let ((prev-bounds
6104 (save-excursion
6105 (goto-char (nth 0 bounds))
6106 (when (markdown-up-list)
6107 (markdown-cur-list-item-bounds)))))
6108 (when prev-bounds
6109 (setq marker (nth 4 prev-bounds)))))
6110 ;; Indent: increment indentation by 4, use same marker.
6111 ((= arg 16) (setq indent (+ cur-indent 4)))
6112 ;; Same level: keep current indentation and marker.
6113 (t (setq indent cur-indent)))
6114 (setq new-indent (make-string indent 32))
6115 (goto-char new-loc)
6116 (cond
6117 ;; Ordered list
6118 ((string-match-p "[0-9]" marker)
6119 (if (= arg 16) ;; starting a new column indented one more level
6120 (insert (concat new-indent "1. "))
6121 ;; Don't use previous match-data
6122 (set-match-data nil)
6123 ;; travel up to the last item and pick the correct number. If
6124 ;; the argument was nil, "new-indent = cur-indent" is the same,
6125 ;; so we don't need special treatment. Neat.
6126 (save-excursion
6127 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
6128 (>= (forward-line -1) 0))))
6129 (let* ((old-prefix (match-string 1))
6130 (old-spacing (match-string 2))
6131 (new-prefix (if old-prefix
6132 (int-to-string (1+ (string-to-number old-prefix)))
6133 "1"))
6134 (space-adjust (- (length old-prefix) (length new-prefix)))
6135 (new-spacing (if (and (match-string 2)
6136 (not (string-match-p "\t" old-spacing))
6137 (< space-adjust 0)
6138 (> space-adjust (- 1 (length (match-string 2)))))
6139 (substring (match-string 2) 0 space-adjust)
6140 (or old-spacing ". "))))
6141 (insert (concat new-indent new-prefix new-spacing)))))
6142 ;; Unordered list, GFM task list, or ordered list with hash mark
6143 ((string-match-p "[\\*\\+-]\\|#\\." marker)
6144 (insert new-indent marker))))
6145 ;; Propertize the newly inserted list item now
6146 (markdown-syntax-propertize-list-items (point-at-bol) (point-at-eol)))))
6148 (defun markdown-move-list-item-up ()
6149 "Move the current list item up in the list when possible.
6150 In nested lists, move child items with the parent item."
6151 (interactive)
6152 (let (cur prev old)
6153 (when (setq cur (markdown-cur-list-item-bounds))
6154 (setq old (point))
6155 (goto-char (nth 0 cur))
6156 (if (markdown-prev-list-item (nth 3 cur))
6157 (progn
6158 (setq prev (markdown-cur-list-item-bounds))
6159 (condition-case nil
6160 (progn
6161 (transpose-regions (nth 0 prev) (nth 1 prev)
6162 (nth 0 cur) (nth 1 cur) t)
6163 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
6164 ;; Catch error in case regions overlap.
6165 (error (goto-char old))))
6166 (goto-char old)))))
6168 (defun markdown-move-list-item-down ()
6169 "Move the current list item down in the list when possible.
6170 In nested lists, move child items with the parent item."
6171 (interactive)
6172 (let (cur next old)
6173 (when (setq cur (markdown-cur-list-item-bounds))
6174 (setq old (point))
6175 (if (markdown-next-list-item (nth 3 cur))
6176 (progn
6177 (setq next (markdown-cur-list-item-bounds))
6178 (condition-case nil
6179 (progn
6180 (transpose-regions (nth 0 cur) (nth 1 cur)
6181 (nth 0 next) (nth 1 next) nil)
6182 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
6183 ;; Catch error in case regions overlap.
6184 (error (goto-char old))))
6185 (goto-char old)))))
6187 (defun markdown-demote-list-item (&optional bounds)
6188 "Indent (or demote) the current list item.
6189 Optionally, BOUNDS of the current list item may be provided if available.
6190 In nested lists, demote child items as well."
6191 (interactive)
6192 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6193 (save-excursion
6194 (let* ((item-start (set-marker (make-marker) (nth 0 bounds)))
6195 (item-end (set-marker (make-marker) (nth 1 bounds)))
6196 (list-start (progn (markdown-beginning-of-list)
6197 (set-marker (make-marker) (point))))
6198 (list-end (progn (markdown-end-of-list)
6199 (set-marker (make-marker) (point)))))
6200 (goto-char item-start)
6201 (while (< (point) item-end)
6202 (unless (markdown-cur-line-blank-p)
6203 (insert (make-string markdown-list-indent-width ? )))
6204 (forward-line))
6205 (markdown-syntax-propertize-list-items list-start list-end)))))
6207 (defun markdown-promote-list-item (&optional bounds)
6208 "Unindent (or promote) the current list item.
6209 Optionally, BOUNDS of the current list item may be provided if available.
6210 In nested lists, demote child items as well."
6211 (interactive)
6212 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6213 (save-excursion
6214 (save-match-data
6215 (let ((item-start (set-marker (make-marker) (nth 0 bounds)))
6216 (item-end (set-marker (make-marker) (nth 1 bounds)))
6217 (list-start (progn (markdown-beginning-of-list)
6218 (set-marker (make-marker) (point))))
6219 (list-end (progn (markdown-end-of-list)
6220 (set-marker (make-marker) (point))))
6221 num regexp)
6222 (goto-char item-start)
6223 (when (looking-at (format "^[ ]\\{1,%d\\}"
6224 markdown-list-indent-width))
6225 (setq num (- (match-end 0) (match-beginning 0)))
6226 (setq regexp (format "^[ ]\\{1,%d\\}" num))
6227 (while (and (< (point) item-end)
6228 (re-search-forward regexp item-end t))
6229 (replace-match "" nil nil)
6230 (forward-line))
6231 (markdown-syntax-propertize-list-items list-start list-end)))))))
6233 (defun markdown-cleanup-list-numbers-level (&optional pfx)
6234 "Update the numbering for level PFX (as a string of spaces).
6236 Assume that the previously found match was for a numbered item in
6237 a list."
6238 (let ((cpfx pfx)
6239 (idx 0)
6240 (continue t)
6241 (step t)
6242 (sep nil))
6243 (while (and continue (not (eobp)))
6244 (setq step t)
6245 (cond
6246 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
6247 (setq cpfx (match-string-no-properties 1))
6248 (cond
6249 ((string= cpfx pfx)
6250 (save-excursion
6251 (replace-match
6252 (concat pfx (number-to-string (setq idx (1+ idx))) ". ")))
6253 (setq sep nil))
6254 ;; indented a level
6255 ((string< pfx cpfx)
6256 (setq sep (markdown-cleanup-list-numbers-level cpfx))
6257 (setq step nil))
6258 ;; exit the loop
6260 (setq step nil)
6261 (setq continue nil))))
6263 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
6264 (setq cpfx (match-string-no-properties 1))
6265 (cond
6266 ;; reset if separated before
6267 ((string= cpfx pfx) (when sep (setq idx 0)))
6268 ((string< cpfx pfx)
6269 (setq step nil)
6270 (setq continue nil))))
6271 (t (setq sep t)))
6273 (when step
6274 (beginning-of-line)
6275 (setq continue (= (forward-line) 0))))
6276 sep))
6278 (defun markdown-cleanup-list-numbers ()
6279 "Update the numbering of ordered lists."
6280 (interactive)
6281 (save-excursion
6282 (goto-char (point-min))
6283 (markdown-cleanup-list-numbers-level "")))
6286 ;;; Movement ==================================================================
6288 (defun markdown-beginning-of-defun (&optional arg)
6289 "`beginning-of-defun-function' for Markdown.
6290 This is used to find the beginning of the defun and should behave
6291 like ‘beginning-of-defun’, returning non-nil if it found the
6292 beginning of a defun. It moves the point backward, right before a
6293 heading which defines a defun. When ARG is non-nil, repeat that
6294 many times. When ARG is negative, move forward to the ARG-th
6295 following section."
6296 (or arg (setq arg 1))
6297 (when (< arg 0) (end-of-line))
6298 ;; Adjust position for setext headings.
6299 (when (and (thing-at-point-looking-at markdown-regex-header-setext)
6300 (not (= (point) (match-beginning 0)))
6301 (not (markdown-code-block-at-point-p)))
6302 (goto-char (match-end 0)))
6303 (let (found)
6304 ;; Move backward with positive argument.
6305 (while (and (not (bobp)) (> arg 0))
6306 (setq found nil)
6307 (while (and (not found)
6308 (not (bobp))
6309 (re-search-backward markdown-regex-header nil 'move))
6310 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6311 (setq found (match-beginning 0)))
6312 (setq arg (1- arg)))
6313 ;; Move forward with negative argument.
6314 (while (and (not (eobp)) (< arg 0))
6315 (setq found nil)
6316 (while (and (not found)
6317 (not (eobp))
6318 (re-search-forward markdown-regex-header nil 'move))
6319 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6320 (setq found (match-beginning 0)))
6321 (setq arg (1+ arg)))
6322 (when found
6323 (beginning-of-line)
6324 t)))
6326 (defun markdown-end-of-defun ()
6327 "`end-of-defun-function’ for Markdown.
6328 This is used to find the end of the defun at point.
6329 It is called with no argument, right after calling ‘beginning-of-defun-raw’,
6330 so it can assume that point is at the beginning of the defun body.
6331 It should move point to the first position after the defun."
6332 (or (eobp) (forward-char 1))
6333 (let (found)
6334 (while (and (not found)
6335 (not (eobp))
6336 (re-search-forward markdown-regex-header nil 'move))
6337 (when (not (markdown-code-block-at-pos (match-beginning 0)))
6338 (setq found (match-beginning 0))))
6339 (when found
6340 (goto-char found)
6341 (skip-syntax-backward "-"))))
6343 (make-obsolete 'markdown-beginning-of-block 'markdown-beginning-of-text-block "v2.2")
6345 (defun markdown-beginning-of-text-block ()
6346 "Move backward to previous beginning of a plain text block.
6347 This function simply looks for blank lines without considering
6348 the surrounding context in light of Markdown syntax. For that, see
6349 `markdown-backward-block'."
6350 (interactive)
6351 (let ((start (point)))
6352 (if (re-search-backward markdown-regex-block-separator nil t)
6353 (goto-char (match-end 0))
6354 (goto-char (point-min)))
6355 (when (and (= start (point)) (not (bobp)))
6356 (forward-line -1)
6357 (if (re-search-backward markdown-regex-block-separator nil t)
6358 (goto-char (match-end 0))
6359 (goto-char (point-min))))))
6361 (make-obsolete 'markdown-end-of-block 'markdown-end-of-text-block "v2.2")
6363 (defun markdown-end-of-text-block ()
6364 "Move forward to next beginning of a plain text block.
6365 This function simply looks for blank lines without considering
6366 the surrounding context in light of Markdown syntax. For that, see
6367 `markdown-forward-block'."
6368 (interactive)
6369 (beginning-of-line)
6370 (skip-chars-forward " \t\n")
6371 (when (= (point) (point-min))
6372 (forward-char))
6373 (if (re-search-forward markdown-regex-block-separator nil t)
6374 (goto-char (match-end 0))
6375 (goto-char (point-max)))
6376 (skip-chars-backward " \t\n")
6377 (forward-line))
6379 (defun markdown-backward-paragraph (&optional arg)
6380 "Move the point to the start of the current paragraph.
6381 With argument ARG, do it ARG times; a negative argument ARG = -N
6382 means move forward N blocks."
6383 (interactive "^p")
6384 (or arg (setq arg 1))
6385 (if (< arg 0)
6386 (markdown-forward-paragraph (- arg))
6387 (dotimes (_ arg)
6388 ;; Skip over whitespace in between paragraphs when moving backward.
6389 (skip-chars-backward " \t\n")
6390 (beginning-of-line)
6391 ;; Skip over code block endings.
6392 (when (markdown-range-properties-exist
6393 (point-at-bol) (point-at-eol)
6394 '(markdown-gfm-block-end
6395 markdown-tilde-fence-end))
6396 (forward-line -1))
6397 ;; Skip over blank lines inside blockquotes.
6398 (while (and (not (eobp))
6399 (looking-at markdown-regex-blockquote)
6400 (= (length (match-string 3)) 0))
6401 (forward-line -1))
6402 ;; Proceed forward based on the type of block of paragraph.
6403 (let (bounds skip)
6404 (cond
6405 ;; Blockquotes
6406 ((looking-at markdown-regex-blockquote)
6407 (while (and (not (bobp))
6408 (looking-at markdown-regex-blockquote)
6409 (> (length (match-string 3)) 0)) ;; not blank
6410 (forward-line -1))
6411 (forward-line))
6412 ;; List items
6413 ((setq bounds (markdown-cur-list-item-bounds))
6414 (goto-char (nth 0 bounds)))
6415 ;; Other
6417 (while (and (not (bobp))
6418 (not skip)
6419 (not (markdown-cur-line-blank-p))
6420 (not (looking-at markdown-regex-blockquote))
6421 (not (markdown-range-properties-exist
6422 (point-at-bol) (point-at-eol)
6423 '(markdown-gfm-block-end
6424 markdown-tilde-fence-end))))
6425 (setq skip (markdown-range-properties-exist
6426 (point-at-bol) (point-at-eol)
6427 '(markdown-gfm-block-begin
6428 markdown-tilde-fence-begin)))
6429 (forward-line -1))
6430 (unless (bobp)
6431 (forward-line 1))))))))
6433 (defun markdown-forward-paragraph (&optional arg)
6434 "Move forward to the next end of a paragraph.
6435 With argument ARG, do it ARG times; a negative argument ARG = -N
6436 means move backward N blocks."
6437 (interactive "^p")
6438 (or arg (setq arg 1))
6439 (if (< arg 0)
6440 (markdown-backward-paragraph (- arg))
6441 (dotimes (_ arg)
6442 ;; Skip whitespace in between paragraphs.
6443 (when (markdown-cur-line-blank-p)
6444 (skip-syntax-forward "-")
6445 (beginning-of-line))
6446 ;; Proceed forward based on the type of block.
6447 (let (bounds skip)
6448 (cond
6449 ;; Blockquotes
6450 ((looking-at markdown-regex-blockquote)
6451 ;; Skip over blank lines inside blockquotes.
6452 (while (and (not (eobp))
6453 (looking-at markdown-regex-blockquote)
6454 (= (length (match-string 3)) 0))
6455 (forward-line))
6456 ;; Move to end of quoted text block
6457 (while (and (not (eobp))
6458 (looking-at markdown-regex-blockquote)
6459 (> (length (match-string 3)) 0)) ;; not blank
6460 (forward-line)))
6461 ;; List items
6462 ((and (markdown-cur-list-item-bounds)
6463 (setq bounds (markdown-next-list-item-bounds)))
6464 (goto-char (nth 0 bounds)))
6465 ;; Other
6467 (forward-line)
6468 (while (and (not (eobp))
6469 (not skip)
6470 (not (markdown-cur-line-blank-p))
6471 (not (looking-at markdown-regex-blockquote))
6472 (not (markdown-range-properties-exist
6473 (point-at-bol) (point-at-eol)
6474 '(markdown-gfm-block-begin
6475 markdown-tilde-fence-begin))))
6476 (setq skip (markdown-range-properties-exist
6477 (point-at-bol) (point-at-eol)
6478 '(markdown-gfm-block-end
6479 markdown-tilde-fence-end)))
6480 (forward-line))))))))
6482 (defun markdown-backward-block (&optional arg)
6483 "Move the point to the start of the current Markdown block.
6484 Moves across complete code blocks, list items, and blockquotes,
6485 but otherwise stops at blank lines, headers, and horizontal
6486 rules. With argument ARG, do it ARG times; a negative argument
6487 ARG = -N means move forward N blocks."
6488 (interactive "^p")
6489 (or arg (setq arg 1))
6490 (if (< arg 0)
6491 (markdown-forward-block (- arg))
6492 (dotimes (_ arg)
6493 ;; Skip over whitespace in between blocks when moving backward,
6494 ;; unless at a block boundary with no whitespace.
6495 (skip-syntax-backward "-")
6496 (beginning-of-line)
6497 ;; Proceed forward based on the type of block.
6498 (cond
6499 ;; Code blocks
6500 ((and (markdown-code-block-at-pos (point)) ;; this line
6501 (markdown-code-block-at-pos (point-at-bol 0))) ;; previous line
6502 (forward-line -1)
6503 (while (and (markdown-code-block-at-point-p) (not (bobp)))
6504 (forward-line -1))
6505 (forward-line))
6506 ;; Headings
6507 ((markdown-heading-at-point)
6508 (goto-char (match-beginning 0)))
6509 ;; Horizontal rules
6510 ((looking-at markdown-regex-hr))
6511 ;; Blockquotes
6512 ((looking-at markdown-regex-blockquote)
6513 (forward-line -1)
6514 (while (and (looking-at markdown-regex-blockquote)
6515 (not (bobp)))
6516 (forward-line -1))
6517 (forward-line))
6518 ;; List items
6519 ((markdown-cur-list-item-bounds)
6520 (markdown-beginning-of-list))
6521 ;; Other
6523 ;; Move forward in case it is a one line regular paragraph.
6524 (unless (markdown-next-line-blank-p)
6525 (forward-line))
6526 (unless (markdown-prev-line-blank-p)
6527 (markdown-backward-paragraph)))))))
6529 (defun markdown-forward-block (&optional arg)
6530 "Move forward to the next end of a Markdown block.
6531 Moves across complete code blocks, list items, and blockquotes,
6532 but otherwise stops at blank lines, headers, and horizontal
6533 rules. With argument ARG, do it ARG times; a negative argument
6534 ARG = -N means move backward N blocks."
6535 (interactive "^p")
6536 (or arg (setq arg 1))
6537 (if (< arg 0)
6538 (markdown-backward-block (- arg))
6539 (dotimes (_ arg)
6540 ;; Skip over whitespace in between blocks when moving forward.
6541 (if (markdown-cur-line-blank-p)
6542 (skip-syntax-forward "-")
6543 (beginning-of-line))
6544 ;; Proceed forward based on the type of block.
6545 (cond
6546 ;; Code blocks
6547 ((markdown-code-block-at-point-p)
6548 (forward-line)
6549 (while (and (markdown-code-block-at-point-p) (not (eobp)))
6550 (forward-line)))
6551 ;; Headings
6552 ((looking-at markdown-regex-header)
6553 (goto-char (or (match-end 4) (match-end 2) (match-end 3)))
6554 (forward-line))
6555 ;; Horizontal rules
6556 ((looking-at markdown-regex-hr)
6557 (forward-line))
6558 ;; Blockquotes
6559 ((looking-at markdown-regex-blockquote)
6560 (forward-line)
6561 (while (and (looking-at markdown-regex-blockquote) (not (eobp)))
6562 (forward-line)))
6563 ;; List items
6564 ((markdown-cur-list-item-bounds)
6565 (markdown-end-of-list)
6566 (forward-line))
6567 ;; Other
6568 (t (markdown-forward-paragraph))))
6569 (skip-syntax-backward "-")
6570 (unless (eobp)
6571 (forward-char 1))))
6573 (defun markdown-backward-page (&optional count)
6574 "Move backward to boundary of the current toplevel section.
6575 With COUNT, repeat, or go forward if negative."
6576 (interactive "p")
6577 (or count (setq count 1))
6578 (if (< count 0)
6579 (markdown-forward-page (- count))
6580 (skip-syntax-backward "-")
6581 (or (markdown-back-to-heading-over-code-block t t)
6582 (goto-char (point-min)))
6583 (when (looking-at markdown-regex-header)
6584 (let ((level (markdown-outline-level)))
6585 (when (> level 1) (markdown-up-heading level))
6586 (when (> count 1)
6587 (condition-case nil
6588 (markdown-backward-same-level (1- count))
6589 (error (goto-char (point-min)))))))))
6591 (defun markdown-forward-page (&optional count)
6592 "Move forward to boundary of the current toplevel section.
6593 With COUNT, repeat, or go backward if negative."
6594 (interactive "p")
6595 (or count (setq count 1))
6596 (if (< count 0)
6597 (markdown-backward-page (- count))
6598 (if (markdown-back-to-heading-over-code-block t t)
6599 (let ((level (markdown-outline-level)))
6600 (when (> level 1) (markdown-up-heading level))
6601 (condition-case nil
6602 (markdown-forward-same-level count)
6603 (error (goto-char (point-max)))))
6604 (markdown-next-visible-heading 1))))
6606 (defun markdown-next-link ()
6607 "Jump to next inline, reference, or wiki link.
6608 If successful, return point. Otherwise, return nil.
6609 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
6610 (interactive)
6611 (let ((opoint (point)))
6612 (when (or (markdown-link-p) (markdown-wiki-link-p))
6613 ;; At a link already, move past it.
6614 (goto-char (+ (match-end 0) 1)))
6615 ;; Search for the next wiki link and move to the beginning.
6616 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t)
6617 (markdown-code-block-at-point-p)
6618 (< (point) (point-max))))
6619 (if (and (not (eq (point) opoint))
6620 (or (markdown-link-p) (markdown-wiki-link-p)))
6621 ;; Group 1 will move past non-escape character in wiki link regexp.
6622 ;; Go to beginning of group zero for all other link types.
6623 (goto-char (or (match-beginning 1) (match-beginning 0)))
6624 (goto-char opoint)
6625 nil)))
6627 (defun markdown-previous-link ()
6628 "Jump to previous wiki link.
6629 If successful, return point. Otherwise, return nil.
6630 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
6631 (interactive)
6632 (let ((opoint (point)))
6633 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t)
6634 (markdown-code-block-at-point-p)
6635 (> (point) (point-min))))
6636 (if (and (not (eq (point) opoint))
6637 (or (markdown-link-p) (markdown-wiki-link-p)))
6638 (goto-char (or (match-beginning 1) (match-beginning 0)))
6639 (goto-char opoint)
6640 nil)))
6643 ;;; Outline ===================================================================
6645 (defun markdown-move-heading-common (move-fn &optional arg adjust)
6646 "Wrapper for `outline-mode' functions to skip false positives.
6647 MOVE-FN is a function and ARG is its argument. For example,
6648 headings inside preformatted code blocks may match
6649 `outline-regexp' but should not be considered as headings.
6650 When ADJUST is non-nil, adjust the point for interactive calls
6651 to avoid leaving the point at invisible markup. This adjustment
6652 generally should only be done for interactive calls, since other
6653 functions may expect the point to be at the beginning of the
6654 regular expression."
6655 (let ((prev -1) (start (point)))
6656 (if arg (funcall move-fn arg) (funcall move-fn))
6657 (while (and (/= prev (point)) (markdown-code-block-at-point-p))
6658 (setq prev (point))
6659 (if arg (funcall move-fn arg) (funcall move-fn)))
6660 ;; Adjust point for setext headings and invisible text.
6661 (save-match-data
6662 (when (and adjust (thing-at-point-looking-at markdown-regex-header))
6663 (if markdown-hide-markup
6664 ;; Move to beginning of heading text if markup is hidden.
6665 (goto-char (or (match-beginning 1) (match-beginning 5)))
6666 ;; Move to beginning of markup otherwise.
6667 (goto-char (or (match-beginning 1) (match-beginning 4))))))
6668 (if (= (point) start) nil (point))))
6670 (defun markdown-next-visible-heading (arg)
6671 "Move to the next visible heading line of any level.
6672 With argument, repeats or can move backward if negative. ARG is
6673 passed to `outline-next-visible-heading'."
6674 (interactive "p")
6675 (markdown-move-heading-common #'outline-next-visible-heading arg 'adjust))
6677 (defun markdown-previous-visible-heading (arg)
6678 "Move to the previous visible heading line of any level.
6679 With argument, repeats or can move backward if negative. ARG is
6680 passed to `outline-previous-visible-heading'."
6681 (interactive "p")
6682 (markdown-move-heading-common #'outline-previous-visible-heading arg 'adjust))
6684 (defun markdown-next-heading ()
6685 "Move to the next heading line of any level."
6686 (markdown-move-heading-common #'outline-next-heading))
6688 (defun markdown-previous-heading ()
6689 "Move to the previous heading line of any level."
6690 (markdown-move-heading-common #'outline-previous-heading))
6692 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok no-error)
6693 "Move back to the beginning of the previous heading.
6694 Returns t if the point is at a heading, the location if a heading
6695 was found, and nil otherwise.
6696 Only visible heading lines are considered, unless INVISIBLE-OK is
6697 non-nil. Throw an error if there is no previous heading unless
6698 NO-ERROR is non-nil.
6699 Leaves match data intact for `markdown-regex-header'."
6700 (beginning-of-line)
6701 (or (and (markdown-heading-at-point)
6702 (not (markdown-code-block-at-point-p)))
6703 (let (found)
6704 (save-excursion
6705 (while (and (not found)
6706 (re-search-backward markdown-regex-header nil t))
6707 (when (and (or invisible-ok (not (outline-invisible-p)))
6708 (not (markdown-code-block-at-point-p)))
6709 (setq found (point))))
6710 (if (not found)
6711 (unless no-error (user-error "Before first heading"))
6712 (setq found (point))))
6713 (when found (goto-char found)))))
6715 (defun markdown-forward-same-level (arg)
6716 "Move forward to the ARG'th heading at same level as this one.
6717 Stop at the first and last headings of a superior heading."
6718 (interactive "p")
6719 (markdown-back-to-heading-over-code-block)
6720 (markdown-move-heading-common #'outline-forward-same-level arg 'adjust))
6722 (defun markdown-backward-same-level (arg)
6723 "Move backward to the ARG'th heading at same level as this one.
6724 Stop at the first and last headings of a superior heading."
6725 (interactive "p")
6726 (markdown-back-to-heading-over-code-block)
6727 (while (> arg 0)
6728 (let ((point-to-move-to
6729 (save-excursion
6730 (markdown-move-heading-common #'outline-get-last-sibling nil 'adjust))))
6731 (if point-to-move-to
6732 (progn
6733 (goto-char point-to-move-to)
6734 (setq arg (1- arg)))
6735 (user-error "No previous same-level heading")))))
6737 (defun markdown-up-heading (arg)
6738 "Move to the visible heading line of which the present line is a subheading.
6739 With argument, move up ARG levels."
6740 (interactive "p")
6741 (and (called-interactively-p 'any)
6742 (not (eq last-command 'markdown-up-heading)) (push-mark))
6743 (markdown-move-heading-common #'outline-up-heading arg 'adjust))
6745 (defun markdown-back-to-heading (&optional invisible-ok)
6746 "Move to previous heading line, or beg of this line if it's a heading.
6747 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
6748 (markdown-move-heading-common #'outline-back-to-heading invisible-ok))
6750 (defalias 'markdown-end-of-heading 'outline-end-of-heading)
6752 (defun markdown-on-heading-p ()
6753 "Return non-nil if point is on a heading line."
6754 (get-text-property (point-at-bol) 'markdown-heading))
6756 (defun markdown-end-of-subtree (&optional invisible-OK)
6757 "Move to the end of the current subtree.
6758 Only visible heading lines are considered, unless INVISIBLE-OK is
6759 non-nil.
6760 Derived from `org-end-of-subtree'."
6761 (markdown-back-to-heading invisible-OK)
6762 (let ((first t)
6763 (level (markdown-outline-level)))
6764 (while (and (not (eobp))
6765 (or first (> (markdown-outline-level) level)))
6766 (setq first nil)
6767 (markdown-next-heading))
6768 (if (memq (preceding-char) '(?\n ?\^M))
6769 (progn
6770 ;; Go to end of line before heading
6771 (forward-char -1)
6772 (if (memq (preceding-char) '(?\n ?\^M))
6773 ;; leave blank line before heading
6774 (forward-char -1)))))
6775 (point))
6777 (defun markdown-outline-fix-visibility ()
6778 "Hide any false positive headings that should not be shown.
6779 For example, headings inside preformatted code blocks may match
6780 `outline-regexp' but should not be shown as headings when cycling.
6781 Also, the ending --- line in metadata blocks appears to be a
6782 setext header, but should not be folded."
6783 (save-excursion
6784 (goto-char (point-min))
6785 ;; Unhide any false positives in metadata blocks
6786 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin)
6787 (let ((body (progn (forward-line)
6788 (markdown-text-property-at-point
6789 'markdown-yaml-metadata-section))))
6790 (when body
6791 (let ((end (progn (goto-char (cl-second body))
6792 (markdown-text-property-at-point
6793 'markdown-yaml-metadata-end))))
6794 (outline-flag-region (point-min) (1+ (cl-second end)) nil)))))
6795 ;; Hide any false positives in code blocks
6796 (unless (outline-on-heading-p)
6797 (outline-next-visible-heading 1))
6798 (while (< (point) (point-max))
6799 (when (markdown-code-block-at-point-p)
6800 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t))
6801 (outline-next-visible-heading 1))))
6803 (defvar markdown-cycle-global-status 1)
6804 (defvar markdown-cycle-subtree-status nil)
6806 (defun markdown-next-preface ()
6807 (let (finish)
6808 (while (and (not finish) (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
6809 nil 'move))
6810 (unless (markdown-code-block-at-point-p)
6811 (goto-char (match-beginning 0))
6812 (setq finish t))))
6813 (when (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
6814 (forward-char -1)))
6816 (defun markdown-show-entry ()
6817 (save-excursion
6818 (outline-back-to-heading t)
6819 (outline-flag-region (1- (point))
6820 (progn
6821 (markdown-next-preface)
6822 (if (= 1 (- (point-max) (point)))
6823 (point-max)
6824 (point)))
6825 nil)))
6827 ;; This function was originally derived from `org-cycle' from org.el.
6828 (defun markdown-cycle (&optional arg)
6829 "Visibility cycling for Markdown mode.
6830 If ARG is t, perform global visibility cycling. If the point is
6831 at an atx-style header, cycle visibility of the corresponding
6832 subtree. Otherwise, indent the current line or insert a tab,
6833 as appropriate, by calling `indent-for-tab-command'."
6834 (interactive "P")
6835 (cond
6837 ;; Global cycling
6838 ((eq arg t)
6839 (cond
6840 ;; Move from overview to contents
6841 ((and (eq last-command this-command)
6842 (eq markdown-cycle-global-status 2))
6843 (markdown-hide-sublevels 1)
6844 (message "CONTENTS")
6845 (setq markdown-cycle-global-status 3)
6846 (markdown-outline-fix-visibility))
6847 ;; Move from contents to all
6848 ((and (eq last-command this-command)
6849 (eq markdown-cycle-global-status 3))
6850 (markdown-show-all)
6851 (message "SHOW ALL")
6852 (setq markdown-cycle-global-status 1))
6853 ;; Defaults to overview
6855 (markdown-hide-body)
6856 (message "OVERVIEW")
6857 (setq markdown-cycle-global-status 2)
6858 (markdown-outline-fix-visibility))))
6860 ;; At a heading: rotate between three different views
6861 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
6862 (markdown-back-to-heading)
6863 (let ((goal-column 0) eoh eol eos)
6864 ;; Determine boundaries
6865 (save-excursion
6866 (markdown-back-to-heading)
6867 (save-excursion
6868 (beginning-of-line 2)
6869 (while (and (not (eobp)) ;; this is like `next-line'
6870 (get-char-property (1- (point)) 'invisible))
6871 (beginning-of-line 2)) (setq eol (point)))
6872 (markdown-end-of-heading) (setq eoh (point))
6873 (markdown-end-of-subtree t)
6874 (skip-chars-forward " \t\n")
6875 (beginning-of-line 1) ; in case this is an item
6876 (setq eos (1- (point))))
6877 ;; Find out what to do next and set `this-command'
6878 (cond
6879 ;; Nothing is hidden behind this heading
6880 ((= eos eoh)
6881 (message "EMPTY ENTRY")
6882 (setq markdown-cycle-subtree-status nil))
6883 ;; Entire subtree is hidden in one line: open it
6884 ((>= eol eos)
6885 (markdown-show-entry)
6886 (markdown-show-children)
6887 (message "CHILDREN")
6888 (setq markdown-cycle-subtree-status 'children))
6889 ;; We just showed the children, now show everything.
6890 ((and (eq last-command this-command)
6891 (eq markdown-cycle-subtree-status 'children))
6892 (markdown-show-subtree)
6893 (message "SUBTREE")
6894 (setq markdown-cycle-subtree-status 'subtree))
6895 ;; Default action: hide the subtree.
6897 (markdown-hide-subtree)
6898 (message "FOLDED")
6899 (setq markdown-cycle-subtree-status 'folded)))))
6901 ;; In a table, move forward by one cell
6902 ((markdown-table-at-point-p)
6903 (call-interactively #'markdown-table-forward-cell))
6905 ;; Otherwise, indent as appropriate
6907 (indent-for-tab-command))))
6909 (defun markdown-shifttab ()
6910 "Handle S-TAB keybinding based on context.
6911 When in a table, move backward one cell.
6912 Otherwise, cycle global heading visibility by calling
6913 `markdown-cycle' with argument t."
6914 (interactive)
6915 (cond ((markdown-table-at-point-p)
6916 (call-interactively #'markdown-table-backward-cell))
6917 (t (markdown-cycle t))))
6919 (defun markdown-outline-level ()
6920 "Return the depth to which a statement is nested in the outline."
6921 (cond
6922 ((and (match-beginning 0)
6923 (markdown-code-block-at-pos (match-beginning 0)))
6924 7) ;; Only 6 header levels are defined.
6925 ((match-end 2) 1)
6926 ((match-end 3) 2)
6927 ((match-end 4)
6928 (length (markdown-trim-whitespace (match-string-no-properties 4))))))
6930 (defun markdown-promote-subtree (&optional arg)
6931 "Promote the current subtree of ATX headings.
6932 Note that Markdown does not support heading levels higher than
6933 six and therefore level-six headings will not be promoted
6934 further. If ARG is non-nil promote the heading, otherwise
6935 demote."
6936 (interactive "*P")
6937 (save-excursion
6938 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
6939 (re-search-backward markdown-regex-header-atx nil t))
6940 (not (markdown-code-block-at-point-p)))
6941 (let ((level (length (match-string 1)))
6942 (promote-or-demote (if arg 1 -1))
6943 (remove 't))
6944 (markdown-cycle-atx promote-or-demote remove)
6945 (catch 'end-of-subtree
6946 (while (and (markdown-next-heading)
6947 (looking-at markdown-regex-header-atx))
6948 ;; Exit if this not a higher level heading; promote otherwise.
6949 (if (and (looking-at markdown-regex-header-atx)
6950 (<= (length (match-string-no-properties 1)) level))
6951 (throw 'end-of-subtree nil)
6952 (markdown-cycle-atx promote-or-demote remove))))))))
6954 (defun markdown-demote-subtree ()
6955 "Demote the current subtree of ATX headings."
6956 (interactive)
6957 (markdown-promote-subtree t))
6959 (defun markdown-move-subtree-up ()
6960 "Move the current subtree of ATX headings up."
6961 (interactive)
6962 (outline-move-subtree-up 1))
6964 (defun markdown-move-subtree-down ()
6965 "Move the current subtree of ATX headings down."
6966 (interactive)
6967 (outline-move-subtree-down 1))
6969 (defun markdown-outline-next ()
6970 "Move to next list item, when in a list, or next visible heading."
6971 (interactive)
6972 (let ((bounds (markdown-next-list-item-bounds)))
6973 (if bounds
6974 (goto-char (nth 0 bounds))
6975 (markdown-next-visible-heading 1))))
6977 (defun markdown-outline-previous ()
6978 "Move to previous list item, when in a list, or previous visible heading."
6979 (interactive)
6980 (let ((bounds (markdown-prev-list-item-bounds)))
6981 (if bounds
6982 (goto-char (nth 0 bounds))
6983 (markdown-previous-visible-heading 1))))
6985 (defun markdown-outline-next-same-level ()
6986 "Move to next list item or heading of same level."
6987 (interactive)
6988 (let ((bounds (markdown-cur-list-item-bounds)))
6989 (if bounds
6990 (markdown-next-list-item (nth 3 bounds))
6991 (markdown-forward-same-level 1))))
6993 (defun markdown-outline-previous-same-level ()
6994 "Move to previous list item or heading of same level."
6995 (interactive)
6996 (let ((bounds (markdown-cur-list-item-bounds)))
6997 (if bounds
6998 (markdown-prev-list-item (nth 3 bounds))
6999 (markdown-backward-same-level 1))))
7001 (defun markdown-outline-up ()
7002 "Move to previous list item, when in a list, or next heading."
7003 (interactive)
7004 (unless (markdown-up-list)
7005 (markdown-up-heading 1)))
7008 ;;; Marking and Narrowing =====================================================
7010 (defun markdown-mark-paragraph ()
7011 "Put mark at end of this block, point at beginning.
7012 The block marked is the one that contains point or follows point.
7014 Interactively, if this command is repeated or (in Transient Mark
7015 mode) if the mark is active, it marks the next block after the
7016 ones already marked."
7017 (interactive)
7018 (if (or (and (eq last-command this-command) (mark t))
7019 (and transient-mark-mode mark-active))
7020 (set-mark
7021 (save-excursion
7022 (goto-char (mark))
7023 (markdown-forward-paragraph)
7024 (point)))
7025 (let ((beginning-of-defun-function 'markdown-backward-paragraph)
7026 (end-of-defun-function 'markdown-forward-paragraph))
7027 (mark-defun))))
7029 (defun markdown-mark-block ()
7030 "Put mark at end of this block, point at beginning.
7031 The block marked is the one that contains point or follows point.
7033 Interactively, if this command is repeated or (in Transient Mark
7034 mode) if the mark is active, it marks the next block after the
7035 ones already marked."
7036 (interactive)
7037 (if (or (and (eq last-command this-command) (mark t))
7038 (and transient-mark-mode mark-active))
7039 (set-mark
7040 (save-excursion
7041 (goto-char (mark))
7042 (markdown-forward-block)
7043 (point)))
7044 (let ((beginning-of-defun-function 'markdown-backward-block)
7045 (end-of-defun-function 'markdown-forward-block))
7046 (mark-defun))))
7048 (defun markdown-narrow-to-block ()
7049 "Make text outside current block invisible.
7050 The current block is the one that contains point or follows point."
7051 (interactive)
7052 (let ((beginning-of-defun-function 'markdown-backward-block)
7053 (end-of-defun-function 'markdown-forward-block))
7054 (narrow-to-defun)))
7056 (defun markdown-mark-text-block ()
7057 "Put mark at end of this plain text block, point at beginning.
7058 The block marked is the one that contains point or follows point.
7060 Interactively, if this command is repeated or (in Transient Mark
7061 mode) if the mark is active, it marks the next block after the
7062 ones already marked."
7063 (interactive)
7064 (if (or (and (eq last-command this-command) (mark t))
7065 (and transient-mark-mode mark-active))
7066 (set-mark
7067 (save-excursion
7068 (goto-char (mark))
7069 (markdown-end-of-text-block)
7070 (point)))
7071 (let ((beginning-of-defun-function 'markdown-beginning-of-text-block)
7072 (end-of-defun-function 'markdown-end-of-text-block))
7073 (mark-defun))))
7075 (defun markdown-mark-page ()
7076 "Put mark at end of this top level section, point at beginning.
7077 The top level section marked is the one that contains point or
7078 follows point.
7080 Interactively, if this command is repeated or (in Transient Mark
7081 mode) if the mark is active, it marks the next page after the
7082 ones already marked."
7083 (interactive)
7084 (if (or (and (eq last-command this-command) (mark t))
7085 (and transient-mark-mode mark-active))
7086 (set-mark
7087 (save-excursion
7088 (goto-char (mark))
7089 (markdown-forward-page)
7090 (point)))
7091 (let ((beginning-of-defun-function 'markdown-backward-page)
7092 (end-of-defun-function 'markdown-forward-page))
7093 (mark-defun))))
7095 (defun markdown-narrow-to-page ()
7096 "Make text outside current top level section invisible.
7097 The current section is the one that contains point or follows point."
7098 (interactive)
7099 (let ((beginning-of-defun-function 'markdown-backward-page)
7100 (end-of-defun-function 'markdown-forward-page))
7101 (narrow-to-defun)))
7103 (defun markdown-mark-subtree ()
7104 "Mark the current subtree.
7105 This puts point at the start of the current subtree, and mark at the end."
7106 (interactive)
7107 (let ((beg))
7108 (if (markdown-heading-at-point)
7109 (beginning-of-line)
7110 (markdown-previous-visible-heading 1))
7111 (setq beg (point))
7112 (markdown-end-of-subtree)
7113 (push-mark (point) nil t)
7114 (goto-char beg)))
7116 (defun markdown-narrow-to-subtree ()
7117 "Narrow buffer to the current subtree."
7118 (interactive)
7119 (save-excursion
7120 (save-match-data
7121 (narrow-to-region
7122 (progn (markdown-back-to-heading-over-code-block t) (point))
7123 (progn (markdown-end-of-subtree)
7124 (if (and (markdown-heading-at-point) (not (eobp)))
7125 (backward-char 1))
7126 (point))))))
7129 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
7131 (defun markdown-move-up ()
7132 "Move thing at point up.
7133 When in a list item, call `markdown-move-list-item-up'.
7134 When in a table, call `markdown-table-move-row-up'.
7135 Otherwise, move the current heading subtree up with
7136 `markdown-move-subtree-up'."
7137 (interactive)
7138 (cond
7139 ((markdown-list-item-at-point-p)
7140 (call-interactively #'markdown-move-list-item-up))
7141 ((markdown-table-at-point-p)
7142 (call-interactively #'markdown-table-move-row-up))
7144 (call-interactively #'markdown-move-subtree-up))))
7146 (defun markdown-move-down ()
7147 "Move thing at point down.
7148 When in a list item, call `markdown-move-list-item-down'.
7149 Otherwise, move the current heading subtree up with
7150 `markdown-move-subtree-down'."
7151 (interactive)
7152 (cond
7153 ((markdown-list-item-at-point-p)
7154 (call-interactively #'markdown-move-list-item-down))
7155 ((markdown-table-at-point-p)
7156 (call-interactively #'markdown-table-move-row-down))
7158 (call-interactively #'markdown-move-subtree-down))))
7160 (defun markdown-promote ()
7161 "Promote or move element at point to the left.
7162 Depending on the context, this function will promote a heading or
7163 list item at the point, move a table column to the left, or cycle
7164 markup."
7165 (interactive)
7166 (let (bounds)
7167 (cond
7168 ;; Promote atx heading subtree
7169 ((thing-at-point-looking-at markdown-regex-header-atx)
7170 (markdown-promote-subtree))
7171 ;; Promote setext heading
7172 ((thing-at-point-looking-at markdown-regex-header-setext)
7173 (markdown-cycle-setext -1))
7174 ;; Promote horizonal rule
7175 ((thing-at-point-looking-at markdown-regex-hr)
7176 (markdown-cycle-hr -1))
7177 ;; Promote list item
7178 ((setq bounds (markdown-cur-list-item-bounds))
7179 (markdown-promote-list-item bounds))
7180 ;; Move table column to the left
7181 ((markdown-table-at-point-p)
7182 (call-interactively #'markdown-table-move-column-left))
7183 ;; Promote bold
7184 ((thing-at-point-looking-at markdown-regex-bold)
7185 (markdown-cycle-bold))
7186 ;; Promote italic
7187 ((thing-at-point-looking-at markdown-regex-italic)
7188 (markdown-cycle-italic))
7190 (user-error "Nothing to promote at point")))))
7192 (defun markdown-demote ()
7193 "Demote or move element at point to the right.
7194 Depending on the context, this function will demote a heading or
7195 list item at the point, move a table column to the right, or cycle
7196 or remove markup."
7197 (interactive)
7198 (let (bounds)
7199 (cond
7200 ;; Demote atx heading subtree
7201 ((thing-at-point-looking-at markdown-regex-header-atx)
7202 (markdown-demote-subtree))
7203 ;; Demote setext heading
7204 ((thing-at-point-looking-at markdown-regex-header-setext)
7205 (markdown-cycle-setext 1))
7206 ;; Demote horizonal rule
7207 ((thing-at-point-looking-at markdown-regex-hr)
7208 (markdown-cycle-hr 1))
7209 ;; Demote list item
7210 ((setq bounds (markdown-cur-list-item-bounds))
7211 (markdown-demote-list-item bounds))
7212 ;; Move table column to the right
7213 ((markdown-table-at-point-p)
7214 (call-interactively #'markdown-table-move-column-right))
7215 ;; Demote bold
7216 ((thing-at-point-looking-at markdown-regex-bold)
7217 (markdown-cycle-bold))
7218 ;; Demote italic
7219 ((thing-at-point-looking-at markdown-regex-italic)
7220 (markdown-cycle-italic))
7222 (user-error "Nothing to demote at point")))))
7225 ;;; Commands ==================================================================
7227 (defun markdown (&optional output-buffer-name)
7228 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
7229 The output buffer name defaults to `markdown-output-buffer-name'.
7230 Return the name of the output buffer used."
7231 (interactive)
7232 (save-window-excursion
7233 (let ((begin-region)
7234 (end-region))
7235 (if (markdown-use-region-p)
7236 (setq begin-region (region-beginning)
7237 end-region (region-end))
7238 (setq begin-region (point-min)
7239 end-region (point-max)))
7241 (unless output-buffer-name
7242 (setq output-buffer-name markdown-output-buffer-name))
7243 (let ((exit-code
7244 (cond
7245 ;; Handle case when `markdown-command' does not read from stdin
7246 ((and (stringp markdown-command) markdown-command-needs-filename)
7247 (if (not buffer-file-name)
7248 (user-error "Must be visiting a file")
7249 ;; Don’t use ‘shell-command’ because it’s not guaranteed to
7250 ;; return the exit code of the process.
7251 (shell-command-on-region
7252 ;; Pass an empty region so that stdin is empty.
7253 (point) (point)
7254 (concat markdown-command " "
7255 (shell-quote-argument buffer-file-name))
7256 output-buffer-name)))
7257 ;; Pass region to `markdown-command' via stdin
7259 (let ((buf (get-buffer-create output-buffer-name)))
7260 (with-current-buffer buf
7261 (setq buffer-read-only nil)
7262 (erase-buffer))
7263 (if (stringp markdown-command)
7264 (call-process-region begin-region end-region
7265 shell-file-name nil buf nil
7266 shell-command-switch markdown-command)
7267 (funcall markdown-command begin-region end-region buf)
7268 ;; If the ‘markdown-command’ function didn’t signal an
7269 ;; error, assume it succeeded by binding ‘exit-code’ to 0.
7270 0))))))
7271 ;; The exit code can be a signal description string, so don’t use ‘=’
7272 ;; or ‘zerop’.
7273 (unless (eq exit-code 0)
7274 (user-error "%s failed with exit code %s"
7275 markdown-command exit-code))))
7276 output-buffer-name))
7278 (defun markdown-standalone (&optional output-buffer-name)
7279 "Special function to provide standalone HTML output.
7280 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
7281 (interactive)
7282 (setq output-buffer-name (markdown output-buffer-name))
7283 (with-current-buffer output-buffer-name
7284 (set-buffer output-buffer-name)
7285 (unless (markdown-output-standalone-p)
7286 (markdown-add-xhtml-header-and-footer output-buffer-name))
7287 (goto-char (point-min))
7288 (html-mode))
7289 output-buffer-name)
7291 (defun markdown-other-window (&optional output-buffer-name)
7292 "Run `markdown-command' on current buffer and display in other window.
7293 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7294 that name."
7295 (interactive)
7296 (markdown-display-buffer-other-window
7297 (markdown-standalone output-buffer-name)))
7299 (defun markdown-output-standalone-p ()
7300 "Determine whether `markdown-command' output is standalone XHTML.
7301 Standalone XHTML output is identified by an occurrence of
7302 `markdown-xhtml-standalone-regexp' in the first five lines of output."
7303 (save-excursion
7304 (goto-char (point-min))
7305 (save-match-data
7306 (re-search-forward
7307 markdown-xhtml-standalone-regexp
7308 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
7309 t))))
7311 (defun markdown-stylesheet-link-string (stylesheet-path)
7312 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
7313 stylesheet-path
7314 "\" />"))
7316 (defun markdown-add-xhtml-header-and-footer (title)
7317 "Wrap XHTML header and footer with given TITLE around current buffer."
7318 (goto-char (point-min))
7319 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
7320 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
7321 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
7322 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
7323 "<head>\n<title>")
7324 (insert title)
7325 (insert "</title>\n")
7326 (when (> (length markdown-content-type) 0)
7327 (insert
7328 (format
7329 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
7330 markdown-content-type
7331 (or (and markdown-coding-system
7332 (fboundp 'coding-system-get)
7333 (coding-system-get markdown-coding-system
7334 'mime-charset))
7335 (and (fboundp 'coding-system-get)
7336 (coding-system-get buffer-file-coding-system
7337 'mime-charset))
7338 "iso-8859-1"))))
7339 (if (> (length markdown-css-paths) 0)
7340 (insert (mapconcat #'markdown-stylesheet-link-string
7341 markdown-css-paths "\n")))
7342 (when (> (length markdown-xhtml-header-content) 0)
7343 (insert markdown-xhtml-header-content))
7344 (insert "\n</head>\n\n"
7345 "<body>\n\n")
7346 (when (> (length markdown-xhtml-body-preamble) 0)
7347 (insert markdown-xhtml-body-preamble "\n"))
7348 (goto-char (point-max))
7349 (when (> (length markdown-xhtml-body-epilogue) 0)
7350 (insert "\n" markdown-xhtml-body-epilogue))
7351 (insert "\n"
7352 "</body>\n"
7353 "</html>\n"))
7355 (defun markdown-preview (&optional output-buffer-name)
7356 "Run `markdown-command' on the current buffer and view output in browser.
7357 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7358 that name."
7359 (interactive)
7360 (browse-url-of-buffer
7361 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
7363 (defun markdown-export-file-name (&optional extension)
7364 "Attempt to generate a filename for Markdown output.
7365 The file extension will be EXTENSION if given, or .html by default.
7366 If the current buffer is visiting a file, we construct a new
7367 output filename based on that filename. Otherwise, return nil."
7368 (when (buffer-file-name)
7369 (unless extension
7370 (setq extension ".html"))
7371 (let ((candidate
7372 (concat
7373 (cond
7374 ((buffer-file-name)
7375 (file-name-sans-extension (buffer-file-name)))
7376 (t (buffer-name)))
7377 extension)))
7378 (cond
7379 ((equal candidate (buffer-file-name))
7380 (concat candidate extension))
7382 candidate)))))
7384 (defun markdown-export (&optional output-file)
7385 "Run Markdown on the current buffer, save to file, and return the filename.
7386 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
7387 generated by `markdown-export-file-name', which will be constructed using the
7388 current filename, but with the extension removed and replaced with .html."
7389 (interactive)
7390 (unless output-file
7391 (setq output-file (markdown-export-file-name ".html")))
7392 (when output-file
7393 (let* ((init-buf (current-buffer))
7394 (init-point (point))
7395 (init-buf-string (buffer-string))
7396 (output-buffer (find-file-noselect output-file))
7397 (output-buffer-name (buffer-name output-buffer)))
7398 (run-hooks 'markdown-before-export-hook)
7399 (markdown-standalone output-buffer-name)
7400 (with-current-buffer output-buffer
7401 (run-hooks 'markdown-after-export-hook)
7402 (save-buffer)
7403 (when markdown-export-kill-buffer (kill-buffer)))
7404 ;; if modified, restore initial buffer
7405 (when (buffer-modified-p init-buf)
7406 (erase-buffer)
7407 (insert init-buf-string)
7408 (save-buffer)
7409 (goto-char init-point))
7410 output-file)))
7412 (defun markdown-export-and-preview ()
7413 "Export to XHTML using `markdown-export' and browse the resulting file."
7414 (interactive)
7415 (browse-url-of-file (markdown-export)))
7417 (defvar markdown-live-preview-buffer nil
7418 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
7419 (make-variable-buffer-local 'markdown-live-preview-buffer)
7421 (defvar markdown-live-preview-source-buffer nil
7422 "Source buffer from which current buffer was generated.
7423 This is the inverse of `markdown-live-preview-buffer'.")
7424 (make-variable-buffer-local 'markdown-live-preview-source-buffer)
7426 (defvar markdown-live-preview-currently-exporting nil)
7428 (defun markdown-live-preview-get-filename ()
7429 "Standardize the filename exported by `markdown-live-preview-export'."
7430 (markdown-export-file-name ".html"))
7432 (defun markdown-live-preview-window-eww (file)
7433 "Preview FILE with eww.
7434 To be used with `markdown-live-preview-window-function'."
7435 (if (require 'eww nil t)
7436 (progn
7437 (eww-open-file file)
7438 (get-buffer "*eww*"))
7439 (error "EWW is not present or not loaded on this version of Emacs")))
7441 (defun markdown-visual-lines-between-points (beg end)
7442 (save-excursion
7443 (goto-char beg)
7444 (cl-loop with count = 0
7445 while (progn (end-of-visual-line)
7446 (and (< (point) end) (line-move-visual 1 t)))
7447 do (cl-incf count)
7448 finally return count)))
7450 (defun markdown-live-preview-window-serialize (buf)
7451 "Get window point and scroll data for all windows displaying BUF."
7452 (when (buffer-live-p buf)
7453 (with-current-buffer buf
7454 (mapcar
7455 (lambda (win)
7456 (with-selected-window win
7457 (let* ((start (window-start))
7458 (pt (window-point))
7459 (pt-or-sym (cond ((= pt (point-min)) 'min)
7460 ((= pt (point-max)) 'max)
7461 (t pt)))
7462 (diff (markdown-visual-lines-between-points
7463 start pt)))
7464 (list win pt-or-sym diff))))
7465 (get-buffer-window-list buf)))))
7467 (defun markdown-get-point-back-lines (pt num-lines)
7468 (save-excursion
7469 (goto-char pt)
7470 (line-move-visual (- num-lines) t)
7471 ;; in testing, can occasionally overshoot the number of lines to traverse
7472 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
7473 (when (> actual-num-lines num-lines)
7474 (line-move-visual (- actual-num-lines num-lines) t)))
7475 (point)))
7477 (defun markdown-live-preview-window-deserialize (window-posns)
7478 "Apply window point and scroll data from WINDOW-POSNS.
7479 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
7480 (cl-destructuring-bind (win pt-or-sym diff) window-posns
7481 (when (window-live-p win)
7482 (with-current-buffer markdown-live-preview-buffer
7483 (set-window-buffer win (current-buffer))
7484 (cl-destructuring-bind (actual-pt actual-diff)
7485 (cl-case pt-or-sym
7486 (min (list (point-min) 0))
7487 (max (list (point-max) diff))
7488 (t (list pt-or-sym diff)))
7489 (set-window-start
7490 win (markdown-get-point-back-lines actual-pt actual-diff))
7491 (set-window-point win actual-pt))))))
7493 (defun markdown-live-preview-export ()
7494 "Export to XHTML using `markdown-export'.
7495 Browse the resulting file within Emacs using
7496 `markdown-live-preview-window-function' Return the buffer
7497 displaying the rendered output."
7498 (interactive)
7499 (let ((filename (markdown-live-preview-get-filename)))
7500 (when filename
7501 (let* ((markdown-live-preview-currently-exporting t)
7502 (cur-buf (current-buffer))
7503 (export-file (markdown-export filename))
7504 ;; get positions in all windows currently displaying output buffer
7505 (window-data
7506 (markdown-live-preview-window-serialize
7507 markdown-live-preview-buffer)))
7508 (save-window-excursion
7509 (let ((output-buffer
7510 (funcall markdown-live-preview-window-function export-file)))
7511 (with-current-buffer output-buffer
7512 (setq markdown-live-preview-source-buffer cur-buf)
7513 (add-hook 'kill-buffer-hook
7514 #'markdown-live-preview-remove-on-kill t t))
7515 (with-current-buffer cur-buf
7516 (setq markdown-live-preview-buffer output-buffer))))
7517 (with-current-buffer cur-buf
7518 ;; reset all windows displaying output buffer to where they were,
7519 ;; now with the new output
7520 (mapc #'markdown-live-preview-window-deserialize window-data)
7521 ;; delete html editing buffer
7522 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
7523 (when (and export-file (file-exists-p export-file)
7524 (eq markdown-live-preview-delete-export
7525 'delete-on-export))
7526 (delete-file export-file))
7527 markdown-live-preview-buffer)))))
7529 (defun markdown-live-preview-remove ()
7530 (when (buffer-live-p markdown-live-preview-buffer)
7531 (kill-buffer markdown-live-preview-buffer))
7532 (setq markdown-live-preview-buffer nil)
7533 ;; if set to 'delete-on-export, the output has already been deleted
7534 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
7535 (let ((outfile-name (markdown-live-preview-get-filename)))
7536 (when (and outfile-name (file-exists-p outfile-name))
7537 (delete-file outfile-name)))))
7539 (defun markdown-get-other-window ()
7540 "Find another window to display preview or output content."
7541 (cond
7542 ((memq markdown-split-window-direction '(vertical below))
7543 (or (window-in-direction 'below) (split-window-vertically)))
7544 ((memq markdown-split-window-direction '(horizontal right))
7545 (or (window-in-direction 'right) (split-window-horizontally)))
7546 (t (split-window-sensibly (get-buffer-window)))))
7548 (defun markdown-display-buffer-other-window (buf)
7549 "Display preview or output buffer BUF in another window."
7550 (let ((cur-buf (current-buffer))
7551 (window (markdown-get-other-window)))
7552 (set-window-buffer window buf)
7553 (set-buffer cur-buf)))
7555 (defun markdown-live-preview-if-markdown ()
7556 (when (and (derived-mode-p 'markdown-mode)
7557 markdown-live-preview-mode)
7558 (unless markdown-live-preview-currently-exporting
7559 (if (buffer-live-p markdown-live-preview-buffer)
7560 (markdown-live-preview-export)
7561 (markdown-display-buffer-other-window
7562 (markdown-live-preview-export))))))
7564 (defun markdown-live-preview-remove-on-kill ()
7565 (cond ((and (derived-mode-p 'markdown-mode)
7566 markdown-live-preview-mode)
7567 (markdown-live-preview-remove))
7568 (markdown-live-preview-source-buffer
7569 (with-current-buffer markdown-live-preview-source-buffer
7570 (setq markdown-live-preview-buffer nil))
7571 (setq markdown-live-preview-source-buffer nil))))
7573 (defun markdown-live-preview-switch-to-output ()
7574 "Switch to output buffer."
7575 (interactive)
7576 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
7577 output buffer in another window."
7578 (if markdown-live-preview-mode
7579 (markdown-display-buffer-other-window (markdown-live-preview-export)))
7580 (markdown-live-preview-mode))
7582 (defun markdown-live-preview-re-export ()
7583 "Re export source buffer."
7584 (interactive)
7585 "If the current buffer is a buffer displaying the exported version of a
7586 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
7587 update this buffer's contents."
7588 (when markdown-live-preview-source-buffer
7589 (with-current-buffer markdown-live-preview-source-buffer
7590 (markdown-live-preview-export))))
7592 (defun markdown-open ()
7593 "Open file for the current buffer with `markdown-open-command'."
7594 (interactive)
7595 (unless markdown-open-command
7596 (user-error "Variable `markdown-open-command' must be set"))
7597 (if (stringp markdown-open-command)
7598 (if (not buffer-file-name)
7599 (user-error "Must be visiting a file")
7600 (save-buffer)
7601 (let ((exit-code (call-process markdown-open-command nil nil nil
7602 buffer-file-name)))
7603 ;; The exit code can be a signal description string, so don’t use ‘=’
7604 ;; or ‘zerop’.
7605 (unless (eq exit-code 0)
7606 (user-error "%s failed with exit code %s"
7607 markdown-open-command exit-code))))
7608 (funcall markdown-open-command))
7609 nil)
7611 (defun markdown-kill-ring-save ()
7612 "Run Markdown on file and store output in the kill ring."
7613 (interactive)
7614 (save-window-excursion
7615 (markdown)
7616 (with-current-buffer markdown-output-buffer-name
7617 (kill-ring-save (point-min) (point-max)))))
7620 ;;; Links =====================================================================
7622 (defun markdown-link-p ()
7623 "Return non-nil when `point' is at a non-wiki link.
7624 See `markdown-wiki-link-p' for more information."
7625 (let ((case-fold-search nil))
7626 (and (not (markdown-wiki-link-p))
7627 (not (markdown-code-block-at-point-p))
7628 (or (thing-at-point-looking-at markdown-regex-link-inline)
7629 (thing-at-point-looking-at markdown-regex-link-reference)
7630 (thing-at-point-looking-at markdown-regex-uri)
7631 (thing-at-point-looking-at markdown-regex-angle-uri)))))
7633 (make-obsolete 'markdown-link-link 'markdown-link-url "v2.3")
7635 (defun markdown-link-at-pos (pos)
7636 "Return properties of link or image at position POS.
7637 Value is a list of elements describing the link:
7638 0. beginning position
7639 1. end position
7640 2. link text
7641 3. URL
7642 4. reference label
7643 5. title text
7644 6. bang (nil or \"!\")"
7645 (save-excursion
7646 (goto-char pos)
7647 (let (begin end text url reference title bang)
7648 (cond
7649 ;; Inline or reference image or link at point.
7650 ((or (thing-at-point-looking-at markdown-regex-link-inline)
7651 (thing-at-point-looking-at markdown-regex-link-reference))
7652 (setq bang (match-string-no-properties 1)
7653 begin (match-beginning 0)
7654 end (match-end 0)
7655 text (match-string-no-properties 3))
7656 (if (char-equal (char-after (match-beginning 5)) ?\[)
7657 ;; Reference link
7658 (setq reference (match-string-no-properties 6))
7659 ;; Inline link
7660 (setq url (match-string-no-properties 6))
7661 (when (match-end 7)
7662 (setq title (substring (match-string-no-properties 7) 1 -1)))))
7663 ;; Angle bracket URI at point.
7664 ((thing-at-point-looking-at markdown-regex-angle-uri)
7665 (setq begin (match-beginning 0)
7666 end (match-end 0)
7667 url (match-string-no-properties 2)))
7668 ;; Plain URI at point.
7669 ((thing-at-point-looking-at markdown-regex-uri)
7670 (setq begin (match-beginning 0)
7671 end (match-end 0)
7672 url (match-string-no-properties 1))))
7673 (list begin end text url reference title bang))))
7675 (defun markdown-link-url ()
7676 "Return the URL part of the regular (non-wiki) link at point.
7677 Works with both inline and reference style links, and with images.
7678 If point is not at a link or the link reference is not defined
7679 returns nil."
7680 (let* ((values (markdown-link-at-pos (point)))
7681 (text (nth 2 values))
7682 (url (nth 3 values))
7683 (ref (nth 4 values)))
7684 (or url (and ref (car (markdown-reference-definition
7685 (downcase (if (string= ref "") text ref))))))))
7687 (defun markdown-follow-link-at-point ()
7688 "Open the current non-wiki link.
7689 If the link is a complete URL, open in browser with `browse-url'.
7690 Otherwise, open with `find-file' after stripping anchor and/or query string.
7691 Translate filenames using `markdown-filename-translate-function'."
7692 (interactive)
7693 (if (markdown-link-p)
7694 (let* ((url (markdown-link-url))
7695 (struct (url-generic-parse-url url))
7696 (full (url-fullness struct))
7697 (file url))
7698 ;; Parse URL, determine fullness, strip query string
7699 (if (fboundp 'url-path-and-query)
7700 (setq file (car (url-path-and-query struct)))
7701 (when (and (setq file (url-filename struct))
7702 (string-match "\\?" file))
7703 (setq file (substring file 0 (match-beginning 0)))))
7704 ;; Open full URLs in browser, files in Emacs
7705 (if full
7706 (browse-url url)
7707 (when (and file (> (length file) 0))
7708 (find-file (funcall markdown-translate-filename-function file)))))
7709 (user-error "Point is not at a Markdown link or URL")))
7711 (defun markdown-fontify-inline-links (last)
7712 "Add text properties to next inline link from point to LAST."
7713 (when (markdown-match-generic-links last nil)
7714 (let* ((link-start (match-beginning 3))
7715 (link-end (match-end 3))
7716 (url-start (match-beginning 6))
7717 (url-end (match-end 6))
7718 (url (match-string-no-properties 6))
7719 (title-start (match-beginning 7))
7720 (title-end (match-end 7))
7721 (title (match-string-no-properties 7))
7722 ;; Markup part
7723 (mp (list 'face 'markdown-markup-face
7724 'invisible 'markdown-markup
7725 'rear-nonsticky t
7726 'font-lock-multiline t))
7727 ;; Link part (without face)
7728 (lp (list 'keymap markdown-mode-mouse-map
7729 'mouse-face 'markdown-highlight-face
7730 'font-lock-multiline t
7731 'help-echo (if title (concat title "\n" url) url)))
7732 ;; URL part
7733 (up (list 'keymap markdown-mode-mouse-map
7734 'face 'markdown-url-face
7735 'invisible 'markdown-markup
7736 'mouse-face 'markdown-highlight-face
7737 'font-lock-multiline t))
7738 ;; URL composition character
7739 (url-char (markdown--first-displayable markdown-url-compose-char))
7740 ;; Title part
7741 (tp (list 'face 'markdown-link-title-face
7742 'invisible 'markdown-markup
7743 'font-lock-multiline t)))
7744 (dolist (g '(1 2 4 5 8))
7745 (when (match-end g)
7746 (add-text-properties (match-beginning g) (match-end g) mp)))
7747 ;; Preserve existing faces applied to link part (e.g., inline code)
7748 (when link-start
7749 (add-text-properties link-start link-end lp)
7750 (add-face-text-property link-start link-end
7751 'markdown-link-face 'append))
7752 (when url-start (add-text-properties url-start url-end up))
7753 (when title-start (add-text-properties url-end title-end tp))
7754 (when (and markdown-hide-urls url-start)
7755 (compose-region url-start (or title-end url-end) url-char))
7756 t)))
7758 (defun markdown-fontify-reference-links (last)
7759 "Add text properties to next reference link from point to LAST."
7760 (when (markdown-match-generic-links last t)
7761 (let* ((link-start (match-beginning 3))
7762 (link-end (match-end 3))
7763 (ref-start (match-beginning 6))
7764 (ref-end (match-end 6))
7765 ;; Markup part
7766 (mp (list 'face 'markdown-markup-face
7767 'invisible 'markdown-markup
7768 'rear-nonsticky t
7769 'font-lock-multiline t))
7770 ;; Link part
7771 (lp (list 'keymap markdown-mode-mouse-map
7772 'face 'markdown-link-face
7773 'mouse-face 'markdown-highlight-face
7774 'font-lock-multiline t
7775 'help-echo (lambda (_ __ pos)
7776 (save-match-data
7777 (save-excursion
7778 (goto-char pos)
7779 (or (markdown-link-url)
7780 "Undefined reference"))))))
7781 ;; URL composition character
7782 (url-char (markdown--first-displayable markdown-url-compose-char))
7783 ;; Reference part
7784 (rp (list 'face 'markdown-reference-face
7785 'invisible 'markdown-markup
7786 'font-lock-multiline t)))
7787 (dolist (g '(1 2 4 5 8))
7788 (when (match-end g)
7789 (add-text-properties (match-beginning g) (match-end g) mp)))
7790 (when link-start (add-text-properties link-start link-end lp))
7791 (when ref-start (add-text-properties ref-start ref-end rp)
7792 (when (and markdown-hide-urls (> (- ref-end ref-start) 2))
7793 (compose-region ref-start ref-end url-char)))
7794 t)))
7796 (defun markdown-fontify-angle-uris (last)
7797 "Add text properties to angle URIs from point to LAST."
7798 (when (markdown-match-angle-uris last)
7799 (let* ((url-start (match-beginning 2))
7800 (url-end (match-end 2))
7801 ;; Markup part
7802 (mp (list 'face 'markdown-markup-face
7803 'invisible 'markdown-markup
7804 'rear-nonsticky t
7805 'font-lock-multiline t))
7806 ;; URI part
7807 (up (list 'keymap markdown-mode-mouse-map
7808 'face 'markdown-plain-url-face
7809 'mouse-face 'markdown-highlight-face
7810 'font-lock-multiline t)))
7811 (dolist (g '(1 3))
7812 (add-text-properties (match-beginning g) (match-end g) mp))
7813 (add-text-properties url-start url-end up)
7814 t)))
7816 (defun markdown-fontify-plain-uris (last)
7817 "Add text properties to plain URLs from point to LAST."
7818 (when (markdown-match-plain-uris last)
7819 (let* ((start (match-beginning 0))
7820 (end (match-end 0))
7821 (props (list 'keymap markdown-mode-mouse-map
7822 'face 'markdown-plain-url-face
7823 'mouse-face 'markdown-highlight-face
7824 'rear-nonsticky t
7825 'font-lock-multiline t)))
7826 (add-text-properties start end props)
7827 t)))
7829 (defun markdown-toggle-url-hiding (&optional arg)
7830 "Toggle the display or hiding of URLs.
7831 With a prefix argument ARG, enable URL hiding if ARG is positive,
7832 and disable it otherwise."
7833 (interactive (list (or current-prefix-arg 'toggle)))
7834 (setq markdown-hide-urls
7835 (if (eq arg 'toggle)
7836 (not markdown-hide-urls)
7837 (> (prefix-numeric-value arg) 0)))
7838 (if markdown-hide-urls
7839 (message "markdown-mode URL hiding enabled")
7840 (message "markdown-mode URL hiding disabled"))
7841 (markdown-reload-extensions))
7844 ;;; Wiki Links ================================================================
7846 (defun markdown-wiki-link-p ()
7847 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
7848 A true wiki link name matches `markdown-regex-wiki-link' but does
7849 not match the current file name after conversion. This modifies
7850 the data returned by `match-data'. Note that the potential wiki
7851 link name must be available via `match-string'."
7852 (when markdown-enable-wiki-links
7853 (let ((case-fold-search nil))
7854 (and (thing-at-point-looking-at markdown-regex-wiki-link)
7855 (not (markdown-code-block-at-point-p))
7856 (or (not buffer-file-name)
7857 (not (string-equal (buffer-file-name)
7858 (markdown-convert-wiki-link-to-filename
7859 (markdown-wiki-link-link)))))))))
7861 (defun markdown-wiki-link-link ()
7862 "Return the link part of the wiki link using current match data.
7863 The location of the link component depends on the value of
7864 `markdown-wiki-link-alias-first'."
7865 (if markdown-wiki-link-alias-first
7866 (or (match-string-no-properties 5) (match-string-no-properties 3))
7867 (match-string-no-properties 3)))
7869 (defun markdown-wiki-link-alias ()
7870 "Return the alias or text part of the wiki link using current match data.
7871 The location of the alias component depends on the value of
7872 `markdown-wiki-link-alias-first'."
7873 (if markdown-wiki-link-alias-first
7874 (match-string-no-properties 3)
7875 (or (match-string-no-properties 5) (match-string-no-properties 3))))
7877 (defun markdown-convert-wiki-link-to-filename (name)
7878 "Generate a filename from the wiki link NAME.
7879 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
7880 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
7881 and [[test test]] both map to Test-test.ext. Look in the current
7882 directory first, then in subdirectories if
7883 `markdown-wiki-link-search-subdirectories' is non-nil, and then
7884 in parent directories if
7885 `markdown-wiki-link-search-parent-directories' is non-nil."
7886 (let* ((basename (markdown-replace-regexp-in-string
7887 "[[:space:]\n]" markdown-link-space-sub-char name))
7888 (basename (if (memq major-mode '(gfm-mode gfm-view-mode))
7889 (concat (upcase (substring basename 0 1))
7890 (downcase (substring basename 1 nil)))
7891 basename))
7892 directory extension default candidates dir)
7893 (when buffer-file-name
7894 (setq directory (file-name-directory buffer-file-name)
7895 extension (file-name-extension buffer-file-name)))
7896 (setq default (concat basename
7897 (when extension (concat "." extension))))
7898 (cond
7899 ;; Look in current directory first.
7900 ((or (null buffer-file-name)
7901 (file-exists-p default))
7902 default)
7903 ;; Possibly search in subdirectories, next.
7904 ((and markdown-wiki-link-search-subdirectories
7905 (setq candidates
7906 (markdown-directory-files-recursively
7907 directory (concat "^" default "$"))))
7908 (car candidates))
7909 ;; Possibly search in parent directories as a last resort.
7910 ((and markdown-wiki-link-search-parent-directories
7911 (setq dir (locate-dominating-file directory default)))
7912 (concat dir default))
7913 ;; If nothing is found, return default in current directory.
7914 (t default))))
7916 (defun markdown-follow-wiki-link (name &optional other)
7917 "Follow the wiki link NAME.
7918 Convert the name to a file name and call `find-file'. Ensure that
7919 the new buffer remains in `markdown-mode'. Open the link in another
7920 window when OTHER is non-nil."
7921 (let ((filename (markdown-convert-wiki-link-to-filename name))
7922 (wp (when buffer-file-name
7923 (file-name-directory buffer-file-name))))
7924 (if (not wp)
7925 (user-error "Must be visiting a file")
7926 (when other (other-window 1))
7927 (let ((default-directory wp))
7928 (find-file filename)))
7929 (when (not (eq major-mode 'markdown-mode))
7930 (markdown-mode))))
7932 (defun markdown-follow-wiki-link-at-point (&optional arg)
7933 "Find Wiki Link at point.
7934 With prefix argument ARG, open the file in other window.
7935 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
7936 (interactive "P")
7937 (if (markdown-wiki-link-p)
7938 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
7939 (user-error "Point is not at a Wiki Link")))
7941 (defun markdown-highlight-wiki-link (from to face)
7942 "Highlight the wiki link in the region between FROM and TO using FACE."
7943 (put-text-property from to 'font-lock-face face))
7945 (defun markdown-unfontify-region-wiki-links (from to)
7946 "Remove wiki link faces from the region specified by FROM and TO."
7947 (interactive "*r")
7948 (let ((modified (buffer-modified-p)))
7949 (remove-text-properties from to '(font-lock-face markdown-link-face))
7950 (remove-text-properties from to '(font-lock-face markdown-missing-link-face))
7951 ;; remove-text-properties marks the buffer modified in emacs 24.3,
7952 ;; undo that if it wasn't originally marked modified
7953 (set-buffer-modified-p modified)))
7955 (defun markdown-fontify-region-wiki-links (from to)
7956 "Search region given by FROM and TO for wiki links and fontify them.
7957 If a wiki link is found check to see if the backing file exists
7958 and highlight accordingly."
7959 (goto-char from)
7960 (save-match-data
7961 (while (re-search-forward markdown-regex-wiki-link to t)
7962 (when (not (markdown-code-block-at-point-p))
7963 (let ((highlight-beginning (match-beginning 1))
7964 (highlight-end (match-end 1))
7965 (file-name
7966 (markdown-convert-wiki-link-to-filename
7967 (markdown-wiki-link-link))))
7968 (if (condition-case nil (file-exists-p file-name) (error nil))
7969 (markdown-highlight-wiki-link
7970 highlight-beginning highlight-end 'markdown-link-face)
7971 (markdown-highlight-wiki-link
7972 highlight-beginning highlight-end 'markdown-missing-link-face)))))))
7974 (defun markdown-extend-changed-region (from to)
7975 "Extend region given by FROM and TO so that we can fontify all links.
7976 The region is extended to the first newline before and the first
7977 newline after."
7978 ;; start looking for the first new line before 'from
7979 (goto-char from)
7980 (re-search-backward "\n" nil t)
7981 (let ((new-from (point-min))
7982 (new-to (point-max)))
7983 (if (not (= (point) from))
7984 (setq new-from (point)))
7985 ;; do the same thing for the first new line after 'to
7986 (goto-char to)
7987 (re-search-forward "\n" nil t)
7988 (if (not (= (point) to))
7989 (setq new-to (point)))
7990 (cl-values new-from new-to)))
7992 (defun markdown-check-change-for-wiki-link (from to)
7993 "Check region between FROM and TO for wiki links and re-fontify as needed."
7994 (interactive "*r")
7995 (let* ((modified (buffer-modified-p))
7996 (buffer-undo-list t)
7997 (inhibit-read-only t)
7998 (inhibit-point-motion-hooks t)
7999 deactivate-mark
8000 buffer-file-truename)
8001 (unwind-protect
8002 (save-excursion
8003 (save-match-data
8004 (save-restriction
8005 ;; Extend the region to fontify so that it starts
8006 ;; and ends at safe places.
8007 (cl-multiple-value-bind (new-from new-to)
8008 (markdown-extend-changed-region from to)
8009 (goto-char new-from)
8010 ;; Only refontify when the range contains text with a
8011 ;; wiki link face or if the wiki link regexp matches.
8012 (when (or (markdown-range-property-any
8013 new-from new-to 'font-lock-face
8014 '(markdown-link-face markdown-missing-link-face))
8015 (re-search-forward
8016 markdown-regex-wiki-link new-to t))
8017 ;; Unfontify existing fontification (start from scratch)
8018 (markdown-unfontify-region-wiki-links new-from new-to)
8019 ;; Now do the fontification.
8020 (markdown-fontify-region-wiki-links new-from new-to))))))
8021 (and (not modified)
8022 (buffer-modified-p)
8023 (set-buffer-modified-p nil)))))
8025 (defun markdown-check-change-for-wiki-link-after-change (from to _)
8026 "Check region between FROM and TO for wiki links and re-fontify as needed.
8027 Designed to be used with the `after-change-functions' hook."
8028 (markdown-check-change-for-wiki-link from to))
8030 (defun markdown-fontify-buffer-wiki-links ()
8031 "Refontify all wiki links in the buffer."
8032 (interactive)
8033 (markdown-check-change-for-wiki-link (point-min) (point-max)))
8035 (defun markdown-toggle-wiki-links (&optional arg)
8036 "Toggle support for wiki links.
8037 With a prefix argument ARG, enable wiki link support if ARG is positive,
8038 and disable it otherwise."
8039 (interactive (list (or current-prefix-arg 'toggle)))
8040 (setq markdown-enable-wiki-links
8041 (if (eq arg 'toggle)
8042 (not markdown-enable-wiki-links)
8043 (> (prefix-numeric-value arg) 0)))
8044 (if markdown-enable-wiki-links
8045 (message "markdown-mode wiki link support enabled")
8046 (message "markdown-mode wiki link support disabled"))
8047 (markdown-reload-extensions))
8049 (defun markdown-setup-wiki-link-hooks ()
8050 "Add or remove hooks for fontifying wiki links.
8051 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
8052 ;; Anytime text changes make sure it gets fontified correctly
8053 (if (and markdown-enable-wiki-links
8054 markdown-wiki-link-fontify-missing)
8055 (add-hook 'after-change-functions
8056 'markdown-check-change-for-wiki-link-after-change t t)
8057 (remove-hook 'after-change-functions
8058 'markdown-check-change-for-wiki-link-after-change t))
8059 ;; If we left the buffer there is a really good chance we were
8060 ;; creating one of the wiki link documents. Make sure we get
8061 ;; refontified when we come back.
8062 (if (and markdown-enable-wiki-links
8063 markdown-wiki-link-fontify-missing)
8064 (progn
8065 (add-hook 'window-configuration-change-hook
8066 'markdown-fontify-buffer-wiki-links t t)
8067 (markdown-fontify-buffer-wiki-links))
8068 (remove-hook 'window-configuration-change-hook
8069 'markdown-fontify-buffer-wiki-links t)
8070 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
8073 ;;; Following & Doing =========================================================
8075 (defun markdown-follow-thing-at-point (arg)
8076 "Follow thing at point if possible, such as a reference link or wiki link.
8077 Opens inline and reference links in a browser. Opens wiki links
8078 to other files in the current window, or the another window if
8079 ARG is non-nil.
8080 See `markdown-follow-link-at-point' and
8081 `markdown-follow-wiki-link-at-point'."
8082 (interactive "P")
8083 (cond ((markdown-link-p)
8084 (markdown-follow-link-at-point))
8085 ((markdown-wiki-link-p)
8086 (markdown-follow-wiki-link-at-point arg))
8088 (user-error "Nothing to follow at point"))))
8090 (make-obsolete 'markdown-jump 'markdown-do "v2.3")
8092 (defun markdown-do ()
8093 "Do something sensible based on context at point.
8094 Jumps between reference links and definitions; between footnote
8095 markers and footnote text."
8096 (interactive)
8097 (cond
8098 ;; Footnote definition
8099 ((markdown-footnote-text-positions)
8100 (markdown-footnote-return))
8101 ;; Footnote marker
8102 ((markdown-footnote-marker-positions)
8103 (markdown-footnote-goto-text))
8104 ;; Reference link
8105 ((thing-at-point-looking-at markdown-regex-link-reference)
8106 (markdown-reference-goto-definition))
8107 ;; Reference definition
8108 ((thing-at-point-looking-at markdown-regex-reference-definition)
8109 (markdown-reference-goto-link (match-string-no-properties 2)))
8110 ;; GFM task list item
8111 ((markdown-gfm-task-list-item-at-point)
8112 (markdown-toggle-gfm-checkbox))
8113 ;; Align table
8114 ((markdown-table-at-point-p)
8115 (call-interactively #'markdown-table-align))
8116 ;; Otherwise
8118 (markdown-insert-gfm-checkbox))))
8121 ;;; Miscellaneous =============================================================
8123 (defun markdown-compress-whitespace-string (str)
8124 "Compress whitespace in STR and return result.
8125 Leading and trailing whitespace is removed. Sequences of multiple
8126 spaces, tabs, and newlines are replaced with single spaces."
8127 (markdown-replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
8128 (markdown-replace-regexp-in-string "[ \t\n]+" " " str)))
8130 (defun markdown--substitute-command-keys (string)
8131 "Like `substitute-command-keys' but, but prefers control characters.
8132 First pass STRING to `substitute-command-keys' and then
8133 substitute `C-i` for `TAB` and `C-m` for `RET`."
8134 (replace-regexp-in-string
8135 "\\<TAB\\>" "C-i"
8136 (replace-regexp-in-string
8137 "\\<RET\\>" "C-m" (substitute-command-keys string) t) t))
8139 (defun markdown-line-number-at-pos (&optional pos)
8140 "Return (narrowed) buffer line number at position POS.
8141 If POS is nil, use current buffer location.
8142 This is an exact copy of `line-number-at-pos' for use in emacs21."
8143 (let ((opoint (or pos (point))) start)
8144 (save-excursion
8145 (goto-char (point-min))
8146 (setq start (point))
8147 (goto-char opoint)
8148 (forward-line 0)
8149 (1+ (count-lines start (point))))))
8151 (defun markdown-inside-link-p ()
8152 "Return t if point is within a link."
8153 (save-match-data
8154 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
8156 (defun markdown-line-is-reference-definition-p ()
8157 "Return whether the current line is a (non-footnote) reference defition."
8158 (save-excursion
8159 (move-beginning-of-line 1)
8160 (and (looking-at-p markdown-regex-reference-definition)
8161 (not (looking-at-p "[ \t]*\\[^")))))
8163 (defun markdown-adaptive-fill-function ()
8164 "Return prefix for filling paragraph or nil if not determined."
8165 (cond
8166 ;; List item inside blockquote
8167 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
8168 (markdown-replace-regexp-in-string
8169 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
8170 ;; Blockquote
8171 ((looking-at markdown-regex-blockquote)
8172 (buffer-substring-no-properties (match-beginning 0) (match-end 2)))
8173 ;; List items
8174 ((looking-at markdown-regex-list)
8175 (match-string-no-properties 0))
8176 ;; Footnote definition
8177 ((looking-at-p markdown-regex-footnote-definition)
8178 " ") ; four spaces
8179 ;; No match
8180 (t nil)))
8182 (defun markdown-fill-paragraph (&optional justify)
8183 "Fill paragraph at or after point.
8184 This function is like \\[fill-paragraph], but it skips Markdown
8185 code blocks. If the point is in a code block, or just before one,
8186 do not fill. Otherwise, call `fill-paragraph' as usual. If
8187 JUSTIFY is non-nil, justify text as well. Since this function
8188 handles filling itself, it always returns t so that
8189 `fill-paragraph' doesn't run."
8190 (interactive "P")
8191 (unless (or (markdown-code-block-at-point-p)
8192 (save-excursion
8193 (back-to-indentation)
8194 (skip-syntax-forward "-")
8195 (markdown-code-block-at-point-p)))
8196 (fill-paragraph justify))
8199 (make-obsolete 'markdown-fill-forward-paragraph-function
8200 'markdown-fill-forward-paragraph "v2.3")
8202 (defun markdown-fill-forward-paragraph (&optional arg)
8203 "Function used by `fill-paragraph' to move over ARG paragraphs.
8204 This is a `fill-forward-paragraph-function' for `markdown-mode'.
8205 It is called with a single argument specifying the number of
8206 paragraphs to move. Just like `forward-paragraph', it should
8207 return the number of paragraphs left to move."
8208 (or arg (setq arg 1))
8209 (if (> arg 0)
8210 ;; With positive ARG, move across ARG non-code-block paragraphs,
8211 ;; one at a time. When passing a code block, don't decrement ARG.
8212 (while (and (not (eobp))
8213 (> arg 0)
8214 (= (forward-paragraph 1) 0)
8215 (or (markdown-code-block-at-pos (point-at-bol 0))
8216 (setq arg (1- arg)))))
8217 ;; Move backward by one paragraph with negative ARG (always -1).
8218 (let ((start (point)))
8219 (setq arg (forward-paragraph arg))
8220 (while (and (not (eobp))
8221 (progn (move-to-left-margin) (not (eobp)))
8222 (looking-at-p paragraph-separate))
8223 (forward-line 1))
8224 (cond
8225 ;; Move point past whitespace following list marker.
8226 ((looking-at markdown-regex-list)
8227 (goto-char (match-end 0)))
8228 ;; Move point past whitespace following pipe at beginning of line
8229 ;; to handle Pandoc line blocks.
8230 ((looking-at "^|\\s-*")
8231 (goto-char (match-end 0)))
8232 ;; Return point if the paragraph passed was a code block.
8233 ((markdown-code-block-at-pos (point-at-bol 2))
8234 (goto-char start)))))
8235 arg)
8237 (defun markdown--inhibit-electric-quote ()
8238 "Function added to `electric-quote-inhibit-functions'.
8239 Return non-nil if the quote has been inserted inside a code block
8240 or span."
8241 (let ((pos (1- (point))))
8242 (or (markdown-inline-code-at-pos pos)
8243 (markdown-code-block-at-pos pos))))
8246 ;;; Extension Framework =======================================================
8248 (defun markdown-reload-extensions ()
8249 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
8250 (interactive)
8251 (when (member major-mode
8252 '(markdown-mode markdown-view-mode gfm-mode gfm-view-mode))
8253 ;; Refontify buffer
8254 (if (eval-when-compile (fboundp 'font-lock-flush))
8255 ;; Use font-lock-flush in Emacs >= 25.1
8256 (font-lock-flush)
8257 ;; Backwards compatibility for Emacs 24.3-24.5
8258 (when (and font-lock-mode (fboundp 'font-lock-refresh-defaults))
8259 (font-lock-refresh-defaults)))
8260 ;; Add or remove hooks related to extensions
8261 (markdown-setup-wiki-link-hooks)))
8263 (defun markdown-handle-local-variables ()
8264 "Run in `hack-local-variables-hook' to update font lock rules.
8265 Checks to see if there is actually a ‘markdown-mode’ file local variable
8266 before regenerating font-lock rules for extensions."
8267 (when (and (boundp 'file-local-variables-alist)
8268 (or (assoc 'markdown-enable-wiki-links file-local-variables-alist)
8269 (assoc 'markdown-enable-math file-local-variables-alist)))
8270 (when (assoc 'markdown-enable-math file-local-variables-alist)
8271 (markdown-toggle-math markdown-enable-math))
8272 (markdown-reload-extensions)))
8275 ;;; Math Support ==============================================================
8277 (make-obsolete 'markdown-enable-math 'markdown-toggle-math "v2.1")
8279 (defconst markdown-mode-font-lock-keywords-math
8280 (list
8281 ;; Equation reference (eq:foo)
8282 '("\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" . ((1 markdown-markup-face)
8283 (2 markdown-reference-face)
8284 (3 markdown-markup-face)))
8285 ;; Equation reference \eqref{foo}
8286 '("\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" . ((1 markdown-markup-face)
8287 (2 markdown-reference-face)
8288 (3 markdown-markup-face))))
8289 "Font lock keywords to add and remove when toggling math support.")
8291 (defun markdown-toggle-math (&optional arg)
8292 "Toggle support for inline and display LaTeX math expressions.
8293 With a prefix argument ARG, enable math mode if ARG is positive,
8294 and disable it otherwise. If called from Lisp, enable the mode
8295 if ARG is omitted or nil."
8296 (interactive (list (or current-prefix-arg 'toggle)))
8297 (setq markdown-enable-math
8298 (if (eq arg 'toggle)
8299 (not markdown-enable-math)
8300 (> (prefix-numeric-value arg) 0)))
8301 (if markdown-enable-math
8302 (progn
8303 (font-lock-add-keywords
8304 'markdown-mode markdown-mode-font-lock-keywords-math)
8305 (message "markdown-mode math support enabled"))
8306 (font-lock-remove-keywords
8307 'markdown-mode markdown-mode-font-lock-keywords-math)
8308 (message "markdown-mode math support disabled"))
8309 (markdown-reload-extensions))
8312 ;;; GFM Checkboxes ============================================================
8314 (define-button-type 'markdown-gfm-checkbox-button
8315 'follow-link t
8316 'face 'markdown-gfm-checkbox-face
8317 'mouse-face 'markdown-highlight-face
8318 'action #'markdown-toggle-gfm-checkbox-button)
8320 (defun markdown-gfm-task-list-item-at-point (&optional bounds)
8321 "Return non-nil if there is a GFM task list item at the point.
8322 Optionally, the list item BOUNDS may be given if available, as
8323 returned by `markdown-cur-list-item-bounds'. When a task list item
8324 is found, the return value is the same value returned by
8325 `markdown-cur-list-item-bounds'."
8326 (unless bounds
8327 (setq bounds (markdown-cur-list-item-bounds)))
8328 (> (length (nth 5 bounds)) 0))
8330 (defun markdown-insert-gfm-checkbox ()
8331 "Add GFM checkbox at point.
8332 Returns t if added.
8333 Returns nil if non-applicable."
8334 (interactive)
8335 (let ((bounds (markdown-cur-list-item-bounds)))
8336 (if bounds
8337 (unless (cl-sixth bounds)
8338 (let ((pos (+ (cl-first bounds) (cl-fourth bounds)))
8339 (markup "[ ] "))
8340 (if (< pos (point))
8341 (save-excursion
8342 (goto-char pos)
8343 (insert markup))
8344 (goto-char pos)
8345 (insert markup))
8346 (syntax-propertize (+ (cl-second bounds) 4))
8348 (unless (save-excursion
8349 (back-to-indentation)
8350 (or (markdown-list-item-at-point-p)
8351 (markdown-heading-at-point)
8352 (markdown-in-comment-p)
8353 (markdown-code-block-at-point-p)))
8354 (let ((pos (save-excursion
8355 (back-to-indentation)
8356 (point)))
8357 (markup (concat (or (save-excursion
8358 (beginning-of-line 0)
8359 (cl-fifth (markdown-cur-list-item-bounds)))
8360 markdown-unordered-list-item-prefix)
8361 "[ ] ")))
8362 (if (< pos (point))
8363 (save-excursion
8364 (goto-char pos)
8365 (insert markup))
8366 (goto-char pos)
8367 (insert markup))
8368 (syntax-propertize (point-at-eol))
8369 t)))))
8371 (defun markdown-toggle-gfm-checkbox ()
8372 "Toggle GFM checkbox at point.
8373 Returns the resulting status as a string, either \"[x]\" or \"[ ]\".
8374 Returns nil if there is no task list item at the point."
8375 (interactive)
8376 (save-match-data
8377 (save-excursion
8378 (let ((bounds (markdown-cur-list-item-bounds)))
8379 (when bounds
8380 ;; Move to beginning of task list item
8381 (goto-char (cl-first bounds))
8382 ;; Advance to column of first non-whitespace after marker
8383 (forward-char (cl-fourth bounds))
8384 (cond ((looking-at "\\[ \\]")
8385 (replace-match
8386 (if markdown-gfm-uppercase-checkbox "[X]" "[x]")
8387 nil t)
8388 (match-string-no-properties 0))
8389 ((looking-at "\\[[xX]\\]")
8390 (replace-match "[ ]" nil t)
8391 (match-string-no-properties 0))))))))
8393 (defun markdown-toggle-gfm-checkbox-button (button)
8394 "Toggle GFM checkbox BUTTON on click."
8395 (save-match-data
8396 (save-excursion
8397 (goto-char (button-start button))
8398 (markdown-toggle-gfm-checkbox))))
8400 (defun markdown-make-gfm-checkboxes-buttons (start end)
8401 "Make GFM checkboxes buttons in region between START and END."
8402 (save-excursion
8403 (goto-char start)
8404 (let ((case-fold-search t))
8405 (save-excursion
8406 (while (re-search-forward markdown-regex-gfm-checkbox end t)
8407 (make-button (match-beginning 1) (match-end 1)
8408 :type 'markdown-gfm-checkbox-button))))))
8410 ;; Called when any modification is made to buffer text.
8411 (defun markdown-gfm-checkbox-after-change-function (beg end _)
8412 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
8413 BEG and END are the limits of scanned region."
8414 (save-excursion
8415 (save-match-data
8416 ;; Rescan between start of line from `beg' and start of line after `end'.
8417 (markdown-make-gfm-checkboxes-buttons
8418 (progn (goto-char beg) (beginning-of-line) (point))
8419 (progn (goto-char end) (forward-line 1) (point))))))
8421 (defun markdown-remove-gfm-checkbox-overlays ()
8422 "Remove all GFM checkbox overlays in buffer."
8423 (save-excursion
8424 (save-restriction
8425 (widen)
8426 (remove-overlays nil nil 'face 'markdown-gfm-checkbox-face))))
8429 ;;; Display inline image =================================================
8431 (defvar markdown-inline-image-overlays nil)
8432 (make-variable-buffer-local 'markdown-inline-image-overlays)
8434 (defun markdown-remove-inline-images ()
8435 "Remove inline image overlays from image links in the buffer.
8436 This can be toggled with `markdown-toggle-inline-images'
8437 or \\[markdown-toggle-inline-images]."
8438 (interactive)
8439 (mapc #'delete-overlay markdown-inline-image-overlays)
8440 (setq markdown-inline-image-overlays nil))
8442 (defun markdown-display-inline-images ()
8443 "Add inline image overlays to image links in the buffer.
8444 This can be toggled with `markdown-toggle-inline-images'
8445 or \\[markdown-toggle-inline-images]."
8446 (interactive)
8447 (unless (display-images-p)
8448 (error "Cannot show images"))
8449 (save-excursion
8450 (save-restriction
8451 (widen)
8452 (goto-char (point-min))
8453 (while (re-search-forward markdown-regex-link-inline nil t)
8454 (let ((start (match-beginning 0))
8455 (end (match-end 0))
8456 (file (match-string-no-properties 6)))
8457 (when (and (not (zerop (length file)))
8458 (file-exists-p file))
8459 (let* ((abspath (if (file-name-absolute-p file)
8460 file
8461 (concat default-directory file)))
8462 (image
8463 (if (and markdown-max-image-size
8464 (image-type-available-p 'imagemagick))
8465 (create-image
8466 abspath 'imagemagick nil
8467 :max-width (car markdown-max-image-size)
8468 :max-height (cdr markdown-max-image-size))
8469 (create-image abspath))))
8470 (when image
8471 (let ((ov (make-overlay start end)))
8472 (overlay-put ov 'display image)
8473 (overlay-put ov 'face 'default)
8474 (push ov markdown-inline-image-overlays))))))))))
8476 (defun markdown-toggle-inline-images ()
8477 "Toggle inline image overlays in the buffer."
8478 (interactive)
8479 (if markdown-inline-image-overlays
8480 (markdown-remove-inline-images)
8481 (markdown-display-inline-images)))
8484 ;;; GFM Code Block Fontification ==============================================
8486 (defcustom markdown-fontify-code-blocks-natively nil
8487 "When non-nil, fontify code in code blocks using the native major mode.
8488 This only works for fenced code blocks where the language is
8489 specified where we can automatically determine the appropriate
8490 mode to use. The language to mode mapping may be customized by
8491 setting the variable `markdown-code-lang-modes'."
8492 :group 'markdown
8493 :type 'boolean
8494 :safe 'booleanp
8495 :package-version '(markdown-mode . "2.3"))
8497 (defcustom markdown-fontify-code-block-default-mode nil
8498 "Default mode to use to fontify code blocks.
8499 This mode is used when automatic detection fails, such as for GFM
8500 code blocks with no language specified."
8501 :group 'markdown
8502 :type '(choice function (const :tag "None" nil))
8503 :package-version '(markdown-mode . "2.4"))
8505 (defun markdown-toggle-fontify-code-blocks-natively (&optional arg)
8506 "Toggle the native fontification of code blocks.
8507 With a prefix argument ARG, enable if ARG is positive,
8508 and disable otherwise."
8509 (interactive (list (or current-prefix-arg 'toggle)))
8510 (setq markdown-fontify-code-blocks-natively
8511 (if (eq arg 'toggle)
8512 (not markdown-fontify-code-blocks-natively)
8513 (> (prefix-numeric-value arg) 0)))
8514 (if markdown-fontify-code-blocks-natively
8515 (message "markdown-mode native code block fontification enabled")
8516 (message "markdown-mode native code block fontification disabled"))
8517 (markdown-reload-extensions))
8519 ;; This is based on `org-src-lang-modes' from org-src.el
8520 (defcustom markdown-code-lang-modes
8521 '(("ocaml" . tuareg-mode) ("elisp" . emacs-lisp-mode) ("ditaa" . artist-mode)
8522 ("asymptote" . asy-mode) ("dot" . fundamental-mode) ("sqlite" . sql-mode)
8523 ("calc" . fundamental-mode) ("C" . c-mode) ("cpp" . c++-mode)
8524 ("C++" . c++-mode) ("screen" . shell-script-mode) ("shell" . sh-mode)
8525 ("bash" . sh-mode))
8526 "Alist mapping languages to their major mode.
8527 The key is the language name, the value is the major mode. For
8528 many languages this is simple, but for language where this is not
8529 the case, this variable provides a way to simplify things on the
8530 user side. For example, there is no ocaml-mode in Emacs, but the
8531 mode to use is `tuareg-mode'."
8532 :group 'markdown
8533 :type '(repeat
8534 (cons
8535 (string "Language name")
8536 (symbol "Major mode")))
8537 :package-version '(markdown-mode . "2.3"))
8539 (defun markdown-get-lang-mode (lang)
8540 "Return major mode that should be used for LANG.
8541 LANG is a string, and the returned major mode is a symbol."
8542 (cl-find-if
8543 'fboundp
8544 (list (cdr (assoc lang markdown-code-lang-modes))
8545 (cdr (assoc (downcase lang) markdown-code-lang-modes))
8546 (intern (concat lang "-mode"))
8547 (intern (concat (downcase lang) "-mode")))))
8549 (defun markdown-fontify-code-blocks-generic (matcher last)
8550 "Add text properties to next code block from point to LAST.
8551 Use matching function MATCHER."
8552 (when (funcall matcher last)
8553 (save-excursion
8554 (save-match-data
8555 (let* ((start (match-beginning 0))
8556 (end (match-end 0))
8557 ;; Find positions outside opening and closing backquotes.
8558 (bol-prev (progn (goto-char start)
8559 (if (bolp) (point-at-bol 0) (point-at-bol))))
8560 (eol-next (progn (goto-char end)
8561 (if (bolp) (point-at-bol 2) (point-at-bol 3))))
8562 lang)
8563 (if (and markdown-fontify-code-blocks-natively
8564 (or (setq lang (markdown-code-block-lang))
8565 markdown-fontify-code-block-default-mode))
8566 (markdown-fontify-code-block-natively lang start end)
8567 (add-text-properties start end '(face markdown-pre-face)))
8568 ;; Set background for block as well as opening and closing lines.
8569 (font-lock-append-text-property
8570 bol-prev eol-next 'face 'markdown-code-face)
8571 ;; Set invisible property for lines before and after, including newline.
8572 (add-text-properties bol-prev start '(invisible markdown-markup))
8573 (add-text-properties end eol-next '(invisible markdown-markup)))))
8576 (defun markdown-fontify-gfm-code-blocks (last)
8577 "Add text properties to next GFM code block from point to LAST."
8578 (markdown-fontify-code-blocks-generic 'markdown-match-gfm-code-blocks last))
8580 (defun markdown-fontify-fenced-code-blocks (last)
8581 "Add text properties to next tilde fenced code block from point to LAST."
8582 (markdown-fontify-code-blocks-generic 'markdown-match-fenced-code-blocks last))
8584 ;; Based on `org-src-font-lock-fontify-block' from org-src.el.
8585 (defun markdown-fontify-code-block-natively (lang start end)
8586 "Fontify given GFM or fenced code block.
8587 This function is called by Emacs for automatic fontification when
8588 `markdown-fontify-code-blocks-natively' is non-nil. LANG is the
8589 language used in the block. START and END specify the block
8590 position."
8591 (let ((lang-mode (if lang (markdown-get-lang-mode lang)
8592 markdown-fontify-code-block-default-mode)))
8593 (when (fboundp lang-mode)
8594 (let ((string (buffer-substring-no-properties start end))
8595 (modified (buffer-modified-p))
8596 (markdown-buffer (current-buffer)) pos next)
8597 (remove-text-properties start end '(face nil))
8598 (with-current-buffer
8599 (get-buffer-create
8600 (concat " markdown-code-fontification:" (symbol-name lang-mode)))
8601 ;; Make sure that modification hooks are not inhibited in
8602 ;; the org-src-fontification buffer in case we're called
8603 ;; from `jit-lock-function' (Bug#25132).
8604 (let ((inhibit-modification-hooks nil))
8605 (delete-region (point-min) (point-max))
8606 (insert string " ")) ;; so there's a final property change
8607 (unless (eq major-mode lang-mode) (funcall lang-mode))
8608 (markdown-font-lock-ensure)
8609 (setq pos (point-min))
8610 (while (setq next (next-single-property-change pos 'face))
8611 (let ((val (get-text-property pos 'face)))
8612 (when val
8613 (put-text-property
8614 (+ start (1- pos)) (1- (+ start next)) 'face
8615 val markdown-buffer)))
8616 (setq pos next)))
8617 (add-text-properties
8618 start end
8619 '(font-lock-fontified t fontified t font-lock-multiline t))
8620 (set-buffer-modified-p modified)))))
8622 (require 'edit-indirect nil t)
8623 (defvar edit-indirect-guess-mode-function)
8624 (defvar edit-indirect-after-commit-functions)
8626 (defun markdown--edit-indirect-after-commit-function (_beg end)
8627 "Ensure trailing newlines at the END of code blocks."
8628 (goto-char end)
8629 (unless (eq (char-before) ?\n)
8630 (insert "\n")))
8632 (defun markdown-edit-code-block ()
8633 "Edit Markdown code block in an indirect buffer."
8634 (interactive)
8635 (save-excursion
8636 (if (fboundp 'edit-indirect-region)
8637 (let* ((bounds (markdown-get-enclosing-fenced-block-construct))
8638 (begin (and bounds (goto-char (nth 0 bounds)) (point-at-bol 2)))
8639 (end (and bounds (goto-char (nth 1 bounds)) (point-at-bol 1))))
8640 (if (and begin end)
8641 (let* ((lang (markdown-code-block-lang))
8642 (mode (or (and lang (markdown-get-lang-mode lang))
8643 markdown-edit-code-block-default-mode))
8644 (edit-indirect-guess-mode-function
8645 (lambda (_parent-buffer _beg _end)
8646 (funcall mode))))
8647 (edit-indirect-region begin end 'display-buffer))
8648 (user-error "Not inside a GFM or tilde fenced code block")))
8649 (when (y-or-n-p "Package edit-indirect needed to edit code blocks. Install it now? ")
8650 (progn (package-refresh-contents)
8651 (package-install 'edit-indirect)
8652 (markdown-edit-code-block))))))
8655 ;;; Table Editing
8657 ;; These functions were originally adapted from `org-table.el'.
8659 ;; General helper functions
8661 (defmacro markdown--with-gensyms (symbols &rest body)
8662 (declare (debug (sexp body)) (indent 1))
8663 `(let ,(mapcar (lambda (s)
8664 `(,s (make-symbol (concat "--" (symbol-name ',s)))))
8665 symbols)
8666 ,@body))
8668 (defun markdown--split-string (string &optional separators)
8669 "Splits STRING into substrings at SEPARATORS.
8670 SEPARATORS is a regular expression. If nil it defaults to
8671 `split-string-default-separators'. This version returns no empty
8672 strings if there are matches at the beginning and end of string."
8673 (let ((start 0) notfirst list)
8674 (while (and (string-match
8675 (or separators split-string-default-separators)
8676 string
8677 (if (and notfirst
8678 (= start (match-beginning 0))
8679 (< start (length string)))
8680 (1+ start) start))
8681 (< (match-beginning 0) (length string)))
8682 (setq notfirst t)
8683 (or (eq (match-beginning 0) 0)
8684 (and (eq (match-beginning 0) (match-end 0))
8685 (eq (match-beginning 0) start))
8686 (push (substring string start (match-beginning 0)) list))
8687 (setq start (match-end 0)))
8688 (or (eq start (length string))
8689 (push (substring string start) list))
8690 (nreverse list)))
8692 (defun markdown--string-width (s)
8693 "Return width of string S.
8694 This version ignores characters with invisibility property
8695 `markdown-markup'."
8696 (let (b)
8697 (when (or (eq t buffer-invisibility-spec)
8698 (member 'markdown-markup buffer-invisibility-spec))
8699 (while (setq b (text-property-any
8700 0 (length s)
8701 'invisible 'markdown-markup s))
8702 (setq s (concat
8703 (substring s 0 b)
8704 (substring s (or (next-single-property-change
8705 b 'invisible s)
8706 (length s))))))))
8707 (string-width s))
8709 (defun markdown--remove-invisible-markup (s)
8710 "Remove Markdown markup from string S.
8711 This version removes characters with invisibility property
8712 `markdown-markup'."
8713 (let (b)
8714 (while (setq b (text-property-any
8715 0 (length s)
8716 'invisible 'markdown-markup s))
8717 (setq s (concat
8718 (substring s 0 b)
8719 (substring s (or (next-single-property-change
8720 b 'invisible s)
8721 (length s)))))))
8724 ;; Functions for maintaining tables
8726 (defvar markdown-table-at-point-p-function nil
8727 "Function to decide if point is inside a table.
8729 The indirection serves to differentiate between standard markdown
8730 tables and gfm tables which are less strict about the markup.")
8732 (defconst markdown-table-line-regexp "^[ \t]*|"
8733 "Regexp matching any line inside a table.")
8735 (defconst markdown-table-hline-regexp "^[ \t]*|[-:]"
8736 "Regexp matching hline inside a table.")
8738 (defconst markdown-table-dline-regexp "^[ \t]*|[^-:]"
8739 "Regexp matching dline inside a table.")
8741 (defun markdown-table-at-point-p ()
8742 "Return non-nil when point is inside a table."
8743 (if (functionp markdown-table-at-point-p-function)
8744 (funcall markdown-table-at-point-p-function)
8745 (markdown--table-at-point-p)))
8747 (defun markdown--table-at-point-p ()
8748 "Return non-nil when point is inside a table."
8749 (save-excursion
8750 (beginning-of-line)
8751 (and (looking-at-p markdown-table-line-regexp)
8752 (not (markdown-code-block-at-point-p)))))
8754 (defconst gfm-table-line-regexp "^.?*|"
8755 "Regexp matching any line inside a table.")
8757 (defconst gfm-table-hline-regexp "^-+\\(|-\\)+"
8758 "Regexp matching hline inside a table.")
8760 ;; GFM simplified tables syntax is as follows:
8761 ;; - A header line for the column names, this is any text
8762 ;; separated by `|'.
8763 ;; - Followed by a string -|-|- ..., the number of dashes is optional
8764 ;; but must be higher than 1. The number of separators should match
8765 ;; the number of columns.
8766 ;; - Followed by the rows of data, which has the same format as the
8767 ;; header line.
8768 ;; Example:
8770 ;; foo | bar
8771 ;; ------|---------
8772 ;; bar | baz
8773 ;; bar | baz
8774 (defun gfm--table-at-point-p ()
8775 "Return non-nil when point is inside a gfm-compatible table."
8776 (or (markdown--table-at-point-p)
8777 (save-excursion
8778 (beginning-of-line)
8779 (when (looking-at-p gfm-table-line-regexp)
8780 ;; we might be at the first line of the table, check if the
8781 ;; line below is the hline
8782 (or (save-excursion
8783 (forward-line 1)
8784 (looking-at-p gfm-table-hline-regexp))
8785 ;; go up to find the header
8786 (catch 'done
8787 (while (looking-at-p gfm-table-line-regexp)
8788 (cond
8789 ((looking-at-p gfm-table-hline-regexp)
8790 (throw 'done t))
8791 ((bobp)
8792 (throw 'done nil)))
8793 (forward-line -1))
8794 nil))))))
8796 (defun markdown-table-hline-at-point-p ()
8797 "Return non-nil when point is on a hline in a table.
8798 This function assumes point is on a table."
8799 (save-excursion
8800 (beginning-of-line)
8801 (looking-at-p markdown-table-hline-regexp)))
8803 (defun markdown-table-begin ()
8804 "Find the beginning of the table and return its position.
8805 This function assumes point is on a table."
8806 (save-excursion
8807 (while (and (not (bobp))
8808 (markdown-table-at-point-p))
8809 (forward-line -1))
8810 (unless (eobp)
8811 (forward-line 1))
8812 (point)))
8814 (defun markdown-table-end ()
8815 "Find the end of the table and return its position.
8816 This function assumes point is on a table."
8817 (save-excursion
8818 (while (and (not (eobp))
8819 (markdown-table-at-point-p))
8820 (forward-line 1))
8821 (point)))
8823 (defun markdown-table-get-dline ()
8824 "Return index of the table data line at point.
8825 This function assumes point is on a table."
8826 (let ((pos (point)) (end (markdown-table-end)) (cnt 0))
8827 (save-excursion
8828 (goto-char (markdown-table-begin))
8829 (while (and (re-search-forward
8830 markdown-table-dline-regexp end t)
8831 (setq cnt (1+ cnt))
8832 (< (point-at-eol) pos))))
8833 cnt))
8835 (defun markdown-table-get-column ()
8836 "Return table column at point.
8837 This function assumes point is on a table."
8838 (let ((pos (point)) (cnt 0))
8839 (save-excursion
8840 (beginning-of-line)
8841 (while (search-forward "|" pos t) (setq cnt (1+ cnt))))
8842 cnt))
8844 (defun markdown-table-get-cell (&optional n)
8845 "Return the content of the cell in column N of current row.
8846 N defaults to column at point. This function assumes point is on
8847 a table."
8848 (and n (markdown-table-goto-column n))
8849 (skip-chars-backward "^|\n") (backward-char 1)
8850 (if (looking-at "|[^|\r\n]*")
8851 (let* ((pos (match-beginning 0))
8852 (val (buffer-substring (1+ pos) (match-end 0))))
8853 (goto-char (min (point-at-eol) (+ 2 pos)))
8854 ;; Trim whitespaces
8855 (setq val (replace-regexp-in-string "\\`[ \t]+" "" val)
8856 val (replace-regexp-in-string "[ \t]+\\'" "" val)))
8857 (forward-char 1) ""))
8859 (defun markdown-table-goto-dline (n)
8860 "Go to the Nth data line in the table at point.
8861 Return t when the line exists, nil otherwise. This function
8862 assumes point is on a table."
8863 (goto-char (markdown-table-begin))
8864 (let ((end (markdown-table-end)) (cnt 0))
8865 (while (and (re-search-forward
8866 markdown-table-dline-regexp end t)
8867 (< (setq cnt (1+ cnt)) n)))
8868 (= cnt n)))
8870 (defun markdown-table-goto-column (n &optional on-delim)
8871 "Go to the Nth column in the table line at point.
8872 With optional argument ON-DELIM, stop with point before the left
8873 delimiter of the cell. If there are less than N cells, just go
8874 beyond the last delimiter. This function assumes point is on a
8875 table."
8876 (beginning-of-line 1)
8877 (when (> n 0)
8878 (while (and (> (setq n (1- n)) -1)
8879 (search-forward "|" (point-at-eol) t)))
8880 (if on-delim
8881 (backward-char 1)
8882 (when (looking-at " ") (forward-char 1)))))
8884 (defmacro markdown-table-save-cell (&rest body)
8885 "Save cell at point, execute BODY and restore cell.
8886 This function assumes point is on a table."
8887 (declare (debug (body)))
8888 (markdown--with-gensyms (line column)
8889 `(let ((,line (copy-marker (line-beginning-position)))
8890 (,column (markdown-table-get-column)))
8891 (unwind-protect
8892 (progn ,@body)
8893 (goto-char ,line)
8894 (markdown-table-goto-column ,column)
8895 (set-marker ,line nil)))))
8897 (defun markdown-table-blank-line (s)
8898 "Convert a table line S into a line with blank cells."
8899 (if (string-match "^[ \t]*|-" s)
8900 (setq s (mapconcat
8901 (lambda (x) (if (member x '(?| ?+)) "|" " "))
8902 s ""))
8903 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
8904 (setq s (replace-match
8905 (concat "|" (make-string (length (match-string 1 s)) ?\ ) "|")
8906 t t s)))
8909 (defun markdown-table-colfmt (fmtspec)
8910 "Process column alignment specifier FMTSPEC for tables."
8911 (when (stringp fmtspec)
8912 (mapcar (lambda (x)
8913 (cond ((string-match-p "^:.*:$" x) 'c)
8914 ((string-match-p "^:" x) 'l)
8915 ((string-match-p ":$" x) 'r)
8916 (t 'd)))
8917 (markdown--split-string fmtspec "\\s-*|\\s-*"))))
8919 (defun markdown-table-align ()
8920 "Align table at point.
8921 This function assumes point is on a table."
8922 (interactive)
8923 (let ((begin (markdown-table-begin))
8924 (end (copy-marker (markdown-table-end))))
8925 (markdown-table-save-cell
8926 (goto-char begin)
8927 (let* (fmtspec
8928 ;; Store table indent
8929 (indent (progn (looking-at "[ \t]*") (match-string 0)))
8930 ;; Split table in lines and save column format specifier
8931 (lines (mapcar (lambda (l)
8932 (if (string-match-p "\\`[ \t]*|[-:]" l)
8933 (progn (setq fmtspec (or fmtspec l)) nil) l))
8934 (markdown--split-string (buffer-substring begin end) "\n")))
8935 ;; Split lines in cells
8936 (cells (mapcar (lambda (l) (markdown--split-string l "\\s-*|\\s-*"))
8937 (remq nil lines)))
8938 ;; Calculate maximum number of cells in a line
8939 (maxcells (if cells
8940 (apply #'max (mapcar #'length cells))
8941 (user-error "Empty table")))
8942 ;; Empty cells to fill short lines
8943 (emptycells (make-list maxcells "")) maxwidths)
8944 ;; Calculate maximum width for each column
8945 (dotimes (i maxcells)
8946 (let ((column (mapcar (lambda (x) (or (nth i x) "")) cells)))
8947 (push (apply #'max 1 (mapcar #'markdown--string-width column))
8948 maxwidths)))
8949 (setq maxwidths (nreverse maxwidths))
8950 ;; Process column format specifier
8951 (setq fmtspec (markdown-table-colfmt fmtspec))
8952 ;; Compute formats needed for output of table lines
8953 (let ((hfmt (concat indent "|"))
8954 (rfmt (concat indent "|"))
8955 hfmt1 rfmt1 fmt)
8956 (dolist (width maxwidths (setq hfmt (concat (substring hfmt 0 -1) "|")))
8957 (setq fmt (pop fmtspec))
8958 (cond ((equal fmt 'l) (setq hfmt1 ":%s-|" rfmt1 " %%-%ds |"))
8959 ((equal fmt 'r) (setq hfmt1 "-%s:|" rfmt1 " %%%ds |"))
8960 ((equal fmt 'c) (setq hfmt1 ":%s:|" rfmt1 " %%-%ds |"))
8961 (t (setq hfmt1 "-%s-|" rfmt1 " %%-%ds |")))
8962 (setq rfmt (concat rfmt (format rfmt1 width)))
8963 (setq hfmt (concat hfmt (format hfmt1 (make-string width ?-)))))
8964 ;; Replace modified lines only
8965 (dolist (line lines)
8966 (let ((line (if line
8967 (apply #'format rfmt (append (pop cells) emptycells))
8968 hfmt))
8969 (previous (buffer-substring (point) (line-end-position))))
8970 (if (equal previous line)
8971 (forward-line)
8972 (insert line "\n")
8973 (delete-region (point) (line-beginning-position 2))))))
8974 (set-marker end nil)))))
8976 (defun markdown-table-insert-row (&optional arg)
8977 "Insert a new row above the row at point into the table.
8978 With optional argument ARG, insert below the current row."
8979 (interactive "P")
8980 (unless (markdown-table-at-point-p)
8981 (user-error "Not at a table"))
8982 (let* ((line (buffer-substring
8983 (line-beginning-position) (line-end-position)))
8984 (new (markdown-table-blank-line line)))
8985 (beginning-of-line (if arg 2 1))
8986 (unless (bolp) (insert "\n"))
8987 (insert-before-markers new "\n")
8988 (beginning-of-line 0)
8989 (re-search-forward "| ?" (line-end-position) t)))
8991 (defun markdown-table-delete-row ()
8992 "Delete row or horizontal line at point from the table."
8993 (interactive)
8994 (unless (markdown-table-at-point-p)
8995 (user-error "Not at a table"))
8996 (let ((col (current-column)))
8997 (kill-region (point-at-bol)
8998 (min (1+ (point-at-eol)) (point-max)))
8999 (unless (markdown-table-at-point-p) (beginning-of-line 0))
9000 (move-to-column col)))
9002 (defun markdown-table-move-row (&optional up)
9003 "Move table line at point down.
9004 With optional argument UP, move it up."
9005 (interactive "P")
9006 (unless (markdown-table-at-point-p)
9007 (user-error "Not at a table"))
9008 (let* ((col (current-column)) (pos (point))
9009 (tonew (if up 0 2)) txt)
9010 (beginning-of-line tonew)
9011 (unless (markdown-table-at-point-p)
9012 (goto-char pos) (user-error "Cannot move row further"))
9013 (goto-char pos) (beginning-of-line 1) (setq pos (point))
9014 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9015 (delete-region (point) (1+ (point-at-eol)))
9016 (beginning-of-line tonew)
9017 (insert txt) (beginning-of-line 0)
9018 (move-to-column col)))
9020 (defun markdown-table-move-row-up ()
9021 "Move table row at point up."
9022 (interactive)
9023 (markdown-table-move-row 'up))
9025 (defun markdown-table-move-row-down ()
9026 "Move table row at point down."
9027 (interactive)
9028 (markdown-table-move-row nil))
9030 (defun markdown-table-insert-column ()
9031 "Insert a new table column."
9032 (interactive)
9033 (unless (markdown-table-at-point-p)
9034 (user-error "Not at a table"))
9035 (let* ((col (max 1 (markdown-table-get-column)))
9036 (begin (markdown-table-begin))
9037 (end (copy-marker (markdown-table-end))))
9038 (markdown-table-save-cell
9039 (goto-char begin)
9040 (while (< (point) end)
9041 (markdown-table-goto-column col t)
9042 (if (markdown-table-hline-at-point-p)
9043 (insert "|---")
9044 (insert "| "))
9045 (forward-line)))
9046 (set-marker end nil)
9047 (markdown-table-align)))
9049 (defun markdown-table-delete-column ()
9050 "Delete column at point from table."
9051 (interactive)
9052 (unless (markdown-table-at-point-p)
9053 (user-error "Not at a table"))
9054 (let ((col (markdown-table-get-column))
9055 (begin (markdown-table-begin))
9056 (end (copy-marker (markdown-table-end))))
9057 (markdown-table-save-cell
9058 (goto-char begin)
9059 (while (< (point) end)
9060 (markdown-table-goto-column col t)
9061 (and (looking-at "|[^|\n]+|")
9062 (replace-match "|"))
9063 (forward-line)))
9064 (set-marker end nil)
9065 (markdown-table-goto-column (max 1 (1- col)))
9066 (markdown-table-align)))
9068 (defun markdown-table-move-column (&optional left)
9069 "Move table column at point to the right.
9070 With optional argument LEFT, move it to the left."
9071 (interactive "P")
9072 (unless (markdown-table-at-point-p)
9073 (user-error "Not at a table"))
9074 (let* ((col (markdown-table-get-column))
9075 (col1 (if left (1- col) col))
9076 (colpos (if left (1- col) (1+ col)))
9077 (begin (markdown-table-begin))
9078 (end (copy-marker (markdown-table-end))))
9079 (when (and left (= col 1))
9080 (user-error "Cannot move column further left"))
9081 (when (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9082 (user-error "Cannot move column further right"))
9083 (markdown-table-save-cell
9084 (goto-char begin)
9085 (while (< (point) end)
9086 (markdown-table-goto-column col1 t)
9087 (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9088 (replace-match "|\\2|\\1|"))
9089 (forward-line)))
9090 (set-marker end nil)
9091 (markdown-table-goto-column colpos)
9092 (markdown-table-align)))
9094 (defun markdown-table-move-column-left ()
9095 "Move table column at point to the left."
9096 (interactive)
9097 (markdown-table-move-column 'left))
9099 (defun markdown-table-move-column-right ()
9100 "Move table column at point to the right."
9101 (interactive)
9102 (markdown-table-move-column nil))
9104 (defun markdown-table-next-row ()
9105 "Go to the next row (same column) in the table.
9106 Create new table lines if required."
9107 (interactive)
9108 (unless (markdown-table-at-point-p)
9109 (user-error "Not at a table"))
9110 (if (or (looking-at "[ \t]*$")
9111 (save-excursion (skip-chars-backward " \t") (bolp)))
9112 (newline)
9113 (markdown-table-align)
9114 (let ((col (markdown-table-get-column)))
9115 (beginning-of-line 2)
9116 (if (or (not (markdown-table-at-point-p))
9117 (markdown-table-hline-at-point-p))
9118 (progn
9119 (beginning-of-line 0)
9120 (markdown-table-insert-row 'below)))
9121 (markdown-table-goto-column col)
9122 (skip-chars-backward "^|\n\r")
9123 (when (looking-at " ") (forward-char 1)))))
9125 (defun markdown-table-forward-cell ()
9126 "Go to the next cell in the table.
9127 Create new table lines if required."
9128 (interactive)
9129 (unless (markdown-table-at-point-p)
9130 (user-error "Not at a table"))
9131 (markdown-table-align)
9132 (let ((end (markdown-table-end)))
9133 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9134 (condition-case nil
9135 (progn
9136 (re-search-forward "|" end)
9137 (if (looking-at "[ \t]*$")
9138 (re-search-forward "|" end))
9139 (if (and (looking-at "[-:]")
9140 (re-search-forward "^[ \t]*|\\([^-:]\\)" end t))
9141 (goto-char (match-beginning 1)))
9142 (if (looking-at "[-:]")
9143 (progn
9144 (beginning-of-line 0)
9145 (markdown-table-insert-row 'below))
9146 (when (looking-at " ") (forward-char 1))))
9147 (error (markdown-table-insert-row 'below)))))
9149 (defun markdown-table-backward-cell ()
9150 "Go to the previous cell in the table."
9151 (interactive)
9152 (unless (markdown-table-at-point-p)
9153 (user-error "Not at a table"))
9154 (markdown-table-align)
9155 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9156 (condition-case nil
9157 (progn
9158 (re-search-backward "|" (markdown-table-begin))
9159 (re-search-backward "|" (markdown-table-begin)))
9160 (error (user-error "Cannot move to previous table cell")))
9161 (while (looking-at "|\\([-:]\\|[ \t]*$\\)")
9162 (re-search-backward "|" (markdown-table-begin)))
9163 (when (looking-at "| ?") (goto-char (match-end 0))))
9165 (defun markdown-table-transpose ()
9166 "Transpose table at point.
9167 Horizontal separator lines will be eliminated."
9168 (interactive)
9169 (unless (markdown-table-at-point-p)
9170 (user-error "Not at a table"))
9171 (let* ((table (buffer-substring-no-properties
9172 (markdown-table-begin) (markdown-table-end)))
9173 ;; Convert table to a Lisp structure
9174 (table (delq nil
9175 (mapcar
9176 (lambda (x)
9177 (unless (string-match-p
9178 markdown-table-hline-regexp x)
9179 (markdown--split-string x "\\s-*|\\s-*")))
9180 (markdown--split-string table "[ \t]*\n[ \t]*"))))
9181 (dline_old (markdown-table-get-dline))
9182 (col_old (markdown-table-get-column))
9183 (contents (mapcar (lambda (_)
9184 (let ((tp table))
9185 (mapcar
9186 (lambda (_)
9187 (prog1
9188 (pop (car tp))
9189 (setq tp (cdr tp))))
9190 table)))
9191 (car table))))
9192 (goto-char (markdown-table-begin))
9193 (re-search-forward "|") (backward-char)
9194 (delete-region (point) (markdown-table-end))
9195 (insert (mapconcat
9196 (lambda(x)
9197 (concat "| " (mapconcat 'identity x " | " ) " |\n"))
9198 contents ""))
9199 (markdown-table-goto-dline col_old)
9200 (markdown-table-goto-column dline_old))
9201 (markdown-table-align))
9203 (defun markdown-table-sort-lines (&optional sorting-type)
9204 "Sort table lines according to the column at point.
9206 The position of point indicates the column to be used for
9207 sorting, and the range of lines is the range between the nearest
9208 horizontal separator lines, or the entire table of no such lines
9209 exist. If point is before the first column, user will be prompted
9210 for the sorting column. If there is an active region, the mark
9211 specifies the first line and the sorting column, while point
9212 should be in the last line to be included into the sorting.
9214 The command then prompts for the sorting type which can be
9215 alphabetically or numerically. Sorting in reverse order is also
9216 possible.
9218 If SORTING-TYPE is specified when this function is called from a
9219 Lisp program, no prompting will take place. SORTING-TYPE must be
9220 a character, any of (?a ?A ?n ?N) where the capital letters
9221 indicate that sorting should be done in reverse order."
9222 (interactive)
9223 (unless (markdown-table-at-point-p)
9224 (user-error "Not at a table"))
9225 ;; Set sorting type and column used for sorting
9226 (let ((column (let ((c (markdown-table-get-column)))
9227 (cond ((> c 0) c)
9228 ((called-interactively-p 'any)
9229 (read-number "Use column N for sorting: "))
9230 (t 1))))
9231 (sorting-type
9232 (or sorting-type
9233 (read-char-exclusive
9234 "Sort type: [a]lpha [n]umeric (A/N means reversed): "))))
9235 (save-restriction
9236 ;; Narrow buffer to appropriate sorting area
9237 (if (region-active-p)
9238 (narrow-to-region
9239 (save-excursion
9240 (progn
9241 (goto-char (region-beginning)) (line-beginning-position)))
9242 (save-excursion
9243 (progn
9244 (goto-char (region-end)) (line-end-position))))
9245 (let ((start (markdown-table-begin))
9246 (end (markdown-table-end)))
9247 (narrow-to-region
9248 (save-excursion
9249 (if (re-search-backward
9250 markdown-table-hline-regexp start t)
9251 (line-beginning-position 2)
9252 start))
9253 (if (save-excursion (re-search-forward
9254 markdown-table-hline-regexp end t))
9255 (match-beginning 0)
9256 end))))
9257 ;; Determine arguments for `sort-subr'
9258 (let* ((extract-key-from-cell
9259 (cl-case sorting-type
9260 ((?a ?A) #'markdown--remove-invisible-markup) ;; #'identity)
9261 ((?n ?N) #'string-to-number)
9262 (t (user-error "Invalid sorting type: %c" sorting-type))))
9263 (predicate
9264 (cl-case sorting-type
9265 ((?n ?N) #'<)
9266 ((?a ?A) #'string<))))
9267 ;; Sort selected area
9268 (goto-char (point-min))
9269 (sort-subr (memq sorting-type '(?A ?N))
9270 (lambda ()
9271 (forward-line)
9272 (while (and (not (eobp))
9273 (not (looking-at
9274 markdown-table-dline-regexp)))
9275 (forward-line)))
9276 #'end-of-line
9277 (lambda ()
9278 (funcall extract-key-from-cell
9279 (markdown-table-get-cell column)))
9281 predicate)
9282 (goto-char (point-min))))))
9284 (defun markdown-table-convert-region (begin end &optional separator)
9285 "Convert region from BEGIN to END to table with SEPARATOR.
9287 If every line contains at least one TAB character, the function
9288 assumes that the material is tab separated (TSV). If every line
9289 contains a comma, comma-separated values (CSV) are assumed. If
9290 not, lines are split at whitespace into cells.
9292 You can use a prefix argument to force a specific separator:
9293 \\[universal-argument] once forces CSV, \\[universal-argument]
9294 twice forces TAB, and \\[universal-argument] three times will
9295 prompt for a regular expression to match the separator, and a
9296 numeric argument N indicates that at least N consecutive
9297 spaces, or alternatively a TAB should be used as the separator."
9299 (interactive "r\nP")
9300 (let* ((begin (min begin end)) (end (max begin end)) re)
9301 (goto-char begin) (beginning-of-line 1)
9302 (setq begin (point-marker))
9303 (goto-char end)
9304 (if (bolp) (backward-char 1) (end-of-line 1))
9305 (setq end (point-marker))
9306 (when (equal separator '(64))
9307 (setq separator (read-regexp "Regexp for cell separator: ")))
9308 (unless separator
9309 ;; Get the right cell separator
9310 (goto-char begin)
9311 (setq separator
9312 (cond
9313 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
9314 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
9315 (t 1))))
9316 (goto-char begin)
9317 (if (equal separator '(4))
9318 ;; Parse CSV
9319 (while (< (point) end)
9320 (cond
9321 ((looking-at "^") (insert "| "))
9322 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
9323 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
9324 (replace-match "\\1") (if (looking-at "\"") (insert "\"")))
9325 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
9326 ((looking-at "[ \t]*,") (replace-match " | "))
9327 (t (beginning-of-line 2))))
9328 (setq re
9329 (cond
9330 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
9331 ((equal separator '(16)) "^\\|\t")
9332 ((integerp separator)
9333 (if (< separator 1)
9334 (user-error "Cell separator must contain one or more spaces")
9335 (format "^ *\\| *\t *\\| \\{%d,\\}" separator)))
9336 ((stringp separator) (format "^ *\\|%s" separator))
9337 (t (error "Invalid cell separator"))))
9338 (while (re-search-forward re end t) (replace-match "| " t t)))
9339 (goto-char begin)
9340 (markdown-table-align)))
9343 ;;; ElDoc Support
9345 (defun markdown-eldoc-function ()
9346 "Return a helpful string when appropriate based on context.
9347 * Report URL when point is at a hidden URL.
9348 * Report language name when point is a code block with hidden markup."
9349 (cond
9350 ;; Hidden URL or reference for inline link
9351 ((and (or (thing-at-point-looking-at markdown-regex-link-inline)
9352 (thing-at-point-looking-at markdown-regex-link-reference))
9353 (or markdown-hide-urls markdown-hide-markup))
9354 (let* ((imagep (string-equal (match-string 1) "!"))
9355 (edit-keys (markdown--substitute-command-keys
9356 (if imagep
9357 "\\[markdown-insert-image]"
9358 "\\[markdown-insert-link]")))
9359 (edit-str (propertize edit-keys 'face 'font-lock-constant-face))
9360 (referencep (string-equal (match-string 5) "["))
9361 (object (if referencep "reference" "URL")))
9362 (format "Hidden %s (%s to edit): %s" object edit-str
9363 (if referencep
9364 (concat
9365 (propertize "[" 'face 'markdown-markup-face)
9366 (propertize (match-string-no-properties 6)
9367 'face 'markdown-reference-face)
9368 (propertize "]" 'face 'markdown-markup-face))
9369 (propertize (match-string-no-properties 6)
9370 'face 'markdown-url-face)))))
9371 ;; Hidden language name for fenced code blocks
9372 ((and (markdown-code-block-at-point-p)
9373 (not (get-text-property (point) 'markdown-pre))
9374 markdown-hide-markup)
9375 (let ((lang (save-excursion (markdown-code-block-lang))))
9376 (unless lang (setq lang "[unspecified]"))
9377 (format "Hidden code block language: %s (%s to toggle markup)"
9378 (propertize lang 'face 'markdown-language-keyword-face)
9379 (markdown--substitute-command-keys
9380 "\\[markdown-toggle-markup-hiding]"))))))
9383 ;;; Mode Definition ==========================================================
9385 (defun markdown-show-version ()
9386 "Show the version number in the minibuffer."
9387 (interactive)
9388 (message "markdown-mode, version %s" markdown-mode-version))
9390 (defun markdown-mode-info ()
9391 "Open the `markdown-mode' homepage."
9392 (interactive)
9393 (browse-url "https://jblevins.org/projects/markdown-mode/"))
9395 ;;;###autoload
9396 (define-derived-mode markdown-mode text-mode "Markdown"
9397 "Major mode for editing Markdown files."
9398 ;; Natural Markdown tab width
9399 (setq tab-width 4)
9400 ;; Comments
9401 (setq-local comment-start "<!-- ")
9402 (setq-local comment-end " -->")
9403 (setq-local comment-start-skip "<!--[ \t]*")
9404 (setq-local comment-column 0)
9405 (setq-local comment-auto-fill-only-comments nil)
9406 (setq-local comment-use-syntax t)
9407 ;; Syntax
9408 (add-hook 'syntax-propertize-extend-region-functions
9409 #'markdown-syntax-propertize-extend-region)
9410 (add-hook 'jit-lock-after-change-extend-region-functions
9411 #'markdown-font-lock-extend-region-function t t)
9412 (setq-local syntax-propertize-function #'markdown-syntax-propertize)
9413 (syntax-propertize (point-max)) ;; Propertize before hooks run, etc.
9414 ;; Font lock.
9415 (setq font-lock-defaults
9416 '(markdown-mode-font-lock-keywords
9417 nil nil nil nil
9418 (font-lock-multiline . t)
9419 (font-lock-syntactic-face-function . markdown-syntactic-face)
9420 (font-lock-extra-managed-props
9421 . (composition display invisible rear-nonsticky
9422 keymap help-echo mouse-face))))
9423 (if markdown-hide-markup
9424 (add-to-invisibility-spec 'markdown-markup)
9425 (remove-from-invisibility-spec 'markdown-markup))
9426 ;; Wiki links
9427 (markdown-setup-wiki-link-hooks)
9428 ;; Math mode
9429 (when markdown-enable-math (markdown-toggle-math t))
9430 ;; Add a buffer-local hook to reload after file-local variables are read
9431 (add-hook 'hack-local-variables-hook #'markdown-handle-local-variables nil t)
9432 ;; For imenu support
9433 (setq imenu-create-index-function
9434 (if markdown-nested-imenu-heading-index
9435 #'markdown-imenu-create-nested-index
9436 #'markdown-imenu-create-flat-index))
9437 ;; For menu support in XEmacs
9438 (easy-menu-add markdown-mode-menu markdown-mode-map)
9439 ;; Defun movement
9440 (setq-local beginning-of-defun-function #'markdown-beginning-of-defun)
9441 (setq-local end-of-defun-function #'markdown-end-of-defun)
9442 ;; Paragraph filling
9443 (setq-local fill-paragraph-function #'markdown-fill-paragraph)
9444 (setq-local paragraph-start
9445 ;; Should match start of lines that start or separate paragraphs
9446 (mapconcat #'identity
9448 "\f" ; starts with a literal line-feed
9449 "[ \t\f]*$" ; space-only line
9450 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9451 "[ \t]*[*+-][ \t]+" ; unordered list item
9452 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
9453 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
9454 "[ \t]*:[ \t]+" ; definition
9455 "^|" ; table or Pandoc line block
9457 "\\|"))
9458 (setq-local paragraph-separate
9459 ;; Should match lines that separate paragraphs without being
9460 ;; part of any paragraph:
9461 (mapconcat #'identity
9462 '("[ \t\f]*$" ; space-only line
9463 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9464 ;; The following is not ideal, but the Fill customization
9465 ;; options really only handle paragraph-starting prefixes,
9466 ;; not paragraph-ending suffixes:
9467 ".* $" ; line ending in two spaces
9468 "^#+"
9469 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
9470 "\\|"))
9471 (setq-local adaptive-fill-first-line-regexp "\\`[ \t]*[A-Z]?>[ \t]*?\\'")
9472 (setq-local adaptive-fill-regexp "\\s-*")
9473 (setq-local adaptive-fill-function #'markdown-adaptive-fill-function)
9474 (setq-local fill-forward-paragraph-function #'markdown-fill-forward-paragraph)
9475 ;; Outline mode
9476 (setq-local outline-regexp markdown-regex-header)
9477 (setq-local outline-level #'markdown-outline-level)
9478 ;; Cause use of ellipses for invisible text.
9479 (add-to-invisibility-spec '(outline . t))
9480 ;; ElDoc support
9481 (if (eval-when-compile (fboundp 'add-function))
9482 (add-function :before-until (local 'eldoc-documentation-function)
9483 #'markdown-eldoc-function)
9484 (setq-local eldoc-documentation-function #'markdown-eldoc-function))
9485 ;; Inhibiting line-breaking:
9486 ;; Separating out each condition into a separate function so that users can
9487 ;; override if desired (with remove-hook)
9488 (add-hook 'fill-nobreak-predicate
9489 #'markdown-line-is-reference-definition-p nil t)
9490 (add-hook 'fill-nobreak-predicate
9491 #'markdown-pipe-at-bol-p nil t)
9493 ;; Indentation
9494 (setq-local indent-line-function markdown-indent-function)
9496 ;; Flyspell
9497 (setq-local flyspell-generic-check-word-predicate
9498 #'markdown-flyspell-check-word-p)
9500 ;; Electric quoting
9501 (add-hook 'electric-quote-inhibit-functions
9502 #'markdown--inhibit-electric-quote nil :local)
9504 ;; Backwards compatibility with markdown-css-path
9505 (when (boundp 'markdown-css-path)
9506 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
9507 (add-to-list 'markdown-css-paths markdown-css-path))
9509 ;; Prepare hooks for XEmacs compatibility
9510 (when (featurep 'xemacs)
9511 (make-local-hook 'after-change-functions)
9512 (make-local-hook 'font-lock-extend-region-functions)
9513 (make-local-hook 'window-configuration-change-hook))
9515 ;; Make checkboxes buttons
9516 (when markdown-make-gfm-checkboxes-buttons
9517 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
9518 (add-hook 'after-change-functions #'markdown-gfm-checkbox-after-change-function t t)
9519 (add-hook 'change-major-mode-hook #'markdown-remove-gfm-checkbox-overlays t t))
9521 ;; edit-indirect
9522 (add-hook 'edit-indirect-after-commit-functions
9523 #'markdown--edit-indirect-after-commit-function
9524 nil 'local)
9526 ;; Marginalized headings
9527 (when markdown-marginalize-headers
9528 (add-hook 'window-configuration-change-hook
9529 #'markdown-marginalize-update-current nil t))
9531 ;; add live preview export hook
9532 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
9533 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
9535 ;;;###autoload
9536 (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode) t)
9537 ;;;###autoload
9538 (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode) t)
9541 ;;; GitHub Flavored Markdown Mode ============================================
9543 (defvar gfm-mode-hook nil
9544 "Hook run when entering GFM mode.")
9546 ;;;###autoload
9547 (define-derived-mode gfm-mode markdown-mode "GFM"
9548 "Major mode for editing GitHub Flavored Markdown files."
9549 (setq markdown-link-space-sub-char "-")
9550 (setq markdown-wiki-link-search-subdirectories t)
9551 (setq-local markdown-table-at-point-p-function 'gfm--table-at-point-p)
9552 (markdown-gfm-parse-buffer-for-languages))
9554 (define-obsolete-variable-alias
9555 'gfm-font-lock-keywords
9556 'markdown-mode-font-lock-keywords "v2.4")
9559 ;;; Viewing modes
9561 (defcustom markdown-hide-markup-in-view-modes t
9562 "Enable hidden markup mode in `markdown-view-mode' and `gfm-view-mode'."
9563 :group 'markdown
9564 :type 'boolean
9565 :safe 'booleanp)
9567 (defvar markdown-view-mode-map
9568 (let ((map (make-sparse-keymap)))
9569 (define-key map (kbd "p") #'markdown-outline-previous)
9570 (define-key map (kbd "n") #'markdown-outline-next)
9571 (define-key map (kbd "f") #'markdown-outline-next-same-level)
9572 (define-key map (kbd "b") #'markdown-outline-previous-same-level)
9573 (define-key map (kbd "u") #'markdown-outline-up)
9574 (define-key map (kbd "DEL") #'scroll-down-command)
9575 (define-key map (kbd "SPC") #'scroll-up-command)
9576 (define-key map (kbd ">") #'end-of-buffer)
9577 (define-key map (kbd "<") #'beginning-of-buffer)
9578 (define-key map (kbd "q") #'kill-this-buffer)
9579 (define-key map (kbd "?") #'describe-mode)
9580 map)
9581 "Keymap for `markdown-view-mode'.")
9583 ;;;###autoload
9584 (define-derived-mode markdown-view-mode markdown-mode "Markdown-View"
9585 "Major mode for viewing Markdown content."
9586 (setq-local markdown-hide-markup markdown-hide-markup-in-view-modes)
9587 (read-only-mode 1))
9589 (defvar gfm-view-mode-map
9590 markdown-view-mode-map
9591 "Keymap for `gfm-view-mode'.")
9593 ;;;###autoload
9594 (define-derived-mode gfm-view-mode gfm-mode "GFM-View"
9595 "Major mode for viewing GitHub Flavored Markdown content."
9596 (setq-local markdown-hide-markup markdown-hide-markup-in-view-modes)
9597 (read-only-mode 1))
9600 ;;; Live Preview Mode ============================================
9601 ;;;###autoload
9602 (define-minor-mode markdown-live-preview-mode
9603 "Toggle native previewing on save for a specific markdown file."
9604 :lighter " MD-Preview"
9605 (if markdown-live-preview-mode
9606 (if (markdown-live-preview-get-filename)
9607 (markdown-display-buffer-other-window (markdown-live-preview-export))
9608 (markdown-live-preview-mode -1)
9609 (user-error "Buffer %s does not visit a file" (current-buffer)))
9610 (markdown-live-preview-remove)))
9613 (provide 'markdown-mode)
9615 ;; Local Variables:
9616 ;; indent-tabs-mode: nil
9617 ;; coding: utf-8
9618 ;; End:
9619 ;;; markdown-mode.el ends here