Use a matching function for inline links
[markdown-mode.git] / markdown-mode.el
blobbeed88717947ecc724cc9cdd8b7c3e78cce5e05a
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-regex-link-reference . ((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 (7 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 form (begin end indent nonlist-indent marker).
2733 If the point is not inside a list item, return nil.
2734 Leave match data intact for `markdown-regex-list'."
2735 (let (cur prev-begin prev-end indent nonlist-indent marker)
2736 ;; Store current location
2737 (setq cur (point))
2738 ;; Verify that cur is between beginning and end of item
2739 (save-excursion
2740 (end-of-line)
2741 (when (re-search-backward markdown-regex-list nil t)
2742 (setq prev-begin (match-beginning 0))
2743 (setq indent (length (match-string 1)))
2744 (setq nonlist-indent (length (match-string 0)))
2745 (setq marker (concat (match-string 2) (match-string 3)))
2746 (save-match-data
2747 (markdown-cur-list-item-end nonlist-indent)
2748 (setq prev-end (point)))
2749 (when (and (>= cur prev-begin)
2750 (<= cur prev-end)
2751 nonlist-indent)
2752 (list prev-begin prev-end indent nonlist-indent marker))))))
2754 (defun markdown-list-item-at-point-p ()
2755 "Return t if there is a list item at the point and nil otherwise."
2756 (save-match-data (markdown-cur-list-item-bounds)))
2758 (defun markdown-bounds-of-thing-at-point (thing)
2759 "Call `bounds-of-thing-at-point' for THING with slight modifications.
2760 Does not include trailing newlines when THING is 'line. Handles the
2761 end of buffer case by setting both endpoints equal to the value of
2762 `point-max', since an empty region will trigger empty markup insertion.
2763 Return bounds of form (beg . end) if THING is found, or nil otherwise."
2764 (let* ((bounds (bounds-of-thing-at-point thing))
2765 (a (car bounds))
2766 (b (cdr bounds)))
2767 (when bounds
2768 (when (eq thing 'line)
2769 (cond ((and (eobp) (markdown-cur-line-blank-p))
2770 (setq a b))
2771 ((char-equal (char-before b) ?\^J)
2772 (setq b (1- b)))))
2773 (cons a b))))
2775 (defun markdown-reference-definition (reference)
2776 "Find out whether Markdown REFERENCE is defined.
2777 REFERENCE should not include the square brackets.
2778 When REFERENCE is defined, return a list of the form (text start end)
2779 containing the definition text itself followed by the start and end
2780 locations of the text. Otherwise, return nil.
2781 Leave match data for `markdown-regex-reference-definition'
2782 intact additional processing."
2783 (let ((reference (downcase reference)))
2784 (save-excursion
2785 (goto-char (point-min))
2786 (catch 'found
2787 (while (re-search-forward markdown-regex-reference-definition nil t)
2788 (when (string= reference (downcase (match-string-no-properties 2)))
2789 (throw 'found
2790 (list (match-string-no-properties 5)
2791 (match-beginning 5) (match-end 5)))))))))
2793 (defun markdown-get-defined-references ()
2794 "Return a list of all defined reference labels (not including square brackets)."
2795 (save-excursion
2796 (goto-char (point-min))
2797 (let (refs)
2798 (while (re-search-forward markdown-regex-reference-definition nil t)
2799 (let ((target (match-string-no-properties 2)))
2800 (cl-pushnew target refs :test #'equal)))
2801 (reverse refs))))
2803 (defun markdown-inline-code-at-point ()
2804 "Return non-nil if the point is at an inline code fragment.
2805 Return nil otherwise. Set match data according to
2806 `markdown-match-code' upon success.
2807 This function searches the block for a code fragment that
2808 contains the point using `markdown-match-code'. We do this
2809 because `thing-at-point-looking-at' does not work reliably with
2810 `markdown-regex-code'.
2812 The match data is set as follows:
2813 Group 1 matches the opening backquotes.
2814 Group 2 matches the code fragment itself, without backquotes.
2815 Group 3 matches the closing backquotes."
2816 (save-excursion
2817 (let ((old-point (point))
2818 (end-of-block (progn (markdown-end-of-text-block) (point)))
2819 found)
2820 (markdown-beginning-of-text-block)
2821 (while (and (markdown-match-code end-of-block)
2822 (setq found t)
2823 (< (match-end 0) old-point)))
2824 (and found ; matched something
2825 (<= (match-beginning 0) old-point) ; match contains old-point
2826 (>= (match-end 0) old-point)))))
2828 (defun markdown-inline-code-at-point-p ()
2829 "Return non-nil if there is inline code at the point.
2830 This is a predicate function counterpart to
2831 `markdown-inline-code-at-point' which does not modify the match
2832 data. See `markdown-code-block-at-point-p' for code blocks."
2833 (save-match-data (markdown-inline-code-at-point)))
2835 (make-obsolete 'markdown-code-at-point-p 'markdown-inline-code-at-point-p "2017-05-10")
2837 (defun markdown-code-block-at-pos (pos)
2838 "Return match data list if there is a code block at POS.
2839 This includes pre blocks, tilde-fenced code blocks, and GFM
2840 quoted code blocks. Return nil otherwise."
2841 (or (get-text-property pos 'markdown-pre)
2842 (markdown-get-enclosing-fenced-block-construct pos)
2843 ;; polymode removes text properties set by markdown-mode, so
2844 ;; check if `poly-markdown-mode' is active and whether the
2845 ;; `chunkmode' property is non-nil at POS.
2846 (and (bound-and-true-p poly-markdown-mode)
2847 (get-text-property pos 'chunkmode))))
2849 ;; Function was renamed to emphasize that it does not modify match-data.
2850 (defalias 'markdown-code-block-at-point 'markdown-code-block-at-point-p)
2852 (defun markdown-code-block-at-point-p ()
2853 "Return non-nil if there is a code block at the point.
2854 This includes pre blocks, tilde-fenced code blocks, and GFM
2855 quoted code blocks. This function does not modify the match
2856 data. See `markdown-inline-code-at-point-p' for inline code."
2857 (save-match-data (markdown-code-block-at-pos (point))))
2859 (defun markdown-heading-at-point ()
2860 "Return non-nil if there is a heading at the point.
2861 Set match data for `markdown-regex-header'."
2862 (let ((match-data (get-text-property (point) 'markdown-heading)))
2863 (when match-data
2864 (set-match-data match-data)
2865 t)))
2868 ;;; Markdown Font Lock Matching Functions =====================================
2870 (defun markdown-range-property-any (begin end prop prop-values)
2871 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
2872 Also returns t if PROP is a list containing one of the PROP-VALUES.
2873 Return nil otherwise."
2874 (let (props)
2875 (catch 'found
2876 (dolist (loc (number-sequence begin end))
2877 (when (setq props (get-char-property loc prop))
2878 (cond ((listp props)
2879 ;; props is a list, check for membership
2880 (dolist (val prop-values)
2881 (when (memq val props) (throw 'found loc))))
2883 ;; props is a scalar, check for equality
2884 (dolist (val prop-values)
2885 (when (eq val props) (throw 'found loc))))))))))
2887 (defun markdown-range-properties-exist (begin end props)
2888 (cl-loop
2889 for loc in (number-sequence begin end)
2890 with result = nil
2891 while (not
2892 (setq result
2893 (cl-some (lambda (prop) (get-char-property loc prop)) props)))
2894 finally return result))
2896 (defun markdown-match-inline-generic (regex last)
2897 "Match inline REGEX from the point to LAST."
2898 (when (re-search-forward regex last t)
2899 (let ((bounds (markdown-code-block-at-pos (match-beginning 1))))
2900 (if (null bounds)
2901 ;; Not in a code block: keep match data and return t when in bounds
2902 (<= (match-end 0) last)
2903 ;; In code block: move past it and recursively search again
2904 (when (< (goto-char (nth 1 bounds)) last)
2905 (markdown-match-inline-generic regex last))))))
2907 (defun markdown-match-code (last)
2908 "Match inline code fragments from point to LAST."
2909 (unless (bobp)
2910 (backward-char 1))
2911 (when (markdown-match-inline-generic markdown-regex-code last)
2912 (set-match-data (list (match-beginning 1) (match-end 1)
2913 (match-beginning 2) (match-end 2)
2914 (match-beginning 3) (match-end 3)
2915 (match-beginning 4) (match-end 4)))
2916 (goto-char (1+ (match-end 0)))))
2918 (defun markdown-match-bold (last)
2919 "Match inline bold from the point to LAST."
2920 (when (markdown-match-inline-generic markdown-regex-bold last)
2921 (let ((begin (match-beginning 2)) (end (match-end 2)))
2922 (cond
2923 ((markdown-range-property-any
2924 begin end 'face (list markdown-inline-code-face
2925 markdown-math-face))
2926 (goto-char (1+ (match-end 0)))
2927 (markdown-match-bold last))
2929 (set-match-data (list (match-beginning 2) (match-end 2)
2930 (match-beginning 3) (match-end 3)
2931 (match-beginning 4) (match-end 4)
2932 (match-beginning 5) (match-end 5)))
2933 (goto-char (1+ (match-end 0))))))))
2935 (defun markdown-match-italic (last)
2936 "Match inline italics from the point to LAST."
2937 (let ((regex (if (eq major-mode 'gfm-mode)
2938 markdown-regex-gfm-italic markdown-regex-italic)))
2939 (when (markdown-match-inline-generic regex last)
2940 (let ((begin (match-beginning 1)) (end (match-end 1)))
2941 (cond
2942 ((markdown-range-property-any
2943 begin begin 'face (list markdown-url-face))
2944 ;; Italics shouldn't begin inside a URL due to an underscore
2945 (goto-char (min (1+ (match-end 0)) last))
2946 (markdown-match-italic last))
2947 ((markdown-range-property-any
2948 begin end 'face (list markdown-inline-code-face
2949 markdown-bold-face
2950 markdown-list-face
2951 markdown-math-face))
2952 (goto-char (1+ (match-end 0)))
2953 (markdown-match-italic last))
2955 (set-match-data (list (match-beginning 1) (match-end 1)
2956 (match-beginning 2) (match-end 2)
2957 (match-beginning 3) (match-end 3)
2958 (match-beginning 4) (match-end 4)))
2959 (goto-char (1+ (match-end 0)))))))))
2961 (defun markdown-match-math-generic (regex last)
2962 "Match REGEX from point to LAST.
2963 REGEX is either `markdown-regex-math-inline-single' for matching
2964 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
2965 (when (and markdown-enable-math (markdown-match-inline-generic regex last))
2966 (let ((begin (match-beginning 1)) (end (match-end 1)))
2967 (prog1
2968 (if (or (markdown-range-property-any
2969 begin end 'face (list markdown-inline-code-face
2970 markdown-bold-face))
2971 (markdown-range-properties-exist
2972 begin end
2973 (markdown-get-fenced-block-middle-properties)))
2974 (markdown-match-math-generic regex last)
2976 (goto-char (1+ (match-end 0)))))))
2978 (defun markdown-match-math-single (last)
2979 "Match single quoted $..$ math from point to LAST."
2980 (markdown-match-math-generic markdown-regex-math-inline-single last))
2982 (defun markdown-match-math-double (last)
2983 "Match double quoted $$..$$ math from point to LAST."
2984 (markdown-match-math-generic markdown-regex-math-inline-double last))
2986 (defun markdown-match-propertized-text (property last)
2987 "Match text with PROPERTY from point to LAST.
2988 Restore match data previously stored in PROPERTY."
2989 (let ((saved (get-text-property (point) property))
2990 pos)
2991 (unless saved
2992 (setq pos (next-single-char-property-change (point) property nil last))
2993 (setq saved (get-text-property pos property)))
2994 (when saved
2995 (set-match-data saved)
2996 ;; Step at least one character beyond point. Otherwise
2997 ;; `font-lock-fontify-keywords-region' infloops.
2998 (goto-char (min (1+ (max (match-end 0) (point)))
2999 (point-max)))
3000 saved)))
3002 (defun markdown-match-pre-blocks (last)
3003 "Match preformatted blocks from point to LAST.
3004 Use data stored in 'markdown-pre text property during syntax
3005 analysis."
3006 (markdown-match-propertized-text 'markdown-pre last))
3008 (defun markdown-match-gfm-code-blocks (last)
3009 "Match GFM quoted code blocks from point to LAST.
3010 Use data stored in 'markdown-gfm-code text property during syntax
3011 analysis."
3012 (markdown-match-propertized-text 'markdown-gfm-code last))
3014 (defun markdown-match-gfm-open-code-blocks (last)
3015 (markdown-match-propertized-text 'markdown-gfm-block-begin last))
3017 (defun markdown-match-gfm-close-code-blocks (last)
3018 (markdown-match-propertized-text 'markdown-gfm-block-end last))
3020 (defun markdown-match-fenced-code-blocks (last)
3021 "Match fenced code blocks from the point to LAST."
3022 (markdown-match-propertized-text 'markdown-fenced-code last))
3024 (defun markdown-match-fenced-start-code-block (last)
3025 (markdown-match-propertized-text 'markdown-tilde-fence-begin last))
3027 (defun markdown-match-fenced-end-code-block (last)
3028 (markdown-match-propertized-text 'markdown-tilde-fence-end last))
3030 (defun markdown-match-blockquotes (last)
3031 "Match blockquotes from point to LAST.
3032 Use data stored in 'markdown-blockquote text property during syntax
3033 analysis."
3034 (markdown-match-propertized-text 'markdown-blockquote last))
3036 (defun markdown-match-heading-1-setext (last)
3037 "Match level 1 setext headings from point to LAST."
3038 (markdown-match-propertized-text 'markdown-heading-1-setext last))
3040 (defun markdown-match-heading-2-setext (last)
3041 "Match level 2 setext headings from point to LAST."
3042 (markdown-match-propertized-text 'markdown-heading-2-setext last))
3044 (defun markdown-match-heading-1-atx (last)
3045 "Match level 1 ATX headings from point to LAST."
3046 (markdown-match-propertized-text 'markdown-heading-1-atx last))
3048 (defun markdown-match-heading-2-atx (last)
3049 "Match level 2 ATX headings from point to LAST."
3050 (markdown-match-propertized-text 'markdown-heading-2-atx last))
3052 (defun markdown-match-heading-3-atx (last)
3053 "Match level 3 ATX headings from point to LAST."
3054 (markdown-match-propertized-text 'markdown-heading-3-atx last))
3056 (defun markdown-match-heading-4-atx (last)
3057 "Match level 4 ATX headings from point to LAST."
3058 (markdown-match-propertized-text 'markdown-heading-4-atx last))
3060 (defun markdown-match-heading-5-atx (last)
3061 "Match level 5 ATX headings from point to LAST."
3062 (markdown-match-propertized-text 'markdown-heading-5-atx last))
3064 (defun markdown-match-heading-6-atx (last)
3065 "Match level 6 ATX headings from point to LAST."
3066 (markdown-match-propertized-text 'markdown-heading-6-atx last))
3068 (defun markdown-match-hr (last)
3069 "Match horizontal rules comments from the point to LAST."
3070 (while (and (re-search-forward markdown-regex-hr last t)
3071 (or (markdown-on-heading-p)
3072 (markdown-code-block-at-point-p))
3073 (< (match-end 0) last))
3074 (forward-line))
3075 (beginning-of-line)
3076 (cond ((looking-at-p markdown-regex-hr)
3077 (forward-line)
3079 (t nil)))
3081 (defun markdown-match-comments (last)
3082 "Match HTML comments from the point to LAST."
3083 (when (and (skip-syntax-forward "^<" last))
3084 (let ((beg (point)))
3085 (when (and (skip-syntax-forward "^>" last) (< (point) last))
3086 (forward-char)
3087 (set-match-data (list beg (point)))
3088 t))))
3090 (defun markdown-match-inline-links (last)
3091 "Match inline links from point to LAST."
3092 ;; Match opening exclamation point (optional) and left bracket.
3093 (when (re-search-forward "\\(!\\)?\\(\\[\\)" last t)
3094 (let* ((bang (match-beginning 1))
3095 (square-begin (match-beginning 2))
3096 ;; Find end of block to prevent matching across blocks
3097 (end-of-block (save-excursion
3098 (progn
3099 (goto-char (match-beginning 2))
3100 (markdown-end-of-text-block)
3101 (point))))
3102 ;; Move over balanced expressions to closing right bracket.
3103 ;; Catch unbalanced expression errors and return nil.
3104 (square-end (condition-case nil
3105 (and (goto-char square-begin)
3106 (scan-sexps (point) 1))
3107 (error nil)))
3108 ;; Continue with point at CONT-POINT upon failure
3109 (cont-point (min end-of-block last))
3110 paren-begin paren-end url-begin url-end
3111 title-begin title-end)
3112 ;; When bracket found, in range, and followed by a left paren...
3113 (when (and square-end (< square-end end-of-block) (goto-char square-end)
3114 (char-equal (char-after (point)) ?\())
3115 ;; Scan across balanced expressions for closing parenthesis.
3116 (setq paren-begin (point)
3117 paren-end (condition-case nil
3118 (scan-sexps (point) 1)
3119 (error nil)))
3120 ;; Check that closing parenthesis is in range
3121 (if (and paren-end (< paren-end end-of-block) (<= paren-end last))
3122 (progn
3123 ;; Search for (optional) title inside closing parenthesis
3124 (when (search-forward "\"" paren-end t)
3125 (setq title-begin (1- (point))
3126 title-end (and (goto-char paren-end)
3127 (search-backward "\"" (1+ title-begin) t))
3128 title-end (and title-end (1+ title-end))))
3129 ;; Store URL range
3130 (setq url-begin (1+ paren-begin)
3131 url-end (1- (or title-begin paren-end)))
3132 ;; Set match data, move point beyond link, and return
3133 (set-match-data
3134 (list (or bang square-begin) paren-end ; 0 - all
3135 bang (and bang (1+ bang)) ; 1 - bang
3136 square-begin (1+ square-begin) ; 2 - markup
3137 (1+ square-begin) (1- square-end) ; 3 - link text
3138 (1- square-end) square-end ; 4 - markup
3139 paren-begin (1+ paren-begin) ; 5 - markup
3140 url-begin url-end ; 6 - url
3141 title-begin title-end ; 7 - title
3142 (1- paren-end) paren-end)) ; 8 - markup
3143 ;; Nullify cont-point and leave point at end and
3144 (setq cont-point nil)
3145 (goto-char paren-end))
3146 ;; If no closing parenthesis in range, update continuation point
3147 (setq cont-point (min end-of-block last))))
3148 (cond
3149 ;; On failure, continue searching at cont-point
3150 ((and cont-point (< cont-point last))
3151 (goto-char cont-point)
3152 (markdown-match-inline-links last))
3153 ;; No more text, return nil
3154 ((and cont-point (= cont-point last))
3155 nil)
3156 ;; Return t if a match occurred
3157 (t t)))))
3159 (defun markdown-get-match-boundaries (start-header end-header last &optional pos)
3160 (save-excursion
3161 (goto-char (or pos (point-min)))
3162 (cl-loop
3163 with cur-result = nil
3164 and st-hdr = (or start-header "\\`")
3165 and end-hdr = (or end-header "\n\n\\|\n\\'\\|\\'")
3166 while (and (< (point) last)
3167 (re-search-forward st-hdr last t)
3168 (progn
3169 (setq cur-result (match-data))
3170 (re-search-forward end-hdr nil t)))
3171 collect (list cur-result (match-data)))))
3173 (defvar markdown-conditional-search-function #'re-search-forward
3174 "Conditional search function used in `markdown-search-until-condition'.
3175 Made into a variable to allow for dynamic let-binding.")
3177 (defun markdown-search-until-condition (condition &rest args)
3178 (let (ret)
3179 (while (and (not ret) (apply markdown-conditional-search-function args))
3180 (setq ret (funcall condition)))
3181 ret))
3183 (defun markdown-match-generic-metadata
3184 (regexp last &optional start-header end-header)
3185 "Match generic metadata specified by REGEXP from the point to LAST.
3186 If START-HEADER is nil, we assume metadata can only occur at the
3187 very top of a file (\"\\`\"). If END-HEADER is nil, we assume it
3188 is \"\n\n\""
3189 (let* ((header-bounds
3190 (markdown-get-match-boundaries start-header end-header last))
3191 (enclosing-header
3192 (cl-find-if ; just take first if multiple
3193 (lambda (match-bounds)
3194 (cl-destructuring-bind (begin end) (cl-second match-bounds)
3195 (and (< (point) begin)
3196 (save-excursion (re-search-forward regexp end t)))))
3197 header-bounds))
3198 (header-begin
3199 (when enclosing-header (cl-second (cl-first enclosing-header))))
3200 (header-end
3201 (when enclosing-header (cl-first (cl-second enclosing-header)))))
3202 (cond ((null enclosing-header)
3203 ;; Don't match anything outside of a header.
3204 nil)
3205 ((markdown-search-until-condition
3206 (lambda () (> (point) header-begin)) regexp (min last header-end) t)
3207 ;; If a metadata item is found, it may span several lines.
3208 (let ((key-beginning (match-beginning 1))
3209 (key-end (match-end 1))
3210 (markup-begin (match-beginning 2))
3211 (markup-end (match-end 2))
3212 (value-beginning (match-beginning 3)))
3213 (set-match-data (list key-beginning (point) ; complete metadata
3214 key-beginning key-end ; key
3215 markup-begin markup-end ; markup
3216 value-beginning (point))) ; value
3218 (t nil))))
3220 (defun markdown-match-declarative-metadata (last)
3221 "Match declarative metadata from the point to LAST."
3222 (markdown-match-generic-metadata markdown-regex-declarative-metadata last))
3224 (defun markdown-match-pandoc-metadata (last)
3225 "Match Pandoc metadata from the point to LAST."
3226 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
3228 (defun markdown-match-yaml-metadata-begin (last)
3229 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last))
3231 (defun markdown-match-yaml-metadata-end (last)
3232 (markdown-match-propertized-text 'markdown-yaml-metadata-end last))
3234 (defun markdown-match-yaml-metadata-key (last)
3235 (markdown-match-propertized-text 'markdown-metadata-key last))
3238 ;;; Syntax Table ==============================================================
3240 (defvar markdown-mode-syntax-table
3241 (let ((tab (make-syntax-table text-mode-syntax-table)))
3242 (modify-syntax-entry ?\" "." tab)
3243 tab)
3244 "Syntax table for `markdown-mode'.")
3247 ;;; Element Insertion =========================================================
3249 (defun markdown-ensure-blank-line-before ()
3250 "If previous line is not already blank, insert a blank line before point."
3251 (unless (bolp) (insert "\n"))
3252 (unless (or (bobp) (looking-back "\n\\s-*\n" nil)) (insert "\n")))
3254 (defun markdown-ensure-blank-line-after ()
3255 "If following line is not already blank, insert a blank line after point.
3256 Return the point where it was originally."
3257 (save-excursion
3258 (unless (eolp) (insert "\n"))
3259 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
3261 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
3262 "Insert the strings S1 and S2, wrapping around region or THING.
3263 If a region is specified by the optional BEG and END arguments,
3264 wrap the strings S1 and S2 around that region.
3265 If there is an active region, wrap the strings S1 and S2 around
3266 the region. If there is not an active region but the point is at
3267 THING, wrap that thing (which defaults to word). Otherwise, just
3268 insert S1 and S2 and place the cursor in between. Return the
3269 bounds of the entire wrapped string, or nil if nothing was wrapped
3270 and S1 and S2 were only inserted."
3271 (let (a b bounds new-point)
3272 (cond
3273 ;; Given region
3274 ((and beg end)
3275 (setq a beg
3276 b end
3277 new-point (+ (point) (length s1))))
3278 ;; Active region
3279 ((markdown-use-region-p)
3280 (setq a (region-beginning)
3281 b (region-end)
3282 new-point (+ (point) (length s1))))
3283 ;; Thing (word) at point
3284 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
3285 (setq a (car bounds)
3286 b (cdr bounds)
3287 new-point (+ (point) (length s1))))
3288 ;; No active region and no word
3290 (setq a (point)
3291 b (point))))
3292 (goto-char b)
3293 (insert s2)
3294 (goto-char a)
3295 (insert s1)
3296 (when new-point (goto-char new-point))
3297 (if (= a b)
3299 (setq b (+ b (length s1) (length s2)))
3300 (cons a b))))
3302 (defun markdown-point-after-unwrap (cur prefix suffix)
3303 "Return desired position of point after an unwrapping operation.
3304 CUR gives the position of the point before the operation.
3305 Additionally, two cons cells must be provided. PREFIX gives the
3306 bounds of the prefix string and SUFFIX gives the bounds of the
3307 suffix string."
3308 (cond ((< cur (cdr prefix)) (car prefix))
3309 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
3310 ((<= cur (cdr suffix))
3311 (- cur (+ (- (cdr prefix) (car prefix))
3312 (- cur (car suffix)))))
3313 (t cur)))
3315 (defun markdown-unwrap-thing-at-point (regexp all text)
3316 "Remove prefix and suffix of thing at point and reposition the point.
3317 When the thing at point matches REGEXP, replace the subexpression
3318 ALL with the string in subexpression TEXT. Reposition the point
3319 in an appropriate location accounting for the removal of prefix
3320 and suffix strings. Return new bounds of string from group TEXT.
3321 When REGEXP is nil, assumes match data is already set."
3322 (when (or (null regexp)
3323 (thing-at-point-looking-at regexp))
3324 (let ((cur (point))
3325 (prefix (cons (match-beginning all) (match-beginning text)))
3326 (suffix (cons (match-end text) (match-end all)))
3327 (bounds (cons (match-beginning text) (match-end text))))
3328 ;; Replace the thing at point
3329 (replace-match (match-string text) t t nil all)
3330 ;; Reposition the point
3331 (goto-char (markdown-point-after-unwrap cur prefix suffix))
3332 ;; Adjust bounds
3333 (setq bounds (cons (car prefix)
3334 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
3336 (defun markdown-unwrap-things-in-region (beg end regexp all text)
3337 "Remove prefix and suffix of all things in region from BEG to END.
3338 When a thing in the region matches REGEXP, replace the
3339 subexpression ALL with the string in subexpression TEXT.
3340 Return a cons cell containing updated bounds for the region."
3341 (save-excursion
3342 (goto-char beg)
3343 (let ((removed 0) len-all len-text)
3344 (while (re-search-forward regexp (- end removed) t)
3345 (setq len-all (length (match-string-no-properties all)))
3346 (setq len-text (length (match-string-no-properties text)))
3347 (setq removed (+ removed (- len-all len-text)))
3348 (replace-match (match-string text) t t nil all))
3349 (cons beg (- end removed)))))
3351 (defun markdown-insert-hr (arg)
3352 "Insert or replace a horizonal rule.
3353 By default, use the first element of `markdown-hr-strings'. When
3354 ARG is non-nil, as when given a prefix, select a different
3355 element as follows. When prefixed with \\[universal-argument],
3356 use the last element of `markdown-hr-strings' instead. When
3357 prefixed with an integer from 1 to the length of
3358 `markdown-hr-strings', use the element in that position instead."
3359 (interactive "*P")
3360 (when (thing-at-point-looking-at markdown-regex-hr)
3361 (delete-region (match-beginning 0) (match-end 0)))
3362 (markdown-ensure-blank-line-before)
3363 (cond ((equal arg '(4))
3364 (insert (car (reverse markdown-hr-strings))))
3365 ((and (integerp arg) (> arg 0)
3366 (<= arg (length markdown-hr-strings)))
3367 (insert (nth (1- arg) markdown-hr-strings)))
3369 (insert (car markdown-hr-strings))))
3370 (markdown-ensure-blank-line-after))
3372 (defun markdown-insert-bold ()
3373 "Insert markup to make a region or word bold.
3374 If there is an active region, make the region bold. If the point
3375 is at a non-bold word, make the word bold. If the point is at a
3376 bold word or phrase, remove the bold markup. Otherwise, simply
3377 insert bold delimiters and place the cursor in between them."
3378 (interactive)
3379 (let ((delim (if markdown-bold-underscore "__" "**")))
3380 (if (markdown-use-region-p)
3381 ;; Active region
3382 (let ((bounds (markdown-unwrap-things-in-region
3383 (region-beginning) (region-end)
3384 markdown-regex-bold 2 4)))
3385 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3386 ;; Bold markup removal, bold word at point, or empty markup insertion
3387 (if (thing-at-point-looking-at markdown-regex-bold)
3388 (markdown-unwrap-thing-at-point nil 2 4)
3389 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3391 (defun markdown-insert-italic ()
3392 "Insert markup to make a region or word italic.
3393 If there is an active region, make the region italic. If the point
3394 is at a non-italic word, make the word italic. If the point is at an
3395 italic word or phrase, remove the italic markup. Otherwise, simply
3396 insert italic delimiters and place the cursor in between them."
3397 (interactive)
3398 (let ((delim (if markdown-italic-underscore "_" "*")))
3399 (if (markdown-use-region-p)
3400 ;; Active region
3401 (let ((bounds (markdown-unwrap-things-in-region
3402 (region-beginning) (region-end)
3403 markdown-regex-italic 1 3)))
3404 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3405 ;; Italic markup removal, italic word at point, or empty markup insertion
3406 (if (thing-at-point-looking-at markdown-regex-italic)
3407 (markdown-unwrap-thing-at-point nil 1 3)
3408 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3410 (defun markdown-insert-strike-through ()
3411 "Insert markup to make a region or word strikethrough.
3412 If there is an active region, make the region strikethrough. If the point
3413 is at a non-bold word, make the word strikethrough. If the point is at a
3414 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
3415 simply insert bold delimiters and place the cursor in between them."
3416 (interactive)
3417 (let ((delim "~~"))
3418 (if (markdown-use-region-p)
3419 ;; Active region
3420 (let ((bounds (markdown-unwrap-things-in-region
3421 (region-beginning) (region-end)
3422 markdown-regex-strike-through 2 4)))
3423 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3424 ;; Strikethrough markup removal, strikethrough word at point, or empty markup insertion
3425 (if (thing-at-point-looking-at markdown-regex-strike-through)
3426 (markdown-unwrap-thing-at-point nil 2 4)
3427 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3429 (defun markdown-insert-code ()
3430 "Insert markup to make a region or word an inline code fragment.
3431 If there is an active region, make the region an inline code
3432 fragment. If the point is at a word, make the word an inline
3433 code fragment. Otherwise, simply insert code delimiters and
3434 place the cursor in between them."
3435 (interactive)
3436 (if (markdown-use-region-p)
3437 ;; Active region
3438 (let ((bounds (markdown-unwrap-things-in-region
3439 (region-beginning) (region-end)
3440 markdown-regex-code 1 3)))
3441 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
3442 ;; Code markup removal, code markup for word, or empty markup insertion
3443 (if (markdown-inline-code-at-point)
3444 (markdown-unwrap-thing-at-point nil 0 2)
3445 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
3447 (defun markdown-insert-kbd ()
3448 "Insert markup to wrap region or word in <kbd> tags.
3449 If there is an active region, use the region. If the point is at
3450 a word, use the word. Otherwise, simply insert <kbd> tags and
3451 place the cursor in between them."
3452 (interactive)
3453 (if (markdown-use-region-p)
3454 ;; Active region
3455 (let ((bounds (markdown-unwrap-things-in-region
3456 (region-beginning) (region-end)
3457 markdown-regex-kbd 0 2)))
3458 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil (car bounds) (cdr bounds)))
3459 ;; Markup removal, markup for word, or empty markup insertion
3460 (if (thing-at-point-looking-at markdown-regex-kbd)
3461 (markdown-unwrap-thing-at-point nil 0 2)
3462 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil))))
3464 (defun markdown-insert-inline-link (text url &optional title)
3465 "Insert an inline link with TEXT pointing to URL.
3466 Optionally, the user can provide a TITLE."
3467 (let ((cur (point)))
3468 (setq title (and title (concat " \"" title "\"")))
3469 (insert (concat "[" text "](" url title ")"))
3470 (cond ((not text) (goto-char (+ 1 cur)))
3471 ((not url) (goto-char (+ 3 (length text) cur))))))
3473 (defun markdown-insert-inline-link-dwim ()
3474 "Insert an inline link of the form [link](url) at point.
3475 If there is an active region, the text in the region will be used
3476 as the URL, if it appears to be a URL, or else as the link text.
3477 If the point is at a URL, use it to create a new link. If the
3478 point is at a reference link, convert it to an inline link. If
3479 the point is at a word, use the word as the link text. In these
3480 cases, the point will be left at the position for inserting a
3481 URL. If there is no active region and the point is not at word,
3482 simply insert link markup and place the point in the position to
3483 enter link text."
3484 (interactive)
3485 (cond
3486 ;; If there is an active region, remove existing links in the
3487 ;; region and use resulting region as link text for a new link.
3488 ((markdown-use-region-p)
3489 (let* ((bounds (markdown-unwrap-things-in-region
3490 (region-beginning) (region-end)
3491 markdown-regex-link-inline 0 3))
3492 (text (buffer-substring (car bounds) (cdr bounds))))
3493 (delete-region (car bounds) (cdr bounds))
3494 (markdown-insert-inline-link text nil)))
3495 ;; If there is an inline link at the point, remove it and add the
3496 ;; link text to the kill ring.
3497 ((thing-at-point-looking-at markdown-regex-link-inline)
3498 (kill-new (match-string 3))
3499 (delete-region (match-beginning 0) (match-end 0)))
3500 ;; If there is an angle URL at the point, use it for a new link.
3501 ((thing-at-point-looking-at markdown-regex-angle-uri)
3502 (let ((url (match-string 2)))
3503 (delete-region (match-beginning 0) (match-end 0))
3504 (markdown-insert-inline-link nil url)))
3505 ;; If there is a plain URL at the point, use it for a new link.
3506 ((thing-at-point-looking-at markdown-regex-uri)
3507 (let ((url (match-string 0)))
3508 (delete-region (match-beginning 0) (match-end 0))
3509 (markdown-insert-inline-link nil url)))
3510 ;; If there is a reference link at point, convert to inline link.
3511 ((thing-at-point-looking-at markdown-regex-link-reference)
3512 (let ((beg (match-beginning 0))
3513 (end (match-end 0))
3514 (text (match-string 3))
3515 (url (markdown-link-link)))
3516 (delete-region beg end)
3517 (markdown-insert-inline-link text url)))
3518 ;; Otherwise, insert a link
3519 (t (let ((bounds (markdown-wrap-or-insert "[" "]()")))
3520 (when bounds
3521 (goto-char (- (cdr bounds) 1)))))))
3523 (defun markdown-insert-reference-link (text label &optional url title)
3524 "Insert a reference link and, optionally, a reference definition.
3525 The link TEXT will be inserted followed by the optional LABEL.
3526 If a URL is given, also insert a definition for the reference
3527 LABEL according to `markdown-reference-location'. If a TITLE is
3528 given, it will be added to the end of the reference definition
3529 and will be used to populate the title attribute when converted
3530 to XHTML. If URL is nil, insert only the link portion (for
3531 example, when a reference label is already defined)."
3532 (insert (concat "[" text "][" label "]"))
3533 (when url
3534 (markdown-insert-reference-definition
3535 (if (string-equal label "") text label)
3536 url title)))
3538 (defun markdown-insert-reference-definition (label &optional url title)
3539 "Add definition for reference LABEL with URL and TITLE.
3540 LABEL is a Markdown reference label without square brackets.
3541 URL and TITLE are optional. When given, the TITLE will
3542 be used to populate the title attribute when converted to XHTML."
3543 ;; END specifies where to leave the point upon return
3544 (let ((end (point)))
3545 (cl-case markdown-reference-location
3546 (end (goto-char (point-max)))
3547 (immediately (markdown-end-of-text-block))
3548 (header (markdown-end-of-defun)))
3549 (unless (markdown-cur-line-blank-p) (insert "\n"))
3550 (insert "\n[" label "]: ")
3551 (if url
3552 (insert url)
3553 ;; When no URL is given, leave cursor at END following the colon
3554 (setq end (point)))
3555 (when (> (length title) 0)
3556 (insert " \"" title "\""))
3557 (unless (looking-at-p "\n")
3558 (insert "\n"))
3559 (goto-char end)
3560 (when url
3561 (message
3562 (substitute-command-keys
3563 "Defined reference [%s], press \\[markdown-jump] to jump there")
3564 label))))
3566 (defun markdown-insert-reference-link-dwim ()
3567 "Insert a reference link of the form [text][label] at point.
3568 If there is an active region, the text in the region will be used
3569 as the link text. If the point is at an inline link, it will be
3570 converted to a reference link. If the point is at a word, it will
3571 be used as the link text. Otherwise, the link text will be read from
3572 the minibuffer. The link label will be read from the minibuffer in
3573 both cases, with completion from the set of currently defined
3574 references. To create an implicit reference link, press RET to
3575 accept the default, an empty label. If the entered referenced
3576 label is not defined, additionally prompt for the URL
3577 and (optional) title. The reference definition is placed at the
3578 location determined by `markdown-reference-location'."
3579 (interactive)
3580 (let* ((defined-labels (markdown-get-defined-references))
3581 (switch (thing-at-point-looking-at markdown-regex-link-inline))
3582 (bounds (cond ((markdown-use-region-p)
3583 (cons (region-beginning) (region-end)))
3584 (switch
3585 (cons (match-beginning 0) (match-end 0)))
3587 (markdown-bounds-of-thing-at-point 'word))))
3588 (text (cond (switch (match-string 3))
3589 (bounds (buffer-substring (car bounds) (cdr bounds)))
3590 (t (read-string "Link Text: "))))
3591 (label (completing-read
3592 "Link Label (default: none): " defined-labels
3593 nil nil nil 'markdown-reference-label-history nil))
3594 (ref (save-match-data
3595 (markdown-reference-definition
3596 (if (> (length label) 0) label text))))
3597 (url (cond (ref nil)
3598 (switch (match-string 6))
3599 (t (read-string "Link URL: "))))
3600 (title (cond
3601 ((= (length url) 0) nil)
3602 (switch (if (> (length (match-string 7)) 2)
3603 (substring (match-string 7) 1 -1)
3604 nil))
3605 (t (read-string "Link Title (optional): ")))))
3606 (when bounds (delete-region (car bounds) (cdr bounds)))
3607 (markdown-insert-reference-link text label url title)))
3609 (defun markdown-insert-uri ()
3610 "Insert markup for an inline URI.
3611 If there is an active region, use it as the URI. If the point is
3612 at a URI, wrap it with angle brackets. If the point is at an
3613 inline URI, remove the angle brackets. Otherwise, simply insert
3614 angle brackets place the point between them."
3615 (interactive)
3616 (if (markdown-use-region-p)
3617 ;; Active region
3618 (let ((bounds (markdown-unwrap-things-in-region
3619 (region-beginning) (region-end)
3620 markdown-regex-angle-uri 0 2)))
3621 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
3622 ;; Markup removal, URI at point, or empty markup insertion
3623 (if (thing-at-point-looking-at markdown-regex-angle-uri)
3624 (markdown-unwrap-thing-at-point nil 0 2)
3625 (markdown-wrap-or-insert "<" ">" 'url nil nil))))
3627 (defun markdown-insert-wiki-link ()
3628 "Insert a wiki link of the form [[WikiLink]].
3629 If there is an active region, use the region as the link text.
3630 If the point is at a word, use the word as the link text. If
3631 there is no active region and the point is not at word, simply
3632 insert link markup."
3633 (interactive)
3634 (if (markdown-use-region-p)
3635 ;; Active region
3636 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
3637 ;; Markup removal, wiki link at at point, or empty markup insertion
3638 (if (thing-at-point-looking-at markdown-regex-wiki-link)
3639 (if (or markdown-wiki-link-alias-first
3640 (null (match-string 5)))
3641 (markdown-unwrap-thing-at-point nil 1 3)
3642 (markdown-unwrap-thing-at-point nil 1 5))
3643 (markdown-wrap-or-insert "[[" "]]"))))
3645 (defun markdown-insert-image (&optional arg)
3646 "Insert image markup using region or word as alt text if possible.
3647 If there is an active region, use the region as the alt text. If the
3648 point is at a word, use the word as the alt text. In these cases, the
3649 point will be left at the position for inserting a URL. If there is no
3650 active region and the point is not at word, simply insert image markup and
3651 place the point in the position to enter alt text. If ARG is nil, insert
3652 inline image markup. Otherwise, insert reference image markup."
3653 (interactive "*P")
3654 (let ((bounds (if arg
3655 (markdown-wrap-or-insert "![" "][]")
3656 (markdown-wrap-or-insert "![" "]()"))))
3657 (when bounds
3658 (goto-char (- (cdr bounds) 1)))))
3660 (defun markdown-insert-reference-image ()
3661 "Insert reference-style image markup using region or word as alt text.
3662 Calls `markdown-insert-image' with prefix argument."
3663 (interactive)
3664 (markdown-insert-image t))
3666 (defun markdown-remove-header ()
3667 "Remove header markup if point is at a header.
3668 Return bounds of remaining header text if a header was removed
3669 and nil otherwise."
3670 (interactive "*")
3671 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
3672 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
3674 (defun markdown-insert-header (&optional level text setext)
3675 "Insert or replace header markup.
3676 The level of the header is specified by LEVEL and header text is
3677 given by TEXT. LEVEL must be an integer from 1 and 6, and the
3678 default value is 1.
3679 When TEXT is nil, the header text is obtained as follows.
3680 If there is an active region, it is used as the header text.
3681 Otherwise, the current line will be used as the header text.
3682 If there is not an active region and the point is at a header,
3683 remove the header markup and replace with level N header.
3684 Otherwise, insert empty header markup and place the cursor in
3685 between.
3686 The style of the header will be atx (hash marks) unless
3687 SETEXT is non-nil, in which case a setext-style (underlined)
3688 header will be inserted."
3689 (interactive "p\nsHeader text: ")
3690 (setq level (min (max (or level 1) 1) (if setext 2 6)))
3691 ;; Determine header text if not given
3692 (when (null text)
3693 (if (markdown-use-region-p)
3694 ;; Active region
3695 (setq text (delete-and-extract-region (region-beginning) (region-end)))
3696 ;; No active region
3697 (markdown-remove-header)
3698 (setq text (delete-and-extract-region
3699 (line-beginning-position) (line-end-position)))
3700 (when (and setext (string-match-p "^[ \t]*$" text))
3701 (setq text (read-string "Header text: "))))
3702 (setq text (markdown-compress-whitespace-string text)))
3703 ;; Insertion with given text
3704 (markdown-ensure-blank-line-before)
3705 (let (hdr)
3706 (cond (setext
3707 (setq hdr (make-string (string-width text) (if (= level 2) ?- ?=)))
3708 (insert text "\n" hdr))
3710 (setq hdr (make-string level ?#))
3711 (insert hdr " " text)
3712 (when (null markdown-asymmetric-header) (insert " " hdr)))))
3713 (markdown-ensure-blank-line-after)
3714 ;; Leave point at end of text
3715 (cond (setext
3716 (backward-char (1+ (string-width text))))
3717 ((null markdown-asymmetric-header)
3718 (backward-char (1+ level)))))
3720 (defun markdown-insert-header-dwim (&optional arg setext)
3721 "Insert or replace header markup.
3722 The level and type of the header are determined automatically by
3723 the type and level of the previous header, unless a prefix
3724 argument is given via ARG.
3725 With a numeric prefix valued 1 to 6, insert a header of the given
3726 level, with the type being determined automatically (note that
3727 only level 1 or 2 setext headers are possible).
3729 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
3730 promote the heading by one level.
3731 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
3732 demote the heading by one level.
3733 When SETEXT is non-nil, prefer setext-style headers when
3734 possible (levels one and two).
3736 When there is an active region, use it for the header text. When
3737 the point is at an existing header, change the type and level
3738 according to the rules above.
3739 Otherwise, if the line is not empty, create a header using the
3740 text on the current line as the header text.
3741 Finally, if the point is on a blank line, insert empty header
3742 markup (atx) or prompt for text (setext).
3743 See `markdown-insert-header' for more details about how the
3744 header text is determined."
3745 (interactive "*P")
3746 (let (level)
3747 (save-excursion
3748 (when (or (thing-at-point-looking-at markdown-regex-header)
3749 (re-search-backward markdown-regex-header nil t))
3750 ;; level of current or previous header
3751 (setq level (markdown-outline-level))
3752 ;; match group 1 indicates a setext header
3753 (setq setext (match-end 1))))
3754 ;; check prefix argument
3755 (cond
3756 ((and (equal arg '(4)) level (> level 1)) ;; C-u
3757 (cl-decf level))
3758 ((and (equal arg '(16)) level (< level 6)) ;; C-u C-u
3759 (cl-incf level))
3760 (arg ;; numeric prefix
3761 (setq level (prefix-numeric-value arg))))
3762 ;; setext headers must be level one or two
3763 (and level (setq setext (and setext (<= level 2))))
3764 ;; insert the heading
3765 (markdown-insert-header level nil setext)))
3767 (defun markdown-insert-header-setext-dwim (&optional arg)
3768 "Insert or replace header markup, with preference for setext.
3769 See `markdown-insert-header-dwim' for details, including how ARG is handled."
3770 (interactive "*P")
3771 (markdown-insert-header-dwim arg t))
3773 (defun markdown-insert-header-atx-1 ()
3774 "Insert a first level atx-style (hash mark) header.
3775 See `markdown-insert-header'."
3776 (interactive "*")
3777 (markdown-insert-header 1 nil nil))
3779 (defun markdown-insert-header-atx-2 ()
3780 "Insert a level two atx-style (hash mark) header.
3781 See `markdown-insert-header'."
3782 (interactive "*")
3783 (markdown-insert-header 2 nil nil))
3785 (defun markdown-insert-header-atx-3 ()
3786 "Insert a level three atx-style (hash mark) header.
3787 See `markdown-insert-header'."
3788 (interactive "*")
3789 (markdown-insert-header 3 nil nil))
3791 (defun markdown-insert-header-atx-4 ()
3792 "Insert a level four atx-style (hash mark) header.
3793 See `markdown-insert-header'."
3794 (interactive "*")
3795 (markdown-insert-header 4 nil nil))
3797 (defun markdown-insert-header-atx-5 ()
3798 "Insert a level five atx-style (hash mark) header.
3799 See `markdown-insert-header'."
3800 (interactive "*")
3801 (markdown-insert-header 5 nil nil))
3803 (defun markdown-insert-header-atx-6 ()
3804 "Insert a sixth level atx-style (hash mark) header.
3805 See `markdown-insert-header'."
3806 (interactive "*")
3807 (markdown-insert-header 6 nil nil))
3809 (defun markdown-insert-header-setext-1 ()
3810 "Insert a setext-style (underlined) first-level header.
3811 See `markdown-insert-header'."
3812 (interactive "*")
3813 (markdown-insert-header 1 nil t))
3815 (defun markdown-insert-header-setext-2 ()
3816 "Insert a setext-style (underlined) second-level header.
3817 See `markdown-insert-header'."
3818 (interactive "*")
3819 (markdown-insert-header 2 nil t))
3821 (defun markdown-blockquote-indentation (loc)
3822 "Return string containing necessary indentation for a blockquote at LOC.
3823 Also see `markdown-pre-indentation'."
3824 (save-excursion
3825 (goto-char loc)
3826 (let* ((list-level (length (markdown-calculate-list-levels)))
3827 (indent ""))
3828 (dotimes (_ list-level indent)
3829 (setq indent (concat indent " "))))))
3831 (defun markdown-insert-blockquote ()
3832 "Start a blockquote section (or blockquote the region).
3833 If Transient Mark mode is on and a region is active, it is used as
3834 the blockquote text."
3835 (interactive)
3836 (if (markdown-use-region-p)
3837 (markdown-blockquote-region (region-beginning) (region-end))
3838 (markdown-ensure-blank-line-before)
3839 (insert (markdown-blockquote-indentation (point)) "> ")
3840 (markdown-ensure-blank-line-after)))
3842 (defun markdown-block-region (beg end prefix)
3843 "Format the region using a block prefix.
3844 Arguments BEG and END specify the beginning and end of the
3845 region. The characters PREFIX will appear at the beginning
3846 of each line."
3847 (save-excursion
3848 (let* ((end-marker (make-marker))
3849 (beg-marker (make-marker)))
3850 ;; Ensure blank line after and remove extra whitespace
3851 (goto-char end)
3852 (skip-syntax-backward "-")
3853 (set-marker end-marker (point))
3854 (delete-horizontal-space)
3855 (markdown-ensure-blank-line-after)
3856 ;; Ensure blank line before and remove extra whitespace
3857 (goto-char beg)
3858 (skip-syntax-forward "-")
3859 (delete-horizontal-space)
3860 (markdown-ensure-blank-line-before)
3861 (set-marker beg-marker (point))
3862 ;; Insert PREFIX before each line
3863 (goto-char beg-marker)
3864 (while (and (< (line-beginning-position) end-marker)
3865 (not (eobp)))
3866 (insert prefix)
3867 (forward-line)))))
3869 (defun markdown-blockquote-region (beg end)
3870 "Blockquote the region.
3871 Arguments BEG and END specify the beginning and end of the region."
3872 (interactive "*r")
3873 (markdown-block-region
3874 beg end (concat (markdown-blockquote-indentation
3875 (max (point-min) (1- beg))) "> ")))
3877 (defun markdown-pre-indentation (loc)
3878 "Return string containing necessary whitespace for a pre block at LOC.
3879 Also see `markdown-blockquote-indentation'."
3880 (save-excursion
3881 (goto-char loc)
3882 (let* ((list-level (length (markdown-calculate-list-levels)))
3883 indent)
3884 (dotimes (_ (1+ list-level) indent)
3885 (setq indent (concat indent " "))))))
3887 (defun markdown-insert-pre ()
3888 "Start a preformatted section (or apply to the region).
3889 If Transient Mark mode is on and a region is active, it is marked
3890 as preformatted text."
3891 (interactive)
3892 (if (markdown-use-region-p)
3893 (markdown-pre-region (region-beginning) (region-end))
3894 (markdown-ensure-blank-line-before)
3895 (insert (markdown-pre-indentation (point)))
3896 (markdown-ensure-blank-line-after)))
3898 (defun markdown-pre-region (beg end)
3899 "Format the region as preformatted text.
3900 Arguments BEG and END specify the beginning and end of the region."
3901 (interactive "*r")
3902 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
3903 (markdown-block-region beg end indent)))
3905 (defun markdown-electric-backquote (arg)
3906 "Insert a backquote.
3907 The numeric prefix argument ARG says how many times to repeat the insertion.
3908 Call `markdown-insert-gfm-code-block' interactively
3909 if three backquotes inserted at the beginning of line."
3910 (interactive "*P")
3911 (self-insert-command (prefix-numeric-value arg))
3912 (when (and markdown-gfm-use-electric-backquote (looking-back "^```" nil))
3913 (replace-match "")
3914 (call-interactively #'markdown-insert-gfm-code-block)))
3916 (defconst markdown-gfm-recognized-languages
3917 ;; to reproduce/update, evaluate the let-form in
3918 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
3919 ;; but with appropriate use of a keyboard macro, indenting and filling it
3920 ;; properly is pretty fast.
3921 '("ABAP" "AGS-Script" "AMPL" "ANTLR" "API-Blueprint" "APL" "ASP" "ATS"
3922 "ActionScript" "Ada" "Agda" "Alloy" "Ant-Build-System" "ApacheConf" "Apex"
3923 "AppleScript" "Arc" "Arduino" "AsciiDoc" "AspectJ" "Assembly" "Augeas"
3924 "AutoHotkey" "AutoIt" "Awk" "Batchfile" "Befunge" "Bison" "BitBake"
3925 "BlitzBasic" "BlitzMax" "Bluespec" "Boo" "Brainfuck" "Brightscript" "Bro" "C#"
3926 "C++" "C-ObjDump" "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "CSS" "Cap'n-Proto"
3927 "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK" "Cirru" "Clarion" "Clean"
3928 "Click" "Clojure" "CoffeeScript" "ColdFusion" "ColdFusion-CFC" "Common-Lisp"
3929 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal" "Cucumber"
3930 "Cuda" "Cycript" "Cython" "D-ObjDump" "DIGITAL-Command-Language" "DM"
3931 "DNS-Zone" "DTrace" "Darcs-Patch" "Dart" "Diff" "Dockerfile" "Dogescript"
3932 "Dylan" "ECL" "ECLiPSe" "Eagle" "Ecere-Projects" "Eiffel" "Elixir" "Elm"
3933 "Emacs-Lisp" "EmberScript" "Erlang" "F#" "FLUX" "FORTRAN" "Factor" "Fancy"
3934 "Fantom" "Filterscript" "Formatted" "Forth" "FreeMarker" "Frege" "G-code"
3935 "GAMS" "GAP" "GAS" "GDScript" "GLSL" "Game-Maker-Language" "Genshi"
3936 "Gentoo-Ebuild" "Gentoo-Eclass" "Gettext-Catalog" "Glyph" "Gnuplot" "Go"
3937 "Golo" "Gosu" "Grace" "Gradle" "Grammatical-Framework"
3938 "Graph-Modeling-Language" "Graphviz-(DOT)" "Groff" "Groovy"
3939 "Groovy-Server-Pages" "HCL" "HTML" "HTML+Django" "HTML+EEX" "HTML+ERB"
3940 "HTML+PHP" "HTTP" "Hack" "Haml" "Handlebars" "Harbour" "Haskell" "Haxe" "Hy"
3941 "HyPhy" "IDL" "IGOR-Pro" "INI" "IRC-log" "Idris" "Inform-7" "Inno-Setup" "Io"
3942 "Ioke" "Isabelle" "Isabelle-ROOT" "JFlex" "JSON" "JSON5" "JSONLD" "JSONiq"
3943 "JSX" "Jade" "Jasmin" "Java" "Java-Server-Pages" "JavaScript" "Julia"
3944 "Jupyter-Notebook" "KRL" "KiCad" "Kit" "Kotlin" "LFE" "LLVM" "LOLCODE" "LSL"
3945 "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex" "LilyPond" "Limbo"
3946 "Linker-Script" "Linux-Kernel-Module" "Liquid" "Literate-Agda"
3947 "Literate-CoffeeScript" "Literate-Haskell" "LiveScript" "Logos" "Logtalk"
3948 "LookML" "LoomScript" "Lua" "MAXScript" "MTML" "MUF" "Makefile" "Mako"
3949 "Markdown" "Mask" "Mathematica" "Matlab" "Maven-POM" "Max" "MediaWiki"
3950 "Mercury" "Metal" "MiniD" "Mirah" "Modelica" "Modula-2"
3951 "Module-Management-System" "Monkey" "Moocode" "MoonScript" "Myghty" "NCL" "NL"
3952 "NSIS" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo" "NewLisp" "Nginx" "Nimrod"
3953 "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml" "ObjDump" "Objective-C"
3954 "Objective-C++" "Objective-J" "Omgrofl" "Opa" "Opal" "OpenCL" "OpenEdge-ABL"
3955 "OpenSCAD" "Org" "Ox" "Oxygene" "Oz" "PAWN" "PHP" "PLSQL" "PLpgSQL" "Pan"
3956 "Papyrus" "Parrot" "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal"
3957 "Perl" "Perl6" "Pickle" "PicoLisp" "PigLatin" "Pike" "Pod" "PogoScript" "Pony"
3958 "PostScript" "PowerShell" "Processing" "Prolog" "Propeller-Spin"
3959 "Protocol-Buffer" "Public-Key" "Puppet" "Pure-Data" "PureBasic" "PureScript"
3960 "Python" "Python-traceback" "QML" "QMake" "RAML" "RDoc" "REALbasic" "RHTML"
3961 "RMarkdown" "Racket" "Ragel-in-Ruby-Host" "Raw-token-data" "Rebol" "Red"
3962 "Redcode" "Ren'Py" "RenderScript" "RobotFramework" "Rouge" "Ruby" "Rust" "SAS"
3963 "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL" "STON" "SVG" "Sage" "SaltStack"
3964 "Sass" "Scala" "Scaml" "Scheme" "Scilab" "Self" "Shell" "ShellSession" "Shen"
3965 "Slash" "Slim" "Smali" "Smalltalk" "Smarty" "SourcePawn" "Squirrel" "Stan"
3966 "Standard-ML" "Stata" "Stylus" "SuperCollider" "Swift" "SystemVerilog" "TOML"
3967 "TXL" "Tcl" "Tcsh" "TeX" "Tea" "Text" "Textile" "Thrift" "Turing" "Turtle"
3968 "Twig" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset" "UnrealScript"
3969 "UrWeb" "VCL" "VHDL" "Vala" "Verilog" "VimL" "Visual-Basic" "Volt" "Vue"
3970 "Web-Ontology-Language" "WebIDL" "X10" "XC" "XML" "XPages" "XProc" "XQuery"
3971 "XS" "XSLT" "Xojo" "Xtend" "YAML" "Yacc" "Zephir" "Zimpl" "desktop" "eC" "edn"
3972 "fish" "mupad" "nesC" "ooc" "reStructuredText" "wisp" "xBase")
3973 "Language specifiers recognized by GitHub's syntax highlighting features.")
3975 (defvar markdown-gfm-used-languages nil
3976 "Language names used in GFM code blocks.")
3977 (make-variable-buffer-local 'markdown-gfm-used-languages)
3979 (defun markdown-trim-whitespace (str)
3980 (markdown-replace-regexp-in-string
3981 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str))
3983 (defun markdown-clean-language-string (str)
3984 (markdown-replace-regexp-in-string
3985 "{\\.?\\|}" "" (markdown-trim-whitespace str)))
3987 (defun markdown-validate-language-string (widget)
3988 (let ((str (widget-value widget)))
3989 (unless (string= str (markdown-clean-language-string str))
3990 (widget-put widget :error (format "Invalid language spec: '%s'" str))
3991 widget)))
3993 (defun markdown-gfm-get-corpus ()
3994 "Create corpus of recognized GFM code block languages for the given buffer."
3995 (let ((given-corpus (append markdown-gfm-additional-languages
3996 markdown-gfm-recognized-languages)))
3997 (append
3998 markdown-gfm-used-languages
3999 (if markdown-gfm-downcase-languages (cl-mapcar #'downcase given-corpus)
4000 given-corpus))))
4002 (defun markdown-gfm-add-used-language (lang)
4003 "Clean LANG and add to list of used languages."
4004 (setq markdown-gfm-used-languages
4005 (cons lang (remove lang markdown-gfm-used-languages))))
4007 (defun markdown-insert-gfm-code-block (&optional lang)
4008 "Insert GFM code block for language LANG.
4009 If LANG is nil, the language will be queried from user. If a
4010 region is active, wrap this region with the markup instead. If
4011 the region boundaries are not on empty lines, these are added
4012 automatically in order to have the correct markup."
4013 (interactive
4014 (list (let ((completion-ignore-case nil))
4015 (condition-case nil
4016 (markdown-clean-language-string
4017 (completing-read
4018 "Programming language: "
4019 (markdown-gfm-get-corpus)
4020 nil 'confirm (car markdown-gfm-used-languages)
4021 'markdown-gfm-language-history))
4022 (quit "")))))
4023 (unless (string= lang "") (markdown-gfm-add-used-language lang))
4024 (when (> (length lang) 0) (setq lang (concat " " lang)))
4025 (if (markdown-use-region-p)
4026 (let ((b (region-beginning)) (e (region-end)))
4027 (goto-char e)
4028 ;; if we're on a blank line, don't newline, otherwise the ```
4029 ;; should go on its own line
4030 (unless (looking-back "\n" nil)
4031 (newline))
4032 (insert "```")
4033 (markdown-ensure-blank-line-after)
4034 (goto-char b)
4035 ;; if we're on a blank line, insert the quotes here, otherwise
4036 ;; add a new line first
4037 (unless (looking-at-p "\n")
4038 (newline)
4039 (forward-line -1))
4040 (markdown-ensure-blank-line-before)
4041 (insert "```" lang))
4042 (markdown-ensure-blank-line-before)
4043 (insert "```" lang "\n\n```")
4044 (markdown-ensure-blank-line-after)
4045 (forward-line -1)))
4047 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer)
4048 (with-current-buffer (or buffer (current-buffer))
4049 (save-excursion
4050 (goto-char (point-min))
4051 (cl-loop
4052 with prop = 'markdown-gfm-block-begin
4053 for pos-prop = (markdown-find-next-prop prop)
4054 while pos-prop
4055 for lang = (progn
4056 (goto-char (car pos-prop))
4057 (save-match-data
4058 (set-match-data (get-text-property (point) prop))
4059 ;; Note: Hard-coded group number assumes tilde
4060 ;; and GFM fenced code regexp groups agree.
4061 (when (and (match-beginning 3) (match-end 3))
4062 (buffer-substring-no-properties
4063 (match-beginning 3) (match-end 3)))))
4064 do (progn (when lang (markdown-gfm-add-used-language lang))
4065 (goto-char (next-single-property-change (point) prop)))))))
4068 ;;; Footnotes ==================================================================
4070 (defun markdown-footnote-counter-inc ()
4071 "Increment `markdown-footnote-counter' and return the new value."
4072 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
4073 (save-excursion
4074 (goto-char (point-min))
4075 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
4076 (point-max) t)
4077 (let ((fn (string-to-number (match-string 1))))
4078 (when (> fn markdown-footnote-counter)
4079 (setq markdown-footnote-counter fn))))))
4080 (cl-incf markdown-footnote-counter))
4082 (defun markdown-insert-footnote ()
4083 "Insert footnote with a new number and move point to footnote definition."
4084 (interactive)
4085 (let ((fn (markdown-footnote-counter-inc)))
4086 (insert (format "[^%d]" fn))
4087 (markdown-footnote-text-find-new-location)
4088 (markdown-ensure-blank-line-before)
4089 (unless (markdown-cur-line-blank-p)
4090 (insert "\n"))
4091 (insert (format "[^%d]: " fn))
4092 (markdown-ensure-blank-line-after)))
4094 (defun markdown-footnote-text-find-new-location ()
4095 "Position the cursor at the proper location for a new footnote text."
4096 (cond
4097 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
4098 ((eq markdown-footnote-location 'immediately) (markdown-end-of-text-block))
4099 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
4101 (defun markdown-footnote-kill ()
4102 "Kill the footnote at point.
4103 The footnote text is killed (and added to the kill ring), the
4104 footnote marker is deleted. Point has to be either at the
4105 footnote marker or in the footnote text."
4106 (interactive)
4107 (let ((marker-pos nil)
4108 (skip-deleting-marker nil)
4109 (starting-footnote-text-positions
4110 (markdown-footnote-text-positions)))
4111 (when starting-footnote-text-positions
4112 ;; We're starting in footnote text, so mark our return position and jump
4113 ;; to the marker if possible.
4114 (let ((marker-pos (markdown-footnote-find-marker
4115 (cl-first starting-footnote-text-positions))))
4116 (if marker-pos
4117 (goto-char (1- marker-pos))
4118 ;; If there isn't a marker, we still want to kill the text.
4119 (setq skip-deleting-marker t))))
4120 ;; Either we didn't start in the text, or we started in the text and jumped
4121 ;; to the marker. We want to assume we're at the marker now and error if
4122 ;; we're not.
4123 (unless skip-deleting-marker
4124 (let ((marker (markdown-footnote-delete-marker)))
4125 (unless marker
4126 (error "Not at a footnote"))
4127 ;; Even if we knew the text position before, it changed when we deleted
4128 ;; the label.
4129 (setq marker-pos (cl-second marker))
4130 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker))))
4131 (unless new-text-pos
4132 (error "No text for footnote `%s'" (cl-first marker)))
4133 (goto-char new-text-pos))))
4134 (let ((pos (markdown-footnote-kill-text)))
4135 (goto-char (if starting-footnote-text-positions
4137 marker-pos)))))
4139 (defun markdown-footnote-delete-marker ()
4140 "Delete a footnote marker at point.
4141 Returns a list (ID START) containing the footnote ID and the
4142 start position of the marker before deletion. If no footnote
4143 marker was deleted, this function returns NIL."
4144 (let ((marker (markdown-footnote-marker-positions)))
4145 (when marker
4146 (delete-region (cl-second marker) (cl-third marker))
4147 (butlast marker))))
4149 (defun markdown-footnote-kill-text ()
4150 "Kill footnote text at point.
4151 Returns the start position of the footnote text before deletion,
4152 or NIL if point was not inside a footnote text.
4154 The killed text is placed in the kill ring (without the footnote
4155 number)."
4156 (let ((fn (markdown-footnote-text-positions)))
4157 (when fn
4158 (let ((text (delete-and-extract-region (cl-second fn) (cl-third fn))))
4159 (string-match (concat "\\[\\" (cl-first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
4160 (kill-new (match-string 1 text))
4161 (when (and (markdown-cur-line-blank-p)
4162 (markdown-prev-line-blank-p)
4163 (not (bobp)))
4164 (delete-region (1- (point)) (point)))
4165 (cl-second fn)))))
4167 (defun markdown-footnote-goto-text ()
4168 "Jump to the text of the footnote at point."
4169 (interactive)
4170 (let ((fn (car (markdown-footnote-marker-positions))))
4171 (unless fn
4172 (error "Not at a footnote marker"))
4173 (let ((new-pos (markdown-footnote-find-text fn)))
4174 (unless new-pos
4175 (error "No definition found for footnote `%s'" fn))
4176 (goto-char new-pos))))
4178 (defun markdown-footnote-return ()
4179 "Return from a footnote to its footnote number in the main text."
4180 (interactive)
4181 (let ((fn (save-excursion
4182 (car (markdown-footnote-text-positions)))))
4183 (unless fn
4184 (error "Not in a footnote"))
4185 (let ((new-pos (markdown-footnote-find-marker fn)))
4186 (unless new-pos
4187 (error "Footnote marker `%s' not found" fn))
4188 (goto-char new-pos))))
4190 (defun markdown-footnote-find-marker (id)
4191 "Find the location of the footnote marker with ID.
4192 The actual buffer position returned is the position directly
4193 following the marker's closing bracket. If no marker is found,
4194 NIL is returned."
4195 (save-excursion
4196 (goto-char (point-min))
4197 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
4198 (skip-chars-backward "^]")
4199 (point))))
4201 (defun markdown-footnote-find-text (id)
4202 "Find the location of the text of footnote ID.
4203 The actual buffer position returned is the position of the first
4204 character of the text, after the footnote's identifier. If no
4205 footnote text is found, NIL is returned."
4206 (save-excursion
4207 (goto-char (point-min))
4208 (when (re-search-forward (concat "^\\[" id "\\]:") nil t)
4209 (skip-chars-forward "[ \t]")
4210 (point))))
4212 (defun markdown-footnote-marker-positions ()
4213 "Return the position and ID of the footnote marker point is on.
4214 The return value is a list (ID START END). If point is not on a
4215 footnote, NIL is returned."
4216 ;; first make sure we're at a footnote marker
4217 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
4218 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
4219 (save-excursion
4220 ;; move point between [ and ^:
4221 (if (looking-at-p "\\[")
4222 (forward-char 1)
4223 (skip-chars-backward "^["))
4224 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
4225 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
4227 (defun markdown-footnote-text-positions ()
4228 "Return the start and end positions of the footnote text point is in.
4229 The exact return value is a list of three elements: (ID START END).
4230 The start position is the position of the opening bracket
4231 of the footnote id. The end position is directly after the
4232 newline that ends the footnote. If point is not in a footnote,
4233 NIL is returned instead."
4234 (save-excursion
4235 (let (result)
4236 (move-beginning-of-line 1)
4237 ;; Try to find the label. If we haven't found the label and we're at a blank
4238 ;; or indented line, back up if possible.
4239 (while (and
4240 (not (and (looking-at markdown-regex-footnote-definition)
4241 (setq result (list (match-string 1) (point)))))
4242 (and (not (bobp))
4243 (or (markdown-cur-line-blank-p)
4244 (>= (current-indentation) 4))))
4245 (forward-line -1))
4246 (when result
4247 ;; Advance if there is a next line that is either blank or indented.
4248 ;; (Need to check if we're on the last line, because
4249 ;; markdown-next-line-blank-p returns true for last line in buffer.)
4250 (while (and (/= (line-end-position) (point-max))
4251 (or (markdown-next-line-blank-p)
4252 (>= (markdown-next-line-indent) 4)))
4253 (forward-line))
4254 ;; Move back while the current line is blank.
4255 (while (markdown-cur-line-blank-p)
4256 (forward-line -1))
4257 ;; Advance to capture this line and a single trailing newline (if there
4258 ;; is one).
4259 (forward-line)
4260 (append result (list (point)))))))
4263 ;;; Element Removal ===========================================================
4265 (defun markdown-kill-thing-at-point ()
4266 "Kill thing at point and add important text, without markup, to kill ring.
4267 Possible things to kill include (roughly in order of precedence):
4268 inline code, headers, horizonal rules, links (add link text to
4269 kill ring), images (add alt text to kill ring), angle uri, email
4270 addresses, bold, italics, reference definition (add URI to kill
4271 ring), footnote markers and text (kill both marker and text, add
4272 text to kill ring), and list items."
4273 (interactive "*")
4274 (let (val)
4275 (cond
4276 ;; Inline code
4277 ((markdown-inline-code-at-point)
4278 (kill-new (match-string 2))
4279 (delete-region (match-beginning 0) (match-end 0)))
4280 ;; ATX header
4281 ((thing-at-point-looking-at markdown-regex-header-atx)
4282 (kill-new (match-string 2))
4283 (delete-region (match-beginning 0) (match-end 0)))
4284 ;; Setext header
4285 ((thing-at-point-looking-at markdown-regex-header-setext)
4286 (kill-new (match-string 1))
4287 (delete-region (match-beginning 0) (match-end 0)))
4288 ;; Horizonal rule
4289 ((thing-at-point-looking-at markdown-regex-hr)
4290 (kill-new (match-string 0))
4291 (delete-region (match-beginning 0) (match-end 0)))
4292 ;; Inline link or image (add link or alt text to kill ring)
4293 ((thing-at-point-looking-at markdown-regex-link-inline)
4294 (kill-new (match-string 3))
4295 (delete-region (match-beginning 0) (match-end 0)))
4296 ;; Reference link or image (add link or alt text to kill ring)
4297 ((thing-at-point-looking-at markdown-regex-link-reference)
4298 (kill-new (match-string 3))
4299 (delete-region (match-beginning 0) (match-end 0)))
4300 ;; Angle URI (add URL to kill ring)
4301 ((thing-at-point-looking-at markdown-regex-angle-uri)
4302 (kill-new (match-string 2))
4303 (delete-region (match-beginning 0) (match-end 0)))
4304 ;; Email address in angle brackets (add email address to kill ring)
4305 ((thing-at-point-looking-at markdown-regex-email)
4306 (kill-new (match-string 1))
4307 (delete-region (match-beginning 0) (match-end 0)))
4308 ;; Wiki link (add alias text to kill ring)
4309 ((and markdown-enable-wiki-links
4310 (thing-at-point-looking-at markdown-regex-wiki-link))
4311 (kill-new (markdown-wiki-link-alias))
4312 (delete-region (match-beginning 1) (match-end 1)))
4313 ;; Bold
4314 ((thing-at-point-looking-at markdown-regex-bold)
4315 (kill-new (match-string 4))
4316 (delete-region (match-beginning 2) (match-end 2)))
4317 ;; Italics
4318 ((thing-at-point-looking-at markdown-regex-italic)
4319 (kill-new (match-string 3))
4320 (delete-region (match-beginning 1) (match-end 1)))
4321 ;; Strikethrough
4322 ((thing-at-point-looking-at markdown-regex-strike-through)
4323 (kill-new (match-string 4))
4324 (delete-region (match-beginning 2) (match-end 2)))
4325 ;; Footnote marker (add footnote text to kill ring)
4326 ((thing-at-point-looking-at markdown-regex-footnote)
4327 (markdown-footnote-kill))
4328 ;; Footnote text (add footnote text to kill ring)
4329 ((setq val (markdown-footnote-text-positions))
4330 (markdown-footnote-kill))
4331 ;; Reference definition (add URL to kill ring)
4332 ((thing-at-point-looking-at markdown-regex-reference-definition)
4333 (kill-new (match-string 5))
4334 (delete-region (match-beginning 0) (match-end 0)))
4335 ;; List item
4336 ((setq val (markdown-cur-list-item-bounds))
4337 (kill-new (delete-and-extract-region (cl-first val) (cl-second val))))
4339 (error "Nothing found at point to kill")))))
4342 ;;; Indentation ====================================================================
4344 (defun markdown-indent-find-next-position (cur-pos positions)
4345 "Return the position after the index of CUR-POS in POSITIONS.
4346 Positions are calculated by `markdown-calc-indents'."
4347 (while (and positions
4348 (not (equal cur-pos (car positions))))
4349 (setq positions (cdr positions)))
4350 (or (cadr positions) 0))
4352 (defun markdown-exdent-find-next-position (cur-pos positions)
4353 "Return the maximal element that precedes CUR-POS from POSITIONS.
4354 Positions are calculated by `markdown-calc-indents'."
4355 (let ((result 0))
4356 (dolist (i positions)
4357 (when (< i cur-pos)
4358 (setq result (max result i))))
4359 result))
4361 (defun markdown-indent-line ()
4362 "Indent the current line using some heuristics.
4363 If the _previous_ command was either `markdown-enter-key' or
4364 `markdown-cycle', then we should cycle to the next
4365 reasonable indentation position. Otherwise, we could have been
4366 called directly by `markdown-enter-key', by an initial call of
4367 `markdown-cycle', or indirectly by `auto-fill-mode'. In
4368 these cases, indent to the default position.
4369 Positions are calculated by `markdown-calc-indents'."
4370 (interactive)
4371 (let ((positions (markdown-calc-indents))
4372 (cursor-pos (current-column))
4373 (_ (back-to-indentation))
4374 (cur-pos (current-column)))
4375 (if (not (equal this-command 'markdown-cycle))
4376 (indent-line-to (car positions))
4377 (setq positions (sort (delete-dups positions) '<))
4378 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions))
4379 (new-cursor-pos
4380 (if (< cur-pos next-pos)
4381 (+ cursor-pos (- next-pos cur-pos))
4382 (- cursor-pos cur-pos))))
4383 (indent-line-to next-pos)
4384 (move-to-column new-cursor-pos)))))
4386 (defun markdown-calc-indents ()
4387 "Return a list of indentation columns to cycle through.
4388 The first element in the returned list should be considered the
4389 default indentation level. This function does not worry about
4390 duplicate positions, which are handled up by calling functions."
4391 (let (pos prev-line-pos positions)
4393 ;; Indentation of previous line
4394 (setq prev-line-pos (markdown-prev-line-indent))
4395 (setq positions (cons prev-line-pos positions))
4397 ;; Indentation of previous non-list-marker text
4398 (when (setq pos (markdown-prev-non-list-indent))
4399 (setq positions (cons pos positions)))
4401 ;; Indentation required for a pre block in current context
4402 (setq pos (length (markdown-pre-indentation (point))))
4403 (setq positions (cons pos positions))
4405 ;; Indentation of the previous line + tab-width
4406 (if prev-line-pos
4407 (setq positions (cons (+ prev-line-pos tab-width) positions))
4408 (setq positions (cons tab-width positions)))
4410 ;; Indentation of the previous line - tab-width
4411 (if (and prev-line-pos (> prev-line-pos tab-width))
4412 (setq positions (cons (- prev-line-pos tab-width) positions)))
4414 ;; Indentation of all preceeding list markers (when in a list)
4415 (when (setq pos (markdown-calculate-list-levels))
4416 (setq positions (append pos positions)))
4418 ;; First column
4419 (setq positions (cons 0 positions))
4421 ;; Return reversed list
4422 (reverse positions)))
4424 (defun markdown-enter-key ()
4425 "Handle RET according to customized settings.
4426 When `markdown-indent-on-enter' is nil, this is equivalent to
4427 `newline'. Otherwise, indent following RET and when the point is
4428 in a list item, start a new item with the same indentation. If
4429 the point is in an empty list item, remove it."
4430 (interactive)
4431 (if (not markdown-indent-on-enter)
4432 (newline)
4433 (let ((bounds (markdown-cur-list-item-bounds)))
4434 (if bounds
4435 (let ((beg (cl-first bounds))
4436 (end (cl-second bounds))
4437 (length (cl-fourth bounds)))
4438 ;; Point is in a list item
4439 (if (= (- end beg) length)
4440 ;; Delete blank list
4441 (progn
4442 (delete-region beg end)
4443 (newline)
4444 (markdown-indent-line))
4445 (call-interactively #'markdown-insert-list-item)))
4446 ;; Point is not in a list
4447 (newline)
4448 (markdown-indent-line)))))
4450 (defun markdown-exdent-or-delete (arg)
4451 "Handle BACKSPACE by cycling through indentation points.
4452 When BACKSPACE is pressed, if there is only whitespace
4453 before the current point, then exdent the line one level.
4454 Otherwise, do normal delete by repeating
4455 `backward-delete-char-untabify' ARG times."
4456 (interactive "*p")
4457 (if (use-region-p)
4458 (backward-delete-char-untabify arg)
4459 (let ((cur-pos (current-column))
4460 (start-of-indention (save-excursion
4461 (back-to-indentation)
4462 (current-column)))
4463 (positions (markdown-calc-indents)))
4464 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
4465 (indent-line-to (markdown-exdent-find-next-position cur-pos positions))
4466 (backward-delete-char-untabify arg)))))
4468 (defun markdown-find-leftmost-column (beg end)
4469 "Find the leftmost column in the region from BEG to END."
4470 (let ((mincol 1000))
4471 (save-excursion
4472 (goto-char beg)
4473 (while (< (point) end)
4474 (back-to-indentation)
4475 (unless (looking-at-p "[ \t]*$")
4476 (setq mincol (min mincol (current-column))))
4477 (forward-line 1)
4479 mincol))
4481 (defun markdown-indent-region (beg end arg)
4482 "Indent the region from BEG to END using some heuristics.
4483 When ARG is non-nil, exdent the region instead.
4484 See `markdown-indent-line' and `markdown-indent-line'."
4485 (interactive "*r\nP")
4486 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
4487 (leftmostcol (markdown-find-leftmost-column beg end))
4488 (next-pos (if arg
4489 (markdown-exdent-find-next-position leftmostcol positions)
4490 (markdown-indent-find-next-position leftmostcol positions))))
4491 (indent-rigidly beg end (- next-pos leftmostcol))
4492 (setq deactivate-mark nil)))
4494 (defun markdown-exdent-region (beg end)
4495 "Call `markdown-indent-region' on region from BEG to END with prefix."
4496 (interactive "*r")
4497 (markdown-indent-region beg end t))
4500 ;;; Markup Completion =========================================================
4502 (defconst markdown-complete-alist
4503 '((markdown-regex-header-atx . markdown-complete-atx)
4504 (markdown-regex-header-setext . markdown-complete-setext)
4505 (markdown-regex-hr . markdown-complete-hr))
4506 "Association list of form (regexp . function) for markup completion.")
4508 (defun markdown-incomplete-atx-p ()
4509 "Return t if ATX header markup is incomplete and nil otherwise.
4510 Assumes match data is available for `markdown-regex-header-atx'.
4511 Checks that the number of trailing hash marks equals the number of leading
4512 hash marks, that there is only a single space before and after the text,
4513 and that there is no extraneous whitespace in the text."
4515 ;; Number of starting and ending hash marks differs
4516 (not (= (length (match-string 1)) (length (match-string 3))))
4517 ;; When the header text is not empty...
4518 (and (> (length (match-string 2)) 0)
4519 ;; ...if there are extra leading, trailing, or interior spaces
4520 (or (not (= (match-beginning 2) (1+ (match-end 1))))
4521 (not (= (match-beginning 3) (1+ (match-end 2))))
4522 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
4523 ;; When the header text is empty...
4524 (and (= (length (match-string 2)) 0)
4525 ;; ...if there are too many or too few spaces
4526 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
4528 (defun markdown-complete-atx ()
4529 "Complete and normalize ATX headers.
4530 Add or remove hash marks to the end of the header to match the
4531 beginning. Ensure that there is only a single space between hash
4532 marks and header text. Removes extraneous whitespace from header text.
4533 Assumes match data is available for `markdown-regex-header-atx'.
4534 Return nil if markup was complete and non-nil if markup was completed."
4535 (when (markdown-incomplete-atx-p)
4536 (let* ((new-marker (make-marker))
4537 (new-marker (set-marker new-marker (match-end 2))))
4538 ;; Hash marks and spacing at end
4539 (goto-char (match-end 2))
4540 (delete-region (match-end 2) (match-end 3))
4541 (insert " " (match-string 1))
4542 ;; Remove extraneous whitespace from title
4543 (replace-match (markdown-compress-whitespace-string (match-string 2))
4544 t t nil 2)
4545 ;; Spacing at beginning
4546 (goto-char (match-end 1))
4547 (delete-region (match-end 1) (match-beginning 2))
4548 (insert " ")
4549 ;; Leave point at end of text
4550 (goto-char new-marker))))
4552 (defun markdown-incomplete-setext-p ()
4553 "Return t if setext header markup is incomplete and nil otherwise.
4554 Assumes match data is available for `markdown-regex-header-setext'.
4555 Checks that length of underline matches text and that there is no
4556 extraneous whitespace in the text."
4557 (or (not (= (length (match-string 1)) (length (match-string 2))))
4558 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
4560 (defun markdown-complete-setext ()
4561 "Complete and normalize setext headers.
4562 Add or remove underline characters to match length of header
4563 text. Removes extraneous whitespace from header text. Assumes
4564 match data is available for `markdown-regex-header-setext'.
4565 Return nil if markup was complete and non-nil if markup was completed."
4566 (when (markdown-incomplete-setext-p)
4567 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
4568 (char (char-after (match-beginning 2)))
4569 (level (if (char-equal char ?-) 2 1)))
4570 (goto-char (match-beginning 0))
4571 (delete-region (match-beginning 0) (match-end 0))
4572 (markdown-insert-header level text t)
4573 t)))
4575 (defun markdown-incomplete-hr-p ()
4576 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
4577 Assumes match data is available for `markdown-regex-hr'."
4578 (not (member (match-string 0) markdown-hr-strings)))
4580 (defun markdown-complete-hr ()
4581 "Complete horizontal rules.
4582 If horizontal rule string is a member of `markdown-hr-strings',
4583 do nothing. Otherwise, replace with the car of
4584 `markdown-hr-strings'.
4585 Assumes match data is available for `markdown-regex-hr'.
4586 Return nil if markup was complete and non-nil if markup was completed."
4587 (when (markdown-incomplete-hr-p)
4588 (replace-match (car markdown-hr-strings))
4591 (defun markdown-complete ()
4592 "Complete markup of object near point or in region when active.
4593 Handle all objects in `markdown-complete-alist', in order.
4594 See `markdown-complete-at-point' and `markdown-complete-region'."
4595 (interactive "*")
4596 (if (markdown-use-region-p)
4597 (markdown-complete-region (region-beginning) (region-end))
4598 (markdown-complete-at-point)))
4600 (defun markdown-complete-at-point ()
4601 "Complete markup of object near point.
4602 Handle all elements of `markdown-complete-alist' in order."
4603 (interactive "*")
4604 (let ((list markdown-complete-alist) found changed)
4605 (while list
4606 (let ((regexp (eval (caar list)))
4607 (function (cdar list)))
4608 (setq list (cdr list))
4609 (when (thing-at-point-looking-at regexp)
4610 (setq found t)
4611 (setq changed (funcall function))
4612 (setq list nil))))
4613 (if found
4614 (or changed (error "Markup at point is complete"))
4615 (error "Nothing to complete at point"))))
4617 (defun markdown-complete-region (beg end)
4618 "Complete markup of objects in region from BEG to END.
4619 Handle all objects in `markdown-complete-alist', in order. Each
4620 match is checked to ensure that a previous regexp does not also
4621 match."
4622 (interactive "*r")
4623 (let ((end-marker (set-marker (make-marker) end))
4624 previous)
4625 (dolist (element markdown-complete-alist)
4626 (let ((regexp (eval (car element)))
4627 (function (cdr element)))
4628 (goto-char beg)
4629 (while (re-search-forward regexp end-marker 'limit)
4630 (when (match-string 0)
4631 ;; Make sure this is not a match for any of the preceding regexps.
4632 ;; This prevents mistaking an HR for a Setext subheading.
4633 (let (match)
4634 (save-match-data
4635 (dolist (prev-regexp previous)
4636 (or match (setq match (looking-back prev-regexp nil)))))
4637 (unless match
4638 (save-excursion (funcall function))))))
4639 (cl-pushnew regexp previous :test #'equal)))
4640 previous))
4642 (defun markdown-complete-buffer ()
4643 "Complete markup for all objects in the current buffer."
4644 (interactive "*")
4645 (markdown-complete-region (point-min) (point-max)))
4648 ;;; Markup Cycling ============================================================
4650 (defun markdown-cycle-atx (arg &optional remove)
4651 "Cycle ATX header markup.
4652 Promote header (decrease level) when ARG is 1 and demote
4653 header (increase level) if arg is -1. When REMOVE is non-nil,
4654 remove the header when the level reaches zero and stop cycling
4655 when it reaches six. Otherwise, perform a proper cycling through
4656 levels one through six. Assumes match data is available for
4657 `markdown-regex-header-atx'."
4658 (let* ((old-level (length (match-string 1)))
4659 (new-level (+ old-level arg))
4660 (text (match-string 2)))
4661 (when (not remove)
4662 (setq new-level (% new-level 6))
4663 (setq new-level (cond ((= new-level 0) 6)
4664 ((< new-level 0) (+ new-level 6))
4665 (t new-level))))
4666 (cond
4667 ((= new-level 0)
4668 (markdown-unwrap-thing-at-point nil 0 2))
4669 ((<= new-level 6)
4670 (goto-char (match-beginning 0))
4671 (delete-region (match-beginning 0) (match-end 0))
4672 (markdown-insert-header new-level text nil)))))
4674 (defun markdown-cycle-setext (arg &optional remove)
4675 "Cycle setext header markup.
4676 Promote header (increase level) when ARG is 1 and demote
4677 header (decrease level or remove) if arg is -1. When demoting a
4678 level-two setext header, replace with a level-three atx header.
4679 When REMOVE is non-nil, remove the header when the level reaches
4680 zero. Otherwise, cycle back to a level six atx header. Assumes
4681 match data is available for `markdown-regex-header-setext'."
4682 (let* ((char (char-after (match-beginning 2)))
4683 (old-level (if (char-equal char ?=) 1 2))
4684 (new-level (+ old-level arg)))
4685 (when (and (not remove) (= new-level 0))
4686 (setq new-level 6))
4687 (cond
4688 ((= new-level 0)
4689 (markdown-unwrap-thing-at-point nil 0 1))
4690 ((<= new-level 2)
4691 (markdown-insert-header new-level nil t))
4692 ((<= new-level 6)
4693 (markdown-insert-header new-level nil nil)))))
4695 (defun markdown-cycle-hr (arg &optional remove)
4696 "Cycle string used for horizontal rule from `markdown-hr-strings'.
4697 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
4698 backwards (promote). When REMOVE is non-nil, remove the hr instead
4699 of cycling when the end of the list is reached.
4700 Assumes match data is available for `markdown-regex-hr'."
4701 (let* ((strings (if (= arg -1)
4702 (reverse markdown-hr-strings)
4703 markdown-hr-strings))
4704 (tail (member (match-string 0) strings))
4705 (new (or (cadr tail)
4706 (if remove
4707 (if (= arg 1)
4709 (car tail))
4710 (car strings)))))
4711 (replace-match new)))
4713 (defun markdown-cycle-bold ()
4714 "Cycle bold markup between underscores and asterisks.
4715 Assumes match data is available for `markdown-regex-bold'."
4716 (save-excursion
4717 (let* ((old-delim (match-string 3))
4718 (new-delim (if (string-equal old-delim "**") "__" "**")))
4719 (replace-match new-delim t t nil 3)
4720 (replace-match new-delim t t nil 5))))
4722 (defun markdown-cycle-italic ()
4723 "Cycle italic markup between underscores and asterisks.
4724 Assumes match data is available for `markdown-regex-italic'."
4725 (save-excursion
4726 (let* ((old-delim (match-string 2))
4727 (new-delim (if (string-equal old-delim "*") "_" "*")))
4728 (replace-match new-delim t t nil 2)
4729 (replace-match new-delim t t nil 4))))
4732 ;;; Keymap ====================================================================
4734 (defvar markdown-mode-map
4735 (let ((map (make-keymap)))
4736 ;; Element insertion
4737 (define-key map "\C-c\C-al" 'markdown-insert-inline-link-dwim)
4738 (define-key map "\C-c\C-aL" 'markdown-insert-reference-link-dwim)
4739 (define-key map "\C-c\C-au" 'markdown-insert-uri)
4740 (define-key map "\C-c\C-af" 'markdown-insert-footnote)
4741 (define-key map "\C-c\C-aw" 'markdown-insert-wiki-link)
4742 (define-key map "\C-c\C-ii" 'markdown-insert-image)
4743 (define-key map "\C-c\C-iI" 'markdown-insert-reference-image)
4744 (define-key map "\C-c\C-i\C-t" 'markdown-toggle-inline-images)
4745 (define-key map "\C-c\C-th" 'markdown-insert-header-dwim)
4746 (define-key map "\C-c\C-tH" 'markdown-insert-header-setext-dwim)
4747 (define-key map "\C-c\C-t1" 'markdown-insert-header-atx-1)
4748 (define-key map "\C-c\C-t2" 'markdown-insert-header-atx-2)
4749 (define-key map "\C-c\C-t3" 'markdown-insert-header-atx-3)
4750 (define-key map "\C-c\C-t4" 'markdown-insert-header-atx-4)
4751 (define-key map "\C-c\C-t5" 'markdown-insert-header-atx-5)
4752 (define-key map "\C-c\C-t6" 'markdown-insert-header-atx-6)
4753 (define-key map "\C-c\C-t!" 'markdown-insert-header-setext-1)
4754 (define-key map "\C-c\C-t@" 'markdown-insert-header-setext-2)
4755 (define-key map "\C-c\C-ss" 'markdown-insert-bold)
4756 (define-key map "\C-c\C-se" 'markdown-insert-italic)
4757 (define-key map "\C-c\C-sc" 'markdown-insert-code)
4758 (define-key map "\C-c\C-sb" 'markdown-insert-blockquote)
4759 (define-key map "\C-c\C-sk" 'markdown-insert-kbd)
4760 (define-key map "\C-c\C-s\C-b" 'markdown-blockquote-region)
4761 (define-key map "\C-c\C-sp" 'markdown-insert-pre)
4762 (define-key map "\C-c\C-s\C-p" 'markdown-pre-region)
4763 (define-key map "\C-c\C-sP" 'markdown-insert-gfm-code-block)
4764 (define-key map "\C-c-" 'markdown-insert-hr)
4765 ;; Element insertion (deprecated)
4766 (define-key map "\C-c\C-ar" 'markdown-insert-reference-link-dwim)
4767 (define-key map "\C-c\C-tt" 'markdown-insert-header-setext-1)
4768 (define-key map "\C-c\C-ts" 'markdown-insert-header-setext-2)
4769 ;; Element removal
4770 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
4771 ;; Promotion, Demotion, Completion, and Cycling
4772 (define-key map (kbd "C-c C--") 'markdown-promote)
4773 (define-key map (kbd "C-c C-=") 'markdown-demote)
4774 (define-key map (kbd "C-c C-]") 'markdown-complete)
4775 ;; Following and Jumping
4776 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
4777 (define-key map (kbd "C-c C-l") 'markdown-jump)
4778 ;; Indentation
4779 (define-key map (kbd "C-m") 'markdown-enter-key)
4780 (define-key map (kbd "DEL") 'markdown-exdent-or-delete)
4781 (define-key map (kbd "C-c >") 'markdown-indent-region)
4782 (define-key map (kbd "C-c <") 'markdown-exdent-region)
4783 ;; Visibility cycling
4784 (define-key map (kbd "TAB") 'markdown-cycle)
4785 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
4786 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
4787 (define-key map (kbd "<backtab>") 'markdown-shifttab)
4788 ;; Header navigation
4789 (define-key map (kbd "C-c C-n") 'markdown-next-visible-heading)
4790 (define-key map (kbd "C-c C-p") 'markdown-previous-visible-heading)
4791 (define-key map (kbd "C-c C-f") 'markdown-forward-same-level)
4792 (define-key map (kbd "C-c C-b") 'markdown-backward-same-level)
4793 (define-key map (kbd "C-c C-u") 'markdown-up-heading)
4794 ;; Buffer-wide commands
4795 (define-key map (kbd "C-c C-c m") 'markdown-other-window)
4796 (define-key map (kbd "C-c C-c p") 'markdown-preview)
4797 (define-key map (kbd "C-c C-c e") 'markdown-export)
4798 (define-key map (kbd "C-c C-c v") 'markdown-export-and-preview)
4799 (define-key map (kbd "C-c C-c o") 'markdown-open)
4800 (define-key map (kbd "C-c C-c l") 'markdown-live-preview-mode)
4801 (define-key map (kbd "C-c C-c w") 'markdown-kill-ring-save)
4802 (define-key map (kbd "C-c C-c c") 'markdown-check-refs)
4803 (define-key map (kbd "C-c C-c n") 'markdown-cleanup-list-numbers)
4804 (define-key map (kbd "C-c C-c ]") 'markdown-complete-buffer)
4805 ;; List editing
4806 (define-key map (kbd "M-<up>") 'markdown-move-up)
4807 (define-key map (kbd "M-<down>") 'markdown-move-down)
4808 (define-key map (kbd "M-<left>") 'markdown-promote)
4809 (define-key map (kbd "M-<right>") 'markdown-demote)
4810 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
4811 (define-key map (kbd "C-c C-j") 'markdown-insert-list-item)
4812 ;; Subtree editing
4813 (define-key map (kbd "M-S-<up>") 'markdown-move-subtree-up)
4814 (define-key map (kbd "M-S-<down>") 'markdown-move-subtree-down)
4815 (define-key map (kbd "M-S-<left>") 'markdown-promote-subtree)
4816 (define-key map (kbd "M-S-<right>") 'markdown-demote-subtree)
4817 ;; Blocks
4818 (define-key map (kbd "M-{") 'markdown-backward-block)
4819 (define-key map (kbd "M-}") 'markdown-forward-block)
4820 (define-key map (kbd "M-h") 'markdown-mark-block)
4821 (define-key map (kbd "C-x n b") 'markdown-narrow-to-block)
4822 ;; Movement
4823 (define-key map (kbd "M-n") 'markdown-next-link)
4824 (define-key map (kbd "M-p") 'markdown-previous-link)
4825 ;; Alternative keys (in case of problems with the arrow keys)
4826 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
4827 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
4828 (define-key map (kbd "C-c C-x l") 'markdown-promote)
4829 (define-key map (kbd "C-c C-x r") 'markdown-demote)
4830 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item)
4831 (define-key map (kbd "C-c C-x C-x") 'markdown-toggle-gfm-checkbox)
4832 map)
4833 "Keymap for Markdown major mode.")
4835 (defvar gfm-mode-map
4836 (let ((map (make-sparse-keymap)))
4837 (set-keymap-parent map markdown-mode-map)
4838 (define-key map (kbd "C-c C-s d") 'markdown-insert-strike-through)
4839 (define-key map "`" 'markdown-electric-backquote)
4840 map)
4841 "Keymap for `gfm-mode'.
4842 See also `markdown-mode-map'.")
4845 ;;; Menu ==================================================================
4847 (easy-menu-define markdown-mode-menu markdown-mode-map
4848 "Menu for Markdown mode"
4849 '("Markdown"
4850 "---"
4851 ("Movement"
4852 ["Jump" markdown-jump]
4853 ["Follow Link" markdown-follow-thing-at-point]
4854 ["Next Link" markdown-next-link]
4855 ["Previous Link" markdown-previous-link]
4856 "---"
4857 ["Next Visible Heading" markdown-next-visible-heading]
4858 ["Previous Visible Heading" markdown-previous-visible-heading]
4859 ["Forward Same Level" markdown-forward-same-level]
4860 ["Backward Same Level" markdown-backward-same-level]
4861 ["Up to Parent Heading" markdown-up-heading]
4862 "---"
4863 ["Forward Block" markdown-forward-block]
4864 ["Backward Block" markdown-backward-block])
4865 ("Show/Hide"
4866 ["Cycle Visibility" markdown-cycle (markdown-on-heading-p)]
4867 ["Cycle Visibility Globally" markdown-shifttab])
4868 "---"
4869 ("Headings & Structure"
4870 ["Automatic Heading" markdown-insert-header-dwim]
4871 ["Automatic Heading (Setext)" markdown-insert-header-setext-dwim]
4872 ("Specific Heading (atx)"
4873 ["First Level Setext" markdown-insert-header-setext-1]
4874 ["Second Level Setext" markdown-insert-header-setext-2])
4875 ("Specific Heading (Setext)"
4876 ["First Level atx" markdown-insert-header-atx-1]
4877 ["Second Level atx" markdown-insert-header-atx-2]
4878 ["Third Level atx" markdown-insert-header-atx-3]
4879 ["Fourth Level atx" markdown-insert-header-atx-4]
4880 ["Fifth Level atx" markdown-insert-header-atx-5]
4881 ["Sixth Level atx" markdown-insert-header-atx-6])
4882 ["Horizontal Rule" markdown-insert-hr]
4883 "---"
4884 ["Move Subtree Up" markdown-move-subtree-up :keys "M-S-<up>"]
4885 ["Move Subtree Down" markdown-move-subtree-down :keys "M-S-<down>"]
4886 ["Promote Subtree" markdown-promote-subtree :keys "M-S-<left>"]
4887 ["Demote Subtree" markdown-demote-subtree :keys "M-S-<right>"]
4888 ["Promote Header" markdown-promote :keys "M-<left>"]
4889 ["Demote Header" markdown-demote :keys "M-<right>"])
4890 ("Region Editing"
4891 ["Indent Region" markdown-indent-region]
4892 ["Exdent Region" markdown-exdent-region])
4893 ("Lists"
4894 ["Insert List Item" markdown-insert-list-item]
4895 ["Move List Item Up" markdown-move-up :keys "M-<up>"]
4896 ["Move List Item Down" markdown-move-down :keys "M-<down>"]
4897 ["Exdent List Item" markdown-promote :keys "M-<left>"]
4898 ["Indent List Item" markdown-demote :keys "M-<right>"]
4899 ["Renumber List" markdown-cleanup-list-numbers]
4900 ["Toggle Task List Item" markdown-toggle-gfm-checkbox])
4901 ("Links & Images"
4902 ["Plain URL" markdown-insert-uri]
4903 ["Inline Link" markdown-insert-inline-link-dwim]
4904 ["Inline Image" markdown-insert-image]
4905 ["Reference Link" markdown-insert-reference-link-dwim]
4906 ["Reference Image" markdown-insert-reference-image]
4907 ["Footnote" markdown-insert-footnote]
4908 ["Wiki Link" markdown-insert-wiki-link]
4909 "---"
4910 ["Check References" markdown-check-refs]
4911 ["Toggle Inline Images" markdown-toggle-inline-images
4912 :style radio
4913 :selected markdown-inline-image-overlays])
4914 ("Styles"
4915 ["Bold" markdown-insert-bold]
4916 ["Italic" markdown-insert-italic]
4917 ["Code" markdown-insert-code]
4918 ["Strikethrough" markdown-insert-strike-through]
4919 ["Keyboard" markdown-insert-kbd]
4920 "---"
4921 ["Blockquote" markdown-insert-blockquote]
4922 ["Preformatted" markdown-insert-pre]
4923 ["GFM Code Block" markdown-insert-gfm-code-block]
4924 "---"
4925 ["Blockquote Region" markdown-blockquote-region]
4926 ["Preformatted Region" markdown-pre-region]
4927 "---"
4928 ["Enable LaTeX math" markdown-toggle-math
4929 :style radio
4930 :selected markdown-enable-math])
4931 "---"
4932 ("Preview & Export"
4933 ["Compile" markdown-other-window]
4934 ["Preview" markdown-preview]
4935 ["Export" markdown-export]
4936 ["Export & View" markdown-export-and-preview]
4937 ["Open" markdown-open]
4938 ["Live Export" markdown-live-preview-mode
4939 :style radio
4940 :selected markdown-live-preview-mode]
4941 ["Kill ring save" markdown-kill-ring-save])
4942 ("Markup Completion and Cycling"
4943 ["Complete Markup" markdown-complete]
4944 ["Promote Element" markdown-promote]
4945 ["Demote Element" markdown-demote])
4946 "---"
4947 ["Kill Element" markdown-kill-thing-at-point]
4948 "---"
4949 ("Documentation"
4950 ["Version" markdown-show-version]
4951 ["Homepage" markdown-mode-info]
4952 ["Describe Mode" (describe-function 'markdown-mode)])))
4955 ;;; imenu =====================================================================
4957 (defun markdown-imenu-create-nested-index ()
4958 "Create and return a nested imenu index alist for the current buffer.
4959 See `imenu-create-index-function' and `imenu--index-alist' for details."
4960 (let* ((root '(nil . nil))
4961 cur-alist
4962 (cur-level 0)
4963 (empty-heading "-")
4964 (self-heading ".")
4965 hashes pos level heading)
4966 (save-excursion
4967 (goto-char (point-min))
4968 (while (re-search-forward markdown-regex-header (point-max) t)
4969 (unless (markdown-code-block-at-point-p)
4970 (cond
4971 ((match-string-no-properties 2) ;; level 1 setext
4972 (setq heading (match-string-no-properties 1))
4973 (setq pos (match-beginning 1)
4974 level 1))
4975 ((match-string-no-properties 3) ;; level 2 setext
4976 (setq heading (match-string-no-properties 1))
4977 (setq pos (match-beginning 1)
4978 level 2))
4979 ((setq hashes (match-string-no-properties 4))
4980 (setq heading (match-string-no-properties 5)
4981 pos (match-beginning 4)
4982 level (length hashes))))
4983 (let ((alist (list (cons heading pos))))
4984 (cond
4985 ((= cur-level level) ; new sibling
4986 (setcdr cur-alist alist)
4987 (setq cur-alist alist))
4988 ((< cur-level level) ; first child
4989 (dotimes (_ (- level cur-level 1))
4990 (setq alist (list (cons empty-heading alist))))
4991 (if cur-alist
4992 (let* ((parent (car cur-alist))
4993 (self-pos (cdr parent)))
4994 (setcdr parent (cons (cons self-heading self-pos) alist)))
4995 (setcdr root alist)) ; primogenitor
4996 (setq cur-alist alist)
4997 (setq cur-level level))
4998 (t ; new sibling of an ancestor
4999 (let ((sibling-alist (last (cdr root))))
5000 (dotimes (_ (1- level))
5001 (setq sibling-alist (last (cdar sibling-alist))))
5002 (setcdr sibling-alist alist)
5003 (setq cur-alist alist))
5004 (setq cur-level level))))))
5005 (cdr root))))
5007 (defun markdown-imenu-create-flat-index ()
5008 "Create and return a flat imenu index alist for the current buffer.
5009 See `imenu-create-index-function' and `imenu--index-alist' for details."
5010 (let* ((empty-heading "-") index heading pos)
5011 (save-excursion
5012 (goto-char (point-min))
5013 (while (re-search-forward markdown-regex-header (point-max) t)
5014 (when (and (not (markdown-code-block-at-point-p))
5015 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin)))
5016 (cond
5017 ((setq heading (match-string-no-properties 1))
5018 (setq pos (match-beginning 1)))
5019 ((setq heading (match-string-no-properties 5))
5020 (setq pos (match-beginning 4))))
5021 (or (> (length heading) 0)
5022 (setq heading empty-heading))
5023 (setq index (append index (list (cons heading pos))))))
5024 index)))
5027 ;;; References ================================================================
5029 (defun markdown-reference-goto-definition ()
5030 "Jump to the definition of the reference at point or create it."
5031 (interactive)
5032 (when (thing-at-point-looking-at markdown-regex-link-reference)
5033 (let* ((text (match-string-no-properties 3))
5034 (reference (match-string-no-properties 6))
5035 (target (downcase (if (string= reference "") text reference)))
5036 (loc (cadr (markdown-reference-definition target))))
5037 (if loc
5038 (goto-char loc)
5039 (goto-char (match-beginning 0))
5040 (markdown-insert-reference-definition target)))))
5042 (defun markdown-reference-find-links (reference)
5043 "Return a list of all links for REFERENCE.
5044 REFERENCE should not include the surrounding square brackets.
5045 Elements of the list have the form (text start line), where
5046 text is the link text, start is the location at the beginning of
5047 the link, and line is the line number on which the link appears."
5048 (let* ((ref-quote (regexp-quote reference))
5049 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
5050 ref-quote ref-quote))
5051 links)
5052 (save-excursion
5053 (goto-char (point-min))
5054 (while (re-search-forward regexp nil t)
5055 (let* ((text (or (match-string-no-properties 1)
5056 (match-string-no-properties 2)))
5057 (start (match-beginning 0))
5058 (line (markdown-line-number-at-pos)))
5059 (cl-pushnew (list text start line) links :test #'equal))))
5060 links))
5062 (defun markdown-get-undefined-refs ()
5063 "Return a list of undefined Markdown references.
5064 Result is an alist of pairs (reference . occurrences), where
5065 occurrences is itself another alist of pairs (label . line-number).
5066 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
5067 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
5068 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
5069 (let ((missing))
5070 (save-excursion
5071 (goto-char (point-min))
5072 (while
5073 (re-search-forward markdown-regex-link-reference nil t)
5074 (let* ((text (match-string-no-properties 3))
5075 (reference (match-string-no-properties 6))
5076 (target (downcase (if (string= reference "") text reference))))
5077 (unless (markdown-reference-definition target)
5078 (let ((entry (assoc target missing)))
5079 (if (not entry)
5080 (cl-pushnew
5081 (cons target (list (cons text (markdown-line-number-at-pos))))
5082 missing :test #'equal)
5083 (setcdr entry
5084 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
5085 (reverse missing))))
5087 (defconst markdown-reference-check-buffer
5088 "*Undefined references for %buffer%*"
5089 "Pattern for name of buffer for listing undefined references.
5090 The string %buffer% will be replaced by the corresponding
5091 `markdown-mode' buffer name.")
5093 (defun markdown-reference-check-buffer (&optional buffer-name)
5094 "Name and return buffer for reference checking.
5095 BUFFER-NAME is the name of the main buffer being visited."
5096 (or buffer-name (setq buffer-name (buffer-name)))
5097 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
5098 "%buffer%" buffer-name
5099 markdown-reference-check-buffer))))
5100 (with-current-buffer refbuf
5101 (when view-mode
5102 (View-exit-and-edit))
5103 (use-local-map button-buffer-map)
5104 (erase-buffer))
5105 refbuf))
5107 (defconst markdown-reference-links-buffer
5108 "*Reference links for %buffer%*"
5109 "Pattern for name of buffer for listing references.
5110 The string %buffer% will be replaced by the corresponding buffer name.")
5112 (defun markdown-reference-links-buffer (&optional buffer-name)
5113 "Name, setup, and return a buffer for listing links.
5114 BUFFER-NAME is the name of the main buffer being visited."
5115 (or buffer-name (setq buffer-name (buffer-name)))
5116 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
5117 "%buffer%" buffer-name
5118 markdown-reference-links-buffer))))
5119 (with-current-buffer linkbuf
5120 (when view-mode
5121 (View-exit-and-edit))
5122 (use-local-map button-buffer-map)
5123 (erase-buffer))
5124 linkbuf))
5126 (when (markdown-use-buttons-p)
5127 ;; Add an empty Markdown reference definition to buffer
5128 ;; specified in the 'target-buffer property. The reference name is
5129 ;; the button's label.
5130 (define-button-type 'markdown-undefined-reference-button
5131 'help-echo "mouse-1, RET: create definition for undefined reference"
5132 'follow-link t
5133 'face 'bold
5134 'action (lambda (b)
5135 (let ((buffer (button-get b 'target-buffer))
5136 (line (button-get b 'target-line))
5137 (label (button-label b)))
5138 (switch-to-buffer-other-window buffer)
5139 (goto-char (point-min))
5140 (forward-line line)
5141 (markdown-insert-reference-definition label)
5142 (markdown-check-refs t))))
5144 ;; Jump to line in buffer specified by 'target-buffer property.
5145 ;; Line number is button's 'line property.
5146 (define-button-type 'markdown-goto-line-button
5147 'help-echo "mouse-1, RET: go to line"
5148 'follow-link t
5149 'face 'italic
5150 'action (lambda (b)
5151 (message (button-get b 'buffer))
5152 (switch-to-buffer-other-window (button-get b 'target-buffer))
5153 ;; use call-interactively to silence compiler
5154 (let ((current-prefix-arg (button-get b 'target-line)))
5155 (call-interactively 'goto-line))))
5157 ;; Jumps to a particular link at location given by 'target-char
5158 ;; property in buffer given by 'target-buffer property.
5159 (define-button-type 'markdown-link-button
5160 'help-echo "mouse-1, RET: jump to location of link"
5161 'follow-link t
5162 'face 'bold
5163 'action (lambda (b)
5164 (let ((target (button-get b 'target-buffer))
5165 (loc (button-get b 'target-char)))
5166 (kill-buffer-and-window)
5167 (switch-to-buffer target)
5168 (goto-char loc)))))
5170 (defun markdown-insert-undefined-reference-button (reference oldbuf)
5171 "Insert a button for creating REFERENCE in buffer OLDBUF.
5172 REFERENCE should be a list of the form (reference . occurrences),
5173 as by `markdown-get-undefined-refs'."
5174 (let ((label (car reference)))
5175 (if (markdown-use-buttons-p)
5176 ;; Create a reference button in Emacs 22
5177 (insert-button label
5178 :type 'markdown-undefined-reference-button
5179 'target-buffer oldbuf
5180 'target-line (cdr (car (cdr reference))))
5181 ;; Insert reference as text in Emacs < 22
5182 (insert label))
5183 (insert " (")
5184 (dolist (occurrence (cdr reference))
5185 (let ((line (cdr occurrence)))
5186 (if (markdown-use-buttons-p)
5187 ;; Create a line number button in Emacs 22
5188 (insert-button (number-to-string line)
5189 :type 'markdown-goto-line-button
5190 'target-buffer oldbuf
5191 'target-line line)
5192 ;; Insert line number as text in Emacs < 22
5193 (insert (number-to-string line)))
5194 (insert " ")))
5195 (delete-char -1)
5196 (insert ")")
5197 (newline)))
5199 (defun markdown-insert-link-button (link oldbuf)
5200 "Insert a button for jumping to LINK in buffer OLDBUF.
5201 LINK should be a list of the form (text char line) containing
5202 the link text, location, and line number."
5203 (let ((label (cl-first link))
5204 (char (cl-second link))
5205 (line (cl-third link)))
5206 (if (markdown-use-buttons-p)
5207 ;; Create a reference button in Emacs 22
5208 (insert-button label
5209 :type 'markdown-link-button
5210 'target-buffer oldbuf
5211 'target-char char)
5212 ;; Insert reference as text in Emacs < 22
5213 (insert label))
5214 (insert (format " (line %d)\n" line))))
5216 (defun markdown-reference-goto-link (&optional reference)
5217 "Jump to the location of the first use of REFERENCE."
5218 (interactive)
5219 (unless reference
5220 (if (thing-at-point-looking-at markdown-regex-reference-definition)
5221 (setq reference (match-string-no-properties 2))
5222 (error "No reference definition at point")))
5223 (let ((links (markdown-reference-find-links reference)))
5224 (cond ((= (length links) 1)
5225 (goto-char (cadr (car links))))
5226 ((> (length links) 1)
5227 (let ((oldbuf (current-buffer))
5228 (linkbuf (markdown-reference-links-buffer)))
5229 (with-current-buffer linkbuf
5230 (insert "Links using reference " reference ":\n\n")
5231 (dolist (link (reverse links))
5232 (markdown-insert-link-button link oldbuf)))
5233 (view-buffer-other-window linkbuf)
5234 (goto-char (point-min))
5235 (forward-line 2)))
5237 (error "No links for reference %s" reference)))))
5239 (defun markdown-check-refs (&optional silent)
5240 "Show all undefined Markdown references in current `markdown-mode' buffer.
5241 If SILENT is non-nil, do not message anything when no undefined
5242 references found.
5243 Links which have empty reference definitions are considered to be
5244 defined."
5245 (interactive "P")
5246 (when (not (eq major-mode 'markdown-mode))
5247 (error "Not available in current mode"))
5248 (let ((oldbuf (current-buffer))
5249 (refs (markdown-get-undefined-refs))
5250 (refbuf (markdown-reference-check-buffer)))
5251 (if (null refs)
5252 (progn
5253 (when (not silent)
5254 (message "No undefined references found"))
5255 (kill-buffer refbuf))
5256 (with-current-buffer refbuf
5257 (insert "The following references are undefined:\n\n")
5258 (dolist (ref refs)
5259 (markdown-insert-undefined-reference-button ref oldbuf))
5260 (view-buffer-other-window refbuf)
5261 (goto-char (point-min))
5262 (forward-line 2)))))
5265 ;;; Lists =====================================================================
5267 (defun markdown-insert-list-item (&optional arg)
5268 "Insert a new list item.
5269 If the point is inside unordered list, insert a bullet mark. If
5270 the point is inside ordered list, insert the next number followed
5271 by a period. Use the previous list item to determine the amount
5272 of whitespace to place before and after list markers.
5274 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
5275 decrease the indentation by one level.
5277 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
5278 increase the indentation by one level."
5279 (interactive "p")
5280 (let (bounds cur-indent marker indent new-indent new-loc)
5281 (save-match-data
5282 ;; Look for a list item on current or previous non-blank line
5283 (save-excursion
5284 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
5285 (not (bobp))
5286 (markdown-cur-line-blank-p))
5287 (forward-line -1)))
5288 (when bounds
5289 (cond ((save-excursion
5290 (skip-chars-backward " \t")
5291 (looking-at-p markdown-regex-list))
5292 (beginning-of-line)
5293 (insert "\n")
5294 (forward-line -1))
5295 ((not (markdown-cur-line-blank-p))
5296 (newline)))
5297 (setq new-loc (point)))
5298 ;; Look ahead for a list item on next non-blank line
5299 (unless bounds
5300 (save-excursion
5301 (while (and (null bounds)
5302 (not (eobp))
5303 (markdown-cur-line-blank-p))
5304 (forward-line)
5305 (setq bounds (markdown-cur-list-item-bounds))))
5306 (when bounds
5307 (setq new-loc (point))
5308 (unless (markdown-cur-line-blank-p)
5309 (newline))))
5310 (if (not bounds)
5311 ;; When not in a list, start a new unordered one
5312 (progn
5313 (unless (markdown-cur-line-blank-p)
5314 (insert "\n"))
5315 (insert markdown-unordered-list-item-prefix))
5316 ;; Compute indentation and marker for new list item
5317 (setq cur-indent (nth 2 bounds))
5318 (setq marker (nth 4 bounds))
5319 (cond
5320 ;; Dedent: decrement indentation, find previous marker.
5321 ((= arg 4)
5322 (setq indent (max (- cur-indent 4) 0))
5323 (let ((prev-bounds
5324 (save-excursion
5325 (when (markdown-prev-list-item (- (nth 3 bounds) 1))
5326 (markdown-cur-list-item-bounds)))))
5327 (when prev-bounds
5328 (setq marker (nth 4 prev-bounds)))))
5329 ;; Indent: increment indentation by 4, use same marker.
5330 ((= arg 16) (setq indent (+ cur-indent 4)))
5331 ;; Same level: keep current indentation and marker.
5332 (t (setq indent cur-indent)))
5333 (setq new-indent (make-string indent 32))
5334 (goto-char new-loc)
5335 (cond
5336 ;; Ordered list
5337 ((string-match-p "[0-9]" marker)
5338 (if (= arg 16) ;; starting a new column indented one more level
5339 (insert (concat new-indent "1. "))
5340 ;; Don't use previous match-data
5341 (set-match-data nil)
5342 ;; travel up to the last item and pick the correct number. If
5343 ;; the argument was nil, "new-indent = cur-indent" is the same,
5344 ;; so we don't need special treatment. Neat.
5345 (save-excursion
5346 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
5347 (>= (forward-line -1) 0))))
5348 (let* ((old-prefix (match-string 1))
5349 (old-spacing (match-string 2))
5350 (new-prefix (if old-prefix
5351 (int-to-string (1+ (string-to-number old-prefix)))
5352 "1"))
5353 (space-adjust (- (length old-prefix) (length new-prefix)))
5354 (new-spacing (if (and (match-string 2)
5355 (not (string-match-p "\t" old-spacing))
5356 (< space-adjust 0)
5357 (> space-adjust (- 1 (length (match-string 2)))))
5358 (substring (match-string 2) 0 space-adjust)
5359 (or old-spacing ". "))))
5360 (insert (concat new-indent new-prefix new-spacing)))))
5361 ;; Unordered list, or ordered list with hash mark
5362 ((string-match-p "[\\*\\+-]\\|#\\." marker)
5363 (insert new-indent marker)))))))
5365 (defun markdown-move-list-item-up ()
5366 "Move the current list item up in the list when possible."
5367 (interactive)
5368 (let (cur prev old)
5369 (when (setq cur (markdown-cur-list-item-bounds))
5370 (setq old (point))
5371 (goto-char (nth 0 cur))
5372 (if (markdown-prev-list-item (nth 3 cur))
5373 (progn
5374 (setq prev (markdown-cur-list-item-bounds))
5375 (condition-case nil
5376 (progn
5377 (transpose-regions (nth 0 prev) (nth 1 prev)
5378 (nth 0 cur) (nth 1 cur) t)
5379 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
5380 ;; Catch error in case regions overlap.
5381 (error (goto-char old))))
5382 (goto-char old)))))
5384 (defun markdown-move-list-item-down ()
5385 "Move the current list item down in the list when possible."
5386 (interactive)
5387 (let (cur next old)
5388 (when (setq cur (markdown-cur-list-item-bounds))
5389 (setq old (point))
5390 (if (markdown-next-list-item (nth 3 cur))
5391 (progn
5392 (setq next (markdown-cur-list-item-bounds))
5393 (condition-case nil
5394 (progn
5395 (transpose-regions (nth 0 cur) (nth 1 cur)
5396 (nth 0 next) (nth 1 next) nil)
5397 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
5398 ;; Catch error in case regions overlap.
5399 (error (goto-char old))))
5400 (goto-char old)))))
5402 (defun markdown-demote-list-item (&optional bounds)
5403 "Indent (or demote) the current list item.
5404 Optionally, BOUNDS of the current list item may be provided if available."
5405 (interactive)
5406 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
5407 (save-excursion
5408 (let ((end-marker (set-marker (make-marker) (nth 1 bounds))))
5409 (goto-char (nth 0 bounds))
5410 (while (< (point) end-marker)
5411 (unless (markdown-cur-line-blank-p)
5412 (insert (make-string markdown-list-indent-width ? )))
5413 (forward-line))))))
5415 (defun markdown-promote-list-item (&optional bounds)
5416 "Unindent (or promote) the current list item.
5417 Optionally, BOUNDS of the current list item may be provided if available."
5418 (interactive)
5419 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
5420 (save-excursion
5421 (save-match-data
5422 (let ((end-marker (set-marker (make-marker) (nth 1 bounds)))
5423 num regexp)
5424 (goto-char (nth 0 bounds))
5425 (when (looking-at (format "^[ ]\\{1,%d\\}"
5426 markdown-list-indent-width))
5427 (setq num (- (match-end 0) (match-beginning 0)))
5428 (setq regexp (format "^[ ]\\{1,%d\\}" num))
5429 (while (and (< (point) end-marker)
5430 (re-search-forward regexp end-marker t))
5431 (replace-match "" nil nil)
5432 (forward-line))))))))
5434 (defun markdown-cleanup-list-numbers-level (&optional pfx)
5435 "Update the numbering for level PFX (as a string of spaces).
5437 Assume that the previously found match was for a numbered item in
5438 a list."
5439 (let ((cpfx pfx)
5440 (idx 0)
5441 (continue t)
5442 (step t)
5443 (sep nil))
5444 (while (and continue (not (eobp)))
5445 (setq step t)
5446 (cond
5447 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
5448 (setq cpfx (match-string-no-properties 1))
5449 (cond
5450 ((string= cpfx pfx)
5451 (save-excursion
5452 (replace-match
5453 (concat pfx (number-to-string (setq idx (1+ idx))) ". ")))
5454 (setq sep nil))
5455 ;; indented a level
5456 ((string< pfx cpfx)
5457 (setq sep (markdown-cleanup-list-numbers-level cpfx))
5458 (setq step nil))
5459 ;; exit the loop
5461 (setq step nil)
5462 (setq continue nil))))
5464 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
5465 (setq cpfx (match-string-no-properties 1))
5466 (cond
5467 ;; reset if separated before
5468 ((string= cpfx pfx) (when sep (setq idx 0)))
5469 ((string< cpfx pfx)
5470 (setq step nil)
5471 (setq continue nil))))
5472 (t (setq sep t)))
5474 (when step
5475 (beginning-of-line)
5476 (setq continue (= (forward-line) 0))))
5477 sep))
5479 (defun markdown-cleanup-list-numbers ()
5480 "Update the numbering of ordered lists."
5481 (interactive)
5482 (save-excursion
5483 (goto-char (point-min))
5484 (markdown-cleanup-list-numbers-level "")))
5487 ;;; Movement ==================================================================
5489 (defun markdown-beginning-of-defun (&optional arg)
5490 "`beginning-of-defun-function' for Markdown.
5491 Move backward to the beginning of the current or previous section.
5492 When ARG is non-nil, repeat that many times. When ARG is negative,
5493 move forward to the ARG-th following section."
5494 (interactive "P")
5495 (or arg (setq arg 1))
5496 (forward-char 1)
5497 (or (re-search-backward markdown-regex-header nil t arg)
5498 (goto-char (point-min))))
5500 (defun markdown-end-of-defun (&optional arg)
5501 "`end-of-defun-function' for Markdown.
5502 Move forward to the end of the current or following section.
5503 When ARG is non-nil, repeat that many times. When ARG is negative,
5504 move back to the ARG-th preceding section."
5505 (interactive "P")
5506 (or arg (setq arg 1))
5507 (when (looking-at markdown-regex-header)
5508 (goto-char (match-beginning 0))
5509 (forward-char 1))
5510 (if (re-search-forward markdown-regex-header nil t arg)
5511 (goto-char (match-beginning 0))
5512 (goto-char (point-max)))
5513 (skip-syntax-backward "-"))
5515 (make-obsolete 'markdown-beginning-of-block 'markdown-beginning-of-text-block "2017-05-18")
5517 (defun markdown-beginning-of-text-block ()
5518 "Move backward to previous beginning of a plain text block.
5519 This function simply looks for blank lines without considering
5520 the surrounding context in light of Markdown syntax. For that, see
5521 `markdown-backward-block'."
5522 (let ((start (point)))
5523 (if (re-search-backward markdown-regex-block-separator nil t)
5524 (goto-char (match-end 0))
5525 (goto-char (point-min)))
5526 (when (and (= start (point)) (not (bobp)))
5527 (forward-line -1)
5528 (if (re-search-backward markdown-regex-block-separator nil t)
5529 (goto-char (match-end 0))
5530 (goto-char (point-min))))))
5532 (make-obsolete 'markdown-end-of-block 'markdown-end-of-text-block "2017-05-18")
5534 (defun markdown-end-of-text-block ()
5535 "Move forward to next beginning of a plain text block.
5536 This function simply looks for blank lines without considering
5537 the surrounding context in light of Markdown syntax. For that, see
5538 `markdown-forward-block'."
5539 (beginning-of-line)
5540 (skip-syntax-forward "-")
5541 (when (= (point) (point-min))
5542 (forward-char))
5543 (if (re-search-forward markdown-regex-block-separator nil t)
5544 (goto-char (match-end 0))
5545 (goto-char (point-max)))
5546 (skip-syntax-backward "-")
5547 (forward-line))
5549 (defun markdown-backward-block (&optional arg)
5550 "Move the point to the start of the current Markdown block.
5551 Moves across complete code blocks, list items, and blockquotes,
5552 but otherwise stops at blank lines, headers, and horizontal
5553 rules. With argument ARG, do it ARG times; a negative argument
5554 ARG = -N means move forward N blocks."
5555 (interactive "p")
5556 (or arg (setq arg 1))
5557 (if (< arg 0)
5558 (markdown-forward-block (- arg))
5559 (dotimes (_ arg)
5560 ;; Skip over whitespace in between blocks when moving backward.
5561 (skip-syntax-backward "-")
5562 (beginning-of-line)
5563 ;; Proceed forward based on the type of block.
5564 (let (bounds)
5565 (cond
5566 ;; Code blocks
5567 ((markdown-code-block-at-point-p)
5568 (forward-line -1)
5569 (while (and (markdown-code-block-at-point-p) (not (bobp)))
5570 (forward-line -1))
5571 (forward-line))
5572 ;; Headings
5573 ((markdown-heading-at-point)
5574 (goto-char (match-beginning 0)))
5575 ;; Horizontal rules
5576 ((looking-at markdown-regex-hr))
5577 ;; Blockquotes
5578 ((looking-at markdown-regex-blockquote)
5579 (forward-line -1)
5580 (while (and (looking-at markdown-regex-blockquote) (not (bobp)))
5581 (forward-line -1))
5582 (forward-line))
5583 ;; List items
5584 ((setq bounds (markdown-cur-list-item-bounds))
5585 (goto-char (cl-first bounds)))
5586 ;; Other
5588 (unless (markdown-prev-line-blank-p)
5589 ;; Already moved to beginning-of-line, so don't move back
5590 ;; again when already at the beginning of a block.
5591 (markdown-beginning-of-text-block))))))
5592 (skip-syntax-forward "-")))
5594 (defun markdown-forward-block (&optional arg)
5595 "Move forward to the next end of a 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 backward N blocks."
5600 (interactive "p")
5601 (or arg (setq arg 1))
5602 (if (< arg 0)
5603 (markdown-backward-block (- arg))
5604 (dotimes (_ arg)
5605 ;; Skip over whitespace in between blocks when moving forward.
5606 (if (markdown-cur-line-blank-p)
5607 (skip-syntax-forward "-")
5608 (beginning-of-line))
5609 ;; Proceed forward based on the type of block.
5610 (let (bounds)
5611 (cond
5612 ;; Code blocks
5613 ((markdown-code-block-at-point-p)
5614 (forward-line)
5615 (while (and (markdown-code-block-at-point-p) (not (eobp)))
5616 (forward-line)))
5617 ;; Headings
5618 ((looking-at markdown-regex-header)
5619 (goto-char (or (match-end 4) (match-end 2) (match-end 3)))
5620 (forward-line))
5621 ;; Horizontal rules
5622 ((looking-at markdown-regex-hr)
5623 (forward-line))
5624 ;; Blockquotes
5625 ((looking-at markdown-regex-blockquote)
5626 (forward-line)
5627 (while (and (looking-at markdown-regex-blockquote) (not (eobp)))
5628 (forward-line)))
5629 ;; List items
5630 ((setq bounds (markdown-cur-list-item-bounds))
5631 (goto-char (cl-second bounds))
5632 (forward-line))
5633 ;; Other
5634 (t (markdown-end-of-text-block)))))))
5636 (defun markdown-next-link ()
5637 "Jump to next inline, reference, or wiki link.
5638 If successful, return point. Otherwise, return nil.
5639 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
5640 (interactive)
5641 (let ((opoint (point)))
5642 (when (or (markdown-link-p) (markdown-wiki-link-p))
5643 ;; At a link already, move past it.
5644 (goto-char (+ (match-end 0) 1)))
5645 ;; Search for the next wiki link and move to the beginning.
5646 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t)
5647 (markdown-code-block-at-point-p)
5648 (< (point) (point-max))))
5649 (if (and (not (eq (point) opoint))
5650 (or (markdown-link-p) (markdown-wiki-link-p)))
5651 ;; Group 1 will move past non-escape character in wiki link regexp.
5652 ;; Go to beginning of group zero for all other link types.
5653 (goto-char (or (match-beginning 1) (match-beginning 0)))
5654 (goto-char opoint)
5655 nil)))
5657 (defun markdown-previous-link ()
5658 "Jump to previous wiki link.
5659 If successful, return point. Otherwise, return nil.
5660 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
5661 (interactive)
5662 (let ((opoint (point)))
5663 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t)
5664 (markdown-code-block-at-point-p)
5665 (> (point) (point-min))))
5666 (if (and (not (eq (point) opoint))
5667 (or (markdown-link-p) (markdown-wiki-link-p)))
5668 (goto-char (or (match-beginning 1) (match-beginning 0)))
5669 (goto-char opoint)
5670 nil)))
5673 ;;; Outline ===================================================================
5675 (defun markdown-move-heading-common (move-fn &optional arg)
5676 "Wrapper for `outline-mode' functions to skip false positives.
5677 MOVE-FN is a function and ARG is its argument. For example,
5678 headings inside preformatted code blocks may match
5679 `outline-regexp' but should not be considered as headings."
5680 (let ((prev -1) (start (point)))
5681 (if arg (funcall move-fn arg) (funcall move-fn))
5682 (while (and (/= prev (point)) (markdown-code-block-at-point-p))
5683 (setq prev (point))
5684 (if arg (funcall move-fn arg) (funcall move-fn)))
5685 (if (= (point) start) nil (point))))
5687 (defun markdown-next-visible-heading (arg)
5688 "Move to the next visible heading line of any level.
5689 With argument, repeats or can move backward if negative. ARG is
5690 passed to `outline-next-visible-heading'."
5691 (interactive "p")
5692 (markdown-move-heading-common 'outline-next-visible-heading arg))
5694 (defun markdown-previous-visible-heading (arg)
5695 "Move to the previous visible heading line of any level.
5696 With argument, repeats or can move backward if negative. ARG is
5697 passed to `outline-previous-visible-heading'."
5698 (interactive "p")
5699 (markdown-move-heading-common 'outline-previous-visible-heading arg))
5701 (defun markdown-next-heading ()
5702 "Move to the next heading line of any level."
5703 (markdown-move-heading-common 'outline-next-heading))
5705 (defun markdown-previous-heading ()
5706 "Move to the previous heading line of any level."
5707 (markdown-move-heading-common 'outline-previous-heading))
5709 (defun markdown-forward-same-level (arg)
5710 "Move forward to the ARG'th heading at same level as this one.
5711 Stop at the first and last headings of a superior heading."
5712 (interactive "p")
5713 (markdown-move-heading-common 'outline-forward-same-level arg))
5715 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok)
5716 (beginning-of-line)
5717 (or (and (outline-on-heading-p invisible-ok)
5718 (not (markdown-code-block-at-point-p)))
5719 (let ((header-re (concat "^\\(?:" outline-regexp "\\)"))
5720 found)
5721 (save-excursion
5722 (while (not found)
5723 (let (finish)
5724 (while (and (not finish) (re-search-backward header-re nil t))
5725 (when (and (or invisible-ok (not (outline-invisible-p)))
5726 (not (markdown-code-block-at-point-p)))
5727 (setq finish t)))
5728 (if (not finish)
5729 (error "Before first heading")
5730 (setq found (point))))))
5731 (goto-char found)
5732 found)))
5734 (defun markdown-backward-same-level (arg)
5735 "Move backward to the ARG'th heading at same level as this one.
5736 Stop at the first and last headings of a superior heading."
5737 (interactive "p")
5738 (markdown-back-to-heading-over-code-block)
5739 (while (> arg 0)
5740 (let ((point-to-move-to (save-excursion
5741 (outline-get-last-sibling))))
5742 (if point-to-move-to
5743 (progn
5744 (goto-char point-to-move-to)
5745 (setq arg (1- arg)))
5746 (error "No previous same-level heading")))))
5748 (defun markdown-up-heading (arg)
5749 "Move to the visible heading line of which the present line is a subheading.
5750 With argument, move up ARG levels."
5751 (interactive "p")
5752 (and (called-interactively-p 'any)
5753 (not (eq last-command 'markdown-up-heading)) (push-mark))
5754 (markdown-move-heading-common 'outline-up-heading arg))
5756 (defun markdown-back-to-heading (&optional invisible-ok)
5757 "Move to previous heading line, or beg of this line if it's a heading.
5758 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
5759 (markdown-move-heading-common 'outline-back-to-heading invisible-ok))
5761 (defalias 'markdown-end-of-heading 'outline-end-of-heading)
5763 (defun markdown-on-heading-p ()
5764 "Return t if point is on a (visible) heading line."
5765 (get-text-property (point) 'markdown-heading))
5767 (defun markdown-end-of-subtree (&optional invisible-OK)
5768 "Move to the end of the current subtree.
5769 Only visible heading lines are considered, unless INVISIBLE-OK is
5770 non-nil.
5771 Derived from `org-end-of-subtree'."
5772 (markdown-back-to-heading invisible-OK)
5773 (let ((first t)
5774 (level (markdown-outline-level)))
5775 (while (and (not (eobp))
5776 (or first (> (markdown-outline-level) level)))
5777 (setq first nil)
5778 (markdown-next-heading))
5779 (if (memq (preceding-char) '(?\n ?\^M))
5780 (progn
5781 ;; Go to end of line before heading
5782 (forward-char -1)
5783 (if (memq (preceding-char) '(?\n ?\^M))
5784 ;; leave blank line before heading
5785 (forward-char -1)))))
5786 (point))
5788 (defun markdown-outline-fix-visibility ()
5789 "Hide any false positive headings that should not be shown.
5790 For example, headings inside preformatted code blocks may match
5791 `outline-regexp' but should not be shown as headings when cycling.
5792 Also, the ending --- line in metadata blocks appears to be a
5793 setext header, but should not be folded."
5794 (save-excursion
5795 (goto-char (point-min))
5796 ;; Unhide any false positives in metadata blocks
5797 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin)
5798 (let ((body (progn (forward-line)
5799 (markdown-text-property-at-point
5800 'markdown-yaml-metadata-section))))
5801 (when body
5802 (let ((end (progn (goto-char (cl-second body))
5803 (markdown-text-property-at-point
5804 'markdown-yaml-metadata-end))))
5805 (outline-flag-region (point-min) (1+ (cl-second end)) nil)))))
5806 ;; Hide any false positives in code blocks
5807 (unless (outline-on-heading-p)
5808 (outline-next-visible-heading 1))
5809 (while (< (point) (point-max))
5810 (when (markdown-code-block-at-point-p)
5811 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t))
5812 (outline-next-visible-heading 1))))
5814 (defvar markdown-cycle-global-status 1)
5815 (defvar markdown-cycle-subtree-status nil)
5817 (defun markdown-next-preface ()
5818 (let (finish)
5819 (while (and (not finish) (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
5820 nil 'move))
5821 (unless (markdown-code-block-at-point-p)
5822 (goto-char (match-beginning 0))
5823 (setq finish t))))
5824 (when (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
5825 (forward-char -1)))
5827 (defun markdown-show-entry ()
5828 (save-excursion
5829 (outline-back-to-heading t)
5830 (outline-flag-region (1- (point))
5831 (progn
5832 (markdown-next-preface)
5833 (if (= 1 (- (point-max) (point)))
5834 (point-max)
5835 (point)))
5836 nil)))
5838 (defun markdown-cycle (&optional arg)
5839 "Visibility cycling for Markdown mode.
5840 If ARG is t, perform global visibility cycling. If the point is
5841 at an atx-style header, cycle visibility of the corresponding
5842 subtree. Otherwise, insert a tab using `indent-relative'.
5843 Derived from `org-cycle'."
5844 (interactive "P")
5845 (cond
5846 ((eq arg t) ;; Global cycling
5847 (cond
5848 ((and (eq last-command this-command)
5849 (eq markdown-cycle-global-status 2))
5850 ;; Move from overview to contents
5851 (markdown-hide-sublevels 1)
5852 (message "CONTENTS")
5853 (setq markdown-cycle-global-status 3)
5854 (markdown-outline-fix-visibility))
5856 ((and (eq last-command this-command)
5857 (eq markdown-cycle-global-status 3))
5858 ;; Move from contents to all
5859 (markdown-show-all)
5860 (message "SHOW ALL")
5861 (setq markdown-cycle-global-status 1))
5864 ;; Defaults to overview
5865 (markdown-hide-body)
5866 (message "OVERVIEW")
5867 (setq markdown-cycle-global-status 2)
5868 (markdown-outline-fix-visibility))))
5870 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
5871 ;; At a heading: rotate between three different views
5872 (markdown-back-to-heading)
5873 (let ((goal-column 0) eoh eol eos)
5874 ;; Determine boundaries
5875 (save-excursion
5876 (markdown-back-to-heading)
5877 (save-excursion
5878 (beginning-of-line 2)
5879 (while (and (not (eobp)) ;; this is like `next-line'
5880 (get-char-property (1- (point)) 'invisible))
5881 (beginning-of-line 2)) (setq eol (point)))
5882 (markdown-end-of-heading) (setq eoh (point))
5883 (markdown-end-of-subtree t)
5884 (skip-chars-forward " \t\n")
5885 (beginning-of-line 1) ; in case this is an item
5886 (setq eos (1- (point))))
5887 ;; Find out what to do next and set `this-command'
5888 (cond
5889 ((= eos eoh)
5890 ;; Nothing is hidden behind this heading
5891 (message "EMPTY ENTRY")
5892 (setq markdown-cycle-subtree-status nil))
5893 ((>= eol eos)
5894 ;; Entire subtree is hidden in one line: open it
5895 (markdown-show-entry)
5896 (markdown-show-children)
5897 (message "CHILDREN")
5898 (setq markdown-cycle-subtree-status 'children))
5899 ((and (eq last-command this-command)
5900 (eq markdown-cycle-subtree-status 'children))
5901 ;; We just showed the children, now show everything.
5902 (markdown-show-subtree)
5903 (message "SUBTREE")
5904 (setq markdown-cycle-subtree-status 'subtree))
5906 ;; Default action: hide the subtree.
5907 (markdown-hide-subtree)
5908 (message "FOLDED")
5909 (setq markdown-cycle-subtree-status 'folded)))))
5912 (indent-for-tab-command))))
5914 (defun markdown-shifttab ()
5915 "Global visibility cycling.
5916 Calls `markdown-cycle' with argument t."
5917 (interactive)
5918 (markdown-cycle t))
5920 (defun markdown-outline-level ()
5921 "Return the depth to which a statement is nested in the outline."
5922 (cond
5923 ((markdown-code-block-at-point-p) 7) ;; Only 6 header levels are defined.
5924 ((match-end 2) 1)
5925 ((match-end 3) 2)
5926 ((match-end 4) (- (match-end 4) (match-beginning 4)))))
5928 (defun markdown-promote-subtree (&optional arg)
5929 "Promote the current subtree of ATX headings.
5930 Note that Markdown does not support heading levels higher than
5931 six and therefore level-six headings will not be promoted
5932 further. If ARG is non-nil promote the heading, otherwise
5933 demote."
5934 (interactive "*P")
5935 (save-excursion
5936 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
5937 (re-search-backward markdown-regex-header-atx nil t))
5938 (not (markdown-code-block-at-point-p)))
5939 (let ((level (length (match-string 1)))
5940 (promote-or-demote (if arg 1 -1))
5941 (remove 't))
5942 (markdown-cycle-atx promote-or-demote remove)
5943 (catch 'end-of-subtree
5944 (while (markdown-next-heading)
5945 ;; Exit if this not a higher level heading; promote otherwise.
5946 (if (and (looking-at markdown-regex-header-atx)
5947 (<= (length (match-string-no-properties 1)) level))
5948 (throw 'end-of-subtree nil)
5949 (markdown-cycle-atx promote-or-demote remove))))))))
5951 (defun markdown-demote-subtree ()
5952 "Demote the current subtree of ATX headings."
5953 (interactive)
5954 (markdown-promote-subtree t))
5956 (defun markdown-move-subtree-up ()
5957 "Move the current subtree of ATX headings up."
5958 (interactive)
5959 (outline-move-subtree-up 1))
5961 (defun markdown-move-subtree-down ()
5962 "Move the current subtree of ATX headings down."
5963 (interactive)
5964 (outline-move-subtree-down 1))
5967 ;;; Marking and Narrowing =====================================================
5969 (defun markdown-mark-block ()
5970 "Put mark at end of this block, point at beginning.
5971 The block marked is the one that contains point or follows point.
5973 Interactively, if this command is repeated or (in Transient Mark
5974 mode) if the mark is active, it marks the next block after the
5975 ones already marked."
5976 (interactive)
5977 (if (or (and (eq last-command this-command) (mark t))
5978 (and transient-mark-mode mark-active))
5979 (set-mark
5980 (save-excursion
5981 (goto-char (mark))
5982 (markdown-forward-block)
5983 (point)))
5984 (let ((beginning-of-defun-function 'markdown-backward-block)
5985 (end-of-defun-function 'markdown-forward-block))
5986 (mark-defun))))
5988 (defun markdown-narrow-to-block ()
5989 "Make text outside current block invisible.
5990 The current block is the one that contains point or follows point."
5991 (interactive)
5992 (let ((beginning-of-defun-function 'markdown-backward-block)
5993 (end-of-defun-function 'markdown-forward-block))
5994 (narrow-to-defun)))
5997 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
5999 (defun markdown-move-up ()
6000 "Move list item up.
6001 Calls `markdown-move-list-item-up'."
6002 (interactive)
6003 (markdown-move-list-item-up))
6005 (defun markdown-move-down ()
6006 "Move list item down.
6007 Calls `markdown-move-list-item-down'."
6008 (interactive)
6009 (markdown-move-list-item-down))
6011 (defun markdown-promote ()
6012 "Either promote header or list item at point or cycle markup.
6013 See `markdown-cycle-atx', `markdown-cycle-setext', and
6014 `markdown-promote-list-item'."
6015 (interactive)
6016 (let (bounds)
6017 (cond
6018 ;; Promote atx header
6019 ((thing-at-point-looking-at markdown-regex-header-atx)
6020 (markdown-cycle-atx -1))
6021 ;; Promote setext header
6022 ((thing-at-point-looking-at markdown-regex-header-setext)
6023 (markdown-cycle-setext -1))
6024 ;; Promote horizonal rule
6025 ((thing-at-point-looking-at markdown-regex-hr)
6026 (markdown-cycle-hr -1))
6027 ;; Promote list item
6028 ((setq bounds (markdown-cur-list-item-bounds))
6029 (markdown-promote-list-item bounds))
6030 ;; Promote bold
6031 ((thing-at-point-looking-at markdown-regex-bold)
6032 (markdown-cycle-bold))
6033 ;; Promote italic
6034 ((thing-at-point-looking-at markdown-regex-italic)
6035 (markdown-cycle-italic))
6037 (error "Nothing to promote at point")))))
6039 (defun markdown-demote ()
6040 "Either demote header or list item at point or cycle or remove markup.
6041 See `markdown-cycle-atx', `markdown-cycle-setext', and
6042 `markdown-demote-list-item'."
6043 (interactive)
6044 (let (bounds)
6045 (cond
6046 ;; Demote atx header
6047 ((thing-at-point-looking-at markdown-regex-header-atx)
6048 (markdown-cycle-atx 1))
6049 ;; Demote setext header
6050 ((thing-at-point-looking-at markdown-regex-header-setext)
6051 (markdown-cycle-setext 1))
6052 ;; Demote horizonal rule
6053 ((thing-at-point-looking-at markdown-regex-hr)
6054 (markdown-cycle-hr 1))
6055 ;; Demote list item
6056 ((setq bounds (markdown-cur-list-item-bounds))
6057 (markdown-demote-list-item bounds))
6058 ;; Demote bold
6059 ((thing-at-point-looking-at markdown-regex-bold)
6060 (markdown-cycle-bold))
6061 ;; Demote italic
6062 ((thing-at-point-looking-at markdown-regex-italic)
6063 (markdown-cycle-italic))
6065 (error "Nothing to demote at point")))))
6068 ;;; Commands ==================================================================
6070 (defun markdown (&optional output-buffer-name)
6071 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
6072 The output buffer name defaults to `markdown-output-buffer-name'.
6073 Return the name of the output buffer used."
6074 (interactive)
6075 (save-window-excursion
6076 (let ((begin-region)
6077 (end-region))
6078 (if (markdown-use-region-p)
6079 (setq begin-region (region-beginning)
6080 end-region (region-end))
6081 (setq begin-region (point-min)
6082 end-region (point-max)))
6084 (unless output-buffer-name
6085 (setq output-buffer-name markdown-output-buffer-name))
6086 (cond
6087 ;; Handle case when `markdown-command' does not read from stdin
6088 (markdown-command-needs-filename
6089 (if (not buffer-file-name)
6090 (error "Must be visiting a file")
6091 (shell-command (concat markdown-command " "
6092 (shell-quote-argument buffer-file-name))
6093 output-buffer-name)))
6094 ;; Pass region to `markdown-command' via stdin
6096 (let ((buf (get-buffer-create output-buffer-name)))
6097 (with-current-buffer buf
6098 (setq buffer-read-only nil)
6099 (erase-buffer))
6100 (call-process-region begin-region end-region
6101 shell-file-name nil buf nil
6102 shell-command-switch markdown-command)))))
6103 output-buffer-name))
6105 (defun markdown-standalone (&optional output-buffer-name)
6106 "Special function to provide standalone HTML output.
6107 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
6108 (interactive)
6109 (setq output-buffer-name (markdown output-buffer-name))
6110 (with-current-buffer output-buffer-name
6111 (set-buffer output-buffer-name)
6112 (unless (markdown-output-standalone-p)
6113 (markdown-add-xhtml-header-and-footer output-buffer-name))
6114 (goto-char (point-min))
6115 (html-mode))
6116 output-buffer-name)
6118 (defun markdown-other-window (&optional output-buffer-name)
6119 "Run `markdown-command' on current buffer and display in other window.
6120 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
6121 that name."
6122 (interactive)
6123 (markdown-display-buffer-other-window
6124 (markdown-standalone output-buffer-name)))
6126 (defun markdown-output-standalone-p ()
6127 "Determine whether `markdown-command' output is standalone XHTML.
6128 Standalone XHTML output is identified by an occurrence of
6129 `markdown-xhtml-standalone-regexp' in the first five lines of output."
6130 (save-excursion
6131 (goto-char (point-min))
6132 (re-search-forward
6133 markdown-xhtml-standalone-regexp
6134 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
6135 t)))
6137 (defun markdown-stylesheet-link-string (stylesheet-path)
6138 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
6139 stylesheet-path
6140 "\" />"))
6142 (defun markdown-add-xhtml-header-and-footer (title)
6143 "Wrap XHTML header and footer with given TITLE around current buffer."
6144 (goto-char (point-min))
6145 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
6146 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
6147 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
6148 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
6149 "<head>\n<title>")
6150 (insert title)
6151 (insert "</title>\n")
6152 (when (> (length markdown-content-type) 0)
6153 (insert
6154 (format
6155 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
6156 markdown-content-type
6157 (or (and markdown-coding-system
6158 (fboundp 'coding-system-get)
6159 (coding-system-get markdown-coding-system
6160 'mime-charset))
6161 (and (fboundp 'coding-system-get)
6162 (coding-system-get buffer-file-coding-system
6163 'mime-charset))
6164 "iso-8859-1"))))
6165 (if (> (length markdown-css-paths) 0)
6166 (insert (mapconcat #'markdown-stylesheet-link-string
6167 markdown-css-paths "\n")))
6168 (when (> (length markdown-xhtml-header-content) 0)
6169 (insert markdown-xhtml-header-content))
6170 (insert "\n</head>\n\n"
6171 "<body>\n\n")
6172 (goto-char (point-max))
6173 (insert "\n"
6174 "</body>\n"
6175 "</html>\n"))
6177 (defun markdown-preview (&optional output-buffer-name)
6178 "Run `markdown-command' on the current buffer and view output in browser.
6179 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
6180 that name."
6181 (interactive)
6182 (browse-url-of-buffer
6183 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
6185 (defun markdown-export-file-name (&optional extension)
6186 "Attempt to generate a filename for Markdown output.
6187 The file extension will be EXTENSION if given, or .html by default.
6188 If the current buffer is visiting a file, we construct a new
6189 output filename based on that filename. Otherwise, return nil."
6190 (when (buffer-file-name)
6191 (unless extension
6192 (setq extension ".html"))
6193 (let ((candidate
6194 (concat
6195 (cond
6196 ((buffer-file-name)
6197 (file-name-sans-extension (buffer-file-name)))
6198 (t (buffer-name)))
6199 extension)))
6200 (cond
6201 ((equal candidate (buffer-file-name))
6202 (concat candidate extension))
6204 candidate)))))
6206 (defun markdown-export (&optional output-file)
6207 "Run Markdown on the current buffer, save to file, and return the filename.
6208 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
6209 generated by `markdown-export-file-name', which will be constructed using the
6210 current filename, but with the extension removed and replaced with .html."
6211 (interactive)
6212 (unless output-file
6213 (setq output-file (markdown-export-file-name ".html")))
6214 (when output-file
6215 (let* ((init-buf (current-buffer))
6216 (init-point (point))
6217 (init-buf-string (buffer-string))
6218 (output-buffer (find-file-noselect output-file))
6219 (output-buffer-name (buffer-name output-buffer)))
6220 (run-hooks 'markdown-before-export-hook)
6221 (markdown-standalone output-buffer-name)
6222 (with-current-buffer output-buffer
6223 (run-hooks 'markdown-after-export-hook)
6224 (save-buffer))
6225 ;; if modified, restore initial buffer
6226 (when (buffer-modified-p init-buf)
6227 (erase-buffer)
6228 (insert init-buf-string)
6229 (save-buffer)
6230 (goto-char init-point))
6231 output-file)))
6233 (defun markdown-export-and-preview ()
6234 "Export to XHTML using `markdown-export' and browse the resulting file."
6235 (interactive)
6236 (browse-url-of-file (markdown-export)))
6238 (defvar markdown-live-preview-buffer nil
6239 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
6240 (make-variable-buffer-local 'markdown-live-preview-buffer)
6242 (defvar markdown-live-preview-source-buffer nil
6243 "Source buffer from which current buffer was generated.
6244 This is the inverse of `markdown-live-preview-buffer'.")
6245 (make-variable-buffer-local 'markdown-live-preview-source-buffer)
6247 (defvar markdown-live-preview-currently-exporting nil)
6249 (defun markdown-live-preview-get-filename ()
6250 "Standardize the filename exported by `markdown-live-preview-export'."
6251 (markdown-export-file-name ".html"))
6253 (defun markdown-live-preview-window-eww (file)
6254 "Preview FILE with eww.
6255 To be used with `markdown-live-preview-window-function'."
6256 (if (require 'eww nil t)
6257 (progn
6258 (eww-open-file file)
6259 (get-buffer "*eww*"))
6260 (error "EWW is not present or not loaded on this version of Emacs")))
6262 (defun markdown-visual-lines-between-points (beg end)
6263 (save-excursion
6264 (goto-char beg)
6265 (cl-loop with count = 0
6266 while (progn (end-of-visual-line)
6267 (and (< (point) end) (line-move-visual 1 t)))
6268 do (cl-incf count)
6269 finally return count)))
6271 (defun markdown-live-preview-window-serialize (buf)
6272 "Get window point and scroll data for all windows displaying BUF."
6273 (when (buffer-live-p buf)
6274 (with-current-buffer buf
6275 (mapcar
6276 (lambda (win)
6277 (with-selected-window win
6278 (let* ((start (window-start))
6279 (pt (window-point))
6280 (pt-or-sym (cond ((= pt (point-min)) 'min)
6281 ((= pt (point-max)) 'max)
6282 (t pt)))
6283 (diff (markdown-visual-lines-between-points
6284 start pt)))
6285 (list win pt-or-sym diff))))
6286 (get-buffer-window-list buf)))))
6288 (defun markdown-get-point-back-lines (pt num-lines)
6289 (save-excursion
6290 (goto-char pt)
6291 (line-move-visual (- num-lines) t)
6292 ;; in testing, can occasionally overshoot the number of lines to traverse
6293 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
6294 (when (> actual-num-lines num-lines)
6295 (line-move-visual (- actual-num-lines num-lines) t)))
6296 (point)))
6298 (defun markdown-live-preview-window-deserialize (window-posns)
6299 "Apply window point and scroll data from WINDOW-POSNS.
6300 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
6301 (cl-destructuring-bind (win pt-or-sym diff) window-posns
6302 (when (window-live-p win)
6303 (with-current-buffer markdown-live-preview-buffer
6304 (set-window-buffer win (current-buffer))
6305 (cl-destructuring-bind (actual-pt actual-diff)
6306 (cl-case pt-or-sym
6307 (min (list (point-min) 0))
6308 (max (list (point-max) diff))
6309 (t (list pt-or-sym diff)))
6310 (set-window-start
6311 win (markdown-get-point-back-lines actual-pt actual-diff))
6312 (set-window-point win actual-pt))))))
6314 (defun markdown-live-preview-export ()
6315 "Export to XHTML using `markdown-export'.
6316 Browse the resulting file within Emacs using
6317 `markdown-live-preview-window-function' Return the buffer
6318 displaying the rendered output."
6319 (interactive)
6320 (let* ((markdown-live-preview-currently-exporting t)
6321 (cur-buf (current-buffer))
6322 (export-file (markdown-export (markdown-live-preview-get-filename)))
6323 ;; get positions in all windows currently displaying output buffer
6324 (window-data
6325 (markdown-live-preview-window-serialize
6326 markdown-live-preview-buffer)))
6327 (save-window-excursion
6328 (let ((output-buffer
6329 (funcall markdown-live-preview-window-function export-file)))
6330 (with-current-buffer output-buffer
6331 (setq markdown-live-preview-source-buffer cur-buf)
6332 (add-hook 'kill-buffer-hook
6333 #'markdown-live-preview-remove-on-kill t t))
6334 (with-current-buffer cur-buf
6335 (setq markdown-live-preview-buffer output-buffer))))
6336 (with-current-buffer cur-buf
6337 ;; reset all windows displaying output buffer to where they were,
6338 ;; now with the new output
6339 (mapc #'markdown-live-preview-window-deserialize window-data)
6340 ;; delete html editing buffer
6341 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
6342 (when (and export-file (file-exists-p export-file)
6343 (eq markdown-live-preview-delete-export
6344 'delete-on-export))
6345 (delete-file export-file))
6346 markdown-live-preview-buffer)))
6348 (defun markdown-live-preview-remove ()
6349 (when (buffer-live-p markdown-live-preview-buffer)
6350 (kill-buffer markdown-live-preview-buffer))
6351 (setq markdown-live-preview-buffer nil)
6352 ;; if set to 'delete-on-export, the output has already been deleted
6353 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
6354 (let ((outfile-name (markdown-live-preview-get-filename)))
6355 (when (file-exists-p outfile-name)
6356 (delete-file outfile-name)))))
6358 (defun markdown-display-buffer-other-window (buf)
6359 (let ((cur-buf (current-buffer))
6360 split-width-threshold split-height-threshold)
6361 (cond ((memq markdown-split-window-direction '(vertical below))
6362 (setq split-width-threshold nil)
6363 (setq split-height-threshold 0))
6364 ((memq markdown-split-window-direction '(horizontal right))
6365 (setq split-width-threshold 0)
6366 (setq split-height-threshold nil)))
6367 (switch-to-buffer-other-window buf)
6368 (set-buffer cur-buf)))
6370 (defun markdown-live-preview-if-markdown ()
6371 (when (and (derived-mode-p 'markdown-mode)
6372 markdown-live-preview-mode)
6373 (unless markdown-live-preview-currently-exporting
6374 (if (buffer-live-p markdown-live-preview-buffer)
6375 (markdown-live-preview-export)
6376 (markdown-display-buffer-other-window
6377 (markdown-live-preview-export))))))
6379 (defun markdown-live-preview-remove-on-kill ()
6380 (cond ((and (derived-mode-p 'markdown-mode)
6381 markdown-live-preview-mode)
6382 (markdown-live-preview-remove))
6383 (markdown-live-preview-source-buffer
6384 (with-current-buffer markdown-live-preview-source-buffer
6385 (setq markdown-live-preview-buffer nil))
6386 (setq markdown-live-preview-source-buffer nil))))
6388 (defun markdown-live-preview-switch-to-output ()
6389 "Switch to output buffer."
6390 (interactive)
6391 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
6392 output buffer in another window."
6393 (if markdown-live-preview-mode
6394 (markdown-display-buffer-other-window (markdown-live-preview-export)))
6395 (markdown-live-preview-mode))
6397 (defun markdown-live-preview-re-export ()
6398 "Re export source buffer."
6399 (interactive)
6400 "If the current buffer is a buffer displaying the exported version of a
6401 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
6402 update this buffer's contents."
6403 (when markdown-live-preview-source-buffer
6404 (with-current-buffer markdown-live-preview-source-buffer
6405 (markdown-live-preview-export))))
6407 (defun markdown-open ()
6408 "Open file for the current buffer with `markdown-open-command'."
6409 (interactive)
6410 (if (not markdown-open-command)
6411 (error "Variable `markdown-open-command' must be set")
6412 (if (not buffer-file-name)
6413 (error "Must be visiting a file")
6414 (call-process markdown-open-command
6415 nil nil nil buffer-file-name))))
6417 (defun markdown-kill-ring-save ()
6418 "Run Markdown on file and store output in the kill ring."
6419 (interactive)
6420 (save-window-excursion
6421 (markdown)
6422 (with-current-buffer markdown-output-buffer-name
6423 (kill-ring-save (point-min) (point-max)))))
6426 ;;; Links =====================================================================
6428 (defun markdown-link-p ()
6429 "Return non-nil when `point' is at a non-wiki link.
6430 See `markdown-wiki-link-p' for more information."
6431 (let ((case-fold-search nil))
6432 (and (not (markdown-wiki-link-p))
6433 (not (markdown-code-block-at-point-p))
6434 (or (thing-at-point-looking-at markdown-regex-link-inline)
6435 (thing-at-point-looking-at markdown-regex-link-reference)
6436 (thing-at-point-looking-at markdown-regex-uri)
6437 (thing-at-point-looking-at markdown-regex-angle-uri)))))
6439 (defun markdown-link-link ()
6440 "Return the link part of the regular (non-wiki) link at point.
6441 Works with both inline and reference style links. If point is
6442 not at a link or the link reference is not defined returns nil."
6443 (cond
6444 ((thing-at-point-looking-at markdown-regex-link-inline)
6445 (match-string-no-properties 6))
6446 ((thing-at-point-looking-at markdown-regex-link-reference)
6447 (let* ((text (match-string-no-properties 3))
6448 (reference (match-string-no-properties 6))
6449 (target (downcase (if (string= reference "") text reference))))
6450 (car (markdown-reference-definition target))))
6451 ((thing-at-point-looking-at markdown-regex-uri)
6452 (match-string-no-properties 0))
6453 ((thing-at-point-looking-at markdown-regex-angle-uri)
6454 (match-string-no-properties 2))
6455 (t nil)))
6457 (defun markdown-follow-link-at-point ()
6458 "Open the current non-wiki link.
6459 If the link is a complete URL, open in browser with `browse-url'.
6460 Otherwise, open with `find-file' after stripping anchor and/or query string."
6461 (interactive)
6462 (if (markdown-link-p)
6463 (let* ((link (markdown-link-link))
6464 (struct (url-generic-parse-url link))
6465 (full (url-fullness struct))
6466 (file link))
6467 ;; Parse URL, determine fullness, strip query string
6468 (if (fboundp 'url-path-and-query)
6469 (setq file (car (url-path-and-query struct)))
6470 (when (and (setq file (url-filename struct))
6471 (string-match "\\?" file))
6472 (setq file (substring file 0 (match-beginning 0)))))
6473 ;; Open full URLs in browser, files in Emacs
6474 (if full
6475 (browse-url link)
6476 (when (and file (> (length file) 0)) (find-file file))))
6477 (error "Point is not at a Markdown link or URI")))
6480 ;;; WikiLink Following/Markup =================================================
6482 (defun markdown-wiki-link-p ()
6483 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
6484 A true wiki link name matches `markdown-regex-wiki-link' but does
6485 not match the current file name after conversion. This modifies
6486 the data returned by `match-data'. Note that the potential wiki
6487 link name must be available via `match-string'."
6488 (when markdown-enable-wiki-links
6489 (let ((case-fold-search nil))
6490 (and (thing-at-point-looking-at markdown-regex-wiki-link)
6491 (not (markdown-code-block-at-point-p))
6492 (or (not buffer-file-name)
6493 (not (string-equal (buffer-file-name)
6494 (markdown-convert-wiki-link-to-filename
6495 (markdown-wiki-link-link)))))))))
6497 (defun markdown-wiki-link-link ()
6498 "Return the link part of the wiki link using current match data.
6499 The location of the link component depends on the value of
6500 `markdown-wiki-link-alias-first'."
6501 (if markdown-wiki-link-alias-first
6502 (or (match-string-no-properties 5) (match-string-no-properties 3))
6503 (match-string-no-properties 3)))
6505 (defun markdown-wiki-link-alias ()
6506 "Return the alias or text part of the wiki link using current match data.
6507 The location of the alias component depends on the value of
6508 `markdown-wiki-link-alias-first'."
6509 (if markdown-wiki-link-alias-first
6510 (match-string-no-properties 3)
6511 (or (match-string-no-properties 5) (match-string-no-properties 3))))
6513 (defun markdown-convert-wiki-link-to-filename (name)
6514 "Generate a filename from the wiki link NAME.
6515 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
6516 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
6517 and [[test test]] both map to Test-test.ext. Look in the current
6518 directory first, then in subdirectories if
6519 `markdown-wiki-link-search-subdirectories' is non-nil, and then
6520 in parent directories if
6521 `markdown-wiki-link-search-parent-directories' is non-nil."
6522 (let* ((basename (markdown-replace-regexp-in-string
6523 "[[:space:]\n]" markdown-link-space-sub-char name))
6524 (basename (if (eq major-mode 'gfm-mode)
6525 (concat (upcase (substring basename 0 1))
6526 (downcase (substring basename 1 nil)))
6527 basename))
6528 directory extension default candidates dir)
6529 (when buffer-file-name
6530 (setq directory (file-name-directory buffer-file-name)
6531 extension (file-name-extension buffer-file-name)))
6532 (setq default (concat basename
6533 (when extension (concat "." extension))))
6534 (cond
6535 ;; Look in current directory first.
6536 ((or (null buffer-file-name)
6537 (file-exists-p default))
6538 default)
6539 ;; Possibly search in subdirectories, next.
6540 ((and markdown-wiki-link-search-subdirectories
6541 (setq candidates
6542 (markdown-directory-files-recursively
6543 directory (concat "^" default "$"))))
6544 (car candidates))
6545 ;; Possibly search in parent directories as a last resort.
6546 ((and markdown-wiki-link-search-parent-directories
6547 (setq dir (locate-dominating-file directory default)))
6548 (concat dir default))
6549 ;; If nothing is found, return default in current directory.
6550 (t default))))
6552 (defun markdown-follow-wiki-link (name &optional other)
6553 "Follow the wiki link NAME.
6554 Convert the name to a file name and call `find-file'. Ensure that
6555 the new buffer remains in `markdown-mode'. Open the link in another
6556 window when OTHER is non-nil."
6557 (let ((filename (markdown-convert-wiki-link-to-filename name))
6558 (wp (when buffer-file-name
6559 (file-name-directory buffer-file-name))))
6560 (if (not wp)
6561 (error "Must be visiting a file")
6562 (when other (other-window 1))
6563 (let ((default-directory wp))
6564 (find-file filename)))
6565 (when (not (eq major-mode 'markdown-mode))
6566 (markdown-mode))))
6568 (defun markdown-follow-wiki-link-at-point (&optional arg)
6569 "Find Wiki Link at point.
6570 With prefix argument ARG, open the file in other window.
6571 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
6572 (interactive "P")
6573 (if (markdown-wiki-link-p)
6574 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
6575 (error "Point is not at a Wiki Link")))
6577 (defun markdown-highlight-wiki-link (from to face)
6578 "Highlight the wiki link in the region between FROM and TO using FACE."
6579 (put-text-property from to 'font-lock-face face))
6581 (defun markdown-unfontify-region-wiki-links (from to)
6582 "Remove wiki link faces from the region specified by FROM and TO."
6583 (interactive "*r")
6584 (let ((modified (buffer-modified-p)))
6585 (remove-text-properties from to '(font-lock-face markdown-link-face))
6586 (remove-text-properties from to '(font-lock-face markdown-missing-link-face))
6587 ;; remove-text-properties marks the buffer modified in emacs 24.3,
6588 ;; undo that if it wasn't originally marked modified
6589 (set-buffer-modified-p modified)))
6591 (defun markdown-fontify-region-wiki-links (from to)
6592 "Search region given by FROM and TO for wiki links and fontify them.
6593 If a wiki link is found check to see if the backing file exists
6594 and highlight accordingly."
6595 (goto-char from)
6596 (save-match-data
6597 (while (re-search-forward markdown-regex-wiki-link to t)
6598 (when (not (markdown-code-block-at-point-p))
6599 (let ((highlight-beginning (match-beginning 1))
6600 (highlight-end (match-end 1))
6601 (file-name
6602 (markdown-convert-wiki-link-to-filename
6603 (markdown-wiki-link-link))))
6604 (if (condition-case nil (file-exists-p file-name) (error nil))
6605 (markdown-highlight-wiki-link
6606 highlight-beginning highlight-end markdown-link-face)
6607 (markdown-highlight-wiki-link
6608 highlight-beginning highlight-end markdown-missing-link-face)))))))
6610 (defun markdown-extend-changed-region (from to)
6611 "Extend region given by FROM and TO so that we can fontify all links.
6612 The region is extended to the first newline before and the first
6613 newline after."
6614 ;; start looking for the first new line before 'from
6615 (goto-char from)
6616 (re-search-backward "\n" nil t)
6617 (let ((new-from (point-min))
6618 (new-to (point-max)))
6619 (if (not (= (point) from))
6620 (setq new-from (point)))
6621 ;; do the same thing for the first new line after 'to
6622 (goto-char to)
6623 (re-search-forward "\n" nil t)
6624 (if (not (= (point) to))
6625 (setq new-to (point)))
6626 (cl-values new-from new-to)))
6628 (defun markdown-check-change-for-wiki-link (from to)
6629 "Check region between FROM and TO for wiki links and re-fontify as needed."
6630 (interactive "*r")
6631 (let* ((modified (buffer-modified-p))
6632 (buffer-undo-list t)
6633 (inhibit-read-only t)
6634 (inhibit-point-motion-hooks t)
6635 deactivate-mark
6636 buffer-file-truename)
6637 (unwind-protect
6638 (save-excursion
6639 (save-match-data
6640 (save-restriction
6641 ;; Extend the region to fontify so that it starts
6642 ;; and ends at safe places.
6643 (cl-multiple-value-bind (new-from new-to)
6644 (markdown-extend-changed-region from to)
6645 (goto-char new-from)
6646 ;; Only refontify when the range contains text with a
6647 ;; wiki link face or if the wiki link regexp matches.
6648 (when (or (markdown-range-property-any
6649 new-from new-to 'font-lock-face
6650 (list markdown-link-face
6651 markdown-missing-link-face))
6652 (re-search-forward
6653 markdown-regex-wiki-link new-to t))
6654 ;; Unfontify existing fontification (start from scratch)
6655 (markdown-unfontify-region-wiki-links new-from new-to)
6656 ;; Now do the fontification.
6657 (markdown-fontify-region-wiki-links new-from new-to))))))
6658 (and (not modified)
6659 (buffer-modified-p)
6660 (set-buffer-modified-p nil)))))
6662 (defun markdown-check-change-for-wiki-link-after-change (from to _)
6663 "Check region between FROM and TO for wiki links and re-fontify as needed.
6664 Designed to be used with the `after-change-functions' hook."
6665 (markdown-check-change-for-wiki-link from to))
6667 (defun markdown-fontify-buffer-wiki-links ()
6668 "Refontify all wiki links in the buffer."
6669 (interactive)
6670 (markdown-check-change-for-wiki-link (point-min) (point-max)))
6673 ;;; Following and Jumping =====================================================
6675 (defun markdown-follow-thing-at-point (arg)
6676 "Follow thing at point if possible, such as a reference link or wiki link.
6677 Opens inline and reference links in a browser. Opens wiki links
6678 to other files in the current window, or the another window if
6679 ARG is non-nil.
6680 See `markdown-follow-link-at-point' and
6681 `markdown-follow-wiki-link-at-point'."
6682 (interactive "P")
6683 (cond ((markdown-link-p)
6684 (markdown-follow-link-at-point))
6685 ((markdown-wiki-link-p)
6686 (markdown-follow-wiki-link-at-point arg))
6688 (error "Nothing to follow at point"))))
6690 (defun markdown-jump ()
6691 "Jump to another location based on context at point.
6692 Jumps between reference links and definitions; between footnote
6693 markers and footnote text."
6694 (interactive)
6695 (cond ((markdown-footnote-text-positions)
6696 (markdown-footnote-return))
6697 ((markdown-footnote-marker-positions)
6698 (markdown-footnote-goto-text))
6699 ((thing-at-point-looking-at markdown-regex-link-reference)
6700 (markdown-reference-goto-definition))
6701 ((thing-at-point-looking-at markdown-regex-reference-definition)
6702 (markdown-reference-goto-link (match-string-no-properties 2)))
6704 (error "Nothing to jump to from context at point"))))
6707 ;;; Miscellaneous =============================================================
6709 (defun markdown-compress-whitespace-string (str)
6710 "Compress whitespace in STR and return result.
6711 Leading and trailing whitespace is removed. Sequences of multiple
6712 spaces, tabs, and newlines are replaced with single spaces."
6713 (markdown-replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
6714 (markdown-replace-regexp-in-string "[ \t\n]+" " " str)))
6716 (defun markdown-line-number-at-pos (&optional pos)
6717 "Return (narrowed) buffer line number at position POS.
6718 If POS is nil, use current buffer location.
6719 This is an exact copy of `line-number-at-pos' for use in emacs21."
6720 (let ((opoint (or pos (point))) start)
6721 (save-excursion
6722 (goto-char (point-min))
6723 (setq start (point))
6724 (goto-char opoint)
6725 (forward-line 0)
6726 (1+ (count-lines start (point))))))
6728 (defun markdown-inside-link-p ()
6729 "Return t if point is within a link."
6730 (save-match-data
6731 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
6733 (defun markdown-line-is-reference-definition-p ()
6734 "Return whether the current line is a (non-footnote) reference defition."
6735 (save-excursion
6736 (move-beginning-of-line 1)
6737 (and (looking-at-p markdown-regex-reference-definition)
6738 (not (looking-at-p "[ \t]*\\[^")))))
6740 (defun markdown-adaptive-fill-function ()
6741 "Return prefix for filling paragraph or nil if not determined."
6742 (cond
6743 ;; List item inside blockquote
6744 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
6745 (markdown-replace-regexp-in-string
6746 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
6747 ;; Blockquote
6748 ((looking-at "^[ \t]*>[ \t]*")
6749 (match-string-no-properties 0))
6750 ;; List items
6751 ((looking-at markdown-regex-list)
6752 (match-string-no-properties 0))
6753 ((looking-at-p markdown-regex-footnote-definition)
6754 " ") ; four spaces
6755 ;; No match
6756 (t nil)))
6758 (defun markdown-fill-paragraph (&optional justify)
6759 "Fill paragraph at or after point.
6760 This function is like \\[fill-paragraph], but it skips Markdown
6761 code blocks. If the point is in a code block, or just before one,
6762 do not fill. Otherwise, call `fill-paragraph' as usual. If
6763 JUSTIFY is non-nil, justify text as well. Since this function
6764 handles filling itself, it always returns t so that
6765 `fill-paragraph' doesn't run."
6766 (interactive "P")
6767 (unless (or (markdown-code-block-at-point-p)
6768 (save-excursion
6769 (back-to-indentation)
6770 (skip-syntax-forward "-")
6771 (markdown-code-block-at-point-p)))
6772 (fill-paragraph justify))
6775 (defun markdown-fill-forward-paragraph-function (&optional arg)
6776 "Function used by `fill-paragraph' to move over ARG paragraphs.
6777 This is a `fill-forward-paragraph-function' for `markdown-mode'.
6778 It is called with a single argument specifying the number of
6779 paragraphs to move. Just like `forward-paragraph', it should
6780 return the number of paragraphs left to move."
6781 (let* ((arg (or arg 1))
6782 (paragraphs-remaining (forward-paragraph arg))
6783 (start (point)))
6784 (when (< arg 0)
6785 (while (and (not (eobp))
6786 (progn (move-to-left-margin) (not (eobp)))
6787 (looking-at-p paragraph-separate))
6788 (forward-line 1))
6789 (if (looking-at markdown-regex-list)
6790 (forward-char (length (match-string 0)))
6791 (goto-char start)))
6792 paragraphs-remaining))
6795 ;;; Extension Framework =======================================================
6797 (defun markdown-reload-extensions ()
6798 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
6799 (interactive)
6800 (when (eq major-mode 'markdown-mode)
6801 ;; Update font lock keywords with extensions
6802 (setq markdown-mode-font-lock-keywords
6803 (append
6804 (markdown-mode-font-lock-keywords-math)
6805 markdown-mode-font-lock-keywords-basic
6806 (markdown-mode-font-lock-keywords-wiki-links)))
6807 ;; Update font lock defaults
6808 (setq font-lock-defaults
6809 '(markdown-mode-font-lock-keywords
6810 nil nil nil nil
6811 (font-lock-syntactic-face-function . markdown-syntactic-face)))
6812 ;; Refontify buffer
6813 (when (and font-lock-mode (fboundp 'font-lock-refresh-defaults))
6814 (font-lock-refresh-defaults))
6816 ;; Add or remove hooks related to extensions
6817 (markdown-setup-wiki-link-hooks)))
6819 (defun markdown-handle-local-variables ()
6820 "Run in `hack-local-variables-hook' to update font lock rules.
6821 Checks to see if there is actually a ‘markdown-mode’ file local variable
6822 before regenerating font-lock rules for extensions."
6823 (when (and (boundp 'file-local-variables-alist)
6824 (assoc 'markdown-enable-wiki-links file-local-variables-alist)
6825 (assoc 'markdown-enable-math file-local-variables-alist))
6826 (markdown-reload-extensions)))
6829 ;;; Wiki Links ================================================================
6831 (defun markdown-toggle-wiki-links (&optional arg)
6832 "Toggle support for wiki links.
6833 With a prefix argument ARG, enable wiki link support if ARG is positive,
6834 and disable it otherwise."
6835 (interactive (list (or current-prefix-arg 'toggle)))
6836 (setq markdown-enable-wiki-links
6837 (if (eq arg 'toggle)
6838 (not markdown-enable-wiki-links)
6839 (> (prefix-numeric-value arg) 0)))
6840 (if markdown-enable-wiki-links
6841 (message "markdown-mode wiki link support enabled")
6842 (message "markdown-mode wiki link support disabled"))
6843 (markdown-reload-extensions))
6845 (defun markdown-setup-wiki-link-hooks ()
6846 "Add or remove hooks for fontifying wiki links.
6847 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
6848 ;; Anytime text changes make sure it gets fontified correctly
6849 (if (and markdown-enable-wiki-links
6850 markdown-wiki-link-fontify-missing)
6851 (add-hook 'after-change-functions
6852 'markdown-check-change-for-wiki-link-after-change t t)
6853 (remove-hook 'after-change-functions
6854 'markdown-check-change-for-wiki-link-after-change t))
6855 ;; If we left the buffer there is a really good chance we were
6856 ;; creating one of the wiki link documents. Make sure we get
6857 ;; refontified when we come back.
6858 (if (and markdown-enable-wiki-links
6859 markdown-wiki-link-fontify-missing)
6860 (progn
6861 (add-hook 'window-configuration-change-hook
6862 'markdown-fontify-buffer-wiki-links t t)
6863 (markdown-fontify-buffer-wiki-links))
6864 (remove-hook 'window-configuration-change-hook
6865 'markdown-fontify-buffer-wiki-links t)
6866 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
6868 (defun markdown-mode-font-lock-keywords-wiki-links ()
6869 "Return wiki-link lock keywords if support is enabled.
6870 If `markdown-wiki-link-fontify-missing' is also enabled, we use
6871 hooks in `markdown-setup-wiki-link-hooks' for fontification instead."
6872 (when (and markdown-enable-wiki-links
6873 (not markdown-wiki-link-fontify-missing))
6874 (list
6875 (cons markdown-regex-wiki-link '((1 markdown-link-face prepend))))))
6878 ;;; Math Support ==============================================================
6880 (make-obsolete 'markdown-enable-math 'markdown-toggle-math "v2.1")
6882 (defun markdown-toggle-math (&optional arg)
6883 "Toggle support for inline and display LaTeX math expressions.
6884 With a prefix argument ARG, enable math mode if ARG is positive,
6885 and disable it otherwise. If called from Lisp, enable the mode
6886 if ARG is omitted or nil."
6887 (interactive (list (or current-prefix-arg 'toggle)))
6888 (setq markdown-enable-math
6889 (if (eq arg 'toggle)
6890 (not markdown-enable-math)
6891 (> (prefix-numeric-value arg) 0)))
6892 (if markdown-enable-math
6893 (message "markdown-mode math support enabled")
6894 (message "markdown-mode math support disabled"))
6895 (markdown-reload-extensions))
6897 (defun markdown-mode-font-lock-keywords-math ()
6898 "Return math font lock keywords if support is enabled."
6899 (when markdown-enable-math
6900 (list
6901 ;; Display mode equations with brackets: \[ \]
6902 (cons markdown-regex-math-display '((1 markdown-markup-face prepend)
6903 (2 markdown-math-face append)
6904 (3 markdown-markup-face prepend)))
6905 ;; Equation reference (eq:foo)
6906 (cons "\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" '((1 markdown-markup-face)
6907 (2 markdown-reference-face)
6908 (3 markdown-markup-face)))
6909 ;; Equation reference \eqref{foo}
6910 (cons "\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" '((1 markdown-markup-face)
6911 (2 markdown-reference-face)
6912 (3 markdown-markup-face))))))
6915 ;;; GFM Checkboxes ============================================================
6917 (require 'button)
6919 (define-button-type 'markdown-gfm-checkbox-button
6920 'follow-link t
6921 'face 'markdown-gfm-checkbox-face
6922 'mouse-face 'markdown-highlight-face
6923 'action #'markdown-toggle-gfm-checkbox-button)
6925 (defun markdown-toggle-gfm-checkbox ()
6926 "Toggle GFM checkbox at point."
6927 (interactive)
6928 (save-match-data
6929 (save-excursion
6930 (let ((bounds (markdown-cur-list-item-bounds)))
6931 (when bounds
6932 ;; Move to beginning of task list item
6933 (goto-char (cl-first bounds))
6934 ;; Advance to column of first non-whitespace after marker
6935 (forward-char (cl-fourth bounds))
6936 (cond ((looking-at "\\[ \\]")
6937 (replace-match "[x]" nil t))
6938 ((looking-at "\\[[xX]\\]")
6939 (replace-match "[ ]" nil t))))))))
6941 (defun markdown-toggle-gfm-checkbox-button (button)
6942 "Toggle GFM checkbox BUTTON on click."
6943 (save-match-data
6944 (save-excursion
6945 (goto-char (button-start button))
6946 (markdown-toggle-gfm-checkbox))))
6948 (defun markdown-make-gfm-checkboxes-buttons (start end)
6949 "Make GFM checkboxes buttons in region between START and END."
6950 (save-excursion
6951 (goto-char start)
6952 (let ((case-fold-search t))
6953 (save-excursion
6954 (while (re-search-forward markdown-regex-gfm-checkbox end t)
6955 (make-button (match-beginning 1) (match-end 1)
6956 :type 'markdown-gfm-checkbox-button))))))
6958 ;; Called when any modification is made to buffer text.
6959 (defun markdown-gfm-checkbox-after-change-function (beg end _)
6960 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
6961 BEG and END are the limits of scanned region."
6962 (save-excursion
6963 (save-match-data
6964 ;; Rescan between start of line from `beg' and start of line after `end'.
6965 (markdown-make-gfm-checkboxes-buttons
6966 (progn (goto-char beg) (beginning-of-line) (point))
6967 (progn (goto-char end) (forward-line 1) (point))))))
6970 ;;; Display inline image =================================================
6972 (defvar markdown-inline-image-overlays nil)
6973 (make-variable-buffer-local 'markdown-inline-image-overlays)
6975 (defun markdown-remove-inline-images ()
6976 "Remove inline image overlays from image links in the buffer.
6977 This can be toggled with `markdown-toggle-inline-images'
6978 or \\[markdown-toggle-inline-images]."
6979 (interactive)
6980 (mapc #'delete-overlay markdown-inline-image-overlays)
6981 (setq markdown-inline-image-overlays nil))
6983 (defun markdown-display-inline-images ()
6984 "Add inline image overlays to image links in the buffer.
6985 This can be toggled with `markdown-toggle-inline-images'
6986 or \\[markdown-toggle-inline-images]."
6987 (interactive)
6988 (unless (display-graphic-p)
6989 (error "Cannot show images"))
6990 (save-excursion
6991 (save-restriction
6992 (widen)
6993 (goto-char (point-min))
6994 (while (re-search-forward markdown-regex-link-inline nil t)
6995 (let ((start (match-beginning 0))
6996 (end (match-end 0))
6997 (file (match-string-no-properties 6)))
6998 (when (file-exists-p file)
6999 (let* ((abspath (if (file-name-absolute-p file)
7000 file
7001 (concat default-directory file)))
7002 (image (create-image abspath)))
7003 (when image
7004 (let ((ov (make-overlay start end)))
7005 (overlay-put ov 'display image)
7006 (overlay-put ov 'face 'default)
7007 (push ov markdown-inline-image-overlays))))))))))
7009 (defun markdown-toggle-inline-images ()
7010 "Toggle inline image overlays in the buffer."
7011 (interactive)
7012 (if markdown-inline-image-overlays
7013 (markdown-remove-inline-images)
7014 (markdown-display-inline-images)))
7017 ;;; Mode Definition ==========================================================
7019 (defun markdown-show-version ()
7020 "Show the version number in the minibuffer."
7021 (interactive)
7022 (message "markdown-mode, version %s" markdown-mode-version))
7024 (defun markdown-mode-info ()
7025 "Open the `markdown-mode' homepage."
7026 (interactive)
7027 (browse-url "http://jblevins.org/projects/markdown-mode/"))
7029 ;;;###autoload
7030 (define-derived-mode markdown-mode text-mode "Markdown"
7031 "Major mode for editing Markdown files."
7032 ;; Natural Markdown tab width
7033 (setq tab-width 4)
7034 ;; Comments
7035 (make-local-variable 'comment-start)
7036 (setq comment-start "<!-- ")
7037 (make-local-variable 'comment-end)
7038 (setq comment-end " -->")
7039 (make-local-variable 'comment-start-skip)
7040 (setq comment-start-skip "<!--[ \t]*")
7041 (make-local-variable 'comment-column)
7042 (setq comment-column 0)
7043 (set (make-local-variable 'comment-auto-fill-only-comments) nil)
7044 ;; Syntax
7045 (add-hook 'syntax-propertize-extend-region-functions
7046 'markdown-syntax-propertize-extend-region)
7047 (add-hook 'jit-lock-after-change-extend-region-functions
7048 'markdown-font-lock-extend-region-function t t)
7049 (set (make-local-variable 'syntax-propertize-function)
7050 'markdown-syntax-propertize)
7051 ;; Font lock.
7052 (set (make-local-variable 'markdown-mode-font-lock-keywords) nil)
7053 (set (make-local-variable 'font-lock-defaults) nil)
7054 (set (make-local-variable 'font-lock-multiline) t)
7055 ;; Extensions
7056 (make-local-variable 'markdown-enable-math)
7057 ;; Reload extensions
7058 (markdown-reload-extensions)
7059 ;; Add a buffer-local hook to reload after file-local variables are read
7060 (add-hook 'hack-local-variables-hook 'markdown-handle-local-variables nil t)
7061 ;; For imenu support
7062 (setq imenu-create-index-function
7063 (if markdown-nested-imenu-heading-index
7064 'markdown-imenu-create-nested-index
7065 'markdown-imenu-create-flat-index))
7066 ;; For menu support in XEmacs
7067 (easy-menu-add markdown-mode-menu markdown-mode-map)
7068 ;; Defun movement
7069 (set (make-local-variable 'beginning-of-defun-function)
7070 'markdown-beginning-of-defun)
7071 (set (make-local-variable 'end-of-defun-function)
7072 'markdown-end-of-defun)
7073 ;; Paragraph filling
7074 (set (make-local-variable 'fill-paragraph-function)
7075 'markdown-fill-paragraph)
7076 (set
7077 ;; Should match start of lines that start or separate paragraphs
7078 (make-local-variable 'paragraph-start)
7079 (mapconcat #'identity
7081 "\f" ; starts with a literal line-feed
7082 "[ \t\f]*$" ; space-only line
7083 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
7084 "[ \t]*[*+-][ \t]+" ; unordered list item
7085 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
7086 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
7087 "[ \t]*:[ \t]+" ; definition
7089 "\\|"))
7090 (set
7091 ;; Should match lines that separate paragraphs without being
7092 ;; part of any paragraph:
7093 (make-local-variable 'paragraph-separate)
7094 (mapconcat #'identity
7095 '("[ \t\f]*$" ; space-only line
7096 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
7097 ;; The following is not ideal, but the Fill customization
7098 ;; options really only handle paragraph-starting prefixes,
7099 ;; not paragraph-ending suffixes:
7100 ".* $" ; line ending in two spaces
7101 "^#+"
7102 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
7103 "\\|"))
7104 (set (make-local-variable 'adaptive-fill-first-line-regexp)
7105 "\\`[ \t]*>[ \t]*?\\'")
7106 (set (make-local-variable 'adaptive-fill-regexp) "\\s-*")
7107 (set (make-local-variable 'adaptive-fill-function)
7108 'markdown-adaptive-fill-function)
7109 (set (make-local-variable 'fill-forward-paragraph-function)
7110 'markdown-fill-forward-paragraph-function)
7111 ;; Outline mode
7112 (make-local-variable 'outline-regexp)
7113 (setq outline-regexp markdown-regex-header)
7114 (make-local-variable 'outline-level)
7115 (setq outline-level 'markdown-outline-level)
7116 ;; Cause use of ellipses for invisible text.
7117 (add-to-invisibility-spec '(outline . t))
7119 ;; Inhibiting line-breaking:
7120 ;; Separating out each condition into a separate function so that users can
7121 ;; override if desired (with remove-hook)
7122 (add-hook 'fill-nobreak-predicate
7123 'markdown-inside-link-p nil t)
7124 (add-hook 'fill-nobreak-predicate
7125 'markdown-line-is-reference-definition-p nil t)
7127 ;; Indentation
7128 (setq indent-line-function markdown-indent-function)
7130 ;; Backwards compatibility with markdown-css-path
7131 (when (boundp 'markdown-css-path)
7132 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
7133 (add-to-list 'markdown-css-paths markdown-css-path))
7135 ;; Prepare hooks for XEmacs compatibility
7136 (when (featurep 'xemacs)
7137 (make-local-hook 'after-change-functions)
7138 (make-local-hook 'font-lock-extend-region-functions)
7139 (make-local-hook 'window-configuration-change-hook))
7141 ;; Initial syntax analysis
7142 (markdown-syntax-propertize (point-min) (point-max))
7144 ;; Make checkboxes buttons
7145 (when markdown-make-gfm-checkboxes-buttons
7146 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
7147 (add-hook 'after-change-functions 'markdown-gfm-checkbox-after-change-function t t))
7149 ;; add live preview export hook
7150 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
7151 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
7153 ;;;###autoload
7154 (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode) t)
7155 ;;;###autoload
7156 (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode) t)
7159 ;;; GitHub Flavored Markdown Mode ============================================
7161 (defvar gfm-mode-hook nil
7162 "Hook run when entering GFM mode.")
7164 (defvar gfm-font-lock-keywords
7165 (append
7166 ;; GFM features to match first
7167 (list
7168 (cons markdown-regex-strike-through '((3 markdown-markup-face)
7169 (4 markdown-strike-through-face)
7170 (5 markdown-markup-face))))
7171 ;; Basic Markdown features (excluding possibly overridden ones)
7172 markdown-mode-font-lock-keywords-basic)
7173 "Default highlighting expressions for GitHub Flavored Markdown mode.")
7175 ;;;###autoload
7176 (define-derived-mode gfm-mode markdown-mode "GFM"
7177 "Major mode for editing GitHub Flavored Markdown files."
7178 (setq markdown-link-space-sub-char "-")
7179 (setq markdown-wiki-link-search-subdirectories t)
7180 (set (make-local-variable 'font-lock-defaults)
7181 '(gfm-font-lock-keywords))
7182 ;; do the initial link fontification
7183 (markdown-gfm-parse-buffer-for-languages))
7186 ;;; Live Preview Mode ============================================
7187 (define-minor-mode markdown-live-preview-mode
7188 "Toggle native previewing on save for a specific markdown file."
7189 :lighter " MD-Preview"
7190 (if markdown-live-preview-mode
7191 (markdown-display-buffer-other-window (markdown-live-preview-export))
7192 (markdown-live-preview-remove)))
7195 (provide 'markdown-mode)
7196 ;; Local Variables:
7197 ;; indent-tabs-mode: nil
7198 ;; End:
7199 ;;; markdown-mode.el ends here