Merge pull request #711 from tarsiiformes/one
[markdown-mode.git] / markdown-mode.el
blob0097d63db9a4859cd3eedd8d86ba0028b514ae18
1 ;;; markdown-mode.el --- Major mode for Markdown-formatted text -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2007-2022 Jason R. Blevins and markdown-mode
4 ;; contributors (see the commit log for details).
6 ;; Author: Jason R. Blevins <jblevins@xbeta.org>
7 ;; Maintainer: Jason R. Blevins <jblevins@xbeta.org>
8 ;; Created: May 24, 2007
9 ;; Version: 2.6-dev
10 ;; Package-Requires: ((emacs "26.1"))
11 ;; Keywords: Markdown, GitHub Flavored Markdown, itex
12 ;; URL: https://jblevins.org/projects/markdown-mode/
14 ;; This file is not part of GNU Emacs.
16 ;; This program is free software; you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
21 ;; This program is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
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)
44 (require 'subr-x)
46 (defvar jit-lock-start)
47 (defvar jit-lock-end)
48 (defvar flyspell-generic-check-word-predicate)
49 (defvar electric-pair-pairs)
50 (defvar sh-ancestor-alist)
52 (declare-function project-roots "project")
53 (declare-function sh-set-shell "sh-script")
56 ;;; Constants =================================================================
58 (defconst markdown-mode-version "2.6-dev"
59 "Markdown mode version number.")
61 (defconst markdown-output-buffer-name "*markdown-output*"
62 "Name of temporary buffer for markdown command output.")
65 ;;; Global Variables ==========================================================
67 (defvar markdown-reference-label-history nil
68 "History of used reference labels.")
70 (defvar markdown-live-preview-mode nil
71 "Sentinel variable for command `markdown-live-preview-mode'.")
73 (defvar markdown-gfm-language-history nil
74 "History list of languages used in the current buffer in GFM code blocks.")
77 ;;; Customizable Variables ====================================================
79 (defvar markdown-mode-hook nil
80 "Hook run when entering Markdown mode.")
82 (defvar markdown-before-export-hook nil
83 "Hook run before running Markdown to export XHTML output.
84 The hook may modify the buffer, which will be restored to it's
85 original state after exporting is complete.")
87 (defvar markdown-after-export-hook nil
88 "Hook run after XHTML output has been saved.
89 Any changes to the output buffer made by this hook will be saved.")
91 (defgroup markdown nil
92 "Major mode for editing text files in Markdown format."
93 :prefix "markdown-"
94 :group 'text
95 :link '(url-link "https://jblevins.org/projects/markdown-mode/"))
97 (defcustom markdown-command (let ((command (cl-loop for cmd in '("markdown" "pandoc" "markdown_py")
98 when (executable-find cmd)
99 return (file-name-nondirectory it))))
100 (or command "markdown"))
101 "Command to run markdown."
102 :group 'markdown
103 :type '(choice (string :tag "Shell command") (repeat (string)) function))
105 (defcustom markdown-command-needs-filename nil
106 "Set to non-nil if `markdown-command' does not accept input from stdin.
107 Instead, it will be passed a filename as the final command line
108 option. As a result, you will only be able to run Markdown from
109 buffers which are visiting a file."
110 :group 'markdown
111 :type 'boolean)
113 (defcustom markdown-open-command nil
114 "Command used for opening Markdown files directly.
115 For example, a standalone Markdown previewer. This command will
116 be called with a single argument: the filename of the current
117 buffer. It can also be a function, which will be called without
118 arguments."
119 :group 'markdown
120 :type '(choice file function (const :tag "None" nil)))
122 (defcustom markdown-open-image-command nil
123 "Command used for opening image files directly.
124 This is used at `markdown-follow-link-at-point'."
125 :group 'markdown
126 :type '(choice file function (const :tag "None" nil)))
128 (defcustom markdown-hr-strings
129 '("-------------------------------------------------------------------------------"
130 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
131 "---------------------------------------"
132 "* * * * * * * * * * * * * * * * * * * *"
133 "---------"
134 "* * * * *")
135 "Strings to use when inserting horizontal rules.
136 The first string in the list will be the default when inserting a
137 horizontal rule. Strings should be listed in decreasing order of
138 prominence (as in headings from level one to six) for use with
139 promotion and demotion functions."
140 :group 'markdown
141 :type '(repeat string))
143 (defcustom markdown-bold-underscore nil
144 "Use two underscores when inserting bold text instead of two asterisks."
145 :group 'markdown
146 :type 'boolean)
148 (defcustom markdown-italic-underscore nil
149 "Use underscores when inserting italic text instead of asterisks."
150 :group 'markdown
151 :type 'boolean)
153 (defcustom markdown-marginalize-headers nil
154 "When non-nil, put opening atx header markup in a left margin.
156 This setting goes well with `markdown-asymmetric-header'. But
157 sadly it conflicts with `linum-mode' since they both use the
158 same margin."
159 :group 'markdown
160 :type 'boolean
161 :safe 'booleanp
162 :package-version '(markdown-mode . "2.4"))
164 (defcustom markdown-marginalize-headers-margin-width 6
165 "Character width of margin used for marginalized headers.
166 The default value is based on there being six heading levels
167 defined by Markdown and HTML. Increasing this produces extra
168 whitespace on the left. Decreasing it may be preferred when
169 fewer than six nested heading levels are used."
170 :group 'markdown
171 :type 'natnump
172 :safe 'natnump
173 :package-version '(markdown-mode . "2.4"))
175 (defcustom markdown-asymmetric-header nil
176 "Determines if atx header style will be asymmetric.
177 Set to a non-nil value to use asymmetric header styling, placing
178 header markup only at the beginning of the line. By default,
179 balanced markup will be inserted at the beginning and end of the
180 line around the header title."
181 :group 'markdown
182 :type 'boolean)
184 (defcustom markdown-indent-function 'markdown-indent-line
185 "Function to use to indent."
186 :group 'markdown
187 :type 'function)
189 (defcustom markdown-indent-on-enter t
190 "Determines indentation behavior when pressing \\[newline].
191 Possible settings are nil, t, and 'indent-and-new-item.
193 When non-nil, pressing \\[newline] will call `newline-and-indent'
194 to indent the following line according to the context using
195 `markdown-indent-function'. In this case, note that
196 \\[electric-newline-and-maybe-indent] can still be used to insert
197 a newline without indentation.
199 When set to 'indent-and-new-item and the point is in a list item
200 when \\[newline] is pressed, the list will be continued on the next
201 line, where a new item will be inserted.
203 When set to nil, simply call `newline' as usual. In this case,
204 you can still indent lines using \\[markdown-cycle] and continue
205 lists with \\[markdown-insert-list-item].
207 Note that this assumes the variable `electric-indent-mode' is
208 non-nil (enabled). When it is *disabled*, the behavior of
209 \\[newline] and `\\[electric-newline-and-maybe-indent]' are
210 reversed."
211 :group 'markdown
212 :type '(choice (const :tag "Don't automatically indent" nil)
213 (const :tag "Automatically indent" t)
214 (const :tag "Automatically indent and insert new list items" indent-and-new-item)))
216 (defcustom markdown-enable-wiki-links nil
217 "Syntax highlighting for wiki links.
218 Set this to a non-nil value to turn on wiki link support by default.
219 Support can be toggled later using the `markdown-toggle-wiki-links'
220 function or \\[markdown-toggle-wiki-links]."
221 :group 'markdown
222 :type 'boolean
223 :safe 'booleanp
224 :package-version '(markdown-mode . "2.2"))
226 (defcustom markdown-wiki-link-alias-first t
227 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
228 Otherwise, they will be treated as [[PageName|alias text]]."
229 :group 'markdown
230 :type 'boolean
231 :safe 'booleanp)
233 (defcustom markdown-wiki-link-search-subdirectories nil
234 "When non-nil, search for wiki link targets in subdirectories.
235 This is the default search behavior for GitHub and is
236 automatically set to t in `gfm-mode'."
237 :group 'markdown
238 :type 'boolean
239 :safe 'booleanp
240 :package-version '(markdown-mode . "2.2"))
242 (defcustom markdown-wiki-link-search-parent-directories nil
243 "When non-nil, search for wiki link targets in parent directories.
244 This is the default search behavior of Ikiwiki."
245 :group 'markdown
246 :type 'boolean
247 :safe 'booleanp
248 :package-version '(markdown-mode . "2.2"))
250 (defcustom markdown-wiki-link-search-type nil
251 "Searching type for markdown wiki link.
253 sub-directories: search for wiki link targets in sub directories
254 parent-directories: search for wiki link targets in parent directories
255 project: search for wiki link targets under project root"
256 :group 'markdown
257 :type '(set
258 (const :tag "search wiki link from subdirectories" sub-directories)
259 (const :tag "search wiki link from parent directories" parent-directories)
260 (const :tag "search wiki link under project root" project))
261 :package-version '(markdown-mode . "2.5"))
263 (make-obsolete-variable 'markdown-wiki-link-search-subdirectories 'markdown-wiki-link-search-type "2.5")
264 (make-obsolete-variable 'markdown-wiki-link-search-parent-directories 'markdown-wiki-link-search-type "2.5")
266 (defcustom markdown-wiki-link-fontify-missing nil
267 "When non-nil, change wiki link face according to existence of target files.
268 This is expensive because it requires checking for the file each time the buffer
269 changes or the user switches windows. It is disabled by default because it may
270 cause lag when typing on slower machines."
271 :group 'markdown
272 :type 'boolean
273 :safe 'booleanp
274 :package-version '(markdown-mode . "2.2"))
276 (defcustom markdown-uri-types
277 '("acap" "cid" "data" "dav" "fax" "file" "ftp"
278 "gopher" "http" "https" "imap" "ldap" "mailto"
279 "mid" "message" "modem" "news" "nfs" "nntp"
280 "pop" "prospero" "rtsp" "service" "sip" "tel"
281 "telnet" "tip" "urn" "vemmi" "wais")
282 "Link types for syntax highlighting of URIs."
283 :group 'markdown
284 :type '(repeat (string :tag "URI scheme")))
286 (defcustom markdown-url-compose-char
287 '(?∞ ?… ?⋯ ?# ?★ ?⚓)
288 "Placeholder character for hidden URLs.
289 This may be a single character or a list of characters. In case
290 of a list, the first one that satisfies `char-displayable-p' will
291 be used."
292 :type '(choice
293 (character :tag "Single URL replacement character")
294 (repeat :tag "List of possible URL replacement characters"
295 character))
296 :package-version '(markdown-mode . "2.3"))
298 (defcustom markdown-blockquote-display-char
299 '("▌" "┃" ">")
300 "String to display when hiding blockquote markup.
301 This may be a single string or a list of string. In case of a
302 list, the first one that satisfies `char-displayable-p' will be
303 used."
304 :type 'string
305 :type '(choice
306 (string :tag "Single blockquote display string")
307 (repeat :tag "List of possible blockquote display strings" string))
308 :package-version '(markdown-mode . "2.3"))
310 (defcustom markdown-hr-display-char
311 '(?─ ?━ ?-)
312 "Character for hiding horizontal rule markup.
313 This may be a single character or a list of characters. In case
314 of a list, the first one that satisfies `char-displayable-p' will
315 be used."
316 :group 'markdown
317 :type '(choice
318 (character :tag "Single HR display character")
319 (repeat :tag "List of possible HR display characters" character))
320 :package-version '(markdown-mode . "2.3"))
322 (defcustom markdown-definition-display-char
323 '(?⁘ ?⁙ ?≡ ?⌑ ?◊ ?:)
324 "Character for replacing definition list markup.
325 This may be a single character or a list of characters. In case
326 of a list, the first one that satisfies `char-displayable-p' will
327 be used."
328 :type '(choice
329 (character :tag "Single definition list character")
330 (repeat :tag "List of possible definition list characters" character))
331 :package-version '(markdown-mode . "2.3"))
333 (defcustom markdown-enable-math nil
334 "Syntax highlighting for inline LaTeX and itex expressions.
335 Set this to a non-nil value to turn on math support by default.
336 Math support can be enabled, disabled, or toggled later using
337 `markdown-toggle-math' or \\[markdown-toggle-math]."
338 :group 'markdown
339 :type 'boolean
340 :safe 'booleanp)
341 (make-variable-buffer-local 'markdown-enable-math)
343 (defcustom markdown-enable-html t
344 "Enable font-lock support for HTML tags and attributes."
345 :group 'markdown
346 :type 'boolean
347 :safe 'booleanp
348 :package-version '(markdown-mode . "2.4"))
350 (defcustom markdown-enable-highlighting-syntax nil
351 "Enable highlighting syntax."
352 :group 'markdown
353 :type 'boolean
354 :safe 'booleanp
355 :package-version '(markdown-mode . "2.5"))
357 (defcustom markdown-css-paths nil
358 "List of URLs of CSS files to link to in the output XHTML."
359 :group 'markdown
360 :type '(repeat (string :tag "CSS File Path")))
362 (defcustom markdown-content-type "text/html"
363 "Content type string for the http-equiv header in XHTML output.
364 When set to an empty string, this attribute is omitted. Defaults to
365 `text/html'."
366 :group 'markdown
367 :type 'string)
369 (defcustom markdown-coding-system nil
370 "Character set string for the http-equiv header in XHTML output.
371 Defaults to `buffer-file-coding-system' (and falling back to
372 `utf-8' when not available). Common settings are `iso-8859-1'
373 and `iso-latin-1'. Use `list-coding-systems' for more choices."
374 :group 'markdown
375 :type 'coding-system)
377 (defcustom markdown-export-kill-buffer t
378 "Kill output buffer after HTML export.
379 When non-nil, kill the HTML output buffer after
380 exporting with `markdown-export'."
381 :group 'markdown
382 :type 'boolean
383 :safe 'booleanp
384 :package-version '(markdown-mode . "2.4"))
386 (defcustom markdown-xhtml-header-content ""
387 "Additional content to include in the XHTML <head> block."
388 :group 'markdown
389 :type 'string)
391 (defcustom markdown-xhtml-body-preamble ""
392 "Content to include in the XHTML <body> block, before the output."
393 :group 'markdown
394 :type 'string
395 :safe 'stringp
396 :package-version '(markdown-mode . "2.4"))
398 (defcustom markdown-xhtml-body-epilogue ""
399 "Content to include in the XHTML <body> block, after the output."
400 :group 'markdown
401 :type 'string
402 :safe 'stringp
403 :package-version '(markdown-mode . "2.4"))
405 (defcustom markdown-xhtml-standalone-regexp
406 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
407 "Regexp indicating whether `markdown-command' output is standalone XHTML."
408 :group 'markdown
409 :type 'regexp)
411 (defcustom markdown-link-space-sub-char "_"
412 "Character to use instead of spaces when mapping wiki links to filenames."
413 :group 'markdown
414 :type 'string)
416 (defcustom markdown-reference-location 'header
417 "Position where new reference definitions are inserted in the document."
418 :group 'markdown
419 :type '(choice (const :tag "At the end of the document" end)
420 (const :tag "Immediately after the current block" immediately)
421 (const :tag "At the end of the subtree" subtree)
422 (const :tag "Before next header" header)))
424 (defcustom markdown-footnote-location 'end
425 "Position where new footnotes are inserted in the document."
426 :group 'markdown
427 :type '(choice (const :tag "At the end of the document" end)
428 (const :tag "Immediately after the current block" immediately)
429 (const :tag "At the end of the subtree" subtree)
430 (const :tag "Before next header" header)))
432 (defcustom markdown-footnote-display '((raise 0.2) (height 0.8))
433 "Display specification for footnote markers and inline footnotes.
434 By default, footnote text is reduced in size and raised. Set to
435 nil to disable this."
436 :group 'markdown
437 :type '(choice (sexp :tag "Display specification")
438 (const :tag "Don't set display property" nil))
439 :package-version '(markdown-mode . "2.4"))
441 (defcustom markdown-sub-superscript-display
442 '(((raise -0.3) (height 0.7)) . ((raise 0.3) (height 0.7)))
443 "Display specification for subscript and superscripts.
444 The car is used for subscript, the cdr is used for superscripts."
445 :group 'markdown
446 :type '(cons (choice (sexp :tag "Subscript form")
447 (const :tag "No lowering" nil))
448 (choice (sexp :tag "Superscript form")
449 (const :tag "No raising" nil)))
450 :package-version '(markdown-mode . "2.4"))
452 (defcustom markdown-unordered-list-item-prefix " * "
453 "String inserted before unordered list items."
454 :group 'markdown
455 :type 'string)
457 (defcustom markdown-ordered-list-enumeration t
458 "When non-nil, use enumerated numbers(1. 2. 3. etc.) for ordered list marker.
459 While nil, always uses '1.' for the marker"
460 :group 'markdown
461 :type 'boolean
462 :package-version '(markdown-mode . "2.5"))
464 (defcustom markdown-nested-imenu-heading-index t
465 "Use nested or flat imenu heading index.
466 A nested index may provide more natural browsing from the menu,
467 but a flat list may allow for faster keyboard navigation via tab
468 completion."
469 :group 'markdown
470 :type 'boolean
471 :safe 'booleanp
472 :package-version '(markdown-mode . "2.2"))
474 (defcustom markdown-add-footnotes-to-imenu t
475 "Add footnotes to end of imenu heading index."
476 :group 'markdown
477 :type 'boolean
478 :safe 'booleanp
479 :package-version '(markdown-mode . "2.4"))
481 (defcustom markdown-make-gfm-checkboxes-buttons t
482 "When non-nil, make GFM checkboxes into buttons."
483 :group 'markdown
484 :type 'boolean)
486 (defcustom markdown-use-pandoc-style-yaml-metadata nil
487 "When non-nil, allow YAML metadata anywhere in the document."
488 :group 'markdown
489 :type 'boolean)
491 (defcustom markdown-split-window-direction 'any
492 "Preference for splitting windows for static and live preview.
493 The default value is 'any, which instructs Emacs to use
494 `split-window-sensibly' to automatically choose how to split
495 windows based on the values of `split-width-threshold' and
496 `split-height-threshold' and the available windows. To force
497 vertically split (left and right) windows, set this to 'vertical
498 or 'right. To force horizontally split (top and bottom) windows,
499 set this to 'horizontal or 'below.
501 If this value is 'any and `display-buffer-alist' is set then
502 `display-buffer' is used for open buffer function"
503 :group 'markdown
504 :type '(choice (const :tag "Automatic" any)
505 (const :tag "Right (vertical)" right)
506 (const :tag "Below (horizontal)" below))
507 :package-version '(markdown-mode . "2.2"))
509 (defcustom markdown-live-preview-window-function
510 #'markdown-live-preview-window-eww
511 "Function to display preview of Markdown output within Emacs.
512 Function must update the buffer containing the preview and return
513 the buffer."
514 :group 'markdown
515 :type 'function)
517 (defcustom markdown-live-preview-delete-export 'delete-on-destroy
518 "Delete exported HTML file when using `markdown-live-preview-export'.
519 If set to 'delete-on-export, delete on every export. When set to
520 'delete-on-destroy delete when quitting from command
521 `markdown-live-preview-mode'. Never delete if set to nil."
522 :group 'markdown
523 :type '(choice
524 (const :tag "Delete on every export" delete-on-export)
525 (const :tag "Delete when quitting live preview" delete-on-destroy)
526 (const :tag "Never delete" nil)))
528 (defcustom markdown-list-indent-width 4
529 "Depth of indentation for markdown lists.
530 Used in `markdown-demote-list-item' and
531 `markdown-promote-list-item'."
532 :group 'markdown
533 :type 'integer)
535 (defcustom markdown-enable-prefix-prompts t
536 "Display prompts for certain prefix commands.
537 Set to nil to disable these prompts."
538 :group 'markdown
539 :type 'boolean
540 :safe 'booleanp
541 :package-version '(markdown-mode . "2.3"))
543 (defcustom markdown-gfm-additional-languages nil
544 "Extra languages made available when inserting GFM code blocks.
545 Language strings must have be trimmed of whitespace and not
546 contain any curly braces. They may be of arbitrary
547 capitalization, though."
548 :group 'markdown
549 :type '(repeat (string :validate markdown-validate-language-string)))
551 (defcustom markdown-gfm-use-electric-backquote t
552 "Use `markdown-electric-backquote' when backquote is hit three times."
553 :group 'markdown
554 :type 'boolean)
556 (defcustom markdown-gfm-downcase-languages t
557 "If non-nil, downcase suggested languages.
558 This applies to insertions done with
559 `markdown-electric-backquote'."
560 :group 'markdown
561 :type 'boolean)
563 (defcustom markdown-edit-code-block-default-mode 'normal-mode
564 "Default mode to use for editing code blocks.
565 This mode is used when automatic detection fails, such as for GFM
566 code blocks with no language specified."
567 :group 'markdown
568 :type '(choice function (const :tag "None" nil))
569 :package-version '(markdown-mode . "2.4"))
571 (defcustom markdown-gfm-uppercase-checkbox nil
572 "If non-nil, use [X] for completed checkboxes, [x] otherwise."
573 :group 'markdown
574 :type 'boolean
575 :safe 'booleanp)
577 (defcustom markdown-hide-urls nil
578 "Hide URLs of inline links and reference tags of reference links.
579 Such URLs will be replaced by a single customizable
580 character, defined by `markdown-url-compose-char', but are still part
581 of the buffer. Links can be edited interactively with
582 \\[markdown-insert-link] or, for example, by deleting the final
583 parenthesis to remove the invisibility property. You can also
584 hover your mouse pointer over the link text to see the URL.
585 Set this to a non-nil value to turn this feature on by default.
586 You can interactively set the value of this variable by calling
587 `markdown-toggle-url-hiding', pressing \\[markdown-toggle-url-hiding],
588 or from the menu Markdown > Links & Images menu."
589 :group 'markdown
590 :type 'boolean
591 :safe 'booleanp
592 :package-version '(markdown-mode . "2.3"))
593 (make-variable-buffer-local 'markdown-hide-urls)
595 (defcustom markdown-translate-filename-function #'identity
596 "Function to use to translate filenames when following links.
597 \\<markdown-mode-map>\\[markdown-follow-thing-at-point] and \\[markdown-follow-link-at-point]
598 call this function with the filename as only argument whenever
599 they encounter a filename (instead of a URL) to be visited and
600 use its return value instead of the filename in the link. For
601 example, if absolute filenames are actually relative to a server
602 root directory, you can set
603 `markdown-translate-filename-function' to a function that
604 prepends the root directory to the given filename."
605 :group 'markdown
606 :type 'function
607 :risky t
608 :package-version '(markdown-mode . "2.4"))
610 (defcustom markdown-max-image-size nil
611 "Maximum width and height for displayed inline images.
612 This variable may be nil or a cons cell (MAX-WIDTH . MAX-HEIGHT).
613 When nil, use the actual size. Otherwise, use ImageMagick to
614 resize larger images to be of the given maximum dimensions. This
615 requires Emacs to be built with ImageMagick support."
616 :group 'markdown
617 :package-version '(markdown-mode . "2.4")
618 :type '(choice
619 (const :tag "Use actual image width" nil)
620 (cons (choice (sexp :tag "Maximum width in pixels")
621 (const :tag "No maximum width" nil))
622 (choice (sexp :tag "Maximum height in pixels")
623 (const :tag "No maximum height" nil)))))
625 (defcustom markdown-mouse-follow-link t
626 "Non-nil means mouse on a link will follow the link.
627 This variable must be set before loading markdown-mode."
628 :group 'markdown
629 :type 'boolean
630 :safe 'booleanp
631 :package-version '(markdown-mode . "2.5"))
633 (defcustom markdown-table-align-p t
634 "Non-nil means that table is aligned after table operation."
635 :group 'markdown
636 :type 'boolean
637 :safe 'booleanp
638 :package-version '(markdown-mode . "2.5"))
640 (defcustom markdown-fontify-whole-heading-line nil
641 "Non-nil means fontify the whole line for headings.
642 This is useful when setting a background color for the
643 markdown-header-face-* faces."
644 :group 'markdown
645 :type 'boolean
646 :safe 'booleanp
647 :package-version '(markdown-mode . "2.5"))
650 ;;; Markdown-Specific `rx' Macro ==============================================
652 ;; Based on python-rx from python.el.
653 (eval-and-compile
654 (defconst markdown-rx-constituents
655 `((newline . ,(rx "\n"))
656 ;; Note: #405 not consider markdown-list-indent-width however this is never used
657 (indent . ,(rx (or (repeat 4 " ") "\t")))
658 (block-end . ,(rx (and (or (one-or-more (zero-or-more blank) "\n") line-end))))
659 (numeral . ,(rx (and (one-or-more (any "0-9#")) ".")))
660 (bullet . ,(rx (any "*+:-")))
661 (list-marker . ,(rx (or (and (one-or-more (any "0-9#")) ".")
662 (any "*+:-"))))
663 (checkbox . ,(rx "[" (any " xX") "]")))
664 "Markdown-specific sexps for `markdown-rx'")
666 (defun markdown-rx-to-string (form &optional no-group)
667 "Markdown mode specialized `rx-to-string' function.
668 This variant supports named Markdown expressions in FORM.
669 NO-GROUP non-nil means don't put shy groups around the result."
670 (let ((rx-constituents (append markdown-rx-constituents rx-constituents)))
671 (rx-to-string form no-group)))
673 (defmacro markdown-rx (&rest regexps)
674 "Markdown mode specialized rx macro.
675 This variant of `rx' supports common Markdown named REGEXPS."
676 (cond ((null regexps)
677 (error "No regexp"))
678 ((cdr regexps)
679 (markdown-rx-to-string `(and ,@regexps) t))
681 (markdown-rx-to-string (car regexps) t)))))
684 ;;; Regular Expressions =======================================================
686 (defconst markdown-regex-comment-start
687 "<!--"
688 "Regular expression matches HTML comment opening.")
690 (defconst markdown-regex-comment-end
691 "--[ \t]*>"
692 "Regular expression matches HTML comment closing.")
694 (defconst markdown-regex-link-inline
695 "\\(?1:!\\)?\\(?2:\\[\\)\\(?3:\\^?\\(?:\\\\\\]\\|[^]]\\)*\\|\\)\\(?4:\\]\\)\\(?5:(\\)\\s-*\\(?6:[^)]*?\\)\\(?:\\s-+\\(?7:\"[^\"]*\"\\)\\)?\\s-*\\(?8:)\\)"
696 "Regular expression for a [text](file) or an image link ![text](file).
697 Group 1 matches the leading exclamation point (optional).
698 Group 2 matches the opening square bracket.
699 Group 3 matches the text inside the square brackets.
700 Group 4 matches the closing square bracket.
701 Group 5 matches the opening parenthesis.
702 Group 6 matches the URL.
703 Group 7 matches the title (optional).
704 Group 8 matches the closing parenthesis.")
706 (defconst markdown-regex-link-reference
707 "\\(?1:!\\)?\\(?2:\\[\\)\\(?3:[^]^][^]]*\\|\\)\\(?4:\\]\\)[ ]?\\(?5:\\[\\)\\(?6:[^]]*?\\)\\(?7:\\]\\)"
708 "Regular expression for a reference link [text][id].
709 Group 1 matches the leading exclamation point (optional).
710 Group 2 matches the opening square bracket for the link text.
711 Group 3 matches the text inside the square brackets.
712 Group 4 matches the closing square bracket for the link text.
713 Group 5 matches the opening square bracket for the reference label.
714 Group 6 matches the reference label.
715 Group 7 matches the closing square bracket for the reference label.")
717 (defconst markdown-regex-reference-definition
718 "^ \\{0,3\\}\\(?1:\\[\\)\\(?2:[^]\n]+?\\)\\(?3:\\]\\)\\(?4::\\)\\s *\\(?5:.*?\\)\\s *\\(?6: \"[^\"]*\"$\\|$\\)"
719 "Regular expression for a reference definition.
720 Group 1 matches the opening square bracket.
721 Group 2 matches the reference label.
722 Group 3 matches the closing square bracket.
723 Group 4 matches the colon.
724 Group 5 matches the URL.
725 Group 6 matches the title attribute (optional).")
727 (defconst markdown-regex-footnote
728 "\\(?1:\\[\\^\\)\\(?2:.+?\\)\\(?3:\\]\\)"
729 "Regular expression for a footnote marker [^fn].
730 Group 1 matches the opening square bracket and carat.
731 Group 2 matches only the label, without the surrounding markup.
732 Group 3 matches the closing square bracket.")
734 (defconst markdown-regex-header
735 "^\\(?:\\(?1:[^\r\n\t -].*\\)\n\\(?:\\(?2:=+\\)\\|\\(?3:-+\\)\\)\\|\\(?4:#+[ \t]+\\)\\(?5:.*?\\)\\(?6:[ \t]*#*\\)\\)$"
736 "Regexp identifying Markdown headings.
737 Group 1 matches the text of a setext heading.
738 Group 2 matches the underline of a level-1 setext heading.
739 Group 3 matches the underline of a level-2 setext heading.
740 Group 4 matches the opening hash marks of an atx heading and whitespace.
741 Group 5 matches the text, without surrounding whitespace, of an atx heading.
742 Group 6 matches the closing whitespace and hash marks of an atx heading.")
744 (defconst markdown-regex-header-setext
745 "^\\([^\r\n\t -].*\\)\n\\(=+\\|-+\\)$"
746 "Regular expression for generic setext-style (underline) headers.")
748 (defconst markdown-regex-header-atx
749 "^\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
750 "Regular expression for generic atx-style (hash mark) headers.")
752 (defconst markdown-regex-hr
753 (rx line-start
754 (group (or (and (repeat 3 (and "*" (? " "))) (* (any "* ")))
755 (and (repeat 3 (and "-" (? " "))) (* (any "- ")))
756 (and (repeat 3 (and "_" (? " "))) (* (any "_ ")))))
757 line-end)
758 "Regular expression for matching Markdown horizontal rules.")
760 (defconst markdown-regex-code
761 "\\(?:\\`\\|[^\\]\\)\\(?1:\\(?2:`+\\)\\(?3:\\(?:.\\|\n[^\n]\\)*?[^`]\\)\\(?4:\\2\\)\\)\\(?:[^`]\\|\\'\\)"
762 "Regular expression for matching inline code fragments.
764 Group 1 matches the entire code fragment including the backquotes.
765 Group 2 matches the opening backquotes.
766 Group 3 matches the code fragment itself, without backquotes.
767 Group 4 matches the closing backquotes.
769 The leading, unnumbered group ensures that the leading backquote
770 character is not escaped.
771 The last group, also unnumbered, requires that the character
772 following the code fragment is not a backquote.
773 Note that \\(?:.\\|\n[^\n]\\) matches any character, including newlines,
774 but not two newlines in a row.")
776 (defconst markdown-regex-kbd
777 "\\(?1:<kbd>\\)\\(?2:\\(?:.\\|\n[^\n]\\)*?\\)\\(?3:</kbd>\\)"
778 "Regular expression for matching <kbd> tags.
779 Groups 1 and 3 match the opening and closing tags.
780 Group 2 matches the key sequence.")
782 (defconst markdown-regex-gfm-code-block-open
783 "^[[:blank:]]*\\(?1:```\\)\\(?2:[[:blank:]]*{?[[:blank:]]*\\)\\(?3:[^`[:space:]]+?\\)?\\(?:[[:blank:]]+\\(?4:.+?\\)\\)?\\(?5:[[:blank:]]*}?[[:blank:]]*\\)$"
784 "Regular expression matching opening of GFM code blocks.
785 Group 1 matches the opening three backquotes and any following whitespace.
786 Group 2 matches the opening brace (optional) and surrounding whitespace.
787 Group 3 matches the language identifier (optional).
788 Group 4 matches the info string (optional).
789 Group 5 matches the closing brace (optional), whitespace, and newline.
790 Groups need to agree with `markdown-regex-tilde-fence-begin'.")
792 (defconst markdown-regex-gfm-code-block-close
793 "^[[:blank:]]*\\(?1:```\\)\\(?2:\\s *?\\)$"
794 "Regular expression matching closing of GFM code blocks.
795 Group 1 matches the closing three backquotes.
796 Group 2 matches any whitespace and the final newline.")
798 (defconst markdown-regex-pre
799 "^\\( \\|\t\\).*$"
800 "Regular expression for matching preformatted text sections.")
802 (defconst markdown-regex-list
803 (markdown-rx line-start
804 ;; 1. Leading whitespace
805 (group (* blank))
806 ;; 2. List marker: a numeral, bullet, or colon
807 (group list-marker)
808 ;; 3. Trailing whitespace
809 (group (+ blank))
810 ;; 4. Optional checkbox for GFM task list items
811 (opt (group (and checkbox (* blank)))))
812 "Regular expression for matching list items.")
814 (defconst markdown-regex-bold
815 "\\(?1:^\\|[^\\]\\)\\(?2:\\(?3:\\*\\*\\|__\\)\\(?4:[^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(?5:\\3\\)\\)"
816 "Regular expression for matching bold text.
817 Group 1 matches the character before the opening asterisk or
818 underscore, if any, ensuring that it is not a backslash escape.
819 Group 2 matches the entire expression, including delimiters.
820 Groups 3 and 5 matches the opening and closing delimiters.
821 Group 4 matches the text inside the delimiters.")
823 (defconst markdown-regex-italic
824 "\\(?:^\\|[^\\]\\)\\(?1:\\(?2:[*_]\\)\\(?3:[^ \n\t\\]\\|[^ \n\t*]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(?4:\\2\\)\\)"
825 "Regular expression for matching italic text.
826 The leading unnumbered matches the character before the opening
827 asterisk or underscore, if any, ensuring that it is not a
828 backslash escape.
829 Group 1 matches the entire expression, including delimiters.
830 Groups 2 and 4 matches the opening and closing delimiters.
831 Group 3 matches the text inside the delimiters.")
833 (defconst markdown-regex-strike-through
834 "\\(?1:^\\|[^\\]\\)\\(?2:\\(?3:~~\\)\\(?4:[^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(?5:~~\\)\\)"
835 "Regular expression for matching strike-through text.
836 Group 1 matches the character before the opening tilde, if any,
837 ensuring that it is not a backslash escape.
838 Group 2 matches the entire expression, including delimiters.
839 Groups 3 and 5 matches the opening and closing delimiters.
840 Group 4 matches the text inside the delimiters.")
842 (defconst markdown-regex-gfm-italic
843 "\\(?:^\\|[^\\]\\)\\(?1:\\(?2:[*_]\\)\\(?3:[^ \\]\\2\\|[^ ]\\(?:.\\|\n[^\n]\\)*?\\)\\(?4:\\2\\)\\)"
844 "Regular expression for matching italic text in GitHub Flavored Markdown.
845 Underscores in words are not treated as special.
846 Group 1 matches the entire expression, including delimiters.
847 Groups 2 and 4 matches the opening and closing delimiters.
848 Group 3 matches the text inside the delimiters.")
850 (defconst markdown-regex-blockquote
851 "^[ \t]*\\(?1:[A-Z]?>\\)\\(?2:[ \t]*\\)\\(?3:.*\\)$"
852 "Regular expression for matching blockquote lines.
853 Also accounts for a potential capital letter preceding the angle
854 bracket, for use with Leanpub blocks (asides, warnings, info
855 blocks, etc.).
856 Group 1 matches the leading angle bracket.
857 Group 2 matches the separating whitespace.
858 Group 3 matches the text.")
860 (defconst markdown-regex-line-break
861 "[^ \n\t][ \t]*\\( \\)\n"
862 "Regular expression for matching line breaks.")
864 (defconst markdown-regex-wiki-link
865 "\\(?:^\\|[^\\]\\)\\(?1:\\(?2:\\[\\[\\)\\(?3:[^]|]+\\)\\(?:\\(?4:|\\)\\(?5:[^]]+\\)\\)?\\(?6:\\]\\]\\)\\)"
866 "Regular expression for matching wiki links.
867 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
868 wiki links of the form [[PageName|link text]].
869 The meanings of the first and second components depend
870 on the value of `markdown-wiki-link-alias-first'.
872 Group 1 matches the entire link.
873 Group 2 matches the opening square brackets.
874 Group 3 matches the first component of the wiki link.
875 Group 4 matches the pipe separator, when present.
876 Group 5 matches the second component of the wiki link, when present.
877 Group 6 matches the closing square brackets.")
879 (defconst markdown-regex-uri
880 (concat "\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>; ]+\\)")
881 "Regular expression for matching inline URIs.")
883 (defconst markdown-regex-angle-uri
884 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
885 "Regular expression for matching inline URIs in angle brackets.")
887 (defconst markdown-regex-email
888 "<\\(\\(?:\\sw\\|\\s_\\|\\s.\\)+@\\(?:\\sw\\|\\s_\\|\\s.\\)+\\)>"
889 "Regular expression for matching inline email addresses.")
891 (defsubst markdown-make-regex-link-generic ()
892 "Make regular expression for matching any recognized link."
893 (concat "\\(?:" markdown-regex-link-inline
894 (when markdown-enable-wiki-links
895 (concat "\\|" markdown-regex-wiki-link))
896 "\\|" markdown-regex-link-reference
897 "\\|" markdown-regex-angle-uri "\\)"))
899 (defconst markdown-regex-gfm-checkbox
900 " \\(\\[[ xX]\\]\\) "
901 "Regular expression for matching GFM checkboxes.
902 Group 1 matches the text to become a button.")
904 (defconst markdown-regex-blank-line
905 "^[[:blank:]]*$"
906 "Regular expression that matches a blank line.")
908 (defconst markdown-regex-block-separator
909 "\n[\n\t\f ]*\n"
910 "Regular expression for matching block boundaries.")
912 (defconst markdown-regex-block-separator-noindent
913 (concat "\\(\\`\\|\\(" markdown-regex-block-separator "\\)[^\n\t\f ]\\)")
914 "Regexp for block separators before lines with no indentation.")
916 (defconst markdown-regex-math-inline-single
917 "\\(?:^\\|[^\\]\\)\\(?1:\\$\\)\\(?2:\\(?:[^\\$]\\|\\\\.\\)*\\)\\(?3:\\$\\)"
918 "Regular expression for itex $..$ math mode expressions.
919 Groups 1 and 3 match the opening and closing dollar signs.
920 Group 2 matches the mathematical expression contained within.")
922 (defconst markdown-regex-math-inline-double
923 "\\(?:^\\|[^\\]\\)\\(?1:\\$\\$\\)\\(?2:\\(?:[^\\$]\\|\\\\.\\)*\\)\\(?3:\\$\\$\\)"
924 "Regular expression for itex $$..$$ math mode expressions.
925 Groups 1 and 3 match opening and closing dollar signs.
926 Group 2 matches the mathematical expression contained within.")
928 (defconst markdown-regex-math-display
929 (rx line-start (* blank)
930 (group (group (repeat 1 2 "\\")) "[")
931 (group (*? anything))
932 (group (backref 2) "]")
933 line-end)
934 "Regular expression for \[..\] or \\[..\\] display math.
935 Groups 1 and 4 match the opening and closing markup.
936 Group 3 matches the mathematical expression contained within.
937 Group 2 matches the opening slashes, and is used internally to
938 match the closing slashes.")
940 (defsubst markdown-make-tilde-fence-regex (num-tildes &optional end-of-line)
941 "Return regexp matching a tilde code fence at least NUM-TILDES long.
942 END-OF-LINE is the regexp construct to indicate end of line; $ if
943 missing."
944 (format "%s%d%s%s" "^[[:blank:]]*\\([~]\\{" num-tildes ",\\}\\)"
945 (or end-of-line "$")))
947 (defconst markdown-regex-tilde-fence-begin
948 (markdown-make-tilde-fence-regex
949 3 "\\([[:blank:]]*{?\\)[[:blank:]]*\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$")
950 "Regular expression for matching tilde-fenced code blocks.
951 Group 1 matches the opening tildes.
952 Group 2 matches (optional) opening brace and surrounding whitespace.
953 Group 3 matches the language identifier (optional).
954 Group 4 matches the info string (optional).
955 Group 5 matches the closing brace (optional) and any surrounding whitespace.
956 Groups need to agree with `markdown-regex-gfm-code-block-open'.")
958 (defconst markdown-regex-declarative-metadata
959 "^[ \t]*\\(?:-[ \t]*\\)?\\([[:alpha:]][[:alpha:] _-]*?\\)\\([:=][ \t]*\\)\\(.*\\)$"
960 "Regular expression for matching declarative metadata statements.
961 This matches MultiMarkdown metadata as well as YAML and TOML
962 assignments such as the following:
964 variable: value
968 variable = value")
970 (defconst markdown-regex-pandoc-metadata
971 "^\\(%\\)\\([ \t]*\\)\\(.*\\(?:\n[ \t]+.*\\)*\\)"
972 "Regular expression for matching Pandoc metadata.")
974 (defconst markdown-regex-yaml-metadata-border
975 "\\(-\\{3\\}\\)$"
976 "Regular expression for matching YAML metadata.")
978 (defconst markdown-regex-yaml-pandoc-metadata-end-border
979 "^\\(\\.\\{3\\}\\|\\-\\{3\\}\\)$"
980 "Regular expression for matching YAML metadata end borders.")
982 (defsubst markdown-get-yaml-metadata-start-border ()
983 "Return YAML metadata start border depending upon whether Pandoc is used."
984 (concat
985 (if markdown-use-pandoc-style-yaml-metadata "^" "\\`")
986 markdown-regex-yaml-metadata-border))
988 (defsubst markdown-get-yaml-metadata-end-border (_)
989 "Return YAML metadata end border depending upon whether Pandoc is used."
990 (if markdown-use-pandoc-style-yaml-metadata
991 markdown-regex-yaml-pandoc-metadata-end-border
992 markdown-regex-yaml-metadata-border))
994 (defconst markdown-regex-inline-attributes
995 "[ \t]*\\(?:{:?\\)[ \t]*\\(?:\\(?:#[[:alpha:]_.:-]+\\|\\.[[:alpha:]_.:-]+\\|\\w+=['\"]?[^\n'\"}]*['\"]?\\),?[ \t]*\\)+\\(?:}\\)[ \t]*$"
996 "Regular expression for matching inline identifiers or attribute lists.
997 Compatible with Pandoc, Python Markdown, PHP Markdown Extra, and Leanpub.")
999 (defconst markdown-regex-leanpub-sections
1000 (concat
1001 "^\\({\\)\\("
1002 (regexp-opt '("frontmatter" "mainmatter" "backmatter" "appendix" "pagebreak"))
1003 "\\)\\(}\\)[ \t]*\n")
1004 "Regular expression for Leanpub section markers and related syntax.")
1006 (defconst markdown-regex-sub-superscript
1007 "\\(?:^\\|[^\\~^]\\)\\(?1:\\(?2:[~^]\\)\\(?3:[+-\u2212]?[[:alnum:]]+\\)\\(?4:\\2\\)\\)"
1008 "The regular expression matching a sub- or superscript.
1009 The leading un-numbered group matches the character before the
1010 opening tilde or carat, if any, ensuring that it is not a
1011 backslash escape, carat, or tilde.
1012 Group 1 matches the entire expression, including markup.
1013 Group 2 matches the opening markup--a tilde or carat.
1014 Group 3 matches the text inside the delimiters.
1015 Group 4 matches the closing markup--a tilde or carat.")
1017 (defconst markdown-regex-include
1018 "^\\(?1:<<\\)\\(?:\\(?2:\\[\\)\\(?3:.*\\)\\(?4:\\]\\)\\)?\\(?:\\(?5:(\\)\\(?6:.*\\)\\(?7:)\\)\\)?\\(?:\\(?8:{\\)\\(?9:.*\\)\\(?10:}\\)\\)?$"
1019 "Regular expression matching common forms of include syntax.
1020 Marked 2, Leanpub, and other processors support some of these forms:
1022 <<[sections/section1.md]
1023 <<(folder/filename)
1024 <<[Code title](folder/filename)
1025 <<{folder/raw_file.html}
1027 Group 1 matches the opening two angle brackets.
1028 Groups 2-4 match the opening square bracket, the text inside,
1029 and the closing square bracket, respectively.
1030 Groups 5-7 match the opening parenthesis, the text inside, and
1031 the closing parenthesis.
1032 Groups 8-10 match the opening brace, the text inside, and the brace.")
1034 (defconst markdown-regex-pandoc-inline-footnote
1035 "\\(?1:\\^\\)\\(?2:\\[\\)\\(?3:\\(?:.\\|\n[^\n]\\)*?\\)\\(?4:\\]\\)"
1036 "Regular expression for Pandoc inline footnote^[footnote text].
1037 Group 1 matches the opening caret.
1038 Group 2 matches the opening square bracket.
1039 Group 3 matches the footnote text, without the surrounding markup.
1040 Group 4 matches the closing square bracket.")
1042 (defconst markdown-regex-html-attr
1043 "\\(\\<[[:alpha:]:-]+\\>\\)\\(\\s-*\\(=\\)\\s-*\\(\".*?\"\\|'.*?'\\|[^'\">[:space:]]+\\)?\\)?"
1044 "Regular expression for matching HTML attributes and values.
1045 Group 1 matches the attribute name.
1046 Group 2 matches the following whitespace, equals sign, and value, if any.
1047 Group 3 matches the equals sign, if any.
1048 Group 4 matches single-, double-, or un-quoted attribute values.")
1050 (defconst markdown-regex-html-tag
1051 (concat "\\(</?\\)\\(\\w+\\)\\(\\(\\s-+" markdown-regex-html-attr
1052 "\\)+\\s-*\\|\\s-*\\)\\(/?>\\)")
1053 "Regular expression for matching HTML tags.
1054 Groups 1 and 9 match the beginning and ending angle brackets and slashes.
1055 Group 2 matches the tag name.
1056 Group 3 matches all attributes and whitespace following the tag name.")
1058 (defconst markdown-regex-html-entity
1059 "\\(&#?[[:alnum:]]+;\\)"
1060 "Regular expression for matching HTML entities.")
1062 (defconst markdown-regex-highlighting
1063 "\\(?1:^\\|[^\\]\\)\\(?2:\\(?3:==\\)\\(?4:[^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(?5:==\\)\\)"
1064 "Regular expression for matching highlighting text.
1065 Group 1 matches the character before the opening equal, if any,
1066 ensuring that it is not a backslash escape.
1067 Group 2 matches the entire expression, including delimiters.
1068 Groups 3 and 5 matches the opening and closing delimiters.
1069 Group 4 matches the text inside the delimiters.")
1072 ;;; Syntax ====================================================================
1074 (defvar markdown--syntax-properties
1075 (list 'markdown-tilde-fence-begin nil
1076 'markdown-tilde-fence-end nil
1077 'markdown-fenced-code nil
1078 'markdown-yaml-metadata-begin nil
1079 'markdown-yaml-metadata-end nil
1080 'markdown-yaml-metadata-section nil
1081 'markdown-gfm-block-begin nil
1082 'markdown-gfm-block-end nil
1083 'markdown-gfm-code nil
1084 'markdown-list-item nil
1085 'markdown-pre nil
1086 'markdown-blockquote nil
1087 'markdown-hr nil
1088 'markdown-comment nil
1089 'markdown-heading nil
1090 'markdown-heading-1-setext nil
1091 'markdown-heading-2-setext nil
1092 'markdown-heading-1-atx nil
1093 'markdown-heading-2-atx nil
1094 'markdown-heading-3-atx nil
1095 'markdown-heading-4-atx nil
1096 'markdown-heading-5-atx nil
1097 'markdown-heading-6-atx nil
1098 'markdown-metadata-key nil
1099 'markdown-metadata-value nil
1100 'markdown-metadata-markup nil)
1101 "Property list of all Markdown syntactic properties.")
1103 (defsubst markdown-in-comment-p (&optional pos)
1104 "Return non-nil if POS is in a comment.
1105 If POS is not given, use point instead."
1106 (get-text-property (or pos (point)) 'markdown-comment))
1108 (defun markdown--face-p (pos faces)
1109 "Return non-nil if face of POS contain FACES."
1110 (let ((face-prop (get-text-property pos 'face)))
1111 (if (listp face-prop)
1112 (cl-loop for face in face-prop
1113 thereis (memq face faces))
1114 (memq face-prop faces))))
1116 (defun markdown-syntax-propertize-extend-region (start end)
1117 "Extend START to END region to include an entire block of text.
1118 This helps improve syntax analysis for block constructs.
1119 Returns a cons (NEW-START . NEW-END) or nil if no adjustment should be made.
1120 Function is called repeatedly until it returns nil. For details, see
1121 `syntax-propertize-extend-region-functions'."
1122 (save-match-data
1123 (save-excursion
1124 (let* ((new-start (progn (goto-char start)
1125 (skip-chars-forward "\n")
1126 (if (re-search-backward "\n\n" nil t)
1127 (min start (match-end 0))
1128 (point-min))))
1129 (new-end (progn (goto-char end)
1130 (skip-chars-backward "\n")
1131 (if (re-search-forward "\n\n" nil t)
1132 (max end (match-beginning 0))
1133 (point-max))))
1134 (code-match (markdown-code-block-at-pos new-start))
1135 ;; FIXME: The `code-match' can return bogus values
1136 ;; when text has been inserted/deleted!
1137 (new-start (min (or (and code-match (cl-first code-match))
1138 (point-max))
1139 new-start))
1140 (code-match (and (< end (point-max))
1141 (markdown-code-block-at-pos end)))
1142 (new-end (max (or (and code-match (cl-second code-match)) 0)
1143 new-end)))
1145 (unless (and (eq new-start start) (eq new-end end))
1146 (cons new-start (min new-end (point-max))))))))
1148 (defun markdown-font-lock-extend-region-function (start end _)
1149 "Used in `jit-lock-after-change-extend-region-functions'.
1150 Delegates to `markdown-syntax-propertize-extend-region'. START
1151 and END are the previous region to refontify."
1152 (let ((res (markdown-syntax-propertize-extend-region start end)))
1153 (when res
1154 ;; syntax-propertize-function is not called when character at
1155 ;; (point-max) is deleted, but font-lock-extend-region-functions
1156 ;; are called. Force a syntax property update in that case.
1157 (when (= end (point-max))
1158 ;; This function is called in a buffer modification hook.
1159 ;; `markdown-syntax-propertize' doesn't save the match data,
1160 ;; so we have to do it here.
1161 (save-match-data
1162 (markdown-syntax-propertize (car res) (cdr res))))
1163 (setq jit-lock-start (car res)
1164 jit-lock-end (cdr res)))))
1166 (defun markdown--cur-list-item-bounds ()
1167 "Return a list describing the list item at point.
1168 Assumes that match data is set for `markdown-regex-list'. See the
1169 documentation for `markdown-cur-list-item-bounds' for the format of
1170 the returned list."
1171 (save-excursion
1172 (let* ((begin (match-beginning 0))
1173 (indent (length (match-string-no-properties 1)))
1174 (nonlist-indent (- (match-end 3) (match-beginning 0)))
1175 (marker (buffer-substring-no-properties
1176 (match-beginning 2) (match-end 3)))
1177 (checkbox (match-string-no-properties 4))
1178 (match (butlast (match-data t)))
1179 (end (markdown-cur-list-item-end nonlist-indent)))
1180 (list begin end indent nonlist-indent marker checkbox match))))
1182 (defun markdown--append-list-item-bounds (marker indent cur-bounds bounds)
1183 "Update list item BOUNDS given list MARKER, block INDENT, and CUR-BOUNDS.
1184 Here, MARKER is a string representing the type of list and INDENT
1185 is an integer giving the indentation, in spaces, of the current
1186 block. CUR-BOUNDS is a list of the form returned by
1187 `markdown-cur-list-item-bounds' and BOUNDS is a list of bounds
1188 values for parent list items. When BOUNDS is nil, it means we are
1189 at baseline (not inside of a nested list)."
1190 (let ((prev-indent (or (cl-third (car bounds)) 0)))
1191 (cond
1192 ;; New list item at baseline.
1193 ((and marker (null bounds))
1194 (list cur-bounds))
1195 ;; List item with greater indentation (four or more spaces).
1196 ;; Increase list level by consing CUR-BOUNDS onto BOUNDS.
1197 ((and marker (>= indent (+ prev-indent markdown-list-indent-width)))
1198 (cons cur-bounds bounds))
1199 ;; List item with greater or equal indentation (less than four spaces).
1200 ;; Keep list level the same by replacing the car of BOUNDS.
1201 ((and marker (>= indent prev-indent))
1202 (cons cur-bounds (cdr bounds)))
1203 ;; Lesser indentation level.
1204 ;; Pop appropriate number of elements off BOUNDS list (e.g., lesser
1205 ;; indentation could move back more than one list level). Note
1206 ;; that this block need not be the beginning of list item.
1207 ((< indent prev-indent)
1208 (while (and (> (length bounds) 1)
1209 (setq prev-indent (cl-third (cadr bounds)))
1210 (< indent (+ prev-indent markdown-list-indent-width)))
1211 (setq bounds (cdr bounds)))
1212 (cons cur-bounds bounds))
1213 ;; Otherwise, do nothing.
1214 (t bounds))))
1216 (defun markdown-syntax-propertize-list-items (start end)
1217 "Propertize list items from START to END.
1218 Stores nested list item information in the `markdown-list-item'
1219 text property to make later syntax analysis easier. The value of
1220 this property is a list with elements of the form (begin . end)
1221 giving the bounds of the current and parent list items."
1222 (save-excursion
1223 (goto-char start)
1224 (let ((prev-list-line -100)
1225 bounds level pre-regexp)
1226 ;; Find a baseline point with zero list indentation
1227 (markdown-search-backward-baseline)
1228 ;; Search for all list items between baseline and END
1229 (while (and (< (point) end)
1230 (re-search-forward markdown-regex-list end 'limit))
1231 ;; Level of list nesting
1232 (setq level (length bounds))
1233 ;; Pre blocks need to be indented one level past the list level
1234 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ level)))
1235 (beginning-of-line)
1236 (cond
1237 ;; Reset at headings, horizontal rules, and top-level blank lines.
1238 ;; Propertize baseline when in range.
1239 ((markdown-new-baseline)
1240 (setq bounds nil))
1241 ;; Make sure this is not a line from a pre block
1242 ((and (looking-at-p pre-regexp)
1243 ;; too indented line is also treated as list if previous line is list
1244 (>= (- (line-number-at-pos) prev-list-line) 2)))
1245 ;; If not, then update levels and propertize list item when in range.
1247 (let* ((indent (current-indentation))
1248 (cur-bounds (markdown--cur-list-item-bounds))
1249 (first (cl-first cur-bounds))
1250 (last (cl-second cur-bounds))
1251 (marker (cl-fifth cur-bounds)))
1252 (setq bounds (markdown--append-list-item-bounds
1253 marker indent cur-bounds bounds))
1254 (when (and (<= start (point)) (<= (point) end))
1255 (setq prev-list-line (line-number-at-pos first))
1256 (put-text-property first last 'markdown-list-item bounds)))))
1257 (end-of-line)))))
1259 (defun markdown-syntax-propertize-pre-blocks (start end)
1260 "Match preformatted text blocks from START to END."
1261 (save-excursion
1262 (goto-char start)
1263 (let (finish)
1264 ;; Use loop for avoiding too many recursive calls
1265 ;; https://github.com/jrblevin/markdown-mode/issues/512
1266 (while (not finish)
1267 (let ((levels (markdown-calculate-list-levels))
1268 indent pre-regexp close-regexp open close)
1269 (while (and (< (point) end) (not close))
1270 ;; Search for a region with sufficient indentation
1271 (if (null levels)
1272 (setq indent 1)
1273 (setq indent (1+ (length levels))))
1274 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1275 (setq close-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1277 (cond
1278 ;; If not at the beginning of a line, move forward
1279 ((not (bolp)) (forward-line))
1280 ;; Move past blank lines
1281 ((markdown-cur-line-blank-p) (forward-line))
1282 ;; At headers and horizontal rules, reset levels
1283 ((markdown-new-baseline) (forward-line) (setq levels nil))
1284 ;; If the current line has sufficient indentation, mark out pre block
1285 ;; The opening should be preceded by a blank line.
1286 ((and (markdown-prev-line-blank) (looking-at pre-regexp))
1287 (setq open (match-beginning 0))
1288 (while (and (or (looking-at-p pre-regexp) (markdown-cur-line-blank-p))
1289 (not (eobp)))
1290 (forward-line))
1291 (skip-syntax-backward "-")
1292 (setq close (point)))
1293 ;; If current line has a list marker, update levels, move to end of block
1294 ((looking-at markdown-regex-list)
1295 (setq levels (markdown-update-list-levels
1296 (match-string 2) (current-indentation) levels))
1297 (markdown-end-of-text-block))
1298 ;; If this is the end of the indentation level, adjust levels accordingly.
1299 ;; Only match end of indentation level if levels is not the empty list.
1300 ((and (car levels) (looking-at-p close-regexp))
1301 (setq levels (markdown-update-list-levels
1302 nil (current-indentation) levels))
1303 (markdown-end-of-text-block))
1304 (t (markdown-end-of-text-block))))
1306 (if (and open close)
1307 ;; Set text property data and continue to search
1308 (put-text-property open close 'markdown-pre (list open close))
1309 (setq finish t))))
1310 nil)))
1312 (defconst markdown-fenced-block-pairs
1313 `(((,markdown-regex-tilde-fence-begin markdown-tilde-fence-begin)
1314 (markdown-make-tilde-fence-regex markdown-tilde-fence-end)
1315 markdown-fenced-code)
1316 ((markdown-get-yaml-metadata-start-border markdown-yaml-metadata-begin)
1317 (markdown-get-yaml-metadata-end-border markdown-yaml-metadata-end)
1318 markdown-yaml-metadata-section)
1319 ((,markdown-regex-gfm-code-block-open markdown-gfm-block-begin)
1320 (,markdown-regex-gfm-code-block-close markdown-gfm-block-end)
1321 markdown-gfm-code))
1322 "Mapping of regular expressions to \"fenced-block\" constructs.
1323 These constructs are distinguished by having a distinctive start
1324 and end pattern, both of which take up an entire line of text,
1325 but no special pattern to identify text within the fenced
1326 blocks (unlike blockquotes and indented-code sections).
1328 Each element within this list takes the form:
1330 ((START-REGEX-OR-FUN START-PROPERTY)
1331 (END-REGEX-OR-FUN END-PROPERTY)
1332 MIDDLE-PROPERTY)
1334 Each *-REGEX-OR-FUN element can be a regular expression as a string, or a
1335 function which evaluates to same. Functions for START-REGEX-OR-FUN accept no
1336 arguments, but functions for END-REGEX-OR-FUN accept a single numerical argument
1337 which is the length of the first group of the START-REGEX-OR-FUN match, which
1338 can be ignored if unnecessary. `markdown-maybe-funcall-regexp' is used to
1339 evaluate these into \"real\" regexps.
1341 The *-PROPERTY elements are the text properties applied to each part of the
1342 block construct when it is matched using
1343 `markdown-syntax-propertize-fenced-block-constructs'. START-PROPERTY is applied
1344 to the text matching START-REGEX-OR-FUN, END-PROPERTY to END-REGEX-OR-FUN, and
1345 MIDDLE-PROPERTY to the text in between the two. The value of *-PROPERTY is the
1346 `match-data' when the regexp was matched to the text. In the case of
1347 MIDDLE-PROPERTY, the value is a false match data of the form '(begin end), with
1348 begin and end set to the edges of the \"middle\" text. This makes fontification
1349 easier.")
1351 (defun markdown-text-property-at-point (prop)
1352 (get-text-property (point) prop))
1354 (defsubst markdown-maybe-funcall-regexp (object &optional arg)
1355 (cond ((functionp object)
1356 (if arg (funcall object arg) (funcall object)))
1357 ((stringp object) object)
1358 (t (error "Object cannot be turned into regex"))))
1360 (defsubst markdown-get-start-fence-regexp ()
1361 "Return regexp to find all \"start\" sections of fenced block constructs.
1362 Which construct is actually contained in the match must be found separately."
1363 (mapconcat
1364 #'identity
1365 (mapcar (lambda (entry) (markdown-maybe-funcall-regexp (caar entry)))
1366 markdown-fenced-block-pairs)
1367 "\\|"))
1369 (defun markdown-get-fenced-block-begin-properties ()
1370 (cl-mapcar (lambda (entry) (cl-cadar entry)) markdown-fenced-block-pairs))
1372 (defun markdown-get-fenced-block-end-properties ()
1373 (cl-mapcar (lambda (entry) (cl-cadadr entry)) markdown-fenced-block-pairs))
1375 (defun markdown-get-fenced-block-middle-properties ()
1376 (cl-mapcar #'cl-third markdown-fenced-block-pairs))
1378 (defun markdown-find-previous-prop (prop &optional lim)
1379 "Find previous place where property PROP is non-nil, up to LIM.
1380 Return a cons of (pos . property). pos is point if point contains
1381 non-nil PROP."
1382 (let ((res
1383 (if (get-text-property (point) prop) (point)
1384 (previous-single-property-change
1385 (point) prop nil (or lim (point-min))))))
1386 (when (and (not (get-text-property res prop))
1387 (> res (point-min))
1388 (get-text-property (1- res) prop))
1389 (cl-decf res))
1390 (when (and res (get-text-property res prop)) (cons res prop))))
1392 (defun markdown-find-next-prop (prop &optional lim)
1393 "Find next place where property PROP is non-nil, up to LIM.
1394 Return a cons of (POS . PROPERTY) where POS is point if point
1395 contains non-nil PROP."
1396 (let ((res
1397 (if (get-text-property (point) prop) (point)
1398 (next-single-property-change
1399 (point) prop nil (or lim (point-max))))))
1400 (when (and res (get-text-property res prop)) (cons res prop))))
1402 (defun markdown-min-of-seq (map-fn seq)
1403 "Apply MAP-FN to SEQ and return element of SEQ with minimum value of MAP-FN."
1404 (cl-loop for el in seq
1405 with min = 1.0e+INF ; infinity
1406 with min-el = nil
1407 do (let ((res (funcall map-fn el)))
1408 (when (< res min)
1409 (setq min res)
1410 (setq min-el el)))
1411 finally return min-el))
1413 (defun markdown-max-of-seq (map-fn seq)
1414 "Apply MAP-FN to SEQ and return element of SEQ with maximum value of MAP-FN."
1415 (cl-loop for el in seq
1416 with max = -1.0e+INF ; negative infinity
1417 with max-el = nil
1418 do (let ((res (funcall map-fn el)))
1419 (when (and res (> res max))
1420 (setq max res)
1421 (setq max-el el)))
1422 finally return max-el))
1424 (defun markdown-find-previous-block ()
1425 "Find previous block.
1426 Detect whether `markdown-syntax-propertize-fenced-block-constructs' was
1427 unable to propertize the entire block, but was able to propertize the beginning
1428 of the block. If so, return a cons of (pos . property) where the beginning of
1429 the block was propertized."
1430 (let ((start-pt (point))
1431 (closest-open
1432 (markdown-max-of-seq
1433 #'car
1434 (cl-remove-if
1435 #'null
1436 (cl-mapcar
1437 #'markdown-find-previous-prop
1438 (markdown-get-fenced-block-begin-properties))))))
1439 (when closest-open
1440 (let* ((length-of-open-match
1441 (let ((match-d
1442 (get-text-property (car closest-open) (cdr closest-open))))
1443 (- (cl-fourth match-d) (cl-third match-d))))
1444 (end-regexp
1445 (markdown-maybe-funcall-regexp
1446 (cl-caadr
1447 (cl-find-if
1448 (lambda (entry) (eq (cl-cadar entry) (cdr closest-open)))
1449 markdown-fenced-block-pairs))
1450 length-of-open-match))
1451 (end-prop-loc
1452 (save-excursion
1453 (save-match-data
1454 (goto-char (car closest-open))
1455 (and (re-search-forward end-regexp start-pt t)
1456 (match-beginning 0))))))
1457 (and (not end-prop-loc) closest-open)))))
1459 (defun markdown-get-fenced-block-from-start (prop)
1460 "Return limits of an enclosing fenced block from its start, using PROP.
1461 Return value is a list usable as `match-data'."
1462 (catch 'no-rest-of-block
1463 (let* ((correct-entry
1464 (cl-find-if
1465 (lambda (entry) (eq (cl-cadar entry) prop))
1466 markdown-fenced-block-pairs))
1467 (begin-of-begin (cl-first (markdown-text-property-at-point prop)))
1468 (middle-prop (cl-third correct-entry))
1469 (end-prop (cl-cadadr correct-entry))
1470 (end-of-end
1471 (save-excursion
1472 (goto-char (match-end 0)) ; end of begin
1473 (unless (eobp) (forward-char))
1474 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
1475 (if (not mid-prop-v) ; no middle
1476 (progn
1477 ;; try to find end by advancing one
1478 (let ((end-prop-v
1479 (markdown-text-property-at-point end-prop)))
1480 (if end-prop-v (cl-second end-prop-v)
1481 (throw 'no-rest-of-block nil))))
1482 (set-match-data mid-prop-v)
1483 (goto-char (match-end 0)) ; end of middle
1484 (beginning-of-line) ; into end
1485 (cl-second (markdown-text-property-at-point end-prop)))))))
1486 (list begin-of-begin end-of-end))))
1488 (defun markdown-get-fenced-block-from-middle (prop)
1489 "Return limits of an enclosing fenced block from its middle, using PROP.
1490 Return value is a list usable as `match-data'."
1491 (let* ((correct-entry
1492 (cl-find-if
1493 (lambda (entry) (eq (cl-third entry) prop))
1494 markdown-fenced-block-pairs))
1495 (begin-prop (cl-cadar correct-entry))
1496 (begin-of-begin
1497 (save-excursion
1498 (goto-char (match-beginning 0))
1499 (unless (bobp) (forward-line -1))
1500 (beginning-of-line)
1501 (cl-first (markdown-text-property-at-point begin-prop))))
1502 (end-prop (cl-cadadr correct-entry))
1503 (end-of-end
1504 (save-excursion
1505 (goto-char (match-end 0))
1506 (beginning-of-line)
1507 (cl-second (markdown-text-property-at-point end-prop)))))
1508 (list begin-of-begin end-of-end)))
1510 (defun markdown-get-fenced-block-from-end (prop)
1511 "Return limits of an enclosing fenced block from its end, using PROP.
1512 Return value is a list usable as `match-data'."
1513 (let* ((correct-entry
1514 (cl-find-if
1515 (lambda (entry) (eq (cl-cadadr entry) prop))
1516 markdown-fenced-block-pairs))
1517 (end-of-end (cl-second (markdown-text-property-at-point prop)))
1518 (middle-prop (cl-third correct-entry))
1519 (begin-prop (cl-cadar correct-entry))
1520 (begin-of-begin
1521 (save-excursion
1522 (goto-char (match-beginning 0)) ; beginning of end
1523 (unless (bobp) (backward-char)) ; into middle
1524 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
1525 (if (not mid-prop-v)
1526 (progn
1527 (beginning-of-line)
1528 (cl-first (markdown-text-property-at-point begin-prop)))
1529 (set-match-data mid-prop-v)
1530 (goto-char (match-beginning 0)) ; beginning of middle
1531 (unless (bobp) (forward-line -1)) ; into beginning
1532 (beginning-of-line)
1533 (cl-first (markdown-text-property-at-point begin-prop)))))))
1534 (list begin-of-begin end-of-end)))
1536 (defun markdown-get-enclosing-fenced-block-construct (&optional pos)
1537 "Get \"fake\" match data for block enclosing POS.
1538 Returns fake match data which encloses the start, middle, and end
1539 of the block construct enclosing POS, if it exists. Used in
1540 `markdown-code-block-at-pos'."
1541 (save-excursion
1542 (when pos (goto-char pos))
1543 (beginning-of-line)
1544 (car
1545 (cl-remove-if
1546 #'null
1547 (cl-mapcar
1548 (lambda (fun-and-prop)
1549 (cl-destructuring-bind (fun prop) fun-and-prop
1550 (when prop
1551 (save-match-data
1552 (set-match-data (markdown-text-property-at-point prop))
1553 (funcall fun prop)))))
1554 `((markdown-get-fenced-block-from-start
1555 ,(cl-find-if
1556 #'markdown-text-property-at-point
1557 (markdown-get-fenced-block-begin-properties)))
1558 (markdown-get-fenced-block-from-middle
1559 ,(cl-find-if
1560 #'markdown-text-property-at-point
1561 (markdown-get-fenced-block-middle-properties)))
1562 (markdown-get-fenced-block-from-end
1563 ,(cl-find-if
1564 #'markdown-text-property-at-point
1565 (markdown-get-fenced-block-end-properties)))))))))
1567 (defun markdown-propertize-end-match (reg end fence-spec middle-begin)
1568 "Get match for REG up to END, if exists, and propertize appropriately.
1569 FENCE-SPEC is an entry in `markdown-fenced-block-pairs' and
1570 MIDDLE-BEGIN is the start of the \"middle\" section of the block."
1571 (when (re-search-forward reg end t)
1572 (let ((close-begin (match-beginning 0)) ; Start of closing line.
1573 (close-end (match-end 0)) ; End of closing line.
1574 (close-data (match-data t))) ; Match data for closing line.
1575 ;; Propertize middle section of fenced block.
1576 (put-text-property middle-begin close-begin
1577 (cl-third fence-spec)
1578 (list middle-begin close-begin))
1579 ;; If the block is a YAML block, propertize the declarations inside
1580 (when (< middle-begin close-begin) ;; workaround #634
1581 (markdown-syntax-propertize-yaml-metadata middle-begin close-begin))
1582 ;; Propertize closing line of fenced block.
1583 (put-text-property close-begin close-end
1584 (cl-cadadr fence-spec) close-data))))
1586 (defun markdown--triple-quote-single-line-p (begin)
1587 (save-excursion
1588 (goto-char begin)
1589 (save-match-data
1590 (and (search-forward "```" nil t)
1591 (search-forward "```" (line-end-position) t)))))
1593 (defun markdown-syntax-propertize-fenced-block-constructs (start end)
1594 "Propertize according to `markdown-fenced-block-pairs' from START to END.
1595 If unable to propertize an entire block (if the start of a block is within START
1596 and END, but the end of the block is not), propertize the start section of a
1597 block, then in a subsequent call propertize both middle and end by finding the
1598 start which was previously propertized."
1599 (let ((start-reg (markdown-get-start-fence-regexp)))
1600 (save-excursion
1601 (goto-char start)
1602 ;; start from previous unclosed block, if exists
1603 (let ((prev-begin-block (markdown-find-previous-block)))
1604 (when prev-begin-block
1605 (let* ((correct-entry
1606 (cl-find-if (lambda (entry)
1607 (eq (cdr prev-begin-block) (cl-cadar entry)))
1608 markdown-fenced-block-pairs))
1609 (enclosed-text-start (1+ (car prev-begin-block)))
1610 (start-length
1611 (save-excursion
1612 (goto-char (car prev-begin-block))
1613 (string-match
1614 (markdown-maybe-funcall-regexp
1615 (caar correct-entry))
1616 (buffer-substring
1617 (point-at-bol) (point-at-eol)))
1618 (- (match-end 1) (match-beginning 1))))
1619 (end-reg (markdown-maybe-funcall-regexp
1620 (cl-caadr correct-entry) start-length)))
1621 (markdown-propertize-end-match
1622 end-reg end correct-entry enclosed-text-start))))
1623 ;; find all new blocks within region
1624 (while (re-search-forward start-reg end t)
1625 ;; we assume the opening constructs take up (only) an entire line,
1626 ;; so we re-check the current line
1627 (let* ((block-start (match-beginning 0))
1628 (cur-line (buffer-substring (point-at-bol) (point-at-eol)))
1629 ;; find entry in `markdown-fenced-block-pairs' corresponding
1630 ;; to regex which was matched
1631 (correct-entry
1632 (cl-find-if
1633 (lambda (fenced-pair)
1634 (string-match-p
1635 (markdown-maybe-funcall-regexp (caar fenced-pair))
1636 cur-line))
1637 markdown-fenced-block-pairs))
1638 (enclosed-text-start
1639 (save-excursion (1+ (point-at-eol))))
1640 (end-reg
1641 (markdown-maybe-funcall-regexp
1642 (cl-caadr correct-entry)
1643 (if (and (match-beginning 1) (match-end 1))
1644 (- (match-end 1) (match-beginning 1))
1645 0)))
1646 (prop (cl-cadar correct-entry)))
1647 (when (or (not (eq prop 'markdown-gfm-block-begin))
1648 (not (markdown--triple-quote-single-line-p block-start)))
1649 ;; get correct match data
1650 (save-excursion
1651 (beginning-of-line)
1652 (re-search-forward
1653 (markdown-maybe-funcall-regexp (caar correct-entry))
1654 (point-at-eol)))
1655 ;; mark starting, even if ending is outside of region
1656 (put-text-property (match-beginning 0) (match-end 0) prop (match-data t))
1657 (markdown-propertize-end-match
1658 end-reg end correct-entry enclosed-text-start)))))))
1660 (defun markdown-syntax-propertize-blockquotes (start end)
1661 "Match blockquotes from START to END."
1662 (save-excursion
1663 (goto-char start)
1664 (while (and (re-search-forward markdown-regex-blockquote end t)
1665 (not (markdown-code-block-at-pos (match-beginning 0))))
1666 (put-text-property (match-beginning 0) (match-end 0)
1667 'markdown-blockquote
1668 (match-data t)))))
1670 (defun markdown-syntax-propertize-hrs (start end)
1671 "Match horizontal rules from START to END."
1672 (save-excursion
1673 (goto-char start)
1674 (while (re-search-forward markdown-regex-hr end t)
1675 (let ((beg (match-beginning 0))
1676 (end (match-end 0)))
1677 (goto-char beg)
1678 (unless (or (markdown-on-heading-p)
1679 (markdown-code-block-at-point-p))
1680 (put-text-property beg end 'markdown-hr (match-data t)))
1681 (goto-char end)))))
1683 (defun markdown-syntax-propertize-yaml-metadata (start end)
1684 "Propertize elements inside YAML metadata blocks from START to END.
1685 Assumes region from START and END is already known to be the interior
1686 region of a YAML metadata block as propertized by
1687 `markdown-syntax-propertize-fenced-block-constructs'."
1688 (save-excursion
1689 (goto-char start)
1690 (cl-loop
1691 while (re-search-forward markdown-regex-declarative-metadata end t)
1692 do (progn
1693 (put-text-property (match-beginning 1) (match-end 1)
1694 'markdown-metadata-key (match-data t))
1695 (put-text-property (match-beginning 2) (match-end 2)
1696 'markdown-metadata-markup (match-data t))
1697 (put-text-property (match-beginning 3) (match-end 3)
1698 'markdown-metadata-value (match-data t))))))
1700 (defun markdown-syntax-propertize-headings (start end)
1701 "Match headings of type SYMBOL with REGEX from START to END."
1702 (goto-char start)
1703 (while (re-search-forward markdown-regex-header end t)
1704 (unless (markdown-code-block-at-pos (match-beginning 0))
1705 (put-text-property
1706 (match-beginning 0) (match-end 0) 'markdown-heading
1707 (match-data t))
1708 (put-text-property
1709 (match-beginning 0) (match-end 0)
1710 (cond ((match-string-no-properties 2) 'markdown-heading-1-setext)
1711 ((match-string-no-properties 3) 'markdown-heading-2-setext)
1712 (t (let ((atx-level (length (markdown-trim-whitespace
1713 (match-string-no-properties 4)))))
1714 (intern (format "markdown-heading-%d-atx" atx-level)))))
1715 (match-data t)))))
1717 (defun markdown-syntax-propertize-comments (start end)
1718 "Match HTML comments from the START to END."
1719 ;; Implement by loop instead of recursive call for avoiding
1720 ;; exceed max-lisp-eval-depth issue
1721 ;; https://github.com/jrblevin/markdown-mode/issues/536
1722 (let (finish)
1723 (goto-char start)
1724 (while (not finish)
1725 (let* ((in-comment (nth 4 (syntax-ppss)))
1726 (comment-begin (nth 8 (syntax-ppss))))
1727 (cond
1728 ;; Comment start
1729 ((and (not in-comment)
1730 (re-search-forward markdown-regex-comment-start end t)
1731 (not (markdown-inline-code-at-point-p))
1732 (not (markdown-code-block-at-point-p)))
1733 (let ((open-beg (match-beginning 0)))
1734 (put-text-property open-beg (1+ open-beg)
1735 'syntax-table (string-to-syntax "<"))
1736 (goto-char (min (1+ (match-end 0)) end (point-max)))))
1737 ;; Comment end
1738 ((and in-comment comment-begin
1739 (re-search-forward markdown-regex-comment-end end t))
1740 (let ((comment-end (match-end 0)))
1741 (put-text-property (1- comment-end) comment-end
1742 'syntax-table (string-to-syntax ">"))
1743 ;; Remove any other text properties inside the comment
1744 (remove-text-properties comment-begin comment-end
1745 markdown--syntax-properties)
1746 (put-text-property comment-begin comment-end
1747 'markdown-comment (list comment-begin comment-end))
1748 (goto-char (min comment-end end (point-max)))))
1749 ;; Nothing found
1750 (t (setq finish t)))))
1751 nil))
1753 (defun markdown-syntax-propertize (start end)
1754 "Function used as `syntax-propertize-function'.
1755 START and END delimit region to propertize."
1756 (with-silent-modifications
1757 (save-excursion
1758 (remove-text-properties start end markdown--syntax-properties)
1759 (markdown-syntax-propertize-fenced-block-constructs start end)
1760 (markdown-syntax-propertize-list-items start end)
1761 (markdown-syntax-propertize-pre-blocks start end)
1762 (markdown-syntax-propertize-blockquotes start end)
1763 (markdown-syntax-propertize-headings start end)
1764 (markdown-syntax-propertize-hrs start end)
1765 (markdown-syntax-propertize-comments start end))))
1768 ;;; Markup Hiding =============================================================
1770 (defconst markdown-markup-properties
1771 '(face markdown-markup-face invisible markdown-markup)
1772 "List of properties and values to apply to markup.")
1774 (defconst markdown-language-keyword-properties
1775 '(face markdown-language-keyword-face invisible markdown-markup)
1776 "List of properties and values to apply to code block language names.")
1778 (defconst markdown-language-info-properties
1779 '(face markdown-language-info-face invisible markdown-markup)
1780 "List of properties and values to apply to code block language info strings.")
1782 (defconst markdown-include-title-properties
1783 '(face markdown-link-title-face invisible markdown-markup)
1784 "List of properties and values to apply to included code titles.")
1786 (defcustom markdown-hide-markup nil
1787 "Determines whether markup in the buffer will be hidden.
1788 When set to nil, all markup is displayed in the buffer as it
1789 appears in the file. An exception is when `markdown-hide-urls'
1790 is non-nil.
1791 Set this to a non-nil value to turn this feature on by default.
1792 You can interactively toggle the value of this variable with
1793 `markdown-toggle-markup-hiding', \\[markdown-toggle-markup-hiding],
1794 or from the Markdown > Show & Hide menu.
1796 Markup hiding works by adding text properties to positions in the
1797 buffer---either the `invisible' property or the `display' property
1798 in cases where alternative glyphs are used (e.g., list bullets).
1799 This does not, however, affect printing or other output.
1800 Functions such as `htmlfontify-buffer' and `ps-print-buffer' will
1801 not honor these text properties. For printing, it would be better
1802 to first convert to HTML or PDF (e.g,. using Pandoc)."
1803 :group 'markdown
1804 :type 'boolean
1805 :safe 'booleanp
1806 :package-version '(markdown-mode . "2.3"))
1807 (make-variable-buffer-local 'markdown-hide-markup)
1809 (defun markdown-toggle-markup-hiding (&optional arg)
1810 "Toggle the display or hiding of markup.
1811 With a prefix argument ARG, enable markup hiding if ARG is positive,
1812 and disable it otherwise.
1813 See `markdown-hide-markup' for additional details."
1814 (interactive (list (or current-prefix-arg 'toggle)))
1815 (setq markdown-hide-markup
1816 (if (eq arg 'toggle)
1817 (not markdown-hide-markup)
1818 (> (prefix-numeric-value arg) 0)))
1819 (if markdown-hide-markup
1820 (progn (add-to-invisibility-spec 'markdown-markup)
1821 (message "markdown-mode markup hiding enabled"))
1822 (progn (remove-from-invisibility-spec 'markdown-markup)
1823 (message "markdown-mode markup hiding disabled")))
1824 (markdown-reload-extensions))
1827 ;;; Font Lock =================================================================
1829 (require 'font-lock)
1831 (defgroup markdown-faces nil
1832 "Faces used in Markdown Mode."
1833 :group 'markdown
1834 :group 'faces)
1836 (defface markdown-italic-face
1837 '((t (:inherit italic)))
1838 "Face for italic text."
1839 :group 'markdown-faces)
1841 (defface markdown-bold-face
1842 '((t (:inherit bold)))
1843 "Face for bold text."
1844 :group 'markdown-faces)
1846 (defface markdown-strike-through-face
1847 '((t (:strike-through t)))
1848 "Face for strike-through text."
1849 :group 'markdown-faces)
1851 (defface markdown-markup-face
1852 '((t (:inherit shadow :slant normal :weight normal)))
1853 "Face for markup elements."
1854 :group 'markdown-faces)
1856 (defface markdown-header-rule-face
1857 '((t (:inherit markdown-markup-face)))
1858 "Base face for headers rules."
1859 :group 'markdown-faces)
1861 (defface markdown-header-delimiter-face
1862 '((t (:inherit markdown-markup-face)))
1863 "Base face for headers hash delimiter."
1864 :group 'markdown-faces)
1866 (defface markdown-list-face
1867 '((t (:inherit markdown-markup-face)))
1868 "Face for list item markers."
1869 :group 'markdown-faces)
1871 (defface markdown-blockquote-face
1872 '((t (:inherit font-lock-doc-face)))
1873 "Face for blockquote sections."
1874 :group 'markdown-faces)
1876 (defface markdown-code-face
1877 '((t (:inherit fixed-pitch)))
1878 "Face for inline code, pre blocks, and fenced code blocks.
1879 This may be used, for example, to add a contrasting background to
1880 inline code fragments and code blocks."
1881 :group 'markdown-faces)
1883 (defface markdown-inline-code-face
1884 '((t (:inherit (markdown-code-face font-lock-constant-face))))
1885 "Face for inline code."
1886 :group 'markdown-faces)
1888 (defface markdown-pre-face
1889 '((t (:inherit (markdown-code-face font-lock-constant-face))))
1890 "Face for preformatted text."
1891 :group 'markdown-faces)
1893 (defface markdown-table-face
1894 '((t (:inherit (markdown-code-face))))
1895 "Face for tables."
1896 :group 'markdown-faces)
1898 (defface markdown-language-keyword-face
1899 '((t (:inherit font-lock-type-face)))
1900 "Face for programming language identifiers."
1901 :group 'markdown-faces)
1903 (defface markdown-language-info-face
1904 '((t (:inherit font-lock-string-face)))
1905 "Face for programming language info strings."
1906 :group 'markdown-faces)
1908 (defface markdown-link-face
1909 '((t (:inherit link)))
1910 "Face for links."
1911 :group 'markdown-faces)
1913 (defface markdown-missing-link-face
1914 '((t (:inherit font-lock-warning-face)))
1915 "Face for missing links."
1916 :group 'markdown-faces)
1918 (defface markdown-reference-face
1919 '((t (:inherit markdown-markup-face)))
1920 "Face for link references."
1921 :group 'markdown-faces)
1923 (defface markdown-footnote-marker-face
1924 '((t (:inherit markdown-markup-face)))
1925 "Face for footnote markers."
1926 :group 'markdown-faces)
1928 (defface markdown-footnote-text-face
1929 '((t (:inherit font-lock-comment-face)))
1930 "Face for footnote text."
1931 :group 'markdown-faces)
1933 (defface markdown-url-face
1934 '((t (:inherit font-lock-string-face)))
1935 "Face for URLs that are part of markup.
1936 For example, this applies to URLs in inline links:
1937 [link text](http://example.com/)."
1938 :group 'markdown-faces)
1940 (defface markdown-plain-url-face
1941 '((t (:inherit markdown-link-face)))
1942 "Face for URLs that are also links.
1943 For example, this applies to plain angle bracket URLs:
1944 <http://example.com/>."
1945 :group 'markdown-faces)
1947 (defface markdown-link-title-face
1948 '((t (:inherit font-lock-comment-face)))
1949 "Face for reference link titles."
1950 :group 'markdown-faces)
1952 (defface markdown-line-break-face
1953 '((t (:inherit font-lock-constant-face :underline t)))
1954 "Face for hard line breaks."
1955 :group 'markdown-faces)
1957 (defface markdown-comment-face
1958 '((t (:inherit font-lock-comment-face)))
1959 "Face for HTML comments."
1960 :group 'markdown-faces)
1962 (defface markdown-math-face
1963 '((t (:inherit font-lock-string-face)))
1964 "Face for LaTeX expressions."
1965 :group 'markdown-faces)
1967 (defface markdown-metadata-key-face
1968 '((t (:inherit font-lock-variable-name-face)))
1969 "Face for metadata keys."
1970 :group 'markdown-faces)
1972 (defface markdown-metadata-value-face
1973 '((t (:inherit font-lock-string-face)))
1974 "Face for metadata values."
1975 :group 'markdown-faces)
1977 (defface markdown-gfm-checkbox-face
1978 '((t (:inherit font-lock-builtin-face)))
1979 "Face for GFM checkboxes."
1980 :group 'markdown-faces)
1982 (defface markdown-highlight-face
1983 '((t (:inherit highlight)))
1984 "Face for mouse highlighting."
1985 :group 'markdown-faces)
1987 (defface markdown-hr-face
1988 '((t (:inherit markdown-markup-face)))
1989 "Face for horizontal rules."
1990 :group 'markdown-faces)
1992 (defface markdown-html-tag-name-face
1993 '((t (:inherit font-lock-type-face)))
1994 "Face for HTML tag names."
1995 :group 'markdown-faces)
1997 (defface markdown-html-tag-delimiter-face
1998 '((t (:inherit markdown-markup-face)))
1999 "Face for HTML tag delimiters."
2000 :group 'markdown-faces)
2002 (defface markdown-html-attr-name-face
2003 '((t (:inherit font-lock-variable-name-face)))
2004 "Face for HTML attribute names."
2005 :group 'markdown-faces)
2007 (defface markdown-html-attr-value-face
2008 '((t (:inherit font-lock-string-face)))
2009 "Face for HTML attribute values."
2010 :group 'markdown-faces)
2012 (defface markdown-html-entity-face
2013 '((t (:inherit font-lock-variable-name-face)))
2014 "Face for HTML entities."
2015 :group 'markdown-faces)
2017 (defface markdown-highlighting-face
2018 '((t (:background "yellow" :foreground "black")))
2019 "Face for highlighting."
2020 :group 'markdown-faces)
2022 (defcustom markdown-header-scaling nil
2023 "Whether to use variable-height faces for headers.
2024 When non-nil, `markdown-header-face' will inherit from
2025 `variable-pitch' and the scaling values in
2026 `markdown-header-scaling-values' will be applied to
2027 headers of levels one through six respectively."
2028 :type 'boolean
2029 :initialize #'custom-initialize-default
2030 :set (lambda (symbol value)
2031 (set-default symbol value)
2032 (markdown-update-header-faces value))
2033 :group 'markdown-faces
2034 :package-version '(markdown-mode . "2.2"))
2036 (defcustom markdown-header-scaling-values
2037 '(2.0 1.7 1.4 1.1 1.0 1.0)
2038 "List of scaling values for headers of level one through six.
2039 Used when `markdown-header-scaling' is non-nil."
2040 :type 'list
2041 :initialize #'custom-initialize-default
2042 :set (lambda (symbol value)
2043 (set-default symbol value)
2044 (markdown-update-header-faces markdown-header-scaling value)))
2046 (defmacro markdown--dotimes-when-compile (i-n body)
2047 (declare (indent 1) (debug ((symbolp form) form)))
2048 (let ((var (car i-n))
2049 (n (cadr i-n))
2050 (code ()))
2051 (dotimes (i (eval n t))
2052 (push (eval body `((,var . ,i))) code))
2053 `(progn ,@(nreverse code))))
2055 (defface markdown-header-face
2056 `((t (:inherit (,@(when markdown-header-scaling '(variable-pitch))
2057 font-lock-function-name-face)
2058 :weight bold)))
2059 "Base face for headers.")
2061 (markdown--dotimes-when-compile (num 6)
2062 (let* ((num1 (1+ num))
2063 (face-name (intern (format "markdown-header-face-%s" num1))))
2064 `(defface ,face-name
2065 (,'\` ((t (:inherit markdown-header-face
2066 :height
2067 (,'\, (if markdown-header-scaling
2068 (float (nth ,num markdown-header-scaling-values))
2069 1.0))))))
2070 (format "Face for level %s headers.
2071 You probably don't want to customize this face directly. Instead
2072 you can customize the base face `markdown-header-face' or the
2073 variable-height variable `markdown-header-scaling'." ,num1))))
2075 (defun markdown-update-header-faces (&optional scaling scaling-values)
2076 "Update header faces, depending on if header SCALING is desired.
2077 If so, use given list of SCALING-VALUES relative to the baseline
2078 size of `markdown-header-face'."
2079 (dotimes (num 6)
2080 (let* ((face-name (intern (format "markdown-header-face-%s" (1+ num))))
2081 (scale (cond ((not scaling) 1.0)
2082 (scaling-values (float (nth num scaling-values)))
2083 (t (float (nth num markdown-header-scaling-values))))))
2084 (unless (get face-name 'saved-face) ; Don't update customized faces
2085 (set-face-attribute face-name nil :height scale)))))
2087 (defun markdown-syntactic-face (state)
2088 "Return font-lock face for characters with given STATE.
2089 See `font-lock-syntactic-face-function' for details."
2090 (let ((in-comment (nth 4 state)))
2091 (cond
2092 (in-comment 'markdown-comment-face)
2093 (t nil))))
2095 (defcustom markdown-list-item-bullets
2096 '("●" "◎" "○" "◆" "◇" "►" "•")
2097 "List of bullets to use for unordered lists.
2098 It can contain any number of symbols, which will be repeated.
2099 Depending on your font, some reasonable choices are:
2100 ♥ ● ◇ ✚ ✜ ☯ ◆ ♠ ♣ ♦ ❀ ◆ ◖ ▶ ► • ★ ▸."
2101 :group 'markdown
2102 :type '(repeat (string :tag "Bullet character"))
2103 :package-version '(markdown-mode . "2.3"))
2105 (defun markdown--footnote-marker-properties ()
2106 "Return a font-lock facespec expression for footnote marker text."
2107 `(face markdown-footnote-marker-face
2108 ,@(when markdown-hide-markup
2109 `(display ,markdown-footnote-display))))
2111 (defun markdown--pandoc-inline-footnote-properties ()
2112 "Return a font-lock facespec expression for Pandoc inline footnote text."
2113 `(face markdown-footnote-text-face
2114 ,@(when markdown-hide-markup
2115 `(display ,markdown-footnote-display))))
2117 (defvar markdown-mode-font-lock-keywords
2118 `((markdown-match-yaml-metadata-begin . ((1 'markdown-markup-face)))
2119 (markdown-match-yaml-metadata-end . ((1 'markdown-markup-face)))
2120 (markdown-match-yaml-metadata-key . ((1 'markdown-metadata-key-face)
2121 (2 'markdown-markup-face)
2122 (3 'markdown-metadata-value-face)))
2123 (markdown-match-gfm-open-code-blocks . ((1 markdown-markup-properties)
2124 (2 markdown-markup-properties nil t)
2125 (3 markdown-language-keyword-properties nil t)
2126 (4 markdown-language-info-properties nil t)
2127 (5 markdown-markup-properties nil t)))
2128 (markdown-match-gfm-close-code-blocks . ((0 markdown-markup-properties)))
2129 (markdown-fontify-gfm-code-blocks)
2130 (markdown-fontify-tables)
2131 (markdown-match-fenced-start-code-block . ((1 markdown-markup-properties)
2132 (2 markdown-markup-properties nil t)
2133 (3 markdown-language-keyword-properties nil t)
2134 (4 markdown-language-info-properties nil t)
2135 (5 markdown-markup-properties nil t)))
2136 (markdown-match-fenced-end-code-block . ((0 markdown-markup-properties)))
2137 (markdown-fontify-fenced-code-blocks)
2138 (markdown-match-pre-blocks . ((0 'markdown-pre-face)))
2139 (markdown-fontify-headings)
2140 (markdown-match-declarative-metadata . ((1 'markdown-metadata-key-face)
2141 (2 'markdown-markup-face)
2142 (3 'markdown-metadata-value-face)))
2143 (markdown-match-pandoc-metadata . ((1 'markdown-markup-face)
2144 (2 'markdown-markup-face)
2145 (3 'markdown-metadata-value-face)))
2146 (markdown-fontify-hrs)
2147 (markdown-match-code . ((1 markdown-markup-properties prepend)
2148 (2 'markdown-inline-code-face prepend)
2149 (3 markdown-markup-properties prepend)))
2150 (,markdown-regex-kbd . ((1 markdown-markup-properties)
2151 (2 'markdown-inline-code-face)
2152 (3 markdown-markup-properties)))
2153 (markdown-fontify-angle-uris)
2154 (,markdown-regex-email . 'markdown-plain-url-face)
2155 (markdown-match-html-tag . ((1 'markdown-html-tag-delimiter-face t)
2156 (2 'markdown-html-tag-name-face t)
2157 (3 'markdown-html-tag-delimiter-face t)
2158 ;; Anchored matcher for HTML tag attributes
2159 (,markdown-regex-html-attr
2160 ;; Before searching, move past tag
2161 ;; name; set limit at tag close.
2162 (progn
2163 (goto-char (match-end 2)) (match-end 3))
2165 . ((1 'markdown-html-attr-name-face)
2166 (3 'markdown-html-tag-delimiter-face nil t)
2167 (4 'markdown-html-attr-value-face nil t)))))
2168 (,markdown-regex-html-entity . 'markdown-html-entity-face)
2169 (markdown-fontify-list-items)
2170 (,markdown-regex-footnote . ((1 markdown-markup-properties) ; [^
2171 (2 (markdown--footnote-marker-properties)) ; label
2172 (3 markdown-markup-properties))) ; ]
2173 (,markdown-regex-pandoc-inline-footnote . ((1 markdown-markup-properties) ; ^
2174 (2 markdown-markup-properties) ; [
2175 (3 (markdown--pandoc-inline-footnote-properties)) ; text
2176 (4 markdown-markup-properties))) ; ]
2177 (markdown-match-includes . ((1 markdown-markup-properties)
2178 (2 markdown-markup-properties nil t)
2179 (3 markdown-include-title-properties nil t)
2180 (4 markdown-markup-properties nil t)
2181 (5 markdown-markup-properties)
2182 (6 'markdown-url-face)
2183 (7 markdown-markup-properties)))
2184 (markdown-fontify-inline-links)
2185 (markdown-fontify-reference-links)
2186 (,markdown-regex-reference-definition . ((1 'markdown-markup-face) ; [
2187 (2 'markdown-reference-face) ; label
2188 (3 'markdown-markup-face) ; ]
2189 (4 'markdown-markup-face) ; :
2190 (5 'markdown-url-face) ; url
2191 (6 'markdown-link-title-face))) ; "title" (optional)
2192 (markdown-fontify-plain-uris)
2193 ;; Math mode $..$
2194 (markdown-match-math-single . ((1 'markdown-markup-face prepend)
2195 (2 'markdown-math-face append)
2196 (3 'markdown-markup-face prepend)))
2197 ;; Math mode $$..$$
2198 (markdown-match-math-double . ((1 'markdown-markup-face prepend)
2199 (2 'markdown-math-face append)
2200 (3 'markdown-markup-face prepend)))
2201 ;; Math mode \[..\] and \\[..\\]
2202 (markdown-match-math-display . ((1 'markdown-markup-face prepend)
2203 (3 'markdown-math-face append)
2204 (4 'markdown-markup-face prepend)))
2205 (markdown-match-bold . ((1 markdown-markup-properties prepend)
2206 (2 'markdown-bold-face append)
2207 (3 markdown-markup-properties prepend)))
2208 (markdown-match-italic . ((1 markdown-markup-properties prepend)
2209 (2 'markdown-italic-face append)
2210 (3 markdown-markup-properties prepend)))
2211 (,markdown-regex-strike-through . ((3 markdown-markup-properties)
2212 (4 'markdown-strike-through-face)
2213 (5 markdown-markup-properties)))
2214 (markdown--match-highlighting . ((3 markdown-markup-properties)
2215 (4 'markdown-highlighting-face)
2216 (5 markdown-markup-properties)))
2217 (,markdown-regex-line-break . (1 'markdown-line-break-face prepend))
2218 (markdown-fontify-sub-superscripts)
2219 (markdown-match-inline-attributes . ((0 markdown-markup-properties prepend)))
2220 (markdown-match-leanpub-sections . ((0 markdown-markup-properties)))
2221 (markdown-fontify-blockquotes)
2222 (markdown-match-wiki-link . ((0 'markdown-link-face prepend))))
2223 "Syntax highlighting for Markdown files.")
2225 ;; Footnotes
2226 (defvar-local markdown-footnote-counter 0
2227 "Counter for footnote numbers.")
2229 (defconst markdown-footnote-chars
2230 "[[:alnum:]-]"
2231 "Regular expression matching any character for a footnote identifier.")
2233 (defconst markdown-regex-footnote-definition
2234 (concat "^ \\{0,3\\}\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:\\(?:[ \t]+\\|$\\)")
2235 "Regular expression matching a footnote definition, capturing the label.")
2238 ;;; Compatibility =============================================================
2240 (defun markdown--pandoc-reference-p ()
2241 (let ((bounds (bounds-of-thing-at-point 'word)))
2242 (when (and bounds (char-before (car bounds)))
2243 (= (char-before (car bounds)) ?@))))
2245 (defun markdown-flyspell-check-word-p ()
2246 "Return t if `flyspell' should check word just before point.
2247 Used for `flyspell-generic-check-word-predicate'."
2248 (save-excursion
2249 (goto-char (1- (point)))
2250 ;; https://github.com/jrblevin/markdown-mode/issues/560
2251 ;; enable spell check YAML meta data
2252 (if (or (and (markdown-code-block-at-point-p)
2253 (not (markdown-text-property-at-point 'markdown-yaml-metadata-section)))
2254 (markdown-inline-code-at-point-p)
2255 (markdown-in-comment-p)
2256 (markdown--face-p (point) '(markdown-reference-face
2257 markdown-markup-face
2258 markdown-plain-url-face
2259 markdown-inline-code-face
2260 markdown-url-face))
2261 (markdown--pandoc-reference-p))
2262 (prog1 nil
2263 ;; If flyspell overlay is put, then remove it
2264 (let ((bounds (bounds-of-thing-at-point 'word)))
2265 (when bounds
2266 (cl-loop for ov in (overlays-in (car bounds) (cdr bounds))
2267 when (overlay-get ov 'flyspell-overlay)
2269 (delete-overlay ov)))))
2270 t)))
2273 ;;; Markdown Parsing Functions ================================================
2275 (defun markdown-cur-line-blank-p ()
2276 "Return t if the current line is blank and nil otherwise."
2277 (save-excursion
2278 (beginning-of-line)
2279 (looking-at-p markdown-regex-blank-line)))
2281 (defun markdown-prev-line-blank ()
2282 "Return t if the previous line is blank and nil otherwise.
2283 If we are at the first line, then consider the previous line to be blank."
2284 (or (= (line-beginning-position) (point-min))
2285 (save-excursion
2286 (forward-line -1)
2287 (looking-at markdown-regex-blank-line))))
2289 (defun markdown-prev-line-blank-p ()
2290 "Like `markdown-prev-line-blank', but preserve `match-data'."
2291 (save-match-data (markdown-prev-line-blank)))
2293 (defun markdown-next-line-blank-p ()
2294 "Return t if the next line is blank and nil otherwise.
2295 If we are at the last line, then consider the next line to be blank."
2296 (or (= (line-end-position) (point-max))
2297 (save-excursion
2298 (forward-line 1)
2299 (markdown-cur-line-blank-p))))
2301 (defun markdown-prev-line-indent ()
2302 "Return the number of leading whitespace characters in the previous line.
2303 Return 0 if the current line is the first line in the buffer."
2304 (save-excursion
2305 (if (= (line-beginning-position) (point-min))
2307 (forward-line -1)
2308 (current-indentation))))
2310 (defun markdown-next-line-indent ()
2311 "Return the number of leading whitespace characters in the next line.
2312 Return 0 if line is the last line in the buffer."
2313 (save-excursion
2314 (if (= (line-end-position) (point-max))
2316 (forward-line 1)
2317 (current-indentation))))
2319 (defun markdown-new-baseline ()
2320 "Determine if the current line begins a new baseline level.
2321 Assume point is positioned at beginning of line."
2322 (or (looking-at markdown-regex-header)
2323 (looking-at markdown-regex-hr)
2324 (and (= (current-indentation) 0)
2325 (not (looking-at markdown-regex-list))
2326 (markdown-prev-line-blank))))
2328 (defun markdown-search-backward-baseline ()
2329 "Search backward baseline point with no indentation and not a list item."
2330 (end-of-line)
2331 (let (stop)
2332 (while (not (or stop (bobp)))
2333 (re-search-backward markdown-regex-block-separator-noindent nil t)
2334 (when (match-end 2)
2335 (goto-char (match-end 2))
2336 (cond
2337 ((markdown-new-baseline)
2338 (setq stop t))
2339 ((looking-at-p markdown-regex-list)
2340 (setq stop nil))
2341 (t (setq stop t)))))))
2343 (defun markdown-update-list-levels (marker indent levels)
2344 "Update list levels given list MARKER, block INDENT, and current LEVELS.
2345 Here, MARKER is a string representing the type of list, INDENT is an integer
2346 giving the indentation, in spaces, of the current block, and LEVELS is a
2347 list of the indentation levels of parent list items. When LEVELS is nil,
2348 it means we are at baseline (not inside of a nested list)."
2349 (cond
2350 ;; New list item at baseline.
2351 ((and marker (null levels))
2352 (setq levels (list indent)))
2353 ;; List item with greater indentation (four or more spaces).
2354 ;; Increase list level.
2355 ((and marker (>= indent (+ (car levels) markdown-list-indent-width)))
2356 (setq levels (cons indent levels)))
2357 ;; List item with greater or equal indentation (less than four spaces).
2358 ;; Do not increase list level.
2359 ((and marker (>= indent (car levels)))
2360 levels)
2361 ;; Lesser indentation level.
2362 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
2363 ;; indentation could move back more than one list level). Note
2364 ;; that this block need not be the beginning of list item.
2365 ((< indent (car levels))
2366 (while (and (> (length levels) 1)
2367 (< indent (+ (cadr levels) markdown-list-indent-width)))
2368 (setq levels (cdr levels)))
2369 levels)
2370 ;; Otherwise, do nothing.
2371 (t levels)))
2373 (defun markdown-calculate-list-levels ()
2374 "Calculate list levels at point.
2375 Return a list of the form (n1 n2 n3 ...) where n1 is the
2376 indentation of the deepest nested list item in the branch of
2377 the list at the point, n2 is the indentation of the parent
2378 list item, and so on. The depth of the list item is therefore
2379 the length of the returned list. If the point is not at or
2380 immediately after a list item, return nil."
2381 (save-excursion
2382 (let ((first (point)) levels indent pre-regexp)
2383 ;; Find a baseline point with zero list indentation
2384 (markdown-search-backward-baseline)
2385 ;; Search for all list items between baseline and LOC
2386 (while (and (< (point) first)
2387 (re-search-forward markdown-regex-list first t))
2388 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
2389 (beginning-of-line)
2390 (cond
2391 ;; Make sure this is not a header or hr
2392 ((markdown-new-baseline) (setq levels nil))
2393 ;; Make sure this is not a line from a pre block
2394 ((looking-at-p pre-regexp))
2395 ;; If not, then update levels
2397 (setq indent (current-indentation))
2398 (setq levels (markdown-update-list-levels (match-string 2)
2399 indent levels))))
2400 (end-of-line))
2401 levels)))
2403 (defun markdown-prev-list-item (level)
2404 "Search backward from point for a list item with indentation LEVEL.
2405 Set point to the beginning of the item, and return point, or nil
2406 upon failure."
2407 (let (bounds indent prev)
2408 (setq prev (point))
2409 (forward-line -1)
2410 (setq indent (current-indentation))
2411 (while
2412 (cond
2413 ;; List item
2414 ((and (looking-at-p markdown-regex-list)
2415 (setq bounds (markdown-cur-list-item-bounds)))
2416 (cond
2417 ;; Stop and return point at item of equal indentation
2418 ((= (nth 3 bounds) level)
2419 (setq prev (point))
2420 nil)
2421 ;; Stop and return nil at item with lesser indentation
2422 ((< (nth 3 bounds) level)
2423 (setq prev nil)
2424 nil)
2425 ;; Stop at beginning of buffer
2426 ((bobp) (setq prev nil))
2427 ;; Continue at item with greater indentation
2428 ((> (nth 3 bounds) level) t)))
2429 ;; Stop at beginning of buffer
2430 ((bobp) (setq prev nil))
2431 ;; Continue if current line is blank
2432 ((markdown-cur-line-blank-p) t)
2433 ;; Continue while indentation is the same or greater
2434 ((>= indent level) t)
2435 ;; Stop if current indentation is less than list item
2436 ;; and the next is blank
2437 ((and (< indent level)
2438 (markdown-next-line-blank-p))
2439 (setq prev nil))
2440 ;; Stop at a header
2441 ((looking-at-p markdown-regex-header) (setq prev nil))
2442 ;; Stop at a horizontal rule
2443 ((looking-at-p markdown-regex-hr) (setq prev nil))
2444 ;; Otherwise, continue.
2445 (t t))
2446 (forward-line -1)
2447 (setq indent (current-indentation)))
2448 prev))
2450 (defun markdown-next-list-item (level)
2451 "Search forward from point for the next list item with indentation LEVEL.
2452 Set point to the beginning of the item, and return point, or nil
2453 upon failure."
2454 (let (bounds indent next)
2455 (setq next (point))
2456 (if (looking-at markdown-regex-header-setext)
2457 (goto-char (match-end 0)))
2458 (forward-line)
2459 (setq indent (current-indentation))
2460 (while
2461 (cond
2462 ;; Stop at end of the buffer.
2463 ((eobp) nil)
2464 ;; Continue if the current line is blank
2465 ((markdown-cur-line-blank-p) t)
2466 ;; List item
2467 ((and (looking-at-p markdown-regex-list)
2468 (setq bounds (markdown-cur-list-item-bounds)))
2469 (cond
2470 ;; Continue at item with greater indentation
2471 ((> (nth 3 bounds) level) t)
2472 ;; Stop and return point at item of equal indentation
2473 ((= (nth 3 bounds) level)
2474 (setq next (point))
2475 nil)
2476 ;; Stop and return nil at item with lesser indentation
2477 ((< (nth 3 bounds) level)
2478 (setq next nil)
2479 nil)))
2480 ;; Continue while indentation is the same or greater
2481 ((>= indent level) t)
2482 ;; Stop if current indentation is less than list item
2483 ;; and the previous line was blank.
2484 ((and (< indent level)
2485 (markdown-prev-line-blank-p))
2486 (setq next nil))
2487 ;; Stop at a header
2488 ((looking-at-p markdown-regex-header) (setq next nil))
2489 ;; Stop at a horizontal rule
2490 ((looking-at-p markdown-regex-hr) (setq next nil))
2491 ;; Otherwise, continue.
2492 (t t))
2493 (forward-line)
2494 (setq indent (current-indentation)))
2495 next))
2497 (defun markdown-cur-list-item-end (level)
2498 "Move to end of list item with pre-marker indentation LEVEL.
2499 Return the point at the end when a list item was found at the
2500 original point. If the point is not in a list item, do nothing."
2501 (let (indent)
2502 (forward-line)
2503 (setq indent (current-indentation))
2504 (while
2505 (cond
2506 ;; Stop at end of the buffer.
2507 ((eobp) nil)
2508 ;; Continue while indentation is the same or greater
2509 ((>= indent level) t)
2510 ;; Continue if the current line is blank
2511 ((looking-at markdown-regex-blank-line) t)
2512 ;; Stop if current indentation is less than list item
2513 ;; and the previous line was blank.
2514 ((and (< indent level)
2515 (markdown-prev-line-blank))
2516 nil)
2517 ;; Stop at a new list items of the same or lesser
2518 ;; indentation, headings, and horizontal rules.
2519 ((looking-at (concat "\\(?:" markdown-regex-list
2520 "\\|" markdown-regex-header
2521 "\\|" markdown-regex-hr "\\)"))
2522 nil)
2523 ;; Otherwise, continue.
2524 (t t))
2525 (forward-line)
2526 (setq indent (current-indentation)))
2527 ;; Don't skip over whitespace for empty list items (marker and
2528 ;; whitespace only), just move to end of whitespace.
2529 (if (save-excursion
2530 (beginning-of-line)
2531 (looking-at (concat markdown-regex-list "[ \t]*$")))
2532 (goto-char (match-end 3))
2533 (skip-chars-backward " \t\n"))
2534 (end-of-line)
2535 (point)))
2537 (defun markdown-cur-list-item-bounds ()
2538 "Return bounds for list item at point.
2539 Return a list of the following form:
2541 (begin end indent nonlist-indent marker checkbox match)
2543 The named components are:
2545 - begin: Position of beginning of list item, including leading indentation.
2546 - end: Position of the end of the list item, including list item text.
2547 - indent: Number of characters of indentation before list marker (an integer).
2548 - nonlist-indent: Number characters of indentation, list
2549 marker, and whitespace following list marker (an integer).
2550 - marker: String containing the list marker and following whitespace
2551 (e.g., \"- \" or \"* \").
2552 - checkbox: String containing the GFM checkbox portion, if any,
2553 including any trailing whitespace before the text
2554 begins (e.g., \"[x] \").
2555 - match: match data for markdown-regex-list
2557 As an example, for the following unordered list item
2559 - item
2561 the returned list would be
2563 (1 14 3 5 \"- \" nil (1 6 1 4 4 5 5 6))
2565 If the point is not inside a list item, return nil."
2566 (car (get-text-property (point-at-bol) 'markdown-list-item)))
2568 (defun markdown-list-item-at-point-p ()
2569 "Return t if there is a list item at the point and nil otherwise."
2570 (save-match-data (markdown-cur-list-item-bounds)))
2572 (defun markdown-prev-list-item-bounds ()
2573 "Return bounds of previous item in the same list of any level.
2574 The return value has the same form as that of
2575 `markdown-cur-list-item-bounds'."
2576 (save-excursion
2577 (let ((cur-bounds (markdown-cur-list-item-bounds))
2578 (beginning-of-list (save-excursion (markdown-beginning-of-list)))
2579 stop)
2580 (when cur-bounds
2581 (goto-char (nth 0 cur-bounds))
2582 (while (and (not stop) (not (bobp))
2583 (re-search-backward markdown-regex-list
2584 beginning-of-list t))
2585 (unless (or (looking-at markdown-regex-hr)
2586 (markdown-code-block-at-point-p))
2587 (setq stop (point))))
2588 (markdown-cur-list-item-bounds)))))
2590 (defun markdown-next-list-item-bounds ()
2591 "Return bounds of next item in the same list of any level.
2592 The return value has the same form as that of
2593 `markdown-cur-list-item-bounds'."
2594 (save-excursion
2595 (let ((cur-bounds (markdown-cur-list-item-bounds))
2596 (end-of-list (save-excursion (markdown-end-of-list)))
2597 stop)
2598 (when cur-bounds
2599 (goto-char (nth 0 cur-bounds))
2600 (end-of-line)
2601 (while (and (not stop) (not (eobp))
2602 (re-search-forward markdown-regex-list
2603 end-of-list t))
2604 (unless (or (looking-at markdown-regex-hr)
2605 (markdown-code-block-at-point-p))
2606 (setq stop (point))))
2607 (when stop
2608 (markdown-cur-list-item-bounds))))))
2610 (defun markdown-beginning-of-list ()
2611 "Move point to beginning of list at point, if any."
2612 (interactive)
2613 (let ((orig-point (point))
2614 (list-begin (save-excursion
2615 (markdown-search-backward-baseline)
2616 ;; Stop at next list item, regardless of the indentation.
2617 (markdown-next-list-item (point-max))
2618 (when (looking-at markdown-regex-list)
2619 (point)))))
2620 (when (and list-begin (<= list-begin orig-point))
2621 (goto-char list-begin))))
2623 (defun markdown-end-of-list ()
2624 "Move point to end of list at point, if any."
2625 (interactive)
2626 (let ((start (point))
2627 (end (save-excursion
2628 (when (markdown-beginning-of-list)
2629 ;; Items can't have nonlist-indent <= 1, so this
2630 ;; moves past all list items.
2631 (markdown-next-list-item 1)
2632 (skip-syntax-backward "-")
2633 (unless (eobp) (forward-char 1))
2634 (point)))))
2635 (when (and end (>= end start))
2636 (goto-char end))))
2638 (defun markdown-up-list ()
2639 "Move point to beginning of parent list item."
2640 (interactive)
2641 (let ((cur-bounds (markdown-cur-list-item-bounds)))
2642 (when cur-bounds
2643 (markdown-prev-list-item (1- (nth 3 cur-bounds)))
2644 (let ((up-bounds (markdown-cur-list-item-bounds)))
2645 (when (and up-bounds (< (nth 3 up-bounds) (nth 3 cur-bounds)))
2646 (point))))))
2648 (defun markdown-bounds-of-thing-at-point (thing)
2649 "Call `bounds-of-thing-at-point' for THING with slight modifications.
2650 Does not include trailing newlines when THING is 'line. Handles the
2651 end of buffer case by setting both endpoints equal to the value of
2652 `point-max', since an empty region will trigger empty markup insertion.
2653 Return bounds of form (beg . end) if THING is found, or nil otherwise."
2654 (let* ((bounds (bounds-of-thing-at-point thing))
2655 (a (car bounds))
2656 (b (cdr bounds)))
2657 (when bounds
2658 (when (eq thing 'line)
2659 (cond ((and (eobp) (markdown-cur-line-blank-p))
2660 (setq a b))
2661 ((char-equal (char-before b) ?\^J)
2662 (setq b (1- b)))))
2663 (cons a b))))
2665 (defun markdown-reference-definition (reference)
2666 "Find out whether Markdown REFERENCE is defined.
2667 REFERENCE should not include the square brackets.
2668 When REFERENCE is defined, return a list of the form (text start end)
2669 containing the definition text itself followed by the start and end
2670 locations of the text. Otherwise, return nil.
2671 Leave match data for `markdown-regex-reference-definition'
2672 intact additional processing."
2673 (let ((reference (downcase reference)))
2674 (save-excursion
2675 (goto-char (point-min))
2676 (catch 'found
2677 (while (re-search-forward markdown-regex-reference-definition nil t)
2678 (when (string= reference (downcase (match-string-no-properties 2)))
2679 (throw 'found
2680 (list (match-string-no-properties 5)
2681 (match-beginning 5) (match-end 5)))))))))
2683 (defun markdown-get-defined-references ()
2684 "Return all defined reference labels and their line numbers.
2685 They does not include square brackets)."
2686 (save-excursion
2687 (goto-char (point-min))
2688 (let (refs)
2689 (while (re-search-forward markdown-regex-reference-definition nil t)
2690 (let ((target (match-string-no-properties 2)))
2691 (cl-pushnew
2692 (cons (downcase target)
2693 (markdown-line-number-at-pos (match-beginning 2)))
2694 refs :test #'equal :key #'car)))
2695 (reverse refs))))
2697 (defun markdown-get-used-uris ()
2698 "Return a list of all used URIs in the buffer."
2699 (save-excursion
2700 (goto-char (point-min))
2701 (let (uris)
2702 (while (re-search-forward
2703 (concat "\\(?:" markdown-regex-link-inline
2704 "\\|" markdown-regex-angle-uri
2705 "\\|" markdown-regex-uri
2706 "\\|" markdown-regex-email
2707 "\\)")
2708 nil t)
2709 (unless (or (markdown-inline-code-at-point-p)
2710 (markdown-code-block-at-point-p))
2711 (cl-pushnew (or (match-string-no-properties 6)
2712 (match-string-no-properties 10)
2713 (match-string-no-properties 12)
2714 (match-string-no-properties 13))
2715 uris :test #'equal)))
2716 (reverse uris))))
2718 (defun markdown-inline-code-at-pos (pos)
2719 "Return non-nil if there is an inline code fragment at POS.
2720 Return nil otherwise. Set match data according to
2721 `markdown-match-code' upon success.
2722 This function searches the block for a code fragment that
2723 contains the point using `markdown-match-code'. We do this
2724 because `thing-at-point-looking-at' does not work reliably with
2725 `markdown-regex-code'.
2727 The match data is set as follows:
2728 Group 1 matches the opening backquotes.
2729 Group 2 matches the code fragment itself, without backquotes.
2730 Group 3 matches the closing backquotes."
2731 (save-excursion
2732 (goto-char pos)
2733 (let ((old-point (point))
2734 (end-of-block (progn (markdown-end-of-text-block) (point)))
2735 found)
2736 (markdown-beginning-of-text-block)
2737 (while (and (markdown-match-code end-of-block)
2738 (setq found t)
2739 (< (match-end 0) old-point)))
2740 (let ((match-group (if (eq (char-after (match-beginning 0)) ?`) 0 1)))
2741 (and found ; matched something
2742 (<= (match-beginning match-group) old-point) ; match contains old-point
2743 (> (match-end 0) old-point))))))
2745 (defun markdown-inline-code-at-pos-p (pos)
2746 "Return non-nil if there is an inline code fragment at POS.
2747 Like `markdown-inline-code-at-pos`, but preserves match data."
2748 (save-match-data (markdown-inline-code-at-pos pos)))
2750 (defun markdown-inline-code-at-point ()
2751 "Return non-nil if the point is at an inline code fragment.
2752 See `markdown-inline-code-at-pos' for details."
2753 (markdown-inline-code-at-pos (point)))
2755 (defun markdown-inline-code-at-point-p (&optional pos)
2756 "Return non-nil if there is inline code at the POS.
2757 This is a predicate function counterpart to
2758 `markdown-inline-code-at-point' which does not modify the match
2759 data. See `markdown-code-block-at-point-p' for code blocks."
2760 (save-match-data (markdown-inline-code-at-pos (or pos (point)))))
2762 (defun markdown-code-block-at-pos (pos)
2763 "Return match data list if there is a code block at POS.
2764 Uses text properties at the beginning of the line position.
2765 This includes pre blocks, tilde-fenced code blocks, and GFM
2766 quoted code blocks. Return nil otherwise."
2767 (let ((bol (save-excursion (goto-char pos) (point-at-bol))))
2768 (or (get-text-property bol 'markdown-pre)
2769 (let* ((bounds (markdown-get-enclosing-fenced-block-construct pos))
2770 (second (cl-second bounds)))
2771 (if second
2772 ;; chunks are right open
2773 (when (< pos second)
2774 bounds)
2775 bounds)))))
2777 ;; Function was renamed to emphasize that it does not modify match-data.
2778 (defalias 'markdown-code-block-at-point 'markdown-code-block-at-point-p)
2780 (defun markdown-code-block-at-point-p (&optional pos)
2781 "Return non-nil if there is a code block at the POS.
2782 This includes pre blocks, tilde-fenced code blocks, and GFM
2783 quoted code blocks. This function does not modify the match
2784 data. See `markdown-inline-code-at-point-p' for inline code."
2785 (save-match-data (markdown-code-block-at-pos (or pos (point)))))
2787 (defun markdown-heading-at-point (&optional pos)
2788 "Return non-nil if there is a heading at the POS.
2789 Set match data for `markdown-regex-header'."
2790 (let ((match-data (get-text-property (or pos (point)) 'markdown-heading)))
2791 (when match-data
2792 (set-match-data match-data)
2793 t)))
2795 (defun markdown-pipe-at-bol-p ()
2796 "Return non-nil if the line begins with a pipe symbol.
2797 This may be useful for tables and Pandoc's line_blocks extension."
2798 (char-equal (char-after (point-at-bol)) ?|))
2801 ;;; Markdown Font Lock Matching Functions =====================================
2803 (defun markdown-range-property-any (begin end prop prop-values)
2804 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
2805 Also returns t if PROP is a list containing one of the PROP-VALUES.
2806 Return nil otherwise."
2807 (let (props)
2808 (catch 'found
2809 (dolist (loc (number-sequence begin end))
2810 (when (setq props (get-text-property loc prop))
2811 (cond ((listp props)
2812 ;; props is a list, check for membership
2813 (dolist (val prop-values)
2814 (when (memq val props) (throw 'found loc))))
2816 ;; props is a scalar, check for equality
2817 (dolist (val prop-values)
2818 (when (eq val props) (throw 'found loc))))))))))
2820 (defun markdown-range-properties-exist (begin end props)
2821 (cl-loop
2822 for loc in (number-sequence begin end)
2823 with result = nil
2824 while (not
2825 (setq result
2826 (cl-some (lambda (prop) (get-text-property loc prop)) props)))
2827 finally return result))
2829 (defun markdown-match-inline-generic (regex last &optional faceless)
2830 "Match inline REGEX from the point to LAST.
2831 When FACELESS is non-nil, do not return matches where faces have been applied."
2832 (when (re-search-forward regex last t)
2833 (let ((bounds (markdown-code-block-at-pos (match-beginning 1)))
2834 (face (and faceless (text-property-not-all
2835 (match-beginning 0) (match-end 0) 'face nil))))
2836 (cond
2837 ;; In code block: move past it and recursively search again
2838 (bounds
2839 (when (< (goto-char (cl-second bounds)) last)
2840 (markdown-match-inline-generic regex last faceless)))
2841 ;; When faces are found in the match range, skip over the match and
2842 ;; recursively search again.
2843 (face
2844 (when (< (goto-char (match-end 0)) last)
2845 (markdown-match-inline-generic regex last faceless)))
2846 ;; Keep match data and return t when in bounds.
2848 (<= (match-end 0) last))))))
2850 (defun markdown-match-code (last)
2851 "Match inline code fragments from point to LAST."
2852 (unless (bobp)
2853 (backward-char 1))
2854 (when (markdown-search-until-condition
2855 (lambda ()
2856 (and
2857 ;; Advance point in case of failure, but without exceeding last.
2858 (goto-char (min (1+ (match-beginning 1)) last))
2859 (not (markdown-in-comment-p (match-beginning 1)))
2860 (not (markdown-in-comment-p (match-end 1)))
2861 (not (markdown-code-block-at-pos (match-beginning 1)))))
2862 markdown-regex-code last t)
2863 (set-match-data (list (match-beginning 1) (match-end 1)
2864 (match-beginning 2) (match-end 2)
2865 (match-beginning 3) (match-end 3)
2866 (match-beginning 4) (match-end 4)))
2867 (goto-char (min (1+ (match-end 0)) last (point-max)))
2870 (defun markdown--gfm-markup-underscore-p (begin end)
2871 (let ((is-underscore (eql (char-after begin) ?_)))
2872 (if (not is-underscore)
2874 (save-excursion
2875 (save-match-data
2876 (goto-char begin)
2877 (and (looking-back "\\(?:^\\|[[:blank:][:punct:]]\\)" (1- begin))
2878 (progn
2879 (goto-char end)
2880 (looking-at-p "\\(?:[[:blank:][:punct:]]\\|$\\)"))))))))
2882 (defun markdown-match-bold (last)
2883 "Match inline bold from the point to LAST."
2884 (when (markdown-match-inline-generic markdown-regex-bold last)
2885 (let ((is-gfm (derived-mode-p 'gfm-mode))
2886 (begin (match-beginning 2))
2887 (end (match-end 2)))
2888 (if (or (markdown-inline-code-at-pos-p begin)
2889 (markdown-inline-code-at-pos-p end)
2890 (markdown-in-comment-p)
2891 (markdown-range-property-any
2892 begin begin 'face '(markdown-url-face
2893 markdown-plain-url-face))
2894 (markdown-range-property-any
2895 begin end 'face '(markdown-hr-face
2896 markdown-math-face))
2897 (and is-gfm (not (markdown--gfm-markup-underscore-p begin end))))
2898 (progn (goto-char (min (1+ begin) last))
2899 (when (< (point) last)
2900 (markdown-match-bold last)))
2901 (set-match-data (list (match-beginning 2) (match-end 2)
2902 (match-beginning 3) (match-end 3)
2903 (match-beginning 4) (match-end 4)
2904 (match-beginning 5) (match-end 5)))
2905 t))))
2907 (defun markdown-match-italic (last)
2908 "Match inline italics from the point to LAST."
2909 (let* ((is-gfm (derived-mode-p 'gfm-mode))
2910 (regex (if is-gfm
2911 markdown-regex-gfm-italic
2912 markdown-regex-italic)))
2913 (when (and (markdown-match-inline-generic regex last)
2914 (not (markdown--face-p
2915 (match-beginning 1)
2916 '(markdown-html-attr-name-face markdown-html-attr-value-face))))
2917 (let ((begin (match-beginning 1))
2918 (end (match-end 1))
2919 (close-end (match-end 4)))
2920 (if (or (eql (char-before begin) (char-after begin))
2921 (markdown-inline-code-at-pos-p begin)
2922 (markdown-inline-code-at-pos-p (1- end))
2923 (markdown-in-comment-p)
2924 (markdown-range-property-any
2925 begin begin 'face '(markdown-url-face
2926 markdown-plain-url-face))
2927 (markdown-range-property-any
2928 begin end 'face '(markdown-bold-face
2929 markdown-list-face
2930 markdown-hr-face
2931 markdown-math-face))
2932 (and is-gfm
2933 (or (char-equal (char-after begin) (char-after (1+ begin))) ;; check bold case
2934 (not (markdown--gfm-markup-underscore-p begin close-end)))))
2935 (progn (goto-char (min (1+ begin) last))
2936 (when (< (point) last)
2937 (markdown-match-italic last)))
2938 (set-match-data (list (match-beginning 1) (match-end 1)
2939 (match-beginning 2) (match-end 2)
2940 (match-beginning 3) (match-end 3)
2941 (match-beginning 4) (match-end 4)))
2942 t)))))
2944 (defun markdown--match-highlighting (last)
2945 (when markdown-enable-highlighting-syntax
2946 (re-search-forward markdown-regex-highlighting last t)))
2948 (defun markdown-match-math-generic (regex last)
2949 "Match REGEX from point to LAST.
2950 REGEX is either `markdown-regex-math-inline-single' for matching
2951 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
2952 (when (markdown-match-inline-generic regex last)
2953 (let ((begin (match-beginning 1)) (end (match-end 1)))
2954 (prog1
2955 (if (or (markdown-range-property-any
2956 begin end 'face
2957 '(markdown-inline-code-face markdown-bold-face))
2958 (markdown-range-properties-exist
2959 begin end
2960 (markdown-get-fenced-block-middle-properties)))
2961 (markdown-match-math-generic regex last)
2963 (goto-char (1+ (match-end 0)))))))
2965 (defun markdown-match-list-items (last)
2966 "Match list items from point to LAST."
2967 (let* ((first (point))
2968 (pos first)
2969 (prop 'markdown-list-item)
2970 (bounds (car (get-text-property pos prop))))
2971 (while
2972 (and (or (null (setq bounds (car (get-text-property pos prop))))
2973 (< (cl-first bounds) pos))
2974 (< (point) last)
2975 (setq pos (next-single-property-change pos prop nil last))
2976 (goto-char pos)))
2977 (when bounds
2978 (set-match-data (cl-seventh bounds))
2979 ;; Step at least one character beyond point. Otherwise
2980 ;; `font-lock-fontify-keywords-region' infloops.
2981 (goto-char (min (1+ (max (point-at-eol) first))
2982 (point-max)))
2983 t)))
2985 (defun markdown-match-math-single (last)
2986 "Match single quoted $..$ math from point to LAST."
2987 (when markdown-enable-math
2988 (when (and (char-equal (char-after) ?$)
2989 (not (bolp))
2990 (not (char-equal (char-before) ?\\))
2991 (not (char-equal (char-before) ?$)))
2992 (forward-char -1))
2993 (markdown-match-math-generic markdown-regex-math-inline-single last)))
2995 (defun markdown-match-math-double (last)
2996 "Match double quoted $$..$$ math from point to LAST."
2997 (when markdown-enable-math
2998 (when (and (< (1+ (point)) (point-max))
2999 (char-equal (char-after) ?$)
3000 (char-equal (char-after (1+ (point))) ?$)
3001 (not (bolp))
3002 (not (char-equal (char-before) ?\\))
3003 (not (char-equal (char-before) ?$)))
3004 (forward-char -1))
3005 (markdown-match-math-generic markdown-regex-math-inline-double last)))
3007 (defun markdown-match-math-display (last)
3008 "Match bracketed display math \[..\] and \\[..\\] from point to LAST."
3009 (when markdown-enable-math
3010 (markdown-match-math-generic markdown-regex-math-display last)))
3012 (defun markdown-match-propertized-text (property last)
3013 "Match text with PROPERTY from point to LAST.
3014 Restore match data previously stored in PROPERTY."
3015 (let ((saved (get-text-property (point) property))
3016 pos)
3017 (unless saved
3018 (setq pos (next-single-property-change (point) property nil last))
3019 (unless (= pos last)
3020 (setq saved (get-text-property pos property))))
3021 (when saved
3022 (set-match-data saved)
3023 ;; Step at least one character beyond point. Otherwise
3024 ;; `font-lock-fontify-keywords-region' infloops.
3025 (goto-char (min (1+ (max (match-end 0) (point)))
3026 (point-max)))
3027 saved)))
3029 (defun markdown-match-pre-blocks (last)
3030 "Match preformatted blocks from point to LAST.
3031 Use data stored in 'markdown-pre text property during syntax
3032 analysis."
3033 (markdown-match-propertized-text 'markdown-pre last))
3035 (defun markdown-match-gfm-code-blocks (last)
3036 "Match GFM quoted code blocks from point to LAST.
3037 Use data stored in 'markdown-gfm-code text property during syntax
3038 analysis."
3039 (markdown-match-propertized-text 'markdown-gfm-code last))
3041 (defun markdown-match-gfm-open-code-blocks (last)
3042 (markdown-match-propertized-text 'markdown-gfm-block-begin last))
3044 (defun markdown-match-gfm-close-code-blocks (last)
3045 (markdown-match-propertized-text 'markdown-gfm-block-end last))
3047 (defun markdown-match-fenced-code-blocks (last)
3048 "Match fenced code blocks from the point to LAST."
3049 (markdown-match-propertized-text 'markdown-fenced-code last))
3051 (defun markdown-match-fenced-start-code-block (last)
3052 (markdown-match-propertized-text 'markdown-tilde-fence-begin last))
3054 (defun markdown-match-fenced-end-code-block (last)
3055 (markdown-match-propertized-text 'markdown-tilde-fence-end last))
3057 (defun markdown-match-blockquotes (last)
3058 "Match blockquotes from point to LAST.
3059 Use data stored in 'markdown-blockquote text property during syntax
3060 analysis."
3061 (markdown-match-propertized-text 'markdown-blockquote last))
3063 (defun markdown-match-hr (last)
3064 "Match horizontal rules comments from the point to LAST."
3065 (markdown-match-propertized-text 'markdown-hr last))
3067 (defun markdown-match-comments (last)
3068 "Match HTML comments from the point to LAST."
3069 (when (and (skip-syntax-forward "^<" last))
3070 (let ((beg (point)))
3071 (when (and (skip-syntax-forward "^>" last) (< (point) last))
3072 (forward-char)
3073 (set-match-data (list beg (point)))
3074 t))))
3076 (defun markdown-match-generic-links (last ref)
3077 "Match inline links from point to LAST.
3078 When REF is non-nil, match reference links instead of standard
3079 links with URLs.
3080 This function should only be used during font-lock, as it
3081 determines syntax based on the presence of faces for previously
3082 processed elements."
3083 ;; Search for the next potential link (not in a code block).
3084 (let ((prohibited-faces '(markdown-pre-face
3085 markdown-code-face
3086 markdown-inline-code-face
3087 markdown-comment-face))
3088 found)
3089 (while
3090 (and (not found) (< (point) last)
3091 (progn
3092 ;; Clear match data to test for a match after functions returns.
3093 (set-match-data nil)
3094 ;; Preliminary regular expression search so we can return
3095 ;; quickly upon failure. This doesn't handle malformed links
3096 ;; or nested square brackets well, so if it passes we back up
3097 ;; continue with a more precise search.
3098 (re-search-forward
3099 (if ref
3100 markdown-regex-link-reference
3101 markdown-regex-link-inline)
3102 last 'limit)))
3103 ;; Keep searching if this is in a code block, inline code, or a
3104 ;; comment, or if it is include syntax. The link text portion
3105 ;; (group 3) may contain inline code or comments, but the
3106 ;; markup, URL, and title should not be part of such elements.
3107 (if (or (markdown-range-property-any
3108 (match-beginning 0) (match-end 2) 'face prohibited-faces)
3109 (markdown-range-property-any
3110 (match-beginning 4) (match-end 0) 'face prohibited-faces)
3111 (and (char-equal (char-after (point-at-bol)) ?<)
3112 (char-equal (char-after (1+ (point-at-bol))) ?<)))
3113 (set-match-data nil)
3114 (setq found t))))
3115 ;; Match opening exclamation point (optional) and left bracket.
3116 (when (match-beginning 2)
3117 (let* ((bang (match-beginning 1))
3118 (first-begin (match-beginning 2))
3119 ;; Find end of block to prevent matching across blocks.
3120 (end-of-block (save-excursion
3121 (progn
3122 (goto-char (match-beginning 2))
3123 (markdown-end-of-text-block)
3124 (point))))
3125 ;; Move over balanced expressions to closing right bracket.
3126 ;; Catch unbalanced expression errors and return nil.
3127 (first-end (condition-case nil
3128 (and (goto-char first-begin)
3129 (scan-sexps (point) 1))
3130 (error nil)))
3131 ;; Continue with point at CONT-POINT upon failure.
3132 (cont-point (min (1+ first-begin) last))
3133 second-begin second-end url-begin url-end
3134 title-begin title-end)
3135 ;; When bracket found, in range, and followed by a left paren/bracket...
3136 (when (and first-end (< first-end end-of-block) (goto-char first-end)
3137 (char-equal (char-after (point)) (if ref ?\[ ?\()))
3138 ;; Scan across balanced expressions for closing parenthesis/bracket.
3139 (setq second-begin (point)
3140 second-end (condition-case nil
3141 (scan-sexps (point) 1)
3142 (error nil)))
3143 ;; Check that closing parenthesis/bracket is in range.
3144 (if (and second-end (<= second-end end-of-block) (<= second-end last))
3145 (progn
3146 ;; Search for (optional) title inside closing parenthesis
3147 (when (and (not ref) (search-forward "\"" second-end t))
3148 (setq title-begin (1- (point))
3149 title-end (and (goto-char second-end)
3150 (search-backward "\"" (1+ title-begin) t))
3151 title-end (and title-end (1+ title-end))))
3152 ;; Store URL/reference range
3153 (setq url-begin (1+ second-begin)
3154 url-end (1- (or title-begin second-end)))
3155 ;; Set match data, move point beyond link, and return
3156 (set-match-data
3157 (list (or bang first-begin) second-end ; 0 - all
3158 bang (and bang (1+ bang)) ; 1 - bang
3159 first-begin (1+ first-begin) ; 2 - markup
3160 (1+ first-begin) (1- first-end) ; 3 - link text
3161 (1- first-end) first-end ; 4 - markup
3162 second-begin (1+ second-begin) ; 5 - markup
3163 url-begin url-end ; 6 - url/reference
3164 title-begin title-end ; 7 - title
3165 (1- second-end) second-end)) ; 8 - markup
3166 ;; Nullify cont-point and leave point at end and
3167 (setq cont-point nil)
3168 (goto-char second-end))
3169 ;; If no closing parenthesis in range, update continuation point
3170 (setq cont-point (min end-of-block second-begin))))
3171 (cond
3172 ;; On failure, continue searching at cont-point
3173 ((and cont-point (< cont-point last))
3174 (goto-char cont-point)
3175 (markdown-match-generic-links last ref))
3176 ;; No more text, return nil
3177 ((and cont-point (= cont-point last))
3178 nil)
3179 ;; Return t if a match occurred
3180 (t t)))))
3182 (defun markdown-match-angle-uris (last)
3183 "Match angle bracket URIs from point to LAST."
3184 (when (markdown-match-inline-generic markdown-regex-angle-uri last)
3185 (goto-char (1+ (match-end 0)))))
3187 (defun markdown-match-plain-uris (last)
3188 "Match plain URIs from point to LAST."
3189 (when (markdown-match-inline-generic markdown-regex-uri last t)
3190 (goto-char (1+ (match-end 0)))))
3192 (defvar markdown-conditional-search-function #'re-search-forward
3193 "Conditional search function used in `markdown-search-until-condition'.
3194 Made into a variable to allow for dynamic let-binding.")
3196 (defun markdown-search-until-condition (condition &rest args)
3197 (let (ret)
3198 (while (and (not ret) (apply markdown-conditional-search-function args))
3199 (setq ret (funcall condition)))
3200 ret))
3202 (defun markdown-metadata-line-p (pos regexp)
3203 (save-excursion
3204 (or (= (line-number-at-pos pos) 1)
3205 (progn
3206 (forward-line -1)
3207 ;; skip multi-line metadata
3208 (while (and (looking-at-p "^\\s-+[[:alpha:]]")
3209 (> (line-number-at-pos (point)) 1))
3210 (forward-line -1))
3211 (looking-at-p regexp)))))
3213 (defun markdown-match-generic-metadata (regexp last)
3214 "Match metadata declarations specified by REGEXP from point to LAST.
3215 These declarations must appear inside a metadata block that begins at
3216 the beginning of the buffer and ends with a blank line (or the end of
3217 the buffer)."
3218 (let* ((first (point))
3219 (end-re "\n[ \t]*\n\\|\n\\'\\|\\'")
3220 (block-begin (goto-char 1))
3221 (block-end (re-search-forward end-re nil t)))
3222 (if (and block-end (> first block-end))
3223 ;; Don't match declarations if there is no metadata block or if
3224 ;; the point is beyond the block. Move point to point-max to
3225 ;; prevent additional searches and return return nil since nothing
3226 ;; was found.
3227 (progn (goto-char (point-max)) nil)
3228 ;; If a block was found that begins before LAST and ends after
3229 ;; point, search for declarations inside it. If the starting is
3230 ;; before the beginning of the block, start there. Otherwise,
3231 ;; move back to FIRST.
3232 (goto-char (if (< first block-begin) block-begin first))
3233 (if (and (re-search-forward regexp (min last block-end) t)
3234 (markdown-metadata-line-p (point) regexp))
3235 ;; If a metadata declaration is found, set match-data and return t.
3236 (let ((key-beginning (match-beginning 1))
3237 (key-end (match-end 1))
3238 (markup-begin (match-beginning 2))
3239 (markup-end (match-end 2))
3240 (value-beginning (match-beginning 3)))
3241 (set-match-data (list key-beginning (point) ; complete metadata
3242 key-beginning key-end ; key
3243 markup-begin markup-end ; markup
3244 value-beginning (point))) ; value
3246 ;; Otherwise, move the point to last and return nil
3247 (goto-char last)
3248 nil))))
3250 (defun markdown-match-declarative-metadata (last)
3251 "Match declarative metadata from the point to LAST."
3252 (markdown-match-generic-metadata markdown-regex-declarative-metadata last))
3254 (defun markdown-match-pandoc-metadata (last)
3255 "Match Pandoc metadata from the point to LAST."
3256 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
3258 (defun markdown-match-yaml-metadata-begin (last)
3259 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last))
3261 (defun markdown-match-yaml-metadata-end (last)
3262 (markdown-match-propertized-text 'markdown-yaml-metadata-end last))
3264 (defun markdown-match-yaml-metadata-key (last)
3265 (markdown-match-propertized-text 'markdown-metadata-key last))
3267 (defun markdown-match-wiki-link (last)
3268 "Match wiki links from point to LAST."
3269 (when (and markdown-enable-wiki-links
3270 (not markdown-wiki-link-fontify-missing)
3271 (markdown-match-inline-generic markdown-regex-wiki-link last))
3272 (let ((begin (match-beginning 1)) (end (match-end 1)))
3273 (if (or (markdown-in-comment-p begin)
3274 (markdown-in-comment-p end)
3275 (markdown-inline-code-at-pos-p begin)
3276 (markdown-inline-code-at-pos-p end)
3277 (markdown-code-block-at-pos begin))
3278 (progn (goto-char (min (1+ begin) last))
3279 (when (< (point) last)
3280 (markdown-match-wiki-link last)))
3281 (set-match-data (list begin end))
3282 t))))
3284 (defun markdown-match-inline-attributes (last)
3285 "Match inline attributes from point to LAST."
3286 ;; #428 re-search-forward markdown-regex-inline-attributes is very slow.
3287 ;; So use simple regex for re-search-forward and use markdown-regex-inline-attributes
3288 ;; against matched string.
3289 (when (markdown-match-inline-generic "[ \t]*\\({\\)\\([^\n]*\\)}[ \t]*$" last)
3290 (if (not (string-match-p markdown-regex-inline-attributes (match-string 0)))
3291 (markdown-match-inline-attributes last)
3292 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
3293 (markdown-inline-code-at-pos-p (match-end 0))
3294 (markdown-in-comment-p))
3295 t))))
3297 (defun markdown-match-leanpub-sections (last)
3298 "Match Leanpub section markers from point to LAST."
3299 (when (markdown-match-inline-generic markdown-regex-leanpub-sections last)
3300 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
3301 (markdown-inline-code-at-pos-p (match-end 0))
3302 (markdown-in-comment-p))
3303 t)))
3305 (defun markdown-match-includes (last)
3306 "Match include statements from point to LAST.
3307 Sets match data for the following seven groups:
3308 Group 1: opening two angle brackets
3309 Group 2: opening title delimiter (optional)
3310 Group 3: title text (optional)
3311 Group 4: closing title delimiter (optional)
3312 Group 5: opening filename delimiter
3313 Group 6: filename
3314 Group 7: closing filename delimiter"
3315 (when (markdown-match-inline-generic markdown-regex-include last)
3316 (let ((valid (not (or (markdown-in-comment-p (match-beginning 0))
3317 (markdown-in-comment-p (match-end 0))
3318 (markdown-code-block-at-pos (match-beginning 0))))))
3319 (cond
3320 ;; Parentheses and maybe square brackets, but no curly braces:
3321 ;; match optional title in square brackets and file in parentheses.
3322 ((and valid (match-beginning 5)
3323 (not (match-beginning 8)))
3324 (set-match-data (list (match-beginning 1) (match-end 7)
3325 (match-beginning 1) (match-end 1)
3326 (match-beginning 2) (match-end 2)
3327 (match-beginning 3) (match-end 3)
3328 (match-beginning 4) (match-end 4)
3329 (match-beginning 5) (match-end 5)
3330 (match-beginning 6) (match-end 6)
3331 (match-beginning 7) (match-end 7))))
3332 ;; Only square brackets present: match file in square brackets.
3333 ((and valid (match-beginning 2)
3334 (not (match-beginning 5))
3335 (not (match-beginning 7)))
3336 (set-match-data (list (match-beginning 1) (match-end 4)
3337 (match-beginning 1) (match-end 1)
3338 nil nil
3339 nil nil
3340 nil nil
3341 (match-beginning 2) (match-end 2)
3342 (match-beginning 3) (match-end 3)
3343 (match-beginning 4) (match-end 4))))
3344 ;; Only curly braces present: match file in curly braces.
3345 ((and valid (match-beginning 8)
3346 (not (match-beginning 2))
3347 (not (match-beginning 5)))
3348 (set-match-data (list (match-beginning 1) (match-end 10)
3349 (match-beginning 1) (match-end 1)
3350 nil nil
3351 nil nil
3352 nil nil
3353 (match-beginning 8) (match-end 8)
3354 (match-beginning 9) (match-end 9)
3355 (match-beginning 10) (match-end 10))))
3357 ;; Not a valid match, move to next line and search again.
3358 (forward-line)
3359 (when (< (point) last)
3360 (setq valid (markdown-match-includes last)))))
3361 valid)))
3363 (defun markdown-match-html-tag (last)
3364 "Match HTML tags from point to LAST."
3365 (when (and markdown-enable-html
3366 (markdown-match-inline-generic markdown-regex-html-tag last t))
3367 (set-match-data (list (match-beginning 0) (match-end 0)
3368 (match-beginning 1) (match-end 1)
3369 (match-beginning 2) (match-end 2)
3370 (match-beginning 9) (match-end 9)))
3374 ;;; Markdown Font Fontification Functions =====================================
3376 (defvar markdown--first-displayable-cache (make-hash-table :test #'equal))
3378 (defun markdown--first-displayable (seq)
3379 "Return the first displayable character or string in SEQ.
3380 SEQ may be an atom or a sequence."
3381 (let ((c (gethash seq markdown--first-displayable-cache t)))
3382 (if (not (eq c t))
3384 (puthash seq
3385 (let ((seq (if (listp seq) seq (list seq))))
3386 (cond ((stringp (car seq))
3387 (cl-find-if
3388 (lambda (str)
3389 (and (mapcar #'char-displayable-p (string-to-list str))))
3390 seq))
3391 ((characterp (car seq))
3392 (cl-find-if #'char-displayable-p seq))))
3393 markdown--first-displayable-cache))))
3395 (defun markdown--marginalize-string (level)
3396 "Generate atx markup string of given LEVEL for left margin."
3397 (let ((margin-left-space-count
3398 (- markdown-marginalize-headers-margin-width level)))
3399 (concat (make-string margin-left-space-count ? )
3400 (make-string level ?#))))
3402 (defun markdown-marginalize-update-current ()
3403 "Update the window configuration to create a left margin."
3404 (if window-system
3405 (let* ((header-delimiter-font-width
3406 (window-font-width nil 'markdown-header-delimiter-face))
3407 (margin-pixel-width (* markdown-marginalize-headers-margin-width
3408 header-delimiter-font-width))
3409 (margin-char-width (/ margin-pixel-width (default-font-width))))
3410 (set-window-margins nil margin-char-width))
3411 ;; As a fallback, simply set margin based on character count.
3412 (set-window-margins nil (1+ markdown-marginalize-headers-margin-width))))
3414 (defun markdown-fontify-headings (last)
3415 "Add text properties to headings from point to LAST."
3416 (when (markdown-match-propertized-text 'markdown-heading last)
3417 (let* ((level (markdown-outline-level))
3418 (heading-face
3419 (intern (format "markdown-header-face-%d" level)))
3420 (heading-props `(face ,heading-face))
3421 (left-markup-props
3422 `(face markdown-header-delimiter-face
3423 ,@(cond
3424 (markdown-hide-markup
3425 `(display ""))
3426 (markdown-marginalize-headers
3427 `(display ((margin left-margin)
3428 ,(markdown--marginalize-string level)))))))
3429 (right-markup-props
3430 `(face markdown-header-delimiter-face
3431 ,@(when markdown-hide-markup `(display ""))))
3432 (rule-props `(face markdown-header-rule-face
3433 ,@(when markdown-hide-markup `(display "")))))
3434 (if (match-end 1)
3435 ;; Setext heading
3436 (progn (add-text-properties
3437 (match-beginning 1) (match-end 1) heading-props)
3438 (if (= level 1)
3439 (add-text-properties
3440 (match-beginning 2) (match-end 2) rule-props)
3441 (add-text-properties
3442 (match-beginning 3) (match-end 3) rule-props)))
3443 ;; atx heading
3444 (if markdown-fontify-whole-heading-line
3445 (let ((header-end (min (point-max) (1+ (match-end 0)))))
3446 (add-text-properties
3447 (match-beginning 0) header-end heading-props))
3448 (add-text-properties
3449 (match-beginning 4) (match-end 4) left-markup-props)
3450 (add-text-properties
3451 (match-beginning 5) (match-end 5) heading-props)
3452 (when (match-end 6)
3453 (add-text-properties
3454 (match-beginning 6) (match-end 6) right-markup-props)))))
3457 (defun markdown-fontify-tables (last)
3458 (when (re-search-forward "|" last t)
3459 (when (markdown-table-at-point-p)
3460 (font-lock-append-text-property
3461 (line-beginning-position) (min (1+ (line-end-position)) (point-max))
3462 'face 'markdown-table-face))
3463 (forward-line 1)
3466 (defun markdown-fontify-blockquotes (last)
3467 "Apply font-lock properties to blockquotes from point to LAST."
3468 (when (markdown-match-blockquotes last)
3469 (let ((display-string
3470 (markdown--first-displayable markdown-blockquote-display-char)))
3471 (add-text-properties
3472 (match-beginning 1) (match-end 1)
3473 (if markdown-hide-markup
3474 `(face markdown-blockquote-face display ,display-string)
3475 `(face markdown-markup-face)))
3476 (font-lock-append-text-property
3477 (match-beginning 0) (match-end 0) 'face 'markdown-blockquote-face)
3478 t)))
3480 (defun markdown-fontify-list-items (last)
3481 "Apply font-lock properties to list markers from point to LAST."
3482 (when (markdown-match-list-items last)
3483 (when (not (markdown-code-block-at-point-p (match-beginning 2)))
3484 (let* ((indent (length (match-string-no-properties 1)))
3485 (level (/ indent markdown-list-indent-width)) ;; level = 0, 1, 2, ...
3486 (bullet (nth (mod level (length markdown-list-item-bullets))
3487 markdown-list-item-bullets)))
3488 (add-text-properties
3489 (match-beginning 2) (match-end 2) '(face markdown-list-face))
3490 (when markdown-hide-markup
3491 (cond
3492 ;; Unordered lists
3493 ((string-match-p "[\\*\\+-]" (match-string 2))
3494 (add-text-properties
3495 (match-beginning 2) (match-end 2) `(display ,bullet)))
3496 ;; Definition lists
3497 ((string-equal ":" (match-string 2))
3498 (let ((display-string
3499 (char-to-string (markdown--first-displayable
3500 markdown-definition-display-char))))
3501 (add-text-properties (match-beginning 2) (match-end 2)
3502 `(display ,display-string))))))))
3505 (defun markdown-fontify-hrs (last)
3506 "Add text properties to horizontal rules from point to LAST."
3507 (when (markdown-match-hr last)
3508 (let ((hr-char (markdown--first-displayable markdown-hr-display-char)))
3509 (add-text-properties
3510 (match-beginning 0) (match-end 0)
3511 `(face markdown-hr-face
3512 font-lock-multiline t
3513 ,@(when (and markdown-hide-markup hr-char)
3514 `(display ,(make-string
3515 (1- (window-body-width)) hr-char)))))
3516 t)))
3518 (defun markdown-fontify-sub-superscripts (last)
3519 "Apply text properties to sub- and superscripts from point to LAST."
3520 (when (markdown-search-until-condition
3521 (lambda () (and (not (markdown-code-block-at-point-p))
3522 (not (markdown-inline-code-at-point-p))
3523 (not (markdown-in-comment-p))))
3524 markdown-regex-sub-superscript last t)
3525 (let* ((subscript-p (string= (match-string 2) "~"))
3526 (props
3527 (if subscript-p
3528 (car markdown-sub-superscript-display)
3529 (cdr markdown-sub-superscript-display)))
3530 (mp (list 'face 'markdown-markup-face
3531 'invisible 'markdown-markup)))
3532 (when markdown-hide-markup
3533 (put-text-property (match-beginning 3) (match-end 3)
3534 'display props))
3535 (add-text-properties (match-beginning 2) (match-end 2) mp)
3536 (add-text-properties (match-beginning 4) (match-end 4) mp)
3537 t)))
3540 ;;; Syntax Table ==============================================================
3542 (defvar markdown-mode-syntax-table
3543 (let ((tab (make-syntax-table text-mode-syntax-table)))
3544 (modify-syntax-entry ?\" "." tab)
3545 tab)
3546 "Syntax table for `markdown-mode'.")
3549 ;;; Element Insertion =========================================================
3551 (defun markdown-ensure-blank-line-before ()
3552 "If previous line is not already blank, insert a blank line before point."
3553 (unless (bolp) (insert "\n"))
3554 (unless (or (bobp) (looking-back "\n\\s-*\n" nil)) (insert "\n")))
3556 (defun markdown-ensure-blank-line-after ()
3557 "If following line is not already blank, insert a blank line after point.
3558 Return the point where it was originally."
3559 (save-excursion
3560 (unless (eolp) (insert "\n"))
3561 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
3563 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
3564 "Insert the strings S1 and S2, wrapping around region or THING.
3565 If a region is specified by the optional BEG and END arguments,
3566 wrap the strings S1 and S2 around that region.
3567 If there is an active region, wrap the strings S1 and S2 around
3568 the region. If there is not an active region but the point is at
3569 THING, wrap that thing (which defaults to word). Otherwise, just
3570 insert S1 and S2 and place the point in between. Return the
3571 bounds of the entire wrapped string, or nil if nothing was wrapped
3572 and S1 and S2 were only inserted."
3573 (let (a b bounds new-point)
3574 (cond
3575 ;; Given region
3576 ((and beg end)
3577 (setq a beg
3578 b end
3579 new-point (+ (point) (length s1))))
3580 ;; Active region
3581 ((use-region-p)
3582 (setq a (region-beginning)
3583 b (region-end)
3584 new-point (+ (point) (length s1))))
3585 ;; Thing (word) at point
3586 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
3587 (setq a (car bounds)
3588 b (cdr bounds)
3589 new-point (+ (point) (length s1))))
3590 ;; No active region and no word
3592 (setq a (point)
3593 b (point))))
3594 (goto-char b)
3595 (insert s2)
3596 (goto-char a)
3597 (insert s1)
3598 (when new-point (goto-char new-point))
3599 (if (= a b)
3601 (setq b (+ b (length s1) (length s2)))
3602 (cons a b))))
3604 (defun markdown-point-after-unwrap (cur prefix suffix)
3605 "Return desired position of point after an unwrapping operation.
3606 CUR gives the position of the point before the operation.
3607 Additionally, two cons cells must be provided. PREFIX gives the
3608 bounds of the prefix string and SUFFIX gives the bounds of the
3609 suffix string."
3610 (cond ((< cur (cdr prefix)) (car prefix))
3611 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
3612 ((<= cur (cdr suffix))
3613 (- cur (+ (- (cdr prefix) (car prefix))
3614 (- cur (car suffix)))))
3615 (t cur)))
3617 (defun markdown-unwrap-thing-at-point (regexp all text)
3618 "Remove prefix and suffix of thing at point and reposition the point.
3619 When the thing at point matches REGEXP, replace the subexpression
3620 ALL with the string in subexpression TEXT. Reposition the point
3621 in an appropriate location accounting for the removal of prefix
3622 and suffix strings. Return new bounds of string from group TEXT.
3623 When REGEXP is nil, assumes match data is already set."
3624 (when (or (null regexp)
3625 (thing-at-point-looking-at regexp))
3626 (let ((cur (point))
3627 (prefix (cons (match-beginning all) (match-beginning text)))
3628 (suffix (cons (match-end text) (match-end all)))
3629 (bounds (cons (match-beginning text) (match-end text))))
3630 ;; Replace the thing at point
3631 (replace-match (match-string text) t t nil all)
3632 ;; Reposition the point
3633 (goto-char (markdown-point-after-unwrap cur prefix suffix))
3634 ;; Adjust bounds
3635 (setq bounds (cons (car prefix)
3636 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
3638 (defun markdown-unwrap-things-in-region (beg end regexp all text)
3639 "Remove prefix and suffix of all things in region from BEG to END.
3640 When a thing in the region matches REGEXP, replace the
3641 subexpression ALL with the string in subexpression TEXT.
3642 Return a cons cell containing updated bounds for the region."
3643 (save-excursion
3644 (goto-char beg)
3645 (let ((removed 0) len-all len-text)
3646 (while (re-search-forward regexp (- end removed) t)
3647 (setq len-all (length (match-string-no-properties all)))
3648 (setq len-text (length (match-string-no-properties text)))
3649 (setq removed (+ removed (- len-all len-text)))
3650 (replace-match (match-string text) t t nil all))
3651 (cons beg (- end removed)))))
3653 (defun markdown-insert-hr (arg)
3654 "Insert or replace a horizontal rule.
3655 By default, use the first element of `markdown-hr-strings'. When
3656 ARG is non-nil, as when given a prefix, select a different
3657 element as follows. When prefixed with \\[universal-argument],
3658 use the last element of `markdown-hr-strings' instead. When
3659 prefixed with an integer from 1 to the length of
3660 `markdown-hr-strings', use the element in that position instead."
3661 (interactive "*P")
3662 (when (thing-at-point-looking-at markdown-regex-hr)
3663 (delete-region (match-beginning 0) (match-end 0)))
3664 (markdown-ensure-blank-line-before)
3665 (cond ((equal arg '(4))
3666 (insert (car (reverse markdown-hr-strings))))
3667 ((and (integerp arg) (> arg 0)
3668 (<= arg (length markdown-hr-strings)))
3669 (insert (nth (1- arg) markdown-hr-strings)))
3671 (insert (car markdown-hr-strings))))
3672 (markdown-ensure-blank-line-after))
3674 (defun markdown--insert-common (start-delim end-delim regex start-group end-group face
3675 &optional skip-space)
3676 (if (use-region-p)
3677 ;; Active region
3678 (let* ((bounds (markdown-unwrap-things-in-region
3679 (region-beginning) (region-end)
3680 regex start-group end-group))
3681 (beg (car bounds))
3682 (end (cdr bounds)))
3683 (when (and beg skip-space)
3684 (save-excursion
3685 (goto-char beg)
3686 (skip-chars-forward "[ \t]")
3687 (setq beg (point))))
3688 (when (and end skip-space)
3689 (save-excursion
3690 (goto-char end)
3691 (skip-chars-backward "[ \t]")
3692 (setq end (point))))
3693 (markdown-wrap-or-insert start-delim end-delim nil beg end))
3694 (if (markdown--face-p (point) (list face))
3695 (save-excursion
3696 (while (and (markdown--face-p (point) (list face)) (not (bobp)))
3697 (forward-char -1))
3698 (forward-char (- (1- (length start-delim)))) ;; for delimiter
3699 (unless (bolp)
3700 (forward-char -1))
3701 (when (looking-at regex)
3702 (markdown-unwrap-thing-at-point nil start-group end-group)))
3703 (if (thing-at-point-looking-at regex)
3704 (markdown-unwrap-thing-at-point nil start-group end-group)
3705 (markdown-wrap-or-insert start-delim end-delim 'word nil nil)))))
3707 (defun markdown-insert-bold ()
3708 "Insert markup to make a region or word bold.
3709 If there is an active region, make the region bold. If the point
3710 is at a non-bold word, make the word bold. If the point is at a
3711 bold word or phrase, remove the bold markup. Otherwise, simply
3712 insert bold delimiters and place the point in between them."
3713 (interactive)
3714 (let ((delim (if markdown-bold-underscore "__" "**")))
3715 (markdown--insert-common delim delim markdown-regex-bold 2 4 'markdown-bold-face t)))
3717 (defun markdown-insert-italic ()
3718 "Insert markup to make a region or word italic.
3719 If there is an active region, make the region italic. If the point
3720 is at a non-italic word, make the word italic. If the point is at an
3721 italic word or phrase, remove the italic markup. Otherwise, simply
3722 insert italic delimiters and place the point in between them."
3723 (interactive)
3724 (let ((delim (if markdown-italic-underscore "_" "*")))
3725 (markdown--insert-common delim delim markdown-regex-italic 1 3 'markdown-italic-face t)))
3727 (defun markdown-insert-strike-through ()
3728 "Insert markup to make a region or word strikethrough.
3729 If there is an active region, make the region strikethrough. If the point
3730 is at a non-bold word, make the word strikethrough. If the point is at a
3731 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
3732 simply insert bold delimiters and place the point in between them."
3733 (interactive)
3734 (markdown--insert-common
3735 "~~" "~~" markdown-regex-strike-through 2 4 'markdown-strike-through-face t))
3737 (defun markdown-insert-code ()
3738 "Insert markup to make a region or word an inline code fragment.
3739 If there is an active region, make the region an inline code
3740 fragment. If the point is at a word, make the word an inline
3741 code fragment. Otherwise, simply insert code delimiters and
3742 place the point in between them."
3743 (interactive)
3744 (if (use-region-p)
3745 ;; Active region
3746 (let ((bounds (markdown-unwrap-things-in-region
3747 (region-beginning) (region-end)
3748 markdown-regex-code 1 3)))
3749 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
3750 ;; Code markup removal, code markup for word, or empty markup insertion
3751 (if (markdown-inline-code-at-point)
3752 (markdown-unwrap-thing-at-point nil 0 2)
3753 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
3755 (defun markdown-insert-kbd ()
3756 "Insert markup to wrap region or word in <kbd> tags.
3757 If there is an active region, use the region. If the point is at
3758 a word, use the word. Otherwise, simply insert <kbd> tags and
3759 place the point in between them."
3760 (interactive)
3761 (if (use-region-p)
3762 ;; Active region
3763 (let ((bounds (markdown-unwrap-things-in-region
3764 (region-beginning) (region-end)
3765 markdown-regex-kbd 0 2)))
3766 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil (car bounds) (cdr bounds)))
3767 ;; Markup removal, markup for word, or empty markup insertion
3768 (if (thing-at-point-looking-at markdown-regex-kbd)
3769 (markdown-unwrap-thing-at-point nil 0 2)
3770 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil))))
3772 (defun markdown-insert-inline-link (text url &optional title)
3773 "Insert an inline link with TEXT pointing to URL.
3774 Optionally, the user can provide a TITLE."
3775 (let ((cur (point)))
3776 (setq title (and title (concat " \"" title "\"")))
3777 (insert (concat "[" text "](" url title ")"))
3778 (cond ((not text) (goto-char (+ 1 cur)))
3779 ((not url) (goto-char (+ 3 (length text) cur))))))
3781 (defun markdown-insert-inline-image (text url &optional title)
3782 "Insert an inline link with alt TEXT pointing to URL.
3783 Optionally, also provide a TITLE."
3784 (let ((cur (point)))
3785 (setq title (and title (concat " \"" title "\"")))
3786 (insert (concat "![" text "](" url title ")"))
3787 (cond ((not text) (goto-char (+ 2 cur)))
3788 ((not url) (goto-char (+ 4 (length text) cur))))))
3790 (defun markdown-insert-reference-link (text label &optional url title)
3791 "Insert a reference link and, optionally, a reference definition.
3792 The link TEXT will be inserted followed by the optional LABEL.
3793 If a URL is given, also insert a definition for the reference
3794 LABEL according to `markdown-reference-location'. If a TITLE is
3795 given, it will be added to the end of the reference definition
3796 and will be used to populate the title attribute when converted
3797 to XHTML. If URL is nil, insert only the link portion (for
3798 example, when a reference label is already defined)."
3799 (insert (concat "[" text "][" label "]"))
3800 (when url
3801 (markdown-insert-reference-definition
3802 (if (string-equal label "") text label)
3803 url title)))
3805 (defun markdown-insert-reference-image (text label &optional url title)
3806 "Insert a reference image and, optionally, a reference definition.
3807 The alt TEXT will be inserted followed by the optional LABEL.
3808 If a URL is given, also insert a definition for the reference
3809 LABEL according to `markdown-reference-location'. If a TITLE is
3810 given, it will be added to the end of the reference definition
3811 and will be used to populate the title attribute when converted
3812 to XHTML. If URL is nil, insert only the link portion (for
3813 example, when a reference label is already defined)."
3814 (insert (concat "![" text "][" label "]"))
3815 (when url
3816 (markdown-insert-reference-definition
3817 (if (string-equal label "") text label)
3818 url title)))
3820 (defun markdown-insert-reference-definition (label &optional url title)
3821 "Add definition for reference LABEL with URL and TITLE.
3822 LABEL is a Markdown reference label without square brackets.
3823 URL and TITLE are optional. When given, the TITLE will
3824 be used to populate the title attribute when converted to XHTML."
3825 ;; END specifies where to leave the point upon return
3826 (let ((end (point)))
3827 (cl-case markdown-reference-location
3828 (end (goto-char (point-max)))
3829 (immediately (markdown-end-of-text-block))
3830 (subtree (markdown-end-of-subtree))
3831 (header (markdown-end-of-defun)))
3832 ;; Skip backwards over local variables. This logic is similar to the one
3833 ;; used in ‘hack-local-variables’.
3834 (when (and enable-local-variables (eobp))
3835 (search-backward "\n\f" (max (- (point) 3000) (point-min)) :move)
3836 (when (let ((case-fold-search t))
3837 (search-forward "Local Variables:" nil :move))
3838 (beginning-of-line 0)
3839 (when (eq (char-before) ?\n) (backward-char))))
3840 (unless (or (markdown-cur-line-blank-p)
3841 (thing-at-point-looking-at markdown-regex-reference-definition))
3842 (insert "\n"))
3843 (insert "\n[" label "]: ")
3844 (if url
3845 (insert url)
3846 ;; When no URL is given, leave point at END following the colon
3847 (setq end (point)))
3848 (when (> (length title) 0)
3849 (insert " \"" title "\""))
3850 (unless (looking-at-p "\n")
3851 (insert "\n"))
3852 (goto-char end)
3853 (when url
3854 (message
3855 (markdown--substitute-command-keys
3856 "Reference [%s] was defined, press \\[markdown-do] to jump there")
3857 label))))
3859 (defcustom markdown-link-make-text-function nil
3860 "Function that automatically generates a link text for a URL.
3862 If non-nil, this function will be called by
3863 `markdown--insert-link-or-image' and the result will be the
3864 default link text. The function should receive exactly one
3865 argument that corresponds to the link URL."
3866 :group 'markdown
3867 :type 'function
3868 :package-version '(markdown-mode . "2.5"))
3870 (defcustom markdown-disable-tooltip-prompt nil
3871 "Disable prompt for tooltip when inserting a link or image.
3873 If non-nil, `markdown-insert-link' and `markdown-insert-link'
3874 will not prompt the user to insert a tooltip text for the given
3875 link or image."
3876 :group 'markdown
3877 :type 'boolean
3878 :safe 'booleanp
3879 :package-version '(markdown-mode . "2.5"))
3881 (defun markdown--insert-link-or-image (image)
3882 "Interactively insert new or update an existing link or image.
3883 When IMAGE is non-nil, insert an image. Otherwise, insert a link.
3884 This is an internal function called by
3885 `markdown-insert-link' and `markdown-insert-image'."
3886 (cl-multiple-value-bind (begin end text uri ref title)
3887 (if (use-region-p)
3888 ;; Use region as either link text or URL as appropriate.
3889 (let ((region (buffer-substring-no-properties
3890 (region-beginning) (region-end))))
3891 (if (string-match markdown-regex-uri region)
3892 ;; Region contains a URL; use it as such.
3893 (list (region-beginning) (region-end)
3894 nil (match-string 0 region) nil nil)
3895 ;; Region doesn't contain a URL, so use it as text.
3896 (list (region-beginning) (region-end)
3897 region nil nil nil)))
3898 ;; Extract and use properties of existing link, if any.
3899 (markdown-link-at-pos (point)))
3900 (let* ((ref (when ref (concat "[" ref "]")))
3901 (defined-refs (mapcar #'car (markdown-get-defined-references)))
3902 (defined-ref-cands (mapcar (lambda (ref) (concat "[" ref "]")) defined-refs))
3903 (used-uris (markdown-get-used-uris))
3904 (uri-or-ref (completing-read
3905 "URL or [reference]: "
3906 (append defined-ref-cands used-uris)
3907 nil nil (or uri ref)))
3908 (ref (cond ((string-match "\\`\\[\\(.*\\)\\]\\'" uri-or-ref)
3909 (match-string 1 uri-or-ref))
3910 ((string-equal "" uri-or-ref)
3911 "")))
3912 (uri (unless ref uri-or-ref))
3913 (text-prompt (if image
3914 "Alt text: "
3915 (if ref
3916 "Link text: "
3917 "Link text (blank for plain URL): ")))
3918 (text (or text (and markdown-link-make-text-function uri
3919 (funcall markdown-link-make-text-function uri))))
3920 (text (completing-read text-prompt defined-refs nil nil text))
3921 (text (if (= (length text) 0) nil text))
3922 (plainp (and uri (not text)))
3923 (implicitp (string-equal ref ""))
3924 (ref (if implicitp text ref))
3925 (definedp (and ref (markdown-reference-definition ref)))
3926 (ref-url (unless (or uri definedp)
3927 (completing-read "Reference URL: " used-uris)))
3928 (title (unless (or plainp definedp markdown-disable-tooltip-prompt)
3929 (read-string "Title (tooltip text, optional): " title)))
3930 (title (if (= (length title) 0) nil title)))
3931 (when (and image implicitp)
3932 (user-error "Reference required: implicit image references are invalid"))
3933 (when (and begin end)
3934 (delete-region begin end))
3935 (cond
3936 ((and (not image) uri text)
3937 (markdown-insert-inline-link text uri title))
3938 ((and image uri text)
3939 (markdown-insert-inline-image text uri title))
3940 ((and ref text)
3941 (if image
3942 (markdown-insert-reference-image text (unless implicitp ref) nil title)
3943 (markdown-insert-reference-link text (unless implicitp ref) nil title))
3944 (unless definedp
3945 (markdown-insert-reference-definition ref ref-url title)))
3946 ((and (not image) uri)
3947 (markdown-insert-uri uri))))))
3949 (defun markdown-insert-link ()
3950 "Insert new or update an existing link, with interactive prompt.
3951 If the point is at an existing link or URL, update the link text,
3952 URL, reference label, and/or title. Otherwise, insert a new link.
3953 The type of link inserted (inline, reference, or plain URL)
3954 depends on which values are provided:
3956 * If a URL and TEXT are given, insert an inline link: [TEXT](URL).
3957 * If [REF] and TEXT are given, insert a reference link: [TEXT][REF].
3958 * If only TEXT is given, insert an implicit reference link: [TEXT][].
3959 * If only a URL is given, insert a plain link: <URL>.
3961 In other words, to create an implicit reference link, leave the
3962 URL prompt empty and to create a plain URL link, leave the link
3963 text empty.
3965 If there is an active region, use the text as the default URL, if
3966 it seems to be a URL, or link text value otherwise.
3968 If a given reference is not defined, this function will
3969 additionally prompt for the URL and optional title. In this case,
3970 the reference definition is placed at the location determined by
3971 `markdown-reference-location'. In addition, it is possible to
3972 have the `markdown-link-make-text-function' function, if non-nil,
3973 define the default link text before prompting the user for it.
3975 If `markdown-disable-tooltip-prompt' is non-nil, the user will
3976 not be prompted to add or modify a tooltip text.
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 prompt.
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 (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 (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 (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 (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 (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" "4D" "ABAP" "ABNF" "AGS-Script" "AMPL" "ANTLR"
4307 "API-Blueprint" "APL" "ASN.1" "ASP" "ATS" "ActionScript" "Ada"
4308 "Adobe-Font-Metrics" "Agda" "Alloy" "Alpine-Abuild" "Altium-Designer"
4309 "AngelScript" "Ant-Build-System" "ApacheConf" "Apex"
4310 "Apollo-Guidance-Computer" "AppleScript" "Arc" "AsciiDoc" "AspectJ" "Assembly"
4311 "Asymptote" "Augeas" "AutoHotkey" "AutoIt" "Awk" "Ballerina" "Batchfile"
4312 "Befunge" "BibTeX" "Bison" "BitBake" "Blade" "BlitzBasic" "BlitzMax"
4313 "Bluespec" "Boo" "Brainfuck" "Brightscript" "C#" "C++" "C-ObjDump"
4314 "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "COLLADA" "CSON" "CSS" "CSV" "CWeb"
4315 "Cabal-Config" "Cap'n-Proto" "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK"
4316 "Cirru" "Clarion" "Clean" "Click" "Clojure" "Closure-Templates"
4317 "Cloud-Firestore-Security-Rules" "CoNLL-U" "CodeQL" "CoffeeScript"
4318 "ColdFusion" "ColdFusion-CFC" "Common-Lisp" "Common-Workflow-Language"
4319 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal" "Csound"
4320 "Csound-Document" "Csound-Score" "Cuda" "Cycript" "Cython" "D-ObjDump"
4321 "DIGITAL-Command-Language" "DM" "DNS-Zone" "DTrace" "Dafny" "Darcs-Patch"
4322 "Dart" "DataWeave" "Dhall" "Diff" "DirectX-3D-File" "Dockerfile" "Dogescript"
4323 "Dylan" "EBNF" "ECL" "ECLiPSe" "EJS" "EML" "EQ" "Eagle" "Easybuild"
4324 "Ecere-Projects" "EditorConfig" "Edje-Data-Collection" "Eiffel" "Elixir" "Elm"
4325 "Emacs-Lisp" "EmberScript" "Erlang" "F#" "F*" "FIGlet-Font" "FLUX" "Factor"
4326 "Fancy" "Fantom" "Faust" "Filebench-WML" "Filterscript" "Formatted" "Forth"
4327 "Fortran" "Fortran-Free-Form" "FreeMarker" "Frege" "G-code" "GAML" "GAMS"
4328 "GAP" "GCC-Machine-Description" "GDB" "GDScript" "GEDCOM" "GLSL" "GN"
4329 "Game-Maker-Language" "Genie" "Genshi" "Gentoo-Ebuild" "Gentoo-Eclass"
4330 "Gerber-Image" "Gettext-Catalog" "Gherkin" "Git-Attributes" "Git-Config"
4331 "Glyph" "Glyph-Bitmap-Distribution-Format" "Gnuplot" "Go" "Golo" "Gosu"
4332 "Grace" "Gradle" "Grammatical-Framework" "Graph-Modeling-Language" "GraphQL"
4333 "Graphviz-(DOT)" "Groovy" "Groovy-Server-Pages" "HAProxy" "HCL" "HLSL" "HTML"
4334 "HTML+Django" "HTML+ECR" "HTML+EEX" "HTML+ERB" "HTML+PHP" "HTML+Razor" "HTTP"
4335 "HXML" "Hack" "Haml" "Handlebars" "Harbour" "Haskell" "Haxe" "HiveQL" "HolyC"
4336 "Hy" "HyPhy" "IDL" "IGOR-Pro" "INI" "IRC-log" "Idris" "Ignore-List" "Inform-7"
4337 "Inno-Setup" "Io" "Ioke" "Isabelle" "Isabelle-ROOT" "JFlex" "JSON"
4338 "JSON-with-Comments" "JSON5" "JSONLD" "JSONiq" "JSX" "Jasmin" "Java"
4339 "Java-Properties" "Java-Server-Pages" "JavaScript" "JavaScript+ERB" "Jison"
4340 "Jison-Lex" "Jolie" "Jsonnet" "Julia" "Jupyter-Notebook" "KRL" "KiCad-Layout"
4341 "KiCad-Legacy-Layout" "KiCad-Schematic" "Kit" "Kotlin" "LFE" "LLVM" "LOLCODE"
4342 "LSL" "LTspice-Symbol" "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex"
4343 "LilyPond" "Limbo" "Linker-Script" "Linux-Kernel-Module" "Liquid"
4344 "Literate-Agda" "Literate-CoffeeScript" "Literate-Haskell" "LiveScript"
4345 "Logos" "Logtalk" "LookML" "LoomScript" "Lua" "M4" "M4Sugar" "MATLAB"
4346 "MAXScript" "MLIR" "MQL4" "MQL5" "MTML" "MUF" "Macaulay2" "Makefile" "Mako"
4347 "Markdown" "Marko" "Mask" "Mathematica" "Maven-POM" "Max" "MediaWiki"
4348 "Mercury" "Meson" "Metal" "Microsoft-Developer-Studio-Project" "MiniD" "Mirah"
4349 "Modelica" "Modula-2" "Modula-3" "Module-Management-System" "Monkey" "Moocode"
4350 "MoonScript" "Motorola-68K-Assembly" "Muse" "Myghty" "NASL" "NCL" "NEON" "NL"
4351 "NPM-Config" "NSIS" "Nearley" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo"
4352 "NewLisp" "Nextflow" "Nginx" "Nim" "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml"
4353 "ObjDump" "Object-Data-Instance-Notation" "ObjectScript" "Objective-C"
4354 "Objective-C++" "Objective-J" "Odin" "Omgrofl" "Opa" "Opal"
4355 "Open-Policy-Agent" "OpenCL" "OpenEdge-ABL" "OpenQASM" "OpenRC-runscript"
4356 "OpenSCAD" "OpenStep-Property-List" "OpenType-Feature-File" "Org" "Ox"
4357 "Oxygene" "Oz" "P4" "PHP" "PLSQL" "PLpgSQL" "POV-Ray-SDL" "Pan" "Papyrus"
4358 "Parrot" "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal" "Pawn"
4359 "Pep8" "Perl" "Pic" "Pickle" "PicoLisp" "PigLatin" "Pike" "PlantUML" "Pod"
4360 "Pod-6" "PogoScript" "Pony" "PostCSS" "PostScript" "PowerBuilder" "PowerShell"
4361 "Prisma" "Processing" "Proguard" "Prolog" "Propeller-Spin" "Protocol-Buffer"
4362 "Public-Key" "Pug" "Puppet" "Pure-Data" "PureBasic" "PureScript" "Python"
4363 "Python-console" "Python-traceback" "QML" "QMake" "Quake" "RAML" "RDoc"
4364 "REALbasic" "REXX" "RHTML" "RMarkdown" "RPC" "RPM-Spec" "RUNOFF" "Racket"
4365 "Ragel" "Raku" "Rascal" "Raw-token-data" "Readline-Config" "Reason" "Rebol"
4366 "Red" "Redcode" "Regular-Expression" "Ren'Py" "RenderScript"
4367 "Rich-Text-Format" "Ring" "Riot" "RobotFramework" "Roff" "Roff-Manpage"
4368 "Rouge" "Ruby" "Rust" "SAS" "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL"
4369 "SRecode-Template" "SSH-Config" "STON" "SVG" "SWIG" "Sage" "SaltStack" "Sass"
4370 "Scala" "Scaml" "Scheme" "Scilab" "Self" "ShaderLab" "Shell" "ShellSession"
4371 "Shen" "Slash" "Slice" "Slim" "SmPL" "Smali" "Smalltalk" "Smarty" "Solidity"
4372 "SourcePawn" "Spline-Font-Database" "Squirrel" "Stan" "Standard-ML" "Starlark"
4373 "Stata" "Stylus" "SubRip-Text" "SugarSS" "SuperCollider" "Svelte" "Swift"
4374 "SystemVerilog" "TI-Program" "TLA" "TOML" "TSQL" "TSX" "TXL" "Tcl" "Tcsh"
4375 "TeX" "Tea" "Terra" "Texinfo" "Text" "Textile" "Thrift" "Turing" "Turtle"
4376 "Twig" "Type-Language" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset"
4377 "Unix-Assembly" "Uno" "UnrealScript" "UrWeb" "VBA" "VBScript" "VCL" "VHDL"
4378 "Vala" "Verilog" "Vim-Snippet" "Vim-script" "Visual-Basic-.NET" "Volt" "Vue"
4379 "Wavefront-Material" "Wavefront-Object" "Web-Ontology-Language" "WebAssembly"
4380 "WebIDL" "WebVTT" "Wget-Config" "Windows-Registry-Entries" "Wollok"
4381 "World-of-Warcraft-Addon-Data" "X-BitMap" "X-Font-Directory-Index" "X-PixMap"
4382 "X10" "XC" "XCompose" "XML" "XML-Property-List" "XPages" "XProc" "XQuery" "XS"
4383 "XSLT" "Xojo" "Xtend" "YAML" "YANG" "YARA" "YASnippet" "Yacc" "ZAP" "ZIL"
4384 "Zeek" "ZenScript" "Zephir" "Zig" "Zimpl" "cURL-Config" "desktop" "dircolors"
4385 "eC" "edn" "fish" "mIRC-Script" "mcfunction" "mupad" "nanorc" "nesC" "ooc"
4386 "reStructuredText" "sed" "wdl" "wisp" "xBase")
4387 "Language specifiers recognized by GitHub's syntax highlighting features.")
4389 (defvar-local markdown-gfm-used-languages nil
4390 "Language names used in GFM code blocks.")
4392 (defun markdown-trim-whitespace (str)
4393 (replace-regexp-in-string
4394 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str))
4396 (defun markdown-clean-language-string (str)
4397 (replace-regexp-in-string
4398 "{\\.?\\|}" "" (markdown-trim-whitespace str)))
4400 (defun markdown-validate-language-string (widget)
4401 (let ((str (widget-value widget)))
4402 (unless (string= str (markdown-clean-language-string str))
4403 (widget-put widget :error (format "Invalid language spec: '%s'" str))
4404 widget)))
4406 (defun markdown-gfm-get-corpus ()
4407 "Create corpus of recognized GFM code block languages for the given buffer."
4408 (let ((given-corpus (append markdown-gfm-additional-languages
4409 markdown-gfm-recognized-languages)))
4410 (append
4411 markdown-gfm-used-languages
4412 (if markdown-gfm-downcase-languages (cl-mapcar #'downcase given-corpus)
4413 given-corpus))))
4415 (defun markdown-gfm-add-used-language (lang)
4416 "Clean LANG and add to list of used languages."
4417 (setq markdown-gfm-used-languages
4418 (cons lang (remove lang markdown-gfm-used-languages))))
4420 (defcustom markdown-spaces-after-code-fence 1
4421 "Number of space characters to insert after a code fence.
4422 \\<gfm-mode-map>\\[markdown-insert-gfm-code-block] inserts this many spaces between an
4423 opening code fence and an info string."
4424 :group 'markdown
4425 :type 'integer
4426 :safe #'natnump
4427 :package-version '(markdown-mode . "2.3"))
4429 (defcustom markdown-code-block-braces nil
4430 "When non-nil, automatically insert braces for GFM code blocks."
4431 :group 'markdown
4432 :type 'boolean)
4434 (defun markdown-insert-gfm-code-block (&optional lang edit)
4435 "Insert GFM code block for language LANG.
4436 If LANG is nil, the language will be queried from user. If a
4437 region is active, wrap this region with the markup instead. If
4438 the region boundaries are not on empty lines, these are added
4439 automatically in order to have the correct markup. When EDIT is
4440 non-nil (e.g., when \\[universal-argument] is given), edit the
4441 code block in an indirect buffer after insertion."
4442 (interactive
4443 (list (let ((completion-ignore-case nil))
4444 (condition-case nil
4445 (markdown-clean-language-string
4446 (completing-read
4447 "Programming language: "
4448 (markdown-gfm-get-corpus)
4449 nil 'confirm (car markdown-gfm-used-languages)
4450 'markdown-gfm-language-history))
4451 (quit "")))
4452 current-prefix-arg))
4453 (unless (string= lang "") (markdown-gfm-add-used-language lang))
4454 (when (and (> (length lang) 0)
4455 (not markdown-code-block-braces))
4456 (setq lang (concat (make-string markdown-spaces-after-code-fence ?\s)
4457 lang)))
4458 (let ((gfm-open-brace (if markdown-code-block-braces "{" ""))
4459 (gfm-close-brace (if markdown-code-block-braces "}" "")))
4460 (if (use-region-p)
4461 (let* ((b (region-beginning)) (e (region-end)) end
4462 (indent (progn (goto-char b) (current-indentation))))
4463 (goto-char e)
4464 ;; if we're on a blank line, don't newline, otherwise the ```
4465 ;; should go on its own line
4466 (unless (looking-back "\n" nil)
4467 (newline))
4468 (indent-to indent)
4469 (insert "```")
4470 (markdown-ensure-blank-line-after)
4471 (setq end (point))
4472 (goto-char b)
4473 ;; if we're on a blank line, insert the quotes here, otherwise
4474 ;; add a new line first
4475 (unless (looking-at-p "\n")
4476 (newline)
4477 (forward-line -1))
4478 (markdown-ensure-blank-line-before)
4479 (indent-to indent)
4480 (insert "```" gfm-open-brace lang gfm-close-brace)
4481 (markdown-syntax-propertize-fenced-block-constructs (point-at-bol) end))
4482 (let ((indent (current-indentation))
4483 start-bol)
4484 (delete-horizontal-space :backward-only)
4485 (markdown-ensure-blank-line-before)
4486 (indent-to indent)
4487 (setq start-bol (point-at-bol))
4488 (insert "```" gfm-open-brace lang gfm-close-brace "\n")
4489 (indent-to indent)
4490 (unless edit (insert ?\n))
4491 (indent-to indent)
4492 (insert "```")
4493 (markdown-ensure-blank-line-after)
4494 (markdown-syntax-propertize-fenced-block-constructs start-bol (point)))
4495 (end-of-line 0)
4496 (when edit (markdown-edit-code-block)))))
4498 (defun markdown-code-block-lang (&optional pos-prop)
4499 "Return the language name for a GFM or tilde fenced code block.
4500 The beginning of the block may be described by POS-PROP,
4501 a cons of (pos . prop) giving the position and property
4502 at the beginning of the block."
4503 (or pos-prop
4504 (setq pos-prop
4505 (markdown-max-of-seq
4506 #'car
4507 (cl-remove-if
4508 #'null
4509 (cl-mapcar
4510 #'markdown-find-previous-prop
4511 (markdown-get-fenced-block-begin-properties))))))
4512 (when pos-prop
4513 (goto-char (car pos-prop))
4514 (set-match-data (get-text-property (point) (cdr pos-prop)))
4515 ;; Note: Hard-coded group number assumes tilde
4516 ;; and GFM fenced code regexp groups agree.
4517 (let ((begin (match-beginning 3))
4518 (end (match-end 3)))
4519 (when (and begin end)
4520 ;; Fix language strings beginning with periods, like ".ruby".
4521 (when (eq (char-after begin) ?.)
4522 (setq begin (1+ begin)))
4523 (buffer-substring-no-properties begin end)))))
4525 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer)
4526 (with-current-buffer (or buffer (current-buffer))
4527 (save-excursion
4528 (goto-char (point-min))
4529 (cl-loop
4530 with prop = 'markdown-gfm-block-begin
4531 for pos-prop = (markdown-find-next-prop prop)
4532 while pos-prop
4533 for lang = (markdown-code-block-lang pos-prop)
4534 do (progn (when lang (markdown-gfm-add-used-language lang))
4535 (goto-char (next-single-property-change (point) prop)))))))
4537 (defun markdown-insert-foldable-block ()
4538 "Insert details disclosure element to make content foldable.
4539 If a region is active, wrap this region with the disclosure
4540 element. More detais here 'https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details'."
4541 (interactive)
4542 (let ((details-open-tag "<details>")
4543 (details-close-tag "</details>")
4544 (summary-open-tag "<summary>")
4545 (summary-close-tag " </summary>"))
4546 (if (use-region-p)
4547 (let* ((b (region-beginning))
4548 (e (region-end))
4549 (indent (progn (goto-char b) (current-indentation))))
4550 (goto-char e)
4551 ;; if we're on a blank line, don't newline, otherwise the tags
4552 ;; should go on its own line
4553 (unless (looking-back "\n" nil)
4554 (newline))
4555 (indent-to indent)
4556 (insert details-close-tag)
4557 (markdown-ensure-blank-line-after)
4558 (goto-char b)
4559 ;; if we're on a blank line, insert the quotes here, otherwise
4560 ;; add a new line first
4561 (unless (looking-at-p "\n")
4562 (newline)
4563 (forward-line -1))
4564 (markdown-ensure-blank-line-before)
4565 (indent-to indent)
4566 (insert details-open-tag "\n")
4567 (insert summary-open-tag summary-close-tag)
4568 (search-backward summary-close-tag))
4569 (let ((indent (current-indentation)))
4570 (delete-horizontal-space :backward-only)
4571 (markdown-ensure-blank-line-before)
4572 (indent-to indent)
4573 (insert details-open-tag "\n")
4574 (insert summary-open-tag summary-close-tag "\n")
4575 (insert details-close-tag)
4576 (indent-to indent)
4577 (markdown-ensure-blank-line-after)
4578 (search-backward summary-close-tag)))))
4581 ;;; Footnotes =================================================================
4583 (defun markdown-footnote-counter-inc ()
4584 "Increment `markdown-footnote-counter' and return the new value."
4585 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
4586 (save-excursion
4587 (goto-char (point-min))
4588 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
4589 (point-max) t)
4590 (let ((fn (string-to-number (match-string 1))))
4591 (when (> fn markdown-footnote-counter)
4592 (setq markdown-footnote-counter fn))))))
4593 (cl-incf markdown-footnote-counter))
4595 (defun markdown-insert-footnote ()
4596 "Insert footnote with a new number and move point to footnote definition."
4597 (interactive)
4598 (let ((fn (markdown-footnote-counter-inc)))
4599 (insert (format "[^%d]" fn))
4600 (markdown-footnote-text-find-new-location)
4601 (markdown-ensure-blank-line-before)
4602 (unless (markdown-cur-line-blank-p)
4603 (insert "\n"))
4604 (insert (format "[^%d]: " fn))
4605 (markdown-ensure-blank-line-after)))
4607 (defun markdown-footnote-text-find-new-location ()
4608 "Position the point at the proper location for a new footnote text."
4609 (cond
4610 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
4611 ((eq markdown-footnote-location 'immediately) (markdown-end-of-text-block))
4612 ((eq markdown-footnote-location 'subtree) (markdown-end-of-subtree))
4613 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
4615 (defun markdown-footnote-kill ()
4616 "Kill the footnote at point.
4617 The footnote text is killed (and added to the kill ring), the
4618 footnote marker is deleted. Point has to be either at the
4619 footnote marker or in the footnote text."
4620 (interactive)
4621 (let ((marker-pos nil)
4622 (skip-deleting-marker nil)
4623 (starting-footnote-text-positions
4624 (markdown-footnote-text-positions)))
4625 (when starting-footnote-text-positions
4626 ;; We're starting in footnote text, so mark our return position and jump
4627 ;; to the marker if possible.
4628 (let ((marker-pos (markdown-footnote-find-marker
4629 (cl-first starting-footnote-text-positions))))
4630 (if marker-pos
4631 (goto-char (1- marker-pos))
4632 ;; If there isn't a marker, we still want to kill the text.
4633 (setq skip-deleting-marker t))))
4634 ;; Either we didn't start in the text, or we started in the text and jumped
4635 ;; to the marker. We want to assume we're at the marker now and error if
4636 ;; we're not.
4637 (unless skip-deleting-marker
4638 (let ((marker (markdown-footnote-delete-marker)))
4639 (unless marker
4640 (error "Not at a footnote"))
4641 ;; Even if we knew the text position before, it changed when we deleted
4642 ;; the label.
4643 (setq marker-pos (cl-second marker))
4644 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker))))
4645 (unless new-text-pos
4646 (error "No text for footnote `%s'" (cl-first marker)))
4647 (goto-char new-text-pos))))
4648 (let ((pos (markdown-footnote-kill-text)))
4649 (goto-char (if starting-footnote-text-positions
4651 marker-pos)))))
4653 (defun markdown-footnote-delete-marker ()
4654 "Delete a footnote marker at point.
4655 Returns a list (ID START) containing the footnote ID and the
4656 start position of the marker before deletion. If no footnote
4657 marker was deleted, this function returns NIL."
4658 (let ((marker (markdown-footnote-marker-positions)))
4659 (when marker
4660 (delete-region (cl-second marker) (cl-third marker))
4661 (butlast marker))))
4663 (defun markdown-footnote-kill-text ()
4664 "Kill footnote text at point.
4665 Returns the start position of the footnote text before deletion,
4666 or NIL if point was not inside a footnote text.
4668 The killed text is placed in the kill ring (without the footnote
4669 number)."
4670 (let ((fn (markdown-footnote-text-positions)))
4671 (when fn
4672 (let ((text (delete-and-extract-region (cl-second fn) (cl-third fn))))
4673 (string-match (concat "\\[\\" (cl-first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
4674 (kill-new (match-string 1 text))
4675 (when (and (markdown-cur-line-blank-p)
4676 (markdown-prev-line-blank-p)
4677 (not (bobp)))
4678 (delete-region (1- (point)) (point)))
4679 (cl-second fn)))))
4681 (defun markdown-footnote-goto-text ()
4682 "Jump to the text of the footnote at point."
4683 (interactive)
4684 (let ((fn (car (markdown-footnote-marker-positions))))
4685 (unless fn
4686 (user-error "Not at a footnote marker"))
4687 (let ((new-pos (markdown-footnote-find-text fn)))
4688 (unless new-pos
4689 (error "No definition found for footnote `%s'" fn))
4690 (goto-char new-pos))))
4692 (defun markdown-footnote-return ()
4693 "Return from a footnote to its footnote number in the main text."
4694 (interactive)
4695 (let ((fn (save-excursion
4696 (car (markdown-footnote-text-positions)))))
4697 (unless fn
4698 (user-error "Not in a footnote"))
4699 (let ((new-pos (markdown-footnote-find-marker fn)))
4700 (unless new-pos
4701 (error "Footnote marker `%s' not found" fn))
4702 (goto-char new-pos))))
4704 (defun markdown-footnote-find-marker (id)
4705 "Find the location of the footnote marker with ID.
4706 The actual buffer position returned is the position directly
4707 following the marker's closing bracket. If no marker is found,
4708 NIL is returned."
4709 (save-excursion
4710 (goto-char (point-min))
4711 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
4712 (skip-chars-backward "^]")
4713 (point))))
4715 (defun markdown-footnote-find-text (id)
4716 "Find the location of the text of footnote ID.
4717 The actual buffer position returned is the position of the first
4718 character of the text, after the footnote's identifier. If no
4719 footnote text is found, NIL is returned."
4720 (save-excursion
4721 (goto-char (point-min))
4722 (when (re-search-forward (concat "^ \\{0,3\\}\\[" id "\\]:") nil t)
4723 (skip-chars-forward "[ \t]")
4724 (point))))
4726 (defun markdown-footnote-marker-positions ()
4727 "Return the position and ID of the footnote marker point is on.
4728 The return value is a list (ID START END). If point is not on a
4729 footnote, NIL is returned."
4730 ;; first make sure we're at a footnote marker
4731 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
4732 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
4733 (save-excursion
4734 ;; move point between [ and ^:
4735 (if (looking-at-p "\\[")
4736 (forward-char 1)
4737 (skip-chars-backward "^["))
4738 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
4739 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
4741 (defun markdown-footnote-text-positions ()
4742 "Return the start and end positions of the footnote text point is in.
4743 The exact return value is a list of three elements: (ID START END).
4744 The start position is the position of the opening bracket
4745 of the footnote id. The end position is directly after the
4746 newline that ends the footnote. If point is not in a footnote,
4747 NIL is returned instead."
4748 (save-excursion
4749 (let (result)
4750 (move-beginning-of-line 1)
4751 ;; Try to find the label. If we haven't found the label and we're at a blank
4752 ;; or indented line, back up if possible.
4753 (while (and
4754 (not (and (looking-at markdown-regex-footnote-definition)
4755 (setq result (list (match-string 1) (point)))))
4756 (and (not (bobp))
4757 (or (markdown-cur-line-blank-p)
4758 (>= (current-indentation) 4))))
4759 (forward-line -1))
4760 (when result
4761 ;; Advance if there is a next line that is either blank or indented.
4762 ;; (Need to check if we're on the last line, because
4763 ;; markdown-next-line-blank-p returns true for last line in buffer.)
4764 (while (and (/= (line-end-position) (point-max))
4765 (or (markdown-next-line-blank-p)
4766 (>= (markdown-next-line-indent) 4)))
4767 (forward-line))
4768 ;; Move back while the current line is blank.
4769 (while (markdown-cur-line-blank-p)
4770 (forward-line -1))
4771 ;; Advance to capture this line and a single trailing newline (if there
4772 ;; is one).
4773 (forward-line)
4774 (append result (list (point)))))))
4776 (defun markdown-get-defined-footnotes ()
4777 "Return a list of all defined footnotes.
4778 Result is an alist of pairs (MARKER . LINE), where MARKER is the
4779 footnote marker, a string, and LINE is the line number containing
4780 the footnote definition.
4782 For example, suppose the following footnotes are defined at positions
4783 448 and 475:
4785 \[^1]: First footnote here.
4786 \[^marker]: Second footnote.
4788 Then the returned list is: ((\"^1\" . 478) (\"^marker\" . 475))"
4789 (save-excursion
4790 (goto-char (point-min))
4791 (let (footnotes)
4792 (while (markdown-search-until-condition
4793 (lambda () (and (not (markdown-code-block-at-point-p))
4794 (not (markdown-inline-code-at-point-p))
4795 (not (markdown-in-comment-p))))
4796 markdown-regex-footnote-definition nil t)
4797 (let ((marker (match-string-no-properties 1))
4798 (pos (match-beginning 0)))
4799 (unless (zerop (length marker))
4800 (cl-pushnew (cons marker pos) footnotes :test #'equal))))
4801 (reverse footnotes))))
4804 ;;; Element Removal ===========================================================
4806 (defun markdown-kill-thing-at-point ()
4807 "Kill thing at point and add important text, without markup, to kill ring.
4808 Possible things to kill include (roughly in order of precedence):
4809 inline code, headers, horizontal rules, links (add link text to
4810 kill ring), images (add alt text to kill ring), angle uri, email
4811 addresses, bold, italics, reference definition (add URI to kill
4812 ring), footnote markers and text (kill both marker and text, add
4813 text to kill ring), and list items."
4814 (interactive "*")
4815 (let (val)
4816 (cond
4817 ;; Inline code
4818 ((markdown-inline-code-at-point)
4819 (kill-new (match-string 2))
4820 (delete-region (match-beginning 0) (match-end 0)))
4821 ;; ATX header
4822 ((thing-at-point-looking-at markdown-regex-header-atx)
4823 (kill-new (match-string 2))
4824 (delete-region (match-beginning 0) (match-end 0)))
4825 ;; Setext header
4826 ((thing-at-point-looking-at markdown-regex-header-setext)
4827 (kill-new (match-string 1))
4828 (delete-region (match-beginning 0) (match-end 0)))
4829 ;; Horizontal rule
4830 ((thing-at-point-looking-at markdown-regex-hr)
4831 (kill-new (match-string 0))
4832 (delete-region (match-beginning 0) (match-end 0)))
4833 ;; Inline link or image (add link or alt text to kill ring)
4834 ((thing-at-point-looking-at markdown-regex-link-inline)
4835 (kill-new (match-string 3))
4836 (delete-region (match-beginning 0) (match-end 0)))
4837 ;; Reference link or image (add link or alt text to kill ring)
4838 ((thing-at-point-looking-at markdown-regex-link-reference)
4839 (kill-new (match-string 3))
4840 (delete-region (match-beginning 0) (match-end 0)))
4841 ;; Angle URI (add URL to kill ring)
4842 ((thing-at-point-looking-at markdown-regex-angle-uri)
4843 (kill-new (match-string 2))
4844 (delete-region (match-beginning 0) (match-end 0)))
4845 ;; Email address in angle brackets (add email address to kill ring)
4846 ((thing-at-point-looking-at markdown-regex-email)
4847 (kill-new (match-string 1))
4848 (delete-region (match-beginning 0) (match-end 0)))
4849 ;; Wiki link (add alias text to kill ring)
4850 ((and markdown-enable-wiki-links
4851 (thing-at-point-looking-at markdown-regex-wiki-link))
4852 (kill-new (markdown-wiki-link-alias))
4853 (delete-region (match-beginning 1) (match-end 1)))
4854 ;; Bold
4855 ((thing-at-point-looking-at markdown-regex-bold)
4856 (kill-new (match-string 4))
4857 (delete-region (match-beginning 2) (match-end 2)))
4858 ;; Italics
4859 ((thing-at-point-looking-at markdown-regex-italic)
4860 (kill-new (match-string 3))
4861 (delete-region (match-beginning 1) (match-end 1)))
4862 ;; Strikethrough
4863 ((thing-at-point-looking-at markdown-regex-strike-through)
4864 (kill-new (match-string 4))
4865 (delete-region (match-beginning 2) (match-end 2)))
4866 ;; Footnote marker (add footnote text to kill ring)
4867 ((thing-at-point-looking-at markdown-regex-footnote)
4868 (markdown-footnote-kill))
4869 ;; Footnote text (add footnote text to kill ring)
4870 ((setq val (markdown-footnote-text-positions))
4871 (markdown-footnote-kill))
4872 ;; Reference definition (add URL to kill ring)
4873 ((thing-at-point-looking-at markdown-regex-reference-definition)
4874 (kill-new (match-string 5))
4875 (delete-region (match-beginning 0) (match-end 0)))
4876 ;; List item
4877 ((setq val (markdown-cur-list-item-bounds))
4878 (kill-new (delete-and-extract-region (cl-first val) (cl-second val))))
4880 (user-error "Nothing found at point to kill")))))
4882 (defun markdown-kill-outline ()
4883 "Kill visible heading and add it to `kill-ring'."
4884 (interactive)
4885 (save-excursion
4886 (markdown-outline-previous)
4887 (kill-region (point) (progn (markdown-outline-next) (point)))))
4889 (defun markdown-kill-block ()
4890 "Kill visible code block, list item, or blockquote and add it to `kill-ring'."
4891 (interactive)
4892 (save-excursion
4893 (markdown-backward-block)
4894 (kill-region (point) (progn (markdown-forward-block) (point)))))
4897 ;;; Indentation ===============================================================
4899 (defun markdown-indent-find-next-position (cur-pos positions)
4900 "Return the position after the index of CUR-POS in POSITIONS.
4901 Positions are calculated by `markdown-calc-indents'."
4902 (while (and positions
4903 (not (equal cur-pos (car positions))))
4904 (setq positions (cdr positions)))
4905 (or (cadr positions) 0))
4907 (defun markdown-outdent-find-next-position (cur-pos positions)
4908 "Return the maximal element that precedes CUR-POS from POSITIONS.
4909 Positions are calculated by `markdown-calc-indents'."
4910 (let ((result 0))
4911 (dolist (i positions)
4912 (when (< i cur-pos)
4913 (setq result (max result i))))
4914 result))
4916 (defun markdown-indent-line ()
4917 "Indent the current line using some heuristics.
4918 If the _previous_ command was either `markdown-enter-key' or
4919 `markdown-cycle', then we should cycle to the next
4920 reasonable indentation position. Otherwise, we could have been
4921 called directly by `markdown-enter-key', by an initial call of
4922 `markdown-cycle', or indirectly by `auto-fill-mode'. In
4923 these cases, indent to the default position.
4924 Positions are calculated by `markdown-calc-indents'."
4925 (interactive)
4926 (let ((positions (markdown-calc-indents))
4927 (point-pos (current-column))
4928 (_ (back-to-indentation))
4929 (cur-pos (current-column)))
4930 (if (not (equal this-command 'markdown-cycle))
4931 (indent-line-to (car positions))
4932 (setq positions (sort (delete-dups positions) '<))
4933 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions))
4934 (new-point-pos (max (+ point-pos (- next-pos cur-pos)) 0)))
4935 (indent-line-to next-pos)
4936 (move-to-column new-point-pos)))))
4938 (defun markdown-calc-indents ()
4939 "Return a list of indentation columns to cycle through.
4940 The first element in the returned list should be considered the
4941 default indentation level. This function does not worry about
4942 duplicate positions, which are handled up by calling functions."
4943 (let (pos prev-line-pos positions)
4945 ;; Indentation of previous line
4946 (setq prev-line-pos (markdown-prev-line-indent))
4947 (setq positions (cons prev-line-pos positions))
4949 ;; Indentation of previous non-list-marker text
4950 (when (setq pos (save-excursion
4951 (forward-line -1)
4952 (when (looking-at markdown-regex-list)
4953 (- (match-end 3) (match-beginning 0)))))
4954 (setq positions (cons pos positions)))
4956 ;; Indentation required for a pre block in current context
4957 (setq pos (length (markdown-pre-indentation (point))))
4958 (setq positions (cons pos positions))
4960 ;; Indentation of the previous line + tab-width
4961 (if prev-line-pos
4962 (setq positions (cons (+ prev-line-pos tab-width) positions))
4963 (setq positions (cons tab-width positions)))
4965 ;; Indentation of the previous line - tab-width
4966 (if (and prev-line-pos (> prev-line-pos tab-width))
4967 (setq positions (cons (- prev-line-pos tab-width) positions)))
4969 ;; Indentation of all preceding list markers (when in a list)
4970 (when (setq pos (markdown-calculate-list-levels))
4971 (setq positions (append pos positions)))
4973 ;; First column
4974 (setq positions (cons 0 positions))
4976 ;; Return reversed list
4977 (reverse positions)))
4979 (defun markdown-enter-key () ;FIXME: Partly obsoleted by electric-indent
4980 "Handle RET depending on the context.
4981 If the point is at a table, move to the next row. Otherwise,
4982 indent according to value of `markdown-indent-on-enter'.
4983 When it is nil, simply call `newline'. Otherwise, indent the next line
4984 following RET using `markdown-indent-line'. Furthermore, when it
4985 is set to 'indent-and-new-item and the point is in a list item,
4986 start a new item with the same indentation. If the point is in an
4987 empty list item, remove it (so that pressing RET twice when in a
4988 list simply adds a blank line)."
4989 (interactive)
4990 (cond
4991 ;; Table
4992 ((markdown-table-at-point-p)
4993 (call-interactively #'markdown-table-next-row))
4994 ;; Indent non-table text
4995 (markdown-indent-on-enter
4996 (let (bounds)
4997 (if (and (memq markdown-indent-on-enter '(indent-and-new-item))
4998 (setq bounds (markdown-cur-list-item-bounds)))
4999 (let ((beg (cl-first bounds))
5000 (end (cl-second bounds))
5001 (length (cl-fourth bounds)))
5002 ;; Point is in a list item
5003 (if (= (- end beg) length)
5004 ;; Delete blank list
5005 (progn
5006 (delete-region beg end)
5007 (newline)
5008 (markdown-indent-line))
5009 (call-interactively #'markdown-insert-list-item)))
5010 ;; Point is not in a list
5011 (newline)
5012 (markdown-indent-line))))
5013 ;; Insert a raw newline
5014 (t (newline))))
5016 (defun markdown-outdent-or-delete (arg)
5017 "Handle BACKSPACE by cycling through indentation points.
5018 When BACKSPACE is pressed, if there is only whitespace
5019 before the current point, then outdent the line one level.
5020 Otherwise, do normal delete by repeating
5021 `backward-delete-char-untabify' ARG times."
5022 (interactive "*p")
5023 (if (use-region-p)
5024 (backward-delete-char-untabify arg)
5025 (let ((cur-pos (current-column))
5026 (start-of-indention (save-excursion
5027 (back-to-indentation)
5028 (current-column)))
5029 (positions (markdown-calc-indents)))
5030 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
5031 (indent-line-to (markdown-outdent-find-next-position cur-pos positions))
5032 (backward-delete-char-untabify arg)))))
5034 (defun markdown-find-leftmost-column (beg end)
5035 "Find the leftmost column in the region from BEG to END."
5036 (let ((mincol 1000))
5037 (save-excursion
5038 (goto-char beg)
5039 (while (< (point) end)
5040 (back-to-indentation)
5041 (unless (looking-at-p "[ \t]*$")
5042 (setq mincol (min mincol (current-column))))
5043 (forward-line 1)
5045 mincol))
5047 (defun markdown-indent-region (beg end arg)
5048 "Indent the region from BEG to END using some heuristics.
5049 When ARG is non-nil, outdent the region instead.
5050 See `markdown-indent-line' and `markdown-indent-line'."
5051 (interactive "*r\nP")
5052 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
5053 (leftmostcol (markdown-find-leftmost-column beg end))
5054 (next-pos (if arg
5055 (markdown-outdent-find-next-position leftmostcol positions)
5056 (markdown-indent-find-next-position leftmostcol positions))))
5057 (indent-rigidly beg end (- next-pos leftmostcol))
5058 (setq deactivate-mark nil)))
5060 (defun markdown-outdent-region (beg end)
5061 "Call `markdown-indent-region' on region from BEG to END with prefix."
5062 (interactive "*r")
5063 (markdown-indent-region beg end t))
5065 (defun markdown--indent-region (start end)
5066 (let ((deactivate-mark nil))
5067 (save-excursion
5068 (goto-char end)
5069 (setq end (point-marker))
5070 (goto-char start)
5071 (when (bolp)
5072 (forward-line 1))
5073 (while (< (point) end)
5074 (unless (or (markdown-code-block-at-point-p) (and (bolp) (eolp)))
5075 (indent-according-to-mode))
5076 (forward-line 1))
5077 (move-marker end nil))))
5080 ;;; Markup Completion =========================================================
5082 (defconst markdown-complete-alist
5083 '((markdown-regex-header-atx . markdown-complete-atx)
5084 (markdown-regex-header-setext . markdown-complete-setext)
5085 (markdown-regex-hr . markdown-complete-hr))
5086 "Association list of form (regexp . function) for markup completion.")
5088 (defun markdown-incomplete-atx-p ()
5089 "Return t if ATX header markup is incomplete and nil otherwise.
5090 Assumes match data is available for `markdown-regex-header-atx'.
5091 Checks that the number of trailing hash marks equals the number of leading
5092 hash marks, that there is only a single space before and after the text,
5093 and that there is no extraneous whitespace in the text."
5095 ;; Number of starting and ending hash marks differs
5096 (not (= (length (match-string 1)) (length (match-string 3))))
5097 ;; When the header text is not empty...
5098 (and (> (length (match-string 2)) 0)
5099 ;; ...if there are extra leading, trailing, or interior spaces
5100 (or (not (= (match-beginning 2) (1+ (match-end 1))))
5101 (not (= (match-beginning 3) (1+ (match-end 2))))
5102 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
5103 ;; When the header text is empty...
5104 (and (= (length (match-string 2)) 0)
5105 ;; ...if there are too many or too few spaces
5106 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
5108 (defun markdown-complete-atx ()
5109 "Complete and normalize ATX headers.
5110 Add or remove hash marks to the end of the header to match the
5111 beginning. Ensure that there is only a single space between hash
5112 marks and header text. Removes extraneous whitespace from header text.
5113 Assumes match data is available for `markdown-regex-header-atx'.
5114 Return nil if markup was complete and non-nil if markup was completed."
5115 (when (markdown-incomplete-atx-p)
5116 (let* ((new-marker (make-marker))
5117 (new-marker (set-marker new-marker (match-end 2))))
5118 ;; Hash marks and spacing at end
5119 (goto-char (match-end 2))
5120 (delete-region (match-end 2) (match-end 3))
5121 (insert " " (match-string 1))
5122 ;; Remove extraneous whitespace from title
5123 (replace-match (markdown-compress-whitespace-string (match-string 2))
5124 t t nil 2)
5125 ;; Spacing at beginning
5126 (goto-char (match-end 1))
5127 (delete-region (match-end 1) (match-beginning 2))
5128 (insert " ")
5129 ;; Leave point at end of text
5130 (goto-char new-marker))))
5132 (defun markdown-incomplete-setext-p ()
5133 "Return t if setext header markup is incomplete and nil otherwise.
5134 Assumes match data is available for `markdown-regex-header-setext'.
5135 Checks that length of underline matches text and that there is no
5136 extraneous whitespace in the text."
5137 (or (not (= (length (match-string 1)) (length (match-string 2))))
5138 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
5140 (defun markdown-complete-setext ()
5141 "Complete and normalize setext headers.
5142 Add or remove underline characters to match length of header
5143 text. Removes extraneous whitespace from header text. Assumes
5144 match data is available for `markdown-regex-header-setext'.
5145 Return nil if markup was complete and non-nil if markup was completed."
5146 (when (markdown-incomplete-setext-p)
5147 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
5148 (char (char-after (match-beginning 2)))
5149 (level (if (char-equal char ?-) 2 1)))
5150 (goto-char (match-beginning 0))
5151 (delete-region (match-beginning 0) (match-end 0))
5152 (markdown-insert-header level text t)
5153 t)))
5155 (defun markdown-incomplete-hr-p ()
5156 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
5157 Assumes match data is available for `markdown-regex-hr'."
5158 (not (member (match-string 0) markdown-hr-strings)))
5160 (defun markdown-complete-hr ()
5161 "Complete horizontal rules.
5162 If horizontal rule string is a member of `markdown-hr-strings',
5163 do nothing. Otherwise, replace with the car of
5164 `markdown-hr-strings'.
5165 Assumes match data is available for `markdown-regex-hr'.
5166 Return nil if markup was complete and non-nil if markup was completed."
5167 (when (markdown-incomplete-hr-p)
5168 (replace-match (car markdown-hr-strings))
5171 (defun markdown-complete ()
5172 "Complete markup of object near point or in region when active.
5173 Handle all objects in `markdown-complete-alist', in order.
5174 See `markdown-complete-at-point' and `markdown-complete-region'."
5175 (interactive "*")
5176 (if (use-region-p)
5177 (markdown-complete-region (region-beginning) (region-end))
5178 (markdown-complete-at-point)))
5180 (defun markdown-complete-at-point ()
5181 "Complete markup of object near point.
5182 Handle all elements of `markdown-complete-alist' in order."
5183 (interactive "*")
5184 (let ((list markdown-complete-alist) found changed)
5185 (while list
5186 (let ((regexp (eval (caar list) t)) ;FIXME: Why `eval'?
5187 (function (cdar list)))
5188 (setq list (cdr list))
5189 (when (thing-at-point-looking-at regexp)
5190 (setq found t)
5191 (setq changed (funcall function))
5192 (setq list nil))))
5193 (if found
5194 (or changed (user-error "Markup at point is complete"))
5195 (user-error "Nothing to complete at point"))))
5197 (defun markdown-complete-region (beg end)
5198 "Complete markup of objects in region from BEG to END.
5199 Handle all objects in `markdown-complete-alist', in order. Each
5200 match is checked to ensure that a previous regexp does not also
5201 match."
5202 (interactive "*r")
5203 (let ((end-marker (set-marker (make-marker) end))
5204 previous)
5205 (dolist (element markdown-complete-alist)
5206 (let ((regexp (eval (car element) t)) ;FIXME: Why `eval'?
5207 (function (cdr element)))
5208 (goto-char beg)
5209 (while (re-search-forward regexp end-marker 'limit)
5210 (when (match-string 0)
5211 ;; Make sure this is not a match for any of the preceding regexps.
5212 ;; This prevents mistaking an HR for a Setext subheading.
5213 (let (match)
5214 (save-match-data
5215 (dolist (prev-regexp previous)
5216 (or match (setq match (looking-back prev-regexp nil)))))
5217 (unless match
5218 (save-excursion (funcall function))))))
5219 (cl-pushnew regexp previous :test #'equal)))
5220 previous))
5222 (defun markdown-complete-buffer ()
5223 "Complete markup for all objects in the current buffer."
5224 (interactive "*")
5225 (markdown-complete-region (point-min) (point-max)))
5228 ;;; Markup Cycling ============================================================
5230 (defun markdown-cycle-atx (arg &optional remove)
5231 "Cycle ATX header markup.
5232 Promote header (decrease level) when ARG is 1 and demote
5233 header (increase level) if arg is -1. When REMOVE is non-nil,
5234 remove the header when the level reaches zero and stop cycling
5235 when it reaches six. Otherwise, perform a proper cycling through
5236 levels one through six. Assumes match data is available for
5237 `markdown-regex-header-atx'."
5238 (let* ((old-level (length (match-string 1)))
5239 (new-level (+ old-level arg))
5240 (text (match-string 2)))
5241 (when (not remove)
5242 (setq new-level (% new-level 6))
5243 (setq new-level (cond ((= new-level 0) 6)
5244 ((< new-level 0) (+ new-level 6))
5245 (t new-level))))
5246 (cond
5247 ((= new-level 0)
5248 (markdown-unwrap-thing-at-point nil 0 2))
5249 ((<= new-level 6)
5250 (goto-char (match-beginning 0))
5251 (delete-region (match-beginning 0) (match-end 0))
5252 (markdown-insert-header new-level text nil)))))
5254 (defun markdown-cycle-setext (arg &optional remove)
5255 "Cycle setext header markup.
5256 Promote header (increase level) when ARG is 1 and demote
5257 header (decrease level or remove) if arg is -1. When demoting a
5258 level-two setext header, replace with a level-three atx header.
5259 When REMOVE is non-nil, remove the header when the level reaches
5260 zero. Otherwise, cycle back to a level six atx header. Assumes
5261 match data is available for `markdown-regex-header-setext'."
5262 (let* ((char (char-after (match-beginning 2)))
5263 (old-level (if (char-equal char ?=) 1 2))
5264 (new-level (+ old-level arg)))
5265 (when (and (not remove) (= new-level 0))
5266 (setq new-level 6))
5267 (cond
5268 ((= new-level 0)
5269 (markdown-unwrap-thing-at-point nil 0 1))
5270 ((<= new-level 2)
5271 (markdown-insert-header new-level nil t))
5272 ((<= new-level 6)
5273 (markdown-insert-header new-level nil nil)))))
5275 (defun markdown-cycle-hr (arg &optional remove)
5276 "Cycle string used for horizontal rule from `markdown-hr-strings'.
5277 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
5278 backwards (promote). When REMOVE is non-nil, remove the hr instead
5279 of cycling when the end of the list is reached.
5280 Assumes match data is available for `markdown-regex-hr'."
5281 (let* ((strings (if (= arg -1)
5282 (reverse markdown-hr-strings)
5283 markdown-hr-strings))
5284 (tail (member (match-string 0) strings))
5285 (new (or (cadr tail)
5286 (if remove
5287 (if (= arg 1)
5289 (car tail))
5290 (car strings)))))
5291 (replace-match new)))
5293 (defun markdown-cycle-bold ()
5294 "Cycle bold markup between underscores and asterisks.
5295 Assumes match data is available for `markdown-regex-bold'."
5296 (save-excursion
5297 (let* ((old-delim (match-string 3))
5298 (new-delim (if (string-equal old-delim "**") "__" "**")))
5299 (replace-match new-delim t t nil 3)
5300 (replace-match new-delim t t nil 5))))
5302 (defun markdown-cycle-italic ()
5303 "Cycle italic markup between underscores and asterisks.
5304 Assumes match data is available for `markdown-regex-italic'."
5305 (save-excursion
5306 (let* ((old-delim (match-string 2))
5307 (new-delim (if (string-equal old-delim "*") "_" "*")))
5308 (replace-match new-delim t t nil 2)
5309 (replace-match new-delim t t nil 4))))
5312 ;;; Keymap ====================================================================
5314 (defun markdown--style-map-prompt ()
5315 "Return a formatted prompt for Markdown markup insertion."
5316 (when markdown-enable-prefix-prompts
5317 (concat
5318 "Markdown: "
5319 (propertize "bold" 'face 'markdown-bold-face) ", "
5320 (propertize "italic" 'face 'markdown-italic-face) ", "
5321 (propertize "code" 'face 'markdown-inline-code-face) ", "
5322 (propertize "C = GFM code" 'face 'markdown-code-face) ", "
5323 (propertize "pre" 'face 'markdown-pre-face) ", "
5324 (propertize "footnote" 'face 'markdown-footnote-text-face) ", "
5325 (propertize "F = foldable" 'face 'markdown-bold-face) ", "
5326 (propertize "q = blockquote" 'face 'markdown-blockquote-face) ", "
5327 (propertize "h & 1-6 = heading" 'face 'markdown-header-face) ", "
5328 (propertize "- = hr" 'face 'markdown-hr-face) ", "
5329 "C-h = more")))
5331 (defun markdown--command-map-prompt ()
5332 "Return prompt for Markdown buffer-wide commands."
5333 (when markdown-enable-prefix-prompts
5334 (concat
5335 "Command: "
5336 (propertize "m" 'face 'markdown-bold-face) "arkdown, "
5337 (propertize "p" 'face 'markdown-bold-face) "review, "
5338 (propertize "o" 'face 'markdown-bold-face) "pen, "
5339 (propertize "e" 'face 'markdown-bold-face) "xport, "
5340 "export & pre" (propertize "v" 'face 'markdown-bold-face) "iew, "
5341 (propertize "c" 'face 'markdown-bold-face) "heck refs, "
5342 (propertize "u" 'face 'markdown-bold-face) "nused refs, "
5343 "C-h = more")))
5345 (defvar markdown-mode-style-map
5346 (let ((map (make-keymap (markdown--style-map-prompt))))
5347 (define-key map (kbd "1") 'markdown-insert-header-atx-1)
5348 (define-key map (kbd "2") 'markdown-insert-header-atx-2)
5349 (define-key map (kbd "3") 'markdown-insert-header-atx-3)
5350 (define-key map (kbd "4") 'markdown-insert-header-atx-4)
5351 (define-key map (kbd "5") 'markdown-insert-header-atx-5)
5352 (define-key map (kbd "6") 'markdown-insert-header-atx-6)
5353 (define-key map (kbd "!") 'markdown-insert-header-setext-1)
5354 (define-key map (kbd "@") 'markdown-insert-header-setext-2)
5355 (define-key map (kbd "b") 'markdown-insert-bold)
5356 (define-key map (kbd "c") 'markdown-insert-code)
5357 (define-key map (kbd "C") 'markdown-insert-gfm-code-block)
5358 (define-key map (kbd "f") 'markdown-insert-footnote)
5359 (define-key map (kbd "F") 'markdown-insert-foldable-block)
5360 (define-key map (kbd "h") 'markdown-insert-header-dwim)
5361 (define-key map (kbd "H") 'markdown-insert-header-setext-dwim)
5362 (define-key map (kbd "i") 'markdown-insert-italic)
5363 (define-key map (kbd "k") 'markdown-insert-kbd)
5364 (define-key map (kbd "l") 'markdown-insert-link)
5365 (define-key map (kbd "p") 'markdown-insert-pre)
5366 (define-key map (kbd "P") 'markdown-pre-region)
5367 (define-key map (kbd "q") 'markdown-insert-blockquote)
5368 (define-key map (kbd "s") 'markdown-insert-strike-through)
5369 (define-key map (kbd "t") 'markdown-insert-table)
5370 (define-key map (kbd "Q") 'markdown-blockquote-region)
5371 (define-key map (kbd "w") 'markdown-insert-wiki-link)
5372 (define-key map (kbd "-") 'markdown-insert-hr)
5373 (define-key map (kbd "[") 'markdown-insert-gfm-checkbox)
5374 ;; Deprecated keys that may be removed in a future version
5375 (define-key map (kbd "e") 'markdown-insert-italic)
5376 map)
5377 "Keymap for Markdown text styling commands.")
5379 (defvar markdown-mode-command-map
5380 (let ((map (make-keymap (markdown--command-map-prompt))))
5381 (define-key map (kbd "m") 'markdown-other-window)
5382 (define-key map (kbd "p") 'markdown-preview)
5383 (define-key map (kbd "e") 'markdown-export)
5384 (define-key map (kbd "v") 'markdown-export-and-preview)
5385 (define-key map (kbd "o") 'markdown-open)
5386 (define-key map (kbd "l") 'markdown-live-preview-mode)
5387 (define-key map (kbd "w") 'markdown-kill-ring-save)
5388 (define-key map (kbd "c") 'markdown-check-refs)
5389 (define-key map (kbd "u") 'markdown-unused-refs)
5390 (define-key map (kbd "n") 'markdown-cleanup-list-numbers)
5391 (define-key map (kbd "]") 'markdown-complete-buffer)
5392 (define-key map (kbd "^") 'markdown-table-sort-lines)
5393 (define-key map (kbd "|") 'markdown-table-convert-region)
5394 (define-key map (kbd "t") 'markdown-table-transpose)
5395 map)
5396 "Keymap for Markdown buffer-wide commands.")
5398 (defvar markdown-mode-map
5399 (let ((map (make-keymap)))
5400 ;; Markup insertion & removal
5401 (define-key map (kbd "C-c C-s") markdown-mode-style-map)
5402 (define-key map (kbd "C-c C-l") 'markdown-insert-link)
5403 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
5404 ;; Promotion, demotion, and cycling
5405 (define-key map (kbd "C-c C--") 'markdown-promote)
5406 (define-key map (kbd "C-c C-=") 'markdown-demote)
5407 (define-key map (kbd "C-c C-]") 'markdown-complete)
5408 ;; Following and doing things
5409 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
5410 (define-key map (kbd "C-c C-d") 'markdown-do)
5411 (define-key map (kbd "C-c '") 'markdown-edit-code-block)
5412 ;; Indentation
5413 (define-key map (kbd "RET") 'markdown-enter-key)
5414 (define-key map (kbd "DEL") 'markdown-outdent-or-delete)
5415 (define-key map (kbd "C-c >") 'markdown-indent-region)
5416 (define-key map (kbd "C-c <") 'markdown-outdent-region)
5417 ;; Visibility cycling
5418 (define-key map (kbd "TAB") 'markdown-cycle)
5419 ;; S-iso-lefttab and S-tab should both be mapped to `backtab' by
5420 ;; (local-)function-key-map.
5421 ;;(define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
5422 ;;(define-key map (kbd "<S-tab>") 'markdown-shifttab)
5423 (define-key map (kbd "<backtab>") 'markdown-shifttab)
5424 ;; Heading and list navigation
5425 (define-key map (kbd "C-c C-n") 'markdown-outline-next)
5426 (define-key map (kbd "C-c C-p") 'markdown-outline-previous)
5427 (define-key map (kbd "C-c C-f") 'markdown-outline-next-same-level)
5428 (define-key map (kbd "C-c C-b") 'markdown-outline-previous-same-level)
5429 (define-key map (kbd "C-c C-u") 'markdown-outline-up)
5430 ;; Buffer-wide commands
5431 (define-key map (kbd "C-c C-c") markdown-mode-command-map)
5432 ;; Subtree, list, and table editing
5433 (define-key map (kbd "C-c <up>") 'markdown-move-up)
5434 (define-key map (kbd "C-c <down>") 'markdown-move-down)
5435 (define-key map (kbd "C-c <left>") 'markdown-promote)
5436 (define-key map (kbd "C-c <right>") 'markdown-demote)
5437 (define-key map (kbd "C-c S-<up>") 'markdown-table-delete-row)
5438 (define-key map (kbd "C-c S-<down>") 'markdown-table-insert-row)
5439 (define-key map (kbd "C-c S-<left>") 'markdown-table-delete-column)
5440 (define-key map (kbd "C-c S-<right>") 'markdown-table-insert-column)
5441 (define-key map (kbd "C-c C-M-h") 'markdown-mark-subtree)
5442 (define-key map (kbd "C-x n s") 'markdown-narrow-to-subtree)
5443 (define-key map (kbd "M-RET") 'markdown-insert-list-item)
5444 (define-key map (kbd "C-c C-j") 'markdown-insert-list-item)
5445 ;; Paragraphs (Markdown context aware)
5446 (define-key map [remap backward-paragraph] 'markdown-backward-paragraph)
5447 (define-key map [remap forward-paragraph] 'markdown-forward-paragraph)
5448 (define-key map [remap mark-paragraph] 'markdown-mark-paragraph)
5449 ;; Blocks (one or more paragraphs)
5450 (define-key map (kbd "C-M-{") 'markdown-backward-block)
5451 (define-key map (kbd "C-M-}") 'markdown-forward-block)
5452 (define-key map (kbd "C-c M-h") 'markdown-mark-block)
5453 (define-key map (kbd "C-x n b") 'markdown-narrow-to-block)
5454 ;; Pages (top-level sections)
5455 (define-key map [remap backward-page] 'markdown-backward-page)
5456 (define-key map [remap forward-page] 'markdown-forward-page)
5457 (define-key map [remap mark-page] 'markdown-mark-page)
5458 (define-key map [remap narrow-to-page] 'markdown-narrow-to-page)
5459 ;; Link Movement
5460 (define-key map (kbd "M-n") 'markdown-next-link)
5461 (define-key map (kbd "M-p") 'markdown-previous-link)
5462 ;; Toggling functionality
5463 (define-key map (kbd "C-c C-x C-e") 'markdown-toggle-math)
5464 (define-key map (kbd "C-c C-x C-f") 'markdown-toggle-fontify-code-blocks-natively)
5465 (define-key map (kbd "C-c C-x C-i") 'markdown-toggle-inline-images)
5466 (define-key map (kbd "C-c C-x C-l") 'markdown-toggle-url-hiding)
5467 (define-key map (kbd "C-c C-x C-m") 'markdown-toggle-markup-hiding)
5468 ;; Alternative keys (in case of problems with the arrow keys)
5469 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
5470 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
5471 (define-key map (kbd "C-c C-x l") 'markdown-promote)
5472 (define-key map (kbd "C-c C-x r") 'markdown-demote)
5473 ;; Deprecated keys that may be removed in a future version
5474 (define-key map (kbd "C-c C-a L") 'markdown-insert-link) ;; C-c C-l
5475 (define-key map (kbd "C-c C-a l") 'markdown-insert-link) ;; C-c C-l
5476 (define-key map (kbd "C-c C-a r") 'markdown-insert-link) ;; C-c C-l
5477 (define-key map (kbd "C-c C-a u") 'markdown-insert-uri) ;; C-c C-l
5478 (define-key map (kbd "C-c C-a f") 'markdown-insert-footnote)
5479 (define-key map (kbd "C-c C-a w") 'markdown-insert-wiki-link)
5480 (define-key map (kbd "C-c C-t 1") 'markdown-insert-header-atx-1)
5481 (define-key map (kbd "C-c C-t 2") 'markdown-insert-header-atx-2)
5482 (define-key map (kbd "C-c C-t 3") 'markdown-insert-header-atx-3)
5483 (define-key map (kbd "C-c C-t 4") 'markdown-insert-header-atx-4)
5484 (define-key map (kbd "C-c C-t 5") 'markdown-insert-header-atx-5)
5485 (define-key map (kbd "C-c C-t 6") 'markdown-insert-header-atx-6)
5486 (define-key map (kbd "C-c C-t !") 'markdown-insert-header-setext-1)
5487 (define-key map (kbd "C-c C-t @") 'markdown-insert-header-setext-2)
5488 (define-key map (kbd "C-c C-t h") 'markdown-insert-header-dwim)
5489 (define-key map (kbd "C-c C-t H") 'markdown-insert-header-setext-dwim)
5490 (define-key map (kbd "C-c C-t s") 'markdown-insert-header-setext-2)
5491 (define-key map (kbd "C-c C-t t") 'markdown-insert-header-setext-1)
5492 (define-key map (kbd "C-c C-i") 'markdown-insert-image)
5493 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item) ;; C-c C-j
5494 (define-key map (kbd "C-c C-x C-x") 'markdown-toggle-gfm-checkbox) ;; C-c C-d
5495 (define-key map (kbd "C-c -") 'markdown-insert-hr)
5496 map)
5497 "Keymap for Markdown major mode.")
5499 (defvar markdown-mode-mouse-map
5500 (when markdown-mouse-follow-link
5501 (let ((map (make-sparse-keymap)))
5502 (define-key map [follow-link] 'mouse-face)
5503 (define-key map [mouse-2] #'markdown-follow-thing-at-point)
5504 map))
5505 "Keymap for following links with mouse.")
5507 (defvar gfm-mode-map
5508 (let ((map (make-sparse-keymap)))
5509 (set-keymap-parent map markdown-mode-map)
5510 (define-key map (kbd "C-c C-s d") 'markdown-insert-strike-through)
5511 (define-key map "`" 'markdown-electric-backquote)
5512 map)
5513 "Keymap for `gfm-mode'.
5514 See also `markdown-mode-map'.")
5517 ;;; Menu ======================================================================
5519 (easy-menu-define markdown-mode-menu markdown-mode-map
5520 "Menu for Markdown mode."
5521 '("Markdown"
5522 "---"
5523 ("Movement"
5524 ["Jump" markdown-do]
5525 ["Follow Link" markdown-follow-thing-at-point]
5526 ["Next Link" markdown-next-link]
5527 ["Previous Link" markdown-previous-link]
5528 "---"
5529 ["Next Heading or List Item" markdown-outline-next]
5530 ["Previous Heading or List Item" markdown-outline-previous]
5531 ["Next at Same Level" markdown-outline-next-same-level]
5532 ["Previous at Same Level" markdown-outline-previous-same-level]
5533 ["Up to Parent" markdown-outline-up]
5534 "---"
5535 ["Forward Paragraph" markdown-forward-paragraph]
5536 ["Backward Paragraph" markdown-backward-paragraph]
5537 ["Forward Block" markdown-forward-block]
5538 ["Backward Block" markdown-backward-block])
5539 ("Show & Hide"
5540 ["Cycle Heading Visibility" markdown-cycle
5541 :enable (markdown-on-heading-p)]
5542 ["Cycle Heading Visibility (Global)" markdown-shifttab]
5543 "---"
5544 ["Narrow to Region" narrow-to-region]
5545 ["Narrow to Block" markdown-narrow-to-block]
5546 ["Narrow to Section" narrow-to-defun]
5547 ["Narrow to Subtree" markdown-narrow-to-subtree]
5548 ["Widen" widen (buffer-narrowed-p)]
5549 "---"
5550 ["Toggle Markup Hiding" markdown-toggle-markup-hiding
5551 :keys "C-c C-x C-m"
5552 :style radio
5553 :selected markdown-hide-markup])
5554 "---"
5555 ("Headings & Structure"
5556 ["Automatic Heading" markdown-insert-header-dwim
5557 :keys "C-c C-s h"]
5558 ["Automatic Heading (Setext)" markdown-insert-header-setext-dwim
5559 :keys "C-c C-s H"]
5560 ("Specific Heading (atx)"
5561 ["First Level atx" markdown-insert-header-atx-1
5562 :keys "C-c C-s 1"]
5563 ["Second Level atx" markdown-insert-header-atx-2
5564 :keys "C-c C-s 2"]
5565 ["Third Level atx" markdown-insert-header-atx-3
5566 :keys "C-c C-s 3"]
5567 ["Fourth Level atx" markdown-insert-header-atx-4
5568 :keys "C-c C-s 4"]
5569 ["Fifth Level atx" markdown-insert-header-atx-5
5570 :keys "C-c C-s 5"]
5571 ["Sixth Level atx" markdown-insert-header-atx-6
5572 :keys "C-c C-s 6"])
5573 ("Specific Heading (Setext)"
5574 ["First Level Setext" markdown-insert-header-setext-1
5575 :keys "C-c C-s !"]
5576 ["Second Level Setext" markdown-insert-header-setext-2
5577 :keys "C-c C-s @"])
5578 ["Horizontal Rule" markdown-insert-hr
5579 :keys "C-c C-s -"]
5580 "---"
5581 ["Move Subtree Up" markdown-move-up
5582 :keys "C-c <up>"]
5583 ["Move Subtree Down" markdown-move-down
5584 :keys "C-c <down>"]
5585 ["Promote Subtree" markdown-promote
5586 :keys "C-c <left>"]
5587 ["Demote Subtree" markdown-demote
5588 :keys "C-c <right>"])
5589 ("Region & Mark"
5590 ["Indent Region" markdown-indent-region]
5591 ["Outdent Region" markdown-outdent-region]
5592 "--"
5593 ["Mark Paragraph" mark-paragraph]
5594 ["Mark Block" markdown-mark-block]
5595 ["Mark Section" mark-defun]
5596 ["Mark Subtree" markdown-mark-subtree])
5597 ("Tables"
5598 ["Move Row Up" markdown-move-up
5599 :enable (markdown-table-at-point-p)
5600 :keys "C-c <up>"]
5601 ["Move Row Down" markdown-move-down
5602 :enable (markdown-table-at-point-p)
5603 :keys "C-c <down>"]
5604 ["Move Column Left" markdown-promote
5605 :enable (markdown-table-at-point-p)
5606 :keys "C-c <left>"]
5607 ["Move Column Right" markdown-demote
5608 :enable (markdown-table-at-point-p)
5609 :keys "C-c <right>"]
5610 ["Delete Row" markdown-table-delete-row
5611 :enable (markdown-table-at-point-p)]
5612 ["Insert Row" markdown-table-insert-row
5613 :enable (markdown-table-at-point-p)]
5614 ["Delete Column" markdown-table-delete-column
5615 :enable (markdown-table-at-point-p)]
5616 ["Insert Column" markdown-table-insert-column
5617 :enable (markdown-table-at-point-p)]
5618 ["Insert Table" markdown-insert-table]
5619 "--"
5620 ["Convert Region to Table" markdown-table-convert-region]
5621 ["Sort Table Lines" markdown-table-sort-lines
5622 :enable (markdown-table-at-point-p)]
5623 ["Transpose Table" markdown-table-transpose
5624 :enable (markdown-table-at-point-p)])
5625 ("Lists"
5626 ["Insert List Item" markdown-insert-list-item]
5627 ["Move Subtree Up" markdown-move-up
5628 :keys "C-c <up>"]
5629 ["Move Subtree Down" markdown-move-down
5630 :keys "C-c <down>"]
5631 ["Indent Subtree" markdown-demote
5632 :keys "C-c <right>"]
5633 ["Outdent Subtree" markdown-promote
5634 :keys "C-c <left>"]
5635 ["Renumber List" markdown-cleanup-list-numbers]
5636 ["Insert Task List Item" markdown-insert-gfm-checkbox
5637 :keys "C-c C-x ["]
5638 ["Toggle Task List Item" markdown-toggle-gfm-checkbox
5639 :enable (markdown-gfm-task-list-item-at-point)
5640 :keys "C-c C-d"])
5641 ("Links & Images"
5642 ["Insert Link" markdown-insert-link]
5643 ["Insert Image" markdown-insert-image]
5644 ["Insert Footnote" markdown-insert-footnote
5645 :keys "C-c C-s f"]
5646 ["Insert Wiki Link" markdown-insert-wiki-link
5647 :keys "C-c C-s w"]
5648 "---"
5649 ["Check References" markdown-check-refs]
5650 ["Find Unused References" markdown-unused-refs]
5651 ["Toggle URL Hiding" markdown-toggle-url-hiding
5652 :style radio
5653 :selected markdown-hide-urls]
5654 ["Toggle Inline Images" markdown-toggle-inline-images
5655 :keys "C-c C-x C-i"
5656 :style radio
5657 :selected markdown-inline-image-overlays]
5658 ["Toggle Wiki Links" markdown-toggle-wiki-links
5659 :style radio
5660 :selected markdown-enable-wiki-links])
5661 ("Styles"
5662 ["Bold" markdown-insert-bold]
5663 ["Italic" markdown-insert-italic]
5664 ["Code" markdown-insert-code]
5665 ["Strikethrough" markdown-insert-strike-through]
5666 ["Keyboard" markdown-insert-kbd]
5667 "---"
5668 ["Blockquote" markdown-insert-blockquote]
5669 ["Preformatted" markdown-insert-pre]
5670 ["GFM Code Block" markdown-insert-gfm-code-block]
5671 ["Edit Code Block" markdown-edit-code-block
5672 :enable (markdown-code-block-at-point-p)]
5673 ["Foldable Block" markdown-insert-foldable-block]
5674 "---"
5675 ["Blockquote Region" markdown-blockquote-region]
5676 ["Preformatted Region" markdown-pre-region]
5677 "---"
5678 ["Fontify Code Blocks Natively"
5679 markdown-toggle-fontify-code-blocks-natively
5680 :style radio
5681 :selected markdown-fontify-code-blocks-natively]
5682 ["LaTeX Math Support" markdown-toggle-math
5683 :style radio
5684 :selected markdown-enable-math])
5685 "---"
5686 ("Preview & Export"
5687 ["Compile" markdown-other-window]
5688 ["Preview" markdown-preview]
5689 ["Export" markdown-export]
5690 ["Export & View" markdown-export-and-preview]
5691 ["Open" markdown-open]
5692 ["Live Export" markdown-live-preview-mode
5693 :style radio
5694 :selected markdown-live-preview-mode]
5695 ["Kill ring save" markdown-kill-ring-save])
5696 ("Markup Completion and Cycling"
5697 ["Complete Markup" markdown-complete]
5698 ["Promote Element" markdown-promote
5699 :keys "C-c C--"]
5700 ["Demote Element" markdown-demote
5701 :keys "C-c C-="])
5702 "---"
5703 ["Kill Element" markdown-kill-thing-at-point]
5704 "---"
5705 ("Documentation"
5706 ["Version" markdown-show-version]
5707 ["Homepage" markdown-mode-info]
5708 ["Describe Mode" (describe-function 'markdown-mode)]
5709 ["Guide" (browse-url "https://leanpub.com/markdown-mode")])))
5712 ;;; imenu =====================================================================
5714 (defun markdown-imenu-create-nested-index ()
5715 "Create and return a nested imenu index alist for the current buffer.
5716 See `imenu-create-index-function' and `imenu--index-alist' for details."
5717 (let* ((root '(nil . nil))
5718 (min-level 9999)
5719 hashes headers)
5720 (save-excursion
5721 ;; Headings
5722 (goto-char (point-min))
5723 (while (re-search-forward markdown-regex-header (point-max) t)
5724 (unless (or (markdown-code-block-at-point-p)
5725 (and (match-beginning 3)
5726 (get-text-property (match-beginning 3) 'markdown-yaml-metadata-end)))
5727 (cond
5728 ((match-string-no-properties 2) ;; level 1 setext
5729 (setq min-level 1)
5730 (push (list :heading (match-string-no-properties 1)
5731 :point (match-beginning 1)
5732 :level 1) headers))
5733 ((match-string-no-properties 3) ;; level 2 setext
5734 (setq min-level (min min-level 2))
5735 (push (list :heading (match-string-no-properties 1)
5736 :point (match-beginning 1)
5737 :level (- 2 (1- min-level))) headers))
5738 ((setq hashes (markdown-trim-whitespace
5739 (match-string-no-properties 4)))
5740 (setq min-level (min min-level (length hashes)))
5741 (push (list :heading (match-string-no-properties 5)
5742 :point (match-beginning 4)
5743 :level (- (length hashes) (1- min-level))) headers)))))
5744 (cl-loop with cur-level = 0
5745 with cur-alist = nil
5746 with empty-heading = "-"
5747 with self-heading = "."
5748 for header in (reverse headers)
5749 for level = (plist-get header :level)
5751 (let ((alist (list (cons (plist-get header :heading) (plist-get header :point)))))
5752 (cond
5753 ((= cur-level level) ; new sibling
5754 (setcdr cur-alist alist)
5755 (setq cur-alist alist))
5756 ((< cur-level level) ; first child
5757 (dotimes (_ (- level cur-level 1))
5758 (setq alist (list (cons empty-heading alist))))
5759 (if cur-alist
5760 (let* ((parent (car cur-alist))
5761 (self-pos (cdr parent)))
5762 (setcdr parent (cons (cons self-heading self-pos) alist)))
5763 (setcdr root alist)) ; primogenitor
5764 (setq cur-alist alist)
5765 (setq cur-level level))
5766 (t ; new sibling of an ancestor
5767 (let ((sibling-alist (last (cdr root))))
5768 (dotimes (_ (1- level))
5769 (setq sibling-alist (last (cdar sibling-alist))))
5770 (setcdr sibling-alist alist)
5771 (setq cur-alist alist))
5772 (setq cur-level level)))))
5773 (setq root (copy-tree root))
5774 ;; Footnotes
5775 (let ((fn (markdown-get-defined-footnotes)))
5776 (if (or (zerop (length fn))
5777 (null markdown-add-footnotes-to-imenu))
5778 (cdr root)
5779 (nconc (cdr root) (list (cons "Footnotes" fn))))))))
5781 (defun markdown-imenu-create-flat-index ()
5782 "Create and return a flat imenu index alist for the current buffer.
5783 See `imenu-create-index-function' and `imenu--index-alist' for details."
5784 (let* ((empty-heading "-") index heading pos)
5785 (save-excursion
5786 ;; Headings
5787 (goto-char (point-min))
5788 (while (re-search-forward markdown-regex-header (point-max) t)
5789 (when (and (not (markdown-code-block-at-point-p (point-at-bol)))
5790 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin)))
5791 (cond
5792 ((setq heading (match-string-no-properties 1))
5793 (setq pos (match-beginning 1)))
5794 ((setq heading (match-string-no-properties 5))
5795 (setq pos (match-beginning 4))))
5796 (or (> (length heading) 0)
5797 (setq heading empty-heading))
5798 (setq index (append index (list (cons heading pos))))))
5799 ;; Footnotes
5800 (when markdown-add-footnotes-to-imenu
5801 (nconc index (markdown-get-defined-footnotes)))
5802 index)))
5805 ;;; References ================================================================
5807 (defun markdown-reference-goto-definition ()
5808 "Jump to the definition of the reference at point or create it."
5809 (interactive)
5810 (when (thing-at-point-looking-at markdown-regex-link-reference)
5811 (let* ((text (match-string-no-properties 3))
5812 (reference (match-string-no-properties 6))
5813 (target (downcase (if (string= reference "") text reference)))
5814 (loc (cadr (save-match-data (markdown-reference-definition target)))))
5815 (if loc
5816 (goto-char loc)
5817 (goto-char (match-beginning 0))
5818 (markdown-insert-reference-definition target)))))
5820 (defun markdown-reference-find-links (reference)
5821 "Return a list of all links for REFERENCE.
5822 REFERENCE should not include the surrounding square brackets.
5823 Elements of the list have the form (text start line), where
5824 text is the link text, start is the location at the beginning of
5825 the link, and line is the line number on which the link appears."
5826 (let* ((ref-quote (regexp-quote reference))
5827 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
5828 ref-quote ref-quote))
5829 links)
5830 (save-excursion
5831 (goto-char (point-min))
5832 (while (re-search-forward regexp nil t)
5833 (let* ((text (or (match-string-no-properties 1)
5834 (match-string-no-properties 2)))
5835 (start (match-beginning 0))
5836 (line (markdown-line-number-at-pos)))
5837 (cl-pushnew (list text start line) links :test #'equal))))
5838 links))
5840 (defmacro markdown-for-all-refs (f)
5841 `(let ((result))
5842 (save-excursion
5843 (goto-char (point-min))
5844 (while
5845 (re-search-forward markdown-regex-link-reference nil t)
5846 (let* ((text (match-string-no-properties 3))
5847 (reference (match-string-no-properties 6))
5848 (target (downcase (if (string= reference "") text reference))))
5849 (,f text target result))))
5850 (reverse result)))
5852 (defmacro markdown-collect-always (_ target result)
5853 `(cl-pushnew ,target ,result :test #'equal))
5855 (defmacro markdown-collect-undefined (text target result)
5856 `(unless (markdown-reference-definition target)
5857 (let ((entry (assoc ,target ,result)))
5858 (if (not entry)
5859 (cl-pushnew
5860 (cons ,target (list (cons ,text (markdown-line-number-at-pos))))
5861 ,result :test #'equal)
5862 (setcdr entry
5863 (append (cdr entry) (list (cons ,text (markdown-line-number-at-pos)))))))))
5865 (defun markdown-get-all-refs ()
5866 "Return a list of all Markdown references."
5867 (markdown-for-all-refs markdown-collect-always))
5869 (defun markdown-get-undefined-refs ()
5870 "Return a list of undefined Markdown references.
5871 Result is an alist of pairs (reference . occurrences), where
5872 occurrences is itself another alist of pairs (label . line-number).
5873 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
5874 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
5875 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
5876 (markdown-for-all-refs markdown-collect-undefined))
5878 (defun markdown-get-unused-refs ()
5879 (cl-sort
5880 (cl-set-difference
5881 (markdown-get-defined-references) (markdown-get-all-refs)
5882 :test (lambda (e1 e2) (equal (car e1) e2)))
5883 #'< :key #'cdr))
5885 (defmacro defun-markdown-buffer (name docstring)
5886 "Define a function to name and return a buffer.
5888 By convention, NAME must be a name of a string constant with
5889 %buffer% placeholder used to name the buffer, and will also be
5890 used as a name of the function defined.
5892 DOCSTRING will be used as the first part of the docstring."
5893 `(defun ,name (&optional buffer-name)
5894 ,(concat docstring "\n\nBUFFER-NAME is the name of the main buffer being visited.")
5895 (or buffer-name (setq buffer-name (buffer-name)))
5896 (let ((refbuf (get-buffer-create (replace-regexp-in-string
5897 "%buffer%" buffer-name
5898 ,name))))
5899 (with-current-buffer refbuf
5900 (when view-mode
5901 (View-exit-and-edit))
5902 (use-local-map button-buffer-map)
5903 (erase-buffer))
5904 refbuf)))
5906 (defconst markdown-reference-check-buffer
5907 "*Undefined references for %buffer%*"
5908 "Pattern for name of buffer for listing undefined references.
5909 The string %buffer% will be replaced by the corresponding
5910 `markdown-mode' buffer name.")
5912 (defun-markdown-buffer
5913 markdown-reference-check-buffer
5914 "Name and return buffer for reference checking.")
5916 (defconst markdown-unused-references-buffer
5917 "*Unused references for %buffer%*"
5918 "Pattern for name of buffer for listing unused references.
5919 The string %buffer% will be replaced by the corresponding
5920 `markdown-mode' buffer name.")
5922 (defun-markdown-buffer
5923 markdown-unused-references-buffer
5924 "Name and return buffer for unused reference checking.")
5926 (defconst markdown-reference-links-buffer
5927 "*Reference links for %buffer%*"
5928 "Pattern for name of buffer for listing references.
5929 The string %buffer% will be replaced by the corresponding buffer name.")
5931 (defun-markdown-buffer
5932 markdown-reference-links-buffer
5933 "Name, setup, and return a buffer for listing links.")
5935 ;; Add an empty Markdown reference definition to buffer
5936 ;; specified in the 'target-buffer property. The reference name is
5937 ;; the button's label.
5938 (define-button-type 'markdown-undefined-reference-button
5939 'help-echo "mouse-1, RET: create definition for undefined reference"
5940 'follow-link t
5941 'face 'bold
5942 'action (lambda (b)
5943 (let ((buffer (button-get b 'target-buffer))
5944 (line (button-get b 'target-line))
5945 (label (button-label b)))
5946 (switch-to-buffer-other-window buffer)
5947 (goto-char (point-min))
5948 (forward-line line)
5949 (markdown-insert-reference-definition label)
5950 (markdown-check-refs t))))
5952 ;; Jump to line in buffer specified by 'target-buffer property.
5953 ;; Line number is button's 'target-line property.
5954 (define-button-type 'markdown-goto-line-button
5955 'help-echo "mouse-1, RET: go to line"
5956 'follow-link t
5957 'face 'italic
5958 'action (lambda (b)
5959 (switch-to-buffer-other-window (button-get b 'target-buffer))
5960 ;; use call-interactively to silence compiler
5961 (let ((current-prefix-arg (button-get b 'target-line)))
5962 (call-interactively 'goto-line))))
5964 ;; Kill a line in buffer specified by 'target-buffer property.
5965 ;; Line number is button's 'target-line property.
5966 (define-button-type 'markdown-kill-line-button
5967 'help-echo "mouse-1, RET: kill line"
5968 'follow-link t
5969 'face 'italic
5970 'action (lambda (b)
5971 (switch-to-buffer-other-window (button-get b 'target-buffer))
5972 ;; use call-interactively to silence compiler
5973 (let ((current-prefix-arg (button-get b 'target-line)))
5974 (call-interactively 'goto-line))
5975 (kill-line 1)
5976 (markdown-unused-refs t)))
5978 ;; Jumps to a particular link at location given by 'target-char
5979 ;; property in buffer given by 'target-buffer property.
5980 (define-button-type 'markdown-location-button
5981 'help-echo "mouse-1, RET: jump to location of link"
5982 'follow-link t
5983 'face 'bold
5984 'action (lambda (b)
5985 (let ((target (button-get b 'target-buffer))
5986 (loc (button-get b 'target-char)))
5987 (kill-buffer-and-window)
5988 (switch-to-buffer target)
5989 (goto-char loc))))
5991 (defun markdown-insert-undefined-reference-button (reference oldbuf)
5992 "Insert a button for creating REFERENCE in buffer OLDBUF.
5993 REFERENCE should be a list of the form (reference . occurrences),
5994 as returned by `markdown-get-undefined-refs'."
5995 (let ((label (car reference)))
5996 ;; Create a reference button
5997 (insert-button label
5998 :type 'markdown-undefined-reference-button
5999 'target-buffer oldbuf
6000 'target-line (cdr (car (cdr reference))))
6001 (insert " (")
6002 (dolist (occurrence (cdr reference))
6003 (let ((line (cdr occurrence)))
6004 ;; Create a line number button
6005 (insert-button (number-to-string line)
6006 :type 'markdown-goto-line-button
6007 'target-buffer oldbuf
6008 'target-line line)
6009 (insert " ")))
6010 (delete-char -1)
6011 (insert ")")
6012 (newline)))
6014 (defun markdown-insert-unused-reference-button (reference oldbuf)
6015 "Insert a button for creating REFERENCE in buffer OLDBUF.
6016 REFERENCE must be a pair of (ref . line-number)."
6017 (let ((label (car reference))
6018 (line (cdr reference)))
6019 ;; Create a reference button
6020 (insert-button label
6021 :type 'markdown-goto-line-button
6022 'face 'bold
6023 'target-buffer oldbuf
6024 'target-line line)
6025 (insert (format " (%d) [" line))
6026 (insert-button "X"
6027 :type 'markdown-kill-line-button
6028 'face 'bold
6029 'target-buffer oldbuf
6030 'target-line line)
6031 (insert "]")
6032 (newline)))
6034 (defun markdown-insert-link-button (link oldbuf)
6035 "Insert a button for jumping to LINK in buffer OLDBUF.
6036 LINK should be a list of the form (text char line) containing
6037 the link text, location, and line number."
6038 (let ((label (cl-first link))
6039 (char (cl-second link))
6040 (line (cl-third link)))
6041 ;; Create a reference button
6042 (insert-button label
6043 :type 'markdown-location-button
6044 'target-buffer oldbuf
6045 'target-char char)
6046 (insert (format " (line %d)\n" line))))
6048 (defun markdown-reference-goto-link (&optional reference)
6049 "Jump to the location of the first use of REFERENCE."
6050 (interactive)
6051 (unless reference
6052 (if (thing-at-point-looking-at markdown-regex-reference-definition)
6053 (setq reference (match-string-no-properties 2))
6054 (user-error "No reference definition at point")))
6055 (let ((links (markdown-reference-find-links reference)))
6056 (cond ((= (length links) 1)
6057 (goto-char (cadr (car links))))
6058 ((> (length links) 1)
6059 (let ((oldbuf (current-buffer))
6060 (linkbuf (markdown-reference-links-buffer)))
6061 (with-current-buffer linkbuf
6062 (insert "Links using reference " reference ":\n\n")
6063 (dolist (link (reverse links))
6064 (markdown-insert-link-button link oldbuf)))
6065 (view-buffer-other-window linkbuf)
6066 (goto-char (point-min))
6067 (forward-line 2)))
6069 (error "No links for reference %s" reference)))))
6071 (defmacro defun-markdown-ref-checker
6072 (name docstring checker-function buffer-function none-message buffer-header insert-reference)
6073 "Define a function NAME acting on result of CHECKER-FUNCTION.
6075 DOCSTRING is used as a docstring for the defined function.
6077 BUFFER-FUNCTION should name and return an auxiliary buffer to put
6078 results in.
6080 NONE-MESSAGE is used when CHECKER-FUNCTION returns no results.
6082 BUFFER-HEADER is put into the auxiliary buffer first, followed by
6083 calling INSERT-REFERENCE for each element in the list returned by
6084 CHECKER-FUNCTION."
6085 `(defun ,name (&optional silent)
6086 ,(concat
6087 docstring
6088 "\n\nIf SILENT is non-nil, do not message anything when no
6089 such references found.")
6090 (interactive "P")
6091 (unless (derived-mode-p 'markdown-mode)
6092 (user-error "Not available in current mode"))
6093 (let ((oldbuf (current-buffer))
6094 (refs (,checker-function))
6095 (refbuf (,buffer-function)))
6096 (if (null refs)
6097 (progn
6098 (when (not silent)
6099 (message ,none-message))
6100 (kill-buffer refbuf))
6101 (with-current-buffer refbuf
6102 (insert ,buffer-header)
6103 (dolist (ref refs)
6104 (,insert-reference ref oldbuf))
6105 (view-buffer-other-window refbuf)
6106 (goto-char (point-min))
6107 (forward-line 2))))))
6109 (defun-markdown-ref-checker
6110 markdown-check-refs
6111 "Show all undefined Markdown references in current `markdown-mode' buffer.
6113 Links which have empty reference definitions are considered to be
6114 defined."
6115 markdown-get-undefined-refs
6116 markdown-reference-check-buffer
6117 "No undefined references found"
6118 "The following references are undefined:\n\n"
6119 markdown-insert-undefined-reference-button)
6122 (defun-markdown-ref-checker
6123 markdown-unused-refs
6124 "Show all unused Markdown references in current `markdown-mode' buffer."
6125 markdown-get-unused-refs
6126 markdown-unused-references-buffer
6127 "No unused references found"
6128 "The following references are unused:\n\n"
6129 markdown-insert-unused-reference-button)
6133 ;;; Lists =====================================================================
6135 (defun markdown-insert-list-item (&optional arg)
6136 "Insert a new list item.
6137 If the point is inside unordered list, insert a bullet mark. If
6138 the point is inside ordered list, insert the next number followed
6139 by a period. Use the previous list item to determine the amount
6140 of whitespace to place before and after list markers.
6142 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
6143 decrease the indentation by one level.
6145 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
6146 increase the indentation by one level."
6147 (interactive "p")
6148 (let (bounds cur-indent marker indent new-indent new-loc)
6149 (save-match-data
6150 ;; Look for a list item on current or previous non-blank line
6151 (save-excursion
6152 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
6153 (not (bobp))
6154 (markdown-cur-line-blank-p))
6155 (forward-line -1)))
6156 (when bounds
6157 (cond ((save-excursion
6158 (skip-chars-backward " \t")
6159 (looking-at-p markdown-regex-list))
6160 (beginning-of-line)
6161 (insert "\n")
6162 (forward-line -1))
6163 ((not (markdown-cur-line-blank-p))
6164 (newline)))
6165 (setq new-loc (point)))
6166 ;; Look ahead for a list item on next non-blank line
6167 (unless bounds
6168 (save-excursion
6169 (while (and (null bounds)
6170 (not (eobp))
6171 (markdown-cur-line-blank-p))
6172 (forward-line)
6173 (setq bounds (markdown-cur-list-item-bounds))))
6174 (when bounds
6175 (setq new-loc (point))
6176 (unless (markdown-cur-line-blank-p)
6177 (newline))))
6178 (if (not bounds)
6179 ;; When not in a list, start a new unordered one
6180 (progn
6181 (unless (markdown-cur-line-blank-p)
6182 (insert "\n"))
6183 (insert markdown-unordered-list-item-prefix))
6184 ;; Compute indentation and marker for new list item
6185 (setq cur-indent (nth 2 bounds))
6186 (setq marker (nth 4 bounds))
6187 ;; If current item is a GFM checkbox, insert new unchecked checkbox.
6188 (when (nth 5 bounds)
6189 (setq marker
6190 (concat marker
6191 (replace-regexp-in-string "[Xx]" " " (nth 5 bounds)))))
6192 (cond
6193 ;; Dedent: decrement indentation, find previous marker.
6194 ((= arg 4)
6195 (setq indent (max (- cur-indent markdown-list-indent-width) 0))
6196 (let ((prev-bounds
6197 (save-excursion
6198 (goto-char (nth 0 bounds))
6199 (when (markdown-up-list)
6200 (markdown-cur-list-item-bounds)))))
6201 (when prev-bounds
6202 (setq marker (nth 4 prev-bounds)))))
6203 ;; Indent: increment indentation by 4, use same marker.
6204 ((= arg 16) (setq indent (+ cur-indent markdown-list-indent-width)))
6205 ;; Same level: keep current indentation and marker.
6206 (t (setq indent cur-indent)))
6207 (setq new-indent (make-string indent 32))
6208 (goto-char new-loc)
6209 (cond
6210 ;; Ordered list
6211 ((string-match-p "[0-9]" marker)
6212 (if (= arg 16) ;; starting a new column indented one more level
6213 (insert (concat new-indent "1. "))
6214 ;; Don't use previous match-data
6215 (set-match-data nil)
6216 ;; travel up to the last item and pick the correct number. If
6217 ;; the argument was nil, "new-indent = cur-indent" is the same,
6218 ;; so we don't need special treatment. Neat.
6219 (save-excursion
6220 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
6221 (>= (forward-line -1) 0))))
6222 (let* ((old-prefix (match-string 1))
6223 (old-spacing (match-string 2))
6224 (new-prefix (if (and old-prefix markdown-ordered-list-enumeration)
6225 (int-to-string (1+ (string-to-number old-prefix)))
6226 "1"))
6227 (space-adjust (- (length old-prefix) (length new-prefix)))
6228 (new-spacing (if (and (match-string 2)
6229 (not (string-match-p "\t" old-spacing))
6230 (< space-adjust 0)
6231 (> space-adjust (- 1 (length (match-string 2)))))
6232 (substring (match-string 2) 0 space-adjust)
6233 (or old-spacing ". "))))
6234 (insert (concat new-indent new-prefix new-spacing)))))
6235 ;; Unordered list, GFM task list, or ordered list with hash mark
6236 ((string-match-p "[\\*\\+-]\\|#\\." marker)
6237 (insert new-indent marker))))
6238 ;; Propertize the newly inserted list item now
6239 (markdown-syntax-propertize-list-items (point-at-bol) (point-at-eol)))))
6241 (defun markdown-move-list-item-up ()
6242 "Move the current list item up in the list when possible.
6243 In nested lists, move child items with the parent item."
6244 (interactive)
6245 (let (cur prev old)
6246 (when (setq cur (markdown-cur-list-item-bounds))
6247 (setq old (point))
6248 (goto-char (nth 0 cur))
6249 (if (markdown-prev-list-item (nth 3 cur))
6250 (progn
6251 (setq prev (markdown-cur-list-item-bounds))
6252 (condition-case nil
6253 (progn
6254 (transpose-regions (nth 0 prev) (nth 1 prev)
6255 (nth 0 cur) (nth 1 cur) t)
6256 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
6257 ;; Catch error in case regions overlap.
6258 (error (goto-char old))))
6259 (goto-char old)))))
6261 (defun markdown-move-list-item-down ()
6262 "Move the current list item down in the list when possible.
6263 In nested lists, move child items with the parent item."
6264 (interactive)
6265 (let (cur next old)
6266 (when (setq cur (markdown-cur-list-item-bounds))
6267 (setq old (point))
6268 (if (markdown-next-list-item (nth 3 cur))
6269 (progn
6270 (setq next (markdown-cur-list-item-bounds))
6271 (condition-case nil
6272 (progn
6273 (transpose-regions (nth 0 cur) (nth 1 cur)
6274 (nth 0 next) (nth 1 next) nil)
6275 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
6276 ;; Catch error in case regions overlap.
6277 (error (goto-char old))))
6278 (goto-char old)))))
6280 (defun markdown-demote-list-item (&optional bounds)
6281 "Indent (or demote) the current list item.
6282 Optionally, BOUNDS of the current list item may be provided if available.
6283 In nested lists, demote child items as well."
6284 (interactive)
6285 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6286 (save-excursion
6287 (let* ((item-start (set-marker (make-marker) (nth 0 bounds)))
6288 (item-end (set-marker (make-marker) (nth 1 bounds)))
6289 (list-start (progn (markdown-beginning-of-list)
6290 (set-marker (make-marker) (point))))
6291 (list-end (progn (markdown-end-of-list)
6292 (set-marker (make-marker) (point)))))
6293 (goto-char item-start)
6294 (while (< (point) item-end)
6295 (unless (markdown-cur-line-blank-p)
6296 (insert (make-string markdown-list-indent-width ? )))
6297 (forward-line))
6298 (markdown-syntax-propertize-list-items list-start list-end)))))
6300 (defun markdown-promote-list-item (&optional bounds)
6301 "Unindent (or promote) the current list item.
6302 Optionally, BOUNDS of the current list item may be provided if available.
6303 In nested lists, demote child items as well."
6304 (interactive)
6305 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6306 (save-excursion
6307 (save-match-data
6308 (let ((item-start (set-marker (make-marker) (nth 0 bounds)))
6309 (item-end (set-marker (make-marker) (nth 1 bounds)))
6310 (list-start (progn (markdown-beginning-of-list)
6311 (set-marker (make-marker) (point))))
6312 (list-end (progn (markdown-end-of-list)
6313 (set-marker (make-marker) (point))))
6314 num regexp)
6315 (goto-char item-start)
6316 (when (looking-at (format "^[ ]\\{1,%d\\}"
6317 markdown-list-indent-width))
6318 (setq num (- (match-end 0) (match-beginning 0)))
6319 (setq regexp (format "^[ ]\\{1,%d\\}" num))
6320 (while (and (< (point) item-end)
6321 (re-search-forward regexp item-end t))
6322 (replace-match "" nil nil)
6323 (forward-line))
6324 (markdown-syntax-propertize-list-items list-start list-end)))))))
6326 (defun markdown-cleanup-list-numbers-level (&optional pfx prev-item)
6327 "Update the numbering for level PFX (as a string of spaces) and PREV-ITEM.
6328 PREV-ITEM is width of previous-indentation and list number
6330 Assume that the previously found match was for a numbered item in
6331 a list."
6332 (let ((cpfx pfx)
6333 (cur-item nil)
6334 (idx 0)
6335 (continue t)
6336 (step t)
6337 (sep nil))
6338 (while (and continue (not (eobp)))
6339 (setq step t)
6340 (cond
6341 ((looking-at "^\\(\\([\s-]*\\)[0-9]+\\)\\. ")
6342 (setq cpfx (match-string-no-properties 2))
6343 (setq cur-item (match-string-no-properties 1)) ;; indentation and list marker
6344 (cond
6345 ((or (= (length cpfx) (length pfx))
6346 (= (length cur-item) (length prev-item)))
6347 (save-excursion
6348 (replace-match
6349 (if (not markdown-ordered-list-enumeration)
6350 (concat pfx "1. ")
6351 (cl-incf idx)
6352 (concat pfx (number-to-string idx) ". "))))
6353 (setq sep nil))
6354 ;; indented a level
6355 ((< (length pfx) (length cpfx))
6356 (setq sep (markdown-cleanup-list-numbers-level cpfx cur-item))
6357 (setq step nil))
6358 ;; exit the loop
6360 (setq step nil)
6361 (setq continue nil))))
6363 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
6364 (setq cpfx (match-string-no-properties 1))
6365 (cond
6366 ;; reset if separated before
6367 ((string= cpfx pfx) (when sep (setq idx 0)))
6368 ((string< cpfx pfx)
6369 (setq step nil)
6370 (setq continue nil))))
6371 (t (setq sep t)))
6373 (when step
6374 (beginning-of-line)
6375 (setq continue (= (forward-line) 0))))
6376 sep))
6378 (defun markdown-cleanup-list-numbers ()
6379 "Update the numbering of ordered lists."
6380 (interactive)
6381 (save-excursion
6382 (goto-char (point-min))
6383 (markdown-cleanup-list-numbers-level "")))
6386 ;;; Movement ==================================================================
6388 (defun markdown-beginning-of-defun (&optional arg)
6389 "`beginning-of-defun-function' for Markdown.
6390 This is used to find the beginning of the defun and should behave
6391 like ‘beginning-of-defun’, returning non-nil if it found the
6392 beginning of a defun. It moves the point backward, right before a
6393 heading which defines a defun. When ARG is non-nil, repeat that
6394 many times. When ARG is negative, move forward to the ARG-th
6395 following section."
6396 (or arg (setq arg 1))
6397 (when (< arg 0) (end-of-line))
6398 ;; Adjust position for setext headings.
6399 (when (and (thing-at-point-looking-at markdown-regex-header-setext)
6400 (not (= (point) (match-beginning 0)))
6401 (not (markdown-code-block-at-point-p)))
6402 (goto-char (match-end 0)))
6403 (let (found)
6404 ;; Move backward with positive argument.
6405 (while (and (not (bobp)) (> arg 0))
6406 (setq found nil)
6407 (while (and (not found)
6408 (not (bobp))
6409 (re-search-backward markdown-regex-header nil 'move))
6410 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6411 (setq found (match-beginning 0)))
6412 (setq arg (1- arg)))
6413 ;; Move forward with negative argument.
6414 (while (and (not (eobp)) (< arg 0))
6415 (setq found nil)
6416 (while (and (not found)
6417 (not (eobp))
6418 (re-search-forward markdown-regex-header nil 'move))
6419 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6420 (setq found (match-beginning 0)))
6421 (setq arg (1+ arg)))
6422 (when found
6423 (beginning-of-line)
6424 t)))
6426 (defun markdown-end-of-defun ()
6427 "`end-of-defun-function’ for Markdown.
6428 This is used to find the end of the defun at point.
6429 It is called with no argument, right after calling ‘beginning-of-defun-raw’,
6430 so it can assume that point is at the beginning of the defun body.
6431 It should move point to the first position after the defun."
6432 (or (eobp) (forward-char 1))
6433 (let (found)
6434 (while (and (not found)
6435 (not (eobp))
6436 (re-search-forward markdown-regex-header nil 'move))
6437 (when (not (markdown-code-block-at-pos (match-beginning 0)))
6438 (setq found (match-beginning 0))))
6439 (when found
6440 (goto-char found)
6441 (skip-syntax-backward "-"))))
6443 (defun markdown-beginning-of-text-block ()
6444 "Move backward to previous beginning of a plain text block.
6445 This function simply looks for blank lines without considering
6446 the surrounding context in light of Markdown syntax. For that, see
6447 `markdown-backward-block'."
6448 (interactive)
6449 (let ((start (point)))
6450 (if (re-search-backward markdown-regex-block-separator nil t)
6451 (goto-char (match-end 0))
6452 (goto-char (point-min)))
6453 (when (and (= start (point)) (not (bobp)))
6454 (forward-line -1)
6455 (if (re-search-backward markdown-regex-block-separator nil t)
6456 (goto-char (match-end 0))
6457 (goto-char (point-min))))))
6459 (defun markdown-end-of-text-block ()
6460 "Move forward to next beginning of a plain text block.
6461 This function simply looks for blank lines without considering
6462 the surrounding context in light of Markdown syntax. For that, see
6463 `markdown-forward-block'."
6464 (interactive)
6465 (beginning-of-line)
6466 (skip-chars-forward " \t\n")
6467 (when (= (point) (point-min))
6468 (forward-char))
6469 (if (re-search-forward markdown-regex-block-separator nil t)
6470 (goto-char (match-end 0))
6471 (goto-char (point-max)))
6472 (skip-chars-backward " \t\n")
6473 (forward-line))
6475 (defun markdown-backward-paragraph (&optional arg)
6476 "Move the point to the start of the current paragraph.
6477 With argument ARG, do it ARG times; a negative argument ARG = -N
6478 means move forward N blocks."
6479 (interactive "^p")
6480 (or arg (setq arg 1))
6481 (if (< arg 0)
6482 (markdown-forward-paragraph (- arg))
6483 (dotimes (_ arg)
6484 ;; Skip over whitespace in between paragraphs when moving backward.
6485 (skip-chars-backward " \t\n")
6486 (beginning-of-line)
6487 ;; Skip over code block endings.
6488 (when (markdown-range-properties-exist
6489 (point-at-bol) (point-at-eol)
6490 '(markdown-gfm-block-end
6491 markdown-tilde-fence-end))
6492 (forward-line -1))
6493 ;; Skip over blank lines inside blockquotes.
6494 (while (and (not (eobp))
6495 (looking-at markdown-regex-blockquote)
6496 (= (length (match-string 3)) 0))
6497 (forward-line -1))
6498 ;; Proceed forward based on the type of block of paragraph.
6499 (let (bounds skip)
6500 (cond
6501 ;; Blockquotes
6502 ((looking-at markdown-regex-blockquote)
6503 (while (and (not (bobp))
6504 (looking-at markdown-regex-blockquote)
6505 (> (length (match-string 3)) 0)) ;; not blank
6506 (forward-line -1))
6507 (forward-line))
6508 ;; List items
6509 ((setq bounds (markdown-cur-list-item-bounds))
6510 (goto-char (nth 0 bounds)))
6511 ;; Other
6513 (while (and (not (bobp))
6514 (not skip)
6515 (not (markdown-cur-line-blank-p))
6516 (not (looking-at markdown-regex-blockquote))
6517 (not (markdown-range-properties-exist
6518 (point-at-bol) (point-at-eol)
6519 '(markdown-gfm-block-end
6520 markdown-tilde-fence-end))))
6521 (setq skip (markdown-range-properties-exist
6522 (point-at-bol) (point-at-eol)
6523 '(markdown-gfm-block-begin
6524 markdown-tilde-fence-begin)))
6525 (forward-line -1))
6526 (unless (bobp)
6527 (forward-line 1))))))))
6529 (defun markdown-forward-paragraph (&optional arg)
6530 "Move forward to the next end of a paragraph.
6531 With argument ARG, do it ARG times; a negative argument ARG = -N
6532 means move backward N blocks."
6533 (interactive "^p")
6534 (or arg (setq arg 1))
6535 (if (< arg 0)
6536 (markdown-backward-paragraph (- arg))
6537 (dotimes (_ arg)
6538 ;; Skip whitespace in between paragraphs.
6539 (when (markdown-cur-line-blank-p)
6540 (skip-syntax-forward "-")
6541 (beginning-of-line))
6542 ;; Proceed forward based on the type of block.
6543 (let (bounds skip)
6544 (cond
6545 ;; Blockquotes
6546 ((looking-at markdown-regex-blockquote)
6547 ;; Skip over blank lines inside blockquotes.
6548 (while (and (not (eobp))
6549 (looking-at markdown-regex-blockquote)
6550 (= (length (match-string 3)) 0))
6551 (forward-line))
6552 ;; Move to end of quoted text block
6553 (while (and (not (eobp))
6554 (looking-at markdown-regex-blockquote)
6555 (> (length (match-string 3)) 0)) ;; not blank
6556 (forward-line)))
6557 ;; List items
6558 ((and (markdown-cur-list-item-bounds)
6559 (setq bounds (markdown-next-list-item-bounds)))
6560 (goto-char (nth 0 bounds)))
6561 ;; Other
6563 (forward-line)
6564 (while (and (not (eobp))
6565 (not skip)
6566 (not (markdown-cur-line-blank-p))
6567 (not (looking-at markdown-regex-blockquote))
6568 (not (markdown-range-properties-exist
6569 (point-at-bol) (point-at-eol)
6570 '(markdown-gfm-block-begin
6571 markdown-tilde-fence-begin))))
6572 (setq skip (markdown-range-properties-exist
6573 (point-at-bol) (point-at-eol)
6574 '(markdown-gfm-block-end
6575 markdown-tilde-fence-end)))
6576 (forward-line))))))))
6578 (defun markdown-backward-block (&optional arg)
6579 "Move the point to the start of the current Markdown block.
6580 Moves across complete code blocks, list items, and blockquotes,
6581 but otherwise stops at blank lines, headers, and horizontal
6582 rules. With argument ARG, do it ARG times; a negative argument
6583 ARG = -N means move forward N blocks."
6584 (interactive "^p")
6585 (or arg (setq arg 1))
6586 (if (< arg 0)
6587 (markdown-forward-block (- arg))
6588 (dotimes (_ arg)
6589 ;; Skip over whitespace in between blocks when moving backward,
6590 ;; unless at a block boundary with no whitespace.
6591 (skip-syntax-backward "-")
6592 (beginning-of-line)
6593 ;; Proceed forward based on the type of block.
6594 (cond
6595 ;; Code blocks
6596 ((and (markdown-code-block-at-pos (point)) ;; this line
6597 (markdown-code-block-at-pos (point-at-bol 0))) ;; previous line
6598 (forward-line -1)
6599 (while (and (markdown-code-block-at-point-p) (not (bobp)))
6600 (forward-line -1))
6601 (forward-line))
6602 ;; Headings
6603 ((markdown-heading-at-point)
6604 (goto-char (match-beginning 0)))
6605 ;; Horizontal rules
6606 ((looking-at markdown-regex-hr))
6607 ;; Blockquotes
6608 ((looking-at markdown-regex-blockquote)
6609 (forward-line -1)
6610 (while (and (looking-at markdown-regex-blockquote)
6611 (not (bobp)))
6612 (forward-line -1))
6613 (forward-line))
6614 ;; List items
6615 ((markdown-cur-list-item-bounds)
6616 (markdown-beginning-of-list))
6617 ;; Other
6619 ;; Move forward in case it is a one line regular paragraph.
6620 (unless (markdown-next-line-blank-p)
6621 (forward-line))
6622 (unless (markdown-prev-line-blank-p)
6623 (markdown-backward-paragraph)))))))
6625 (defun markdown-forward-block (&optional arg)
6626 "Move forward to the next end of a Markdown block.
6627 Moves across complete code blocks, list items, and blockquotes,
6628 but otherwise stops at blank lines, headers, and horizontal
6629 rules. With argument ARG, do it ARG times; a negative argument
6630 ARG = -N means move backward N blocks."
6631 (interactive "^p")
6632 (or arg (setq arg 1))
6633 (if (< arg 0)
6634 (markdown-backward-block (- arg))
6635 (dotimes (_ arg)
6636 ;; Skip over whitespace in between blocks when moving forward.
6637 (if (markdown-cur-line-blank-p)
6638 (skip-syntax-forward "-")
6639 (beginning-of-line))
6640 ;; Proceed forward based on the type of block.
6641 (cond
6642 ;; Code blocks
6643 ((markdown-code-block-at-point-p)
6644 (forward-line)
6645 (while (and (markdown-code-block-at-point-p) (not (eobp)))
6646 (forward-line)))
6647 ;; Headings
6648 ((looking-at markdown-regex-header)
6649 (goto-char (or (match-end 4) (match-end 2) (match-end 3)))
6650 (forward-line))
6651 ;; Horizontal rules
6652 ((looking-at markdown-regex-hr)
6653 (forward-line))
6654 ;; Blockquotes
6655 ((looking-at markdown-regex-blockquote)
6656 (forward-line)
6657 (while (and (looking-at markdown-regex-blockquote) (not (eobp)))
6658 (forward-line)))
6659 ;; List items
6660 ((markdown-cur-list-item-bounds)
6661 (markdown-end-of-list)
6662 (forward-line))
6663 ;; Other
6664 (t (markdown-forward-paragraph))))
6665 (skip-syntax-backward "-")
6666 (unless (eobp)
6667 (forward-char 1))))
6669 (defun markdown-backward-page (&optional count)
6670 "Move backward to boundary of the current toplevel section.
6671 With COUNT, repeat, or go forward if negative."
6672 (interactive "p")
6673 (or count (setq count 1))
6674 (if (< count 0)
6675 (markdown-forward-page (- count))
6676 (skip-syntax-backward "-")
6677 (or (markdown-back-to-heading-over-code-block t t)
6678 (goto-char (point-min)))
6679 (when (looking-at markdown-regex-header)
6680 (let ((level (markdown-outline-level)))
6681 (when (> level 1) (markdown-up-heading level))
6682 (when (> count 1)
6683 (condition-case nil
6684 (markdown-backward-same-level (1- count))
6685 (error (goto-char (point-min)))))))))
6687 (defun markdown-forward-page (&optional count)
6688 "Move forward to boundary of the current toplevel section.
6689 With COUNT, repeat, or go backward if negative."
6690 (interactive "p")
6691 (or count (setq count 1))
6692 (if (< count 0)
6693 (markdown-backward-page (- count))
6694 (if (markdown-back-to-heading-over-code-block t t)
6695 (let ((level (markdown-outline-level)))
6696 (when (> level 1) (markdown-up-heading level))
6697 (condition-case nil
6698 (markdown-forward-same-level count)
6699 (error (goto-char (point-max)))))
6700 (markdown-next-visible-heading 1))))
6702 (defun markdown-next-link ()
6703 "Jump to next inline, reference, or wiki link.
6704 If successful, return point. Otherwise, return nil.
6705 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
6706 (interactive)
6707 (let ((opoint (point)))
6708 (when (or (markdown-link-p) (markdown-wiki-link-p))
6709 ;; At a link already, move past it.
6710 (goto-char (+ (match-end 0) 1)))
6711 ;; Search for the next wiki link and move to the beginning.
6712 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t)
6713 (markdown-code-block-at-point-p)
6714 (< (point) (point-max))))
6715 (if (and (not (eq (point) opoint))
6716 (or (markdown-link-p) (markdown-wiki-link-p)))
6717 ;; Group 1 will move past non-escape character in wiki link regexp.
6718 ;; Go to beginning of group zero for all other link types.
6719 (goto-char (or (match-beginning 1) (match-beginning 0)))
6720 (goto-char opoint)
6721 nil)))
6723 (defun markdown-previous-link ()
6724 "Jump to previous wiki link.
6725 If successful, return point. Otherwise, return nil.
6726 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
6727 (interactive)
6728 (let ((opoint (point)))
6729 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t)
6730 (markdown-code-block-at-point-p)
6731 (> (point) (point-min))))
6732 (if (and (not (eq (point) opoint))
6733 (or (markdown-link-p) (markdown-wiki-link-p)))
6734 (goto-char (or (match-beginning 1) (match-beginning 0)))
6735 (goto-char opoint)
6736 nil)))
6739 ;;; Outline ===================================================================
6741 (defun markdown-move-heading-common (move-fn &optional arg adjust)
6742 "Wrapper for `outline-mode' functions to skip false positives.
6743 MOVE-FN is a function and ARG is its argument. For example,
6744 headings inside preformatted code blocks may match
6745 `outline-regexp' but should not be considered as headings.
6746 When ADJUST is non-nil, adjust the point for interactive calls
6747 to avoid leaving the point at invisible markup. This adjustment
6748 generally should only be done for interactive calls, since other
6749 functions may expect the point to be at the beginning of the
6750 regular expression."
6751 (let ((prev -1) (start (point)))
6752 (if arg (funcall move-fn arg) (funcall move-fn))
6753 (while (and (/= prev (point)) (markdown-code-block-at-point-p))
6754 (setq prev (point))
6755 (if arg (funcall move-fn arg) (funcall move-fn)))
6756 ;; Adjust point for setext headings and invisible text.
6757 (save-match-data
6758 (when (and adjust (thing-at-point-looking-at markdown-regex-header))
6759 (if markdown-hide-markup
6760 ;; Move to beginning of heading text if markup is hidden.
6761 (goto-char (or (match-beginning 1) (match-beginning 5)))
6762 ;; Move to beginning of markup otherwise.
6763 (goto-char (or (match-beginning 1) (match-beginning 4))))))
6764 (if (= (point) start) nil (point))))
6766 (defun markdown-next-visible-heading (arg)
6767 "Move to the next visible heading line of any level.
6768 With argument, repeats or can move backward if negative. ARG is
6769 passed to `outline-next-visible-heading'."
6770 (interactive "p")
6771 (markdown-move-heading-common #'outline-next-visible-heading arg 'adjust))
6773 (defun markdown-previous-visible-heading (arg)
6774 "Move to the previous visible heading line of any level.
6775 With argument, repeats or can move backward if negative. ARG is
6776 passed to `outline-previous-visible-heading'."
6777 (interactive "p")
6778 (markdown-move-heading-common #'outline-previous-visible-heading arg 'adjust))
6780 (defun markdown-next-heading ()
6781 "Move to the next heading line of any level."
6782 (markdown-move-heading-common #'outline-next-heading))
6784 (defun markdown-previous-heading ()
6785 "Move to the previous heading line of any level."
6786 (markdown-move-heading-common #'outline-previous-heading))
6788 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok no-error)
6789 "Move back to the beginning of the previous heading.
6790 Returns t if the point is at a heading, the location if a heading
6791 was found, and nil otherwise.
6792 Only visible heading lines are considered, unless INVISIBLE-OK is
6793 non-nil. Throw an error if there is no previous heading unless
6794 NO-ERROR is non-nil.
6795 Leaves match data intact for `markdown-regex-header'."
6796 (beginning-of-line)
6797 (or (and (markdown-heading-at-point)
6798 (not (markdown-code-block-at-point-p)))
6799 (let (found)
6800 (save-excursion
6801 (while (and (not found)
6802 (re-search-backward markdown-regex-header nil t))
6803 (when (and (or invisible-ok (not (outline-invisible-p)))
6804 (not (markdown-code-block-at-point-p)))
6805 (setq found (point))))
6806 (if (not found)
6807 (unless no-error (user-error "Before first heading"))
6808 (setq found (point))))
6809 (when found (goto-char found)))))
6811 (defun markdown-forward-same-level (arg)
6812 "Move forward to the ARG'th heading at same level as this one.
6813 Stop at the first and last headings of a superior heading."
6814 (interactive "p")
6815 (markdown-back-to-heading-over-code-block)
6816 (markdown-move-heading-common #'outline-forward-same-level arg 'adjust))
6818 (defun markdown-backward-same-level (arg)
6819 "Move backward to the ARG'th heading at same level as this one.
6820 Stop at the first and last headings of a superior heading."
6821 (interactive "p")
6822 (markdown-back-to-heading-over-code-block)
6823 (while (> arg 0)
6824 (let ((point-to-move-to
6825 (save-excursion
6826 (markdown-move-heading-common #'outline-get-last-sibling nil 'adjust))))
6827 (if point-to-move-to
6828 (progn
6829 (goto-char point-to-move-to)
6830 (setq arg (1- arg)))
6831 (user-error "No previous same-level heading")))))
6833 (defun markdown-up-heading (arg &optional interactive)
6834 "Move to the visible heading line of which the present line is a subheading.
6835 With argument, move up ARG levels. When called interactively (or
6836 INTERACTIVE is non-nil), also push the mark."
6837 (interactive "p\np")
6838 (and interactive (not (eq last-command 'markdown-up-heading))
6839 (push-mark))
6840 (markdown-move-heading-common #'outline-up-heading arg 'adjust))
6842 (defun markdown-back-to-heading (&optional invisible-ok)
6843 "Move to previous heading line, or beg of this line if it's a heading.
6844 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
6845 (interactive)
6846 (markdown-move-heading-common #'outline-back-to-heading invisible-ok))
6848 (defalias 'markdown-end-of-heading 'outline-end-of-heading)
6850 (defun markdown-on-heading-p ()
6851 "Return non-nil if point is on a heading line."
6852 (get-text-property (point-at-bol) 'markdown-heading))
6854 (defun markdown-end-of-subtree (&optional invisible-OK)
6855 "Move to the end of the current subtree.
6856 Only visible heading lines are considered, unless INVISIBLE-OK is
6857 non-nil.
6858 Derived from `org-end-of-subtree'."
6859 (markdown-back-to-heading invisible-OK)
6860 (let ((first t)
6861 (level (markdown-outline-level)))
6862 (while (and (not (eobp))
6863 (or first (> (markdown-outline-level) level)))
6864 (setq first nil)
6865 (markdown-next-heading))
6866 (if (memq (preceding-char) '(?\n ?\^M))
6867 (progn
6868 ;; Go to end of line before heading
6869 (forward-char -1)
6870 (if (memq (preceding-char) '(?\n ?\^M))
6871 ;; leave blank line before heading
6872 (forward-char -1)))))
6873 (point))
6875 (defun markdown-outline-fix-visibility ()
6876 "Hide any false positive headings that should not be shown.
6877 For example, headings inside preformatted code blocks may match
6878 `outline-regexp' but should not be shown as headings when cycling.
6879 Also, the ending --- line in metadata blocks appears to be a
6880 setext header, but should not be folded."
6881 (save-excursion
6882 (goto-char (point-min))
6883 ;; Unhide any false positives in metadata blocks
6884 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin)
6885 (let ((body (progn (forward-line)
6886 (markdown-text-property-at-point
6887 'markdown-yaml-metadata-section))))
6888 (when body
6889 (let ((end (progn (goto-char (cl-second body))
6890 (markdown-text-property-at-point
6891 'markdown-yaml-metadata-end))))
6892 (outline-flag-region (point-min) (1+ (cl-second end)) nil)))))
6893 ;; Hide any false positives in code blocks
6894 (unless (outline-on-heading-p)
6895 (outline-next-visible-heading 1))
6896 (while (< (point) (point-max))
6897 (when (markdown-code-block-at-point-p)
6898 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t))
6899 (outline-next-visible-heading 1))))
6901 (defvar markdown-cycle-global-status 1)
6902 (defvar markdown-cycle-subtree-status nil)
6904 (defun markdown-next-preface ()
6905 (let (finish)
6906 (while (and (not finish) (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
6907 nil 'move))
6908 (unless (markdown-code-block-at-point-p)
6909 (goto-char (match-beginning 0))
6910 (setq finish t))))
6911 (when (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
6912 (forward-char -1)))
6914 (defun markdown-show-entry ()
6915 (save-excursion
6916 (outline-back-to-heading t)
6917 (outline-flag-region (1- (point))
6918 (progn
6919 (markdown-next-preface)
6920 (if (= 1 (- (point-max) (point)))
6921 (point-max)
6922 (point)))
6923 nil)))
6925 ;; This function was originally derived from `org-cycle' from org.el.
6926 (defun markdown-cycle (&optional arg)
6927 "Visibility cycling for Markdown mode.
6928 This function is called with a `\\[universal-argument]' or if ARG is t, perform
6929 global visibility cycling. If the point is at an atx-style header, cycle
6930 visibility of the corresponding subtree. Otherwise, indent the current line
6931 or insert a tab, as appropriate, by calling `indent-for-tab-command'."
6932 (interactive "P")
6933 (cond
6935 ;; Global cycling
6936 (arg
6937 (cond
6938 ;; Move from overview to contents
6939 ((and (eq last-command this-command)
6940 (eq markdown-cycle-global-status 2))
6941 (outline-hide-sublevels 1)
6942 (message "CONTENTS")
6943 (setq markdown-cycle-global-status 3)
6944 (markdown-outline-fix-visibility))
6945 ;; Move from contents to all
6946 ((and (eq last-command this-command)
6947 (eq markdown-cycle-global-status 3))
6948 (outline-show-all)
6949 (message "SHOW ALL")
6950 (setq markdown-cycle-global-status 1))
6951 ;; Defaults to overview
6953 (outline-hide-body)
6954 (message "OVERVIEW")
6955 (setq markdown-cycle-global-status 2)
6956 (markdown-outline-fix-visibility))))
6958 ;; At a heading: rotate between three different views
6959 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
6960 (markdown-back-to-heading)
6961 (let ((goal-column 0) eoh eol eos)
6962 ;; Determine boundaries
6963 (save-excursion
6964 (markdown-back-to-heading)
6965 (save-excursion
6966 (beginning-of-line 2)
6967 (while (and (not (eobp)) ;; this is like `next-line'
6968 (get-char-property (1- (point)) 'invisible))
6969 (beginning-of-line 2)) (setq eol (point)))
6970 (markdown-end-of-heading) (setq eoh (point))
6971 (markdown-end-of-subtree t)
6972 (skip-chars-forward " \t\n")
6973 (beginning-of-line 1) ; in case this is an item
6974 (setq eos (1- (point))))
6975 ;; Find out what to do next and set `this-command'
6976 (cond
6977 ;; Nothing is hidden behind this heading
6978 ((= eos eoh)
6979 (message "EMPTY ENTRY")
6980 (setq markdown-cycle-subtree-status nil))
6981 ;; Entire subtree is hidden in one line: open it
6982 ((>= eol eos)
6983 (markdown-show-entry)
6984 (outline-show-children)
6985 (message "CHILDREN")
6986 (setq markdown-cycle-subtree-status 'children))
6987 ;; We just showed the children, now show everything.
6988 ((and (eq last-command this-command)
6989 (eq markdown-cycle-subtree-status 'children))
6990 (outline-show-subtree)
6991 (message "SUBTREE")
6992 (setq markdown-cycle-subtree-status 'subtree))
6993 ;; Default action: hide the subtree.
6995 (outline-hide-subtree)
6996 (message "FOLDED")
6997 (setq markdown-cycle-subtree-status 'folded)))))
6999 ;; In a table, move forward by one cell
7000 ((markdown-table-at-point-p)
7001 (call-interactively #'markdown-table-forward-cell))
7003 ;; Otherwise, indent as appropriate
7005 (indent-for-tab-command))))
7007 (defun markdown-shifttab ()
7008 "Handle S-TAB keybinding based on context.
7009 When in a table, move backward one cell.
7010 Otherwise, cycle global heading visibility by calling
7011 `markdown-cycle' with argument t."
7012 (interactive)
7013 (cond ((markdown-table-at-point-p)
7014 (call-interactively #'markdown-table-backward-cell))
7015 (t (markdown-cycle t))))
7017 (defun markdown-outline-level ()
7018 "Return the depth to which a statement is nested in the outline."
7019 (cond
7020 ((and (match-beginning 0)
7021 (markdown-code-block-at-pos (match-beginning 0)))
7022 7) ;; Only 6 header levels are defined.
7023 ((match-end 2) 1)
7024 ((match-end 3) 2)
7025 ((match-end 4)
7026 (length (markdown-trim-whitespace (match-string-no-properties 4))))))
7028 (defun markdown-promote-subtree (&optional arg)
7029 "Promote the current subtree of ATX headings.
7030 Note that Markdown does not support heading levels higher than
7031 six and therefore level-six headings will not be promoted
7032 further. If ARG is non-nil promote the heading, otherwise
7033 demote."
7034 (interactive "*P")
7035 (save-excursion
7036 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
7037 (re-search-backward markdown-regex-header-atx nil t))
7038 (not (markdown-code-block-at-point-p)))
7039 (let ((level (length (match-string 1)))
7040 (promote-or-demote (if arg 1 -1))
7041 (remove 't))
7042 (markdown-cycle-atx promote-or-demote remove)
7043 (catch 'end-of-subtree
7044 (while (and (markdown-next-heading)
7045 (looking-at markdown-regex-header-atx))
7046 ;; Exit if this not a higher level heading; promote otherwise.
7047 (if (and (looking-at markdown-regex-header-atx)
7048 (<= (length (match-string-no-properties 1)) level))
7049 (throw 'end-of-subtree nil)
7050 (markdown-cycle-atx promote-or-demote remove))))))))
7052 (defun markdown-demote-subtree ()
7053 "Demote the current subtree of ATX headings."
7054 (interactive)
7055 (markdown-promote-subtree t))
7057 (defun markdown-move-subtree-up ()
7058 "Move the current subtree of ATX headings up."
7059 (interactive)
7060 (outline-move-subtree-up 1))
7062 (defun markdown-move-subtree-down ()
7063 "Move the current subtree of ATX headings down."
7064 (interactive)
7065 (outline-move-subtree-down 1))
7067 (defun markdown-outline-next ()
7068 "Move to next list item, when in a list, or next visible heading."
7069 (interactive)
7070 (let ((bounds (markdown-next-list-item-bounds)))
7071 (if bounds
7072 (goto-char (nth 0 bounds))
7073 (markdown-next-visible-heading 1))))
7075 (defun markdown-outline-previous ()
7076 "Move to previous list item, when in a list, or previous visible heading."
7077 (interactive)
7078 (let ((bounds (markdown-prev-list-item-bounds)))
7079 (if bounds
7080 (goto-char (nth 0 bounds))
7081 (markdown-previous-visible-heading 1))))
7083 (defun markdown-outline-next-same-level ()
7084 "Move to next list item or heading of same level."
7085 (interactive)
7086 (let ((bounds (markdown-cur-list-item-bounds)))
7087 (if bounds
7088 (markdown-next-list-item (nth 3 bounds))
7089 (markdown-forward-same-level 1))))
7091 (defun markdown-outline-previous-same-level ()
7092 "Move to previous list item or heading of same level."
7093 (interactive)
7094 (let ((bounds (markdown-cur-list-item-bounds)))
7095 (if bounds
7096 (markdown-prev-list-item (nth 3 bounds))
7097 (markdown-backward-same-level 1))))
7099 (defun markdown-outline-up ()
7100 "Move to previous list item, when in a list, or previous heading."
7101 (interactive)
7102 (unless (markdown-up-list)
7103 (markdown-up-heading 1)))
7106 ;;; Marking and Narrowing =====================================================
7108 (defun markdown-mark-paragraph ()
7109 "Put mark at end of this block, point at beginning.
7110 The block marked is the one that contains point or follows point.
7112 Interactively, if this command is repeated or (in Transient Mark
7113 mode) if the mark is active, it marks the next block after the
7114 ones already marked."
7115 (interactive)
7116 (if (or (and (eq last-command this-command) (mark t))
7117 (and transient-mark-mode mark-active))
7118 (set-mark
7119 (save-excursion
7120 (goto-char (mark))
7121 (markdown-forward-paragraph)
7122 (point)))
7123 (let ((beginning-of-defun-function #'markdown-backward-paragraph)
7124 (end-of-defun-function #'markdown-forward-paragraph))
7125 (mark-defun))))
7127 (defun markdown-mark-block ()
7128 "Put mark at end of this block, point at beginning.
7129 The block marked is the one that contains point or follows point.
7131 Interactively, if this command is repeated or (in Transient Mark
7132 mode) if the mark is active, it marks the next block after the
7133 ones already marked."
7134 (interactive)
7135 (if (or (and (eq last-command this-command) (mark t))
7136 (and transient-mark-mode mark-active))
7137 (set-mark
7138 (save-excursion
7139 (goto-char (mark))
7140 (markdown-forward-block)
7141 (point)))
7142 (let ((beginning-of-defun-function #'markdown-backward-block)
7143 (end-of-defun-function #'markdown-forward-block))
7144 (mark-defun))))
7146 (defun markdown-narrow-to-block ()
7147 "Make text outside current block invisible.
7148 The current block is the one that contains point or follows point."
7149 (interactive)
7150 (let ((beginning-of-defun-function #'markdown-backward-block)
7151 (end-of-defun-function #'markdown-forward-block))
7152 (narrow-to-defun)))
7154 (defun markdown-mark-text-block ()
7155 "Put mark at end of this plain text block, point at beginning.
7156 The block marked is the one that contains point or follows point.
7158 Interactively, if this command is repeated or (in Transient Mark
7159 mode) if the mark is active, it marks the next block after the
7160 ones already marked."
7161 (interactive)
7162 (if (or (and (eq last-command this-command) (mark t))
7163 (and transient-mark-mode mark-active))
7164 (set-mark
7165 (save-excursion
7166 (goto-char (mark))
7167 (markdown-end-of-text-block)
7168 (point)))
7169 (let ((beginning-of-defun-function #'markdown-beginning-of-text-block)
7170 (end-of-defun-function #'markdown-end-of-text-block))
7171 (mark-defun))))
7173 (defun markdown-mark-page ()
7174 "Put mark at end of this top level section, point at beginning.
7175 The top level section marked is the one that contains point or
7176 follows point.
7178 Interactively, if this command is repeated or (in Transient Mark
7179 mode) if the mark is active, it marks the next page after the
7180 ones already marked."
7181 (interactive)
7182 (if (or (and (eq last-command this-command) (mark t))
7183 (and transient-mark-mode mark-active))
7184 (set-mark
7185 (save-excursion
7186 (goto-char (mark))
7187 (markdown-forward-page)
7188 (point)))
7189 (let ((beginning-of-defun-function #'markdown-backward-page)
7190 (end-of-defun-function #'markdown-forward-page))
7191 (mark-defun))))
7193 (defun markdown-narrow-to-page ()
7194 "Make text outside current top level section invisible.
7195 The current section is the one that contains point or follows point."
7196 (interactive)
7197 (let ((beginning-of-defun-function #'markdown-backward-page)
7198 (end-of-defun-function #'markdown-forward-page))
7199 (narrow-to-defun)))
7201 (defun markdown-mark-subtree ()
7202 "Mark the current subtree.
7203 This puts point at the start of the current subtree, and mark at the end."
7204 (interactive)
7205 (let ((beg))
7206 (if (markdown-heading-at-point)
7207 (beginning-of-line)
7208 (markdown-previous-visible-heading 1))
7209 (setq beg (point))
7210 (markdown-end-of-subtree)
7211 (push-mark (point) nil t)
7212 (goto-char beg)))
7214 (defun markdown-narrow-to-subtree ()
7215 "Narrow buffer to the current subtree."
7216 (interactive)
7217 (save-excursion
7218 (save-match-data
7219 (narrow-to-region
7220 (progn (markdown-back-to-heading-over-code-block t) (point))
7221 (progn (markdown-end-of-subtree)
7222 (if (and (markdown-heading-at-point) (not (eobp)))
7223 (backward-char 1))
7224 (point))))))
7227 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
7229 (defun markdown-move-up ()
7230 "Move thing at point up.
7231 When in a list item, call `markdown-move-list-item-up'.
7232 When in a table, call `markdown-table-move-row-up'.
7233 Otherwise, move the current heading subtree up with
7234 `markdown-move-subtree-up'."
7235 (interactive)
7236 (cond
7237 ((markdown-list-item-at-point-p)
7238 (call-interactively #'markdown-move-list-item-up))
7239 ((markdown-table-at-point-p)
7240 (call-interactively #'markdown-table-move-row-up))
7242 (call-interactively #'markdown-move-subtree-up))))
7244 (defun markdown-move-down ()
7245 "Move thing at point down.
7246 When in a list item, call `markdown-move-list-item-down'.
7247 Otherwise, move the current heading subtree up with
7248 `markdown-move-subtree-down'."
7249 (interactive)
7250 (cond
7251 ((markdown-list-item-at-point-p)
7252 (call-interactively #'markdown-move-list-item-down))
7253 ((markdown-table-at-point-p)
7254 (call-interactively #'markdown-table-move-row-down))
7256 (call-interactively #'markdown-move-subtree-down))))
7258 (defun markdown-promote ()
7259 "Promote or move element at point to the left.
7260 Depending on the context, this function will promote a heading or
7261 list item at the point, move a table column to the left, or cycle
7262 markup."
7263 (interactive)
7264 (let (bounds)
7265 (cond
7266 ;; Promote atx heading subtree
7267 ((thing-at-point-looking-at markdown-regex-header-atx)
7268 (markdown-promote-subtree))
7269 ;; Promote setext heading
7270 ((thing-at-point-looking-at markdown-regex-header-setext)
7271 (markdown-cycle-setext -1))
7272 ;; Promote horizontal rule
7273 ((thing-at-point-looking-at markdown-regex-hr)
7274 (markdown-cycle-hr -1))
7275 ;; Promote list item
7276 ((setq bounds (markdown-cur-list-item-bounds))
7277 (markdown-promote-list-item bounds))
7278 ;; Move table column to the left
7279 ((markdown-table-at-point-p)
7280 (call-interactively #'markdown-table-move-column-left))
7281 ;; Promote bold
7282 ((thing-at-point-looking-at markdown-regex-bold)
7283 (markdown-cycle-bold))
7284 ;; Promote italic
7285 ((thing-at-point-looking-at markdown-regex-italic)
7286 (markdown-cycle-italic))
7288 (user-error "Nothing to promote at point")))))
7290 (defun markdown-demote ()
7291 "Demote or move element at point to the right.
7292 Depending on the context, this function will demote a heading or
7293 list item at the point, move a table column to the right, or cycle
7294 or remove markup."
7295 (interactive)
7296 (let (bounds)
7297 (cond
7298 ;; Demote atx heading subtree
7299 ((thing-at-point-looking-at markdown-regex-header-atx)
7300 (markdown-demote-subtree))
7301 ;; Demote setext heading
7302 ((thing-at-point-looking-at markdown-regex-header-setext)
7303 (markdown-cycle-setext 1))
7304 ;; Demote horizontal rule
7305 ((thing-at-point-looking-at markdown-regex-hr)
7306 (markdown-cycle-hr 1))
7307 ;; Demote list item
7308 ((setq bounds (markdown-cur-list-item-bounds))
7309 (markdown-demote-list-item bounds))
7310 ;; Move table column to the right
7311 ((markdown-table-at-point-p)
7312 (call-interactively #'markdown-table-move-column-right))
7313 ;; Demote bold
7314 ((thing-at-point-looking-at markdown-regex-bold)
7315 (markdown-cycle-bold))
7316 ;; Demote italic
7317 ((thing-at-point-looking-at markdown-regex-italic)
7318 (markdown-cycle-italic))
7320 (user-error "Nothing to demote at point")))))
7323 ;;; Commands ==================================================================
7325 (defun markdown (&optional output-buffer-name)
7326 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
7327 The output buffer name defaults to `markdown-output-buffer-name'.
7328 Return the name of the output buffer used."
7329 (interactive)
7330 (save-window-excursion
7331 (let* ((commands (cond ((stringp markdown-command) (split-string markdown-command))
7332 ((listp markdown-command) markdown-command)))
7333 (command (car-safe commands))
7334 (command-args (cdr-safe commands))
7335 begin-region end-region)
7336 (if (use-region-p)
7337 (setq begin-region (region-beginning)
7338 end-region (region-end))
7339 (setq begin-region (point-min)
7340 end-region (point-max)))
7342 (unless output-buffer-name
7343 (setq output-buffer-name markdown-output-buffer-name))
7344 (when (and (stringp command) (not (executable-find command)))
7345 (user-error "Markdown command %s is not found" command))
7346 (let ((exit-code
7347 (cond
7348 ;; Handle case when `markdown-command' does not read from stdin
7349 ((and (stringp command) markdown-command-needs-filename)
7350 (if (not buffer-file-name)
7351 (user-error "Must be visiting a file")
7352 ;; Don’t use ‘shell-command’ because it’s not guaranteed to
7353 ;; return the exit code of the process.
7354 (let ((command (if (listp markdown-command)
7355 (string-join markdown-command " ")
7356 markdown-command)))
7357 (shell-command-on-region
7358 ;; Pass an empty region so that stdin is empty.
7359 (point) (point)
7360 (concat command " "
7361 (shell-quote-argument buffer-file-name))
7362 output-buffer-name))))
7363 ;; Pass region to `markdown-command' via stdin
7365 (let ((buf (get-buffer-create output-buffer-name)))
7366 (with-current-buffer buf
7367 (setq buffer-read-only nil)
7368 (erase-buffer))
7369 (if (stringp command)
7370 (if (not (null command-args))
7371 (apply #'call-process-region begin-region end-region command nil buf nil command-args)
7372 (call-process-region begin-region end-region command nil buf))
7373 (if markdown-command-needs-filename
7374 (if (not buffer-file-name)
7375 (user-error "Must be visiting a file")
7376 (funcall markdown-command begin-region end-region buf buffer-file-name))
7377 (funcall markdown-command begin-region end-region buf))
7378 ;; If the ‘markdown-command’ function didn’t signal an
7379 ;; error, assume it succeeded by binding ‘exit-code’ to 0.
7380 0))))))
7381 ;; The exit code can be a signal description string, so don’t use ‘=’
7382 ;; or ‘zerop’.
7383 (unless (eq exit-code 0)
7384 (user-error "%s failed with exit code %s"
7385 markdown-command exit-code))))
7386 output-buffer-name))
7388 (defun markdown-standalone (&optional output-buffer-name)
7389 "Special function to provide standalone HTML output.
7390 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
7391 (interactive)
7392 (setq output-buffer-name (markdown output-buffer-name))
7393 (with-current-buffer output-buffer-name
7394 (set-buffer output-buffer-name)
7395 (unless (markdown-output-standalone-p)
7396 (markdown-add-xhtml-header-and-footer output-buffer-name))
7397 (goto-char (point-min))
7398 (html-mode))
7399 output-buffer-name)
7401 (defun markdown-other-window (&optional output-buffer-name)
7402 "Run `markdown-command' on current buffer and display in other window.
7403 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7404 that name."
7405 (interactive)
7406 (markdown-display-buffer-other-window
7407 (markdown-standalone output-buffer-name)))
7409 (defun markdown-output-standalone-p ()
7410 "Determine whether `markdown-command' output is standalone XHTML.
7411 Standalone XHTML output is identified by an occurrence of
7412 `markdown-xhtml-standalone-regexp' in the first five lines of output."
7413 (save-excursion
7414 (goto-char (point-min))
7415 (save-match-data
7416 (re-search-forward
7417 markdown-xhtml-standalone-regexp
7418 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
7419 t))))
7421 (defun markdown-stylesheet-link-string (stylesheet-path)
7422 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
7423 (or (and (string-prefix-p "~" stylesheet-path)
7424 (expand-file-name stylesheet-path))
7425 stylesheet-path)
7426 "\" />"))
7428 (defun markdown-add-xhtml-header-and-footer (title)
7429 "Wrap XHTML header and footer with given TITLE around current buffer."
7430 (goto-char (point-min))
7431 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
7432 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
7433 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
7434 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
7435 "<head>\n<title>")
7436 (insert title)
7437 (insert "</title>\n")
7438 (unless (= (length markdown-content-type) 0)
7439 (insert
7440 (format
7441 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
7442 markdown-content-type
7443 (or (and markdown-coding-system
7444 (coding-system-get markdown-coding-system
7445 'mime-charset))
7446 (coding-system-get buffer-file-coding-system
7447 'mime-charset)
7448 "utf-8"))))
7449 (if (> (length markdown-css-paths) 0)
7450 (insert (mapconcat #'markdown-stylesheet-link-string
7451 markdown-css-paths "\n")))
7452 (when (> (length markdown-xhtml-header-content) 0)
7453 (insert markdown-xhtml-header-content))
7454 (insert "\n</head>\n\n"
7455 "<body>\n\n")
7456 (when (> (length markdown-xhtml-body-preamble) 0)
7457 (insert markdown-xhtml-body-preamble "\n"))
7458 (goto-char (point-max))
7459 (when (> (length markdown-xhtml-body-epilogue) 0)
7460 (insert "\n" markdown-xhtml-body-epilogue))
7461 (insert "\n"
7462 "</body>\n"
7463 "</html>\n"))
7465 (defun markdown-preview (&optional output-buffer-name)
7466 "Run `markdown-command' on the current buffer and view output in browser.
7467 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7468 that name."
7469 (interactive)
7470 (browse-url-of-buffer
7471 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
7473 (defun markdown-export-file-name (&optional extension)
7474 "Attempt to generate a filename for Markdown output.
7475 The file extension will be EXTENSION if given, or .html by default.
7476 If the current buffer is visiting a file, we construct a new
7477 output filename based on that filename. Otherwise, return nil."
7478 (when (buffer-file-name)
7479 (unless extension
7480 (setq extension ".html"))
7481 (let ((candidate
7482 (concat
7483 (cond
7484 ((buffer-file-name)
7485 (file-name-sans-extension (buffer-file-name)))
7486 (t (buffer-name)))
7487 extension)))
7488 (cond
7489 ((equal candidate (buffer-file-name))
7490 (concat candidate extension))
7492 candidate)))))
7494 (defun markdown-export (&optional output-file)
7495 "Run Markdown on the current buffer, save to file, and return the filename.
7496 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
7497 generated by `markdown-export-file-name', which will be constructed using the
7498 current filename, but with the extension removed and replaced with .html."
7499 (interactive)
7500 (unless output-file
7501 (setq output-file (markdown-export-file-name ".html")))
7502 (when output-file
7503 (let* ((init-buf (current-buffer))
7504 (init-point (point))
7505 (init-buf-string (buffer-string))
7506 (output-buffer (find-file-noselect output-file))
7507 (output-buffer-name (buffer-name output-buffer)))
7508 (run-hooks 'markdown-before-export-hook)
7509 (markdown-standalone output-buffer-name)
7510 (with-current-buffer output-buffer
7511 (run-hooks 'markdown-after-export-hook)
7512 (save-buffer)
7513 (when markdown-export-kill-buffer (kill-buffer)))
7514 ;; if modified, restore initial buffer
7515 (when (buffer-modified-p init-buf)
7516 (erase-buffer)
7517 (insert init-buf-string)
7518 (save-buffer)
7519 (goto-char init-point))
7520 output-file)))
7522 (defun markdown-export-and-preview ()
7523 "Export to XHTML using `markdown-export' and browse the resulting file."
7524 (interactive)
7525 (browse-url-of-file (markdown-export)))
7527 (defvar-local markdown-live-preview-buffer nil
7528 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
7530 (defvar-local markdown-live-preview-source-buffer nil
7531 "Source buffer from which current buffer was generated.
7532 This is the inverse of `markdown-live-preview-buffer'.")
7534 (defvar markdown-live-preview-currently-exporting nil)
7536 (defun markdown-live-preview-get-filename ()
7537 "Standardize the filename exported by `markdown-live-preview-export'."
7538 (markdown-export-file-name ".html"))
7540 (defun markdown-live-preview-window-eww (file)
7541 "Preview FILE with eww.
7542 To be used with `markdown-live-preview-window-function'."
7543 (eww-open-file file)
7544 (get-buffer "*eww*"))
7546 (defun markdown-visual-lines-between-points (beg end)
7547 (save-excursion
7548 (goto-char beg)
7549 (cl-loop with count = 0
7550 while (progn (end-of-visual-line)
7551 (and (< (point) end) (line-move-visual 1 t)))
7552 do (cl-incf count)
7553 finally return count)))
7555 (defun markdown-live-preview-window-serialize (buf)
7556 "Get window point and scroll data for all windows displaying BUF."
7557 (when (buffer-live-p buf)
7558 (with-current-buffer buf
7559 (mapcar
7560 (lambda (win)
7561 (with-selected-window win
7562 (let* ((start (window-start))
7563 (pt (window-point))
7564 (pt-or-sym (cond ((= pt (point-min)) 'min)
7565 ((= pt (point-max)) 'max)
7566 (t pt)))
7567 (diff (markdown-visual-lines-between-points
7568 start pt)))
7569 (list win pt-or-sym diff))))
7570 (get-buffer-window-list buf)))))
7572 (defun markdown-get-point-back-lines (pt num-lines)
7573 (save-excursion
7574 (goto-char pt)
7575 (line-move-visual (- num-lines) t)
7576 ;; in testing, can occasionally overshoot the number of lines to traverse
7577 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
7578 (when (> actual-num-lines num-lines)
7579 (line-move-visual (- actual-num-lines num-lines) t)))
7580 (point)))
7582 (defun markdown-live-preview-window-deserialize (window-posns)
7583 "Apply window point and scroll data from WINDOW-POSNS.
7584 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
7585 (cl-destructuring-bind (win pt-or-sym diff) window-posns
7586 (when (window-live-p win)
7587 (with-current-buffer markdown-live-preview-buffer
7588 (set-window-buffer win (current-buffer))
7589 (cl-destructuring-bind (actual-pt actual-diff)
7590 (cl-case pt-or-sym
7591 (min (list (point-min) 0))
7592 (max (list (point-max) diff))
7593 (t (list pt-or-sym diff)))
7594 (set-window-start
7595 win (markdown-get-point-back-lines actual-pt actual-diff))
7596 (set-window-point win actual-pt))))))
7598 (defun markdown-live-preview-export ()
7599 "Export to XHTML using `markdown-export'.
7600 Browse the resulting file within Emacs using
7601 `markdown-live-preview-window-function' Return the buffer
7602 displaying the rendered output."
7603 (interactive)
7604 (let ((filename (markdown-live-preview-get-filename)))
7605 (when filename
7606 (let* ((markdown-live-preview-currently-exporting t)
7607 (cur-buf (current-buffer))
7608 (export-file (markdown-export filename))
7609 ;; get positions in all windows currently displaying output buffer
7610 (window-data
7611 (markdown-live-preview-window-serialize
7612 markdown-live-preview-buffer)))
7613 (save-window-excursion
7614 (let ((output-buffer
7615 (funcall markdown-live-preview-window-function export-file)))
7616 (with-current-buffer output-buffer
7617 (setq markdown-live-preview-source-buffer cur-buf)
7618 (add-hook 'kill-buffer-hook
7619 #'markdown-live-preview-remove-on-kill t t))
7620 (with-current-buffer cur-buf
7621 (setq markdown-live-preview-buffer output-buffer))))
7622 (with-current-buffer cur-buf
7623 ;; reset all windows displaying output buffer to where they were,
7624 ;; now with the new output
7625 (mapc #'markdown-live-preview-window-deserialize window-data)
7626 ;; delete html editing buffer
7627 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
7628 (when (and export-file (file-exists-p export-file)
7629 (eq markdown-live-preview-delete-export
7630 'delete-on-export))
7631 (delete-file export-file))
7632 markdown-live-preview-buffer)))))
7634 (defun markdown-live-preview-remove ()
7635 (when (buffer-live-p markdown-live-preview-buffer)
7636 (kill-buffer markdown-live-preview-buffer))
7637 (setq markdown-live-preview-buffer nil)
7638 ;; if set to 'delete-on-export, the output has already been deleted
7639 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
7640 (let ((outfile-name (markdown-live-preview-get-filename)))
7641 (when (and outfile-name (file-exists-p outfile-name))
7642 (delete-file outfile-name)))))
7644 (defun markdown-get-other-window ()
7645 "Find another window to display preview or output content."
7646 (cond
7647 ((memq markdown-split-window-direction '(vertical below))
7648 (or (window-in-direction 'below) (split-window-vertically)))
7649 ((memq markdown-split-window-direction '(horizontal right))
7650 (or (window-in-direction 'right) (split-window-horizontally)))
7651 (t (split-window-sensibly (get-buffer-window)))))
7653 (defun markdown-display-buffer-other-window (buf)
7654 "Display preview or output buffer BUF in another window."
7655 (if (and display-buffer-alist (eq markdown-split-window-direction 'any))
7656 (display-buffer buf)
7657 (let ((cur-buf (current-buffer))
7658 (window (markdown-get-other-window)))
7659 (set-window-buffer window buf)
7660 (set-buffer cur-buf))))
7662 (defun markdown-live-preview-if-markdown ()
7663 (when (and (derived-mode-p 'markdown-mode)
7664 markdown-live-preview-mode)
7665 (unless markdown-live-preview-currently-exporting
7666 (if (buffer-live-p markdown-live-preview-buffer)
7667 (markdown-live-preview-export)
7668 (markdown-display-buffer-other-window
7669 (markdown-live-preview-export))))))
7671 (defun markdown-live-preview-remove-on-kill ()
7672 (cond ((and (derived-mode-p 'markdown-mode)
7673 markdown-live-preview-mode)
7674 (markdown-live-preview-remove))
7675 (markdown-live-preview-source-buffer
7676 (with-current-buffer markdown-live-preview-source-buffer
7677 (setq markdown-live-preview-buffer nil))
7678 (setq markdown-live-preview-source-buffer nil))))
7680 (defun markdown-live-preview-switch-to-output ()
7681 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
7682 output buffer in another window."
7683 (interactive)
7684 (if markdown-live-preview-mode
7685 (markdown-display-buffer-other-window (markdown-live-preview-export)))
7686 (markdown-live-preview-mode))
7688 (defun markdown-live-preview-re-export ()
7689 "If the current buffer is a buffer displaying the exported version of a
7690 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
7691 update this buffer's contents."
7692 (interactive)
7693 (when markdown-live-preview-source-buffer
7694 (with-current-buffer markdown-live-preview-source-buffer
7695 (markdown-live-preview-export))))
7697 (defun markdown-open ()
7698 "Open file for the current buffer with `markdown-open-command'."
7699 (interactive)
7700 (unless markdown-open-command
7701 (user-error "Variable `markdown-open-command' must be set"))
7702 (if (stringp markdown-open-command)
7703 (if (not buffer-file-name)
7704 (user-error "Must be visiting a file")
7705 (save-buffer)
7706 (let ((exit-code (call-process markdown-open-command nil nil nil
7707 buffer-file-name)))
7708 ;; The exit code can be a signal description string, so don’t use ‘=’
7709 ;; or ‘zerop’.
7710 (unless (eq exit-code 0)
7711 (user-error "%s failed with exit code %s"
7712 markdown-open-command exit-code))))
7713 (funcall markdown-open-command))
7714 nil)
7716 (defun markdown-kill-ring-save ()
7717 "Run Markdown on file and store output in the kill ring."
7718 (interactive)
7719 (save-window-excursion
7720 (markdown)
7721 (with-current-buffer markdown-output-buffer-name
7722 (kill-ring-save (point-min) (point-max)))))
7725 ;;; Links =====================================================================
7727 (defun markdown-backward-to-link-start ()
7728 "Backward link start position if current position is in link title."
7729 ;; Issue #305
7730 (when (eq (get-text-property (point) 'face) 'markdown-link-face)
7731 (skip-chars-backward "^[")
7732 (forward-char -1)))
7734 (defun markdown-link-p ()
7735 "Return non-nil when `point' is at a non-wiki link.
7736 See `markdown-wiki-link-p' for more information."
7737 (save-excursion
7738 (let ((case-fold-search nil))
7739 (when (and (not (markdown-wiki-link-p)) (not (markdown-code-block-at-point-p)))
7740 (markdown-backward-to-link-start)
7741 (or (thing-at-point-looking-at markdown-regex-link-inline)
7742 (thing-at-point-looking-at markdown-regex-link-reference)
7743 (thing-at-point-looking-at markdown-regex-uri)
7744 (thing-at-point-looking-at markdown-regex-angle-uri))))))
7746 (defun markdown-link-at-pos (pos)
7747 "Return properties of link or image at position POS.
7748 Value is a list of elements describing the link:
7749 0. beginning position
7750 1. end position
7751 2. link text
7752 3. URL
7753 4. reference label
7754 5. title text
7755 6. bang (nil or \"!\")"
7756 (save-excursion
7757 (goto-char pos)
7758 (markdown-backward-to-link-start)
7759 (let (begin end text url reference title bang)
7760 (cond
7761 ;; Inline image or link at point.
7762 ((thing-at-point-looking-at markdown-regex-link-inline)
7763 (setq bang (match-string-no-properties 1)
7764 begin (match-beginning 0)
7765 end (match-end 0)
7766 text (match-string-no-properties 3)
7767 url (match-string-no-properties 6))
7768 (if (match-end 7)
7769 (setq title (substring (match-string-no-properties 7) 1 -1))
7770 ;; #408 URL contains close parenthesis case
7771 (goto-char (match-beginning 5))
7772 (let ((paren-end (scan-sexps (point) 1)))
7773 (when (and paren-end (< end paren-end))
7774 (setq url (buffer-substring (match-beginning 6) (1- paren-end)))))))
7775 ;; Reference link at point.
7776 ((or (thing-at-point-looking-at markdown-regex-link-inline)
7777 (thing-at-point-looking-at markdown-regex-link-reference))
7778 (setq bang (match-string-no-properties 1)
7779 begin (match-beginning 0)
7780 end (match-end 0)
7781 text (match-string-no-properties 3))
7782 (when (char-equal (char-after (match-beginning 5)) ?\[)
7783 (setq reference (match-string-no-properties 6))))
7784 ;; Angle bracket URI at point.
7785 ((thing-at-point-looking-at markdown-regex-angle-uri)
7786 (setq begin (match-beginning 0)
7787 end (match-end 0)
7788 url (match-string-no-properties 2)))
7789 ;; Plain URI at point.
7790 ((thing-at-point-looking-at markdown-regex-uri)
7791 (setq begin (match-beginning 0)
7792 end (match-end 0)
7793 url (match-string-no-properties 1))))
7794 (list begin end text url reference title bang))))
7796 (defun markdown-link-url ()
7797 "Return the URL part of the regular (non-wiki) link at point.
7798 Works with both inline and reference style links, and with images.
7799 If point is not at a link or the link reference is not defined
7800 returns nil."
7801 (let* ((values (markdown-link-at-pos (point)))
7802 (text (nth 2 values))
7803 (url (nth 3 values))
7804 (ref (nth 4 values)))
7805 (or url (and ref (car (markdown-reference-definition
7806 (downcase (if (string= ref "") text ref))))))))
7808 (defun markdown--browse-url (url)
7809 (let* ((struct (url-generic-parse-url url))
7810 (full (url-fullness struct))
7811 (file url))
7812 ;; Parse URL, determine fullness, strip query string
7813 (setq file (car (url-path-and-query struct)))
7814 ;; Open full URLs in browser, files in Emacs
7815 (if full
7816 (browse-url url)
7817 (when (and file (> (length file) 0))
7818 (let ((link-file (funcall markdown-translate-filename-function file)))
7819 (if (and markdown-open-image-command (string-match-p (image-file-name-regexp) link-file))
7820 (if (functionp markdown-open-image-command)
7821 (funcall markdown-open-image-command link-file)
7822 (process-file markdown-open-image-command nil nil nil link-file))
7823 (find-file link-file)))))))
7825 (defun markdown-follow-link-at-point (&optional event)
7826 "Open the non-wiki link at point or EVENT.
7827 If the link is a complete URL, open in browser with `browse-url'.
7828 Otherwise, open with `find-file' after stripping anchor and/or query string.
7829 Translate filenames using `markdown-filename-translate-function'."
7830 (interactive (list last-command-event))
7831 (save-excursion
7832 (if event (posn-set-point (event-start event)))
7833 (if (markdown-link-p)
7834 (markdown--browse-url (markdown-link-url))
7835 (user-error "Point is not at a Markdown link or URL"))))
7837 (defun markdown-fontify-inline-links (last)
7838 "Add text properties to next inline link from point to LAST."
7839 (when (markdown-match-generic-links last nil)
7840 (let* ((link-start (match-beginning 3))
7841 (link-end (match-end 3))
7842 (url-start (match-beginning 6))
7843 (url-end (match-end 6))
7844 (url (match-string-no-properties 6))
7845 (title-start (match-beginning 7))
7846 (title-end (match-end 7))
7847 (title (match-string-no-properties 7))
7848 ;; Markup part
7849 (mp (list 'face 'markdown-markup-face
7850 'invisible 'markdown-markup
7851 'rear-nonsticky t
7852 'font-lock-multiline t))
7853 ;; Link part (without face)
7854 (lp (list 'keymap markdown-mode-mouse-map
7855 'mouse-face 'markdown-highlight-face
7856 'font-lock-multiline t
7857 'help-echo (if title (concat title "\n" url) url)))
7858 ;; URL part
7859 (up (list 'keymap markdown-mode-mouse-map
7860 'face 'markdown-url-face
7861 'invisible 'markdown-markup
7862 'mouse-face 'markdown-highlight-face
7863 'font-lock-multiline t))
7864 ;; URL composition character
7865 (url-char (markdown--first-displayable markdown-url-compose-char))
7866 ;; Title part
7867 (tp (list 'face 'markdown-link-title-face
7868 'invisible 'markdown-markup
7869 'font-lock-multiline t)))
7870 (dolist (g '(1 2 4 5 8))
7871 (when (match-end g)
7872 (add-text-properties (match-beginning g) (match-end g) mp)))
7873 ;; Preserve existing faces applied to link part (e.g., inline code)
7874 (when link-start
7875 (add-text-properties link-start link-end lp)
7876 (add-face-text-property link-start link-end
7877 'markdown-link-face 'append))
7878 (when url-start (add-text-properties url-start url-end up))
7879 (when title-start (add-text-properties url-end title-end tp))
7880 (when (and markdown-hide-urls url-start)
7881 (compose-region url-start (or title-end url-end) url-char))
7882 t)))
7884 (defun markdown-fontify-reference-links (last)
7885 "Add text properties to next reference link from point to LAST."
7886 (when (markdown-match-generic-links last t)
7887 (let* ((link-start (match-beginning 3))
7888 (link-end (match-end 3))
7889 (ref-start (match-beginning 6))
7890 (ref-end (match-end 6))
7891 ;; Markup part
7892 (mp (list 'face 'markdown-markup-face
7893 'invisible 'markdown-markup
7894 'rear-nonsticky t
7895 'font-lock-multiline t))
7896 ;; Link part
7897 (lp (list 'keymap markdown-mode-mouse-map
7898 'face 'markdown-link-face
7899 'mouse-face 'markdown-highlight-face
7900 'font-lock-multiline t
7901 'help-echo (lambda (_ __ pos)
7902 (save-match-data
7903 (save-excursion
7904 (goto-char pos)
7905 (or (markdown-link-url)
7906 "Undefined reference"))))))
7907 ;; URL composition character
7908 (url-char (markdown--first-displayable markdown-url-compose-char))
7909 ;; Reference part
7910 (rp (list 'face 'markdown-reference-face
7911 'invisible 'markdown-markup
7912 'font-lock-multiline t)))
7913 (dolist (g '(1 2 4 5 8))
7914 (when (match-end g)
7915 (add-text-properties (match-beginning g) (match-end g) mp)))
7916 (when link-start (add-text-properties link-start link-end lp))
7917 (when ref-start (add-text-properties ref-start ref-end rp)
7918 (when (and markdown-hide-urls (> (- ref-end ref-start) 2))
7919 (compose-region ref-start ref-end url-char)))
7920 t)))
7922 (defun markdown-fontify-angle-uris (last)
7923 "Add text properties to angle URIs from point to LAST."
7924 (when (markdown-match-angle-uris last)
7925 (let* ((url-start (match-beginning 2))
7926 (url-end (match-end 2))
7927 ;; Markup part
7928 (mp (list 'face 'markdown-markup-face
7929 'invisible 'markdown-markup
7930 'rear-nonsticky t
7931 'font-lock-multiline t))
7932 ;; URI part
7933 (up (list 'keymap markdown-mode-mouse-map
7934 'face 'markdown-plain-url-face
7935 'mouse-face 'markdown-highlight-face
7936 'font-lock-multiline t)))
7937 (dolist (g '(1 3))
7938 (add-text-properties (match-beginning g) (match-end g) mp))
7939 (add-text-properties url-start url-end up)
7940 t)))
7942 (defun markdown-fontify-plain-uris (last)
7943 "Add text properties to plain URLs from point to LAST."
7944 (when (markdown-match-plain-uris last)
7945 (let* ((start (match-beginning 0))
7946 (end (match-end 0))
7947 (props (list 'keymap markdown-mode-mouse-map
7948 'face 'markdown-plain-url-face
7949 'mouse-face 'markdown-highlight-face
7950 'rear-nonsticky t
7951 'font-lock-multiline t)))
7952 (add-text-properties start end props)
7953 t)))
7955 (defun markdown-toggle-url-hiding (&optional arg)
7956 "Toggle the display or hiding of URLs.
7957 With a prefix argument ARG, enable URL hiding if ARG is positive,
7958 and disable it otherwise."
7959 (interactive (list (or current-prefix-arg 'toggle)))
7960 (setq markdown-hide-urls
7961 (if (eq arg 'toggle)
7962 (not markdown-hide-urls)
7963 (> (prefix-numeric-value arg) 0)))
7964 (if markdown-hide-urls
7965 (message "markdown-mode URL hiding enabled")
7966 (message "markdown-mode URL hiding disabled"))
7967 (markdown-reload-extensions))
7970 ;;; Wiki Links ================================================================
7972 (defun markdown-wiki-link-p ()
7973 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
7974 A true wiki link name matches `markdown-regex-wiki-link' but does
7975 not match the current file name after conversion. This modifies
7976 the data returned by `match-data'. Note that the potential wiki
7977 link name must be available via `match-string'."
7978 (when markdown-enable-wiki-links
7979 (let ((case-fold-search nil))
7980 (and (thing-at-point-looking-at markdown-regex-wiki-link)
7981 (not (markdown-code-block-at-point-p))
7982 (or (not buffer-file-name)
7983 (not (string-equal (buffer-file-name)
7984 (markdown-convert-wiki-link-to-filename
7985 (markdown-wiki-link-link)))))))))
7987 (defun markdown-wiki-link-link ()
7988 "Return the link part of the wiki link using current match data.
7989 The location of the link component depends on the value of
7990 `markdown-wiki-link-alias-first'."
7991 (if markdown-wiki-link-alias-first
7992 (or (match-string-no-properties 5) (match-string-no-properties 3))
7993 (match-string-no-properties 3)))
7995 (defun markdown-wiki-link-alias ()
7996 "Return the alias or text part of the wiki link using current match data.
7997 The location of the alias component depends on the value of
7998 `markdown-wiki-link-alias-first'."
7999 (if markdown-wiki-link-alias-first
8000 (match-string-no-properties 3)
8001 (or (match-string-no-properties 5) (match-string-no-properties 3))))
8003 (defun markdown--wiki-link-search-types ()
8004 (let ((ret (and markdown-wiki-link-search-type
8005 (cl-copy-list markdown-wiki-link-search-type))))
8006 (when (and markdown-wiki-link-search-subdirectories
8007 (not (memq 'sub-directories markdown-wiki-link-search-type)))
8008 (push 'sub-directories ret))
8009 (when (and markdown-wiki-link-search-parent-directories
8010 (not (memq 'parent-directories markdown-wiki-link-search-type)))
8011 (push 'parent-directories ret))
8012 ret))
8014 (defun markdown--project-root ()
8015 (or (cl-loop for dir in '(".git" ".hg" ".svn")
8016 when (locate-dominating-file default-directory dir)
8017 return it)
8018 (progn
8019 (require 'project)
8020 (let ((project (project-current t)))
8021 (with-no-warnings
8022 (if (fboundp 'project-root)
8023 (project-root project)
8024 (car (project-roots project))))))))
8026 (defun markdown-convert-wiki-link-to-filename (name)
8027 "Generate a filename from the wiki link NAME.
8028 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
8029 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
8030 and [[test test]] both map to Test-test.ext. Look in the current
8031 directory first, then in subdirectories if
8032 `markdown-wiki-link-search-subdirectories' is non-nil, and then
8033 in parent directories if
8034 `markdown-wiki-link-search-parent-directories' is non-nil."
8035 (save-match-data
8036 ;; This function must not overwrite match data(PR #590)
8037 (let* ((basename (replace-regexp-in-string
8038 "[[:space:]\n]" markdown-link-space-sub-char name))
8039 (basename (if (derived-mode-p 'gfm-mode)
8040 (concat (upcase (substring basename 0 1))
8041 (downcase (substring basename 1 nil)))
8042 basename))
8043 (search-types (markdown--wiki-link-search-types))
8044 directory extension default candidates dir)
8045 (when buffer-file-name
8046 (setq directory (file-name-directory buffer-file-name)
8047 extension (file-name-extension buffer-file-name)))
8048 (setq default (concat basename
8049 (when extension (concat "." extension))))
8050 (cond
8051 ;; Look in current directory first.
8052 ((or (null buffer-file-name)
8053 (file-exists-p default))
8054 default)
8055 ;; Possibly search in subdirectories, next.
8056 ((and (memq 'sub-directories search-types)
8057 (setq candidates
8058 (directory-files-recursively
8059 directory (concat "^" default "$"))))
8060 (car candidates))
8061 ;; Possibly search in parent directories as a last resort.
8062 ((and (memq 'parent-directories search-types)
8063 (setq dir (locate-dominating-file directory default)))
8064 (concat dir default))
8065 ((and (memq 'project search-types)
8066 (setq candidates
8067 (directory-files-recursively
8068 (markdown--project-root) (concat "^" default "$"))))
8069 (car candidates))
8070 ;; If nothing is found, return default in current directory.
8071 (t default)))))
8073 (defun markdown-follow-wiki-link (name &optional other)
8074 "Follow the wiki link NAME.
8075 Convert the name to a file name and call `find-file'. Ensure that
8076 the new buffer remains in `markdown-mode'. Open the link in another
8077 window when OTHER is non-nil."
8078 (let ((filename (markdown-convert-wiki-link-to-filename name))
8079 (wp (when buffer-file-name
8080 (file-name-directory buffer-file-name))))
8081 (if (not wp)
8082 (user-error "Must be visiting a file")
8083 (when other (other-window 1))
8084 (let ((default-directory wp))
8085 (find-file filename)))
8086 (unless (derived-mode-p 'markdown-mode)
8087 (markdown-mode))))
8089 (defun markdown-follow-wiki-link-at-point (&optional arg)
8090 "Find Wiki Link at point.
8091 With prefix argument ARG, open the file in other window.
8092 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
8093 (interactive "P")
8094 (if (markdown-wiki-link-p)
8095 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
8096 (user-error "Point is not at a Wiki Link")))
8098 (defun markdown-highlight-wiki-link (from to face)
8099 "Highlight the wiki link in the region between FROM and TO using FACE."
8100 (put-text-property from to 'font-lock-face face))
8102 (defun markdown-unfontify-region-wiki-links (from to)
8103 "Remove wiki link faces from the region specified by FROM and TO."
8104 (interactive "*r")
8105 (let ((modified (buffer-modified-p)))
8106 (remove-text-properties from to '(font-lock-face markdown-link-face))
8107 (remove-text-properties from to '(font-lock-face markdown-missing-link-face))
8108 ;; remove-text-properties marks the buffer modified in emacs 24.3,
8109 ;; undo that if it wasn't originally marked modified
8110 (set-buffer-modified-p modified)))
8112 (defun markdown-fontify-region-wiki-links (from to)
8113 "Search region given by FROM and TO for wiki links and fontify them.
8114 If a wiki link is found check to see if the backing file exists
8115 and highlight accordingly."
8116 (goto-char from)
8117 (save-match-data
8118 (while (re-search-forward markdown-regex-wiki-link to t)
8119 (when (not (markdown-code-block-at-point-p))
8120 (let ((highlight-beginning (match-beginning 1))
8121 (highlight-end (match-end 1))
8122 (file-name
8123 (markdown-convert-wiki-link-to-filename
8124 (markdown-wiki-link-link))))
8125 (if (condition-case nil (file-exists-p file-name) (error nil))
8126 (markdown-highlight-wiki-link
8127 highlight-beginning highlight-end 'markdown-link-face)
8128 (markdown-highlight-wiki-link
8129 highlight-beginning highlight-end 'markdown-missing-link-face)))))))
8131 (defun markdown-extend-changed-region (from to)
8132 "Extend region given by FROM and TO so that we can fontify all links.
8133 The region is extended to the first newline before and the first
8134 newline after."
8135 ;; start looking for the first new line before 'from
8136 (goto-char from)
8137 (re-search-backward "\n" nil t)
8138 (let ((new-from (point-min))
8139 (new-to (point-max)))
8140 (if (not (= (point) from))
8141 (setq new-from (point)))
8142 ;; do the same thing for the first new line after 'to
8143 (goto-char to)
8144 (re-search-forward "\n" nil t)
8145 (if (not (= (point) to))
8146 (setq new-to (point)))
8147 (cl-values new-from new-to)))
8149 (defun markdown-check-change-for-wiki-link (from to)
8150 "Check region between FROM and TO for wiki links and re-fontify as needed."
8151 (interactive "*r")
8152 (let* ((modified (buffer-modified-p))
8153 (buffer-undo-list t)
8154 (inhibit-read-only t)
8155 (inhibit-point-motion-hooks t)
8156 deactivate-mark
8157 buffer-file-truename)
8158 (unwind-protect
8159 (save-excursion
8160 (save-match-data
8161 (save-restriction
8162 ;; Extend the region to fontify so that it starts
8163 ;; and ends at safe places.
8164 (cl-multiple-value-bind (new-from new-to)
8165 (markdown-extend-changed-region from to)
8166 (goto-char new-from)
8167 ;; Only refontify when the range contains text with a
8168 ;; wiki link face or if the wiki link regexp matches.
8169 (when (or (markdown-range-property-any
8170 new-from new-to 'font-lock-face
8171 '(markdown-link-face markdown-missing-link-face))
8172 (re-search-forward
8173 markdown-regex-wiki-link new-to t))
8174 ;; Unfontify existing fontification (start from scratch)
8175 (markdown-unfontify-region-wiki-links new-from new-to)
8176 ;; Now do the fontification.
8177 (markdown-fontify-region-wiki-links new-from new-to))))))
8178 (and (not modified)
8179 (buffer-modified-p)
8180 (set-buffer-modified-p nil)))))
8182 (defun markdown-check-change-for-wiki-link-after-change (from to _)
8183 "Check region between FROM and TO for wiki links and re-fontify as needed.
8184 Designed to be used with the `after-change-functions' hook."
8185 (markdown-check-change-for-wiki-link from to))
8187 (defun markdown-fontify-buffer-wiki-links ()
8188 "Refontify all wiki links in the buffer."
8189 (interactive)
8190 (markdown-check-change-for-wiki-link (point-min) (point-max)))
8192 (defun markdown-toggle-wiki-links (&optional arg)
8193 "Toggle support for wiki links.
8194 With a prefix argument ARG, enable wiki link support if ARG is positive,
8195 and disable it otherwise."
8196 (interactive (list (or current-prefix-arg 'toggle)))
8197 (setq markdown-enable-wiki-links
8198 (if (eq arg 'toggle)
8199 (not markdown-enable-wiki-links)
8200 (> (prefix-numeric-value arg) 0)))
8201 (if markdown-enable-wiki-links
8202 (message "markdown-mode wiki link support enabled")
8203 (message "markdown-mode wiki link support disabled"))
8204 (markdown-reload-extensions))
8206 (defun markdown-setup-wiki-link-hooks ()
8207 "Add or remove hooks for fontifying wiki links.
8208 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
8209 ;; Anytime text changes make sure it gets fontified correctly
8210 (if (and markdown-enable-wiki-links
8211 markdown-wiki-link-fontify-missing)
8212 (add-hook 'after-change-functions
8213 #'markdown-check-change-for-wiki-link-after-change t t)
8214 (remove-hook 'after-change-functions
8215 #'markdown-check-change-for-wiki-link-after-change t))
8216 ;; If we left the buffer there is a really good chance we were
8217 ;; creating one of the wiki link documents. Make sure we get
8218 ;; refontified when we come back.
8219 (if (and markdown-enable-wiki-links
8220 markdown-wiki-link-fontify-missing)
8221 (progn
8222 (add-hook 'window-configuration-change-hook
8223 #'markdown-fontify-buffer-wiki-links t t)
8224 (markdown-fontify-buffer-wiki-links))
8225 (remove-hook 'window-configuration-change-hook
8226 #'markdown-fontify-buffer-wiki-links t)
8227 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
8230 ;;; Following & Doing =========================================================
8232 (defun markdown-follow-thing-at-point (arg)
8233 "Follow thing at point if possible, such as a reference link or wiki link.
8234 Opens inline and reference links in a browser. Opens wiki links
8235 to other files in the current window, or the another window if
8236 ARG is non-nil.
8237 See `markdown-follow-link-at-point' and
8238 `markdown-follow-wiki-link-at-point'."
8239 (interactive "P")
8240 (cond ((markdown-link-p)
8241 (markdown--browse-url (markdown-link-url)))
8242 ((markdown-wiki-link-p)
8243 (markdown-follow-wiki-link-at-point arg))
8245 (let* ((values (markdown-link-at-pos (point)))
8246 (url (nth 3 values)))
8247 (unless url
8248 (user-error "Nothing to follow at point"))
8249 (markdown--browse-url url)))))
8251 (defun markdown-do ()
8252 "Do something sensible based on context at point.
8253 Jumps between reference links and definitions; between footnote
8254 markers and footnote text."
8255 (interactive)
8256 (cond
8257 ;; Footnote definition
8258 ((markdown-footnote-text-positions)
8259 (markdown-footnote-return))
8260 ;; Footnote marker
8261 ((markdown-footnote-marker-positions)
8262 (markdown-footnote-goto-text))
8263 ;; Reference link
8264 ((thing-at-point-looking-at markdown-regex-link-reference)
8265 (markdown-reference-goto-definition))
8266 ;; Reference definition
8267 ((thing-at-point-looking-at markdown-regex-reference-definition)
8268 (markdown-reference-goto-link (match-string-no-properties 2)))
8269 ;; Link
8270 ((or (markdown-link-p) (markdown-wiki-link-p))
8271 (markdown-follow-thing-at-point nil))
8272 ;; GFM task list item
8273 ((markdown-gfm-task-list-item-at-point)
8274 (markdown-toggle-gfm-checkbox))
8275 ;; Align table
8276 ((markdown-table-at-point-p)
8277 (call-interactively #'markdown-table-align))
8278 ;; Otherwise
8280 (markdown-insert-gfm-checkbox))))
8283 ;;; Miscellaneous =============================================================
8285 (defun markdown-compress-whitespace-string (str)
8286 "Compress whitespace in STR and return result.
8287 Leading and trailing whitespace is removed. Sequences of multiple
8288 spaces, tabs, and newlines are replaced with single spaces."
8289 (replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
8290 (replace-regexp-in-string "[ \t\n]+" " " str)))
8292 (defun markdown--substitute-command-keys (string)
8293 "Like `substitute-command-keys' but, but prefers control characters.
8294 First pass STRING to `substitute-command-keys' and then
8295 substitute `C-i` for `TAB` and `C-m` for `RET`."
8296 (replace-regexp-in-string
8297 "\\<TAB\\>" "C-i"
8298 (replace-regexp-in-string
8299 "\\<RET\\>" "C-m" (substitute-command-keys string) t) t))
8301 (defun markdown-line-number-at-pos (&optional pos)
8302 "Return (narrowed) buffer line number at position POS.
8303 If POS is nil, use current buffer location.
8304 This is an exact copy of `line-number-at-pos' for use in emacs21."
8305 (let ((opoint (or pos (point))) start)
8306 (save-excursion
8307 (goto-char (point-min))
8308 (setq start (point))
8309 (goto-char opoint)
8310 (forward-line 0)
8311 (1+ (count-lines start (point))))))
8313 (defun markdown-inside-link-p ()
8314 "Return t if point is within a link."
8315 (save-match-data
8316 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
8318 (defun markdown-line-is-reference-definition-p ()
8319 "Return whether the current line is a (non-footnote) reference definition."
8320 (save-excursion
8321 (move-beginning-of-line 1)
8322 (and (looking-at-p markdown-regex-reference-definition)
8323 (not (looking-at-p "[ \t]*\\[^")))))
8325 (defun markdown-adaptive-fill-function ()
8326 "Return prefix for filling paragraph or nil if not determined."
8327 (cond
8328 ;; List item inside blockquote
8329 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
8330 (replace-regexp-in-string
8331 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
8332 ;; Blockquote
8333 ((looking-at markdown-regex-blockquote)
8334 (buffer-substring-no-properties (match-beginning 0) (match-end 2)))
8335 ;; List items
8336 ((looking-at markdown-regex-list)
8337 (match-string-no-properties 0))
8338 ;; Footnote definition
8339 ((looking-at-p markdown-regex-footnote-definition)
8340 " ") ; four spaces
8341 ;; No match
8342 (t nil)))
8344 (defun markdown-fill-paragraph (&optional justify)
8345 "Fill paragraph at or after point.
8346 This function is like \\[fill-paragraph], but it skips Markdown
8347 code blocks. If the point is in a code block, or just before one,
8348 do not fill. Otherwise, call `fill-paragraph' as usual. If
8349 JUSTIFY is non-nil, justify text as well. Since this function
8350 handles filling itself, it always returns t so that
8351 `fill-paragraph' doesn't run."
8352 (interactive "P")
8353 (unless (or (markdown-code-block-at-point-p)
8354 (save-excursion
8355 (back-to-indentation)
8356 (skip-syntax-forward "-")
8357 (markdown-code-block-at-point-p)))
8358 (let ((fill-prefix (save-excursion
8359 (goto-char (line-beginning-position))
8360 (when (looking-at "\\([ \t]*>[ \t]*\\(?:>[ \t]*\\)+\\)")
8361 (match-string-no-properties 1)))))
8362 (fill-paragraph justify)))
8365 (defun markdown-fill-forward-paragraph (&optional arg)
8366 "Function used by `fill-paragraph' to move over ARG paragraphs.
8367 This is a `fill-forward-paragraph-function' for `markdown-mode'.
8368 It is called with a single argument specifying the number of
8369 paragraphs to move. Just like `forward-paragraph', it should
8370 return the number of paragraphs left to move."
8371 (or arg (setq arg 1))
8372 (if (> arg 0)
8373 ;; With positive ARG, move across ARG non-code-block paragraphs,
8374 ;; one at a time. When passing a code block, don't decrement ARG.
8375 (while (and (not (eobp))
8376 (> arg 0)
8377 (= (forward-paragraph 1) 0)
8378 (or (markdown-code-block-at-pos (point-at-bol 0))
8379 (setq arg (1- arg)))))
8380 ;; Move backward by one paragraph with negative ARG (always -1).
8381 (let ((start (point)))
8382 (setq arg (forward-paragraph arg))
8383 (while (and (not (eobp))
8384 (progn (move-to-left-margin) (not (eobp)))
8385 (looking-at-p paragraph-separate))
8386 (forward-line 1))
8387 (cond
8388 ;; Move point past whitespace following list marker.
8389 ((looking-at markdown-regex-list)
8390 (goto-char (match-end 0)))
8391 ;; Move point past whitespace following pipe at beginning of line
8392 ;; to handle Pandoc line blocks.
8393 ((looking-at "^|\\s-*")
8394 (goto-char (match-end 0)))
8395 ;; Return point if the paragraph passed was a code block.
8396 ((markdown-code-block-at-pos (point-at-bol 2))
8397 (goto-char start)))))
8398 arg)
8400 (defun markdown--inhibit-electric-quote ()
8401 "Function added to `electric-quote-inhibit-functions'.
8402 Return non-nil if the quote has been inserted inside a code block
8403 or span."
8404 (let ((pos (1- (point))))
8405 (or (markdown-inline-code-at-pos pos)
8406 (markdown-code-block-at-pos pos))))
8409 ;;; Extension Framework =======================================================
8411 (defun markdown-reload-extensions ()
8412 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
8413 (interactive)
8414 (when (derived-mode-p 'markdown-mode)
8415 ;; Refontify buffer
8416 (font-lock-flush)
8417 ;; Add or remove hooks related to extensions
8418 (markdown-setup-wiki-link-hooks)))
8420 (defun markdown-handle-local-variables ()
8421 "Run in `hack-local-variables-hook' to update font lock rules.
8422 Checks to see if there is actually a ‘markdown-mode’ file local variable
8423 before regenerating font-lock rules for extensions."
8424 (when (or (assoc 'markdown-enable-wiki-links file-local-variables-alist)
8425 (assoc 'markdown-enable-math file-local-variables-alist))
8426 (when (assoc 'markdown-enable-math file-local-variables-alist)
8427 (markdown-toggle-math markdown-enable-math))
8428 (markdown-reload-extensions)))
8431 ;;; Math Support ==============================================================
8433 (defconst markdown-mode-font-lock-keywords-math
8434 (list
8435 ;; Equation reference (eq:foo)
8436 '("\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" . ((1 markdown-markup-face)
8437 (2 markdown-reference-face)
8438 (3 markdown-markup-face)))
8439 ;; Equation reference \eqref{foo}
8440 '("\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" . ((1 markdown-markup-face)
8441 (2 markdown-reference-face)
8442 (3 markdown-markup-face))))
8443 "Font lock keywords to add and remove when toggling math support.")
8445 (defun markdown-toggle-math (&optional arg)
8446 "Toggle support for inline and display LaTeX math expressions.
8447 With a prefix argument ARG, enable math mode if ARG is positive,
8448 and disable it otherwise. If called from Lisp, enable the mode
8449 if ARG is omitted or nil."
8450 (interactive (list (or current-prefix-arg 'toggle)))
8451 (setq markdown-enable-math
8452 (if (eq arg 'toggle)
8453 (not markdown-enable-math)
8454 (> (prefix-numeric-value arg) 0)))
8455 (if markdown-enable-math
8456 (progn
8457 (font-lock-add-keywords
8458 'markdown-mode markdown-mode-font-lock-keywords-math)
8459 (message "markdown-mode math support enabled"))
8460 (font-lock-remove-keywords
8461 'markdown-mode markdown-mode-font-lock-keywords-math)
8462 (message "markdown-mode math support disabled"))
8463 (markdown-reload-extensions))
8466 ;;; GFM Checkboxes ============================================================
8468 (define-button-type 'markdown-gfm-checkbox-button
8469 'follow-link t
8470 'face 'markdown-gfm-checkbox-face
8471 'mouse-face 'markdown-highlight-face
8472 'action #'markdown-toggle-gfm-checkbox-button)
8474 (defun markdown-gfm-task-list-item-at-point (&optional bounds)
8475 "Return non-nil if there is a GFM task list item at the point.
8476 Optionally, the list item BOUNDS may be given if available, as
8477 returned by `markdown-cur-list-item-bounds'. When a task list item
8478 is found, the return value is the same value returned by
8479 `markdown-cur-list-item-bounds'."
8480 (unless bounds
8481 (setq bounds (markdown-cur-list-item-bounds)))
8482 (> (length (nth 5 bounds)) 0))
8484 (defun markdown-insert-gfm-checkbox ()
8485 "Add GFM checkbox at point.
8486 Returns t if added.
8487 Returns nil if non-applicable."
8488 (interactive)
8489 (let ((bounds (markdown-cur-list-item-bounds)))
8490 (if bounds
8491 (unless (cl-sixth bounds)
8492 (let ((pos (+ (cl-first bounds) (cl-fourth bounds)))
8493 (markup "[ ] "))
8494 (if (< pos (point))
8495 (save-excursion
8496 (goto-char pos)
8497 (insert markup))
8498 (goto-char pos)
8499 (insert markup))
8500 (syntax-propertize (+ (cl-second bounds) 4))
8502 (unless (save-excursion
8503 (back-to-indentation)
8504 (or (markdown-list-item-at-point-p)
8505 (markdown-heading-at-point)
8506 (markdown-in-comment-p)
8507 (markdown-code-block-at-point-p)))
8508 (let ((pos (save-excursion
8509 (back-to-indentation)
8510 (point)))
8511 (markup (concat (or (save-excursion
8512 (beginning-of-line 0)
8513 (cl-fifth (markdown-cur-list-item-bounds)))
8514 markdown-unordered-list-item-prefix)
8515 "[ ] ")))
8516 (if (< pos (point))
8517 (save-excursion
8518 (goto-char pos)
8519 (insert markup))
8520 (goto-char pos)
8521 (insert markup))
8522 (syntax-propertize (point-at-eol))
8523 t)))))
8525 (defun markdown-toggle-gfm-checkbox ()
8526 "Toggle GFM checkbox at point.
8527 Returns the resulting status as a string, either \"[x]\" or \"[ ]\".
8528 Returns nil if there is no task list item at the point."
8529 (interactive)
8530 (save-match-data
8531 (save-excursion
8532 (let ((bounds (markdown-cur-list-item-bounds)))
8533 (when bounds
8534 ;; Move to beginning of task list item
8535 (goto-char (cl-first bounds))
8536 ;; Advance to column of first non-whitespace after marker
8537 (forward-char (cl-fourth bounds))
8538 (cond ((looking-at "\\[ \\]")
8539 (replace-match
8540 (if markdown-gfm-uppercase-checkbox "[X]" "[x]")
8541 nil t)
8542 (match-string-no-properties 0))
8543 ((looking-at "\\[[xX]\\]")
8544 (replace-match "[ ]" nil t)
8545 (match-string-no-properties 0))))))))
8547 (defun markdown-toggle-gfm-checkbox-button (button)
8548 "Toggle GFM checkbox BUTTON on click."
8549 (save-match-data
8550 (save-excursion
8551 (goto-char (button-start button))
8552 (markdown-toggle-gfm-checkbox))))
8554 (defun markdown-make-gfm-checkboxes-buttons (start end)
8555 "Make GFM checkboxes buttons in region between START and END."
8556 (save-excursion
8557 (goto-char start)
8558 (let ((case-fold-search t))
8559 (save-excursion
8560 (while (re-search-forward markdown-regex-gfm-checkbox end t)
8561 (make-button (match-beginning 1) (match-end 1)
8562 :type 'markdown-gfm-checkbox-button))))))
8564 ;; Called when any modification is made to buffer text.
8565 (defun markdown-gfm-checkbox-after-change-function (beg end _)
8566 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
8567 BEG and END are the limits of scanned region."
8568 (save-excursion
8569 (save-match-data
8570 ;; Rescan between start of line from `beg' and start of line after `end'.
8571 (markdown-make-gfm-checkboxes-buttons
8572 (progn (goto-char beg) (beginning-of-line) (point))
8573 (progn (goto-char end) (forward-line 1) (point))))))
8575 (defun markdown-remove-gfm-checkbox-overlays ()
8576 "Remove all GFM checkbox overlays in buffer."
8577 (save-excursion
8578 (save-restriction
8579 (widen)
8580 (remove-overlays nil nil 'face 'markdown-gfm-checkbox-face))))
8583 ;;; Display inline image ======================================================
8585 (defvar-local markdown-inline-image-overlays nil)
8587 (defun markdown-remove-inline-images ()
8588 "Remove inline image overlays from image links in the buffer.
8589 This can be toggled with `markdown-toggle-inline-images'
8590 or \\[markdown-toggle-inline-images]."
8591 (interactive)
8592 (mapc #'delete-overlay markdown-inline-image-overlays)
8593 (setq markdown-inline-image-overlays nil))
8595 (defcustom markdown-display-remote-images nil
8596 "If non-nil, download and display remote images.
8597 See also `markdown-inline-image-overlays'.
8599 Only image URLs specified with a protocol listed in
8600 `markdown-remote-image-protocols' are displayed."
8601 :group 'markdown
8602 :type 'boolean)
8604 (defcustom markdown-remote-image-protocols '("https")
8605 "List of protocols to use to download remote images.
8606 See also `markdown-display-remote-images'."
8607 :group 'markdown
8608 :type '(repeat string))
8610 (defvar markdown--remote-image-cache
8611 (make-hash-table :test 'equal)
8612 "A map from URLs to image paths.")
8614 (defun markdown--get-remote-image (url)
8615 "Retrieve the image path for a given URL."
8616 (or (gethash url markdown--remote-image-cache)
8617 (let ((dl-path (make-temp-file "markdown-mode--image")))
8618 (require 'url)
8619 (url-copy-file url dl-path t)
8620 (puthash url dl-path markdown--remote-image-cache))))
8622 (defun markdown-display-inline-images ()
8623 "Add inline image overlays to image links in the buffer.
8624 This can be toggled with `markdown-toggle-inline-images'
8625 or \\[markdown-toggle-inline-images]."
8626 (interactive)
8627 (unless (display-images-p)
8628 (error "Cannot show images"))
8629 (save-excursion
8630 (save-restriction
8631 (widen)
8632 (goto-char (point-min))
8633 (while (re-search-forward markdown-regex-link-inline nil t)
8634 (let* ((start (match-beginning 0))
8635 (imagep (match-beginning 1))
8636 (end (match-end 0))
8637 (file (match-string-no-properties 6)))
8638 (when (and imagep
8639 (not (zerop (length file))))
8640 (unless (file-exists-p file)
8641 (let* ((download-file (funcall markdown-translate-filename-function file))
8642 (valid-url (ignore-errors
8643 (member (downcase (url-type (url-generic-parse-url download-file)))
8644 markdown-remote-image-protocols))))
8645 (if (and markdown-display-remote-images valid-url)
8646 (setq file (markdown--get-remote-image download-file))
8647 (when (not valid-url)
8648 ;; strip query parameter
8649 (setq file (replace-regexp-in-string "?.+\\'" "" file))
8650 (unless (file-exists-p file)
8651 (setq file (url-unhex-string file)))))))
8652 (when (file-exists-p file)
8653 (let* ((abspath (if (file-name-absolute-p file)
8654 file
8655 (concat default-directory file)))
8656 (image
8657 (cond ((and markdown-max-image-size
8658 (image-type-available-p 'imagemagick))
8659 (create-image
8660 abspath 'imagemagick nil
8661 :max-width (car markdown-max-image-size)
8662 :max-height (cdr markdown-max-image-size)))
8663 (markdown-max-image-size
8664 (create-image abspath nil nil
8665 :max-width (car markdown-max-image-size)
8666 :max-height (cdr markdown-max-image-size)))
8667 (t (create-image abspath)))))
8668 (when image
8669 (let ((ov (make-overlay start end)))
8670 (overlay-put ov 'display image)
8671 (overlay-put ov 'face 'default)
8672 (push ov markdown-inline-image-overlays)))))))))))
8674 (defun markdown-toggle-inline-images ()
8675 "Toggle inline image overlays in the buffer."
8676 (interactive)
8677 (if markdown-inline-image-overlays
8678 (markdown-remove-inline-images)
8679 (markdown-display-inline-images)))
8682 ;;; GFM Code Block Fontification ==============================================
8684 (defcustom markdown-fontify-code-blocks-natively nil
8685 "When non-nil, fontify code in code blocks using the native major mode.
8686 This only works for fenced code blocks where the language is
8687 specified where we can automatically determine the appropriate
8688 mode to use. The language to mode mapping may be customized by
8689 setting the variable `markdown-code-lang-modes'."
8690 :group 'markdown
8691 :type 'boolean
8692 :safe #'booleanp
8693 :package-version '(markdown-mode . "2.3"))
8695 (defcustom markdown-fontify-code-block-default-mode nil
8696 "Default mode to use to fontify code blocks.
8697 This mode is used when automatic detection fails, such as for GFM
8698 code blocks with no language specified."
8699 :group 'markdown
8700 :type '(choice function (const :tag "None" nil))
8701 :package-version '(markdown-mode . "2.4"))
8703 (defun markdown-toggle-fontify-code-blocks-natively (&optional arg)
8704 "Toggle the native fontification of code blocks.
8705 With a prefix argument ARG, enable if ARG is positive,
8706 and disable otherwise."
8707 (interactive (list (or current-prefix-arg 'toggle)))
8708 (setq markdown-fontify-code-blocks-natively
8709 (if (eq arg 'toggle)
8710 (not markdown-fontify-code-blocks-natively)
8711 (> (prefix-numeric-value arg) 0)))
8712 (if markdown-fontify-code-blocks-natively
8713 (message "markdown-mode native code block fontification enabled")
8714 (message "markdown-mode native code block fontification disabled"))
8715 (markdown-reload-extensions))
8717 ;; This is based on `org-src-lang-modes' from org-src.el
8718 (defcustom markdown-code-lang-modes
8719 '(("ocaml" . tuareg-mode) ("elisp" . emacs-lisp-mode) ("ditaa" . artist-mode)
8720 ("asymptote" . asy-mode) ("dot" . fundamental-mode) ("sqlite" . sql-mode)
8721 ("calc" . fundamental-mode) ("C" . c-mode) ("cpp" . c++-mode)
8722 ("C++" . c++-mode) ("screen" . shell-script-mode) ("shell" . sh-mode)
8723 ("bash" . sh-mode))
8724 "Alist mapping languages to their major mode.
8725 The key is the language name, the value is the major mode. For
8726 many languages this is simple, but for language where this is not
8727 the case, this variable provides a way to simplify things on the
8728 user side. For example, there is no ocaml-mode in Emacs, but the
8729 mode to use is `tuareg-mode'."
8730 :group 'markdown
8731 :type '(repeat
8732 (cons
8733 (string "Language name")
8734 (symbol "Major mode")))
8735 :package-version '(markdown-mode . "2.3"))
8737 (defun markdown-get-lang-mode (lang)
8738 "Return major mode that should be used for LANG.
8739 LANG is a string, and the returned major mode is a symbol."
8740 (cl-find-if
8741 'fboundp
8742 (list (cdr (assoc lang markdown-code-lang-modes))
8743 (cdr (assoc (downcase lang) markdown-code-lang-modes))
8744 (intern (concat lang "-mode"))
8745 (intern (concat (downcase lang) "-mode")))))
8747 (defun markdown-fontify-code-blocks-generic (matcher last)
8748 "Add text properties to next code block from point to LAST.
8749 Use matching function MATCHER."
8750 (when (funcall matcher last)
8751 (save-excursion
8752 (save-match-data
8753 (let* ((start (match-beginning 0))
8754 (end (match-end 0))
8755 ;; Find positions outside opening and closing backquotes.
8756 (bol-prev (progn (goto-char start)
8757 (if (bolp) (point-at-bol 0) (point-at-bol))))
8758 (eol-next (progn (goto-char end)
8759 (if (bolp) (point-at-bol 2) (point-at-bol 3))))
8760 lang)
8761 (if (and markdown-fontify-code-blocks-natively
8762 (or (setq lang (markdown-code-block-lang))
8763 markdown-fontify-code-block-default-mode))
8764 (markdown-fontify-code-block-natively lang start end)
8765 (add-text-properties start end '(face markdown-pre-face)))
8766 ;; Set background for block as well as opening and closing lines.
8767 (font-lock-append-text-property
8768 bol-prev eol-next 'face 'markdown-code-face)
8769 ;; Set invisible property for lines before and after, including newline.
8770 (add-text-properties bol-prev start '(invisible markdown-markup))
8771 (add-text-properties end eol-next '(invisible markdown-markup)))))
8774 (defun markdown-fontify-gfm-code-blocks (last)
8775 "Add text properties to next GFM code block from point to LAST."
8776 (markdown-fontify-code-blocks-generic 'markdown-match-gfm-code-blocks last))
8778 (defun markdown-fontify-fenced-code-blocks (last)
8779 "Add text properties to next tilde fenced code block from point to LAST."
8780 (markdown-fontify-code-blocks-generic 'markdown-match-fenced-code-blocks last))
8782 ;; Based on `org-src-font-lock-fontify-block' from org-src.el.
8783 (defun markdown-fontify-code-block-natively (lang start end)
8784 "Fontify given GFM or fenced code block.
8785 This function is called by Emacs for automatic fontification when
8786 `markdown-fontify-code-blocks-natively' is non-nil. LANG is the
8787 language used in the block. START and END specify the block
8788 position."
8789 (let ((lang-mode (if lang (markdown-get-lang-mode lang)
8790 markdown-fontify-code-block-default-mode)))
8791 (when (fboundp lang-mode)
8792 (let ((string (buffer-substring-no-properties start end))
8793 (modified (buffer-modified-p))
8794 (markdown-buffer (current-buffer)) pos next)
8795 (remove-text-properties start end '(face nil))
8796 (with-current-buffer
8797 (get-buffer-create
8798 (concat " markdown-code-fontification:" (symbol-name lang-mode)))
8799 ;; Make sure that modification hooks are not inhibited in
8800 ;; the org-src-fontification buffer in case we're called
8801 ;; from `jit-lock-function' (Bug#25132).
8802 (let ((inhibit-modification-hooks nil))
8803 (delete-region (point-min) (point-max))
8804 (insert string " ")) ;; so there's a final property change
8805 (unless (eq major-mode lang-mode) (funcall lang-mode))
8806 (font-lock-ensure)
8807 (setq pos (point-min))
8808 (while (setq next (next-single-property-change pos 'face))
8809 (let ((val (get-text-property pos 'face)))
8810 (when val
8811 (put-text-property
8812 (+ start (1- pos)) (1- (+ start next)) 'face
8813 val markdown-buffer)))
8814 (setq pos next)))
8815 (add-text-properties
8816 start end
8817 '(font-lock-fontified t fontified t font-lock-multiline t))
8818 (set-buffer-modified-p modified)))))
8820 (require 'edit-indirect nil t)
8821 (defvar edit-indirect-guess-mode-function)
8822 (defvar edit-indirect-after-commit-functions)
8824 (defun markdown--edit-indirect-after-commit-function (beg end)
8825 "Corrective logic run on code block content from lines BEG to END.
8826 Restores code block indentation from BEG to END, and ensures trailing newlines
8827 at the END of code blocks."
8828 ;; ensure trailing newlines
8829 (goto-char end)
8830 (unless (eq (char-before) ?\n)
8831 (insert "\n"))
8832 ;; restore code block indentation
8833 (goto-char (- beg 1))
8834 (let ((block-indentation (current-indentation)))
8835 (when (> block-indentation 0)
8836 (indent-rigidly beg end block-indentation)))
8837 (font-lock-ensure))
8839 (defun markdown-edit-code-block ()
8840 "Edit Markdown code block in an indirect buffer."
8841 (interactive)
8842 (save-excursion
8843 (if (fboundp 'edit-indirect-region)
8844 (let* ((bounds (markdown-get-enclosing-fenced-block-construct))
8845 (begin (and bounds (not (null (nth 0 bounds))) (goto-char (nth 0 bounds)) (point-at-bol 2)))
8846 (end (and bounds(not (null (nth 1 bounds))) (goto-char (nth 1 bounds)) (point-at-bol 1))))
8847 (if (and begin end)
8848 (let* ((indentation (and (goto-char (nth 0 bounds)) (current-indentation)))
8849 (lang (markdown-code-block-lang))
8850 (mode (or (and lang (markdown-get-lang-mode lang))
8851 markdown-edit-code-block-default-mode))
8852 (edit-indirect-guess-mode-function
8853 (lambda (_parent-buffer _beg _end)
8854 (funcall mode)))
8855 (indirect-buf (edit-indirect-region begin end 'display-buffer)))
8856 ;; reset `sh-shell' when indirect buffer
8857 (when (and (not (member system-type '(ms-dos windows-nt)))
8858 (member mode '(shell-script-mode sh-mode))
8859 (member lang (append
8860 (mapcar (lambda (e) (symbol-name (car e)))
8861 sh-ancestor-alist)
8862 '("csh" "rc" "sh"))))
8863 (with-current-buffer indirect-buf
8864 (sh-set-shell lang)))
8865 (when (> indentation 0) ;; un-indent in edit-indirect buffer
8866 (with-current-buffer indirect-buf
8867 (indent-rigidly (point-min) (point-max) (- indentation)))))
8868 (user-error "Not inside a GFM or tilde fenced code block")))
8869 (when (y-or-n-p "Package edit-indirect needed to edit code blocks. Install it now? ")
8870 (progn (package-refresh-contents)
8871 (package-install 'edit-indirect)
8872 (markdown-edit-code-block))))))
8875 ;;; Table Editing =============================================================
8877 ;; These functions were originally adapted from `org-table.el'.
8879 ;; General helper functions
8881 (defmacro markdown--with-gensyms (symbols &rest body)
8882 (declare (debug (sexp body)) (indent 1))
8883 `(let ,(mapcar (lambda (s)
8884 `(,s (make-symbol (concat "--" (symbol-name ',s)))))
8885 symbols)
8886 ,@body))
8888 (defun markdown--split-string (string &optional separators)
8889 "Splits STRING into substrings at SEPARATORS.
8890 SEPARATORS is a regular expression. If nil it defaults to
8891 `split-string-default-separators'. This version returns no empty
8892 strings if there are matches at the beginning and end of string."
8893 (let ((start 0) notfirst list)
8894 (while (and (string-match
8895 (or separators split-string-default-separators)
8896 string
8897 (if (and notfirst
8898 (= start (match-beginning 0))
8899 (< start (length string)))
8900 (1+ start) start))
8901 (< (match-beginning 0) (length string)))
8902 (setq notfirst t)
8903 (or (eq (match-beginning 0) 0)
8904 (and (eq (match-beginning 0) (match-end 0))
8905 (eq (match-beginning 0) start))
8906 (push (substring string start (match-beginning 0)) list))
8907 (setq start (match-end 0)))
8908 (or (eq start (length string))
8909 (push (substring string start) list))
8910 (nreverse list)))
8912 (defun markdown--string-width (s)
8913 "Return width of string S.
8914 This version ignores characters with invisibility property
8915 `markdown-markup'."
8916 (let (b)
8917 (when (or (eq t buffer-invisibility-spec)
8918 (member 'markdown-markup buffer-invisibility-spec))
8919 (while (setq b (text-property-any
8920 0 (length s)
8921 'invisible 'markdown-markup s))
8922 (setq s (concat
8923 (substring s 0 b)
8924 (substring s (or (next-single-property-change
8925 b 'invisible s)
8926 (length s))))))))
8927 (string-width s))
8929 (defun markdown--remove-invisible-markup (s)
8930 "Remove Markdown markup from string S.
8931 This version removes characters with invisibility property
8932 `markdown-markup'."
8933 (let (b)
8934 (while (setq b (text-property-any
8935 0 (length s)
8936 'invisible 'markdown-markup s))
8937 (setq s (concat
8938 (substring s 0 b)
8939 (substring s (or (next-single-property-change
8940 b 'invisible s)
8941 (length s)))))))
8944 ;; Functions for maintaining tables
8946 (defvar markdown-table-at-point-p-function #'markdown--table-at-point-p
8947 "Function to decide if point is inside a table.
8949 The indirection serves to differentiate between standard markdown
8950 tables and gfm tables which are less strict about the markup.")
8952 (defconst markdown-table-line-regexp "^[ \t]*|"
8953 "Regexp matching any line inside a table.")
8955 (defconst markdown-table-hline-regexp "^[ \t]*|[-:]"
8956 "Regexp matching hline inside a table.")
8958 (defconst markdown-table-dline-regexp "^[ \t]*|[^-:]"
8959 "Regexp matching dline inside a table.")
8961 (defun markdown-table-at-point-p ()
8962 "Return non-nil when point is inside a table."
8963 (funcall markdown-table-at-point-p-function))
8965 (defun markdown--table-at-point-p ()
8966 "Return non-nil when point is inside a table."
8967 (save-excursion
8968 (beginning-of-line)
8969 (and (looking-at-p markdown-table-line-regexp)
8970 (not (markdown-code-block-at-point-p)))))
8972 (defconst gfm-table-line-regexp "^.?*|"
8973 "Regexp matching any line inside a table.")
8975 (defconst gfm-table-hline-regexp "^-+\\(|-\\)+"
8976 "Regexp matching hline inside a table.")
8978 ;; GFM simplified tables syntax is as follows:
8979 ;; - A header line for the column names, this is any text
8980 ;; separated by `|'.
8981 ;; - Followed by a string -|-|- ..., the number of dashes is optional
8982 ;; but must be higher than 1. The number of separators should match
8983 ;; the number of columns.
8984 ;; - Followed by the rows of data, which has the same format as the
8985 ;; header line.
8986 ;; Example:
8988 ;; foo | bar
8989 ;; ------|---------
8990 ;; bar | baz
8991 ;; bar | baz
8992 (defun gfm--table-at-point-p ()
8993 "Return non-nil when point is inside a gfm-compatible table."
8994 (or (markdown--table-at-point-p)
8995 (save-excursion
8996 (beginning-of-line)
8997 (when (looking-at-p gfm-table-line-regexp)
8998 ;; we might be at the first line of the table, check if the
8999 ;; line below is the hline
9000 (or (save-excursion
9001 (forward-line 1)
9002 (looking-at-p gfm-table-hline-regexp))
9003 ;; go up to find the header
9004 (catch 'done
9005 (while (looking-at-p gfm-table-line-regexp)
9006 (cond
9007 ((looking-at-p gfm-table-hline-regexp)
9008 (throw 'done t))
9009 ((bobp)
9010 (throw 'done nil)))
9011 (forward-line -1))
9012 nil))))))
9014 (defun markdown-table-hline-at-point-p ()
9015 "Return non-nil when point is on a hline in a table.
9016 This function assumes point is on a table."
9017 (save-excursion
9018 (beginning-of-line)
9019 (looking-at-p markdown-table-hline-regexp)))
9021 (defun markdown-table-begin ()
9022 "Find the beginning of the table and return its position.
9023 This function assumes point is on a table."
9024 (save-excursion
9025 (while (and (not (bobp))
9026 (markdown-table-at-point-p))
9027 (forward-line -1))
9028 (unless (or (eobp)
9029 (markdown-table-at-point-p))
9030 (forward-line 1))
9031 (point)))
9033 (defun markdown-table-end ()
9034 "Find the end of the table and return its position.
9035 This function assumes point is on a table."
9036 (save-excursion
9037 (while (and (not (eobp))
9038 (markdown-table-at-point-p))
9039 (forward-line 1))
9040 (point)))
9042 (defun markdown-table-get-dline ()
9043 "Return index of the table data line at point.
9044 This function assumes point is on a table."
9045 (let ((pos (point)) (end (markdown-table-end)) (cnt 0))
9046 (save-excursion
9047 (goto-char (markdown-table-begin))
9048 (while (and (re-search-forward
9049 markdown-table-dline-regexp end t)
9050 (setq cnt (1+ cnt))
9051 (< (point-at-eol) pos))))
9052 cnt))
9054 (defun markdown--thing-at-wiki-link (pos)
9055 (when markdown-enable-wiki-links
9056 (save-excursion
9057 (save-match-data
9058 (goto-char pos)
9059 (thing-at-point-looking-at markdown-regex-wiki-link)))))
9061 (defun markdown-table-get-column ()
9062 "Return table column at point.
9063 This function assumes point is on a table."
9064 (let ((pos (point)) (cnt 0))
9065 (save-excursion
9066 (beginning-of-line)
9067 (while (search-forward "|" pos t)
9068 (when (and (not (looking-back "\\\\|" (line-beginning-position)))
9069 (not (markdown--thing-at-wiki-link (match-beginning 0))))
9070 (setq cnt (1+ cnt)))))
9071 cnt))
9073 (defun markdown-table-get-cell (&optional n)
9074 "Return the content of the cell in column N of current row.
9075 N defaults to column at point. This function assumes point is on
9076 a table."
9077 (and n (markdown-table-goto-column n))
9078 (skip-chars-backward "^|\n") (backward-char 1)
9079 (if (looking-at "|[^|\r\n]*")
9080 (let* ((pos (match-beginning 0))
9081 (val (buffer-substring (1+ pos) (match-end 0))))
9082 (goto-char (min (point-at-eol) (+ 2 pos)))
9083 ;; Trim whitespaces
9084 (setq val (replace-regexp-in-string "\\`[ \t]+" "" val)
9085 val (replace-regexp-in-string "[ \t]+\\'" "" val)))
9086 (forward-char 1) ""))
9088 (defun markdown-table-goto-dline (n)
9089 "Go to the Nth data line in the table at point.
9090 Return t when the line exists, nil otherwise. This function
9091 assumes point is on a table."
9092 (goto-char (markdown-table-begin))
9093 (let ((end (markdown-table-end)) (cnt 0))
9094 (while (and (re-search-forward
9095 markdown-table-dline-regexp end t)
9096 (< (setq cnt (1+ cnt)) n)))
9097 (= cnt n)))
9099 (defun markdown-table-goto-column (n &optional on-delim)
9100 "Go to the Nth column in the table line at point.
9101 With optional argument ON-DELIM, stop with point before the left
9102 delimiter of the cell. If there are less than N cells, just go
9103 beyond the last delimiter. This function assumes point is on a
9104 table."
9105 (beginning-of-line 1)
9106 (when (> n 0)
9107 (while (and (> n 0) (search-forward "|" (point-at-eol) t))
9108 (when (and (not (looking-back "\\\\|" (line-beginning-position)))
9109 (not (markdown--thing-at-wiki-link (match-beginning 0))))
9110 (cl-decf n)))
9111 (if on-delim
9112 (backward-char 1)
9113 (when (looking-at " ") (forward-char 1)))))
9115 (defmacro markdown-table-save-cell (&rest body)
9116 "Save cell at point, execute BODY and restore cell.
9117 This function assumes point is on a table."
9118 (declare (debug (body)))
9119 (markdown--with-gensyms (line column)
9120 `(let ((,line (copy-marker (line-beginning-position)))
9121 (,column (markdown-table-get-column)))
9122 (unwind-protect
9123 (progn ,@body)
9124 (goto-char ,line)
9125 (markdown-table-goto-column ,column)
9126 (set-marker ,line nil)))))
9128 (defun markdown-table-blank-line (s)
9129 "Convert a table line S into a line with blank cells."
9130 (if (string-match "^[ \t]*|-" s)
9131 (setq s (mapconcat
9132 (lambda (x) (if (member x '(?| ?+)) "|" " "))
9133 s ""))
9134 (with-temp-buffer
9135 (insert s)
9136 (goto-char (point-min))
9137 (when (re-search-forward "|" nil t)
9138 (let ((cur (point))
9139 ret)
9140 (while (re-search-forward "|" nil t)
9141 (when (and (not (eql (char-before (match-beginning 0)) ?\\))
9142 (not (markdown--thing-at-wiki-link (match-beginning 0))))
9143 (push (make-string (- (match-beginning 0) cur) ? ) ret)
9144 (setq cur (match-end 0))))
9145 (format "|%s|" (string-join (nreverse ret) "|")))))))
9147 (defun markdown-table-colfmt (fmtspec)
9148 "Process column alignment specifier FMTSPEC for tables."
9149 (when (stringp fmtspec)
9150 (mapcar (lambda (x)
9151 (cond ((string-match-p "^:.*:$" x) 'c)
9152 ((string-match-p "^:" x) 'l)
9153 ((string-match-p ":$" x) 'r)
9154 (t 'd)))
9155 (markdown--split-string fmtspec "\\s-*|\\s-*"))))
9157 (defun markdown--first-column-p (bar-pos)
9158 (save-excursion
9159 (save-match-data
9160 (goto-char bar-pos)
9161 (looking-back "^\\s-*" (line-beginning-position)))))
9163 (defun markdown--table-line-to-columns (line)
9164 (with-temp-buffer
9165 (insert line)
9166 (goto-char (point-min))
9167 (let ((cur (point))
9168 ret)
9169 (while (re-search-forward "\\s-*\\(|\\)\\s-*" nil t)
9170 (if (markdown--first-column-p (match-beginning 1))
9171 (setq cur (match-end 0))
9172 (cond ((eql (char-before (match-beginning 1)) ?\\)
9173 ;; keep spaces
9174 (goto-char (match-end 1)))
9175 ((markdown--thing-at-wiki-link (match-beginning 1))) ;; do nothing
9177 (push (buffer-substring-no-properties cur (match-beginning 0)) ret)
9178 (setq cur (match-end 0))))))
9179 (when (< cur (length line))
9180 (push (buffer-substring-no-properties cur (point-max)) ret))
9181 (nreverse ret))))
9183 (defun markdown-table-align ()
9184 "Align table at point.
9185 This function assumes point is on a table."
9186 (interactive)
9187 (let ((begin (markdown-table-begin))
9188 (end (copy-marker (markdown-table-end))))
9189 (markdown-table-save-cell
9190 (goto-char begin)
9191 (let* (fmtspec
9192 ;; Store table indent
9193 (indent (progn (looking-at "[ \t]*") (match-string 0)))
9194 ;; Split table in lines and save column format specifier
9195 (lines (mapcar (lambda (l)
9196 (if (string-match-p "\\`[ \t]*|[ \t]*[-:]" l)
9197 (progn (setq fmtspec (or fmtspec l)) nil) l))
9198 (markdown--split-string (buffer-substring begin end) "\n")))
9199 ;; Split lines in cells
9200 (cells (mapcar (lambda (l) (markdown--table-line-to-columns l))
9201 (remq nil lines)))
9202 ;; Calculate maximum number of cells in a line
9203 (maxcells (if cells
9204 (apply #'max (mapcar #'length cells))
9205 (user-error "Empty table")))
9206 ;; Empty cells to fill short lines
9207 (emptycells (make-list maxcells ""))
9208 maxwidths)
9209 ;; Calculate maximum width for each column
9210 (dotimes (i maxcells)
9211 (let ((column (mapcar (lambda (x) (or (nth i x) "")) cells)))
9212 (push (apply #'max 1 (mapcar #'markdown--string-width column))
9213 maxwidths)))
9214 (setq maxwidths (nreverse maxwidths))
9215 ;; Process column format specifier
9216 (setq fmtspec (markdown-table-colfmt fmtspec))
9217 ;; Compute formats needed for output of table lines
9218 (let ((hfmt (concat indent "|"))
9219 (rfmt (concat indent "|"))
9220 hfmt1 rfmt1 fmt)
9221 (dolist (width maxwidths (setq hfmt (concat (substring hfmt 0 -1) "|")))
9222 (setq fmt (pop fmtspec))
9223 (cond ((equal fmt 'l) (setq hfmt1 ":%s-|" rfmt1 " %%-%ds |"))
9224 ((equal fmt 'r) (setq hfmt1 "-%s:|" rfmt1 " %%%ds |"))
9225 ((equal fmt 'c) (setq hfmt1 ":%s:|" rfmt1 " %%-%ds |"))
9226 (t (setq hfmt1 "-%s-|" rfmt1 " %%-%ds |")))
9227 (setq rfmt (concat rfmt (format rfmt1 width)))
9228 (setq hfmt (concat hfmt (format hfmt1 (make-string width ?-)))))
9229 ;; Replace modified lines only
9230 (dolist (line lines)
9231 (let ((line (if line
9232 (apply #'format rfmt (append (pop cells) emptycells))
9233 hfmt))
9234 (previous (buffer-substring (point) (line-end-position))))
9235 (if (equal previous line)
9236 (forward-line)
9237 (insert line "\n")
9238 (delete-region (point) (line-beginning-position 2))))))
9239 (set-marker end nil)))))
9241 (defun markdown-table-insert-row (&optional arg)
9242 "Insert a new row above the row at point into the table.
9243 With optional argument ARG, insert below the current row."
9244 (interactive "P")
9245 (unless (markdown-table-at-point-p)
9246 (user-error "Not at a table"))
9247 (let* ((line (buffer-substring
9248 (line-beginning-position) (line-end-position)))
9249 (new (markdown-table-blank-line line)))
9250 (beginning-of-line (if arg 2 1))
9251 (unless (bolp) (insert "\n"))
9252 (insert-before-markers new "\n")
9253 (beginning-of-line 0)
9254 (re-search-forward "| ?" (line-end-position) t)))
9256 (defun markdown-table-delete-row ()
9257 "Delete row or horizontal line at point from the table."
9258 (interactive)
9259 (unless (markdown-table-at-point-p)
9260 (user-error "Not at a table"))
9261 (let ((col (current-column)))
9262 (kill-region (point-at-bol)
9263 (min (1+ (point-at-eol)) (point-max)))
9264 (unless (markdown-table-at-point-p) (beginning-of-line 0))
9265 (move-to-column col)))
9267 (defun markdown-table-move-row (&optional up)
9268 "Move table line at point down.
9269 With optional argument UP, move it up."
9270 (interactive "P")
9271 (unless (markdown-table-at-point-p)
9272 (user-error "Not at a table"))
9273 (let* ((col (current-column)) (pos (point))
9274 (tonew (if up 0 2)) txt)
9275 (beginning-of-line tonew)
9276 (unless (markdown-table-at-point-p)
9277 (goto-char pos) (user-error "Cannot move row further"))
9278 (goto-char pos) (beginning-of-line 1) (setq pos (point))
9279 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9280 (delete-region (point) (1+ (point-at-eol)))
9281 (beginning-of-line tonew)
9282 (insert txt) (beginning-of-line 0)
9283 (move-to-column col)))
9285 (defun markdown-table-move-row-up ()
9286 "Move table row at point up."
9287 (interactive)
9288 (markdown-table-move-row 'up))
9290 (defun markdown-table-move-row-down ()
9291 "Move table row at point down."
9292 (interactive)
9293 (markdown-table-move-row nil))
9295 (defun markdown-table-insert-column ()
9296 "Insert a new table column."
9297 (interactive)
9298 (unless (markdown-table-at-point-p)
9299 (user-error "Not at a table"))
9300 (let* ((col (max 1 (markdown-table-get-column)))
9301 (begin (markdown-table-begin))
9302 (end (copy-marker (markdown-table-end))))
9303 (markdown-table-save-cell
9304 (goto-char begin)
9305 (while (< (point) end)
9306 (markdown-table-goto-column col t)
9307 (if (markdown-table-hline-at-point-p)
9308 (insert "|---")
9309 (insert "| "))
9310 (forward-line)))
9311 (set-marker end nil)
9312 (when markdown-table-align-p
9313 (markdown-table-align))))
9315 (defun markdown-table-delete-column ()
9316 "Delete column at point from table."
9317 (interactive)
9318 (unless (markdown-table-at-point-p)
9319 (user-error "Not at a table"))
9320 (let ((col (markdown-table-get-column))
9321 (begin (markdown-table-begin))
9322 (end (copy-marker (markdown-table-end))))
9323 (markdown-table-save-cell
9324 (goto-char begin)
9325 (while (< (point) end)
9326 (markdown-table-goto-column col t)
9327 (and (looking-at "|\\(?:\\\\|\\|[^|\n]\\)+|")
9328 (replace-match "|"))
9329 (forward-line)))
9330 (set-marker end nil)
9331 (markdown-table-goto-column (max 1 (1- col)))
9332 (when markdown-table-align-p
9333 (markdown-table-align))))
9335 (defun markdown-table-move-column (&optional left)
9336 "Move table column at point to the right.
9337 With optional argument LEFT, move it to the left."
9338 (interactive "P")
9339 (unless (markdown-table-at-point-p)
9340 (user-error "Not at a table"))
9341 (let* ((col (markdown-table-get-column))
9342 (col1 (if left (1- col) col))
9343 (colpos (if left (1- col) (1+ col)))
9344 (begin (markdown-table-begin))
9345 (end (copy-marker (markdown-table-end))))
9346 (when (and left (= col 1))
9347 (user-error "Cannot move column further left"))
9348 (when (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9349 (user-error "Cannot move column further right"))
9350 (markdown-table-save-cell
9351 (goto-char begin)
9352 (while (< (point) end)
9353 (markdown-table-goto-column col1 t)
9354 (when (looking-at "|\\(\\(?:\\\\|\\|[^|\n]\\|\\)+\\)|\\(\\(?:\\\\|\\|[^|\n]\\|\\)+\\)|")
9355 (replace-match "|\\2|\\1|"))
9356 (forward-line)))
9357 (set-marker end nil)
9358 (markdown-table-goto-column colpos)
9359 (when markdown-table-align-p
9360 (markdown-table-align))))
9362 (defun markdown-table-move-column-left ()
9363 "Move table column at point to the left."
9364 (interactive)
9365 (markdown-table-move-column 'left))
9367 (defun markdown-table-move-column-right ()
9368 "Move table column at point to the right."
9369 (interactive)
9370 (markdown-table-move-column nil))
9372 (defun markdown-table-next-row ()
9373 "Go to the next row (same column) in the table.
9374 Create new table lines if required."
9375 (interactive)
9376 (unless (markdown-table-at-point-p)
9377 (user-error "Not at a table"))
9378 (if (or (looking-at "[ \t]*$")
9379 (save-excursion (skip-chars-backward " \t") (bolp)))
9380 (newline)
9381 (when markdown-table-align-p
9382 (markdown-table-align))
9383 (let ((col (markdown-table-get-column)))
9384 (beginning-of-line 2)
9385 (if (or (not (markdown-table-at-point-p))
9386 (markdown-table-hline-at-point-p))
9387 (progn
9388 (beginning-of-line 0)
9389 (markdown-table-insert-row 'below)))
9390 (markdown-table-goto-column col)
9391 (skip-chars-backward "^|\n\r")
9392 (when (looking-at " ") (forward-char 1)))))
9394 (defun markdown-table-forward-cell ()
9395 "Go to the next cell in the table.
9396 Create new table lines if required."
9397 (interactive)
9398 (unless (markdown-table-at-point-p)
9399 (user-error "Not at a table"))
9400 (when markdown-table-align-p
9401 (markdown-table-align))
9402 (let ((end (markdown-table-end)))
9403 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9404 (condition-case nil
9405 (progn
9406 (re-search-forward "\\(?:^\\|[^\\]\\)|" end)
9407 (when (looking-at "[ \t]*$")
9408 (re-search-forward "\\(?:^\\|[^\\]:\\)|" end))
9409 (when (and (looking-at "[-:]")
9410 (re-search-forward "^\\(?:[ \t]*\\|[^\\]\\)|\\([^-:]\\)" end t))
9411 (goto-char (match-beginning 1)))
9412 (if (looking-at "[-:]")
9413 (progn
9414 (beginning-of-line 0)
9415 (markdown-table-insert-row 'below))
9416 (when (looking-at " ") (forward-char 1))))
9417 (error (markdown-table-insert-row 'below)))))
9419 (defun markdown-table-backward-cell ()
9420 "Go to the previous cell in the table."
9421 (interactive)
9422 (unless (markdown-table-at-point-p)
9423 (user-error "Not at a table"))
9424 (when markdown-table-align-p
9425 (markdown-table-align))
9426 (when (markdown-table-hline-at-point-p) (beginning-of-line 1))
9427 (condition-case nil
9428 (progn
9429 (re-search-backward "\\(?:^\\|[^\\]\\)|" (markdown-table-begin))
9430 ;; When this function is called while in the first cell in a
9431 ;; table, the point will now be at the beginning of a line. In
9432 ;; this case, we need to move past one additional table
9433 ;; boundary, the end of the table on the previous line.
9434 (when (= (point) (line-beginning-position))
9435 (re-search-backward "\\(?:^\\|[^\\]\\)|" (markdown-table-begin)))
9436 (re-search-backward "\\(?:^\\|[^\\]\\)|" (markdown-table-begin)))
9437 (error (user-error "Cannot move to previous table cell")))
9438 (when (looking-at "\\(?:^\\|[^\\]\\)| ?") (goto-char (match-end 0)))
9440 ;; This may have dropped point on the hline.
9441 (when (markdown-table-hline-at-point-p)
9442 (markdown-table-backward-cell)))
9444 (defun markdown-table-transpose ()
9445 "Transpose table at point.
9446 Horizontal separator lines will be eliminated."
9447 (interactive)
9448 (unless (markdown-table-at-point-p)
9449 (user-error "Not at a table"))
9450 (let* ((table (buffer-substring-no-properties
9451 (markdown-table-begin) (markdown-table-end)))
9452 ;; Convert table to Lisp structure
9453 (table (delq nil
9454 (mapcar
9455 (lambda (x)
9456 (unless (string-match-p
9457 markdown-table-hline-regexp x)
9458 (markdown--table-line-to-columns x)))
9459 (markdown--split-string table "[ \t]*\n[ \t]*"))))
9460 (dline_old (markdown-table-get-dline))
9461 (col_old (markdown-table-get-column))
9462 (contents (mapcar (lambda (_)
9463 (let ((tp table))
9464 (mapcar
9465 (lambda (_)
9466 (prog1
9467 (pop (car tp))
9468 (setq tp (cdr tp))))
9469 table)))
9470 (car table))))
9471 (goto-char (markdown-table-begin))
9472 (save-excursion
9473 (re-search-forward "|") (backward-char)
9474 (delete-region (point) (markdown-table-end))
9475 (insert (mapconcat
9476 (lambda(x)
9477 (concat "| " (mapconcat 'identity x " | " ) " |\n"))
9478 contents "")))
9479 (markdown-table-goto-dline col_old)
9480 (markdown-table-goto-column dline_old))
9481 (when markdown-table-align-p
9482 (markdown-table-align)))
9484 (defun markdown-table-sort-lines (&optional sorting-type)
9485 "Sort table lines according to the column at point.
9487 The position of point indicates the column to be used for
9488 sorting, and the range of lines is the range between the nearest
9489 horizontal separator lines, or the entire table of no such lines
9490 exist. If point is before the first column, user will be prompted
9491 for the sorting column. If there is an active region, the mark
9492 specifies the first line and the sorting column, while point
9493 should be in the last line to be included into the sorting.
9495 The command then prompts for the sorting type which can be
9496 alphabetically or numerically. Sorting in reverse order is also
9497 possible.
9499 If SORTING-TYPE is specified when this function is called from a
9500 Lisp program, no prompting will take place. SORTING-TYPE must be
9501 a character, any of (?a ?A ?n ?N) where the capital letters
9502 indicate that sorting should be done in reverse order."
9503 (interactive)
9504 (unless (markdown-table-at-point-p)
9505 (user-error "Not at a table"))
9506 ;; Set sorting type and column used for sorting
9507 (let ((column (let ((c (markdown-table-get-column)))
9508 (cond ((> c 0) c)
9509 ((called-interactively-p 'any)
9510 (read-number "Use column N for sorting: "))
9511 (t 1))))
9512 (sorting-type
9513 (or sorting-type
9514 (progn
9515 ;; workaround #641
9516 ;; Emacs < 28 hides prompt message by another message. This erases it.
9517 (message "")
9518 (read-char-exclusive
9519 "Sort type: [a]lpha [n]umeric (A/N means reversed): ")))))
9520 (save-restriction
9521 ;; Narrow buffer to appropriate sorting area
9522 (if (region-active-p)
9523 (narrow-to-region
9524 (save-excursion
9525 (progn
9526 (goto-char (region-beginning)) (line-beginning-position)))
9527 (save-excursion
9528 (progn
9529 (goto-char (region-end)) (line-end-position))))
9530 (let ((start (markdown-table-begin))
9531 (end (markdown-table-end)))
9532 (narrow-to-region
9533 (save-excursion
9534 (if (re-search-backward
9535 markdown-table-hline-regexp start t)
9536 (line-beginning-position 2)
9537 start))
9538 (if (save-excursion (re-search-forward
9539 markdown-table-hline-regexp end t))
9540 (match-beginning 0)
9541 end))))
9542 ;; Determine arguments for `sort-subr'
9543 (let* ((extract-key-from-cell
9544 (cl-case sorting-type
9545 ((?a ?A) #'markdown--remove-invisible-markup) ;; #'identity)
9546 ((?n ?N) #'string-to-number)
9547 (t (user-error "Invalid sorting type: %c" sorting-type))))
9548 (predicate
9549 (cl-case sorting-type
9550 ((?n ?N) #'<)
9551 ((?a ?A) #'string<))))
9552 ;; Sort selected area
9553 (goto-char (point-min))
9554 (sort-subr (memq sorting-type '(?A ?N))
9555 (lambda ()
9556 (forward-line)
9557 (while (and (not (eobp))
9558 (not (looking-at
9559 markdown-table-dline-regexp)))
9560 (forward-line)))
9561 #'end-of-line
9562 (lambda ()
9563 (funcall extract-key-from-cell
9564 (markdown-table-get-cell column)))
9566 predicate)
9567 (goto-char (point-min))))))
9569 (defun markdown-table-convert-region (begin end &optional separator)
9570 "Convert region from BEGIN to END to table with SEPARATOR.
9572 If every line contains at least one TAB character, the function
9573 assumes that the material is tab separated (TSV). If every line
9574 contains a comma, comma-separated values (CSV) are assumed. If
9575 not, lines are split at whitespace into cells.
9577 You can use a prefix argument to force a specific separator:
9578 \\[universal-argument] once forces CSV, \\[universal-argument]
9579 twice forces TAB, and \\[universal-argument] three times will
9580 prompt for a regular expression to match the separator, and a
9581 numeric argument N indicates that at least N consecutive
9582 spaces, or alternatively a TAB should be used as the separator."
9584 (interactive "r\nP")
9585 (let* ((begin (min begin end)) (end (max begin end)) re)
9586 (goto-char begin) (beginning-of-line 1)
9587 (setq begin (point-marker))
9588 (goto-char end)
9589 (if (bolp) (backward-char 1) (end-of-line 1))
9590 (setq end (point-marker))
9591 (when (equal separator '(64))
9592 (setq separator (read-regexp "Regexp for cell separator: ")))
9593 (unless separator
9594 ;; Get the right cell separator
9595 (goto-char begin)
9596 (setq separator
9597 (cond
9598 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
9599 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
9600 (t 1))))
9601 (goto-char begin)
9602 (if (equal separator '(4))
9603 ;; Parse CSV
9604 (while (< (point) end)
9605 (cond
9606 ((looking-at "^") (insert "| "))
9607 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
9608 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
9609 (replace-match "\\1") (if (looking-at "\"") (insert "\"")))
9610 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
9611 ((looking-at "[ \t]*,") (replace-match " | "))
9612 (t (beginning-of-line 2))))
9613 (setq re
9614 (cond
9615 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
9616 ((equal separator '(16)) "^\\|\t")
9617 ((integerp separator)
9618 (if (< separator 1)
9619 (user-error "Cell separator must contain one or more spaces")
9620 (format "^ *\\| *\t *\\| \\{%d,\\}\\|$" separator)))
9621 ((stringp separator) (format "^ *\\|%s" separator))
9622 (t (error "Invalid cell separator"))))
9623 (let (finish)
9624 (while (and (not finish) (re-search-forward re end t))
9625 (if (eolp)
9626 (progn
9627 (replace-match "|" t t)
9628 (forward-line 1)
9629 (when (eobp)
9630 (setq finish t)))
9631 (replace-match "| " t t)))))
9632 (goto-char begin)
9633 (when markdown-table-align-p
9634 (markdown-table-align))))
9636 (defun markdown-insert-table (&optional rows columns align)
9637 "Insert an empty pipe table.
9638 Optional arguments ROWS, COLUMNS, and ALIGN specify number of
9639 rows and columns and the column alignment."
9640 (interactive)
9641 (let* ((rows (or rows (string-to-number (read-string "Row size: "))))
9642 (columns (or columns (string-to-number (read-string "Column size: "))))
9643 (align (or align (read-string "Alignment ([l]eft, [r]ight, [c]enter, or RET for default): ")))
9644 (align (cond ((equal align "l") ":--")
9645 ((equal align "r") "--:")
9646 ((equal align "c") ":-:")
9647 (t "---")))
9648 (pos (point))
9649 (indent (make-string (current-column) ?\ ))
9650 (line (concat
9651 (apply 'concat indent "|"
9652 (make-list columns " |")) "\n"))
9653 (hline (apply 'concat indent "|"
9654 (make-list columns (concat align "|")))))
9655 (if (string-match
9656 "^[ \t]*$" (buffer-substring-no-properties
9657 (point-at-bol) (point)))
9658 (beginning-of-line 1)
9659 (newline))
9660 (dotimes (_ rows) (insert line))
9661 (goto-char pos)
9662 (if (> rows 1)
9663 (progn
9664 (end-of-line 1) (insert (concat "\n" hline)) (goto-char pos)))
9665 (markdown-table-forward-cell)))
9668 ;;; ElDoc Support =============================================================
9670 (defun markdown-eldoc-function (&rest _ignored)
9671 "Return a helpful string when appropriate based on context.
9672 * Report URL when point is at a hidden URL.
9673 * Report language name when point is a code block with hidden markup."
9674 (cond
9675 ;; Hidden URL or reference for inline link
9676 ((and (or (thing-at-point-looking-at markdown-regex-link-inline)
9677 (thing-at-point-looking-at markdown-regex-link-reference))
9678 (or markdown-hide-urls markdown-hide-markup))
9679 (let* ((imagep (string-equal (match-string 1) "!"))
9680 (referencep (string-equal (match-string 5) "["))
9681 (link (match-string-no-properties 6))
9682 (edit-keys (markdown--substitute-command-keys
9683 (if imagep
9684 "\\[markdown-insert-image]"
9685 "\\[markdown-insert-link]")))
9686 (edit-str (propertize edit-keys 'face 'font-lock-constant-face))
9687 (object (if referencep "reference" "URL")))
9688 (format "Hidden %s (%s to edit): %s" object edit-str
9689 (if referencep
9690 (concat
9691 (propertize "[" 'face 'markdown-markup-face)
9692 (propertize link 'face 'markdown-reference-face)
9693 (propertize "]" 'face 'markdown-markup-face))
9694 (propertize link 'face 'markdown-url-face)))))
9695 ;; Hidden language name for fenced code blocks
9696 ((and (markdown-code-block-at-point-p)
9697 (not (get-text-property (point) 'markdown-pre))
9698 markdown-hide-markup)
9699 (let ((lang (save-excursion (markdown-code-block-lang))))
9700 (unless lang (setq lang "[unspecified]"))
9701 (format "Hidden code block language: %s (%s to toggle markup)"
9702 (propertize lang 'face 'markdown-language-keyword-face)
9703 (markdown--substitute-command-keys
9704 "\\[markdown-toggle-markup-hiding]"))))))
9707 ;;; Mode Definition ==========================================================
9709 (defun markdown-show-version ()
9710 "Show the version number in the minibuffer."
9711 (interactive)
9712 (message "markdown-mode, version %s" markdown-mode-version))
9714 (defun markdown-mode-info ()
9715 "Open the `markdown-mode' homepage."
9716 (interactive)
9717 (browse-url "https://jblevins.org/projects/markdown-mode/"))
9719 ;;;###autoload
9720 (define-derived-mode markdown-mode text-mode "Markdown"
9721 "Major mode for editing Markdown files."
9722 (when buffer-read-only
9723 (when (or (not (buffer-file-name)) (file-writable-p (buffer-file-name)))
9724 (setq-local buffer-read-only nil)))
9725 ;; Natural Markdown tab width
9726 (setq tab-width 4)
9727 ;; Comments
9728 (setq-local comment-start "<!-- ")
9729 (setq-local comment-end " -->")
9730 (setq-local comment-start-skip "<!--[ \t]*")
9731 (setq-local comment-column 0)
9732 (setq-local comment-auto-fill-only-comments nil)
9733 (setq-local comment-use-syntax t)
9734 ;; Sentence
9735 (setq-local sentence-end-base "[.?!…‽][]\"'”’)}»›*_`~]*")
9736 ;; Syntax
9737 (add-hook 'syntax-propertize-extend-region-functions
9738 #'markdown-syntax-propertize-extend-region nil t)
9739 (add-hook 'jit-lock-after-change-extend-region-functions
9740 #'markdown-font-lock-extend-region-function t t)
9741 (setq-local syntax-propertize-function #'markdown-syntax-propertize)
9742 (syntax-propertize (point-max)) ;; Propertize before hooks run, etc.
9743 ;; Font lock.
9744 (setq font-lock-defaults
9745 '(markdown-mode-font-lock-keywords
9746 nil nil nil nil
9747 (font-lock-multiline . t)
9748 (font-lock-syntactic-face-function . markdown-syntactic-face)
9749 (font-lock-extra-managed-props
9750 . (composition display invisible rear-nonsticky
9751 keymap help-echo mouse-face))))
9752 (if markdown-hide-markup
9753 (add-to-invisibility-spec 'markdown-markup)
9754 (remove-from-invisibility-spec 'markdown-markup))
9755 ;; Wiki links
9756 (markdown-setup-wiki-link-hooks)
9757 ;; Math mode
9758 (when markdown-enable-math (markdown-toggle-math t))
9759 ;; Add a buffer-local hook to reload after file-local variables are read
9760 (add-hook 'hack-local-variables-hook #'markdown-handle-local-variables nil t)
9761 ;; For imenu support
9762 (setq imenu-create-index-function
9763 (if markdown-nested-imenu-heading-index
9764 #'markdown-imenu-create-nested-index
9765 #'markdown-imenu-create-flat-index))
9767 ;; Defun movement
9768 (setq-local beginning-of-defun-function #'markdown-beginning-of-defun)
9769 (setq-local end-of-defun-function #'markdown-end-of-defun)
9770 ;; Paragraph filling
9771 (setq-local fill-paragraph-function #'markdown-fill-paragraph)
9772 (setq-local paragraph-start
9773 ;; Should match start of lines that start or separate paragraphs
9774 (mapconcat #'identity
9776 "\f" ; starts with a literal line-feed
9777 "[ \t\f]*$" ; space-only line
9778 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9779 "[ \t]*[*+-][ \t]+" ; unordered list item
9780 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
9781 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
9782 "[ \t]*:[ \t]+" ; definition
9783 "^|" ; table or Pandoc line block
9785 "\\|"))
9786 (setq-local paragraph-separate
9787 ;; Should match lines that separate paragraphs without being
9788 ;; part of any paragraph:
9789 (mapconcat #'identity
9790 '("[ \t\f]*$" ; space-only line
9791 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9792 ;; The following is not ideal, but the Fill customization
9793 ;; options really only handle paragraph-starting prefixes,
9794 ;; not paragraph-ending suffixes:
9795 ".* $" ; line ending in two spaces
9796 "^#+"
9797 "^\\(?: \\)?[-=]+[ \t]*$" ;; setext
9798 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
9799 "\\|"))
9800 (setq-local adaptive-fill-first-line-regexp "\\`[ \t]*[A-Z]?>[ \t]*?\\'")
9801 (setq-local adaptive-fill-regexp "\\s-*")
9802 (setq-local adaptive-fill-function #'markdown-adaptive-fill-function)
9803 (setq-local fill-forward-paragraph-function #'markdown-fill-forward-paragraph)
9804 ;; Outline mode
9805 (setq-local outline-regexp markdown-regex-header)
9806 (setq-local outline-level #'markdown-outline-level)
9807 ;; Cause use of ellipses for invisible text.
9808 (add-to-invisibility-spec '(outline . t))
9809 ;; ElDoc support
9810 (if (boundp 'eldoc-documentation-functions)
9811 (add-hook 'eldoc-documentation-functions #'markdown-eldoc-function nil t)
9812 (add-function :before-until (local 'eldoc-documentation-function)
9813 #'markdown-eldoc-function))
9814 ;; Inhibiting line-breaking:
9815 ;; Separating out each condition into a separate function so that users can
9816 ;; override if desired (with remove-hook)
9817 (add-hook 'fill-nobreak-predicate
9818 #'markdown-line-is-reference-definition-p nil t)
9819 (add-hook 'fill-nobreak-predicate
9820 #'markdown-pipe-at-bol-p nil t)
9822 ;; Indentation
9823 (setq-local indent-line-function markdown-indent-function)
9824 (setq-local indent-region-function #'markdown--indent-region)
9826 ;; Flyspell
9827 (setq-local flyspell-generic-check-word-predicate
9828 #'markdown-flyspell-check-word-p)
9830 ;; Electric quoting
9831 (add-hook 'electric-quote-inhibit-functions
9832 #'markdown--inhibit-electric-quote nil :local)
9834 ;; Make checkboxes buttons
9835 (when markdown-make-gfm-checkboxes-buttons
9836 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
9837 (add-hook 'after-change-functions #'markdown-gfm-checkbox-after-change-function t t)
9838 (add-hook 'change-major-mode-hook #'markdown-remove-gfm-checkbox-overlays t t))
9840 ;; edit-indirect
9841 (add-hook 'edit-indirect-after-commit-functions
9842 #'markdown--edit-indirect-after-commit-function
9843 nil 'local)
9845 ;; Marginalized headings
9846 (when markdown-marginalize-headers
9847 (add-hook 'window-configuration-change-hook
9848 #'markdown-marginalize-update-current nil t))
9850 ;; add live preview export hook
9851 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
9852 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
9854 ;;;###autoload
9855 (add-to-list 'auto-mode-alist
9856 '("\\.\\(?:md\\|markdown\\|mkd\\|mdown\\|mkdn\\|mdwn\\)\\'" . markdown-mode))
9859 ;;; GitHub Flavored Markdown Mode ============================================
9861 (defun gfm--electric-pair-fence-code-block ()
9862 (when (and electric-pair-mode
9863 (not markdown-gfm-use-electric-backquote)
9864 (eql last-command-event ?`)
9865 (let ((count 0))
9866 (while (eql (char-before (- (point) count)) ?`)
9867 (cl-incf count))
9868 (= count 3))
9869 (eql (char-after) ?`))
9870 (save-excursion (insert (make-string 2 ?`)))))
9872 (defvar gfm-mode-hook nil
9873 "Hook run when entering GFM mode.")
9875 ;;;###autoload
9876 (define-derived-mode gfm-mode markdown-mode "GFM"
9877 "Major mode for editing GitHub Flavored Markdown files."
9878 (setq markdown-link-space-sub-char "-")
9879 (setq markdown-wiki-link-search-subdirectories t)
9880 (setq-local markdown-table-at-point-p-function #'gfm--table-at-point-p)
9881 (add-hook 'post-self-insert-hook #'gfm--electric-pair-fence-code-block 'append t)
9882 (markdown-gfm-parse-buffer-for-languages))
9885 ;;; Viewing modes =============================================================
9887 (defcustom markdown-hide-markup-in-view-modes t
9888 "Enable hidden markup mode in `markdown-view-mode' and `gfm-view-mode'."
9889 :group 'markdown
9890 :type 'boolean
9891 :safe #'booleanp)
9893 (defvar markdown-view-mode-map
9894 (let ((map (make-sparse-keymap)))
9895 (define-key map (kbd "p") #'markdown-outline-previous)
9896 (define-key map (kbd "n") #'markdown-outline-next)
9897 (define-key map (kbd "f") #'markdown-outline-next-same-level)
9898 (define-key map (kbd "b") #'markdown-outline-previous-same-level)
9899 (define-key map (kbd "u") #'markdown-outline-up)
9900 (define-key map (kbd "DEL") #'scroll-down-command)
9901 (define-key map (kbd "SPC") #'scroll-up-command)
9902 (define-key map (kbd ">") #'end-of-buffer)
9903 (define-key map (kbd "<") #'beginning-of-buffer)
9904 (define-key map (kbd "q") #'kill-this-buffer)
9905 (define-key map (kbd "?") #'describe-mode)
9906 map)
9907 "Keymap for `markdown-view-mode'.")
9909 (defun markdown--filter-visible (beg end &optional delete)
9910 (let ((result "")
9911 (invisible-faces '(markdown-header-delimiter-face markdown-header-rule-face)))
9912 (while (< beg end)
9913 (when (markdown--face-p beg invisible-faces)
9914 (cl-incf beg)
9915 (while (and (markdown--face-p beg invisible-faces) (< beg end))
9916 (cl-incf beg)))
9917 (let ((next (next-single-char-property-change beg 'invisible)))
9918 (unless (get-char-property beg 'invisible)
9919 (setq result (concat result (buffer-substring beg (min end next)))))
9920 (setq beg next)))
9921 (prog1 result
9922 (when delete
9923 (let ((inhibit-read-only t))
9924 (delete-region beg end))))))
9926 ;;;###autoload
9927 (define-derived-mode markdown-view-mode markdown-mode "Markdown-View"
9928 "Major mode for viewing Markdown content."
9929 (setq-local markdown-hide-markup markdown-hide-markup-in-view-modes)
9930 (add-to-invisibility-spec 'markdown-markup)
9931 (setq-local filter-buffer-substring-function #'markdown--filter-visible)
9932 (read-only-mode 1))
9934 (defvar gfm-view-mode-map
9935 markdown-view-mode-map
9936 "Keymap for `gfm-view-mode'.")
9938 ;;;###autoload
9939 (define-derived-mode gfm-view-mode gfm-mode "GFM-View"
9940 "Major mode for viewing GitHub Flavored Markdown content."
9941 (setq-local markdown-hide-markup markdown-hide-markup-in-view-modes)
9942 (setq-local markdown-fontify-code-blocks-natively t)
9943 (setq-local filter-buffer-substring-function #'markdown--filter-visible)
9944 (add-to-invisibility-spec 'markdown-markup)
9945 (read-only-mode 1))
9948 ;;; Live Preview Mode ========================================================
9949 ;;;###autoload
9950 (define-minor-mode markdown-live-preview-mode
9951 "Toggle native previewing on save for a specific markdown file."
9952 :lighter " MD-Preview"
9953 (if markdown-live-preview-mode
9954 (if (markdown-live-preview-get-filename)
9955 (markdown-display-buffer-other-window (markdown-live-preview-export))
9956 (markdown-live-preview-mode -1)
9957 (user-error "Buffer %s does not visit a file" (current-buffer)))
9958 (markdown-live-preview-remove)))
9961 (provide 'markdown-mode)
9963 ;; Local Variables:
9964 ;; indent-tabs-mode: nil
9965 ;; coding: utf-8
9966 ;; End:
9967 ;;; markdown-mode.el ends here