Marginally speed up markdown-cur-list-item-end
[markdown-mode.git] / markdown-mode.el
blobed62db09e1962c5affc112ed240996e503c95e9c
1 ;;; markdown-mode.el --- Major mode for Markdown-formatted text -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2007-2017 Jason R. Blevins and markdown-mode
4 ;; contributors (see the commit log for details).
6 ;; Author: Jason R. Blevins <jblevins@xbeta.org>
7 ;; Maintainer: Jason R. Blevins <jblevins@xbeta.org>
8 ;; Created: May 24, 2007
9 ;; Version: 2.4-dev
10 ;; Package-Requires: ((emacs "24") (cl-lib "0.5"))
11 ;; Keywords: Markdown, GitHub Flavored Markdown, itex
12 ;; URL: https://jblevins.org/projects/markdown-mode/
14 ;; This file is not part of GNU Emacs.
16 ;; This program is free software; you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
21 ;; This program is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
29 ;;; Commentary:
31 ;; See the README.md file for details.
34 ;;; Code:
36 (require 'easymenu)
37 (require 'outline)
38 (require 'thingatpt)
39 (require 'cl-lib)
40 (require 'url-parse)
41 (require 'button)
42 (require 'color)
43 (require 'rx)
45 (defvar jit-lock-start)
46 (defvar jit-lock-end)
47 (defvar flyspell-generic-check-word-predicate)
49 (declare-function eww-open-file "eww")
50 (declare-function url-path-and-query "url-parse")
53 ;;; Constants =================================================================
55 (defconst markdown-mode-version "2.4-dev"
56 "Markdown mode version number.")
58 (defconst markdown-output-buffer-name "*markdown-output*"
59 "Name of temporary buffer for markdown command output.")
62 ;;; Global Variables ==========================================================
64 (defvar markdown-reference-label-history nil
65 "History of used reference labels.")
67 (defvar markdown-live-preview-mode nil
68 "Sentinel variable for command `markdown-live-preview-mode'.")
70 (defvar markdown-gfm-language-history nil
71 "History list of languages used in the current buffer in GFM code blocks.")
74 ;;; Customizable Variables ====================================================
76 (defvar markdown-mode-hook nil
77 "Hook run when entering Markdown mode.")
79 (defvar markdown-before-export-hook nil
80 "Hook run before running Markdown to export XHTML output.
81 The hook may modify the buffer, which will be restored to it's
82 original state after exporting is complete.")
84 (defvar markdown-after-export-hook nil
85 "Hook run after XHTML output has been saved.
86 Any changes to the output buffer made by this hook will be saved.")
88 (defgroup markdown nil
89 "Major mode for editing text files in Markdown format."
90 :prefix "markdown-"
91 :group 'wp
92 :link '(url-link "https://jblevins.org/projects/markdown-mode/"))
94 (defcustom markdown-command "markdown"
95 "Command to run markdown."
96 :group 'markdown
97 :type '(choice (string :tag "Shell command") function))
99 (defcustom markdown-command-needs-filename nil
100 "Set to non-nil if `markdown-command' does not accept input from stdin.
101 Instead, it will be passed a filename as the final command line
102 option. As a result, you will only be able to run Markdown from
103 buffers which are visiting a file."
104 :group 'markdown
105 :type 'boolean)
107 (defcustom markdown-open-command nil
108 "Command used for opening Markdown files directly.
109 For example, a standalone Markdown previewer. This command will
110 be called with a single argument: the filename of the current
111 buffer. It can also be a function, which will be called without
112 arguments."
113 :group 'markdown
114 :type '(choice file function (const :tag "None" nil)))
116 (defcustom markdown-hr-strings
117 '("-------------------------------------------------------------------------------"
118 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
119 "---------------------------------------"
120 "* * * * * * * * * * * * * * * * * * * *"
121 "---------"
122 "* * * * *")
123 "Strings to use when inserting horizontal rules.
124 The first string in the list will be the default when inserting a
125 horizontal rule. Strings should be listed in decreasing order of
126 prominence (as in headings from level one to six) for use with
127 promotion and demotion functions."
128 :group 'markdown
129 :type '(repeat string))
131 (defcustom markdown-bold-underscore nil
132 "Use two underscores when inserting bold text instead of two asterisks."
133 :group 'markdown
134 :type 'boolean)
136 (defcustom markdown-italic-underscore nil
137 "Use underscores when inserting italic text instead of asterisks."
138 :group 'markdown
139 :type 'boolean)
141 (defcustom markdown-marginalize-headers nil
142 "When non-nil, put opening atx header markup in a left margin.
144 This setting goes well with `markdown-asymmetric-header'. But
145 sadly it conflicts with `linum-mode' since they both use the
146 same margin."
147 :group 'markdown
148 :type 'boolean
149 :safe 'booleanp
150 :package-version '(markdown-mode . "2.4"))
152 (defcustom markdown-marginalize-headers-margin-width 6
153 "Character width of margin used for marginalized headers.
154 The default value is based on there being six heading levels
155 defined by Markdown and HTML. Increasing this produces extra
156 whitespace on the left. Decreasing it may be preferred when
157 fewer than six nested heading levels are used."
158 :group 'markdown
159 :type 'natnump
160 :safe 'natnump
161 :package-version '(markdown-mode . "2.4"))
163 (defcustom markdown-asymmetric-header nil
164 "Determines if atx header style will be asymmetric.
165 Set to a non-nil value to use asymmetric header styling, placing
166 header markup only at the beginning of the line. By default,
167 balanced markup will be inserted at the beginning and end of the
168 line around the header title."
169 :group 'markdown
170 :type 'boolean)
172 (defcustom markdown-indent-function 'markdown-indent-line
173 "Function to use to indent."
174 :group 'markdown
175 :type 'function)
177 (defcustom markdown-indent-on-enter t
178 "Determines indentation behavior when pressing \\[newline].
179 Possible settings are nil, t, and 'indent-and-new-item.
181 When non-nil, pressing \\[newline] will call `newline-and-indent'
182 to indent the following line according to the context using
183 `markdown-indent-function'. In this case, note that
184 \\[electric-newline-and-maybe-indent] can still be used to insert
185 a newline without indentation.
187 When set to 'indent-and-new-item and the point is in a list item
188 when \\[newline] is pressed, the list will be continued on the next
189 line, where a new item will be inserted.
191 When set to nil, simply call `newline' as usual. In this case,
192 you can still indent lines using \\[markdown-cycle] and continue
193 lists with \\[markdown-insert-list-item].
195 Note that this assumes the variable `electric-indent-mode' is
196 non-nil (enabled). When it is *disabled*, the behavior of
197 \\[newline] and `\\[electric-newline-and-maybe-indent]' are
198 reversed."
199 :group 'markdown
200 :type '(choice (const :tag "Don't automatically indent" nil)
201 (const :tag "Automatically indent" t)
202 (const :tag "Automatically indent and insert new list items" indent-and-new-item)))
204 (defcustom markdown-enable-wiki-links nil
205 "Syntax highlighting for wiki links.
206 Set this to a non-nil value to turn on wiki link support by default.
207 Support can be toggled later using the `markdown-toggle-wiki-links'
208 function or \\[markdown-toggle-wiki-links]."
209 :group 'markdown
210 :type 'boolean
211 :safe 'booleanp
212 :package-version '(markdown-mode . "2.2"))
214 (defcustom markdown-wiki-link-alias-first t
215 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
216 Otherwise, they will be treated as [[PageName|alias text]]."
217 :group 'markdown
218 :type 'boolean
219 :safe 'booleanp)
221 (defcustom markdown-wiki-link-search-subdirectories nil
222 "When non-nil, search for wiki link targets in subdirectories.
223 This is the default search behavior for GitHub and is
224 automatically set to t in `gfm-mode'."
225 :group 'markdown
226 :type 'boolean
227 :safe 'booleanp
228 :package-version '(markdown-mode . "2.2"))
230 (defcustom markdown-wiki-link-search-parent-directories nil
231 "When non-nil, search for wiki link targets in parent directories.
232 This is the default search behavior of Ikiwiki."
233 :group 'markdown
234 :type 'boolean
235 :safe 'booleanp
236 :package-version '(markdown-mode . "2.2"))
238 (defcustom markdown-wiki-link-fontify-missing nil
239 "When non-nil, change wiki link face according to existence of target files.
240 This is expensive because it requires checking for the file each time the buffer
241 changes or the user switches windows. It is disabled by default because it may
242 cause lag when typing on slower machines."
243 :group 'markdown
244 :type 'boolean
245 :safe 'booleanp
246 :package-version '(markdown-mode . "2.2"))
248 (defcustom markdown-uri-types
249 '("acap" "cid" "data" "dav" "fax" "file" "ftp"
250 "gopher" "http" "https" "imap" "ldap" "mailto"
251 "mid" "message" "modem" "news" "nfs" "nntp"
252 "pop" "prospero" "rtsp" "service" "sip" "tel"
253 "telnet" "tip" "urn" "vemmi" "wais")
254 "Link types for syntax highlighting of URIs."
255 :group 'markdown
256 :type '(repeat (string :tag "URI scheme")))
258 (defcustom markdown-url-compose-char
259 '(?∞ ?… ?⋯ ?# ?★ ?⚓)
260 "Placeholder character for hidden URLs.
261 This may be a single character or a list of characters. In case
262 of a list, the first one that satisfies `char-displayable-p' will
263 be used."
264 :type '(choice
265 (character :tag "Single URL replacement character")
266 (repeat :tag "List of possible URL replacement characters"
267 character))
268 :package-version '(markdown-mode . "2.3"))
270 (defcustom markdown-blockquote-display-char
271 '("▌" "┃" ">")
272 "String to display when hiding blockquote markup.
273 This may be a single string or a list of string. In case of a
274 list, the first one that satisfies `char-displayable-p' will be
275 used."
276 :type 'string
277 :type '(choice
278 (string :tag "Single blockquote display string")
279 (repeat :tag "List of possible blockquote display strings" string))
280 :package-version '(markdown-mode . "2.3"))
282 (defcustom markdown-hr-display-char
283 '(?─ ?━ ?-)
284 "Character for hiding horizontal rule markup.
285 This may be a single character or a list of characters. In case
286 of a list, the first one that satisfies `char-displayable-p' will
287 be used."
288 :group 'markdown
289 :type '(choice
290 (character :tag "Single HR display character")
291 (repeat :tag "List of possible HR display characters" character))
292 :package-version '(markdown-mode . "2.3"))
294 (defcustom markdown-definition-display-char
295 '(?⁘ ?⁙ ?≡ ?⌑ ?◊ ?:)
296 "Character for replacing definition list markup.
297 This may be a single character or a list of characters. In case
298 of a list, the first one that satisfies `char-displayable-p' will
299 be used."
300 :type '(choice
301 (character :tag "Single definition list character")
302 (repeat :tag "List of possible definition list characters" character))
303 :package-version '(markdown-mode . "2.3"))
305 (defcustom markdown-enable-math nil
306 "Syntax highlighting for inline LaTeX and itex expressions.
307 Set this to a non-nil value to turn on math support by default.
308 Math support can be enabled, disabled, or toggled later using
309 `markdown-toggle-math' or \\[markdown-toggle-math]."
310 :group 'markdown
311 :type 'boolean
312 :safe 'booleanp)
313 (make-variable-buffer-local 'markdown-enable-math)
315 (defcustom markdown-enable-html t
316 "Enable font-lock support for HTML tags and attributes."
317 :group 'markdown
318 :type 'boolean
319 :safe 'booleanp
320 :package-version '(markdown-mode . "2.4"))
322 (defcustom markdown-css-paths nil
323 "URL of CSS file to link to in the output XHTML."
324 :group 'markdown
325 :type '(repeat (string :tag "CSS File Path")))
327 (defcustom markdown-content-type ""
328 "Content type string for the http-equiv header in XHTML output.
329 When set to a non-empty string, insert the http-equiv attribute.
330 Otherwise, this attribute is omitted."
331 :group 'markdown
332 :type 'string)
334 (defcustom markdown-coding-system nil
335 "Character set string for the http-equiv header in XHTML output.
336 Defaults to `buffer-file-coding-system' (and falling back to
337 `iso-8859-1' when not available). Common settings are `utf-8'
338 and `iso-latin-1'. Use `list-coding-systems' for more choices."
339 :group 'markdown
340 :type 'coding-system)
342 (defcustom markdown-export-kill-buffer t
343 "Kill output buffer after HTML export.
344 When non-nil, kill the HTML output buffer after
345 exporting with `markdown-export'."
346 :group 'markdown
347 :type 'boolean
348 :safe 'booleanp
349 :package-version '(markdown-mode . "2.4"))
351 (defcustom markdown-xhtml-header-content ""
352 "Additional content to include in the XHTML <head> block."
353 :group 'markdown
354 :type 'string)
356 (defcustom markdown-xhtml-standalone-regexp
357 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
358 "Regexp indicating whether `markdown-command' output is standalone XHTML."
359 :group 'markdown
360 :type 'regexp)
362 (defcustom markdown-link-space-sub-char "_"
363 "Character to use instead of spaces when mapping wiki links to filenames."
364 :group 'markdown
365 :type 'string)
367 (defcustom markdown-reference-location 'header
368 "Position where new reference definitions are inserted in the document."
369 :group 'markdown
370 :type '(choice (const :tag "At the end of the document" end)
371 (const :tag "Immediately after the current block" immediately)
372 (const :tag "At the end of the subtree" subtree)
373 (const :tag "Before next header" header)))
375 (defcustom markdown-footnote-location 'end
376 "Position where new footnotes are inserted in the document."
377 :group 'markdown
378 :type '(choice (const :tag "At the end of the document" end)
379 (const :tag "Immediately after the current block" immediately)
380 (const :tag "At the end of the subtree" subtree)
381 (const :tag "Before next header" header)))
383 (defcustom markdown-footnote-display '((raise 0.2) (height 0.8))
384 "Display specification for footnote markers and inline footnotes.
385 By default, footnote text is reduced in size and raised. Set to
386 nil to disable this."
387 :group 'markdown
388 :type '(choice (sexp :tag "Display specification")
389 (const :tag "Don't set display property" nil))
390 :package-version '(markdown-mode . "2.4"))
392 (defcustom markdown-sub-superscript-display
393 '(((raise -0.3) (height 0.7)) . ((raise 0.3) (height 0.7)))
394 "Display specification for subscript and superscripts.
395 The car is used for subscript, the cdr is used for superscripts."
396 :group 'markdown
397 :type '(cons (choice (sexp :tag "Subscript form")
398 (const :tag "No lowering" nil))
399 (choice (sexp :tag "Superscript form")
400 (const :tag "No raising" nil)))
401 :package-version '(markdown-mode . "2.4"))
403 (defcustom markdown-unordered-list-item-prefix " * "
404 "String inserted before unordered list items."
405 :group 'markdown
406 :type 'string)
408 (defcustom markdown-nested-imenu-heading-index t
409 "Use nested or flat imenu heading index.
410 A nested index may provide more natural browsing from the menu,
411 but a flat list may allow for faster keyboard navigation via tab
412 completion."
413 :group 'markdown
414 :type 'boolean
415 :safe 'booleanp
416 :package-version '(markdown-mode . "2.2"))
418 (defcustom markdown-make-gfm-checkboxes-buttons t
419 "When non-nil, make GFM checkboxes into buttons."
420 :group 'markdown
421 :type 'boolean)
423 (defcustom markdown-use-pandoc-style-yaml-metadata nil
424 "When non-nil, allow YAML metadata anywhere in the document."
425 :group 'markdown
426 :type 'boolean)
428 (defcustom markdown-split-window-direction 'any
429 "Preference for splitting windows for static and live preview.
430 The default value is 'any, which instructs Emacs to use
431 `split-window-sensibly' to automatically choose how to split
432 windows based on the values of `split-width-threshold' and
433 `split-height-threshold' and the available windows. To force
434 vertically split (left and right) windows, set this to 'vertical
435 or 'right. To force horizontally split (top and bottom) windows,
436 set this to 'horizontal or 'below."
437 :group 'markdown
438 :type '(choice (const :tag "Automatic" any)
439 (const :tag "Right (vertical)" right)
440 (const :tag "Below (horizontal)" below))
441 :package-version '(markdown-mode . "2.2"))
443 (defcustom markdown-live-preview-window-function
444 'markdown-live-preview-window-eww
445 "Function to display preview of Markdown output within Emacs.
446 Function must update the buffer containing the preview and return
447 the buffer."
448 :group 'markdown
449 :type 'function)
451 (defcustom markdown-live-preview-delete-export 'delete-on-destroy
452 "Delete exported HTML file when using `markdown-live-preview-export'.
453 If set to 'delete-on-export, delete on every export. When set to
454 'delete-on-destroy delete when quitting from command
455 `markdown-live-preview-mode'. Never delete if set to nil."
456 :group 'markdown
457 :type '(choice
458 (const :tag "Delete on every export" delete-on-export)
459 (const :tag "Delete when quitting live preview" delete-on-destroy)
460 (const :tag "Never delete" nil)))
462 (defcustom markdown-list-indent-width 4
463 "Depth of indentation for markdown lists.
464 Used in `markdown-demote-list-item' and
465 `markdown-promote-list-item'."
466 :group 'markdown
467 :type 'integer)
469 (defcustom markdown-enable-prefix-prompts t
470 "Display prompts for certain prefix commands.
471 Set to nil to disable these prompts."
472 :group 'markdown
473 :type 'boolean
474 :safe 'booleanp
475 :package-version '(markdown-mode . "2.3"))
477 (defcustom markdown-gfm-additional-languages nil
478 "Extra languages made available when inserting GFM code blocks.
479 Language strings must have be trimmed of whitespace and not
480 contain any curly braces. They may be of arbitrary
481 capitalization, though."
482 :group 'markdown
483 :type '(repeat (string :validate markdown-validate-language-string)))
485 (defcustom markdown-gfm-use-electric-backquote t
486 "Use `markdown-electric-backquote' when backquote is hit three times."
487 :group 'markdown
488 :type 'boolean)
490 (defcustom markdown-gfm-downcase-languages t
491 "If non-nil, downcase suggested languages.
492 This applies to insertions done with
493 `markdown-electric-backquote'."
494 :group 'markdown
495 :type 'boolean)
497 (defcustom markdown-edit-code-block-default-mode 'normal-mode
498 "Default mode to use for editing code blocks.
499 This mode is used when automatic detection fails, such as for GFM
500 code blocks with no language specified."
501 :group 'markdown
502 :type 'symbol
503 :package-version '(markdown-mode . "2.4"))
505 (defcustom markdown-gfm-uppercase-checkbox nil
506 "If non-nil, use [X] for completed checkboxes, [x] otherwise."
507 :group 'markdown
508 :type 'boolean
509 :safe 'booleanp)
511 (defcustom markdown-hide-urls nil
512 "Hide URLs of inline links and reference tags of reference links.
513 Such URLs will be replaced by a single customizable
514 character, defined by `markdown-url-compose-char', but are still part
515 of the buffer. Links can be edited interactively with
516 \\[markdown-insert-link] or, for example, by deleting the final
517 parenthesis to remove the invisibility property. You can also
518 hover your mouse pointer over the link text to see the URL.
519 Set this to a non-nil value to turn this feature on by default.
520 You can interactively set the value of this variable by calling
521 `markdown-toggle-url-hiding', pressing \\[markdown-toggle-url-hiding],
522 or from the menu Markdown > Links & Images menu."
523 :group 'markdown
524 :type 'boolean
525 :safe 'booleanp
526 :package-version '(markdown-mode . "2.3"))
527 (make-variable-buffer-local 'markdown-hide-urls)
529 (defcustom markdown-translate-filename-function #'identity
530 "Function to use to translate filenames when following links.
531 \\<markdown-mode-map>\\[markdown-follow-thing-at-point] and \\[markdown-follow-link-at-point]
532 call this function with the filename as only argument whenever
533 they encounter a filename (instead of a URL) to be visited and
534 use its return value instead of the filename in the link. For
535 example, if absolute filenames are actually relative to a server
536 root directory, you can set
537 `markdown-translate-filename-function' to a function that
538 prepends the root directory to the given filename."
539 :group 'markdown
540 :type 'function
541 :risky t
542 :package-version '(markdown-mode . "2.4"))
544 (defcustom markdown-max-image-size nil
545 "Maximum width and height for displayed inline images.
546 This variable may be nil or a cons cell (MAX-WIDTH . MAX-HEIGHT).
547 When nil, use the actual size. Otherwise, use ImageMagick to
548 resize larger images to be of the given maximum dimensions. This
549 requires Emacs to be built with ImageMagick support."
550 :group 'markdown
551 :package-version '(markdown-mode . "2.4")
552 :type '(choice
553 (const :tag "Use actual image width" nil)
554 (cons (choice (sexp :tag "Maximum width in pixels")
555 (const :tag "No maximum width" nil))
556 (choice (sexp :tag "Maximum height in pixels")
557 (const :tag "No maximum height" nil)))))
560 ;;; Markdown-Specific `rx' Macro
562 ;; Based on python-rx from python.el.
563 (eval-and-compile
564 (defconst markdown-rx-constituents
565 `((newline . ,(rx "\n"))
566 (indent . ,(rx (or (repeat 4 " ") "\t")))
567 (block-end . ,(rx (and (or (one-or-more (zero-or-more blank) "\n") line-end))))
568 (numeral . ,(rx (and (one-or-more (any "0-9#")) ".")))
569 (bullet . ,(rx (any "*+:-")))
570 (list-marker . ,(rx (or (and (one-or-more (any "0-9#")) ".")
571 (any "*+:-"))))
572 (checkbox . ,(rx "[" (any " xX") "]")))
573 "Markdown-specific sexps for `markdown-rx'")
575 (defmacro markdown-rx (&rest regexps)
576 "Markdown mode specialized rx macro.
577 This variant of `rx' supports common Markdown named REGEXPS."
578 (let ((rx-constituents (append markdown-rx-constituents rx-constituents)))
579 (cond ((null regexps)
580 (error "No regexp"))
581 ((cdr regexps)
582 (rx-to-string `(and ,@regexps) t))
584 (rx-to-string (car regexps) t))))))
587 ;;; Regular Expressions =======================================================
589 (defconst markdown-regex-comment-start
590 "<!--"
591 "Regular expression matches HTML comment opening.")
593 (defconst markdown-regex-comment-end
594 "--[ \t]*>"
595 "Regular expression matches HTML comment closing.")
597 (defconst markdown-regex-link-inline
598 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)\\((\\)\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?\\()\\)"
599 "Regular expression for a [text](file) or an image link ![text](file).
600 Group 1 matches the leading exclamation point (optional).
601 Group 2 matches the opening square bracket.
602 Group 3 matches the text inside the square brackets.
603 Group 4 matches the closing square bracket.
604 Group 5 matches the opening parenthesis.
605 Group 6 matches the URL.
606 Group 7 matches the title (optional).
607 Group 8 matches the closing parenthesis.")
609 (defconst markdown-regex-link-reference
610 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)[ ]?\\(\\[\\)\\([^]]*?\\)\\(\\]\\)"
611 "Regular expression for a reference link [text][id].
612 Group 1 matches the leading exclamation point (optional).
613 Group 2 matches the opening square bracket for the link text.
614 Group 3 matches the text inside the square brackets.
615 Group 4 matches the closing square bracket for the link text.
616 Group 5 matches the opening square bracket for the reference label.
617 Group 6 matches the reference label.
618 Group 7 matches the closing square bracket for the reference label.")
620 (defconst markdown-regex-reference-definition
621 "^ \\{0,3\\}\\(\\[\\)\\([^]\n]+?\\)\\(\\]\\)\\(:\\)\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
622 "Regular expression for a reference definition.
623 Group 1 matches the opening square bracket.
624 Group 2 matches the reference label.
625 Group 3 matches the closing square bracket.
626 Group 4 matches the colon.
627 Group 5 matches the URL.
628 Group 6 matches the title attribute (optional).")
630 (defconst markdown-regex-footnote
631 "\\(\\[\\^\\)\\(.+?\\)\\(\\]\\)"
632 "Regular expression for a footnote marker [^fn].
633 Group 1 matches the opening square bracket and carat.
634 Group 2 matches only the label, without the surrounding markup.
635 Group 3 matches the closing square bracket.")
637 (defconst markdown-regex-header
638 "^\\(?:\\([^\r\n\t -].*\\)\n\\(?:\\(=+\\)\\|\\(-+\\)\\)\\|\\(#+[ \t]+\\)\\(.*?\\)\\([ \t]*#*\\)\\)$"
639 "Regexp identifying Markdown headings.
640 Group 1 matches the text of a setext heading.
641 Group 2 matches the underline of a level-1 setext heading.
642 Group 3 matches the underline of a level-2 setext heading.
643 Group 4 matches the opening hash marks of an atx heading and whitespace.
644 Group 5 matches the text, without surrounding whitespace, of an atx heading.
645 Group 6 matches the closing whitespace and hash marks of an atx heading.")
647 (defconst markdown-regex-header-setext
648 "^\\([^\r\n\t -].*\\)\n\\(=+\\|-+\\)$"
649 "Regular expression for generic setext-style (underline) headers.")
651 (defconst markdown-regex-header-atx
652 "^\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
653 "Regular expression for generic atx-style (hash mark) headers.")
655 (defconst markdown-regex-hr
656 (rx line-start
657 (group (or (and (repeat 3 (and "*" (? " "))) (* (any "* ")))
658 (and (repeat 3 (and "-" (? " "))) (* (any "- ")))
659 (and (repeat 3 (and "_" (? " "))) (* (any "_ ")))))
660 line-end)
661 "Regular expression for matching Markdown horizontal rules.")
663 (defconst markdown-regex-code
664 "\\(?:\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(?:.\\|\n[^\n]\\)*?[^`]\\)\\(\\2\\)\\)\\(?:[^`]\\|\\'\\)"
665 "Regular expression for matching inline code fragments.
667 Group 1 matches the entire code fragment including the backquotes.
668 Group 2 matches the opening backquotes.
669 Group 3 matches the code fragment itself, without backquotes.
670 Group 4 matches the closing backquotes.
672 The leading, unnumbered group ensures that the leading backquote
673 character is not escaped.
674 The last group, also unnumbered, requires that the character
675 following the code fragment is not a backquote.
676 Note that \\(?:.\\|\n[^\n]\\) matches any character, including newlines,
677 but not two newlines in a row.")
679 (defconst markdown-regex-kbd
680 "\\(<kbd>\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(</kbd>\\)"
681 "Regular expression for matching <kbd> tags.
682 Groups 1 and 3 match the opening and closing tags.
683 Group 2 matches the key sequence.")
685 (defconst markdown-regex-gfm-code-block-open
686 "^[[:blank:]]*\\(```\\)\\([[:blank:]]*{?[[:blank:]]*\\)\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$"
687 "Regular expression matching opening of GFM code blocks.
688 Group 1 matches the opening three backquotes and any following whitespace.
689 Group 2 matches the opening brace (optional) and surrounding whitespace.
690 Group 3 matches the language identifier (optional).
691 Group 4 matches the info string (optional).
692 Group 5 matches the closing brace (optional), whitespace, and newline.
693 Groups need to agree with `markdown-regex-tilde-fence-begin'.")
695 (defconst markdown-regex-gfm-code-block-close
696 "^[[:blank:]]*\\(```\\)\\(\\s *?\\)$"
697 "Regular expression matching closing of GFM code blocks.
698 Group 1 matches the closing three backquotes.
699 Group 2 matches any whitespace and the final newline.")
701 (defconst markdown-regex-pre
702 "^\\( \\|\t\\).*$"
703 "Regular expression for matching preformatted text sections.")
705 (defconst markdown-regex-list
706 (markdown-rx line-start
707 ;; 1. Leading whitespace
708 (group (* blank))
709 ;; 2. List marker: a numeral, bullet, or colon
710 (group list-marker)
711 ;; 3. Trailing whitespace
712 (group (+ blank))
713 ;; 4. Optional checkbox for GFM task list items
714 (opt (group (and checkbox (* blank)))))
715 "Regular expression for matching list items.")
717 (defconst markdown-regex-bold
718 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
719 "Regular expression for matching bold text.
720 Group 1 matches the character before the opening asterisk or
721 underscore, if any, ensuring that it is not a backslash escape.
722 Group 2 matches the entire expression, including delimiters.
723 Groups 3 and 5 matches the opening and closing delimiters.
724 Group 4 matches the text inside the delimiters.")
726 (defconst markdown-regex-italic
727 "\\(?:^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t*]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
728 "Regular expression for matching italic text.
729 The leading unnumbered matches the character before the opening
730 asterisk or underscore, if any, ensuring that it is not a
731 backslash escape.
732 Group 1 matches the entire expression, including delimiters.
733 Groups 2 and 4 matches the opening and closing delimiters.
734 Group 3 matches the text inside the delimiters.")
736 (defconst markdown-regex-strike-through
737 "\\(^\\|[^\\]\\)\\(\\(~~\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(~~\\)\\)"
738 "Regular expression for matching strike-through text.
739 Group 1 matches the character before the opening tilde, if any,
740 ensuring that it is not a backslash escape.
741 Group 2 matches the entire expression, including delimiters.
742 Groups 3 and 5 matches the opening and closing delimiters.
743 Group 4 matches the text inside the delimiters.")
745 (defconst markdown-regex-gfm-italic
746 "\\(?:^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\2\\|[^ ]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
747 "Regular expression for matching italic text in GitHub Flavored Markdown.
748 Underscores in words are not treated as special.
749 Group 1 matches the entire expression, including delimiters.
750 Groups 2 and 4 matches the opening and closing delimiters.
751 Group 3 matches the text inside the delimiters.")
753 (defconst markdown-regex-blockquote
754 "^[ \t]*\\([A-Z]?>\\)\\([ \t]*\\)\\(.*\\)$"
755 "Regular expression for matching blockquote lines.
756 Also accounts for a potential capital letter preceding the angle
757 bracket, for use with Leanpub blocks (asides, warnings, info
758 blocks, etc.).
759 Group 1 matches the leading angle bracket.
760 Group 2 matches the separating whitespace.
761 Group 3 matches the text.")
763 (defconst markdown-regex-line-break
764 "[^ \n\t][ \t]*\\( \\)$"
765 "Regular expression for matching line breaks.")
767 (defconst markdown-regex-wiki-link
768 "\\(?:^\\|[^\\]\\)\\(\\(\\[\\[\\)\\([^]|]+\\)\\(?:\\(|\\)\\([^]]+\\)\\)?\\(\\]\\]\\)\\)"
769 "Regular expression for matching wiki links.
770 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
771 wiki links of the form [[PageName|link text]].
772 The meanings of the first and second components depend
773 on the value of `markdown-wiki-link-alias-first'.
775 Group 1 matches the entire link.
776 Group 2 matches the opening square brackets.
777 Group 3 matches the first component of the wiki link.
778 Group 4 matches the pipe separator, when present.
779 Group 5 matches the second component of the wiki link, when present.
780 Group 6 matches the closing square brackets.")
782 (defconst markdown-regex-uri
783 (concat "\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+\\)")
784 "Regular expression for matching inline URIs.")
786 (defconst markdown-regex-angle-uri
787 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
788 "Regular expression for matching inline URIs in angle brackets.")
790 (defconst markdown-regex-email
791 "<\\(\\(?:\\sw\\|\\s_\\|\\s.\\)+@\\(?:\\sw\\|\\s_\\|\\s.\\)+\\)>"
792 "Regular expression for matching inline email addresses.")
794 (defsubst markdown-make-regex-link-generic ()
795 "Make regular expression for matching any recognized link."
796 (concat "\\(?:" markdown-regex-link-inline
797 (when markdown-enable-wiki-links
798 (concat "\\|" markdown-regex-wiki-link))
799 "\\|" markdown-regex-link-reference
800 "\\|" markdown-regex-angle-uri "\\)"))
802 (defconst markdown-regex-gfm-checkbox
803 " \\(\\[[ xX]\\]\\) "
804 "Regular expression for matching GFM checkboxes.
805 Group 1 matches the text to become a button.")
807 (defconst markdown-regex-blank-line
808 "^[[:blank:]]*$"
809 "Regular expression that matches a blank line.")
811 (defconst markdown-regex-block-separator
812 "\n[\n\t\f ]*\n"
813 "Regular expression for matching block boundaries.")
815 (defconst markdown-regex-block-separator-noindent
816 (concat "\\(\\`\\|\\(" markdown-regex-block-separator "\\)[^\n\t\f ]\\)")
817 "Regexp for block separators before lines with no indentation.")
819 (defconst markdown-regex-math-inline-single
820 "\\(?:^\\|[^\\]\\)\\(\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\)"
821 "Regular expression for itex $..$ math mode expressions.
822 Groups 1 and 3 match the opening and closing dollar signs.
823 Group 2 matches the mathematical expression contained within.")
825 (defconst markdown-regex-math-inline-double
826 "\\(?:^\\|[^\\]\\)\\(\\$\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\$\\)"
827 "Regular expression for itex $$..$$ math mode expressions.
828 Groups 1 and 3 match opening and closing dollar signs.
829 Group 2 matches the mathematical expression contained within.")
831 (defconst markdown-regex-math-display
832 (rx line-start (* blank)
833 (group (group (repeat 1 2 "\\")) "[")
834 (group (*? anything))
835 (group (backref 2) "]")
836 line-end)
837 "Regular expression for \[..\] or \\[..\\] display math.
838 Groups 1 and 4 match the opening and closing markup.
839 Group 3 matches the mathematical expression contained within.
840 Group 2 matches the opening slashes, and is used internally to
841 match the closing slashes.")
843 (defsubst markdown-make-tilde-fence-regex (num-tildes &optional end-of-line)
844 "Return regexp matching a tilde code fence at least NUM-TILDES long.
845 END-OF-LINE is the regexp construct to indicate end of line; $ if
846 missing."
847 (format "%s%d%s%s" "^[[:blank:]]*\\([~]\\{" num-tildes ",\\}\\)"
848 (or end-of-line "$")))
850 (defconst markdown-regex-tilde-fence-begin
851 (markdown-make-tilde-fence-regex
852 3 "\\([[:blank:]]*{?\\)[[:blank:]]*\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$")
853 "Regular expression for matching tilde-fenced code blocks.
854 Group 1 matches the opening tildes.
855 Group 2 matches (optional) opening brace and surrounding whitespace.
856 Group 3 matches the language identifier (optional).
857 Group 4 matches the info string (optional).
858 Group 5 matches the closing brace (optional) and any surrounding whitespace.
859 Groups need to agree with `markdown-regex-gfm-code-block-open'.")
861 (defconst markdown-regex-declarative-metadata
862 "^\\([[:alpha:]][[:alpha:] _-]*?\\)\\([:=][ \t]*\\)\\(.*\\)$"
863 "Regular expression for matching declarative metadata statements.
864 This matches MultiMarkdown metadata as well as YAML and TOML
865 assignments such as the following:
867 variable: value
871 variable = value")
873 (defconst markdown-regex-pandoc-metadata
874 "^\\(%\\)\\([ \t]*\\)\\(.*\\(?:\n[ \t]+.*\\)*\\)"
875 "Regular expression for matching Pandoc metadata.")
877 (defconst markdown-regex-yaml-metadata-border
878 "\\(-\\{3\\}\\)$"
879 "Regular expression for matching YAML metadata.")
881 (defconst markdown-regex-yaml-pandoc-metadata-end-border
882 "^\\(\\.\\{3\\}\\|\\-\\{3\\}\\)$"
883 "Regular expression for matching YAML metadata end borders.")
885 (defsubst markdown-get-yaml-metadata-start-border ()
886 "Return YAML metadata start border depending upon whether Pandoc is used."
887 (concat
888 (if markdown-use-pandoc-style-yaml-metadata "^" "\\`")
889 markdown-regex-yaml-metadata-border))
891 (defsubst markdown-get-yaml-metadata-end-border (_)
892 "Return YAML metadata end border depending upon whether Pandoc is used."
893 (if markdown-use-pandoc-style-yaml-metadata
894 markdown-regex-yaml-pandoc-metadata-end-border
895 markdown-regex-yaml-metadata-border))
897 (defconst markdown-regex-inline-attributes
898 "[ \t]*\\({:?\\)[ \t]*\\(\\(#[[:alpha:]_.:-]+\\|\\.[[:alpha:]_.:-]+\\|\\w+=['\"]?[^\n'\"]*['\"]?\\),?[ \t]*\\)+\\(}\\)[ \t]*$"
899 "Regular expression for matching inline identifiers or attribute lists.
900 Compatible with Pandoc, Python Markdown, PHP Markdown Extra, and Leanpub.")
902 (defconst markdown-regex-leanpub-sections
903 (concat
904 "^\\({\\)\\("
905 (regexp-opt '("frontmatter" "mainmatter" "backmatter" "appendix" "pagebreak"))
906 "\\)\\(}\\)[ \t]*\n")
907 "Regular expression for Leanpub section markers and related syntax.")
909 (defconst markdown-regex-sub-superscript
910 "\\(?:^\\|[^\\~^]\\)\\(\\([~^]\\)\\([[:alnum:]]+\\)\\(\\2\\)\\)"
911 "The regular expression matching a sub- or superscript.
912 The leading un-numbered group matches the character before the
913 opening tilde or carat, if any, ensuring that it is not a
914 backslash escape, carat, or tilde.
915 Group 1 matches the entire expression, including markup.
916 Group 2 matches the opening markup--a tilde or carat.
917 Group 3 matches the text inside the delimiters.
918 Group 4 matches the closing markup--a tilde or carat.")
920 (defconst markdown-regex-include
921 "^\\(<<\\)\\(?:\\(\\[\\)\\(.*\\)\\(\\]\\)\\)?\\(?:\\((\\)\\(.*\\)\\()\\)\\)?\\(?:\\({\\)\\(.*\\)\\(}\\)\\)?$"
922 "Regular expression matching common forms of include syntax.
923 Marked 2, Leanpub, and other processors support some of these forms:
925 <<[sections/section1.md]
926 <<(folder/filename)
927 <<[Code title](folder/filename)
928 <<{folder/raw_file.html}
930 Group 1 matches the opening two angle brackets.
931 Groups 2-4 match the opening square bracket, the text inside,
932 and the closing square bracket, respectively.
933 Groups 5-7 match the opening parenthesis, the text inside, and
934 the closing parenthesis.
935 Groups 8-10 match the opening brace, the text inside, and the brace.")
937 (defconst markdown-regex-pandoc-inline-footnote
938 "\\(\\^\\)\\(\\[\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(\\]\\)"
939 "Regular expression for Pandoc inline footnote^[footnote text].
940 Group 1 matches the opening caret.
941 Group 2 matches the opening square bracket.
942 Group 3 matches the footnote text, without the surrounding markup.
943 Group 4 matches the closing square bracket.")
945 (defconst markdown-regex-html-attr
946 "\\(\\<[[:alpha:]:-]+\\>\\)\\(\\s-*\\(=\\)\\s-*\\(\".*?\"\\|'.*?'\\|[^'\">[:space:]]+\\)?\\)?"
947 "Regular expression for matching HTML attributes and values.
948 Group 1 matches the attribute name.
949 Group 2 matches the following whitespace, equals sign, and value, if any.
950 Group 3 matches the equals sign, if any.
951 Group 4 matches single-, double-, or un-quoted attribute values.")
953 (defconst markdown-regex-html-tag
954 (concat "\\(</?\\)\\(\\w+\\)\\(\\(\\s-+" markdown-regex-html-attr
955 "\\)+\\s-*\\|\\s-*\\)\\(/?>\\)")
956 "Regular expression for matching HTML tags.
957 Groups 1 and 9 match the beginning and ending angle brackets and slashes.
958 Group 2 matches the tag name.
959 Group 3 matches all attributes and whitespace following the tag name.")
961 (defconst markdown-regex-html-entity
962 "\\(&#?[[:alnum:]]+;\\)"
963 "Regular expression for matching HTML entities.")
966 ;;; Syntax ====================================================================
968 (defvar markdown--syntax-properties
969 (list 'markdown-tilde-fence-begin nil
970 'markdown-tilde-fence-end nil
971 'markdown-fenced-code nil
972 'markdown-yaml-metadata-begin nil
973 'markdown-yaml-metadata-end nil
974 'markdown-yaml-metadata-section nil
975 'markdown-gfm-block-begin nil
976 'markdown-gfm-block-end nil
977 'markdown-gfm-code nil
978 'markdown-list-item nil
979 'markdown-pre nil
980 'markdown-blockquote nil
981 'markdown-hr nil
982 'markdown-comment nil
983 'markdown-heading nil
984 'markdown-heading-1-setext nil
985 'markdown-heading-2-setext nil
986 'markdown-heading-1-atx nil
987 'markdown-heading-2-atx nil
988 'markdown-heading-3-atx nil
989 'markdown-heading-4-atx nil
990 'markdown-heading-5-atx nil
991 'markdown-heading-6-atx nil
992 'markdown-metadata-key nil
993 'markdown-metadata-value nil
994 'markdown-metadata-markup nil)
995 "Property list of all Markdown syntactic properties.")
997 (defsubst markdown-in-comment-p (&optional pos)
998 "Return non-nil if POS is in a comment.
999 If POS is not given, use point instead."
1000 (get-text-property (or pos (point)) 'markdown-comment))
1002 (defun markdown-syntax-propertize-extend-region (start end)
1003 "Extend START to END region to include an entire block of text.
1004 This helps improve syntax analysis for block constructs.
1005 Returns a cons (NEW-START . NEW-END) or nil if no adjustment should be made.
1006 Function is called repeatedly until it returns nil. For details, see
1007 `syntax-propertize-extend-region-functions'."
1008 (save-match-data
1009 (save-excursion
1010 (let* ((new-start (progn (goto-char start)
1011 (skip-chars-forward "\n")
1012 (if (re-search-backward "\n\n" nil t)
1013 (min start (match-end 0))
1014 (point-min))))
1015 (new-end (progn (goto-char end)
1016 (skip-chars-backward "\n")
1017 (if (re-search-forward "\n\n" nil t)
1018 (max end (match-beginning 0))
1019 (point-max))))
1020 (code-match (markdown--code-block-at-pos-no-syntax new-start))
1021 (new-start (or (and code-match (cl-first code-match)) new-start))
1022 (code-match (and (< end (point-max))
1023 (markdown--code-block-at-pos-no-syntax end)))
1024 (new-end (or (and code-match (cl-second code-match)) new-end)))
1025 (unless (and (eq new-start start) (eq new-end end))
1026 (cons new-start (min new-end (point-max))))))))
1028 (defun markdown-font-lock-extend-region-function (start end _)
1029 "Used in `jit-lock-after-change-extend-region-functions'.
1030 Delegates to `markdown-syntax-propertize-extend-region'. START
1031 and END are the previous region to refontify."
1032 (let ((res (markdown-syntax-propertize-extend-region start end)))
1033 (when res
1034 ;; syntax-propertize-function is not called when character at
1035 ;; (point-max) is deleted, but font-lock-extend-region-functions
1036 ;; are called. Force a syntax property update in that case.
1037 (when (= end (point-max))
1038 ;; This function is called in a buffer modification hook.
1039 ;; `markdown-syntax-propertize' doesn't save the match data,
1040 ;; so we have to do it here.
1041 (save-match-data
1042 (markdown-syntax-propertize (car res) (cdr res))))
1043 (setq jit-lock-start (car res)
1044 jit-lock-end (cdr res)))))
1046 (defun markdown--cur-list-item-bounds ()
1047 "Return a list describing the list item at point.
1048 Assumes that match data is set for `markdown-regex-list'. See the
1049 documentation for `markdown-cur-list-item-bounds' for the format of
1050 the returned list."
1051 (save-excursion
1052 (let* ((begin (match-beginning 0))
1053 (indent (length (match-string-no-properties 1)))
1054 (nonlist-indent (- (match-end 3) (match-beginning 0)))
1055 (marker (buffer-substring-no-properties
1056 (match-beginning 2) (match-end 3)))
1057 (checkbox (match-string-no-properties 4))
1058 (match (butlast (match-data t)))
1059 (end (markdown-cur-list-item-end nonlist-indent)))
1060 (list begin end indent nonlist-indent marker checkbox match))))
1062 (defun markdown--append-list-item-bounds (marker indent cur-bounds bounds)
1063 "Update list item BOUNDS given list MARKER, block INDENT, and CUR-BOUNDS.
1064 Here, MARKER is a string representing the type of list and INDENT
1065 is an integer giving the indentation, in spaces, of the current
1066 block. CUR-BOUNDS is a list of the form returned by
1067 `markdown-cur-list-item-bounds' and BOUNDS is a list of bounds
1068 values for parent list items. When BOUNDS is nil, it means we are
1069 at baseline (not inside of a nested list)."
1070 (let ((prev-indent (or (cl-third (car bounds)) 0)))
1071 (cond
1072 ;; New list item at baseline.
1073 ((and marker (null bounds))
1074 (list cur-bounds))
1075 ;; List item with greater indentation (four or more spaces).
1076 ;; Increase list level by consing CUR-BOUNDS onto BOUNDS.
1077 ((and marker (>= indent (+ prev-indent 4)))
1078 (cons cur-bounds bounds))
1079 ;; List item with greater or equal indentation (less than four spaces).
1080 ;; Keep list level the same by replacing the car of BOUNDS.
1081 ((and marker (>= indent prev-indent))
1082 (cons cur-bounds (cdr bounds)))
1083 ;; Lesser indentation level.
1084 ;; Pop appropriate number of elements off BOUNDS list (e.g., lesser
1085 ;; indentation could move back more than one list level). Note
1086 ;; that this block need not be the beginning of list item.
1087 ((< indent prev-indent)
1088 (while (and (> (length bounds) 1)
1089 (setq prev-indent (cl-third (cadr bounds)))
1090 (< indent (+ prev-indent 4)))
1091 (setq bounds (cdr bounds)))
1092 (cons cur-bounds bounds))
1093 ;; Otherwise, do nothing.
1094 (t bounds))))
1096 (defun markdown-syntax-propertize-list-items (start end)
1097 "Propertize list items from START to END.
1098 Stores nested list item information in the `markdown-list-item'
1099 text property to make later syntax analysis easier. The value of
1100 this property is a list with elements of the form (begin . end)
1101 giving the bounds of the current and parent list items."
1102 (save-excursion
1103 (goto-char start)
1104 (let (bounds level pre-regexp)
1105 ;; Find a baseline point with zero list indentation
1106 (markdown-search-backward-baseline)
1107 ;; Search for all list items between baseline and END
1108 (while (and (< (point) end)
1109 (re-search-forward markdown-regex-list end t))
1110 ;; Level of list nesting
1111 (setq level (length bounds))
1112 ;; Pre blocks need to be indented one level past the list level
1113 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ level)))
1114 (beginning-of-line)
1115 (cond
1116 ;; Reset at headings, horizontal rules, and top-level blank lines.
1117 ;; Propertize baseline when in range.
1118 ((markdown-new-baseline)
1119 (setq bounds nil))
1120 ;; Make sure this is not a line from a pre block
1121 ((looking-at-p pre-regexp))
1122 ;; If not, then update levels and propertize list item when in range.
1124 (let* ((indent (current-indentation))
1125 (cur-bounds (markdown--cur-list-item-bounds))
1126 (first (cl-first cur-bounds))
1127 (last (cl-second cur-bounds))
1128 (marker (cl-fifth cur-bounds)))
1129 (setq bounds (markdown--append-list-item-bounds
1130 marker indent cur-bounds bounds))
1131 (when (and (<= start (point)) (<= (point) end))
1132 (put-text-property first last 'markdown-list-item bounds)))))
1133 (end-of-line)))))
1135 (defun markdown-syntax-propertize-pre-blocks (start end)
1136 "Match preformatted text blocks from START to END."
1137 (save-excursion
1138 (goto-char start)
1139 (let ((levels (markdown-calculate-list-levels))
1140 indent pre-regexp close-regexp open close)
1141 (while (and (< (point) end) (not close))
1142 ;; Search for a region with sufficient indentation
1143 (if (null levels)
1144 (setq indent 1)
1145 (setq indent (1+ (length levels))))
1146 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1147 (setq close-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1149 (cond
1150 ;; If not at the beginning of a line, move forward
1151 ((not (bolp)) (forward-line))
1152 ;; Move past blank lines
1153 ((markdown-cur-line-blank-p) (forward-line))
1154 ;; At headers and horizontal rules, reset levels
1155 ((markdown-new-baseline) (forward-line) (setq levels nil))
1156 ;; If the current line has sufficient indentation, mark out pre block
1157 ;; The opening should be preceded by a blank line.
1158 ((and (markdown-prev-line-blank) (looking-at pre-regexp))
1159 (setq open (match-beginning 0))
1160 (while (and (or (looking-at-p pre-regexp) (markdown-cur-line-blank-p))
1161 (not (eobp)))
1162 (forward-line))
1163 (skip-syntax-backward "-")
1164 (setq close (point)))
1165 ;; If current line has a list marker, update levels, move to end of block
1166 ((looking-at markdown-regex-list)
1167 (setq levels (markdown-update-list-levels
1168 (match-string 2) (current-indentation) levels))
1169 (markdown-end-of-text-block))
1170 ;; If this is the end of the indentation level, adjust levels accordingly.
1171 ;; Only match end of indentation level if levels is not the empty list.
1172 ((and (car levels) (looking-at-p close-regexp))
1173 (setq levels (markdown-update-list-levels
1174 nil (current-indentation) levels))
1175 (markdown-end-of-text-block))
1176 (t (markdown-end-of-text-block))))
1178 (when (and open close)
1179 ;; Set text property data
1180 (put-text-property open close 'markdown-pre (list open close))
1181 ;; Recursively search again
1182 (markdown-syntax-propertize-pre-blocks (point) end)))))
1184 (defconst markdown-fenced-block-pairs
1185 `(((,markdown-regex-tilde-fence-begin markdown-tilde-fence-begin)
1186 (markdown-make-tilde-fence-regex markdown-tilde-fence-end)
1187 markdown-fenced-code)
1188 ((markdown-get-yaml-metadata-start-border markdown-yaml-metadata-begin)
1189 (markdown-get-yaml-metadata-end-border markdown-yaml-metadata-end)
1190 markdown-yaml-metadata-section)
1191 ((,markdown-regex-gfm-code-block-open markdown-gfm-block-begin)
1192 (,markdown-regex-gfm-code-block-close markdown-gfm-block-end)
1193 markdown-gfm-code))
1194 "Mapping of regular expressions to \"fenced-block\" constructs.
1195 These constructs are distinguished by having a distinctive start
1196 and end pattern, both of which take up an entire line of text,
1197 but no special pattern to identify text within the fenced
1198 blocks (unlike blockquotes and indented-code sections).
1200 Each element within this list takes the form:
1202 ((START-REGEX-OR-FUN START-PROPERTY)
1203 (END-REGEX-OR-FUN END-PROPERTY)
1204 MIDDLE-PROPERTY)
1206 Each *-REGEX-OR-FUN element can be a regular expression as a string, or a
1207 function which evaluates to same. Functions for START-REGEX-OR-FUN accept no
1208 arguments, but functions for END-REGEX-OR-FUN accept a single numerical argument
1209 which is the length of the first group of the START-REGEX-OR-FUN match, which
1210 can be ignored if unnecessary. `markdown-maybe-funcall-regexp' is used to
1211 evaluate these into \"real\" regexps.
1213 The *-PROPERTY elements are the text properties applied to each part of the
1214 block construct when it is matched using
1215 `markdown-syntax-propertize-fenced-block-constructs'. START-PROPERTY is applied
1216 to the text matching START-REGEX-OR-FUN, END-PROPERTY to END-REGEX-OR-FUN, and
1217 MIDDLE-PROPERTY to the text in between the two. The value of *-PROPERTY is the
1218 `match-data' when the regexp was matched to the text. In the case of
1219 MIDDLE-PROPERTY, the value is a false match data of the form '(begin end), with
1220 begin and end set to the edges of the \"middle\" text. This makes fontification
1221 easier.")
1223 (defun markdown-text-property-at-point (prop)
1224 (get-text-property (point) prop))
1226 (defsubst markdown-maybe-funcall-regexp (object &optional arg)
1227 (cond ((functionp object)
1228 (if arg (funcall object arg) (funcall object)))
1229 ((stringp object) object)
1230 (t (error "Object cannot be turned into regex"))))
1232 (defsubst markdown-get-start-fence-regexp ()
1233 "Return regexp to find all \"start\" sections of fenced block constructs.
1234 Which construct is actually contained in the match must be found separately."
1235 (mapconcat
1236 #'identity
1237 (mapcar (lambda (entry) (markdown-maybe-funcall-regexp (caar entry)))
1238 markdown-fenced-block-pairs)
1239 "\\|"))
1241 (defun markdown-get-fenced-block-begin-properties ()
1242 (cl-mapcar (lambda (entry) (cl-cadar entry)) markdown-fenced-block-pairs))
1244 (defun markdown-get-fenced-block-end-properties ()
1245 (cl-mapcar (lambda (entry) (cl-cadadr entry)) markdown-fenced-block-pairs))
1247 (defun markdown-get-fenced-block-middle-properties ()
1248 (cl-mapcar #'cl-third markdown-fenced-block-pairs))
1250 (defun markdown-find-previous-prop (prop &optional lim)
1251 "Find previous place where property PROP is non-nil, up to LIM.
1252 Return a cons of (pos . property). pos is point if point contains
1253 non-nil PROP."
1254 (let ((res
1255 (if (get-text-property (point) prop) (point)
1256 (previous-single-property-change
1257 (point) prop nil (or lim (point-min))))))
1258 (when (and (not (get-text-property res prop))
1259 (> res (point-min))
1260 (get-text-property (1- res) prop))
1261 (cl-decf res))
1262 (when (and res (get-text-property res prop)) (cons res prop))))
1264 (defun markdown-find-next-prop (prop &optional lim)
1265 "Find next place where property PROP is non-nil, up to LIM.
1266 Return a cons of (POS . PROPERTY) where POS is point if point
1267 contains non-nil PROP."
1268 (let ((res
1269 (if (get-text-property (point) prop) (point)
1270 (next-single-property-change
1271 (point) prop nil (or lim (point-max))))))
1272 (when (and res (get-text-property res prop)) (cons res prop))))
1274 (defun markdown-min-of-seq (map-fn seq)
1275 "Apply MAP-FN to SEQ and return element of SEQ with minimum value of MAP-FN."
1276 (cl-loop for el in seq
1277 with min = 1.0e+INF ; infinity
1278 with min-el = nil
1279 do (let ((res (funcall map-fn el)))
1280 (when (< res min)
1281 (setq min res)
1282 (setq min-el el)))
1283 finally return min-el))
1285 (defun markdown-max-of-seq (map-fn seq)
1286 "Apply MAP-FN to SEQ and return element of SEQ with maximum value of MAP-FN."
1287 (cl-loop for el in seq
1288 with max = -1.0e+INF ; negative infinity
1289 with max-el = nil
1290 do (let ((res (funcall map-fn el)))
1291 (when (and res (> res max))
1292 (setq max res)
1293 (setq max-el el)))
1294 finally return max-el))
1296 (defun markdown-find-previous-block ()
1297 "Find previous block.
1298 Detect whether `markdown-syntax-propertize-fenced-block-constructs' was
1299 unable to propertize the entire block, but was able to propertize the beginning
1300 of the block. If so, return a cons of (pos . property) where the beginning of
1301 the block was propertized."
1302 (let ((start-pt (point))
1303 (closest-open
1304 (markdown-max-of-seq
1305 #'car
1306 (cl-remove-if
1307 #'null
1308 (cl-mapcar
1309 #'markdown-find-previous-prop
1310 (markdown-get-fenced-block-begin-properties))))))
1311 (when closest-open
1312 (let* ((length-of-open-match
1313 (let ((match-d
1314 (get-text-property (car closest-open) (cdr closest-open))))
1315 (- (cl-fourth match-d) (cl-third match-d))))
1316 (end-regexp
1317 (markdown-maybe-funcall-regexp
1318 (cl-caadr
1319 (cl-find-if
1320 (lambda (entry) (eq (cl-cadar entry) (cdr closest-open)))
1321 markdown-fenced-block-pairs))
1322 length-of-open-match))
1323 (end-prop-loc
1324 (save-excursion
1325 (save-match-data
1326 (goto-char (car closest-open))
1327 (and (re-search-forward end-regexp start-pt t)
1328 (match-beginning 0))))))
1329 (and (not end-prop-loc) closest-open)))))
1331 (defun markdown-get-fenced-block-from-start (prop)
1332 "Return limits of an enclosing fenced block from its start, using PROP.
1333 Return value is a list usable as `match-data'."
1334 (catch 'no-rest-of-block
1335 (let* ((correct-entry
1336 (cl-find-if
1337 (lambda (entry) (eq (cl-cadar entry) prop))
1338 markdown-fenced-block-pairs))
1339 (begin-of-begin (cl-first (markdown-text-property-at-point prop)))
1340 (middle-prop (cl-third correct-entry))
1341 (end-prop (cl-cadadr correct-entry))
1342 (end-of-end
1343 (save-excursion
1344 (goto-char (match-end 0)) ; end of begin
1345 (unless (eobp) (forward-char))
1346 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
1347 (if (not mid-prop-v) ; no middle
1348 (progn
1349 ;; try to find end by advancing one
1350 (let ((end-prop-v
1351 (markdown-text-property-at-point end-prop)))
1352 (if end-prop-v (cl-second end-prop-v)
1353 (throw 'no-rest-of-block nil))))
1354 (set-match-data mid-prop-v)
1355 (goto-char (match-end 0)) ; end of middle
1356 (beginning-of-line) ; into end
1357 (cl-second (markdown-text-property-at-point end-prop)))))))
1358 (list begin-of-begin end-of-end))))
1360 (defun markdown-get-fenced-block-from-middle (prop)
1361 "Return limits of an enclosing fenced block from its middle, using PROP.
1362 Return value is a list usable as `match-data'."
1363 (let* ((correct-entry
1364 (cl-find-if
1365 (lambda (entry) (eq (cl-third entry) prop))
1366 markdown-fenced-block-pairs))
1367 (begin-prop (cl-cadar correct-entry))
1368 (begin-of-begin
1369 (save-excursion
1370 (goto-char (match-beginning 0))
1371 (unless (bobp) (forward-line -1))
1372 (beginning-of-line)
1373 (cl-first (markdown-text-property-at-point begin-prop))))
1374 (end-prop (cl-cadadr correct-entry))
1375 (end-of-end
1376 (save-excursion
1377 (goto-char (match-end 0))
1378 (beginning-of-line)
1379 (cl-second (markdown-text-property-at-point end-prop)))))
1380 (list begin-of-begin end-of-end)))
1382 (defun markdown-get-fenced-block-from-end (prop)
1383 "Return limits of an enclosing fenced block from its end, using PROP.
1384 Return value is a list usable as `match-data'."
1385 (let* ((correct-entry
1386 (cl-find-if
1387 (lambda (entry) (eq (cl-cadadr entry) prop))
1388 markdown-fenced-block-pairs))
1389 (end-of-end (cl-second (markdown-text-property-at-point prop)))
1390 (middle-prop (cl-third correct-entry))
1391 (begin-prop (cl-cadar correct-entry))
1392 (begin-of-begin
1393 (save-excursion
1394 (goto-char (match-beginning 0)) ; beginning of end
1395 (unless (bobp) (backward-char)) ; into middle
1396 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
1397 (if (not mid-prop-v)
1398 (progn
1399 (beginning-of-line)
1400 (cl-first (markdown-text-property-at-point begin-prop)))
1401 (set-match-data mid-prop-v)
1402 (goto-char (match-beginning 0)) ; beginning of middle
1403 (unless (bobp) (forward-line -1)) ; into beginning
1404 (beginning-of-line)
1405 (cl-first (markdown-text-property-at-point begin-prop)))))))
1406 (list begin-of-begin end-of-end)))
1408 (defun markdown-get-enclosing-fenced-block-construct (&optional pos)
1409 "Get \"fake\" match data for block enclosing POS.
1410 Returns fake match data which encloses the start, middle, and end
1411 of the block construct enclosing POS, if it exists. Used in
1412 `markdown-code-block-at-pos'."
1413 (save-excursion
1414 (when pos (goto-char pos))
1415 (beginning-of-line)
1416 (car
1417 (cl-remove-if
1418 #'null
1419 (cl-mapcar
1420 (lambda (fun-and-prop)
1421 (cl-destructuring-bind (fun prop) fun-and-prop
1422 (when prop
1423 (save-match-data
1424 (set-match-data (markdown-text-property-at-point prop))
1425 (funcall fun prop)))))
1426 `((markdown-get-fenced-block-from-start
1427 ,(cl-find-if
1428 #'markdown-text-property-at-point
1429 (markdown-get-fenced-block-begin-properties)))
1430 (markdown-get-fenced-block-from-middle
1431 ,(cl-find-if
1432 #'markdown-text-property-at-point
1433 (markdown-get-fenced-block-middle-properties)))
1434 (markdown-get-fenced-block-from-end
1435 ,(cl-find-if
1436 #'markdown-text-property-at-point
1437 (markdown-get-fenced-block-end-properties)))))))))
1439 (defun markdown-propertize-end-match (reg end fence-spec middle-begin)
1440 "Get match for REG up to END, if exists, and propertize appropriately.
1441 FENCE-SPEC is an entry in `markdown-fenced-block-pairs' and
1442 MIDDLE-BEGIN is the start of the \"middle\" section of the block."
1443 (when (re-search-forward reg end t)
1444 (let ((close-begin (match-beginning 0)) ; Start of closing line.
1445 (close-end (match-end 0)) ; End of closing line.
1446 (close-data (match-data t))) ; Match data for closing line.
1447 ;; Propertize middle section of fenced block.
1448 (put-text-property middle-begin close-begin
1449 (cl-third fence-spec)
1450 (list middle-begin close-begin))
1451 ;; If the block is a YAML block, propertize the declarations inside
1452 (markdown-syntax-propertize-yaml-metadata middle-begin close-begin)
1453 ;; Propertize closing line of fenced block.
1454 (put-text-property close-begin close-end
1455 (cl-cadadr fence-spec) close-data))))
1457 (defun markdown-syntax-propertize-fenced-block-constructs (start end)
1458 "Propertize according to `markdown-fenced-block-pairs' from START to END.
1459 If unable to propertize an entire block (if the start of a block is within START
1460 and END, but the end of the block is not), propertize the start section of a
1461 block, then in a subsequent call propertize both middle and end by finding the
1462 start which was previously propertized."
1463 (let ((start-reg (markdown-get-start-fence-regexp)))
1464 (save-excursion
1465 (goto-char start)
1466 ;; start from previous unclosed block, if exists
1467 (let ((prev-begin-block (markdown-find-previous-block)))
1468 (when prev-begin-block
1469 (let* ((correct-entry
1470 (cl-find-if (lambda (entry)
1471 (eq (cdr prev-begin-block) (cl-cadar entry)))
1472 markdown-fenced-block-pairs))
1473 (enclosed-text-start (1+ (car prev-begin-block)))
1474 (start-length
1475 (save-excursion
1476 (goto-char (car prev-begin-block))
1477 (string-match
1478 (markdown-maybe-funcall-regexp
1479 (caar correct-entry))
1480 (buffer-substring
1481 (point-at-bol) (point-at-eol)))
1482 (- (match-end 1) (match-beginning 1))))
1483 (end-reg (markdown-maybe-funcall-regexp
1484 (cl-caadr correct-entry) start-length)))
1485 (markdown-propertize-end-match
1486 end-reg end correct-entry enclosed-text-start))))
1487 ;; find all new blocks within region
1488 (while (re-search-forward start-reg end t)
1489 ;; we assume the opening constructs take up (only) an entire line,
1490 ;; so we re-check the current line
1491 (let* ((cur-line (buffer-substring (point-at-bol) (point-at-eol)))
1492 ;; find entry in `markdown-fenced-block-pairs' corresponding
1493 ;; to regex which was matched
1494 (correct-entry
1495 (cl-find-if
1496 (lambda (fenced-pair)
1497 (string-match-p
1498 (markdown-maybe-funcall-regexp (caar fenced-pair))
1499 cur-line))
1500 markdown-fenced-block-pairs))
1501 (enclosed-text-start
1502 (save-excursion (1+ (point-at-eol))))
1503 (end-reg
1504 (markdown-maybe-funcall-regexp
1505 (cl-caadr correct-entry)
1506 (if (and (match-beginning 1) (match-end 1))
1507 (- (match-end 1) (match-beginning 1))
1508 0))))
1509 ;; get correct match data
1510 (save-excursion
1511 (beginning-of-line)
1512 (re-search-forward
1513 (markdown-maybe-funcall-regexp (caar correct-entry))
1514 (point-at-eol)))
1515 ;; mark starting, even if ending is outside of region
1516 (put-text-property (match-beginning 0) (match-end 0)
1517 (cl-cadar correct-entry) (match-data t))
1518 (markdown-propertize-end-match
1519 end-reg end correct-entry enclosed-text-start))))))
1521 (defun markdown-syntax-propertize-blockquotes (start end)
1522 "Match blockquotes from START to END."
1523 (save-excursion
1524 (goto-char start)
1525 (while (and (re-search-forward markdown-regex-blockquote end t)
1526 (not (markdown-code-block-at-pos (match-beginning 0))))
1527 (put-text-property (match-beginning 0) (match-end 0)
1528 'markdown-blockquote
1529 (match-data t)))))
1531 (defun markdown-syntax-propertize-hrs (start end)
1532 "Match horizontal rules from START to END."
1533 (save-excursion
1534 (goto-char start)
1535 (while (re-search-forward markdown-regex-hr end t)
1536 (unless (or (markdown-on-heading-p)
1537 (markdown-code-block-at-point-p))
1538 (put-text-property (match-beginning 0) (match-end 0)
1539 'markdown-hr
1540 (match-data t))))))
1542 (defun markdown-syntax-propertize-yaml-metadata (start end)
1543 "Propertize elements inside YAML metadata blocks from START to END.
1544 Assumes region from START and END is already known to be the interior
1545 region of a YAML metadata block as propertized by
1546 `markdown-syntax-propertize-fenced-block-constructs'."
1547 (save-excursion
1548 (goto-char start)
1549 (cl-loop
1550 while (re-search-forward markdown-regex-declarative-metadata end t)
1551 do (progn
1552 (put-text-property (match-beginning 1) (match-end 1)
1553 'markdown-metadata-key (match-data t))
1554 (put-text-property (match-beginning 2) (match-end 2)
1555 'markdown-metadata-markup (match-data t))
1556 (put-text-property (match-beginning 3) (match-end 3)
1557 'markdown-metadata-value (match-data t))))))
1559 (defun markdown-syntax-propertize-headings (start end)
1560 "Match headings of type SYMBOL with REGEX from START to END."
1561 (goto-char start)
1562 (while (re-search-forward markdown-regex-header end t)
1563 (unless (markdown-code-block-at-pos (match-beginning 0))
1564 (put-text-property
1565 (match-beginning 0) (match-end 0) 'markdown-heading
1566 (match-data t))
1567 (put-text-property
1568 (match-beginning 0) (match-end 0)
1569 (cond ((match-string-no-properties 2) 'markdown-heading-1-setext)
1570 ((match-string-no-properties 3) 'markdown-heading-2-setext)
1571 (t (let ((atx-level (length (markdown-trim-whitespace
1572 (match-string-no-properties 4)))))
1573 (intern (format "markdown-heading-%d-atx" atx-level)))))
1574 (match-data t)))))
1576 (defun markdown-syntax-propertize-comments (start end)
1577 "Match HTML comments from the START to END."
1578 (let* ((in-comment (nth 4 (syntax-ppss))))
1579 (goto-char start)
1580 (cond
1581 ;; Comment start
1582 ((and (not in-comment)
1583 (re-search-forward markdown-regex-comment-start end t)
1584 (not (markdown-inline-code-at-point-p))
1585 (not (markdown-code-block-at-point-p)))
1586 (let ((open-beg (match-beginning 0)))
1587 (put-text-property open-beg (1+ open-beg)
1588 'syntax-table (string-to-syntax "<"))
1589 (markdown-syntax-propertize-comments
1590 (min (1+ (match-end 0)) end (point-max)) end)))
1591 ;; Comment end
1592 ((and in-comment
1593 (re-search-forward markdown-regex-comment-end end t))
1594 (let ((comment-end (match-end 0))
1595 (comment-begin (nth 8 (syntax-ppss))))
1596 (put-text-property (1- comment-end) comment-end
1597 'syntax-table (string-to-syntax ">"))
1598 ;; Remove any other text properties inside the comment
1599 (remove-text-properties comment-begin comment-end
1600 markdown--syntax-properties)
1601 (put-text-property comment-begin comment-end
1602 'markdown-comment (list comment-begin comment-end))
1603 (markdown-syntax-propertize-comments
1604 (min (1+ comment-end) end (point-max)) end)))
1605 ;; Nothing found
1606 (t nil))))
1608 (defun markdown-syntax-propertize (start end)
1609 "Function used as `syntax-propertize-function'.
1610 START and END delimit region to propertize."
1611 (with-silent-modifications
1612 (save-excursion
1613 (remove-text-properties start end markdown--syntax-properties)
1614 (markdown-syntax-propertize-fenced-block-constructs start end)
1615 (markdown-syntax-propertize-list-items start end)
1616 (markdown-syntax-propertize-pre-blocks start end)
1617 (markdown-syntax-propertize-blockquotes start end)
1618 (markdown-syntax-propertize-headings start end)
1619 (markdown-syntax-propertize-hrs start end)
1620 (markdown-syntax-propertize-comments start end))))
1623 ;;; Markup Hiding
1625 (defconst markdown-markup-properties
1626 '(face markdown-markup-face invisible markdown-markup)
1627 "List of properties and values to apply to markup.")
1629 (defconst markdown-language-keyword-properties
1630 '(face markdown-language-keyword-face invisible markdown-markup)
1631 "List of properties and values to apply to code block language names.")
1633 (defconst markdown-language-info-properties
1634 '(face markdown-language-info-face invisible markdown-markup)
1635 "List of properties and values to apply to code block language info strings.")
1637 (defconst markdown-include-title-properties
1638 '(face markdown-link-title-face invisible markdown-markup)
1639 "List of properties and values to apply to included code titles.")
1641 (defcustom markdown-hide-markup nil
1642 "Determines whether markup in the buffer will be hidden.
1643 When set to nil, all markup is displayed in the buffer as it
1644 appears in the file. An exception is when `markdown-hide-urls'
1645 is non-nil.
1646 Set this to a non-nil value to turn this feature on by default.
1647 You can interactively toggle the value of this variable with
1648 `markdown-toggle-markup-hiding', \\[markdown-toggle-markup-hiding],
1649 or from the Markdown > Show & Hide menu.
1651 Markup hiding works by adding text properties to positions in the
1652 buffer---either the `invisible' property or the `display' property
1653 in cases where alternative glyphs are used (e.g., list bullets).
1654 This does not, however, affect printing or other output.
1655 Functions such as `htmlfontify-buffer' and `ps-print-buffer' will
1656 not honor these text properties. For printing, it would be better
1657 to first convert to HTML or PDF (e.g,. using Pandoc)."
1658 :group 'markdown
1659 :type 'boolean
1660 :safe 'booleanp
1661 :package-version '(markdown-mode . "2.3"))
1662 (make-variable-buffer-local 'markdown-hide-markup)
1664 (defun markdown-toggle-markup-hiding (&optional arg)
1665 "Toggle the display or hiding of markup.
1666 With a prefix argument ARG, enable markup hiding if ARG is positive,
1667 and disable it otherwise.
1668 See `markdown-hide-markup' for additional details."
1669 (interactive (list (or current-prefix-arg 'toggle)))
1670 (setq markdown-hide-markup
1671 (if (eq arg 'toggle)
1672 (not markdown-hide-markup)
1673 (> (prefix-numeric-value arg) 0)))
1674 (if markdown-hide-markup
1675 (progn (add-to-invisibility-spec 'markdown-markup)
1676 (message "markdown-mode markup hiding enabled"))
1677 (progn (remove-from-invisibility-spec 'markdown-markup)
1678 (message "markdown-mode markup hiding disabled")))
1679 (markdown-reload-extensions))
1682 ;;; Font Lock =================================================================
1684 (require 'font-lock)
1686 (defvar markdown-italic-face 'markdown-italic-face
1687 "Face name to use for italic text.")
1689 (defvar markdown-bold-face 'markdown-bold-face
1690 "Face name to use for bold text.")
1692 (defvar markdown-strike-through-face 'markdown-strike-through-face
1693 "Face name to use for strike-through text.")
1695 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
1696 "Face name to use as a base for header delimiters.")
1698 (defvar markdown-header-rule-face 'markdown-header-rule-face
1699 "Face name to use as a base for header rules.")
1701 (defvar markdown-header-face 'markdown-header-face
1702 "Face name to use as a base for headers.")
1704 (defvar markdown-header-face-1 'markdown-header-face-1
1705 "Face name to use for level-1 headers.")
1707 (defvar markdown-header-face-2 'markdown-header-face-2
1708 "Face name to use for level-2 headers.")
1710 (defvar markdown-header-face-3 'markdown-header-face-3
1711 "Face name to use for level-3 headers.")
1713 (defvar markdown-header-face-4 'markdown-header-face-4
1714 "Face name to use for level-4 headers.")
1716 (defvar markdown-header-face-5 'markdown-header-face-5
1717 "Face name to use for level-5 headers.")
1719 (defvar markdown-header-face-6 'markdown-header-face-6
1720 "Face name to use for level-6 headers.")
1722 (defvar markdown-inline-code-face 'markdown-inline-code-face
1723 "Face name to use for inline code.")
1725 (defvar markdown-list-face 'markdown-list-face
1726 "Face name to use for list markers.")
1728 (defvar markdown-blockquote-face 'markdown-blockquote-face
1729 "Face name to use for blockquote.")
1731 (defvar markdown-pre-face 'markdown-pre-face
1732 "Face name to use for preformatted text.")
1734 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
1735 "Face name to use for programming language identifiers.")
1737 (defvar markdown-language-info-face 'markdown-language-info-face
1738 "Face name to use for programming info strings.")
1740 (defvar markdown-link-face 'markdown-link-face
1741 "Face name to use for links.")
1743 (defvar markdown-missing-link-face 'markdown-missing-link-face
1744 "Face name to use for links where the linked file does not exist.")
1746 (defvar markdown-reference-face 'markdown-reference-face
1747 "Face name to use for reference.")
1749 (defvar markdown-footnote-marker-face 'markdown-footnote-marker-face
1750 "Face name to use for footnote markers.")
1752 (defvar markdown-url-face 'markdown-url-face
1753 "Face name to use for URLs.")
1755 (defvar markdown-link-title-face 'markdown-link-title-face
1756 "Face name to use for reference link titles.")
1758 (defvar markdown-line-break-face 'markdown-line-break-face
1759 "Face name to use for hard line breaks.")
1761 (defvar markdown-comment-face 'markdown-comment-face
1762 "Face name to use for HTML comments.")
1764 (defvar markdown-math-face 'markdown-math-face
1765 "Face name to use for LaTeX expressions.")
1767 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
1768 "Face name to use for metadata keys.")
1770 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
1771 "Face name to use for metadata values.")
1773 (defvar markdown-gfm-checkbox-face 'markdown-gfm-checkbox-face
1774 "Face name to use for GFM checkboxes.")
1776 (defvar markdown-highlight-face 'markdown-highlight-face
1777 "Face name to use for mouse highlighting.")
1779 (defvar markdown-markup-face 'markdown-markup-face
1780 "Face name to use for markup elements.")
1782 (make-obsolete-variable 'markdown-italic-face "Use face name directly" "v2.4")
1783 (make-obsolete-variable 'markdown-bold-face "Use face name directly" "v2.4")
1784 (make-obsolete-variable 'markdown-strike-through-face "Use face name directly" "v2.4")
1785 (make-obsolete-variable 'markdown-header-delimiter-face "Use face name directly" "v2.4")
1786 (make-obsolete-variable 'markdown-header-rule-face "Use face name directly" "v2.4")
1787 (make-obsolete-variable 'markdown-header-face "Use face name directly" "v2.4")
1788 (make-obsolete-variable 'markdown-header-face-1 "Use face name directly" "v2.4")
1789 (make-obsolete-variable 'markdown-header-face-2 "Use face name directly" "v2.4")
1790 (make-obsolete-variable 'markdown-header-face-3 "Use face name directly" "v2.4")
1791 (make-obsolete-variable 'markdown-header-face-4 "Use face name directly" "v2.4")
1792 (make-obsolete-variable 'markdown-header-face-5 "Use face name directly" "v2.4")
1793 (make-obsolete-variable 'markdown-header-face-6 "Use face name directly" "v2.4")
1794 (make-obsolete-variable 'markdown-inline-code-face "Use face name directly" "v2.4")
1795 (make-obsolete-variable 'markdown-list-face "Use face name directly" "v2.4")
1796 (make-obsolete-variable 'markdown-blockquote-face "Use face name directly" "v2.4")
1797 (make-obsolete-variable 'markdown-pre-face "Use face name directly" "v2.4")
1798 (make-obsolete-variable 'markdown-language-keyword-face "Use face name directly" "v2.4")
1799 (make-obsolete-variable 'markdown-language-info-face "Use face name directly" "v2.4")
1800 (make-obsolete-variable 'markdown-link-face "Use face name directly" "v2.4")
1801 (make-obsolete-variable 'markdown-missing-link-face "Use face name directly" "v2.4")
1802 (make-obsolete-variable 'markdown-reference-face "Use face name directly" "v2.4")
1803 (make-obsolete-variable 'markdown-footnote-marker-face "Use face name directly" "v2.4")
1804 (make-obsolete-variable 'markdown-url-face "Use face name directly" "v2.4")
1805 (make-obsolete-variable 'markdown-link-title-face "Use face name directly" "v2.4")
1806 (make-obsolete-variable 'markdown-line-break-face "Use face name directly" "v2.4")
1807 (make-obsolete-variable 'markdown-comment-face "Use face name directly" "v2.4")
1808 (make-obsolete-variable 'markdown-math-face "Use face name directly" "v2.4")
1809 (make-obsolete-variable 'markdown-metadata-key-face "Use face name directly" "v2.4")
1810 (make-obsolete-variable 'markdown-metadata-value-face "Use face name directly" "v2.4")
1811 (make-obsolete-variable 'markdown-gfm-checkbox-face "Use face name directly" "v2.4")
1812 (make-obsolete-variable 'markdown-highlight-face "Use face name directly" "v2.4")
1813 (make-obsolete-variable 'markdown-markup-face "Use face name directly" "v2.4")
1815 (defgroup markdown-faces nil
1816 "Faces used in Markdown Mode"
1817 :group 'markdown
1818 :group 'faces)
1820 (defface markdown-italic-face
1821 '((t (:inherit italic)))
1822 "Face for italic text."
1823 :group 'markdown-faces)
1825 (defface markdown-bold-face
1826 '((t (:inherit bold)))
1827 "Face for bold text."
1828 :group 'markdown-faces)
1830 (defface markdown-strike-through-face
1831 '((t (:strike-through t)))
1832 "Face for strike-through text."
1833 :group 'markdown-faces)
1835 (defface markdown-markup-face
1836 '((t (:inherit shadow :slant normal :weight normal)))
1837 "Face for markup elements."
1838 :group 'markdown-faces)
1840 (defface markdown-header-rule-face
1841 '((t (:inherit markdown-markup-face)))
1842 "Base face for headers rules."
1843 :group 'markdown-faces)
1845 (defface markdown-header-delimiter-face
1846 '((t (:inherit markdown-markup-face)))
1847 "Base face for headers hash delimiter."
1848 :group 'markdown-faces)
1850 (defface markdown-list-face
1851 '((t (:inherit markdown-markup-face)))
1852 "Face for list item markers."
1853 :group 'markdown-faces)
1855 (defface markdown-blockquote-face
1856 '((t (:inherit font-lock-doc-face)))
1857 "Face for blockquote sections."
1858 :group 'markdown-faces)
1860 (defface markdown-code-face
1861 '((t (:inherit fixed-pitch)))
1862 "Face for inline code, pre blocks, and fenced code blocks.
1863 This may be used, for example, to add a contrasting background to
1864 inline code fragments and code blocks."
1865 :group 'markdown-faces)
1867 (defface markdown-inline-code-face
1868 '((t (:inherit (markdown-code-face font-lock-constant-face))))
1869 "Face for inline code."
1870 :group 'markdown-faces)
1872 (defface markdown-pre-face
1873 '((t (:inherit (markdown-code-face font-lock-constant-face))))
1874 "Face for preformatted text."
1875 :group 'markdown-faces)
1877 (defface markdown-table-face
1878 '((t (:inherit (markdown-code-face))))
1879 "Face for tables."
1880 :group 'markdown-faces)
1882 (defface markdown-language-keyword-face
1883 '((t (:inherit font-lock-type-face)))
1884 "Face for programming language identifiers."
1885 :group 'markdown-faces)
1887 (defface markdown-language-info-face
1888 '((t (:inherit font-lock-string-face)))
1889 "Face for programming language info strings."
1890 :group 'markdown-faces)
1892 (defface markdown-link-face
1893 '((t (:inherit link)))
1894 "Face for links."
1895 :group 'markdown-faces)
1897 (defface markdown-missing-link-face
1898 '((t (:inherit font-lock-warning-face)))
1899 "Face for missing links."
1900 :group 'markdown-faces)
1902 (defface markdown-reference-face
1903 '((t (:inherit markdown-markup-face)))
1904 "Face for link references."
1905 :group 'markdown-faces)
1907 (define-obsolete-face-alias 'markdown-footnote-face
1908 'markdown-footnote-marker-face "v2.3")
1910 (defface markdown-footnote-marker-face
1911 '((t (:inherit markdown-markup-face)))
1912 "Face for footnote markers."
1913 :group 'markdown-faces)
1915 (defface markdown-footnote-text-face
1916 '((t (:inherit font-lock-comment-face)))
1917 "Face for footnote text."
1918 :group 'markdown-faces)
1920 (defface markdown-url-face
1921 '((t (:inherit font-lock-string-face)))
1922 "Face for URLs that are part of markup.
1923 For example, this applies to URLs in inline links:
1924 [link text](http://example.com/)."
1925 :group 'markdown-faces)
1927 (defface markdown-plain-url-face
1928 '((t (:inherit markdown-link-face)))
1929 "Face for URLs that are also links.
1930 For example, this applies to plain angle bracket URLs:
1931 <http://example.com/>."
1932 :group 'markdown-faces)
1934 (defface markdown-link-title-face
1935 '((t (:inherit font-lock-comment-face)))
1936 "Face for reference link titles."
1937 :group 'markdown-faces)
1939 (defface markdown-line-break-face
1940 '((t (:inherit font-lock-constant-face :underline t)))
1941 "Face for hard line breaks."
1942 :group 'markdown-faces)
1944 (defface markdown-comment-face
1945 '((t (:inherit font-lock-comment-face)))
1946 "Face for HTML comments."
1947 :group 'markdown-faces)
1949 (defface markdown-math-face
1950 '((t (:inherit font-lock-string-face)))
1951 "Face for LaTeX expressions."
1952 :group 'markdown-faces)
1954 (defface markdown-metadata-key-face
1955 '((t (:inherit font-lock-variable-name-face)))
1956 "Face for metadata keys."
1957 :group 'markdown-faces)
1959 (defface markdown-metadata-value-face
1960 '((t (:inherit font-lock-string-face)))
1961 "Face for metadata values."
1962 :group 'markdown-faces)
1964 (defface markdown-gfm-checkbox-face
1965 '((t (:inherit font-lock-builtin-face)))
1966 "Face for GFM checkboxes."
1967 :group 'markdown-faces)
1969 (defface markdown-highlight-face
1970 '((t (:inherit highlight)))
1971 "Face for mouse highlighting."
1972 :group 'markdown-faces)
1974 (defface markdown-hr-face
1975 '((t (:inherit markdown-markup-face)))
1976 "Face for horizontal rules."
1977 :group 'markdown-faces)
1979 (defface markdown-html-tag-name-face
1980 '((t (:inherit font-lock-type-face)))
1981 "Face for HTML tag names."
1982 :group 'markdown-faces)
1984 (defface markdown-html-tag-delimiter-face
1985 '((t (:inherit markdown-markup-face)))
1986 "Face for HTML tag delimiters."
1987 :group 'markdown-faces)
1989 (defface markdown-html-attr-name-face
1990 '((t (:inherit font-lock-variable-name-face)))
1991 "Face for HTML attribute names."
1992 :group 'markdown-faces)
1994 (defface markdown-html-attr-value-face
1995 '((t (:inherit font-lock-string-face)))
1996 "Face for HTML attribute values."
1997 :group 'markdown-faces)
1999 (defface markdown-html-entity-face
2000 '((t (:inherit font-lock-variable-name-face)))
2001 "Face for HTML entities."
2002 :group 'markdown-faces)
2004 (defcustom markdown-header-scaling nil
2005 "Whether to use variable-height faces for headers.
2006 When non-nil, `markdown-header-face' will inherit from
2007 `variable-pitch' and the scaling values in
2008 `markdown-header-scaling-values' will be applied to
2009 headers of levels one through six respectively."
2010 :type 'boolean
2011 :initialize 'custom-initialize-default
2012 :set (lambda (symbol value)
2013 (set-default symbol value)
2014 (markdown-update-header-faces value))
2015 :group 'markdown-faces
2016 :package-version '(markdown-mode . "2.2"))
2018 (defcustom markdown-header-scaling-values
2019 '(2.0 1.7 1.4 1.1 1.0 1.0)
2020 "List of scaling values for headers of level one through six.
2021 Used when `markdown-header-scaling' is non-nil."
2022 :type 'list
2023 :initialize 'custom-initialize-default
2024 :set (lambda (symbol value)
2025 (set-default symbol value)
2026 (markdown-update-header-faces markdown-header-scaling value))
2027 :group 'markdown-faces)
2029 (defun markdown-make-header-faces ()
2030 "Build the faces used for Markdown headers."
2031 (let ((inherit-faces '(font-lock-function-name-face)))
2032 (when markdown-header-scaling
2033 (setq inherit-faces (cons 'variable-pitch inherit-faces)))
2034 (defface markdown-header-face
2035 `((t (:inherit ,inherit-faces :weight bold)))
2036 "Base face for headers."
2037 :group 'markdown-faces))
2038 (dotimes (num 6)
2039 (let* ((num1 (1+ num))
2040 (face-name (intern (format "markdown-header-face-%s" num1)))
2041 (scale (if markdown-header-scaling
2042 (float (nth num markdown-header-scaling-values))
2043 1.0)))
2044 (eval
2045 `(defface ,face-name
2046 '((t (:inherit markdown-header-face :height ,scale)))
2047 (format "Face for level %s headers.
2048 You probably don't want to customize this face directly. Instead
2049 you can customize the base face `markdown-header-face' or the
2050 variable-height variable `markdown-header-scaling'." ,num1)
2051 :group 'markdown-faces)))))
2053 (markdown-make-header-faces)
2055 (defun markdown-update-header-faces (&optional scaling scaling-values)
2056 "Update header faces, depending on if header SCALING is desired.
2057 If so, use given list of SCALING-VALUES relative to the baseline
2058 size of `markdown-header-face'."
2059 (dotimes (num 6)
2060 (let* ((face-name (intern (format "markdown-header-face-%s" (1+ num))))
2061 (scale (cond ((not scaling) 1.0)
2062 (scaling-values (float (nth num scaling-values)))
2063 (t (float (nth num markdown-header-scaling-values))))))
2064 (unless (get face-name 'saved-face) ; Don't update customized faces
2065 (set-face-attribute face-name nil :height scale)))))
2067 (defun markdown-syntactic-face (state)
2068 "Return font-lock face for characters with given STATE.
2069 See `font-lock-syntactic-face-function' for details."
2070 (let ((in-comment (nth 4 state)))
2071 (cond
2072 (in-comment 'markdown-comment-face)
2073 (t nil))))
2075 (defcustom markdown-list-item-bullets
2076 '("●" "◎" "○" "◆" "◇" "►" "•")
2077 "List of bullets to use for unordered lists.
2078 It can contain any number of symbols, which will be repeated.
2079 Depending on your font, some reasonable choices are:
2080 ♥ ● ◇ ✚ ✜ ☯ ◆ ♠ ♣ ♦ ❀ ◆ ◖ ▶ ► • ★ ▸."
2081 :group 'markdown
2082 :type '(repeat (string :tag "Bullet character"))
2083 :package-version '(markdown-mode . "2.3"))
2085 (defun markdown--footnote-marker-properties ()
2086 "Return a font-lock facespec expression for footnote marker text."
2087 `(face markdown-footnote-marker-face
2088 ,@(when markdown-hide-markup
2089 `(display ,markdown-footnote-display))))
2091 (defun markdown--pandoc-inline-footnote-properties ()
2092 "Return a font-lock facespec expression for Pandoc inline footnote text."
2093 `(face markdown-footnote-text-face
2094 ,@(when markdown-hide-markup
2095 `(display ,markdown-footnote-display))))
2097 (defvar markdown-mode-font-lock-keywords
2098 `((markdown-match-yaml-metadata-begin . ((1 'markdown-markup-face)))
2099 (markdown-match-yaml-metadata-end . ((1 'markdown-markup-face)))
2100 (markdown-match-yaml-metadata-key . ((1 'markdown-metadata-key-face)
2101 (2 'markdown-markup-face)
2102 (3 'markdown-metadata-value-face)))
2103 (markdown-match-gfm-open-code-blocks . ((1 markdown-markup-properties)
2104 (2 markdown-markup-properties nil t)
2105 (3 markdown-language-keyword-properties nil t)
2106 (4 markdown-language-info-properties nil t)
2107 (5 markdown-markup-properties nil t)))
2108 (markdown-match-gfm-close-code-blocks . ((0 markdown-markup-properties)))
2109 (markdown-fontify-gfm-code-blocks)
2110 (markdown-fontify-tables)
2111 (markdown-match-fenced-start-code-block . ((1 markdown-markup-properties)
2112 (2 markdown-markup-properties nil t)
2113 (3 markdown-language-keyword-properties nil t)
2114 (4 markdown-language-info-properties nil t)
2115 (5 markdown-markup-properties nil t)))
2116 (markdown-match-fenced-end-code-block . ((0 markdown-markup-properties)))
2117 (markdown-fontify-fenced-code-blocks)
2118 (markdown-match-pre-blocks . ((0 'markdown-pre-face)))
2119 (markdown-fontify-headings)
2120 (markdown-match-declarative-metadata . ((1 'markdown-metadata-key-face)
2121 (2 'markdown-markup-face)
2122 (3 'markdown-metadata-value-face)))
2123 (markdown-match-pandoc-metadata . ((1 'markdown-markup-face)
2124 (2 'markdown-markup-face)
2125 (3 'markdown-metadata-value-face)))
2126 (markdown-fontify-hrs)
2127 (markdown-match-code . ((1 markdown-markup-properties prepend)
2128 (2 'markdown-inline-code-face prepend)
2129 (3 markdown-markup-properties prepend)))
2130 (,markdown-regex-kbd . ((1 markdown-markup-properties)
2131 (2 'markdown-inline-code-face)
2132 (3 markdown-markup-properties)))
2133 (markdown-fontify-angle-uris)
2134 (,markdown-regex-email . 'markdown-plain-url-face)
2135 (markdown-match-html-tag . ((1 'markdown-html-tag-delimiter-face t)
2136 (2 'markdown-html-tag-name-face t)
2137 (3 'markdown-html-tag-delimiter-face t)
2138 ;; Anchored matcher for HTML tag attributes
2139 (,markdown-regex-html-attr
2140 ;; Before searching, move past tag
2141 ;; name; set limit at tag close.
2142 (progn
2143 (goto-char (match-end 2)) (match-end 3))
2145 . ((1 'markdown-html-attr-name-face)
2146 (3 'markdown-html-tag-delimiter-face nil t)
2147 (4 'markdown-html-attr-value-face nil t)))))
2148 (,markdown-regex-html-entity . 'markdown-html-entity-face)
2149 (markdown-fontify-list-items)
2150 (,markdown-regex-footnote . ((1 markdown-markup-properties) ; [^
2151 (2 (markdown--footnote-marker-properties)) ; label
2152 (3 markdown-markup-properties))) ; ]
2153 (,markdown-regex-pandoc-inline-footnote . ((1 markdown-markup-properties) ; ^
2154 (2 markdown-markup-properties) ; [
2155 (3 (markdown--pandoc-inline-footnote-properties)) ; text
2156 (4 markdown-markup-properties))) ; ]
2157 (markdown-match-includes . ((1 markdown-markup-properties)
2158 (2 markdown-markup-properties nil t)
2159 (3 markdown-include-title-properties nil t)
2160 (4 markdown-markup-properties nil t)
2161 (5 markdown-markup-properties)
2162 (6 'markdown-url-face)
2163 (7 markdown-markup-properties)))
2164 (markdown-fontify-inline-links)
2165 (markdown-fontify-reference-links)
2166 (,markdown-regex-reference-definition . ((1 'markdown-markup-face) ; [
2167 (2 'markdown-reference-face) ; label
2168 (3 'markdown-markup-face) ; ]
2169 (4 'markdown-markup-face) ; :
2170 (5 'markdown-url-face) ; url
2171 (6 'markdown-link-title-face))) ; "title" (optional)
2172 (markdown-fontify-plain-uris)
2173 ;; Math mode $..$
2174 (markdown-match-math-single . ((1 'markdown-markup-face prepend)
2175 (2 'markdown-math-face append)
2176 (3 'markdown-markup-face prepend)))
2177 ;; Math mode $$..$$
2178 (markdown-match-math-double . ((1 'markdown-markup-face prepend)
2179 (2 'markdown-math-face append)
2180 (3 'markdown-markup-face prepend)))
2181 ;; Math mode \[..\] and \\[..\\]
2182 (markdown-match-math-display . ((1 'markdown-markup-face prepend)
2183 (3 'markdown-math-face append)
2184 (4 'markdown-markup-face prepend)))
2185 (markdown-match-bold . ((1 markdown-markup-properties prepend)
2186 (2 'markdown-bold-face append)
2187 (3 markdown-markup-properties prepend)))
2188 (markdown-match-italic . ((1 markdown-markup-properties prepend)
2189 (2 'markdown-italic-face append)
2190 (3 markdown-markup-properties prepend)))
2191 (,markdown-regex-strike-through . ((3 markdown-markup-properties)
2192 (4 'markdown-strike-through-face)
2193 (5 markdown-markup-properties)))
2194 (,markdown-regex-line-break . (1 'markdown-line-break-face prepend))
2195 (markdown-fontify-sub-superscripts)
2196 (markdown-match-inline-attributes . ((0 markdown-markup-properties prepend)))
2197 (markdown-match-leanpub-sections . ((0 markdown-markup-properties)))
2198 (markdown-fontify-blockquotes)
2199 (markdown-match-wiki-link . ((0 'markdown-link-face prepend))))
2200 "Syntax highlighting for Markdown files.")
2202 (define-obsolete-variable-alias
2203 'markdown-mode-font-lock-keywords-basic
2204 'markdown-mode-font-lock-keywords "v2.4")
2206 ;; Footnotes
2207 (defvar markdown-footnote-counter 0
2208 "Counter for footnote numbers.")
2209 (make-variable-buffer-local 'markdown-footnote-counter)
2211 (defconst markdown-footnote-chars
2212 "[[:alnum:]-]"
2213 "Regular expression matching any character that is allowed in a footnote identifier.")
2215 (defconst markdown-regex-footnote-definition
2216 (concat "^ \\{0,3\\}\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:\\(?:[ \t]+\\|$\\)")
2217 "Regular expression matching a footnote definition, capturing the label.")
2220 ;;; Compatibility =============================================================
2222 (defun markdown-replace-regexp-in-string (regexp rep string)
2223 "Replace ocurrences of REGEXP with REP in STRING.
2224 This is a compatibility wrapper to provide `replace-regexp-in-string'
2225 in XEmacs 21."
2226 (if (featurep 'xemacs)
2227 (replace-in-string string regexp rep)
2228 (replace-regexp-in-string regexp rep string)))
2230 ;; `markdown-use-region-p' is a compatibility function which checks
2231 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
2232 (eval-and-compile
2233 (cond
2234 ;; Emacs 24 and newer
2235 ((fboundp 'use-region-p)
2236 (defalias 'markdown-use-region-p 'use-region-p))
2237 ;; XEmacs
2238 ((fboundp 'region-active-p)
2239 (defalias 'markdown-use-region-p 'region-active-p))))
2241 ;; Use new names for outline-mode functions in Emacs 25 and later.
2242 (eval-and-compile
2243 (defalias 'markdown-hide-sublevels
2244 (if (fboundp 'outline-hide-sublevels)
2245 'outline-hide-sublevels
2246 'hide-sublevels))
2247 (defalias 'markdown-show-all
2248 (if (fboundp 'outline-show-all)
2249 'outline-show-all
2250 'show-all))
2251 (defalias 'markdown-hide-body
2252 (if (fboundp 'outline-hide-body)
2253 'outline-hide-body
2254 'hide-body))
2255 (defalias 'markdown-show-children
2256 (if (fboundp 'outline-show-children)
2257 'outline-show-children
2258 'show-children))
2259 (defalias 'markdown-show-subtree
2260 (if (fboundp 'outline-show-subtree)
2261 'outline-show-subtree
2262 'show-subtree))
2263 (defalias 'markdown-hide-subtree
2264 (if (fboundp 'outline-hide-subtree)
2265 'outline-hide-subtree
2266 'hide-subtree)))
2268 ;; Provide directory-name-p to Emacs 24
2269 (defsubst markdown-directory-name-p (name)
2270 "Return non-nil if NAME ends with a directory separator character.
2271 Taken from `directory-name-p' from Emacs 25 and provided here for
2272 backwards compatibility."
2273 (let ((len (length name))
2274 (lastc ?.))
2275 (if (> len 0)
2276 (setq lastc (aref name (1- len))))
2277 (or (= lastc ?/)
2278 (and (memq system-type '(windows-nt ms-dos))
2279 (= lastc ?\\)))))
2281 ;; Provide a function to find files recursively in Emacs 24.
2282 (defalias 'markdown-directory-files-recursively
2283 (if (fboundp 'directory-files-recursively)
2284 'directory-files-recursively
2285 (lambda (dir regexp)
2286 "Return list of all files under DIR that have file names matching REGEXP.
2287 This function works recursively. Files are returned in \"depth first\"
2288 order, and files from each directory are sorted in alphabetical order.
2289 Each file name appears in the returned list in its absolute form.
2290 Based on `directory-files-recursively' from Emacs 25 and provided
2291 here for backwards compatibility."
2292 (let ((result nil)
2293 (files nil)
2294 ;; When DIR is "/", remote file names like "/method:" could
2295 ;; also be offered. We shall suppress them.
2296 (tramp-mode (and tramp-mode (file-remote-p (expand-file-name dir)))))
2297 (dolist (file (sort (file-name-all-completions "" dir)
2298 'string<))
2299 (unless (member file '("./" "../"))
2300 (if (markdown-directory-name-p file)
2301 (let* ((leaf (substring file 0 (1- (length file))))
2302 (full-file (expand-file-name leaf dir)))
2303 (setq result
2304 (nconc result (markdown-directory-files-recursively
2305 full-file regexp))))
2306 (when (string-match-p regexp file)
2307 (push (expand-file-name file dir) files)))))
2308 (nconc result (nreverse files))))))
2310 (defun markdown-flyspell-check-word-p ()
2311 "Return t if `flyspell' should check word just before point.
2312 Used for `flyspell-generic-check-word-predicate'."
2313 (save-excursion
2314 (goto-char (1- (point)))
2315 (not (or (markdown-code-block-at-point-p)
2316 (markdown-inline-code-at-point-p)
2317 (markdown-in-comment-p)
2318 (let ((faces (get-text-property (point) 'face)))
2319 (if (listp faces)
2320 (or (memq 'markdown-reference-face faces)
2321 (memq 'markdown-markup-face faces)
2322 (memq 'markdown-plain-url-face faces)
2323 (memq 'markdown-inline-code-face faces)
2324 (memq 'markdown-url-face faces))
2325 (memq faces '(markdown-reference-face
2326 markdown-markup-face
2327 markdown-plain-url-face
2328 markdown-inline-code-face
2329 markdown-url-face))))))))
2331 (defun markdown-font-lock-ensure ()
2332 "Provide `font-lock-ensure' in Emacs 24."
2333 (if (fboundp 'font-lock-ensure)
2334 (font-lock-ensure)
2335 (with-no-warnings
2336 ;; Suppress warning about non-interactive use of
2337 ;; `font-lock-fontify-buffer' in Emacs 25.
2338 (font-lock-fontify-buffer))))
2341 ;;; Markdown Parsing Functions ================================================
2343 (define-obsolete-function-alias
2344 'markdown-cur-line-blank 'markdown-cur-line-blank-p "v2.4")
2345 (define-obsolete-function-alias
2346 'markdown-next-line-blank 'markdown-next-line-blank-p "v2.4")
2348 (defun markdown-cur-line-blank-p ()
2349 "Return t if the current line is blank and nil otherwise."
2350 (save-excursion
2351 (beginning-of-line)
2352 (looking-at-p markdown-regex-blank-line)))
2354 (defun markdown-prev-line-blank ()
2355 "Return t if the previous line is blank and nil otherwise.
2356 If we are at the first line, then consider the previous line to be blank."
2357 (or (= (line-beginning-position) (point-min))
2358 (save-excursion
2359 (forward-line -1)
2360 (looking-at markdown-regex-blank-line))))
2362 (defun markdown-prev-line-blank-p ()
2363 "Like `markdown-prev-line-blank', but preserve `match-data'."
2364 (save-match-data (markdown-prev-line-blank)))
2366 (defun markdown-next-line-blank-p ()
2367 "Return t if the next line is blank and nil otherwise.
2368 If we are at the last line, then consider the next line to be blank."
2369 (or (= (line-end-position) (point-max))
2370 (save-excursion
2371 (forward-line 1)
2372 (markdown-cur-line-blank-p))))
2374 (defun markdown-prev-line-indent ()
2375 "Return the number of leading whitespace characters in the previous line.
2376 Return 0 if the current line is the first line in the buffer."
2377 (save-excursion
2378 (if (= (line-beginning-position) (point-min))
2380 (forward-line -1)
2381 (current-indentation))))
2383 (defun markdown-next-line-indent ()
2384 "Return the number of leading whitespace characters in the next line.
2385 Return 0 if line is the last line in the buffer."
2386 (save-excursion
2387 (if (= (line-end-position) (point-max))
2389 (forward-line 1)
2390 (current-indentation))))
2392 (defun markdown-new-baseline ()
2393 "Determine if the current line begins a new baseline level.
2394 Assume point is positioned at beginning of line."
2395 (or (looking-at markdown-regex-header)
2396 (looking-at markdown-regex-hr)
2397 (and (= (current-indentation) 0)
2398 (not (looking-at markdown-regex-list))
2399 (markdown-prev-line-blank))))
2401 (defun markdown-search-backward-baseline ()
2402 "Search backward baseline point with no indentation and not a list item."
2403 (end-of-line)
2404 (let (stop)
2405 (while (not (or stop (bobp)))
2406 (re-search-backward markdown-regex-block-separator-noindent nil t)
2407 (when (match-end 2)
2408 (goto-char (match-end 2))
2409 (cond
2410 ((markdown-new-baseline)
2411 (setq stop t))
2412 ((looking-at-p markdown-regex-list)
2413 (setq stop nil))
2414 (t (setq stop t)))))))
2416 (defun markdown-update-list-levels (marker indent levels)
2417 "Update list levels given list MARKER, block INDENT, and current LEVELS.
2418 Here, MARKER is a string representing the type of list, INDENT is an integer
2419 giving the indentation, in spaces, of the current block, and LEVELS is a
2420 list of the indentation levels of parent list items. When LEVELS is nil,
2421 it means we are at baseline (not inside of a nested list)."
2422 (cond
2423 ;; New list item at baseline.
2424 ((and marker (null levels))
2425 (setq levels (list indent)))
2426 ;; List item with greater indentation (four or more spaces).
2427 ;; Increase list level.
2428 ((and marker (>= indent (+ (car levels) 4)))
2429 (setq levels (cons indent levels)))
2430 ;; List item with greater or equal indentation (less than four spaces).
2431 ;; Do not increase list level.
2432 ((and marker (>= indent (car levels)))
2433 levels)
2434 ;; Lesser indentation level.
2435 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
2436 ;; indentation could move back more than one list level). Note
2437 ;; that this block need not be the beginning of list item.
2438 ((< indent (car levels))
2439 (while (and (> (length levels) 1)
2440 (< indent (+ (cadr levels) 4)))
2441 (setq levels (cdr levels)))
2442 levels)
2443 ;; Otherwise, do nothing.
2444 (t levels)))
2446 (defun markdown-calculate-list-levels ()
2447 "Calculate list levels at point.
2448 Return a list of the form (n1 n2 n3 ...) where n1 is the
2449 indentation of the deepest nested list item in the branch of
2450 the list at the point, n2 is the indentation of the parent
2451 list item, and so on. The depth of the list item is therefore
2452 the length of the returned list. If the point is not at or
2453 immediately after a list item, return nil."
2454 (save-excursion
2455 (let ((first (point)) levels indent pre-regexp)
2456 ;; Find a baseline point with zero list indentation
2457 (markdown-search-backward-baseline)
2458 ;; Search for all list items between baseline and LOC
2459 (while (and (< (point) first)
2460 (re-search-forward markdown-regex-list first t))
2461 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
2462 (beginning-of-line)
2463 (cond
2464 ;; Make sure this is not a header or hr
2465 ((markdown-new-baseline) (setq levels nil))
2466 ;; Make sure this is not a line from a pre block
2467 ((looking-at-p pre-regexp))
2468 ;; If not, then update levels
2470 (setq indent (current-indentation))
2471 (setq levels (markdown-update-list-levels (match-string 2)
2472 indent levels))))
2473 (end-of-line))
2474 levels)))
2476 (defun markdown-prev-list-item (level)
2477 "Search backward from point for a list item with indentation LEVEL.
2478 Set point to the beginning of the item, and return point, or nil
2479 upon failure."
2480 (let (bounds indent prev)
2481 (setq prev (point))
2482 (forward-line -1)
2483 (setq indent (current-indentation))
2484 (while
2485 (cond
2486 ;; List item
2487 ((and (looking-at-p markdown-regex-list)
2488 (setq bounds (markdown-cur-list-item-bounds)))
2489 (cond
2490 ;; Stop and return point at item of equal indentation
2491 ((= (nth 3 bounds) level)
2492 (setq prev (point))
2493 nil)
2494 ;; Stop and return nil at item with lesser indentation
2495 ((< (nth 3 bounds) level)
2496 (setq prev nil)
2497 nil)
2498 ;; Stop at beginning of buffer
2499 ((bobp) (setq prev nil))
2500 ;; Continue at item with greater indentation
2501 ((> (nth 3 bounds) level) t)))
2502 ;; Stop at beginning of buffer
2503 ((bobp) (setq prev nil))
2504 ;; Continue if current line is blank
2505 ((markdown-cur-line-blank-p) t)
2506 ;; Continue while indentation is the same or greater
2507 ((>= indent level) t)
2508 ;; Stop if current indentation is less than list item
2509 ;; and the next is blank
2510 ((and (< indent level)
2511 (markdown-next-line-blank-p))
2512 (setq prev nil))
2513 ;; Stop at a header
2514 ((looking-at-p markdown-regex-header) (setq prev nil))
2515 ;; Stop at a horizontal rule
2516 ((looking-at-p markdown-regex-hr) (setq prev nil))
2517 ;; Otherwise, continue.
2518 (t t))
2519 (forward-line -1)
2520 (setq indent (current-indentation)))
2521 prev))
2523 (defun markdown-next-list-item (level)
2524 "Search forward from point for the next list item with indentation LEVEL.
2525 Set point to the beginning of the item, and return point, or nil
2526 upon failure."
2527 (let (bounds indent next)
2528 (setq next (point))
2529 (if (looking-at markdown-regex-header-setext)
2530 (goto-char (match-end 0)))
2531 (forward-line)
2532 (setq indent (current-indentation))
2533 (while
2534 (cond
2535 ;; Stop at end of the buffer.
2536 ((eobp) nil)
2537 ;; Continue if the current line is blank
2538 ((markdown-cur-line-blank-p) t)
2539 ;; List item
2540 ((and (looking-at-p markdown-regex-list)
2541 (setq bounds (markdown-cur-list-item-bounds)))
2542 (cond
2543 ;; Continue at item with greater indentation
2544 ((> (nth 3 bounds) level) t)
2545 ;; Stop and return point at item of equal indentation
2546 ((= (nth 3 bounds) level)
2547 (setq next (point))
2548 nil)
2549 ;; Stop and return nil at item with lesser indentation
2550 ((< (nth 3 bounds) level)
2551 (setq next nil)
2552 nil)))
2553 ;; Continue while indentation is the same or greater
2554 ((>= indent level) t)
2555 ;; Stop if current indentation is less than list item
2556 ;; and the previous line was blank.
2557 ((and (< indent level)
2558 (markdown-prev-line-blank-p))
2559 (setq next nil))
2560 ;; Stop at a header
2561 ((looking-at-p markdown-regex-header) (setq next nil))
2562 ;; Stop at a horizontal rule
2563 ((looking-at-p markdown-regex-hr) (setq next nil))
2564 ;; Otherwise, continue.
2565 (t t))
2566 (forward-line)
2567 (setq indent (current-indentation)))
2568 next))
2570 (defun markdown-cur-list-item-end (level)
2571 "Move to end of list item with pre-marker indentation LEVEL.
2572 Return the point at the end when a list item was found at the
2573 original point. If the point is not in a list item, do nothing."
2574 (let (indent)
2575 (forward-line)
2576 (setq indent (current-indentation))
2577 (while
2578 (cond
2579 ;; Stop at end of the buffer.
2580 ((eobp) nil)
2581 ;; Continue while indentation is the same or greater
2582 ((>= indent level) t)
2583 ;; Continue if the current line is blank
2584 ((looking-at markdown-regex-blank-line) t)
2585 ;; Stop if current indentation is less than list item
2586 ;; and the previous line was blank.
2587 ((and (< indent level)
2588 (markdown-prev-line-blank))
2589 nil)
2590 ;; Stop at a new list items of the same or lesser
2591 ;; indentation, headings, and horizontal rules.
2592 ((looking-at (concat "\\(?:" markdown-regex-list
2593 "\\|" markdown-regex-header
2594 "\\|" markdown-regex-hr "\\)"))
2595 nil)
2596 ;; Otherwise, continue.
2597 (t t))
2598 (forward-line)
2599 (setq indent (current-indentation)))
2600 ;; Don't skip over whitespace for empty list items (marker and
2601 ;; whitespace only), just move to end of whitespace.
2602 (if (save-excursion
2603 (beginning-of-line)
2604 (looking-at (concat markdown-regex-list "[ \t]*$")))
2605 (goto-char (match-end 3))
2606 (skip-chars-backward " \t\n"))
2607 (end-of-line)
2608 (point)))
2610 (defun markdown-cur-list-item-bounds ()
2611 "Return bounds for list item at point.
2612 Return a list of the following form:
2614 (begin end indent nonlist-indent marker checkbox match)
2616 The named components are:
2618 - begin: Position of beginning of list item, including leading indentation.
2619 - end: Position of the end of the list item, including list item text.
2620 - indent: Number of characters of indentation before list marker (an integer).
2621 - nonlist-indent: Number characters of indentation, list
2622 marker, and whitespace following list marker (an integer).
2623 - marker: String containing the list marker and following whitespace
2624 (e.g., \"- \" or \"* \").
2625 - checkbox: String containing the GFM checkbox portion, if any,
2626 including any trailing whitespace before the text
2627 begins (e.g., \"[x] \").
2628 - match: match data for markdown-regex-list
2630 As an example, for the following unordered list item
2632 - item
2634 the returned list would be
2636 (1 14 3 5 \"- \" nil (1 6 1 4 4 5 5 6))
2638 If the point is not inside a list item, return nil."
2639 (car (get-text-property (point-at-bol) 'markdown-list-item)))
2641 (defun markdown-list-item-at-point-p ()
2642 "Return t if there is a list item at the point and nil otherwise."
2643 (save-match-data (markdown-cur-list-item-bounds)))
2645 (defun markdown-prev-list-item-bounds ()
2646 "Return bounds of previous item in the same list of any level.
2647 The return value has the same form as that of
2648 `markdown-cur-list-item-bounds'."
2649 (save-excursion
2650 (let ((cur-bounds (markdown-cur-list-item-bounds))
2651 (beginning-of-list (save-excursion (markdown-beginning-of-list)))
2652 stop)
2653 (when cur-bounds
2654 (goto-char (nth 0 cur-bounds))
2655 (while (and (not stop) (not (bobp))
2656 (re-search-backward markdown-regex-list
2657 beginning-of-list t))
2658 (unless (or (looking-at markdown-regex-hr)
2659 (markdown-code-block-at-point-p))
2660 (setq stop (point))))
2661 (markdown-cur-list-item-bounds)))))
2663 (defun markdown-next-list-item-bounds ()
2664 "Return bounds of next item in the same list of any level.
2665 The return value has the same form as that of
2666 `markdown-cur-list-item-bounds'."
2667 (save-excursion
2668 (let ((cur-bounds (markdown-cur-list-item-bounds))
2669 (end-of-list (save-excursion (markdown-end-of-list)))
2670 stop)
2671 (when cur-bounds
2672 (goto-char (nth 0 cur-bounds))
2673 (end-of-line)
2674 (while (and (not stop) (not (eobp))
2675 (re-search-forward markdown-regex-list
2676 end-of-list t))
2677 (unless (or (looking-at markdown-regex-hr)
2678 (markdown-code-block-at-point-p))
2679 (setq stop (point))))
2680 (when stop
2681 (markdown-cur-list-item-bounds))))))
2683 (defun markdown-beginning-of-list ()
2684 "Move point to beginning of list at point, if any."
2685 (interactive)
2686 (let ((orig-point (point))
2687 (list-begin (save-excursion
2688 (markdown-search-backward-baseline)
2689 ;; Stop at next list item, regardless of the indentation.
2690 (markdown-next-list-item (point-max))
2691 (when (looking-at markdown-regex-list)
2692 (point)))))
2693 (when (and list-begin (<= list-begin orig-point))
2694 (goto-char list-begin))))
2696 (defun markdown-end-of-list ()
2697 "Move point to end of list at point, if any."
2698 (interactive)
2699 (let ((start (point))
2700 (end (save-excursion
2701 (when (markdown-beginning-of-list)
2702 ;; Items can't have nonlist-indent <= 1, so this
2703 ;; moves past all list items.
2704 (markdown-next-list-item 1)
2705 (skip-syntax-backward "-")
2706 (unless (eobp) (forward-char 1))
2707 (point)))))
2708 (when (and end (>= end start))
2709 (goto-char end))))
2711 (defun markdown-up-list ()
2712 "Move point to beginning of parent list item."
2713 (interactive)
2714 (let ((cur-bounds (markdown-cur-list-item-bounds)))
2715 (when cur-bounds
2716 (markdown-prev-list-item (1- (nth 3 cur-bounds)))
2717 (let ((up-bounds (markdown-cur-list-item-bounds)))
2718 (when (and up-bounds (< (nth 3 up-bounds) (nth 3 cur-bounds)))
2719 (point))))))
2721 (defun markdown-bounds-of-thing-at-point (thing)
2722 "Call `bounds-of-thing-at-point' for THING with slight modifications.
2723 Does not include trailing newlines when THING is 'line. Handles the
2724 end of buffer case by setting both endpoints equal to the value of
2725 `point-max', since an empty region will trigger empty markup insertion.
2726 Return bounds of form (beg . end) if THING is found, or nil otherwise."
2727 (let* ((bounds (bounds-of-thing-at-point thing))
2728 (a (car bounds))
2729 (b (cdr bounds)))
2730 (when bounds
2731 (when (eq thing 'line)
2732 (cond ((and (eobp) (markdown-cur-line-blank-p))
2733 (setq a b))
2734 ((char-equal (char-before b) ?\^J)
2735 (setq b (1- b)))))
2736 (cons a b))))
2738 (defun markdown-reference-definition (reference)
2739 "Find out whether Markdown REFERENCE is defined.
2740 REFERENCE should not include the square brackets.
2741 When REFERENCE is defined, return a list of the form (text start end)
2742 containing the definition text itself followed by the start and end
2743 locations of the text. Otherwise, return nil.
2744 Leave match data for `markdown-regex-reference-definition'
2745 intact additional processing."
2746 (let ((reference (downcase reference)))
2747 (save-excursion
2748 (goto-char (point-min))
2749 (catch 'found
2750 (while (re-search-forward markdown-regex-reference-definition nil t)
2751 (when (string= reference (downcase (match-string-no-properties 2)))
2752 (throw 'found
2753 (list (match-string-no-properties 5)
2754 (match-beginning 5) (match-end 5)))))))))
2756 (defun markdown-get-defined-references ()
2757 "Return a list of all defined reference labels (not including square brackets)."
2758 (save-excursion
2759 (goto-char (point-min))
2760 (let (refs)
2761 (while (re-search-forward markdown-regex-reference-definition nil t)
2762 (let ((target (match-string-no-properties 2)))
2763 (cl-pushnew target refs :test #'equal)))
2764 (reverse refs))))
2766 (defun markdown-get-used-uris ()
2767 "Return a list of all used URIs in the buffer."
2768 (save-excursion
2769 (goto-char (point-min))
2770 (let (uris)
2771 (while (re-search-forward
2772 (concat "\\(?:" markdown-regex-link-inline
2773 "\\|" markdown-regex-angle-uri
2774 "\\|" markdown-regex-uri
2775 "\\|" markdown-regex-email
2776 "\\)")
2777 nil t)
2778 (unless (or (markdown-inline-code-at-point-p)
2779 (markdown-code-block-at-point-p))
2780 (cl-pushnew (or (match-string-no-properties 6)
2781 (match-string-no-properties 10)
2782 (match-string-no-properties 12)
2783 (match-string-no-properties 13))
2784 uris :test #'equal)))
2785 (reverse uris))))
2787 (defun markdown-inline-code-at-pos (pos)
2788 "Return non-nil if there is an inline code fragment at POS.
2789 Return nil otherwise. Set match data according to
2790 `markdown-match-code' upon success.
2791 This function searches the block for a code fragment that
2792 contains the point using `markdown-match-code'. We do this
2793 because `thing-at-point-looking-at' does not work reliably with
2794 `markdown-regex-code'.
2796 The match data is set as follows:
2797 Group 1 matches the opening backquotes.
2798 Group 2 matches the code fragment itself, without backquotes.
2799 Group 3 matches the closing backquotes."
2800 (save-excursion
2801 (goto-char pos)
2802 (let ((old-point (point))
2803 (end-of-block (progn (markdown-end-of-text-block) (point)))
2804 found)
2805 (markdown-beginning-of-text-block)
2806 (while (and (markdown-match-code end-of-block)
2807 (setq found t)
2808 (< (match-end 0) old-point)))
2809 (and found ; matched something
2810 (<= (match-beginning 0) old-point) ; match contains old-point
2811 (>= (match-end 0) old-point)))))
2813 (defun markdown-inline-code-at-pos-p (pos)
2814 "Return non-nil if there is an inline code fragment at POS.
2815 Like `markdown-inline-code-at-pos`, but preserves match data."
2816 (save-match-data (markdown-inline-code-at-pos pos)))
2818 (defun markdown-inline-code-at-point ()
2819 "Return non-nil if the point is at an inline code fragment.
2820 See `markdown-inline-code-at-pos' for details."
2821 (markdown-inline-code-at-pos (point)))
2823 (defun markdown-inline-code-at-point-p ()
2824 "Return non-nil if there is inline code at the point.
2825 This is a predicate function counterpart to
2826 `markdown-inline-code-at-point' which does not modify the match
2827 data. See `markdown-code-block-at-point-p' for code blocks."
2828 (save-match-data (markdown-inline-code-at-pos (point))))
2830 (make-obsolete 'markdown-code-at-point-p 'markdown-inline-code-at-point-p "v2.2")
2832 (defun markdown--code-block-at-pos-no-syntax (pos)
2833 "Return match data list if there may be a code block at POS.
2834 This includes pre blocks, tilde-fenced code blocks, and GFM
2835 quoted code blocks. Return nil otherwise. This function does not
2836 use text properties, which have not yet been set during the
2837 syntax propertization phase."
2838 (setq pos (save-excursion (goto-char pos) (point-at-bol)))
2839 (let (match)
2840 (cond
2841 ;; Indented code blocks
2842 ((looking-at markdown-regex-pre)
2843 (let ((start (save-excursion
2844 (markdown-search-backward-baseline) (point)))
2845 (end (save-excursion
2846 (while (and (or (looking-at-p markdown-regex-pre)
2847 (markdown-cur-line-blank-p))
2848 (not (eobp)))
2849 (forward-line))
2850 (point))))
2851 (list start end start start start end end end)))
2852 ;; Fenced code blocks
2853 ((setq match (markdown-get-enclosing-fenced-block-construct pos))
2854 match))))
2856 (defun markdown-code-block-at-pos (pos)
2857 "Return match data list if there is a code block at POS.
2858 This includes pre blocks, tilde-fenced code blocks, and GFM
2859 quoted code blocks. Return nil otherwise. This function uses
2860 cached text properties at the beginning of the line position for
2861 performance reasons, but therefore it must run after the syntax
2862 propertization phase."
2863 (setq pos (save-excursion (goto-char pos) (point-at-bol)))
2864 (or (get-text-property pos 'markdown-pre)
2865 ;;(markdown-get-enclosing-fenced-block-construct pos)
2866 (when (markdown-range-properties-exist
2867 pos pos '(markdown-gfm-block-begin
2868 markdown-gfm-code
2869 markdown-gfm-block-end
2870 markdown-tilde-fence-begin
2871 markdown-fenced-code
2872 markdown-tilde-fence-end
2873 markdown-yaml-metadata-begin
2874 markdown-yaml-metadata-section
2875 markdown-yaml-metadata-end))
2876 (markdown-get-enclosing-fenced-block-construct pos))
2877 ;; polymode removes text properties set by markdown-mode, so
2878 ;; check if `poly-markdown-mode' is active and whether the
2879 ;; `chunkmode' property is non-nil at POS.
2880 (and (bound-and-true-p poly-markdown-mode)
2881 (get-text-property pos 'chunkmode))))
2883 ;; Function was renamed to emphasize that it does not modify match-data.
2884 (defalias 'markdown-code-block-at-point 'markdown-code-block-at-point-p)
2886 (defun markdown-code-block-at-point-p ()
2887 "Return non-nil if there is a code block at the point.
2888 This includes pre blocks, tilde-fenced code blocks, and GFM
2889 quoted code blocks. This function does not modify the match
2890 data. See `markdown-inline-code-at-point-p' for inline code."
2891 (save-match-data (markdown-code-block-at-pos (point))))
2893 (defun markdown-heading-at-point ()
2894 "Return non-nil if there is a heading at the point.
2895 Set match data for `markdown-regex-header'."
2896 (let ((match-data (get-text-property (point) 'markdown-heading)))
2897 (when match-data
2898 (set-match-data match-data)
2899 t)))
2901 (defun markdown-pipe-at-bol-p ()
2902 "Return non-nil if the line begins with a pipe symbol.
2903 This may be useful for tables and Pandoc's line_blocks extension."
2904 (char-equal (char-after (point-at-bol)) ?|))
2907 ;;; Markdown Font Lock Matching Functions =====================================
2909 (defun markdown-range-property-any (begin end prop prop-values)
2910 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
2911 Also returns t if PROP is a list containing one of the PROP-VALUES.
2912 Return nil otherwise."
2913 (let (props)
2914 (catch 'found
2915 (dolist (loc (number-sequence begin end))
2916 (when (setq props (get-text-property loc prop))
2917 (cond ((listp props)
2918 ;; props is a list, check for membership
2919 (dolist (val prop-values)
2920 (when (memq val props) (throw 'found loc))))
2922 ;; props is a scalar, check for equality
2923 (dolist (val prop-values)
2924 (when (eq val props) (throw 'found loc))))))))))
2926 (defun markdown-range-properties-exist (begin end props)
2927 (cl-loop
2928 for loc in (number-sequence begin end)
2929 with result = nil
2930 while (not
2931 (setq result
2932 (cl-some (lambda (prop) (get-text-property loc prop)) props)))
2933 finally return result))
2935 (defun markdown-match-inline-generic (regex last &optional faceless)
2936 "Match inline REGEX from the point to LAST.
2937 When FACELESS is non-nil, do not return matches where faces have been applied."
2938 (when (re-search-forward regex last t)
2939 (let ((bounds (markdown-code-block-at-pos (match-beginning 1)))
2940 (face (and faceless (text-property-not-all
2941 (match-beginning 0) (match-end 0) 'face nil))))
2942 (cond
2943 ;; In code block: move past it and recursively search again
2944 (bounds
2945 (when (< (goto-char (cl-second bounds)) last)
2946 (markdown-match-inline-generic regex last faceless)))
2947 ;; When faces are found in the match range, skip over the match and
2948 ;; recursively search again.
2949 (face
2950 (when (< (goto-char (match-end 0)) last)
2951 (markdown-match-inline-generic regex last faceless)))
2952 ;; Keep match data and return t when in bounds.
2954 (<= (match-end 0) last))))))
2956 (defun markdown-match-code (last)
2957 "Match inline code fragments from point to LAST."
2958 (unless (bobp)
2959 (backward-char 1))
2960 (when (markdown-search-until-condition
2961 (lambda ()
2962 (and
2963 ;; Advance point in case of failure, but without exceeding last.
2964 (goto-char (min (1+ (match-beginning 1)) last))
2965 (not (markdown-in-comment-p (match-beginning 1)))
2966 (not (markdown-in-comment-p (match-end 1)))
2967 (not (markdown-code-block-at-pos (match-beginning 1)))))
2968 markdown-regex-code last t)
2969 (set-match-data (list (match-beginning 1) (match-end 1)
2970 (match-beginning 2) (match-end 2)
2971 (match-beginning 3) (match-end 3)
2972 (match-beginning 4) (match-end 4)))
2973 (goto-char (min (1+ (match-end 0)) last (point-max)))
2976 (defun markdown-match-bold (last)
2977 "Match inline bold from the point to LAST."
2978 (when (markdown-match-inline-generic markdown-regex-bold last)
2979 (let ((begin (match-beginning 2))
2980 (end (match-end 2)))
2981 (if (or (markdown-inline-code-at-pos-p begin)
2982 (markdown-inline-code-at-pos-p end)
2983 (markdown-in-comment-p)
2984 (markdown-range-property-any
2985 begin begin 'face '(markdown-url-face
2986 markdown-plain-url-face))
2987 (markdown-range-property-any
2988 begin end 'face '(markdown-hr-face
2989 markdown-math-face)))
2990 (progn (goto-char (min (1+ begin) last))
2991 (when (< (point) last)
2992 (markdown-match-italic last)))
2993 (set-match-data (list (match-beginning 2) (match-end 2)
2994 (match-beginning 3) (match-end 3)
2995 (match-beginning 4) (match-end 4)
2996 (match-beginning 5) (match-end 5)))
2997 t))))
2999 (defun markdown-match-italic (last)
3000 "Match inline italics from the point to LAST."
3001 (let ((regex (if (memq major-mode '(gfm-mode gfm-view-mode))
3002 markdown-regex-gfm-italic markdown-regex-italic)))
3003 (when (markdown-match-inline-generic regex last)
3004 (let ((begin (match-beginning 1))
3005 (end (match-end 1)))
3006 (if (or (markdown-inline-code-at-pos-p begin)
3007 (markdown-inline-code-at-pos-p end)
3008 (markdown-in-comment-p)
3009 (markdown-range-property-any
3010 begin begin 'face '(markdown-url-face
3011 markdown-plain-url-face))
3012 (markdown-range-property-any
3013 begin end 'face '(markdown-bold-face
3014 markdown-list-face
3015 markdown-hr-face
3016 markdown-math-face)))
3017 (progn (goto-char (min (1+ begin) last))
3018 (when (< (point) last)
3019 (markdown-match-italic last)))
3020 (set-match-data (list (match-beginning 1) (match-end 1)
3021 (match-beginning 2) (match-end 2)
3022 (match-beginning 3) (match-end 3)
3023 (match-beginning 4) (match-end 4)))
3024 t)))))
3026 (defun markdown-match-math-generic (regex last)
3027 "Match REGEX from point to LAST.
3028 REGEX is either `markdown-regex-math-inline-single' for matching
3029 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
3030 (when (and markdown-enable-math (markdown-match-inline-generic regex last))
3031 (let ((begin (match-beginning 1)) (end (match-end 1)))
3032 (prog1
3033 (if (or (markdown-range-property-any
3034 begin end 'face
3035 '(markdown-inline-code-face markdown-bold-face))
3036 (markdown-range-properties-exist
3037 begin end
3038 (markdown-get-fenced-block-middle-properties)))
3039 (markdown-match-math-generic regex last)
3041 (goto-char (1+ (match-end 0)))))))
3043 (defun markdown-match-list-items (last)
3044 "Match list items from point to LAST."
3045 (let* ((first (point))
3046 (pos first)
3047 (prop 'markdown-list-item)
3048 (bounds (car (get-text-property pos prop))))
3049 (while
3050 (and (or (null (setq bounds (car (get-text-property pos prop))))
3051 (< (cl-first bounds) pos))
3052 (< (point) last)
3053 (setq pos (next-single-char-property-change pos prop nil last))
3054 (goto-char pos)))
3055 (when bounds
3056 (set-match-data (cl-seventh bounds))
3057 ;; Step at least one character beyond point. Otherwise
3058 ;; `font-lock-fontify-keywords-region' infloops.
3059 (goto-char (min (1+ (max (point-at-eol) first))
3060 (point-max)))
3061 t)))
3063 (defun markdown-match-math-single (last)
3064 "Match single quoted $..$ math from point to LAST."
3065 (markdown-match-math-generic markdown-regex-math-inline-single last))
3067 (defun markdown-match-math-double (last)
3068 "Match double quoted $$..$$ math from point to LAST."
3069 (markdown-match-math-generic markdown-regex-math-inline-double last))
3071 (defun markdown-match-math-display (last)
3072 "Match bracketed display math \[..\] and \\[..\\] from point to LAST."
3073 (markdown-match-math-generic markdown-regex-math-display last))
3075 (defun markdown-match-propertized-text (property last)
3076 "Match text with PROPERTY from point to LAST.
3077 Restore match data previously stored in PROPERTY."
3078 (let ((saved (get-text-property (point) property))
3079 pos)
3080 (unless saved
3081 (setq pos (next-single-char-property-change (point) property nil last))
3082 (setq saved (get-text-property pos property)))
3083 (when saved
3084 (set-match-data saved)
3085 ;; Step at least one character beyond point. Otherwise
3086 ;; `font-lock-fontify-keywords-region' infloops.
3087 (goto-char (min (1+ (max (match-end 0) (point)))
3088 (point-max)))
3089 saved)))
3091 (defun markdown-match-pre-blocks (last)
3092 "Match preformatted blocks from point to LAST.
3093 Use data stored in 'markdown-pre text property during syntax
3094 analysis."
3095 (markdown-match-propertized-text 'markdown-pre last))
3097 (defun markdown-match-gfm-code-blocks (last)
3098 "Match GFM quoted code blocks from point to LAST.
3099 Use data stored in 'markdown-gfm-code text property during syntax
3100 analysis."
3101 (markdown-match-propertized-text 'markdown-gfm-code last))
3103 (defun markdown-match-gfm-open-code-blocks (last)
3104 (markdown-match-propertized-text 'markdown-gfm-block-begin last))
3106 (defun markdown-match-gfm-close-code-blocks (last)
3107 (markdown-match-propertized-text 'markdown-gfm-block-end last))
3109 (defun markdown-match-fenced-code-blocks (last)
3110 "Match fenced code blocks from the point to LAST."
3111 (markdown-match-propertized-text 'markdown-fenced-code last))
3113 (defun markdown-match-fenced-start-code-block (last)
3114 (markdown-match-propertized-text 'markdown-tilde-fence-begin last))
3116 (defun markdown-match-fenced-end-code-block (last)
3117 (markdown-match-propertized-text 'markdown-tilde-fence-end last))
3119 (defun markdown-match-blockquotes (last)
3120 "Match blockquotes from point to LAST.
3121 Use data stored in 'markdown-blockquote text property during syntax
3122 analysis."
3123 (markdown-match-propertized-text 'markdown-blockquote last))
3125 (defun markdown-match-hr (last)
3126 "Match horizontal rules comments from the point to LAST."
3127 (markdown-match-propertized-text 'markdown-hr last))
3129 (defun markdown-match-comments (last)
3130 "Match HTML comments from the point to LAST."
3131 (when (and (skip-syntax-forward "^<" last))
3132 (let ((beg (point)))
3133 (when (and (skip-syntax-forward "^>" last) (< (point) last))
3134 (forward-char)
3135 (set-match-data (list beg (point)))
3136 t))))
3138 (defun markdown-match-generic-links (last ref)
3139 "Match inline links from point to LAST.
3140 When REF is non-nil, match reference links instead of standard
3141 links with URLs."
3142 ;; Search for the next potential link (not in a code block).
3143 (while (and (progn
3144 ;; Clear match data to test for a match after functions returns.
3145 (set-match-data nil)
3146 ;; Preliminary regular expression search so we can return
3147 ;; quickly upon failure. This doesn't handle malformed links
3148 ;; or nested square brackets well, so if it passes we back up
3149 ;; continue with a more precise search.
3150 (re-search-forward
3151 (if ref
3152 markdown-regex-link-reference
3153 markdown-regex-link-inline)
3154 last 'limit))
3155 ;; Keep searching if this is in a code block, inline
3156 ;; code, or a comment, or if it is include syntax.
3157 (or (markdown-code-block-at-point-p)
3158 (markdown-inline-code-at-pos-p (match-beginning 0))
3159 (markdown-inline-code-at-pos-p (match-end 0))
3160 (markdown-in-comment-p)
3161 (and (char-equal (char-after (point-at-bol)) ?<)
3162 (char-equal (char-after (1+ (point-at-bol))) ?<)))
3163 (< (point) last)))
3164 ;; Match opening exclamation point (optional) and left bracket.
3165 (when (match-beginning 2)
3166 (let* ((bang (match-beginning 1))
3167 (first-begin (match-beginning 2))
3168 ;; Find end of block to prevent matching across blocks.
3169 (end-of-block (save-excursion
3170 (progn
3171 (goto-char (match-beginning 2))
3172 (markdown-end-of-text-block)
3173 (point))))
3174 ;; Move over balanced expressions to closing right bracket.
3175 ;; Catch unbalanced expression errors and return nil.
3176 (first-end (condition-case nil
3177 (and (goto-char first-begin)
3178 (scan-sexps (point) 1))
3179 (error nil)))
3180 ;; Continue with point at CONT-POINT upon failure.
3181 (cont-point (min (1+ first-begin) last))
3182 second-begin second-end url-begin url-end
3183 title-begin title-end)
3184 ;; When bracket found, in range, and followed by a left paren/bracket...
3185 (when (and first-end (< first-end end-of-block) (goto-char first-end)
3186 (char-equal (char-after (point)) (if ref ?\[ ?\()))
3187 ;; Scan across balanced expressions for closing parenthesis/bracket.
3188 (setq second-begin (point)
3189 second-end (condition-case nil
3190 (scan-sexps (point) 1)
3191 (error nil)))
3192 ;; Check that closing parenthesis/bracket is in range.
3193 (if (and second-end (<= second-end end-of-block) (<= second-end last))
3194 (progn
3195 ;; Search for (optional) title inside closing parenthesis
3196 (when (and (not ref) (search-forward "\"" second-end t))
3197 (setq title-begin (1- (point))
3198 title-end (and (goto-char second-end)
3199 (search-backward "\"" (1+ title-begin) t))
3200 title-end (and title-end (1+ title-end))))
3201 ;; Store URL/reference range
3202 (setq url-begin (1+ second-begin)
3203 url-end (1- (or title-begin second-end)))
3204 ;; Set match data, move point beyond link, and return
3205 (set-match-data
3206 (list (or bang first-begin) second-end ; 0 - all
3207 bang (and bang (1+ bang)) ; 1 - bang
3208 first-begin (1+ first-begin) ; 2 - markup
3209 (1+ first-begin) (1- first-end) ; 3 - link text
3210 (1- first-end) first-end ; 4 - markup
3211 second-begin (1+ second-begin) ; 5 - markup
3212 url-begin url-end ; 6 - url/reference
3213 title-begin title-end ; 7 - title
3214 (1- second-end) second-end)) ; 8 - markup
3215 ;; Nullify cont-point and leave point at end and
3216 (setq cont-point nil)
3217 (goto-char second-end))
3218 ;; If no closing parenthesis in range, update continuation point
3219 (setq cont-point (min end-of-block second-begin))))
3220 (cond
3221 ;; On failure, continue searching at cont-point
3222 ((and cont-point (< cont-point last))
3223 (goto-char cont-point)
3224 (markdown-match-generic-links last ref))
3225 ;; No more text, return nil
3226 ((and cont-point (= cont-point last))
3227 nil)
3228 ;; Return t if a match occurred
3229 (t t)))))
3231 (defun markdown-match-inline-links (last)
3232 "Match standard inline links from point to LAST."
3233 (markdown-match-generic-links last nil))
3235 (defun markdown-match-reference-links (last)
3236 "Match inline reference links from point to LAST."
3237 (markdown-match-generic-links last t))
3239 (defun markdown-match-angle-uris (last)
3240 "Match angle bracket URIs from point to LAST."
3241 (when (markdown-match-inline-generic markdown-regex-angle-uri last)
3242 (goto-char (1+ (match-end 0)))))
3244 (defun markdown-match-plain-uris (last)
3245 "Match plain URIs from point to LAST."
3246 (when (markdown-match-inline-generic markdown-regex-uri last t)
3247 (goto-char (1+ (match-end 0)))))
3249 (defvar markdown-conditional-search-function #'re-search-forward
3250 "Conditional search function used in `markdown-search-until-condition'.
3251 Made into a variable to allow for dynamic let-binding.")
3253 (defun markdown-search-until-condition (condition &rest args)
3254 (let (ret)
3255 (while (and (not ret) (apply markdown-conditional-search-function args))
3256 (setq ret (funcall condition)))
3257 ret))
3259 (defun markdown-match-generic-metadata (regexp last)
3260 "Match metadata declarations specified by REGEXP from point to LAST.
3261 These declarations must appear inside a metadata block that begins at
3262 the beginning of the buffer and ends with a blank line (or the end of
3263 the buffer)."
3264 (let* ((first (point))
3265 (end-re "\n[ \t]*\n\\|\n\\'\\|\\'")
3266 (block-begin (goto-char 1))
3267 (block-end (re-search-forward end-re nil t)))
3268 (if (and block-end (> first block-end))
3269 ;; Don't match declarations if there is no metadata block or if
3270 ;; the point is beyond the block. Move point to point-max to
3271 ;; prevent additional searches and return return nil since nothing
3272 ;; was found.
3273 (progn (goto-char (point-max)) nil)
3274 ;; If a block was found that begins before LAST and ends after
3275 ;; point, search for declarations inside it. If the starting is
3276 ;; before the beginning of the block, start there. Otherwise,
3277 ;; move back to FIRST.
3278 (goto-char (if (< first block-begin) block-begin first))
3279 (if (re-search-forward regexp (min last block-end) t)
3280 ;; If a metadata declaration is found, set match-data and return t.
3281 (let ((key-beginning (match-beginning 1))
3282 (key-end (match-end 1))
3283 (markup-begin (match-beginning 2))
3284 (markup-end (match-end 2))
3285 (value-beginning (match-beginning 3)))
3286 (set-match-data (list key-beginning (point) ; complete metadata
3287 key-beginning key-end ; key
3288 markup-begin markup-end ; markup
3289 value-beginning (point))) ; value
3291 ;; Otherwise, move the point to last and return nil
3292 (goto-char last)
3293 nil))))
3295 (defun markdown-match-declarative-metadata (last)
3296 "Match declarative metadata from the point to LAST."
3297 (markdown-match-generic-metadata markdown-regex-declarative-metadata last))
3299 (defun markdown-match-pandoc-metadata (last)
3300 "Match Pandoc metadata from the point to LAST."
3301 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
3303 (defun markdown-match-yaml-metadata-begin (last)
3304 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last))
3306 (defun markdown-match-yaml-metadata-end (last)
3307 (markdown-match-propertized-text 'markdown-yaml-metadata-end last))
3309 (defun markdown-match-yaml-metadata-key (last)
3310 (markdown-match-propertized-text 'markdown-metadata-key last))
3312 (defun markdown-match-wiki-link (last)
3313 "Match wiki links from point to LAST."
3314 (when (and markdown-enable-wiki-links
3315 (not markdown-wiki-link-fontify-missing)
3316 (markdown-match-inline-generic markdown-regex-wiki-link last))
3317 (let ((begin (match-beginning 1)) (end (match-end 1)))
3318 (if (or (markdown-in-comment-p begin)
3319 (markdown-in-comment-p end)
3320 (markdown-inline-code-at-pos-p begin)
3321 (markdown-inline-code-at-pos-p end)
3322 (markdown-code-block-at-pos begin))
3323 (progn (goto-char (min (1+ begin) last))
3324 (when (< (point) last)
3325 (markdown-match-wiki-link last)))
3326 (set-match-data (list begin end))
3327 t))))
3329 (defun markdown-match-inline-attributes (last)
3330 "Match inline attributes from point to LAST."
3331 (when (markdown-match-inline-generic markdown-regex-inline-attributes last)
3332 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
3333 (markdown-inline-code-at-pos-p (match-end 0))
3334 (markdown-in-comment-p))
3335 t)))
3337 (defun markdown-match-leanpub-sections (last)
3338 "Match Leanpub section markers from point to LAST."
3339 (when (markdown-match-inline-generic markdown-regex-leanpub-sections last)
3340 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
3341 (markdown-inline-code-at-pos-p (match-end 0))
3342 (markdown-in-comment-p))
3343 t)))
3345 (defun markdown-match-includes (last)
3346 "Match include statements from point to LAST.
3347 Sets match data for the following seven groups:
3348 Group 1: opening two angle brackets
3349 Group 2: opening title delimiter (optional)
3350 Group 3: title text (optional)
3351 Group 4: closing title delimiter (optional)
3352 Group 5: opening filename delimiter
3353 Group 6: filename
3354 Group 7: closing filename delimiter"
3355 (when (markdown-match-inline-generic markdown-regex-include last)
3356 (let ((valid (not (or (markdown-in-comment-p (match-beginning 0))
3357 (markdown-in-comment-p (match-end 0))
3358 (markdown-code-block-at-pos (match-beginning 0))))))
3359 (cond
3360 ;; Parentheses and maybe square brackets, but no curly braces:
3361 ;; match optional title in square brackets and file in parentheses.
3362 ((and valid (match-beginning 5)
3363 (not (match-beginning 8)))
3364 (set-match-data (list (match-beginning 1) (match-end 7)
3365 (match-beginning 1) (match-end 1)
3366 (match-beginning 2) (match-end 2)
3367 (match-beginning 3) (match-end 3)
3368 (match-beginning 4) (match-end 4)
3369 (match-beginning 5) (match-end 5)
3370 (match-beginning 6) (match-end 6)
3371 (match-beginning 7) (match-end 7))))
3372 ;; Only square brackets present: match file in square brackets.
3373 ((and valid (match-beginning 2)
3374 (not (match-beginning 5))
3375 (not (match-beginning 7)))
3376 (set-match-data (list (match-beginning 1) (match-end 4)
3377 (match-beginning 1) (match-end 1)
3378 nil nil
3379 nil nil
3380 nil nil
3381 (match-beginning 2) (match-end 2)
3382 (match-beginning 3) (match-end 3)
3383 (match-beginning 4) (match-end 4))))
3384 ;; Only curly braces present: match file in curly braces.
3385 ((and valid (match-beginning 8)
3386 (not (match-beginning 2))
3387 (not (match-beginning 5)))
3388 (set-match-data (list (match-beginning 1) (match-end 10)
3389 (match-beginning 1) (match-end 1)
3390 nil nil
3391 nil nil
3392 nil nil
3393 (match-beginning 8) (match-end 8)
3394 (match-beginning 9) (match-end 9)
3395 (match-beginning 10) (match-end 10))))
3397 ;; Not a valid match, move to next line and search again.
3398 (forward-line)
3399 (when (< (point) last)
3400 (setq valid (markdown-match-includes last)))))
3401 valid)))
3403 (defun markdown-match-html-tag (last)
3404 "Match HTML tags from point to LAST."
3405 (when (and markdown-enable-html
3406 (markdown-match-inline-generic markdown-regex-html-tag last t))
3407 (set-match-data (list (match-beginning 0) (match-end 0)
3408 (match-beginning 1) (match-end 1)
3409 (match-beginning 2) (match-end 2)
3410 (match-beginning 9) (match-end 9)))
3414 ;;; Markdown Font Fontification Functions =====================================
3416 (defun markdown--first-displayable (seq)
3417 "Return the first displayable character or string in SEQ.
3418 SEQ may be an atom or a sequence."
3419 (let ((seq (if (listp seq) seq (list seq))))
3420 (cond ((stringp (car seq))
3421 (cl-find-if
3422 (lambda (str)
3423 (and (mapcar #'char-displayable-p (string-to-list str))))
3424 seq))
3425 ((characterp (car seq))
3426 (cl-find-if #'char-displayable-p seq)))))
3428 (defun markdown--marginalize-string (level)
3429 "Generate atx markup string of given LEVEL for left margin."
3430 (let ((margin-left-space-count
3431 (- markdown-marginalize-headers-margin-width level)))
3432 (concat (make-string margin-left-space-count ? )
3433 (make-string level ?#))))
3435 (defun markdown-marginalize-update-current ()
3436 "Update the window configuration to create a left margin."
3437 ;; Emacs 25 or later is needed for window-font-width and default-font-width.
3438 (if (and (fboundp 'window-font-width) (fboundp 'default-font-width))
3439 (let* ((header-delimiter-font-width
3440 (window-font-width nil 'markdown-header-delimiter-face))
3441 (margin-pixel-width (* markdown-marginalize-headers-margin-width
3442 header-delimiter-font-width))
3443 (margin-char-width (/ margin-pixel-width (default-font-width))))
3444 (set-window-margins nil margin-char-width))
3445 ;; As a fallback, simply set margin based on character count.
3446 (set-window-margins nil markdown-marginalize-headers-margin-width)))
3448 (defun markdown-fontify-headings (last)
3449 "Add text properties to headings from point to LAST."
3450 (when (markdown-match-propertized-text 'markdown-heading last)
3451 (let* ((level (markdown-outline-level))
3452 (heading-face
3453 (intern (format "markdown-header-face-%d" level)))
3454 (heading-props `(face ,heading-face))
3455 (left-markup-props
3456 `(face markdown-header-delimiter-face
3457 ,@(cond
3458 (markdown-hide-markup
3459 `(display ""))
3460 (markdown-marginalize-headers
3461 `(display ((margin left-margin)
3462 ,(markdown--marginalize-string level)))))))
3463 (right-markup-props
3464 `(face markdown-header-delimiter-face
3465 ,@(when markdown-hide-markup `(display ""))))
3466 (rule-props `(face markdown-header-rule-face
3467 ,@(when markdown-hide-markup `(display "")))))
3468 (if (match-end 1)
3469 ;; Setext heading
3470 (progn (add-text-properties
3471 (match-beginning 1) (match-end 1) heading-props)
3472 (if (= level 1)
3473 (add-text-properties
3474 (match-beginning 2) (match-end 2) rule-props)
3475 (add-text-properties
3476 (match-beginning 3) (match-end 3) rule-props)))
3477 ;; atx heading
3478 (add-text-properties
3479 (match-beginning 4) (match-end 4) left-markup-props)
3480 (add-text-properties
3481 (match-beginning 5) (match-end 5) heading-props)
3482 (when (match-end 6)
3483 (add-text-properties
3484 (match-beginning 6) (match-end 6) right-markup-props))))
3487 (defun markdown-fontify-tables (last)
3488 (when (and (re-search-forward "|" last t)
3489 (markdown-table-at-point-p))
3490 (font-lock-append-text-property
3491 (line-beginning-position) (min (1+ (line-end-position)) (point-max))
3492 'face 'markdown-table-face)
3493 (forward-line 1)
3496 (defun markdown-fontify-blockquotes (last)
3497 "Apply font-lock properties to blockquotes from point to LAST."
3498 (when (markdown-match-blockquotes last)
3499 (let ((display-string
3500 (markdown--first-displayable markdown-blockquote-display-char)))
3501 (add-text-properties
3502 (match-beginning 1) (match-end 1)
3503 (if markdown-hide-markup
3504 `(face markdown-blockquote-face display ,display-string)
3505 `(face markdown-markup-face)))
3506 (font-lock-append-text-property
3507 (match-beginning 0) (match-end 0) 'face 'markdown-blockquote-face)
3508 t)))
3510 (defun markdown-fontify-list-items (last)
3511 "Apply font-lock properties to list markers from point to LAST."
3512 (when (markdown-match-list-items last)
3513 (let* ((indent (length (match-string-no-properties 1)))
3514 (level (/ indent 4)) ;; level = 0, 1, 2, ...
3515 (bullet (nth (mod level (length markdown-list-item-bullets))
3516 markdown-list-item-bullets)))
3517 (add-text-properties
3518 (match-beginning 2) (match-end 2) '(face markdown-list-face))
3519 (when markdown-hide-markup
3520 (cond
3521 ;; Unordered lists
3522 ((string-match-p "[\\*\\+-]" (match-string 2))
3523 (add-text-properties
3524 (match-beginning 2) (match-end 2) `(display ,bullet)))
3525 ;; Definition lists
3526 ((string-equal ":" (match-string 2))
3527 (let ((display-string
3528 (char-to-string (markdown--first-displayable
3529 markdown-definition-display-char))))
3530 (add-text-properties (match-beginning 2) (match-end 2)
3531 `(display ,display-string)))))))
3534 (defun markdown-fontify-hrs (last)
3535 "Add text properties to horizontal rules from point to LAST."
3536 (when (markdown-match-hr last)
3537 (let ((hr-char (markdown--first-displayable markdown-hr-display-char)))
3538 (add-text-properties
3539 (match-beginning 0) (match-end 0)
3540 `(face markdown-hr-face
3541 font-lock-multiline t
3542 ,@(when (and markdown-hide-markup hr-char)
3543 `(display ,(make-string
3544 (window-body-width) hr-char)))))
3545 t)))
3547 (defun markdown-fontify-sub-superscripts (last)
3548 "Apply text properties to sub- and superscripts from point to LAST."
3549 (when (markdown-search-until-condition
3550 (lambda () (and (not (markdown-code-block-at-point-p))
3551 (not (markdown-inline-code-at-point-p))
3552 (not (markdown-in-comment-p))))
3553 markdown-regex-sub-superscript last t)
3554 (let* ((subscript-p (string= (match-string 2) "~"))
3555 (props
3556 (if subscript-p
3557 (car markdown-sub-superscript-display)
3558 (cdr markdown-sub-superscript-display)))
3559 (mp (list 'face 'markdown-markup-face
3560 'invisible 'markdown-markup)))
3561 (when markdown-hide-markup
3562 (put-text-property (match-beginning 3) (match-end 3)
3563 'display props))
3564 (add-text-properties (match-beginning 2) (match-end 2) mp)
3565 (add-text-properties (match-beginning 4) (match-end 4) mp)
3566 t)))
3569 ;;; Syntax Table ==============================================================
3571 (defvar markdown-mode-syntax-table
3572 (let ((tab (make-syntax-table text-mode-syntax-table)))
3573 (modify-syntax-entry ?\" "." tab)
3574 tab)
3575 "Syntax table for `markdown-mode'.")
3578 ;;; Element Insertion =========================================================
3580 (defun markdown-ensure-blank-line-before ()
3581 "If previous line is not already blank, insert a blank line before point."
3582 (unless (bolp) (insert "\n"))
3583 (unless (or (bobp) (looking-back "\n\\s-*\n" nil)) (insert "\n")))
3585 (defun markdown-ensure-blank-line-after ()
3586 "If following line is not already blank, insert a blank line after point.
3587 Return the point where it was originally."
3588 (save-excursion
3589 (unless (eolp) (insert "\n"))
3590 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
3592 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
3593 "Insert the strings S1 and S2, wrapping around region or THING.
3594 If a region is specified by the optional BEG and END arguments,
3595 wrap the strings S1 and S2 around that region.
3596 If there is an active region, wrap the strings S1 and S2 around
3597 the region. If there is not an active region but the point is at
3598 THING, wrap that thing (which defaults to word). Otherwise, just
3599 insert S1 and S2 and place the point in between. Return the
3600 bounds of the entire wrapped string, or nil if nothing was wrapped
3601 and S1 and S2 were only inserted."
3602 (let (a b bounds new-point)
3603 (cond
3604 ;; Given region
3605 ((and beg end)
3606 (setq a beg
3607 b end
3608 new-point (+ (point) (length s1))))
3609 ;; Active region
3610 ((markdown-use-region-p)
3611 (setq a (region-beginning)
3612 b (region-end)
3613 new-point (+ (point) (length s1))))
3614 ;; Thing (word) at point
3615 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
3616 (setq a (car bounds)
3617 b (cdr bounds)
3618 new-point (+ (point) (length s1))))
3619 ;; No active region and no word
3621 (setq a (point)
3622 b (point))))
3623 (goto-char b)
3624 (insert s2)
3625 (goto-char a)
3626 (insert s1)
3627 (when new-point (goto-char new-point))
3628 (if (= a b)
3630 (setq b (+ b (length s1) (length s2)))
3631 (cons a b))))
3633 (defun markdown-point-after-unwrap (cur prefix suffix)
3634 "Return desired position of point after an unwrapping operation.
3635 CUR gives the position of the point before the operation.
3636 Additionally, two cons cells must be provided. PREFIX gives the
3637 bounds of the prefix string and SUFFIX gives the bounds of the
3638 suffix string."
3639 (cond ((< cur (cdr prefix)) (car prefix))
3640 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
3641 ((<= cur (cdr suffix))
3642 (- cur (+ (- (cdr prefix) (car prefix))
3643 (- cur (car suffix)))))
3644 (t cur)))
3646 (defun markdown-unwrap-thing-at-point (regexp all text)
3647 "Remove prefix and suffix of thing at point and reposition the point.
3648 When the thing at point matches REGEXP, replace the subexpression
3649 ALL with the string in subexpression TEXT. Reposition the point
3650 in an appropriate location accounting for the removal of prefix
3651 and suffix strings. Return new bounds of string from group TEXT.
3652 When REGEXP is nil, assumes match data is already set."
3653 (when (or (null regexp)
3654 (thing-at-point-looking-at regexp))
3655 (let ((cur (point))
3656 (prefix (cons (match-beginning all) (match-beginning text)))
3657 (suffix (cons (match-end text) (match-end all)))
3658 (bounds (cons (match-beginning text) (match-end text))))
3659 ;; Replace the thing at point
3660 (replace-match (match-string text) t t nil all)
3661 ;; Reposition the point
3662 (goto-char (markdown-point-after-unwrap cur prefix suffix))
3663 ;; Adjust bounds
3664 (setq bounds (cons (car prefix)
3665 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
3667 (defun markdown-unwrap-things-in-region (beg end regexp all text)
3668 "Remove prefix and suffix of all things in region from BEG to END.
3669 When a thing in the region matches REGEXP, replace the
3670 subexpression ALL with the string in subexpression TEXT.
3671 Return a cons cell containing updated bounds for the region."
3672 (save-excursion
3673 (goto-char beg)
3674 (let ((removed 0) len-all len-text)
3675 (while (re-search-forward regexp (- end removed) t)
3676 (setq len-all (length (match-string-no-properties all)))
3677 (setq len-text (length (match-string-no-properties text)))
3678 (setq removed (+ removed (- len-all len-text)))
3679 (replace-match (match-string text) t t nil all))
3680 (cons beg (- end removed)))))
3682 (defun markdown-insert-hr (arg)
3683 "Insert or replace a horizonal rule.
3684 By default, use the first element of `markdown-hr-strings'. When
3685 ARG is non-nil, as when given a prefix, select a different
3686 element as follows. When prefixed with \\[universal-argument],
3687 use the last element of `markdown-hr-strings' instead. When
3688 prefixed with an integer from 1 to the length of
3689 `markdown-hr-strings', use the element in that position instead."
3690 (interactive "*P")
3691 (when (thing-at-point-looking-at markdown-regex-hr)
3692 (delete-region (match-beginning 0) (match-end 0)))
3693 (markdown-ensure-blank-line-before)
3694 (cond ((equal arg '(4))
3695 (insert (car (reverse markdown-hr-strings))))
3696 ((and (integerp arg) (> arg 0)
3697 (<= arg (length markdown-hr-strings)))
3698 (insert (nth (1- arg) markdown-hr-strings)))
3700 (insert (car markdown-hr-strings))))
3701 (markdown-ensure-blank-line-after))
3703 (defun markdown-insert-bold ()
3704 "Insert markup to make a region or word bold.
3705 If there is an active region, make the region bold. If the point
3706 is at a non-bold word, make the word bold. If the point is at a
3707 bold word or phrase, remove the bold markup. Otherwise, simply
3708 insert bold delimiters and place the point in between them."
3709 (interactive)
3710 (let ((delim (if markdown-bold-underscore "__" "**")))
3711 (if (markdown-use-region-p)
3712 ;; Active region
3713 (let ((bounds (markdown-unwrap-things-in-region
3714 (region-beginning) (region-end)
3715 markdown-regex-bold 2 4)))
3716 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3717 ;; Bold markup removal, bold word at point, or empty markup insertion
3718 (if (thing-at-point-looking-at markdown-regex-bold)
3719 (markdown-unwrap-thing-at-point nil 2 4)
3720 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3722 (defun markdown-insert-italic ()
3723 "Insert markup to make a region or word italic.
3724 If there is an active region, make the region italic. If the point
3725 is at a non-italic word, make the word italic. If the point is at an
3726 italic word or phrase, remove the italic markup. Otherwise, simply
3727 insert italic delimiters and place the point in between them."
3728 (interactive)
3729 (let ((delim (if markdown-italic-underscore "_" "*")))
3730 (if (markdown-use-region-p)
3731 ;; Active region
3732 (let ((bounds (markdown-unwrap-things-in-region
3733 (region-beginning) (region-end)
3734 markdown-regex-italic 1 3)))
3735 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3736 ;; Italic markup removal, italic word at point, or empty markup insertion
3737 (if (thing-at-point-looking-at markdown-regex-italic)
3738 (markdown-unwrap-thing-at-point nil 1 3)
3739 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3741 (defun markdown-insert-strike-through ()
3742 "Insert markup to make a region or word strikethrough.
3743 If there is an active region, make the region strikethrough. If the point
3744 is at a non-bold word, make the word strikethrough. If the point is at a
3745 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
3746 simply insert bold delimiters and place the point in between them."
3747 (interactive)
3748 (let ((delim "~~"))
3749 (if (markdown-use-region-p)
3750 ;; Active region
3751 (let ((bounds (markdown-unwrap-things-in-region
3752 (region-beginning) (region-end)
3753 markdown-regex-strike-through 2 4)))
3754 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3755 ;; Strikethrough markup removal, strikethrough word at point, or empty markup insertion
3756 (if (thing-at-point-looking-at markdown-regex-strike-through)
3757 (markdown-unwrap-thing-at-point nil 2 4)
3758 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3760 (defun markdown-insert-code ()
3761 "Insert markup to make a region or word an inline code fragment.
3762 If there is an active region, make the region an inline code
3763 fragment. If the point is at a word, make the word an inline
3764 code fragment. Otherwise, simply insert code delimiters and
3765 place the point in between them."
3766 (interactive)
3767 (if (markdown-use-region-p)
3768 ;; Active region
3769 (let ((bounds (markdown-unwrap-things-in-region
3770 (region-beginning) (region-end)
3771 markdown-regex-code 1 3)))
3772 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
3773 ;; Code markup removal, code markup for word, or empty markup insertion
3774 (if (markdown-inline-code-at-point)
3775 (markdown-unwrap-thing-at-point nil 0 2)
3776 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
3778 (defun markdown-insert-kbd ()
3779 "Insert markup to wrap region or word in <kbd> tags.
3780 If there is an active region, use the region. If the point is at
3781 a word, use the word. Otherwise, simply insert <kbd> tags and
3782 place the point in between them."
3783 (interactive)
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-kbd 0 2)))
3789 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil (car bounds) (cdr bounds)))
3790 ;; Markup removal, markup for word, or empty markup insertion
3791 (if (thing-at-point-looking-at markdown-regex-kbd)
3792 (markdown-unwrap-thing-at-point nil 0 2)
3793 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil))))
3795 (defun markdown-insert-inline-link (text url &optional title)
3796 "Insert an inline link with TEXT pointing to URL.
3797 Optionally, the user can provide a TITLE."
3798 (let ((cur (point)))
3799 (setq title (and title (concat " \"" title "\"")))
3800 (insert (concat "[" text "](" url title ")"))
3801 (cond ((not text) (goto-char (+ 1 cur)))
3802 ((not url) (goto-char (+ 3 (length text) cur))))))
3804 (defun markdown-insert-inline-image (text url &optional title)
3805 "Insert an inline link with alt TEXT pointing to URL.
3806 Optionally, also provide a TITLE."
3807 (let ((cur (point)))
3808 (setq title (and title (concat " \"" title "\"")))
3809 (insert (concat "![" text "](" url title ")"))
3810 (cond ((not text) (goto-char (+ 2 cur)))
3811 ((not url) (goto-char (+ 4 (length text) cur))))))
3813 (defun markdown-insert-reference-link (text label &optional url title)
3814 "Insert a reference link and, optionally, a reference definition.
3815 The link TEXT will be inserted followed by the optional LABEL.
3816 If a URL is given, also insert a definition for the reference
3817 LABEL according to `markdown-reference-location'. If a TITLE is
3818 given, it will be added to the end of the reference definition
3819 and will be used to populate the title attribute when converted
3820 to XHTML. If URL is nil, insert only the link portion (for
3821 example, when a reference label is already defined)."
3822 (insert (concat "[" text "][" label "]"))
3823 (when url
3824 (markdown-insert-reference-definition
3825 (if (string-equal label "") text label)
3826 url title)))
3828 (defun markdown-insert-reference-image (text label &optional url title)
3829 "Insert a reference image and, optionally, a reference definition.
3830 The alt TEXT will be inserted followed by the optional LABEL.
3831 If a URL is given, also insert a definition for the reference
3832 LABEL according to `markdown-reference-location'. If a TITLE is
3833 given, it will be added to the end of the reference definition
3834 and will be used to populate the title attribute when converted
3835 to XHTML. If URL is nil, insert only the link portion (for
3836 example, when a reference label is already defined)."
3837 (insert (concat "![" text "][" label "]"))
3838 (when url
3839 (markdown-insert-reference-definition
3840 (if (string-equal label "") text label)
3841 url title)))
3843 (defun markdown-insert-reference-definition (label &optional url title)
3844 "Add definition for reference LABEL with URL and TITLE.
3845 LABEL is a Markdown reference label without square brackets.
3846 URL and TITLE are optional. When given, the TITLE will
3847 be used to populate the title attribute when converted to XHTML."
3848 ;; END specifies where to leave the point upon return
3849 (let ((end (point)))
3850 (cl-case markdown-reference-location
3851 (end (goto-char (point-max)))
3852 (immediately (markdown-end-of-text-block))
3853 (subtree (markdown-end-of-subtree))
3854 (header (markdown-end-of-defun)))
3855 ;; Skip backwards over local variables. This logic is similar to the one
3856 ;; used in ‘hack-local-variables’.
3857 (when (and enable-local-variables (eobp))
3858 (search-backward "\n\f" (max (- (point) 3000) (point-min)) :move)
3859 (when (let ((case-fold-search t))
3860 (search-forward "Local Variables:" nil :move))
3861 (beginning-of-line 0)
3862 (when (eq (char-before) ?\n) (backward-char))))
3863 (unless (or (markdown-cur-line-blank-p)
3864 (thing-at-point-looking-at markdown-regex-reference-definition))
3865 (insert "\n"))
3866 (insert "\n[" label "]: ")
3867 (if url
3868 (insert url)
3869 ;; When no URL is given, leave point at END following the colon
3870 (setq end (point)))
3871 (when (> (length title) 0)
3872 (insert " \"" title "\""))
3873 (unless (looking-at-p "\n")
3874 (insert "\n"))
3875 (goto-char end)
3876 (when url
3877 (message
3878 (markdown--substitute-command-keys
3879 "Reference [%s] was defined, press \\[markdown-do] to jump there")
3880 label))))
3882 (define-obsolete-function-alias
3883 'markdown-insert-inline-link-dwim 'markdown-insert-link "v2.3")
3884 (define-obsolete-function-alias
3885 'markdown-insert-reference-link-dwim 'markdown-insert-link "v2.3")
3887 (defun markdown--insert-link-or-image (image)
3888 "Interactively insert new or update an existing link or image.
3889 When IMAGE is non-nil, insert an image. Otherwise, insert a link.
3890 This is an internal function called by
3891 `markdown-insert-link' and `markdown-insert-image'."
3892 (cl-multiple-value-bind (begin end text uri ref title)
3893 (if (markdown-use-region-p)
3894 ;; Use region as either link text or URL as appropriate.
3895 (let ((region (buffer-substring-no-properties
3896 (region-beginning) (region-end))))
3897 (if (string-match markdown-regex-uri region)
3898 ;; Region contains a URL; use it as such.
3899 (list (region-beginning) (region-end)
3900 nil (match-string 0 region) nil nil)
3901 ;; Region doesn't contain a URL, so use it as text.
3902 (list (region-beginning) (region-end)
3903 region nil nil nil)))
3904 ;; Extract and use properties of existing link, if any.
3905 (markdown-link-at-pos (point)))
3906 (let* ((ref (when ref (concat "[" ref "]")))
3907 (defined-refs (append
3908 (mapcar (lambda (ref) (concat "[" ref "]"))
3909 (markdown-get-defined-references))))
3910 (used-uris (markdown-get-used-uris))
3911 (uri-or-ref (completing-read
3912 "URL or [reference]: "
3913 (append defined-refs used-uris)
3914 nil nil (or uri ref)))
3915 (ref (cond ((string-match "\\`\\[\\(.*\\)\\]\\'" uri-or-ref)
3916 (match-string 1 uri-or-ref))
3917 ((string-equal "" uri-or-ref)
3918 "")))
3919 (uri (unless ref uri-or-ref))
3920 (text-prompt (if image
3921 "Alt text: "
3922 (if ref
3923 "Link text: "
3924 "Link text (blank for plain URL): ")))
3925 (text (read-string text-prompt text))
3926 (text (if (= (length text) 0) nil text))
3927 (plainp (and uri (not text)))
3928 (implicitp (string-equal ref ""))
3929 (ref (if implicitp text ref))
3930 (definedp (and ref (markdown-reference-definition ref)))
3931 (ref-url (unless (or uri definedp)
3932 (completing-read "Reference URL: " used-uris)))
3933 (title (unless (or plainp definedp)
3934 (read-string "Title (tooltip text, optional): " title)))
3935 (title (if (= (length title) 0) nil title)))
3936 (when (and image implicitp)
3937 (user-error "Reference required: implicit image references are invalid"))
3938 (when (and begin end)
3939 (delete-region begin end))
3940 (cond
3941 ((and (not image) uri text)
3942 (markdown-insert-inline-link text uri title))
3943 ((and image uri text)
3944 (markdown-insert-inline-image text uri title))
3945 ((and ref text)
3946 (if image
3947 (markdown-insert-reference-image text (unless implicitp ref) nil title)
3948 (markdown-insert-reference-link text (unless implicitp ref) nil title))
3949 (unless definedp
3950 (markdown-insert-reference-definition ref ref-url title)))
3951 ((and (not image) uri)
3952 (markdown-insert-uri uri))))))
3954 (defun markdown-insert-link ()
3955 "Insert new or update an existing link, with interactive prompts.
3956 If the point is at an existing link or URL, update the link text,
3957 URL, reference label, and/or title. Otherwise, insert a new link.
3958 The type of link inserted (inline, reference, or plain URL)
3959 depends on which values are provided:
3961 * If a URL and TEXT are given, insert an inline link: [TEXT](URL).
3962 * If [REF] and TEXT are given, insert a reference link: [TEXT][REF].
3963 * If only TEXT is given, insert an implicit reference link: [TEXT][].
3964 * If only a URL is given, insert a plain link: <URL>.
3966 In other words, to create an implicit reference link, leave the
3967 URL prompt empty and to create a plain URL link, leave the link
3968 text empty.
3970 If there is an active region, use the text as the default URL, if
3971 it seems to be a URL, or link text value otherwise.
3973 If a given reference is not defined, this function will
3974 additionally prompt for the URL and optional title. In this case,
3975 the reference definition is placed at the location determined by
3976 `markdown-reference-location'.
3978 Through updating the link, this function can be used to convert a
3979 link of one type (inline, reference, or plain) to another type by
3980 selectively adding or removing information via the prompts."
3981 (interactive)
3982 (markdown--insert-link-or-image nil))
3984 (defun markdown-insert-image ()
3985 "Insert new or update an existing image, with interactive prompts.
3986 If the point is at an existing image, update the alt text, URL,
3987 reference label, and/or title. Otherwise, insert a new image.
3988 The type of image inserted (inline or reference) depends on which
3989 values are provided:
3991 * If a URL and ALT-TEXT are given, insert an inline image:
3992 ![ALT-TEXT](URL).
3993 * If [REF] and ALT-TEXT are given, insert a reference image:
3994 ![ALT-TEXT][REF].
3996 If there is an active region, use the text as the default URL, if
3997 it seems to be a URL, or alt text value otherwise.
3999 If a given reference is not defined, this function will
4000 additionally prompt for the URL and optional title. In this case,
4001 the reference definition is placed at the location determined by
4002 `markdown-reference-location'.
4004 Through updating the image, this function can be used to convert an
4005 image of one type (inline or reference) to another type by
4006 selectively adding or removing information via the prompts."
4007 (interactive)
4008 (markdown--insert-link-or-image t))
4010 (defun markdown-insert-uri (&optional uri)
4011 "Insert markup for an inline URI.
4012 If there is an active region, use it as the URI. If the point is
4013 at a URI, wrap it with angle brackets. If the point is at an
4014 inline URI, remove the angle brackets. Otherwise, simply insert
4015 angle brackets place the point between them."
4016 (interactive)
4017 (if (markdown-use-region-p)
4018 ;; Active region
4019 (let ((bounds (markdown-unwrap-things-in-region
4020 (region-beginning) (region-end)
4021 markdown-regex-angle-uri 0 2)))
4022 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
4023 ;; Markup removal, URI at point, new URI, or empty markup insertion
4024 (if (thing-at-point-looking-at markdown-regex-angle-uri)
4025 (markdown-unwrap-thing-at-point nil 0 2)
4026 (if uri
4027 (insert "<" uri ">")
4028 (markdown-wrap-or-insert "<" ">" 'url nil nil)))))
4030 (defun markdown-insert-wiki-link ()
4031 "Insert a wiki link of the form [[WikiLink]].
4032 If there is an active region, use the region as the link text.
4033 If the point is at a word, use the word as the link text. If
4034 there is no active region and the point is not at word, simply
4035 insert link markup."
4036 (interactive)
4037 (if (markdown-use-region-p)
4038 ;; Active region
4039 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
4040 ;; Markup removal, wiki link at at point, or empty markup insertion
4041 (if (thing-at-point-looking-at markdown-regex-wiki-link)
4042 (if (or markdown-wiki-link-alias-first
4043 (null (match-string 5)))
4044 (markdown-unwrap-thing-at-point nil 1 3)
4045 (markdown-unwrap-thing-at-point nil 1 5))
4046 (markdown-wrap-or-insert "[[" "]]"))))
4048 (defun markdown-remove-header ()
4049 "Remove header markup if point is at a header.
4050 Return bounds of remaining header text if a header was removed
4051 and nil otherwise."
4052 (interactive "*")
4053 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
4054 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
4056 (defun markdown-insert-header (&optional level text setext)
4057 "Insert or replace header markup.
4058 The level of the header is specified by LEVEL and header text is
4059 given by TEXT. LEVEL must be an integer from 1 and 6, and the
4060 default value is 1.
4061 When TEXT is nil, the header text is obtained as follows.
4062 If there is an active region, it is used as the header text.
4063 Otherwise, the current line will be used as the header text.
4064 If there is not an active region and the point is at a header,
4065 remove the header markup and replace with level N header.
4066 Otherwise, insert empty header markup and place the point in
4067 between.
4068 The style of the header will be atx (hash marks) unless
4069 SETEXT is non-nil, in which case a setext-style (underlined)
4070 header will be inserted."
4071 (interactive "p\nsHeader text: ")
4072 (setq level (min (max (or level 1) 1) (if setext 2 6)))
4073 ;; Determine header text if not given
4074 (when (null text)
4075 (if (markdown-use-region-p)
4076 ;; Active region
4077 (setq text (delete-and-extract-region (region-beginning) (region-end)))
4078 ;; No active region
4079 (markdown-remove-header)
4080 (setq text (delete-and-extract-region
4081 (line-beginning-position) (line-end-position)))
4082 (when (and setext (string-match-p "^[ \t]*$" text))
4083 (setq text (read-string "Header text: "))))
4084 (setq text (markdown-compress-whitespace-string text)))
4085 ;; Insertion with given text
4086 (markdown-ensure-blank-line-before)
4087 (let (hdr)
4088 (cond (setext
4089 (setq hdr (make-string (string-width text) (if (= level 2) ?- ?=)))
4090 (insert text "\n" hdr))
4092 (setq hdr (make-string level ?#))
4093 (insert hdr " " text)
4094 (when (null markdown-asymmetric-header) (insert " " hdr)))))
4095 (markdown-ensure-blank-line-after)
4096 ;; Leave point at end of text
4097 (cond (setext
4098 (backward-char (1+ (string-width text))))
4099 ((null markdown-asymmetric-header)
4100 (backward-char (1+ level)))))
4102 (defun markdown-insert-header-dwim (&optional arg setext)
4103 "Insert or replace header markup.
4104 The level and type of the header are determined automatically by
4105 the type and level of the previous header, unless a prefix
4106 argument is given via ARG.
4107 With a numeric prefix valued 1 to 6, insert a header of the given
4108 level, with the type being determined automatically (note that
4109 only level 1 or 2 setext headers are possible).
4111 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
4112 promote the heading by one level.
4113 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
4114 demote the heading by one level.
4115 When SETEXT is non-nil, prefer setext-style headers when
4116 possible (levels one and two).
4118 When there is an active region, use it for the header text. When
4119 the point is at an existing header, change the type and level
4120 according to the rules above.
4121 Otherwise, if the line is not empty, create a header using the
4122 text on the current line as the header text.
4123 Finally, if the point is on a blank line, insert empty header
4124 markup (atx) or prompt for text (setext).
4125 See `markdown-insert-header' for more details about how the
4126 header text is determined."
4127 (interactive "*P")
4128 (let (level)
4129 (save-excursion
4130 (when (or (thing-at-point-looking-at markdown-regex-header)
4131 (re-search-backward markdown-regex-header nil t))
4132 ;; level of current or previous header
4133 (setq level (markdown-outline-level))
4134 ;; match group 1 indicates a setext header
4135 (setq setext (match-end 1))))
4136 ;; check prefix argument
4137 (cond
4138 ((and (equal arg '(4)) level (> level 1)) ;; C-u
4139 (cl-decf level))
4140 ((and (equal arg '(16)) level (< level 6)) ;; C-u C-u
4141 (cl-incf level))
4142 (arg ;; numeric prefix
4143 (setq level (prefix-numeric-value arg))))
4144 ;; setext headers must be level one or two
4145 (and level (setq setext (and setext (<= level 2))))
4146 ;; insert the heading
4147 (markdown-insert-header level nil setext)))
4149 (defun markdown-insert-header-setext-dwim (&optional arg)
4150 "Insert or replace header markup, with preference for setext.
4151 See `markdown-insert-header-dwim' for details, including how ARG is handled."
4152 (interactive "*P")
4153 (markdown-insert-header-dwim arg t))
4155 (defun markdown-insert-header-atx-1 ()
4156 "Insert a first level atx-style (hash mark) header.
4157 See `markdown-insert-header'."
4158 (interactive "*")
4159 (markdown-insert-header 1 nil nil))
4161 (defun markdown-insert-header-atx-2 ()
4162 "Insert a level two atx-style (hash mark) header.
4163 See `markdown-insert-header'."
4164 (interactive "*")
4165 (markdown-insert-header 2 nil nil))
4167 (defun markdown-insert-header-atx-3 ()
4168 "Insert a level three atx-style (hash mark) header.
4169 See `markdown-insert-header'."
4170 (interactive "*")
4171 (markdown-insert-header 3 nil nil))
4173 (defun markdown-insert-header-atx-4 ()
4174 "Insert a level four atx-style (hash mark) header.
4175 See `markdown-insert-header'."
4176 (interactive "*")
4177 (markdown-insert-header 4 nil nil))
4179 (defun markdown-insert-header-atx-5 ()
4180 "Insert a level five atx-style (hash mark) header.
4181 See `markdown-insert-header'."
4182 (interactive "*")
4183 (markdown-insert-header 5 nil nil))
4185 (defun markdown-insert-header-atx-6 ()
4186 "Insert a sixth level atx-style (hash mark) header.
4187 See `markdown-insert-header'."
4188 (interactive "*")
4189 (markdown-insert-header 6 nil nil))
4191 (defun markdown-insert-header-setext-1 ()
4192 "Insert a setext-style (underlined) first-level header.
4193 See `markdown-insert-header'."
4194 (interactive "*")
4195 (markdown-insert-header 1 nil t))
4197 (defun markdown-insert-header-setext-2 ()
4198 "Insert a setext-style (underlined) second-level header.
4199 See `markdown-insert-header'."
4200 (interactive "*")
4201 (markdown-insert-header 2 nil t))
4203 (defun markdown-blockquote-indentation (loc)
4204 "Return string containing necessary indentation for a blockquote at LOC.
4205 Also see `markdown-pre-indentation'."
4206 (save-excursion
4207 (goto-char loc)
4208 (let* ((list-level (length (markdown-calculate-list-levels)))
4209 (indent ""))
4210 (dotimes (_ list-level indent)
4211 (setq indent (concat indent " "))))))
4213 (defun markdown-insert-blockquote ()
4214 "Start a blockquote section (or blockquote the region).
4215 If Transient Mark mode is on and a region is active, it is used as
4216 the blockquote text."
4217 (interactive)
4218 (if (markdown-use-region-p)
4219 (markdown-blockquote-region (region-beginning) (region-end))
4220 (markdown-ensure-blank-line-before)
4221 (insert (markdown-blockquote-indentation (point)) "> ")
4222 (markdown-ensure-blank-line-after)))
4224 (defun markdown-block-region (beg end prefix)
4225 "Format the region using a block prefix.
4226 Arguments BEG and END specify the beginning and end of the
4227 region. The characters PREFIX will appear at the beginning
4228 of each line."
4229 (save-excursion
4230 (let* ((end-marker (make-marker))
4231 (beg-marker (make-marker))
4232 (prefix-without-trailing-whitespace
4233 (replace-regexp-in-string (rx (+ blank) eos) "" prefix)))
4234 ;; Ensure blank line after and remove extra whitespace
4235 (goto-char end)
4236 (skip-syntax-backward "-")
4237 (set-marker end-marker (point))
4238 (delete-horizontal-space)
4239 (markdown-ensure-blank-line-after)
4240 ;; Ensure blank line before and remove extra whitespace
4241 (goto-char beg)
4242 (skip-syntax-forward "-")
4243 (delete-horizontal-space)
4244 (markdown-ensure-blank-line-before)
4245 (set-marker beg-marker (point))
4246 ;; Insert PREFIX before each line
4247 (goto-char beg-marker)
4248 (while (and (< (line-beginning-position) end-marker)
4249 (not (eobp)))
4250 ;; Don’t insert trailing whitespace.
4251 (insert (if (eolp) prefix-without-trailing-whitespace prefix))
4252 (forward-line)))))
4254 (defun markdown-blockquote-region (beg end)
4255 "Blockquote the region.
4256 Arguments BEG and END specify the beginning and end of the region."
4257 (interactive "*r")
4258 (markdown-block-region
4259 beg end (concat (markdown-blockquote-indentation
4260 (max (point-min) (1- beg))) "> ")))
4262 (defun markdown-pre-indentation (loc)
4263 "Return string containing necessary whitespace for a pre block at LOC.
4264 Also see `markdown-blockquote-indentation'."
4265 (save-excursion
4266 (goto-char loc)
4267 (let* ((list-level (length (markdown-calculate-list-levels)))
4268 indent)
4269 (dotimes (_ (1+ list-level) indent)
4270 (setq indent (concat indent " "))))))
4272 (defun markdown-insert-pre ()
4273 "Start a preformatted section (or apply to the region).
4274 If Transient Mark mode is on and a region is active, it is marked
4275 as preformatted text."
4276 (interactive)
4277 (if (markdown-use-region-p)
4278 (markdown-pre-region (region-beginning) (region-end))
4279 (markdown-ensure-blank-line-before)
4280 (insert (markdown-pre-indentation (point)))
4281 (markdown-ensure-blank-line-after)))
4283 (defun markdown-pre-region (beg end)
4284 "Format the region as preformatted text.
4285 Arguments BEG and END specify the beginning and end of the region."
4286 (interactive "*r")
4287 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
4288 (markdown-block-region beg end indent)))
4290 (defun markdown-electric-backquote (arg)
4291 "Insert a backquote.
4292 The numeric prefix argument ARG says how many times to repeat the insertion.
4293 Call `markdown-insert-gfm-code-block' interactively
4294 if three backquotes inserted at the beginning of line."
4295 (interactive "*P")
4296 (self-insert-command (prefix-numeric-value arg))
4297 (when (and markdown-gfm-use-electric-backquote (looking-back "^```" nil))
4298 (replace-match "")
4299 (call-interactively #'markdown-insert-gfm-code-block)))
4301 (defconst markdown-gfm-recognized-languages
4302 ;; To reproduce/update, evaluate the let-form in
4303 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
4304 ;; but with appropriate use of a keyboard macro, indenting and filling it
4305 ;; properly is pretty fast.
4306 '("1C-Enterprise" "ABAP" "ABNF" "AGS-Script" "AMPL" "ANTLR"
4307 "API-Blueprint" "APL" "ASN.1" "ASP" "ATS" "ActionScript" "Ada" "Agda"
4308 "Alloy" "Alpine-Abuild" "Ant-Build-System" "ApacheConf" "Apex"
4309 "Apollo-Guidance-Computer" "AppleScript" "Arc" "Arduino" "AsciiDoc"
4310 "AspectJ" "Assembly" "Augeas" "AutoHotkey" "AutoIt" "Awk" "Batchfile"
4311 "Befunge" "Bison" "BitBake" "Blade" "BlitzBasic" "BlitzMax" "Bluespec"
4312 "Boo" "Brainfuck" "Brightscript" "Bro" "C#" "C++" "C-ObjDump"
4313 "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "COLLADA" "CSON" "CSS" "CSV"
4314 "CWeb" "Cap'n-Proto" "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK"
4315 "Cirru" "Clarion" "Clean" "Click" "Clojure" "Closure-Templates"
4316 "CoffeeScript" "ColdFusion" "ColdFusion-CFC" "Common-Lisp"
4317 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal"
4318 "Csound" "Csound-Document" "Csound-Score" "Cuda" "Cycript" "Cython"
4319 "D-ObjDump" "DIGITAL-Command-Language" "DM" "DNS-Zone" "DTrace"
4320 "Darcs-Patch" "Dart" "Diff" "Dockerfile" "Dogescript" "Dylan" "EBNF"
4321 "ECL" "ECLiPSe" "EJS" "EQ" "Eagle" "Ecere-Projects" "Eiffel" "Elixir"
4322 "Elm" "Emacs-Lisp" "EmberScript" "Erlang" "F#" "FLUX" "Factor" "Fancy"
4323 "Fantom" "Filebench-WML" "Filterscript" "Formatted" "Forth" "Fortran"
4324 "FreeMarker" "Frege" "G-code" "GAMS" "GAP" "GCC-Machine-Description"
4325 "GDB" "GDScript" "GLSL" "GN" "Game-Maker-Language" "Genie" "Genshi"
4326 "Gentoo-Ebuild" "Gentoo-Eclass" "Gettext-Catalog" "Gherkin" "Glyph"
4327 "Gnuplot" "Go" "Golo" "Gosu" "Grace" "Gradle" "Grammatical-Framework"
4328 "Graph-Modeling-Language" "GraphQL" "Graphviz-(DOT)" "Groovy"
4329 "Groovy-Server-Pages" "HCL" "HLSL" "HTML" "HTML+Django" "HTML+ECR"
4330 "HTML+EEX" "HTML+ERB" "HTML+PHP" "HTTP" "Hack" "Haml" "Handlebars"
4331 "Harbour" "Haskell" "Haxe" "Hy" "HyPhy" "IDL" "IGOR-Pro" "INI"
4332 "IRC-log" "Idris" "Inform-7" "Inno-Setup" "Io" "Ioke" "Isabelle"
4333 "Isabelle-ROOT" "JFlex" "JSON" "JSON5" "JSONLD" "JSONiq" "JSX"
4334 "Jasmin" "Java" "Java-Server-Pages" "JavaScript" "Jison" "Jison-Lex"
4335 "Jolie" "Julia" "Jupyter-Notebook" "KRL" "KiCad" "Kit" "Kotlin" "LFE"
4336 "LLVM" "LOLCODE" "LSL" "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex"
4337 "LilyPond" "Limbo" "Linker-Script" "Linux-Kernel-Module" "Liquid"
4338 "Literate-Agda" "Literate-CoffeeScript" "Literate-Haskell"
4339 "LiveScript" "Logos" "Logtalk" "LookML" "LoomScript" "Lua" "M4"
4340 "M4Sugar" "MAXScript" "MQL4" "MQL5" "MTML" "MUF" "Makefile" "Mako"
4341 "Markdown" "Marko" "Mask" "Mathematica" "Matlab" "Maven-POM" "Max"
4342 "MediaWiki" "Mercury" "Meson" "Metal" "MiniD" "Mirah" "Modelica"
4343 "Modula-2" "Module-Management-System" "Monkey" "Moocode" "MoonScript"
4344 "Myghty" "NCL" "NL" "NSIS" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo"
4345 "NewLisp" "Nginx" "Nim" "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml"
4346 "ObjDump" "Objective-C" "Objective-C++" "Objective-J" "Omgrofl" "Opa"
4347 "Opal" "OpenCL" "OpenEdge-ABL" "OpenRC-runscript" "OpenSCAD"
4348 "OpenType-Feature-File" "Org" "Ox" "Oxygene" "Oz" "P4" "PAWN" "PHP"
4349 "PLSQL" "PLpgSQL" "POV-Ray-SDL" "Pan" "Papyrus" "Parrot"
4350 "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal" "Pep8"
4351 "Perl" "Perl6" "Pic" "Pickle" "PicoLisp" "PigLatin" "Pike" "Pod"
4352 "PogoScript" "Pony" "PostScript" "PowerBuilder" "PowerShell"
4353 "Processing" "Prolog" "Propeller-Spin" "Protocol-Buffer" "Public-Key"
4354 "Pug" "Puppet" "Pure-Data" "PureBasic" "PureScript" "Python"
4355 "Python-console" "Python-traceback" "QML" "QMake" "RAML" "RDoc"
4356 "REALbasic" "REXX" "RHTML" "RMarkdown" "RPM-Spec" "RUNOFF" "Racket"
4357 "Ragel" "Rascal" "Raw-token-data" "Reason" "Rebol" "Red" "Redcode"
4358 "Regular-Expression" "Ren'Py" "RenderScript" "RobotFramework" "Roff"
4359 "Rouge" "Ruby" "Rust" "SAS" "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL"
4360 "SRecode-Template" "STON" "SVG" "Sage" "SaltStack" "Sass" "Scala"
4361 "Scaml" "Scheme" "Scilab" "Self" "ShaderLab" "Shell" "ShellSession"
4362 "Shen" "Slash" "Slim" "Smali" "Smalltalk" "Smarty" "SourcePawn"
4363 "Spline-Font-Database" "Squirrel" "Stan" "Standard-ML" "Stata"
4364 "Stylus" "SubRip-Text" "Sublime-Text-Config" "SuperCollider" "Swift"
4365 "SystemVerilog" "TI-Program" "TLA" "TOML" "TXL" "Tcl" "Tcsh" "TeX"
4366 "Tea" "Terra" "Text" "Textile" "Thrift" "Turing" "Turtle" "Twig"
4367 "Type-Language" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset"
4368 "Unix-Assembly" "Uno" "UnrealScript" "UrWeb" "VCL" "VHDL" "Vala"
4369 "Verilog" "Vim-script" "Visual-Basic" "Volt" "Vue"
4370 "Wavefront-Material" "Wavefront-Object" "Web-Ontology-Language"
4371 "WebAssembly" "WebIDL" "World-of-Warcraft-Addon-Data" "X10" "XC"
4372 "XCompose" "XML" "XPages" "XProc" "XQuery" "XS" "XSLT" "Xojo" "Xtend"
4373 "YAML" "YANG" "Yacc" "Zephir" "Zimpl" "desktop" "eC" "edn" "fish"
4374 "mupad" "nesC" "ooc" "reStructuredText" "wisp" "xBase")
4375 "Language specifiers recognized by GitHub's syntax highlighting features.")
4377 (defvar markdown-gfm-used-languages nil
4378 "Language names used in GFM code blocks.")
4379 (make-variable-buffer-local 'markdown-gfm-used-languages)
4381 (defun markdown-trim-whitespace (str)
4382 (markdown-replace-regexp-in-string
4383 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str))
4385 (defun markdown-clean-language-string (str)
4386 (markdown-replace-regexp-in-string
4387 "{\\.?\\|}" "" (markdown-trim-whitespace str)))
4389 (defun markdown-validate-language-string (widget)
4390 (let ((str (widget-value widget)))
4391 (unless (string= str (markdown-clean-language-string str))
4392 (widget-put widget :error (format "Invalid language spec: '%s'" str))
4393 widget)))
4395 (defun markdown-gfm-get-corpus ()
4396 "Create corpus of recognized GFM code block languages for the given buffer."
4397 (let ((given-corpus (append markdown-gfm-additional-languages
4398 markdown-gfm-recognized-languages)))
4399 (append
4400 markdown-gfm-used-languages
4401 (if markdown-gfm-downcase-languages (cl-mapcar #'downcase given-corpus)
4402 given-corpus))))
4404 (defun markdown-gfm-add-used-language (lang)
4405 "Clean LANG and add to list of used languages."
4406 (setq markdown-gfm-used-languages
4407 (cons lang (remove lang markdown-gfm-used-languages))))
4409 (defcustom markdown-spaces-after-code-fence 1
4410 "Number of space characters to insert after a code fence.
4411 \\<gfm-mode-map>\\[markdown-insert-gfm-code-block] inserts this many spaces between an
4412 opening code fence and an info string."
4413 :group 'markdown
4414 :type 'integer
4415 :safe #'natnump
4416 :package-version '(markdown-mode . "2.3"))
4418 (defun markdown-insert-gfm-code-block (&optional lang edit)
4419 "Insert GFM code block for language LANG.
4420 If LANG is nil, the language will be queried from user. If a
4421 region is active, wrap this region with the markup instead. If
4422 the region boundaries are not on empty lines, these are added
4423 automatically in order to have the correct markup. When EDIT is
4424 non-nil (e.g., when \\[universal-argument] is given), edit the
4425 code block in an indirect buffer after insertion."
4426 (interactive
4427 (list (let ((completion-ignore-case nil))
4428 (condition-case nil
4429 (markdown-clean-language-string
4430 (completing-read
4431 "Programming language: "
4432 (markdown-gfm-get-corpus)
4433 nil 'confirm (car markdown-gfm-used-languages)
4434 'markdown-gfm-language-history))
4435 (quit "")))
4436 current-prefix-arg))
4437 (unless (string= lang "") (markdown-gfm-add-used-language lang))
4438 (when (> (length lang) 0)
4439 (setq lang (concat (make-string markdown-spaces-after-code-fence ?\s)
4440 lang)))
4441 (if (markdown-use-region-p)
4442 (let* ((b (region-beginning)) (e (region-end)) end
4443 (indent (progn (goto-char b) (current-indentation))))
4444 (goto-char e)
4445 ;; if we're on a blank line, don't newline, otherwise the ```
4446 ;; should go on its own line
4447 (unless (looking-back "\n" nil)
4448 (newline))
4449 (indent-to indent)
4450 (insert "```")
4451 (markdown-ensure-blank-line-after)
4452 (setq end (point))
4453 (goto-char b)
4454 ;; if we're on a blank line, insert the quotes here, otherwise
4455 ;; add a new line first
4456 (unless (looking-at-p "\n")
4457 (newline)
4458 (forward-line -1))
4459 (markdown-ensure-blank-line-before)
4460 (indent-to indent)
4461 (insert "```" lang)
4462 (markdown-syntax-propertize-fenced-block-constructs (point-at-bol) end))
4463 (let ((indent (current-indentation)) start-bol)
4464 (delete-horizontal-space :backward-only)
4465 (markdown-ensure-blank-line-before)
4466 (indent-to indent)
4467 (setq start-bol (point-at-bol))
4468 (insert "```" lang "\n")
4469 (indent-to indent)
4470 (unless edit (insert ?\n))
4471 (indent-to indent)
4472 (insert "```")
4473 (markdown-ensure-blank-line-after)
4474 (markdown-syntax-propertize-fenced-block-constructs start-bol (point)))
4475 (end-of-line 0)
4476 (when edit (markdown-edit-code-block))))
4478 (defun markdown-code-block-lang (&optional pos-prop)
4479 "Return the language name for a GFM or tilde fenced code block.
4480 The beginning of the block may be described by POS-PROP,
4481 a cons of (pos . prop) giving the position and property
4482 at the beginning of the block."
4483 (or pos-prop
4484 (setq pos-prop
4485 (markdown-max-of-seq
4486 #'car
4487 (cl-remove-if
4488 #'null
4489 (cl-mapcar
4490 #'markdown-find-previous-prop
4491 (markdown-get-fenced-block-begin-properties))))))
4492 (when pos-prop
4493 (goto-char (car pos-prop))
4494 (set-match-data (get-text-property (point) (cdr pos-prop)))
4495 ;; Note: Hard-coded group number assumes tilde
4496 ;; and GFM fenced code regexp groups agree.
4497 (let ((begin (match-beginning 3))
4498 (end (match-end 3)))
4499 (when (and begin end)
4500 ;; Fix language strings beginning with periods, like ".ruby".
4501 (when (eq (char-after begin) ?.)
4502 (setq begin (1+ begin)))
4503 (buffer-substring-no-properties begin end)))))
4505 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer)
4506 (with-current-buffer (or buffer (current-buffer))
4507 (save-excursion
4508 (goto-char (point-min))
4509 (cl-loop
4510 with prop = 'markdown-gfm-block-begin
4511 for pos-prop = (markdown-find-next-prop prop)
4512 while pos-prop
4513 for lang = (markdown-code-block-lang pos-prop)
4514 do (progn (when lang (markdown-gfm-add-used-language lang))
4515 (goto-char (next-single-property-change (point) prop)))))))
4518 ;;; Footnotes ==================================================================
4520 (defun markdown-footnote-counter-inc ()
4521 "Increment `markdown-footnote-counter' and return the new value."
4522 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
4523 (save-excursion
4524 (goto-char (point-min))
4525 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
4526 (point-max) t)
4527 (let ((fn (string-to-number (match-string 1))))
4528 (when (> fn markdown-footnote-counter)
4529 (setq markdown-footnote-counter fn))))))
4530 (cl-incf markdown-footnote-counter))
4532 (defun markdown-insert-footnote ()
4533 "Insert footnote with a new number and move point to footnote definition."
4534 (interactive)
4535 (let ((fn (markdown-footnote-counter-inc)))
4536 (insert (format "[^%d]" fn))
4537 (markdown-footnote-text-find-new-location)
4538 (markdown-ensure-blank-line-before)
4539 (unless (markdown-cur-line-blank-p)
4540 (insert "\n"))
4541 (insert (format "[^%d]: " fn))
4542 (markdown-ensure-blank-line-after)))
4544 (defun markdown-footnote-text-find-new-location ()
4545 "Position the point at the proper location for a new footnote text."
4546 (cond
4547 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
4548 ((eq markdown-footnote-location 'immediately) (markdown-end-of-text-block))
4549 ((eq markdown-footnote-location 'subtree) (markdown-end-of-subtree))
4550 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
4552 (defun markdown-footnote-kill ()
4553 "Kill the footnote at point.
4554 The footnote text is killed (and added to the kill ring), the
4555 footnote marker is deleted. Point has to be either at the
4556 footnote marker or in the footnote text."
4557 (interactive)
4558 (let ((marker-pos nil)
4559 (skip-deleting-marker nil)
4560 (starting-footnote-text-positions
4561 (markdown-footnote-text-positions)))
4562 (when starting-footnote-text-positions
4563 ;; We're starting in footnote text, so mark our return position and jump
4564 ;; to the marker if possible.
4565 (let ((marker-pos (markdown-footnote-find-marker
4566 (cl-first starting-footnote-text-positions))))
4567 (if marker-pos
4568 (goto-char (1- marker-pos))
4569 ;; If there isn't a marker, we still want to kill the text.
4570 (setq skip-deleting-marker t))))
4571 ;; Either we didn't start in the text, or we started in the text and jumped
4572 ;; to the marker. We want to assume we're at the marker now and error if
4573 ;; we're not.
4574 (unless skip-deleting-marker
4575 (let ((marker (markdown-footnote-delete-marker)))
4576 (unless marker
4577 (error "Not at a footnote"))
4578 ;; Even if we knew the text position before, it changed when we deleted
4579 ;; the label.
4580 (setq marker-pos (cl-second marker))
4581 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker))))
4582 (unless new-text-pos
4583 (error "No text for footnote `%s'" (cl-first marker)))
4584 (goto-char new-text-pos))))
4585 (let ((pos (markdown-footnote-kill-text)))
4586 (goto-char (if starting-footnote-text-positions
4588 marker-pos)))))
4590 (defun markdown-footnote-delete-marker ()
4591 "Delete a footnote marker at point.
4592 Returns a list (ID START) containing the footnote ID and the
4593 start position of the marker before deletion. If no footnote
4594 marker was deleted, this function returns NIL."
4595 (let ((marker (markdown-footnote-marker-positions)))
4596 (when marker
4597 (delete-region (cl-second marker) (cl-third marker))
4598 (butlast marker))))
4600 (defun markdown-footnote-kill-text ()
4601 "Kill footnote text at point.
4602 Returns the start position of the footnote text before deletion,
4603 or NIL if point was not inside a footnote text.
4605 The killed text is placed in the kill ring (without the footnote
4606 number)."
4607 (let ((fn (markdown-footnote-text-positions)))
4608 (when fn
4609 (let ((text (delete-and-extract-region (cl-second fn) (cl-third fn))))
4610 (string-match (concat "\\[\\" (cl-first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
4611 (kill-new (match-string 1 text))
4612 (when (and (markdown-cur-line-blank-p)
4613 (markdown-prev-line-blank-p)
4614 (not (bobp)))
4615 (delete-region (1- (point)) (point)))
4616 (cl-second fn)))))
4618 (defun markdown-footnote-goto-text ()
4619 "Jump to the text of the footnote at point."
4620 (interactive)
4621 (let ((fn (car (markdown-footnote-marker-positions))))
4622 (unless fn
4623 (user-error "Not at a footnote marker"))
4624 (let ((new-pos (markdown-footnote-find-text fn)))
4625 (unless new-pos
4626 (error "No definition found for footnote `%s'" fn))
4627 (goto-char new-pos))))
4629 (defun markdown-footnote-return ()
4630 "Return from a footnote to its footnote number in the main text."
4631 (interactive)
4632 (let ((fn (save-excursion
4633 (car (markdown-footnote-text-positions)))))
4634 (unless fn
4635 (user-error "Not in a footnote"))
4636 (let ((new-pos (markdown-footnote-find-marker fn)))
4637 (unless new-pos
4638 (error "Footnote marker `%s' not found" fn))
4639 (goto-char new-pos))))
4641 (defun markdown-footnote-find-marker (id)
4642 "Find the location of the footnote marker with ID.
4643 The actual buffer position returned is the position directly
4644 following the marker's closing bracket. If no marker is found,
4645 NIL is returned."
4646 (save-excursion
4647 (goto-char (point-min))
4648 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
4649 (skip-chars-backward "^]")
4650 (point))))
4652 (defun markdown-footnote-find-text (id)
4653 "Find the location of the text of footnote ID.
4654 The actual buffer position returned is the position of the first
4655 character of the text, after the footnote's identifier. If no
4656 footnote text is found, NIL is returned."
4657 (save-excursion
4658 (goto-char (point-min))
4659 (when (re-search-forward (concat "^ \\{0,3\\}\\[" id "\\]:") nil t)
4660 (skip-chars-forward "[ \t]")
4661 (point))))
4663 (defun markdown-footnote-marker-positions ()
4664 "Return the position and ID of the footnote marker point is on.
4665 The return value is a list (ID START END). If point is not on a
4666 footnote, NIL is returned."
4667 ;; first make sure we're at a footnote marker
4668 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
4669 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
4670 (save-excursion
4671 ;; move point between [ and ^:
4672 (if (looking-at-p "\\[")
4673 (forward-char 1)
4674 (skip-chars-backward "^["))
4675 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
4676 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
4678 (defun markdown-footnote-text-positions ()
4679 "Return the start and end positions of the footnote text point is in.
4680 The exact return value is a list of three elements: (ID START END).
4681 The start position is the position of the opening bracket
4682 of the footnote id. The end position is directly after the
4683 newline that ends the footnote. If point is not in a footnote,
4684 NIL is returned instead."
4685 (save-excursion
4686 (let (result)
4687 (move-beginning-of-line 1)
4688 ;; Try to find the label. If we haven't found the label and we're at a blank
4689 ;; or indented line, back up if possible.
4690 (while (and
4691 (not (and (looking-at markdown-regex-footnote-definition)
4692 (setq result (list (match-string 1) (point)))))
4693 (and (not (bobp))
4694 (or (markdown-cur-line-blank-p)
4695 (>= (current-indentation) 4))))
4696 (forward-line -1))
4697 (when result
4698 ;; Advance if there is a next line that is either blank or indented.
4699 ;; (Need to check if we're on the last line, because
4700 ;; markdown-next-line-blank-p returns true for last line in buffer.)
4701 (while (and (/= (line-end-position) (point-max))
4702 (or (markdown-next-line-blank-p)
4703 (>= (markdown-next-line-indent) 4)))
4704 (forward-line))
4705 ;; Move back while the current line is blank.
4706 (while (markdown-cur-line-blank-p)
4707 (forward-line -1))
4708 ;; Advance to capture this line and a single trailing newline (if there
4709 ;; is one).
4710 (forward-line)
4711 (append result (list (point)))))))
4714 ;;; Element Removal ===========================================================
4716 (defun markdown-kill-thing-at-point ()
4717 "Kill thing at point and add important text, without markup, to kill ring.
4718 Possible things to kill include (roughly in order of precedence):
4719 inline code, headers, horizonal rules, links (add link text to
4720 kill ring), images (add alt text to kill ring), angle uri, email
4721 addresses, bold, italics, reference definition (add URI to kill
4722 ring), footnote markers and text (kill both marker and text, add
4723 text to kill ring), and list items."
4724 (interactive "*")
4725 (let (val)
4726 (cond
4727 ;; Inline code
4728 ((markdown-inline-code-at-point)
4729 (kill-new (match-string 2))
4730 (delete-region (match-beginning 0) (match-end 0)))
4731 ;; ATX header
4732 ((thing-at-point-looking-at markdown-regex-header-atx)
4733 (kill-new (match-string 2))
4734 (delete-region (match-beginning 0) (match-end 0)))
4735 ;; Setext header
4736 ((thing-at-point-looking-at markdown-regex-header-setext)
4737 (kill-new (match-string 1))
4738 (delete-region (match-beginning 0) (match-end 0)))
4739 ;; Horizonal rule
4740 ((thing-at-point-looking-at markdown-regex-hr)
4741 (kill-new (match-string 0))
4742 (delete-region (match-beginning 0) (match-end 0)))
4743 ;; Inline link or image (add link or alt text to kill ring)
4744 ((thing-at-point-looking-at markdown-regex-link-inline)
4745 (kill-new (match-string 3))
4746 (delete-region (match-beginning 0) (match-end 0)))
4747 ;; Reference link or image (add link or alt text to kill ring)
4748 ((thing-at-point-looking-at markdown-regex-link-reference)
4749 (kill-new (match-string 3))
4750 (delete-region (match-beginning 0) (match-end 0)))
4751 ;; Angle URI (add URL to kill ring)
4752 ((thing-at-point-looking-at markdown-regex-angle-uri)
4753 (kill-new (match-string 2))
4754 (delete-region (match-beginning 0) (match-end 0)))
4755 ;; Email address in angle brackets (add email address to kill ring)
4756 ((thing-at-point-looking-at markdown-regex-email)
4757 (kill-new (match-string 1))
4758 (delete-region (match-beginning 0) (match-end 0)))
4759 ;; Wiki link (add alias text to kill ring)
4760 ((and markdown-enable-wiki-links
4761 (thing-at-point-looking-at markdown-regex-wiki-link))
4762 (kill-new (markdown-wiki-link-alias))
4763 (delete-region (match-beginning 1) (match-end 1)))
4764 ;; Bold
4765 ((thing-at-point-looking-at markdown-regex-bold)
4766 (kill-new (match-string 4))
4767 (delete-region (match-beginning 2) (match-end 2)))
4768 ;; Italics
4769 ((thing-at-point-looking-at markdown-regex-italic)
4770 (kill-new (match-string 3))
4771 (delete-region (match-beginning 1) (match-end 1)))
4772 ;; Strikethrough
4773 ((thing-at-point-looking-at markdown-regex-strike-through)
4774 (kill-new (match-string 4))
4775 (delete-region (match-beginning 2) (match-end 2)))
4776 ;; Footnote marker (add footnote text to kill ring)
4777 ((thing-at-point-looking-at markdown-regex-footnote)
4778 (markdown-footnote-kill))
4779 ;; Footnote text (add footnote text to kill ring)
4780 ((setq val (markdown-footnote-text-positions))
4781 (markdown-footnote-kill))
4782 ;; Reference definition (add URL to kill ring)
4783 ((thing-at-point-looking-at markdown-regex-reference-definition)
4784 (kill-new (match-string 5))
4785 (delete-region (match-beginning 0) (match-end 0)))
4786 ;; List item
4787 ((setq val (markdown-cur-list-item-bounds))
4788 (kill-new (delete-and-extract-region (cl-first val) (cl-second val))))
4790 (user-error "Nothing found at point to kill")))))
4793 ;;; Indentation ====================================================================
4795 (defun markdown-indent-find-next-position (cur-pos positions)
4796 "Return the position after the index of CUR-POS in POSITIONS.
4797 Positions are calculated by `markdown-calc-indents'."
4798 (while (and positions
4799 (not (equal cur-pos (car positions))))
4800 (setq positions (cdr positions)))
4801 (or (cadr positions) 0))
4803 (define-obsolete-function-alias 'markdown-exdent-find-next-position
4804 'markdown-outdent-find-next-position "v2.3")
4806 (defun markdown-outdent-find-next-position (cur-pos positions)
4807 "Return the maximal element that precedes CUR-POS from POSITIONS.
4808 Positions are calculated by `markdown-calc-indents'."
4809 (let ((result 0))
4810 (dolist (i positions)
4811 (when (< i cur-pos)
4812 (setq result (max result i))))
4813 result))
4815 (defun markdown-indent-line ()
4816 "Indent the current line using some heuristics.
4817 If the _previous_ command was either `markdown-enter-key' or
4818 `markdown-cycle', then we should cycle to the next
4819 reasonable indentation position. Otherwise, we could have been
4820 called directly by `markdown-enter-key', by an initial call of
4821 `markdown-cycle', or indirectly by `auto-fill-mode'. In
4822 these cases, indent to the default position.
4823 Positions are calculated by `markdown-calc-indents'."
4824 (interactive)
4825 (let ((positions (markdown-calc-indents))
4826 (point-pos (current-column))
4827 (_ (back-to-indentation))
4828 (cur-pos (current-column)))
4829 (if (not (equal this-command 'markdown-cycle))
4830 (indent-line-to (car positions))
4831 (setq positions (sort (delete-dups positions) '<))
4832 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions))
4833 (new-point-pos (max (+ point-pos (- next-pos cur-pos)) 0)))
4834 (indent-line-to next-pos)
4835 (move-to-column new-point-pos)))))
4837 (defun markdown-calc-indents ()
4838 "Return a list of indentation columns to cycle through.
4839 The first element in the returned list should be considered the
4840 default indentation level. This function does not worry about
4841 duplicate positions, which are handled up by calling functions."
4842 (let (pos prev-line-pos positions)
4844 ;; Indentation of previous line
4845 (setq prev-line-pos (markdown-prev-line-indent))
4846 (setq positions (cons prev-line-pos positions))
4848 ;; Indentation of previous non-list-marker text
4849 (when (setq pos (save-excursion
4850 (forward-line -1)
4851 (when (looking-at markdown-regex-list)
4852 (- (match-end 3) (match-beginning 0)))))
4853 (setq positions (cons pos positions)))
4855 ;; Indentation required for a pre block in current context
4856 (setq pos (length (markdown-pre-indentation (point))))
4857 (setq positions (cons pos positions))
4859 ;; Indentation of the previous line + tab-width
4860 (if prev-line-pos
4861 (setq positions (cons (+ prev-line-pos tab-width) positions))
4862 (setq positions (cons tab-width positions)))
4864 ;; Indentation of the previous line - tab-width
4865 (if (and prev-line-pos (> prev-line-pos tab-width))
4866 (setq positions (cons (- prev-line-pos tab-width) positions)))
4868 ;; Indentation of all preceeding list markers (when in a list)
4869 (when (setq pos (markdown-calculate-list-levels))
4870 (setq positions (append pos positions)))
4872 ;; First column
4873 (setq positions (cons 0 positions))
4875 ;; Return reversed list
4876 (reverse positions)))
4878 (defun markdown-enter-key ()
4879 "Handle RET depending on the context.
4880 If the point is at a table, move to the next row. Otherwise,
4881 indent according to value of `markdown-indent-on-enter'.
4882 When it is nil, simply call `newline'. Otherwise, indent the next line
4883 following RET using `markdown-indent-line'. Furthermore, when it
4884 is set to 'indent-and-new-item and the point is in a list item,
4885 start a new item with the same indentation. If the point is in an
4886 empty list item, remove it (so that pressing RET twice when in a
4887 list simply adds a blank line)."
4888 (interactive)
4889 (cond
4890 ;; Table
4891 ((markdown-table-at-point-p)
4892 (call-interactively #'markdown-table-next-row))
4893 ;; Indent non-table text
4894 (markdown-indent-on-enter
4895 (let (bounds)
4896 (if (and (memq markdown-indent-on-enter '(indent-and-new-item))
4897 (setq bounds (markdown-cur-list-item-bounds)))
4898 (let ((beg (cl-first bounds))
4899 (end (cl-second bounds))
4900 (length (cl-fourth bounds)))
4901 ;; Point is in a list item
4902 (if (= (- end beg) length)
4903 ;; Delete blank list
4904 (progn
4905 (delete-region beg end)
4906 (newline)
4907 (markdown-indent-line))
4908 (call-interactively #'markdown-insert-list-item)))
4909 ;; Point is not in a list
4910 (newline)
4911 (markdown-indent-line))))
4912 ;; Insert a raw newline
4913 (t (newline))))
4915 (define-obsolete-function-alias 'markdown-exdent-or-delete
4916 'markdown-outdent-or-delete "v2.3")
4918 (defun markdown-outdent-or-delete (arg)
4919 "Handle BACKSPACE by cycling through indentation points.
4920 When BACKSPACE is pressed, if there is only whitespace
4921 before the current point, then outdent the line one level.
4922 Otherwise, do normal delete by repeating
4923 `backward-delete-char-untabify' ARG times."
4924 (interactive "*p")
4925 (if (use-region-p)
4926 (backward-delete-char-untabify arg)
4927 (let ((cur-pos (current-column))
4928 (start-of-indention (save-excursion
4929 (back-to-indentation)
4930 (current-column)))
4931 (positions (markdown-calc-indents)))
4932 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
4933 (indent-line-to (markdown-outdent-find-next-position cur-pos positions))
4934 (backward-delete-char-untabify arg)))))
4936 (defun markdown-find-leftmost-column (beg end)
4937 "Find the leftmost column in the region from BEG to END."
4938 (let ((mincol 1000))
4939 (save-excursion
4940 (goto-char beg)
4941 (while (< (point) end)
4942 (back-to-indentation)
4943 (unless (looking-at-p "[ \t]*$")
4944 (setq mincol (min mincol (current-column))))
4945 (forward-line 1)
4947 mincol))
4949 (defun markdown-indent-region (beg end arg)
4950 "Indent the region from BEG to END using some heuristics.
4951 When ARG is non-nil, outdent the region instead.
4952 See `markdown-indent-line' and `markdown-indent-line'."
4953 (interactive "*r\nP")
4954 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
4955 (leftmostcol (markdown-find-leftmost-column beg end))
4956 (next-pos (if arg
4957 (markdown-outdent-find-next-position leftmostcol positions)
4958 (markdown-indent-find-next-position leftmostcol positions))))
4959 (indent-rigidly beg end (- next-pos leftmostcol))
4960 (setq deactivate-mark nil)))
4962 (define-obsolete-function-alias 'markdown-exdent-region
4963 'markdown-outdent-region "v2.3")
4965 (defun markdown-outdent-region (beg end)
4966 "Call `markdown-indent-region' on region from BEG to END with prefix."
4967 (interactive "*r")
4968 (markdown-indent-region beg end t))
4971 ;;; Markup Completion =========================================================
4973 (defconst markdown-complete-alist
4974 '((markdown-regex-header-atx . markdown-complete-atx)
4975 (markdown-regex-header-setext . markdown-complete-setext)
4976 (markdown-regex-hr . markdown-complete-hr))
4977 "Association list of form (regexp . function) for markup completion.")
4979 (defun markdown-incomplete-atx-p ()
4980 "Return t if ATX header markup is incomplete and nil otherwise.
4981 Assumes match data is available for `markdown-regex-header-atx'.
4982 Checks that the number of trailing hash marks equals the number of leading
4983 hash marks, that there is only a single space before and after the text,
4984 and that there is no extraneous whitespace in the text."
4986 ;; Number of starting and ending hash marks differs
4987 (not (= (length (match-string 1)) (length (match-string 3))))
4988 ;; When the header text is not empty...
4989 (and (> (length (match-string 2)) 0)
4990 ;; ...if there are extra leading, trailing, or interior spaces
4991 (or (not (= (match-beginning 2) (1+ (match-end 1))))
4992 (not (= (match-beginning 3) (1+ (match-end 2))))
4993 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
4994 ;; When the header text is empty...
4995 (and (= (length (match-string 2)) 0)
4996 ;; ...if there are too many or too few spaces
4997 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
4999 (defun markdown-complete-atx ()
5000 "Complete and normalize ATX headers.
5001 Add or remove hash marks to the end of the header to match the
5002 beginning. Ensure that there is only a single space between hash
5003 marks and header text. Removes extraneous whitespace from header text.
5004 Assumes match data is available for `markdown-regex-header-atx'.
5005 Return nil if markup was complete and non-nil if markup was completed."
5006 (when (markdown-incomplete-atx-p)
5007 (let* ((new-marker (make-marker))
5008 (new-marker (set-marker new-marker (match-end 2))))
5009 ;; Hash marks and spacing at end
5010 (goto-char (match-end 2))
5011 (delete-region (match-end 2) (match-end 3))
5012 (insert " " (match-string 1))
5013 ;; Remove extraneous whitespace from title
5014 (replace-match (markdown-compress-whitespace-string (match-string 2))
5015 t t nil 2)
5016 ;; Spacing at beginning
5017 (goto-char (match-end 1))
5018 (delete-region (match-end 1) (match-beginning 2))
5019 (insert " ")
5020 ;; Leave point at end of text
5021 (goto-char new-marker))))
5023 (defun markdown-incomplete-setext-p ()
5024 "Return t if setext header markup is incomplete and nil otherwise.
5025 Assumes match data is available for `markdown-regex-header-setext'.
5026 Checks that length of underline matches text and that there is no
5027 extraneous whitespace in the text."
5028 (or (not (= (length (match-string 1)) (length (match-string 2))))
5029 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
5031 (defun markdown-complete-setext ()
5032 "Complete and normalize setext headers.
5033 Add or remove underline characters to match length of header
5034 text. Removes extraneous whitespace from header text. Assumes
5035 match data is available for `markdown-regex-header-setext'.
5036 Return nil if markup was complete and non-nil if markup was completed."
5037 (when (markdown-incomplete-setext-p)
5038 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
5039 (char (char-after (match-beginning 2)))
5040 (level (if (char-equal char ?-) 2 1)))
5041 (goto-char (match-beginning 0))
5042 (delete-region (match-beginning 0) (match-end 0))
5043 (markdown-insert-header level text t)
5044 t)))
5046 (defun markdown-incomplete-hr-p ()
5047 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
5048 Assumes match data is available for `markdown-regex-hr'."
5049 (not (member (match-string 0) markdown-hr-strings)))
5051 (defun markdown-complete-hr ()
5052 "Complete horizontal rules.
5053 If horizontal rule string is a member of `markdown-hr-strings',
5054 do nothing. Otherwise, replace with the car of
5055 `markdown-hr-strings'.
5056 Assumes match data is available for `markdown-regex-hr'.
5057 Return nil if markup was complete and non-nil if markup was completed."
5058 (when (markdown-incomplete-hr-p)
5059 (replace-match (car markdown-hr-strings))
5062 (defun markdown-complete ()
5063 "Complete markup of object near point or in region when active.
5064 Handle all objects in `markdown-complete-alist', in order.
5065 See `markdown-complete-at-point' and `markdown-complete-region'."
5066 (interactive "*")
5067 (if (markdown-use-region-p)
5068 (markdown-complete-region (region-beginning) (region-end))
5069 (markdown-complete-at-point)))
5071 (defun markdown-complete-at-point ()
5072 "Complete markup of object near point.
5073 Handle all elements of `markdown-complete-alist' in order."
5074 (interactive "*")
5075 (let ((list markdown-complete-alist) found changed)
5076 (while list
5077 (let ((regexp (eval (caar list)))
5078 (function (cdar list)))
5079 (setq list (cdr list))
5080 (when (thing-at-point-looking-at regexp)
5081 (setq found t)
5082 (setq changed (funcall function))
5083 (setq list nil))))
5084 (if found
5085 (or changed (user-error "Markup at point is complete"))
5086 (user-error "Nothing to complete at point"))))
5088 (defun markdown-complete-region (beg end)
5089 "Complete markup of objects in region from BEG to END.
5090 Handle all objects in `markdown-complete-alist', in order. Each
5091 match is checked to ensure that a previous regexp does not also
5092 match."
5093 (interactive "*r")
5094 (let ((end-marker (set-marker (make-marker) end))
5095 previous)
5096 (dolist (element markdown-complete-alist)
5097 (let ((regexp (eval (car element)))
5098 (function (cdr element)))
5099 (goto-char beg)
5100 (while (re-search-forward regexp end-marker 'limit)
5101 (when (match-string 0)
5102 ;; Make sure this is not a match for any of the preceding regexps.
5103 ;; This prevents mistaking an HR for a Setext subheading.
5104 (let (match)
5105 (save-match-data
5106 (dolist (prev-regexp previous)
5107 (or match (setq match (looking-back prev-regexp nil)))))
5108 (unless match
5109 (save-excursion (funcall function))))))
5110 (cl-pushnew regexp previous :test #'equal)))
5111 previous))
5113 (defun markdown-complete-buffer ()
5114 "Complete markup for all objects in the current buffer."
5115 (interactive "*")
5116 (markdown-complete-region (point-min) (point-max)))
5119 ;;; Markup Cycling ============================================================
5121 (defun markdown-cycle-atx (arg &optional remove)
5122 "Cycle ATX header markup.
5123 Promote header (decrease level) when ARG is 1 and demote
5124 header (increase level) if arg is -1. When REMOVE is non-nil,
5125 remove the header when the level reaches zero and stop cycling
5126 when it reaches six. Otherwise, perform a proper cycling through
5127 levels one through six. Assumes match data is available for
5128 `markdown-regex-header-atx'."
5129 (let* ((old-level (length (match-string 1)))
5130 (new-level (+ old-level arg))
5131 (text (match-string 2)))
5132 (when (not remove)
5133 (setq new-level (% new-level 6))
5134 (setq new-level (cond ((= new-level 0) 6)
5135 ((< new-level 0) (+ new-level 6))
5136 (t new-level))))
5137 (cond
5138 ((= new-level 0)
5139 (markdown-unwrap-thing-at-point nil 0 2))
5140 ((<= new-level 6)
5141 (goto-char (match-beginning 0))
5142 (delete-region (match-beginning 0) (match-end 0))
5143 (markdown-insert-header new-level text nil)))))
5145 (defun markdown-cycle-setext (arg &optional remove)
5146 "Cycle setext header markup.
5147 Promote header (increase level) when ARG is 1 and demote
5148 header (decrease level or remove) if arg is -1. When demoting a
5149 level-two setext header, replace with a level-three atx header.
5150 When REMOVE is non-nil, remove the header when the level reaches
5151 zero. Otherwise, cycle back to a level six atx header. Assumes
5152 match data is available for `markdown-regex-header-setext'."
5153 (let* ((char (char-after (match-beginning 2)))
5154 (old-level (if (char-equal char ?=) 1 2))
5155 (new-level (+ old-level arg)))
5156 (when (and (not remove) (= new-level 0))
5157 (setq new-level 6))
5158 (cond
5159 ((= new-level 0)
5160 (markdown-unwrap-thing-at-point nil 0 1))
5161 ((<= new-level 2)
5162 (markdown-insert-header new-level nil t))
5163 ((<= new-level 6)
5164 (markdown-insert-header new-level nil nil)))))
5166 (defun markdown-cycle-hr (arg &optional remove)
5167 "Cycle string used for horizontal rule from `markdown-hr-strings'.
5168 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
5169 backwards (promote). When REMOVE is non-nil, remove the hr instead
5170 of cycling when the end of the list is reached.
5171 Assumes match data is available for `markdown-regex-hr'."
5172 (let* ((strings (if (= arg -1)
5173 (reverse markdown-hr-strings)
5174 markdown-hr-strings))
5175 (tail (member (match-string 0) strings))
5176 (new (or (cadr tail)
5177 (if remove
5178 (if (= arg 1)
5180 (car tail))
5181 (car strings)))))
5182 (replace-match new)))
5184 (defun markdown-cycle-bold ()
5185 "Cycle bold markup between underscores and asterisks.
5186 Assumes match data is available for `markdown-regex-bold'."
5187 (save-excursion
5188 (let* ((old-delim (match-string 3))
5189 (new-delim (if (string-equal old-delim "**") "__" "**")))
5190 (replace-match new-delim t t nil 3)
5191 (replace-match new-delim t t nil 5))))
5193 (defun markdown-cycle-italic ()
5194 "Cycle italic markup between underscores and asterisks.
5195 Assumes match data is available for `markdown-regex-italic'."
5196 (save-excursion
5197 (let* ((old-delim (match-string 2))
5198 (new-delim (if (string-equal old-delim "*") "_" "*")))
5199 (replace-match new-delim t t nil 2)
5200 (replace-match new-delim t t nil 4))))
5203 ;;; Keymap ====================================================================
5205 (defun markdown--style-map-prompt ()
5206 "Return a formatted prompt for Markdown markup insertion."
5207 (when markdown-enable-prefix-prompts
5208 (concat
5209 "Markdown: "
5210 (propertize "bold" 'face 'markdown-bold-face) ", "
5211 (propertize "italic" 'face 'markdown-italic-face) ", "
5212 (propertize "code" 'face 'markdown-inline-code-face) ", "
5213 (propertize "C = GFM code" 'face 'markdown-code-face) ", "
5214 (propertize "pre" 'face 'markdown-pre-face) ", "
5215 (propertize "footnote" 'face 'markdown-footnote-text-face) ", "
5216 (propertize "q = blockquote" 'face 'markdown-blockquote-face) ", "
5217 (propertize "h & 1-6 = heading" 'face 'markdown-header-face) ", "
5218 (propertize "- = hr" 'face 'markdown-hr-face) ", "
5219 "C-h = more")))
5221 (defun markdown--command-map-prompt ()
5222 "Return prompt for Markdown buffer-wide commands."
5223 (when markdown-enable-prefix-prompts
5224 (concat
5225 "Command: "
5226 (propertize "m" 'face 'markdown-bold-face) "arkdown, "
5227 (propertize "p" 'face 'markdown-bold-face) "review, "
5228 (propertize "o" 'face 'markdown-bold-face) "pen, "
5229 (propertize "e" 'face 'markdown-bold-face) "xport, "
5230 "export & pre" (propertize "v" 'face 'markdown-bold-face) "iew, "
5231 (propertize "c" 'face 'markdown-bold-face) "heck refs, "
5232 "C-h = more")))
5234 (defvar markdown-mode-style-map
5235 (let ((map (make-keymap (markdown--style-map-prompt))))
5236 (define-key map (kbd "1") 'markdown-insert-header-atx-1)
5237 (define-key map (kbd "2") 'markdown-insert-header-atx-2)
5238 (define-key map (kbd "3") 'markdown-insert-header-atx-3)
5239 (define-key map (kbd "4") 'markdown-insert-header-atx-4)
5240 (define-key map (kbd "5") 'markdown-insert-header-atx-5)
5241 (define-key map (kbd "6") 'markdown-insert-header-atx-6)
5242 (define-key map (kbd "!") 'markdown-insert-header-setext-1)
5243 (define-key map (kbd "@") 'markdown-insert-header-setext-2)
5244 (define-key map (kbd "b") 'markdown-insert-bold)
5245 (define-key map (kbd "c") 'markdown-insert-code)
5246 (define-key map (kbd "C") 'markdown-insert-gfm-code-block)
5247 (define-key map (kbd "f") 'markdown-insert-footnote)
5248 (define-key map (kbd "h") 'markdown-insert-header-dwim)
5249 (define-key map (kbd "H") 'markdown-insert-header-setext-dwim)
5250 (define-key map (kbd "i") 'markdown-insert-italic)
5251 (define-key map (kbd "k") 'markdown-insert-kbd)
5252 (define-key map (kbd "l") 'markdown-insert-link)
5253 (define-key map (kbd "p") 'markdown-insert-pre)
5254 (define-key map (kbd "P") 'markdown-pre-region)
5255 (define-key map (kbd "q") 'markdown-insert-blockquote)
5256 (define-key map (kbd "s") 'markdown-insert-strike-through)
5257 (define-key map (kbd "Q") 'markdown-blockquote-region)
5258 (define-key map (kbd "w") 'markdown-insert-wiki-link)
5259 (define-key map (kbd "-") 'markdown-insert-hr)
5260 (define-key map (kbd "[") 'markdown-insert-gfm-checkbox)
5261 ;; Deprecated keys that may be removed in a future version
5262 (define-key map (kbd "e") 'markdown-insert-italic)
5263 map)
5264 "Keymap for Markdown text styling commands.")
5266 (defvar markdown-mode-command-map
5267 (let ((map (make-keymap (markdown--command-map-prompt))))
5268 (define-key map (kbd "m") 'markdown-other-window)
5269 (define-key map (kbd "p") 'markdown-preview)
5270 (define-key map (kbd "e") 'markdown-export)
5271 (define-key map (kbd "v") 'markdown-export-and-preview)
5272 (define-key map (kbd "o") 'markdown-open)
5273 (define-key map (kbd "l") 'markdown-live-preview-mode)
5274 (define-key map (kbd "w") 'markdown-kill-ring-save)
5275 (define-key map (kbd "c") 'markdown-check-refs)
5276 (define-key map (kbd "n") 'markdown-cleanup-list-numbers)
5277 (define-key map (kbd "]") 'markdown-complete-buffer)
5278 (define-key map (kbd "^") 'markdown-table-sort-lines)
5279 (define-key map (kbd "|") 'markdown-table-convert-region)
5280 (define-key map (kbd "t") 'markdown-table-transpose)
5281 map)
5282 "Keymap for Markdown buffer-wide commands.")
5284 (defvar markdown-mode-map
5285 (let ((map (make-keymap)))
5286 ;; Markup insertion & removal
5287 (define-key map (kbd "C-c C-s") markdown-mode-style-map)
5288 (define-key map (kbd "C-c C-l") 'markdown-insert-link)
5289 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
5290 ;; Promotion, demotion, and cycling
5291 (define-key map (kbd "C-c C--") 'markdown-promote)
5292 (define-key map (kbd "C-c C-=") 'markdown-demote)
5293 (define-key map (kbd "C-c C-]") 'markdown-complete)
5294 ;; Following and doing things
5295 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
5296 (define-key map (kbd "C-c C-d") 'markdown-do)
5297 (define-key map (kbd "C-c '") 'markdown-edit-code-block)
5298 ;; Indentation
5299 (define-key map (kbd "C-m") 'markdown-enter-key)
5300 (define-key map (kbd "DEL") 'markdown-outdent-or-delete)
5301 (define-key map (kbd "C-c >") 'markdown-indent-region)
5302 (define-key map (kbd "C-c <") 'markdown-outdent-region)
5303 ;; Visibility cycling
5304 (define-key map (kbd "TAB") 'markdown-cycle)
5305 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
5306 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
5307 (define-key map (kbd "<backtab>") 'markdown-shifttab)
5308 ;; Heading and list navigation
5309 (define-key map (kbd "C-c C-n") 'markdown-outline-next)
5310 (define-key map (kbd "C-c C-p") 'markdown-outline-previous)
5311 (define-key map (kbd "C-c C-f") 'markdown-outline-next-same-level)
5312 (define-key map (kbd "C-c C-b") 'markdown-outline-previous-same-level)
5313 (define-key map (kbd "C-c C-u") 'markdown-outline-up)
5314 ;; Buffer-wide commands
5315 (define-key map (kbd "C-c C-c") markdown-mode-command-map)
5316 ;; Subtree, list, and table editing
5317 (define-key map (kbd "C-c <up>") 'markdown-move-up)
5318 (define-key map (kbd "C-c <down>") 'markdown-move-down)
5319 (define-key map (kbd "C-c <left>") 'markdown-promote)
5320 (define-key map (kbd "C-c <right>") 'markdown-demote)
5321 (define-key map (kbd "C-c S-<up>") 'markdown-table-delete-row)
5322 (define-key map (kbd "C-c S-<down>") 'markdown-table-insert-row)
5323 (define-key map (kbd "C-c S-<left>") 'markdown-table-delete-column)
5324 (define-key map (kbd "C-c S-<right>") 'markdown-table-insert-column)
5325 (define-key map (kbd "C-c C-M-h") 'markdown-mark-subtree)
5326 (define-key map (kbd "C-x n s") 'markdown-narrow-to-subtree)
5327 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
5328 (define-key map (kbd "C-c C-j") 'markdown-insert-list-item)
5329 ;; Paragraphs (Markdown context aware)
5330 (define-key map [remap backward-paragraph] 'markdown-backward-paragraph)
5331 (define-key map [remap forward-paragraph] 'markdown-forward-paragraph)
5332 (define-key map [remap mark-paragraph] 'markdown-mark-paragraph)
5333 ;; Blocks (one or more paragraphs)
5334 (define-key map (kbd "C-M-{") 'markdown-backward-block)
5335 (define-key map (kbd "C-M-}") 'markdown-forward-block)
5336 (define-key map (kbd "C-c M-h") 'markdown-mark-block)
5337 (define-key map (kbd "C-x n b") 'markdown-narrow-to-block)
5338 ;; Pages (top-level sections)
5339 (define-key map [remap backward-page] 'markdown-backward-page)
5340 (define-key map [remap forward-page] 'markdown-forward-page)
5341 (define-key map [remap mark-page] 'markdown-mark-page)
5342 (define-key map [remap narrow-to-page] 'markdown-narrow-to-page)
5343 ;; Link Movement
5344 (define-key map (kbd "M-n") 'markdown-next-link)
5345 (define-key map (kbd "M-p") 'markdown-previous-link)
5346 ;; Toggling functionality
5347 (define-key map (kbd "C-c C-x C-e") 'markdown-toggle-math)
5348 (define-key map (kbd "C-c C-x C-f") 'markdown-toggle-fontify-code-blocks-natively)
5349 (define-key map (kbd "C-c C-x C-i") 'markdown-toggle-inline-images)
5350 (define-key map (kbd "C-c C-x C-l") 'markdown-toggle-url-hiding)
5351 (define-key map (kbd "C-c C-x C-m") 'markdown-toggle-markup-hiding)
5352 ;; Alternative keys (in case of problems with the arrow keys)
5353 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
5354 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
5355 (define-key map (kbd "C-c C-x l") 'markdown-promote)
5356 (define-key map (kbd "C-c C-x r") 'markdown-demote)
5357 ;; Deprecated keys that may be removed in a future version
5358 (define-key map (kbd "C-c C-a L") 'markdown-insert-link) ;; C-c C-l
5359 (define-key map (kbd "C-c C-a l") 'markdown-insert-link) ;; C-c C-l
5360 (define-key map (kbd "C-c C-a r") 'markdown-insert-link) ;; C-c C-l
5361 (define-key map (kbd "C-c C-a u") 'markdown-insert-uri) ;; C-c C-l
5362 (define-key map (kbd "C-c C-a f") 'markdown-insert-footnote)
5363 (define-key map (kbd "C-c C-a w") 'markdown-insert-wiki-link)
5364 (define-key map (kbd "C-c C-t 1") 'markdown-insert-header-atx-1)
5365 (define-key map (kbd "C-c C-t 2") 'markdown-insert-header-atx-2)
5366 (define-key map (kbd "C-c C-t 3") 'markdown-insert-header-atx-3)
5367 (define-key map (kbd "C-c C-t 4") 'markdown-insert-header-atx-4)
5368 (define-key map (kbd "C-c C-t 5") 'markdown-insert-header-atx-5)
5369 (define-key map (kbd "C-c C-t 6") 'markdown-insert-header-atx-6)
5370 (define-key map (kbd "C-c C-t !") 'markdown-insert-header-setext-1)
5371 (define-key map (kbd "C-c C-t @") 'markdown-insert-header-setext-2)
5372 (define-key map (kbd "C-c C-t h") 'markdown-insert-header-dwim)
5373 (define-key map (kbd "C-c C-t H") 'markdown-insert-header-setext-dwim)
5374 (define-key map (kbd "C-c C-t s") 'markdown-insert-header-setext-2)
5375 (define-key map (kbd "C-c C-t t") 'markdown-insert-header-setext-1)
5376 (define-key map (kbd "C-c C-i") 'markdown-insert-image)
5377 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item) ;; C-c C-j
5378 (define-key map (kbd "C-c C-x C-x") 'markdown-toggle-gfm-checkbox) ;; C-c C-d
5379 (define-key map (kbd "C-c -") 'markdown-insert-hr)
5380 map)
5381 "Keymap for Markdown major mode.")
5383 (defvar markdown-mode-mouse-map
5384 (let ((map (make-sparse-keymap)))
5385 (define-key map [follow-link] 'mouse-face)
5386 (define-key map [mouse-2] 'markdown-follow-link-at-point)
5387 map)
5388 "Keymap for following links with mouse.")
5390 (defvar gfm-mode-map
5391 (let ((map (make-sparse-keymap)))
5392 (set-keymap-parent map markdown-mode-map)
5393 (define-key map (kbd "C-c C-s d") 'markdown-insert-strike-through)
5394 (define-key map "`" 'markdown-electric-backquote)
5395 map)
5396 "Keymap for `gfm-mode'.
5397 See also `markdown-mode-map'.")
5400 ;;; Menu ==================================================================
5402 (easy-menu-define markdown-mode-menu markdown-mode-map
5403 "Menu for Markdown mode"
5404 '("Markdown"
5405 "---"
5406 ("Movement"
5407 ["Jump" markdown-do]
5408 ["Follow Link" markdown-follow-thing-at-point]
5409 ["Next Link" markdown-next-link]
5410 ["Previous Link" markdown-previous-link]
5411 "---"
5412 ["Next Heading or List Item" markdown-outline-next]
5413 ["Previous Heading or List Item" markdown-outline-previous]
5414 ["Next at Same Level" markdown-outline-next-same-level]
5415 ["Previous at Same Level" markdown-outline-previous-same-level]
5416 ["Up to Parent" markdown-outline-up]
5417 "---"
5418 ["Forward Paragraph" markdown-forward-paragraph]
5419 ["Backward Paragraph" markdown-backward-paragraph]
5420 ["Forward Block" markdown-forward-block]
5421 ["Backward Block" markdown-backward-block])
5422 ("Show & Hide"
5423 ["Cycle Heading Visibility" markdown-cycle (markdown-on-heading-p)]
5424 ["Cycle Heading Visibility (Global)" markdown-shifttab]
5425 "---"
5426 ["Narrow to Region" narrow-to-region]
5427 ["Narrow to Block" markdown-narrow-to-block]
5428 ["Narrow to Section" narrow-to-defun]
5429 ["Narrow to Subtree" markdown-narrow-to-subtree]
5430 ["Widen" widen (buffer-narrowed-p)]
5431 "---"
5432 ["Toggle Markup Hiding" markdown-toggle-markup-hiding
5433 :keys "C-c C-x C-m"
5434 :style radio
5435 :selected markdown-hide-markup])
5436 "---"
5437 ("Headings & Structure"
5438 ["Automatic Heading" markdown-insert-header-dwim :keys "C-c C-s h"]
5439 ["Automatic Heading (Setext)" markdown-insert-header-setext-dwim :keys "C-c C-s H"]
5440 ("Specific Heading (atx)"
5441 ["First Level atx" markdown-insert-header-atx-1 :keys "C-c C-s 1"]
5442 ["Second Level atx" markdown-insert-header-atx-2 :keys "C-c C-s 2"]
5443 ["Third Level atx" markdown-insert-header-atx-3 :keys "C-c C-s 3"]
5444 ["Fourth Level atx" markdown-insert-header-atx-4 :keys "C-c C-s 4"]
5445 ["Fifth Level atx" markdown-insert-header-atx-5 :keys "C-c C-s 5"]
5446 ["Sixth Level atx" markdown-insert-header-atx-6 :keys "C-c C-s 6"])
5447 ("Specific Heading (Setext)"
5448 ["First Level Setext" markdown-insert-header-setext-1 :keys "C-c C-s !"]
5449 ["Second Level Setext" markdown-insert-header-setext-2 :keys "C-c C-s @"])
5450 ["Horizontal Rule" markdown-insert-hr :keys "C-c C-s -"]
5451 "---"
5452 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
5453 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
5454 ["Promote Subtree" markdown-promote :keys "C-c <left>"]
5455 ["Demote Subtree" markdown-demote :keys "C-c <right>"])
5456 ("Region & Mark"
5457 ["Indent Region" markdown-indent-region]
5458 ["Outdent Region" markdown-outdent-region]
5459 "--"
5460 ["Mark Paragraph" mark-paragraph]
5461 ["Mark Block" markdown-mark-block]
5462 ["Mark Section" mark-defun]
5463 ["Mark Subtree" markdown-mark-subtree])
5464 ("Lists"
5465 ["Insert List Item" markdown-insert-list-item]
5466 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
5467 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
5468 ["Indent Subtree" markdown-demote :keys "C-c <right>"]
5469 ["Outdent Subtree" markdown-promote :keys "C-c <left>"]
5470 ["Renumber List" markdown-cleanup-list-numbers]
5471 ["Insert Task List Item" markdown-insert-gfm-checkbox :keys "C-c C-x ["]
5472 ["Toggle Task List Item" markdown-toggle-gfm-checkbox (markdown-gfm-task-list-item-at-point) :keys "C-c C-d"])
5473 ("Links & Images"
5474 ["Insert Link" markdown-insert-link]
5475 ["Insert Image" markdown-insert-image]
5476 ["Insert Footnote" markdown-insert-footnote :keys "C-c C-s f"]
5477 ["Insert Wiki Link" markdown-insert-wiki-link :keys "C-c C-s w"]
5478 "---"
5479 ["Check References" markdown-check-refs]
5480 ["Toggle URL Hiding" markdown-toggle-url-hiding
5481 :style radio
5482 :selected markdown-hide-urls]
5483 ["Toggle Inline Images" markdown-toggle-inline-images
5484 :keys "C-c C-x C-i"
5485 :style radio
5486 :selected markdown-inline-image-overlays]
5487 ["Toggle Wiki Links" markdown-toggle-wiki-links
5488 :style radio
5489 :selected markdown-enable-wiki-links])
5490 ("Styles"
5491 ["Bold" markdown-insert-bold]
5492 ["Italic" markdown-insert-italic]
5493 ["Code" markdown-insert-code]
5494 ["Strikethrough" markdown-insert-strike-through]
5495 ["Keyboard" markdown-insert-kbd]
5496 "---"
5497 ["Blockquote" markdown-insert-blockquote]
5498 ["Preformatted" markdown-insert-pre]
5499 ["GFM Code Block" markdown-insert-gfm-code-block]
5500 ["Edit Code Block" markdown-edit-code-block (markdown-code-block-at-point-p)]
5501 "---"
5502 ["Blockquote Region" markdown-blockquote-region]
5503 ["Preformatted Region" markdown-pre-region]
5504 "---"
5505 ["Fontify Code Blocks Natively" markdown-toggle-fontify-code-blocks-natively
5506 :style radio
5507 :selected markdown-fontify-code-blocks-natively]
5508 ["LaTeX Math Support" markdown-toggle-math
5509 :style radio
5510 :selected markdown-enable-math])
5511 "---"
5512 ("Preview & Export"
5513 ["Compile" markdown-other-window]
5514 ["Preview" markdown-preview]
5515 ["Export" markdown-export]
5516 ["Export & View" markdown-export-and-preview]
5517 ["Open" markdown-open]
5518 ["Live Export" markdown-live-preview-mode
5519 :style radio
5520 :selected markdown-live-preview-mode]
5521 ["Kill ring save" markdown-kill-ring-save])
5522 ("Markup Completion and Cycling"
5523 ["Complete Markup" markdown-complete]
5524 ["Promote Element" markdown-promote :keys "C-c C--"]
5525 ["Demote Element" markdown-demote :keys "C-c C-="])
5526 "---"
5527 ["Kill Element" markdown-kill-thing-at-point]
5528 "---"
5529 ("Documentation"
5530 ["Version" markdown-show-version]
5531 ["Homepage" markdown-mode-info]
5532 ["Describe Mode" (describe-function 'markdown-mode)]
5533 ["Guide" (browse-url "https://leanpub.com/markdown-mode")])))
5536 ;;; imenu =====================================================================
5538 (defun markdown-imenu-create-nested-index ()
5539 "Create and return a nested imenu index alist for the current buffer.
5540 See `imenu-create-index-function' and `imenu--index-alist' for details."
5541 (let* ((root '(nil . nil))
5542 cur-alist
5543 (cur-level 0)
5544 (empty-heading "-")
5545 (self-heading ".")
5546 hashes pos level heading)
5547 (save-excursion
5548 (goto-char (point-min))
5549 (while (re-search-forward markdown-regex-header (point-max) t)
5550 (unless (markdown-code-block-at-point-p)
5551 (cond
5552 ((match-string-no-properties 2) ;; level 1 setext
5553 (setq heading (match-string-no-properties 1))
5554 (setq pos (match-beginning 1)
5555 level 1))
5556 ((match-string-no-properties 3) ;; level 2 setext
5557 (setq heading (match-string-no-properties 1))
5558 (setq pos (match-beginning 1)
5559 level 2))
5560 ((setq hashes (markdown-trim-whitespace
5561 (match-string-no-properties 4)))
5562 (setq heading (match-string-no-properties 5)
5563 pos (match-beginning 4)
5564 level (length hashes))))
5565 (let ((alist (list (cons heading pos))))
5566 (cond
5567 ((= cur-level level) ; new sibling
5568 (setcdr cur-alist alist)
5569 (setq cur-alist alist))
5570 ((< cur-level level) ; first child
5571 (dotimes (_ (- level cur-level 1))
5572 (setq alist (list (cons empty-heading alist))))
5573 (if cur-alist
5574 (let* ((parent (car cur-alist))
5575 (self-pos (cdr parent)))
5576 (setcdr parent (cons (cons self-heading self-pos) alist)))
5577 (setcdr root alist)) ; primogenitor
5578 (setq cur-alist alist)
5579 (setq cur-level level))
5580 (t ; new sibling of an ancestor
5581 (let ((sibling-alist (last (cdr root))))
5582 (dotimes (_ (1- level))
5583 (setq sibling-alist (last (cdar sibling-alist))))
5584 (setcdr sibling-alist alist)
5585 (setq cur-alist alist))
5586 (setq cur-level level))))))
5587 (cdr root))))
5589 (defun markdown-imenu-create-flat-index ()
5590 "Create and return a flat imenu index alist for the current buffer.
5591 See `imenu-create-index-function' and `imenu--index-alist' for details."
5592 (let* ((empty-heading "-") index heading pos)
5593 (save-excursion
5594 (goto-char (point-min))
5595 (while (re-search-forward markdown-regex-header (point-max) t)
5596 (when (and (not (markdown-code-block-at-point-p))
5597 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin)))
5598 (cond
5599 ((setq heading (match-string-no-properties 1))
5600 (setq pos (match-beginning 1)))
5601 ((setq heading (match-string-no-properties 5))
5602 (setq pos (match-beginning 4))))
5603 (or (> (length heading) 0)
5604 (setq heading empty-heading))
5605 (setq index (append index (list (cons heading pos))))))
5606 index)))
5609 ;;; References ================================================================
5611 (defun markdown-reference-goto-definition ()
5612 "Jump to the definition of the reference at point or create it."
5613 (interactive)
5614 (when (thing-at-point-looking-at markdown-regex-link-reference)
5615 (let* ((text (match-string-no-properties 3))
5616 (reference (match-string-no-properties 6))
5617 (target (downcase (if (string= reference "") text reference)))
5618 (loc (cadr (save-match-data (markdown-reference-definition target)))))
5619 (if loc
5620 (goto-char loc)
5621 (goto-char (match-beginning 0))
5622 (markdown-insert-reference-definition target)))))
5624 (defun markdown-reference-find-links (reference)
5625 "Return a list of all links for REFERENCE.
5626 REFERENCE should not include the surrounding square brackets.
5627 Elements of the list have the form (text start line), where
5628 text is the link text, start is the location at the beginning of
5629 the link, and line is the line number on which the link appears."
5630 (let* ((ref-quote (regexp-quote reference))
5631 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
5632 ref-quote ref-quote))
5633 links)
5634 (save-excursion
5635 (goto-char (point-min))
5636 (while (re-search-forward regexp nil t)
5637 (let* ((text (or (match-string-no-properties 1)
5638 (match-string-no-properties 2)))
5639 (start (match-beginning 0))
5640 (line (markdown-line-number-at-pos)))
5641 (cl-pushnew (list text start line) links :test #'equal))))
5642 links))
5644 (defun markdown-get-undefined-refs ()
5645 "Return a list of undefined Markdown references.
5646 Result is an alist of pairs (reference . occurrences), where
5647 occurrences is itself another alist of pairs (label . line-number).
5648 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
5649 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
5650 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
5651 (let ((missing))
5652 (save-excursion
5653 (goto-char (point-min))
5654 (while
5655 (re-search-forward markdown-regex-link-reference nil t)
5656 (let* ((text (match-string-no-properties 3))
5657 (reference (match-string-no-properties 6))
5658 (target (downcase (if (string= reference "") text reference))))
5659 (unless (markdown-reference-definition target)
5660 (let ((entry (assoc target missing)))
5661 (if (not entry)
5662 (cl-pushnew
5663 (cons target (list (cons text (markdown-line-number-at-pos))))
5664 missing :test #'equal)
5665 (setcdr entry
5666 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
5667 (reverse missing))))
5669 (defconst markdown-reference-check-buffer
5670 "*Undefined references for %buffer%*"
5671 "Pattern for name of buffer for listing undefined references.
5672 The string %buffer% will be replaced by the corresponding
5673 `markdown-mode' buffer name.")
5675 (defun markdown-reference-check-buffer (&optional buffer-name)
5676 "Name and return buffer for reference checking.
5677 BUFFER-NAME is the name of the main buffer being visited."
5678 (or buffer-name (setq buffer-name (buffer-name)))
5679 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
5680 "%buffer%" buffer-name
5681 markdown-reference-check-buffer))))
5682 (with-current-buffer refbuf
5683 (when view-mode
5684 (View-exit-and-edit))
5685 (use-local-map button-buffer-map)
5686 (erase-buffer))
5687 refbuf))
5689 (defconst markdown-reference-links-buffer
5690 "*Reference links for %buffer%*"
5691 "Pattern for name of buffer for listing references.
5692 The string %buffer% will be replaced by the corresponding buffer name.")
5694 (defun markdown-reference-links-buffer (&optional buffer-name)
5695 "Name, setup, and return a buffer for listing links.
5696 BUFFER-NAME is the name of the main buffer being visited."
5697 (or buffer-name (setq buffer-name (buffer-name)))
5698 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
5699 "%buffer%" buffer-name
5700 markdown-reference-links-buffer))))
5701 (with-current-buffer linkbuf
5702 (when view-mode
5703 (View-exit-and-edit))
5704 (use-local-map button-buffer-map)
5705 (erase-buffer))
5706 linkbuf))
5708 ;; Add an empty Markdown reference definition to buffer
5709 ;; specified in the 'target-buffer property. The reference name is
5710 ;; the button's label.
5711 (define-button-type 'markdown-undefined-reference-button
5712 'help-echo "mouse-1, RET: create definition for undefined reference"
5713 'follow-link t
5714 'face 'bold
5715 'action (lambda (b)
5716 (let ((buffer (button-get b 'target-buffer))
5717 (line (button-get b 'target-line))
5718 (label (button-label b)))
5719 (switch-to-buffer-other-window buffer)
5720 (goto-char (point-min))
5721 (forward-line line)
5722 (markdown-insert-reference-definition label)
5723 (markdown-check-refs t))))
5725 ;; Jump to line in buffer specified by 'target-buffer property.
5726 ;; Line number is button's 'line property.
5727 (define-button-type 'markdown-goto-line-button
5728 'help-echo "mouse-1, RET: go to line"
5729 'follow-link t
5730 'face 'italic
5731 'action (lambda (b)
5732 (message (button-get b 'buffer))
5733 (switch-to-buffer-other-window (button-get b 'target-buffer))
5734 ;; use call-interactively to silence compiler
5735 (let ((current-prefix-arg (button-get b 'target-line)))
5736 (call-interactively 'goto-line))))
5738 ;; Jumps to a particular link at location given by 'target-char
5739 ;; property in buffer given by 'target-buffer property.
5740 (define-button-type 'markdown-location-button
5741 'help-echo "mouse-1, RET: jump to location of link"
5742 'follow-link t
5743 'face 'bold
5744 'action (lambda (b)
5745 (let ((target (button-get b 'target-buffer))
5746 (loc (button-get b 'target-char)))
5747 (kill-buffer-and-window)
5748 (switch-to-buffer target)
5749 (goto-char loc))))
5751 (defun markdown-insert-undefined-reference-button (reference oldbuf)
5752 "Insert a button for creating REFERENCE in buffer OLDBUF.
5753 REFERENCE should be a list of the form (reference . occurrences),
5754 as by `markdown-get-undefined-refs'."
5755 (let ((label (car reference)))
5756 ;; Create a reference button
5757 (insert-button label
5758 :type 'markdown-undefined-reference-button
5759 'target-buffer oldbuf
5760 'target-line (cdr (car (cdr reference))))
5761 (insert " (")
5762 (dolist (occurrence (cdr reference))
5763 (let ((line (cdr occurrence)))
5764 ;; Create a line number button
5765 (insert-button (number-to-string line)
5766 :type 'markdown-goto-line-button
5767 'target-buffer oldbuf
5768 'target-line line)
5769 (insert " ")))
5770 (delete-char -1)
5771 (insert ")")
5772 (newline)))
5774 (defun markdown-insert-link-button (link oldbuf)
5775 "Insert a button for jumping to LINK in buffer OLDBUF.
5776 LINK should be a list of the form (text char line) containing
5777 the link text, location, and line number."
5778 (let ((label (cl-first link))
5779 (char (cl-second link))
5780 (line (cl-third link)))
5781 ;; Create a reference button
5782 (insert-button label
5783 :type 'markdown-location-button
5784 'target-buffer oldbuf
5785 'target-char char)
5786 (insert (format " (line %d)\n" line))))
5788 (defun markdown-reference-goto-link (&optional reference)
5789 "Jump to the location of the first use of REFERENCE."
5790 (interactive)
5791 (unless reference
5792 (if (thing-at-point-looking-at markdown-regex-reference-definition)
5793 (setq reference (match-string-no-properties 2))
5794 (user-error "No reference definition at point")))
5795 (let ((links (markdown-reference-find-links reference)))
5796 (cond ((= (length links) 1)
5797 (goto-char (cadr (car links))))
5798 ((> (length links) 1)
5799 (let ((oldbuf (current-buffer))
5800 (linkbuf (markdown-reference-links-buffer)))
5801 (with-current-buffer linkbuf
5802 (insert "Links using reference " reference ":\n\n")
5803 (dolist (link (reverse links))
5804 (markdown-insert-link-button link oldbuf)))
5805 (view-buffer-other-window linkbuf)
5806 (goto-char (point-min))
5807 (forward-line 2)))
5809 (error "No links for reference %s" reference)))))
5811 (defun markdown-check-refs (&optional silent)
5812 "Show all undefined Markdown references in current `markdown-mode' buffer.
5813 If SILENT is non-nil, do not message anything when no undefined
5814 references found.
5815 Links which have empty reference definitions are considered to be
5816 defined."
5817 (interactive "P")
5818 (when (not (eq major-mode 'markdown-mode))
5819 (user-error "Not available in current mode"))
5820 (let ((oldbuf (current-buffer))
5821 (refs (markdown-get-undefined-refs))
5822 (refbuf (markdown-reference-check-buffer)))
5823 (if (null refs)
5824 (progn
5825 (when (not silent)
5826 (message "No undefined references found"))
5827 (kill-buffer refbuf))
5828 (with-current-buffer refbuf
5829 (insert "The following references are undefined:\n\n")
5830 (dolist (ref refs)
5831 (markdown-insert-undefined-reference-button ref oldbuf))
5832 (view-buffer-other-window refbuf)
5833 (goto-char (point-min))
5834 (forward-line 2)))))
5837 ;;; Lists =====================================================================
5839 (defun markdown-insert-list-item (&optional arg)
5840 "Insert a new list item.
5841 If the point is inside unordered list, insert a bullet mark. If
5842 the point is inside ordered list, insert the next number followed
5843 by a period. Use the previous list item to determine the amount
5844 of whitespace to place before and after list markers.
5846 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
5847 decrease the indentation by one level.
5849 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
5850 increase the indentation by one level."
5851 (interactive "p")
5852 (let (bounds cur-indent marker indent new-indent new-loc)
5853 (save-match-data
5854 ;; Look for a list item on current or previous non-blank line
5855 (save-excursion
5856 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
5857 (not (bobp))
5858 (markdown-cur-line-blank-p))
5859 (forward-line -1)))
5860 (when bounds
5861 (cond ((save-excursion
5862 (skip-chars-backward " \t")
5863 (looking-at-p markdown-regex-list))
5864 (beginning-of-line)
5865 (insert "\n")
5866 (forward-line -1))
5867 ((not (markdown-cur-line-blank-p))
5868 (newline)))
5869 (setq new-loc (point)))
5870 ;; Look ahead for a list item on next non-blank line
5871 (unless bounds
5872 (save-excursion
5873 (while (and (null bounds)
5874 (not (eobp))
5875 (markdown-cur-line-blank-p))
5876 (forward-line)
5877 (setq bounds (markdown-cur-list-item-bounds))))
5878 (when bounds
5879 (setq new-loc (point))
5880 (unless (markdown-cur-line-blank-p)
5881 (newline))))
5882 (if (not bounds)
5883 ;; When not in a list, start a new unordered one
5884 (progn
5885 (unless (markdown-cur-line-blank-p)
5886 (insert "\n"))
5887 (insert markdown-unordered-list-item-prefix))
5888 ;; Compute indentation and marker for new list item
5889 (setq cur-indent (nth 2 bounds))
5890 (setq marker (nth 4 bounds))
5891 ;; If current item is a GFM checkbox, insert new unchecked checkbox.
5892 (when (nth 5 bounds)
5893 (setq marker
5894 (concat marker
5895 (replace-regexp-in-string "[Xx]" " " (nth 5 bounds)))))
5896 (cond
5897 ;; Dedent: decrement indentation, find previous marker.
5898 ((= arg 4)
5899 (setq indent (max (- cur-indent 4) 0))
5900 (let ((prev-bounds
5901 (save-excursion
5902 (goto-char (nth 0 bounds))
5903 (when (markdown-up-list)
5904 (markdown-cur-list-item-bounds)))))
5905 (when prev-bounds
5906 (setq marker (nth 4 prev-bounds)))))
5907 ;; Indent: increment indentation by 4, use same marker.
5908 ((= arg 16) (setq indent (+ cur-indent 4)))
5909 ;; Same level: keep current indentation and marker.
5910 (t (setq indent cur-indent)))
5911 (setq new-indent (make-string indent 32))
5912 (goto-char new-loc)
5913 (cond
5914 ;; Ordered list
5915 ((string-match-p "[0-9]" marker)
5916 (if (= arg 16) ;; starting a new column indented one more level
5917 (insert (concat new-indent "1. "))
5918 ;; Don't use previous match-data
5919 (set-match-data nil)
5920 ;; travel up to the last item and pick the correct number. If
5921 ;; the argument was nil, "new-indent = cur-indent" is the same,
5922 ;; so we don't need special treatment. Neat.
5923 (save-excursion
5924 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
5925 (>= (forward-line -1) 0))))
5926 (let* ((old-prefix (match-string 1))
5927 (old-spacing (match-string 2))
5928 (new-prefix (if old-prefix
5929 (int-to-string (1+ (string-to-number old-prefix)))
5930 "1"))
5931 (space-adjust (- (length old-prefix) (length new-prefix)))
5932 (new-spacing (if (and (match-string 2)
5933 (not (string-match-p "\t" old-spacing))
5934 (< space-adjust 0)
5935 (> space-adjust (- 1 (length (match-string 2)))))
5936 (substring (match-string 2) 0 space-adjust)
5937 (or old-spacing ". "))))
5938 (insert (concat new-indent new-prefix new-spacing)))))
5939 ;; Unordered list, GFM task list, or ordered list with hash mark
5940 ((string-match-p "[\\*\\+-]\\|#\\." marker)
5941 (insert new-indent marker))))
5942 ;; Propertize the newly inserted list item now
5943 (markdown-syntax-propertize-list-items (point-at-bol) (point-at-eol)))))
5945 (defun markdown-move-list-item-up ()
5946 "Move the current list item up in the list when possible.
5947 In nested lists, move child items with the parent item."
5948 (interactive)
5949 (let (cur prev old)
5950 (when (setq cur (markdown-cur-list-item-bounds))
5951 (setq old (point))
5952 (goto-char (nth 0 cur))
5953 (if (markdown-prev-list-item (nth 3 cur))
5954 (progn
5955 (setq prev (markdown-cur-list-item-bounds))
5956 (condition-case nil
5957 (progn
5958 (transpose-regions (nth 0 prev) (nth 1 prev)
5959 (nth 0 cur) (nth 1 cur) t)
5960 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
5961 ;; Catch error in case regions overlap.
5962 (error (goto-char old))))
5963 (goto-char old)))))
5965 (defun markdown-move-list-item-down ()
5966 "Move the current list item down in the list when possible.
5967 In nested lists, move child items with the parent item."
5968 (interactive)
5969 (let (cur next old)
5970 (when (setq cur (markdown-cur-list-item-bounds))
5971 (setq old (point))
5972 (if (markdown-next-list-item (nth 3 cur))
5973 (progn
5974 (setq next (markdown-cur-list-item-bounds))
5975 (condition-case nil
5976 (progn
5977 (transpose-regions (nth 0 cur) (nth 1 cur)
5978 (nth 0 next) (nth 1 next) nil)
5979 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
5980 ;; Catch error in case regions overlap.
5981 (error (goto-char old))))
5982 (goto-char old)))))
5984 (defun markdown-demote-list-item (&optional bounds)
5985 "Indent (or demote) the current list item.
5986 Optionally, BOUNDS of the current list item may be provided if available.
5987 In nested lists, demote child items as well."
5988 (interactive)
5989 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
5990 (save-excursion
5991 (let* ((item-start (set-marker (make-marker) (nth 0 bounds)))
5992 (item-end (set-marker (make-marker) (nth 1 bounds)))
5993 (list-start (progn (markdown-beginning-of-list)
5994 (set-marker (make-marker) (point))))
5995 (list-end (progn (markdown-end-of-list)
5996 (set-marker (make-marker) (point)))))
5997 (goto-char item-start)
5998 (while (< (point) item-end)
5999 (unless (markdown-cur-line-blank-p)
6000 (insert (make-string markdown-list-indent-width ? )))
6001 (forward-line))
6002 (markdown-syntax-propertize-list-items list-start list-end)))))
6004 (defun markdown-promote-list-item (&optional bounds)
6005 "Unindent (or promote) the current list item.
6006 Optionally, BOUNDS of the current list item may be provided if available.
6007 In nested lists, demote child items as well."
6008 (interactive)
6009 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6010 (save-excursion
6011 (save-match-data
6012 (let ((item-start (set-marker (make-marker) (nth 0 bounds)))
6013 (item-end (set-marker (make-marker) (nth 1 bounds)))
6014 (list-start (progn (markdown-beginning-of-list)
6015 (set-marker (make-marker) (point))))
6016 (list-end (progn (markdown-end-of-list)
6017 (set-marker (make-marker) (point))))
6018 num regexp)
6019 (goto-char item-start)
6020 (when (looking-at (format "^[ ]\\{1,%d\\}"
6021 markdown-list-indent-width))
6022 (setq num (- (match-end 0) (match-beginning 0)))
6023 (setq regexp (format "^[ ]\\{1,%d\\}" num))
6024 (while (and (< (point) item-end)
6025 (re-search-forward regexp item-end t))
6026 (replace-match "" nil nil)
6027 (forward-line))
6028 (markdown-syntax-propertize-list-items list-start list-end)))))))
6030 (defun markdown-cleanup-list-numbers-level (&optional pfx)
6031 "Update the numbering for level PFX (as a string of spaces).
6033 Assume that the previously found match was for a numbered item in
6034 a list."
6035 (let ((cpfx pfx)
6036 (idx 0)
6037 (continue t)
6038 (step t)
6039 (sep nil))
6040 (while (and continue (not (eobp)))
6041 (setq step t)
6042 (cond
6043 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
6044 (setq cpfx (match-string-no-properties 1))
6045 (cond
6046 ((string= cpfx pfx)
6047 (save-excursion
6048 (replace-match
6049 (concat pfx (number-to-string (setq idx (1+ idx))) ". ")))
6050 (setq sep nil))
6051 ;; indented a level
6052 ((string< pfx cpfx)
6053 (setq sep (markdown-cleanup-list-numbers-level cpfx))
6054 (setq step nil))
6055 ;; exit the loop
6057 (setq step nil)
6058 (setq continue nil))))
6060 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
6061 (setq cpfx (match-string-no-properties 1))
6062 (cond
6063 ;; reset if separated before
6064 ((string= cpfx pfx) (when sep (setq idx 0)))
6065 ((string< cpfx pfx)
6066 (setq step nil)
6067 (setq continue nil))))
6068 (t (setq sep t)))
6070 (when step
6071 (beginning-of-line)
6072 (setq continue (= (forward-line) 0))))
6073 sep))
6075 (defun markdown-cleanup-list-numbers ()
6076 "Update the numbering of ordered lists."
6077 (interactive)
6078 (save-excursion
6079 (goto-char (point-min))
6080 (markdown-cleanup-list-numbers-level "")))
6083 ;;; Movement ==================================================================
6085 (defun markdown-beginning-of-defun (&optional arg)
6086 "`beginning-of-defun-function' for Markdown.
6087 This is used to find the beginning of the defun and should behave
6088 like ‘beginning-of-defun’, returning non-nil if it found the
6089 beginning of a defun. It moves the point backward, right before a
6090 heading which defines a defun. When ARG is non-nil, repeat that
6091 many times. When ARG is negative, move forward to the ARG-th
6092 following section."
6093 (or arg (setq arg 1))
6094 (when (< arg 0) (end-of-line))
6095 ;; Adjust position for setext headings.
6096 (when (and (thing-at-point-looking-at markdown-regex-header-setext)
6097 (not (= (point) (match-beginning 0)))
6098 (not (markdown-code-block-at-point-p)))
6099 (goto-char (match-end 0)))
6100 (let (found)
6101 ;; Move backward with positive argument.
6102 (while (and (not (bobp)) (> arg 0))
6103 (setq found nil)
6104 (while (and (not found)
6105 (not (bobp))
6106 (re-search-backward markdown-regex-header nil 'move))
6107 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6108 (setq found (match-beginning 0)))
6109 (setq arg (1- arg)))
6110 ;; Move forward with negative argument.
6111 (while (and (not (eobp)) (< arg 0))
6112 (setq found nil)
6113 (while (and (not found)
6114 (not (eobp))
6115 (re-search-forward markdown-regex-header nil 'move))
6116 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6117 (setq found (match-beginning 0)))
6118 (setq arg (1+ arg)))
6119 (when found
6120 (beginning-of-line)
6121 t)))
6123 (defun markdown-end-of-defun ()
6124 "`end-of-defun-function’ for Markdown.
6125 This is used to find the end of the defun at point.
6126 It is called with no argument, right after calling ‘beginning-of-defun-raw’,
6127 so it can assume that point is at the beginning of the defun body.
6128 It should move point to the first position after the defun."
6129 (or (eobp) (forward-char 1))
6130 (let (found)
6131 (while (and (not found)
6132 (not (eobp))
6133 (re-search-forward markdown-regex-header nil 'move))
6134 (when (not (markdown-code-block-at-pos (match-beginning 0)))
6135 (setq found (match-beginning 0))))
6136 (when found
6137 (goto-char found)
6138 (skip-syntax-backward "-"))))
6140 (make-obsolete 'markdown-beginning-of-block 'markdown-beginning-of-text-block "v2.2")
6142 (defun markdown-beginning-of-text-block ()
6143 "Move backward to previous beginning of a plain text block.
6144 This function simply looks for blank lines without considering
6145 the surrounding context in light of Markdown syntax. For that, see
6146 `markdown-backward-block'."
6147 (interactive)
6148 (let ((start (point)))
6149 (if (re-search-backward markdown-regex-block-separator nil t)
6150 (goto-char (match-end 0))
6151 (goto-char (point-min)))
6152 (when (and (= start (point)) (not (bobp)))
6153 (forward-line -1)
6154 (if (re-search-backward markdown-regex-block-separator nil t)
6155 (goto-char (match-end 0))
6156 (goto-char (point-min))))))
6158 (make-obsolete 'markdown-end-of-block 'markdown-end-of-text-block "v2.2")
6160 (defun markdown-end-of-text-block ()
6161 "Move forward to next beginning of a plain text block.
6162 This function simply looks for blank lines without considering
6163 the surrounding context in light of Markdown syntax. For that, see
6164 `markdown-forward-block'."
6165 (interactive)
6166 (beginning-of-line)
6167 (skip-chars-forward " \t\n")
6168 (when (= (point) (point-min))
6169 (forward-char))
6170 (if (re-search-forward markdown-regex-block-separator nil t)
6171 (goto-char (match-end 0))
6172 (goto-char (point-max)))
6173 (skip-chars-backward " \t\n")
6174 (forward-line))
6176 (defun markdown-backward-paragraph (&optional arg)
6177 "Move the point to the start of the current paragraph.
6178 With argument ARG, do it ARG times; a negative argument ARG = -N
6179 means move forward N blocks."
6180 (interactive "^p")
6181 (or arg (setq arg 1))
6182 (if (< arg 0)
6183 (markdown-forward-paragraph (- arg))
6184 (dotimes (_ arg)
6185 ;; Skip over whitespace in between paragraphs when moving backward.
6186 (skip-chars-backward " \t\n")
6187 (beginning-of-line)
6188 ;; Skip over code block endings.
6189 (when (markdown-range-properties-exist
6190 (point-at-bol) (point-at-eol)
6191 '(markdown-gfm-block-end
6192 markdown-tilde-fence-end))
6193 (forward-line -1))
6194 ;; Skip over blank lines inside blockquotes.
6195 (while (and (not (eobp))
6196 (looking-at markdown-regex-blockquote)
6197 (= (length (match-string 3)) 0))
6198 (forward-line -1))
6199 ;; Proceed forward based on the type of block of paragraph.
6200 (let (bounds skip)
6201 (cond
6202 ;; Blockquotes
6203 ((looking-at markdown-regex-blockquote)
6204 (while (and (not (bobp))
6205 (looking-at markdown-regex-blockquote)
6206 (> (length (match-string 3)) 0)) ;; not blank
6207 (forward-line -1))
6208 (forward-line))
6209 ;; List items
6210 ((setq bounds (markdown-cur-list-item-bounds))
6211 (goto-char (nth 0 bounds)))
6212 ;; Other
6214 (while (and (not (bobp))
6215 (not skip)
6216 (not (markdown-cur-line-blank-p))
6217 (not (looking-at markdown-regex-blockquote))
6218 (not (markdown-range-properties-exist
6219 (point-at-bol) (point-at-eol)
6220 '(markdown-gfm-block-end
6221 markdown-tilde-fence-end))))
6222 (setq skip (markdown-range-properties-exist
6223 (point-at-bol) (point-at-eol)
6224 '(markdown-gfm-block-begin
6225 markdown-tilde-fence-begin)))
6226 (forward-line -1))
6227 (unless (bobp)
6228 (forward-line 1))))))))
6230 (defun markdown-forward-paragraph (&optional arg)
6231 "Move forward to the next end of a paragraph.
6232 With argument ARG, do it ARG times; a negative argument ARG = -N
6233 means move backward N blocks."
6234 (interactive "^p")
6235 (or arg (setq arg 1))
6236 (if (< arg 0)
6237 (markdown-backward-paragraph (- arg))
6238 (dotimes (_ arg)
6239 ;; Skip whitespace in between paragraphs.
6240 (when (markdown-cur-line-blank-p)
6241 (skip-syntax-forward "-")
6242 (beginning-of-line))
6243 ;; Proceed forward based on the type of block.
6244 (let (bounds skip)
6245 (cond
6246 ;; Blockquotes
6247 ((looking-at markdown-regex-blockquote)
6248 ;; Skip over blank lines inside blockquotes.
6249 (while (and (not (eobp))
6250 (looking-at markdown-regex-blockquote)
6251 (= (length (match-string 3)) 0))
6252 (forward-line))
6253 ;; Move to end of quoted text block
6254 (while (and (not (eobp))
6255 (looking-at markdown-regex-blockquote)
6256 (> (length (match-string 3)) 0)) ;; not blank
6257 (forward-line)))
6258 ;; List items
6259 ((and (markdown-cur-list-item-bounds)
6260 (setq bounds (markdown-next-list-item-bounds)))
6261 (goto-char (nth 0 bounds)))
6262 ;; Other
6264 (forward-line)
6265 (while (and (not (eobp))
6266 (not skip)
6267 (not (markdown-cur-line-blank-p))
6268 (not (looking-at markdown-regex-blockquote))
6269 (not (markdown-range-properties-exist
6270 (point-at-bol) (point-at-eol)
6271 '(markdown-gfm-block-begin
6272 markdown-tilde-fence-begin))))
6273 (setq skip (markdown-range-properties-exist
6274 (point-at-bol) (point-at-eol)
6275 '(markdown-gfm-block-end
6276 markdown-tilde-fence-end)))
6277 (forward-line))))))))
6279 (defun markdown-backward-block (&optional arg)
6280 "Move the point to the start of the current Markdown block.
6281 Moves across complete code blocks, list items, and blockquotes,
6282 but otherwise stops at blank lines, headers, and horizontal
6283 rules. With argument ARG, do it ARG times; a negative argument
6284 ARG = -N means move forward N blocks."
6285 (interactive "^p")
6286 (or arg (setq arg 1))
6287 (if (< arg 0)
6288 (markdown-forward-block (- arg))
6289 (dotimes (_ arg)
6290 ;; Skip over whitespace in between blocks when moving backward,
6291 ;; unless at a block boundary with no whitespace.
6292 (skip-syntax-backward "-")
6293 (beginning-of-line)
6294 ;; Proceed forward based on the type of block.
6295 (cond
6296 ;; Code blocks
6297 ((and (markdown-code-block-at-pos (point)) ;; this line
6298 (markdown-code-block-at-pos (point-at-bol 0))) ;; previous line
6299 (forward-line -1)
6300 (while (and (markdown-code-block-at-point-p) (not (bobp)))
6301 (forward-line -1))
6302 (forward-line))
6303 ;; Headings
6304 ((markdown-heading-at-point)
6305 (goto-char (match-beginning 0)))
6306 ;; Horizontal rules
6307 ((looking-at markdown-regex-hr))
6308 ;; Blockquotes
6309 ((looking-at markdown-regex-blockquote)
6310 (forward-line -1)
6311 (while (and (looking-at markdown-regex-blockquote)
6312 (not (bobp)))
6313 (forward-line -1))
6314 (forward-line))
6315 ;; List items
6316 ((markdown-cur-list-item-bounds)
6317 (markdown-beginning-of-list))
6318 ;; Other
6320 ;; Move forward in case it is a one line regular paragraph.
6321 (unless (markdown-next-line-blank-p)
6322 (forward-line))
6323 (unless (markdown-prev-line-blank-p)
6324 (markdown-backward-paragraph)))))))
6326 (defun markdown-forward-block (&optional arg)
6327 "Move forward to the next end of a Markdown block.
6328 Moves across complete code blocks, list items, and blockquotes,
6329 but otherwise stops at blank lines, headers, and horizontal
6330 rules. With argument ARG, do it ARG times; a negative argument
6331 ARG = -N means move backward N blocks."
6332 (interactive "^p")
6333 (or arg (setq arg 1))
6334 (if (< arg 0)
6335 (markdown-backward-block (- arg))
6336 (dotimes (_ arg)
6337 ;; Skip over whitespace in between blocks when moving forward.
6338 (if (markdown-cur-line-blank-p)
6339 (skip-syntax-forward "-")
6340 (beginning-of-line))
6341 ;; Proceed forward based on the type of block.
6342 (cond
6343 ;; Code blocks
6344 ((markdown-code-block-at-point-p)
6345 (forward-line)
6346 (while (and (markdown-code-block-at-point-p) (not (eobp)))
6347 (forward-line)))
6348 ;; Headings
6349 ((looking-at markdown-regex-header)
6350 (goto-char (or (match-end 4) (match-end 2) (match-end 3)))
6351 (forward-line))
6352 ;; Horizontal rules
6353 ((looking-at markdown-regex-hr)
6354 (forward-line))
6355 ;; Blockquotes
6356 ((looking-at markdown-regex-blockquote)
6357 (forward-line)
6358 (while (and (looking-at markdown-regex-blockquote) (not (eobp)))
6359 (forward-line)))
6360 ;; List items
6361 ((markdown-cur-list-item-bounds)
6362 (markdown-end-of-list)
6363 (forward-line))
6364 ;; Other
6365 (t (markdown-forward-paragraph))))
6366 (skip-syntax-backward "-")
6367 (unless (eobp)
6368 (forward-char 1))))
6370 (defun markdown-backward-page (&optional count)
6371 "Move backward to boundary of the current toplevel section.
6372 With COUNT, repeat, or go forward if negative."
6373 (interactive "p")
6374 (or count (setq count 1))
6375 (if (< count 0)
6376 (markdown-forward-page (- count))
6377 (skip-syntax-backward "-")
6378 (or (markdown-back-to-heading-over-code-block t t)
6379 (goto-char (point-min)))
6380 (when (looking-at markdown-regex-header)
6381 (let ((level (markdown-outline-level)))
6382 (when (> level 1) (markdown-up-heading level))
6383 (when (> count 1)
6384 (condition-case nil
6385 (markdown-backward-same-level (1- count))
6386 (error (goto-char (point-min)))))))))
6388 (defun markdown-forward-page (&optional count)
6389 "Move forward to boundary of the current toplevel section.
6390 With COUNT, repeat, or go backward if negative."
6391 (interactive "p")
6392 (or count (setq count 1))
6393 (if (< count 0)
6394 (markdown-backward-page (- count))
6395 (if (markdown-back-to-heading-over-code-block t t)
6396 (let ((level (markdown-outline-level)))
6397 (when (> level 1) (markdown-up-heading level))
6398 (condition-case nil
6399 (markdown-forward-same-level count)
6400 (error (goto-char (point-max)))))
6401 (markdown-next-visible-heading 1))))
6403 (defun markdown-next-link ()
6404 "Jump to next inline, reference, or wiki link.
6405 If successful, return point. Otherwise, return nil.
6406 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
6407 (interactive)
6408 (let ((opoint (point)))
6409 (when (or (markdown-link-p) (markdown-wiki-link-p))
6410 ;; At a link already, move past it.
6411 (goto-char (+ (match-end 0) 1)))
6412 ;; Search for the next wiki link and move to the beginning.
6413 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t)
6414 (markdown-code-block-at-point-p)
6415 (< (point) (point-max))))
6416 (if (and (not (eq (point) opoint))
6417 (or (markdown-link-p) (markdown-wiki-link-p)))
6418 ;; Group 1 will move past non-escape character in wiki link regexp.
6419 ;; Go to beginning of group zero for all other link types.
6420 (goto-char (or (match-beginning 1) (match-beginning 0)))
6421 (goto-char opoint)
6422 nil)))
6424 (defun markdown-previous-link ()
6425 "Jump to previous wiki link.
6426 If successful, return point. Otherwise, return nil.
6427 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
6428 (interactive)
6429 (let ((opoint (point)))
6430 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t)
6431 (markdown-code-block-at-point-p)
6432 (> (point) (point-min))))
6433 (if (and (not (eq (point) opoint))
6434 (or (markdown-link-p) (markdown-wiki-link-p)))
6435 (goto-char (or (match-beginning 1) (match-beginning 0)))
6436 (goto-char opoint)
6437 nil)))
6440 ;;; Outline ===================================================================
6442 (defun markdown-move-heading-common (move-fn &optional arg adjust)
6443 "Wrapper for `outline-mode' functions to skip false positives.
6444 MOVE-FN is a function and ARG is its argument. For example,
6445 headings inside preformatted code blocks may match
6446 `outline-regexp' but should not be considered as headings.
6447 When ADJUST is non-nil, adjust the point for interactive calls
6448 to avoid leaving the point at invisible markup. This adjustment
6449 generally should only be done for interactive calls, since other
6450 functions may expect the point to be at the beginning of the
6451 regular expression."
6452 (let ((prev -1) (start (point)))
6453 (if arg (funcall move-fn arg) (funcall move-fn))
6454 (while (and (/= prev (point)) (markdown-code-block-at-point-p))
6455 (setq prev (point))
6456 (if arg (funcall move-fn arg) (funcall move-fn)))
6457 ;; Adjust point for setext headings and invisible text.
6458 (save-match-data
6459 (when (and adjust (thing-at-point-looking-at markdown-regex-header))
6460 (if markdown-hide-markup
6461 ;; Move to beginning of heading text if markup is hidden.
6462 (goto-char (or (match-beginning 1) (match-beginning 5)))
6463 ;; Move to beginning of markup otherwise.
6464 (goto-char (or (match-beginning 1) (match-beginning 4))))))
6465 (if (= (point) start) nil (point))))
6467 (defun markdown-next-visible-heading (arg)
6468 "Move to the next visible heading line of any level.
6469 With argument, repeats or can move backward if negative. ARG is
6470 passed to `outline-next-visible-heading'."
6471 (interactive "p")
6472 (markdown-move-heading-common #'outline-next-visible-heading arg 'adjust))
6474 (defun markdown-previous-visible-heading (arg)
6475 "Move to the previous visible heading line of any level.
6476 With argument, repeats or can move backward if negative. ARG is
6477 passed to `outline-previous-visible-heading'."
6478 (interactive "p")
6479 (markdown-move-heading-common #'outline-previous-visible-heading arg 'adjust))
6481 (defun markdown-next-heading ()
6482 "Move to the next heading line of any level."
6483 (markdown-move-heading-common #'outline-next-heading))
6485 (defun markdown-previous-heading ()
6486 "Move to the previous heading line of any level."
6487 (markdown-move-heading-common #'outline-previous-heading))
6489 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok no-error)
6490 "Move back to the beginning of the previous heading.
6491 Returns t if the point is at a heading, the location if a heading
6492 was found, and nil otherwise.
6493 Only visible heading lines are considered, unless INVISIBLE-OK is
6494 non-nil. Throw an error if there is no previous heading unless
6495 NO-ERROR is non-nil.
6496 Leaves match data intact for `markdown-regex-header'."
6497 (beginning-of-line)
6498 (or (and (markdown-heading-at-point)
6499 (not (markdown-code-block-at-point-p)))
6500 (let (found)
6501 (save-excursion
6502 (while (and (not found)
6503 (re-search-backward markdown-regex-header nil t))
6504 (when (and (or invisible-ok (not (outline-invisible-p)))
6505 (not (markdown-code-block-at-point-p)))
6506 (setq found (point))))
6507 (if (not found)
6508 (unless no-error (user-error "Before first heading"))
6509 (setq found (point))))
6510 (when found (goto-char found)))))
6512 (defun markdown-forward-same-level (arg)
6513 "Move forward to the ARG'th heading at same level as this one.
6514 Stop at the first and last headings of a superior heading."
6515 (interactive "p")
6516 (markdown-back-to-heading-over-code-block)
6517 (markdown-move-heading-common #'outline-forward-same-level arg 'adjust))
6519 (defun markdown-backward-same-level (arg)
6520 "Move backward to the ARG'th heading at same level as this one.
6521 Stop at the first and last headings of a superior heading."
6522 (interactive "p")
6523 (markdown-back-to-heading-over-code-block)
6524 (while (> arg 0)
6525 (let ((point-to-move-to
6526 (save-excursion
6527 (markdown-move-heading-common #'outline-get-last-sibling nil 'adjust))))
6528 (if point-to-move-to
6529 (progn
6530 (goto-char point-to-move-to)
6531 (setq arg (1- arg)))
6532 (user-error "No previous same-level heading")))))
6534 (defun markdown-up-heading (arg)
6535 "Move to the visible heading line of which the present line is a subheading.
6536 With argument, move up ARG levels."
6537 (interactive "p")
6538 (and (called-interactively-p 'any)
6539 (not (eq last-command 'markdown-up-heading)) (push-mark))
6540 (markdown-move-heading-common #'outline-up-heading arg 'adjust))
6542 (defun markdown-back-to-heading (&optional invisible-ok)
6543 "Move to previous heading line, or beg of this line if it's a heading.
6544 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
6545 (markdown-move-heading-common #'outline-back-to-heading invisible-ok))
6547 (defalias 'markdown-end-of-heading 'outline-end-of-heading)
6549 (defun markdown-on-heading-p ()
6550 "Return non-nil if point is on a heading line."
6551 (get-text-property (point-at-bol) 'markdown-heading))
6553 (defun markdown-end-of-subtree (&optional invisible-OK)
6554 "Move to the end of the current subtree.
6555 Only visible heading lines are considered, unless INVISIBLE-OK is
6556 non-nil.
6557 Derived from `org-end-of-subtree'."
6558 (markdown-back-to-heading invisible-OK)
6559 (let ((first t)
6560 (level (markdown-outline-level)))
6561 (while (and (not (eobp))
6562 (or first (> (markdown-outline-level) level)))
6563 (setq first nil)
6564 (markdown-next-heading))
6565 (if (memq (preceding-char) '(?\n ?\^M))
6566 (progn
6567 ;; Go to end of line before heading
6568 (forward-char -1)
6569 (if (memq (preceding-char) '(?\n ?\^M))
6570 ;; leave blank line before heading
6571 (forward-char -1)))))
6572 (point))
6574 (defun markdown-outline-fix-visibility ()
6575 "Hide any false positive headings that should not be shown.
6576 For example, headings inside preformatted code blocks may match
6577 `outline-regexp' but should not be shown as headings when cycling.
6578 Also, the ending --- line in metadata blocks appears to be a
6579 setext header, but should not be folded."
6580 (save-excursion
6581 (goto-char (point-min))
6582 ;; Unhide any false positives in metadata blocks
6583 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin)
6584 (let ((body (progn (forward-line)
6585 (markdown-text-property-at-point
6586 'markdown-yaml-metadata-section))))
6587 (when body
6588 (let ((end (progn (goto-char (cl-second body))
6589 (markdown-text-property-at-point
6590 'markdown-yaml-metadata-end))))
6591 (outline-flag-region (point-min) (1+ (cl-second end)) nil)))))
6592 ;; Hide any false positives in code blocks
6593 (unless (outline-on-heading-p)
6594 (outline-next-visible-heading 1))
6595 (while (< (point) (point-max))
6596 (when (markdown-code-block-at-point-p)
6597 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t))
6598 (outline-next-visible-heading 1))))
6600 (defvar markdown-cycle-global-status 1)
6601 (defvar markdown-cycle-subtree-status nil)
6603 (defun markdown-next-preface ()
6604 (let (finish)
6605 (while (and (not finish) (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
6606 nil 'move))
6607 (unless (markdown-code-block-at-point-p)
6608 (goto-char (match-beginning 0))
6609 (setq finish t))))
6610 (when (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
6611 (forward-char -1)))
6613 (defun markdown-show-entry ()
6614 (save-excursion
6615 (outline-back-to-heading t)
6616 (outline-flag-region (1- (point))
6617 (progn
6618 (markdown-next-preface)
6619 (if (= 1 (- (point-max) (point)))
6620 (point-max)
6621 (point)))
6622 nil)))
6624 ;; This function was originally derived from `org-cycle' from org.el.
6625 (defun markdown-cycle (&optional arg)
6626 "Visibility cycling for Markdown mode.
6627 If ARG is t, perform global visibility cycling. If the point is
6628 at an atx-style header, cycle visibility of the corresponding
6629 subtree. Otherwise, indent the current line or insert a tab,
6630 as appropriate, by calling `indent-for-tab-command'."
6631 (interactive "P")
6632 (cond
6634 ;; Global cycling
6635 ((eq arg t)
6636 (cond
6637 ;; Move from overview to contents
6638 ((and (eq last-command this-command)
6639 (eq markdown-cycle-global-status 2))
6640 (markdown-hide-sublevels 1)
6641 (message "CONTENTS")
6642 (setq markdown-cycle-global-status 3)
6643 (markdown-outline-fix-visibility))
6644 ;; Move from contents to all
6645 ((and (eq last-command this-command)
6646 (eq markdown-cycle-global-status 3))
6647 (markdown-show-all)
6648 (message "SHOW ALL")
6649 (setq markdown-cycle-global-status 1))
6650 ;; Defaults to overview
6652 (markdown-hide-body)
6653 (message "OVERVIEW")
6654 (setq markdown-cycle-global-status 2)
6655 (markdown-outline-fix-visibility))))
6657 ;; At a heading: rotate between three different views
6658 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
6659 (markdown-back-to-heading)
6660 (let ((goal-column 0) eoh eol eos)
6661 ;; Determine boundaries
6662 (save-excursion
6663 (markdown-back-to-heading)
6664 (save-excursion
6665 (beginning-of-line 2)
6666 (while (and (not (eobp)) ;; this is like `next-line'
6667 (get-char-property (1- (point)) 'invisible))
6668 (beginning-of-line 2)) (setq eol (point)))
6669 (markdown-end-of-heading) (setq eoh (point))
6670 (markdown-end-of-subtree t)
6671 (skip-chars-forward " \t\n")
6672 (beginning-of-line 1) ; in case this is an item
6673 (setq eos (1- (point))))
6674 ;; Find out what to do next and set `this-command'
6675 (cond
6676 ;; Nothing is hidden behind this heading
6677 ((= eos eoh)
6678 (message "EMPTY ENTRY")
6679 (setq markdown-cycle-subtree-status nil))
6680 ;; Entire subtree is hidden in one line: open it
6681 ((>= eol eos)
6682 (markdown-show-entry)
6683 (markdown-show-children)
6684 (message "CHILDREN")
6685 (setq markdown-cycle-subtree-status 'children))
6686 ;; We just showed the children, now show everything.
6687 ((and (eq last-command this-command)
6688 (eq markdown-cycle-subtree-status 'children))
6689 (markdown-show-subtree)
6690 (message "SUBTREE")
6691 (setq markdown-cycle-subtree-status 'subtree))
6692 ;; Default action: hide the subtree.
6694 (markdown-hide-subtree)
6695 (message "FOLDED")
6696 (setq markdown-cycle-subtree-status 'folded)))))
6698 ;; In a table, move forward by one cell
6699 ((markdown-table-at-point-p)
6700 (call-interactively #'markdown-table-forward-cell))
6702 ;; Otherwise, indent as appropriate
6704 (indent-for-tab-command))))
6706 (defun markdown-shifttab ()
6707 "Handle S-TAB keybinding based on context.
6708 When in a table, move backward one cell.
6709 Otherwise, cycle global heading visibility by calling
6710 `markdown-cycle' with argument t."
6711 (interactive)
6712 (cond ((markdown-table-at-point-p)
6713 (call-interactively #'markdown-table-backward-cell))
6714 (t (markdown-cycle t))))
6716 (defun markdown-outline-level ()
6717 "Return the depth to which a statement is nested in the outline."
6718 (cond
6719 ((and (match-beginning 0)
6720 (markdown-code-block-at-pos (match-beginning 0)))
6721 7) ;; Only 6 header levels are defined.
6722 ((match-end 2) 1)
6723 ((match-end 3) 2)
6724 ((match-end 4)
6725 (length (markdown-trim-whitespace (match-string-no-properties 4))))))
6727 (defun markdown-promote-subtree (&optional arg)
6728 "Promote the current subtree of ATX headings.
6729 Note that Markdown does not support heading levels higher than
6730 six and therefore level-six headings will not be promoted
6731 further. If ARG is non-nil promote the heading, otherwise
6732 demote."
6733 (interactive "*P")
6734 (save-excursion
6735 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
6736 (re-search-backward markdown-regex-header-atx nil t))
6737 (not (markdown-code-block-at-point-p)))
6738 (let ((level (length (match-string 1)))
6739 (promote-or-demote (if arg 1 -1))
6740 (remove 't))
6741 (markdown-cycle-atx promote-or-demote remove)
6742 (catch 'end-of-subtree
6743 (while (and (markdown-next-heading)
6744 (looking-at markdown-regex-header-atx))
6745 ;; Exit if this not a higher level heading; promote otherwise.
6746 (if (and (looking-at markdown-regex-header-atx)
6747 (<= (length (match-string-no-properties 1)) level))
6748 (throw 'end-of-subtree nil)
6749 (markdown-cycle-atx promote-or-demote remove))))))))
6751 (defun markdown-demote-subtree ()
6752 "Demote the current subtree of ATX headings."
6753 (interactive)
6754 (markdown-promote-subtree t))
6756 (defun markdown-move-subtree-up ()
6757 "Move the current subtree of ATX headings up."
6758 (interactive)
6759 (outline-move-subtree-up 1))
6761 (defun markdown-move-subtree-down ()
6762 "Move the current subtree of ATX headings down."
6763 (interactive)
6764 (outline-move-subtree-down 1))
6766 (defun markdown-outline-next ()
6767 "Move to next list item, when in a list, or next visible heading."
6768 (interactive)
6769 (let ((bounds (markdown-next-list-item-bounds)))
6770 (if bounds
6771 (goto-char (nth 0 bounds))
6772 (markdown-next-visible-heading 1))))
6774 (defun markdown-outline-previous ()
6775 "Move to previous list item, when in a list, or previous visible heading."
6776 (interactive)
6777 (let ((bounds (markdown-prev-list-item-bounds)))
6778 (if bounds
6779 (goto-char (nth 0 bounds))
6780 (markdown-previous-visible-heading 1))))
6782 (defun markdown-outline-next-same-level ()
6783 "Move to next list item or heading of same level."
6784 (interactive)
6785 (let ((bounds (markdown-cur-list-item-bounds)))
6786 (if bounds
6787 (markdown-next-list-item (nth 3 bounds))
6788 (markdown-forward-same-level 1))))
6790 (defun markdown-outline-previous-same-level ()
6791 "Move to previous list item or heading of same level."
6792 (interactive)
6793 (let ((bounds (markdown-cur-list-item-bounds)))
6794 (if bounds
6795 (markdown-prev-list-item (nth 3 bounds))
6796 (markdown-backward-same-level 1))))
6798 (defun markdown-outline-up ()
6799 "Move to previous list item, when in a list, or next heading."
6800 (interactive)
6801 (unless (markdown-up-list)
6802 (markdown-up-heading 1)))
6805 ;;; Marking and Narrowing =====================================================
6807 (defun markdown-mark-paragraph ()
6808 "Put mark at end of this block, point at beginning.
6809 The block marked is the one that contains point or follows point.
6811 Interactively, if this command is repeated or (in Transient Mark
6812 mode) if the mark is active, it marks the next block after the
6813 ones already marked."
6814 (interactive)
6815 (if (or (and (eq last-command this-command) (mark t))
6816 (and transient-mark-mode mark-active))
6817 (set-mark
6818 (save-excursion
6819 (goto-char (mark))
6820 (markdown-forward-paragraph)
6821 (point)))
6822 (let ((beginning-of-defun-function 'markdown-backward-paragraph)
6823 (end-of-defun-function 'markdown-forward-paragraph))
6824 (mark-defun))))
6826 (defun markdown-mark-block ()
6827 "Put mark at end of this block, point at beginning.
6828 The block marked is the one that contains point or follows point.
6830 Interactively, if this command is repeated or (in Transient Mark
6831 mode) if the mark is active, it marks the next block after the
6832 ones already marked."
6833 (interactive)
6834 (if (or (and (eq last-command this-command) (mark t))
6835 (and transient-mark-mode mark-active))
6836 (set-mark
6837 (save-excursion
6838 (goto-char (mark))
6839 (markdown-forward-block)
6840 (point)))
6841 (let ((beginning-of-defun-function 'markdown-backward-block)
6842 (end-of-defun-function 'markdown-forward-block))
6843 (mark-defun))))
6845 (defun markdown-narrow-to-block ()
6846 "Make text outside current block invisible.
6847 The current block is the one that contains point or follows point."
6848 (interactive)
6849 (let ((beginning-of-defun-function 'markdown-backward-block)
6850 (end-of-defun-function 'markdown-forward-block))
6851 (narrow-to-defun)))
6853 (defun markdown-mark-text-block ()
6854 "Put mark at end of this plain text block, point at beginning.
6855 The block marked is the one that contains point or follows point.
6857 Interactively, if this command is repeated or (in Transient Mark
6858 mode) if the mark is active, it marks the next block after the
6859 ones already marked."
6860 (interactive)
6861 (if (or (and (eq last-command this-command) (mark t))
6862 (and transient-mark-mode mark-active))
6863 (set-mark
6864 (save-excursion
6865 (goto-char (mark))
6866 (markdown-end-of-text-block)
6867 (point)))
6868 (let ((beginning-of-defun-function 'markdown-beginning-of-text-block)
6869 (end-of-defun-function 'markdown-end-of-text-block))
6870 (mark-defun))))
6872 (defun markdown-mark-page ()
6873 "Put mark at end of this top level section, point at beginning.
6874 The top level section marked is the one that contains point or
6875 follows point.
6877 Interactively, if this command is repeated or (in Transient Mark
6878 mode) if the mark is active, it marks the next page after the
6879 ones already marked."
6880 (interactive)
6881 (if (or (and (eq last-command this-command) (mark t))
6882 (and transient-mark-mode mark-active))
6883 (set-mark
6884 (save-excursion
6885 (goto-char (mark))
6886 (markdown-forward-page)
6887 (point)))
6888 (let ((beginning-of-defun-function 'markdown-backward-page)
6889 (end-of-defun-function 'markdown-forward-page))
6890 (mark-defun))))
6892 (defun markdown-narrow-to-page ()
6893 "Make text outside current top level section invisible.
6894 The current section is the one that contains point or follows point."
6895 (interactive)
6896 (let ((beginning-of-defun-function 'markdown-backward-page)
6897 (end-of-defun-function 'markdown-forward-page))
6898 (narrow-to-defun)))
6900 (defun markdown-mark-subtree ()
6901 "Mark the current subtree.
6902 This puts point at the start of the current subtree, and mark at the end."
6903 (interactive)
6904 (let ((beg))
6905 (if (markdown-heading-at-point)
6906 (beginning-of-line)
6907 (markdown-previous-visible-heading 1))
6908 (setq beg (point))
6909 (markdown-end-of-subtree)
6910 (push-mark (point) nil t)
6911 (goto-char beg)))
6913 (defun markdown-narrow-to-subtree ()
6914 "Narrow buffer to the current subtree."
6915 (interactive)
6916 (save-excursion
6917 (save-match-data
6918 (narrow-to-region
6919 (progn (markdown-back-to-heading-over-code-block t) (point))
6920 (progn (markdown-end-of-subtree)
6921 (if (and (markdown-heading-at-point) (not (eobp)))
6922 (backward-char 1))
6923 (point))))))
6926 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
6928 (defun markdown-move-up ()
6929 "Move thing at point up.
6930 When in a list item, call `markdown-move-list-item-up'.
6931 When in a table, call `markdown-table-move-row-up'.
6932 Otherwise, move the current heading subtree up with
6933 `markdown-move-subtree-up'."
6934 (interactive)
6935 (cond
6936 ((markdown-list-item-at-point-p)
6937 (call-interactively #'markdown-move-list-item-up))
6938 ((markdown-table-at-point-p)
6939 (call-interactively #'markdown-table-move-row-up))
6941 (call-interactively #'markdown-move-subtree-up))))
6943 (defun markdown-move-down ()
6944 "Move thing at point down.
6945 When in a list item, call `markdown-move-list-item-down'.
6946 Otherwise, move the current heading subtree up with
6947 `markdown-move-subtree-down'."
6948 (interactive)
6949 (cond
6950 ((markdown-list-item-at-point-p)
6951 (call-interactively #'markdown-move-list-item-down))
6952 ((markdown-table-at-point-p)
6953 (call-interactively #'markdown-table-move-row-down))
6955 (call-interactively #'markdown-move-subtree-down))))
6957 (defun markdown-promote ()
6958 "Promote or move element at point to the left.
6959 Depending on the context, this function will promote a heading or
6960 list item at the point, move a table column to the left, or cycle
6961 markup."
6962 (interactive)
6963 (let (bounds)
6964 (cond
6965 ;; Promote atx heading subtree
6966 ((thing-at-point-looking-at markdown-regex-header-atx)
6967 (markdown-promote-subtree))
6968 ;; Promote setext heading
6969 ((thing-at-point-looking-at markdown-regex-header-setext)
6970 (markdown-cycle-setext -1))
6971 ;; Promote horizonal rule
6972 ((thing-at-point-looking-at markdown-regex-hr)
6973 (markdown-cycle-hr -1))
6974 ;; Promote list item
6975 ((setq bounds (markdown-cur-list-item-bounds))
6976 (markdown-promote-list-item bounds))
6977 ;; Move table column to the left
6978 ((markdown-table-at-point-p)
6979 (call-interactively #'markdown-table-move-column-left))
6980 ;; Promote bold
6981 ((thing-at-point-looking-at markdown-regex-bold)
6982 (markdown-cycle-bold))
6983 ;; Promote italic
6984 ((thing-at-point-looking-at markdown-regex-italic)
6985 (markdown-cycle-italic))
6987 (user-error "Nothing to promote at point")))))
6989 (defun markdown-demote ()
6990 "Demote or move element at point to the right.
6991 Depending on the context, this function will demote a heading or
6992 list item at the point, move a table column to the right, or cycle
6993 or remove markup."
6994 (interactive)
6995 (let (bounds)
6996 (cond
6997 ;; Demote atx heading subtree
6998 ((thing-at-point-looking-at markdown-regex-header-atx)
6999 (markdown-demote-subtree))
7000 ;; Demote setext heading
7001 ((thing-at-point-looking-at markdown-regex-header-setext)
7002 (markdown-cycle-setext 1))
7003 ;; Demote horizonal rule
7004 ((thing-at-point-looking-at markdown-regex-hr)
7005 (markdown-cycle-hr 1))
7006 ;; Demote list item
7007 ((setq bounds (markdown-cur-list-item-bounds))
7008 (markdown-demote-list-item bounds))
7009 ;; Move table column to the right
7010 ((markdown-table-at-point-p)
7011 (call-interactively #'markdown-table-move-column-right))
7012 ;; Demote bold
7013 ((thing-at-point-looking-at markdown-regex-bold)
7014 (markdown-cycle-bold))
7015 ;; Demote italic
7016 ((thing-at-point-looking-at markdown-regex-italic)
7017 (markdown-cycle-italic))
7019 (user-error "Nothing to demote at point")))))
7022 ;;; Commands ==================================================================
7024 (defun markdown (&optional output-buffer-name)
7025 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
7026 The output buffer name defaults to `markdown-output-buffer-name'.
7027 Return the name of the output buffer used."
7028 (interactive)
7029 (save-window-excursion
7030 (let ((begin-region)
7031 (end-region))
7032 (if (markdown-use-region-p)
7033 (setq begin-region (region-beginning)
7034 end-region (region-end))
7035 (setq begin-region (point-min)
7036 end-region (point-max)))
7038 (unless output-buffer-name
7039 (setq output-buffer-name markdown-output-buffer-name))
7040 (cond
7041 ;; Handle case when `markdown-command' does not read from stdin
7042 ((and (stringp markdown-command) markdown-command-needs-filename)
7043 (if (not buffer-file-name)
7044 (user-error "Must be visiting a file")
7045 (shell-command (concat markdown-command " "
7046 (shell-quote-argument buffer-file-name))
7047 output-buffer-name)))
7048 ;; Pass region to `markdown-command' via stdin
7050 (let ((buf (get-buffer-create output-buffer-name)))
7051 (with-current-buffer buf
7052 (setq buffer-read-only nil)
7053 (erase-buffer))
7054 (if (stringp markdown-command)
7055 (call-process-region begin-region end-region
7056 shell-file-name nil buf nil
7057 shell-command-switch markdown-command)
7058 (funcall markdown-command begin-region end-region buf))))))
7059 output-buffer-name))
7061 (defun markdown-standalone (&optional output-buffer-name)
7062 "Special function to provide standalone HTML output.
7063 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
7064 (interactive)
7065 (setq output-buffer-name (markdown output-buffer-name))
7066 (with-current-buffer output-buffer-name
7067 (set-buffer output-buffer-name)
7068 (unless (markdown-output-standalone-p)
7069 (markdown-add-xhtml-header-and-footer output-buffer-name))
7070 (goto-char (point-min))
7071 (html-mode))
7072 output-buffer-name)
7074 (defun markdown-other-window (&optional output-buffer-name)
7075 "Run `markdown-command' on current buffer and display in other window.
7076 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7077 that name."
7078 (interactive)
7079 (markdown-display-buffer-other-window
7080 (markdown-standalone output-buffer-name)))
7082 (defun markdown-output-standalone-p ()
7083 "Determine whether `markdown-command' output is standalone XHTML.
7084 Standalone XHTML output is identified by an occurrence of
7085 `markdown-xhtml-standalone-regexp' in the first five lines of output."
7086 (save-excursion
7087 (goto-char (point-min))
7088 (save-match-data
7089 (re-search-forward
7090 markdown-xhtml-standalone-regexp
7091 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
7092 t))))
7094 (defun markdown-stylesheet-link-string (stylesheet-path)
7095 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
7096 stylesheet-path
7097 "\" />"))
7099 (defun markdown-add-xhtml-header-and-footer (title)
7100 "Wrap XHTML header and footer with given TITLE around current buffer."
7101 (goto-char (point-min))
7102 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
7103 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
7104 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
7105 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
7106 "<head>\n<title>")
7107 (insert title)
7108 (insert "</title>\n")
7109 (when (> (length markdown-content-type) 0)
7110 (insert
7111 (format
7112 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
7113 markdown-content-type
7114 (or (and markdown-coding-system
7115 (fboundp 'coding-system-get)
7116 (coding-system-get markdown-coding-system
7117 'mime-charset))
7118 (and (fboundp 'coding-system-get)
7119 (coding-system-get buffer-file-coding-system
7120 'mime-charset))
7121 "iso-8859-1"))))
7122 (if (> (length markdown-css-paths) 0)
7123 (insert (mapconcat #'markdown-stylesheet-link-string
7124 markdown-css-paths "\n")))
7125 (when (> (length markdown-xhtml-header-content) 0)
7126 (insert markdown-xhtml-header-content))
7127 (insert "\n</head>\n\n"
7128 "<body>\n\n")
7129 (goto-char (point-max))
7130 (insert "\n"
7131 "</body>\n"
7132 "</html>\n"))
7134 (defun markdown-preview (&optional output-buffer-name)
7135 "Run `markdown-command' on the current buffer and view output in browser.
7136 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7137 that name."
7138 (interactive)
7139 (browse-url-of-buffer
7140 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
7142 (defun markdown-export-file-name (&optional extension)
7143 "Attempt to generate a filename for Markdown output.
7144 The file extension will be EXTENSION if given, or .html by default.
7145 If the current buffer is visiting a file, we construct a new
7146 output filename based on that filename. Otherwise, return nil."
7147 (when (buffer-file-name)
7148 (unless extension
7149 (setq extension ".html"))
7150 (let ((candidate
7151 (concat
7152 (cond
7153 ((buffer-file-name)
7154 (file-name-sans-extension (buffer-file-name)))
7155 (t (buffer-name)))
7156 extension)))
7157 (cond
7158 ((equal candidate (buffer-file-name))
7159 (concat candidate extension))
7161 candidate)))))
7163 (defun markdown-export (&optional output-file)
7164 "Run Markdown on the current buffer, save to file, and return the filename.
7165 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
7166 generated by `markdown-export-file-name', which will be constructed using the
7167 current filename, but with the extension removed and replaced with .html."
7168 (interactive)
7169 (unless output-file
7170 (setq output-file (markdown-export-file-name ".html")))
7171 (when output-file
7172 (let* ((init-buf (current-buffer))
7173 (init-point (point))
7174 (init-buf-string (buffer-string))
7175 (output-buffer (find-file-noselect output-file))
7176 (output-buffer-name (buffer-name output-buffer)))
7177 (run-hooks 'markdown-before-export-hook)
7178 (markdown-standalone output-buffer-name)
7179 (with-current-buffer output-buffer
7180 (run-hooks 'markdown-after-export-hook)
7181 (save-buffer)
7182 (when markdown-export-kill-buffer (kill-buffer)))
7183 ;; if modified, restore initial buffer
7184 (when (buffer-modified-p init-buf)
7185 (erase-buffer)
7186 (insert init-buf-string)
7187 (save-buffer)
7188 (goto-char init-point))
7189 output-file)))
7191 (defun markdown-export-and-preview ()
7192 "Export to XHTML using `markdown-export' and browse the resulting file."
7193 (interactive)
7194 (browse-url-of-file (markdown-export)))
7196 (defvar markdown-live-preview-buffer nil
7197 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
7198 (make-variable-buffer-local 'markdown-live-preview-buffer)
7200 (defvar markdown-live-preview-source-buffer nil
7201 "Source buffer from which current buffer was generated.
7202 This is the inverse of `markdown-live-preview-buffer'.")
7203 (make-variable-buffer-local 'markdown-live-preview-source-buffer)
7205 (defvar markdown-live-preview-currently-exporting nil)
7207 (defun markdown-live-preview-get-filename ()
7208 "Standardize the filename exported by `markdown-live-preview-export'."
7209 (markdown-export-file-name ".html"))
7211 (defun markdown-live-preview-window-eww (file)
7212 "Preview FILE with eww.
7213 To be used with `markdown-live-preview-window-function'."
7214 (if (require 'eww nil t)
7215 (progn
7216 (eww-open-file file)
7217 (get-buffer "*eww*"))
7218 (error "EWW is not present or not loaded on this version of Emacs")))
7220 (defun markdown-visual-lines-between-points (beg end)
7221 (save-excursion
7222 (goto-char beg)
7223 (cl-loop with count = 0
7224 while (progn (end-of-visual-line)
7225 (and (< (point) end) (line-move-visual 1 t)))
7226 do (cl-incf count)
7227 finally return count)))
7229 (defun markdown-live-preview-window-serialize (buf)
7230 "Get window point and scroll data for all windows displaying BUF."
7231 (when (buffer-live-p buf)
7232 (with-current-buffer buf
7233 (mapcar
7234 (lambda (win)
7235 (with-selected-window win
7236 (let* ((start (window-start))
7237 (pt (window-point))
7238 (pt-or-sym (cond ((= pt (point-min)) 'min)
7239 ((= pt (point-max)) 'max)
7240 (t pt)))
7241 (diff (markdown-visual-lines-between-points
7242 start pt)))
7243 (list win pt-or-sym diff))))
7244 (get-buffer-window-list buf)))))
7246 (defun markdown-get-point-back-lines (pt num-lines)
7247 (save-excursion
7248 (goto-char pt)
7249 (line-move-visual (- num-lines) t)
7250 ;; in testing, can occasionally overshoot the number of lines to traverse
7251 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
7252 (when (> actual-num-lines num-lines)
7253 (line-move-visual (- actual-num-lines num-lines) t)))
7254 (point)))
7256 (defun markdown-live-preview-window-deserialize (window-posns)
7257 "Apply window point and scroll data from WINDOW-POSNS.
7258 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
7259 (cl-destructuring-bind (win pt-or-sym diff) window-posns
7260 (when (window-live-p win)
7261 (with-current-buffer markdown-live-preview-buffer
7262 (set-window-buffer win (current-buffer))
7263 (cl-destructuring-bind (actual-pt actual-diff)
7264 (cl-case pt-or-sym
7265 (min (list (point-min) 0))
7266 (max (list (point-max) diff))
7267 (t (list pt-or-sym diff)))
7268 (set-window-start
7269 win (markdown-get-point-back-lines actual-pt actual-diff))
7270 (set-window-point win actual-pt))))))
7272 (defun markdown-live-preview-export ()
7273 "Export to XHTML using `markdown-export'.
7274 Browse the resulting file within Emacs using
7275 `markdown-live-preview-window-function' Return the buffer
7276 displaying the rendered output."
7277 (interactive)
7278 (let ((filename (markdown-live-preview-get-filename)))
7279 (when filename
7280 (let* ((markdown-live-preview-currently-exporting t)
7281 (cur-buf (current-buffer))
7282 (export-file (markdown-export filename))
7283 ;; get positions in all windows currently displaying output buffer
7284 (window-data
7285 (markdown-live-preview-window-serialize
7286 markdown-live-preview-buffer)))
7287 (save-window-excursion
7288 (let ((output-buffer
7289 (funcall markdown-live-preview-window-function export-file)))
7290 (with-current-buffer output-buffer
7291 (setq markdown-live-preview-source-buffer cur-buf)
7292 (add-hook 'kill-buffer-hook
7293 #'markdown-live-preview-remove-on-kill t t))
7294 (with-current-buffer cur-buf
7295 (setq markdown-live-preview-buffer output-buffer))))
7296 (with-current-buffer cur-buf
7297 ;; reset all windows displaying output buffer to where they were,
7298 ;; now with the new output
7299 (mapc #'markdown-live-preview-window-deserialize window-data)
7300 ;; delete html editing buffer
7301 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
7302 (when (and export-file (file-exists-p export-file)
7303 (eq markdown-live-preview-delete-export
7304 'delete-on-export))
7305 (delete-file export-file))
7306 markdown-live-preview-buffer)))))
7308 (defun markdown-live-preview-remove ()
7309 (when (buffer-live-p markdown-live-preview-buffer)
7310 (kill-buffer markdown-live-preview-buffer))
7311 (setq markdown-live-preview-buffer nil)
7312 ;; if set to 'delete-on-export, the output has already been deleted
7313 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
7314 (let ((outfile-name (markdown-live-preview-get-filename)))
7315 (when (and outfile-name (file-exists-p outfile-name))
7316 (delete-file outfile-name)))))
7318 (defun markdown-get-other-window ()
7319 "Find another window to display preview or output content."
7320 (cond
7321 ((memq markdown-split-window-direction '(vertical below))
7322 (or (window-in-direction 'below) (split-window-vertically)))
7323 ((memq markdown-split-window-direction '(horizontal right))
7324 (or (window-in-direction 'right) (split-window-horizontally)))
7325 (t (split-window-sensibly (get-buffer-window)))))
7327 (defun markdown-display-buffer-other-window (buf)
7328 "Display preview or output buffer BUF in another window."
7329 (let ((cur-buf (current-buffer))
7330 (window (markdown-get-other-window)))
7331 (set-window-buffer window buf)
7332 (set-buffer cur-buf)))
7334 (defun markdown-live-preview-if-markdown ()
7335 (when (and (derived-mode-p 'markdown-mode)
7336 markdown-live-preview-mode)
7337 (unless markdown-live-preview-currently-exporting
7338 (if (buffer-live-p markdown-live-preview-buffer)
7339 (markdown-live-preview-export)
7340 (markdown-display-buffer-other-window
7341 (markdown-live-preview-export))))))
7343 (defun markdown-live-preview-remove-on-kill ()
7344 (cond ((and (derived-mode-p 'markdown-mode)
7345 markdown-live-preview-mode)
7346 (markdown-live-preview-remove))
7347 (markdown-live-preview-source-buffer
7348 (with-current-buffer markdown-live-preview-source-buffer
7349 (setq markdown-live-preview-buffer nil))
7350 (setq markdown-live-preview-source-buffer nil))))
7352 (defun markdown-live-preview-switch-to-output ()
7353 "Switch to output buffer."
7354 (interactive)
7355 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
7356 output buffer in another window."
7357 (if markdown-live-preview-mode
7358 (markdown-display-buffer-other-window (markdown-live-preview-export)))
7359 (markdown-live-preview-mode))
7361 (defun markdown-live-preview-re-export ()
7362 "Re export source buffer."
7363 (interactive)
7364 "If the current buffer is a buffer displaying the exported version of a
7365 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
7366 update this buffer's contents."
7367 (when markdown-live-preview-source-buffer
7368 (with-current-buffer markdown-live-preview-source-buffer
7369 (markdown-live-preview-export))))
7371 (defun markdown-open ()
7372 "Open file for the current buffer with `markdown-open-command'."
7373 (interactive)
7374 (unless markdown-open-command
7375 (user-error "Variable `markdown-open-command' must be set"))
7376 (if (stringp markdown-open-command)
7377 (if (not buffer-file-name)
7378 (user-error "Must be visiting a file")
7379 (save-buffer)
7380 (call-process markdown-open-command nil 0 nil buffer-file-name))
7381 (funcall markdown-open-command))
7382 nil)
7384 (defun markdown-kill-ring-save ()
7385 "Run Markdown on file and store output in the kill ring."
7386 (interactive)
7387 (save-window-excursion
7388 (markdown)
7389 (with-current-buffer markdown-output-buffer-name
7390 (kill-ring-save (point-min) (point-max)))))
7393 ;;; Links =====================================================================
7395 (defun markdown-link-p ()
7396 "Return non-nil when `point' is at a non-wiki link.
7397 See `markdown-wiki-link-p' for more information."
7398 (let ((case-fold-search nil))
7399 (and (not (markdown-wiki-link-p))
7400 (not (markdown-code-block-at-point-p))
7401 (or (thing-at-point-looking-at markdown-regex-link-inline)
7402 (thing-at-point-looking-at markdown-regex-link-reference)
7403 (thing-at-point-looking-at markdown-regex-uri)
7404 (thing-at-point-looking-at markdown-regex-angle-uri)))))
7406 (make-obsolete 'markdown-link-link 'markdown-link-url "v2.3")
7408 (defun markdown-link-at-pos (pos)
7409 "Return properties of link or image at position POS.
7410 Value is a list of elements describing the link:
7411 0. beginning position
7412 1. end position
7413 2. link text
7414 3. URL
7415 4. reference label
7416 5. title text
7417 6. bang (nil or \"!\")"
7418 (save-excursion
7419 (goto-char pos)
7420 (let (begin end text url reference title bang)
7421 (cond
7422 ;; Inline or reference image or link at point.
7423 ((or (thing-at-point-looking-at markdown-regex-link-inline)
7424 (thing-at-point-looking-at markdown-regex-link-reference))
7425 (setq bang (match-string-no-properties 1)
7426 begin (match-beginning 0)
7427 end (match-end 0)
7428 text (match-string-no-properties 3))
7429 (if (char-equal (char-after (match-beginning 5)) ?\[)
7430 ;; Reference link
7431 (setq reference (match-string-no-properties 6))
7432 ;; Inline link
7433 (setq url (match-string-no-properties 6))
7434 (when (match-end 7)
7435 (setq title (substring (match-string-no-properties 7) 1 -1)))))
7436 ;; Angle bracket URI at point.
7437 ((thing-at-point-looking-at markdown-regex-angle-uri)
7438 (setq begin (match-beginning 0)
7439 end (match-end 0)
7440 url (match-string-no-properties 2)))
7441 ;; Plain URI at point.
7442 ((thing-at-point-looking-at markdown-regex-uri)
7443 (setq begin (match-beginning 0)
7444 end (match-end 0)
7445 url (match-string-no-properties 1))))
7446 (list begin end text url reference title bang))))
7448 (defun markdown-link-url ()
7449 "Return the URL part of the regular (non-wiki) link at point.
7450 Works with both inline and reference style links, and with images.
7451 If point is not at a link or the link reference is not defined
7452 returns nil."
7453 (let* ((values (markdown-link-at-pos (point)))
7454 (text (nth 2 values))
7455 (url (nth 3 values))
7456 (ref (nth 4 values)))
7457 (or url (and ref (car (markdown-reference-definition
7458 (downcase (if (string= ref "") text ref))))))))
7460 (defun markdown-follow-link-at-point ()
7461 "Open the current non-wiki link.
7462 If the link is a complete URL, open in browser with `browse-url'.
7463 Otherwise, open with `find-file' after stripping anchor and/or query string.
7464 Translate filenames using `markdown-filename-translate-function'."
7465 (interactive)
7466 (if (markdown-link-p)
7467 (let* ((url (markdown-link-url))
7468 (struct (url-generic-parse-url url))
7469 (full (url-fullness struct))
7470 (file url))
7471 ;; Parse URL, determine fullness, strip query string
7472 (if (fboundp 'url-path-and-query)
7473 (setq file (car (url-path-and-query struct)))
7474 (when (and (setq file (url-filename struct))
7475 (string-match "\\?" file))
7476 (setq file (substring file 0 (match-beginning 0)))))
7477 ;; Open full URLs in browser, files in Emacs
7478 (if full
7479 (browse-url url)
7480 (when (and file (> (length file) 0))
7481 (find-file (funcall markdown-translate-filename-function file)))))
7482 (user-error "Point is not at a Markdown link or URL")))
7484 (defun markdown-fontify-inline-links (last)
7485 "Add text properties to next inline link from point to LAST."
7486 (when (markdown-match-generic-links last nil)
7487 (let* ((link-start (match-beginning 3))
7488 (link-end (match-end 3))
7489 (url-start (match-beginning 6))
7490 (url-end (match-end 6))
7491 (url (match-string-no-properties 6))
7492 (title-start (match-beginning 7))
7493 (title-end (match-end 7))
7494 (title (match-string-no-properties 7))
7495 ;; Markup part
7496 (mp (list 'face 'markdown-markup-face
7497 'invisible 'markdown-markup
7498 'rear-nonsticky t
7499 'font-lock-multiline t))
7500 ;; Link part
7501 (lp (list 'keymap markdown-mode-mouse-map
7502 'face 'markdown-link-face
7503 'mouse-face 'markdown-highlight-face
7504 'font-lock-multiline t
7505 'help-echo (if title (concat title "\n" url) url)))
7506 ;; URL part
7507 (up (list 'keymap markdown-mode-mouse-map
7508 'face 'markdown-url-face
7509 'invisible 'markdown-markup
7510 'mouse-face 'markdown-highlight-face
7511 'font-lock-multiline t))
7512 ;; URL composition character
7513 (url-char (markdown--first-displayable markdown-url-compose-char))
7514 ;; Title part
7515 (tp (list 'face 'markdown-link-title-face
7516 'invisible 'markdown-markup
7517 'font-lock-multiline t)))
7518 (dolist (g '(1 2 4 5 8))
7519 (when (match-end g)
7520 (add-text-properties (match-beginning g) (match-end g) mp)))
7521 (when link-start (add-text-properties link-start link-end lp))
7522 (when url-start (add-text-properties url-start url-end up))
7523 (when title-start (add-text-properties url-end title-end tp))
7524 (when (and markdown-hide-urls url-start)
7525 (compose-region url-start (or title-end url-end) url-char))
7526 t)))
7528 (defun markdown-fontify-reference-links (last)
7529 "Add text properties to next reference link from point to LAST."
7530 (when (markdown-match-generic-links last t)
7531 (let* ((link-start (match-beginning 3))
7532 (link-end (match-end 3))
7533 (ref-start (match-beginning 6))
7534 (ref-end (match-end 6))
7535 ;; Markup part
7536 (mp (list 'face 'markdown-markup-face
7537 'invisible 'markdown-markup
7538 'rear-nonsticky t
7539 'font-lock-multiline t))
7540 ;; Link part
7541 (lp (list 'keymap markdown-mode-mouse-map
7542 'face 'markdown-link-face
7543 'mouse-face 'markdown-highlight-face
7544 'font-lock-multiline t
7545 'help-echo (lambda (_ __ pos)
7546 (save-match-data
7547 (save-excursion
7548 (goto-char pos)
7549 (or (markdown-link-url)
7550 "Undefined reference"))))))
7551 ;; URL composition character
7552 (url-char (markdown--first-displayable markdown-url-compose-char))
7553 ;; Reference part
7554 (rp (list 'face 'markdown-reference-face
7555 'invisible 'markdown-markup
7556 'font-lock-multiline t)))
7557 (dolist (g '(1 2 4 5 8))
7558 (when (match-end g)
7559 (add-text-properties (match-beginning g) (match-end g) mp)))
7560 (when link-start (add-text-properties link-start link-end lp))
7561 (when ref-start (add-text-properties ref-start ref-end rp)
7562 (when (and markdown-hide-urls (> (- ref-end ref-start) 2))
7563 (compose-region ref-start ref-end url-char)))
7564 t)))
7566 (defun markdown-fontify-angle-uris (last)
7567 "Add text properties to angle URIs from point to LAST."
7568 (when (markdown-match-angle-uris last)
7569 (let* ((url-start (match-beginning 2))
7570 (url-end (match-end 2))
7571 ;; Markup part
7572 (mp (list 'face 'markdown-markup-face
7573 'invisible 'markdown-markup
7574 'rear-nonsticky t
7575 'font-lock-multiline t))
7576 ;; URI part
7577 (up (list 'keymap markdown-mode-mouse-map
7578 'face 'markdown-plain-url-face
7579 'mouse-face 'markdown-highlight-face
7580 'font-lock-multiline t)))
7581 (dolist (g '(1 3))
7582 (add-text-properties (match-beginning g) (match-end g) mp))
7583 (add-text-properties url-start url-end up)
7584 t)))
7586 (defun markdown-fontify-plain-uris (last)
7587 "Add text properties to plain URLs from point to LAST."
7588 (when (markdown-match-plain-uris last)
7589 (let* ((start (match-beginning 0))
7590 (end (match-end 0))
7591 (props (list 'keymap markdown-mode-mouse-map
7592 'face 'markdown-plain-url-face
7593 'mouse-face 'markdown-highlight-face
7594 'rear-nonsticky t
7595 'font-lock-multiline t)))
7596 (add-text-properties start end props)
7597 t)))
7599 (defun markdown-toggle-url-hiding (&optional arg)
7600 "Toggle the display or hiding of URLs.
7601 With a prefix argument ARG, enable URL hiding if ARG is positive,
7602 and disable it otherwise."
7603 (interactive (list (or current-prefix-arg 'toggle)))
7604 (setq markdown-hide-urls
7605 (if (eq arg 'toggle)
7606 (not markdown-hide-urls)
7607 (> (prefix-numeric-value arg) 0)))
7608 (if markdown-hide-urls
7609 (message "markdown-mode URL hiding enabled")
7610 (message "markdown-mode URL hiding disabled"))
7611 (markdown-reload-extensions))
7614 ;;; WikiLink Following/Markup =================================================
7616 (defun markdown-wiki-link-p ()
7617 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
7618 A true wiki link name matches `markdown-regex-wiki-link' but does
7619 not match the current file name after conversion. This modifies
7620 the data returned by `match-data'. Note that the potential wiki
7621 link name must be available via `match-string'."
7622 (when markdown-enable-wiki-links
7623 (let ((case-fold-search nil))
7624 (and (thing-at-point-looking-at markdown-regex-wiki-link)
7625 (not (markdown-code-block-at-point-p))
7626 (or (not buffer-file-name)
7627 (not (string-equal (buffer-file-name)
7628 (markdown-convert-wiki-link-to-filename
7629 (markdown-wiki-link-link)))))))))
7631 (defun markdown-wiki-link-link ()
7632 "Return the link part of the wiki link using current match data.
7633 The location of the link component depends on the value of
7634 `markdown-wiki-link-alias-first'."
7635 (if markdown-wiki-link-alias-first
7636 (or (match-string-no-properties 5) (match-string-no-properties 3))
7637 (match-string-no-properties 3)))
7639 (defun markdown-wiki-link-alias ()
7640 "Return the alias or text part of the wiki link using current match data.
7641 The location of the alias component depends on the value of
7642 `markdown-wiki-link-alias-first'."
7643 (if markdown-wiki-link-alias-first
7644 (match-string-no-properties 3)
7645 (or (match-string-no-properties 5) (match-string-no-properties 3))))
7647 (defun markdown-convert-wiki-link-to-filename (name)
7648 "Generate a filename from the wiki link NAME.
7649 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
7650 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
7651 and [[test test]] both map to Test-test.ext. Look in the current
7652 directory first, then in subdirectories if
7653 `markdown-wiki-link-search-subdirectories' is non-nil, and then
7654 in parent directories if
7655 `markdown-wiki-link-search-parent-directories' is non-nil."
7656 (let* ((basename (markdown-replace-regexp-in-string
7657 "[[:space:]\n]" markdown-link-space-sub-char name))
7658 (basename (if (eq major-mode '(gfm-mode gfm-view-mode))
7659 (concat (upcase (substring basename 0 1))
7660 (downcase (substring basename 1 nil)))
7661 basename))
7662 directory extension default candidates dir)
7663 (when buffer-file-name
7664 (setq directory (file-name-directory buffer-file-name)
7665 extension (file-name-extension buffer-file-name)))
7666 (setq default (concat basename
7667 (when extension (concat "." extension))))
7668 (cond
7669 ;; Look in current directory first.
7670 ((or (null buffer-file-name)
7671 (file-exists-p default))
7672 default)
7673 ;; Possibly search in subdirectories, next.
7674 ((and markdown-wiki-link-search-subdirectories
7675 (setq candidates
7676 (markdown-directory-files-recursively
7677 directory (concat "^" default "$"))))
7678 (car candidates))
7679 ;; Possibly search in parent directories as a last resort.
7680 ((and markdown-wiki-link-search-parent-directories
7681 (setq dir (locate-dominating-file directory default)))
7682 (concat dir default))
7683 ;; If nothing is found, return default in current directory.
7684 (t default))))
7686 (defun markdown-follow-wiki-link (name &optional other)
7687 "Follow the wiki link NAME.
7688 Convert the name to a file name and call `find-file'. Ensure that
7689 the new buffer remains in `markdown-mode'. Open the link in another
7690 window when OTHER is non-nil."
7691 (let ((filename (markdown-convert-wiki-link-to-filename name))
7692 (wp (when buffer-file-name
7693 (file-name-directory buffer-file-name))))
7694 (if (not wp)
7695 (user-error "Must be visiting a file")
7696 (when other (other-window 1))
7697 (let ((default-directory wp))
7698 (find-file filename)))
7699 (when (not (eq major-mode 'markdown-mode))
7700 (markdown-mode))))
7702 (defun markdown-follow-wiki-link-at-point (&optional arg)
7703 "Find Wiki Link at point.
7704 With prefix argument ARG, open the file in other window.
7705 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
7706 (interactive "P")
7707 (if (markdown-wiki-link-p)
7708 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
7709 (user-error "Point is not at a Wiki Link")))
7711 (defun markdown-highlight-wiki-link (from to face)
7712 "Highlight the wiki link in the region between FROM and TO using FACE."
7713 (put-text-property from to 'font-lock-face face))
7715 (defun markdown-unfontify-region-wiki-links (from to)
7716 "Remove wiki link faces from the region specified by FROM and TO."
7717 (interactive "*r")
7718 (let ((modified (buffer-modified-p)))
7719 (remove-text-properties from to '(font-lock-face markdown-link-face))
7720 (remove-text-properties from to '(font-lock-face markdown-missing-link-face))
7721 ;; remove-text-properties marks the buffer modified in emacs 24.3,
7722 ;; undo that if it wasn't originally marked modified
7723 (set-buffer-modified-p modified)))
7725 (defun markdown-fontify-region-wiki-links (from to)
7726 "Search region given by FROM and TO for wiki links and fontify them.
7727 If a wiki link is found check to see if the backing file exists
7728 and highlight accordingly."
7729 (goto-char from)
7730 (save-match-data
7731 (while (re-search-forward markdown-regex-wiki-link to t)
7732 (when (not (markdown-code-block-at-point-p))
7733 (let ((highlight-beginning (match-beginning 1))
7734 (highlight-end (match-end 1))
7735 (file-name
7736 (markdown-convert-wiki-link-to-filename
7737 (markdown-wiki-link-link))))
7738 (if (condition-case nil (file-exists-p file-name) (error nil))
7739 (markdown-highlight-wiki-link
7740 highlight-beginning highlight-end 'markdown-link-face)
7741 (markdown-highlight-wiki-link
7742 highlight-beginning highlight-end 'markdown-missing-link-face)))))))
7744 (defun markdown-extend-changed-region (from to)
7745 "Extend region given by FROM and TO so that we can fontify all links.
7746 The region is extended to the first newline before and the first
7747 newline after."
7748 ;; start looking for the first new line before 'from
7749 (goto-char from)
7750 (re-search-backward "\n" nil t)
7751 (let ((new-from (point-min))
7752 (new-to (point-max)))
7753 (if (not (= (point) from))
7754 (setq new-from (point)))
7755 ;; do the same thing for the first new line after 'to
7756 (goto-char to)
7757 (re-search-forward "\n" nil t)
7758 (if (not (= (point) to))
7759 (setq new-to (point)))
7760 (cl-values new-from new-to)))
7762 (defun markdown-check-change-for-wiki-link (from to)
7763 "Check region between FROM and TO for wiki links and re-fontify as needed."
7764 (interactive "*r")
7765 (let* ((modified (buffer-modified-p))
7766 (buffer-undo-list t)
7767 (inhibit-read-only t)
7768 (inhibit-point-motion-hooks t)
7769 deactivate-mark
7770 buffer-file-truename)
7771 (unwind-protect
7772 (save-excursion
7773 (save-match-data
7774 (save-restriction
7775 ;; Extend the region to fontify so that it starts
7776 ;; and ends at safe places.
7777 (cl-multiple-value-bind (new-from new-to)
7778 (markdown-extend-changed-region from to)
7779 (goto-char new-from)
7780 ;; Only refontify when the range contains text with a
7781 ;; wiki link face or if the wiki link regexp matches.
7782 (when (or (markdown-range-property-any
7783 new-from new-to 'font-lock-face
7784 '(markdown-link-face markdown-missing-link-face))
7785 (re-search-forward
7786 markdown-regex-wiki-link new-to t))
7787 ;; Unfontify existing fontification (start from scratch)
7788 (markdown-unfontify-region-wiki-links new-from new-to)
7789 ;; Now do the fontification.
7790 (markdown-fontify-region-wiki-links new-from new-to))))))
7791 (and (not modified)
7792 (buffer-modified-p)
7793 (set-buffer-modified-p nil)))))
7795 (defun markdown-check-change-for-wiki-link-after-change (from to _)
7796 "Check region between FROM and TO for wiki links and re-fontify as needed.
7797 Designed to be used with the `after-change-functions' hook."
7798 (markdown-check-change-for-wiki-link from to))
7800 (defun markdown-fontify-buffer-wiki-links ()
7801 "Refontify all wiki links in the buffer."
7802 (interactive)
7803 (markdown-check-change-for-wiki-link (point-min) (point-max)))
7806 ;;; Following & Doing =========================================================
7808 (defun markdown-follow-thing-at-point (arg)
7809 "Follow thing at point if possible, such as a reference link or wiki link.
7810 Opens inline and reference links in a browser. Opens wiki links
7811 to other files in the current window, or the another window if
7812 ARG is non-nil.
7813 See `markdown-follow-link-at-point' and
7814 `markdown-follow-wiki-link-at-point'."
7815 (interactive "P")
7816 (cond ((markdown-link-p)
7817 (markdown-follow-link-at-point))
7818 ((markdown-wiki-link-p)
7819 (markdown-follow-wiki-link-at-point arg))
7821 (user-error "Nothing to follow at point"))))
7823 (make-obsolete 'markdown-jump 'markdown-do "v2.3")
7825 (defun markdown-do ()
7826 "Do something sensible based on context at point.
7827 Jumps between reference links and definitions; between footnote
7828 markers and footnote text."
7829 (interactive)
7830 (cond
7831 ;; Footnote definition
7832 ((markdown-footnote-text-positions)
7833 (markdown-footnote-return))
7834 ;; Footnote marker
7835 ((markdown-footnote-marker-positions)
7836 (markdown-footnote-goto-text))
7837 ;; Reference link
7838 ((thing-at-point-looking-at markdown-regex-link-reference)
7839 (markdown-reference-goto-definition))
7840 ;; Reference definition
7841 ((thing-at-point-looking-at markdown-regex-reference-definition)
7842 (markdown-reference-goto-link (match-string-no-properties 2)))
7843 ;; GFM task list item
7844 ((markdown-gfm-task-list-item-at-point)
7845 (markdown-toggle-gfm-checkbox))
7846 ;; Align table
7847 ((markdown-table-at-point-p)
7848 (call-interactively #'markdown-table-align))
7849 ;; Otherwise
7851 (markdown-insert-gfm-checkbox))))
7854 ;;; Miscellaneous =============================================================
7856 (defun markdown-compress-whitespace-string (str)
7857 "Compress whitespace in STR and return result.
7858 Leading and trailing whitespace is removed. Sequences of multiple
7859 spaces, tabs, and newlines are replaced with single spaces."
7860 (markdown-replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
7861 (markdown-replace-regexp-in-string "[ \t\n]+" " " str)))
7863 (defun markdown--substitute-command-keys (string)
7864 "Like `substitute-command-keys' but, but prefers control characters.
7865 First pass STRING to `substitute-command-keys' and then
7866 substitute `C-i` for `TAB` and `C-m` for `RET`."
7867 (replace-regexp-in-string
7868 "\\<TAB\\>" "C-i"
7869 (replace-regexp-in-string
7870 "\\<RET\\>" "C-m" (substitute-command-keys string) t) t))
7872 (defun markdown-line-number-at-pos (&optional pos)
7873 "Return (narrowed) buffer line number at position POS.
7874 If POS is nil, use current buffer location.
7875 This is an exact copy of `line-number-at-pos' for use in emacs21."
7876 (let ((opoint (or pos (point))) start)
7877 (save-excursion
7878 (goto-char (point-min))
7879 (setq start (point))
7880 (goto-char opoint)
7881 (forward-line 0)
7882 (1+ (count-lines start (point))))))
7884 (defun markdown-inside-link-p ()
7885 "Return t if point is within a link."
7886 (save-match-data
7887 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
7889 (defun markdown-line-is-reference-definition-p ()
7890 "Return whether the current line is a (non-footnote) reference defition."
7891 (save-excursion
7892 (move-beginning-of-line 1)
7893 (and (looking-at-p markdown-regex-reference-definition)
7894 (not (looking-at-p "[ \t]*\\[^")))))
7896 (defun markdown-adaptive-fill-function ()
7897 "Return prefix for filling paragraph or nil if not determined."
7898 (cond
7899 ;; List item inside blockquote
7900 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
7901 (markdown-replace-regexp-in-string
7902 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
7903 ;; Blockquote
7904 ((looking-at markdown-regex-blockquote)
7905 (buffer-substring-no-properties (match-beginning 0) (match-end 2)))
7906 ;; List items
7907 ((looking-at markdown-regex-list)
7908 (match-string-no-properties 0))
7909 ;; Footnote definition
7910 ((looking-at-p markdown-regex-footnote-definition)
7911 " ") ; four spaces
7912 ;; No match
7913 (t nil)))
7915 (defun markdown-fill-paragraph (&optional justify)
7916 "Fill paragraph at or after point.
7917 This function is like \\[fill-paragraph], but it skips Markdown
7918 code blocks. If the point is in a code block, or just before one,
7919 do not fill. Otherwise, call `fill-paragraph' as usual. If
7920 JUSTIFY is non-nil, justify text as well. Since this function
7921 handles filling itself, it always returns t so that
7922 `fill-paragraph' doesn't run."
7923 (interactive "P")
7924 (unless (or (markdown-code-block-at-point-p)
7925 (save-excursion
7926 (back-to-indentation)
7927 (skip-syntax-forward "-")
7928 (markdown-code-block-at-point-p)))
7929 (fill-paragraph justify))
7932 (make-obsolete 'markdown-fill-forward-paragraph-function
7933 'markdown-fill-forward-paragraph "v2.3")
7935 (defun markdown-fill-forward-paragraph (&optional arg)
7936 "Function used by `fill-paragraph' to move over ARG paragraphs.
7937 This is a `fill-forward-paragraph-function' for `markdown-mode'.
7938 It is called with a single argument specifying the number of
7939 paragraphs to move. Just like `forward-paragraph', it should
7940 return the number of paragraphs left to move."
7941 (or arg (setq arg 1))
7942 (if (> arg 0)
7943 ;; With positive ARG, move across ARG non-code-block paragraphs,
7944 ;; one at a time. When passing a code block, don't decrement ARG.
7945 (while (and (not (eobp))
7946 (> arg 0)
7947 (= (forward-paragraph 1) 0)
7948 (or (markdown-code-block-at-pos (point-at-bol 0))
7949 (setq arg (1- arg)))))
7950 ;; Move backward by one paragraph with negative ARG (always -1).
7951 (let ((start (point)))
7952 (setq arg (forward-paragraph arg))
7953 (while (and (not (eobp))
7954 (progn (move-to-left-margin) (not (eobp)))
7955 (looking-at-p paragraph-separate))
7956 (forward-line 1))
7957 (cond
7958 ;; Move point past whitespace following list marker.
7959 ((looking-at markdown-regex-list)
7960 (goto-char (match-end 0)))
7961 ;; Move point past whitespace following pipe at beginning of line
7962 ;; to handle Pandoc line blocks.
7963 ((looking-at "^|\\s-*")
7964 (goto-char (match-end 0)))
7965 ;; Return point if the paragraph passed was a code block.
7966 ((markdown-code-block-at-pos (point-at-bol 2))
7967 (goto-char start)))))
7968 arg)
7970 (defun markdown--inhibit-electric-quote ()
7971 "Function added to `electric-quote-inhibit-functions'.
7972 Return non-nil if the quote has been inserted inside a code block
7973 or span."
7974 (let ((pos (1- (point))))
7975 (or (markdown-inline-code-at-pos pos)
7976 (markdown-code-block-at-pos pos))))
7979 ;;; Extension Framework =======================================================
7981 (defun markdown-reload-extensions ()
7982 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
7983 (interactive)
7984 (when (member major-mode
7985 '(markdown-mode markdown-view-mode gfm-mode gfm-view-mode))
7986 ;; Refontify buffer
7987 (if (eval-when-compile (fboundp 'font-lock-flush))
7988 ;; Use font-lock-flush in Emacs >= 25.1
7989 (font-lock-flush)
7990 ;; Backwards compatibility for Emacs 24.3-24.5
7991 (when (and font-lock-mode (fboundp 'font-lock-refresh-defaults))
7992 (font-lock-refresh-defaults)))
7993 ;; Add or remove hooks related to extensions
7994 (markdown-setup-wiki-link-hooks)))
7996 (defun markdown-handle-local-variables ()
7997 "Run in `hack-local-variables-hook' to update font lock rules.
7998 Checks to see if there is actually a ‘markdown-mode’ file local variable
7999 before regenerating font-lock rules for extensions."
8000 (when (and (boundp 'file-local-variables-alist)
8001 (or (assoc 'markdown-enable-wiki-links file-local-variables-alist)
8002 (assoc 'markdown-enable-math file-local-variables-alist)))
8003 (when (assoc 'markdown-enable-math file-local-variables-alist)
8004 (markdown-toggle-math markdown-enable-math))
8005 (markdown-reload-extensions)))
8008 ;;; Wiki Links ================================================================
8010 (defun markdown-toggle-wiki-links (&optional arg)
8011 "Toggle support for wiki links.
8012 With a prefix argument ARG, enable wiki link support if ARG is positive,
8013 and disable it otherwise."
8014 (interactive (list (or current-prefix-arg 'toggle)))
8015 (setq markdown-enable-wiki-links
8016 (if (eq arg 'toggle)
8017 (not markdown-enable-wiki-links)
8018 (> (prefix-numeric-value arg) 0)))
8019 (if markdown-enable-wiki-links
8020 (message "markdown-mode wiki link support enabled")
8021 (message "markdown-mode wiki link support disabled"))
8022 (markdown-reload-extensions))
8024 (defun markdown-setup-wiki-link-hooks ()
8025 "Add or remove hooks for fontifying wiki links.
8026 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
8027 ;; Anytime text changes make sure it gets fontified correctly
8028 (if (and markdown-enable-wiki-links
8029 markdown-wiki-link-fontify-missing)
8030 (add-hook 'after-change-functions
8031 'markdown-check-change-for-wiki-link-after-change t t)
8032 (remove-hook 'after-change-functions
8033 'markdown-check-change-for-wiki-link-after-change t))
8034 ;; If we left the buffer there is a really good chance we were
8035 ;; creating one of the wiki link documents. Make sure we get
8036 ;; refontified when we come back.
8037 (if (and markdown-enable-wiki-links
8038 markdown-wiki-link-fontify-missing)
8039 (progn
8040 (add-hook 'window-configuration-change-hook
8041 'markdown-fontify-buffer-wiki-links t t)
8042 (markdown-fontify-buffer-wiki-links))
8043 (remove-hook 'window-configuration-change-hook
8044 'markdown-fontify-buffer-wiki-links t)
8045 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
8048 ;;; Math Support ==============================================================
8050 (make-obsolete 'markdown-enable-math 'markdown-toggle-math "v2.1")
8052 (defconst markdown-mode-font-lock-keywords-math
8053 (list
8054 ;; Equation reference (eq:foo)
8055 '("\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" . ((1 markdown-markup-face)
8056 (2 markdown-reference-face)
8057 (3 markdown-markup-face)))
8058 ;; Equation reference \eqref{foo}
8059 '("\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" . ((1 markdown-markup-face)
8060 (2 markdown-reference-face)
8061 (3 markdown-markup-face))))
8062 "Font lock keywords to add and remove when toggling math support.")
8064 (defun markdown-toggle-math (&optional arg)
8065 "Toggle support for inline and display LaTeX math expressions.
8066 With a prefix argument ARG, enable math mode if ARG is positive,
8067 and disable it otherwise. If called from Lisp, enable the mode
8068 if ARG is omitted or nil."
8069 (interactive (list (or current-prefix-arg 'toggle)))
8070 (setq markdown-enable-math
8071 (if (eq arg 'toggle)
8072 (not markdown-enable-math)
8073 (> (prefix-numeric-value arg) 0)))
8074 (if markdown-enable-math
8075 (progn
8076 (font-lock-add-keywords
8077 'markdown-mode markdown-mode-font-lock-keywords-math)
8078 (message "markdown-mode math support enabled"))
8079 (font-lock-remove-keywords
8080 'markdown-mode markdown-mode-font-lock-keywords-math)
8081 (message "markdown-mode math support disabled"))
8082 (markdown-reload-extensions))
8085 ;;; GFM Checkboxes ============================================================
8087 (define-button-type 'markdown-gfm-checkbox-button
8088 'follow-link t
8089 'face 'markdown-gfm-checkbox-face
8090 'mouse-face 'markdown-highlight-face
8091 'action #'markdown-toggle-gfm-checkbox-button)
8093 (defun markdown-gfm-task-list-item-at-point (&optional bounds)
8094 "Return non-nil if there is a GFM task list item at the point.
8095 Optionally, the list item BOUNDS may be given if available, as
8096 returned by `markdown-cur-list-item-bounds'. When a task list item
8097 is found, the return value is the same value returned by
8098 `markdown-cur-list-item-bounds'."
8099 (unless bounds
8100 (setq bounds (markdown-cur-list-item-bounds)))
8101 (> (length (nth 5 bounds)) 0))
8103 (defun markdown-insert-gfm-checkbox ()
8104 "Add GFM checkbox at point.
8105 Returns t if added.
8106 Returns nil if non-applicable."
8107 (interactive)
8108 (let ((bounds (markdown-cur-list-item-bounds)))
8109 (if bounds
8110 (unless (cl-sixth bounds)
8111 (let ((pos (+ (cl-first bounds) (cl-fourth bounds)))
8112 (markup "[ ] "))
8113 (if (< pos (point))
8114 (save-excursion
8115 (goto-char pos)
8116 (insert markup))
8117 (goto-char pos)
8118 (insert markup))
8119 (syntax-propertize (+ (cl-second bounds) 4))
8121 (unless (save-excursion
8122 (back-to-indentation)
8123 (or (markdown-list-item-at-point-p)
8124 (markdown-heading-at-point)
8125 (markdown-in-comment-p)
8126 (markdown-code-block-at-point-p)))
8127 (let ((pos (save-excursion
8128 (back-to-indentation)
8129 (point)))
8130 (markup (concat (or (save-excursion
8131 (beginning-of-line 0)
8132 (cl-fifth (markdown-cur-list-item-bounds)))
8133 markdown-unordered-list-item-prefix)
8134 "[ ] ")))
8135 (if (< pos (point))
8136 (save-excursion
8137 (goto-char pos)
8138 (insert markup))
8139 (goto-char pos)
8140 (insert markup))
8141 (syntax-propertize (point-at-eol))
8142 t)))))
8144 (defun markdown-toggle-gfm-checkbox ()
8145 "Toggle GFM checkbox at point.
8146 Returns the resulting status as a string, either \"[x]\" or \"[ ]\".
8147 Returns nil if there is no task list item at the point."
8148 (interactive)
8149 (save-match-data
8150 (save-excursion
8151 (let ((bounds (markdown-cur-list-item-bounds)))
8152 (when bounds
8153 ;; Move to beginning of task list item
8154 (goto-char (cl-first bounds))
8155 ;; Advance to column of first non-whitespace after marker
8156 (forward-char (cl-fourth bounds))
8157 (cond ((looking-at "\\[ \\]")
8158 (replace-match
8159 (if markdown-gfm-uppercase-checkbox "[X]" "[x]")
8160 nil t)
8161 (match-string-no-properties 0))
8162 ((looking-at "\\[[xX]\\]")
8163 (replace-match "[ ]" nil t)
8164 (match-string-no-properties 0))))))))
8166 (defun markdown-toggle-gfm-checkbox-button (button)
8167 "Toggle GFM checkbox BUTTON on click."
8168 (save-match-data
8169 (save-excursion
8170 (goto-char (button-start button))
8171 (markdown-toggle-gfm-checkbox))))
8173 (defun markdown-make-gfm-checkboxes-buttons (start end)
8174 "Make GFM checkboxes buttons in region between START and END."
8175 (save-excursion
8176 (goto-char start)
8177 (let ((case-fold-search t))
8178 (save-excursion
8179 (while (re-search-forward markdown-regex-gfm-checkbox end t)
8180 (make-button (match-beginning 1) (match-end 1)
8181 :type 'markdown-gfm-checkbox-button))))))
8183 ;; Called when any modification is made to buffer text.
8184 (defun markdown-gfm-checkbox-after-change-function (beg end _)
8185 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
8186 BEG and END are the limits of scanned region."
8187 (save-excursion
8188 (save-match-data
8189 ;; Rescan between start of line from `beg' and start of line after `end'.
8190 (markdown-make-gfm-checkboxes-buttons
8191 (progn (goto-char beg) (beginning-of-line) (point))
8192 (progn (goto-char end) (forward-line 1) (point))))))
8194 (defun markdown-remove-gfm-checkbox-overlays ()
8195 "Remove all GFM checkbox overlays in buffer."
8196 (save-excursion
8197 (save-restriction
8198 (widen)
8199 (remove-overlays nil nil 'face 'markdown-gfm-checkbox-face))))
8202 ;;; Display inline image =================================================
8204 (defvar markdown-inline-image-overlays nil)
8205 (make-variable-buffer-local 'markdown-inline-image-overlays)
8207 (defun markdown-remove-inline-images ()
8208 "Remove inline image overlays from image links in the buffer.
8209 This can be toggled with `markdown-toggle-inline-images'
8210 or \\[markdown-toggle-inline-images]."
8211 (interactive)
8212 (mapc #'delete-overlay markdown-inline-image-overlays)
8213 (setq markdown-inline-image-overlays nil))
8215 (defun markdown-display-inline-images ()
8216 "Add inline image overlays to image links in the buffer.
8217 This can be toggled with `markdown-toggle-inline-images'
8218 or \\[markdown-toggle-inline-images]."
8219 (interactive)
8220 (unless (display-images-p)
8221 (error "Cannot show images"))
8222 (save-excursion
8223 (save-restriction
8224 (widen)
8225 (goto-char (point-min))
8226 (while (re-search-forward markdown-regex-link-inline nil t)
8227 (let ((start (match-beginning 0))
8228 (end (match-end 0))
8229 (file (match-string-no-properties 6)))
8230 (when (file-exists-p file)
8231 (let* ((abspath (if (file-name-absolute-p file)
8232 file
8233 (concat default-directory file)))
8234 (image
8235 (if (and markdown-max-image-size
8236 (image-type-available-p 'imagemagick))
8237 (create-image
8238 abspath 'imagemagick nil
8239 :max-width (car markdown-max-image-size)
8240 :max-height (cdr markdown-max-image-size))
8241 (create-image abspath))))
8242 (when image
8243 (let ((ov (make-overlay start end)))
8244 (overlay-put ov 'display image)
8245 (overlay-put ov 'face 'default)
8246 (push ov markdown-inline-image-overlays))))))))))
8248 (defun markdown-toggle-inline-images ()
8249 "Toggle inline image overlays in the buffer."
8250 (interactive)
8251 (if markdown-inline-image-overlays
8252 (markdown-remove-inline-images)
8253 (markdown-display-inline-images)))
8256 ;;; GFM Code Block Fontification ==============================================
8258 (defcustom markdown-fontify-code-blocks-natively nil
8259 "When non-nil, fontify code in code blocks using the native major mode.
8260 This only works for fenced code blocks where the language is
8261 specified where we can automatically determine the appropriate
8262 mode to use. The language to mode mapping may be customized by
8263 setting the variable `markdown-code-lang-modes'."
8264 :group 'markdown
8265 :type 'boolean
8266 :safe 'booleanp
8267 :package-version '(markdown-mode . "2.3"))
8269 (defun markdown-toggle-fontify-code-blocks-natively (&optional arg)
8270 "Toggle the native fontification of code blocks.
8271 With a prefix argument ARG, enable if ARG is positive,
8272 and disable otherwise."
8273 (interactive (list (or current-prefix-arg 'toggle)))
8274 (setq markdown-fontify-code-blocks-natively
8275 (if (eq arg 'toggle)
8276 (not markdown-fontify-code-blocks-natively)
8277 (> (prefix-numeric-value arg) 0)))
8278 (if markdown-fontify-code-blocks-natively
8279 (message "markdown-mode native code block fontification enabled")
8280 (message "markdown-mode native code block fontification disabled"))
8281 (markdown-reload-extensions))
8283 ;; This is based on `org-src-lang-modes' from org-src.el
8284 (defcustom markdown-code-lang-modes
8285 '(("ocaml" . tuareg-mode) ("elisp" . emacs-lisp-mode) ("ditaa" . artist-mode)
8286 ("asymptote" . asy-mode) ("dot" . fundamental-mode) ("sqlite" . sql-mode)
8287 ("calc" . fundamental-mode) ("C" . c-mode) ("cpp" . c++-mode)
8288 ("C++" . c++-mode) ("screen" . shell-script-mode) ("shell" . sh-mode)
8289 ("bash" . sh-mode))
8290 "Alist mapping languages to their major mode.
8291 The key is the language name, the value is the major mode. For
8292 many languages this is simple, but for language where this is not
8293 the case, this variable provides a way to simplify things on the
8294 user side. For example, there is no ocaml-mode in Emacs, but the
8295 mode to use is `tuareg-mode'."
8296 :group 'markdown
8297 :type '(repeat
8298 (cons
8299 (string "Language name")
8300 (symbol "Major mode")))
8301 :package-version '(markdown-mode . "2.3"))
8303 (defun markdown-get-lang-mode (lang)
8304 "Return major mode that should be used for LANG.
8305 LANG is a string, and the returned major mode is a symbol."
8306 (cl-find-if
8307 'fboundp
8308 (list (cdr (assoc lang markdown-code-lang-modes))
8309 (cdr (assoc (downcase lang) markdown-code-lang-modes))
8310 (intern (concat lang "-mode"))
8311 (intern (concat (downcase lang) "-mode")))))
8313 (defun markdown-fontify-code-blocks-generic (matcher last)
8314 "Add text properties to next code block from point to LAST.
8315 Use matching function MATCHER."
8316 (when (funcall matcher last)
8317 (save-excursion
8318 (save-match-data
8319 (let* ((start (match-beginning 0))
8320 (end (match-end 0))
8321 ;; Find positions outside opening and closing backquotes.
8322 (bol-prev (progn (goto-char start)
8323 (if (bolp) (point-at-bol 0) (point-at-bol))))
8324 (eol-next (progn (goto-char end)
8325 (if (bolp) (point-at-bol 2) (point-at-bol 3))))
8326 lang)
8327 (if (and markdown-fontify-code-blocks-natively
8328 (setq lang (markdown-code-block-lang)))
8329 (markdown-fontify-code-block-natively lang start end)
8330 (add-text-properties start end '(face markdown-pre-face)))
8331 ;; Set background for block as well as opening and closing lines.
8332 (font-lock-append-text-property
8333 bol-prev eol-next 'face 'markdown-code-face)
8334 ;; Set invisible property for lines before and after, including newline.
8335 (add-text-properties bol-prev start '(invisible markdown-markup))
8336 (add-text-properties end eol-next '(invisible markdown-markup)))))
8339 (defun markdown-fontify-gfm-code-blocks (last)
8340 "Add text properties to next GFM code block from point to LAST."
8341 (markdown-fontify-code-blocks-generic 'markdown-match-gfm-code-blocks last))
8343 (defun markdown-fontify-fenced-code-blocks (last)
8344 "Add text properties to next tilde fenced code block from point to LAST."
8345 (markdown-fontify-code-blocks-generic 'markdown-match-fenced-code-blocks last))
8347 ;; Based on `org-src-font-lock-fontify-block' from org-src.el.
8348 (defun markdown-fontify-code-block-natively (lang start end)
8349 "Fontify given GFM or fenced code block.
8350 This function is called by Emacs for automatic fontification when
8351 `markdown-fontify-code-blocks-natively' is non-nil. LANG is the
8352 language used in the block. START and END specify the block
8353 position."
8354 (let ((lang-mode (markdown-get-lang-mode lang)))
8355 (when (fboundp lang-mode)
8356 (let ((string (buffer-substring-no-properties start end))
8357 (modified (buffer-modified-p))
8358 (markdown-buffer (current-buffer)) pos next)
8359 (remove-text-properties start end '(face nil))
8360 (with-current-buffer
8361 (get-buffer-create
8362 (concat " markdown-code-fontification:" (symbol-name lang-mode)))
8363 ;; Make sure that modification hooks are not inhibited in
8364 ;; the org-src-fontification buffer in case we're called
8365 ;; from `jit-lock-function' (Bug#25132).
8366 (let ((inhibit-modification-hooks nil))
8367 (delete-region (point-min) (point-max))
8368 (insert string " ")) ;; so there's a final property change
8369 (unless (eq major-mode lang-mode) (funcall lang-mode))
8370 (markdown-font-lock-ensure)
8371 (setq pos (point-min))
8372 (while (setq next (next-single-property-change pos 'face))
8373 (let ((val (get-text-property pos 'face)))
8374 (when val
8375 (put-text-property
8376 (+ start (1- pos)) (1- (+ start next)) 'face
8377 val markdown-buffer)))
8378 (setq pos next)))
8379 (add-text-properties
8380 start end
8381 '(font-lock-fontified t fontified t font-lock-multiline t))
8382 (set-buffer-modified-p modified)))))
8384 (require 'edit-indirect nil t)
8385 (defvar edit-indirect-guess-mode-function)
8386 (defvar edit-indirect-after-commit-functions)
8388 (defun markdown--edit-indirect-after-commit-function (_beg end)
8389 "Ensure trailing newlines at the END of code blocks."
8390 (goto-char end)
8391 (unless (eq (char-before) ?\n)
8392 (insert "\n")))
8394 (defun markdown-edit-code-block ()
8395 "Edit Markdown code block in an indirect buffer."
8396 (interactive)
8397 (save-excursion
8398 (if (fboundp 'edit-indirect-region)
8399 (let* ((bounds (markdown-get-enclosing-fenced-block-construct))
8400 (begin (and bounds (goto-char (nth 0 bounds)) (point-at-bol 2)))
8401 (end (and bounds (goto-char (nth 1 bounds)) (point-at-bol 1))))
8402 (if (and begin end)
8403 (let* ((lang (markdown-code-block-lang))
8404 (mode (or (and lang (markdown-get-lang-mode lang))
8405 markdown-edit-code-block-default-mode))
8406 (edit-indirect-guess-mode-function
8407 (lambda (_parent-buffer _beg _end)
8408 (funcall mode))))
8409 (edit-indirect-region begin end 'display-buffer))
8410 (user-error "Not inside a GFM or tilde fenced code block")))
8411 (when (y-or-n-p "Package edit-indirect needed to edit code blocks. Install it now? ")
8412 (progn (package-refresh-contents)
8413 (package-install 'edit-indirect)
8414 (markdown-edit-code-block))))))
8417 ;;; Table Editing
8419 ;; These functions were originally adapted from `org-table.el'.
8421 ;; General helper functions
8423 (defmacro markdown--with-gensyms (symbols &rest body)
8424 (declare (debug (sexp body)) (indent 1))
8425 `(let ,(mapcar (lambda (s)
8426 `(,s (make-symbol (concat "--" (symbol-name ',s)))))
8427 symbols)
8428 ,@body))
8430 (defun markdown--split-string (string &optional separators)
8431 "Splits STRING into substrings at SEPARATORS.
8432 SEPARATORS is a regular expression. If nil it defaults to
8433 `split-string-default-separators'. This version returns no empty
8434 strings if there are matches at the beginning and end of string."
8435 (let ((start 0) notfirst list)
8436 (while (and (string-match
8437 (or separators split-string-default-separators)
8438 string
8439 (if (and notfirst
8440 (= start (match-beginning 0))
8441 (< start (length string)))
8442 (1+ start) start))
8443 (< (match-beginning 0) (length string)))
8444 (setq notfirst t)
8445 (or (eq (match-beginning 0) 0)
8446 (and (eq (match-beginning 0) (match-end 0))
8447 (eq (match-beginning 0) start))
8448 (push (substring string start (match-beginning 0)) list))
8449 (setq start (match-end 0)))
8450 (or (eq start (length string))
8451 (push (substring string start) list))
8452 (nreverse list)))
8454 (defun markdown--string-width (s)
8455 "Return width of string S.
8456 This version ignores characters with invisibility property
8457 `markdown-markup'."
8458 (let (b)
8459 (when (or (eq t buffer-invisibility-spec)
8460 (member 'markdown-markup buffer-invisibility-spec))
8461 (while (setq b (text-property-any
8462 0 (length s)
8463 'invisible 'markdown-markup s))
8464 (setq s (concat
8465 (substring s 0 b)
8466 (substring s (or (next-single-property-change
8467 b 'invisible s)
8468 (length s))))))))
8469 (string-width s))
8471 (defun markdown--remove-invisible-markup (s)
8472 "Remove Markdown markup from string S.
8473 This version removes characters with invisibility property
8474 `markdown-markup'."
8475 (let (b)
8476 (while (setq b (text-property-any
8477 0 (length s)
8478 'invisible 'markdown-markup s))
8479 (setq s (concat
8480 (substring s 0 b)
8481 (substring s (or (next-single-property-change
8482 b 'invisible s)
8483 (length s)))))))
8486 ;; Functions for maintaining tables
8488 (defvar markdown-table-at-point-p-function nil
8489 "Function to decide if point is inside a table.
8491 The indirection serves to differentiate between standard markdown
8492 tables and gfm tables which are less strict about the markup.")
8494 (defconst markdown-table-line-regexp "^[ \t]*|"
8495 "Regexp matching any line inside a table.")
8497 (defconst markdown-table-hline-regexp "^[ \t]*|[-:]"
8498 "Regexp matching hline inside a table.")
8500 (defconst markdown-table-dline-regexp "^[ \t]*|[^-:]"
8501 "Regexp matching dline inside a table.")
8503 (defun markdown-table-at-point-p ()
8504 "Return non-nil when point is inside a table."
8505 (if (functionp markdown-table-at-point-p-function)
8506 (funcall markdown-table-at-point-p-function)
8507 (markdown--table-at-point-p)))
8509 (defun markdown--table-at-point-p ()
8510 "Return non-nil when point is inside a table."
8511 (save-excursion
8512 (beginning-of-line)
8513 (and (looking-at-p markdown-table-line-regexp)
8514 (not (markdown-code-block-at-point-p)))))
8516 (defconst gfm-table-line-regexp "^.?*|"
8517 "Regexp matching any line inside a table.")
8519 (defconst gfm-table-hline-regexp "^-+\\(|-\\)+"
8520 "Regexp matching hline inside a table.")
8522 ;; GFM simplified tables syntax is as follows:
8523 ;; - A header line for the column names, this is any text
8524 ;; separated by `|'.
8525 ;; - Followed by a string -|-|- ..., the number of dashes is optional
8526 ;; but must be higher than 1. The number of separators should match
8527 ;; the number of columns.
8528 ;; - Followed by the rows of data, which has the same format as the
8529 ;; header line.
8530 ;; Example:
8532 ;; foo | bar
8533 ;; ------|---------
8534 ;; bar | baz
8535 ;; bar | baz
8536 (defun gfm--table-at-point-p ()
8537 "Return non-nil when point is inside a gfm-compatible table."
8538 (or (markdown--table-at-point-p)
8539 (save-excursion
8540 (beginning-of-line)
8541 (when (looking-at-p gfm-table-line-regexp)
8542 ;; we might be at the first line of the table, check if the
8543 ;; line below is the hline
8544 (or (save-excursion
8545 (forward-line 1)
8546 (looking-at-p gfm-table-hline-regexp))
8547 ;; go up to find the header
8548 (catch 'done
8549 (while (looking-at-p gfm-table-line-regexp)
8550 (cond
8551 ((looking-at-p gfm-table-hline-regexp)
8552 (throw 'done t))
8553 ((bobp)
8554 (throw 'done nil)))
8555 (forward-line -1))
8556 nil))))))
8558 (defun markdown-table-hline-at-point-p ()
8559 "Return non-nil when point is on a hline in a table.
8560 This function assumes point is on a table."
8561 (save-excursion
8562 (beginning-of-line)
8563 (looking-at-p markdown-table-hline-regexp)))
8565 (defun markdown-table-begin ()
8566 "Find the beginning of the table and return its position.
8567 This function assumes point is on a table."
8568 (save-excursion
8569 (while (and (not (bobp))
8570 (markdown-table-at-point-p))
8571 (forward-line -1))
8572 (unless (eobp)
8573 (forward-line 1))
8574 (point)))
8576 (defun markdown-table-end ()
8577 "Find the end of the table and return its position.
8578 This function assumes point is on a table."
8579 (save-excursion
8580 (while (and (not (eobp))
8581 (markdown-table-at-point-p))
8582 (forward-line 1))
8583 (point)))
8585 (defun markdown-table-get-dline ()
8586 "Return index of the table data line at point.
8587 This function assumes point is on a table."
8588 (let ((pos (point)) (end (markdown-table-end)) (cnt 0))
8589 (save-excursion
8590 (goto-char (markdown-table-begin))
8591 (while (and (re-search-forward
8592 markdown-table-dline-regexp end t)
8593 (setq cnt (1+ cnt))
8594 (< (point-at-eol) pos))))
8595 cnt))
8597 (defun markdown-table-get-column ()
8598 "Return table column at point.
8599 This function assumes point is on a table."
8600 (let ((pos (point)) (cnt 0))
8601 (save-excursion
8602 (beginning-of-line)
8603 (while (search-forward "|" pos t) (setq cnt (1+ cnt))))
8604 cnt))
8606 (defun markdown-table-get-cell (&optional n)
8607 "Return the content of the cell in column N of current row.
8608 N defaults to column at point. This function assumes point is on
8609 a table."
8610 (and n (markdown-table-goto-column n))
8611 (skip-chars-backward "^|\n") (backward-char 1)
8612 (if (looking-at "|[^|\r\n]*")
8613 (let* ((pos (match-beginning 0))
8614 (val (buffer-substring (1+ pos) (match-end 0))))
8615 (goto-char (min (point-at-eol) (+ 2 pos)))
8616 ;; Trim whitespaces
8617 (setq val (replace-regexp-in-string "\\`[ \t]+" "" val)
8618 val (replace-regexp-in-string "[ \t]+\\'" "" val)))
8619 (forward-char 1) ""))
8621 (defun markdown-table-goto-dline (n)
8622 "Go to the Nth data line in the table at point.
8623 Return t when the line exists, nil otherwise. This function
8624 assumes point is on a table."
8625 (goto-char (markdown-table-begin))
8626 (let ((end (markdown-table-end)) (cnt 0))
8627 (while (and (re-search-forward
8628 markdown-table-dline-regexp end t)
8629 (< (setq cnt (1+ cnt)) n)))
8630 (= cnt n)))
8632 (defun markdown-table-goto-column (n &optional on-delim)
8633 "Go to the Nth column in the table line at point.
8634 With optional argument ON-DELIM, stop with point before the left
8635 delimiter of the cell. If there are less than N cells, just go
8636 beyond the last delimiter. This function assumes point is on a
8637 table."
8638 (beginning-of-line 1)
8639 (when (> n 0)
8640 (while (and (> (setq n (1- n)) -1)
8641 (search-forward "|" (point-at-eol) t)))
8642 (if on-delim
8643 (backward-char 1)
8644 (when (looking-at " ") (forward-char 1)))))
8646 (defmacro markdown-table-save-cell (&rest body)
8647 "Save cell at point, execute BODY and restore cell.
8648 This function assumes point is on a table."
8649 (declare (debug (body)))
8650 (markdown--with-gensyms (line column)
8651 `(let ((,line (copy-marker (line-beginning-position)))
8652 (,column (markdown-table-get-column)))
8653 (unwind-protect
8654 (progn ,@body)
8655 (goto-char ,line)
8656 (markdown-table-goto-column ,column)
8657 (set-marker ,line nil)))))
8659 (defun markdown-table-blank-line (s)
8660 "Convert a table line S into a line with blank cells."
8661 (if (string-match "^[ \t]*|-" s)
8662 (setq s (mapconcat
8663 (lambda (x) (if (member x '(?| ?+)) "|" " "))
8664 s ""))
8665 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
8666 (setq s (replace-match
8667 (concat "|" (make-string (length (match-string 1 s)) ?\ ) "|")
8668 t t s)))
8671 (defun markdown-table-colfmt (fmtspec)
8672 "Process column alignment specifier FMTSPEC for tables."
8673 (when (stringp fmtspec)
8674 (mapcar (lambda (x)
8675 (cond ((string-match-p "^:.*:$" x) 'c)
8676 ((string-match-p "^:" x) 'l)
8677 ((string-match-p ":$" x) 'r)
8678 (t 'd)))
8679 (markdown--split-string fmtspec "\\s-*|\\s-*"))))
8681 (defun markdown-table-align ()
8682 "Align table at point.
8683 This function assumes point is on a table."
8684 (interactive)
8685 (let ((begin (markdown-table-begin))
8686 (end (copy-marker (markdown-table-end))))
8687 (markdown-table-save-cell
8688 (goto-char begin)
8689 (let* (fmtspec
8690 ;; Store table indent
8691 (indent (progn (looking-at "[ \t]*") (match-string 0)))
8692 ;; Split table in lines and save column format specifier
8693 (lines (mapcar (lambda (l)
8694 (if (string-match-p "\\`[ \t]*|[-:]" l)
8695 (progn (setq fmtspec (or fmtspec l)) nil) l))
8696 (markdown--split-string (buffer-substring begin end) "\n")))
8697 ;; Split lines in cells
8698 (cells (mapcar (lambda (l) (markdown--split-string l "\\s-*|\\s-*"))
8699 (remq nil lines)))
8700 ;; Calculate maximum number of cells in a line
8701 (maxcells (if cells
8702 (apply #'max (mapcar #'length cells))
8703 (user-error "Empty table")))
8704 ;; Empty cells to fill short lines
8705 (emptycells (make-list maxcells "")) maxwidths)
8706 ;; Calculate maximum width for each column
8707 (dotimes (i maxcells)
8708 (let ((column (mapcar (lambda (x) (or (nth i x) "")) cells)))
8709 (push (apply #'max 1 (mapcar #'markdown--string-width column))
8710 maxwidths)))
8711 (setq maxwidths (nreverse maxwidths))
8712 ;; Process column format specifier
8713 (setq fmtspec (markdown-table-colfmt fmtspec))
8714 ;; Compute formats needed for output of table lines
8715 (let ((hfmt (concat indent "|"))
8716 (rfmt (concat indent "|"))
8717 hfmt1 rfmt1 fmt)
8718 (dolist (width maxwidths (setq hfmt (concat (substring hfmt 0 -1) "|")))
8719 (setq fmt (pop fmtspec))
8720 (cond ((equal fmt 'l) (setq hfmt1 ":%s-|" rfmt1 " %%-%ds |"))
8721 ((equal fmt 'r) (setq hfmt1 "-%s:|" rfmt1 " %%%ds |"))
8722 ((equal fmt 'c) (setq hfmt1 ":%s:|" rfmt1 " %%-%ds |"))
8723 (t (setq hfmt1 "-%s-|" rfmt1 " %%-%ds |")))
8724 (setq rfmt (concat rfmt (format rfmt1 width)))
8725 (setq hfmt (concat hfmt (format hfmt1 (make-string width ?-)))))
8726 ;; Replace modified lines only
8727 (dolist (line lines)
8728 (let ((line (if line
8729 (apply #'format rfmt (append (pop cells) emptycells))
8730 hfmt))
8731 (previous (buffer-substring (point) (line-end-position))))
8732 (if (equal previous line)
8733 (forward-line)
8734 (insert line "\n")
8735 (delete-region (point) (line-beginning-position 2))))))
8736 (set-marker end nil)))))
8738 (defun markdown-table-insert-row (&optional arg)
8739 "Insert a new row above the row at point into the table.
8740 With optional argument ARG, insert below the current row."
8741 (interactive "P")
8742 (unless (markdown-table-at-point-p)
8743 (user-error "Not at a table"))
8744 (let* ((line (buffer-substring
8745 (line-beginning-position) (line-end-position)))
8746 (new (markdown-table-blank-line line)))
8747 (beginning-of-line (if arg 2 1))
8748 (unless (bolp) (insert "\n"))
8749 (insert-before-markers new "\n")
8750 (beginning-of-line 0)
8751 (re-search-forward "| ?" (line-end-position) t)))
8753 (defun markdown-table-delete-row ()
8754 "Delete row or horizontal line at point from the table."
8755 (interactive)
8756 (unless (markdown-table-at-point-p)
8757 (user-error "Not at a table"))
8758 (let ((col (current-column)))
8759 (kill-region (point-at-bol)
8760 (min (1+ (point-at-eol)) (point-max)))
8761 (unless (markdown-table-at-point-p) (beginning-of-line 0))
8762 (move-to-column col)))
8764 (defun markdown-table-move-row (&optional up)
8765 "Move table line at point down.
8766 With optional argument UP, move it up."
8767 (interactive "P")
8768 (unless (markdown-table-at-point-p)
8769 (user-error "Not at a table"))
8770 (let* ((col (current-column)) (pos (point))
8771 (tonew (if up 0 2)) txt)
8772 (beginning-of-line tonew)
8773 (unless (markdown-table-at-point-p)
8774 (goto-char pos) (user-error "Cannot move row further"))
8775 (goto-char pos) (beginning-of-line 1) (setq pos (point))
8776 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8777 (delete-region (point) (1+ (point-at-eol)))
8778 (beginning-of-line tonew)
8779 (insert txt) (beginning-of-line 0)
8780 (move-to-column col)))
8782 (defun markdown-table-move-row-up ()
8783 "Move table row at point up."
8784 (interactive)
8785 (markdown-table-move-row 'up))
8787 (defun markdown-table-move-row-down ()
8788 "Move table row at point down."
8789 (interactive)
8790 (markdown-table-move-row nil))
8792 (defun markdown-table-insert-column ()
8793 "Insert a new table column."
8794 (interactive)
8795 (unless (markdown-table-at-point-p)
8796 (user-error "Not at a table"))
8797 (let* ((col (max 1 (markdown-table-get-column)))
8798 (begin (markdown-table-begin))
8799 (end (copy-marker (markdown-table-end))))
8800 (markdown-table-save-cell
8801 (goto-char begin)
8802 (while (< (point) end)
8803 (markdown-table-goto-column col t)
8804 (if (markdown-table-hline-at-point-p)
8805 (insert "|---")
8806 (insert "| "))
8807 (forward-line)))
8808 (set-marker end nil)
8809 (markdown-table-align)))
8811 (defun markdown-table-delete-column ()
8812 "Delete column at point from table."
8813 (interactive)
8814 (unless (markdown-table-at-point-p)
8815 (user-error "Not at a table"))
8816 (let ((col (markdown-table-get-column))
8817 (begin (markdown-table-begin))
8818 (end (copy-marker (markdown-table-end))))
8819 (markdown-table-save-cell
8820 (goto-char begin)
8821 (while (< (point) end)
8822 (markdown-table-goto-column col t)
8823 (and (looking-at "|[^|\n]+|")
8824 (replace-match "|"))
8825 (forward-line)))
8826 (set-marker end nil)
8827 (markdown-table-goto-column (max 1 (1- col)))
8828 (markdown-table-align)))
8830 (defun markdown-table-move-column (&optional left)
8831 "Move table column at point to the right.
8832 With optional argument LEFT, move it to the left."
8833 (interactive "P")
8834 (unless (markdown-table-at-point-p)
8835 (user-error "Not at a table"))
8836 (let* ((col (markdown-table-get-column))
8837 (col1 (if left (1- col) col))
8838 (colpos (if left (1- col) (1+ col)))
8839 (begin (markdown-table-begin))
8840 (end (copy-marker (markdown-table-end))))
8841 (when (and left (= col 1))
8842 (user-error "Cannot move column further left"))
8843 (when (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8844 (user-error "Cannot move column further right"))
8845 (markdown-table-save-cell
8846 (goto-char begin)
8847 (while (< (point) end)
8848 (markdown-table-goto-column col1 t)
8849 (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8850 (replace-match "|\\2|\\1|"))
8851 (forward-line)))
8852 (set-marker end nil)
8853 (markdown-table-goto-column colpos)
8854 (markdown-table-align)))
8856 (defun markdown-table-move-column-left ()
8857 "Move table column at point to the left."
8858 (interactive)
8859 (markdown-table-move-column 'left))
8861 (defun markdown-table-move-column-right ()
8862 "Move table column at point to the right."
8863 (interactive)
8864 (markdown-table-move-column nil))
8866 (defun markdown-table-next-row ()
8867 "Go to the next row (same column) in the table.
8868 Create new table lines if required."
8869 (interactive)
8870 (unless (markdown-table-at-point-p)
8871 (user-error "Not at a table"))
8872 (if (or (looking-at "[ \t]*$")
8873 (save-excursion (skip-chars-backward " \t") (bolp)))
8874 (newline)
8875 (markdown-table-align)
8876 (let ((col (markdown-table-get-column)))
8877 (beginning-of-line 2)
8878 (if (or (not (markdown-table-at-point-p))
8879 (markdown-table-hline-at-point-p))
8880 (progn
8881 (beginning-of-line 0)
8882 (markdown-table-insert-row 'below)))
8883 (markdown-table-goto-column col)
8884 (skip-chars-backward "^|\n\r")
8885 (when (looking-at " ") (forward-char 1)))))
8887 (defun markdown-table-forward-cell ()
8888 "Go to the next cell in the table.
8889 Create new table lines if required."
8890 (interactive)
8891 (unless (markdown-table-at-point-p)
8892 (user-error "Not at a table"))
8893 (markdown-table-align)
8894 (let ((end (markdown-table-end)))
8895 (when (markdown-table-hline-at-point-p) (end-of-line 1))
8896 (condition-case nil
8897 (progn
8898 (re-search-forward "|" end)
8899 (if (looking-at "[ \t]*$")
8900 (re-search-forward "|" end))
8901 (if (and (looking-at "[-:]")
8902 (re-search-forward "^[ \t]*|\\([^-:]\\)" end t))
8903 (goto-char (match-beginning 1)))
8904 (if (looking-at "[-:]")
8905 (progn
8906 (beginning-of-line 0)
8907 (markdown-table-insert-row 'below))
8908 (when (looking-at " ") (forward-char 1))))
8909 (error (markdown-table-insert-row 'below)))))
8911 (defun markdown-table-backward-cell ()
8912 "Go to the previous cell in the table."
8913 (interactive)
8914 (unless (markdown-table-at-point-p)
8915 (user-error "Not at a table"))
8916 (markdown-table-align)
8917 (when (markdown-table-hline-at-point-p) (end-of-line 1))
8918 (condition-case nil
8919 (progn
8920 (re-search-backward "|" (markdown-table-begin))
8921 (re-search-backward "|" (markdown-table-begin)))
8922 (error (user-error "Cannot move to previous table cell")))
8923 (while (looking-at "|\\([-:]\\|[ \t]*$\\)")
8924 (re-search-backward "|" (markdown-table-begin)))
8925 (when (looking-at "| ?") (goto-char (match-end 0))))
8927 (defun markdown-table-transpose ()
8928 "Transpose table at point.
8929 Horizontal separator lines will be eliminated."
8930 (interactive)
8931 (unless (markdown-table-at-point-p)
8932 (user-error "Not at a table"))
8933 (let* ((table (buffer-substring-no-properties
8934 (markdown-table-begin) (markdown-table-end)))
8935 ;; Convert table to a Lisp structure
8936 (table (delq nil
8937 (mapcar
8938 (lambda (x)
8939 (unless (string-match-p
8940 markdown-table-hline-regexp x)
8941 (markdown--split-string x "\\s-*|\\s-*")))
8942 (markdown--split-string table "[ \t]*\n[ \t]*"))))
8943 (dline_old (markdown-table-get-dline))
8944 (col_old (markdown-table-get-column))
8945 (contents (mapcar (lambda (_)
8946 (let ((tp table))
8947 (mapcar
8948 (lambda (_)
8949 (prog1
8950 (pop (car tp))
8951 (setq tp (cdr tp))))
8952 table)))
8953 (car table))))
8954 (goto-char (markdown-table-begin))
8955 (re-search-forward "|") (backward-char)
8956 (delete-region (point) (markdown-table-end))
8957 (insert (mapconcat
8958 (lambda(x)
8959 (concat "| " (mapconcat 'identity x " | " ) " |\n"))
8960 contents ""))
8961 (markdown-table-goto-dline col_old)
8962 (markdown-table-goto-column dline_old))
8963 (markdown-table-align))
8965 (defun markdown-table-sort-lines (&optional sorting-type)
8966 "Sort table lines according to the column at point.
8968 The position of point indicates the column to be used for
8969 sorting, and the range of lines is the range between the nearest
8970 horizontal separator lines, or the entire table of no such lines
8971 exist. If point is before the first column, user will be prompted
8972 for the sorting column. If there is an active region, the mark
8973 specifies the first line and the sorting column, while point
8974 should be in the last line to be included into the sorting.
8976 The command then prompts for the sorting type which can be
8977 alphabetically or numerically. Sorting in reverse order is also
8978 possible.
8980 If SORTING-TYPE is specified when this function is called from a
8981 Lisp program, no prompting will take place. SORTING-TYPE must be
8982 a character, any of (?a ?A ?n ?N) where the capital letters
8983 indicate that sorting should be done in reverse order."
8984 (interactive)
8985 (unless (markdown-table-at-point-p)
8986 (user-error "Not at a table"))
8987 ;; Set sorting type and column used for sorting
8988 (let ((column (let ((c (markdown-table-get-column)))
8989 (cond ((> c 0) c)
8990 ((called-interactively-p 'any)
8991 (read-number "Use column N for sorting: "))
8992 (t 1))))
8993 (sorting-type
8994 (or sorting-type
8995 (read-char-exclusive
8996 "Sort type: [a]lpha [n]umeric (A/N means reversed): "))))
8997 (save-restriction
8998 ;; Narrow buffer to appropriate sorting area
8999 (if (region-active-p)
9000 (narrow-to-region
9001 (save-excursion
9002 (progn
9003 (goto-char (region-beginning)) (line-beginning-position)))
9004 (save-excursion
9005 (progn
9006 (goto-char (region-end)) (line-end-position))))
9007 (let ((start (markdown-table-begin))
9008 (end (markdown-table-end)))
9009 (narrow-to-region
9010 (save-excursion
9011 (if (re-search-backward
9012 markdown-table-hline-regexp start t)
9013 (line-beginning-position 2)
9014 start))
9015 (if (save-excursion (re-search-forward
9016 markdown-table-hline-regexp end t))
9017 (match-beginning 0)
9018 end))))
9019 ;; Determine arguments for `sort-subr'
9020 (let* ((extract-key-from-cell
9021 (cl-case sorting-type
9022 ((?a ?A) #'markdown--remove-invisible-markup) ;; #'identity)
9023 ((?n ?N) #'string-to-number)
9024 (t (user-error "Invalid sorting type: %c" sorting-type))))
9025 (predicate
9026 (cl-case sorting-type
9027 ((?n ?N) #'<)
9028 ((?a ?A) #'string<))))
9029 ;; Sort selected area
9030 (goto-char (point-min))
9031 (sort-subr (memq sorting-type '(?A ?N))
9032 (lambda ()
9033 (forward-line)
9034 (while (and (not (eobp))
9035 (not (looking-at
9036 markdown-table-dline-regexp)))
9037 (forward-line)))
9038 #'end-of-line
9039 (lambda ()
9040 (funcall extract-key-from-cell
9041 (markdown-table-get-cell column)))
9043 predicate)
9044 (goto-char (point-min))))))
9046 (defun markdown-table-convert-region (begin end &optional separator)
9047 "Convert region from BEGIN to END to table with SEPARATOR.
9049 If every line contains at least one TAB character, the function
9050 assumes that the material is tab separated (TSV). If every line
9051 contains a comma, comma-separated values (CSV) are assumed. If
9052 not, lines are split at whitespace into cells.
9054 You can use a prefix argument to force a specific separator:
9055 \\[universal-argument] once forces CSV, \\[universal-argument]
9056 twice forces TAB, and \\[universal-argument] three times will
9057 prompt for a regular expression to match the separator, and a
9058 numeric argument N indicates that at least N consecutive
9059 spaces, or alternatively a TAB should be used as the separator."
9061 (interactive "r\nP")
9062 (let* ((begin (min begin end)) (end (max begin end)) re)
9063 (goto-char begin) (beginning-of-line 1)
9064 (setq begin (point-marker))
9065 (goto-char end)
9066 (if (bolp) (backward-char 1) (end-of-line 1))
9067 (setq end (point-marker))
9068 (when (equal separator '(64))
9069 (setq separator (read-regexp "Regexp for cell separator: ")))
9070 (unless separator
9071 ;; Get the right cell separator
9072 (goto-char begin)
9073 (setq separator
9074 (cond
9075 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
9076 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
9077 (t 1))))
9078 (goto-char begin)
9079 (if (equal separator '(4))
9080 ;; Parse CSV
9081 (while (< (point) end)
9082 (cond
9083 ((looking-at "^") (insert "| "))
9084 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
9085 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
9086 (replace-match "\\1") (if (looking-at "\"") (insert "\"")))
9087 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
9088 ((looking-at "[ \t]*,") (replace-match " | "))
9089 (t (beginning-of-line 2))))
9090 (setq re
9091 (cond
9092 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
9093 ((equal separator '(16)) "^\\|\t")
9094 ((integerp separator)
9095 (if (< separator 1)
9096 (user-error "Cell separator must contain one or more spaces")
9097 (format "^ *\\| *\t *\\| \\{%d,\\}" separator)))
9098 ((stringp separator) (format "^ *\\|%s" separator))
9099 (t (error "Invalid cell separator"))))
9100 (while (re-search-forward re end t) (replace-match "| " t t)))
9101 (goto-char begin)
9102 (markdown-table-align)))
9105 ;;; ElDoc Support
9107 (defun markdown-eldoc-function ()
9108 "Return a helpful string when appropriate based on context.
9109 * Report URL when point is at a hidden URL.
9110 * Report language name when point is a code block with hidden markup."
9111 (cond
9112 ;; Hidden URL or reference for inline link
9113 ((and (or (thing-at-point-looking-at markdown-regex-link-inline)
9114 (thing-at-point-looking-at markdown-regex-link-reference))
9115 (or markdown-hide-urls markdown-hide-markup))
9116 (let* ((imagep (string-equal (match-string 1) "!"))
9117 (edit-keys (markdown--substitute-command-keys
9118 (if imagep
9119 "\\[markdown-insert-image]"
9120 "\\[markdown-insert-link]")))
9121 (edit-str (propertize edit-keys 'face 'font-lock-constant-face))
9122 (referencep (string-equal (match-string 5) "["))
9123 (object (if referencep "reference" "URL")))
9124 (format "Hidden %s (%s to edit): %s" object edit-str
9125 (if referencep
9126 (concat
9127 (propertize "[" 'face 'markdown-markup-face)
9128 (propertize (match-string-no-properties 6)
9129 'face 'markdown-reference-face)
9130 (propertize "]" 'face 'markdown-markup-face))
9131 (propertize (match-string-no-properties 6)
9132 'face 'markdown-url-face)))))
9133 ;; Hidden language name for fenced code blocks
9134 ((and (markdown-code-block-at-point-p)
9135 (not (get-text-property (point) 'markdown-pre))
9136 markdown-hide-markup)
9137 (let ((lang (save-excursion (markdown-code-block-lang))))
9138 (unless lang (setq lang "[unspecified]"))
9139 (format "Hidden code block language: %s (%s to toggle markup)"
9140 (propertize lang 'face 'markdown-language-keyword-face)
9141 (markdown--substitute-command-keys
9142 "\\[markdown-toggle-markup-hiding]"))))))
9145 ;;; Mode Definition ==========================================================
9147 (defun markdown-show-version ()
9148 "Show the version number in the minibuffer."
9149 (interactive)
9150 (message "markdown-mode, version %s" markdown-mode-version))
9152 (defun markdown-mode-info ()
9153 "Open the `markdown-mode' homepage."
9154 (interactive)
9155 (browse-url "https://jblevins.org/projects/markdown-mode/"))
9157 ;;;###autoload
9158 (define-derived-mode markdown-mode text-mode "Markdown"
9159 "Major mode for editing Markdown files."
9160 ;; Natural Markdown tab width
9161 (setq tab-width 4)
9162 ;; Comments
9163 (setq-local comment-start "<!-- ")
9164 (setq-local comment-end " -->")
9165 (setq-local comment-start-skip "<!--[ \t]*")
9166 (setq-local comment-column 0)
9167 (setq-local comment-auto-fill-only-comments nil)
9168 (setq-local comment-use-syntax t)
9169 ;; Syntax
9170 (add-hook 'syntax-propertize-extend-region-functions
9171 #'markdown-syntax-propertize-extend-region)
9172 (add-hook 'jit-lock-after-change-extend-region-functions
9173 #'markdown-font-lock-extend-region-function t t)
9174 (setq-local syntax-propertize-function #'markdown-syntax-propertize)
9175 (syntax-propertize (point-max)) ;; Propertize before hooks run, etc.
9176 ;; Font lock.
9177 (setq font-lock-defaults
9178 '(markdown-mode-font-lock-keywords
9179 nil nil nil nil
9180 (font-lock-multiline . t)
9181 (font-lock-syntactic-face-function . markdown-syntactic-face)
9182 (font-lock-extra-managed-props . (composition display invisible))))
9183 (if markdown-hide-markup
9184 (add-to-invisibility-spec 'markdown-markup)
9185 (remove-from-invisibility-spec 'markdown-markup))
9186 ;; Wiki links
9187 (markdown-setup-wiki-link-hooks)
9188 ;; Math mode
9189 (when markdown-enable-math (markdown-toggle-math t))
9190 ;; Add a buffer-local hook to reload after file-local variables are read
9191 (add-hook 'hack-local-variables-hook #'markdown-handle-local-variables nil t)
9192 ;; For imenu support
9193 (setq imenu-create-index-function
9194 (if markdown-nested-imenu-heading-index
9195 #'markdown-imenu-create-nested-index
9196 #'markdown-imenu-create-flat-index))
9197 ;; For menu support in XEmacs
9198 (easy-menu-add markdown-mode-menu markdown-mode-map)
9199 ;; Defun movement
9200 (setq-local beginning-of-defun-function #'markdown-beginning-of-defun)
9201 (setq-local end-of-defun-function #'markdown-end-of-defun)
9202 ;; Paragraph filling
9203 (setq-local fill-paragraph-function #'markdown-fill-paragraph)
9204 (setq-local paragraph-start
9205 ;; Should match start of lines that start or separate paragraphs
9206 (mapconcat #'identity
9208 "\f" ; starts with a literal line-feed
9209 "[ \t\f]*$" ; space-only line
9210 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9211 "[ \t]*[*+-][ \t]+" ; unordered list item
9212 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
9213 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
9214 "[ \t]*:[ \t]+" ; definition
9215 "^|" ; table or Pandoc line block
9217 "\\|"))
9218 (setq-local paragraph-separate
9219 ;; Should match lines that separate paragraphs without being
9220 ;; part of any paragraph:
9221 (mapconcat #'identity
9222 '("[ \t\f]*$" ; space-only line
9223 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9224 ;; The following is not ideal, but the Fill customization
9225 ;; options really only handle paragraph-starting prefixes,
9226 ;; not paragraph-ending suffixes:
9227 ".* $" ; line ending in two spaces
9228 "^#+"
9229 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
9230 "\\|"))
9231 (setq-local adaptive-fill-first-line-regexp "\\`[ \t]*[A-Z]?>[ \t]*?\\'")
9232 (setq-local adaptive-fill-regexp "\\s-*")
9233 (setq-local adaptive-fill-function #'markdown-adaptive-fill-function)
9234 (setq-local fill-forward-paragraph-function #'markdown-fill-forward-paragraph)
9235 ;; Outline mode
9236 (setq-local outline-regexp markdown-regex-header)
9237 (setq-local outline-level #'markdown-outline-level)
9238 ;; Cause use of ellipses for invisible text.
9239 (add-to-invisibility-spec '(outline . t))
9240 ;; ElDoc support
9241 (if (eval-when-compile (fboundp 'add-function))
9242 (add-function :before-until (local 'eldoc-documentation-function)
9243 #'markdown-eldoc-function)
9244 (setq-local eldoc-documentation-function #'markdown-eldoc-function))
9245 ;; Inhibiting line-breaking:
9246 ;; Separating out each condition into a separate function so that users can
9247 ;; override if desired (with remove-hook)
9248 (add-hook 'fill-nobreak-predicate
9249 #'markdown-line-is-reference-definition-p nil t)
9250 (add-hook 'fill-nobreak-predicate
9251 #'markdown-pipe-at-bol-p nil t)
9253 ;; Indentation
9254 (setq-local indent-line-function markdown-indent-function)
9256 ;; Flyspell
9257 (setq-local flyspell-generic-check-word-predicate
9258 #'markdown-flyspell-check-word-p)
9260 ;; Electric quoting
9261 (add-hook 'electric-quote-inhibit-functions
9262 #'markdown--inhibit-electric-quote nil :local)
9264 ;; Backwards compatibility with markdown-css-path
9265 (when (boundp 'markdown-css-path)
9266 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
9267 (add-to-list 'markdown-css-paths markdown-css-path))
9269 ;; Prepare hooks for XEmacs compatibility
9270 (when (featurep 'xemacs)
9271 (make-local-hook 'after-change-functions)
9272 (make-local-hook 'font-lock-extend-region-functions)
9273 (make-local-hook 'window-configuration-change-hook))
9275 ;; Make checkboxes buttons
9276 (when markdown-make-gfm-checkboxes-buttons
9277 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
9278 (add-hook 'after-change-functions #'markdown-gfm-checkbox-after-change-function t t)
9279 (add-hook 'change-major-mode-hook #'markdown-remove-gfm-checkbox-overlays t t))
9281 ;; edit-indirect
9282 (add-hook 'edit-indirect-after-commit-functions
9283 #'markdown--edit-indirect-after-commit-function
9284 nil 'local)
9286 ;; Marginalized headings
9287 (when markdown-marginalize-headers
9288 (add-hook 'window-configuration-change-hook
9289 #'markdown-marginalize-update-current nil t))
9291 ;; add live preview export hook
9292 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
9293 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
9295 ;;;###autoload
9296 (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode) t)
9297 ;;;###autoload
9298 (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode) t)
9301 ;;; GitHub Flavored Markdown Mode ============================================
9303 (defvar gfm-mode-hook nil
9304 "Hook run when entering GFM mode.")
9306 ;;;###autoload
9307 (define-derived-mode gfm-mode markdown-mode "GFM"
9308 "Major mode for editing GitHub Flavored Markdown files."
9309 (setq markdown-link-space-sub-char "-")
9310 (setq markdown-wiki-link-search-subdirectories t)
9311 (setq-local markdown-table-at-point-p-function 'gfm--table-at-point-p)
9312 (markdown-gfm-parse-buffer-for-languages))
9314 (define-obsolete-variable-alias
9315 'gfm-font-lock-keywords
9316 'markdown-mode-font-lock-keywords "v2.4")
9319 ;;; Viewing modes
9321 (defcustom markdown-hide-markup-in-view-modes t
9322 "Enable hidden markup mode in `markdown-view-mode' and `gfm-view-mode'."
9323 :group 'markdown
9324 :type 'boolean
9325 :safe 'booleanp)
9327 (defvar markdown-view-mode-map
9328 (let ((map (make-sparse-keymap)))
9329 (define-key map (kbd "p") #'markdown-outline-previous)
9330 (define-key map (kbd "n") #'markdown-outline-next)
9331 (define-key map (kbd "f") #'markdown-outline-next-same-level)
9332 (define-key map (kbd "b") #'markdown-outline-previous-same-level)
9333 (define-key map (kbd "u") #'markdown-outline-up)
9334 (define-key map (kbd "DEL") #'scroll-down-command)
9335 (define-key map (kbd "SPC") #'scroll-up-command)
9336 (define-key map (kbd ">") #'end-of-buffer)
9337 (define-key map (kbd "<") #'beginning-of-buffer)
9338 (define-key map (kbd "q") #'kill-this-buffer)
9339 (define-key map (kbd "?") #'describe-mode)
9340 map)
9341 "Keymap for `markdown-view-mode'.")
9343 (define-derived-mode markdown-view-mode markdown-mode "Markdown-View"
9344 "Major mode for viewing Markdown content."
9345 (setq-local markdown-hide-markup markdown-hide-markup-in-view-modes)
9346 (read-only-mode 1))
9348 (defvar gfm-view-mode-map
9349 markdown-view-mode-map
9350 "Keymap for `gfm-view-mode'.")
9352 (define-derived-mode gfm-view-mode gfm-mode "GFM-View"
9353 "Major mode for viewing GitHub Flavored Markdown content."
9354 (setq-local markdown-hide-markup markdown-hide-markup-in-view-modes)
9355 (read-only-mode 1))
9358 ;;; Live Preview Mode ============================================
9359 (define-minor-mode markdown-live-preview-mode
9360 "Toggle native previewing on save for a specific markdown file."
9361 :lighter " MD-Preview"
9362 (if markdown-live-preview-mode
9363 (if (markdown-live-preview-get-filename)
9364 (markdown-display-buffer-other-window (markdown-live-preview-export))
9365 (markdown-live-preview-mode -1)
9366 (user-error "Buffer %s does not visit a file" (current-buffer)))
9367 (markdown-live-preview-remove)))
9370 (provide 'markdown-mode)
9372 ;; Local Variables:
9373 ;; indent-tabs-mode: nil
9374 ;; coding: utf-8
9375 ;; End:
9376 ;;; markdown-mode.el ends here