Merge pull request #738 from jrblevin/issue-737
[markdown-mode.git] / markdown-mode.el
blobed8f962d8e5c1a566dc93d041ad7379e6d3fd072
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-alpha
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-alpha"
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 (line-beginning-position) (line-end-position)))
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 (line-beginning-position) (line-end-position)))
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+ (line-end-position))))
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 (line-end-position)))
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 (line-beginning-position) '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) (line-beginning-position))))
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 (line-beginning-position)) ?|))
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-markup-face))
2928 (markdown-range-property-any
2929 begin end 'face '(markdown-bold-face
2930 markdown-list-face
2931 markdown-hr-face
2932 markdown-math-face))
2933 (and is-gfm
2934 (or (char-equal (char-after begin) (char-after (1+ begin))) ;; check bold case
2935 (not (markdown--gfm-markup-underscore-p begin close-end)))))
2936 (progn (goto-char (min (1+ begin) last))
2937 (when (< (point) last)
2938 (markdown-match-italic last)))
2939 (set-match-data (list (match-beginning 1) (match-end 1)
2940 (match-beginning 2) (match-end 2)
2941 (match-beginning 3) (match-end 3)
2942 (match-beginning 4) (match-end 4)))
2943 t)))))
2945 (defun markdown--match-highlighting (last)
2946 (when markdown-enable-highlighting-syntax
2947 (re-search-forward markdown-regex-highlighting last t)))
2949 (defun markdown-match-math-generic (regex last)
2950 "Match REGEX from point to LAST.
2951 REGEX is either `markdown-regex-math-inline-single' for matching
2952 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
2953 (when (markdown-match-inline-generic regex last)
2954 (let ((begin (match-beginning 1)) (end (match-end 1)))
2955 (prog1
2956 (if (or (markdown-range-property-any
2957 begin end 'face
2958 '(markdown-inline-code-face markdown-bold-face))
2959 (markdown-range-properties-exist
2960 begin end
2961 (markdown-get-fenced-block-middle-properties)))
2962 (markdown-match-math-generic regex last)
2964 (goto-char (1+ (match-end 0)))))))
2966 (defun markdown-match-list-items (last)
2967 "Match list items from point to LAST."
2968 (let* ((first (point))
2969 (pos first)
2970 (prop 'markdown-list-item)
2971 (bounds (car (get-text-property pos prop))))
2972 (while
2973 (and (or (null (setq bounds (car (get-text-property pos prop))))
2974 (< (cl-first bounds) pos))
2975 (< (point) last)
2976 (setq pos (next-single-property-change pos prop nil last))
2977 (goto-char pos)))
2978 (when bounds
2979 (set-match-data (cl-seventh bounds))
2980 ;; Step at least one character beyond point. Otherwise
2981 ;; `font-lock-fontify-keywords-region' infloops.
2982 (goto-char (min (1+ (max (line-end-position) first))
2983 (point-max)))
2984 t)))
2986 (defun markdown-match-math-single (last)
2987 "Match single quoted $..$ math from point to LAST."
2988 (when markdown-enable-math
2989 (when (and (char-equal (char-after) ?$)
2990 (not (bolp))
2991 (not (char-equal (char-before) ?\\))
2992 (not (char-equal (char-before) ?$)))
2993 (forward-char -1))
2994 (markdown-match-math-generic markdown-regex-math-inline-single last)))
2996 (defun markdown-match-math-double (last)
2997 "Match double quoted $$..$$ math from point to LAST."
2998 (when markdown-enable-math
2999 (when (and (< (1+ (point)) (point-max))
3000 (char-equal (char-after) ?$)
3001 (char-equal (char-after (1+ (point))) ?$)
3002 (not (bolp))
3003 (not (char-equal (char-before) ?\\))
3004 (not (char-equal (char-before) ?$)))
3005 (forward-char -1))
3006 (markdown-match-math-generic markdown-regex-math-inline-double last)))
3008 (defun markdown-match-math-display (last)
3009 "Match bracketed display math \[..\] and \\[..\\] from point to LAST."
3010 (when markdown-enable-math
3011 (markdown-match-math-generic markdown-regex-math-display last)))
3013 (defun markdown-match-propertized-text (property last)
3014 "Match text with PROPERTY from point to LAST.
3015 Restore match data previously stored in PROPERTY."
3016 (let ((saved (get-text-property (point) property))
3017 pos)
3018 (unless saved
3019 (setq pos (next-single-property-change (point) property nil last))
3020 (unless (= pos last)
3021 (setq saved (get-text-property pos property))))
3022 (when saved
3023 (set-match-data saved)
3024 ;; Step at least one character beyond point. Otherwise
3025 ;; `font-lock-fontify-keywords-region' infloops.
3026 (goto-char (min (1+ (max (match-end 0) (point)))
3027 (point-max)))
3028 saved)))
3030 (defun markdown-match-pre-blocks (last)
3031 "Match preformatted blocks from point to LAST.
3032 Use data stored in \\='markdown-pre text property during syntax
3033 analysis."
3034 (markdown-match-propertized-text 'markdown-pre last))
3036 (defun markdown-match-gfm-code-blocks (last)
3037 "Match GFM quoted code blocks from point to LAST.
3038 Use data stored in \\='markdown-gfm-code text property during syntax
3039 analysis."
3040 (markdown-match-propertized-text 'markdown-gfm-code last))
3042 (defun markdown-match-gfm-open-code-blocks (last)
3043 (markdown-match-propertized-text 'markdown-gfm-block-begin last))
3045 (defun markdown-match-gfm-close-code-blocks (last)
3046 (markdown-match-propertized-text 'markdown-gfm-block-end last))
3048 (defun markdown-match-fenced-code-blocks (last)
3049 "Match fenced code blocks from the point to LAST."
3050 (markdown-match-propertized-text 'markdown-fenced-code last))
3052 (defun markdown-match-fenced-start-code-block (last)
3053 (markdown-match-propertized-text 'markdown-tilde-fence-begin last))
3055 (defun markdown-match-fenced-end-code-block (last)
3056 (markdown-match-propertized-text 'markdown-tilde-fence-end last))
3058 (defun markdown-match-blockquotes (last)
3059 "Match blockquotes from point to LAST.
3060 Use data stored in \\='markdown-blockquote text property during syntax
3061 analysis."
3062 (markdown-match-propertized-text 'markdown-blockquote last))
3064 (defun markdown-match-hr (last)
3065 "Match horizontal rules comments from the point to LAST."
3066 (markdown-match-propertized-text 'markdown-hr last))
3068 (defun markdown-match-comments (last)
3069 "Match HTML comments from the point to LAST."
3070 (when (and (skip-syntax-forward "^<" last))
3071 (let ((beg (point)))
3072 (when (and (skip-syntax-forward "^>" last) (< (point) last))
3073 (forward-char)
3074 (set-match-data (list beg (point)))
3075 t))))
3077 (defun markdown-match-generic-links (last ref)
3078 "Match inline links from point to LAST.
3079 When REF is non-nil, match reference links instead of standard
3080 links with URLs.
3081 This function should only be used during font-lock, as it
3082 determines syntax based on the presence of faces for previously
3083 processed elements."
3084 ;; Search for the next potential link (not in a code block).
3085 (let ((prohibited-faces '(markdown-pre-face
3086 markdown-code-face
3087 markdown-inline-code-face
3088 markdown-comment-face))
3089 found)
3090 (while
3091 (and (not found) (< (point) last)
3092 (progn
3093 ;; Clear match data to test for a match after functions returns.
3094 (set-match-data nil)
3095 ;; Preliminary regular expression search so we can return
3096 ;; quickly upon failure. This doesn't handle malformed links
3097 ;; or nested square brackets well, so if it passes we back up
3098 ;; continue with a more precise search.
3099 (re-search-forward
3100 (if ref
3101 markdown-regex-link-reference
3102 markdown-regex-link-inline)
3103 last 'limit)))
3104 ;; Keep searching if this is in a code block, inline code, or a
3105 ;; comment, or if it is include syntax. The link text portion
3106 ;; (group 3) may contain inline code or comments, but the
3107 ;; markup, URL, and title should not be part of such elements.
3108 (if (or (markdown-range-property-any
3109 (match-beginning 0) (match-end 2) 'face prohibited-faces)
3110 (markdown-range-property-any
3111 (match-beginning 4) (match-end 0) 'face prohibited-faces)
3112 (and (char-equal (char-after (line-beginning-position)) ?<)
3113 (char-equal (char-after (1+ (line-beginning-position))) ?<)))
3114 (set-match-data nil)
3115 (setq found t))))
3116 ;; Match opening exclamation point (optional) and left bracket.
3117 (when (match-beginning 2)
3118 (let* ((bang (match-beginning 1))
3119 (first-begin (match-beginning 2))
3120 ;; Find end of block to prevent matching across blocks.
3121 (end-of-block (save-excursion
3122 (progn
3123 (goto-char (match-beginning 2))
3124 (markdown-end-of-text-block)
3125 (point))))
3126 ;; Move over balanced expressions to closing right bracket.
3127 ;; Catch unbalanced expression errors and return nil.
3128 (first-end (condition-case nil
3129 (and (goto-char first-begin)
3130 (scan-sexps (point) 1))
3131 (error nil)))
3132 ;; Continue with point at CONT-POINT upon failure.
3133 (cont-point (min (1+ first-begin) last))
3134 second-begin second-end url-begin url-end
3135 title-begin title-end)
3136 ;; When bracket found, in range, and followed by a left paren/bracket...
3137 (when (and first-end (< first-end end-of-block) (goto-char first-end)
3138 (char-equal (char-after (point)) (if ref ?\[ ?\()))
3139 ;; Scan across balanced expressions for closing parenthesis/bracket.
3140 (setq second-begin (point)
3141 second-end (condition-case nil
3142 (scan-sexps (point) 1)
3143 (error nil)))
3144 ;; Check that closing parenthesis/bracket is in range.
3145 (if (and second-end (<= second-end end-of-block) (<= second-end last))
3146 (progn
3147 ;; Search for (optional) title inside closing parenthesis
3148 (when (and (not ref) (search-forward "\"" second-end t))
3149 (setq title-begin (1- (point))
3150 title-end (and (goto-char second-end)
3151 (search-backward "\"" (1+ title-begin) t))
3152 title-end (and title-end (1+ title-end))))
3153 ;; Store URL/reference range
3154 (setq url-begin (1+ second-begin)
3155 url-end (1- (or title-begin second-end)))
3156 ;; Set match data, move point beyond link, and return
3157 (set-match-data
3158 (list (or bang first-begin) second-end ; 0 - all
3159 bang (and bang (1+ bang)) ; 1 - bang
3160 first-begin (1+ first-begin) ; 2 - markup
3161 (1+ first-begin) (1- first-end) ; 3 - link text
3162 (1- first-end) first-end ; 4 - markup
3163 second-begin (1+ second-begin) ; 5 - markup
3164 url-begin url-end ; 6 - url/reference
3165 title-begin title-end ; 7 - title
3166 (1- second-end) second-end)) ; 8 - markup
3167 ;; Nullify cont-point and leave point at end and
3168 (setq cont-point nil)
3169 (goto-char second-end))
3170 ;; If no closing parenthesis in range, update continuation point
3171 (setq cont-point (min end-of-block second-begin))))
3172 (cond
3173 ;; On failure, continue searching at cont-point
3174 ((and cont-point (< cont-point last))
3175 (goto-char cont-point)
3176 (markdown-match-generic-links last ref))
3177 ;; No more text, return nil
3178 ((and cont-point (= cont-point last))
3179 nil)
3180 ;; Return t if a match occurred
3181 (t t)))))
3183 (defun markdown-match-angle-uris (last)
3184 "Match angle bracket URIs from point to LAST."
3185 (when (markdown-match-inline-generic markdown-regex-angle-uri last)
3186 (goto-char (1+ (match-end 0)))))
3188 (defun markdown-match-plain-uris (last)
3189 "Match plain URIs from point to LAST."
3190 (when (markdown-match-inline-generic markdown-regex-uri last t)
3191 (goto-char (1+ (match-end 0)))))
3193 (defvar markdown-conditional-search-function #'re-search-forward
3194 "Conditional search function used in `markdown-search-until-condition'.
3195 Made into a variable to allow for dynamic let-binding.")
3197 (defun markdown-search-until-condition (condition &rest args)
3198 (let (ret)
3199 (while (and (not ret) (apply markdown-conditional-search-function args))
3200 (setq ret (funcall condition)))
3201 ret))
3203 (defun markdown-metadata-line-p (pos regexp)
3204 (save-excursion
3205 (or (= (line-number-at-pos pos) 1)
3206 (progn
3207 (forward-line -1)
3208 ;; skip multi-line metadata
3209 (while (and (looking-at-p "^\\s-+[[:alpha:]]")
3210 (> (line-number-at-pos (point)) 1))
3211 (forward-line -1))
3212 (looking-at-p regexp)))))
3214 (defun markdown-match-generic-metadata (regexp last)
3215 "Match metadata declarations specified by REGEXP from point to LAST.
3216 These declarations must appear inside a metadata block that begins at
3217 the beginning of the buffer and ends with a blank line (or the end of
3218 the buffer)."
3219 (let* ((first (point))
3220 (end-re "\n[ \t]*\n\\|\n\\'\\|\\'")
3221 (block-begin (goto-char 1))
3222 (block-end (re-search-forward end-re nil t)))
3223 (if (and block-end (> first block-end))
3224 ;; Don't match declarations if there is no metadata block or if
3225 ;; the point is beyond the block. Move point to point-max to
3226 ;; prevent additional searches and return return nil since nothing
3227 ;; was found.
3228 (progn (goto-char (point-max)) nil)
3229 ;; If a block was found that begins before LAST and ends after
3230 ;; point, search for declarations inside it. If the starting is
3231 ;; before the beginning of the block, start there. Otherwise,
3232 ;; move back to FIRST.
3233 (goto-char (if (< first block-begin) block-begin first))
3234 (if (and (re-search-forward regexp (min last block-end) t)
3235 (markdown-metadata-line-p (point) regexp))
3236 ;; If a metadata declaration is found, set match-data and return t.
3237 (let ((key-beginning (match-beginning 1))
3238 (key-end (match-end 1))
3239 (markup-begin (match-beginning 2))
3240 (markup-end (match-end 2))
3241 (value-beginning (match-beginning 3)))
3242 (set-match-data (list key-beginning (point) ; complete metadata
3243 key-beginning key-end ; key
3244 markup-begin markup-end ; markup
3245 value-beginning (point))) ; value
3247 ;; Otherwise, move the point to last and return nil
3248 (goto-char last)
3249 nil))))
3251 (defun markdown-match-declarative-metadata (last)
3252 "Match declarative metadata from the point to LAST."
3253 (markdown-match-generic-metadata markdown-regex-declarative-metadata last))
3255 (defun markdown-match-pandoc-metadata (last)
3256 "Match Pandoc metadata from the point to LAST."
3257 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
3259 (defun markdown-match-yaml-metadata-begin (last)
3260 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last))
3262 (defun markdown-match-yaml-metadata-end (last)
3263 (markdown-match-propertized-text 'markdown-yaml-metadata-end last))
3265 (defun markdown-match-yaml-metadata-key (last)
3266 (markdown-match-propertized-text 'markdown-metadata-key last))
3268 (defun markdown-match-wiki-link (last)
3269 "Match wiki links from point to LAST."
3270 (when (and markdown-enable-wiki-links
3271 (not markdown-wiki-link-fontify-missing)
3272 (markdown-match-inline-generic markdown-regex-wiki-link last))
3273 (let ((begin (match-beginning 1)) (end (match-end 1)))
3274 (if (or (markdown-in-comment-p begin)
3275 (markdown-in-comment-p end)
3276 (markdown-inline-code-at-pos-p begin)
3277 (markdown-inline-code-at-pos-p end)
3278 (markdown-code-block-at-pos begin))
3279 (progn (goto-char (min (1+ begin) last))
3280 (when (< (point) last)
3281 (markdown-match-wiki-link last)))
3282 (set-match-data (list begin end))
3283 t))))
3285 (defun markdown-match-inline-attributes (last)
3286 "Match inline attributes from point to LAST."
3287 ;; #428 re-search-forward markdown-regex-inline-attributes is very slow.
3288 ;; So use simple regex for re-search-forward and use markdown-regex-inline-attributes
3289 ;; against matched string.
3290 (when (markdown-match-inline-generic "[ \t]*\\({\\)\\([^\n]*\\)}[ \t]*$" last)
3291 (if (not (string-match-p markdown-regex-inline-attributes (match-string 0)))
3292 (markdown-match-inline-attributes last)
3293 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
3294 (markdown-inline-code-at-pos-p (match-end 0))
3295 (markdown-in-comment-p))
3296 t))))
3298 (defun markdown-match-leanpub-sections (last)
3299 "Match Leanpub section markers from point to LAST."
3300 (when (markdown-match-inline-generic markdown-regex-leanpub-sections last)
3301 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
3302 (markdown-inline-code-at-pos-p (match-end 0))
3303 (markdown-in-comment-p))
3304 t)))
3306 (defun markdown-match-includes (last)
3307 "Match include statements from point to LAST.
3308 Sets match data for the following seven groups:
3309 Group 1: opening two angle brackets
3310 Group 2: opening title delimiter (optional)
3311 Group 3: title text (optional)
3312 Group 4: closing title delimiter (optional)
3313 Group 5: opening filename delimiter
3314 Group 6: filename
3315 Group 7: closing filename delimiter"
3316 (when (markdown-match-inline-generic markdown-regex-include last)
3317 (let ((valid (not (or (markdown-in-comment-p (match-beginning 0))
3318 (markdown-in-comment-p (match-end 0))
3319 (markdown-code-block-at-pos (match-beginning 0))))))
3320 (cond
3321 ;; Parentheses and maybe square brackets, but no curly braces:
3322 ;; match optional title in square brackets and file in parentheses.
3323 ((and valid (match-beginning 5)
3324 (not (match-beginning 8)))
3325 (set-match-data (list (match-beginning 1) (match-end 7)
3326 (match-beginning 1) (match-end 1)
3327 (match-beginning 2) (match-end 2)
3328 (match-beginning 3) (match-end 3)
3329 (match-beginning 4) (match-end 4)
3330 (match-beginning 5) (match-end 5)
3331 (match-beginning 6) (match-end 6)
3332 (match-beginning 7) (match-end 7))))
3333 ;; Only square brackets present: match file in square brackets.
3334 ((and valid (match-beginning 2)
3335 (not (match-beginning 5))
3336 (not (match-beginning 7)))
3337 (set-match-data (list (match-beginning 1) (match-end 4)
3338 (match-beginning 1) (match-end 1)
3339 nil nil
3340 nil nil
3341 nil nil
3342 (match-beginning 2) (match-end 2)
3343 (match-beginning 3) (match-end 3)
3344 (match-beginning 4) (match-end 4))))
3345 ;; Only curly braces present: match file in curly braces.
3346 ((and valid (match-beginning 8)
3347 (not (match-beginning 2))
3348 (not (match-beginning 5)))
3349 (set-match-data (list (match-beginning 1) (match-end 10)
3350 (match-beginning 1) (match-end 1)
3351 nil nil
3352 nil nil
3353 nil nil
3354 (match-beginning 8) (match-end 8)
3355 (match-beginning 9) (match-end 9)
3356 (match-beginning 10) (match-end 10))))
3358 ;; Not a valid match, move to next line and search again.
3359 (forward-line)
3360 (when (< (point) last)
3361 (setq valid (markdown-match-includes last)))))
3362 valid)))
3364 (defun markdown-match-html-tag (last)
3365 "Match HTML tags from point to LAST."
3366 (when (and markdown-enable-html
3367 (markdown-match-inline-generic markdown-regex-html-tag last t))
3368 (set-match-data (list (match-beginning 0) (match-end 0)
3369 (match-beginning 1) (match-end 1)
3370 (match-beginning 2) (match-end 2)
3371 (match-beginning 9) (match-end 9)))
3375 ;;; Markdown Font Fontification Functions =====================================
3377 (defvar markdown--first-displayable-cache (make-hash-table :test #'equal))
3379 (defun markdown--first-displayable (seq)
3380 "Return the first displayable character or string in SEQ.
3381 SEQ may be an atom or a sequence."
3382 (let ((c (gethash seq markdown--first-displayable-cache t)))
3383 (if (not (eq c t))
3385 (puthash seq
3386 (let ((seq (if (listp seq) seq (list seq))))
3387 (cond ((stringp (car seq))
3388 (cl-find-if
3389 (lambda (str)
3390 (and (mapcar #'char-displayable-p (string-to-list str))))
3391 seq))
3392 ((characterp (car seq))
3393 (cl-find-if #'char-displayable-p seq))))
3394 markdown--first-displayable-cache))))
3396 (defun markdown--marginalize-string (level)
3397 "Generate atx markup string of given LEVEL for left margin."
3398 (let ((margin-left-space-count
3399 (- markdown-marginalize-headers-margin-width level)))
3400 (concat (make-string margin-left-space-count ? )
3401 (make-string level ?#))))
3403 (defun markdown-marginalize-update-current ()
3404 "Update the window configuration to create a left margin."
3405 (if window-system
3406 (let* ((header-delimiter-font-width
3407 (window-font-width nil 'markdown-header-delimiter-face))
3408 (margin-pixel-width (* markdown-marginalize-headers-margin-width
3409 header-delimiter-font-width))
3410 (margin-char-width (/ margin-pixel-width (default-font-width))))
3411 (set-window-margins nil margin-char-width))
3412 ;; As a fallback, simply set margin based on character count.
3413 (set-window-margins nil (1+ markdown-marginalize-headers-margin-width))))
3415 (defun markdown-fontify-headings (last)
3416 "Add text properties to headings from point to LAST."
3417 (when (markdown-match-propertized-text 'markdown-heading last)
3418 (let* ((level (markdown-outline-level))
3419 (heading-face
3420 (intern (format "markdown-header-face-%d" level)))
3421 (heading-props `(face ,heading-face))
3422 (left-markup-props
3423 `(face markdown-header-delimiter-face
3424 ,@(cond
3425 (markdown-hide-markup
3426 `(display ""))
3427 (markdown-marginalize-headers
3428 `(display ((margin left-margin)
3429 ,(markdown--marginalize-string level)))))))
3430 (right-markup-props
3431 `(face markdown-header-delimiter-face
3432 ,@(when markdown-hide-markup `(display ""))))
3433 (rule-props `(face markdown-header-rule-face
3434 ,@(when markdown-hide-markup `(display "")))))
3435 (if (match-end 1)
3436 ;; Setext heading
3437 (progn (add-text-properties
3438 (match-beginning 1) (match-end 1) heading-props)
3439 (if (= level 1)
3440 (add-text-properties
3441 (match-beginning 2) (match-end 2) rule-props)
3442 (add-text-properties
3443 (match-beginning 3) (match-end 3) rule-props)))
3444 ;; atx heading
3445 (if markdown-fontify-whole-heading-line
3446 (let ((header-end (min (point-max) (1+ (match-end 0)))))
3447 (add-text-properties
3448 (match-beginning 0) header-end heading-props))
3449 (add-text-properties
3450 (match-beginning 4) (match-end 4) left-markup-props)
3451 (add-text-properties
3452 (match-beginning 5) (match-end 5) heading-props)
3453 (when (match-end 6)
3454 (add-text-properties
3455 (match-beginning 6) (match-end 6) right-markup-props)))))
3458 (defun markdown-fontify-tables (last)
3459 (when (re-search-forward "|" last t)
3460 (when (markdown-table-at-point-p)
3461 (font-lock-append-text-property
3462 (line-beginning-position) (min (1+ (line-end-position)) (point-max))
3463 'face 'markdown-table-face))
3464 (forward-line 1)
3467 (defun markdown-fontify-blockquotes (last)
3468 "Apply font-lock properties to blockquotes from point to LAST."
3469 (when (markdown-match-blockquotes last)
3470 (let ((display-string
3471 (markdown--first-displayable markdown-blockquote-display-char)))
3472 (add-text-properties
3473 (match-beginning 1) (match-end 1)
3474 (if markdown-hide-markup
3475 `(face markdown-blockquote-face display ,display-string)
3476 `(face markdown-markup-face)))
3477 (font-lock-append-text-property
3478 (match-beginning 0) (match-end 0) 'face 'markdown-blockquote-face)
3479 t)))
3481 (defun markdown-fontify-list-items (last)
3482 "Apply font-lock properties to list markers from point to LAST."
3483 (when (markdown-match-list-items last)
3484 (when (not (markdown-code-block-at-point-p (match-beginning 2)))
3485 (let* ((indent (length (match-string-no-properties 1)))
3486 (level (/ indent markdown-list-indent-width)) ;; level = 0, 1, 2, ...
3487 (bullet (nth (mod level (length markdown-list-item-bullets))
3488 markdown-list-item-bullets)))
3489 (add-text-properties
3490 (match-beginning 2) (match-end 2) '(face markdown-list-face))
3491 (when markdown-hide-markup
3492 (cond
3493 ;; Unordered lists
3494 ((string-match-p "[\\*\\+-]" (match-string 2))
3495 (add-text-properties
3496 (match-beginning 2) (match-end 2) `(display ,bullet)))
3497 ;; Definition lists
3498 ((string-equal ":" (match-string 2))
3499 (let ((display-string
3500 (char-to-string (markdown--first-displayable
3501 markdown-definition-display-char))))
3502 (add-text-properties (match-beginning 2) (match-end 2)
3503 `(display ,display-string))))))))
3506 (defun markdown-fontify-hrs (last)
3507 "Add text properties to horizontal rules from point to LAST."
3508 (when (markdown-match-hr last)
3509 (let ((hr-char (markdown--first-displayable markdown-hr-display-char)))
3510 (add-text-properties
3511 (match-beginning 0) (match-end 0)
3512 `(face markdown-hr-face
3513 font-lock-multiline t
3514 ,@(when (and markdown-hide-markup hr-char)
3515 `(display ,(make-string
3516 (1- (window-body-width)) hr-char)))))
3517 t)))
3519 (defun markdown-fontify-sub-superscripts (last)
3520 "Apply text properties to sub- and superscripts from point to LAST."
3521 (when (markdown-search-until-condition
3522 (lambda () (and (not (markdown-code-block-at-point-p))
3523 (not (markdown-inline-code-at-point-p))
3524 (not (markdown-in-comment-p))))
3525 markdown-regex-sub-superscript last t)
3526 (let* ((subscript-p (string= (match-string 2) "~"))
3527 (props
3528 (if subscript-p
3529 (car markdown-sub-superscript-display)
3530 (cdr markdown-sub-superscript-display)))
3531 (mp (list 'face 'markdown-markup-face
3532 'invisible 'markdown-markup)))
3533 (when markdown-hide-markup
3534 (put-text-property (match-beginning 3) (match-end 3)
3535 'display props))
3536 (add-text-properties (match-beginning 2) (match-end 2) mp)
3537 (add-text-properties (match-beginning 4) (match-end 4) mp)
3538 t)))
3541 ;;; Syntax Table ==============================================================
3543 (defvar markdown-mode-syntax-table
3544 (let ((tab (make-syntax-table text-mode-syntax-table)))
3545 (modify-syntax-entry ?\" "." tab)
3546 tab)
3547 "Syntax table for `markdown-mode'.")
3550 ;;; Element Insertion =========================================================
3552 (defun markdown-ensure-blank-line-before ()
3553 "If previous line is not already blank, insert a blank line before point."
3554 (unless (bolp) (insert "\n"))
3555 (unless (or (bobp) (looking-back "\n\\s-*\n" nil)) (insert "\n")))
3557 (defun markdown-ensure-blank-line-after ()
3558 "If following line is not already blank, insert a blank line after point.
3559 Return the point where it was originally."
3560 (save-excursion
3561 (unless (eolp) (insert "\n"))
3562 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
3564 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
3565 "Insert the strings S1 and S2, wrapping around region or THING.
3566 If a region is specified by the optional BEG and END arguments,
3567 wrap the strings S1 and S2 around that region.
3568 If there is an active region, wrap the strings S1 and S2 around
3569 the region. If there is not an active region but the point is at
3570 THING, wrap that thing (which defaults to word). Otherwise, just
3571 insert S1 and S2 and place the point in between. Return the
3572 bounds of the entire wrapped string, or nil if nothing was wrapped
3573 and S1 and S2 were only inserted."
3574 (let (a b bounds new-point)
3575 (cond
3576 ;; Given region
3577 ((and beg end)
3578 (setq a beg
3579 b end
3580 new-point (+ (point) (length s1))))
3581 ;; Active region
3582 ((use-region-p)
3583 (setq a (region-beginning)
3584 b (region-end)
3585 new-point (+ (point) (length s1))))
3586 ;; Thing (word) at point
3587 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
3588 (setq a (car bounds)
3589 b (cdr bounds)
3590 new-point (+ (point) (length s1))))
3591 ;; No active region and no word
3593 (setq a (point)
3594 b (point))))
3595 (goto-char b)
3596 (insert s2)
3597 (goto-char a)
3598 (insert s1)
3599 (when new-point (goto-char new-point))
3600 (if (= a b)
3602 (setq b (+ b (length s1) (length s2)))
3603 (cons a b))))
3605 (defun markdown-point-after-unwrap (cur prefix suffix)
3606 "Return desired position of point after an unwrapping operation.
3607 CUR gives the position of the point before the operation.
3608 Additionally, two cons cells must be provided. PREFIX gives the
3609 bounds of the prefix string and SUFFIX gives the bounds of the
3610 suffix string."
3611 (cond ((< cur (cdr prefix)) (car prefix))
3612 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
3613 ((<= cur (cdr suffix))
3614 (- cur (+ (- (cdr prefix) (car prefix))
3615 (- cur (car suffix)))))
3616 (t cur)))
3618 (defun markdown-unwrap-thing-at-point (regexp all text)
3619 "Remove prefix and suffix of thing at point and reposition the point.
3620 When the thing at point matches REGEXP, replace the subexpression
3621 ALL with the string in subexpression TEXT. Reposition the point
3622 in an appropriate location accounting for the removal of prefix
3623 and suffix strings. Return new bounds of string from group TEXT.
3624 When REGEXP is nil, assumes match data is already set."
3625 (when (or (null regexp)
3626 (thing-at-point-looking-at regexp))
3627 (let ((cur (point))
3628 (prefix (cons (match-beginning all) (match-beginning text)))
3629 (suffix (cons (match-end text) (match-end all)))
3630 (bounds (cons (match-beginning text) (match-end text))))
3631 ;; Replace the thing at point
3632 (replace-match (match-string text) t t nil all)
3633 ;; Reposition the point
3634 (goto-char (markdown-point-after-unwrap cur prefix suffix))
3635 ;; Adjust bounds
3636 (setq bounds (cons (car prefix)
3637 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
3639 (defun markdown-unwrap-things-in-region (beg end regexp all text)
3640 "Remove prefix and suffix of all things in region from BEG to END.
3641 When a thing in the region matches REGEXP, replace the
3642 subexpression ALL with the string in subexpression TEXT.
3643 Return a cons cell containing updated bounds for the region."
3644 (save-excursion
3645 (goto-char beg)
3646 (let ((removed 0) len-all len-text)
3647 (while (re-search-forward regexp (- end removed) t)
3648 (setq len-all (length (match-string-no-properties all)))
3649 (setq len-text (length (match-string-no-properties text)))
3650 (setq removed (+ removed (- len-all len-text)))
3651 (replace-match (match-string text) t t nil all))
3652 (cons beg (- end removed)))))
3654 (defun markdown-insert-hr (arg)
3655 "Insert or replace a horizontal rule.
3656 By default, use the first element of `markdown-hr-strings'. When
3657 ARG is non-nil, as when given a prefix, select a different
3658 element as follows. When prefixed with \\[universal-argument],
3659 use the last element of `markdown-hr-strings' instead. When
3660 prefixed with an integer from 1 to the length of
3661 `markdown-hr-strings', use the element in that position instead."
3662 (interactive "*P")
3663 (when (thing-at-point-looking-at markdown-regex-hr)
3664 (delete-region (match-beginning 0) (match-end 0)))
3665 (markdown-ensure-blank-line-before)
3666 (cond ((equal arg '(4))
3667 (insert (car (reverse markdown-hr-strings))))
3668 ((and (integerp arg) (> arg 0)
3669 (<= arg (length markdown-hr-strings)))
3670 (insert (nth (1- arg) markdown-hr-strings)))
3672 (insert (car markdown-hr-strings))))
3673 (markdown-ensure-blank-line-after))
3675 (defun markdown--insert-common (start-delim end-delim regex start-group end-group face
3676 &optional skip-space)
3677 (if (use-region-p)
3678 ;; Active region
3679 (let* ((bounds (markdown-unwrap-things-in-region
3680 (region-beginning) (region-end)
3681 regex start-group end-group))
3682 (beg (car bounds))
3683 (end (cdr bounds)))
3684 (when (and beg skip-space)
3685 (save-excursion
3686 (goto-char beg)
3687 (skip-chars-forward "[ \t]")
3688 (setq beg (point))))
3689 (when (and end skip-space)
3690 (save-excursion
3691 (goto-char end)
3692 (skip-chars-backward "[ \t]")
3693 (setq end (point))))
3694 (markdown-wrap-or-insert start-delim end-delim nil beg end))
3695 (if (markdown--face-p (point) (list face))
3696 (save-excursion
3697 (while (and (markdown--face-p (point) (list face)) (not (bobp)))
3698 (forward-char -1))
3699 (forward-char (- (1- (length start-delim)))) ;; for delimiter
3700 (unless (bolp)
3701 (forward-char -1))
3702 (when (looking-at regex)
3703 (markdown-unwrap-thing-at-point nil start-group end-group)))
3704 (if (thing-at-point-looking-at regex)
3705 (markdown-unwrap-thing-at-point nil start-group end-group)
3706 (markdown-wrap-or-insert start-delim end-delim 'word nil nil)))))
3708 (defun markdown-insert-bold ()
3709 "Insert markup to make a region or word bold.
3710 If there is an active region, make the region bold. If the point
3711 is at a non-bold word, make the word bold. If the point is at a
3712 bold word or phrase, remove the bold markup. Otherwise, simply
3713 insert bold delimiters and place the point in between them."
3714 (interactive)
3715 (let ((delim (if markdown-bold-underscore "__" "**")))
3716 (markdown--insert-common delim delim markdown-regex-bold 2 4 'markdown-bold-face t)))
3718 (defun markdown-insert-italic ()
3719 "Insert markup to make a region or word italic.
3720 If there is an active region, make the region italic. If the point
3721 is at a non-italic word, make the word italic. If the point is at an
3722 italic word or phrase, remove the italic markup. Otherwise, simply
3723 insert italic delimiters and place the point in between them."
3724 (interactive)
3725 (let ((delim (if markdown-italic-underscore "_" "*")))
3726 (markdown--insert-common delim delim markdown-regex-italic 1 3 'markdown-italic-face t)))
3728 (defun markdown-insert-strike-through ()
3729 "Insert markup to make a region or word strikethrough.
3730 If there is an active region, make the region strikethrough. If the point
3731 is at a non-bold word, make the word strikethrough. If the point is at a
3732 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
3733 simply insert bold delimiters and place the point in between them."
3734 (interactive)
3735 (markdown--insert-common
3736 "~~" "~~" markdown-regex-strike-through 2 4 'markdown-strike-through-face t))
3738 (defun markdown-insert-code ()
3739 "Insert markup to make a region or word an inline code fragment.
3740 If there is an active region, make the region an inline code
3741 fragment. If the point is at a word, make the word an inline
3742 code fragment. Otherwise, simply insert code delimiters and
3743 place the point in between them."
3744 (interactive)
3745 (if (use-region-p)
3746 ;; Active region
3747 (let ((bounds (markdown-unwrap-things-in-region
3748 (region-beginning) (region-end)
3749 markdown-regex-code 1 3)))
3750 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
3751 ;; Code markup removal, code markup for word, or empty markup insertion
3752 (if (markdown-inline-code-at-point)
3753 (markdown-unwrap-thing-at-point nil 0 2)
3754 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
3756 (defun markdown-insert-kbd ()
3757 "Insert markup to wrap region or word in <kbd> tags.
3758 If there is an active region, use the region. If the point is at
3759 a word, use the word. Otherwise, simply insert <kbd> tags and
3760 place the point in between them."
3761 (interactive)
3762 (if (use-region-p)
3763 ;; Active region
3764 (let ((bounds (markdown-unwrap-things-in-region
3765 (region-beginning) (region-end)
3766 markdown-regex-kbd 0 2)))
3767 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil (car bounds) (cdr bounds)))
3768 ;; Markup removal, markup for word, or empty markup insertion
3769 (if (thing-at-point-looking-at markdown-regex-kbd)
3770 (markdown-unwrap-thing-at-point nil 0 2)
3771 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil))))
3773 (defun markdown-insert-inline-link (text url &optional title)
3774 "Insert an inline link with TEXT pointing to URL.
3775 Optionally, the user can provide a TITLE."
3776 (let ((cur (point)))
3777 (setq title (and title (concat " \"" title "\"")))
3778 (insert (concat "[" text "](" url title ")"))
3779 (cond ((not text) (goto-char (+ 1 cur)))
3780 ((not url) (goto-char (+ 3 (length text) cur))))))
3782 (defun markdown-insert-inline-image (text url &optional title)
3783 "Insert an inline link with alt TEXT pointing to URL.
3784 Optionally, also provide a TITLE."
3785 (let ((cur (point)))
3786 (setq title (and title (concat " \"" title "\"")))
3787 (insert (concat "![" text "](" url title ")"))
3788 (cond ((not text) (goto-char (+ 2 cur)))
3789 ((not url) (goto-char (+ 4 (length text) cur))))))
3791 (defun markdown-insert-reference-link (text label &optional url title)
3792 "Insert a reference link and, optionally, a reference definition.
3793 The link TEXT will be inserted followed by the optional LABEL.
3794 If a URL is given, also insert a definition for the reference
3795 LABEL according to `markdown-reference-location'. If a TITLE is
3796 given, it will be added to the end of the reference definition
3797 and will be used to populate the title attribute when converted
3798 to XHTML. If URL is nil, insert only the link portion (for
3799 example, when a reference label is already defined)."
3800 (insert (concat "[" text "][" label "]"))
3801 (when url
3802 (markdown-insert-reference-definition
3803 (if (string-equal label "") text label)
3804 url title)))
3806 (defun markdown-insert-reference-image (text label &optional url title)
3807 "Insert a reference image and, optionally, a reference definition.
3808 The alt TEXT will be inserted followed by the optional LABEL.
3809 If a URL is given, also insert a definition for the reference
3810 LABEL according to `markdown-reference-location'. If a TITLE is
3811 given, it will be added to the end of the reference definition
3812 and will be used to populate the title attribute when converted
3813 to XHTML. If URL is nil, insert only the link portion (for
3814 example, when a reference label is already defined)."
3815 (insert (concat "![" text "][" label "]"))
3816 (when url
3817 (markdown-insert-reference-definition
3818 (if (string-equal label "") text label)
3819 url title)))
3821 (defun markdown-insert-reference-definition (label &optional url title)
3822 "Add definition for reference LABEL with URL and TITLE.
3823 LABEL is a Markdown reference label without square brackets.
3824 URL and TITLE are optional. When given, the TITLE will
3825 be used to populate the title attribute when converted to XHTML."
3826 ;; END specifies where to leave the point upon return
3827 (let ((end (point)))
3828 (cl-case markdown-reference-location
3829 (end (goto-char (point-max)))
3830 (immediately (markdown-end-of-text-block))
3831 (subtree (markdown-end-of-subtree))
3832 (header (markdown-end-of-defun)))
3833 ;; Skip backwards over local variables. This logic is similar to the one
3834 ;; used in ‘hack-local-variables’.
3835 (when (and enable-local-variables (eobp))
3836 (search-backward "\n\f" (max (- (point) 3000) (point-min)) :move)
3837 (when (let ((case-fold-search t))
3838 (search-forward "Local Variables:" nil :move))
3839 (beginning-of-line 0)
3840 (when (eq (char-before) ?\n) (backward-char))))
3841 (unless (or (markdown-cur-line-blank-p)
3842 (thing-at-point-looking-at markdown-regex-reference-definition))
3843 (insert "\n"))
3844 (insert "\n[" label "]: ")
3845 (if url
3846 (insert url)
3847 ;; When no URL is given, leave point at END following the colon
3848 (setq end (point)))
3849 (when (> (length title) 0)
3850 (insert " \"" title "\""))
3851 (unless (looking-at-p "\n")
3852 (insert "\n"))
3853 (goto-char end)
3854 (when url
3855 (message
3856 (markdown--substitute-command-keys
3857 "Reference [%s] was defined, press \\[markdown-do] to jump there")
3858 label))))
3860 (defcustom markdown-link-make-text-function nil
3861 "Function that automatically generates a link text for a URL.
3863 If non-nil, this function will be called by
3864 `markdown--insert-link-or-image' and the result will be the
3865 default link text. The function should receive exactly one
3866 argument that corresponds to the link URL."
3867 :group 'markdown
3868 :type 'function
3869 :package-version '(markdown-mode . "2.5"))
3871 (defcustom markdown-disable-tooltip-prompt nil
3872 "Disable prompt for tooltip when inserting a link or image.
3874 If non-nil, `markdown-insert-link' and `markdown-insert-link'
3875 will not prompt the user to insert a tooltip text for the given
3876 link or image."
3877 :group 'markdown
3878 :type 'boolean
3879 :safe 'booleanp
3880 :package-version '(markdown-mode . "2.5"))
3882 (defun markdown--insert-link-or-image (image)
3883 "Interactively insert new or update an existing link or image.
3884 When IMAGE is non-nil, insert an image. Otherwise, insert a link.
3885 This is an internal function called by
3886 `markdown-insert-link' and `markdown-insert-image'."
3887 (cl-multiple-value-bind (begin end text uri ref title)
3888 (if (use-region-p)
3889 ;; Use region as either link text or URL as appropriate.
3890 (let ((region (buffer-substring-no-properties
3891 (region-beginning) (region-end))))
3892 (if (string-match markdown-regex-uri region)
3893 ;; Region contains a URL; use it as such.
3894 (list (region-beginning) (region-end)
3895 nil (match-string 0 region) nil nil)
3896 ;; Region doesn't contain a URL, so use it as text.
3897 (list (region-beginning) (region-end)
3898 region nil nil nil)))
3899 ;; Extract and use properties of existing link, if any.
3900 (markdown-link-at-pos (point)))
3901 (let* ((ref (when ref (concat "[" ref "]")))
3902 (defined-refs (mapcar #'car (markdown-get-defined-references)))
3903 (defined-ref-cands (mapcar (lambda (ref) (concat "[" ref "]")) defined-refs))
3904 (used-uris (markdown-get-used-uris))
3905 (uri-or-ref (completing-read
3906 "URL or [reference]: "
3907 (append defined-ref-cands used-uris)
3908 nil nil (or uri ref)))
3909 (ref (cond ((string-match "\\`\\[\\(.*\\)\\]\\'" uri-or-ref)
3910 (match-string 1 uri-or-ref))
3911 ((string-equal "" uri-or-ref)
3912 "")))
3913 (uri (unless ref uri-or-ref))
3914 (text-prompt (if image
3915 "Alt text: "
3916 (if ref
3917 "Link text: "
3918 "Link text (blank for plain URL): ")))
3919 (text (or text (and markdown-link-make-text-function uri
3920 (funcall markdown-link-make-text-function uri))))
3921 (text (completing-read text-prompt defined-refs nil nil text))
3922 (text (if (= (length text) 0) nil text))
3923 (plainp (and uri (not text)))
3924 (implicitp (string-equal ref ""))
3925 (ref (if implicitp text ref))
3926 (definedp (and ref (markdown-reference-definition ref)))
3927 (ref-url (unless (or uri definedp)
3928 (completing-read "Reference URL: " used-uris)))
3929 (title (unless (or plainp definedp markdown-disable-tooltip-prompt)
3930 (read-string "Title (tooltip text, optional): " title)))
3931 (title (if (= (length title) 0) nil title)))
3932 (when (and image implicitp)
3933 (user-error "Reference required: implicit image references are invalid"))
3934 (when (and begin end)
3935 (delete-region begin end))
3936 (cond
3937 ((and (not image) uri text)
3938 (markdown-insert-inline-link text uri title))
3939 ((and image uri text)
3940 (markdown-insert-inline-image text uri title))
3941 ((and ref text)
3942 (if image
3943 (markdown-insert-reference-image text (unless implicitp ref) nil title)
3944 (markdown-insert-reference-link text (unless implicitp ref) nil title))
3945 (unless definedp
3946 (markdown-insert-reference-definition ref ref-url title)))
3947 ((and (not image) uri)
3948 (markdown-insert-uri uri))))))
3950 (defun markdown-insert-link ()
3951 "Insert new or update an existing link, with interactive prompt.
3952 If the point is at an existing link or URL, update the link text,
3953 URL, reference label, and/or title. Otherwise, insert a new link.
3954 The type of link inserted (inline, reference, or plain URL)
3955 depends on which values are provided:
3957 * If a URL and TEXT are given, insert an inline link: [TEXT](URL).
3958 * If [REF] and TEXT are given, insert a reference link: [TEXT][REF].
3959 * If only TEXT is given, insert an implicit reference link: [TEXT][].
3960 * If only a URL is given, insert a plain link: <URL>.
3962 In other words, to create an implicit reference link, leave the
3963 URL prompt empty and to create a plain URL link, leave the link
3964 text empty.
3966 If there is an active region, use the text as the default URL, if
3967 it seems to be a URL, or link text value otherwise.
3969 If a given reference is not defined, this function will
3970 additionally prompt for the URL and optional title. In this case,
3971 the reference definition is placed at the location determined by
3972 `markdown-reference-location'. In addition, it is possible to
3973 have the `markdown-link-make-text-function' function, if non-nil,
3974 define the default link text before prompting the user for it.
3976 If `markdown-disable-tooltip-prompt' is non-nil, the user will
3977 not be prompted to add or modify a tooltip text.
3979 Through updating the link, this function can be used to convert a
3980 link of one type (inline, reference, or plain) to another type by
3981 selectively adding or removing information via the prompts."
3982 (interactive)
3983 (markdown--insert-link-or-image nil))
3985 (defun markdown-insert-image ()
3986 "Insert new or update an existing image, with interactive prompt.
3987 If the point is at an existing image, update the alt text, URL,
3988 reference label, and/or title. Otherwise, insert a new image.
3989 The type of image inserted (inline or reference) depends on which
3990 values are provided:
3992 * If a URL and ALT-TEXT are given, insert an inline image:
3993 ![ALT-TEXT](URL).
3994 * If [REF] and ALT-TEXT are given, insert a reference image:
3995 ![ALT-TEXT][REF].
3997 If there is an active region, use the text as the default URL, if
3998 it seems to be a URL, or alt text value otherwise.
4000 If a given reference is not defined, this function will
4001 additionally prompt for the URL and optional title. In this case,
4002 the reference definition is placed at the location determined by
4003 `markdown-reference-location'.
4005 Through updating the image, this function can be used to convert an
4006 image of one type (inline or reference) to another type by
4007 selectively adding or removing information via the prompts."
4008 (interactive)
4009 (markdown--insert-link-or-image t))
4011 (defun markdown-insert-uri (&optional uri)
4012 "Insert markup for an inline URI.
4013 If there is an active region, use it as the URI. If the point is
4014 at a URI, wrap it with angle brackets. If the point is at an
4015 inline URI, remove the angle brackets. Otherwise, simply insert
4016 angle brackets place the point between them."
4017 (interactive)
4018 (if (use-region-p)
4019 ;; Active region
4020 (let ((bounds (markdown-unwrap-things-in-region
4021 (region-beginning) (region-end)
4022 markdown-regex-angle-uri 0 2)))
4023 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
4024 ;; Markup removal, URI at point, new URI, or empty markup insertion
4025 (if (thing-at-point-looking-at markdown-regex-angle-uri)
4026 (markdown-unwrap-thing-at-point nil 0 2)
4027 (if uri
4028 (insert "<" uri ">")
4029 (markdown-wrap-or-insert "<" ">" 'url nil nil)))))
4031 (defun markdown-insert-wiki-link ()
4032 "Insert a wiki link of the form [[WikiLink]].
4033 If there is an active region, use the region as the link text.
4034 If the point is at a word, use the word as the link text. If
4035 there is no active region and the point is not at word, simply
4036 insert link markup."
4037 (interactive)
4038 (if (use-region-p)
4039 ;; Active region
4040 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
4041 ;; Markup removal, wiki link at at point, or empty markup insertion
4042 (if (thing-at-point-looking-at markdown-regex-wiki-link)
4043 (if (or markdown-wiki-link-alias-first
4044 (null (match-string 5)))
4045 (markdown-unwrap-thing-at-point nil 1 3)
4046 (markdown-unwrap-thing-at-point nil 1 5))
4047 (markdown-wrap-or-insert "[[" "]]"))))
4049 (defun markdown-remove-header ()
4050 "Remove header markup if point is at a header.
4051 Return bounds of remaining header text if a header was removed
4052 and nil otherwise."
4053 (interactive "*")
4054 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
4055 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
4057 (defun markdown-insert-header (&optional level text setext)
4058 "Insert or replace header markup.
4059 The level of the header is specified by LEVEL and header text is
4060 given by TEXT. LEVEL must be an integer from 1 and 6, and the
4061 default value is 1.
4062 When TEXT is nil, the header text is obtained as follows.
4063 If there is an active region, it is used as the header text.
4064 Otherwise, the current line will be used as the header text.
4065 If there is not an active region and the point is at a header,
4066 remove the header markup and replace with level N header.
4067 Otherwise, insert empty header markup and place the point in
4068 between.
4069 The style of the header will be atx (hash marks) unless
4070 SETEXT is non-nil, in which case a setext-style (underlined)
4071 header will be inserted."
4072 (interactive "p\nsHeader text: ")
4073 (setq level (min (max (or level 1) 1) (if setext 2 6)))
4074 ;; Determine header text if not given
4075 (when (null text)
4076 (if (use-region-p)
4077 ;; Active region
4078 (setq text (delete-and-extract-region (region-beginning) (region-end)))
4079 ;; No active region
4080 (markdown-remove-header)
4081 (setq text (delete-and-extract-region
4082 (line-beginning-position) (line-end-position)))
4083 (when (and setext (string-match-p "^[ \t]*$" text))
4084 (setq text (read-string "Header text: "))))
4085 (setq text (markdown-compress-whitespace-string text)))
4086 ;; Insertion with given text
4087 (markdown-ensure-blank-line-before)
4088 (let (hdr)
4089 (cond (setext
4090 (setq hdr (make-string (string-width text) (if (= level 2) ?- ?=)))
4091 (insert text "\n" hdr))
4093 (setq hdr (make-string level ?#))
4094 (insert hdr " " text)
4095 (when (null markdown-asymmetric-header) (insert " " hdr)))))
4096 (markdown-ensure-blank-line-after)
4097 ;; Leave point at end of text
4098 (cond (setext
4099 (backward-char (1+ (string-width text))))
4100 ((null markdown-asymmetric-header)
4101 (backward-char (1+ level)))))
4103 (defun markdown-insert-header-dwim (&optional arg setext)
4104 "Insert or replace header markup.
4105 The level and type of the header are determined automatically by
4106 the type and level of the previous header, unless a prefix
4107 argument is given via ARG.
4108 With a numeric prefix valued 1 to 6, insert a header of the given
4109 level, with the type being determined automatically (note that
4110 only level 1 or 2 setext headers are possible).
4112 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
4113 promote the heading by one level.
4114 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
4115 demote the heading by one level.
4116 When SETEXT is non-nil, prefer setext-style headers when
4117 possible (levels one and two).
4119 When there is an active region, use it for the header text. When
4120 the point is at an existing header, change the type and level
4121 according to the rules above.
4122 Otherwise, if the line is not empty, create a header using the
4123 text on the current line as the header text.
4124 Finally, if the point is on a blank line, insert empty header
4125 markup (atx) or prompt for text (setext).
4126 See `markdown-insert-header' for more details about how the
4127 header text is determined."
4128 (interactive "*P")
4129 (let (level)
4130 (save-excursion
4131 (when (or (thing-at-point-looking-at markdown-regex-header)
4132 (re-search-backward markdown-regex-header nil t))
4133 ;; level of current or previous header
4134 (setq level (markdown-outline-level))
4135 ;; match group 1 indicates a setext header
4136 (setq setext (match-end 1))))
4137 ;; check prefix argument
4138 (cond
4139 ((and (equal arg '(4)) level (> level 1)) ;; C-u
4140 (cl-decf level))
4141 ((and (equal arg '(16)) level (< level 6)) ;; C-u C-u
4142 (cl-incf level))
4143 (arg ;; numeric prefix
4144 (setq level (prefix-numeric-value arg))))
4145 ;; setext headers must be level one or two
4146 (and level (setq setext (and setext (<= level 2))))
4147 ;; insert the heading
4148 (markdown-insert-header level nil setext)))
4150 (defun markdown-insert-header-setext-dwim (&optional arg)
4151 "Insert or replace header markup, with preference for setext.
4152 See `markdown-insert-header-dwim' for details, including how ARG is handled."
4153 (interactive "*P")
4154 (markdown-insert-header-dwim arg t))
4156 (defun markdown-insert-header-atx-1 ()
4157 "Insert a first level atx-style (hash mark) header.
4158 See `markdown-insert-header'."
4159 (interactive "*")
4160 (markdown-insert-header 1 nil nil))
4162 (defun markdown-insert-header-atx-2 ()
4163 "Insert a level two atx-style (hash mark) header.
4164 See `markdown-insert-header'."
4165 (interactive "*")
4166 (markdown-insert-header 2 nil nil))
4168 (defun markdown-insert-header-atx-3 ()
4169 "Insert a level three atx-style (hash mark) header.
4170 See `markdown-insert-header'."
4171 (interactive "*")
4172 (markdown-insert-header 3 nil nil))
4174 (defun markdown-insert-header-atx-4 ()
4175 "Insert a level four atx-style (hash mark) header.
4176 See `markdown-insert-header'."
4177 (interactive "*")
4178 (markdown-insert-header 4 nil nil))
4180 (defun markdown-insert-header-atx-5 ()
4181 "Insert a level five atx-style (hash mark) header.
4182 See `markdown-insert-header'."
4183 (interactive "*")
4184 (markdown-insert-header 5 nil nil))
4186 (defun markdown-insert-header-atx-6 ()
4187 "Insert a sixth level atx-style (hash mark) header.
4188 See `markdown-insert-header'."
4189 (interactive "*")
4190 (markdown-insert-header 6 nil nil))
4192 (defun markdown-insert-header-setext-1 ()
4193 "Insert a setext-style (underlined) first-level header.
4194 See `markdown-insert-header'."
4195 (interactive "*")
4196 (markdown-insert-header 1 nil t))
4198 (defun markdown-insert-header-setext-2 ()
4199 "Insert a setext-style (underlined) second-level header.
4200 See `markdown-insert-header'."
4201 (interactive "*")
4202 (markdown-insert-header 2 nil t))
4204 (defun markdown-blockquote-indentation (loc)
4205 "Return string containing necessary indentation for a blockquote at LOC.
4206 Also see `markdown-pre-indentation'."
4207 (save-excursion
4208 (goto-char loc)
4209 (let* ((list-level (length (markdown-calculate-list-levels)))
4210 (indent ""))
4211 (dotimes (_ list-level indent)
4212 (setq indent (concat indent " "))))))
4214 (defun markdown-insert-blockquote ()
4215 "Start a blockquote section (or blockquote the region).
4216 If Transient Mark mode is on and a region is active, it is used as
4217 the blockquote text."
4218 (interactive)
4219 (if (use-region-p)
4220 (markdown-blockquote-region (region-beginning) (region-end))
4221 (markdown-ensure-blank-line-before)
4222 (insert (markdown-blockquote-indentation (point)) "> ")
4223 (markdown-ensure-blank-line-after)))
4225 (defun markdown-block-region (beg end prefix)
4226 "Format the region using a block prefix.
4227 Arguments BEG and END specify the beginning and end of the
4228 region. The characters PREFIX will appear at the beginning
4229 of each line."
4230 (save-excursion
4231 (let* ((end-marker (make-marker))
4232 (beg-marker (make-marker))
4233 (prefix-without-trailing-whitespace
4234 (replace-regexp-in-string (rx (+ blank) eos) "" prefix)))
4235 ;; Ensure blank line after and remove extra whitespace
4236 (goto-char end)
4237 (skip-syntax-backward "-")
4238 (set-marker end-marker (point))
4239 (delete-horizontal-space)
4240 (markdown-ensure-blank-line-after)
4241 ;; Ensure blank line before and remove extra whitespace
4242 (goto-char beg)
4243 (skip-syntax-forward "-")
4244 (delete-horizontal-space)
4245 (markdown-ensure-blank-line-before)
4246 (set-marker beg-marker (point))
4247 ;; Insert PREFIX before each line
4248 (goto-char beg-marker)
4249 (while (and (< (line-beginning-position) end-marker)
4250 (not (eobp)))
4251 ;; Don’t insert trailing whitespace.
4252 (insert (if (eolp) prefix-without-trailing-whitespace prefix))
4253 (forward-line)))))
4255 (defun markdown-blockquote-region (beg end)
4256 "Blockquote the region.
4257 Arguments BEG and END specify the beginning and end of the region."
4258 (interactive "*r")
4259 (markdown-block-region
4260 beg end (concat (markdown-blockquote-indentation
4261 (max (point-min) (1- beg))) "> ")))
4263 (defun markdown-pre-indentation (loc)
4264 "Return string containing necessary whitespace for a pre block at LOC.
4265 Also see `markdown-blockquote-indentation'."
4266 (save-excursion
4267 (goto-char loc)
4268 (let* ((list-level (length (markdown-calculate-list-levels)))
4269 indent)
4270 (dotimes (_ (1+ list-level) indent)
4271 (setq indent (concat indent " "))))))
4273 (defun markdown-insert-pre ()
4274 "Start a preformatted section (or apply to the region).
4275 If Transient Mark mode is on and a region is active, it is marked
4276 as preformatted text."
4277 (interactive)
4278 (if (use-region-p)
4279 (markdown-pre-region (region-beginning) (region-end))
4280 (markdown-ensure-blank-line-before)
4281 (insert (markdown-pre-indentation (point)))
4282 (markdown-ensure-blank-line-after)))
4284 (defun markdown-pre-region (beg end)
4285 "Format the region as preformatted text.
4286 Arguments BEG and END specify the beginning and end of the region."
4287 (interactive "*r")
4288 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
4289 (markdown-block-region beg end indent)))
4291 (defun markdown-electric-backquote (arg)
4292 "Insert a backquote.
4293 The numeric prefix argument ARG says how many times to repeat the insertion.
4294 Call `markdown-insert-gfm-code-block' interactively
4295 if three backquotes inserted at the beginning of line."
4296 (interactive "*P")
4297 (self-insert-command (prefix-numeric-value arg))
4298 (when (and markdown-gfm-use-electric-backquote (looking-back "^```" nil))
4299 (replace-match "")
4300 (call-interactively #'markdown-insert-gfm-code-block)))
4302 (defconst markdown-gfm-recognized-languages
4303 ;; To reproduce/update, evaluate the let-form in
4304 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
4305 ;; but with appropriate use of a keyboard macro, indenting and filling it
4306 ;; properly is pretty fast.
4307 '("1C-Enterprise" "4D" "ABAP" "ABNF" "AGS-Script" "AMPL" "ANTLR"
4308 "API-Blueprint" "APL" "ASN.1" "ASP" "ATS" "ActionScript" "Ada"
4309 "Adobe-Font-Metrics" "Agda" "Alloy" "Alpine-Abuild" "Altium-Designer"
4310 "AngelScript" "Ant-Build-System" "ApacheConf" "Apex"
4311 "Apollo-Guidance-Computer" "AppleScript" "Arc" "AsciiDoc" "AspectJ" "Assembly"
4312 "Asymptote" "Augeas" "AutoHotkey" "AutoIt" "Awk" "Ballerina" "Batchfile"
4313 "Befunge" "BibTeX" "Bison" "BitBake" "Blade" "BlitzBasic" "BlitzMax"
4314 "Bluespec" "Boo" "Brainfuck" "Brightscript" "C#" "C++" "C-ObjDump"
4315 "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "COLLADA" "CSON" "CSS" "CSV" "CWeb"
4316 "Cabal-Config" "Cap'n-Proto" "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK"
4317 "Cirru" "Clarion" "Clean" "Click" "Clojure" "Closure-Templates"
4318 "Cloud-Firestore-Security-Rules" "CoNLL-U" "CodeQL" "CoffeeScript"
4319 "ColdFusion" "ColdFusion-CFC" "Common-Lisp" "Common-Workflow-Language"
4320 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal" "Csound"
4321 "Csound-Document" "Csound-Score" "Cuda" "Cycript" "Cython" "D-ObjDump"
4322 "DIGITAL-Command-Language" "DM" "DNS-Zone" "DTrace" "Dafny" "Darcs-Patch"
4323 "Dart" "DataWeave" "Dhall" "Diff" "DirectX-3D-File" "Dockerfile" "Dogescript"
4324 "Dylan" "EBNF" "ECL" "ECLiPSe" "EJS" "EML" "EQ" "Eagle" "Easybuild"
4325 "Ecere-Projects" "EditorConfig" "Edje-Data-Collection" "Eiffel" "Elixir" "Elm"
4326 "Emacs-Lisp" "EmberScript" "Erlang" "F#" "F*" "FIGlet-Font" "FLUX" "Factor"
4327 "Fancy" "Fantom" "Faust" "Filebench-WML" "Filterscript" "Formatted" "Forth"
4328 "Fortran" "Fortran-Free-Form" "FreeMarker" "Frege" "G-code" "GAML" "GAMS"
4329 "GAP" "GCC-Machine-Description" "GDB" "GDScript" "GEDCOM" "GLSL" "GN"
4330 "Game-Maker-Language" "Genie" "Genshi" "Gentoo-Ebuild" "Gentoo-Eclass"
4331 "Gerber-Image" "Gettext-Catalog" "Gherkin" "Git-Attributes" "Git-Config"
4332 "Glyph" "Glyph-Bitmap-Distribution-Format" "Gnuplot" "Go" "Golo" "Gosu"
4333 "Grace" "Gradle" "Grammatical-Framework" "Graph-Modeling-Language" "GraphQL"
4334 "Graphviz-(DOT)" "Groovy" "Groovy-Server-Pages" "HAProxy" "HCL" "HLSL" "HTML"
4335 "HTML+Django" "HTML+ECR" "HTML+EEX" "HTML+ERB" "HTML+PHP" "HTML+Razor" "HTTP"
4336 "HXML" "Hack" "Haml" "Handlebars" "Harbour" "Haskell" "Haxe" "HiveQL" "HolyC"
4337 "Hy" "HyPhy" "IDL" "IGOR-Pro" "INI" "IRC-log" "Idris" "Ignore-List" "Inform-7"
4338 "Inno-Setup" "Io" "Ioke" "Isabelle" "Isabelle-ROOT" "JFlex" "JSON"
4339 "JSON-with-Comments" "JSON5" "JSONLD" "JSONiq" "JSX" "Jasmin" "Java"
4340 "Java-Properties" "Java-Server-Pages" "JavaScript" "JavaScript+ERB" "Jison"
4341 "Jison-Lex" "Jolie" "Jsonnet" "Julia" "Jupyter-Notebook" "KRL" "KiCad-Layout"
4342 "KiCad-Legacy-Layout" "KiCad-Schematic" "Kit" "Kotlin" "LFE" "LLVM" "LOLCODE"
4343 "LSL" "LTspice-Symbol" "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex"
4344 "LilyPond" "Limbo" "Linker-Script" "Linux-Kernel-Module" "Liquid"
4345 "Literate-Agda" "Literate-CoffeeScript" "Literate-Haskell" "LiveScript"
4346 "Logos" "Logtalk" "LookML" "LoomScript" "Lua" "M4" "M4Sugar" "MATLAB"
4347 "MAXScript" "MLIR" "MQL4" "MQL5" "MTML" "MUF" "Macaulay2" "Makefile" "Mako"
4348 "Markdown" "Marko" "Mask" "Mathematica" "Maven-POM" "Max" "MediaWiki"
4349 "Mercury" "Meson" "Metal" "Microsoft-Developer-Studio-Project" "MiniD" "Mirah"
4350 "Modelica" "Modula-2" "Modula-3" "Module-Management-System" "Monkey" "Moocode"
4351 "MoonScript" "Motorola-68K-Assembly" "Muse" "Myghty" "NASL" "NCL" "NEON" "NL"
4352 "NPM-Config" "NSIS" "Nearley" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo"
4353 "NewLisp" "Nextflow" "Nginx" "Nim" "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml"
4354 "ObjDump" "Object-Data-Instance-Notation" "ObjectScript" "Objective-C"
4355 "Objective-C++" "Objective-J" "Odin" "Omgrofl" "Opa" "Opal"
4356 "Open-Policy-Agent" "OpenCL" "OpenEdge-ABL" "OpenQASM" "OpenRC-runscript"
4357 "OpenSCAD" "OpenStep-Property-List" "OpenType-Feature-File" "Org" "Ox"
4358 "Oxygene" "Oz" "P4" "PHP" "PLSQL" "PLpgSQL" "POV-Ray-SDL" "Pan" "Papyrus"
4359 "Parrot" "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal" "Pawn"
4360 "Pep8" "Perl" "Pic" "Pickle" "PicoLisp" "PigLatin" "Pike" "PlantUML" "Pod"
4361 "Pod-6" "PogoScript" "Pony" "PostCSS" "PostScript" "PowerBuilder" "PowerShell"
4362 "Prisma" "Processing" "Proguard" "Prolog" "Propeller-Spin" "Protocol-Buffer"
4363 "Public-Key" "Pug" "Puppet" "Pure-Data" "PureBasic" "PureScript" "Python"
4364 "Python-console" "Python-traceback" "QML" "QMake" "Quake" "RAML" "RDoc"
4365 "REALbasic" "REXX" "RHTML" "RMarkdown" "RPC" "RPM-Spec" "RUNOFF" "Racket"
4366 "Ragel" "Raku" "Rascal" "Raw-token-data" "Readline-Config" "Reason" "Rebol"
4367 "Red" "Redcode" "Regular-Expression" "Ren'Py" "RenderScript"
4368 "Rich-Text-Format" "Ring" "Riot" "RobotFramework" "Roff" "Roff-Manpage"
4369 "Rouge" "Ruby" "Rust" "SAS" "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL"
4370 "SRecode-Template" "SSH-Config" "STON" "SVG" "SWIG" "Sage" "SaltStack" "Sass"
4371 "Scala" "Scaml" "Scheme" "Scilab" "Self" "ShaderLab" "Shell" "ShellSession"
4372 "Shen" "Slash" "Slice" "Slim" "SmPL" "Smali" "Smalltalk" "Smarty" "Solidity"
4373 "SourcePawn" "Spline-Font-Database" "Squirrel" "Stan" "Standard-ML" "Starlark"
4374 "Stata" "Stylus" "SubRip-Text" "SugarSS" "SuperCollider" "Svelte" "Swift"
4375 "SystemVerilog" "TI-Program" "TLA" "TOML" "TSQL" "TSX" "TXL" "Tcl" "Tcsh"
4376 "TeX" "Tea" "Terra" "Texinfo" "Text" "Textile" "Thrift" "Turing" "Turtle"
4377 "Twig" "Type-Language" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset"
4378 "Unix-Assembly" "Uno" "UnrealScript" "UrWeb" "VBA" "VBScript" "VCL" "VHDL"
4379 "Vala" "Verilog" "Vim-Snippet" "Vim-script" "Visual-Basic-.NET" "Volt" "Vue"
4380 "Wavefront-Material" "Wavefront-Object" "Web-Ontology-Language" "WebAssembly"
4381 "WebIDL" "WebVTT" "Wget-Config" "Windows-Registry-Entries" "Wollok"
4382 "World-of-Warcraft-Addon-Data" "X-BitMap" "X-Font-Directory-Index" "X-PixMap"
4383 "X10" "XC" "XCompose" "XML" "XML-Property-List" "XPages" "XProc" "XQuery" "XS"
4384 "XSLT" "Xojo" "Xtend" "YAML" "YANG" "YARA" "YASnippet" "Yacc" "ZAP" "ZIL"
4385 "Zeek" "ZenScript" "Zephir" "Zig" "Zimpl" "cURL-Config" "desktop" "dircolors"
4386 "eC" "edn" "fish" "mIRC-Script" "mcfunction" "mupad" "nanorc" "nesC" "ooc"
4387 "reStructuredText" "sed" "wdl" "wisp" "xBase")
4388 "Language specifiers recognized by GitHub's syntax highlighting features.")
4390 (defvar-local markdown-gfm-used-languages nil
4391 "Language names used in GFM code blocks.")
4393 (defun markdown-trim-whitespace (str)
4394 (replace-regexp-in-string
4395 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str))
4397 (defun markdown-clean-language-string (str)
4398 (replace-regexp-in-string
4399 "{\\.?\\|}" "" (markdown-trim-whitespace str)))
4401 (defun markdown-validate-language-string (widget)
4402 (let ((str (widget-value widget)))
4403 (unless (string= str (markdown-clean-language-string str))
4404 (widget-put widget :error (format "Invalid language spec: '%s'" str))
4405 widget)))
4407 (defun markdown-gfm-get-corpus ()
4408 "Create corpus of recognized GFM code block languages for the given buffer."
4409 (let ((given-corpus (append markdown-gfm-additional-languages
4410 markdown-gfm-recognized-languages)))
4411 (append
4412 markdown-gfm-used-languages
4413 (if markdown-gfm-downcase-languages (cl-mapcar #'downcase given-corpus)
4414 given-corpus))))
4416 (defun markdown-gfm-add-used-language (lang)
4417 "Clean LANG and add to list of used languages."
4418 (setq markdown-gfm-used-languages
4419 (cons lang (remove lang markdown-gfm-used-languages))))
4421 (defcustom markdown-spaces-after-code-fence 1
4422 "Number of space characters to insert after a code fence.
4423 \\<gfm-mode-map>\\[markdown-insert-gfm-code-block] inserts this many spaces between an
4424 opening code fence and an info string."
4425 :group 'markdown
4426 :type 'integer
4427 :safe #'natnump
4428 :package-version '(markdown-mode . "2.3"))
4430 (defcustom markdown-code-block-braces nil
4431 "When non-nil, automatically insert braces for GFM code blocks."
4432 :group 'markdown
4433 :type 'boolean)
4435 (defun markdown-insert-gfm-code-block (&optional lang edit)
4436 "Insert GFM code block for language LANG.
4437 If LANG is nil, the language will be queried from user. If a
4438 region is active, wrap this region with the markup instead. If
4439 the region boundaries are not on empty lines, these are added
4440 automatically in order to have the correct markup. When EDIT is
4441 non-nil (e.g., when \\[universal-argument] is given), edit the
4442 code block in an indirect buffer after insertion."
4443 (interactive
4444 (list (let ((completion-ignore-case nil))
4445 (condition-case nil
4446 (markdown-clean-language-string
4447 (completing-read
4448 "Programming language: "
4449 (markdown-gfm-get-corpus)
4450 nil 'confirm (car markdown-gfm-used-languages)
4451 'markdown-gfm-language-history))
4452 (quit "")))
4453 current-prefix-arg))
4454 (unless (string= lang "") (markdown-gfm-add-used-language lang))
4455 (when (and (> (length lang) 0)
4456 (not markdown-code-block-braces))
4457 (setq lang (concat (make-string markdown-spaces-after-code-fence ?\s)
4458 lang)))
4459 (let ((gfm-open-brace (if markdown-code-block-braces "{" ""))
4460 (gfm-close-brace (if markdown-code-block-braces "}" "")))
4461 (if (use-region-p)
4462 (let* ((b (region-beginning)) (e (region-end)) end
4463 (indent (progn (goto-char b) (current-indentation))))
4464 (goto-char e)
4465 ;; if we're on a blank line, don't newline, otherwise the ```
4466 ;; should go on its own line
4467 (unless (looking-back "\n" nil)
4468 (newline))
4469 (indent-to indent)
4470 (insert "```")
4471 (markdown-ensure-blank-line-after)
4472 (setq end (point))
4473 (goto-char b)
4474 ;; if we're on a blank line, insert the quotes here, otherwise
4475 ;; add a new line first
4476 (unless (looking-at-p "\n")
4477 (newline)
4478 (forward-line -1))
4479 (markdown-ensure-blank-line-before)
4480 (indent-to indent)
4481 (insert "```" gfm-open-brace lang gfm-close-brace)
4482 (markdown-syntax-propertize-fenced-block-constructs (line-beginning-position) end))
4483 (let ((indent (current-indentation))
4484 start-bol)
4485 (delete-horizontal-space :backward-only)
4486 (markdown-ensure-blank-line-before)
4487 (indent-to indent)
4488 (setq start-bol (line-beginning-position))
4489 (insert "```" gfm-open-brace lang gfm-close-brace "\n")
4490 (indent-to indent)
4491 (unless edit (insert ?\n))
4492 (indent-to indent)
4493 (insert "```")
4494 (markdown-ensure-blank-line-after)
4495 (markdown-syntax-propertize-fenced-block-constructs start-bol (point)))
4496 (end-of-line 0)
4497 (when edit (markdown-edit-code-block)))))
4499 (defun markdown-code-block-lang (&optional pos-prop)
4500 "Return the language name for a GFM or tilde fenced code block.
4501 The beginning of the block may be described by POS-PROP,
4502 a cons of (pos . prop) giving the position and property
4503 at the beginning of the block."
4504 (or pos-prop
4505 (setq pos-prop
4506 (markdown-max-of-seq
4507 #'car
4508 (cl-remove-if
4509 #'null
4510 (cl-mapcar
4511 #'markdown-find-previous-prop
4512 (markdown-get-fenced-block-begin-properties))))))
4513 (when pos-prop
4514 (goto-char (car pos-prop))
4515 (set-match-data (get-text-property (point) (cdr pos-prop)))
4516 ;; Note: Hard-coded group number assumes tilde
4517 ;; and GFM fenced code regexp groups agree.
4518 (let ((begin (match-beginning 3))
4519 (end (match-end 3)))
4520 (when (and begin end)
4521 ;; Fix language strings beginning with periods, like ".ruby".
4522 (when (eq (char-after begin) ?.)
4523 (setq begin (1+ begin)))
4524 (buffer-substring-no-properties begin end)))))
4526 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer)
4527 (with-current-buffer (or buffer (current-buffer))
4528 (save-excursion
4529 (goto-char (point-min))
4530 (cl-loop
4531 with prop = 'markdown-gfm-block-begin
4532 for pos-prop = (markdown-find-next-prop prop)
4533 while pos-prop
4534 for lang = (markdown-code-block-lang pos-prop)
4535 do (progn (when lang (markdown-gfm-add-used-language lang))
4536 (goto-char (next-single-property-change (point) prop)))))))
4538 (defun markdown-insert-foldable-block ()
4539 "Insert details disclosure element to make content foldable.
4540 If a region is active, wrap this region with the disclosure
4541 element. More detais here https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details."
4542 (interactive)
4543 (let ((details-open-tag "<details>")
4544 (details-close-tag "</details>")
4545 (summary-open-tag "<summary>")
4546 (summary-close-tag " </summary>"))
4547 (if (use-region-p)
4548 (let* ((b (region-beginning))
4549 (e (region-end))
4550 (indent (progn (goto-char b) (current-indentation))))
4551 (goto-char e)
4552 ;; if we're on a blank line, don't newline, otherwise the tags
4553 ;; should go on its own line
4554 (unless (looking-back "\n" nil)
4555 (newline))
4556 (indent-to indent)
4557 (insert details-close-tag)
4558 (markdown-ensure-blank-line-after)
4559 (goto-char b)
4560 ;; if we're on a blank line, insert the quotes here, otherwise
4561 ;; add a new line first
4562 (unless (looking-at-p "\n")
4563 (newline)
4564 (forward-line -1))
4565 (markdown-ensure-blank-line-before)
4566 (indent-to indent)
4567 (insert details-open-tag "\n")
4568 (insert summary-open-tag summary-close-tag)
4569 (search-backward summary-close-tag))
4570 (let ((indent (current-indentation)))
4571 (delete-horizontal-space :backward-only)
4572 (markdown-ensure-blank-line-before)
4573 (indent-to indent)
4574 (insert details-open-tag "\n")
4575 (insert summary-open-tag summary-close-tag "\n")
4576 (insert details-close-tag)
4577 (indent-to indent)
4578 (markdown-ensure-blank-line-after)
4579 (search-backward summary-close-tag)))))
4582 ;;; Footnotes =================================================================
4584 (defun markdown-footnote-counter-inc ()
4585 "Increment `markdown-footnote-counter' and return the new value."
4586 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
4587 (save-excursion
4588 (goto-char (point-min))
4589 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
4590 (point-max) t)
4591 (let ((fn (string-to-number (match-string 1))))
4592 (when (> fn markdown-footnote-counter)
4593 (setq markdown-footnote-counter fn))))))
4594 (cl-incf markdown-footnote-counter))
4596 (defun markdown-insert-footnote ()
4597 "Insert footnote with a new number and move point to footnote definition."
4598 (interactive)
4599 (let ((fn (markdown-footnote-counter-inc)))
4600 (insert (format "[^%d]" fn))
4601 (markdown-footnote-text-find-new-location)
4602 (markdown-ensure-blank-line-before)
4603 (unless (markdown-cur-line-blank-p)
4604 (insert "\n"))
4605 (insert (format "[^%d]: " fn))
4606 (markdown-ensure-blank-line-after)))
4608 (defun markdown-footnote-text-find-new-location ()
4609 "Position the point at the proper location for a new footnote text."
4610 (cond
4611 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
4612 ((eq markdown-footnote-location 'immediately) (markdown-end-of-text-block))
4613 ((eq markdown-footnote-location 'subtree) (markdown-end-of-subtree))
4614 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
4616 (defun markdown-footnote-kill ()
4617 "Kill the footnote at point.
4618 The footnote text is killed (and added to the kill ring), the
4619 footnote marker is deleted. Point has to be either at the
4620 footnote marker or in the footnote text."
4621 (interactive)
4622 (let ((marker-pos nil)
4623 (skip-deleting-marker nil)
4624 (starting-footnote-text-positions
4625 (markdown-footnote-text-positions)))
4626 (when starting-footnote-text-positions
4627 ;; We're starting in footnote text, so mark our return position and jump
4628 ;; to the marker if possible.
4629 (let ((marker-pos (markdown-footnote-find-marker
4630 (cl-first starting-footnote-text-positions))))
4631 (if marker-pos
4632 (goto-char (1- marker-pos))
4633 ;; If there isn't a marker, we still want to kill the text.
4634 (setq skip-deleting-marker t))))
4635 ;; Either we didn't start in the text, or we started in the text and jumped
4636 ;; to the marker. We want to assume we're at the marker now and error if
4637 ;; we're not.
4638 (unless skip-deleting-marker
4639 (let ((marker (markdown-footnote-delete-marker)))
4640 (unless marker
4641 (error "Not at a footnote"))
4642 ;; Even if we knew the text position before, it changed when we deleted
4643 ;; the label.
4644 (setq marker-pos (cl-second marker))
4645 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker))))
4646 (unless new-text-pos
4647 (error "No text for footnote `%s'" (cl-first marker)))
4648 (goto-char new-text-pos))))
4649 (let ((pos (markdown-footnote-kill-text)))
4650 (goto-char (if starting-footnote-text-positions
4652 marker-pos)))))
4654 (defun markdown-footnote-delete-marker ()
4655 "Delete a footnote marker at point.
4656 Returns a list (ID START) containing the footnote ID and the
4657 start position of the marker before deletion. If no footnote
4658 marker was deleted, this function returns NIL."
4659 (let ((marker (markdown-footnote-marker-positions)))
4660 (when marker
4661 (delete-region (cl-second marker) (cl-third marker))
4662 (butlast marker))))
4664 (defun markdown-footnote-kill-text ()
4665 "Kill footnote text at point.
4666 Returns the start position of the footnote text before deletion,
4667 or NIL if point was not inside a footnote text.
4669 The killed text is placed in the kill ring (without the footnote
4670 number)."
4671 (let ((fn (markdown-footnote-text-positions)))
4672 (when fn
4673 (let ((text (delete-and-extract-region (cl-second fn) (cl-third fn))))
4674 (string-match (concat "\\[\\" (cl-first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
4675 (kill-new (match-string 1 text))
4676 (when (and (markdown-cur-line-blank-p)
4677 (markdown-prev-line-blank-p)
4678 (not (bobp)))
4679 (delete-region (1- (point)) (point)))
4680 (cl-second fn)))))
4682 (defun markdown-footnote-goto-text ()
4683 "Jump to the text of the footnote at point."
4684 (interactive)
4685 (let ((fn (car (markdown-footnote-marker-positions))))
4686 (unless fn
4687 (user-error "Not at a footnote marker"))
4688 (let ((new-pos (markdown-footnote-find-text fn)))
4689 (unless new-pos
4690 (error "No definition found for footnote `%s'" fn))
4691 (goto-char new-pos))))
4693 (defun markdown-footnote-return ()
4694 "Return from a footnote to its footnote number in the main text."
4695 (interactive)
4696 (let ((fn (save-excursion
4697 (car (markdown-footnote-text-positions)))))
4698 (unless fn
4699 (user-error "Not in a footnote"))
4700 (let ((new-pos (markdown-footnote-find-marker fn)))
4701 (unless new-pos
4702 (error "Footnote marker `%s' not found" fn))
4703 (goto-char new-pos))))
4705 (defun markdown-footnote-find-marker (id)
4706 "Find the location of the footnote marker with ID.
4707 The actual buffer position returned is the position directly
4708 following the marker's closing bracket. If no marker is found,
4709 NIL is returned."
4710 (save-excursion
4711 (goto-char (point-min))
4712 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
4713 (skip-chars-backward "^]")
4714 (point))))
4716 (defun markdown-footnote-find-text (id)
4717 "Find the location of the text of footnote ID.
4718 The actual buffer position returned is the position of the first
4719 character of the text, after the footnote's identifier. If no
4720 footnote text is found, NIL is returned."
4721 (save-excursion
4722 (goto-char (point-min))
4723 (when (re-search-forward (concat "^ \\{0,3\\}\\[" id "\\]:") nil t)
4724 (skip-chars-forward "[ \t]")
4725 (point))))
4727 (defun markdown-footnote-marker-positions ()
4728 "Return the position and ID of the footnote marker point is on.
4729 The return value is a list (ID START END). If point is not on a
4730 footnote, NIL is returned."
4731 ;; first make sure we're at a footnote marker
4732 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
4733 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
4734 (save-excursion
4735 ;; move point between [ and ^:
4736 (if (looking-at-p "\\[")
4737 (forward-char 1)
4738 (skip-chars-backward "^["))
4739 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
4740 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
4742 (defun markdown-footnote-text-positions ()
4743 "Return the start and end positions of the footnote text point is in.
4744 The exact return value is a list of three elements: (ID START END).
4745 The start position is the position of the opening bracket
4746 of the footnote id. The end position is directly after the
4747 newline that ends the footnote. If point is not in a footnote,
4748 NIL is returned instead."
4749 (save-excursion
4750 (let (result)
4751 (move-beginning-of-line 1)
4752 ;; Try to find the label. If we haven't found the label and we're at a blank
4753 ;; or indented line, back up if possible.
4754 (while (and
4755 (not (and (looking-at markdown-regex-footnote-definition)
4756 (setq result (list (match-string 1) (point)))))
4757 (and (not (bobp))
4758 (or (markdown-cur-line-blank-p)
4759 (>= (current-indentation) 4))))
4760 (forward-line -1))
4761 (when result
4762 ;; Advance if there is a next line that is either blank or indented.
4763 ;; (Need to check if we're on the last line, because
4764 ;; markdown-next-line-blank-p returns true for last line in buffer.)
4765 (while (and (/= (line-end-position) (point-max))
4766 (or (markdown-next-line-blank-p)
4767 (>= (markdown-next-line-indent) 4)))
4768 (forward-line))
4769 ;; Move back while the current line is blank.
4770 (while (markdown-cur-line-blank-p)
4771 (forward-line -1))
4772 ;; Advance to capture this line and a single trailing newline (if there
4773 ;; is one).
4774 (forward-line)
4775 (append result (list (point)))))))
4777 (defun markdown-get-defined-footnotes ()
4778 "Return a list of all defined footnotes.
4779 Result is an alist of pairs (MARKER . LINE), where MARKER is the
4780 footnote marker, a string, and LINE is the line number containing
4781 the footnote definition.
4783 For example, suppose the following footnotes are defined at positions
4784 448 and 475:
4786 \[^1]: First footnote here.
4787 \[^marker]: Second footnote.
4789 Then the returned list is: ((\"^1\" . 478) (\"^marker\" . 475))"
4790 (save-excursion
4791 (goto-char (point-min))
4792 (let (footnotes)
4793 (while (markdown-search-until-condition
4794 (lambda () (and (not (markdown-code-block-at-point-p))
4795 (not (markdown-inline-code-at-point-p))
4796 (not (markdown-in-comment-p))))
4797 markdown-regex-footnote-definition nil t)
4798 (let ((marker (match-string-no-properties 1))
4799 (pos (match-beginning 0)))
4800 (unless (zerop (length marker))
4801 (cl-pushnew (cons marker pos) footnotes :test #'equal))))
4802 (reverse footnotes))))
4805 ;;; Element Removal ===========================================================
4807 (defun markdown-kill-thing-at-point ()
4808 "Kill thing at point and add important text, without markup, to kill ring.
4809 Possible things to kill include (roughly in order of precedence):
4810 inline code, headers, horizontal rules, links (add link text to
4811 kill ring), images (add alt text to kill ring), angle uri, email
4812 addresses, bold, italics, reference definition (add URI to kill
4813 ring), footnote markers and text (kill both marker and text, add
4814 text to kill ring), and list items."
4815 (interactive "*")
4816 (let (val)
4817 (cond
4818 ;; Inline code
4819 ((markdown-inline-code-at-point)
4820 (kill-new (match-string 2))
4821 (delete-region (match-beginning 0) (match-end 0)))
4822 ;; ATX header
4823 ((thing-at-point-looking-at markdown-regex-header-atx)
4824 (kill-new (match-string 2))
4825 (delete-region (match-beginning 0) (match-end 0)))
4826 ;; Setext header
4827 ((thing-at-point-looking-at markdown-regex-header-setext)
4828 (kill-new (match-string 1))
4829 (delete-region (match-beginning 0) (match-end 0)))
4830 ;; Horizontal rule
4831 ((thing-at-point-looking-at markdown-regex-hr)
4832 (kill-new (match-string 0))
4833 (delete-region (match-beginning 0) (match-end 0)))
4834 ;; Inline link or image (add link or alt text to kill ring)
4835 ((thing-at-point-looking-at markdown-regex-link-inline)
4836 (kill-new (match-string 3))
4837 (delete-region (match-beginning 0) (match-end 0)))
4838 ;; Reference link or image (add link or alt text to kill ring)
4839 ((thing-at-point-looking-at markdown-regex-link-reference)
4840 (kill-new (match-string 3))
4841 (delete-region (match-beginning 0) (match-end 0)))
4842 ;; Angle URI (add URL to kill ring)
4843 ((thing-at-point-looking-at markdown-regex-angle-uri)
4844 (kill-new (match-string 2))
4845 (delete-region (match-beginning 0) (match-end 0)))
4846 ;; Email address in angle brackets (add email address to kill ring)
4847 ((thing-at-point-looking-at markdown-regex-email)
4848 (kill-new (match-string 1))
4849 (delete-region (match-beginning 0) (match-end 0)))
4850 ;; Wiki link (add alias text to kill ring)
4851 ((and markdown-enable-wiki-links
4852 (thing-at-point-looking-at markdown-regex-wiki-link))
4853 (kill-new (markdown-wiki-link-alias))
4854 (delete-region (match-beginning 1) (match-end 1)))
4855 ;; Bold
4856 ((thing-at-point-looking-at markdown-regex-bold)
4857 (kill-new (match-string 4))
4858 (delete-region (match-beginning 2) (match-end 2)))
4859 ;; Italics
4860 ((thing-at-point-looking-at markdown-regex-italic)
4861 (kill-new (match-string 3))
4862 (delete-region (match-beginning 1) (match-end 1)))
4863 ;; Strikethrough
4864 ((thing-at-point-looking-at markdown-regex-strike-through)
4865 (kill-new (match-string 4))
4866 (delete-region (match-beginning 2) (match-end 2)))
4867 ;; Footnote marker (add footnote text to kill ring)
4868 ((thing-at-point-looking-at markdown-regex-footnote)
4869 (markdown-footnote-kill))
4870 ;; Footnote text (add footnote text to kill ring)
4871 ((setq val (markdown-footnote-text-positions))
4872 (markdown-footnote-kill))
4873 ;; Reference definition (add URL to kill ring)
4874 ((thing-at-point-looking-at markdown-regex-reference-definition)
4875 (kill-new (match-string 5))
4876 (delete-region (match-beginning 0) (match-end 0)))
4877 ;; List item
4878 ((setq val (markdown-cur-list-item-bounds))
4879 (kill-new (delete-and-extract-region (cl-first val) (cl-second val))))
4881 (user-error "Nothing found at point to kill")))))
4883 (defun markdown-kill-outline ()
4884 "Kill visible heading and add it to `kill-ring'."
4885 (interactive)
4886 (save-excursion
4887 (markdown-outline-previous)
4888 (kill-region (point) (progn (markdown-outline-next) (point)))))
4890 (defun markdown-kill-block ()
4891 "Kill visible code block, list item, or blockquote and add it to `kill-ring'."
4892 (interactive)
4893 (save-excursion
4894 (markdown-backward-block)
4895 (kill-region (point) (progn (markdown-forward-block) (point)))))
4898 ;;; Indentation ===============================================================
4900 (defun markdown-indent-find-next-position (cur-pos positions)
4901 "Return the position after the index of CUR-POS in POSITIONS.
4902 Positions are calculated by `markdown-calc-indents'."
4903 (while (and positions
4904 (not (equal cur-pos (car positions))))
4905 (setq positions (cdr positions)))
4906 (or (cadr positions) 0))
4908 (defun markdown-outdent-find-next-position (cur-pos positions)
4909 "Return the maximal element that precedes CUR-POS from POSITIONS.
4910 Positions are calculated by `markdown-calc-indents'."
4911 (let ((result 0))
4912 (dolist (i positions)
4913 (when (< i cur-pos)
4914 (setq result (max result i))))
4915 result))
4917 (defun markdown-indent-line ()
4918 "Indent the current line using some heuristics.
4919 If the _previous_ command was either `markdown-enter-key' or
4920 `markdown-cycle', then we should cycle to the next
4921 reasonable indentation position. Otherwise, we could have been
4922 called directly by `markdown-enter-key', by an initial call of
4923 `markdown-cycle', or indirectly by `auto-fill-mode'. In
4924 these cases, indent to the default position.
4925 Positions are calculated by `markdown-calc-indents'."
4926 (interactive)
4927 (let ((positions (markdown-calc-indents))
4928 (point-pos (current-column))
4929 (_ (back-to-indentation))
4930 (cur-pos (current-column)))
4931 (if (not (equal this-command 'markdown-cycle))
4932 (indent-line-to (car positions))
4933 (setq positions (sort (delete-dups positions) '<))
4934 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions))
4935 (new-point-pos (max (+ point-pos (- next-pos cur-pos)) 0)))
4936 (indent-line-to next-pos)
4937 (move-to-column new-point-pos)))))
4939 (defun markdown-calc-indents ()
4940 "Return a list of indentation columns to cycle through.
4941 The first element in the returned list should be considered the
4942 default indentation level. This function does not worry about
4943 duplicate positions, which are handled up by calling functions."
4944 (let (pos prev-line-pos positions)
4946 ;; Indentation of previous line
4947 (setq prev-line-pos (markdown-prev-line-indent))
4948 (setq positions (cons prev-line-pos positions))
4950 ;; Indentation of previous non-list-marker text
4951 (when (setq pos (save-excursion
4952 (forward-line -1)
4953 (when (looking-at markdown-regex-list)
4954 (- (match-end 3) (match-beginning 0)))))
4955 (setq positions (cons pos positions)))
4957 ;; Indentation required for a pre block in current context
4958 (setq pos (length (markdown-pre-indentation (point))))
4959 (setq positions (cons pos positions))
4961 ;; Indentation of the previous line + tab-width
4962 (if prev-line-pos
4963 (setq positions (cons (+ prev-line-pos tab-width) positions))
4964 (setq positions (cons tab-width positions)))
4966 ;; Indentation of the previous line - tab-width
4967 (if (and prev-line-pos (> prev-line-pos tab-width))
4968 (setq positions (cons (- prev-line-pos tab-width) positions)))
4970 ;; Indentation of all preceding list markers (when in a list)
4971 (when (setq pos (markdown-calculate-list-levels))
4972 (setq positions (append pos positions)))
4974 ;; First column
4975 (setq positions (cons 0 positions))
4977 ;; Return reversed list
4978 (reverse positions)))
4980 (defun markdown-enter-key () ;FIXME: Partly obsoleted by electric-indent
4981 "Handle RET depending on the context.
4982 If the point is at a table, move to the next row. Otherwise,
4983 indent according to value of `markdown-indent-on-enter'.
4984 When it is nil, simply call `newline'. Otherwise, indent the next line
4985 following RET using `markdown-indent-line'. Furthermore, when it
4986 is set to \\='indent-and-new-item and the point is in a list item,
4987 start a new item with the same indentation. If the point is in an
4988 empty list item, remove it (so that pressing RET twice when in a
4989 list simply adds a blank line)."
4990 (interactive)
4991 (cond
4992 ;; Table
4993 ((markdown-table-at-point-p)
4994 (call-interactively #'markdown-table-next-row))
4995 ;; Indent non-table text
4996 (markdown-indent-on-enter
4997 (let (bounds)
4998 (if (and (memq markdown-indent-on-enter '(indent-and-new-item))
4999 (setq bounds (markdown-cur-list-item-bounds)))
5000 (let ((beg (cl-first bounds))
5001 (end (cl-second bounds))
5002 (length (cl-fourth bounds)))
5003 ;; Point is in a list item
5004 (if (= (- end beg) length)
5005 ;; Delete blank list
5006 (progn
5007 (delete-region beg end)
5008 (newline)
5009 (markdown-indent-line))
5010 (call-interactively #'markdown-insert-list-item)))
5011 ;; Point is not in a list
5012 (newline)
5013 (markdown-indent-line))))
5014 ;; Insert a raw newline
5015 (t (newline))))
5017 (defun markdown-outdent-or-delete (arg)
5018 "Handle BACKSPACE by cycling through indentation points.
5019 When BACKSPACE is pressed, if there is only whitespace
5020 before the current point, then outdent the line one level.
5021 Otherwise, do normal delete by repeating
5022 `backward-delete-char-untabify' ARG times."
5023 (interactive "*p")
5024 (if (use-region-p)
5025 (backward-delete-char-untabify arg)
5026 (let ((cur-pos (current-column))
5027 (start-of-indention (save-excursion
5028 (back-to-indentation)
5029 (current-column)))
5030 (positions (markdown-calc-indents)))
5031 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
5032 (indent-line-to (markdown-outdent-find-next-position cur-pos positions))
5033 (backward-delete-char-untabify arg)))))
5035 (defun markdown-find-leftmost-column (beg end)
5036 "Find the leftmost column in the region from BEG to END."
5037 (let ((mincol 1000))
5038 (save-excursion
5039 (goto-char beg)
5040 (while (< (point) end)
5041 (back-to-indentation)
5042 (unless (looking-at-p "[ \t]*$")
5043 (setq mincol (min mincol (current-column))))
5044 (forward-line 1)
5046 mincol))
5048 (defun markdown-indent-region (beg end arg)
5049 "Indent the region from BEG to END using some heuristics.
5050 When ARG is non-nil, outdent the region instead.
5051 See `markdown-indent-line' and `markdown-indent-line'."
5052 (interactive "*r\nP")
5053 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
5054 (leftmostcol (markdown-find-leftmost-column beg end))
5055 (next-pos (if arg
5056 (markdown-outdent-find-next-position leftmostcol positions)
5057 (markdown-indent-find-next-position leftmostcol positions))))
5058 (indent-rigidly beg end (- next-pos leftmostcol))
5059 (setq deactivate-mark nil)))
5061 (defun markdown-outdent-region (beg end)
5062 "Call `markdown-indent-region' on region from BEG to END with prefix."
5063 (interactive "*r")
5064 (markdown-indent-region beg end t))
5066 (defun markdown--indent-region (start end)
5067 (let ((deactivate-mark nil))
5068 (save-excursion
5069 (goto-char end)
5070 (setq end (point-marker))
5071 (goto-char start)
5072 (when (bolp)
5073 (forward-line 1))
5074 (while (< (point) end)
5075 (unless (or (markdown-code-block-at-point-p) (and (bolp) (eolp)))
5076 (indent-according-to-mode))
5077 (forward-line 1))
5078 (move-marker end nil))))
5081 ;;; Markup Completion =========================================================
5083 (defconst markdown-complete-alist
5084 '((markdown-regex-header-atx . markdown-complete-atx)
5085 (markdown-regex-header-setext . markdown-complete-setext)
5086 (markdown-regex-hr . markdown-complete-hr))
5087 "Association list of form (regexp . function) for markup completion.")
5089 (defun markdown-incomplete-atx-p ()
5090 "Return t if ATX header markup is incomplete and nil otherwise.
5091 Assumes match data is available for `markdown-regex-header-atx'.
5092 Checks that the number of trailing hash marks equals the number of leading
5093 hash marks, that there is only a single space before and after the text,
5094 and that there is no extraneous whitespace in the text."
5096 ;; Number of starting and ending hash marks differs
5097 (not (= (length (match-string 1)) (length (match-string 3))))
5098 ;; When the header text is not empty...
5099 (and (> (length (match-string 2)) 0)
5100 ;; ...if there are extra leading, trailing, or interior spaces
5101 (or (not (= (match-beginning 2) (1+ (match-end 1))))
5102 (not (= (match-beginning 3) (1+ (match-end 2))))
5103 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
5104 ;; When the header text is empty...
5105 (and (= (length (match-string 2)) 0)
5106 ;; ...if there are too many or too few spaces
5107 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
5109 (defun markdown-complete-atx ()
5110 "Complete and normalize ATX headers.
5111 Add or remove hash marks to the end of the header to match the
5112 beginning. Ensure that there is only a single space between hash
5113 marks and header text. Removes extraneous whitespace from header text.
5114 Assumes match data is available for `markdown-regex-header-atx'.
5115 Return nil if markup was complete and non-nil if markup was completed."
5116 (when (markdown-incomplete-atx-p)
5117 (let* ((new-marker (make-marker))
5118 (new-marker (set-marker new-marker (match-end 2))))
5119 ;; Hash marks and spacing at end
5120 (goto-char (match-end 2))
5121 (delete-region (match-end 2) (match-end 3))
5122 (insert " " (match-string 1))
5123 ;; Remove extraneous whitespace from title
5124 (replace-match (markdown-compress-whitespace-string (match-string 2))
5125 t t nil 2)
5126 ;; Spacing at beginning
5127 (goto-char (match-end 1))
5128 (delete-region (match-end 1) (match-beginning 2))
5129 (insert " ")
5130 ;; Leave point at end of text
5131 (goto-char new-marker))))
5133 (defun markdown-incomplete-setext-p ()
5134 "Return t if setext header markup is incomplete and nil otherwise.
5135 Assumes match data is available for `markdown-regex-header-setext'.
5136 Checks that length of underline matches text and that there is no
5137 extraneous whitespace in the text."
5138 (or (not (= (length (match-string 1)) (length (match-string 2))))
5139 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
5141 (defun markdown-complete-setext ()
5142 "Complete and normalize setext headers.
5143 Add or remove underline characters to match length of header
5144 text. Removes extraneous whitespace from header text. Assumes
5145 match data is available for `markdown-regex-header-setext'.
5146 Return nil if markup was complete and non-nil if markup was completed."
5147 (when (markdown-incomplete-setext-p)
5148 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
5149 (char (char-after (match-beginning 2)))
5150 (level (if (char-equal char ?-) 2 1)))
5151 (goto-char (match-beginning 0))
5152 (delete-region (match-beginning 0) (match-end 0))
5153 (markdown-insert-header level text t)
5154 t)))
5156 (defun markdown-incomplete-hr-p ()
5157 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
5158 Assumes match data is available for `markdown-regex-hr'."
5159 (not (member (match-string 0) markdown-hr-strings)))
5161 (defun markdown-complete-hr ()
5162 "Complete horizontal rules.
5163 If horizontal rule string is a member of `markdown-hr-strings',
5164 do nothing. Otherwise, replace with the car of
5165 `markdown-hr-strings'.
5166 Assumes match data is available for `markdown-regex-hr'.
5167 Return nil if markup was complete and non-nil if markup was completed."
5168 (when (markdown-incomplete-hr-p)
5169 (replace-match (car markdown-hr-strings))
5172 (defun markdown-complete ()
5173 "Complete markup of object near point or in region when active.
5174 Handle all objects in `markdown-complete-alist', in order.
5175 See `markdown-complete-at-point' and `markdown-complete-region'."
5176 (interactive "*")
5177 (if (use-region-p)
5178 (markdown-complete-region (region-beginning) (region-end))
5179 (markdown-complete-at-point)))
5181 (defun markdown-complete-at-point ()
5182 "Complete markup of object near point.
5183 Handle all elements of `markdown-complete-alist' in order."
5184 (interactive "*")
5185 (let ((list markdown-complete-alist) found changed)
5186 (while list
5187 (let ((regexp (eval (caar list) t)) ;FIXME: Why `eval'?
5188 (function (cdar list)))
5189 (setq list (cdr list))
5190 (when (thing-at-point-looking-at regexp)
5191 (setq found t)
5192 (setq changed (funcall function))
5193 (setq list nil))))
5194 (if found
5195 (or changed (user-error "Markup at point is complete"))
5196 (user-error "Nothing to complete at point"))))
5198 (defun markdown-complete-region (beg end)
5199 "Complete markup of objects in region from BEG to END.
5200 Handle all objects in `markdown-complete-alist', in order. Each
5201 match is checked to ensure that a previous regexp does not also
5202 match."
5203 (interactive "*r")
5204 (let ((end-marker (set-marker (make-marker) end))
5205 previous)
5206 (dolist (element markdown-complete-alist)
5207 (let ((regexp (eval (car element) t)) ;FIXME: Why `eval'?
5208 (function (cdr element)))
5209 (goto-char beg)
5210 (while (re-search-forward regexp end-marker 'limit)
5211 (when (match-string 0)
5212 ;; Make sure this is not a match for any of the preceding regexps.
5213 ;; This prevents mistaking an HR for a Setext subheading.
5214 (let (match)
5215 (save-match-data
5216 (dolist (prev-regexp previous)
5217 (or match (setq match (looking-back prev-regexp nil)))))
5218 (unless match
5219 (save-excursion (funcall function))))))
5220 (cl-pushnew regexp previous :test #'equal)))
5221 previous))
5223 (defun markdown-complete-buffer ()
5224 "Complete markup for all objects in the current buffer."
5225 (interactive "*")
5226 (markdown-complete-region (point-min) (point-max)))
5229 ;;; Markup Cycling ============================================================
5231 (defun markdown-cycle-atx (arg &optional remove)
5232 "Cycle ATX header markup.
5233 Promote header (decrease level) when ARG is 1 and demote
5234 header (increase level) if arg is -1. When REMOVE is non-nil,
5235 remove the header when the level reaches zero and stop cycling
5236 when it reaches six. Otherwise, perform a proper cycling through
5237 levels one through six. Assumes match data is available for
5238 `markdown-regex-header-atx'."
5239 (let* ((old-level (length (match-string 1)))
5240 (new-level (+ old-level arg))
5241 (text (match-string 2)))
5242 (when (not remove)
5243 (setq new-level (% new-level 6))
5244 (setq new-level (cond ((= new-level 0) 6)
5245 ((< new-level 0) (+ new-level 6))
5246 (t new-level))))
5247 (cond
5248 ((= new-level 0)
5249 (markdown-unwrap-thing-at-point nil 0 2))
5250 ((<= new-level 6)
5251 (goto-char (match-beginning 0))
5252 (delete-region (match-beginning 0) (match-end 0))
5253 (markdown-insert-header new-level text nil)))))
5255 (defun markdown-cycle-setext (arg &optional remove)
5256 "Cycle setext header markup.
5257 Promote header (increase level) when ARG is 1 and demote
5258 header (decrease level or remove) if arg is -1. When demoting a
5259 level-two setext header, replace with a level-three atx header.
5260 When REMOVE is non-nil, remove the header when the level reaches
5261 zero. Otherwise, cycle back to a level six atx header. Assumes
5262 match data is available for `markdown-regex-header-setext'."
5263 (let* ((char (char-after (match-beginning 2)))
5264 (old-level (if (char-equal char ?=) 1 2))
5265 (new-level (+ old-level arg)))
5266 (when (and (not remove) (= new-level 0))
5267 (setq new-level 6))
5268 (cond
5269 ((= new-level 0)
5270 (markdown-unwrap-thing-at-point nil 0 1))
5271 ((<= new-level 2)
5272 (markdown-insert-header new-level nil t))
5273 ((<= new-level 6)
5274 (markdown-insert-header new-level nil nil)))))
5276 (defun markdown-cycle-hr (arg &optional remove)
5277 "Cycle string used for horizontal rule from `markdown-hr-strings'.
5278 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
5279 backwards (promote). When REMOVE is non-nil, remove the hr instead
5280 of cycling when the end of the list is reached.
5281 Assumes match data is available for `markdown-regex-hr'."
5282 (let* ((strings (if (= arg -1)
5283 (reverse markdown-hr-strings)
5284 markdown-hr-strings))
5285 (tail (member (match-string 0) strings))
5286 (new (or (cadr tail)
5287 (if remove
5288 (if (= arg 1)
5290 (car tail))
5291 (car strings)))))
5292 (replace-match new)))
5294 (defun markdown-cycle-bold ()
5295 "Cycle bold markup between underscores and asterisks.
5296 Assumes match data is available for `markdown-regex-bold'."
5297 (save-excursion
5298 (let* ((old-delim (match-string 3))
5299 (new-delim (if (string-equal old-delim "**") "__" "**")))
5300 (replace-match new-delim t t nil 3)
5301 (replace-match new-delim t t nil 5))))
5303 (defun markdown-cycle-italic ()
5304 "Cycle italic markup between underscores and asterisks.
5305 Assumes match data is available for `markdown-regex-italic'."
5306 (save-excursion
5307 (let* ((old-delim (match-string 2))
5308 (new-delim (if (string-equal old-delim "*") "_" "*")))
5309 (replace-match new-delim t t nil 2)
5310 (replace-match new-delim t t nil 4))))
5313 ;;; Keymap ====================================================================
5315 (defun markdown--style-map-prompt ()
5316 "Return a formatted prompt for Markdown markup insertion."
5317 (when markdown-enable-prefix-prompts
5318 (concat
5319 "Markdown: "
5320 (propertize "bold" 'face 'markdown-bold-face) ", "
5321 (propertize "italic" 'face 'markdown-italic-face) ", "
5322 (propertize "code" 'face 'markdown-inline-code-face) ", "
5323 (propertize "C = GFM code" 'face 'markdown-code-face) ", "
5324 (propertize "pre" 'face 'markdown-pre-face) ", "
5325 (propertize "footnote" 'face 'markdown-footnote-text-face) ", "
5326 (propertize "F = foldable" 'face 'markdown-bold-face) ", "
5327 (propertize "q = blockquote" 'face 'markdown-blockquote-face) ", "
5328 (propertize "h & 1-6 = heading" 'face 'markdown-header-face) ", "
5329 (propertize "- = hr" 'face 'markdown-hr-face) ", "
5330 "C-h = more")))
5332 (defun markdown--command-map-prompt ()
5333 "Return prompt for Markdown buffer-wide commands."
5334 (when markdown-enable-prefix-prompts
5335 (concat
5336 "Command: "
5337 (propertize "m" 'face 'markdown-bold-face) "arkdown, "
5338 (propertize "p" 'face 'markdown-bold-face) "review, "
5339 (propertize "o" 'face 'markdown-bold-face) "pen, "
5340 (propertize "e" 'face 'markdown-bold-face) "xport, "
5341 "export & pre" (propertize "v" 'face 'markdown-bold-face) "iew, "
5342 (propertize "c" 'face 'markdown-bold-face) "heck refs, "
5343 (propertize "u" 'face 'markdown-bold-face) "nused refs, "
5344 "C-h = more")))
5346 (defvar markdown-mode-style-map
5347 (let ((map (make-keymap (markdown--style-map-prompt))))
5348 (define-key map (kbd "1") 'markdown-insert-header-atx-1)
5349 (define-key map (kbd "2") 'markdown-insert-header-atx-2)
5350 (define-key map (kbd "3") 'markdown-insert-header-atx-3)
5351 (define-key map (kbd "4") 'markdown-insert-header-atx-4)
5352 (define-key map (kbd "5") 'markdown-insert-header-atx-5)
5353 (define-key map (kbd "6") 'markdown-insert-header-atx-6)
5354 (define-key map (kbd "!") 'markdown-insert-header-setext-1)
5355 (define-key map (kbd "@") 'markdown-insert-header-setext-2)
5356 (define-key map (kbd "b") 'markdown-insert-bold)
5357 (define-key map (kbd "c") 'markdown-insert-code)
5358 (define-key map (kbd "C") 'markdown-insert-gfm-code-block)
5359 (define-key map (kbd "f") 'markdown-insert-footnote)
5360 (define-key map (kbd "F") 'markdown-insert-foldable-block)
5361 (define-key map (kbd "h") 'markdown-insert-header-dwim)
5362 (define-key map (kbd "H") 'markdown-insert-header-setext-dwim)
5363 (define-key map (kbd "i") 'markdown-insert-italic)
5364 (define-key map (kbd "k") 'markdown-insert-kbd)
5365 (define-key map (kbd "l") 'markdown-insert-link)
5366 (define-key map (kbd "p") 'markdown-insert-pre)
5367 (define-key map (kbd "P") 'markdown-pre-region)
5368 (define-key map (kbd "q") 'markdown-insert-blockquote)
5369 (define-key map (kbd "s") 'markdown-insert-strike-through)
5370 (define-key map (kbd "t") 'markdown-insert-table)
5371 (define-key map (kbd "Q") 'markdown-blockquote-region)
5372 (define-key map (kbd "w") 'markdown-insert-wiki-link)
5373 (define-key map (kbd "-") 'markdown-insert-hr)
5374 (define-key map (kbd "[") 'markdown-insert-gfm-checkbox)
5375 ;; Deprecated keys that may be removed in a future version
5376 (define-key map (kbd "e") 'markdown-insert-italic)
5377 map)
5378 "Keymap for Markdown text styling commands.")
5380 (defvar markdown-mode-command-map
5381 (let ((map (make-keymap (markdown--command-map-prompt))))
5382 (define-key map (kbd "m") 'markdown-other-window)
5383 (define-key map (kbd "p") 'markdown-preview)
5384 (define-key map (kbd "e") 'markdown-export)
5385 (define-key map (kbd "v") 'markdown-export-and-preview)
5386 (define-key map (kbd "o") 'markdown-open)
5387 (define-key map (kbd "l") 'markdown-live-preview-mode)
5388 (define-key map (kbd "w") 'markdown-kill-ring-save)
5389 (define-key map (kbd "c") 'markdown-check-refs)
5390 (define-key map (kbd "u") 'markdown-unused-refs)
5391 (define-key map (kbd "n") 'markdown-cleanup-list-numbers)
5392 (define-key map (kbd "]") 'markdown-complete-buffer)
5393 (define-key map (kbd "^") 'markdown-table-sort-lines)
5394 (define-key map (kbd "|") 'markdown-table-convert-region)
5395 (define-key map (kbd "t") 'markdown-table-transpose)
5396 map)
5397 "Keymap for Markdown buffer-wide commands.")
5399 (defvar markdown-mode-map
5400 (let ((map (make-keymap)))
5401 ;; Markup insertion & removal
5402 (define-key map (kbd "C-c C-s") markdown-mode-style-map)
5403 (define-key map (kbd "C-c C-l") 'markdown-insert-link)
5404 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
5405 ;; Promotion, demotion, and cycling
5406 (define-key map (kbd "C-c C--") 'markdown-promote)
5407 (define-key map (kbd "C-c C-=") 'markdown-demote)
5408 (define-key map (kbd "C-c C-]") 'markdown-complete)
5409 ;; Following and doing things
5410 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
5411 (define-key map (kbd "C-c C-d") 'markdown-do)
5412 (define-key map (kbd "C-c '") 'markdown-edit-code-block)
5413 ;; Indentation
5414 (define-key map (kbd "RET") 'markdown-enter-key)
5415 (define-key map (kbd "DEL") 'markdown-outdent-or-delete)
5416 (define-key map (kbd "C-c >") 'markdown-indent-region)
5417 (define-key map (kbd "C-c <") 'markdown-outdent-region)
5418 ;; Visibility cycling
5419 (define-key map (kbd "TAB") 'markdown-cycle)
5420 ;; S-iso-lefttab and S-tab should both be mapped to `backtab' by
5421 ;; (local-)function-key-map.
5422 ;;(define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
5423 ;;(define-key map (kbd "<S-tab>") 'markdown-shifttab)
5424 (define-key map (kbd "<backtab>") 'markdown-shifttab)
5425 ;; Heading and list navigation
5426 (define-key map (kbd "C-c C-n") 'markdown-outline-next)
5427 (define-key map (kbd "C-c C-p") 'markdown-outline-previous)
5428 (define-key map (kbd "C-c C-f") 'markdown-outline-next-same-level)
5429 (define-key map (kbd "C-c C-b") 'markdown-outline-previous-same-level)
5430 (define-key map (kbd "C-c C-u") 'markdown-outline-up)
5431 ;; Buffer-wide commands
5432 (define-key map (kbd "C-c C-c") markdown-mode-command-map)
5433 ;; Subtree, list, and table editing
5434 (define-key map (kbd "C-c <up>") 'markdown-move-up)
5435 (define-key map (kbd "C-c <down>") 'markdown-move-down)
5436 (define-key map (kbd "C-c <left>") 'markdown-promote)
5437 (define-key map (kbd "C-c <right>") 'markdown-demote)
5438 (define-key map (kbd "C-c S-<up>") 'markdown-table-delete-row)
5439 (define-key map (kbd "C-c S-<down>") 'markdown-table-insert-row)
5440 (define-key map (kbd "C-c S-<left>") 'markdown-table-delete-column)
5441 (define-key map (kbd "C-c S-<right>") 'markdown-table-insert-column)
5442 (define-key map (kbd "C-c C-M-h") 'markdown-mark-subtree)
5443 (define-key map (kbd "C-x n s") 'markdown-narrow-to-subtree)
5444 (define-key map (kbd "M-RET") 'markdown-insert-list-item)
5445 (define-key map (kbd "C-c C-j") 'markdown-insert-list-item)
5446 ;; Paragraphs (Markdown context aware)
5447 (define-key map [remap backward-paragraph] 'markdown-backward-paragraph)
5448 (define-key map [remap forward-paragraph] 'markdown-forward-paragraph)
5449 (define-key map [remap mark-paragraph] 'markdown-mark-paragraph)
5450 ;; Blocks (one or more paragraphs)
5451 (define-key map (kbd "C-M-{") 'markdown-backward-block)
5452 (define-key map (kbd "C-M-}") 'markdown-forward-block)
5453 (define-key map (kbd "C-c M-h") 'markdown-mark-block)
5454 (define-key map (kbd "C-x n b") 'markdown-narrow-to-block)
5455 ;; Pages (top-level sections)
5456 (define-key map [remap backward-page] 'markdown-backward-page)
5457 (define-key map [remap forward-page] 'markdown-forward-page)
5458 (define-key map [remap mark-page] 'markdown-mark-page)
5459 (define-key map [remap narrow-to-page] 'markdown-narrow-to-page)
5460 ;; Link Movement
5461 (define-key map (kbd "M-n") 'markdown-next-link)
5462 (define-key map (kbd "M-p") 'markdown-previous-link)
5463 ;; Toggling functionality
5464 (define-key map (kbd "C-c C-x C-e") 'markdown-toggle-math)
5465 (define-key map (kbd "C-c C-x C-f") 'markdown-toggle-fontify-code-blocks-natively)
5466 (define-key map (kbd "C-c C-x C-i") 'markdown-toggle-inline-images)
5467 (define-key map (kbd "C-c C-x C-l") 'markdown-toggle-url-hiding)
5468 (define-key map (kbd "C-c C-x C-m") 'markdown-toggle-markup-hiding)
5469 ;; Alternative keys (in case of problems with the arrow keys)
5470 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
5471 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
5472 (define-key map (kbd "C-c C-x l") 'markdown-promote)
5473 (define-key map (kbd "C-c C-x r") 'markdown-demote)
5474 ;; Deprecated keys that may be removed in a future version
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 l") 'markdown-insert-link) ;; C-c C-l
5477 (define-key map (kbd "C-c C-a r") 'markdown-insert-link) ;; C-c C-l
5478 (define-key map (kbd "C-c C-a u") 'markdown-insert-uri) ;; C-c C-l
5479 (define-key map (kbd "C-c C-a f") 'markdown-insert-footnote)
5480 (define-key map (kbd "C-c C-a w") 'markdown-insert-wiki-link)
5481 (define-key map (kbd "C-c C-t 1") 'markdown-insert-header-atx-1)
5482 (define-key map (kbd "C-c C-t 2") 'markdown-insert-header-atx-2)
5483 (define-key map (kbd "C-c C-t 3") 'markdown-insert-header-atx-3)
5484 (define-key map (kbd "C-c C-t 4") 'markdown-insert-header-atx-4)
5485 (define-key map (kbd "C-c C-t 5") 'markdown-insert-header-atx-5)
5486 (define-key map (kbd "C-c C-t 6") 'markdown-insert-header-atx-6)
5487 (define-key map (kbd "C-c C-t !") 'markdown-insert-header-setext-1)
5488 (define-key map (kbd "C-c C-t @") 'markdown-insert-header-setext-2)
5489 (define-key map (kbd "C-c C-t h") 'markdown-insert-header-dwim)
5490 (define-key map (kbd "C-c C-t H") 'markdown-insert-header-setext-dwim)
5491 (define-key map (kbd "C-c C-t s") 'markdown-insert-header-setext-2)
5492 (define-key map (kbd "C-c C-t t") 'markdown-insert-header-setext-1)
5493 (define-key map (kbd "C-c C-i") 'markdown-insert-image)
5494 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item) ;; C-c C-j
5495 (define-key map (kbd "C-c C-x C-x") 'markdown-toggle-gfm-checkbox) ;; C-c C-d
5496 (define-key map (kbd "C-c -") 'markdown-insert-hr)
5497 map)
5498 "Keymap for Markdown major mode.")
5500 (defvar markdown-mode-mouse-map
5501 (when markdown-mouse-follow-link
5502 (let ((map (make-sparse-keymap)))
5503 (define-key map [follow-link] 'mouse-face)
5504 (define-key map [mouse-2] #'markdown-follow-thing-at-point)
5505 map))
5506 "Keymap for following links with mouse.")
5508 (defvar gfm-mode-map
5509 (let ((map (make-sparse-keymap)))
5510 (set-keymap-parent map markdown-mode-map)
5511 (define-key map (kbd "C-c C-s d") 'markdown-insert-strike-through)
5512 (define-key map "`" 'markdown-electric-backquote)
5513 map)
5514 "Keymap for `gfm-mode'.
5515 See also `markdown-mode-map'.")
5518 ;;; Menu ======================================================================
5520 (easy-menu-define markdown-mode-menu markdown-mode-map
5521 "Menu for Markdown mode."
5522 '("Markdown"
5523 "---"
5524 ("Movement"
5525 ["Jump" markdown-do]
5526 ["Follow Link" markdown-follow-thing-at-point]
5527 ["Next Link" markdown-next-link]
5528 ["Previous Link" markdown-previous-link]
5529 "---"
5530 ["Next Heading or List Item" markdown-outline-next]
5531 ["Previous Heading or List Item" markdown-outline-previous]
5532 ["Next at Same Level" markdown-outline-next-same-level]
5533 ["Previous at Same Level" markdown-outline-previous-same-level]
5534 ["Up to Parent" markdown-outline-up]
5535 "---"
5536 ["Forward Paragraph" markdown-forward-paragraph]
5537 ["Backward Paragraph" markdown-backward-paragraph]
5538 ["Forward Block" markdown-forward-block]
5539 ["Backward Block" markdown-backward-block])
5540 ("Show & Hide"
5541 ["Cycle Heading Visibility" markdown-cycle
5542 :enable (markdown-on-heading-p)]
5543 ["Cycle Heading Visibility (Global)" markdown-shifttab]
5544 "---"
5545 ["Narrow to Region" narrow-to-region]
5546 ["Narrow to Block" markdown-narrow-to-block]
5547 ["Narrow to Section" narrow-to-defun]
5548 ["Narrow to Subtree" markdown-narrow-to-subtree]
5549 ["Widen" widen (buffer-narrowed-p)]
5550 "---"
5551 ["Toggle Markup Hiding" markdown-toggle-markup-hiding
5552 :keys "C-c C-x C-m"
5553 :style radio
5554 :selected markdown-hide-markup])
5555 "---"
5556 ("Headings & Structure"
5557 ["Automatic Heading" markdown-insert-header-dwim
5558 :keys "C-c C-s h"]
5559 ["Automatic Heading (Setext)" markdown-insert-header-setext-dwim
5560 :keys "C-c C-s H"]
5561 ("Specific Heading (atx)"
5562 ["First Level atx" markdown-insert-header-atx-1
5563 :keys "C-c C-s 1"]
5564 ["Second Level atx" markdown-insert-header-atx-2
5565 :keys "C-c C-s 2"]
5566 ["Third Level atx" markdown-insert-header-atx-3
5567 :keys "C-c C-s 3"]
5568 ["Fourth Level atx" markdown-insert-header-atx-4
5569 :keys "C-c C-s 4"]
5570 ["Fifth Level atx" markdown-insert-header-atx-5
5571 :keys "C-c C-s 5"]
5572 ["Sixth Level atx" markdown-insert-header-atx-6
5573 :keys "C-c C-s 6"])
5574 ("Specific Heading (Setext)"
5575 ["First Level Setext" markdown-insert-header-setext-1
5576 :keys "C-c C-s !"]
5577 ["Second Level Setext" markdown-insert-header-setext-2
5578 :keys "C-c C-s @"])
5579 ["Horizontal Rule" markdown-insert-hr
5580 :keys "C-c C-s -"]
5581 "---"
5582 ["Move Subtree Up" markdown-move-up
5583 :keys "C-c <up>"]
5584 ["Move Subtree Down" markdown-move-down
5585 :keys "C-c <down>"]
5586 ["Promote Subtree" markdown-promote
5587 :keys "C-c <left>"]
5588 ["Demote Subtree" markdown-demote
5589 :keys "C-c <right>"])
5590 ("Region & Mark"
5591 ["Indent Region" markdown-indent-region]
5592 ["Outdent Region" markdown-outdent-region]
5593 "--"
5594 ["Mark Paragraph" mark-paragraph]
5595 ["Mark Block" markdown-mark-block]
5596 ["Mark Section" mark-defun]
5597 ["Mark Subtree" markdown-mark-subtree])
5598 ("Tables"
5599 ["Move Row Up" markdown-move-up
5600 :enable (markdown-table-at-point-p)
5601 :keys "C-c <up>"]
5602 ["Move Row Down" markdown-move-down
5603 :enable (markdown-table-at-point-p)
5604 :keys "C-c <down>"]
5605 ["Move Column Left" markdown-promote
5606 :enable (markdown-table-at-point-p)
5607 :keys "C-c <left>"]
5608 ["Move Column Right" markdown-demote
5609 :enable (markdown-table-at-point-p)
5610 :keys "C-c <right>"]
5611 ["Delete Row" markdown-table-delete-row
5612 :enable (markdown-table-at-point-p)]
5613 ["Insert Row" markdown-table-insert-row
5614 :enable (markdown-table-at-point-p)]
5615 ["Delete Column" markdown-table-delete-column
5616 :enable (markdown-table-at-point-p)]
5617 ["Insert Column" markdown-table-insert-column
5618 :enable (markdown-table-at-point-p)]
5619 ["Insert Table" markdown-insert-table]
5620 "--"
5621 ["Convert Region to Table" markdown-table-convert-region]
5622 ["Sort Table Lines" markdown-table-sort-lines
5623 :enable (markdown-table-at-point-p)]
5624 ["Transpose Table" markdown-table-transpose
5625 :enable (markdown-table-at-point-p)])
5626 ("Lists"
5627 ["Insert List Item" markdown-insert-list-item]
5628 ["Move Subtree Up" markdown-move-up
5629 :keys "C-c <up>"]
5630 ["Move Subtree Down" markdown-move-down
5631 :keys "C-c <down>"]
5632 ["Indent Subtree" markdown-demote
5633 :keys "C-c <right>"]
5634 ["Outdent Subtree" markdown-promote
5635 :keys "C-c <left>"]
5636 ["Renumber List" markdown-cleanup-list-numbers]
5637 ["Insert Task List Item" markdown-insert-gfm-checkbox
5638 :keys "C-c C-x ["]
5639 ["Toggle Task List Item" markdown-toggle-gfm-checkbox
5640 :enable (markdown-gfm-task-list-item-at-point)
5641 :keys "C-c C-d"])
5642 ("Links & Images"
5643 ["Insert Link" markdown-insert-link]
5644 ["Insert Image" markdown-insert-image]
5645 ["Insert Footnote" markdown-insert-footnote
5646 :keys "C-c C-s f"]
5647 ["Insert Wiki Link" markdown-insert-wiki-link
5648 :keys "C-c C-s w"]
5649 "---"
5650 ["Check References" markdown-check-refs]
5651 ["Find Unused References" markdown-unused-refs]
5652 ["Toggle URL Hiding" markdown-toggle-url-hiding
5653 :style radio
5654 :selected markdown-hide-urls]
5655 ["Toggle Inline Images" markdown-toggle-inline-images
5656 :keys "C-c C-x C-i"
5657 :style radio
5658 :selected markdown-inline-image-overlays]
5659 ["Toggle Wiki Links" markdown-toggle-wiki-links
5660 :style radio
5661 :selected markdown-enable-wiki-links])
5662 ("Styles"
5663 ["Bold" markdown-insert-bold]
5664 ["Italic" markdown-insert-italic]
5665 ["Code" markdown-insert-code]
5666 ["Strikethrough" markdown-insert-strike-through]
5667 ["Keyboard" markdown-insert-kbd]
5668 "---"
5669 ["Blockquote" markdown-insert-blockquote]
5670 ["Preformatted" markdown-insert-pre]
5671 ["GFM Code Block" markdown-insert-gfm-code-block]
5672 ["Edit Code Block" markdown-edit-code-block
5673 :enable (markdown-code-block-at-point-p)]
5674 ["Foldable Block" markdown-insert-foldable-block]
5675 "---"
5676 ["Blockquote Region" markdown-blockquote-region]
5677 ["Preformatted Region" markdown-pre-region]
5678 "---"
5679 ["Fontify Code Blocks Natively"
5680 markdown-toggle-fontify-code-blocks-natively
5681 :style radio
5682 :selected markdown-fontify-code-blocks-natively]
5683 ["LaTeX Math Support" markdown-toggle-math
5684 :style radio
5685 :selected markdown-enable-math])
5686 "---"
5687 ("Preview & Export"
5688 ["Compile" markdown-other-window]
5689 ["Preview" markdown-preview]
5690 ["Export" markdown-export]
5691 ["Export & View" markdown-export-and-preview]
5692 ["Open" markdown-open]
5693 ["Live Export" markdown-live-preview-mode
5694 :style radio
5695 :selected markdown-live-preview-mode]
5696 ["Kill ring save" markdown-kill-ring-save])
5697 ("Markup Completion and Cycling"
5698 ["Complete Markup" markdown-complete]
5699 ["Promote Element" markdown-promote
5700 :keys "C-c C--"]
5701 ["Demote Element" markdown-demote
5702 :keys "C-c C-="])
5703 "---"
5704 ["Kill Element" markdown-kill-thing-at-point]
5705 "---"
5706 ("Documentation"
5707 ["Version" markdown-show-version]
5708 ["Homepage" markdown-mode-info]
5709 ["Describe Mode" (describe-function 'markdown-mode)]
5710 ["Guide" (browse-url "https://leanpub.com/markdown-mode")])))
5713 ;;; imenu =====================================================================
5715 (defun markdown-imenu-create-nested-index ()
5716 "Create and return a nested imenu index alist for the current buffer.
5717 See `imenu-create-index-function' and `imenu--index-alist' for details."
5718 (let* ((root '(nil . nil))
5719 (min-level 9999)
5720 hashes headers)
5721 (save-excursion
5722 ;; Headings
5723 (goto-char (point-min))
5724 (while (re-search-forward markdown-regex-header (point-max) t)
5725 (unless (or (markdown-code-block-at-point-p)
5726 (and (match-beginning 3)
5727 (get-text-property (match-beginning 3) 'markdown-yaml-metadata-end)))
5728 (cond
5729 ((match-string-no-properties 2) ;; level 1 setext
5730 (setq min-level 1)
5731 (push (list :heading (match-string-no-properties 1)
5732 :point (match-beginning 1)
5733 :level 1) headers))
5734 ((match-string-no-properties 3) ;; level 2 setext
5735 (setq min-level (min min-level 2))
5736 (push (list :heading (match-string-no-properties 1)
5737 :point (match-beginning 1)
5738 :level (- 2 (1- min-level))) headers))
5739 ((setq hashes (markdown-trim-whitespace
5740 (match-string-no-properties 4)))
5741 (setq min-level (min min-level (length hashes)))
5742 (push (list :heading (match-string-no-properties 5)
5743 :point (match-beginning 4)
5744 :level (- (length hashes) (1- min-level))) headers)))))
5745 (cl-loop with cur-level = 0
5746 with cur-alist = nil
5747 with empty-heading = "-"
5748 with self-heading = "."
5749 for header in (reverse headers)
5750 for level = (plist-get header :level)
5752 (let ((alist (list (cons (plist-get header :heading) (plist-get header :point)))))
5753 (cond
5754 ((= cur-level level) ; new sibling
5755 (setcdr cur-alist alist)
5756 (setq cur-alist alist))
5757 ((< cur-level level) ; first child
5758 (dotimes (_ (- level cur-level 1))
5759 (setq alist (list (cons empty-heading alist))))
5760 (if cur-alist
5761 (let* ((parent (car cur-alist))
5762 (self-pos (cdr parent)))
5763 (setcdr parent (cons (cons self-heading self-pos) alist)))
5764 (setcdr root alist)) ; primogenitor
5765 (setq cur-alist alist)
5766 (setq cur-level level))
5767 (t ; new sibling of an ancestor
5768 (let ((sibling-alist (last (cdr root))))
5769 (dotimes (_ (1- level))
5770 (setq sibling-alist (last (cdar sibling-alist))))
5771 (setcdr sibling-alist alist)
5772 (setq cur-alist alist))
5773 (setq cur-level level)))))
5774 (setq root (copy-tree root))
5775 ;; Footnotes
5776 (let ((fn (markdown-get-defined-footnotes)))
5777 (if (or (zerop (length fn))
5778 (null markdown-add-footnotes-to-imenu))
5779 (cdr root)
5780 (nconc (cdr root) (list (cons "Footnotes" fn))))))))
5782 (defun markdown-imenu-create-flat-index ()
5783 "Create and return a flat imenu index alist for the current buffer.
5784 See `imenu-create-index-function' and `imenu--index-alist' for details."
5785 (let* ((empty-heading "-") index heading pos)
5786 (save-excursion
5787 ;; Headings
5788 (goto-char (point-min))
5789 (while (re-search-forward markdown-regex-header (point-max) t)
5790 (when (and (not (markdown-code-block-at-point-p (line-beginning-position)))
5791 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin)))
5792 (cond
5793 ((setq heading (match-string-no-properties 1))
5794 (setq pos (match-beginning 1)))
5795 ((setq heading (match-string-no-properties 5))
5796 (setq pos (match-beginning 4))))
5797 (or (> (length heading) 0)
5798 (setq heading empty-heading))
5799 (setq index (append index (list (cons heading pos))))))
5800 ;; Footnotes
5801 (when markdown-add-footnotes-to-imenu
5802 (nconc index (markdown-get-defined-footnotes)))
5803 index)))
5806 ;;; References ================================================================
5808 (defun markdown-reference-goto-definition ()
5809 "Jump to the definition of the reference at point or create it."
5810 (interactive)
5811 (when (thing-at-point-looking-at markdown-regex-link-reference)
5812 (let* ((text (match-string-no-properties 3))
5813 (reference (match-string-no-properties 6))
5814 (target (downcase (if (string= reference "") text reference)))
5815 (loc (cadr (save-match-data (markdown-reference-definition target)))))
5816 (if loc
5817 (goto-char loc)
5818 (goto-char (match-beginning 0))
5819 (markdown-insert-reference-definition target)))))
5821 (defun markdown-reference-find-links (reference)
5822 "Return a list of all links for REFERENCE.
5823 REFERENCE should not include the surrounding square brackets.
5824 Elements of the list have the form (text start line), where
5825 text is the link text, start is the location at the beginning of
5826 the link, and line is the line number on which the link appears."
5827 (let* ((ref-quote (regexp-quote reference))
5828 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
5829 ref-quote ref-quote))
5830 links)
5831 (save-excursion
5832 (goto-char (point-min))
5833 (while (re-search-forward regexp nil t)
5834 (let* ((text (or (match-string-no-properties 1)
5835 (match-string-no-properties 2)))
5836 (start (match-beginning 0))
5837 (line (markdown-line-number-at-pos)))
5838 (cl-pushnew (list text start line) links :test #'equal))))
5839 links))
5841 (defmacro markdown-for-all-refs (f)
5842 `(let ((result))
5843 (save-excursion
5844 (goto-char (point-min))
5845 (while
5846 (re-search-forward markdown-regex-link-reference nil t)
5847 (let* ((text (match-string-no-properties 3))
5848 (reference (match-string-no-properties 6))
5849 (target (downcase (if (string= reference "") text reference))))
5850 (,f text target result))))
5851 (reverse result)))
5853 (defmacro markdown-collect-always (_ target result)
5854 `(cl-pushnew ,target ,result :test #'equal))
5856 (defmacro markdown-collect-undefined (text target result)
5857 `(unless (markdown-reference-definition target)
5858 (let ((entry (assoc ,target ,result)))
5859 (if (not entry)
5860 (cl-pushnew
5861 (cons ,target (list (cons ,text (markdown-line-number-at-pos))))
5862 ,result :test #'equal)
5863 (setcdr entry
5864 (append (cdr entry) (list (cons ,text (markdown-line-number-at-pos)))))))))
5866 (defun markdown-get-all-refs ()
5867 "Return a list of all Markdown references."
5868 (markdown-for-all-refs markdown-collect-always))
5870 (defun markdown-get-undefined-refs ()
5871 "Return a list of undefined Markdown references.
5872 Result is an alist of pairs (reference . occurrences), where
5873 occurrences is itself another alist of pairs (label . line-number).
5874 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
5875 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
5876 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
5877 (markdown-for-all-refs markdown-collect-undefined))
5879 (defun markdown-get-unused-refs ()
5880 (cl-sort
5881 (cl-set-difference
5882 (markdown-get-defined-references) (markdown-get-all-refs)
5883 :test (lambda (e1 e2) (equal (car e1) e2)))
5884 #'< :key #'cdr))
5886 (defmacro defun-markdown-buffer (name docstring)
5887 "Define a function to name and return a buffer.
5889 By convention, NAME must be a name of a string constant with
5890 %buffer% placeholder used to name the buffer, and will also be
5891 used as a name of the function defined.
5893 DOCSTRING will be used as the first part of the docstring."
5894 `(defun ,name (&optional buffer-name)
5895 ,(concat docstring "\n\nBUFFER-NAME is the name of the main buffer being visited.")
5896 (or buffer-name (setq buffer-name (buffer-name)))
5897 (let ((refbuf (get-buffer-create (replace-regexp-in-string
5898 "%buffer%" buffer-name
5899 ,name))))
5900 (with-current-buffer refbuf
5901 (when view-mode
5902 (View-exit-and-edit))
5903 (use-local-map button-buffer-map)
5904 (erase-buffer))
5905 refbuf)))
5907 (defconst markdown-reference-check-buffer
5908 "*Undefined references for %buffer%*"
5909 "Pattern for name of buffer for listing undefined references.
5910 The string %buffer% will be replaced by the corresponding
5911 `markdown-mode' buffer name.")
5913 (defun-markdown-buffer
5914 markdown-reference-check-buffer
5915 "Name and return buffer for reference checking.")
5917 (defconst markdown-unused-references-buffer
5918 "*Unused references for %buffer%*"
5919 "Pattern for name of buffer for listing unused references.
5920 The string %buffer% will be replaced by the corresponding
5921 `markdown-mode' buffer name.")
5923 (defun-markdown-buffer
5924 markdown-unused-references-buffer
5925 "Name and return buffer for unused reference checking.")
5927 (defconst markdown-reference-links-buffer
5928 "*Reference links for %buffer%*"
5929 "Pattern for name of buffer for listing references.
5930 The string %buffer% will be replaced by the corresponding buffer name.")
5932 (defun-markdown-buffer
5933 markdown-reference-links-buffer
5934 "Name, setup, and return a buffer for listing links.")
5936 ;; Add an empty Markdown reference definition to buffer
5937 ;; specified in the 'target-buffer property. The reference name is
5938 ;; the button's label.
5939 (define-button-type 'markdown-undefined-reference-button
5940 'help-echo "mouse-1, RET: create definition for undefined reference"
5941 'follow-link t
5942 'face 'bold
5943 'action (lambda (b)
5944 (let ((buffer (button-get b 'target-buffer))
5945 (line (button-get b 'target-line))
5946 (label (button-label b)))
5947 (switch-to-buffer-other-window buffer)
5948 (goto-char (point-min))
5949 (forward-line line)
5950 (markdown-insert-reference-definition label)
5951 (markdown-check-refs t))))
5953 ;; Jump to line in buffer specified by 'target-buffer property.
5954 ;; Line number is button's 'target-line property.
5955 (define-button-type 'markdown-goto-line-button
5956 'help-echo "mouse-1, RET: go to line"
5957 'follow-link t
5958 'face 'italic
5959 'action (lambda (b)
5960 (switch-to-buffer-other-window (button-get b 'target-buffer))
5961 ;; use call-interactively to silence compiler
5962 (let ((current-prefix-arg (button-get b 'target-line)))
5963 (call-interactively 'goto-line))))
5965 ;; Kill a line in buffer specified by 'target-buffer property.
5966 ;; Line number is button's 'target-line property.
5967 (define-button-type 'markdown-kill-line-button
5968 'help-echo "mouse-1, RET: kill line"
5969 'follow-link t
5970 'face 'italic
5971 'action (lambda (b)
5972 (switch-to-buffer-other-window (button-get b 'target-buffer))
5973 ;; use call-interactively to silence compiler
5974 (let ((current-prefix-arg (button-get b 'target-line)))
5975 (call-interactively 'goto-line))
5976 (kill-line 1)
5977 (markdown-unused-refs t)))
5979 ;; Jumps to a particular link at location given by 'target-char
5980 ;; property in buffer given by 'target-buffer property.
5981 (define-button-type 'markdown-location-button
5982 'help-echo "mouse-1, RET: jump to location of link"
5983 'follow-link t
5984 'face 'bold
5985 'action (lambda (b)
5986 (let ((target (button-get b 'target-buffer))
5987 (loc (button-get b 'target-char)))
5988 (kill-buffer-and-window)
5989 (switch-to-buffer target)
5990 (goto-char loc))))
5992 (defun markdown-insert-undefined-reference-button (reference oldbuf)
5993 "Insert a button for creating REFERENCE in buffer OLDBUF.
5994 REFERENCE should be a list of the form (reference . occurrences),
5995 as returned by `markdown-get-undefined-refs'."
5996 (let ((label (car reference)))
5997 ;; Create a reference button
5998 (insert-button label
5999 :type 'markdown-undefined-reference-button
6000 'target-buffer oldbuf
6001 'target-line (cdr (car (cdr reference))))
6002 (insert " (")
6003 (dolist (occurrence (cdr reference))
6004 (let ((line (cdr occurrence)))
6005 ;; Create a line number button
6006 (insert-button (number-to-string line)
6007 :type 'markdown-goto-line-button
6008 'target-buffer oldbuf
6009 'target-line line)
6010 (insert " ")))
6011 (delete-char -1)
6012 (insert ")")
6013 (newline)))
6015 (defun markdown-insert-unused-reference-button (reference oldbuf)
6016 "Insert a button for creating REFERENCE in buffer OLDBUF.
6017 REFERENCE must be a pair of (ref . line-number)."
6018 (let ((label (car reference))
6019 (line (cdr reference)))
6020 ;; Create a reference button
6021 (insert-button label
6022 :type 'markdown-goto-line-button
6023 'face 'bold
6024 'target-buffer oldbuf
6025 'target-line line)
6026 (insert (format " (%d) [" line))
6027 (insert-button "X"
6028 :type 'markdown-kill-line-button
6029 'face 'bold
6030 'target-buffer oldbuf
6031 'target-line line)
6032 (insert "]")
6033 (newline)))
6035 (defun markdown-insert-link-button (link oldbuf)
6036 "Insert a button for jumping to LINK in buffer OLDBUF.
6037 LINK should be a list of the form (text char line) containing
6038 the link text, location, and line number."
6039 (let ((label (cl-first link))
6040 (char (cl-second link))
6041 (line (cl-third link)))
6042 ;; Create a reference button
6043 (insert-button label
6044 :type 'markdown-location-button
6045 'target-buffer oldbuf
6046 'target-char char)
6047 (insert (format " (line %d)\n" line))))
6049 (defun markdown-reference-goto-link (&optional reference)
6050 "Jump to the location of the first use of REFERENCE."
6051 (interactive)
6052 (unless reference
6053 (if (thing-at-point-looking-at markdown-regex-reference-definition)
6054 (setq reference (match-string-no-properties 2))
6055 (user-error "No reference definition at point")))
6056 (let ((links (markdown-reference-find-links reference)))
6057 (cond ((= (length links) 1)
6058 (goto-char (cadr (car links))))
6059 ((> (length links) 1)
6060 (let ((oldbuf (current-buffer))
6061 (linkbuf (markdown-reference-links-buffer)))
6062 (with-current-buffer linkbuf
6063 (insert "Links using reference " reference ":\n\n")
6064 (dolist (link (reverse links))
6065 (markdown-insert-link-button link oldbuf)))
6066 (view-buffer-other-window linkbuf)
6067 (goto-char (point-min))
6068 (forward-line 2)))
6070 (error "No links for reference %s" reference)))))
6072 (defmacro defun-markdown-ref-checker
6073 (name docstring checker-function buffer-function none-message buffer-header insert-reference)
6074 "Define a function NAME acting on result of CHECKER-FUNCTION.
6076 DOCSTRING is used as a docstring for the defined function.
6078 BUFFER-FUNCTION should name and return an auxiliary buffer to put
6079 results in.
6081 NONE-MESSAGE is used when CHECKER-FUNCTION returns no results.
6083 BUFFER-HEADER is put into the auxiliary buffer first, followed by
6084 calling INSERT-REFERENCE for each element in the list returned by
6085 CHECKER-FUNCTION."
6086 `(defun ,name (&optional silent)
6087 ,(concat
6088 docstring
6089 "\n\nIf SILENT is non-nil, do not message anything when no
6090 such references found.")
6091 (interactive "P")
6092 (unless (derived-mode-p 'markdown-mode)
6093 (user-error "Not available in current mode"))
6094 (let ((oldbuf (current-buffer))
6095 (refs (,checker-function))
6096 (refbuf (,buffer-function)))
6097 (if (null refs)
6098 (progn
6099 (when (not silent)
6100 (message ,none-message))
6101 (kill-buffer refbuf))
6102 (with-current-buffer refbuf
6103 (insert ,buffer-header)
6104 (dolist (ref refs)
6105 (,insert-reference ref oldbuf))
6106 (view-buffer-other-window refbuf)
6107 (goto-char (point-min))
6108 (forward-line 2))))))
6110 (defun-markdown-ref-checker
6111 markdown-check-refs
6112 "Show all undefined Markdown references in current `markdown-mode' buffer.
6114 Links which have empty reference definitions are considered to be
6115 defined."
6116 markdown-get-undefined-refs
6117 markdown-reference-check-buffer
6118 "No undefined references found"
6119 "The following references are undefined:\n\n"
6120 markdown-insert-undefined-reference-button)
6123 (defun-markdown-ref-checker
6124 markdown-unused-refs
6125 "Show all unused Markdown references in current `markdown-mode' buffer."
6126 markdown-get-unused-refs
6127 markdown-unused-references-buffer
6128 "No unused references found"
6129 "The following references are unused:\n\n"
6130 markdown-insert-unused-reference-button)
6134 ;;; Lists =====================================================================
6136 (defun markdown-insert-list-item (&optional arg)
6137 "Insert a new list item.
6138 If the point is inside unordered list, insert a bullet mark. If
6139 the point is inside ordered list, insert the next number followed
6140 by a period. Use the previous list item to determine the amount
6141 of whitespace to place before and after list markers.
6143 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
6144 decrease the indentation by one level.
6146 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
6147 increase the indentation by one level."
6148 (interactive "p")
6149 (let (bounds cur-indent marker indent new-indent new-loc)
6150 (save-match-data
6151 ;; Look for a list item on current or previous non-blank line
6152 (save-excursion
6153 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
6154 (not (bobp))
6155 (markdown-cur-line-blank-p))
6156 (forward-line -1)))
6157 (when bounds
6158 (cond ((save-excursion
6159 (skip-chars-backward " \t")
6160 (looking-at-p markdown-regex-list))
6161 (beginning-of-line)
6162 (insert "\n")
6163 (forward-line -1))
6164 ((not (markdown-cur-line-blank-p))
6165 (newline)))
6166 (setq new-loc (point)))
6167 ;; Look ahead for a list item on next non-blank line
6168 (unless bounds
6169 (save-excursion
6170 (while (and (null bounds)
6171 (not (eobp))
6172 (markdown-cur-line-blank-p))
6173 (forward-line)
6174 (setq bounds (markdown-cur-list-item-bounds))))
6175 (when bounds
6176 (setq new-loc (point))
6177 (unless (markdown-cur-line-blank-p)
6178 (newline))))
6179 (if (not bounds)
6180 ;; When not in a list, start a new unordered one
6181 (progn
6182 (unless (markdown-cur-line-blank-p)
6183 (insert "\n"))
6184 (insert markdown-unordered-list-item-prefix))
6185 ;; Compute indentation and marker for new list item
6186 (setq cur-indent (nth 2 bounds))
6187 (setq marker (nth 4 bounds))
6188 ;; If current item is a GFM checkbox, insert new unchecked checkbox.
6189 (when (nth 5 bounds)
6190 (setq marker
6191 (concat marker
6192 (replace-regexp-in-string "[Xx]" " " (nth 5 bounds)))))
6193 (cond
6194 ;; Dedent: decrement indentation, find previous marker.
6195 ((= arg 4)
6196 (setq indent (max (- cur-indent markdown-list-indent-width) 0))
6197 (let ((prev-bounds
6198 (save-excursion
6199 (goto-char (nth 0 bounds))
6200 (when (markdown-up-list)
6201 (markdown-cur-list-item-bounds)))))
6202 (when prev-bounds
6203 (setq marker (nth 4 prev-bounds)))))
6204 ;; Indent: increment indentation by 4, use same marker.
6205 ((= arg 16) (setq indent (+ cur-indent markdown-list-indent-width)))
6206 ;; Same level: keep current indentation and marker.
6207 (t (setq indent cur-indent)))
6208 (setq new-indent (make-string indent 32))
6209 (goto-char new-loc)
6210 (cond
6211 ;; Ordered list
6212 ((string-match-p "[0-9]" marker)
6213 (if (= arg 16) ;; starting a new column indented one more level
6214 (insert (concat new-indent "1. "))
6215 ;; Don't use previous match-data
6216 (set-match-data nil)
6217 ;; travel up to the last item and pick the correct number. If
6218 ;; the argument was nil, "new-indent = cur-indent" is the same,
6219 ;; so we don't need special treatment. Neat.
6220 (save-excursion
6221 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
6222 (>= (forward-line -1) 0))))
6223 (let* ((old-prefix (match-string 1))
6224 (old-spacing (match-string 2))
6225 (new-prefix (if (and old-prefix markdown-ordered-list-enumeration)
6226 (int-to-string (1+ (string-to-number old-prefix)))
6227 "1"))
6228 (space-adjust (- (length old-prefix) (length new-prefix)))
6229 (new-spacing (if (and (match-string 2)
6230 (not (string-match-p "\t" old-spacing))
6231 (< space-adjust 0)
6232 (> space-adjust (- 1 (length (match-string 2)))))
6233 (substring (match-string 2) 0 space-adjust)
6234 (or old-spacing ". "))))
6235 (insert (concat new-indent new-prefix new-spacing)))))
6236 ;; Unordered list, GFM task list, or ordered list with hash mark
6237 ((string-match-p "[\\*\\+-]\\|#\\." marker)
6238 (insert new-indent marker))))
6239 ;; Propertize the newly inserted list item now
6240 (markdown-syntax-propertize-list-items (line-beginning-position) (line-end-position)))))
6242 (defun markdown-move-list-item-up ()
6243 "Move the current list item up in the list when possible.
6244 In nested lists, move child items with the parent item."
6245 (interactive)
6246 (let (cur prev old)
6247 (when (setq cur (markdown-cur-list-item-bounds))
6248 (setq old (point))
6249 (goto-char (nth 0 cur))
6250 (if (markdown-prev-list-item (nth 3 cur))
6251 (progn
6252 (setq prev (markdown-cur-list-item-bounds))
6253 (condition-case nil
6254 (progn
6255 (transpose-regions (nth 0 prev) (nth 1 prev)
6256 (nth 0 cur) (nth 1 cur) t)
6257 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
6258 ;; Catch error in case regions overlap.
6259 (error (goto-char old))))
6260 (goto-char old)))))
6262 (defun markdown-move-list-item-down ()
6263 "Move the current list item down in the list when possible.
6264 In nested lists, move child items with the parent item."
6265 (interactive)
6266 (let (cur next old)
6267 (when (setq cur (markdown-cur-list-item-bounds))
6268 (setq old (point))
6269 (if (markdown-next-list-item (nth 3 cur))
6270 (progn
6271 (setq next (markdown-cur-list-item-bounds))
6272 (condition-case nil
6273 (progn
6274 (transpose-regions (nth 0 cur) (nth 1 cur)
6275 (nth 0 next) (nth 1 next) nil)
6276 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
6277 ;; Catch error in case regions overlap.
6278 (error (goto-char old))))
6279 (goto-char old)))))
6281 (defun markdown-demote-list-item (&optional bounds)
6282 "Indent (or demote) the current list item.
6283 Optionally, BOUNDS of the current list item may be provided if available.
6284 In nested lists, demote child items as well."
6285 (interactive)
6286 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6287 (save-excursion
6288 (let* ((item-start (set-marker (make-marker) (nth 0 bounds)))
6289 (item-end (set-marker (make-marker) (nth 1 bounds)))
6290 (list-start (progn (markdown-beginning-of-list)
6291 (set-marker (make-marker) (point))))
6292 (list-end (progn (markdown-end-of-list)
6293 (set-marker (make-marker) (point)))))
6294 (goto-char item-start)
6295 (while (< (point) item-end)
6296 (unless (markdown-cur-line-blank-p)
6297 (insert (make-string markdown-list-indent-width ? )))
6298 (forward-line))
6299 (markdown-syntax-propertize-list-items list-start list-end)))))
6301 (defun markdown-promote-list-item (&optional bounds)
6302 "Unindent (or promote) the current list item.
6303 Optionally, BOUNDS of the current list item may be provided if available.
6304 In nested lists, demote child items as well."
6305 (interactive)
6306 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6307 (save-excursion
6308 (save-match-data
6309 (let ((item-start (set-marker (make-marker) (nth 0 bounds)))
6310 (item-end (set-marker (make-marker) (nth 1 bounds)))
6311 (list-start (progn (markdown-beginning-of-list)
6312 (set-marker (make-marker) (point))))
6313 (list-end (progn (markdown-end-of-list)
6314 (set-marker (make-marker) (point))))
6315 num regexp)
6316 (goto-char item-start)
6317 (when (looking-at (format "^[ ]\\{1,%d\\}"
6318 markdown-list-indent-width))
6319 (setq num (- (match-end 0) (match-beginning 0)))
6320 (setq regexp (format "^[ ]\\{1,%d\\}" num))
6321 (while (and (< (point) item-end)
6322 (re-search-forward regexp item-end t))
6323 (replace-match "" nil nil)
6324 (forward-line))
6325 (markdown-syntax-propertize-list-items list-start list-end)))))))
6327 (defun markdown-cleanup-list-numbers-level (&optional pfx prev-item)
6328 "Update the numbering for level PFX (as a string of spaces) and PREV-ITEM.
6329 PREV-ITEM is width of previous-indentation and list number
6331 Assume that the previously found match was for a numbered item in
6332 a list."
6333 (let ((cpfx pfx)
6334 (cur-item nil)
6335 (idx 0)
6336 (continue t)
6337 (step t)
6338 (sep nil))
6339 (while (and continue (not (eobp)))
6340 (setq step t)
6341 (cond
6342 ((looking-at "^\\(\\([\s-]*\\)[0-9]+\\)\\. ")
6343 (setq cpfx (match-string-no-properties 2))
6344 (setq cur-item (match-string-no-properties 1)) ;; indentation and list marker
6345 (cond
6346 ((or (= (length cpfx) (length pfx))
6347 (= (length cur-item) (length prev-item)))
6348 (save-excursion
6349 (replace-match
6350 (if (not markdown-ordered-list-enumeration)
6351 (concat pfx "1. ")
6352 (cl-incf idx)
6353 (concat pfx (number-to-string idx) ". "))))
6354 (setq sep nil))
6355 ;; indented a level
6356 ((< (length pfx) (length cpfx))
6357 (setq sep (markdown-cleanup-list-numbers-level cpfx cur-item))
6358 (setq step nil))
6359 ;; exit the loop
6361 (setq step nil)
6362 (setq continue nil))))
6364 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
6365 (setq cpfx (match-string-no-properties 1))
6366 (cond
6367 ;; reset if separated before
6368 ((string= cpfx pfx) (when sep (setq idx 0)))
6369 ((string< cpfx pfx)
6370 (setq step nil)
6371 (setq continue nil))))
6372 (t (setq sep t)))
6374 (when step
6375 (beginning-of-line)
6376 (setq continue (= (forward-line) 0))))
6377 sep))
6379 (defun markdown-cleanup-list-numbers ()
6380 "Update the numbering of ordered lists."
6381 (interactive)
6382 (save-excursion
6383 (goto-char (point-min))
6384 (markdown-cleanup-list-numbers-level "")))
6387 ;;; Movement ==================================================================
6389 (defun markdown-beginning-of-defun (&optional arg)
6390 "`beginning-of-defun-function' for Markdown.
6391 This is used to find the beginning of the defun and should behave
6392 like ‘beginning-of-defun’, returning non-nil if it found the
6393 beginning of a defun. It moves the point backward, right before a
6394 heading which defines a defun. When ARG is non-nil, repeat that
6395 many times. When ARG is negative, move forward to the ARG-th
6396 following section."
6397 (or arg (setq arg 1))
6398 (when (< arg 0) (end-of-line))
6399 ;; Adjust position for setext headings.
6400 (when (and (thing-at-point-looking-at markdown-regex-header-setext)
6401 (not (= (point) (match-beginning 0)))
6402 (not (markdown-code-block-at-point-p)))
6403 (goto-char (match-end 0)))
6404 (let (found)
6405 ;; Move backward with positive argument.
6406 (while (and (not (bobp)) (> arg 0))
6407 (setq found nil)
6408 (while (and (not found)
6409 (not (bobp))
6410 (re-search-backward markdown-regex-header nil 'move))
6411 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6412 (setq found (match-beginning 0)))
6413 (setq arg (1- arg)))
6414 ;; Move forward with negative argument.
6415 (while (and (not (eobp)) (< arg 0))
6416 (setq found nil)
6417 (while (and (not found)
6418 (not (eobp))
6419 (re-search-forward markdown-regex-header nil 'move))
6420 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6421 (setq found (match-beginning 0)))
6422 (setq arg (1+ arg)))
6423 (when found
6424 (beginning-of-line)
6425 t)))
6427 (defun markdown-end-of-defun ()
6428 "`end-of-defun-function’ for Markdown.
6429 This is used to find the end of the defun at point.
6430 It is called with no argument, right after calling ‘beginning-of-defun-raw’,
6431 so it can assume that point is at the beginning of the defun body.
6432 It should move point to the first position after the defun."
6433 (or (eobp) (forward-char 1))
6434 (let (found)
6435 (while (and (not found)
6436 (not (eobp))
6437 (re-search-forward markdown-regex-header nil 'move))
6438 (when (not (markdown-code-block-at-pos (match-beginning 0)))
6439 (setq found (match-beginning 0))))
6440 (when found
6441 (goto-char found)
6442 (skip-syntax-backward "-"))))
6444 (defun markdown-beginning-of-text-block ()
6445 "Move backward to previous beginning of a plain text block.
6446 This function simply looks for blank lines without considering
6447 the surrounding context in light of Markdown syntax. For that, see
6448 `markdown-backward-block'."
6449 (interactive)
6450 (let ((start (point)))
6451 (if (re-search-backward markdown-regex-block-separator nil t)
6452 (goto-char (match-end 0))
6453 (goto-char (point-min)))
6454 (when (and (= start (point)) (not (bobp)))
6455 (forward-line -1)
6456 (if (re-search-backward markdown-regex-block-separator nil t)
6457 (goto-char (match-end 0))
6458 (goto-char (point-min))))))
6460 (defun markdown-end-of-text-block ()
6461 "Move forward to next beginning of a plain text block.
6462 This function simply looks for blank lines without considering
6463 the surrounding context in light of Markdown syntax. For that, see
6464 `markdown-forward-block'."
6465 (interactive)
6466 (beginning-of-line)
6467 (skip-chars-forward " \t\n")
6468 (when (= (point) (point-min))
6469 (forward-char))
6470 (if (re-search-forward markdown-regex-block-separator nil t)
6471 (goto-char (match-end 0))
6472 (goto-char (point-max)))
6473 (skip-chars-backward " \t\n")
6474 (forward-line))
6476 (defun markdown-backward-paragraph (&optional arg)
6477 "Move the point to the start of the current paragraph.
6478 With argument ARG, do it ARG times; a negative argument ARG = -N
6479 means move forward N blocks."
6480 (interactive "^p")
6481 (or arg (setq arg 1))
6482 (if (< arg 0)
6483 (markdown-forward-paragraph (- arg))
6484 (dotimes (_ arg)
6485 ;; Skip over whitespace in between paragraphs when moving backward.
6486 (skip-chars-backward " \t\n")
6487 (beginning-of-line)
6488 ;; Skip over code block endings.
6489 (when (markdown-range-properties-exist
6490 (line-beginning-position) (line-end-position)
6491 '(markdown-gfm-block-end
6492 markdown-tilde-fence-end))
6493 (forward-line -1))
6494 ;; Skip over blank lines inside blockquotes.
6495 (while (and (not (eobp))
6496 (looking-at markdown-regex-blockquote)
6497 (= (length (match-string 3)) 0))
6498 (forward-line -1))
6499 ;; Proceed forward based on the type of block of paragraph.
6500 (let (bounds skip)
6501 (cond
6502 ;; Blockquotes
6503 ((looking-at markdown-regex-blockquote)
6504 (while (and (not (bobp))
6505 (looking-at markdown-regex-blockquote)
6506 (> (length (match-string 3)) 0)) ;; not blank
6507 (forward-line -1))
6508 (forward-line))
6509 ;; List items
6510 ((setq bounds (markdown-cur-list-item-bounds))
6511 (goto-char (nth 0 bounds)))
6512 ;; Other
6514 (while (and (not (bobp))
6515 (not skip)
6516 (not (markdown-cur-line-blank-p))
6517 (not (looking-at markdown-regex-blockquote))
6518 (not (markdown-range-properties-exist
6519 (line-beginning-position) (line-end-position)
6520 '(markdown-gfm-block-end
6521 markdown-tilde-fence-end))))
6522 (setq skip (markdown-range-properties-exist
6523 (line-beginning-position) (line-end-position)
6524 '(markdown-gfm-block-begin
6525 markdown-tilde-fence-begin)))
6526 (forward-line -1))
6527 (unless (bobp)
6528 (forward-line 1))))))))
6530 (defun markdown-forward-paragraph (&optional arg)
6531 "Move forward to the next end of a paragraph.
6532 With argument ARG, do it ARG times; a negative argument ARG = -N
6533 means move backward N blocks."
6534 (interactive "^p")
6535 (or arg (setq arg 1))
6536 (if (< arg 0)
6537 (markdown-backward-paragraph (- arg))
6538 (dotimes (_ arg)
6539 ;; Skip whitespace in between paragraphs.
6540 (when (markdown-cur-line-blank-p)
6541 (skip-syntax-forward "-")
6542 (beginning-of-line))
6543 ;; Proceed forward based on the type of block.
6544 (let (bounds skip)
6545 (cond
6546 ;; Blockquotes
6547 ((looking-at markdown-regex-blockquote)
6548 ;; Skip over blank lines inside blockquotes.
6549 (while (and (not (eobp))
6550 (looking-at markdown-regex-blockquote)
6551 (= (length (match-string 3)) 0))
6552 (forward-line))
6553 ;; Move to end of quoted text block
6554 (while (and (not (eobp))
6555 (looking-at markdown-regex-blockquote)
6556 (> (length (match-string 3)) 0)) ;; not blank
6557 (forward-line)))
6558 ;; List items
6559 ((and (markdown-cur-list-item-bounds)
6560 (setq bounds (markdown-next-list-item-bounds)))
6561 (goto-char (nth 0 bounds)))
6562 ;; Other
6564 (forward-line)
6565 (while (and (not (eobp))
6566 (not skip)
6567 (not (markdown-cur-line-blank-p))
6568 (not (looking-at markdown-regex-blockquote))
6569 (not (markdown-range-properties-exist
6570 (line-beginning-position) (line-end-position)
6571 '(markdown-gfm-block-begin
6572 markdown-tilde-fence-begin))))
6573 (setq skip (markdown-range-properties-exist
6574 (line-beginning-position) (line-end-position)
6575 '(markdown-gfm-block-end
6576 markdown-tilde-fence-end)))
6577 (forward-line))))))))
6579 (defun markdown-backward-block (&optional arg)
6580 "Move the point to the start of the current Markdown block.
6581 Moves across complete code blocks, list items, and blockquotes,
6582 but otherwise stops at blank lines, headers, and horizontal
6583 rules. With argument ARG, do it ARG times; a negative argument
6584 ARG = -N means move forward N blocks."
6585 (interactive "^p")
6586 (or arg (setq arg 1))
6587 (if (< arg 0)
6588 (markdown-forward-block (- arg))
6589 (dotimes (_ arg)
6590 ;; Skip over whitespace in between blocks when moving backward,
6591 ;; unless at a block boundary with no whitespace.
6592 (skip-syntax-backward "-")
6593 (beginning-of-line)
6594 ;; Proceed forward based on the type of block.
6595 (cond
6596 ;; Code blocks
6597 ((and (markdown-code-block-at-pos (point)) ;; this line
6598 (markdown-code-block-at-pos (line-beginning-position 0))) ;; previous line
6599 (forward-line -1)
6600 (while (and (markdown-code-block-at-point-p) (not (bobp)))
6601 (forward-line -1))
6602 (forward-line))
6603 ;; Headings
6604 ((markdown-heading-at-point)
6605 (goto-char (match-beginning 0)))
6606 ;; Horizontal rules
6607 ((looking-at markdown-regex-hr))
6608 ;; Blockquotes
6609 ((looking-at markdown-regex-blockquote)
6610 (forward-line -1)
6611 (while (and (looking-at markdown-regex-blockquote)
6612 (not (bobp)))
6613 (forward-line -1))
6614 (forward-line))
6615 ;; List items
6616 ((markdown-cur-list-item-bounds)
6617 (markdown-beginning-of-list))
6618 ;; Other
6620 ;; Move forward in case it is a one line regular paragraph.
6621 (unless (markdown-next-line-blank-p)
6622 (forward-line))
6623 (unless (markdown-prev-line-blank-p)
6624 (markdown-backward-paragraph)))))))
6626 (defun markdown-forward-block (&optional arg)
6627 "Move forward to the next end of a Markdown block.
6628 Moves across complete code blocks, list items, and blockquotes,
6629 but otherwise stops at blank lines, headers, and horizontal
6630 rules. With argument ARG, do it ARG times; a negative argument
6631 ARG = -N means move backward N blocks."
6632 (interactive "^p")
6633 (or arg (setq arg 1))
6634 (if (< arg 0)
6635 (markdown-backward-block (- arg))
6636 (dotimes (_ arg)
6637 ;; Skip over whitespace in between blocks when moving forward.
6638 (if (markdown-cur-line-blank-p)
6639 (skip-syntax-forward "-")
6640 (beginning-of-line))
6641 ;; Proceed forward based on the type of block.
6642 (cond
6643 ;; Code blocks
6644 ((markdown-code-block-at-point-p)
6645 (forward-line)
6646 (while (and (markdown-code-block-at-point-p) (not (eobp)))
6647 (forward-line)))
6648 ;; Headings
6649 ((looking-at markdown-regex-header)
6650 (goto-char (or (match-end 4) (match-end 2) (match-end 3)))
6651 (forward-line))
6652 ;; Horizontal rules
6653 ((looking-at markdown-regex-hr)
6654 (forward-line))
6655 ;; Blockquotes
6656 ((looking-at markdown-regex-blockquote)
6657 (forward-line)
6658 (while (and (looking-at markdown-regex-blockquote) (not (eobp)))
6659 (forward-line)))
6660 ;; List items
6661 ((markdown-cur-list-item-bounds)
6662 (markdown-end-of-list)
6663 (forward-line))
6664 ;; Other
6665 (t (markdown-forward-paragraph))))
6666 (skip-syntax-backward "-")
6667 (unless (eobp)
6668 (forward-char 1))))
6670 (defun markdown-backward-page (&optional count)
6671 "Move backward to boundary of the current toplevel section.
6672 With COUNT, repeat, or go forward if negative."
6673 (interactive "p")
6674 (or count (setq count 1))
6675 (if (< count 0)
6676 (markdown-forward-page (- count))
6677 (skip-syntax-backward "-")
6678 (or (markdown-back-to-heading-over-code-block t t)
6679 (goto-char (point-min)))
6680 (when (looking-at markdown-regex-header)
6681 (let ((level (markdown-outline-level)))
6682 (when (> level 1) (markdown-up-heading level))
6683 (when (> count 1)
6684 (condition-case nil
6685 (markdown-backward-same-level (1- count))
6686 (error (goto-char (point-min)))))))))
6688 (defun markdown-forward-page (&optional count)
6689 "Move forward to boundary of the current toplevel section.
6690 With COUNT, repeat, or go backward if negative."
6691 (interactive "p")
6692 (or count (setq count 1))
6693 (if (< count 0)
6694 (markdown-backward-page (- count))
6695 (if (markdown-back-to-heading-over-code-block t t)
6696 (let ((level (markdown-outline-level)))
6697 (when (> level 1) (markdown-up-heading level))
6698 (condition-case nil
6699 (markdown-forward-same-level count)
6700 (error (goto-char (point-max)))))
6701 (markdown-next-visible-heading 1))))
6703 (defun markdown-next-link ()
6704 "Jump to next inline, reference, or wiki link.
6705 If successful, return point. Otherwise, return nil.
6706 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
6707 (interactive)
6708 (let ((opoint (point)))
6709 (when (or (markdown-link-p) (markdown-wiki-link-p))
6710 ;; At a link already, move past it.
6711 (goto-char (+ (match-end 0) 1)))
6712 ;; Search for the next wiki link and move to the beginning.
6713 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t)
6714 (markdown-code-block-at-point-p)
6715 (< (point) (point-max))))
6716 (if (and (not (eq (point) opoint))
6717 (or (markdown-link-p) (markdown-wiki-link-p)))
6718 ;; Group 1 will move past non-escape character in wiki link regexp.
6719 ;; Go to beginning of group zero for all other link types.
6720 (goto-char (or (match-beginning 1) (match-beginning 0)))
6721 (goto-char opoint)
6722 nil)))
6724 (defun markdown-previous-link ()
6725 "Jump to previous wiki link.
6726 If successful, return point. Otherwise, return nil.
6727 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
6728 (interactive)
6729 (let ((opoint (point)))
6730 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t)
6731 (markdown-code-block-at-point-p)
6732 (> (point) (point-min))))
6733 (if (and (not (eq (point) opoint))
6734 (or (markdown-link-p) (markdown-wiki-link-p)))
6735 (goto-char (or (match-beginning 1) (match-beginning 0)))
6736 (goto-char opoint)
6737 nil)))
6740 ;;; Outline ===================================================================
6742 (defun markdown-move-heading-common (move-fn &optional arg adjust)
6743 "Wrapper for `outline-mode' functions to skip false positives.
6744 MOVE-FN is a function and ARG is its argument. For example,
6745 headings inside preformatted code blocks may match
6746 `outline-regexp' but should not be considered as headings.
6747 When ADJUST is non-nil, adjust the point for interactive calls
6748 to avoid leaving the point at invisible markup. This adjustment
6749 generally should only be done for interactive calls, since other
6750 functions may expect the point to be at the beginning of the
6751 regular expression."
6752 (let ((prev -1) (start (point)))
6753 (if arg (funcall move-fn arg) (funcall move-fn))
6754 (while (and (/= prev (point)) (markdown-code-block-at-point-p))
6755 (setq prev (point))
6756 (if arg (funcall move-fn arg) (funcall move-fn)))
6757 ;; Adjust point for setext headings and invisible text.
6758 (save-match-data
6759 (when (and adjust (thing-at-point-looking-at markdown-regex-header))
6760 (if markdown-hide-markup
6761 ;; Move to beginning of heading text if markup is hidden.
6762 (goto-char (or (match-beginning 1) (match-beginning 5)))
6763 ;; Move to beginning of markup otherwise.
6764 (goto-char (or (match-beginning 1) (match-beginning 4))))))
6765 (if (= (point) start) nil (point))))
6767 (defun markdown-next-visible-heading (arg)
6768 "Move to the next visible heading line of any level.
6769 With argument, repeats or can move backward if negative. ARG is
6770 passed to `outline-next-visible-heading'."
6771 (interactive "p")
6772 (markdown-move-heading-common #'outline-next-visible-heading arg 'adjust))
6774 (defun markdown-previous-visible-heading (arg)
6775 "Move to the previous visible heading line of any level.
6776 With argument, repeats or can move backward if negative. ARG is
6777 passed to `outline-previous-visible-heading'."
6778 (interactive "p")
6779 (markdown-move-heading-common #'outline-previous-visible-heading arg 'adjust))
6781 (defun markdown-next-heading ()
6782 "Move to the next heading line of any level."
6783 (markdown-move-heading-common #'outline-next-heading))
6785 (defun markdown-previous-heading ()
6786 "Move to the previous heading line of any level."
6787 (markdown-move-heading-common #'outline-previous-heading))
6789 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok no-error)
6790 "Move back to the beginning of the previous heading.
6791 Returns t if the point is at a heading, the location if a heading
6792 was found, and nil otherwise.
6793 Only visible heading lines are considered, unless INVISIBLE-OK is
6794 non-nil. Throw an error if there is no previous heading unless
6795 NO-ERROR is non-nil.
6796 Leaves match data intact for `markdown-regex-header'."
6797 (beginning-of-line)
6798 (or (and (markdown-heading-at-point)
6799 (not (markdown-code-block-at-point-p)))
6800 (let (found)
6801 (save-excursion
6802 (while (and (not found)
6803 (re-search-backward markdown-regex-header nil t))
6804 (when (and (or invisible-ok (not (outline-invisible-p)))
6805 (not (markdown-code-block-at-point-p)))
6806 (setq found (point))))
6807 (if (not found)
6808 (unless no-error (user-error "Before first heading"))
6809 (setq found (point))))
6810 (when found (goto-char found)))))
6812 (defun markdown-forward-same-level (arg)
6813 "Move forward to the ARG'th heading at same level as this one.
6814 Stop at the first and last headings of a superior heading."
6815 (interactive "p")
6816 (markdown-back-to-heading-over-code-block)
6817 (markdown-move-heading-common #'outline-forward-same-level arg 'adjust))
6819 (defun markdown-backward-same-level (arg)
6820 "Move backward to the ARG'th heading at same level as this one.
6821 Stop at the first and last headings of a superior heading."
6822 (interactive "p")
6823 (markdown-back-to-heading-over-code-block)
6824 (while (> arg 0)
6825 (let ((point-to-move-to
6826 (save-excursion
6827 (markdown-move-heading-common #'outline-get-last-sibling nil 'adjust))))
6828 (if point-to-move-to
6829 (progn
6830 (goto-char point-to-move-to)
6831 (setq arg (1- arg)))
6832 (user-error "No previous same-level heading")))))
6834 (defun markdown-up-heading (arg &optional interactive)
6835 "Move to the visible heading line of which the present line is a subheading.
6836 With argument, move up ARG levels. When called interactively (or
6837 INTERACTIVE is non-nil), also push the mark."
6838 (interactive "p\np")
6839 (and interactive (not (eq last-command 'markdown-up-heading))
6840 (push-mark))
6841 (markdown-move-heading-common #'outline-up-heading arg 'adjust))
6843 (defun markdown-back-to-heading (&optional invisible-ok)
6844 "Move to previous heading line, or beg of this line if it's a heading.
6845 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
6846 (interactive)
6847 (markdown-move-heading-common #'outline-back-to-heading invisible-ok))
6849 (defalias 'markdown-end-of-heading 'outline-end-of-heading)
6851 (defun markdown-on-heading-p ()
6852 "Return non-nil if point is on a heading line."
6853 (get-text-property (line-beginning-position) 'markdown-heading))
6855 (defun markdown-end-of-subtree (&optional invisible-OK)
6856 "Move to the end of the current subtree.
6857 Only visible heading lines are considered, unless INVISIBLE-OK is
6858 non-nil.
6859 Derived from `org-end-of-subtree'."
6860 (markdown-back-to-heading invisible-OK)
6861 (let ((first t)
6862 (level (markdown-outline-level)))
6863 (while (and (not (eobp))
6864 (or first (> (markdown-outline-level) level)))
6865 (setq first nil)
6866 (markdown-next-heading))
6867 (if (memq (preceding-char) '(?\n ?\^M))
6868 (progn
6869 ;; Go to end of line before heading
6870 (forward-char -1)
6871 (if (memq (preceding-char) '(?\n ?\^M))
6872 ;; leave blank line before heading
6873 (forward-char -1)))))
6874 (point))
6876 (defun markdown-outline-fix-visibility ()
6877 "Hide any false positive headings that should not be shown.
6878 For example, headings inside preformatted code blocks may match
6879 `outline-regexp' but should not be shown as headings when cycling.
6880 Also, the ending --- line in metadata blocks appears to be a
6881 setext header, but should not be folded."
6882 (save-excursion
6883 (goto-char (point-min))
6884 ;; Unhide any false positives in metadata blocks
6885 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin)
6886 (let ((body (progn (forward-line)
6887 (markdown-text-property-at-point
6888 'markdown-yaml-metadata-section))))
6889 (when body
6890 (let ((end (progn (goto-char (cl-second body))
6891 (markdown-text-property-at-point
6892 'markdown-yaml-metadata-end))))
6893 (outline-flag-region (point-min) (1+ (cl-second end)) nil)))))
6894 ;; Hide any false positives in code blocks
6895 (unless (outline-on-heading-p)
6896 (outline-next-visible-heading 1))
6897 (while (< (point) (point-max))
6898 (when (markdown-code-block-at-point-p)
6899 (outline-flag-region (1- (line-beginning-position)) (line-end-position) t))
6900 (outline-next-visible-heading 1))))
6902 (defvar markdown-cycle-global-status 1)
6903 (defvar markdown-cycle-subtree-status nil)
6905 (defun markdown-next-preface ()
6906 (let (finish)
6907 (while (and (not finish) (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
6908 nil 'move))
6909 (unless (markdown-code-block-at-point-p)
6910 (goto-char (match-beginning 0))
6911 (setq finish t))))
6912 (when (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
6913 (forward-char -1)))
6915 (defun markdown-show-entry ()
6916 (save-excursion
6917 (outline-back-to-heading t)
6918 (outline-flag-region (1- (point))
6919 (progn
6920 (markdown-next-preface)
6921 (if (= 1 (- (point-max) (point)))
6922 (point-max)
6923 (point)))
6924 nil)))
6926 ;; This function was originally derived from `org-cycle' from org.el.
6927 (defun markdown-cycle (&optional arg)
6928 "Visibility cycling for Markdown mode.
6929 This function is called with a `\\[universal-argument]' or if ARG is t, perform
6930 global visibility cycling. If the point is at an atx-style header, cycle
6931 visibility of the corresponding subtree. Otherwise, indent the current line
6932 or insert a tab, as appropriate, by calling `indent-for-tab-command'."
6933 (interactive "P")
6934 (cond
6936 ;; Global cycling
6937 (arg
6938 (cond
6939 ;; Move from overview to contents
6940 ((and (eq last-command this-command)
6941 (eq markdown-cycle-global-status 2))
6942 (outline-hide-sublevels 1)
6943 (message "CONTENTS")
6944 (setq markdown-cycle-global-status 3)
6945 (markdown-outline-fix-visibility))
6946 ;; Move from contents to all
6947 ((and (eq last-command this-command)
6948 (eq markdown-cycle-global-status 3))
6949 (outline-show-all)
6950 (message "SHOW ALL")
6951 (setq markdown-cycle-global-status 1))
6952 ;; Defaults to overview
6954 (outline-hide-body)
6955 (message "OVERVIEW")
6956 (setq markdown-cycle-global-status 2)
6957 (markdown-outline-fix-visibility))))
6959 ;; At a heading: rotate between three different views
6960 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
6961 (markdown-back-to-heading)
6962 (let ((goal-column 0) eoh eol eos)
6963 ;; Determine boundaries
6964 (save-excursion
6965 (markdown-back-to-heading)
6966 (save-excursion
6967 (beginning-of-line 2)
6968 (while (and (not (eobp)) ;; this is like `next-line'
6969 (get-char-property (1- (point)) 'invisible))
6970 (beginning-of-line 2)) (setq eol (point)))
6971 (markdown-end-of-heading) (setq eoh (point))
6972 (markdown-end-of-subtree t)
6973 (skip-chars-forward " \t\n")
6974 (beginning-of-line 1) ; in case this is an item
6975 (setq eos (1- (point))))
6976 ;; Find out what to do next and set `this-command'
6977 (cond
6978 ;; Nothing is hidden behind this heading
6979 ((= eos eoh)
6980 (message "EMPTY ENTRY")
6981 (setq markdown-cycle-subtree-status nil))
6982 ;; Entire subtree is hidden in one line: open it
6983 ((>= eol eos)
6984 (markdown-show-entry)
6985 (outline-show-children)
6986 (message "CHILDREN")
6987 (setq markdown-cycle-subtree-status 'children))
6988 ;; We just showed the children, now show everything.
6989 ((and (eq last-command this-command)
6990 (eq markdown-cycle-subtree-status 'children))
6991 (outline-show-subtree)
6992 (message "SUBTREE")
6993 (setq markdown-cycle-subtree-status 'subtree))
6994 ;; Default action: hide the subtree.
6996 (outline-hide-subtree)
6997 (message "FOLDED")
6998 (setq markdown-cycle-subtree-status 'folded)))))
7000 ;; In a table, move forward by one cell
7001 ((markdown-table-at-point-p)
7002 (call-interactively #'markdown-table-forward-cell))
7004 ;; Otherwise, indent as appropriate
7006 (indent-for-tab-command))))
7008 (defun markdown-shifttab ()
7009 "Handle S-TAB keybinding based on context.
7010 When in a table, move backward one cell.
7011 Otherwise, cycle global heading visibility by calling
7012 `markdown-cycle' with argument t."
7013 (interactive)
7014 (cond ((markdown-table-at-point-p)
7015 (call-interactively #'markdown-table-backward-cell))
7016 (t (markdown-cycle t))))
7018 (defun markdown-outline-level ()
7019 "Return the depth to which a statement is nested in the outline."
7020 (cond
7021 ((and (match-beginning 0)
7022 (markdown-code-block-at-pos (match-beginning 0)))
7023 7) ;; Only 6 header levels are defined.
7024 ((match-end 2) 1)
7025 ((match-end 3) 2)
7026 ((match-end 4)
7027 (length (markdown-trim-whitespace (match-string-no-properties 4))))))
7029 (defun markdown-promote-subtree (&optional arg)
7030 "Promote the current subtree of ATX headings.
7031 Note that Markdown does not support heading levels higher than
7032 six and therefore level-six headings will not be promoted
7033 further. If ARG is non-nil promote the heading, otherwise
7034 demote."
7035 (interactive "*P")
7036 (save-excursion
7037 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
7038 (re-search-backward markdown-regex-header-atx nil t))
7039 (not (markdown-code-block-at-point-p)))
7040 (let ((level (length (match-string 1)))
7041 (promote-or-demote (if arg 1 -1))
7042 (remove 't))
7043 (markdown-cycle-atx promote-or-demote remove)
7044 (catch 'end-of-subtree
7045 (while (and (markdown-next-heading)
7046 (looking-at markdown-regex-header-atx))
7047 ;; Exit if this not a higher level heading; promote otherwise.
7048 (if (and (looking-at markdown-regex-header-atx)
7049 (<= (length (match-string-no-properties 1)) level))
7050 (throw 'end-of-subtree nil)
7051 (markdown-cycle-atx promote-or-demote remove))))))))
7053 (defun markdown-demote-subtree ()
7054 "Demote the current subtree of ATX headings."
7055 (interactive)
7056 (markdown-promote-subtree t))
7058 (defun markdown-move-subtree-up ()
7059 "Move the current subtree of ATX headings up."
7060 (interactive)
7061 (outline-move-subtree-up 1))
7063 (defun markdown-move-subtree-down ()
7064 "Move the current subtree of ATX headings down."
7065 (interactive)
7066 (outline-move-subtree-down 1))
7068 (defun markdown-outline-next ()
7069 "Move to next list item, when in a list, or next visible heading."
7070 (interactive)
7071 (let ((bounds (markdown-next-list-item-bounds)))
7072 (if bounds
7073 (goto-char (nth 0 bounds))
7074 (markdown-next-visible-heading 1))))
7076 (defun markdown-outline-previous ()
7077 "Move to previous list item, when in a list, or previous visible heading."
7078 (interactive)
7079 (let ((bounds (markdown-prev-list-item-bounds)))
7080 (if bounds
7081 (goto-char (nth 0 bounds))
7082 (markdown-previous-visible-heading 1))))
7084 (defun markdown-outline-next-same-level ()
7085 "Move to next list item or heading of same level."
7086 (interactive)
7087 (let ((bounds (markdown-cur-list-item-bounds)))
7088 (if bounds
7089 (markdown-next-list-item (nth 3 bounds))
7090 (markdown-forward-same-level 1))))
7092 (defun markdown-outline-previous-same-level ()
7093 "Move to previous list item or heading of same level."
7094 (interactive)
7095 (let ((bounds (markdown-cur-list-item-bounds)))
7096 (if bounds
7097 (markdown-prev-list-item (nth 3 bounds))
7098 (markdown-backward-same-level 1))))
7100 (defun markdown-outline-up ()
7101 "Move to previous list item, when in a list, or previous heading."
7102 (interactive)
7103 (unless (markdown-up-list)
7104 (markdown-up-heading 1)))
7107 ;;; Marking and Narrowing =====================================================
7109 (defun markdown-mark-paragraph ()
7110 "Put mark at end of this block, point at beginning.
7111 The block marked is the one that contains point or follows point.
7113 Interactively, if this command is repeated or (in Transient Mark
7114 mode) if the mark is active, it marks the next block after the
7115 ones already marked."
7116 (interactive)
7117 (if (or (and (eq last-command this-command) (mark t))
7118 (and transient-mark-mode mark-active))
7119 (set-mark
7120 (save-excursion
7121 (goto-char (mark))
7122 (markdown-forward-paragraph)
7123 (point)))
7124 (let ((beginning-of-defun-function #'markdown-backward-paragraph)
7125 (end-of-defun-function #'markdown-forward-paragraph))
7126 (mark-defun))))
7128 (defun markdown-mark-block ()
7129 "Put mark at end of this block, point at beginning.
7130 The block marked is the one that contains point or follows point.
7132 Interactively, if this command is repeated or (in Transient Mark
7133 mode) if the mark is active, it marks the next block after the
7134 ones already marked."
7135 (interactive)
7136 (if (or (and (eq last-command this-command) (mark t))
7137 (and transient-mark-mode mark-active))
7138 (set-mark
7139 (save-excursion
7140 (goto-char (mark))
7141 (markdown-forward-block)
7142 (point)))
7143 (let ((beginning-of-defun-function #'markdown-backward-block)
7144 (end-of-defun-function #'markdown-forward-block))
7145 (mark-defun))))
7147 (defun markdown-narrow-to-block ()
7148 "Make text outside current block invisible.
7149 The current block is the one that contains point or follows point."
7150 (interactive)
7151 (let ((beginning-of-defun-function #'markdown-backward-block)
7152 (end-of-defun-function #'markdown-forward-block))
7153 (narrow-to-defun)))
7155 (defun markdown-mark-text-block ()
7156 "Put mark at end of this plain text block, point at beginning.
7157 The block marked is the one that contains point or follows point.
7159 Interactively, if this command is repeated or (in Transient Mark
7160 mode) if the mark is active, it marks the next block after the
7161 ones already marked."
7162 (interactive)
7163 (if (or (and (eq last-command this-command) (mark t))
7164 (and transient-mark-mode mark-active))
7165 (set-mark
7166 (save-excursion
7167 (goto-char (mark))
7168 (markdown-end-of-text-block)
7169 (point)))
7170 (let ((beginning-of-defun-function #'markdown-beginning-of-text-block)
7171 (end-of-defun-function #'markdown-end-of-text-block))
7172 (mark-defun))))
7174 (defun markdown-mark-page ()
7175 "Put mark at end of this top level section, point at beginning.
7176 The top level section marked is the one that contains point or
7177 follows point.
7179 Interactively, if this command is repeated or (in Transient Mark
7180 mode) if the mark is active, it marks the next page after the
7181 ones already marked."
7182 (interactive)
7183 (if (or (and (eq last-command this-command) (mark t))
7184 (and transient-mark-mode mark-active))
7185 (set-mark
7186 (save-excursion
7187 (goto-char (mark))
7188 (markdown-forward-page)
7189 (point)))
7190 (let ((beginning-of-defun-function #'markdown-backward-page)
7191 (end-of-defun-function #'markdown-forward-page))
7192 (mark-defun))))
7194 (defun markdown-narrow-to-page ()
7195 "Make text outside current top level section invisible.
7196 The current section is the one that contains point or follows point."
7197 (interactive)
7198 (let ((beginning-of-defun-function #'markdown-backward-page)
7199 (end-of-defun-function #'markdown-forward-page))
7200 (narrow-to-defun)))
7202 (defun markdown-mark-subtree ()
7203 "Mark the current subtree.
7204 This puts point at the start of the current subtree, and mark at the end."
7205 (interactive)
7206 (let ((beg))
7207 (if (markdown-heading-at-point)
7208 (beginning-of-line)
7209 (markdown-previous-visible-heading 1))
7210 (setq beg (point))
7211 (markdown-end-of-subtree)
7212 (push-mark (point) nil t)
7213 (goto-char beg)))
7215 (defun markdown-narrow-to-subtree ()
7216 "Narrow buffer to the current subtree."
7217 (interactive)
7218 (save-excursion
7219 (save-match-data
7220 (narrow-to-region
7221 (progn (markdown-back-to-heading-over-code-block t) (point))
7222 (progn (markdown-end-of-subtree)
7223 (if (and (markdown-heading-at-point) (not (eobp)))
7224 (backward-char 1))
7225 (point))))))
7228 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
7230 (defun markdown-move-up ()
7231 "Move thing at point up.
7232 When in a list item, call `markdown-move-list-item-up'.
7233 When in a table, call `markdown-table-move-row-up'.
7234 Otherwise, move the current heading subtree up with
7235 `markdown-move-subtree-up'."
7236 (interactive)
7237 (cond
7238 ((markdown-list-item-at-point-p)
7239 (call-interactively #'markdown-move-list-item-up))
7240 ((markdown-table-at-point-p)
7241 (call-interactively #'markdown-table-move-row-up))
7243 (call-interactively #'markdown-move-subtree-up))))
7245 (defun markdown-move-down ()
7246 "Move thing at point down.
7247 When in a list item, call `markdown-move-list-item-down'.
7248 Otherwise, move the current heading subtree up with
7249 `markdown-move-subtree-down'."
7250 (interactive)
7251 (cond
7252 ((markdown-list-item-at-point-p)
7253 (call-interactively #'markdown-move-list-item-down))
7254 ((markdown-table-at-point-p)
7255 (call-interactively #'markdown-table-move-row-down))
7257 (call-interactively #'markdown-move-subtree-down))))
7259 (defun markdown-promote ()
7260 "Promote or move element at point to the left.
7261 Depending on the context, this function will promote a heading or
7262 list item at the point, move a table column to the left, or cycle
7263 markup."
7264 (interactive)
7265 (let (bounds)
7266 (cond
7267 ;; Promote atx heading subtree
7268 ((thing-at-point-looking-at markdown-regex-header-atx)
7269 (markdown-promote-subtree))
7270 ;; Promote setext heading
7271 ((thing-at-point-looking-at markdown-regex-header-setext)
7272 (markdown-cycle-setext -1))
7273 ;; Promote horizontal rule
7274 ((thing-at-point-looking-at markdown-regex-hr)
7275 (markdown-cycle-hr -1))
7276 ;; Promote list item
7277 ((setq bounds (markdown-cur-list-item-bounds))
7278 (markdown-promote-list-item bounds))
7279 ;; Move table column to the left
7280 ((markdown-table-at-point-p)
7281 (call-interactively #'markdown-table-move-column-left))
7282 ;; Promote bold
7283 ((thing-at-point-looking-at markdown-regex-bold)
7284 (markdown-cycle-bold))
7285 ;; Promote italic
7286 ((thing-at-point-looking-at markdown-regex-italic)
7287 (markdown-cycle-italic))
7289 (user-error "Nothing to promote at point")))))
7291 (defun markdown-demote ()
7292 "Demote or move element at point to the right.
7293 Depending on the context, this function will demote a heading or
7294 list item at the point, move a table column to the right, or cycle
7295 or remove markup."
7296 (interactive)
7297 (let (bounds)
7298 (cond
7299 ;; Demote atx heading subtree
7300 ((thing-at-point-looking-at markdown-regex-header-atx)
7301 (markdown-demote-subtree))
7302 ;; Demote setext heading
7303 ((thing-at-point-looking-at markdown-regex-header-setext)
7304 (markdown-cycle-setext 1))
7305 ;; Demote horizontal rule
7306 ((thing-at-point-looking-at markdown-regex-hr)
7307 (markdown-cycle-hr 1))
7308 ;; Demote list item
7309 ((setq bounds (markdown-cur-list-item-bounds))
7310 (markdown-demote-list-item bounds))
7311 ;; Move table column to the right
7312 ((markdown-table-at-point-p)
7313 (call-interactively #'markdown-table-move-column-right))
7314 ;; Demote bold
7315 ((thing-at-point-looking-at markdown-regex-bold)
7316 (markdown-cycle-bold))
7317 ;; Demote italic
7318 ((thing-at-point-looking-at markdown-regex-italic)
7319 (markdown-cycle-italic))
7321 (user-error "Nothing to demote at point")))))
7324 ;;; Commands ==================================================================
7326 (defun markdown (&optional output-buffer-name)
7327 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
7328 The output buffer name defaults to `markdown-output-buffer-name'.
7329 Return the name of the output buffer used."
7330 (interactive)
7331 (save-window-excursion
7332 (let* ((commands (cond ((stringp markdown-command) (split-string markdown-command))
7333 ((listp markdown-command) markdown-command)))
7334 (command (car-safe commands))
7335 (command-args (cdr-safe commands))
7336 begin-region end-region)
7337 (if (use-region-p)
7338 (setq begin-region (region-beginning)
7339 end-region (region-end))
7340 (setq begin-region (point-min)
7341 end-region (point-max)))
7343 (unless output-buffer-name
7344 (setq output-buffer-name markdown-output-buffer-name))
7345 (when (and (stringp command) (not (executable-find command)))
7346 (user-error "Markdown command %s is not found" command))
7347 (let ((exit-code
7348 (cond
7349 ;; Handle case when `markdown-command' does not read from stdin
7350 ((and (stringp command) markdown-command-needs-filename)
7351 (if (not buffer-file-name)
7352 (user-error "Must be visiting a file")
7353 ;; Don’t use ‘shell-command’ because it’s not guaranteed to
7354 ;; return the exit code of the process.
7355 (let ((command (if (listp markdown-command)
7356 (string-join markdown-command " ")
7357 markdown-command)))
7358 (shell-command-on-region
7359 ;; Pass an empty region so that stdin is empty.
7360 (point) (point)
7361 (concat command " "
7362 (shell-quote-argument buffer-file-name))
7363 output-buffer-name))))
7364 ;; Pass region to `markdown-command' via stdin
7366 (let ((buf (get-buffer-create output-buffer-name)))
7367 (with-current-buffer buf
7368 (setq buffer-read-only nil)
7369 (erase-buffer))
7370 (if (stringp command)
7371 (if (not (null command-args))
7372 (apply #'call-process-region begin-region end-region command nil buf nil command-args)
7373 (call-process-region begin-region end-region command nil buf))
7374 (if markdown-command-needs-filename
7375 (if (not buffer-file-name)
7376 (user-error "Must be visiting a file")
7377 (funcall markdown-command begin-region end-region buf buffer-file-name))
7378 (funcall markdown-command begin-region end-region buf))
7379 ;; If the ‘markdown-command’ function didn’t signal an
7380 ;; error, assume it succeeded by binding ‘exit-code’ to 0.
7381 0))))))
7382 ;; The exit code can be a signal description string, so don’t use ‘=’
7383 ;; or ‘zerop’.
7384 (unless (eq exit-code 0)
7385 (user-error "%s failed with exit code %s"
7386 markdown-command exit-code))))
7387 output-buffer-name))
7389 (defun markdown-standalone (&optional output-buffer-name)
7390 "Special function to provide standalone HTML output.
7391 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
7392 (interactive)
7393 (setq output-buffer-name (markdown output-buffer-name))
7394 (with-current-buffer output-buffer-name
7395 (set-buffer output-buffer-name)
7396 (unless (markdown-output-standalone-p)
7397 (markdown-add-xhtml-header-and-footer output-buffer-name))
7398 (goto-char (point-min))
7399 (html-mode))
7400 output-buffer-name)
7402 (defun markdown-other-window (&optional output-buffer-name)
7403 "Run `markdown-command' on current buffer and display in other window.
7404 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7405 that name."
7406 (interactive)
7407 (markdown-display-buffer-other-window
7408 (markdown-standalone output-buffer-name)))
7410 (defun markdown-output-standalone-p ()
7411 "Determine whether `markdown-command' output is standalone XHTML.
7412 Standalone XHTML output is identified by an occurrence of
7413 `markdown-xhtml-standalone-regexp' in the first five lines of output."
7414 (save-excursion
7415 (goto-char (point-min))
7416 (save-match-data
7417 (re-search-forward
7418 markdown-xhtml-standalone-regexp
7419 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
7420 t))))
7422 (defun markdown-stylesheet-link-string (stylesheet-path)
7423 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
7424 (or (and (string-prefix-p "~" stylesheet-path)
7425 (expand-file-name stylesheet-path))
7426 stylesheet-path)
7427 "\" />"))
7429 (defun markdown-add-xhtml-header-and-footer (title)
7430 "Wrap XHTML header and footer with given TITLE around current buffer."
7431 (goto-char (point-min))
7432 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
7433 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
7434 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
7435 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
7436 "<head>\n<title>")
7437 (insert title)
7438 (insert "</title>\n")
7439 (unless (= (length markdown-content-type) 0)
7440 (insert
7441 (format
7442 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
7443 markdown-content-type
7444 (or (and markdown-coding-system
7445 (coding-system-get markdown-coding-system
7446 'mime-charset))
7447 (coding-system-get buffer-file-coding-system
7448 'mime-charset)
7449 "utf-8"))))
7450 (if (> (length markdown-css-paths) 0)
7451 (insert (mapconcat #'markdown-stylesheet-link-string
7452 markdown-css-paths "\n")))
7453 (when (> (length markdown-xhtml-header-content) 0)
7454 (insert markdown-xhtml-header-content))
7455 (insert "\n</head>\n\n"
7456 "<body>\n\n")
7457 (when (> (length markdown-xhtml-body-preamble) 0)
7458 (insert markdown-xhtml-body-preamble "\n"))
7459 (goto-char (point-max))
7460 (when (> (length markdown-xhtml-body-epilogue) 0)
7461 (insert "\n" markdown-xhtml-body-epilogue))
7462 (insert "\n"
7463 "</body>\n"
7464 "</html>\n"))
7466 (defun markdown-preview (&optional output-buffer-name)
7467 "Run `markdown-command' on the current buffer and view output in browser.
7468 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7469 that name."
7470 (interactive)
7471 (browse-url-of-buffer
7472 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
7474 (defun markdown-export-file-name (&optional extension)
7475 "Attempt to generate a filename for Markdown output.
7476 The file extension will be EXTENSION if given, or .html by default.
7477 If the current buffer is visiting a file, we construct a new
7478 output filename based on that filename. Otherwise, return nil."
7479 (when (buffer-file-name)
7480 (unless extension
7481 (setq extension ".html"))
7482 (let ((candidate
7483 (concat
7484 (cond
7485 ((buffer-file-name)
7486 (file-name-sans-extension (buffer-file-name)))
7487 (t (buffer-name)))
7488 extension)))
7489 (cond
7490 ((equal candidate (buffer-file-name))
7491 (concat candidate extension))
7493 candidate)))))
7495 (defun markdown-export (&optional output-file)
7496 "Run Markdown on the current buffer, save to file, and return the filename.
7497 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
7498 generated by `markdown-export-file-name', which will be constructed using the
7499 current filename, but with the extension removed and replaced with .html."
7500 (interactive)
7501 (unless output-file
7502 (setq output-file (markdown-export-file-name ".html")))
7503 (when output-file
7504 (let* ((init-buf (current-buffer))
7505 (init-point (point))
7506 (init-buf-string (buffer-string))
7507 (output-buffer (find-file-noselect output-file))
7508 (output-buffer-name (buffer-name output-buffer)))
7509 (run-hooks 'markdown-before-export-hook)
7510 (markdown-standalone output-buffer-name)
7511 (with-current-buffer output-buffer
7512 (run-hooks 'markdown-after-export-hook)
7513 (save-buffer)
7514 (when markdown-export-kill-buffer (kill-buffer)))
7515 ;; if modified, restore initial buffer
7516 (when (buffer-modified-p init-buf)
7517 (erase-buffer)
7518 (insert init-buf-string)
7519 (save-buffer)
7520 (goto-char init-point))
7521 output-file)))
7523 (defun markdown-export-and-preview ()
7524 "Export to XHTML using `markdown-export' and browse the resulting file."
7525 (interactive)
7526 (browse-url-of-file (markdown-export)))
7528 (defvar-local markdown-live-preview-buffer nil
7529 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
7531 (defvar-local markdown-live-preview-source-buffer nil
7532 "Source buffer from which current buffer was generated.
7533 This is the inverse of `markdown-live-preview-buffer'.")
7535 (defvar markdown-live-preview-currently-exporting nil)
7537 (defun markdown-live-preview-get-filename ()
7538 "Standardize the filename exported by `markdown-live-preview-export'."
7539 (markdown-export-file-name ".html"))
7541 (defun markdown-live-preview-window-eww (file)
7542 "Preview FILE with eww.
7543 To be used with `markdown-live-preview-window-function'."
7544 (when (and (bound-and-true-p eww-auto-rename-buffer)
7545 markdown-live-preview-buffer)
7546 (kill-buffer markdown-live-preview-buffer))
7547 (eww-open-file file)
7548 ;; #737 if `eww-auto-rename-buffer' is non-nil, the buffer name is not "*eww*"
7549 ;; Try to find the buffer whose name ends with "eww*"
7550 (if (bound-and-true-p eww-auto-rename-buffer)
7551 (cl-loop for buf in (buffer-list)
7552 when (string-match-p "eww\\*\\'" (buffer-name buf))
7553 return buf)
7554 (get-buffer "*eww*")))
7556 (defun markdown-visual-lines-between-points (beg end)
7557 (save-excursion
7558 (goto-char beg)
7559 (cl-loop with count = 0
7560 while (progn (end-of-visual-line)
7561 (and (< (point) end) (line-move-visual 1 t)))
7562 do (cl-incf count)
7563 finally return count)))
7565 (defun markdown-live-preview-window-serialize (buf)
7566 "Get window point and scroll data for all windows displaying BUF."
7567 (when (buffer-live-p buf)
7568 (with-current-buffer buf
7569 (mapcar
7570 (lambda (win)
7571 (with-selected-window win
7572 (let* ((start (window-start))
7573 (pt (window-point))
7574 (pt-or-sym (cond ((= pt (point-min)) 'min)
7575 ((= pt (point-max)) 'max)
7576 (t pt)))
7577 (diff (markdown-visual-lines-between-points
7578 start pt)))
7579 (list win pt-or-sym diff))))
7580 (get-buffer-window-list buf)))))
7582 (defun markdown-get-point-back-lines (pt num-lines)
7583 (save-excursion
7584 (goto-char pt)
7585 (line-move-visual (- num-lines) t)
7586 ;; in testing, can occasionally overshoot the number of lines to traverse
7587 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
7588 (when (> actual-num-lines num-lines)
7589 (line-move-visual (- actual-num-lines num-lines) t)))
7590 (point)))
7592 (defun markdown-live-preview-window-deserialize (window-posns)
7593 "Apply window point and scroll data from WINDOW-POSNS.
7594 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
7595 (cl-destructuring-bind (win pt-or-sym diff) window-posns
7596 (when (window-live-p win)
7597 (with-current-buffer markdown-live-preview-buffer
7598 (set-window-buffer win (current-buffer))
7599 (cl-destructuring-bind (actual-pt actual-diff)
7600 (cl-case pt-or-sym
7601 (min (list (point-min) 0))
7602 (max (list (point-max) diff))
7603 (t (list pt-or-sym diff)))
7604 (set-window-start
7605 win (markdown-get-point-back-lines actual-pt actual-diff))
7606 (set-window-point win actual-pt))))))
7608 (defun markdown-live-preview-export ()
7609 "Export to XHTML using `markdown-export'.
7610 Browse the resulting file within Emacs using
7611 `markdown-live-preview-window-function' Return the buffer
7612 displaying the rendered output."
7613 (interactive)
7614 (let ((filename (markdown-live-preview-get-filename)))
7615 (when filename
7616 (let* ((markdown-live-preview-currently-exporting t)
7617 (cur-buf (current-buffer))
7618 (export-file (markdown-export filename))
7619 ;; get positions in all windows currently displaying output buffer
7620 (window-data
7621 (markdown-live-preview-window-serialize
7622 markdown-live-preview-buffer)))
7623 (save-window-excursion
7624 (let ((output-buffer
7625 (funcall markdown-live-preview-window-function export-file)))
7626 (with-current-buffer output-buffer
7627 (setq markdown-live-preview-source-buffer cur-buf)
7628 (add-hook 'kill-buffer-hook
7629 #'markdown-live-preview-remove-on-kill t t))
7630 (with-current-buffer cur-buf
7631 (setq markdown-live-preview-buffer output-buffer))))
7632 (with-current-buffer cur-buf
7633 ;; reset all windows displaying output buffer to where they were,
7634 ;; now with the new output
7635 (mapc #'markdown-live-preview-window-deserialize window-data)
7636 ;; delete html editing buffer
7637 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
7638 (when (and export-file (file-exists-p export-file)
7639 (eq markdown-live-preview-delete-export
7640 'delete-on-export))
7641 (delete-file export-file))
7642 markdown-live-preview-buffer)))))
7644 (defun markdown-live-preview-remove ()
7645 (when (buffer-live-p markdown-live-preview-buffer)
7646 (kill-buffer markdown-live-preview-buffer))
7647 (setq markdown-live-preview-buffer nil)
7648 ;; if set to 'delete-on-export, the output has already been deleted
7649 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
7650 (let ((outfile-name (markdown-live-preview-get-filename)))
7651 (when (and outfile-name (file-exists-p outfile-name))
7652 (delete-file outfile-name)))))
7654 (defun markdown-get-other-window ()
7655 "Find another window to display preview or output content."
7656 (cond
7657 ((memq markdown-split-window-direction '(vertical below))
7658 (or (window-in-direction 'below) (split-window-vertically)))
7659 ((memq markdown-split-window-direction '(horizontal right))
7660 (or (window-in-direction 'right) (split-window-horizontally)))
7661 (t (split-window-sensibly (get-buffer-window)))))
7663 (defun markdown-display-buffer-other-window (buf)
7664 "Display preview or output buffer BUF in another window."
7665 (if (and display-buffer-alist (eq markdown-split-window-direction 'any))
7666 (display-buffer buf)
7667 (let ((cur-buf (current-buffer))
7668 (window (markdown-get-other-window)))
7669 (set-window-buffer window buf)
7670 (set-buffer cur-buf))))
7672 (defun markdown-live-preview-if-markdown ()
7673 (when (and (derived-mode-p 'markdown-mode)
7674 markdown-live-preview-mode)
7675 (unless markdown-live-preview-currently-exporting
7676 (if (buffer-live-p markdown-live-preview-buffer)
7677 (markdown-live-preview-export)
7678 (markdown-display-buffer-other-window
7679 (markdown-live-preview-export))))))
7681 (defun markdown-live-preview-remove-on-kill ()
7682 (cond ((and (derived-mode-p 'markdown-mode)
7683 markdown-live-preview-mode)
7684 (markdown-live-preview-remove))
7685 (markdown-live-preview-source-buffer
7686 (with-current-buffer markdown-live-preview-source-buffer
7687 (setq markdown-live-preview-buffer nil))
7688 (setq markdown-live-preview-source-buffer nil))))
7690 (defun markdown-live-preview-switch-to-output ()
7691 "Turn on `markdown-live-preview-mode' and switch to output buffer.
7692 The output buffer is opened in another window."
7693 (interactive)
7694 (if markdown-live-preview-mode
7695 (markdown-display-buffer-other-window (markdown-live-preview-export)))
7696 (markdown-live-preview-mode))
7698 (defun markdown-live-preview-re-export ()
7699 "Re-export the current live previewed content.
7700 If the current buffer is a buffer displaying the exported version of a
7701 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
7702 update this buffer's contents."
7703 (interactive)
7704 (when markdown-live-preview-source-buffer
7705 (with-current-buffer markdown-live-preview-source-buffer
7706 (markdown-live-preview-export))))
7708 (defun markdown-open ()
7709 "Open file for the current buffer with `markdown-open-command'."
7710 (interactive)
7711 (unless markdown-open-command
7712 (user-error "Variable `markdown-open-command' must be set"))
7713 (if (stringp markdown-open-command)
7714 (if (not buffer-file-name)
7715 (user-error "Must be visiting a file")
7716 (save-buffer)
7717 (let ((exit-code (call-process markdown-open-command nil nil nil
7718 buffer-file-name)))
7719 ;; The exit code can be a signal description string, so don’t use ‘=’
7720 ;; or ‘zerop’.
7721 (unless (eq exit-code 0)
7722 (user-error "%s failed with exit code %s"
7723 markdown-open-command exit-code))))
7724 (funcall markdown-open-command))
7725 nil)
7727 (defun markdown-kill-ring-save ()
7728 "Run Markdown on file and store output in the kill ring."
7729 (interactive)
7730 (save-window-excursion
7731 (markdown)
7732 (with-current-buffer markdown-output-buffer-name
7733 (kill-ring-save (point-min) (point-max)))))
7736 ;;; Links =====================================================================
7738 (defun markdown-backward-to-link-start ()
7739 "Backward link start position if current position is in link title."
7740 ;; Issue #305
7741 (when (eq (get-text-property (point) 'face) 'markdown-link-face)
7742 (skip-chars-backward "^[")
7743 (forward-char -1)))
7745 (defun markdown-link-p ()
7746 "Return non-nil when `point' is at a non-wiki link.
7747 See `markdown-wiki-link-p' for more information."
7748 (save-excursion
7749 (let ((case-fold-search nil))
7750 (when (and (not (markdown-wiki-link-p)) (not (markdown-code-block-at-point-p)))
7751 (markdown-backward-to-link-start)
7752 (or (thing-at-point-looking-at markdown-regex-link-inline)
7753 (thing-at-point-looking-at markdown-regex-link-reference)
7754 (thing-at-point-looking-at markdown-regex-uri)
7755 (thing-at-point-looking-at markdown-regex-angle-uri))))))
7757 (defun markdown-link-at-pos (pos)
7758 "Return properties of link or image at position POS.
7759 Value is a list of elements describing the link:
7760 0. beginning position
7761 1. end position
7762 2. link text
7763 3. URL
7764 4. reference label
7765 5. title text
7766 6. bang (nil or \"!\")"
7767 (save-excursion
7768 (goto-char pos)
7769 (markdown-backward-to-link-start)
7770 (let (begin end text url reference title bang)
7771 (cond
7772 ;; Inline image or link at point.
7773 ((thing-at-point-looking-at markdown-regex-link-inline)
7774 (setq bang (match-string-no-properties 1)
7775 begin (match-beginning 0)
7776 end (match-end 0)
7777 text (match-string-no-properties 3)
7778 url (match-string-no-properties 6))
7779 (if (match-end 7)
7780 (setq title (substring (match-string-no-properties 7) 1 -1))
7781 ;; #408 URL contains close parenthesis case
7782 (goto-char (match-beginning 5))
7783 (let ((paren-end (scan-sexps (point) 1)))
7784 (when (and paren-end (< end paren-end))
7785 (setq url (buffer-substring (match-beginning 6) (1- paren-end)))))))
7786 ;; Reference link at point.
7787 ((or (thing-at-point-looking-at markdown-regex-link-inline)
7788 (thing-at-point-looking-at markdown-regex-link-reference))
7789 (setq bang (match-string-no-properties 1)
7790 begin (match-beginning 0)
7791 end (match-end 0)
7792 text (match-string-no-properties 3))
7793 (when (char-equal (char-after (match-beginning 5)) ?\[)
7794 (setq reference (match-string-no-properties 6))))
7795 ;; Angle bracket URI at point.
7796 ((thing-at-point-looking-at markdown-regex-angle-uri)
7797 (setq begin (match-beginning 0)
7798 end (match-end 0)
7799 url (match-string-no-properties 2)))
7800 ;; Plain URI at point.
7801 ((thing-at-point-looking-at markdown-regex-uri)
7802 (setq begin (match-beginning 0)
7803 end (match-end 0)
7804 url (match-string-no-properties 1))))
7805 (list begin end text url reference title bang))))
7807 (defun markdown-link-url ()
7808 "Return the URL part of the regular (non-wiki) link at point.
7809 Works with both inline and reference style links, and with images.
7810 If point is not at a link or the link reference is not defined
7811 returns nil."
7812 (let* ((values (markdown-link-at-pos (point)))
7813 (text (nth 2 values))
7814 (url (nth 3 values))
7815 (ref (nth 4 values)))
7816 (or url (and ref (car (markdown-reference-definition
7817 (downcase (if (string= ref "") text ref))))))))
7819 (defun markdown--browse-url (url)
7820 (let* ((struct (url-generic-parse-url url))
7821 (full (url-fullness struct))
7822 (file url))
7823 ;; Parse URL, determine fullness, strip query string
7824 (setq file (car (url-path-and-query struct)))
7825 ;; Open full URLs in browser, files in Emacs
7826 (if full
7827 (browse-url url)
7828 (when (and file (> (length file) 0))
7829 (let ((link-file (funcall markdown-translate-filename-function file)))
7830 (if (and markdown-open-image-command (string-match-p (image-file-name-regexp) link-file))
7831 (if (functionp markdown-open-image-command)
7832 (funcall markdown-open-image-command link-file)
7833 (process-file markdown-open-image-command nil nil nil link-file))
7834 (find-file link-file)))))))
7836 (defun markdown-follow-link-at-point (&optional event)
7837 "Open the non-wiki link at point or EVENT.
7838 If the link is a complete URL, open in browser with `browse-url'.
7839 Otherwise, open with `find-file' after stripping anchor and/or query string.
7840 Translate filenames using `markdown-filename-translate-function'."
7841 (interactive (list last-command-event))
7842 (save-excursion
7843 (if event (posn-set-point (event-start event)))
7844 (if (markdown-link-p)
7845 (markdown--browse-url (markdown-link-url))
7846 (user-error "Point is not at a Markdown link or URL"))))
7848 (defun markdown-fontify-inline-links (last)
7849 "Add text properties to next inline link from point to LAST."
7850 (when (markdown-match-generic-links last nil)
7851 (let* ((link-start (match-beginning 3))
7852 (link-end (match-end 3))
7853 (url-start (match-beginning 6))
7854 (url-end (match-end 6))
7855 (url (match-string-no-properties 6))
7856 (title-start (match-beginning 7))
7857 (title-end (match-end 7))
7858 (title (match-string-no-properties 7))
7859 ;; Markup part
7860 (mp (list 'invisible 'markdown-markup
7861 'rear-nonsticky t
7862 'font-lock-multiline t))
7863 ;; Link part (without face)
7864 (lp (list 'keymap markdown-mode-mouse-map
7865 'mouse-face 'markdown-highlight-face
7866 'font-lock-multiline t
7867 'help-echo (if title (concat title "\n" url) url)))
7868 ;; URL part
7869 (up (list 'keymap markdown-mode-mouse-map
7870 'invisible 'markdown-markup
7871 'mouse-face 'markdown-highlight-face
7872 'font-lock-multiline t))
7873 ;; URL composition character
7874 (url-char (markdown--first-displayable markdown-url-compose-char))
7875 ;; Title part
7876 (tp (list 'invisible 'markdown-markup
7877 'font-lock-multiline t)))
7878 (dolist (g '(1 2 4 5 8))
7879 (when (match-end g)
7880 (add-text-properties (match-beginning g) (match-end g) mp)
7881 (add-face-text-property (match-beginning g) (match-end g) 'markdown-markup-face)))
7882 ;; Preserve existing faces applied to link part (e.g., inline code)
7883 (when link-start
7884 (add-text-properties link-start link-end lp)
7885 (add-face-text-property link-start link-end 'markdown-link-face))
7886 (when url-start
7887 (add-text-properties url-start url-end up)
7888 (add-face-text-property url-start url-end 'markdown-url-face))
7889 (when title-start
7890 (add-text-properties url-end title-end tp)
7891 (add-face-text-property url-end title-end 'markdown-link-title-face))
7892 (when (and markdown-hide-urls url-start)
7893 (compose-region url-start (or title-end url-end) url-char))
7894 t)))
7896 (defun markdown-fontify-reference-links (last)
7897 "Add text properties to next reference link from point to LAST."
7898 (when (markdown-match-generic-links last t)
7899 (let* ((link-start (match-beginning 3))
7900 (link-end (match-end 3))
7901 (ref-start (match-beginning 6))
7902 (ref-end (match-end 6))
7903 ;; Markup part
7904 (mp (list 'invisible 'markdown-markup
7905 'rear-nonsticky t
7906 'font-lock-multiline t))
7907 ;; Link part
7908 (lp (list 'keymap markdown-mode-mouse-map
7909 'mouse-face 'markdown-highlight-face
7910 'font-lock-multiline t
7911 'help-echo (lambda (_ __ pos)
7912 (save-match-data
7913 (save-excursion
7914 (goto-char pos)
7915 (or (markdown-link-url)
7916 "Undefined reference"))))))
7917 ;; URL composition character
7918 (url-char (markdown--first-displayable markdown-url-compose-char))
7919 ;; Reference part
7920 (rp (list 'invisible 'markdown-markup
7921 'font-lock-multiline t)))
7922 (dolist (g '(1 2 4 5 8))
7923 (when (match-end g)
7924 (add-text-properties (match-beginning g) (match-end g) mp)
7925 (add-face-text-property (match-beginning g) (match-end g) 'markdown-markup-face)))
7926 (when link-start
7927 (add-text-properties link-start link-end lp)
7928 (add-face-text-property link-start link-end 'markdown-link-face))
7929 (when ref-start
7930 (add-text-properties ref-start ref-end rp)
7931 (add-face-text-property ref-start ref-end 'markdown-reference-face)
7932 (when (and markdown-hide-urls (> (- ref-end ref-start) 2))
7933 (compose-region ref-start ref-end url-char)))
7934 t)))
7936 (defun markdown-fontify-angle-uris (last)
7937 "Add text properties to angle URIs from point to LAST."
7938 (when (markdown-match-angle-uris last)
7939 (let* ((url-start (match-beginning 2))
7940 (url-end (match-end 2))
7941 ;; Markup part
7942 (mp (list 'face 'markdown-markup-face
7943 'invisible 'markdown-markup
7944 'rear-nonsticky t
7945 'font-lock-multiline t))
7946 ;; URI part
7947 (up (list 'keymap markdown-mode-mouse-map
7948 'face 'markdown-plain-url-face
7949 'mouse-face 'markdown-highlight-face
7950 'font-lock-multiline t)))
7951 (dolist (g '(1 3))
7952 (add-text-properties (match-beginning g) (match-end g) mp))
7953 (add-text-properties url-start url-end up)
7954 t)))
7956 (defun markdown-fontify-plain-uris (last)
7957 "Add text properties to plain URLs from point to LAST."
7958 (when (markdown-match-plain-uris last)
7959 (let* ((start (match-beginning 0))
7960 (end (match-end 0))
7961 (props (list 'keymap markdown-mode-mouse-map
7962 'face 'markdown-plain-url-face
7963 'mouse-face 'markdown-highlight-face
7964 'rear-nonsticky t
7965 'font-lock-multiline t)))
7966 (add-text-properties start end props)
7967 t)))
7969 (defun markdown-toggle-url-hiding (&optional arg)
7970 "Toggle the display or hiding of URLs.
7971 With a prefix argument ARG, enable URL hiding if ARG is positive,
7972 and disable it otherwise."
7973 (interactive (list (or current-prefix-arg 'toggle)))
7974 (setq markdown-hide-urls
7975 (if (eq arg 'toggle)
7976 (not markdown-hide-urls)
7977 (> (prefix-numeric-value arg) 0)))
7978 (if markdown-hide-urls
7979 (message "markdown-mode URL hiding enabled")
7980 (message "markdown-mode URL hiding disabled"))
7981 (markdown-reload-extensions))
7984 ;;; Wiki Links ================================================================
7986 (defun markdown-wiki-link-p ()
7987 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
7988 A true wiki link name matches `markdown-regex-wiki-link' but does
7989 not match the current file name after conversion. This modifies
7990 the data returned by `match-data'. Note that the potential wiki
7991 link name must be available via `match-string'."
7992 (when markdown-enable-wiki-links
7993 (let ((case-fold-search nil))
7994 (and (thing-at-point-looking-at markdown-regex-wiki-link)
7995 (not (markdown-code-block-at-point-p))
7996 (or (not buffer-file-name)
7997 (not (string-equal (buffer-file-name)
7998 (markdown-convert-wiki-link-to-filename
7999 (markdown-wiki-link-link)))))))))
8001 (defun markdown-wiki-link-link ()
8002 "Return the link part of the wiki link using current match data.
8003 The location of the link component depends on the value of
8004 `markdown-wiki-link-alias-first'."
8005 (if markdown-wiki-link-alias-first
8006 (or (match-string-no-properties 5) (match-string-no-properties 3))
8007 (match-string-no-properties 3)))
8009 (defun markdown-wiki-link-alias ()
8010 "Return the alias or text part of the wiki link using current match data.
8011 The location of the alias component depends on the value of
8012 `markdown-wiki-link-alias-first'."
8013 (if markdown-wiki-link-alias-first
8014 (match-string-no-properties 3)
8015 (or (match-string-no-properties 5) (match-string-no-properties 3))))
8017 (defun markdown--wiki-link-search-types ()
8018 (let ((ret (and markdown-wiki-link-search-type
8019 (cl-copy-list markdown-wiki-link-search-type))))
8020 (when (and markdown-wiki-link-search-subdirectories
8021 (not (memq 'sub-directories markdown-wiki-link-search-type)))
8022 (push 'sub-directories ret))
8023 (when (and markdown-wiki-link-search-parent-directories
8024 (not (memq 'parent-directories markdown-wiki-link-search-type)))
8025 (push 'parent-directories ret))
8026 ret))
8028 (defun markdown--project-root ()
8029 (or (cl-loop for dir in '(".git" ".hg" ".svn")
8030 when (locate-dominating-file default-directory dir)
8031 return it)
8032 (progn
8033 (require 'project)
8034 (let ((project (project-current t)))
8035 (with-no-warnings
8036 (if (fboundp 'project-root)
8037 (project-root project)
8038 (car (project-roots project))))))))
8040 (defun markdown-convert-wiki-link-to-filename (name)
8041 "Generate a filename from the wiki link NAME.
8042 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
8043 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
8044 and [[test test]] both map to Test-test.ext. Look in the current
8045 directory first, then in subdirectories if
8046 `markdown-wiki-link-search-subdirectories' is non-nil, and then
8047 in parent directories if
8048 `markdown-wiki-link-search-parent-directories' is non-nil."
8049 (save-match-data
8050 ;; This function must not overwrite match data(PR #590)
8051 (let* ((basename (replace-regexp-in-string
8052 "[[:space:]\n]" markdown-link-space-sub-char name))
8053 (basename (if (derived-mode-p 'gfm-mode)
8054 (concat (upcase (substring basename 0 1))
8055 (downcase (substring basename 1 nil)))
8056 basename))
8057 (search-types (markdown--wiki-link-search-types))
8058 directory extension default candidates dir)
8059 (when buffer-file-name
8060 (setq directory (file-name-directory buffer-file-name)
8061 extension (file-name-extension buffer-file-name)))
8062 (setq default (concat basename
8063 (when extension (concat "." extension))))
8064 (cond
8065 ;; Look in current directory first.
8066 ((or (null buffer-file-name)
8067 (file-exists-p default))
8068 default)
8069 ;; Possibly search in subdirectories, next.
8070 ((and (memq 'sub-directories search-types)
8071 (setq candidates
8072 (directory-files-recursively
8073 directory (concat "^" default "$"))))
8074 (car candidates))
8075 ;; Possibly search in parent directories as a last resort.
8076 ((and (memq 'parent-directories search-types)
8077 (setq dir (locate-dominating-file directory default)))
8078 (concat dir default))
8079 ((and (memq 'project search-types)
8080 (setq candidates
8081 (directory-files-recursively
8082 (markdown--project-root) (concat "^" default "$"))))
8083 (car candidates))
8084 ;; If nothing is found, return default in current directory.
8085 (t default)))))
8087 (defun markdown-follow-wiki-link (name &optional other)
8088 "Follow the wiki link NAME.
8089 Convert the name to a file name and call `find-file'. Ensure that
8090 the new buffer remains in `markdown-mode'. Open the link in another
8091 window when OTHER is non-nil."
8092 (let ((filename (markdown-convert-wiki-link-to-filename name))
8093 (wp (when buffer-file-name
8094 (file-name-directory buffer-file-name))))
8095 (if (not wp)
8096 (user-error "Must be visiting a file")
8097 (when other (other-window 1))
8098 (let ((default-directory wp))
8099 (find-file filename)))
8100 (unless (derived-mode-p 'markdown-mode)
8101 (markdown-mode))))
8103 (defun markdown-follow-wiki-link-at-point (&optional arg)
8104 "Find Wiki Link at point.
8105 With prefix argument ARG, open the file in other window.
8106 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
8107 (interactive "P")
8108 (if (markdown-wiki-link-p)
8109 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
8110 (user-error "Point is not at a Wiki Link")))
8112 (defun markdown-highlight-wiki-link (from to face)
8113 "Highlight the wiki link in the region between FROM and TO using FACE."
8114 (put-text-property from to 'font-lock-face face))
8116 (defun markdown-unfontify-region-wiki-links (from to)
8117 "Remove wiki link faces from the region specified by FROM and TO."
8118 (interactive "*r")
8119 (let ((modified (buffer-modified-p)))
8120 (remove-text-properties from to '(font-lock-face markdown-link-face))
8121 (remove-text-properties from to '(font-lock-face markdown-missing-link-face))
8122 ;; remove-text-properties marks the buffer modified in emacs 24.3,
8123 ;; undo that if it wasn't originally marked modified
8124 (set-buffer-modified-p modified)))
8126 (defun markdown-fontify-region-wiki-links (from to)
8127 "Search region given by FROM and TO for wiki links and fontify them.
8128 If a wiki link is found check to see if the backing file exists
8129 and highlight accordingly."
8130 (goto-char from)
8131 (save-match-data
8132 (while (re-search-forward markdown-regex-wiki-link to t)
8133 (when (not (markdown-code-block-at-point-p))
8134 (let ((highlight-beginning (match-beginning 1))
8135 (highlight-end (match-end 1))
8136 (file-name
8137 (markdown-convert-wiki-link-to-filename
8138 (markdown-wiki-link-link))))
8139 (if (condition-case nil (file-exists-p file-name) (error nil))
8140 (markdown-highlight-wiki-link
8141 highlight-beginning highlight-end 'markdown-link-face)
8142 (markdown-highlight-wiki-link
8143 highlight-beginning highlight-end 'markdown-missing-link-face)))))))
8145 (defun markdown-extend-changed-region (from to)
8146 "Extend region given by FROM and TO so that we can fontify all links.
8147 The region is extended to the first newline before and the first
8148 newline after."
8149 ;; start looking for the first new line before 'from
8150 (goto-char from)
8151 (re-search-backward "\n" nil t)
8152 (let ((new-from (point-min))
8153 (new-to (point-max)))
8154 (if (not (= (point) from))
8155 (setq new-from (point)))
8156 ;; do the same thing for the first new line after 'to
8157 (goto-char to)
8158 (re-search-forward "\n" nil t)
8159 (if (not (= (point) to))
8160 (setq new-to (point)))
8161 (cl-values new-from new-to)))
8163 (defun markdown-check-change-for-wiki-link (from to)
8164 "Check region between FROM and TO for wiki links and re-fontify as needed."
8165 (interactive "*r")
8166 (let* ((modified (buffer-modified-p))
8167 (buffer-undo-list t)
8168 (inhibit-read-only t)
8169 deactivate-mark
8170 buffer-file-truename)
8171 (unwind-protect
8172 (save-excursion
8173 (save-match-data
8174 (save-restriction
8175 (cursor-intangible-mode +1) ;; inhibit-point-motion-hooks is obsoleted since Emacs 29
8176 ;; Extend the region to fontify so that it starts
8177 ;; and ends at safe places.
8178 (cl-multiple-value-bind (new-from new-to)
8179 (markdown-extend-changed-region from to)
8180 (goto-char new-from)
8181 ;; Only refontify when the range contains text with a
8182 ;; wiki link face or if the wiki link regexp matches.
8183 (when (or (markdown-range-property-any
8184 new-from new-to 'font-lock-face
8185 '(markdown-link-face markdown-missing-link-face))
8186 (re-search-forward
8187 markdown-regex-wiki-link new-to t))
8188 ;; Unfontify existing fontification (start from scratch)
8189 (markdown-unfontify-region-wiki-links new-from new-to)
8190 ;; Now do the fontification.
8191 (markdown-fontify-region-wiki-links new-from new-to))))))
8192 (cursor-intangible-mode -1)
8193 (and (not modified)
8194 (buffer-modified-p)
8195 (set-buffer-modified-p nil)))))
8197 (defun markdown-check-change-for-wiki-link-after-change (from to _)
8198 "Check region between FROM and TO for wiki links and re-fontify as needed.
8199 Designed to be used with the `after-change-functions' hook."
8200 (markdown-check-change-for-wiki-link from to))
8202 (defun markdown-fontify-buffer-wiki-links ()
8203 "Refontify all wiki links in the buffer."
8204 (interactive)
8205 (markdown-check-change-for-wiki-link (point-min) (point-max)))
8207 (defun markdown-toggle-wiki-links (&optional arg)
8208 "Toggle support for wiki links.
8209 With a prefix argument ARG, enable wiki link support if ARG is positive,
8210 and disable it otherwise."
8211 (interactive (list (or current-prefix-arg 'toggle)))
8212 (setq markdown-enable-wiki-links
8213 (if (eq arg 'toggle)
8214 (not markdown-enable-wiki-links)
8215 (> (prefix-numeric-value arg) 0)))
8216 (if markdown-enable-wiki-links
8217 (message "markdown-mode wiki link support enabled")
8218 (message "markdown-mode wiki link support disabled"))
8219 (markdown-reload-extensions))
8221 (defun markdown-setup-wiki-link-hooks ()
8222 "Add or remove hooks for fontifying wiki links.
8223 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
8224 ;; Anytime text changes make sure it gets fontified correctly
8225 (if (and markdown-enable-wiki-links
8226 markdown-wiki-link-fontify-missing)
8227 (add-hook 'after-change-functions
8228 #'markdown-check-change-for-wiki-link-after-change t t)
8229 (remove-hook 'after-change-functions
8230 #'markdown-check-change-for-wiki-link-after-change t))
8231 ;; If we left the buffer there is a really good chance we were
8232 ;; creating one of the wiki link documents. Make sure we get
8233 ;; refontified when we come back.
8234 (if (and markdown-enable-wiki-links
8235 markdown-wiki-link-fontify-missing)
8236 (progn
8237 (add-hook 'window-configuration-change-hook
8238 #'markdown-fontify-buffer-wiki-links t t)
8239 (markdown-fontify-buffer-wiki-links))
8240 (remove-hook 'window-configuration-change-hook
8241 #'markdown-fontify-buffer-wiki-links t)
8242 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
8245 ;;; Following & Doing =========================================================
8247 (defun markdown-follow-thing-at-point (arg)
8248 "Follow thing at point if possible, such as a reference link or wiki link.
8249 Opens inline and reference links in a browser. Opens wiki links
8250 to other files in the current window, or the another window if
8251 ARG is non-nil.
8252 See `markdown-follow-link-at-point' and
8253 `markdown-follow-wiki-link-at-point'."
8254 (interactive "P")
8255 (cond ((markdown-link-p)
8256 (markdown--browse-url (markdown-link-url)))
8257 ((markdown-wiki-link-p)
8258 (markdown-follow-wiki-link-at-point arg))
8260 (let* ((values (markdown-link-at-pos (point)))
8261 (url (nth 3 values)))
8262 (unless url
8263 (user-error "Nothing to follow at point"))
8264 (markdown--browse-url url)))))
8266 (defun markdown-do ()
8267 "Do something sensible based on context at point.
8268 Jumps between reference links and definitions; between footnote
8269 markers and footnote text."
8270 (interactive)
8271 (cond
8272 ;; Footnote definition
8273 ((markdown-footnote-text-positions)
8274 (markdown-footnote-return))
8275 ;; Footnote marker
8276 ((markdown-footnote-marker-positions)
8277 (markdown-footnote-goto-text))
8278 ;; Reference link
8279 ((thing-at-point-looking-at markdown-regex-link-reference)
8280 (markdown-reference-goto-definition))
8281 ;; Reference definition
8282 ((thing-at-point-looking-at markdown-regex-reference-definition)
8283 (markdown-reference-goto-link (match-string-no-properties 2)))
8284 ;; Link
8285 ((or (markdown-link-p) (markdown-wiki-link-p))
8286 (markdown-follow-thing-at-point nil))
8287 ;; GFM task list item
8288 ((markdown-gfm-task-list-item-at-point)
8289 (markdown-toggle-gfm-checkbox))
8290 ;; Align table
8291 ((markdown-table-at-point-p)
8292 (call-interactively #'markdown-table-align))
8293 ;; Otherwise
8295 (markdown-insert-gfm-checkbox))))
8298 ;;; Miscellaneous =============================================================
8300 (defun markdown-compress-whitespace-string (str)
8301 "Compress whitespace in STR and return result.
8302 Leading and trailing whitespace is removed. Sequences of multiple
8303 spaces, tabs, and newlines are replaced with single spaces."
8304 (replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
8305 (replace-regexp-in-string "[ \t\n]+" " " str)))
8307 (defun markdown--substitute-command-keys (string)
8308 "Like `substitute-command-keys' but, but prefers control characters.
8309 First pass STRING to `substitute-command-keys' and then
8310 substitute `C-i` for `TAB` and `C-m` for `RET`."
8311 (replace-regexp-in-string
8312 "\\<TAB\\>" "C-i"
8313 (replace-regexp-in-string
8314 "\\<RET\\>" "C-m" (substitute-command-keys string) t) t))
8316 (defun markdown-line-number-at-pos (&optional pos)
8317 "Return (narrowed) buffer line number at position POS.
8318 If POS is nil, use current buffer location.
8319 This is an exact copy of `line-number-at-pos' for use in emacs21."
8320 (let ((opoint (or pos (point))) start)
8321 (save-excursion
8322 (goto-char (point-min))
8323 (setq start (point))
8324 (goto-char opoint)
8325 (forward-line 0)
8326 (1+ (count-lines start (point))))))
8328 (defun markdown-inside-link-p ()
8329 "Return t if point is within a link."
8330 (save-match-data
8331 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
8333 (defun markdown-line-is-reference-definition-p ()
8334 "Return whether the current line is a (non-footnote) reference definition."
8335 (save-excursion
8336 (move-beginning-of-line 1)
8337 (and (looking-at-p markdown-regex-reference-definition)
8338 (not (looking-at-p "[ \t]*\\[^")))))
8340 (defun markdown-adaptive-fill-function ()
8341 "Return prefix for filling paragraph or nil if not determined."
8342 (cond
8343 ;; List item inside blockquote
8344 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
8345 (replace-regexp-in-string
8346 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
8347 ;; Blockquote
8348 ((looking-at markdown-regex-blockquote)
8349 (buffer-substring-no-properties (match-beginning 0) (match-end 2)))
8350 ;; List items
8351 ((looking-at markdown-regex-list)
8352 (match-string-no-properties 0))
8353 ;; Footnote definition
8354 ((looking-at-p markdown-regex-footnote-definition)
8355 " ") ; four spaces
8356 ;; No match
8357 (t nil)))
8359 (defun markdown-fill-paragraph (&optional justify)
8360 "Fill paragraph at or after point.
8361 This function is like \\[fill-paragraph], but it skips Markdown
8362 code blocks. If the point is in a code block, or just before one,
8363 do not fill. Otherwise, call `fill-paragraph' as usual. If
8364 JUSTIFY is non-nil, justify text as well. Since this function
8365 handles filling itself, it always returns t so that
8366 `fill-paragraph' doesn't run."
8367 (interactive "P")
8368 (unless (or (markdown-code-block-at-point-p)
8369 (save-excursion
8370 (back-to-indentation)
8371 (skip-syntax-forward "-")
8372 (markdown-code-block-at-point-p)))
8373 (let ((fill-prefix (save-excursion
8374 (goto-char (line-beginning-position))
8375 (when (looking-at "\\([ \t]*>[ \t]*\\(?:>[ \t]*\\)+\\)")
8376 (match-string-no-properties 1)))))
8377 (fill-paragraph justify)))
8380 (defun markdown-fill-forward-paragraph (&optional arg)
8381 "Function used by `fill-paragraph' to move over ARG paragraphs.
8382 This is a `fill-forward-paragraph-function' for `markdown-mode'.
8383 It is called with a single argument specifying the number of
8384 paragraphs to move. Just like `forward-paragraph', it should
8385 return the number of paragraphs left to move."
8386 (or arg (setq arg 1))
8387 (if (> arg 0)
8388 ;; With positive ARG, move across ARG non-code-block paragraphs,
8389 ;; one at a time. When passing a code block, don't decrement ARG.
8390 (while (and (not (eobp))
8391 (> arg 0)
8392 (= (forward-paragraph 1) 0)
8393 (or (markdown-code-block-at-pos (line-beginning-position 0))
8394 (setq arg (1- arg)))))
8395 ;; Move backward by one paragraph with negative ARG (always -1).
8396 (let ((start (point)))
8397 (setq arg (forward-paragraph arg))
8398 (while (and (not (eobp))
8399 (progn (move-to-left-margin) (not (eobp)))
8400 (looking-at-p paragraph-separate))
8401 (forward-line 1))
8402 (cond
8403 ;; Move point past whitespace following list marker.
8404 ((looking-at markdown-regex-list)
8405 (goto-char (match-end 0)))
8406 ;; Move point past whitespace following pipe at beginning of line
8407 ;; to handle Pandoc line blocks.
8408 ((looking-at "^|\\s-*")
8409 (goto-char (match-end 0)))
8410 ;; Return point if the paragraph passed was a code block.
8411 ((markdown-code-block-at-pos (line-beginning-position 2))
8412 (goto-char start)))))
8413 arg)
8415 (defun markdown--inhibit-electric-quote ()
8416 "Function added to `electric-quote-inhibit-functions'.
8417 Return non-nil if the quote has been inserted inside a code block
8418 or span."
8419 (let ((pos (1- (point))))
8420 (or (markdown-inline-code-at-pos pos)
8421 (markdown-code-block-at-pos pos))))
8424 ;;; Extension Framework =======================================================
8426 (defun markdown-reload-extensions ()
8427 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
8428 (interactive)
8429 (when (derived-mode-p 'markdown-mode)
8430 ;; Refontify buffer
8431 (font-lock-flush)
8432 ;; Add or remove hooks related to extensions
8433 (markdown-setup-wiki-link-hooks)))
8435 (defun markdown-handle-local-variables ()
8436 "Run in `hack-local-variables-hook' to update font lock rules.
8437 Checks to see if there is actually a ‘markdown-mode’ file local variable
8438 before regenerating font-lock rules for extensions."
8439 (when (or (assoc 'markdown-enable-wiki-links file-local-variables-alist)
8440 (assoc 'markdown-enable-math file-local-variables-alist))
8441 (when (assoc 'markdown-enable-math file-local-variables-alist)
8442 (markdown-toggle-math markdown-enable-math))
8443 (markdown-reload-extensions)))
8446 ;;; Math Support ==============================================================
8448 (defconst markdown-mode-font-lock-keywords-math
8449 (list
8450 ;; Equation reference (eq:foo)
8451 '("\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" . ((1 markdown-markup-face)
8452 (2 markdown-reference-face)
8453 (3 markdown-markup-face)))
8454 ;; Equation reference \eqref{foo}
8455 '("\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" . ((1 markdown-markup-face)
8456 (2 markdown-reference-face)
8457 (3 markdown-markup-face))))
8458 "Font lock keywords to add and remove when toggling math support.")
8460 (defun markdown-toggle-math (&optional arg)
8461 "Toggle support for inline and display LaTeX math expressions.
8462 With a prefix argument ARG, enable math mode if ARG is positive,
8463 and disable it otherwise. If called from Lisp, enable the mode
8464 if ARG is omitted or nil."
8465 (interactive (list (or current-prefix-arg 'toggle)))
8466 (setq markdown-enable-math
8467 (if (eq arg 'toggle)
8468 (not markdown-enable-math)
8469 (> (prefix-numeric-value arg) 0)))
8470 (if markdown-enable-math
8471 (progn
8472 (font-lock-add-keywords
8473 'markdown-mode markdown-mode-font-lock-keywords-math)
8474 (message "markdown-mode math support enabled"))
8475 (font-lock-remove-keywords
8476 'markdown-mode markdown-mode-font-lock-keywords-math)
8477 (message "markdown-mode math support disabled"))
8478 (markdown-reload-extensions))
8481 ;;; GFM Checkboxes ============================================================
8483 (define-button-type 'markdown-gfm-checkbox-button
8484 'follow-link t
8485 'face 'markdown-gfm-checkbox-face
8486 'mouse-face 'markdown-highlight-face
8487 'action #'markdown-toggle-gfm-checkbox-button)
8489 (defun markdown-gfm-task-list-item-at-point (&optional bounds)
8490 "Return non-nil if there is a GFM task list item at the point.
8491 Optionally, the list item BOUNDS may be given if available, as
8492 returned by `markdown-cur-list-item-bounds'. When a task list item
8493 is found, the return value is the same value returned by
8494 `markdown-cur-list-item-bounds'."
8495 (unless bounds
8496 (setq bounds (markdown-cur-list-item-bounds)))
8497 (> (length (nth 5 bounds)) 0))
8499 (defun markdown-insert-gfm-checkbox ()
8500 "Add GFM checkbox at point.
8501 Returns t if added.
8502 Returns nil if non-applicable."
8503 (interactive)
8504 (let ((bounds (markdown-cur-list-item-bounds)))
8505 (if bounds
8506 (unless (cl-sixth bounds)
8507 (let ((pos (+ (cl-first bounds) (cl-fourth bounds)))
8508 (markup "[ ] "))
8509 (if (< pos (point))
8510 (save-excursion
8511 (goto-char pos)
8512 (insert markup))
8513 (goto-char pos)
8514 (insert markup))
8515 (syntax-propertize (+ (cl-second bounds) 4))
8517 (unless (save-excursion
8518 (back-to-indentation)
8519 (or (markdown-list-item-at-point-p)
8520 (markdown-heading-at-point)
8521 (markdown-in-comment-p)
8522 (markdown-code-block-at-point-p)))
8523 (let ((pos (save-excursion
8524 (back-to-indentation)
8525 (point)))
8526 (markup (concat (or (save-excursion
8527 (beginning-of-line 0)
8528 (cl-fifth (markdown-cur-list-item-bounds)))
8529 markdown-unordered-list-item-prefix)
8530 "[ ] ")))
8531 (if (< pos (point))
8532 (save-excursion
8533 (goto-char pos)
8534 (insert markup))
8535 (goto-char pos)
8536 (insert markup))
8537 (syntax-propertize (line-end-position))
8538 t)))))
8540 (defun markdown-toggle-gfm-checkbox ()
8541 "Toggle GFM checkbox at point.
8542 Returns the resulting status as a string, either \"[x]\" or \"[ ]\".
8543 Returns nil if there is no task list item at the point."
8544 (interactive)
8545 (save-match-data
8546 (save-excursion
8547 (let ((bounds (markdown-cur-list-item-bounds)))
8548 (when bounds
8549 ;; Move to beginning of task list item
8550 (goto-char (cl-first bounds))
8551 ;; Advance to column of first non-whitespace after marker
8552 (forward-char (cl-fourth bounds))
8553 (cond ((looking-at "\\[ \\]")
8554 (replace-match
8555 (if markdown-gfm-uppercase-checkbox "[X]" "[x]")
8556 nil t)
8557 (match-string-no-properties 0))
8558 ((looking-at "\\[[xX]\\]")
8559 (replace-match "[ ]" nil t)
8560 (match-string-no-properties 0))))))))
8562 (defun markdown-toggle-gfm-checkbox-button (button)
8563 "Toggle GFM checkbox BUTTON on click."
8564 (save-match-data
8565 (save-excursion
8566 (goto-char (button-start button))
8567 (markdown-toggle-gfm-checkbox))))
8569 (defun markdown-make-gfm-checkboxes-buttons (start end)
8570 "Make GFM checkboxes buttons in region between START and END."
8571 (save-excursion
8572 (goto-char start)
8573 (let ((case-fold-search t))
8574 (save-excursion
8575 (while (re-search-forward markdown-regex-gfm-checkbox end t)
8576 (make-button (match-beginning 1) (match-end 1)
8577 :type 'markdown-gfm-checkbox-button))))))
8579 ;; Called when any modification is made to buffer text.
8580 (defun markdown-gfm-checkbox-after-change-function (beg end _)
8581 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
8582 BEG and END are the limits of scanned region."
8583 (save-excursion
8584 (save-match-data
8585 ;; Rescan between start of line from `beg' and start of line after `end'.
8586 (markdown-make-gfm-checkboxes-buttons
8587 (progn (goto-char beg) (beginning-of-line) (point))
8588 (progn (goto-char end) (forward-line 1) (point))))))
8590 (defun markdown-remove-gfm-checkbox-overlays ()
8591 "Remove all GFM checkbox overlays in buffer."
8592 (save-excursion
8593 (save-restriction
8594 (widen)
8595 (remove-overlays nil nil 'face 'markdown-gfm-checkbox-face))))
8598 ;;; Display inline image ======================================================
8600 (defvar-local markdown-inline-image-overlays nil)
8602 (defun markdown-remove-inline-images ()
8603 "Remove inline image overlays from image links in the buffer.
8604 This can be toggled with `markdown-toggle-inline-images'
8605 or \\[markdown-toggle-inline-images]."
8606 (interactive)
8607 (mapc #'delete-overlay markdown-inline-image-overlays)
8608 (setq markdown-inline-image-overlays nil))
8610 (defcustom markdown-display-remote-images nil
8611 "If non-nil, download and display remote images.
8612 See also `markdown-inline-image-overlays'.
8614 Only image URLs specified with a protocol listed in
8615 `markdown-remote-image-protocols' are displayed."
8616 :group 'markdown
8617 :type 'boolean)
8619 (defcustom markdown-remote-image-protocols '("https")
8620 "List of protocols to use to download remote images.
8621 See also `markdown-display-remote-images'."
8622 :group 'markdown
8623 :type '(repeat string))
8625 (defvar markdown--remote-image-cache
8626 (make-hash-table :test 'equal)
8627 "A map from URLs to image paths.")
8629 (defun markdown--get-remote-image (url)
8630 "Retrieve the image path for a given URL."
8631 (or (gethash url markdown--remote-image-cache)
8632 (let ((dl-path (make-temp-file "markdown-mode--image")))
8633 (require 'url)
8634 (url-copy-file url dl-path t)
8635 (puthash url dl-path markdown--remote-image-cache))))
8637 (defun markdown-display-inline-images ()
8638 "Add inline image overlays to image links in the buffer.
8639 This can be toggled with `markdown-toggle-inline-images'
8640 or \\[markdown-toggle-inline-images]."
8641 (interactive)
8642 (unless (display-images-p)
8643 (error "Cannot show images"))
8644 (save-excursion
8645 (save-restriction
8646 (widen)
8647 (goto-char (point-min))
8648 (while (re-search-forward markdown-regex-link-inline nil t)
8649 (let* ((start (match-beginning 0))
8650 (imagep (match-beginning 1))
8651 (end (match-end 0))
8652 (file (match-string-no-properties 6)))
8653 (when (and imagep
8654 (not (zerop (length file))))
8655 (unless (file-exists-p file)
8656 (let* ((download-file (funcall markdown-translate-filename-function file))
8657 (valid-url (ignore-errors
8658 (member (downcase (url-type (url-generic-parse-url download-file)))
8659 markdown-remote-image-protocols))))
8660 (if (and markdown-display-remote-images valid-url)
8661 (setq file (markdown--get-remote-image download-file))
8662 (when (not valid-url)
8663 ;; strip query parameter
8664 (setq file (replace-regexp-in-string "?.+\\'" "" file))
8665 (unless (file-exists-p file)
8666 (setq file (url-unhex-string file)))))))
8667 (when (file-exists-p file)
8668 (let* ((abspath (if (file-name-absolute-p file)
8669 file
8670 (concat default-directory file)))
8671 (image
8672 (cond ((and markdown-max-image-size
8673 (image-type-available-p 'imagemagick))
8674 (create-image
8675 abspath 'imagemagick nil
8676 :max-width (car markdown-max-image-size)
8677 :max-height (cdr markdown-max-image-size)))
8678 (markdown-max-image-size
8679 (create-image abspath nil nil
8680 :max-width (car markdown-max-image-size)
8681 :max-height (cdr markdown-max-image-size)))
8682 (t (create-image abspath)))))
8683 (when image
8684 (let ((ov (make-overlay start end)))
8685 (overlay-put ov 'display image)
8686 (overlay-put ov 'face 'default)
8687 (push ov markdown-inline-image-overlays)))))))))))
8689 (defun markdown-toggle-inline-images ()
8690 "Toggle inline image overlays in the buffer."
8691 (interactive)
8692 (if markdown-inline-image-overlays
8693 (markdown-remove-inline-images)
8694 (markdown-display-inline-images)))
8697 ;;; GFM Code Block Fontification ==============================================
8699 (defcustom markdown-fontify-code-blocks-natively nil
8700 "When non-nil, fontify code in code blocks using the native major mode.
8701 This only works for fenced code blocks where the language is
8702 specified where we can automatically determine the appropriate
8703 mode to use. The language to mode mapping may be customized by
8704 setting the variable `markdown-code-lang-modes'."
8705 :group 'markdown
8706 :type 'boolean
8707 :safe #'booleanp
8708 :package-version '(markdown-mode . "2.3"))
8710 (defcustom markdown-fontify-code-block-default-mode nil
8711 "Default mode to use to fontify code blocks.
8712 This mode is used when automatic detection fails, such as for GFM
8713 code blocks with no language specified."
8714 :group 'markdown
8715 :type '(choice function (const :tag "None" nil))
8716 :package-version '(markdown-mode . "2.4"))
8718 (defun markdown-toggle-fontify-code-blocks-natively (&optional arg)
8719 "Toggle the native fontification of code blocks.
8720 With a prefix argument ARG, enable if ARG is positive,
8721 and disable otherwise."
8722 (interactive (list (or current-prefix-arg 'toggle)))
8723 (setq markdown-fontify-code-blocks-natively
8724 (if (eq arg 'toggle)
8725 (not markdown-fontify-code-blocks-natively)
8726 (> (prefix-numeric-value arg) 0)))
8727 (if markdown-fontify-code-blocks-natively
8728 (message "markdown-mode native code block fontification enabled")
8729 (message "markdown-mode native code block fontification disabled"))
8730 (markdown-reload-extensions))
8732 ;; This is based on `org-src-lang-modes' from org-src.el
8733 (defcustom markdown-code-lang-modes
8734 '(("ocaml" . tuareg-mode) ("elisp" . emacs-lisp-mode) ("ditaa" . artist-mode)
8735 ("asymptote" . asy-mode) ("dot" . fundamental-mode) ("sqlite" . sql-mode)
8736 ("calc" . fundamental-mode) ("C" . c-mode) ("cpp" . c++-mode)
8737 ("C++" . c++-mode) ("screen" . shell-script-mode) ("shell" . sh-mode)
8738 ("bash" . sh-mode))
8739 "Alist mapping languages to their major mode.
8740 The key is the language name, the value is the major mode. For
8741 many languages this is simple, but for language where this is not
8742 the case, this variable provides a way to simplify things on the
8743 user side. For example, there is no ocaml-mode in Emacs, but the
8744 mode to use is `tuareg-mode'."
8745 :group 'markdown
8746 :type '(repeat
8747 (cons
8748 (string "Language name")
8749 (symbol "Major mode")))
8750 :package-version '(markdown-mode . "2.3"))
8752 (defun markdown-get-lang-mode (lang)
8753 "Return major mode that should be used for LANG.
8754 LANG is a string, and the returned major mode is a symbol."
8755 (cl-find-if
8756 'fboundp
8757 (list (cdr (assoc lang markdown-code-lang-modes))
8758 (cdr (assoc (downcase lang) markdown-code-lang-modes))
8759 (intern (concat lang "-mode"))
8760 (intern (concat (downcase lang) "-mode")))))
8762 (defun markdown-fontify-code-blocks-generic (matcher last)
8763 "Add text properties to next code block from point to LAST.
8764 Use matching function MATCHER."
8765 (when (funcall matcher last)
8766 (save-excursion
8767 (save-match-data
8768 (let* ((start (match-beginning 0))
8769 (end (match-end 0))
8770 ;; Find positions outside opening and closing backquotes.
8771 (bol-prev (progn (goto-char start)
8772 (if (bolp) (line-beginning-position 0) (line-beginning-position))))
8773 (eol-next (progn (goto-char end)
8774 (if (bolp) (line-beginning-position 2) (line-beginning-position 3))))
8775 lang)
8776 (if (and markdown-fontify-code-blocks-natively
8777 (or (setq lang (markdown-code-block-lang))
8778 markdown-fontify-code-block-default-mode))
8779 (markdown-fontify-code-block-natively lang start end)
8780 (add-text-properties start end '(face markdown-pre-face)))
8781 ;; Set background for block as well as opening and closing lines.
8782 (font-lock-append-text-property
8783 bol-prev eol-next 'face 'markdown-code-face)
8784 ;; Set invisible property for lines before and after, including newline.
8785 (add-text-properties bol-prev start '(invisible markdown-markup))
8786 (add-text-properties end eol-next '(invisible markdown-markup)))))
8789 (defun markdown-fontify-gfm-code-blocks (last)
8790 "Add text properties to next GFM code block from point to LAST."
8791 (markdown-fontify-code-blocks-generic 'markdown-match-gfm-code-blocks last))
8793 (defun markdown-fontify-fenced-code-blocks (last)
8794 "Add text properties to next tilde fenced code block from point to LAST."
8795 (markdown-fontify-code-blocks-generic 'markdown-match-fenced-code-blocks last))
8797 ;; Based on `org-src-font-lock-fontify-block' from org-src.el.
8798 (defun markdown-fontify-code-block-natively (lang start end)
8799 "Fontify given GFM or fenced code block.
8800 This function is called by Emacs for automatic fontification when
8801 `markdown-fontify-code-blocks-natively' is non-nil. LANG is the
8802 language used in the block. START and END specify the block
8803 position."
8804 (let ((lang-mode (if lang (markdown-get-lang-mode lang)
8805 markdown-fontify-code-block-default-mode)))
8806 (when (fboundp lang-mode)
8807 (let ((string (buffer-substring-no-properties start end))
8808 (modified (buffer-modified-p))
8809 (markdown-buffer (current-buffer)) pos next)
8810 (remove-text-properties start end '(face nil))
8811 (with-current-buffer
8812 (get-buffer-create
8813 (concat " markdown-code-fontification:" (symbol-name lang-mode)))
8814 ;; Make sure that modification hooks are not inhibited in
8815 ;; the org-src-fontification buffer in case we're called
8816 ;; from `jit-lock-function' (Bug#25132).
8817 (let ((inhibit-modification-hooks nil))
8818 (delete-region (point-min) (point-max))
8819 (insert string " ")) ;; so there's a final property change
8820 (unless (eq major-mode lang-mode) (funcall lang-mode))
8821 (font-lock-ensure)
8822 (setq pos (point-min))
8823 (while (setq next (next-single-property-change pos 'face))
8824 (let ((val (get-text-property pos 'face)))
8825 (when val
8826 (put-text-property
8827 (+ start (1- pos)) (1- (+ start next)) 'face
8828 val markdown-buffer)))
8829 (setq pos next)))
8830 (add-text-properties
8831 start end
8832 '(font-lock-fontified t fontified t font-lock-multiline t))
8833 (set-buffer-modified-p modified)))))
8835 (require 'edit-indirect nil t)
8836 (defvar edit-indirect-guess-mode-function)
8837 (defvar edit-indirect-after-commit-functions)
8839 (defun markdown--edit-indirect-after-commit-function (beg end)
8840 "Corrective logic run on code block content from lines BEG to END.
8841 Restores code block indentation from BEG to END, and ensures trailing newlines
8842 at the END of code blocks."
8843 ;; ensure trailing newlines
8844 (goto-char end)
8845 (unless (eq (char-before) ?\n)
8846 (insert "\n"))
8847 ;; restore code block indentation
8848 (goto-char (- beg 1))
8849 (let ((block-indentation (current-indentation)))
8850 (when (> block-indentation 0)
8851 (indent-rigidly beg end block-indentation)))
8852 (font-lock-ensure))
8854 (defun markdown-edit-code-block ()
8855 "Edit Markdown code block in an indirect buffer."
8856 (interactive)
8857 (save-excursion
8858 (if (fboundp 'edit-indirect-region)
8859 (let* ((bounds (markdown-get-enclosing-fenced-block-construct))
8860 (begin (and bounds (not (null (nth 0 bounds))) (goto-char (nth 0 bounds)) (line-beginning-position 2)))
8861 (end (and bounds(not (null (nth 1 bounds))) (goto-char (nth 1 bounds)) (line-beginning-position 1))))
8862 (if (and begin end)
8863 (let* ((indentation (and (goto-char (nth 0 bounds)) (current-indentation)))
8864 (lang (markdown-code-block-lang))
8865 (mode (or (and lang (markdown-get-lang-mode lang))
8866 markdown-edit-code-block-default-mode))
8867 (edit-indirect-guess-mode-function
8868 (lambda (_parent-buffer _beg _end)
8869 (funcall mode)))
8870 (indirect-buf (edit-indirect-region begin end 'display-buffer)))
8871 ;; reset `sh-shell' when indirect buffer
8872 (when (and (not (member system-type '(ms-dos windows-nt)))
8873 (member mode '(shell-script-mode sh-mode))
8874 (member lang (append
8875 (mapcar (lambda (e) (symbol-name (car e)))
8876 sh-ancestor-alist)
8877 '("csh" "rc" "sh"))))
8878 (with-current-buffer indirect-buf
8879 (sh-set-shell lang)))
8880 (when (> indentation 0) ;; un-indent in edit-indirect buffer
8881 (with-current-buffer indirect-buf
8882 (indent-rigidly (point-min) (point-max) (- indentation)))))
8883 (user-error "Not inside a GFM or tilde fenced code block")))
8884 (when (y-or-n-p "Package edit-indirect needed to edit code blocks. Install it now? ")
8885 (progn (package-refresh-contents)
8886 (package-install 'edit-indirect)
8887 (markdown-edit-code-block))))))
8890 ;;; Table Editing =============================================================
8892 ;; These functions were originally adapted from `org-table.el'.
8894 ;; General helper functions
8896 (defmacro markdown--with-gensyms (symbols &rest body)
8897 (declare (debug (sexp body)) (indent 1))
8898 `(let ,(mapcar (lambda (s)
8899 `(,s (make-symbol (concat "--" (symbol-name ',s)))))
8900 symbols)
8901 ,@body))
8903 (defun markdown--split-string (string &optional separators)
8904 "Splits STRING into substrings at SEPARATORS.
8905 SEPARATORS is a regular expression. If nil it defaults to
8906 `split-string-default-separators'. This version returns no empty
8907 strings if there are matches at the beginning and end of string."
8908 (let ((start 0) notfirst list)
8909 (while (and (string-match
8910 (or separators split-string-default-separators)
8911 string
8912 (if (and notfirst
8913 (= start (match-beginning 0))
8914 (< start (length string)))
8915 (1+ start) start))
8916 (< (match-beginning 0) (length string)))
8917 (setq notfirst t)
8918 (or (eq (match-beginning 0) 0)
8919 (and (eq (match-beginning 0) (match-end 0))
8920 (eq (match-beginning 0) start))
8921 (push (substring string start (match-beginning 0)) list))
8922 (setq start (match-end 0)))
8923 (or (eq start (length string))
8924 (push (substring string start) list))
8925 (nreverse list)))
8927 (defun markdown--string-width (s)
8928 "Return width of string S.
8929 This version ignores characters with invisibility property
8930 `markdown-markup'."
8931 (let (b)
8932 (when (or (eq t buffer-invisibility-spec)
8933 (member 'markdown-markup buffer-invisibility-spec))
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))))))))
8942 (string-width s))
8944 (defun markdown--remove-invisible-markup (s)
8945 "Remove Markdown markup from string S.
8946 This version removes characters with invisibility property
8947 `markdown-markup'."
8948 (let (b)
8949 (while (setq b (text-property-any
8950 0 (length s)
8951 'invisible 'markdown-markup s))
8952 (setq s (concat
8953 (substring s 0 b)
8954 (substring s (or (next-single-property-change
8955 b 'invisible s)
8956 (length s)))))))
8959 ;; Functions for maintaining tables
8961 (defvar markdown-table-at-point-p-function #'markdown--table-at-point-p
8962 "Function to decide if point is inside a table.
8964 The indirection serves to differentiate between standard markdown
8965 tables and gfm tables which are less strict about the markup.")
8967 (defconst markdown-table-line-regexp "^[ \t]*|"
8968 "Regexp matching any line inside a table.")
8970 (defconst markdown-table-hline-regexp "^[ \t]*|[-:]"
8971 "Regexp matching hline inside a table.")
8973 (defconst markdown-table-dline-regexp "^[ \t]*|[^-:]"
8974 "Regexp matching dline inside a table.")
8976 (defun markdown-table-at-point-p ()
8977 "Return non-nil when point is inside a table."
8978 (funcall markdown-table-at-point-p-function))
8980 (defun markdown--table-at-point-p ()
8981 "Return non-nil when point is inside a table."
8982 (save-excursion
8983 (beginning-of-line)
8984 (and (looking-at-p markdown-table-line-regexp)
8985 (not (markdown-code-block-at-point-p)))))
8987 (defconst gfm-table-line-regexp "^.?*|"
8988 "Regexp matching any line inside a table.")
8990 (defconst gfm-table-hline-regexp "^-+\\(|-\\)+"
8991 "Regexp matching hline inside a table.")
8993 ;; GFM simplified tables syntax is as follows:
8994 ;; - A header line for the column names, this is any text
8995 ;; separated by `|'.
8996 ;; - Followed by a string -|-|- ..., the number of dashes is optional
8997 ;; but must be higher than 1. The number of separators should match
8998 ;; the number of columns.
8999 ;; - Followed by the rows of data, which has the same format as the
9000 ;; header line.
9001 ;; Example:
9003 ;; foo | bar
9004 ;; ------|---------
9005 ;; bar | baz
9006 ;; bar | baz
9007 (defun gfm--table-at-point-p ()
9008 "Return non-nil when point is inside a gfm-compatible table."
9009 (or (markdown--table-at-point-p)
9010 (save-excursion
9011 (beginning-of-line)
9012 (when (looking-at-p gfm-table-line-regexp)
9013 ;; we might be at the first line of the table, check if the
9014 ;; line below is the hline
9015 (or (save-excursion
9016 (forward-line 1)
9017 (looking-at-p gfm-table-hline-regexp))
9018 ;; go up to find the header
9019 (catch 'done
9020 (while (looking-at-p gfm-table-line-regexp)
9021 (cond
9022 ((looking-at-p gfm-table-hline-regexp)
9023 (throw 'done t))
9024 ((bobp)
9025 (throw 'done nil)))
9026 (forward-line -1))
9027 nil))))))
9029 (defun markdown-table-hline-at-point-p ()
9030 "Return non-nil when point is on a hline in a table.
9031 This function assumes point is on a table."
9032 (save-excursion
9033 (beginning-of-line)
9034 (looking-at-p markdown-table-hline-regexp)))
9036 (defun markdown-table-begin ()
9037 "Find the beginning of the table and return its position.
9038 This function assumes point is on a table."
9039 (save-excursion
9040 (while (and (not (bobp))
9041 (markdown-table-at-point-p))
9042 (forward-line -1))
9043 (unless (or (eobp)
9044 (markdown-table-at-point-p))
9045 (forward-line 1))
9046 (point)))
9048 (defun markdown-table-end ()
9049 "Find the end of the table and return its position.
9050 This function assumes point is on a table."
9051 (save-excursion
9052 (while (and (not (eobp))
9053 (markdown-table-at-point-p))
9054 (forward-line 1))
9055 (point)))
9057 (defun markdown-table-get-dline ()
9058 "Return index of the table data line at point.
9059 This function assumes point is on a table."
9060 (let ((pos (point)) (end (markdown-table-end)) (cnt 0))
9061 (save-excursion
9062 (goto-char (markdown-table-begin))
9063 (while (and (re-search-forward
9064 markdown-table-dline-regexp end t)
9065 (setq cnt (1+ cnt))
9066 (< (line-end-position) pos))))
9067 cnt))
9069 (defun markdown--thing-at-wiki-link (pos)
9070 (when markdown-enable-wiki-links
9071 (save-excursion
9072 (save-match-data
9073 (goto-char pos)
9074 (thing-at-point-looking-at markdown-regex-wiki-link)))))
9076 (defun markdown-table-get-column ()
9077 "Return table column at point.
9078 This function assumes point is on a table."
9079 (let ((pos (point)) (cnt 0))
9080 (save-excursion
9081 (beginning-of-line)
9082 (while (search-forward "|" pos t)
9083 (when (and (not (looking-back "\\\\|" (line-beginning-position)))
9084 (not (markdown--thing-at-wiki-link (match-beginning 0))))
9085 (setq cnt (1+ cnt)))))
9086 cnt))
9088 (defun markdown-table-get-cell (&optional n)
9089 "Return the content of the cell in column N of current row.
9090 N defaults to column at point. This function assumes point is on
9091 a table."
9092 (and n (markdown-table-goto-column n))
9093 (skip-chars-backward "^|\n") (backward-char 1)
9094 (if (looking-at "|[^|\r\n]*")
9095 (let* ((pos (match-beginning 0))
9096 (val (buffer-substring (1+ pos) (match-end 0))))
9097 (goto-char (min (line-end-position) (+ 2 pos)))
9098 ;; Trim whitespaces
9099 (setq val (replace-regexp-in-string "\\`[ \t]+" "" val)
9100 val (replace-regexp-in-string "[ \t]+\\'" "" val)))
9101 (forward-char 1) ""))
9103 (defun markdown-table-goto-dline (n)
9104 "Go to the Nth data line in the table at point.
9105 Return t when the line exists, nil otherwise. This function
9106 assumes point is on a table."
9107 (goto-char (markdown-table-begin))
9108 (let ((end (markdown-table-end)) (cnt 0))
9109 (while (and (re-search-forward
9110 markdown-table-dline-regexp end t)
9111 (< (setq cnt (1+ cnt)) n)))
9112 (= cnt n)))
9114 (defun markdown-table-goto-column (n &optional on-delim)
9115 "Go to the Nth column in the table line at point.
9116 With optional argument ON-DELIM, stop with point before the left
9117 delimiter of the cell. If there are less than N cells, just go
9118 beyond the last delimiter. This function assumes point is on a
9119 table."
9120 (beginning-of-line 1)
9121 (when (> n 0)
9122 (while (and (> n 0) (search-forward "|" (line-end-position) t))
9123 (when (and (not (looking-back "\\\\|" (line-beginning-position)))
9124 (not (markdown--thing-at-wiki-link (match-beginning 0))))
9125 (cl-decf n)))
9126 (if on-delim
9127 (backward-char 1)
9128 (when (looking-at " ") (forward-char 1)))))
9130 (defmacro markdown-table-save-cell (&rest body)
9131 "Save cell at point, execute BODY and restore cell.
9132 This function assumes point is on a table."
9133 (declare (debug (body)))
9134 (markdown--with-gensyms (line column)
9135 `(let ((,line (copy-marker (line-beginning-position)))
9136 (,column (markdown-table-get-column)))
9137 (unwind-protect
9138 (progn ,@body)
9139 (goto-char ,line)
9140 (markdown-table-goto-column ,column)
9141 (set-marker ,line nil)))))
9143 (defun markdown-table-blank-line (s)
9144 "Convert a table line S into a line with blank cells."
9145 (if (string-match "^[ \t]*|-" s)
9146 (setq s (mapconcat
9147 (lambda (x) (if (member x '(?| ?+)) "|" " "))
9148 s ""))
9149 (with-temp-buffer
9150 (insert s)
9151 (goto-char (point-min))
9152 (when (re-search-forward "|" nil t)
9153 (let ((cur (point))
9154 ret)
9155 (while (re-search-forward "|" nil t)
9156 (when (and (not (eql (char-before (match-beginning 0)) ?\\))
9157 (not (markdown--thing-at-wiki-link (match-beginning 0))))
9158 (push (make-string (- (match-beginning 0) cur) ? ) ret)
9159 (setq cur (match-end 0))))
9160 (format "|%s|" (string-join (nreverse ret) "|")))))))
9162 (defun markdown-table-colfmt (fmtspec)
9163 "Process column alignment specifier FMTSPEC for tables."
9164 (when (stringp fmtspec)
9165 (mapcar (lambda (x)
9166 (cond ((string-match-p "^:.*:$" x) 'c)
9167 ((string-match-p "^:" x) 'l)
9168 ((string-match-p ":$" x) 'r)
9169 (t 'd)))
9170 (markdown--split-string fmtspec "\\s-*|\\s-*"))))
9172 (defun markdown--first-column-p (bar-pos)
9173 (save-excursion
9174 (save-match-data
9175 (goto-char bar-pos)
9176 (looking-back "^\\s-*" (line-beginning-position)))))
9178 (defun markdown--table-line-to-columns (line)
9179 (with-temp-buffer
9180 (insert line)
9181 (goto-char (point-min))
9182 (let ((cur (point))
9183 ret)
9184 (while (re-search-forward "\\s-*\\(|\\)\\s-*" nil t)
9185 (if (markdown--first-column-p (match-beginning 1))
9186 (setq cur (match-end 0))
9187 (cond ((eql (char-before (match-beginning 1)) ?\\)
9188 ;; keep spaces
9189 (goto-char (match-end 1)))
9190 ((markdown--thing-at-wiki-link (match-beginning 1))) ;; do nothing
9192 (push (buffer-substring-no-properties cur (match-beginning 0)) ret)
9193 (setq cur (match-end 0))))))
9194 (when (< cur (length line))
9195 (push (buffer-substring-no-properties cur (point-max)) ret))
9196 (nreverse ret))))
9198 (defun markdown-table-align ()
9199 "Align table at point.
9200 This function assumes point is on a table."
9201 (interactive)
9202 (let ((begin (markdown-table-begin))
9203 (end (copy-marker (markdown-table-end))))
9204 (markdown-table-save-cell
9205 (goto-char begin)
9206 (let* (fmtspec
9207 ;; Store table indent
9208 (indent (progn (looking-at "[ \t]*") (match-string 0)))
9209 ;; Split table in lines and save column format specifier
9210 (lines (mapcar (lambda (l)
9211 (if (string-match-p "\\`[ \t]*|[ \t]*[-:]" l)
9212 (progn (setq fmtspec (or fmtspec l)) nil) l))
9213 (markdown--split-string (buffer-substring begin end) "\n")))
9214 ;; Split lines in cells
9215 (cells (mapcar (lambda (l) (markdown--table-line-to-columns l))
9216 (remq nil lines)))
9217 ;; Calculate maximum number of cells in a line
9218 (maxcells (if cells
9219 (apply #'max (mapcar #'length cells))
9220 (user-error "Empty table")))
9221 ;; Empty cells to fill short lines
9222 (emptycells (make-list maxcells ""))
9223 maxwidths)
9224 ;; Calculate maximum width for each column
9225 (dotimes (i maxcells)
9226 (let ((column (mapcar (lambda (x) (or (nth i x) "")) cells)))
9227 (push (apply #'max 1 (mapcar #'markdown--string-width column))
9228 maxwidths)))
9229 (setq maxwidths (nreverse maxwidths))
9230 ;; Process column format specifier
9231 (setq fmtspec (markdown-table-colfmt fmtspec))
9232 ;; Compute formats needed for output of table lines
9233 (let ((hfmt (concat indent "|"))
9234 (rfmt (concat indent "|"))
9235 hfmt1 rfmt1 fmt)
9236 (dolist (width maxwidths (setq hfmt (concat (substring hfmt 0 -1) "|")))
9237 (setq fmt (pop fmtspec))
9238 (cond ((equal fmt 'l) (setq hfmt1 ":%s-|" rfmt1 " %%-%ds |"))
9239 ((equal fmt 'r) (setq hfmt1 "-%s:|" rfmt1 " %%%ds |"))
9240 ((equal fmt 'c) (setq hfmt1 ":%s:|" rfmt1 " %%-%ds |"))
9241 (t (setq hfmt1 "-%s-|" rfmt1 " %%-%ds |")))
9242 (setq rfmt (concat rfmt (format rfmt1 width)))
9243 (setq hfmt (concat hfmt (format hfmt1 (make-string width ?-)))))
9244 ;; Replace modified lines only
9245 (dolist (line lines)
9246 (let ((line (if line
9247 (apply #'format rfmt (append (pop cells) emptycells))
9248 hfmt))
9249 (previous (buffer-substring (point) (line-end-position))))
9250 (if (equal previous line)
9251 (forward-line)
9252 (insert line "\n")
9253 (delete-region (point) (line-beginning-position 2))))))
9254 (set-marker end nil)))))
9256 (defun markdown-table-insert-row (&optional arg)
9257 "Insert a new row above the row at point into the table.
9258 With optional argument ARG, insert below the current row."
9259 (interactive "P")
9260 (unless (markdown-table-at-point-p)
9261 (user-error "Not at a table"))
9262 (let* ((line (buffer-substring
9263 (line-beginning-position) (line-end-position)))
9264 (new (markdown-table-blank-line line)))
9265 (beginning-of-line (if arg 2 1))
9266 (unless (bolp) (insert "\n"))
9267 (insert-before-markers new "\n")
9268 (beginning-of-line 0)
9269 (re-search-forward "| ?" (line-end-position) t)))
9271 (defun markdown-table-delete-row ()
9272 "Delete row or horizontal line at point from the table."
9273 (interactive)
9274 (unless (markdown-table-at-point-p)
9275 (user-error "Not at a table"))
9276 (let ((col (current-column)))
9277 (kill-region (line-beginning-position)
9278 (min (1+ (line-end-position)) (point-max)))
9279 (unless (markdown-table-at-point-p) (beginning-of-line 0))
9280 (move-to-column col)))
9282 (defun markdown-table-move-row (&optional up)
9283 "Move table line at point down.
9284 With optional argument UP, move it up."
9285 (interactive "P")
9286 (unless (markdown-table-at-point-p)
9287 (user-error "Not at a table"))
9288 (let* ((col (current-column)) (pos (point))
9289 (tonew (if up 0 2)) txt)
9290 (beginning-of-line tonew)
9291 (unless (markdown-table-at-point-p)
9292 (goto-char pos) (user-error "Cannot move row further"))
9293 (goto-char pos) (beginning-of-line 1) (setq pos (point))
9294 (setq txt (buffer-substring (point) (1+ (line-end-position))))
9295 (delete-region (point) (1+ (line-end-position)))
9296 (beginning-of-line tonew)
9297 (insert txt) (beginning-of-line 0)
9298 (move-to-column col)))
9300 (defun markdown-table-move-row-up ()
9301 "Move table row at point up."
9302 (interactive)
9303 (markdown-table-move-row 'up))
9305 (defun markdown-table-move-row-down ()
9306 "Move table row at point down."
9307 (interactive)
9308 (markdown-table-move-row nil))
9310 (defun markdown-table-insert-column ()
9311 "Insert a new table column."
9312 (interactive)
9313 (unless (markdown-table-at-point-p)
9314 (user-error "Not at a table"))
9315 (let* ((col (max 1 (markdown-table-get-column)))
9316 (begin (markdown-table-begin))
9317 (end (copy-marker (markdown-table-end))))
9318 (markdown-table-save-cell
9319 (goto-char begin)
9320 (while (< (point) end)
9321 (markdown-table-goto-column col t)
9322 (if (markdown-table-hline-at-point-p)
9323 (insert "|---")
9324 (insert "| "))
9325 (forward-line)))
9326 (set-marker end nil)
9327 (when markdown-table-align-p
9328 (markdown-table-align))))
9330 (defun markdown-table-delete-column ()
9331 "Delete column at point from table."
9332 (interactive)
9333 (unless (markdown-table-at-point-p)
9334 (user-error "Not at a table"))
9335 (let ((col (markdown-table-get-column))
9336 (begin (markdown-table-begin))
9337 (end (copy-marker (markdown-table-end))))
9338 (markdown-table-save-cell
9339 (goto-char begin)
9340 (while (< (point) end)
9341 (markdown-table-goto-column col t)
9342 (and (looking-at "|\\(?:\\\\|\\|[^|\n]\\)+|")
9343 (replace-match "|"))
9344 (forward-line)))
9345 (set-marker end nil)
9346 (markdown-table-goto-column (max 1 (1- col)))
9347 (when markdown-table-align-p
9348 (markdown-table-align))))
9350 (defun markdown-table-move-column (&optional left)
9351 "Move table column at point to the right.
9352 With optional argument LEFT, move it to the left."
9353 (interactive "P")
9354 (unless (markdown-table-at-point-p)
9355 (user-error "Not at a table"))
9356 (let* ((col (markdown-table-get-column))
9357 (col1 (if left (1- col) col))
9358 (colpos (if left (1- col) (1+ col)))
9359 (begin (markdown-table-begin))
9360 (end (copy-marker (markdown-table-end))))
9361 (when (and left (= col 1))
9362 (user-error "Cannot move column further left"))
9363 (when (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9364 (user-error "Cannot move column further right"))
9365 (markdown-table-save-cell
9366 (goto-char begin)
9367 (while (< (point) end)
9368 (markdown-table-goto-column col1 t)
9369 (when (looking-at "|\\(\\(?:\\\\|\\|[^|\n]\\|\\)+\\)|\\(\\(?:\\\\|\\|[^|\n]\\|\\)+\\)|")
9370 (replace-match "|\\2|\\1|"))
9371 (forward-line)))
9372 (set-marker end nil)
9373 (markdown-table-goto-column colpos)
9374 (when markdown-table-align-p
9375 (markdown-table-align))))
9377 (defun markdown-table-move-column-left ()
9378 "Move table column at point to the left."
9379 (interactive)
9380 (markdown-table-move-column 'left))
9382 (defun markdown-table-move-column-right ()
9383 "Move table column at point to the right."
9384 (interactive)
9385 (markdown-table-move-column nil))
9387 (defun markdown-table-next-row ()
9388 "Go to the next row (same column) in the table.
9389 Create new table lines if required."
9390 (interactive)
9391 (unless (markdown-table-at-point-p)
9392 (user-error "Not at a table"))
9393 (if (or (looking-at "[ \t]*$")
9394 (save-excursion (skip-chars-backward " \t") (bolp)))
9395 (newline)
9396 (when markdown-table-align-p
9397 (markdown-table-align))
9398 (let ((col (markdown-table-get-column)))
9399 (beginning-of-line 2)
9400 (if (or (not (markdown-table-at-point-p))
9401 (markdown-table-hline-at-point-p))
9402 (progn
9403 (beginning-of-line 0)
9404 (markdown-table-insert-row 'below)))
9405 (markdown-table-goto-column col)
9406 (skip-chars-backward "^|\n\r")
9407 (when (looking-at " ") (forward-char 1)))))
9409 (defun markdown-table-forward-cell ()
9410 "Go to the next cell in the table.
9411 Create new table lines if required."
9412 (interactive)
9413 (unless (markdown-table-at-point-p)
9414 (user-error "Not at a table"))
9415 (when markdown-table-align-p
9416 (markdown-table-align))
9417 (let ((end (markdown-table-end)))
9418 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9419 (condition-case nil
9420 (progn
9421 (re-search-forward "\\(?:^\\|[^\\]\\)|" end)
9422 (when (looking-at "[ \t]*$")
9423 (re-search-forward "\\(?:^\\|[^\\]:\\)|" end))
9424 (when (and (looking-at "[-:]")
9425 (re-search-forward "^\\(?:[ \t]*\\|[^\\]\\)|\\([^-:]\\)" end t))
9426 (goto-char (match-beginning 1)))
9427 (if (looking-at "[-:]")
9428 (progn
9429 (beginning-of-line 0)
9430 (markdown-table-insert-row 'below))
9431 (when (looking-at " ") (forward-char 1))))
9432 (error (markdown-table-insert-row 'below)))))
9434 (defun markdown-table-backward-cell ()
9435 "Go to the previous cell in the table."
9436 (interactive)
9437 (unless (markdown-table-at-point-p)
9438 (user-error "Not at a table"))
9439 (when markdown-table-align-p
9440 (markdown-table-align))
9441 (when (markdown-table-hline-at-point-p) (beginning-of-line 1))
9442 (condition-case nil
9443 (progn
9444 (re-search-backward "\\(?:^\\|[^\\]\\)|" (markdown-table-begin))
9445 ;; When this function is called while in the first cell in a
9446 ;; table, the point will now be at the beginning of a line. In
9447 ;; this case, we need to move past one additional table
9448 ;; boundary, the end of the table on the previous line.
9449 (when (= (point) (line-beginning-position))
9450 (re-search-backward "\\(?:^\\|[^\\]\\)|" (markdown-table-begin)))
9451 (re-search-backward "\\(?:^\\|[^\\]\\)|" (markdown-table-begin)))
9452 (error (user-error "Cannot move to previous table cell")))
9453 (when (looking-at "\\(?:^\\|[^\\]\\)| ?") (goto-char (match-end 0)))
9455 ;; This may have dropped point on the hline.
9456 (when (markdown-table-hline-at-point-p)
9457 (markdown-table-backward-cell)))
9459 (defun markdown-table-transpose ()
9460 "Transpose table at point.
9461 Horizontal separator lines will be eliminated."
9462 (interactive)
9463 (unless (markdown-table-at-point-p)
9464 (user-error "Not at a table"))
9465 (let* ((table (buffer-substring-no-properties
9466 (markdown-table-begin) (markdown-table-end)))
9467 ;; Convert table to Lisp structure
9468 (table (delq nil
9469 (mapcar
9470 (lambda (x)
9471 (unless (string-match-p
9472 markdown-table-hline-regexp x)
9473 (markdown--table-line-to-columns x)))
9474 (markdown--split-string table "[ \t]*\n[ \t]*"))))
9475 (dline_old (markdown-table-get-dline))
9476 (col_old (markdown-table-get-column))
9477 (contents (mapcar (lambda (_)
9478 (let ((tp table))
9479 (mapcar
9480 (lambda (_)
9481 (prog1
9482 (pop (car tp))
9483 (setq tp (cdr tp))))
9484 table)))
9485 (car table))))
9486 (goto-char (markdown-table-begin))
9487 (save-excursion
9488 (re-search-forward "|") (backward-char)
9489 (delete-region (point) (markdown-table-end))
9490 (insert (mapconcat
9491 (lambda(x)
9492 (concat "| " (mapconcat 'identity x " | " ) " |\n"))
9493 contents "")))
9494 (markdown-table-goto-dline col_old)
9495 (markdown-table-goto-column dline_old))
9496 (when markdown-table-align-p
9497 (markdown-table-align)))
9499 (defun markdown-table-sort-lines (&optional sorting-type)
9500 "Sort table lines according to the column at point.
9502 The position of point indicates the column to be used for
9503 sorting, and the range of lines is the range between the nearest
9504 horizontal separator lines, or the entire table of no such lines
9505 exist. If point is before the first column, user will be prompted
9506 for the sorting column. If there is an active region, the mark
9507 specifies the first line and the sorting column, while point
9508 should be in the last line to be included into the sorting.
9510 The command then prompts for the sorting type which can be
9511 alphabetically or numerically. Sorting in reverse order is also
9512 possible.
9514 If SORTING-TYPE is specified when this function is called from a
9515 Lisp program, no prompting will take place. SORTING-TYPE must be
9516 a character, any of (?a ?A ?n ?N) where the capital letters
9517 indicate that sorting should be done in reverse order."
9518 (interactive)
9519 (unless (markdown-table-at-point-p)
9520 (user-error "Not at a table"))
9521 ;; Set sorting type and column used for sorting
9522 (let ((column (let ((c (markdown-table-get-column)))
9523 (cond ((> c 0) c)
9524 ((called-interactively-p 'any)
9525 (read-number "Use column N for sorting: "))
9526 (t 1))))
9527 (sorting-type
9528 (or sorting-type
9529 (progn
9530 ;; workaround #641
9531 ;; Emacs < 28 hides prompt message by another message. This erases it.
9532 (message "")
9533 (read-char-exclusive
9534 "Sort type: [a]lpha [n]umeric (A/N means reversed): ")))))
9535 (save-restriction
9536 ;; Narrow buffer to appropriate sorting area
9537 (if (region-active-p)
9538 (narrow-to-region
9539 (save-excursion
9540 (progn
9541 (goto-char (region-beginning)) (line-beginning-position)))
9542 (save-excursion
9543 (progn
9544 (goto-char (region-end)) (line-end-position))))
9545 (let ((start (markdown-table-begin))
9546 (end (markdown-table-end)))
9547 (narrow-to-region
9548 (save-excursion
9549 (if (re-search-backward
9550 markdown-table-hline-regexp start t)
9551 (line-beginning-position 2)
9552 start))
9553 (if (save-excursion (re-search-forward
9554 markdown-table-hline-regexp end t))
9555 (match-beginning 0)
9556 end))))
9557 ;; Determine arguments for `sort-subr'
9558 (let* ((extract-key-from-cell
9559 (cl-case sorting-type
9560 ((?a ?A) #'markdown--remove-invisible-markup) ;; #'identity)
9561 ((?n ?N) #'string-to-number)
9562 (t (user-error "Invalid sorting type: %c" sorting-type))))
9563 (predicate
9564 (cl-case sorting-type
9565 ((?n ?N) #'<)
9566 ((?a ?A) #'string<))))
9567 ;; Sort selected area
9568 (goto-char (point-min))
9569 (sort-subr (memq sorting-type '(?A ?N))
9570 (lambda ()
9571 (forward-line)
9572 (while (and (not (eobp))
9573 (not (looking-at
9574 markdown-table-dline-regexp)))
9575 (forward-line)))
9576 #'end-of-line
9577 (lambda ()
9578 (funcall extract-key-from-cell
9579 (markdown-table-get-cell column)))
9581 predicate)
9582 (goto-char (point-min))))))
9584 (defun markdown-table-convert-region (begin end &optional separator)
9585 "Convert region from BEGIN to END to table with SEPARATOR.
9587 If every line contains at least one TAB character, the function
9588 assumes that the material is tab separated (TSV). If every line
9589 contains a comma, comma-separated values (CSV) are assumed. If
9590 not, lines are split at whitespace into cells.
9592 You can use a prefix argument to force a specific separator:
9593 \\[universal-argument] once forces CSV, \\[universal-argument]
9594 twice forces TAB, and \\[universal-argument] three times will
9595 prompt for a regular expression to match the separator, and a
9596 numeric argument N indicates that at least N consecutive
9597 spaces, or alternatively a TAB should be used as the separator."
9599 (interactive "r\nP")
9600 (let* ((begin (min begin end)) (end (max begin end)) re)
9601 (goto-char begin) (beginning-of-line 1)
9602 (setq begin (point-marker))
9603 (goto-char end)
9604 (if (bolp) (backward-char 1) (end-of-line 1))
9605 (setq end (point-marker))
9606 (when (equal separator '(64))
9607 (setq separator (read-regexp "Regexp for cell separator: ")))
9608 (unless separator
9609 ;; Get the right cell separator
9610 (goto-char begin)
9611 (setq separator
9612 (cond
9613 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
9614 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
9615 (t 1))))
9616 (goto-char begin)
9617 (if (equal separator '(4))
9618 ;; Parse CSV
9619 (while (< (point) end)
9620 (cond
9621 ((looking-at "^") (insert "| "))
9622 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
9623 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
9624 (replace-match "\\1") (if (looking-at "\"") (insert "\"")))
9625 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
9626 ((looking-at "[ \t]*,") (replace-match " | "))
9627 (t (beginning-of-line 2))))
9628 (setq re
9629 (cond
9630 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
9631 ((equal separator '(16)) "^\\|\t")
9632 ((integerp separator)
9633 (if (< separator 1)
9634 (user-error "Cell separator must contain one or more spaces")
9635 (format "^ *\\| *\t *\\| \\{%d,\\}\\|$" separator)))
9636 ((stringp separator) (format "^ *\\|%s" separator))
9637 (t (error "Invalid cell separator"))))
9638 (let (finish)
9639 (while (and (not finish) (re-search-forward re end t))
9640 (if (eolp)
9641 (progn
9642 (replace-match "|" t t)
9643 (forward-line 1)
9644 (when (eobp)
9645 (setq finish t)))
9646 (replace-match "| " t t)))))
9647 (goto-char begin)
9648 (when markdown-table-align-p
9649 (markdown-table-align))))
9651 (defun markdown-insert-table (&optional rows columns align)
9652 "Insert an empty pipe table.
9653 Optional arguments ROWS, COLUMNS, and ALIGN specify number of
9654 rows and columns and the column alignment."
9655 (interactive)
9656 (let* ((rows (or rows (string-to-number (read-string "Row size: "))))
9657 (columns (or columns (string-to-number (read-string "Column size: "))))
9658 (align (or align (read-string "Alignment ([l]eft, [r]ight, [c]enter, or RET for default): ")))
9659 (align (cond ((equal align "l") ":--")
9660 ((equal align "r") "--:")
9661 ((equal align "c") ":-:")
9662 (t "---")))
9663 (pos (point))
9664 (indent (make-string (current-column) ?\ ))
9665 (line (concat
9666 (apply 'concat indent "|"
9667 (make-list columns " |")) "\n"))
9668 (hline (apply 'concat indent "|"
9669 (make-list columns (concat align "|")))))
9670 (if (string-match
9671 "^[ \t]*$" (buffer-substring-no-properties
9672 (line-beginning-position) (point)))
9673 (beginning-of-line 1)
9674 (newline))
9675 (dotimes (_ rows) (insert line))
9676 (goto-char pos)
9677 (if (> rows 1)
9678 (progn
9679 (end-of-line 1) (insert (concat "\n" hline)) (goto-char pos)))
9680 (markdown-table-forward-cell)))
9683 ;;; ElDoc Support =============================================================
9685 (defun markdown-eldoc-function (&rest _ignored)
9686 "Return a helpful string when appropriate based on context.
9687 * Report URL when point is at a hidden URL.
9688 * Report language name when point is a code block with hidden markup."
9689 (cond
9690 ;; Hidden URL or reference for inline link
9691 ((and (or (thing-at-point-looking-at markdown-regex-link-inline)
9692 (thing-at-point-looking-at markdown-regex-link-reference))
9693 (or markdown-hide-urls markdown-hide-markup))
9694 (let* ((imagep (string-equal (match-string 1) "!"))
9695 (referencep (string-equal (match-string 5) "["))
9696 (link (match-string-no-properties 6))
9697 (edit-keys (markdown--substitute-command-keys
9698 (if imagep
9699 "\\[markdown-insert-image]"
9700 "\\[markdown-insert-link]")))
9701 (edit-str (propertize edit-keys 'face 'font-lock-constant-face))
9702 (object (if referencep "reference" "URL")))
9703 (format "Hidden %s (%s to edit): %s" object edit-str
9704 (if referencep
9705 (concat
9706 (propertize "[" 'face 'markdown-markup-face)
9707 (propertize link 'face 'markdown-reference-face)
9708 (propertize "]" 'face 'markdown-markup-face))
9709 (propertize link 'face 'markdown-url-face)))))
9710 ;; Hidden language name for fenced code blocks
9711 ((and (markdown-code-block-at-point-p)
9712 (not (get-text-property (point) 'markdown-pre))
9713 markdown-hide-markup)
9714 (let ((lang (save-excursion (markdown-code-block-lang))))
9715 (unless lang (setq lang "[unspecified]"))
9716 (format "Hidden code block language: %s (%s to toggle markup)"
9717 (propertize lang 'face 'markdown-language-keyword-face)
9718 (markdown--substitute-command-keys
9719 "\\[markdown-toggle-markup-hiding]"))))))
9722 ;;; Mode Definition ==========================================================
9724 (defun markdown-show-version ()
9725 "Show the version number in the minibuffer."
9726 (interactive)
9727 (message "markdown-mode, version %s" markdown-mode-version))
9729 (defun markdown-mode-info ()
9730 "Open the `markdown-mode' homepage."
9731 (interactive)
9732 (browse-url "https://jblevins.org/projects/markdown-mode/"))
9734 ;;;###autoload
9735 (define-derived-mode markdown-mode text-mode "Markdown"
9736 "Major mode for editing Markdown files."
9737 (when buffer-read-only
9738 (when (or (not (buffer-file-name)) (file-writable-p (buffer-file-name)))
9739 (setq-local buffer-read-only nil)))
9740 ;; Natural Markdown tab width
9741 (setq tab-width 4)
9742 ;; Comments
9743 (setq-local comment-start "<!-- ")
9744 (setq-local comment-end " -->")
9745 (setq-local comment-start-skip "<!--[ \t]*")
9746 (setq-local comment-column 0)
9747 (setq-local comment-auto-fill-only-comments nil)
9748 (setq-local comment-use-syntax t)
9749 ;; Sentence
9750 (setq-local sentence-end-base "[.?!…‽][]\"'”’)}»›*_`~]*")
9751 ;; Syntax
9752 (add-hook 'syntax-propertize-extend-region-functions
9753 #'markdown-syntax-propertize-extend-region nil t)
9754 (add-hook 'jit-lock-after-change-extend-region-functions
9755 #'markdown-font-lock-extend-region-function t t)
9756 (setq-local syntax-propertize-function #'markdown-syntax-propertize)
9757 (syntax-propertize (point-max)) ;; Propertize before hooks run, etc.
9758 ;; Font lock.
9759 (setq font-lock-defaults
9760 '(markdown-mode-font-lock-keywords
9761 nil nil nil nil
9762 (font-lock-multiline . t)
9763 (font-lock-syntactic-face-function . markdown-syntactic-face)
9764 (font-lock-extra-managed-props
9765 . (composition display invisible rear-nonsticky
9766 keymap help-echo mouse-face))))
9767 (if markdown-hide-markup
9768 (add-to-invisibility-spec 'markdown-markup)
9769 (remove-from-invisibility-spec 'markdown-markup))
9770 ;; Wiki links
9771 (markdown-setup-wiki-link-hooks)
9772 ;; Math mode
9773 (when markdown-enable-math (markdown-toggle-math t))
9774 ;; Add a buffer-local hook to reload after file-local variables are read
9775 (add-hook 'hack-local-variables-hook #'markdown-handle-local-variables nil t)
9776 ;; For imenu support
9777 (setq imenu-create-index-function
9778 (if markdown-nested-imenu-heading-index
9779 #'markdown-imenu-create-nested-index
9780 #'markdown-imenu-create-flat-index))
9782 ;; Defun movement
9783 (setq-local beginning-of-defun-function #'markdown-beginning-of-defun)
9784 (setq-local end-of-defun-function #'markdown-end-of-defun)
9785 ;; Paragraph filling
9786 (setq-local fill-paragraph-function #'markdown-fill-paragraph)
9787 (setq-local paragraph-start
9788 ;; Should match start of lines that start or separate paragraphs
9789 (mapconcat #'identity
9791 "\f" ; starts with a literal line-feed
9792 "[ \t\f]*$" ; space-only line
9793 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9794 "[ \t]*[*+-][ \t]+" ; unordered list item
9795 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
9796 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
9797 "[ \t]*:[ \t]+" ; definition
9798 "^|" ; table or Pandoc line block
9800 "\\|"))
9801 (setq-local paragraph-separate
9802 ;; Should match lines that separate paragraphs without being
9803 ;; part of any paragraph:
9804 (mapconcat #'identity
9805 '("[ \t\f]*$" ; space-only line
9806 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9807 ;; The following is not ideal, but the Fill customization
9808 ;; options really only handle paragraph-starting prefixes,
9809 ;; not paragraph-ending suffixes:
9810 ".* $" ; line ending in two spaces
9811 "^#+"
9812 "^\\(?: \\)?[-=]+[ \t]*$" ;; setext
9813 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
9814 "\\|"))
9815 (setq-local adaptive-fill-first-line-regexp "\\`[ \t]*[A-Z]?>[ \t]*?\\'")
9816 (setq-local adaptive-fill-regexp "\\s-*")
9817 (setq-local adaptive-fill-function #'markdown-adaptive-fill-function)
9818 (setq-local fill-forward-paragraph-function #'markdown-fill-forward-paragraph)
9819 ;; Outline mode
9820 (setq-local outline-regexp markdown-regex-header)
9821 (setq-local outline-level #'markdown-outline-level)
9822 ;; Cause use of ellipses for invisible text.
9823 (add-to-invisibility-spec '(outline . t))
9824 ;; ElDoc support
9825 (if (boundp 'eldoc-documentation-functions)
9826 (add-hook 'eldoc-documentation-functions #'markdown-eldoc-function nil t)
9827 (add-function :before-until (local 'eldoc-documentation-function)
9828 #'markdown-eldoc-function))
9829 ;; Inhibiting line-breaking:
9830 ;; Separating out each condition into a separate function so that users can
9831 ;; override if desired (with remove-hook)
9832 (add-hook 'fill-nobreak-predicate
9833 #'markdown-line-is-reference-definition-p nil t)
9834 (add-hook 'fill-nobreak-predicate
9835 #'markdown-pipe-at-bol-p nil t)
9837 ;; Indentation
9838 (setq-local indent-line-function markdown-indent-function)
9839 (setq-local indent-region-function #'markdown--indent-region)
9841 ;; Flyspell
9842 (setq-local flyspell-generic-check-word-predicate
9843 #'markdown-flyspell-check-word-p)
9845 ;; Electric quoting
9846 (add-hook 'electric-quote-inhibit-functions
9847 #'markdown--inhibit-electric-quote nil :local)
9849 ;; Make checkboxes buttons
9850 (when markdown-make-gfm-checkboxes-buttons
9851 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
9852 (add-hook 'after-change-functions #'markdown-gfm-checkbox-after-change-function t t)
9853 (add-hook 'change-major-mode-hook #'markdown-remove-gfm-checkbox-overlays t t))
9855 ;; edit-indirect
9856 (add-hook 'edit-indirect-after-commit-functions
9857 #'markdown--edit-indirect-after-commit-function
9858 nil 'local)
9860 ;; Marginalized headings
9861 (when markdown-marginalize-headers
9862 (add-hook 'window-configuration-change-hook
9863 #'markdown-marginalize-update-current nil t))
9865 ;; add live preview export hook
9866 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
9867 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
9869 ;;;###autoload
9870 (add-to-list 'auto-mode-alist
9871 '("\\.\\(?:md\\|markdown\\|mkd\\|mdown\\|mkdn\\|mdwn\\)\\'" . markdown-mode))
9874 ;;; GitHub Flavored Markdown Mode ============================================
9876 (defun gfm--electric-pair-fence-code-block ()
9877 (when (and electric-pair-mode
9878 (not markdown-gfm-use-electric-backquote)
9879 (eql last-command-event ?`)
9880 (let ((count 0))
9881 (while (eql (char-before (- (point) count)) ?`)
9882 (cl-incf count))
9883 (= count 3))
9884 (eql (char-after) ?`))
9885 (save-excursion (insert (make-string 2 ?`)))))
9887 (defvar gfm-mode-hook nil
9888 "Hook run when entering GFM mode.")
9890 ;;;###autoload
9891 (define-derived-mode gfm-mode markdown-mode "GFM"
9892 "Major mode for editing GitHub Flavored Markdown files."
9893 (setq markdown-link-space-sub-char "-")
9894 (setq markdown-wiki-link-search-subdirectories t)
9895 (setq-local markdown-table-at-point-p-function #'gfm--table-at-point-p)
9896 (add-hook 'post-self-insert-hook #'gfm--electric-pair-fence-code-block 'append t)
9897 (markdown-gfm-parse-buffer-for-languages))
9900 ;;; Viewing modes =============================================================
9902 (defcustom markdown-hide-markup-in-view-modes t
9903 "Enable hidden markup mode in `markdown-view-mode' and `gfm-view-mode'."
9904 :group 'markdown
9905 :type 'boolean
9906 :safe #'booleanp)
9908 (defvar markdown-view-mode-map
9909 (let ((map (make-sparse-keymap)))
9910 (define-key map (kbd "p") #'markdown-outline-previous)
9911 (define-key map (kbd "n") #'markdown-outline-next)
9912 (define-key map (kbd "f") #'markdown-outline-next-same-level)
9913 (define-key map (kbd "b") #'markdown-outline-previous-same-level)
9914 (define-key map (kbd "u") #'markdown-outline-up)
9915 (define-key map (kbd "DEL") #'scroll-down-command)
9916 (define-key map (kbd "SPC") #'scroll-up-command)
9917 (define-key map (kbd ">") #'end-of-buffer)
9918 (define-key map (kbd "<") #'beginning-of-buffer)
9919 (define-key map (kbd "q") #'kill-this-buffer)
9920 (define-key map (kbd "?") #'describe-mode)
9921 map)
9922 "Keymap for `markdown-view-mode'.")
9924 (defun markdown--filter-visible (beg end &optional delete)
9925 (let ((result "")
9926 (invisible-faces '(markdown-header-delimiter-face markdown-header-rule-face)))
9927 (while (< beg end)
9928 (when (markdown--face-p beg invisible-faces)
9929 (cl-incf beg)
9930 (while (and (markdown--face-p beg invisible-faces) (< beg end))
9931 (cl-incf beg)))
9932 (let ((next (next-single-char-property-change beg 'invisible)))
9933 (unless (get-char-property beg 'invisible)
9934 (setq result (concat result (buffer-substring beg (min end next)))))
9935 (setq beg next)))
9936 (prog1 result
9937 (when delete
9938 (let ((inhibit-read-only t))
9939 (delete-region beg end))))))
9941 ;;;###autoload
9942 (define-derived-mode markdown-view-mode markdown-mode "Markdown-View"
9943 "Major mode for viewing Markdown content."
9944 (setq-local markdown-hide-markup markdown-hide-markup-in-view-modes)
9945 (add-to-invisibility-spec 'markdown-markup)
9946 (setq-local filter-buffer-substring-function #'markdown--filter-visible)
9947 (read-only-mode 1))
9949 (defvar gfm-view-mode-map
9950 markdown-view-mode-map
9951 "Keymap for `gfm-view-mode'.")
9953 ;;;###autoload
9954 (define-derived-mode gfm-view-mode gfm-mode "GFM-View"
9955 "Major mode for viewing GitHub Flavored Markdown content."
9956 (setq-local markdown-hide-markup markdown-hide-markup-in-view-modes)
9957 (setq-local markdown-fontify-code-blocks-natively t)
9958 (setq-local filter-buffer-substring-function #'markdown--filter-visible)
9959 (add-to-invisibility-spec 'markdown-markup)
9960 (read-only-mode 1))
9963 ;;; Live Preview Mode ========================================================
9964 ;;;###autoload
9965 (define-minor-mode markdown-live-preview-mode
9966 "Toggle native previewing on save for a specific markdown file."
9967 :lighter " MD-Preview"
9968 (if markdown-live-preview-mode
9969 (if (markdown-live-preview-get-filename)
9970 (markdown-display-buffer-other-window (markdown-live-preview-export))
9971 (markdown-live-preview-mode -1)
9972 (user-error "Buffer %s does not visit a file" (current-buffer)))
9973 (markdown-live-preview-remove)))
9976 (provide 'markdown-mode)
9978 ;; Local Variables:
9979 ;; indent-tabs-mode: nil
9980 ;; coding: utf-8
9981 ;; End:
9982 ;;; markdown-mode.el ends here