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