Added 26.1 release
[markdown-mode.git] / markdown-mode.el
blob642608f2d40d54cad556a5bac0d81ec3649e1ffd
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-sort
5815 (cl-set-difference
5816 (markdown-get-defined-references) (markdown-get-all-refs)
5817 :test (lambda (e1 e2) (equal (car e1) e2)))
5818 #'< :key #'cdr))
5820 (defmacro defun-markdown-buffer (name docstring)
5821 "Define a function to name and return a buffer.
5823 By convention, NAME must be a name of a string constant with
5824 %buffer% placeholder used to name the buffer, and will also be
5825 used as a name of the function defined.
5827 DOCSTRING will be used as the first part of the docstring."
5828 `(defun ,name (&optional buffer-name)
5829 ,(concat docstring "\n\nBUFFER-NAME is the name of the main buffer being visited.")
5830 (or buffer-name (setq buffer-name (buffer-name)))
5831 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
5832 "%buffer%" buffer-name
5833 ,name))))
5834 (with-current-buffer refbuf
5835 (when view-mode
5836 (View-exit-and-edit))
5837 (use-local-map button-buffer-map)
5838 (erase-buffer))
5839 refbuf)))
5841 (defconst markdown-reference-check-buffer
5842 "*Undefined references for %buffer%*"
5843 "Pattern for name of buffer for listing undefined references.
5844 The string %buffer% will be replaced by the corresponding
5845 `markdown-mode' buffer name.")
5847 (defun-markdown-buffer
5848 markdown-reference-check-buffer
5849 "Name and return buffer for reference checking.")
5851 (defconst markdown-unused-references-buffer
5852 "*Unused references for %buffer%*"
5853 "Pattern for name of buffer for listing unused references.
5854 The string %buffer% will be replaced by the corresponding
5855 `markdown-mode' buffer name.")
5857 (defun-markdown-buffer
5858 markdown-unused-references-buffer
5859 "Name and return buffer for unused reference checking.")
5861 (defconst markdown-reference-links-buffer
5862 "*Reference links for %buffer%*"
5863 "Pattern for name of buffer for listing references.
5864 The string %buffer% will be replaced by the corresponding buffer name.")
5866 (defun-markdown-buffer
5867 markdown-reference-links-buffer
5868 "Name, setup, and return a buffer for listing links.")
5870 ;; Add an empty Markdown reference definition to buffer
5871 ;; specified in the 'target-buffer property. The reference name is
5872 ;; the button's label.
5873 (define-button-type 'markdown-undefined-reference-button
5874 'help-echo "mouse-1, RET: create definition for undefined reference"
5875 'follow-link t
5876 'face 'bold
5877 'action (lambda (b)
5878 (let ((buffer (button-get b 'target-buffer))
5879 (line (button-get b 'target-line))
5880 (label (button-label b)))
5881 (switch-to-buffer-other-window buffer)
5882 (goto-char (point-min))
5883 (forward-line line)
5884 (markdown-insert-reference-definition label)
5885 (markdown-check-refs t))))
5887 ;; Jump to line in buffer specified by 'target-buffer property.
5888 ;; Line number is button's 'target-line property.
5889 (define-button-type 'markdown-goto-line-button
5890 'help-echo "mouse-1, RET: go to line"
5891 'follow-link t
5892 'face 'italic
5893 'action (lambda (b)
5894 (switch-to-buffer-other-window (button-get b 'target-buffer))
5895 ;; use call-interactively to silence compiler
5896 (let ((current-prefix-arg (button-get b 'target-line)))
5897 (call-interactively 'goto-line))))
5899 ;; Kill a line in buffer specified by 'target-buffer property.
5900 ;; Line number is button's 'target-line property.
5901 (define-button-type 'markdown-kill-line-button
5902 'help-echo "mouse-1, RET: kill line"
5903 'follow-link t
5904 'face 'italic
5905 'action (lambda (b)
5906 (switch-to-buffer-other-window (button-get b 'target-buffer))
5907 ;; use call-interactively to silence compiler
5908 (let ((current-prefix-arg (button-get b 'target-line)))
5909 (call-interactively 'goto-line))
5910 (kill-line 1)
5911 (markdown-unused-refs t)))
5913 ;; Jumps to a particular link at location given by 'target-char
5914 ;; property in buffer given by 'target-buffer property.
5915 (define-button-type 'markdown-location-button
5916 'help-echo "mouse-1, RET: jump to location of link"
5917 'follow-link t
5918 'face 'bold
5919 'action (lambda (b)
5920 (let ((target (button-get b 'target-buffer))
5921 (loc (button-get b 'target-char)))
5922 (kill-buffer-and-window)
5923 (switch-to-buffer target)
5924 (goto-char loc))))
5926 (defun markdown-insert-undefined-reference-button (reference oldbuf)
5927 "Insert a button for creating REFERENCE in buffer OLDBUF.
5928 REFERENCE should be a list of the form (reference . occurrences),
5929 as returned by `markdown-get-undefined-refs'."
5930 (let ((label (car reference)))
5931 ;; Create a reference button
5932 (insert-button label
5933 :type 'markdown-undefined-reference-button
5934 'target-buffer oldbuf
5935 'target-line (cdr (car (cdr reference))))
5936 (insert " (")
5937 (dolist (occurrence (cdr reference))
5938 (let ((line (cdr occurrence)))
5939 ;; Create a line number button
5940 (insert-button (number-to-string line)
5941 :type 'markdown-goto-line-button
5942 'target-buffer oldbuf
5943 'target-line line)
5944 (insert " ")))
5945 (delete-char -1)
5946 (insert ")")
5947 (newline)))
5949 (defun markdown-insert-unused-reference-button (reference oldbuf)
5950 "Insert a button for creating REFERENCE in buffer OLDBUF.
5951 REFERENCE must be a pair of (ref . line-number)."
5952 (let ((label (car reference))
5953 (line (cdr reference)))
5954 ;; Create a reference button
5955 (insert-button label
5956 :type 'markdown-goto-line-button
5957 'face 'bold
5958 'target-buffer oldbuf
5959 'target-line line)
5960 (insert (format " (%d) [" line))
5961 (insert-button "X"
5962 :type 'markdown-kill-line-button
5963 'face 'bold
5964 'target-buffer oldbuf
5965 'target-line line)
5966 (insert "]")
5967 (newline)))
5969 (defun markdown-insert-link-button (link oldbuf)
5970 "Insert a button for jumping to LINK in buffer OLDBUF.
5971 LINK should be a list of the form (text char line) containing
5972 the link text, location, and line number."
5973 (let ((label (cl-first link))
5974 (char (cl-second link))
5975 (line (cl-third link)))
5976 ;; Create a reference button
5977 (insert-button label
5978 :type 'markdown-location-button
5979 'target-buffer oldbuf
5980 'target-char char)
5981 (insert (format " (line %d)\n" line))))
5983 (defun markdown-reference-goto-link (&optional reference)
5984 "Jump to the location of the first use of REFERENCE."
5985 (interactive)
5986 (unless reference
5987 (if (thing-at-point-looking-at markdown-regex-reference-definition)
5988 (setq reference (match-string-no-properties 2))
5989 (user-error "No reference definition at point")))
5990 (let ((links (markdown-reference-find-links reference)))
5991 (cond ((= (length links) 1)
5992 (goto-char (cadr (car links))))
5993 ((> (length links) 1)
5994 (let ((oldbuf (current-buffer))
5995 (linkbuf (markdown-reference-links-buffer)))
5996 (with-current-buffer linkbuf
5997 (insert "Links using reference " reference ":\n\n")
5998 (dolist (link (reverse links))
5999 (markdown-insert-link-button link oldbuf)))
6000 (view-buffer-other-window linkbuf)
6001 (goto-char (point-min))
6002 (forward-line 2)))
6004 (error "No links for reference %s" reference)))))
6006 (defmacro defun-markdown-ref-checker
6007 (name docstring checker-function buffer-function none-message buffer-header insert-reference)
6008 "Define a function NAME acting on result of CHECKER-FUNCTION.
6010 DOCSTRING is used as a docstring for the defined function.
6012 BUFFER-FUNCTION should name and return an auxiliary buffer to put
6013 results in.
6015 NONE-MESSAGE is used when CHECKER-FUNCTION returns no results.
6017 BUFFER-HEADER is put into the auxiliary buffer first, followed by
6018 calling INSERT-REFERENCE for each element in the list returned by
6019 CHECKER-FUNCTION."
6020 `(defun ,name (&optional silent)
6021 ,(concat
6022 docstring
6023 "\n\nIf SILENT is non-nil, do not message anything when no
6024 such references found.")
6025 (interactive "P")
6026 (when (not (memq major-mode '(markdown-mode gfm-mode)))
6027 (user-error "Not available in current mode"))
6028 (let ((oldbuf (current-buffer))
6029 (refs (,checker-function))
6030 (refbuf (,buffer-function)))
6031 (if (null refs)
6032 (progn
6033 (when (not silent)
6034 (message ,none-message))
6035 (kill-buffer refbuf))
6036 (with-current-buffer refbuf
6037 (insert ,buffer-header)
6038 (dolist (ref refs)
6039 (,insert-reference ref oldbuf))
6040 (view-buffer-other-window refbuf)
6041 (goto-char (point-min))
6042 (forward-line 2))))))
6044 (defun-markdown-ref-checker
6045 markdown-check-refs
6046 "Show all undefined Markdown references in current `markdown-mode' buffer.
6048 Links which have empty reference definitions are considered to be
6049 defined."
6050 markdown-get-undefined-refs
6051 markdown-reference-check-buffer
6052 "No undefined references found"
6053 "The following references are undefined:\n\n"
6054 markdown-insert-undefined-reference-button)
6057 (defun-markdown-ref-checker
6058 markdown-unused-refs
6059 "Show all unused Markdown references in current `markdown-mode' buffer."
6060 markdown-get-unused-refs
6061 markdown-unused-references-buffer
6062 "No unused references found"
6063 "The following references are unused:\n\n"
6064 markdown-insert-unused-reference-button)
6068 ;;; Lists =====================================================================
6070 (defun markdown-insert-list-item (&optional arg)
6071 "Insert a new list item.
6072 If the point is inside unordered list, insert a bullet mark. If
6073 the point is inside ordered list, insert the next number followed
6074 by a period. Use the previous list item to determine the amount
6075 of whitespace to place before and after list markers.
6077 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
6078 decrease the indentation by one level.
6080 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
6081 increase the indentation by one level."
6082 (interactive "p")
6083 (let (bounds cur-indent marker indent new-indent new-loc)
6084 (save-match-data
6085 ;; Look for a list item on current or previous non-blank line
6086 (save-excursion
6087 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
6088 (not (bobp))
6089 (markdown-cur-line-blank-p))
6090 (forward-line -1)))
6091 (when bounds
6092 (cond ((save-excursion
6093 (skip-chars-backward " \t")
6094 (looking-at-p markdown-regex-list))
6095 (beginning-of-line)
6096 (insert "\n")
6097 (forward-line -1))
6098 ((not (markdown-cur-line-blank-p))
6099 (newline)))
6100 (setq new-loc (point)))
6101 ;; Look ahead for a list item on next non-blank line
6102 (unless bounds
6103 (save-excursion
6104 (while (and (null bounds)
6105 (not (eobp))
6106 (markdown-cur-line-blank-p))
6107 (forward-line)
6108 (setq bounds (markdown-cur-list-item-bounds))))
6109 (when bounds
6110 (setq new-loc (point))
6111 (unless (markdown-cur-line-blank-p)
6112 (newline))))
6113 (if (not bounds)
6114 ;; When not in a list, start a new unordered one
6115 (progn
6116 (unless (markdown-cur-line-blank-p)
6117 (insert "\n"))
6118 (insert markdown-unordered-list-item-prefix))
6119 ;; Compute indentation and marker for new list item
6120 (setq cur-indent (nth 2 bounds))
6121 (setq marker (nth 4 bounds))
6122 ;; If current item is a GFM checkbox, insert new unchecked checkbox.
6123 (when (nth 5 bounds)
6124 (setq marker
6125 (concat marker
6126 (replace-regexp-in-string "[Xx]" " " (nth 5 bounds)))))
6127 (cond
6128 ;; Dedent: decrement indentation, find previous marker.
6129 ((= arg 4)
6130 (setq indent (max (- cur-indent 4) 0))
6131 (let ((prev-bounds
6132 (save-excursion
6133 (goto-char (nth 0 bounds))
6134 (when (markdown-up-list)
6135 (markdown-cur-list-item-bounds)))))
6136 (when prev-bounds
6137 (setq marker (nth 4 prev-bounds)))))
6138 ;; Indent: increment indentation by 4, use same marker.
6139 ((= arg 16) (setq indent (+ cur-indent 4)))
6140 ;; Same level: keep current indentation and marker.
6141 (t (setq indent cur-indent)))
6142 (setq new-indent (make-string indent 32))
6143 (goto-char new-loc)
6144 (cond
6145 ;; Ordered list
6146 ((string-match-p "[0-9]" marker)
6147 (if (= arg 16) ;; starting a new column indented one more level
6148 (insert (concat new-indent "1. "))
6149 ;; Don't use previous match-data
6150 (set-match-data nil)
6151 ;; travel up to the last item and pick the correct number. If
6152 ;; the argument was nil, "new-indent = cur-indent" is the same,
6153 ;; so we don't need special treatment. Neat.
6154 (save-excursion
6155 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
6156 (>= (forward-line -1) 0))))
6157 (let* ((old-prefix (match-string 1))
6158 (old-spacing (match-string 2))
6159 (new-prefix (if old-prefix
6160 (int-to-string (1+ (string-to-number old-prefix)))
6161 "1"))
6162 (space-adjust (- (length old-prefix) (length new-prefix)))
6163 (new-spacing (if (and (match-string 2)
6164 (not (string-match-p "\t" old-spacing))
6165 (< space-adjust 0)
6166 (> space-adjust (- 1 (length (match-string 2)))))
6167 (substring (match-string 2) 0 space-adjust)
6168 (or old-spacing ". "))))
6169 (insert (concat new-indent new-prefix new-spacing)))))
6170 ;; Unordered list, GFM task list, or ordered list with hash mark
6171 ((string-match-p "[\\*\\+-]\\|#\\." marker)
6172 (insert new-indent marker))))
6173 ;; Propertize the newly inserted list item now
6174 (markdown-syntax-propertize-list-items (point-at-bol) (point-at-eol)))))
6176 (defun markdown-move-list-item-up ()
6177 "Move the current list item up in the list when possible.
6178 In nested lists, move child items with the parent item."
6179 (interactive)
6180 (let (cur prev old)
6181 (when (setq cur (markdown-cur-list-item-bounds))
6182 (setq old (point))
6183 (goto-char (nth 0 cur))
6184 (if (markdown-prev-list-item (nth 3 cur))
6185 (progn
6186 (setq prev (markdown-cur-list-item-bounds))
6187 (condition-case nil
6188 (progn
6189 (transpose-regions (nth 0 prev) (nth 1 prev)
6190 (nth 0 cur) (nth 1 cur) t)
6191 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
6192 ;; Catch error in case regions overlap.
6193 (error (goto-char old))))
6194 (goto-char old)))))
6196 (defun markdown-move-list-item-down ()
6197 "Move the current list item down in the list when possible.
6198 In nested lists, move child items with the parent item."
6199 (interactive)
6200 (let (cur next old)
6201 (when (setq cur (markdown-cur-list-item-bounds))
6202 (setq old (point))
6203 (if (markdown-next-list-item (nth 3 cur))
6204 (progn
6205 (setq next (markdown-cur-list-item-bounds))
6206 (condition-case nil
6207 (progn
6208 (transpose-regions (nth 0 cur) (nth 1 cur)
6209 (nth 0 next) (nth 1 next) nil)
6210 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
6211 ;; Catch error in case regions overlap.
6212 (error (goto-char old))))
6213 (goto-char old)))))
6215 (defun markdown-demote-list-item (&optional bounds)
6216 "Indent (or demote) the current list item.
6217 Optionally, BOUNDS of the current list item may be provided if available.
6218 In nested lists, demote child items as well."
6219 (interactive)
6220 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6221 (save-excursion
6222 (let* ((item-start (set-marker (make-marker) (nth 0 bounds)))
6223 (item-end (set-marker (make-marker) (nth 1 bounds)))
6224 (list-start (progn (markdown-beginning-of-list)
6225 (set-marker (make-marker) (point))))
6226 (list-end (progn (markdown-end-of-list)
6227 (set-marker (make-marker) (point)))))
6228 (goto-char item-start)
6229 (while (< (point) item-end)
6230 (unless (markdown-cur-line-blank-p)
6231 (insert (make-string markdown-list-indent-width ? )))
6232 (forward-line))
6233 (markdown-syntax-propertize-list-items list-start list-end)))))
6235 (defun markdown-promote-list-item (&optional bounds)
6236 "Unindent (or promote) the current list item.
6237 Optionally, BOUNDS of the current list item may be provided if available.
6238 In nested lists, demote child items as well."
6239 (interactive)
6240 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6241 (save-excursion
6242 (save-match-data
6243 (let ((item-start (set-marker (make-marker) (nth 0 bounds)))
6244 (item-end (set-marker (make-marker) (nth 1 bounds)))
6245 (list-start (progn (markdown-beginning-of-list)
6246 (set-marker (make-marker) (point))))
6247 (list-end (progn (markdown-end-of-list)
6248 (set-marker (make-marker) (point))))
6249 num regexp)
6250 (goto-char item-start)
6251 (when (looking-at (format "^[ ]\\{1,%d\\}"
6252 markdown-list-indent-width))
6253 (setq num (- (match-end 0) (match-beginning 0)))
6254 (setq regexp (format "^[ ]\\{1,%d\\}" num))
6255 (while (and (< (point) item-end)
6256 (re-search-forward regexp item-end t))
6257 (replace-match "" nil nil)
6258 (forward-line))
6259 (markdown-syntax-propertize-list-items list-start list-end)))))))
6261 (defun markdown-cleanup-list-numbers-level (&optional pfx)
6262 "Update the numbering for level PFX (as a string of spaces).
6264 Assume that the previously found match was for a numbered item in
6265 a list."
6266 (let ((cpfx pfx)
6267 (idx 0)
6268 (continue t)
6269 (step t)
6270 (sep nil))
6271 (while (and continue (not (eobp)))
6272 (setq step t)
6273 (cond
6274 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
6275 (setq cpfx (match-string-no-properties 1))
6276 (cond
6277 ((string= cpfx pfx)
6278 (save-excursion
6279 (replace-match
6280 (concat pfx (number-to-string (setq idx (1+ idx))) ". ")))
6281 (setq sep nil))
6282 ;; indented a level
6283 ((string< pfx cpfx)
6284 (setq sep (markdown-cleanup-list-numbers-level cpfx))
6285 (setq step nil))
6286 ;; exit the loop
6288 (setq step nil)
6289 (setq continue nil))))
6291 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
6292 (setq cpfx (match-string-no-properties 1))
6293 (cond
6294 ;; reset if separated before
6295 ((string= cpfx pfx) (when sep (setq idx 0)))
6296 ((string< cpfx pfx)
6297 (setq step nil)
6298 (setq continue nil))))
6299 (t (setq sep t)))
6301 (when step
6302 (beginning-of-line)
6303 (setq continue (= (forward-line) 0))))
6304 sep))
6306 (defun markdown-cleanup-list-numbers ()
6307 "Update the numbering of ordered lists."
6308 (interactive)
6309 (save-excursion
6310 (goto-char (point-min))
6311 (markdown-cleanup-list-numbers-level "")))
6314 ;;; Movement ==================================================================
6316 (defun markdown-beginning-of-defun (&optional arg)
6317 "`beginning-of-defun-function' for Markdown.
6318 This is used to find the beginning of the defun and should behave
6319 like ‘beginning-of-defun’, returning non-nil if it found the
6320 beginning of a defun. It moves the point backward, right before a
6321 heading which defines a defun. When ARG is non-nil, repeat that
6322 many times. When ARG is negative, move forward to the ARG-th
6323 following section."
6324 (or arg (setq arg 1))
6325 (when (< arg 0) (end-of-line))
6326 ;; Adjust position for setext headings.
6327 (when (and (thing-at-point-looking-at markdown-regex-header-setext)
6328 (not (= (point) (match-beginning 0)))
6329 (not (markdown-code-block-at-point-p)))
6330 (goto-char (match-end 0)))
6331 (let (found)
6332 ;; Move backward with positive argument.
6333 (while (and (not (bobp)) (> arg 0))
6334 (setq found nil)
6335 (while (and (not found)
6336 (not (bobp))
6337 (re-search-backward markdown-regex-header nil 'move))
6338 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6339 (setq found (match-beginning 0)))
6340 (setq arg (1- arg)))
6341 ;; Move forward with negative argument.
6342 (while (and (not (eobp)) (< arg 0))
6343 (setq found nil)
6344 (while (and (not found)
6345 (not (eobp))
6346 (re-search-forward markdown-regex-header nil 'move))
6347 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6348 (setq found (match-beginning 0)))
6349 (setq arg (1+ arg)))
6350 (when found
6351 (beginning-of-line)
6352 t)))
6354 (defun markdown-end-of-defun ()
6355 "`end-of-defun-function’ for Markdown.
6356 This is used to find the end of the defun at point.
6357 It is called with no argument, right after calling ‘beginning-of-defun-raw’,
6358 so it can assume that point is at the beginning of the defun body.
6359 It should move point to the first position after the defun."
6360 (or (eobp) (forward-char 1))
6361 (let (found)
6362 (while (and (not found)
6363 (not (eobp))
6364 (re-search-forward markdown-regex-header nil 'move))
6365 (when (not (markdown-code-block-at-pos (match-beginning 0)))
6366 (setq found (match-beginning 0))))
6367 (when found
6368 (goto-char found)
6369 (skip-syntax-backward "-"))))
6371 (make-obsolete 'markdown-beginning-of-block 'markdown-beginning-of-text-block "v2.2")
6373 (defun markdown-beginning-of-text-block ()
6374 "Move backward to previous beginning of a plain text block.
6375 This function simply looks for blank lines without considering
6376 the surrounding context in light of Markdown syntax. For that, see
6377 `markdown-backward-block'."
6378 (interactive)
6379 (let ((start (point)))
6380 (if (re-search-backward markdown-regex-block-separator nil t)
6381 (goto-char (match-end 0))
6382 (goto-char (point-min)))
6383 (when (and (= start (point)) (not (bobp)))
6384 (forward-line -1)
6385 (if (re-search-backward markdown-regex-block-separator nil t)
6386 (goto-char (match-end 0))
6387 (goto-char (point-min))))))
6389 (make-obsolete 'markdown-end-of-block 'markdown-end-of-text-block "v2.2")
6391 (defun markdown-end-of-text-block ()
6392 "Move forward to next beginning of a plain text block.
6393 This function simply looks for blank lines without considering
6394 the surrounding context in light of Markdown syntax. For that, see
6395 `markdown-forward-block'."
6396 (interactive)
6397 (beginning-of-line)
6398 (skip-chars-forward " \t\n")
6399 (when (= (point) (point-min))
6400 (forward-char))
6401 (if (re-search-forward markdown-regex-block-separator nil t)
6402 (goto-char (match-end 0))
6403 (goto-char (point-max)))
6404 (skip-chars-backward " \t\n")
6405 (forward-line))
6407 (defun markdown-backward-paragraph (&optional arg)
6408 "Move the point to the start of the current paragraph.
6409 With argument ARG, do it ARG times; a negative argument ARG = -N
6410 means move forward N blocks."
6411 (interactive "^p")
6412 (or arg (setq arg 1))
6413 (if (< arg 0)
6414 (markdown-forward-paragraph (- arg))
6415 (dotimes (_ arg)
6416 ;; Skip over whitespace in between paragraphs when moving backward.
6417 (skip-chars-backward " \t\n")
6418 (beginning-of-line)
6419 ;; Skip over code block endings.
6420 (when (markdown-range-properties-exist
6421 (point-at-bol) (point-at-eol)
6422 '(markdown-gfm-block-end
6423 markdown-tilde-fence-end))
6424 (forward-line -1))
6425 ;; Skip over blank lines inside blockquotes.
6426 (while (and (not (eobp))
6427 (looking-at markdown-regex-blockquote)
6428 (= (length (match-string 3)) 0))
6429 (forward-line -1))
6430 ;; Proceed forward based on the type of block of paragraph.
6431 (let (bounds skip)
6432 (cond
6433 ;; Blockquotes
6434 ((looking-at markdown-regex-blockquote)
6435 (while (and (not (bobp))
6436 (looking-at markdown-regex-blockquote)
6437 (> (length (match-string 3)) 0)) ;; not blank
6438 (forward-line -1))
6439 (forward-line))
6440 ;; List items
6441 ((setq bounds (markdown-cur-list-item-bounds))
6442 (goto-char (nth 0 bounds)))
6443 ;; Other
6445 (while (and (not (bobp))
6446 (not skip)
6447 (not (markdown-cur-line-blank-p))
6448 (not (looking-at markdown-regex-blockquote))
6449 (not (markdown-range-properties-exist
6450 (point-at-bol) (point-at-eol)
6451 '(markdown-gfm-block-end
6452 markdown-tilde-fence-end))))
6453 (setq skip (markdown-range-properties-exist
6454 (point-at-bol) (point-at-eol)
6455 '(markdown-gfm-block-begin
6456 markdown-tilde-fence-begin)))
6457 (forward-line -1))
6458 (unless (bobp)
6459 (forward-line 1))))))))
6461 (defun markdown-forward-paragraph (&optional arg)
6462 "Move forward to the next end of a paragraph.
6463 With argument ARG, do it ARG times; a negative argument ARG = -N
6464 means move backward N blocks."
6465 (interactive "^p")
6466 (or arg (setq arg 1))
6467 (if (< arg 0)
6468 (markdown-backward-paragraph (- arg))
6469 (dotimes (_ arg)
6470 ;; Skip whitespace in between paragraphs.
6471 (when (markdown-cur-line-blank-p)
6472 (skip-syntax-forward "-")
6473 (beginning-of-line))
6474 ;; Proceed forward based on the type of block.
6475 (let (bounds skip)
6476 (cond
6477 ;; Blockquotes
6478 ((looking-at markdown-regex-blockquote)
6479 ;; Skip over blank lines inside blockquotes.
6480 (while (and (not (eobp))
6481 (looking-at markdown-regex-blockquote)
6482 (= (length (match-string 3)) 0))
6483 (forward-line))
6484 ;; Move to end of quoted text block
6485 (while (and (not (eobp))
6486 (looking-at markdown-regex-blockquote)
6487 (> (length (match-string 3)) 0)) ;; not blank
6488 (forward-line)))
6489 ;; List items
6490 ((and (markdown-cur-list-item-bounds)
6491 (setq bounds (markdown-next-list-item-bounds)))
6492 (goto-char (nth 0 bounds)))
6493 ;; Other
6495 (forward-line)
6496 (while (and (not (eobp))
6497 (not skip)
6498 (not (markdown-cur-line-blank-p))
6499 (not (looking-at markdown-regex-blockquote))
6500 (not (markdown-range-properties-exist
6501 (point-at-bol) (point-at-eol)
6502 '(markdown-gfm-block-begin
6503 markdown-tilde-fence-begin))))
6504 (setq skip (markdown-range-properties-exist
6505 (point-at-bol) (point-at-eol)
6506 '(markdown-gfm-block-end
6507 markdown-tilde-fence-end)))
6508 (forward-line))))))))
6510 (defun markdown-backward-block (&optional arg)
6511 "Move the point to the start of the current Markdown block.
6512 Moves across complete code blocks, list items, and blockquotes,
6513 but otherwise stops at blank lines, headers, and horizontal
6514 rules. With argument ARG, do it ARG times; a negative argument
6515 ARG = -N means move forward N blocks."
6516 (interactive "^p")
6517 (or arg (setq arg 1))
6518 (if (< arg 0)
6519 (markdown-forward-block (- arg))
6520 (dotimes (_ arg)
6521 ;; Skip over whitespace in between blocks when moving backward,
6522 ;; unless at a block boundary with no whitespace.
6523 (skip-syntax-backward "-")
6524 (beginning-of-line)
6525 ;; Proceed forward based on the type of block.
6526 (cond
6527 ;; Code blocks
6528 ((and (markdown-code-block-at-pos (point)) ;; this line
6529 (markdown-code-block-at-pos (point-at-bol 0))) ;; previous line
6530 (forward-line -1)
6531 (while (and (markdown-code-block-at-point-p) (not (bobp)))
6532 (forward-line -1))
6533 (forward-line))
6534 ;; Headings
6535 ((markdown-heading-at-point)
6536 (goto-char (match-beginning 0)))
6537 ;; Horizontal rules
6538 ((looking-at markdown-regex-hr))
6539 ;; Blockquotes
6540 ((looking-at markdown-regex-blockquote)
6541 (forward-line -1)
6542 (while (and (looking-at markdown-regex-blockquote)
6543 (not (bobp)))
6544 (forward-line -1))
6545 (forward-line))
6546 ;; List items
6547 ((markdown-cur-list-item-bounds)
6548 (markdown-beginning-of-list))
6549 ;; Other
6551 ;; Move forward in case it is a one line regular paragraph.
6552 (unless (markdown-next-line-blank-p)
6553 (forward-line))
6554 (unless (markdown-prev-line-blank-p)
6555 (markdown-backward-paragraph)))))))
6557 (defun markdown-forward-block (&optional arg)
6558 "Move forward to the next end of a Markdown block.
6559 Moves across complete code blocks, list items, and blockquotes,
6560 but otherwise stops at blank lines, headers, and horizontal
6561 rules. With argument ARG, do it ARG times; a negative argument
6562 ARG = -N means move backward N blocks."
6563 (interactive "^p")
6564 (or arg (setq arg 1))
6565 (if (< arg 0)
6566 (markdown-backward-block (- arg))
6567 (dotimes (_ arg)
6568 ;; Skip over whitespace in between blocks when moving forward.
6569 (if (markdown-cur-line-blank-p)
6570 (skip-syntax-forward "-")
6571 (beginning-of-line))
6572 ;; Proceed forward based on the type of block.
6573 (cond
6574 ;; Code blocks
6575 ((markdown-code-block-at-point-p)
6576 (forward-line)
6577 (while (and (markdown-code-block-at-point-p) (not (eobp)))
6578 (forward-line)))
6579 ;; Headings
6580 ((looking-at markdown-regex-header)
6581 (goto-char (or (match-end 4) (match-end 2) (match-end 3)))
6582 (forward-line))
6583 ;; Horizontal rules
6584 ((looking-at markdown-regex-hr)
6585 (forward-line))
6586 ;; Blockquotes
6587 ((looking-at markdown-regex-blockquote)
6588 (forward-line)
6589 (while (and (looking-at markdown-regex-blockquote) (not (eobp)))
6590 (forward-line)))
6591 ;; List items
6592 ((markdown-cur-list-item-bounds)
6593 (markdown-end-of-list)
6594 (forward-line))
6595 ;; Other
6596 (t (markdown-forward-paragraph))))
6597 (skip-syntax-backward "-")
6598 (unless (eobp)
6599 (forward-char 1))))
6601 (defun markdown-backward-page (&optional count)
6602 "Move backward to boundary of the current toplevel section.
6603 With COUNT, repeat, or go forward if negative."
6604 (interactive "p")
6605 (or count (setq count 1))
6606 (if (< count 0)
6607 (markdown-forward-page (- count))
6608 (skip-syntax-backward "-")
6609 (or (markdown-back-to-heading-over-code-block t t)
6610 (goto-char (point-min)))
6611 (when (looking-at markdown-regex-header)
6612 (let ((level (markdown-outline-level)))
6613 (when (> level 1) (markdown-up-heading level))
6614 (when (> count 1)
6615 (condition-case nil
6616 (markdown-backward-same-level (1- count))
6617 (error (goto-char (point-min)))))))))
6619 (defun markdown-forward-page (&optional count)
6620 "Move forward to boundary of the current toplevel section.
6621 With COUNT, repeat, or go backward if negative."
6622 (interactive "p")
6623 (or count (setq count 1))
6624 (if (< count 0)
6625 (markdown-backward-page (- count))
6626 (if (markdown-back-to-heading-over-code-block t t)
6627 (let ((level (markdown-outline-level)))
6628 (when (> level 1) (markdown-up-heading level))
6629 (condition-case nil
6630 (markdown-forward-same-level count)
6631 (error (goto-char (point-max)))))
6632 (markdown-next-visible-heading 1))))
6634 (defun markdown-next-link ()
6635 "Jump to next inline, reference, or wiki link.
6636 If successful, return point. Otherwise, return nil.
6637 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
6638 (interactive)
6639 (let ((opoint (point)))
6640 (when (or (markdown-link-p) (markdown-wiki-link-p))
6641 ;; At a link already, move past it.
6642 (goto-char (+ (match-end 0) 1)))
6643 ;; Search for the next wiki link and move to the beginning.
6644 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t)
6645 (markdown-code-block-at-point-p)
6646 (< (point) (point-max))))
6647 (if (and (not (eq (point) opoint))
6648 (or (markdown-link-p) (markdown-wiki-link-p)))
6649 ;; Group 1 will move past non-escape character in wiki link regexp.
6650 ;; Go to beginning of group zero for all other link types.
6651 (goto-char (or (match-beginning 1) (match-beginning 0)))
6652 (goto-char opoint)
6653 nil)))
6655 (defun markdown-previous-link ()
6656 "Jump to previous wiki link.
6657 If successful, return point. Otherwise, return nil.
6658 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
6659 (interactive)
6660 (let ((opoint (point)))
6661 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t)
6662 (markdown-code-block-at-point-p)
6663 (> (point) (point-min))))
6664 (if (and (not (eq (point) opoint))
6665 (or (markdown-link-p) (markdown-wiki-link-p)))
6666 (goto-char (or (match-beginning 1) (match-beginning 0)))
6667 (goto-char opoint)
6668 nil)))
6671 ;;; Outline ===================================================================
6673 (defun markdown-move-heading-common (move-fn &optional arg adjust)
6674 "Wrapper for `outline-mode' functions to skip false positives.
6675 MOVE-FN is a function and ARG is its argument. For example,
6676 headings inside preformatted code blocks may match
6677 `outline-regexp' but should not be considered as headings.
6678 When ADJUST is non-nil, adjust the point for interactive calls
6679 to avoid leaving the point at invisible markup. This adjustment
6680 generally should only be done for interactive calls, since other
6681 functions may expect the point to be at the beginning of the
6682 regular expression."
6683 (let ((prev -1) (start (point)))
6684 (if arg (funcall move-fn arg) (funcall move-fn))
6685 (while (and (/= prev (point)) (markdown-code-block-at-point-p))
6686 (setq prev (point))
6687 (if arg (funcall move-fn arg) (funcall move-fn)))
6688 ;; Adjust point for setext headings and invisible text.
6689 (save-match-data
6690 (when (and adjust (thing-at-point-looking-at markdown-regex-header))
6691 (if markdown-hide-markup
6692 ;; Move to beginning of heading text if markup is hidden.
6693 (goto-char (or (match-beginning 1) (match-beginning 5)))
6694 ;; Move to beginning of markup otherwise.
6695 (goto-char (or (match-beginning 1) (match-beginning 4))))))
6696 (if (= (point) start) nil (point))))
6698 (defun markdown-next-visible-heading (arg)
6699 "Move to the next visible heading line of any level.
6700 With argument, repeats or can move backward if negative. ARG is
6701 passed to `outline-next-visible-heading'."
6702 (interactive "p")
6703 (markdown-move-heading-common #'outline-next-visible-heading arg 'adjust))
6705 (defun markdown-previous-visible-heading (arg)
6706 "Move to the previous visible heading line of any level.
6707 With argument, repeats or can move backward if negative. ARG is
6708 passed to `outline-previous-visible-heading'."
6709 (interactive "p")
6710 (markdown-move-heading-common #'outline-previous-visible-heading arg 'adjust))
6712 (defun markdown-next-heading ()
6713 "Move to the next heading line of any level."
6714 (markdown-move-heading-common #'outline-next-heading))
6716 (defun markdown-previous-heading ()
6717 "Move to the previous heading line of any level."
6718 (markdown-move-heading-common #'outline-previous-heading))
6720 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok no-error)
6721 "Move back to the beginning of the previous heading.
6722 Returns t if the point is at a heading, the location if a heading
6723 was found, and nil otherwise.
6724 Only visible heading lines are considered, unless INVISIBLE-OK is
6725 non-nil. Throw an error if there is no previous heading unless
6726 NO-ERROR is non-nil.
6727 Leaves match data intact for `markdown-regex-header'."
6728 (beginning-of-line)
6729 (or (and (markdown-heading-at-point)
6730 (not (markdown-code-block-at-point-p)))
6731 (let (found)
6732 (save-excursion
6733 (while (and (not found)
6734 (re-search-backward markdown-regex-header nil t))
6735 (when (and (or invisible-ok (not (outline-invisible-p)))
6736 (not (markdown-code-block-at-point-p)))
6737 (setq found (point))))
6738 (if (not found)
6739 (unless no-error (user-error "Before first heading"))
6740 (setq found (point))))
6741 (when found (goto-char found)))))
6743 (defun markdown-forward-same-level (arg)
6744 "Move forward to the ARG'th heading at same level as this one.
6745 Stop at the first and last headings of a superior heading."
6746 (interactive "p")
6747 (markdown-back-to-heading-over-code-block)
6748 (markdown-move-heading-common #'outline-forward-same-level arg 'adjust))
6750 (defun markdown-backward-same-level (arg)
6751 "Move backward to the ARG'th heading at same level as this one.
6752 Stop at the first and last headings of a superior heading."
6753 (interactive "p")
6754 (markdown-back-to-heading-over-code-block)
6755 (while (> arg 0)
6756 (let ((point-to-move-to
6757 (save-excursion
6758 (markdown-move-heading-common #'outline-get-last-sibling nil 'adjust))))
6759 (if point-to-move-to
6760 (progn
6761 (goto-char point-to-move-to)
6762 (setq arg (1- arg)))
6763 (user-error "No previous same-level heading")))))
6765 (defun markdown-up-heading (arg)
6766 "Move to the visible heading line of which the present line is a subheading.
6767 With argument, move up ARG levels."
6768 (interactive "p")
6769 (and (called-interactively-p 'any)
6770 (not (eq last-command 'markdown-up-heading)) (push-mark))
6771 (markdown-move-heading-common #'outline-up-heading arg 'adjust))
6773 (defun markdown-back-to-heading (&optional invisible-ok)
6774 "Move to previous heading line, or beg of this line if it's a heading.
6775 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
6776 (markdown-move-heading-common #'outline-back-to-heading invisible-ok))
6778 (defalias 'markdown-end-of-heading 'outline-end-of-heading)
6780 (defun markdown-on-heading-p ()
6781 "Return non-nil if point is on a heading line."
6782 (get-text-property (point-at-bol) 'markdown-heading))
6784 (defun markdown-end-of-subtree (&optional invisible-OK)
6785 "Move to the end of the current subtree.
6786 Only visible heading lines are considered, unless INVISIBLE-OK is
6787 non-nil.
6788 Derived from `org-end-of-subtree'."
6789 (markdown-back-to-heading invisible-OK)
6790 (let ((first t)
6791 (level (markdown-outline-level)))
6792 (while (and (not (eobp))
6793 (or first (> (markdown-outline-level) level)))
6794 (setq first nil)
6795 (markdown-next-heading))
6796 (if (memq (preceding-char) '(?\n ?\^M))
6797 (progn
6798 ;; Go to end of line before heading
6799 (forward-char -1)
6800 (if (memq (preceding-char) '(?\n ?\^M))
6801 ;; leave blank line before heading
6802 (forward-char -1)))))
6803 (point))
6805 (defun markdown-outline-fix-visibility ()
6806 "Hide any false positive headings that should not be shown.
6807 For example, headings inside preformatted code blocks may match
6808 `outline-regexp' but should not be shown as headings when cycling.
6809 Also, the ending --- line in metadata blocks appears to be a
6810 setext header, but should not be folded."
6811 (save-excursion
6812 (goto-char (point-min))
6813 ;; Unhide any false positives in metadata blocks
6814 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin)
6815 (let ((body (progn (forward-line)
6816 (markdown-text-property-at-point
6817 'markdown-yaml-metadata-section))))
6818 (when body
6819 (let ((end (progn (goto-char (cl-second body))
6820 (markdown-text-property-at-point
6821 'markdown-yaml-metadata-end))))
6822 (outline-flag-region (point-min) (1+ (cl-second end)) nil)))))
6823 ;; Hide any false positives in code blocks
6824 (unless (outline-on-heading-p)
6825 (outline-next-visible-heading 1))
6826 (while (< (point) (point-max))
6827 (when (markdown-code-block-at-point-p)
6828 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t))
6829 (outline-next-visible-heading 1))))
6831 (defvar markdown-cycle-global-status 1)
6832 (defvar markdown-cycle-subtree-status nil)
6834 (defun markdown-next-preface ()
6835 (let (finish)
6836 (while (and (not finish) (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
6837 nil 'move))
6838 (unless (markdown-code-block-at-point-p)
6839 (goto-char (match-beginning 0))
6840 (setq finish t))))
6841 (when (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
6842 (forward-char -1)))
6844 (defun markdown-show-entry ()
6845 (save-excursion
6846 (outline-back-to-heading t)
6847 (outline-flag-region (1- (point))
6848 (progn
6849 (markdown-next-preface)
6850 (if (= 1 (- (point-max) (point)))
6851 (point-max)
6852 (point)))
6853 nil)))
6855 ;; This function was originally derived from `org-cycle' from org.el.
6856 (defun markdown-cycle (&optional arg)
6857 "Visibility cycling for Markdown mode.
6858 If ARG is t, perform global visibility cycling. If the point is
6859 at an atx-style header, cycle visibility of the corresponding
6860 subtree. Otherwise, indent the current line or insert a tab,
6861 as appropriate, by calling `indent-for-tab-command'."
6862 (interactive "P")
6863 (cond
6865 ;; Global cycling
6866 ((eq arg t)
6867 (cond
6868 ;; Move from overview to contents
6869 ((and (eq last-command this-command)
6870 (eq markdown-cycle-global-status 2))
6871 (markdown-hide-sublevels 1)
6872 (message "CONTENTS")
6873 (setq markdown-cycle-global-status 3)
6874 (markdown-outline-fix-visibility))
6875 ;; Move from contents to all
6876 ((and (eq last-command this-command)
6877 (eq markdown-cycle-global-status 3))
6878 (markdown-show-all)
6879 (message "SHOW ALL")
6880 (setq markdown-cycle-global-status 1))
6881 ;; Defaults to overview
6883 (markdown-hide-body)
6884 (message "OVERVIEW")
6885 (setq markdown-cycle-global-status 2)
6886 (markdown-outline-fix-visibility))))
6888 ;; At a heading: rotate between three different views
6889 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
6890 (markdown-back-to-heading)
6891 (let ((goal-column 0) eoh eol eos)
6892 ;; Determine boundaries
6893 (save-excursion
6894 (markdown-back-to-heading)
6895 (save-excursion
6896 (beginning-of-line 2)
6897 (while (and (not (eobp)) ;; this is like `next-line'
6898 (get-char-property (1- (point)) 'invisible))
6899 (beginning-of-line 2)) (setq eol (point)))
6900 (markdown-end-of-heading) (setq eoh (point))
6901 (markdown-end-of-subtree t)
6902 (skip-chars-forward " \t\n")
6903 (beginning-of-line 1) ; in case this is an item
6904 (setq eos (1- (point))))
6905 ;; Find out what to do next and set `this-command'
6906 (cond
6907 ;; Nothing is hidden behind this heading
6908 ((= eos eoh)
6909 (message "EMPTY ENTRY")
6910 (setq markdown-cycle-subtree-status nil))
6911 ;; Entire subtree is hidden in one line: open it
6912 ((>= eol eos)
6913 (markdown-show-entry)
6914 (markdown-show-children)
6915 (message "CHILDREN")
6916 (setq markdown-cycle-subtree-status 'children))
6917 ;; We just showed the children, now show everything.
6918 ((and (eq last-command this-command)
6919 (eq markdown-cycle-subtree-status 'children))
6920 (markdown-show-subtree)
6921 (message "SUBTREE")
6922 (setq markdown-cycle-subtree-status 'subtree))
6923 ;; Default action: hide the subtree.
6925 (markdown-hide-subtree)
6926 (message "FOLDED")
6927 (setq markdown-cycle-subtree-status 'folded)))))
6929 ;; In a table, move forward by one cell
6930 ((markdown-table-at-point-p)
6931 (call-interactively #'markdown-table-forward-cell))
6933 ;; Otherwise, indent as appropriate
6935 (indent-for-tab-command))))
6937 (defun markdown-shifttab ()
6938 "Handle S-TAB keybinding based on context.
6939 When in a table, move backward one cell.
6940 Otherwise, cycle global heading visibility by calling
6941 `markdown-cycle' with argument t."
6942 (interactive)
6943 (cond ((markdown-table-at-point-p)
6944 (call-interactively #'markdown-table-backward-cell))
6945 (t (markdown-cycle t))))
6947 (defun markdown-outline-level ()
6948 "Return the depth to which a statement is nested in the outline."
6949 (cond
6950 ((and (match-beginning 0)
6951 (markdown-code-block-at-pos (match-beginning 0)))
6952 7) ;; Only 6 header levels are defined.
6953 ((match-end 2) 1)
6954 ((match-end 3) 2)
6955 ((match-end 4)
6956 (length (markdown-trim-whitespace (match-string-no-properties 4))))))
6958 (defun markdown-promote-subtree (&optional arg)
6959 "Promote the current subtree of ATX headings.
6960 Note that Markdown does not support heading levels higher than
6961 six and therefore level-six headings will not be promoted
6962 further. If ARG is non-nil promote the heading, otherwise
6963 demote."
6964 (interactive "*P")
6965 (save-excursion
6966 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
6967 (re-search-backward markdown-regex-header-atx nil t))
6968 (not (markdown-code-block-at-point-p)))
6969 (let ((level (length (match-string 1)))
6970 (promote-or-demote (if arg 1 -1))
6971 (remove 't))
6972 (markdown-cycle-atx promote-or-demote remove)
6973 (catch 'end-of-subtree
6974 (while (and (markdown-next-heading)
6975 (looking-at markdown-regex-header-atx))
6976 ;; Exit if this not a higher level heading; promote otherwise.
6977 (if (and (looking-at markdown-regex-header-atx)
6978 (<= (length (match-string-no-properties 1)) level))
6979 (throw 'end-of-subtree nil)
6980 (markdown-cycle-atx promote-or-demote remove))))))))
6982 (defun markdown-demote-subtree ()
6983 "Demote the current subtree of ATX headings."
6984 (interactive)
6985 (markdown-promote-subtree t))
6987 (defun markdown-move-subtree-up ()
6988 "Move the current subtree of ATX headings up."
6989 (interactive)
6990 (outline-move-subtree-up 1))
6992 (defun markdown-move-subtree-down ()
6993 "Move the current subtree of ATX headings down."
6994 (interactive)
6995 (outline-move-subtree-down 1))
6997 (defun markdown-outline-next ()
6998 "Move to next list item, when in a list, or next visible heading."
6999 (interactive)
7000 (let ((bounds (markdown-next-list-item-bounds)))
7001 (if bounds
7002 (goto-char (nth 0 bounds))
7003 (markdown-next-visible-heading 1))))
7005 (defun markdown-outline-previous ()
7006 "Move to previous list item, when in a list, or previous visible heading."
7007 (interactive)
7008 (let ((bounds (markdown-prev-list-item-bounds)))
7009 (if bounds
7010 (goto-char (nth 0 bounds))
7011 (markdown-previous-visible-heading 1))))
7013 (defun markdown-outline-next-same-level ()
7014 "Move to next list item or heading of same level."
7015 (interactive)
7016 (let ((bounds (markdown-cur-list-item-bounds)))
7017 (if bounds
7018 (markdown-next-list-item (nth 3 bounds))
7019 (markdown-forward-same-level 1))))
7021 (defun markdown-outline-previous-same-level ()
7022 "Move to previous list item or heading of same level."
7023 (interactive)
7024 (let ((bounds (markdown-cur-list-item-bounds)))
7025 (if bounds
7026 (markdown-prev-list-item (nth 3 bounds))
7027 (markdown-backward-same-level 1))))
7029 (defun markdown-outline-up ()
7030 "Move to previous list item, when in a list, or next heading."
7031 (interactive)
7032 (unless (markdown-up-list)
7033 (markdown-up-heading 1)))
7036 ;;; Marking and Narrowing =====================================================
7038 (defun markdown-mark-paragraph ()
7039 "Put mark at end of this block, point at beginning.
7040 The block marked is the one that contains point or follows point.
7042 Interactively, if this command is repeated or (in Transient Mark
7043 mode) if the mark is active, it marks the next block after the
7044 ones already marked."
7045 (interactive)
7046 (if (or (and (eq last-command this-command) (mark t))
7047 (and transient-mark-mode mark-active))
7048 (set-mark
7049 (save-excursion
7050 (goto-char (mark))
7051 (markdown-forward-paragraph)
7052 (point)))
7053 (let ((beginning-of-defun-function 'markdown-backward-paragraph)
7054 (end-of-defun-function 'markdown-forward-paragraph))
7055 (mark-defun))))
7057 (defun markdown-mark-block ()
7058 "Put mark at end of this block, point at beginning.
7059 The block marked is the one that contains point or follows point.
7061 Interactively, if this command is repeated or (in Transient Mark
7062 mode) if the mark is active, it marks the next block after the
7063 ones already marked."
7064 (interactive)
7065 (if (or (and (eq last-command this-command) (mark t))
7066 (and transient-mark-mode mark-active))
7067 (set-mark
7068 (save-excursion
7069 (goto-char (mark))
7070 (markdown-forward-block)
7071 (point)))
7072 (let ((beginning-of-defun-function 'markdown-backward-block)
7073 (end-of-defun-function 'markdown-forward-block))
7074 (mark-defun))))
7076 (defun markdown-narrow-to-block ()
7077 "Make text outside current block invisible.
7078 The current block is the one that contains point or follows point."
7079 (interactive)
7080 (let ((beginning-of-defun-function 'markdown-backward-block)
7081 (end-of-defun-function 'markdown-forward-block))
7082 (narrow-to-defun)))
7084 (defun markdown-mark-text-block ()
7085 "Put mark at end of this plain text block, point at beginning.
7086 The block marked is the one that contains point or follows point.
7088 Interactively, if this command is repeated or (in Transient Mark
7089 mode) if the mark is active, it marks the next block after the
7090 ones already marked."
7091 (interactive)
7092 (if (or (and (eq last-command this-command) (mark t))
7093 (and transient-mark-mode mark-active))
7094 (set-mark
7095 (save-excursion
7096 (goto-char (mark))
7097 (markdown-end-of-text-block)
7098 (point)))
7099 (let ((beginning-of-defun-function 'markdown-beginning-of-text-block)
7100 (end-of-defun-function 'markdown-end-of-text-block))
7101 (mark-defun))))
7103 (defun markdown-mark-page ()
7104 "Put mark at end of this top level section, point at beginning.
7105 The top level section marked is the one that contains point or
7106 follows point.
7108 Interactively, if this command is repeated or (in Transient Mark
7109 mode) if the mark is active, it marks the next page after the
7110 ones already marked."
7111 (interactive)
7112 (if (or (and (eq last-command this-command) (mark t))
7113 (and transient-mark-mode mark-active))
7114 (set-mark
7115 (save-excursion
7116 (goto-char (mark))
7117 (markdown-forward-page)
7118 (point)))
7119 (let ((beginning-of-defun-function 'markdown-backward-page)
7120 (end-of-defun-function 'markdown-forward-page))
7121 (mark-defun))))
7123 (defun markdown-narrow-to-page ()
7124 "Make text outside current top level section invisible.
7125 The current section is the one that contains point or follows point."
7126 (interactive)
7127 (let ((beginning-of-defun-function 'markdown-backward-page)
7128 (end-of-defun-function 'markdown-forward-page))
7129 (narrow-to-defun)))
7131 (defun markdown-mark-subtree ()
7132 "Mark the current subtree.
7133 This puts point at the start of the current subtree, and mark at the end."
7134 (interactive)
7135 (let ((beg))
7136 (if (markdown-heading-at-point)
7137 (beginning-of-line)
7138 (markdown-previous-visible-heading 1))
7139 (setq beg (point))
7140 (markdown-end-of-subtree)
7141 (push-mark (point) nil t)
7142 (goto-char beg)))
7144 (defun markdown-narrow-to-subtree ()
7145 "Narrow buffer to the current subtree."
7146 (interactive)
7147 (save-excursion
7148 (save-match-data
7149 (narrow-to-region
7150 (progn (markdown-back-to-heading-over-code-block t) (point))
7151 (progn (markdown-end-of-subtree)
7152 (if (and (markdown-heading-at-point) (not (eobp)))
7153 (backward-char 1))
7154 (point))))))
7157 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
7159 (defun markdown-move-up ()
7160 "Move thing at point up.
7161 When in a list item, call `markdown-move-list-item-up'.
7162 When in a table, call `markdown-table-move-row-up'.
7163 Otherwise, move the current heading subtree up with
7164 `markdown-move-subtree-up'."
7165 (interactive)
7166 (cond
7167 ((markdown-list-item-at-point-p)
7168 (call-interactively #'markdown-move-list-item-up))
7169 ((markdown-table-at-point-p)
7170 (call-interactively #'markdown-table-move-row-up))
7172 (call-interactively #'markdown-move-subtree-up))))
7174 (defun markdown-move-down ()
7175 "Move thing at point down.
7176 When in a list item, call `markdown-move-list-item-down'.
7177 Otherwise, move the current heading subtree up with
7178 `markdown-move-subtree-down'."
7179 (interactive)
7180 (cond
7181 ((markdown-list-item-at-point-p)
7182 (call-interactively #'markdown-move-list-item-down))
7183 ((markdown-table-at-point-p)
7184 (call-interactively #'markdown-table-move-row-down))
7186 (call-interactively #'markdown-move-subtree-down))))
7188 (defun markdown-promote ()
7189 "Promote or move element at point to the left.
7190 Depending on the context, this function will promote a heading or
7191 list item at the point, move a table column to the left, or cycle
7192 markup."
7193 (interactive)
7194 (let (bounds)
7195 (cond
7196 ;; Promote atx heading subtree
7197 ((thing-at-point-looking-at markdown-regex-header-atx)
7198 (markdown-promote-subtree))
7199 ;; Promote setext heading
7200 ((thing-at-point-looking-at markdown-regex-header-setext)
7201 (markdown-cycle-setext -1))
7202 ;; Promote horizonal rule
7203 ((thing-at-point-looking-at markdown-regex-hr)
7204 (markdown-cycle-hr -1))
7205 ;; Promote list item
7206 ((setq bounds (markdown-cur-list-item-bounds))
7207 (markdown-promote-list-item bounds))
7208 ;; Move table column to the left
7209 ((markdown-table-at-point-p)
7210 (call-interactively #'markdown-table-move-column-left))
7211 ;; Promote bold
7212 ((thing-at-point-looking-at markdown-regex-bold)
7213 (markdown-cycle-bold))
7214 ;; Promote italic
7215 ((thing-at-point-looking-at markdown-regex-italic)
7216 (markdown-cycle-italic))
7218 (user-error "Nothing to promote at point")))))
7220 (defun markdown-demote ()
7221 "Demote or move element at point to the right.
7222 Depending on the context, this function will demote a heading or
7223 list item at the point, move a table column to the right, or cycle
7224 or remove markup."
7225 (interactive)
7226 (let (bounds)
7227 (cond
7228 ;; Demote atx heading subtree
7229 ((thing-at-point-looking-at markdown-regex-header-atx)
7230 (markdown-demote-subtree))
7231 ;; Demote setext heading
7232 ((thing-at-point-looking-at markdown-regex-header-setext)
7233 (markdown-cycle-setext 1))
7234 ;; Demote horizonal rule
7235 ((thing-at-point-looking-at markdown-regex-hr)
7236 (markdown-cycle-hr 1))
7237 ;; Demote list item
7238 ((setq bounds (markdown-cur-list-item-bounds))
7239 (markdown-demote-list-item bounds))
7240 ;; Move table column to the right
7241 ((markdown-table-at-point-p)
7242 (call-interactively #'markdown-table-move-column-right))
7243 ;; Demote bold
7244 ((thing-at-point-looking-at markdown-regex-bold)
7245 (markdown-cycle-bold))
7246 ;; Demote italic
7247 ((thing-at-point-looking-at markdown-regex-italic)
7248 (markdown-cycle-italic))
7250 (user-error "Nothing to demote at point")))))
7253 ;;; Commands ==================================================================
7255 (defun markdown (&optional output-buffer-name)
7256 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
7257 The output buffer name defaults to `markdown-output-buffer-name'.
7258 Return the name of the output buffer used."
7259 (interactive)
7260 (save-window-excursion
7261 (let ((begin-region)
7262 (end-region))
7263 (if (markdown-use-region-p)
7264 (setq begin-region (region-beginning)
7265 end-region (region-end))
7266 (setq begin-region (point-min)
7267 end-region (point-max)))
7269 (unless output-buffer-name
7270 (setq output-buffer-name markdown-output-buffer-name))
7271 (let ((exit-code
7272 (cond
7273 ;; Handle case when `markdown-command' does not read from stdin
7274 ((and (stringp markdown-command) markdown-command-needs-filename)
7275 (if (not buffer-file-name)
7276 (user-error "Must be visiting a file")
7277 ;; Don’t use ‘shell-command’ because it’s not guaranteed to
7278 ;; return the exit code of the process.
7279 (shell-command-on-region
7280 ;; Pass an empty region so that stdin is empty.
7281 (point) (point)
7282 (concat markdown-command " "
7283 (shell-quote-argument buffer-file-name))
7284 output-buffer-name)))
7285 ;; Pass region to `markdown-command' via stdin
7287 (let ((buf (get-buffer-create output-buffer-name)))
7288 (with-current-buffer buf
7289 (setq buffer-read-only nil)
7290 (erase-buffer))
7291 (if (stringp markdown-command)
7292 (call-process-region begin-region end-region
7293 shell-file-name nil buf nil
7294 shell-command-switch markdown-command)
7295 (funcall markdown-command begin-region end-region buf)
7296 ;; If the ‘markdown-command’ function didn’t signal an
7297 ;; error, assume it succeeded by binding ‘exit-code’ to 0.
7298 0))))))
7299 ;; The exit code can be a signal description string, so don’t use ‘=’
7300 ;; or ‘zerop’.
7301 (unless (eq exit-code 0)
7302 (user-error "%s failed with exit code %s"
7303 markdown-command exit-code))))
7304 output-buffer-name))
7306 (defun markdown-standalone (&optional output-buffer-name)
7307 "Special function to provide standalone HTML output.
7308 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
7309 (interactive)
7310 (setq output-buffer-name (markdown output-buffer-name))
7311 (with-current-buffer output-buffer-name
7312 (set-buffer output-buffer-name)
7313 (unless (markdown-output-standalone-p)
7314 (markdown-add-xhtml-header-and-footer output-buffer-name))
7315 (goto-char (point-min))
7316 (html-mode))
7317 output-buffer-name)
7319 (defun markdown-other-window (&optional output-buffer-name)
7320 "Run `markdown-command' on current buffer and display in other window.
7321 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7322 that name."
7323 (interactive)
7324 (markdown-display-buffer-other-window
7325 (markdown-standalone output-buffer-name)))
7327 (defun markdown-output-standalone-p ()
7328 "Determine whether `markdown-command' output is standalone XHTML.
7329 Standalone XHTML output is identified by an occurrence of
7330 `markdown-xhtml-standalone-regexp' in the first five lines of output."
7331 (save-excursion
7332 (goto-char (point-min))
7333 (save-match-data
7334 (re-search-forward
7335 markdown-xhtml-standalone-regexp
7336 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
7337 t))))
7339 (defun markdown-stylesheet-link-string (stylesheet-path)
7340 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
7341 stylesheet-path
7342 "\" />"))
7344 (defun markdown-add-xhtml-header-and-footer (title)
7345 "Wrap XHTML header and footer with given TITLE around current buffer."
7346 (goto-char (point-min))
7347 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
7348 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
7349 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
7350 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
7351 "<head>\n<title>")
7352 (insert title)
7353 (insert "</title>\n")
7354 (when (> (length markdown-content-type) 0)
7355 (insert
7356 (format
7357 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
7358 markdown-content-type
7359 (or (and markdown-coding-system
7360 (fboundp 'coding-system-get)
7361 (coding-system-get markdown-coding-system
7362 'mime-charset))
7363 (and (fboundp 'coding-system-get)
7364 (coding-system-get buffer-file-coding-system
7365 'mime-charset))
7366 "iso-8859-1"))))
7367 (if (> (length markdown-css-paths) 0)
7368 (insert (mapconcat #'markdown-stylesheet-link-string
7369 markdown-css-paths "\n")))
7370 (when (> (length markdown-xhtml-header-content) 0)
7371 (insert markdown-xhtml-header-content))
7372 (insert "\n</head>\n\n"
7373 "<body>\n\n")
7374 (when (> (length markdown-xhtml-body-preamble) 0)
7375 (insert markdown-xhtml-body-preamble "\n"))
7376 (goto-char (point-max))
7377 (when (> (length markdown-xhtml-body-epilogue) 0)
7378 (insert "\n" markdown-xhtml-body-epilogue))
7379 (insert "\n"
7380 "</body>\n"
7381 "</html>\n"))
7383 (defun markdown-preview (&optional output-buffer-name)
7384 "Run `markdown-command' on the current buffer and view output in browser.
7385 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7386 that name."
7387 (interactive)
7388 (browse-url-of-buffer
7389 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
7391 (defun markdown-export-file-name (&optional extension)
7392 "Attempt to generate a filename for Markdown output.
7393 The file extension will be EXTENSION if given, or .html by default.
7394 If the current buffer is visiting a file, we construct a new
7395 output filename based on that filename. Otherwise, return nil."
7396 (when (buffer-file-name)
7397 (unless extension
7398 (setq extension ".html"))
7399 (let ((candidate
7400 (concat
7401 (cond
7402 ((buffer-file-name)
7403 (file-name-sans-extension (buffer-file-name)))
7404 (t (buffer-name)))
7405 extension)))
7406 (cond
7407 ((equal candidate (buffer-file-name))
7408 (concat candidate extension))
7410 candidate)))))
7412 (defun markdown-export (&optional output-file)
7413 "Run Markdown on the current buffer, save to file, and return the filename.
7414 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
7415 generated by `markdown-export-file-name', which will be constructed using the
7416 current filename, but with the extension removed and replaced with .html."
7417 (interactive)
7418 (unless output-file
7419 (setq output-file (markdown-export-file-name ".html")))
7420 (when output-file
7421 (let* ((init-buf (current-buffer))
7422 (init-point (point))
7423 (init-buf-string (buffer-string))
7424 (output-buffer (find-file-noselect output-file))
7425 (output-buffer-name (buffer-name output-buffer)))
7426 (run-hooks 'markdown-before-export-hook)
7427 (markdown-standalone output-buffer-name)
7428 (with-current-buffer output-buffer
7429 (run-hooks 'markdown-after-export-hook)
7430 (save-buffer)
7431 (when markdown-export-kill-buffer (kill-buffer)))
7432 ;; if modified, restore initial buffer
7433 (when (buffer-modified-p init-buf)
7434 (erase-buffer)
7435 (insert init-buf-string)
7436 (save-buffer)
7437 (goto-char init-point))
7438 output-file)))
7440 (defun markdown-export-and-preview ()
7441 "Export to XHTML using `markdown-export' and browse the resulting file."
7442 (interactive)
7443 (browse-url-of-file (markdown-export)))
7445 (defvar markdown-live-preview-buffer nil
7446 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
7447 (make-variable-buffer-local 'markdown-live-preview-buffer)
7449 (defvar markdown-live-preview-source-buffer nil
7450 "Source buffer from which current buffer was generated.
7451 This is the inverse of `markdown-live-preview-buffer'.")
7452 (make-variable-buffer-local 'markdown-live-preview-source-buffer)
7454 (defvar markdown-live-preview-currently-exporting nil)
7456 (defun markdown-live-preview-get-filename ()
7457 "Standardize the filename exported by `markdown-live-preview-export'."
7458 (markdown-export-file-name ".html"))
7460 (defun markdown-live-preview-window-eww (file)
7461 "Preview FILE with eww.
7462 To be used with `markdown-live-preview-window-function'."
7463 (if (require 'eww nil t)
7464 (progn
7465 (eww-open-file file)
7466 (get-buffer "*eww*"))
7467 (error "EWW is not present or not loaded on this version of Emacs")))
7469 (defun markdown-visual-lines-between-points (beg end)
7470 (save-excursion
7471 (goto-char beg)
7472 (cl-loop with count = 0
7473 while (progn (end-of-visual-line)
7474 (and (< (point) end) (line-move-visual 1 t)))
7475 do (cl-incf count)
7476 finally return count)))
7478 (defun markdown-live-preview-window-serialize (buf)
7479 "Get window point and scroll data for all windows displaying BUF."
7480 (when (buffer-live-p buf)
7481 (with-current-buffer buf
7482 (mapcar
7483 (lambda (win)
7484 (with-selected-window win
7485 (let* ((start (window-start))
7486 (pt (window-point))
7487 (pt-or-sym (cond ((= pt (point-min)) 'min)
7488 ((= pt (point-max)) 'max)
7489 (t pt)))
7490 (diff (markdown-visual-lines-between-points
7491 start pt)))
7492 (list win pt-or-sym diff))))
7493 (get-buffer-window-list buf)))))
7495 (defun markdown-get-point-back-lines (pt num-lines)
7496 (save-excursion
7497 (goto-char pt)
7498 (line-move-visual (- num-lines) t)
7499 ;; in testing, can occasionally overshoot the number of lines to traverse
7500 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
7501 (when (> actual-num-lines num-lines)
7502 (line-move-visual (- actual-num-lines num-lines) t)))
7503 (point)))
7505 (defun markdown-live-preview-window-deserialize (window-posns)
7506 "Apply window point and scroll data from WINDOW-POSNS.
7507 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
7508 (cl-destructuring-bind (win pt-or-sym diff) window-posns
7509 (when (window-live-p win)
7510 (with-current-buffer markdown-live-preview-buffer
7511 (set-window-buffer win (current-buffer))
7512 (cl-destructuring-bind (actual-pt actual-diff)
7513 (cl-case pt-or-sym
7514 (min (list (point-min) 0))
7515 (max (list (point-max) diff))
7516 (t (list pt-or-sym diff)))
7517 (set-window-start
7518 win (markdown-get-point-back-lines actual-pt actual-diff))
7519 (set-window-point win actual-pt))))))
7521 (defun markdown-live-preview-export ()
7522 "Export to XHTML using `markdown-export'.
7523 Browse the resulting file within Emacs using
7524 `markdown-live-preview-window-function' Return the buffer
7525 displaying the rendered output."
7526 (interactive)
7527 (let ((filename (markdown-live-preview-get-filename)))
7528 (when filename
7529 (let* ((markdown-live-preview-currently-exporting t)
7530 (cur-buf (current-buffer))
7531 (export-file (markdown-export filename))
7532 ;; get positions in all windows currently displaying output buffer
7533 (window-data
7534 (markdown-live-preview-window-serialize
7535 markdown-live-preview-buffer)))
7536 (save-window-excursion
7537 (let ((output-buffer
7538 (funcall markdown-live-preview-window-function export-file)))
7539 (with-current-buffer output-buffer
7540 (setq markdown-live-preview-source-buffer cur-buf)
7541 (add-hook 'kill-buffer-hook
7542 #'markdown-live-preview-remove-on-kill t t))
7543 (with-current-buffer cur-buf
7544 (setq markdown-live-preview-buffer output-buffer))))
7545 (with-current-buffer cur-buf
7546 ;; reset all windows displaying output buffer to where they were,
7547 ;; now with the new output
7548 (mapc #'markdown-live-preview-window-deserialize window-data)
7549 ;; delete html editing buffer
7550 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
7551 (when (and export-file (file-exists-p export-file)
7552 (eq markdown-live-preview-delete-export
7553 'delete-on-export))
7554 (delete-file export-file))
7555 markdown-live-preview-buffer)))))
7557 (defun markdown-live-preview-remove ()
7558 (when (buffer-live-p markdown-live-preview-buffer)
7559 (kill-buffer markdown-live-preview-buffer))
7560 (setq markdown-live-preview-buffer nil)
7561 ;; if set to 'delete-on-export, the output has already been deleted
7562 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
7563 (let ((outfile-name (markdown-live-preview-get-filename)))
7564 (when (and outfile-name (file-exists-p outfile-name))
7565 (delete-file outfile-name)))))
7567 (defun markdown-get-other-window ()
7568 "Find another window to display preview or output content."
7569 (cond
7570 ((memq markdown-split-window-direction '(vertical below))
7571 (or (window-in-direction 'below) (split-window-vertically)))
7572 ((memq markdown-split-window-direction '(horizontal right))
7573 (or (window-in-direction 'right) (split-window-horizontally)))
7574 (t (split-window-sensibly (get-buffer-window)))))
7576 (defun markdown-display-buffer-other-window (buf)
7577 "Display preview or output buffer BUF in another window."
7578 (let ((cur-buf (current-buffer))
7579 (window (markdown-get-other-window)))
7580 (set-window-buffer window buf)
7581 (set-buffer cur-buf)))
7583 (defun markdown-live-preview-if-markdown ()
7584 (when (and (derived-mode-p 'markdown-mode)
7585 markdown-live-preview-mode)
7586 (unless markdown-live-preview-currently-exporting
7587 (if (buffer-live-p markdown-live-preview-buffer)
7588 (markdown-live-preview-export)
7589 (markdown-display-buffer-other-window
7590 (markdown-live-preview-export))))))
7592 (defun markdown-live-preview-remove-on-kill ()
7593 (cond ((and (derived-mode-p 'markdown-mode)
7594 markdown-live-preview-mode)
7595 (markdown-live-preview-remove))
7596 (markdown-live-preview-source-buffer
7597 (with-current-buffer markdown-live-preview-source-buffer
7598 (setq markdown-live-preview-buffer nil))
7599 (setq markdown-live-preview-source-buffer nil))))
7601 (defun markdown-live-preview-switch-to-output ()
7602 "Switch to output buffer."
7603 (interactive)
7604 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
7605 output buffer in another window."
7606 (if markdown-live-preview-mode
7607 (markdown-display-buffer-other-window (markdown-live-preview-export)))
7608 (markdown-live-preview-mode))
7610 (defun markdown-live-preview-re-export ()
7611 "Re export source buffer."
7612 (interactive)
7613 "If the current buffer is a buffer displaying the exported version of a
7614 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
7615 update this buffer's contents."
7616 (when markdown-live-preview-source-buffer
7617 (with-current-buffer markdown-live-preview-source-buffer
7618 (markdown-live-preview-export))))
7620 (defun markdown-open ()
7621 "Open file for the current buffer with `markdown-open-command'."
7622 (interactive)
7623 (unless markdown-open-command
7624 (user-error "Variable `markdown-open-command' must be set"))
7625 (if (stringp markdown-open-command)
7626 (if (not buffer-file-name)
7627 (user-error "Must be visiting a file")
7628 (save-buffer)
7629 (let ((exit-code (call-process markdown-open-command nil nil nil
7630 buffer-file-name)))
7631 ;; The exit code can be a signal description string, so don’t use ‘=’
7632 ;; or ‘zerop’.
7633 (unless (eq exit-code 0)
7634 (user-error "%s failed with exit code %s"
7635 markdown-open-command exit-code))))
7636 (funcall markdown-open-command))
7637 nil)
7639 (defun markdown-kill-ring-save ()
7640 "Run Markdown on file and store output in the kill ring."
7641 (interactive)
7642 (save-window-excursion
7643 (markdown)
7644 (with-current-buffer markdown-output-buffer-name
7645 (kill-ring-save (point-min) (point-max)))))
7648 ;;; Links =====================================================================
7650 (defun markdown-link-p ()
7651 "Return non-nil when `point' is at a non-wiki link.
7652 See `markdown-wiki-link-p' for more information."
7653 (let ((case-fold-search nil))
7654 (and (not (markdown-wiki-link-p))
7655 (not (markdown-code-block-at-point-p))
7656 (or (thing-at-point-looking-at markdown-regex-link-inline)
7657 (thing-at-point-looking-at markdown-regex-link-reference)
7658 (thing-at-point-looking-at markdown-regex-uri)
7659 (thing-at-point-looking-at markdown-regex-angle-uri)))))
7661 (make-obsolete 'markdown-link-link 'markdown-link-url "v2.3")
7663 (defun markdown-link-at-pos (pos)
7664 "Return properties of link or image at position POS.
7665 Value is a list of elements describing the link:
7666 0. beginning position
7667 1. end position
7668 2. link text
7669 3. URL
7670 4. reference label
7671 5. title text
7672 6. bang (nil or \"!\")"
7673 (save-excursion
7674 (goto-char pos)
7675 (let (begin end text url reference title bang)
7676 (cond
7677 ;; Inline or reference image or link at point.
7678 ((or (thing-at-point-looking-at markdown-regex-link-inline)
7679 (thing-at-point-looking-at markdown-regex-link-reference))
7680 (setq bang (match-string-no-properties 1)
7681 begin (match-beginning 0)
7682 end (match-end 0)
7683 text (match-string-no-properties 3))
7684 (if (char-equal (char-after (match-beginning 5)) ?\[)
7685 ;; Reference link
7686 (setq reference (match-string-no-properties 6))
7687 ;; Inline link
7688 (setq url (match-string-no-properties 6))
7689 (when (match-end 7)
7690 (setq title (substring (match-string-no-properties 7) 1 -1)))))
7691 ;; Angle bracket URI at point.
7692 ((thing-at-point-looking-at markdown-regex-angle-uri)
7693 (setq begin (match-beginning 0)
7694 end (match-end 0)
7695 url (match-string-no-properties 2)))
7696 ;; Plain URI at point.
7697 ((thing-at-point-looking-at markdown-regex-uri)
7698 (setq begin (match-beginning 0)
7699 end (match-end 0)
7700 url (match-string-no-properties 1))))
7701 (list begin end text url reference title bang))))
7703 (defun markdown-link-url ()
7704 "Return the URL part of the regular (non-wiki) link at point.
7705 Works with both inline and reference style links, and with images.
7706 If point is not at a link or the link reference is not defined
7707 returns nil."
7708 (let* ((values (markdown-link-at-pos (point)))
7709 (text (nth 2 values))
7710 (url (nth 3 values))
7711 (ref (nth 4 values)))
7712 (or url (and ref (car (markdown-reference-definition
7713 (downcase (if (string= ref "") text ref))))))))
7715 (defun markdown-follow-link-at-point ()
7716 "Open the current non-wiki link.
7717 If the link is a complete URL, open in browser with `browse-url'.
7718 Otherwise, open with `find-file' after stripping anchor and/or query string.
7719 Translate filenames using `markdown-filename-translate-function'."
7720 (interactive)
7721 (if (markdown-link-p)
7722 (let* ((url (markdown-link-url))
7723 (struct (url-generic-parse-url url))
7724 (full (url-fullness struct))
7725 (file url))
7726 ;; Parse URL, determine fullness, strip query string
7727 (if (fboundp 'url-path-and-query)
7728 (setq file (car (url-path-and-query struct)))
7729 (when (and (setq file (url-filename struct))
7730 (string-match "\\?" file))
7731 (setq file (substring file 0 (match-beginning 0)))))
7732 ;; Open full URLs in browser, files in Emacs
7733 (if full
7734 (browse-url url)
7735 (when (and file (> (length file) 0))
7736 (find-file (funcall markdown-translate-filename-function file)))))
7737 (user-error "Point is not at a Markdown link or URL")))
7739 (defun markdown-fontify-inline-links (last)
7740 "Add text properties to next inline link from point to LAST."
7741 (when (markdown-match-generic-links last nil)
7742 (let* ((link-start (match-beginning 3))
7743 (link-end (match-end 3))
7744 (url-start (match-beginning 6))
7745 (url-end (match-end 6))
7746 (url (match-string-no-properties 6))
7747 (title-start (match-beginning 7))
7748 (title-end (match-end 7))
7749 (title (match-string-no-properties 7))
7750 ;; Markup part
7751 (mp (list 'face 'markdown-markup-face
7752 'invisible 'markdown-markup
7753 'rear-nonsticky t
7754 'font-lock-multiline t))
7755 ;; Link part (without face)
7756 (lp (list 'keymap markdown-mode-mouse-map
7757 'mouse-face 'markdown-highlight-face
7758 'font-lock-multiline t
7759 'help-echo (if title (concat title "\n" url) url)))
7760 ;; URL part
7761 (up (list 'keymap markdown-mode-mouse-map
7762 'face 'markdown-url-face
7763 'invisible 'markdown-markup
7764 'mouse-face 'markdown-highlight-face
7765 'font-lock-multiline t))
7766 ;; URL composition character
7767 (url-char (markdown--first-displayable markdown-url-compose-char))
7768 ;; Title part
7769 (tp (list 'face 'markdown-link-title-face
7770 'invisible 'markdown-markup
7771 'font-lock-multiline t)))
7772 (dolist (g '(1 2 4 5 8))
7773 (when (match-end g)
7774 (add-text-properties (match-beginning g) (match-end g) mp)))
7775 ;; Preserve existing faces applied to link part (e.g., inline code)
7776 (when link-start
7777 (add-text-properties link-start link-end lp)
7778 (add-face-text-property link-start link-end
7779 'markdown-link-face 'append))
7780 (when url-start (add-text-properties url-start url-end up))
7781 (when title-start (add-text-properties url-end title-end tp))
7782 (when (and markdown-hide-urls url-start)
7783 (compose-region url-start (or title-end url-end) url-char))
7784 t)))
7786 (defun markdown-fontify-reference-links (last)
7787 "Add text properties to next reference link from point to LAST."
7788 (when (markdown-match-generic-links last t)
7789 (let* ((link-start (match-beginning 3))
7790 (link-end (match-end 3))
7791 (ref-start (match-beginning 6))
7792 (ref-end (match-end 6))
7793 ;; Markup part
7794 (mp (list 'face 'markdown-markup-face
7795 'invisible 'markdown-markup
7796 'rear-nonsticky t
7797 'font-lock-multiline t))
7798 ;; Link part
7799 (lp (list 'keymap markdown-mode-mouse-map
7800 'face 'markdown-link-face
7801 'mouse-face 'markdown-highlight-face
7802 'font-lock-multiline t
7803 'help-echo (lambda (_ __ pos)
7804 (save-match-data
7805 (save-excursion
7806 (goto-char pos)
7807 (or (markdown-link-url)
7808 "Undefined reference"))))))
7809 ;; URL composition character
7810 (url-char (markdown--first-displayable markdown-url-compose-char))
7811 ;; Reference part
7812 (rp (list 'face 'markdown-reference-face
7813 'invisible 'markdown-markup
7814 'font-lock-multiline t)))
7815 (dolist (g '(1 2 4 5 8))
7816 (when (match-end g)
7817 (add-text-properties (match-beginning g) (match-end g) mp)))
7818 (when link-start (add-text-properties link-start link-end lp))
7819 (when ref-start (add-text-properties ref-start ref-end rp)
7820 (when (and markdown-hide-urls (> (- ref-end ref-start) 2))
7821 (compose-region ref-start ref-end url-char)))
7822 t)))
7824 (defun markdown-fontify-angle-uris (last)
7825 "Add text properties to angle URIs from point to LAST."
7826 (when (markdown-match-angle-uris last)
7827 (let* ((url-start (match-beginning 2))
7828 (url-end (match-end 2))
7829 ;; Markup part
7830 (mp (list 'face 'markdown-markup-face
7831 'invisible 'markdown-markup
7832 'rear-nonsticky t
7833 'font-lock-multiline t))
7834 ;; URI part
7835 (up (list 'keymap markdown-mode-mouse-map
7836 'face 'markdown-plain-url-face
7837 'mouse-face 'markdown-highlight-face
7838 'font-lock-multiline t)))
7839 (dolist (g '(1 3))
7840 (add-text-properties (match-beginning g) (match-end g) mp))
7841 (add-text-properties url-start url-end up)
7842 t)))
7844 (defun markdown-fontify-plain-uris (last)
7845 "Add text properties to plain URLs from point to LAST."
7846 (when (markdown-match-plain-uris last)
7847 (let* ((start (match-beginning 0))
7848 (end (match-end 0))
7849 (props (list 'keymap markdown-mode-mouse-map
7850 'face 'markdown-plain-url-face
7851 'mouse-face 'markdown-highlight-face
7852 'rear-nonsticky t
7853 'font-lock-multiline t)))
7854 (add-text-properties start end props)
7855 t)))
7857 (defun markdown-toggle-url-hiding (&optional arg)
7858 "Toggle the display or hiding of URLs.
7859 With a prefix argument ARG, enable URL hiding if ARG is positive,
7860 and disable it otherwise."
7861 (interactive (list (or current-prefix-arg 'toggle)))
7862 (setq markdown-hide-urls
7863 (if (eq arg 'toggle)
7864 (not markdown-hide-urls)
7865 (> (prefix-numeric-value arg) 0)))
7866 (if markdown-hide-urls
7867 (message "markdown-mode URL hiding enabled")
7868 (message "markdown-mode URL hiding disabled"))
7869 (markdown-reload-extensions))
7872 ;;; Wiki Links ================================================================
7874 (defun markdown-wiki-link-p ()
7875 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
7876 A true wiki link name matches `markdown-regex-wiki-link' but does
7877 not match the current file name after conversion. This modifies
7878 the data returned by `match-data'. Note that the potential wiki
7879 link name must be available via `match-string'."
7880 (when markdown-enable-wiki-links
7881 (let ((case-fold-search nil))
7882 (and (thing-at-point-looking-at markdown-regex-wiki-link)
7883 (not (markdown-code-block-at-point-p))
7884 (or (not buffer-file-name)
7885 (not (string-equal (buffer-file-name)
7886 (markdown-convert-wiki-link-to-filename
7887 (markdown-wiki-link-link)))))))))
7889 (defun markdown-wiki-link-link ()
7890 "Return the link part of the wiki link using current match data.
7891 The location of the link component depends on the value of
7892 `markdown-wiki-link-alias-first'."
7893 (if markdown-wiki-link-alias-first
7894 (or (match-string-no-properties 5) (match-string-no-properties 3))
7895 (match-string-no-properties 3)))
7897 (defun markdown-wiki-link-alias ()
7898 "Return the alias or text part of the wiki link using current match data.
7899 The location of the alias component depends on the value of
7900 `markdown-wiki-link-alias-first'."
7901 (if markdown-wiki-link-alias-first
7902 (match-string-no-properties 3)
7903 (or (match-string-no-properties 5) (match-string-no-properties 3))))
7905 (defun markdown-convert-wiki-link-to-filename (name)
7906 "Generate a filename from the wiki link NAME.
7907 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
7908 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
7909 and [[test test]] both map to Test-test.ext. Look in the current
7910 directory first, then in subdirectories if
7911 `markdown-wiki-link-search-subdirectories' is non-nil, and then
7912 in parent directories if
7913 `markdown-wiki-link-search-parent-directories' is non-nil."
7914 (let* ((basename (markdown-replace-regexp-in-string
7915 "[[:space:]\n]" markdown-link-space-sub-char name))
7916 (basename (if (memq major-mode '(gfm-mode gfm-view-mode))
7917 (concat (upcase (substring basename 0 1))
7918 (downcase (substring basename 1 nil)))
7919 basename))
7920 directory extension default candidates dir)
7921 (when buffer-file-name
7922 (setq directory (file-name-directory buffer-file-name)
7923 extension (file-name-extension buffer-file-name)))
7924 (setq default (concat basename
7925 (when extension (concat "." extension))))
7926 (cond
7927 ;; Look in current directory first.
7928 ((or (null buffer-file-name)
7929 (file-exists-p default))
7930 default)
7931 ;; Possibly search in subdirectories, next.
7932 ((and markdown-wiki-link-search-subdirectories
7933 (setq candidates
7934 (markdown-directory-files-recursively
7935 directory (concat "^" default "$"))))
7936 (car candidates))
7937 ;; Possibly search in parent directories as a last resort.
7938 ((and markdown-wiki-link-search-parent-directories
7939 (setq dir (locate-dominating-file directory default)))
7940 (concat dir default))
7941 ;; If nothing is found, return default in current directory.
7942 (t default))))
7944 (defun markdown-follow-wiki-link (name &optional other)
7945 "Follow the wiki link NAME.
7946 Convert the name to a file name and call `find-file'. Ensure that
7947 the new buffer remains in `markdown-mode'. Open the link in another
7948 window when OTHER is non-nil."
7949 (let ((filename (markdown-convert-wiki-link-to-filename name))
7950 (wp (when buffer-file-name
7951 (file-name-directory buffer-file-name))))
7952 (if (not wp)
7953 (user-error "Must be visiting a file")
7954 (when other (other-window 1))
7955 (let ((default-directory wp))
7956 (find-file filename)))
7957 (when (not (eq major-mode 'markdown-mode))
7958 (markdown-mode))))
7960 (defun markdown-follow-wiki-link-at-point (&optional arg)
7961 "Find Wiki Link at point.
7962 With prefix argument ARG, open the file in other window.
7963 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
7964 (interactive "P")
7965 (if (markdown-wiki-link-p)
7966 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
7967 (user-error "Point is not at a Wiki Link")))
7969 (defun markdown-highlight-wiki-link (from to face)
7970 "Highlight the wiki link in the region between FROM and TO using FACE."
7971 (put-text-property from to 'font-lock-face face))
7973 (defun markdown-unfontify-region-wiki-links (from to)
7974 "Remove wiki link faces from the region specified by FROM and TO."
7975 (interactive "*r")
7976 (let ((modified (buffer-modified-p)))
7977 (remove-text-properties from to '(font-lock-face markdown-link-face))
7978 (remove-text-properties from to '(font-lock-face markdown-missing-link-face))
7979 ;; remove-text-properties marks the buffer modified in emacs 24.3,
7980 ;; undo that if it wasn't originally marked modified
7981 (set-buffer-modified-p modified)))
7983 (defun markdown-fontify-region-wiki-links (from to)
7984 "Search region given by FROM and TO for wiki links and fontify them.
7985 If a wiki link is found check to see if the backing file exists
7986 and highlight accordingly."
7987 (goto-char from)
7988 (save-match-data
7989 (while (re-search-forward markdown-regex-wiki-link to t)
7990 (when (not (markdown-code-block-at-point-p))
7991 (let ((highlight-beginning (match-beginning 1))
7992 (highlight-end (match-end 1))
7993 (file-name
7994 (markdown-convert-wiki-link-to-filename
7995 (markdown-wiki-link-link))))
7996 (if (condition-case nil (file-exists-p file-name) (error nil))
7997 (markdown-highlight-wiki-link
7998 highlight-beginning highlight-end 'markdown-link-face)
7999 (markdown-highlight-wiki-link
8000 highlight-beginning highlight-end 'markdown-missing-link-face)))))))
8002 (defun markdown-extend-changed-region (from to)
8003 "Extend region given by FROM and TO so that we can fontify all links.
8004 The region is extended to the first newline before and the first
8005 newline after."
8006 ;; start looking for the first new line before 'from
8007 (goto-char from)
8008 (re-search-backward "\n" nil t)
8009 (let ((new-from (point-min))
8010 (new-to (point-max)))
8011 (if (not (= (point) from))
8012 (setq new-from (point)))
8013 ;; do the same thing for the first new line after 'to
8014 (goto-char to)
8015 (re-search-forward "\n" nil t)
8016 (if (not (= (point) to))
8017 (setq new-to (point)))
8018 (cl-values new-from new-to)))
8020 (defun markdown-check-change-for-wiki-link (from to)
8021 "Check region between FROM and TO for wiki links and re-fontify as needed."
8022 (interactive "*r")
8023 (let* ((modified (buffer-modified-p))
8024 (buffer-undo-list t)
8025 (inhibit-read-only t)
8026 (inhibit-point-motion-hooks t)
8027 deactivate-mark
8028 buffer-file-truename)
8029 (unwind-protect
8030 (save-excursion
8031 (save-match-data
8032 (save-restriction
8033 ;; Extend the region to fontify so that it starts
8034 ;; and ends at safe places.
8035 (cl-multiple-value-bind (new-from new-to)
8036 (markdown-extend-changed-region from to)
8037 (goto-char new-from)
8038 ;; Only refontify when the range contains text with a
8039 ;; wiki link face or if the wiki link regexp matches.
8040 (when (or (markdown-range-property-any
8041 new-from new-to 'font-lock-face
8042 '(markdown-link-face markdown-missing-link-face))
8043 (re-search-forward
8044 markdown-regex-wiki-link new-to t))
8045 ;; Unfontify existing fontification (start from scratch)
8046 (markdown-unfontify-region-wiki-links new-from new-to)
8047 ;; Now do the fontification.
8048 (markdown-fontify-region-wiki-links new-from new-to))))))
8049 (and (not modified)
8050 (buffer-modified-p)
8051 (set-buffer-modified-p nil)))))
8053 (defun markdown-check-change-for-wiki-link-after-change (from to _)
8054 "Check region between FROM and TO for wiki links and re-fontify as needed.
8055 Designed to be used with the `after-change-functions' hook."
8056 (markdown-check-change-for-wiki-link from to))
8058 (defun markdown-fontify-buffer-wiki-links ()
8059 "Refontify all wiki links in the buffer."
8060 (interactive)
8061 (markdown-check-change-for-wiki-link (point-min) (point-max)))
8063 (defun markdown-toggle-wiki-links (&optional arg)
8064 "Toggle support for wiki links.
8065 With a prefix argument ARG, enable wiki link support if ARG is positive,
8066 and disable it otherwise."
8067 (interactive (list (or current-prefix-arg 'toggle)))
8068 (setq markdown-enable-wiki-links
8069 (if (eq arg 'toggle)
8070 (not markdown-enable-wiki-links)
8071 (> (prefix-numeric-value arg) 0)))
8072 (if markdown-enable-wiki-links
8073 (message "markdown-mode wiki link support enabled")
8074 (message "markdown-mode wiki link support disabled"))
8075 (markdown-reload-extensions))
8077 (defun markdown-setup-wiki-link-hooks ()
8078 "Add or remove hooks for fontifying wiki links.
8079 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
8080 ;; Anytime text changes make sure it gets fontified correctly
8081 (if (and markdown-enable-wiki-links
8082 markdown-wiki-link-fontify-missing)
8083 (add-hook 'after-change-functions
8084 'markdown-check-change-for-wiki-link-after-change t t)
8085 (remove-hook 'after-change-functions
8086 'markdown-check-change-for-wiki-link-after-change t))
8087 ;; If we left the buffer there is a really good chance we were
8088 ;; creating one of the wiki link documents. Make sure we get
8089 ;; refontified when we come back.
8090 (if (and markdown-enable-wiki-links
8091 markdown-wiki-link-fontify-missing)
8092 (progn
8093 (add-hook 'window-configuration-change-hook
8094 'markdown-fontify-buffer-wiki-links t t)
8095 (markdown-fontify-buffer-wiki-links))
8096 (remove-hook 'window-configuration-change-hook
8097 'markdown-fontify-buffer-wiki-links t)
8098 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
8101 ;;; Following & Doing =========================================================
8103 (defun markdown-follow-thing-at-point (arg)
8104 "Follow thing at point if possible, such as a reference link or wiki link.
8105 Opens inline and reference links in a browser. Opens wiki links
8106 to other files in the current window, or the another window if
8107 ARG is non-nil.
8108 See `markdown-follow-link-at-point' and
8109 `markdown-follow-wiki-link-at-point'."
8110 (interactive "P")
8111 (cond ((markdown-link-p)
8112 (markdown-follow-link-at-point))
8113 ((markdown-wiki-link-p)
8114 (markdown-follow-wiki-link-at-point arg))
8116 (user-error "Nothing to follow at point"))))
8118 (make-obsolete 'markdown-jump 'markdown-do "v2.3")
8120 (defun markdown-do ()
8121 "Do something sensible based on context at point.
8122 Jumps between reference links and definitions; between footnote
8123 markers and footnote text."
8124 (interactive)
8125 (cond
8126 ;; Footnote definition
8127 ((markdown-footnote-text-positions)
8128 (markdown-footnote-return))
8129 ;; Footnote marker
8130 ((markdown-footnote-marker-positions)
8131 (markdown-footnote-goto-text))
8132 ;; Reference link
8133 ((thing-at-point-looking-at markdown-regex-link-reference)
8134 (markdown-reference-goto-definition))
8135 ;; Reference definition
8136 ((thing-at-point-looking-at markdown-regex-reference-definition)
8137 (markdown-reference-goto-link (match-string-no-properties 2)))
8138 ;; GFM task list item
8139 ((markdown-gfm-task-list-item-at-point)
8140 (markdown-toggle-gfm-checkbox))
8141 ;; Align table
8142 ((markdown-table-at-point-p)
8143 (call-interactively #'markdown-table-align))
8144 ;; Otherwise
8146 (markdown-insert-gfm-checkbox))))
8149 ;;; Miscellaneous =============================================================
8151 (defun markdown-compress-whitespace-string (str)
8152 "Compress whitespace in STR and return result.
8153 Leading and trailing whitespace is removed. Sequences of multiple
8154 spaces, tabs, and newlines are replaced with single spaces."
8155 (markdown-replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
8156 (markdown-replace-regexp-in-string "[ \t\n]+" " " str)))
8158 (defun markdown--substitute-command-keys (string)
8159 "Like `substitute-command-keys' but, but prefers control characters.
8160 First pass STRING to `substitute-command-keys' and then
8161 substitute `C-i` for `TAB` and `C-m` for `RET`."
8162 (replace-regexp-in-string
8163 "\\<TAB\\>" "C-i"
8164 (replace-regexp-in-string
8165 "\\<RET\\>" "C-m" (substitute-command-keys string) t) t))
8167 (defun markdown-line-number-at-pos (&optional pos)
8168 "Return (narrowed) buffer line number at position POS.
8169 If POS is nil, use current buffer location.
8170 This is an exact copy of `line-number-at-pos' for use in emacs21."
8171 (let ((opoint (or pos (point))) start)
8172 (save-excursion
8173 (goto-char (point-min))
8174 (setq start (point))
8175 (goto-char opoint)
8176 (forward-line 0)
8177 (1+ (count-lines start (point))))))
8179 (defun markdown-inside-link-p ()
8180 "Return t if point is within a link."
8181 (save-match-data
8182 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
8184 (defun markdown-line-is-reference-definition-p ()
8185 "Return whether the current line is a (non-footnote) reference defition."
8186 (save-excursion
8187 (move-beginning-of-line 1)
8188 (and (looking-at-p markdown-regex-reference-definition)
8189 (not (looking-at-p "[ \t]*\\[^")))))
8191 (defun markdown-adaptive-fill-function ()
8192 "Return prefix for filling paragraph or nil if not determined."
8193 (cond
8194 ;; List item inside blockquote
8195 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
8196 (markdown-replace-regexp-in-string
8197 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
8198 ;; Blockquote
8199 ((looking-at markdown-regex-blockquote)
8200 (buffer-substring-no-properties (match-beginning 0) (match-end 2)))
8201 ;; List items
8202 ((looking-at markdown-regex-list)
8203 (match-string-no-properties 0))
8204 ;; Footnote definition
8205 ((looking-at-p markdown-regex-footnote-definition)
8206 " ") ; four spaces
8207 ;; No match
8208 (t nil)))
8210 (defun markdown-fill-paragraph (&optional justify)
8211 "Fill paragraph at or after point.
8212 This function is like \\[fill-paragraph], but it skips Markdown
8213 code blocks. If the point is in a code block, or just before one,
8214 do not fill. Otherwise, call `fill-paragraph' as usual. If
8215 JUSTIFY is non-nil, justify text as well. Since this function
8216 handles filling itself, it always returns t so that
8217 `fill-paragraph' doesn't run."
8218 (interactive "P")
8219 (unless (or (markdown-code-block-at-point-p)
8220 (save-excursion
8221 (back-to-indentation)
8222 (skip-syntax-forward "-")
8223 (markdown-code-block-at-point-p)))
8224 (fill-paragraph justify))
8227 (make-obsolete 'markdown-fill-forward-paragraph-function
8228 'markdown-fill-forward-paragraph "v2.3")
8230 (defun markdown-fill-forward-paragraph (&optional arg)
8231 "Function used by `fill-paragraph' to move over ARG paragraphs.
8232 This is a `fill-forward-paragraph-function' for `markdown-mode'.
8233 It is called with a single argument specifying the number of
8234 paragraphs to move. Just like `forward-paragraph', it should
8235 return the number of paragraphs left to move."
8236 (or arg (setq arg 1))
8237 (if (> arg 0)
8238 ;; With positive ARG, move across ARG non-code-block paragraphs,
8239 ;; one at a time. When passing a code block, don't decrement ARG.
8240 (while (and (not (eobp))
8241 (> arg 0)
8242 (= (forward-paragraph 1) 0)
8243 (or (markdown-code-block-at-pos (point-at-bol 0))
8244 (setq arg (1- arg)))))
8245 ;; Move backward by one paragraph with negative ARG (always -1).
8246 (let ((start (point)))
8247 (setq arg (forward-paragraph arg))
8248 (while (and (not (eobp))
8249 (progn (move-to-left-margin) (not (eobp)))
8250 (looking-at-p paragraph-separate))
8251 (forward-line 1))
8252 (cond
8253 ;; Move point past whitespace following list marker.
8254 ((looking-at markdown-regex-list)
8255 (goto-char (match-end 0)))
8256 ;; Move point past whitespace following pipe at beginning of line
8257 ;; to handle Pandoc line blocks.
8258 ((looking-at "^|\\s-*")
8259 (goto-char (match-end 0)))
8260 ;; Return point if the paragraph passed was a code block.
8261 ((markdown-code-block-at-pos (point-at-bol 2))
8262 (goto-char start)))))
8263 arg)
8265 (defun markdown--inhibit-electric-quote ()
8266 "Function added to `electric-quote-inhibit-functions'.
8267 Return non-nil if the quote has been inserted inside a code block
8268 or span."
8269 (let ((pos (1- (point))))
8270 (or (markdown-inline-code-at-pos pos)
8271 (markdown-code-block-at-pos pos))))
8274 ;;; Extension Framework =======================================================
8276 (defun markdown-reload-extensions ()
8277 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
8278 (interactive)
8279 (when (member major-mode
8280 '(markdown-mode markdown-view-mode gfm-mode gfm-view-mode))
8281 ;; Refontify buffer
8282 (if (eval-when-compile (fboundp 'font-lock-flush))
8283 ;; Use font-lock-flush in Emacs >= 25.1
8284 (font-lock-flush)
8285 ;; Backwards compatibility for Emacs 24.3-24.5
8286 (when (and font-lock-mode (fboundp 'font-lock-refresh-defaults))
8287 (font-lock-refresh-defaults)))
8288 ;; Add or remove hooks related to extensions
8289 (markdown-setup-wiki-link-hooks)))
8291 (defun markdown-handle-local-variables ()
8292 "Run in `hack-local-variables-hook' to update font lock rules.
8293 Checks to see if there is actually a ‘markdown-mode’ file local variable
8294 before regenerating font-lock rules for extensions."
8295 (when (and (boundp 'file-local-variables-alist)
8296 (or (assoc 'markdown-enable-wiki-links file-local-variables-alist)
8297 (assoc 'markdown-enable-math file-local-variables-alist)))
8298 (when (assoc 'markdown-enable-math file-local-variables-alist)
8299 (markdown-toggle-math markdown-enable-math))
8300 (markdown-reload-extensions)))
8303 ;;; Math Support ==============================================================
8305 (make-obsolete 'markdown-enable-math 'markdown-toggle-math "v2.1")
8307 (defconst markdown-mode-font-lock-keywords-math
8308 (list
8309 ;; Equation reference (eq:foo)
8310 '("\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" . ((1 markdown-markup-face)
8311 (2 markdown-reference-face)
8312 (3 markdown-markup-face)))
8313 ;; Equation reference \eqref{foo}
8314 '("\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" . ((1 markdown-markup-face)
8315 (2 markdown-reference-face)
8316 (3 markdown-markup-face))))
8317 "Font lock keywords to add and remove when toggling math support.")
8319 (defun markdown-toggle-math (&optional arg)
8320 "Toggle support for inline and display LaTeX math expressions.
8321 With a prefix argument ARG, enable math mode if ARG is positive,
8322 and disable it otherwise. If called from Lisp, enable the mode
8323 if ARG is omitted or nil."
8324 (interactive (list (or current-prefix-arg 'toggle)))
8325 (setq markdown-enable-math
8326 (if (eq arg 'toggle)
8327 (not markdown-enable-math)
8328 (> (prefix-numeric-value arg) 0)))
8329 (if markdown-enable-math
8330 (progn
8331 (font-lock-add-keywords
8332 'markdown-mode markdown-mode-font-lock-keywords-math)
8333 (message "markdown-mode math support enabled"))
8334 (font-lock-remove-keywords
8335 'markdown-mode markdown-mode-font-lock-keywords-math)
8336 (message "markdown-mode math support disabled"))
8337 (markdown-reload-extensions))
8340 ;;; GFM Checkboxes ============================================================
8342 (define-button-type 'markdown-gfm-checkbox-button
8343 'follow-link t
8344 'face 'markdown-gfm-checkbox-face
8345 'mouse-face 'markdown-highlight-face
8346 'action #'markdown-toggle-gfm-checkbox-button)
8348 (defun markdown-gfm-task-list-item-at-point (&optional bounds)
8349 "Return non-nil if there is a GFM task list item at the point.
8350 Optionally, the list item BOUNDS may be given if available, as
8351 returned by `markdown-cur-list-item-bounds'. When a task list item
8352 is found, the return value is the same value returned by
8353 `markdown-cur-list-item-bounds'."
8354 (unless bounds
8355 (setq bounds (markdown-cur-list-item-bounds)))
8356 (> (length (nth 5 bounds)) 0))
8358 (defun markdown-insert-gfm-checkbox ()
8359 "Add GFM checkbox at point.
8360 Returns t if added.
8361 Returns nil if non-applicable."
8362 (interactive)
8363 (let ((bounds (markdown-cur-list-item-bounds)))
8364 (if bounds
8365 (unless (cl-sixth bounds)
8366 (let ((pos (+ (cl-first bounds) (cl-fourth bounds)))
8367 (markup "[ ] "))
8368 (if (< pos (point))
8369 (save-excursion
8370 (goto-char pos)
8371 (insert markup))
8372 (goto-char pos)
8373 (insert markup))
8374 (syntax-propertize (+ (cl-second bounds) 4))
8376 (unless (save-excursion
8377 (back-to-indentation)
8378 (or (markdown-list-item-at-point-p)
8379 (markdown-heading-at-point)
8380 (markdown-in-comment-p)
8381 (markdown-code-block-at-point-p)))
8382 (let ((pos (save-excursion
8383 (back-to-indentation)
8384 (point)))
8385 (markup (concat (or (save-excursion
8386 (beginning-of-line 0)
8387 (cl-fifth (markdown-cur-list-item-bounds)))
8388 markdown-unordered-list-item-prefix)
8389 "[ ] ")))
8390 (if (< pos (point))
8391 (save-excursion
8392 (goto-char pos)
8393 (insert markup))
8394 (goto-char pos)
8395 (insert markup))
8396 (syntax-propertize (point-at-eol))
8397 t)))))
8399 (defun markdown-toggle-gfm-checkbox ()
8400 "Toggle GFM checkbox at point.
8401 Returns the resulting status as a string, either \"[x]\" or \"[ ]\".
8402 Returns nil if there is no task list item at the point."
8403 (interactive)
8404 (save-match-data
8405 (save-excursion
8406 (let ((bounds (markdown-cur-list-item-bounds)))
8407 (when bounds
8408 ;; Move to beginning of task list item
8409 (goto-char (cl-first bounds))
8410 ;; Advance to column of first non-whitespace after marker
8411 (forward-char (cl-fourth bounds))
8412 (cond ((looking-at "\\[ \\]")
8413 (replace-match
8414 (if markdown-gfm-uppercase-checkbox "[X]" "[x]")
8415 nil t)
8416 (match-string-no-properties 0))
8417 ((looking-at "\\[[xX]\\]")
8418 (replace-match "[ ]" nil t)
8419 (match-string-no-properties 0))))))))
8421 (defun markdown-toggle-gfm-checkbox-button (button)
8422 "Toggle GFM checkbox BUTTON on click."
8423 (save-match-data
8424 (save-excursion
8425 (goto-char (button-start button))
8426 (markdown-toggle-gfm-checkbox))))
8428 (defun markdown-make-gfm-checkboxes-buttons (start end)
8429 "Make GFM checkboxes buttons in region between START and END."
8430 (save-excursion
8431 (goto-char start)
8432 (let ((case-fold-search t))
8433 (save-excursion
8434 (while (re-search-forward markdown-regex-gfm-checkbox end t)
8435 (make-button (match-beginning 1) (match-end 1)
8436 :type 'markdown-gfm-checkbox-button))))))
8438 ;; Called when any modification is made to buffer text.
8439 (defun markdown-gfm-checkbox-after-change-function (beg end _)
8440 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
8441 BEG and END are the limits of scanned region."
8442 (save-excursion
8443 (save-match-data
8444 ;; Rescan between start of line from `beg' and start of line after `end'.
8445 (markdown-make-gfm-checkboxes-buttons
8446 (progn (goto-char beg) (beginning-of-line) (point))
8447 (progn (goto-char end) (forward-line 1) (point))))))
8449 (defun markdown-remove-gfm-checkbox-overlays ()
8450 "Remove all GFM checkbox overlays in buffer."
8451 (save-excursion
8452 (save-restriction
8453 (widen)
8454 (remove-overlays nil nil 'face 'markdown-gfm-checkbox-face))))
8457 ;;; Display inline image =================================================
8459 (defvar markdown-inline-image-overlays nil)
8460 (make-variable-buffer-local 'markdown-inline-image-overlays)
8462 (defun markdown-remove-inline-images ()
8463 "Remove inline image overlays from image links in the buffer.
8464 This can be toggled with `markdown-toggle-inline-images'
8465 or \\[markdown-toggle-inline-images]."
8466 (interactive)
8467 (mapc #'delete-overlay markdown-inline-image-overlays)
8468 (setq markdown-inline-image-overlays nil))
8470 (defun markdown-display-inline-images ()
8471 "Add inline image overlays to image links in the buffer.
8472 This can be toggled with `markdown-toggle-inline-images'
8473 or \\[markdown-toggle-inline-images]."
8474 (interactive)
8475 (unless (display-images-p)
8476 (error "Cannot show images"))
8477 (save-excursion
8478 (save-restriction
8479 (widen)
8480 (goto-char (point-min))
8481 (while (re-search-forward markdown-regex-link-inline nil t)
8482 (let ((start (match-beginning 0))
8483 (end (match-end 0))
8484 (file (match-string-no-properties 6)))
8485 (when (and (not (zerop (length file)))
8486 (file-exists-p file))
8487 (let* ((abspath (if (file-name-absolute-p file)
8488 file
8489 (concat default-directory file)))
8490 (image
8491 (if (and markdown-max-image-size
8492 (image-type-available-p 'imagemagick))
8493 (create-image
8494 abspath 'imagemagick nil
8495 :max-width (car markdown-max-image-size)
8496 :max-height (cdr markdown-max-image-size))
8497 (create-image abspath))))
8498 (when image
8499 (let ((ov (make-overlay start end)))
8500 (overlay-put ov 'display image)
8501 (overlay-put ov 'face 'default)
8502 (push ov markdown-inline-image-overlays))))))))))
8504 (defun markdown-toggle-inline-images ()
8505 "Toggle inline image overlays in the buffer."
8506 (interactive)
8507 (if markdown-inline-image-overlays
8508 (markdown-remove-inline-images)
8509 (markdown-display-inline-images)))
8512 ;;; GFM Code Block Fontification ==============================================
8514 (defcustom markdown-fontify-code-blocks-natively nil
8515 "When non-nil, fontify code in code blocks using the native major mode.
8516 This only works for fenced code blocks where the language is
8517 specified where we can automatically determine the appropriate
8518 mode to use. The language to mode mapping may be customized by
8519 setting the variable `markdown-code-lang-modes'."
8520 :group 'markdown
8521 :type 'boolean
8522 :safe 'booleanp
8523 :package-version '(markdown-mode . "2.3"))
8525 (defcustom markdown-fontify-code-block-default-mode nil
8526 "Default mode to use to fontify code blocks.
8527 This mode is used when automatic detection fails, such as for GFM
8528 code blocks with no language specified."
8529 :group 'markdown
8530 :type '(choice function (const :tag "None" nil))
8531 :package-version '(markdown-mode . "2.4"))
8533 (defun markdown-toggle-fontify-code-blocks-natively (&optional arg)
8534 "Toggle the native fontification of code blocks.
8535 With a prefix argument ARG, enable if ARG is positive,
8536 and disable otherwise."
8537 (interactive (list (or current-prefix-arg 'toggle)))
8538 (setq markdown-fontify-code-blocks-natively
8539 (if (eq arg 'toggle)
8540 (not markdown-fontify-code-blocks-natively)
8541 (> (prefix-numeric-value arg) 0)))
8542 (if markdown-fontify-code-blocks-natively
8543 (message "markdown-mode native code block fontification enabled")
8544 (message "markdown-mode native code block fontification disabled"))
8545 (markdown-reload-extensions))
8547 ;; This is based on `org-src-lang-modes' from org-src.el
8548 (defcustom markdown-code-lang-modes
8549 '(("ocaml" . tuareg-mode) ("elisp" . emacs-lisp-mode) ("ditaa" . artist-mode)
8550 ("asymptote" . asy-mode) ("dot" . fundamental-mode) ("sqlite" . sql-mode)
8551 ("calc" . fundamental-mode) ("C" . c-mode) ("cpp" . c++-mode)
8552 ("C++" . c++-mode) ("screen" . shell-script-mode) ("shell" . sh-mode)
8553 ("bash" . sh-mode))
8554 "Alist mapping languages to their major mode.
8555 The key is the language name, the value is the major mode. For
8556 many languages this is simple, but for language where this is not
8557 the case, this variable provides a way to simplify things on the
8558 user side. For example, there is no ocaml-mode in Emacs, but the
8559 mode to use is `tuareg-mode'."
8560 :group 'markdown
8561 :type '(repeat
8562 (cons
8563 (string "Language name")
8564 (symbol "Major mode")))
8565 :package-version '(markdown-mode . "2.3"))
8567 (defun markdown-get-lang-mode (lang)
8568 "Return major mode that should be used for LANG.
8569 LANG is a string, and the returned major mode is a symbol."
8570 (cl-find-if
8571 'fboundp
8572 (list (cdr (assoc lang markdown-code-lang-modes))
8573 (cdr (assoc (downcase lang) markdown-code-lang-modes))
8574 (intern (concat lang "-mode"))
8575 (intern (concat (downcase lang) "-mode")))))
8577 (defun markdown-fontify-code-blocks-generic (matcher last)
8578 "Add text properties to next code block from point to LAST.
8579 Use matching function MATCHER."
8580 (when (funcall matcher last)
8581 (save-excursion
8582 (save-match-data
8583 (let* ((start (match-beginning 0))
8584 (end (match-end 0))
8585 ;; Find positions outside opening and closing backquotes.
8586 (bol-prev (progn (goto-char start)
8587 (if (bolp) (point-at-bol 0) (point-at-bol))))
8588 (eol-next (progn (goto-char end)
8589 (if (bolp) (point-at-bol 2) (point-at-bol 3))))
8590 lang)
8591 (if (and markdown-fontify-code-blocks-natively
8592 (or (setq lang (markdown-code-block-lang))
8593 markdown-fontify-code-block-default-mode))
8594 (markdown-fontify-code-block-natively lang start end)
8595 (add-text-properties start end '(face markdown-pre-face)))
8596 ;; Set background for block as well as opening and closing lines.
8597 (font-lock-append-text-property
8598 bol-prev eol-next 'face 'markdown-code-face)
8599 ;; Set invisible property for lines before and after, including newline.
8600 (add-text-properties bol-prev start '(invisible markdown-markup))
8601 (add-text-properties end eol-next '(invisible markdown-markup)))))
8604 (defun markdown-fontify-gfm-code-blocks (last)
8605 "Add text properties to next GFM code block from point to LAST."
8606 (markdown-fontify-code-blocks-generic 'markdown-match-gfm-code-blocks last))
8608 (defun markdown-fontify-fenced-code-blocks (last)
8609 "Add text properties to next tilde fenced code block from point to LAST."
8610 (markdown-fontify-code-blocks-generic 'markdown-match-fenced-code-blocks last))
8612 ;; Based on `org-src-font-lock-fontify-block' from org-src.el.
8613 (defun markdown-fontify-code-block-natively (lang start end)
8614 "Fontify given GFM or fenced code block.
8615 This function is called by Emacs for automatic fontification when
8616 `markdown-fontify-code-blocks-natively' is non-nil. LANG is the
8617 language used in the block. START and END specify the block
8618 position."
8619 (let ((lang-mode (if lang (markdown-get-lang-mode lang)
8620 markdown-fontify-code-block-default-mode)))
8621 (when (fboundp lang-mode)
8622 (let ((string (buffer-substring-no-properties start end))
8623 (modified (buffer-modified-p))
8624 (markdown-buffer (current-buffer)) pos next)
8625 (remove-text-properties start end '(face nil))
8626 (with-current-buffer
8627 (get-buffer-create
8628 (concat " markdown-code-fontification:" (symbol-name lang-mode)))
8629 ;; Make sure that modification hooks are not inhibited in
8630 ;; the org-src-fontification buffer in case we're called
8631 ;; from `jit-lock-function' (Bug#25132).
8632 (let ((inhibit-modification-hooks nil))
8633 (delete-region (point-min) (point-max))
8634 (insert string " ")) ;; so there's a final property change
8635 (unless (eq major-mode lang-mode) (funcall lang-mode))
8636 (markdown-font-lock-ensure)
8637 (setq pos (point-min))
8638 (while (setq next (next-single-property-change pos 'face))
8639 (let ((val (get-text-property pos 'face)))
8640 (when val
8641 (put-text-property
8642 (+ start (1- pos)) (1- (+ start next)) 'face
8643 val markdown-buffer)))
8644 (setq pos next)))
8645 (add-text-properties
8646 start end
8647 '(font-lock-fontified t fontified t font-lock-multiline t))
8648 (set-buffer-modified-p modified)))))
8650 (require 'edit-indirect nil t)
8651 (defvar edit-indirect-guess-mode-function)
8652 (defvar edit-indirect-after-commit-functions)
8654 (defun markdown--edit-indirect-after-commit-function (_beg end)
8655 "Ensure trailing newlines at the END of code blocks."
8656 (goto-char end)
8657 (unless (eq (char-before) ?\n)
8658 (insert "\n")))
8660 (defun markdown-edit-code-block ()
8661 "Edit Markdown code block in an indirect buffer."
8662 (interactive)
8663 (save-excursion
8664 (if (fboundp 'edit-indirect-region)
8665 (let* ((bounds (markdown-get-enclosing-fenced-block-construct))
8666 (begin (and bounds (goto-char (nth 0 bounds)) (point-at-bol 2)))
8667 (end (and bounds (goto-char (nth 1 bounds)) (point-at-bol 1))))
8668 (if (and begin end)
8669 (let* ((lang (markdown-code-block-lang))
8670 (mode (or (and lang (markdown-get-lang-mode lang))
8671 markdown-edit-code-block-default-mode))
8672 (edit-indirect-guess-mode-function
8673 (lambda (_parent-buffer _beg _end)
8674 (funcall mode))))
8675 (edit-indirect-region begin end 'display-buffer))
8676 (user-error "Not inside a GFM or tilde fenced code block")))
8677 (when (y-or-n-p "Package edit-indirect needed to edit code blocks. Install it now? ")
8678 (progn (package-refresh-contents)
8679 (package-install 'edit-indirect)
8680 (markdown-edit-code-block))))))
8683 ;;; Table Editing
8685 ;; These functions were originally adapted from `org-table.el'.
8687 ;; General helper functions
8689 (defmacro markdown--with-gensyms (symbols &rest body)
8690 (declare (debug (sexp body)) (indent 1))
8691 `(let ,(mapcar (lambda (s)
8692 `(,s (make-symbol (concat "--" (symbol-name ',s)))))
8693 symbols)
8694 ,@body))
8696 (defun markdown--split-string (string &optional separators)
8697 "Splits STRING into substrings at SEPARATORS.
8698 SEPARATORS is a regular expression. If nil it defaults to
8699 `split-string-default-separators'. This version returns no empty
8700 strings if there are matches at the beginning and end of string."
8701 (let ((start 0) notfirst list)
8702 (while (and (string-match
8703 (or separators split-string-default-separators)
8704 string
8705 (if (and notfirst
8706 (= start (match-beginning 0))
8707 (< start (length string)))
8708 (1+ start) start))
8709 (< (match-beginning 0) (length string)))
8710 (setq notfirst t)
8711 (or (eq (match-beginning 0) 0)
8712 (and (eq (match-beginning 0) (match-end 0))
8713 (eq (match-beginning 0) start))
8714 (push (substring string start (match-beginning 0)) list))
8715 (setq start (match-end 0)))
8716 (or (eq start (length string))
8717 (push (substring string start) list))
8718 (nreverse list)))
8720 (defun markdown--string-width (s)
8721 "Return width of string S.
8722 This version ignores characters with invisibility property
8723 `markdown-markup'."
8724 (let (b)
8725 (when (or (eq t buffer-invisibility-spec)
8726 (member 'markdown-markup buffer-invisibility-spec))
8727 (while (setq b (text-property-any
8728 0 (length s)
8729 'invisible 'markdown-markup s))
8730 (setq s (concat
8731 (substring s 0 b)
8732 (substring s (or (next-single-property-change
8733 b 'invisible s)
8734 (length s))))))))
8735 (string-width s))
8737 (defun markdown--remove-invisible-markup (s)
8738 "Remove Markdown markup from string S.
8739 This version removes characters with invisibility property
8740 `markdown-markup'."
8741 (let (b)
8742 (while (setq b (text-property-any
8743 0 (length s)
8744 'invisible 'markdown-markup s))
8745 (setq s (concat
8746 (substring s 0 b)
8747 (substring s (or (next-single-property-change
8748 b 'invisible s)
8749 (length s)))))))
8752 ;; Functions for maintaining tables
8754 (defvar markdown-table-at-point-p-function nil
8755 "Function to decide if point is inside a table.
8757 The indirection serves to differentiate between standard markdown
8758 tables and gfm tables which are less strict about the markup.")
8760 (defconst markdown-table-line-regexp "^[ \t]*|"
8761 "Regexp matching any line inside a table.")
8763 (defconst markdown-table-hline-regexp "^[ \t]*|[-:]"
8764 "Regexp matching hline inside a table.")
8766 (defconst markdown-table-dline-regexp "^[ \t]*|[^-:]"
8767 "Regexp matching dline inside a table.")
8769 (defun markdown-table-at-point-p ()
8770 "Return non-nil when point is inside a table."
8771 (if (functionp markdown-table-at-point-p-function)
8772 (funcall markdown-table-at-point-p-function)
8773 (markdown--table-at-point-p)))
8775 (defun markdown--table-at-point-p ()
8776 "Return non-nil when point is inside a table."
8777 (save-excursion
8778 (beginning-of-line)
8779 (and (looking-at-p markdown-table-line-regexp)
8780 (not (markdown-code-block-at-point-p)))))
8782 (defconst gfm-table-line-regexp "^.?*|"
8783 "Regexp matching any line inside a table.")
8785 (defconst gfm-table-hline-regexp "^-+\\(|-\\)+"
8786 "Regexp matching hline inside a table.")
8788 ;; GFM simplified tables syntax is as follows:
8789 ;; - A header line for the column names, this is any text
8790 ;; separated by `|'.
8791 ;; - Followed by a string -|-|- ..., the number of dashes is optional
8792 ;; but must be higher than 1. The number of separators should match
8793 ;; the number of columns.
8794 ;; - Followed by the rows of data, which has the same format as the
8795 ;; header line.
8796 ;; Example:
8798 ;; foo | bar
8799 ;; ------|---------
8800 ;; bar | baz
8801 ;; bar | baz
8802 (defun gfm--table-at-point-p ()
8803 "Return non-nil when point is inside a gfm-compatible table."
8804 (or (markdown--table-at-point-p)
8805 (save-excursion
8806 (beginning-of-line)
8807 (when (looking-at-p gfm-table-line-regexp)
8808 ;; we might be at the first line of the table, check if the
8809 ;; line below is the hline
8810 (or (save-excursion
8811 (forward-line 1)
8812 (looking-at-p gfm-table-hline-regexp))
8813 ;; go up to find the header
8814 (catch 'done
8815 (while (looking-at-p gfm-table-line-regexp)
8816 (cond
8817 ((looking-at-p gfm-table-hline-regexp)
8818 (throw 'done t))
8819 ((bobp)
8820 (throw 'done nil)))
8821 (forward-line -1))
8822 nil))))))
8824 (defun markdown-table-hline-at-point-p ()
8825 "Return non-nil when point is on a hline in a table.
8826 This function assumes point is on a table."
8827 (save-excursion
8828 (beginning-of-line)
8829 (looking-at-p markdown-table-hline-regexp)))
8831 (defun markdown-table-begin ()
8832 "Find the beginning of the table and return its position.
8833 This function assumes point is on a table."
8834 (save-excursion
8835 (while (and (not (bobp))
8836 (markdown-table-at-point-p))
8837 (forward-line -1))
8838 (unless (eobp)
8839 (forward-line 1))
8840 (point)))
8842 (defun markdown-table-end ()
8843 "Find the end of the table and return its position.
8844 This function assumes point is on a table."
8845 (save-excursion
8846 (while (and (not (eobp))
8847 (markdown-table-at-point-p))
8848 (forward-line 1))
8849 (point)))
8851 (defun markdown-table-get-dline ()
8852 "Return index of the table data line at point.
8853 This function assumes point is on a table."
8854 (let ((pos (point)) (end (markdown-table-end)) (cnt 0))
8855 (save-excursion
8856 (goto-char (markdown-table-begin))
8857 (while (and (re-search-forward
8858 markdown-table-dline-regexp end t)
8859 (setq cnt (1+ cnt))
8860 (< (point-at-eol) pos))))
8861 cnt))
8863 (defun markdown-table-get-column ()
8864 "Return table column at point.
8865 This function assumes point is on a table."
8866 (let ((pos (point)) (cnt 0))
8867 (save-excursion
8868 (beginning-of-line)
8869 (while (search-forward "|" pos t) (setq cnt (1+ cnt))))
8870 cnt))
8872 (defun markdown-table-get-cell (&optional n)
8873 "Return the content of the cell in column N of current row.
8874 N defaults to column at point. This function assumes point is on
8875 a table."
8876 (and n (markdown-table-goto-column n))
8877 (skip-chars-backward "^|\n") (backward-char 1)
8878 (if (looking-at "|[^|\r\n]*")
8879 (let* ((pos (match-beginning 0))
8880 (val (buffer-substring (1+ pos) (match-end 0))))
8881 (goto-char (min (point-at-eol) (+ 2 pos)))
8882 ;; Trim whitespaces
8883 (setq val (replace-regexp-in-string "\\`[ \t]+" "" val)
8884 val (replace-regexp-in-string "[ \t]+\\'" "" val)))
8885 (forward-char 1) ""))
8887 (defun markdown-table-goto-dline (n)
8888 "Go to the Nth data line in the table at point.
8889 Return t when the line exists, nil otherwise. This function
8890 assumes point is on a table."
8891 (goto-char (markdown-table-begin))
8892 (let ((end (markdown-table-end)) (cnt 0))
8893 (while (and (re-search-forward
8894 markdown-table-dline-regexp end t)
8895 (< (setq cnt (1+ cnt)) n)))
8896 (= cnt n)))
8898 (defun markdown-table-goto-column (n &optional on-delim)
8899 "Go to the Nth column in the table line at point.
8900 With optional argument ON-DELIM, stop with point before the left
8901 delimiter of the cell. If there are less than N cells, just go
8902 beyond the last delimiter. This function assumes point is on a
8903 table."
8904 (beginning-of-line 1)
8905 (when (> n 0)
8906 (while (and (> (setq n (1- n)) -1)
8907 (search-forward "|" (point-at-eol) t)))
8908 (if on-delim
8909 (backward-char 1)
8910 (when (looking-at " ") (forward-char 1)))))
8912 (defmacro markdown-table-save-cell (&rest body)
8913 "Save cell at point, execute BODY and restore cell.
8914 This function assumes point is on a table."
8915 (declare (debug (body)))
8916 (markdown--with-gensyms (line column)
8917 `(let ((,line (copy-marker (line-beginning-position)))
8918 (,column (markdown-table-get-column)))
8919 (unwind-protect
8920 (progn ,@body)
8921 (goto-char ,line)
8922 (markdown-table-goto-column ,column)
8923 (set-marker ,line nil)))))
8925 (defun markdown-table-blank-line (s)
8926 "Convert a table line S into a line with blank cells."
8927 (if (string-match "^[ \t]*|-" s)
8928 (setq s (mapconcat
8929 (lambda (x) (if (member x '(?| ?+)) "|" " "))
8930 s ""))
8931 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
8932 (setq s (replace-match
8933 (concat "|" (make-string (length (match-string 1 s)) ?\ ) "|")
8934 t t s)))
8937 (defun markdown-table-colfmt (fmtspec)
8938 "Process column alignment specifier FMTSPEC for tables."
8939 (when (stringp fmtspec)
8940 (mapcar (lambda (x)
8941 (cond ((string-match-p "^:.*:$" x) 'c)
8942 ((string-match-p "^:" x) 'l)
8943 ((string-match-p ":$" x) 'r)
8944 (t 'd)))
8945 (markdown--split-string fmtspec "\\s-*|\\s-*"))))
8947 (defun markdown-table-align ()
8948 "Align table at point.
8949 This function assumes point is on a table."
8950 (interactive)
8951 (let ((begin (markdown-table-begin))
8952 (end (copy-marker (markdown-table-end))))
8953 (markdown-table-save-cell
8954 (goto-char begin)
8955 (let* (fmtspec
8956 ;; Store table indent
8957 (indent (progn (looking-at "[ \t]*") (match-string 0)))
8958 ;; Split table in lines and save column format specifier
8959 (lines (mapcar (lambda (l)
8960 (if (string-match-p "\\`[ \t]*|[-:]" l)
8961 (progn (setq fmtspec (or fmtspec l)) nil) l))
8962 (markdown--split-string (buffer-substring begin end) "\n")))
8963 ;; Split lines in cells
8964 (cells (mapcar (lambda (l) (markdown--split-string l "\\s-*|\\s-*"))
8965 (remq nil lines)))
8966 ;; Calculate maximum number of cells in a line
8967 (maxcells (if cells
8968 (apply #'max (mapcar #'length cells))
8969 (user-error "Empty table")))
8970 ;; Empty cells to fill short lines
8971 (emptycells (make-list maxcells "")) maxwidths)
8972 ;; Calculate maximum width for each column
8973 (dotimes (i maxcells)
8974 (let ((column (mapcar (lambda (x) (or (nth i x) "")) cells)))
8975 (push (apply #'max 1 (mapcar #'markdown--string-width column))
8976 maxwidths)))
8977 (setq maxwidths (nreverse maxwidths))
8978 ;; Process column format specifier
8979 (setq fmtspec (markdown-table-colfmt fmtspec))
8980 ;; Compute formats needed for output of table lines
8981 (let ((hfmt (concat indent "|"))
8982 (rfmt (concat indent "|"))
8983 hfmt1 rfmt1 fmt)
8984 (dolist (width maxwidths (setq hfmt (concat (substring hfmt 0 -1) "|")))
8985 (setq fmt (pop fmtspec))
8986 (cond ((equal fmt 'l) (setq hfmt1 ":%s-|" rfmt1 " %%-%ds |"))
8987 ((equal fmt 'r) (setq hfmt1 "-%s:|" rfmt1 " %%%ds |"))
8988 ((equal fmt 'c) (setq hfmt1 ":%s:|" rfmt1 " %%-%ds |"))
8989 (t (setq hfmt1 "-%s-|" rfmt1 " %%-%ds |")))
8990 (setq rfmt (concat rfmt (format rfmt1 width)))
8991 (setq hfmt (concat hfmt (format hfmt1 (make-string width ?-)))))
8992 ;; Replace modified lines only
8993 (dolist (line lines)
8994 (let ((line (if line
8995 (apply #'format rfmt (append (pop cells) emptycells))
8996 hfmt))
8997 (previous (buffer-substring (point) (line-end-position))))
8998 (if (equal previous line)
8999 (forward-line)
9000 (insert line "\n")
9001 (delete-region (point) (line-beginning-position 2))))))
9002 (set-marker end nil)))))
9004 (defun markdown-table-insert-row (&optional arg)
9005 "Insert a new row above the row at point into the table.
9006 With optional argument ARG, insert below the current row."
9007 (interactive "P")
9008 (unless (markdown-table-at-point-p)
9009 (user-error "Not at a table"))
9010 (let* ((line (buffer-substring
9011 (line-beginning-position) (line-end-position)))
9012 (new (markdown-table-blank-line line)))
9013 (beginning-of-line (if arg 2 1))
9014 (unless (bolp) (insert "\n"))
9015 (insert-before-markers new "\n")
9016 (beginning-of-line 0)
9017 (re-search-forward "| ?" (line-end-position) t)))
9019 (defun markdown-table-delete-row ()
9020 "Delete row or horizontal line at point from the table."
9021 (interactive)
9022 (unless (markdown-table-at-point-p)
9023 (user-error "Not at a table"))
9024 (let ((col (current-column)))
9025 (kill-region (point-at-bol)
9026 (min (1+ (point-at-eol)) (point-max)))
9027 (unless (markdown-table-at-point-p) (beginning-of-line 0))
9028 (move-to-column col)))
9030 (defun markdown-table-move-row (&optional up)
9031 "Move table line at point down.
9032 With optional argument UP, move it up."
9033 (interactive "P")
9034 (unless (markdown-table-at-point-p)
9035 (user-error "Not at a table"))
9036 (let* ((col (current-column)) (pos (point))
9037 (tonew (if up 0 2)) txt)
9038 (beginning-of-line tonew)
9039 (unless (markdown-table-at-point-p)
9040 (goto-char pos) (user-error "Cannot move row further"))
9041 (goto-char pos) (beginning-of-line 1) (setq pos (point))
9042 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9043 (delete-region (point) (1+ (point-at-eol)))
9044 (beginning-of-line tonew)
9045 (insert txt) (beginning-of-line 0)
9046 (move-to-column col)))
9048 (defun markdown-table-move-row-up ()
9049 "Move table row at point up."
9050 (interactive)
9051 (markdown-table-move-row 'up))
9053 (defun markdown-table-move-row-down ()
9054 "Move table row at point down."
9055 (interactive)
9056 (markdown-table-move-row nil))
9058 (defun markdown-table-insert-column ()
9059 "Insert a new table column."
9060 (interactive)
9061 (unless (markdown-table-at-point-p)
9062 (user-error "Not at a table"))
9063 (let* ((col (max 1 (markdown-table-get-column)))
9064 (begin (markdown-table-begin))
9065 (end (copy-marker (markdown-table-end))))
9066 (markdown-table-save-cell
9067 (goto-char begin)
9068 (while (< (point) end)
9069 (markdown-table-goto-column col t)
9070 (if (markdown-table-hline-at-point-p)
9071 (insert "|---")
9072 (insert "| "))
9073 (forward-line)))
9074 (set-marker end nil)
9075 (markdown-table-align)))
9077 (defun markdown-table-delete-column ()
9078 "Delete column at point from table."
9079 (interactive)
9080 (unless (markdown-table-at-point-p)
9081 (user-error "Not at a table"))
9082 (let ((col (markdown-table-get-column))
9083 (begin (markdown-table-begin))
9084 (end (copy-marker (markdown-table-end))))
9085 (markdown-table-save-cell
9086 (goto-char begin)
9087 (while (< (point) end)
9088 (markdown-table-goto-column col t)
9089 (and (looking-at "|[^|\n]+|")
9090 (replace-match "|"))
9091 (forward-line)))
9092 (set-marker end nil)
9093 (markdown-table-goto-column (max 1 (1- col)))
9094 (markdown-table-align)))
9096 (defun markdown-table-move-column (&optional left)
9097 "Move table column at point to the right.
9098 With optional argument LEFT, move it to the left."
9099 (interactive "P")
9100 (unless (markdown-table-at-point-p)
9101 (user-error "Not at a table"))
9102 (let* ((col (markdown-table-get-column))
9103 (col1 (if left (1- col) col))
9104 (colpos (if left (1- col) (1+ col)))
9105 (begin (markdown-table-begin))
9106 (end (copy-marker (markdown-table-end))))
9107 (when (and left (= col 1))
9108 (user-error "Cannot move column further left"))
9109 (when (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9110 (user-error "Cannot move column further right"))
9111 (markdown-table-save-cell
9112 (goto-char begin)
9113 (while (< (point) end)
9114 (markdown-table-goto-column col1 t)
9115 (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9116 (replace-match "|\\2|\\1|"))
9117 (forward-line)))
9118 (set-marker end nil)
9119 (markdown-table-goto-column colpos)
9120 (markdown-table-align)))
9122 (defun markdown-table-move-column-left ()
9123 "Move table column at point to the left."
9124 (interactive)
9125 (markdown-table-move-column 'left))
9127 (defun markdown-table-move-column-right ()
9128 "Move table column at point to the right."
9129 (interactive)
9130 (markdown-table-move-column nil))
9132 (defun markdown-table-next-row ()
9133 "Go to the next row (same column) in the table.
9134 Create new table lines if required."
9135 (interactive)
9136 (unless (markdown-table-at-point-p)
9137 (user-error "Not at a table"))
9138 (if (or (looking-at "[ \t]*$")
9139 (save-excursion (skip-chars-backward " \t") (bolp)))
9140 (newline)
9141 (markdown-table-align)
9142 (let ((col (markdown-table-get-column)))
9143 (beginning-of-line 2)
9144 (if (or (not (markdown-table-at-point-p))
9145 (markdown-table-hline-at-point-p))
9146 (progn
9147 (beginning-of-line 0)
9148 (markdown-table-insert-row 'below)))
9149 (markdown-table-goto-column col)
9150 (skip-chars-backward "^|\n\r")
9151 (when (looking-at " ") (forward-char 1)))))
9153 (defun markdown-table-forward-cell ()
9154 "Go to the next cell in the table.
9155 Create new table lines if required."
9156 (interactive)
9157 (unless (markdown-table-at-point-p)
9158 (user-error "Not at a table"))
9159 (markdown-table-align)
9160 (let ((end (markdown-table-end)))
9161 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9162 (condition-case nil
9163 (progn
9164 (re-search-forward "|" end)
9165 (if (looking-at "[ \t]*$")
9166 (re-search-forward "|" end))
9167 (if (and (looking-at "[-:]")
9168 (re-search-forward "^[ \t]*|\\([^-:]\\)" end t))
9169 (goto-char (match-beginning 1)))
9170 (if (looking-at "[-:]")
9171 (progn
9172 (beginning-of-line 0)
9173 (markdown-table-insert-row 'below))
9174 (when (looking-at " ") (forward-char 1))))
9175 (error (markdown-table-insert-row 'below)))))
9177 (defun markdown-table-backward-cell ()
9178 "Go to the previous cell in the table."
9179 (interactive)
9180 (unless (markdown-table-at-point-p)
9181 (user-error "Not at a table"))
9182 (markdown-table-align)
9183 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9184 (condition-case nil
9185 (progn
9186 (re-search-backward "|" (markdown-table-begin))
9187 (re-search-backward "|" (markdown-table-begin)))
9188 (error (user-error "Cannot move to previous table cell")))
9189 (while (looking-at "|\\([-:]\\|[ \t]*$\\)")
9190 (re-search-backward "|" (markdown-table-begin)))
9191 (when (looking-at "| ?") (goto-char (match-end 0))))
9193 (defun markdown-table-transpose ()
9194 "Transpose table at point.
9195 Horizontal separator lines will be eliminated."
9196 (interactive)
9197 (unless (markdown-table-at-point-p)
9198 (user-error "Not at a table"))
9199 (let* ((table (buffer-substring-no-properties
9200 (markdown-table-begin) (markdown-table-end)))
9201 ;; Convert table to a Lisp structure
9202 (table (delq nil
9203 (mapcar
9204 (lambda (x)
9205 (unless (string-match-p
9206 markdown-table-hline-regexp x)
9207 (markdown--split-string x "\\s-*|\\s-*")))
9208 (markdown--split-string table "[ \t]*\n[ \t]*"))))
9209 (dline_old (markdown-table-get-dline))
9210 (col_old (markdown-table-get-column))
9211 (contents (mapcar (lambda (_)
9212 (let ((tp table))
9213 (mapcar
9214 (lambda (_)
9215 (prog1
9216 (pop (car tp))
9217 (setq tp (cdr tp))))
9218 table)))
9219 (car table))))
9220 (goto-char (markdown-table-begin))
9221 (re-search-forward "|") (backward-char)
9222 (delete-region (point) (markdown-table-end))
9223 (insert (mapconcat
9224 (lambda(x)
9225 (concat "| " (mapconcat 'identity x " | " ) " |\n"))
9226 contents ""))
9227 (markdown-table-goto-dline col_old)
9228 (markdown-table-goto-column dline_old))
9229 (markdown-table-align))
9231 (defun markdown-table-sort-lines (&optional sorting-type)
9232 "Sort table lines according to the column at point.
9234 The position of point indicates the column to be used for
9235 sorting, and the range of lines is the range between the nearest
9236 horizontal separator lines, or the entire table of no such lines
9237 exist. If point is before the first column, user will be prompted
9238 for the sorting column. If there is an active region, the mark
9239 specifies the first line and the sorting column, while point
9240 should be in the last line to be included into the sorting.
9242 The command then prompts for the sorting type which can be
9243 alphabetically or numerically. Sorting in reverse order is also
9244 possible.
9246 If SORTING-TYPE is specified when this function is called from a
9247 Lisp program, no prompting will take place. SORTING-TYPE must be
9248 a character, any of (?a ?A ?n ?N) where the capital letters
9249 indicate that sorting should be done in reverse order."
9250 (interactive)
9251 (unless (markdown-table-at-point-p)
9252 (user-error "Not at a table"))
9253 ;; Set sorting type and column used for sorting
9254 (let ((column (let ((c (markdown-table-get-column)))
9255 (cond ((> c 0) c)
9256 ((called-interactively-p 'any)
9257 (read-number "Use column N for sorting: "))
9258 (t 1))))
9259 (sorting-type
9260 (or sorting-type
9261 (read-char-exclusive
9262 "Sort type: [a]lpha [n]umeric (A/N means reversed): "))))
9263 (save-restriction
9264 ;; Narrow buffer to appropriate sorting area
9265 (if (region-active-p)
9266 (narrow-to-region
9267 (save-excursion
9268 (progn
9269 (goto-char (region-beginning)) (line-beginning-position)))
9270 (save-excursion
9271 (progn
9272 (goto-char (region-end)) (line-end-position))))
9273 (let ((start (markdown-table-begin))
9274 (end (markdown-table-end)))
9275 (narrow-to-region
9276 (save-excursion
9277 (if (re-search-backward
9278 markdown-table-hline-regexp start t)
9279 (line-beginning-position 2)
9280 start))
9281 (if (save-excursion (re-search-forward
9282 markdown-table-hline-regexp end t))
9283 (match-beginning 0)
9284 end))))
9285 ;; Determine arguments for `sort-subr'
9286 (let* ((extract-key-from-cell
9287 (cl-case sorting-type
9288 ((?a ?A) #'markdown--remove-invisible-markup) ;; #'identity)
9289 ((?n ?N) #'string-to-number)
9290 (t (user-error "Invalid sorting type: %c" sorting-type))))
9291 (predicate
9292 (cl-case sorting-type
9293 ((?n ?N) #'<)
9294 ((?a ?A) #'string<))))
9295 ;; Sort selected area
9296 (goto-char (point-min))
9297 (sort-subr (memq sorting-type '(?A ?N))
9298 (lambda ()
9299 (forward-line)
9300 (while (and (not (eobp))
9301 (not (looking-at
9302 markdown-table-dline-regexp)))
9303 (forward-line)))
9304 #'end-of-line
9305 (lambda ()
9306 (funcall extract-key-from-cell
9307 (markdown-table-get-cell column)))
9309 predicate)
9310 (goto-char (point-min))))))
9312 (defun markdown-table-convert-region (begin end &optional separator)
9313 "Convert region from BEGIN to END to table with SEPARATOR.
9315 If every line contains at least one TAB character, the function
9316 assumes that the material is tab separated (TSV). If every line
9317 contains a comma, comma-separated values (CSV) are assumed. If
9318 not, lines are split at whitespace into cells.
9320 You can use a prefix argument to force a specific separator:
9321 \\[universal-argument] once forces CSV, \\[universal-argument]
9322 twice forces TAB, and \\[universal-argument] three times will
9323 prompt for a regular expression to match the separator, and a
9324 numeric argument N indicates that at least N consecutive
9325 spaces, or alternatively a TAB should be used as the separator."
9327 (interactive "r\nP")
9328 (let* ((begin (min begin end)) (end (max begin end)) re)
9329 (goto-char begin) (beginning-of-line 1)
9330 (setq begin (point-marker))
9331 (goto-char end)
9332 (if (bolp) (backward-char 1) (end-of-line 1))
9333 (setq end (point-marker))
9334 (when (equal separator '(64))
9335 (setq separator (read-regexp "Regexp for cell separator: ")))
9336 (unless separator
9337 ;; Get the right cell separator
9338 (goto-char begin)
9339 (setq separator
9340 (cond
9341 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
9342 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
9343 (t 1))))
9344 (goto-char begin)
9345 (if (equal separator '(4))
9346 ;; Parse CSV
9347 (while (< (point) end)
9348 (cond
9349 ((looking-at "^") (insert "| "))
9350 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
9351 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
9352 (replace-match "\\1") (if (looking-at "\"") (insert "\"")))
9353 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
9354 ((looking-at "[ \t]*,") (replace-match " | "))
9355 (t (beginning-of-line 2))))
9356 (setq re
9357 (cond
9358 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
9359 ((equal separator '(16)) "^\\|\t")
9360 ((integerp separator)
9361 (if (< separator 1)
9362 (user-error "Cell separator must contain one or more spaces")
9363 (format "^ *\\| *\t *\\| \\{%d,\\}" separator)))
9364 ((stringp separator) (format "^ *\\|%s" separator))
9365 (t (error "Invalid cell separator"))))
9366 (while (re-search-forward re end t) (replace-match "| " t t)))
9367 (goto-char begin)
9368 (markdown-table-align)))
9371 ;;; ElDoc Support
9373 (defun markdown-eldoc-function ()
9374 "Return a helpful string when appropriate based on context.
9375 * Report URL when point is at a hidden URL.
9376 * Report language name when point is a code block with hidden markup."
9377 (cond
9378 ;; Hidden URL or reference for inline link
9379 ((and (or (thing-at-point-looking-at markdown-regex-link-inline)
9380 (thing-at-point-looking-at markdown-regex-link-reference))
9381 (or markdown-hide-urls markdown-hide-markup))
9382 (let* ((imagep (string-equal (match-string 1) "!"))
9383 (edit-keys (markdown--substitute-command-keys
9384 (if imagep
9385 "\\[markdown-insert-image]"
9386 "\\[markdown-insert-link]")))
9387 (edit-str (propertize edit-keys 'face 'font-lock-constant-face))
9388 (referencep (string-equal (match-string 5) "["))
9389 (object (if referencep "reference" "URL")))
9390 (format "Hidden %s (%s to edit): %s" object edit-str
9391 (if referencep
9392 (concat
9393 (propertize "[" 'face 'markdown-markup-face)
9394 (propertize (match-string-no-properties 6)
9395 'face 'markdown-reference-face)
9396 (propertize "]" 'face 'markdown-markup-face))
9397 (propertize (match-string-no-properties 6)
9398 'face 'markdown-url-face)))))
9399 ;; Hidden language name for fenced code blocks
9400 ((and (markdown-code-block-at-point-p)
9401 (not (get-text-property (point) 'markdown-pre))
9402 markdown-hide-markup)
9403 (let ((lang (save-excursion (markdown-code-block-lang))))
9404 (unless lang (setq lang "[unspecified]"))
9405 (format "Hidden code block language: %s (%s to toggle markup)"
9406 (propertize lang 'face 'markdown-language-keyword-face)
9407 (markdown--substitute-command-keys
9408 "\\[markdown-toggle-markup-hiding]"))))))
9411 ;;; Mode Definition ==========================================================
9413 (defun markdown-show-version ()
9414 "Show the version number in the minibuffer."
9415 (interactive)
9416 (message "markdown-mode, version %s" markdown-mode-version))
9418 (defun markdown-mode-info ()
9419 "Open the `markdown-mode' homepage."
9420 (interactive)
9421 (browse-url "https://jblevins.org/projects/markdown-mode/"))
9423 ;;;###autoload
9424 (define-derived-mode markdown-mode text-mode "Markdown"
9425 "Major mode for editing Markdown files."
9426 ;; Natural Markdown tab width
9427 (setq tab-width 4)
9428 ;; Comments
9429 (setq-local comment-start "<!-- ")
9430 (setq-local comment-end " -->")
9431 (setq-local comment-start-skip "<!--[ \t]*")
9432 (setq-local comment-column 0)
9433 (setq-local comment-auto-fill-only-comments nil)
9434 (setq-local comment-use-syntax t)
9435 ;; Syntax
9436 (add-hook 'syntax-propertize-extend-region-functions
9437 #'markdown-syntax-propertize-extend-region)
9438 (add-hook 'jit-lock-after-change-extend-region-functions
9439 #'markdown-font-lock-extend-region-function t t)
9440 (setq-local syntax-propertize-function #'markdown-syntax-propertize)
9441 (syntax-propertize (point-max)) ;; Propertize before hooks run, etc.
9442 ;; Font lock.
9443 (setq font-lock-defaults
9444 '(markdown-mode-font-lock-keywords
9445 nil nil nil nil
9446 (font-lock-multiline . t)
9447 (font-lock-syntactic-face-function . markdown-syntactic-face)
9448 (font-lock-extra-managed-props
9449 . (composition display invisible rear-nonsticky
9450 keymap help-echo mouse-face))))
9451 (if markdown-hide-markup
9452 (add-to-invisibility-spec 'markdown-markup)
9453 (remove-from-invisibility-spec 'markdown-markup))
9454 ;; Wiki links
9455 (markdown-setup-wiki-link-hooks)
9456 ;; Math mode
9457 (when markdown-enable-math (markdown-toggle-math t))
9458 ;; Add a buffer-local hook to reload after file-local variables are read
9459 (add-hook 'hack-local-variables-hook #'markdown-handle-local-variables nil t)
9460 ;; For imenu support
9461 (setq imenu-create-index-function
9462 (if markdown-nested-imenu-heading-index
9463 #'markdown-imenu-create-nested-index
9464 #'markdown-imenu-create-flat-index))
9465 ;; For menu support in XEmacs
9466 (easy-menu-add markdown-mode-menu markdown-mode-map)
9467 ;; Defun movement
9468 (setq-local beginning-of-defun-function #'markdown-beginning-of-defun)
9469 (setq-local end-of-defun-function #'markdown-end-of-defun)
9470 ;; Paragraph filling
9471 (setq-local fill-paragraph-function #'markdown-fill-paragraph)
9472 (setq-local paragraph-start
9473 ;; Should match start of lines that start or separate paragraphs
9474 (mapconcat #'identity
9476 "\f" ; starts with a literal line-feed
9477 "[ \t\f]*$" ; space-only line
9478 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9479 "[ \t]*[*+-][ \t]+" ; unordered list item
9480 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
9481 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
9482 "[ \t]*:[ \t]+" ; definition
9483 "^|" ; table or Pandoc line block
9485 "\\|"))
9486 (setq-local paragraph-separate
9487 ;; Should match lines that separate paragraphs without being
9488 ;; part of any paragraph:
9489 (mapconcat #'identity
9490 '("[ \t\f]*$" ; space-only line
9491 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9492 ;; The following is not ideal, but the Fill customization
9493 ;; options really only handle paragraph-starting prefixes,
9494 ;; not paragraph-ending suffixes:
9495 ".* $" ; line ending in two spaces
9496 "^#+"
9497 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
9498 "\\|"))
9499 (setq-local adaptive-fill-first-line-regexp "\\`[ \t]*[A-Z]?>[ \t]*?\\'")
9500 (setq-local adaptive-fill-regexp "\\s-*")
9501 (setq-local adaptive-fill-function #'markdown-adaptive-fill-function)
9502 (setq-local fill-forward-paragraph-function #'markdown-fill-forward-paragraph)
9503 ;; Outline mode
9504 (setq-local outline-regexp markdown-regex-header)
9505 (setq-local outline-level #'markdown-outline-level)
9506 ;; Cause use of ellipses for invisible text.
9507 (add-to-invisibility-spec '(outline . t))
9508 ;; ElDoc support
9509 (if (eval-when-compile (fboundp 'add-function))
9510 (add-function :before-until (local 'eldoc-documentation-function)
9511 #'markdown-eldoc-function)
9512 (setq-local eldoc-documentation-function #'markdown-eldoc-function))
9513 ;; Inhibiting line-breaking:
9514 ;; Separating out each condition into a separate function so that users can
9515 ;; override if desired (with remove-hook)
9516 (add-hook 'fill-nobreak-predicate
9517 #'markdown-line-is-reference-definition-p nil t)
9518 (add-hook 'fill-nobreak-predicate
9519 #'markdown-pipe-at-bol-p nil t)
9521 ;; Indentation
9522 (setq-local indent-line-function markdown-indent-function)
9524 ;; Flyspell
9525 (setq-local flyspell-generic-check-word-predicate
9526 #'markdown-flyspell-check-word-p)
9528 ;; Electric quoting
9529 (add-hook 'electric-quote-inhibit-functions
9530 #'markdown--inhibit-electric-quote nil :local)
9532 ;; Backwards compatibility with markdown-css-path
9533 (when (boundp 'markdown-css-path)
9534 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
9535 (add-to-list 'markdown-css-paths markdown-css-path))
9537 ;; Prepare hooks for XEmacs compatibility
9538 (when (featurep 'xemacs)
9539 (make-local-hook 'after-change-functions)
9540 (make-local-hook 'font-lock-extend-region-functions)
9541 (make-local-hook 'window-configuration-change-hook))
9543 ;; Make checkboxes buttons
9544 (when markdown-make-gfm-checkboxes-buttons
9545 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
9546 (add-hook 'after-change-functions #'markdown-gfm-checkbox-after-change-function t t)
9547 (add-hook 'change-major-mode-hook #'markdown-remove-gfm-checkbox-overlays t t))
9549 ;; edit-indirect
9550 (add-hook 'edit-indirect-after-commit-functions
9551 #'markdown--edit-indirect-after-commit-function
9552 nil 'local)
9554 ;; Marginalized headings
9555 (when markdown-marginalize-headers
9556 (add-hook 'window-configuration-change-hook
9557 #'markdown-marginalize-update-current nil t))
9559 ;; add live preview export hook
9560 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
9561 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
9563 ;;;###autoload
9564 (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode) t)
9565 ;;;###autoload
9566 (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode) t)
9569 ;;; GitHub Flavored Markdown Mode ============================================
9571 (defvar gfm-mode-hook nil
9572 "Hook run when entering GFM mode.")
9574 ;;;###autoload
9575 (define-derived-mode gfm-mode markdown-mode "GFM"
9576 "Major mode for editing GitHub Flavored Markdown files."
9577 (setq markdown-link-space-sub-char "-")
9578 (setq markdown-wiki-link-search-subdirectories t)
9579 (setq-local markdown-table-at-point-p-function 'gfm--table-at-point-p)
9580 (markdown-gfm-parse-buffer-for-languages))
9582 (define-obsolete-variable-alias
9583 'gfm-font-lock-keywords
9584 'markdown-mode-font-lock-keywords "v2.4")
9587 ;;; Viewing modes
9589 (defcustom markdown-hide-markup-in-view-modes t
9590 "Enable hidden markup mode in `markdown-view-mode' and `gfm-view-mode'."
9591 :group 'markdown
9592 :type 'boolean
9593 :safe 'booleanp)
9595 (defvar markdown-view-mode-map
9596 (let ((map (make-sparse-keymap)))
9597 (define-key map (kbd "p") #'markdown-outline-previous)
9598 (define-key map (kbd "n") #'markdown-outline-next)
9599 (define-key map (kbd "f") #'markdown-outline-next-same-level)
9600 (define-key map (kbd "b") #'markdown-outline-previous-same-level)
9601 (define-key map (kbd "u") #'markdown-outline-up)
9602 (define-key map (kbd "DEL") #'scroll-down-command)
9603 (define-key map (kbd "SPC") #'scroll-up-command)
9604 (define-key map (kbd ">") #'end-of-buffer)
9605 (define-key map (kbd "<") #'beginning-of-buffer)
9606 (define-key map (kbd "q") #'kill-this-buffer)
9607 (define-key map (kbd "?") #'describe-mode)
9608 map)
9609 "Keymap for `markdown-view-mode'.")
9611 ;;;###autoload
9612 (define-derived-mode markdown-view-mode markdown-mode "Markdown-View"
9613 "Major mode for viewing Markdown content."
9614 (setq-local markdown-hide-markup markdown-hide-markup-in-view-modes)
9615 (read-only-mode 1))
9617 (defvar gfm-view-mode-map
9618 markdown-view-mode-map
9619 "Keymap for `gfm-view-mode'.")
9621 ;;;###autoload
9622 (define-derived-mode gfm-view-mode gfm-mode "GFM-View"
9623 "Major mode for viewing GitHub Flavored Markdown content."
9624 (setq-local markdown-hide-markup markdown-hide-markup-in-view-modes)
9625 (read-only-mode 1))
9628 ;;; Live Preview Mode ============================================
9629 ;;;###autoload
9630 (define-minor-mode markdown-live-preview-mode
9631 "Toggle native previewing on save for a specific markdown file."
9632 :lighter " MD-Preview"
9633 (if markdown-live-preview-mode
9634 (if (markdown-live-preview-get-filename)
9635 (markdown-display-buffer-other-window (markdown-live-preview-export))
9636 (markdown-live-preview-mode -1)
9637 (user-error "Buffer %s does not visit a file" (current-buffer)))
9638 (markdown-live-preview-remove)))
9641 (provide 'markdown-mode)
9643 ;; Local Variables:
9644 ;; indent-tabs-mode: nil
9645 ;; coding: utf-8
9646 ;; End:
9647 ;;; markdown-mode.el ends here