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