Revert "Add verbosity, argument to markdown-toggle-inline-images"
[markdown-mode.git] / markdown-mode.el
blobc07a09c202d7aa7338bdabff18f55a639c87a5c1
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.3-dev
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 3 of the License, or
19 ;; (at your option) any later version.
21 ;; This program is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
29 ;;; Commentary:
31 ;; markdown-mode is a major mode for editing [Markdown][]-formatted
32 ;; text. The latest stable version is markdown-mode 2.2, released on
33 ;; May 26, 2017. See the [release notes][] for details.
34 ;; markdown-mode is free software, licensed under the GNU GPL v2.
36 ;; ![Markdown Mode Screenshot](http://jblevins.org/projects/markdown-mode/screenshots/20160108-001.png)
38 ;; [Markdown]: http://daringfireball.net/projects/markdown/
39 ;; [release notes]: http://jblevins.org/projects/markdown-mode/rev-2-2
41 ;;; Documentation:
43 ;; <a href="https://leanpub.com/markdown-mode"><img src="http://jblevins.org/projects/markdown-mode/guide-v2.2.png" align="right" height="350" width="252"></a>
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 ;; ``` Lisp
73 ;; (require 'package)
74 ;; (add-to-list 'package-archives
75 ;; '("melpa-stable" . "https://stable.melpa.org/packages/"))
76 ;; (package-initialize)
77 ;; ```
79 ;; Then, after restarting Emacs or evaluating the above statements, issue
80 ;; the following command: `M-x package-install RET markdown-mode RET`.
81 ;; When installed this way, the major modes `markdown-mode' and `gfm-mode'
82 ;; will be autoloaded and `markdown-mode' will be used for file names
83 ;; ending in either `.md` or `.markdown`.
85 ;; Alternatively, if you manage loading packages with [use-package][]
86 ;; then you can automatically install and configure `markdown-mode' by
87 ;; adding a declaration such as this one to your init file (as an
88 ;; example; adjust settings as desired):
90 ;; ``` Lisp
91 ;; (use-package markdown-mode
92 ;; :ensure t
93 ;; :commands (markdown-mode gfm-mode)
94 ;; :mode (("README\\.md\\'" . gfm-mode)
95 ;; ("\\.md\\'" . markdown-mode)
96 ;; ("\\.markdown\\'" . markdown-mode))
97 ;; :init (setq markdown-command "multimarkdown"))
98 ;; ```
100 ;; [MELPA Stable]: http://stable.melpa.org/
101 ;; [use-package]: https://github.com/jwiegley/use-package
103 ;; **Direct Download**
105 ;; Alternatively you can manually download and install markdown-mode.
106 ;; First, download the [latest stable version][markdown-mode.el] and
107 ;; save the file where Emacs can find it (i.e., a directory in your
108 ;; `load-path'). You can then configure `markdown-mode' and `gfm-mode'
109 ;; to load automatically by adding the following to your init file:
111 ;; ``` Lisp
112 ;; (autoload 'markdown-mode "markdown-mode"
113 ;; "Major mode for editing Markdown files" t)
114 ;; (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode))
115 ;; (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode))
117 ;; (autoload 'gfm-mode "markdown-mode"
118 ;; "Major mode for editing GitHub Flavored Markdown files" t)
119 ;; (add-to-list 'auto-mode-alist '("README\\.md\\'" . gfm-mode))
120 ;; ```
122 ;; [markdown-mode.el]: http://jblevins.org/projects/markdown-mode/markdown-mode.el
124 ;; **Development Version**
126 ;; To follow or contribute to markdown-mode development, you can
127 ;; browse or clone the Git repository
128 ;; [on GitHub](https://github.com/jrblevin/markdown-mode):
130 ;; ```
131 ;; git clone https://github.com/jrblevin/markdown-mode.git
132 ;; ```
134 ;; If you prefer to install and use the development version, which may
135 ;; become unstable at some times, you can either clone the Git
136 ;; repository as above or install markdown-mode from
137 ;; [MELPA](https://melpa.org/#/markdown-mode).
139 ;; If you clone the repository directly, then make sure that Emacs can
140 ;; find it by adding the following line to your startup file:
142 ;; ``` Lisp
143 ;; (add-to-list 'load-path "/path/to/markdown-mode/repository")
144 ;; ```
146 ;; **Packaged Installation**
148 ;; markdown-mode is also available in several package managers. You
149 ;; may want to confirm that the package you install contains the
150 ;; latest stable version first (and please notify the package
151 ;; maintainer if not).
153 ;; * Debian Linux: [elpa-markdown-mode][] and [emacs-goodies-el][]
154 ;; * Ubuntu Linux: [elpa-markdown-mode][elpa-ubuntu] and [emacs-goodies-el][emacs-goodies-el-ubuntu]
155 ;; * RedHat and Fedora Linux: [emacs-goodies][]
156 ;; * NetBSD: [textproc/markdown-mode][]
157 ;; * MacPorts: [markdown-mode.el][macports-package] ([pending][macports-ticket])
158 ;; * FreeBSD: [textproc/markdown-mode.el][freebsd-port]
160 ;; [elpa-markdown-mode]: https://packages.debian.org/sid/lisp/elpa-markdown-mode
161 ;; [elpa-ubuntu]: http://packages.ubuntu.com/search?keywords=elpa-markdown-mode
162 ;; [emacs-goodies-el]: http://packages.debian.org/emacs-goodies-el
163 ;; [emacs-goodies-el-ubuntu]: http://packages.ubuntu.com/search?keywords=emacs-goodies-el
164 ;; [emacs-goodies]: https://apps.fedoraproject.org/packages/emacs-goodies
165 ;; [textproc/markdown-mode]: http://pkgsrc.se/textproc/markdown-mode
166 ;; [macports-package]: https://trac.macports.org/browser/trunk/dports/editors/markdown-mode.el/Portfile
167 ;; [macports-ticket]: http://trac.macports.org/ticket/35716
168 ;; [freebsd-port]: http://svnweb.freebsd.org/ports/head/textproc/markdown-mode.el
170 ;; **Dependencies**
172 ;; `markdown-mode' depends on `cl-lib', which has been bundled with
173 ;; GNU Emacs since 24.3. Users of GNU Emacs 24.1 and 24.2 can install
174 ;; `cl-lib' with `package.el'.
176 ;;; Usage:
178 ;; Keybindings are grouped by prefixes based on their function. For
179 ;; example, the commands for inserting links are grouped under `C-c
180 ;; C-a`, where the `C-a` is a mnemonic for the HTML `<a>` tag. In
181 ;; other cases, the connection to HTML is not direct. For example,
182 ;; commands dealing with headings begin with `C-c C-t` (mnemonic:
183 ;; titling). The primary commands in each group will are described
184 ;; below. You can obtain a list of all keybindings by pressing `C-c
185 ;; C-h`. Movement and shifting commands tend to be associated with
186 ;; paired delimiters such as `M-{` and `M-}` or `C-c <` and `C-c >`.
187 ;; Outline navigation keybindings the same as in `org-mode'. Finally,
188 ;; commands for running Markdown or doing maintenance on an open file
189 ;; are grouped under the `C-c C-c` prefix. The most commonly used
190 ;; commands are described below. You can obtain a list of all
191 ;; keybindings by pressing `C-c C-h`.
193 ;; * Hyperlinks: `C-c C-a`
195 ;; In this group, `C-c C-a l` inserts an inline link of the form
196 ;; `[text](url)`. The link text is determined as follows. First,
197 ;; if there is an active region (i.e., when transient mark mode is
198 ;; on and the mark is active), use it as the link text. Second,
199 ;; if the point is at a word, use that word as the link text. In
200 ;; these two cases, the original text will be replaced with the
201 ;; link and point will be left at the position for inserting a
202 ;; URL. Otherwise, insert empty link markup and place the point
203 ;; for inserting the link text.
205 ;; `C-c C-a L` inserts a reference link of the form `[text][label]`
206 ;; and, optionally, a corresponding reference label definition.
207 ;; The link text is determined in the same way as with an inline
208 ;; link (using the region, when active, or the word at the point),
209 ;; but instead of inserting empty markup as a last resort, the
210 ;; link text will be read from the minibuffer. The reference
211 ;; label will be read from the minibuffer in both cases, with
212 ;; completion from the set of currently defined references. To
213 ;; create an implicit reference link, press `RET` to accept the
214 ;; default, an empty label. If the entered referenced label is
215 ;; not defined, additionally prompt for the URL and (optional)
216 ;; title. If a URL is provided, a reference definition will be
217 ;; inserted in accordance with `markdown-reference-location'.
218 ;; If a title is given, it will be added to the end of the
219 ;; reference definition and will be used to populate the title
220 ;; attribute when converted to XHTML.
222 ;; `C-c C-a u` inserts a bare url, delimited by angle brackets. When
223 ;; there is an active region, the text in the region is used as the
224 ;; URL. If the point is at a URL, that url is used. Otherwise,
225 ;; insert angle brackets and position the point in between them
226 ;; for inserting the URL.
228 ;; `C-c C-a f` inserts a footnote marker at the point, inserts a
229 ;; footnote definition below, and positions the point for
230 ;; inserting the footnote text. Note that footnotes are an
231 ;; extension to Markdown and are not supported by all processors.
233 ;; `C-c C-a w` behaves much like the inline link insertion command
234 ;; and inserts a wiki link of the form `[[WikiLink]]`. If there
235 ;; is an active region, use the region as the link text. If the
236 ;; point is at a word, use the word as the link text. If there is
237 ;; no active region and the point is not at word, simply insert
238 ;; link markup. Note that wiki links are an extension to Markdown
239 ;; and are not supported by all processors.
241 ;; * Images: `C-c C-i`
243 ;; `C-c C-i i` inserts markup for an inline image, using the
244 ;; active region or the word at point, if any, as the alt text.
245 ;; `C-c C-i I` behaves similarly and inserts a reference-style
246 ;; image.
248 ;; Local images associated with image links may be displayed
249 ;; inline in the buffer by pressing `C-c C-x C-i`
250 ;; (`markdown-toggle-inline-images'). This is a toggle command, so
251 ;; pressing this once again will remove inline images.
253 ;; * Styles: `C-c C-s`
255 ;; `C-c C-s e` inserts markup to make a region or word italic (`e`
256 ;; for `<em>` or emphasis). If there is an active region, make
257 ;; the region italic. If the point is at a non-italic word, make
258 ;; the word italic. If the point is at an italic word or phrase,
259 ;; remove the italic markup. Otherwise, simply insert italic
260 ;; delimiters and place the cursor in between them. Similarly,
261 ;; use `C-c C-s s` for bold (`<strong>`), `C-c C-s c` for
262 ;; inline code (`<code>`), and `C-c C-s k` for inserting `<kbd>`
263 ;; tags.
265 ;; `C-c C-s b` inserts a blockquote using the active region, if any,
266 ;; or starts a new blockquote. `C-c C-s C-b` is a variation which
267 ;; always operates on the region, regardless of whether it is
268 ;; active or not. The appropriate amount of indentation, if any,
269 ;; is calculated automatically given the surrounding context, but
270 ;; may be adjusted later using the region indentation commands.
272 ;; `C-c C-s p` behaves similarly for inserting preformatted code
273 ;; blocks, with `C-c C-s C-p` being the region-only counterpart.
275 ;; * Headings: `C-c C-t`
277 ;; All heading insertion commands use the text in the active
278 ;; region, if any, as the heading text. Otherwise, if the current
279 ;; line is not blank, they use the text on the current line.
280 ;; Finally, the setext commands will prompt for heading text if
281 ;; there is no active region and the current line is blank.
283 ;; `C-c C-t h` inserts a heading with automatically chosen type and
284 ;; level (both determined by the previous heading). `C-c C-t H`
285 ;; behaves similarly, but uses setext (underlined) headings when
286 ;; possible, still calculating the level automatically.
287 ;; In cases where the automatically-determined level is not what
288 ;; you intended, the level can be quickly promoted or demoted
289 ;; (as described below). Alternatively, a `C-u` prefix can be
290 ;; given to insert a heading promoted by one level or a `C-u C-u`
291 ;; prefix can be given to insert a heading demoted by one level.
293 ;; To insert a heading of a specific level and type, use `C-c C-t 1`
294 ;; through `C-c C-t 6` for atx (hash mark) headings and `C-c C-t !` or
295 ;; `C-c C-t @` for setext headings of level one or two, respectively.
296 ;; Note that `!` is `S-1` and `@` is `S-2`.
298 ;; If the point is at a heading, these commands will replace the
299 ;; existing markup in order to update the level and/or type of the
300 ;; heading. To remove the markup of the heading at the point,
301 ;; press `C-c C-k` to kill the heading and press `C-y` to yank the
302 ;; heading text back into the buffer.
304 ;; * Horizontal Rules: `C-c -`
306 ;; `C-c -` inserts a horizontal rule. By default, insert the
307 ;; first string in the list `markdown-hr-strings' (the most
308 ;; prominent rule). With a `C-u` prefix, insert the last string.
309 ;; With a numeric prefix `N`, insert the string in position `N`
310 ;; (counting from 1).
312 ;; * Markdown and Maintenance Commands: `C-c C-c`
314 ;; *Compile:* `C-c C-c m` will run Markdown on the current buffer
315 ;; and show the output in another buffer. *Preview*: `C-c C-c p`
316 ;; runs Markdown on the current buffer and previews, stores the
317 ;; output in a temporary file, and displays the file in a browser.
318 ;; *Export:* `C-c C-c e` will run Markdown on the current buffer
319 ;; and save the result in the file `basename.html`, where
320 ;; `basename` is the name of the Markdown file with the extension
321 ;; removed. *Export and View:* press `C-c C-c v` to export the
322 ;; file and view it in a browser. *Open:* `C-c C-c o` will open
323 ;; the Markdown source file directly using `markdown-open-command'.
324 ;; *Live Export*: Press `C-c C-c l` to turn on
325 ;; `markdown-live-preview-mode' to view the exported output
326 ;; side-by-side with the source Markdown. **For all export commands,
327 ;; the output file will be overwritten without notice.**
328 ;; `markdown-live-preview-window-function' can be customized to open
329 ;; in a browser other than `eww'. If you want to force the
330 ;; preview window to appear at the bottom or right, you can
331 ;; customize `markdown-split-window-direction`.
333 ;; To summarize:
335 ;; - `C-c C-c m`: `markdown-command' > `*markdown-output*` buffer.
336 ;; - `C-c C-c p`: `markdown-command' > temporary file > browser.
337 ;; - `C-c C-c e`: `markdown-command' > `basename.html`.
338 ;; - `C-c C-c v`: `markdown-command' > `basename.html` > browser.
339 ;; - `C-c C-c w`: `markdown-command' > kill ring.
340 ;; - `C-c C-c o`: `markdown-open-command'.
341 ;; - `C-c C-c l`: `markdown-live-preview-mode' > `*eww*` buffer.
343 ;; `C-c C-c c` will check for undefined references. If there are
344 ;; any, a small buffer will open with a list of undefined
345 ;; references and the line numbers on which they appear. In Emacs
346 ;; 22 and greater, selecting a reference from this list and
347 ;; pressing `RET` will insert an empty reference definition at the
348 ;; end of the buffer. Similarly, selecting the line number will
349 ;; jump to the corresponding line.
351 ;; `C-c C-c n` renumbers any ordered lists in the buffer that are
352 ;; out of sequence.
354 ;; `C-c C-c ]` completes all headings and normalizes all horizontal
355 ;; rules in the buffer.
357 ;; * Following Links: `C-c C-o`
359 ;; Press `C-c C-o` when the point is on an inline or reference
360 ;; link to open the URL in a browser. When the point is at a
361 ;; wiki link, open it in another buffer (in the current window,
362 ;; or in the other window with the `C-u` prefix). Use `M-p` and
363 ;; `M-n` to quickly jump to the previous or next link of any type.
365 ;; * Jumping: `C-c C-l`
367 ;; Use `C-c C-l` to jump from the object at point to its counterpart
368 ;; elsewhere in the text, when possible. Jumps between reference
369 ;; links and definitions; between footnote markers and footnote
370 ;; text. If more than one link uses the same reference name, a
371 ;; new buffer will be created containing clickable buttons for jumping
372 ;; to each link. You may press `TAB` or `S-TAB` to jump between
373 ;; buttons in this window.
375 ;; * Promotion and Demotion: `C-c C--` and `C-c C-=`
377 ;; Headings, horizontal rules, and list items can be promoted and
378 ;; demoted, as well as bold and italic text. For headings,
379 ;; "promotion" means *decreasing* the level (i.e., moving from
380 ;; `<h2>` to `<h1>`) while "demotion" means *increasing* the
381 ;; level. For horizontal rules, promotion and demotion means
382 ;; moving backward or forward through the list of rule strings in
383 ;; `markdown-hr-strings'. For bold and italic text, promotion and
384 ;; demotion means changing the markup from underscores to asterisks.
385 ;; Press `C-c C--` or `M-LEFT` to promote the element at the point
386 ;; if possible.
388 ;; To remember these commands, note that `-` is for decreasing the
389 ;; level (promoting), and `=` (on the same key as `+`) is for
390 ;; increasing the level (demoting). Similarly, the left and right
391 ;; arrow keys indicate the direction that the atx heading markup
392 ;; is moving in when promoting or demoting.
394 ;; * Completion: `C-c C-]`
396 ;; Complete markup is in normalized form, which means, for
397 ;; example, that the underline portion of a setext header is the
398 ;; same length as the heading text, or that the number of leading
399 ;; and trailing hash marks of an atx header are equal and that
400 ;; there is no extra whitespace in the header text. `C-c C-]`
401 ;; completes the markup at the point, if it is determined to be
402 ;; incomplete.
404 ;; * Editing Lists: `M-RET`, `M-UP`, `M-DOWN`, `M-LEFT`, and `M-RIGHT`
406 ;; New list items can be inserted with `M-RET` or `C-c C-j`. This
407 ;; command determines the appropriate marker (one of the possible
408 ;; unordered list markers or the next number in sequence for an
409 ;; ordered list) and indentation level by examining nearby list
410 ;; items. If there is no list before or after the point, start a
411 ;; new list. Prefix this command by `C-u` to decrease the
412 ;; indentation by one level. Prefix this command by `C-u C-u` to
413 ;; increase the indentation by one level.
415 ;; Existing list items can be moved up or down with `M-UP` or
416 ;; `M-DOWN` and indented or exdented with `M-RIGHT` or `M-LEFT`.
418 ;; * Editing Subtrees: `M-S-UP`, `M-S-DOWN`, `M-S-LEFT`, and `M-S-RIGHT`
420 ;; Entire subtrees of ATX headings can be promoted and demoted
421 ;; with `M-S-LEFT` and `M-S-RIGHT`, which mirror the bindings
422 ;; for promotion and demotion of list items. Similarly, subtrees
423 ;; can be moved up and down with `M-S-UP` and `M-S-DOWN`.
425 ;; Please note the following "boundary" behavior for promotion and
426 ;; demotion. Any level-six headings will not be demoted further
427 ;; (i.e., they remain at level six, since Markdown and HTML define
428 ;; only six levels) and any level-one headings will promoted away
429 ;; entirely (i.e., heading markup will be removed, since a
430 ;; level-zero heading is not defined).
432 ;; * Shifting the Region: `C-c <` and `C-c >`
434 ;; Text in the region can be indented or exdented as a group using
435 ;; `C-c >` to indent to the next indentation point (calculated in
436 ;; the current context), and `C-c <` to exdent to the previous
437 ;; indentation point. These keybindings are the same as those for
438 ;; similar commands in `python-mode'.
440 ;; * Killing Elements: `C-c C-k`
442 ;; Press `C-c C-k` to kill the thing at point and add important
443 ;; text, without markup, to the kill ring. Possible things to
444 ;; kill include (roughly in order of precedece): inline code,
445 ;; headings, horizonal rules, links (add link text to kill ring),
446 ;; images (add alt text to kill ring), angle URIs, email
447 ;; addresses, bold, italics, reference definitions (add URI to
448 ;; kill ring), footnote markers and text (kill both marker and
449 ;; text, add text to kill ring), and list items.
451 ;; * Outline Navigation: `C-c C-n`, `C-c C-p`, `C-c C-f`, `C-c C-b`, and `C-c C-u`
453 ;; Navigation between headings is possible using `outline-mode'.
454 ;; Use `C-c C-n` and `C-c C-p` to move between the next and previous
455 ;; visible headings. Similarly, `C-c C-f` and `C-c C-b` move to the
456 ;; next and previous visible headings at the same level as the one
457 ;; at the point. Finally, `C-c C-u` will move up to a lower-level
458 ;; (higher precedence) visible heading.
460 ;; * Movement by Markdown Blocks: `M-{` and `M-}`
462 ;; These keys are usually bound to `forward-paragraph' and
463 ;; `backward-paragraph', but those built-in Emacs functions are
464 ;; based on simple regular expressions and can fail in Markdown.
465 ;; Blocks in `markdown-mode' are code blocks, blockquotes, list
466 ;; items (which may contain other blocks), headings, horizontal
467 ;; rules, or plain text paragraphs separated by whitespace.
468 ;; Instead, they are bound to `markdown-forward-block' and
469 ;; `markdown-backward-block'. To mark or narrow to a block, you
470 ;; can use `M-h` (`markdown-mark-block') and `C-x n b`
471 ;; (`markdown-narrow-to-block').
473 ;; * Movement by Defuns: `C-M-a`, `C-M-e`, and `C-M-h`
475 ;; The usual Emacs commands can be used to move by defuns
476 ;; (top-level major definitions). In markdown-mode, a defun is a
477 ;; section. As usual, `C-M-a` will move the point to the
478 ;; beginning of the current or preceding defun, `C-M-e` will move
479 ;; to the end of the current or following defun, and `C-M-h` will
480 ;; put the region around the entire defun.
482 ;; * Movement by Plain Text Blocks: `C-M-{`, `C-M-}`, and `C-c M-h`
484 ;; While the block and defun movement commands respect Markdown
485 ;; syntax, these commands simply move over whitespace-separated
486 ;; plain text blocks without regard for the context. You can use
487 ;; these commands to move over entire lists, whitespace separated
488 ;; segments of code, etc. To move backward use `C-M-{`
489 ;; (`markdown-beginning-of-text-block`) and to move forward use
490 ;; `C-M-}` (`markdown-end-of-text-block`). To mark a plain text
491 ;; block, use `C-c M-h` (`markdown-mark-text-block`).
493 ;; * Miscellaneous Commands:
495 ;; When the `[edit-indirect](https://github.com/Fanael/edit-indirect/)`
496 ;; package is installed, <kbd>C-c '</kbd> (`markdown-edit-code-block`)
497 ;; can be used to edit a code block in an indirect buffer in the
498 ;; native major mode. Press <kbd>C-c C-c</kbd> to commit changes
499 ;; and return or <kbd>C-c C-k</kbd> to cancel.
501 ;; As noted, many of the commands above behave differently depending
502 ;; on whether Transient Mark mode is enabled or not. When it makes
503 ;; sense, if Transient Mark mode is on and the region is active, the
504 ;; command applies to the text in the region (e.g., `C-c C-s s` makes the
505 ;; region bold). For users who prefer to work outside of Transient
506 ;; Mark mode, since Emacs 22 it can be enabled temporarily by pressing
507 ;; `C-SPC C-SPC`. When this is not the case, many commands then
508 ;; proceed to look work with the word or line at the point.
510 ;; When applicable, commands that specifically act on the region even
511 ;; outside of Transient Mark mode have the same keybinding as their
512 ;; standard counterpart, but the letter is uppercase. For example,
513 ;; `markdown-insert-blockquote' is bound to `C-c C-s b` and only acts on
514 ;; the region in Transient Mark mode while `markdown-blockquote-region'
515 ;; is bound to `C-c C-s B` and always applies to the region (when nonempty).
517 ;; Note that these region-specific functions are useful in many
518 ;; cases where it may not be obvious. For example, yanking text from
519 ;; the kill ring sets the mark at the beginning of the yanked text
520 ;; and moves the point to the end. Therefore, the (inactive) region
521 ;; contains the yanked text. So, `C-y` followed by `C-c C-s C-b` will
522 ;; yank text and turn it into a blockquote.
524 ;; markdown-mode attempts to be flexible in how it handles
525 ;; indentation. When you press `TAB` repeatedly, the point will cycle
526 ;; through several possible indentation levels corresponding to things
527 ;; you might have in mind when you press `RET` at the end of a line or
528 ;; `TAB`. For example, you may want to start a new list item,
529 ;; continue a list item with hanging indentation, indent for a nested
530 ;; pre block, and so on. Exdention is handled similarly when backspace
531 ;; is pressed at the beginning of the non-whitespace portion of a line.
533 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
534 ;; visibility cycling for atx- or hash-style headings. There are two
535 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
536 ;; the table of contents view (headings only), outline view (top-level
537 ;; headings only), and the full document view. Pressing `TAB` while the
538 ;; point is at a heading will cycle through levels of visibility for the
539 ;; subtree: completely folded, visible children, and fully visible.
540 ;; Note that mixing hash and underline style headings will give undesired
541 ;; results.
543 ;;; Customization:
545 ;; Although no configuration is *necessary* there are a few things
546 ;; that can be customized. The `M-x customize-mode` command
547 ;; provides an interface to all of the possible customizations:
549 ;; * `markdown-command' - the command used to run Markdown (default:
550 ;; `markdown`). This variable may be customized to pass
551 ;; command-line options to your Markdown processor of choice.
553 ;; * `markdown-command-needs-filename' - set to `t' if
554 ;; `markdown-command' does not accept standard input (default:
555 ;; `nil'). When `nil', `markdown-mode' will pass the Markdown
556 ;; content to `markdown-command' using standard input (`stdin`).
557 ;; When set to `t', `markdown-mode' will pass the name of the file
558 ;; as the final command-line argument to `markdown-command'. Note
559 ;; that in the latter case, you will only be able to run
560 ;; `markdown-command' from buffers which are visiting a file.
562 ;; * `markdown-open-command' - the command used for calling a standalone
563 ;; Markdown previewer which is capable of opening Markdown source files
564 ;; directly (default: `nil'). This command will be called
565 ;; with a single argument, the filename of the current buffer.
566 ;; A representative program is the Mac app [Marked 2][], a
567 ;; live-updating Markdown previewer which can be [called from a
568 ;; simple shell script](http://jblevins.org/log/marked-2-command).
570 ;; * `markdown-hr-strings' - list of strings to use when inserting
571 ;; horizontal rules. Different strings will not be distinguished
572 ;; when converted to HTML--they will all be converted to
573 ;; `<hr/>`--but they may add visual distinction and style to plain
574 ;; text documents. To maintain some notion of promotion and
575 ;; demotion, keep these sorted from largest to smallest.
577 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
578 ;; underscores when inserting bold text instead of two asterisks
579 ;; (default: `nil').
581 ;; * `markdown-italic-underscore' - set to a non-nil value to use
582 ;; underscores when inserting italic text instead of asterisks
583 ;; (default: `nil').
585 ;; * `markdown-asymmetric-header' - set to a non-nil value to use
586 ;; asymmetric header styling, placing header characters only on
587 ;; the left of headers (default: `nil').
589 ;; * `markdown-header-scaling' - set to a non-nil value to use
590 ;; a variable-pitch font for headings where the size corresponds
591 ;; to the level of the heading (default: `nil').
593 ;; * `markdown-header-scaling-values' - list of scaling values,
594 ;; relative to baseline, for headers of levels one through six,
595 ;; used when `markdown-header-scaling' is non-nil
596 ;; (default: `(2.0 1.7 1.4 1.1 1.0 1.0)`).
598 ;; * `markdown-list-indent-width' - depth of indentation for lists
599 ;; when inserting, promoting, and demoting list items (default: 4).
601 ;; * `markdown-indent-function' - the function to use for automatic
602 ;; indentation (default: `markdown-indent-line').
604 ;; * `markdown-indent-on-enter' - Set to a non-nil value to
605 ;; automatically indent new lines when `RET' is pressed.
606 ;; Set to `indent-and-new-item' to additionally continue lists
607 ;; when `RET' is pressed (default: `t').
609 ;; * `markdown-enable-wiki-links' - syntax highlighting for wiki
610 ;; links (default: `nil'). Set this to a non-nil value to turn on
611 ;; wiki link support by default. Wiki link support can be toggled
612 ;; later using the function `markdown-toggle-wiki-links'."
614 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
615 ;; treat aliased wiki links like `[[link text|PageName]]`
616 ;; (default: `t'). When set to nil, they will be treated as
617 ;; `[[PageName|link text]]'.
619 ;; * `markdown-uri-types' - a list of protocol schemes (e.g., "http")
620 ;; for URIs that `markdown-mode' should highlight.
622 ;; * `markdown-enable-math' - syntax highlighting for LaTeX
623 ;; fragments (default: `nil'). Set this to `t' to turn on math
624 ;; support by default. Math support can be enabled, disabled, or
625 ;; toggled later using the function `markdown-toggle-math'."
627 ;; * `markdown-css-paths' - CSS files to link to in XHTML output
628 ;; (default: `nil`).
630 ;; * `markdown-content-type' - when set to a nonempty string, an
631 ;; `http-equiv` attribute will be included in the XHTML `<head>`
632 ;; block (default: `""`). If needed, the suggested values are
633 ;; `application/xhtml+xml` or `text/html`. See also:
634 ;; `markdown-coding-system'.
636 ;; * `markdown-coding-system' - used for specifying the character
637 ;; set identifier in the `http-equiv` attribute when included
638 ;; (default: `nil'). See `markdown-content-type', which must
639 ;; be set before this variable has any effect. When set to `nil',
640 ;; `buffer-file-coding-system' will be used to automatically
641 ;; determine the coding system string (falling back to
642 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
643 ;; and `iso-latin-1'.
645 ;; * `markdown-xhtml-header-content' - additional content to include
646 ;; in the XHTML `<head>` block (default: `""`).
648 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
649 ;; `markdown-mode' uses to determine whether the output of
650 ;; `markdown-command' is a standalone XHTML document or an XHTML
651 ;; fragment (default: `"^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"`). If
652 ;; this regular expression not matched in the first five lines of
653 ;; output, `markdown-mode' assumes the output is a fragment and
654 ;; adds a header and footer.
656 ;; * `markdown-link-space-sub-char' - a character to replace spaces
657 ;; when mapping wiki links to filenames (default: `"_"`).
658 ;; For example, use an underscore for compatibility with the
659 ;; Python Markdown WikiLinks extension. In `gfm-mode', this is
660 ;; set to `"-"` to conform with GitHub wiki links.
662 ;; * `markdown-reference-location' - where to insert reference
663 ;; definitions (default: `header`). The possible locations are
664 ;; the end of the document (`end`), after the current block
665 ;; (`immediately`), the end of the current subtree (`subtree'),
666 ;; or before the next header (`header`).
668 ;; * `markdown-footnote-location' - where to insert footnote text
669 ;; (default: `end`). The set of location options is the same as
670 ;; for `markdown-reference-location'.
672 ;; * `markdown-nested-imenu-heading-index' - Use nested imenu
673 ;; heading instead of a flat index (default: `t'). A nested
674 ;; index may provide more natural browsing from the menu, but a
675 ;; flat list may allow for faster keyboard navigation via tab
676 ;; completion.
678 ;; * `comment-auto-fill-only-comments' - variable is made
679 ;; buffer-local and set to `nil' by default. In programming
680 ;; language modes, when this variable is non-nil, only comments
681 ;; will be filled by auto-fill-mode. However, comments in
682 ;; Markdown documents are rare and the most users probably intend
683 ;; for the actual content of the document to be filled. Making
684 ;; this variable buffer-local allows `markdown-mode' to override
685 ;; the default behavior induced when the global variable is non-nil.
687 ;; * `markdown-gfm-additional-languages', - additional languages to
688 ;; make available, aside from those predefined in
689 ;; `markdown-gfm-recognized-languages', when inserting GFM code
690 ;; blocks (default: `nil`). Language strings must have be trimmed
691 ;; of whitespace and not contain any curly braces. They may be of
692 ;; arbitrary capitalization, though.
694 ;; * `markdown-gfm-use-electric-backquote' - use
695 ;; `markdown-electric-backquote' for interactive insertion of GFM
696 ;; code blocks when backquote is pressed three times (default: `t`).
698 ;; * `markdown-make-gfm-checkboxes-buttons' - Whether GitHub
699 ;; Flavored Markdown style task lists (checkboxes) should be
700 ;; turned into buttons that can be toggled with mouse-1 or RET. If
701 ;; non-nil (default), then buttons are enabled. This works in
702 ;; `markdown-mode' as well as `gfm-mode'.
704 ;; * `markdown-hide-urls' - Determines whether URL and reference
705 ;; labels are hidden for inline and reference links (default: `t`).
706 ;; By default, inline links will appear in the buffer as
707 ;; `[link](∞)` instead of
708 ;; `[link](http://perhaps.a/very/long/url/)`. To change the
709 ;; placeholder (composition) character used, set the variable
710 ;; `markdown-url-compose-char'. URL hiding can be toggled
711 ;; interactively using `C-c C-x C-l` (`markdown-toggle-url-hiding')
712 ;; or from the Markdown | Links & Images menu.
714 ;; * `markdown-hide-markup' - Determines whether all possible markup
715 ;; is hidden or otherwise beautified (default: `nil'). The actual
716 ;; buffer text remains unchanged, but the display will be altered.
717 ;; Brackets and URLs for links will be hidden, asterisks and
718 ;; underscores for italic and bold text will be hidden, text
719 ;; bullets for unordered lists will be replaced by Unicode
720 ;; bullets, and so on. Since this includes URLs and reference
721 ;; labels, when non-nil this setting supersedes `markdown-hide-urls'.
722 ;; Markup hiding can be toggled using `C-c C-x C-m`
723 ;; (`markdown-toggle-markup-hiding') or from the Markdown | Show &
724 ;; Hide menu.
726 ;; Unicode bullets are used to replace ASCII list item markers.
727 ;; The list of characters used, in order of list level, can be
728 ;; specified by setting the variable `markdown-list-item-bullets'.
729 ;; The placeholder characters used to replace other markup can
730 ;; be changed by customizing the corresponding variables:
731 ;; `markdown-blockquote-display-char',
732 ;; `markdown-hr-display-char', and
733 ;; `markdown-definition-display-char'.
735 ;; * `markdown-fontify-code-blocks-natively' - Whether to fontify
736 ;; code in code blocks using the native major mode. This only
737 ;; works for fenced code blocks where the language is specified
738 ;; where we can automatically determine the appropriate mode to
739 ;; use. The language to mode mapping may be customized by setting
740 ;; the variable `markdown-code-lang-modes'. This can be toggled
741 ;; interactively by pressing `C-c C-x C-f`
742 ;; (`markdown-toggle-fontify-code-blocks-natively').
744 ;; Additionally, the faces used for syntax highlighting can be modified to
745 ;; your liking by issuing `M-x customize-group RET markdown-faces`
746 ;; or by using the "Markdown Faces" link at the bottom of the mode
747 ;; customization screen.
749 ;; [Marked 2]: https://itunes.apple.com/us/app/marked-2/id890031187?mt=12&uo=4&at=11l5Vs&ct=mm
751 ;;; Extensions:
753 ;; Besides supporting the basic Markdown syntax, Markdown Mode also
754 ;; includes syntax highlighting for `[[Wiki Links]]`. This can be
755 ;; enabled by setting `markdown-enable-wiki-links' to a non-nil value.
756 ;; Wiki links may be followed by pressing `C-c C-o` when the point
757 ;; is at a wiki link. Use `M-p` and `M-n` to quickly jump to the
758 ;; previous and next links (including links of other types).
759 ;; Aliased or piped wiki links of the form `[[link text|PageName]]`
760 ;; are also supported. Since some wikis reverse these components, set
761 ;; `markdown-wiki-link-alias-first' to nil to treat them as
762 ;; `[[PageName|link text]]`. If `markdown-wiki-link-fontify-missing'
763 ;; is also non-nil, Markdown Mode will highlight wiki links with
764 ;; missing target file in a different color. By default, Markdown
765 ;; Mode only searches for target files in the current directory.
766 ;; Search in subdirectories can be enabled by setting
767 ;; `markdown-wiki-link-search-subdirectories' to a non-nil value.
768 ;; Sequential parent directory search (as in [Ikiwiki][]) can be
769 ;; enabled by setting `markdown-wiki-link-search-parent-directories'
770 ;; to a non-nil value.
772 ;; [Ikiwiki]: https://ikiwiki.info
774 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
775 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
776 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
777 ;; You can do this either by using `M-x customize-group markdown`
778 ;; or by placing the following in your `.emacs` file:
780 ;; ``` Lisp
781 ;; (setq markdown-command "markdown | smartypants")
782 ;; ```
784 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
786 ;; Syntax highlighting for mathematical expressions written
787 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
788 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
789 ;; either via customize or by placing `(setq markdown-enable-math t)`
790 ;; in `.emacs`, and then restarting Emacs or calling
791 ;; `markdown-reload-extensions'.
793 ;;; GitHub Flavored Markdown (GFM):
795 ;; A [GitHub Flavored Markdown][GFM] mode, `gfm-mode', is also
796 ;; available. The GitHub implementation differs slightly from
797 ;; standard Markdown in that it supports things like different
798 ;; behavior for underscores inside of words, automatic linking of
799 ;; URLs, strikethrough text, and fenced code blocks with an optional
800 ;; language keyword.
802 ;; The GFM-specific features above apply to `README.md` files, wiki
803 ;; pages, and other Markdown-formatted files in repositories on
804 ;; GitHub. GitHub also enables [additional features][GFM comments] for
805 ;; writing on the site (for issues, pull requests, messages, etc.)
806 ;; that are further extensions of GFM. These features include task
807 ;; lists (checkboxes), newlines corresponding to hard line breaks,
808 ;; auto-linked references to issues and commits, wiki links, and so
809 ;; on. To make matters more confusing, although task lists are not
810 ;; part of [GFM proper][GFM], [since 2014][] they are rendered (in a
811 ;; read-only fashion) in all Markdown documents in repositories on the
812 ;; site. These additional extensions are supported to varying degrees
813 ;; by `markdown-mode' and `gfm-mode' as described below.
815 ;; * **URL autolinking:** Both `markdown-mode' and `gfm-mode' support
816 ;; highlighting of URLs without angle brackets.
818 ;; * **Multiple underscores in words:** You must enable `gfm-mode' to
819 ;; toggle support for underscores inside of words. In this mode
820 ;; variable names such as `a_test_variable` will not trigger
821 ;; emphasis (italics).
823 ;; * **Fenced code blocks:** Code blocks quoted with backquotes, with
824 ;; optional programming language keywords, are highlighted in
825 ;; both `markdown-mode' and `gfm-mode'. They can be inserted with
826 ;; `C-c C-s P`. If there is an active region, the text in the
827 ;; region will be placed inside the code block. You will be
828 ;; prompted for the name of the language, but may press enter to
829 ;; continue without naming a language.
831 ;; * **Strikethrough:** Strikethrough text is supported in both
832 ;; `markdown-mode' and `gfm-mode'. It can be inserted (and toggled)
833 ;; using `C-c C-s d`. Following the mnemonics for the other style
834 ;; keybindings, the letter `d` coincides with the HTML tag `<del>`.
836 ;; * **Task lists:** GFM task lists will be rendered as checkboxes
837 ;; (Emacs buttons) in both `markdown-mode' and `gfm-mode' when
838 ;; `markdown-make-gfm-checkboxes-buttons' is set to a non-nil value
839 ;; (and it is set to t by default). These checkboxes can be
840 ;; toggled by clicking `mouse-1`, pressing `RET` over the button,
841 ;; or by pressing `C-c C-x C-x` with the point anywhere in the task
842 ;; list item.
844 ;; * **Wiki links:** Generic wiki links are supported in
845 ;; `markdown-mode', but in `gfm-mode' specifically they will be
846 ;; treated as they are on GitHub: spaces will be replaced by hyphens
847 ;; in filenames and the first letter of the filename will be
848 ;; capitalized. For example, `[[wiki link]]' will map to a file
849 ;; named `Wiki-link` with the same extension as the current file.
850 ;; If a file with this name does not exist in the current directory,
851 ;; the first match in a subdirectory, if any, will be used instead.
853 ;; * **Newlines:** Neither `markdown-mode' nor `gfm-mode' do anything
854 ;; specifically with respect to newline behavior. If you use
855 ;; `gfm-mode' mostly to write text for comments or issues on the
856 ;; GitHub site--where newlines are significant and correspond to
857 ;; hard line breaks--then you may want to enable `visual-line-mode'
858 ;; for line wrapping in buffers. You can do this with a
859 ;; `gfm-mode-hook' as follows:
861 ;; ``` Lisp
862 ;; ;; Use visual-line-mode in gfm-mode
863 ;; (defun my-gfm-mode-hook ()
864 ;; (visual-line-mode 1))
865 ;; (add-hook 'gfm-mode-hook 'my-gfm-mode-hook)
866 ;; ```
868 ;; * **Preview:** GFM-specific preview can be powered by setting
869 ;; `markdown-command' to use [Docter][]. This may also be
870 ;; configured to work with [Marked 2][] for `markdown-open-command'.
872 ;; [GFM]: http://github.github.com/github-flavored-markdown/
873 ;; [GFM comments]: https://help.github.com/articles/writing-on-github/
874 ;; [since 2014]: https://github.com/blog/1825-task-lists-in-all-markdown-documents
875 ;; [Docter]: https://github.com/alampros/Docter
877 ;;; Acknowledgments:
879 ;; markdown-mode has benefited greatly from the efforts of the many
880 ;; volunteers who have sent patches, test cases, bug reports,
881 ;; suggestions, helped with packaging, etc. Thank you for your
882 ;; contributions! See the [contributors graph][contrib] for details.
884 ;; [contrib]: https://github.com/jrblevin/markdown-mode/graphs/contributors
886 ;;; Bugs:
888 ;; markdown-mode is developed and tested primarily for compatibility
889 ;; with GNU Emacs 24.3 and later. If you find any bugs in
890 ;; markdown-mode, please construct a test case or a patch and open a
891 ;; ticket on the [GitHub issue tracker][issues].
893 ;; [issues]: https://github.com/jrblevin/markdown-mode/issues
895 ;;; History:
897 ;; markdown-mode was written and is maintained by Jason Blevins. The
898 ;; first version was released on May 24, 2007.
900 ;; * 2007-05-24: [Version 1.1][]
901 ;; * 2007-05-25: [Version 1.2][]
902 ;; * 2007-06-05: [Version 1.3][]
903 ;; * 2007-06-29: [Version 1.4][]
904 ;; * 2007-10-11: [Version 1.5][]
905 ;; * 2008-06-04: [Version 1.6][]
906 ;; * 2009-10-01: [Version 1.7][]
907 ;; * 2011-08-12: [Version 1.8][]
908 ;; * 2011-08-15: [Version 1.8.1][]
909 ;; * 2013-01-25: [Version 1.9][]
910 ;; * 2013-03-24: [Version 2.0][]
911 ;; * 2016-01-09: [Version 2.1][]
912 ;; * 2016-05-26: [Version 2.2][]
914 ;; [Version 1.1]: http://jblevins.org/projects/markdown-mode/rev-1-1
915 ;; [Version 1.2]: http://jblevins.org/projects/markdown-mode/rev-1-2
916 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
917 ;; [Version 1.4]: http://jblevins.org/projects/markdown-mode/rev-1-4
918 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
919 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
920 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
921 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
922 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
923 ;; [Version 1.9]: http://jblevins.org/projects/markdown-mode/rev-1-9
924 ;; [Version 2.0]: http://jblevins.org/projects/markdown-mode/rev-2-0
925 ;; [Version 2.1]: http://jblevins.org/projects/markdown-mode/rev-2-1
926 ;; [Version 2.2]: http://jblevins.org/projects/markdown-mode/rev-2-2
929 ;;; Code:
931 (require 'easymenu)
932 (require 'outline)
933 (require 'thingatpt)
934 (require 'cl-lib)
935 (require 'url-parse)
936 (require 'button)
937 (require 'color)
939 (defvar jit-lock-start)
940 (defvar jit-lock-end)
941 (defvar flyspell-generic-check-word-predicate)
943 (declare-function eww-open-file "eww")
944 (declare-function url-path-and-query "url-parse")
947 ;;; Constants =================================================================
949 (defconst markdown-mode-version "2.3-dev"
950 "Markdown mode version number.")
952 (defconst markdown-output-buffer-name "*markdown-output*"
953 "Name of temporary buffer for markdown command output.")
955 (defconst markdown-sub-superscript-display
956 '(((raise -0.3) (height 0.7)) ; subscript
957 ((raise 0.3) (height 0.7))) ; superscript
958 "Parameters for sub- and superscript formatting.")
961 ;;; Global Variables ==========================================================
963 (defvar markdown-reference-label-history nil
964 "History of used reference labels.")
966 (defvar markdown-live-preview-mode nil
967 "Sentinel variable for command `markdown-live-preview-mode'.")
969 (defvar markdown-gfm-language-history nil
970 "History list of languages used in the current buffer in GFM code blocks.")
973 ;;; Customizable Variables ====================================================
975 (defvar markdown-mode-hook nil
976 "Hook run when entering Markdown mode.")
978 (defvar markdown-before-export-hook nil
979 "Hook run before running Markdown to export XHTML output.
980 The hook may modify the buffer, which will be restored to it's
981 original state after exporting is complete.")
983 (defvar markdown-after-export-hook nil
984 "Hook run after XHTML output has been saved.
985 Any changes to the output buffer made by this hook will be saved.")
987 (defgroup markdown nil
988 "Major mode for editing text files in Markdown format."
989 :prefix "markdown-"
990 :group 'wp
991 :link '(url-link "http://jblevins.org/projects/markdown-mode/"))
993 (defcustom markdown-command "markdown"
994 "Command to run markdown."
995 :group 'markdown
996 :type 'string)
998 (defcustom markdown-command-needs-filename nil
999 "Set to non-nil if `markdown-command' does not accept input from stdin.
1000 Instead, it will be passed a filename as the final command line
1001 option. As a result, you will only be able to run Markdown from
1002 buffers which are visiting a file."
1003 :group 'markdown
1004 :type 'boolean)
1006 (defcustom markdown-open-command nil
1007 "Command used for opening Markdown files directly.
1008 For example, a standalone Markdown previewer. This command will
1009 be called with a single argument: the filename of the current
1010 buffer."
1011 :group 'markdown
1012 :type 'string)
1014 (defcustom markdown-hr-strings
1015 '("-------------------------------------------------------------------------------"
1016 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
1017 "---------------------------------------"
1018 "* * * * * * * * * * * * * * * * * * * *"
1019 "---------"
1020 "* * * * *")
1021 "Strings to use when inserting horizontal rules.
1022 The first string in the list will be the default when inserting a
1023 horizontal rule. Strings should be listed in decreasing order of
1024 prominence (as in headings from level one to six) for use with
1025 promotion and demotion functions."
1026 :group 'markdown
1027 :type 'list)
1029 (defcustom markdown-bold-underscore nil
1030 "Use two underscores when inserting bold text instead of two asterisks."
1031 :group 'markdown
1032 :type 'boolean)
1034 (defcustom markdown-italic-underscore nil
1035 "Use underscores when inserting italic text instead of asterisks."
1036 :group 'markdown
1037 :type 'boolean)
1039 (defcustom markdown-asymmetric-header nil
1040 "Determines if atx header style will be asymmetric.
1041 Set to a non-nil value to use asymmetric header styling, placing
1042 header markup only at the beginning of the line. By default,
1043 balanced markup will be inserted at the beginning and end of the
1044 line around the header title."
1045 :group 'markdown
1046 :type 'boolean)
1048 (defcustom markdown-indent-function 'markdown-indent-line
1049 "Function to use to indent."
1050 :group 'markdown
1051 :type 'function)
1053 (defcustom markdown-indent-on-enter t
1054 "Determines indentation behavior when pressing \\[newline].
1055 Possible settings are nil, t, and 'indent-and-new-item.
1057 When non-nil, pressing \\[newline] will call `newline-and-indent'
1058 to indent the following line according to the context using
1059 `markdown-indent-function'. In this case, note that
1060 \\[electric-newline-and-maybe-indent] can still be used to insert
1061 a newline without indentation.
1063 When set to 'indent-and-new-item and the point is in a list item
1064 when \\[newline] is pressed, the list will be continued on the next
1065 line, where a new item will be inserted.
1067 When set to nil, simply call `newline' as usual. In this case,
1068 you can still indent lines using \\[markdown-cycle] and continue
1069 lists with \\[markdown-insert-list-item].
1071 Note that this assumes the variable `electric-indent-mode' is
1072 non-nil (enabled). When it is *disabled*, the behavior of
1073 \\[newline] and `\\[electric-newline-and-maybe-indent]' are
1074 reversed."
1075 :group 'markdown
1076 :type '(choice (const :tag "Don't automatically indent" nil)
1077 (const :tag "Automatically indent" t)
1078 (const :tag "Automatically indent and insert new list items" indent-and-new-item)))
1080 (defcustom markdown-enable-wiki-links nil
1081 "Syntax highlighting for wiki links.
1082 Set this to a non-nil value to turn on wiki link support by default.
1083 Support can be toggled later using the `markdown-toggle-wiki-links'
1084 function or \\[markdown-toggle-wiki-links]."
1085 :group 'markdown
1086 :type 'boolean
1087 :safe 'booleanp
1088 :package-version '(markdown-mode . "2.2"))
1090 (defcustom markdown-wiki-link-alias-first t
1091 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
1092 Otherwise, they will be treated as [[PageName|alias text]]."
1093 :group 'markdown
1094 :type 'boolean
1095 :safe 'booleanp)
1097 (defcustom markdown-wiki-link-search-subdirectories nil
1098 "When non-nil, search for wiki link targets in subdirectories.
1099 This is the default search behavior for GitHub and is
1100 automatically set to t in `gfm-mode'."
1101 :group 'markdown
1102 :type 'boolean
1103 :safe 'booleanp
1104 :package-version '(markdown-mode . "2.2"))
1106 (defcustom markdown-wiki-link-search-parent-directories nil
1107 "When non-nil, search for wiki link targets in parent directories.
1108 This is the default search behavior of Ikiwiki."
1109 :group 'markdown
1110 :type 'boolean
1111 :safe 'booleanp
1112 :package-version '(markdown-mode . "2.2"))
1114 (defcustom markdown-wiki-link-fontify-missing nil
1115 "When non-nil, change wiki link face according to existence of target files.
1116 This is expensive because it requires checking for the file each time the buffer
1117 changes or the user switches windows. It is disabled by default because it may
1118 cause lag when typing on slower machines."
1119 :group 'markdown
1120 :type 'boolean
1121 :safe 'booleanp
1122 :package-version '(markdown-mode . "2.2"))
1124 (defcustom markdown-uri-types
1125 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
1126 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
1127 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
1128 "Link types for syntax highlighting of URIs."
1129 :group 'markdown
1130 :type 'list)
1132 (defcustom markdown-url-compose-char
1133 (cond
1134 ((char-displayable-p ?∞) ?∞)
1135 ((char-displayable-p ?…) ?…)
1136 (t ?#))
1137 "Placeholder character for hidden URLs.
1138 Depending on your font, some good choices are …, ⋯, #, ∞, ★, and ⚓."
1139 :type 'character
1140 :safe 'characterp
1141 :package-version '(markdown-mode . "2.3"))
1143 (defcustom markdown-blockquote-display-char
1144 (cond
1145 ((char-displayable-p ?▌) "▌")
1146 ((char-displayable-p ?┃) "┃")
1147 ((char-displayable-p ?│) "│")
1148 ((char-displayable-p ?|) "|")
1149 (t ">"))
1150 "Character for hiding blockquote markup."
1151 :type 'string
1152 :safe 'stringp
1153 :package-version '(markdown-mode . "2.3"))
1155 (defcustom markdown-hr-display-char
1156 (cond ((char-displayable-p ?─) ?─)
1157 ((char-displayable-p ?━) ?━)
1158 (t ?-))
1159 "Character for hiding horizontal rule markup."
1160 :type 'character
1161 :safe 'characterp
1162 :package-version '(markdown-mode . "2.3"))
1164 (defcustom markdown-definition-display-char
1165 (cond ((char-displayable-p ?⁘) ?⁘)
1166 ((char-displayable-p ?⁙) ?⁙)
1167 ((char-displayable-p ?≡) ?≡)
1168 ((char-displayable-p ?⌑) ?⌑)
1169 ((char-displayable-p ?◊) ?◊)
1170 (t nil))
1171 "Character for replacing definition list markup."
1172 :type 'character
1173 :safe 'characterp
1174 :package-version '(markdown-mode . "2.3"))
1176 (defcustom markdown-enable-math nil
1177 "Syntax highlighting for inline LaTeX and itex expressions.
1178 Set this to a non-nil value to turn on math support by default.
1179 Math support can be enabled, disabled, or toggled later using
1180 `markdown-toggle-math' or \\[markdown-toggle-math]."
1181 :group 'markdown
1182 :type 'boolean
1183 :safe 'booleanp)
1184 (make-variable-buffer-local 'markdown-enable-math)
1186 (defcustom markdown-css-paths nil
1187 "URL of CSS file to link to in the output XHTML."
1188 :group 'markdown
1189 :type 'list)
1191 (defcustom markdown-content-type ""
1192 "Content type string for the http-equiv header in XHTML output.
1193 When set to a non-empty string, insert the http-equiv attribute.
1194 Otherwise, this attribute is omitted."
1195 :group 'markdown
1196 :type 'string)
1198 (defcustom markdown-coding-system nil
1199 "Character set string for the http-equiv header in XHTML output.
1200 Defaults to `buffer-file-coding-system' (and falling back to
1201 `iso-8859-1' when not available). Common settings are `utf-8'
1202 and `iso-latin-1'. Use `list-coding-systems' for more choices."
1203 :group 'markdown
1204 :type 'coding-system)
1206 (defcustom markdown-xhtml-header-content ""
1207 "Additional content to include in the XHTML <head> block."
1208 :group 'markdown
1209 :type 'string)
1211 (defcustom markdown-xhtml-standalone-regexp
1212 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
1213 "Regexp indicating whether `markdown-command' output is standalone XHTML."
1214 :group 'markdown
1215 :type 'regexp)
1217 (defcustom markdown-link-space-sub-char "_"
1218 "Character to use instead of spaces when mapping wiki links to filenames."
1219 :group 'markdown
1220 :type 'string)
1222 (defcustom markdown-reference-location 'header
1223 "Position where new reference definitions are inserted in the document."
1224 :group 'markdown
1225 :type '(choice (const :tag "At the end of the document" end)
1226 (const :tag "Immediately after the current block" immediately)
1227 (const :tag "At the end of the subtree" subtree)
1228 (const :tag "Before next header" header)))
1230 (defcustom markdown-footnote-location 'end
1231 "Position where new footnotes are inserted in the document."
1232 :group 'markdown
1233 :type '(choice (const :tag "At the end of the document" end)
1234 (const :tag "Immediately after the current block" immediately)
1235 (const :tag "At the end of the subtree" subtree)
1236 (const :tag "Before next header" header)))
1238 (defcustom markdown-unordered-list-item-prefix " * "
1239 "String inserted before unordered list items."
1240 :group 'markdown
1241 :type 'string)
1243 (defcustom markdown-nested-imenu-heading-index t
1244 "Use nested or flat imenu heading index.
1245 A nested index may provide more natural browsing from the menu,
1246 but a flat list may allow for faster keyboard navigation via tab
1247 completion."
1248 :group 'markdown
1249 :type 'boolean
1250 :safe 'booleanp
1251 :package-version '(markdown-mode . "2.2"))
1253 (defcustom markdown-make-gfm-checkboxes-buttons t
1254 "When non-nil, make GFM checkboxes into buttons."
1255 :group 'markdown
1256 :type 'boolean)
1258 (defcustom markdown-use-pandoc-style-yaml-metadata nil
1259 "When non-nil, allow yaml metadata anywhere in the document."
1260 :group 'markdown
1261 :type 'boolean)
1263 (defcustom markdown-split-window-direction 'any
1264 "Preference for splitting windows for static and live preview.
1265 The default value is 'any, which instructs Emacs to use
1266 `split-window-sensibly' to automatically choose how to split
1267 windows based on the values of `split-width-threshold' and
1268 `split-height-threshold' and the available windows. To force
1269 vertically split (left and right) windows, set this to 'vertical
1270 or 'right. To force horizontally split (top and bottom) windows,
1271 set this to 'horizontal or 'below."
1272 :group 'markdown
1273 :type '(choice (const :tag "Automatic" any)
1274 (const :tag "Right (vertical)" right)
1275 (const :tag "Below (horizontal)" below))
1276 :package-version '(markdown-mode . "2.2"))
1278 (defcustom markdown-live-preview-window-function
1279 'markdown-live-preview-window-eww
1280 "Function to display preview of Markdown output within Emacs.
1281 Function must update the buffer containing the preview and return
1282 the buffer."
1283 :group 'markdown
1284 :type 'function)
1286 (defcustom markdown-live-preview-delete-export 'delete-on-destroy
1287 "Delete exported HTML file when using `markdown-live-preview-export'.
1288 If set to 'delete-on-export, delete on every export. When set to
1289 'delete-on-destroy delete when quitting from command
1290 `markdown-live-preview-mode'. Never delete if set to nil."
1291 :group 'markdown
1292 :type '(choice
1293 (const :tag "Delete on every export" delete-on-export)
1294 (const :tag "Delete when quitting live preview" delete-on-destroy)
1295 (const :tag "Never delete" nil)))
1297 (defcustom markdown-list-indent-width 4
1298 "Depth of indentation for markdown lists.
1299 Used in `markdown-demote-list-item' and
1300 `markdown-promote-list-item'."
1301 :group 'markdown
1302 :type 'integer)
1304 (defcustom markdown-gfm-additional-languages nil
1305 "Extra languages made available when inserting GFM code blocks.
1306 Language strings must have be trimmed of whitespace and not
1307 contain any curly braces. They may be of arbitrary
1308 capitalization, though."
1309 :group 'markdown
1310 :type '(repeat (string :validate markdown-validate-language-string)))
1312 (defcustom markdown-gfm-use-electric-backquote t
1313 "Use `markdown-electric-backquote' when backquote is hit three times."
1314 :group 'markdown
1315 :type 'boolean)
1317 (defcustom markdown-gfm-downcase-languages t
1318 "If non-nil, downcase suggested languages.
1319 This applies to insertions done with
1320 `markdown-electric-backquote'."
1321 :group 'markdown
1322 :type 'boolean)
1324 (defcustom markdown-hide-urls t
1325 "Hide URLs of inline links and reference tags of reference links.
1326 Such URLs will be replaced by an ellipsis (…), but it is still
1327 part of the buffer. Deleting the final parenthesis, for example,
1328 allows easy editing of the URL. You can also hover your mouse
1329 pointer over the link text to see the URL.
1330 Set this to a non-nil value to turn this feature on by default.
1331 You can interactively set the value of this variable by calling
1332 `markdown-toggle-url-hiding' or from the menu Markdown > Links &
1333 Images menu."
1334 :group 'markdown
1335 :type 'boolean
1336 :safe 'booleanp
1337 :package-version '(markdown-mode . "2.3"))
1338 (make-variable-buffer-local 'markdown-hide-urls)
1341 ;;; Regular Expressions =======================================================
1343 (defconst markdown-regex-comment-start
1344 "<!--"
1345 "Regular expression matches HTML comment opening.")
1347 (defconst markdown-regex-comment-end
1348 "--[ \t]*>"
1349 "Regular expression matches HTML comment closing.")
1351 (defconst markdown-regex-link-inline
1352 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)\\((\\)\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?\\()\\)"
1353 "Regular expression for a [text](file) or an image link ![text](file).
1354 Group 1 matches the leading exclamation point (optional).
1355 Group 2 matches the opening square bracket.
1356 Group 3 matches the text inside the square brackets.
1357 Group 4 matches the closing square bracket.
1358 Group 5 matches the opening parenthesis.
1359 Group 6 matches the URL.
1360 Group 7 matches the title (optional).
1361 Group 8 matches the closing parenthesis.")
1363 (defconst markdown-regex-link-reference
1364 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)[ ]?\\(\\[\\)\\([^]]*?\\)\\(\\]\\)"
1365 "Regular expression for a reference link [text][id].
1366 Group 1 matches the leading exclamation point (optional).
1367 Group 2 matches the opening square bracket for the link text.
1368 Group 3 matches the text inside the square brackets.
1369 Group 4 matches the closing square bracket for the link text.
1370 Group 5 matches the opening square bracket for the reference label.
1371 Group 6 matches the reference label.
1372 Group 7 matches the closing square bracket for the reference label.")
1374 (defconst markdown-regex-reference-definition
1375 "^ \\{0,3\\}\\(\\[\\)\\([^]\n]+?\\)\\(\\]\\)\\(:\\)\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
1376 "Regular expression for a reference definition.
1377 Group 1 matches the opening square bracket.
1378 Group 2 matches the reference label.
1379 Group 3 matches the closing square bracket.
1380 Group 4 matches the colon.
1381 Group 5 matches the URL.
1382 Group 6 matches the title attribute (optional).")
1384 (defconst markdown-regex-footnote
1385 "\\(\\[\\^\\)\\(.+?\\)\\(\\]\\)"
1386 "Regular expression for a footnote marker [^fn].
1387 Group 1 matches the opening square bracket and carat.
1388 Group 2 matches only the label, without the surrounding markup.
1389 Group 3 matches the closing square bracket.")
1391 (defconst markdown-regex-header
1392 "^\\(?:\\([^\r\n\t -].*\\)\n\\(?:\\(=+\\)\\|\\(-+\\)\\)\\|\\(#+[ \t]+\\)\\(.*?\\)\\([ \t]*#*\\)\\)$"
1393 "Regexp identifying Markdown headings.
1394 Group 1 matches the text of a setext heading.
1395 Group 2 matches the underline of a level-1 setext heading.
1396 Group 3 matches the underline of a level-2 setext heading.
1397 Group 4 matches the opening hash marks of an atx heading and whitespace.
1398 Group 5 matches the text, without surrounding whitespace, of an atx heading.
1399 Group 6 matches the closing whitespace and hash marks of an atx heading.")
1401 (defconst markdown-regex-header-setext
1402 "^\\([^\r\n\t -].*\\)\n\\(=+\\|-+\\)$"
1403 "Regular expression for generic setext-style (underline) headers.")
1405 (defconst markdown-regex-header-atx
1406 "^\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1407 "Regular expression for generic atx-style (hash mark) headers.")
1409 (defconst markdown-regex-hr
1410 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1411 "Regular expression for matching Markdown horizontal rules.")
1413 (defconst markdown-regex-code
1414 "\\(?:\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(?:.\\|\n[^\n]\\)*?[^`]\\)\\(\\2\\)\\)\\(?:[^`]\\|\\'\\)"
1415 "Regular expression for matching inline code fragments.
1417 Group 1 matches the entire code fragment including the backquotes.
1418 Group 2 matches the opening backquotes.
1419 Group 3 matches the code fragment itself, without backquotes.
1420 Group 4 matches the closing backquotes.
1422 The leading, unnumbered group ensures that the leading backquote
1423 character is not escaped.
1424 The last group, also unnumbered, requires that the character
1425 following the code fragment is not a backquote.
1426 Note that \\(?:.\\|\n[^\n]\\) matches any character, including newlines,
1427 but not two newlines in a row.")
1429 (defconst markdown-regex-kbd
1430 "\\(<kbd>\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(</kbd>\\)"
1431 "Regular expression for matching <kbd> tags.
1432 Groups 1 and 3 match the opening and closing tags.
1433 Group 2 matches the key sequence.")
1435 (defconst markdown-regex-gfm-code-block-open
1436 "^[[:blank:]]*\\(```\\)\\([[:blank:]]*{?[[:blank:]]*\\)\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$"
1437 "Regular expression matching opening of GFM code blocks.
1438 Group 1 matches the opening three backquotes and any following whitespace.
1439 Group 2 matches the opening brace (optional) and surrounding whitespace.
1440 Group 3 matches the language identifier (optional).
1441 Group 4 matches the info string (optional).
1442 Group 5 matches the closing brace (optional), whitespace, and newline.
1443 Groups need to agree with `markdown-regex-tilde-fence-begin'.")
1445 (defconst markdown-regex-gfm-code-block-close
1446 "^[[:blank:]]*\\(```\\)\\(\\s *?\\)$"
1447 "Regular expression matching closing of GFM code blocks.
1448 Group 1 matches the closing three backquotes.
1449 Group 2 matches any whitespace and the final newline.")
1451 (defconst markdown-regex-pre
1452 "^\\( \\|\t\\).*$"
1453 "Regular expression for matching preformatted text sections.")
1455 (defconst markdown-regex-list
1456 "^\\([ \t]*\\)\\([0-9#]+\\.\\|[\\*\\+:-]\\)\\([ \t]+\\)"
1457 "Regular expression for matching list items.")
1459 (defconst markdown-regex-bold
1460 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1461 "Regular expression for matching bold text.
1462 Group 1 matches the character before the opening asterisk or
1463 underscore, if any, ensuring that it is not a backslash escape.
1464 Group 2 matches the entire expression, including delimiters.
1465 Groups 3 and 5 matches the opening and closing delimiters.
1466 Group 4 matches the text inside the delimiters.")
1468 (defconst markdown-regex-italic
1469 "\\(?:^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1470 "Regular expression for matching italic text.
1471 The leading unnumbered matches the character before the opening
1472 asterisk or underscore, if any, ensuring that it is not a
1473 backslash escape.
1474 Group 1 matches the entire expression, including delimiters.
1475 Groups 2 and 4 matches the opening and closing delimiters.
1476 Group 3 matches the text inside the delimiters.")
1478 (defconst markdown-regex-strike-through
1479 "\\(^\\|[^\\]\\)\\(\\(~~\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(~~\\)\\)"
1480 "Regular expression for matching strike-through text.
1481 Group 1 matches the character before the opening tilde, if any,
1482 ensuring that it is not a backslash escape.
1483 Group 2 matches the entire expression, including delimiters.
1484 Groups 3 and 5 matches the opening and closing delimiters.
1485 Group 4 matches the text inside the delimiters.")
1487 (defconst markdown-regex-gfm-italic
1488 "\\(?:^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\2\\|[^ ]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1489 "Regular expression for matching italic text in GitHub Flavored Markdown.
1490 Underscores in words are not treated as special.
1491 Group 1 matches the entire expression, including delimiters.
1492 Groups 2 and 4 matches the opening and closing delimiters.
1493 Group 3 matches the text inside the delimiters.")
1495 (defconst markdown-regex-blockquote
1496 "^[ \t]*\\([A-Z]?>\\)\\([ \t]*\\)\\(.*\\)$"
1497 "Regular expression for matching blockquote lines.
1498 Also accounts for a potential capital letter preceding the angle
1499 bracket, for use with Leanpub blocks (asides, warnings, info
1500 blocks, etc.).
1501 Group 1 matches the leading angle bracket.
1502 Group 2 matches the separating whitespace.
1503 Group 3 matches the text.")
1505 (defconst markdown-regex-line-break
1506 "[^ \n\t][ \t]*\\( \\)$"
1507 "Regular expression for matching line breaks.")
1509 (defconst markdown-regex-wiki-link
1510 "\\(?:^\\|[^\\]\\)\\(\\(\\[\\[\\)\\([^]|]+\\)\\(?:\\(|\\)\\([^]]+\\)\\)?\\(\\]\\]\\)\\)"
1511 "Regular expression for matching wiki links.
1512 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1513 wiki links of the form [[PageName|link text]].
1514 The meanings of the first and second components depend
1515 on the value of `markdown-wiki-link-alias-first'.
1517 Group 1 matches the entire link.
1518 Group 2 matches the opening square brackets.
1519 Group 3 matches the first component of the wiki link.
1520 Group 4 matches the pipe separator, when present.
1521 Group 5 matches the second component of the wiki link, when present.
1522 Group 6 matches the closing square brackets.")
1524 (defconst markdown-regex-uri
1525 (concat "\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+\\)")
1526 "Regular expression for matching inline URIs.")
1528 (defconst markdown-regex-angle-uri
1529 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1530 "Regular expression for matching inline URIs in angle brackets.")
1532 (defconst markdown-regex-email
1533 "<\\(\\(?:\\sw\\|\\s_\\|\\s.\\)+@\\(?:\\sw\\|\\s_\\|\\s.\\)+\\)>"
1534 "Regular expression for matching inline email addresses.")
1536 (defsubst markdown-make-regex-link-generic ()
1537 "Make regular expression for matching any recognized link."
1538 (concat "\\(?:" markdown-regex-link-inline
1539 (when markdown-enable-wiki-links
1540 (concat "\\|" markdown-regex-wiki-link))
1541 "\\|" markdown-regex-link-reference
1542 "\\|" markdown-regex-angle-uri "\\)"))
1544 (defconst markdown-regex-gfm-checkbox
1545 " \\(\\[[ xX]\\]\\) "
1546 "Regular expression for matching GFM checkboxes.
1547 Group 1 matches the text to become a button.")
1549 (defconst markdown-regex-block-separator
1550 "\n[\n\t\f ]*\n"
1551 "Regular expression for matching block boundaries.")
1553 (defconst markdown-regex-block-separator-noindent
1554 (concat "\\(\\`\\|\\(" markdown-regex-block-separator "\\)[^\n\t\f ]\\)")
1555 "Regexp for block separators before lines with no indentation.")
1557 (defconst markdown-regex-math-inline-single
1558 "\\(?:^\\|[^\\]\\)\\(\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\)"
1559 "Regular expression for itex $..$ math mode expressions.
1560 Groups 1 and 3 match the opening and closing dollar signs.
1561 Group 3 matches the mathematical expression contained within.")
1563 (defconst markdown-regex-math-inline-double
1564 "\\(?:^\\|[^\\]\\)\\(\\$\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\$\\)"
1565 "Regular expression for itex $$..$$ math mode expressions.
1566 Groups 1 and 3 match opening and closing dollar signs.
1567 Group 3 matches the mathematical expression contained within.")
1569 (defconst markdown-regex-math-display
1570 "^\\(\\\\\\[\\)\\(\\(?:.\\|\n\\)*?\\)?\\(\\\\\\]\\)$"
1571 "Regular expression for itex \[..\] display mode expressions.
1572 Groups 1 and 3 match the opening and closing delimiters.
1573 Group 2 matches the mathematical expression contained within.")
1575 (defsubst markdown-make-tilde-fence-regex (num-tildes &optional end-of-line)
1576 "Return regexp matching a tilde code fence at least NUM-TILDES long.
1577 END-OF-LINE is the regexp construct to indicate end of line; $ if
1578 missing."
1579 (format "%s%d%s%s" "^[[:blank:]]*\\([~]\\{" num-tildes ",\\}\\)"
1580 (or end-of-line "$")))
1582 (defconst markdown-regex-tilde-fence-begin
1583 (markdown-make-tilde-fence-regex
1584 3 "\\([[:blank:]]*{?\\)[[:blank:]]*\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$")
1585 "Regular expression for matching tilde-fenced code blocks.
1586 Group 1 matches the opening tildes.
1587 Group 2 matches (optional) opening brace and surrounding whitespace.
1588 Group 3 matches the language identifier (optional).
1589 Group 4 matches the info string (optional).
1590 Group 5 matches the closing brace (optional) and any surrounding whitespace.
1591 Groups need to agree with `markdown-regex-gfm-code-block-open'.")
1593 (defconst markdown-regex-declarative-metadata
1594 "^\\([[:alpha:]][[:alpha:] _-]*?\\)\\([:=][ \t]*\\)\\(.*\\)$"
1595 "Regular expression for matching declarative metadata statements.
1596 This matches MultiMarkdown metadata as well as YAML and TOML
1597 assignments such as the following:
1599 variable: value
1603 variable = value")
1605 (defconst markdown-regex-pandoc-metadata
1606 "^\\(%\\)\\([ \t]*\\)\\(.*\\(?:\n[ \t]+.*\\)*\\)"
1607 "Regular expression for matching Pandoc metadata.")
1609 (defconst markdown-regex-yaml-metadata-border
1610 "\\(-\\{3\\}\\)$"
1611 "Regular expression for matching yaml metadata.")
1613 (defconst markdown-regex-yaml-pandoc-metadata-end-border
1614 "^\\(\\.\\{3\\}\\|\\-\\{3\\}\\)$"
1615 "Regular expression for matching yaml metadata end borders.")
1617 (defsubst markdown-get-yaml-metadata-start-border ()
1618 "Return yaml metadata start border depending upon whether Pandoc is used."
1619 (concat
1620 (if markdown-use-pandoc-style-yaml-metadata "^" "\\`")
1621 markdown-regex-yaml-metadata-border))
1623 (defsubst markdown-get-yaml-metadata-end-border (_)
1624 "Return yaml metadata end border depending upon whether Pandoc is used."
1625 (if markdown-use-pandoc-style-yaml-metadata
1626 markdown-regex-yaml-pandoc-metadata-end-border
1627 markdown-regex-yaml-metadata-border))
1629 (defconst markdown-regex-inline-attributes
1630 "[ \t]*\\({:?\\)[ \t]*\\(\\(#[[:alpha:]_.:-]+\\|\\.[[:alpha:]_.:-]+\\|\\w+=['\"]?[^\n'\"]*['\"]?\\),?[ \t]*\\)+\\(}\\)[ \t]*$"
1631 "Regular expression for matching inline identifiers or attribute lists.
1632 Compatible with Pandoc, Python Markdown, PHP Markdown Extra, and Leanpub.")
1634 (defconst markdown-regex-leanpub-sections
1635 (concat
1636 "^\\({\\)\\("
1637 (regexp-opt '("frontmatter" "mainmatter" "backmatter" "appendix" "pagebreak"))
1638 "\\)\\(}\\)[ \t]*\n")
1639 "Regular expression for Leanpub section markers and related syntax.")
1641 (defconst markdown-regex-sub-superscript
1642 "\\(?:^\\|[^\\~^]\\)\\(\\([~^]\\)\\([[:alnum:]]+\\)\\(\\2\\)\\)"
1643 "The regular expression matching a sub- or superscript.
1644 The leading un-numbered group matches the character before the
1645 opening tilde or carat, if any, ensuring that it is not a
1646 backslash escape, carat, or tilde.
1647 Group 1 matches the entire expression, including markup.
1648 Group 2 matches the opening markup--a tilde or carat.
1649 Group 3 matches the text inside the delimiters.
1650 Group 4 matches the closing markup--a tilde or carat.")
1652 (defconst markdown-regex-include
1653 "^\\(<<\\)\\(?:\\(\\[\\)\\(.*\\)\\(\\]\\)\\)?\\(?:\\((\\)\\(.*\\)\\()\\)\\)?\\(?:\\({\\)\\(.*\\)\\(}\\)\\)?$"
1654 "Regular expression matching common forms of include syntax.
1655 Marked 2, Leanpub, and other processors support some of these forms:
1657 <<[sections/section1.md]
1658 <<(folder/filename)
1659 <<[Code title](folder/filename)
1660 <<{folder/raw_file.html}
1662 Group 1 matches the opening two angle brackets.
1663 Groups 2-4 match the opening square bracket, the text inside,
1664 and the closing square bracket, respectively.
1665 Groups 5-7 match the opening parenthesis, the text inside, and
1666 the closing parenthesis.
1667 Groups 8-10 match the opening brace, the text inside, and the brace.")
1669 (defconst markdown-regex-pandoc-inline-footnote
1670 "\\(\\^\\)\\(\\[\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(\\]\\)"
1671 "Regular expression for Pandoc inline footnote^[footnote text].
1672 Group 1 matches the opening caret.
1673 Group 2 matches the opening square bracket.
1674 Group 3 matches the footnote text, without the surrounding markup.
1675 Group 4 matches the closing square bracket.")
1678 ;;; Syntax ====================================================================
1680 (defsubst markdown-in-comment-p (&optional pos)
1681 "Return non-nil if POS is in a comment.
1682 If POS is not given, use point instead."
1683 (nth 4 (syntax-ppss pos)))
1685 (defun markdown-syntax-propertize-extend-region (start end)
1686 "Extend START to END region to include an entire block of text.
1687 This helps improve syntax analysis for block constructs.
1688 Returns a cons (NEW-START . NEW-END) or nil if no adjustment should be made.
1689 Function is called repeatedly until it returns nil. For details, see
1690 `syntax-propertize-extend-region-functions'."
1691 (save-match-data
1692 (save-excursion
1693 (let* ((new-start (progn (goto-char start)
1694 (skip-chars-forward "\n")
1695 (if (re-search-backward "\n\n" nil t)
1696 (min start (match-end 0))
1697 (point-min))))
1698 (new-end (progn (goto-char end)
1699 (skip-chars-backward "\n")
1700 (if (re-search-forward "\n\n" nil t)
1701 (max end (match-beginning 0))
1702 (point-max))))
1703 (code-match (markdown-code-block-at-pos new-start))
1704 (new-start (or (and code-match (cl-first code-match)) new-start))
1705 (code-match (and (< end (point-max)) (markdown-code-block-at-pos end)))
1706 (new-end (or (and code-match (cl-second code-match)) new-end)))
1707 (unless (and (eq new-start start) (eq new-end end))
1708 (cons new-start (min new-end (point-max))))))))
1710 (defun markdown-font-lock-extend-region-function (start end _)
1711 "Used in `jit-lock-after-change-extend-region-functions'.
1712 Delegates to `markdown-syntax-propertize-extend-region'. START
1713 and END are the previous region to refontify."
1714 (let ((res (markdown-syntax-propertize-extend-region start end)))
1715 (when res
1716 ;; syntax-propertize-function is not called when character at
1717 ;; (point-max) is deleted, but font-lock-extend-region-functions
1718 ;; are called. Force a syntax property update in that case.
1719 (when (= end (point-max))
1720 (markdown-syntax-propertize (car res) (cdr res)))
1721 (setq jit-lock-start (car res)
1722 jit-lock-end (cdr res)))))
1724 (defun markdown-syntax-propertize-pre-blocks (start end)
1725 "Match preformatted text blocks from START to END."
1726 (save-excursion
1727 (goto-char start)
1728 (let ((levels (markdown-calculate-list-levels))
1729 indent pre-regexp close-regexp open close)
1730 (while (and (< (point) end) (not close))
1731 ;; Search for a region with sufficient indentation
1732 (if (null levels)
1733 (setq indent 1)
1734 (setq indent (1+ (length levels))))
1735 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1736 (setq close-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1738 (cond
1739 ;; If not at the beginning of a line, move forward
1740 ((not (bolp)) (forward-line))
1741 ;; Move past blank lines
1742 ((markdown-cur-line-blank) (forward-line))
1743 ;; At headers and horizontal rules, reset levels
1744 ((markdown-new-baseline) (forward-line) (setq levels nil))
1745 ;; If the current line has sufficient indentation, mark out pre block
1746 ;; The opening should be preceded by a blank line.
1747 ((and (looking-at pre-regexp)
1748 (markdown-prev-line-blank-p))
1749 (setq open (match-beginning 0))
1750 (while (and (or (looking-at-p pre-regexp) (markdown-cur-line-blank))
1751 (not (eobp)))
1752 (forward-line))
1753 (skip-syntax-backward "-")
1754 (setq close (point)))
1755 ;; If current line has a list marker, update levels, move to end of block
1756 ((looking-at markdown-regex-list)
1757 (setq levels (markdown-update-list-levels
1758 (match-string 2) (current-indentation) levels))
1759 (markdown-end-of-text-block))
1760 ;; If this is the end of the indentation level, adjust levels accordingly.
1761 ;; Only match end of indentation level if levels is not the empty list.
1762 ((and (car levels) (looking-at-p close-regexp))
1763 (setq levels (markdown-update-list-levels
1764 nil (current-indentation) levels))
1765 (markdown-end-of-text-block))
1766 (t (markdown-end-of-text-block))))
1768 (when (and open close)
1769 ;; Set text property data
1770 (put-text-property open close 'markdown-pre (list open close))
1771 ;; Recursively search again
1772 (markdown-syntax-propertize-pre-blocks (point) end)))))
1774 (defconst markdown-fenced-block-pairs
1775 `(((,markdown-regex-tilde-fence-begin markdown-tilde-fence-begin)
1776 (markdown-make-tilde-fence-regex markdown-tilde-fence-end)
1777 markdown-fenced-code)
1778 ((markdown-get-yaml-metadata-start-border markdown-yaml-metadata-begin)
1779 (markdown-get-yaml-metadata-end-border markdown-yaml-metadata-end)
1780 markdown-yaml-metadata-section)
1781 ((,markdown-regex-gfm-code-block-open markdown-gfm-block-begin)
1782 (,markdown-regex-gfm-code-block-close markdown-gfm-block-end)
1783 markdown-gfm-code))
1784 "Mapping of regular expressions to \"fenced-block\" constructs.
1785 These constructs are distinguished by having a distinctive start
1786 and end pattern, both of which take up an entire line of text,
1787 but no special pattern to identify text within the fenced
1788 blocks (unlike blockquotes and indented-code sections).
1790 Each element within this list takes the form:
1792 ((START-REGEX-OR-FUN START-PROPERTY)
1793 (END-REGEX-OR-FUN END-PROPERTY)
1794 MIDDLE-PROPERTY)
1796 Each *-REGEX-OR-FUN element can be a regular expression as a string, or a
1797 function which evaluates to same. Functions for START-REGEX-OR-FUN accept no
1798 arguments, but functions for END-REGEX-OR-FUN accept a single numerical argument
1799 which is the length of the first group of the START-REGEX-OR-FUN match, which
1800 can be ignored if unnecessary. `markdown-maybe-funcall-regexp' is used to
1801 evaluate these into \"real\" regexps.
1803 The *-PROPERTY elements are the text properties applied to each part of the
1804 block construct when it is matched using
1805 `markdown-syntax-propertize-fenced-block-constructs'. START-PROPERTY is applied
1806 to the text matching START-REGEX-OR-FUN, END-PROPERTY to END-REGEX-OR-FUN, and
1807 MIDDLE-PROPERTY to the text in between the two. The value of *-PROPERTY is the
1808 `match-data' when the regexp was matched to the text. In the case of
1809 MIDDLE-PROPERTY, the value is a false match data of the form '(begin end), with
1810 begin and end set to the edges of the \"middle\" text. This makes fontification
1811 easier.")
1813 (defun markdown-text-property-at-point (prop)
1814 (get-text-property (point) prop))
1816 (defsubst markdown-maybe-funcall-regexp (object &optional arg)
1817 (cond ((functionp object)
1818 (if arg (funcall object arg) (funcall object)))
1819 ((stringp object) object)
1820 (t (error "Object cannot be turned into regex"))))
1822 (defsubst markdown-get-start-fence-regexp ()
1823 "Return regexp to find all \"start\" sections of fenced block constructs.
1824 Which construct is actually contained in the match must be found separately."
1825 (mapconcat
1826 #'identity
1827 (mapcar (lambda (entry) (markdown-maybe-funcall-regexp (caar entry)))
1828 markdown-fenced-block-pairs)
1829 "\\|"))
1831 (defun markdown-get-fenced-block-begin-properties ()
1832 (cl-mapcar (lambda (entry) (cl-cadar entry)) markdown-fenced-block-pairs))
1834 (defun markdown-get-fenced-block-end-properties ()
1835 (cl-mapcar (lambda (entry) (cl-cadadr entry)) markdown-fenced-block-pairs))
1837 (defun markdown-get-fenced-block-middle-properties ()
1838 (cl-mapcar #'cl-third markdown-fenced-block-pairs))
1840 (defun markdown-find-previous-prop (prop &optional lim)
1841 "Find previous place where property PROP is non-nil, up to LIM.
1842 Return a cons of (pos . property). pos is point if point contains
1843 non-nil PROP."
1844 (let ((res
1845 (if (get-text-property (point) prop) (point)
1846 (previous-single-property-change
1847 (point) prop nil (or lim (point-min))))))
1848 (when (and (not (get-text-property res prop))
1849 (> res (point-min))
1850 (get-text-property (1- res) prop))
1851 (cl-decf res))
1852 (when (and res (get-text-property res prop)) (cons res prop))))
1854 (defun markdown-find-next-prop (prop &optional lim)
1855 "Find next place where property PROP is non-nil, up to LIM.
1856 Return a cons of (POS . PROPERTY) where POS is point if point
1857 contains non-nil PROP."
1858 (let ((res
1859 (if (get-text-property (point) prop) (point)
1860 (next-single-property-change
1861 (point) prop nil (or lim (point-max))))))
1862 (when (and res (get-text-property res prop)) (cons res prop))))
1864 (defun markdown-min-of-seq (map-fn seq)
1865 "Apply MAP-FN to SEQ and return element of SEQ with minimum value of MAP-FN."
1866 (cl-loop for el in seq
1867 with min = 1.0e+INF ; infinity
1868 with min-el = nil
1869 do (let ((res (funcall map-fn el)))
1870 (when (< res min)
1871 (setq min res)
1872 (setq min-el el)))
1873 finally return min-el))
1875 (defun markdown-max-of-seq (map-fn seq)
1876 "Apply MAP-FN to SEQ and return element of SEQ with maximum value of MAP-FN."
1877 (cl-loop for el in seq
1878 with max = -1.0e+INF ; negative infinity
1879 with max-el = nil
1880 do (let ((res (funcall map-fn el)))
1881 (when (and res (> res max))
1882 (setq max res)
1883 (setq max-el el)))
1884 finally return max-el))
1886 (defun markdown-find-previous-block ()
1887 "Find previous block.
1888 Detect whether `markdown-syntax-propertize-fenced-block-constructs' was
1889 unable to propertize the entire block, but was able to propertize the beginning
1890 of the block. If so, return a cons of (pos . property) where the beginning of
1891 the block was propertized."
1892 (let ((start-pt (point))
1893 (closest-open
1894 (markdown-max-of-seq
1895 #'car
1896 (cl-remove-if
1897 #'null
1898 (cl-mapcar
1899 #'markdown-find-previous-prop
1900 (markdown-get-fenced-block-begin-properties))))))
1901 (when closest-open
1902 (let* ((length-of-open-match
1903 (let ((match-d
1904 (get-text-property (car closest-open) (cdr closest-open))))
1905 (- (cl-fourth match-d) (cl-third match-d))))
1906 (end-regexp
1907 (markdown-maybe-funcall-regexp
1908 (cl-caadr
1909 (cl-find-if
1910 (lambda (entry) (eq (cl-cadar entry) (cdr closest-open)))
1911 markdown-fenced-block-pairs))
1912 length-of-open-match))
1913 (end-prop-loc
1914 (save-excursion
1915 (save-match-data
1916 (goto-char (car closest-open))
1917 (and (re-search-forward end-regexp start-pt t)
1918 (match-beginning 0))))))
1919 (and (not end-prop-loc) closest-open)))))
1921 (defun markdown-get-fenced-block-from-start (prop)
1922 "Return limits of an enclosing fenced block from its start, using PROP.
1923 Return value is a list usable as `match-data'."
1924 (catch 'no-rest-of-block
1925 (let* ((correct-entry
1926 (cl-find-if
1927 (lambda (entry) (eq (cl-cadar entry) prop))
1928 markdown-fenced-block-pairs))
1929 (begin-of-begin (cl-first (markdown-text-property-at-point prop)))
1930 (middle-prop (cl-third correct-entry))
1931 (end-prop (cl-cadadr correct-entry))
1932 (end-of-end
1933 (save-excursion
1934 (goto-char (match-end 0)) ; end of begin
1935 (unless (eobp) (forward-char))
1936 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
1937 (if (not mid-prop-v) ; no middle
1938 (progn
1939 ;; try to find end by advancing one
1940 (let ((end-prop-v
1941 (markdown-text-property-at-point end-prop)))
1942 (if end-prop-v (cl-second end-prop-v)
1943 (throw 'no-rest-of-block nil))))
1944 (set-match-data mid-prop-v)
1945 (goto-char (match-end 0)) ; end of middle
1946 (beginning-of-line) ; into end
1947 (cl-second (markdown-text-property-at-point end-prop)))))))
1948 (list begin-of-begin end-of-end))))
1950 (defun markdown-get-fenced-block-from-middle (prop)
1951 "Return limits of an enclosing fenced block from its middle, using PROP.
1952 Return value is a list usable as `match-data'."
1953 (let* ((correct-entry
1954 (cl-find-if
1955 (lambda (entry) (eq (cl-third entry) prop))
1956 markdown-fenced-block-pairs))
1957 (begin-prop (cl-cadar correct-entry))
1958 (begin-of-begin
1959 (save-excursion
1960 (goto-char (match-beginning 0))
1961 (unless (bobp) (forward-line -1))
1962 (beginning-of-line)
1963 (cl-first (markdown-text-property-at-point begin-prop))))
1964 (end-prop (cl-cadadr correct-entry))
1965 (end-of-end
1966 (save-excursion
1967 (goto-char (match-end 0))
1968 (beginning-of-line)
1969 (cl-second (markdown-text-property-at-point end-prop)))))
1970 (list begin-of-begin end-of-end)))
1972 (defun markdown-get-fenced-block-from-end (prop)
1973 "Return limits of an enclosing fenced block from its end, using PROP.
1974 Return value is a list usable as `match-data'."
1975 (let* ((correct-entry
1976 (cl-find-if
1977 (lambda (entry) (eq (cl-cadadr entry) prop))
1978 markdown-fenced-block-pairs))
1979 (end-of-end (cl-second (markdown-text-property-at-point prop)))
1980 (middle-prop (cl-third correct-entry))
1981 (begin-prop (cl-cadar correct-entry))
1982 (begin-of-begin
1983 (save-excursion
1984 (goto-char (match-beginning 0)) ; beginning of end
1985 (unless (bobp) (backward-char)) ; into middle
1986 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
1987 (if (not mid-prop-v)
1988 (progn
1989 (beginning-of-line)
1990 (cl-first (markdown-text-property-at-point begin-prop)))
1991 (set-match-data mid-prop-v)
1992 (goto-char (match-beginning 0)) ; beginning of middle
1993 (unless (bobp) (forward-line -1)) ; into beginning
1994 (beginning-of-line)
1995 (cl-first (markdown-text-property-at-point begin-prop)))))))
1996 (list begin-of-begin end-of-end)))
1998 (defun markdown-get-enclosing-fenced-block-construct (&optional pos)
1999 "Get \"fake\" match data for block enclosing POS.
2000 Returns fake match data which encloses the start, middle, and end
2001 of the block construct enclosing POS, if it exists. Used in
2002 `markdown-code-block-at-pos'."
2003 (save-excursion
2004 (when pos (goto-char pos))
2005 (beginning-of-line)
2006 (car
2007 (cl-remove-if
2008 #'null
2009 (cl-mapcar
2010 (lambda (fun-and-prop)
2011 (cl-destructuring-bind (fun prop) fun-and-prop
2012 (when prop
2013 (save-match-data
2014 (set-match-data (markdown-text-property-at-point prop))
2015 (funcall fun prop)))))
2016 `((markdown-get-fenced-block-from-start
2017 ,(cl-find-if
2018 #'markdown-text-property-at-point
2019 (markdown-get-fenced-block-begin-properties)))
2020 (markdown-get-fenced-block-from-middle
2021 ,(cl-find-if
2022 #'markdown-text-property-at-point
2023 (markdown-get-fenced-block-middle-properties)))
2024 (markdown-get-fenced-block-from-end
2025 ,(cl-find-if
2026 #'markdown-text-property-at-point
2027 (markdown-get-fenced-block-end-properties)))))))))
2029 (defun markdown-propertize-end-match (reg end fence-spec middle-begin)
2030 "Get match for REG up to END, if exists, and propertize appropriately.
2031 FENCE-SPEC is an entry in `markdown-fenced-block-pairs' and
2032 MIDDLE-BEGIN is the start of the \"middle\" section of the block."
2033 (when (re-search-forward reg end t)
2034 (let ((close-begin (match-beginning 0)) ; Start of closing line.
2035 (close-end (match-end 0)) ; End of closing line.
2036 (close-data (match-data t))) ; Match data for closing line.
2037 ;; Propertize middle section of fenced block.
2038 (put-text-property middle-begin close-begin
2039 (cl-third fence-spec)
2040 (list middle-begin close-begin))
2041 ;; Propertize closing line of fenced block.
2042 (put-text-property close-begin close-end
2043 (cl-cadadr fence-spec) close-data))))
2045 (defun markdown-syntax-propertize-fenced-block-constructs (start end)
2046 "Propertize according to `markdown-fenced-block-pairs' from START to END.
2047 If unable to propertize an entire block (if the start of a block is within START
2048 and END, but the end of the block is not), propertize the start section of a
2049 block, then in a subsequent call propertize both middle and end by finding the
2050 start which was previously propertized."
2051 (let ((start-reg (markdown-get-start-fence-regexp)))
2052 (save-excursion
2053 (goto-char start)
2054 ;; start from previous unclosed block, if exists
2055 (let ((prev-begin-block (markdown-find-previous-block)))
2056 (when prev-begin-block
2057 (let* ((correct-entry
2058 (cl-find-if (lambda (entry)
2059 (eq (cdr prev-begin-block) (cl-cadar entry)))
2060 markdown-fenced-block-pairs))
2061 (enclosed-text-start (1+ (car prev-begin-block)))
2062 (start-length
2063 (save-excursion
2064 (goto-char (car prev-begin-block))
2065 (string-match
2066 (markdown-maybe-funcall-regexp
2067 (caar correct-entry))
2068 (buffer-substring
2069 (point-at-bol) (point-at-eol)))
2070 (- (match-end 1) (match-beginning 1))))
2071 (end-reg (markdown-maybe-funcall-regexp
2072 (cl-caadr correct-entry) start-length)))
2073 (markdown-propertize-end-match
2074 end-reg end correct-entry enclosed-text-start))))
2075 ;; find all new blocks within region
2076 (while (re-search-forward start-reg end t)
2077 ;; we assume the opening constructs take up (only) an entire line,
2078 ;; so we re-check the current line
2079 (let* ((cur-line (buffer-substring (point-at-bol) (point-at-eol)))
2080 ;; find entry in `markdown-fenced-block-pairs' corresponding
2081 ;; to regex which was matched
2082 (correct-entry
2083 (cl-find-if
2084 (lambda (fenced-pair)
2085 (string-match-p
2086 (markdown-maybe-funcall-regexp (caar fenced-pair))
2087 cur-line))
2088 markdown-fenced-block-pairs))
2089 (enclosed-text-start
2090 (save-excursion (1+ (point-at-eol))))
2091 (end-reg
2092 (markdown-maybe-funcall-regexp
2093 (cl-caadr correct-entry)
2094 (if (and (match-beginning 1) (match-end 1))
2095 (- (match-end 1) (match-beginning 1))
2096 0))))
2097 ;; get correct match data
2098 (save-excursion
2099 (beginning-of-line)
2100 (re-search-forward
2101 (markdown-maybe-funcall-regexp (caar correct-entry))
2102 (point-at-eol)))
2103 ;; mark starting, even if ending is outside of region
2104 (put-text-property (match-beginning 0) (match-end 0)
2105 (cl-cadar correct-entry) (match-data t))
2106 (markdown-propertize-end-match
2107 end-reg end correct-entry enclosed-text-start))))))
2109 (defun markdown-syntax-propertize-blockquotes (start end)
2110 "Match blockquotes from START to END."
2111 (save-excursion
2112 (goto-char start)
2113 (while (and (re-search-forward markdown-regex-blockquote end t)
2114 (not (markdown-code-block-at-pos (match-beginning 0))))
2115 (put-text-property (match-beginning 0) (match-end 0)
2116 'markdown-blockquote
2117 (match-data t)))))
2119 (defun markdown-syntax-propertize-hrs (start end)
2120 "Match horizontal rules from START to END."
2121 (save-excursion
2122 (goto-char start)
2123 (while (re-search-forward markdown-regex-hr end t)
2124 (unless (or (markdown-on-heading-p)
2125 (markdown-code-block-at-point-p))
2126 (put-text-property (match-beginning 0) (match-end 0)
2127 'markdown-hr
2128 (match-data t))))))
2130 (defun markdown-syntax-propertize-yaml-metadata (start end)
2131 (save-excursion
2132 (goto-char start)
2133 (cl-loop
2134 while (re-search-forward markdown-regex-declarative-metadata end t)
2135 do (when (get-text-property (match-beginning 0)
2136 'markdown-yaml-metadata-section)
2137 (put-text-property (match-beginning 1) (match-end 1)
2138 'markdown-metadata-key (match-data t))
2139 (put-text-property (match-beginning 2) (match-end 2)
2140 'markdown-metadata-markup (match-data t))
2141 (put-text-property (match-beginning 3) (match-end 3)
2142 'markdown-metadata-value (match-data t))))))
2144 (defun markdown-syntax-propertize-headings (start end)
2145 "Match headings of type SYMBOL with REGEX from START to END."
2146 (goto-char start)
2147 (while (re-search-forward markdown-regex-header end t)
2148 (unless (markdown-code-block-at-pos (match-beginning 0))
2149 (put-text-property
2150 (match-beginning 0) (match-end 0) 'markdown-heading
2151 (match-data t))
2152 (put-text-property
2153 (match-beginning 0) (match-end 0)
2154 (cond ((match-string-no-properties 2) 'markdown-heading-1-setext)
2155 ((match-string-no-properties 3) 'markdown-heading-2-setext)
2156 (t (let ((atx-level (length (markdown-trim-whitespace
2157 (match-string-no-properties 4)))))
2158 (intern (format "markdown-heading-%d-atx" atx-level)))))
2159 (match-data t)))))
2161 (defun markdown-syntax-propertize-comments (start end)
2162 "Match HTML comments from the START to END."
2163 (let* ((in-comment (markdown-in-comment-p)))
2164 (goto-char start)
2165 (cond
2166 ;; Comment start
2167 ((and (not in-comment)
2168 (re-search-forward markdown-regex-comment-start end t)
2169 (not (markdown-inline-code-at-point-p))
2170 (not (markdown-code-block-at-point-p)))
2171 (let ((open-beg (match-beginning 0)))
2172 (put-text-property open-beg (1+ open-beg)
2173 'syntax-table (string-to-syntax "<"))
2174 (markdown-syntax-propertize-comments
2175 (min (1+ (match-end 0)) end (point-max)) end)))
2176 ;; Comment end
2177 ((and in-comment
2178 (re-search-forward markdown-regex-comment-end end t))
2179 (put-text-property (1- (match-end 0)) (match-end 0)
2180 'syntax-table (string-to-syntax ">"))
2181 (markdown-syntax-propertize-comments
2182 (min (1+ (match-end 0)) end (point-max)) end))
2183 ;; Nothing found
2184 (t nil))))
2186 (defvar markdown--syntax-properties
2187 (list 'markdown-tilde-fence-begin nil
2188 'markdown-tilde-fence-end nil
2189 'markdown-fenced-code nil
2190 'markdown-yaml-metadata-begin nil
2191 'markdown-yaml-metadata-end nil
2192 'markdown-yaml-metadata-section nil
2193 'markdown-gfm-block-begin nil
2194 'markdown-gfm-block-end nil
2195 'markdown-gfm-code nil
2196 'markdown-pre nil
2197 'markdown-blockquote nil
2198 'markdown-hr nil
2199 'markdown-heading nil
2200 'markdown-heading-1-setext nil
2201 'markdown-heading-2-setext nil
2202 'markdown-heading-1-atx nil
2203 'markdown-heading-2-atx nil
2204 'markdown-heading-3-atx nil
2205 'markdown-heading-4-atx nil
2206 'markdown-heading-5-atx nil
2207 'markdown-heading-6-atx nil
2208 'markdown-metadata-key nil
2209 'markdown-metadata-value nil
2210 'markdown-metadata-markup nil)
2211 "Property list of all Markdown syntactic properties.")
2213 (defun markdown-syntax-propertize (start end)
2214 "Function used as `syntax-propertize-function'.
2215 START and END delimit region to propertize."
2216 (with-silent-modifications
2217 (save-excursion
2218 (remove-text-properties start end markdown--syntax-properties)
2219 (markdown-syntax-propertize-fenced-block-constructs start end)
2220 (markdown-syntax-propertize-yaml-metadata start end)
2221 (markdown-syntax-propertize-pre-blocks start end)
2222 (markdown-syntax-propertize-blockquotes start end)
2223 (markdown-syntax-propertize-headings start end)
2224 (markdown-syntax-propertize-hrs start end)
2225 (markdown-syntax-propertize-comments start end))))
2228 ;;; Markup Hiding
2230 (defconst markdown-markup-properties
2231 '(face markdown-markup-face invisible markdown-markup)
2232 "List of properties and values to apply to markup.")
2234 (defconst markdown-language-keyword-properties
2235 '(face markdown-language-keyword-face invisible markdown-markup)
2236 "List of properties and values to apply to code block language names.")
2238 (defconst markdown-language-info-properties
2239 '(face markdown-language-info-face invisible markdown-markup)
2240 "List of properties and values to apply to code block language info strings.")
2242 (defconst markdown-include-title-properties
2243 '(face markdown-link-title-face invisible markdown-markup)
2244 "List of properties and values to apply to included code titles.")
2246 (defconst markdown-inline-footnote-properties
2247 '(face nil display ((raise 0.2) (height 0.8)))
2248 "Properties to apply to footnote markers and inline footnotes.")
2250 (defcustom markdown-hide-markup nil
2251 "Determines whether markup in the buffer will be hidden.
2252 When set to nil, all markup is displayed in the buffer as it
2253 appears in the file. An exception is when `markdown-hide-urls'
2254 is non-nil.
2255 Set this to a non-nil value to turn this feature on by default.
2256 You can interactively toggle the value of this variable with
2257 `markdown-toggle-markup-hiding', \\[markdown-toggle-markup-hiding],
2258 or from the Markdown > Show & Hide menu."
2259 :group 'markdown
2260 :type 'boolean
2261 :safe 'booleanp
2262 :package-version '(markdown-mode . "2.3"))
2263 (make-variable-buffer-local 'markdown-hide-markup)
2265 (defun markdown-toggle-markup-hiding (&optional arg)
2266 "Toggle the display or hiding of markup.
2267 With a prefix argument ARG, enable markup hiding if ARG is positive,
2268 and disable it otherwise."
2269 (interactive (list (or current-prefix-arg 'toggle)))
2270 (setq markdown-hide-markup
2271 (if (eq arg 'toggle)
2272 (not markdown-hide-markup)
2273 (> (prefix-numeric-value arg) 0)))
2274 (if markdown-hide-markup
2275 (progn (add-to-invisibility-spec 'markdown-markup)
2276 (message "markdown-mode markup hiding enabled"))
2277 (progn (remove-from-invisibility-spec 'markdown-markup)
2278 (message "markdown-mode markup hiding disabled")))
2279 (markdown-reload-extensions))
2282 ;;; Font Lock =================================================================
2284 (require 'font-lock)
2286 (defvar markdown-italic-face 'markdown-italic-face
2287 "Face name to use for italic text.")
2289 (defvar markdown-bold-face 'markdown-bold-face
2290 "Face name to use for bold text.")
2292 (defvar markdown-strike-through-face 'markdown-strike-through-face
2293 "Face name to use for strike-through text.")
2295 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
2296 "Face name to use as a base for header delimiters.")
2298 (defvar markdown-header-rule-face 'markdown-header-rule-face
2299 "Face name to use as a base for header rules.")
2301 (defvar markdown-header-face 'markdown-header-face
2302 "Face name to use as a base for headers.")
2304 (defvar markdown-header-face-1 'markdown-header-face-1
2305 "Face name to use for level-1 headers.")
2307 (defvar markdown-header-face-2 'markdown-header-face-2
2308 "Face name to use for level-2 headers.")
2310 (defvar markdown-header-face-3 'markdown-header-face-3
2311 "Face name to use for level-3 headers.")
2313 (defvar markdown-header-face-4 'markdown-header-face-4
2314 "Face name to use for level-4 headers.")
2316 (defvar markdown-header-face-5 'markdown-header-face-5
2317 "Face name to use for level-5 headers.")
2319 (defvar markdown-header-face-6 'markdown-header-face-6
2320 "Face name to use for level-6 headers.")
2322 (defvar markdown-inline-code-face 'markdown-inline-code-face
2323 "Face name to use for inline code.")
2325 (defvar markdown-list-face 'markdown-list-face
2326 "Face name to use for list markers.")
2328 (defvar markdown-blockquote-face 'markdown-blockquote-face
2329 "Face name to use for blockquote.")
2331 (defvar markdown-pre-face 'markdown-pre-face
2332 "Face name to use for preformatted text.")
2334 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
2335 "Face name to use for programming language identifiers.")
2337 (defvar markdown-language-info-face 'markdown-language-info-face
2338 "Face name to use for programming info strings.")
2340 (defvar markdown-link-face 'markdown-link-face
2341 "Face name to use for links.")
2343 (defvar markdown-missing-link-face 'markdown-missing-link-face
2344 "Face name to use for links where the linked file does not exist.")
2346 (defvar markdown-reference-face 'markdown-reference-face
2347 "Face name to use for reference.")
2349 (defvar markdown-footnote-marker-face 'markdown-footnote-marker-face
2350 "Face name to use for footnote markers.")
2352 (defvar markdown-url-face 'markdown-url-face
2353 "Face name to use for URLs.")
2355 (defvar markdown-link-title-face 'markdown-link-title-face
2356 "Face name to use for reference link titles.")
2358 (defvar markdown-line-break-face 'markdown-line-break-face
2359 "Face name to use for hard line breaks.")
2361 (defvar markdown-comment-face 'markdown-comment-face
2362 "Face name to use for HTML comments.")
2364 (defvar markdown-math-face 'markdown-math-face
2365 "Face name to use for LaTeX expressions.")
2367 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
2368 "Face name to use for metadata keys.")
2370 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
2371 "Face name to use for metadata values.")
2373 (defvar markdown-gfm-checkbox-face 'markdown-gfm-checkbox-face
2374 "Face name to use for GFM checkboxes.")
2376 (defvar markdown-highlight-face 'markdown-highlight-face
2377 "Face name to use for mouse highlighting.")
2379 (defvar markdown-markup-face 'markdown-markup-face
2380 "Face name to use for markup elements.")
2382 (defgroup markdown-faces nil
2383 "Faces used in Markdown Mode"
2384 :group 'markdown
2385 :group 'faces)
2387 (defface markdown-italic-face
2388 '((t (:inherit italic)))
2389 "Face for italic text."
2390 :group 'markdown-faces)
2392 (defface markdown-bold-face
2393 '((t (:inherit bold)))
2394 "Face for bold text."
2395 :group 'markdown-faces)
2397 (defface markdown-strike-through-face
2398 '((t (:strike-through t)))
2399 "Face for strike-through text."
2400 :group 'markdown-faces)
2402 (defface markdown-markup-face
2403 '((t (:inherit shadow :slant normal :weight normal)))
2404 "Face for markup elements."
2405 :group 'markdown-faces)
2407 (defface markdown-header-rule-face
2408 '((t (:inherit markdown-markup-face)))
2409 "Base face for headers rules."
2410 :group 'markdown-faces)
2412 (defface markdown-header-delimiter-face
2413 '((t (:inherit markdown-markup-face)))
2414 "Base face for headers hash delimiter."
2415 :group 'markdown-faces)
2417 (defface markdown-list-face
2418 '((t (:inherit markdown-markup-face)))
2419 "Face for list item markers."
2420 :group 'markdown-faces)
2422 (defface markdown-blockquote-face
2423 '((t (:inherit font-lock-doc-face)))
2424 "Face for blockquote sections."
2425 :group 'markdown-faces)
2427 (defface markdown-code-face
2428 `((t (:inherit fixed-pitch)))
2429 "Face for inline code, pre blocks, and fenced code blocks."
2430 :group 'markdown-faces)
2432 (defface markdown-inline-code-face
2433 '((t (:inherit markdown-code-face font-lock-constant-face)))
2434 "Face for inline code."
2435 :group 'markdown-faces)
2437 (defface markdown-pre-face
2438 '((t (:inherit (markdown-code-face font-lock-constant-face))))
2439 "Face for preformatted text."
2440 :group 'markdown-faces)
2442 (defface markdown-language-keyword-face
2443 '((t (:inherit font-lock-type-face)))
2444 "Face for programming language identifiers."
2445 :group 'markdown-faces)
2447 (defface markdown-language-info-face
2448 '((t (:inherit font-lock-string-face)))
2449 "Face for programming language info strings."
2450 :group 'markdown-faces)
2452 (defface markdown-link-face
2453 '((t (:inherit link)))
2454 "Face for links."
2455 :group 'markdown-faces)
2457 (defface markdown-missing-link-face
2458 '((t (:inherit font-lock-warning-face)))
2459 "Face for missing links."
2460 :group 'markdown-faces)
2462 (defface markdown-reference-face
2463 '((t (:inherit markdown-markup-face)))
2464 "Face for link references."
2465 :group 'markdown-faces)
2467 (define-obsolete-face-alias 'markdown-footnote-face
2468 'markdown-footnote-marker-face "v2.3")
2470 (defface markdown-footnote-marker-face
2471 '((t (:inherit markdown-markup-face)))
2472 "Face for footnote markers."
2473 :group 'markdown-faces)
2475 (defface markdown-footnote-text-face
2476 '((t (:inherit font-lock-comment-face)))
2477 "Face for footnote text."
2478 :group 'markdown-faces)
2480 (defface markdown-url-face
2481 '((t (:inherit font-lock-string-face)))
2482 "Face for URLs that are part of markup.
2483 For example, this applies to URLs in inline links:
2484 [link text](http://example.com/)."
2485 :group 'markdown-faces)
2487 (defface markdown-plain-url-face
2488 '((t (:inherit markdown-link-face)))
2489 "Face for URLs that are also links.
2490 For example, this applies to plain angle bracket URLs:
2491 <http://example.com/>."
2492 :group 'markdown-faces)
2494 (defface markdown-link-title-face
2495 '((t (:inherit font-lock-comment-face)))
2496 "Face for reference link titles."
2497 :group 'markdown-faces)
2499 (defface markdown-line-break-face
2500 '((t (:inherit font-lock-constant-face :underline t)))
2501 "Face for hard line breaks."
2502 :group 'markdown-faces)
2504 (defface markdown-comment-face
2505 '((t (:inherit font-lock-comment-face)))
2506 "Face for HTML comments."
2507 :group 'markdown-faces)
2509 (defface markdown-math-face
2510 '((t (:inherit font-lock-string-face)))
2511 "Face for LaTeX expressions."
2512 :group 'markdown-faces)
2514 (defface markdown-metadata-key-face
2515 '((t (:inherit font-lock-variable-name-face)))
2516 "Face for metadata keys."
2517 :group 'markdown-faces)
2519 (defface markdown-metadata-value-face
2520 '((t (:inherit font-lock-string-face)))
2521 "Face for metadata values."
2522 :group 'markdown-faces)
2524 (defface markdown-gfm-checkbox-face
2525 '((t (:inherit font-lock-builtin-face)))
2526 "Face for GFM checkboxes."
2527 :group 'markdown-faces)
2529 (defface markdown-highlight-face
2530 '((t (:inherit highlight)))
2531 "Face for mouse highlighting."
2532 :group 'markdown-faces)
2534 (defface markdown-hr-face
2535 '((t (:inherit markdown-markup-face)))
2536 "Face for horizontal rules."
2537 :group 'markdown-faces)
2539 (defcustom markdown-header-scaling nil
2540 "Whether to use variable-height faces for headers.
2541 When non-nil, `markdown-header-face' will inherit from
2542 `variable-pitch' and the scaling values in
2543 `markdown-header-scaling-values' will be applied to
2544 headers of levels one through six respectively."
2545 :type 'boolean
2546 :initialize 'custom-initialize-default
2547 :set (lambda (symbol value)
2548 (set-default symbol value)
2549 (markdown-update-header-faces value))
2550 :group 'markdown-faces
2551 :package-version '(markdown-mode . "2.2"))
2553 (defcustom markdown-header-scaling-values
2554 '(2.0 1.7 1.4 1.1 1.0 1.0)
2555 "List of scaling values for headers of level one through six.
2556 Used when `markdown-header-scaling' is non-nil."
2557 :type 'list
2558 :initialize 'custom-initialize-default
2559 :set (lambda (symbol value)
2560 (set-default symbol value)
2561 (markdown-update-header-faces markdown-header-scaling value))
2562 :group 'markdown-faces)
2564 (defun markdown-make-header-faces ()
2565 "Build the faces used for Markdown headers."
2566 (let ((inherit-faces '(font-lock-function-name-face)))
2567 (when markdown-header-scaling
2568 (setq inherit-faces (cons 'variable-pitch inherit-faces)))
2569 (defface markdown-header-face
2570 `((t (:inherit ,inherit-faces :weight bold)))
2571 "Base face for headers."
2572 :group 'markdown-faces))
2573 (dotimes (num 6)
2574 (let* ((num1 (1+ num))
2575 (face-name (intern (format "markdown-header-face-%s" num1)))
2576 (scale (if markdown-header-scaling
2577 (float (nth num markdown-header-scaling-values))
2578 1.0)))
2579 (eval
2580 `(defface ,face-name
2581 '((t (:inherit markdown-header-face :height ,scale)))
2582 (format "Face for level %s headers.
2583 You probably don't want to customize this face directly. Instead
2584 you can customize the base face `markdown-header-face' or the
2585 variable-height variable `markdown-header-scaling'." ,num1)
2586 :group 'markdown-faces)))))
2588 (markdown-make-header-faces)
2590 (defun markdown-update-header-faces (&optional scaling scaling-values)
2591 "Update header faces, depending on if header SCALING is desired.
2592 If so, use given list of SCALING-VALUES relative to the baseline
2593 size of `markdown-header-face'."
2594 (dotimes (num 6)
2595 (let* ((face-name (intern (format "markdown-header-face-%s" (1+ num))))
2596 (scale (cond ((not scaling) 1.0)
2597 (scaling-values (float (nth num scaling-values)))
2598 (t (float (nth num markdown-header-scaling-values))))))
2599 (unless (get face-name 'saved-face) ; Don't update customized faces
2600 (set-face-attribute face-name nil :height scale)))))
2602 (defun markdown-update-code-face ()
2603 "Generate `markdown-code-face' for code block backgrounds.
2604 When using a light-background theme, darken the background slightly for
2605 code blocks. Similarly, when using a dark-background theme, lighten it
2606 slightly. If the face has been customized already, leave it alone."
2607 ;; Don't update customized faces
2608 (unless (get 'markdown-code-face 'saved-face)
2609 (let ((bg (face-background 'default)))
2610 (when (and bg (not (equal bg "unspecified-bg")))
2611 (set-face-attribute
2612 'markdown-code-face nil
2613 :background
2614 (cl-case (cdr (assq 'background-mode (frame-parameters)))
2615 ('light (color-darken-name bg 3))
2616 ('dark (color-lighten-name bg 3))))))))
2618 (defun markdown-syntactic-face (state)
2619 "Return font-lock face for characters with given STATE.
2620 See `font-lock-syntactic-face-function' for details."
2621 (let ((in-comment (nth 4 state)))
2622 (cond
2623 (in-comment 'markdown-comment-face)
2624 (t nil))))
2626 (defcustom markdown-list-item-bullets
2627 '("●" "◎" "○" "◆" "◇" "►" "•")
2628 "List of bullets to use for unordered lists.
2629 It can contain any number of symbols, which will be repeated.
2630 Depending on your font, some reasonable choices are:
2631 ♥ ● ◇ ✚ ✜ ☯ ◆ ♠ ♣ ♦ ❀ ◆ ◖ ▶ ► • ★ ▸."
2632 :group 'markdown
2633 :type '(repeat (string :tag "Bullet character")))
2635 (defvar markdown-mode-font-lock-keywords-basic
2636 `((markdown-match-yaml-metadata-begin . ((1 markdown-markup-face)))
2637 (markdown-match-yaml-metadata-end . ((1 markdown-markup-face)))
2638 (markdown-match-yaml-metadata-key . ((1 markdown-metadata-key-face)
2639 (2 markdown-markup-face)
2640 (3 markdown-metadata-value-face)))
2641 (markdown-match-gfm-open-code-blocks . ((1 markdown-markup-properties)
2642 (2 markdown-markup-properties nil t)
2643 (3 markdown-language-keyword-properties nil t)
2644 (4 markdown-language-info-properties nil t)
2645 (5 markdown-markup-properties nil t)))
2646 (markdown-match-gfm-close-code-blocks . ((0 markdown-markup-properties)))
2647 (markdown-fontify-gfm-code-blocks)
2648 (markdown-match-fenced-start-code-block . ((1 markdown-markup-properties)
2649 (2 markdown-markup-properties nil t)
2650 (3 markdown-language-keyword-properties nil t)
2651 (4 markdown-language-info-properties nil t)
2652 (5 markdown-markup-properties nil t)))
2653 (markdown-match-fenced-end-code-block . ((0 markdown-markup-properties)))
2654 (markdown-fontify-fenced-code-blocks)
2655 (markdown-match-pre-blocks . ((0 markdown-pre-face)))
2656 (markdown-fontify-headings)
2657 (markdown-match-declarative-metadata . ((1 markdown-metadata-key-face)
2658 (2 markdown-markup-face)
2659 (3 markdown-metadata-value-face)))
2660 (markdown-match-pandoc-metadata . ((1 markdown-markup-face)
2661 (2 markdown-markup-face)
2662 (3 markdown-metadata-value-face)))
2663 (markdown-fontify-hrs)
2664 (markdown-match-code . ((1 markdown-markup-properties prepend)
2665 (2 markdown-inline-code-face prepend)
2666 (3 markdown-markup-properties prepend)))
2667 (,markdown-regex-kbd . ((1 markdown-markup-properties)
2668 (2 markdown-inline-code-face)
2669 (3 markdown-markup-properties)))
2670 (markdown-fontify-angle-uris)
2671 (,markdown-regex-email . 'markdown-plain-url-face)
2672 (markdown-fontify-list-items)
2673 (,markdown-regex-footnote . ((0 markdown-inline-footnote-properties)
2674 (1 markdown-markup-properties) ; [^
2675 (2 markdown-footnote-marker-face) ; label
2676 (3 markdown-markup-properties))) ; ]
2677 (,markdown-regex-pandoc-inline-footnote . ((0 markdown-inline-footnote-properties)
2678 (1 markdown-markup-properties) ; ^
2679 (2 markdown-markup-properties) ; [
2680 (3 'markdown-footnote-text-face) ; text
2681 (4 markdown-markup-properties))) ; ]
2682 (markdown-match-includes . ((1 markdown-markup-properties)
2683 (2 markdown-markup-properties nil t)
2684 (3 markdown-include-title-properties nil t)
2685 (4 markdown-markup-properties nil t)
2686 (5 markdown-markup-properties)
2687 (6 'markdown-url-face)
2688 (7 markdown-markup-properties)))
2689 (markdown-fontify-inline-links)
2690 (markdown-fontify-reference-links)
2691 (,markdown-regex-reference-definition . ((1 markdown-markup-face) ; [
2692 (2 markdown-reference-face) ; label
2693 (3 markdown-markup-face) ; ]
2694 (4 markdown-markup-face) ; :
2695 (5 markdown-url-face) ; url
2696 (6 markdown-link-title-face))) ; "title" (optional)
2697 (markdown-fontify-plain-uris)
2698 ;; Math mode $..$
2699 (markdown-match-math-single . ((1 markdown-markup-face prepend)
2700 (2 markdown-math-face append)
2701 (3 markdown-markup-face prepend)))
2702 ;; Math mode $$..$$
2703 (markdown-match-math-double . ((1 markdown-markup-face prepend)
2704 (2 markdown-math-face append)
2705 (3 markdown-markup-face prepend)))
2706 (markdown-match-bold . ((1 markdown-markup-properties prepend)
2707 (2 markdown-bold-face append)
2708 (3 markdown-markup-properties prepend)))
2709 (markdown-match-italic . ((1 markdown-markup-properties prepend)
2710 (2 markdown-italic-face append)
2711 (3 markdown-markup-properties prepend)))
2712 (,markdown-regex-strike-through . ((3 markdown-markup-properties)
2713 (4 markdown-strike-through-face)
2714 (5 markdown-markup-properties)))
2715 (,markdown-regex-line-break . (1 markdown-line-break-face prepend))
2716 (markdown-fontify-sub-superscripts)
2717 (markdown-match-inline-attributes . ((0 markdown-markup-properties prepend)))
2718 (markdown-match-leanpub-sections . ((0 markdown-markup-properties)))
2719 (markdown-fontify-blockquotes))
2720 "Syntax highlighting for Markdown files.")
2722 (defvar markdown-mode-font-lock-keywords nil
2723 "Default highlighting expressions for Markdown mode.
2724 This variable is defined as a buffer-local variable for dynamic
2725 extension support.")
2727 ;; Footnotes
2728 (defvar markdown-footnote-counter 0
2729 "Counter for footnote numbers.")
2730 (make-variable-buffer-local 'markdown-footnote-counter)
2732 (defconst markdown-footnote-chars
2733 "[[:alnum:]-]"
2734 "Regular expression matching any character that is allowed in a footnote identifier.")
2736 (defconst markdown-regex-footnote-definition
2737 (concat "^\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:\\(?:[ \t]+\\|$\\)")
2738 "Regular expression matching a footnote definition, capturing the label.")
2741 ;;; Compatibility =============================================================
2743 (defun markdown-replace-regexp-in-string (regexp rep string)
2744 "Replace ocurrences of REGEXP with REP in STRING.
2745 This is a compatibility wrapper to provide `replace-regexp-in-string'
2746 in XEmacs 21."
2747 (if (featurep 'xemacs)
2748 (replace-in-string string regexp rep)
2749 (replace-regexp-in-string regexp rep string)))
2751 ;; `markdown-use-region-p' is a compatibility function which checks
2752 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
2753 (eval-and-compile
2754 (cond
2755 ;; Emacs 24 and newer
2756 ((fboundp 'use-region-p)
2757 (defalias 'markdown-use-region-p 'use-region-p))
2758 ;; XEmacs
2759 ((fboundp 'region-active-p)
2760 (defalias 'markdown-use-region-p 'region-active-p))))
2762 ;; Use new names for outline-mode functions in Emacs 25 and later.
2763 (eval-and-compile
2764 (defalias 'markdown-hide-sublevels
2765 (if (fboundp 'outline-hide-sublevels)
2766 'outline-hide-sublevels
2767 'hide-sublevels))
2768 (defalias 'markdown-show-all
2769 (if (fboundp 'outline-show-all)
2770 'outline-show-all
2771 'show-all))
2772 (defalias 'markdown-hide-body
2773 (if (fboundp 'outline-hide-body)
2774 'outline-hide-body
2775 'hide-body))
2776 (defalias 'markdown-show-children
2777 (if (fboundp 'outline-show-children)
2778 'outline-show-children
2779 'show-children))
2780 (defalias 'markdown-show-subtree
2781 (if (fboundp 'outline-show-subtree)
2782 'outline-show-subtree
2783 'show-subtree))
2784 (defalias 'markdown-hide-subtree
2785 (if (fboundp 'outline-hide-subtree)
2786 'outline-hide-subtree
2787 'hide-subtree)))
2789 ;; Provide directory-name-p to Emacs 24
2790 (defsubst markdown-directory-name-p (name)
2791 "Return non-nil if NAME ends with a directory separator character.
2792 Taken from `directory-name-p' from Emacs 25 and provided here for
2793 backwards compatibility."
2794 (let ((len (length name))
2795 (lastc ?.))
2796 (if (> len 0)
2797 (setq lastc (aref name (1- len))))
2798 (or (= lastc ?/)
2799 (and (memq system-type '(windows-nt ms-dos))
2800 (= lastc ?\\)))))
2802 ;; Provide a function to find files recursively in Emacs 24.
2803 (defalias 'markdown-directory-files-recursively
2804 (if (fboundp 'directory-files-recursively)
2805 'directory-files-recursively
2806 (lambda (dir regexp)
2807 "Return list of all files under DIR that have file names matching REGEXP.
2808 This function works recursively. Files are returned in \"depth first\"
2809 order, and files from each directory are sorted in alphabetical order.
2810 Each file name appears in the returned list in its absolute form.
2811 Based on `directory-files-recursively' from Emacs 25 and provided
2812 here for backwards compatibility."
2813 (let ((result nil)
2814 (files nil)
2815 ;; When DIR is "/", remote file names like "/method:" could
2816 ;; also be offered. We shall suppress them.
2817 (tramp-mode (and tramp-mode (file-remote-p (expand-file-name dir)))))
2818 (dolist (file (sort (file-name-all-completions "" dir)
2819 'string<))
2820 (unless (member file '("./" "../"))
2821 (if (markdown-directory-name-p file)
2822 (let* ((leaf (substring file 0 (1- (length file))))
2823 (full-file (expand-file-name leaf dir)))
2824 (setq result
2825 (nconc result (markdown-directory-files-recursively
2826 full-file regexp))))
2827 (when (string-match-p regexp file)
2828 (push (expand-file-name file dir) files)))))
2829 (nconc result (nreverse files))))))
2831 (defun markdown-flyspell-check-word-p ()
2832 "Return t if `flyspell' should check word just before point.
2833 Used for `flyspell-generic-check-word-predicate'."
2834 (save-excursion
2835 (goto-char (1- (point)))
2836 (not (or (markdown-code-block-at-point-p)
2837 (markdown-inline-code-at-point-p)
2838 (markdown-in-comment-p)
2839 (let ((faces (get-text-property (point) 'face)))
2840 (if (listp faces)
2841 (or (memq 'markdown-reference-face faces)
2842 (memq 'markdown-markup-face faces)
2843 (memq 'markdown-plain-url-face faces)
2844 (memq 'markdown-url-face faces))
2845 (memq faces '(markdown-reference-face
2846 markdown-markup-face
2847 markdown-plain-url-face
2848 markdown-url-face))))))))
2850 (defun markdown-font-lock-ensure ()
2851 "Provide `font-lock-ensure' in Emacs 24."
2852 (if (fboundp 'font-lock-ensure)
2853 (font-lock-ensure)
2854 (with-no-warnings
2855 ;; Suppress warning about non-interactive use of
2856 ;; `font-lock-fontify-buffer' in Emacs 25.
2857 (font-lock-fontify-buffer))))
2860 ;;; Markdown Parsing Functions ================================================
2862 (defun markdown-cur-line-blank (&optional predicate)
2863 "Return t if the current line is blank and nil otherwise.
2864 When PREDICATE is non-nil, don't modify the match data."
2865 (save-excursion
2866 (beginning-of-line)
2867 (let ((regexp "^\\s *$"))
2868 (if predicate
2869 (looking-at-p regexp)
2870 (looking-at regexp)))))
2872 (defun markdown-cur-line-blank-p ()
2873 "Same as `markdown-cur-line-blank', but does not change the match data."
2874 (markdown-cur-line-blank t))
2876 (defun markdown-prev-line-blank (&optional predicate)
2877 "Return t if the previous line is blank and nil otherwise.
2878 If we are at the first line, then consider the previous line to be blank.
2879 When PREDICATE is non-nil, don't modify the match data."
2880 (or (= (line-beginning-position) (point-min))
2881 (save-excursion
2882 (forward-line -1)
2883 (markdown-cur-line-blank predicate))))
2885 (defun markdown-prev-line-blank-p ()
2886 "Same as `markdown-prev-line-blank', but does not change the match data."
2887 (markdown-prev-line-blank t))
2889 (defun markdown-next-line-blank (&optional predicate)
2890 "Return t if the next line is blank and nil otherwise.
2891 If we are at the last line, then consider the next line to be blank.
2892 When PREDICATE is non-nil, don't modify the match data."
2893 (or (= (line-end-position) (point-max))
2894 (save-excursion
2895 (forward-line 1)
2896 (markdown-cur-line-blank predicate))))
2898 (defun markdown-next-line-blank-p ()
2899 "Same as `markdown-next-line-blank', but does not change the match data."
2900 (markdown-next-line-blank t))
2902 (defun markdown-prev-line-indent ()
2903 "Return the number of leading whitespace characters in the previous line.
2904 Return 0 if the current line is the first line in the buffer."
2905 (save-excursion
2906 (if (= (line-beginning-position) (point-min))
2908 (forward-line -1)
2909 (current-indentation))))
2911 (defun markdown-next-line-indent ()
2912 "Return the number of leading whitespace characters in the next line.
2913 Return 0 if line is the last line in the buffer."
2914 (save-excursion
2915 (if (= (line-end-position) (point-max))
2917 (forward-line 1)
2918 (current-indentation))))
2920 (defun markdown-cur-non-list-indent ()
2921 "Return beginning position of list item text (not including the list marker).
2922 Return nil if the current line is not the beginning of a list item."
2923 (save-match-data
2924 (save-excursion
2925 (beginning-of-line)
2926 (when (re-search-forward markdown-regex-list (line-end-position) t)
2927 (current-column)))))
2929 (defun markdown-prev-non-list-indent ()
2930 "Return position of the first non-list-marker on the previous line."
2931 (save-excursion
2932 (forward-line -1)
2933 (markdown-cur-non-list-indent)))
2935 (defun markdown-new-baseline ()
2936 "Determine if the current line begins a new baseline level."
2937 (save-excursion
2938 (beginning-of-line)
2939 (or (looking-at markdown-regex-header)
2940 (looking-at markdown-regex-hr)
2941 (and (null (markdown-cur-non-list-indent))
2942 (= (current-indentation) 0)
2943 (markdown-prev-line-blank)))))
2945 (defun markdown-search-backward-baseline ()
2946 "Search backward baseline point with no indentation and not a list item."
2947 (end-of-line)
2948 (let (stop)
2949 (while (not (or stop (bobp)))
2950 (re-search-backward markdown-regex-block-separator-noindent nil t)
2951 (when (match-end 2)
2952 (goto-char (match-end 2))
2953 (cond
2954 ((markdown-new-baseline)
2955 (setq stop t))
2956 ((looking-at-p markdown-regex-list)
2957 (setq stop nil))
2958 (t (setq stop t)))))))
2960 (defun markdown-update-list-levels (marker indent levels)
2961 "Update list levels given list MARKER, block INDENT, and current LEVELS.
2962 Here, MARKER is a string representing the type of list, INDENT is an integer
2963 giving the indentation, in spaces, of the current block, and LEVELS is a
2964 list of the indentation levels of parent list items. When LEVELS is nil,
2965 it means we are at baseline (not inside of a nested list)."
2966 (cond
2967 ;; New list item at baseline.
2968 ((and marker (null levels))
2969 (setq levels (list indent)))
2970 ;; List item with greater indentation (four or more spaces).
2971 ;; Increase list level.
2972 ((and marker (>= indent (+ (car levels) 4)))
2973 (setq levels (cons indent levels)))
2974 ;; List item with greater or equal indentation (less than four spaces).
2975 ;; Do not increase list level.
2976 ((and marker (>= indent (car levels)))
2977 levels)
2978 ;; Lesser indentation level.
2979 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
2980 ;; indentation could move back more than one list level). Note
2981 ;; that this block need not be the beginning of list item.
2982 ((< indent (car levels))
2983 (while (and (> (length levels) 1)
2984 (< indent (+ (cadr levels) 4)))
2985 (setq levels (cdr levels)))
2986 levels)
2987 ;; Otherwise, do nothing.
2988 (t levels)))
2990 (defun markdown-calculate-list-levels ()
2991 "Calculate list levels at point.
2992 Return a list of the form (n1 n2 n3 ...) where n1 is the
2993 indentation of the deepest nested list item in the branch of
2994 the list at the point, n2 is the indentation of the parent
2995 list item, and so on. The depth of the list item is therefore
2996 the length of the returned list. If the point is not at or
2997 immediately after a list item, return nil."
2998 (save-excursion
2999 (let ((first (point)) levels indent pre-regexp)
3000 ;; Find a baseline point with zero list indentation
3001 (markdown-search-backward-baseline)
3002 ;; Search for all list items between baseline and LOC
3003 (while (and (< (point) first)
3004 (re-search-forward markdown-regex-list first t))
3005 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
3006 (beginning-of-line)
3007 (cond
3008 ;; Make sure this is not a header or hr
3009 ((markdown-new-baseline) (setq levels nil))
3010 ;; Make sure this is not a line from a pre block
3011 ((looking-at-p pre-regexp))
3012 ;; If not, then update levels
3014 (setq indent (current-indentation))
3015 (setq levels (markdown-update-list-levels (match-string 2)
3016 indent levels))))
3017 (end-of-line))
3018 levels)))
3020 (defun markdown-prev-list-item (level)
3021 "Search backward from point for a list item with indentation LEVEL.
3022 Set point to the beginning of the item, and return point, or nil
3023 upon failure."
3024 (let (bounds indent prev)
3025 (setq prev (point))
3026 (forward-line -1)
3027 (setq indent (current-indentation))
3028 (while
3029 (cond
3030 ;; List item
3031 ((and (looking-at-p markdown-regex-list)
3032 (setq bounds (markdown-cur-list-item-bounds)))
3033 (cond
3034 ;; Stop and return point at item of lesser or equal indentation
3035 ((<= (nth 3 bounds) level)
3036 (setq prev (point))
3037 nil)
3038 ;; Stop at beginning of buffer
3039 ((bobp) (setq prev nil))
3040 ;; Continue at item with greater indentation
3041 ((> (nth 3 bounds) level) t)))
3042 ;; Stop at beginning of buffer
3043 ((bobp) (setq prev nil))
3044 ;; Continue if current line is blank
3045 ((markdown-cur-line-blank-p) t)
3046 ;; Continue while indentation is the same or greater
3047 ((>= indent level) t)
3048 ;; Stop if current indentation is less than list item
3049 ;; and the next is blank
3050 ((and (< indent level)
3051 (markdown-next-line-blank-p))
3052 (setq prev nil))
3053 ;; Stop at a header
3054 ((looking-at-p markdown-regex-header) (setq prev nil))
3055 ;; Stop at a horizontal rule
3056 ((looking-at-p markdown-regex-hr) (setq prev nil))
3057 ;; Otherwise, continue.
3058 (t t))
3059 (forward-line -1)
3060 (setq indent (current-indentation)))
3061 prev))
3063 (defun markdown-next-list-item (level)
3064 "Search forward from point for the next list item with indentation LEVEL.
3065 Set point to the beginning of the item, and return point, or nil
3066 upon failure."
3067 (let (bounds indent next)
3068 (setq next (point))
3069 (forward-line)
3070 (setq indent (current-indentation))
3071 (while
3072 (cond
3073 ;; Stop at end of the buffer.
3074 ((eobp) nil)
3075 ;; Continue if the current line is blank
3076 ((markdown-cur-line-blank-p) t)
3077 ;; List item
3078 ((and (looking-at-p markdown-regex-list)
3079 (setq bounds (markdown-cur-list-item-bounds)))
3080 (cond
3081 ;; Continue at item with greater indentation
3082 ((> (nth 3 bounds) level) t)
3083 ;; Stop and return point at item of equal indentation
3084 ((= (nth 3 bounds) level)
3085 (setq next (point))
3086 nil)
3087 ;; Stop and return nil at item with lesser indentation
3088 ((< (nth 3 bounds) level)
3089 (setq next nil)
3090 nil)))
3091 ;; Continue while indentation is the same or greater
3092 ((>= indent level) t)
3093 ;; Stop if current indentation is less than list item
3094 ;; and the previous line was blank.
3095 ((and (< indent level)
3096 (markdown-prev-line-blank-p))
3097 (setq next nil))
3098 ;; Stop at a header
3099 ((looking-at-p markdown-regex-header) (setq next nil))
3100 ;; Stop at a horizontal rule
3101 ((looking-at-p markdown-regex-hr) (setq next nil))
3102 ;; Otherwise, continue.
3103 (t t))
3104 (forward-line)
3105 (setq indent (current-indentation)))
3106 next))
3108 (defun markdown-cur-list-item-end (level)
3109 "Move to the end of the current list item with nonlist indentation LEVEL.
3110 If the point is not in a list item, do nothing."
3111 (let (indent)
3112 (forward-line)
3113 (setq indent (current-indentation))
3114 (while
3115 (cond
3116 ;; Stop at end of the buffer.
3117 ((eobp) nil)
3118 ;; Continue if the current line is blank
3119 ((markdown-cur-line-blank-p) t)
3120 ;; Continue while indentation is the same or greater
3121 ((>= indent level) t)
3122 ;; Stop if current indentation is less than list item
3123 ;; and the previous line was blank.
3124 ((and (< indent level)
3125 (markdown-prev-line-blank-p))
3126 nil)
3127 ;; Stop at a new list item of the same or lesser indentation
3128 ((looking-at-p markdown-regex-list) nil)
3129 ;; Stop at a header
3130 ((looking-at-p markdown-regex-header) nil)
3131 ;; Stop at a horizontal rule
3132 ((looking-at-p markdown-regex-hr) nil)
3133 ;; Otherwise, continue.
3134 (t t))
3135 (forward-line)
3136 (setq indent (current-indentation)))
3137 ;; Don't skip over whitespace for empty list items (marker and
3138 ;; whitespace only), just move to end of whitespace.
3139 (if (looking-back (concat markdown-regex-list "\\s-*") nil)
3140 (goto-char (match-end 3))
3141 (skip-syntax-backward "-"))))
3143 (defun markdown-cur-list-item-bounds ()
3144 "Return bounds and indentation of the current list item.
3145 Return a list of the following form:
3147 (begin end indent nonlist-indent marker checkbox)
3149 The named components are:
3151 - begin: Position of beginning of list item, including leading indentation.
3152 - end: Position of the end of the list item, including list item text.
3153 - indent: Number of characters of indentation before list marker (an integer).
3154 - nonlist-indent: Number characters of indentation, list
3155 marker, and whitespace following list marker (an integer).
3156 - marker: String containing the list marker and following whitespace
3157 (e.g., \"- \" or \"* \").
3159 As an example, for the following unordered list item
3161 - item
3163 the returned list would be
3165 (1 14 3 5 \"- \")
3167 If the point is not inside a list item, return nil.
3168 Leave match data intact for `markdown-regex-list'."
3169 (let (cur prev-begin prev-end indent nonlist-indent marker)
3170 ;; Store current location
3171 (setq cur (point))
3172 ;; Verify that cur is between beginning and end of item
3173 (save-excursion
3174 (end-of-line)
3175 (when (re-search-backward markdown-regex-list nil t)
3176 (setq prev-begin (match-beginning 0))
3177 (setq indent (length (match-string-no-properties 1)))
3178 (setq nonlist-indent (length (match-string 0)))
3179 (setq marker (concat (match-string-no-properties 2)
3180 (match-string-no-properties 3)))
3181 (save-match-data
3182 (markdown-cur-list-item-end nonlist-indent)
3183 (setq prev-end (point)))
3184 (when (and (>= cur prev-begin)
3185 (<= cur prev-end)
3186 nonlist-indent)
3187 (list prev-begin prev-end indent nonlist-indent marker))))))
3189 (defun markdown-list-item-at-point-p ()
3190 "Return t if there is a list item at the point and nil otherwise."
3191 (save-match-data (markdown-cur-list-item-bounds)))
3193 (defun markdown-bounds-of-thing-at-point (thing)
3194 "Call `bounds-of-thing-at-point' for THING with slight modifications.
3195 Does not include trailing newlines when THING is 'line. Handles the
3196 end of buffer case by setting both endpoints equal to the value of
3197 `point-max', since an empty region will trigger empty markup insertion.
3198 Return bounds of form (beg . end) if THING is found, or nil otherwise."
3199 (let* ((bounds (bounds-of-thing-at-point thing))
3200 (a (car bounds))
3201 (b (cdr bounds)))
3202 (when bounds
3203 (when (eq thing 'line)
3204 (cond ((and (eobp) (markdown-cur-line-blank-p))
3205 (setq a b))
3206 ((char-equal (char-before b) ?\^J)
3207 (setq b (1- b)))))
3208 (cons a b))))
3210 (defun markdown-reference-definition (reference)
3211 "Find out whether Markdown REFERENCE is defined.
3212 REFERENCE should not include the square brackets.
3213 When REFERENCE is defined, return a list of the form (text start end)
3214 containing the definition text itself followed by the start and end
3215 locations of the text. Otherwise, return nil.
3216 Leave match data for `markdown-regex-reference-definition'
3217 intact additional processing."
3218 (let ((reference (downcase reference)))
3219 (save-excursion
3220 (goto-char (point-min))
3221 (catch 'found
3222 (while (re-search-forward markdown-regex-reference-definition nil t)
3223 (when (string= reference (downcase (match-string-no-properties 2)))
3224 (throw 'found
3225 (list (match-string-no-properties 5)
3226 (match-beginning 5) (match-end 5)))))))))
3228 (defun markdown-get-defined-references ()
3229 "Return a list of all defined reference labels (not including square brackets)."
3230 (save-excursion
3231 (goto-char (point-min))
3232 (let (refs)
3233 (while (re-search-forward markdown-regex-reference-definition nil t)
3234 (let ((target (match-string-no-properties 2)))
3235 (cl-pushnew target refs :test #'equal)))
3236 (reverse refs))))
3238 (defun markdown-get-used-uris ()
3239 "Return a list of all used URIs in the buffer."
3240 (save-excursion
3241 (goto-char (point-min))
3242 (let (uris)
3243 (while (re-search-forward
3244 (concat "\\(?:" markdown-regex-link-inline
3245 "\\|" markdown-regex-angle-uri
3246 "\\|" markdown-regex-uri
3247 "\\|" markdown-regex-email
3248 "\\)")
3249 nil t)
3250 (unless (or (markdown-inline-code-at-point-p)
3251 (markdown-code-block-at-point-p))
3252 (cl-pushnew (or (match-string-no-properties 6)
3253 (match-string-no-properties 10)
3254 (match-string-no-properties 12)
3255 (match-string-no-properties 13))
3256 uris :test #'equal)))
3257 (reverse uris))))
3259 (defun markdown-inline-code-at-pos (pos)
3260 "Return non-nil if there is an inline code fragment at POS.
3261 Return nil otherwise. Set match data according to
3262 `markdown-match-code' upon success.
3263 This function searches the block for a code fragment that
3264 contains the point using `markdown-match-code'. We do this
3265 because `thing-at-point-looking-at' does not work reliably with
3266 `markdown-regex-code'.
3268 The match data is set as follows:
3269 Group 1 matches the opening backquotes.
3270 Group 2 matches the code fragment itself, without backquotes.
3271 Group 3 matches the closing backquotes."
3272 (save-excursion
3273 (goto-char pos)
3274 (let ((old-point (point))
3275 (end-of-block (progn (markdown-end-of-text-block) (point)))
3276 found)
3277 (markdown-beginning-of-text-block)
3278 (while (and (markdown-match-code end-of-block)
3279 (setq found t)
3280 (< (match-end 0) old-point)))
3281 (and found ; matched something
3282 (<= (match-beginning 0) old-point) ; match contains old-point
3283 (>= (match-end 0) old-point)))))
3285 (defun markdown-inline-code-at-pos-p (pos)
3286 "Return non-nil if there is an inline code fragment at POS.
3287 Like `markdown-inline-code-at-pos`, but preserves match data."
3288 (save-match-data (markdown-inline-code-at-pos pos)))
3290 (defun markdown-inline-code-at-point ()
3291 "Return non-nil if the point is at an inline code fragment.
3292 See `markdown-inline-code-at-pos' for details."
3293 (markdown-inline-code-at-pos (point)))
3295 (defun markdown-inline-code-at-point-p ()
3296 "Return non-nil if there is inline code at the point.
3297 This is a predicate function counterpart to
3298 `markdown-inline-code-at-point' which does not modify the match
3299 data. See `markdown-code-block-at-point-p' for code blocks."
3300 (save-match-data (markdown-inline-code-at-pos (point))))
3302 (make-obsolete 'markdown-code-at-point-p 'markdown-inline-code-at-point-p "v2.2")
3304 (defun markdown-code-block-at-pos (pos)
3305 "Return match data list if there is a code block at POS.
3306 Uses text properties at the beginning of the line position.
3307 This includes pre blocks, tilde-fenced code blocks, and GFM
3308 quoted code blocks. Return nil otherwise."
3309 (setq pos (save-excursion (goto-char pos) (point-at-bol)))
3310 (or (get-text-property pos 'markdown-pre)
3311 (markdown-get-enclosing-fenced-block-construct pos)
3312 ;; polymode removes text properties set by markdown-mode, so
3313 ;; check if `poly-markdown-mode' is active and whether the
3314 ;; `chunkmode' property is non-nil at POS.
3315 (and (bound-and-true-p poly-markdown-mode)
3316 (get-text-property pos 'chunkmode))))
3318 ;; Function was renamed to emphasize that it does not modify match-data.
3319 (defalias 'markdown-code-block-at-point 'markdown-code-block-at-point-p)
3321 (defun markdown-code-block-at-point-p ()
3322 "Return non-nil if there is a code block at the point.
3323 This includes pre blocks, tilde-fenced code blocks, and GFM
3324 quoted code blocks. This function does not modify the match
3325 data. See `markdown-inline-code-at-point-p' for inline code."
3326 (save-match-data (markdown-code-block-at-pos (point))))
3328 (defun markdown-heading-at-point ()
3329 "Return non-nil if there is a heading at the point.
3330 Set match data for `markdown-regex-header'."
3331 (let ((match-data (get-text-property (point) 'markdown-heading)))
3332 (when match-data
3333 (set-match-data match-data)
3334 t)))
3336 (defun markdown-pipe-at-bol-p ()
3337 "Return non-nil if the line begins with a pipe symbol.
3338 This may be useful for tables and Pandoc's line_blocks extension."
3339 (char-equal (char-after (point-at-bol)) ?|))
3342 ;;; Markdown Font Lock Matching Functions =====================================
3344 (defun markdown-range-property-any (begin end prop prop-values)
3345 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
3346 Also returns t if PROP is a list containing one of the PROP-VALUES.
3347 Return nil otherwise."
3348 (let (props)
3349 (catch 'found
3350 (dolist (loc (number-sequence begin end))
3351 (when (setq props (get-text-property loc prop))
3352 (cond ((listp props)
3353 ;; props is a list, check for membership
3354 (dolist (val prop-values)
3355 (when (memq val props) (throw 'found loc))))
3357 ;; props is a scalar, check for equality
3358 (dolist (val prop-values)
3359 (when (eq val props) (throw 'found loc))))))))))
3361 (defun markdown-range-properties-exist (begin end props)
3362 (cl-loop
3363 for loc in (number-sequence begin end)
3364 with result = nil
3365 while (not
3366 (setq result
3367 (cl-some (lambda (prop) (get-text-property loc prop)) props)))
3368 finally return result))
3370 (defun markdown-match-inline-generic (regex last &optional faceless)
3371 "Match inline REGEX from the point to LAST.
3372 When FACELESS is non-nil, do not return matches where faces have been applied."
3373 (when (re-search-forward regex last t)
3374 (let ((bounds (markdown-code-block-at-pos (match-beginning 1)))
3375 (face (and faceless (text-property-not-all
3376 (match-beginning 0) (match-end 0) 'face nil))))
3377 (cond
3378 ;; In code block: move past it and recursively search again
3379 (bounds
3380 (when (< (goto-char (cl-second bounds)) last)
3381 (markdown-match-inline-generic regex last faceless)))
3382 ;; When faces are found in the match range, skip over the match and
3383 ;; recursively search again.
3384 (face
3385 (when (< (goto-char (match-end 0)) last)
3386 (markdown-match-inline-generic regex last faceless)))
3387 ;; Keep match data and return t when in bounds.
3389 (<= (match-end 0) last))))))
3391 (defun markdown-match-code (last)
3392 "Match inline code fragments from point to LAST."
3393 (unless (bobp)
3394 (backward-char 1))
3395 (when (markdown-match-inline-generic markdown-regex-code last)
3396 (let ((begin (match-beginning 1))
3397 (end (match-end 1))
3398 (open-begin (match-beginning 2))
3399 (open-end (match-end 2))
3400 (code-begin (match-beginning 3))
3401 (code-end (match-end 3))
3402 (close-begin (match-beginning 4))
3403 (close-end (match-end 4)))
3404 (if (or (markdown-in-comment-p begin)
3405 (markdown-in-comment-p end)
3406 (markdown-code-block-at-pos begin))
3407 (progn (goto-char (min (1+ begin) last))
3408 (when (< (point) last)
3409 (markdown-match-code last)))
3410 (set-match-data (list begin end
3411 open-begin open-end
3412 code-begin code-end
3413 close-begin close-end))
3414 t))))
3416 (defun markdown-match-bold (last)
3417 "Match inline bold from the point to LAST."
3418 (when (markdown-match-inline-generic markdown-regex-bold last)
3419 (let ((begin (match-beginning 2))
3420 (end (match-end 2)))
3421 (if (or (markdown-inline-code-at-pos-p begin)
3422 (markdown-inline-code-at-pos-p end)
3423 (markdown-in-comment-p)
3424 (markdown-range-property-any
3425 begin begin 'face '(markdown-url-face
3426 markdown-plain-url-face))
3427 (markdown-range-property-any
3428 begin end 'face '(markdown-inline-code-face
3429 markdown-math-face)))
3430 (progn (goto-char (min (1+ begin) last))
3431 (when (< (point) last)
3432 (markdown-match-italic last)))
3433 (set-match-data (list (match-beginning 2) (match-end 2)
3434 (match-beginning 3) (match-end 3)
3435 (match-beginning 4) (match-end 4)
3436 (match-beginning 5) (match-end 5)))
3437 t))))
3439 (defun markdown-match-italic (last)
3440 "Match inline italics from the point to LAST."
3441 (let ((regex (if (eq major-mode 'gfm-mode)
3442 markdown-regex-gfm-italic markdown-regex-italic)))
3443 (when (markdown-match-inline-generic regex last)
3444 (let ((begin (match-beginning 1))
3445 (end (match-end 1)))
3446 (if (or (markdown-inline-code-at-pos-p begin)
3447 (markdown-inline-code-at-pos-p end)
3448 (markdown-in-comment-p)
3449 (markdown-range-property-any
3450 begin begin 'face '(markdown-url-face
3451 markdown-plain-url-face))
3452 (markdown-range-property-any
3453 begin end 'face '(markdown-inline-code-face
3454 markdown-bold-face
3455 markdown-list-face
3456 markdown-math-face)))
3457 (progn (goto-char (min (1+ begin) last))
3458 (when (< (point) last)
3459 (markdown-match-italic last)))
3460 (set-match-data (list (match-beginning 1) (match-end 1)
3461 (match-beginning 2) (match-end 2)
3462 (match-beginning 3) (match-end 3)
3463 (match-beginning 4) (match-end 4)))
3464 t)))))
3466 (defun markdown-match-math-generic (regex last)
3467 "Match REGEX from point to LAST.
3468 REGEX is either `markdown-regex-math-inline-single' for matching
3469 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
3470 (when (and markdown-enable-math (markdown-match-inline-generic regex last))
3471 (let ((begin (match-beginning 1)) (end (match-end 1)))
3472 (prog1
3473 (if (or (markdown-range-property-any
3474 begin end 'face (list markdown-inline-code-face
3475 markdown-bold-face))
3476 (markdown-range-properties-exist
3477 begin end
3478 (markdown-get-fenced-block-middle-properties)))
3479 (markdown-match-math-generic regex last)
3481 (goto-char (1+ (match-end 0)))))))
3483 (defun markdown-match-list-items (last)
3484 "Match list items from point to LAST."
3485 (when (markdown-match-inline-generic markdown-regex-list last)
3486 (let ((begin (match-beginning 2))
3487 (end (match-end 2)))
3488 (if (or (markdown-range-property-any
3489 begin end 'face (list markdown-inline-code-face
3490 markdown-bold-face
3491 markdown-math-face))
3492 (markdown-range-properties-exist begin end '(markdown-hr))
3493 (markdown-in-comment-p))
3494 (progn (goto-char (min (1+ (match-end 0)) last))
3495 (markdown-match-list-items last))
3496 (set-match-data (list (match-beginning 0) (match-end 0)
3497 (match-beginning 1) (match-end 1)
3498 (match-beginning 2) (match-end 2)))
3499 (goto-char (1+ (match-end 0)))))))
3501 (defun markdown-match-math-single (last)
3502 "Match single quoted $..$ math from point to LAST."
3503 (markdown-match-math-generic markdown-regex-math-inline-single last))
3505 (defun markdown-match-math-double (last)
3506 "Match double quoted $$..$$ math from point to LAST."
3507 (markdown-match-math-generic markdown-regex-math-inline-double last))
3509 (defun markdown-match-propertized-text (property last)
3510 "Match text with PROPERTY from point to LAST.
3511 Restore match data previously stored in PROPERTY."
3512 (let ((saved (get-text-property (point) property))
3513 pos)
3514 (unless saved
3515 (setq pos (next-single-char-property-change (point) property nil last))
3516 (setq saved (get-text-property pos property)))
3517 (when saved
3518 (set-match-data saved)
3519 ;; Step at least one character beyond point. Otherwise
3520 ;; `font-lock-fontify-keywords-region' infloops.
3521 (goto-char (min (1+ (max (match-end 0) (point)))
3522 (point-max)))
3523 saved)))
3525 (defun markdown-match-pre-blocks (last)
3526 "Match preformatted blocks from point to LAST.
3527 Use data stored in 'markdown-pre text property during syntax
3528 analysis."
3529 (markdown-match-propertized-text 'markdown-pre last))
3531 (defun markdown-match-gfm-code-blocks (last)
3532 "Match GFM quoted code blocks from point to LAST.
3533 Use data stored in 'markdown-gfm-code text property during syntax
3534 analysis."
3535 (markdown-match-propertized-text 'markdown-gfm-code last))
3537 (defun markdown-match-gfm-open-code-blocks (last)
3538 (markdown-match-propertized-text 'markdown-gfm-block-begin last))
3540 (defun markdown-match-gfm-close-code-blocks (last)
3541 (markdown-match-propertized-text 'markdown-gfm-block-end last))
3543 (defun markdown-match-fenced-code-blocks (last)
3544 "Match fenced code blocks from the point to LAST."
3545 (markdown-match-propertized-text 'markdown-fenced-code last))
3547 (defun markdown-match-fenced-start-code-block (last)
3548 (markdown-match-propertized-text 'markdown-tilde-fence-begin last))
3550 (defun markdown-match-fenced-end-code-block (last)
3551 (markdown-match-propertized-text 'markdown-tilde-fence-end last))
3553 (defun markdown-match-blockquotes (last)
3554 "Match blockquotes from point to LAST.
3555 Use data stored in 'markdown-blockquote text property during syntax
3556 analysis."
3557 (markdown-match-propertized-text 'markdown-blockquote last))
3559 (defun markdown-match-hr (last)
3560 "Match horizontal rules comments from the point to LAST."
3561 (markdown-match-propertized-text 'markdown-hr last))
3563 (defun markdown-match-comments (last)
3564 "Match HTML comments from the point to LAST."
3565 (when (and (skip-syntax-forward "^<" last))
3566 (let ((beg (point)))
3567 (when (and (skip-syntax-forward "^>" last) (< (point) last))
3568 (forward-char)
3569 (set-match-data (list beg (point)))
3570 t))))
3572 (defun markdown-match-generic-links (last ref)
3573 "Match inline links from point to LAST.
3574 When REF is non-nil, match reference links instead of standard
3575 links with URLs."
3576 ;; Search for the next potential link (not in a code block).
3577 (while (and (progn
3578 ;; Clear match data to test for a match after functions returns.
3579 (set-match-data nil)
3580 (re-search-forward "\\(!\\)?\\(\\[\\)" last 'limit))
3581 ;; Keep searching if this is in a code block, inline
3582 ;; code, or a comment, or if it is include syntax.
3583 (or (markdown-code-block-at-point-p)
3584 (markdown-inline-code-at-pos-p (match-beginning 0))
3585 (markdown-inline-code-at-pos-p (match-end 0))
3586 (markdown-in-comment-p)
3587 (and (char-equal (char-after (point-at-bol)) ?<)
3588 (char-equal (char-after (1+ (point-at-bol))) ?<)))
3589 (< (point) last)))
3590 ;; Match opening exclamation point (optional) and left bracket.
3591 (when (match-beginning 2)
3592 (let* ((bang (match-beginning 1))
3593 (first-begin (match-beginning 2))
3594 ;; Find end of block to prevent matching across blocks.
3595 (end-of-block (save-excursion
3596 (progn
3597 (goto-char (match-beginning 2))
3598 (markdown-end-of-text-block)
3599 (point))))
3600 ;; Move over balanced expressions to closing right bracket.
3601 ;; Catch unbalanced expression errors and return nil.
3602 (first-end (condition-case nil
3603 (and (goto-char first-begin)
3604 (scan-sexps (point) 1))
3605 (error nil)))
3606 ;; Continue with point at CONT-POINT upon failure.
3607 (cont-point (min (1+ first-begin) last))
3608 second-begin second-end url-begin url-end
3609 title-begin title-end)
3610 ;; When bracket found, in range, and followed by a left paren/bracket...
3611 (when (and first-end (< first-end end-of-block) (goto-char first-end)
3612 (char-equal (char-after (point)) (if ref ?\[ ?\()))
3613 ;; Scan across balanced expressions for closing parenthesis/bracket.
3614 (setq second-begin (point)
3615 second-end (condition-case nil
3616 (scan-sexps (point) 1)
3617 (error nil)))
3618 ;; Check that closing parenthesis/bracket is in range.
3619 (if (and second-end (<= second-end end-of-block) (<= second-end last))
3620 (progn
3621 ;; Search for (optional) title inside closing parenthesis
3622 (when (and (not ref) (search-forward "\"" second-end t))
3623 (setq title-begin (1- (point))
3624 title-end (and (goto-char second-end)
3625 (search-backward "\"" (1+ title-begin) t))
3626 title-end (and title-end (1+ title-end))))
3627 ;; Store URL/reference range
3628 (setq url-begin (1+ second-begin)
3629 url-end (1- (or title-begin second-end)))
3630 ;; Set match data, move point beyond link, and return
3631 (set-match-data
3632 (list (or bang first-begin) second-end ; 0 - all
3633 bang (and bang (1+ bang)) ; 1 - bang
3634 first-begin (1+ first-begin) ; 2 - markup
3635 (1+ first-begin) (1- first-end) ; 3 - link text
3636 (1- first-end) first-end ; 4 - markup
3637 second-begin (1+ second-begin) ; 5 - markup
3638 url-begin url-end ; 6 - url/reference
3639 title-begin title-end ; 7 - title
3640 (1- second-end) second-end)) ; 8 - markup
3641 ;; Nullify cont-point and leave point at end and
3642 (setq cont-point nil)
3643 (goto-char second-end))
3644 ;; If no closing parenthesis in range, update continuation point
3645 (setq cont-point (min end-of-block last))))
3646 (cond
3647 ;; On failure, continue searching at cont-point
3648 ((and cont-point (< cont-point last))
3649 ;;(message "Failure, starting over at cont-point = %d" cont-point)
3650 (goto-char cont-point)
3651 (markdown-match-generic-links last ref))
3652 ;; No more text, return nil
3653 ((and cont-point (= cont-point last))
3654 nil)
3655 ;; Return t if a match occurred
3656 (t t)))))
3658 (defun markdown-match-inline-links (last)
3659 "Match standard inline links from point to LAST."
3660 (markdown-match-generic-links last nil))
3662 (defun markdown-match-reference-links (last)
3663 "Match inline reference links from point to LAST."
3664 (markdown-match-generic-links last t))
3666 (defun markdown-match-angle-uris (last)
3667 "Match angle bracket URIs from point to LAST."
3668 (when (markdown-match-inline-generic markdown-regex-angle-uri last)
3669 (goto-char (1+ (match-end 0)))))
3671 (defun markdown-match-plain-uris (last)
3672 "Match plain URIs from point to LAST."
3673 (when (markdown-match-inline-generic markdown-regex-uri last t)
3674 (goto-char (1+ (match-end 0)))))
3676 (defun markdown-get-match-boundaries (start-header end-header last &optional pos)
3677 (save-excursion
3678 (goto-char (or pos (point-min)))
3679 (cl-loop
3680 with cur-result = nil
3681 and st-hdr = (or start-header "\\`")
3682 and end-hdr = (or end-header "\n\n\\|\n\\'\\|\\'")
3683 while (and (< (point) last)
3684 (re-search-forward st-hdr last t)
3685 (progn
3686 (setq cur-result (match-data))
3687 (re-search-forward end-hdr nil t)))
3688 collect (list cur-result (match-data)))))
3690 (defvar markdown-conditional-search-function #'re-search-forward
3691 "Conditional search function used in `markdown-search-until-condition'.
3692 Made into a variable to allow for dynamic let-binding.")
3694 (defun markdown-search-until-condition (condition &rest args)
3695 (let (ret)
3696 (while (and (not ret) (apply markdown-conditional-search-function args))
3697 (setq ret (funcall condition)))
3698 ret))
3700 (defun markdown-match-generic-metadata
3701 (regexp last &optional start-header end-header)
3702 "Match generic metadata specified by REGEXP from the point to LAST.
3703 If START-HEADER is nil, we assume metadata can only occur at the
3704 very top of a file (\"\\`\"). If END-HEADER is nil, we assume it
3705 is \"\n\n\""
3706 (let* ((header-bounds
3707 (markdown-get-match-boundaries start-header end-header last))
3708 (enclosing-header
3709 (cl-find-if ; just take first if multiple
3710 (lambda (match-bounds)
3711 (cl-destructuring-bind (begin end) (cl-second match-bounds)
3712 (and (< (point) begin)
3713 (save-excursion (re-search-forward regexp end t)))))
3714 header-bounds))
3715 (header-begin
3716 (when enclosing-header (cl-second (cl-first enclosing-header))))
3717 (header-end
3718 (when enclosing-header (cl-first (cl-second enclosing-header)))))
3719 (cond ((null enclosing-header)
3720 ;; Don't match anything outside of a header.
3721 nil)
3722 ((markdown-search-until-condition
3723 (lambda () (> (point) header-begin)) regexp (min last header-end) t)
3724 ;; If a metadata item is found, it may span several lines.
3725 (let ((key-beginning (match-beginning 1))
3726 (key-end (match-end 1))
3727 (markup-begin (match-beginning 2))
3728 (markup-end (match-end 2))
3729 (value-beginning (match-beginning 3)))
3730 (set-match-data (list key-beginning (point) ; complete metadata
3731 key-beginning key-end ; key
3732 markup-begin markup-end ; markup
3733 value-beginning (point))) ; value
3735 (t nil))))
3737 (defun markdown-match-declarative-metadata (last)
3738 "Match declarative metadata from the point to LAST."
3739 (markdown-match-generic-metadata markdown-regex-declarative-metadata last))
3741 (defun markdown-match-pandoc-metadata (last)
3742 "Match Pandoc metadata from the point to LAST."
3743 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
3745 (defun markdown-match-yaml-metadata-begin (last)
3746 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last))
3748 (defun markdown-match-yaml-metadata-end (last)
3749 (markdown-match-propertized-text 'markdown-yaml-metadata-end last))
3751 (defun markdown-match-yaml-metadata-key (last)
3752 (markdown-match-propertized-text 'markdown-metadata-key last))
3754 (defun markdown-match-inline-attributes (last)
3755 "Match inline attributes from point to LAST."
3756 (when (markdown-match-inline-generic markdown-regex-inline-attributes last)
3757 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
3758 (markdown-inline-code-at-pos-p (match-end 0))
3759 (markdown-in-comment-p))
3760 t)))
3762 (defun markdown-match-leanpub-sections (last)
3763 "Match Leanpub section markers from point to LAST."
3764 (when (markdown-match-inline-generic markdown-regex-leanpub-sections last)
3765 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
3766 (markdown-inline-code-at-pos-p (match-end 0))
3767 (markdown-in-comment-p))
3768 t)))
3770 (defun markdown-match-includes (last)
3771 "Match include statements from point to LAST.
3772 Sets match data for the following seven groups:
3773 Group 1: opening two angle brackets
3774 Group 2: opening title delimiter (optional)
3775 Group 3: title text (optional)
3776 Group 4: closing title delimiter (optional)
3777 Group 5: opening filename delimiter
3778 Group 6: filename
3779 Group 7: closing filename delimiter"
3780 (when (markdown-match-inline-generic markdown-regex-include last)
3781 (let ((valid (not (or (markdown-in-comment-p (match-beginning 0))
3782 (markdown-in-comment-p (match-end 0))
3783 (markdown-code-block-at-pos (match-beginning 0))))))
3784 (cond
3785 ;; Parentheses and maybe square brackets, but no curly braces:
3786 ;; match optional title in square brackets and file in parentheses.
3787 ((and valid (match-beginning 5)
3788 (not (match-beginning 8)))
3789 (set-match-data (list (match-beginning 1) (match-end 7)
3790 (match-beginning 1) (match-end 1)
3791 (match-beginning 2) (match-end 2)
3792 (match-beginning 3) (match-end 3)
3793 (match-beginning 4) (match-end 4)
3794 (match-beginning 5) (match-end 5)
3795 (match-beginning 6) (match-end 6)
3796 (match-beginning 7) (match-end 7))))
3797 ;; Only square brackets present: match file in square brackets.
3798 ((and valid (match-beginning 2)
3799 (not (match-beginning 5))
3800 (not (match-beginning 7)))
3801 (set-match-data (list (match-beginning 1) (match-end 4)
3802 (match-beginning 1) (match-end 1)
3803 nil nil
3804 nil nil
3805 nil nil
3806 (match-beginning 2) (match-end 2)
3807 (match-beginning 3) (match-end 3)
3808 (match-beginning 4) (match-end 4))))
3809 ;; Only curly braces present: match file in curly braces.
3810 ((and valid (match-beginning 8)
3811 (not (match-beginning 2))
3812 (not (match-beginning 5)))
3813 (set-match-data (list (match-beginning 1) (match-end 10)
3814 (match-beginning 1) (match-end 1)
3815 nil nil
3816 nil nil
3817 nil nil
3818 (match-beginning 8) (match-end 8)
3819 (match-beginning 9) (match-end 9)
3820 (match-beginning 10) (match-end 10))))
3822 ;; Not a valid match, move to next line and search again.
3823 (forward-line)
3824 (when (< (point) last)
3825 (setq valid (markdown-match-includes last)))))
3826 valid)))
3829 ;;; Markdown Font Fontification Functions =====================================
3831 (defun markdown-fontify-headings (last)
3832 "Add text properties to headings from point to LAST."
3833 (when (markdown-match-propertized-text 'markdown-heading last)
3834 (let* ((level (markdown-outline-level))
3835 (heading-face
3836 (intern (format "markdown-header-face-%d" level)))
3837 (heading-props `(face ,heading-face))
3838 (markup-props `(face markdown-header-delimiter-face
3839 ,@(when markdown-hide-markup `(display ""))))
3840 (rule-props `(face markdown-header-rule-face
3841 ,@(when markdown-hide-markup `(display "")))))
3842 (if (match-end 1)
3843 ;; Setext heading
3844 (progn (add-text-properties
3845 (match-beginning 1) (match-end 1) heading-props)
3846 (if (= level 1)
3847 (add-text-properties
3848 (match-beginning 2) (match-end 2) rule-props)
3849 (add-text-properties
3850 (match-beginning 3) (match-end 3) rule-props)))
3851 ;; atx heading
3852 (add-text-properties
3853 (match-beginning 4) (match-end 4) markup-props)
3854 (add-text-properties
3855 (match-beginning 5) (match-end 5) heading-props)
3856 (when (match-end 6)
3857 (add-text-properties
3858 (match-beginning 6) (match-end 6) markup-props))))
3861 (defun markdown-fontify-blockquotes (last)
3862 "Apply font-lock properties to blockquotes from point to LAST."
3863 (when (markdown-match-blockquotes last)
3864 (add-text-properties
3865 (match-beginning 1) (match-end 1)
3866 (if markdown-hide-markup
3867 `(face markdown-blockquote-face
3868 display ,markdown-blockquote-display-char)
3869 `(face markdown-markup-face
3870 ,@(when markdown-hide-markup
3871 `(display ,markdown-blockquote-display-char)))))
3872 (font-lock-append-text-property
3873 (match-beginning 0) (match-end 0) 'face 'markdown-blockquote-face)
3876 (defun markdown-fontify-list-items (last)
3877 "Apply font-lock properties to list markers from point to LAST."
3878 (when (markdown-match-list-items last)
3879 (let* ((indent (length (match-string-no-properties 1)))
3880 (level (/ indent 4)) ;; level = 0, 1, 2, ...
3881 (bullet (nth (mod level (length markdown-list-item-bullets))
3882 markdown-list-item-bullets)))
3883 (add-text-properties
3884 (match-beginning 2) (match-end 2) '(face markdown-list-face))
3885 (when markdown-hide-markup
3886 (cond
3887 ;; Unordered lists
3888 ((string-match-p "[\\*\\+-]" (match-string 2))
3889 (add-text-properties
3890 (match-beginning 2) (match-end 2) `(display ,bullet)))
3891 ;; Definition lists
3892 ((string-equal ":" (match-string 2))
3893 (add-text-properties
3894 (match-beginning 2) (match-end 2)
3895 `(display ,(char-to-string markdown-definition-display-char)))))))
3898 (defun markdown-fontify-hrs (last)
3899 "Add text properties to horizontal rules from point to LAST."
3900 (when (markdown-match-hr last)
3901 (add-text-properties
3902 (match-beginning 0) (match-end 0)
3903 `(face markdown-hr-face
3904 font-lock-multiline t
3905 ,@(when markdown-hide-markup
3906 `(display ,(make-string
3907 (window-body-width) markdown-hr-display-char)))))
3910 (defun markdown-fontify-sub-superscripts (last)
3911 "Apply text properties to sub- and superscripts from point to LAST."
3912 (when (markdown-search-until-condition
3913 (lambda () (and (not (markdown-code-block-at-point-p))
3914 (not (markdown-inline-code-at-point-p))
3915 (not (markdown-in-comment-p))))
3916 markdown-regex-sub-superscript last t)
3917 (let* ((subscript-p (string= (match-string 2) "~"))
3918 (index (if subscript-p 0 1))
3919 (mp (list 'face 'markdown-markup-face
3920 'invisible 'markdown-markup)))
3921 (when markdown-hide-markup
3922 (put-text-property (match-beginning 3) (match-end 3)
3923 'display
3924 (nth index markdown-sub-superscript-display)))
3925 (add-text-properties (match-beginning 2) (match-end 2) mp)
3926 (add-text-properties (match-beginning 4) (match-end 4) mp)
3927 t)))
3930 ;;; Syntax Table ==============================================================
3932 (defvar markdown-mode-syntax-table
3933 (let ((tab (make-syntax-table text-mode-syntax-table)))
3934 (modify-syntax-entry ?\" "." tab)
3935 tab)
3936 "Syntax table for `markdown-mode'.")
3939 ;;; Element Insertion =========================================================
3941 (defun markdown-ensure-blank-line-before ()
3942 "If previous line is not already blank, insert a blank line before point."
3943 (unless (bolp) (insert "\n"))
3944 (unless (or (bobp) (looking-back "\n\\s-*\n" nil)) (insert "\n")))
3946 (defun markdown-ensure-blank-line-after ()
3947 "If following line is not already blank, insert a blank line after point.
3948 Return the point where it was originally."
3949 (save-excursion
3950 (unless (eolp) (insert "\n"))
3951 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
3953 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
3954 "Insert the strings S1 and S2, wrapping around region or THING.
3955 If a region is specified by the optional BEG and END arguments,
3956 wrap the strings S1 and S2 around that region.
3957 If there is an active region, wrap the strings S1 and S2 around
3958 the region. If there is not an active region but the point is at
3959 THING, wrap that thing (which defaults to word). Otherwise, just
3960 insert S1 and S2 and place the cursor in between. Return the
3961 bounds of the entire wrapped string, or nil if nothing was wrapped
3962 and S1 and S2 were only inserted."
3963 (let (a b bounds new-point)
3964 (cond
3965 ;; Given region
3966 ((and beg end)
3967 (setq a beg
3968 b end
3969 new-point (+ (point) (length s1))))
3970 ;; Active region
3971 ((markdown-use-region-p)
3972 (setq a (region-beginning)
3973 b (region-end)
3974 new-point (+ (point) (length s1))))
3975 ;; Thing (word) at point
3976 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
3977 (setq a (car bounds)
3978 b (cdr bounds)
3979 new-point (+ (point) (length s1))))
3980 ;; No active region and no word
3982 (setq a (point)
3983 b (point))))
3984 (goto-char b)
3985 (insert s2)
3986 (goto-char a)
3987 (insert s1)
3988 (when new-point (goto-char new-point))
3989 (if (= a b)
3991 (setq b (+ b (length s1) (length s2)))
3992 (cons a b))))
3994 (defun markdown-point-after-unwrap (cur prefix suffix)
3995 "Return desired position of point after an unwrapping operation.
3996 CUR gives the position of the point before the operation.
3997 Additionally, two cons cells must be provided. PREFIX gives the
3998 bounds of the prefix string and SUFFIX gives the bounds of the
3999 suffix string."
4000 (cond ((< cur (cdr prefix)) (car prefix))
4001 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
4002 ((<= cur (cdr suffix))
4003 (- cur (+ (- (cdr prefix) (car prefix))
4004 (- cur (car suffix)))))
4005 (t cur)))
4007 (defun markdown-unwrap-thing-at-point (regexp all text)
4008 "Remove prefix and suffix of thing at point and reposition the point.
4009 When the thing at point matches REGEXP, replace the subexpression
4010 ALL with the string in subexpression TEXT. Reposition the point
4011 in an appropriate location accounting for the removal of prefix
4012 and suffix strings. Return new bounds of string from group TEXT.
4013 When REGEXP is nil, assumes match data is already set."
4014 (when (or (null regexp)
4015 (thing-at-point-looking-at regexp))
4016 (let ((cur (point))
4017 (prefix (cons (match-beginning all) (match-beginning text)))
4018 (suffix (cons (match-end text) (match-end all)))
4019 (bounds (cons (match-beginning text) (match-end text))))
4020 ;; Replace the thing at point
4021 (replace-match (match-string text) t t nil all)
4022 ;; Reposition the point
4023 (goto-char (markdown-point-after-unwrap cur prefix suffix))
4024 ;; Adjust bounds
4025 (setq bounds (cons (car prefix)
4026 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
4028 (defun markdown-unwrap-things-in-region (beg end regexp all text)
4029 "Remove prefix and suffix of all things in region from BEG to END.
4030 When a thing in the region matches REGEXP, replace the
4031 subexpression ALL with the string in subexpression TEXT.
4032 Return a cons cell containing updated bounds for the region."
4033 (save-excursion
4034 (goto-char beg)
4035 (let ((removed 0) len-all len-text)
4036 (while (re-search-forward regexp (- end removed) t)
4037 (setq len-all (length (match-string-no-properties all)))
4038 (setq len-text (length (match-string-no-properties text)))
4039 (setq removed (+ removed (- len-all len-text)))
4040 (replace-match (match-string text) t t nil all))
4041 (cons beg (- end removed)))))
4043 (defun markdown-insert-hr (arg)
4044 "Insert or replace a horizonal rule.
4045 By default, use the first element of `markdown-hr-strings'. When
4046 ARG is non-nil, as when given a prefix, select a different
4047 element as follows. When prefixed with \\[universal-argument],
4048 use the last element of `markdown-hr-strings' instead. When
4049 prefixed with an integer from 1 to the length of
4050 `markdown-hr-strings', use the element in that position instead."
4051 (interactive "*P")
4052 (when (thing-at-point-looking-at markdown-regex-hr)
4053 (delete-region (match-beginning 0) (match-end 0)))
4054 (markdown-ensure-blank-line-before)
4055 (cond ((equal arg '(4))
4056 (insert (car (reverse markdown-hr-strings))))
4057 ((and (integerp arg) (> arg 0)
4058 (<= arg (length markdown-hr-strings)))
4059 (insert (nth (1- arg) markdown-hr-strings)))
4061 (insert (car markdown-hr-strings))))
4062 (markdown-ensure-blank-line-after))
4064 (defun markdown-insert-bold ()
4065 "Insert markup to make a region or word bold.
4066 If there is an active region, make the region bold. If the point
4067 is at a non-bold word, make the word bold. If the point is at a
4068 bold word or phrase, remove the bold markup. Otherwise, simply
4069 insert bold delimiters and place the cursor in between them."
4070 (interactive)
4071 (let ((delim (if markdown-bold-underscore "__" "**")))
4072 (if (markdown-use-region-p)
4073 ;; Active region
4074 (let ((bounds (markdown-unwrap-things-in-region
4075 (region-beginning) (region-end)
4076 markdown-regex-bold 2 4)))
4077 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4078 ;; Bold markup removal, bold word at point, or empty markup insertion
4079 (if (thing-at-point-looking-at markdown-regex-bold)
4080 (markdown-unwrap-thing-at-point nil 2 4)
4081 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4083 (defun markdown-insert-italic ()
4084 "Insert markup to make a region or word italic.
4085 If there is an active region, make the region italic. If the point
4086 is at a non-italic word, make the word italic. If the point is at an
4087 italic word or phrase, remove the italic markup. Otherwise, simply
4088 insert italic delimiters and place the cursor in between them."
4089 (interactive)
4090 (let ((delim (if markdown-italic-underscore "_" "*")))
4091 (if (markdown-use-region-p)
4092 ;; Active region
4093 (let ((bounds (markdown-unwrap-things-in-region
4094 (region-beginning) (region-end)
4095 markdown-regex-italic 1 3)))
4096 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4097 ;; Italic markup removal, italic word at point, or empty markup insertion
4098 (if (thing-at-point-looking-at markdown-regex-italic)
4099 (markdown-unwrap-thing-at-point nil 1 3)
4100 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4102 (defun markdown-insert-strike-through ()
4103 "Insert markup to make a region or word strikethrough.
4104 If there is an active region, make the region strikethrough. If the point
4105 is at a non-bold word, make the word strikethrough. If the point is at a
4106 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
4107 simply insert bold delimiters and place the cursor in between them."
4108 (interactive)
4109 (let ((delim "~~"))
4110 (if (markdown-use-region-p)
4111 ;; Active region
4112 (let ((bounds (markdown-unwrap-things-in-region
4113 (region-beginning) (region-end)
4114 markdown-regex-strike-through 2 4)))
4115 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4116 ;; Strikethrough markup removal, strikethrough word at point, or empty markup insertion
4117 (if (thing-at-point-looking-at markdown-regex-strike-through)
4118 (markdown-unwrap-thing-at-point nil 2 4)
4119 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4121 (defun markdown-insert-code ()
4122 "Insert markup to make a region or word an inline code fragment.
4123 If there is an active region, make the region an inline code
4124 fragment. If the point is at a word, make the word an inline
4125 code fragment. Otherwise, simply insert code delimiters and
4126 place the cursor in between them."
4127 (interactive)
4128 (if (markdown-use-region-p)
4129 ;; Active region
4130 (let ((bounds (markdown-unwrap-things-in-region
4131 (region-beginning) (region-end)
4132 markdown-regex-code 1 3)))
4133 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
4134 ;; Code markup removal, code markup for word, or empty markup insertion
4135 (if (markdown-inline-code-at-point)
4136 (markdown-unwrap-thing-at-point nil 0 2)
4137 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
4139 (defun markdown-insert-kbd ()
4140 "Insert markup to wrap region or word in <kbd> tags.
4141 If there is an active region, use the region. If the point is at
4142 a word, use the word. Otherwise, simply insert <kbd> tags and
4143 place the cursor in between them."
4144 (interactive)
4145 (if (markdown-use-region-p)
4146 ;; Active region
4147 (let ((bounds (markdown-unwrap-things-in-region
4148 (region-beginning) (region-end)
4149 markdown-regex-kbd 0 2)))
4150 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil (car bounds) (cdr bounds)))
4151 ;; Markup removal, markup for word, or empty markup insertion
4152 (if (thing-at-point-looking-at markdown-regex-kbd)
4153 (markdown-unwrap-thing-at-point nil 0 2)
4154 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil))))
4156 (defun markdown-insert-inline-link (text url &optional title)
4157 "Insert an inline link with TEXT pointing to URL.
4158 Optionally, the user can provide a TITLE."
4159 (let ((cur (point)))
4160 (setq title (and title (concat " \"" title "\"")))
4161 (insert (concat "[" text "](" url title ")"))
4162 (cond ((not text) (goto-char (+ 1 cur)))
4163 ((not url) (goto-char (+ 3 (length text) cur))))))
4165 (defun markdown-insert-inline-link-dwim ()
4166 "Insert an inline link of the form [link](url) at point.
4167 If there is an active region, the text in the region will be used
4168 as the URL, if it appears to be a URL, or else as the link text.
4169 If the point is at a URL, use it to create a new link. If the
4170 point is at a reference link, convert it to an inline link. If
4171 the point is at a word, use the word as the link text. In these
4172 cases, the point will be left at the position for inserting a
4173 URL. If there is no active region and the point is not at word,
4174 simply insert link markup and place the point in the position to
4175 enter link text."
4176 (interactive)
4177 (cond
4178 ;; If there is an active region, remove existing links in the
4179 ;; region and use resulting region as link text for a new link.
4180 ((markdown-use-region-p)
4181 (let* ((bounds (markdown-unwrap-things-in-region
4182 (region-beginning) (region-end)
4183 markdown-regex-link-inline 0 3))
4184 (text (buffer-substring (car bounds) (cdr bounds))))
4185 (delete-region (car bounds) (cdr bounds))
4186 (markdown-insert-inline-link text nil)))
4187 ;; If there is an inline link at the point, remove it and add the
4188 ;; link text to the kill ring.
4189 ((thing-at-point-looking-at markdown-regex-link-inline)
4190 (kill-new (match-string 3))
4191 (delete-region (match-beginning 0) (match-end 0)))
4192 ;; If there is an angle URL at the point, use it for a new link.
4193 ((thing-at-point-looking-at markdown-regex-angle-uri)
4194 (let ((url (match-string 2)))
4195 (delete-region (match-beginning 0) (match-end 0))
4196 (markdown-insert-inline-link nil url)))
4197 ;; If there is a plain URL at the point, use it for a new link.
4198 ((thing-at-point-looking-at markdown-regex-uri)
4199 (let ((url (match-string 0)))
4200 (delete-region (match-beginning 0) (match-end 0))
4201 (markdown-insert-inline-link nil url)))
4202 ;; If there is a reference link at point, convert to inline link.
4203 ((thing-at-point-looking-at markdown-regex-link-reference)
4204 (let ((beg (match-beginning 0))
4205 (end (match-end 0))
4206 (text (match-string 3))
4207 (url (markdown-link-url)))
4208 (delete-region beg end)
4209 (markdown-insert-inline-link text url)))
4210 ;; Otherwise, insert a link
4211 (t (let ((bounds (markdown-wrap-or-insert "[" "]()")))
4212 (when bounds
4213 (goto-char (- (cdr bounds) 1)))))))
4215 (defun markdown-insert-reference-link (text label &optional url title)
4216 "Insert a reference link and, optionally, a reference definition.
4217 The link TEXT will be inserted followed by the optional LABEL.
4218 If a URL is given, also insert a definition for the reference
4219 LABEL according to `markdown-reference-location'. If a TITLE is
4220 given, it will be added to the end of the reference definition
4221 and will be used to populate the title attribute when converted
4222 to XHTML. If URL is nil, insert only the link portion (for
4223 example, when a reference label is already defined)."
4224 (insert (concat "[" text "][" label "]"))
4225 (when url
4226 (markdown-insert-reference-definition
4227 (if (string-equal label "") text label)
4228 url title)))
4230 (defun markdown-insert-reference-definition (label &optional url title)
4231 "Add definition for reference LABEL with URL and TITLE.
4232 LABEL is a Markdown reference label without square brackets.
4233 URL and TITLE are optional. When given, the TITLE will
4234 be used to populate the title attribute when converted to XHTML."
4235 ;; END specifies where to leave the point upon return
4236 (let ((end (point)))
4237 (cl-case markdown-reference-location
4238 (end (goto-char (point-max)))
4239 (immediately (markdown-end-of-text-block))
4240 (subtree (markdown-end-of-subtree))
4241 (header (markdown-end-of-defun)))
4242 (unless (or (markdown-cur-line-blank-p)
4243 (thing-at-point-looking-at markdown-regex-reference-definition))
4244 (insert "\n"))
4245 (insert "\n[" label "]: ")
4246 (if url
4247 (insert url)
4248 ;; When no URL is given, leave cursor at END following the colon
4249 (setq end (point)))
4250 (when (> (length title) 0)
4251 (insert " \"" title "\""))
4252 (unless (looking-at-p "\n")
4253 (insert "\n"))
4254 (goto-char end)
4255 (when url
4256 (message
4257 (substitute-command-keys
4258 "Defined reference [%s], press \\[markdown-jump] to jump there")
4259 label))))
4261 (defun markdown-insert-reference-link-dwim ()
4262 "Insert a reference link of the form [text][label] at point.
4263 If there is an active region, the text in the region will be used
4264 as the link text. If the point is at an inline link, it will be
4265 converted to a reference link. If the point is at a word, it will
4266 be used as the link text. Otherwise, the link text will be read from
4267 the minibuffer. The link label will be read from the minibuffer in
4268 both cases, with completion from the set of currently defined
4269 references. To create an implicit reference link, press RET to
4270 accept the default, an empty label. If the entered referenced
4271 label is not defined, additionally prompt for the URL
4272 and (optional) title. The reference definition is placed at the
4273 location determined by `markdown-reference-location'."
4274 (interactive)
4275 (let* ((defined-labels (markdown-get-defined-references))
4276 (switch (thing-at-point-looking-at markdown-regex-link-inline))
4277 (bounds (cond ((markdown-use-region-p)
4278 (cons (region-beginning) (region-end)))
4279 (switch
4280 (cons (match-beginning 0) (match-end 0)))
4282 (markdown-bounds-of-thing-at-point 'word))))
4283 (text (cond (switch (match-string 3))
4284 (bounds (buffer-substring (car bounds) (cdr bounds)))
4285 (t (read-string "Link Text: "))))
4286 (label (completing-read
4287 "Link Label (default: none): " defined-labels
4288 nil nil nil 'markdown-reference-label-history nil))
4289 (ref (save-match-data
4290 (markdown-reference-definition
4291 (if (> (length label) 0) label text))))
4292 (url (cond (ref nil)
4293 (switch (match-string 6))
4294 (t (read-string "Link URL: "))))
4295 (title (cond
4296 ((= (length url) 0) nil)
4297 (switch (if (> (length (match-string 7)) 2)
4298 (substring (match-string 7) 1 -1)
4299 nil))
4300 (t (read-string "Link Title (optional): ")))))
4301 (when bounds (delete-region (car bounds) (cdr bounds)))
4302 (markdown-insert-reference-link text label url title)))
4304 (defun markdown-insert-uri ()
4305 "Insert markup for an inline URI.
4306 If there is an active region, use it as the URI. If the point is
4307 at a URI, wrap it with angle brackets. If the point is at an
4308 inline URI, remove the angle brackets. Otherwise, simply insert
4309 angle brackets place the point between them."
4310 (interactive)
4311 (if (markdown-use-region-p)
4312 ;; Active region
4313 (let ((bounds (markdown-unwrap-things-in-region
4314 (region-beginning) (region-end)
4315 markdown-regex-angle-uri 0 2)))
4316 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
4317 ;; Markup removal, URI at point, or empty markup insertion
4318 (if (thing-at-point-looking-at markdown-regex-angle-uri)
4319 (markdown-unwrap-thing-at-point nil 0 2)
4320 (markdown-wrap-or-insert "<" ">" 'url nil nil))))
4322 (defun markdown-insert-wiki-link ()
4323 "Insert a wiki link of the form [[WikiLink]].
4324 If there is an active region, use the region as the link text.
4325 If the point is at a word, use the word as the link text. If
4326 there is no active region and the point is not at word, simply
4327 insert link markup."
4328 (interactive)
4329 (if (markdown-use-region-p)
4330 ;; Active region
4331 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
4332 ;; Markup removal, wiki link at at point, or empty markup insertion
4333 (if (thing-at-point-looking-at markdown-regex-wiki-link)
4334 (if (or markdown-wiki-link-alias-first
4335 (null (match-string 5)))
4336 (markdown-unwrap-thing-at-point nil 1 3)
4337 (markdown-unwrap-thing-at-point nil 1 5))
4338 (markdown-wrap-or-insert "[[" "]]"))))
4340 (defun markdown-insert-image (&optional arg)
4341 "Insert image markup using region or word as alt text if possible.
4342 If there is an active region, use the region as the alt text. If the
4343 point is at a word, use the word as the alt text. In these cases, the
4344 point will be left at the position for inserting a URL. If there is no
4345 active region and the point is not at word, simply insert image markup and
4346 place the point in the position to enter alt text. If ARG is nil, insert
4347 inline image markup. Otherwise, insert reference image markup."
4348 (interactive "*P")
4349 (let ((bounds (if arg
4350 (markdown-wrap-or-insert "![" "][]")
4351 (markdown-wrap-or-insert "![" "]()"))))
4352 (when bounds
4353 (goto-char (- (cdr bounds) 1)))))
4355 (defun markdown-insert-reference-image ()
4356 "Insert reference-style image markup using region or word as alt text.
4357 Calls `markdown-insert-image' with prefix argument."
4358 (interactive)
4359 (markdown-insert-image t))
4361 (defun markdown-remove-header ()
4362 "Remove header markup if point is at a header.
4363 Return bounds of remaining header text if a header was removed
4364 and nil otherwise."
4365 (interactive "*")
4366 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
4367 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
4369 (defun markdown-insert-header (&optional level text setext)
4370 "Insert or replace header markup.
4371 The level of the header is specified by LEVEL and header text is
4372 given by TEXT. LEVEL must be an integer from 1 and 6, and the
4373 default value is 1.
4374 When TEXT is nil, the header text is obtained as follows.
4375 If there is an active region, it is used as the header text.
4376 Otherwise, the current line will be used as the header text.
4377 If there is not an active region and the point is at a header,
4378 remove the header markup and replace with level N header.
4379 Otherwise, insert empty header markup and place the cursor in
4380 between.
4381 The style of the header will be atx (hash marks) unless
4382 SETEXT is non-nil, in which case a setext-style (underlined)
4383 header will be inserted."
4384 (interactive "p\nsHeader text: ")
4385 (setq level (min (max (or level 1) 1) (if setext 2 6)))
4386 ;; Determine header text if not given
4387 (when (null text)
4388 (if (markdown-use-region-p)
4389 ;; Active region
4390 (setq text (delete-and-extract-region (region-beginning) (region-end)))
4391 ;; No active region
4392 (markdown-remove-header)
4393 (setq text (delete-and-extract-region
4394 (line-beginning-position) (line-end-position)))
4395 (when (and setext (string-match-p "^[ \t]*$" text))
4396 (setq text (read-string "Header text: "))))
4397 (setq text (markdown-compress-whitespace-string text)))
4398 ;; Insertion with given text
4399 (markdown-ensure-blank-line-before)
4400 (let (hdr)
4401 (cond (setext
4402 (setq hdr (make-string (string-width text) (if (= level 2) ?- ?=)))
4403 (insert text "\n" hdr))
4405 (setq hdr (make-string level ?#))
4406 (insert hdr " " text)
4407 (when (null markdown-asymmetric-header) (insert " " hdr)))))
4408 (markdown-ensure-blank-line-after)
4409 ;; Leave point at end of text
4410 (cond (setext
4411 (backward-char (1+ (string-width text))))
4412 ((null markdown-asymmetric-header)
4413 (backward-char (1+ level)))))
4415 (defun markdown-insert-header-dwim (&optional arg setext)
4416 "Insert or replace header markup.
4417 The level and type of the header are determined automatically by
4418 the type and level of the previous header, unless a prefix
4419 argument is given via ARG.
4420 With a numeric prefix valued 1 to 6, insert a header of the given
4421 level, with the type being determined automatically (note that
4422 only level 1 or 2 setext headers are possible).
4424 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
4425 promote the heading by one level.
4426 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
4427 demote the heading by one level.
4428 When SETEXT is non-nil, prefer setext-style headers when
4429 possible (levels one and two).
4431 When there is an active region, use it for the header text. When
4432 the point is at an existing header, change the type and level
4433 according to the rules above.
4434 Otherwise, if the line is not empty, create a header using the
4435 text on the current line as the header text.
4436 Finally, if the point is on a blank line, insert empty header
4437 markup (atx) or prompt for text (setext).
4438 See `markdown-insert-header' for more details about how the
4439 header text is determined."
4440 (interactive "*P")
4441 (let (level)
4442 (save-excursion
4443 (when (or (thing-at-point-looking-at markdown-regex-header)
4444 (re-search-backward markdown-regex-header nil t))
4445 ;; level of current or previous header
4446 (setq level (markdown-outline-level))
4447 ;; match group 1 indicates a setext header
4448 (setq setext (match-end 1))))
4449 ;; check prefix argument
4450 (cond
4451 ((and (equal arg '(4)) level (> level 1)) ;; C-u
4452 (cl-decf level))
4453 ((and (equal arg '(16)) level (< level 6)) ;; C-u C-u
4454 (cl-incf level))
4455 (arg ;; numeric prefix
4456 (setq level (prefix-numeric-value arg))))
4457 ;; setext headers must be level one or two
4458 (and level (setq setext (and setext (<= level 2))))
4459 ;; insert the heading
4460 (markdown-insert-header level nil setext)))
4462 (defun markdown-insert-header-setext-dwim (&optional arg)
4463 "Insert or replace header markup, with preference for setext.
4464 See `markdown-insert-header-dwim' for details, including how ARG is handled."
4465 (interactive "*P")
4466 (markdown-insert-header-dwim arg t))
4468 (defun markdown-insert-header-atx-1 ()
4469 "Insert a first level atx-style (hash mark) header.
4470 See `markdown-insert-header'."
4471 (interactive "*")
4472 (markdown-insert-header 1 nil nil))
4474 (defun markdown-insert-header-atx-2 ()
4475 "Insert a level two atx-style (hash mark) header.
4476 See `markdown-insert-header'."
4477 (interactive "*")
4478 (markdown-insert-header 2 nil nil))
4480 (defun markdown-insert-header-atx-3 ()
4481 "Insert a level three atx-style (hash mark) header.
4482 See `markdown-insert-header'."
4483 (interactive "*")
4484 (markdown-insert-header 3 nil nil))
4486 (defun markdown-insert-header-atx-4 ()
4487 "Insert a level four atx-style (hash mark) header.
4488 See `markdown-insert-header'."
4489 (interactive "*")
4490 (markdown-insert-header 4 nil nil))
4492 (defun markdown-insert-header-atx-5 ()
4493 "Insert a level five atx-style (hash mark) header.
4494 See `markdown-insert-header'."
4495 (interactive "*")
4496 (markdown-insert-header 5 nil nil))
4498 (defun markdown-insert-header-atx-6 ()
4499 "Insert a sixth level atx-style (hash mark) header.
4500 See `markdown-insert-header'."
4501 (interactive "*")
4502 (markdown-insert-header 6 nil nil))
4504 (defun markdown-insert-header-setext-1 ()
4505 "Insert a setext-style (underlined) first-level header.
4506 See `markdown-insert-header'."
4507 (interactive "*")
4508 (markdown-insert-header 1 nil t))
4510 (defun markdown-insert-header-setext-2 ()
4511 "Insert a setext-style (underlined) second-level header.
4512 See `markdown-insert-header'."
4513 (interactive "*")
4514 (markdown-insert-header 2 nil t))
4516 (defun markdown-blockquote-indentation (loc)
4517 "Return string containing necessary indentation for a blockquote at LOC.
4518 Also see `markdown-pre-indentation'."
4519 (save-excursion
4520 (goto-char loc)
4521 (let* ((list-level (length (markdown-calculate-list-levels)))
4522 (indent ""))
4523 (dotimes (_ list-level indent)
4524 (setq indent (concat indent " "))))))
4526 (defun markdown-insert-blockquote ()
4527 "Start a blockquote section (or blockquote the region).
4528 If Transient Mark mode is on and a region is active, it is used as
4529 the blockquote text."
4530 (interactive)
4531 (if (markdown-use-region-p)
4532 (markdown-blockquote-region (region-beginning) (region-end))
4533 (markdown-ensure-blank-line-before)
4534 (insert (markdown-blockquote-indentation (point)) "> ")
4535 (markdown-ensure-blank-line-after)))
4537 (defun markdown-block-region (beg end prefix)
4538 "Format the region using a block prefix.
4539 Arguments BEG and END specify the beginning and end of the
4540 region. The characters PREFIX will appear at the beginning
4541 of each line."
4542 (save-excursion
4543 (let* ((end-marker (make-marker))
4544 (beg-marker (make-marker)))
4545 ;; Ensure blank line after and remove extra whitespace
4546 (goto-char end)
4547 (skip-syntax-backward "-")
4548 (set-marker end-marker (point))
4549 (delete-horizontal-space)
4550 (markdown-ensure-blank-line-after)
4551 ;; Ensure blank line before and remove extra whitespace
4552 (goto-char beg)
4553 (skip-syntax-forward "-")
4554 (delete-horizontal-space)
4555 (markdown-ensure-blank-line-before)
4556 (set-marker beg-marker (point))
4557 ;; Insert PREFIX before each line
4558 (goto-char beg-marker)
4559 (while (and (< (line-beginning-position) end-marker)
4560 (not (eobp)))
4561 (insert prefix)
4562 (forward-line)))))
4564 (defun markdown-blockquote-region (beg end)
4565 "Blockquote the region.
4566 Arguments BEG and END specify the beginning and end of the region."
4567 (interactive "*r")
4568 (markdown-block-region
4569 beg end (concat (markdown-blockquote-indentation
4570 (max (point-min) (1- beg))) "> ")))
4572 (defun markdown-pre-indentation (loc)
4573 "Return string containing necessary whitespace for a pre block at LOC.
4574 Also see `markdown-blockquote-indentation'."
4575 (save-excursion
4576 (goto-char loc)
4577 (let* ((list-level (length (markdown-calculate-list-levels)))
4578 indent)
4579 (dotimes (_ (1+ list-level) indent)
4580 (setq indent (concat indent " "))))))
4582 (defun markdown-insert-pre ()
4583 "Start a preformatted section (or apply to the region).
4584 If Transient Mark mode is on and a region is active, it is marked
4585 as preformatted text."
4586 (interactive)
4587 (if (markdown-use-region-p)
4588 (markdown-pre-region (region-beginning) (region-end))
4589 (markdown-ensure-blank-line-before)
4590 (insert (markdown-pre-indentation (point)))
4591 (markdown-ensure-blank-line-after)))
4593 (defun markdown-pre-region (beg end)
4594 "Format the region as preformatted text.
4595 Arguments BEG and END specify the beginning and end of the region."
4596 (interactive "*r")
4597 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
4598 (markdown-block-region beg end indent)))
4600 (defun markdown-electric-backquote (arg)
4601 "Insert a backquote.
4602 The numeric prefix argument ARG says how many times to repeat the insertion.
4603 Call `markdown-insert-gfm-code-block' interactively
4604 if three backquotes inserted at the beginning of line."
4605 (interactive "*P")
4606 (self-insert-command (prefix-numeric-value arg))
4607 (when (and markdown-gfm-use-electric-backquote (looking-back "^```" nil))
4608 (replace-match "")
4609 (call-interactively #'markdown-insert-gfm-code-block)))
4611 (defconst markdown-gfm-recognized-languages
4612 ;; To reproduce/update, evaluate the let-form in
4613 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
4614 ;; but with appropriate use of a keyboard macro, indenting and filling it
4615 ;; properly is pretty fast.
4616 '("1C-Enterprise" "ABAP" "ABNF" "AGS-Script" "AMPL" "ANTLR"
4617 "API-Blueprint" "APL" "ASN.1" "ASP" "ATS" "ActionScript" "Ada" "Agda"
4618 "Alloy" "Alpine-Abuild" "Ant-Build-System" "ApacheConf" "Apex"
4619 "Apollo-Guidance-Computer" "AppleScript" "Arc" "Arduino" "AsciiDoc"
4620 "AspectJ" "Assembly" "Augeas" "AutoHotkey" "AutoIt" "Awk" "Batchfile"
4621 "Befunge" "Bison" "BitBake" "Blade" "BlitzBasic" "BlitzMax" "Bluespec"
4622 "Boo" "Brainfuck" "Brightscript" "Bro" "C#" "C++" "C-ObjDump"
4623 "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "COLLADA" "CSON" "CSS" "CSV"
4624 "CWeb" "Cap'n-Proto" "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK"
4625 "Cirru" "Clarion" "Clean" "Click" "Clojure" "Closure-Templates"
4626 "CoffeeScript" "ColdFusion" "ColdFusion-CFC" "Common-Lisp"
4627 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal"
4628 "Csound" "Csound-Document" "Csound-Score" "Cuda" "Cycript" "Cython"
4629 "D-ObjDump" "DIGITAL-Command-Language" "DM" "DNS-Zone" "DTrace"
4630 "Darcs-Patch" "Dart" "Diff" "Dockerfile" "Dogescript" "Dylan" "EBNF"
4631 "ECL" "ECLiPSe" "EJS" "EQ" "Eagle" "Ecere-Projects" "Eiffel" "Elixir"
4632 "Elm" "Emacs-Lisp" "EmberScript" "Erlang" "F#" "FLUX" "Factor" "Fancy"
4633 "Fantom" "Filebench-WML" "Filterscript" "Formatted" "Forth" "Fortran"
4634 "FreeMarker" "Frege" "G-code" "GAMS" "GAP" "GCC-Machine-Description"
4635 "GDB" "GDScript" "GLSL" "GN" "Game-Maker-Language" "Genie" "Genshi"
4636 "Gentoo-Ebuild" "Gentoo-Eclass" "Gettext-Catalog" "Gherkin" "Glyph"
4637 "Gnuplot" "Go" "Golo" "Gosu" "Grace" "Gradle" "Grammatical-Framework"
4638 "Graph-Modeling-Language" "GraphQL" "Graphviz-(DOT)" "Groovy"
4639 "Groovy-Server-Pages" "HCL" "HLSL" "HTML" "HTML+Django" "HTML+ECR"
4640 "HTML+EEX" "HTML+ERB" "HTML+PHP" "HTTP" "Hack" "Haml" "Handlebars"
4641 "Harbour" "Haskell" "Haxe" "Hy" "HyPhy" "IDL" "IGOR-Pro" "INI"
4642 "IRC-log" "Idris" "Inform-7" "Inno-Setup" "Io" "Ioke" "Isabelle"
4643 "Isabelle-ROOT" "JFlex" "JSON" "JSON5" "JSONLD" "JSONiq" "JSX"
4644 "Jasmin" "Java" "Java-Server-Pages" "JavaScript" "Jison" "Jison-Lex"
4645 "Jolie" "Julia" "Jupyter-Notebook" "KRL" "KiCad" "Kit" "Kotlin" "LFE"
4646 "LLVM" "LOLCODE" "LSL" "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex"
4647 "LilyPond" "Limbo" "Linker-Script" "Linux-Kernel-Module" "Liquid"
4648 "Literate-Agda" "Literate-CoffeeScript" "Literate-Haskell"
4649 "LiveScript" "Logos" "Logtalk" "LookML" "LoomScript" "Lua" "M4"
4650 "M4Sugar" "MAXScript" "MQL4" "MQL5" "MTML" "MUF" "Makefile" "Mako"
4651 "Markdown" "Marko" "Mask" "Mathematica" "Matlab" "Maven-POM" "Max"
4652 "MediaWiki" "Mercury" "Meson" "Metal" "MiniD" "Mirah" "Modelica"
4653 "Modula-2" "Module-Management-System" "Monkey" "Moocode" "MoonScript"
4654 "Myghty" "NCL" "NL" "NSIS" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo"
4655 "NewLisp" "Nginx" "Nim" "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml"
4656 "ObjDump" "Objective-C" "Objective-C++" "Objective-J" "Omgrofl" "Opa"
4657 "Opal" "OpenCL" "OpenEdge-ABL" "OpenRC-runscript" "OpenSCAD"
4658 "OpenType-Feature-File" "Org" "Ox" "Oxygene" "Oz" "P4" "PAWN" "PHP"
4659 "PLSQL" "PLpgSQL" "POV-Ray-SDL" "Pan" "Papyrus" "Parrot"
4660 "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal" "Pep8"
4661 "Perl" "Perl6" "Pic" "Pickle" "PicoLisp" "PigLatin" "Pike" "Pod"
4662 "PogoScript" "Pony" "PostScript" "PowerBuilder" "PowerShell"
4663 "Processing" "Prolog" "Propeller-Spin" "Protocol-Buffer" "Public-Key"
4664 "Pug" "Puppet" "Pure-Data" "PureBasic" "PureScript" "Python"
4665 "Python-console" "Python-traceback" "QML" "QMake" "RAML" "RDoc"
4666 "REALbasic" "REXX" "RHTML" "RMarkdown" "RPM-Spec" "RUNOFF" "Racket"
4667 "Ragel" "Rascal" "Raw-token-data" "Reason" "Rebol" "Red" "Redcode"
4668 "Regular-Expression" "Ren'Py" "RenderScript" "RobotFramework" "Roff"
4669 "Rouge" "Ruby" "Rust" "SAS" "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL"
4670 "SRecode-Template" "STON" "SVG" "Sage" "SaltStack" "Sass" "Scala"
4671 "Scaml" "Scheme" "Scilab" "Self" "ShaderLab" "Shell" "ShellSession"
4672 "Shen" "Slash" "Slim" "Smali" "Smalltalk" "Smarty" "SourcePawn"
4673 "Spline-Font-Database" "Squirrel" "Stan" "Standard-ML" "Stata"
4674 "Stylus" "SubRip-Text" "Sublime-Text-Config" "SuperCollider" "Swift"
4675 "SystemVerilog" "TI-Program" "TLA" "TOML" "TXL" "Tcl" "Tcsh" "TeX"
4676 "Tea" "Terra" "Text" "Textile" "Thrift" "Turing" "Turtle" "Twig"
4677 "Type-Language" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset"
4678 "Unix-Assembly" "Uno" "UnrealScript" "UrWeb" "VCL" "VHDL" "Vala"
4679 "Verilog" "Vim-script" "Visual-Basic" "Volt" "Vue"
4680 "Wavefront-Material" "Wavefront-Object" "Web-Ontology-Language"
4681 "WebAssembly" "WebIDL" "World-of-Warcraft-Addon-Data" "X10" "XC"
4682 "XCompose" "XML" "XPages" "XProc" "XQuery" "XS" "XSLT" "Xojo" "Xtend"
4683 "YAML" "YANG" "Yacc" "Zephir" "Zimpl" "desktop" "eC" "edn" "fish"
4684 "mupad" "nesC" "ooc" "reStructuredText" "wisp" "xBase")
4685 "Language specifiers recognized by GitHub's syntax highlighting features.")
4687 (defvar markdown-gfm-used-languages nil
4688 "Language names used in GFM code blocks.")
4689 (make-variable-buffer-local 'markdown-gfm-used-languages)
4691 (defun markdown-trim-whitespace (str)
4692 (markdown-replace-regexp-in-string
4693 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str))
4695 (defun markdown-clean-language-string (str)
4696 (markdown-replace-regexp-in-string
4697 "{\\.?\\|}" "" (markdown-trim-whitespace str)))
4699 (defun markdown-validate-language-string (widget)
4700 (let ((str (widget-value widget)))
4701 (unless (string= str (markdown-clean-language-string str))
4702 (widget-put widget :error (format "Invalid language spec: '%s'" str))
4703 widget)))
4705 (defun markdown-gfm-get-corpus ()
4706 "Create corpus of recognized GFM code block languages for the given buffer."
4707 (let ((given-corpus (append markdown-gfm-additional-languages
4708 markdown-gfm-recognized-languages)))
4709 (append
4710 markdown-gfm-used-languages
4711 (if markdown-gfm-downcase-languages (cl-mapcar #'downcase given-corpus)
4712 given-corpus))))
4714 (defun markdown-gfm-add-used-language (lang)
4715 "Clean LANG and add to list of used languages."
4716 (setq markdown-gfm-used-languages
4717 (cons lang (remove lang markdown-gfm-used-languages))))
4719 (defun markdown-insert-gfm-code-block (&optional lang)
4720 "Insert GFM code block for language LANG.
4721 If LANG is nil, the language will be queried from user. If a
4722 region is active, wrap this region with the markup instead. If
4723 the region boundaries are not on empty lines, these are added
4724 automatically in order to have the correct markup."
4725 (interactive
4726 (list (let ((completion-ignore-case nil))
4727 (condition-case nil
4728 (markdown-clean-language-string
4729 (completing-read
4730 "Programming language: "
4731 (markdown-gfm-get-corpus)
4732 nil 'confirm (car markdown-gfm-used-languages)
4733 'markdown-gfm-language-history))
4734 (quit "")))))
4735 (unless (string= lang "") (markdown-gfm-add-used-language lang))
4736 (when (> (length lang) 0) (setq lang (concat " " lang)))
4737 (if (markdown-use-region-p)
4738 (let ((b (region-beginning)) (e (region-end)))
4739 (goto-char e)
4740 ;; if we're on a blank line, don't newline, otherwise the ```
4741 ;; should go on its own line
4742 (unless (looking-back "\n" nil)
4743 (newline))
4744 (insert "```")
4745 (markdown-ensure-blank-line-after)
4746 (goto-char b)
4747 ;; if we're on a blank line, insert the quotes here, otherwise
4748 ;; add a new line first
4749 (unless (looking-at-p "\n")
4750 (newline)
4751 (forward-line -1))
4752 (markdown-ensure-blank-line-before)
4753 (insert "```" lang))
4754 (markdown-ensure-blank-line-before)
4755 (insert "```" lang "\n\n```")
4756 (markdown-ensure-blank-line-after)
4757 (forward-line -1)))
4759 (defun markdown-code-block-lang (&optional pos-prop)
4760 "Return the language name for a GFM or tilde fenced code block.
4761 The beginning of the block may be described by POS-PROP,
4762 a cons of (pos . prop) giving the position and property
4763 at the beginning of the block."
4764 (or pos-prop
4765 (setq pos-prop
4766 (markdown-max-of-seq
4767 #'car
4768 (cl-remove-if
4769 #'null
4770 (cl-mapcar
4771 #'markdown-find-previous-prop
4772 (markdown-get-fenced-block-begin-properties))))))
4773 (when pos-prop
4774 (goto-char (car pos-prop))
4775 (set-match-data (get-text-property (point) (cdr pos-prop)))
4776 ;; Note: Hard-coded group number assumes tilde
4777 ;; and GFM fenced code regexp groups agree.
4778 (let ((begin (match-beginning 3))
4779 (end (match-end 3)))
4780 (when (and begin end)
4781 ;; Fix language strings beginning with periods, like ".ruby".
4782 (when (eq (char-after begin) ?.)
4783 (setq begin (1+ begin)))
4784 (buffer-substring-no-properties begin end)))))
4786 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer)
4787 (with-current-buffer (or buffer (current-buffer))
4788 (save-excursion
4789 (goto-char (point-min))
4790 (cl-loop
4791 with prop = 'markdown-gfm-block-begin
4792 for pos-prop = (markdown-find-next-prop prop)
4793 while pos-prop
4794 for lang = (markdown-code-block-lang pos-prop)
4795 do (progn (when lang (markdown-gfm-add-used-language lang))
4796 (goto-char (next-single-property-change (point) prop)))))))
4799 ;;; Footnotes ==================================================================
4801 (defun markdown-footnote-counter-inc ()
4802 "Increment `markdown-footnote-counter' and return the new value."
4803 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
4804 (save-excursion
4805 (goto-char (point-min))
4806 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
4807 (point-max) t)
4808 (let ((fn (string-to-number (match-string 1))))
4809 (when (> fn markdown-footnote-counter)
4810 (setq markdown-footnote-counter fn))))))
4811 (cl-incf markdown-footnote-counter))
4813 (defun markdown-insert-footnote ()
4814 "Insert footnote with a new number and move point to footnote definition."
4815 (interactive)
4816 (let ((fn (markdown-footnote-counter-inc)))
4817 (insert (format "[^%d]" fn))
4818 (markdown-footnote-text-find-new-location)
4819 (markdown-ensure-blank-line-before)
4820 (unless (markdown-cur-line-blank-p)
4821 (insert "\n"))
4822 (insert (format "[^%d]: " fn))
4823 (markdown-ensure-blank-line-after)))
4825 (defun markdown-footnote-text-find-new-location ()
4826 "Position the cursor at the proper location for a new footnote text."
4827 (cond
4828 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
4829 ((eq markdown-footnote-location 'immediately) (markdown-end-of-text-block))
4830 ((eq markdown-footnote-location 'subtree) (markdown-end-of-subtree))
4831 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
4833 (defun markdown-footnote-kill ()
4834 "Kill the footnote at point.
4835 The footnote text is killed (and added to the kill ring), the
4836 footnote marker is deleted. Point has to be either at the
4837 footnote marker or in the footnote text."
4838 (interactive)
4839 (let ((marker-pos nil)
4840 (skip-deleting-marker nil)
4841 (starting-footnote-text-positions
4842 (markdown-footnote-text-positions)))
4843 (when starting-footnote-text-positions
4844 ;; We're starting in footnote text, so mark our return position and jump
4845 ;; to the marker if possible.
4846 (let ((marker-pos (markdown-footnote-find-marker
4847 (cl-first starting-footnote-text-positions))))
4848 (if marker-pos
4849 (goto-char (1- marker-pos))
4850 ;; If there isn't a marker, we still want to kill the text.
4851 (setq skip-deleting-marker t))))
4852 ;; Either we didn't start in the text, or we started in the text and jumped
4853 ;; to the marker. We want to assume we're at the marker now and error if
4854 ;; we're not.
4855 (unless skip-deleting-marker
4856 (let ((marker (markdown-footnote-delete-marker)))
4857 (unless marker
4858 (error "Not at a footnote"))
4859 ;; Even if we knew the text position before, it changed when we deleted
4860 ;; the label.
4861 (setq marker-pos (cl-second marker))
4862 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker))))
4863 (unless new-text-pos
4864 (error "No text for footnote `%s'" (cl-first marker)))
4865 (goto-char new-text-pos))))
4866 (let ((pos (markdown-footnote-kill-text)))
4867 (goto-char (if starting-footnote-text-positions
4869 marker-pos)))))
4871 (defun markdown-footnote-delete-marker ()
4872 "Delete a footnote marker at point.
4873 Returns a list (ID START) containing the footnote ID and the
4874 start position of the marker before deletion. If no footnote
4875 marker was deleted, this function returns NIL."
4876 (let ((marker (markdown-footnote-marker-positions)))
4877 (when marker
4878 (delete-region (cl-second marker) (cl-third marker))
4879 (butlast marker))))
4881 (defun markdown-footnote-kill-text ()
4882 "Kill footnote text at point.
4883 Returns the start position of the footnote text before deletion,
4884 or NIL if point was not inside a footnote text.
4886 The killed text is placed in the kill ring (without the footnote
4887 number)."
4888 (let ((fn (markdown-footnote-text-positions)))
4889 (when fn
4890 (let ((text (delete-and-extract-region (cl-second fn) (cl-third fn))))
4891 (string-match (concat "\\[\\" (cl-first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
4892 (kill-new (match-string 1 text))
4893 (when (and (markdown-cur-line-blank-p)
4894 (markdown-prev-line-blank-p)
4895 (not (bobp)))
4896 (delete-region (1- (point)) (point)))
4897 (cl-second fn)))))
4899 (defun markdown-footnote-goto-text ()
4900 "Jump to the text of the footnote at point."
4901 (interactive)
4902 (let ((fn (car (markdown-footnote-marker-positions))))
4903 (unless fn
4904 (error "Not at a footnote marker"))
4905 (let ((new-pos (markdown-footnote-find-text fn)))
4906 (unless new-pos
4907 (error "No definition found for footnote `%s'" fn))
4908 (goto-char new-pos))))
4910 (defun markdown-footnote-return ()
4911 "Return from a footnote to its footnote number in the main text."
4912 (interactive)
4913 (let ((fn (save-excursion
4914 (car (markdown-footnote-text-positions)))))
4915 (unless fn
4916 (error "Not in a footnote"))
4917 (let ((new-pos (markdown-footnote-find-marker fn)))
4918 (unless new-pos
4919 (error "Footnote marker `%s' not found" fn))
4920 (goto-char new-pos))))
4922 (defun markdown-footnote-find-marker (id)
4923 "Find the location of the footnote marker with ID.
4924 The actual buffer position returned is the position directly
4925 following the marker's closing bracket. If no marker is found,
4926 NIL is returned."
4927 (save-excursion
4928 (goto-char (point-min))
4929 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
4930 (skip-chars-backward "^]")
4931 (point))))
4933 (defun markdown-footnote-find-text (id)
4934 "Find the location of the text of footnote ID.
4935 The actual buffer position returned is the position of the first
4936 character of the text, after the footnote's identifier. If no
4937 footnote text is found, NIL is returned."
4938 (save-excursion
4939 (goto-char (point-min))
4940 (when (re-search-forward (concat "^\\[" id "\\]:") nil t)
4941 (skip-chars-forward "[ \t]")
4942 (point))))
4944 (defun markdown-footnote-marker-positions ()
4945 "Return the position and ID of the footnote marker point is on.
4946 The return value is a list (ID START END). If point is not on a
4947 footnote, NIL is returned."
4948 ;; first make sure we're at a footnote marker
4949 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
4950 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
4951 (save-excursion
4952 ;; move point between [ and ^:
4953 (if (looking-at-p "\\[")
4954 (forward-char 1)
4955 (skip-chars-backward "^["))
4956 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
4957 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
4959 (defun markdown-footnote-text-positions ()
4960 "Return the start and end positions of the footnote text point is in.
4961 The exact return value is a list of three elements: (ID START END).
4962 The start position is the position of the opening bracket
4963 of the footnote id. The end position is directly after the
4964 newline that ends the footnote. If point is not in a footnote,
4965 NIL is returned instead."
4966 (save-excursion
4967 (let (result)
4968 (move-beginning-of-line 1)
4969 ;; Try to find the label. If we haven't found the label and we're at a blank
4970 ;; or indented line, back up if possible.
4971 (while (and
4972 (not (and (looking-at markdown-regex-footnote-definition)
4973 (setq result (list (match-string 1) (point)))))
4974 (and (not (bobp))
4975 (or (markdown-cur-line-blank-p)
4976 (>= (current-indentation) 4))))
4977 (forward-line -1))
4978 (when result
4979 ;; Advance if there is a next line that is either blank or indented.
4980 ;; (Need to check if we're on the last line, because
4981 ;; markdown-next-line-blank-p returns true for last line in buffer.)
4982 (while (and (/= (line-end-position) (point-max))
4983 (or (markdown-next-line-blank-p)
4984 (>= (markdown-next-line-indent) 4)))
4985 (forward-line))
4986 ;; Move back while the current line is blank.
4987 (while (markdown-cur-line-blank-p)
4988 (forward-line -1))
4989 ;; Advance to capture this line and a single trailing newline (if there
4990 ;; is one).
4991 (forward-line)
4992 (append result (list (point)))))))
4995 ;;; Element Removal ===========================================================
4997 (defun markdown-kill-thing-at-point ()
4998 "Kill thing at point and add important text, without markup, to kill ring.
4999 Possible things to kill include (roughly in order of precedence):
5000 inline code, headers, horizonal rules, links (add link text to
5001 kill ring), images (add alt text to kill ring), angle uri, email
5002 addresses, bold, italics, reference definition (add URI to kill
5003 ring), footnote markers and text (kill both marker and text, add
5004 text to kill ring), and list items."
5005 (interactive "*")
5006 (let (val)
5007 (cond
5008 ;; Inline code
5009 ((markdown-inline-code-at-point)
5010 (kill-new (match-string 2))
5011 (delete-region (match-beginning 0) (match-end 0)))
5012 ;; ATX header
5013 ((thing-at-point-looking-at markdown-regex-header-atx)
5014 (kill-new (match-string 2))
5015 (delete-region (match-beginning 0) (match-end 0)))
5016 ;; Setext header
5017 ((thing-at-point-looking-at markdown-regex-header-setext)
5018 (kill-new (match-string 1))
5019 (delete-region (match-beginning 0) (match-end 0)))
5020 ;; Horizonal rule
5021 ((thing-at-point-looking-at markdown-regex-hr)
5022 (kill-new (match-string 0))
5023 (delete-region (match-beginning 0) (match-end 0)))
5024 ;; Inline link or image (add link or alt text to kill ring)
5025 ((thing-at-point-looking-at markdown-regex-link-inline)
5026 (kill-new (match-string 3))
5027 (delete-region (match-beginning 0) (match-end 0)))
5028 ;; Reference link or image (add link or alt text to kill ring)
5029 ((thing-at-point-looking-at markdown-regex-link-reference)
5030 (kill-new (match-string 3))
5031 (delete-region (match-beginning 0) (match-end 0)))
5032 ;; Angle URI (add URL to kill ring)
5033 ((thing-at-point-looking-at markdown-regex-angle-uri)
5034 (kill-new (match-string 2))
5035 (delete-region (match-beginning 0) (match-end 0)))
5036 ;; Email address in angle brackets (add email address to kill ring)
5037 ((thing-at-point-looking-at markdown-regex-email)
5038 (kill-new (match-string 1))
5039 (delete-region (match-beginning 0) (match-end 0)))
5040 ;; Wiki link (add alias text to kill ring)
5041 ((and markdown-enable-wiki-links
5042 (thing-at-point-looking-at markdown-regex-wiki-link))
5043 (kill-new (markdown-wiki-link-alias))
5044 (delete-region (match-beginning 1) (match-end 1)))
5045 ;; Bold
5046 ((thing-at-point-looking-at markdown-regex-bold)
5047 (kill-new (match-string 4))
5048 (delete-region (match-beginning 2) (match-end 2)))
5049 ;; Italics
5050 ((thing-at-point-looking-at markdown-regex-italic)
5051 (kill-new (match-string 3))
5052 (delete-region (match-beginning 1) (match-end 1)))
5053 ;; Strikethrough
5054 ((thing-at-point-looking-at markdown-regex-strike-through)
5055 (kill-new (match-string 4))
5056 (delete-region (match-beginning 2) (match-end 2)))
5057 ;; Footnote marker (add footnote text to kill ring)
5058 ((thing-at-point-looking-at markdown-regex-footnote)
5059 (markdown-footnote-kill))
5060 ;; Footnote text (add footnote text to kill ring)
5061 ((setq val (markdown-footnote-text-positions))
5062 (markdown-footnote-kill))
5063 ;; Reference definition (add URL to kill ring)
5064 ((thing-at-point-looking-at markdown-regex-reference-definition)
5065 (kill-new (match-string 5))
5066 (delete-region (match-beginning 0) (match-end 0)))
5067 ;; List item
5068 ((setq val (markdown-cur-list-item-bounds))
5069 (kill-new (delete-and-extract-region (cl-first val) (cl-second val))))
5071 (error "Nothing found at point to kill")))))
5074 ;;; Indentation ====================================================================
5076 (defun markdown-indent-find-next-position (cur-pos positions)
5077 "Return the position after the index of CUR-POS in POSITIONS.
5078 Positions are calculated by `markdown-calc-indents'."
5079 (while (and positions
5080 (not (equal cur-pos (car positions))))
5081 (setq positions (cdr positions)))
5082 (or (cadr positions) 0))
5084 (defun markdown-exdent-find-next-position (cur-pos positions)
5085 "Return the maximal element that precedes CUR-POS from POSITIONS.
5086 Positions are calculated by `markdown-calc-indents'."
5087 (let ((result 0))
5088 (dolist (i positions)
5089 (when (< i cur-pos)
5090 (setq result (max result i))))
5091 result))
5093 (defun markdown-indent-line ()
5094 "Indent the current line using some heuristics.
5095 If the _previous_ command was either `markdown-enter-key' or
5096 `markdown-cycle', then we should cycle to the next
5097 reasonable indentation position. Otherwise, we could have been
5098 called directly by `markdown-enter-key', by an initial call of
5099 `markdown-cycle', or indirectly by `auto-fill-mode'. In
5100 these cases, indent to the default position.
5101 Positions are calculated by `markdown-calc-indents'."
5102 (interactive)
5103 (let ((positions (markdown-calc-indents))
5104 (cursor-pos (current-column))
5105 (_ (back-to-indentation))
5106 (cur-pos (current-column)))
5107 (if (not (equal this-command 'markdown-cycle))
5108 (indent-line-to (car positions))
5109 (setq positions (sort (delete-dups positions) '<))
5110 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions))
5111 (new-cursor-pos
5112 (if (< cur-pos next-pos)
5113 (+ cursor-pos (- next-pos cur-pos))
5114 (- cursor-pos cur-pos))))
5115 (indent-line-to next-pos)
5116 (move-to-column new-cursor-pos)))))
5118 (defun markdown-calc-indents ()
5119 "Return a list of indentation columns to cycle through.
5120 The first element in the returned list should be considered the
5121 default indentation level. This function does not worry about
5122 duplicate positions, which are handled up by calling functions."
5123 (let (pos prev-line-pos positions)
5125 ;; Indentation of previous line
5126 (setq prev-line-pos (markdown-prev-line-indent))
5127 (setq positions (cons prev-line-pos positions))
5129 ;; Indentation of previous non-list-marker text
5130 (when (setq pos (markdown-prev-non-list-indent))
5131 (setq positions (cons pos positions)))
5133 ;; Indentation required for a pre block in current context
5134 (setq pos (length (markdown-pre-indentation (point))))
5135 (setq positions (cons pos positions))
5137 ;; Indentation of the previous line + tab-width
5138 (if prev-line-pos
5139 (setq positions (cons (+ prev-line-pos tab-width) positions))
5140 (setq positions (cons tab-width positions)))
5142 ;; Indentation of the previous line - tab-width
5143 (if (and prev-line-pos (> prev-line-pos tab-width))
5144 (setq positions (cons (- prev-line-pos tab-width) positions)))
5146 ;; Indentation of all preceeding list markers (when in a list)
5147 (when (setq pos (markdown-calculate-list-levels))
5148 (setq positions (append pos positions)))
5150 ;; First column
5151 (setq positions (cons 0 positions))
5153 ;; Return reversed list
5154 (reverse positions)))
5156 (defun markdown-enter-key ()
5157 "Handle RET according to value of `markdown-indent-on-enter'.
5158 When it is nil, simply call `newline'. Otherwise, indent the next line
5159 following RET using `markdown-indent-line'. Furthermore, when it
5160 is set to 'indent-and-new-item and the point is in a list item,
5161 start a new item with the same indentation. If the point is in an
5162 empty list item, remove it (so that pressing RET twice when in a
5163 list simply adds a blank line)."
5164 (interactive)
5165 (if (not markdown-indent-on-enter)
5166 (newline)
5167 (let (bounds)
5168 (if (and (memq markdown-indent-on-enter '(indent-and-new-item))
5169 (setq bounds (markdown-cur-list-item-bounds)))
5170 (let ((beg (cl-first bounds))
5171 (end (cl-second bounds))
5172 (length (cl-fourth bounds)))
5173 ;; Point is in a list item
5174 (if (= (- end beg) length)
5175 ;; Delete blank list
5176 (progn
5177 (delete-region beg end)
5178 (newline)
5179 (markdown-indent-line))
5180 (call-interactively #'markdown-insert-list-item)))
5181 ;; Point is not in a list
5182 (newline)
5183 (markdown-indent-line)))))
5185 (defun markdown-exdent-or-delete (arg)
5186 "Handle BACKSPACE by cycling through indentation points.
5187 When BACKSPACE is pressed, if there is only whitespace
5188 before the current point, then exdent the line one level.
5189 Otherwise, do normal delete by repeating
5190 `backward-delete-char-untabify' ARG times."
5191 (interactive "*p")
5192 (if (use-region-p)
5193 (backward-delete-char-untabify arg)
5194 (let ((cur-pos (current-column))
5195 (start-of-indention (save-excursion
5196 (back-to-indentation)
5197 (current-column)))
5198 (positions (markdown-calc-indents)))
5199 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
5200 (indent-line-to (markdown-exdent-find-next-position cur-pos positions))
5201 (backward-delete-char-untabify arg)))))
5203 (defun markdown-find-leftmost-column (beg end)
5204 "Find the leftmost column in the region from BEG to END."
5205 (let ((mincol 1000))
5206 (save-excursion
5207 (goto-char beg)
5208 (while (< (point) end)
5209 (back-to-indentation)
5210 (unless (looking-at-p "[ \t]*$")
5211 (setq mincol (min mincol (current-column))))
5212 (forward-line 1)
5214 mincol))
5216 (defun markdown-indent-region (beg end arg)
5217 "Indent the region from BEG to END using some heuristics.
5218 When ARG is non-nil, exdent the region instead.
5219 See `markdown-indent-line' and `markdown-indent-line'."
5220 (interactive "*r\nP")
5221 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
5222 (leftmostcol (markdown-find-leftmost-column beg end))
5223 (next-pos (if arg
5224 (markdown-exdent-find-next-position leftmostcol positions)
5225 (markdown-indent-find-next-position leftmostcol positions))))
5226 (indent-rigidly beg end (- next-pos leftmostcol))
5227 (setq deactivate-mark nil)))
5229 (defun markdown-exdent-region (beg end)
5230 "Call `markdown-indent-region' on region from BEG to END with prefix."
5231 (interactive "*r")
5232 (markdown-indent-region beg end t))
5235 ;;; Markup Completion =========================================================
5237 (defconst markdown-complete-alist
5238 '((markdown-regex-header-atx . markdown-complete-atx)
5239 (markdown-regex-header-setext . markdown-complete-setext)
5240 (markdown-regex-hr . markdown-complete-hr))
5241 "Association list of form (regexp . function) for markup completion.")
5243 (defun markdown-incomplete-atx-p ()
5244 "Return t if ATX header markup is incomplete and nil otherwise.
5245 Assumes match data is available for `markdown-regex-header-atx'.
5246 Checks that the number of trailing hash marks equals the number of leading
5247 hash marks, that there is only a single space before and after the text,
5248 and that there is no extraneous whitespace in the text."
5250 ;; Number of starting and ending hash marks differs
5251 (not (= (length (match-string 1)) (length (match-string 3))))
5252 ;; When the header text is not empty...
5253 (and (> (length (match-string 2)) 0)
5254 ;; ...if there are extra leading, trailing, or interior spaces
5255 (or (not (= (match-beginning 2) (1+ (match-end 1))))
5256 (not (= (match-beginning 3) (1+ (match-end 2))))
5257 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
5258 ;; When the header text is empty...
5259 (and (= (length (match-string 2)) 0)
5260 ;; ...if there are too many or too few spaces
5261 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
5263 (defun markdown-complete-atx ()
5264 "Complete and normalize ATX headers.
5265 Add or remove hash marks to the end of the header to match the
5266 beginning. Ensure that there is only a single space between hash
5267 marks and header text. Removes extraneous whitespace from header text.
5268 Assumes match data is available for `markdown-regex-header-atx'.
5269 Return nil if markup was complete and non-nil if markup was completed."
5270 (when (markdown-incomplete-atx-p)
5271 (let* ((new-marker (make-marker))
5272 (new-marker (set-marker new-marker (match-end 2))))
5273 ;; Hash marks and spacing at end
5274 (goto-char (match-end 2))
5275 (delete-region (match-end 2) (match-end 3))
5276 (insert " " (match-string 1))
5277 ;; Remove extraneous whitespace from title
5278 (replace-match (markdown-compress-whitespace-string (match-string 2))
5279 t t nil 2)
5280 ;; Spacing at beginning
5281 (goto-char (match-end 1))
5282 (delete-region (match-end 1) (match-beginning 2))
5283 (insert " ")
5284 ;; Leave point at end of text
5285 (goto-char new-marker))))
5287 (defun markdown-incomplete-setext-p ()
5288 "Return t if setext header markup is incomplete and nil otherwise.
5289 Assumes match data is available for `markdown-regex-header-setext'.
5290 Checks that length of underline matches text and that there is no
5291 extraneous whitespace in the text."
5292 (or (not (= (length (match-string 1)) (length (match-string 2))))
5293 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
5295 (defun markdown-complete-setext ()
5296 "Complete and normalize setext headers.
5297 Add or remove underline characters to match length of header
5298 text. Removes extraneous whitespace from header text. Assumes
5299 match data is available for `markdown-regex-header-setext'.
5300 Return nil if markup was complete and non-nil if markup was completed."
5301 (when (markdown-incomplete-setext-p)
5302 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
5303 (char (char-after (match-beginning 2)))
5304 (level (if (char-equal char ?-) 2 1)))
5305 (goto-char (match-beginning 0))
5306 (delete-region (match-beginning 0) (match-end 0))
5307 (markdown-insert-header level text t)
5308 t)))
5310 (defun markdown-incomplete-hr-p ()
5311 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
5312 Assumes match data is available for `markdown-regex-hr'."
5313 (not (member (match-string 0) markdown-hr-strings)))
5315 (defun markdown-complete-hr ()
5316 "Complete horizontal rules.
5317 If horizontal rule string is a member of `markdown-hr-strings',
5318 do nothing. Otherwise, replace with the car of
5319 `markdown-hr-strings'.
5320 Assumes match data is available for `markdown-regex-hr'.
5321 Return nil if markup was complete and non-nil if markup was completed."
5322 (when (markdown-incomplete-hr-p)
5323 (replace-match (car markdown-hr-strings))
5326 (defun markdown-complete ()
5327 "Complete markup of object near point or in region when active.
5328 Handle all objects in `markdown-complete-alist', in order.
5329 See `markdown-complete-at-point' and `markdown-complete-region'."
5330 (interactive "*")
5331 (if (markdown-use-region-p)
5332 (markdown-complete-region (region-beginning) (region-end))
5333 (markdown-complete-at-point)))
5335 (defun markdown-complete-at-point ()
5336 "Complete markup of object near point.
5337 Handle all elements of `markdown-complete-alist' in order."
5338 (interactive "*")
5339 (let ((list markdown-complete-alist) found changed)
5340 (while list
5341 (let ((regexp (eval (caar list)))
5342 (function (cdar list)))
5343 (setq list (cdr list))
5344 (when (thing-at-point-looking-at regexp)
5345 (setq found t)
5346 (setq changed (funcall function))
5347 (setq list nil))))
5348 (if found
5349 (or changed (error "Markup at point is complete"))
5350 (error "Nothing to complete at point"))))
5352 (defun markdown-complete-region (beg end)
5353 "Complete markup of objects in region from BEG to END.
5354 Handle all objects in `markdown-complete-alist', in order. Each
5355 match is checked to ensure that a previous regexp does not also
5356 match."
5357 (interactive "*r")
5358 (let ((end-marker (set-marker (make-marker) end))
5359 previous)
5360 (dolist (element markdown-complete-alist)
5361 (let ((regexp (eval (car element)))
5362 (function (cdr element)))
5363 (goto-char beg)
5364 (while (re-search-forward regexp end-marker 'limit)
5365 (when (match-string 0)
5366 ;; Make sure this is not a match for any of the preceding regexps.
5367 ;; This prevents mistaking an HR for a Setext subheading.
5368 (let (match)
5369 (save-match-data
5370 (dolist (prev-regexp previous)
5371 (or match (setq match (looking-back prev-regexp nil)))))
5372 (unless match
5373 (save-excursion (funcall function))))))
5374 (cl-pushnew regexp previous :test #'equal)))
5375 previous))
5377 (defun markdown-complete-buffer ()
5378 "Complete markup for all objects in the current buffer."
5379 (interactive "*")
5380 (markdown-complete-region (point-min) (point-max)))
5383 ;;; Markup Cycling ============================================================
5385 (defun markdown-cycle-atx (arg &optional remove)
5386 "Cycle ATX header markup.
5387 Promote header (decrease level) when ARG is 1 and demote
5388 header (increase level) if arg is -1. When REMOVE is non-nil,
5389 remove the header when the level reaches zero and stop cycling
5390 when it reaches six. Otherwise, perform a proper cycling through
5391 levels one through six. Assumes match data is available for
5392 `markdown-regex-header-atx'."
5393 (let* ((old-level (length (match-string 1)))
5394 (new-level (+ old-level arg))
5395 (text (match-string 2)))
5396 (when (not remove)
5397 (setq new-level (% new-level 6))
5398 (setq new-level (cond ((= new-level 0) 6)
5399 ((< new-level 0) (+ new-level 6))
5400 (t new-level))))
5401 (cond
5402 ((= new-level 0)
5403 (markdown-unwrap-thing-at-point nil 0 2))
5404 ((<= new-level 6)
5405 (goto-char (match-beginning 0))
5406 (delete-region (match-beginning 0) (match-end 0))
5407 (markdown-insert-header new-level text nil)))))
5409 (defun markdown-cycle-setext (arg &optional remove)
5410 "Cycle setext header markup.
5411 Promote header (increase level) when ARG is 1 and demote
5412 header (decrease level or remove) if arg is -1. When demoting a
5413 level-two setext header, replace with a level-three atx header.
5414 When REMOVE is non-nil, remove the header when the level reaches
5415 zero. Otherwise, cycle back to a level six atx header. Assumes
5416 match data is available for `markdown-regex-header-setext'."
5417 (let* ((char (char-after (match-beginning 2)))
5418 (old-level (if (char-equal char ?=) 1 2))
5419 (new-level (+ old-level arg)))
5420 (when (and (not remove) (= new-level 0))
5421 (setq new-level 6))
5422 (cond
5423 ((= new-level 0)
5424 (markdown-unwrap-thing-at-point nil 0 1))
5425 ((<= new-level 2)
5426 (markdown-insert-header new-level nil t))
5427 ((<= new-level 6)
5428 (markdown-insert-header new-level nil nil)))))
5430 (defun markdown-cycle-hr (arg &optional remove)
5431 "Cycle string used for horizontal rule from `markdown-hr-strings'.
5432 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
5433 backwards (promote). When REMOVE is non-nil, remove the hr instead
5434 of cycling when the end of the list is reached.
5435 Assumes match data is available for `markdown-regex-hr'."
5436 (let* ((strings (if (= arg -1)
5437 (reverse markdown-hr-strings)
5438 markdown-hr-strings))
5439 (tail (member (match-string 0) strings))
5440 (new (or (cadr tail)
5441 (if remove
5442 (if (= arg 1)
5444 (car tail))
5445 (car strings)))))
5446 (replace-match new)))
5448 (defun markdown-cycle-bold ()
5449 "Cycle bold markup between underscores and asterisks.
5450 Assumes match data is available for `markdown-regex-bold'."
5451 (save-excursion
5452 (let* ((old-delim (match-string 3))
5453 (new-delim (if (string-equal old-delim "**") "__" "**")))
5454 (replace-match new-delim t t nil 3)
5455 (replace-match new-delim t t nil 5))))
5457 (defun markdown-cycle-italic ()
5458 "Cycle italic markup between underscores and asterisks.
5459 Assumes match data is available for `markdown-regex-italic'."
5460 (save-excursion
5461 (let* ((old-delim (match-string 2))
5462 (new-delim (if (string-equal old-delim "*") "_" "*")))
5463 (replace-match new-delim t t nil 2)
5464 (replace-match new-delim t t nil 4))))
5467 ;;; Keymap ====================================================================
5469 (defvar markdown-mode-map
5470 (let ((map (make-keymap)))
5471 ;; Element insertion
5472 (define-key map "\C-c\C-al" 'markdown-insert-inline-link-dwim)
5473 (define-key map "\C-c\C-aL" 'markdown-insert-reference-link-dwim)
5474 (define-key map "\C-c\C-au" 'markdown-insert-uri)
5475 (define-key map "\C-c\C-af" 'markdown-insert-footnote)
5476 (define-key map "\C-c\C-aw" 'markdown-insert-wiki-link)
5477 (define-key map "\C-c\C-ii" 'markdown-insert-image)
5478 (define-key map "\C-c\C-iI" 'markdown-insert-reference-image)
5479 (define-key map "\C-c\C-th" 'markdown-insert-header-dwim)
5480 (define-key map "\C-c\C-tH" 'markdown-insert-header-setext-dwim)
5481 (define-key map "\C-c\C-t1" 'markdown-insert-header-atx-1)
5482 (define-key map "\C-c\C-t2" 'markdown-insert-header-atx-2)
5483 (define-key map "\C-c\C-t3" 'markdown-insert-header-atx-3)
5484 (define-key map "\C-c\C-t4" 'markdown-insert-header-atx-4)
5485 (define-key map "\C-c\C-t5" 'markdown-insert-header-atx-5)
5486 (define-key map "\C-c\C-t6" 'markdown-insert-header-atx-6)
5487 (define-key map "\C-c\C-t!" 'markdown-insert-header-setext-1)
5488 (define-key map "\C-c\C-t@" 'markdown-insert-header-setext-2)
5489 (define-key map "\C-c\C-ss" 'markdown-insert-bold)
5490 (define-key map "\C-c\C-se" 'markdown-insert-italic)
5491 (define-key map "\C-c\C-sc" 'markdown-insert-code)
5492 (define-key map "\C-c\C-sb" 'markdown-insert-blockquote)
5493 (define-key map "\C-c\C-sk" 'markdown-insert-kbd)
5494 (define-key map "\C-c\C-s\C-b" 'markdown-blockquote-region)
5495 (define-key map "\C-c\C-sp" 'markdown-insert-pre)
5496 (define-key map "\C-c\C-s\C-p" 'markdown-pre-region)
5497 (define-key map "\C-c\C-sP" 'markdown-insert-gfm-code-block)
5498 (define-key map "\C-c-" 'markdown-insert-hr)
5499 ;; Element insertion (deprecated)
5500 (define-key map "\C-c\C-ar" 'markdown-insert-reference-link-dwim)
5501 (define-key map "\C-c\C-tt" 'markdown-insert-header-setext-1)
5502 (define-key map "\C-c\C-ts" 'markdown-insert-header-setext-2)
5503 ;; Element removal
5504 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
5505 ;; Promotion, Demotion, Completion, and Cycling
5506 (define-key map (kbd "C-c C--") 'markdown-promote)
5507 (define-key map (kbd "C-c C-=") 'markdown-demote)
5508 (define-key map (kbd "C-c C-]") 'markdown-complete)
5509 ;; Following and Jumping
5510 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
5511 (define-key map (kbd "C-c C-l") 'markdown-jump)
5512 ;; Indentation
5513 (define-key map (kbd "C-m") 'markdown-enter-key)
5514 (define-key map (kbd "DEL") 'markdown-exdent-or-delete)
5515 (define-key map (kbd "C-c >") 'markdown-indent-region)
5516 (define-key map (kbd "C-c <") 'markdown-exdent-region)
5517 ;; Visibility cycling
5518 (define-key map (kbd "TAB") 'markdown-cycle)
5519 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
5520 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
5521 (define-key map (kbd "<backtab>") 'markdown-shifttab)
5522 ;; Header navigation
5523 (define-key map (kbd "C-c C-n") 'markdown-next-visible-heading)
5524 (define-key map (kbd "C-c C-p") 'markdown-previous-visible-heading)
5525 (define-key map (kbd "C-c C-f") 'markdown-forward-same-level)
5526 (define-key map (kbd "C-c C-b") 'markdown-backward-same-level)
5527 (define-key map (kbd "C-c C-u") 'markdown-up-heading)
5528 ;; Buffer-wide commands
5529 (define-key map (kbd "C-c C-c m") 'markdown-other-window)
5530 (define-key map (kbd "C-c C-c p") 'markdown-preview)
5531 (define-key map (kbd "C-c C-c e") 'markdown-export)
5532 (define-key map (kbd "C-c C-c v") 'markdown-export-and-preview)
5533 (define-key map (kbd "C-c C-c o") 'markdown-open)
5534 (define-key map (kbd "C-c C-c l") 'markdown-live-preview-mode)
5535 (define-key map (kbd "C-c C-c w") 'markdown-kill-ring-save)
5536 (define-key map (kbd "C-c C-c c") 'markdown-check-refs)
5537 (define-key map (kbd "C-c C-c n") 'markdown-cleanup-list-numbers)
5538 (define-key map (kbd "C-c C-c ]") 'markdown-complete-buffer)
5539 (define-key map (kbd "C-c '") 'markdown-edit-code-block)
5540 ;; List editing
5541 (define-key map (kbd "M-<up>") 'markdown-move-up)
5542 (define-key map (kbd "M-<down>") 'markdown-move-down)
5543 (define-key map (kbd "M-<left>") 'markdown-promote)
5544 (define-key map (kbd "M-<right>") 'markdown-demote)
5545 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
5546 (define-key map (kbd "C-c C-j") 'markdown-insert-list-item)
5547 ;; Subtree editing
5548 (define-key map (kbd "M-S-<up>") 'markdown-move-subtree-up)
5549 (define-key map (kbd "M-S-<down>") 'markdown-move-subtree-down)
5550 (define-key map (kbd "M-S-<left>") 'markdown-promote-subtree)
5551 (define-key map (kbd "M-S-<right>") 'markdown-demote-subtree)
5552 (define-key map (kbd "C-c C-M-h") 'markdown-mark-subtree)
5553 (define-key map (kbd "C-x n s") 'markdown-narrow-to-subtree)
5554 ;; Blocks
5555 (define-key map [remap backward-paragraph] 'markdown-backward-block)
5556 (define-key map [remap forward-paragraph] 'markdown-forward-block)
5557 (define-key map [remap mark-paragraph] 'markdown-mark-block)
5558 (define-key map (kbd "C-x n b") 'markdown-narrow-to-block)
5559 ;; Text Blocks (contextually unaware)
5560 (define-key map (kbd "C-M-{") 'markdown-beginning-of-text-block)
5561 (define-key map (kbd "C-M-}") 'markdown-end-of-text-block)
5562 (define-key map (kbd "C-c M-h") 'markdown-mark-text-block)
5563 ;; Pages (top-level sections)
5564 (define-key map [remap backward-page] 'markdown-backward-page)
5565 (define-key map [remap forward-page] 'markdown-forward-page)
5566 (define-key map [remap mark-page] 'markdown-mark-page)
5567 (define-key map [remap narrow-to-page] 'markdown-narrow-to-page)
5568 ;; Link Movement
5569 (define-key map (kbd "M-n") 'markdown-next-link)
5570 (define-key map (kbd "M-p") 'markdown-previous-link)
5571 ;; Toggling functionality
5572 (define-key map (kbd "C-c C-x C-f") 'markdown-toggle-fontify-code-blocks-natively)
5573 (define-key map (kbd "C-c C-x C-i") 'markdown-toggle-inline-images)
5574 (define-key map (kbd "C-c C-x C-l") 'markdown-toggle-url-hiding)
5575 (define-key map (kbd "C-c C-x C-m") 'markdown-toggle-markup-hiding)
5576 (define-key map (kbd "C-c C-x C-x") 'markdown-toggle-gfm-checkbox)
5577 ;; Alternative keys (in case of problems with the arrow keys)
5578 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
5579 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
5580 (define-key map (kbd "C-c C-x l") 'markdown-promote)
5581 (define-key map (kbd "C-c C-x r") 'markdown-demote)
5582 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item)
5583 ;; Deprecated keys
5584 (define-key map "\C-c\C-i\C-t" 'markdown-toggle-inline-images)
5585 map)
5586 "Keymap for Markdown major mode.")
5588 (defvar markdown-mode-mouse-map
5589 (let ((map (make-sparse-keymap)))
5590 (define-key map [follow-link] 'mouse-face)
5591 (define-key map [mouse-2] 'markdown-follow-link-at-point)
5592 map)
5593 "Keymap for following links with mouse.")
5595 (defvar gfm-mode-map
5596 (let ((map (make-sparse-keymap)))
5597 (set-keymap-parent map markdown-mode-map)
5598 (define-key map (kbd "C-c C-s d") 'markdown-insert-strike-through)
5599 (define-key map "`" 'markdown-electric-backquote)
5600 map)
5601 "Keymap for `gfm-mode'.
5602 See also `markdown-mode-map'.")
5605 ;;; Menu ==================================================================
5607 (easy-menu-define markdown-mode-menu markdown-mode-map
5608 "Menu for Markdown mode"
5609 '("Markdown"
5610 "---"
5611 ("Movement"
5612 ["Jump" markdown-jump]
5613 ["Follow Link" markdown-follow-thing-at-point]
5614 ["Next Link" markdown-next-link]
5615 ["Previous Link" markdown-previous-link]
5616 "---"
5617 ["Next Visible Heading" markdown-next-visible-heading]
5618 ["Previous Visible Heading" markdown-previous-visible-heading]
5619 ["Forward Same Level" markdown-forward-same-level]
5620 ["Backward Same Level" markdown-backward-same-level]
5621 ["Up to Parent Heading" markdown-up-heading]
5622 "---"
5623 ["Forward Block" markdown-forward-block]
5624 ["Backward Block" markdown-backward-block])
5625 ("Show & Hide"
5626 ["Cycle Heading Visibility" markdown-cycle (markdown-on-heading-p)]
5627 ["Cycle Heading Visibility (Global)" markdown-shifttab]
5628 "---"
5629 ["Narrow to Region" narrow-to-region]
5630 ["Narrow to Block" markdown-narrow-to-block]
5631 ["Narrow to Section" narrow-to-defun]
5632 ["Narrow to Subtree" markdown-narrow-to-subtree]
5633 ["Widen" widen (buffer-narrowed-p)]
5634 "---"
5635 ["Toggle Markup Hiding" markdown-toggle-markup-hiding
5636 :style radio
5637 :selected markdown-hide-markup])
5638 "---"
5639 ("Headings & Structure"
5640 ["Automatic Heading" markdown-insert-header-dwim]
5641 ["Automatic Heading (Setext)" markdown-insert-header-setext-dwim]
5642 ("Specific Heading (atx)"
5643 ["First Level Setext" markdown-insert-header-setext-1]
5644 ["Second Level Setext" markdown-insert-header-setext-2])
5645 ("Specific Heading (Setext)"
5646 ["First Level atx" markdown-insert-header-atx-1]
5647 ["Second Level atx" markdown-insert-header-atx-2]
5648 ["Third Level atx" markdown-insert-header-atx-3]
5649 ["Fourth Level atx" markdown-insert-header-atx-4]
5650 ["Fifth Level atx" markdown-insert-header-atx-5]
5651 ["Sixth Level atx" markdown-insert-header-atx-6])
5652 ["Horizontal Rule" markdown-insert-hr]
5653 "---"
5654 ["Move Subtree Up" markdown-move-subtree-up :keys "M-S-<up>"]
5655 ["Move Subtree Down" markdown-move-subtree-down :keys "M-S-<down>"]
5656 ["Promote Subtree" markdown-promote-subtree :keys "M-S-<left>"]
5657 ["Demote Subtree" markdown-demote-subtree :keys "M-S-<right>"]
5658 ["Promote Header" markdown-promote :keys "M-<left>"]
5659 ["Demote Header" markdown-demote :keys "M-<right>"])
5660 ("Region & Mark"
5661 ["Indent Region" markdown-indent-region]
5662 ["Exdent Region" markdown-exdent-region]
5663 "--"
5664 ["Mark Block" markdown-mark-block]
5665 ["Mark Plain Text Block" markdown-mark-text-block]
5666 ["Mark Section" mark-defun]
5667 ["Mark Subtree" markdown-mark-subtree])
5668 ("Lists"
5669 ["Insert List Item" markdown-insert-list-item]
5670 ["Move List Item Up" markdown-move-up :keys "M-<up>"]
5671 ["Move List Item Down" markdown-move-down :keys "M-<down>"]
5672 ["Exdent List Item" markdown-promote :keys "M-<left>"]
5673 ["Indent List Item" markdown-demote :keys "M-<right>"]
5674 ["Renumber List" markdown-cleanup-list-numbers]
5675 ["Toggle Task List Item" markdown-toggle-gfm-checkbox])
5676 ("Links & Images"
5677 ["Plain URL" markdown-insert-uri]
5678 ["Inline Link" markdown-insert-inline-link-dwim]
5679 ["Inline Image" markdown-insert-image]
5680 ["Reference Link" markdown-insert-reference-link-dwim]
5681 ["Reference Image" markdown-insert-reference-image]
5682 ["Footnote" markdown-insert-footnote]
5683 ["Wiki Link" markdown-insert-wiki-link]
5684 "---"
5685 ["Check References" markdown-check-refs]
5686 ["Toggle URL Hiding" markdown-toggle-url-hiding
5687 :style radio
5688 :selected markdown-hide-urls]
5689 ["Toggle Inline Images" markdown-toggle-inline-images
5690 :style radio
5691 :selected markdown-inline-image-overlays]
5692 ["Toggle Wiki Links" markdown-toggle-wiki-links
5693 :style radio
5694 :selected markdown-enable-wiki-links])
5695 ("Styles"
5696 ["Bold" markdown-insert-bold]
5697 ["Italic" markdown-insert-italic]
5698 ["Code" markdown-insert-code]
5699 ["Strikethrough" markdown-insert-strike-through]
5700 ["Keyboard" markdown-insert-kbd]
5701 "---"
5702 ["Blockquote" markdown-insert-blockquote]
5703 ["Preformatted" markdown-insert-pre]
5704 ["GFM Code Block" markdown-insert-gfm-code-block]
5705 ["Edit Code Block" markdown-edit-code-block (markdown-code-block-at-point-p)]
5706 "---"
5707 ["Blockquote Region" markdown-blockquote-region]
5708 ["Preformatted Region" markdown-pre-region]
5709 "---"
5710 ["Fontify Code Blocks Natively" markdown-toggle-fontify-code-blocks-natively
5711 :style radio
5712 :selected markdown-fontify-code-blocks-natively]
5713 ["LaTeX Math Support" markdown-toggle-math
5714 :style radio
5715 :selected markdown-enable-math])
5716 "---"
5717 ("Preview & Export"
5718 ["Compile" markdown-other-window]
5719 ["Preview" markdown-preview]
5720 ["Export" markdown-export]
5721 ["Export & View" markdown-export-and-preview]
5722 ["Open" markdown-open]
5723 ["Live Export" markdown-live-preview-mode
5724 :style radio
5725 :selected markdown-live-preview-mode]
5726 ["Kill ring save" markdown-kill-ring-save])
5727 ("Markup Completion and Cycling"
5728 ["Complete Markup" markdown-complete]
5729 ["Promote Element" markdown-promote]
5730 ["Demote Element" markdown-demote])
5731 "---"
5732 ["Kill Element" markdown-kill-thing-at-point]
5733 "---"
5734 ("Documentation"
5735 ["Version" markdown-show-version]
5736 ["Homepage" markdown-mode-info]
5737 ["Describe Mode" (describe-function 'markdown-mode)]
5738 ["Guide" (browse-url "https://leanpub.com/markdown-mode")])))
5741 ;;; imenu =====================================================================
5743 (defun markdown-imenu-create-nested-index ()
5744 "Create and return a nested imenu index alist for the current buffer.
5745 See `imenu-create-index-function' and `imenu--index-alist' for details."
5746 (let* ((root '(nil . nil))
5747 cur-alist
5748 (cur-level 0)
5749 (empty-heading "-")
5750 (self-heading ".")
5751 hashes pos level heading)
5752 (save-excursion
5753 (goto-char (point-min))
5754 (while (re-search-forward markdown-regex-header (point-max) t)
5755 (unless (markdown-code-block-at-point-p)
5756 (cond
5757 ((match-string-no-properties 2) ;; level 1 setext
5758 (setq heading (match-string-no-properties 1))
5759 (setq pos (match-beginning 1)
5760 level 1))
5761 ((match-string-no-properties 3) ;; level 2 setext
5762 (setq heading (match-string-no-properties 1))
5763 (setq pos (match-beginning 1)
5764 level 2))
5765 ((setq hashes (markdown-trim-whitespace
5766 (match-string-no-properties 4)))
5767 (setq heading (match-string-no-properties 5)
5768 pos (match-beginning 4)
5769 level (length hashes))))
5770 (let ((alist (list (cons heading pos))))
5771 (cond
5772 ((= cur-level level) ; new sibling
5773 (setcdr cur-alist alist)
5774 (setq cur-alist alist))
5775 ((< cur-level level) ; first child
5776 (dotimes (_ (- level cur-level 1))
5777 (setq alist (list (cons empty-heading alist))))
5778 (if cur-alist
5779 (let* ((parent (car cur-alist))
5780 (self-pos (cdr parent)))
5781 (setcdr parent (cons (cons self-heading self-pos) alist)))
5782 (setcdr root alist)) ; primogenitor
5783 (setq cur-alist alist)
5784 (setq cur-level level))
5785 (t ; new sibling of an ancestor
5786 (let ((sibling-alist (last (cdr root))))
5787 (dotimes (_ (1- level))
5788 (setq sibling-alist (last (cdar sibling-alist))))
5789 (setcdr sibling-alist alist)
5790 (setq cur-alist alist))
5791 (setq cur-level level))))))
5792 (cdr root))))
5794 (defun markdown-imenu-create-flat-index ()
5795 "Create and return a flat imenu index alist for the current buffer.
5796 See `imenu-create-index-function' and `imenu--index-alist' for details."
5797 (let* ((empty-heading "-") index heading pos)
5798 (save-excursion
5799 (goto-char (point-min))
5800 (while (re-search-forward markdown-regex-header (point-max) t)
5801 (when (and (not (markdown-code-block-at-point-p))
5802 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin)))
5803 (cond
5804 ((setq heading (match-string-no-properties 1))
5805 (setq pos (match-beginning 1)))
5806 ((setq heading (match-string-no-properties 5))
5807 (setq pos (match-beginning 4))))
5808 (or (> (length heading) 0)
5809 (setq heading empty-heading))
5810 (setq index (append index (list (cons heading pos))))))
5811 index)))
5814 ;;; References ================================================================
5816 (defun markdown-reference-goto-definition ()
5817 "Jump to the definition of the reference at point or create it."
5818 (interactive)
5819 (when (thing-at-point-looking-at markdown-regex-link-reference)
5820 (let* ((text (match-string-no-properties 3))
5821 (reference (match-string-no-properties 6))
5822 (target (downcase (if (string= reference "") text reference)))
5823 (loc (cadr (save-match-data (markdown-reference-definition target)))))
5824 (if loc
5825 (goto-char loc)
5826 (goto-char (match-beginning 0))
5827 (markdown-insert-reference-definition target)))))
5829 (defun markdown-reference-find-links (reference)
5830 "Return a list of all links for REFERENCE.
5831 REFERENCE should not include the surrounding square brackets.
5832 Elements of the list have the form (text start line), where
5833 text is the link text, start is the location at the beginning of
5834 the link, and line is the line number on which the link appears."
5835 (let* ((ref-quote (regexp-quote reference))
5836 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
5837 ref-quote ref-quote))
5838 links)
5839 (save-excursion
5840 (goto-char (point-min))
5841 (while (re-search-forward regexp nil t)
5842 (let* ((text (or (match-string-no-properties 1)
5843 (match-string-no-properties 2)))
5844 (start (match-beginning 0))
5845 (line (markdown-line-number-at-pos)))
5846 (cl-pushnew (list text start line) links :test #'equal))))
5847 links))
5849 (defun markdown-get-undefined-refs ()
5850 "Return a list of undefined Markdown references.
5851 Result is an alist of pairs (reference . occurrences), where
5852 occurrences is itself another alist of pairs (label . line-number).
5853 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
5854 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
5855 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
5856 (let ((missing))
5857 (save-excursion
5858 (goto-char (point-min))
5859 (while
5860 (re-search-forward markdown-regex-link-reference nil t)
5861 (let* ((text (match-string-no-properties 3))
5862 (reference (match-string-no-properties 6))
5863 (target (downcase (if (string= reference "") text reference))))
5864 (unless (markdown-reference-definition target)
5865 (let ((entry (assoc target missing)))
5866 (if (not entry)
5867 (cl-pushnew
5868 (cons target (list (cons text (markdown-line-number-at-pos))))
5869 missing :test #'equal)
5870 (setcdr entry
5871 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
5872 (reverse missing))))
5874 (defconst markdown-reference-check-buffer
5875 "*Undefined references for %buffer%*"
5876 "Pattern for name of buffer for listing undefined references.
5877 The string %buffer% will be replaced by the corresponding
5878 `markdown-mode' buffer name.")
5880 (defun markdown-reference-check-buffer (&optional buffer-name)
5881 "Name and return buffer for reference checking.
5882 BUFFER-NAME is the name of the main buffer being visited."
5883 (or buffer-name (setq buffer-name (buffer-name)))
5884 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
5885 "%buffer%" buffer-name
5886 markdown-reference-check-buffer))))
5887 (with-current-buffer refbuf
5888 (when view-mode
5889 (View-exit-and-edit))
5890 (use-local-map button-buffer-map)
5891 (erase-buffer))
5892 refbuf))
5894 (defconst markdown-reference-links-buffer
5895 "*Reference links for %buffer%*"
5896 "Pattern for name of buffer for listing references.
5897 The string %buffer% will be replaced by the corresponding buffer name.")
5899 (defun markdown-reference-links-buffer (&optional buffer-name)
5900 "Name, setup, and return a buffer for listing links.
5901 BUFFER-NAME is the name of the main buffer being visited."
5902 (or buffer-name (setq buffer-name (buffer-name)))
5903 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
5904 "%buffer%" buffer-name
5905 markdown-reference-links-buffer))))
5906 (with-current-buffer linkbuf
5907 (when view-mode
5908 (View-exit-and-edit))
5909 (use-local-map button-buffer-map)
5910 (erase-buffer))
5911 linkbuf))
5913 ;; Add an empty Markdown reference definition to buffer
5914 ;; specified in the 'target-buffer property. The reference name is
5915 ;; the button's label.
5916 (define-button-type 'markdown-undefined-reference-button
5917 'help-echo "mouse-1, RET: create definition for undefined reference"
5918 'follow-link t
5919 'face 'bold
5920 'action (lambda (b)
5921 (let ((buffer (button-get b 'target-buffer))
5922 (line (button-get b 'target-line))
5923 (label (button-label b)))
5924 (switch-to-buffer-other-window buffer)
5925 (goto-char (point-min))
5926 (forward-line line)
5927 (markdown-insert-reference-definition label)
5928 (markdown-check-refs t))))
5930 ;; Jump to line in buffer specified by 'target-buffer property.
5931 ;; Line number is button's 'line property.
5932 (define-button-type 'markdown-goto-line-button
5933 'help-echo "mouse-1, RET: go to line"
5934 'follow-link t
5935 'face 'italic
5936 'action (lambda (b)
5937 (message (button-get b 'buffer))
5938 (switch-to-buffer-other-window (button-get b 'target-buffer))
5939 ;; use call-interactively to silence compiler
5940 (let ((current-prefix-arg (button-get b 'target-line)))
5941 (call-interactively 'goto-line))))
5943 ;; Jumps to a particular link at location given by 'target-char
5944 ;; property in buffer given by 'target-buffer property.
5945 (define-button-type 'markdown-location-button
5946 'help-echo "mouse-1, RET: jump to location of link"
5947 'follow-link t
5948 'face 'bold
5949 'action (lambda (b)
5950 (let ((target (button-get b 'target-buffer))
5951 (loc (button-get b 'target-char)))
5952 (kill-buffer-and-window)
5953 (switch-to-buffer target)
5954 (goto-char loc))))
5956 (defun markdown-insert-undefined-reference-button (reference oldbuf)
5957 "Insert a button for creating REFERENCE in buffer OLDBUF.
5958 REFERENCE should be a list of the form (reference . occurrences),
5959 as by `markdown-get-undefined-refs'."
5960 (let ((label (car reference)))
5961 ;; Create a reference button
5962 (insert-button label
5963 :type 'markdown-undefined-reference-button
5964 'target-buffer oldbuf
5965 'target-line (cdr (car (cdr reference))))
5966 (insert " (")
5967 (dolist (occurrence (cdr reference))
5968 (let ((line (cdr occurrence)))
5969 ;; Create a line number button
5970 (insert-button (number-to-string line)
5971 :type 'markdown-goto-line-button
5972 'target-buffer oldbuf
5973 'target-line line)
5974 (insert " ")))
5975 (delete-char -1)
5976 (insert ")")
5977 (newline)))
5979 (defun markdown-insert-link-button (link oldbuf)
5980 "Insert a button for jumping to LINK in buffer OLDBUF.
5981 LINK should be a list of the form (text char line) containing
5982 the link text, location, and line number."
5983 (let ((label (cl-first link))
5984 (char (cl-second link))
5985 (line (cl-third link)))
5986 ;; Create a reference button
5987 (insert-button label
5988 :type 'markdown-location-button
5989 'target-buffer oldbuf
5990 'target-char char)
5991 (insert (format " (line %d)\n" line))))
5993 (defun markdown-reference-goto-link (&optional reference)
5994 "Jump to the location of the first use of REFERENCE."
5995 (interactive)
5996 (unless reference
5997 (if (thing-at-point-looking-at markdown-regex-reference-definition)
5998 (setq reference (match-string-no-properties 2))
5999 (error "No reference definition at point")))
6000 (let ((links (markdown-reference-find-links reference)))
6001 (cond ((= (length links) 1)
6002 (goto-char (cadr (car links))))
6003 ((> (length links) 1)
6004 (let ((oldbuf (current-buffer))
6005 (linkbuf (markdown-reference-links-buffer)))
6006 (with-current-buffer linkbuf
6007 (insert "Links using reference " reference ":\n\n")
6008 (dolist (link (reverse links))
6009 (markdown-insert-link-button link oldbuf)))
6010 (view-buffer-other-window linkbuf)
6011 (goto-char (point-min))
6012 (forward-line 2)))
6014 (error "No links for reference %s" reference)))))
6016 (defun markdown-check-refs (&optional silent)
6017 "Show all undefined Markdown references in current `markdown-mode' buffer.
6018 If SILENT is non-nil, do not message anything when no undefined
6019 references found.
6020 Links which have empty reference definitions are considered to be
6021 defined."
6022 (interactive "P")
6023 (when (not (eq major-mode 'markdown-mode))
6024 (error "Not available in current mode"))
6025 (let ((oldbuf (current-buffer))
6026 (refs (markdown-get-undefined-refs))
6027 (refbuf (markdown-reference-check-buffer)))
6028 (if (null refs)
6029 (progn
6030 (when (not silent)
6031 (message "No undefined references found"))
6032 (kill-buffer refbuf))
6033 (with-current-buffer refbuf
6034 (insert "The following references are undefined:\n\n")
6035 (dolist (ref refs)
6036 (markdown-insert-undefined-reference-button ref oldbuf))
6037 (view-buffer-other-window refbuf)
6038 (goto-char (point-min))
6039 (forward-line 2)))))
6042 ;;; Lists =====================================================================
6044 (defun markdown-insert-list-item (&optional arg)
6045 "Insert a new list item.
6046 If the point is inside unordered list, insert a bullet mark. If
6047 the point is inside ordered list, insert the next number followed
6048 by a period. Use the previous list item to determine the amount
6049 of whitespace to place before and after list markers.
6051 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
6052 decrease the indentation by one level.
6054 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
6055 increase the indentation by one level."
6056 (interactive "p")
6057 (let (bounds cur-indent marker indent new-indent new-loc)
6058 (save-match-data
6059 ;; Look for a list item on current or previous non-blank line
6060 (save-excursion
6061 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
6062 (not (bobp))
6063 (markdown-cur-line-blank-p))
6064 (forward-line -1)))
6065 (when bounds
6066 (cond ((save-excursion
6067 (skip-chars-backward " \t")
6068 (looking-at-p markdown-regex-list))
6069 (beginning-of-line)
6070 (insert "\n")
6071 (forward-line -1))
6072 ((not (markdown-cur-line-blank-p))
6073 (newline)))
6074 (setq new-loc (point)))
6075 ;; Look ahead for a list item on next non-blank line
6076 (unless bounds
6077 (save-excursion
6078 (while (and (null bounds)
6079 (not (eobp))
6080 (markdown-cur-line-blank-p))
6081 (forward-line)
6082 (setq bounds (markdown-cur-list-item-bounds))))
6083 (when bounds
6084 (setq new-loc (point))
6085 (unless (markdown-cur-line-blank-p)
6086 (newline))))
6087 (if (not bounds)
6088 ;; When not in a list, start a new unordered one
6089 (progn
6090 (unless (markdown-cur-line-blank-p)
6091 (insert "\n"))
6092 (insert markdown-unordered-list-item-prefix))
6093 ;; Compute indentation and marker for new list item
6094 (setq cur-indent (nth 2 bounds))
6095 (setq marker (nth 4 bounds))
6096 ;; Is this a GFM checkbox?
6097 (when (save-excursion
6098 (goto-char (cl-first bounds))
6099 (forward-char (cl-fourth bounds))
6100 (looking-at "\\(\\[\\)[xX ]\\(\\]\\s-*\\)"))
6101 (setq marker (concat marker (match-string 1) " " (match-string 2))))
6102 (cond
6103 ;; Dedent: decrement indentation, find previous marker.
6104 ((= arg 4)
6105 (setq indent (max (- cur-indent 4) 0))
6106 (let ((prev-bounds
6107 (save-excursion
6108 (when (markdown-prev-list-item (- (nth 3 bounds) 1))
6109 (markdown-cur-list-item-bounds)))))
6110 (when prev-bounds
6111 (setq marker (nth 4 prev-bounds)))))
6112 ;; Indent: increment indentation by 4, use same marker.
6113 ((= arg 16) (setq indent (+ cur-indent 4)))
6114 ;; Same level: keep current indentation and marker.
6115 (t (setq indent cur-indent)))
6116 (setq new-indent (make-string indent 32))
6117 (goto-char new-loc)
6118 (cond
6119 ;; Ordered list
6120 ((string-match-p "[0-9]" marker)
6121 (if (= arg 16) ;; starting a new column indented one more level
6122 (insert (concat new-indent "1. "))
6123 ;; Don't use previous match-data
6124 (set-match-data nil)
6125 ;; travel up to the last item and pick the correct number. If
6126 ;; the argument was nil, "new-indent = cur-indent" is the same,
6127 ;; so we don't need special treatment. Neat.
6128 (save-excursion
6129 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
6130 (>= (forward-line -1) 0))))
6131 (let* ((old-prefix (match-string 1))
6132 (old-spacing (match-string 2))
6133 (new-prefix (if old-prefix
6134 (int-to-string (1+ (string-to-number old-prefix)))
6135 "1"))
6136 (space-adjust (- (length old-prefix) (length new-prefix)))
6137 (new-spacing (if (and (match-string 2)
6138 (not (string-match-p "\t" old-spacing))
6139 (< space-adjust 0)
6140 (> space-adjust (- 1 (length (match-string 2)))))
6141 (substring (match-string 2) 0 space-adjust)
6142 (or old-spacing ". "))))
6143 (insert (concat new-indent new-prefix new-spacing)))))
6144 ;; Unordered list, GFM task list, or ordered list with hash mark
6145 ((string-match-p "[\\*\\+-]\\|#\\." marker)
6146 (insert new-indent marker)))))))
6148 (defun markdown-move-list-item-up ()
6149 "Move the current list item up in the list when possible."
6150 (interactive)
6151 (let (cur prev old)
6152 (when (setq cur (markdown-cur-list-item-bounds))
6153 (setq old (point))
6154 (goto-char (nth 0 cur))
6155 (if (markdown-prev-list-item (nth 3 cur))
6156 (progn
6157 (setq prev (markdown-cur-list-item-bounds))
6158 (condition-case nil
6159 (progn
6160 (transpose-regions (nth 0 prev) (nth 1 prev)
6161 (nth 0 cur) (nth 1 cur) t)
6162 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
6163 ;; Catch error in case regions overlap.
6164 (error (goto-char old))))
6165 (goto-char old)))))
6167 (defun markdown-move-list-item-down ()
6168 "Move the current list item down in the list when possible."
6169 (interactive)
6170 (let (cur next old)
6171 (when (setq cur (markdown-cur-list-item-bounds))
6172 (setq old (point))
6173 (if (markdown-next-list-item (nth 3 cur))
6174 (progn
6175 (setq next (markdown-cur-list-item-bounds))
6176 (condition-case nil
6177 (progn
6178 (transpose-regions (nth 0 cur) (nth 1 cur)
6179 (nth 0 next) (nth 1 next) nil)
6180 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
6181 ;; Catch error in case regions overlap.
6182 (error (goto-char old))))
6183 (goto-char old)))))
6185 (defun markdown-demote-list-item (&optional bounds)
6186 "Indent (or demote) the current list item.
6187 Optionally, BOUNDS of the current list item may be provided if available."
6188 (interactive)
6189 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6190 (save-excursion
6191 (let ((end-marker (set-marker (make-marker) (nth 1 bounds))))
6192 (goto-char (nth 0 bounds))
6193 (while (< (point) end-marker)
6194 (unless (markdown-cur-line-blank-p)
6195 (insert (make-string markdown-list-indent-width ? )))
6196 (forward-line))))))
6198 (defun markdown-promote-list-item (&optional bounds)
6199 "Unindent (or promote) the current list item.
6200 Optionally, BOUNDS of the current list item may be provided if available."
6201 (interactive)
6202 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6203 (save-excursion
6204 (save-match-data
6205 (let ((end-marker (set-marker (make-marker) (nth 1 bounds)))
6206 num regexp)
6207 (goto-char (nth 0 bounds))
6208 (when (looking-at (format "^[ ]\\{1,%d\\}"
6209 markdown-list-indent-width))
6210 (setq num (- (match-end 0) (match-beginning 0)))
6211 (setq regexp (format "^[ ]\\{1,%d\\}" num))
6212 (while (and (< (point) end-marker)
6213 (re-search-forward regexp end-marker t))
6214 (replace-match "" nil nil)
6215 (forward-line))))))))
6217 (defun markdown-cleanup-list-numbers-level (&optional pfx)
6218 "Update the numbering for level PFX (as a string of spaces).
6220 Assume that the previously found match was for a numbered item in
6221 a list."
6222 (let ((cpfx pfx)
6223 (idx 0)
6224 (continue t)
6225 (step t)
6226 (sep nil))
6227 (while (and continue (not (eobp)))
6228 (setq step t)
6229 (cond
6230 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
6231 (setq cpfx (match-string-no-properties 1))
6232 (cond
6233 ((string= cpfx pfx)
6234 (save-excursion
6235 (replace-match
6236 (concat pfx (number-to-string (setq idx (1+ idx))) ". ")))
6237 (setq sep nil))
6238 ;; indented a level
6239 ((string< pfx cpfx)
6240 (setq sep (markdown-cleanup-list-numbers-level cpfx))
6241 (setq step nil))
6242 ;; exit the loop
6244 (setq step nil)
6245 (setq continue nil))))
6247 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
6248 (setq cpfx (match-string-no-properties 1))
6249 (cond
6250 ;; reset if separated before
6251 ((string= cpfx pfx) (when sep (setq idx 0)))
6252 ((string< cpfx pfx)
6253 (setq step nil)
6254 (setq continue nil))))
6255 (t (setq sep t)))
6257 (when step
6258 (beginning-of-line)
6259 (setq continue (= (forward-line) 0))))
6260 sep))
6262 (defun markdown-cleanup-list-numbers ()
6263 "Update the numbering of ordered lists."
6264 (interactive)
6265 (save-excursion
6266 (goto-char (point-min))
6267 (markdown-cleanup-list-numbers-level "")))
6270 ;;; Movement ==================================================================
6272 (defun markdown-beginning-of-defun (&optional arg)
6273 "`beginning-of-defun-function' for Markdown.
6274 This is used to find the beginning of the defun and should behave
6275 like ‘beginning-of-defun’, returning non-nil if it found the
6276 beginning of a defun. It moves the point backward, right before a
6277 heading which defines a defun. When ARG is non-nil, repeat that
6278 many times. When ARG is negative, move forward to the ARG-th
6279 following section."
6280 (or arg (setq arg 1))
6281 (when (< arg 0) (end-of-line))
6282 ;; Adjust position for setext headings.
6283 (when (and (thing-at-point-looking-at markdown-regex-header-setext)
6284 (not (= (point) (match-beginning 0)))
6285 (not (markdown-code-block-at-point-p)))
6286 (goto-char (match-end 0)))
6287 (let (found)
6288 ;; Move backward with positive argument.
6289 (while (and (not (bobp)) (> arg 0))
6290 (setq found nil)
6291 (while (and (not found)
6292 (not (bobp))
6293 (re-search-backward markdown-regex-header nil 'move))
6294 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6295 (setq found (match-beginning 0)))
6296 (setq arg (1- arg)))
6297 ;; Move forward with negative argument.
6298 (while (and (not (eobp)) (< arg 0))
6299 (setq found nil)
6300 (while (and (not found)
6301 (not (eobp))
6302 (re-search-forward markdown-regex-header nil 'move))
6303 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6304 (setq found (match-beginning 0)))
6305 (setq arg (1+ arg)))
6306 (when found
6307 (beginning-of-line)
6308 t)))
6310 (defun markdown-end-of-defun ()
6311 "`end-of-defun-function’ for Markdown.
6312 This is used to find the end of the defun at point.
6313 It is called with no argument, right after calling ‘beginning-of-defun-raw’,
6314 so it can assume that point is at the beginning of the defun body.
6315 It should move point to the first position after the defun."
6316 (or (eobp) (forward-char 1))
6317 (let (found)
6318 (while (and (not found)
6319 (not (eobp))
6320 (re-search-forward markdown-regex-header nil 'move))
6321 (when (not (markdown-code-block-at-pos (match-beginning 0)))
6322 (setq found (match-beginning 0))))
6323 (when found
6324 (goto-char found)
6325 (skip-syntax-backward "-"))))
6327 (make-obsolete 'markdown-beginning-of-block 'markdown-beginning-of-text-block "v2.2")
6329 (defun markdown-beginning-of-text-block ()
6330 "Move backward to previous beginning of a plain text block.
6331 This function simply looks for blank lines without considering
6332 the surrounding context in light of Markdown syntax. For that, see
6333 `markdown-backward-block'."
6334 (interactive)
6335 (let ((start (point)))
6336 (if (re-search-backward markdown-regex-block-separator nil t)
6337 (goto-char (match-end 0))
6338 (goto-char (point-min)))
6339 (when (and (= start (point)) (not (bobp)))
6340 (forward-line -1)
6341 (if (re-search-backward markdown-regex-block-separator nil t)
6342 (goto-char (match-end 0))
6343 (goto-char (point-min))))))
6345 (make-obsolete 'markdown-end-of-block 'markdown-end-of-text-block "v2.2")
6347 (defun markdown-end-of-text-block ()
6348 "Move forward to next beginning of a plain text block.
6349 This function simply looks for blank lines without considering
6350 the surrounding context in light of Markdown syntax. For that, see
6351 `markdown-forward-block'."
6352 (interactive)
6353 (beginning-of-line)
6354 (skip-syntax-forward "-")
6355 (when (= (point) (point-min))
6356 (forward-char))
6357 (if (re-search-forward markdown-regex-block-separator nil t)
6358 (goto-char (match-end 0))
6359 (goto-char (point-max)))
6360 (skip-syntax-backward "-")
6361 (forward-line))
6363 (defun markdown-backward-block (&optional arg)
6364 "Move the point to the start of the current Markdown block.
6365 Moves across complete code blocks, list items, and blockquotes,
6366 but otherwise stops at blank lines, headers, and horizontal
6367 rules. With argument ARG, do it ARG times; a negative argument
6368 ARG = -N means move forward N blocks."
6369 (interactive "p")
6370 (or arg (setq arg 1))
6371 (if (< arg 0)
6372 (markdown-forward-block (- arg))
6373 (dotimes (_ arg)
6374 ;; Skip over whitespace in between blocks when moving backward.
6375 (skip-syntax-backward "-")
6376 (beginning-of-line)
6377 ;; Proceed forward based on the type of block.
6378 (let (bounds)
6379 (cond
6380 ;; Code blocks
6381 ((markdown-code-block-at-point-p)
6382 (forward-line -1)
6383 (while (and (markdown-code-block-at-point-p) (not (bobp)))
6384 (forward-line -1))
6385 (forward-line))
6386 ;; Headings
6387 ((markdown-heading-at-point)
6388 (goto-char (match-beginning 0)))
6389 ;; Horizontal rules
6390 ((looking-at markdown-regex-hr))
6391 ;; Blockquotes
6392 ((looking-at markdown-regex-blockquote)
6393 (forward-line -1)
6394 (while (and (looking-at markdown-regex-blockquote) (not (bobp)))
6395 (forward-line -1))
6396 (forward-line))
6397 ;; List items
6398 ((setq bounds (markdown-cur-list-item-bounds))
6399 (goto-char (cl-first bounds)))
6400 ;; Other
6402 (unless (markdown-prev-line-blank-p)
6403 ;; Already moved to beginning-of-line, so don't move back
6404 ;; again when already at the beginning of a block.
6405 (markdown-beginning-of-text-block))))))
6406 (skip-syntax-forward "-")))
6408 (defun markdown-forward-block (&optional arg)
6409 "Move forward to the next end of a Markdown block.
6410 Moves across complete code blocks, list items, and blockquotes,
6411 but otherwise stops at blank lines, headers, and horizontal
6412 rules. With argument ARG, do it ARG times; a negative argument
6413 ARG = -N means move backward N blocks."
6414 (interactive "p")
6415 (or arg (setq arg 1))
6416 (if (< arg 0)
6417 (markdown-backward-block (- arg))
6418 (dotimes (_ arg)
6419 ;; Skip over whitespace in between blocks when moving forward.
6420 (if (markdown-cur-line-blank-p)
6421 (skip-syntax-forward "-")
6422 (beginning-of-line))
6423 ;; Proceed forward based on the type of block.
6424 (let (bounds)
6425 (cond
6426 ;; Code blocks
6427 ((markdown-code-block-at-point-p)
6428 (forward-line)
6429 (while (and (markdown-code-block-at-point-p) (not (eobp)))
6430 (forward-line)))
6431 ;; Headings
6432 ((looking-at markdown-regex-header)
6433 (goto-char (or (match-end 4) (match-end 2) (match-end 3)))
6434 (forward-line))
6435 ;; Horizontal rules
6436 ((looking-at markdown-regex-hr)
6437 (forward-line))
6438 ;; Blockquotes
6439 ((looking-at markdown-regex-blockquote)
6440 (forward-line)
6441 (while (and (looking-at markdown-regex-blockquote) (not (eobp)))
6442 (forward-line)))
6443 ;; List items
6444 ((setq bounds (markdown-cur-list-item-bounds))
6445 (goto-char (cl-second bounds))
6446 (forward-line))
6447 ;; Other
6448 (t (markdown-end-of-text-block)))))))
6450 (defun markdown-backward-page (&optional count)
6451 "Move backward to boundary of the current toplevel section.
6452 With COUNT, repeat, or go forward if negative."
6453 (interactive "p")
6454 (or count (setq count 1))
6455 (if (< count 0)
6456 (markdown-forward-page (- count))
6457 (skip-syntax-backward "-")
6458 (or (markdown-back-to-heading-over-code-block t t)
6459 (goto-char (point-min)))
6460 (when (looking-at markdown-regex-header)
6461 (let ((level (markdown-outline-level)))
6462 (when (> level 1) (markdown-up-heading level))
6463 (when (> count 1)
6464 (condition-case nil
6465 (markdown-backward-same-level (1- count))
6466 (error (goto-char (point-min)))))))))
6468 (defun markdown-forward-page (&optional count)
6469 "Move forward to boundary of the current toplevel section.
6470 With COUNT, repeat, or go backward if negative."
6471 (interactive "p")
6472 (or count (setq count 1))
6473 (if (< count 0)
6474 (markdown-backward-page (- count))
6475 (if (markdown-back-to-heading-over-code-block t t)
6476 (let ((level (markdown-outline-level)))
6477 (when (> level 1) (markdown-up-heading level))
6478 (condition-case nil
6479 (markdown-forward-same-level count)
6480 (error (goto-char (point-max)))))
6481 (markdown-next-visible-heading 1))))
6483 (defun markdown-next-link ()
6484 "Jump to next inline, reference, or wiki link.
6485 If successful, return point. Otherwise, return nil.
6486 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
6487 (interactive)
6488 (let ((opoint (point)))
6489 (when (or (markdown-link-p) (markdown-wiki-link-p))
6490 ;; At a link already, move past it.
6491 (goto-char (+ (match-end 0) 1)))
6492 ;; Search for the next wiki link and move to the beginning.
6493 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t)
6494 (markdown-code-block-at-point-p)
6495 (< (point) (point-max))))
6496 (if (and (not (eq (point) opoint))
6497 (or (markdown-link-p) (markdown-wiki-link-p)))
6498 ;; Group 1 will move past non-escape character in wiki link regexp.
6499 ;; Go to beginning of group zero for all other link types.
6500 (goto-char (or (match-beginning 1) (match-beginning 0)))
6501 (goto-char opoint)
6502 nil)))
6504 (defun markdown-previous-link ()
6505 "Jump to previous wiki link.
6506 If successful, return point. Otherwise, return nil.
6507 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
6508 (interactive)
6509 (let ((opoint (point)))
6510 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t)
6511 (markdown-code-block-at-point-p)
6512 (> (point) (point-min))))
6513 (if (and (not (eq (point) opoint))
6514 (or (markdown-link-p) (markdown-wiki-link-p)))
6515 (goto-char (or (match-beginning 1) (match-beginning 0)))
6516 (goto-char opoint)
6517 nil)))
6520 ;;; Outline ===================================================================
6522 (defun markdown-move-heading-common (move-fn &optional arg)
6523 "Wrapper for `outline-mode' functions to skip false positives.
6524 MOVE-FN is a function and ARG is its argument. For example,
6525 headings inside preformatted code blocks may match
6526 `outline-regexp' but should not be considered as headings."
6527 (let ((prev -1) (start (point)))
6528 (if arg (funcall move-fn arg) (funcall move-fn))
6529 (while (and (/= prev (point)) (markdown-code-block-at-point-p))
6530 (setq prev (point))
6531 (if arg (funcall move-fn arg) (funcall move-fn)))
6532 ;; Adjust point for setext headings
6533 (save-match-data
6534 (when (thing-at-point-looking-at markdown-regex-header-setext)
6535 (goto-char (match-beginning 0))))
6536 (if (= (point) start) nil (point))))
6538 (defun markdown-next-visible-heading (arg)
6539 "Move to the next visible heading line of any level.
6540 With argument, repeats or can move backward if negative. ARG is
6541 passed to `outline-next-visible-heading'."
6542 (interactive "p")
6543 (markdown-move-heading-common 'outline-next-visible-heading arg))
6545 (defun markdown-previous-visible-heading (arg)
6546 "Move to the previous visible heading line of any level.
6547 With argument, repeats or can move backward if negative. ARG is
6548 passed to `outline-previous-visible-heading'."
6549 (interactive "p")
6550 (markdown-move-heading-common 'outline-previous-visible-heading arg))
6552 (defun markdown-next-heading ()
6553 "Move to the next heading line of any level."
6554 (markdown-move-heading-common 'outline-next-heading))
6556 (defun markdown-previous-heading ()
6557 "Move to the previous heading line of any level."
6558 (markdown-move-heading-common 'outline-previous-heading))
6560 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok no-error)
6561 "Move back to the beginning of the previous heading.
6562 Returns t if the point is at a heading, the location if a heading
6563 was found, and nil otherwise.
6564 Only visible heading lines are considered, unless INVISIBLE-OK is
6565 non-nil. Throw an error if there is no previous heading unless
6566 NO-ERROR is non-nil.
6567 Leaves match data intact for `markdown-regex-header'."
6568 (beginning-of-line)
6569 (or (and (markdown-heading-at-point)
6570 (not (markdown-code-block-at-point-p)))
6571 (let (found)
6572 (save-excursion
6573 (while (and (not found)
6574 (re-search-backward markdown-regex-header nil t))
6575 (when (and (or invisible-ok (not (outline-invisible-p)))
6576 (not (markdown-code-block-at-point-p)))
6577 (setq found (point))))
6578 (if (not found)
6579 (unless no-error (error "Before first heading"))
6580 (setq found (point))))
6581 (when found (goto-char found)))))
6583 (defun markdown-forward-same-level (arg)
6584 "Move forward to the ARG'th heading at same level as this one.
6585 Stop at the first and last headings of a superior heading."
6586 (interactive "p")
6587 (markdown-back-to-heading-over-code-block)
6588 (markdown-move-heading-common 'outline-forward-same-level arg))
6590 (defun markdown-backward-same-level (arg)
6591 "Move backward to the ARG'th heading at same level as this one.
6592 Stop at the first and last headings of a superior heading."
6593 (interactive "p")
6594 (markdown-back-to-heading-over-code-block)
6595 (while (> arg 0)
6596 ;; outline-get-last-sibling needs match-data set for outline-regexp.
6597 (let ((point-to-move-to (save-excursion
6598 (outline-get-last-sibling))))
6599 (if point-to-move-to
6600 (progn
6601 (goto-char point-to-move-to)
6602 (setq arg (1- arg)))
6603 (error "No previous same-level heading")))))
6605 (defun markdown-up-heading (arg)
6606 "Move to the visible heading line of which the present line is a subheading.
6607 With argument, move up ARG levels."
6608 (interactive "p")
6609 (and (called-interactively-p 'any)
6610 (not (eq last-command 'markdown-up-heading)) (push-mark))
6611 (markdown-move-heading-common 'outline-up-heading arg))
6613 (defun markdown-back-to-heading (&optional invisible-ok)
6614 "Move to previous heading line, or beg of this line if it's a heading.
6615 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
6616 (markdown-move-heading-common 'outline-back-to-heading invisible-ok))
6618 (defalias 'markdown-end-of-heading 'outline-end-of-heading)
6620 (defun markdown-on-heading-p ()
6621 "Return non-nil if point is on a heading line."
6622 (get-text-property (point-at-bol) 'markdown-heading))
6624 (defun markdown-end-of-subtree (&optional invisible-OK)
6625 "Move to the end of the current subtree.
6626 Only visible heading lines are considered, unless INVISIBLE-OK is
6627 non-nil.
6628 Derived from `org-end-of-subtree'."
6629 (markdown-back-to-heading invisible-OK)
6630 (let ((first t)
6631 (level (markdown-outline-level)))
6632 (while (and (not (eobp))
6633 (or first (> (markdown-outline-level) level)))
6634 (setq first nil)
6635 (markdown-next-heading))
6636 (if (memq (preceding-char) '(?\n ?\^M))
6637 (progn
6638 ;; Go to end of line before heading
6639 (forward-char -1)
6640 (if (memq (preceding-char) '(?\n ?\^M))
6641 ;; leave blank line before heading
6642 (forward-char -1)))))
6643 (point))
6645 (defun markdown-outline-fix-visibility ()
6646 "Hide any false positive headings that should not be shown.
6647 For example, headings inside preformatted code blocks may match
6648 `outline-regexp' but should not be shown as headings when cycling.
6649 Also, the ending --- line in metadata blocks appears to be a
6650 setext header, but should not be folded."
6651 (save-excursion
6652 (goto-char (point-min))
6653 ;; Unhide any false positives in metadata blocks
6654 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin)
6655 (let ((body (progn (forward-line)
6656 (markdown-text-property-at-point
6657 'markdown-yaml-metadata-section))))
6658 (when body
6659 (let ((end (progn (goto-char (cl-second body))
6660 (markdown-text-property-at-point
6661 'markdown-yaml-metadata-end))))
6662 (outline-flag-region (point-min) (1+ (cl-second end)) nil)))))
6663 ;; Hide any false positives in code blocks
6664 (unless (outline-on-heading-p)
6665 (outline-next-visible-heading 1))
6666 (while (< (point) (point-max))
6667 (when (markdown-code-block-at-point-p)
6668 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t))
6669 (outline-next-visible-heading 1))))
6671 (defvar markdown-cycle-global-status 1)
6672 (defvar markdown-cycle-subtree-status nil)
6674 (defun markdown-next-preface ()
6675 (let (finish)
6676 (while (and (not finish) (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
6677 nil 'move))
6678 (unless (markdown-code-block-at-point-p)
6679 (goto-char (match-beginning 0))
6680 (setq finish t))))
6681 (when (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
6682 (forward-char -1)))
6684 (defun markdown-show-entry ()
6685 (save-excursion
6686 (outline-back-to-heading t)
6687 (outline-flag-region (1- (point))
6688 (progn
6689 (markdown-next-preface)
6690 (if (= 1 (- (point-max) (point)))
6691 (point-max)
6692 (point)))
6693 nil)))
6695 (defun markdown-cycle (&optional arg)
6696 "Visibility cycling for Markdown mode.
6697 If ARG is t, perform global visibility cycling. If the point is
6698 at an atx-style header, cycle visibility of the corresponding
6699 subtree. Otherwise, insert a tab using `indent-relative'.
6700 Derived from `org-cycle'."
6701 (interactive "P")
6702 (cond
6703 ((eq arg t) ;; Global cycling
6704 (cond
6705 ((and (eq last-command this-command)
6706 (eq markdown-cycle-global-status 2))
6707 ;; Move from overview to contents
6708 (markdown-hide-sublevels 1)
6709 (message "CONTENTS")
6710 (setq markdown-cycle-global-status 3)
6711 (markdown-outline-fix-visibility))
6713 ((and (eq last-command this-command)
6714 (eq markdown-cycle-global-status 3))
6715 ;; Move from contents to all
6716 (markdown-show-all)
6717 (message "SHOW ALL")
6718 (setq markdown-cycle-global-status 1))
6721 ;; Defaults to overview
6722 (markdown-hide-body)
6723 (message "OVERVIEW")
6724 (setq markdown-cycle-global-status 2)
6725 (markdown-outline-fix-visibility))))
6727 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
6728 ;; At a heading: rotate between three different views
6729 (markdown-back-to-heading)
6730 (let ((goal-column 0) eoh eol eos)
6731 ;; Determine boundaries
6732 (save-excursion
6733 (markdown-back-to-heading)
6734 (save-excursion
6735 (beginning-of-line 2)
6736 (while (and (not (eobp)) ;; this is like `next-line'
6737 (get-char-property (1- (point)) 'invisible))
6738 (beginning-of-line 2)) (setq eol (point)))
6739 (markdown-end-of-heading) (setq eoh (point))
6740 (markdown-end-of-subtree t)
6741 (skip-chars-forward " \t\n")
6742 (beginning-of-line 1) ; in case this is an item
6743 (setq eos (1- (point))))
6744 ;; Find out what to do next and set `this-command'
6745 (cond
6746 ((= eos eoh)
6747 ;; Nothing is hidden behind this heading
6748 (message "EMPTY ENTRY")
6749 (setq markdown-cycle-subtree-status nil))
6750 ((>= eol eos)
6751 ;; Entire subtree is hidden in one line: open it
6752 (markdown-show-entry)
6753 (markdown-show-children)
6754 (message "CHILDREN")
6755 (setq markdown-cycle-subtree-status 'children))
6756 ((and (eq last-command this-command)
6757 (eq markdown-cycle-subtree-status 'children))
6758 ;; We just showed the children, now show everything.
6759 (markdown-show-subtree)
6760 (message "SUBTREE")
6761 (setq markdown-cycle-subtree-status 'subtree))
6763 ;; Default action: hide the subtree.
6764 (markdown-hide-subtree)
6765 (message "FOLDED")
6766 (setq markdown-cycle-subtree-status 'folded)))))
6769 (indent-for-tab-command))))
6771 (defun markdown-shifttab ()
6772 "Global visibility cycling.
6773 Calls `markdown-cycle' with argument t."
6774 (interactive)
6775 (markdown-cycle t))
6777 (defun markdown-outline-level ()
6778 "Return the depth to which a statement is nested in the outline."
6779 (cond
6780 ((markdown-code-block-at-point-p) 7) ;; Only 6 header levels are defined.
6781 ((match-end 2) 1)
6782 ((match-end 3) 2)
6783 ((match-end 4)
6784 (length (markdown-trim-whitespace (match-string-no-properties 4))))))
6786 (defun markdown-promote-subtree (&optional arg)
6787 "Promote the current subtree of ATX headings.
6788 Note that Markdown does not support heading levels higher than
6789 six and therefore level-six headings will not be promoted
6790 further. If ARG is non-nil promote the heading, otherwise
6791 demote."
6792 (interactive "*P")
6793 (save-excursion
6794 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
6795 (re-search-backward markdown-regex-header-atx nil t))
6796 (not (markdown-code-block-at-point-p)))
6797 (let ((level (length (match-string 1)))
6798 (promote-or-demote (if arg 1 -1))
6799 (remove 't))
6800 (markdown-cycle-atx promote-or-demote remove)
6801 (catch 'end-of-subtree
6802 (while (markdown-next-heading)
6803 ;; Exit if this not a higher level heading; promote otherwise.
6804 (if (and (looking-at markdown-regex-header-atx)
6805 (<= (length (match-string-no-properties 1)) level))
6806 (throw 'end-of-subtree nil)
6807 (markdown-cycle-atx promote-or-demote remove))))))))
6809 (defun markdown-demote-subtree ()
6810 "Demote the current subtree of ATX headings."
6811 (interactive)
6812 (markdown-promote-subtree t))
6814 (defun markdown-move-subtree-up ()
6815 "Move the current subtree of ATX headings up."
6816 (interactive)
6817 (outline-move-subtree-up 1))
6819 (defun markdown-move-subtree-down ()
6820 "Move the current subtree of ATX headings down."
6821 (interactive)
6822 (outline-move-subtree-down 1))
6825 ;;; Marking and Narrowing =====================================================
6827 (defun markdown-mark-block ()
6828 "Put mark at end of this block, point at beginning.
6829 The block marked is the one that contains point or follows point.
6831 Interactively, if this command is repeated or (in Transient Mark
6832 mode) if the mark is active, it marks the next block after the
6833 ones already marked."
6834 (interactive)
6835 (if (or (and (eq last-command this-command) (mark t))
6836 (and transient-mark-mode mark-active))
6837 (set-mark
6838 (save-excursion
6839 (goto-char (mark))
6840 (markdown-forward-block)
6841 (point)))
6842 (let ((beginning-of-defun-function 'markdown-backward-block)
6843 (end-of-defun-function 'markdown-forward-block))
6844 (mark-defun))))
6846 (defun markdown-narrow-to-block ()
6847 "Make text outside current block invisible.
6848 The current block is the one that contains point or follows point."
6849 (interactive)
6850 (let ((beginning-of-defun-function 'markdown-backward-block)
6851 (end-of-defun-function 'markdown-forward-block))
6852 (narrow-to-defun)))
6854 (defun markdown-mark-text-block ()
6855 "Put mark at end of this plain text block, point at beginning.
6856 The block marked is the one that contains point or follows point.
6858 Interactively, if this command is repeated or (in Transient Mark
6859 mode) if the mark is active, it marks the next block after the
6860 ones already marked."
6861 (interactive)
6862 (if (or (and (eq last-command this-command) (mark t))
6863 (and transient-mark-mode mark-active))
6864 (set-mark
6865 (save-excursion
6866 (goto-char (mark))
6867 (markdown-end-of-text-block)
6868 (point)))
6869 (let ((beginning-of-defun-function 'markdown-beginning-of-text-block)
6870 (end-of-defun-function 'markdown-end-of-text-block))
6871 (mark-defun))))
6873 (defun markdown-mark-page ()
6874 "Put mark at end of this top level section, point at beginning.
6875 The top level section marked is the one that contains point or
6876 follows point.
6878 Interactively, if this command is repeated or (in Transient Mark
6879 mode) if the mark is active, it marks the next page after the
6880 ones already marked."
6881 (interactive)
6882 (if (or (and (eq last-command this-command) (mark t))
6883 (and transient-mark-mode mark-active))
6884 (set-mark
6885 (save-excursion
6886 (goto-char (mark))
6887 (markdown-forward-page)
6888 (point)))
6889 (let ((beginning-of-defun-function 'markdown-backward-page)
6890 (end-of-defun-function 'markdown-forward-page))
6891 (mark-defun))))
6893 (defun markdown-narrow-to-page ()
6894 "Make text outside current top level section invisible.
6895 The current section is the one that contains point or follows point."
6896 (interactive)
6897 (let ((beginning-of-defun-function 'markdown-backward-page)
6898 (end-of-defun-function 'markdown-forward-page))
6899 (narrow-to-defun)))
6901 (defun markdown-mark-subtree ()
6902 "Mark the current subtree.
6903 This puts point at the start of the current subtree, and mark at the end."
6904 (interactive)
6905 (let ((beg))
6906 (if (markdown-heading-at-point)
6907 (beginning-of-line)
6908 (markdown-previous-visible-heading 1))
6909 (setq beg (point))
6910 (markdown-end-of-subtree)
6911 (push-mark (point) nil t)
6912 (goto-char beg)))
6914 (defun markdown-narrow-to-subtree ()
6915 "Narrow buffer to the current subtree."
6916 (interactive)
6917 (save-excursion
6918 (save-match-data
6919 (narrow-to-region
6920 (progn (markdown-back-to-heading-over-code-block t) (point))
6921 (progn (markdown-end-of-subtree)
6922 (if (and (markdown-heading-at-point) (not (eobp)))
6923 (backward-char 1))
6924 (point))))))
6927 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
6929 (defun markdown-move-up ()
6930 "Move list item up.
6931 Calls `markdown-move-list-item-up'."
6932 (interactive)
6933 (markdown-move-list-item-up))
6935 (defun markdown-move-down ()
6936 "Move list item down.
6937 Calls `markdown-move-list-item-down'."
6938 (interactive)
6939 (markdown-move-list-item-down))
6941 (defun markdown-promote ()
6942 "Either promote header or list item at point or cycle markup.
6943 See `markdown-cycle-atx', `markdown-cycle-setext', and
6944 `markdown-promote-list-item'."
6945 (interactive)
6946 (let (bounds)
6947 (cond
6948 ;; Promote atx header
6949 ((thing-at-point-looking-at markdown-regex-header-atx)
6950 (markdown-cycle-atx -1))
6951 ;; Promote setext header
6952 ((thing-at-point-looking-at markdown-regex-header-setext)
6953 (markdown-cycle-setext -1))
6954 ;; Promote horizonal rule
6955 ((thing-at-point-looking-at markdown-regex-hr)
6956 (markdown-cycle-hr -1))
6957 ;; Promote list item
6958 ((setq bounds (markdown-cur-list-item-bounds))
6959 (markdown-promote-list-item bounds))
6960 ;; Promote bold
6961 ((thing-at-point-looking-at markdown-regex-bold)
6962 (markdown-cycle-bold))
6963 ;; Promote italic
6964 ((thing-at-point-looking-at markdown-regex-italic)
6965 (markdown-cycle-italic))
6967 (error "Nothing to promote at point")))))
6969 (defun markdown-demote ()
6970 "Either demote header or list item at point or cycle or remove markup.
6971 See `markdown-cycle-atx', `markdown-cycle-setext', and
6972 `markdown-demote-list-item'."
6973 (interactive)
6974 (let (bounds)
6975 (cond
6976 ;; Demote atx header
6977 ((thing-at-point-looking-at markdown-regex-header-atx)
6978 (markdown-cycle-atx 1))
6979 ;; Demote setext header
6980 ((thing-at-point-looking-at markdown-regex-header-setext)
6981 (markdown-cycle-setext 1))
6982 ;; Demote horizonal rule
6983 ((thing-at-point-looking-at markdown-regex-hr)
6984 (markdown-cycle-hr 1))
6985 ;; Demote list item
6986 ((setq bounds (markdown-cur-list-item-bounds))
6987 (markdown-demote-list-item bounds))
6988 ;; Demote bold
6989 ((thing-at-point-looking-at markdown-regex-bold)
6990 (markdown-cycle-bold))
6991 ;; Demote italic
6992 ((thing-at-point-looking-at markdown-regex-italic)
6993 (markdown-cycle-italic))
6995 (error "Nothing to demote at point")))))
6998 ;;; Commands ==================================================================
7000 (defun markdown (&optional output-buffer-name)
7001 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
7002 The output buffer name defaults to `markdown-output-buffer-name'.
7003 Return the name of the output buffer used."
7004 (interactive)
7005 (save-window-excursion
7006 (let ((begin-region)
7007 (end-region))
7008 (if (markdown-use-region-p)
7009 (setq begin-region (region-beginning)
7010 end-region (region-end))
7011 (setq begin-region (point-min)
7012 end-region (point-max)))
7014 (unless output-buffer-name
7015 (setq output-buffer-name markdown-output-buffer-name))
7016 (cond
7017 ;; Handle case when `markdown-command' does not read from stdin
7018 (markdown-command-needs-filename
7019 (if (not buffer-file-name)
7020 (error "Must be visiting a file")
7021 (shell-command (concat markdown-command " "
7022 (shell-quote-argument buffer-file-name))
7023 output-buffer-name)))
7024 ;; Pass region to `markdown-command' via stdin
7026 (let ((buf (get-buffer-create output-buffer-name)))
7027 (with-current-buffer buf
7028 (setq buffer-read-only nil)
7029 (erase-buffer))
7030 (call-process-region begin-region end-region
7031 shell-file-name nil buf nil
7032 shell-command-switch markdown-command)))))
7033 output-buffer-name))
7035 (defun markdown-standalone (&optional output-buffer-name)
7036 "Special function to provide standalone HTML output.
7037 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
7038 (interactive)
7039 (setq output-buffer-name (markdown output-buffer-name))
7040 (with-current-buffer output-buffer-name
7041 (set-buffer output-buffer-name)
7042 (unless (markdown-output-standalone-p)
7043 (markdown-add-xhtml-header-and-footer output-buffer-name))
7044 (goto-char (point-min))
7045 (html-mode))
7046 output-buffer-name)
7048 (defun markdown-other-window (&optional output-buffer-name)
7049 "Run `markdown-command' on current buffer and display in other window.
7050 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7051 that name."
7052 (interactive)
7053 (markdown-display-buffer-other-window
7054 (markdown-standalone output-buffer-name)))
7056 (defun markdown-output-standalone-p ()
7057 "Determine whether `markdown-command' output is standalone XHTML.
7058 Standalone XHTML output is identified by an occurrence of
7059 `markdown-xhtml-standalone-regexp' in the first five lines of output."
7060 (save-excursion
7061 (goto-char (point-min))
7062 (save-match-data
7063 (re-search-forward
7064 markdown-xhtml-standalone-regexp
7065 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
7066 t))))
7068 (defun markdown-stylesheet-link-string (stylesheet-path)
7069 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
7070 stylesheet-path
7071 "\" />"))
7073 (defun markdown-add-xhtml-header-and-footer (title)
7074 "Wrap XHTML header and footer with given TITLE around current buffer."
7075 (goto-char (point-min))
7076 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
7077 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
7078 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
7079 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
7080 "<head>\n<title>")
7081 (insert title)
7082 (insert "</title>\n")
7083 (when (> (length markdown-content-type) 0)
7084 (insert
7085 (format
7086 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
7087 markdown-content-type
7088 (or (and markdown-coding-system
7089 (fboundp 'coding-system-get)
7090 (coding-system-get markdown-coding-system
7091 'mime-charset))
7092 (and (fboundp 'coding-system-get)
7093 (coding-system-get buffer-file-coding-system
7094 'mime-charset))
7095 "iso-8859-1"))))
7096 (if (> (length markdown-css-paths) 0)
7097 (insert (mapconcat #'markdown-stylesheet-link-string
7098 markdown-css-paths "\n")))
7099 (when (> (length markdown-xhtml-header-content) 0)
7100 (insert markdown-xhtml-header-content))
7101 (insert "\n</head>\n\n"
7102 "<body>\n\n")
7103 (goto-char (point-max))
7104 (insert "\n"
7105 "</body>\n"
7106 "</html>\n"))
7108 (defun markdown-preview (&optional output-buffer-name)
7109 "Run `markdown-command' on the current buffer and view output in browser.
7110 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7111 that name."
7112 (interactive)
7113 (browse-url-of-buffer
7114 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
7116 (defun markdown-export-file-name (&optional extension)
7117 "Attempt to generate a filename for Markdown output.
7118 The file extension will be EXTENSION if given, or .html by default.
7119 If the current buffer is visiting a file, we construct a new
7120 output filename based on that filename. Otherwise, return nil."
7121 (when (buffer-file-name)
7122 (unless extension
7123 (setq extension ".html"))
7124 (let ((candidate
7125 (concat
7126 (cond
7127 ((buffer-file-name)
7128 (file-name-sans-extension (buffer-file-name)))
7129 (t (buffer-name)))
7130 extension)))
7131 (cond
7132 ((equal candidate (buffer-file-name))
7133 (concat candidate extension))
7135 candidate)))))
7137 (defun markdown-export (&optional output-file)
7138 "Run Markdown on the current buffer, save to file, and return the filename.
7139 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
7140 generated by `markdown-export-file-name', which will be constructed using the
7141 current filename, but with the extension removed and replaced with .html."
7142 (interactive)
7143 (unless output-file
7144 (setq output-file (markdown-export-file-name ".html")))
7145 (when output-file
7146 (let* ((init-buf (current-buffer))
7147 (init-point (point))
7148 (init-buf-string (buffer-string))
7149 (output-buffer (find-file-noselect output-file))
7150 (output-buffer-name (buffer-name output-buffer)))
7151 (run-hooks 'markdown-before-export-hook)
7152 (markdown-standalone output-buffer-name)
7153 (with-current-buffer output-buffer
7154 (run-hooks 'markdown-after-export-hook)
7155 (save-buffer))
7156 ;; if modified, restore initial buffer
7157 (when (buffer-modified-p init-buf)
7158 (erase-buffer)
7159 (insert init-buf-string)
7160 (save-buffer)
7161 (goto-char init-point))
7162 output-file)))
7164 (defun markdown-export-and-preview ()
7165 "Export to XHTML using `markdown-export' and browse the resulting file."
7166 (interactive)
7167 (browse-url-of-file (markdown-export)))
7169 (defvar markdown-live-preview-buffer nil
7170 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
7171 (make-variable-buffer-local 'markdown-live-preview-buffer)
7173 (defvar markdown-live-preview-source-buffer nil
7174 "Source buffer from which current buffer was generated.
7175 This is the inverse of `markdown-live-preview-buffer'.")
7176 (make-variable-buffer-local 'markdown-live-preview-source-buffer)
7178 (defvar markdown-live-preview-currently-exporting nil)
7180 (defun markdown-live-preview-get-filename ()
7181 "Standardize the filename exported by `markdown-live-preview-export'."
7182 (markdown-export-file-name ".html"))
7184 (defun markdown-live-preview-window-eww (file)
7185 "Preview FILE with eww.
7186 To be used with `markdown-live-preview-window-function'."
7187 (if (require 'eww nil t)
7188 (progn
7189 (eww-open-file file)
7190 (get-buffer "*eww*"))
7191 (error "EWW is not present or not loaded on this version of Emacs")))
7193 (defun markdown-visual-lines-between-points (beg end)
7194 (save-excursion
7195 (goto-char beg)
7196 (cl-loop with count = 0
7197 while (progn (end-of-visual-line)
7198 (and (< (point) end) (line-move-visual 1 t)))
7199 do (cl-incf count)
7200 finally return count)))
7202 (defun markdown-live-preview-window-serialize (buf)
7203 "Get window point and scroll data for all windows displaying BUF."
7204 (when (buffer-live-p buf)
7205 (with-current-buffer buf
7206 (mapcar
7207 (lambda (win)
7208 (with-selected-window win
7209 (let* ((start (window-start))
7210 (pt (window-point))
7211 (pt-or-sym (cond ((= pt (point-min)) 'min)
7212 ((= pt (point-max)) 'max)
7213 (t pt)))
7214 (diff (markdown-visual-lines-between-points
7215 start pt)))
7216 (list win pt-or-sym diff))))
7217 (get-buffer-window-list buf)))))
7219 (defun markdown-get-point-back-lines (pt num-lines)
7220 (save-excursion
7221 (goto-char pt)
7222 (line-move-visual (- num-lines) t)
7223 ;; in testing, can occasionally overshoot the number of lines to traverse
7224 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
7225 (when (> actual-num-lines num-lines)
7226 (line-move-visual (- actual-num-lines num-lines) t)))
7227 (point)))
7229 (defun markdown-live-preview-window-deserialize (window-posns)
7230 "Apply window point and scroll data from WINDOW-POSNS.
7231 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
7232 (cl-destructuring-bind (win pt-or-sym diff) window-posns
7233 (when (window-live-p win)
7234 (with-current-buffer markdown-live-preview-buffer
7235 (set-window-buffer win (current-buffer))
7236 (cl-destructuring-bind (actual-pt actual-diff)
7237 (cl-case pt-or-sym
7238 (min (list (point-min) 0))
7239 (max (list (point-max) diff))
7240 (t (list pt-or-sym diff)))
7241 (set-window-start
7242 win (markdown-get-point-back-lines actual-pt actual-diff))
7243 (set-window-point win actual-pt))))))
7245 (defun markdown-live-preview-export ()
7246 "Export to XHTML using `markdown-export'.
7247 Browse the resulting file within Emacs using
7248 `markdown-live-preview-window-function' Return the buffer
7249 displaying the rendered output."
7250 (interactive)
7251 (let ((filename (markdown-live-preview-get-filename)))
7252 (when filename
7253 (let* ((markdown-live-preview-currently-exporting t)
7254 (cur-buf (current-buffer))
7255 (export-file (markdown-export filename))
7256 ;; get positions in all windows currently displaying output buffer
7257 (window-data
7258 (markdown-live-preview-window-serialize
7259 markdown-live-preview-buffer)))
7260 (save-window-excursion
7261 (let ((output-buffer
7262 (funcall markdown-live-preview-window-function export-file)))
7263 (with-current-buffer output-buffer
7264 (setq markdown-live-preview-source-buffer cur-buf)
7265 (add-hook 'kill-buffer-hook
7266 #'markdown-live-preview-remove-on-kill t t))
7267 (with-current-buffer cur-buf
7268 (setq markdown-live-preview-buffer output-buffer))))
7269 (with-current-buffer cur-buf
7270 ;; reset all windows displaying output buffer to where they were,
7271 ;; now with the new output
7272 (mapc #'markdown-live-preview-window-deserialize window-data)
7273 ;; delete html editing buffer
7274 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
7275 (when (and export-file (file-exists-p export-file)
7276 (eq markdown-live-preview-delete-export
7277 'delete-on-export))
7278 (delete-file export-file))
7279 markdown-live-preview-buffer)))))
7281 (defun markdown-live-preview-remove ()
7282 (when (buffer-live-p markdown-live-preview-buffer)
7283 (kill-buffer markdown-live-preview-buffer))
7284 (setq markdown-live-preview-buffer nil)
7285 ;; if set to 'delete-on-export, the output has already been deleted
7286 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
7287 (let ((outfile-name (markdown-live-preview-get-filename)))
7288 (when (and outfile-name (file-exists-p outfile-name))
7289 (delete-file outfile-name)))))
7291 (defun markdown-get-other-window ()
7292 "Find another window to display preview or output content."
7293 (cond
7294 ((memq markdown-split-window-direction '(vertical below))
7295 (or (window-in-direction 'below) (split-window-vertically)))
7296 ((memq markdown-split-window-direction '(horizontal right))
7297 (or (window-in-direction 'right) (split-window-horizontally)))
7298 (t (split-window-sensibly (get-buffer-window)))))
7300 (defun markdown-display-buffer-other-window (buf)
7301 "Display preview or output buffer BUF in another window."
7302 (let ((cur-buf (current-buffer))
7303 (window (markdown-get-other-window)))
7304 (set-window-buffer window buf)
7305 (set-buffer cur-buf)))
7307 (defun markdown-live-preview-if-markdown ()
7308 (when (and (derived-mode-p 'markdown-mode)
7309 markdown-live-preview-mode)
7310 (unless markdown-live-preview-currently-exporting
7311 (if (buffer-live-p markdown-live-preview-buffer)
7312 (markdown-live-preview-export)
7313 (markdown-display-buffer-other-window
7314 (markdown-live-preview-export))))))
7316 (defun markdown-live-preview-remove-on-kill ()
7317 (cond ((and (derived-mode-p 'markdown-mode)
7318 markdown-live-preview-mode)
7319 (markdown-live-preview-remove))
7320 (markdown-live-preview-source-buffer
7321 (with-current-buffer markdown-live-preview-source-buffer
7322 (setq markdown-live-preview-buffer nil))
7323 (setq markdown-live-preview-source-buffer nil))))
7325 (defun markdown-live-preview-switch-to-output ()
7326 "Switch to output buffer."
7327 (interactive)
7328 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
7329 output buffer in another window."
7330 (if markdown-live-preview-mode
7331 (markdown-display-buffer-other-window (markdown-live-preview-export)))
7332 (markdown-live-preview-mode))
7334 (defun markdown-live-preview-re-export ()
7335 "Re export source buffer."
7336 (interactive)
7337 "If the current buffer is a buffer displaying the exported version of a
7338 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
7339 update this buffer's contents."
7340 (when markdown-live-preview-source-buffer
7341 (with-current-buffer markdown-live-preview-source-buffer
7342 (markdown-live-preview-export))))
7344 (defun markdown-open ()
7345 "Open file for the current buffer with `markdown-open-command'."
7346 (interactive)
7347 (if (not markdown-open-command)
7348 (error "Variable `markdown-open-command' must be set")
7349 (if (not buffer-file-name)
7350 (error "Must be visiting a file")
7351 (call-process markdown-open-command
7352 nil nil nil buffer-file-name))))
7354 (defun markdown-kill-ring-save ()
7355 "Run Markdown on file and store output in the kill ring."
7356 (interactive)
7357 (save-window-excursion
7358 (markdown)
7359 (with-current-buffer markdown-output-buffer-name
7360 (kill-ring-save (point-min) (point-max)))))
7363 ;;; Links =====================================================================
7365 (defun markdown-link-p ()
7366 "Return non-nil when `point' is at a non-wiki link.
7367 See `markdown-wiki-link-p' for more information."
7368 (let ((case-fold-search nil))
7369 (and (not (markdown-wiki-link-p))
7370 (not (markdown-code-block-at-point-p))
7371 (or (thing-at-point-looking-at markdown-regex-link-inline)
7372 (thing-at-point-looking-at markdown-regex-link-reference)
7373 (thing-at-point-looking-at markdown-regex-uri)
7374 (thing-at-point-looking-at markdown-regex-angle-uri)))))
7376 (make-obsolete 'markdown-link-link 'markdown-link-url "v2.3")
7378 (defun markdown-link-at-pos (pos)
7379 "Return properties of link at position POS.
7380 Value is a list of elements describing the link:
7381 0. beginning position
7382 1. end position
7383 2. link text
7384 3. URL
7385 4. reference label
7386 5. title text"
7387 (save-excursion
7388 (goto-char pos)
7389 (let (begin end text url reference title)
7390 (cond
7391 ;; Inline or reference image or link at point.
7392 ((or (thing-at-point-looking-at markdown-regex-link-inline)
7393 (thing-at-point-looking-at markdown-regex-link-reference))
7394 (when (null (match-beginning 1))
7395 ;; No exclamation point, so not an image.
7396 (setq begin (match-beginning 0)
7397 end (match-end 0)
7398 text (match-string-no-properties 3))
7399 (if (char-equal (char-after (match-beginning 5)) ?\[)
7400 ;; Reference link
7401 (setq reference (match-string-no-properties 6))
7402 ;; Inline link
7403 (setq url (match-string-no-properties 6))
7404 (when (match-end 7)
7405 (setq title (substring (match-string-no-properties 7) 1 -1))))))
7406 ;; Angle bracket URI at point.
7407 ((thing-at-point-looking-at markdown-regex-angle-uri)
7408 (setq begin (match-beginning 0)
7409 end (match-end 0)
7410 url (match-string-no-properties 2)))
7411 ;; Plain URI at point.
7412 ((thing-at-point-looking-at markdown-regex-uri)
7413 (setq begin (match-beginning 0)
7414 end (match-end 0)
7415 url (match-string-no-properties 1))))
7416 (list begin end text url reference title))))
7418 (defun markdown-link-url ()
7419 "Return the URL part of the regular (non-wiki) link at point.
7420 Works with both inline and reference style links. If point is
7421 not at a link or the link reference is not defined returns nil."
7422 (let* ((values (markdown-link-at-pos (point)))
7423 (text (nth 2 values))
7424 (url (nth 3 values))
7425 (ref (nth 4 values)))
7426 (or url (and ref (car (markdown-reference-definition
7427 (downcase (if (string= ref "") text ref))))))))
7429 (defun markdown-follow-link-at-point ()
7430 "Open the current non-wiki link.
7431 If the link is a complete URL, open in browser with `browse-url'.
7432 Otherwise, open with `find-file' after stripping anchor and/or query string."
7433 (interactive)
7434 (if (markdown-link-p)
7435 (let* ((url (markdown-link-url))
7436 (struct (url-generic-parse-url url))
7437 (full (url-fullness struct))
7438 (file url))
7439 ;; Parse URL, determine fullness, strip query string
7440 (if (fboundp 'url-path-and-query)
7441 (setq file (car (url-path-and-query struct)))
7442 (when (and (setq file (url-filename struct))
7443 (string-match "\\?" file))
7444 (setq file (substring file 0 (match-beginning 0)))))
7445 ;; Open full URLs in browser, files in Emacs
7446 (if full
7447 (browse-url url)
7448 (when (and file (> (length file) 0)) (find-file file))))
7449 (error "Point is not at a Markdown link or URL")))
7451 (defun markdown-fontify-inline-links (last)
7452 "Add text properties to next inline link from point to LAST."
7453 (when (markdown-match-generic-links last nil)
7454 (let* ((link-start (match-beginning 3))
7455 (link-end (match-end 3))
7456 (url-start (match-beginning 6))
7457 (url-end (match-end 6))
7458 (url (match-string-no-properties 6))
7459 (title-start (match-beginning 7))
7460 (title-end (match-end 7))
7461 (title (match-string-no-properties 7))
7462 ;; Markup part
7463 (mp (list 'face 'markdown-markup-face
7464 'invisible 'markdown-markup
7465 'font-lock-multiline t))
7466 ;; Link part
7467 (lp (list 'keymap markdown-mode-mouse-map
7468 'face markdown-link-face
7469 'mouse-face 'markdown-highlight-face
7470 'font-lock-multiline t
7471 'help-echo (if title (concat title "\n" url) url)))
7472 ;; URL part
7473 (up (list 'keymap markdown-mode-mouse-map
7474 'face 'markdown-url-face
7475 'invisible 'markdown-markup
7476 'mouse-face 'markdown-highlight-face
7477 'font-lock-multiline t))
7478 ;; Title part
7479 (tp (list 'face 'markdown-link-title-face
7480 'invisible 'markdown-markup
7481 'font-lock-multiline t)))
7482 (dolist (g '(1 2 4 5 8))
7483 (when (match-end g)
7484 (add-text-properties (match-beginning g) (match-end g) mp)))
7485 (when link-start (add-text-properties link-start link-end lp))
7486 (when url-start (add-text-properties url-start url-end up))
7487 (when title-start (add-text-properties url-end title-end tp))
7488 (when (and markdown-hide-urls url-start)
7489 (compose-region url-start (or title-end url-end)
7490 markdown-url-compose-char))
7491 t)))
7493 (defun markdown-fontify-reference-links (last)
7494 "Add text properties to next reference link from point to LAST."
7495 (when (markdown-match-generic-links last t)
7496 (let* ((link-start (match-beginning 3))
7497 (link-end (match-end 3))
7498 (ref-start (match-beginning 6))
7499 (ref-end (match-end 6))
7500 ;; Markup part
7501 (mp (list 'face 'markdown-markup-face
7502 'invisible 'markdown-markup
7503 'font-lock-multiline t))
7504 ;; Link part
7505 (lp (list 'keymap markdown-mode-mouse-map
7506 'face markdown-link-face
7507 'mouse-face 'markdown-highlight-face
7508 'font-lock-multiline t
7509 'help-echo (lambda (_ __ pos)
7510 (save-match-data
7511 (save-excursion
7512 (goto-char pos)
7513 (or (markdown-link-url)
7514 "Undefined reference"))))))
7515 ;; Reference part
7516 (rp (list 'face 'markdown-reference-face
7517 'invisible 'markdown-markup
7518 'font-lock-multiline t)))
7519 (dolist (g '(1 2 4 5 8))
7520 (when (match-end g)
7521 (add-text-properties (match-beginning g) (match-end g) mp)))
7522 (when link-start (add-text-properties link-start link-end lp))
7523 (when ref-start (add-text-properties ref-start ref-end rp)
7524 (when (and markdown-hide-urls (> (- ref-end ref-start) 3))
7525 (compose-region ref-start ref-end markdown-url-compose-char)))
7526 t)))
7528 (defun markdown-fontify-angle-uris (last)
7529 "Add text properties to angle URIs from point to LAST."
7530 (when (markdown-match-angle-uris last)
7531 (let* ((url-start (match-beginning 2))
7532 (url-end (match-end 2))
7533 ;; Markup part
7534 (mp (list 'face 'markdown-markup-face
7535 'invisible 'markdown-markup
7536 'font-lock-multiline t))
7537 ;; URI part
7538 (up (list 'keymap markdown-mode-mouse-map
7539 'face 'markdown-plain-url-face
7540 'mouse-face 'markdown-highlight-face
7541 'font-lock-multiline t)))
7542 (dolist (g '(1 3))
7543 (add-text-properties (match-beginning g) (match-end g) mp))
7544 (add-text-properties url-start url-end up)
7545 t)))
7547 (defun markdown-fontify-plain-uris (last)
7548 "Add text properties to plain URLs from point to LAST."
7549 (when (markdown-match-plain-uris last)
7550 (let* ((start (match-beginning 0))
7551 (end (match-end 0))
7552 (props (list 'keymap markdown-mode-mouse-map
7553 'face 'markdown-plain-url-face
7554 'mouse-face 'markdown-highlight-face
7555 'font-lock-multiline t)))
7556 (add-text-properties start end props)
7557 t)))
7559 (defun markdown-toggle-url-hiding (&optional arg)
7560 "Toggle the display or hiding of URLs.
7561 With a prefix argument ARG, enable URL hiding if ARG is positive,
7562 and disable it otherwise."
7563 (interactive (list (or current-prefix-arg 'toggle)))
7564 (setq markdown-hide-urls
7565 (if (eq arg 'toggle)
7566 (not markdown-hide-urls)
7567 (> (prefix-numeric-value arg) 0)))
7568 (if markdown-hide-urls
7569 (message "markdown-mode URL hiding enabled")
7570 (message "markdown-mode URL hiding disabled"))
7571 (markdown-reload-extensions))
7574 ;;; WikiLink Following/Markup =================================================
7576 (defun markdown-wiki-link-p ()
7577 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
7578 A true wiki link name matches `markdown-regex-wiki-link' but does
7579 not match the current file name after conversion. This modifies
7580 the data returned by `match-data'. Note that the potential wiki
7581 link name must be available via `match-string'."
7582 (when markdown-enable-wiki-links
7583 (let ((case-fold-search nil))
7584 (and (thing-at-point-looking-at markdown-regex-wiki-link)
7585 (not (markdown-code-block-at-point-p))
7586 (or (not buffer-file-name)
7587 (not (string-equal (buffer-file-name)
7588 (markdown-convert-wiki-link-to-filename
7589 (markdown-wiki-link-link)))))))))
7591 (defun markdown-wiki-link-link ()
7592 "Return the link part of the wiki link using current match data.
7593 The location of the link component depends on the value of
7594 `markdown-wiki-link-alias-first'."
7595 (if markdown-wiki-link-alias-first
7596 (or (match-string-no-properties 5) (match-string-no-properties 3))
7597 (match-string-no-properties 3)))
7599 (defun markdown-wiki-link-alias ()
7600 "Return the alias or text part of the wiki link using current match data.
7601 The location of the alias component depends on the value of
7602 `markdown-wiki-link-alias-first'."
7603 (if markdown-wiki-link-alias-first
7604 (match-string-no-properties 3)
7605 (or (match-string-no-properties 5) (match-string-no-properties 3))))
7607 (defun markdown-convert-wiki-link-to-filename (name)
7608 "Generate a filename from the wiki link NAME.
7609 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
7610 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
7611 and [[test test]] both map to Test-test.ext. Look in the current
7612 directory first, then in subdirectories if
7613 `markdown-wiki-link-search-subdirectories' is non-nil, and then
7614 in parent directories if
7615 `markdown-wiki-link-search-parent-directories' is non-nil."
7616 (let* ((basename (markdown-replace-regexp-in-string
7617 "[[:space:]\n]" markdown-link-space-sub-char name))
7618 (basename (if (eq major-mode 'gfm-mode)
7619 (concat (upcase (substring basename 0 1))
7620 (downcase (substring basename 1 nil)))
7621 basename))
7622 directory extension default candidates dir)
7623 (when buffer-file-name
7624 (setq directory (file-name-directory buffer-file-name)
7625 extension (file-name-extension buffer-file-name)))
7626 (setq default (concat basename
7627 (when extension (concat "." extension))))
7628 (cond
7629 ;; Look in current directory first.
7630 ((or (null buffer-file-name)
7631 (file-exists-p default))
7632 default)
7633 ;; Possibly search in subdirectories, next.
7634 ((and markdown-wiki-link-search-subdirectories
7635 (setq candidates
7636 (markdown-directory-files-recursively
7637 directory (concat "^" default "$"))))
7638 (car candidates))
7639 ;; Possibly search in parent directories as a last resort.
7640 ((and markdown-wiki-link-search-parent-directories
7641 (setq dir (locate-dominating-file directory default)))
7642 (concat dir default))
7643 ;; If nothing is found, return default in current directory.
7644 (t default))))
7646 (defun markdown-follow-wiki-link (name &optional other)
7647 "Follow the wiki link NAME.
7648 Convert the name to a file name and call `find-file'. Ensure that
7649 the new buffer remains in `markdown-mode'. Open the link in another
7650 window when OTHER is non-nil."
7651 (let ((filename (markdown-convert-wiki-link-to-filename name))
7652 (wp (when buffer-file-name
7653 (file-name-directory buffer-file-name))))
7654 (if (not wp)
7655 (error "Must be visiting a file")
7656 (when other (other-window 1))
7657 (let ((default-directory wp))
7658 (find-file filename)))
7659 (when (not (eq major-mode 'markdown-mode))
7660 (markdown-mode))))
7662 (defun markdown-follow-wiki-link-at-point (&optional arg)
7663 "Find Wiki Link at point.
7664 With prefix argument ARG, open the file in other window.
7665 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
7666 (interactive "P")
7667 (if (markdown-wiki-link-p)
7668 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
7669 (error "Point is not at a Wiki Link")))
7671 (defun markdown-highlight-wiki-link (from to face)
7672 "Highlight the wiki link in the region between FROM and TO using FACE."
7673 (put-text-property from to 'font-lock-face face))
7675 (defun markdown-unfontify-region-wiki-links (from to)
7676 "Remove wiki link faces from the region specified by FROM and TO."
7677 (interactive "*r")
7678 (let ((modified (buffer-modified-p)))
7679 (remove-text-properties from to '(font-lock-face markdown-link-face))
7680 (remove-text-properties from to '(font-lock-face markdown-missing-link-face))
7681 ;; remove-text-properties marks the buffer modified in emacs 24.3,
7682 ;; undo that if it wasn't originally marked modified
7683 (set-buffer-modified-p modified)))
7685 (defun markdown-fontify-region-wiki-links (from to)
7686 "Search region given by FROM and TO for wiki links and fontify them.
7687 If a wiki link is found check to see if the backing file exists
7688 and highlight accordingly."
7689 (goto-char from)
7690 (save-match-data
7691 (while (re-search-forward markdown-regex-wiki-link to t)
7692 (when (not (markdown-code-block-at-point-p))
7693 (let ((highlight-beginning (match-beginning 1))
7694 (highlight-end (match-end 1))
7695 (file-name
7696 (markdown-convert-wiki-link-to-filename
7697 (markdown-wiki-link-link))))
7698 (if (condition-case nil (file-exists-p file-name) (error nil))
7699 (markdown-highlight-wiki-link
7700 highlight-beginning highlight-end markdown-link-face)
7701 (markdown-highlight-wiki-link
7702 highlight-beginning highlight-end markdown-missing-link-face)))))))
7704 (defun markdown-extend-changed-region (from to)
7705 "Extend region given by FROM and TO so that we can fontify all links.
7706 The region is extended to the first newline before and the first
7707 newline after."
7708 ;; start looking for the first new line before 'from
7709 (goto-char from)
7710 (re-search-backward "\n" nil t)
7711 (let ((new-from (point-min))
7712 (new-to (point-max)))
7713 (if (not (= (point) from))
7714 (setq new-from (point)))
7715 ;; do the same thing for the first new line after 'to
7716 (goto-char to)
7717 (re-search-forward "\n" nil t)
7718 (if (not (= (point) to))
7719 (setq new-to (point)))
7720 (cl-values new-from new-to)))
7722 (defun markdown-check-change-for-wiki-link (from to)
7723 "Check region between FROM and TO for wiki links and re-fontify as needed."
7724 (interactive "*r")
7725 (let* ((modified (buffer-modified-p))
7726 (buffer-undo-list t)
7727 (inhibit-read-only t)
7728 (inhibit-point-motion-hooks t)
7729 deactivate-mark
7730 buffer-file-truename)
7731 (unwind-protect
7732 (save-excursion
7733 (save-match-data
7734 (save-restriction
7735 ;; Extend the region to fontify so that it starts
7736 ;; and ends at safe places.
7737 (cl-multiple-value-bind (new-from new-to)
7738 (markdown-extend-changed-region from to)
7739 (goto-char new-from)
7740 ;; Only refontify when the range contains text with a
7741 ;; wiki link face or if the wiki link regexp matches.
7742 (when (or (markdown-range-property-any
7743 new-from new-to 'font-lock-face
7744 (list markdown-link-face
7745 markdown-missing-link-face))
7746 (re-search-forward
7747 markdown-regex-wiki-link new-to t))
7748 ;; Unfontify existing fontification (start from scratch)
7749 (markdown-unfontify-region-wiki-links new-from new-to)
7750 ;; Now do the fontification.
7751 (markdown-fontify-region-wiki-links new-from new-to))))))
7752 (and (not modified)
7753 (buffer-modified-p)
7754 (set-buffer-modified-p nil)))))
7756 (defun markdown-check-change-for-wiki-link-after-change (from to _)
7757 "Check region between FROM and TO for wiki links and re-fontify as needed.
7758 Designed to be used with the `after-change-functions' hook."
7759 (markdown-check-change-for-wiki-link from to))
7761 (defun markdown-fontify-buffer-wiki-links ()
7762 "Refontify all wiki links in the buffer."
7763 (interactive)
7764 (markdown-check-change-for-wiki-link (point-min) (point-max)))
7767 ;;; Following and Jumping =====================================================
7769 (defun markdown-follow-thing-at-point (arg)
7770 "Follow thing at point if possible, such as a reference link or wiki link.
7771 Opens inline and reference links in a browser. Opens wiki links
7772 to other files in the current window, or the another window if
7773 ARG is non-nil.
7774 See `markdown-follow-link-at-point' and
7775 `markdown-follow-wiki-link-at-point'."
7776 (interactive "P")
7777 (cond ((markdown-link-p)
7778 (markdown-follow-link-at-point))
7779 ((markdown-wiki-link-p)
7780 (markdown-follow-wiki-link-at-point arg))
7782 (error "Nothing to follow at point"))))
7784 (defun markdown-jump ()
7785 "Jump to another location based on context at point.
7786 Jumps between reference links and definitions; between footnote
7787 markers and footnote text."
7788 (interactive)
7789 (cond ((markdown-footnote-text-positions)
7790 (markdown-footnote-return))
7791 ((markdown-footnote-marker-positions)
7792 (markdown-footnote-goto-text))
7793 ((thing-at-point-looking-at markdown-regex-link-reference)
7794 (markdown-reference-goto-definition))
7795 ((thing-at-point-looking-at markdown-regex-reference-definition)
7796 (markdown-reference-goto-link (match-string-no-properties 2)))
7798 (error "Nothing to jump to from context at point"))))
7801 ;;; Miscellaneous =============================================================
7803 (defun markdown-compress-whitespace-string (str)
7804 "Compress whitespace in STR and return result.
7805 Leading and trailing whitespace is removed. Sequences of multiple
7806 spaces, tabs, and newlines are replaced with single spaces."
7807 (markdown-replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
7808 (markdown-replace-regexp-in-string "[ \t\n]+" " " str)))
7810 (defun markdown-line-number-at-pos (&optional pos)
7811 "Return (narrowed) buffer line number at position POS.
7812 If POS is nil, use current buffer location.
7813 This is an exact copy of `line-number-at-pos' for use in emacs21."
7814 (let ((opoint (or pos (point))) start)
7815 (save-excursion
7816 (goto-char (point-min))
7817 (setq start (point))
7818 (goto-char opoint)
7819 (forward-line 0)
7820 (1+ (count-lines start (point))))))
7822 (defun markdown-inside-link-p ()
7823 "Return t if point is within a link."
7824 (save-match-data
7825 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
7827 (defun markdown-line-is-reference-definition-p ()
7828 "Return whether the current line is a (non-footnote) reference defition."
7829 (save-excursion
7830 (move-beginning-of-line 1)
7831 (and (looking-at-p markdown-regex-reference-definition)
7832 (not (looking-at-p "[ \t]*\\[^")))))
7834 (defun markdown-adaptive-fill-function ()
7835 "Return prefix for filling paragraph or nil if not determined."
7836 (cond
7837 ;; List item inside blockquote
7838 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
7839 (markdown-replace-regexp-in-string
7840 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
7841 ;; Blockquote
7842 ((looking-at markdown-regex-blockquote)
7843 (buffer-substring-no-properties (match-beginning 0) (match-end 2)))
7844 ;; List items
7845 ((looking-at markdown-regex-list)
7846 (match-string-no-properties 0))
7847 ;; Footnote definition
7848 ((looking-at-p markdown-regex-footnote-definition)
7849 " ") ; four spaces
7850 ;; No match
7851 (t nil)))
7853 (defun markdown-fill-paragraph (&optional justify)
7854 "Fill paragraph at or after point.
7855 This function is like \\[fill-paragraph], but it skips Markdown
7856 code blocks. If the point is in a code block, or just before one,
7857 do not fill. Otherwise, call `fill-paragraph' as usual. If
7858 JUSTIFY is non-nil, justify text as well. Since this function
7859 handles filling itself, it always returns t so that
7860 `fill-paragraph' doesn't run."
7861 (interactive "P")
7862 (unless (or (markdown-code-block-at-point-p)
7863 (save-excursion
7864 (back-to-indentation)
7865 (skip-syntax-forward "-")
7866 (markdown-code-block-at-point-p)))
7867 (fill-paragraph justify))
7870 (make-obsolete 'markdown-fill-forward-paragraph-function
7871 'markdown-fill-forward-paragraph "v2.3")
7873 (defun markdown-fill-forward-paragraph (&optional arg)
7874 "Function used by `fill-paragraph' to move over ARG paragraphs.
7875 This is a `fill-forward-paragraph-function' for `markdown-mode'.
7876 It is called with a single argument specifying the number of
7877 paragraphs to move. Just like `forward-paragraph', it should
7878 return the number of paragraphs left to move."
7879 (or arg (setq arg 1))
7880 (if (> arg 0)
7881 ;; With positive ARG, move across ARG non-code-block paragraphs,
7882 ;; one at a time. When passing a code block, don't decrement ARG.
7883 (while (and (not (eobp))
7884 (> arg 0)
7885 (= (forward-paragraph 1) 0)
7886 (or (markdown-code-block-at-pos (point-at-bol 0))
7887 (setq arg (1- arg)))))
7888 ;; Move backward by one paragraph with negative ARG (always -1).
7889 (let ((start (point)))
7890 (setq arg (forward-paragraph arg))
7891 (while (and (not (eobp))
7892 (progn (move-to-left-margin) (not (eobp)))
7893 (looking-at-p paragraph-separate))
7894 (forward-line 1))
7895 (cond
7896 ;; Move point past whitespace following list marker.
7897 ((looking-at markdown-regex-list)
7898 (goto-char (match-end 0)))
7899 ;; Move point past whitespace following pipe at beginning of line
7900 ;; to handle Pandoc line blocks.
7901 ((looking-at "^|\\s-*")
7902 (goto-char (match-end 0)))
7903 ;; Return point if the paragraph passed was a code block.
7904 ((markdown-code-block-at-pos (point-at-bol 2))
7905 (goto-char start)))))
7906 arg)
7909 ;;; Extension Framework =======================================================
7911 (defun markdown-reload-extensions ()
7912 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
7913 (interactive)
7914 (when (eq major-mode 'markdown-mode)
7915 ;; Update font lock keywords with extensions
7916 (setq markdown-mode-font-lock-keywords
7917 (append
7918 (markdown-mode-font-lock-keywords-math)
7919 markdown-mode-font-lock-keywords-basic
7920 (markdown-mode-font-lock-keywords-wiki-links)))
7921 ;; Update font lock defaults
7922 (setq font-lock-defaults
7923 '(markdown-mode-font-lock-keywords
7924 nil nil nil nil
7925 (font-lock-syntactic-face-function . markdown-syntactic-face)))
7926 ;; Refontify buffer
7927 (when (and font-lock-mode (fboundp 'font-lock-refresh-defaults))
7928 (font-lock-refresh-defaults))
7930 ;; Add or remove hooks related to extensions
7931 (markdown-setup-wiki-link-hooks)))
7933 (defun markdown-handle-local-variables ()
7934 "Run in `hack-local-variables-hook' to update font lock rules.
7935 Checks to see if there is actually a ‘markdown-mode’ file local variable
7936 before regenerating font-lock rules for extensions."
7937 (when (and (boundp 'file-local-variables-alist)
7938 (assoc 'markdown-enable-wiki-links file-local-variables-alist)
7939 (assoc 'markdown-enable-math file-local-variables-alist))
7940 (markdown-reload-extensions)))
7943 ;;; Wiki Links ================================================================
7945 (defun markdown-toggle-wiki-links (&optional arg)
7946 "Toggle support for wiki links.
7947 With a prefix argument ARG, enable wiki link support if ARG is positive,
7948 and disable it otherwise."
7949 (interactive (list (or current-prefix-arg 'toggle)))
7950 (setq markdown-enable-wiki-links
7951 (if (eq arg 'toggle)
7952 (not markdown-enable-wiki-links)
7953 (> (prefix-numeric-value arg) 0)))
7954 (if markdown-enable-wiki-links
7955 (message "markdown-mode wiki link support enabled")
7956 (message "markdown-mode wiki link support disabled"))
7957 (markdown-reload-extensions))
7959 (defun markdown-setup-wiki-link-hooks ()
7960 "Add or remove hooks for fontifying wiki links.
7961 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
7962 ;; Anytime text changes make sure it gets fontified correctly
7963 (if (and markdown-enable-wiki-links
7964 markdown-wiki-link-fontify-missing)
7965 (add-hook 'after-change-functions
7966 'markdown-check-change-for-wiki-link-after-change t t)
7967 (remove-hook 'after-change-functions
7968 'markdown-check-change-for-wiki-link-after-change t))
7969 ;; If we left the buffer there is a really good chance we were
7970 ;; creating one of the wiki link documents. Make sure we get
7971 ;; refontified when we come back.
7972 (if (and markdown-enable-wiki-links
7973 markdown-wiki-link-fontify-missing)
7974 (progn
7975 (add-hook 'window-configuration-change-hook
7976 'markdown-fontify-buffer-wiki-links t t)
7977 (markdown-fontify-buffer-wiki-links))
7978 (remove-hook 'window-configuration-change-hook
7979 'markdown-fontify-buffer-wiki-links t)
7980 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
7982 (defun markdown-mode-font-lock-keywords-wiki-links ()
7983 "Return wiki-link lock keywords if support is enabled.
7984 If `markdown-wiki-link-fontify-missing' is also enabled, we use
7985 hooks in `markdown-setup-wiki-link-hooks' for fontification instead."
7986 (when (and markdown-enable-wiki-links
7987 (not markdown-wiki-link-fontify-missing))
7988 (list
7989 (cons markdown-regex-wiki-link '((1 markdown-link-face prepend))))))
7992 ;;; Math Support ==============================================================
7994 (make-obsolete 'markdown-enable-math 'markdown-toggle-math "v2.1")
7996 (defun markdown-toggle-math (&optional arg)
7997 "Toggle support for inline and display LaTeX math expressions.
7998 With a prefix argument ARG, enable math mode if ARG is positive,
7999 and disable it otherwise. If called from Lisp, enable the mode
8000 if ARG is omitted or nil."
8001 (interactive (list (or current-prefix-arg 'toggle)))
8002 (setq markdown-enable-math
8003 (if (eq arg 'toggle)
8004 (not markdown-enable-math)
8005 (> (prefix-numeric-value arg) 0)))
8006 (if markdown-enable-math
8007 (message "markdown-mode math support enabled")
8008 (message "markdown-mode math support disabled"))
8009 (markdown-reload-extensions))
8011 (defun markdown-mode-font-lock-keywords-math ()
8012 "Return math font lock keywords if support is enabled."
8013 (when markdown-enable-math
8014 (list
8015 ;; Display mode equations with brackets: \[ \]
8016 (cons markdown-regex-math-display '((1 markdown-markup-face prepend)
8017 (2 markdown-math-face append)
8018 (3 markdown-markup-face prepend)))
8019 ;; Equation reference (eq:foo)
8020 (cons "\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" '((1 markdown-markup-face)
8021 (2 markdown-reference-face)
8022 (3 markdown-markup-face)))
8023 ;; Equation reference \eqref{foo}
8024 (cons "\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" '((1 markdown-markup-face)
8025 (2 markdown-reference-face)
8026 (3 markdown-markup-face))))))
8029 ;;; GFM Checkboxes ============================================================
8031 (define-button-type 'markdown-gfm-checkbox-button
8032 'follow-link t
8033 'face 'markdown-gfm-checkbox-face
8034 'mouse-face 'markdown-highlight-face
8035 'action #'markdown-toggle-gfm-checkbox-button)
8037 (defun markdown-toggle-gfm-checkbox ()
8038 "Toggle GFM checkbox at point.
8039 Returns the resulting status as a string, either \"[x]\" or \"[ ]\".
8040 Returns nil if there is no task list item at the point."
8041 (interactive)
8042 (save-match-data
8043 (save-excursion
8044 (let ((bounds (markdown-cur-list-item-bounds)))
8045 (when bounds
8046 ;; Move to beginning of task list item
8047 (goto-char (cl-first bounds))
8048 ;; Advance to column of first non-whitespace after marker
8049 (forward-char (cl-fourth bounds))
8050 (cond ((looking-at "\\[ \\]")
8051 (replace-match "[x]" nil t)
8052 (match-string-no-properties 0))
8053 ((looking-at "\\[[xX]\\]")
8054 (replace-match "[ ]" nil t)
8055 (match-string-no-properties 0))))))))
8057 (defun markdown-toggle-gfm-checkbox-button (button)
8058 "Toggle GFM checkbox BUTTON on click."
8059 (save-match-data
8060 (save-excursion
8061 (goto-char (button-start button))
8062 (markdown-toggle-gfm-checkbox))))
8064 (defun markdown-make-gfm-checkboxes-buttons (start end)
8065 "Make GFM checkboxes buttons in region between START and END."
8066 (save-excursion
8067 (goto-char start)
8068 (let ((case-fold-search t))
8069 (save-excursion
8070 (while (re-search-forward markdown-regex-gfm-checkbox end t)
8071 (make-button (match-beginning 1) (match-end 1)
8072 :type 'markdown-gfm-checkbox-button))))))
8074 ;; Called when any modification is made to buffer text.
8075 (defun markdown-gfm-checkbox-after-change-function (beg end _)
8076 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
8077 BEG and END are the limits of scanned region."
8078 (save-excursion
8079 (save-match-data
8080 ;; Rescan between start of line from `beg' and start of line after `end'.
8081 (markdown-make-gfm-checkboxes-buttons
8082 (progn (goto-char beg) (beginning-of-line) (point))
8083 (progn (goto-char end) (forward-line 1) (point))))))
8086 ;;; Display inline image =================================================
8088 (defvar markdown-inline-image-overlays nil)
8089 (make-variable-buffer-local 'markdown-inline-image-overlays)
8091 (defun markdown-remove-inline-images ()
8092 "Remove inline image overlays from image links in the buffer.
8093 This can be toggled with `markdown-toggle-inline-images'
8094 or \\[markdown-toggle-inline-images]."
8095 (interactive)
8096 (mapc #'delete-overlay markdown-inline-image-overlays)
8097 (setq markdown-inline-image-overlays nil))
8099 (defun markdown-display-inline-images ()
8100 "Add inline image overlays to image links in the buffer.
8101 This can be toggled with `markdown-toggle-inline-images'
8102 or \\[markdown-toggle-inline-images]."
8103 (interactive)
8104 (unless (display-graphic-p)
8105 (error "Cannot show images"))
8106 (save-excursion
8107 (save-restriction
8108 (widen)
8109 (goto-char (point-min))
8110 (while (re-search-forward markdown-regex-link-inline nil t)
8111 (let ((start (match-beginning 0))
8112 (end (match-end 0))
8113 (file (match-string-no-properties 6)))
8114 (when (file-exists-p file)
8115 (let* ((abspath (if (file-name-absolute-p file)
8116 file
8117 (concat default-directory file)))
8118 (image (create-image abspath)))
8119 (when image
8120 (let ((ov (make-overlay start end)))
8121 (overlay-put ov 'display image)
8122 (overlay-put ov 'face 'default)
8123 (push ov markdown-inline-image-overlays))))))))))
8125 (defun markdown-toggle-inline-images ()
8126 "Toggle inline image overlays in the buffer."
8127 (interactive)
8128 (if markdown-inline-image-overlays
8129 (markdown-remove-inline-images)
8130 (markdown-display-inline-images)))
8133 ;;; GFM Code Block Fontification ==============================================
8135 (defcustom markdown-fontify-code-blocks-natively nil
8136 "When non-nil, fontify code in code blocks using the native major mode.
8137 This only works for fenced code blocks where the language is
8138 specified where we can automatically determine the appropriate
8139 mode to use. The language to mode mapping may be customized by
8140 setting the variable `markdown-code-lang-modes'."
8141 :group 'markdown
8142 :type 'boolean)
8144 (defun markdown-toggle-fontify-code-blocks-natively (&optional arg)
8145 "Toggle the native fontification of code blocks.
8146 With a prefix argument ARG, enable if ARG is positive,
8147 and disable otherwise."
8148 (interactive (list (or current-prefix-arg 'toggle)))
8149 (setq markdown-fontify-code-blocks-natively
8150 (if (eq arg 'toggle)
8151 (not markdown-fontify-code-blocks-natively)
8152 (> (prefix-numeric-value arg) 0)))
8153 (if markdown-fontify-code-blocks-natively
8154 (message "markdown-mode native code block fontification enabled")
8155 (message "markdown-mode native code block fontification disabled"))
8156 (markdown-reload-extensions))
8158 ;; This is based on `org-src-lang-modes' from org-src.el
8159 (defcustom markdown-code-lang-modes
8160 '(("ocaml" . tuareg-mode) ("elisp" . emacs-lisp-mode) ("ditaa" . artist-mode)
8161 ("asymptote" . asy-mode) ("dot" . fundamental-mode) ("sqlite" . sql-mode)
8162 ("calc" . fundamental-mode) ("C" . c-mode) ("cpp" . c++-mode)
8163 ("C++" . c++-mode) ("screen" . shell-script-mode) ("shell" . sh-mode)
8164 ("bash" . sh-mode))
8165 "Alist mapping languages to their major mode.
8166 The key is the language name, the value is the major mode. For
8167 many languages this is simple, but for language where this is not
8168 the case, this variable provides a way to simplify things on the
8169 user side. For example, there is no ocaml-mode in Emacs, but the
8170 mode to use is `tuareg-mode'."
8171 :group 'markdown
8172 :type '(repeat
8173 (cons
8174 (string "Language name")
8175 (symbol "Major mode"))))
8177 (defun markdown-get-lang-mode (lang)
8178 "Return major mode that should be used for LANG.
8179 LANG is a string, and the returned major mode is a symbol."
8180 (cl-find-if
8181 'fboundp
8182 (list (cdr (assoc lang markdown-code-lang-modes))
8183 (cdr (assoc (downcase lang) markdown-code-lang-modes))
8184 (intern (concat lang "-mode"))
8185 (intern (concat (downcase lang) "-mode")))))
8187 (defun markdown-fontify-code-blocks-generic (matcher last)
8188 "Add text properties to next code block from point to LAST.
8189 Use matching function MATCHER."
8190 (when (funcall matcher last)
8191 (save-excursion
8192 (save-match-data
8193 (let* ((start (match-beginning 0))
8194 (end (match-end 0))
8195 ;; Find positions outside opening and closing backquotes.
8196 (bol-prev (progn (goto-char start)
8197 (if (bolp) (point-at-bol 0) (point-at-bol))))
8198 (eol-next (progn (goto-char end)
8199 (if (bolp) (point-at-bol 2) (point-at-bol 3))))
8200 lang)
8201 (if (and markdown-fontify-code-blocks-natively
8202 (setq lang (markdown-code-block-lang)))
8203 (markdown-fontify-code-block-natively lang start end)
8204 (add-text-properties start end '(face markdown-pre-face)))
8205 ;; Set background for block as well as opening and closing lines.
8206 (font-lock-append-text-property
8207 bol-prev eol-next 'face 'markdown-code-face)
8208 ;; Set invisible property for lines before and after, including newline.
8209 (add-text-properties bol-prev start '(invisible markdown-markup))
8210 (add-text-properties end eol-next '(invisible markdown-markup)))))
8213 (defun markdown-fontify-gfm-code-blocks (last)
8214 "Add text properties to next GFM code block from point to LAST."
8215 (markdown-fontify-code-blocks-generic 'markdown-match-gfm-code-blocks last))
8217 (defun markdown-fontify-fenced-code-blocks (last)
8218 "Add text properties to next tilde fenced code block from point to LAST."
8219 (markdown-fontify-code-blocks-generic 'markdown-match-fenced-code-blocks last))
8221 ;; Based on `org-src-font-lock-fontify-block' from org-src.el.
8222 (defun markdown-fontify-code-block-natively (lang start end)
8223 "Fontify given GFM or fenced code block.
8224 This function is called by Emacs for automatic fontification when
8225 `markdown-fontify-code-blocks-natively' is non-nil. LANG is the
8226 language used in the block. START and END specify the block
8227 position."
8228 (let ((lang-mode (markdown-get-lang-mode lang)))
8229 (when (fboundp lang-mode)
8230 (let ((string (buffer-substring-no-properties start end))
8231 (modified (buffer-modified-p))
8232 (markdown-buffer (current-buffer)) pos next)
8233 (remove-text-properties start end '(face nil))
8234 (with-current-buffer
8235 (get-buffer-create
8236 (concat " markdown-code-fontification:" (symbol-name lang-mode)))
8237 ;; Make sure that modification hooks are not inhibited in
8238 ;; the org-src-fontification buffer in case we're called
8239 ;; from `jit-lock-function' (Bug#25132).
8240 (let ((inhibit-modification-hooks nil))
8241 (delete-region (point-min) (point-max))
8242 (insert string " ")) ;; so there's a final property change
8243 (unless (eq major-mode lang-mode) (funcall lang-mode))
8244 (markdown-font-lock-ensure)
8245 (setq pos (point-min))
8246 (while (setq next (next-single-property-change pos 'face))
8247 (let ((val (get-text-property pos 'face)))
8248 (when val
8249 (put-text-property
8250 (+ start (1- pos)) (1- (+ start next)) 'face
8251 val markdown-buffer)))
8252 (setq pos next)))
8253 (add-text-properties
8254 start end
8255 '(font-lock-fontified t fontified t font-lock-multiline t))
8256 (set-buffer-modified-p modified)))))
8258 (require 'edit-indirect nil t)
8259 (defvar edit-indirect-guess-mode-function)
8261 (defun markdown-edit-code-block ()
8262 "Edit Markdown code block in an indirect buffer."
8263 (interactive)
8264 (save-excursion
8265 (if (fboundp 'edit-indirect-region)
8266 (let* ((bounds (markdown-get-enclosing-fenced-block-construct))
8267 (begin (and bounds (goto-char (nth 0 bounds)) (point-at-bol 2)))
8268 (end (and bounds (goto-char (nth 1 bounds)) (point-at-bol 1))))
8269 (if (and begin end)
8270 (let* ((lang (markdown-code-block-lang))
8271 (mode (and lang (markdown-get-lang-mode lang)))
8272 (edit-indirect-guess-mode-function
8273 (lambda (_parent-buffer _beg _end)
8274 (funcall mode))))
8275 (edit-indirect-region begin end 'display-buffer))
8276 (error "Not inside a GFM or tilde fenced code block")))
8277 (when (y-or-n-p "Package edit-indirect needed to edit code blocks. Install it now? ")
8278 (progn (package-refresh-contents)
8279 (package-install 'edit-indirect)
8280 (markdown-edit-code-block))))))
8283 ;;; Mode Definition ==========================================================
8285 (defun markdown-show-version ()
8286 "Show the version number in the minibuffer."
8287 (interactive)
8288 (message "markdown-mode, version %s" markdown-mode-version))
8290 (defun markdown-mode-info ()
8291 "Open the `markdown-mode' homepage."
8292 (interactive)
8293 (browse-url "http://jblevins.org/projects/markdown-mode/"))
8295 ;;;###autoload
8296 (define-derived-mode markdown-mode text-mode "Markdown"
8297 "Major mode for editing Markdown files."
8298 ;; Natural Markdown tab width
8299 (setq tab-width 4)
8300 ;; Comments
8301 (make-local-variable 'comment-start)
8302 (setq comment-start "<!-- ")
8303 (make-local-variable 'comment-end)
8304 (setq comment-end " -->")
8305 (make-local-variable 'comment-start-skip)
8306 (setq comment-start-skip "<!--[ \t]*")
8307 (make-local-variable 'comment-column)
8308 (setq comment-column 0)
8309 (set (make-local-variable 'comment-auto-fill-only-comments) nil)
8310 ;; Syntax
8311 (add-hook 'syntax-propertize-extend-region-functions
8312 'markdown-syntax-propertize-extend-region)
8313 (add-hook 'jit-lock-after-change-extend-region-functions
8314 'markdown-font-lock-extend-region-function t t)
8315 (set (make-local-variable 'syntax-propertize-function)
8316 'markdown-syntax-propertize)
8317 ;; Font lock.
8318 (set (make-local-variable 'markdown-mode-font-lock-keywords) nil)
8319 (set (make-local-variable 'font-lock-defaults) nil)
8320 (set (make-local-variable 'font-lock-multiline) t)
8321 (add-to-list 'font-lock-extra-managed-props 'composition)
8322 (add-to-list 'font-lock-extra-managed-props 'invisible)
8323 (add-to-list 'font-lock-extra-managed-props 'display)
8324 (if markdown-hide-markup
8325 (add-to-invisibility-spec 'markdown-markup)
8326 (remove-from-invisibility-spec 'markdown-markup))
8327 (markdown-update-code-face)
8328 ;; Reload extensions
8329 (markdown-reload-extensions)
8330 ;; Add a buffer-local hook to reload after file-local variables are read
8331 (add-hook 'hack-local-variables-hook 'markdown-handle-local-variables nil t)
8332 ;; For imenu support
8333 (setq imenu-create-index-function
8334 (if markdown-nested-imenu-heading-index
8335 'markdown-imenu-create-nested-index
8336 'markdown-imenu-create-flat-index))
8337 ;; For menu support in XEmacs
8338 (easy-menu-add markdown-mode-menu markdown-mode-map)
8339 ;; Defun movement
8340 (set (make-local-variable 'beginning-of-defun-function)
8341 'markdown-beginning-of-defun)
8342 (set (make-local-variable 'end-of-defun-function)
8343 'markdown-end-of-defun)
8344 ;; Paragraph filling
8345 (set (make-local-variable 'fill-paragraph-function)
8346 'markdown-fill-paragraph)
8347 (set
8348 ;; Should match start of lines that start or separate paragraphs
8349 (make-local-variable 'paragraph-start)
8350 (mapconcat #'identity
8352 "\f" ; starts with a literal line-feed
8353 "[ \t\f]*$" ; space-only line
8354 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
8355 "[ \t]*[*+-][ \t]+" ; unordered list item
8356 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
8357 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
8358 "[ \t]*:[ \t]+" ; definition
8359 "^|" ; table or Pandoc line block
8361 "\\|"))
8362 (set
8363 ;; Should match lines that separate paragraphs without being
8364 ;; part of any paragraph:
8365 (make-local-variable 'paragraph-separate)
8366 (mapconcat #'identity
8367 '("[ \t\f]*$" ; space-only line
8368 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
8369 ;; The following is not ideal, but the Fill customization
8370 ;; options really only handle paragraph-starting prefixes,
8371 ;; not paragraph-ending suffixes:
8372 ".* $" ; line ending in two spaces
8373 "^#+"
8374 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
8375 "\\|"))
8376 (set (make-local-variable 'adaptive-fill-first-line-regexp)
8377 "\\`[ \t]*[A-Z]?>[ \t]*?\\'")
8378 (set (make-local-variable 'adaptive-fill-regexp) "\\s-*")
8379 (set (make-local-variable 'adaptive-fill-function)
8380 'markdown-adaptive-fill-function)
8381 (set (make-local-variable 'fill-forward-paragraph-function)
8382 #'markdown-fill-forward-paragraph)
8383 ;; Outline mode
8384 (make-local-variable 'outline-regexp)
8385 (setq outline-regexp markdown-regex-header)
8386 (make-local-variable 'outline-level)
8387 (setq outline-level 'markdown-outline-level)
8388 ;; Cause use of ellipses for invisible text.
8389 (add-to-invisibility-spec '(outline . t))
8391 ;; Inhibiting line-breaking:
8392 ;; Separating out each condition into a separate function so that users can
8393 ;; override if desired (with remove-hook)
8394 (add-hook 'fill-nobreak-predicate
8395 'markdown-inside-link-p nil t)
8396 (add-hook 'fill-nobreak-predicate
8397 'markdown-line-is-reference-definition-p nil t)
8398 (add-hook 'fill-nobreak-predicate
8399 'markdown-pipe-at-bol-p nil t)
8401 ;; Indentation
8402 (setq indent-line-function markdown-indent-function)
8404 ;; Flyspell
8405 (set (make-local-variable 'flyspell-generic-check-word-predicate)
8406 'markdown-flyspell-check-word-p)
8408 ;; Backwards compatibility with markdown-css-path
8409 (when (boundp 'markdown-css-path)
8410 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
8411 (add-to-list 'markdown-css-paths markdown-css-path))
8413 ;; Prepare hooks for XEmacs compatibility
8414 (when (featurep 'xemacs)
8415 (make-local-hook 'after-change-functions)
8416 (make-local-hook 'font-lock-extend-region-functions)
8417 (make-local-hook 'window-configuration-change-hook))
8419 ;; Make checkboxes buttons
8420 (when markdown-make-gfm-checkboxes-buttons
8421 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
8422 (add-hook 'after-change-functions 'markdown-gfm-checkbox-after-change-function t t))
8424 ;; add live preview export hook
8425 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
8426 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
8428 ;;;###autoload
8429 (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode) t)
8430 ;;;###autoload
8431 (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode) t)
8434 ;;; GitHub Flavored Markdown Mode ============================================
8436 (defvar gfm-mode-hook nil
8437 "Hook run when entering GFM mode.")
8439 (defvar gfm-font-lock-keywords
8440 ;; Basic Markdown features (excluding possibly overridden ones)
8441 markdown-mode-font-lock-keywords-basic
8442 "Default highlighting expressions for GitHub Flavored Markdown mode.")
8444 ;;;###autoload
8445 (define-derived-mode gfm-mode markdown-mode "GFM"
8446 "Major mode for editing GitHub Flavored Markdown files."
8447 (setq markdown-link-space-sub-char "-")
8448 (setq markdown-wiki-link-search-subdirectories t)
8449 (set (make-local-variable 'font-lock-defaults)
8450 '(gfm-font-lock-keywords))
8451 ;; do the initial link fontification
8452 (markdown-gfm-parse-buffer-for-languages))
8455 ;;; Live Preview Mode ============================================
8456 (define-minor-mode markdown-live-preview-mode
8457 "Toggle native previewing on save for a specific markdown file."
8458 :lighter " MD-Preview"
8459 (if markdown-live-preview-mode
8460 (if (markdown-live-preview-get-filename)
8461 (markdown-display-buffer-other-window (markdown-live-preview-export))
8462 (markdown-live-preview-mode -1)
8463 (error "Buffer %s does not visit a file" (current-buffer)))
8464 (markdown-live-preview-remove)))
8467 (provide 'markdown-mode)
8468 ;; Local Variables:
8469 ;; indent-tabs-mode: nil
8470 ;; End:
8471 ;;; markdown-mode.el ends here