Clarify markdown-code-block-at-point-p
[markdown-mode.git] / markdown-mode.el
blob56f92d5597d7412e96bd02a1969d0c3c92824f93
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 <jrblevin@sdf.org>
7 ;; Maintainer: Jason R. Blevins <jrblevin@sdf.org>
8 ;; Created: May 24, 2007
9 ;; Version: 2.1
10 ;; Package-Requires: ((emacs "24") (cl-lib "0.5"))
11 ;; Keywords: Markdown, GitHub Flavored Markdown, itex
12 ;; URL: http://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 2, or (at your option)
19 ;; 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, write to the Free Software
28 ;; Foundation, Inc., 51 Franklin Street, Fifth Floor,
29 ;; Boston, MA 02110-1301, USA.
31 ;;; Commentary:
33 ;; markdown-mode is a major mode for editing [Markdown][]-formatted
34 ;; text. The latest stable version is markdown-mode 2.1, released on
35 ;; January 9, 2016. See the [release notes][] for details.
36 ;; markdown-mode is free software, licensed under the GNU GPL.
38 ;; ![Markdown Mode Screenshot](http://jblevins.org/projects/markdown-mode/screenshots/20160108-001.png)
40 ;; [Markdown]: http://daringfireball.net/projects/markdown/
41 ;; [release notes]: http://jblevins.org/projects/markdown-mode/rev-2-1
43 ;;; Installation:
45 ;; The recommended way to install markdown-mode is to install the package
46 ;; from [MELPA Stable](https://stable.melpa.org/#/markdown-mode)
47 ;; using `package.el'. First, configure `package.el' and the MELPA Stable
48 ;; repository by adding the following to your `.emacs', `init.el',
49 ;; or equivalent startup file:
51 ;; (require 'package)
52 ;; (add-to-list 'package-archives
53 ;; '("melpa-stable" . "https://stable.melpa.org/packages/"))
54 ;; (package-initialize)
56 ;; Then, after restarting Emacs or evaluating the above statements, issue
57 ;; the following command: `M-x package-install RET markdown-mode RET`.
58 ;; When installed this way, the major modes `markdown-mode' and `gfm-mode'
59 ;; will be autoloaded and `markdown-mode' will be used for file names
60 ;; ending in either `.md` or `.markdown`.
62 ;; Alternatively, if you manage loading packages with [use-package][]
63 ;; then you can automatically install and configure `markdown-mode' by
64 ;; adding a declaration such as this one to your init file (as an
65 ;; example; adjust settings as desired):
67 ;; (use-package markdown-mode
68 ;; :ensure t
69 ;; :commands (markdown-mode gfm-mode)
70 ;; :mode (("README\\.md\\'" . gfm-mode)
71 ;; ("\\.md\\'" . markdown-mode)
72 ;; ("\\.markdown\\'" . markdown-mode))
73 ;; :init (setq markdown-command "multimarkdown"))
75 ;; [MELPA Stable]: http://stable.melpa.org/
76 ;; [use-package]: https://github.com/jwiegley/use-package
78 ;; **Direct Download**
80 ;; Alternatively you can manually download and install markdown-mode.
81 ;; First, download the [latest stable version][markdown-mode.el] and
82 ;; save the file where Emacs can find it (i.e., a directory in your
83 ;; `load-path'). You can then configure `markdown-mode' and `gfm-mode'
84 ;; to load automatically by adding the following to your init file:
86 ;; (autoload 'markdown-mode "markdown-mode"
87 ;; "Major mode for editing Markdown files" t)
88 ;; (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode))
89 ;; (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode))
91 ;; (autoload 'gfm-mode "markdown-mode"
92 ;; "Major mode for editing GitHub Flavored Markdown files" t)
93 ;; (add-to-list 'auto-mode-alist '("README\\.md\\'" . gfm-mode))
95 ;; [markdown-mode.el]: http://jblevins.org/projects/markdown-mode/markdown-mode.el
97 ;; **Development Version**
99 ;; To follow or contribute to markdown-mode development, you can
100 ;; browse or clone the Git repository
101 ;; [on GitHub](https://github.com/jrblevin/markdown-mode):
103 ;; git clone https://github.com/jrblevin/markdown-mode.git
105 ;; If you prefer to install and use the development version, which may
106 ;; become unstable at some times, you can either clone the Git
107 ;; repository as above or install markdown-mode from
108 ;; [MELPA](https://melpa.org/#/markdown-mode).
110 ;; If you clone the repository directly, then make sure that Emacs can
111 ;; find it by adding the following line to your startup file:
113 ;; (add-to-list 'load-path "/path/to/markdown-mode/repository")
115 ;; **Packaged Installation**
117 ;; markdown-mode is also available in several package managers. You
118 ;; may want to confirm that the package you install contains the
119 ;; latest stable version first (and please notify the package
120 ;; maintainer if not).
122 ;; * Debian Linux: [elpa-markdown-mode][] and [emacs-goodies-el][]
123 ;; * Ubuntu Linux: [elpa-markdown-mode][elpa-ubuntu] and [emacs-goodies-el][emacs-goodies-el-ubuntu]
124 ;; * RedHat and Fedora Linux: [emacs-goodies][]
125 ;; * NetBSD: [textproc/markdown-mode][]
126 ;; * MacPorts: [markdown-mode.el][macports-package] ([pending][macports-ticket])
127 ;; * FreeBSD: [textproc/markdown-mode.el][freebsd-port]
129 ;; [elpa-markdown-mode]: https://packages.debian.org/sid/lisp/elpa-markdown-mode
130 ;; [elpa-ubuntu]: http://packages.ubuntu.com/search?keywords=elpa-markdown-mode
131 ;; [emacs-goodies-el]: http://packages.debian.org/emacs-goodies-el
132 ;; [emacs-goodies-el-ubuntu]: http://packages.ubuntu.com/search?keywords=emacs-goodies-el
133 ;; [emacs-goodies]: https://apps.fedoraproject.org/packages/emacs-goodies
134 ;; [textproc/markdown-mode]: http://pkgsrc.se/textproc/markdown-mode
135 ;; [macports-package]: https://trac.macports.org/browser/trunk/dports/editors/markdown-mode.el/Portfile
136 ;; [macports-ticket]: http://trac.macports.org/ticket/35716
137 ;; [freebsd-port]: http://svnweb.freebsd.org/ports/head/textproc/markdown-mode.el
139 ;; **Dependencies**
141 ;; `markdown-mode' depends on `cl-lib', which has been bundled with
142 ;; GNU Emacs since 24.3. Users of GNU Emacs 24.1 and 24.2 can install
143 ;; `cl-lib' with `package.el'.
145 ;;; Usage:
147 ;; Keybindings are grouped by prefixes based on their function. For
148 ;; example, the commands for inserting links are grouped under `C-c
149 ;; C-a`, where the `C-a` is a mnemonic for the HTML `<a>` tag. In
150 ;; other cases, the connection to HTML is not direct. For example,
151 ;; commands dealing with headings begin with `C-c C-t` (mnemonic:
152 ;; titling). The primary commands in each group will are described
153 ;; below. You can obtain a list of all keybindings by pressing `C-c
154 ;; C-h`. Movement and shifting commands tend to be associated with
155 ;; paired delimiters such as `M-{` and `M-}` or `C-c <` and `C-c >`.
156 ;; Outline navigation keybindings the same as in `org-mode'. Finally,
157 ;; commands for running Markdown or doing maintenance on an open file
158 ;; are grouped under the `C-c C-c` prefix. The most commonly used
159 ;; commands are described below. You can obtain a list of all
160 ;; keybindings by pressing `C-c C-h`.
162 ;; * Hyperlinks: `C-c C-a`
164 ;; In this group, `C-c C-a l` inserts an inline link of the form
165 ;; `[text](url)`. The link text is determined as follows. First,
166 ;; if there is an active region (i.e., when transient mark mode is
167 ;; on and the mark is active), use it as the link text. Second,
168 ;; if the point is at a word, use that word as the link text. In
169 ;; these two cases, the original text will be replaced with the
170 ;; link and point will be left at the position for inserting a
171 ;; URL. Otherwise, insert empty link markup and place the point
172 ;; for inserting the link text.
174 ;; `C-c C-a L` inserts a reference link of the form `[text][label]`
175 ;; and, optionally, a corresponding reference label definition.
176 ;; The link text is determined in the same way as with an inline
177 ;; link (using the region, when active, or the word at the point),
178 ;; but instead of inserting empty markup as a last resort, the
179 ;; link text will be read from the minibuffer. The reference
180 ;; label will be read from the minibuffer in both cases, with
181 ;; completion from the set of currently defined references. To
182 ;; create an implicit reference link, press `RET` to accept the
183 ;; default, an empty label. If the entered referenced label is
184 ;; not defined, additionally prompt for the URL and (optional)
185 ;; title. If a URL is provided, a reference definition will be
186 ;; inserted in accordance with `markdown-reference-location'.
187 ;; If a title is given, it will be added to the end of the
188 ;; reference definition and will be used to populate the title
189 ;; attribute when converted to XHTML.
191 ;; `C-c C-a u` inserts a bare url, delimited by angle brackets. When
192 ;; there is an active region, the text in the region is used as the
193 ;; URL. If the point is at a URL, that url is used. Otherwise,
194 ;; insert angle brackets and position the point in between them
195 ;; for inserting the URL.
197 ;; `C-c C-a f` inserts a footnote marker at the point, inserts a
198 ;; footnote definition below, and positions the point for
199 ;; inserting the footnote text. Note that footnotes are an
200 ;; extension to Markdown and are not supported by all processors.
202 ;; `C-c C-a w` behaves much like the inline link insertion command
203 ;; and inserts a wiki link of the form `[[WikiLink]]`. If there
204 ;; is an active region, use the region as the link text. If the
205 ;; point is at a word, use the word as the link text. If there is
206 ;; no active region and the point is not at word, simply insert
207 ;; link markup. Note that wiki links are an extension to Markdown
208 ;; and are not supported by all processors.
210 ;; * Images: `C-c C-i`
212 ;; `C-c C-i i` inserts markup for an inline image, using the
213 ;; active region or the word at point, if any, as the alt text.
214 ;; `C-c C-i I` behaves similarly and inserts a reference-style
215 ;; image.
217 ;; Local images associated with image links may be displayed
218 ;; inline in the buffer by pressing `C-c C-i C-t`
219 ;; (`markdown-toggle-inline-images'). This is a toggle command, so
220 ;; pressing this once again will remove inline images.
222 ;; * Styles: `C-c C-s`
224 ;; `C-c C-s e` inserts markup to make a region or word italic (`e`
225 ;; for `<em>` or emphasis). If there is an active region, make
226 ;; the region italic. If the point is at a non-italic word, make
227 ;; the word italic. If the point is at an italic word or phrase,
228 ;; remove the italic markup. Otherwise, simply insert italic
229 ;; delimiters and place the cursor in between them. Similarly,
230 ;; use `C-c C-s s` for bold (`<strong>`), `C-c C-s c` for
231 ;; inline code (`<code>`), and `C-c C-s k` for inserting `<kbd>`
232 ;; tags.
234 ;; `C-c C-s b` inserts a blockquote using the active region, if any,
235 ;; or starts a new blockquote. `C-c C-s C-b` is a variation which
236 ;; always operates on the region, regardless of whether it is
237 ;; active or not. The appropriate amount of indentation, if any,
238 ;; is calculated automatically given the surrounding context, but
239 ;; may be adjusted later using the region indentation commands.
241 ;; `C-c C-s p` behaves similarly for inserting preformatted code
242 ;; blocks, with `C-c C-s C-p` being the region-only counterpart.
244 ;; * Headings: `C-c C-t`
246 ;; All heading insertion commands use the text in the active
247 ;; region, if any, as the heading text. Otherwise, if the current
248 ;; line is not blank, they use the text on the current line.
249 ;; Finally, the setext commands will prompt for heading text if
250 ;; there is no active region and the current line is blank.
252 ;; `C-c C-t h` inserts a heading with automatically chosen type and
253 ;; level (both determined by the previous heading). `C-c C-t H`
254 ;; behaves similarly, but uses setext (underlined) headings when
255 ;; possible, still calculating the level automatically.
256 ;; In cases where the automatically-determined level is not what
257 ;; you intended, the level can be quickly promoted or demoted
258 ;; (as described below). Alternatively, a `C-u` prefix can be
259 ;; given to insert a heading promoted by one level or a `C-u C-u`
260 ;; prefix can be given to insert a heading demoted by one level.
262 ;; To insert a heading of a specific level and type, use `C-c C-t 1`
263 ;; through `C-c C-t 6` for atx (hash mark) headings and `C-c C-t !` or
264 ;; `C-c C-t @` for setext headings of level one or two, respectively.
265 ;; Note that `!` is `S-1` and `@` is `S-2`.
267 ;; If the point is at a heading, these commands will replace the
268 ;; existing markup in order to update the level and/or type of the
269 ;; heading. To remove the markup of the heading at the point,
270 ;; press `C-c C-k` to kill the heading and press `C-y` to yank the
271 ;; heading text back into the buffer.
273 ;; * Horizontal Rules: `C-c -`
275 ;; `C-c -` inserts a horizontal rule. By default, insert the
276 ;; first string in the list `markdown-hr-strings' (the most
277 ;; prominent rule). With a `C-u` prefix, insert the last string.
278 ;; With a numeric prefix `N`, insert the string in position `N`
279 ;; (counting from 1).
281 ;; * Markdown and Maintenance Commands: `C-c C-c`
283 ;; *Compile:* `C-c C-c m` will run Markdown on the current buffer
284 ;; and show the output in another buffer. *Preview*: `C-c C-c p`
285 ;; runs Markdown on the current buffer and previews, stores the
286 ;; output in a temporary file, and displays the file in a browser.
287 ;; *Export:* `C-c C-c e` will run Markdown on the current buffer
288 ;; and save the result in the file `basename.html`, where
289 ;; `basename` is the name of the Markdown file with the extension
290 ;; removed. *Export and View:* press `C-c C-c v` to export the
291 ;; file and view it in a browser. *Open:* `C-c C-c o` will open
292 ;; the Markdown source file directly using `markdown-open-command'.
293 ;; *Live Export*: Press `C-c C-c l` to turn on
294 ;; `markdown-live-preview-mode' to view the exported output
295 ;; side-by-side with the source Markdown. **For all export commands,
296 ;; the output file will be overwritten without notice.**
297 ;; `markdown-live-preview-window-function' can be customized to open
298 ;; in a browser other than `eww'. If you want to force the
299 ;; preview window to appear at the bottom or right, you can
300 ;; customize `markdown-split-window-direction`.
302 ;; To summarize:
304 ;; - `C-c C-c m`: `markdown-command' > `*markdown-output*` buffer.
305 ;; - `C-c C-c p`: `markdown-command' > temporary file > browser.
306 ;; - `C-c C-c e`: `markdown-command' > `basename.html`.
307 ;; - `C-c C-c v`: `markdown-command' > `basename.html` > browser.
308 ;; - `C-c C-c w`: `markdown-command' > kill ring.
309 ;; - `C-c C-c o`: `markdown-open-command'.
310 ;; - `C-c C-c l`: `markdown-live-preview-mode' > `*eww*` buffer.
312 ;; `C-c C-c c` will check for undefined references. If there are
313 ;; any, a small buffer will open with a list of undefined
314 ;; references and the line numbers on which they appear. In Emacs
315 ;; 22 and greater, selecting a reference from this list and
316 ;; pressing `RET` will insert an empty reference definition at the
317 ;; end of the buffer. Similarly, selecting the line number will
318 ;; jump to the corresponding line.
320 ;; `C-c C-c n` renumbers any ordered lists in the buffer that are
321 ;; out of sequence.
323 ;; `C-c C-c ]` completes all headings and normalizes all horizontal
324 ;; rules in the buffer.
326 ;; * Following Links: `C-c C-o`
328 ;; Press `C-c C-o` when the point is on an inline or reference
329 ;; link to open the URL in a browser. When the point is at a
330 ;; wiki link, open it in another buffer (in the current window,
331 ;; or in the other window with the `C-u` prefix). Use `M-p` and
332 ;; `M-n` to quickly jump to the previous or next link of any type.
334 ;; * Jumping: `C-c C-l`
336 ;; Use `C-c C-l` to jump from the object at point to its counterpart
337 ;; elsewhere in the text, when possible. Jumps between reference
338 ;; links and definitions; between footnote markers and footnote
339 ;; text. If more than one link uses the same reference name, a
340 ;; new buffer will be created containing clickable buttons for jumping
341 ;; to each link. You may press `TAB` or `S-TAB` to jump between
342 ;; buttons in this window.
344 ;; * Promotion and Demotion: `C-c C--` and `C-c C-=`
346 ;; Headings, horizontal rules, and list items can be promoted and
347 ;; demoted, as well as bold and italic text. For headings,
348 ;; "promotion" means *decreasing* the level (i.e., moving from
349 ;; `<h2>` to `<h1>`) while "demotion" means *increasing* the
350 ;; level. For horizontal rules, promotion and demotion means
351 ;; moving backward or forward through the list of rule strings in
352 ;; `markdown-hr-strings'. For bold and italic text, promotion and
353 ;; demotion means changing the markup from underscores to asterisks.
354 ;; Press `C-c C--` or `M-LEFT` to promote the element at the point
355 ;; if possible.
357 ;; To remember these commands, note that `-` is for decreasing the
358 ;; level (promoting), and `=` (on the same key as `+`) is for
359 ;; increasing the level (demoting). Similarly, the left and right
360 ;; arrow keys indicate the direction that the atx heading markup
361 ;; is moving in when promoting or demoting.
363 ;; * Completion: `C-c C-]`
365 ;; Complete markup is in normalized form, which means, for
366 ;; example, that the underline portion of a setext header is the
367 ;; same length as the heading text, or that the number of leading
368 ;; and trailing hash marks of an atx header are equal and that
369 ;; there is no extra whitespace in the header text. `C-c C-]`
370 ;; completes the markup at the point, if it is determined to be
371 ;; incomplete.
373 ;; * Editing Lists: `M-RET`, `M-UP`, `M-DOWN`, `M-LEFT`, and `M-RIGHT`
375 ;; New list items can be inserted with `M-RET` or `C-c C-j`. This
376 ;; command determines the appropriate marker (one of the possible
377 ;; unordered list markers or the next number in sequence for an
378 ;; ordered list) and indentation level by examining nearby list
379 ;; items. If there is no list before or after the point, start a
380 ;; new list. Prefix this command by `C-u` to decrease the
381 ;; indentation by one level. Prefix this command by `C-u C-u` to
382 ;; increase the indentation by one level.
384 ;; Existing list items can be moved up or down with `M-UP` or
385 ;; `M-DOWN` and indented or exdented with `M-RIGHT` or `M-LEFT`.
387 ;; * Editing Subtrees: `M-S-UP`, `M-S-DOWN`, `M-S-LEFT`, and `M-S-RIGHT`
389 ;; Entire subtrees of ATX headings can be promoted and demoted
390 ;; with `M-S-LEFT` and `M-S-RIGHT`, which mirror the bindings
391 ;; for promotion and demotion of list items. Similarly, subtrees
392 ;; can be moved up and down with `M-S-UP` and `M-S-DOWN`.
394 ;; Please note the following "boundary" behavior for promotion and
395 ;; demotion. Any level-six headings will not be demoted further
396 ;; (i.e., they remain at level six, since Markdown and HTML define
397 ;; only six levels) and any level-one headings will promoted away
398 ;; entirely (i.e., heading markup will be removed, since a
399 ;; level-zero heading is not defined).
401 ;; * Shifting the Region: `C-c <` and `C-c >`
403 ;; Text in the region can be indented or exdented as a group using
404 ;; `C-c >` to indent to the next indentation point (calculated in
405 ;; the current context), and `C-c <` to exdent to the previous
406 ;; indentation point. These keybindings are the same as those for
407 ;; similar commands in `python-mode'.
409 ;; * Killing Elements: `C-c C-k`
411 ;; Press `C-c C-k` to kill the thing at point and add important
412 ;; text, without markup, to the kill ring. Possible things to
413 ;; kill include (roughly in order of precedece): inline code,
414 ;; headings, horizonal rules, links (add link text to kill ring),
415 ;; images (add alt text to kill ring), angle URIs, email
416 ;; addresses, bold, italics, reference definitions (add URI to
417 ;; kill ring), footnote markers and text (kill both marker and
418 ;; text, add text to kill ring), and list items.
420 ;; * Outline Navigation: `C-c C-n`, `C-c C-p`, `C-c C-f`, `C-c C-b`, and `C-c C-u`
422 ;; Navigation between headings is possible using `outline-mode'.
423 ;; Use `C-c C-n` and `C-c C-p` to move between the next and previous
424 ;; visible headings. Similarly, `C-c C-f` and `C-c C-b` move to the
425 ;; next and previous visible headings at the same level as the one
426 ;; at the point. Finally, `C-c C-u` will move up to a lower-level
427 ;; (higher precedence) visible heading.
429 ;; * Movement by Paragraph: `M-{` and `M-}`
431 ;; The definition of a "paragraph" is slightly different in
432 ;; markdown-mode than, say, text-mode, because markdown-mode
433 ;; supports filling for list items and respects hard line breaks,
434 ;; both of which break paragraphs. Therefore, the usual the usual
435 ;; paragraph movement commands `M-{` and `M-}`
436 ;; (`backward-paragraph` and `forward-paragraph`) will move by the
437 ;; same units. To mark a "paragraph", use `M-h` (`mark-paragraph`).
439 ;; * Movement by Defun: `C-M-a`, `C-M-e`, and `C-M-h`
441 ;; The usual Emacs commands can be used to move by defuns
442 ;; (top-level major definitions). In markdown-mode, a defun is a
443 ;; section. As usual, `C-M-a` will move the point to the
444 ;; beginning of the current or preceding defun, `C-M-e` will move
445 ;; to the end of the current or following defun, and `C-M-h` will
446 ;; put the region around the entire defun.
448 ;; As noted, many of the commands above behave differently depending
449 ;; on whether Transient Mark mode is enabled or not. When it makes
450 ;; sense, if Transient Mark mode is on and the region is active, the
451 ;; command applies to the text in the region (e.g., `C-c C-s s` makes the
452 ;; region bold). For users who prefer to work outside of Transient
453 ;; Mark mode, since Emacs 22 it can be enabled temporarily by pressing
454 ;; `C-SPC C-SPC`. When this is not the case, many commands then
455 ;; proceed to look work with the word or line at the point.
457 ;; When applicable, commands that specifically act on the region even
458 ;; outside of Transient Mark mode have the same keybinding as their
459 ;; standard counterpart, but the letter is uppercase. For example,
460 ;; `markdown-insert-blockquote' is bound to `C-c C-s b` and only acts on
461 ;; the region in Transient Mark mode while `markdown-blockquote-region'
462 ;; is bound to `C-c C-s B` and always applies to the region (when nonempty).
464 ;; Note that these region-specific functions are useful in many
465 ;; cases where it may not be obvious. For example, yanking text from
466 ;; the kill ring sets the mark at the beginning of the yanked text
467 ;; and moves the point to the end. Therefore, the (inactive) region
468 ;; contains the yanked text. So, `C-y` followed by `C-c C-s C-b` will
469 ;; yank text and turn it into a blockquote.
471 ;; markdown-mode attempts to be flexible in how it handles
472 ;; indentation. When you press `TAB` repeatedly, the point will cycle
473 ;; through several possible indentation levels corresponding to things
474 ;; you might have in mind when you press `RET` at the end of a line or
475 ;; `TAB`. For example, you may want to start a new list item,
476 ;; continue a list item with hanging indentation, indent for a nested
477 ;; pre block, and so on. Exdention is handled similarly when backspace
478 ;; is pressed at the beginning of the non-whitespace portion of a line.
480 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
481 ;; visibility cycling for atx- or hash-style headings. There are two
482 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
483 ;; the table of contents view (headings only), outline view (top-level
484 ;; headings only), and the full document view. Pressing `TAB` while the
485 ;; point is at a heading will cycle through levels of visibility for the
486 ;; subtree: completely folded, visible children, and fully visible.
487 ;; Note that mixing hash and underline style headings will give undesired
488 ;; results.
490 ;;; Customization:
492 ;; Although no configuration is *necessary* there are a few things
493 ;; that can be customized. The `M-x customize-mode` command
494 ;; provides an interface to all of the possible customizations:
496 ;; * `markdown-command' - the command used to run Markdown (default:
497 ;; `markdown`). This variable may be customized to pass
498 ;; command-line options to your Markdown processor of choice.
500 ;; * `markdown-command-needs-filename' - set to `t' if
501 ;; `markdown-command' does not accept standard input (default:
502 ;; `nil'). When `nil', `markdown-mode' will pass the Markdown
503 ;; content to `markdown-command' using standard input (`stdin`).
504 ;; When set to `t', `markdown-mode' will pass the name of the file
505 ;; as the final command-line argument to `markdown-command'. Note
506 ;; that in the latter case, you will only be able to run
507 ;; `markdown-command' from buffers which are visiting a file.
509 ;; * `markdown-open-command' - the command used for calling a standalone
510 ;; Markdown previewer which is capable of opening Markdown source files
511 ;; directly (default: `nil'). This command will be called
512 ;; with a single argument, the filename of the current buffer.
513 ;; A representative program is the Mac app [Marked 2][], a
514 ;; live-updating Markdown previewer which can be [called from a
515 ;; simple shell script](http://jblevins.org/log/marked-2-command).
517 ;; * `markdown-hr-strings' - list of strings to use when inserting
518 ;; horizontal rules. Different strings will not be distinguished
519 ;; when converted to HTML--they will all be converted to
520 ;; `<hr/>`--but they may add visual distinction and style to plain
521 ;; text documents. To maintain some notion of promotion and
522 ;; demotion, keep these sorted from largest to smallest.
524 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
525 ;; underscores when inserting bold text instead of two asterisks
526 ;; (default: `nil').
528 ;; * `markdown-italic-underscore' - set to a non-nil value to use
529 ;; underscores when inserting italic text instead of asterisks
530 ;; (default: `nil').
532 ;; * `markdown-asymmetric-header' - set to a non-nil value to use
533 ;; asymmetric header styling, placing header characters only on
534 ;; the left of headers (default: `nil').
536 ;; * `markdown-header-scaling' - set to a non-nil value to use
537 ;; a variable-pitch font for headings where the size corresponds
538 ;; to the level of the heading (default: `nil').
540 ;; * `markdown-header-scaling-values' - list of scaling values,
541 ;; relative to baseline, for headers of levels one through six,
542 ;; used when `markdown-header-scaling' is non-nil
543 ;; (default: `(list 1.8 1.4 1.2 1.0 1.0 1.0)`).
545 ;; * `markdown-list-indent-width' - depth of indentation for lists
546 ;; when inserting, promoting, and demoting list items (default: 4).
548 ;; * `markdown-indent-function' - the function to use for automatic
549 ;; indentation (default: `markdown-indent-line').
551 ;; * `markdown-indent-on-enter' - set to a non-nil value to
552 ;; automatically indent new lines and/or continue lists when the
553 ;; enter key is pressed (default: `t')
555 ;; * `markdown-enable-wiki-links' - syntax highlighting for wiki
556 ;; links (default: `nil'). Set this to a non-nil value to turn on
557 ;; wiki link support by default. Wiki link support can be toggled
558 ;; later using the function `markdown-toggle-wiki-links'."
560 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
561 ;; treat aliased wiki links like `[[link text|PageName]]`
562 ;; (default: `t'). When set to nil, they will be treated as
563 ;; `[[PageName|link text]]'.
565 ;; * `markdown-uri-types' - a list of protocol schemes (e.g., "http")
566 ;; for URIs that `markdown-mode' should highlight.
568 ;; * `markdown-enable-math' - syntax highlighting for LaTeX
569 ;; fragments (default: `nil'). Set this to `t' to turn on math
570 ;; support by default. Math support can be enabled, disabled, or
571 ;; toggled later using the function `markdown-toggle-math'."
573 ;; * `markdown-css-paths' - CSS files to link to in XHTML output
574 ;; (default: `nil`).
576 ;; * `markdown-content-type' - when set to a nonempty string, an
577 ;; `http-equiv` attribute will be included in the XHTML `<head>`
578 ;; block (default: `""`). If needed, the suggested values are
579 ;; `application/xhtml+xml` or `text/html`. See also:
580 ;; `markdown-coding-system'.
582 ;; * `markdown-coding-system' - used for specifying the character
583 ;; set identifier in the `http-equiv` attribute when included
584 ;; (default: `nil'). See `markdown-content-type', which must
585 ;; be set before this variable has any effect. When set to `nil',
586 ;; `buffer-file-coding-system' will be used to automatically
587 ;; determine the coding system string (falling back to
588 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
589 ;; and `iso-latin-1'.
591 ;; * `markdown-xhtml-header-content' - additional content to include
592 ;; in the XHTML `<head>` block (default: `""`).
594 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
595 ;; `markdown-mode' uses to determine whether the output of
596 ;; `markdown-command' is a standalone XHTML document or an XHTML
597 ;; fragment (default: `"^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"`). If
598 ;; this regular expression not matched in the first five lines of
599 ;; output, `markdown-mode' assumes the output is a fragment and
600 ;; adds a header and footer.
602 ;; * `markdown-link-space-sub-char' - a character to replace spaces
603 ;; when mapping wiki links to filenames (default: `"_"`).
604 ;; For example, use an underscore for compatibility with the
605 ;; Python Markdown WikiLinks extension. In `gfm-mode', this is
606 ;; set to `"-"` to conform with GitHub wiki links.
608 ;; * `markdown-reference-location' - where to insert reference
609 ;; definitions (default: `header`). The possible locations are
610 ;; the end of the document (`end`), after the current block
611 ;; (`immediately`), before the next header (`header`).
613 ;; * `markdown-footnote-location' - where to insert footnote text
614 ;; (default: `end`). The set of location options is the same as
615 ;; for `markdown-reference-location'.
617 ;; * `markdown-nested-imenu-heading-index' - Use nested imenu
618 ;; heading instead of a flat index (default: `nil'). A nested
619 ;; index may provide more natural browsing from the menu, but a
620 ;; flat list may allow for faster keyboard navigation via tab
621 ;; completion.
623 ;; * `comment-auto-fill-only-comments' - variable is made
624 ;; buffer-local and set to `nil' by default. In programming
625 ;; language modes, when this variable is non-nil, only comments
626 ;; will be filled by auto-fill-mode. However, comments in
627 ;; Markdown documents are rare and the most users probably intend
628 ;; for the actual content of the document to be filled. Making
629 ;; this variable buffer-local allows `markdown-mode' to override
630 ;; the default behavior induced when the global variable is non-nil.
632 ;; * `markdown-gfm-additional-languages', - additional languages to
633 ;; make available, aside from those predefined in
634 ;; `markdown-gfm-recognized-languages', when inserting GFM code
635 ;; blocks (default: `nil`). Language strings must have be trimmed
636 ;; of whitespace and not contain any curly braces. They may be of
637 ;; arbitrary capitalization, though.
639 ;; * `markdown-gfm-use-electric-backquote' - use
640 ;; `markdown-electric-backquote' for interactive insertion of GFM
641 ;; code blocks when backquote is pressed three times (default: `t`).
643 ;; * `markdown-make-gfm-checkboxes-buttons' - Whether GitHub
644 ;; Flavored Markdown style task lists (checkboxes) should be
645 ;; turned into buttons that can be toggled with mouse-1 or RET. If
646 ;; non-nil (default), then buttons are enabled. This works in
647 ;; `markdown-mode' as well as `gfm-mode'.
649 ;; Additionally, the faces used for syntax highlighting can be modified to
650 ;; your liking by issuing `M-x customize-group RET markdown-faces`
651 ;; or by using the "Markdown Faces" link at the bottom of the mode
652 ;; customization screen.
654 ;; [Marked 2]: https://itunes.apple.com/us/app/marked-2/id890031187?mt=12&uo=4&at=11l5Vs&ct=mm
656 ;;; Extensions:
658 ;; Besides supporting the basic Markdown syntax, Markdown Mode also
659 ;; includes syntax highlighting for `[[Wiki Links]]`. This can be
660 ;; enabled by setting `markdown-enable-wiki-links' to a non-nil value.
661 ;; Wiki links may be followed by pressing `C-c C-o` when the point
662 ;; is at a wiki link. Use `M-p` and `M-n` to quickly jump to the
663 ;; previous and next links (including links of other types).
664 ;; Aliased or piped wiki links of the form `[[link text|PageName]]`
665 ;; are also supported. Since some wikis reverse these components, set
666 ;; `markdown-wiki-link-alias-first' to nil to treat them as
667 ;; `[[PageName|link text]]`. If `markdown-wiki-link-fontify-missing'
668 ;; is also non-nil, Markdown Mode will highlight wiki links with
669 ;; missing target file in a different color. By default, Markdown
670 ;; Mode only searches for target files in the current directory.
671 ;; Search in subdirectories can be enabled by setting
672 ;; `markdown-wiki-link-search-subdirectories' to a non-nil value.
673 ;; Sequential parent directory search (as in [Ikiwiki][]) can be
674 ;; enabled by setting `markdown-wiki-link-search-parent-directories'
675 ;; to a non-nil value.
677 ;; [Ikiwiki]: https://ikiwiki.info
679 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
680 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
681 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
682 ;; You can do this either by using `M-x customize-group markdown`
683 ;; or by placing the following in your `.emacs` file:
685 ;; (setq markdown-command "markdown | smartypants")
687 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
689 ;; Syntax highlighting for mathematical expressions written
690 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
691 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
692 ;; either via customize or by placing `(setq markdown-enable-math t)`
693 ;; in `.emacs`, and then restarting Emacs or calling
694 ;; `markdown-reload-extensions'.
696 ;;; GitHub Flavored Markdown (GFM):
698 ;; A [GitHub Flavored Markdown][GFM] mode, `gfm-mode', is also
699 ;; available. The GitHub implementation differs slightly from
700 ;; standard Markdown in that it supports things like different
701 ;; behavior for underscores inside of words, automatic linking of
702 ;; URLs, strikethrough text, and fenced code blocks with an optional
703 ;; language keyword.
705 ;; The GFM-specific features above apply to `README.md` files, wiki
706 ;; pages, and other Markdown-formatted files in repositories on
707 ;; GitHub. GitHub also enables [additional features][GFM comments] for
708 ;; writing on the site (for issues, pull requests, messages, etc.)
709 ;; that are further extensions of GFM. These features include task
710 ;; lists (checkboxes), newlines corresponding to hard line breaks,
711 ;; auto-linked references to issues and commits, wiki links, and so
712 ;; on. To make matters more confusing, although task lists are not
713 ;; part of [GFM proper][GFM], [since 2014][] they are rendered (in a
714 ;; read-only fashion) in all Markdown documents in repositories on the
715 ;; site. These additional extensions are supported to varying degrees
716 ;; by `markdown-mode' and `gfm-mode' as described below.
718 ;; * **URL autolinking:** Both `markdown-mode' and `gfm-mode' support
719 ;; highlighting of URLs without angle brackets.
721 ;; * **Multiple underscores in words:** You must enable `gfm-mode' to
722 ;; toggle support for underscores inside of words. In this mode
723 ;; variable names such as `a_test_variable` will not trigger
724 ;; emphasis (italics).
726 ;; * **Fenced code blocks:** Code blocks quoted with backquotes, with
727 ;; optional programming language keywords, are highlighted in
728 ;; both `markdown-mode' and `gfm-mode'. They can be inserted with
729 ;; `C-c C-s P`. If there is an active region, the text in the
730 ;; region will be placed inside the code block. You will be
731 ;; prompted for the name of the language, but may press enter to
732 ;; continue without naming a language.
734 ;; * **Strikethrough:** Strikethrough text is only supported in
735 ;; `gfm-mode' and can be inserted (and toggled) using `C-c C-s d`.
736 ;; Following the mnemonics for the other style keybindings, the
737 ;; letter `d` coincides with the HTML tag `<del>`.
739 ;; * **Task lists:** GFM task lists will be rendered as checkboxes
740 ;; (Emacs buttons) in both `markdown-mode' and `gfm-mode' when
741 ;; `markdown-make-gfm-checkboxes-buttons' is set to a non-nil value
742 ;; (and it is set to t by default). These checkboxes can be
743 ;; toggled by clicking `mouse-1`, pressing `RET` over the button,
744 ;; or by pressing `C-c C-x C-x` with the point anywhere in the task
745 ;; list item.
747 ;; * **Wiki links:** Generic wiki links are supported in
748 ;; `markdown-mode', but in `gfm-mode' specifically they will be
749 ;; treated as they are on GitHub: spaces will be replaced by hyphens
750 ;; in filenames and the first letter of the filename will be
751 ;; capitalized. For example, `[[wiki link]]' will map to a file
752 ;; named `Wiki-link` with the same extension as the current file.
753 ;; If a file with this name does not exist in the current directory,
754 ;; the first match in a subdirectory, if any, will be used instead.
756 ;; * **Newlines:** Neither `markdown-mode' nor `gfm-mode' do anything
757 ;; specifically with respect to newline behavior. If you use
758 ;; `gfm-mode' mostly to write text for comments or issues on the
759 ;; GitHub site--where newlines are significant and correspond to
760 ;; hard line breaks--then you may want to enable `visual-line-mode'
761 ;; for line wrapping in buffers. You can do this with a
762 ;; `gfm-mode-hook' as follows:
764 ;; ;; Use visual-line-mode in gfm-mode
765 ;; (defun my-gfm-mode-hook ()
766 ;; (visual-line-mode 1))
767 ;; (add-hook 'gfm-mode-hook 'my-gfm-mode-hook)
769 ;; * **Preview:** GFM-specific preview can be powered by setting
770 ;; `markdown-command' to use [Docter][]. This may also be
771 ;; configured to work with [Marked 2][] for `markdown-open-command'.
773 ;; [GFM]: http://github.github.com/github-flavored-markdown/
774 ;; [GFM comments]: https://help.github.com/articles/writing-on-github/
775 ;; [since 2014]: https://github.com/blog/1825-task-lists-in-all-markdown-documents
776 ;; [Docter]: https://github.com/alampros/Docter
778 ;;; Acknowledgments:
780 ;; markdown-mode has benefited greatly from the efforts of the many
781 ;; volunteers who have sent patches, test cases, bug reports,
782 ;; suggestions, helped with packaging, etc. Thank you for your
783 ;; contributions! See the [contributors graph][contrib] for details.
785 ;; [contrib]: https://github.com/jrblevin/markdown-mode/graphs/contributors
787 ;;; Bugs:
789 ;; markdown-mode is developed and tested primarily for compatibility
790 ;; with GNU Emacs 24.3 and later. If you find any bugs in
791 ;; markdown-mode, please construct a test case or a patch and open a
792 ;; ticket on the [GitHub issue tracker][issues].
794 ;; [issues]: https://github.com/jrblevin/markdown-mode/issues
796 ;;; History:
798 ;; markdown-mode was written and is maintained by Jason Blevins. The
799 ;; first version was released on May 24, 2007.
801 ;; * 2007-05-24: [Version 1.1][]
802 ;; * 2007-05-25: [Version 1.2][]
803 ;; * 2007-06-05: [Version 1.3][]
804 ;; * 2007-06-29: [Version 1.4][]
805 ;; * 2007-10-11: [Version 1.5][]
806 ;; * 2008-06-04: [Version 1.6][]
807 ;; * 2009-10-01: [Version 1.7][]
808 ;; * 2011-08-12: [Version 1.8][]
809 ;; * 2011-08-15: [Version 1.8.1][]
810 ;; * 2013-01-25: [Version 1.9][]
811 ;; * 2013-03-24: [Version 2.0][]
812 ;; * 2016-01-09: [Version 2.1][]
814 ;; [Version 1.1]: http://jblevins.org/projects/markdown-mode/rev-1-1
815 ;; [Version 1.2]: http://jblevins.org/projects/markdown-mode/rev-1-2
816 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
817 ;; [Version 1.4]: http://jblevins.org/projects/markdown-mode/rev-1-4
818 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
819 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
820 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
821 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
822 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
823 ;; [Version 1.9]: http://jblevins.org/projects/markdown-mode/rev-1-9
824 ;; [Version 2.0]: http://jblevins.org/projects/markdown-mode/rev-2-0
825 ;; [Version 2.1]: http://jblevins.org/projects/markdown-mode/rev-2-1
828 ;;; Code:
830 (require 'easymenu)
831 (require 'outline)
832 (require 'thingatpt)
833 (require 'cl-lib)
834 (require 'url-parse)
836 (defvar jit-lock-start)
837 (defvar jit-lock-end)
839 (declare-function eww-open-file "eww")
840 (declare-function url-path-and-query "url-parse")
843 ;;; Constants =================================================================
845 (defconst markdown-mode-version "2.1"
846 "Markdown mode version number.")
848 (defconst markdown-output-buffer-name "*markdown-output*"
849 "Name of temporary buffer for markdown command output.")
852 ;;; Global Variables ==========================================================
854 (defvar markdown-reference-label-history nil
855 "History of used reference labels.")
857 (defvar markdown-live-preview-mode nil
858 "Sentinel variable for command `markdown-live-preview-mode'.")
860 (defvar markdown-gfm-language-history nil
861 "History list of languages used in the current buffer in GFM code blocks.")
864 ;;; Customizable Variables ====================================================
866 (defvar markdown-mode-hook nil
867 "Hook run when entering Markdown mode.")
869 (defvar markdown-before-export-hook nil
870 "Hook run before running Markdown to export XHTML output.
871 The hook may modify the buffer, which will be restored to it's
872 original state after exporting is complete.")
874 (defvar markdown-after-export-hook nil
875 "Hook run after XHTML output has been saved.
876 Any changes to the output buffer made by this hook will be saved.")
878 (defgroup markdown nil
879 "Major mode for editing text files in Markdown format."
880 :prefix "markdown-"
881 :group 'wp
882 :link '(url-link "http://jblevins.org/projects/markdown-mode/"))
884 (defcustom markdown-command "markdown"
885 "Command to run markdown."
886 :group 'markdown
887 :type 'string)
889 (defcustom markdown-command-needs-filename nil
890 "Set to non-nil if `markdown-command' does not accept input from stdin.
891 Instead, it will be passed a filename as the final command line
892 option. As a result, you will only be able to run Markdown from
893 buffers which are visiting a file."
894 :group 'markdown
895 :type 'boolean)
897 (defcustom markdown-open-command nil
898 "Command used for opening Markdown files directly.
899 For example, a standalone Markdown previewer. This command will
900 be called with a single argument: the filename of the current
901 buffer."
902 :group 'markdown
903 :type 'string)
905 (defcustom markdown-hr-strings
906 '("-------------------------------------------------------------------------------"
907 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
908 "---------------------------------------"
909 "* * * * * * * * * * * * * * * * * * * *"
910 "---------"
911 "* * * * *")
912 "Strings to use when inserting horizontal rules.
913 The first string in the list will be the default when inserting a
914 horizontal rule. Strings should be listed in decreasing order of
915 prominence (as in headings from level one to six) for use with
916 promotion and demotion functions."
917 :group 'markdown
918 :type 'list)
920 (defcustom markdown-bold-underscore nil
921 "Use two underscores when inserting bold text instead of two asterisks."
922 :group 'markdown
923 :type 'boolean)
925 (defcustom markdown-italic-underscore nil
926 "Use underscores when inserting italic text instead of asterisks."
927 :group 'markdown
928 :type 'boolean)
930 (defcustom markdown-asymmetric-header nil
931 "Determines if atx header style will be asymmetric.
932 Set to a non-nil value to use asymmetric header styling, placing
933 header markup only at the beginning of the line. By default,
934 balanced markup will be inserted at the beginning and end of the
935 line around the header title."
936 :group 'markdown
937 :type 'boolean)
939 (defcustom markdown-indent-function 'markdown-indent-line
940 "Function to use to indent."
941 :group 'markdown
942 :type 'function)
944 (defcustom markdown-indent-on-enter t
945 "Indent new lines and continue lists when enter is pressed.
946 When this variable is set to t, pressing RET will call
947 `newline-and-indent' and will continue a list. When set to nil,
948 define RET to call `newline' as usual. In the latter case, you
949 can still use auto-indentation by pressing
950 \\[newline-and-indent] or continue lists with
951 \\[markdown-insert-list-item]."
952 :group 'markdown
953 :type 'boolean)
955 (defcustom markdown-enable-wiki-links nil
956 "Syntax highlighting for wiki links.
957 Set this to a non-nil value to turn on wiki link support by default.
958 Support can be toggled later using the `markdown-toggle-wiki-links'
959 function or \\[markdown-toggle-wiki-links]."
960 :group 'markdown
961 :type 'boolean
962 :safe 'booleanp)
964 (defcustom markdown-wiki-link-alias-first t
965 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
966 Otherwise, they will be treated as [[PageName|alias text]]."
967 :group 'markdown
968 :type 'boolean
969 :safe 'booleanp)
971 (defcustom markdown-wiki-link-search-subdirectories nil
972 "When non-nil, search for wiki link targets in subdirectories.
973 This is the default search behavior for GitHub and is
974 automatically set to t in `gfm-mode'."
975 :group 'markdown
976 :type 'boolean
977 :safe 'booleanp)
979 (defcustom markdown-wiki-link-search-parent-directories nil
980 "When non-nil, search for wiki link targets in parent directories.
981 This is the default search behavior of Ikiwiki."
982 :group 'markdown
983 :type 'boolean
984 :safe 'booleanp)
986 (defcustom markdown-wiki-link-fontify-missing nil
987 "When non-nil, change wiki link face according to existence of target files.
988 This is expensive because it requires checking for the file each time the buffer
989 changes or the user switches windows. It is disabled by default because it may
990 cause lag when typing on slower machines."
991 :group 'markdown
992 :type 'boolean
993 :safe 'booleanp)
995 (defcustom markdown-uri-types
996 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
997 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
998 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
999 "Link types for syntax highlighting of URIs."
1000 :group 'markdown
1001 :type 'list)
1003 (defcustom markdown-enable-math nil
1004 "Syntax highlighting for inline LaTeX and itex expressions.
1005 Set this to a non-nil value to turn on math support by default.
1006 Math support can be enabled, disabled, or toggled later using
1007 `markdown-toggle-math' or \\[markdown-toggle-math]."
1008 :group 'markdown
1009 :type 'boolean
1010 :safe 'booleanp)
1012 (defcustom markdown-css-paths nil
1013 "URL of CSS file to link to in the output XHTML."
1014 :group 'markdown
1015 :type 'list)
1017 (defcustom markdown-content-type ""
1018 "Content type string for the http-equiv header in XHTML output.
1019 When set to a non-empty string, insert the http-equiv attribute.
1020 Otherwise, this attribute is omitted."
1021 :group 'markdown
1022 :type 'string)
1024 (defcustom markdown-coding-system nil
1025 "Character set string for the http-equiv header in XHTML output.
1026 Defaults to `buffer-file-coding-system' (and falling back to
1027 `iso-8859-1' when not available). Common settings are `utf-8'
1028 and `iso-latin-1'. Use `list-coding-systems' for more choices."
1029 :group 'markdown
1030 :type 'coding-system)
1032 (defcustom markdown-xhtml-header-content ""
1033 "Additional content to include in the XHTML <head> block."
1034 :group 'markdown
1035 :type 'string)
1037 (defcustom markdown-xhtml-standalone-regexp
1038 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
1039 "Regexp indicating whether `markdown-command' output is standalone XHTML."
1040 :group 'markdown
1041 :type 'regexp)
1043 (defcustom markdown-link-space-sub-char "_"
1044 "Character to use instead of spaces when mapping wiki links to filenames."
1045 :group 'markdown
1046 :type 'string)
1048 (defcustom markdown-reference-location 'header
1049 "Position where new reference definitions are inserted in the document."
1050 :group 'markdown
1051 :type '(choice (const :tag "At the end of the document" end)
1052 (const :tag "Immediately after the current block" immediately)
1053 (const :tag "Before next header" header)))
1055 (defcustom markdown-footnote-location 'end
1056 "Position where new footnotes are inserted in the document."
1057 :group 'markdown
1058 :type '(choice (const :tag "At the end of the document" end)
1059 (const :tag "Immediately after the current block" immediately)
1060 (const :tag "Before next header" header)))
1062 (defcustom markdown-unordered-list-item-prefix " * "
1063 "String inserted before unordered list items."
1064 :group 'markdown
1065 :type 'string)
1067 (defcustom markdown-nested-imenu-heading-index nil
1068 "Use nested or flat imenu heading index.
1069 A nested index may provide more natural browsing from the menu,
1070 but a flat list may allow for faster keyboard navigation via tab
1071 completion."
1072 :group 'markdown
1073 :type 'boolean)
1075 (defcustom markdown-make-gfm-checkboxes-buttons t
1076 "When non-nil, make GFM checkboxes into buttons."
1077 :group 'markdown
1078 :type 'boolean)
1080 (defcustom markdown-use-pandoc-style-yaml-metadata nil
1081 "When non-nil, allow yaml metadata anywhere in the document."
1082 :group 'markdown
1083 :type 'boolean)
1085 (defcustom markdown-split-window-direction 'any
1086 "Preference for splitting windows for static and live preview.
1087 The default value is 'any, which instructs Emacs to use
1088 `split-window-sensibly' to automatically choose how to split
1089 windows based on the values of `split-width-threshold' and
1090 `split-height-threshold' and the available windows. To force
1091 vertically split (left and right) windows, set this to 'vertical
1092 or 'right. To force horizontally split (top and bottom) windows,
1093 set this to 'horizontal or 'below."
1094 :group 'markdown
1095 :type 'symbol)
1097 (defcustom markdown-live-preview-window-function
1098 'markdown-live-preview-window-eww
1099 "Function to display preview of Markdown output within Emacs.
1100 Function must update the buffer containing the preview and return
1101 the buffer."
1102 :group 'markdown
1103 :type 'function)
1105 (defcustom markdown-live-preview-delete-export 'delete-on-destroy
1106 "Delete exported html file when using `markdown-live-preview-export'.
1107 If set to 'delete-on-export, delete on every export. When set to
1108 'delete-on-destroy delete when quitting from command
1109 `markdown-live-preview-mode'. Never delete if set to nil."
1110 :group 'markdown
1111 :type 'symbol)
1113 (defcustom markdown-list-indent-width 4
1114 "Depth of indentation for markdown lists.
1115 Used in `markdown-demote-list-item' and
1116 `markdown-promote-list-item'."
1117 :group 'markdown
1118 :type 'integer)
1120 (defcustom markdown-gfm-additional-languages nil
1121 "Extra languages made available when inserting GFM code blocks.
1122 Language strings must have be trimmed of whitespace and not
1123 contain any curly braces. They may be of arbitrary
1124 capitalization, though."
1125 :group 'markdown
1126 :type '(repeat (string :validate markdown-validate-language-string)))
1128 (defcustom markdown-gfm-use-electric-backquote t
1129 "Use `markdown-electric-backquote' when backquote is hit three times."
1130 :group 'markdown
1131 :type 'boolean)
1133 (defcustom markdown-gfm-downcase-languages t
1134 "If non-nil, downcase suggested languages.
1135 This applies to insertions done with
1136 `markdown-electric-backquote'."
1137 :group 'markdown
1138 :type 'boolean)
1141 ;;; Regular Expressions =======================================================
1143 (defconst markdown-regex-comment-start
1144 "<!--"
1145 "Regular expression matches HTML comment opening.")
1147 (defconst markdown-regex-comment-end
1148 "--[ \t]*>"
1149 "Regular expression matches HTML comment closing.")
1151 (defconst markdown-regex-link-inline
1152 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)\\((\\)\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?\\()\\)"
1153 "Regular expression for a [text](file) or an image link ![text](file).
1154 Group 1 matches the leading exclamation point (optional).
1155 Group 2 matches the opening square bracket.
1156 Group 3 matches the text inside the square brackets.
1157 Group 4 matches the closing square bracket.
1158 Group 5 matches the opening parenthesis.
1159 Group 6 matches the URL.
1160 Group 7 matches the title (optional).
1161 Group 8 matches the closing parenthesis.")
1163 (defconst markdown-regex-link-reference
1164 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)[ ]?\\(\\[\\)\\([^]]*?\\)\\(\\]\\)"
1165 "Regular expression for a reference link [text][id].
1166 Group 1 matches the leading exclamation point (optional).
1167 Group 2 matches the opening square bracket for the link text.
1168 Group 3 matches the text inside the square brackets.
1169 Group 4 matches the closing square bracket for the link text.
1170 Group 5 matches the opening square bracket for the reference label.
1171 Group 6 matches the reference label.
1172 Group 7 matches the closing square bracket for the reference label.")
1174 (defconst markdown-regex-reference-definition
1175 "^ \\{0,3\\}\\(\\[\\)\\([^]\n]+?\\)\\(\\]\\)\\(:\\)\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
1176 "Regular expression for a reference definition.
1177 Group 1 matches the opening square bracket.
1178 Group 2 matches the reference label.
1179 Group 3 matches the closing square bracket.
1180 Group 4 matches the colon.
1181 Group 5 matches the URL.
1182 Group 6 matches the title attribute (optional).")
1184 (defconst markdown-regex-footnote
1185 "\\(\\[\\^\\)\\(.+?\\)\\(\\]\\)"
1186 "Regular expression for a footnote marker [^fn].
1187 Group 1 matches the opening square bracket and carat.
1188 Group 2 matches only the label, without the surrounding markup.
1189 Group 3 matches the closing square bracket.")
1191 (defconst markdown-regex-header
1192 "^\\(?:\\([^\r\n\t -].*\\)\n\\(?:\\(=+\\)\\|\\(-+\\)\\)\\|\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)\\)$"
1193 "Regexp identifying Markdown headings.
1194 Group 1 matches the text of a setext heading.
1195 Group 2 matches the underline of a level-1 setext heading.
1196 Group 3 matches the underline of a level-2 setext heading.
1197 Group 4 matches the opening hash marks of an atx heading.
1198 Group 5 matches the text, without surrounding whitespace, of an atx heading.
1199 Group 6 matches the closing hash marks of an atx heading.")
1201 (defconst markdown-regex-header-setext
1202 "^\\([^\r\n\t -].*\\)\n\\(=+\\|-+\\)$"
1203 "Regular expression for generic setext-style (underline) headers.")
1205 (defconst markdown-regex-header-atx
1206 "^\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1207 "Regular expression for generic atx-style (hash mark) headers.")
1209 (defconst markdown-regex-hr
1210 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1211 "Regular expression for matching Markdown horizontal rules.")
1213 (defconst markdown-regex-code
1214 "\\(?:\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(?:.\\|\n[^\n]\\)*?[^`]\\)\\(\\2\\)\\)\\(?:[^`]\\|\\'\\)"
1215 "Regular expression for matching inline code fragments.
1217 Group 1 matches the entire code fragment including the backquotes.
1218 Group 2 matches the opening backquotes.
1219 Group 3 matches the code fragment itself, without backquotes.
1220 Group 4 matches the closing backquotes.
1222 The leading, unnumbered group ensures that the leading backquote
1223 character is not escaped.
1224 The last group, also unnumbered, requires that the character
1225 following the code fragment is not a backquote.
1226 Note that \\(?:.\\|\n[^\n]\\) matches any character, including newlines,
1227 but not two newlines in a row.")
1229 (defconst markdown-regex-kbd
1230 "\\(<kbd>\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(</kbd>\\)"
1231 "Regular expression for matching <kbd> tags.
1232 Groups 1 and 3 match the opening and closing tags.
1233 Group 2 matches the key sequence.")
1235 (defconst markdown-regex-gfm-code-block-open
1236 "^[[:blank:]]*\\(```\\)[[:blank:]]*\\({\\)?[[:blank:]]*\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?[[:blank:]]*\\(}\\)?[[:blank:]]*$"
1237 "Regular expression matching opening of GFM code blocks.
1238 Group 1 matches the opening three backquotes.
1239 Group 2 matches the opening brace (optional).
1240 Group 3 matches the language identifier (optional).
1241 Group 4 matches the info string (optional).
1242 Group 5 matches the closing brace (optional).
1243 Groups need to agree with `markdown-regex-tilde-fence-begin'.")
1245 (defconst markdown-regex-gfm-code-block-close
1246 "^[[:blank:]]*\\(```\\)\\s *?$"
1247 "Regular expression matching closing of GFM code blocks.
1248 Group 1 matches the closing three backquotes.")
1250 (defconst markdown-regex-pre
1251 "^\\( \\|\t\\).*$"
1252 "Regular expression for matching preformatted text sections.")
1254 (defconst markdown-regex-list
1255 "^\\([ \t]*\\)\\([0-9#]+\\.\\|[\\*\\+:-]\\)\\([ \t]+\\)"
1256 "Regular expression for matching list items.")
1258 (defconst markdown-regex-bold
1259 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1260 "Regular expression for matching bold text.
1261 Group 1 matches the character before the opening asterisk or
1262 underscore, if any, ensuring that it is not a backslash escape.
1263 Group 2 matches the entire expression, including delimiters.
1264 Groups 3 and 5 matches the opening and closing delimiters.
1265 Group 4 matches the text inside the delimiters.")
1267 (defconst markdown-regex-italic
1268 "\\(?:^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1269 "Regular expression for matching italic text.
1270 The leading unnumbered matches the character before the opening
1271 asterisk or underscore, if any, ensuring that it is not a
1272 backslash escape.
1273 Group 1 matches the entire expression, including delimiters.
1274 Groups 2 and 4 matches the opening and closing delimiters.
1275 Group 3 matches the text inside the delimiters.")
1277 (defconst markdown-regex-strike-through
1278 "\\(^\\|[^\\]\\)\\(\\(~~\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(~~\\)\\)"
1279 "Regular expression for matching strike-through text.
1280 Group 1 matches the character before the opening tilde, if any,
1281 ensuring that it is not a backslash escape.
1282 Group 2 matches the entire expression, including delimiters.
1283 Groups 3 and 5 matches the opening and closing delimiters.
1284 Group 4 matches the text inside the delimiters.")
1286 (defconst markdown-regex-gfm-italic
1287 "\\(?:^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\2\\|[^ ]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1288 "Regular expression for matching italic text in GitHub Flavored Markdown.
1289 Underscores in words are not treated as special.
1290 Group 1 matches the entire expression, including delimiters.
1291 Groups 2 and 4 matches the opening and closing delimiters.
1292 Group 3 matches the text inside the delimiters.")
1294 (defconst markdown-regex-blockquote
1295 "^[ \t]*\\(>\\)\\(.*\\)$"
1296 "Regular expression for matching blockquote lines.
1297 Group 1 matches the leading angle bracket.
1298 Group 2 matches the text.")
1300 (defconst markdown-regex-line-break
1301 "[^ \n\t][ \t]*\\( \\)$"
1302 "Regular expression for matching line breaks.")
1304 (defconst markdown-regex-wiki-link
1305 "\\(?:^\\|[^\\]\\)\\(\\(\\[\\[\\)\\([^]|]+\\)\\(?:\\(|\\)\\([^]]+\\)\\)?\\(\\]\\]\\)\\)"
1306 "Regular expression for matching wiki links.
1307 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1308 wiki links of the form [[PageName|link text]].
1309 The meanings of the first and second components depend
1310 on the value of `markdown-wiki-link-alias-first'.
1312 Group 1 matches the entire link.
1313 Group 2 matches the opening square brackets.
1314 Group 3 matches the first component of the wiki link.
1315 Group 4 matches the pipe separator, when present.
1316 Group 5 matches the second component of the wiki link, when present.
1317 Group 6 matches the closing square brackets.")
1319 (defconst markdown-regex-uri
1320 (concat (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+")
1321 "Regular expression for matching inline URIs.")
1323 (defconst markdown-regex-angle-uri
1324 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1325 "Regular expression for matching inline URIs in angle brackets.")
1327 (defconst markdown-regex-email
1328 "<\\(\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+\\)>"
1329 "Regular expression for matching inline email addresses.")
1331 (defsubst markdown-make-regex-link-generic ()
1332 "Make regular expression for matching any recognized link."
1333 (concat "\\(?:" markdown-regex-link-inline
1334 (when markdown-enable-wiki-links
1335 (concat "\\|" markdown-regex-wiki-link))
1336 "\\|" markdown-regex-link-reference
1337 "\\|" markdown-regex-angle-uri "\\)"))
1339 (defconst markdown-regex-gfm-checkbox
1340 " \\(\\[[ xX]\\]\\) "
1341 "Regular expression for matching GFM checkboxes.
1342 Group 1 matches the text to become a button.")
1344 (defconst markdown-regex-block-separator
1345 "\n[\n\t\f ]*\n"
1346 "Regular expression for matching block boundaries.")
1348 (defconst markdown-regex-block-separator-noindent
1349 (concat "\\(\\`\\|\\(" markdown-regex-block-separator "\\)[^\n\t\f ]\\)")
1350 "Regexp for block separators before lines with no indentation.")
1352 (defconst markdown-regex-math-inline-single
1353 "\\(?:^\\|[^\\]\\)\\(\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\)"
1354 "Regular expression for itex $..$ math mode expressions.
1355 Groups 1 and 3 match the opening and closing dollar signs.
1356 Group 3 matches the mathematical expression contained within.")
1358 (defconst markdown-regex-math-inline-double
1359 "\\(?:^\\|[^\\]\\)\\(\\$\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\$\\)"
1360 "Regular expression for itex $$..$$ math mode expressions.
1361 Groups 1 and 3 match opening and closing dollar signs.
1362 Group 3 matches the mathematical expression contained within.")
1364 (defconst markdown-regex-math-display
1365 "^\\(\\\\\\[\\)\\(\\(?:.\\|\n\\)*?\\)?\\(\\\\\\]\\)$"
1366 "Regular expression for itex \[..\] display mode expressions.
1367 Groups 1 and 3 match the opening and closing delimiters.
1368 Group 2 matches the mathematical expression contained within.")
1370 (defsubst markdown-make-tilde-fence-regex (num-tildes &optional end-of-line)
1371 "Return regexp matching a tilde code fence at least NUM-TILDES long.
1372 END-OF-LINE is the regexp construct to indicate end of line; $ if
1373 missing."
1374 (format "%s%d%s%s" "^[[:blank:]]*\\([~]\\{" num-tildes ",\\}\\)"
1375 (or end-of-line "$")))
1377 (defconst markdown-regex-tilde-fence-begin
1378 (markdown-make-tilde-fence-regex
1379 3 "[[:blank:]]*\\({\\)?[[:blank:]]*\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?[[:blank:]]*\\(}\\)?[[:blank:]]*$")
1380 "Regular expression for matching tilde-fenced code blocks.
1381 Group 1 matches the opening tildes.
1382 Group 2 matches the opening brace (optional).
1383 Group 3 matches the language identifier (optional).
1384 Group 4 matches the info string (optional).
1385 Group 5 matches the closing brace (optional).
1386 Groups need to agree with `markdown-regex-gfm-code-block-open'.")
1388 (defconst markdown-regex-declarative-metadata
1389 "^\\([[:alpha:]][[:alpha:] _-]*?\\)\\([:=][ \t]*\\)\\(.*\\)$"
1390 "Regular expression for matching declarative metadata statements.
1391 This matches MultiMarkdown metadata as well as YAML and TOML
1392 assignments such as the following:
1394 variable: value
1398 variable = value")
1400 (defconst markdown-regex-pandoc-metadata
1401 "^\\(%\\)\\([ \t]*\\)\\(.*\\(?:\n[ \t]+.*\\)*\\)"
1402 "Regular expression for matching Pandoc metadata.")
1404 (defconst markdown-regex-yaml-metadata-border
1405 "\\(-\\{3\\}\\)$"
1406 "Regular expression for matching yaml metadata.")
1408 (defconst markdown-regex-yaml-pandoc-metadata-end-border
1409 "^\\(\\.\\{3\\}\\|\\-\\{3\\}\\)$"
1410 "Regular expression for matching yaml metadata end borders.")
1412 (defsubst markdown-get-yaml-metadata-start-border ()
1413 "Return yaml metadata start border depending upon whether Pandoc is used."
1414 (concat
1415 (if markdown-use-pandoc-style-yaml-metadata "^" "\\`")
1416 markdown-regex-yaml-metadata-border))
1418 (defsubst markdown-get-yaml-metadata-end-border (_)
1419 "Return yaml metadata end border depending upon whether Pandoc is used."
1420 (if markdown-use-pandoc-style-yaml-metadata
1421 markdown-regex-yaml-pandoc-metadata-end-border
1422 markdown-regex-yaml-metadata-border))
1425 ;;; Syntax ====================================================================
1427 (defun markdown-syntax-propertize-extend-region (start end)
1428 "Extend START to END region to include an entire block of text.
1429 This helps improve syntax analysis for block constructs.
1430 Returns a cons (NEW-START . NEW-END) or nil if no adjustment should be made.
1431 Function is called repeatedly until it returns nil. For details, see
1432 `syntax-propertize-extend-region-functions'."
1433 (save-match-data
1434 (save-excursion
1435 (let* ((new-start (progn (goto-char start)
1436 (if (re-search-backward
1437 markdown-regex-block-separator-noindent nil t)
1438 (min start (match-end 0))
1439 (point-min))))
1440 (new-end (progn (goto-char end)
1441 (if (re-search-forward
1442 markdown-regex-block-separator-noindent nil t)
1443 (max end (match-beginning 0))
1444 (point-max))))
1445 (code-match (markdown-code-block-at-pos new-start))
1446 (new-start (or (and code-match (cl-first code-match)) new-start))
1447 (code-match (and (< end (point-max)) (markdown-code-block-at-pos end)))
1448 (new-end (or (and code-match (cl-second code-match)) new-end)))
1449 (unless (and (eq new-start start) (eq new-end end))
1450 (cons new-start (min new-end (point-max))))))))
1452 (defun markdown-font-lock-extend-region-function (start end _)
1453 "Used in `jit-lock-after-change-extend-region-functions'.
1454 Delegates to `markdown-syntax-propertize-extend-region'. START
1455 and END are the previous region to refontify."
1456 (let ((res (markdown-syntax-propertize-extend-region start end)))
1457 (when res
1458 ;; syntax-propertize-function is not called when character at
1459 ;; (point-max) is deleted, but font-lock-extend-region-functions
1460 ;; are called. Force a syntax property update in that case.
1461 (when (= end (point-max))
1462 (markdown-syntax-propertize (car res) (cdr res)))
1463 (setq jit-lock-start (car res)
1464 jit-lock-end (cdr res)))))
1466 (defun markdown-syntax-propertize-pre-blocks (start end)
1467 "Match preformatted text blocks from START to END."
1468 (save-excursion
1469 (goto-char start)
1470 (let ((levels (markdown-calculate-list-levels))
1471 indent pre-regexp close-regexp open close)
1472 (while (and (< (point) end) (not close))
1473 ;; Search for a region with sufficient indentation
1474 (if (null levels)
1475 (setq indent 1)
1476 (setq indent (1+ (length levels))))
1477 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1478 (setq close-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1480 (cond
1481 ;; If not at the beginning of a line, move forward
1482 ((not (bolp)) (forward-line))
1483 ;; Move past blank lines
1484 ((markdown-cur-line-blank-p) (forward-line))
1485 ;; At headers and horizontal rules, reset levels
1486 ((markdown-new-baseline-p) (forward-line) (setq levels nil))
1487 ;; If the current line has sufficient indentation, mark out pre block
1488 ;; The opening should be preceded by a blank line.
1489 ((and (looking-at pre-regexp)
1490 (save-match-data (markdown-prev-line-blank-p)))
1491 (setq open (match-beginning 0))
1492 (while (and (or (looking-at-p pre-regexp) (markdown-cur-line-blank-p))
1493 (not (eobp)))
1494 (forward-line))
1495 (skip-syntax-backward "-")
1496 (setq close (point)))
1497 ;; If current line has a list marker, update levels, move to end of block
1498 ((looking-at markdown-regex-list)
1499 (setq levels (markdown-update-list-levels
1500 (match-string 2) (current-indentation) levels))
1501 (markdown-end-of-text-block))
1502 ;; If this is the end of the indentation level, adjust levels accordingly.
1503 ;; Only match end of indentation level if levels is not the empty list.
1504 ((and (car levels) (looking-at-p close-regexp))
1505 (setq levels (markdown-update-list-levels
1506 nil (current-indentation) levels))
1507 (markdown-end-of-text-block))
1508 (t (markdown-end-of-text-block))))
1510 (when (and open close)
1511 ;; Set text property data
1512 (put-text-property open close 'markdown-pre (list open close))
1513 ;; Recursively search again
1514 (markdown-syntax-propertize-pre-blocks (point) end)))))
1516 (defconst markdown-fenced-block-pairs
1517 `(((,markdown-regex-tilde-fence-begin markdown-tilde-fence-begin)
1518 (markdown-make-tilde-fence-regex markdown-tilde-fence-end)
1519 markdown-fenced-code)
1520 ((markdown-get-yaml-metadata-start-border markdown-yaml-metadata-begin)
1521 (markdown-get-yaml-metadata-end-border markdown-yaml-metadata-end)
1522 markdown-yaml-metadata-section)
1523 ((,markdown-regex-gfm-code-block-open markdown-gfm-block-begin)
1524 (,markdown-regex-gfm-code-block-close markdown-gfm-block-end)
1525 markdown-gfm-code))
1526 "Mapping of regular expressions to \"fenced-block\" constructs.
1527 These constructs are distinguished by having a distinctive start
1528 and end pattern, both of which take up an entire line of text,
1529 but no special pattern to identify text within the fenced
1530 blocks (unlike blockquotes and indented-code sections).
1532 Each element within this list takes the form:
1534 ((START-REGEX-OR-FUN START-PROPERTY)
1535 (END-REGEX-OR-FUN END-PROPERTY)
1536 MIDDLE-PROPERTY)
1538 Each *-REGEX-OR-FUN element can be a regular expression as a string, or a
1539 function which evaluates to same. Functions for START-REGEX-OR-FUN accept no
1540 arguments, but functions for END-REGEX-OR-FUN accept a single numerical argument
1541 which is the length of the first group of the START-REGEX-OR-FUN match, which
1542 can be ignored if unnecessary. `markdown-maybe-funcall-regexp' is used to
1543 evaluate these into \"real\" regexps.
1545 The *-PROPERTY elements are the text properties applied to each part of the
1546 block construct when it is matched using
1547 `markdown-syntax-propertize-fenced-block-constructs'. START-PROPERTY is applied
1548 to the text matching START-REGEX-OR-FUN, END-PROPERTY to END-REGEX-OR-FUN, and
1549 MIDDLE-PROPERTY to the text in between the two. The value of *-PROPERTY is the
1550 `match-data' when the regexp was matched to the text. In the case of
1551 MIDDLE-PROPERTY, the value is a false match data of the form '(begin end), with
1552 begin and end set to the edges of the \"middle\" text. This makes fontification
1553 easier.")
1555 (defun markdown-text-property-at-point (prop)
1556 (get-text-property (point) prop))
1558 (defsubst markdown-maybe-funcall-regexp (object &optional arg)
1559 (cond ((functionp object)
1560 (if arg (funcall object arg) (funcall object)))
1561 ((stringp object) object)
1562 (t (error "Object cannot be turned into regex"))))
1564 (defsubst markdown-get-start-fence-regexp ()
1565 "Return regexp to find all \"start\" sections of fenced block constructs.
1566 Which construct is actually contained in the match must be found separately."
1567 (mapconcat
1568 #'identity
1569 ;; FIXME: Why `cl-mapcar' rather than `mapcar'?
1570 (cl-mapcar (lambda (entry) (markdown-maybe-funcall-regexp (caar entry)))
1571 markdown-fenced-block-pairs)
1572 "\\|"))
1574 (defun markdown-get-fenced-block-begin-properties ()
1575 (cl-mapcar (lambda (entry) (cl-cadar entry)) markdown-fenced-block-pairs))
1577 (defun markdown-get-fenced-block-end-properties ()
1578 (cl-mapcar (lambda (entry) (cl-cadadr entry)) markdown-fenced-block-pairs))
1580 (defun markdown-get-fenced-block-middle-properties ()
1581 (cl-mapcar #'cl-third markdown-fenced-block-pairs))
1583 (defun markdown-find-previous-prop (prop &optional lim)
1584 "Find previous place where property PROP is non-nil, up to LIM.
1585 Return a cons of (pos . property). pos is point if point contains
1586 non-nil PROP."
1587 (let ((res
1588 (if (get-text-property (point) prop) (point)
1589 (previous-single-property-change
1590 (point) prop nil (or lim (point-min))))))
1591 (when (and (not (get-text-property res prop))
1592 (> res (point-min))
1593 (get-text-property (1- res) prop))
1594 (cl-decf res))
1595 (when (and res (get-text-property res prop)) (cons res prop))))
1597 (defun markdown-find-next-prop (prop &optional lim)
1598 "Find next place where property PROP is non-nil, up to LIM.
1599 Return a cons of (POS . PROPERTY) where POS is point if point
1600 contains non-nil PROP."
1601 (let ((res
1602 (if (get-text-property (point) prop) (point)
1603 (next-single-property-change
1604 (point) prop nil (or lim (point-max))))))
1605 (when (and res (get-text-property res prop)) (cons res prop))))
1607 (defun markdown-min-of-seq (map-fn seq)
1608 "Apply MAP-FN to SEQ and return element of SEQ with minimum value of MAP-FN."
1609 (cl-loop for el in seq
1610 with min = 1.0e+INF ; infinity
1611 with min-el = nil
1612 do (let ((res (funcall map-fn el)))
1613 (when (< res min)
1614 (setq min res)
1615 (setq min-el el)))
1616 finally return min-el))
1618 (defun markdown-find-previous-block ()
1619 "Find previous block.
1620 Detect whether `markdown-syntax-propertize-fenced-block-constructs' was
1621 unable to propertize the entire block, but was able to propertize the beginning
1622 of the block. If so, return a cons of (pos . property) where the beginning of
1623 the block was propertized."
1624 (let ((start-pt (point))
1625 (closest-open
1626 (markdown-min-of-seq
1627 #'car
1628 (cl-remove-if
1629 #'null
1630 (cl-mapcar
1631 #'markdown-find-previous-prop
1632 (markdown-get-fenced-block-begin-properties))))))
1633 (when closest-open
1634 (let* ((length-of-open-match
1635 (let ((match-d
1636 (get-text-property (car closest-open) (cdr closest-open))))
1637 (- (cl-fourth match-d) (cl-third match-d))))
1638 (end-regexp
1639 (markdown-maybe-funcall-regexp
1640 (cl-caadr
1641 (cl-find-if
1642 (lambda (entry) (eq (cl-cadar entry) (cdr closest-open)))
1643 markdown-fenced-block-pairs))
1644 length-of-open-match))
1645 (end-prop-loc
1646 (save-excursion
1647 (save-match-data
1648 (goto-char (car closest-open))
1649 (and (re-search-forward end-regexp start-pt t)
1650 (match-beginning 0))))))
1651 (and (not end-prop-loc) closest-open)))))
1653 (defun markdown-get-fenced-block-from-start (prop)
1654 "Return limits of an enclosing fenced block from its start, using PROP.
1655 Return value is a list usable as `match-data'."
1656 (catch 'no-rest-of-block
1657 (let* ((correct-entry
1658 (cl-find-if
1659 (lambda (entry) (eq (cl-cadar entry) prop))
1660 markdown-fenced-block-pairs))
1661 (begin-of-begin (cl-first (markdown-text-property-at-point prop)))
1662 (middle-prop (cl-third correct-entry))
1663 (end-prop (cl-cadadr correct-entry))
1664 (end-of-end
1665 (save-excursion
1666 (goto-char (match-end 0)) ; end of begin
1667 (unless (eobp) (forward-char))
1668 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
1669 (if (not mid-prop-v) ; no middle
1670 (progn
1671 ;; try to find end by advancing one
1672 (let ((end-prop-v
1673 (markdown-text-property-at-point end-prop)))
1674 (if end-prop-v (cl-second end-prop-v)
1675 (throw 'no-rest-of-block nil))))
1676 (set-match-data mid-prop-v)
1677 (goto-char (match-end 0)) ; end of middle
1678 (beginning-of-line) ; into end
1679 (cl-second (markdown-text-property-at-point end-prop)))))))
1680 (list begin-of-begin end-of-end))))
1682 (defun markdown-get-fenced-block-from-middle (prop)
1683 "Return limits of an enclosing fenced block from its middle, using PROP.
1684 Return value is a list usable as `match-data'."
1685 (let* ((correct-entry
1686 (cl-find-if
1687 (lambda (entry) (eq (cl-third entry) prop))
1688 markdown-fenced-block-pairs))
1689 (begin-prop (cl-cadar correct-entry))
1690 (begin-of-begin
1691 (save-excursion
1692 (goto-char (match-beginning 0))
1693 (unless (bobp) (forward-line -1))
1694 (beginning-of-line)
1695 (cl-first (markdown-text-property-at-point begin-prop))))
1696 (end-prop (cl-cadadr correct-entry))
1697 (end-of-end
1698 (save-excursion
1699 (goto-char (match-end 0))
1700 (beginning-of-line)
1701 (cl-second (markdown-text-property-at-point end-prop)))))
1702 (list begin-of-begin end-of-end)))
1704 (defun markdown-get-fenced-block-from-end (prop)
1705 "Return limits of an enclosing fenced block from its end, using PROP.
1706 Return value is a list usable as `match-data'."
1707 (let* ((correct-entry
1708 (cl-find-if
1709 (lambda (entry) (eq (cl-cadadr entry) prop))
1710 markdown-fenced-block-pairs))
1711 (end-of-end (cl-second (markdown-text-property-at-point prop)))
1712 (middle-prop (cl-third correct-entry))
1713 (begin-prop (cl-cadar correct-entry))
1714 (begin-of-begin
1715 (save-excursion
1716 (goto-char (match-beginning 0)) ; beginning of end
1717 (unless (bobp) (backward-char)) ; into middle
1718 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
1719 (if (not mid-prop-v)
1720 (progn
1721 (beginning-of-line)
1722 (cl-first (markdown-text-property-at-point begin-prop)))
1723 (set-match-data mid-prop-v)
1724 (goto-char (match-beginning 0)) ; beginning of middle
1725 (unless (bobp) (forward-line -1)) ; into beginning
1726 (beginning-of-line)
1727 (cl-first (markdown-text-property-at-point begin-prop)))))))
1728 (list begin-of-begin end-of-end)))
1730 (defun markdown-get-enclosing-fenced-block-construct (&optional pos)
1731 "Get \"fake\" match data for block enclosing POS.
1732 Returns fake match data which encloses the start, middle, and end
1733 of the block construct enclosing POS, if it exists. Used in
1734 `markdown-code-block-at-pos'."
1735 (save-excursion
1736 (when pos (goto-char pos))
1737 (beginning-of-line)
1738 (car
1739 (cl-remove-if
1740 #'null
1741 (cl-mapcar
1742 (lambda (fun-and-prop)
1743 (cl-destructuring-bind (fun prop) fun-and-prop
1744 (when prop
1745 (save-match-data
1746 (set-match-data (markdown-text-property-at-point prop))
1747 (funcall fun prop)))))
1748 `((markdown-get-fenced-block-from-start
1749 ,(cl-find-if
1750 #'markdown-text-property-at-point
1751 (markdown-get-fenced-block-begin-properties)))
1752 (markdown-get-fenced-block-from-middle
1753 ,(cl-find-if
1754 #'markdown-text-property-at-point
1755 (markdown-get-fenced-block-middle-properties)))
1756 (markdown-get-fenced-block-from-end
1757 ,(cl-find-if
1758 #'markdown-text-property-at-point
1759 (markdown-get-fenced-block-end-properties)))))))))
1761 (defun markdown-propertize-end-match (reg end correct-entry enclosed-text-start)
1762 "Get match for REG up to END, if exists, and propertize appropriately.
1763 CORRECT-ENTRY is an entry in `markdown-fenced-block-pairs' and
1764 ENCLOSED-TEXT-START is the start of the \"middle\" section of the block."
1765 (when (re-search-forward reg end t)
1766 (put-text-property (match-beginning 0) (match-end 0)
1767 (cl-cadadr correct-entry) (match-data t))
1768 (put-text-property
1769 enclosed-text-start (match-beginning 0) (cl-third correct-entry)
1770 (list enclosed-text-start (match-beginning 0)))))
1772 (defun markdown-syntax-propertize-fenced-block-constructs (start end)
1773 "Propertize according to `markdown-fenced-block-pairs' from START to END.
1774 If unable to propertize an entire block (if the start of a block is within START
1775 and END, but the end of the block is not), propertize the start section of a
1776 block, then in a subsequent call propertize both middle and end by finding the
1777 start which was previously propertized."
1778 (let ((start-reg (markdown-get-start-fence-regexp)))
1779 (save-excursion
1780 (goto-char start)
1781 ;; start from previous unclosed block, if exists
1782 (let ((prev-begin-block (markdown-find-previous-block)))
1783 (when prev-begin-block
1784 (let* ((correct-entry
1785 (cl-find-if (lambda (entry)
1786 (eq (cdr prev-begin-block) (cl-cadar entry)))
1787 markdown-fenced-block-pairs))
1788 (enclosed-text-start (1+ (car prev-begin-block)))
1789 (start-length
1790 (save-excursion
1791 (goto-char (car prev-begin-block))
1792 (string-match
1793 (markdown-maybe-funcall-regexp
1794 (caar correct-entry))
1795 (buffer-substring
1796 (point-at-bol) (point-at-eol)))
1797 (- (match-end 1) (match-beginning 1))))
1798 (end-reg (markdown-maybe-funcall-regexp
1799 (cl-caadr correct-entry) start-length)))
1800 (markdown-propertize-end-match
1801 end-reg end correct-entry enclosed-text-start))))
1802 ;; find all new blocks within region
1803 (while (re-search-forward start-reg end t)
1804 ;; we assume the opening constructs take up (only) an entire line,
1805 ;; so we re-check the current line
1806 (let* ((cur-line (buffer-substring (point-at-bol) (point-at-eol)))
1807 ;; find entry in `markdown-fenced-block-pairs' corresponding
1808 ;; to regex which was matched
1809 (correct-entry
1810 (cl-find-if
1811 (lambda (fenced-pair)
1812 (string-match-p
1813 (markdown-maybe-funcall-regexp (caar fenced-pair))
1814 cur-line))
1815 markdown-fenced-block-pairs))
1816 (enclosed-text-start
1817 (save-excursion (1+ (point-at-eol))))
1818 (end-reg
1819 (markdown-maybe-funcall-regexp
1820 (cl-caadr correct-entry)
1821 (if (and (match-beginning 1) (match-end 1))
1822 (- (match-end 1) (match-beginning 1))
1823 0))))
1824 ;; get correct match data
1825 (save-excursion
1826 (beginning-of-line)
1827 (re-search-forward
1828 (markdown-maybe-funcall-regexp (caar correct-entry))
1829 (point-at-eol)))
1830 ;; mark starting, even if ending is outside of region
1831 (put-text-property (match-beginning 0) (match-end 0)
1832 (cl-cadar correct-entry) (match-data t))
1833 (markdown-propertize-end-match
1834 end-reg end correct-entry enclosed-text-start))))))
1836 (defun markdown-syntax-propertize-blockquotes (start end)
1837 "Match blockquotes from START to END."
1838 (save-excursion
1839 (goto-char start)
1840 (while (and (re-search-forward markdown-regex-blockquote end t)
1841 (not (markdown-code-block-at-pos (match-beginning 0))))
1842 (put-text-property (match-beginning 0) (match-end 0)
1843 'markdown-blockquote
1844 (match-data t)))))
1846 (defun markdown-syntax-propertize-yaml-metadata (start end)
1847 (save-excursion
1848 (goto-char start)
1849 (cl-loop
1850 while (re-search-forward markdown-regex-declarative-metadata end t)
1851 do (when (get-text-property (match-beginning 0)
1852 'markdown-yaml-metadata-section)
1853 (put-text-property (match-beginning 1) (match-end 1)
1854 'markdown-metadata-key (match-data t))
1855 (put-text-property (match-beginning 2) (match-end 2)
1856 'markdown-metadata-markup (match-data t))
1857 (put-text-property (match-beginning 3) (match-end 3)
1858 'markdown-metadata-value (match-data t))))))
1860 (defun markdown-syntax-propertize-headings (start end)
1861 "Match headings of type SYMBOL with REGEX from START to END."
1862 (goto-char start)
1863 (while (re-search-forward markdown-regex-header end t)
1864 (unless (markdown-code-block-at-pos (match-beginning 0))
1865 (put-text-property
1866 (match-beginning 0) (match-end 0) 'markdown-heading t)
1867 (put-text-property
1868 (match-beginning 0) (match-end 0)
1869 (cond ((match-string-no-properties 2) 'markdown-heading-1-setext)
1870 ((match-string-no-properties 3) 'markdown-heading-2-setext)
1871 (t (let ((atx-level (length (match-string-no-properties 4))))
1872 (intern (format "markdown-heading-%d-atx" atx-level)))))
1873 (match-data t)))))
1875 (defun markdown-syntax-propertize-comments (start end)
1876 "Match HTML comments from the START to END."
1877 (let* ((state (syntax-ppss)) (in-comment (nth 4 state)))
1878 (goto-char start)
1879 (cond
1880 ;; Comment start
1881 ((and (not in-comment)
1882 (re-search-forward markdown-regex-comment-start end t)
1883 (not (markdown-inline-code-at-point-p))
1884 (not (markdown-code-block-at-point-p)))
1885 (let ((open-beg (match-beginning 0)))
1886 (put-text-property open-beg (1+ open-beg)
1887 'syntax-table (string-to-syntax "<"))
1888 (markdown-syntax-propertize-comments
1889 (min (1+ (match-end 0)) end (point-max)) end)))
1890 ;; Comment end
1891 ((and in-comment
1892 (re-search-forward markdown-regex-comment-end end t))
1893 (put-text-property (1- (match-end 0)) (match-end 0)
1894 'syntax-table (string-to-syntax ">"))
1895 (markdown-syntax-propertize-comments
1896 (min (1+ (match-end 0)) end (point-max)) end))
1897 ;; Nothing found
1898 (t nil))))
1900 (defvar markdown--syntax-properties
1901 (list 'markdown-tilde-fence-begin nil
1902 'markdown-tilde-fence-end nil
1903 'markdown-fenced-code nil
1904 'markdown-yaml-metadata-begin nil
1905 'markdown-yaml-metadata-end nil
1906 'markdown-yaml-metadata-section nil
1907 'markdown-gfm-block-begin nil
1908 'markdown-gfm-block-end nil
1909 'markdown-gfm-code nil
1910 'markdown-pre nil
1911 'markdown-blockquote nil
1912 'markdown-heading nil
1913 'markdown-heading-1-setext nil
1914 'markdown-heading-2-setext nil
1915 'markdown-heading-1-atx nil
1916 'markdown-heading-2-atx nil
1917 'markdown-heading-3-atx nil
1918 'markdown-heading-4-atx nil
1919 'markdown-heading-5-atx nil
1920 'markdown-heading-6-atx nil
1921 'markdown-metadata-key nil
1922 'markdown-metadata-value nil
1923 'markdown-metadata-markup nil)
1924 "Property list of all known markdown syntactic properties.")
1926 (defun markdown-syntax-propertize (start end)
1927 "Function used as `syntax-propertize-function'.
1928 START and END delimit region to propertize."
1929 (with-silent-modifications
1930 (save-excursion
1931 (remove-text-properties start end markdown--syntax-properties)
1932 (markdown-syntax-propertize-fenced-block-constructs start end)
1933 (markdown-syntax-propertize-yaml-metadata start end)
1934 (markdown-syntax-propertize-pre-blocks start end)
1935 (markdown-syntax-propertize-blockquotes start end)
1936 (markdown-syntax-propertize-headings start end)
1937 (markdown-syntax-propertize-comments start end))))
1940 ;;; Font Lock =================================================================
1942 (require 'font-lock)
1944 (defvar markdown-italic-face 'markdown-italic-face
1945 "Face name to use for italic text.")
1947 (defvar markdown-bold-face 'markdown-bold-face
1948 "Face name to use for bold text.")
1950 (defvar markdown-strike-through-face 'markdown-strike-through-face
1951 "Face name to use for strike-through text.")
1953 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
1954 "Face name to use as a base for header delimiters.")
1956 (defvar markdown-header-rule-face 'markdown-header-rule-face
1957 "Face name to use as a base for header rules.")
1959 (defvar markdown-header-face 'markdown-header-face
1960 "Face name to use as a base for headers.")
1962 (defvar markdown-header-face-1 'markdown-header-face-1
1963 "Face name to use for level-1 headers.")
1965 (defvar markdown-header-face-2 'markdown-header-face-2
1966 "Face name to use for level-2 headers.")
1968 (defvar markdown-header-face-3 'markdown-header-face-3
1969 "Face name to use for level-3 headers.")
1971 (defvar markdown-header-face-4 'markdown-header-face-4
1972 "Face name to use for level-4 headers.")
1974 (defvar markdown-header-face-5 'markdown-header-face-5
1975 "Face name to use for level-5 headers.")
1977 (defvar markdown-header-face-6 'markdown-header-face-6
1978 "Face name to use for level-6 headers.")
1980 (defvar markdown-inline-code-face 'markdown-inline-code-face
1981 "Face name to use for inline code.")
1983 (defvar markdown-list-face 'markdown-list-face
1984 "Face name to use for list markers.")
1986 (defvar markdown-blockquote-face 'markdown-blockquote-face
1987 "Face name to use for blockquote.")
1989 (defvar markdown-pre-face 'markdown-pre-face
1990 "Face name to use for preformatted text.")
1992 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
1993 "Face name to use for programming language identifiers.")
1995 (defvar markdown-language-info-face 'markdown-language-info-face
1996 "Face name to use for programming info strings.")
1998 (defvar markdown-link-face 'markdown-link-face
1999 "Face name to use for links.")
2001 (defvar markdown-missing-link-face 'markdown-missing-link-face
2002 "Face name to use for links where the linked file does not exist.")
2004 (defvar markdown-reference-face 'markdown-reference-face
2005 "Face name to use for reference.")
2007 (defvar markdown-footnote-face 'markdown-footnote-face
2008 "Face name to use for footnote identifiers.")
2010 (defvar markdown-url-face 'markdown-url-face
2011 "Face name to use for URLs.")
2013 (defvar markdown-link-title-face 'markdown-link-title-face
2014 "Face name to use for reference link titles.")
2016 (defvar markdown-line-break-face 'markdown-line-break-face
2017 "Face name to use for hard line breaks.")
2019 (defvar markdown-comment-face 'markdown-comment-face
2020 "Face name to use for HTML comments.")
2022 (defvar markdown-math-face 'markdown-math-face
2023 "Face name to use for LaTeX expressions.")
2025 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
2026 "Face name to use for metadata keys.")
2028 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
2029 "Face name to use for metadata values.")
2031 (defvar markdown-gfm-checkbox-face 'markdown-gfm-checkbox-face
2032 "Face name to use for GFM checkboxes.")
2034 (defvar markdown-highlight-face 'markdown-highlight-face
2035 "Face name to use for mouse highlighting.")
2037 (defvar markdown-markup-face 'markdown-markup-face
2038 "Face name to use for markup elements.")
2040 (defgroup markdown-faces nil
2041 "Faces used in Markdown Mode"
2042 :group 'markdown
2043 :group 'faces)
2045 (defface markdown-italic-face
2046 '((t (:inherit font-lock-variable-name-face :slant italic :weight normal)))
2047 "Face for italic text."
2048 :group 'markdown-faces)
2050 (defface markdown-bold-face
2051 '((t (:inherit font-lock-variable-name-face :weight bold :slant normal)))
2052 "Face for bold text."
2053 :group 'markdown-faces)
2055 (defface markdown-strike-through-face
2056 '((t (:inherit font-lock-variable-name-face :strike-through t)))
2057 "Face for strike-through text."
2058 :group 'markdown-faces)
2060 (defface markdown-markup-face
2061 '((t (:inherit shadow :slant normal :weight normal)))
2062 "Face for markup elements."
2063 :group 'markdown-faces)
2065 (defface markdown-header-rule-face
2066 '((t (:inherit markdown-markup-face)))
2067 "Base face for headers rules."
2068 :group 'markdown-faces)
2070 (defface markdown-header-delimiter-face
2071 '((t (:inherit markdown-markup-face)))
2072 "Base face for headers hash delimiter."
2073 :group 'markdown-faces)
2075 (defface markdown-inline-code-face
2076 '((t (:inherit font-lock-constant-face)))
2077 "Face for inline code."
2078 :group 'markdown-faces)
2080 (defface markdown-list-face
2081 '((t (:inherit markdown-markup-face)))
2082 "Face for list item markers."
2083 :group 'markdown-faces)
2085 (defface markdown-blockquote-face
2086 '((t (:inherit font-lock-doc-face)))
2087 "Face for blockquote sections."
2088 :group 'markdown-faces)
2090 (defface markdown-pre-face
2091 '((t (:inherit font-lock-constant-face)))
2092 "Face for preformatted text."
2093 :group 'markdown-faces)
2095 (defface markdown-language-keyword-face
2096 '((t (:inherit font-lock-type-face)))
2097 "Face for programming language identifiers."
2098 :group 'markdown-faces)
2100 (defface markdown-language-info-face
2101 '((t (:inherit font-lock-string-face)))
2102 "Face for programming language info strings."
2103 :group 'markdown-faces)
2105 (defface markdown-link-face
2106 '((t (:inherit font-lock-keyword-face)))
2107 "Face for links."
2108 :group 'markdown-faces)
2110 (defface markdown-missing-link-face
2111 '((t (:inherit font-lock-warning-face)))
2112 "Face for missing links."
2113 :group 'markdown-faces)
2115 (defface markdown-reference-face
2116 '((t (:inherit markdown-markup-face)))
2117 "Face for link references."
2118 :group 'markdown-faces)
2120 (defface markdown-footnote-face
2121 '((t (:inherit markdown-markup-face)))
2122 "Face for footnote markers."
2123 :group 'markdown-faces)
2125 (defface markdown-url-face
2126 '((t (:inherit font-lock-string-face)))
2127 "Face for URLs."
2128 :group 'markdown-faces)
2130 (defface markdown-link-title-face
2131 '((t (:inherit font-lock-comment-face)))
2132 "Face for reference link titles."
2133 :group 'markdown-faces)
2135 (defface markdown-line-break-face
2136 '((t (:inherit font-lock-constant-face :underline t)))
2137 "Face for hard line breaks."
2138 :group 'markdown-faces)
2140 (defface markdown-comment-face
2141 '((t (:inherit font-lock-comment-face)))
2142 "Face for HTML comments."
2143 :group 'markdown-faces)
2145 (defface markdown-math-face
2146 '((t (:inherit font-lock-string-face)))
2147 "Face for LaTeX expressions."
2148 :group 'markdown-faces)
2150 (defface markdown-metadata-key-face
2151 '((t (:inherit font-lock-variable-name-face)))
2152 "Face for metadata keys."
2153 :group 'markdown-faces)
2155 (defface markdown-metadata-value-face
2156 '((t (:inherit font-lock-string-face)))
2157 "Face for metadata values."
2158 :group 'markdown-faces)
2160 (defface markdown-gfm-checkbox-face
2161 '((t (:inherit font-lock-builtin-face)))
2162 "Face for GFM checkboxes."
2163 :group 'markdown-faces)
2165 (defface markdown-highlight-face
2166 '((t (:inherit highlight)))
2167 "Face for mouse highlighting."
2168 :group 'markdown-faces)
2170 (defcustom markdown-header-scaling nil
2171 "Whether to use variable-height faces for headers.
2172 When non-nil, `markdown-header-face' will inherit from
2173 `variable-pitch' and the scaling values in
2174 `markdown-header-scaling-values' will be applied to
2175 headers of levels one through six respectively."
2176 :type 'boolean
2177 :initialize 'custom-initialize-default
2178 :set (lambda (symbol value)
2179 (set-default symbol value)
2180 (markdown-update-header-faces value))
2181 :group 'markdown-faces)
2183 (defcustom markdown-header-scaling-values
2184 '(1.8 1.4 1.2 1.0 1.0 1.0)
2185 "List of scaling values for headers of level one through six.
2186 Used when `markdown-header-scaling' is non-nil."
2187 :type 'list
2188 :initialize 'custom-initialize-default
2189 :set (lambda (symbol value)
2190 (set-default symbol value)
2191 (markdown-update-header-faces markdown-header-scaling value))
2192 :group 'markdown-faces)
2194 (defun markdown-make-header-faces ()
2195 "Build the faces used for Markdown headers."
2196 (let ((inherit-faces '(font-lock-function-name-face)))
2197 (when markdown-header-scaling
2198 (setq inherit-faces (cons 'variable-pitch inherit-faces)))
2199 (defface markdown-header-face
2200 `((t (:inherit ,inherit-faces :weight bold)))
2201 "Base face for headers."
2202 :group 'markdown-faces))
2203 (dotimes (num 6)
2204 (let* ((num1 (1+ num))
2205 (face-name (intern (format "markdown-header-face-%s" num1)))
2206 (scale (if markdown-header-scaling
2207 (float (nth num markdown-header-scaling-values))
2208 1.0)))
2209 (eval
2210 `(defface ,face-name
2211 '((t (:inherit markdown-header-face :height ,scale)))
2212 (format "Face for level %s headers.
2214 You probably don't want to customize this face directly. Instead
2215 you can customize the base face `markdown-header-face' or the
2216 variable-height variable `markdown-header-scaling'." ,num1)
2217 :group 'markdown-faces)))))
2219 (markdown-make-header-faces)
2221 (defun markdown-update-header-faces (&optional scaling scaling-values)
2222 "Update header faces, depending on if header SCALING is desired.
2223 If so, use given list of SCALING-VALUES relative to the baseline
2224 size of `markdown-header-face'."
2225 (dotimes (num 6)
2226 (let* ((face-name (intern (format "markdown-header-face-%s" (1+ num))))
2227 (scale (cond ((not scaling) 1.0)
2228 (scaling-values (float (nth num scaling-values)))
2229 (t (float (nth num markdown-header-scaling-values))))))
2230 (unless (get face-name 'saved-face) ; Don't update customized faces
2231 (set-face-attribute face-name nil :height scale)))))
2233 (defun markdown-syntactic-face (state)
2234 "Return font-lock face for characters with given STATE.
2235 See `font-lock-syntactic-face-function' for details."
2236 (let ((in-comment (nth 4 state)))
2237 (cond
2238 (in-comment 'markdown-comment-face)
2239 (t nil))))
2241 (defvar markdown-mode-font-lock-keywords-basic
2242 `((markdown-match-yaml-metadata-begin . ((1 markdown-markup-face)))
2243 (markdown-match-yaml-metadata-end . ((1 markdown-markup-face)))
2244 (markdown-match-yaml-metadata-key . ((1 markdown-metadata-key-face)
2245 (2 markdown-markup-face)
2246 (3 markdown-metadata-value-face)))
2247 (markdown-match-gfm-open-code-blocks . ((1 markdown-markup-face)
2248 (2 markdown-markup-face nil t)
2249 (3 markdown-language-keyword-face nil t)
2250 (4 markdown-language-info-face nil t)
2251 (5 markdown-markup-face nil t)))
2252 (markdown-match-gfm-close-code-blocks . ((1 markdown-markup-face)))
2253 (markdown-match-gfm-code-blocks . ((0 markdown-pre-face)))
2254 (markdown-match-fenced-start-code-block . ((1 markdown-markup-face)
2255 (2 markdown-markup-face nil t)
2256 (3 markdown-language-keyword-face nil t)
2257 (4 markdown-language-info-face nil t)
2258 (5 markdown-markup-face nil t)))
2259 (markdown-match-fenced-end-code-block . ((0 markdown-markup-face)))
2260 (markdown-match-fenced-code-blocks . ((0 markdown-pre-face)))
2261 (markdown-match-pre-blocks . ((0 markdown-pre-face)))
2262 (markdown-match-blockquotes . ((1 markdown-markup-face)
2263 (2 markdown-blockquote-face)))
2264 (markdown-match-heading-1-setext . ((1 markdown-header-face-1)
2265 (2 markdown-header-rule-face)))
2266 (markdown-match-heading-2-setext . ((1 markdown-header-face-2)
2267 (3 markdown-header-rule-face)))
2268 (markdown-match-heading-6-atx . ((4 markdown-header-delimiter-face)
2269 (5 markdown-header-face-6)
2270 (6 markdown-header-delimiter-face)))
2271 (markdown-match-heading-5-atx . ((4 markdown-header-delimiter-face)
2272 (5 markdown-header-face-5)
2273 (6 markdown-header-delimiter-face)))
2274 (markdown-match-heading-4-atx . ((4 markdown-header-delimiter-face)
2275 (5 markdown-header-face-4)
2276 (6 markdown-header-delimiter-face)))
2277 (markdown-match-heading-3-atx . ((4 markdown-header-delimiter-face)
2278 (5 markdown-header-face-3)
2279 (6 markdown-header-delimiter-face)))
2280 (markdown-match-heading-2-atx . ((4 markdown-header-delimiter-face)
2281 (5 markdown-header-face-2)
2282 (6 markdown-header-delimiter-face)))
2283 (markdown-match-heading-1-atx . ((4 markdown-header-delimiter-face)
2284 (5 markdown-header-face-1)
2285 (6 markdown-header-delimiter-face)))
2286 (markdown-match-declarative-metadata . ((1 markdown-metadata-key-face)
2287 (2 markdown-markup-face)
2288 (3 markdown-metadata-value-face)))
2289 (markdown-match-pandoc-metadata . ((1 markdown-markup-face)
2290 (2 markdown-markup-face)
2291 (3 markdown-metadata-value-face)))
2292 (markdown-match-hr . markdown-header-delimiter-face)
2293 (markdown-match-code . ((1 markdown-markup-face)
2294 (2 markdown-inline-code-face)
2295 (3 markdown-markup-face)))
2296 (,markdown-regex-kbd . ((1 markdown-markup-face)
2297 (2 markdown-inline-code-face)
2298 (3 markdown-markup-face)))
2299 (,markdown-regex-angle-uri . ((1 markdown-markup-face)
2300 (2 markdown-link-face)
2301 (3 markdown-markup-face)))
2302 (,markdown-regex-list . (2 markdown-list-face))
2303 (,markdown-regex-footnote . ((1 markdown-markup-face) ; [^
2304 (2 markdown-footnote-face) ; label
2305 (3 markdown-markup-face))) ; ]
2306 (,markdown-regex-link-inline . ((1 markdown-markup-face nil t) ; ! (optional)
2307 (2 markdown-markup-face) ; [
2308 (3 markdown-link-face) ; text
2309 (4 markdown-markup-face) ; ]
2310 (5 markdown-markup-face) ; (
2311 (6 markdown-url-face) ; url
2312 (7 markdown-link-title-face nil t) ; "title" (optional)
2313 (8 markdown-markup-face))) ; )
2314 (,markdown-regex-link-reference . ((1 markdown-markup-face nil t) ; ! (optional)
2315 (2 markdown-markup-face) ; [
2316 (3 markdown-link-face) ; text
2317 (4 markdown-markup-face) ; ]
2318 (5 markdown-markup-face) ; [
2319 (6 markdown-reference-face) ; label
2320 (7 markdown-markup-face))) ; ]
2321 (,markdown-regex-reference-definition . ((1 markdown-markup-face) ; [
2322 (2 markdown-reference-face) ; label
2323 (3 markdown-markup-face) ; ]
2324 (4 markdown-markup-face) ; :
2325 (5 markdown-url-face) ; url
2326 (6 markdown-link-title-face))) ; "title" (optional)
2327 ;; Math mode $..$
2328 (markdown-match-math-single . ((1 markdown-markup-face prepend)
2329 (2 markdown-math-face append)
2330 (3 markdown-markup-face prepend)))
2331 ;; Math mode $$..$$
2332 (markdown-match-math-double . ((1 markdown-markup-face prepend)
2333 (2 markdown-math-face append)
2334 (3 markdown-markup-face prepend)))
2335 (markdown-match-bold . ((1 markdown-markup-face prepend)
2336 (2 markdown-bold-face append)
2337 (3 markdown-markup-face prepend)))
2338 (markdown-match-italic . ((1 markdown-markup-face prepend)
2339 (2 markdown-italic-face append)
2340 (3 markdown-markup-face prepend)))
2341 (,markdown-regex-uri . markdown-link-face)
2342 (,markdown-regex-email . markdown-link-face)
2343 (,markdown-regex-line-break . (1 markdown-line-break-face prepend)))
2345 "Syntax highlighting for Markdown files.")
2347 (defvar markdown-mode-font-lock-keywords nil
2348 "Default highlighting expressions for Markdown mode.
2349 This variable is defined as a buffer-local variable for dynamic
2350 extension support.")
2352 ;; Footnotes
2353 (defvar markdown-footnote-counter 0
2354 "Counter for footnote numbers.")
2355 (make-variable-buffer-local 'markdown-footnote-counter)
2357 (defconst markdown-footnote-chars
2358 "[[:alnum:]-]"
2359 "Regular expression matching any character that is allowed in a footnote identifier.")
2361 (defconst markdown-regex-footnote-definition
2362 (concat "^\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:\\(?:[ \t]+\\|$\\)")
2363 "Regular expression matching a footnote definition, capturing the label.")
2366 ;;; Compatibility =============================================================
2368 (defun markdown-replace-regexp-in-string (regexp rep string)
2369 "Replace ocurrences of REGEXP with REP in STRING.
2370 This is a compatibility wrapper to provide `replace-regexp-in-string'
2371 in XEmacs 21."
2372 (if (featurep 'xemacs)
2373 (replace-in-string string regexp rep)
2374 (replace-regexp-in-string regexp rep string)))
2376 ;; `markdown-use-region-p' is a compatibility function which checks
2377 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
2378 (eval-and-compile
2379 (cond
2380 ;; Emacs 24 and newer
2381 ((fboundp 'use-region-p)
2382 (defalias 'markdown-use-region-p 'use-region-p))
2383 ;; XEmacs
2384 ((fboundp 'region-active-p)
2385 (defalias 'markdown-use-region-p 'region-active-p))))
2387 (defun markdown-use-buttons-p ()
2388 "Determine whether this Emacs supports buttons."
2389 (or (featurep 'button) (locate-library "button")))
2391 ;; Use new names for outline-mode functions in Emacs 25 and later.
2392 (eval-and-compile
2393 (defalias 'markdown-hide-sublevels
2394 (if (fboundp 'outline-hide-sublevels)
2395 'outline-hide-sublevels
2396 'hide-sublevels))
2397 (defalias 'markdown-show-all
2398 (if (fboundp 'outline-show-all)
2399 'outline-show-all
2400 'show-all))
2401 (defalias 'markdown-hide-body
2402 (if (fboundp 'outline-hide-body)
2403 'outline-hide-body
2404 'hide-body))
2405 (defalias 'markdown-show-children
2406 (if (fboundp 'outline-show-children)
2407 'outline-show-children
2408 'show-children))
2409 (defalias 'markdown-show-subtree
2410 (if (fboundp 'outline-show-subtree)
2411 'outline-show-subtree
2412 'show-subtree))
2413 (defalias 'markdown-hide-subtree
2414 (if (fboundp 'outline-hide-subtree)
2415 'outline-hide-subtree
2416 'hide-subtree)))
2418 ;; Provide directory-name-p to Emacs 24
2419 (defsubst markdown-directory-name-p (name)
2420 "Return non-nil if NAME ends with a directory separator character.
2421 Taken from `directory-name-p' from Emacs 25 and provided here for
2422 backwards compatibility."
2423 (let ((len (length name))
2424 (lastc ?.))
2425 (if (> len 0)
2426 (setq lastc (aref name (1- len))))
2427 (or (= lastc ?/)
2428 (and (memq system-type '(windows-nt ms-dos))
2429 (= lastc ?\\)))))
2431 ;; Provide a function to find files recursively in Emacs 24.
2432 (defalias 'markdown-directory-files-recursively
2433 (if (fboundp 'directory-files-recursively)
2434 'directory-files-recursively
2435 (lambda (dir regexp)
2436 "Return list of all files under DIR that have file names matching REGEXP.
2437 This function works recursively. Files are returned in \"depth first\"
2438 order, and files from each directory are sorted in alphabetical order.
2439 Each file name appears in the returned list in its absolute form.
2440 Based on `directory-files-recursively' from Emacs 25 and provided
2441 here for backwards compatibility."
2442 (let ((result nil)
2443 (files nil)
2444 ;; When DIR is "/", remote file names like "/method:" could
2445 ;; also be offered. We shall suppress them.
2446 (tramp-mode (and tramp-mode (file-remote-p (expand-file-name dir)))))
2447 (dolist (file (sort (file-name-all-completions "" dir)
2448 'string<))
2449 (unless (member file '("./" "../"))
2450 (if (markdown-directory-name-p file)
2451 (let* ((leaf (substring file 0 (1- (length file))))
2452 (full-file (expand-file-name leaf dir)))
2453 (setq result
2454 (nconc result (markdown-directory-files-recursively
2455 full-file regexp))))
2456 (when (string-match regexp file)
2457 (push (expand-file-name file dir) files)))))
2458 (nconc result (nreverse files))))))
2461 ;;; Markdown Parsing Functions ================================================
2463 (defun markdown-cur-line-blank-p ()
2464 "Return t if the current line is blank and nil otherwise."
2465 (save-excursion
2466 (beginning-of-line)
2467 (looking-at-p "^\\s *$")))
2469 (defun markdown-prev-line-blank-p ()
2470 "Return t if the previous line is blank and nil otherwise.
2471 If we are at the first line, then consider the previous line to be blank."
2472 (or (= (line-beginning-position) (point-min))
2473 (save-excursion
2474 (forward-line -1)
2475 (markdown-cur-line-blank-p))))
2477 (defun markdown-next-line-blank-p ()
2478 "Return t if the next line is blank and nil otherwise.
2479 If we are at the last line, then consider the next line to be blank."
2480 (or (= (line-end-position) (point-max))
2481 (save-excursion
2482 (forward-line 1)
2483 (markdown-cur-line-blank-p))))
2485 (defun markdown-prev-line-indent ()
2486 "Return the number of leading whitespace characters in the previous line.
2487 Return 0 if the current line is the first line in the buffer."
2488 (save-excursion
2489 (if (= (line-beginning-position) (point-min))
2491 (forward-line -1)
2492 (current-indentation))))
2494 (defun markdown-next-line-indent ()
2495 "Return the number of leading whitespace characters in the next line.
2496 Return 0 if line is the last line in the buffer."
2497 (save-excursion
2498 (if (= (line-end-position) (point-max))
2500 (forward-line 1)
2501 (current-indentation))))
2503 (defun markdown-cur-non-list-indent ()
2504 "Return beginning position of list item text (not including the list marker).
2505 Return nil if the current line is not the beginning of a list item."
2506 (save-match-data
2507 (save-excursion
2508 (beginning-of-line)
2509 (when (re-search-forward markdown-regex-list (line-end-position) t)
2510 (current-column)))))
2512 (defun markdown-prev-non-list-indent ()
2513 "Return position of the first non-list-marker on the previous line."
2514 (save-excursion
2515 (forward-line -1)
2516 (markdown-cur-non-list-indent)))
2518 (defun markdown-new-baseline-p ()
2519 "Determine if the current line begins a new baseline level."
2520 (save-excursion
2521 (beginning-of-line)
2522 (or (looking-at-p markdown-regex-header)
2523 (looking-at-p markdown-regex-hr)
2524 (and (null (markdown-cur-non-list-indent))
2525 (= (current-indentation) 0)
2526 (markdown-prev-line-blank-p)))))
2528 (defun markdown-search-backward-baseline ()
2529 "Search backward baseline point with no indentation and not a list item."
2530 (end-of-line)
2531 (let (stop)
2532 (while (not (or stop (bobp)))
2533 (re-search-backward markdown-regex-block-separator-noindent nil t)
2534 (when (match-end 2)
2535 (goto-char (match-end 2))
2536 (cond
2537 ((markdown-new-baseline-p)
2538 (setq stop t))
2539 ((looking-at-p markdown-regex-list)
2540 (setq stop nil))
2541 (t (setq stop t)))))))
2543 (defun markdown-update-list-levels (marker indent levels)
2544 "Update list levels given list MARKER, block INDENT, and current LEVELS.
2545 Here, MARKER is a string representing the type of list, INDENT is an integer
2546 giving the indentation, in spaces, of the current block, and LEVELS is a
2547 list of the indentation levels of parent list items. When LEVELS is nil,
2548 it means we are at baseline (not inside of a nested list)."
2549 (cond
2550 ;; New list item at baseline.
2551 ((and marker (null levels))
2552 (setq levels (list indent)))
2553 ;; List item with greater indentation (four or more spaces).
2554 ;; Increase list level.
2555 ((and marker (>= indent (+ (car levels) 4)))
2556 (setq levels (cons indent levels)))
2557 ;; List item with greater or equal indentation (less than four spaces).
2558 ;; Do not increase list level.
2559 ((and marker (>= indent (car levels)))
2560 levels)
2561 ;; Lesser indentation level.
2562 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
2563 ;; indentation could move back more than one list level). Note
2564 ;; that this block need not be the beginning of list item.
2565 ((< indent (car levels))
2566 (while (and (> (length levels) 1)
2567 (< indent (+ (cadr levels) 4)))
2568 (setq levels (cdr levels)))
2569 levels)
2570 ;; Otherwise, do nothing.
2571 (t levels)))
2573 (defun markdown-calculate-list-levels ()
2574 "Calculate list levels at point.
2575 Return a list of the form (n1 n2 n3 ...) where n1 is the
2576 indentation of the deepest nested list item in the branch of
2577 the list at the point, n2 is the indentation of the parent
2578 list item, and so on. The depth of the list item is therefore
2579 the length of the returned list. If the point is not at or
2580 immediately after a list item, return nil."
2581 (save-excursion
2582 (let ((first (point)) levels indent pre-regexp)
2583 ;; Find a baseline point with zero list indentation
2584 (markdown-search-backward-baseline)
2585 ;; Search for all list items between baseline and LOC
2586 (while (and (< (point) first)
2587 (re-search-forward markdown-regex-list first t))
2588 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
2589 (beginning-of-line)
2590 (cond
2591 ;; Make sure this is not a header or hr
2592 ((markdown-new-baseline-p) (setq levels nil))
2593 ;; Make sure this is not a line from a pre block
2594 ((looking-at-p pre-regexp))
2595 ;; If not, then update levels
2597 (setq indent (current-indentation))
2598 (setq levels (markdown-update-list-levels (match-string 2)
2599 indent levels))))
2600 (end-of-line))
2601 levels)))
2603 (defun markdown-prev-list-item (level)
2604 "Search backward from point for a list item with indentation LEVEL.
2605 Set point to the beginning of the item, and return point, or nil
2606 upon failure."
2607 (let (bounds indent prev)
2608 (setq prev (point))
2609 (forward-line -1)
2610 (setq indent (current-indentation))
2611 (while
2612 (cond
2613 ;; List item
2614 ((and (looking-at-p markdown-regex-list)
2615 (setq bounds (markdown-cur-list-item-bounds)))
2616 (cond
2617 ;; Stop and return point at item of lesser or equal indentation
2618 ((<= (nth 3 bounds) level)
2619 (setq prev (point))
2620 nil)
2621 ;; Stop at beginning of buffer
2622 ((bobp) (setq prev nil))
2623 ;; Continue at item with greater indentation
2624 ((> (nth 3 bounds) level) t)))
2625 ;; Stop at beginning of buffer
2626 ((bobp) (setq prev nil))
2627 ;; Continue if current line is blank
2628 ((markdown-cur-line-blank-p) t)
2629 ;; Continue while indentation is the same or greater
2630 ((>= indent level) t)
2631 ;; Stop if current indentation is less than list item
2632 ;; and the next is blank
2633 ((and (< indent level)
2634 (markdown-next-line-blank-p))
2635 (setq prev nil))
2636 ;; Stop at a header
2637 ((looking-at-p markdown-regex-header) (setq prev nil))
2638 ;; Stop at a horizontal rule
2639 ((looking-at-p markdown-regex-hr) (setq prev nil))
2640 ;; Otherwise, continue.
2641 (t t))
2642 (forward-line -1)
2643 (setq indent (current-indentation)))
2644 prev))
2646 (defun markdown-next-list-item (level)
2647 "Search forward from point for the next list item with indentation LEVEL.
2648 Set point to the beginning of the item, and return point, or nil
2649 upon failure."
2650 (let (bounds indent next)
2651 (setq next (point))
2652 (forward-line)
2653 (setq indent (current-indentation))
2654 (while
2655 (cond
2656 ;; Stop at end of the buffer.
2657 ((eobp) nil)
2658 ;; Continue if the current line is blank
2659 ((markdown-cur-line-blank-p) t)
2660 ;; List item
2661 ((and (looking-at-p markdown-regex-list)
2662 (setq bounds (markdown-cur-list-item-bounds)))
2663 (cond
2664 ;; Continue at item with greater indentation
2665 ((> (nth 3 bounds) level) t)
2666 ;; Stop and return point at item of equal indentation
2667 ((= (nth 3 bounds) level)
2668 (setq next (point))
2669 nil)
2670 ;; Stop and return nil at item with lesser indentation
2671 ((< (nth 3 bounds) level)
2672 (setq next nil)
2673 nil)))
2674 ;; Continue while indentation is the same or greater
2675 ((>= indent level) t)
2676 ;; Stop if current indentation is less than list item
2677 ;; and the previous line was blank.
2678 ((and (< indent level)
2679 (markdown-prev-line-blank-p))
2680 (setq next nil))
2681 ;; Stop at a header
2682 ((looking-at-p markdown-regex-header) (setq next nil))
2683 ;; Stop at a horizontal rule
2684 ((looking-at-p markdown-regex-hr) (setq next nil))
2685 ;; Otherwise, continue.
2686 (t t))
2687 (forward-line)
2688 (setq indent (current-indentation)))
2689 next))
2691 (defun markdown-cur-list-item-end (level)
2692 "Move to the end of the current list item with nonlist indentation LEVEL.
2693 If the point is not in a list item, do nothing."
2694 (let (indent)
2695 (forward-line)
2696 (setq indent (current-indentation))
2697 (while
2698 (cond
2699 ;; Stop at end of the buffer.
2700 ((eobp) nil)
2701 ;; Continue if the current line is blank
2702 ((markdown-cur-line-blank-p) t)
2703 ;; Continue while indentation is the same or greater
2704 ((>= indent level) t)
2705 ;; Stop if current indentation is less than list item
2706 ;; and the previous line was blank.
2707 ((and (< indent level)
2708 (markdown-prev-line-blank-p))
2709 nil)
2710 ;; Stop at a new list item of the same or lesser indentation
2711 ((looking-at-p markdown-regex-list) nil)
2712 ;; Stop at a header
2713 ((looking-at-p markdown-regex-header) nil)
2714 ;; Stop at a horizontal rule
2715 ((looking-at-p markdown-regex-hr) nil)
2716 ;; Otherwise, continue.
2717 (t t))
2718 (forward-line)
2719 (setq indent (current-indentation)))
2720 ;; Don't skip over whitespace for empty list items (marker and
2721 ;; whitespace only), just move to end of whitespace.
2722 (if (looking-back (concat markdown-regex-list "\\s-*") nil)
2723 (goto-char (match-end 3))
2724 (skip-syntax-backward "-"))))
2726 (defun markdown-cur-list-item-bounds ()
2727 "Return bounds and indentation of the current list item.
2728 Return a list of the form (begin end indent nonlist-indent marker).
2729 If the point is not inside a list item, return nil.
2730 Leave match data intact for `markdown-regex-list'."
2731 (let (cur prev-begin prev-end indent nonlist-indent marker)
2732 ;; Store current location
2733 (setq cur (point))
2734 ;; Verify that cur is between beginning and end of item
2735 (save-excursion
2736 (end-of-line)
2737 (when (re-search-backward markdown-regex-list nil t)
2738 (setq prev-begin (match-beginning 0))
2739 (setq indent (length (match-string 1)))
2740 (setq nonlist-indent (length (match-string 0)))
2741 (setq marker (concat (match-string 2) (match-string 3)))
2742 (save-match-data
2743 (markdown-cur-list-item-end nonlist-indent)
2744 (setq prev-end (point)))
2745 (when (and (>= cur prev-begin)
2746 (<= cur prev-end)
2747 nonlist-indent)
2748 (list prev-begin prev-end indent nonlist-indent marker))))))
2750 (defun markdown-list-item-at-point-p ()
2751 "Return t if there is a list item at the point and nil otherwise."
2752 (save-match-data (markdown-cur-list-item-bounds)))
2754 (defun markdown-bounds-of-thing-at-point (thing)
2755 "Call `bounds-of-thing-at-point' for THING with slight modifications.
2756 Does not include trailing newlines when THING is 'line. Handles the
2757 end of buffer case by setting both endpoints equal to the value of
2758 `point-max', since an empty region will trigger empty markup insertion.
2759 Return bounds of form (beg . end) if THING is found, or nil otherwise."
2760 (let* ((bounds (bounds-of-thing-at-point thing))
2761 (a (car bounds))
2762 (b (cdr bounds)))
2763 (when bounds
2764 (when (eq thing 'line)
2765 (cond ((and (eobp) (markdown-cur-line-blank-p))
2766 (setq a b))
2767 ((char-equal (char-before b) ?\^J)
2768 (setq b (1- b)))))
2769 (cons a b))))
2771 (defun markdown-reference-definition (reference)
2772 "Find out whether Markdown REFERENCE is defined.
2773 REFERENCE should not include the square brackets.
2774 When REFERENCE is defined, return a list of the form (text start end)
2775 containing the definition text itself followed by the start and end
2776 locations of the text. Otherwise, return nil.
2777 Leave match data for `markdown-regex-reference-definition'
2778 intact additional processing."
2779 (let ((reference (downcase reference)))
2780 (save-excursion
2781 (goto-char (point-min))
2782 (catch 'found
2783 (while (re-search-forward markdown-regex-reference-definition nil t)
2784 (when (string= reference (downcase (match-string-no-properties 2)))
2785 (throw 'found
2786 (list (match-string-no-properties 5)
2787 (match-beginning 5) (match-end 5)))))))))
2789 (defun markdown-get-defined-references ()
2790 "Return a list of all defined reference labels (not including square brackets)."
2791 (save-excursion
2792 (goto-char (point-min))
2793 (let (refs)
2794 (while (re-search-forward markdown-regex-reference-definition nil t)
2795 (let ((target (match-string-no-properties 2)))
2796 (cl-pushnew target refs :test #'equal)))
2797 (reverse refs))))
2799 (defun markdown-inline-code-at-point ()
2800 "Return non-nil if the point is at an inline code fragment.
2801 Return nil otherwise. Set match data according to
2802 `markdown-match-code' upon success.
2803 This function searches the block for a code fragment that
2804 contains the point using `markdown-match-code'. We do this
2805 because `thing-at-point-looking-at' does not work reliably with
2806 `markdown-regex-code'.
2808 The match data is set as follows:
2809 Group 1 matches the opening backquotes.
2810 Group 2 matches the code fragment itself, without backquotes.
2811 Group 3 matches the closing backquotes."
2812 (save-excursion
2813 (let ((old-point (point))
2814 (end-of-block (progn (markdown-end-of-text-block) (point)))
2815 found)
2816 (markdown-beginning-of-text-block)
2817 (while (and (markdown-match-code end-of-block)
2818 (setq found t)
2819 (< (match-end 0) old-point)))
2820 (and found ; matched something
2821 (<= (match-beginning 0) old-point) ; match contains old-point
2822 (>= (match-end 0) old-point)))))
2824 (defun markdown-inline-code-at-point-p ()
2825 "Return non-nil if there is inline code at the point.
2826 This is a predicate function counterpart to
2827 `markdown-inline-code-at-point' which does not modify the match
2828 data. See `markdown-code-block-at-point-p' for code blocks."
2829 (save-match-data (markdown-inline-code-at-point)))
2831 (make-obsolete 'markdown-code-at-point-p 'markdown-inline-code-at-point-p "2017-05-10")
2833 (defun markdown-code-block-at-pos (pos)
2834 "Return match data list if there is a code block at POS.
2835 This includes pre blocks, tilde-fenced code blocks, and GFM
2836 quoted code blocks. Return nil otherwise."
2837 (or (get-text-property pos 'markdown-pre)
2838 (markdown-get-enclosing-fenced-block-construct pos)
2839 ;; polymode removes text properties set by markdown-mode, so
2840 ;; check if `poly-markdown-mode' is active and whether the
2841 ;; `chunkmode' property is non-nil at POS.
2842 (and (bound-and-true-p poly-markdown-mode)
2843 (get-text-property pos 'chunkmode))))
2845 ;; Function was renamed to emphasize that it does not modify match-data.
2846 (defalias 'markdown-code-block-at-point 'markdown-code-block-at-point-p)
2848 (defun markdown-code-block-at-point-p ()
2849 "Return non-nil if there is a code block at the point.
2850 This includes pre blocks, tilde-fenced code blocks, and GFM
2851 quoted code blocks. This function does not modify the match
2852 data. See `markdown-inline-code-at-point-p' for inline code."
2853 (save-match-data (markdown-code-block-at-pos (point))))
2856 ;;; Markdown Font Lock Matching Functions =====================================
2858 (defun markdown-range-property-any (begin end prop prop-values)
2859 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
2860 Also returns t if PROP is a list containing one of the PROP-VALUES.
2861 Return nil otherwise."
2862 (let (props)
2863 (catch 'found
2864 (dolist (loc (number-sequence begin end))
2865 (when (setq props (get-char-property loc prop))
2866 (cond ((listp props)
2867 ;; props is a list, check for membership
2868 (dolist (val prop-values)
2869 (when (memq val props) (throw 'found loc))))
2871 ;; props is a scalar, check for equality
2872 (dolist (val prop-values)
2873 (when (eq val props) (throw 'found loc))))))))))
2875 (defun markdown-range-properties-exist (begin end props)
2876 (cl-loop
2877 for loc in (number-sequence begin end)
2878 with result = nil
2879 while (not
2880 (setq result
2881 (cl-some (lambda (prop) (get-char-property loc prop)) props)))
2882 finally return result))
2884 (defun markdown-match-inline-generic (regex last)
2885 "Match inline REGEX from the point to LAST."
2886 (when (re-search-forward regex last t)
2887 (let ((bounds (markdown-code-block-at-pos (match-beginning 1))))
2888 (if (null bounds)
2889 ;; Not in a code block: keep match data and return t when in bounds
2890 (<= (match-end 0) last)
2891 ;; In code block: move past it and recursively search again
2892 (when (< (goto-char (nth 1 bounds)) last)
2893 (markdown-match-inline-generic regex last))))))
2895 (defun markdown-match-code (last)
2896 "Match inline code fragments from point to LAST."
2897 (unless (bobp)
2898 (backward-char 1))
2899 (when (markdown-match-inline-generic markdown-regex-code last)
2900 (set-match-data (list (match-beginning 1) (match-end 1)
2901 (match-beginning 2) (match-end 2)
2902 (match-beginning 3) (match-end 3)
2903 (match-beginning 4) (match-end 4)))
2904 (goto-char (1+ (match-end 0)))))
2906 (defun markdown-match-bold (last)
2907 "Match inline bold from the point to LAST."
2908 (when (markdown-match-inline-generic markdown-regex-bold last)
2909 (let ((begin (match-beginning 2)) (end (match-end 2)))
2910 (cond
2911 ((markdown-range-property-any
2912 begin end 'face (list markdown-inline-code-face
2913 markdown-math-face))
2914 (goto-char (1+ (match-end 0)))
2915 (markdown-match-bold last))
2917 (set-match-data (list (match-beginning 2) (match-end 2)
2918 (match-beginning 3) (match-end 3)
2919 (match-beginning 4) (match-end 4)
2920 (match-beginning 5) (match-end 5)))
2921 (goto-char (1+ (match-end 0))))))))
2923 (defun markdown-match-italic (last)
2924 "Match inline italics from the point to LAST."
2925 (let ((regex (if (eq major-mode 'gfm-mode)
2926 markdown-regex-gfm-italic markdown-regex-italic)))
2927 (when (markdown-match-inline-generic regex last)
2928 (let ((begin (match-beginning 1)) (end (match-end 1)))
2929 (cond
2930 ((markdown-range-property-any
2931 begin begin 'face (list markdown-url-face))
2932 ;; Italics shouldn't begin inside a URL due to an underscore
2933 (goto-char (min (1+ (match-end 0)) last))
2934 (markdown-match-italic last))
2935 ((markdown-range-property-any
2936 begin end 'face (list markdown-inline-code-face
2937 markdown-bold-face
2938 markdown-list-face
2939 markdown-math-face))
2940 (goto-char (1+ (match-end 0)))
2941 (markdown-match-italic last))
2943 (set-match-data (list (match-beginning 1) (match-end 1)
2944 (match-beginning 2) (match-end 2)
2945 (match-beginning 3) (match-end 3)
2946 (match-beginning 4) (match-end 4)))
2947 (goto-char (1+ (match-end 0)))))))))
2949 (defun markdown-match-math-generic (regex last)
2950 "Match REGEX from point to LAST.
2951 REGEX is either `markdown-regex-math-inline-single' for matching
2952 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
2953 (when (and markdown-enable-math (markdown-match-inline-generic regex last))
2954 (let ((begin (match-beginning 1)) (end (match-end 1)))
2955 (prog1
2956 (if (or (markdown-range-property-any
2957 begin end 'face (list markdown-inline-code-face
2958 markdown-bold-face))
2959 (markdown-range-properties-exist
2960 begin end
2961 (markdown-get-fenced-block-middle-properties)))
2962 (markdown-match-math-generic regex last)
2964 (goto-char (1+ (match-end 0)))))))
2966 (defun markdown-match-math-single (last)
2967 "Match single quoted $..$ math from point to LAST."
2968 (markdown-match-math-generic markdown-regex-math-inline-single last))
2970 (defun markdown-match-math-double (last)
2971 "Match double quoted $$..$$ math from point to LAST."
2972 (markdown-match-math-generic markdown-regex-math-inline-double last))
2974 (defun markdown-match-propertized-text (property last)
2975 "Match text with PROPERTY from point to LAST.
2976 Restore match data previously stored in PROPERTY."
2977 (let ((saved (get-text-property (point) property))
2978 pos)
2979 (unless saved
2980 (setq pos (next-single-char-property-change (point) property nil last))
2981 (setq saved (get-text-property pos property)))
2982 (when saved
2983 (set-match-data saved)
2984 ;; Step at least one character beyond point. Otherwise
2985 ;; `font-lock-fontify-keywords-region' infloops.
2986 (goto-char (min (1+ (max (match-end 0) (point)))
2987 (point-max)))
2988 saved)))
2990 (defun markdown-match-pre-blocks (last)
2991 "Match preformatted blocks from point to LAST.
2992 Use data stored in 'markdown-pre text property during syntax
2993 analysis."
2994 (markdown-match-propertized-text 'markdown-pre last))
2996 (defun markdown-match-gfm-code-blocks (last)
2997 "Match GFM quoted code blocks from point to LAST.
2998 Use data stored in 'markdown-gfm-code text property during syntax
2999 analysis."
3000 (markdown-match-propertized-text 'markdown-gfm-code last))
3002 (defun markdown-match-gfm-open-code-blocks (last)
3003 (markdown-match-propertized-text 'markdown-gfm-block-begin last))
3005 (defun markdown-match-gfm-close-code-blocks (last)
3006 (markdown-match-propertized-text 'markdown-gfm-block-end last))
3008 (defun markdown-match-fenced-code-blocks (last)
3009 "Match fenced code blocks from the point to LAST."
3010 (markdown-match-propertized-text 'markdown-fenced-code last))
3012 (defun markdown-match-fenced-start-code-block (last)
3013 (markdown-match-propertized-text 'markdown-tilde-fence-begin last))
3015 (defun markdown-match-fenced-end-code-block (last)
3016 (markdown-match-propertized-text 'markdown-tilde-fence-end last))
3018 (defun markdown-match-blockquotes (last)
3019 "Match blockquotes from point to LAST.
3020 Use data stored in 'markdown-blockquote text property during syntax
3021 analysis."
3022 (markdown-match-propertized-text 'markdown-blockquote last))
3024 (defun markdown-match-heading-1-setext (last)
3025 "Match level 1 setext headings from point to LAST."
3026 (markdown-match-propertized-text 'markdown-heading-1-setext last))
3028 (defun markdown-match-heading-2-setext (last)
3029 "Match level 2 setext headings from point to LAST."
3030 (markdown-match-propertized-text 'markdown-heading-2-setext last))
3032 (defun markdown-match-heading-1-atx (last)
3033 "Match level 1 ATX headings from point to LAST."
3034 (markdown-match-propertized-text 'markdown-heading-1-atx last))
3036 (defun markdown-match-heading-2-atx (last)
3037 "Match level 2 ATX headings from point to LAST."
3038 (markdown-match-propertized-text 'markdown-heading-2-atx last))
3040 (defun markdown-match-heading-3-atx (last)
3041 "Match level 3 ATX headings from point to LAST."
3042 (markdown-match-propertized-text 'markdown-heading-3-atx last))
3044 (defun markdown-match-heading-4-atx (last)
3045 "Match level 4 ATX headings from point to LAST."
3046 (markdown-match-propertized-text 'markdown-heading-4-atx last))
3048 (defun markdown-match-heading-5-atx (last)
3049 "Match level 5 ATX headings from point to LAST."
3050 (markdown-match-propertized-text 'markdown-heading-5-atx last))
3052 (defun markdown-match-heading-6-atx (last)
3053 "Match level 6 ATX headings from point to LAST."
3054 (markdown-match-propertized-text 'markdown-heading-6-atx last))
3056 (defun markdown-match-hr (last)
3057 "Match horizontal rules comments from the point to LAST."
3058 (while (and (re-search-forward markdown-regex-hr last t)
3059 (or (markdown-on-heading-p)
3060 (markdown-code-block-at-point-p))
3061 (< (match-end 0) last))
3062 (forward-line))
3063 (beginning-of-line)
3064 (cond ((looking-at-p markdown-regex-hr)
3065 (forward-line)
3067 (t nil)))
3069 (defun markdown-match-comments (last)
3070 "Match HTML comments from the point to LAST."
3071 (when (and (skip-syntax-forward "^<" last))
3072 (let ((beg (point)))
3073 (when (and (skip-syntax-forward "^>" last) (< (point) last))
3074 (forward-char)
3075 (set-match-data (list beg (point)))
3076 t))))
3078 (defun markdown-get-match-boundaries (start-header end-header last &optional pos)
3079 (save-excursion
3080 (goto-char (or pos (point-min)))
3081 (cl-loop
3082 with cur-result = nil
3083 and st-hdr = (or start-header "\\`")
3084 and end-hdr = (or end-header "\n\n\\|\n\\'\\|\\'")
3085 while (and (< (point) last)
3086 (re-search-forward st-hdr last t)
3087 (progn
3088 (setq cur-result (match-data))
3089 (re-search-forward end-hdr nil t)))
3090 collect (list cur-result (match-data)))))
3092 (defvar markdown-conditional-search-function #'re-search-forward
3093 "Conditional search function used in `markdown-search-until-condition'.
3094 Made into a variable to allow for dynamic let-binding.")
3096 (defun markdown-search-until-condition (condition &rest args)
3097 (let (ret)
3098 (while (and (not ret) (apply markdown-conditional-search-function args))
3099 (setq ret (funcall condition)))
3100 ret))
3102 (defun markdown-match-generic-metadata
3103 (regexp last &optional start-header end-header)
3104 "Match generic metadata specified by REGEXP from the point to LAST.
3105 If START-HEADER is nil, we assume metadata can only occur at the
3106 very top of a file (\"\\`\"). If END-HEADER is nil, we assume it
3107 is \"\n\n\""
3108 (let* ((header-bounds
3109 (markdown-get-match-boundaries start-header end-header last))
3110 (enclosing-header
3111 (cl-find-if ; just take first if multiple
3112 (lambda (match-bounds)
3113 (cl-destructuring-bind (begin end) (cl-second match-bounds)
3114 (and (< (point) begin)
3115 (save-excursion (re-search-forward regexp end t)))))
3116 header-bounds))
3117 (header-begin
3118 (when enclosing-header (cl-second (cl-first enclosing-header))))
3119 (header-end
3120 (when enclosing-header (cl-first (cl-second enclosing-header)))))
3121 (cond ((null enclosing-header)
3122 ;; Don't match anything outside of a header.
3123 nil)
3124 ((markdown-search-until-condition
3125 (lambda () (> (point) header-begin)) regexp (min last header-end) t)
3126 ;; If a metadata item is found, it may span several lines.
3127 (let ((key-beginning (match-beginning 1))
3128 (key-end (match-end 1))
3129 (markup-begin (match-beginning 2))
3130 (markup-end (match-end 2))
3131 (value-beginning (match-beginning 3)))
3132 (set-match-data (list key-beginning (point) ; complete metadata
3133 key-beginning key-end ; key
3134 markup-begin markup-end ; markup
3135 value-beginning (point))) ; value
3137 (t nil))))
3139 (defun markdown-match-declarative-metadata (last)
3140 "Match declarative metadata from the point to LAST."
3141 (markdown-match-generic-metadata markdown-regex-declarative-metadata last))
3143 (defun markdown-match-pandoc-metadata (last)
3144 "Match Pandoc metadata from the point to LAST."
3145 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
3147 (defun markdown-match-yaml-metadata-begin (last)
3148 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last))
3150 (defun markdown-match-yaml-metadata-end (last)
3151 (markdown-match-propertized-text 'markdown-yaml-metadata-end last))
3153 (defun markdown-match-yaml-metadata-key (last)
3154 (markdown-match-propertized-text 'markdown-metadata-key last))
3157 ;;; Syntax Table ==============================================================
3159 (defvar markdown-mode-syntax-table
3160 (let ((tab (make-syntax-table text-mode-syntax-table)))
3161 (modify-syntax-entry ?\" "." tab)
3162 tab)
3163 "Syntax table for `markdown-mode'.")
3166 ;;; Element Insertion =========================================================
3168 (defun markdown-ensure-blank-line-before ()
3169 "If previous line is not already blank, insert a blank line before point."
3170 (unless (bolp) (insert "\n"))
3171 (unless (or (bobp) (looking-back "\n\\s-*\n" nil)) (insert "\n")))
3173 (defun markdown-ensure-blank-line-after ()
3174 "If following line is not already blank, insert a blank line after point.
3175 Return the point where it was originally."
3176 (save-excursion
3177 (unless (eolp) (insert "\n"))
3178 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
3180 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
3181 "Insert the strings S1 and S2, wrapping around region or THING.
3182 If a region is specified by the optional BEG and END arguments,
3183 wrap the strings S1 and S2 around that region.
3184 If there is an active region, wrap the strings S1 and S2 around
3185 the region. If there is not an active region but the point is at
3186 THING, wrap that thing (which defaults to word). Otherwise, just
3187 insert S1 and S2 and place the cursor in between. Return the
3188 bounds of the entire wrapped string, or nil if nothing was wrapped
3189 and S1 and S2 were only inserted."
3190 (let (a b bounds new-point)
3191 (cond
3192 ;; Given region
3193 ((and beg end)
3194 (setq a beg
3195 b end
3196 new-point (+ (point) (length s1))))
3197 ;; Active region
3198 ((markdown-use-region-p)
3199 (setq a (region-beginning)
3200 b (region-end)
3201 new-point (+ (point) (length s1))))
3202 ;; Thing (word) at point
3203 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
3204 (setq a (car bounds)
3205 b (cdr bounds)
3206 new-point (+ (point) (length s1))))
3207 ;; No active region and no word
3209 (setq a (point)
3210 b (point))))
3211 (goto-char b)
3212 (insert s2)
3213 (goto-char a)
3214 (insert s1)
3215 (when new-point (goto-char new-point))
3216 (if (= a b)
3218 (setq b (+ b (length s1) (length s2)))
3219 (cons a b))))
3221 (defun markdown-point-after-unwrap (cur prefix suffix)
3222 "Return desired position of point after an unwrapping operation.
3223 CUR gives the position of the point before the operation.
3224 Additionally, two cons cells must be provided. PREFIX gives the
3225 bounds of the prefix string and SUFFIX gives the bounds of the
3226 suffix string."
3227 (cond ((< cur (cdr prefix)) (car prefix))
3228 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
3229 ((<= cur (cdr suffix))
3230 (- cur (+ (- (cdr prefix) (car prefix))
3231 (- cur (car suffix)))))
3232 (t cur)))
3234 (defun markdown-unwrap-thing-at-point (regexp all text)
3235 "Remove prefix and suffix of thing at point and reposition the point.
3236 When the thing at point matches REGEXP, replace the subexpression
3237 ALL with the string in subexpression TEXT. Reposition the point
3238 in an appropriate location accounting for the removal of prefix
3239 and suffix strings. Return new bounds of string from group TEXT.
3240 When REGEXP is nil, assumes match data is already set."
3241 (when (or (null regexp)
3242 (thing-at-point-looking-at regexp))
3243 (let ((cur (point))
3244 (prefix (cons (match-beginning all) (match-beginning text)))
3245 (suffix (cons (match-end text) (match-end all)))
3246 (bounds (cons (match-beginning text) (match-end text))))
3247 ;; Replace the thing at point
3248 (replace-match (match-string text) t t nil all)
3249 ;; Reposition the point
3250 (goto-char (markdown-point-after-unwrap cur prefix suffix))
3251 ;; Adjust bounds
3252 (setq bounds (cons (car prefix)
3253 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
3255 (defun markdown-unwrap-things-in-region (beg end regexp all text)
3256 "Remove prefix and suffix of all things in region from BEG to END.
3257 When a thing in the region matches REGEXP, replace the
3258 subexpression ALL with the string in subexpression TEXT.
3259 Return a cons cell containing updated bounds for the region."
3260 (save-excursion
3261 (goto-char beg)
3262 (let ((removed 0) len-all len-text)
3263 (while (re-search-forward regexp (- end removed) t)
3264 (setq len-all (length (match-string-no-properties all)))
3265 (setq len-text (length (match-string-no-properties text)))
3266 (setq removed (+ removed (- len-all len-text)))
3267 (replace-match (match-string text) t t nil all))
3268 (cons beg (- end removed)))))
3270 (defun markdown-insert-hr (arg)
3271 "Insert or replace a horizonal rule.
3272 By default, use the first element of `markdown-hr-strings'. When
3273 ARG is non-nil, as when given a prefix, select a different
3274 element as follows. When prefixed with \\[universal-argument],
3275 use the last element of `markdown-hr-strings' instead. When
3276 prefixed with an integer from 1 to the length of
3277 `markdown-hr-strings', use the element in that position instead."
3278 (interactive "*P")
3279 (when (thing-at-point-looking-at markdown-regex-hr)
3280 (delete-region (match-beginning 0) (match-end 0)))
3281 (markdown-ensure-blank-line-before)
3282 (cond ((equal arg '(4))
3283 (insert (car (reverse markdown-hr-strings))))
3284 ((and (integerp arg) (> arg 0)
3285 (<= arg (length markdown-hr-strings)))
3286 (insert (nth (1- arg) markdown-hr-strings)))
3288 (insert (car markdown-hr-strings))))
3289 (markdown-ensure-blank-line-after))
3291 (defun markdown-insert-bold ()
3292 "Insert markup to make a region or word bold.
3293 If there is an active region, make the region bold. If the point
3294 is at a non-bold word, make the word bold. If the point is at a
3295 bold word or phrase, remove the bold markup. Otherwise, simply
3296 insert bold delimiters and place the cursor in between them."
3297 (interactive)
3298 (let ((delim (if markdown-bold-underscore "__" "**")))
3299 (if (markdown-use-region-p)
3300 ;; Active region
3301 (let ((bounds (markdown-unwrap-things-in-region
3302 (region-beginning) (region-end)
3303 markdown-regex-bold 2 4)))
3304 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3305 ;; Bold markup removal, bold word at point, or empty markup insertion
3306 (if (thing-at-point-looking-at markdown-regex-bold)
3307 (markdown-unwrap-thing-at-point nil 2 4)
3308 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3310 (defun markdown-insert-italic ()
3311 "Insert markup to make a region or word italic.
3312 If there is an active region, make the region italic. If the point
3313 is at a non-italic word, make the word italic. If the point is at an
3314 italic word or phrase, remove the italic markup. Otherwise, simply
3315 insert italic delimiters and place the cursor in between them."
3316 (interactive)
3317 (let ((delim (if markdown-italic-underscore "_" "*")))
3318 (if (markdown-use-region-p)
3319 ;; Active region
3320 (let ((bounds (markdown-unwrap-things-in-region
3321 (region-beginning) (region-end)
3322 markdown-regex-italic 1 3)))
3323 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3324 ;; Italic markup removal, italic word at point, or empty markup insertion
3325 (if (thing-at-point-looking-at markdown-regex-italic)
3326 (markdown-unwrap-thing-at-point nil 1 3)
3327 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3329 (defun markdown-insert-strike-through ()
3330 "Insert markup to make a region or word strikethrough.
3331 If there is an active region, make the region strikethrough. If the point
3332 is at a non-bold word, make the word strikethrough. If the point is at a
3333 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
3334 simply insert bold delimiters and place the cursor in between them."
3335 (interactive)
3336 (let ((delim "~~"))
3337 (if (markdown-use-region-p)
3338 ;; Active region
3339 (let ((bounds (markdown-unwrap-things-in-region
3340 (region-beginning) (region-end)
3341 markdown-regex-strike-through 2 4)))
3342 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3343 ;; Strikethrough markup removal, strikethrough word at point, or empty markup insertion
3344 (if (thing-at-point-looking-at markdown-regex-strike-through)
3345 (markdown-unwrap-thing-at-point nil 2 4)
3346 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3348 (defun markdown-insert-code ()
3349 "Insert markup to make a region or word an inline code fragment.
3350 If there is an active region, make the region an inline code
3351 fragment. If the point is at a word, make the word an inline
3352 code fragment. Otherwise, simply insert code delimiters and
3353 place the cursor in between them."
3354 (interactive)
3355 (if (markdown-use-region-p)
3356 ;; Active region
3357 (let ((bounds (markdown-unwrap-things-in-region
3358 (region-beginning) (region-end)
3359 markdown-regex-code 1 3)))
3360 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
3361 ;; Code markup removal, code markup for word, or empty markup insertion
3362 (if (markdown-inline-code-at-point)
3363 (markdown-unwrap-thing-at-point nil 0 2)
3364 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
3366 (defun markdown-insert-kbd ()
3367 "Insert markup to wrap region or word in <kbd> tags.
3368 If there is an active region, use the region. If the point is at
3369 a word, use the word. Otherwise, simply insert <kbd> tags and
3370 place the cursor in between them."
3371 (interactive)
3372 (if (markdown-use-region-p)
3373 ;; Active region
3374 (let ((bounds (markdown-unwrap-things-in-region
3375 (region-beginning) (region-end)
3376 markdown-regex-kbd 0 2)))
3377 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil (car bounds) (cdr bounds)))
3378 ;; Markup removal, markup for word, or empty markup insertion
3379 (if (thing-at-point-looking-at markdown-regex-kbd)
3380 (markdown-unwrap-thing-at-point nil 0 2)
3381 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil))))
3383 (defun markdown-insert-inline-link (text url &optional title)
3384 "Insert an inline link with TEXT pointing to URL.
3385 Optionally, the user can provide a TITLE."
3386 (let ((cur (point)))
3387 (setq title (and title (concat " \"" title "\"")))
3388 (insert (concat "[" text "](" url title ")"))
3389 (cond ((not text) (goto-char (+ 1 cur)))
3390 ((not url) (goto-char (+ 3 (length text) cur))))))
3392 (defun markdown-insert-inline-link-dwim ()
3393 "Insert an inline link of the form [link](url) at point.
3394 If there is an active region, the text in the region will be used
3395 as the URL, if it appears to be a URL, or else as the link text.
3396 If the point is at a URL, use it to create a new link. If the
3397 point is at a reference link, convert it to an inline link. If
3398 the point is at a word, use the word as the link text. In these
3399 cases, the point will be left at the position for inserting a
3400 URL. If there is no active region and the point is not at word,
3401 simply insert link markup and place the point in the position to
3402 enter link text."
3403 (interactive)
3404 (cond
3405 ;; If there is an active region, remove existing links in the
3406 ;; region and use resulting region as link text for a new link.
3407 ((markdown-use-region-p)
3408 (let* ((bounds (markdown-unwrap-things-in-region
3409 (region-beginning) (region-end)
3410 markdown-regex-link-inline 0 3))
3411 (text (buffer-substring (car bounds) (cdr bounds))))
3412 (delete-region (car bounds) (cdr bounds))
3413 (markdown-insert-inline-link text nil)))
3414 ;; If there is an inline link at the point, remove it and add the
3415 ;; link text to the kill ring.
3416 ((thing-at-point-looking-at markdown-regex-link-inline)
3417 (kill-new (match-string 3))
3418 (delete-region (match-beginning 0) (match-end 0)))
3419 ;; If there is an angle URL at the point, use it for a new link.
3420 ((thing-at-point-looking-at markdown-regex-angle-uri)
3421 (let ((url (match-string 2)))
3422 (delete-region (match-beginning 0) (match-end 0))
3423 (markdown-insert-inline-link nil url)))
3424 ;; If there is a plain URL at the point, use it for a new link.
3425 ((thing-at-point-looking-at markdown-regex-uri)
3426 (let ((url (match-string 0)))
3427 (delete-region (match-beginning 0) (match-end 0))
3428 (markdown-insert-inline-link nil url)))
3429 ;; If there is a reference link at point, convert to inline link.
3430 ((thing-at-point-looking-at markdown-regex-link-reference)
3431 (let ((beg (match-beginning 0))
3432 (end (match-end 0))
3433 (text (match-string 3))
3434 (url (markdown-link-link)))
3435 (delete-region beg end)
3436 (markdown-insert-inline-link text url)))
3437 ;; Otherwise, insert a link
3438 (t (let ((bounds (markdown-wrap-or-insert "[" "]()")))
3439 (when bounds
3440 (goto-char (- (cdr bounds) 1)))))))
3442 (defun markdown-insert-reference-link (text label &optional url title)
3443 "Insert a reference link and, optionally, a reference definition.
3444 The link TEXT will be inserted followed by the optional LABEL.
3445 If a URL is given, also insert a definition for the reference
3446 LABEL according to `markdown-reference-location'. If a TITLE is
3447 given, it will be added to the end of the reference definition
3448 and will be used to populate the title attribute when converted
3449 to XHTML. If URL is nil, insert only the link portion (for
3450 example, when a reference label is already defined)."
3451 (insert (concat "[" text "][" label "]"))
3452 (when url
3453 (markdown-insert-reference-definition
3454 (if (string-equal label "") text label)
3455 url title)))
3457 (defun markdown-insert-reference-definition (label &optional url title)
3458 "Add definition for reference LABEL with URL and TITLE.
3459 LABEL is a Markdown reference label without square brackets.
3460 URL and TITLE are optional. When given, the TITLE will
3461 be used to populate the title attribute when converted to XHTML."
3462 ;; END specifies where to leave the point upon return
3463 (let ((end (point)))
3464 (cl-case markdown-reference-location
3465 (end (goto-char (point-max)))
3466 (immediately (markdown-end-of-text-block))
3467 (header (markdown-end-of-defun)))
3468 (unless (markdown-cur-line-blank-p) (insert "\n"))
3469 (insert "\n[" label "]: ")
3470 (if url
3471 (insert url)
3472 ;; When no URL is given, leave cursor at END following the colon
3473 (setq end (point)))
3474 (when (> (length title) 0)
3475 (insert " \"" title "\""))
3476 (unless (looking-at-p "\n")
3477 (insert "\n"))
3478 (goto-char end)
3479 (when url
3480 (message
3481 (substitute-command-keys
3482 "Defined reference [%s], press \\[markdown-jump] to jump there")
3483 label))))
3485 (defun markdown-insert-reference-link-dwim ()
3486 "Insert a reference link of the form [text][label] at point.
3487 If there is an active region, the text in the region will be used
3488 as the link text. If the point is at an inline link, it will be
3489 converted to a reference link. If the point is at a word, it will
3490 be used as the link text. Otherwise, the link text will be read from
3491 the minibuffer. The link label will be read from the minibuffer in
3492 both cases, with completion from the set of currently defined
3493 references. To create an implicit reference link, press RET to
3494 accept the default, an empty label. If the entered referenced
3495 label is not defined, additionally prompt for the URL
3496 and (optional) title. The reference definition is placed at the
3497 location determined by `markdown-reference-location'."
3498 (interactive)
3499 (let* ((defined-labels (markdown-get-defined-references))
3500 (switch (thing-at-point-looking-at markdown-regex-link-inline))
3501 (bounds (cond ((markdown-use-region-p)
3502 (cons (region-beginning) (region-end)))
3503 (switch
3504 (cons (match-beginning 0) (match-end 0)))
3506 (markdown-bounds-of-thing-at-point 'word))))
3507 (text (cond (switch (match-string 3))
3508 (bounds (buffer-substring (car bounds) (cdr bounds)))
3509 (t (read-string "Link Text: "))))
3510 (label (completing-read
3511 "Link Label (default: none): " defined-labels
3512 nil nil nil 'markdown-reference-label-history nil))
3513 (ref (save-match-data
3514 (markdown-reference-definition
3515 (if (> (length label) 0) label text))))
3516 (url (cond (ref nil)
3517 (switch (match-string 6))
3518 (t (read-string "Link URL: "))))
3519 (title (cond
3520 ((= (length url) 0) nil)
3521 (switch (if (> (length (match-string 7)) 2)
3522 (substring (match-string 7) 1 -1)
3523 nil))
3524 (t (read-string "Link Title (optional): ")))))
3525 (when bounds (delete-region (car bounds) (cdr bounds)))
3526 (markdown-insert-reference-link text label url title)))
3528 (defun markdown-insert-uri ()
3529 "Insert markup for an inline URI.
3530 If there is an active region, use it as the URI. If the point is
3531 at a URI, wrap it with angle brackets. If the point is at an
3532 inline URI, remove the angle brackets. Otherwise, simply insert
3533 angle brackets place the point between them."
3534 (interactive)
3535 (if (markdown-use-region-p)
3536 ;; Active region
3537 (let ((bounds (markdown-unwrap-things-in-region
3538 (region-beginning) (region-end)
3539 markdown-regex-angle-uri 0 2)))
3540 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
3541 ;; Markup removal, URI at point, or empty markup insertion
3542 (if (thing-at-point-looking-at markdown-regex-angle-uri)
3543 (markdown-unwrap-thing-at-point nil 0 2)
3544 (markdown-wrap-or-insert "<" ">" 'url nil nil))))
3546 (defun markdown-insert-wiki-link ()
3547 "Insert a wiki link of the form [[WikiLink]].
3548 If there is an active region, use the region as the link text.
3549 If the point is at a word, use the word as the link text. If
3550 there is no active region and the point is not at word, simply
3551 insert link markup."
3552 (interactive)
3553 (if (markdown-use-region-p)
3554 ;; Active region
3555 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
3556 ;; Markup removal, wiki link at at point, or empty markup insertion
3557 (if (thing-at-point-looking-at markdown-regex-wiki-link)
3558 (if (or markdown-wiki-link-alias-first
3559 (null (match-string 5)))
3560 (markdown-unwrap-thing-at-point nil 1 3)
3561 (markdown-unwrap-thing-at-point nil 1 5))
3562 (markdown-wrap-or-insert "[[" "]]"))))
3564 (defun markdown-insert-image (&optional arg)
3565 "Insert image markup using region or word as alt text if possible.
3566 If there is an active region, use the region as the alt text. If the
3567 point is at a word, use the word as the alt text. In these cases, the
3568 point will be left at the position for inserting a URL. If there is no
3569 active region and the point is not at word, simply insert image markup and
3570 place the point in the position to enter alt text. If ARG is nil, insert
3571 inline image markup. Otherwise, insert reference image markup."
3572 (interactive "*P")
3573 (let ((bounds (if arg
3574 (markdown-wrap-or-insert "![" "][]")
3575 (markdown-wrap-or-insert "![" "]()"))))
3576 (when bounds
3577 (goto-char (- (cdr bounds) 1)))))
3579 (defun markdown-insert-reference-image ()
3580 "Insert reference-style image markup using region or word as alt text.
3581 Calls `markdown-insert-image' with prefix argument."
3582 (interactive)
3583 (markdown-insert-image t))
3585 (defun markdown-remove-header ()
3586 "Remove header markup if point is at a header.
3587 Return bounds of remaining header text if a header was removed
3588 and nil otherwise."
3589 (interactive "*")
3590 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
3591 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
3593 (defun markdown-insert-header (&optional level text setext)
3594 "Insert or replace header markup.
3595 The level of the header is specified by LEVEL and header text is
3596 given by TEXT. LEVEL must be an integer from 1 and 6, and the
3597 default value is 1.
3598 When TEXT is nil, the header text is obtained as follows.
3599 If there is an active region, it is used as the header text.
3600 Otherwise, the current line will be used as the header text.
3601 If there is not an active region and the point is at a header,
3602 remove the header markup and replace with level N header.
3603 Otherwise, insert empty header markup and place the cursor in
3604 between.
3605 The style of the header will be atx (hash marks) unless
3606 SETEXT is non-nil, in which case a setext-style (underlined)
3607 header will be inserted."
3608 (interactive "p\nsHeader text: ")
3609 (setq level (min (max (or level 1) 1) (if setext 2 6)))
3610 ;; Determine header text if not given
3611 (when (null text)
3612 (if (markdown-use-region-p)
3613 ;; Active region
3614 (setq text (delete-and-extract-region (region-beginning) (region-end)))
3615 ;; No active region
3616 (markdown-remove-header)
3617 (setq text (delete-and-extract-region
3618 (line-beginning-position) (line-end-position)))
3619 (when (and setext (string-match-p "^[ \t]*$" text))
3620 (setq text (read-string "Header text: "))))
3621 (setq text (markdown-compress-whitespace-string text)))
3622 ;; Insertion with given text
3623 (markdown-ensure-blank-line-before)
3624 (let (hdr)
3625 (cond (setext
3626 (setq hdr (make-string (string-width text) (if (= level 2) ?- ?=)))
3627 (insert text "\n" hdr))
3629 (setq hdr (make-string level ?#))
3630 (insert hdr " " text)
3631 (when (null markdown-asymmetric-header) (insert " " hdr)))))
3632 (markdown-ensure-blank-line-after)
3633 ;; Leave point at end of text
3634 (cond (setext
3635 (backward-char (1+ (string-width text))))
3636 ((null markdown-asymmetric-header)
3637 (backward-char (1+ level)))))
3639 (defun markdown-insert-header-dwim (&optional arg setext)
3640 "Insert or replace header markup.
3641 The level and type of the header are determined automatically by
3642 the type and level of the previous header, unless a prefix
3643 argument is given via ARG.
3644 With a numeric prefix valued 1 to 6, insert a header of the given
3645 level, with the type being determined automatically (note that
3646 only level 1 or 2 setext headers are possible).
3648 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
3649 promote the heading by one level.
3650 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
3651 demote the heading by one level.
3652 When SETEXT is non-nil, prefer setext-style headers when
3653 possible (levels one and two).
3655 When there is an active region, use it for the header text. When
3656 the point is at an existing header, change the type and level
3657 according to the rules above.
3658 Otherwise, if the line is not empty, create a header using the
3659 text on the current line as the header text.
3660 Finally, if the point is on a blank line, insert empty header
3661 markup (atx) or prompt for text (setext).
3662 See `markdown-insert-header' for more details about how the
3663 header text is determined."
3664 (interactive "*P")
3665 (let (level)
3666 (save-excursion
3667 (when (or (thing-at-point-looking-at markdown-regex-header)
3668 (re-search-backward markdown-regex-header nil t))
3669 ;; level of current or previous header
3670 (setq level (markdown-outline-level))
3671 ;; match group 1 indicates a setext header
3672 (setq setext (match-end 1))))
3673 ;; check prefix argument
3674 (cond
3675 ((and (equal arg '(4)) level (> level 1)) ;; C-u
3676 (cl-decf level))
3677 ((and (equal arg '(16)) level (< level 6)) ;; C-u C-u
3678 (cl-incf level))
3679 (arg ;; numeric prefix
3680 (setq level (prefix-numeric-value arg))))
3681 ;; setext headers must be level one or two
3682 (and level (setq setext (and setext (<= level 2))))
3683 ;; insert the heading
3684 (markdown-insert-header level nil setext)))
3686 (defun markdown-insert-header-setext-dwim (&optional arg)
3687 "Insert or replace header markup, with preference for setext.
3688 See `markdown-insert-header-dwim' for details, including how ARG is handled."
3689 (interactive "*P")
3690 (markdown-insert-header-dwim arg t))
3692 (defun markdown-insert-header-atx-1 ()
3693 "Insert a first level atx-style (hash mark) header.
3694 See `markdown-insert-header'."
3695 (interactive "*")
3696 (markdown-insert-header 1 nil nil))
3698 (defun markdown-insert-header-atx-2 ()
3699 "Insert a level two atx-style (hash mark) header.
3700 See `markdown-insert-header'."
3701 (interactive "*")
3702 (markdown-insert-header 2 nil nil))
3704 (defun markdown-insert-header-atx-3 ()
3705 "Insert a level three atx-style (hash mark) header.
3706 See `markdown-insert-header'."
3707 (interactive "*")
3708 (markdown-insert-header 3 nil nil))
3710 (defun markdown-insert-header-atx-4 ()
3711 "Insert a level four atx-style (hash mark) header.
3712 See `markdown-insert-header'."
3713 (interactive "*")
3714 (markdown-insert-header 4 nil nil))
3716 (defun markdown-insert-header-atx-5 ()
3717 "Insert a level five atx-style (hash mark) header.
3718 See `markdown-insert-header'."
3719 (interactive "*")
3720 (markdown-insert-header 5 nil nil))
3722 (defun markdown-insert-header-atx-6 ()
3723 "Insert a sixth level atx-style (hash mark) header.
3724 See `markdown-insert-header'."
3725 (interactive "*")
3726 (markdown-insert-header 6 nil nil))
3728 (defun markdown-insert-header-setext-1 ()
3729 "Insert a setext-style (underlined) first-level header.
3730 See `markdown-insert-header'."
3731 (interactive "*")
3732 (markdown-insert-header 1 nil t))
3734 (defun markdown-insert-header-setext-2 ()
3735 "Insert a setext-style (underlined) second-level header.
3736 See `markdown-insert-header'."
3737 (interactive "*")
3738 (markdown-insert-header 2 nil t))
3740 (defun markdown-blockquote-indentation (loc)
3741 "Return string containing necessary indentation for a blockquote at LOC.
3742 Also see `markdown-pre-indentation'."
3743 (save-excursion
3744 (goto-char loc)
3745 (let* ((list-level (length (markdown-calculate-list-levels)))
3746 (indent ""))
3747 (dotimes (_ list-level indent)
3748 (setq indent (concat indent " "))))))
3750 (defun markdown-insert-blockquote ()
3751 "Start a blockquote section (or blockquote the region).
3752 If Transient Mark mode is on and a region is active, it is used as
3753 the blockquote text."
3754 (interactive)
3755 (if (markdown-use-region-p)
3756 (markdown-blockquote-region (region-beginning) (region-end))
3757 (markdown-ensure-blank-line-before)
3758 (insert (markdown-blockquote-indentation (point)) "> ")
3759 (markdown-ensure-blank-line-after)))
3761 (defun markdown-block-region (beg end prefix)
3762 "Format the region using a block prefix.
3763 Arguments BEG and END specify the beginning and end of the
3764 region. The characters PREFIX will appear at the beginning
3765 of each line."
3766 (save-excursion
3767 (let* ((end-marker (make-marker))
3768 (beg-marker (make-marker)))
3769 ;; Ensure blank line after and remove extra whitespace
3770 (goto-char end)
3771 (skip-syntax-backward "-")
3772 (set-marker end-marker (point))
3773 (delete-horizontal-space)
3774 (markdown-ensure-blank-line-after)
3775 ;; Ensure blank line before and remove extra whitespace
3776 (goto-char beg)
3777 (skip-syntax-forward "-")
3778 (delete-horizontal-space)
3779 (markdown-ensure-blank-line-before)
3780 (set-marker beg-marker (point))
3781 ;; Insert PREFIX before each line
3782 (goto-char beg-marker)
3783 (while (and (< (line-beginning-position) end-marker)
3784 (not (eobp)))
3785 (insert prefix)
3786 (forward-line)))))
3788 (defun markdown-blockquote-region (beg end)
3789 "Blockquote the region.
3790 Arguments BEG and END specify the beginning and end of the region."
3791 (interactive "*r")
3792 (markdown-block-region
3793 beg end (concat (markdown-blockquote-indentation
3794 (max (point-min) (1- beg))) "> ")))
3796 (defun markdown-pre-indentation (loc)
3797 "Return string containing necessary whitespace for a pre block at LOC.
3798 Also see `markdown-blockquote-indentation'."
3799 (save-excursion
3800 (goto-char loc)
3801 (let* ((list-level (length (markdown-calculate-list-levels)))
3802 indent)
3803 (dotimes (_ (1+ list-level) indent)
3804 (setq indent (concat indent " "))))))
3806 (defun markdown-insert-pre ()
3807 "Start a preformatted section (or apply to the region).
3808 If Transient Mark mode is on and a region is active, it is marked
3809 as preformatted text."
3810 (interactive)
3811 (if (markdown-use-region-p)
3812 (markdown-pre-region (region-beginning) (region-end))
3813 (markdown-ensure-blank-line-before)
3814 (insert (markdown-pre-indentation (point)))
3815 (markdown-ensure-blank-line-after)))
3817 (defun markdown-pre-region (beg end)
3818 "Format the region as preformatted text.
3819 Arguments BEG and END specify the beginning and end of the region."
3820 (interactive "*r")
3821 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
3822 (markdown-block-region beg end indent)))
3824 (defun markdown-electric-backquote (arg)
3825 "Insert a backquote.
3826 The numeric prefix argument ARG says how many times to repeat the insertion.
3827 Call `markdown-insert-gfm-code-block' interactively
3828 if three backquotes inserted at the beginning of line."
3829 (interactive "*P")
3830 (self-insert-command (prefix-numeric-value arg))
3831 (when (and markdown-gfm-use-electric-backquote (looking-back "^```" nil))
3832 (replace-match "")
3833 (call-interactively #'markdown-insert-gfm-code-block)))
3835 (defconst markdown-gfm-recognized-languages
3836 ;; to reproduce/update, evaluate the let-form in
3837 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
3838 ;; but with appropriate use of a keyboard macro, indenting and filling it
3839 ;; properly is pretty fast.
3840 '("ABAP" "AGS-Script" "AMPL" "ANTLR" "API-Blueprint" "APL" "ASP" "ATS"
3841 "ActionScript" "Ada" "Agda" "Alloy" "Ant-Build-System" "ApacheConf" "Apex"
3842 "AppleScript" "Arc" "Arduino" "AsciiDoc" "AspectJ" "Assembly" "Augeas"
3843 "AutoHotkey" "AutoIt" "Awk" "Batchfile" "Befunge" "Bison" "BitBake"
3844 "BlitzBasic" "BlitzMax" "Bluespec" "Boo" "Brainfuck" "Brightscript" "Bro" "C#"
3845 "C++" "C-ObjDump" "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "CSS" "Cap'n-Proto"
3846 "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK" "Cirru" "Clarion" "Clean"
3847 "Click" "Clojure" "CoffeeScript" "ColdFusion" "ColdFusion-CFC" "Common-Lisp"
3848 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal" "Cucumber"
3849 "Cuda" "Cycript" "Cython" "D-ObjDump" "DIGITAL-Command-Language" "DM"
3850 "DNS-Zone" "DTrace" "Darcs-Patch" "Dart" "Diff" "Dockerfile" "Dogescript"
3851 "Dylan" "ECL" "ECLiPSe" "Eagle" "Ecere-Projects" "Eiffel" "Elixir" "Elm"
3852 "Emacs-Lisp" "EmberScript" "Erlang" "F#" "FLUX" "FORTRAN" "Factor" "Fancy"
3853 "Fantom" "Filterscript" "Formatted" "Forth" "FreeMarker" "Frege" "G-code"
3854 "GAMS" "GAP" "GAS" "GDScript" "GLSL" "Game-Maker-Language" "Genshi"
3855 "Gentoo-Ebuild" "Gentoo-Eclass" "Gettext-Catalog" "Glyph" "Gnuplot" "Go"
3856 "Golo" "Gosu" "Grace" "Gradle" "Grammatical-Framework"
3857 "Graph-Modeling-Language" "Graphviz-(DOT)" "Groff" "Groovy"
3858 "Groovy-Server-Pages" "HCL" "HTML" "HTML+Django" "HTML+EEX" "HTML+ERB"
3859 "HTML+PHP" "HTTP" "Hack" "Haml" "Handlebars" "Harbour" "Haskell" "Haxe" "Hy"
3860 "HyPhy" "IDL" "IGOR-Pro" "INI" "IRC-log" "Idris" "Inform-7" "Inno-Setup" "Io"
3861 "Ioke" "Isabelle" "Isabelle-ROOT" "JFlex" "JSON" "JSON5" "JSONLD" "JSONiq"
3862 "JSX" "Jade" "Jasmin" "Java" "Java-Server-Pages" "JavaScript" "Julia"
3863 "Jupyter-Notebook" "KRL" "KiCad" "Kit" "Kotlin" "LFE" "LLVM" "LOLCODE" "LSL"
3864 "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex" "LilyPond" "Limbo"
3865 "Linker-Script" "Linux-Kernel-Module" "Liquid" "Literate-Agda"
3866 "Literate-CoffeeScript" "Literate-Haskell" "LiveScript" "Logos" "Logtalk"
3867 "LookML" "LoomScript" "Lua" "MAXScript" "MTML" "MUF" "Makefile" "Mako"
3868 "Markdown" "Mask" "Mathematica" "Matlab" "Maven-POM" "Max" "MediaWiki"
3869 "Mercury" "Metal" "MiniD" "Mirah" "Modelica" "Modula-2"
3870 "Module-Management-System" "Monkey" "Moocode" "MoonScript" "Myghty" "NCL" "NL"
3871 "NSIS" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo" "NewLisp" "Nginx" "Nimrod"
3872 "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml" "ObjDump" "Objective-C"
3873 "Objective-C++" "Objective-J" "Omgrofl" "Opa" "Opal" "OpenCL" "OpenEdge-ABL"
3874 "OpenSCAD" "Org" "Ox" "Oxygene" "Oz" "PAWN" "PHP" "PLSQL" "PLpgSQL" "Pan"
3875 "Papyrus" "Parrot" "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal"
3876 "Perl" "Perl6" "Pickle" "PicoLisp" "PigLatin" "Pike" "Pod" "PogoScript" "Pony"
3877 "PostScript" "PowerShell" "Processing" "Prolog" "Propeller-Spin"
3878 "Protocol-Buffer" "Public-Key" "Puppet" "Pure-Data" "PureBasic" "PureScript"
3879 "Python" "Python-traceback" "QML" "QMake" "RAML" "RDoc" "REALbasic" "RHTML"
3880 "RMarkdown" "Racket" "Ragel-in-Ruby-Host" "Raw-token-data" "Rebol" "Red"
3881 "Redcode" "Ren'Py" "RenderScript" "RobotFramework" "Rouge" "Ruby" "Rust" "SAS"
3882 "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL" "STON" "SVG" "Sage" "SaltStack"
3883 "Sass" "Scala" "Scaml" "Scheme" "Scilab" "Self" "Shell" "ShellSession" "Shen"
3884 "Slash" "Slim" "Smali" "Smalltalk" "Smarty" "SourcePawn" "Squirrel" "Stan"
3885 "Standard-ML" "Stata" "Stylus" "SuperCollider" "Swift" "SystemVerilog" "TOML"
3886 "TXL" "Tcl" "Tcsh" "TeX" "Tea" "Text" "Textile" "Thrift" "Turing" "Turtle"
3887 "Twig" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset" "UnrealScript"
3888 "UrWeb" "VCL" "VHDL" "Vala" "Verilog" "VimL" "Visual-Basic" "Volt" "Vue"
3889 "Web-Ontology-Language" "WebIDL" "X10" "XC" "XML" "XPages" "XProc" "XQuery"
3890 "XS" "XSLT" "Xojo" "Xtend" "YAML" "Yacc" "Zephir" "Zimpl" "desktop" "eC" "edn"
3891 "fish" "mupad" "nesC" "ooc" "reStructuredText" "wisp" "xBase")
3892 "Language specifiers recognized by GitHub's syntax highlighting features.")
3894 (defvar markdown-gfm-used-languages nil
3895 "Language names used in GFM code blocks.")
3896 (make-variable-buffer-local 'markdown-gfm-used-languages)
3898 (defun markdown-trim-whitespace (str)
3899 (markdown-replace-regexp-in-string
3900 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str))
3902 (defun markdown-clean-language-string (str)
3903 (markdown-replace-regexp-in-string
3904 "{\\.?\\|}" "" (markdown-trim-whitespace str)))
3906 (defun markdown-validate-language-string (widget)
3907 (let ((str (widget-value widget)))
3908 (unless (string= str (markdown-clean-language-string str))
3909 (widget-put widget :error (format "Invalid language spec: '%s'" str))
3910 widget)))
3912 (defun markdown-gfm-get-corpus ()
3913 "Create corpus of recognized GFM code block languages for the given buffer."
3914 (let ((given-corpus (append markdown-gfm-additional-languages
3915 markdown-gfm-recognized-languages)))
3916 (append
3917 markdown-gfm-used-languages
3918 (if markdown-gfm-downcase-languages (cl-mapcar #'downcase given-corpus)
3919 given-corpus))))
3921 (defun markdown-gfm-add-used-language (lang)
3922 "Clean LANG and add to list of used languages."
3923 (setq markdown-gfm-used-languages
3924 (cons lang (remove lang markdown-gfm-used-languages))))
3926 (defun markdown-insert-gfm-code-block (&optional lang)
3927 "Insert GFM code block for language LANG.
3928 If LANG is nil, the language will be queried from user. If a
3929 region is active, wrap this region with the markup instead. If
3930 the region boundaries are not on empty lines, these are added
3931 automatically in order to have the correct markup."
3932 (interactive
3933 (list (let ((completion-ignore-case nil))
3934 (condition-case nil
3935 (markdown-clean-language-string
3936 (completing-read
3937 "Programming language: "
3938 (markdown-gfm-get-corpus)
3939 nil 'confirm (car markdown-gfm-used-languages)
3940 'markdown-gfm-language-history))
3941 (quit "")))))
3942 (unless (string= lang "") (markdown-gfm-add-used-language lang))
3943 (when (> (length lang) 0) (setq lang (concat " " lang)))
3944 (if (markdown-use-region-p)
3945 (let ((b (region-beginning)) (e (region-end)))
3946 (goto-char e)
3947 ;; if we're on a blank line, don't newline, otherwise the ```
3948 ;; should go on its own line
3949 (unless (looking-back "\n" nil)
3950 (newline))
3951 (insert "```")
3952 (markdown-ensure-blank-line-after)
3953 (goto-char b)
3954 ;; if we're on a blank line, insert the quotes here, otherwise
3955 ;; add a new line first
3956 (unless (looking-at-p "\n")
3957 (newline)
3958 (forward-line -1))
3959 (markdown-ensure-blank-line-before)
3960 (insert "```" lang))
3961 (markdown-ensure-blank-line-before)
3962 (insert "```" lang "\n\n```")
3963 (markdown-ensure-blank-line-after)
3964 (forward-line -1)))
3966 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer)
3967 (with-current-buffer (or buffer (current-buffer))
3968 (save-excursion
3969 (goto-char (point-min))
3970 (cl-loop
3971 with prop = 'markdown-gfm-block-begin
3972 for pos-prop = (markdown-find-next-prop prop)
3973 while pos-prop
3974 for lang = (progn
3975 (goto-char (car pos-prop))
3976 (save-match-data
3977 (set-match-data (get-text-property (point) prop))
3978 ;; Note: Hard-coded group number assumes tilde
3979 ;; and GFM fenced code regexp groups agree.
3980 (when (and (match-beginning 3) (match-end 3))
3981 (buffer-substring-no-properties
3982 (match-beginning 3) (match-end 3)))))
3983 do (progn (when lang (markdown-gfm-add-used-language lang))
3984 (goto-char (next-single-property-change (point) prop)))))))
3987 ;;; Footnotes ==================================================================
3989 (defun markdown-footnote-counter-inc ()
3990 "Increment `markdown-footnote-counter' and return the new value."
3991 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
3992 (save-excursion
3993 (goto-char (point-min))
3994 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
3995 (point-max) t)
3996 (let ((fn (string-to-number (match-string 1))))
3997 (when (> fn markdown-footnote-counter)
3998 (setq markdown-footnote-counter fn))))))
3999 (cl-incf markdown-footnote-counter))
4001 (defun markdown-insert-footnote ()
4002 "Insert footnote with a new number and move point to footnote definition."
4003 (interactive)
4004 (let ((fn (markdown-footnote-counter-inc)))
4005 (insert (format "[^%d]" fn))
4006 (markdown-footnote-text-find-new-location)
4007 (markdown-ensure-blank-line-before)
4008 (unless (markdown-cur-line-blank-p)
4009 (insert "\n"))
4010 (insert (format "[^%d]: " fn))
4011 (markdown-ensure-blank-line-after)))
4013 (defun markdown-footnote-text-find-new-location ()
4014 "Position the cursor at the proper location for a new footnote text."
4015 (cond
4016 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
4017 ((eq markdown-footnote-location 'immediately) (markdown-end-of-text-block))
4018 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
4020 (defun markdown-footnote-kill ()
4021 "Kill the footnote at point.
4022 The footnote text is killed (and added to the kill ring), the
4023 footnote marker is deleted. Point has to be either at the
4024 footnote marker or in the footnote text."
4025 (interactive)
4026 (let ((marker-pos nil)
4027 (skip-deleting-marker nil)
4028 (starting-footnote-text-positions
4029 (markdown-footnote-text-positions)))
4030 (when starting-footnote-text-positions
4031 ;; We're starting in footnote text, so mark our return position and jump
4032 ;; to the marker if possible.
4033 (let ((marker-pos (markdown-footnote-find-marker
4034 (cl-first starting-footnote-text-positions))))
4035 (if marker-pos
4036 (goto-char (1- marker-pos))
4037 ;; If there isn't a marker, we still want to kill the text.
4038 (setq skip-deleting-marker t))))
4039 ;; Either we didn't start in the text, or we started in the text and jumped
4040 ;; to the marker. We want to assume we're at the marker now and error if
4041 ;; we're not.
4042 (unless skip-deleting-marker
4043 (let ((marker (markdown-footnote-delete-marker)))
4044 (unless marker
4045 (error "Not at a footnote"))
4046 ;; Even if we knew the text position before, it changed when we deleted
4047 ;; the label.
4048 (setq marker-pos (cl-second marker))
4049 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker))))
4050 (unless new-text-pos
4051 (error "No text for footnote `%s'" (cl-first marker)))
4052 (goto-char new-text-pos))))
4053 (let ((pos (markdown-footnote-kill-text)))
4054 (goto-char (if starting-footnote-text-positions
4056 marker-pos)))))
4058 (defun markdown-footnote-delete-marker ()
4059 "Delete a footnote marker at point.
4060 Returns a list (ID START) containing the footnote ID and the
4061 start position of the marker before deletion. If no footnote
4062 marker was deleted, this function returns NIL."
4063 (let ((marker (markdown-footnote-marker-positions)))
4064 (when marker
4065 (delete-region (cl-second marker) (cl-third marker))
4066 (butlast marker))))
4068 (defun markdown-footnote-kill-text ()
4069 "Kill footnote text at point.
4070 Returns the start position of the footnote text before deletion,
4071 or NIL if point was not inside a footnote text.
4073 The killed text is placed in the kill ring (without the footnote
4074 number)."
4075 (let ((fn (markdown-footnote-text-positions)))
4076 (when fn
4077 (let ((text (delete-and-extract-region (cl-second fn) (cl-third fn))))
4078 (string-match (concat "\\[\\" (cl-first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
4079 (kill-new (match-string 1 text))
4080 (when (and (markdown-cur-line-blank-p)
4081 (markdown-prev-line-blank-p)
4082 (not (bobp)))
4083 (delete-region (1- (point)) (point)))
4084 (cl-second fn)))))
4086 (defun markdown-footnote-goto-text ()
4087 "Jump to the text of the footnote at point."
4088 (interactive)
4089 (let ((fn (car (markdown-footnote-marker-positions))))
4090 (unless fn
4091 (error "Not at a footnote marker"))
4092 (let ((new-pos (markdown-footnote-find-text fn)))
4093 (unless new-pos
4094 (error "No definition found for footnote `%s'" fn))
4095 (goto-char new-pos))))
4097 (defun markdown-footnote-return ()
4098 "Return from a footnote to its footnote number in the main text."
4099 (interactive)
4100 (let ((fn (save-excursion
4101 (car (markdown-footnote-text-positions)))))
4102 (unless fn
4103 (error "Not in a footnote"))
4104 (let ((new-pos (markdown-footnote-find-marker fn)))
4105 (unless new-pos
4106 (error "Footnote marker `%s' not found" fn))
4107 (goto-char new-pos))))
4109 (defun markdown-footnote-find-marker (id)
4110 "Find the location of the footnote marker with ID.
4111 The actual buffer position returned is the position directly
4112 following the marker's closing bracket. If no marker is found,
4113 NIL is returned."
4114 (save-excursion
4115 (goto-char (point-min))
4116 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
4117 (skip-chars-backward "^]")
4118 (point))))
4120 (defun markdown-footnote-find-text (id)
4121 "Find the location of the text of footnote ID.
4122 The actual buffer position returned is the position of the first
4123 character of the text, after the footnote's identifier. If no
4124 footnote text is found, NIL is returned."
4125 (save-excursion
4126 (goto-char (point-min))
4127 (when (re-search-forward (concat "^\\[" id "\\]:") nil t)
4128 (skip-chars-forward "[ \t]")
4129 (point))))
4131 (defun markdown-footnote-marker-positions ()
4132 "Return the position and ID of the footnote marker point is on.
4133 The return value is a list (ID START END). If point is not on a
4134 footnote, NIL is returned."
4135 ;; first make sure we're at a footnote marker
4136 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
4137 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
4138 (save-excursion
4139 ;; move point between [ and ^:
4140 (if (looking-at-p "\\[")
4141 (forward-char 1)
4142 (skip-chars-backward "^["))
4143 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
4144 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
4146 (defun markdown-footnote-text-positions ()
4147 "Return the start and end positions of the footnote text point is in.
4148 The exact return value is a list of three elements: (ID START END).
4149 The start position is the position of the opening bracket
4150 of the footnote id. The end position is directly after the
4151 newline that ends the footnote. If point is not in a footnote,
4152 NIL is returned instead."
4153 (save-excursion
4154 (let (result)
4155 (move-beginning-of-line 1)
4156 ;; Try to find the label. If we haven't found the label and we're at a blank
4157 ;; or indented line, back up if possible.
4158 (while (and
4159 (not (and (looking-at markdown-regex-footnote-definition)
4160 (setq result (list (match-string 1) (point)))))
4161 (and (not (bobp))
4162 (or (markdown-cur-line-blank-p)
4163 (>= (current-indentation) 4))))
4164 (forward-line -1))
4165 (when result
4166 ;; Advance if there is a next line that is either blank or indented.
4167 ;; (Need to check if we're on the last line, because
4168 ;; markdown-next-line-blank-p returns true for last line in buffer.)
4169 (while (and (/= (line-end-position) (point-max))
4170 (or (markdown-next-line-blank-p)
4171 (>= (markdown-next-line-indent) 4)))
4172 (forward-line))
4173 ;; Move back while the current line is blank.
4174 (while (markdown-cur-line-blank-p)
4175 (forward-line -1))
4176 ;; Advance to capture this line and a single trailing newline (if there
4177 ;; is one).
4178 (forward-line)
4179 (append result (list (point)))))))
4182 ;;; Element Removal ===========================================================
4184 (defun markdown-kill-thing-at-point ()
4185 "Kill thing at point and add important text, without markup, to kill ring.
4186 Possible things to kill include (roughly in order of precedence):
4187 inline code, headers, horizonal rules, links (add link text to
4188 kill ring), images (add alt text to kill ring), angle uri, email
4189 addresses, bold, italics, reference definition (add URI to kill
4190 ring), footnote markers and text (kill both marker and text, add
4191 text to kill ring), and list items."
4192 (interactive "*")
4193 (let (val)
4194 (cond
4195 ;; Inline code
4196 ((markdown-inline-code-at-point)
4197 (kill-new (match-string 2))
4198 (delete-region (match-beginning 0) (match-end 0)))
4199 ;; ATX header
4200 ((thing-at-point-looking-at markdown-regex-header-atx)
4201 (kill-new (match-string 2))
4202 (delete-region (match-beginning 0) (match-end 0)))
4203 ;; Setext header
4204 ((thing-at-point-looking-at markdown-regex-header-setext)
4205 (kill-new (match-string 1))
4206 (delete-region (match-beginning 0) (match-end 0)))
4207 ;; Horizonal rule
4208 ((thing-at-point-looking-at markdown-regex-hr)
4209 (kill-new (match-string 0))
4210 (delete-region (match-beginning 0) (match-end 0)))
4211 ;; Inline link or image (add link or alt text to kill ring)
4212 ((thing-at-point-looking-at markdown-regex-link-inline)
4213 (kill-new (match-string 3))
4214 (delete-region (match-beginning 0) (match-end 0)))
4215 ;; Reference link or image (add link or alt text to kill ring)
4216 ((thing-at-point-looking-at markdown-regex-link-reference)
4217 (kill-new (match-string 3))
4218 (delete-region (match-beginning 0) (match-end 0)))
4219 ;; Angle URI (add URL to kill ring)
4220 ((thing-at-point-looking-at markdown-regex-angle-uri)
4221 (kill-new (match-string 2))
4222 (delete-region (match-beginning 0) (match-end 0)))
4223 ;; Email address in angle brackets (add email address to kill ring)
4224 ((thing-at-point-looking-at markdown-regex-email)
4225 (kill-new (match-string 1))
4226 (delete-region (match-beginning 0) (match-end 0)))
4227 ;; Wiki link (add alias text to kill ring)
4228 ((and markdown-enable-wiki-links
4229 (thing-at-point-looking-at markdown-regex-wiki-link))
4230 (kill-new (markdown-wiki-link-alias))
4231 (delete-region (match-beginning 1) (match-end 1)))
4232 ;; Bold
4233 ((thing-at-point-looking-at markdown-regex-bold)
4234 (kill-new (match-string 4))
4235 (delete-region (match-beginning 2) (match-end 2)))
4236 ;; Italics
4237 ((thing-at-point-looking-at markdown-regex-italic)
4238 (kill-new (match-string 3))
4239 (delete-region (match-beginning 1) (match-end 1)))
4240 ;; Strikethrough
4241 ((thing-at-point-looking-at markdown-regex-strike-through)
4242 (kill-new (match-string 4))
4243 (delete-region (match-beginning 2) (match-end 2)))
4244 ;; Footnote marker (add footnote text to kill ring)
4245 ((thing-at-point-looking-at markdown-regex-footnote)
4246 (markdown-footnote-kill))
4247 ;; Footnote text (add footnote text to kill ring)
4248 ((setq val (markdown-footnote-text-positions))
4249 (markdown-footnote-kill))
4250 ;; Reference definition (add URL to kill ring)
4251 ((thing-at-point-looking-at markdown-regex-reference-definition)
4252 (kill-new (match-string 5))
4253 (delete-region (match-beginning 0) (match-end 0)))
4254 ;; List item
4255 ((setq val (markdown-cur-list-item-bounds))
4256 (kill-new (delete-and-extract-region (cl-first val) (cl-second val))))
4258 (error "Nothing found at point to kill")))))
4261 ;;; Indentation ====================================================================
4263 (defun markdown-indent-find-next-position (cur-pos positions)
4264 "Return the position after the index of CUR-POS in POSITIONS.
4265 Positions are calculated by `markdown-calc-indents'."
4266 (while (and positions
4267 (not (equal cur-pos (car positions))))
4268 (setq positions (cdr positions)))
4269 (or (cadr positions) 0))
4271 (defun markdown-exdent-find-next-position (cur-pos positions)
4272 "Return the maximal element that precedes CUR-POS from POSITIONS.
4273 Positions are calculated by `markdown-calc-indents'."
4274 (let ((result 0))
4275 (dolist (i positions)
4276 (when (< i cur-pos)
4277 (setq result (max result i))))
4278 result))
4280 (defun markdown-indent-line ()
4281 "Indent the current line using some heuristics.
4282 If the _previous_ command was either `markdown-enter-key' or
4283 `markdown-cycle', then we should cycle to the next
4284 reasonable indentation position. Otherwise, we could have been
4285 called directly by `markdown-enter-key', by an initial call of
4286 `markdown-cycle', or indirectly by `auto-fill-mode'. In
4287 these cases, indent to the default position.
4288 Positions are calculated by `markdown-calc-indents'."
4289 (interactive)
4290 (let ((positions (markdown-calc-indents))
4291 (cursor-pos (current-column))
4292 (_ (back-to-indentation))
4293 (cur-pos (current-column)))
4294 (if (not (equal this-command 'markdown-cycle))
4295 (indent-line-to (car positions))
4296 (setq positions (sort (delete-dups positions) '<))
4297 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions))
4298 (new-cursor-pos
4299 (if (< cur-pos next-pos)
4300 (+ cursor-pos (- next-pos cur-pos))
4301 (- cursor-pos cur-pos))))
4302 (indent-line-to next-pos)
4303 (move-to-column new-cursor-pos)))))
4305 (defun markdown-calc-indents ()
4306 "Return a list of indentation columns to cycle through.
4307 The first element in the returned list should be considered the
4308 default indentation level. This function does not worry about
4309 duplicate positions, which are handled up by calling functions."
4310 (let (pos prev-line-pos positions)
4312 ;; Indentation of previous line
4313 (setq prev-line-pos (markdown-prev-line-indent))
4314 (setq positions (cons prev-line-pos positions))
4316 ;; Indentation of previous non-list-marker text
4317 (when (setq pos (markdown-prev-non-list-indent))
4318 (setq positions (cons pos positions)))
4320 ;; Indentation required for a pre block in current context
4321 (setq pos (length (markdown-pre-indentation (point))))
4322 (setq positions (cons pos positions))
4324 ;; Indentation of the previous line + tab-width
4325 (if prev-line-pos
4326 (setq positions (cons (+ prev-line-pos tab-width) positions))
4327 (setq positions (cons tab-width positions)))
4329 ;; Indentation of the previous line - tab-width
4330 (if (and prev-line-pos (> prev-line-pos tab-width))
4331 (setq positions (cons (- prev-line-pos tab-width) positions)))
4333 ;; Indentation of all preceeding list markers (when in a list)
4334 (when (setq pos (markdown-calculate-list-levels))
4335 (setq positions (append pos positions)))
4337 ;; First column
4338 (setq positions (cons 0 positions))
4340 ;; Return reversed list
4341 (reverse positions)))
4343 (defun markdown-enter-key ()
4344 "Handle RET according to customized settings.
4345 When `markdown-indent-on-enter' is nil, this is equivalent to
4346 `newline'. Otherwise, indent following RET and when the point is
4347 in a list item, start a new item with the same indentation. If
4348 the point is in an empty list item, remove it."
4349 (interactive)
4350 (if (not markdown-indent-on-enter)
4351 (newline)
4352 (let ((bounds (markdown-cur-list-item-bounds)))
4353 (if bounds
4354 (let ((beg (cl-first bounds))
4355 (end (cl-second bounds))
4356 (length (cl-fourth bounds)))
4357 ;; Point is in a list item
4358 (if (= (- end beg) length)
4359 ;; Delete blank list
4360 (progn
4361 (delete-region beg end)
4362 (newline)
4363 (markdown-indent-line))
4364 (call-interactively #'markdown-insert-list-item)))
4365 ;; Point is not in a list
4366 (newline)
4367 (markdown-indent-line)))))
4369 (defun markdown-exdent-or-delete (arg)
4370 "Handle BACKSPACE by cycling through indentation points.
4371 When BACKSPACE is pressed, if there is only whitespace
4372 before the current point, then exdent the line one level.
4373 Otherwise, do normal delete by repeating
4374 `backward-delete-char-untabify' ARG times."
4375 (interactive "*p")
4376 (if (use-region-p)
4377 (backward-delete-char-untabify arg)
4378 (let ((cur-pos (current-column))
4379 (start-of-indention (save-excursion
4380 (back-to-indentation)
4381 (current-column)))
4382 (positions (markdown-calc-indents)))
4383 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
4384 (indent-line-to (markdown-exdent-find-next-position cur-pos positions))
4385 (backward-delete-char-untabify arg)))))
4387 (defun markdown-find-leftmost-column (beg end)
4388 "Find the leftmost column in the region from BEG to END."
4389 (let ((mincol 1000))
4390 (save-excursion
4391 (goto-char beg)
4392 (while (< (point) end)
4393 (back-to-indentation)
4394 (unless (looking-at-p "[ \t]*$")
4395 (setq mincol (min mincol (current-column))))
4396 (forward-line 1)
4398 mincol))
4400 (defun markdown-indent-region (beg end arg)
4401 "Indent the region from BEG to END using some heuristics.
4402 When ARG is non-nil, exdent the region instead.
4403 See `markdown-indent-line' and `markdown-indent-line'."
4404 (interactive "*r\nP")
4405 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
4406 (leftmostcol (markdown-find-leftmost-column beg end))
4407 (next-pos (if arg
4408 (markdown-exdent-find-next-position leftmostcol positions)
4409 (markdown-indent-find-next-position leftmostcol positions))))
4410 (indent-rigidly beg end (- next-pos leftmostcol))
4411 (setq deactivate-mark nil)))
4413 (defun markdown-exdent-region (beg end)
4414 "Call `markdown-indent-region' on region from BEG to END with prefix."
4415 (interactive "*r")
4416 (markdown-indent-region beg end t))
4419 ;;; Markup Completion =========================================================
4421 (defconst markdown-complete-alist
4422 '((markdown-regex-header-atx . markdown-complete-atx)
4423 (markdown-regex-header-setext . markdown-complete-setext)
4424 (markdown-regex-hr . markdown-complete-hr))
4425 "Association list of form (regexp . function) for markup completion.")
4427 (defun markdown-incomplete-atx-p ()
4428 "Return t if ATX header markup is incomplete and nil otherwise.
4429 Assumes match data is available for `markdown-regex-header-atx'.
4430 Checks that the number of trailing hash marks equals the number of leading
4431 hash marks, that there is only a single space before and after the text,
4432 and that there is no extraneous whitespace in the text."
4434 ;; Number of starting and ending hash marks differs
4435 (not (= (length (match-string 1)) (length (match-string 3))))
4436 ;; When the header text is not empty...
4437 (and (> (length (match-string 2)) 0)
4438 ;; ...if there are extra leading, trailing, or interior spaces
4439 (or (not (= (match-beginning 2) (1+ (match-end 1))))
4440 (not (= (match-beginning 3) (1+ (match-end 2))))
4441 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
4442 ;; When the header text is empty...
4443 (and (= (length (match-string 2)) 0)
4444 ;; ...if there are too many or too few spaces
4445 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
4447 (defun markdown-complete-atx ()
4448 "Complete and normalize ATX headers.
4449 Add or remove hash marks to the end of the header to match the
4450 beginning. Ensure that there is only a single space between hash
4451 marks and header text. Removes extraneous whitespace from header text.
4452 Assumes match data is available for `markdown-regex-header-atx'.
4453 Return nil if markup was complete and non-nil if markup was completed."
4454 (when (markdown-incomplete-atx-p)
4455 (let* ((new-marker (make-marker))
4456 (new-marker (set-marker new-marker (match-end 2))))
4457 ;; Hash marks and spacing at end
4458 (goto-char (match-end 2))
4459 (delete-region (match-end 2) (match-end 3))
4460 (insert " " (match-string 1))
4461 ;; Remove extraneous whitespace from title
4462 (replace-match (markdown-compress-whitespace-string (match-string 2))
4463 t t nil 2)
4464 ;; Spacing at beginning
4465 (goto-char (match-end 1))
4466 (delete-region (match-end 1) (match-beginning 2))
4467 (insert " ")
4468 ;; Leave point at end of text
4469 (goto-char new-marker))))
4471 (defun markdown-incomplete-setext-p ()
4472 "Return t if setext header markup is incomplete and nil otherwise.
4473 Assumes match data is available for `markdown-regex-header-setext'.
4474 Checks that length of underline matches text and that there is no
4475 extraneous whitespace in the text."
4476 (or (not (= (length (match-string 1)) (length (match-string 2))))
4477 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
4479 (defun markdown-complete-setext ()
4480 "Complete and normalize setext headers.
4481 Add or remove underline characters to match length of header
4482 text. Removes extraneous whitespace from header text. Assumes
4483 match data is available for `markdown-regex-header-setext'.
4484 Return nil if markup was complete and non-nil if markup was completed."
4485 (when (markdown-incomplete-setext-p)
4486 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
4487 (char (char-after (match-beginning 2)))
4488 (level (if (char-equal char ?-) 2 1)))
4489 (goto-char (match-beginning 0))
4490 (delete-region (match-beginning 0) (match-end 0))
4491 (markdown-insert-header level text t)
4492 t)))
4494 (defun markdown-incomplete-hr-p ()
4495 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
4496 Assumes match data is available for `markdown-regex-hr'."
4497 (not (member (match-string 0) markdown-hr-strings)))
4499 (defun markdown-complete-hr ()
4500 "Complete horizontal rules.
4501 If horizontal rule string is a member of `markdown-hr-strings',
4502 do nothing. Otherwise, replace with the car of
4503 `markdown-hr-strings'.
4504 Assumes match data is available for `markdown-regex-hr'.
4505 Return nil if markup was complete and non-nil if markup was completed."
4506 (when (markdown-incomplete-hr-p)
4507 (replace-match (car markdown-hr-strings))
4510 (defun markdown-complete ()
4511 "Complete markup of object near point or in region when active.
4512 Handle all objects in `markdown-complete-alist', in order.
4513 See `markdown-complete-at-point' and `markdown-complete-region'."
4514 (interactive "*")
4515 (if (markdown-use-region-p)
4516 (markdown-complete-region (region-beginning) (region-end))
4517 (markdown-complete-at-point)))
4519 (defun markdown-complete-at-point ()
4520 "Complete markup of object near point.
4521 Handle all elements of `markdown-complete-alist' in order."
4522 (interactive "*")
4523 (let ((list markdown-complete-alist) found changed)
4524 (while list
4525 (let ((regexp (eval (caar list)))
4526 (function (cdar list)))
4527 (setq list (cdr list))
4528 (when (thing-at-point-looking-at regexp)
4529 (setq found t)
4530 (setq changed (funcall function))
4531 (setq list nil))))
4532 (if found
4533 (or changed (error "Markup at point is complete"))
4534 (error "Nothing to complete at point"))))
4536 (defun markdown-complete-region (beg end)
4537 "Complete markup of objects in region from BEG to END.
4538 Handle all objects in `markdown-complete-alist', in order. Each
4539 match is checked to ensure that a previous regexp does not also
4540 match."
4541 (interactive "*r")
4542 (let ((end-marker (set-marker (make-marker) end))
4543 previous)
4544 (dolist (element markdown-complete-alist)
4545 (let ((regexp (eval (car element)))
4546 (function (cdr element)))
4547 (goto-char beg)
4548 (while (re-search-forward regexp end-marker 'limit)
4549 (when (match-string 0)
4550 ;; Make sure this is not a match for any of the preceding regexps.
4551 ;; This prevents mistaking an HR for a Setext subheading.
4552 (let (match)
4553 (save-match-data
4554 (dolist (prev-regexp previous)
4555 (or match (setq match (looking-back prev-regexp nil)))))
4556 (unless match
4557 (save-excursion (funcall function))))))
4558 (cl-pushnew regexp previous :test #'equal)))
4559 previous))
4561 (defun markdown-complete-buffer ()
4562 "Complete markup for all objects in the current buffer."
4563 (interactive "*")
4564 (markdown-complete-region (point-min) (point-max)))
4567 ;;; Markup Cycling ============================================================
4569 (defun markdown-cycle-atx (arg &optional remove)
4570 "Cycle ATX header markup.
4571 Promote header (decrease level) when ARG is 1 and demote
4572 header (increase level) if arg is -1. When REMOVE is non-nil,
4573 remove the header when the level reaches zero and stop cycling
4574 when it reaches six. Otherwise, perform a proper cycling through
4575 levels one through six. Assumes match data is available for
4576 `markdown-regex-header-atx'."
4577 (let* ((old-level (length (match-string 1)))
4578 (new-level (+ old-level arg))
4579 (text (match-string 2)))
4580 (when (not remove)
4581 (setq new-level (% new-level 6))
4582 (setq new-level (cond ((= new-level 0) 6)
4583 ((< new-level 0) (+ new-level 6))
4584 (t new-level))))
4585 (cond
4586 ((= new-level 0)
4587 (markdown-unwrap-thing-at-point nil 0 2))
4588 ((<= new-level 6)
4589 (goto-char (match-beginning 0))
4590 (delete-region (match-beginning 0) (match-end 0))
4591 (markdown-insert-header new-level text nil)))))
4593 (defun markdown-cycle-setext (arg &optional remove)
4594 "Cycle setext header markup.
4595 Promote header (increase level) when ARG is 1 and demote
4596 header (decrease level or remove) if arg is -1. When demoting a
4597 level-two setext header, replace with a level-three atx header.
4598 When REMOVE is non-nil, remove the header when the level reaches
4599 zero. Otherwise, cycle back to a level six atx header. Assumes
4600 match data is available for `markdown-regex-header-setext'."
4601 (let* ((char (char-after (match-beginning 2)))
4602 (old-level (if (char-equal char ?=) 1 2))
4603 (new-level (+ old-level arg)))
4604 (when (and (not remove) (= new-level 0))
4605 (setq new-level 6))
4606 (cond
4607 ((= new-level 0)
4608 (markdown-unwrap-thing-at-point nil 0 1))
4609 ((<= new-level 2)
4610 (markdown-insert-header new-level nil t))
4611 ((<= new-level 6)
4612 (markdown-insert-header new-level nil nil)))))
4614 (defun markdown-cycle-hr (arg &optional remove)
4615 "Cycle string used for horizontal rule from `markdown-hr-strings'.
4616 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
4617 backwards (promote). When REMOVE is non-nil, remove the hr instead
4618 of cycling when the end of the list is reached.
4619 Assumes match data is available for `markdown-regex-hr'."
4620 (let* ((strings (if (= arg -1)
4621 (reverse markdown-hr-strings)
4622 markdown-hr-strings))
4623 (tail (member (match-string 0) strings))
4624 (new (or (cadr tail)
4625 (if remove
4626 (if (= arg 1)
4628 (car tail))
4629 (car strings)))))
4630 (replace-match new)))
4632 (defun markdown-cycle-bold ()
4633 "Cycle bold markup between underscores and asterisks.
4634 Assumes match data is available for `markdown-regex-bold'."
4635 (save-excursion
4636 (let* ((old-delim (match-string 3))
4637 (new-delim (if (string-equal old-delim "**") "__" "**")))
4638 (replace-match new-delim t t nil 3)
4639 (replace-match new-delim t t nil 5))))
4641 (defun markdown-cycle-italic ()
4642 "Cycle italic markup between underscores and asterisks.
4643 Assumes match data is available for `markdown-regex-italic'."
4644 (save-excursion
4645 (let* ((old-delim (match-string 2))
4646 (new-delim (if (string-equal old-delim "*") "_" "*")))
4647 (replace-match new-delim t t nil 2)
4648 (replace-match new-delim t t nil 4))))
4651 ;;; Keymap ====================================================================
4653 (defvar markdown-mode-map
4654 (let ((map (make-keymap)))
4655 ;; Element insertion
4656 (define-key map "\C-c\C-al" 'markdown-insert-inline-link-dwim)
4657 (define-key map "\C-c\C-aL" 'markdown-insert-reference-link-dwim)
4658 (define-key map "\C-c\C-au" 'markdown-insert-uri)
4659 (define-key map "\C-c\C-af" 'markdown-insert-footnote)
4660 (define-key map "\C-c\C-aw" 'markdown-insert-wiki-link)
4661 (define-key map "\C-c\C-ii" 'markdown-insert-image)
4662 (define-key map "\C-c\C-iI" 'markdown-insert-reference-image)
4663 (define-key map "\C-c\C-i\C-t" 'markdown-toggle-inline-images)
4664 (define-key map "\C-c\C-th" 'markdown-insert-header-dwim)
4665 (define-key map "\C-c\C-tH" 'markdown-insert-header-setext-dwim)
4666 (define-key map "\C-c\C-t1" 'markdown-insert-header-atx-1)
4667 (define-key map "\C-c\C-t2" 'markdown-insert-header-atx-2)
4668 (define-key map "\C-c\C-t3" 'markdown-insert-header-atx-3)
4669 (define-key map "\C-c\C-t4" 'markdown-insert-header-atx-4)
4670 (define-key map "\C-c\C-t5" 'markdown-insert-header-atx-5)
4671 (define-key map "\C-c\C-t6" 'markdown-insert-header-atx-6)
4672 (define-key map "\C-c\C-t!" 'markdown-insert-header-setext-1)
4673 (define-key map "\C-c\C-t@" 'markdown-insert-header-setext-2)
4674 (define-key map "\C-c\C-ss" 'markdown-insert-bold)
4675 (define-key map "\C-c\C-se" 'markdown-insert-italic)
4676 (define-key map "\C-c\C-sc" 'markdown-insert-code)
4677 (define-key map "\C-c\C-sb" 'markdown-insert-blockquote)
4678 (define-key map "\C-c\C-sk" 'markdown-insert-kbd)
4679 (define-key map "\C-c\C-s\C-b" 'markdown-blockquote-region)
4680 (define-key map "\C-c\C-sp" 'markdown-insert-pre)
4681 (define-key map "\C-c\C-s\C-p" 'markdown-pre-region)
4682 (define-key map "\C-c\C-sP" 'markdown-insert-gfm-code-block)
4683 (define-key map "\C-c-" 'markdown-insert-hr)
4684 ;; Element insertion (deprecated)
4685 (define-key map "\C-c\C-ar" 'markdown-insert-reference-link-dwim)
4686 (define-key map "\C-c\C-tt" 'markdown-insert-header-setext-1)
4687 (define-key map "\C-c\C-ts" 'markdown-insert-header-setext-2)
4688 ;; Element removal
4689 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
4690 ;; Promotion, Demotion, Completion, and Cycling
4691 (define-key map (kbd "C-c C--") 'markdown-promote)
4692 (define-key map (kbd "C-c C-=") 'markdown-demote)
4693 (define-key map (kbd "C-c C-]") 'markdown-complete)
4694 ;; Following and Jumping
4695 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
4696 (define-key map (kbd "C-c C-l") 'markdown-jump)
4697 ;; Indentation
4698 (define-key map (kbd "C-m") 'markdown-enter-key)
4699 (define-key map (kbd "DEL") 'markdown-exdent-or-delete)
4700 (define-key map (kbd "C-c >") 'markdown-indent-region)
4701 (define-key map (kbd "C-c <") 'markdown-exdent-region)
4702 ;; Visibility cycling
4703 (define-key map (kbd "TAB") 'markdown-cycle)
4704 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
4705 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
4706 (define-key map (kbd "<backtab>") 'markdown-shifttab)
4707 ;; Header navigation
4708 (define-key map (kbd "C-c C-n") 'markdown-next-visible-heading)
4709 (define-key map (kbd "C-c C-p") 'markdown-previous-visible-heading)
4710 (define-key map (kbd "C-c C-f") 'markdown-forward-same-level)
4711 (define-key map (kbd "C-c C-b") 'markdown-backward-same-level)
4712 (define-key map (kbd "C-c C-u") 'markdown-up-heading)
4713 ;; Buffer-wide commands
4714 (define-key map (kbd "C-c C-c m") 'markdown-other-window)
4715 (define-key map (kbd "C-c C-c p") 'markdown-preview)
4716 (define-key map (kbd "C-c C-c e") 'markdown-export)
4717 (define-key map (kbd "C-c C-c v") 'markdown-export-and-preview)
4718 (define-key map (kbd "C-c C-c o") 'markdown-open)
4719 (define-key map (kbd "C-c C-c l") 'markdown-live-preview-mode)
4720 (define-key map (kbd "C-c C-c w") 'markdown-kill-ring-save)
4721 (define-key map (kbd "C-c C-c c") 'markdown-check-refs)
4722 (define-key map (kbd "C-c C-c n") 'markdown-cleanup-list-numbers)
4723 (define-key map (kbd "C-c C-c ]") 'markdown-complete-buffer)
4724 ;; List editing
4725 (define-key map (kbd "M-<up>") 'markdown-move-up)
4726 (define-key map (kbd "M-<down>") 'markdown-move-down)
4727 (define-key map (kbd "M-<left>") 'markdown-promote)
4728 (define-key map (kbd "M-<right>") 'markdown-demote)
4729 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
4730 (define-key map (kbd "C-c C-j") 'markdown-insert-list-item)
4731 ;; Subtree editing
4732 (define-key map (kbd "M-S-<up>") 'markdown-move-subtree-up)
4733 (define-key map (kbd "M-S-<down>") 'markdown-move-subtree-down)
4734 (define-key map (kbd "M-S-<left>") 'markdown-promote-subtree)
4735 (define-key map (kbd "M-S-<right>") 'markdown-demote-subtree)
4736 ;; Movement
4737 (define-key map (kbd "M-n") 'markdown-next-link)
4738 (define-key map (kbd "M-p") 'markdown-previous-link)
4739 ;; Alternative keys (in case of problems with the arrow keys)
4740 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
4741 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
4742 (define-key map (kbd "C-c C-x l") 'markdown-promote)
4743 (define-key map (kbd "C-c C-x r") 'markdown-demote)
4744 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item)
4745 (define-key map (kbd "C-c C-x C-x") 'markdown-toggle-gfm-checkbox)
4746 map)
4747 "Keymap for Markdown major mode.")
4749 (defvar gfm-mode-map
4750 (let ((map (make-sparse-keymap)))
4751 (set-keymap-parent map markdown-mode-map)
4752 (define-key map (kbd "C-c C-s d") 'markdown-insert-strike-through)
4753 (define-key map "`" 'markdown-electric-backquote)
4754 map)
4755 "Keymap for `gfm-mode'.
4756 See also `markdown-mode-map'.")
4759 ;;; Menu ==================================================================
4761 (easy-menu-define markdown-mode-menu markdown-mode-map
4762 "Menu for Markdown mode"
4763 '("Markdown"
4764 "---"
4765 ("Movement"
4766 ["Jump" markdown-jump]
4767 ["Follow Link" markdown-follow-thing-at-point]
4768 ["Next Link" markdown-next-link]
4769 ["Previous Link" markdown-previous-link]
4770 "---"
4771 ["Next Visible Heading" markdown-next-visible-heading]
4772 ["Previous Visible Heading" markdown-previous-visible-heading]
4773 ["Forward Same Level" markdown-forward-same-level]
4774 ["Backward Same Level" markdown-backward-same-level]
4775 ["Up to Parent Heading" markdown-up-heading])
4776 ("Show/Hide"
4777 ["Cycle Visibility" markdown-cycle (markdown-on-heading-p)]
4778 ["Cycle Visibility Globally" markdown-shifttab])
4779 "---"
4780 ("Headings & Structure"
4781 ["Automatic Heading" markdown-insert-header-dwim]
4782 ["Automatic Heading (Setext)" markdown-insert-header-setext-dwim]
4783 ("Specific Heading (atx)"
4784 ["First Level Setext" markdown-insert-header-setext-1]
4785 ["Second Level Setext" markdown-insert-header-setext-2])
4786 ("Specific Heading (Setext)"
4787 ["First Level atx" markdown-insert-header-atx-1]
4788 ["Second Level atx" markdown-insert-header-atx-2]
4789 ["Third Level atx" markdown-insert-header-atx-3]
4790 ["Fourth Level atx" markdown-insert-header-atx-4]
4791 ["Fifth Level atx" markdown-insert-header-atx-5]
4792 ["Sixth Level atx" markdown-insert-header-atx-6])
4793 ["Horizontal Rule" markdown-insert-hr]
4794 "---"
4795 ["Move Subtree Up" markdown-move-subtree-up :keys "M-S-<up>"]
4796 ["Move Subtree Down" markdown-move-subtree-down :keys "M-S-<down>"]
4797 ["Promote Subtree" markdown-promote-subtree :keys "M-S-<left>"]
4798 ["Demote Subtree" markdown-demote-subtree :keys "M-S-<right>"]
4799 ["Promote Header" markdown-promote :keys "M-<left>"]
4800 ["Demote Header" markdown-demote :keys "M-<right>"])
4801 ("Region Editing"
4802 ["Indent Region" markdown-indent-region]
4803 ["Exdent Region" markdown-exdent-region])
4804 ("Lists"
4805 ["Insert List Item" markdown-insert-list-item]
4806 ["Move List Item Up" markdown-move-up :keys "M-<up>"]
4807 ["Move List Item Down" markdown-move-down :keys "M-<down>"]
4808 ["Exdent List Item" markdown-promote :keys "M-<left>"]
4809 ["Indent List Item" markdown-demote :keys "M-<right>"]
4810 ["Renumber List" markdown-cleanup-list-numbers]
4811 ["Toggle Task List Item" markdown-toggle-gfm-checkbox])
4812 ("Links & Images"
4813 ["Plain URL" markdown-insert-uri]
4814 ["Inline Link" markdown-insert-inline-link-dwim]
4815 ["Inline Image" markdown-insert-image]
4816 ["Reference Link" markdown-insert-reference-link-dwim]
4817 ["Reference Image" markdown-insert-reference-image]
4818 ["Footnote" markdown-insert-footnote]
4819 ["Wiki Link" markdown-insert-wiki-link]
4820 "---"
4821 ["Check References" markdown-check-refs]
4822 ["Toggle Inline Images" markdown-toggle-inline-images
4823 :style radio
4824 :selected markdown-inline-image-overlays])
4825 ("Styles"
4826 ["Bold" markdown-insert-bold]
4827 ["Italic" markdown-insert-italic]
4828 ["Code" markdown-insert-code]
4829 ["Strikethrough" markdown-insert-strike-through]
4830 ["Keyboard" markdown-insert-kbd]
4831 "---"
4832 ["Blockquote" markdown-insert-blockquote]
4833 ["Preformatted" markdown-insert-pre]
4834 ["GFM Code Block" markdown-insert-gfm-code-block]
4835 "---"
4836 ["Blockquote Region" markdown-blockquote-region]
4837 ["Preformatted Region" markdown-pre-region]
4838 "---"
4839 ["Enable LaTeX math" markdown-toggle-math
4840 :style radio
4841 :selected markdown-enable-math])
4842 "---"
4843 ("Preview & Export"
4844 ["Compile" markdown-other-window]
4845 ["Preview" markdown-preview]
4846 ["Export" markdown-export]
4847 ["Export & View" markdown-export-and-preview]
4848 ["Open" markdown-open]
4849 ["Live Export" markdown-live-preview-mode
4850 :style radio
4851 :selected markdown-live-preview-mode]
4852 ["Kill ring save" markdown-kill-ring-save])
4853 ("Markup Completion and Cycling"
4854 ["Complete Markup" markdown-complete]
4855 ["Promote Element" markdown-promote]
4856 ["Demote Element" markdown-demote])
4857 "---"
4858 ["Kill Element" markdown-kill-thing-at-point]
4859 "---"
4860 ("Documentation"
4861 ["Version" markdown-show-version]
4862 ["Homepage" markdown-mode-info]
4863 ["Describe Mode" (describe-function 'markdown-mode)])))
4866 ;;; imenu =====================================================================
4868 (defun markdown-imenu-create-nested-index ()
4869 "Create and return a nested imenu index alist for the current buffer.
4870 See `imenu-create-index-function' and `imenu--index-alist' for details."
4871 (let* ((root '(nil . nil))
4872 cur-alist
4873 (cur-level 0)
4874 (empty-heading "-")
4875 (self-heading ".")
4876 hashes pos level heading)
4877 (save-excursion
4878 (goto-char (point-min))
4879 (while (re-search-forward markdown-regex-header (point-max) t)
4880 (unless (markdown-code-block-at-point-p)
4881 (cond
4882 ((match-string-no-properties 2) ;; level 1 setext
4883 (setq heading (match-string-no-properties 1))
4884 (setq pos (match-beginning 1)
4885 level 1))
4886 ((match-string-no-properties 3) ;; level 2 setext
4887 (setq heading (match-string-no-properties 1))
4888 (setq pos (match-beginning 1)
4889 level 2))
4890 ((setq hashes (match-string-no-properties 4))
4891 (setq heading (match-string-no-properties 5)
4892 pos (match-beginning 4)
4893 level (length hashes))))
4894 (let ((alist (list (cons heading pos))))
4895 (cond
4896 ((= cur-level level) ; new sibling
4897 (setcdr cur-alist alist)
4898 (setq cur-alist alist))
4899 ((< cur-level level) ; first child
4900 (dotimes (_ (- level cur-level 1))
4901 (setq alist (list (cons empty-heading alist))))
4902 (if cur-alist
4903 (let* ((parent (car cur-alist))
4904 (self-pos (cdr parent)))
4905 (setcdr parent (cons (cons self-heading self-pos) alist)))
4906 (setcdr root alist)) ; primogenitor
4907 (setq cur-alist alist)
4908 (setq cur-level level))
4909 (t ; new sibling of an ancestor
4910 (let ((sibling-alist (last (cdr root))))
4911 (dotimes (_ (1- level))
4912 (setq sibling-alist (last (cdar sibling-alist))))
4913 (setcdr sibling-alist alist)
4914 (setq cur-alist alist))
4915 (setq cur-level level))))))
4916 (cdr root))))
4918 (defun markdown-imenu-create-flat-index ()
4919 "Create and return a flat imenu index alist for the current buffer.
4920 See `imenu-create-index-function' and `imenu--index-alist' for details."
4921 (let* ((empty-heading "-") index heading pos)
4922 (save-excursion
4923 (goto-char (point-min))
4924 (while (re-search-forward markdown-regex-header (point-max) t)
4925 (when (and (not (markdown-code-block-at-point-p))
4926 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin)))
4927 (cond
4928 ((setq heading (match-string-no-properties 1))
4929 (setq pos (match-beginning 1)))
4930 ((setq heading (match-string-no-properties 5))
4931 (setq pos (match-beginning 4))))
4932 (or (> (length heading) 0)
4933 (setq heading empty-heading))
4934 (setq index (append index (list (cons heading pos))))))
4935 index)))
4938 ;;; References ================================================================
4940 (defun markdown-reference-goto-definition ()
4941 "Jump to the definition of the reference at point or create it."
4942 (interactive)
4943 (when (thing-at-point-looking-at markdown-regex-link-reference)
4944 (let* ((text (match-string-no-properties 3))
4945 (reference (match-string-no-properties 6))
4946 (target (downcase (if (string= reference "") text reference)))
4947 (loc (cadr (markdown-reference-definition target))))
4948 (if loc
4949 (goto-char loc)
4950 (goto-char (match-beginning 0))
4951 (markdown-insert-reference-definition target)))))
4953 (defun markdown-reference-find-links (reference)
4954 "Return a list of all links for REFERENCE.
4955 REFERENCE should not include the surrounding square brackets.
4956 Elements of the list have the form (text start line), where
4957 text is the link text, start is the location at the beginning of
4958 the link, and line is the line number on which the link appears."
4959 (let* ((ref-quote (regexp-quote reference))
4960 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
4961 ref-quote ref-quote))
4962 links)
4963 (save-excursion
4964 (goto-char (point-min))
4965 (while (re-search-forward regexp nil t)
4966 (let* ((text (or (match-string-no-properties 1)
4967 (match-string-no-properties 2)))
4968 (start (match-beginning 0))
4969 (line (markdown-line-number-at-pos)))
4970 (cl-pushnew (list text start line) links :test #'equal))))
4971 links))
4973 (defun markdown-get-undefined-refs ()
4974 "Return a list of undefined Markdown references.
4975 Result is an alist of pairs (reference . occurrences), where
4976 occurrences is itself another alist of pairs (label . line-number).
4977 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
4978 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
4979 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
4980 (let ((missing))
4981 (save-excursion
4982 (goto-char (point-min))
4983 (while
4984 (re-search-forward markdown-regex-link-reference nil t)
4985 (let* ((text (match-string-no-properties 3))
4986 (reference (match-string-no-properties 6))
4987 (target (downcase (if (string= reference "") text reference))))
4988 (unless (markdown-reference-definition target)
4989 (let ((entry (assoc target missing)))
4990 (if (not entry)
4991 (cl-pushnew
4992 (cons target (list (cons text (markdown-line-number-at-pos))))
4993 missing :test #'equal)
4994 (setcdr entry
4995 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
4996 (reverse missing))))
4998 (defconst markdown-reference-check-buffer
4999 "*Undefined references for %buffer%*"
5000 "Pattern for name of buffer for listing undefined references.
5001 The string %buffer% will be replaced by the corresponding
5002 `markdown-mode' buffer name.")
5004 (defun markdown-reference-check-buffer (&optional buffer-name)
5005 "Name and return buffer for reference checking.
5006 BUFFER-NAME is the name of the main buffer being visited."
5007 (or buffer-name (setq buffer-name (buffer-name)))
5008 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
5009 "%buffer%" buffer-name
5010 markdown-reference-check-buffer))))
5011 (with-current-buffer refbuf
5012 (when view-mode
5013 (View-exit-and-edit))
5014 (use-local-map button-buffer-map)
5015 (erase-buffer))
5016 refbuf))
5018 (defconst markdown-reference-links-buffer
5019 "*Reference links for %buffer%*"
5020 "Pattern for name of buffer for listing references.
5021 The string %buffer% will be replaced by the corresponding buffer name.")
5023 (defun markdown-reference-links-buffer (&optional buffer-name)
5024 "Name, setup, and return a buffer for listing links.
5025 BUFFER-NAME is the name of the main buffer being visited."
5026 (or buffer-name (setq buffer-name (buffer-name)))
5027 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
5028 "%buffer%" buffer-name
5029 markdown-reference-links-buffer))))
5030 (with-current-buffer linkbuf
5031 (when view-mode
5032 (View-exit-and-edit))
5033 (use-local-map button-buffer-map)
5034 (erase-buffer))
5035 linkbuf))
5037 (when (markdown-use-buttons-p)
5038 ;; Add an empty Markdown reference definition to buffer
5039 ;; specified in the 'target-buffer property. The reference name is
5040 ;; the button's label.
5041 (define-button-type 'markdown-undefined-reference-button
5042 'help-echo "mouse-1, RET: create definition for undefined reference"
5043 'follow-link t
5044 'face 'bold
5045 'action (lambda (b)
5046 (let ((buffer (button-get b 'target-buffer))
5047 (line (button-get b 'target-line))
5048 (label (button-label b)))
5049 (switch-to-buffer-other-window buffer)
5050 (goto-char (point-min))
5051 (forward-line line)
5052 (markdown-insert-reference-definition label)
5053 (markdown-check-refs t))))
5055 ;; Jump to line in buffer specified by 'target-buffer property.
5056 ;; Line number is button's 'line property.
5057 (define-button-type 'markdown-goto-line-button
5058 'help-echo "mouse-1, RET: go to line"
5059 'follow-link t
5060 'face 'italic
5061 'action (lambda (b)
5062 (message (button-get b 'buffer))
5063 (switch-to-buffer-other-window (button-get b 'target-buffer))
5064 ;; use call-interactively to silence compiler
5065 (let ((current-prefix-arg (button-get b 'target-line)))
5066 (call-interactively 'goto-line))))
5068 ;; Jumps to a particular link at location given by 'target-char
5069 ;; property in buffer given by 'target-buffer property.
5070 (define-button-type 'markdown-link-button
5071 'help-echo "mouse-1, RET: jump to location of link"
5072 'follow-link t
5073 'face 'bold
5074 'action (lambda (b)
5075 (let ((target (button-get b 'target-buffer))
5076 (loc (button-get b 'target-char)))
5077 (kill-buffer-and-window)
5078 (switch-to-buffer target)
5079 (goto-char loc)))))
5081 (defun markdown-insert-undefined-reference-button (reference oldbuf)
5082 "Insert a button for creating REFERENCE in buffer OLDBUF.
5083 REFERENCE should be a list of the form (reference . occurrences),
5084 as by `markdown-get-undefined-refs'."
5085 (let ((label (car reference)))
5086 (if (markdown-use-buttons-p)
5087 ;; Create a reference button in Emacs 22
5088 (insert-button label
5089 :type 'markdown-undefined-reference-button
5090 'target-buffer oldbuf
5091 'target-line (cdr (car (cdr reference))))
5092 ;; Insert reference as text in Emacs < 22
5093 (insert label))
5094 (insert " (")
5095 (dolist (occurrence (cdr reference))
5096 (let ((line (cdr occurrence)))
5097 (if (markdown-use-buttons-p)
5098 ;; Create a line number button in Emacs 22
5099 (insert-button (number-to-string line)
5100 :type 'markdown-goto-line-button
5101 'target-buffer oldbuf
5102 'target-line line)
5103 ;; Insert line number as text in Emacs < 22
5104 (insert (number-to-string line)))
5105 (insert " ")))
5106 (delete-char -1)
5107 (insert ")")
5108 (newline)))
5110 (defun markdown-insert-link-button (link oldbuf)
5111 "Insert a button for jumping to LINK in buffer OLDBUF.
5112 LINK should be a list of the form (text char line) containing
5113 the link text, location, and line number."
5114 (let ((label (cl-first link))
5115 (char (cl-second link))
5116 (line (cl-third link)))
5117 (if (markdown-use-buttons-p)
5118 ;; Create a reference button in Emacs 22
5119 (insert-button label
5120 :type 'markdown-link-button
5121 'target-buffer oldbuf
5122 'target-char char)
5123 ;; Insert reference as text in Emacs < 22
5124 (insert label))
5125 (insert (format " (line %d)\n" line))))
5127 (defun markdown-reference-goto-link (&optional reference)
5128 "Jump to the location of the first use of REFERENCE."
5129 (interactive)
5130 (unless reference
5131 (if (thing-at-point-looking-at markdown-regex-reference-definition)
5132 (setq reference (match-string-no-properties 2))
5133 (error "No reference definition at point")))
5134 (let ((links (markdown-reference-find-links reference)))
5135 (cond ((= (length links) 1)
5136 (goto-char (cadr (car links))))
5137 ((> (length links) 1)
5138 (let ((oldbuf (current-buffer))
5139 (linkbuf (markdown-reference-links-buffer)))
5140 (with-current-buffer linkbuf
5141 (insert "Links using reference " reference ":\n\n")
5142 (dolist (link (reverse links))
5143 (markdown-insert-link-button link oldbuf)))
5144 (view-buffer-other-window linkbuf)
5145 (goto-char (point-min))
5146 (forward-line 2)))
5148 (error "No links for reference %s" reference)))))
5150 (defun markdown-check-refs (&optional silent)
5151 "Show all undefined Markdown references in current `markdown-mode' buffer.
5152 If SILENT is non-nil, do not message anything when no undefined
5153 references found.
5154 Links which have empty reference definitions are considered to be
5155 defined."
5156 (interactive "P")
5157 (when (not (eq major-mode 'markdown-mode))
5158 (error "Not available in current mode"))
5159 (let ((oldbuf (current-buffer))
5160 (refs (markdown-get-undefined-refs))
5161 (refbuf (markdown-reference-check-buffer)))
5162 (if (null refs)
5163 (progn
5164 (when (not silent)
5165 (message "No undefined references found"))
5166 (kill-buffer refbuf))
5167 (with-current-buffer refbuf
5168 (insert "The following references are undefined:\n\n")
5169 (dolist (ref refs)
5170 (markdown-insert-undefined-reference-button ref oldbuf))
5171 (view-buffer-other-window refbuf)
5172 (goto-char (point-min))
5173 (forward-line 2)))))
5176 ;;; Lists =====================================================================
5178 (defun markdown-insert-list-item (&optional arg)
5179 "Insert a new list item.
5180 If the point is inside unordered list, insert a bullet mark. If
5181 the point is inside ordered list, insert the next number followed
5182 by a period. Use the previous list item to determine the amount
5183 of whitespace to place before and after list markers.
5185 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
5186 decrease the indentation by one level.
5188 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
5189 increase the indentation by one level."
5190 (interactive "p")
5191 (let (bounds cur-indent marker indent new-indent new-loc)
5192 (save-match-data
5193 ;; Look for a list item on current or previous non-blank line
5194 (save-excursion
5195 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
5196 (not (bobp))
5197 (markdown-cur-line-blank-p))
5198 (forward-line -1)))
5199 (when bounds
5200 (cond ((save-excursion
5201 (skip-chars-backward " \t")
5202 (looking-at-p markdown-regex-list))
5203 (beginning-of-line)
5204 (insert "\n")
5205 (forward-line -1))
5206 ((not (markdown-cur-line-blank-p))
5207 (newline)))
5208 (setq new-loc (point)))
5209 ;; Look ahead for a list item on next non-blank line
5210 (unless bounds
5211 (save-excursion
5212 (while (and (null bounds)
5213 (not (eobp))
5214 (markdown-cur-line-blank-p))
5215 (forward-line)
5216 (setq bounds (markdown-cur-list-item-bounds))))
5217 (when bounds
5218 (setq new-loc (point))
5219 (unless (markdown-cur-line-blank-p)
5220 (newline))))
5221 (if (not bounds)
5222 ;; When not in a list, start a new unordered one
5223 (progn
5224 (unless (markdown-cur-line-blank-p)
5225 (insert "\n"))
5226 (insert markdown-unordered-list-item-prefix))
5227 ;; Compute indentation and marker for new list item
5228 (setq cur-indent (nth 2 bounds))
5229 (setq marker (nth 4 bounds))
5230 (cond
5231 ;; Dedent: decrement indentation, find previous marker.
5232 ((= arg 4)
5233 (setq indent (max (- cur-indent 4) 0))
5234 (let ((prev-bounds
5235 (save-excursion
5236 (when (markdown-prev-list-item (- (nth 3 bounds) 1))
5237 (markdown-cur-list-item-bounds)))))
5238 (when prev-bounds
5239 (setq marker (nth 4 prev-bounds)))))
5240 ;; Indent: increment indentation by 4, use same marker.
5241 ((= arg 16) (setq indent (+ cur-indent 4)))
5242 ;; Same level: keep current indentation and marker.
5243 (t (setq indent cur-indent)))
5244 (setq new-indent (make-string indent 32))
5245 (goto-char new-loc)
5246 (cond
5247 ;; Ordered list
5248 ((string-match-p "[0-9]" marker)
5249 (if (= arg 16) ;; starting a new column indented one more level
5250 (insert (concat new-indent "1. "))
5251 ;; Don't use previous match-data
5252 (set-match-data nil)
5253 ;; travel up to the last item and pick the correct number. If
5254 ;; the argument was nil, "new-indent = cur-indent" is the same,
5255 ;; so we don't need special treatment. Neat.
5256 (save-excursion
5257 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
5258 (>= (forward-line -1) 0))))
5259 (let* ((old-prefix (match-string 1))
5260 (old-spacing (match-string 2))
5261 (new-prefix (if old-prefix
5262 (int-to-string (1+ (string-to-number old-prefix)))
5263 "1"))
5264 (space-adjust (- (length old-prefix) (length new-prefix)))
5265 (new-spacing (if (and (match-string 2)
5266 (not (string-match-p "\t" old-spacing))
5267 (< space-adjust 0)
5268 (> space-adjust (- 1 (length (match-string 2)))))
5269 (substring (match-string 2) 0 space-adjust)
5270 (or old-spacing ". "))))
5271 (insert (concat new-indent new-prefix new-spacing)))))
5272 ;; Unordered list, or ordered list with hash mark
5273 ((string-match-p "[\\*\\+-]\\|#\\." marker)
5274 (insert new-indent marker)))))))
5276 (defun markdown-move-list-item-up ()
5277 "Move the current list item up in the list when possible."
5278 (interactive)
5279 (let (cur prev old)
5280 (when (setq cur (markdown-cur-list-item-bounds))
5281 (setq old (point))
5282 (goto-char (nth 0 cur))
5283 (if (markdown-prev-list-item (nth 3 cur))
5284 (progn
5285 (setq prev (markdown-cur-list-item-bounds))
5286 (condition-case nil
5287 (progn
5288 (transpose-regions (nth 0 prev) (nth 1 prev)
5289 (nth 0 cur) (nth 1 cur) t)
5290 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
5291 ;; Catch error in case regions overlap.
5292 (error (goto-char old))))
5293 (goto-char old)))))
5295 (defun markdown-move-list-item-down ()
5296 "Move the current list item down in the list when possible."
5297 (interactive)
5298 (let (cur next old)
5299 (when (setq cur (markdown-cur-list-item-bounds))
5300 (setq old (point))
5301 (if (markdown-next-list-item (nth 3 cur))
5302 (progn
5303 (setq next (markdown-cur-list-item-bounds))
5304 (condition-case nil
5305 (progn
5306 (transpose-regions (nth 0 cur) (nth 1 cur)
5307 (nth 0 next) (nth 1 next) nil)
5308 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
5309 ;; Catch error in case regions overlap.
5310 (error (goto-char old))))
5311 (goto-char old)))))
5313 (defun markdown-demote-list-item (&optional bounds)
5314 "Indent (or demote) the current list item.
5315 Optionally, BOUNDS of the current list item may be provided if available."
5316 (interactive)
5317 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
5318 (save-excursion
5319 (let ((end-marker (set-marker (make-marker) (nth 1 bounds))))
5320 (goto-char (nth 0 bounds))
5321 (while (< (point) end-marker)
5322 (unless (markdown-cur-line-blank-p)
5323 (insert (make-string markdown-list-indent-width ? )))
5324 (forward-line))))))
5326 (defun markdown-promote-list-item (&optional bounds)
5327 "Unindent (or promote) the current list item.
5328 Optionally, BOUNDS of the current list item may be provided if available."
5329 (interactive)
5330 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
5331 (save-excursion
5332 (save-match-data
5333 (let ((end-marker (set-marker (make-marker) (nth 1 bounds)))
5334 num regexp)
5335 (goto-char (nth 0 bounds))
5336 (when (looking-at (format "^[ ]\\{1,%d\\}"
5337 markdown-list-indent-width))
5338 (setq num (- (match-end 0) (match-beginning 0)))
5339 (setq regexp (format "^[ ]\\{1,%d\\}" num))
5340 (while (and (< (point) end-marker)
5341 (re-search-forward regexp end-marker t))
5342 (replace-match "" nil nil)
5343 (forward-line))))))))
5345 (defun markdown-cleanup-list-numbers-level (&optional pfx)
5346 "Update the numbering for level PFX (as a string of spaces).
5348 Assume that the previously found match was for a numbered item in
5349 a list."
5350 (let ((cpfx pfx)
5351 (idx 0)
5352 (continue t)
5353 (step t)
5354 (sep nil))
5355 (while (and continue (not (eobp)))
5356 (setq step t)
5357 (cond
5358 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
5359 (setq cpfx (match-string-no-properties 1))
5360 (cond
5361 ((string= cpfx pfx)
5362 (save-excursion
5363 (replace-match
5364 (concat pfx (number-to-string (setq idx (1+ idx))) ". ")))
5365 (setq sep nil))
5366 ;; indented a level
5367 ((string< pfx cpfx)
5368 (setq sep (markdown-cleanup-list-numbers-level cpfx))
5369 (setq step nil))
5370 ;; exit the loop
5372 (setq step nil)
5373 (setq continue nil))))
5375 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
5376 (setq cpfx (match-string-no-properties 1))
5377 (cond
5378 ;; reset if separated before
5379 ((string= cpfx pfx) (when sep (setq idx 0)))
5380 ((string< cpfx pfx)
5381 (setq step nil)
5382 (setq continue nil))))
5383 (t (setq sep t)))
5385 (when step
5386 (beginning-of-line)
5387 (setq continue (= (forward-line) 0))))
5388 sep))
5390 (defun markdown-cleanup-list-numbers ()
5391 "Update the numbering of ordered lists."
5392 (interactive)
5393 (save-excursion
5394 (goto-char (point-min))
5395 (markdown-cleanup-list-numbers-level "")))
5398 ;;; Movement ==================================================================
5400 (defun markdown-beginning-of-defun (&optional arg)
5401 "`beginning-of-defun-function' for Markdown.
5402 Move backward to the beginning of the current or previous section.
5403 When ARG is non-nil, repeat that many times. When ARG is negative,
5404 move forward to the ARG-th following section."
5405 (interactive "P")
5406 (or arg (setq arg 1))
5407 (forward-char 1)
5408 (or (re-search-backward markdown-regex-header nil t arg)
5409 (goto-char (point-min))))
5411 (defun markdown-end-of-defun (&optional arg)
5412 "`end-of-defun-function' for Markdown.
5413 Move forward to the end of the current or following section.
5414 When ARG is non-nil, repeat that many times. When ARG is negative,
5415 move back to the ARG-th preceding section."
5416 (interactive "P")
5417 (or arg (setq arg 1))
5418 (when (looking-at markdown-regex-header)
5419 (goto-char (match-beginning 0))
5420 (forward-char 1))
5421 (if (re-search-forward markdown-regex-header nil t arg)
5422 (goto-char (match-beginning 0))
5423 (goto-char (point-max)))
5424 (skip-syntax-backward "-"))
5426 (make-obsolete 'markdown-beginning-of-block 'markdown-beginning-of-text-block "2017-05-18")
5428 (defun markdown-beginning-of-text-block ()
5429 "Move backward to previous beginning of a plain text block.
5430 This function simply looks for blank lines without considering
5431 the surrounding context in light of Markdown syntax. For that, see
5432 `markdown-beginning-of-block-element'."
5433 (let ((start (point)))
5434 (if (re-search-backward markdown-regex-block-separator nil t)
5435 (goto-char (match-end 0))
5436 (goto-char (point-min)))
5437 (when (and (= start (point)) (not (bobp)))
5438 (forward-line -1)
5439 (if (re-search-backward markdown-regex-block-separator nil t)
5440 (goto-char (match-end 0))
5441 (goto-char (point-min))))))
5443 (make-obsolete 'markdown-end-of-block 'markdown-end-of-text-block "2017-05-18")
5445 (defun markdown-end-of-text-block ()
5446 "Move forward to next beginning of a plain text block.
5447 This function simply looks for blank lines without considering
5448 the surrounding context in light of Markdown syntax. For that, see
5449 `markdown-end-of-block-element'."
5450 (beginning-of-line)
5451 (skip-syntax-forward "-")
5452 (when (= (point) (point-min))
5453 (forward-char))
5454 (if (re-search-forward markdown-regex-block-separator nil t)
5455 (goto-char (match-end 0))
5456 (goto-char (point-max)))
5457 (skip-syntax-backward "-")
5458 (forward-line))
5460 (defun markdown-end-of-block-element ()
5461 "Move the point to the start of the next block unit.
5462 Stops at blank lines, list items, headers, and horizontal rules."
5463 (interactive)
5464 (forward-line)
5465 (while (and (or (not (markdown-prev-line-blank-p))
5466 (markdown-cur-line-blank-p))
5467 (not (or (looking-at-p markdown-regex-list)
5468 (looking-at-p markdown-regex-header)
5469 (looking-at-p markdown-regex-hr)))
5470 (not (eobp)))
5471 (forward-line)))
5473 (defun markdown-next-link ()
5474 "Jump to next inline, reference, or wiki link.
5475 If successful, return point. Otherwise, return nil.
5476 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
5477 (interactive)
5478 (let ((opoint (point)))
5479 (when (or (markdown-link-p) (markdown-wiki-link-p))
5480 ;; At a link already, move past it.
5481 (goto-char (+ (match-end 0) 1)))
5482 ;; Search for the next wiki link and move to the beginning.
5483 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t)
5484 (markdown-code-block-at-point-p)
5485 (< (point) (point-max))))
5486 (if (and (not (eq (point) opoint))
5487 (or (markdown-link-p) (markdown-wiki-link-p)))
5488 ;; Group 1 will move past non-escape character in wiki link regexp.
5489 ;; Go to beginning of group zero for all other link types.
5490 (goto-char (or (match-beginning 1) (match-beginning 0)))
5491 (goto-char opoint)
5492 nil)))
5494 (defun markdown-previous-link ()
5495 "Jump to previous wiki link.
5496 If successful, return point. Otherwise, return nil.
5497 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
5498 (interactive)
5499 (let ((opoint (point)))
5500 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t)
5501 (markdown-code-block-at-point-p)
5502 (> (point) (point-min))))
5503 (if (and (not (eq (point) opoint))
5504 (or (markdown-link-p) (markdown-wiki-link-p)))
5505 (goto-char (or (match-beginning 1) (match-beginning 0)))
5506 (goto-char opoint)
5507 nil)))
5510 ;;; Outline ===================================================================
5512 (defun markdown-move-heading-common (move-fn &optional arg)
5513 "Wrapper for `outline-mode' functions to skip false positives.
5514 MOVE-FN is a function and ARG is its argument. For example,
5515 headings inside preformatted code blocks may match
5516 `outline-regexp' but should not be considered as headings."
5517 (let ((prev -1) (start (point)))
5518 (if arg (funcall move-fn arg) (funcall move-fn))
5519 (while (and (/= prev (point)) (markdown-code-block-at-point-p))
5520 (setq prev (point))
5521 (if arg (funcall move-fn arg) (funcall move-fn)))
5522 (if (= (point) start) nil (point))))
5524 (defun markdown-next-visible-heading (arg)
5525 "Move to the next visible heading line of any level.
5526 With argument, repeats or can move backward if negative. ARG is
5527 passed to `outline-next-visible-heading'."
5528 (interactive "p")
5529 (markdown-move-heading-common 'outline-next-visible-heading arg))
5531 (defun markdown-previous-visible-heading (arg)
5532 "Move to the previous visible heading line of any level.
5533 With argument, repeats or can move backward if negative. ARG is
5534 passed to `outline-previous-visible-heading'."
5535 (interactive "p")
5536 (markdown-move-heading-common 'outline-previous-visible-heading arg))
5538 (defun markdown-next-heading ()
5539 "Move to the next heading line of any level."
5540 (markdown-move-heading-common 'outline-next-heading))
5542 (defun markdown-previous-heading ()
5543 "Move to the previous heading line of any level."
5544 (markdown-move-heading-common 'outline-previous-heading))
5546 (defun markdown-forward-same-level (arg)
5547 "Move forward to the ARG'th heading at same level as this one.
5548 Stop at the first and last headings of a superior heading."
5549 (interactive "p")
5550 (markdown-move-heading-common 'outline-forward-same-level arg))
5552 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok)
5553 (beginning-of-line)
5554 (or (and (outline-on-heading-p invisible-ok)
5555 (not (markdown-code-block-at-point-p)))
5556 (let ((header-re (concat "^\\(?:" outline-regexp "\\)"))
5557 found)
5558 (save-excursion
5559 (while (not found)
5560 (let (finish)
5561 (while (and (not finish) (re-search-backward header-re nil t))
5562 (when (and (or invisible-ok (not (outline-invisible-p)))
5563 (not (markdown-code-block-at-point-p)))
5564 (setq finish t)))
5565 (if (not finish)
5566 (error "Before first heading")
5567 (setq found (point))))))
5568 (goto-char found)
5569 found)))
5571 (defun markdown-backward-same-level (arg)
5572 "Move backward to the ARG'th heading at same level as this one.
5573 Stop at the first and last headings of a superior heading."
5574 (interactive "p")
5575 (markdown-back-to-heading-over-code-block)
5576 (while (> arg 0)
5577 (let ((point-to-move-to (save-excursion
5578 (outline-get-last-sibling))))
5579 (if point-to-move-to
5580 (progn
5581 (goto-char point-to-move-to)
5582 (setq arg (1- arg)))
5583 (error "No previous same-level heading")))))
5585 (defun markdown-up-heading (arg)
5586 "Move to the visible heading line of which the present line is a subheading.
5587 With argument, move up ARG levels."
5588 (interactive "p")
5589 (and (called-interactively-p 'any)
5590 (not (eq last-command 'markdown-up-heading)) (push-mark))
5591 (markdown-move-heading-common 'outline-up-heading arg))
5593 (defun markdown-back-to-heading (&optional invisible-ok)
5594 "Move to previous heading line, or beg of this line if it's a heading.
5595 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
5596 (markdown-move-heading-common 'outline-back-to-heading invisible-ok))
5598 (defalias 'markdown-end-of-heading 'outline-end-of-heading)
5600 (defun markdown-on-heading-p ()
5601 "Return t if point is on a (visible) heading line."
5602 (get-text-property (point) 'markdown-heading))
5604 (defun markdown-end-of-subtree (&optional invisible-OK)
5605 "Move to the end of the current subtree.
5606 Only visible heading lines are considered, unless INVISIBLE-OK is
5607 non-nil.
5608 Derived from `org-end-of-subtree'."
5609 (markdown-back-to-heading invisible-OK)
5610 (let ((first t)
5611 (level (markdown-outline-level)))
5612 (while (and (not (eobp))
5613 (or first (> (markdown-outline-level) level)))
5614 (setq first nil)
5615 (markdown-next-heading))
5616 (if (memq (preceding-char) '(?\n ?\^M))
5617 (progn
5618 ;; Go to end of line before heading
5619 (forward-char -1)
5620 (if (memq (preceding-char) '(?\n ?\^M))
5621 ;; leave blank line before heading
5622 (forward-char -1)))))
5623 (point))
5625 (defun markdown-outline-fix-visibility ()
5626 "Hide any false positive headings that should not be shown.
5627 For example, headings inside preformatted code blocks may match
5628 `outline-regexp' but should not be shown as headings when cycling.
5629 Also, the ending --- line in metadata blocks appears to be a
5630 setext header, but should not be folded."
5631 (save-excursion
5632 (goto-char (point-min))
5633 ;; Unhide any false positives in metadata blocks
5634 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin)
5635 (let ((body (progn (forward-line)
5636 (markdown-text-property-at-point
5637 'markdown-yaml-metadata-section))))
5638 (when body
5639 (let ((end (progn (goto-char (cl-second body))
5640 (markdown-text-property-at-point
5641 'markdown-yaml-metadata-end))))
5642 (outline-flag-region (point-min) (1+ (cl-second end)) nil)))))
5643 ;; Hide any false positives in code blocks
5644 (unless (outline-on-heading-p)
5645 (outline-next-visible-heading 1))
5646 (while (< (point) (point-max))
5647 (when (markdown-code-block-at-point-p)
5648 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t))
5649 (outline-next-visible-heading 1))))
5651 (defvar markdown-cycle-global-status 1)
5652 (defvar markdown-cycle-subtree-status nil)
5654 (defun markdown-next-preface ()
5655 (let (finish)
5656 (while (and (not finish) (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
5657 nil 'move))
5658 (unless (markdown-code-block-at-point-p)
5659 (goto-char (match-beginning 0))
5660 (setq finish t))))
5661 (when (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
5662 (forward-char -1)))
5664 (defun markdown-show-entry ()
5665 (save-excursion
5666 (outline-back-to-heading t)
5667 (outline-flag-region (1- (point))
5668 (progn
5669 (markdown-next-preface)
5670 (if (= 1 (- (point-max) (point)))
5671 (point-max)
5672 (point)))
5673 nil)))
5675 (defun markdown-cycle (&optional arg)
5676 "Visibility cycling for Markdown mode.
5677 If ARG is t, perform global visibility cycling. If the point is
5678 at an atx-style header, cycle visibility of the corresponding
5679 subtree. Otherwise, insert a tab using `indent-relative'.
5680 Derived from `org-cycle'."
5681 (interactive "P")
5682 (cond
5683 ((eq arg t) ;; Global cycling
5684 (cond
5685 ((and (eq last-command this-command)
5686 (eq markdown-cycle-global-status 2))
5687 ;; Move from overview to contents
5688 (markdown-hide-sublevels 1)
5689 (message "CONTENTS")
5690 (setq markdown-cycle-global-status 3)
5691 (markdown-outline-fix-visibility))
5693 ((and (eq last-command this-command)
5694 (eq markdown-cycle-global-status 3))
5695 ;; Move from contents to all
5696 (markdown-show-all)
5697 (message "SHOW ALL")
5698 (setq markdown-cycle-global-status 1))
5701 ;; Defaults to overview
5702 (markdown-hide-body)
5703 (message "OVERVIEW")
5704 (setq markdown-cycle-global-status 2)
5705 (markdown-outline-fix-visibility))))
5707 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
5708 ;; At a heading: rotate between three different views
5709 (markdown-back-to-heading)
5710 (let ((goal-column 0) eoh eol eos)
5711 ;; Determine boundaries
5712 (save-excursion
5713 (markdown-back-to-heading)
5714 (save-excursion
5715 (beginning-of-line 2)
5716 (while (and (not (eobp)) ;; this is like `next-line'
5717 (get-char-property (1- (point)) 'invisible))
5718 (beginning-of-line 2)) (setq eol (point)))
5719 (markdown-end-of-heading) (setq eoh (point))
5720 (markdown-end-of-subtree t)
5721 (skip-chars-forward " \t\n")
5722 (beginning-of-line 1) ; in case this is an item
5723 (setq eos (1- (point))))
5724 ;; Find out what to do next and set `this-command'
5725 (cond
5726 ((= eos eoh)
5727 ;; Nothing is hidden behind this heading
5728 (message "EMPTY ENTRY")
5729 (setq markdown-cycle-subtree-status nil))
5730 ((>= eol eos)
5731 ;; Entire subtree is hidden in one line: open it
5732 (markdown-show-entry)
5733 (markdown-show-children)
5734 (message "CHILDREN")
5735 (setq markdown-cycle-subtree-status 'children))
5736 ((and (eq last-command this-command)
5737 (eq markdown-cycle-subtree-status 'children))
5738 ;; We just showed the children, now show everything.
5739 (markdown-show-subtree)
5740 (message "SUBTREE")
5741 (setq markdown-cycle-subtree-status 'subtree))
5743 ;; Default action: hide the subtree.
5744 (markdown-hide-subtree)
5745 (message "FOLDED")
5746 (setq markdown-cycle-subtree-status 'folded)))))
5749 (indent-for-tab-command))))
5751 (defun markdown-shifttab ()
5752 "Global visibility cycling.
5753 Calls `markdown-cycle' with argument t."
5754 (interactive)
5755 (markdown-cycle t))
5757 (defun markdown-outline-level ()
5758 "Return the depth to which a statement is nested in the outline."
5759 (cond
5760 ((markdown-code-block-at-point-p) 7) ;; Only 6 header levels are defined.
5761 ((match-end 2) 1)
5762 ((match-end 3) 2)
5763 ((match-end 4) (- (match-end 4) (match-beginning 4)))))
5765 (defun markdown-promote-subtree (&optional arg)
5766 "Promote the current subtree of ATX headings.
5767 Note that Markdown does not support heading levels higher than
5768 six and therefore level-six headings will not be promoted
5769 further. If ARG is non-nil promote the heading, otherwise
5770 demote."
5771 (interactive "*P")
5772 (save-excursion
5773 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
5774 (re-search-backward markdown-regex-header-atx nil t))
5775 (not (markdown-code-block-at-point-p)))
5776 (let ((level (length (match-string 1)))
5777 (promote-or-demote (if arg 1 -1))
5778 (remove 't))
5779 (markdown-cycle-atx promote-or-demote remove)
5780 (catch 'end-of-subtree
5781 (while (markdown-next-heading)
5782 ;; Exit if this not a higher level heading; promote otherwise.
5783 (if (and (looking-at markdown-regex-header-atx)
5784 (<= (length (match-string-no-properties 1)) level))
5785 (throw 'end-of-subtree nil)
5786 (markdown-cycle-atx promote-or-demote remove))))))))
5788 (defun markdown-demote-subtree ()
5789 "Demote the current subtree of ATX headings."
5790 (interactive)
5791 (markdown-promote-subtree t))
5793 (defun markdown-move-subtree-up ()
5794 "Move the current subtree of ATX headings up."
5795 (interactive)
5796 (outline-move-subtree-up 1))
5798 (defun markdown-move-subtree-down ()
5799 "Move the current subtree of ATX headings down."
5800 (interactive)
5801 (outline-move-subtree-down 1))
5804 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
5806 (defun markdown-move-up ()
5807 "Move list item up.
5808 Calls `markdown-move-list-item-up'."
5809 (interactive)
5810 (markdown-move-list-item-up))
5812 (defun markdown-move-down ()
5813 "Move list item down.
5814 Calls `markdown-move-list-item-down'."
5815 (interactive)
5816 (markdown-move-list-item-down))
5818 (defun markdown-promote ()
5819 "Either promote header or list item at point or cycle markup.
5820 See `markdown-cycle-atx', `markdown-cycle-setext', and
5821 `markdown-promote-list-item'."
5822 (interactive)
5823 (let (bounds)
5824 (cond
5825 ;; Promote atx header
5826 ((thing-at-point-looking-at markdown-regex-header-atx)
5827 (markdown-cycle-atx -1))
5828 ;; Promote setext header
5829 ((thing-at-point-looking-at markdown-regex-header-setext)
5830 (markdown-cycle-setext -1))
5831 ;; Promote horizonal rule
5832 ((thing-at-point-looking-at markdown-regex-hr)
5833 (markdown-cycle-hr -1))
5834 ;; Promote list item
5835 ((setq bounds (markdown-cur-list-item-bounds))
5836 (markdown-promote-list-item bounds))
5837 ;; Promote bold
5838 ((thing-at-point-looking-at markdown-regex-bold)
5839 (markdown-cycle-bold))
5840 ;; Promote italic
5841 ((thing-at-point-looking-at markdown-regex-italic)
5842 (markdown-cycle-italic))
5844 (error "Nothing to promote at point")))))
5846 (defun markdown-demote ()
5847 "Either demote header or list item at point or cycle or remove markup.
5848 See `markdown-cycle-atx', `markdown-cycle-setext', and
5849 `markdown-demote-list-item'."
5850 (interactive)
5851 (let (bounds)
5852 (cond
5853 ;; Demote atx header
5854 ((thing-at-point-looking-at markdown-regex-header-atx)
5855 (markdown-cycle-atx 1))
5856 ;; Demote setext header
5857 ((thing-at-point-looking-at markdown-regex-header-setext)
5858 (markdown-cycle-setext 1))
5859 ;; Demote horizonal rule
5860 ((thing-at-point-looking-at markdown-regex-hr)
5861 (markdown-cycle-hr 1))
5862 ;; Demote list item
5863 ((setq bounds (markdown-cur-list-item-bounds))
5864 (markdown-demote-list-item bounds))
5865 ;; Demote bold
5866 ((thing-at-point-looking-at markdown-regex-bold)
5867 (markdown-cycle-bold))
5868 ;; Demote italic
5869 ((thing-at-point-looking-at markdown-regex-italic)
5870 (markdown-cycle-italic))
5872 (error "Nothing to demote at point")))))
5875 ;;; Commands ==================================================================
5877 (defun markdown (&optional output-buffer-name)
5878 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
5879 The output buffer name defaults to `markdown-output-buffer-name'.
5880 Return the name of the output buffer used."
5881 (interactive)
5882 (save-window-excursion
5883 (let ((begin-region)
5884 (end-region))
5885 (if (markdown-use-region-p)
5886 (setq begin-region (region-beginning)
5887 end-region (region-end))
5888 (setq begin-region (point-min)
5889 end-region (point-max)))
5891 (unless output-buffer-name
5892 (setq output-buffer-name markdown-output-buffer-name))
5893 (cond
5894 ;; Handle case when `markdown-command' does not read from stdin
5895 (markdown-command-needs-filename
5896 (if (not buffer-file-name)
5897 (error "Must be visiting a file")
5898 (shell-command (concat markdown-command " "
5899 (shell-quote-argument buffer-file-name))
5900 output-buffer-name)))
5901 ;; Pass region to `markdown-command' via stdin
5903 (let ((buf (get-buffer-create output-buffer-name)))
5904 (with-current-buffer buf
5905 (setq buffer-read-only nil)
5906 (erase-buffer))
5907 (call-process-region begin-region end-region
5908 shell-file-name nil buf nil
5909 shell-command-switch markdown-command)))))
5910 output-buffer-name))
5912 (defun markdown-standalone (&optional output-buffer-name)
5913 "Special function to provide standalone HTML output.
5914 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
5915 (interactive)
5916 (setq output-buffer-name (markdown output-buffer-name))
5917 (with-current-buffer output-buffer-name
5918 (set-buffer output-buffer-name)
5919 (unless (markdown-output-standalone-p)
5920 (markdown-add-xhtml-header-and-footer output-buffer-name))
5921 (goto-char (point-min))
5922 (html-mode))
5923 output-buffer-name)
5925 (defun markdown-other-window (&optional output-buffer-name)
5926 "Run `markdown-command' on current buffer and display in other window.
5927 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
5928 that name."
5929 (interactive)
5930 (markdown-display-buffer-other-window
5931 (markdown-standalone output-buffer-name)))
5933 (defun markdown-output-standalone-p ()
5934 "Determine whether `markdown-command' output is standalone XHTML.
5935 Standalone XHTML output is identified by an occurrence of
5936 `markdown-xhtml-standalone-regexp' in the first five lines of output."
5937 (save-excursion
5938 (goto-char (point-min))
5939 (re-search-forward
5940 markdown-xhtml-standalone-regexp
5941 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
5942 t)))
5944 (defun markdown-stylesheet-link-string (stylesheet-path)
5945 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
5946 stylesheet-path
5947 "\" />"))
5949 (defun markdown-add-xhtml-header-and-footer (title)
5950 "Wrap XHTML header and footer with given TITLE around current buffer."
5951 (goto-char (point-min))
5952 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
5953 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
5954 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
5955 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
5956 "<head>\n<title>")
5957 (insert title)
5958 (insert "</title>\n")
5959 (when (> (length markdown-content-type) 0)
5960 (insert
5961 (format
5962 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
5963 markdown-content-type
5964 (or (and markdown-coding-system
5965 (fboundp 'coding-system-get)
5966 (coding-system-get markdown-coding-system
5967 'mime-charset))
5968 (and (fboundp 'coding-system-get)
5969 (coding-system-get buffer-file-coding-system
5970 'mime-charset))
5971 "iso-8859-1"))))
5972 (if (> (length markdown-css-paths) 0)
5973 (insert (mapconcat #'markdown-stylesheet-link-string
5974 markdown-css-paths "\n")))
5975 (when (> (length markdown-xhtml-header-content) 0)
5976 (insert markdown-xhtml-header-content))
5977 (insert "\n</head>\n\n"
5978 "<body>\n\n")
5979 (goto-char (point-max))
5980 (insert "\n"
5981 "</body>\n"
5982 "</html>\n"))
5984 (defun markdown-preview (&optional output-buffer-name)
5985 "Run `markdown-command' on the current buffer and view output in browser.
5986 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
5987 that name."
5988 (interactive)
5989 (browse-url-of-buffer
5990 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
5992 (defun markdown-export-file-name (&optional extension)
5993 "Attempt to generate a filename for Markdown output.
5994 The file extension will be EXTENSION if given, or .html by default.
5995 If the current buffer is visiting a file, we construct a new
5996 output filename based on that filename. Otherwise, return nil."
5997 (when (buffer-file-name)
5998 (unless extension
5999 (setq extension ".html"))
6000 (let ((candidate
6001 (concat
6002 (cond
6003 ((buffer-file-name)
6004 (file-name-sans-extension (buffer-file-name)))
6005 (t (buffer-name)))
6006 extension)))
6007 (cond
6008 ((equal candidate (buffer-file-name))
6009 (concat candidate extension))
6011 candidate)))))
6013 (defun markdown-export (&optional output-file)
6014 "Run Markdown on the current buffer, save to file, and return the filename.
6015 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
6016 generated by `markdown-export-file-name', which will be constructed using the
6017 current filename, but with the extension removed and replaced with .html."
6018 (interactive)
6019 (unless output-file
6020 (setq output-file (markdown-export-file-name ".html")))
6021 (when output-file
6022 (let* ((init-buf (current-buffer))
6023 (init-point (point))
6024 (init-buf-string (buffer-string))
6025 (output-buffer (find-file-noselect output-file))
6026 (output-buffer-name (buffer-name output-buffer)))
6027 (run-hooks 'markdown-before-export-hook)
6028 (markdown-standalone output-buffer-name)
6029 (with-current-buffer output-buffer
6030 (run-hooks 'markdown-after-export-hook)
6031 (save-buffer))
6032 ;; if modified, restore initial buffer
6033 (when (buffer-modified-p init-buf)
6034 (erase-buffer)
6035 (insert init-buf-string)
6036 (save-buffer)
6037 (goto-char init-point))
6038 output-file)))
6040 (defun markdown-export-and-preview ()
6041 "Export to XHTML using `markdown-export' and browse the resulting file."
6042 (interactive)
6043 (browse-url-of-file (markdown-export)))
6045 (defvar markdown-live-preview-buffer nil
6046 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
6047 (make-variable-buffer-local 'markdown-live-preview-buffer)
6049 (defvar markdown-live-preview-source-buffer nil
6050 "Source buffer from which current buffer was generated.
6051 This is the inverse of `markdown-live-preview-buffer'.")
6052 (make-variable-buffer-local 'markdown-live-preview-source-buffer)
6054 (defvar markdown-live-preview-currently-exporting nil)
6056 (defun markdown-live-preview-get-filename ()
6057 "Standardize the filename exported by `markdown-live-preview-export'."
6058 (markdown-export-file-name ".html"))
6060 (defun markdown-live-preview-window-eww (file)
6061 "Preview FILE with eww.
6062 To be used with `markdown-live-preview-window-function'."
6063 (if (require 'eww nil t)
6064 (progn
6065 (eww-open-file file)
6066 (get-buffer "*eww*"))
6067 (error "EWW is not present or not loaded on this version of Emacs")))
6069 (defun markdown-visual-lines-between-points (beg end)
6070 (save-excursion
6071 (goto-char beg)
6072 (cl-loop with count = 0
6073 while (progn (end-of-visual-line)
6074 (and (< (point) end) (line-move-visual 1 t)))
6075 do (cl-incf count)
6076 finally return count)))
6078 (defun markdown-live-preview-window-serialize (buf)
6079 "Get window point and scroll data for all windows displaying BUF."
6080 (when (buffer-live-p buf)
6081 (with-current-buffer buf
6082 (mapcar
6083 (lambda (win)
6084 (with-selected-window win
6085 (let* ((start (window-start))
6086 (pt (window-point))
6087 (pt-or-sym (cond ((= pt (point-min)) 'min)
6088 ((= pt (point-max)) 'max)
6089 (t pt)))
6090 (diff (markdown-visual-lines-between-points
6091 start pt)))
6092 (list win pt-or-sym diff))))
6093 (get-buffer-window-list buf)))))
6095 (defun markdown-get-point-back-lines (pt num-lines)
6096 (save-excursion
6097 (goto-char pt)
6098 (line-move-visual (- num-lines) t)
6099 ;; in testing, can occasionally overshoot the number of lines to traverse
6100 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
6101 (when (> actual-num-lines num-lines)
6102 (line-move-visual (- actual-num-lines num-lines) t)))
6103 (point)))
6105 (defun markdown-live-preview-window-deserialize (window-posns)
6106 "Apply window point and scroll data from WINDOW-POSNS.
6107 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
6108 (cl-destructuring-bind (win pt-or-sym diff) window-posns
6109 (when (window-live-p win)
6110 (with-current-buffer markdown-live-preview-buffer
6111 (set-window-buffer win (current-buffer))
6112 (cl-destructuring-bind (actual-pt actual-diff)
6113 (cl-case pt-or-sym
6114 (min (list (point-min) 0))
6115 (max (list (point-max) diff))
6116 (t (list pt-or-sym diff)))
6117 (set-window-start
6118 win (markdown-get-point-back-lines actual-pt actual-diff))
6119 (set-window-point win actual-pt))))))
6121 (defun markdown-live-preview-export ()
6122 "Export to XHTML using `markdown-export'.
6123 Browse the resulting file within Emacs using
6124 `markdown-live-preview-window-function' Return the buffer
6125 displaying the rendered output."
6126 (interactive)
6127 (let* ((markdown-live-preview-currently-exporting t)
6128 (cur-buf (current-buffer))
6129 (export-file (markdown-export (markdown-live-preview-get-filename)))
6130 ;; get positions in all windows currently displaying output buffer
6131 (window-data
6132 (markdown-live-preview-window-serialize
6133 markdown-live-preview-buffer)))
6134 (save-window-excursion
6135 (let ((output-buffer
6136 (funcall markdown-live-preview-window-function export-file)))
6137 (with-current-buffer output-buffer
6138 (setq markdown-live-preview-source-buffer cur-buf)
6139 (add-hook 'kill-buffer-hook
6140 #'markdown-live-preview-remove-on-kill t t))
6141 (with-current-buffer cur-buf
6142 (setq markdown-live-preview-buffer output-buffer))))
6143 (with-current-buffer cur-buf
6144 ;; reset all windows displaying output buffer to where they were,
6145 ;; now with the new output
6146 (mapc #'markdown-live-preview-window-deserialize window-data)
6147 ;; delete html editing buffer
6148 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
6149 (when (and export-file (file-exists-p export-file)
6150 (eq markdown-live-preview-delete-export
6151 'delete-on-export))
6152 (delete-file export-file))
6153 markdown-live-preview-buffer)))
6155 (defun markdown-live-preview-remove ()
6156 (when (buffer-live-p markdown-live-preview-buffer)
6157 (kill-buffer markdown-live-preview-buffer))
6158 (setq markdown-live-preview-buffer nil)
6159 ;; if set to 'delete-on-export, the output has already been deleted
6160 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
6161 (let ((outfile-name (markdown-live-preview-get-filename)))
6162 (when (file-exists-p outfile-name)
6163 (delete-file outfile-name)))))
6165 (defun markdown-display-buffer-other-window (buf)
6166 (let ((cur-buf (current-buffer))
6167 split-width-threshold split-height-threshold)
6168 (cond ((memq markdown-split-window-direction '(vertical below))
6169 (setq split-width-threshold nil)
6170 (setq split-height-threshold 0))
6171 ((memq markdown-split-window-direction '(horizontal right))
6172 (setq split-width-threshold 0)
6173 (setq split-height-threshold nil)))
6174 (switch-to-buffer-other-window buf)
6175 (set-buffer cur-buf)))
6177 (defun markdown-live-preview-if-markdown ()
6178 (when (and (derived-mode-p 'markdown-mode)
6179 markdown-live-preview-mode)
6180 (unless markdown-live-preview-currently-exporting
6181 (if (buffer-live-p markdown-live-preview-buffer)
6182 (markdown-live-preview-export)
6183 (markdown-display-buffer-other-window
6184 (markdown-live-preview-export))))))
6186 (defun markdown-live-preview-remove-on-kill ()
6187 (cond ((and (derived-mode-p 'markdown-mode)
6188 markdown-live-preview-mode)
6189 (markdown-live-preview-remove))
6190 (markdown-live-preview-source-buffer
6191 (with-current-buffer markdown-live-preview-source-buffer
6192 (setq markdown-live-preview-buffer nil))
6193 (setq markdown-live-preview-source-buffer nil))))
6195 (defun markdown-live-preview-switch-to-output ()
6196 "Switch to output buffer."
6197 (interactive)
6198 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
6199 output buffer in another window."
6200 (if markdown-live-preview-mode
6201 (markdown-display-buffer-other-window (markdown-live-preview-export)))
6202 (markdown-live-preview-mode))
6204 (defun markdown-live-preview-re-export ()
6205 "Re export source buffer."
6206 (interactive)
6207 "If the current buffer is a buffer displaying the exported version of a
6208 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
6209 update this buffer's contents."
6210 (when markdown-live-preview-source-buffer
6211 (with-current-buffer markdown-live-preview-source-buffer
6212 (markdown-live-preview-export))))
6214 (defun markdown-open ()
6215 "Open file for the current buffer with `markdown-open-command'."
6216 (interactive)
6217 (if (not markdown-open-command)
6218 (error "Variable `markdown-open-command' must be set")
6219 (if (not buffer-file-name)
6220 (error "Must be visiting a file")
6221 (call-process markdown-open-command
6222 nil nil nil buffer-file-name))))
6224 (defun markdown-kill-ring-save ()
6225 "Run Markdown on file and store output in the kill ring."
6226 (interactive)
6227 (save-window-excursion
6228 (markdown)
6229 (with-current-buffer markdown-output-buffer-name
6230 (kill-ring-save (point-min) (point-max)))))
6233 ;;; Links =====================================================================
6235 (defun markdown-link-p ()
6236 "Return non-nil when `point' is at a non-wiki link.
6237 See `markdown-wiki-link-p' for more information."
6238 (let ((case-fold-search nil))
6239 (and (not (markdown-wiki-link-p))
6240 (not (markdown-code-block-at-point-p))
6241 (or (thing-at-point-looking-at markdown-regex-link-inline)
6242 (thing-at-point-looking-at markdown-regex-link-reference)
6243 (thing-at-point-looking-at markdown-regex-uri)
6244 (thing-at-point-looking-at markdown-regex-angle-uri)))))
6246 (defun markdown-link-link ()
6247 "Return the link part of the regular (non-wiki) link at point.
6248 Works with both inline and reference style links. If point is
6249 not at a link or the link reference is not defined returns nil."
6250 (cond
6251 ((thing-at-point-looking-at markdown-regex-link-inline)
6252 (match-string-no-properties 6))
6253 ((thing-at-point-looking-at markdown-regex-link-reference)
6254 (let* ((text (match-string-no-properties 3))
6255 (reference (match-string-no-properties 6))
6256 (target (downcase (if (string= reference "") text reference))))
6257 (car (markdown-reference-definition target))))
6258 ((thing-at-point-looking-at markdown-regex-uri)
6259 (match-string-no-properties 0))
6260 ((thing-at-point-looking-at markdown-regex-angle-uri)
6261 (match-string-no-properties 2))
6262 (t nil)))
6264 (defun markdown-follow-link-at-point ()
6265 "Open the current non-wiki link.
6266 If the link is a complete URL, open in browser with `browse-url'.
6267 Otherwise, open with `find-file' after stripping anchor and/or query string."
6268 (interactive)
6269 (if (markdown-link-p)
6270 (let* ((link (markdown-link-link))
6271 (struct (url-generic-parse-url link))
6272 (full (url-fullness struct))
6273 (file link))
6274 ;; Parse URL, determine fullness, strip query string
6275 (if (fboundp 'url-path-and-query)
6276 (setq file (car (url-path-and-query struct)))
6277 (when (and (setq file (url-filename struct))
6278 (string-match "\\?" file))
6279 (setq file (substring file 0 (match-beginning 0)))))
6280 ;; Open full URLs in browser, files in Emacs
6281 (if full
6282 (browse-url link)
6283 (when (and file (> (length file) 0)) (find-file file))))
6284 (error "Point is not at a Markdown link or URI")))
6287 ;;; WikiLink Following/Markup =================================================
6289 (defun markdown-wiki-link-p ()
6290 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
6291 A true wiki link name matches `markdown-regex-wiki-link' but does
6292 not match the current file name after conversion. This modifies
6293 the data returned by `match-data'. Note that the potential wiki
6294 link name must be available via `match-string'."
6295 (when markdown-enable-wiki-links
6296 (let ((case-fold-search nil))
6297 (and (thing-at-point-looking-at markdown-regex-wiki-link)
6298 (not (markdown-code-block-at-point-p))
6299 (or (not buffer-file-name)
6300 (not (string-equal (buffer-file-name)
6301 (markdown-convert-wiki-link-to-filename
6302 (markdown-wiki-link-link)))))))))
6304 (defun markdown-wiki-link-link ()
6305 "Return the link part of the wiki link using current match data.
6306 The location of the link component depends on the value of
6307 `markdown-wiki-link-alias-first'."
6308 (if markdown-wiki-link-alias-first
6309 (or (match-string-no-properties 5) (match-string-no-properties 3))
6310 (match-string-no-properties 3)))
6312 (defun markdown-wiki-link-alias ()
6313 "Return the alias or text part of the wiki link using current match data.
6314 The location of the alias component depends on the value of
6315 `markdown-wiki-link-alias-first'."
6316 (if markdown-wiki-link-alias-first
6317 (match-string-no-properties 3)
6318 (or (match-string-no-properties 5) (match-string-no-properties 3))))
6320 (defun markdown-convert-wiki-link-to-filename (name)
6321 "Generate a filename from the wiki link NAME.
6322 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
6323 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
6324 and [[test test]] both map to Test-test.ext. Look in the current
6325 directory first, then in subdirectories if
6326 `markdown-wiki-link-search-subdirectories' is non-nil, and then
6327 in parent directories if
6328 `markdown-wiki-link-search-parent-directories' is non-nil."
6329 (let* ((basename (markdown-replace-regexp-in-string
6330 "[[:space:]\n]" markdown-link-space-sub-char name))
6331 (basename (if (eq major-mode 'gfm-mode)
6332 (concat (upcase (substring basename 0 1))
6333 (downcase (substring basename 1 nil)))
6334 basename))
6335 directory extension default candidates dir)
6336 (when buffer-file-name
6337 (setq directory (file-name-directory buffer-file-name)
6338 extension (file-name-extension buffer-file-name)))
6339 (setq default (concat basename
6340 (when extension (concat "." extension))))
6341 (cond
6342 ;; Look in current directory first.
6343 ((or (null buffer-file-name)
6344 (file-exists-p default))
6345 default)
6346 ;; Possibly search in subdirectories, next.
6347 ((and markdown-wiki-link-search-subdirectories
6348 (setq candidates
6349 (markdown-directory-files-recursively
6350 directory (concat "^" default "$"))))
6351 (car candidates))
6352 ;; Possibly search in parent directories as a last resort.
6353 ((and markdown-wiki-link-search-parent-directories
6354 (setq dir (locate-dominating-file directory default)))
6355 (concat dir default))
6356 ;; If nothing is found, return default in current directory.
6357 (t default))))
6359 (defun markdown-follow-wiki-link (name &optional other)
6360 "Follow the wiki link NAME.
6361 Convert the name to a file name and call `find-file'. Ensure that
6362 the new buffer remains in `markdown-mode'. Open the link in another
6363 window when OTHER is non-nil."
6364 (let ((filename (markdown-convert-wiki-link-to-filename name))
6365 (wp (when buffer-file-name
6366 (file-name-directory buffer-file-name))))
6367 (if (not wp)
6368 (error "Must be visiting a file")
6369 (when other (other-window 1))
6370 (let ((default-directory wp))
6371 (find-file filename)))
6372 (when (not (eq major-mode 'markdown-mode))
6373 (markdown-mode))))
6375 (defun markdown-follow-wiki-link-at-point (&optional arg)
6376 "Find Wiki Link at point.
6377 With prefix argument ARG, open the file in other window.
6378 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
6379 (interactive "P")
6380 (if (markdown-wiki-link-p)
6381 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
6382 (error "Point is not at a Wiki Link")))
6384 (defun markdown-highlight-wiki-link (from to face)
6385 "Highlight the wiki link in the region between FROM and TO using FACE."
6386 (put-text-property from to 'font-lock-face face))
6388 (defun markdown-unfontify-region-wiki-links (from to)
6389 "Remove wiki link faces from the region specified by FROM and TO."
6390 (interactive "*r")
6391 (let ((modified (buffer-modified-p)))
6392 (remove-text-properties from to '(font-lock-face markdown-link-face))
6393 (remove-text-properties from to '(font-lock-face markdown-missing-link-face))
6394 ;; remove-text-properties marks the buffer modified in emacs 24.3,
6395 ;; undo that if it wasn't originally marked modified
6396 (set-buffer-modified-p modified)))
6398 (defun markdown-fontify-region-wiki-links (from to)
6399 "Search region given by FROM and TO for wiki links and fontify them.
6400 If a wiki link is found check to see if the backing file exists
6401 and highlight accordingly."
6402 (goto-char from)
6403 (save-match-data
6404 (while (re-search-forward markdown-regex-wiki-link to t)
6405 (when (not (markdown-code-block-at-point-p))
6406 (let ((highlight-beginning (match-beginning 1))
6407 (highlight-end (match-end 1))
6408 (file-name
6409 (markdown-convert-wiki-link-to-filename
6410 (markdown-wiki-link-link))))
6411 (if (condition-case nil (file-exists-p file-name) (error nil))
6412 (markdown-highlight-wiki-link
6413 highlight-beginning highlight-end markdown-link-face)
6414 (markdown-highlight-wiki-link
6415 highlight-beginning highlight-end markdown-missing-link-face)))))))
6417 (defun markdown-extend-changed-region (from to)
6418 "Extend region given by FROM and TO so that we can fontify all links.
6419 The region is extended to the first newline before and the first
6420 newline after."
6421 ;; start looking for the first new line before 'from
6422 (goto-char from)
6423 (re-search-backward "\n" nil t)
6424 (let ((new-from (point-min))
6425 (new-to (point-max)))
6426 (if (not (= (point) from))
6427 (setq new-from (point)))
6428 ;; do the same thing for the first new line after 'to
6429 (goto-char to)
6430 (re-search-forward "\n" nil t)
6431 (if (not (= (point) to))
6432 (setq new-to (point)))
6433 (cl-values new-from new-to)))
6435 (defun markdown-check-change-for-wiki-link (from to)
6436 "Check region between FROM and TO for wiki links and re-fontify as needed."
6437 (interactive "*r")
6438 (let* ((modified (buffer-modified-p))
6439 (buffer-undo-list t)
6440 (inhibit-read-only t)
6441 (inhibit-point-motion-hooks t)
6442 deactivate-mark
6443 buffer-file-truename)
6444 (unwind-protect
6445 (save-excursion
6446 (save-match-data
6447 (save-restriction
6448 ;; Extend the region to fontify so that it starts
6449 ;; and ends at safe places.
6450 (cl-multiple-value-bind (new-from new-to)
6451 (markdown-extend-changed-region from to)
6452 (goto-char new-from)
6453 ;; Only refontify when the range contains text with a
6454 ;; wiki link face or if the wiki link regexp matches.
6455 (when (or (markdown-range-property-any
6456 new-from new-to 'font-lock-face
6457 (list markdown-link-face
6458 markdown-missing-link-face))
6459 (re-search-forward
6460 markdown-regex-wiki-link new-to t))
6461 ;; Unfontify existing fontification (start from scratch)
6462 (markdown-unfontify-region-wiki-links new-from new-to)
6463 ;; Now do the fontification.
6464 (markdown-fontify-region-wiki-links new-from new-to))))))
6465 (and (not modified)
6466 (buffer-modified-p)
6467 (set-buffer-modified-p nil)))))
6469 (defun markdown-check-change-for-wiki-link-after-change (from to _)
6470 "Check region between FROM and TO for wiki links and re-fontify as needed.
6471 Designed to be used with the `after-change-functions' hook."
6472 (markdown-check-change-for-wiki-link from to))
6474 (defun markdown-fontify-buffer-wiki-links ()
6475 "Refontify all wiki links in the buffer."
6476 (interactive)
6477 (markdown-check-change-for-wiki-link (point-min) (point-max)))
6480 ;;; Following and Jumping =====================================================
6482 (defun markdown-follow-thing-at-point (arg)
6483 "Follow thing at point if possible, such as a reference link or wiki link.
6484 Opens inline and reference links in a browser. Opens wiki links
6485 to other files in the current window, or the another window if
6486 ARG is non-nil.
6487 See `markdown-follow-link-at-point' and
6488 `markdown-follow-wiki-link-at-point'."
6489 (interactive "P")
6490 (cond ((markdown-link-p)
6491 (markdown-follow-link-at-point))
6492 ((markdown-wiki-link-p)
6493 (markdown-follow-wiki-link-at-point arg))
6495 (error "Nothing to follow at point"))))
6497 (defun markdown-jump ()
6498 "Jump to another location based on context at point.
6499 Jumps between reference links and definitions; between footnote
6500 markers and footnote text."
6501 (interactive)
6502 (cond ((markdown-footnote-text-positions)
6503 (markdown-footnote-return))
6504 ((markdown-footnote-marker-positions)
6505 (markdown-footnote-goto-text))
6506 ((thing-at-point-looking-at markdown-regex-link-reference)
6507 (markdown-reference-goto-definition))
6508 ((thing-at-point-looking-at markdown-regex-reference-definition)
6509 (markdown-reference-goto-link (match-string-no-properties 2)))
6511 (error "Nothing to jump to from context at point"))))
6514 ;;; Miscellaneous =============================================================
6516 (defun markdown-compress-whitespace-string (str)
6517 "Compress whitespace in STR and return result.
6518 Leading and trailing whitespace is removed. Sequences of multiple
6519 spaces, tabs, and newlines are replaced with single spaces."
6520 (markdown-replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
6521 (markdown-replace-regexp-in-string "[ \t\n]+" " " str)))
6523 (defun markdown-line-number-at-pos (&optional pos)
6524 "Return (narrowed) buffer line number at position POS.
6525 If POS is nil, use current buffer location.
6526 This is an exact copy of `line-number-at-pos' for use in emacs21."
6527 (let ((opoint (or pos (point))) start)
6528 (save-excursion
6529 (goto-char (point-min))
6530 (setq start (point))
6531 (goto-char opoint)
6532 (forward-line 0)
6533 (1+ (count-lines start (point))))))
6535 (defun markdown-inside-link-p ()
6536 "Return t if point is within a link."
6537 (save-match-data
6538 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
6540 (defun markdown-line-is-reference-definition-p ()
6541 "Return whether the current line is a (non-footnote) reference defition."
6542 (save-excursion
6543 (move-beginning-of-line 1)
6544 (and (looking-at-p markdown-regex-reference-definition)
6545 (not (looking-at-p "[ \t]*\\[^")))))
6547 (defun markdown-adaptive-fill-function ()
6548 "Return prefix for filling paragraph or nil if not determined."
6549 (cond
6550 ;; List item inside blockquote
6551 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
6552 (markdown-replace-regexp-in-string
6553 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
6554 ;; Blockquote
6555 ((looking-at "^[ \t]*>[ \t]*")
6556 (match-string-no-properties 0))
6557 ;; List items
6558 ((looking-at markdown-regex-list)
6559 (match-string-no-properties 0))
6560 ((looking-at-p markdown-regex-footnote-definition)
6561 " ") ; four spaces
6562 ;; No match
6563 (t nil)))
6565 (defun markdown-fill-paragraph (&optional justify)
6566 "Fill paragraph at or after point.
6567 This function is like \\[fill-paragraph], but it skips Markdown
6568 code blocks. If the point is in a code block, or just before one,
6569 do not fill. Otherwise, call `fill-paragraph' as usual. If
6570 JUSTIFY is non-nil, justify text as well. Since this function
6571 handles filling itself, it always returns t so that
6572 `fill-paragraph' doesn't run."
6573 (interactive "P")
6574 (unless (or (markdown-code-block-at-point-p)
6575 (save-excursion
6576 (back-to-indentation)
6577 (skip-syntax-forward "-")
6578 (markdown-code-block-at-point-p)))
6579 (fill-paragraph justify))
6582 (defun markdown-fill-forward-paragraph-function (&optional arg)
6583 "Function used by `fill-paragraph' to move over ARG paragraphs.
6584 This is a `fill-forward-paragraph-function' for `markdown-mode'.
6585 It is called with a single argument specifying the number of
6586 paragraphs to move. Just like `forward-paragraph', it should
6587 return the number of paragraphs left to move."
6588 (let* ((arg (or arg 1))
6589 (paragraphs-remaining (forward-paragraph arg))
6590 (start (point)))
6591 (when (< arg 0)
6592 (while (and (not (eobp))
6593 (progn (move-to-left-margin) (not (eobp)))
6594 (looking-at-p paragraph-separate))
6595 (forward-line 1))
6596 (if (looking-at markdown-regex-list)
6597 (forward-char (length (match-string 0)))
6598 (goto-char start)))
6599 paragraphs-remaining))
6602 ;;; Extension Framework =======================================================
6604 (defun markdown-reload-extensions ()
6605 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
6606 (interactive)
6607 (when (eq major-mode 'markdown-mode)
6608 ;; Update font lock keywords with extensions
6609 (setq markdown-mode-font-lock-keywords
6610 (append
6611 (markdown-mode-font-lock-keywords-math)
6612 markdown-mode-font-lock-keywords-basic
6613 (markdown-mode-font-lock-keywords-wiki-links)))
6614 ;; Update font lock defaults
6615 (setq font-lock-defaults
6616 '(markdown-mode-font-lock-keywords
6617 nil nil nil nil
6618 (font-lock-syntactic-face-function . markdown-syntactic-face)))
6619 ;; Refontify buffer
6620 (when (and font-lock-mode (fboundp 'font-lock-refresh-defaults))
6621 (font-lock-refresh-defaults))
6623 ;; Add or remove hooks related to extensions
6624 (markdown-setup-wiki-link-hooks)))
6626 (defun markdown-handle-local-variables ()
6627 "Run in `hack-local-variables-hook' to update font lock rules.
6628 Checks to see if there is actually a ‘markdown-mode’ file local variable
6629 before regenerating font-lock rules for extensions."
6630 (when (and (boundp 'file-local-variables-alist)
6631 (assoc 'markdown-enable-wiki-links file-local-variables-alist)
6632 (assoc 'markdown-enable-math file-local-variables-alist))
6633 (markdown-reload-extensions)))
6636 ;;; Wiki Links ================================================================
6638 (defun markdown-toggle-wiki-links (&optional arg)
6639 "Toggle support for wiki links.
6640 With a prefix argument ARG, enable wiki link support if ARG is positive,
6641 and disable it otherwise."
6642 (interactive (list (or current-prefix-arg 'toggle)))
6643 (setq markdown-enable-wiki-links
6644 (if (eq arg 'toggle)
6645 (not markdown-enable-wiki-links)
6646 (> (prefix-numeric-value arg) 0)))
6647 (if markdown-enable-wiki-links
6648 (message "markdown-mode wiki link support enabled")
6649 (message "markdown-mode wiki link support disabled"))
6650 (markdown-reload-extensions))
6652 (defun markdown-setup-wiki-link-hooks ()
6653 "Add or remove hooks for fontifying wiki links.
6654 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
6655 ;; Anytime text changes make sure it gets fontified correctly
6656 (if (and markdown-enable-wiki-links
6657 markdown-wiki-link-fontify-missing)
6658 (add-hook 'after-change-functions
6659 'markdown-check-change-for-wiki-link-after-change t t)
6660 (remove-hook 'after-change-functions
6661 'markdown-check-change-for-wiki-link-after-change t))
6662 ;; If we left the buffer there is a really good chance we were
6663 ;; creating one of the wiki link documents. Make sure we get
6664 ;; refontified when we come back.
6665 (if (and markdown-enable-wiki-links
6666 markdown-wiki-link-fontify-missing)
6667 (progn
6668 (add-hook 'window-configuration-change-hook
6669 'markdown-fontify-buffer-wiki-links t t)
6670 (markdown-fontify-buffer-wiki-links))
6671 (remove-hook 'window-configuration-change-hook
6672 'markdown-fontify-buffer-wiki-links t)
6673 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
6675 (defun markdown-mode-font-lock-keywords-wiki-links ()
6676 "Return wiki-link lock keywords if support is enabled.
6677 If `markdown-wiki-link-fontify-missing' is also enabled, we use
6678 hooks in `markdown-setup-wiki-link-hooks' for fontification instead."
6679 (when (and markdown-enable-wiki-links
6680 (not markdown-wiki-link-fontify-missing))
6681 (list
6682 (cons markdown-regex-wiki-link '((1 markdown-link-face prepend))))))
6685 ;;; Math Support ==============================================================
6687 (make-obsolete 'markdown-enable-math 'markdown-toggle-math "v2.1")
6689 (defun markdown-toggle-math (&optional arg)
6690 "Toggle support for inline and display LaTeX math expressions.
6691 With a prefix argument ARG, enable math mode if ARG is positive,
6692 and disable it otherwise. If called from Lisp, enable the mode
6693 if ARG is omitted or nil."
6694 (interactive (list (or current-prefix-arg 'toggle)))
6695 (setq markdown-enable-math
6696 (if (eq arg 'toggle)
6697 (not markdown-enable-math)
6698 (> (prefix-numeric-value arg) 0)))
6699 (if markdown-enable-math
6700 (message "markdown-mode math support enabled")
6701 (message "markdown-mode math support disabled"))
6702 (markdown-reload-extensions))
6704 (defun markdown-mode-font-lock-keywords-math ()
6705 "Return math font lock keywords if support is enabled."
6706 (when markdown-enable-math
6707 (list
6708 ;; Display mode equations with brackets: \[ \]
6709 (cons markdown-regex-math-display '((1 markdown-markup-face prepend)
6710 (2 markdown-math-face append)
6711 (3 markdown-markup-face prepend)))
6712 ;; Equation reference (eq:foo)
6713 (cons "\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" '((1 markdown-markup-face)
6714 (2 markdown-reference-face)
6715 (3 markdown-markup-face)))
6716 ;; Equation reference \eqref{foo}
6717 (cons "\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" '((1 markdown-markup-face)
6718 (2 markdown-reference-face)
6719 (3 markdown-markup-face))))))
6722 ;;; GFM Checkboxes ============================================================
6724 (require 'button)
6726 (define-button-type 'markdown-gfm-checkbox-button
6727 'follow-link t
6728 'face 'markdown-gfm-checkbox-face
6729 'mouse-face 'markdown-highlight-face
6730 'action #'markdown-toggle-gfm-checkbox-button)
6732 (defun markdown-toggle-gfm-checkbox ()
6733 "Toggle GFM checkbox at point."
6734 (interactive)
6735 (save-match-data
6736 (save-excursion
6737 (let ((bounds (markdown-cur-list-item-bounds)))
6738 (when bounds
6739 ;; Move to beginning of task list item
6740 (goto-char (cl-first bounds))
6741 ;; Advance to column of first non-whitespace after marker
6742 (forward-char (cl-fourth bounds))
6743 (cond ((looking-at "\\[ \\]")
6744 (replace-match "[x]" nil t))
6745 ((looking-at "\\[[xX]\\]")
6746 (replace-match "[ ]" nil t))))))))
6748 (defun markdown-toggle-gfm-checkbox-button (button)
6749 "Toggle GFM checkbox BUTTON on click."
6750 (save-match-data
6751 (save-excursion
6752 (goto-char (button-start button))
6753 (markdown-toggle-gfm-checkbox))))
6755 (defun markdown-make-gfm-checkboxes-buttons (start end)
6756 "Make GFM checkboxes buttons in region between START and END."
6757 (save-excursion
6758 (goto-char start)
6759 (let ((case-fold-search t))
6760 (save-excursion
6761 (while (re-search-forward markdown-regex-gfm-checkbox end t)
6762 (make-button (match-beginning 1) (match-end 1)
6763 :type 'markdown-gfm-checkbox-button))))))
6765 ;; Called when any modification is made to buffer text.
6766 (defun markdown-gfm-checkbox-after-change-function (beg end _)
6767 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
6768 BEG and END are the limits of scanned region."
6769 (save-excursion
6770 (save-match-data
6771 ;; Rescan between start of line from `beg' and start of line after `end'.
6772 (markdown-make-gfm-checkboxes-buttons
6773 (progn (goto-char beg) (beginning-of-line) (point))
6774 (progn (goto-char end) (forward-line 1) (point))))))
6777 ;;; Display inline image =================================================
6779 (defvar markdown-inline-image-overlays nil)
6780 (make-variable-buffer-local 'markdown-inline-image-overlays)
6782 (defun markdown-remove-inline-images ()
6783 "Remove inline image overlays from image links in the buffer.
6784 This can be toggled with `markdown-toggle-inline-images'
6785 or \\[markdown-toggle-inline-images]."
6786 (interactive)
6787 (mapc #'delete-overlay markdown-inline-image-overlays)
6788 (setq markdown-inline-image-overlays nil))
6790 (defun markdown-display-inline-images ()
6791 "Add inline image overlays to image links in the buffer.
6792 This can be toggled with `markdown-toggle-inline-images'
6793 or \\[markdown-toggle-inline-images]."
6794 (interactive)
6795 (unless (display-graphic-p)
6796 (error "Cannot show images"))
6797 (save-excursion
6798 (save-restriction
6799 (widen)
6800 (goto-char (point-min))
6801 (while (re-search-forward markdown-regex-link-inline nil t)
6802 (let ((start (match-beginning 0))
6803 (end (match-end 0))
6804 (file (match-string-no-properties 6)))
6805 (when (file-exists-p file)
6806 (let* ((abspath (if (file-name-absolute-p file)
6807 file
6808 (concat default-directory file)))
6809 (image (create-image abspath)))
6810 (when image
6811 (let ((ov (make-overlay start end)))
6812 (overlay-put ov 'display image)
6813 (overlay-put ov 'face 'default)
6814 (push ov markdown-inline-image-overlays))))))))))
6816 (defun markdown-toggle-inline-images ()
6817 "Toggle inline image overlays in the buffer."
6818 (interactive)
6819 (if markdown-inline-image-overlays
6820 (markdown-remove-inline-images)
6821 (markdown-display-inline-images)))
6824 ;;; Mode Definition ==========================================================
6826 (defun markdown-show-version ()
6827 "Show the version number in the minibuffer."
6828 (interactive)
6829 (message "markdown-mode, version %s" markdown-mode-version))
6831 (defun markdown-mode-info ()
6832 "Open the `markdown-mode' homepage."
6833 (interactive)
6834 (browse-url "http://jblevins.org/projects/markdown-mode/"))
6836 ;;;###autoload
6837 (define-derived-mode markdown-mode text-mode "Markdown"
6838 "Major mode for editing Markdown files."
6839 ;; Natural Markdown tab width
6840 (setq tab-width 4)
6841 ;; Comments
6842 (make-local-variable 'comment-start)
6843 (setq comment-start "<!-- ")
6844 (make-local-variable 'comment-end)
6845 (setq comment-end " -->")
6846 (make-local-variable 'comment-start-skip)
6847 (setq comment-start-skip "<!--[ \t]*")
6848 (make-local-variable 'comment-column)
6849 (setq comment-column 0)
6850 (set (make-local-variable 'comment-auto-fill-only-comments) nil)
6851 ;; Syntax
6852 (add-hook 'syntax-propertize-extend-region-functions
6853 'markdown-syntax-propertize-extend-region)
6854 (add-hook 'jit-lock-after-change-extend-region-functions
6855 'markdown-font-lock-extend-region-function t t)
6856 (set (make-local-variable 'syntax-propertize-function)
6857 'markdown-syntax-propertize)
6858 ;; Font lock.
6859 (set (make-local-variable 'markdown-mode-font-lock-keywords) nil)
6860 (set (make-local-variable 'font-lock-defaults) nil)
6861 (set (make-local-variable 'font-lock-multiline) t)
6862 ;; Extensions
6863 (make-local-variable 'markdown-enable-math)
6864 ;; Reload extensions
6865 (markdown-reload-extensions)
6866 ;; Add a buffer-local hook to reload after file-local variables are read
6867 (add-hook 'hack-local-variables-hook 'markdown-handle-local-variables nil t)
6868 ;; For imenu support
6869 (setq imenu-create-index-function
6870 (if markdown-nested-imenu-heading-index
6871 'markdown-imenu-create-nested-index
6872 'markdown-imenu-create-flat-index))
6873 ;; For menu support in XEmacs
6874 (easy-menu-add markdown-mode-menu markdown-mode-map)
6875 ;; Defun movement
6876 (set (make-local-variable 'beginning-of-defun-function)
6877 'markdown-beginning-of-defun)
6878 (set (make-local-variable 'end-of-defun-function)
6879 'markdown-end-of-defun)
6880 ;; Paragraph filling
6881 (set (make-local-variable 'fill-paragraph-function)
6882 'markdown-fill-paragraph)
6883 (set
6884 ;; Should match start of lines that start or separate paragraphs
6885 (make-local-variable 'paragraph-start)
6886 (mapconcat #'identity
6888 "\f" ; starts with a literal line-feed
6889 "[ \t\f]*$" ; space-only line
6890 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
6891 "[ \t]*[*+-][ \t]+" ; unordered list item
6892 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
6893 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
6894 "[ \t]*:[ \t]+" ; definition
6896 "\\|"))
6897 (set
6898 ;; Should match lines that separate paragraphs without being
6899 ;; part of any paragraph:
6900 (make-local-variable 'paragraph-separate)
6901 (mapconcat #'identity
6902 '("[ \t\f]*$" ; space-only line
6903 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
6904 ;; The following is not ideal, but the Fill customization
6905 ;; options really only handle paragraph-starting prefixes,
6906 ;; not paragraph-ending suffixes:
6907 ".* $" ; line ending in two spaces
6908 "^#+"
6909 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
6910 "\\|"))
6911 (set (make-local-variable 'adaptive-fill-first-line-regexp)
6912 "\\`[ \t]*>[ \t]*?\\'")
6913 (set (make-local-variable 'adaptive-fill-regexp) "\\s-*")
6914 (set (make-local-variable 'adaptive-fill-function)
6915 'markdown-adaptive-fill-function)
6916 (set (make-local-variable 'fill-forward-paragraph-function)
6917 'markdown-fill-forward-paragraph-function)
6918 ;; Outline mode
6919 (make-local-variable 'outline-regexp)
6920 (setq outline-regexp markdown-regex-header)
6921 (make-local-variable 'outline-level)
6922 (setq outline-level 'markdown-outline-level)
6923 ;; Cause use of ellipses for invisible text.
6924 (add-to-invisibility-spec '(outline . t))
6926 ;; Inhibiting line-breaking:
6927 ;; Separating out each condition into a separate function so that users can
6928 ;; override if desired (with remove-hook)
6929 (add-hook 'fill-nobreak-predicate
6930 'markdown-inside-link-p nil t)
6931 (add-hook 'fill-nobreak-predicate
6932 'markdown-line-is-reference-definition-p nil t)
6934 ;; Indentation
6935 (setq indent-line-function markdown-indent-function)
6937 ;; Backwards compatibility with markdown-css-path
6938 (when (boundp 'markdown-css-path)
6939 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
6940 (add-to-list 'markdown-css-paths markdown-css-path))
6942 ;; Prepare hooks for XEmacs compatibility
6943 (when (featurep 'xemacs)
6944 (make-local-hook 'after-change-functions)
6945 (make-local-hook 'font-lock-extend-region-functions)
6946 (make-local-hook 'window-configuration-change-hook))
6948 ;; Initial syntax analysis
6949 (markdown-syntax-propertize (point-min) (point-max))
6951 ;; Make checkboxes buttons
6952 (when markdown-make-gfm-checkboxes-buttons
6953 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
6954 (add-hook 'after-change-functions 'markdown-gfm-checkbox-after-change-function t t))
6956 ;; add live preview export hook
6957 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
6958 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
6960 ;;;###autoload
6961 (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode) t)
6962 ;;;###autoload
6963 (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode) t)
6966 ;;; GitHub Flavored Markdown Mode ============================================
6968 (defvar gfm-mode-hook nil
6969 "Hook run when entering GFM mode.")
6971 (defvar gfm-font-lock-keywords
6972 (append
6973 ;; GFM features to match first
6974 (list
6975 (cons markdown-regex-strike-through '((3 markdown-markup-face)
6976 (4 markdown-strike-through-face)
6977 (5 markdown-markup-face))))
6978 ;; Basic Markdown features (excluding possibly overridden ones)
6979 markdown-mode-font-lock-keywords-basic)
6980 "Default highlighting expressions for GitHub Flavored Markdown mode.")
6982 ;;;###autoload
6983 (define-derived-mode gfm-mode markdown-mode "GFM"
6984 "Major mode for editing GitHub Flavored Markdown files."
6985 (setq markdown-link-space-sub-char "-")
6986 (setq markdown-wiki-link-search-subdirectories t)
6987 (set (make-local-variable 'font-lock-defaults)
6988 '(gfm-font-lock-keywords))
6989 ;; do the initial link fontification
6990 (markdown-gfm-parse-buffer-for-languages))
6993 ;;; Live Preview Mode ============================================
6994 (define-minor-mode markdown-live-preview-mode
6995 "Toggle native previewing on save for a specific markdown file."
6996 :lighter " MD-Preview"
6997 (if markdown-live-preview-mode
6998 (markdown-display-buffer-other-window (markdown-live-preview-export))
6999 (markdown-live-preview-remove)))
7002 (provide 'markdown-mode)
7003 ;; Local Variables:
7004 ;; indent-tabs-mode: nil
7005 ;; End:
7006 ;;; markdown-mode.el ends here