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