Add Markdown and GFM viewing modes
[markdown-mode.git] / markdown-mode.el
blob4be654b5e33ed5ad8cfe703764460b034617d8df
1 ;;; markdown-mode.el --- Major mode for Markdown-formatted text -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2007-2017 Jason R. Blevins and markdown-mode
4 ;; contributors (see the commit log for details).
6 ;; Author: Jason R. Blevins <jblevins@xbeta.org>
7 ;; Maintainer: Jason R. Blevins <jblevins@xbeta.org>
8 ;; Created: May 24, 2007
9 ;; Version: 2.4-dev
10 ;; Package-Requires: ((emacs "24") (cl-lib "0.5"))
11 ;; Keywords: Markdown, GitHub Flavored Markdown, itex
12 ;; URL: https://jblevins.org/projects/markdown-mode/
14 ;; This file is not part of GNU Emacs.
16 ;; This program is free software; you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
21 ;; This program is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
29 ;;; Commentary:
31 ;; See the README.md file for details.
34 ;;; Code:
36 (require 'easymenu)
37 (require 'outline)
38 (require 'thingatpt)
39 (require 'cl-lib)
40 (require 'url-parse)
41 (require 'button)
42 (require 'color)
43 (require 'rx)
45 (defvar jit-lock-start)
46 (defvar jit-lock-end)
47 (defvar flyspell-generic-check-word-predicate)
49 (declare-function eww-open-file "eww")
50 (declare-function url-path-and-query "url-parse")
53 ;;; Constants =================================================================
55 (defconst markdown-mode-version "2.4-dev"
56 "Markdown mode version number.")
58 (defconst markdown-output-buffer-name "*markdown-output*"
59 "Name of temporary buffer for markdown command output.")
61 (defconst markdown-sub-superscript-display
62 '(((raise -0.3) (height 0.7)) ; subscript
63 ((raise 0.3) (height 0.7))) ; superscript
64 "Parameters for sub- and superscript formatting.")
67 ;;; Global Variables ==========================================================
69 (defvar markdown-reference-label-history nil
70 "History of used reference labels.")
72 (defvar markdown-live-preview-mode nil
73 "Sentinel variable for command `markdown-live-preview-mode'.")
75 (defvar markdown-gfm-language-history nil
76 "History list of languages used in the current buffer in GFM code blocks.")
79 ;;; Customizable Variables ====================================================
81 (defvar markdown-mode-hook nil
82 "Hook run when entering Markdown mode.")
84 (defvar markdown-before-export-hook nil
85 "Hook run before running Markdown to export XHTML output.
86 The hook may modify the buffer, which will be restored to it's
87 original state after exporting is complete.")
89 (defvar markdown-after-export-hook nil
90 "Hook run after XHTML output has been saved.
91 Any changes to the output buffer made by this hook will be saved.")
93 (defgroup markdown nil
94 "Major mode for editing text files in Markdown format."
95 :prefix "markdown-"
96 :group 'wp
97 :link '(url-link "https://jblevins.org/projects/markdown-mode/"))
99 (defcustom markdown-command "markdown"
100 "Command to run markdown."
101 :group 'markdown
102 :type '(choice (string :tag "Shell command") function))
104 (defcustom markdown-command-needs-filename nil
105 "Set to non-nil if `markdown-command' does not accept input from stdin.
106 Instead, it will be passed a filename as the final command line
107 option. As a result, you will only be able to run Markdown from
108 buffers which are visiting a file."
109 :group 'markdown
110 :type 'boolean)
112 (defcustom markdown-open-command nil
113 "Command used for opening Markdown files directly.
114 For example, a standalone Markdown previewer. This command will
115 be called with a single argument: the filename of the current
116 buffer. It can also be a function, which will be called without
117 arguments."
118 :group 'markdown
119 :type '(choice file function (const :tag "None" nil)))
121 (defcustom markdown-hr-strings
122 '("-------------------------------------------------------------------------------"
123 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
124 "---------------------------------------"
125 "* * * * * * * * * * * * * * * * * * * *"
126 "---------"
127 "* * * * *")
128 "Strings to use when inserting horizontal rules.
129 The first string in the list will be the default when inserting a
130 horizontal rule. Strings should be listed in decreasing order of
131 prominence (as in headings from level one to six) for use with
132 promotion and demotion functions."
133 :group 'markdown
134 :type '(repeat string))
136 (defcustom markdown-bold-underscore nil
137 "Use two underscores when inserting bold text instead of two asterisks."
138 :group 'markdown
139 :type 'boolean)
141 (defcustom markdown-italic-underscore nil
142 "Use underscores when inserting italic text instead of asterisks."
143 :group 'markdown
144 :type 'boolean)
146 (defcustom markdown-marginalize-headers nil
147 "When non-nil, put opening atx header markup in a left margin.
149 This setting goes well with `markdown-asymmetric-header'. But
150 sadly it conflicts with `linum-mode' since they both use the
151 same margin."
152 :group 'markdown
153 :type 'boolean
154 :safe 'booleanp
155 :package-version '(markdown-mode . "2.4"))
157 (defcustom markdown-marginalize-headers-margin-width 6
158 "Character width of margin used for marginalized headers.
159 The default value is based on there being six heading levels
160 defined by Markdown and HTML. Increasing this produces extra
161 whitespace on the left. Decreasing it may be preferred when
162 fewer than six nested heading levels are used."
163 :group 'markdown
164 :type 'natnump
165 :safe 'natnump
166 :package-version '(markdown-mode . "2.4"))
168 (defcustom markdown-asymmetric-header nil
169 "Determines if atx header style will be asymmetric.
170 Set to a non-nil value to use asymmetric header styling, placing
171 header markup only at the beginning of the line. By default,
172 balanced markup will be inserted at the beginning and end of the
173 line around the header title."
174 :group 'markdown
175 :type 'boolean)
177 (defcustom markdown-indent-function 'markdown-indent-line
178 "Function to use to indent."
179 :group 'markdown
180 :type 'function)
182 (defcustom markdown-indent-on-enter t
183 "Determines indentation behavior when pressing \\[newline].
184 Possible settings are nil, t, and 'indent-and-new-item.
186 When non-nil, pressing \\[newline] will call `newline-and-indent'
187 to indent the following line according to the context using
188 `markdown-indent-function'. In this case, note that
189 \\[electric-newline-and-maybe-indent] can still be used to insert
190 a newline without indentation.
192 When set to 'indent-and-new-item and the point is in a list item
193 when \\[newline] is pressed, the list will be continued on the next
194 line, where a new item will be inserted.
196 When set to nil, simply call `newline' as usual. In this case,
197 you can still indent lines using \\[markdown-cycle] and continue
198 lists with \\[markdown-insert-list-item].
200 Note that this assumes the variable `electric-indent-mode' is
201 non-nil (enabled). When it is *disabled*, the behavior of
202 \\[newline] and `\\[electric-newline-and-maybe-indent]' are
203 reversed."
204 :group 'markdown
205 :type '(choice (const :tag "Don't automatically indent" nil)
206 (const :tag "Automatically indent" t)
207 (const :tag "Automatically indent and insert new list items" indent-and-new-item)))
209 (defcustom markdown-enable-wiki-links nil
210 "Syntax highlighting for wiki links.
211 Set this to a non-nil value to turn on wiki link support by default.
212 Support can be toggled later using the `markdown-toggle-wiki-links'
213 function or \\[markdown-toggle-wiki-links]."
214 :group 'markdown
215 :type 'boolean
216 :safe 'booleanp
217 :package-version '(markdown-mode . "2.2"))
219 (defcustom markdown-wiki-link-alias-first t
220 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
221 Otherwise, they will be treated as [[PageName|alias text]]."
222 :group 'markdown
223 :type 'boolean
224 :safe 'booleanp)
226 (defcustom markdown-wiki-link-search-subdirectories nil
227 "When non-nil, search for wiki link targets in subdirectories.
228 This is the default search behavior for GitHub and is
229 automatically set to t in `gfm-mode'."
230 :group 'markdown
231 :type 'boolean
232 :safe 'booleanp
233 :package-version '(markdown-mode . "2.2"))
235 (defcustom markdown-wiki-link-search-parent-directories nil
236 "When non-nil, search for wiki link targets in parent directories.
237 This is the default search behavior of Ikiwiki."
238 :group 'markdown
239 :type 'boolean
240 :safe 'booleanp
241 :package-version '(markdown-mode . "2.2"))
243 (defcustom markdown-wiki-link-fontify-missing nil
244 "When non-nil, change wiki link face according to existence of target files.
245 This is expensive because it requires checking for the file each time the buffer
246 changes or the user switches windows. It is disabled by default because it may
247 cause lag when typing on slower machines."
248 :group 'markdown
249 :type 'boolean
250 :safe 'booleanp
251 :package-version '(markdown-mode . "2.2"))
253 (defcustom markdown-uri-types
254 '("acap" "cid" "data" "dav" "fax" "file" "ftp"
255 "gopher" "http" "https" "imap" "ldap" "mailto"
256 "mid" "message" "modem" "news" "nfs" "nntp"
257 "pop" "prospero" "rtsp" "service" "sip" "tel"
258 "telnet" "tip" "urn" "vemmi" "wais")
259 "Link types for syntax highlighting of URIs."
260 :group 'markdown
261 :type '(repeat (string :tag "URI scheme")))
263 (defcustom markdown-url-compose-char
264 '(?∞ ?… ?⋯ ?# ?★ ?⚓)
265 "Placeholder character for hidden URLs.
266 This may be a single character or a list of characters. In case
267 of a list, the first one that satisfies `char-displayable-p' will
268 be used."
269 :type '(choice
270 (character :tag "Single URL replacement character")
271 (repeat :tag "List of possible URL replacement characters"
272 character))
273 :package-version '(markdown-mode . "2.3"))
275 (defcustom markdown-blockquote-display-char
276 '("▌" "┃" ">")
277 "String to display when hiding blockquote markup.
278 This may be a single string or a list of string. In case of a
279 list, the first one that satisfies `char-displayable-p' will be
280 used."
281 :type 'string
282 :type '(choice
283 (string :tag "Single blockquote display string")
284 (repeat :tag "List of possible blockquote display strings" string))
285 :package-version '(markdown-mode . "2.3"))
287 (defcustom markdown-hr-display-char
288 '(?─ ?━ ?-)
289 "Character for hiding horizontal rule markup.
290 This may be a single character or a list of characters. In case
291 of a list, the first one that satisfies `char-displayable-p' will
292 be used."
293 :group 'markdown
294 :type '(choice
295 (character :tag "Single HR display character")
296 (repeat :tag "List of possible HR display characters" character))
297 :package-version '(markdown-mode . "2.3"))
299 (defcustom markdown-definition-display-char
300 '(?⁘ ?⁙ ?≡ ?⌑ ?◊ ?:)
301 "Character for replacing definition list markup.
302 This may be a single character or a list of characters. In case
303 of a list, the first one that satisfies `char-displayable-p' will
304 be used."
305 :type '(choice
306 (character :tag "Single definition list character")
307 (repeat :tag "List of possible definition list characters" character))
308 :package-version '(markdown-mode . "2.3"))
310 (defcustom markdown-enable-math nil
311 "Syntax highlighting for inline LaTeX and itex expressions.
312 Set this to a non-nil value to turn on math support by default.
313 Math support can be enabled, disabled, or toggled later using
314 `markdown-toggle-math' or \\[markdown-toggle-math]."
315 :group 'markdown
316 :type 'boolean
317 :safe 'booleanp)
318 (make-variable-buffer-local 'markdown-enable-math)
320 (defcustom markdown-enable-html t
321 "Enable font-lock support for HTML tags and attributes."
322 :group 'markdown
323 :type 'boolean
324 :safe 'booleanp
325 :package-version '(markdown-mode . "2.4"))
327 (defcustom markdown-css-paths nil
328 "URL of CSS file to link to in the output XHTML."
329 :group 'markdown
330 :type '(repeat (string :tag "CSS File Path")))
332 (defcustom markdown-content-type ""
333 "Content type string for the http-equiv header in XHTML output.
334 When set to a non-empty string, insert the http-equiv attribute.
335 Otherwise, this attribute is omitted."
336 :group 'markdown
337 :type 'string)
339 (defcustom markdown-coding-system nil
340 "Character set string for the http-equiv header in XHTML output.
341 Defaults to `buffer-file-coding-system' (and falling back to
342 `iso-8859-1' when not available). Common settings are `utf-8'
343 and `iso-latin-1'. Use `list-coding-systems' for more choices."
344 :group 'markdown
345 :type 'coding-system)
347 (defcustom markdown-export-kill-buffer t
348 "Kill output buffer after HTML export.
349 When non-nil, kill the HTML output buffer after
350 exporting with `markdown-export'."
351 :group 'markdown
352 :type 'boolean
353 :safe 'booleanp
354 :package-version '(markdown-mode . "2.4"))
356 (defcustom markdown-xhtml-header-content ""
357 "Additional content to include in the XHTML <head> block."
358 :group 'markdown
359 :type 'string)
361 (defcustom markdown-xhtml-standalone-regexp
362 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
363 "Regexp indicating whether `markdown-command' output is standalone XHTML."
364 :group 'markdown
365 :type 'regexp)
367 (defcustom markdown-link-space-sub-char "_"
368 "Character to use instead of spaces when mapping wiki links to filenames."
369 :group 'markdown
370 :type 'string)
372 (defcustom markdown-reference-location 'header
373 "Position where new reference definitions are inserted in the document."
374 :group 'markdown
375 :type '(choice (const :tag "At the end of the document" end)
376 (const :tag "Immediately after the current block" immediately)
377 (const :tag "At the end of the subtree" subtree)
378 (const :tag "Before next header" header)))
380 (defcustom markdown-footnote-location 'end
381 "Position where new footnotes are inserted in the document."
382 :group 'markdown
383 :type '(choice (const :tag "At the end of the document" end)
384 (const :tag "Immediately after the current block" immediately)
385 (const :tag "At the end of the subtree" subtree)
386 (const :tag "Before next header" header)))
388 (defcustom markdown-footnote-display '((raise 0.2) (height 0.8))
389 "Display specification for footnote markers and inline footnotes.
390 By default, footnote text is reduced in size and raised. Set to
391 nil to disable this."
392 :group 'markdown
393 :type '(choice (sexp :tag "Display specification")
394 (const :tag "Don't set display property" nil))
395 :package-version '(markdown-mode . "2.4"))
397 (defcustom markdown-sub-superscript-display
398 '(((raise -0.3) (height 0.7)) . ((raise 0.3) (height 0.7)))
399 "Display specification for subscript and superscripts.
400 The car is used for subscript, the cdr is used for superscripts."
401 :group 'markdown
402 :type '(cons (choice (sexp :tag "Subscript form")
403 (const :tag "No lowering" nil))
404 (choice (sexp :tag "Superscript form")
405 (const :tag "No raising" nil)))
406 :package-version '(markdown-mode . "2.4"))
408 (defcustom markdown-unordered-list-item-prefix " * "
409 "String inserted before unordered list items."
410 :group 'markdown
411 :type 'string)
413 (defcustom markdown-nested-imenu-heading-index t
414 "Use nested or flat imenu heading index.
415 A nested index may provide more natural browsing from the menu,
416 but a flat list may allow for faster keyboard navigation via tab
417 completion."
418 :group 'markdown
419 :type 'boolean
420 :safe 'booleanp
421 :package-version '(markdown-mode . "2.2"))
423 (defcustom markdown-make-gfm-checkboxes-buttons t
424 "When non-nil, make GFM checkboxes into buttons."
425 :group 'markdown
426 :type 'boolean)
428 (defcustom markdown-use-pandoc-style-yaml-metadata nil
429 "When non-nil, allow YAML metadata anywhere in the document."
430 :group 'markdown
431 :type 'boolean)
433 (defcustom markdown-split-window-direction 'any
434 "Preference for splitting windows for static and live preview.
435 The default value is 'any, which instructs Emacs to use
436 `split-window-sensibly' to automatically choose how to split
437 windows based on the values of `split-width-threshold' and
438 `split-height-threshold' and the available windows. To force
439 vertically split (left and right) windows, set this to 'vertical
440 or 'right. To force horizontally split (top and bottom) windows,
441 set this to 'horizontal or 'below."
442 :group 'markdown
443 :type '(choice (const :tag "Automatic" any)
444 (const :tag "Right (vertical)" right)
445 (const :tag "Below (horizontal)" below))
446 :package-version '(markdown-mode . "2.2"))
448 (defcustom markdown-live-preview-window-function
449 'markdown-live-preview-window-eww
450 "Function to display preview of Markdown output within Emacs.
451 Function must update the buffer containing the preview and return
452 the buffer."
453 :group 'markdown
454 :type 'function)
456 (defcustom markdown-live-preview-delete-export 'delete-on-destroy
457 "Delete exported HTML file when using `markdown-live-preview-export'.
458 If set to 'delete-on-export, delete on every export. When set to
459 'delete-on-destroy delete when quitting from command
460 `markdown-live-preview-mode'. Never delete if set to nil."
461 :group 'markdown
462 :type '(choice
463 (const :tag "Delete on every export" delete-on-export)
464 (const :tag "Delete when quitting live preview" delete-on-destroy)
465 (const :tag "Never delete" nil)))
467 (defcustom markdown-list-indent-width 4
468 "Depth of indentation for markdown lists.
469 Used in `markdown-demote-list-item' and
470 `markdown-promote-list-item'."
471 :group 'markdown
472 :type 'integer)
474 (defcustom markdown-enable-prefix-prompts t
475 "Display prompts for certain prefix commands.
476 Set to nil to disable these prompts."
477 :group 'markdown
478 :type 'boolean
479 :safe 'booleanp
480 :package-version '(markdown-mode . "2.3"))
482 (defcustom markdown-gfm-additional-languages nil
483 "Extra languages made available when inserting GFM code blocks.
484 Language strings must have be trimmed of whitespace and not
485 contain any curly braces. They may be of arbitrary
486 capitalization, though."
487 :group 'markdown
488 :type '(repeat (string :validate markdown-validate-language-string)))
490 (defcustom markdown-gfm-use-electric-backquote t
491 "Use `markdown-electric-backquote' when backquote is hit three times."
492 :group 'markdown
493 :type 'boolean)
495 (defcustom markdown-gfm-downcase-languages t
496 "If non-nil, downcase suggested languages.
497 This applies to insertions done with
498 `markdown-electric-backquote'."
499 :group 'markdown
500 :type 'boolean)
502 (defcustom markdown-edit-code-block-default-mode 'normal-mode
503 "Default mode to use for editing code blocks.
504 This mode is used when automatic detection fails, such as for GFM
505 code blocks with no language specified."
506 :group 'markdown
507 :type 'symbol
508 :package-version '(markdown-mode . "2.4"))
510 (defcustom markdown-gfm-uppercase-checkbox nil
511 "If non-nil, use [X] for completed checkboxes, [x] otherwise."
512 :group 'markdown
513 :type 'boolean
514 :safe 'booleanp)
516 (defcustom markdown-hide-urls nil
517 "Hide URLs of inline links and reference tags of reference links.
518 Such URLs will be replaced by a single customizable
519 character, defined by `markdown-url-compose-char', but are still part
520 of the buffer. Links can be edited interactively with
521 \\[markdown-insert-link] or, for example, by deleting the final
522 parenthesis to remove the invisibility property. You can also
523 hover your mouse pointer over the link text to see the URL.
524 Set this to a non-nil value to turn this feature on by default.
525 You can interactively set the value of this variable by calling
526 `markdown-toggle-url-hiding', pressing \\[markdown-toggle-url-hiding],
527 or from the menu Markdown > Links & Images menu."
528 :group 'markdown
529 :type 'boolean
530 :safe 'booleanp
531 :package-version '(markdown-mode . "2.3"))
532 (make-variable-buffer-local 'markdown-hide-urls)
534 (defcustom markdown-translate-filename-function #'identity
535 "Function to use to translate filenames when following links.
536 \\<markdown-mode-map>\\[markdown-follow-thing-at-point] and \\[markdown-follow-link-at-point]
537 call this function with the filename as only argument whenever
538 they encounter a filename (instead of a URL) to be visited and
539 use its return value instead of the filename in the link. For
540 example, if absolute filenames are actually relative to a server
541 root directory, you can set
542 `markdown-translate-filename-function' to a function that
543 prepends the root directory to the given filename."
544 :group 'markdown
545 :type 'function
546 :risky t
547 :package-version '(markdown-mode . "2.4"))
549 (defcustom markdown-max-image-size nil
550 "Maximum width and height for displayed inline images.
551 This variable may be nil or a cons cell (MAX-WIDTH . MAX-HEIGHT).
552 When nil, use the actual size. Otherwise, use ImageMagick to
553 resize larger images to be of the given maximum dimensions. This
554 requires Emacs to be built with ImageMagick support."
555 :group 'markdown
556 :package-version '(markdown-mode . "2.4")
557 :type '(choice
558 (const :tag "Use actual image width" nil)
559 (cons (choice (sexp :tag "Maximum width in pixels")
560 (const :tag "No maximum width" nil))
561 (choice (sexp :tag "Maximum height in pixels")
562 (const :tag "No maximum height" nil)))))
565 ;;; Markdown-Specific `rx' Macro
567 ;; Based on python-rx from python.el.
568 (eval-and-compile
569 (defconst markdown-rx-constituents
570 `((newline . ,(rx "\n"))
571 (indent . ,(rx (or (repeat 4 " ") "\t")))
572 (block-end . ,(rx (and (or (one-or-more (zero-or-more blank) "\n") line-end))))
573 (numeral . ,(rx (and (one-or-more (any "0-9#")) ".")))
574 (bullet . ,(rx (any "*+:-")))
575 (list-marker . ,(rx (or (and (one-or-more (any "0-9#")) ".")
576 (any "*+:-"))))
577 (checkbox . ,(rx "[" (any " xX") "]")))
578 "Markdown-specific sexps for `markdown-rx'")
580 (defmacro markdown-rx (&rest regexps)
581 "Markdown mode specialized rx macro.
582 This variant of `rx' supports common Markdown named REGEXPS."
583 (let ((rx-constituents (append markdown-rx-constituents rx-constituents)))
584 (cond ((null regexps)
585 (error "No regexp"))
586 ((cdr regexps)
587 (rx-to-string `(and ,@regexps) t))
589 (rx-to-string (car regexps) t))))))
592 ;;; Regular Expressions =======================================================
594 (defconst markdown-regex-comment-start
595 "<!--"
596 "Regular expression matches HTML comment opening.")
598 (defconst markdown-regex-comment-end
599 "--[ \t]*>"
600 "Regular expression matches HTML comment closing.")
602 (defconst markdown-regex-link-inline
603 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)\\((\\)\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?\\()\\)"
604 "Regular expression for a [text](file) or an image link ![text](file).
605 Group 1 matches the leading exclamation point (optional).
606 Group 2 matches the opening square bracket.
607 Group 3 matches the text inside the square brackets.
608 Group 4 matches the closing square bracket.
609 Group 5 matches the opening parenthesis.
610 Group 6 matches the URL.
611 Group 7 matches the title (optional).
612 Group 8 matches the closing parenthesis.")
614 (defconst markdown-regex-link-reference
615 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)[ ]?\\(\\[\\)\\([^]]*?\\)\\(\\]\\)"
616 "Regular expression for a reference link [text][id].
617 Group 1 matches the leading exclamation point (optional).
618 Group 2 matches the opening square bracket for the link text.
619 Group 3 matches the text inside the square brackets.
620 Group 4 matches the closing square bracket for the link text.
621 Group 5 matches the opening square bracket for the reference label.
622 Group 6 matches the reference label.
623 Group 7 matches the closing square bracket for the reference label.")
625 (defconst markdown-regex-reference-definition
626 "^ \\{0,3\\}\\(\\[\\)\\([^]\n]+?\\)\\(\\]\\)\\(:\\)\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
627 "Regular expression for a reference definition.
628 Group 1 matches the opening square bracket.
629 Group 2 matches the reference label.
630 Group 3 matches the closing square bracket.
631 Group 4 matches the colon.
632 Group 5 matches the URL.
633 Group 6 matches the title attribute (optional).")
635 (defconst markdown-regex-footnote
636 "\\(\\[\\^\\)\\(.+?\\)\\(\\]\\)"
637 "Regular expression for a footnote marker [^fn].
638 Group 1 matches the opening square bracket and carat.
639 Group 2 matches only the label, without the surrounding markup.
640 Group 3 matches the closing square bracket.")
642 (defconst markdown-regex-header
643 "^\\(?:\\([^\r\n\t -].*\\)\n\\(?:\\(=+\\)\\|\\(-+\\)\\)\\|\\(#+[ \t]+\\)\\(.*?\\)\\([ \t]*#*\\)\\)$"
644 "Regexp identifying Markdown headings.
645 Group 1 matches the text of a setext heading.
646 Group 2 matches the underline of a level-1 setext heading.
647 Group 3 matches the underline of a level-2 setext heading.
648 Group 4 matches the opening hash marks of an atx heading and whitespace.
649 Group 5 matches the text, without surrounding whitespace, of an atx heading.
650 Group 6 matches the closing whitespace and hash marks of an atx heading.")
652 (defconst markdown-regex-header-setext
653 "^\\([^\r\n\t -].*\\)\n\\(=+\\|-+\\)$"
654 "Regular expression for generic setext-style (underline) headers.")
656 (defconst markdown-regex-header-atx
657 "^\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
658 "Regular expression for generic atx-style (hash mark) headers.")
660 (defconst markdown-regex-hr
661 (rx line-start
662 (group (or (and (repeat 3 (and "*" (? " "))) (* (any "* ")))
663 (and (repeat 3 (and "-" (? " "))) (* (any "- ")))
664 (and (repeat 3 (and "_" (? " "))) (* (any "_ ")))))
665 line-end)
666 "Regular expression for matching Markdown horizontal rules.")
668 (defconst markdown-regex-code
669 "\\(?:\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(?:.\\|\n[^\n]\\)*?[^`]\\)\\(\\2\\)\\)\\(?:[^`]\\|\\'\\)"
670 "Regular expression for matching inline code fragments.
672 Group 1 matches the entire code fragment including the backquotes.
673 Group 2 matches the opening backquotes.
674 Group 3 matches the code fragment itself, without backquotes.
675 Group 4 matches the closing backquotes.
677 The leading, unnumbered group ensures that the leading backquote
678 character is not escaped.
679 The last group, also unnumbered, requires that the character
680 following the code fragment is not a backquote.
681 Note that \\(?:.\\|\n[^\n]\\) matches any character, including newlines,
682 but not two newlines in a row.")
684 (defconst markdown-regex-kbd
685 "\\(<kbd>\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(</kbd>\\)"
686 "Regular expression for matching <kbd> tags.
687 Groups 1 and 3 match the opening and closing tags.
688 Group 2 matches the key sequence.")
690 (defconst markdown-regex-gfm-code-block-open
691 "^[[:blank:]]*\\(```\\)\\([[:blank:]]*{?[[:blank:]]*\\)\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$"
692 "Regular expression matching opening of GFM code blocks.
693 Group 1 matches the opening three backquotes and any following whitespace.
694 Group 2 matches the opening brace (optional) and surrounding whitespace.
695 Group 3 matches the language identifier (optional).
696 Group 4 matches the info string (optional).
697 Group 5 matches the closing brace (optional), whitespace, and newline.
698 Groups need to agree with `markdown-regex-tilde-fence-begin'.")
700 (defconst markdown-regex-gfm-code-block-close
701 "^[[:blank:]]*\\(```\\)\\(\\s *?\\)$"
702 "Regular expression matching closing of GFM code blocks.
703 Group 1 matches the closing three backquotes.
704 Group 2 matches any whitespace and the final newline.")
706 (defconst markdown-regex-pre
707 "^\\( \\|\t\\).*$"
708 "Regular expression for matching preformatted text sections.")
710 (defconst markdown-regex-list
711 (markdown-rx line-start
712 ;; 1. Leading whitespace
713 (group (* blank))
714 ;; 2. List marker: a numeral, bullet, or colon
715 (group list-marker)
716 ;; 3. Trailing whitespace
717 (group (+ blank))
718 ;; 4. Optional checkbox for GFM task list items
719 (opt (group (and checkbox (* blank)))))
720 "Regular expression for matching list items.")
722 (defconst markdown-regex-bold
723 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
724 "Regular expression for matching bold text.
725 Group 1 matches the character before the opening asterisk or
726 underscore, if any, ensuring that it is not a backslash escape.
727 Group 2 matches the entire expression, including delimiters.
728 Groups 3 and 5 matches the opening and closing delimiters.
729 Group 4 matches the text inside the delimiters.")
731 (defconst markdown-regex-italic
732 "\\(?:^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t*]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
733 "Regular expression for matching italic text.
734 The leading unnumbered matches the character before the opening
735 asterisk or underscore, if any, ensuring that it is not a
736 backslash escape.
737 Group 1 matches the entire expression, including delimiters.
738 Groups 2 and 4 matches the opening and closing delimiters.
739 Group 3 matches the text inside the delimiters.")
741 (defconst markdown-regex-strike-through
742 "\\(^\\|[^\\]\\)\\(\\(~~\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(~~\\)\\)"
743 "Regular expression for matching strike-through text.
744 Group 1 matches the character before the opening tilde, if any,
745 ensuring that it is not a backslash escape.
746 Group 2 matches the entire expression, including delimiters.
747 Groups 3 and 5 matches the opening and closing delimiters.
748 Group 4 matches the text inside the delimiters.")
750 (defconst markdown-regex-gfm-italic
751 "\\(?:^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\2\\|[^ ]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
752 "Regular expression for matching italic text in GitHub Flavored Markdown.
753 Underscores in words are not treated as special.
754 Group 1 matches the entire expression, including delimiters.
755 Groups 2 and 4 matches the opening and closing delimiters.
756 Group 3 matches the text inside the delimiters.")
758 (defconst markdown-regex-blockquote
759 "^[ \t]*\\([A-Z]?>\\)\\([ \t]*\\)\\(.*\\)$"
760 "Regular expression for matching blockquote lines.
761 Also accounts for a potential capital letter preceding the angle
762 bracket, for use with Leanpub blocks (asides, warnings, info
763 blocks, etc.).
764 Group 1 matches the leading angle bracket.
765 Group 2 matches the separating whitespace.
766 Group 3 matches the text.")
768 (defconst markdown-regex-line-break
769 "[^ \n\t][ \t]*\\( \\)$"
770 "Regular expression for matching line breaks.")
772 (defconst markdown-regex-wiki-link
773 "\\(?:^\\|[^\\]\\)\\(\\(\\[\\[\\)\\([^]|]+\\)\\(?:\\(|\\)\\([^]]+\\)\\)?\\(\\]\\]\\)\\)"
774 "Regular expression for matching wiki links.
775 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
776 wiki links of the form [[PageName|link text]].
777 The meanings of the first and second components depend
778 on the value of `markdown-wiki-link-alias-first'.
780 Group 1 matches the entire link.
781 Group 2 matches the opening square brackets.
782 Group 3 matches the first component of the wiki link.
783 Group 4 matches the pipe separator, when present.
784 Group 5 matches the second component of the wiki link, when present.
785 Group 6 matches the closing square brackets.")
787 (defconst markdown-regex-uri
788 (concat "\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+\\)")
789 "Regular expression for matching inline URIs.")
791 (defconst markdown-regex-angle-uri
792 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
793 "Regular expression for matching inline URIs in angle brackets.")
795 (defconst markdown-regex-email
796 "<\\(\\(?:\\sw\\|\\s_\\|\\s.\\)+@\\(?:\\sw\\|\\s_\\|\\s.\\)+\\)>"
797 "Regular expression for matching inline email addresses.")
799 (defsubst markdown-make-regex-link-generic ()
800 "Make regular expression for matching any recognized link."
801 (concat "\\(?:" markdown-regex-link-inline
802 (when markdown-enable-wiki-links
803 (concat "\\|" markdown-regex-wiki-link))
804 "\\|" markdown-regex-link-reference
805 "\\|" markdown-regex-angle-uri "\\)"))
807 (defconst markdown-regex-gfm-checkbox
808 " \\(\\[[ xX]\\]\\) "
809 "Regular expression for matching GFM checkboxes.
810 Group 1 matches the text to become a button.")
812 (defconst markdown-regex-blank-line
813 "^[[:blank:]]*$"
814 "Regular expression that matches a blank line.")
816 (defconst markdown-regex-block-separator
817 "\n[\n\t\f ]*\n"
818 "Regular expression for matching block boundaries.")
820 (defconst markdown-regex-block-separator-noindent
821 (concat "\\(\\`\\|\\(" markdown-regex-block-separator "\\)[^\n\t\f ]\\)")
822 "Regexp for block separators before lines with no indentation.")
824 (defconst markdown-regex-math-inline-single
825 "\\(?:^\\|[^\\]\\)\\(\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\)"
826 "Regular expression for itex $..$ math mode expressions.
827 Groups 1 and 3 match the opening and closing dollar signs.
828 Group 2 matches the mathematical expression contained within.")
830 (defconst markdown-regex-math-inline-double
831 "\\(?:^\\|[^\\]\\)\\(\\$\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\$\\)"
832 "Regular expression for itex $$..$$ math mode expressions.
833 Groups 1 and 3 match opening and closing dollar signs.
834 Group 2 matches the mathematical expression contained within.")
836 (defconst markdown-regex-math-display
837 (rx line-start (* blank)
838 (group (group (repeat 1 2 "\\")) "[")
839 (group (*? anything))
840 (group (backref 2) "]")
841 line-end)
842 "Regular expression for \[..\] or \\[..\\] display math.
843 Groups 1 and 4 match the opening and closing markup.
844 Group 3 matches the mathematical expression contained within.
845 Group 2 matches the opening slashes, and is used internally to
846 match the closing slashes.")
848 (defsubst markdown-make-tilde-fence-regex (num-tildes &optional end-of-line)
849 "Return regexp matching a tilde code fence at least NUM-TILDES long.
850 END-OF-LINE is the regexp construct to indicate end of line; $ if
851 missing."
852 (format "%s%d%s%s" "^[[:blank:]]*\\([~]\\{" num-tildes ",\\}\\)"
853 (or end-of-line "$")))
855 (defconst markdown-regex-tilde-fence-begin
856 (markdown-make-tilde-fence-regex
857 3 "\\([[:blank:]]*{?\\)[[:blank:]]*\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$")
858 "Regular expression for matching tilde-fenced code blocks.
859 Group 1 matches the opening tildes.
860 Group 2 matches (optional) opening brace and surrounding whitespace.
861 Group 3 matches the language identifier (optional).
862 Group 4 matches the info string (optional).
863 Group 5 matches the closing brace (optional) and any surrounding whitespace.
864 Groups need to agree with `markdown-regex-gfm-code-block-open'.")
866 (defconst markdown-regex-declarative-metadata
867 "^\\([[:alpha:]][[:alpha:] _-]*?\\)\\([:=][ \t]*\\)\\(.*\\)$"
868 "Regular expression for matching declarative metadata statements.
869 This matches MultiMarkdown metadata as well as YAML and TOML
870 assignments such as the following:
872 variable: value
876 variable = value")
878 (defconst markdown-regex-pandoc-metadata
879 "^\\(%\\)\\([ \t]*\\)\\(.*\\(?:\n[ \t]+.*\\)*\\)"
880 "Regular expression for matching Pandoc metadata.")
882 (defconst markdown-regex-yaml-metadata-border
883 "\\(-\\{3\\}\\)$"
884 "Regular expression for matching YAML metadata.")
886 (defconst markdown-regex-yaml-pandoc-metadata-end-border
887 "^\\(\\.\\{3\\}\\|\\-\\{3\\}\\)$"
888 "Regular expression for matching YAML metadata end borders.")
890 (defsubst markdown-get-yaml-metadata-start-border ()
891 "Return YAML metadata start border depending upon whether Pandoc is used."
892 (concat
893 (if markdown-use-pandoc-style-yaml-metadata "^" "\\`")
894 markdown-regex-yaml-metadata-border))
896 (defsubst markdown-get-yaml-metadata-end-border (_)
897 "Return YAML metadata end border depending upon whether Pandoc is used."
898 (if markdown-use-pandoc-style-yaml-metadata
899 markdown-regex-yaml-pandoc-metadata-end-border
900 markdown-regex-yaml-metadata-border))
902 (defconst markdown-regex-inline-attributes
903 "[ \t]*\\({:?\\)[ \t]*\\(\\(#[[:alpha:]_.:-]+\\|\\.[[:alpha:]_.:-]+\\|\\w+=['\"]?[^\n'\"]*['\"]?\\),?[ \t]*\\)+\\(}\\)[ \t]*$"
904 "Regular expression for matching inline identifiers or attribute lists.
905 Compatible with Pandoc, Python Markdown, PHP Markdown Extra, and Leanpub.")
907 (defconst markdown-regex-leanpub-sections
908 (concat
909 "^\\({\\)\\("
910 (regexp-opt '("frontmatter" "mainmatter" "backmatter" "appendix" "pagebreak"))
911 "\\)\\(}\\)[ \t]*\n")
912 "Regular expression for Leanpub section markers and related syntax.")
914 (defconst markdown-regex-sub-superscript
915 "\\(?:^\\|[^\\~^]\\)\\(\\([~^]\\)\\([[:alnum:]]+\\)\\(\\2\\)\\)"
916 "The regular expression matching a sub- or superscript.
917 The leading un-numbered group matches the character before the
918 opening tilde or carat, if any, ensuring that it is not a
919 backslash escape, carat, or tilde.
920 Group 1 matches the entire expression, including markup.
921 Group 2 matches the opening markup--a tilde or carat.
922 Group 3 matches the text inside the delimiters.
923 Group 4 matches the closing markup--a tilde or carat.")
925 (defconst markdown-regex-include
926 "^\\(<<\\)\\(?:\\(\\[\\)\\(.*\\)\\(\\]\\)\\)?\\(?:\\((\\)\\(.*\\)\\()\\)\\)?\\(?:\\({\\)\\(.*\\)\\(}\\)\\)?$"
927 "Regular expression matching common forms of include syntax.
928 Marked 2, Leanpub, and other processors support some of these forms:
930 <<[sections/section1.md]
931 <<(folder/filename)
932 <<[Code title](folder/filename)
933 <<{folder/raw_file.html}
935 Group 1 matches the opening two angle brackets.
936 Groups 2-4 match the opening square bracket, the text inside,
937 and the closing square bracket, respectively.
938 Groups 5-7 match the opening parenthesis, the text inside, and
939 the closing parenthesis.
940 Groups 8-10 match the opening brace, the text inside, and the brace.")
942 (defconst markdown-regex-pandoc-inline-footnote
943 "\\(\\^\\)\\(\\[\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(\\]\\)"
944 "Regular expression for Pandoc inline footnote^[footnote text].
945 Group 1 matches the opening caret.
946 Group 2 matches the opening square bracket.
947 Group 3 matches the footnote text, without the surrounding markup.
948 Group 4 matches the closing square bracket.")
950 (defconst markdown-regex-html-attr
951 "\\(\\<[[:alpha:]:-]+\\>\\)\\(\\s-*\\(=\\)\\s-*\\(\".*?\"\\|'.*?'\\|[^'\">[:space:]]+\\)?\\)?"
952 "Regular expression for matching HTML attributes and values.
953 Group 1 matches the attribute name.
954 Group 2 matches the following whitespace, equals sign, and value, if any.
955 Group 3 matches the equals sign, if any.
956 Group 4 matches single-, double-, or un-quoted attribute values.")
958 (defconst markdown-regex-html-tag
959 (concat "\\(</?\\)\\(\\w+\\)\\(\\(\\s-+" markdown-regex-html-attr
960 "\\)+\\s-*\\|\\s-*\\)\\(/?>\\)")
961 "Regular expression for matching HTML tags.
962 Groups 1 and 9 match the beginning and ending angle brackets and slashes.
963 Group 2 matches the tag name.
964 Group 3 matches all attributes and whitespace following the tag name.")
966 (defconst markdown-regex-html-entity
967 "\\(&#?[[:alnum:]]+;\\)"
968 "Regular expression for matching HTML entities.")
971 ;;; Syntax ====================================================================
973 (defsubst markdown-in-comment-p (&optional pos)
974 "Return non-nil if POS is in a comment.
975 If POS is not given, use point instead."
976 (get-text-property (or pos (point)) 'markdown-comment))
978 (defun markdown-syntax-propertize-extend-region (start end)
979 "Extend START to END region to include an entire block of text.
980 This helps improve syntax analysis for block constructs.
981 Returns a cons (NEW-START . NEW-END) or nil if no adjustment should be made.
982 Function is called repeatedly until it returns nil. For details, see
983 `syntax-propertize-extend-region-functions'."
984 (save-match-data
985 (save-excursion
986 (let* ((new-start (progn (goto-char start)
987 (skip-chars-forward "\n")
988 (if (re-search-backward "\n\n" nil t)
989 (min start (match-end 0))
990 (point-min))))
991 (new-end (progn (goto-char end)
992 (skip-chars-backward "\n")
993 (if (re-search-forward "\n\n" nil t)
994 (max end (match-beginning 0))
995 (point-max))))
996 (code-match (markdown--code-block-at-pos-no-syntax new-start))
997 (new-start (or (and code-match (cl-first code-match)) new-start))
998 (code-match (and (< end (point-max))
999 (markdown--code-block-at-pos-no-syntax end)))
1000 (new-end (or (and code-match (cl-second code-match)) new-end)))
1001 (unless (and (eq new-start start) (eq new-end end))
1002 (cons new-start (min new-end (point-max))))))))
1004 (defun markdown-font-lock-extend-region-function (start end _)
1005 "Used in `jit-lock-after-change-extend-region-functions'.
1006 Delegates to `markdown-syntax-propertize-extend-region'. START
1007 and END are the previous region to refontify."
1008 (let ((res (markdown-syntax-propertize-extend-region start end)))
1009 (when res
1010 ;; syntax-propertize-function is not called when character at
1011 ;; (point-max) is deleted, but font-lock-extend-region-functions
1012 ;; are called. Force a syntax property update in that case.
1013 (when (= end (point-max))
1014 ;; This function is called in a buffer modification hook.
1015 ;; `markdown-syntax-propertize' doesn't save the match data,
1016 ;; so we have to do it here.
1017 (save-match-data
1018 (markdown-syntax-propertize (car res) (cdr res))))
1019 (setq jit-lock-start (car res)
1020 jit-lock-end (cdr res)))))
1022 (defun markdown--cur-list-item-bounds ()
1023 "Return a list describing the list item at point.
1024 Assumes that match data is set for `markdown-regex-list'. See the
1025 documentation for `markdown-cur-list-item-bounds' for the format of
1026 the returned list."
1027 (save-excursion
1028 (let* ((begin (match-beginning 0))
1029 (indent (length (match-string-no-properties 1)))
1030 (nonlist-indent (- (match-end 3) (match-beginning 0)))
1031 (marker (buffer-substring-no-properties
1032 (match-beginning 2) (match-end 3)))
1033 (checkbox (match-string-no-properties 4))
1034 (match (butlast (match-data t)))
1035 (end (markdown-cur-list-item-end nonlist-indent)))
1036 (list begin end indent nonlist-indent marker checkbox match))))
1038 (defun markdown--append-list-item-bounds (marker indent cur-bounds bounds)
1039 "Update list item BOUNDS given list MARKER, block INDENT, and CUR-BOUNDS.
1040 Here, MARKER is a string representing the type of list and INDENT
1041 is an integer giving the indentation, in spaces, of the current
1042 block. CUR-BOUNDS is a list of the form returned by
1043 `markdown-cur-list-item-bounds' and BOUNDS is a list of bounds
1044 values for parent list items. When BOUNDS is nil, it means we are
1045 at baseline (not inside of a nested list)."
1046 (let ((prev-indent (or (cl-third (car bounds)) 0)))
1047 (cond
1048 ;; New list item at baseline.
1049 ((and marker (null bounds))
1050 (list cur-bounds))
1051 ;; List item with greater indentation (four or more spaces).
1052 ;; Increase list level by consing CUR-BOUNDS onto BOUNDS.
1053 ((and marker (>= indent (+ prev-indent 4)))
1054 (cons cur-bounds bounds))
1055 ;; List item with greater or equal indentation (less than four spaces).
1056 ;; Keep list level the same by replacing the car of BOUNDS.
1057 ((and marker (>= indent prev-indent))
1058 (cons cur-bounds (cdr bounds)))
1059 ;; Lesser indentation level.
1060 ;; Pop appropriate number of elements off BOUNDS list (e.g., lesser
1061 ;; indentation could move back more than one list level). Note
1062 ;; that this block need not be the beginning of list item.
1063 ((< indent prev-indent)
1064 (while (and (> (length bounds) 1)
1065 (setq prev-indent (cl-third (cadr bounds)))
1066 (< indent (+ prev-indent 4)))
1067 (setq bounds (cdr bounds)))
1068 (cons cur-bounds bounds))
1069 ;; Otherwise, do nothing.
1070 (t bounds))))
1072 (defun markdown-syntax-propertize-list-items (start end)
1073 "Propertize list items from START to END.
1074 Stores nested list item information in the `markdown-list-item'
1075 text property to make later syntax analysis easier. The value of
1076 this property is a list with elements of the form (begin . end)
1077 giving the bounds of the current and parent list items."
1078 (save-excursion
1079 (goto-char start)
1080 (let (bounds level pre-regexp)
1081 ;; Find a baseline point with zero list indentation
1082 (markdown-search-backward-baseline)
1083 ;; Search for all list items between baseline and END
1084 (while (and (< (point) end)
1085 (re-search-forward markdown-regex-list end t))
1086 ;; Level of list nesting
1087 (setq level (length bounds))
1088 ;; Pre blocks need to be indented one level past the list level
1089 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ level)))
1090 (beginning-of-line)
1091 (cond
1092 ;; Reset at headings, horizontal rules, and top-level blank lines.
1093 ;; Propertize baseline when in range.
1094 ((markdown-new-baseline)
1095 (setq bounds nil))
1096 ;; Make sure this is not a line from a pre block
1097 ((looking-at-p pre-regexp))
1098 ;; If not, then update levels and propertize list item when in range.
1100 (let* ((indent (current-indentation))
1101 (cur-bounds (markdown--cur-list-item-bounds))
1102 (first (cl-first cur-bounds))
1103 (last (cl-second cur-bounds))
1104 (marker (cl-fifth cur-bounds)))
1105 (setq bounds (markdown--append-list-item-bounds
1106 marker indent cur-bounds bounds))
1107 (when (and (<= start (point)) (<= (point) end))
1108 (put-text-property first last 'markdown-list-item bounds)))))
1109 (end-of-line)))))
1111 (defun markdown-syntax-propertize-pre-blocks (start end)
1112 "Match preformatted text blocks from START to END."
1113 (save-excursion
1114 (goto-char start)
1115 (let ((levels (markdown-calculate-list-levels))
1116 indent pre-regexp close-regexp open close)
1117 (while (and (< (point) end) (not close))
1118 ;; Search for a region with sufficient indentation
1119 (if (null levels)
1120 (setq indent 1)
1121 (setq indent (1+ (length levels))))
1122 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1123 (setq close-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1125 (cond
1126 ;; If not at the beginning of a line, move forward
1127 ((not (bolp)) (forward-line))
1128 ;; Move past blank lines
1129 ((markdown-cur-line-blank-p) (forward-line))
1130 ;; At headers and horizontal rules, reset levels
1131 ((markdown-new-baseline) (forward-line) (setq levels nil))
1132 ;; If the current line has sufficient indentation, mark out pre block
1133 ;; The opening should be preceded by a blank line.
1134 ((and (markdown-prev-line-blank) (looking-at pre-regexp))
1135 (setq open (match-beginning 0))
1136 (while (and (or (looking-at-p pre-regexp) (markdown-cur-line-blank-p))
1137 (not (eobp)))
1138 (forward-line))
1139 (skip-syntax-backward "-")
1140 (setq close (point)))
1141 ;; If current line has a list marker, update levels, move to end of block
1142 ((looking-at markdown-regex-list)
1143 (setq levels (markdown-update-list-levels
1144 (match-string 2) (current-indentation) levels))
1145 (markdown-end-of-text-block))
1146 ;; If this is the end of the indentation level, adjust levels accordingly.
1147 ;; Only match end of indentation level if levels is not the empty list.
1148 ((and (car levels) (looking-at-p close-regexp))
1149 (setq levels (markdown-update-list-levels
1150 nil (current-indentation) levels))
1151 (markdown-end-of-text-block))
1152 (t (markdown-end-of-text-block))))
1154 (when (and open close)
1155 ;; Set text property data
1156 (put-text-property open close 'markdown-pre (list open close))
1157 ;; Recursively search again
1158 (markdown-syntax-propertize-pre-blocks (point) end)))))
1160 (defconst markdown-fenced-block-pairs
1161 `(((,markdown-regex-tilde-fence-begin markdown-tilde-fence-begin)
1162 (markdown-make-tilde-fence-regex markdown-tilde-fence-end)
1163 markdown-fenced-code)
1164 ((markdown-get-yaml-metadata-start-border markdown-yaml-metadata-begin)
1165 (markdown-get-yaml-metadata-end-border markdown-yaml-metadata-end)
1166 markdown-yaml-metadata-section)
1167 ((,markdown-regex-gfm-code-block-open markdown-gfm-block-begin)
1168 (,markdown-regex-gfm-code-block-close markdown-gfm-block-end)
1169 markdown-gfm-code))
1170 "Mapping of regular expressions to \"fenced-block\" constructs.
1171 These constructs are distinguished by having a distinctive start
1172 and end pattern, both of which take up an entire line of text,
1173 but no special pattern to identify text within the fenced
1174 blocks (unlike blockquotes and indented-code sections).
1176 Each element within this list takes the form:
1178 ((START-REGEX-OR-FUN START-PROPERTY)
1179 (END-REGEX-OR-FUN END-PROPERTY)
1180 MIDDLE-PROPERTY)
1182 Each *-REGEX-OR-FUN element can be a regular expression as a string, or a
1183 function which evaluates to same. Functions for START-REGEX-OR-FUN accept no
1184 arguments, but functions for END-REGEX-OR-FUN accept a single numerical argument
1185 which is the length of the first group of the START-REGEX-OR-FUN match, which
1186 can be ignored if unnecessary. `markdown-maybe-funcall-regexp' is used to
1187 evaluate these into \"real\" regexps.
1189 The *-PROPERTY elements are the text properties applied to each part of the
1190 block construct when it is matched using
1191 `markdown-syntax-propertize-fenced-block-constructs'. START-PROPERTY is applied
1192 to the text matching START-REGEX-OR-FUN, END-PROPERTY to END-REGEX-OR-FUN, and
1193 MIDDLE-PROPERTY to the text in between the two. The value of *-PROPERTY is the
1194 `match-data' when the regexp was matched to the text. In the case of
1195 MIDDLE-PROPERTY, the value is a false match data of the form '(begin end), with
1196 begin and end set to the edges of the \"middle\" text. This makes fontification
1197 easier.")
1199 (defun markdown-text-property-at-point (prop)
1200 (get-text-property (point) prop))
1202 (defsubst markdown-maybe-funcall-regexp (object &optional arg)
1203 (cond ((functionp object)
1204 (if arg (funcall object arg) (funcall object)))
1205 ((stringp object) object)
1206 (t (error "Object cannot be turned into regex"))))
1208 (defsubst markdown-get-start-fence-regexp ()
1209 "Return regexp to find all \"start\" sections of fenced block constructs.
1210 Which construct is actually contained in the match must be found separately."
1211 (mapconcat
1212 #'identity
1213 (mapcar (lambda (entry) (markdown-maybe-funcall-regexp (caar entry)))
1214 markdown-fenced-block-pairs)
1215 "\\|"))
1217 (defun markdown-get-fenced-block-begin-properties ()
1218 (cl-mapcar (lambda (entry) (cl-cadar entry)) markdown-fenced-block-pairs))
1220 (defun markdown-get-fenced-block-end-properties ()
1221 (cl-mapcar (lambda (entry) (cl-cadadr entry)) markdown-fenced-block-pairs))
1223 (defun markdown-get-fenced-block-middle-properties ()
1224 (cl-mapcar #'cl-third markdown-fenced-block-pairs))
1226 (defun markdown-find-previous-prop (prop &optional lim)
1227 "Find previous place where property PROP is non-nil, up to LIM.
1228 Return a cons of (pos . property). pos is point if point contains
1229 non-nil PROP."
1230 (let ((res
1231 (if (get-text-property (point) prop) (point)
1232 (previous-single-property-change
1233 (point) prop nil (or lim (point-min))))))
1234 (when (and (not (get-text-property res prop))
1235 (> res (point-min))
1236 (get-text-property (1- res) prop))
1237 (cl-decf res))
1238 (when (and res (get-text-property res prop)) (cons res prop))))
1240 (defun markdown-find-next-prop (prop &optional lim)
1241 "Find next place where property PROP is non-nil, up to LIM.
1242 Return a cons of (POS . PROPERTY) where POS is point if point
1243 contains non-nil PROP."
1244 (let ((res
1245 (if (get-text-property (point) prop) (point)
1246 (next-single-property-change
1247 (point) prop nil (or lim (point-max))))))
1248 (when (and res (get-text-property res prop)) (cons res prop))))
1250 (defun markdown-min-of-seq (map-fn seq)
1251 "Apply MAP-FN to SEQ and return element of SEQ with minimum value of MAP-FN."
1252 (cl-loop for el in seq
1253 with min = 1.0e+INF ; infinity
1254 with min-el = nil
1255 do (let ((res (funcall map-fn el)))
1256 (when (< res min)
1257 (setq min res)
1258 (setq min-el el)))
1259 finally return min-el))
1261 (defun markdown-max-of-seq (map-fn seq)
1262 "Apply MAP-FN to SEQ and return element of SEQ with maximum value of MAP-FN."
1263 (cl-loop for el in seq
1264 with max = -1.0e+INF ; negative infinity
1265 with max-el = nil
1266 do (let ((res (funcall map-fn el)))
1267 (when (and res (> res max))
1268 (setq max res)
1269 (setq max-el el)))
1270 finally return max-el))
1272 (defun markdown-find-previous-block ()
1273 "Find previous block.
1274 Detect whether `markdown-syntax-propertize-fenced-block-constructs' was
1275 unable to propertize the entire block, but was able to propertize the beginning
1276 of the block. If so, return a cons of (pos . property) where the beginning of
1277 the block was propertized."
1278 (let ((start-pt (point))
1279 (closest-open
1280 (markdown-max-of-seq
1281 #'car
1282 (cl-remove-if
1283 #'null
1284 (cl-mapcar
1285 #'markdown-find-previous-prop
1286 (markdown-get-fenced-block-begin-properties))))))
1287 (when closest-open
1288 (let* ((length-of-open-match
1289 (let ((match-d
1290 (get-text-property (car closest-open) (cdr closest-open))))
1291 (- (cl-fourth match-d) (cl-third match-d))))
1292 (end-regexp
1293 (markdown-maybe-funcall-regexp
1294 (cl-caadr
1295 (cl-find-if
1296 (lambda (entry) (eq (cl-cadar entry) (cdr closest-open)))
1297 markdown-fenced-block-pairs))
1298 length-of-open-match))
1299 (end-prop-loc
1300 (save-excursion
1301 (save-match-data
1302 (goto-char (car closest-open))
1303 (and (re-search-forward end-regexp start-pt t)
1304 (match-beginning 0))))))
1305 (and (not end-prop-loc) closest-open)))))
1307 (defun markdown-get-fenced-block-from-start (prop)
1308 "Return limits of an enclosing fenced block from its start, using PROP.
1309 Return value is a list usable as `match-data'."
1310 (catch 'no-rest-of-block
1311 (let* ((correct-entry
1312 (cl-find-if
1313 (lambda (entry) (eq (cl-cadar entry) prop))
1314 markdown-fenced-block-pairs))
1315 (begin-of-begin (cl-first (markdown-text-property-at-point prop)))
1316 (middle-prop (cl-third correct-entry))
1317 (end-prop (cl-cadadr correct-entry))
1318 (end-of-end
1319 (save-excursion
1320 (goto-char (match-end 0)) ; end of begin
1321 (unless (eobp) (forward-char))
1322 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
1323 (if (not mid-prop-v) ; no middle
1324 (progn
1325 ;; try to find end by advancing one
1326 (let ((end-prop-v
1327 (markdown-text-property-at-point end-prop)))
1328 (if end-prop-v (cl-second end-prop-v)
1329 (throw 'no-rest-of-block nil))))
1330 (set-match-data mid-prop-v)
1331 (goto-char (match-end 0)) ; end of middle
1332 (beginning-of-line) ; into end
1333 (cl-second (markdown-text-property-at-point end-prop)))))))
1334 (list begin-of-begin end-of-end))))
1336 (defun markdown-get-fenced-block-from-middle (prop)
1337 "Return limits of an enclosing fenced block from its middle, using PROP.
1338 Return value is a list usable as `match-data'."
1339 (let* ((correct-entry
1340 (cl-find-if
1341 (lambda (entry) (eq (cl-third entry) prop))
1342 markdown-fenced-block-pairs))
1343 (begin-prop (cl-cadar correct-entry))
1344 (begin-of-begin
1345 (save-excursion
1346 (goto-char (match-beginning 0))
1347 (unless (bobp) (forward-line -1))
1348 (beginning-of-line)
1349 (cl-first (markdown-text-property-at-point begin-prop))))
1350 (end-prop (cl-cadadr correct-entry))
1351 (end-of-end
1352 (save-excursion
1353 (goto-char (match-end 0))
1354 (beginning-of-line)
1355 (cl-second (markdown-text-property-at-point end-prop)))))
1356 (list begin-of-begin end-of-end)))
1358 (defun markdown-get-fenced-block-from-end (prop)
1359 "Return limits of an enclosing fenced block from its end, using PROP.
1360 Return value is a list usable as `match-data'."
1361 (let* ((correct-entry
1362 (cl-find-if
1363 (lambda (entry) (eq (cl-cadadr entry) prop))
1364 markdown-fenced-block-pairs))
1365 (end-of-end (cl-second (markdown-text-property-at-point prop)))
1366 (middle-prop (cl-third correct-entry))
1367 (begin-prop (cl-cadar correct-entry))
1368 (begin-of-begin
1369 (save-excursion
1370 (goto-char (match-beginning 0)) ; beginning of end
1371 (unless (bobp) (backward-char)) ; into middle
1372 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
1373 (if (not mid-prop-v)
1374 (progn
1375 (beginning-of-line)
1376 (cl-first (markdown-text-property-at-point begin-prop)))
1377 (set-match-data mid-prop-v)
1378 (goto-char (match-beginning 0)) ; beginning of middle
1379 (unless (bobp) (forward-line -1)) ; into beginning
1380 (beginning-of-line)
1381 (cl-first (markdown-text-property-at-point begin-prop)))))))
1382 (list begin-of-begin end-of-end)))
1384 (defun markdown-get-enclosing-fenced-block-construct (&optional pos)
1385 "Get \"fake\" match data for block enclosing POS.
1386 Returns fake match data which encloses the start, middle, and end
1387 of the block construct enclosing POS, if it exists. Used in
1388 `markdown-code-block-at-pos'."
1389 (save-excursion
1390 (when pos (goto-char pos))
1391 (beginning-of-line)
1392 (car
1393 (cl-remove-if
1394 #'null
1395 (cl-mapcar
1396 (lambda (fun-and-prop)
1397 (cl-destructuring-bind (fun prop) fun-and-prop
1398 (when prop
1399 (save-match-data
1400 (set-match-data (markdown-text-property-at-point prop))
1401 (funcall fun prop)))))
1402 `((markdown-get-fenced-block-from-start
1403 ,(cl-find-if
1404 #'markdown-text-property-at-point
1405 (markdown-get-fenced-block-begin-properties)))
1406 (markdown-get-fenced-block-from-middle
1407 ,(cl-find-if
1408 #'markdown-text-property-at-point
1409 (markdown-get-fenced-block-middle-properties)))
1410 (markdown-get-fenced-block-from-end
1411 ,(cl-find-if
1412 #'markdown-text-property-at-point
1413 (markdown-get-fenced-block-end-properties)))))))))
1415 (defun markdown-propertize-end-match (reg end fence-spec middle-begin)
1416 "Get match for REG up to END, if exists, and propertize appropriately.
1417 FENCE-SPEC is an entry in `markdown-fenced-block-pairs' and
1418 MIDDLE-BEGIN is the start of the \"middle\" section of the block."
1419 (when (re-search-forward reg end t)
1420 (let ((close-begin (match-beginning 0)) ; Start of closing line.
1421 (close-end (match-end 0)) ; End of closing line.
1422 (close-data (match-data t))) ; Match data for closing line.
1423 ;; Propertize middle section of fenced block.
1424 (put-text-property middle-begin close-begin
1425 (cl-third fence-spec)
1426 (list middle-begin close-begin))
1427 ;; If the block is a YAML block, propertize the declarations inside
1428 (markdown-syntax-propertize-yaml-metadata middle-begin close-begin)
1429 ;; Propertize closing line of fenced block.
1430 (put-text-property close-begin close-end
1431 (cl-cadadr fence-spec) close-data))))
1433 (defun markdown-syntax-propertize-fenced-block-constructs (start end)
1434 "Propertize according to `markdown-fenced-block-pairs' from START to END.
1435 If unable to propertize an entire block (if the start of a block is within START
1436 and END, but the end of the block is not), propertize the start section of a
1437 block, then in a subsequent call propertize both middle and end by finding the
1438 start which was previously propertized."
1439 (let ((start-reg (markdown-get-start-fence-regexp)))
1440 (save-excursion
1441 (goto-char start)
1442 ;; start from previous unclosed block, if exists
1443 (let ((prev-begin-block (markdown-find-previous-block)))
1444 (when prev-begin-block
1445 (let* ((correct-entry
1446 (cl-find-if (lambda (entry)
1447 (eq (cdr prev-begin-block) (cl-cadar entry)))
1448 markdown-fenced-block-pairs))
1449 (enclosed-text-start (1+ (car prev-begin-block)))
1450 (start-length
1451 (save-excursion
1452 (goto-char (car prev-begin-block))
1453 (string-match
1454 (markdown-maybe-funcall-regexp
1455 (caar correct-entry))
1456 (buffer-substring
1457 (point-at-bol) (point-at-eol)))
1458 (- (match-end 1) (match-beginning 1))))
1459 (end-reg (markdown-maybe-funcall-regexp
1460 (cl-caadr correct-entry) start-length)))
1461 (markdown-propertize-end-match
1462 end-reg end correct-entry enclosed-text-start))))
1463 ;; find all new blocks within region
1464 (while (re-search-forward start-reg end t)
1465 ;; we assume the opening constructs take up (only) an entire line,
1466 ;; so we re-check the current line
1467 (let* ((cur-line (buffer-substring (point-at-bol) (point-at-eol)))
1468 ;; find entry in `markdown-fenced-block-pairs' corresponding
1469 ;; to regex which was matched
1470 (correct-entry
1471 (cl-find-if
1472 (lambda (fenced-pair)
1473 (string-match-p
1474 (markdown-maybe-funcall-regexp (caar fenced-pair))
1475 cur-line))
1476 markdown-fenced-block-pairs))
1477 (enclosed-text-start
1478 (save-excursion (1+ (point-at-eol))))
1479 (end-reg
1480 (markdown-maybe-funcall-regexp
1481 (cl-caadr correct-entry)
1482 (if (and (match-beginning 1) (match-end 1))
1483 (- (match-end 1) (match-beginning 1))
1484 0))))
1485 ;; get correct match data
1486 (save-excursion
1487 (beginning-of-line)
1488 (re-search-forward
1489 (markdown-maybe-funcall-regexp (caar correct-entry))
1490 (point-at-eol)))
1491 ;; mark starting, even if ending is outside of region
1492 (put-text-property (match-beginning 0) (match-end 0)
1493 (cl-cadar correct-entry) (match-data t))
1494 (markdown-propertize-end-match
1495 end-reg end correct-entry enclosed-text-start))))))
1497 (defun markdown-syntax-propertize-blockquotes (start end)
1498 "Match blockquotes from START to END."
1499 (save-excursion
1500 (goto-char start)
1501 (while (and (re-search-forward markdown-regex-blockquote end t)
1502 (not (markdown-code-block-at-pos (match-beginning 0))))
1503 (put-text-property (match-beginning 0) (match-end 0)
1504 'markdown-blockquote
1505 (match-data t)))))
1507 (defun markdown-syntax-propertize-hrs (start end)
1508 "Match horizontal rules from START to END."
1509 (save-excursion
1510 (goto-char start)
1511 (while (re-search-forward markdown-regex-hr end t)
1512 (unless (or (markdown-on-heading-p)
1513 (markdown-code-block-at-point-p))
1514 (put-text-property (match-beginning 0) (match-end 0)
1515 'markdown-hr
1516 (match-data t))))))
1518 (defun markdown-syntax-propertize-yaml-metadata (start end)
1519 "Propertize elements inside YAML metadata blocks from START to END.
1520 Assumes region from START and END is already known to be the interior
1521 region of a YAML metadata block as propertized by
1522 `markdown-syntax-propertize-fenced-block-constructs'."
1523 (save-excursion
1524 (goto-char start)
1525 (cl-loop
1526 while (re-search-forward markdown-regex-declarative-metadata end t)
1527 do (progn
1528 (put-text-property (match-beginning 1) (match-end 1)
1529 'markdown-metadata-key (match-data t))
1530 (put-text-property (match-beginning 2) (match-end 2)
1531 'markdown-metadata-markup (match-data t))
1532 (put-text-property (match-beginning 3) (match-end 3)
1533 'markdown-metadata-value (match-data t))))))
1535 (defun markdown-syntax-propertize-headings (start end)
1536 "Match headings of type SYMBOL with REGEX from START to END."
1537 (goto-char start)
1538 (while (re-search-forward markdown-regex-header end t)
1539 (unless (markdown-code-block-at-pos (match-beginning 0))
1540 (put-text-property
1541 (match-beginning 0) (match-end 0) 'markdown-heading
1542 (match-data t))
1543 (put-text-property
1544 (match-beginning 0) (match-end 0)
1545 (cond ((match-string-no-properties 2) 'markdown-heading-1-setext)
1546 ((match-string-no-properties 3) 'markdown-heading-2-setext)
1547 (t (let ((atx-level (length (markdown-trim-whitespace
1548 (match-string-no-properties 4)))))
1549 (intern (format "markdown-heading-%d-atx" atx-level)))))
1550 (match-data t)))))
1552 (defun markdown-syntax-propertize-comments (start end)
1553 "Match HTML comments from the START to END."
1554 (let* ((in-comment (nth 4 (syntax-ppss))))
1555 (goto-char start)
1556 (cond
1557 ;; Comment start
1558 ((and (not in-comment)
1559 (re-search-forward markdown-regex-comment-start end t)
1560 (not (markdown-inline-code-at-point-p))
1561 (not (markdown-code-block-at-point-p)))
1562 (let ((open-beg (match-beginning 0)))
1563 (put-text-property open-beg (1+ open-beg)
1564 'syntax-table (string-to-syntax "<"))
1565 (markdown-syntax-propertize-comments
1566 (min (1+ (match-end 0)) end (point-max)) end)))
1567 ;; Comment end
1568 ((and in-comment
1569 (re-search-forward markdown-regex-comment-end end t))
1570 (let ((comment-end (match-end 0))
1571 (comment-begin (nth 8 (syntax-ppss))))
1572 (put-text-property (1- comment-end) comment-end
1573 'syntax-table (string-to-syntax ">"))
1574 ;; Remove any other text properties inside the comment
1575 (remove-text-properties comment-begin comment-end
1576 markdown--syntax-properties)
1577 (put-text-property comment-begin comment-end
1578 'markdown-comment (list comment-begin comment-end))
1579 (markdown-syntax-propertize-comments
1580 (min (1+ comment-end) end (point-max)) end)))
1581 ;; Nothing found
1582 (t nil))))
1584 (defvar markdown--syntax-properties
1585 (list 'markdown-tilde-fence-begin nil
1586 'markdown-tilde-fence-end nil
1587 'markdown-fenced-code nil
1588 'markdown-yaml-metadata-begin nil
1589 'markdown-yaml-metadata-end nil
1590 'markdown-yaml-metadata-section nil
1591 'markdown-gfm-block-begin nil
1592 'markdown-gfm-block-end nil
1593 'markdown-gfm-code nil
1594 'markdown-list-item nil
1595 'markdown-pre nil
1596 'markdown-blockquote nil
1597 'markdown-hr nil
1598 'markdown-comment nil
1599 'markdown-heading nil
1600 'markdown-heading-1-setext nil
1601 'markdown-heading-2-setext nil
1602 'markdown-heading-1-atx nil
1603 'markdown-heading-2-atx nil
1604 'markdown-heading-3-atx nil
1605 'markdown-heading-4-atx nil
1606 'markdown-heading-5-atx nil
1607 'markdown-heading-6-atx nil
1608 'markdown-metadata-key nil
1609 'markdown-metadata-value nil
1610 'markdown-metadata-markup nil)
1611 "Property list of all Markdown syntactic properties.")
1613 (defun markdown-syntax-propertize (start end)
1614 "Function used as `syntax-propertize-function'.
1615 START and END delimit region to propertize."
1616 (with-silent-modifications
1617 (save-excursion
1618 (remove-text-properties start end markdown--syntax-properties)
1619 (markdown-syntax-propertize-fenced-block-constructs start end)
1620 (markdown-syntax-propertize-list-items start end)
1621 (markdown-syntax-propertize-pre-blocks start end)
1622 (markdown-syntax-propertize-blockquotes start end)
1623 (markdown-syntax-propertize-headings start end)
1624 (markdown-syntax-propertize-hrs start end)
1625 (markdown-syntax-propertize-comments start end))))
1628 ;;; Markup Hiding
1630 (defconst markdown-markup-properties
1631 '(face markdown-markup-face invisible markdown-markup)
1632 "List of properties and values to apply to markup.")
1634 (defconst markdown-language-keyword-properties
1635 '(face markdown-language-keyword-face invisible markdown-markup)
1636 "List of properties and values to apply to code block language names.")
1638 (defconst markdown-language-info-properties
1639 '(face markdown-language-info-face invisible markdown-markup)
1640 "List of properties and values to apply to code block language info strings.")
1642 (defconst markdown-include-title-properties
1643 '(face markdown-link-title-face invisible markdown-markup)
1644 "List of properties and values to apply to included code titles.")
1646 (defcustom markdown-hide-markup nil
1647 "Determines whether markup in the buffer will be hidden.
1648 When set to nil, all markup is displayed in the buffer as it
1649 appears in the file. An exception is when `markdown-hide-urls'
1650 is non-nil.
1651 Set this to a non-nil value to turn this feature on by default.
1652 You can interactively toggle the value of this variable with
1653 `markdown-toggle-markup-hiding', \\[markdown-toggle-markup-hiding],
1654 or from the Markdown > Show & Hide menu.
1656 Markup hiding works by adding text properties to positions in the
1657 buffer---either the `invisible' property or the `display' property
1658 in cases where alternative glyphs are used (e.g., list bullets).
1659 This does not, however, affect printing or other output.
1660 Functions such as `htmlfontify-buffer' and `ps-print-buffer' will
1661 not honor these text properties. For printing, it would be better
1662 to first convert to HTML or PDF (e.g,. using Pandoc)."
1663 :group 'markdown
1664 :type 'boolean
1665 :safe 'booleanp
1666 :package-version '(markdown-mode . "2.3"))
1667 (make-variable-buffer-local 'markdown-hide-markup)
1669 (defun markdown-toggle-markup-hiding (&optional arg)
1670 "Toggle the display or hiding of markup.
1671 With a prefix argument ARG, enable markup hiding if ARG is positive,
1672 and disable it otherwise.
1673 See `markdown-hide-markup' for additional details."
1674 (interactive (list (or current-prefix-arg 'toggle)))
1675 (setq markdown-hide-markup
1676 (if (eq arg 'toggle)
1677 (not markdown-hide-markup)
1678 (> (prefix-numeric-value arg) 0)))
1679 (if markdown-hide-markup
1680 (progn (add-to-invisibility-spec 'markdown-markup)
1681 (message "markdown-mode markup hiding enabled"))
1682 (progn (remove-from-invisibility-spec 'markdown-markup)
1683 (message "markdown-mode markup hiding disabled")))
1684 (markdown-reload-extensions))
1687 ;;; Font Lock =================================================================
1689 (require 'font-lock)
1691 (defvar markdown-italic-face 'markdown-italic-face
1692 "Face name to use for italic text.")
1694 (defvar markdown-bold-face 'markdown-bold-face
1695 "Face name to use for bold text.")
1697 (defvar markdown-strike-through-face 'markdown-strike-through-face
1698 "Face name to use for strike-through text.")
1700 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
1701 "Face name to use as a base for header delimiters.")
1703 (defvar markdown-header-rule-face 'markdown-header-rule-face
1704 "Face name to use as a base for header rules.")
1706 (defvar markdown-header-face 'markdown-header-face
1707 "Face name to use as a base for headers.")
1709 (defvar markdown-header-face-1 'markdown-header-face-1
1710 "Face name to use for level-1 headers.")
1712 (defvar markdown-header-face-2 'markdown-header-face-2
1713 "Face name to use for level-2 headers.")
1715 (defvar markdown-header-face-3 'markdown-header-face-3
1716 "Face name to use for level-3 headers.")
1718 (defvar markdown-header-face-4 'markdown-header-face-4
1719 "Face name to use for level-4 headers.")
1721 (defvar markdown-header-face-5 'markdown-header-face-5
1722 "Face name to use for level-5 headers.")
1724 (defvar markdown-header-face-6 'markdown-header-face-6
1725 "Face name to use for level-6 headers.")
1727 (defvar markdown-inline-code-face 'markdown-inline-code-face
1728 "Face name to use for inline code.")
1730 (defvar markdown-list-face 'markdown-list-face
1731 "Face name to use for list markers.")
1733 (defvar markdown-blockquote-face 'markdown-blockquote-face
1734 "Face name to use for blockquote.")
1736 (defvar markdown-pre-face 'markdown-pre-face
1737 "Face name to use for preformatted text.")
1739 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
1740 "Face name to use for programming language identifiers.")
1742 (defvar markdown-language-info-face 'markdown-language-info-face
1743 "Face name to use for programming info strings.")
1745 (defvar markdown-link-face 'markdown-link-face
1746 "Face name to use for links.")
1748 (defvar markdown-missing-link-face 'markdown-missing-link-face
1749 "Face name to use for links where the linked file does not exist.")
1751 (defvar markdown-reference-face 'markdown-reference-face
1752 "Face name to use for reference.")
1754 (defvar markdown-footnote-marker-face 'markdown-footnote-marker-face
1755 "Face name to use for footnote markers.")
1757 (defvar markdown-url-face 'markdown-url-face
1758 "Face name to use for URLs.")
1760 (defvar markdown-link-title-face 'markdown-link-title-face
1761 "Face name to use for reference link titles.")
1763 (defvar markdown-line-break-face 'markdown-line-break-face
1764 "Face name to use for hard line breaks.")
1766 (defvar markdown-comment-face 'markdown-comment-face
1767 "Face name to use for HTML comments.")
1769 (defvar markdown-math-face 'markdown-math-face
1770 "Face name to use for LaTeX expressions.")
1772 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
1773 "Face name to use for metadata keys.")
1775 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
1776 "Face name to use for metadata values.")
1778 (defvar markdown-gfm-checkbox-face 'markdown-gfm-checkbox-face
1779 "Face name to use for GFM checkboxes.")
1781 (defvar markdown-highlight-face 'markdown-highlight-face
1782 "Face name to use for mouse highlighting.")
1784 (defvar markdown-markup-face 'markdown-markup-face
1785 "Face name to use for markup elements.")
1787 (make-obsolete-variable 'markdown-italic-face "Use face name directly" "v2.4")
1788 (make-obsolete-variable 'markdown-bold-face "Use face name directly" "v2.4")
1789 (make-obsolete-variable 'markdown-strike-through-face "Use face name directly" "v2.4")
1790 (make-obsolete-variable 'markdown-header-delimiter-face "Use face name directly" "v2.4")
1791 (make-obsolete-variable 'markdown-header-rule-face "Use face name directly" "v2.4")
1792 (make-obsolete-variable 'markdown-header-face "Use face name directly" "v2.4")
1793 (make-obsolete-variable 'markdown-header-face-1 "Use face name directly" "v2.4")
1794 (make-obsolete-variable 'markdown-header-face-2 "Use face name directly" "v2.4")
1795 (make-obsolete-variable 'markdown-header-face-3 "Use face name directly" "v2.4")
1796 (make-obsolete-variable 'markdown-header-face-4 "Use face name directly" "v2.4")
1797 (make-obsolete-variable 'markdown-header-face-5 "Use face name directly" "v2.4")
1798 (make-obsolete-variable 'markdown-header-face-6 "Use face name directly" "v2.4")
1799 (make-obsolete-variable 'markdown-inline-code-face "Use face name directly" "v2.4")
1800 (make-obsolete-variable 'markdown-list-face "Use face name directly" "v2.4")
1801 (make-obsolete-variable 'markdown-blockquote-face "Use face name directly" "v2.4")
1802 (make-obsolete-variable 'markdown-pre-face "Use face name directly" "v2.4")
1803 (make-obsolete-variable 'markdown-language-keyword-face "Use face name directly" "v2.4")
1804 (make-obsolete-variable 'markdown-language-info-face "Use face name directly" "v2.4")
1805 (make-obsolete-variable 'markdown-link-face "Use face name directly" "v2.4")
1806 (make-obsolete-variable 'markdown-missing-link-face "Use face name directly" "v2.4")
1807 (make-obsolete-variable 'markdown-reference-face "Use face name directly" "v2.4")
1808 (make-obsolete-variable 'markdown-footnote-marker-face "Use face name directly" "v2.4")
1809 (make-obsolete-variable 'markdown-url-face "Use face name directly" "v2.4")
1810 (make-obsolete-variable 'markdown-link-title-face "Use face name directly" "v2.4")
1811 (make-obsolete-variable 'markdown-line-break-face "Use face name directly" "v2.4")
1812 (make-obsolete-variable 'markdown-comment-face "Use face name directly" "v2.4")
1813 (make-obsolete-variable 'markdown-math-face "Use face name directly" "v2.4")
1814 (make-obsolete-variable 'markdown-metadata-key-face "Use face name directly" "v2.4")
1815 (make-obsolete-variable 'markdown-metadata-value-face "Use face name directly" "v2.4")
1816 (make-obsolete-variable 'markdown-gfm-checkbox-face "Use face name directly" "v2.4")
1817 (make-obsolete-variable 'markdown-highlight-face "Use face name directly" "v2.4")
1818 (make-obsolete-variable 'markdown-markup-face "Use face name directly" "v2.4")
1820 (defgroup markdown-faces nil
1821 "Faces used in Markdown Mode"
1822 :group 'markdown
1823 :group 'faces)
1825 (defface markdown-italic-face
1826 '((t (:inherit italic)))
1827 "Face for italic text."
1828 :group 'markdown-faces)
1830 (defface markdown-bold-face
1831 '((t (:inherit bold)))
1832 "Face for bold text."
1833 :group 'markdown-faces)
1835 (defface markdown-strike-through-face
1836 '((t (:strike-through t)))
1837 "Face for strike-through text."
1838 :group 'markdown-faces)
1840 (defface markdown-markup-face
1841 '((t (:inherit shadow :slant normal :weight normal)))
1842 "Face for markup elements."
1843 :group 'markdown-faces)
1845 (defface markdown-header-rule-face
1846 '((t (:inherit markdown-markup-face)))
1847 "Base face for headers rules."
1848 :group 'markdown-faces)
1850 (defface markdown-header-delimiter-face
1851 '((t (:inherit markdown-markup-face)))
1852 "Base face for headers hash delimiter."
1853 :group 'markdown-faces)
1855 (defface markdown-list-face
1856 '((t (:inherit markdown-markup-face)))
1857 "Face for list item markers."
1858 :group 'markdown-faces)
1860 (defface markdown-blockquote-face
1861 '((t (:inherit font-lock-doc-face)))
1862 "Face for blockquote sections."
1863 :group 'markdown-faces)
1865 (defface markdown-code-face
1866 '((t (:inherit fixed-pitch)))
1867 "Face for inline code, pre blocks, and fenced code blocks.
1868 This may be used, for example, to add a contrasting background to
1869 inline code fragments and code blocks."
1870 :group 'markdown-faces)
1872 (defface markdown-inline-code-face
1873 '((t (:inherit (markdown-code-face font-lock-constant-face))))
1874 "Face for inline code."
1875 :group 'markdown-faces)
1877 (defface markdown-pre-face
1878 '((t (:inherit (markdown-code-face font-lock-constant-face))))
1879 "Face for preformatted text."
1880 :group 'markdown-faces)
1882 (defface markdown-table-face
1883 '((t (:inherit (markdown-code-face))))
1884 "Face for tables."
1885 :group 'markdown-faces)
1887 (defface markdown-language-keyword-face
1888 '((t (:inherit font-lock-type-face)))
1889 "Face for programming language identifiers."
1890 :group 'markdown-faces)
1892 (defface markdown-language-info-face
1893 '((t (:inherit font-lock-string-face)))
1894 "Face for programming language info strings."
1895 :group 'markdown-faces)
1897 (defface markdown-link-face
1898 '((t (:inherit link)))
1899 "Face for links."
1900 :group 'markdown-faces)
1902 (defface markdown-missing-link-face
1903 '((t (:inherit font-lock-warning-face)))
1904 "Face for missing links."
1905 :group 'markdown-faces)
1907 (defface markdown-reference-face
1908 '((t (:inherit markdown-markup-face)))
1909 "Face for link references."
1910 :group 'markdown-faces)
1912 (define-obsolete-face-alias 'markdown-footnote-face
1913 'markdown-footnote-marker-face "v2.3")
1915 (defface markdown-footnote-marker-face
1916 '((t (:inherit markdown-markup-face)))
1917 "Face for footnote markers."
1918 :group 'markdown-faces)
1920 (defface markdown-footnote-text-face
1921 '((t (:inherit font-lock-comment-face)))
1922 "Face for footnote text."
1923 :group 'markdown-faces)
1925 (defface markdown-url-face
1926 '((t (:inherit font-lock-string-face)))
1927 "Face for URLs that are part of markup.
1928 For example, this applies to URLs in inline links:
1929 [link text](http://example.com/)."
1930 :group 'markdown-faces)
1932 (defface markdown-plain-url-face
1933 '((t (:inherit markdown-link-face)))
1934 "Face for URLs that are also links.
1935 For example, this applies to plain angle bracket URLs:
1936 <http://example.com/>."
1937 :group 'markdown-faces)
1939 (defface markdown-link-title-face
1940 '((t (:inherit font-lock-comment-face)))
1941 "Face for reference link titles."
1942 :group 'markdown-faces)
1944 (defface markdown-line-break-face
1945 '((t (:inherit font-lock-constant-face :underline t)))
1946 "Face for hard line breaks."
1947 :group 'markdown-faces)
1949 (defface markdown-comment-face
1950 '((t (:inherit font-lock-comment-face)))
1951 "Face for HTML comments."
1952 :group 'markdown-faces)
1954 (defface markdown-math-face
1955 '((t (:inherit font-lock-string-face)))
1956 "Face for LaTeX expressions."
1957 :group 'markdown-faces)
1959 (defface markdown-metadata-key-face
1960 '((t (:inherit font-lock-variable-name-face)))
1961 "Face for metadata keys."
1962 :group 'markdown-faces)
1964 (defface markdown-metadata-value-face
1965 '((t (:inherit font-lock-string-face)))
1966 "Face for metadata values."
1967 :group 'markdown-faces)
1969 (defface markdown-gfm-checkbox-face
1970 '((t (:inherit font-lock-builtin-face)))
1971 "Face for GFM checkboxes."
1972 :group 'markdown-faces)
1974 (defface markdown-highlight-face
1975 '((t (:inherit highlight)))
1976 "Face for mouse highlighting."
1977 :group 'markdown-faces)
1979 (defface markdown-hr-face
1980 '((t (:inherit markdown-markup-face)))
1981 "Face for horizontal rules."
1982 :group 'markdown-faces)
1984 (defface markdown-html-tag-name-face
1985 '((t (:inherit font-lock-type-face)))
1986 "Face for HTML tag names."
1987 :group 'markdown-faces)
1989 (defface markdown-html-tag-delimiter-face
1990 '((t (:inherit markdown-markup-face)))
1991 "Face for HTML tag delimiters."
1992 :group 'markdown-faces)
1994 (defface markdown-html-attr-name-face
1995 '((t (:inherit font-lock-variable-name-face)))
1996 "Face for HTML attribute names."
1997 :group 'markdown-faces)
1999 (defface markdown-html-attr-value-face
2000 '((t (:inherit font-lock-string-face)))
2001 "Face for HTML attribute values."
2002 :group 'markdown-faces)
2004 (defface markdown-html-entity-face
2005 '((t (:inherit font-lock-variable-name-face)))
2006 "Face for HTML entities."
2007 :group 'markdown-faces)
2009 (defcustom markdown-header-scaling nil
2010 "Whether to use variable-height faces for headers.
2011 When non-nil, `markdown-header-face' will inherit from
2012 `variable-pitch' and the scaling values in
2013 `markdown-header-scaling-values' will be applied to
2014 headers of levels one through six respectively."
2015 :type 'boolean
2016 :initialize 'custom-initialize-default
2017 :set (lambda (symbol value)
2018 (set-default symbol value)
2019 (markdown-update-header-faces value))
2020 :group 'markdown-faces
2021 :package-version '(markdown-mode . "2.2"))
2023 (defcustom markdown-header-scaling-values
2024 '(2.0 1.7 1.4 1.1 1.0 1.0)
2025 "List of scaling values for headers of level one through six.
2026 Used when `markdown-header-scaling' is non-nil."
2027 :type 'list
2028 :initialize 'custom-initialize-default
2029 :set (lambda (symbol value)
2030 (set-default symbol value)
2031 (markdown-update-header-faces markdown-header-scaling value))
2032 :group 'markdown-faces)
2034 (defun markdown-make-header-faces ()
2035 "Build the faces used for Markdown headers."
2036 (let ((inherit-faces '(font-lock-function-name-face)))
2037 (when markdown-header-scaling
2038 (setq inherit-faces (cons 'variable-pitch inherit-faces)))
2039 (defface markdown-header-face
2040 `((t (:inherit ,inherit-faces :weight bold)))
2041 "Base face for headers."
2042 :group 'markdown-faces))
2043 (dotimes (num 6)
2044 (let* ((num1 (1+ num))
2045 (face-name (intern (format "markdown-header-face-%s" num1)))
2046 (scale (if markdown-header-scaling
2047 (float (nth num markdown-header-scaling-values))
2048 1.0)))
2049 (eval
2050 `(defface ,face-name
2051 '((t (:inherit markdown-header-face :height ,scale)))
2052 (format "Face for level %s headers.
2053 You probably don't want to customize this face directly. Instead
2054 you can customize the base face `markdown-header-face' or the
2055 variable-height variable `markdown-header-scaling'." ,num1)
2056 :group 'markdown-faces)))))
2058 (markdown-make-header-faces)
2060 (defun markdown-update-header-faces (&optional scaling scaling-values)
2061 "Update header faces, depending on if header SCALING is desired.
2062 If so, use given list of SCALING-VALUES relative to the baseline
2063 size of `markdown-header-face'."
2064 (dotimes (num 6)
2065 (let* ((face-name (intern (format "markdown-header-face-%s" (1+ num))))
2066 (scale (cond ((not scaling) 1.0)
2067 (scaling-values (float (nth num scaling-values)))
2068 (t (float (nth num markdown-header-scaling-values))))))
2069 (unless (get face-name 'saved-face) ; Don't update customized faces
2070 (set-face-attribute face-name nil :height scale)))))
2072 (defun markdown-syntactic-face (state)
2073 "Return font-lock face for characters with given STATE.
2074 See `font-lock-syntactic-face-function' for details."
2075 (let ((in-comment (nth 4 state)))
2076 (cond
2077 (in-comment 'markdown-comment-face)
2078 (t nil))))
2080 (defcustom markdown-list-item-bullets
2081 '("●" "◎" "○" "◆" "◇" "►" "•")
2082 "List of bullets to use for unordered lists.
2083 It can contain any number of symbols, which will be repeated.
2084 Depending on your font, some reasonable choices are:
2085 ♥ ● ◇ ✚ ✜ ☯ ◆ ♠ ♣ ♦ ❀ ◆ ◖ ▶ ► • ★ ▸."
2086 :group 'markdown
2087 :type '(repeat (string :tag "Bullet character"))
2088 :package-version '(markdown-mode . "2.3"))
2090 (defun markdown--footnote-marker-properties ()
2091 "Return a font-lock facespec expression for footnote marker text."
2092 `(face markdown-footnote-marker-face
2093 ,@(when markdown-hide-markup
2094 `(display ,markdown-footnote-display))))
2096 (defun markdown--pandoc-inline-footnote-properties ()
2097 "Return a font-lock facespec expression for Pandoc inline footnote text."
2098 `(face markdown-footnote-text-face
2099 ,@(when markdown-hide-markup
2100 `(display ,markdown-footnote-display))))
2102 (defvar markdown-mode-font-lock-keywords-basic
2103 `((markdown-match-yaml-metadata-begin . ((1 'markdown-markup-face)))
2104 (markdown-match-yaml-metadata-end . ((1 'markdown-markup-face)))
2105 (markdown-match-yaml-metadata-key . ((1 'markdown-metadata-key-face)
2106 (2 'markdown-markup-face)
2107 (3 'markdown-metadata-value-face)))
2108 (markdown-match-gfm-open-code-blocks . ((1 markdown-markup-properties)
2109 (2 markdown-markup-properties nil t)
2110 (3 markdown-language-keyword-properties nil t)
2111 (4 markdown-language-info-properties nil t)
2112 (5 markdown-markup-properties nil t)))
2113 (markdown-match-gfm-close-code-blocks . ((0 markdown-markup-properties)))
2114 (markdown-fontify-gfm-code-blocks)
2115 (markdown-fontify-tables)
2116 (markdown-match-fenced-start-code-block . ((1 markdown-markup-properties)
2117 (2 markdown-markup-properties nil t)
2118 (3 markdown-language-keyword-properties nil t)
2119 (4 markdown-language-info-properties nil t)
2120 (5 markdown-markup-properties nil t)))
2121 (markdown-match-fenced-end-code-block . ((0 markdown-markup-properties)))
2122 (markdown-fontify-fenced-code-blocks)
2123 (markdown-match-pre-blocks . ((0 'markdown-pre-face)))
2124 (markdown-fontify-headings)
2125 (markdown-match-declarative-metadata . ((1 'markdown-metadata-key-face)
2126 (2 'markdown-markup-face)
2127 (3 'markdown-metadata-value-face)))
2128 (markdown-match-pandoc-metadata . ((1 'markdown-markup-face)
2129 (2 'markdown-markup-face)
2130 (3 'markdown-metadata-value-face)))
2131 (markdown-fontify-hrs)
2132 (markdown-match-code . ((1 markdown-markup-properties prepend)
2133 (2 'markdown-inline-code-face prepend)
2134 (3 markdown-markup-properties prepend)))
2135 (,markdown-regex-kbd . ((1 markdown-markup-properties)
2136 (2 'markdown-inline-code-face)
2137 (3 markdown-markup-properties)))
2138 (markdown-fontify-angle-uris)
2139 (,markdown-regex-email . 'markdown-plain-url-face)
2140 (markdown-match-html-tag . ((1 'markdown-html-tag-delimiter-face t)
2141 (2 'markdown-html-tag-name-face t)
2142 (3 'markdown-html-tag-delimiter-face t)
2143 ;; Anchored matcher for HTML tag attributes
2144 (,markdown-regex-html-attr
2145 ;; Before searching, move past tag
2146 ;; name; set limit at tag close.
2147 (progn
2148 (goto-char (match-end 2)) (match-end 3))
2150 . ((1 'markdown-html-attr-name-face)
2151 (3 'markdown-html-tag-delimiter-face nil t)
2152 (4 'markdown-html-attr-value-face nil t)))))
2153 (,markdown-regex-html-entity . 'markdown-html-entity-face)
2154 (markdown-fontify-list-items)
2155 (,markdown-regex-footnote . ((1 markdown-markup-properties) ; [^
2156 (2 (markdown--footnote-marker-properties)) ; label
2157 (3 markdown-markup-properties))) ; ]
2158 (,markdown-regex-pandoc-inline-footnote . ((1 markdown-markup-properties) ; ^
2159 (2 markdown-markup-properties) ; [
2160 (3 (markdown--pandoc-inline-footnote-properties)) ; text
2161 (4 markdown-markup-properties))) ; ]
2162 (markdown-match-includes . ((1 markdown-markup-properties)
2163 (2 markdown-markup-properties nil t)
2164 (3 markdown-include-title-properties nil t)
2165 (4 markdown-markup-properties nil t)
2166 (5 markdown-markup-properties)
2167 (6 'markdown-url-face)
2168 (7 markdown-markup-properties)))
2169 (markdown-fontify-inline-links)
2170 (markdown-fontify-reference-links)
2171 (,markdown-regex-reference-definition . ((1 'markdown-markup-face) ; [
2172 (2 'markdown-reference-face) ; label
2173 (3 'markdown-markup-face) ; ]
2174 (4 'markdown-markup-face) ; :
2175 (5 'markdown-url-face) ; url
2176 (6 'markdown-link-title-face))) ; "title" (optional)
2177 (markdown-fontify-plain-uris)
2178 ;; Math mode $..$
2179 (markdown-match-math-single . ((1 'markdown-markup-face prepend)
2180 (2 'markdown-math-face append)
2181 (3 'markdown-markup-face prepend)))
2182 ;; Math mode $$..$$
2183 (markdown-match-math-double . ((1 'markdown-markup-face prepend)
2184 (2 'markdown-math-face append)
2185 (3 'markdown-markup-face prepend)))
2186 ;; Math mode \[..\] and \\[..\\]
2187 (markdown-match-math-display . ((1 'markdown-markup-face prepend)
2188 (3 'markdown-math-face append)
2189 (4 'markdown-markup-face prepend)))
2190 (markdown-match-bold . ((1 markdown-markup-properties prepend)
2191 (2 'markdown-bold-face append)
2192 (3 markdown-markup-properties prepend)))
2193 (markdown-match-italic . ((1 markdown-markup-properties prepend)
2194 (2 'markdown-italic-face append)
2195 (3 markdown-markup-properties prepend)))
2196 (,markdown-regex-strike-through . ((3 markdown-markup-properties)
2197 (4 'markdown-strike-through-face)
2198 (5 markdown-markup-properties)))
2199 (,markdown-regex-line-break . (1 'markdown-line-break-face prepend))
2200 (markdown-fontify-sub-superscripts)
2201 (markdown-match-inline-attributes . ((0 markdown-markup-properties prepend)))
2202 (markdown-match-leanpub-sections . ((0 markdown-markup-properties)))
2203 (markdown-fontify-blockquotes)
2204 (markdown-match-wiki-link . ((0 'markdown-link-face prepend))))
2205 "Syntax highlighting for Markdown files.")
2207 (define-obsolete-variable-alias
2208 'markdown-mode-font-lock-keywords-basic
2209 'markdown-mode-font-lock-keywords "v2.4")
2211 ;; Footnotes
2212 (defvar markdown-footnote-counter 0
2213 "Counter for footnote numbers.")
2214 (make-variable-buffer-local 'markdown-footnote-counter)
2216 (defconst markdown-footnote-chars
2217 "[[:alnum:]-]"
2218 "Regular expression matching any character that is allowed in a footnote identifier.")
2220 (defconst markdown-regex-footnote-definition
2221 (concat "^ \\{0,3\\}\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:\\(?:[ \t]+\\|$\\)")
2222 "Regular expression matching a footnote definition, capturing the label.")
2225 ;;; Compatibility =============================================================
2227 (defun markdown-replace-regexp-in-string (regexp rep string)
2228 "Replace ocurrences of REGEXP with REP in STRING.
2229 This is a compatibility wrapper to provide `replace-regexp-in-string'
2230 in XEmacs 21."
2231 (if (featurep 'xemacs)
2232 (replace-in-string string regexp rep)
2233 (replace-regexp-in-string regexp rep string)))
2235 ;; `markdown-use-region-p' is a compatibility function which checks
2236 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
2237 (eval-and-compile
2238 (cond
2239 ;; Emacs 24 and newer
2240 ((fboundp 'use-region-p)
2241 (defalias 'markdown-use-region-p 'use-region-p))
2242 ;; XEmacs
2243 ((fboundp 'region-active-p)
2244 (defalias 'markdown-use-region-p 'region-active-p))))
2246 ;; Use new names for outline-mode functions in Emacs 25 and later.
2247 (eval-and-compile
2248 (defalias 'markdown-hide-sublevels
2249 (if (fboundp 'outline-hide-sublevels)
2250 'outline-hide-sublevels
2251 'hide-sublevels))
2252 (defalias 'markdown-show-all
2253 (if (fboundp 'outline-show-all)
2254 'outline-show-all
2255 'show-all))
2256 (defalias 'markdown-hide-body
2257 (if (fboundp 'outline-hide-body)
2258 'outline-hide-body
2259 'hide-body))
2260 (defalias 'markdown-show-children
2261 (if (fboundp 'outline-show-children)
2262 'outline-show-children
2263 'show-children))
2264 (defalias 'markdown-show-subtree
2265 (if (fboundp 'outline-show-subtree)
2266 'outline-show-subtree
2267 'show-subtree))
2268 (defalias 'markdown-hide-subtree
2269 (if (fboundp 'outline-hide-subtree)
2270 'outline-hide-subtree
2271 'hide-subtree)))
2273 ;; Provide directory-name-p to Emacs 24
2274 (defsubst markdown-directory-name-p (name)
2275 "Return non-nil if NAME ends with a directory separator character.
2276 Taken from `directory-name-p' from Emacs 25 and provided here for
2277 backwards compatibility."
2278 (let ((len (length name))
2279 (lastc ?.))
2280 (if (> len 0)
2281 (setq lastc (aref name (1- len))))
2282 (or (= lastc ?/)
2283 (and (memq system-type '(windows-nt ms-dos))
2284 (= lastc ?\\)))))
2286 ;; Provide a function to find files recursively in Emacs 24.
2287 (defalias 'markdown-directory-files-recursively
2288 (if (fboundp 'directory-files-recursively)
2289 'directory-files-recursively
2290 (lambda (dir regexp)
2291 "Return list of all files under DIR that have file names matching REGEXP.
2292 This function works recursively. Files are returned in \"depth first\"
2293 order, and files from each directory are sorted in alphabetical order.
2294 Each file name appears in the returned list in its absolute form.
2295 Based on `directory-files-recursively' from Emacs 25 and provided
2296 here for backwards compatibility."
2297 (let ((result nil)
2298 (files nil)
2299 ;; When DIR is "/", remote file names like "/method:" could
2300 ;; also be offered. We shall suppress them.
2301 (tramp-mode (and tramp-mode (file-remote-p (expand-file-name dir)))))
2302 (dolist (file (sort (file-name-all-completions "" dir)
2303 'string<))
2304 (unless (member file '("./" "../"))
2305 (if (markdown-directory-name-p file)
2306 (let* ((leaf (substring file 0 (1- (length file))))
2307 (full-file (expand-file-name leaf dir)))
2308 (setq result
2309 (nconc result (markdown-directory-files-recursively
2310 full-file regexp))))
2311 (when (string-match-p regexp file)
2312 (push (expand-file-name file dir) files)))))
2313 (nconc result (nreverse files))))))
2315 (defun markdown-flyspell-check-word-p ()
2316 "Return t if `flyspell' should check word just before point.
2317 Used for `flyspell-generic-check-word-predicate'."
2318 (save-excursion
2319 (goto-char (1- (point)))
2320 (not (or (markdown-code-block-at-point-p)
2321 (markdown-inline-code-at-point-p)
2322 (markdown-in-comment-p)
2323 (let ((faces (get-text-property (point) 'face)))
2324 (if (listp faces)
2325 (or (memq 'markdown-reference-face faces)
2326 (memq 'markdown-markup-face faces)
2327 (memq 'markdown-plain-url-face faces)
2328 (memq 'markdown-inline-code-face faces)
2329 (memq 'markdown-url-face faces))
2330 (memq faces '(markdown-reference-face
2331 markdown-markup-face
2332 markdown-plain-url-face
2333 markdown-inline-code-face
2334 markdown-url-face))))))))
2336 (defun markdown-font-lock-ensure ()
2337 "Provide `font-lock-ensure' in Emacs 24."
2338 (if (fboundp 'font-lock-ensure)
2339 (font-lock-ensure)
2340 (with-no-warnings
2341 ;; Suppress warning about non-interactive use of
2342 ;; `font-lock-fontify-buffer' in Emacs 25.
2343 (font-lock-fontify-buffer))))
2346 ;;; Markdown Parsing Functions ================================================
2348 (define-obsolete-function-alias
2349 'markdown-cur-line-blank 'markdown-cur-line-blank-p "v2.4")
2350 (define-obsolete-function-alias
2351 'markdown-next-line-blank 'markdown-next-line-blank-p "v2.4")
2353 (defun markdown-cur-line-blank-p ()
2354 "Return t if the current line is blank and nil otherwise."
2355 (save-excursion
2356 (beginning-of-line)
2357 (looking-at-p markdown-regex-blank-line)))
2359 (defun markdown-prev-line-blank ()
2360 "Return t if the previous line is blank and nil otherwise.
2361 If we are at the first line, then consider the previous line to be blank."
2362 (or (= (line-beginning-position) (point-min))
2363 (save-excursion
2364 (forward-line -1)
2365 (looking-at markdown-regex-blank-line))))
2367 (defun markdown-prev-line-blank-p ()
2368 "Like `markdown-prev-line-blank', but preserve `match-data'."
2369 (save-match-data (markdown-prev-line-blank)))
2371 (defun markdown-next-line-blank-p ()
2372 "Return t if the next line is blank and nil otherwise.
2373 If we are at the last line, then consider the next line to be blank."
2374 (or (= (line-end-position) (point-max))
2375 (save-excursion
2376 (forward-line 1)
2377 (markdown-cur-line-blank-p))))
2379 (defun markdown-prev-line-indent ()
2380 "Return the number of leading whitespace characters in the previous line.
2381 Return 0 if the current line is the first line in the buffer."
2382 (save-excursion
2383 (if (= (line-beginning-position) (point-min))
2385 (forward-line -1)
2386 (current-indentation))))
2388 (defun markdown-next-line-indent ()
2389 "Return the number of leading whitespace characters in the next line.
2390 Return 0 if line is the last line in the buffer."
2391 (save-excursion
2392 (if (= (line-end-position) (point-max))
2394 (forward-line 1)
2395 (current-indentation))))
2397 (defun markdown-new-baseline ()
2398 "Determine if the current line begins a new baseline level.
2399 Assume point is positioned at beginning of line."
2400 (or (looking-at markdown-regex-header)
2401 (looking-at markdown-regex-hr)
2402 (and (= (current-indentation) 0)
2403 (not (looking-at markdown-regex-list))
2404 (markdown-prev-line-blank))))
2406 (defun markdown-search-backward-baseline ()
2407 "Search backward baseline point with no indentation and not a list item."
2408 (end-of-line)
2409 (let (stop)
2410 (while (not (or stop (bobp)))
2411 (re-search-backward markdown-regex-block-separator-noindent nil t)
2412 (when (match-end 2)
2413 (goto-char (match-end 2))
2414 (cond
2415 ((markdown-new-baseline)
2416 (setq stop t))
2417 ((looking-at-p markdown-regex-list)
2418 (setq stop nil))
2419 (t (setq stop t)))))))
2421 (defun markdown-update-list-levels (marker indent levels)
2422 "Update list levels given list MARKER, block INDENT, and current LEVELS.
2423 Here, MARKER is a string representing the type of list, INDENT is an integer
2424 giving the indentation, in spaces, of the current block, and LEVELS is a
2425 list of the indentation levels of parent list items. When LEVELS is nil,
2426 it means we are at baseline (not inside of a nested list)."
2427 (cond
2428 ;; New list item at baseline.
2429 ((and marker (null levels))
2430 (setq levels (list indent)))
2431 ;; List item with greater indentation (four or more spaces).
2432 ;; Increase list level.
2433 ((and marker (>= indent (+ (car levels) 4)))
2434 (setq levels (cons indent levels)))
2435 ;; List item with greater or equal indentation (less than four spaces).
2436 ;; Do not increase list level.
2437 ((and marker (>= indent (car levels)))
2438 levels)
2439 ;; Lesser indentation level.
2440 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
2441 ;; indentation could move back more than one list level). Note
2442 ;; that this block need not be the beginning of list item.
2443 ((< indent (car levels))
2444 (while (and (> (length levels) 1)
2445 (< indent (+ (cadr levels) 4)))
2446 (setq levels (cdr levels)))
2447 levels)
2448 ;; Otherwise, do nothing.
2449 (t levels)))
2451 (defun markdown-calculate-list-levels ()
2452 "Calculate list levels at point.
2453 Return a list of the form (n1 n2 n3 ...) where n1 is the
2454 indentation of the deepest nested list item in the branch of
2455 the list at the point, n2 is the indentation of the parent
2456 list item, and so on. The depth of the list item is therefore
2457 the length of the returned list. If the point is not at or
2458 immediately after a list item, return nil."
2459 (save-excursion
2460 (let ((first (point)) levels indent pre-regexp)
2461 ;; Find a baseline point with zero list indentation
2462 (markdown-search-backward-baseline)
2463 ;; Search for all list items between baseline and LOC
2464 (while (and (< (point) first)
2465 (re-search-forward markdown-regex-list first t))
2466 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
2467 (beginning-of-line)
2468 (cond
2469 ;; Make sure this is not a header or hr
2470 ((markdown-new-baseline) (setq levels nil))
2471 ;; Make sure this is not a line from a pre block
2472 ((looking-at-p pre-regexp))
2473 ;; If not, then update levels
2475 (setq indent (current-indentation))
2476 (setq levels (markdown-update-list-levels (match-string 2)
2477 indent levels))))
2478 (end-of-line))
2479 levels)))
2481 (defun markdown-prev-list-item (level)
2482 "Search backward from point for a list item with indentation LEVEL.
2483 Set point to the beginning of the item, and return point, or nil
2484 upon failure."
2485 (let (bounds indent prev)
2486 (setq prev (point))
2487 (forward-line -1)
2488 (setq indent (current-indentation))
2489 (while
2490 (cond
2491 ;; List item
2492 ((and (looking-at-p markdown-regex-list)
2493 (setq bounds (markdown-cur-list-item-bounds)))
2494 (cond
2495 ;; Stop and return point at item of equal indentation
2496 ((= (nth 3 bounds) level)
2497 (setq prev (point))
2498 nil)
2499 ;; Stop and return nil at item with lesser indentation
2500 ((< (nth 3 bounds) level)
2501 (setq prev nil)
2502 nil)
2503 ;; Stop at beginning of buffer
2504 ((bobp) (setq prev nil))
2505 ;; Continue at item with greater indentation
2506 ((> (nth 3 bounds) level) t)))
2507 ;; Stop at beginning of buffer
2508 ((bobp) (setq prev nil))
2509 ;; Continue if current line is blank
2510 ((markdown-cur-line-blank-p) t)
2511 ;; Continue while indentation is the same or greater
2512 ((>= indent level) t)
2513 ;; Stop if current indentation is less than list item
2514 ;; and the next is blank
2515 ((and (< indent level)
2516 (markdown-next-line-blank-p))
2517 (setq prev nil))
2518 ;; Stop at a header
2519 ((looking-at-p markdown-regex-header) (setq prev nil))
2520 ;; Stop at a horizontal rule
2521 ((looking-at-p markdown-regex-hr) (setq prev nil))
2522 ;; Otherwise, continue.
2523 (t t))
2524 (forward-line -1)
2525 (setq indent (current-indentation)))
2526 prev))
2528 (defun markdown-next-list-item (level)
2529 "Search forward from point for the next list item with indentation LEVEL.
2530 Set point to the beginning of the item, and return point, or nil
2531 upon failure."
2532 (let (bounds indent next)
2533 (setq next (point))
2534 (if (looking-at markdown-regex-header-setext)
2535 (goto-char (match-end 0)))
2536 (forward-line)
2537 (setq indent (current-indentation))
2538 (while
2539 (cond
2540 ;; Stop at end of the buffer.
2541 ((eobp) nil)
2542 ;; Continue if the current line is blank
2543 ((markdown-cur-line-blank-p) t)
2544 ;; List item
2545 ((and (looking-at-p markdown-regex-list)
2546 (setq bounds (markdown-cur-list-item-bounds)))
2547 (cond
2548 ;; Continue at item with greater indentation
2549 ((> (nth 3 bounds) level) t)
2550 ;; Stop and return point at item of equal indentation
2551 ((= (nth 3 bounds) level)
2552 (setq next (point))
2553 nil)
2554 ;; Stop and return nil at item with lesser indentation
2555 ((< (nth 3 bounds) level)
2556 (setq next nil)
2557 nil)))
2558 ;; Continue while indentation is the same or greater
2559 ((>= indent level) t)
2560 ;; Stop if current indentation is less than list item
2561 ;; and the previous line was blank.
2562 ((and (< indent level)
2563 (markdown-prev-line-blank-p))
2564 (setq next nil))
2565 ;; Stop at a header
2566 ((looking-at-p markdown-regex-header) (setq next nil))
2567 ;; Stop at a horizontal rule
2568 ((looking-at-p markdown-regex-hr) (setq next nil))
2569 ;; Otherwise, continue.
2570 (t t))
2571 (forward-line)
2572 (setq indent (current-indentation)))
2573 next))
2575 (defun markdown-cur-list-item-end (level)
2576 "Move to end of list item with pre-marker indentation LEVEL.
2577 Return the point at the end when a list item was found at the
2578 original point. If the point is not in a list item, do nothing."
2579 (let (indent)
2580 (forward-line)
2581 (setq indent (current-indentation))
2582 (while
2583 (cond
2584 ;; Stop at end of the buffer.
2585 ((eobp) nil)
2586 ;; Continue if the current line is blank
2587 ((looking-at markdown-regex-blank-line) t)
2588 ;; Continue while indentation is the same or greater
2589 ((>= indent level) t)
2590 ;; Stop if current indentation is less than list item
2591 ;; and the previous line was blank.
2592 ((and (< indent level)
2593 (markdown-prev-line-blank))
2594 nil)
2595 ;; Stop at a new list item of the same or lesser indentation
2596 ((looking-at markdown-regex-list) nil)
2597 ;; Stop at a header
2598 ((looking-at markdown-regex-header) nil)
2599 ;; Stop at a horizontal rule
2600 ((looking-at markdown-regex-hr) nil)
2601 ;; Otherwise, continue.
2602 (t t))
2603 (forward-line)
2604 (setq indent (current-indentation)))
2605 ;; Don't skip over whitespace for empty list items (marker and
2606 ;; whitespace only), just move to end of whitespace.
2607 (save-match-data
2608 (if (looking-back (concat markdown-regex-list "\\s-*") (point-at-bol))
2609 (goto-char (match-end 3))
2610 (skip-chars-backward " \t\n")))
2611 (point)))
2613 (defun markdown-cur-list-item-bounds ()
2614 "Return bounds for list item at point.
2615 Return a list of the following form:
2617 (begin end indent nonlist-indent marker checkbox match)
2619 The named components are:
2621 - begin: Position of beginning of list item, including leading indentation.
2622 - end: Position of the end of the list item, including list item text.
2623 - indent: Number of characters of indentation before list marker (an integer).
2624 - nonlist-indent: Number characters of indentation, list
2625 marker, and whitespace following list marker (an integer).
2626 - marker: String containing the list marker and following whitespace
2627 (e.g., \"- \" or \"* \").
2628 - checkbox: String containing the GFM checkbox portion, if any,
2629 including any trailing whitespace before the text
2630 begins (e.g., \"[x] \").
2631 - match: match data for markdown-regex-list
2633 As an example, for the following unordered list item
2635 - item
2637 the returned list would be
2639 (1 14 3 5 \"- \" nil (1 6 1 4 4 5 5 6))
2641 If the point is not inside a list item, return nil."
2642 (car (get-text-property (point-at-bol) 'markdown-list-item)))
2644 (defun markdown-list-item-at-point-p ()
2645 "Return t if there is a list item at the point and nil otherwise."
2646 (save-match-data (markdown-cur-list-item-bounds)))
2648 (defun markdown-prev-list-item-bounds ()
2649 "Return bounds of previous item in the same list of any level.
2650 The return value has the same form as that of
2651 `markdown-cur-list-item-bounds'."
2652 (save-excursion
2653 (let ((cur-bounds (markdown-cur-list-item-bounds))
2654 (beginning-of-list (save-excursion (markdown-beginning-of-list)))
2655 stop)
2656 (when cur-bounds
2657 (goto-char (nth 0 cur-bounds))
2658 (while (and (not stop) (not (bobp))
2659 (re-search-backward markdown-regex-list
2660 beginning-of-list t))
2661 (unless (or (looking-at markdown-regex-hr)
2662 (markdown-code-block-at-point-p))
2663 (setq stop (point))))
2664 (markdown-cur-list-item-bounds)))))
2666 (defun markdown-next-list-item-bounds ()
2667 "Return bounds of next item in the same list of any level.
2668 The return value has the same form as that of
2669 `markdown-cur-list-item-bounds'."
2670 (save-excursion
2671 (let ((cur-bounds (markdown-cur-list-item-bounds))
2672 (end-of-list (save-excursion (markdown-end-of-list)))
2673 stop)
2674 (when cur-bounds
2675 (goto-char (nth 0 cur-bounds))
2676 (end-of-line)
2677 (while (and (not stop) (not (eobp))
2678 (re-search-forward markdown-regex-list
2679 end-of-list t))
2680 (unless (or (looking-at markdown-regex-hr)
2681 (markdown-code-block-at-point-p))
2682 (setq stop (point))))
2683 (when stop
2684 (markdown-cur-list-item-bounds))))))
2686 (defun markdown-beginning-of-list ()
2687 "Move point to beginning of list at point, if any."
2688 (interactive)
2689 (let ((orig-point (point))
2690 (list-begin (save-excursion
2691 (markdown-search-backward-baseline)
2692 ;; Stop at next list item, regardless of the indentation.
2693 (markdown-next-list-item (point-max))
2694 (when (looking-at markdown-regex-list)
2695 (point)))))
2696 (when (and list-begin (<= list-begin orig-point))
2697 (goto-char list-begin))))
2699 (defun markdown-end-of-list ()
2700 "Move point to end of list at point, if any."
2701 (interactive)
2702 (let ((start (point))
2703 (end (save-excursion
2704 (when (markdown-beginning-of-list)
2705 ;; Items can't have nonlist-indent <= 1, so this
2706 ;; moves past all list items.
2707 (markdown-next-list-item 1)
2708 (skip-syntax-backward "-")
2709 (unless (eobp) (forward-char 1))
2710 (point)))))
2711 (when (and end (>= end start))
2712 (goto-char end))))
2714 (defun markdown-up-list ()
2715 "Move point to beginning of parent list item."
2716 (interactive)
2717 (let ((cur-bounds (markdown-cur-list-item-bounds)))
2718 (when cur-bounds
2719 (markdown-prev-list-item (1- (nth 3 cur-bounds)))
2720 (let ((up-bounds (markdown-cur-list-item-bounds)))
2721 (when (and up-bounds (< (nth 3 up-bounds) (nth 3 cur-bounds)))
2722 (point))))))
2724 (defun markdown-bounds-of-thing-at-point (thing)
2725 "Call `bounds-of-thing-at-point' for THING with slight modifications.
2726 Does not include trailing newlines when THING is 'line. Handles the
2727 end of buffer case by setting both endpoints equal to the value of
2728 `point-max', since an empty region will trigger empty markup insertion.
2729 Return bounds of form (beg . end) if THING is found, or nil otherwise."
2730 (let* ((bounds (bounds-of-thing-at-point thing))
2731 (a (car bounds))
2732 (b (cdr bounds)))
2733 (when bounds
2734 (when (eq thing 'line)
2735 (cond ((and (eobp) (markdown-cur-line-blank-p))
2736 (setq a b))
2737 ((char-equal (char-before b) ?\^J)
2738 (setq b (1- b)))))
2739 (cons a b))))
2741 (defun markdown-reference-definition (reference)
2742 "Find out whether Markdown REFERENCE is defined.
2743 REFERENCE should not include the square brackets.
2744 When REFERENCE is defined, return a list of the form (text start end)
2745 containing the definition text itself followed by the start and end
2746 locations of the text. Otherwise, return nil.
2747 Leave match data for `markdown-regex-reference-definition'
2748 intact additional processing."
2749 (let ((reference (downcase reference)))
2750 (save-excursion
2751 (goto-char (point-min))
2752 (catch 'found
2753 (while (re-search-forward markdown-regex-reference-definition nil t)
2754 (when (string= reference (downcase (match-string-no-properties 2)))
2755 (throw 'found
2756 (list (match-string-no-properties 5)
2757 (match-beginning 5) (match-end 5)))))))))
2759 (defun markdown-get-defined-references ()
2760 "Return a list of all defined reference labels (not including square brackets)."
2761 (save-excursion
2762 (goto-char (point-min))
2763 (let (refs)
2764 (while (re-search-forward markdown-regex-reference-definition nil t)
2765 (let ((target (match-string-no-properties 2)))
2766 (cl-pushnew target refs :test #'equal)))
2767 (reverse refs))))
2769 (defun markdown-get-used-uris ()
2770 "Return a list of all used URIs in the buffer."
2771 (save-excursion
2772 (goto-char (point-min))
2773 (let (uris)
2774 (while (re-search-forward
2775 (concat "\\(?:" markdown-regex-link-inline
2776 "\\|" markdown-regex-angle-uri
2777 "\\|" markdown-regex-uri
2778 "\\|" markdown-regex-email
2779 "\\)")
2780 nil t)
2781 (unless (or (markdown-inline-code-at-point-p)
2782 (markdown-code-block-at-point-p))
2783 (cl-pushnew (or (match-string-no-properties 6)
2784 (match-string-no-properties 10)
2785 (match-string-no-properties 12)
2786 (match-string-no-properties 13))
2787 uris :test #'equal)))
2788 (reverse uris))))
2790 (defun markdown-inline-code-at-pos (pos)
2791 "Return non-nil if there is an inline code fragment at POS.
2792 Return nil otherwise. Set match data according to
2793 `markdown-match-code' upon success.
2794 This function searches the block for a code fragment that
2795 contains the point using `markdown-match-code'. We do this
2796 because `thing-at-point-looking-at' does not work reliably with
2797 `markdown-regex-code'.
2799 The match data is set as follows:
2800 Group 1 matches the opening backquotes.
2801 Group 2 matches the code fragment itself, without backquotes.
2802 Group 3 matches the closing backquotes."
2803 (save-excursion
2804 (goto-char pos)
2805 (let ((old-point (point))
2806 (end-of-block (progn (markdown-end-of-text-block) (point)))
2807 found)
2808 (markdown-beginning-of-text-block)
2809 (while (and (markdown-match-code end-of-block)
2810 (setq found t)
2811 (< (match-end 0) old-point)))
2812 (and found ; matched something
2813 (<= (match-beginning 0) old-point) ; match contains old-point
2814 (>= (match-end 0) old-point)))))
2816 (defun markdown-inline-code-at-pos-p (pos)
2817 "Return non-nil if there is an inline code fragment at POS.
2818 Like `markdown-inline-code-at-pos`, but preserves match data."
2819 (save-match-data (markdown-inline-code-at-pos pos)))
2821 (defun markdown-inline-code-at-point ()
2822 "Return non-nil if the point is at an inline code fragment.
2823 See `markdown-inline-code-at-pos' for details."
2824 (markdown-inline-code-at-pos (point)))
2826 (defun markdown-inline-code-at-point-p ()
2827 "Return non-nil if there is inline code at the point.
2828 This is a predicate function counterpart to
2829 `markdown-inline-code-at-point' which does not modify the match
2830 data. See `markdown-code-block-at-point-p' for code blocks."
2831 (save-match-data (markdown-inline-code-at-pos (point))))
2833 (make-obsolete 'markdown-code-at-point-p 'markdown-inline-code-at-point-p "v2.2")
2835 (defun markdown--code-block-at-pos-no-syntax (pos)
2836 "Return match data list if there may be a code block at POS.
2837 This includes pre blocks, tilde-fenced code blocks, and GFM
2838 quoted code blocks. Return nil otherwise. This function does not
2839 use text properties, which have not yet been set during the
2840 syntax propertization phase."
2841 (setq pos (save-excursion (goto-char pos) (point-at-bol)))
2842 (let (match)
2843 (cond
2844 ;; Indented code blocks
2845 ((looking-at markdown-regex-pre)
2846 (let ((start (save-excursion
2847 (markdown-search-backward-baseline) (point)))
2848 (end (save-excursion
2849 (while (and (or (looking-at-p markdown-regex-pre)
2850 (markdown-cur-line-blank-p))
2851 (not (eobp)))
2852 (forward-line))
2853 (point))))
2854 (list start end start start start end end end)))
2855 ;; Fenced code blocks
2856 ((setq match (markdown-get-enclosing-fenced-block-construct pos))
2857 match))))
2859 (defun markdown-code-block-at-pos (pos)
2860 "Return match data list if there is a code block at POS.
2861 This includes pre blocks, tilde-fenced code blocks, and GFM
2862 quoted code blocks. Return nil otherwise. This function uses
2863 cached text properties at the beginning of the line position for
2864 performance reasons, but therefore it must run after the syntax
2865 propertization phase."
2866 (setq pos (save-excursion (goto-char pos) (point-at-bol)))
2867 (or (get-text-property pos 'markdown-pre)
2868 ;;(markdown-get-enclosing-fenced-block-construct pos)
2869 (when (markdown-range-properties-exist
2870 pos pos '(markdown-gfm-block-begin
2871 markdown-gfm-code
2872 markdown-gfm-block-end
2873 markdown-tilde-fence-begin
2874 markdown-fenced-code
2875 markdown-tilde-fence-end
2876 markdown-yaml-metadata-begin
2877 markdown-yaml-metadata-section
2878 markdown-yaml-metadata-end))
2879 (markdown-get-enclosing-fenced-block-construct pos))
2880 ;; polymode removes text properties set by markdown-mode, so
2881 ;; check if `poly-markdown-mode' is active and whether the
2882 ;; `chunkmode' property is non-nil at POS.
2883 (and (bound-and-true-p poly-markdown-mode)
2884 (get-text-property pos 'chunkmode))))
2886 ;; Function was renamed to emphasize that it does not modify match-data.
2887 (defalias 'markdown-code-block-at-point 'markdown-code-block-at-point-p)
2889 (defun markdown-code-block-at-point-p ()
2890 "Return non-nil if there is a code block at the point.
2891 This includes pre blocks, tilde-fenced code blocks, and GFM
2892 quoted code blocks. This function does not modify the match
2893 data. See `markdown-inline-code-at-point-p' for inline code."
2894 (save-match-data (markdown-code-block-at-pos (point))))
2896 (defun markdown-heading-at-point ()
2897 "Return non-nil if there is a heading at the point.
2898 Set match data for `markdown-regex-header'."
2899 (let ((match-data (get-text-property (point) 'markdown-heading)))
2900 (when match-data
2901 (set-match-data match-data)
2902 t)))
2904 (defun markdown-pipe-at-bol-p ()
2905 "Return non-nil if the line begins with a pipe symbol.
2906 This may be useful for tables and Pandoc's line_blocks extension."
2907 (char-equal (char-after (point-at-bol)) ?|))
2910 ;;; Markdown Font Lock Matching Functions =====================================
2912 (defun markdown-range-property-any (begin end prop prop-values)
2913 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
2914 Also returns t if PROP is a list containing one of the PROP-VALUES.
2915 Return nil otherwise."
2916 (let (props)
2917 (catch 'found
2918 (dolist (loc (number-sequence begin end))
2919 (when (setq props (get-text-property loc prop))
2920 (cond ((listp props)
2921 ;; props is a list, check for membership
2922 (dolist (val prop-values)
2923 (when (memq val props) (throw 'found loc))))
2925 ;; props is a scalar, check for equality
2926 (dolist (val prop-values)
2927 (when (eq val props) (throw 'found loc))))))))))
2929 (defun markdown-range-properties-exist (begin end props)
2930 (cl-loop
2931 for loc in (number-sequence begin end)
2932 with result = nil
2933 while (not
2934 (setq result
2935 (cl-some (lambda (prop) (get-text-property loc prop)) props)))
2936 finally return result))
2938 (defun markdown-match-inline-generic (regex last &optional faceless)
2939 "Match inline REGEX from the point to LAST.
2940 When FACELESS is non-nil, do not return matches where faces have been applied."
2941 (when (re-search-forward regex last t)
2942 (let ((bounds (markdown-code-block-at-pos (match-beginning 1)))
2943 (face (and faceless (text-property-not-all
2944 (match-beginning 0) (match-end 0) 'face nil))))
2945 (cond
2946 ;; In code block: move past it and recursively search again
2947 (bounds
2948 (when (< (goto-char (cl-second bounds)) last)
2949 (markdown-match-inline-generic regex last faceless)))
2950 ;; When faces are found in the match range, skip over the match and
2951 ;; recursively search again.
2952 (face
2953 (when (< (goto-char (match-end 0)) last)
2954 (markdown-match-inline-generic regex last faceless)))
2955 ;; Keep match data and return t when in bounds.
2957 (<= (match-end 0) last))))))
2959 (defun markdown-match-code (last)
2960 "Match inline code fragments from point to LAST."
2961 (unless (bobp)
2962 (backward-char 1))
2963 (when (markdown-search-until-condition
2964 (lambda ()
2965 (and
2966 ;; Advance point in case of failure, but without exceeding last.
2967 (goto-char (min (1+ (match-beginning 1)) last))
2968 (not (markdown-in-comment-p (match-beginning 1)))
2969 (not (markdown-in-comment-p (match-end 1)))
2970 (not (markdown-code-block-at-pos (match-beginning 1)))))
2971 markdown-regex-code last t)
2972 (set-match-data (list (match-beginning 1) (match-end 1)
2973 (match-beginning 2) (match-end 2)
2974 (match-beginning 3) (match-end 3)
2975 (match-beginning 4) (match-end 4)))
2976 (goto-char (min (1+ (match-end 0)) last (point-max)))
2979 (defun markdown-match-bold (last)
2980 "Match inline bold from the point to LAST."
2981 (when (markdown-match-inline-generic markdown-regex-bold last)
2982 (let ((begin (match-beginning 2))
2983 (end (match-end 2)))
2984 (if (or (markdown-inline-code-at-pos-p begin)
2985 (markdown-inline-code-at-pos-p end)
2986 (markdown-in-comment-p)
2987 (markdown-range-property-any
2988 begin begin 'face '(markdown-url-face
2989 markdown-plain-url-face))
2990 (markdown-range-property-any
2991 begin end 'face '(markdown-hr-face
2992 markdown-math-face)))
2993 (progn (goto-char (min (1+ begin) last))
2994 (when (< (point) last)
2995 (markdown-match-italic last)))
2996 (set-match-data (list (match-beginning 2) (match-end 2)
2997 (match-beginning 3) (match-end 3)
2998 (match-beginning 4) (match-end 4)
2999 (match-beginning 5) (match-end 5)))
3000 t))))
3002 (defun markdown-match-italic (last)
3003 "Match inline italics from the point to LAST."
3004 (let ((regex (if (memq major-mode '(gfm-mode gfm-view-mode))
3005 markdown-regex-gfm-italic markdown-regex-italic)))
3006 (when (markdown-match-inline-generic regex last)
3007 (let ((begin (match-beginning 1))
3008 (end (match-end 1)))
3009 (if (or (markdown-inline-code-at-pos-p begin)
3010 (markdown-inline-code-at-pos-p end)
3011 (markdown-in-comment-p)
3012 (markdown-range-property-any
3013 begin begin 'face '(markdown-url-face
3014 markdown-plain-url-face))
3015 (markdown-range-property-any
3016 begin end 'face '(markdown-bold-face
3017 markdown-list-face
3018 markdown-hr-face
3019 markdown-math-face)))
3020 (progn (goto-char (min (1+ begin) last))
3021 (when (< (point) last)
3022 (markdown-match-italic last)))
3023 (set-match-data (list (match-beginning 1) (match-end 1)
3024 (match-beginning 2) (match-end 2)
3025 (match-beginning 3) (match-end 3)
3026 (match-beginning 4) (match-end 4)))
3027 t)))))
3029 (defun markdown-match-math-generic (regex last)
3030 "Match REGEX from point to LAST.
3031 REGEX is either `markdown-regex-math-inline-single' for matching
3032 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
3033 (when (and markdown-enable-math (markdown-match-inline-generic regex last))
3034 (let ((begin (match-beginning 1)) (end (match-end 1)))
3035 (prog1
3036 (if (or (markdown-range-property-any
3037 begin end 'face
3038 '(markdown-inline-code-face markdown-bold-face))
3039 (markdown-range-properties-exist
3040 begin end
3041 (markdown-get-fenced-block-middle-properties)))
3042 (markdown-match-math-generic regex last)
3044 (goto-char (1+ (match-end 0)))))))
3046 (defun markdown-match-list-items (last)
3047 "Match list items from point to LAST."
3048 (let* ((first (point))
3049 (pos first)
3050 (prop 'markdown-list-item)
3051 (bounds (car (get-text-property pos prop))))
3052 (while
3053 (and (or (null (setq bounds (car (get-text-property pos prop))))
3054 (< (cl-first bounds) pos))
3055 (< (point) last)
3056 (setq pos (next-single-char-property-change pos prop nil last))
3057 (goto-char pos)))
3058 (when bounds
3059 (set-match-data (cl-seventh bounds))
3060 ;; Step at least one character beyond point. Otherwise
3061 ;; `font-lock-fontify-keywords-region' infloops.
3062 (goto-char (min (1+ (max (point-at-eol) first))
3063 (point-max)))
3064 t)))
3066 (defun markdown-match-math-single (last)
3067 "Match single quoted $..$ math from point to LAST."
3068 (markdown-match-math-generic markdown-regex-math-inline-single last))
3070 (defun markdown-match-math-double (last)
3071 "Match double quoted $$..$$ math from point to LAST."
3072 (markdown-match-math-generic markdown-regex-math-inline-double last))
3074 (defun markdown-match-math-display (last)
3075 "Match bracketed display math \[..\] and \\[..\\] from point to LAST."
3076 (markdown-match-math-generic markdown-regex-math-display last))
3078 (defun markdown-match-propertized-text (property last)
3079 "Match text with PROPERTY from point to LAST.
3080 Restore match data previously stored in PROPERTY."
3081 (let ((saved (get-text-property (point) property))
3082 pos)
3083 (unless saved
3084 (setq pos (next-single-char-property-change (point) property nil last))
3085 (setq saved (get-text-property pos property)))
3086 (when saved
3087 (set-match-data saved)
3088 ;; Step at least one character beyond point. Otherwise
3089 ;; `font-lock-fontify-keywords-region' infloops.
3090 (goto-char (min (1+ (max (match-end 0) (point)))
3091 (point-max)))
3092 saved)))
3094 (defun markdown-match-pre-blocks (last)
3095 "Match preformatted blocks from point to LAST.
3096 Use data stored in 'markdown-pre text property during syntax
3097 analysis."
3098 (markdown-match-propertized-text 'markdown-pre last))
3100 (defun markdown-match-gfm-code-blocks (last)
3101 "Match GFM quoted code blocks from point to LAST.
3102 Use data stored in 'markdown-gfm-code text property during syntax
3103 analysis."
3104 (markdown-match-propertized-text 'markdown-gfm-code last))
3106 (defun markdown-match-gfm-open-code-blocks (last)
3107 (markdown-match-propertized-text 'markdown-gfm-block-begin last))
3109 (defun markdown-match-gfm-close-code-blocks (last)
3110 (markdown-match-propertized-text 'markdown-gfm-block-end last))
3112 (defun markdown-match-fenced-code-blocks (last)
3113 "Match fenced code blocks from the point to LAST."
3114 (markdown-match-propertized-text 'markdown-fenced-code last))
3116 (defun markdown-match-fenced-start-code-block (last)
3117 (markdown-match-propertized-text 'markdown-tilde-fence-begin last))
3119 (defun markdown-match-fenced-end-code-block (last)
3120 (markdown-match-propertized-text 'markdown-tilde-fence-end last))
3122 (defun markdown-match-blockquotes (last)
3123 "Match blockquotes from point to LAST.
3124 Use data stored in 'markdown-blockquote text property during syntax
3125 analysis."
3126 (markdown-match-propertized-text 'markdown-blockquote last))
3128 (defun markdown-match-hr (last)
3129 "Match horizontal rules comments from the point to LAST."
3130 (markdown-match-propertized-text 'markdown-hr last))
3132 (defun markdown-match-comments (last)
3133 "Match HTML comments from the point to LAST."
3134 (when (and (skip-syntax-forward "^<" last))
3135 (let ((beg (point)))
3136 (when (and (skip-syntax-forward "^>" last) (< (point) last))
3137 (forward-char)
3138 (set-match-data (list beg (point)))
3139 t))))
3141 (defun markdown-match-generic-links (last ref)
3142 "Match inline links from point to LAST.
3143 When REF is non-nil, match reference links instead of standard
3144 links with URLs."
3145 ;; Search for the next potential link (not in a code block).
3146 (while (and (progn
3147 ;; Clear match data to test for a match after functions returns.
3148 (set-match-data nil)
3149 ;; Preliminary regular expression search so we can return
3150 ;; quickly upon failure. This doesn't handle malformed links
3151 ;; or nested square brackets well, so if it passes we back up
3152 ;; continue with a more precise search.
3153 (re-search-forward
3154 (if ref
3155 markdown-regex-link-reference
3156 markdown-regex-link-inline)
3157 last 'limit))
3158 ;; Keep searching if this is in a code block, inline
3159 ;; code, or a comment, or if it is include syntax.
3160 (or (markdown-code-block-at-point-p)
3161 (markdown-inline-code-at-pos-p (match-beginning 0))
3162 (markdown-inline-code-at-pos-p (match-end 0))
3163 (markdown-in-comment-p)
3164 (and (char-equal (char-after (point-at-bol)) ?<)
3165 (char-equal (char-after (1+ (point-at-bol))) ?<)))
3166 (< (point) last)))
3167 ;; Match opening exclamation point (optional) and left bracket.
3168 (when (match-beginning 2)
3169 (let* ((bang (match-beginning 1))
3170 (first-begin (match-beginning 2))
3171 ;; Find end of block to prevent matching across blocks.
3172 (end-of-block (save-excursion
3173 (progn
3174 (goto-char (match-beginning 2))
3175 (markdown-end-of-text-block)
3176 (point))))
3177 ;; Move over balanced expressions to closing right bracket.
3178 ;; Catch unbalanced expression errors and return nil.
3179 (first-end (condition-case nil
3180 (and (goto-char first-begin)
3181 (scan-sexps (point) 1))
3182 (error nil)))
3183 ;; Continue with point at CONT-POINT upon failure.
3184 (cont-point (min (1+ first-begin) last))
3185 second-begin second-end url-begin url-end
3186 title-begin title-end)
3187 ;; When bracket found, in range, and followed by a left paren/bracket...
3188 (when (and first-end (< first-end end-of-block) (goto-char first-end)
3189 (char-equal (char-after (point)) (if ref ?\[ ?\()))
3190 ;; Scan across balanced expressions for closing parenthesis/bracket.
3191 (setq second-begin (point)
3192 second-end (condition-case nil
3193 (scan-sexps (point) 1)
3194 (error nil)))
3195 ;; Check that closing parenthesis/bracket is in range.
3196 (if (and second-end (<= second-end end-of-block) (<= second-end last))
3197 (progn
3198 ;; Search for (optional) title inside closing parenthesis
3199 (when (and (not ref) (search-forward "\"" second-end t))
3200 (setq title-begin (1- (point))
3201 title-end (and (goto-char second-end)
3202 (search-backward "\"" (1+ title-begin) t))
3203 title-end (and title-end (1+ title-end))))
3204 ;; Store URL/reference range
3205 (setq url-begin (1+ second-begin)
3206 url-end (1- (or title-begin second-end)))
3207 ;; Set match data, move point beyond link, and return
3208 (set-match-data
3209 (list (or bang first-begin) second-end ; 0 - all
3210 bang (and bang (1+ bang)) ; 1 - bang
3211 first-begin (1+ first-begin) ; 2 - markup
3212 (1+ first-begin) (1- first-end) ; 3 - link text
3213 (1- first-end) first-end ; 4 - markup
3214 second-begin (1+ second-begin) ; 5 - markup
3215 url-begin url-end ; 6 - url/reference
3216 title-begin title-end ; 7 - title
3217 (1- second-end) second-end)) ; 8 - markup
3218 ;; Nullify cont-point and leave point at end and
3219 (setq cont-point nil)
3220 (goto-char second-end))
3221 ;; If no closing parenthesis in range, update continuation point
3222 (setq cont-point (min end-of-block second-begin))))
3223 (cond
3224 ;; On failure, continue searching at cont-point
3225 ((and cont-point (< cont-point last))
3226 (goto-char cont-point)
3227 (markdown-match-generic-links last ref))
3228 ;; No more text, return nil
3229 ((and cont-point (= cont-point last))
3230 nil)
3231 ;; Return t if a match occurred
3232 (t t)))))
3234 (defun markdown-match-inline-links (last)
3235 "Match standard inline links from point to LAST."
3236 (markdown-match-generic-links last nil))
3238 (defun markdown-match-reference-links (last)
3239 "Match inline reference links from point to LAST."
3240 (markdown-match-generic-links last t))
3242 (defun markdown-match-angle-uris (last)
3243 "Match angle bracket URIs from point to LAST."
3244 (when (markdown-match-inline-generic markdown-regex-angle-uri last)
3245 (goto-char (1+ (match-end 0)))))
3247 (defun markdown-match-plain-uris (last)
3248 "Match plain URIs from point to LAST."
3249 (when (markdown-match-inline-generic markdown-regex-uri last t)
3250 (goto-char (1+ (match-end 0)))))
3252 (defvar markdown-conditional-search-function #'re-search-forward
3253 "Conditional search function used in `markdown-search-until-condition'.
3254 Made into a variable to allow for dynamic let-binding.")
3256 (defun markdown-search-until-condition (condition &rest args)
3257 (let (ret)
3258 (while (and (not ret) (apply markdown-conditional-search-function args))
3259 (setq ret (funcall condition)))
3260 ret))
3262 (defun markdown-match-generic-metadata (regexp last)
3263 "Match metadata declarations specified by REGEXP from point to LAST.
3264 These declarations must appear inside a metadata block that begins at
3265 the beginning of the buffer and ends with a blank line (or the end of
3266 the buffer)."
3267 (let* ((first (point))
3268 (end-re "\n[ \t]*\n\\|\n\\'\\|\\'")
3269 (block-begin (goto-char 1))
3270 (block-end (re-search-forward end-re nil t)))
3271 (if (and block-end (> first block-end))
3272 ;; Don't match declarations if there is no metadata block or if
3273 ;; the point is beyond the block. Move point to point-max to
3274 ;; prevent additional searches and return return nil since nothing
3275 ;; was found.
3276 (progn (goto-char (point-max)) nil)
3277 ;; If a block was found that begins before LAST and ends after
3278 ;; point, search for declarations inside it. If the starting is
3279 ;; before the beginning of the block, start there. Otherwise,
3280 ;; move back to FIRST.
3281 (goto-char (if (< first block-begin) block-begin first))
3282 (if (re-search-forward regexp (min last block-end) t)
3283 ;; If a metadata declaration is found, set match-data and return t.
3284 (let ((key-beginning (match-beginning 1))
3285 (key-end (match-end 1))
3286 (markup-begin (match-beginning 2))
3287 (markup-end (match-end 2))
3288 (value-beginning (match-beginning 3)))
3289 (set-match-data (list key-beginning (point) ; complete metadata
3290 key-beginning key-end ; key
3291 markup-begin markup-end ; markup
3292 value-beginning (point))) ; value
3294 ;; Otherwise, move the point to last and return nil
3295 (goto-char last)
3296 nil))))
3298 (defun markdown-match-declarative-metadata (last)
3299 "Match declarative metadata from the point to LAST."
3300 (markdown-match-generic-metadata markdown-regex-declarative-metadata last))
3302 (defun markdown-match-pandoc-metadata (last)
3303 "Match Pandoc metadata from the point to LAST."
3304 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
3306 (defun markdown-match-yaml-metadata-begin (last)
3307 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last))
3309 (defun markdown-match-yaml-metadata-end (last)
3310 (markdown-match-propertized-text 'markdown-yaml-metadata-end last))
3312 (defun markdown-match-yaml-metadata-key (last)
3313 (markdown-match-propertized-text 'markdown-metadata-key last))
3315 (defun markdown-match-wiki-link (last)
3316 "Match wiki links from point to LAST."
3317 (when (and markdown-enable-wiki-links
3318 (not markdown-wiki-link-fontify-missing)
3319 (markdown-match-inline-generic markdown-regex-wiki-link last))
3320 (let ((begin (match-beginning 1)) (end (match-end 1)))
3321 (if (or (markdown-in-comment-p begin)
3322 (markdown-in-comment-p end)
3323 (markdown-inline-code-at-pos-p begin)
3324 (markdown-inline-code-at-pos-p end)
3325 (markdown-code-block-at-pos begin))
3326 (progn (goto-char (min (1+ begin) last))
3327 (when (< (point) last)
3328 (markdown-match-wiki-link last)))
3329 (set-match-data (list begin end))
3330 t))))
3332 (defun markdown-match-inline-attributes (last)
3333 "Match inline attributes from point to LAST."
3334 (when (markdown-match-inline-generic markdown-regex-inline-attributes last)
3335 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
3336 (markdown-inline-code-at-pos-p (match-end 0))
3337 (markdown-in-comment-p))
3338 t)))
3340 (defun markdown-match-leanpub-sections (last)
3341 "Match Leanpub section markers from point to LAST."
3342 (when (markdown-match-inline-generic markdown-regex-leanpub-sections last)
3343 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
3344 (markdown-inline-code-at-pos-p (match-end 0))
3345 (markdown-in-comment-p))
3346 t)))
3348 (defun markdown-match-includes (last)
3349 "Match include statements from point to LAST.
3350 Sets match data for the following seven groups:
3351 Group 1: opening two angle brackets
3352 Group 2: opening title delimiter (optional)
3353 Group 3: title text (optional)
3354 Group 4: closing title delimiter (optional)
3355 Group 5: opening filename delimiter
3356 Group 6: filename
3357 Group 7: closing filename delimiter"
3358 (when (markdown-match-inline-generic markdown-regex-include last)
3359 (let ((valid (not (or (markdown-in-comment-p (match-beginning 0))
3360 (markdown-in-comment-p (match-end 0))
3361 (markdown-code-block-at-pos (match-beginning 0))))))
3362 (cond
3363 ;; Parentheses and maybe square brackets, but no curly braces:
3364 ;; match optional title in square brackets and file in parentheses.
3365 ((and valid (match-beginning 5)
3366 (not (match-beginning 8)))
3367 (set-match-data (list (match-beginning 1) (match-end 7)
3368 (match-beginning 1) (match-end 1)
3369 (match-beginning 2) (match-end 2)
3370 (match-beginning 3) (match-end 3)
3371 (match-beginning 4) (match-end 4)
3372 (match-beginning 5) (match-end 5)
3373 (match-beginning 6) (match-end 6)
3374 (match-beginning 7) (match-end 7))))
3375 ;; Only square brackets present: match file in square brackets.
3376 ((and valid (match-beginning 2)
3377 (not (match-beginning 5))
3378 (not (match-beginning 7)))
3379 (set-match-data (list (match-beginning 1) (match-end 4)
3380 (match-beginning 1) (match-end 1)
3381 nil nil
3382 nil nil
3383 nil nil
3384 (match-beginning 2) (match-end 2)
3385 (match-beginning 3) (match-end 3)
3386 (match-beginning 4) (match-end 4))))
3387 ;; Only curly braces present: match file in curly braces.
3388 ((and valid (match-beginning 8)
3389 (not (match-beginning 2))
3390 (not (match-beginning 5)))
3391 (set-match-data (list (match-beginning 1) (match-end 10)
3392 (match-beginning 1) (match-end 1)
3393 nil nil
3394 nil nil
3395 nil nil
3396 (match-beginning 8) (match-end 8)
3397 (match-beginning 9) (match-end 9)
3398 (match-beginning 10) (match-end 10))))
3400 ;; Not a valid match, move to next line and search again.
3401 (forward-line)
3402 (when (< (point) last)
3403 (setq valid (markdown-match-includes last)))))
3404 valid)))
3406 (defun markdown-match-html-tag (last)
3407 "Match HTML tags from point to LAST."
3408 (when (and markdown-enable-html
3409 (markdown-match-inline-generic markdown-regex-html-tag last t))
3410 (set-match-data (list (match-beginning 0) (match-end 0)
3411 (match-beginning 1) (match-end 1)
3412 (match-beginning 2) (match-end 2)
3413 (match-beginning 9) (match-end 9)))
3417 ;;; Markdown Font Fontification Functions =====================================
3419 (defun markdown--first-displayable (seq)
3420 "Return the first displayable character or string in SEQ.
3421 SEQ may be an atom or a sequence."
3422 (let ((seq (if (listp seq) seq (list seq))))
3423 (cond ((stringp (car seq))
3424 (cl-find-if
3425 (lambda (str)
3426 (and (mapcar #'char-displayable-p (string-to-list str))))
3427 seq))
3428 ((characterp (car seq))
3429 (cl-find-if #'char-displayable-p seq)))))
3431 (defun markdown--marginalize-string (level)
3432 "Generate atx markup string of given LEVEL for left margin."
3433 (let ((margin-left-space-count
3434 (- markdown-marginalize-headers-margin-width level)))
3435 (concat (make-string margin-left-space-count ? )
3436 (make-string level ?#))))
3438 (defun markdown-marginalize-update-current ()
3439 "Update the window configuration to create a left margin."
3440 ;; Emacs 25 or later is needed for window-font-width and default-font-width.
3441 (if (and (fboundp 'window-font-width) (fboundp 'default-font-width))
3442 (let* ((header-delimiter-font-width
3443 (window-font-width nil 'markdown-header-delimiter-face))
3444 (margin-pixel-width (* markdown-marginalize-headers-margin-width
3445 header-delimiter-font-width))
3446 (margin-char-width (/ margin-pixel-width (default-font-width))))
3447 (set-window-margins nil margin-char-width))
3448 ;; As a fallback, simply set margin based on character count.
3449 (set-window-margins nil markdown-marginalize-headers-margin-width)))
3451 (defun markdown-fontify-headings (last)
3452 "Add text properties to headings from point to LAST."
3453 (when (markdown-match-propertized-text 'markdown-heading last)
3454 (let* ((level (markdown-outline-level))
3455 (heading-face
3456 (intern (format "markdown-header-face-%d" level)))
3457 (heading-props `(face ,heading-face))
3458 (left-markup-props
3459 `(face markdown-header-delimiter-face
3460 ,@(cond
3461 (markdown-hide-markup
3462 `(display ""))
3463 (markdown-marginalize-headers
3464 `(display ((margin left-margin)
3465 ,(markdown--marginalize-string level)))))))
3466 (right-markup-props
3467 `(face markdown-header-delimiter-face
3468 ,@(when markdown-hide-markup `(display ""))))
3469 (rule-props `(face markdown-header-rule-face
3470 ,@(when markdown-hide-markup `(display "")))))
3471 (if (match-end 1)
3472 ;; Setext heading
3473 (progn (add-text-properties
3474 (match-beginning 1) (match-end 1) heading-props)
3475 (if (= level 1)
3476 (add-text-properties
3477 (match-beginning 2) (match-end 2) rule-props)
3478 (add-text-properties
3479 (match-beginning 3) (match-end 3) rule-props)))
3480 ;; atx heading
3481 (add-text-properties
3482 (match-beginning 4) (match-end 4) left-markup-props)
3483 (add-text-properties
3484 (match-beginning 5) (match-end 5) heading-props)
3485 (when (match-end 6)
3486 (add-text-properties
3487 (match-beginning 6) (match-end 6) right-markup-props))))
3490 (defun markdown-fontify-tables (last)
3491 (when (and (re-search-forward "|" last t)
3492 (markdown-table-at-point-p))
3493 (font-lock-append-text-property
3494 (line-beginning-position) (min (1+ (line-end-position)) (point-max))
3495 'face 'markdown-table-face)
3496 (forward-line 1)
3499 (defun markdown-fontify-blockquotes (last)
3500 "Apply font-lock properties to blockquotes from point to LAST."
3501 (when (markdown-match-blockquotes last)
3502 (let ((display-string
3503 (markdown--first-displayable markdown-blockquote-display-char)))
3504 (add-text-properties
3505 (match-beginning 1) (match-end 1)
3506 (if markdown-hide-markup
3507 `(face markdown-blockquote-face display ,display-string)
3508 `(face markdown-markup-face)))
3509 (font-lock-append-text-property
3510 (match-beginning 0) (match-end 0) 'face 'markdown-blockquote-face)
3511 t)))
3513 (defun markdown-fontify-list-items (last)
3514 "Apply font-lock properties to list markers from point to LAST."
3515 (when (markdown-match-list-items last)
3516 (let* ((indent (length (match-string-no-properties 1)))
3517 (level (/ indent 4)) ;; level = 0, 1, 2, ...
3518 (bullet (nth (mod level (length markdown-list-item-bullets))
3519 markdown-list-item-bullets)))
3520 (add-text-properties
3521 (match-beginning 2) (match-end 2) '(face markdown-list-face))
3522 (when markdown-hide-markup
3523 (cond
3524 ;; Unordered lists
3525 ((string-match-p "[\\*\\+-]" (match-string 2))
3526 (add-text-properties
3527 (match-beginning 2) (match-end 2) `(display ,bullet)))
3528 ;; Definition lists
3529 ((string-equal ":" (match-string 2))
3530 (let ((display-string
3531 (char-to-string (markdown--first-displayable
3532 markdown-definition-display-char))))
3533 (add-text-properties (match-beginning 2) (match-end 2)
3534 `(display ,display-string)))))))
3537 (defun markdown-fontify-hrs (last)
3538 "Add text properties to horizontal rules from point to LAST."
3539 (when (markdown-match-hr last)
3540 (let ((hr-char (markdown--first-displayable markdown-hr-display-char)))
3541 (add-text-properties
3542 (match-beginning 0) (match-end 0)
3543 `(face markdown-hr-face
3544 font-lock-multiline t
3545 ,@(when (and markdown-hide-markup hr-char)
3546 `(display ,(make-string
3547 (window-body-width) hr-char)))))
3548 t)))
3550 (defun markdown-fontify-sub-superscripts (last)
3551 "Apply text properties to sub- and superscripts from point to LAST."
3552 (when (markdown-search-until-condition
3553 (lambda () (and (not (markdown-code-block-at-point-p))
3554 (not (markdown-inline-code-at-point-p))
3555 (not (markdown-in-comment-p))))
3556 markdown-regex-sub-superscript last t)
3557 (let* ((subscript-p (string= (match-string 2) "~"))
3558 (props
3559 (if subscript-p
3560 (car markdown-sub-superscript-display)
3561 (cdr markdown-sub-superscript-display)))
3562 (mp (list 'face 'markdown-markup-face
3563 'invisible 'markdown-markup)))
3564 (when markdown-hide-markup
3565 (put-text-property (match-beginning 3) (match-end 3)
3566 'display props))
3567 (add-text-properties (match-beginning 2) (match-end 2) mp)
3568 (add-text-properties (match-beginning 4) (match-end 4) mp)
3569 t)))
3572 ;;; Syntax Table ==============================================================
3574 (defvar markdown-mode-syntax-table
3575 (let ((tab (make-syntax-table text-mode-syntax-table)))
3576 (modify-syntax-entry ?\" "." tab)
3577 tab)
3578 "Syntax table for `markdown-mode'.")
3581 ;;; Element Insertion =========================================================
3583 (defun markdown-ensure-blank-line-before ()
3584 "If previous line is not already blank, insert a blank line before point."
3585 (unless (bolp) (insert "\n"))
3586 (unless (or (bobp) (looking-back "\n\\s-*\n" nil)) (insert "\n")))
3588 (defun markdown-ensure-blank-line-after ()
3589 "If following line is not already blank, insert a blank line after point.
3590 Return the point where it was originally."
3591 (save-excursion
3592 (unless (eolp) (insert "\n"))
3593 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
3595 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
3596 "Insert the strings S1 and S2, wrapping around region or THING.
3597 If a region is specified by the optional BEG and END arguments,
3598 wrap the strings S1 and S2 around that region.
3599 If there is an active region, wrap the strings S1 and S2 around
3600 the region. If there is not an active region but the point is at
3601 THING, wrap that thing (which defaults to word). Otherwise, just
3602 insert S1 and S2 and place the point in between. Return the
3603 bounds of the entire wrapped string, or nil if nothing was wrapped
3604 and S1 and S2 were only inserted."
3605 (let (a b bounds new-point)
3606 (cond
3607 ;; Given region
3608 ((and beg end)
3609 (setq a beg
3610 b end
3611 new-point (+ (point) (length s1))))
3612 ;; Active region
3613 ((markdown-use-region-p)
3614 (setq a (region-beginning)
3615 b (region-end)
3616 new-point (+ (point) (length s1))))
3617 ;; Thing (word) at point
3618 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
3619 (setq a (car bounds)
3620 b (cdr bounds)
3621 new-point (+ (point) (length s1))))
3622 ;; No active region and no word
3624 (setq a (point)
3625 b (point))))
3626 (goto-char b)
3627 (insert s2)
3628 (goto-char a)
3629 (insert s1)
3630 (when new-point (goto-char new-point))
3631 (if (= a b)
3633 (setq b (+ b (length s1) (length s2)))
3634 (cons a b))))
3636 (defun markdown-point-after-unwrap (cur prefix suffix)
3637 "Return desired position of point after an unwrapping operation.
3638 CUR gives the position of the point before the operation.
3639 Additionally, two cons cells must be provided. PREFIX gives the
3640 bounds of the prefix string and SUFFIX gives the bounds of the
3641 suffix string."
3642 (cond ((< cur (cdr prefix)) (car prefix))
3643 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
3644 ((<= cur (cdr suffix))
3645 (- cur (+ (- (cdr prefix) (car prefix))
3646 (- cur (car suffix)))))
3647 (t cur)))
3649 (defun markdown-unwrap-thing-at-point (regexp all text)
3650 "Remove prefix and suffix of thing at point and reposition the point.
3651 When the thing at point matches REGEXP, replace the subexpression
3652 ALL with the string in subexpression TEXT. Reposition the point
3653 in an appropriate location accounting for the removal of prefix
3654 and suffix strings. Return new bounds of string from group TEXT.
3655 When REGEXP is nil, assumes match data is already set."
3656 (when (or (null regexp)
3657 (thing-at-point-looking-at regexp))
3658 (let ((cur (point))
3659 (prefix (cons (match-beginning all) (match-beginning text)))
3660 (suffix (cons (match-end text) (match-end all)))
3661 (bounds (cons (match-beginning text) (match-end text))))
3662 ;; Replace the thing at point
3663 (replace-match (match-string text) t t nil all)
3664 ;; Reposition the point
3665 (goto-char (markdown-point-after-unwrap cur prefix suffix))
3666 ;; Adjust bounds
3667 (setq bounds (cons (car prefix)
3668 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
3670 (defun markdown-unwrap-things-in-region (beg end regexp all text)
3671 "Remove prefix and suffix of all things in region from BEG to END.
3672 When a thing in the region matches REGEXP, replace the
3673 subexpression ALL with the string in subexpression TEXT.
3674 Return a cons cell containing updated bounds for the region."
3675 (save-excursion
3676 (goto-char beg)
3677 (let ((removed 0) len-all len-text)
3678 (while (re-search-forward regexp (- end removed) t)
3679 (setq len-all (length (match-string-no-properties all)))
3680 (setq len-text (length (match-string-no-properties text)))
3681 (setq removed (+ removed (- len-all len-text)))
3682 (replace-match (match-string text) t t nil all))
3683 (cons beg (- end removed)))))
3685 (defun markdown-insert-hr (arg)
3686 "Insert or replace a horizonal rule.
3687 By default, use the first element of `markdown-hr-strings'. When
3688 ARG is non-nil, as when given a prefix, select a different
3689 element as follows. When prefixed with \\[universal-argument],
3690 use the last element of `markdown-hr-strings' instead. When
3691 prefixed with an integer from 1 to the length of
3692 `markdown-hr-strings', use the element in that position instead."
3693 (interactive "*P")
3694 (when (thing-at-point-looking-at markdown-regex-hr)
3695 (delete-region (match-beginning 0) (match-end 0)))
3696 (markdown-ensure-blank-line-before)
3697 (cond ((equal arg '(4))
3698 (insert (car (reverse markdown-hr-strings))))
3699 ((and (integerp arg) (> arg 0)
3700 (<= arg (length markdown-hr-strings)))
3701 (insert (nth (1- arg) markdown-hr-strings)))
3703 (insert (car markdown-hr-strings))))
3704 (markdown-ensure-blank-line-after))
3706 (defun markdown-insert-bold ()
3707 "Insert markup to make a region or word bold.
3708 If there is an active region, make the region bold. If the point
3709 is at a non-bold word, make the word bold. If the point is at a
3710 bold word or phrase, remove the bold markup. Otherwise, simply
3711 insert bold delimiters and place the point in between them."
3712 (interactive)
3713 (let ((delim (if markdown-bold-underscore "__" "**")))
3714 (if (markdown-use-region-p)
3715 ;; Active region
3716 (let ((bounds (markdown-unwrap-things-in-region
3717 (region-beginning) (region-end)
3718 markdown-regex-bold 2 4)))
3719 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3720 ;; Bold markup removal, bold word at point, or empty markup insertion
3721 (if (thing-at-point-looking-at markdown-regex-bold)
3722 (markdown-unwrap-thing-at-point nil 2 4)
3723 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3725 (defun markdown-insert-italic ()
3726 "Insert markup to make a region or word italic.
3727 If there is an active region, make the region italic. If the point
3728 is at a non-italic word, make the word italic. If the point is at an
3729 italic word or phrase, remove the italic markup. Otherwise, simply
3730 insert italic delimiters and place the point in between them."
3731 (interactive)
3732 (let ((delim (if markdown-italic-underscore "_" "*")))
3733 (if (markdown-use-region-p)
3734 ;; Active region
3735 (let ((bounds (markdown-unwrap-things-in-region
3736 (region-beginning) (region-end)
3737 markdown-regex-italic 1 3)))
3738 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3739 ;; Italic markup removal, italic word at point, or empty markup insertion
3740 (if (thing-at-point-looking-at markdown-regex-italic)
3741 (markdown-unwrap-thing-at-point nil 1 3)
3742 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3744 (defun markdown-insert-strike-through ()
3745 "Insert markup to make a region or word strikethrough.
3746 If there is an active region, make the region strikethrough. If the point
3747 is at a non-bold word, make the word strikethrough. If the point is at a
3748 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
3749 simply insert bold delimiters and place the point in between them."
3750 (interactive)
3751 (let ((delim "~~"))
3752 (if (markdown-use-region-p)
3753 ;; Active region
3754 (let ((bounds (markdown-unwrap-things-in-region
3755 (region-beginning) (region-end)
3756 markdown-regex-strike-through 2 4)))
3757 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3758 ;; Strikethrough markup removal, strikethrough word at point, or empty markup insertion
3759 (if (thing-at-point-looking-at markdown-regex-strike-through)
3760 (markdown-unwrap-thing-at-point nil 2 4)
3761 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3763 (defun markdown-insert-code ()
3764 "Insert markup to make a region or word an inline code fragment.
3765 If there is an active region, make the region an inline code
3766 fragment. If the point is at a word, make the word an inline
3767 code fragment. Otherwise, simply insert code delimiters and
3768 place the point in between them."
3769 (interactive)
3770 (if (markdown-use-region-p)
3771 ;; Active region
3772 (let ((bounds (markdown-unwrap-things-in-region
3773 (region-beginning) (region-end)
3774 markdown-regex-code 1 3)))
3775 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
3776 ;; Code markup removal, code markup for word, or empty markup insertion
3777 (if (markdown-inline-code-at-point)
3778 (markdown-unwrap-thing-at-point nil 0 2)
3779 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
3781 (defun markdown-insert-kbd ()
3782 "Insert markup to wrap region or word in <kbd> tags.
3783 If there is an active region, use the region. If the point is at
3784 a word, use the word. Otherwise, simply insert <kbd> tags and
3785 place the point in between them."
3786 (interactive)
3787 (if (markdown-use-region-p)
3788 ;; Active region
3789 (let ((bounds (markdown-unwrap-things-in-region
3790 (region-beginning) (region-end)
3791 markdown-regex-kbd 0 2)))
3792 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil (car bounds) (cdr bounds)))
3793 ;; Markup removal, markup for word, or empty markup insertion
3794 (if (thing-at-point-looking-at markdown-regex-kbd)
3795 (markdown-unwrap-thing-at-point nil 0 2)
3796 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil))))
3798 (defun markdown-insert-inline-link (text url &optional title)
3799 "Insert an inline link with TEXT pointing to URL.
3800 Optionally, the user can provide a TITLE."
3801 (let ((cur (point)))
3802 (setq title (and title (concat " \"" title "\"")))
3803 (insert (concat "[" text "](" url title ")"))
3804 (cond ((not text) (goto-char (+ 1 cur)))
3805 ((not url) (goto-char (+ 3 (length text) cur))))))
3807 (defun markdown-insert-inline-image (text url &optional title)
3808 "Insert an inline link with alt TEXT pointing to URL.
3809 Optionally, also provide a TITLE."
3810 (let ((cur (point)))
3811 (setq title (and title (concat " \"" title "\"")))
3812 (insert (concat "![" text "](" url title ")"))
3813 (cond ((not text) (goto-char (+ 2 cur)))
3814 ((not url) (goto-char (+ 4 (length text) cur))))))
3816 (defun markdown-insert-reference-link (text label &optional url title)
3817 "Insert a reference link and, optionally, a reference definition.
3818 The link TEXT will be inserted followed by the optional LABEL.
3819 If a URL is given, also insert a definition for the reference
3820 LABEL according to `markdown-reference-location'. If a TITLE is
3821 given, it will be added to the end of the reference definition
3822 and will be used to populate the title attribute when converted
3823 to XHTML. If URL is nil, insert only the link portion (for
3824 example, when a reference label is already defined)."
3825 (insert (concat "[" text "][" label "]"))
3826 (when url
3827 (markdown-insert-reference-definition
3828 (if (string-equal label "") text label)
3829 url title)))
3831 (defun markdown-insert-reference-image (text label &optional url title)
3832 "Insert a reference image and, optionally, a reference definition.
3833 The alt TEXT will be inserted followed by the optional LABEL.
3834 If a URL is given, also insert a definition for the reference
3835 LABEL according to `markdown-reference-location'. If a TITLE is
3836 given, it will be added to the end of the reference definition
3837 and will be used to populate the title attribute when converted
3838 to XHTML. If URL is nil, insert only the link portion (for
3839 example, when a reference label is already defined)."
3840 (insert (concat "![" text "][" label "]"))
3841 (when url
3842 (markdown-insert-reference-definition
3843 (if (string-equal label "") text label)
3844 url title)))
3846 (defun markdown-insert-reference-definition (label &optional url title)
3847 "Add definition for reference LABEL with URL and TITLE.
3848 LABEL is a Markdown reference label without square brackets.
3849 URL and TITLE are optional. When given, the TITLE will
3850 be used to populate the title attribute when converted to XHTML."
3851 ;; END specifies where to leave the point upon return
3852 (let ((end (point)))
3853 (cl-case markdown-reference-location
3854 (end (goto-char (point-max)))
3855 (immediately (markdown-end-of-text-block))
3856 (subtree (markdown-end-of-subtree))
3857 (header (markdown-end-of-defun)))
3858 ;; Skip backwards over local variables. This logic is similar to the one
3859 ;; used in ‘hack-local-variables’.
3860 (when (and enable-local-variables (eobp))
3861 (search-backward "\n\f" (max (- (point) 3000) (point-min)) :move)
3862 (when (let ((case-fold-search t))
3863 (search-forward "Local Variables:" nil :move))
3864 (beginning-of-line 0)
3865 (when (eq (char-before) ?\n) (backward-char))))
3866 (unless (or (markdown-cur-line-blank-p)
3867 (thing-at-point-looking-at markdown-regex-reference-definition))
3868 (insert "\n"))
3869 (insert "\n[" label "]: ")
3870 (if url
3871 (insert url)
3872 ;; When no URL is given, leave point at END following the colon
3873 (setq end (point)))
3874 (when (> (length title) 0)
3875 (insert " \"" title "\""))
3876 (unless (looking-at-p "\n")
3877 (insert "\n"))
3878 (goto-char end)
3879 (when url
3880 (message
3881 (markdown--substitute-command-keys
3882 "Reference [%s] was defined, press \\[markdown-do] to jump there")
3883 label))))
3885 (define-obsolete-function-alias
3886 'markdown-insert-inline-link-dwim 'markdown-insert-link "v2.3")
3887 (define-obsolete-function-alias
3888 'markdown-insert-reference-link-dwim 'markdown-insert-link "v2.3")
3890 (defun markdown--insert-link-or-image (image)
3891 "Interactively insert new or update an existing link or image.
3892 When IMAGE is non-nil, insert an image. Otherwise, insert a link.
3893 This is an internal function called by
3894 `markdown-insert-link' and `markdown-insert-image'."
3895 (cl-multiple-value-bind (begin end text uri ref title)
3896 (if (markdown-use-region-p)
3897 ;; Use region as either link text or URL as appropriate.
3898 (let ((region (buffer-substring-no-properties
3899 (region-beginning) (region-end))))
3900 (if (string-match markdown-regex-uri region)
3901 ;; Region contains a URL; use it as such.
3902 (list (region-beginning) (region-end)
3903 nil (match-string 0 region) nil nil)
3904 ;; Region doesn't contain a URL, so use it as text.
3905 (list (region-beginning) (region-end)
3906 region nil nil nil)))
3907 ;; Extract and use properties of existing link, if any.
3908 (markdown-link-at-pos (point)))
3909 (let* ((ref (when ref (concat "[" ref "]")))
3910 (defined-refs (append
3911 (mapcar (lambda (ref) (concat "[" ref "]"))
3912 (markdown-get-defined-references))))
3913 (used-uris (markdown-get-used-uris))
3914 (uri-or-ref (completing-read
3915 "URL or [reference]: "
3916 (append defined-refs used-uris)
3917 nil nil (or uri ref)))
3918 (ref (cond ((string-match "\\`\\[\\(.*\\)\\]\\'" uri-or-ref)
3919 (match-string 1 uri-or-ref))
3920 ((string-equal "" uri-or-ref)
3921 "")))
3922 (uri (unless ref uri-or-ref))
3923 (text-prompt (if image
3924 "Alt text: "
3925 (if ref
3926 "Link text: "
3927 "Link text (blank for plain URL): ")))
3928 (text (read-string text-prompt text))
3929 (text (if (= (length text) 0) nil text))
3930 (plainp (and uri (not text)))
3931 (implicitp (string-equal ref ""))
3932 (ref (if implicitp text ref))
3933 (definedp (and ref (markdown-reference-definition ref)))
3934 (ref-url (unless (or uri definedp)
3935 (completing-read "Reference URL: " used-uris)))
3936 (title (unless (or plainp definedp)
3937 (read-string "Title (tooltip text, optional): " title)))
3938 (title (if (= (length title) 0) nil title)))
3939 (when (and image implicitp)
3940 (user-error "Reference required: implicit image references are invalid"))
3941 (when (and begin end)
3942 (delete-region begin end))
3943 (cond
3944 ((and (not image) uri text)
3945 (markdown-insert-inline-link text uri title))
3946 ((and image uri text)
3947 (markdown-insert-inline-image text uri title))
3948 ((and ref text)
3949 (if image
3950 (markdown-insert-reference-image text (unless implicitp ref) nil title)
3951 (markdown-insert-reference-link text (unless implicitp ref) nil title))
3952 (unless definedp
3953 (markdown-insert-reference-definition ref ref-url title)))
3954 ((and (not image) uri)
3955 (markdown-insert-uri uri))))))
3957 (defun markdown-insert-link ()
3958 "Insert new or update an existing link, with interactive prompts.
3959 If the point is at an existing link or URL, update the link text,
3960 URL, reference label, and/or title. Otherwise, insert a new link.
3961 The type of link inserted (inline, reference, or plain URL)
3962 depends on which values are provided:
3964 * If a URL and TEXT are given, insert an inline link: [TEXT](URL).
3965 * If [REF] and TEXT are given, insert a reference link: [TEXT][REF].
3966 * If only TEXT is given, insert an implicit reference link: [TEXT][].
3967 * If only a URL is given, insert a plain link: <URL>.
3969 In other words, to create an implicit reference link, leave the
3970 URL prompt empty and to create a plain URL link, leave the link
3971 text empty.
3973 If there is an active region, use the text as the default URL, if
3974 it seems to be a URL, or link text value otherwise.
3976 If a given reference is not defined, this function will
3977 additionally prompt for the URL and optional title. In this case,
3978 the reference definition is placed at the location determined by
3979 `markdown-reference-location'.
3981 Through updating the link, this function can be used to convert a
3982 link of one type (inline, reference, or plain) to another type by
3983 selectively adding or removing information via the prompts."
3984 (interactive)
3985 (markdown--insert-link-or-image nil))
3987 (defun markdown-insert-image ()
3988 "Insert new or update an existing image, with interactive prompts.
3989 If the point is at an existing image, update the alt text, URL,
3990 reference label, and/or title. Otherwise, insert a new image.
3991 The type of image inserted (inline or reference) depends on which
3992 values are provided:
3994 * If a URL and ALT-TEXT are given, insert an inline image:
3995 ![ALT-TEXT](URL).
3996 * If [REF] and ALT-TEXT are given, insert a reference image:
3997 ![ALT-TEXT][REF].
3999 If there is an active region, use the text as the default URL, if
4000 it seems to be a URL, or alt text value otherwise.
4002 If a given reference is not defined, this function will
4003 additionally prompt for the URL and optional title. In this case,
4004 the reference definition is placed at the location determined by
4005 `markdown-reference-location'.
4007 Through updating the image, this function can be used to convert an
4008 image of one type (inline or reference) to another type by
4009 selectively adding or removing information via the prompts."
4010 (interactive)
4011 (markdown--insert-link-or-image t))
4013 (defun markdown-insert-uri (&optional uri)
4014 "Insert markup for an inline URI.
4015 If there is an active region, use it as the URI. If the point is
4016 at a URI, wrap it with angle brackets. If the point is at an
4017 inline URI, remove the angle brackets. Otherwise, simply insert
4018 angle brackets place the point between them."
4019 (interactive)
4020 (if (markdown-use-region-p)
4021 ;; Active region
4022 (let ((bounds (markdown-unwrap-things-in-region
4023 (region-beginning) (region-end)
4024 markdown-regex-angle-uri 0 2)))
4025 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
4026 ;; Markup removal, URI at point, new URI, or empty markup insertion
4027 (if (thing-at-point-looking-at markdown-regex-angle-uri)
4028 (markdown-unwrap-thing-at-point nil 0 2)
4029 (if uri
4030 (insert "<" uri ">")
4031 (markdown-wrap-or-insert "<" ">" 'url nil nil)))))
4033 (defun markdown-insert-wiki-link ()
4034 "Insert a wiki link of the form [[WikiLink]].
4035 If there is an active region, use the region as the link text.
4036 If the point is at a word, use the word as the link text. If
4037 there is no active region and the point is not at word, simply
4038 insert link markup."
4039 (interactive)
4040 (if (markdown-use-region-p)
4041 ;; Active region
4042 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
4043 ;; Markup removal, wiki link at at point, or empty markup insertion
4044 (if (thing-at-point-looking-at markdown-regex-wiki-link)
4045 (if (or markdown-wiki-link-alias-first
4046 (null (match-string 5)))
4047 (markdown-unwrap-thing-at-point nil 1 3)
4048 (markdown-unwrap-thing-at-point nil 1 5))
4049 (markdown-wrap-or-insert "[[" "]]"))))
4051 (defun markdown-remove-header ()
4052 "Remove header markup if point is at a header.
4053 Return bounds of remaining header text if a header was removed
4054 and nil otherwise."
4055 (interactive "*")
4056 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
4057 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
4059 (defun markdown-insert-header (&optional level text setext)
4060 "Insert or replace header markup.
4061 The level of the header is specified by LEVEL and header text is
4062 given by TEXT. LEVEL must be an integer from 1 and 6, and the
4063 default value is 1.
4064 When TEXT is nil, the header text is obtained as follows.
4065 If there is an active region, it is used as the header text.
4066 Otherwise, the current line will be used as the header text.
4067 If there is not an active region and the point is at a header,
4068 remove the header markup and replace with level N header.
4069 Otherwise, insert empty header markup and place the point in
4070 between.
4071 The style of the header will be atx (hash marks) unless
4072 SETEXT is non-nil, in which case a setext-style (underlined)
4073 header will be inserted."
4074 (interactive "p\nsHeader text: ")
4075 (setq level (min (max (or level 1) 1) (if setext 2 6)))
4076 ;; Determine header text if not given
4077 (when (null text)
4078 (if (markdown-use-region-p)
4079 ;; Active region
4080 (setq text (delete-and-extract-region (region-beginning) (region-end)))
4081 ;; No active region
4082 (markdown-remove-header)
4083 (setq text (delete-and-extract-region
4084 (line-beginning-position) (line-end-position)))
4085 (when (and setext (string-match-p "^[ \t]*$" text))
4086 (setq text (read-string "Header text: "))))
4087 (setq text (markdown-compress-whitespace-string text)))
4088 ;; Insertion with given text
4089 (markdown-ensure-blank-line-before)
4090 (let (hdr)
4091 (cond (setext
4092 (setq hdr (make-string (string-width text) (if (= level 2) ?- ?=)))
4093 (insert text "\n" hdr))
4095 (setq hdr (make-string level ?#))
4096 (insert hdr " " text)
4097 (when (null markdown-asymmetric-header) (insert " " hdr)))))
4098 (markdown-ensure-blank-line-after)
4099 ;; Leave point at end of text
4100 (cond (setext
4101 (backward-char (1+ (string-width text))))
4102 ((null markdown-asymmetric-header)
4103 (backward-char (1+ level)))))
4105 (defun markdown-insert-header-dwim (&optional arg setext)
4106 "Insert or replace header markup.
4107 The level and type of the header are determined automatically by
4108 the type and level of the previous header, unless a prefix
4109 argument is given via ARG.
4110 With a numeric prefix valued 1 to 6, insert a header of the given
4111 level, with the type being determined automatically (note that
4112 only level 1 or 2 setext headers are possible).
4114 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
4115 promote the heading by one level.
4116 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
4117 demote the heading by one level.
4118 When SETEXT is non-nil, prefer setext-style headers when
4119 possible (levels one and two).
4121 When there is an active region, use it for the header text. When
4122 the point is at an existing header, change the type and level
4123 according to the rules above.
4124 Otherwise, if the line is not empty, create a header using the
4125 text on the current line as the header text.
4126 Finally, if the point is on a blank line, insert empty header
4127 markup (atx) or prompt for text (setext).
4128 See `markdown-insert-header' for more details about how the
4129 header text is determined."
4130 (interactive "*P")
4131 (let (level)
4132 (save-excursion
4133 (when (or (thing-at-point-looking-at markdown-regex-header)
4134 (re-search-backward markdown-regex-header nil t))
4135 ;; level of current or previous header
4136 (setq level (markdown-outline-level))
4137 ;; match group 1 indicates a setext header
4138 (setq setext (match-end 1))))
4139 ;; check prefix argument
4140 (cond
4141 ((and (equal arg '(4)) level (> level 1)) ;; C-u
4142 (cl-decf level))
4143 ((and (equal arg '(16)) level (< level 6)) ;; C-u C-u
4144 (cl-incf level))
4145 (arg ;; numeric prefix
4146 (setq level (prefix-numeric-value arg))))
4147 ;; setext headers must be level one or two
4148 (and level (setq setext (and setext (<= level 2))))
4149 ;; insert the heading
4150 (markdown-insert-header level nil setext)))
4152 (defun markdown-insert-header-setext-dwim (&optional arg)
4153 "Insert or replace header markup, with preference for setext.
4154 See `markdown-insert-header-dwim' for details, including how ARG is handled."
4155 (interactive "*P")
4156 (markdown-insert-header-dwim arg t))
4158 (defun markdown-insert-header-atx-1 ()
4159 "Insert a first level atx-style (hash mark) header.
4160 See `markdown-insert-header'."
4161 (interactive "*")
4162 (markdown-insert-header 1 nil nil))
4164 (defun markdown-insert-header-atx-2 ()
4165 "Insert a level two atx-style (hash mark) header.
4166 See `markdown-insert-header'."
4167 (interactive "*")
4168 (markdown-insert-header 2 nil nil))
4170 (defun markdown-insert-header-atx-3 ()
4171 "Insert a level three atx-style (hash mark) header.
4172 See `markdown-insert-header'."
4173 (interactive "*")
4174 (markdown-insert-header 3 nil nil))
4176 (defun markdown-insert-header-atx-4 ()
4177 "Insert a level four atx-style (hash mark) header.
4178 See `markdown-insert-header'."
4179 (interactive "*")
4180 (markdown-insert-header 4 nil nil))
4182 (defun markdown-insert-header-atx-5 ()
4183 "Insert a level five atx-style (hash mark) header.
4184 See `markdown-insert-header'."
4185 (interactive "*")
4186 (markdown-insert-header 5 nil nil))
4188 (defun markdown-insert-header-atx-6 ()
4189 "Insert a sixth level atx-style (hash mark) header.
4190 See `markdown-insert-header'."
4191 (interactive "*")
4192 (markdown-insert-header 6 nil nil))
4194 (defun markdown-insert-header-setext-1 ()
4195 "Insert a setext-style (underlined) first-level header.
4196 See `markdown-insert-header'."
4197 (interactive "*")
4198 (markdown-insert-header 1 nil t))
4200 (defun markdown-insert-header-setext-2 ()
4201 "Insert a setext-style (underlined) second-level header.
4202 See `markdown-insert-header'."
4203 (interactive "*")
4204 (markdown-insert-header 2 nil t))
4206 (defun markdown-blockquote-indentation (loc)
4207 "Return string containing necessary indentation for a blockquote at LOC.
4208 Also see `markdown-pre-indentation'."
4209 (save-excursion
4210 (goto-char loc)
4211 (let* ((list-level (length (markdown-calculate-list-levels)))
4212 (indent ""))
4213 (dotimes (_ list-level indent)
4214 (setq indent (concat indent " "))))))
4216 (defun markdown-insert-blockquote ()
4217 "Start a blockquote section (or blockquote the region).
4218 If Transient Mark mode is on and a region is active, it is used as
4219 the blockquote text."
4220 (interactive)
4221 (if (markdown-use-region-p)
4222 (markdown-blockquote-region (region-beginning) (region-end))
4223 (markdown-ensure-blank-line-before)
4224 (insert (markdown-blockquote-indentation (point)) "> ")
4225 (markdown-ensure-blank-line-after)))
4227 (defun markdown-block-region (beg end prefix)
4228 "Format the region using a block prefix.
4229 Arguments BEG and END specify the beginning and end of the
4230 region. The characters PREFIX will appear at the beginning
4231 of each line."
4232 (save-excursion
4233 (let* ((end-marker (make-marker))
4234 (beg-marker (make-marker))
4235 (prefix-without-trailing-whitespace
4236 (replace-regexp-in-string (rx (+ blank) eos) "" prefix)))
4237 ;; Ensure blank line after and remove extra whitespace
4238 (goto-char end)
4239 (skip-syntax-backward "-")
4240 (set-marker end-marker (point))
4241 (delete-horizontal-space)
4242 (markdown-ensure-blank-line-after)
4243 ;; Ensure blank line before and remove extra whitespace
4244 (goto-char beg)
4245 (skip-syntax-forward "-")
4246 (delete-horizontal-space)
4247 (markdown-ensure-blank-line-before)
4248 (set-marker beg-marker (point))
4249 ;; Insert PREFIX before each line
4250 (goto-char beg-marker)
4251 (while (and (< (line-beginning-position) end-marker)
4252 (not (eobp)))
4253 ;; Don’t insert trailing whitespace.
4254 (insert (if (eolp) prefix-without-trailing-whitespace prefix))
4255 (forward-line)))))
4257 (defun markdown-blockquote-region (beg end)
4258 "Blockquote the region.
4259 Arguments BEG and END specify the beginning and end of the region."
4260 (interactive "*r")
4261 (markdown-block-region
4262 beg end (concat (markdown-blockquote-indentation
4263 (max (point-min) (1- beg))) "> ")))
4265 (defun markdown-pre-indentation (loc)
4266 "Return string containing necessary whitespace for a pre block at LOC.
4267 Also see `markdown-blockquote-indentation'."
4268 (save-excursion
4269 (goto-char loc)
4270 (let* ((list-level (length (markdown-calculate-list-levels)))
4271 indent)
4272 (dotimes (_ (1+ list-level) indent)
4273 (setq indent (concat indent " "))))))
4275 (defun markdown-insert-pre ()
4276 "Start a preformatted section (or apply to the region).
4277 If Transient Mark mode is on and a region is active, it is marked
4278 as preformatted text."
4279 (interactive)
4280 (if (markdown-use-region-p)
4281 (markdown-pre-region (region-beginning) (region-end))
4282 (markdown-ensure-blank-line-before)
4283 (insert (markdown-pre-indentation (point)))
4284 (markdown-ensure-blank-line-after)))
4286 (defun markdown-pre-region (beg end)
4287 "Format the region as preformatted text.
4288 Arguments BEG and END specify the beginning and end of the region."
4289 (interactive "*r")
4290 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
4291 (markdown-block-region beg end indent)))
4293 (defun markdown-electric-backquote (arg)
4294 "Insert a backquote.
4295 The numeric prefix argument ARG says how many times to repeat the insertion.
4296 Call `markdown-insert-gfm-code-block' interactively
4297 if three backquotes inserted at the beginning of line."
4298 (interactive "*P")
4299 (self-insert-command (prefix-numeric-value arg))
4300 (when (and markdown-gfm-use-electric-backquote (looking-back "^```" nil))
4301 (replace-match "")
4302 (call-interactively #'markdown-insert-gfm-code-block)))
4304 (defconst markdown-gfm-recognized-languages
4305 ;; To reproduce/update, evaluate the let-form in
4306 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
4307 ;; but with appropriate use of a keyboard macro, indenting and filling it
4308 ;; properly is pretty fast.
4309 '("1C-Enterprise" "ABAP" "ABNF" "AGS-Script" "AMPL" "ANTLR"
4310 "API-Blueprint" "APL" "ASN.1" "ASP" "ATS" "ActionScript" "Ada" "Agda"
4311 "Alloy" "Alpine-Abuild" "Ant-Build-System" "ApacheConf" "Apex"
4312 "Apollo-Guidance-Computer" "AppleScript" "Arc" "Arduino" "AsciiDoc"
4313 "AspectJ" "Assembly" "Augeas" "AutoHotkey" "AutoIt" "Awk" "Batchfile"
4314 "Befunge" "Bison" "BitBake" "Blade" "BlitzBasic" "BlitzMax" "Bluespec"
4315 "Boo" "Brainfuck" "Brightscript" "Bro" "C#" "C++" "C-ObjDump"
4316 "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "COLLADA" "CSON" "CSS" "CSV"
4317 "CWeb" "Cap'n-Proto" "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK"
4318 "Cirru" "Clarion" "Clean" "Click" "Clojure" "Closure-Templates"
4319 "CoffeeScript" "ColdFusion" "ColdFusion-CFC" "Common-Lisp"
4320 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal"
4321 "Csound" "Csound-Document" "Csound-Score" "Cuda" "Cycript" "Cython"
4322 "D-ObjDump" "DIGITAL-Command-Language" "DM" "DNS-Zone" "DTrace"
4323 "Darcs-Patch" "Dart" "Diff" "Dockerfile" "Dogescript" "Dylan" "EBNF"
4324 "ECL" "ECLiPSe" "EJS" "EQ" "Eagle" "Ecere-Projects" "Eiffel" "Elixir"
4325 "Elm" "Emacs-Lisp" "EmberScript" "Erlang" "F#" "FLUX" "Factor" "Fancy"
4326 "Fantom" "Filebench-WML" "Filterscript" "Formatted" "Forth" "Fortran"
4327 "FreeMarker" "Frege" "G-code" "GAMS" "GAP" "GCC-Machine-Description"
4328 "GDB" "GDScript" "GLSL" "GN" "Game-Maker-Language" "Genie" "Genshi"
4329 "Gentoo-Ebuild" "Gentoo-Eclass" "Gettext-Catalog" "Gherkin" "Glyph"
4330 "Gnuplot" "Go" "Golo" "Gosu" "Grace" "Gradle" "Grammatical-Framework"
4331 "Graph-Modeling-Language" "GraphQL" "Graphviz-(DOT)" "Groovy"
4332 "Groovy-Server-Pages" "HCL" "HLSL" "HTML" "HTML+Django" "HTML+ECR"
4333 "HTML+EEX" "HTML+ERB" "HTML+PHP" "HTTP" "Hack" "Haml" "Handlebars"
4334 "Harbour" "Haskell" "Haxe" "Hy" "HyPhy" "IDL" "IGOR-Pro" "INI"
4335 "IRC-log" "Idris" "Inform-7" "Inno-Setup" "Io" "Ioke" "Isabelle"
4336 "Isabelle-ROOT" "JFlex" "JSON" "JSON5" "JSONLD" "JSONiq" "JSX"
4337 "Jasmin" "Java" "Java-Server-Pages" "JavaScript" "Jison" "Jison-Lex"
4338 "Jolie" "Julia" "Jupyter-Notebook" "KRL" "KiCad" "Kit" "Kotlin" "LFE"
4339 "LLVM" "LOLCODE" "LSL" "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex"
4340 "LilyPond" "Limbo" "Linker-Script" "Linux-Kernel-Module" "Liquid"
4341 "Literate-Agda" "Literate-CoffeeScript" "Literate-Haskell"
4342 "LiveScript" "Logos" "Logtalk" "LookML" "LoomScript" "Lua" "M4"
4343 "M4Sugar" "MAXScript" "MQL4" "MQL5" "MTML" "MUF" "Makefile" "Mako"
4344 "Markdown" "Marko" "Mask" "Mathematica" "Matlab" "Maven-POM" "Max"
4345 "MediaWiki" "Mercury" "Meson" "Metal" "MiniD" "Mirah" "Modelica"
4346 "Modula-2" "Module-Management-System" "Monkey" "Moocode" "MoonScript"
4347 "Myghty" "NCL" "NL" "NSIS" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo"
4348 "NewLisp" "Nginx" "Nim" "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml"
4349 "ObjDump" "Objective-C" "Objective-C++" "Objective-J" "Omgrofl" "Opa"
4350 "Opal" "OpenCL" "OpenEdge-ABL" "OpenRC-runscript" "OpenSCAD"
4351 "OpenType-Feature-File" "Org" "Ox" "Oxygene" "Oz" "P4" "PAWN" "PHP"
4352 "PLSQL" "PLpgSQL" "POV-Ray-SDL" "Pan" "Papyrus" "Parrot"
4353 "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal" "Pep8"
4354 "Perl" "Perl6" "Pic" "Pickle" "PicoLisp" "PigLatin" "Pike" "Pod"
4355 "PogoScript" "Pony" "PostScript" "PowerBuilder" "PowerShell"
4356 "Processing" "Prolog" "Propeller-Spin" "Protocol-Buffer" "Public-Key"
4357 "Pug" "Puppet" "Pure-Data" "PureBasic" "PureScript" "Python"
4358 "Python-console" "Python-traceback" "QML" "QMake" "RAML" "RDoc"
4359 "REALbasic" "REXX" "RHTML" "RMarkdown" "RPM-Spec" "RUNOFF" "Racket"
4360 "Ragel" "Rascal" "Raw-token-data" "Reason" "Rebol" "Red" "Redcode"
4361 "Regular-Expression" "Ren'Py" "RenderScript" "RobotFramework" "Roff"
4362 "Rouge" "Ruby" "Rust" "SAS" "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL"
4363 "SRecode-Template" "STON" "SVG" "Sage" "SaltStack" "Sass" "Scala"
4364 "Scaml" "Scheme" "Scilab" "Self" "ShaderLab" "Shell" "ShellSession"
4365 "Shen" "Slash" "Slim" "Smali" "Smalltalk" "Smarty" "SourcePawn"
4366 "Spline-Font-Database" "Squirrel" "Stan" "Standard-ML" "Stata"
4367 "Stylus" "SubRip-Text" "Sublime-Text-Config" "SuperCollider" "Swift"
4368 "SystemVerilog" "TI-Program" "TLA" "TOML" "TXL" "Tcl" "Tcsh" "TeX"
4369 "Tea" "Terra" "Text" "Textile" "Thrift" "Turing" "Turtle" "Twig"
4370 "Type-Language" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset"
4371 "Unix-Assembly" "Uno" "UnrealScript" "UrWeb" "VCL" "VHDL" "Vala"
4372 "Verilog" "Vim-script" "Visual-Basic" "Volt" "Vue"
4373 "Wavefront-Material" "Wavefront-Object" "Web-Ontology-Language"
4374 "WebAssembly" "WebIDL" "World-of-Warcraft-Addon-Data" "X10" "XC"
4375 "XCompose" "XML" "XPages" "XProc" "XQuery" "XS" "XSLT" "Xojo" "Xtend"
4376 "YAML" "YANG" "Yacc" "Zephir" "Zimpl" "desktop" "eC" "edn" "fish"
4377 "mupad" "nesC" "ooc" "reStructuredText" "wisp" "xBase")
4378 "Language specifiers recognized by GitHub's syntax highlighting features.")
4380 (defvar markdown-gfm-used-languages nil
4381 "Language names used in GFM code blocks.")
4382 (make-variable-buffer-local 'markdown-gfm-used-languages)
4384 (defun markdown-trim-whitespace (str)
4385 (markdown-replace-regexp-in-string
4386 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str))
4388 (defun markdown-clean-language-string (str)
4389 (markdown-replace-regexp-in-string
4390 "{\\.?\\|}" "" (markdown-trim-whitespace str)))
4392 (defun markdown-validate-language-string (widget)
4393 (let ((str (widget-value widget)))
4394 (unless (string= str (markdown-clean-language-string str))
4395 (widget-put widget :error (format "Invalid language spec: '%s'" str))
4396 widget)))
4398 (defun markdown-gfm-get-corpus ()
4399 "Create corpus of recognized GFM code block languages for the given buffer."
4400 (let ((given-corpus (append markdown-gfm-additional-languages
4401 markdown-gfm-recognized-languages)))
4402 (append
4403 markdown-gfm-used-languages
4404 (if markdown-gfm-downcase-languages (cl-mapcar #'downcase given-corpus)
4405 given-corpus))))
4407 (defun markdown-gfm-add-used-language (lang)
4408 "Clean LANG and add to list of used languages."
4409 (setq markdown-gfm-used-languages
4410 (cons lang (remove lang markdown-gfm-used-languages))))
4412 (defcustom markdown-spaces-after-code-fence 1
4413 "Number of space characters to insert after a code fence.
4414 \\<gfm-mode-map>\\[markdown-insert-gfm-code-block] inserts this many spaces between an
4415 opening code fence and an info string."
4416 :group 'markdown
4417 :type 'integer
4418 :safe #'natnump
4419 :package-version '(markdown-mode . "2.3"))
4421 (defun markdown-insert-gfm-code-block (&optional lang edit)
4422 "Insert GFM code block for language LANG.
4423 If LANG is nil, the language will be queried from user. If a
4424 region is active, wrap this region with the markup instead. If
4425 the region boundaries are not on empty lines, these are added
4426 automatically in order to have the correct markup. When EDIT is
4427 non-nil (e.g., when \\[universal-argument] is given), edit the
4428 code block in an indirect buffer after insertion."
4429 (interactive
4430 (list (let ((completion-ignore-case nil))
4431 (condition-case nil
4432 (markdown-clean-language-string
4433 (completing-read
4434 "Programming language: "
4435 (markdown-gfm-get-corpus)
4436 nil 'confirm (car markdown-gfm-used-languages)
4437 'markdown-gfm-language-history))
4438 (quit "")))
4439 current-prefix-arg))
4440 (unless (string= lang "") (markdown-gfm-add-used-language lang))
4441 (when (> (length lang) 0)
4442 (setq lang (concat (make-string markdown-spaces-after-code-fence ?\s)
4443 lang)))
4444 (if (markdown-use-region-p)
4445 (let* ((b (region-beginning)) (e (region-end)) end
4446 (indent (progn (goto-char b) (current-indentation))))
4447 (goto-char e)
4448 ;; if we're on a blank line, don't newline, otherwise the ```
4449 ;; should go on its own line
4450 (unless (looking-back "\n" nil)
4451 (newline))
4452 (indent-to indent)
4453 (insert "```")
4454 (markdown-ensure-blank-line-after)
4455 (setq end (point))
4456 (goto-char b)
4457 ;; if we're on a blank line, insert the quotes here, otherwise
4458 ;; add a new line first
4459 (unless (looking-at-p "\n")
4460 (newline)
4461 (forward-line -1))
4462 (markdown-ensure-blank-line-before)
4463 (indent-to indent)
4464 (insert "```" lang)
4465 (markdown-syntax-propertize-fenced-block-constructs (point-at-bol) end))
4466 (let ((indent (current-indentation)) start-bol)
4467 (delete-horizontal-space :backward-only)
4468 (markdown-ensure-blank-line-before)
4469 (indent-to indent)
4470 (setq start-bol (point-at-bol))
4471 (insert "```" lang "\n")
4472 (indent-to indent)
4473 (unless edit (insert ?\n))
4474 (indent-to indent)
4475 (insert "```")
4476 (markdown-ensure-blank-line-after)
4477 (markdown-syntax-propertize-fenced-block-constructs start-bol (point)))
4478 (end-of-line 0)
4479 (when edit (markdown-edit-code-block))))
4481 (defun markdown-code-block-lang (&optional pos-prop)
4482 "Return the language name for a GFM or tilde fenced code block.
4483 The beginning of the block may be described by POS-PROP,
4484 a cons of (pos . prop) giving the position and property
4485 at the beginning of the block."
4486 (or pos-prop
4487 (setq pos-prop
4488 (markdown-max-of-seq
4489 #'car
4490 (cl-remove-if
4491 #'null
4492 (cl-mapcar
4493 #'markdown-find-previous-prop
4494 (markdown-get-fenced-block-begin-properties))))))
4495 (when pos-prop
4496 (goto-char (car pos-prop))
4497 (set-match-data (get-text-property (point) (cdr pos-prop)))
4498 ;; Note: Hard-coded group number assumes tilde
4499 ;; and GFM fenced code regexp groups agree.
4500 (let ((begin (match-beginning 3))
4501 (end (match-end 3)))
4502 (when (and begin end)
4503 ;; Fix language strings beginning with periods, like ".ruby".
4504 (when (eq (char-after begin) ?.)
4505 (setq begin (1+ begin)))
4506 (buffer-substring-no-properties begin end)))))
4508 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer)
4509 (with-current-buffer (or buffer (current-buffer))
4510 (save-excursion
4511 (goto-char (point-min))
4512 (cl-loop
4513 with prop = 'markdown-gfm-block-begin
4514 for pos-prop = (markdown-find-next-prop prop)
4515 while pos-prop
4516 for lang = (markdown-code-block-lang pos-prop)
4517 do (progn (when lang (markdown-gfm-add-used-language lang))
4518 (goto-char (next-single-property-change (point) prop)))))))
4521 ;;; Footnotes ==================================================================
4523 (defun markdown-footnote-counter-inc ()
4524 "Increment `markdown-footnote-counter' and return the new value."
4525 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
4526 (save-excursion
4527 (goto-char (point-min))
4528 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
4529 (point-max) t)
4530 (let ((fn (string-to-number (match-string 1))))
4531 (when (> fn markdown-footnote-counter)
4532 (setq markdown-footnote-counter fn))))))
4533 (cl-incf markdown-footnote-counter))
4535 (defun markdown-insert-footnote ()
4536 "Insert footnote with a new number and move point to footnote definition."
4537 (interactive)
4538 (let ((fn (markdown-footnote-counter-inc)))
4539 (insert (format "[^%d]" fn))
4540 (markdown-footnote-text-find-new-location)
4541 (markdown-ensure-blank-line-before)
4542 (unless (markdown-cur-line-blank-p)
4543 (insert "\n"))
4544 (insert (format "[^%d]: " fn))
4545 (markdown-ensure-blank-line-after)))
4547 (defun markdown-footnote-text-find-new-location ()
4548 "Position the point at the proper location for a new footnote text."
4549 (cond
4550 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
4551 ((eq markdown-footnote-location 'immediately) (markdown-end-of-text-block))
4552 ((eq markdown-footnote-location 'subtree) (markdown-end-of-subtree))
4553 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
4555 (defun markdown-footnote-kill ()
4556 "Kill the footnote at point.
4557 The footnote text is killed (and added to the kill ring), the
4558 footnote marker is deleted. Point has to be either at the
4559 footnote marker or in the footnote text."
4560 (interactive)
4561 (let ((marker-pos nil)
4562 (skip-deleting-marker nil)
4563 (starting-footnote-text-positions
4564 (markdown-footnote-text-positions)))
4565 (when starting-footnote-text-positions
4566 ;; We're starting in footnote text, so mark our return position and jump
4567 ;; to the marker if possible.
4568 (let ((marker-pos (markdown-footnote-find-marker
4569 (cl-first starting-footnote-text-positions))))
4570 (if marker-pos
4571 (goto-char (1- marker-pos))
4572 ;; If there isn't a marker, we still want to kill the text.
4573 (setq skip-deleting-marker t))))
4574 ;; Either we didn't start in the text, or we started in the text and jumped
4575 ;; to the marker. We want to assume we're at the marker now and error if
4576 ;; we're not.
4577 (unless skip-deleting-marker
4578 (let ((marker (markdown-footnote-delete-marker)))
4579 (unless marker
4580 (error "Not at a footnote"))
4581 ;; Even if we knew the text position before, it changed when we deleted
4582 ;; the label.
4583 (setq marker-pos (cl-second marker))
4584 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker))))
4585 (unless new-text-pos
4586 (error "No text for footnote `%s'" (cl-first marker)))
4587 (goto-char new-text-pos))))
4588 (let ((pos (markdown-footnote-kill-text)))
4589 (goto-char (if starting-footnote-text-positions
4591 marker-pos)))))
4593 (defun markdown-footnote-delete-marker ()
4594 "Delete a footnote marker at point.
4595 Returns a list (ID START) containing the footnote ID and the
4596 start position of the marker before deletion. If no footnote
4597 marker was deleted, this function returns NIL."
4598 (let ((marker (markdown-footnote-marker-positions)))
4599 (when marker
4600 (delete-region (cl-second marker) (cl-third marker))
4601 (butlast marker))))
4603 (defun markdown-footnote-kill-text ()
4604 "Kill footnote text at point.
4605 Returns the start position of the footnote text before deletion,
4606 or NIL if point was not inside a footnote text.
4608 The killed text is placed in the kill ring (without the footnote
4609 number)."
4610 (let ((fn (markdown-footnote-text-positions)))
4611 (when fn
4612 (let ((text (delete-and-extract-region (cl-second fn) (cl-third fn))))
4613 (string-match (concat "\\[\\" (cl-first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
4614 (kill-new (match-string 1 text))
4615 (when (and (markdown-cur-line-blank-p)
4616 (markdown-prev-line-blank-p)
4617 (not (bobp)))
4618 (delete-region (1- (point)) (point)))
4619 (cl-second fn)))))
4621 (defun markdown-footnote-goto-text ()
4622 "Jump to the text of the footnote at point."
4623 (interactive)
4624 (let ((fn (car (markdown-footnote-marker-positions))))
4625 (unless fn
4626 (user-error "Not at a footnote marker"))
4627 (let ((new-pos (markdown-footnote-find-text fn)))
4628 (unless new-pos
4629 (error "No definition found for footnote `%s'" fn))
4630 (goto-char new-pos))))
4632 (defun markdown-footnote-return ()
4633 "Return from a footnote to its footnote number in the main text."
4634 (interactive)
4635 (let ((fn (save-excursion
4636 (car (markdown-footnote-text-positions)))))
4637 (unless fn
4638 (user-error "Not in a footnote"))
4639 (let ((new-pos (markdown-footnote-find-marker fn)))
4640 (unless new-pos
4641 (error "Footnote marker `%s' not found" fn))
4642 (goto-char new-pos))))
4644 (defun markdown-footnote-find-marker (id)
4645 "Find the location of the footnote marker with ID.
4646 The actual buffer position returned is the position directly
4647 following the marker's closing bracket. If no marker is found,
4648 NIL is returned."
4649 (save-excursion
4650 (goto-char (point-min))
4651 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
4652 (skip-chars-backward "^]")
4653 (point))))
4655 (defun markdown-footnote-find-text (id)
4656 "Find the location of the text of footnote ID.
4657 The actual buffer position returned is the position of the first
4658 character of the text, after the footnote's identifier. If no
4659 footnote text is found, NIL is returned."
4660 (save-excursion
4661 (goto-char (point-min))
4662 (when (re-search-forward (concat "^ \\{0,3\\}\\[" id "\\]:") nil t)
4663 (skip-chars-forward "[ \t]")
4664 (point))))
4666 (defun markdown-footnote-marker-positions ()
4667 "Return the position and ID of the footnote marker point is on.
4668 The return value is a list (ID START END). If point is not on a
4669 footnote, NIL is returned."
4670 ;; first make sure we're at a footnote marker
4671 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
4672 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
4673 (save-excursion
4674 ;; move point between [ and ^:
4675 (if (looking-at-p "\\[")
4676 (forward-char 1)
4677 (skip-chars-backward "^["))
4678 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
4679 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
4681 (defun markdown-footnote-text-positions ()
4682 "Return the start and end positions of the footnote text point is in.
4683 The exact return value is a list of three elements: (ID START END).
4684 The start position is the position of the opening bracket
4685 of the footnote id. The end position is directly after the
4686 newline that ends the footnote. If point is not in a footnote,
4687 NIL is returned instead."
4688 (save-excursion
4689 (let (result)
4690 (move-beginning-of-line 1)
4691 ;; Try to find the label. If we haven't found the label and we're at a blank
4692 ;; or indented line, back up if possible.
4693 (while (and
4694 (not (and (looking-at markdown-regex-footnote-definition)
4695 (setq result (list (match-string 1) (point)))))
4696 (and (not (bobp))
4697 (or (markdown-cur-line-blank-p)
4698 (>= (current-indentation) 4))))
4699 (forward-line -1))
4700 (when result
4701 ;; Advance if there is a next line that is either blank or indented.
4702 ;; (Need to check if we're on the last line, because
4703 ;; markdown-next-line-blank-p returns true for last line in buffer.)
4704 (while (and (/= (line-end-position) (point-max))
4705 (or (markdown-next-line-blank-p)
4706 (>= (markdown-next-line-indent) 4)))
4707 (forward-line))
4708 ;; Move back while the current line is blank.
4709 (while (markdown-cur-line-blank-p)
4710 (forward-line -1))
4711 ;; Advance to capture this line and a single trailing newline (if there
4712 ;; is one).
4713 (forward-line)
4714 (append result (list (point)))))))
4717 ;;; Element Removal ===========================================================
4719 (defun markdown-kill-thing-at-point ()
4720 "Kill thing at point and add important text, without markup, to kill ring.
4721 Possible things to kill include (roughly in order of precedence):
4722 inline code, headers, horizonal rules, links (add link text to
4723 kill ring), images (add alt text to kill ring), angle uri, email
4724 addresses, bold, italics, reference definition (add URI to kill
4725 ring), footnote markers and text (kill both marker and text, add
4726 text to kill ring), and list items."
4727 (interactive "*")
4728 (let (val)
4729 (cond
4730 ;; Inline code
4731 ((markdown-inline-code-at-point)
4732 (kill-new (match-string 2))
4733 (delete-region (match-beginning 0) (match-end 0)))
4734 ;; ATX header
4735 ((thing-at-point-looking-at markdown-regex-header-atx)
4736 (kill-new (match-string 2))
4737 (delete-region (match-beginning 0) (match-end 0)))
4738 ;; Setext header
4739 ((thing-at-point-looking-at markdown-regex-header-setext)
4740 (kill-new (match-string 1))
4741 (delete-region (match-beginning 0) (match-end 0)))
4742 ;; Horizonal rule
4743 ((thing-at-point-looking-at markdown-regex-hr)
4744 (kill-new (match-string 0))
4745 (delete-region (match-beginning 0) (match-end 0)))
4746 ;; Inline link or image (add link or alt text to kill ring)
4747 ((thing-at-point-looking-at markdown-regex-link-inline)
4748 (kill-new (match-string 3))
4749 (delete-region (match-beginning 0) (match-end 0)))
4750 ;; Reference link or image (add link or alt text to kill ring)
4751 ((thing-at-point-looking-at markdown-regex-link-reference)
4752 (kill-new (match-string 3))
4753 (delete-region (match-beginning 0) (match-end 0)))
4754 ;; Angle URI (add URL to kill ring)
4755 ((thing-at-point-looking-at markdown-regex-angle-uri)
4756 (kill-new (match-string 2))
4757 (delete-region (match-beginning 0) (match-end 0)))
4758 ;; Email address in angle brackets (add email address to kill ring)
4759 ((thing-at-point-looking-at markdown-regex-email)
4760 (kill-new (match-string 1))
4761 (delete-region (match-beginning 0) (match-end 0)))
4762 ;; Wiki link (add alias text to kill ring)
4763 ((and markdown-enable-wiki-links
4764 (thing-at-point-looking-at markdown-regex-wiki-link))
4765 (kill-new (markdown-wiki-link-alias))
4766 (delete-region (match-beginning 1) (match-end 1)))
4767 ;; Bold
4768 ((thing-at-point-looking-at markdown-regex-bold)
4769 (kill-new (match-string 4))
4770 (delete-region (match-beginning 2) (match-end 2)))
4771 ;; Italics
4772 ((thing-at-point-looking-at markdown-regex-italic)
4773 (kill-new (match-string 3))
4774 (delete-region (match-beginning 1) (match-end 1)))
4775 ;; Strikethrough
4776 ((thing-at-point-looking-at markdown-regex-strike-through)
4777 (kill-new (match-string 4))
4778 (delete-region (match-beginning 2) (match-end 2)))
4779 ;; Footnote marker (add footnote text to kill ring)
4780 ((thing-at-point-looking-at markdown-regex-footnote)
4781 (markdown-footnote-kill))
4782 ;; Footnote text (add footnote text to kill ring)
4783 ((setq val (markdown-footnote-text-positions))
4784 (markdown-footnote-kill))
4785 ;; Reference definition (add URL to kill ring)
4786 ((thing-at-point-looking-at markdown-regex-reference-definition)
4787 (kill-new (match-string 5))
4788 (delete-region (match-beginning 0) (match-end 0)))
4789 ;; List item
4790 ((setq val (markdown-cur-list-item-bounds))
4791 (kill-new (delete-and-extract-region (cl-first val) (cl-second val))))
4793 (user-error "Nothing found at point to kill")))))
4796 ;;; Indentation ====================================================================
4798 (defun markdown-indent-find-next-position (cur-pos positions)
4799 "Return the position after the index of CUR-POS in POSITIONS.
4800 Positions are calculated by `markdown-calc-indents'."
4801 (while (and positions
4802 (not (equal cur-pos (car positions))))
4803 (setq positions (cdr positions)))
4804 (or (cadr positions) 0))
4806 (define-obsolete-function-alias 'markdown-exdent-find-next-position
4807 'markdown-outdent-find-next-position "v2.3")
4809 (defun markdown-outdent-find-next-position (cur-pos positions)
4810 "Return the maximal element that precedes CUR-POS from POSITIONS.
4811 Positions are calculated by `markdown-calc-indents'."
4812 (let ((result 0))
4813 (dolist (i positions)
4814 (when (< i cur-pos)
4815 (setq result (max result i))))
4816 result))
4818 (defun markdown-indent-line ()
4819 "Indent the current line using some heuristics.
4820 If the _previous_ command was either `markdown-enter-key' or
4821 `markdown-cycle', then we should cycle to the next
4822 reasonable indentation position. Otherwise, we could have been
4823 called directly by `markdown-enter-key', by an initial call of
4824 `markdown-cycle', or indirectly by `auto-fill-mode'. In
4825 these cases, indent to the default position.
4826 Positions are calculated by `markdown-calc-indents'."
4827 (interactive)
4828 (let ((positions (markdown-calc-indents))
4829 (point-pos (current-column))
4830 (_ (back-to-indentation))
4831 (cur-pos (current-column)))
4832 (if (not (equal this-command 'markdown-cycle))
4833 (indent-line-to (car positions))
4834 (setq positions (sort (delete-dups positions) '<))
4835 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions))
4836 (new-point-pos (max (+ point-pos (- next-pos cur-pos)) 0)))
4837 (indent-line-to next-pos)
4838 (move-to-column new-point-pos)))))
4840 (defun markdown-calc-indents ()
4841 "Return a list of indentation columns to cycle through.
4842 The first element in the returned list should be considered the
4843 default indentation level. This function does not worry about
4844 duplicate positions, which are handled up by calling functions."
4845 (let (pos prev-line-pos positions)
4847 ;; Indentation of previous line
4848 (setq prev-line-pos (markdown-prev-line-indent))
4849 (setq positions (cons prev-line-pos positions))
4851 ;; Indentation of previous non-list-marker text
4852 (when (setq pos (save-excursion
4853 (forward-line -1)
4854 (when (looking-at markdown-regex-list)
4855 (- (match-end 3) (match-beginning 0)))))
4856 (setq positions (cons pos positions)))
4858 ;; Indentation required for a pre block in current context
4859 (setq pos (length (markdown-pre-indentation (point))))
4860 (setq positions (cons pos positions))
4862 ;; Indentation of the previous line + tab-width
4863 (if prev-line-pos
4864 (setq positions (cons (+ prev-line-pos tab-width) positions))
4865 (setq positions (cons tab-width positions)))
4867 ;; Indentation of the previous line - tab-width
4868 (if (and prev-line-pos (> prev-line-pos tab-width))
4869 (setq positions (cons (- prev-line-pos tab-width) positions)))
4871 ;; Indentation of all preceeding list markers (when in a list)
4872 (when (setq pos (markdown-calculate-list-levels))
4873 (setq positions (append pos positions)))
4875 ;; First column
4876 (setq positions (cons 0 positions))
4878 ;; Return reversed list
4879 (reverse positions)))
4881 (defun markdown-enter-key ()
4882 "Handle RET depending on the context.
4883 If the point is at a table, move to the next row. Otherwise,
4884 indent according to value of `markdown-indent-on-enter'.
4885 When it is nil, simply call `newline'. Otherwise, indent the next line
4886 following RET using `markdown-indent-line'. Furthermore, when it
4887 is set to 'indent-and-new-item and the point is in a list item,
4888 start a new item with the same indentation. If the point is in an
4889 empty list item, remove it (so that pressing RET twice when in a
4890 list simply adds a blank line)."
4891 (interactive)
4892 (cond
4893 ;; Table
4894 ((markdown-table-at-point-p)
4895 (call-interactively #'markdown-table-next-row))
4896 ;; Indent non-table text
4897 (markdown-indent-on-enter
4898 (let (bounds)
4899 (if (and (memq markdown-indent-on-enter '(indent-and-new-item))
4900 (setq bounds (markdown-cur-list-item-bounds)))
4901 (let ((beg (cl-first bounds))
4902 (end (cl-second bounds))
4903 (length (cl-fourth bounds)))
4904 ;; Point is in a list item
4905 (if (= (- end beg) length)
4906 ;; Delete blank list
4907 (progn
4908 (delete-region beg end)
4909 (newline)
4910 (markdown-indent-line))
4911 (call-interactively #'markdown-insert-list-item)))
4912 ;; Point is not in a list
4913 (newline)
4914 (markdown-indent-line))))
4915 ;; Insert a raw newline
4916 (t (newline))))
4918 (define-obsolete-function-alias 'markdown-exdent-or-delete
4919 'markdown-outdent-or-delete "v2.3")
4921 (defun markdown-outdent-or-delete (arg)
4922 "Handle BACKSPACE by cycling through indentation points.
4923 When BACKSPACE is pressed, if there is only whitespace
4924 before the current point, then outdent the line one level.
4925 Otherwise, do normal delete by repeating
4926 `backward-delete-char-untabify' ARG times."
4927 (interactive "*p")
4928 (if (use-region-p)
4929 (backward-delete-char-untabify arg)
4930 (let ((cur-pos (current-column))
4931 (start-of-indention (save-excursion
4932 (back-to-indentation)
4933 (current-column)))
4934 (positions (markdown-calc-indents)))
4935 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
4936 (indent-line-to (markdown-outdent-find-next-position cur-pos positions))
4937 (backward-delete-char-untabify arg)))))
4939 (defun markdown-find-leftmost-column (beg end)
4940 "Find the leftmost column in the region from BEG to END."
4941 (let ((mincol 1000))
4942 (save-excursion
4943 (goto-char beg)
4944 (while (< (point) end)
4945 (back-to-indentation)
4946 (unless (looking-at-p "[ \t]*$")
4947 (setq mincol (min mincol (current-column))))
4948 (forward-line 1)
4950 mincol))
4952 (defun markdown-indent-region (beg end arg)
4953 "Indent the region from BEG to END using some heuristics.
4954 When ARG is non-nil, outdent the region instead.
4955 See `markdown-indent-line' and `markdown-indent-line'."
4956 (interactive "*r\nP")
4957 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
4958 (leftmostcol (markdown-find-leftmost-column beg end))
4959 (next-pos (if arg
4960 (markdown-outdent-find-next-position leftmostcol positions)
4961 (markdown-indent-find-next-position leftmostcol positions))))
4962 (indent-rigidly beg end (- next-pos leftmostcol))
4963 (setq deactivate-mark nil)))
4965 (define-obsolete-function-alias 'markdown-exdent-region
4966 'markdown-outdent-region "v2.3")
4968 (defun markdown-outdent-region (beg end)
4969 "Call `markdown-indent-region' on region from BEG to END with prefix."
4970 (interactive "*r")
4971 (markdown-indent-region beg end t))
4974 ;;; Markup Completion =========================================================
4976 (defconst markdown-complete-alist
4977 '((markdown-regex-header-atx . markdown-complete-atx)
4978 (markdown-regex-header-setext . markdown-complete-setext)
4979 (markdown-regex-hr . markdown-complete-hr))
4980 "Association list of form (regexp . function) for markup completion.")
4982 (defun markdown-incomplete-atx-p ()
4983 "Return t if ATX header markup is incomplete and nil otherwise.
4984 Assumes match data is available for `markdown-regex-header-atx'.
4985 Checks that the number of trailing hash marks equals the number of leading
4986 hash marks, that there is only a single space before and after the text,
4987 and that there is no extraneous whitespace in the text."
4989 ;; Number of starting and ending hash marks differs
4990 (not (= (length (match-string 1)) (length (match-string 3))))
4991 ;; When the header text is not empty...
4992 (and (> (length (match-string 2)) 0)
4993 ;; ...if there are extra leading, trailing, or interior spaces
4994 (or (not (= (match-beginning 2) (1+ (match-end 1))))
4995 (not (= (match-beginning 3) (1+ (match-end 2))))
4996 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
4997 ;; When the header text is empty...
4998 (and (= (length (match-string 2)) 0)
4999 ;; ...if there are too many or too few spaces
5000 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
5002 (defun markdown-complete-atx ()
5003 "Complete and normalize ATX headers.
5004 Add or remove hash marks to the end of the header to match the
5005 beginning. Ensure that there is only a single space between hash
5006 marks and header text. Removes extraneous whitespace from header text.
5007 Assumes match data is available for `markdown-regex-header-atx'.
5008 Return nil if markup was complete and non-nil if markup was completed."
5009 (when (markdown-incomplete-atx-p)
5010 (let* ((new-marker (make-marker))
5011 (new-marker (set-marker new-marker (match-end 2))))
5012 ;; Hash marks and spacing at end
5013 (goto-char (match-end 2))
5014 (delete-region (match-end 2) (match-end 3))
5015 (insert " " (match-string 1))
5016 ;; Remove extraneous whitespace from title
5017 (replace-match (markdown-compress-whitespace-string (match-string 2))
5018 t t nil 2)
5019 ;; Spacing at beginning
5020 (goto-char (match-end 1))
5021 (delete-region (match-end 1) (match-beginning 2))
5022 (insert " ")
5023 ;; Leave point at end of text
5024 (goto-char new-marker))))
5026 (defun markdown-incomplete-setext-p ()
5027 "Return t if setext header markup is incomplete and nil otherwise.
5028 Assumes match data is available for `markdown-regex-header-setext'.
5029 Checks that length of underline matches text and that there is no
5030 extraneous whitespace in the text."
5031 (or (not (= (length (match-string 1)) (length (match-string 2))))
5032 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
5034 (defun markdown-complete-setext ()
5035 "Complete and normalize setext headers.
5036 Add or remove underline characters to match length of header
5037 text. Removes extraneous whitespace from header text. Assumes
5038 match data is available for `markdown-regex-header-setext'.
5039 Return nil if markup was complete and non-nil if markup was completed."
5040 (when (markdown-incomplete-setext-p)
5041 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
5042 (char (char-after (match-beginning 2)))
5043 (level (if (char-equal char ?-) 2 1)))
5044 (goto-char (match-beginning 0))
5045 (delete-region (match-beginning 0) (match-end 0))
5046 (markdown-insert-header level text t)
5047 t)))
5049 (defun markdown-incomplete-hr-p ()
5050 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
5051 Assumes match data is available for `markdown-regex-hr'."
5052 (not (member (match-string 0) markdown-hr-strings)))
5054 (defun markdown-complete-hr ()
5055 "Complete horizontal rules.
5056 If horizontal rule string is a member of `markdown-hr-strings',
5057 do nothing. Otherwise, replace with the car of
5058 `markdown-hr-strings'.
5059 Assumes match data is available for `markdown-regex-hr'.
5060 Return nil if markup was complete and non-nil if markup was completed."
5061 (when (markdown-incomplete-hr-p)
5062 (replace-match (car markdown-hr-strings))
5065 (defun markdown-complete ()
5066 "Complete markup of object near point or in region when active.
5067 Handle all objects in `markdown-complete-alist', in order.
5068 See `markdown-complete-at-point' and `markdown-complete-region'."
5069 (interactive "*")
5070 (if (markdown-use-region-p)
5071 (markdown-complete-region (region-beginning) (region-end))
5072 (markdown-complete-at-point)))
5074 (defun markdown-complete-at-point ()
5075 "Complete markup of object near point.
5076 Handle all elements of `markdown-complete-alist' in order."
5077 (interactive "*")
5078 (let ((list markdown-complete-alist) found changed)
5079 (while list
5080 (let ((regexp (eval (caar list)))
5081 (function (cdar list)))
5082 (setq list (cdr list))
5083 (when (thing-at-point-looking-at regexp)
5084 (setq found t)
5085 (setq changed (funcall function))
5086 (setq list nil))))
5087 (if found
5088 (or changed (user-error "Markup at point is complete"))
5089 (user-error "Nothing to complete at point"))))
5091 (defun markdown-complete-region (beg end)
5092 "Complete markup of objects in region from BEG to END.
5093 Handle all objects in `markdown-complete-alist', in order. Each
5094 match is checked to ensure that a previous regexp does not also
5095 match."
5096 (interactive "*r")
5097 (let ((end-marker (set-marker (make-marker) end))
5098 previous)
5099 (dolist (element markdown-complete-alist)
5100 (let ((regexp (eval (car element)))
5101 (function (cdr element)))
5102 (goto-char beg)
5103 (while (re-search-forward regexp end-marker 'limit)
5104 (when (match-string 0)
5105 ;; Make sure this is not a match for any of the preceding regexps.
5106 ;; This prevents mistaking an HR for a Setext subheading.
5107 (let (match)
5108 (save-match-data
5109 (dolist (prev-regexp previous)
5110 (or match (setq match (looking-back prev-regexp nil)))))
5111 (unless match
5112 (save-excursion (funcall function))))))
5113 (cl-pushnew regexp previous :test #'equal)))
5114 previous))
5116 (defun markdown-complete-buffer ()
5117 "Complete markup for all objects in the current buffer."
5118 (interactive "*")
5119 (markdown-complete-region (point-min) (point-max)))
5122 ;;; Markup Cycling ============================================================
5124 (defun markdown-cycle-atx (arg &optional remove)
5125 "Cycle ATX header markup.
5126 Promote header (decrease level) when ARG is 1 and demote
5127 header (increase level) if arg is -1. When REMOVE is non-nil,
5128 remove the header when the level reaches zero and stop cycling
5129 when it reaches six. Otherwise, perform a proper cycling through
5130 levels one through six. Assumes match data is available for
5131 `markdown-regex-header-atx'."
5132 (let* ((old-level (length (match-string 1)))
5133 (new-level (+ old-level arg))
5134 (text (match-string 2)))
5135 (when (not remove)
5136 (setq new-level (% new-level 6))
5137 (setq new-level (cond ((= new-level 0) 6)
5138 ((< new-level 0) (+ new-level 6))
5139 (t new-level))))
5140 (cond
5141 ((= new-level 0)
5142 (markdown-unwrap-thing-at-point nil 0 2))
5143 ((<= new-level 6)
5144 (goto-char (match-beginning 0))
5145 (delete-region (match-beginning 0) (match-end 0))
5146 (markdown-insert-header new-level text nil)))))
5148 (defun markdown-cycle-setext (arg &optional remove)
5149 "Cycle setext header markup.
5150 Promote header (increase level) when ARG is 1 and demote
5151 header (decrease level or remove) if arg is -1. When demoting a
5152 level-two setext header, replace with a level-three atx header.
5153 When REMOVE is non-nil, remove the header when the level reaches
5154 zero. Otherwise, cycle back to a level six atx header. Assumes
5155 match data is available for `markdown-regex-header-setext'."
5156 (let* ((char (char-after (match-beginning 2)))
5157 (old-level (if (char-equal char ?=) 1 2))
5158 (new-level (+ old-level arg)))
5159 (when (and (not remove) (= new-level 0))
5160 (setq new-level 6))
5161 (cond
5162 ((= new-level 0)
5163 (markdown-unwrap-thing-at-point nil 0 1))
5164 ((<= new-level 2)
5165 (markdown-insert-header new-level nil t))
5166 ((<= new-level 6)
5167 (markdown-insert-header new-level nil nil)))))
5169 (defun markdown-cycle-hr (arg &optional remove)
5170 "Cycle string used for horizontal rule from `markdown-hr-strings'.
5171 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
5172 backwards (promote). When REMOVE is non-nil, remove the hr instead
5173 of cycling when the end of the list is reached.
5174 Assumes match data is available for `markdown-regex-hr'."
5175 (let* ((strings (if (= arg -1)
5176 (reverse markdown-hr-strings)
5177 markdown-hr-strings))
5178 (tail (member (match-string 0) strings))
5179 (new (or (cadr tail)
5180 (if remove
5181 (if (= arg 1)
5183 (car tail))
5184 (car strings)))))
5185 (replace-match new)))
5187 (defun markdown-cycle-bold ()
5188 "Cycle bold markup between underscores and asterisks.
5189 Assumes match data is available for `markdown-regex-bold'."
5190 (save-excursion
5191 (let* ((old-delim (match-string 3))
5192 (new-delim (if (string-equal old-delim "**") "__" "**")))
5193 (replace-match new-delim t t nil 3)
5194 (replace-match new-delim t t nil 5))))
5196 (defun markdown-cycle-italic ()
5197 "Cycle italic markup between underscores and asterisks.
5198 Assumes match data is available for `markdown-regex-italic'."
5199 (save-excursion
5200 (let* ((old-delim (match-string 2))
5201 (new-delim (if (string-equal old-delim "*") "_" "*")))
5202 (replace-match new-delim t t nil 2)
5203 (replace-match new-delim t t nil 4))))
5206 ;;; Keymap ====================================================================
5208 (defun markdown--style-map-prompt ()
5209 "Return a formatted prompt for Markdown markup insertion."
5210 (when markdown-enable-prefix-prompts
5211 (concat
5212 "Markdown: "
5213 (propertize "bold" 'face 'markdown-bold-face) ", "
5214 (propertize "italic" 'face 'markdown-italic-face) ", "
5215 (propertize "code" 'face 'markdown-inline-code-face) ", "
5216 (propertize "C = GFM code" 'face 'markdown-code-face) ", "
5217 (propertize "pre" 'face 'markdown-pre-face) ", "
5218 (propertize "footnote" 'face 'markdown-footnote-text-face) ", "
5219 (propertize "q = blockquote" 'face 'markdown-blockquote-face) ", "
5220 (propertize "h & 1-6 = heading" 'face 'markdown-header-face) ", "
5221 (propertize "- = hr" 'face 'markdown-hr-face) ", "
5222 "C-h = more")))
5224 (defun markdown--command-map-prompt ()
5225 "Return prompt for Markdown buffer-wide commands."
5226 (when markdown-enable-prefix-prompts
5227 (concat
5228 "Command: "
5229 (propertize "m" 'face 'markdown-bold-face) "arkdown, "
5230 (propertize "p" 'face 'markdown-bold-face) "review, "
5231 (propertize "o" 'face 'markdown-bold-face) "pen, "
5232 (propertize "e" 'face 'markdown-bold-face) "xport, "
5233 "export & pre" (propertize "v" 'face 'markdown-bold-face) "iew, "
5234 (propertize "c" 'face 'markdown-bold-face) "heck refs, "
5235 "C-h = more")))
5237 (defvar markdown-mode-style-map
5238 (let ((map (make-keymap (markdown--style-map-prompt))))
5239 (define-key map (kbd "1") 'markdown-insert-header-atx-1)
5240 (define-key map (kbd "2") 'markdown-insert-header-atx-2)
5241 (define-key map (kbd "3") 'markdown-insert-header-atx-3)
5242 (define-key map (kbd "4") 'markdown-insert-header-atx-4)
5243 (define-key map (kbd "5") 'markdown-insert-header-atx-5)
5244 (define-key map (kbd "6") 'markdown-insert-header-atx-6)
5245 (define-key map (kbd "!") 'markdown-insert-header-setext-1)
5246 (define-key map (kbd "@") 'markdown-insert-header-setext-2)
5247 (define-key map (kbd "b") 'markdown-insert-bold)
5248 (define-key map (kbd "c") 'markdown-insert-code)
5249 (define-key map (kbd "C") 'markdown-insert-gfm-code-block)
5250 (define-key map (kbd "f") 'markdown-insert-footnote)
5251 (define-key map (kbd "h") 'markdown-insert-header-dwim)
5252 (define-key map (kbd "H") 'markdown-insert-header-setext-dwim)
5253 (define-key map (kbd "i") 'markdown-insert-italic)
5254 (define-key map (kbd "k") 'markdown-insert-kbd)
5255 (define-key map (kbd "l") 'markdown-insert-link)
5256 (define-key map (kbd "p") 'markdown-insert-pre)
5257 (define-key map (kbd "P") 'markdown-pre-region)
5258 (define-key map (kbd "q") 'markdown-insert-blockquote)
5259 (define-key map (kbd "s") 'markdown-insert-strike-through)
5260 (define-key map (kbd "Q") 'markdown-blockquote-region)
5261 (define-key map (kbd "w") 'markdown-insert-wiki-link)
5262 (define-key map (kbd "-") 'markdown-insert-hr)
5263 (define-key map (kbd "[") 'markdown-insert-gfm-checkbox)
5264 ;; Deprecated keys that may be removed in a future version
5265 (define-key map (kbd "e") 'markdown-insert-italic)
5266 map)
5267 "Keymap for Markdown text styling commands.")
5269 (defvar markdown-mode-command-map
5270 (let ((map (make-keymap (markdown--command-map-prompt))))
5271 (define-key map (kbd "m") 'markdown-other-window)
5272 (define-key map (kbd "p") 'markdown-preview)
5273 (define-key map (kbd "e") 'markdown-export)
5274 (define-key map (kbd "v") 'markdown-export-and-preview)
5275 (define-key map (kbd "o") 'markdown-open)
5276 (define-key map (kbd "l") 'markdown-live-preview-mode)
5277 (define-key map (kbd "w") 'markdown-kill-ring-save)
5278 (define-key map (kbd "c") 'markdown-check-refs)
5279 (define-key map (kbd "n") 'markdown-cleanup-list-numbers)
5280 (define-key map (kbd "]") 'markdown-complete-buffer)
5281 (define-key map (kbd "^") 'markdown-table-sort-lines)
5282 (define-key map (kbd "|") 'markdown-table-convert-region)
5283 (define-key map (kbd "t") 'markdown-table-transpose)
5284 map)
5285 "Keymap for Markdown buffer-wide commands.")
5287 (defvar markdown-mode-map
5288 (let ((map (make-keymap)))
5289 ;; Markup insertion & removal
5290 (define-key map (kbd "C-c C-s") markdown-mode-style-map)
5291 (define-key map (kbd "C-c C-l") 'markdown-insert-link)
5292 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
5293 ;; Promotion, demotion, and cycling
5294 (define-key map (kbd "C-c C--") 'markdown-promote)
5295 (define-key map (kbd "C-c C-=") 'markdown-demote)
5296 (define-key map (kbd "C-c C-]") 'markdown-complete)
5297 ;; Following and doing things
5298 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
5299 (define-key map (kbd "C-c C-d") 'markdown-do)
5300 (define-key map (kbd "C-c '") 'markdown-edit-code-block)
5301 ;; Indentation
5302 (define-key map (kbd "C-m") 'markdown-enter-key)
5303 (define-key map (kbd "DEL") 'markdown-outdent-or-delete)
5304 (define-key map (kbd "C-c >") 'markdown-indent-region)
5305 (define-key map (kbd "C-c <") 'markdown-outdent-region)
5306 ;; Visibility cycling
5307 (define-key map (kbd "TAB") 'markdown-cycle)
5308 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
5309 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
5310 (define-key map (kbd "<backtab>") 'markdown-shifttab)
5311 ;; Heading and list navigation
5312 (define-key map (kbd "C-c C-n") 'markdown-outline-next)
5313 (define-key map (kbd "C-c C-p") 'markdown-outline-previous)
5314 (define-key map (kbd "C-c C-f") 'markdown-outline-next-same-level)
5315 (define-key map (kbd "C-c C-b") 'markdown-outline-previous-same-level)
5316 (define-key map (kbd "C-c C-u") 'markdown-outline-up)
5317 ;; Buffer-wide commands
5318 (define-key map (kbd "C-c C-c") markdown-mode-command-map)
5319 ;; Subtree, list, and table editing
5320 (define-key map (kbd "C-c <up>") 'markdown-move-up)
5321 (define-key map (kbd "C-c <down>") 'markdown-move-down)
5322 (define-key map (kbd "C-c <left>") 'markdown-promote)
5323 (define-key map (kbd "C-c <right>") 'markdown-demote)
5324 (define-key map (kbd "C-c S-<up>") 'markdown-table-delete-row)
5325 (define-key map (kbd "C-c S-<down>") 'markdown-table-insert-row)
5326 (define-key map (kbd "C-c S-<left>") 'markdown-table-delete-column)
5327 (define-key map (kbd "C-c S-<right>") 'markdown-table-insert-column)
5328 (define-key map (kbd "C-c C-M-h") 'markdown-mark-subtree)
5329 (define-key map (kbd "C-x n s") 'markdown-narrow-to-subtree)
5330 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
5331 (define-key map (kbd "C-c C-j") 'markdown-insert-list-item)
5332 ;; Paragraphs (Markdown context aware)
5333 (define-key map [remap backward-paragraph] 'markdown-backward-paragraph)
5334 (define-key map [remap forward-paragraph] 'markdown-forward-paragraph)
5335 (define-key map [remap mark-paragraph] 'markdown-mark-paragraph)
5336 ;; Blocks (one or more paragraphs)
5337 (define-key map (kbd "C-M-{") 'markdown-backward-block)
5338 (define-key map (kbd "C-M-}") 'markdown-forward-block)
5339 (define-key map (kbd "C-c M-h") 'markdown-mark-block)
5340 (define-key map (kbd "C-x n b") 'markdown-narrow-to-block)
5341 ;; Pages (top-level sections)
5342 (define-key map [remap backward-page] 'markdown-backward-page)
5343 (define-key map [remap forward-page] 'markdown-forward-page)
5344 (define-key map [remap mark-page] 'markdown-mark-page)
5345 (define-key map [remap narrow-to-page] 'markdown-narrow-to-page)
5346 ;; Link Movement
5347 (define-key map (kbd "M-n") 'markdown-next-link)
5348 (define-key map (kbd "M-p") 'markdown-previous-link)
5349 ;; Toggling functionality
5350 (define-key map (kbd "C-c C-x C-e") 'markdown-toggle-math)
5351 (define-key map (kbd "C-c C-x C-f") 'markdown-toggle-fontify-code-blocks-natively)
5352 (define-key map (kbd "C-c C-x C-i") 'markdown-toggle-inline-images)
5353 (define-key map (kbd "C-c C-x C-l") 'markdown-toggle-url-hiding)
5354 (define-key map (kbd "C-c C-x C-m") 'markdown-toggle-markup-hiding)
5355 ;; Alternative keys (in case of problems with the arrow keys)
5356 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
5357 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
5358 (define-key map (kbd "C-c C-x l") 'markdown-promote)
5359 (define-key map (kbd "C-c C-x r") 'markdown-demote)
5360 ;; Deprecated keys that may be removed in a future version
5361 (define-key map (kbd "C-c C-a L") 'markdown-insert-link) ;; C-c C-l
5362 (define-key map (kbd "C-c C-a l") 'markdown-insert-link) ;; C-c C-l
5363 (define-key map (kbd "C-c C-a r") 'markdown-insert-link) ;; C-c C-l
5364 (define-key map (kbd "C-c C-a u") 'markdown-insert-uri) ;; C-c C-l
5365 (define-key map (kbd "C-c C-a f") 'markdown-insert-footnote)
5366 (define-key map (kbd "C-c C-a w") 'markdown-insert-wiki-link)
5367 (define-key map (kbd "C-c C-t 1") 'markdown-insert-header-atx-1)
5368 (define-key map (kbd "C-c C-t 2") 'markdown-insert-header-atx-2)
5369 (define-key map (kbd "C-c C-t 3") 'markdown-insert-header-atx-3)
5370 (define-key map (kbd "C-c C-t 4") 'markdown-insert-header-atx-4)
5371 (define-key map (kbd "C-c C-t 5") 'markdown-insert-header-atx-5)
5372 (define-key map (kbd "C-c C-t 6") 'markdown-insert-header-atx-6)
5373 (define-key map (kbd "C-c C-t !") 'markdown-insert-header-setext-1)
5374 (define-key map (kbd "C-c C-t @") 'markdown-insert-header-setext-2)
5375 (define-key map (kbd "C-c C-t h") 'markdown-insert-header-dwim)
5376 (define-key map (kbd "C-c C-t H") 'markdown-insert-header-setext-dwim)
5377 (define-key map (kbd "C-c C-t s") 'markdown-insert-header-setext-2)
5378 (define-key map (kbd "C-c C-t t") 'markdown-insert-header-setext-1)
5379 (define-key map (kbd "C-c C-i") 'markdown-insert-image)
5380 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item) ;; C-c C-j
5381 (define-key map (kbd "C-c C-x C-x") 'markdown-toggle-gfm-checkbox) ;; C-c C-d
5382 (define-key map (kbd "C-c -") 'markdown-insert-hr)
5383 map)
5384 "Keymap for Markdown major mode.")
5386 (defvar markdown-mode-mouse-map
5387 (let ((map (make-sparse-keymap)))
5388 (define-key map [follow-link] 'mouse-face)
5389 (define-key map [mouse-2] 'markdown-follow-link-at-point)
5390 map)
5391 "Keymap for following links with mouse.")
5393 (defvar gfm-mode-map
5394 (let ((map (make-sparse-keymap)))
5395 (set-keymap-parent map markdown-mode-map)
5396 (define-key map (kbd "C-c C-s d") 'markdown-insert-strike-through)
5397 (define-key map "`" 'markdown-electric-backquote)
5398 map)
5399 "Keymap for `gfm-mode'.
5400 See also `markdown-mode-map'.")
5403 ;;; Menu ==================================================================
5405 (easy-menu-define markdown-mode-menu markdown-mode-map
5406 "Menu for Markdown mode"
5407 '("Markdown"
5408 "---"
5409 ("Movement"
5410 ["Jump" markdown-do]
5411 ["Follow Link" markdown-follow-thing-at-point]
5412 ["Next Link" markdown-next-link]
5413 ["Previous Link" markdown-previous-link]
5414 "---"
5415 ["Next Heading or List Item" markdown-outline-next]
5416 ["Previous Heading or List Item" markdown-outline-previous]
5417 ["Next at Same Level" markdown-outline-next-same-level]
5418 ["Previous at Same Level" markdown-outline-previous-same-level]
5419 ["Up to Parent" markdown-outline-up]
5420 "---"
5421 ["Forward Paragraph" markdown-forward-paragraph]
5422 ["Backward Paragraph" markdown-backward-paragraph]
5423 ["Forward Block" markdown-forward-block]
5424 ["Backward Block" markdown-backward-block])
5425 ("Show & Hide"
5426 ["Cycle Heading Visibility" markdown-cycle (markdown-on-heading-p)]
5427 ["Cycle Heading Visibility (Global)" markdown-shifttab]
5428 "---"
5429 ["Narrow to Region" narrow-to-region]
5430 ["Narrow to Block" markdown-narrow-to-block]
5431 ["Narrow to Section" narrow-to-defun]
5432 ["Narrow to Subtree" markdown-narrow-to-subtree]
5433 ["Widen" widen (buffer-narrowed-p)]
5434 "---"
5435 ["Toggle Markup Hiding" markdown-toggle-markup-hiding
5436 :keys "C-c C-x C-m"
5437 :style radio
5438 :selected markdown-hide-markup])
5439 "---"
5440 ("Headings & Structure"
5441 ["Automatic Heading" markdown-insert-header-dwim :keys "C-c C-s h"]
5442 ["Automatic Heading (Setext)" markdown-insert-header-setext-dwim :keys "C-c C-s H"]
5443 ("Specific Heading (atx)"
5444 ["First Level atx" markdown-insert-header-atx-1 :keys "C-c C-s 1"]
5445 ["Second Level atx" markdown-insert-header-atx-2 :keys "C-c C-s 2"]
5446 ["Third Level atx" markdown-insert-header-atx-3 :keys "C-c C-s 3"]
5447 ["Fourth Level atx" markdown-insert-header-atx-4 :keys "C-c C-s 4"]
5448 ["Fifth Level atx" markdown-insert-header-atx-5 :keys "C-c C-s 5"]
5449 ["Sixth Level atx" markdown-insert-header-atx-6 :keys "C-c C-s 6"])
5450 ("Specific Heading (Setext)"
5451 ["First Level Setext" markdown-insert-header-setext-1 :keys "C-c C-s !"]
5452 ["Second Level Setext" markdown-insert-header-setext-2 :keys "C-c C-s @"])
5453 ["Horizontal Rule" markdown-insert-hr :keys "C-c C-s -"]
5454 "---"
5455 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
5456 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
5457 ["Promote Subtree" markdown-promote :keys "C-c <left>"]
5458 ["Demote Subtree" markdown-demote :keys "C-c <right>"])
5459 ("Region & Mark"
5460 ["Indent Region" markdown-indent-region]
5461 ["Outdent Region" markdown-outdent-region]
5462 "--"
5463 ["Mark Paragraph" mark-paragraph]
5464 ["Mark Block" markdown-mark-block]
5465 ["Mark Section" mark-defun]
5466 ["Mark Subtree" markdown-mark-subtree])
5467 ("Lists"
5468 ["Insert List Item" markdown-insert-list-item]
5469 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
5470 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
5471 ["Indent Subtree" markdown-demote :keys "C-c <right>"]
5472 ["Outdent Subtree" markdown-promote :keys "C-c <left>"]
5473 ["Renumber List" markdown-cleanup-list-numbers]
5474 ["Insert Task List Item" markdown-insert-gfm-checkbox :keys "C-c C-x ["]
5475 ["Toggle Task List Item" markdown-toggle-gfm-checkbox (markdown-gfm-task-list-item-at-point) :keys "C-c C-d"])
5476 ("Links & Images"
5477 ["Insert Link" markdown-insert-link]
5478 ["Insert Image" markdown-insert-image]
5479 ["Insert Footnote" markdown-insert-footnote :keys "C-c C-s f"]
5480 ["Insert Wiki Link" markdown-insert-wiki-link :keys "C-c C-s w"]
5481 "---"
5482 ["Check References" markdown-check-refs]
5483 ["Toggle URL Hiding" markdown-toggle-url-hiding
5484 :style radio
5485 :selected markdown-hide-urls]
5486 ["Toggle Inline Images" markdown-toggle-inline-images
5487 :keys "C-c C-x C-i"
5488 :style radio
5489 :selected markdown-inline-image-overlays]
5490 ["Toggle Wiki Links" markdown-toggle-wiki-links
5491 :style radio
5492 :selected markdown-enable-wiki-links])
5493 ("Styles"
5494 ["Bold" markdown-insert-bold]
5495 ["Italic" markdown-insert-italic]
5496 ["Code" markdown-insert-code]
5497 ["Strikethrough" markdown-insert-strike-through]
5498 ["Keyboard" markdown-insert-kbd]
5499 "---"
5500 ["Blockquote" markdown-insert-blockquote]
5501 ["Preformatted" markdown-insert-pre]
5502 ["GFM Code Block" markdown-insert-gfm-code-block]
5503 ["Edit Code Block" markdown-edit-code-block (markdown-code-block-at-point-p)]
5504 "---"
5505 ["Blockquote Region" markdown-blockquote-region]
5506 ["Preformatted Region" markdown-pre-region]
5507 "---"
5508 ["Fontify Code Blocks Natively" markdown-toggle-fontify-code-blocks-natively
5509 :style radio
5510 :selected markdown-fontify-code-blocks-natively]
5511 ["LaTeX Math Support" markdown-toggle-math
5512 :style radio
5513 :selected markdown-enable-math])
5514 "---"
5515 ("Preview & Export"
5516 ["Compile" markdown-other-window]
5517 ["Preview" markdown-preview]
5518 ["Export" markdown-export]
5519 ["Export & View" markdown-export-and-preview]
5520 ["Open" markdown-open]
5521 ["Live Export" markdown-live-preview-mode
5522 :style radio
5523 :selected markdown-live-preview-mode]
5524 ["Kill ring save" markdown-kill-ring-save])
5525 ("Markup Completion and Cycling"
5526 ["Complete Markup" markdown-complete]
5527 ["Promote Element" markdown-promote :keys "C-c C--"]
5528 ["Demote Element" markdown-demote :keys "C-c C-="])
5529 "---"
5530 ["Kill Element" markdown-kill-thing-at-point]
5531 "---"
5532 ("Documentation"
5533 ["Version" markdown-show-version]
5534 ["Homepage" markdown-mode-info]
5535 ["Describe Mode" (describe-function 'markdown-mode)]
5536 ["Guide" (browse-url "https://leanpub.com/markdown-mode")])))
5539 ;;; imenu =====================================================================
5541 (defun markdown-imenu-create-nested-index ()
5542 "Create and return a nested imenu index alist for the current buffer.
5543 See `imenu-create-index-function' and `imenu--index-alist' for details."
5544 (let* ((root '(nil . nil))
5545 cur-alist
5546 (cur-level 0)
5547 (empty-heading "-")
5548 (self-heading ".")
5549 hashes pos level heading)
5550 (save-excursion
5551 (goto-char (point-min))
5552 (while (re-search-forward markdown-regex-header (point-max) t)
5553 (unless (markdown-code-block-at-point-p)
5554 (cond
5555 ((match-string-no-properties 2) ;; level 1 setext
5556 (setq heading (match-string-no-properties 1))
5557 (setq pos (match-beginning 1)
5558 level 1))
5559 ((match-string-no-properties 3) ;; level 2 setext
5560 (setq heading (match-string-no-properties 1))
5561 (setq pos (match-beginning 1)
5562 level 2))
5563 ((setq hashes (markdown-trim-whitespace
5564 (match-string-no-properties 4)))
5565 (setq heading (match-string-no-properties 5)
5566 pos (match-beginning 4)
5567 level (length hashes))))
5568 (let ((alist (list (cons heading pos))))
5569 (cond
5570 ((= cur-level level) ; new sibling
5571 (setcdr cur-alist alist)
5572 (setq cur-alist alist))
5573 ((< cur-level level) ; first child
5574 (dotimes (_ (- level cur-level 1))
5575 (setq alist (list (cons empty-heading alist))))
5576 (if cur-alist
5577 (let* ((parent (car cur-alist))
5578 (self-pos (cdr parent)))
5579 (setcdr parent (cons (cons self-heading self-pos) alist)))
5580 (setcdr root alist)) ; primogenitor
5581 (setq cur-alist alist)
5582 (setq cur-level level))
5583 (t ; new sibling of an ancestor
5584 (let ((sibling-alist (last (cdr root))))
5585 (dotimes (_ (1- level))
5586 (setq sibling-alist (last (cdar sibling-alist))))
5587 (setcdr sibling-alist alist)
5588 (setq cur-alist alist))
5589 (setq cur-level level))))))
5590 (cdr root))))
5592 (defun markdown-imenu-create-flat-index ()
5593 "Create and return a flat imenu index alist for the current buffer.
5594 See `imenu-create-index-function' and `imenu--index-alist' for details."
5595 (let* ((empty-heading "-") index heading pos)
5596 (save-excursion
5597 (goto-char (point-min))
5598 (while (re-search-forward markdown-regex-header (point-max) t)
5599 (when (and (not (markdown-code-block-at-point-p))
5600 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin)))
5601 (cond
5602 ((setq heading (match-string-no-properties 1))
5603 (setq pos (match-beginning 1)))
5604 ((setq heading (match-string-no-properties 5))
5605 (setq pos (match-beginning 4))))
5606 (or (> (length heading) 0)
5607 (setq heading empty-heading))
5608 (setq index (append index (list (cons heading pos))))))
5609 index)))
5612 ;;; References ================================================================
5614 (defun markdown-reference-goto-definition ()
5615 "Jump to the definition of the reference at point or create it."
5616 (interactive)
5617 (when (thing-at-point-looking-at markdown-regex-link-reference)
5618 (let* ((text (match-string-no-properties 3))
5619 (reference (match-string-no-properties 6))
5620 (target (downcase (if (string= reference "") text reference)))
5621 (loc (cadr (save-match-data (markdown-reference-definition target)))))
5622 (if loc
5623 (goto-char loc)
5624 (goto-char (match-beginning 0))
5625 (markdown-insert-reference-definition target)))))
5627 (defun markdown-reference-find-links (reference)
5628 "Return a list of all links for REFERENCE.
5629 REFERENCE should not include the surrounding square brackets.
5630 Elements of the list have the form (text start line), where
5631 text is the link text, start is the location at the beginning of
5632 the link, and line is the line number on which the link appears."
5633 (let* ((ref-quote (regexp-quote reference))
5634 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
5635 ref-quote ref-quote))
5636 links)
5637 (save-excursion
5638 (goto-char (point-min))
5639 (while (re-search-forward regexp nil t)
5640 (let* ((text (or (match-string-no-properties 1)
5641 (match-string-no-properties 2)))
5642 (start (match-beginning 0))
5643 (line (markdown-line-number-at-pos)))
5644 (cl-pushnew (list text start line) links :test #'equal))))
5645 links))
5647 (defun markdown-get-undefined-refs ()
5648 "Return a list of undefined Markdown references.
5649 Result is an alist of pairs (reference . occurrences), where
5650 occurrences is itself another alist of pairs (label . line-number).
5651 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
5652 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
5653 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
5654 (let ((missing))
5655 (save-excursion
5656 (goto-char (point-min))
5657 (while
5658 (re-search-forward markdown-regex-link-reference nil t)
5659 (let* ((text (match-string-no-properties 3))
5660 (reference (match-string-no-properties 6))
5661 (target (downcase (if (string= reference "") text reference))))
5662 (unless (markdown-reference-definition target)
5663 (let ((entry (assoc target missing)))
5664 (if (not entry)
5665 (cl-pushnew
5666 (cons target (list (cons text (markdown-line-number-at-pos))))
5667 missing :test #'equal)
5668 (setcdr entry
5669 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
5670 (reverse missing))))
5672 (defconst markdown-reference-check-buffer
5673 "*Undefined references for %buffer%*"
5674 "Pattern for name of buffer for listing undefined references.
5675 The string %buffer% will be replaced by the corresponding
5676 `markdown-mode' buffer name.")
5678 (defun markdown-reference-check-buffer (&optional buffer-name)
5679 "Name and return buffer for reference checking.
5680 BUFFER-NAME is the name of the main buffer being visited."
5681 (or buffer-name (setq buffer-name (buffer-name)))
5682 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
5683 "%buffer%" buffer-name
5684 markdown-reference-check-buffer))))
5685 (with-current-buffer refbuf
5686 (when view-mode
5687 (View-exit-and-edit))
5688 (use-local-map button-buffer-map)
5689 (erase-buffer))
5690 refbuf))
5692 (defconst markdown-reference-links-buffer
5693 "*Reference links for %buffer%*"
5694 "Pattern for name of buffer for listing references.
5695 The string %buffer% will be replaced by the corresponding buffer name.")
5697 (defun markdown-reference-links-buffer (&optional buffer-name)
5698 "Name, setup, and return a buffer for listing links.
5699 BUFFER-NAME is the name of the main buffer being visited."
5700 (or buffer-name (setq buffer-name (buffer-name)))
5701 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
5702 "%buffer%" buffer-name
5703 markdown-reference-links-buffer))))
5704 (with-current-buffer linkbuf
5705 (when view-mode
5706 (View-exit-and-edit))
5707 (use-local-map button-buffer-map)
5708 (erase-buffer))
5709 linkbuf))
5711 ;; Add an empty Markdown reference definition to buffer
5712 ;; specified in the 'target-buffer property. The reference name is
5713 ;; the button's label.
5714 (define-button-type 'markdown-undefined-reference-button
5715 'help-echo "mouse-1, RET: create definition for undefined reference"
5716 'follow-link t
5717 'face 'bold
5718 'action (lambda (b)
5719 (let ((buffer (button-get b 'target-buffer))
5720 (line (button-get b 'target-line))
5721 (label (button-label b)))
5722 (switch-to-buffer-other-window buffer)
5723 (goto-char (point-min))
5724 (forward-line line)
5725 (markdown-insert-reference-definition label)
5726 (markdown-check-refs t))))
5728 ;; Jump to line in buffer specified by 'target-buffer property.
5729 ;; Line number is button's 'line property.
5730 (define-button-type 'markdown-goto-line-button
5731 'help-echo "mouse-1, RET: go to line"
5732 'follow-link t
5733 'face 'italic
5734 'action (lambda (b)
5735 (message (button-get b 'buffer))
5736 (switch-to-buffer-other-window (button-get b 'target-buffer))
5737 ;; use call-interactively to silence compiler
5738 (let ((current-prefix-arg (button-get b 'target-line)))
5739 (call-interactively 'goto-line))))
5741 ;; Jumps to a particular link at location given by 'target-char
5742 ;; property in buffer given by 'target-buffer property.
5743 (define-button-type 'markdown-location-button
5744 'help-echo "mouse-1, RET: jump to location of link"
5745 'follow-link t
5746 'face 'bold
5747 'action (lambda (b)
5748 (let ((target (button-get b 'target-buffer))
5749 (loc (button-get b 'target-char)))
5750 (kill-buffer-and-window)
5751 (switch-to-buffer target)
5752 (goto-char loc))))
5754 (defun markdown-insert-undefined-reference-button (reference oldbuf)
5755 "Insert a button for creating REFERENCE in buffer OLDBUF.
5756 REFERENCE should be a list of the form (reference . occurrences),
5757 as by `markdown-get-undefined-refs'."
5758 (let ((label (car reference)))
5759 ;; Create a reference button
5760 (insert-button label
5761 :type 'markdown-undefined-reference-button
5762 'target-buffer oldbuf
5763 'target-line (cdr (car (cdr reference))))
5764 (insert " (")
5765 (dolist (occurrence (cdr reference))
5766 (let ((line (cdr occurrence)))
5767 ;; Create a line number button
5768 (insert-button (number-to-string line)
5769 :type 'markdown-goto-line-button
5770 'target-buffer oldbuf
5771 'target-line line)
5772 (insert " ")))
5773 (delete-char -1)
5774 (insert ")")
5775 (newline)))
5777 (defun markdown-insert-link-button (link oldbuf)
5778 "Insert a button for jumping to LINK in buffer OLDBUF.
5779 LINK should be a list of the form (text char line) containing
5780 the link text, location, and line number."
5781 (let ((label (cl-first link))
5782 (char (cl-second link))
5783 (line (cl-third link)))
5784 ;; Create a reference button
5785 (insert-button label
5786 :type 'markdown-location-button
5787 'target-buffer oldbuf
5788 'target-char char)
5789 (insert (format " (line %d)\n" line))))
5791 (defun markdown-reference-goto-link (&optional reference)
5792 "Jump to the location of the first use of REFERENCE."
5793 (interactive)
5794 (unless reference
5795 (if (thing-at-point-looking-at markdown-regex-reference-definition)
5796 (setq reference (match-string-no-properties 2))
5797 (user-error "No reference definition at point")))
5798 (let ((links (markdown-reference-find-links reference)))
5799 (cond ((= (length links) 1)
5800 (goto-char (cadr (car links))))
5801 ((> (length links) 1)
5802 (let ((oldbuf (current-buffer))
5803 (linkbuf (markdown-reference-links-buffer)))
5804 (with-current-buffer linkbuf
5805 (insert "Links using reference " reference ":\n\n")
5806 (dolist (link (reverse links))
5807 (markdown-insert-link-button link oldbuf)))
5808 (view-buffer-other-window linkbuf)
5809 (goto-char (point-min))
5810 (forward-line 2)))
5812 (error "No links for reference %s" reference)))))
5814 (defun markdown-check-refs (&optional silent)
5815 "Show all undefined Markdown references in current `markdown-mode' buffer.
5816 If SILENT is non-nil, do not message anything when no undefined
5817 references found.
5818 Links which have empty reference definitions are considered to be
5819 defined."
5820 (interactive "P")
5821 (when (not (eq major-mode 'markdown-mode))
5822 (user-error "Not available in current mode"))
5823 (let ((oldbuf (current-buffer))
5824 (refs (markdown-get-undefined-refs))
5825 (refbuf (markdown-reference-check-buffer)))
5826 (if (null refs)
5827 (progn
5828 (when (not silent)
5829 (message "No undefined references found"))
5830 (kill-buffer refbuf))
5831 (with-current-buffer refbuf
5832 (insert "The following references are undefined:\n\n")
5833 (dolist (ref refs)
5834 (markdown-insert-undefined-reference-button ref oldbuf))
5835 (view-buffer-other-window refbuf)
5836 (goto-char (point-min))
5837 (forward-line 2)))))
5840 ;;; Lists =====================================================================
5842 (defun markdown-insert-list-item (&optional arg)
5843 "Insert a new list item.
5844 If the point is inside unordered list, insert a bullet mark. If
5845 the point is inside ordered list, insert the next number followed
5846 by a period. Use the previous list item to determine the amount
5847 of whitespace to place before and after list markers.
5849 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
5850 decrease the indentation by one level.
5852 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
5853 increase the indentation by one level."
5854 (interactive "p")
5855 (let (bounds cur-indent marker indent new-indent new-loc)
5856 (save-match-data
5857 ;; Look for a list item on current or previous non-blank line
5858 (save-excursion
5859 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
5860 (not (bobp))
5861 (markdown-cur-line-blank-p))
5862 (forward-line -1)))
5863 (when bounds
5864 (cond ((save-excursion
5865 (skip-chars-backward " \t")
5866 (looking-at-p markdown-regex-list))
5867 (beginning-of-line)
5868 (insert "\n")
5869 (forward-line -1))
5870 ((not (markdown-cur-line-blank-p))
5871 (newline)))
5872 (setq new-loc (point)))
5873 ;; Look ahead for a list item on next non-blank line
5874 (unless bounds
5875 (save-excursion
5876 (while (and (null bounds)
5877 (not (eobp))
5878 (markdown-cur-line-blank-p))
5879 (forward-line)
5880 (setq bounds (markdown-cur-list-item-bounds))))
5881 (when bounds
5882 (setq new-loc (point))
5883 (unless (markdown-cur-line-blank-p)
5884 (newline))))
5885 (if (not bounds)
5886 ;; When not in a list, start a new unordered one
5887 (progn
5888 (unless (markdown-cur-line-blank-p)
5889 (insert "\n"))
5890 (insert markdown-unordered-list-item-prefix))
5891 ;; Compute indentation and marker for new list item
5892 (setq cur-indent (nth 2 bounds))
5893 (setq marker (nth 4 bounds))
5894 ;; If current item is a GFM checkbox, insert new unchecked checkbox.
5895 (when (nth 5 bounds)
5896 (setq marker
5897 (concat marker
5898 (replace-regexp-in-string "[Xx]" " " (nth 5 bounds)))))
5899 (cond
5900 ;; Dedent: decrement indentation, find previous marker.
5901 ((= arg 4)
5902 (setq indent (max (- cur-indent 4) 0))
5903 (let ((prev-bounds
5904 (save-excursion
5905 (goto-char (nth 0 bounds))
5906 (when (markdown-up-list)
5907 (markdown-cur-list-item-bounds)))))
5908 (when prev-bounds
5909 (setq marker (nth 4 prev-bounds)))))
5910 ;; Indent: increment indentation by 4, use same marker.
5911 ((= arg 16) (setq indent (+ cur-indent 4)))
5912 ;; Same level: keep current indentation and marker.
5913 (t (setq indent cur-indent)))
5914 (setq new-indent (make-string indent 32))
5915 (goto-char new-loc)
5916 (cond
5917 ;; Ordered list
5918 ((string-match-p "[0-9]" marker)
5919 (if (= arg 16) ;; starting a new column indented one more level
5920 (insert (concat new-indent "1. "))
5921 ;; Don't use previous match-data
5922 (set-match-data nil)
5923 ;; travel up to the last item and pick the correct number. If
5924 ;; the argument was nil, "new-indent = cur-indent" is the same,
5925 ;; so we don't need special treatment. Neat.
5926 (save-excursion
5927 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
5928 (>= (forward-line -1) 0))))
5929 (let* ((old-prefix (match-string 1))
5930 (old-spacing (match-string 2))
5931 (new-prefix (if old-prefix
5932 (int-to-string (1+ (string-to-number old-prefix)))
5933 "1"))
5934 (space-adjust (- (length old-prefix) (length new-prefix)))
5935 (new-spacing (if (and (match-string 2)
5936 (not (string-match-p "\t" old-spacing))
5937 (< space-adjust 0)
5938 (> space-adjust (- 1 (length (match-string 2)))))
5939 (substring (match-string 2) 0 space-adjust)
5940 (or old-spacing ". "))))
5941 (insert (concat new-indent new-prefix new-spacing)))))
5942 ;; Unordered list, GFM task list, or ordered list with hash mark
5943 ((string-match-p "[\\*\\+-]\\|#\\." marker)
5944 (insert new-indent marker))))
5945 ;; Propertize the newly inserted list item now
5946 (markdown-syntax-propertize-list-items (point-at-bol) (point-at-eol)))))
5948 (defun markdown-move-list-item-up ()
5949 "Move the current list item up in the list when possible.
5950 In nested lists, move child items with the parent item."
5951 (interactive)
5952 (let (cur prev old)
5953 (when (setq cur (markdown-cur-list-item-bounds))
5954 (setq old (point))
5955 (goto-char (nth 0 cur))
5956 (if (markdown-prev-list-item (nth 3 cur))
5957 (progn
5958 (setq prev (markdown-cur-list-item-bounds))
5959 (condition-case nil
5960 (progn
5961 (transpose-regions (nth 0 prev) (nth 1 prev)
5962 (nth 0 cur) (nth 1 cur) t)
5963 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
5964 ;; Catch error in case regions overlap.
5965 (error (goto-char old))))
5966 (goto-char old)))))
5968 (defun markdown-move-list-item-down ()
5969 "Move the current list item down in the list when possible.
5970 In nested lists, move child items with the parent item."
5971 (interactive)
5972 (let (cur next old)
5973 (when (setq cur (markdown-cur-list-item-bounds))
5974 (setq old (point))
5975 (if (markdown-next-list-item (nth 3 cur))
5976 (progn
5977 (setq next (markdown-cur-list-item-bounds))
5978 (condition-case nil
5979 (progn
5980 (transpose-regions (nth 0 cur) (nth 1 cur)
5981 (nth 0 next) (nth 1 next) nil)
5982 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
5983 ;; Catch error in case regions overlap.
5984 (error (goto-char old))))
5985 (goto-char old)))))
5987 (defun markdown-demote-list-item (&optional bounds)
5988 "Indent (or demote) the current list item.
5989 Optionally, BOUNDS of the current list item may be provided if available.
5990 In nested lists, demote child items as well."
5991 (interactive)
5992 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
5993 (save-excursion
5994 (let* ((item-start (set-marker (make-marker) (nth 0 bounds)))
5995 (item-end (set-marker (make-marker) (nth 1 bounds)))
5996 (list-start (progn (markdown-beginning-of-list)
5997 (set-marker (make-marker) (point))))
5998 (list-end (progn (markdown-end-of-list)
5999 (set-marker (make-marker) (point)))))
6000 (goto-char item-start)
6001 (while (< (point) item-end)
6002 (unless (markdown-cur-line-blank-p)
6003 (insert (make-string markdown-list-indent-width ? )))
6004 (forward-line))
6005 (markdown-syntax-propertize-list-items list-start list-end)))))
6007 (defun markdown-promote-list-item (&optional bounds)
6008 "Unindent (or promote) the current list item.
6009 Optionally, BOUNDS of the current list item may be provided if available.
6010 In nested lists, demote child items as well."
6011 (interactive)
6012 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6013 (save-excursion
6014 (save-match-data
6015 (let ((item-start (set-marker (make-marker) (nth 0 bounds)))
6016 (item-end (set-marker (make-marker) (nth 1 bounds)))
6017 (list-start (progn (markdown-beginning-of-list)
6018 (set-marker (make-marker) (point))))
6019 (list-end (progn (markdown-end-of-list)
6020 (set-marker (make-marker) (point))))
6021 num regexp)
6022 (goto-char item-start)
6023 (when (looking-at (format "^[ ]\\{1,%d\\}"
6024 markdown-list-indent-width))
6025 (setq num (- (match-end 0) (match-beginning 0)))
6026 (setq regexp (format "^[ ]\\{1,%d\\}" num))
6027 (while (and (< (point) item-end)
6028 (re-search-forward regexp item-end t))
6029 (replace-match "" nil nil)
6030 (forward-line))
6031 (markdown-syntax-propertize-list-items list-start list-end)))))))
6033 (defun markdown-cleanup-list-numbers-level (&optional pfx)
6034 "Update the numbering for level PFX (as a string of spaces).
6036 Assume that the previously found match was for a numbered item in
6037 a list."
6038 (let ((cpfx pfx)
6039 (idx 0)
6040 (continue t)
6041 (step t)
6042 (sep nil))
6043 (while (and continue (not (eobp)))
6044 (setq step t)
6045 (cond
6046 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
6047 (setq cpfx (match-string-no-properties 1))
6048 (cond
6049 ((string= cpfx pfx)
6050 (save-excursion
6051 (replace-match
6052 (concat pfx (number-to-string (setq idx (1+ idx))) ". ")))
6053 (setq sep nil))
6054 ;; indented a level
6055 ((string< pfx cpfx)
6056 (setq sep (markdown-cleanup-list-numbers-level cpfx))
6057 (setq step nil))
6058 ;; exit the loop
6060 (setq step nil)
6061 (setq continue nil))))
6063 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
6064 (setq cpfx (match-string-no-properties 1))
6065 (cond
6066 ;; reset if separated before
6067 ((string= cpfx pfx) (when sep (setq idx 0)))
6068 ((string< cpfx pfx)
6069 (setq step nil)
6070 (setq continue nil))))
6071 (t (setq sep t)))
6073 (when step
6074 (beginning-of-line)
6075 (setq continue (= (forward-line) 0))))
6076 sep))
6078 (defun markdown-cleanup-list-numbers ()
6079 "Update the numbering of ordered lists."
6080 (interactive)
6081 (save-excursion
6082 (goto-char (point-min))
6083 (markdown-cleanup-list-numbers-level "")))
6086 ;;; Movement ==================================================================
6088 (defun markdown-beginning-of-defun (&optional arg)
6089 "`beginning-of-defun-function' for Markdown.
6090 This is used to find the beginning of the defun and should behave
6091 like ‘beginning-of-defun’, returning non-nil if it found the
6092 beginning of a defun. It moves the point backward, right before a
6093 heading which defines a defun. When ARG is non-nil, repeat that
6094 many times. When ARG is negative, move forward to the ARG-th
6095 following section."
6096 (or arg (setq arg 1))
6097 (when (< arg 0) (end-of-line))
6098 ;; Adjust position for setext headings.
6099 (when (and (thing-at-point-looking-at markdown-regex-header-setext)
6100 (not (= (point) (match-beginning 0)))
6101 (not (markdown-code-block-at-point-p)))
6102 (goto-char (match-end 0)))
6103 (let (found)
6104 ;; Move backward with positive argument.
6105 (while (and (not (bobp)) (> arg 0))
6106 (setq found nil)
6107 (while (and (not found)
6108 (not (bobp))
6109 (re-search-backward markdown-regex-header nil 'move))
6110 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6111 (setq found (match-beginning 0)))
6112 (setq arg (1- arg)))
6113 ;; Move forward with negative argument.
6114 (while (and (not (eobp)) (< arg 0))
6115 (setq found nil)
6116 (while (and (not found)
6117 (not (eobp))
6118 (re-search-forward markdown-regex-header nil 'move))
6119 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6120 (setq found (match-beginning 0)))
6121 (setq arg (1+ arg)))
6122 (when found
6123 (beginning-of-line)
6124 t)))
6126 (defun markdown-end-of-defun ()
6127 "`end-of-defun-function’ for Markdown.
6128 This is used to find the end of the defun at point.
6129 It is called with no argument, right after calling ‘beginning-of-defun-raw’,
6130 so it can assume that point is at the beginning of the defun body.
6131 It should move point to the first position after the defun."
6132 (or (eobp) (forward-char 1))
6133 (let (found)
6134 (while (and (not found)
6135 (not (eobp))
6136 (re-search-forward markdown-regex-header nil 'move))
6137 (when (not (markdown-code-block-at-pos (match-beginning 0)))
6138 (setq found (match-beginning 0))))
6139 (when found
6140 (goto-char found)
6141 (skip-syntax-backward "-"))))
6143 (make-obsolete 'markdown-beginning-of-block 'markdown-beginning-of-text-block "v2.2")
6145 (defun markdown-beginning-of-text-block ()
6146 "Move backward to previous beginning of a plain text block.
6147 This function simply looks for blank lines without considering
6148 the surrounding context in light of Markdown syntax. For that, see
6149 `markdown-backward-block'."
6150 (interactive)
6151 (let ((start (point)))
6152 (if (re-search-backward markdown-regex-block-separator nil t)
6153 (goto-char (match-end 0))
6154 (goto-char (point-min)))
6155 (when (and (= start (point)) (not (bobp)))
6156 (forward-line -1)
6157 (if (re-search-backward markdown-regex-block-separator nil t)
6158 (goto-char (match-end 0))
6159 (goto-char (point-min))))))
6161 (make-obsolete 'markdown-end-of-block 'markdown-end-of-text-block "v2.2")
6163 (defun markdown-end-of-text-block ()
6164 "Move forward to next beginning of a plain text block.
6165 This function simply looks for blank lines without considering
6166 the surrounding context in light of Markdown syntax. For that, see
6167 `markdown-forward-block'."
6168 (interactive)
6169 (beginning-of-line)
6170 (skip-chars-forward " \t\n")
6171 (when (= (point) (point-min))
6172 (forward-char))
6173 (if (re-search-forward markdown-regex-block-separator nil t)
6174 (goto-char (match-end 0))
6175 (goto-char (point-max)))
6176 (skip-chars-backward " \t\n")
6177 (forward-line))
6179 (defun markdown-backward-paragraph (&optional arg)
6180 "Move the point to the start of the current paragraph.
6181 With argument ARG, do it ARG times; a negative argument ARG = -N
6182 means move forward N blocks."
6183 (interactive "^p")
6184 (or arg (setq arg 1))
6185 (if (< arg 0)
6186 (markdown-forward-paragraph (- arg))
6187 (dotimes (_ arg)
6188 ;; Skip over whitespace in between paragraphs when moving backward.
6189 (skip-chars-backward " \t\n")
6190 (beginning-of-line)
6191 ;; Skip over code block endings.
6192 (when (markdown-range-properties-exist
6193 (point-at-bol) (point-at-eol)
6194 '(markdown-gfm-block-end
6195 markdown-tilde-fence-end))
6196 (forward-line -1))
6197 ;; Skip over blank lines inside blockquotes.
6198 (while (and (not (eobp))
6199 (looking-at markdown-regex-blockquote)
6200 (= (length (match-string 3)) 0))
6201 (forward-line -1))
6202 ;; Proceed forward based on the type of block of paragraph.
6203 (let (bounds skip)
6204 (cond
6205 ;; Blockquotes
6206 ((looking-at markdown-regex-blockquote)
6207 (while (and (not (bobp))
6208 (looking-at markdown-regex-blockquote)
6209 (> (length (match-string 3)) 0)) ;; not blank
6210 (forward-line -1))
6211 (forward-line))
6212 ;; List items
6213 ((setq bounds (markdown-cur-list-item-bounds))
6214 (goto-char (nth 0 bounds)))
6215 ;; Other
6217 (while (and (not (bobp))
6218 (not skip)
6219 (not (markdown-cur-line-blank-p))
6220 (not (looking-at markdown-regex-blockquote))
6221 (not (markdown-range-properties-exist
6222 (point-at-bol) (point-at-eol)
6223 '(markdown-gfm-block-end
6224 markdown-tilde-fence-end))))
6225 (setq skip (markdown-range-properties-exist
6226 (point-at-bol) (point-at-eol)
6227 '(markdown-gfm-block-begin
6228 markdown-tilde-fence-begin)))
6229 (forward-line -1))
6230 (unless (bobp)
6231 (forward-line 1))))))))
6233 (defun markdown-forward-paragraph (&optional arg)
6234 "Move forward to the next end of a paragraph.
6235 With argument ARG, do it ARG times; a negative argument ARG = -N
6236 means move backward N blocks."
6237 (interactive "^p")
6238 (or arg (setq arg 1))
6239 (if (< arg 0)
6240 (markdown-backward-paragraph (- arg))
6241 (dotimes (_ arg)
6242 ;; Skip whitespace in between paragraphs.
6243 (when (markdown-cur-line-blank-p)
6244 (skip-syntax-forward "-")
6245 (beginning-of-line))
6246 ;; Proceed forward based on the type of block.
6247 (let (bounds skip)
6248 (cond
6249 ;; Blockquotes
6250 ((looking-at markdown-regex-blockquote)
6251 ;; Skip over blank lines inside blockquotes.
6252 (while (and (not (eobp))
6253 (looking-at markdown-regex-blockquote)
6254 (= (length (match-string 3)) 0))
6255 (forward-line))
6256 ;; Move to end of quoted text block
6257 (while (and (not (eobp))
6258 (looking-at markdown-regex-blockquote)
6259 (> (length (match-string 3)) 0)) ;; not blank
6260 (forward-line)))
6261 ;; List items
6262 ((and (markdown-cur-list-item-bounds)
6263 (setq bounds (markdown-next-list-item-bounds)))
6264 (goto-char (nth 0 bounds)))
6265 ;; Other
6267 (forward-line)
6268 (while (and (not (eobp))
6269 (not skip)
6270 (not (markdown-cur-line-blank-p))
6271 (not (looking-at markdown-regex-blockquote))
6272 (not (markdown-range-properties-exist
6273 (point-at-bol) (point-at-eol)
6274 '(markdown-gfm-block-begin
6275 markdown-tilde-fence-begin))))
6276 (setq skip (markdown-range-properties-exist
6277 (point-at-bol) (point-at-eol)
6278 '(markdown-gfm-block-end
6279 markdown-tilde-fence-end)))
6280 (forward-line))))))))
6282 (defun markdown-backward-block (&optional arg)
6283 "Move the point to the start of the current Markdown block.
6284 Moves across complete code blocks, list items, and blockquotes,
6285 but otherwise stops at blank lines, headers, and horizontal
6286 rules. With argument ARG, do it ARG times; a negative argument
6287 ARG = -N means move forward N blocks."
6288 (interactive "^p")
6289 (or arg (setq arg 1))
6290 (if (< arg 0)
6291 (markdown-forward-block (- arg))
6292 (dotimes (_ arg)
6293 ;; Skip over whitespace in between blocks when moving backward,
6294 ;; unless at a block boundary with no whitespace.
6295 (skip-syntax-backward "-")
6296 (beginning-of-line)
6297 ;; Proceed forward based on the type of block.
6298 (cond
6299 ;; Code blocks
6300 ((and (markdown-code-block-at-pos (point)) ;; this line
6301 (markdown-code-block-at-pos (point-at-bol 0))) ;; previous line
6302 (forward-line -1)
6303 (while (and (markdown-code-block-at-point-p) (not (bobp)))
6304 (forward-line -1))
6305 (forward-line))
6306 ;; Headings
6307 ((markdown-heading-at-point)
6308 (goto-char (match-beginning 0)))
6309 ;; Horizontal rules
6310 ((looking-at markdown-regex-hr))
6311 ;; Blockquotes
6312 ((looking-at markdown-regex-blockquote)
6313 (forward-line -1)
6314 (while (and (looking-at markdown-regex-blockquote)
6315 (not (bobp)))
6316 (forward-line -1))
6317 (forward-line))
6318 ;; List items
6319 ((markdown-cur-list-item-bounds)
6320 (markdown-beginning-of-list))
6321 ;; Other
6323 ;; Move forward in case it is a one line regular paragraph.
6324 (unless (markdown-next-line-blank-p)
6325 (forward-line))
6326 (unless (markdown-prev-line-blank-p)
6327 (markdown-backward-paragraph)))))))
6329 (defun markdown-forward-block (&optional arg)
6330 "Move forward to the next end of a Markdown block.
6331 Moves across complete code blocks, list items, and blockquotes,
6332 but otherwise stops at blank lines, headers, and horizontal
6333 rules. With argument ARG, do it ARG times; a negative argument
6334 ARG = -N means move backward N blocks."
6335 (interactive "^p")
6336 (or arg (setq arg 1))
6337 (if (< arg 0)
6338 (markdown-backward-block (- arg))
6339 (dotimes (_ arg)
6340 ;; Skip over whitespace in between blocks when moving forward.
6341 (if (markdown-cur-line-blank-p)
6342 (skip-syntax-forward "-")
6343 (beginning-of-line))
6344 ;; Proceed forward based on the type of block.
6345 (cond
6346 ;; Code blocks
6347 ((markdown-code-block-at-point-p)
6348 (forward-line)
6349 (while (and (markdown-code-block-at-point-p) (not (eobp)))
6350 (forward-line)))
6351 ;; Headings
6352 ((looking-at markdown-regex-header)
6353 (goto-char (or (match-end 4) (match-end 2) (match-end 3)))
6354 (forward-line))
6355 ;; Horizontal rules
6356 ((looking-at markdown-regex-hr)
6357 (forward-line))
6358 ;; Blockquotes
6359 ((looking-at markdown-regex-blockquote)
6360 (forward-line)
6361 (while (and (looking-at markdown-regex-blockquote) (not (eobp)))
6362 (forward-line)))
6363 ;; List items
6364 ((markdown-cur-list-item-bounds)
6365 (markdown-end-of-list)
6366 (forward-line))
6367 ;; Other
6368 (t (markdown-forward-paragraph))))
6369 (skip-syntax-backward "-")
6370 (unless (eobp)
6371 (forward-char 1))))
6373 (defun markdown-backward-page (&optional count)
6374 "Move backward to boundary of the current toplevel section.
6375 With COUNT, repeat, or go forward if negative."
6376 (interactive "p")
6377 (or count (setq count 1))
6378 (if (< count 0)
6379 (markdown-forward-page (- count))
6380 (skip-syntax-backward "-")
6381 (or (markdown-back-to-heading-over-code-block t t)
6382 (goto-char (point-min)))
6383 (when (looking-at markdown-regex-header)
6384 (let ((level (markdown-outline-level)))
6385 (when (> level 1) (markdown-up-heading level))
6386 (when (> count 1)
6387 (condition-case nil
6388 (markdown-backward-same-level (1- count))
6389 (error (goto-char (point-min)))))))))
6391 (defun markdown-forward-page (&optional count)
6392 "Move forward to boundary of the current toplevel section.
6393 With COUNT, repeat, or go backward if negative."
6394 (interactive "p")
6395 (or count (setq count 1))
6396 (if (< count 0)
6397 (markdown-backward-page (- count))
6398 (if (markdown-back-to-heading-over-code-block t t)
6399 (let ((level (markdown-outline-level)))
6400 (when (> level 1) (markdown-up-heading level))
6401 (condition-case nil
6402 (markdown-forward-same-level count)
6403 (error (goto-char (point-max)))))
6404 (markdown-next-visible-heading 1))))
6406 (defun markdown-next-link ()
6407 "Jump to next inline, reference, or wiki link.
6408 If successful, return point. Otherwise, return nil.
6409 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
6410 (interactive)
6411 (let ((opoint (point)))
6412 (when (or (markdown-link-p) (markdown-wiki-link-p))
6413 ;; At a link already, move past it.
6414 (goto-char (+ (match-end 0) 1)))
6415 ;; Search for the next wiki link and move to the beginning.
6416 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t)
6417 (markdown-code-block-at-point-p)
6418 (< (point) (point-max))))
6419 (if (and (not (eq (point) opoint))
6420 (or (markdown-link-p) (markdown-wiki-link-p)))
6421 ;; Group 1 will move past non-escape character in wiki link regexp.
6422 ;; Go to beginning of group zero for all other link types.
6423 (goto-char (or (match-beginning 1) (match-beginning 0)))
6424 (goto-char opoint)
6425 nil)))
6427 (defun markdown-previous-link ()
6428 "Jump to previous wiki link.
6429 If successful, return point. Otherwise, return nil.
6430 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
6431 (interactive)
6432 (let ((opoint (point)))
6433 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t)
6434 (markdown-code-block-at-point-p)
6435 (> (point) (point-min))))
6436 (if (and (not (eq (point) opoint))
6437 (or (markdown-link-p) (markdown-wiki-link-p)))
6438 (goto-char (or (match-beginning 1) (match-beginning 0)))
6439 (goto-char opoint)
6440 nil)))
6443 ;;; Outline ===================================================================
6445 (defun markdown-move-heading-common (move-fn &optional arg adjust)
6446 "Wrapper for `outline-mode' functions to skip false positives.
6447 MOVE-FN is a function and ARG is its argument. For example,
6448 headings inside preformatted code blocks may match
6449 `outline-regexp' but should not be considered as headings.
6450 When ADJUST is non-nil, adjust the point for interactive calls
6451 to avoid leaving the point at invisible markup. This adjustment
6452 generally should only be done for interactive calls, since other
6453 functions may expect the point to be at the beginning of the
6454 regular expression."
6455 (let ((prev -1) (start (point)))
6456 (if arg (funcall move-fn arg) (funcall move-fn))
6457 (while (and (/= prev (point)) (markdown-code-block-at-point-p))
6458 (setq prev (point))
6459 (if arg (funcall move-fn arg) (funcall move-fn)))
6460 ;; Adjust point for setext headings and invisible text.
6461 (save-match-data
6462 (when (and adjust (thing-at-point-looking-at markdown-regex-header))
6463 (if markdown-hide-markup
6464 ;; Move to beginning of heading text if markup is hidden.
6465 (goto-char (or (match-beginning 1) (match-beginning 5)))
6466 ;; Move to beginning of markup otherwise.
6467 (goto-char (or (match-beginning 1) (match-beginning 4))))))
6468 (if (= (point) start) nil (point))))
6470 (defun markdown-next-visible-heading (arg)
6471 "Move to the next visible heading line of any level.
6472 With argument, repeats or can move backward if negative. ARG is
6473 passed to `outline-next-visible-heading'."
6474 (interactive "p")
6475 (markdown-move-heading-common #'outline-next-visible-heading arg 'adjust))
6477 (defun markdown-previous-visible-heading (arg)
6478 "Move to the previous visible heading line of any level.
6479 With argument, repeats or can move backward if negative. ARG is
6480 passed to `outline-previous-visible-heading'."
6481 (interactive "p")
6482 (markdown-move-heading-common #'outline-previous-visible-heading arg 'adjust))
6484 (defun markdown-next-heading ()
6485 "Move to the next heading line of any level."
6486 (markdown-move-heading-common #'outline-next-heading))
6488 (defun markdown-previous-heading ()
6489 "Move to the previous heading line of any level."
6490 (markdown-move-heading-common #'outline-previous-heading))
6492 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok no-error)
6493 "Move back to the beginning of the previous heading.
6494 Returns t if the point is at a heading, the location if a heading
6495 was found, and nil otherwise.
6496 Only visible heading lines are considered, unless INVISIBLE-OK is
6497 non-nil. Throw an error if there is no previous heading unless
6498 NO-ERROR is non-nil.
6499 Leaves match data intact for `markdown-regex-header'."
6500 (beginning-of-line)
6501 (or (and (markdown-heading-at-point)
6502 (not (markdown-code-block-at-point-p)))
6503 (let (found)
6504 (save-excursion
6505 (while (and (not found)
6506 (re-search-backward markdown-regex-header nil t))
6507 (when (and (or invisible-ok (not (outline-invisible-p)))
6508 (not (markdown-code-block-at-point-p)))
6509 (setq found (point))))
6510 (if (not found)
6511 (unless no-error (user-error "Before first heading"))
6512 (setq found (point))))
6513 (when found (goto-char found)))))
6515 (defun markdown-forward-same-level (arg)
6516 "Move forward to the ARG'th heading at same level as this one.
6517 Stop at the first and last headings of a superior heading."
6518 (interactive "p")
6519 (markdown-back-to-heading-over-code-block)
6520 (markdown-move-heading-common #'outline-forward-same-level arg 'adjust))
6522 (defun markdown-backward-same-level (arg)
6523 "Move backward to the ARG'th heading at same level as this one.
6524 Stop at the first and last headings of a superior heading."
6525 (interactive "p")
6526 (markdown-back-to-heading-over-code-block)
6527 (while (> arg 0)
6528 (let ((point-to-move-to
6529 (save-excursion
6530 (markdown-move-heading-common #'outline-get-last-sibling nil 'adjust))))
6531 (if point-to-move-to
6532 (progn
6533 (goto-char point-to-move-to)
6534 (setq arg (1- arg)))
6535 (user-error "No previous same-level heading")))))
6537 (defun markdown-up-heading (arg)
6538 "Move to the visible heading line of which the present line is a subheading.
6539 With argument, move up ARG levels."
6540 (interactive "p")
6541 (and (called-interactively-p 'any)
6542 (not (eq last-command 'markdown-up-heading)) (push-mark))
6543 (markdown-move-heading-common #'outline-up-heading arg 'adjust))
6545 (defun markdown-back-to-heading (&optional invisible-ok)
6546 "Move to previous heading line, or beg of this line if it's a heading.
6547 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
6548 (markdown-move-heading-common #'outline-back-to-heading invisible-ok))
6550 (defalias 'markdown-end-of-heading 'outline-end-of-heading)
6552 (defun markdown-on-heading-p ()
6553 "Return non-nil if point is on a heading line."
6554 (get-text-property (point-at-bol) 'markdown-heading))
6556 (defun markdown-end-of-subtree (&optional invisible-OK)
6557 "Move to the end of the current subtree.
6558 Only visible heading lines are considered, unless INVISIBLE-OK is
6559 non-nil.
6560 Derived from `org-end-of-subtree'."
6561 (markdown-back-to-heading invisible-OK)
6562 (let ((first t)
6563 (level (markdown-outline-level)))
6564 (while (and (not (eobp))
6565 (or first (> (markdown-outline-level) level)))
6566 (setq first nil)
6567 (markdown-next-heading))
6568 (if (memq (preceding-char) '(?\n ?\^M))
6569 (progn
6570 ;; Go to end of line before heading
6571 (forward-char -1)
6572 (if (memq (preceding-char) '(?\n ?\^M))
6573 ;; leave blank line before heading
6574 (forward-char -1)))))
6575 (point))
6577 (defun markdown-outline-fix-visibility ()
6578 "Hide any false positive headings that should not be shown.
6579 For example, headings inside preformatted code blocks may match
6580 `outline-regexp' but should not be shown as headings when cycling.
6581 Also, the ending --- line in metadata blocks appears to be a
6582 setext header, but should not be folded."
6583 (save-excursion
6584 (goto-char (point-min))
6585 ;; Unhide any false positives in metadata blocks
6586 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin)
6587 (let ((body (progn (forward-line)
6588 (markdown-text-property-at-point
6589 'markdown-yaml-metadata-section))))
6590 (when body
6591 (let ((end (progn (goto-char (cl-second body))
6592 (markdown-text-property-at-point
6593 'markdown-yaml-metadata-end))))
6594 (outline-flag-region (point-min) (1+ (cl-second end)) nil)))))
6595 ;; Hide any false positives in code blocks
6596 (unless (outline-on-heading-p)
6597 (outline-next-visible-heading 1))
6598 (while (< (point) (point-max))
6599 (when (markdown-code-block-at-point-p)
6600 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t))
6601 (outline-next-visible-heading 1))))
6603 (defvar markdown-cycle-global-status 1)
6604 (defvar markdown-cycle-subtree-status nil)
6606 (defun markdown-next-preface ()
6607 (let (finish)
6608 (while (and (not finish) (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
6609 nil 'move))
6610 (unless (markdown-code-block-at-point-p)
6611 (goto-char (match-beginning 0))
6612 (setq finish t))))
6613 (when (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
6614 (forward-char -1)))
6616 (defun markdown-show-entry ()
6617 (save-excursion
6618 (outline-back-to-heading t)
6619 (outline-flag-region (1- (point))
6620 (progn
6621 (markdown-next-preface)
6622 (if (= 1 (- (point-max) (point)))
6623 (point-max)
6624 (point)))
6625 nil)))
6627 ;; This function was originally derived from `org-cycle' from org.el.
6628 (defun markdown-cycle (&optional arg)
6629 "Visibility cycling for Markdown mode.
6630 If ARG is t, perform global visibility cycling. If the point is
6631 at an atx-style header, cycle visibility of the corresponding
6632 subtree. Otherwise, indent the current line or insert a tab,
6633 as appropriate, by calling `indent-for-tab-command'."
6634 (interactive "P")
6635 (cond
6637 ;; Global cycling
6638 ((eq arg t)
6639 (cond
6640 ;; Move from overview to contents
6641 ((and (eq last-command this-command)
6642 (eq markdown-cycle-global-status 2))
6643 (markdown-hide-sublevels 1)
6644 (message "CONTENTS")
6645 (setq markdown-cycle-global-status 3)
6646 (markdown-outline-fix-visibility))
6647 ;; Move from contents to all
6648 ((and (eq last-command this-command)
6649 (eq markdown-cycle-global-status 3))
6650 (markdown-show-all)
6651 (message "SHOW ALL")
6652 (setq markdown-cycle-global-status 1))
6653 ;; Defaults to overview
6655 (markdown-hide-body)
6656 (message "OVERVIEW")
6657 (setq markdown-cycle-global-status 2)
6658 (markdown-outline-fix-visibility))))
6660 ;; At a heading: rotate between three different views
6661 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
6662 (markdown-back-to-heading)
6663 (let ((goal-column 0) eoh eol eos)
6664 ;; Determine boundaries
6665 (save-excursion
6666 (markdown-back-to-heading)
6667 (save-excursion
6668 (beginning-of-line 2)
6669 (while (and (not (eobp)) ;; this is like `next-line'
6670 (get-char-property (1- (point)) 'invisible))
6671 (beginning-of-line 2)) (setq eol (point)))
6672 (markdown-end-of-heading) (setq eoh (point))
6673 (markdown-end-of-subtree t)
6674 (skip-chars-forward " \t\n")
6675 (beginning-of-line 1) ; in case this is an item
6676 (setq eos (1- (point))))
6677 ;; Find out what to do next and set `this-command'
6678 (cond
6679 ;; Nothing is hidden behind this heading
6680 ((= eos eoh)
6681 (message "EMPTY ENTRY")
6682 (setq markdown-cycle-subtree-status nil))
6683 ;; Entire subtree is hidden in one line: open it
6684 ((>= eol eos)
6685 (markdown-show-entry)
6686 (markdown-show-children)
6687 (message "CHILDREN")
6688 (setq markdown-cycle-subtree-status 'children))
6689 ;; We just showed the children, now show everything.
6690 ((and (eq last-command this-command)
6691 (eq markdown-cycle-subtree-status 'children))
6692 (markdown-show-subtree)
6693 (message "SUBTREE")
6694 (setq markdown-cycle-subtree-status 'subtree))
6695 ;; Default action: hide the subtree.
6697 (markdown-hide-subtree)
6698 (message "FOLDED")
6699 (setq markdown-cycle-subtree-status 'folded)))))
6701 ;; In a table, move forward by one cell
6702 ((markdown-table-at-point-p)
6703 (call-interactively #'markdown-table-forward-cell))
6705 ;; Otherwise, indent as appropriate
6707 (indent-for-tab-command))))
6709 (defun markdown-shifttab ()
6710 "Handle S-TAB keybinding based on context.
6711 When in a table, move backward one cell.
6712 Otherwise, cycle global heading visibility by calling
6713 `markdown-cycle' with argument t."
6714 (interactive)
6715 (cond ((markdown-table-at-point-p)
6716 (call-interactively #'markdown-table-backward-cell))
6717 (t (markdown-cycle t))))
6719 (defun markdown-outline-level ()
6720 "Return the depth to which a statement is nested in the outline."
6721 (cond
6722 ((and (match-beginning 0)
6723 (markdown-code-block-at-pos (match-beginning 0)))
6724 7) ;; Only 6 header levels are defined.
6725 ((match-end 2) 1)
6726 ((match-end 3) 2)
6727 ((match-end 4)
6728 (length (markdown-trim-whitespace (match-string-no-properties 4))))))
6730 (defun markdown-promote-subtree (&optional arg)
6731 "Promote the current subtree of ATX headings.
6732 Note that Markdown does not support heading levels higher than
6733 six and therefore level-six headings will not be promoted
6734 further. If ARG is non-nil promote the heading, otherwise
6735 demote."
6736 (interactive "*P")
6737 (save-excursion
6738 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
6739 (re-search-backward markdown-regex-header-atx nil t))
6740 (not (markdown-code-block-at-point-p)))
6741 (let ((level (length (match-string 1)))
6742 (promote-or-demote (if arg 1 -1))
6743 (remove 't))
6744 (markdown-cycle-atx promote-or-demote remove)
6745 (catch 'end-of-subtree
6746 (while (and (markdown-next-heading)
6747 (looking-at markdown-regex-header-atx))
6748 ;; Exit if this not a higher level heading; promote otherwise.
6749 (if (and (looking-at markdown-regex-header-atx)
6750 (<= (length (match-string-no-properties 1)) level))
6751 (throw 'end-of-subtree nil)
6752 (markdown-cycle-atx promote-or-demote remove))))))))
6754 (defun markdown-demote-subtree ()
6755 "Demote the current subtree of ATX headings."
6756 (interactive)
6757 (markdown-promote-subtree t))
6759 (defun markdown-move-subtree-up ()
6760 "Move the current subtree of ATX headings up."
6761 (interactive)
6762 (outline-move-subtree-up 1))
6764 (defun markdown-move-subtree-down ()
6765 "Move the current subtree of ATX headings down."
6766 (interactive)
6767 (outline-move-subtree-down 1))
6769 (defun markdown-outline-next ()
6770 "Move to next list item, when in a list, or next visible heading."
6771 (interactive)
6772 (let ((bounds (markdown-next-list-item-bounds)))
6773 (if bounds
6774 (goto-char (nth 0 bounds))
6775 (markdown-next-visible-heading 1))))
6777 (defun markdown-outline-previous ()
6778 "Move to previous list item, when in a list, or previous visible heading."
6779 (interactive)
6780 (let ((bounds (markdown-prev-list-item-bounds)))
6781 (if bounds
6782 (goto-char (nth 0 bounds))
6783 (markdown-previous-visible-heading 1))))
6785 (defun markdown-outline-next-same-level ()
6786 "Move to next list item or heading of same level."
6787 (interactive)
6788 (let ((bounds (markdown-cur-list-item-bounds)))
6789 (if bounds
6790 (markdown-next-list-item (nth 3 bounds))
6791 (markdown-forward-same-level 1))))
6793 (defun markdown-outline-previous-same-level ()
6794 "Move to previous list item or heading of same level."
6795 (interactive)
6796 (let ((bounds (markdown-cur-list-item-bounds)))
6797 (if bounds
6798 (markdown-prev-list-item (nth 3 bounds))
6799 (markdown-backward-same-level 1))))
6801 (defun markdown-outline-up ()
6802 "Move to previous list item, when in a list, or next heading."
6803 (interactive)
6804 (unless (markdown-up-list)
6805 (markdown-up-heading 1)))
6808 ;;; Marking and Narrowing =====================================================
6810 (defun markdown-mark-paragraph ()
6811 "Put mark at end of this block, point at beginning.
6812 The block marked is the one that contains point or follows point.
6814 Interactively, if this command is repeated or (in Transient Mark
6815 mode) if the mark is active, it marks the next block after the
6816 ones already marked."
6817 (interactive)
6818 (if (or (and (eq last-command this-command) (mark t))
6819 (and transient-mark-mode mark-active))
6820 (set-mark
6821 (save-excursion
6822 (goto-char (mark))
6823 (markdown-forward-paragraph)
6824 (point)))
6825 (let ((beginning-of-defun-function 'markdown-backward-paragraph)
6826 (end-of-defun-function 'markdown-forward-paragraph))
6827 (mark-defun))))
6829 (defun markdown-mark-block ()
6830 "Put mark at end of this block, point at beginning.
6831 The block marked is the one that contains point or follows point.
6833 Interactively, if this command is repeated or (in Transient Mark
6834 mode) if the mark is active, it marks the next block after the
6835 ones already marked."
6836 (interactive)
6837 (if (or (and (eq last-command this-command) (mark t))
6838 (and transient-mark-mode mark-active))
6839 (set-mark
6840 (save-excursion
6841 (goto-char (mark))
6842 (markdown-forward-block)
6843 (point)))
6844 (let ((beginning-of-defun-function 'markdown-backward-block)
6845 (end-of-defun-function 'markdown-forward-block))
6846 (mark-defun))))
6848 (defun markdown-narrow-to-block ()
6849 "Make text outside current block invisible.
6850 The current block is the one that contains point or follows point."
6851 (interactive)
6852 (let ((beginning-of-defun-function 'markdown-backward-block)
6853 (end-of-defun-function 'markdown-forward-block))
6854 (narrow-to-defun)))
6856 (defun markdown-mark-text-block ()
6857 "Put mark at end of this plain text block, point at beginning.
6858 The block marked is the one that contains point or follows point.
6860 Interactively, if this command is repeated or (in Transient Mark
6861 mode) if the mark is active, it marks the next block after the
6862 ones already marked."
6863 (interactive)
6864 (if (or (and (eq last-command this-command) (mark t))
6865 (and transient-mark-mode mark-active))
6866 (set-mark
6867 (save-excursion
6868 (goto-char (mark))
6869 (markdown-end-of-text-block)
6870 (point)))
6871 (let ((beginning-of-defun-function 'markdown-beginning-of-text-block)
6872 (end-of-defun-function 'markdown-end-of-text-block))
6873 (mark-defun))))
6875 (defun markdown-mark-page ()
6876 "Put mark at end of this top level section, point at beginning.
6877 The top level section marked is the one that contains point or
6878 follows point.
6880 Interactively, if this command is repeated or (in Transient Mark
6881 mode) if the mark is active, it marks the next page after the
6882 ones already marked."
6883 (interactive)
6884 (if (or (and (eq last-command this-command) (mark t))
6885 (and transient-mark-mode mark-active))
6886 (set-mark
6887 (save-excursion
6888 (goto-char (mark))
6889 (markdown-forward-page)
6890 (point)))
6891 (let ((beginning-of-defun-function 'markdown-backward-page)
6892 (end-of-defun-function 'markdown-forward-page))
6893 (mark-defun))))
6895 (defun markdown-narrow-to-page ()
6896 "Make text outside current top level section invisible.
6897 The current section is the one that contains point or follows point."
6898 (interactive)
6899 (let ((beginning-of-defun-function 'markdown-backward-page)
6900 (end-of-defun-function 'markdown-forward-page))
6901 (narrow-to-defun)))
6903 (defun markdown-mark-subtree ()
6904 "Mark the current subtree.
6905 This puts point at the start of the current subtree, and mark at the end."
6906 (interactive)
6907 (let ((beg))
6908 (if (markdown-heading-at-point)
6909 (beginning-of-line)
6910 (markdown-previous-visible-heading 1))
6911 (setq beg (point))
6912 (markdown-end-of-subtree)
6913 (push-mark (point) nil t)
6914 (goto-char beg)))
6916 (defun markdown-narrow-to-subtree ()
6917 "Narrow buffer to the current subtree."
6918 (interactive)
6919 (save-excursion
6920 (save-match-data
6921 (narrow-to-region
6922 (progn (markdown-back-to-heading-over-code-block t) (point))
6923 (progn (markdown-end-of-subtree)
6924 (if (and (markdown-heading-at-point) (not (eobp)))
6925 (backward-char 1))
6926 (point))))))
6929 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
6931 (defun markdown-move-up ()
6932 "Move thing at point up.
6933 When in a list item, call `markdown-move-list-item-up'.
6934 When in a table, call `markdown-table-move-row-up'.
6935 Otherwise, move the current heading subtree up with
6936 `markdown-move-subtree-up'."
6937 (interactive)
6938 (cond
6939 ((markdown-list-item-at-point-p)
6940 (call-interactively #'markdown-move-list-item-up))
6941 ((markdown-table-at-point-p)
6942 (call-interactively #'markdown-table-move-row-up))
6944 (call-interactively #'markdown-move-subtree-up))))
6946 (defun markdown-move-down ()
6947 "Move thing at point down.
6948 When in a list item, call `markdown-move-list-item-down'.
6949 Otherwise, move the current heading subtree up with
6950 `markdown-move-subtree-down'."
6951 (interactive)
6952 (cond
6953 ((markdown-list-item-at-point-p)
6954 (call-interactively #'markdown-move-list-item-down))
6955 ((markdown-table-at-point-p)
6956 (call-interactively #'markdown-table-move-row-down))
6958 (call-interactively #'markdown-move-subtree-down))))
6960 (defun markdown-promote ()
6961 "Promote or move element at point to the left.
6962 Depending on the context, this function will promote a heading or
6963 list item at the point, move a table column to the left, or cycle
6964 markup."
6965 (interactive)
6966 (let (bounds)
6967 (cond
6968 ;; Promote atx heading subtree
6969 ((thing-at-point-looking-at markdown-regex-header-atx)
6970 (markdown-promote-subtree))
6971 ;; Promote setext heading
6972 ((thing-at-point-looking-at markdown-regex-header-setext)
6973 (markdown-cycle-setext -1))
6974 ;; Promote horizonal rule
6975 ((thing-at-point-looking-at markdown-regex-hr)
6976 (markdown-cycle-hr -1))
6977 ;; Promote list item
6978 ((setq bounds (markdown-cur-list-item-bounds))
6979 (markdown-promote-list-item bounds))
6980 ;; Move table column to the left
6981 ((markdown-table-at-point-p)
6982 (call-interactively #'markdown-table-move-column-left))
6983 ;; Promote bold
6984 ((thing-at-point-looking-at markdown-regex-bold)
6985 (markdown-cycle-bold))
6986 ;; Promote italic
6987 ((thing-at-point-looking-at markdown-regex-italic)
6988 (markdown-cycle-italic))
6990 (user-error "Nothing to promote at point")))))
6992 (defun markdown-demote ()
6993 "Demote or move element at point to the right.
6994 Depending on the context, this function will demote a heading or
6995 list item at the point, move a table column to the right, or cycle
6996 or remove markup."
6997 (interactive)
6998 (let (bounds)
6999 (cond
7000 ;; Demote atx heading subtree
7001 ((thing-at-point-looking-at markdown-regex-header-atx)
7002 (markdown-demote-subtree))
7003 ;; Demote setext heading
7004 ((thing-at-point-looking-at markdown-regex-header-setext)
7005 (markdown-cycle-setext 1))
7006 ;; Demote horizonal rule
7007 ((thing-at-point-looking-at markdown-regex-hr)
7008 (markdown-cycle-hr 1))
7009 ;; Demote list item
7010 ((setq bounds (markdown-cur-list-item-bounds))
7011 (markdown-demote-list-item bounds))
7012 ;; Move table column to the right
7013 ((markdown-table-at-point-p)
7014 (call-interactively #'markdown-table-move-column-right))
7015 ;; Demote bold
7016 ((thing-at-point-looking-at markdown-regex-bold)
7017 (markdown-cycle-bold))
7018 ;; Demote italic
7019 ((thing-at-point-looking-at markdown-regex-italic)
7020 (markdown-cycle-italic))
7022 (user-error "Nothing to demote at point")))))
7025 ;;; Commands ==================================================================
7027 (defun markdown (&optional output-buffer-name)
7028 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
7029 The output buffer name defaults to `markdown-output-buffer-name'.
7030 Return the name of the output buffer used."
7031 (interactive)
7032 (save-window-excursion
7033 (let ((begin-region)
7034 (end-region))
7035 (if (markdown-use-region-p)
7036 (setq begin-region (region-beginning)
7037 end-region (region-end))
7038 (setq begin-region (point-min)
7039 end-region (point-max)))
7041 (unless output-buffer-name
7042 (setq output-buffer-name markdown-output-buffer-name))
7043 (cond
7044 ;; Handle case when `markdown-command' does not read from stdin
7045 ((and (stringp markdown-command) markdown-command-needs-filename)
7046 (if (not buffer-file-name)
7047 (user-error "Must be visiting a file")
7048 (shell-command (concat markdown-command " "
7049 (shell-quote-argument buffer-file-name))
7050 output-buffer-name)))
7051 ;; Pass region to `markdown-command' via stdin
7053 (let ((buf (get-buffer-create output-buffer-name)))
7054 (with-current-buffer buf
7055 (setq buffer-read-only nil)
7056 (erase-buffer))
7057 (if (stringp markdown-command)
7058 (call-process-region begin-region end-region
7059 shell-file-name nil buf nil
7060 shell-command-switch markdown-command)
7061 (funcall markdown-command begin-region end-region buf))))))
7062 output-buffer-name))
7064 (defun markdown-standalone (&optional output-buffer-name)
7065 "Special function to provide standalone HTML output.
7066 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
7067 (interactive)
7068 (setq output-buffer-name (markdown output-buffer-name))
7069 (with-current-buffer output-buffer-name
7070 (set-buffer output-buffer-name)
7071 (unless (markdown-output-standalone-p)
7072 (markdown-add-xhtml-header-and-footer output-buffer-name))
7073 (goto-char (point-min))
7074 (html-mode))
7075 output-buffer-name)
7077 (defun markdown-other-window (&optional output-buffer-name)
7078 "Run `markdown-command' on current buffer and display in other window.
7079 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7080 that name."
7081 (interactive)
7082 (markdown-display-buffer-other-window
7083 (markdown-standalone output-buffer-name)))
7085 (defun markdown-output-standalone-p ()
7086 "Determine whether `markdown-command' output is standalone XHTML.
7087 Standalone XHTML output is identified by an occurrence of
7088 `markdown-xhtml-standalone-regexp' in the first five lines of output."
7089 (save-excursion
7090 (goto-char (point-min))
7091 (save-match-data
7092 (re-search-forward
7093 markdown-xhtml-standalone-regexp
7094 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
7095 t))))
7097 (defun markdown-stylesheet-link-string (stylesheet-path)
7098 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
7099 stylesheet-path
7100 "\" />"))
7102 (defun markdown-add-xhtml-header-and-footer (title)
7103 "Wrap XHTML header and footer with given TITLE around current buffer."
7104 (goto-char (point-min))
7105 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
7106 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
7107 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
7108 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
7109 "<head>\n<title>")
7110 (insert title)
7111 (insert "</title>\n")
7112 (when (> (length markdown-content-type) 0)
7113 (insert
7114 (format
7115 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
7116 markdown-content-type
7117 (or (and markdown-coding-system
7118 (fboundp 'coding-system-get)
7119 (coding-system-get markdown-coding-system
7120 'mime-charset))
7121 (and (fboundp 'coding-system-get)
7122 (coding-system-get buffer-file-coding-system
7123 'mime-charset))
7124 "iso-8859-1"))))
7125 (if (> (length markdown-css-paths) 0)
7126 (insert (mapconcat #'markdown-stylesheet-link-string
7127 markdown-css-paths "\n")))
7128 (when (> (length markdown-xhtml-header-content) 0)
7129 (insert markdown-xhtml-header-content))
7130 (insert "\n</head>\n\n"
7131 "<body>\n\n")
7132 (goto-char (point-max))
7133 (insert "\n"
7134 "</body>\n"
7135 "</html>\n"))
7137 (defun markdown-preview (&optional output-buffer-name)
7138 "Run `markdown-command' on the current buffer and view output in browser.
7139 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7140 that name."
7141 (interactive)
7142 (browse-url-of-buffer
7143 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
7145 (defun markdown-export-file-name (&optional extension)
7146 "Attempt to generate a filename for Markdown output.
7147 The file extension will be EXTENSION if given, or .html by default.
7148 If the current buffer is visiting a file, we construct a new
7149 output filename based on that filename. Otherwise, return nil."
7150 (when (buffer-file-name)
7151 (unless extension
7152 (setq extension ".html"))
7153 (let ((candidate
7154 (concat
7155 (cond
7156 ((buffer-file-name)
7157 (file-name-sans-extension (buffer-file-name)))
7158 (t (buffer-name)))
7159 extension)))
7160 (cond
7161 ((equal candidate (buffer-file-name))
7162 (concat candidate extension))
7164 candidate)))))
7166 (defun markdown-export (&optional output-file)
7167 "Run Markdown on the current buffer, save to file, and return the filename.
7168 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
7169 generated by `markdown-export-file-name', which will be constructed using the
7170 current filename, but with the extension removed and replaced with .html."
7171 (interactive)
7172 (unless output-file
7173 (setq output-file (markdown-export-file-name ".html")))
7174 (when output-file
7175 (let* ((init-buf (current-buffer))
7176 (init-point (point))
7177 (init-buf-string (buffer-string))
7178 (output-buffer (find-file-noselect output-file))
7179 (output-buffer-name (buffer-name output-buffer)))
7180 (run-hooks 'markdown-before-export-hook)
7181 (markdown-standalone output-buffer-name)
7182 (with-current-buffer output-buffer
7183 (run-hooks 'markdown-after-export-hook)
7184 (save-buffer)
7185 (when markdown-export-kill-buffer (kill-buffer)))
7186 ;; if modified, restore initial buffer
7187 (when (buffer-modified-p init-buf)
7188 (erase-buffer)
7189 (insert init-buf-string)
7190 (save-buffer)
7191 (goto-char init-point))
7192 output-file)))
7194 (defun markdown-export-and-preview ()
7195 "Export to XHTML using `markdown-export' and browse the resulting file."
7196 (interactive)
7197 (browse-url-of-file (markdown-export)))
7199 (defvar markdown-live-preview-buffer nil
7200 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
7201 (make-variable-buffer-local 'markdown-live-preview-buffer)
7203 (defvar markdown-live-preview-source-buffer nil
7204 "Source buffer from which current buffer was generated.
7205 This is the inverse of `markdown-live-preview-buffer'.")
7206 (make-variable-buffer-local 'markdown-live-preview-source-buffer)
7208 (defvar markdown-live-preview-currently-exporting nil)
7210 (defun markdown-live-preview-get-filename ()
7211 "Standardize the filename exported by `markdown-live-preview-export'."
7212 (markdown-export-file-name ".html"))
7214 (defun markdown-live-preview-window-eww (file)
7215 "Preview FILE with eww.
7216 To be used with `markdown-live-preview-window-function'."
7217 (if (require 'eww nil t)
7218 (progn
7219 (eww-open-file file)
7220 (get-buffer "*eww*"))
7221 (error "EWW is not present or not loaded on this version of Emacs")))
7223 (defun markdown-visual-lines-between-points (beg end)
7224 (save-excursion
7225 (goto-char beg)
7226 (cl-loop with count = 0
7227 while (progn (end-of-visual-line)
7228 (and (< (point) end) (line-move-visual 1 t)))
7229 do (cl-incf count)
7230 finally return count)))
7232 (defun markdown-live-preview-window-serialize (buf)
7233 "Get window point and scroll data for all windows displaying BUF."
7234 (when (buffer-live-p buf)
7235 (with-current-buffer buf
7236 (mapcar
7237 (lambda (win)
7238 (with-selected-window win
7239 (let* ((start (window-start))
7240 (pt (window-point))
7241 (pt-or-sym (cond ((= pt (point-min)) 'min)
7242 ((= pt (point-max)) 'max)
7243 (t pt)))
7244 (diff (markdown-visual-lines-between-points
7245 start pt)))
7246 (list win pt-or-sym diff))))
7247 (get-buffer-window-list buf)))))
7249 (defun markdown-get-point-back-lines (pt num-lines)
7250 (save-excursion
7251 (goto-char pt)
7252 (line-move-visual (- num-lines) t)
7253 ;; in testing, can occasionally overshoot the number of lines to traverse
7254 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
7255 (when (> actual-num-lines num-lines)
7256 (line-move-visual (- actual-num-lines num-lines) t)))
7257 (point)))
7259 (defun markdown-live-preview-window-deserialize (window-posns)
7260 "Apply window point and scroll data from WINDOW-POSNS.
7261 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
7262 (cl-destructuring-bind (win pt-or-sym diff) window-posns
7263 (when (window-live-p win)
7264 (with-current-buffer markdown-live-preview-buffer
7265 (set-window-buffer win (current-buffer))
7266 (cl-destructuring-bind (actual-pt actual-diff)
7267 (cl-case pt-or-sym
7268 (min (list (point-min) 0))
7269 (max (list (point-max) diff))
7270 (t (list pt-or-sym diff)))
7271 (set-window-start
7272 win (markdown-get-point-back-lines actual-pt actual-diff))
7273 (set-window-point win actual-pt))))))
7275 (defun markdown-live-preview-export ()
7276 "Export to XHTML using `markdown-export'.
7277 Browse the resulting file within Emacs using
7278 `markdown-live-preview-window-function' Return the buffer
7279 displaying the rendered output."
7280 (interactive)
7281 (let ((filename (markdown-live-preview-get-filename)))
7282 (when filename
7283 (let* ((markdown-live-preview-currently-exporting t)
7284 (cur-buf (current-buffer))
7285 (export-file (markdown-export filename))
7286 ;; get positions in all windows currently displaying output buffer
7287 (window-data
7288 (markdown-live-preview-window-serialize
7289 markdown-live-preview-buffer)))
7290 (save-window-excursion
7291 (let ((output-buffer
7292 (funcall markdown-live-preview-window-function export-file)))
7293 (with-current-buffer output-buffer
7294 (setq markdown-live-preview-source-buffer cur-buf)
7295 (add-hook 'kill-buffer-hook
7296 #'markdown-live-preview-remove-on-kill t t))
7297 (with-current-buffer cur-buf
7298 (setq markdown-live-preview-buffer output-buffer))))
7299 (with-current-buffer cur-buf
7300 ;; reset all windows displaying output buffer to where they were,
7301 ;; now with the new output
7302 (mapc #'markdown-live-preview-window-deserialize window-data)
7303 ;; delete html editing buffer
7304 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
7305 (when (and export-file (file-exists-p export-file)
7306 (eq markdown-live-preview-delete-export
7307 'delete-on-export))
7308 (delete-file export-file))
7309 markdown-live-preview-buffer)))))
7311 (defun markdown-live-preview-remove ()
7312 (when (buffer-live-p markdown-live-preview-buffer)
7313 (kill-buffer markdown-live-preview-buffer))
7314 (setq markdown-live-preview-buffer nil)
7315 ;; if set to 'delete-on-export, the output has already been deleted
7316 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
7317 (let ((outfile-name (markdown-live-preview-get-filename)))
7318 (when (and outfile-name (file-exists-p outfile-name))
7319 (delete-file outfile-name)))))
7321 (defun markdown-get-other-window ()
7322 "Find another window to display preview or output content."
7323 (cond
7324 ((memq markdown-split-window-direction '(vertical below))
7325 (or (window-in-direction 'below) (split-window-vertically)))
7326 ((memq markdown-split-window-direction '(horizontal right))
7327 (or (window-in-direction 'right) (split-window-horizontally)))
7328 (t (split-window-sensibly (get-buffer-window)))))
7330 (defun markdown-display-buffer-other-window (buf)
7331 "Display preview or output buffer BUF in another window."
7332 (let ((cur-buf (current-buffer))
7333 (window (markdown-get-other-window)))
7334 (set-window-buffer window buf)
7335 (set-buffer cur-buf)))
7337 (defun markdown-live-preview-if-markdown ()
7338 (when (and (derived-mode-p 'markdown-mode)
7339 markdown-live-preview-mode)
7340 (unless markdown-live-preview-currently-exporting
7341 (if (buffer-live-p markdown-live-preview-buffer)
7342 (markdown-live-preview-export)
7343 (markdown-display-buffer-other-window
7344 (markdown-live-preview-export))))))
7346 (defun markdown-live-preview-remove-on-kill ()
7347 (cond ((and (derived-mode-p 'markdown-mode)
7348 markdown-live-preview-mode)
7349 (markdown-live-preview-remove))
7350 (markdown-live-preview-source-buffer
7351 (with-current-buffer markdown-live-preview-source-buffer
7352 (setq markdown-live-preview-buffer nil))
7353 (setq markdown-live-preview-source-buffer nil))))
7355 (defun markdown-live-preview-switch-to-output ()
7356 "Switch to output buffer."
7357 (interactive)
7358 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
7359 output buffer in another window."
7360 (if markdown-live-preview-mode
7361 (markdown-display-buffer-other-window (markdown-live-preview-export)))
7362 (markdown-live-preview-mode))
7364 (defun markdown-live-preview-re-export ()
7365 "Re export source buffer."
7366 (interactive)
7367 "If the current buffer is a buffer displaying the exported version of a
7368 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
7369 update this buffer's contents."
7370 (when markdown-live-preview-source-buffer
7371 (with-current-buffer markdown-live-preview-source-buffer
7372 (markdown-live-preview-export))))
7374 (defun markdown-open ()
7375 "Open file for the current buffer with `markdown-open-command'."
7376 (interactive)
7377 (unless markdown-open-command
7378 (user-error "Variable `markdown-open-command' must be set"))
7379 (if (stringp markdown-open-command)
7380 (if (not buffer-file-name)
7381 (user-error "Must be visiting a file")
7382 (save-buffer)
7383 (call-process markdown-open-command nil 0 nil buffer-file-name))
7384 (funcall markdown-open-command))
7385 nil)
7387 (defun markdown-kill-ring-save ()
7388 "Run Markdown on file and store output in the kill ring."
7389 (interactive)
7390 (save-window-excursion
7391 (markdown)
7392 (with-current-buffer markdown-output-buffer-name
7393 (kill-ring-save (point-min) (point-max)))))
7396 ;;; Links =====================================================================
7398 (defun markdown-link-p ()
7399 "Return non-nil when `point' is at a non-wiki link.
7400 See `markdown-wiki-link-p' for more information."
7401 (let ((case-fold-search nil))
7402 (and (not (markdown-wiki-link-p))
7403 (not (markdown-code-block-at-point-p))
7404 (or (thing-at-point-looking-at markdown-regex-link-inline)
7405 (thing-at-point-looking-at markdown-regex-link-reference)
7406 (thing-at-point-looking-at markdown-regex-uri)
7407 (thing-at-point-looking-at markdown-regex-angle-uri)))))
7409 (make-obsolete 'markdown-link-link 'markdown-link-url "v2.3")
7411 (defun markdown-link-at-pos (pos)
7412 "Return properties of link or image at position POS.
7413 Value is a list of elements describing the link:
7414 0. beginning position
7415 1. end position
7416 2. link text
7417 3. URL
7418 4. reference label
7419 5. title text
7420 6. bang (nil or \"!\")"
7421 (save-excursion
7422 (goto-char pos)
7423 (let (begin end text url reference title bang)
7424 (cond
7425 ;; Inline or reference image or link at point.
7426 ((or (thing-at-point-looking-at markdown-regex-link-inline)
7427 (thing-at-point-looking-at markdown-regex-link-reference))
7428 (setq bang (match-string-no-properties 1)
7429 begin (match-beginning 0)
7430 end (match-end 0)
7431 text (match-string-no-properties 3))
7432 (if (char-equal (char-after (match-beginning 5)) ?\[)
7433 ;; Reference link
7434 (setq reference (match-string-no-properties 6))
7435 ;; Inline link
7436 (setq url (match-string-no-properties 6))
7437 (when (match-end 7)
7438 (setq title (substring (match-string-no-properties 7) 1 -1)))))
7439 ;; Angle bracket URI at point.
7440 ((thing-at-point-looking-at markdown-regex-angle-uri)
7441 (setq begin (match-beginning 0)
7442 end (match-end 0)
7443 url (match-string-no-properties 2)))
7444 ;; Plain URI at point.
7445 ((thing-at-point-looking-at markdown-regex-uri)
7446 (setq begin (match-beginning 0)
7447 end (match-end 0)
7448 url (match-string-no-properties 1))))
7449 (list begin end text url reference title bang))))
7451 (defun markdown-link-url ()
7452 "Return the URL part of the regular (non-wiki) link at point.
7453 Works with both inline and reference style links, and with images.
7454 If point is not at a link or the link reference is not defined
7455 returns nil."
7456 (let* ((values (markdown-link-at-pos (point)))
7457 (text (nth 2 values))
7458 (url (nth 3 values))
7459 (ref (nth 4 values)))
7460 (or url (and ref (car (markdown-reference-definition
7461 (downcase (if (string= ref "") text ref))))))))
7463 (defun markdown-follow-link-at-point ()
7464 "Open the current non-wiki link.
7465 If the link is a complete URL, open in browser with `browse-url'.
7466 Otherwise, open with `find-file' after stripping anchor and/or query string.
7467 Translate filenames using `markdown-filename-translate-function'."
7468 (interactive)
7469 (if (markdown-link-p)
7470 (let* ((url (markdown-link-url))
7471 (struct (url-generic-parse-url url))
7472 (full (url-fullness struct))
7473 (file url))
7474 ;; Parse URL, determine fullness, strip query string
7475 (if (fboundp 'url-path-and-query)
7476 (setq file (car (url-path-and-query struct)))
7477 (when (and (setq file (url-filename struct))
7478 (string-match "\\?" file))
7479 (setq file (substring file 0 (match-beginning 0)))))
7480 ;; Open full URLs in browser, files in Emacs
7481 (if full
7482 (browse-url url)
7483 (when (and file (> (length file) 0))
7484 (find-file (funcall markdown-translate-filename-function file)))))
7485 (user-error "Point is not at a Markdown link or URL")))
7487 (defun markdown-fontify-inline-links (last)
7488 "Add text properties to next inline link from point to LAST."
7489 (when (markdown-match-generic-links last nil)
7490 (let* ((link-start (match-beginning 3))
7491 (link-end (match-end 3))
7492 (url-start (match-beginning 6))
7493 (url-end (match-end 6))
7494 (url (match-string-no-properties 6))
7495 (title-start (match-beginning 7))
7496 (title-end (match-end 7))
7497 (title (match-string-no-properties 7))
7498 ;; Markup part
7499 (mp (list 'face 'markdown-markup-face
7500 'invisible 'markdown-markup
7501 'rear-nonsticky t
7502 'font-lock-multiline t))
7503 ;; Link part
7504 (lp (list 'keymap markdown-mode-mouse-map
7505 'face 'markdown-link-face
7506 'mouse-face 'markdown-highlight-face
7507 'font-lock-multiline t
7508 'help-echo (if title (concat title "\n" url) url)))
7509 ;; URL part
7510 (up (list 'keymap markdown-mode-mouse-map
7511 'face 'markdown-url-face
7512 'invisible 'markdown-markup
7513 'mouse-face 'markdown-highlight-face
7514 'font-lock-multiline t))
7515 ;; URL composition character
7516 (url-char (markdown--first-displayable markdown-url-compose-char))
7517 ;; Title part
7518 (tp (list 'face 'markdown-link-title-face
7519 'invisible 'markdown-markup
7520 'font-lock-multiline t)))
7521 (dolist (g '(1 2 4 5 8))
7522 (when (match-end g)
7523 (add-text-properties (match-beginning g) (match-end g) mp)))
7524 (when link-start (add-text-properties link-start link-end lp))
7525 (when url-start (add-text-properties url-start url-end up))
7526 (when title-start (add-text-properties url-end title-end tp))
7527 (when (and markdown-hide-urls url-start)
7528 (compose-region url-start (or title-end url-end) url-char))
7529 t)))
7531 (defun markdown-fontify-reference-links (last)
7532 "Add text properties to next reference link from point to LAST."
7533 (when (markdown-match-generic-links last t)
7534 (let* ((link-start (match-beginning 3))
7535 (link-end (match-end 3))
7536 (ref-start (match-beginning 6))
7537 (ref-end (match-end 6))
7538 ;; Markup part
7539 (mp (list 'face 'markdown-markup-face
7540 'invisible 'markdown-markup
7541 'rear-nonsticky t
7542 'font-lock-multiline t))
7543 ;; Link part
7544 (lp (list 'keymap markdown-mode-mouse-map
7545 'face 'markdown-link-face
7546 'mouse-face 'markdown-highlight-face
7547 'font-lock-multiline t
7548 'help-echo (lambda (_ __ pos)
7549 (save-match-data
7550 (save-excursion
7551 (goto-char pos)
7552 (or (markdown-link-url)
7553 "Undefined reference"))))))
7554 ;; URL composition character
7555 (url-char (markdown--first-displayable markdown-url-compose-char))
7556 ;; Reference part
7557 (rp (list 'face 'markdown-reference-face
7558 'invisible 'markdown-markup
7559 'font-lock-multiline t)))
7560 (dolist (g '(1 2 4 5 8))
7561 (when (match-end g)
7562 (add-text-properties (match-beginning g) (match-end g) mp)))
7563 (when link-start (add-text-properties link-start link-end lp))
7564 (when ref-start (add-text-properties ref-start ref-end rp)
7565 (when (and markdown-hide-urls (> (- ref-end ref-start) 2))
7566 (compose-region ref-start ref-end url-char)))
7567 t)))
7569 (defun markdown-fontify-angle-uris (last)
7570 "Add text properties to angle URIs from point to LAST."
7571 (when (markdown-match-angle-uris last)
7572 (let* ((url-start (match-beginning 2))
7573 (url-end (match-end 2))
7574 ;; Markup part
7575 (mp (list 'face 'markdown-markup-face
7576 'invisible 'markdown-markup
7577 'rear-nonsticky t
7578 'font-lock-multiline t))
7579 ;; URI part
7580 (up (list 'keymap markdown-mode-mouse-map
7581 'face 'markdown-plain-url-face
7582 'mouse-face 'markdown-highlight-face
7583 'font-lock-multiline t)))
7584 (dolist (g '(1 3))
7585 (add-text-properties (match-beginning g) (match-end g) mp))
7586 (add-text-properties url-start url-end up)
7587 t)))
7589 (defun markdown-fontify-plain-uris (last)
7590 "Add text properties to plain URLs from point to LAST."
7591 (when (markdown-match-plain-uris last)
7592 (let* ((start (match-beginning 0))
7593 (end (match-end 0))
7594 (props (list 'keymap markdown-mode-mouse-map
7595 'face 'markdown-plain-url-face
7596 'mouse-face 'markdown-highlight-face
7597 'rear-nonsticky t
7598 'font-lock-multiline t)))
7599 (add-text-properties start end props)
7600 t)))
7602 (defun markdown-toggle-url-hiding (&optional arg)
7603 "Toggle the display or hiding of URLs.
7604 With a prefix argument ARG, enable URL hiding if ARG is positive,
7605 and disable it otherwise."
7606 (interactive (list (or current-prefix-arg 'toggle)))
7607 (setq markdown-hide-urls
7608 (if (eq arg 'toggle)
7609 (not markdown-hide-urls)
7610 (> (prefix-numeric-value arg) 0)))
7611 (if markdown-hide-urls
7612 (message "markdown-mode URL hiding enabled")
7613 (message "markdown-mode URL hiding disabled"))
7614 (markdown-reload-extensions))
7617 ;;; WikiLink Following/Markup =================================================
7619 (defun markdown-wiki-link-p ()
7620 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
7621 A true wiki link name matches `markdown-regex-wiki-link' but does
7622 not match the current file name after conversion. This modifies
7623 the data returned by `match-data'. Note that the potential wiki
7624 link name must be available via `match-string'."
7625 (when markdown-enable-wiki-links
7626 (let ((case-fold-search nil))
7627 (and (thing-at-point-looking-at markdown-regex-wiki-link)
7628 (not (markdown-code-block-at-point-p))
7629 (or (not buffer-file-name)
7630 (not (string-equal (buffer-file-name)
7631 (markdown-convert-wiki-link-to-filename
7632 (markdown-wiki-link-link)))))))))
7634 (defun markdown-wiki-link-link ()
7635 "Return the link part of the wiki link using current match data.
7636 The location of the link component depends on the value of
7637 `markdown-wiki-link-alias-first'."
7638 (if markdown-wiki-link-alias-first
7639 (or (match-string-no-properties 5) (match-string-no-properties 3))
7640 (match-string-no-properties 3)))
7642 (defun markdown-wiki-link-alias ()
7643 "Return the alias or text part of the wiki link using current match data.
7644 The location of the alias component depends on the value of
7645 `markdown-wiki-link-alias-first'."
7646 (if markdown-wiki-link-alias-first
7647 (match-string-no-properties 3)
7648 (or (match-string-no-properties 5) (match-string-no-properties 3))))
7650 (defun markdown-convert-wiki-link-to-filename (name)
7651 "Generate a filename from the wiki link NAME.
7652 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
7653 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
7654 and [[test test]] both map to Test-test.ext. Look in the current
7655 directory first, then in subdirectories if
7656 `markdown-wiki-link-search-subdirectories' is non-nil, and then
7657 in parent directories if
7658 `markdown-wiki-link-search-parent-directories' is non-nil."
7659 (let* ((basename (markdown-replace-regexp-in-string
7660 "[[:space:]\n]" markdown-link-space-sub-char name))
7661 (basename (if (eq major-mode '(gfm-mode gfm-view-mode))
7662 (concat (upcase (substring basename 0 1))
7663 (downcase (substring basename 1 nil)))
7664 basename))
7665 directory extension default candidates dir)
7666 (when buffer-file-name
7667 (setq directory (file-name-directory buffer-file-name)
7668 extension (file-name-extension buffer-file-name)))
7669 (setq default (concat basename
7670 (when extension (concat "." extension))))
7671 (cond
7672 ;; Look in current directory first.
7673 ((or (null buffer-file-name)
7674 (file-exists-p default))
7675 default)
7676 ;; Possibly search in subdirectories, next.
7677 ((and markdown-wiki-link-search-subdirectories
7678 (setq candidates
7679 (markdown-directory-files-recursively
7680 directory (concat "^" default "$"))))
7681 (car candidates))
7682 ;; Possibly search in parent directories as a last resort.
7683 ((and markdown-wiki-link-search-parent-directories
7684 (setq dir (locate-dominating-file directory default)))
7685 (concat dir default))
7686 ;; If nothing is found, return default in current directory.
7687 (t default))))
7689 (defun markdown-follow-wiki-link (name &optional other)
7690 "Follow the wiki link NAME.
7691 Convert the name to a file name and call `find-file'. Ensure that
7692 the new buffer remains in `markdown-mode'. Open the link in another
7693 window when OTHER is non-nil."
7694 (let ((filename (markdown-convert-wiki-link-to-filename name))
7695 (wp (when buffer-file-name
7696 (file-name-directory buffer-file-name))))
7697 (if (not wp)
7698 (user-error "Must be visiting a file")
7699 (when other (other-window 1))
7700 (let ((default-directory wp))
7701 (find-file filename)))
7702 (when (not (eq major-mode 'markdown-mode))
7703 (markdown-mode))))
7705 (defun markdown-follow-wiki-link-at-point (&optional arg)
7706 "Find Wiki Link at point.
7707 With prefix argument ARG, open the file in other window.
7708 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
7709 (interactive "P")
7710 (if (markdown-wiki-link-p)
7711 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
7712 (user-error "Point is not at a Wiki Link")))
7714 (defun markdown-highlight-wiki-link (from to face)
7715 "Highlight the wiki link in the region between FROM and TO using FACE."
7716 (put-text-property from to 'font-lock-face face))
7718 (defun markdown-unfontify-region-wiki-links (from to)
7719 "Remove wiki link faces from the region specified by FROM and TO."
7720 (interactive "*r")
7721 (let ((modified (buffer-modified-p)))
7722 (remove-text-properties from to '(font-lock-face markdown-link-face))
7723 (remove-text-properties from to '(font-lock-face markdown-missing-link-face))
7724 ;; remove-text-properties marks the buffer modified in emacs 24.3,
7725 ;; undo that if it wasn't originally marked modified
7726 (set-buffer-modified-p modified)))
7728 (defun markdown-fontify-region-wiki-links (from to)
7729 "Search region given by FROM and TO for wiki links and fontify them.
7730 If a wiki link is found check to see if the backing file exists
7731 and highlight accordingly."
7732 (goto-char from)
7733 (save-match-data
7734 (while (re-search-forward markdown-regex-wiki-link to t)
7735 (when (not (markdown-code-block-at-point-p))
7736 (let ((highlight-beginning (match-beginning 1))
7737 (highlight-end (match-end 1))
7738 (file-name
7739 (markdown-convert-wiki-link-to-filename
7740 (markdown-wiki-link-link))))
7741 (if (condition-case nil (file-exists-p file-name) (error nil))
7742 (markdown-highlight-wiki-link
7743 highlight-beginning highlight-end 'markdown-link-face)
7744 (markdown-highlight-wiki-link
7745 highlight-beginning highlight-end 'markdown-missing-link-face)))))))
7747 (defun markdown-extend-changed-region (from to)
7748 "Extend region given by FROM and TO so that we can fontify all links.
7749 The region is extended to the first newline before and the first
7750 newline after."
7751 ;; start looking for the first new line before 'from
7752 (goto-char from)
7753 (re-search-backward "\n" nil t)
7754 (let ((new-from (point-min))
7755 (new-to (point-max)))
7756 (if (not (= (point) from))
7757 (setq new-from (point)))
7758 ;; do the same thing for the first new line after 'to
7759 (goto-char to)
7760 (re-search-forward "\n" nil t)
7761 (if (not (= (point) to))
7762 (setq new-to (point)))
7763 (cl-values new-from new-to)))
7765 (defun markdown-check-change-for-wiki-link (from to)
7766 "Check region between FROM and TO for wiki links and re-fontify as needed."
7767 (interactive "*r")
7768 (let* ((modified (buffer-modified-p))
7769 (buffer-undo-list t)
7770 (inhibit-read-only t)
7771 (inhibit-point-motion-hooks t)
7772 deactivate-mark
7773 buffer-file-truename)
7774 (unwind-protect
7775 (save-excursion
7776 (save-match-data
7777 (save-restriction
7778 ;; Extend the region to fontify so that it starts
7779 ;; and ends at safe places.
7780 (cl-multiple-value-bind (new-from new-to)
7781 (markdown-extend-changed-region from to)
7782 (goto-char new-from)
7783 ;; Only refontify when the range contains text with a
7784 ;; wiki link face or if the wiki link regexp matches.
7785 (when (or (markdown-range-property-any
7786 new-from new-to 'font-lock-face
7787 '(markdown-link-face markdown-missing-link-face))
7788 (re-search-forward
7789 markdown-regex-wiki-link new-to t))
7790 ;; Unfontify existing fontification (start from scratch)
7791 (markdown-unfontify-region-wiki-links new-from new-to)
7792 ;; Now do the fontification.
7793 (markdown-fontify-region-wiki-links new-from new-to))))))
7794 (and (not modified)
7795 (buffer-modified-p)
7796 (set-buffer-modified-p nil)))))
7798 (defun markdown-check-change-for-wiki-link-after-change (from to _)
7799 "Check region between FROM and TO for wiki links and re-fontify as needed.
7800 Designed to be used with the `after-change-functions' hook."
7801 (markdown-check-change-for-wiki-link from to))
7803 (defun markdown-fontify-buffer-wiki-links ()
7804 "Refontify all wiki links in the buffer."
7805 (interactive)
7806 (markdown-check-change-for-wiki-link (point-min) (point-max)))
7809 ;;; Following & Doing =========================================================
7811 (defun markdown-follow-thing-at-point (arg)
7812 "Follow thing at point if possible, such as a reference link or wiki link.
7813 Opens inline and reference links in a browser. Opens wiki links
7814 to other files in the current window, or the another window if
7815 ARG is non-nil.
7816 See `markdown-follow-link-at-point' and
7817 `markdown-follow-wiki-link-at-point'."
7818 (interactive "P")
7819 (cond ((markdown-link-p)
7820 (markdown-follow-link-at-point))
7821 ((markdown-wiki-link-p)
7822 (markdown-follow-wiki-link-at-point arg))
7824 (user-error "Nothing to follow at point"))))
7826 (make-obsolete 'markdown-jump 'markdown-do "v2.3")
7828 (defun markdown-do ()
7829 "Do something sensible based on context at point.
7830 Jumps between reference links and definitions; between footnote
7831 markers and footnote text."
7832 (interactive)
7833 (cond
7834 ;; Footnote definition
7835 ((markdown-footnote-text-positions)
7836 (markdown-footnote-return))
7837 ;; Footnote marker
7838 ((markdown-footnote-marker-positions)
7839 (markdown-footnote-goto-text))
7840 ;; Reference link
7841 ((thing-at-point-looking-at markdown-regex-link-reference)
7842 (markdown-reference-goto-definition))
7843 ;; Reference definition
7844 ((thing-at-point-looking-at markdown-regex-reference-definition)
7845 (markdown-reference-goto-link (match-string-no-properties 2)))
7846 ;; GFM task list item
7847 ((markdown-gfm-task-list-item-at-point)
7848 (markdown-toggle-gfm-checkbox))
7849 ;; Align table
7850 ((markdown-table-at-point-p)
7851 (call-interactively #'markdown-table-align))
7852 ;; Otherwise
7854 (markdown-insert-gfm-checkbox))))
7857 ;;; Miscellaneous =============================================================
7859 (defun markdown-compress-whitespace-string (str)
7860 "Compress whitespace in STR and return result.
7861 Leading and trailing whitespace is removed. Sequences of multiple
7862 spaces, tabs, and newlines are replaced with single spaces."
7863 (markdown-replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
7864 (markdown-replace-regexp-in-string "[ \t\n]+" " " str)))
7866 (defun markdown--substitute-command-keys (string)
7867 "Like `substitute-command-keys' but, but prefers control characters.
7868 First pass STRING to `substitute-command-keys' and then
7869 substitute `C-i` for `TAB` and `C-m` for `RET`."
7870 (replace-regexp-in-string
7871 "\\<TAB\\>" "C-i"
7872 (replace-regexp-in-string
7873 "\\<RET\\>" "C-m" (substitute-command-keys string) t) t))
7875 (defun markdown-line-number-at-pos (&optional pos)
7876 "Return (narrowed) buffer line number at position POS.
7877 If POS is nil, use current buffer location.
7878 This is an exact copy of `line-number-at-pos' for use in emacs21."
7879 (let ((opoint (or pos (point))) start)
7880 (save-excursion
7881 (goto-char (point-min))
7882 (setq start (point))
7883 (goto-char opoint)
7884 (forward-line 0)
7885 (1+ (count-lines start (point))))))
7887 (defun markdown-inside-link-p ()
7888 "Return t if point is within a link."
7889 (save-match-data
7890 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
7892 (defun markdown-line-is-reference-definition-p ()
7893 "Return whether the current line is a (non-footnote) reference defition."
7894 (save-excursion
7895 (move-beginning-of-line 1)
7896 (and (looking-at-p markdown-regex-reference-definition)
7897 (not (looking-at-p "[ \t]*\\[^")))))
7899 (defun markdown-adaptive-fill-function ()
7900 "Return prefix for filling paragraph or nil if not determined."
7901 (cond
7902 ;; List item inside blockquote
7903 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
7904 (markdown-replace-regexp-in-string
7905 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
7906 ;; Blockquote
7907 ((looking-at markdown-regex-blockquote)
7908 (buffer-substring-no-properties (match-beginning 0) (match-end 2)))
7909 ;; List items
7910 ((looking-at markdown-regex-list)
7911 (match-string-no-properties 0))
7912 ;; Footnote definition
7913 ((looking-at-p markdown-regex-footnote-definition)
7914 " ") ; four spaces
7915 ;; No match
7916 (t nil)))
7918 (defun markdown-fill-paragraph (&optional justify)
7919 "Fill paragraph at or after point.
7920 This function is like \\[fill-paragraph], but it skips Markdown
7921 code blocks. If the point is in a code block, or just before one,
7922 do not fill. Otherwise, call `fill-paragraph' as usual. If
7923 JUSTIFY is non-nil, justify text as well. Since this function
7924 handles filling itself, it always returns t so that
7925 `fill-paragraph' doesn't run."
7926 (interactive "P")
7927 (unless (or (markdown-code-block-at-point-p)
7928 (save-excursion
7929 (back-to-indentation)
7930 (skip-syntax-forward "-")
7931 (markdown-code-block-at-point-p)))
7932 (fill-paragraph justify))
7935 (make-obsolete 'markdown-fill-forward-paragraph-function
7936 'markdown-fill-forward-paragraph "v2.3")
7938 (defun markdown-fill-forward-paragraph (&optional arg)
7939 "Function used by `fill-paragraph' to move over ARG paragraphs.
7940 This is a `fill-forward-paragraph-function' for `markdown-mode'.
7941 It is called with a single argument specifying the number of
7942 paragraphs to move. Just like `forward-paragraph', it should
7943 return the number of paragraphs left to move."
7944 (or arg (setq arg 1))
7945 (if (> arg 0)
7946 ;; With positive ARG, move across ARG non-code-block paragraphs,
7947 ;; one at a time. When passing a code block, don't decrement ARG.
7948 (while (and (not (eobp))
7949 (> arg 0)
7950 (= (forward-paragraph 1) 0)
7951 (or (markdown-code-block-at-pos (point-at-bol 0))
7952 (setq arg (1- arg)))))
7953 ;; Move backward by one paragraph with negative ARG (always -1).
7954 (let ((start (point)))
7955 (setq arg (forward-paragraph arg))
7956 (while (and (not (eobp))
7957 (progn (move-to-left-margin) (not (eobp)))
7958 (looking-at-p paragraph-separate))
7959 (forward-line 1))
7960 (cond
7961 ;; Move point past whitespace following list marker.
7962 ((looking-at markdown-regex-list)
7963 (goto-char (match-end 0)))
7964 ;; Move point past whitespace following pipe at beginning of line
7965 ;; to handle Pandoc line blocks.
7966 ((looking-at "^|\\s-*")
7967 (goto-char (match-end 0)))
7968 ;; Return point if the paragraph passed was a code block.
7969 ((markdown-code-block-at-pos (point-at-bol 2))
7970 (goto-char start)))))
7971 arg)
7973 (defun markdown--inhibit-electric-quote ()
7974 "Function added to `electric-quote-inhibit-functions'.
7975 Return non-nil if the quote has been inserted inside a code block
7976 or span."
7977 (let ((pos (1- (point))))
7978 (or (markdown-inline-code-at-pos pos)
7979 (markdown-code-block-at-pos pos))))
7982 ;;; Extension Framework =======================================================
7984 (defun markdown-reload-extensions ()
7985 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
7986 (interactive)
7987 (when (member major-mode
7988 '(markdown-mode markdown-view-mode gfm-mode gfm-view-mode))
7989 ;; Refontify buffer
7990 (if (eval-when-compile (fboundp 'font-lock-flush))
7991 ;; Use font-lock-flush in Emacs >= 25.1
7992 (font-lock-flush)
7993 ;; Backwards compatibility for Emacs 24.3-24.5
7994 (when (and font-lock-mode (fboundp 'font-lock-refresh-defaults))
7995 (font-lock-refresh-defaults)))
7996 ;; Add or remove hooks related to extensions
7997 (markdown-setup-wiki-link-hooks)))
7999 (defun markdown-handle-local-variables ()
8000 "Run in `hack-local-variables-hook' to update font lock rules.
8001 Checks to see if there is actually a ‘markdown-mode’ file local variable
8002 before regenerating font-lock rules for extensions."
8003 (when (and (boundp 'file-local-variables-alist)
8004 (or (assoc 'markdown-enable-wiki-links file-local-variables-alist)
8005 (assoc 'markdown-enable-math file-local-variables-alist)))
8006 (when (assoc 'markdown-enable-math file-local-variables-alist)
8007 (markdown-toggle-math markdown-enable-math))
8008 (markdown-reload-extensions)))
8011 ;;; Wiki Links ================================================================
8013 (defun markdown-toggle-wiki-links (&optional arg)
8014 "Toggle support for wiki links.
8015 With a prefix argument ARG, enable wiki link support if ARG is positive,
8016 and disable it otherwise."
8017 (interactive (list (or current-prefix-arg 'toggle)))
8018 (setq markdown-enable-wiki-links
8019 (if (eq arg 'toggle)
8020 (not markdown-enable-wiki-links)
8021 (> (prefix-numeric-value arg) 0)))
8022 (if markdown-enable-wiki-links
8023 (message "markdown-mode wiki link support enabled")
8024 (message "markdown-mode wiki link support disabled"))
8025 (markdown-reload-extensions))
8027 (defun markdown-setup-wiki-link-hooks ()
8028 "Add or remove hooks for fontifying wiki links.
8029 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
8030 ;; Anytime text changes make sure it gets fontified correctly
8031 (if (and markdown-enable-wiki-links
8032 markdown-wiki-link-fontify-missing)
8033 (add-hook 'after-change-functions
8034 'markdown-check-change-for-wiki-link-after-change t t)
8035 (remove-hook 'after-change-functions
8036 'markdown-check-change-for-wiki-link-after-change t))
8037 ;; If we left the buffer there is a really good chance we were
8038 ;; creating one of the wiki link documents. Make sure we get
8039 ;; refontified when we come back.
8040 (if (and markdown-enable-wiki-links
8041 markdown-wiki-link-fontify-missing)
8042 (progn
8043 (add-hook 'window-configuration-change-hook
8044 'markdown-fontify-buffer-wiki-links t t)
8045 (markdown-fontify-buffer-wiki-links))
8046 (remove-hook 'window-configuration-change-hook
8047 'markdown-fontify-buffer-wiki-links t)
8048 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
8051 ;;; Math Support ==============================================================
8053 (make-obsolete 'markdown-enable-math 'markdown-toggle-math "v2.1")
8055 (defconst markdown-mode-font-lock-keywords-math
8056 (list
8057 ;; Equation reference (eq:foo)
8058 '("\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" . ((1 markdown-markup-face)
8059 (2 markdown-reference-face)
8060 (3 markdown-markup-face)))
8061 ;; Equation reference \eqref{foo}
8062 '("\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" . ((1 markdown-markup-face)
8063 (2 markdown-reference-face)
8064 (3 markdown-markup-face))))
8065 "Font lock keywords to add and remove when toggling math support.")
8067 (defun markdown-toggle-math (&optional arg)
8068 "Toggle support for inline and display LaTeX math expressions.
8069 With a prefix argument ARG, enable math mode if ARG is positive,
8070 and disable it otherwise. If called from Lisp, enable the mode
8071 if ARG is omitted or nil."
8072 (interactive (list (or current-prefix-arg 'toggle)))
8073 (setq markdown-enable-math
8074 (if (eq arg 'toggle)
8075 (not markdown-enable-math)
8076 (> (prefix-numeric-value arg) 0)))
8077 (if markdown-enable-math
8078 (progn
8079 (font-lock-add-keywords
8080 'markdown-mode markdown-mode-font-lock-keywords-math)
8081 (message "markdown-mode math support enabled"))
8082 (font-lock-remove-keywords
8083 'markdown-mode markdown-mode-font-lock-keywords-math)
8084 (message "markdown-mode math support disabled"))
8085 (markdown-reload-extensions))
8088 ;;; GFM Checkboxes ============================================================
8090 (define-button-type 'markdown-gfm-checkbox-button
8091 'follow-link t
8092 'face 'markdown-gfm-checkbox-face
8093 'mouse-face 'markdown-highlight-face
8094 'action #'markdown-toggle-gfm-checkbox-button)
8096 (defun markdown-gfm-task-list-item-at-point (&optional bounds)
8097 "Return non-nil if there is a GFM task list item at the point.
8098 Optionally, the list item BOUNDS may be given if available, as
8099 returned by `markdown-cur-list-item-bounds'. When a task list item
8100 is found, the return value is the same value returned by
8101 `markdown-cur-list-item-bounds'."
8102 (unless bounds
8103 (setq bounds (markdown-cur-list-item-bounds)))
8104 (> (length (nth 5 bounds)) 0))
8106 (defun markdown-insert-gfm-checkbox ()
8107 "Add GFM checkbox at point.
8108 Returns t if added.
8109 Returns nil if non-applicable."
8110 (interactive)
8111 (let ((bounds (markdown-cur-list-item-bounds)))
8112 (if bounds
8113 (unless (cl-sixth bounds)
8114 (let ((pos (+ (cl-first bounds) (cl-fourth bounds)))
8115 (markup "[ ] "))
8116 (if (< pos (point))
8117 (save-excursion
8118 (goto-char pos)
8119 (insert markup))
8120 (goto-char pos)
8121 (insert markup))
8122 (syntax-propertize (+ (cl-second bounds) 4))
8124 (unless (save-excursion
8125 (back-to-indentation)
8126 (or (markdown-list-item-at-point-p)
8127 (markdown-heading-at-point)
8128 (markdown-in-comment-p)
8129 (markdown-code-block-at-point-p)))
8130 (let ((pos (save-excursion
8131 (back-to-indentation)
8132 (point)))
8133 (markup (concat (or (save-excursion
8134 (beginning-of-line 0)
8135 (cl-fifth (markdown-cur-list-item-bounds)))
8136 markdown-unordered-list-item-prefix)
8137 "[ ] ")))
8138 (if (< pos (point))
8139 (save-excursion
8140 (goto-char pos)
8141 (insert markup))
8142 (goto-char pos)
8143 (insert markup))
8144 (syntax-propertize (point-at-eol))
8145 t)))))
8147 (defun markdown-toggle-gfm-checkbox ()
8148 "Toggle GFM checkbox at point.
8149 Returns the resulting status as a string, either \"[x]\" or \"[ ]\".
8150 Returns nil if there is no task list item at the point."
8151 (interactive)
8152 (save-match-data
8153 (save-excursion
8154 (let ((bounds (markdown-cur-list-item-bounds)))
8155 (when bounds
8156 ;; Move to beginning of task list item
8157 (goto-char (cl-first bounds))
8158 ;; Advance to column of first non-whitespace after marker
8159 (forward-char (cl-fourth bounds))
8160 (cond ((looking-at "\\[ \\]")
8161 (replace-match
8162 (if markdown-gfm-uppercase-checkbox "[X]" "[x]")
8163 nil t)
8164 (match-string-no-properties 0))
8165 ((looking-at "\\[[xX]\\]")
8166 (replace-match "[ ]" nil t)
8167 (match-string-no-properties 0))))))))
8169 (defun markdown-toggle-gfm-checkbox-button (button)
8170 "Toggle GFM checkbox BUTTON on click."
8171 (save-match-data
8172 (save-excursion
8173 (goto-char (button-start button))
8174 (markdown-toggle-gfm-checkbox))))
8176 (defun markdown-make-gfm-checkboxes-buttons (start end)
8177 "Make GFM checkboxes buttons in region between START and END."
8178 (save-excursion
8179 (goto-char start)
8180 (let ((case-fold-search t))
8181 (save-excursion
8182 (while (re-search-forward markdown-regex-gfm-checkbox end t)
8183 (make-button (match-beginning 1) (match-end 1)
8184 :type 'markdown-gfm-checkbox-button))))))
8186 ;; Called when any modification is made to buffer text.
8187 (defun markdown-gfm-checkbox-after-change-function (beg end _)
8188 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
8189 BEG and END are the limits of scanned region."
8190 (save-excursion
8191 (save-match-data
8192 ;; Rescan between start of line from `beg' and start of line after `end'.
8193 (markdown-make-gfm-checkboxes-buttons
8194 (progn (goto-char beg) (beginning-of-line) (point))
8195 (progn (goto-char end) (forward-line 1) (point))))))
8197 (defun markdown-remove-gfm-checkbox-overlays ()
8198 "Remove all GFM checkbox overlays in buffer."
8199 (save-excursion
8200 (save-restriction
8201 (widen)
8202 (remove-overlays nil nil 'face 'markdown-gfm-checkbox-face))))
8205 ;;; Display inline image =================================================
8207 (defvar markdown-inline-image-overlays nil)
8208 (make-variable-buffer-local 'markdown-inline-image-overlays)
8210 (defun markdown-remove-inline-images ()
8211 "Remove inline image overlays from image links in the buffer.
8212 This can be toggled with `markdown-toggle-inline-images'
8213 or \\[markdown-toggle-inline-images]."
8214 (interactive)
8215 (mapc #'delete-overlay markdown-inline-image-overlays)
8216 (setq markdown-inline-image-overlays nil))
8218 (defun markdown-display-inline-images ()
8219 "Add inline image overlays to image links in the buffer.
8220 This can be toggled with `markdown-toggle-inline-images'
8221 or \\[markdown-toggle-inline-images]."
8222 (interactive)
8223 (unless (display-images-p)
8224 (error "Cannot show images"))
8225 (save-excursion
8226 (save-restriction
8227 (widen)
8228 (goto-char (point-min))
8229 (while (re-search-forward markdown-regex-link-inline nil t)
8230 (let ((start (match-beginning 0))
8231 (end (match-end 0))
8232 (file (match-string-no-properties 6)))
8233 (when (file-exists-p file)
8234 (let* ((abspath (if (file-name-absolute-p file)
8235 file
8236 (concat default-directory file)))
8237 (image
8238 (if (and markdown-max-image-size
8239 (image-type-available-p 'imagemagick))
8240 (create-image
8241 abspath 'imagemagick nil
8242 :max-width (car markdown-max-image-size)
8243 :max-height (cdr markdown-max-image-size))
8244 (create-image abspath))))
8245 (when image
8246 (let ((ov (make-overlay start end)))
8247 (overlay-put ov 'display image)
8248 (overlay-put ov 'face 'default)
8249 (push ov markdown-inline-image-overlays))))))))))
8251 (defun markdown-toggle-inline-images ()
8252 "Toggle inline image overlays in the buffer."
8253 (interactive)
8254 (if markdown-inline-image-overlays
8255 (markdown-remove-inline-images)
8256 (markdown-display-inline-images)))
8259 ;;; GFM Code Block Fontification ==============================================
8261 (defcustom markdown-fontify-code-blocks-natively nil
8262 "When non-nil, fontify code in code blocks using the native major mode.
8263 This only works for fenced code blocks where the language is
8264 specified where we can automatically determine the appropriate
8265 mode to use. The language to mode mapping may be customized by
8266 setting the variable `markdown-code-lang-modes'."
8267 :group 'markdown
8268 :type 'boolean
8269 :safe 'booleanp
8270 :package-version '(markdown-mode . "2.3"))
8272 (defun markdown-toggle-fontify-code-blocks-natively (&optional arg)
8273 "Toggle the native fontification of code blocks.
8274 With a prefix argument ARG, enable if ARG is positive,
8275 and disable otherwise."
8276 (interactive (list (or current-prefix-arg 'toggle)))
8277 (setq markdown-fontify-code-blocks-natively
8278 (if (eq arg 'toggle)
8279 (not markdown-fontify-code-blocks-natively)
8280 (> (prefix-numeric-value arg) 0)))
8281 (if markdown-fontify-code-blocks-natively
8282 (message "markdown-mode native code block fontification enabled")
8283 (message "markdown-mode native code block fontification disabled"))
8284 (markdown-reload-extensions))
8286 ;; This is based on `org-src-lang-modes' from org-src.el
8287 (defcustom markdown-code-lang-modes
8288 '(("ocaml" . tuareg-mode) ("elisp" . emacs-lisp-mode) ("ditaa" . artist-mode)
8289 ("asymptote" . asy-mode) ("dot" . fundamental-mode) ("sqlite" . sql-mode)
8290 ("calc" . fundamental-mode) ("C" . c-mode) ("cpp" . c++-mode)
8291 ("C++" . c++-mode) ("screen" . shell-script-mode) ("shell" . sh-mode)
8292 ("bash" . sh-mode))
8293 "Alist mapping languages to their major mode.
8294 The key is the language name, the value is the major mode. For
8295 many languages this is simple, but for language where this is not
8296 the case, this variable provides a way to simplify things on the
8297 user side. For example, there is no ocaml-mode in Emacs, but the
8298 mode to use is `tuareg-mode'."
8299 :group 'markdown
8300 :type '(repeat
8301 (cons
8302 (string "Language name")
8303 (symbol "Major mode")))
8304 :package-version '(markdown-mode . "2.3"))
8306 (defun markdown-get-lang-mode (lang)
8307 "Return major mode that should be used for LANG.
8308 LANG is a string, and the returned major mode is a symbol."
8309 (cl-find-if
8310 'fboundp
8311 (list (cdr (assoc lang markdown-code-lang-modes))
8312 (cdr (assoc (downcase lang) markdown-code-lang-modes))
8313 (intern (concat lang "-mode"))
8314 (intern (concat (downcase lang) "-mode")))))
8316 (defun markdown-fontify-code-blocks-generic (matcher last)
8317 "Add text properties to next code block from point to LAST.
8318 Use matching function MATCHER."
8319 (when (funcall matcher last)
8320 (save-excursion
8321 (save-match-data
8322 (let* ((start (match-beginning 0))
8323 (end (match-end 0))
8324 ;; Find positions outside opening and closing backquotes.
8325 (bol-prev (progn (goto-char start)
8326 (if (bolp) (point-at-bol 0) (point-at-bol))))
8327 (eol-next (progn (goto-char end)
8328 (if (bolp) (point-at-bol 2) (point-at-bol 3))))
8329 lang)
8330 (if (and markdown-fontify-code-blocks-natively
8331 (setq lang (markdown-code-block-lang)))
8332 (markdown-fontify-code-block-natively lang start end)
8333 (add-text-properties start end '(face markdown-pre-face)))
8334 ;; Set background for block as well as opening and closing lines.
8335 (font-lock-append-text-property
8336 bol-prev eol-next 'face 'markdown-code-face)
8337 ;; Set invisible property for lines before and after, including newline.
8338 (add-text-properties bol-prev start '(invisible markdown-markup))
8339 (add-text-properties end eol-next '(invisible markdown-markup)))))
8342 (defun markdown-fontify-gfm-code-blocks (last)
8343 "Add text properties to next GFM code block from point to LAST."
8344 (markdown-fontify-code-blocks-generic 'markdown-match-gfm-code-blocks last))
8346 (defun markdown-fontify-fenced-code-blocks (last)
8347 "Add text properties to next tilde fenced code block from point to LAST."
8348 (markdown-fontify-code-blocks-generic 'markdown-match-fenced-code-blocks last))
8350 ;; Based on `org-src-font-lock-fontify-block' from org-src.el.
8351 (defun markdown-fontify-code-block-natively (lang start end)
8352 "Fontify given GFM or fenced code block.
8353 This function is called by Emacs for automatic fontification when
8354 `markdown-fontify-code-blocks-natively' is non-nil. LANG is the
8355 language used in the block. START and END specify the block
8356 position."
8357 (let ((lang-mode (markdown-get-lang-mode lang)))
8358 (when (fboundp lang-mode)
8359 (let ((string (buffer-substring-no-properties start end))
8360 (modified (buffer-modified-p))
8361 (markdown-buffer (current-buffer)) pos next)
8362 (remove-text-properties start end '(face nil))
8363 (with-current-buffer
8364 (get-buffer-create
8365 (concat " markdown-code-fontification:" (symbol-name lang-mode)))
8366 ;; Make sure that modification hooks are not inhibited in
8367 ;; the org-src-fontification buffer in case we're called
8368 ;; from `jit-lock-function' (Bug#25132).
8369 (let ((inhibit-modification-hooks nil))
8370 (delete-region (point-min) (point-max))
8371 (insert string " ")) ;; so there's a final property change
8372 (unless (eq major-mode lang-mode) (funcall lang-mode))
8373 (markdown-font-lock-ensure)
8374 (setq pos (point-min))
8375 (while (setq next (next-single-property-change pos 'face))
8376 (let ((val (get-text-property pos 'face)))
8377 (when val
8378 (put-text-property
8379 (+ start (1- pos)) (1- (+ start next)) 'face
8380 val markdown-buffer)))
8381 (setq pos next)))
8382 (add-text-properties
8383 start end
8384 '(font-lock-fontified t fontified t font-lock-multiline t))
8385 (set-buffer-modified-p modified)))))
8387 (require 'edit-indirect nil t)
8388 (defvar edit-indirect-guess-mode-function)
8389 (defvar edit-indirect-after-commit-functions)
8391 (defun markdown--edit-indirect-after-commit-function (_beg end)
8392 "Ensure trailing newlines at the END of code blocks."
8393 (goto-char end)
8394 (unless (eq (char-before) ?\n)
8395 (insert "\n")))
8397 (defun markdown-edit-code-block ()
8398 "Edit Markdown code block in an indirect buffer."
8399 (interactive)
8400 (save-excursion
8401 (if (fboundp 'edit-indirect-region)
8402 (let* ((bounds (markdown-get-enclosing-fenced-block-construct))
8403 (begin (and bounds (goto-char (nth 0 bounds)) (point-at-bol 2)))
8404 (end (and bounds (goto-char (nth 1 bounds)) (point-at-bol 1))))
8405 (if (and begin end)
8406 (let* ((lang (markdown-code-block-lang))
8407 (mode (or (and lang (markdown-get-lang-mode lang))
8408 markdown-edit-code-block-default-mode))
8409 (edit-indirect-guess-mode-function
8410 (lambda (_parent-buffer _beg _end)
8411 (funcall mode))))
8412 (edit-indirect-region begin end 'display-buffer))
8413 (user-error "Not inside a GFM or tilde fenced code block")))
8414 (when (y-or-n-p "Package edit-indirect needed to edit code blocks. Install it now? ")
8415 (progn (package-refresh-contents)
8416 (package-install 'edit-indirect)
8417 (markdown-edit-code-block))))))
8420 ;;; Table Editing
8422 ;; These functions were originally adapted from `org-table.el'.
8424 ;; General helper functions
8426 (defmacro markdown--with-gensyms (symbols &rest body)
8427 (declare (debug (sexp body)) (indent 1))
8428 `(let ,(mapcar (lambda (s)
8429 `(,s (make-symbol (concat "--" (symbol-name ',s)))))
8430 symbols)
8431 ,@body))
8433 (defun markdown--split-string (string &optional separators)
8434 "Splits STRING into substrings at SEPARATORS.
8435 SEPARATORS is a regular expression. If nil it defaults to
8436 `split-string-default-separators'. This version returns no empty
8437 strings if there are matches at the beginning and end of string."
8438 (let ((start 0) notfirst list)
8439 (while (and (string-match
8440 (or separators split-string-default-separators)
8441 string
8442 (if (and notfirst
8443 (= start (match-beginning 0))
8444 (< start (length string)))
8445 (1+ start) start))
8446 (< (match-beginning 0) (length string)))
8447 (setq notfirst t)
8448 (or (eq (match-beginning 0) 0)
8449 (and (eq (match-beginning 0) (match-end 0))
8450 (eq (match-beginning 0) start))
8451 (push (substring string start (match-beginning 0)) list))
8452 (setq start (match-end 0)))
8453 (or (eq start (length string))
8454 (push (substring string start) list))
8455 (nreverse list)))
8457 (defun markdown--string-width (s)
8458 "Return width of string S.
8459 This version ignores characters with invisibility property
8460 `markdown-markup'."
8461 (let (b)
8462 (when (or (eq t buffer-invisibility-spec)
8463 (member 'markdown-markup buffer-invisibility-spec))
8464 (while (setq b (text-property-any
8465 0 (length s)
8466 'invisible 'markdown-markup s))
8467 (setq s (concat
8468 (substring s 0 b)
8469 (substring s (or (next-single-property-change
8470 b 'invisible s)
8471 (length s))))))))
8472 (string-width s))
8474 (defun markdown--remove-invisible-markup (s)
8475 "Remove Markdown markup from string S.
8476 This version removes characters with invisibility property
8477 `markdown-markup'."
8478 (let (b)
8479 (while (setq b (text-property-any
8480 0 (length s)
8481 'invisible 'markdown-markup s))
8482 (setq s (concat
8483 (substring s 0 b)
8484 (substring s (or (next-single-property-change
8485 b 'invisible s)
8486 (length s)))))))
8489 ;; Functions for maintaining tables
8491 (defvar markdown-table-at-point-p-function nil
8492 "Function to decide if point is inside a table.
8494 The indirection serves to differentiate between standard markdown
8495 tables and gfm tables which are less strict about the markup.")
8497 (defconst markdown-table-line-regexp "^[ \t]*|"
8498 "Regexp matching any line inside a table.")
8500 (defconst markdown-table-hline-regexp "^[ \t]*|[-:]"
8501 "Regexp matching hline inside a table.")
8503 (defconst markdown-table-dline-regexp "^[ \t]*|[^-:]"
8504 "Regexp matching dline inside a table.")
8506 (defun markdown-table-at-point-p ()
8507 "Return non-nil when point is inside a table."
8508 (if (functionp markdown-table-at-point-p-function)
8509 (funcall markdown-table-at-point-p-function)
8510 (markdown--table-at-point-p)))
8512 (defun markdown--table-at-point-p ()
8513 "Return non-nil when point is inside a table."
8514 (save-excursion
8515 (beginning-of-line)
8516 (and (looking-at-p markdown-table-line-regexp)
8517 (not (markdown-code-block-at-point-p)))))
8519 (defconst gfm-table-line-regexp "^.?*|"
8520 "Regexp matching any line inside a table.")
8522 (defconst gfm-table-hline-regexp "^-+\\(|-\\)+"
8523 "Regexp matching hline inside a table.")
8525 ;; GFM simplified tables syntax is as follows:
8526 ;; - A header line for the column names, this is any text
8527 ;; separated by `|'.
8528 ;; - Followed by a string -|-|- ..., the number of dashes is optional
8529 ;; but must be higher than 1. The number of separators should match
8530 ;; the number of columns.
8531 ;; - Followed by the rows of data, which has the same format as the
8532 ;; header line.
8533 ;; Example:
8535 ;; foo | bar
8536 ;; ------|---------
8537 ;; bar | baz
8538 ;; bar | baz
8539 (defun gfm--table-at-point-p ()
8540 "Return non-nil when point is inside a gfm-compatible table."
8541 (or (markdown--table-at-point-p)
8542 (save-excursion
8543 (beginning-of-line)
8544 (when (looking-at-p gfm-table-line-regexp)
8545 ;; we might be at the first line of the table, check if the
8546 ;; line below is the hline
8547 (or (save-excursion
8548 (forward-line 1)
8549 (looking-at-p gfm-table-hline-regexp))
8550 ;; go up to find the header
8551 (catch 'done
8552 (while (looking-at-p gfm-table-line-regexp)
8553 (cond
8554 ((looking-at-p gfm-table-hline-regexp)
8555 (throw 'done t))
8556 ((bobp)
8557 (throw 'done nil)))
8558 (forward-line -1))
8559 nil))))))
8561 (defun markdown-table-hline-at-point-p ()
8562 "Return non-nil when point is on a hline in a table.
8563 This function assumes point is on a table."
8564 (save-excursion
8565 (beginning-of-line)
8566 (looking-at-p markdown-table-hline-regexp)))
8568 (defun markdown-table-begin ()
8569 "Find the beginning of the table and return its position.
8570 This function assumes point is on a table."
8571 (save-excursion
8572 (while (and (not (bobp))
8573 (markdown-table-at-point-p))
8574 (forward-line -1))
8575 (unless (eobp)
8576 (forward-line 1))
8577 (point)))
8579 (defun markdown-table-end ()
8580 "Find the end of the table and return its position.
8581 This function assumes point is on a table."
8582 (save-excursion
8583 (while (and (not (eobp))
8584 (markdown-table-at-point-p))
8585 (forward-line 1))
8586 (point)))
8588 (defun markdown-table-get-dline ()
8589 "Return index of the table data line at point.
8590 This function assumes point is on a table."
8591 (let ((pos (point)) (end (markdown-table-end)) (cnt 0))
8592 (save-excursion
8593 (goto-char (markdown-table-begin))
8594 (while (and (re-search-forward
8595 markdown-table-dline-regexp end t)
8596 (setq cnt (1+ cnt))
8597 (< (point-at-eol) pos))))
8598 cnt))
8600 (defun markdown-table-get-column ()
8601 "Return table column at point.
8602 This function assumes point is on a table."
8603 (let ((pos (point)) (cnt 0))
8604 (save-excursion
8605 (beginning-of-line)
8606 (while (search-forward "|" pos t) (setq cnt (1+ cnt))))
8607 cnt))
8609 (defun markdown-table-get-cell (&optional n)
8610 "Return the content of the cell in column N of current row.
8611 N defaults to column at point. This function assumes point is on
8612 a table."
8613 (and n (markdown-table-goto-column n))
8614 (skip-chars-backward "^|\n") (backward-char 1)
8615 (if (looking-at "|[^|\r\n]*")
8616 (let* ((pos (match-beginning 0))
8617 (val (buffer-substring (1+ pos) (match-end 0))))
8618 (goto-char (min (point-at-eol) (+ 2 pos)))
8619 ;; Trim whitespaces
8620 (setq val (replace-regexp-in-string "\\`[ \t]+" "" val)
8621 val (replace-regexp-in-string "[ \t]+\\'" "" val)))
8622 (forward-char 1) ""))
8624 (defun markdown-table-goto-dline (n)
8625 "Go to the Nth data line in the table at point.
8626 Return t when the line exists, nil otherwise. This function
8627 assumes point is on a table."
8628 (goto-char (markdown-table-begin))
8629 (let ((end (markdown-table-end)) (cnt 0))
8630 (while (and (re-search-forward
8631 markdown-table-dline-regexp end t)
8632 (< (setq cnt (1+ cnt)) n)))
8633 (= cnt n)))
8635 (defun markdown-table-goto-column (n &optional on-delim)
8636 "Go to the Nth column in the table line at point.
8637 With optional argument ON-DELIM, stop with point before the left
8638 delimiter of the cell. If there are less than N cells, just go
8639 beyond the last delimiter. This function assumes point is on a
8640 table."
8641 (beginning-of-line 1)
8642 (when (> n 0)
8643 (while (and (> (setq n (1- n)) -1)
8644 (search-forward "|" (point-at-eol) t)))
8645 (if on-delim
8646 (backward-char 1)
8647 (when (looking-at " ") (forward-char 1)))))
8649 (defmacro markdown-table-save-cell (&rest body)
8650 "Save cell at point, execute BODY and restore cell.
8651 This function assumes point is on a table."
8652 (declare (debug (body)))
8653 (markdown--with-gensyms (line column)
8654 `(let ((,line (copy-marker (line-beginning-position)))
8655 (,column (markdown-table-get-column)))
8656 (unwind-protect
8657 (progn ,@body)
8658 (goto-char ,line)
8659 (markdown-table-goto-column ,column)
8660 (set-marker ,line nil)))))
8662 (defun markdown-table-blank-line (s)
8663 "Convert a table line S into a line with blank cells."
8664 (if (string-match "^[ \t]*|-" s)
8665 (setq s (mapconcat
8666 (lambda (x) (if (member x '(?| ?+)) "|" " "))
8667 s ""))
8668 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
8669 (setq s (replace-match
8670 (concat "|" (make-string (length (match-string 1 s)) ?\ ) "|")
8671 t t s)))
8674 (defun markdown-table-colfmt (fmtspec)
8675 "Process column alignment specifier FMTSPEC for tables."
8676 (when (stringp fmtspec)
8677 (mapcar (lambda (x)
8678 (cond ((string-match-p "^:.*:$" x) 'c)
8679 ((string-match-p "^:" x) 'l)
8680 ((string-match-p ":$" x) 'r)
8681 (t 'd)))
8682 (markdown--split-string fmtspec "\\s-*|\\s-*"))))
8684 (defun markdown-table-align ()
8685 "Align table at point.
8686 This function assumes point is on a table."
8687 (interactive)
8688 (let ((begin (markdown-table-begin))
8689 (end (copy-marker (markdown-table-end))))
8690 (markdown-table-save-cell
8691 (goto-char begin)
8692 (let* (fmtspec
8693 ;; Store table indent
8694 (indent (progn (looking-at "[ \t]*") (match-string 0)))
8695 ;; Split table in lines and save column format specifier
8696 (lines (mapcar (lambda (l)
8697 (if (string-match-p "\\`[ \t]*|[-:]" l)
8698 (progn (setq fmtspec (or fmtspec l)) nil) l))
8699 (markdown--split-string (buffer-substring begin end) "\n")))
8700 ;; Split lines in cells
8701 (cells (mapcar (lambda (l) (markdown--split-string l "\\s-*|\\s-*"))
8702 (remq nil lines)))
8703 ;; Calculate maximum number of cells in a line
8704 (maxcells (if cells
8705 (apply #'max (mapcar #'length cells))
8706 (user-error "Empty table")))
8707 ;; Empty cells to fill short lines
8708 (emptycells (make-list maxcells "")) maxwidths)
8709 ;; Calculate maximum width for each column
8710 (dotimes (i maxcells)
8711 (let ((column (mapcar (lambda (x) (or (nth i x) "")) cells)))
8712 (push (apply #'max 1 (mapcar #'markdown--string-width column))
8713 maxwidths)))
8714 (setq maxwidths (nreverse maxwidths))
8715 ;; Process column format specifier
8716 (setq fmtspec (markdown-table-colfmt fmtspec))
8717 ;; Compute formats needed for output of table lines
8718 (let ((hfmt (concat indent "|"))
8719 (rfmt (concat indent "|"))
8720 hfmt1 rfmt1 fmt)
8721 (dolist (width maxwidths (setq hfmt (concat (substring hfmt 0 -1) "|")))
8722 (setq fmt (pop fmtspec))
8723 (cond ((equal fmt 'l) (setq hfmt1 ":%s-|" rfmt1 " %%-%ds |"))
8724 ((equal fmt 'r) (setq hfmt1 "-%s:|" rfmt1 " %%%ds |"))
8725 ((equal fmt 'c) (setq hfmt1 ":%s:|" rfmt1 " %%-%ds |"))
8726 (t (setq hfmt1 "-%s-|" rfmt1 " %%-%ds |")))
8727 (setq rfmt (concat rfmt (format rfmt1 width)))
8728 (setq hfmt (concat hfmt (format hfmt1 (make-string width ?-)))))
8729 ;; Replace modified lines only
8730 (dolist (line lines)
8731 (let ((line (if line
8732 (apply #'format rfmt (append (pop cells) emptycells))
8733 hfmt))
8734 (previous (buffer-substring (point) (line-end-position))))
8735 (if (equal previous line)
8736 (forward-line)
8737 (insert line "\n")
8738 (delete-region (point) (line-beginning-position 2))))))
8739 (set-marker end nil)))))
8741 (defun markdown-table-insert-row (&optional arg)
8742 "Insert a new row above the row at point into the table.
8743 With optional argument ARG, insert below the current row."
8744 (interactive "P")
8745 (unless (markdown-table-at-point-p)
8746 (user-error "Not at a table"))
8747 (let* ((line (buffer-substring
8748 (line-beginning-position) (line-end-position)))
8749 (new (markdown-table-blank-line line)))
8750 (beginning-of-line (if arg 2 1))
8751 (unless (bolp) (insert "\n"))
8752 (insert-before-markers new "\n")
8753 (beginning-of-line 0)
8754 (re-search-forward "| ?" (line-end-position) t)))
8756 (defun markdown-table-delete-row ()
8757 "Delete row or horizontal line at point from the table."
8758 (interactive)
8759 (unless (markdown-table-at-point-p)
8760 (user-error "Not at a table"))
8761 (let ((col (current-column)))
8762 (kill-region (point-at-bol)
8763 (min (1+ (point-at-eol)) (point-max)))
8764 (unless (markdown-table-at-point-p) (beginning-of-line 0))
8765 (move-to-column col)))
8767 (defun markdown-table-move-row (&optional up)
8768 "Move table line at point down.
8769 With optional argument UP, move it up."
8770 (interactive "P")
8771 (unless (markdown-table-at-point-p)
8772 (user-error "Not at a table"))
8773 (let* ((col (current-column)) (pos (point))
8774 (tonew (if up 0 2)) txt)
8775 (beginning-of-line tonew)
8776 (unless (markdown-table-at-point-p)
8777 (goto-char pos) (user-error "Cannot move row further"))
8778 (goto-char pos) (beginning-of-line 1) (setq pos (point))
8779 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8780 (delete-region (point) (1+ (point-at-eol)))
8781 (beginning-of-line tonew)
8782 (insert txt) (beginning-of-line 0)
8783 (move-to-column col)))
8785 (defun markdown-table-move-row-up ()
8786 "Move table row at point up."
8787 (interactive)
8788 (markdown-table-move-row 'up))
8790 (defun markdown-table-move-row-down ()
8791 "Move table row at point down."
8792 (interactive)
8793 (markdown-table-move-row nil))
8795 (defun markdown-table-insert-column ()
8796 "Insert a new table column."
8797 (interactive)
8798 (unless (markdown-table-at-point-p)
8799 (user-error "Not at a table"))
8800 (let* ((col (max 1 (markdown-table-get-column)))
8801 (begin (markdown-table-begin))
8802 (end (copy-marker (markdown-table-end))))
8803 (markdown-table-save-cell
8804 (goto-char begin)
8805 (while (< (point) end)
8806 (markdown-table-goto-column col t)
8807 (if (markdown-table-hline-at-point-p)
8808 (insert "|---")
8809 (insert "| "))
8810 (forward-line)))
8811 (set-marker end nil)
8812 (markdown-table-align)))
8814 (defun markdown-table-delete-column ()
8815 "Delete column at point from table."
8816 (interactive)
8817 (unless (markdown-table-at-point-p)
8818 (user-error "Not at a table"))
8819 (let ((col (markdown-table-get-column))
8820 (begin (markdown-table-begin))
8821 (end (copy-marker (markdown-table-end))))
8822 (markdown-table-save-cell
8823 (goto-char begin)
8824 (while (< (point) end)
8825 (markdown-table-goto-column col t)
8826 (and (looking-at "|[^|\n]+|")
8827 (replace-match "|"))
8828 (forward-line)))
8829 (set-marker end nil)
8830 (markdown-table-goto-column (max 1 (1- col)))
8831 (markdown-table-align)))
8833 (defun markdown-table-move-column (&optional left)
8834 "Move table column at point to the right.
8835 With optional argument LEFT, move it to the left."
8836 (interactive "P")
8837 (unless (markdown-table-at-point-p)
8838 (user-error "Not at a table"))
8839 (let* ((col (markdown-table-get-column))
8840 (col1 (if left (1- col) col))
8841 (colpos (if left (1- col) (1+ col)))
8842 (begin (markdown-table-begin))
8843 (end (copy-marker (markdown-table-end))))
8844 (when (and left (= col 1))
8845 (user-error "Cannot move column further left"))
8846 (when (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8847 (user-error "Cannot move column further right"))
8848 (markdown-table-save-cell
8849 (goto-char begin)
8850 (while (< (point) end)
8851 (markdown-table-goto-column col1 t)
8852 (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8853 (replace-match "|\\2|\\1|"))
8854 (forward-line)))
8855 (set-marker end nil)
8856 (markdown-table-goto-column colpos)
8857 (markdown-table-align)))
8859 (defun markdown-table-move-column-left ()
8860 "Move table column at point to the left."
8861 (interactive)
8862 (markdown-table-move-column 'left))
8864 (defun markdown-table-move-column-right ()
8865 "Move table column at point to the right."
8866 (interactive)
8867 (markdown-table-move-column nil))
8869 (defun markdown-table-next-row ()
8870 "Go to the next row (same column) in the table.
8871 Create new table lines if required."
8872 (interactive)
8873 (unless (markdown-table-at-point-p)
8874 (user-error "Not at a table"))
8875 (if (or (looking-at "[ \t]*$")
8876 (save-excursion (skip-chars-backward " \t") (bolp)))
8877 (newline)
8878 (markdown-table-align)
8879 (let ((col (markdown-table-get-column)))
8880 (beginning-of-line 2)
8881 (if (or (not (markdown-table-at-point-p))
8882 (markdown-table-hline-at-point-p))
8883 (progn
8884 (beginning-of-line 0)
8885 (markdown-table-insert-row 'below)))
8886 (markdown-table-goto-column col)
8887 (skip-chars-backward "^|\n\r")
8888 (when (looking-at " ") (forward-char 1)))))
8890 (defun markdown-table-forward-cell ()
8891 "Go to the next cell in the table.
8892 Create new table lines if required."
8893 (interactive)
8894 (unless (markdown-table-at-point-p)
8895 (user-error "Not at a table"))
8896 (markdown-table-align)
8897 (let ((end (markdown-table-end)))
8898 (when (markdown-table-hline-at-point-p) (end-of-line 1))
8899 (condition-case nil
8900 (progn
8901 (re-search-forward "|" end)
8902 (if (looking-at "[ \t]*$")
8903 (re-search-forward "|" end))
8904 (if (and (looking-at "[-:]")
8905 (re-search-forward "^[ \t]*|\\([^-:]\\)" end t))
8906 (goto-char (match-beginning 1)))
8907 (if (looking-at "[-:]")
8908 (progn
8909 (beginning-of-line 0)
8910 (markdown-table-insert-row 'below))
8911 (when (looking-at " ") (forward-char 1))))
8912 (error (markdown-table-insert-row 'below)))))
8914 (defun markdown-table-backward-cell ()
8915 "Go to the previous cell in the table."
8916 (interactive)
8917 (unless (markdown-table-at-point-p)
8918 (user-error "Not at a table"))
8919 (markdown-table-align)
8920 (when (markdown-table-hline-at-point-p) (end-of-line 1))
8921 (condition-case nil
8922 (progn
8923 (re-search-backward "|" (markdown-table-begin))
8924 (re-search-backward "|" (markdown-table-begin)))
8925 (error (user-error "Cannot move to previous table cell")))
8926 (while (looking-at "|\\([-:]\\|[ \t]*$\\)")
8927 (re-search-backward "|" (markdown-table-begin)))
8928 (when (looking-at "| ?") (goto-char (match-end 0))))
8930 (defun markdown-table-transpose ()
8931 "Transpose table at point.
8932 Horizontal separator lines will be eliminated."
8933 (interactive)
8934 (unless (markdown-table-at-point-p)
8935 (user-error "Not at a table"))
8936 (let* ((table (buffer-substring-no-properties
8937 (markdown-table-begin) (markdown-table-end)))
8938 ;; Convert table to a Lisp structure
8939 (table (delq nil
8940 (mapcar
8941 (lambda (x)
8942 (unless (string-match-p
8943 markdown-table-hline-regexp x)
8944 (markdown--split-string x "\\s-*|\\s-*")))
8945 (markdown--split-string table "[ \t]*\n[ \t]*"))))
8946 (dline_old (markdown-table-get-dline))
8947 (col_old (markdown-table-get-column))
8948 (contents (mapcar (lambda (_)
8949 (let ((tp table))
8950 (mapcar
8951 (lambda (_)
8952 (prog1
8953 (pop (car tp))
8954 (setq tp (cdr tp))))
8955 table)))
8956 (car table))))
8957 (goto-char (markdown-table-begin))
8958 (re-search-forward "|") (backward-char)
8959 (delete-region (point) (markdown-table-end))
8960 (insert (mapconcat
8961 (lambda(x)
8962 (concat "| " (mapconcat 'identity x " | " ) " |\n"))
8963 contents ""))
8964 (markdown-table-goto-dline col_old)
8965 (markdown-table-goto-column dline_old))
8966 (markdown-table-align))
8968 (defun markdown-table-sort-lines (&optional sorting-type)
8969 "Sort table lines according to the column at point.
8971 The position of point indicates the column to be used for
8972 sorting, and the range of lines is the range between the nearest
8973 horizontal separator lines, or the entire table of no such lines
8974 exist. If point is before the first column, user will be prompted
8975 for the sorting column. If there is an active region, the mark
8976 specifies the first line and the sorting column, while point
8977 should be in the last line to be included into the sorting.
8979 The command then prompts for the sorting type which can be
8980 alphabetically or numerically. Sorting in reverse order is also
8981 possible.
8983 If SORTING-TYPE is specified when this function is called from a
8984 Lisp program, no prompting will take place. SORTING-TYPE must be
8985 a character, any of (?a ?A ?n ?N) where the capital letters
8986 indicate that sorting should be done in reverse order."
8987 (interactive)
8988 (unless (markdown-table-at-point-p)
8989 (user-error "Not at a table"))
8990 ;; Set sorting type and column used for sorting
8991 (let ((column (let ((c (markdown-table-get-column)))
8992 (cond ((> c 0) c)
8993 ((called-interactively-p 'any)
8994 (read-number "Use column N for sorting: "))
8995 (t 1))))
8996 (sorting-type
8997 (or sorting-type
8998 (read-char-exclusive
8999 "Sort type: [a]lpha [n]umeric (A/N means reversed): "))))
9000 (save-restriction
9001 ;; Narrow buffer to appropriate sorting area
9002 (if (region-active-p)
9003 (narrow-to-region
9004 (save-excursion
9005 (progn
9006 (goto-char (region-beginning)) (line-beginning-position)))
9007 (save-excursion
9008 (progn
9009 (goto-char (region-end)) (line-end-position))))
9010 (let ((start (markdown-table-begin))
9011 (end (markdown-table-end)))
9012 (narrow-to-region
9013 (save-excursion
9014 (if (re-search-backward
9015 markdown-table-hline-regexp start t)
9016 (line-beginning-position 2)
9017 start))
9018 (if (save-excursion (re-search-forward
9019 markdown-table-hline-regexp end t))
9020 (match-beginning 0)
9021 end))))
9022 ;; Determine arguments for `sort-subr'
9023 (let* ((extract-key-from-cell
9024 (cl-case sorting-type
9025 ((?a ?A) #'markdown--remove-invisible-markup) ;; #'identity)
9026 ((?n ?N) #'string-to-number)
9027 (t (user-error "Invalid sorting type: %c" sorting-type))))
9028 (predicate
9029 (cl-case sorting-type
9030 ((?n ?N) #'<)
9031 ((?a ?A) #'string<))))
9032 ;; Sort selected area
9033 (goto-char (point-min))
9034 (sort-subr (memq sorting-type '(?A ?N))
9035 (lambda ()
9036 (forward-line)
9037 (while (and (not (eobp))
9038 (not (looking-at
9039 markdown-table-dline-regexp)))
9040 (forward-line)))
9041 #'end-of-line
9042 (lambda ()
9043 (funcall extract-key-from-cell
9044 (markdown-table-get-cell column)))
9046 predicate)
9047 (goto-char (point-min))))))
9049 (defun markdown-table-convert-region (begin end &optional separator)
9050 "Convert region from BEGIN to END to table with SEPARATOR.
9052 If every line contains at least one TAB character, the function
9053 assumes that the material is tab separated (TSV). If every line
9054 contains a comma, comma-separated values (CSV) are assumed. If
9055 not, lines are split at whitespace into cells.
9057 You can use a prefix argument to force a specific separator:
9058 \\[universal-argument] once forces CSV, \\[universal-argument]
9059 twice forces TAB, and \\[universal-argument] three times will
9060 prompt for a regular expression to match the separator, and a
9061 numeric argument N indicates that at least N consecutive
9062 spaces, or alternatively a TAB should be used as the separator."
9064 (interactive "r\nP")
9065 (let* ((begin (min begin end)) (end (max begin end)) re)
9066 (goto-char begin) (beginning-of-line 1)
9067 (setq begin (point-marker))
9068 (goto-char end)
9069 (if (bolp) (backward-char 1) (end-of-line 1))
9070 (setq end (point-marker))
9071 (when (equal separator '(64))
9072 (setq separator (read-regexp "Regexp for cell separator: ")))
9073 (unless separator
9074 ;; Get the right cell separator
9075 (goto-char begin)
9076 (setq separator
9077 (cond
9078 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
9079 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
9080 (t 1))))
9081 (goto-char begin)
9082 (if (equal separator '(4))
9083 ;; Parse CSV
9084 (while (< (point) end)
9085 (cond
9086 ((looking-at "^") (insert "| "))
9087 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
9088 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
9089 (replace-match "\\1") (if (looking-at "\"") (insert "\"")))
9090 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
9091 ((looking-at "[ \t]*,") (replace-match " | "))
9092 (t (beginning-of-line 2))))
9093 (setq re
9094 (cond
9095 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
9096 ((equal separator '(16)) "^\\|\t")
9097 ((integerp separator)
9098 (if (< separator 1)
9099 (user-error "Cell separator must contain one or more spaces")
9100 (format "^ *\\| *\t *\\| \\{%d,\\}" separator)))
9101 ((stringp separator) (format "^ *\\|%s" separator))
9102 (t (error "Invalid cell separator"))))
9103 (while (re-search-forward re end t) (replace-match "| " t t)))
9104 (goto-char begin)
9105 (markdown-table-align)))
9108 ;;; ElDoc Support
9110 (defun markdown-eldoc-function ()
9111 "Return a helpful string when appropriate based on context.
9112 * Report URL when point is at a hidden URL.
9113 * Report language name when point is a code block with hidden markup."
9114 (cond
9115 ;; Hidden URL or reference for inline link
9116 ((and (or (thing-at-point-looking-at markdown-regex-link-inline)
9117 (thing-at-point-looking-at markdown-regex-link-reference))
9118 (or markdown-hide-urls markdown-hide-markup))
9119 (let* ((imagep (string-equal (match-string 1) "!"))
9120 (edit-keys (markdown--substitute-command-keys
9121 (if imagep
9122 "\\[markdown-insert-image]"
9123 "\\[markdown-insert-link]")))
9124 (edit-str (propertize edit-keys 'face 'font-lock-constant-face))
9125 (referencep (string-equal (match-string 5) "["))
9126 (object (if referencep "reference" "URL")))
9127 (format "Hidden %s (%s to edit): %s" object edit-str
9128 (if referencep
9129 (concat
9130 (propertize "[" 'face 'markdown-markup-face)
9131 (propertize (match-string-no-properties 6)
9132 'face 'markdown-reference-face)
9133 (propertize "]" 'face 'markdown-markup-face))
9134 (propertize (match-string-no-properties 6)
9135 'face 'markdown-url-face)))))
9136 ;; Hidden language name for fenced code blocks
9137 ((and (markdown-code-block-at-point-p)
9138 (not (get-text-property (point) 'markdown-pre))
9139 markdown-hide-markup)
9140 (let ((lang (save-excursion (markdown-code-block-lang))))
9141 (unless lang (setq lang "[unspecified]"))
9142 (format "Hidden code block language: %s (%s to toggle markup)"
9143 (propertize lang 'face 'markdown-language-keyword-face)
9144 (markdown--substitute-command-keys
9145 "\\[markdown-toggle-markup-hiding]"))))))
9148 ;;; Mode Definition ==========================================================
9150 (defun markdown-show-version ()
9151 "Show the version number in the minibuffer."
9152 (interactive)
9153 (message "markdown-mode, version %s" markdown-mode-version))
9155 (defun markdown-mode-info ()
9156 "Open the `markdown-mode' homepage."
9157 (interactive)
9158 (browse-url "https://jblevins.org/projects/markdown-mode/"))
9160 ;;;###autoload
9161 (define-derived-mode markdown-mode text-mode "Markdown"
9162 "Major mode for editing Markdown files."
9163 ;; Natural Markdown tab width
9164 (setq tab-width 4)
9165 ;; Comments
9166 (setq-local comment-start "<!-- ")
9167 (setq-local comment-end " -->")
9168 (setq-local comment-start-skip "<!--[ \t]*")
9169 (setq-local comment-column 0)
9170 (setq-local comment-auto-fill-only-comments nil)
9171 (setq-local comment-use-syntax t)
9172 ;; Syntax
9173 (add-hook 'syntax-propertize-extend-region-functions
9174 #'markdown-syntax-propertize-extend-region)
9175 (add-hook 'jit-lock-after-change-extend-region-functions
9176 #'markdown-font-lock-extend-region-function t t)
9177 (setq-local syntax-propertize-function #'markdown-syntax-propertize)
9178 (syntax-propertize (point-max)) ;; Propertize before hooks run, etc.
9179 ;; Font lock.
9180 (setq font-lock-defaults
9181 '(markdown-mode-font-lock-keywords
9182 nil nil nil nil
9183 (font-lock-multiline . t)
9184 (font-lock-syntactic-face-function . markdown-syntactic-face)
9185 (font-lock-extra-managed-props . '(composition display invisible))))
9186 (if markdown-hide-markup
9187 (add-to-invisibility-spec 'markdown-markup)
9188 (remove-from-invisibility-spec 'markdown-markup))
9189 ;; Wiki links
9190 (markdown-setup-wiki-link-hooks)
9191 ;; Math mode
9192 (when markdown-enable-math (markdown-toggle-math t))
9193 ;; Add a buffer-local hook to reload after file-local variables are read
9194 (add-hook 'hack-local-variables-hook #'markdown-handle-local-variables nil t)
9195 ;; For imenu support
9196 (setq imenu-create-index-function
9197 (if markdown-nested-imenu-heading-index
9198 #'markdown-imenu-create-nested-index
9199 #'markdown-imenu-create-flat-index))
9200 ;; For menu support in XEmacs
9201 (easy-menu-add markdown-mode-menu markdown-mode-map)
9202 ;; Defun movement
9203 (setq-local beginning-of-defun-function #'markdown-beginning-of-defun)
9204 (setq-local end-of-defun-function #'markdown-end-of-defun)
9205 ;; Paragraph filling
9206 (setq-local fill-paragraph-function #'markdown-fill-paragraph)
9207 (setq-local paragraph-start
9208 ;; Should match start of lines that start or separate paragraphs
9209 (mapconcat #'identity
9211 "\f" ; starts with a literal line-feed
9212 "[ \t\f]*$" ; space-only line
9213 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9214 "[ \t]*[*+-][ \t]+" ; unordered list item
9215 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
9216 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
9217 "[ \t]*:[ \t]+" ; definition
9218 "^|" ; table or Pandoc line block
9220 "\\|"))
9221 (setq-local paragraph-separate
9222 ;; Should match lines that separate paragraphs without being
9223 ;; part of any paragraph:
9224 (mapconcat #'identity
9225 '("[ \t\f]*$" ; space-only line
9226 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9227 ;; The following is not ideal, but the Fill customization
9228 ;; options really only handle paragraph-starting prefixes,
9229 ;; not paragraph-ending suffixes:
9230 ".* $" ; line ending in two spaces
9231 "^#+"
9232 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
9233 "\\|"))
9234 (setq-local adaptive-fill-first-line-regexp "\\`[ \t]*[A-Z]?>[ \t]*?\\'")
9235 (setq-local adaptive-fill-regexp "\\s-*")
9236 (setq-local adaptive-fill-function #'markdown-adaptive-fill-function)
9237 (setq-local fill-forward-paragraph-function #'markdown-fill-forward-paragraph)
9238 ;; Outline mode
9239 (setq-local outline-regexp markdown-regex-header)
9240 (setq-local outline-level #'markdown-outline-level)
9241 ;; Cause use of ellipses for invisible text.
9242 (add-to-invisibility-spec '(outline . t))
9243 ;; ElDoc support
9244 (if (eval-when-compile (fboundp 'add-function))
9245 (add-function :before-until (local 'eldoc-documentation-function)
9246 #'markdown-eldoc-function)
9247 (setq-local eldoc-documentation-function #'markdown-eldoc-function))
9248 ;; Inhibiting line-breaking:
9249 ;; Separating out each condition into a separate function so that users can
9250 ;; override if desired (with remove-hook)
9251 (add-hook 'fill-nobreak-predicate
9252 #'markdown-line-is-reference-definition-p nil t)
9253 (add-hook 'fill-nobreak-predicate
9254 #'markdown-pipe-at-bol-p nil t)
9256 ;; Indentation
9257 (setq-local indent-line-function markdown-indent-function)
9259 ;; Flyspell
9260 (setq-local flyspell-generic-check-word-predicate
9261 #'markdown-flyspell-check-word-p)
9263 ;; Electric quoting
9264 (add-hook 'electric-quote-inhibit-functions
9265 #'markdown--inhibit-electric-quote nil :local)
9267 ;; Backwards compatibility with markdown-css-path
9268 (when (boundp 'markdown-css-path)
9269 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
9270 (add-to-list 'markdown-css-paths markdown-css-path))
9272 ;; Prepare hooks for XEmacs compatibility
9273 (when (featurep 'xemacs)
9274 (make-local-hook 'after-change-functions)
9275 (make-local-hook 'font-lock-extend-region-functions)
9276 (make-local-hook 'window-configuration-change-hook))
9278 ;; Make checkboxes buttons
9279 (when markdown-make-gfm-checkboxes-buttons
9280 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
9281 (add-hook 'after-change-functions #'markdown-gfm-checkbox-after-change-function t t)
9282 (add-hook 'change-major-mode-hook #'markdown-remove-gfm-checkbox-overlays t t))
9284 ;; edit-indirect
9285 (add-hook 'edit-indirect-after-commit-functions
9286 #'markdown--edit-indirect-after-commit-function
9287 nil 'local)
9289 ;; Marginalized headings
9290 (when markdown-marginalize-headers
9291 (add-hook 'window-configuration-change-hook
9292 #'markdown-marginalize-update-current nil t))
9294 ;; add live preview export hook
9295 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
9296 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
9298 ;;;###autoload
9299 (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode) t)
9300 ;;;###autoload
9301 (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode) t)
9304 ;;; GitHub Flavored Markdown Mode ============================================
9306 (defvar gfm-mode-hook nil
9307 "Hook run when entering GFM mode.")
9309 ;;;###autoload
9310 (define-derived-mode gfm-mode markdown-mode "GFM"
9311 "Major mode for editing GitHub Flavored Markdown files."
9312 (setq markdown-link-space-sub-char "-")
9313 (setq markdown-wiki-link-search-subdirectories t)
9314 (setq-local markdown-table-at-point-p-function 'gfm--table-at-point-p)
9315 (markdown-gfm-parse-buffer-for-languages))
9317 (define-obsolete-variable-alias
9318 'gfm-font-lock-keywords
9319 'markdown-mode-font-lock-keywords "v2.4")
9322 ;;; Viewing modes
9324 (defcustom markdown-hide-markup-in-view-modes t
9325 "Enable hidden markup mode in `markdown-view-mode' and `gfm-view-mode'."
9326 :group 'markdown
9327 :type 'boolean
9328 :safe 'booleanp)
9330 (defvar markdown-view-mode-map
9331 (let ((map (make-sparse-keymap)))
9332 (define-key map (kbd "p") #'markdown-outline-previous)
9333 (define-key map (kbd "n") #'markdown-outline-next)
9334 (define-key map (kbd "f") #'markdown-outline-next-same-level)
9335 (define-key map (kbd "b") #'markdown-outline-previous-same-level)
9336 (define-key map (kbd "u") #'markdown-outline-up)
9337 (define-key map (kbd "DEL") #'scroll-down-command)
9338 (define-key map (kbd "SPC") #'scroll-up-command)
9339 (define-key map (kbd ">") #'end-of-buffer)
9340 (define-key map (kbd "<") #'beginning-of-buffer)
9341 (define-key map (kbd "q") #'kill-this-buffer)
9342 (define-key map (kbd "?") #'describe-mode)
9343 map)
9344 "Keymap for `markdown-view-mode'.")
9346 (define-derived-mode markdown-view-mode markdown-mode "Markdown-View"
9347 "Major mode for viewing Markdown content."
9348 (setq-local markdown-hide-markup markdown-hide-markup-in-view-modes)
9349 (read-only-mode 1))
9351 (defvar gfm-view-mode-map
9352 markdown-view-mode-map
9353 "Keymap for `gfm-view-mode'.")
9355 (define-derived-mode gfm-view-mode gfm-mode "GFM-View"
9356 "Major mode for viewing GitHub Flavored Markdown content."
9357 (setq-local markdown-hide-markup markdown-hide-markup-in-view-modes)
9358 (read-only-mode 1))
9361 ;;; Live Preview Mode ============================================
9362 (define-minor-mode markdown-live-preview-mode
9363 "Toggle native previewing on save for a specific markdown file."
9364 :lighter " MD-Preview"
9365 (if markdown-live-preview-mode
9366 (if (markdown-live-preview-get-filename)
9367 (markdown-display-buffer-other-window (markdown-live-preview-export))
9368 (markdown-live-preview-mode -1)
9369 (user-error "Buffer %s does not visit a file" (current-buffer)))
9370 (markdown-live-preview-remove)))
9373 (provide 'markdown-mode)
9375 ;; Local Variables:
9376 ;; indent-tabs-mode: nil
9377 ;; coding: utf-8
9378 ;; End:
9379 ;;; markdown-mode.el ends here