Use a list for blockquote display characters
[markdown-mode.git] / markdown-mode.el
blobf0b2269f011f0809fbd3d0055ba4a4a759a0d2b8
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 <jblevins@xbeta.org>
7 ;; Maintainer: Jason R. Blevins <jblevins@xbeta.org>
8 ;; Created: May 24, 2007
9 ;; Version: 2.4-dev
10 ;; Package-Requires: ((emacs "24") (cl-lib "0.5"))
11 ;; Keywords: Markdown, GitHub Flavored Markdown, itex
12 ;; URL: https://jblevins.org/projects/markdown-mode/
14 ;; This file is not part of GNU Emacs.
16 ;; This program is free software; you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
21 ;; This program is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
29 ;;; Commentary:
31 ;; markdown-mode is a major mode for editing [Markdown][]-formatted
32 ;; text. The latest stable version is markdown-mode 2.3, released on
33 ;; August 31, 2017. See the [release notes][] for details.
34 ;; markdown-mode is free software, licensed under the GNU GPL,
35 ;; version 3 or later.
37 ;; ![Markdown Mode Screenshot](https://jblevins.org/projects/markdown-mode/screenshots/20170818-001.png)
39 ;; [Markdown]: http://daringfireball.net/projects/markdown/
40 ;; [release notes]: https://jblevins.org/projects/markdown-mode/rev-2-3
42 ;;; Documentation:
44 ;; <a href="https://leanpub.com/markdown-mode">
45 ;; <img src="https://jblevins.org/projects/markdown-mode/guide-v2.3.png" align="right" height="350" width="231">
46 ;; </a>
48 ;; The primary documentation for Markdown Mode is available below, and
49 ;; is generated from comments in the source code. For a more in-depth
50 ;; treatment, the [_Guide to Markdown Mode for Emacs_][guide] covers
51 ;; Markdown syntax, advanced movement and editing in Emacs,
52 ;; extensions, configuration examples, tips and tricks, and a survey
53 ;; of other packages that work with Markdown Mode. Finally, Emacs is
54 ;; also a self-documenting editor. This means that the source code
55 ;; itself contains additional documentation: each function has its own
56 ;; docstring available via `C-h f` (`describe-function'), individual
57 ;; keybindings can be investigated with `C-h k` (`describe-key'), and
58 ;; a complete list of keybindings is available using `C-h m`
59 ;; (`describe-mode').
61 ;; [guide]: https://leanpub.com/markdown-mode
63 ;;; Installation:
65 ;; _Note:_ To use all of the features of `markdown-mode', you'll need
66 ;; to install the Emacs package itself and also have a local Markdown
67 ;; processor installed (e.g., Markdown.pl, MultiMarkdown, or Pandoc).
68 ;; The external processor is not required for editing, but will be
69 ;; used for rendering HTML for preview and export. After installing
70 ;; the Emacs package, be sure to configure `markdown-command' to point
71 ;; to the preferred Markdown executable on your system. See the
72 ;; Customization section below for more details.
74 ;; The recommended way to install `markdown-mode' is to install the package
75 ;; from [MELPA Stable](https://stable.melpa.org/#/markdown-mode)
76 ;; using `package.el'. First, configure `package.el' and the MELPA Stable
77 ;; repository by adding the following to your `.emacs', `init.el',
78 ;; or equivalent startup file:
80 ;; ``` Lisp
81 ;; (require 'package)
82 ;; (add-to-list 'package-archives
83 ;; '("melpa-stable" . "https://stable.melpa.org/packages/"))
84 ;; (package-initialize)
85 ;; ```
87 ;; Then, after restarting Emacs or evaluating the above statements, issue
88 ;; the following command: `M-x package-install RET markdown-mode RET`.
89 ;; When installed this way, the major modes `markdown-mode' and `gfm-mode'
90 ;; will be autoloaded and `markdown-mode' will be used for file names
91 ;; ending in either `.md` or `.markdown`.
93 ;; Alternatively, if you manage loading packages with [use-package][]
94 ;; then you can automatically install and configure `markdown-mode' by
95 ;; adding a declaration such as this one to your init file (as an
96 ;; example; adjust settings as desired):
98 ;; ``` Lisp
99 ;; (use-package markdown-mode
100 ;; :ensure t
101 ;; :commands (markdown-mode gfm-mode)
102 ;; :mode (("README\\.md\\'" . gfm-mode)
103 ;; ("\\.md\\'" . markdown-mode)
104 ;; ("\\.markdown\\'" . markdown-mode))
105 ;; :init (setq markdown-command "multimarkdown"))
106 ;; ```
108 ;; [MELPA Stable]: http://stable.melpa.org/
109 ;; [use-package]: https://github.com/jwiegley/use-package
111 ;; **Direct Download**
113 ;; Alternatively you can manually download and install markdown-mode.
114 ;; First, download the [latest stable version][markdown-mode.el] and
115 ;; save the file where Emacs can find it (i.e., a directory in your
116 ;; `load-path'). You can then configure `markdown-mode' and `gfm-mode'
117 ;; to load automatically by adding the following to your init file:
119 ;; ``` Lisp
120 ;; (autoload 'markdown-mode "markdown-mode"
121 ;; "Major mode for editing Markdown files" t)
122 ;; (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode))
123 ;; (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode))
125 ;; (autoload 'gfm-mode "markdown-mode"
126 ;; "Major mode for editing GitHub Flavored Markdown files" t)
127 ;; (add-to-list 'auto-mode-alist '("README\\.md\\'" . gfm-mode))
128 ;; ```
130 ;; [markdown-mode.el]: https://jblevins.org/projects/markdown-mode/markdown-mode.el
132 ;; **Development Version**
134 ;; To follow or contribute to markdown-mode development, you can
135 ;; browse or clone the Git repository
136 ;; [on GitHub](https://github.com/jrblevin/markdown-mode):
138 ;; ```
139 ;; git clone https://github.com/jrblevin/markdown-mode.git
140 ;; ```
142 ;; If you prefer to install and use the development version, which may
143 ;; become unstable at some times, you can either clone the Git
144 ;; repository as above or install markdown-mode from
145 ;; [MELPA](https://melpa.org/#/markdown-mode).
147 ;; If you clone the repository directly, then make sure that Emacs can
148 ;; find it by adding the following line to your startup file:
150 ;; ``` Lisp
151 ;; (add-to-list 'load-path "/path/to/markdown-mode/repository")
152 ;; ```
154 ;; **Packaged Installation**
156 ;; markdown-mode is also available in several package managers. You
157 ;; may want to confirm that the package you install contains the
158 ;; latest stable version first (and please notify the package
159 ;; maintainer if not).
161 ;; * Debian Linux: [elpa-markdown-mode][] and [emacs-goodies-el][]
162 ;; * Ubuntu Linux: [elpa-markdown-mode][elpa-ubuntu] and [emacs-goodies-el][emacs-goodies-el-ubuntu]
163 ;; * RedHat and Fedora Linux: [emacs-goodies][]
164 ;; * NetBSD: [textproc/markdown-mode][]
165 ;; * MacPorts: [markdown-mode.el][macports-package] ([pending][macports-ticket])
166 ;; * FreeBSD: [textproc/markdown-mode.el][freebsd-port]
168 ;; [elpa-markdown-mode]: https://packages.debian.org/sid/lisp/elpa-markdown-mode
169 ;; [elpa-ubuntu]: http://packages.ubuntu.com/search?keywords=elpa-markdown-mode
170 ;; [emacs-goodies-el]: http://packages.debian.org/emacs-goodies-el
171 ;; [emacs-goodies-el-ubuntu]: http://packages.ubuntu.com/search?keywords=emacs-goodies-el
172 ;; [emacs-goodies]: https://apps.fedoraproject.org/packages/emacs-goodies
173 ;; [textproc/markdown-mode]: http://pkgsrc.se/textproc/markdown-mode
174 ;; [macports-package]: https://trac.macports.org/browser/trunk/dports/editors/markdown-mode.el/Portfile
175 ;; [macports-ticket]: http://trac.macports.org/ticket/35716
176 ;; [freebsd-port]: http://svnweb.freebsd.org/ports/head/textproc/markdown-mode.el
178 ;; **Dependencies**
180 ;; To enable editing of code blocks in indirect buffers using `C-c '`,
181 ;; you will need to install the [`edit-indirect'][ei] package.
183 ;; [ei]: https://github.com/Fanael/edit-indirect/
185 ;;; Usage:
187 ;; Keybindings are grouped by prefixes based on their function. For
188 ;; example, the commands for styling text are grouped under `C-c C-s`
189 ;; and toggle commands begin with `C-c C-x`. The primary commands in
190 ;; each group will are described below. You can obtain a list of all
191 ;; keybindings by pressing `C-c C-h`. Movement and shifting commands
192 ;; tend to be associated with paired delimiters such as `M-{` and
193 ;; `M-}` or `C-c <` and `C-c >`. Outline navigation keybindings the
194 ;; same as in `org-mode'. Finally, commands for running Markdown or
195 ;; doing maintenance on an open file are grouped under the `C-c C-c`
196 ;; prefix. The most commonly used commands are described below. You
197 ;; can obtain a list of all keybindings by pressing `C-c C-h`.
199 ;; * Links and Images: `C-c C-l` and `C-c C-i`
201 ;; `C-c C-l` (`markdown-insert-link`) is a general command for
202 ;; inserting new link markup or editing existing link markup. This
203 ;; is especially useful when markup or URL hiding is enabled, so
204 ;; that URLs can't easily be edited directly. This command can be
205 ;; used to insert links of any form: either inline links,
206 ;; reference links, or plain URLs in angle brackets. The URL or
207 ;; `[reference]` label, link text, and optional title are entered
208 ;; through a series of interactive prompts. The type of link is
209 ;; determined by which values are provided:
211 ;; * If both a URL and link text are given, insert an inline link:
212 ;; `[text](url)`.
213 ;; * If both a `[reference]` label and link text are given, insert
214 ;; a reference link: `[text][reference]`.
215 ;; * If only link text is given, insert an implicit reference link:
216 ;; `[text][]`.
217 ;; * If only a URL is given, insert a plain URL link:
218 ;; `<url>`.
220 ;; Similarly, `C-c C-i` (`markdown-insert-image`) is a general
221 ;; command for inserting or editing image markup. As with the link
222 ;; insertion command, through a series interactive prompts you can
223 ;; insert either an inline or reference image:
225 ;; * If both a URL and alt text are given, insert an inline
226 ;; image: `![alt text](url)`.
227 ;; * If both a `[reference]` label and alt text are given,
228 ;; insert a reference link: `![alt text][reference]`.
230 ;; If there is an existing link or image at the point, these
231 ;; command will edit the existing markup rather than inserting new
232 ;; markup. Otherwise, if there is an active region, these commands
233 ;; use the region as either the default URL (if it seems to be a
234 ;; URL) or link text value otherwise. In that case, the region
235 ;; will be deleted and replaced by the link.
237 ;; Note that these functions can be used to convert links and
238 ;; images from one type to another (inline, reference, or plain
239 ;; URL) by selectively adding or removing properties via the
240 ;; interactive prompts.
242 ;; If a reference label is given that is not yet defined, you
243 ;; will be prompted for the URL and optional title and the
244 ;; reference will be inserted according to the value of
245 ;; `markdown-reference-location'. If a title is given, it will be
246 ;; added to the end of the reference definition and will be used
247 ;; to populate the title attribute when converted to HTML.
249 ;; Local images associated with image links may be displayed
250 ;; inline in the buffer by pressing `C-c C-x C-i`
251 ;; (`markdown-toggle-inline-images'). This is a toggle command, so
252 ;; pressing this once again will remove inline images.
254 ;; * Text Styles: `C-c C-s`
256 ;; `C-c C-s i` inserts markup to make a region or word italic. If
257 ;; there is an active region, make the region italic. If the point
258 ;; is at a non-italic word, make the word italic. If the point is
259 ;; at an italic word or phrase, remove the italic markup.
260 ;; Otherwise, simply insert italic delimiters and place the cursor
261 ;; in between them. Similarly, use `C-c C-s b` for bold, `C-c C-s c`
262 ;; for inline code, and `C-c C-s k` for inserting `<kbd>` tags.
264 ;; `C-c C-s q` inserts a blockquote using the active region, if
265 ;; any, or starts a new blockquote. `C-c C-s Q` is a variation
266 ;; which always operates on the region, regardless of whether it
267 ;; is active or not (i.e., when `transient-mark-mode` is off but
268 ;; the mark is set). The appropriate amount of indentation, if
269 ;; any, is calculated automatically given the surrounding context,
270 ;; but may be adjusted later using the region indentation
271 ;; commands.
273 ;; `C-c C-s p` behaves similarly for inserting preformatted code
274 ;; blocks (with `C-c C-s P` being the region-only counterpart)
275 ;; and `C-c C-s C` inserts a GFM style backquote fenced code block.
277 ;; * Headings: `C-c C-s`
279 ;; To insert or replace headings, there are two options. You can
280 ;; insert a specific level heading directly or you can have
281 ;; `markdown-mode' determine the level for you based on the previous
282 ;; heading. As with the other markup commands, the heading
283 ;; insertion commands use the text in the active region, if any,
284 ;; as the heading text. Otherwise, if the current line is not
285 ;; blank, they use the text on the current line. Finally, the
286 ;; setext commands will prompt for heading text if there is no
287 ;; active region and the current line is blank.
289 ;; `C-c C-s h` inserts a heading with automatically chosen type and
290 ;; level (both determined by the previous heading). `C-c C-s H`
291 ;; behaves similarly, but uses setext (underlined) headings when
292 ;; possible, still calculating the level automatically.
293 ;; In cases where the automatically-determined level is not what
294 ;; you intended, the level can be quickly promoted or demoted
295 ;; (as described below). Alternatively, a `C-u` prefix can be
296 ;; given to insert a heading _promoted_ (lower number) by one
297 ;; level or a `C-u C-u` prefix can be given to insert a heading
298 ;; demoted (higher number) by one level.
300 ;; To insert a heading of a specific level and type, use `C-c C-s 1`
301 ;; through `C-c C-s 6` for atx (hash mark) headings and `C-c C-s !` or
302 ;; `C-c C-s @` for setext headings of level one or two, respectively.
303 ;; Note that `!` is `S-1` and `@` is `S-2`.
305 ;; If the point is at a heading, these commands will replace the
306 ;; existing markup in order to update the level and/or type of the
307 ;; heading. To remove the markup of the heading at the point,
308 ;; press `C-c C-k` to kill the heading and press `C-y` to yank the
309 ;; heading text back into the buffer.
311 ;; * Horizontal Rules: `C-c C-s -`
313 ;; `C-c C-s -` inserts a horizontal rule. By default, insert the
314 ;; first string in the list `markdown-hr-strings' (the most
315 ;; prominent rule). With a `C-u` prefix, insert the last string.
316 ;; With a numeric prefix `N`, insert the string in position `N`
317 ;; (counting from 1).
319 ;; * Footnotes: `C-c C-s f`
321 ;; `C-c C-s f` inserts a footnote marker at the point, inserts a
322 ;; footnote definition below, and positions the point for
323 ;; inserting the footnote text. Note that footnotes are an
324 ;; extension to Markdown and are not supported by all processors.
326 ;; * Wiki Links: `C-c C-s w`
328 ;; `C-c C-s w` inserts a wiki link of the form `[[WikiLink]]`. If
329 ;; there is an active region, use the region as the link text. If the
330 ;; point is at a word, use the word as the link text. If there is
331 ;; no active region and the point is not at word, simply insert
332 ;; link markup. Note that wiki links are an extension to Markdown
333 ;; and are not supported by all processors.
335 ;; * Markdown and Maintenance Commands: `C-c C-c`
337 ;; *Compile:* `C-c C-c m` will run Markdown on the current buffer
338 ;; and show the output in another buffer. *Preview*: `C-c C-c p`
339 ;; runs Markdown on the current buffer and previews, stores the
340 ;; output in a temporary file, and displays the file in a browser.
341 ;; *Export:* `C-c C-c e` will run Markdown on the current buffer
342 ;; and save the result in the file `basename.html`, where
343 ;; `basename` is the name of the Markdown file with the extension
344 ;; removed. *Export and View:* press `C-c C-c v` to export the
345 ;; file and view it in a browser. *Open:* `C-c C-c o` will open
346 ;; the Markdown source file directly using `markdown-open-command'.
347 ;; *Live Export*: Press `C-c C-c l` to turn on
348 ;; `markdown-live-preview-mode' to view the exported output
349 ;; side-by-side with the source Markdown. **For all export commands,
350 ;; the output file will be overwritten without notice.**
351 ;; `markdown-live-preview-window-function' can be customized to open
352 ;; in a browser other than `eww'. If you want to force the
353 ;; preview window to appear at the bottom or right, you can
354 ;; customize `markdown-split-window-direction'.
356 ;; To summarize:
358 ;; - `C-c C-c m`: `markdown-command' > `*markdown-output*` buffer.
359 ;; - `C-c C-c p`: `markdown-command' > temporary file > browser.
360 ;; - `C-c C-c e`: `markdown-command' > `basename.html`.
361 ;; - `C-c C-c v`: `markdown-command' > `basename.html` > browser.
362 ;; - `C-c C-c w`: `markdown-command' > kill ring.
363 ;; - `C-c C-c o`: `markdown-open-command'.
364 ;; - `C-c C-c l`: `markdown-live-preview-mode' > `*eww*` buffer.
366 ;; `C-c C-c c` will check for undefined references. If there are
367 ;; any, a small buffer will open with a list of undefined
368 ;; references and the line numbers on which they appear. In Emacs
369 ;; 22 and greater, selecting a reference from this list and
370 ;; pressing `RET` will insert an empty reference definition at the
371 ;; end of the buffer. Similarly, selecting the line number will
372 ;; jump to the corresponding line.
374 ;; `C-c C-c n` renumbers any ordered lists in the buffer that are
375 ;; out of sequence.
377 ;; `C-c C-c ]` completes all headings and normalizes all horizontal
378 ;; rules in the buffer.
380 ;; * Following Links: `C-c C-o`
382 ;; Press `C-c C-o` when the point is on an inline or reference
383 ;; link to open the URL in a browser. When the point is at a
384 ;; wiki link, open it in another buffer (in the current window,
385 ;; or in the other window with the `C-u` prefix). Use `M-p` and
386 ;; `M-n` to quickly jump to the previous or next link of any type.
388 ;; * Doing Things: `C-c C-d`
390 ;; Use `C-c C-d` to do something sensible with the object at the point:
392 ;; - Jumps between reference links and reference definitions.
393 ;; If more than one link uses the same reference label, a
394 ;; window will be shown containing clickable buttons for
395 ;; jumping to each link. Pressing `TAB` or `S-TAB` cycles
396 ;; between buttons in this window.
397 ;; - Jumps between footnote markers and footnote text.
398 ;; - Toggles the completion status of GFM task list items
399 ;; (checkboxes).
400 ;; - Re-aligns table columns.
402 ;; * Promotion and Demotion: `C-c C--` and `C-c C-=`
404 ;; Headings, horizontal rules, and list items can be promoted and
405 ;; demoted, as well as bold and italic text. For headings,
406 ;; "promotion" means *decreasing* the level (i.e., moving from
407 ;; `<h2>` to `<h1>`) while "demotion" means *increasing* the
408 ;; level. For horizontal rules, promotion and demotion means
409 ;; moving backward or forward through the list of rule strings in
410 ;; `markdown-hr-strings'. For bold and italic text, promotion and
411 ;; demotion means changing the markup from underscores to asterisks.
412 ;; Press `C-c C--` or `C-c LEFT` to promote the element at the point
413 ;; if possible.
415 ;; To remember these commands, note that `-` is for decreasing the
416 ;; level (promoting), and `=` (on the same key as `+`) is for
417 ;; increasing the level (demoting). Similarly, the left and right
418 ;; arrow keys indicate the direction that the atx heading markup
419 ;; is moving in when promoting or demoting.
421 ;; * Completion: `C-c C-]`
423 ;; Complete markup is in normalized form, which means, for
424 ;; example, that the underline portion of a setext header is the
425 ;; same length as the heading text, or that the number of leading
426 ;; and trailing hash marks of an atx header are equal and that
427 ;; there is no extra whitespace in the header text. `C-c C-]`
428 ;; completes the markup at the point, if it is determined to be
429 ;; incomplete.
431 ;; * Editing Lists: `M-RET`, `C-c UP`, `C-c DOWN`, `C-c LEFT`, and `C-c RIGHT`
433 ;; New list items can be inserted with `M-RET` or `C-c C-j`. This
434 ;; command determines the appropriate marker (one of the possible
435 ;; unordered list markers or the next number in sequence for an
436 ;; ordered list) and indentation level by examining nearby list
437 ;; items. If there is no list before or after the point, start a
438 ;; new list. As with heading insertion, you may prefix this
439 ;; command by `C-u` to decrease the indentation by one level.
440 ;; Prefix this command by `C-u C-u` to increase the indentation by
441 ;; one level.
443 ;; Existing list items (and their nested sub-items) can be moved
444 ;; up or down with `C-c UP` or `C-c DOWN` and indented or
445 ;; outdented with `C-c RIGHT` or `C-c LEFT`.
447 ;; * Editing Subtrees: `C-c UP`, `C-c DOWN`, `C-c LEFT`, and `C-c RIGHT`
449 ;; Entire subtrees of ATX headings can be promoted and demoted
450 ;; with `C-c LEFT` and `C-c RIGHT`, which are the same keybindings
451 ;; used for promotion and demotion of list items. If the point is in
452 ;; a list item, the operate on the list item. Otherwise, they operate
453 ;; on the current heading subtree. Similarly, subtrees can be
454 ;; moved up and down with `C-c UP` and `C-c DOWN`.
456 ;; These commands currently do not work properly if there are
457 ;; Setext headings in the affected region.
459 ;; Please note the following "boundary" behavior for promotion and
460 ;; demotion. Any level-six headings will not be demoted further
461 ;; (i.e., they remain at level six, since Markdown and HTML define
462 ;; only six levels) and any level-one headings will promoted away
463 ;; entirely (i.e., heading markup will be removed, since a
464 ;; level-zero heading is not defined).
466 ;; * Shifting the Region: `C-c <` and `C-c >`
468 ;; Text in the region can be indented or outdented as a group using
469 ;; `C-c >` to indent to the next indentation point (calculated in
470 ;; the current context), and `C-c <` to outdent to the previous
471 ;; indentation point. These keybindings are the same as those for
472 ;; similar commands in `python-mode'.
474 ;; * Killing Elements: `C-c C-k`
476 ;; Press `C-c C-k` to kill the thing at point and add important
477 ;; text, without markup, to the kill ring. Possible things to
478 ;; kill include (roughly in order of precedece): inline code,
479 ;; headings, horizonal rules, links (add link text to kill ring),
480 ;; images (add alt text to kill ring), angle URIs, email
481 ;; addresses, bold, italics, reference definitions (add URI to
482 ;; kill ring), footnote markers and text (kill both marker and
483 ;; text, add text to kill ring), and list items.
485 ;; * Outline Navigation: `C-c C-n`, `C-c C-p`, `C-c C-f`, `C-c C-b`, and `C-c C-u`
487 ;; These keys are used for hierarchical navigation in lists and
488 ;; headings. When the point is in a list, they move between list
489 ;; items. Otherwise, they move between headings. Use `C-c C-n` and
490 ;; `C-c C-p` to move between the next and previous visible
491 ;; headings or list items of any level. Similarly, `C-c C-f` and
492 ;; `C-c C-b` move to the next and previous visible headings or
493 ;; list items at the same level as the one at the point. Finally,
494 ;; `C-c C-u` will move up to the parent heading or list item.
496 ;; * Movement by Markdown paragraph: `M-{`, `M-}`, and `M-h`
498 ;; Paragraphs in `markdown-mode' are regular paragraphs,
499 ;; paragraphs inside blockquotes, individual list items, headings,
500 ;; etc. These keys are usually bound to `forward-paragraph' and
501 ;; `backward-paragraph', but the built-in Emacs functions are
502 ;; based on simple regular expressions that fail in Markdown
503 ;; files. Instead, they are bound to `markdown-forward-paragraph'
504 ;; and `markdown-backward-paragraph'. To mark a paragraph,
505 ;; you can use `M-h` (`markdown-mark-paragraph').
507 ;; * Movement by Markdown block: `C-M-{`, `C-M-}`, and `C-c M-h`
509 ;; Markdown blocks are regular paragraphs in many cases, but
510 ;; contain many paragraphs in other cases: blocks are considered
511 ;; to be entire lists, entire code blocks, and entire blockquotes.
512 ;; To move backward one block use `C-M-{`
513 ;; (`markdown-beginning-block`) and to move forward use `C-M-}`
514 ;; (`markdown-end-of-block`). To mark a block, use `C-c M-h`
515 ;; (`markdown-mark-block`).
517 ;; * Movement by Defuns: `C-M-a`, `C-M-e`, and `C-M-h`
519 ;; The usual Emacs commands can be used to move by defuns
520 ;; (top-level major definitions). In markdown-mode, a defun is a
521 ;; section. As usual, `C-M-a` will move the point to the
522 ;; beginning of the current or preceding defun, `C-M-e` will move
523 ;; to the end of the current or following defun, and `C-M-h` will
524 ;; put the region around the entire defun.
526 ;; * Table Editing:
528 ;; Markdown Mode includes support for editing tables, which
529 ;; have the following basic format:
531 ;; | Right | Left | Center | Default |
532 ;; |------:|:-----|:------:|---------|
533 ;; | 12 | 12 | 12 | 12 |
534 ;; | 123 | 123 | 123 | 123 |
535 ;; | 1 | 1 | 1 | 1 |
537 ;; The first line contains column headers. The second line
538 ;; contains a separator line between the headers and the content.
539 ;; Each following line is a row in the table. Columns are always
540 ;; separated by the pipe character. The colons indicate column
541 ;; alignment.
543 ;; A table is re-aligned automatically each time you press `TAB`
544 ;; or `RET` inside the table. `TAB` also moves to the next
545 ;; field (`RET` to the next row) and creates new table rows at
546 ;; the end of the table or before horizontal separator lines. The
547 ;; indentation of the table is set by the first line. Column
548 ;; centering inside Emacs is not supported.
550 ;; Beginning pipe characters are required for proper detection of
551 ;; table borders inside Emacs. Any line starting with `|-` or `|:`
552 ;; is considered as a horizontal separator line and will be
553 ;; expanded on the next re-align to span the whole table width. No
554 ;; padding is allowed between the beginning pipe character and
555 ;; header separator symbol. So, to create the above table, you
556 ;; would only type
558 ;; |Right|Left|Center|Default|
559 ;; |-
561 ;; and then press `TAB` to align the table and start filling in
562 ;; cells.
564 ;; Then you can jump with `TAB` from one cell to the next or with
565 ;; `S-TAB` to the previous one. `RET` will jump to the to the
566 ;; next cell in the same column, and create a new row if there is
567 ;; no such cell or if the next row is beyond a separator line.
569 ;; You can also convert selected region to a table. Basic editing
570 ;; capabilities include inserting, deleting, and moving of columns
571 ;; and rows, and table re-alignment, sorting, transposition:
573 ;; - `C-c UP` or `C-c DOWN` - Move the current row up or down.
574 ;; - `C-c LEFT` or `C-c RIGHT` - Move the current column left or right.
575 ;; - `C-c S-UP` - Kill the current row.
576 ;; - `C-c S-DOWN` - Insert a row above the current row. With a
577 ;; prefix argument, row line is created below the current one.
578 ;; - `C-c S-LEFT` - Kill the current column.
579 ;; - `C-c S-RIGHT` - Insert a new column to the left of the current one.
580 ;; - `C-c C-d` - Re-align the current table (`markdown-do`).
581 ;; - `C-c C-c ^` - Sort the rows of a table by a specified column.
582 ;; This command prompts you for the column number and a sort
583 ;; method (alphabetical or numerical, optionally in reverse).
584 ;; - `C-c C-c |` - Convert the region to a table. This function
585 ;; attempts to recognize comma, tab, and space separated data
586 ;; and then splits the data into cells accordingly.
587 ;; - `C-c C-c t` - Transpose table at point.
589 ;; The table editing functions try to handle markup hiding
590 ;; correctly when calculating column widths, however, columns
591 ;; containing hidden markup may not always be aligned properly.
593 ;; * Miscellaneous Commands:
595 ;; When the [`edit-indirect'][ei] package is installed, `C-c '`
596 ;; (`markdown-edit-code-block`) can be used to edit a code block
597 ;; in an indirect buffer in the native major mode. Press `C-c C-c`
598 ;; to commit changes and return or `C-c C-k` to cancel. You can
599 ;; also give a prefix argument to the insertion command, as in
600 ;; `C-u C-c C-s C`, to edit the code block in an indirect buffer
601 ;; upon insertion.
603 ;; As noted, many of the commands above behave differently depending
604 ;; on whether Transient Mark mode is enabled or not. When it makes
605 ;; sense, if Transient Mark mode is on and the region is active, the
606 ;; command applies to the text in the region (e.g., `C-c C-s b` makes the
607 ;; region bold). For users who prefer to work outside of Transient
608 ;; Mark mode, since Emacs 22 it can be enabled temporarily by pressing
609 ;; `C-SPC C-SPC`. When this is not the case, many commands then
610 ;; proceed to look work with the word or line at the point.
612 ;; When applicable, commands that specifically act on the region even
613 ;; outside of Transient Mark mode have the same keybinding as their
614 ;; standard counterpart, but the letter is uppercase. For example,
615 ;; `markdown-insert-blockquote' is bound to `C-c C-s q` and only acts on
616 ;; the region in Transient Mark mode while `markdown-blockquote-region'
617 ;; is bound to `C-c C-s Q` and always applies to the region (when nonempty).
619 ;; Note that these region-specific functions are useful in many
620 ;; cases where it may not be obvious. For example, yanking text from
621 ;; the kill ring sets the mark at the beginning of the yanked text
622 ;; and moves the point to the end. Therefore, the (inactive) region
623 ;; contains the yanked text. So, `C-y` followed by `C-c C-s Q` will
624 ;; yank text and turn it into a blockquote.
626 ;; markdown-mode attempts to be flexible in how it handles
627 ;; indentation. When you press `TAB` repeatedly, the point will cycle
628 ;; through several possible indentation levels corresponding to things
629 ;; you might have in mind when you press `RET` at the end of a line or
630 ;; `TAB`. For example, you may want to start a new list item,
631 ;; continue a list item with hanging indentation, indent for a nested
632 ;; pre block, and so on. Outdenting is handled similarly when backspace
633 ;; is pressed at the beginning of the non-whitespace portion of a line.
635 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
636 ;; visibility cycling for atx- or hash-style headings. There are two
637 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
638 ;; the table of contents view (headings only), outline view (top-level
639 ;; headings only), and the full document view. Pressing `TAB` while the
640 ;; point is at a heading will cycle through levels of visibility for the
641 ;; subtree: completely folded, visible children, and fully visible.
642 ;; Note that mixing hash and underline style headings will give undesired
643 ;; results.
645 ;;; Customization:
647 ;; Although no configuration is *necessary* there are a few things
648 ;; that can be customized. The `M-x customize-mode` command
649 ;; provides an interface to all of the possible customizations:
651 ;; * `markdown-command' - the command used to run Markdown (default:
652 ;; `markdown`). This variable may be customized to pass
653 ;; command-line options to your Markdown processor of choice. It can
654 ;; also be a function; in this case `markdown' will call it with three
655 ;; arguments: the beginning and end of the region to process, and
656 ;; a buffer to write the output to.
658 ;; * `markdown-command-needs-filename' - set to `t' if
659 ;; `markdown-command' does not accept standard input (default:
660 ;; `nil'). When `nil', `markdown-mode' will pass the Markdown
661 ;; content to `markdown-command' using standard input (`stdin`).
662 ;; When set to `t', `markdown-mode' will pass the name of the file
663 ;; as the final command-line argument to `markdown-command'. Note
664 ;; that in the latter case, you will only be able to run
665 ;; `markdown-command' from buffers which are visiting a file. If
666 ;; `markdown-command' is a function, `markdown-command-needs-filename'
667 ;; is ignored.
669 ;; * `markdown-open-command' - the command used for calling a standalone
670 ;; Markdown previewer which is capable of opening Markdown source files
671 ;; directly (default: `nil'). This command will be called
672 ;; with a single argument, the filename of the current buffer.
673 ;; A representative program is the Mac app [Marked 2][], a
674 ;; live-updating Markdown previewer which can be [called from a
675 ;; simple shell script](https://jblevins.org/log/marked-2-command).
676 ;; This variable can also be a function; in this case `markdown-open'
677 ;; will call it without arguments to preview the current buffer.
679 ;; * `markdown-hr-strings' - list of strings to use when inserting
680 ;; horizontal rules. Different strings will not be distinguished
681 ;; when converted to HTML--they will all be converted to
682 ;; `<hr/>`--but they may add visual distinction and style to plain
683 ;; text documents. To maintain some notion of promotion and
684 ;; demotion, keep these sorted from largest to smallest.
686 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
687 ;; underscores when inserting bold text instead of two asterisks
688 ;; (default: `nil').
690 ;; * `markdown-italic-underscore' - set to a non-nil value to use
691 ;; underscores when inserting italic text instead of asterisks
692 ;; (default: `nil').
694 ;; * `markdown-asymmetric-header' - set to a non-nil value to use
695 ;; asymmetric header styling, placing header characters only on
696 ;; the left of headers (default: `nil').
698 ;; * `markdown-header-scaling' - set to a non-nil value to use
699 ;; a variable-pitch font for headings where the size corresponds
700 ;; to the level of the heading (default: `nil').
702 ;; * `markdown-header-scaling-values' - list of scaling values,
703 ;; relative to baseline, for headers of levels one through six,
704 ;; used when `markdown-header-scaling' is non-nil
705 ;; (default: `(2.0 1.7 1.4 1.1 1.0 1.0)`).
707 ;; * `markdown-marginalize-headers' - put opening atx header markup
708 ;; in the left margin when non-nil (default: `nil').
710 ;; * `markdown-marginalize-headers-margin-width' - width of margin
711 ;; used for marginalized headers (default: 6).
713 ;; * `markdown-list-indent-width' - depth of indentation for lists
714 ;; when inserting, promoting, and demoting list items (default: 4).
716 ;; * `markdown-indent-function' - the function to use for automatic
717 ;; indentation (default: `markdown-indent-line').
719 ;; * `markdown-indent-on-enter' - Set to a non-nil value to
720 ;; automatically indent new lines when `RET` is pressed.
721 ;; Set to `indent-and-new-item' to additionally continue lists
722 ;; when `RET` is pressed (default: `t').
724 ;; * `markdown-enable-wiki-links' - syntax highlighting for wiki
725 ;; links (default: `nil'). Set this to a non-nil value to turn on
726 ;; wiki link support by default. Wiki link support can be toggled
727 ;; later using the function `markdown-toggle-wiki-links'."
729 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
730 ;; treat aliased wiki links like `[[link text|PageName]]`
731 ;; (default: `t'). When set to nil, they will be treated as
732 ;; `[[PageName|link text]]'.
734 ;; * `markdown-uri-types' - a list of protocol schemes (e.g., "http")
735 ;; for URIs that `markdown-mode' should highlight.
737 ;; * `markdown-enable-math' - font lock for inline and display LaTeX
738 ;; math expressions (default: `nil'). Set this to `t' to turn on
739 ;; math support by default. Math support can be toggled
740 ;; interactively later using `C-c C-x C-e`
741 ;; (`markdown-toggle-math').
743 ;; * `markdown-css-paths' - CSS files to link to in XHTML output
744 ;; (default: `nil`).
746 ;; * `markdown-content-type' - when set to a nonempty string, an
747 ;; `http-equiv` attribute will be included in the XHTML `<head>`
748 ;; block (default: `""`). If needed, the suggested values are
749 ;; `application/xhtml+xml` or `text/html`. See also:
750 ;; `markdown-coding-system'.
752 ;; * `markdown-coding-system' - used for specifying the character
753 ;; set identifier in the `http-equiv` attribute when included
754 ;; (default: `nil'). See `markdown-content-type', which must
755 ;; be set before this variable has any effect. When set to `nil',
756 ;; `buffer-file-coding-system' will be used to automatically
757 ;; determine the coding system string (falling back to
758 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
759 ;; and `iso-latin-1'.
761 ;; * `markdown-xhtml-header-content' - additional content to include
762 ;; in the XHTML `<head>` block (default: `""`).
764 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
765 ;; `markdown-mode' uses to determine whether the output of
766 ;; `markdown-command' is a standalone XHTML document or an XHTML
767 ;; fragment (default: `"^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"`). If
768 ;; this regular expression not matched in the first five lines of
769 ;; output, `markdown-mode' assumes the output is a fragment and
770 ;; adds a header and footer.
772 ;; * `markdown-link-space-sub-char' - a character to replace spaces
773 ;; when mapping wiki links to filenames (default: `"_"`).
774 ;; For example, use an underscore for compatibility with the
775 ;; Python Markdown WikiLinks extension. In `gfm-mode', this is
776 ;; set to `"-"` to conform with GitHub wiki links.
778 ;; * `markdown-reference-location' - where to insert reference
779 ;; definitions (default: `header`). The possible locations are
780 ;; the end of the document (`end`), after the current block
781 ;; (`immediately`), the end of the current subtree (`subtree'),
782 ;; or before the next header (`header`).
784 ;; * `markdown-footnote-location' - where to insert footnote text
785 ;; (default: `end`). The set of location options is the same as
786 ;; for `markdown-reference-location'.
788 ;; * `markdown-nested-imenu-heading-index' - Use nested imenu
789 ;; heading instead of a flat index (default: `t'). A nested
790 ;; index may provide more natural browsing from the menu, but a
791 ;; flat list may allow for faster keyboard navigation via tab
792 ;; completion.
794 ;; * `comment-auto-fill-only-comments' - variable is made
795 ;; buffer-local and set to `nil' by default. In programming
796 ;; language modes, when this variable is non-nil, only comments
797 ;; will be filled by auto-fill-mode. However, comments in
798 ;; Markdown documents are rare and the most users probably intend
799 ;; for the actual content of the document to be filled. Making
800 ;; this variable buffer-local allows `markdown-mode' to override
801 ;; the default behavior induced when the global variable is non-nil.
803 ;; * `markdown-gfm-additional-languages', - additional languages to
804 ;; make available, aside from those predefined in
805 ;; `markdown-gfm-recognized-languages', when inserting GFM code
806 ;; blocks (default: `nil`). Language strings must have be trimmed
807 ;; of whitespace and not contain any curly braces. They may be of
808 ;; arbitrary capitalization, though.
810 ;; * `markdown-gfm-use-electric-backquote' - use
811 ;; `markdown-electric-backquote' for interactive insertion of GFM
812 ;; code blocks when backquote is pressed three times (default: `t`).
814 ;; * `markdown-make-gfm-checkboxes-buttons' - Whether GitHub
815 ;; Flavored Markdown style task lists (checkboxes) should be
816 ;; turned into buttons that can be toggled with mouse-1 or RET. If
817 ;; non-nil (default), then buttons are enabled. This works in
818 ;; `markdown-mode' as well as `gfm-mode'.
820 ;; * `markdown-hide-urls' - Determines whether URL and reference
821 ;; labels are hidden for inline and reference links (default: `nil').
822 ;; When non-nil, inline links will appear in the buffer as
823 ;; `[link](∞)` instead of
824 ;; `[link](http://perhaps.a/very/long/url/)`. To change the
825 ;; placeholder (composition) character used, set the variable
826 ;; `markdown-url-compose-char'. URL hiding can be toggled
827 ;; interactively using `C-c C-x C-l` (`markdown-toggle-url-hiding')
828 ;; or from the Markdown | Links & Images menu.
830 ;; * `markdown-hide-markup' - Determines whether all possible markup
831 ;; is hidden or otherwise beautified (default: `nil'). The actual
832 ;; buffer text remains unchanged, but the display will be altered.
833 ;; Brackets and URLs for links will be hidden, asterisks and
834 ;; underscores for italic and bold text will be hidden, text
835 ;; bullets for unordered lists will be replaced by Unicode
836 ;; bullets, and so on. Since this includes URLs and reference
837 ;; labels, when non-nil this setting supersedes `markdown-hide-urls'.
838 ;; Markup hiding can be toggled using `C-c C-x C-m`
839 ;; (`markdown-toggle-markup-hiding') or from the Markdown | Show &
840 ;; Hide menu.
842 ;; Unicode bullets are used to replace ASCII list item markers.
843 ;; The list of characters used, in order of list level, can be
844 ;; specified by setting the variable `markdown-list-item-bullets'.
845 ;; The placeholder characters used to replace other markup can
846 ;; be changed by customizing the corresponding variables:
847 ;; `markdown-blockquote-display-char',
848 ;; `markdown-hr-display-char', and
849 ;; `markdown-definition-display-char'.
851 ;; * `markdown-fontify-code-blocks-natively' - Whether to fontify
852 ;; code in code blocks using the native major mode. This only
853 ;; works for fenced code blocks where the language is specified
854 ;; where we can automatically determine the appropriate mode to
855 ;; use. The language to mode mapping may be customized by setting
856 ;; the variable `markdown-code-lang-modes'. This can be toggled
857 ;; interactively by pressing `C-c C-x C-f`
858 ;; (`markdown-toggle-fontify-code-blocks-natively').
860 ;; * `markdown-gfm-uppercase-checkbox' - When non-nil, complete GFM
861 ;; task list items with `[X]` instead of `[x]` (default: `nil').
862 ;; This is useful for compatibility with `org-mode', which doesn't
863 ;; recognize the lowercase variant.
865 ;; * `markdown-translate-filename-function' - A function to be used to
866 ;; translate filenames in links.
868 ;; Additionally, the faces used for syntax highlighting can be modified to
869 ;; your liking by issuing `M-x customize-group RET markdown-faces`
870 ;; or by using the "Markdown Faces" link at the bottom of the mode
871 ;; customization screen.
873 ;; [Marked 2]: https://itunes.apple.com/us/app/marked-2/id890031187?mt=12&uo=4&at=11l5Vs&ct=mm
875 ;;; Extensions:
877 ;; Besides supporting the basic Markdown syntax, Markdown Mode also
878 ;; includes syntax highlighting for `[[Wiki Links]]`. This can be
879 ;; enabled by setting `markdown-enable-wiki-links' to a non-nil value.
880 ;; Wiki links may be followed by pressing `C-c C-o` when the point
881 ;; is at a wiki link. Use `M-p` and `M-n` to quickly jump to the
882 ;; previous and next links (including links of other types).
883 ;; Aliased or piped wiki links of the form `[[link text|PageName]]`
884 ;; are also supported. Since some wikis reverse these components, set
885 ;; `markdown-wiki-link-alias-first' to nil to treat them as
886 ;; `[[PageName|link text]]`. If `markdown-wiki-link-fontify-missing'
887 ;; is also non-nil, Markdown Mode will highlight wiki links with
888 ;; missing target file in a different color. By default, Markdown
889 ;; Mode only searches for target files in the current directory.
890 ;; Search in subdirectories can be enabled by setting
891 ;; `markdown-wiki-link-search-subdirectories' to a non-nil value.
892 ;; Sequential parent directory search (as in [Ikiwiki][]) can be
893 ;; enabled by setting `markdown-wiki-link-search-parent-directories'
894 ;; to a non-nil value.
896 ;; [Ikiwiki]: https://ikiwiki.info
898 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
899 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
900 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
901 ;; You can do this either by using `M-x customize-group markdown`
902 ;; or by placing the following in your `.emacs` file:
904 ;; ``` Lisp
905 ;; (setq markdown-command "markdown | smartypants")
906 ;; ```
908 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
910 ;; Syntax highlighting for mathematical expressions written
911 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
912 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
913 ;; either via customize or by placing `(setq markdown-enable-math t)`
914 ;; in `.emacs`, and then restarting Emacs or calling
915 ;; `markdown-reload-extensions'.
917 ;;; GitHub Flavored Markdown (GFM):
919 ;; A [GitHub Flavored Markdown][GFM] mode, `gfm-mode', is also
920 ;; available. The GitHub implementation differs slightly from
921 ;; standard Markdown in that it supports things like different
922 ;; behavior for underscores inside of words, automatic linking of
923 ;; URLs, strikethrough text, and fenced code blocks with an optional
924 ;; language keyword.
926 ;; The GFM-specific features above apply to `README.md` files, wiki
927 ;; pages, and other Markdown-formatted files in repositories on
928 ;; GitHub. GitHub also enables [additional features][GFM comments] for
929 ;; writing on the site (for issues, pull requests, messages, etc.)
930 ;; that are further extensions of GFM. These features include task
931 ;; lists (checkboxes), newlines corresponding to hard line breaks,
932 ;; auto-linked references to issues and commits, wiki links, and so
933 ;; on. To make matters more confusing, although task lists are not
934 ;; part of [GFM proper][GFM], [since 2014][] they are rendered (in a
935 ;; read-only fashion) in all Markdown documents in repositories on the
936 ;; site. These additional extensions are supported to varying degrees
937 ;; by `markdown-mode' and `gfm-mode' as described below.
939 ;; * **URL autolinking:** Both `markdown-mode' and `gfm-mode' support
940 ;; highlighting of URLs without angle brackets.
942 ;; * **Multiple underscores in words:** You must enable `gfm-mode' to
943 ;; toggle support for underscores inside of words. In this mode
944 ;; variable names such as `a_test_variable` will not trigger
945 ;; emphasis (italics).
947 ;; * **Fenced code blocks:** Code blocks quoted with backquotes, with
948 ;; optional programming language keywords, are highlighted in
949 ;; both `markdown-mode' and `gfm-mode'. They can be inserted with
950 ;; `C-c C-s C`. If there is an active region, the text in the
951 ;; region will be placed inside the code block. You will be
952 ;; prompted for the name of the language, but may press enter to
953 ;; continue without naming a language.
955 ;; * **Strikethrough:** Strikethrough text is supported in both
956 ;; `markdown-mode' and `gfm-mode'. It can be inserted (and toggled)
957 ;; using `C-c C-s s`.
959 ;; * **Task lists:** GFM task lists will be rendered as checkboxes
960 ;; (Emacs buttons) in both `markdown-mode' and `gfm-mode' when
961 ;; `markdown-make-gfm-checkboxes-buttons' is set to a non-nil value
962 ;; (and it is set to t by default). These checkboxes can be
963 ;; toggled by clicking `mouse-1`, pressing `RET` over the button,
964 ;; or by pressing `C-c C-d` (`markdown-do`) with the point anywhere
965 ;; in the task list item. A normal list item can be turned to a
966 ;; check list item by the same command, or more specifically
967 ;; `C-c C-s [` (`markdown-insert-gfm-checkbox`).
969 ;; * **Wiki links:** Generic wiki links are supported in
970 ;; `markdown-mode', but in `gfm-mode' specifically they will be
971 ;; treated as they are on GitHub: spaces will be replaced by hyphens
972 ;; in filenames and the first letter of the filename will be
973 ;; capitalized. For example, `[[wiki link]]' will map to a file
974 ;; named `Wiki-link` with the same extension as the current file.
975 ;; If a file with this name does not exist in the current directory,
976 ;; the first match in a subdirectory, if any, will be used instead.
978 ;; * **Newlines:** Neither `markdown-mode' nor `gfm-mode' do anything
979 ;; specifically with respect to newline behavior. If you use
980 ;; `gfm-mode' mostly to write text for comments or issues on the
981 ;; GitHub site--where newlines are significant and correspond to
982 ;; hard line breaks--then you may want to enable `visual-line-mode'
983 ;; for line wrapping in buffers. You can do this with a
984 ;; `gfm-mode-hook' as follows:
986 ;; ``` Lisp
987 ;; ;; Use visual-line-mode in gfm-mode
988 ;; (defun my-gfm-mode-hook ()
989 ;; (visual-line-mode 1))
990 ;; (add-hook 'gfm-mode-hook 'my-gfm-mode-hook)
991 ;; ```
993 ;; * **Preview:** GFM-specific preview can be powered by setting
994 ;; `markdown-command' to use [Docter][]. This may also be
995 ;; configured to work with [Marked 2][] for `markdown-open-command'.
997 ;; [GFM]: http://github.github.com/github-flavored-markdown/
998 ;; [GFM comments]: https://help.github.com/articles/writing-on-github/
999 ;; [since 2014]: https://github.com/blog/1825-task-lists-in-all-markdown-documents
1000 ;; [Docter]: https://github.com/alampros/Docter
1002 ;;; Acknowledgments:
1004 ;; markdown-mode has benefited greatly from the efforts of the many
1005 ;; volunteers who have sent patches, test cases, bug reports,
1006 ;; suggestions, helped with packaging, etc. Thank you for your
1007 ;; contributions! See the [contributors graph][contrib] for details.
1009 ;; [contrib]: https://github.com/jrblevin/markdown-mode/graphs/contributors
1011 ;;; Bugs:
1013 ;; markdown-mode is developed and tested primarily for compatibility
1014 ;; with GNU Emacs 24.3 and later. If you find any bugs in
1015 ;; markdown-mode, please construct a test case or a patch and open a
1016 ;; ticket on the [GitHub issue tracker][issues]. See the
1017 ;; contributing guidelines in `CONTRIBUTING.md` for details on
1018 ;; creating pull requests.
1020 ;; [issues]: https://github.com/jrblevin/markdown-mode/issues
1022 ;;; History:
1024 ;; markdown-mode was written and is maintained by Jason Blevins. The
1025 ;; first version was released on May 24, 2007.
1027 ;; * 2007-05-24: [Version 1.1][]
1028 ;; * 2007-05-25: [Version 1.2][]
1029 ;; * 2007-06-05: [Version 1.3][]
1030 ;; * 2007-06-29: [Version 1.4][]
1031 ;; * 2007-10-11: [Version 1.5][]
1032 ;; * 2008-06-04: [Version 1.6][]
1033 ;; * 2009-10-01: [Version 1.7][]
1034 ;; * 2011-08-12: [Version 1.8][]
1035 ;; * 2011-08-15: [Version 1.8.1][]
1036 ;; * 2013-01-25: [Version 1.9][]
1037 ;; * 2013-03-24: [Version 2.0][]
1038 ;; * 2016-01-09: [Version 2.1][]
1039 ;; * 2017-05-26: [Version 2.2][]
1040 ;; * 2017-08-31: [Version 2.3][]
1042 ;; [Version 1.1]: https://jblevins.org/projects/markdown-mode/rev-1-1
1043 ;; [Version 1.2]: https://jblevins.org/projects/markdown-mode/rev-1-2
1044 ;; [Version 1.3]: https://jblevins.org/projects/markdown-mode/rev-1-3
1045 ;; [Version 1.4]: https://jblevins.org/projects/markdown-mode/rev-1-4
1046 ;; [Version 1.5]: https://jblevins.org/projects/markdown-mode/rev-1-5
1047 ;; [Version 1.6]: https://jblevins.org/projects/markdown-mode/rev-1-6
1048 ;; [Version 1.7]: https://jblevins.org/projects/markdown-mode/rev-1-7
1049 ;; [Version 1.8]: https://jblevins.org/projects/markdown-mode/rev-1-8
1050 ;; [Version 1.8.1]: https://jblevins.org/projects/markdown-mode/rev-1-8-1
1051 ;; [Version 1.9]: https://jblevins.org/projects/markdown-mode/rev-1-9
1052 ;; [Version 2.0]: https://jblevins.org/projects/markdown-mode/rev-2-0
1053 ;; [Version 2.1]: https://jblevins.org/projects/markdown-mode/rev-2-1
1054 ;; [Version 2.2]: https://jblevins.org/projects/markdown-mode/rev-2-2
1055 ;; [Version 2.3]: https://jblevins.org/projects/markdown-mode/rev-2-3
1058 ;;; Code:
1060 (require 'easymenu)
1061 (require 'outline)
1062 (require 'thingatpt)
1063 (require 'cl-lib)
1064 (require 'url-parse)
1065 (require 'button)
1066 (require 'color)
1067 (require 'rx)
1069 (defvar jit-lock-start)
1070 (defvar jit-lock-end)
1071 (defvar flyspell-generic-check-word-predicate)
1073 (declare-function eww-open-file "eww")
1074 (declare-function url-path-and-query "url-parse")
1077 ;;; Constants =================================================================
1079 (defconst markdown-mode-version "2.4-dev"
1080 "Markdown mode version number.")
1082 (defconst markdown-output-buffer-name "*markdown-output*"
1083 "Name of temporary buffer for markdown command output.")
1085 (defconst markdown-sub-superscript-display
1086 '(((raise -0.3) (height 0.7)) ; subscript
1087 ((raise 0.3) (height 0.7))) ; superscript
1088 "Parameters for sub- and superscript formatting.")
1091 ;;; Global Variables ==========================================================
1093 (defvar markdown-reference-label-history nil
1094 "History of used reference labels.")
1096 (defvar markdown-live-preview-mode nil
1097 "Sentinel variable for command `markdown-live-preview-mode'.")
1099 (defvar markdown-gfm-language-history nil
1100 "History list of languages used in the current buffer in GFM code blocks.")
1103 ;;; Customizable Variables ====================================================
1105 (defvar markdown-mode-hook nil
1106 "Hook run when entering Markdown mode.")
1108 (defvar markdown-before-export-hook nil
1109 "Hook run before running Markdown to export XHTML output.
1110 The hook may modify the buffer, which will be restored to it's
1111 original state after exporting is complete.")
1113 (defvar markdown-after-export-hook nil
1114 "Hook run after XHTML output has been saved.
1115 Any changes to the output buffer made by this hook will be saved.")
1117 (defgroup markdown nil
1118 "Major mode for editing text files in Markdown format."
1119 :prefix "markdown-"
1120 :group 'wp
1121 :link '(url-link "https://jblevins.org/projects/markdown-mode/"))
1123 (defcustom markdown-command "markdown"
1124 "Command to run markdown."
1125 :group 'markdown
1126 :type '(choice (string :tag "Shell command") function))
1128 (defcustom markdown-command-needs-filename nil
1129 "Set to non-nil if `markdown-command' does not accept input from stdin.
1130 Instead, it will be passed a filename as the final command line
1131 option. As a result, you will only be able to run Markdown from
1132 buffers which are visiting a file."
1133 :group 'markdown
1134 :type 'boolean)
1136 (defcustom markdown-open-command nil
1137 "Command used for opening Markdown files directly.
1138 For example, a standalone Markdown previewer. This command will
1139 be called with a single argument: the filename of the current
1140 buffer. It can also be a function, which will be called without
1141 arguments."
1142 :group 'markdown
1143 :type '(choice file function (const :tag "None" nil)))
1145 (defcustom markdown-hr-strings
1146 '("-------------------------------------------------------------------------------"
1147 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
1148 "---------------------------------------"
1149 "* * * * * * * * * * * * * * * * * * * *"
1150 "---------"
1151 "* * * * *")
1152 "Strings to use when inserting horizontal rules.
1153 The first string in the list will be the default when inserting a
1154 horizontal rule. Strings should be listed in decreasing order of
1155 prominence (as in headings from level one to six) for use with
1156 promotion and demotion functions."
1157 :group 'markdown
1158 :type '(repeat string))
1160 (defcustom markdown-bold-underscore nil
1161 "Use two underscores when inserting bold text instead of two asterisks."
1162 :group 'markdown
1163 :type 'boolean)
1165 (defcustom markdown-italic-underscore nil
1166 "Use underscores when inserting italic text instead of asterisks."
1167 :group 'markdown
1168 :type 'boolean)
1170 (defcustom markdown-marginalize-headers nil
1171 "When non-nil, put opening atx header markup in a left margin.
1173 This setting goes well with `markdown-asymmetric-header'. But
1174 sadly it conflicts with `linum-mode' since they both use the
1175 same margin."
1176 :group 'markdown
1177 :type 'boolean
1178 :safe 'booleanp
1179 :package-version '(markdown-mode . "2.4"))
1181 (defcustom markdown-marginalize-headers-margin-width 6
1182 "Character width of margin used for marginalized headers.
1183 The default value is based on there being six heading levels
1184 defined by Markdown and HTML. Increasing this produces extra
1185 whitespace on the left. Decreasing it may be preferred when
1186 fewer than six nested heading levels are used."
1187 :group 'markdown
1188 :type 'natnump
1189 :safe 'natnump
1190 :package-version '(markdown-mode . "2.4"))
1192 (defcustom markdown-asymmetric-header nil
1193 "Determines if atx header style will be asymmetric.
1194 Set to a non-nil value to use asymmetric header styling, placing
1195 header markup only at the beginning of the line. By default,
1196 balanced markup will be inserted at the beginning and end of the
1197 line around the header title."
1198 :group 'markdown
1199 :type 'boolean)
1201 (defcustom markdown-indent-function 'markdown-indent-line
1202 "Function to use to indent."
1203 :group 'markdown
1204 :type 'function)
1206 (defcustom markdown-indent-on-enter t
1207 "Determines indentation behavior when pressing \\[newline].
1208 Possible settings are nil, t, and 'indent-and-new-item.
1210 When non-nil, pressing \\[newline] will call `newline-and-indent'
1211 to indent the following line according to the context using
1212 `markdown-indent-function'. In this case, note that
1213 \\[electric-newline-and-maybe-indent] can still be used to insert
1214 a newline without indentation.
1216 When set to 'indent-and-new-item and the point is in a list item
1217 when \\[newline] is pressed, the list will be continued on the next
1218 line, where a new item will be inserted.
1220 When set to nil, simply call `newline' as usual. In this case,
1221 you can still indent lines using \\[markdown-cycle] and continue
1222 lists with \\[markdown-insert-list-item].
1224 Note that this assumes the variable `electric-indent-mode' is
1225 non-nil (enabled). When it is *disabled*, the behavior of
1226 \\[newline] and `\\[electric-newline-and-maybe-indent]' are
1227 reversed."
1228 :group 'markdown
1229 :type '(choice (const :tag "Don't automatically indent" nil)
1230 (const :tag "Automatically indent" t)
1231 (const :tag "Automatically indent and insert new list items" indent-and-new-item)))
1233 (defcustom markdown-enable-wiki-links nil
1234 "Syntax highlighting for wiki links.
1235 Set this to a non-nil value to turn on wiki link support by default.
1236 Support can be toggled later using the `markdown-toggle-wiki-links'
1237 function or \\[markdown-toggle-wiki-links]."
1238 :group 'markdown
1239 :type 'boolean
1240 :safe 'booleanp
1241 :package-version '(markdown-mode . "2.2"))
1243 (defcustom markdown-wiki-link-alias-first t
1244 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
1245 Otherwise, they will be treated as [[PageName|alias text]]."
1246 :group 'markdown
1247 :type 'boolean
1248 :safe 'booleanp)
1250 (defcustom markdown-wiki-link-search-subdirectories nil
1251 "When non-nil, search for wiki link targets in subdirectories.
1252 This is the default search behavior for GitHub and is
1253 automatically set to t in `gfm-mode'."
1254 :group 'markdown
1255 :type 'boolean
1256 :safe 'booleanp
1257 :package-version '(markdown-mode . "2.2"))
1259 (defcustom markdown-wiki-link-search-parent-directories nil
1260 "When non-nil, search for wiki link targets in parent directories.
1261 This is the default search behavior of Ikiwiki."
1262 :group 'markdown
1263 :type 'boolean
1264 :safe 'booleanp
1265 :package-version '(markdown-mode . "2.2"))
1267 (defcustom markdown-wiki-link-fontify-missing nil
1268 "When non-nil, change wiki link face according to existence of target files.
1269 This is expensive because it requires checking for the file each time the buffer
1270 changes or the user switches windows. It is disabled by default because it may
1271 cause lag when typing on slower machines."
1272 :group 'markdown
1273 :type 'boolean
1274 :safe 'booleanp
1275 :package-version '(markdown-mode . "2.2"))
1277 (defcustom markdown-uri-types
1278 '("acap" "cid" "data" "dav" "fax" "file" "ftp"
1279 "gopher" "http" "https" "imap" "ldap" "mailto"
1280 "mid" "message" "modem" "news" "nfs" "nntp"
1281 "pop" "prospero" "rtsp" "service" "sip" "tel"
1282 "telnet" "tip" "urn" "vemmi" "wais")
1283 "Link types for syntax highlighting of URIs."
1284 :group 'markdown
1285 :type '(repeat (string :tag "URI scheme")))
1287 (defcustom markdown-url-compose-char
1288 '(?∞ ?… ?⋯ ?# ?★ ?⚓)
1289 "Placeholder character for hidden URLs.
1290 This may be a single character or a list of characters. In case
1291 of a list, the first one that satisfies `char-displayable-p' will
1292 be used."
1293 :type '(choice
1294 (character :tag "Single URL replacement character")
1295 (repeat :tag "List of possible URL replacement characters"
1296 character))
1297 :package-version '(markdown-mode . "2.3"))
1299 (defcustom markdown-blockquote-display-char
1300 '("▌" "┃" ">")
1301 "String to display when hiding blockquote markup."
1302 :type 'string
1303 :type '(choice
1304 (string :tag "Single blockquote display string")
1305 (repeat :tag "List of possible blockquote display strings" string))
1306 :package-version '(markdown-mode . "2.3"))
1308 (defcustom markdown-hr-display-char
1309 '(?─ ?━ ?-)
1310 "Character for hiding horizontal rule markup.
1311 This may be a single character or a list of characters. In case
1312 of a list, the first one that satisfies `char-displayable-p' will
1313 be used."
1314 :group 'markdown
1315 :type '(choice
1316 (character :tag "Single HR display character")
1317 (repeat :tag "List of possible HR display characters" character))
1318 :package-version '(markdown-mode . "2.3"))
1320 (defcustom markdown-definition-display-char
1321 (cond ((char-displayable-p ?⁘) ?⁘)
1322 ((char-displayable-p ?⁙) ?⁙)
1323 ((char-displayable-p ?≡) ?≡)
1324 ((char-displayable-p ?⌑) ?⌑)
1325 ((char-displayable-p ?◊) ?◊)
1326 (t nil))
1327 "Character for replacing definition list markup."
1328 :type 'character
1329 :safe 'characterp
1330 :package-version '(markdown-mode . "2.3"))
1332 (defcustom markdown-enable-math nil
1333 "Syntax highlighting for inline LaTeX and itex expressions.
1334 Set this to a non-nil value to turn on math support by default.
1335 Math support can be enabled, disabled, or toggled later using
1336 `markdown-toggle-math' or \\[markdown-toggle-math]."
1337 :group 'markdown
1338 :type 'boolean
1339 :safe 'booleanp)
1340 (make-variable-buffer-local 'markdown-enable-math)
1342 (defcustom markdown-css-paths nil
1343 "URL of CSS file to link to in the output XHTML."
1344 :group 'markdown
1345 :type '(repeat (string :tag "CSS File Path")))
1347 (defcustom markdown-content-type ""
1348 "Content type string for the http-equiv header in XHTML output.
1349 When set to a non-empty string, insert the http-equiv attribute.
1350 Otherwise, this attribute is omitted."
1351 :group 'markdown
1352 :type 'string)
1354 (defcustom markdown-coding-system nil
1355 "Character set string for the http-equiv header in XHTML output.
1356 Defaults to `buffer-file-coding-system' (and falling back to
1357 `iso-8859-1' when not available). Common settings are `utf-8'
1358 and `iso-latin-1'. Use `list-coding-systems' for more choices."
1359 :group 'markdown
1360 :type 'coding-system)
1362 (defcustom markdown-export-kill-buffer t
1363 "Kill output buffer after HTML export.
1364 When non-nil, kill the HTML output buffer after
1365 exporting with `markdown-export'."
1366 :group 'markdown
1367 :type 'boolean
1368 :safe 'booleanp
1369 :package-version '(markdown-mode . "2.4"))
1371 (defcustom markdown-xhtml-header-content ""
1372 "Additional content to include in the XHTML <head> block."
1373 :group 'markdown
1374 :type 'string)
1376 (defcustom markdown-xhtml-standalone-regexp
1377 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
1378 "Regexp indicating whether `markdown-command' output is standalone XHTML."
1379 :group 'markdown
1380 :type 'regexp)
1382 (defcustom markdown-link-space-sub-char "_"
1383 "Character to use instead of spaces when mapping wiki links to filenames."
1384 :group 'markdown
1385 :type 'string)
1387 (defcustom markdown-reference-location 'header
1388 "Position where new reference definitions are inserted in the document."
1389 :group 'markdown
1390 :type '(choice (const :tag "At the end of the document" end)
1391 (const :tag "Immediately after the current block" immediately)
1392 (const :tag "At the end of the subtree" subtree)
1393 (const :tag "Before next header" header)))
1395 (defcustom markdown-footnote-location 'end
1396 "Position where new footnotes are inserted in the document."
1397 :group 'markdown
1398 :type '(choice (const :tag "At the end of the document" end)
1399 (const :tag "Immediately after the current block" immediately)
1400 (const :tag "At the end of the subtree" subtree)
1401 (const :tag "Before next header" header)))
1403 (defcustom markdown-unordered-list-item-prefix " * "
1404 "String inserted before unordered list items."
1405 :group 'markdown
1406 :type 'string)
1408 (defcustom markdown-nested-imenu-heading-index t
1409 "Use nested or flat imenu heading index.
1410 A nested index may provide more natural browsing from the menu,
1411 but a flat list may allow for faster keyboard navigation via tab
1412 completion."
1413 :group 'markdown
1414 :type 'boolean
1415 :safe 'booleanp
1416 :package-version '(markdown-mode . "2.2"))
1418 (defcustom markdown-make-gfm-checkboxes-buttons t
1419 "When non-nil, make GFM checkboxes into buttons."
1420 :group 'markdown
1421 :type 'boolean)
1423 (defcustom markdown-use-pandoc-style-yaml-metadata nil
1424 "When non-nil, allow YAML metadata anywhere in the document."
1425 :group 'markdown
1426 :type 'boolean)
1428 (defcustom markdown-split-window-direction 'any
1429 "Preference for splitting windows for static and live preview.
1430 The default value is 'any, which instructs Emacs to use
1431 `split-window-sensibly' to automatically choose how to split
1432 windows based on the values of `split-width-threshold' and
1433 `split-height-threshold' and the available windows. To force
1434 vertically split (left and right) windows, set this to 'vertical
1435 or 'right. To force horizontally split (top and bottom) windows,
1436 set this to 'horizontal or 'below."
1437 :group 'markdown
1438 :type '(choice (const :tag "Automatic" any)
1439 (const :tag "Right (vertical)" right)
1440 (const :tag "Below (horizontal)" below))
1441 :package-version '(markdown-mode . "2.2"))
1443 (defcustom markdown-live-preview-window-function
1444 'markdown-live-preview-window-eww
1445 "Function to display preview of Markdown output within Emacs.
1446 Function must update the buffer containing the preview and return
1447 the buffer."
1448 :group 'markdown
1449 :type 'function)
1451 (defcustom markdown-live-preview-delete-export 'delete-on-destroy
1452 "Delete exported HTML file when using `markdown-live-preview-export'.
1453 If set to 'delete-on-export, delete on every export. When set to
1454 'delete-on-destroy delete when quitting from command
1455 `markdown-live-preview-mode'. Never delete if set to nil."
1456 :group 'markdown
1457 :type '(choice
1458 (const :tag "Delete on every export" delete-on-export)
1459 (const :tag "Delete when quitting live preview" delete-on-destroy)
1460 (const :tag "Never delete" nil)))
1462 (defcustom markdown-list-indent-width 4
1463 "Depth of indentation for markdown lists.
1464 Used in `markdown-demote-list-item' and
1465 `markdown-promote-list-item'."
1466 :group 'markdown
1467 :type 'integer)
1469 (defcustom markdown-enable-prefix-prompts t
1470 "Display prompts for certain prefix commands.
1471 Set to nil to disable these prompts."
1472 :group 'markdown
1473 :type 'boolean
1474 :safe 'booleanp
1475 :package-version '(markdown-mode . "2.3"))
1477 (defcustom markdown-gfm-additional-languages nil
1478 "Extra languages made available when inserting GFM code blocks.
1479 Language strings must have be trimmed of whitespace and not
1480 contain any curly braces. They may be of arbitrary
1481 capitalization, though."
1482 :group 'markdown
1483 :type '(repeat (string :validate markdown-validate-language-string)))
1485 (defcustom markdown-gfm-use-electric-backquote t
1486 "Use `markdown-electric-backquote' when backquote is hit three times."
1487 :group 'markdown
1488 :type 'boolean)
1490 (defcustom markdown-gfm-downcase-languages t
1491 "If non-nil, downcase suggested languages.
1492 This applies to insertions done with
1493 `markdown-electric-backquote'."
1494 :group 'markdown
1495 :type 'boolean)
1497 (defcustom markdown-edit-code-block-default-mode 'normal-mode
1498 "Default mode to use for editing code blocks.
1499 This mode is used when automatic detection fails, such as for GFM
1500 code blocks with no language specified."
1501 :group 'markdown
1502 :type 'symbol
1503 :package-version '(markdown-mode . "2.4"))
1505 (defcustom markdown-gfm-uppercase-checkbox nil
1506 "If non-nil, use [X] for completed checkboxes, [x] otherwise."
1507 :group 'markdown
1508 :type 'boolean
1509 :safe 'booleanp)
1511 (defcustom markdown-hide-urls nil
1512 "Hide URLs of inline links and reference tags of reference links.
1513 Such URLs will be replaced by a single customizable
1514 character, defined by `markdown-url-compose-char', but are still part
1515 of the buffer. Links can be edited interactively with
1516 \\[markdown-insert-link] or, for example, by deleting the final
1517 parenthesis to remove the invisibility property. You can also
1518 hover your mouse pointer over the link text to see the URL.
1519 Set this to a non-nil value to turn this feature on by default.
1520 You can interactively set the value of this variable by calling
1521 `markdown-toggle-url-hiding', pressing \\[markdown-toggle-url-hiding],
1522 or from the menu Markdown > Links & Images menu."
1523 :group 'markdown
1524 :type 'boolean
1525 :safe 'booleanp
1526 :package-version '(markdown-mode . "2.3"))
1527 (make-variable-buffer-local 'markdown-hide-urls)
1529 (defcustom markdown-translate-filename-function #'identity
1530 "Function to use to translate filenames when following links.
1531 \\<markdown-mode-map>\\[markdown-follow-thing-at-point] and \\[markdown-follow-link-at-point]
1532 call this function with the filename as only argument whenever
1533 they encounter a filename (instead of a URL) to be visited and
1534 use its return value instead of the filename in the link. For
1535 example, if absolute filenames are actually relative to a server
1536 root directory, you can set
1537 `markdown-translate-filename-function' to a function that
1538 prepends the root directory to the given filename."
1539 :group 'markdown
1540 :type 'function
1541 :risky t
1542 :package-version '(markdown-mode . "2.4"))
1545 ;;; Regular Expressions =======================================================
1547 (defconst markdown-regex-comment-start
1548 "<!--"
1549 "Regular expression matches HTML comment opening.")
1551 (defconst markdown-regex-comment-end
1552 "--[ \t]*>"
1553 "Regular expression matches HTML comment closing.")
1555 (defconst markdown-regex-link-inline
1556 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)\\((\\)\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?\\()\\)"
1557 "Regular expression for a [text](file) or an image link ![text](file).
1558 Group 1 matches the leading exclamation point (optional).
1559 Group 2 matches the opening square bracket.
1560 Group 3 matches the text inside the square brackets.
1561 Group 4 matches the closing square bracket.
1562 Group 5 matches the opening parenthesis.
1563 Group 6 matches the URL.
1564 Group 7 matches the title (optional).
1565 Group 8 matches the closing parenthesis.")
1567 (defconst markdown-regex-link-reference
1568 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)[ ]?\\(\\[\\)\\([^]]*?\\)\\(\\]\\)"
1569 "Regular expression for a reference link [text][id].
1570 Group 1 matches the leading exclamation point (optional).
1571 Group 2 matches the opening square bracket for the link text.
1572 Group 3 matches the text inside the square brackets.
1573 Group 4 matches the closing square bracket for the link text.
1574 Group 5 matches the opening square bracket for the reference label.
1575 Group 6 matches the reference label.
1576 Group 7 matches the closing square bracket for the reference label.")
1578 (defconst markdown-regex-reference-definition
1579 "^ \\{0,3\\}\\(\\[\\)\\([^]\n]+?\\)\\(\\]\\)\\(:\\)\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
1580 "Regular expression for a reference definition.
1581 Group 1 matches the opening square bracket.
1582 Group 2 matches the reference label.
1583 Group 3 matches the closing square bracket.
1584 Group 4 matches the colon.
1585 Group 5 matches the URL.
1586 Group 6 matches the title attribute (optional).")
1588 (defconst markdown-regex-footnote
1589 "\\(\\[\\^\\)\\(.+?\\)\\(\\]\\)"
1590 "Regular expression for a footnote marker [^fn].
1591 Group 1 matches the opening square bracket and carat.
1592 Group 2 matches only the label, without the surrounding markup.
1593 Group 3 matches the closing square bracket.")
1595 (defconst markdown-regex-header
1596 "^\\(?:\\([^\r\n\t -].*\\)\n\\(?:\\(=+\\)\\|\\(-+\\)\\)\\|\\(#+[ \t]+\\)\\(.*?\\)\\([ \t]*#*\\)\\)$"
1597 "Regexp identifying Markdown headings.
1598 Group 1 matches the text of a setext heading.
1599 Group 2 matches the underline of a level-1 setext heading.
1600 Group 3 matches the underline of a level-2 setext heading.
1601 Group 4 matches the opening hash marks of an atx heading and whitespace.
1602 Group 5 matches the text, without surrounding whitespace, of an atx heading.
1603 Group 6 matches the closing whitespace and hash marks of an atx heading.")
1605 (defconst markdown-regex-header-setext
1606 "^\\([^\r\n\t -].*\\)\n\\(=+\\|-+\\)$"
1607 "Regular expression for generic setext-style (underline) headers.")
1609 (defconst markdown-regex-header-atx
1610 "^\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1611 "Regular expression for generic atx-style (hash mark) headers.")
1613 (defconst markdown-regex-hr
1614 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1615 "Regular expression for matching Markdown horizontal rules.")
1617 (defconst markdown-regex-code
1618 "\\(?:\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(?:.\\|\n[^\n]\\)*?[^`]\\)\\(\\2\\)\\)\\(?:[^`]\\|\\'\\)"
1619 "Regular expression for matching inline code fragments.
1621 Group 1 matches the entire code fragment including the backquotes.
1622 Group 2 matches the opening backquotes.
1623 Group 3 matches the code fragment itself, without backquotes.
1624 Group 4 matches the closing backquotes.
1626 The leading, unnumbered group ensures that the leading backquote
1627 character is not escaped.
1628 The last group, also unnumbered, requires that the character
1629 following the code fragment is not a backquote.
1630 Note that \\(?:.\\|\n[^\n]\\) matches any character, including newlines,
1631 but not two newlines in a row.")
1633 (defconst markdown-regex-kbd
1634 "\\(<kbd>\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(</kbd>\\)"
1635 "Regular expression for matching <kbd> tags.
1636 Groups 1 and 3 match the opening and closing tags.
1637 Group 2 matches the key sequence.")
1639 (defconst markdown-regex-gfm-code-block-open
1640 "^[[:blank:]]*\\(```\\)\\([[:blank:]]*{?[[:blank:]]*\\)\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$"
1641 "Regular expression matching opening of GFM code blocks.
1642 Group 1 matches the opening three backquotes and any following whitespace.
1643 Group 2 matches the opening brace (optional) and surrounding whitespace.
1644 Group 3 matches the language identifier (optional).
1645 Group 4 matches the info string (optional).
1646 Group 5 matches the closing brace (optional), whitespace, and newline.
1647 Groups need to agree with `markdown-regex-tilde-fence-begin'.")
1649 (defconst markdown-regex-gfm-code-block-close
1650 "^[[:blank:]]*\\(```\\)\\(\\s *?\\)$"
1651 "Regular expression matching closing of GFM code blocks.
1652 Group 1 matches the closing three backquotes.
1653 Group 2 matches any whitespace and the final newline.")
1655 (defconst markdown-regex-pre
1656 "^\\( \\|\t\\).*$"
1657 "Regular expression for matching preformatted text sections.")
1659 (defconst markdown-regex-list
1660 "^\\([ \t]*\\)\\([0-9#]+\\.\\|[\\*\\+:-]\\)\\([ \t]+\\)"
1661 "Regular expression for matching list items.")
1663 (defconst markdown-regex-bold
1664 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1665 "Regular expression for matching bold text.
1666 Group 1 matches the character before the opening asterisk or
1667 underscore, if any, ensuring that it is not a backslash escape.
1668 Group 2 matches the entire expression, including delimiters.
1669 Groups 3 and 5 matches the opening and closing delimiters.
1670 Group 4 matches the text inside the delimiters.")
1672 (defconst markdown-regex-italic
1673 "\\(?:^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1674 "Regular expression for matching italic text.
1675 The leading unnumbered matches the character before the opening
1676 asterisk or underscore, if any, ensuring that it is not a
1677 backslash escape.
1678 Group 1 matches the entire expression, including delimiters.
1679 Groups 2 and 4 matches the opening and closing delimiters.
1680 Group 3 matches the text inside the delimiters.")
1682 (defconst markdown-regex-strike-through
1683 "\\(^\\|[^\\]\\)\\(\\(~~\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(~~\\)\\)"
1684 "Regular expression for matching strike-through text.
1685 Group 1 matches the character before the opening tilde, if any,
1686 ensuring that it is not a backslash escape.
1687 Group 2 matches the entire expression, including delimiters.
1688 Groups 3 and 5 matches the opening and closing delimiters.
1689 Group 4 matches the text inside the delimiters.")
1691 (defconst markdown-regex-gfm-italic
1692 "\\(?:^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\2\\|[^ ]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1693 "Regular expression for matching italic text in GitHub Flavored Markdown.
1694 Underscores in words are not treated as special.
1695 Group 1 matches the entire expression, including delimiters.
1696 Groups 2 and 4 matches the opening and closing delimiters.
1697 Group 3 matches the text inside the delimiters.")
1699 (defconst markdown-regex-blockquote
1700 "^[ \t]*\\([A-Z]?>\\)\\([ \t]*\\)\\(.*\\)$"
1701 "Regular expression for matching blockquote lines.
1702 Also accounts for a potential capital letter preceding the angle
1703 bracket, for use with Leanpub blocks (asides, warnings, info
1704 blocks, etc.).
1705 Group 1 matches the leading angle bracket.
1706 Group 2 matches the separating whitespace.
1707 Group 3 matches the text.")
1709 (defconst markdown-regex-line-break
1710 "[^ \n\t][ \t]*\\( \\)$"
1711 "Regular expression for matching line breaks.")
1713 (defconst markdown-regex-wiki-link
1714 "\\(?:^\\|[^\\]\\)\\(\\(\\[\\[\\)\\([^]|]+\\)\\(?:\\(|\\)\\([^]]+\\)\\)?\\(\\]\\]\\)\\)"
1715 "Regular expression for matching wiki links.
1716 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1717 wiki links of the form [[PageName|link text]].
1718 The meanings of the first and second components depend
1719 on the value of `markdown-wiki-link-alias-first'.
1721 Group 1 matches the entire link.
1722 Group 2 matches the opening square brackets.
1723 Group 3 matches the first component of the wiki link.
1724 Group 4 matches the pipe separator, when present.
1725 Group 5 matches the second component of the wiki link, when present.
1726 Group 6 matches the closing square brackets.")
1728 (defconst markdown-regex-uri
1729 (concat "\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+\\)")
1730 "Regular expression for matching inline URIs.")
1732 (defconst markdown-regex-angle-uri
1733 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1734 "Regular expression for matching inline URIs in angle brackets.")
1736 (defconst markdown-regex-email
1737 "<\\(\\(?:\\sw\\|\\s_\\|\\s.\\)+@\\(?:\\sw\\|\\s_\\|\\s.\\)+\\)>"
1738 "Regular expression for matching inline email addresses.")
1740 (defsubst markdown-make-regex-link-generic ()
1741 "Make regular expression for matching any recognized link."
1742 (concat "\\(?:" markdown-regex-link-inline
1743 (when markdown-enable-wiki-links
1744 (concat "\\|" markdown-regex-wiki-link))
1745 "\\|" markdown-regex-link-reference
1746 "\\|" markdown-regex-angle-uri "\\)"))
1748 (defconst markdown-regex-gfm-checkbox
1749 " \\(\\[[ xX]\\]\\) "
1750 "Regular expression for matching GFM checkboxes.
1751 Group 1 matches the text to become a button.")
1753 (defconst markdown-regex-block-separator
1754 "\n[\n\t\f ]*\n"
1755 "Regular expression for matching block boundaries.")
1757 (defconst markdown-regex-block-separator-noindent
1758 (concat "\\(\\`\\|\\(" markdown-regex-block-separator "\\)[^\n\t\f ]\\)")
1759 "Regexp for block separators before lines with no indentation.")
1761 (defconst markdown-regex-math-inline-single
1762 "\\(?:^\\|[^\\]\\)\\(\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\)"
1763 "Regular expression for itex $..$ math mode expressions.
1764 Groups 1 and 3 match the opening and closing dollar signs.
1765 Group 2 matches the mathematical expression contained within.")
1767 (defconst markdown-regex-math-inline-double
1768 "\\(?:^\\|[^\\]\\)\\(\\$\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\$\\)"
1769 "Regular expression for itex $$..$$ math mode expressions.
1770 Groups 1 and 3 match opening and closing dollar signs.
1771 Group 2 matches the mathematical expression contained within.")
1773 (defconst markdown-regex-math-display
1774 (rx line-start
1775 (group (group (repeat 1 2 "\\")) "[")
1776 (group (*? anything))
1777 (group (backref 2) "]")
1778 line-end)
1779 "Regular expression for \[..\] or \\[..\\] display math.
1780 Groups 1 and 4 match the opening and closing markup.
1781 Group 3 matches the mathematical expression contained within.
1782 Group 2 matches the opening slashes, and is used internally to
1783 match the closing slashes.")
1785 (defsubst markdown-make-tilde-fence-regex (num-tildes &optional end-of-line)
1786 "Return regexp matching a tilde code fence at least NUM-TILDES long.
1787 END-OF-LINE is the regexp construct to indicate end of line; $ if
1788 missing."
1789 (format "%s%d%s%s" "^[[:blank:]]*\\([~]\\{" num-tildes ",\\}\\)"
1790 (or end-of-line "$")))
1792 (defconst markdown-regex-tilde-fence-begin
1793 (markdown-make-tilde-fence-regex
1794 3 "\\([[:blank:]]*{?\\)[[:blank:]]*\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$")
1795 "Regular expression for matching tilde-fenced code blocks.
1796 Group 1 matches the opening tildes.
1797 Group 2 matches (optional) opening brace and surrounding whitespace.
1798 Group 3 matches the language identifier (optional).
1799 Group 4 matches the info string (optional).
1800 Group 5 matches the closing brace (optional) and any surrounding whitespace.
1801 Groups need to agree with `markdown-regex-gfm-code-block-open'.")
1803 (defconst markdown-regex-declarative-metadata
1804 "^\\([[:alpha:]][[:alpha:] _-]*?\\)\\([:=][ \t]*\\)\\(.*\\)$"
1805 "Regular expression for matching declarative metadata statements.
1806 This matches MultiMarkdown metadata as well as YAML and TOML
1807 assignments such as the following:
1809 variable: value
1813 variable = value")
1815 (defconst markdown-regex-pandoc-metadata
1816 "^\\(%\\)\\([ \t]*\\)\\(.*\\(?:\n[ \t]+.*\\)*\\)"
1817 "Regular expression for matching Pandoc metadata.")
1819 (defconst markdown-regex-yaml-metadata-border
1820 "\\(-\\{3\\}\\)$"
1821 "Regular expression for matching YAML metadata.")
1823 (defconst markdown-regex-yaml-pandoc-metadata-end-border
1824 "^\\(\\.\\{3\\}\\|\\-\\{3\\}\\)$"
1825 "Regular expression for matching YAML metadata end borders.")
1827 (defsubst markdown-get-yaml-metadata-start-border ()
1828 "Return YAML metadata start border depending upon whether Pandoc is used."
1829 (concat
1830 (if markdown-use-pandoc-style-yaml-metadata "^" "\\`")
1831 markdown-regex-yaml-metadata-border))
1833 (defsubst markdown-get-yaml-metadata-end-border (_)
1834 "Return YAML metadata end border depending upon whether Pandoc is used."
1835 (if markdown-use-pandoc-style-yaml-metadata
1836 markdown-regex-yaml-pandoc-metadata-end-border
1837 markdown-regex-yaml-metadata-border))
1839 (defconst markdown-regex-inline-attributes
1840 "[ \t]*\\({:?\\)[ \t]*\\(\\(#[[:alpha:]_.:-]+\\|\\.[[:alpha:]_.:-]+\\|\\w+=['\"]?[^\n'\"]*['\"]?\\),?[ \t]*\\)+\\(}\\)[ \t]*$"
1841 "Regular expression for matching inline identifiers or attribute lists.
1842 Compatible with Pandoc, Python Markdown, PHP Markdown Extra, and Leanpub.")
1844 (defconst markdown-regex-leanpub-sections
1845 (concat
1846 "^\\({\\)\\("
1847 (regexp-opt '("frontmatter" "mainmatter" "backmatter" "appendix" "pagebreak"))
1848 "\\)\\(}\\)[ \t]*\n")
1849 "Regular expression for Leanpub section markers and related syntax.")
1851 (defconst markdown-regex-sub-superscript
1852 "\\(?:^\\|[^\\~^]\\)\\(\\([~^]\\)\\([[:alnum:]]+\\)\\(\\2\\)\\)"
1853 "The regular expression matching a sub- or superscript.
1854 The leading un-numbered group matches the character before the
1855 opening tilde or carat, if any, ensuring that it is not a
1856 backslash escape, carat, or tilde.
1857 Group 1 matches the entire expression, including markup.
1858 Group 2 matches the opening markup--a tilde or carat.
1859 Group 3 matches the text inside the delimiters.
1860 Group 4 matches the closing markup--a tilde or carat.")
1862 (defconst markdown-regex-include
1863 "^\\(<<\\)\\(?:\\(\\[\\)\\(.*\\)\\(\\]\\)\\)?\\(?:\\((\\)\\(.*\\)\\()\\)\\)?\\(?:\\({\\)\\(.*\\)\\(}\\)\\)?$"
1864 "Regular expression matching common forms of include syntax.
1865 Marked 2, Leanpub, and other processors support some of these forms:
1867 <<[sections/section1.md]
1868 <<(folder/filename)
1869 <<[Code title](folder/filename)
1870 <<{folder/raw_file.html}
1872 Group 1 matches the opening two angle brackets.
1873 Groups 2-4 match the opening square bracket, the text inside,
1874 and the closing square bracket, respectively.
1875 Groups 5-7 match the opening parenthesis, the text inside, and
1876 the closing parenthesis.
1877 Groups 8-10 match the opening brace, the text inside, and the brace.")
1879 (defconst markdown-regex-pandoc-inline-footnote
1880 "\\(\\^\\)\\(\\[\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(\\]\\)"
1881 "Regular expression for Pandoc inline footnote^[footnote text].
1882 Group 1 matches the opening caret.
1883 Group 2 matches the opening square bracket.
1884 Group 3 matches the footnote text, without the surrounding markup.
1885 Group 4 matches the closing square bracket.")
1888 ;;; Syntax ====================================================================
1890 (defsubst markdown-in-comment-p (&optional pos)
1891 "Return non-nil if POS is in a comment.
1892 If POS is not given, use point instead."
1893 (nth 4 (syntax-ppss pos)))
1895 (defun markdown-syntax-propertize-extend-region (start end)
1896 "Extend START to END region to include an entire block of text.
1897 This helps improve syntax analysis for block constructs.
1898 Returns a cons (NEW-START . NEW-END) or nil if no adjustment should be made.
1899 Function is called repeatedly until it returns nil. For details, see
1900 `syntax-propertize-extend-region-functions'."
1901 (save-match-data
1902 (save-excursion
1903 (let* ((new-start (progn (goto-char start)
1904 (skip-chars-forward "\n")
1905 (if (re-search-backward "\n\n" nil t)
1906 (min start (match-end 0))
1907 (point-min))))
1908 (new-end (progn (goto-char end)
1909 (skip-chars-backward "\n")
1910 (if (re-search-forward "\n\n" nil t)
1911 (max end (match-beginning 0))
1912 (point-max))))
1913 (code-match (markdown-code-block-at-pos new-start))
1914 (new-start (or (and code-match (cl-first code-match)) new-start))
1915 (code-match (and (< end (point-max)) (markdown-code-block-at-pos end)))
1916 (new-end (or (and code-match (cl-second code-match)) new-end)))
1917 (unless (and (eq new-start start) (eq new-end end))
1918 (cons new-start (min new-end (point-max))))))))
1920 (defun markdown-font-lock-extend-region-function (start end _)
1921 "Used in `jit-lock-after-change-extend-region-functions'.
1922 Delegates to `markdown-syntax-propertize-extend-region'. START
1923 and END are the previous region to refontify."
1924 (let ((res (markdown-syntax-propertize-extend-region start end)))
1925 (when res
1926 ;; syntax-propertize-function is not called when character at
1927 ;; (point-max) is deleted, but font-lock-extend-region-functions
1928 ;; are called. Force a syntax property update in that case.
1929 (when (= end (point-max))
1930 ;; This function is called in a buffer modification hook.
1931 ;; `markdown-syntax-propertize' doesn't save the match data,
1932 ;; so we have to do it here.
1933 (save-match-data
1934 (markdown-syntax-propertize (car res) (cdr res))))
1935 (setq jit-lock-start (car res)
1936 jit-lock-end (cdr res)))))
1938 (defun markdown-syntax-propertize-pre-blocks (start end)
1939 "Match preformatted text blocks from START to END."
1940 (save-excursion
1941 (goto-char start)
1942 (let ((levels (markdown-calculate-list-levels))
1943 indent pre-regexp close-regexp open close)
1944 (while (and (< (point) end) (not close))
1945 ;; Search for a region with sufficient indentation
1946 (if (null levels)
1947 (setq indent 1)
1948 (setq indent (1+ (length levels))))
1949 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1950 (setq close-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1952 (cond
1953 ;; If not at the beginning of a line, move forward
1954 ((not (bolp)) (forward-line))
1955 ;; Move past blank lines
1956 ((markdown-cur-line-blank) (forward-line))
1957 ;; At headers and horizontal rules, reset levels
1958 ((markdown-new-baseline) (forward-line) (setq levels nil))
1959 ;; If the current line has sufficient indentation, mark out pre block
1960 ;; The opening should be preceded by a blank line.
1961 ((and (looking-at pre-regexp)
1962 (markdown-prev-line-blank-p))
1963 (setq open (match-beginning 0))
1964 (while (and (or (looking-at-p pre-regexp) (markdown-cur-line-blank))
1965 (not (eobp)))
1966 (forward-line))
1967 (skip-syntax-backward "-")
1968 (setq close (point)))
1969 ;; If current line has a list marker, update levels, move to end of block
1970 ((looking-at markdown-regex-list)
1971 (setq levels (markdown-update-list-levels
1972 (match-string 2) (current-indentation) levels))
1973 (markdown-end-of-text-block))
1974 ;; If this is the end of the indentation level, adjust levels accordingly.
1975 ;; Only match end of indentation level if levels is not the empty list.
1976 ((and (car levels) (looking-at-p close-regexp))
1977 (setq levels (markdown-update-list-levels
1978 nil (current-indentation) levels))
1979 (markdown-end-of-text-block))
1980 (t (markdown-end-of-text-block))))
1982 (when (and open close)
1983 ;; Set text property data
1984 (put-text-property open close 'markdown-pre (list open close))
1985 ;; Recursively search again
1986 (markdown-syntax-propertize-pre-blocks (point) end)))))
1988 (defconst markdown-fenced-block-pairs
1989 `(((,markdown-regex-tilde-fence-begin markdown-tilde-fence-begin)
1990 (markdown-make-tilde-fence-regex markdown-tilde-fence-end)
1991 markdown-fenced-code)
1992 ((markdown-get-yaml-metadata-start-border markdown-yaml-metadata-begin)
1993 (markdown-get-yaml-metadata-end-border markdown-yaml-metadata-end)
1994 markdown-yaml-metadata-section)
1995 ((,markdown-regex-gfm-code-block-open markdown-gfm-block-begin)
1996 (,markdown-regex-gfm-code-block-close markdown-gfm-block-end)
1997 markdown-gfm-code))
1998 "Mapping of regular expressions to \"fenced-block\" constructs.
1999 These constructs are distinguished by having a distinctive start
2000 and end pattern, both of which take up an entire line of text,
2001 but no special pattern to identify text within the fenced
2002 blocks (unlike blockquotes and indented-code sections).
2004 Each element within this list takes the form:
2006 ((START-REGEX-OR-FUN START-PROPERTY)
2007 (END-REGEX-OR-FUN END-PROPERTY)
2008 MIDDLE-PROPERTY)
2010 Each *-REGEX-OR-FUN element can be a regular expression as a string, or a
2011 function which evaluates to same. Functions for START-REGEX-OR-FUN accept no
2012 arguments, but functions for END-REGEX-OR-FUN accept a single numerical argument
2013 which is the length of the first group of the START-REGEX-OR-FUN match, which
2014 can be ignored if unnecessary. `markdown-maybe-funcall-regexp' is used to
2015 evaluate these into \"real\" regexps.
2017 The *-PROPERTY elements are the text properties applied to each part of the
2018 block construct when it is matched using
2019 `markdown-syntax-propertize-fenced-block-constructs'. START-PROPERTY is applied
2020 to the text matching START-REGEX-OR-FUN, END-PROPERTY to END-REGEX-OR-FUN, and
2021 MIDDLE-PROPERTY to the text in between the two. The value of *-PROPERTY is the
2022 `match-data' when the regexp was matched to the text. In the case of
2023 MIDDLE-PROPERTY, the value is a false match data of the form '(begin end), with
2024 begin and end set to the edges of the \"middle\" text. This makes fontification
2025 easier.")
2027 (defun markdown-text-property-at-point (prop)
2028 (get-text-property (point) prop))
2030 (defsubst markdown-maybe-funcall-regexp (object &optional arg)
2031 (cond ((functionp object)
2032 (if arg (funcall object arg) (funcall object)))
2033 ((stringp object) object)
2034 (t (error "Object cannot be turned into regex"))))
2036 (defsubst markdown-get-start-fence-regexp ()
2037 "Return regexp to find all \"start\" sections of fenced block constructs.
2038 Which construct is actually contained in the match must be found separately."
2039 (mapconcat
2040 #'identity
2041 (mapcar (lambda (entry) (markdown-maybe-funcall-regexp (caar entry)))
2042 markdown-fenced-block-pairs)
2043 "\\|"))
2045 (defun markdown-get-fenced-block-begin-properties ()
2046 (cl-mapcar (lambda (entry) (cl-cadar entry)) markdown-fenced-block-pairs))
2048 (defun markdown-get-fenced-block-end-properties ()
2049 (cl-mapcar (lambda (entry) (cl-cadadr entry)) markdown-fenced-block-pairs))
2051 (defun markdown-get-fenced-block-middle-properties ()
2052 (cl-mapcar #'cl-third markdown-fenced-block-pairs))
2054 (defun markdown-find-previous-prop (prop &optional lim)
2055 "Find previous place where property PROP is non-nil, up to LIM.
2056 Return a cons of (pos . property). pos is point if point contains
2057 non-nil PROP."
2058 (let ((res
2059 (if (get-text-property (point) prop) (point)
2060 (previous-single-property-change
2061 (point) prop nil (or lim (point-min))))))
2062 (when (and (not (get-text-property res prop))
2063 (> res (point-min))
2064 (get-text-property (1- res) prop))
2065 (cl-decf res))
2066 (when (and res (get-text-property res prop)) (cons res prop))))
2068 (defun markdown-find-next-prop (prop &optional lim)
2069 "Find next place where property PROP is non-nil, up to LIM.
2070 Return a cons of (POS . PROPERTY) where POS is point if point
2071 contains non-nil PROP."
2072 (let ((res
2073 (if (get-text-property (point) prop) (point)
2074 (next-single-property-change
2075 (point) prop nil (or lim (point-max))))))
2076 (when (and res (get-text-property res prop)) (cons res prop))))
2078 (defun markdown-min-of-seq (map-fn seq)
2079 "Apply MAP-FN to SEQ and return element of SEQ with minimum value of MAP-FN."
2080 (cl-loop for el in seq
2081 with min = 1.0e+INF ; infinity
2082 with min-el = nil
2083 do (let ((res (funcall map-fn el)))
2084 (when (< res min)
2085 (setq min res)
2086 (setq min-el el)))
2087 finally return min-el))
2089 (defun markdown-max-of-seq (map-fn seq)
2090 "Apply MAP-FN to SEQ and return element of SEQ with maximum value of MAP-FN."
2091 (cl-loop for el in seq
2092 with max = -1.0e+INF ; negative infinity
2093 with max-el = nil
2094 do (let ((res (funcall map-fn el)))
2095 (when (and res (> res max))
2096 (setq max res)
2097 (setq max-el el)))
2098 finally return max-el))
2100 (defun markdown-find-previous-block ()
2101 "Find previous block.
2102 Detect whether `markdown-syntax-propertize-fenced-block-constructs' was
2103 unable to propertize the entire block, but was able to propertize the beginning
2104 of the block. If so, return a cons of (pos . property) where the beginning of
2105 the block was propertized."
2106 (let ((start-pt (point))
2107 (closest-open
2108 (markdown-max-of-seq
2109 #'car
2110 (cl-remove-if
2111 #'null
2112 (cl-mapcar
2113 #'markdown-find-previous-prop
2114 (markdown-get-fenced-block-begin-properties))))))
2115 (when closest-open
2116 (let* ((length-of-open-match
2117 (let ((match-d
2118 (get-text-property (car closest-open) (cdr closest-open))))
2119 (- (cl-fourth match-d) (cl-third match-d))))
2120 (end-regexp
2121 (markdown-maybe-funcall-regexp
2122 (cl-caadr
2123 (cl-find-if
2124 (lambda (entry) (eq (cl-cadar entry) (cdr closest-open)))
2125 markdown-fenced-block-pairs))
2126 length-of-open-match))
2127 (end-prop-loc
2128 (save-excursion
2129 (save-match-data
2130 (goto-char (car closest-open))
2131 (and (re-search-forward end-regexp start-pt t)
2132 (match-beginning 0))))))
2133 (and (not end-prop-loc) closest-open)))))
2135 (defun markdown-get-fenced-block-from-start (prop)
2136 "Return limits of an enclosing fenced block from its start, using PROP.
2137 Return value is a list usable as `match-data'."
2138 (catch 'no-rest-of-block
2139 (let* ((correct-entry
2140 (cl-find-if
2141 (lambda (entry) (eq (cl-cadar entry) prop))
2142 markdown-fenced-block-pairs))
2143 (begin-of-begin (cl-first (markdown-text-property-at-point prop)))
2144 (middle-prop (cl-third correct-entry))
2145 (end-prop (cl-cadadr correct-entry))
2146 (end-of-end
2147 (save-excursion
2148 (goto-char (match-end 0)) ; end of begin
2149 (unless (eobp) (forward-char))
2150 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
2151 (if (not mid-prop-v) ; no middle
2152 (progn
2153 ;; try to find end by advancing one
2154 (let ((end-prop-v
2155 (markdown-text-property-at-point end-prop)))
2156 (if end-prop-v (cl-second end-prop-v)
2157 (throw 'no-rest-of-block nil))))
2158 (set-match-data mid-prop-v)
2159 (goto-char (match-end 0)) ; end of middle
2160 (beginning-of-line) ; into end
2161 (cl-second (markdown-text-property-at-point end-prop)))))))
2162 (list begin-of-begin end-of-end))))
2164 (defun markdown-get-fenced-block-from-middle (prop)
2165 "Return limits of an enclosing fenced block from its middle, using PROP.
2166 Return value is a list usable as `match-data'."
2167 (let* ((correct-entry
2168 (cl-find-if
2169 (lambda (entry) (eq (cl-third entry) prop))
2170 markdown-fenced-block-pairs))
2171 (begin-prop (cl-cadar correct-entry))
2172 (begin-of-begin
2173 (save-excursion
2174 (goto-char (match-beginning 0))
2175 (unless (bobp) (forward-line -1))
2176 (beginning-of-line)
2177 (cl-first (markdown-text-property-at-point begin-prop))))
2178 (end-prop (cl-cadadr correct-entry))
2179 (end-of-end
2180 (save-excursion
2181 (goto-char (match-end 0))
2182 (beginning-of-line)
2183 (cl-second (markdown-text-property-at-point end-prop)))))
2184 (list begin-of-begin end-of-end)))
2186 (defun markdown-get-fenced-block-from-end (prop)
2187 "Return limits of an enclosing fenced block from its end, using PROP.
2188 Return value is a list usable as `match-data'."
2189 (let* ((correct-entry
2190 (cl-find-if
2191 (lambda (entry) (eq (cl-cadadr entry) prop))
2192 markdown-fenced-block-pairs))
2193 (end-of-end (cl-second (markdown-text-property-at-point prop)))
2194 (middle-prop (cl-third correct-entry))
2195 (begin-prop (cl-cadar correct-entry))
2196 (begin-of-begin
2197 (save-excursion
2198 (goto-char (match-beginning 0)) ; beginning of end
2199 (unless (bobp) (backward-char)) ; into middle
2200 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
2201 (if (not mid-prop-v)
2202 (progn
2203 (beginning-of-line)
2204 (cl-first (markdown-text-property-at-point begin-prop)))
2205 (set-match-data mid-prop-v)
2206 (goto-char (match-beginning 0)) ; beginning of middle
2207 (unless (bobp) (forward-line -1)) ; into beginning
2208 (beginning-of-line)
2209 (cl-first (markdown-text-property-at-point begin-prop)))))))
2210 (list begin-of-begin end-of-end)))
2212 (defun markdown-get-enclosing-fenced-block-construct (&optional pos)
2213 "Get \"fake\" match data for block enclosing POS.
2214 Returns fake match data which encloses the start, middle, and end
2215 of the block construct enclosing POS, if it exists. Used in
2216 `markdown-code-block-at-pos'."
2217 (save-excursion
2218 (when pos (goto-char pos))
2219 (beginning-of-line)
2220 (car
2221 (cl-remove-if
2222 #'null
2223 (cl-mapcar
2224 (lambda (fun-and-prop)
2225 (cl-destructuring-bind (fun prop) fun-and-prop
2226 (when prop
2227 (save-match-data
2228 (set-match-data (markdown-text-property-at-point prop))
2229 (funcall fun prop)))))
2230 `((markdown-get-fenced-block-from-start
2231 ,(cl-find-if
2232 #'markdown-text-property-at-point
2233 (markdown-get-fenced-block-begin-properties)))
2234 (markdown-get-fenced-block-from-middle
2235 ,(cl-find-if
2236 #'markdown-text-property-at-point
2237 (markdown-get-fenced-block-middle-properties)))
2238 (markdown-get-fenced-block-from-end
2239 ,(cl-find-if
2240 #'markdown-text-property-at-point
2241 (markdown-get-fenced-block-end-properties)))))))))
2243 (defun markdown-propertize-end-match (reg end fence-spec middle-begin)
2244 "Get match for REG up to END, if exists, and propertize appropriately.
2245 FENCE-SPEC is an entry in `markdown-fenced-block-pairs' and
2246 MIDDLE-BEGIN is the start of the \"middle\" section of the block."
2247 (when (re-search-forward reg end t)
2248 (let ((close-begin (match-beginning 0)) ; Start of closing line.
2249 (close-end (match-end 0)) ; End of closing line.
2250 (close-data (match-data t))) ; Match data for closing line.
2251 ;; Propertize middle section of fenced block.
2252 (put-text-property middle-begin close-begin
2253 (cl-third fence-spec)
2254 (list middle-begin close-begin))
2255 ;; Propertize closing line of fenced block.
2256 (put-text-property close-begin close-end
2257 (cl-cadadr fence-spec) close-data))))
2259 (defun markdown-syntax-propertize-fenced-block-constructs (start end)
2260 "Propertize according to `markdown-fenced-block-pairs' from START to END.
2261 If unable to propertize an entire block (if the start of a block is within START
2262 and END, but the end of the block is not), propertize the start section of a
2263 block, then in a subsequent call propertize both middle and end by finding the
2264 start which was previously propertized."
2265 (let ((start-reg (markdown-get-start-fence-regexp)))
2266 (save-excursion
2267 (goto-char start)
2268 ;; start from previous unclosed block, if exists
2269 (let ((prev-begin-block (markdown-find-previous-block)))
2270 (when prev-begin-block
2271 (let* ((correct-entry
2272 (cl-find-if (lambda (entry)
2273 (eq (cdr prev-begin-block) (cl-cadar entry)))
2274 markdown-fenced-block-pairs))
2275 (enclosed-text-start (1+ (car prev-begin-block)))
2276 (start-length
2277 (save-excursion
2278 (goto-char (car prev-begin-block))
2279 (string-match
2280 (markdown-maybe-funcall-regexp
2281 (caar correct-entry))
2282 (buffer-substring
2283 (point-at-bol) (point-at-eol)))
2284 (- (match-end 1) (match-beginning 1))))
2285 (end-reg (markdown-maybe-funcall-regexp
2286 (cl-caadr correct-entry) start-length)))
2287 (markdown-propertize-end-match
2288 end-reg end correct-entry enclosed-text-start))))
2289 ;; find all new blocks within region
2290 (while (re-search-forward start-reg end t)
2291 ;; we assume the opening constructs take up (only) an entire line,
2292 ;; so we re-check the current line
2293 (let* ((cur-line (buffer-substring (point-at-bol) (point-at-eol)))
2294 ;; find entry in `markdown-fenced-block-pairs' corresponding
2295 ;; to regex which was matched
2296 (correct-entry
2297 (cl-find-if
2298 (lambda (fenced-pair)
2299 (string-match-p
2300 (markdown-maybe-funcall-regexp (caar fenced-pair))
2301 cur-line))
2302 markdown-fenced-block-pairs))
2303 (enclosed-text-start
2304 (save-excursion (1+ (point-at-eol))))
2305 (end-reg
2306 (markdown-maybe-funcall-regexp
2307 (cl-caadr correct-entry)
2308 (if (and (match-beginning 1) (match-end 1))
2309 (- (match-end 1) (match-beginning 1))
2310 0))))
2311 ;; get correct match data
2312 (save-excursion
2313 (beginning-of-line)
2314 (re-search-forward
2315 (markdown-maybe-funcall-regexp (caar correct-entry))
2316 (point-at-eol)))
2317 ;; mark starting, even if ending is outside of region
2318 (put-text-property (match-beginning 0) (match-end 0)
2319 (cl-cadar correct-entry) (match-data t))
2320 (markdown-propertize-end-match
2321 end-reg end correct-entry enclosed-text-start))))))
2323 (defun markdown-syntax-propertize-blockquotes (start end)
2324 "Match blockquotes from START to END."
2325 (save-excursion
2326 (goto-char start)
2327 (while (and (re-search-forward markdown-regex-blockquote end t)
2328 (not (markdown-code-block-at-pos (match-beginning 0))))
2329 (put-text-property (match-beginning 0) (match-end 0)
2330 'markdown-blockquote
2331 (match-data t)))))
2333 (defun markdown-syntax-propertize-hrs (start end)
2334 "Match horizontal rules from START to END."
2335 (save-excursion
2336 (goto-char start)
2337 (while (re-search-forward markdown-regex-hr end t)
2338 (unless (or (markdown-on-heading-p)
2339 (markdown-code-block-at-point-p))
2340 (put-text-property (match-beginning 0) (match-end 0)
2341 'markdown-hr
2342 (match-data t))))))
2344 (defun markdown-syntax-propertize-yaml-metadata (start end)
2345 (save-excursion
2346 (goto-char start)
2347 (cl-loop
2348 while (re-search-forward markdown-regex-declarative-metadata end t)
2349 do (when (get-text-property (match-beginning 0)
2350 'markdown-yaml-metadata-section)
2351 (put-text-property (match-beginning 1) (match-end 1)
2352 'markdown-metadata-key (match-data t))
2353 (put-text-property (match-beginning 2) (match-end 2)
2354 'markdown-metadata-markup (match-data t))
2355 (put-text-property (match-beginning 3) (match-end 3)
2356 'markdown-metadata-value (match-data t))))))
2358 (defun markdown-syntax-propertize-headings (start end)
2359 "Match headings of type SYMBOL with REGEX from START to END."
2360 (goto-char start)
2361 (while (re-search-forward markdown-regex-header end t)
2362 (unless (markdown-code-block-at-pos (match-beginning 0))
2363 (put-text-property
2364 (match-beginning 0) (match-end 0) 'markdown-heading
2365 (match-data t))
2366 (put-text-property
2367 (match-beginning 0) (match-end 0)
2368 (cond ((match-string-no-properties 2) 'markdown-heading-1-setext)
2369 ((match-string-no-properties 3) 'markdown-heading-2-setext)
2370 (t (let ((atx-level (length (markdown-trim-whitespace
2371 (match-string-no-properties 4)))))
2372 (intern (format "markdown-heading-%d-atx" atx-level)))))
2373 (match-data t)))))
2375 (defun markdown-syntax-propertize-comments (start end)
2376 "Match HTML comments from the START to END."
2377 (let* ((in-comment (markdown-in-comment-p)))
2378 (goto-char start)
2379 (cond
2380 ;; Comment start
2381 ((and (not in-comment)
2382 (re-search-forward markdown-regex-comment-start end t)
2383 (not (markdown-inline-code-at-point-p))
2384 (not (markdown-code-block-at-point-p)))
2385 (let ((open-beg (match-beginning 0)))
2386 (put-text-property open-beg (1+ open-beg)
2387 'syntax-table (string-to-syntax "<"))
2388 (markdown-syntax-propertize-comments
2389 (min (1+ (match-end 0)) end (point-max)) end)))
2390 ;; Comment end
2391 ((and in-comment
2392 (re-search-forward markdown-regex-comment-end end t))
2393 (put-text-property (1- (match-end 0)) (match-end 0)
2394 'syntax-table (string-to-syntax ">"))
2395 (markdown-syntax-propertize-comments
2396 (min (1+ (match-end 0)) end (point-max)) end))
2397 ;; Nothing found
2398 (t nil))))
2400 (defvar markdown--syntax-properties
2401 (list 'markdown-tilde-fence-begin nil
2402 'markdown-tilde-fence-end nil
2403 'markdown-fenced-code nil
2404 'markdown-yaml-metadata-begin nil
2405 'markdown-yaml-metadata-end nil
2406 'markdown-yaml-metadata-section nil
2407 'markdown-gfm-block-begin nil
2408 'markdown-gfm-block-end nil
2409 'markdown-gfm-code nil
2410 'markdown-pre nil
2411 'markdown-blockquote nil
2412 'markdown-hr nil
2413 'markdown-heading nil
2414 'markdown-heading-1-setext nil
2415 'markdown-heading-2-setext nil
2416 'markdown-heading-1-atx nil
2417 'markdown-heading-2-atx nil
2418 'markdown-heading-3-atx nil
2419 'markdown-heading-4-atx nil
2420 'markdown-heading-5-atx nil
2421 'markdown-heading-6-atx nil
2422 'markdown-metadata-key nil
2423 'markdown-metadata-value nil
2424 'markdown-metadata-markup nil)
2425 "Property list of all Markdown syntactic properties.")
2427 (defun markdown-syntax-propertize (start end)
2428 "Function used as `syntax-propertize-function'.
2429 START and END delimit region to propertize."
2430 (with-silent-modifications
2431 (save-excursion
2432 (remove-text-properties start end markdown--syntax-properties)
2433 (markdown-syntax-propertize-fenced-block-constructs start end)
2434 (markdown-syntax-propertize-yaml-metadata start end)
2435 (markdown-syntax-propertize-pre-blocks start end)
2436 (markdown-syntax-propertize-blockquotes start end)
2437 (markdown-syntax-propertize-headings start end)
2438 (markdown-syntax-propertize-hrs start end)
2439 (markdown-syntax-propertize-comments start end))))
2442 ;;; Markup Hiding
2444 (defconst markdown-markup-properties
2445 '(face markdown-markup-face invisible markdown-markup)
2446 "List of properties and values to apply to markup.")
2448 (defconst markdown-language-keyword-properties
2449 '(face markdown-language-keyword-face invisible markdown-markup)
2450 "List of properties and values to apply to code block language names.")
2452 (defconst markdown-language-info-properties
2453 '(face markdown-language-info-face invisible markdown-markup)
2454 "List of properties and values to apply to code block language info strings.")
2456 (defconst markdown-include-title-properties
2457 '(face markdown-link-title-face invisible markdown-markup)
2458 "List of properties and values to apply to included code titles.")
2460 (defconst markdown-inline-footnote-properties
2461 '(face nil display ((raise 0.2) (height 0.8)))
2462 "Properties to apply to footnote markers and inline footnotes.")
2464 (defcustom markdown-hide-markup nil
2465 "Determines whether markup in the buffer will be hidden.
2466 When set to nil, all markup is displayed in the buffer as it
2467 appears in the file. An exception is when `markdown-hide-urls'
2468 is non-nil.
2469 Set this to a non-nil value to turn this feature on by default.
2470 You can interactively toggle the value of this variable with
2471 `markdown-toggle-markup-hiding', \\[markdown-toggle-markup-hiding],
2472 or from the Markdown > Show & Hide menu.
2474 Markup hiding works by adding text properties to positions in the
2475 buffer---either the `invisible' property or the `display' property
2476 in cases where alternative glyphs are used (e.g., list bullets).
2477 This does not, however, affect printing or other output.
2478 Functions such as `htmlfontify-buffer' and `ps-print-buffer' will
2479 not honor these text properties. For printing, it would be better
2480 to first convert to HTML or PDF (e.g,. using Pandoc)."
2481 :group 'markdown
2482 :type 'boolean
2483 :safe 'booleanp
2484 :package-version '(markdown-mode . "2.3"))
2485 (make-variable-buffer-local 'markdown-hide-markup)
2487 (defun markdown-toggle-markup-hiding (&optional arg)
2488 "Toggle the display or hiding of markup.
2489 With a prefix argument ARG, enable markup hiding if ARG is positive,
2490 and disable it otherwise.
2491 See `markdown-hide-markup' for additional details."
2492 (interactive (list (or current-prefix-arg 'toggle)))
2493 (setq markdown-hide-markup
2494 (if (eq arg 'toggle)
2495 (not markdown-hide-markup)
2496 (> (prefix-numeric-value arg) 0)))
2497 (if markdown-hide-markup
2498 (progn (add-to-invisibility-spec 'markdown-markup)
2499 (message "markdown-mode markup hiding enabled"))
2500 (progn (remove-from-invisibility-spec 'markdown-markup)
2501 (message "markdown-mode markup hiding disabled")))
2502 (markdown-reload-extensions))
2505 ;;; Font Lock =================================================================
2507 (require 'font-lock)
2509 (defvar markdown-italic-face 'markdown-italic-face
2510 "Face name to use for italic text.")
2512 (defvar markdown-bold-face 'markdown-bold-face
2513 "Face name to use for bold text.")
2515 (defvar markdown-strike-through-face 'markdown-strike-through-face
2516 "Face name to use for strike-through text.")
2518 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
2519 "Face name to use as a base for header delimiters.")
2521 (defvar markdown-header-rule-face 'markdown-header-rule-face
2522 "Face name to use as a base for header rules.")
2524 (defvar markdown-header-face 'markdown-header-face
2525 "Face name to use as a base for headers.")
2527 (defvar markdown-header-face-1 'markdown-header-face-1
2528 "Face name to use for level-1 headers.")
2530 (defvar markdown-header-face-2 'markdown-header-face-2
2531 "Face name to use for level-2 headers.")
2533 (defvar markdown-header-face-3 'markdown-header-face-3
2534 "Face name to use for level-3 headers.")
2536 (defvar markdown-header-face-4 'markdown-header-face-4
2537 "Face name to use for level-4 headers.")
2539 (defvar markdown-header-face-5 'markdown-header-face-5
2540 "Face name to use for level-5 headers.")
2542 (defvar markdown-header-face-6 'markdown-header-face-6
2543 "Face name to use for level-6 headers.")
2545 (defvar markdown-inline-code-face 'markdown-inline-code-face
2546 "Face name to use for inline code.")
2548 (defvar markdown-list-face 'markdown-list-face
2549 "Face name to use for list markers.")
2551 (defvar markdown-blockquote-face 'markdown-blockquote-face
2552 "Face name to use for blockquote.")
2554 (defvar markdown-pre-face 'markdown-pre-face
2555 "Face name to use for preformatted text.")
2557 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
2558 "Face name to use for programming language identifiers.")
2560 (defvar markdown-language-info-face 'markdown-language-info-face
2561 "Face name to use for programming info strings.")
2563 (defvar markdown-link-face 'markdown-link-face
2564 "Face name to use for links.")
2566 (defvar markdown-missing-link-face 'markdown-missing-link-face
2567 "Face name to use for links where the linked file does not exist.")
2569 (defvar markdown-reference-face 'markdown-reference-face
2570 "Face name to use for reference.")
2572 (defvar markdown-footnote-marker-face 'markdown-footnote-marker-face
2573 "Face name to use for footnote markers.")
2575 (defvar markdown-url-face 'markdown-url-face
2576 "Face name to use for URLs.")
2578 (defvar markdown-link-title-face 'markdown-link-title-face
2579 "Face name to use for reference link titles.")
2581 (defvar markdown-line-break-face 'markdown-line-break-face
2582 "Face name to use for hard line breaks.")
2584 (defvar markdown-comment-face 'markdown-comment-face
2585 "Face name to use for HTML comments.")
2587 (defvar markdown-math-face 'markdown-math-face
2588 "Face name to use for LaTeX expressions.")
2590 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
2591 "Face name to use for metadata keys.")
2593 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
2594 "Face name to use for metadata values.")
2596 (defvar markdown-gfm-checkbox-face 'markdown-gfm-checkbox-face
2597 "Face name to use for GFM checkboxes.")
2599 (defvar markdown-highlight-face 'markdown-highlight-face
2600 "Face name to use for mouse highlighting.")
2602 (defvar markdown-markup-face 'markdown-markup-face
2603 "Face name to use for markup elements.")
2605 (defgroup markdown-faces nil
2606 "Faces used in Markdown Mode"
2607 :group 'markdown
2608 :group 'faces)
2610 (defface markdown-italic-face
2611 '((t (:inherit italic)))
2612 "Face for italic text."
2613 :group 'markdown-faces)
2615 (defface markdown-bold-face
2616 '((t (:inherit bold)))
2617 "Face for bold text."
2618 :group 'markdown-faces)
2620 (defface markdown-strike-through-face
2621 '((t (:strike-through t)))
2622 "Face for strike-through text."
2623 :group 'markdown-faces)
2625 (defface markdown-markup-face
2626 '((t (:inherit shadow :slant normal :weight normal)))
2627 "Face for markup elements."
2628 :group 'markdown-faces)
2630 (defface markdown-header-rule-face
2631 '((t (:inherit markdown-markup-face)))
2632 "Base face for headers rules."
2633 :group 'markdown-faces)
2635 (defface markdown-header-delimiter-face
2636 '((t (:inherit markdown-markup-face)))
2637 "Base face for headers hash delimiter."
2638 :group 'markdown-faces)
2640 (defface markdown-list-face
2641 '((t (:inherit markdown-markup-face)))
2642 "Face for list item markers."
2643 :group 'markdown-faces)
2645 (defface markdown-blockquote-face
2646 '((t (:inherit font-lock-doc-face)))
2647 "Face for blockquote sections."
2648 :group 'markdown-faces)
2650 (defface markdown-code-face
2651 '((t (:inherit fixed-pitch)))
2652 "Face for inline code, pre blocks, and fenced code blocks.
2653 This may be used, for example, to add a contrasting background to
2654 inline code fragments and code blocks."
2655 :group 'markdown-faces)
2657 (defface markdown-inline-code-face
2658 '((t (:inherit (markdown-code-face font-lock-constant-face))))
2659 "Face for inline code."
2660 :group 'markdown-faces)
2662 (defface markdown-pre-face
2663 '((t (:inherit (markdown-code-face font-lock-constant-face))))
2664 "Face for preformatted text."
2665 :group 'markdown-faces)
2667 (defface markdown-language-keyword-face
2668 '((t (:inherit font-lock-type-face)))
2669 "Face for programming language identifiers."
2670 :group 'markdown-faces)
2672 (defface markdown-language-info-face
2673 '((t (:inherit font-lock-string-face)))
2674 "Face for programming language info strings."
2675 :group 'markdown-faces)
2677 (defface markdown-link-face
2678 '((t (:inherit link)))
2679 "Face for links."
2680 :group 'markdown-faces)
2682 (defface markdown-missing-link-face
2683 '((t (:inherit font-lock-warning-face)))
2684 "Face for missing links."
2685 :group 'markdown-faces)
2687 (defface markdown-reference-face
2688 '((t (:inherit markdown-markup-face)))
2689 "Face for link references."
2690 :group 'markdown-faces)
2692 (define-obsolete-face-alias 'markdown-footnote-face
2693 'markdown-footnote-marker-face "v2.3")
2695 (defface markdown-footnote-marker-face
2696 '((t (:inherit markdown-markup-face)))
2697 "Face for footnote markers."
2698 :group 'markdown-faces)
2700 (defface markdown-footnote-text-face
2701 '((t (:inherit font-lock-comment-face)))
2702 "Face for footnote text."
2703 :group 'markdown-faces)
2705 (defface markdown-url-face
2706 '((t (:inherit font-lock-string-face)))
2707 "Face for URLs that are part of markup.
2708 For example, this applies to URLs in inline links:
2709 [link text](http://example.com/)."
2710 :group 'markdown-faces)
2712 (defface markdown-plain-url-face
2713 '((t (:inherit markdown-link-face)))
2714 "Face for URLs that are also links.
2715 For example, this applies to plain angle bracket URLs:
2716 <http://example.com/>."
2717 :group 'markdown-faces)
2719 (defface markdown-link-title-face
2720 '((t (:inherit font-lock-comment-face)))
2721 "Face for reference link titles."
2722 :group 'markdown-faces)
2724 (defface markdown-line-break-face
2725 '((t (:inherit font-lock-constant-face :underline t)))
2726 "Face for hard line breaks."
2727 :group 'markdown-faces)
2729 (defface markdown-comment-face
2730 '((t (:inherit font-lock-comment-face)))
2731 "Face for HTML comments."
2732 :group 'markdown-faces)
2734 (defface markdown-math-face
2735 '((t (:inherit font-lock-string-face)))
2736 "Face for LaTeX expressions."
2737 :group 'markdown-faces)
2739 (defface markdown-metadata-key-face
2740 '((t (:inherit font-lock-variable-name-face)))
2741 "Face for metadata keys."
2742 :group 'markdown-faces)
2744 (defface markdown-metadata-value-face
2745 '((t (:inherit font-lock-string-face)))
2746 "Face for metadata values."
2747 :group 'markdown-faces)
2749 (defface markdown-gfm-checkbox-face
2750 '((t (:inherit font-lock-builtin-face)))
2751 "Face for GFM checkboxes."
2752 :group 'markdown-faces)
2754 (defface markdown-highlight-face
2755 '((t (:inherit highlight)))
2756 "Face for mouse highlighting."
2757 :group 'markdown-faces)
2759 (defface markdown-hr-face
2760 '((t (:inherit markdown-markup-face)))
2761 "Face for horizontal rules."
2762 :group 'markdown-faces)
2764 (defcustom markdown-header-scaling nil
2765 "Whether to use variable-height faces for headers.
2766 When non-nil, `markdown-header-face' will inherit from
2767 `variable-pitch' and the scaling values in
2768 `markdown-header-scaling-values' will be applied to
2769 headers of levels one through six respectively."
2770 :type 'boolean
2771 :initialize 'custom-initialize-default
2772 :set (lambda (symbol value)
2773 (set-default symbol value)
2774 (markdown-update-header-faces value))
2775 :group 'markdown-faces
2776 :package-version '(markdown-mode . "2.2"))
2778 (defcustom markdown-header-scaling-values
2779 '(2.0 1.7 1.4 1.1 1.0 1.0)
2780 "List of scaling values for headers of level one through six.
2781 Used when `markdown-header-scaling' is non-nil."
2782 :type 'list
2783 :initialize 'custom-initialize-default
2784 :set (lambda (symbol value)
2785 (set-default symbol value)
2786 (markdown-update-header-faces markdown-header-scaling value))
2787 :group 'markdown-faces)
2789 (defun markdown-make-header-faces ()
2790 "Build the faces used for Markdown headers."
2791 (let ((inherit-faces '(font-lock-function-name-face)))
2792 (when markdown-header-scaling
2793 (setq inherit-faces (cons 'variable-pitch inherit-faces)))
2794 (defface markdown-header-face
2795 `((t (:inherit ,inherit-faces :weight bold)))
2796 "Base face for headers."
2797 :group 'markdown-faces))
2798 (dotimes (num 6)
2799 (let* ((num1 (1+ num))
2800 (face-name (intern (format "markdown-header-face-%s" num1)))
2801 (scale (if markdown-header-scaling
2802 (float (nth num markdown-header-scaling-values))
2803 1.0)))
2804 (eval
2805 `(defface ,face-name
2806 '((t (:inherit markdown-header-face :height ,scale)))
2807 (format "Face for level %s headers.
2808 You probably don't want to customize this face directly. Instead
2809 you can customize the base face `markdown-header-face' or the
2810 variable-height variable `markdown-header-scaling'." ,num1)
2811 :group 'markdown-faces)))))
2813 (markdown-make-header-faces)
2815 (defun markdown-update-header-faces (&optional scaling scaling-values)
2816 "Update header faces, depending on if header SCALING is desired.
2817 If so, use given list of SCALING-VALUES relative to the baseline
2818 size of `markdown-header-face'."
2819 (dotimes (num 6)
2820 (let* ((face-name (intern (format "markdown-header-face-%s" (1+ num))))
2821 (scale (cond ((not scaling) 1.0)
2822 (scaling-values (float (nth num scaling-values)))
2823 (t (float (nth num markdown-header-scaling-values))))))
2824 (unless (get face-name 'saved-face) ; Don't update customized faces
2825 (set-face-attribute face-name nil :height scale)))))
2827 (defun markdown-syntactic-face (state)
2828 "Return font-lock face for characters with given STATE.
2829 See `font-lock-syntactic-face-function' for details."
2830 (let ((in-comment (nth 4 state)))
2831 (cond
2832 (in-comment 'markdown-comment-face)
2833 (t nil))))
2835 (defcustom markdown-list-item-bullets
2836 '("●" "◎" "○" "◆" "◇" "►" "•")
2837 "List of bullets to use for unordered lists.
2838 It can contain any number of symbols, which will be repeated.
2839 Depending on your font, some reasonable choices are:
2840 ♥ ● ◇ ✚ ✜ ☯ ◆ ♠ ♣ ♦ ❀ ◆ ◖ ▶ ► • ★ ▸."
2841 :group 'markdown
2842 :type '(repeat (string :tag "Bullet character"))
2843 :package-version '(markdown-mode . "2.3"))
2845 (defvar markdown-mode-font-lock-keywords-basic
2846 `((markdown-match-yaml-metadata-begin . ((1 markdown-markup-face)))
2847 (markdown-match-yaml-metadata-end . ((1 markdown-markup-face)))
2848 (markdown-match-yaml-metadata-key . ((1 markdown-metadata-key-face)
2849 (2 markdown-markup-face)
2850 (3 markdown-metadata-value-face)))
2851 (markdown-match-gfm-open-code-blocks . ((1 markdown-markup-properties)
2852 (2 markdown-markup-properties nil t)
2853 (3 markdown-language-keyword-properties nil t)
2854 (4 markdown-language-info-properties nil t)
2855 (5 markdown-markup-properties nil t)))
2856 (markdown-match-gfm-close-code-blocks . ((0 markdown-markup-properties)))
2857 (markdown-fontify-gfm-code-blocks)
2858 (markdown-match-fenced-start-code-block . ((1 markdown-markup-properties)
2859 (2 markdown-markup-properties nil t)
2860 (3 markdown-language-keyword-properties nil t)
2861 (4 markdown-language-info-properties nil t)
2862 (5 markdown-markup-properties nil t)))
2863 (markdown-match-fenced-end-code-block . ((0 markdown-markup-properties)))
2864 (markdown-fontify-fenced-code-blocks)
2865 (markdown-match-pre-blocks . ((0 markdown-pre-face)))
2866 (markdown-fontify-headings)
2867 (markdown-match-declarative-metadata . ((1 markdown-metadata-key-face)
2868 (2 markdown-markup-face)
2869 (3 markdown-metadata-value-face)))
2870 (markdown-match-pandoc-metadata . ((1 markdown-markup-face)
2871 (2 markdown-markup-face)
2872 (3 markdown-metadata-value-face)))
2873 (markdown-fontify-hrs)
2874 (markdown-match-code . ((1 markdown-markup-properties prepend)
2875 (2 markdown-inline-code-face prepend)
2876 (3 markdown-markup-properties prepend)))
2877 (,markdown-regex-kbd . ((1 markdown-markup-properties)
2878 (2 markdown-inline-code-face)
2879 (3 markdown-markup-properties)))
2880 (markdown-fontify-angle-uris)
2881 (,markdown-regex-email . 'markdown-plain-url-face)
2882 (markdown-fontify-list-items)
2883 (,markdown-regex-footnote . ((0 markdown-inline-footnote-properties)
2884 (1 markdown-markup-properties) ; [^
2885 (2 markdown-footnote-marker-face) ; label
2886 (3 markdown-markup-properties))) ; ]
2887 (,markdown-regex-pandoc-inline-footnote . ((0 markdown-inline-footnote-properties)
2888 (1 markdown-markup-properties) ; ^
2889 (2 markdown-markup-properties) ; [
2890 (3 'markdown-footnote-text-face) ; text
2891 (4 markdown-markup-properties))) ; ]
2892 (markdown-match-includes . ((1 markdown-markup-properties)
2893 (2 markdown-markup-properties nil t)
2894 (3 markdown-include-title-properties nil t)
2895 (4 markdown-markup-properties nil t)
2896 (5 markdown-markup-properties)
2897 (6 'markdown-url-face)
2898 (7 markdown-markup-properties)))
2899 (markdown-fontify-inline-links)
2900 (markdown-fontify-reference-links)
2901 (,markdown-regex-reference-definition . ((1 markdown-markup-face) ; [
2902 (2 markdown-reference-face) ; label
2903 (3 markdown-markup-face) ; ]
2904 (4 markdown-markup-face) ; :
2905 (5 markdown-url-face) ; url
2906 (6 markdown-link-title-face))) ; "title" (optional)
2907 (markdown-fontify-plain-uris)
2908 ;; Math mode $..$
2909 (markdown-match-math-single . ((1 markdown-markup-face prepend)
2910 (2 markdown-math-face append)
2911 (3 markdown-markup-face prepend)))
2912 ;; Math mode $$..$$
2913 (markdown-match-math-double . ((1 markdown-markup-face prepend)
2914 (2 markdown-math-face append)
2915 (3 markdown-markup-face prepend)))
2916 ;; Math mode \[..\] and \\[..\\]
2917 (markdown-match-math-display . ((1 markdown-markup-face prepend)
2918 (3 markdown-math-face append)
2919 (4 markdown-markup-face prepend)))
2920 (markdown-match-bold . ((1 markdown-markup-properties prepend)
2921 (2 markdown-bold-face append)
2922 (3 markdown-markup-properties prepend)))
2923 (markdown-match-italic . ((1 markdown-markup-properties prepend)
2924 (2 markdown-italic-face append)
2925 (3 markdown-markup-properties prepend)))
2926 (,markdown-regex-strike-through . ((3 markdown-markup-properties)
2927 (4 markdown-strike-through-face)
2928 (5 markdown-markup-properties)))
2929 (,markdown-regex-line-break . (1 markdown-line-break-face prepend))
2930 (markdown-fontify-sub-superscripts)
2931 (markdown-match-inline-attributes . ((0 markdown-markup-properties prepend)))
2932 (markdown-match-leanpub-sections . ((0 markdown-markup-properties)))
2933 (markdown-fontify-blockquotes)
2934 (markdown-match-wiki-link . ((0 markdown-link-face prepend))))
2935 "Syntax highlighting for Markdown files.")
2937 ;; Footnotes
2938 (defvar markdown-footnote-counter 0
2939 "Counter for footnote numbers.")
2940 (make-variable-buffer-local 'markdown-footnote-counter)
2942 (defconst markdown-footnote-chars
2943 "[[:alnum:]-]"
2944 "Regular expression matching any character that is allowed in a footnote identifier.")
2946 (defconst markdown-regex-footnote-definition
2947 (concat "^ \\{0,3\\}\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:\\(?:[ \t]+\\|$\\)")
2948 "Regular expression matching a footnote definition, capturing the label.")
2951 ;;; Compatibility =============================================================
2953 (defun markdown-replace-regexp-in-string (regexp rep string)
2954 "Replace ocurrences of REGEXP with REP in STRING.
2955 This is a compatibility wrapper to provide `replace-regexp-in-string'
2956 in XEmacs 21."
2957 (if (featurep 'xemacs)
2958 (replace-in-string string regexp rep)
2959 (replace-regexp-in-string regexp rep string)))
2961 ;; `markdown-use-region-p' is a compatibility function which checks
2962 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
2963 (eval-and-compile
2964 (cond
2965 ;; Emacs 24 and newer
2966 ((fboundp 'use-region-p)
2967 (defalias 'markdown-use-region-p 'use-region-p))
2968 ;; XEmacs
2969 ((fboundp 'region-active-p)
2970 (defalias 'markdown-use-region-p 'region-active-p))))
2972 ;; Use new names for outline-mode functions in Emacs 25 and later.
2973 (eval-and-compile
2974 (defalias 'markdown-hide-sublevels
2975 (if (fboundp 'outline-hide-sublevels)
2976 'outline-hide-sublevels
2977 'hide-sublevels))
2978 (defalias 'markdown-show-all
2979 (if (fboundp 'outline-show-all)
2980 'outline-show-all
2981 'show-all))
2982 (defalias 'markdown-hide-body
2983 (if (fboundp 'outline-hide-body)
2984 'outline-hide-body
2985 'hide-body))
2986 (defalias 'markdown-show-children
2987 (if (fboundp 'outline-show-children)
2988 'outline-show-children
2989 'show-children))
2990 (defalias 'markdown-show-subtree
2991 (if (fboundp 'outline-show-subtree)
2992 'outline-show-subtree
2993 'show-subtree))
2994 (defalias 'markdown-hide-subtree
2995 (if (fboundp 'outline-hide-subtree)
2996 'outline-hide-subtree
2997 'hide-subtree)))
2999 ;; Provide directory-name-p to Emacs 24
3000 (defsubst markdown-directory-name-p (name)
3001 "Return non-nil if NAME ends with a directory separator character.
3002 Taken from `directory-name-p' from Emacs 25 and provided here for
3003 backwards compatibility."
3004 (let ((len (length name))
3005 (lastc ?.))
3006 (if (> len 0)
3007 (setq lastc (aref name (1- len))))
3008 (or (= lastc ?/)
3009 (and (memq system-type '(windows-nt ms-dos))
3010 (= lastc ?\\)))))
3012 ;; Provide a function to find files recursively in Emacs 24.
3013 (defalias 'markdown-directory-files-recursively
3014 (if (fboundp 'directory-files-recursively)
3015 'directory-files-recursively
3016 (lambda (dir regexp)
3017 "Return list of all files under DIR that have file names matching REGEXP.
3018 This function works recursively. Files are returned in \"depth first\"
3019 order, and files from each directory are sorted in alphabetical order.
3020 Each file name appears in the returned list in its absolute form.
3021 Based on `directory-files-recursively' from Emacs 25 and provided
3022 here for backwards compatibility."
3023 (let ((result nil)
3024 (files nil)
3025 ;; When DIR is "/", remote file names like "/method:" could
3026 ;; also be offered. We shall suppress them.
3027 (tramp-mode (and tramp-mode (file-remote-p (expand-file-name dir)))))
3028 (dolist (file (sort (file-name-all-completions "" dir)
3029 'string<))
3030 (unless (member file '("./" "../"))
3031 (if (markdown-directory-name-p file)
3032 (let* ((leaf (substring file 0 (1- (length file))))
3033 (full-file (expand-file-name leaf dir)))
3034 (setq result
3035 (nconc result (markdown-directory-files-recursively
3036 full-file regexp))))
3037 (when (string-match-p regexp file)
3038 (push (expand-file-name file dir) files)))))
3039 (nconc result (nreverse files))))))
3041 (defun markdown-flyspell-check-word-p ()
3042 "Return t if `flyspell' should check word just before point.
3043 Used for `flyspell-generic-check-word-predicate'."
3044 (save-excursion
3045 (goto-char (1- (point)))
3046 (not (or (markdown-code-block-at-point-p)
3047 (markdown-inline-code-at-point-p)
3048 (markdown-in-comment-p)
3049 (let ((faces (get-text-property (point) 'face)))
3050 (if (listp faces)
3051 (or (memq 'markdown-reference-face faces)
3052 (memq 'markdown-markup-face faces)
3053 (memq 'markdown-plain-url-face faces)
3054 (memq 'markdown-inline-code-face faces)
3055 (memq 'markdown-url-face faces))
3056 (memq faces '(markdown-reference-face
3057 markdown-markup-face
3058 markdown-plain-url-face
3059 markdown-inline-code-face
3060 markdown-url-face))))))))
3062 (defun markdown-font-lock-ensure ()
3063 "Provide `font-lock-ensure' in Emacs 24."
3064 (if (fboundp 'font-lock-ensure)
3065 (font-lock-ensure)
3066 (with-no-warnings
3067 ;; Suppress warning about non-interactive use of
3068 ;; `font-lock-fontify-buffer' in Emacs 25.
3069 (font-lock-fontify-buffer))))
3072 ;;; Markdown Parsing Functions ================================================
3074 (defun markdown-cur-line-blank (&optional predicate)
3075 "Return t if the current line is blank and nil otherwise.
3076 When PREDICATE is non-nil, don't modify the match data."
3077 (save-excursion
3078 (beginning-of-line)
3079 (let ((regexp "^\\s *$"))
3080 (if predicate
3081 (looking-at-p regexp)
3082 (looking-at regexp)))))
3084 (defun markdown-cur-line-blank-p ()
3085 "Same as `markdown-cur-line-blank', but does not change the match data."
3086 (markdown-cur-line-blank t))
3088 (defun markdown-prev-line-blank (&optional predicate)
3089 "Return t if the previous line is blank and nil otherwise.
3090 If we are at the first line, then consider the previous line to be blank.
3091 When PREDICATE is non-nil, don't modify the match data."
3092 (or (= (line-beginning-position) (point-min))
3093 (save-excursion
3094 (forward-line -1)
3095 (markdown-cur-line-blank predicate))))
3097 (defun markdown-prev-line-blank-p ()
3098 "Same as `markdown-prev-line-blank', but does not change the match data."
3099 (markdown-prev-line-blank t))
3101 (defun markdown-next-line-blank (&optional predicate)
3102 "Return t if the next line is blank and nil otherwise.
3103 If we are at the last line, then consider the next line to be blank.
3104 When PREDICATE is non-nil, don't modify the match data."
3105 (or (= (line-end-position) (point-max))
3106 (save-excursion
3107 (forward-line 1)
3108 (markdown-cur-line-blank predicate))))
3110 (defun markdown-next-line-blank-p ()
3111 "Same as `markdown-next-line-blank', but does not change the match data."
3112 (markdown-next-line-blank t))
3114 (defun markdown-prev-line-indent ()
3115 "Return the number of leading whitespace characters in the previous line.
3116 Return 0 if the current line is the first line in the buffer."
3117 (save-excursion
3118 (if (= (line-beginning-position) (point-min))
3120 (forward-line -1)
3121 (current-indentation))))
3123 (defun markdown-next-line-indent ()
3124 "Return the number of leading whitespace characters in the next line.
3125 Return 0 if line is the last line in the buffer."
3126 (save-excursion
3127 (if (= (line-end-position) (point-max))
3129 (forward-line 1)
3130 (current-indentation))))
3132 (defun markdown-cur-non-list-indent ()
3133 "Return beginning position of list item text (not including the list marker).
3134 Return nil if the current line is not the beginning of a list item."
3135 (save-match-data
3136 (save-excursion
3137 (beginning-of-line)
3138 (when (re-search-forward markdown-regex-list (line-end-position) t)
3139 (current-column)))))
3141 (defun markdown-prev-non-list-indent ()
3142 "Return position of the first non-list-marker on the previous line."
3143 (save-excursion
3144 (forward-line -1)
3145 (markdown-cur-non-list-indent)))
3147 (defun markdown-new-baseline ()
3148 "Determine if the current line begins a new baseline level."
3149 (save-excursion
3150 (beginning-of-line)
3151 (or (looking-at markdown-regex-header)
3152 (looking-at markdown-regex-hr)
3153 (and (null (markdown-cur-non-list-indent))
3154 (= (current-indentation) 0)
3155 (markdown-prev-line-blank)))))
3157 (defun markdown-search-backward-baseline ()
3158 "Search backward baseline point with no indentation and not a list item."
3159 (end-of-line)
3160 (let (stop)
3161 (while (not (or stop (bobp)))
3162 (re-search-backward markdown-regex-block-separator-noindent nil t)
3163 (when (match-end 2)
3164 (goto-char (match-end 2))
3165 (cond
3166 ((markdown-new-baseline)
3167 (setq stop t))
3168 ((looking-at-p markdown-regex-list)
3169 (setq stop nil))
3170 (t (setq stop t)))))))
3172 (defun markdown-update-list-levels (marker indent levels)
3173 "Update list levels given list MARKER, block INDENT, and current LEVELS.
3174 Here, MARKER is a string representing the type of list, INDENT is an integer
3175 giving the indentation, in spaces, of the current block, and LEVELS is a
3176 list of the indentation levels of parent list items. When LEVELS is nil,
3177 it means we are at baseline (not inside of a nested list)."
3178 (cond
3179 ;; New list item at baseline.
3180 ((and marker (null levels))
3181 (setq levels (list indent)))
3182 ;; List item with greater indentation (four or more spaces).
3183 ;; Increase list level.
3184 ((and marker (>= indent (+ (car levels) 4)))
3185 (setq levels (cons indent levels)))
3186 ;; List item with greater or equal indentation (less than four spaces).
3187 ;; Do not increase list level.
3188 ((and marker (>= indent (car levels)))
3189 levels)
3190 ;; Lesser indentation level.
3191 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
3192 ;; indentation could move back more than one list level). Note
3193 ;; that this block need not be the beginning of list item.
3194 ((< indent (car levels))
3195 (while (and (> (length levels) 1)
3196 (< indent (+ (cadr levels) 4)))
3197 (setq levels (cdr levels)))
3198 levels)
3199 ;; Otherwise, do nothing.
3200 (t levels)))
3202 (defun markdown-calculate-list-levels ()
3203 "Calculate list levels at point.
3204 Return a list of the form (n1 n2 n3 ...) where n1 is the
3205 indentation of the deepest nested list item in the branch of
3206 the list at the point, n2 is the indentation of the parent
3207 list item, and so on. The depth of the list item is therefore
3208 the length of the returned list. If the point is not at or
3209 immediately after a list item, return nil."
3210 (save-excursion
3211 (let ((first (point)) levels indent pre-regexp)
3212 ;; Find a baseline point with zero list indentation
3213 (markdown-search-backward-baseline)
3214 ;; Search for all list items between baseline and LOC
3215 (while (and (< (point) first)
3216 (re-search-forward markdown-regex-list first t))
3217 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
3218 (beginning-of-line)
3219 (cond
3220 ;; Make sure this is not a header or hr
3221 ((markdown-new-baseline) (setq levels nil))
3222 ;; Make sure this is not a line from a pre block
3223 ((looking-at-p pre-regexp))
3224 ;; If not, then update levels
3226 (setq indent (current-indentation))
3227 (setq levels (markdown-update-list-levels (match-string 2)
3228 indent levels))))
3229 (end-of-line))
3230 levels)))
3232 (defun markdown-prev-list-item (level)
3233 "Search backward from point for a list item with indentation LEVEL.
3234 Set point to the beginning of the item, and return point, or nil
3235 upon failure."
3236 (let (bounds indent prev)
3237 (setq prev (point))
3238 (forward-line -1)
3239 (setq indent (current-indentation))
3240 (while
3241 (cond
3242 ;; List item
3243 ((and (looking-at-p markdown-regex-list)
3244 (setq bounds (markdown-cur-list-item-bounds)))
3245 (cond
3246 ;; Stop and return point at item of equal indentation
3247 ((= (nth 3 bounds) level)
3248 (setq prev (point))
3249 nil)
3250 ;; Stop and return nil at item with lesser indentation
3251 ((< (nth 3 bounds) level)
3252 (setq prev nil)
3253 nil)
3254 ;; Stop at beginning of buffer
3255 ((bobp) (setq prev nil))
3256 ;; Continue at item with greater indentation
3257 ((> (nth 3 bounds) level) t)))
3258 ;; Stop at beginning of buffer
3259 ((bobp) (setq prev nil))
3260 ;; Continue if current line is blank
3261 ((markdown-cur-line-blank-p) t)
3262 ;; Continue while indentation is the same or greater
3263 ((>= indent level) t)
3264 ;; Stop if current indentation is less than list item
3265 ;; and the next is blank
3266 ((and (< indent level)
3267 (markdown-next-line-blank-p))
3268 (setq prev nil))
3269 ;; Stop at a header
3270 ((looking-at-p markdown-regex-header) (setq prev nil))
3271 ;; Stop at a horizontal rule
3272 ((looking-at-p markdown-regex-hr) (setq prev nil))
3273 ;; Otherwise, continue.
3274 (t t))
3275 (forward-line -1)
3276 (setq indent (current-indentation)))
3277 prev))
3279 (defun markdown-next-list-item (level)
3280 "Search forward from point for the next list item with indentation LEVEL.
3281 Set point to the beginning of the item, and return point, or nil
3282 upon failure."
3283 (let (bounds indent next)
3284 (setq next (point))
3285 (if (looking-at markdown-regex-header-setext)
3286 (goto-char (match-end 0)))
3287 (forward-line)
3288 (setq indent (current-indentation))
3289 (while
3290 (cond
3291 ;; Stop at end of the buffer.
3292 ((eobp) nil)
3293 ;; Continue if the current line is blank
3294 ((markdown-cur-line-blank-p) t)
3295 ;; List item
3296 ((and (looking-at-p markdown-regex-list)
3297 (setq bounds (markdown-cur-list-item-bounds)))
3298 (cond
3299 ;; Continue at item with greater indentation
3300 ((> (nth 3 bounds) level) t)
3301 ;; Stop and return point at item of equal indentation
3302 ((= (nth 3 bounds) level)
3303 (setq next (point))
3304 nil)
3305 ;; Stop and return nil at item with lesser indentation
3306 ((< (nth 3 bounds) level)
3307 (setq next nil)
3308 nil)))
3309 ;; Continue while indentation is the same or greater
3310 ((>= indent level) t)
3311 ;; Stop if current indentation is less than list item
3312 ;; and the previous line was blank.
3313 ((and (< indent level)
3314 (markdown-prev-line-blank-p))
3315 (setq next nil))
3316 ;; Stop at a header
3317 ((looking-at-p markdown-regex-header) (setq next nil))
3318 ;; Stop at a horizontal rule
3319 ((looking-at-p markdown-regex-hr) (setq next nil))
3320 ;; Otherwise, continue.
3321 (t t))
3322 (forward-line)
3323 (setq indent (current-indentation)))
3324 next))
3326 (defun markdown-cur-list-item-end (level)
3327 "Move to the end of the current list item with nonlist indentation LEVEL.
3328 If the point is not in a list item, do nothing."
3329 (let (indent)
3330 (forward-line)
3331 (setq indent (current-indentation))
3332 (while
3333 (cond
3334 ;; Stop at end of the buffer.
3335 ((eobp) nil)
3336 ;; Continue if the current line is blank
3337 ((markdown-cur-line-blank-p) t)
3338 ;; Continue while indentation is the same or greater
3339 ((>= indent level) t)
3340 ;; Stop if current indentation is less than list item
3341 ;; and the previous line was blank.
3342 ((and (< indent level)
3343 (markdown-prev-line-blank-p))
3344 nil)
3345 ;; Stop at a new list item of the same or lesser indentation
3346 ((looking-at-p markdown-regex-list) nil)
3347 ;; Stop at a header
3348 ((looking-at-p markdown-regex-header) nil)
3349 ;; Stop at a horizontal rule
3350 ((looking-at-p markdown-regex-hr) nil)
3351 ;; Otherwise, continue.
3352 (t t))
3353 (forward-line)
3354 (setq indent (current-indentation)))
3355 ;; Don't skip over whitespace for empty list items (marker and
3356 ;; whitespace only), just move to end of whitespace.
3357 (if (looking-back (concat markdown-regex-list "\\s-*") nil)
3358 (goto-char (match-end 3))
3359 (skip-syntax-backward "-"))))
3361 (defun markdown-cur-list-item-bounds ()
3362 "Return bounds and indentation of the current list item.
3363 Return a list of the following form:
3365 (begin end indent nonlist-indent marker checkbox)
3367 The named components are:
3369 - begin: Position of beginning of list item, including leading indentation.
3370 - end: Position of the end of the list item, including list item text.
3371 - indent: Number of characters of indentation before list marker (an integer).
3372 - nonlist-indent: Number characters of indentation, list
3373 marker, and whitespace following list marker (an integer).
3374 - marker: String containing the list marker and following whitespace
3375 (e.g., \"- \" or \"* \").
3376 - checkbox: String containing the GFM checkbox portion, if any,
3377 including any trailing whitespace before the text
3378 begins (e.g., \"[x] \").
3380 As an example, for the following unordered list item
3382 - item
3384 the returned list would be
3386 (1 14 3 5 \"- \" nil)
3388 If the point is not inside a list item, return nil.
3389 Leave match data intact for `markdown-regex-list'."
3390 (save-excursion
3391 (let ((cur (point)))
3392 (end-of-line)
3393 (when (re-search-backward markdown-regex-list nil t)
3394 (let* ((begin (match-beginning 0))
3395 (indent (length (match-string-no-properties 1)))
3396 (nonlist-indent (length (match-string 0)))
3397 (marker (concat (match-string-no-properties 2)
3398 (match-string-no-properties 3)))
3399 (checkbox (progn (goto-char (match-end 0))
3400 (when (looking-at "\\[[xX ]\\]\\s-*")
3401 (match-string-no-properties 0))))
3402 (end (save-match-data
3403 (markdown-cur-list-item-end nonlist-indent)
3404 (point))))
3405 (when (and (>= cur begin) (<= cur end) nonlist-indent)
3406 (list begin end indent nonlist-indent marker checkbox)))))))
3408 (defun markdown-list-item-at-point-p ()
3409 "Return t if there is a list item at the point and nil otherwise."
3410 (save-match-data (markdown-cur-list-item-bounds)))
3412 (defun markdown-prev-list-item-bounds ()
3413 "Return bounds of previous item in the same list of any level.
3414 The return value has the same form as that of
3415 `markdown-cur-list-item-bounds'."
3416 (save-excursion
3417 (let ((cur-bounds (markdown-cur-list-item-bounds))
3418 (beginning-of-list (save-excursion (markdown-beginning-of-list)))
3419 stop)
3420 (when cur-bounds
3421 (goto-char (nth 0 cur-bounds))
3422 (while (and (not stop) (not (bobp))
3423 (re-search-backward markdown-regex-list
3424 beginning-of-list t))
3425 (unless (or (looking-at markdown-regex-hr)
3426 (markdown-code-block-at-point-p))
3427 (setq stop (point))))
3428 (markdown-cur-list-item-bounds)))))
3430 (defun markdown-next-list-item-bounds ()
3431 "Return bounds of next item in the same list of any level.
3432 The return value has the same form as that of
3433 `markdown-cur-list-item-bounds'."
3434 (save-excursion
3435 (let ((cur-bounds (markdown-cur-list-item-bounds))
3436 (end-of-list (save-excursion (markdown-end-of-list)))
3437 stop)
3438 (when cur-bounds
3439 (goto-char (nth 0 cur-bounds))
3440 (end-of-line)
3441 (while (and (not stop) (not (eobp))
3442 (re-search-forward markdown-regex-list
3443 end-of-list t))
3444 (unless (or (looking-at markdown-regex-hr)
3445 (markdown-code-block-at-point-p))
3446 (setq stop (point))))
3447 (when stop
3448 (markdown-cur-list-item-bounds))))))
3450 (defun markdown-beginning-of-list ()
3451 "Move point to beginning of list at point, if any."
3452 (interactive)
3453 (let ((orig-point (point))
3454 (list-begin (save-excursion
3455 (markdown-search-backward-baseline)
3456 ;; Stop at next list item, regardless of the indentation.
3457 (markdown-next-list-item (point-max))
3458 (when (looking-at markdown-regex-list)
3459 (point)))))
3460 (when (and list-begin (<= list-begin orig-point))
3461 (goto-char list-begin))))
3463 (defun markdown-end-of-list ()
3464 "Move point to end of list at point, if any."
3465 (interactive)
3466 (let ((start (point))
3467 (end (save-excursion
3468 (when (markdown-beginning-of-list)
3469 ;; Items can't have nonlist-indent <= 1, so this
3470 ;; moves past all list items.
3471 (markdown-next-list-item 1)
3472 (skip-syntax-backward "-")
3473 (unless (eobp) (forward-char 1))
3474 (point)))))
3475 (when (and end (>= end start))
3476 (goto-char end))))
3478 (defun markdown-up-list ()
3479 "Move point to beginning of parent list item."
3480 (interactive)
3481 (let ((cur-bounds (markdown-cur-list-item-bounds)))
3482 (when cur-bounds
3483 (markdown-prev-list-item (1- (nth 3 cur-bounds)))
3484 (let ((up-bounds (markdown-cur-list-item-bounds)))
3485 (when (and up-bounds (< (nth 3 up-bounds) (nth 3 cur-bounds)))
3486 (point))))))
3488 (defun markdown-bounds-of-thing-at-point (thing)
3489 "Call `bounds-of-thing-at-point' for THING with slight modifications.
3490 Does not include trailing newlines when THING is 'line. Handles the
3491 end of buffer case by setting both endpoints equal to the value of
3492 `point-max', since an empty region will trigger empty markup insertion.
3493 Return bounds of form (beg . end) if THING is found, or nil otherwise."
3494 (let* ((bounds (bounds-of-thing-at-point thing))
3495 (a (car bounds))
3496 (b (cdr bounds)))
3497 (when bounds
3498 (when (eq thing 'line)
3499 (cond ((and (eobp) (markdown-cur-line-blank-p))
3500 (setq a b))
3501 ((char-equal (char-before b) ?\^J)
3502 (setq b (1- b)))))
3503 (cons a b))))
3505 (defun markdown-reference-definition (reference)
3506 "Find out whether Markdown REFERENCE is defined.
3507 REFERENCE should not include the square brackets.
3508 When REFERENCE is defined, return a list of the form (text start end)
3509 containing the definition text itself followed by the start and end
3510 locations of the text. Otherwise, return nil.
3511 Leave match data for `markdown-regex-reference-definition'
3512 intact additional processing."
3513 (let ((reference (downcase reference)))
3514 (save-excursion
3515 (goto-char (point-min))
3516 (catch 'found
3517 (while (re-search-forward markdown-regex-reference-definition nil t)
3518 (when (string= reference (downcase (match-string-no-properties 2)))
3519 (throw 'found
3520 (list (match-string-no-properties 5)
3521 (match-beginning 5) (match-end 5)))))))))
3523 (defun markdown-get-defined-references ()
3524 "Return a list of all defined reference labels (not including square brackets)."
3525 (save-excursion
3526 (goto-char (point-min))
3527 (let (refs)
3528 (while (re-search-forward markdown-regex-reference-definition nil t)
3529 (let ((target (match-string-no-properties 2)))
3530 (cl-pushnew target refs :test #'equal)))
3531 (reverse refs))))
3533 (defun markdown-get-used-uris ()
3534 "Return a list of all used URIs in the buffer."
3535 (save-excursion
3536 (goto-char (point-min))
3537 (let (uris)
3538 (while (re-search-forward
3539 (concat "\\(?:" markdown-regex-link-inline
3540 "\\|" markdown-regex-angle-uri
3541 "\\|" markdown-regex-uri
3542 "\\|" markdown-regex-email
3543 "\\)")
3544 nil t)
3545 (unless (or (markdown-inline-code-at-point-p)
3546 (markdown-code-block-at-point-p))
3547 (cl-pushnew (or (match-string-no-properties 6)
3548 (match-string-no-properties 10)
3549 (match-string-no-properties 12)
3550 (match-string-no-properties 13))
3551 uris :test #'equal)))
3552 (reverse uris))))
3554 (defun markdown-inline-code-at-pos (pos)
3555 "Return non-nil if there is an inline code fragment at POS.
3556 Return nil otherwise. Set match data according to
3557 `markdown-match-code' upon success.
3558 This function searches the block for a code fragment that
3559 contains the point using `markdown-match-code'. We do this
3560 because `thing-at-point-looking-at' does not work reliably with
3561 `markdown-regex-code'.
3563 The match data is set as follows:
3564 Group 1 matches the opening backquotes.
3565 Group 2 matches the code fragment itself, without backquotes.
3566 Group 3 matches the closing backquotes."
3567 (save-excursion
3568 (goto-char pos)
3569 (let ((old-point (point))
3570 (end-of-block (progn (markdown-end-of-text-block) (point)))
3571 found)
3572 (markdown-beginning-of-text-block)
3573 (while (and (markdown-match-code end-of-block)
3574 (setq found t)
3575 (< (match-end 0) old-point)))
3576 (and found ; matched something
3577 (<= (match-beginning 0) old-point) ; match contains old-point
3578 (>= (match-end 0) old-point)))))
3580 (defun markdown-inline-code-at-pos-p (pos)
3581 "Return non-nil if there is an inline code fragment at POS.
3582 Like `markdown-inline-code-at-pos`, but preserves match data."
3583 (save-match-data (markdown-inline-code-at-pos pos)))
3585 (defun markdown-inline-code-at-point ()
3586 "Return non-nil if the point is at an inline code fragment.
3587 See `markdown-inline-code-at-pos' for details."
3588 (markdown-inline-code-at-pos (point)))
3590 (defun markdown-inline-code-at-point-p ()
3591 "Return non-nil if there is inline code at the point.
3592 This is a predicate function counterpart to
3593 `markdown-inline-code-at-point' which does not modify the match
3594 data. See `markdown-code-block-at-point-p' for code blocks."
3595 (save-match-data (markdown-inline-code-at-pos (point))))
3597 (make-obsolete 'markdown-code-at-point-p 'markdown-inline-code-at-point-p "v2.2")
3599 (defun markdown-code-block-at-pos (pos)
3600 "Return match data list if there is a code block at POS.
3601 Uses text properties at the beginning of the line position.
3602 This includes pre blocks, tilde-fenced code blocks, and GFM
3603 quoted code blocks. Return nil otherwise."
3604 (setq pos (save-excursion (goto-char pos) (point-at-bol)))
3605 (or (get-text-property pos 'markdown-pre)
3606 (markdown-get-enclosing-fenced-block-construct pos)
3607 ;; polymode removes text properties set by markdown-mode, so
3608 ;; check if `poly-markdown-mode' is active and whether the
3609 ;; `chunkmode' property is non-nil at POS.
3610 (and (bound-and-true-p poly-markdown-mode)
3611 (get-text-property pos 'chunkmode))))
3613 ;; Function was renamed to emphasize that it does not modify match-data.
3614 (defalias 'markdown-code-block-at-point 'markdown-code-block-at-point-p)
3616 (defun markdown-code-block-at-point-p ()
3617 "Return non-nil if there is a code block at the point.
3618 This includes pre blocks, tilde-fenced code blocks, and GFM
3619 quoted code blocks. This function does not modify the match
3620 data. See `markdown-inline-code-at-point-p' for inline code."
3621 (save-match-data (markdown-code-block-at-pos (point))))
3623 (defun markdown-heading-at-point ()
3624 "Return non-nil if there is a heading at the point.
3625 Set match data for `markdown-regex-header'."
3626 (let ((match-data (get-text-property (point) 'markdown-heading)))
3627 (when match-data
3628 (set-match-data match-data)
3629 t)))
3631 (defun markdown-pipe-at-bol-p ()
3632 "Return non-nil if the line begins with a pipe symbol.
3633 This may be useful for tables and Pandoc's line_blocks extension."
3634 (char-equal (char-after (point-at-bol)) ?|))
3637 ;;; Markdown Font Lock Matching Functions =====================================
3639 (defun markdown-range-property-any (begin end prop prop-values)
3640 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
3641 Also returns t if PROP is a list containing one of the PROP-VALUES.
3642 Return nil otherwise."
3643 (let (props)
3644 (catch 'found
3645 (dolist (loc (number-sequence begin end))
3646 (when (setq props (get-text-property loc prop))
3647 (cond ((listp props)
3648 ;; props is a list, check for membership
3649 (dolist (val prop-values)
3650 (when (memq val props) (throw 'found loc))))
3652 ;; props is a scalar, check for equality
3653 (dolist (val prop-values)
3654 (when (eq val props) (throw 'found loc))))))))))
3656 (defun markdown-range-properties-exist (begin end props)
3657 (cl-loop
3658 for loc in (number-sequence begin end)
3659 with result = nil
3660 while (not
3661 (setq result
3662 (cl-some (lambda (prop) (get-text-property loc prop)) props)))
3663 finally return result))
3665 (defun markdown-match-inline-generic (regex last &optional faceless)
3666 "Match inline REGEX from the point to LAST.
3667 When FACELESS is non-nil, do not return matches where faces have been applied."
3668 (when (re-search-forward regex last t)
3669 (let ((bounds (markdown-code-block-at-pos (match-beginning 1)))
3670 (face (and faceless (text-property-not-all
3671 (match-beginning 0) (match-end 0) 'face nil))))
3672 (cond
3673 ;; In code block: move past it and recursively search again
3674 (bounds
3675 (when (< (goto-char (cl-second bounds)) last)
3676 (markdown-match-inline-generic regex last faceless)))
3677 ;; When faces are found in the match range, skip over the match and
3678 ;; recursively search again.
3679 (face
3680 (when (< (goto-char (match-end 0)) last)
3681 (markdown-match-inline-generic regex last faceless)))
3682 ;; Keep match data and return t when in bounds.
3684 (<= (match-end 0) last))))))
3686 (defun markdown-match-code (last)
3687 "Match inline code fragments from point to LAST."
3688 (unless (bobp)
3689 (backward-char 1))
3690 (when (markdown-match-inline-generic markdown-regex-code last)
3691 (let ((begin (match-beginning 1))
3692 (end (match-end 1))
3693 (open-begin (match-beginning 2))
3694 (open-end (match-end 2))
3695 (code-begin (match-beginning 3))
3696 (code-end (match-end 3))
3697 (close-begin (match-beginning 4))
3698 (close-end (match-end 4)))
3699 (if (or (markdown-in-comment-p begin)
3700 (markdown-in-comment-p end)
3701 (markdown-code-block-at-pos begin))
3702 (progn (goto-char (min (1+ begin) last))
3703 (when (< (point) last)
3704 (markdown-match-code last)))
3705 (set-match-data (list begin end
3706 open-begin open-end
3707 code-begin code-end
3708 close-begin close-end))
3709 t))))
3711 (defun markdown-match-bold (last)
3712 "Match inline bold from the point to LAST."
3713 (when (markdown-match-inline-generic markdown-regex-bold last)
3714 (let ((begin (match-beginning 2))
3715 (end (match-end 2)))
3716 (if (or (markdown-inline-code-at-pos-p begin)
3717 (markdown-inline-code-at-pos-p end)
3718 (markdown-in-comment-p)
3719 (markdown-range-property-any
3720 begin begin 'face '(markdown-url-face
3721 markdown-plain-url-face))
3722 (markdown-range-property-any
3723 begin end 'face '(markdown-inline-code-face
3724 markdown-math-face)))
3725 (progn (goto-char (min (1+ begin) last))
3726 (when (< (point) last)
3727 (markdown-match-italic last)))
3728 (set-match-data (list (match-beginning 2) (match-end 2)
3729 (match-beginning 3) (match-end 3)
3730 (match-beginning 4) (match-end 4)
3731 (match-beginning 5) (match-end 5)))
3732 t))))
3734 (defun markdown-match-italic (last)
3735 "Match inline italics from the point to LAST."
3736 (let ((regex (if (eq major-mode 'gfm-mode)
3737 markdown-regex-gfm-italic markdown-regex-italic)))
3738 (when (markdown-match-inline-generic regex last)
3739 (let ((begin (match-beginning 1))
3740 (end (match-end 1)))
3741 (if (or (markdown-inline-code-at-pos-p begin)
3742 (markdown-inline-code-at-pos-p end)
3743 (markdown-in-comment-p)
3744 (markdown-range-property-any
3745 begin begin 'face '(markdown-url-face
3746 markdown-plain-url-face))
3747 (markdown-range-property-any
3748 begin end 'face '(markdown-inline-code-face
3749 markdown-bold-face
3750 markdown-list-face
3751 markdown-math-face)))
3752 (progn (goto-char (min (1+ begin) last))
3753 (when (< (point) last)
3754 (markdown-match-italic last)))
3755 (set-match-data (list (match-beginning 1) (match-end 1)
3756 (match-beginning 2) (match-end 2)
3757 (match-beginning 3) (match-end 3)
3758 (match-beginning 4) (match-end 4)))
3759 t)))))
3761 (defun markdown-match-math-generic (regex last)
3762 "Match REGEX from point to LAST.
3763 REGEX is either `markdown-regex-math-inline-single' for matching
3764 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
3765 (when (and markdown-enable-math (markdown-match-inline-generic regex last))
3766 (let ((begin (match-beginning 1)) (end (match-end 1)))
3767 (prog1
3768 (if (or (markdown-range-property-any
3769 begin end 'face (list markdown-inline-code-face
3770 markdown-bold-face))
3771 (markdown-range-properties-exist
3772 begin end
3773 (markdown-get-fenced-block-middle-properties)))
3774 (markdown-match-math-generic regex last)
3776 (goto-char (1+ (match-end 0)))))))
3778 (defun markdown-match-list-items (last)
3779 "Match list items from point to LAST."
3780 (when (markdown-match-inline-generic markdown-regex-list last)
3781 (let ((begin (match-beginning 2))
3782 (end (match-end 2)))
3783 (if (or (markdown-range-property-any
3784 begin end 'face (list markdown-inline-code-face
3785 markdown-bold-face
3786 markdown-math-face))
3787 (markdown-range-properties-exist begin end '(markdown-hr))
3788 (markdown-in-comment-p))
3789 (progn (goto-char (min (1+ (match-end 0)) last))
3790 (markdown-match-list-items last))
3791 (set-match-data (list (match-beginning 0) (match-end 0)
3792 (match-beginning 1) (match-end 1)
3793 (match-beginning 2) (match-end 2)))
3794 (goto-char (1+ (match-end 0)))))))
3796 (defun markdown-match-math-single (last)
3797 "Match single quoted $..$ math from point to LAST."
3798 (markdown-match-math-generic markdown-regex-math-inline-single last))
3800 (defun markdown-match-math-double (last)
3801 "Match double quoted $$..$$ math from point to LAST."
3802 (markdown-match-math-generic markdown-regex-math-inline-double last))
3804 (defun markdown-match-math-display (last)
3805 "Match bracketed display math \[..\] and \\[..\\] from point to LAST."
3806 (markdown-match-math-generic markdown-regex-math-display last))
3808 (defun markdown-match-propertized-text (property last)
3809 "Match text with PROPERTY from point to LAST.
3810 Restore match data previously stored in PROPERTY."
3811 (let ((saved (get-text-property (point) property))
3812 pos)
3813 (unless saved
3814 (setq pos (next-single-char-property-change (point) property nil last))
3815 (setq saved (get-text-property pos property)))
3816 (when saved
3817 (set-match-data saved)
3818 ;; Step at least one character beyond point. Otherwise
3819 ;; `font-lock-fontify-keywords-region' infloops.
3820 (goto-char (min (1+ (max (match-end 0) (point)))
3821 (point-max)))
3822 saved)))
3824 (defun markdown-match-pre-blocks (last)
3825 "Match preformatted blocks from point to LAST.
3826 Use data stored in 'markdown-pre text property during syntax
3827 analysis."
3828 (markdown-match-propertized-text 'markdown-pre last))
3830 (defun markdown-match-gfm-code-blocks (last)
3831 "Match GFM quoted code blocks from point to LAST.
3832 Use data stored in 'markdown-gfm-code text property during syntax
3833 analysis."
3834 (markdown-match-propertized-text 'markdown-gfm-code last))
3836 (defun markdown-match-gfm-open-code-blocks (last)
3837 (markdown-match-propertized-text 'markdown-gfm-block-begin last))
3839 (defun markdown-match-gfm-close-code-blocks (last)
3840 (markdown-match-propertized-text 'markdown-gfm-block-end last))
3842 (defun markdown-match-fenced-code-blocks (last)
3843 "Match fenced code blocks from the point to LAST."
3844 (markdown-match-propertized-text 'markdown-fenced-code last))
3846 (defun markdown-match-fenced-start-code-block (last)
3847 (markdown-match-propertized-text 'markdown-tilde-fence-begin last))
3849 (defun markdown-match-fenced-end-code-block (last)
3850 (markdown-match-propertized-text 'markdown-tilde-fence-end last))
3852 (defun markdown-match-blockquotes (last)
3853 "Match blockquotes from point to LAST.
3854 Use data stored in 'markdown-blockquote text property during syntax
3855 analysis."
3856 (markdown-match-propertized-text 'markdown-blockquote last))
3858 (defun markdown-match-hr (last)
3859 "Match horizontal rules comments from the point to LAST."
3860 (markdown-match-propertized-text 'markdown-hr last))
3862 (defun markdown-match-comments (last)
3863 "Match HTML comments from the point to LAST."
3864 (when (and (skip-syntax-forward "^<" last))
3865 (let ((beg (point)))
3866 (when (and (skip-syntax-forward "^>" last) (< (point) last))
3867 (forward-char)
3868 (set-match-data (list beg (point)))
3869 t))))
3871 (defun markdown-match-generic-links (last ref)
3872 "Match inline links from point to LAST.
3873 When REF is non-nil, match reference links instead of standard
3874 links with URLs."
3875 ;; Search for the next potential link (not in a code block).
3876 (while (and (progn
3877 ;; Clear match data to test for a match after functions returns.
3878 (set-match-data nil)
3879 (re-search-forward "\\(!\\)?\\(\\[\\)" last 'limit))
3880 ;; Keep searching if this is in a code block, inline
3881 ;; code, or a comment, or if it is include syntax.
3882 (or (markdown-code-block-at-point-p)
3883 (markdown-inline-code-at-pos-p (match-beginning 0))
3884 (markdown-inline-code-at-pos-p (match-end 0))
3885 (markdown-in-comment-p)
3886 (and (char-equal (char-after (point-at-bol)) ?<)
3887 (char-equal (char-after (1+ (point-at-bol))) ?<)))
3888 (< (point) last)))
3889 ;; Match opening exclamation point (optional) and left bracket.
3890 (when (match-beginning 2)
3891 (let* ((bang (match-beginning 1))
3892 (first-begin (match-beginning 2))
3893 ;; Find end of block to prevent matching across blocks.
3894 (end-of-block (save-excursion
3895 (progn
3896 (goto-char (match-beginning 2))
3897 (markdown-end-of-text-block)
3898 (point))))
3899 ;; Move over balanced expressions to closing right bracket.
3900 ;; Catch unbalanced expression errors and return nil.
3901 (first-end (condition-case nil
3902 (and (goto-char first-begin)
3903 (scan-sexps (point) 1))
3904 (error nil)))
3905 ;; Continue with point at CONT-POINT upon failure.
3906 (cont-point (min (1+ first-begin) last))
3907 second-begin second-end url-begin url-end
3908 title-begin title-end)
3909 ;; When bracket found, in range, and followed by a left paren/bracket...
3910 (when (and first-end (< first-end end-of-block) (goto-char first-end)
3911 (char-equal (char-after (point)) (if ref ?\[ ?\()))
3912 ;; Scan across balanced expressions for closing parenthesis/bracket.
3913 (setq second-begin (point)
3914 second-end (condition-case nil
3915 (scan-sexps (point) 1)
3916 (error nil)))
3917 ;; Check that closing parenthesis/bracket is in range.
3918 (if (and second-end (<= second-end end-of-block) (<= second-end last))
3919 (progn
3920 ;; Search for (optional) title inside closing parenthesis
3921 (when (and (not ref) (search-forward "\"" second-end t))
3922 (setq title-begin (1- (point))
3923 title-end (and (goto-char second-end)
3924 (search-backward "\"" (1+ title-begin) t))
3925 title-end (and title-end (1+ title-end))))
3926 ;; Store URL/reference range
3927 (setq url-begin (1+ second-begin)
3928 url-end (1- (or title-begin second-end)))
3929 ;; Set match data, move point beyond link, and return
3930 (set-match-data
3931 (list (or bang first-begin) second-end ; 0 - all
3932 bang (and bang (1+ bang)) ; 1 - bang
3933 first-begin (1+ first-begin) ; 2 - markup
3934 (1+ first-begin) (1- first-end) ; 3 - link text
3935 (1- first-end) first-end ; 4 - markup
3936 second-begin (1+ second-begin) ; 5 - markup
3937 url-begin url-end ; 6 - url/reference
3938 title-begin title-end ; 7 - title
3939 (1- second-end) second-end)) ; 8 - markup
3940 ;; Nullify cont-point and leave point at end and
3941 (setq cont-point nil)
3942 (goto-char second-end))
3943 ;; If no closing parenthesis in range, update continuation point
3944 (setq cont-point (min end-of-block second-begin))))
3945 (cond
3946 ;; On failure, continue searching at cont-point
3947 ((and cont-point (< cont-point last))
3948 (goto-char cont-point)
3949 (markdown-match-generic-links last ref))
3950 ;; No more text, return nil
3951 ((and cont-point (= cont-point last))
3952 nil)
3953 ;; Return t if a match occurred
3954 (t t)))))
3956 (defun markdown-match-inline-links (last)
3957 "Match standard inline links from point to LAST."
3958 (markdown-match-generic-links last nil))
3960 (defun markdown-match-reference-links (last)
3961 "Match inline reference links from point to LAST."
3962 (markdown-match-generic-links last t))
3964 (defun markdown-match-angle-uris (last)
3965 "Match angle bracket URIs from point to LAST."
3966 (when (markdown-match-inline-generic markdown-regex-angle-uri last)
3967 (goto-char (1+ (match-end 0)))))
3969 (defun markdown-match-plain-uris (last)
3970 "Match plain URIs from point to LAST."
3971 (when (markdown-match-inline-generic markdown-regex-uri last t)
3972 (goto-char (1+ (match-end 0)))))
3974 (defvar markdown-conditional-search-function #'re-search-forward
3975 "Conditional search function used in `markdown-search-until-condition'.
3976 Made into a variable to allow for dynamic let-binding.")
3978 (defun markdown-search-until-condition (condition &rest args)
3979 (let (ret)
3980 (while (and (not ret) (apply markdown-conditional-search-function args))
3981 (setq ret (funcall condition)))
3982 ret))
3984 (defun markdown-match-generic-metadata
3985 (regexp last &optional block-begin-re block-end-re)
3986 "Match metadata declarations specified by REGEXP from point to LAST.
3987 These declarations must appear inside a metadata block specified
3988 by BLOCK-BEGIN-RE and BLOCK-END-RE. BLOCK-BEGIN-RE is a regular
3989 expression denoting the beginning of a metadata block. If it is
3990 nil, we assume metadata can only appear at the beginning of the
3991 buffer. Similarly, BLOCK-END-RE is a regular expression denoting
3992 the end of a metadata block. If it is nil, assume blocks end with
3993 a blank line or the end of the buffer. There may be at most one such
3994 block in a file. Subsequent blocks will be ignored."
3995 (let* ((first (point))
3996 (begin-re (or block-begin-re "\\`"))
3997 (end-re (or block-end-re "\n[ \t]*\n\\|\n\\'\\|\\'"))
3999 ;; (prev-block-begin (when (re-search-backward begin-re (point-min) t) (match-end 0)))
4000 ;; (next-block-begin (when (re-search-forward begin-re last t) (match-end 0)))
4001 ;; (block-begin (or prev-block-begin next-block-begin))
4003 (block-begin (when (or (re-search-backward begin-re (point-min) t)
4004 (re-search-forward begin-re last t))
4005 (match-end 0)))
4007 (block-end (and block-begin (goto-char block-begin)
4008 (re-search-forward end-re nil t))))
4009 (cond
4010 ;; Don't match declarations if there is no metadata block or if
4011 ;; the point is beyond the block. Move point to point-max to
4012 ;; prevent additional searches and return return nil since nothing
4013 ;; was found.
4014 ((or (null block-begin) (and block-end (> first block-end)))
4015 (goto-char (point-max))
4016 nil)
4017 ;; No declarations to match if a block was found but not in
4018 ;; range. Move point to LAST, to resume there, and return nil.
4019 ((> block-begin last)
4020 (goto-char last)
4021 nil)
4022 ;; If a block was found that begins before LAST and ends after
4023 ;; point, search for declarations inside it.
4025 ;; If the starting is before the beginning of the block, start
4026 ;; there. Otherwise, move back to FIRST.
4027 (goto-char (if (< first block-begin) block-begin first))
4028 (if (re-search-forward regexp (min last block-end) t)
4029 ;; If a metadata declaration is found, set match-data and return t.
4030 (let ((key-beginning (match-beginning 1))
4031 (key-end (match-end 1))
4032 (markup-begin (match-beginning 2))
4033 (markup-end (match-end 2))
4034 (value-beginning (match-beginning 3)))
4035 (set-match-data (list key-beginning (point) ; complete metadata
4036 key-beginning key-end ; key
4037 markup-begin markup-end ; markup
4038 value-beginning (point))) ; value
4040 ;; Otherwise, move the point to last and return nil
4041 (goto-char last)
4042 nil)))))
4044 (defun markdown-match-declarative-metadata (last)
4045 "Match declarative metadata from the point to LAST."
4046 (markdown-match-generic-metadata markdown-regex-declarative-metadata last))
4048 (defun markdown-match-pandoc-metadata (last)
4049 "Match Pandoc metadata from the point to LAST."
4050 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
4052 (defun markdown-match-yaml-metadata-begin (last)
4053 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last))
4055 (defun markdown-match-yaml-metadata-end (last)
4056 (markdown-match-propertized-text 'markdown-yaml-metadata-end last))
4058 (defun markdown-match-yaml-metadata-key (last)
4059 (markdown-match-propertized-text 'markdown-metadata-key last))
4061 (defun markdown-match-wiki-link (last)
4062 "Match wiki links from point to LAST."
4063 (when (and markdown-enable-wiki-links
4064 (not markdown-wiki-link-fontify-missing)
4065 (markdown-match-inline-generic markdown-regex-wiki-link last))
4066 (let ((begin (match-beginning 1)) (end (match-end 1)))
4067 (if (or (markdown-in-comment-p begin)
4068 (markdown-in-comment-p end)
4069 (markdown-inline-code-at-pos-p begin)
4070 (markdown-inline-code-at-pos-p end)
4071 (markdown-code-block-at-pos begin))
4072 (progn (goto-char (min (1+ begin) last))
4073 (when (< (point) last)
4074 (markdown-match-wiki-link last)))
4075 (set-match-data (list begin end))
4076 t))))
4078 (defun markdown-match-inline-attributes (last)
4079 "Match inline attributes from point to LAST."
4080 (when (markdown-match-inline-generic markdown-regex-inline-attributes last)
4081 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
4082 (markdown-inline-code-at-pos-p (match-end 0))
4083 (markdown-in-comment-p))
4084 t)))
4086 (defun markdown-match-leanpub-sections (last)
4087 "Match Leanpub section markers from point to LAST."
4088 (when (markdown-match-inline-generic markdown-regex-leanpub-sections last)
4089 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
4090 (markdown-inline-code-at-pos-p (match-end 0))
4091 (markdown-in-comment-p))
4092 t)))
4094 (defun markdown-match-includes (last)
4095 "Match include statements from point to LAST.
4096 Sets match data for the following seven groups:
4097 Group 1: opening two angle brackets
4098 Group 2: opening title delimiter (optional)
4099 Group 3: title text (optional)
4100 Group 4: closing title delimiter (optional)
4101 Group 5: opening filename delimiter
4102 Group 6: filename
4103 Group 7: closing filename delimiter"
4104 (when (markdown-match-inline-generic markdown-regex-include last)
4105 (let ((valid (not (or (markdown-in-comment-p (match-beginning 0))
4106 (markdown-in-comment-p (match-end 0))
4107 (markdown-code-block-at-pos (match-beginning 0))))))
4108 (cond
4109 ;; Parentheses and maybe square brackets, but no curly braces:
4110 ;; match optional title in square brackets and file in parentheses.
4111 ((and valid (match-beginning 5)
4112 (not (match-beginning 8)))
4113 (set-match-data (list (match-beginning 1) (match-end 7)
4114 (match-beginning 1) (match-end 1)
4115 (match-beginning 2) (match-end 2)
4116 (match-beginning 3) (match-end 3)
4117 (match-beginning 4) (match-end 4)
4118 (match-beginning 5) (match-end 5)
4119 (match-beginning 6) (match-end 6)
4120 (match-beginning 7) (match-end 7))))
4121 ;; Only square brackets present: match file in square brackets.
4122 ((and valid (match-beginning 2)
4123 (not (match-beginning 5))
4124 (not (match-beginning 7)))
4125 (set-match-data (list (match-beginning 1) (match-end 4)
4126 (match-beginning 1) (match-end 1)
4127 nil nil
4128 nil nil
4129 nil nil
4130 (match-beginning 2) (match-end 2)
4131 (match-beginning 3) (match-end 3)
4132 (match-beginning 4) (match-end 4))))
4133 ;; Only curly braces present: match file in curly braces.
4134 ((and valid (match-beginning 8)
4135 (not (match-beginning 2))
4136 (not (match-beginning 5)))
4137 (set-match-data (list (match-beginning 1) (match-end 10)
4138 (match-beginning 1) (match-end 1)
4139 nil nil
4140 nil nil
4141 nil nil
4142 (match-beginning 8) (match-end 8)
4143 (match-beginning 9) (match-end 9)
4144 (match-beginning 10) (match-end 10))))
4146 ;; Not a valid match, move to next line and search again.
4147 (forward-line)
4148 (when (< (point) last)
4149 (setq valid (markdown-match-includes last)))))
4150 valid)))
4153 ;;; Markdown Font Fontification Functions =====================================
4155 (defun markdown--first-displayable (seq)
4156 "Return the first displayable character or string in SEQ.
4157 SEQ may be an atom or a sequence."
4158 (let ((seq (if (listp seq) seq (list seq))))
4159 (cond ((stringp (car seq))
4160 (cl-find-if
4161 (lambda (str)
4162 (and (mapcar #'char-displayable-p (string-to-list str))))
4163 seq))
4164 ((characterp (car seq))
4165 (cl-find-if #'char-displayable-p seq)))))
4167 (defun markdown--marginalize-string (level)
4168 "Generate atx markup string of given LEVEL for left margin."
4169 (let ((margin-left-space-count
4170 (- markdown-marginalize-headers-margin-width level)))
4171 (concat (make-string margin-left-space-count ? )
4172 (make-string level ?#))))
4174 (defun markdown-marginalize-update-current ()
4175 "Update the window configuration to create a left margin."
4176 ;; Emacs 25 or later is needed for window-font-width and default-font-width.
4177 (if (and (fboundp 'window-font-width) (fboundp 'default-font-width))
4178 (let* ((header-delimiter-font-width
4179 (window-font-width nil 'markdown-header-delimiter-face))
4180 (margin-pixel-width (* markdown-marginalize-headers-margin-width
4181 header-delimiter-font-width))
4182 (margin-char-width (/ margin-pixel-width (default-font-width))))
4183 (set-window-margins nil margin-char-width))
4184 ;; As a fallback, simply set margin based on character count.
4185 (set-window-margins nil markdown-marginalize-headers-margin-width)))
4187 (defun markdown-fontify-headings (last)
4188 "Add text properties to headings from point to LAST."
4189 (when (markdown-match-propertized-text 'markdown-heading last)
4190 (let* ((level (markdown-outline-level))
4191 (heading-face
4192 (intern (format "markdown-header-face-%d" level)))
4193 (heading-props `(face ,heading-face))
4194 (left-markup-props
4195 `(face markdown-header-delimiter-face
4196 ,@(cond
4197 (markdown-hide-markup
4198 `(display ""))
4199 (markdown-marginalize-headers
4200 `(display ((margin left-margin)
4201 ,(markdown--marginalize-string level)))))))
4202 (right-markup-props
4203 `(face markdown-header-delimiter-face
4204 ,@(when markdown-hide-markup `(display ""))))
4205 (rule-props `(face markdown-header-rule-face
4206 ,@(when markdown-hide-markup `(display "")))))
4207 (if (match-end 1)
4208 ;; Setext heading
4209 (progn (add-text-properties
4210 (match-beginning 1) (match-end 1) heading-props)
4211 (if (= level 1)
4212 (add-text-properties
4213 (match-beginning 2) (match-end 2) rule-props)
4214 (add-text-properties
4215 (match-beginning 3) (match-end 3) rule-props)))
4216 ;; atx heading
4217 (add-text-properties
4218 (match-beginning 4) (match-end 4) left-markup-props)
4219 (add-text-properties
4220 (match-beginning 5) (match-end 5) heading-props)
4221 (when (match-end 6)
4222 (add-text-properties
4223 (match-beginning 6) (match-end 6) right-markup-props))))
4226 (defun markdown-fontify-blockquotes (last)
4227 "Apply font-lock properties to blockquotes from point to LAST."
4228 (when (markdown-match-blockquotes last)
4229 (let ((display-string
4230 (markdown--first-displayable markdown-blockquote-display-char)))
4231 (add-text-properties
4232 (match-beginning 1) (match-end 1)
4233 (if markdown-hide-markup
4234 `(face markdown-blockquote-face display ,display-string)
4235 `(face markdown-markup-face)))
4236 (font-lock-append-text-property
4237 (match-beginning 0) (match-end 0) 'face 'markdown-blockquote-face)
4238 t)))
4240 (defun markdown-fontify-list-items (last)
4241 "Apply font-lock properties to list markers from point to LAST."
4242 (when (markdown-match-list-items last)
4243 (let* ((indent (length (match-string-no-properties 1)))
4244 (level (/ indent 4)) ;; level = 0, 1, 2, ...
4245 (bullet (nth (mod level (length markdown-list-item-bullets))
4246 markdown-list-item-bullets)))
4247 (add-text-properties
4248 (match-beginning 2) (match-end 2) '(face markdown-list-face))
4249 (when markdown-hide-markup
4250 (cond
4251 ;; Unordered lists
4252 ((string-match-p "[\\*\\+-]" (match-string 2))
4253 (add-text-properties
4254 (match-beginning 2) (match-end 2) `(display ,bullet)))
4255 ;; Definition lists
4256 ((string-equal ":" (match-string 2))
4257 (add-text-properties
4258 (match-beginning 2) (match-end 2)
4259 `(display ,(char-to-string markdown-definition-display-char)))))))
4262 (defun markdown-fontify-hrs (last)
4263 "Add text properties to horizontal rules from point to LAST."
4264 (when (markdown-match-hr last)
4265 (let ((hr-char (markdown--first-displayable markdown-hr-display-char)))
4266 (add-text-properties
4267 (match-beginning 0) (match-end 0)
4268 `(face markdown-hr-face
4269 font-lock-multiline t
4270 ,@(when (and markdown-hide-markup hr-char)
4271 `(display ,(make-string
4272 (window-body-width) hr-char)))))
4273 t)))
4275 (defun markdown-fontify-sub-superscripts (last)
4276 "Apply text properties to sub- and superscripts from point to LAST."
4277 (when (markdown-search-until-condition
4278 (lambda () (and (not (markdown-code-block-at-point-p))
4279 (not (markdown-inline-code-at-point-p))
4280 (not (markdown-in-comment-p))))
4281 markdown-regex-sub-superscript last t)
4282 (let* ((subscript-p (string= (match-string 2) "~"))
4283 (index (if subscript-p 0 1))
4284 (mp (list 'face 'markdown-markup-face
4285 'invisible 'markdown-markup)))
4286 (when markdown-hide-markup
4287 (put-text-property (match-beginning 3) (match-end 3)
4288 'display
4289 (nth index markdown-sub-superscript-display)))
4290 (add-text-properties (match-beginning 2) (match-end 2) mp)
4291 (add-text-properties (match-beginning 4) (match-end 4) mp)
4292 t)))
4295 ;;; Syntax Table ==============================================================
4297 (defvar markdown-mode-syntax-table
4298 (let ((tab (make-syntax-table text-mode-syntax-table)))
4299 (modify-syntax-entry ?\" "." tab)
4300 tab)
4301 "Syntax table for `markdown-mode'.")
4304 ;;; Element Insertion =========================================================
4306 (defun markdown-ensure-blank-line-before ()
4307 "If previous line is not already blank, insert a blank line before point."
4308 (unless (bolp) (insert "\n"))
4309 (unless (or (bobp) (looking-back "\n\\s-*\n" nil)) (insert "\n")))
4311 (defun markdown-ensure-blank-line-after ()
4312 "If following line is not already blank, insert a blank line after point.
4313 Return the point where it was originally."
4314 (save-excursion
4315 (unless (eolp) (insert "\n"))
4316 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
4318 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
4319 "Insert the strings S1 and S2, wrapping around region or THING.
4320 If a region is specified by the optional BEG and END arguments,
4321 wrap the strings S1 and S2 around that region.
4322 If there is an active region, wrap the strings S1 and S2 around
4323 the region. If there is not an active region but the point is at
4324 THING, wrap that thing (which defaults to word). Otherwise, just
4325 insert S1 and S2 and place the cursor in between. Return the
4326 bounds of the entire wrapped string, or nil if nothing was wrapped
4327 and S1 and S2 were only inserted."
4328 (let (a b bounds new-point)
4329 (cond
4330 ;; Given region
4331 ((and beg end)
4332 (setq a beg
4333 b end
4334 new-point (+ (point) (length s1))))
4335 ;; Active region
4336 ((markdown-use-region-p)
4337 (setq a (region-beginning)
4338 b (region-end)
4339 new-point (+ (point) (length s1))))
4340 ;; Thing (word) at point
4341 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
4342 (setq a (car bounds)
4343 b (cdr bounds)
4344 new-point (+ (point) (length s1))))
4345 ;; No active region and no word
4347 (setq a (point)
4348 b (point))))
4349 (goto-char b)
4350 (insert s2)
4351 (goto-char a)
4352 (insert s1)
4353 (when new-point (goto-char new-point))
4354 (if (= a b)
4356 (setq b (+ b (length s1) (length s2)))
4357 (cons a b))))
4359 (defun markdown-point-after-unwrap (cur prefix suffix)
4360 "Return desired position of point after an unwrapping operation.
4361 CUR gives the position of the point before the operation.
4362 Additionally, two cons cells must be provided. PREFIX gives the
4363 bounds of the prefix string and SUFFIX gives the bounds of the
4364 suffix string."
4365 (cond ((< cur (cdr prefix)) (car prefix))
4366 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
4367 ((<= cur (cdr suffix))
4368 (- cur (+ (- (cdr prefix) (car prefix))
4369 (- cur (car suffix)))))
4370 (t cur)))
4372 (defun markdown-unwrap-thing-at-point (regexp all text)
4373 "Remove prefix and suffix of thing at point and reposition the point.
4374 When the thing at point matches REGEXP, replace the subexpression
4375 ALL with the string in subexpression TEXT. Reposition the point
4376 in an appropriate location accounting for the removal of prefix
4377 and suffix strings. Return new bounds of string from group TEXT.
4378 When REGEXP is nil, assumes match data is already set."
4379 (when (or (null regexp)
4380 (thing-at-point-looking-at regexp))
4381 (let ((cur (point))
4382 (prefix (cons (match-beginning all) (match-beginning text)))
4383 (suffix (cons (match-end text) (match-end all)))
4384 (bounds (cons (match-beginning text) (match-end text))))
4385 ;; Replace the thing at point
4386 (replace-match (match-string text) t t nil all)
4387 ;; Reposition the point
4388 (goto-char (markdown-point-after-unwrap cur prefix suffix))
4389 ;; Adjust bounds
4390 (setq bounds (cons (car prefix)
4391 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
4393 (defun markdown-unwrap-things-in-region (beg end regexp all text)
4394 "Remove prefix and suffix of all things in region from BEG to END.
4395 When a thing in the region matches REGEXP, replace the
4396 subexpression ALL with the string in subexpression TEXT.
4397 Return a cons cell containing updated bounds for the region."
4398 (save-excursion
4399 (goto-char beg)
4400 (let ((removed 0) len-all len-text)
4401 (while (re-search-forward regexp (- end removed) t)
4402 (setq len-all (length (match-string-no-properties all)))
4403 (setq len-text (length (match-string-no-properties text)))
4404 (setq removed (+ removed (- len-all len-text)))
4405 (replace-match (match-string text) t t nil all))
4406 (cons beg (- end removed)))))
4408 (defun markdown-insert-hr (arg)
4409 "Insert or replace a horizonal rule.
4410 By default, use the first element of `markdown-hr-strings'. When
4411 ARG is non-nil, as when given a prefix, select a different
4412 element as follows. When prefixed with \\[universal-argument],
4413 use the last element of `markdown-hr-strings' instead. When
4414 prefixed with an integer from 1 to the length of
4415 `markdown-hr-strings', use the element in that position instead."
4416 (interactive "*P")
4417 (when (thing-at-point-looking-at markdown-regex-hr)
4418 (delete-region (match-beginning 0) (match-end 0)))
4419 (markdown-ensure-blank-line-before)
4420 (cond ((equal arg '(4))
4421 (insert (car (reverse markdown-hr-strings))))
4422 ((and (integerp arg) (> arg 0)
4423 (<= arg (length markdown-hr-strings)))
4424 (insert (nth (1- arg) markdown-hr-strings)))
4426 (insert (car markdown-hr-strings))))
4427 (markdown-ensure-blank-line-after))
4429 (defun markdown-insert-bold ()
4430 "Insert markup to make a region or word bold.
4431 If there is an active region, make the region bold. If the point
4432 is at a non-bold word, make the word bold. If the point is at a
4433 bold word or phrase, remove the bold markup. Otherwise, simply
4434 insert bold delimiters and place the cursor in between them."
4435 (interactive)
4436 (let ((delim (if markdown-bold-underscore "__" "**")))
4437 (if (markdown-use-region-p)
4438 ;; Active region
4439 (let ((bounds (markdown-unwrap-things-in-region
4440 (region-beginning) (region-end)
4441 markdown-regex-bold 2 4)))
4442 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4443 ;; Bold markup removal, bold word at point, or empty markup insertion
4444 (if (thing-at-point-looking-at markdown-regex-bold)
4445 (markdown-unwrap-thing-at-point nil 2 4)
4446 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4448 (defun markdown-insert-italic ()
4449 "Insert markup to make a region or word italic.
4450 If there is an active region, make the region italic. If the point
4451 is at a non-italic word, make the word italic. If the point is at an
4452 italic word or phrase, remove the italic markup. Otherwise, simply
4453 insert italic delimiters and place the cursor in between them."
4454 (interactive)
4455 (let ((delim (if markdown-italic-underscore "_" "*")))
4456 (if (markdown-use-region-p)
4457 ;; Active region
4458 (let ((bounds (markdown-unwrap-things-in-region
4459 (region-beginning) (region-end)
4460 markdown-regex-italic 1 3)))
4461 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4462 ;; Italic markup removal, italic word at point, or empty markup insertion
4463 (if (thing-at-point-looking-at markdown-regex-italic)
4464 (markdown-unwrap-thing-at-point nil 1 3)
4465 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4467 (defun markdown-insert-strike-through ()
4468 "Insert markup to make a region or word strikethrough.
4469 If there is an active region, make the region strikethrough. If the point
4470 is at a non-bold word, make the word strikethrough. If the point is at a
4471 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
4472 simply insert bold delimiters and place the cursor in between them."
4473 (interactive)
4474 (let ((delim "~~"))
4475 (if (markdown-use-region-p)
4476 ;; Active region
4477 (let ((bounds (markdown-unwrap-things-in-region
4478 (region-beginning) (region-end)
4479 markdown-regex-strike-through 2 4)))
4480 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4481 ;; Strikethrough markup removal, strikethrough word at point, or empty markup insertion
4482 (if (thing-at-point-looking-at markdown-regex-strike-through)
4483 (markdown-unwrap-thing-at-point nil 2 4)
4484 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4486 (defun markdown-insert-code ()
4487 "Insert markup to make a region or word an inline code fragment.
4488 If there is an active region, make the region an inline code
4489 fragment. If the point is at a word, make the word an inline
4490 code fragment. Otherwise, simply insert code delimiters and
4491 place the cursor in between them."
4492 (interactive)
4493 (if (markdown-use-region-p)
4494 ;; Active region
4495 (let ((bounds (markdown-unwrap-things-in-region
4496 (region-beginning) (region-end)
4497 markdown-regex-code 1 3)))
4498 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
4499 ;; Code markup removal, code markup for word, or empty markup insertion
4500 (if (markdown-inline-code-at-point)
4501 (markdown-unwrap-thing-at-point nil 0 2)
4502 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
4504 (defun markdown-insert-kbd ()
4505 "Insert markup to wrap region or word in <kbd> tags.
4506 If there is an active region, use the region. If the point is at
4507 a word, use the word. Otherwise, simply insert <kbd> tags and
4508 place the cursor in between them."
4509 (interactive)
4510 (if (markdown-use-region-p)
4511 ;; Active region
4512 (let ((bounds (markdown-unwrap-things-in-region
4513 (region-beginning) (region-end)
4514 markdown-regex-kbd 0 2)))
4515 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil (car bounds) (cdr bounds)))
4516 ;; Markup removal, markup for word, or empty markup insertion
4517 (if (thing-at-point-looking-at markdown-regex-kbd)
4518 (markdown-unwrap-thing-at-point nil 0 2)
4519 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil))))
4521 (defun markdown-insert-inline-link (text url &optional title)
4522 "Insert an inline link with TEXT pointing to URL.
4523 Optionally, the user can provide a TITLE."
4524 (let ((cur (point)))
4525 (setq title (and title (concat " \"" title "\"")))
4526 (insert (concat "[" text "](" url title ")"))
4527 (cond ((not text) (goto-char (+ 1 cur)))
4528 ((not url) (goto-char (+ 3 (length text) cur))))))
4530 (defun markdown-insert-inline-image (text url &optional title)
4531 "Insert an inline link with alt TEXT pointing to URL.
4532 Optionally, also provide a TITLE."
4533 (let ((cur (point)))
4534 (setq title (and title (concat " \"" title "\"")))
4535 (insert (concat "![" text "](" url title ")"))
4536 (cond ((not text) (goto-char (+ 2 cur)))
4537 ((not url) (goto-char (+ 4 (length text) cur))))))
4539 (defun markdown-insert-reference-link (text label &optional url title)
4540 "Insert a reference link and, optionally, a reference definition.
4541 The link TEXT will be inserted followed by the optional LABEL.
4542 If a URL is given, also insert a definition for the reference
4543 LABEL according to `markdown-reference-location'. If a TITLE is
4544 given, it will be added to the end of the reference definition
4545 and will be used to populate the title attribute when converted
4546 to XHTML. If URL is nil, insert only the link portion (for
4547 example, when a reference label is already defined)."
4548 (insert (concat "[" text "][" label "]"))
4549 (when url
4550 (markdown-insert-reference-definition
4551 (if (string-equal label "") text label)
4552 url title)))
4554 (defun markdown-insert-reference-image (text label &optional url title)
4555 "Insert a reference image and, optionally, a reference definition.
4556 The alt TEXT will be inserted followed by the optional LABEL.
4557 If a URL is given, also insert a definition for the reference
4558 LABEL according to `markdown-reference-location'. If a TITLE is
4559 given, it will be added to the end of the reference definition
4560 and will be used to populate the title attribute when converted
4561 to XHTML. If URL is nil, insert only the link portion (for
4562 example, when a reference label is already defined)."
4563 (insert (concat "![" text "][" label "]"))
4564 (when url
4565 (markdown-insert-reference-definition
4566 (if (string-equal label "") text label)
4567 url title)))
4569 (defun markdown-insert-reference-definition (label &optional url title)
4570 "Add definition for reference LABEL with URL and TITLE.
4571 LABEL is a Markdown reference label without square brackets.
4572 URL and TITLE are optional. When given, the TITLE will
4573 be used to populate the title attribute when converted to XHTML."
4574 ;; END specifies where to leave the point upon return
4575 (let ((end (point)))
4576 (cl-case markdown-reference-location
4577 (end (goto-char (point-max)))
4578 (immediately (markdown-end-of-text-block))
4579 (subtree (markdown-end-of-subtree))
4580 (header (markdown-end-of-defun)))
4581 ;; Skip backwards over local variables. This logic is similar to the one
4582 ;; used in ‘hack-local-variables’.
4583 (when (and enable-local-variables (eobp))
4584 (search-backward "\n\f" (max (- (point) 3000) (point-min)) :move)
4585 (when (let ((case-fold-search t))
4586 (search-forward "Local Variables:" nil :move))
4587 (beginning-of-line 0)
4588 (when (eq (char-before) ?\n) (backward-char))))
4589 (unless (or (markdown-cur-line-blank-p)
4590 (thing-at-point-looking-at markdown-regex-reference-definition))
4591 (insert "\n"))
4592 (insert "\n[" label "]: ")
4593 (if url
4594 (insert url)
4595 ;; When no URL is given, leave cursor at END following the colon
4596 (setq end (point)))
4597 (when (> (length title) 0)
4598 (insert " \"" title "\""))
4599 (unless (looking-at-p "\n")
4600 (insert "\n"))
4601 (goto-char end)
4602 (when url
4603 (message
4604 (markdown--substitute-command-keys
4605 "Reference [%s] was defined, press \\[markdown-do] to jump there")
4606 label))))
4608 (define-obsolete-function-alias
4609 'markdown-insert-inline-link-dwim 'markdown-insert-link "v2.3")
4610 (define-obsolete-function-alias
4611 'markdown-insert-reference-link-dwim 'markdown-insert-link "v2.3")
4613 (defun markdown--insert-link-or-image (image)
4614 "Interactively insert new or update an existing link or image.
4615 When IMAGE is non-nil, insert an image. Otherwise, insert a link.
4616 This is an internal function called by
4617 `markdown-insert-link' and `markdown-insert-image'."
4618 (cl-multiple-value-bind (begin end text uri ref title)
4619 (if (markdown-use-region-p)
4620 ;; Use region as either link text or URL as appropriate.
4621 (let ((region (buffer-substring-no-properties
4622 (region-beginning) (region-end))))
4623 (if (string-match markdown-regex-uri region)
4624 ;; Region contains a URL; use it as such.
4625 (list (region-beginning) (region-end)
4626 nil (match-string 0 region) nil nil)
4627 ;; Region doesn't contain a URL, so use it as text.
4628 (list (region-beginning) (region-end)
4629 region nil nil nil)))
4630 ;; Extract and use properties of existing link, if any.
4631 (markdown-link-at-pos (point)))
4632 (let* ((ref (when ref (concat "[" ref "]")))
4633 (defined-refs (append
4634 (mapcar (lambda (ref) (concat "[" ref "]"))
4635 (markdown-get-defined-references))))
4636 (used-uris (markdown-get-used-uris))
4637 (uri-or-ref (completing-read
4638 "URL or [reference]: "
4639 (append defined-refs used-uris)
4640 nil nil (or uri ref)))
4641 (ref (cond ((string-match "\\`\\[\\(.*\\)\\]\\'" uri-or-ref)
4642 (match-string 1 uri-or-ref))
4643 ((string-equal "" uri-or-ref)
4644 "")))
4645 (uri (unless ref uri-or-ref))
4646 (text-prompt (if image
4647 "Alt text: "
4648 (if ref
4649 "Link text: "
4650 "Link text (blank for plain URL): ")))
4651 (text (read-string text-prompt text))
4652 (text (if (= (length text) 0) nil text))
4653 (plainp (and uri (not text)))
4654 (implicitp (string-equal ref ""))
4655 (ref (if implicitp text ref))
4656 (definedp (and ref (markdown-reference-definition ref)))
4657 (ref-url (unless (or uri definedp)
4658 (completing-read "Reference URL: " used-uris)))
4659 (title (unless (or plainp definedp)
4660 (read-string "Title (tooltip text, optional): " title)))
4661 (title (if (= (length title) 0) nil title)))
4662 (when (and image implicitp)
4663 (user-error "Reference required: implicit image references are invalid"))
4664 (when (and begin end)
4665 (delete-region begin end))
4666 (cond
4667 ((and (not image) uri text)
4668 (markdown-insert-inline-link text uri title))
4669 ((and image uri text)
4670 (markdown-insert-inline-image text uri title))
4671 ((and ref text)
4672 (if image
4673 (markdown-insert-reference-image text (unless implicitp ref) nil title)
4674 (markdown-insert-reference-link text (unless implicitp ref) nil title))
4675 (unless definedp
4676 (markdown-insert-reference-definition ref ref-url title)))
4677 ((and (not image) uri)
4678 (markdown-insert-uri uri))))))
4680 (defun markdown-insert-link ()
4681 "Insert new or update an existing link, with interactive prompts.
4682 If the point is at an existing link or URL, update the link text,
4683 URL, reference label, and/or title. Otherwise, insert a new link.
4684 The type of link inserted (inline, reference, or plain URL)
4685 depends on which values are provided:
4687 * If a URL and TEXT are given, insert an inline link: [TEXT](URL).
4688 * If [REF] and TEXT are given, insert a reference link: [TEXT][REF].
4689 * If only TEXT is given, insert an implicit reference link: [TEXT][].
4690 * If only a URL is given, insert a plain link: <URL>.
4692 In other words, to create an implicit reference link, leave the
4693 URL prompt empty and to create a plain URL link, leave the link
4694 text empty.
4696 If there is an active region, use the text as the default URL, if
4697 it seems to be a URL, or link text value otherwise.
4699 If a given reference is not defined, this function will
4700 additionally prompt for the URL and optional title. In this case,
4701 the reference definition is placed at the location determined by
4702 `markdown-reference-location'.
4704 Through updating the link, this function can be used to convert a
4705 link of one type (inline, reference, or plain) to another type by
4706 selectively adding or removing information via the prompts."
4707 (interactive)
4708 (markdown--insert-link-or-image nil))
4710 (defun markdown-insert-image ()
4711 "Insert new or update an existing image, with interactive prompts.
4712 If the point is at an existing image, update the alt text, URL,
4713 reference label, and/or title. Otherwise, insert a new image.
4714 The type of image inserted (inline or reference) depends on which
4715 values are provided:
4717 * If a URL and ALT-TEXT are given, insert an inline image:
4718 ![ALT-TEXT](URL).
4719 * If [REF] and ALT-TEXT are given, insert a reference image:
4720 ![ALT-TEXT][REF].
4722 If there is an active region, use the text as the default URL, if
4723 it seems to be a URL, or alt text value otherwise.
4725 If a given reference is not defined, this function will
4726 additionally prompt for the URL and optional title. In this case,
4727 the reference definition is placed at the location determined by
4728 `markdown-reference-location'.
4730 Through updating the image, this function can be used to convert an
4731 image of one type (inline or reference) to another type by
4732 selectively adding or removing information via the prompts."
4733 (interactive)
4734 (markdown--insert-link-or-image t))
4736 (defun markdown-insert-uri (&optional uri)
4737 "Insert markup for an inline URI.
4738 If there is an active region, use it as the URI. If the point is
4739 at a URI, wrap it with angle brackets. If the point is at an
4740 inline URI, remove the angle brackets. Otherwise, simply insert
4741 angle brackets place the point between them."
4742 (interactive)
4743 (if (markdown-use-region-p)
4744 ;; Active region
4745 (let ((bounds (markdown-unwrap-things-in-region
4746 (region-beginning) (region-end)
4747 markdown-regex-angle-uri 0 2)))
4748 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
4749 ;; Markup removal, URI at point, new URI, or empty markup insertion
4750 (if (thing-at-point-looking-at markdown-regex-angle-uri)
4751 (markdown-unwrap-thing-at-point nil 0 2)
4752 (if uri
4753 (insert "<" uri ">")
4754 (markdown-wrap-or-insert "<" ">" 'url nil nil)))))
4756 (defun markdown-insert-wiki-link ()
4757 "Insert a wiki link of the form [[WikiLink]].
4758 If there is an active region, use the region as the link text.
4759 If the point is at a word, use the word as the link text. If
4760 there is no active region and the point is not at word, simply
4761 insert link markup."
4762 (interactive)
4763 (if (markdown-use-region-p)
4764 ;; Active region
4765 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
4766 ;; Markup removal, wiki link at at point, or empty markup insertion
4767 (if (thing-at-point-looking-at markdown-regex-wiki-link)
4768 (if (or markdown-wiki-link-alias-first
4769 (null (match-string 5)))
4770 (markdown-unwrap-thing-at-point nil 1 3)
4771 (markdown-unwrap-thing-at-point nil 1 5))
4772 (markdown-wrap-or-insert "[[" "]]"))))
4774 (defun markdown-remove-header ()
4775 "Remove header markup if point is at a header.
4776 Return bounds of remaining header text if a header was removed
4777 and nil otherwise."
4778 (interactive "*")
4779 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
4780 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
4782 (defun markdown-insert-header (&optional level text setext)
4783 "Insert or replace header markup.
4784 The level of the header is specified by LEVEL and header text is
4785 given by TEXT. LEVEL must be an integer from 1 and 6, and the
4786 default value is 1.
4787 When TEXT is nil, the header text is obtained as follows.
4788 If there is an active region, it is used as the header text.
4789 Otherwise, the current line will be used as the header text.
4790 If there is not an active region and the point is at a header,
4791 remove the header markup and replace with level N header.
4792 Otherwise, insert empty header markup and place the cursor in
4793 between.
4794 The style of the header will be atx (hash marks) unless
4795 SETEXT is non-nil, in which case a setext-style (underlined)
4796 header will be inserted."
4797 (interactive "p\nsHeader text: ")
4798 (setq level (min (max (or level 1) 1) (if setext 2 6)))
4799 ;; Determine header text if not given
4800 (when (null text)
4801 (if (markdown-use-region-p)
4802 ;; Active region
4803 (setq text (delete-and-extract-region (region-beginning) (region-end)))
4804 ;; No active region
4805 (markdown-remove-header)
4806 (setq text (delete-and-extract-region
4807 (line-beginning-position) (line-end-position)))
4808 (when (and setext (string-match-p "^[ \t]*$" text))
4809 (setq text (read-string "Header text: "))))
4810 (setq text (markdown-compress-whitespace-string text)))
4811 ;; Insertion with given text
4812 (markdown-ensure-blank-line-before)
4813 (let (hdr)
4814 (cond (setext
4815 (setq hdr (make-string (string-width text) (if (= level 2) ?- ?=)))
4816 (insert text "\n" hdr))
4818 (setq hdr (make-string level ?#))
4819 (insert hdr " " text)
4820 (when (null markdown-asymmetric-header) (insert " " hdr)))))
4821 (markdown-ensure-blank-line-after)
4822 ;; Leave point at end of text
4823 (cond (setext
4824 (backward-char (1+ (string-width text))))
4825 ((null markdown-asymmetric-header)
4826 (backward-char (1+ level)))))
4828 (defun markdown-insert-header-dwim (&optional arg setext)
4829 "Insert or replace header markup.
4830 The level and type of the header are determined automatically by
4831 the type and level of the previous header, unless a prefix
4832 argument is given via ARG.
4833 With a numeric prefix valued 1 to 6, insert a header of the given
4834 level, with the type being determined automatically (note that
4835 only level 1 or 2 setext headers are possible).
4837 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
4838 promote the heading by one level.
4839 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
4840 demote the heading by one level.
4841 When SETEXT is non-nil, prefer setext-style headers when
4842 possible (levels one and two).
4844 When there is an active region, use it for the header text. When
4845 the point is at an existing header, change the type and level
4846 according to the rules above.
4847 Otherwise, if the line is not empty, create a header using the
4848 text on the current line as the header text.
4849 Finally, if the point is on a blank line, insert empty header
4850 markup (atx) or prompt for text (setext).
4851 See `markdown-insert-header' for more details about how the
4852 header text is determined."
4853 (interactive "*P")
4854 (let (level)
4855 (save-excursion
4856 (when (or (thing-at-point-looking-at markdown-regex-header)
4857 (re-search-backward markdown-regex-header nil t))
4858 ;; level of current or previous header
4859 (setq level (markdown-outline-level))
4860 ;; match group 1 indicates a setext header
4861 (setq setext (match-end 1))))
4862 ;; check prefix argument
4863 (cond
4864 ((and (equal arg '(4)) level (> level 1)) ;; C-u
4865 (cl-decf level))
4866 ((and (equal arg '(16)) level (< level 6)) ;; C-u C-u
4867 (cl-incf level))
4868 (arg ;; numeric prefix
4869 (setq level (prefix-numeric-value arg))))
4870 ;; setext headers must be level one or two
4871 (and level (setq setext (and setext (<= level 2))))
4872 ;; insert the heading
4873 (markdown-insert-header level nil setext)))
4875 (defun markdown-insert-header-setext-dwim (&optional arg)
4876 "Insert or replace header markup, with preference for setext.
4877 See `markdown-insert-header-dwim' for details, including how ARG is handled."
4878 (interactive "*P")
4879 (markdown-insert-header-dwim arg t))
4881 (defun markdown-insert-header-atx-1 ()
4882 "Insert a first level atx-style (hash mark) header.
4883 See `markdown-insert-header'."
4884 (interactive "*")
4885 (markdown-insert-header 1 nil nil))
4887 (defun markdown-insert-header-atx-2 ()
4888 "Insert a level two atx-style (hash mark) header.
4889 See `markdown-insert-header'."
4890 (interactive "*")
4891 (markdown-insert-header 2 nil nil))
4893 (defun markdown-insert-header-atx-3 ()
4894 "Insert a level three atx-style (hash mark) header.
4895 See `markdown-insert-header'."
4896 (interactive "*")
4897 (markdown-insert-header 3 nil nil))
4899 (defun markdown-insert-header-atx-4 ()
4900 "Insert a level four atx-style (hash mark) header.
4901 See `markdown-insert-header'."
4902 (interactive "*")
4903 (markdown-insert-header 4 nil nil))
4905 (defun markdown-insert-header-atx-5 ()
4906 "Insert a level five atx-style (hash mark) header.
4907 See `markdown-insert-header'."
4908 (interactive "*")
4909 (markdown-insert-header 5 nil nil))
4911 (defun markdown-insert-header-atx-6 ()
4912 "Insert a sixth level atx-style (hash mark) header.
4913 See `markdown-insert-header'."
4914 (interactive "*")
4915 (markdown-insert-header 6 nil nil))
4917 (defun markdown-insert-header-setext-1 ()
4918 "Insert a setext-style (underlined) first-level header.
4919 See `markdown-insert-header'."
4920 (interactive "*")
4921 (markdown-insert-header 1 nil t))
4923 (defun markdown-insert-header-setext-2 ()
4924 "Insert a setext-style (underlined) second-level header.
4925 See `markdown-insert-header'."
4926 (interactive "*")
4927 (markdown-insert-header 2 nil t))
4929 (defun markdown-blockquote-indentation (loc)
4930 "Return string containing necessary indentation for a blockquote at LOC.
4931 Also see `markdown-pre-indentation'."
4932 (save-excursion
4933 (goto-char loc)
4934 (let* ((list-level (length (markdown-calculate-list-levels)))
4935 (indent ""))
4936 (dotimes (_ list-level indent)
4937 (setq indent (concat indent " "))))))
4939 (defun markdown-insert-blockquote ()
4940 "Start a blockquote section (or blockquote the region).
4941 If Transient Mark mode is on and a region is active, it is used as
4942 the blockquote text."
4943 (interactive)
4944 (if (markdown-use-region-p)
4945 (markdown-blockquote-region (region-beginning) (region-end))
4946 (markdown-ensure-blank-line-before)
4947 (insert (markdown-blockquote-indentation (point)) "> ")
4948 (markdown-ensure-blank-line-after)))
4950 (defun markdown-block-region (beg end prefix)
4951 "Format the region using a block prefix.
4952 Arguments BEG and END specify the beginning and end of the
4953 region. The characters PREFIX will appear at the beginning
4954 of each line."
4955 (save-excursion
4956 (let* ((end-marker (make-marker))
4957 (beg-marker (make-marker))
4958 (prefix-without-trailing-whitespace
4959 (replace-regexp-in-string (rx (+ blank) eos) "" prefix)))
4960 ;; Ensure blank line after and remove extra whitespace
4961 (goto-char end)
4962 (skip-syntax-backward "-")
4963 (set-marker end-marker (point))
4964 (delete-horizontal-space)
4965 (markdown-ensure-blank-line-after)
4966 ;; Ensure blank line before and remove extra whitespace
4967 (goto-char beg)
4968 (skip-syntax-forward "-")
4969 (delete-horizontal-space)
4970 (markdown-ensure-blank-line-before)
4971 (set-marker beg-marker (point))
4972 ;; Insert PREFIX before each line
4973 (goto-char beg-marker)
4974 (while (and (< (line-beginning-position) end-marker)
4975 (not (eobp)))
4976 ;; Don’t insert trailing whitespace.
4977 (insert (if (eolp) prefix-without-trailing-whitespace prefix))
4978 (forward-line)))))
4980 (defun markdown-blockquote-region (beg end)
4981 "Blockquote the region.
4982 Arguments BEG and END specify the beginning and end of the region."
4983 (interactive "*r")
4984 (markdown-block-region
4985 beg end (concat (markdown-blockquote-indentation
4986 (max (point-min) (1- beg))) "> ")))
4988 (defun markdown-pre-indentation (loc)
4989 "Return string containing necessary whitespace for a pre block at LOC.
4990 Also see `markdown-blockquote-indentation'."
4991 (save-excursion
4992 (goto-char loc)
4993 (let* ((list-level (length (markdown-calculate-list-levels)))
4994 indent)
4995 (dotimes (_ (1+ list-level) indent)
4996 (setq indent (concat indent " "))))))
4998 (defun markdown-insert-pre ()
4999 "Start a preformatted section (or apply to the region).
5000 If Transient Mark mode is on and a region is active, it is marked
5001 as preformatted text."
5002 (interactive)
5003 (if (markdown-use-region-p)
5004 (markdown-pre-region (region-beginning) (region-end))
5005 (markdown-ensure-blank-line-before)
5006 (insert (markdown-pre-indentation (point)))
5007 (markdown-ensure-blank-line-after)))
5009 (defun markdown-pre-region (beg end)
5010 "Format the region as preformatted text.
5011 Arguments BEG and END specify the beginning and end of the region."
5012 (interactive "*r")
5013 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
5014 (markdown-block-region beg end indent)))
5016 (defun markdown-electric-backquote (arg)
5017 "Insert a backquote.
5018 The numeric prefix argument ARG says how many times to repeat the insertion.
5019 Call `markdown-insert-gfm-code-block' interactively
5020 if three backquotes inserted at the beginning of line."
5021 (interactive "*P")
5022 (self-insert-command (prefix-numeric-value arg))
5023 (when (and markdown-gfm-use-electric-backquote (looking-back "^```" nil))
5024 (replace-match "")
5025 (call-interactively #'markdown-insert-gfm-code-block)))
5027 (defconst markdown-gfm-recognized-languages
5028 ;; To reproduce/update, evaluate the let-form in
5029 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
5030 ;; but with appropriate use of a keyboard macro, indenting and filling it
5031 ;; properly is pretty fast.
5032 '("1C-Enterprise" "ABAP" "ABNF" "AGS-Script" "AMPL" "ANTLR"
5033 "API-Blueprint" "APL" "ASN.1" "ASP" "ATS" "ActionScript" "Ada" "Agda"
5034 "Alloy" "Alpine-Abuild" "Ant-Build-System" "ApacheConf" "Apex"
5035 "Apollo-Guidance-Computer" "AppleScript" "Arc" "Arduino" "AsciiDoc"
5036 "AspectJ" "Assembly" "Augeas" "AutoHotkey" "AutoIt" "Awk" "Batchfile"
5037 "Befunge" "Bison" "BitBake" "Blade" "BlitzBasic" "BlitzMax" "Bluespec"
5038 "Boo" "Brainfuck" "Brightscript" "Bro" "C#" "C++" "C-ObjDump"
5039 "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "COLLADA" "CSON" "CSS" "CSV"
5040 "CWeb" "Cap'n-Proto" "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK"
5041 "Cirru" "Clarion" "Clean" "Click" "Clojure" "Closure-Templates"
5042 "CoffeeScript" "ColdFusion" "ColdFusion-CFC" "Common-Lisp"
5043 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal"
5044 "Csound" "Csound-Document" "Csound-Score" "Cuda" "Cycript" "Cython"
5045 "D-ObjDump" "DIGITAL-Command-Language" "DM" "DNS-Zone" "DTrace"
5046 "Darcs-Patch" "Dart" "Diff" "Dockerfile" "Dogescript" "Dylan" "EBNF"
5047 "ECL" "ECLiPSe" "EJS" "EQ" "Eagle" "Ecere-Projects" "Eiffel" "Elixir"
5048 "Elm" "Emacs-Lisp" "EmberScript" "Erlang" "F#" "FLUX" "Factor" "Fancy"
5049 "Fantom" "Filebench-WML" "Filterscript" "Formatted" "Forth" "Fortran"
5050 "FreeMarker" "Frege" "G-code" "GAMS" "GAP" "GCC-Machine-Description"
5051 "GDB" "GDScript" "GLSL" "GN" "Game-Maker-Language" "Genie" "Genshi"
5052 "Gentoo-Ebuild" "Gentoo-Eclass" "Gettext-Catalog" "Gherkin" "Glyph"
5053 "Gnuplot" "Go" "Golo" "Gosu" "Grace" "Gradle" "Grammatical-Framework"
5054 "Graph-Modeling-Language" "GraphQL" "Graphviz-(DOT)" "Groovy"
5055 "Groovy-Server-Pages" "HCL" "HLSL" "HTML" "HTML+Django" "HTML+ECR"
5056 "HTML+EEX" "HTML+ERB" "HTML+PHP" "HTTP" "Hack" "Haml" "Handlebars"
5057 "Harbour" "Haskell" "Haxe" "Hy" "HyPhy" "IDL" "IGOR-Pro" "INI"
5058 "IRC-log" "Idris" "Inform-7" "Inno-Setup" "Io" "Ioke" "Isabelle"
5059 "Isabelle-ROOT" "JFlex" "JSON" "JSON5" "JSONLD" "JSONiq" "JSX"
5060 "Jasmin" "Java" "Java-Server-Pages" "JavaScript" "Jison" "Jison-Lex"
5061 "Jolie" "Julia" "Jupyter-Notebook" "KRL" "KiCad" "Kit" "Kotlin" "LFE"
5062 "LLVM" "LOLCODE" "LSL" "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex"
5063 "LilyPond" "Limbo" "Linker-Script" "Linux-Kernel-Module" "Liquid"
5064 "Literate-Agda" "Literate-CoffeeScript" "Literate-Haskell"
5065 "LiveScript" "Logos" "Logtalk" "LookML" "LoomScript" "Lua" "M4"
5066 "M4Sugar" "MAXScript" "MQL4" "MQL5" "MTML" "MUF" "Makefile" "Mako"
5067 "Markdown" "Marko" "Mask" "Mathematica" "Matlab" "Maven-POM" "Max"
5068 "MediaWiki" "Mercury" "Meson" "Metal" "MiniD" "Mirah" "Modelica"
5069 "Modula-2" "Module-Management-System" "Monkey" "Moocode" "MoonScript"
5070 "Myghty" "NCL" "NL" "NSIS" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo"
5071 "NewLisp" "Nginx" "Nim" "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml"
5072 "ObjDump" "Objective-C" "Objective-C++" "Objective-J" "Omgrofl" "Opa"
5073 "Opal" "OpenCL" "OpenEdge-ABL" "OpenRC-runscript" "OpenSCAD"
5074 "OpenType-Feature-File" "Org" "Ox" "Oxygene" "Oz" "P4" "PAWN" "PHP"
5075 "PLSQL" "PLpgSQL" "POV-Ray-SDL" "Pan" "Papyrus" "Parrot"
5076 "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal" "Pep8"
5077 "Perl" "Perl6" "Pic" "Pickle" "PicoLisp" "PigLatin" "Pike" "Pod"
5078 "PogoScript" "Pony" "PostScript" "PowerBuilder" "PowerShell"
5079 "Processing" "Prolog" "Propeller-Spin" "Protocol-Buffer" "Public-Key"
5080 "Pug" "Puppet" "Pure-Data" "PureBasic" "PureScript" "Python"
5081 "Python-console" "Python-traceback" "QML" "QMake" "RAML" "RDoc"
5082 "REALbasic" "REXX" "RHTML" "RMarkdown" "RPM-Spec" "RUNOFF" "Racket"
5083 "Ragel" "Rascal" "Raw-token-data" "Reason" "Rebol" "Red" "Redcode"
5084 "Regular-Expression" "Ren'Py" "RenderScript" "RobotFramework" "Roff"
5085 "Rouge" "Ruby" "Rust" "SAS" "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL"
5086 "SRecode-Template" "STON" "SVG" "Sage" "SaltStack" "Sass" "Scala"
5087 "Scaml" "Scheme" "Scilab" "Self" "ShaderLab" "Shell" "ShellSession"
5088 "Shen" "Slash" "Slim" "Smali" "Smalltalk" "Smarty" "SourcePawn"
5089 "Spline-Font-Database" "Squirrel" "Stan" "Standard-ML" "Stata"
5090 "Stylus" "SubRip-Text" "Sublime-Text-Config" "SuperCollider" "Swift"
5091 "SystemVerilog" "TI-Program" "TLA" "TOML" "TXL" "Tcl" "Tcsh" "TeX"
5092 "Tea" "Terra" "Text" "Textile" "Thrift" "Turing" "Turtle" "Twig"
5093 "Type-Language" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset"
5094 "Unix-Assembly" "Uno" "UnrealScript" "UrWeb" "VCL" "VHDL" "Vala"
5095 "Verilog" "Vim-script" "Visual-Basic" "Volt" "Vue"
5096 "Wavefront-Material" "Wavefront-Object" "Web-Ontology-Language"
5097 "WebAssembly" "WebIDL" "World-of-Warcraft-Addon-Data" "X10" "XC"
5098 "XCompose" "XML" "XPages" "XProc" "XQuery" "XS" "XSLT" "Xojo" "Xtend"
5099 "YAML" "YANG" "Yacc" "Zephir" "Zimpl" "desktop" "eC" "edn" "fish"
5100 "mupad" "nesC" "ooc" "reStructuredText" "wisp" "xBase")
5101 "Language specifiers recognized by GitHub's syntax highlighting features.")
5103 (defvar markdown-gfm-used-languages nil
5104 "Language names used in GFM code blocks.")
5105 (make-variable-buffer-local 'markdown-gfm-used-languages)
5107 (defun markdown-trim-whitespace (str)
5108 (markdown-replace-regexp-in-string
5109 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str))
5111 (defun markdown-clean-language-string (str)
5112 (markdown-replace-regexp-in-string
5113 "{\\.?\\|}" "" (markdown-trim-whitespace str)))
5115 (defun markdown-validate-language-string (widget)
5116 (let ((str (widget-value widget)))
5117 (unless (string= str (markdown-clean-language-string str))
5118 (widget-put widget :error (format "Invalid language spec: '%s'" str))
5119 widget)))
5121 (defun markdown-gfm-get-corpus ()
5122 "Create corpus of recognized GFM code block languages for the given buffer."
5123 (let ((given-corpus (append markdown-gfm-additional-languages
5124 markdown-gfm-recognized-languages)))
5125 (append
5126 markdown-gfm-used-languages
5127 (if markdown-gfm-downcase-languages (cl-mapcar #'downcase given-corpus)
5128 given-corpus))))
5130 (defun markdown-gfm-add-used-language (lang)
5131 "Clean LANG and add to list of used languages."
5132 (setq markdown-gfm-used-languages
5133 (cons lang (remove lang markdown-gfm-used-languages))))
5135 (defcustom markdown-spaces-after-code-fence 1
5136 "Number of space characters to insert after a code fence.
5137 \\<gfm-mode-map>\\[markdown-insert-gfm-code-block] inserts this many spaces between an
5138 opening code fence and an info string."
5139 :group 'markdown
5140 :type 'integer
5141 :safe #'natnump
5142 :package-version '(markdown-mode . "2.3"))
5144 (defun markdown-insert-gfm-code-block (&optional lang edit)
5145 "Insert GFM code block for language LANG.
5146 If LANG is nil, the language will be queried from user. If a
5147 region is active, wrap this region with the markup instead. If
5148 the region boundaries are not on empty lines, these are added
5149 automatically in order to have the correct markup. When EDIT is
5150 non-nil (e.g., when \\[universal-argument] is given), edit the
5151 code block in an indirect buffer after insertion."
5152 (interactive
5153 (list (let ((completion-ignore-case nil))
5154 (condition-case nil
5155 (markdown-clean-language-string
5156 (completing-read
5157 "Programming language: "
5158 (markdown-gfm-get-corpus)
5159 nil 'confirm (car markdown-gfm-used-languages)
5160 'markdown-gfm-language-history))
5161 (quit "")))
5162 current-prefix-arg))
5163 (unless (string= lang "") (markdown-gfm-add-used-language lang))
5164 (when (> (length lang) 0)
5165 (setq lang (concat (make-string markdown-spaces-after-code-fence ?\s)
5166 lang)))
5167 (if (markdown-use-region-p)
5168 (let* ((b (region-beginning)) (e (region-end)) end
5169 (indent (progn (goto-char b) (current-indentation))))
5170 (goto-char e)
5171 ;; if we're on a blank line, don't newline, otherwise the ```
5172 ;; should go on its own line
5173 (unless (looking-back "\n" nil)
5174 (newline))
5175 (indent-to indent)
5176 (insert "```")
5177 (markdown-ensure-blank-line-after)
5178 (setq end (point))
5179 (goto-char b)
5180 ;; if we're on a blank line, insert the quotes here, otherwise
5181 ;; add a new line first
5182 (unless (looking-at-p "\n")
5183 (newline)
5184 (forward-line -1))
5185 (markdown-ensure-blank-line-before)
5186 (indent-to indent)
5187 (insert "```" lang)
5188 (markdown-syntax-propertize-fenced-block-constructs (point-at-bol) end))
5189 (let ((indent (current-indentation)) start)
5190 (delete-horizontal-space :backward-only)
5191 (markdown-ensure-blank-line-before)
5192 (indent-to indent)
5193 (setq start (point))
5194 (insert "```" lang "\n")
5195 (indent-to indent)
5196 (unless edit (insert ?\n))
5197 (indent-to indent)
5198 (insert "```")
5199 (markdown-ensure-blank-line-after)
5200 (markdown-syntax-propertize-fenced-block-constructs start (point)))
5201 (end-of-line 0)
5202 (when edit (markdown-edit-code-block))))
5204 (defun markdown-code-block-lang (&optional pos-prop)
5205 "Return the language name for a GFM or tilde fenced code block.
5206 The beginning of the block may be described by POS-PROP,
5207 a cons of (pos . prop) giving the position and property
5208 at the beginning of the block."
5209 (or pos-prop
5210 (setq pos-prop
5211 (markdown-max-of-seq
5212 #'car
5213 (cl-remove-if
5214 #'null
5215 (cl-mapcar
5216 #'markdown-find-previous-prop
5217 (markdown-get-fenced-block-begin-properties))))))
5218 (when pos-prop
5219 (goto-char (car pos-prop))
5220 (set-match-data (get-text-property (point) (cdr pos-prop)))
5221 ;; Note: Hard-coded group number assumes tilde
5222 ;; and GFM fenced code regexp groups agree.
5223 (let ((begin (match-beginning 3))
5224 (end (match-end 3)))
5225 (when (and begin end)
5226 ;; Fix language strings beginning with periods, like ".ruby".
5227 (when (eq (char-after begin) ?.)
5228 (setq begin (1+ begin)))
5229 (buffer-substring-no-properties begin end)))))
5231 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer)
5232 (with-current-buffer (or buffer (current-buffer))
5233 (save-excursion
5234 (goto-char (point-min))
5235 (cl-loop
5236 with prop = 'markdown-gfm-block-begin
5237 for pos-prop = (markdown-find-next-prop prop)
5238 while pos-prop
5239 for lang = (markdown-code-block-lang pos-prop)
5240 do (progn (when lang (markdown-gfm-add-used-language lang))
5241 (goto-char (next-single-property-change (point) prop)))))))
5244 ;;; Footnotes ==================================================================
5246 (defun markdown-footnote-counter-inc ()
5247 "Increment `markdown-footnote-counter' and return the new value."
5248 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
5249 (save-excursion
5250 (goto-char (point-min))
5251 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
5252 (point-max) t)
5253 (let ((fn (string-to-number (match-string 1))))
5254 (when (> fn markdown-footnote-counter)
5255 (setq markdown-footnote-counter fn))))))
5256 (cl-incf markdown-footnote-counter))
5258 (defun markdown-insert-footnote ()
5259 "Insert footnote with a new number and move point to footnote definition."
5260 (interactive)
5261 (let ((fn (markdown-footnote-counter-inc)))
5262 (insert (format "[^%d]" fn))
5263 (markdown-footnote-text-find-new-location)
5264 (markdown-ensure-blank-line-before)
5265 (unless (markdown-cur-line-blank-p)
5266 (insert "\n"))
5267 (insert (format "[^%d]: " fn))
5268 (markdown-ensure-blank-line-after)))
5270 (defun markdown-footnote-text-find-new-location ()
5271 "Position the cursor at the proper location for a new footnote text."
5272 (cond
5273 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
5274 ((eq markdown-footnote-location 'immediately) (markdown-end-of-text-block))
5275 ((eq markdown-footnote-location 'subtree) (markdown-end-of-subtree))
5276 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
5278 (defun markdown-footnote-kill ()
5279 "Kill the footnote at point.
5280 The footnote text is killed (and added to the kill ring), the
5281 footnote marker is deleted. Point has to be either at the
5282 footnote marker or in the footnote text."
5283 (interactive)
5284 (let ((marker-pos nil)
5285 (skip-deleting-marker nil)
5286 (starting-footnote-text-positions
5287 (markdown-footnote-text-positions)))
5288 (when starting-footnote-text-positions
5289 ;; We're starting in footnote text, so mark our return position and jump
5290 ;; to the marker if possible.
5291 (let ((marker-pos (markdown-footnote-find-marker
5292 (cl-first starting-footnote-text-positions))))
5293 (if marker-pos
5294 (goto-char (1- marker-pos))
5295 ;; If there isn't a marker, we still want to kill the text.
5296 (setq skip-deleting-marker t))))
5297 ;; Either we didn't start in the text, or we started in the text and jumped
5298 ;; to the marker. We want to assume we're at the marker now and error if
5299 ;; we're not.
5300 (unless skip-deleting-marker
5301 (let ((marker (markdown-footnote-delete-marker)))
5302 (unless marker
5303 (error "Not at a footnote"))
5304 ;; Even if we knew the text position before, it changed when we deleted
5305 ;; the label.
5306 (setq marker-pos (cl-second marker))
5307 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker))))
5308 (unless new-text-pos
5309 (error "No text for footnote `%s'" (cl-first marker)))
5310 (goto-char new-text-pos))))
5311 (let ((pos (markdown-footnote-kill-text)))
5312 (goto-char (if starting-footnote-text-positions
5314 marker-pos)))))
5316 (defun markdown-footnote-delete-marker ()
5317 "Delete a footnote marker at point.
5318 Returns a list (ID START) containing the footnote ID and the
5319 start position of the marker before deletion. If no footnote
5320 marker was deleted, this function returns NIL."
5321 (let ((marker (markdown-footnote-marker-positions)))
5322 (when marker
5323 (delete-region (cl-second marker) (cl-third marker))
5324 (butlast marker))))
5326 (defun markdown-footnote-kill-text ()
5327 "Kill footnote text at point.
5328 Returns the start position of the footnote text before deletion,
5329 or NIL if point was not inside a footnote text.
5331 The killed text is placed in the kill ring (without the footnote
5332 number)."
5333 (let ((fn (markdown-footnote-text-positions)))
5334 (when fn
5335 (let ((text (delete-and-extract-region (cl-second fn) (cl-third fn))))
5336 (string-match (concat "\\[\\" (cl-first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
5337 (kill-new (match-string 1 text))
5338 (when (and (markdown-cur-line-blank-p)
5339 (markdown-prev-line-blank-p)
5340 (not (bobp)))
5341 (delete-region (1- (point)) (point)))
5342 (cl-second fn)))))
5344 (defun markdown-footnote-goto-text ()
5345 "Jump to the text of the footnote at point."
5346 (interactive)
5347 (let ((fn (car (markdown-footnote-marker-positions))))
5348 (unless fn
5349 (user-error "Not at a footnote marker"))
5350 (let ((new-pos (markdown-footnote-find-text fn)))
5351 (unless new-pos
5352 (error "No definition found for footnote `%s'" fn))
5353 (goto-char new-pos))))
5355 (defun markdown-footnote-return ()
5356 "Return from a footnote to its footnote number in the main text."
5357 (interactive)
5358 (let ((fn (save-excursion
5359 (car (markdown-footnote-text-positions)))))
5360 (unless fn
5361 (user-error "Not in a footnote"))
5362 (let ((new-pos (markdown-footnote-find-marker fn)))
5363 (unless new-pos
5364 (error "Footnote marker `%s' not found" fn))
5365 (goto-char new-pos))))
5367 (defun markdown-footnote-find-marker (id)
5368 "Find the location of the footnote marker with ID.
5369 The actual buffer position returned is the position directly
5370 following the marker's closing bracket. If no marker is found,
5371 NIL is returned."
5372 (save-excursion
5373 (goto-char (point-min))
5374 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
5375 (skip-chars-backward "^]")
5376 (point))))
5378 (defun markdown-footnote-find-text (id)
5379 "Find the location of the text of footnote ID.
5380 The actual buffer position returned is the position of the first
5381 character of the text, after the footnote's identifier. If no
5382 footnote text is found, NIL is returned."
5383 (save-excursion
5384 (goto-char (point-min))
5385 (when (re-search-forward (concat "^ \\{0,3\\}\\[" id "\\]:") nil t)
5386 (skip-chars-forward "[ \t]")
5387 (point))))
5389 (defun markdown-footnote-marker-positions ()
5390 "Return the position and ID of the footnote marker point is on.
5391 The return value is a list (ID START END). If point is not on a
5392 footnote, NIL is returned."
5393 ;; first make sure we're at a footnote marker
5394 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
5395 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
5396 (save-excursion
5397 ;; move point between [ and ^:
5398 (if (looking-at-p "\\[")
5399 (forward-char 1)
5400 (skip-chars-backward "^["))
5401 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
5402 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
5404 (defun markdown-footnote-text-positions ()
5405 "Return the start and end positions of the footnote text point is in.
5406 The exact return value is a list of three elements: (ID START END).
5407 The start position is the position of the opening bracket
5408 of the footnote id. The end position is directly after the
5409 newline that ends the footnote. If point is not in a footnote,
5410 NIL is returned instead."
5411 (save-excursion
5412 (let (result)
5413 (move-beginning-of-line 1)
5414 ;; Try to find the label. If we haven't found the label and we're at a blank
5415 ;; or indented line, back up if possible.
5416 (while (and
5417 (not (and (looking-at markdown-regex-footnote-definition)
5418 (setq result (list (match-string 1) (point)))))
5419 (and (not (bobp))
5420 (or (markdown-cur-line-blank-p)
5421 (>= (current-indentation) 4))))
5422 (forward-line -1))
5423 (when result
5424 ;; Advance if there is a next line that is either blank or indented.
5425 ;; (Need to check if we're on the last line, because
5426 ;; markdown-next-line-blank-p returns true for last line in buffer.)
5427 (while (and (/= (line-end-position) (point-max))
5428 (or (markdown-next-line-blank-p)
5429 (>= (markdown-next-line-indent) 4)))
5430 (forward-line))
5431 ;; Move back while the current line is blank.
5432 (while (markdown-cur-line-blank-p)
5433 (forward-line -1))
5434 ;; Advance to capture this line and a single trailing newline (if there
5435 ;; is one).
5436 (forward-line)
5437 (append result (list (point)))))))
5440 ;;; Element Removal ===========================================================
5442 (defun markdown-kill-thing-at-point ()
5443 "Kill thing at point and add important text, without markup, to kill ring.
5444 Possible things to kill include (roughly in order of precedence):
5445 inline code, headers, horizonal rules, links (add link text to
5446 kill ring), images (add alt text to kill ring), angle uri, email
5447 addresses, bold, italics, reference definition (add URI to kill
5448 ring), footnote markers and text (kill both marker and text, add
5449 text to kill ring), and list items."
5450 (interactive "*")
5451 (let (val)
5452 (cond
5453 ;; Inline code
5454 ((markdown-inline-code-at-point)
5455 (kill-new (match-string 2))
5456 (delete-region (match-beginning 0) (match-end 0)))
5457 ;; ATX header
5458 ((thing-at-point-looking-at markdown-regex-header-atx)
5459 (kill-new (match-string 2))
5460 (delete-region (match-beginning 0) (match-end 0)))
5461 ;; Setext header
5462 ((thing-at-point-looking-at markdown-regex-header-setext)
5463 (kill-new (match-string 1))
5464 (delete-region (match-beginning 0) (match-end 0)))
5465 ;; Horizonal rule
5466 ((thing-at-point-looking-at markdown-regex-hr)
5467 (kill-new (match-string 0))
5468 (delete-region (match-beginning 0) (match-end 0)))
5469 ;; Inline link or image (add link or alt text to kill ring)
5470 ((thing-at-point-looking-at markdown-regex-link-inline)
5471 (kill-new (match-string 3))
5472 (delete-region (match-beginning 0) (match-end 0)))
5473 ;; Reference link or image (add link or alt text to kill ring)
5474 ((thing-at-point-looking-at markdown-regex-link-reference)
5475 (kill-new (match-string 3))
5476 (delete-region (match-beginning 0) (match-end 0)))
5477 ;; Angle URI (add URL to kill ring)
5478 ((thing-at-point-looking-at markdown-regex-angle-uri)
5479 (kill-new (match-string 2))
5480 (delete-region (match-beginning 0) (match-end 0)))
5481 ;; Email address in angle brackets (add email address to kill ring)
5482 ((thing-at-point-looking-at markdown-regex-email)
5483 (kill-new (match-string 1))
5484 (delete-region (match-beginning 0) (match-end 0)))
5485 ;; Wiki link (add alias text to kill ring)
5486 ((and markdown-enable-wiki-links
5487 (thing-at-point-looking-at markdown-regex-wiki-link))
5488 (kill-new (markdown-wiki-link-alias))
5489 (delete-region (match-beginning 1) (match-end 1)))
5490 ;; Bold
5491 ((thing-at-point-looking-at markdown-regex-bold)
5492 (kill-new (match-string 4))
5493 (delete-region (match-beginning 2) (match-end 2)))
5494 ;; Italics
5495 ((thing-at-point-looking-at markdown-regex-italic)
5496 (kill-new (match-string 3))
5497 (delete-region (match-beginning 1) (match-end 1)))
5498 ;; Strikethrough
5499 ((thing-at-point-looking-at markdown-regex-strike-through)
5500 (kill-new (match-string 4))
5501 (delete-region (match-beginning 2) (match-end 2)))
5502 ;; Footnote marker (add footnote text to kill ring)
5503 ((thing-at-point-looking-at markdown-regex-footnote)
5504 (markdown-footnote-kill))
5505 ;; Footnote text (add footnote text to kill ring)
5506 ((setq val (markdown-footnote-text-positions))
5507 (markdown-footnote-kill))
5508 ;; Reference definition (add URL to kill ring)
5509 ((thing-at-point-looking-at markdown-regex-reference-definition)
5510 (kill-new (match-string 5))
5511 (delete-region (match-beginning 0) (match-end 0)))
5512 ;; List item
5513 ((setq val (markdown-cur-list-item-bounds))
5514 (kill-new (delete-and-extract-region (cl-first val) (cl-second val))))
5516 (user-error "Nothing found at point to kill")))))
5519 ;;; Indentation ====================================================================
5521 (defun markdown-indent-find-next-position (cur-pos positions)
5522 "Return the position after the index of CUR-POS in POSITIONS.
5523 Positions are calculated by `markdown-calc-indents'."
5524 (while (and positions
5525 (not (equal cur-pos (car positions))))
5526 (setq positions (cdr positions)))
5527 (or (cadr positions) 0))
5529 (define-obsolete-function-alias 'markdown-exdent-find-next-position
5530 'markdown-outdent-find-next-position "v2.3")
5532 (defun markdown-outdent-find-next-position (cur-pos positions)
5533 "Return the maximal element that precedes CUR-POS from POSITIONS.
5534 Positions are calculated by `markdown-calc-indents'."
5535 (let ((result 0))
5536 (dolist (i positions)
5537 (when (< i cur-pos)
5538 (setq result (max result i))))
5539 result))
5541 (defun markdown-indent-line ()
5542 "Indent the current line using some heuristics.
5543 If the _previous_ command was either `markdown-enter-key' or
5544 `markdown-cycle', then we should cycle to the next
5545 reasonable indentation position. Otherwise, we could have been
5546 called directly by `markdown-enter-key', by an initial call of
5547 `markdown-cycle', or indirectly by `auto-fill-mode'. In
5548 these cases, indent to the default position.
5549 Positions are calculated by `markdown-calc-indents'."
5550 (interactive)
5551 (let ((positions (markdown-calc-indents))
5552 (cursor-pos (current-column))
5553 (_ (back-to-indentation))
5554 (cur-pos (current-column)))
5555 (if (not (equal this-command 'markdown-cycle))
5556 (indent-line-to (car positions))
5557 (setq positions (sort (delete-dups positions) '<))
5558 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions))
5559 (new-cursor-pos
5560 (if (< cur-pos next-pos)
5561 (+ cursor-pos (- next-pos cur-pos))
5562 (- cursor-pos cur-pos))))
5563 (indent-line-to next-pos)
5564 (move-to-column new-cursor-pos)))))
5566 (defun markdown-calc-indents ()
5567 "Return a list of indentation columns to cycle through.
5568 The first element in the returned list should be considered the
5569 default indentation level. This function does not worry about
5570 duplicate positions, which are handled up by calling functions."
5571 (let (pos prev-line-pos positions)
5573 ;; Indentation of previous line
5574 (setq prev-line-pos (markdown-prev-line-indent))
5575 (setq positions (cons prev-line-pos positions))
5577 ;; Indentation of previous non-list-marker text
5578 (when (setq pos (markdown-prev-non-list-indent))
5579 (setq positions (cons pos positions)))
5581 ;; Indentation required for a pre block in current context
5582 (setq pos (length (markdown-pre-indentation (point))))
5583 (setq positions (cons pos positions))
5585 ;; Indentation of the previous line + tab-width
5586 (if prev-line-pos
5587 (setq positions (cons (+ prev-line-pos tab-width) positions))
5588 (setq positions (cons tab-width positions)))
5590 ;; Indentation of the previous line - tab-width
5591 (if (and prev-line-pos (> prev-line-pos tab-width))
5592 (setq positions (cons (- prev-line-pos tab-width) positions)))
5594 ;; Indentation of all preceeding list markers (when in a list)
5595 (when (setq pos (markdown-calculate-list-levels))
5596 (setq positions (append pos positions)))
5598 ;; First column
5599 (setq positions (cons 0 positions))
5601 ;; Return reversed list
5602 (reverse positions)))
5604 (defun markdown-enter-key ()
5605 "Handle RET depending on the context.
5606 If the point is at a table, move to the next row. Otherwise,
5607 indent according to value of `markdown-indent-on-enter'.
5608 When it is nil, simply call `newline'. Otherwise, indent the next line
5609 following RET using `markdown-indent-line'. Furthermore, when it
5610 is set to 'indent-and-new-item and the point is in a list item,
5611 start a new item with the same indentation. If the point is in an
5612 empty list item, remove it (so that pressing RET twice when in a
5613 list simply adds a blank line)."
5614 (interactive)
5615 (cond
5616 ;; Table
5617 ((markdown-table-at-point-p)
5618 (call-interactively #'markdown-table-next-row))
5619 ;; Indent non-table text
5620 (markdown-indent-on-enter
5621 (let (bounds)
5622 (if (and (memq markdown-indent-on-enter '(indent-and-new-item))
5623 (setq bounds (markdown-cur-list-item-bounds)))
5624 (let ((beg (cl-first bounds))
5625 (end (cl-second bounds))
5626 (length (cl-fourth bounds)))
5627 ;; Point is in a list item
5628 (if (= (- end beg) length)
5629 ;; Delete blank list
5630 (progn
5631 (delete-region beg end)
5632 (newline)
5633 (markdown-indent-line))
5634 (call-interactively #'markdown-insert-list-item)))
5635 ;; Point is not in a list
5636 (newline)
5637 (markdown-indent-line))))
5638 ;; Insert a raw newline
5639 (t (newline))))
5641 (define-obsolete-function-alias 'markdown-exdent-or-delete
5642 'markdown-outdent-or-delete "v2.3")
5644 (defun markdown-outdent-or-delete (arg)
5645 "Handle BACKSPACE by cycling through indentation points.
5646 When BACKSPACE is pressed, if there is only whitespace
5647 before the current point, then outdent the line one level.
5648 Otherwise, do normal delete by repeating
5649 `backward-delete-char-untabify' ARG times."
5650 (interactive "*p")
5651 (if (use-region-p)
5652 (backward-delete-char-untabify arg)
5653 (let ((cur-pos (current-column))
5654 (start-of-indention (save-excursion
5655 (back-to-indentation)
5656 (current-column)))
5657 (positions (markdown-calc-indents)))
5658 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
5659 (indent-line-to (markdown-outdent-find-next-position cur-pos positions))
5660 (backward-delete-char-untabify arg)))))
5662 (defun markdown-find-leftmost-column (beg end)
5663 "Find the leftmost column in the region from BEG to END."
5664 (let ((mincol 1000))
5665 (save-excursion
5666 (goto-char beg)
5667 (while (< (point) end)
5668 (back-to-indentation)
5669 (unless (looking-at-p "[ \t]*$")
5670 (setq mincol (min mincol (current-column))))
5671 (forward-line 1)
5673 mincol))
5675 (defun markdown-indent-region (beg end arg)
5676 "Indent the region from BEG to END using some heuristics.
5677 When ARG is non-nil, outdent the region instead.
5678 See `markdown-indent-line' and `markdown-indent-line'."
5679 (interactive "*r\nP")
5680 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
5681 (leftmostcol (markdown-find-leftmost-column beg end))
5682 (next-pos (if arg
5683 (markdown-outdent-find-next-position leftmostcol positions)
5684 (markdown-indent-find-next-position leftmostcol positions))))
5685 (indent-rigidly beg end (- next-pos leftmostcol))
5686 (setq deactivate-mark nil)))
5688 (define-obsolete-function-alias 'markdown-exdent-region
5689 'markdown-outdent-region "v2.3")
5691 (defun markdown-outdent-region (beg end)
5692 "Call `markdown-indent-region' on region from BEG to END with prefix."
5693 (interactive "*r")
5694 (markdown-indent-region beg end t))
5697 ;;; Markup Completion =========================================================
5699 (defconst markdown-complete-alist
5700 '((markdown-regex-header-atx . markdown-complete-atx)
5701 (markdown-regex-header-setext . markdown-complete-setext)
5702 (markdown-regex-hr . markdown-complete-hr))
5703 "Association list of form (regexp . function) for markup completion.")
5705 (defun markdown-incomplete-atx-p ()
5706 "Return t if ATX header markup is incomplete and nil otherwise.
5707 Assumes match data is available for `markdown-regex-header-atx'.
5708 Checks that the number of trailing hash marks equals the number of leading
5709 hash marks, that there is only a single space before and after the text,
5710 and that there is no extraneous whitespace in the text."
5712 ;; Number of starting and ending hash marks differs
5713 (not (= (length (match-string 1)) (length (match-string 3))))
5714 ;; When the header text is not empty...
5715 (and (> (length (match-string 2)) 0)
5716 ;; ...if there are extra leading, trailing, or interior spaces
5717 (or (not (= (match-beginning 2) (1+ (match-end 1))))
5718 (not (= (match-beginning 3) (1+ (match-end 2))))
5719 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
5720 ;; When the header text is empty...
5721 (and (= (length (match-string 2)) 0)
5722 ;; ...if there are too many or too few spaces
5723 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
5725 (defun markdown-complete-atx ()
5726 "Complete and normalize ATX headers.
5727 Add or remove hash marks to the end of the header to match the
5728 beginning. Ensure that there is only a single space between hash
5729 marks and header text. Removes extraneous whitespace from header text.
5730 Assumes match data is available for `markdown-regex-header-atx'.
5731 Return nil if markup was complete and non-nil if markup was completed."
5732 (when (markdown-incomplete-atx-p)
5733 (let* ((new-marker (make-marker))
5734 (new-marker (set-marker new-marker (match-end 2))))
5735 ;; Hash marks and spacing at end
5736 (goto-char (match-end 2))
5737 (delete-region (match-end 2) (match-end 3))
5738 (insert " " (match-string 1))
5739 ;; Remove extraneous whitespace from title
5740 (replace-match (markdown-compress-whitespace-string (match-string 2))
5741 t t nil 2)
5742 ;; Spacing at beginning
5743 (goto-char (match-end 1))
5744 (delete-region (match-end 1) (match-beginning 2))
5745 (insert " ")
5746 ;; Leave point at end of text
5747 (goto-char new-marker))))
5749 (defun markdown-incomplete-setext-p ()
5750 "Return t if setext header markup is incomplete and nil otherwise.
5751 Assumes match data is available for `markdown-regex-header-setext'.
5752 Checks that length of underline matches text and that there is no
5753 extraneous whitespace in the text."
5754 (or (not (= (length (match-string 1)) (length (match-string 2))))
5755 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
5757 (defun markdown-complete-setext ()
5758 "Complete and normalize setext headers.
5759 Add or remove underline characters to match length of header
5760 text. Removes extraneous whitespace from header text. Assumes
5761 match data is available for `markdown-regex-header-setext'.
5762 Return nil if markup was complete and non-nil if markup was completed."
5763 (when (markdown-incomplete-setext-p)
5764 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
5765 (char (char-after (match-beginning 2)))
5766 (level (if (char-equal char ?-) 2 1)))
5767 (goto-char (match-beginning 0))
5768 (delete-region (match-beginning 0) (match-end 0))
5769 (markdown-insert-header level text t)
5770 t)))
5772 (defun markdown-incomplete-hr-p ()
5773 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
5774 Assumes match data is available for `markdown-regex-hr'."
5775 (not (member (match-string 0) markdown-hr-strings)))
5777 (defun markdown-complete-hr ()
5778 "Complete horizontal rules.
5779 If horizontal rule string is a member of `markdown-hr-strings',
5780 do nothing. Otherwise, replace with the car of
5781 `markdown-hr-strings'.
5782 Assumes match data is available for `markdown-regex-hr'.
5783 Return nil if markup was complete and non-nil if markup was completed."
5784 (when (markdown-incomplete-hr-p)
5785 (replace-match (car markdown-hr-strings))
5788 (defun markdown-complete ()
5789 "Complete markup of object near point or in region when active.
5790 Handle all objects in `markdown-complete-alist', in order.
5791 See `markdown-complete-at-point' and `markdown-complete-region'."
5792 (interactive "*")
5793 (if (markdown-use-region-p)
5794 (markdown-complete-region (region-beginning) (region-end))
5795 (markdown-complete-at-point)))
5797 (defun markdown-complete-at-point ()
5798 "Complete markup of object near point.
5799 Handle all elements of `markdown-complete-alist' in order."
5800 (interactive "*")
5801 (let ((list markdown-complete-alist) found changed)
5802 (while list
5803 (let ((regexp (eval (caar list)))
5804 (function (cdar list)))
5805 (setq list (cdr list))
5806 (when (thing-at-point-looking-at regexp)
5807 (setq found t)
5808 (setq changed (funcall function))
5809 (setq list nil))))
5810 (if found
5811 (or changed (user-error "Markup at point is complete"))
5812 (user-error "Nothing to complete at point"))))
5814 (defun markdown-complete-region (beg end)
5815 "Complete markup of objects in region from BEG to END.
5816 Handle all objects in `markdown-complete-alist', in order. Each
5817 match is checked to ensure that a previous regexp does not also
5818 match."
5819 (interactive "*r")
5820 (let ((end-marker (set-marker (make-marker) end))
5821 previous)
5822 (dolist (element markdown-complete-alist)
5823 (let ((regexp (eval (car element)))
5824 (function (cdr element)))
5825 (goto-char beg)
5826 (while (re-search-forward regexp end-marker 'limit)
5827 (when (match-string 0)
5828 ;; Make sure this is not a match for any of the preceding regexps.
5829 ;; This prevents mistaking an HR for a Setext subheading.
5830 (let (match)
5831 (save-match-data
5832 (dolist (prev-regexp previous)
5833 (or match (setq match (looking-back prev-regexp nil)))))
5834 (unless match
5835 (save-excursion (funcall function))))))
5836 (cl-pushnew regexp previous :test #'equal)))
5837 previous))
5839 (defun markdown-complete-buffer ()
5840 "Complete markup for all objects in the current buffer."
5841 (interactive "*")
5842 (markdown-complete-region (point-min) (point-max)))
5845 ;;; Markup Cycling ============================================================
5847 (defun markdown-cycle-atx (arg &optional remove)
5848 "Cycle ATX header markup.
5849 Promote header (decrease level) when ARG is 1 and demote
5850 header (increase level) if arg is -1. When REMOVE is non-nil,
5851 remove the header when the level reaches zero and stop cycling
5852 when it reaches six. Otherwise, perform a proper cycling through
5853 levels one through six. Assumes match data is available for
5854 `markdown-regex-header-atx'."
5855 (let* ((old-level (length (match-string 1)))
5856 (new-level (+ old-level arg))
5857 (text (match-string 2)))
5858 (when (not remove)
5859 (setq new-level (% new-level 6))
5860 (setq new-level (cond ((= new-level 0) 6)
5861 ((< new-level 0) (+ new-level 6))
5862 (t new-level))))
5863 (cond
5864 ((= new-level 0)
5865 (markdown-unwrap-thing-at-point nil 0 2))
5866 ((<= new-level 6)
5867 (goto-char (match-beginning 0))
5868 (delete-region (match-beginning 0) (match-end 0))
5869 (markdown-insert-header new-level text nil)))))
5871 (defun markdown-cycle-setext (arg &optional remove)
5872 "Cycle setext header markup.
5873 Promote header (increase level) when ARG is 1 and demote
5874 header (decrease level or remove) if arg is -1. When demoting a
5875 level-two setext header, replace with a level-three atx header.
5876 When REMOVE is non-nil, remove the header when the level reaches
5877 zero. Otherwise, cycle back to a level six atx header. Assumes
5878 match data is available for `markdown-regex-header-setext'."
5879 (let* ((char (char-after (match-beginning 2)))
5880 (old-level (if (char-equal char ?=) 1 2))
5881 (new-level (+ old-level arg)))
5882 (when (and (not remove) (= new-level 0))
5883 (setq new-level 6))
5884 (cond
5885 ((= new-level 0)
5886 (markdown-unwrap-thing-at-point nil 0 1))
5887 ((<= new-level 2)
5888 (markdown-insert-header new-level nil t))
5889 ((<= new-level 6)
5890 (markdown-insert-header new-level nil nil)))))
5892 (defun markdown-cycle-hr (arg &optional remove)
5893 "Cycle string used for horizontal rule from `markdown-hr-strings'.
5894 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
5895 backwards (promote). When REMOVE is non-nil, remove the hr instead
5896 of cycling when the end of the list is reached.
5897 Assumes match data is available for `markdown-regex-hr'."
5898 (let* ((strings (if (= arg -1)
5899 (reverse markdown-hr-strings)
5900 markdown-hr-strings))
5901 (tail (member (match-string 0) strings))
5902 (new (or (cadr tail)
5903 (if remove
5904 (if (= arg 1)
5906 (car tail))
5907 (car strings)))))
5908 (replace-match new)))
5910 (defun markdown-cycle-bold ()
5911 "Cycle bold markup between underscores and asterisks.
5912 Assumes match data is available for `markdown-regex-bold'."
5913 (save-excursion
5914 (let* ((old-delim (match-string 3))
5915 (new-delim (if (string-equal old-delim "**") "__" "**")))
5916 (replace-match new-delim t t nil 3)
5917 (replace-match new-delim t t nil 5))))
5919 (defun markdown-cycle-italic ()
5920 "Cycle italic markup between underscores and asterisks.
5921 Assumes match data is available for `markdown-regex-italic'."
5922 (save-excursion
5923 (let* ((old-delim (match-string 2))
5924 (new-delim (if (string-equal old-delim "*") "_" "*")))
5925 (replace-match new-delim t t nil 2)
5926 (replace-match new-delim t t nil 4))))
5929 ;;; Keymap ====================================================================
5931 (defun markdown--style-map-prompt ()
5932 "Return a formatted prompt for Markdown markup insertion."
5933 (when markdown-enable-prefix-prompts
5934 (concat
5935 "Markdown: "
5936 (propertize "bold" 'face 'markdown-bold-face) ", "
5937 (propertize "italic" 'face 'markdown-italic-face) ", "
5938 (propertize "code" 'face 'markdown-inline-code-face) ", "
5939 (propertize "C = GFM code" 'face 'markdown-code-face) ", "
5940 (propertize "pre" 'face 'markdown-pre-face) ", "
5941 (propertize "footnote" 'face 'markdown-footnote-text-face) ", "
5942 (propertize "q = blockquote" 'face 'markdown-blockquote-face) ", "
5943 (propertize "h & 1-6 = heading" 'face 'markdown-header-face) ", "
5944 (propertize "- = hr" 'face 'markdown-hr-face) ", "
5945 "C-h = more")))
5947 (defun markdown--command-map-prompt ()
5948 "Return prompt for Markdown buffer-wide commands."
5949 (when markdown-enable-prefix-prompts
5950 (concat
5951 "Command: "
5952 (propertize "m" 'face 'markdown-bold-face) "arkdown, "
5953 (propertize "p" 'face 'markdown-bold-face) "review, "
5954 (propertize "o" 'face 'markdown-bold-face) "pen, "
5955 (propertize "e" 'face 'markdown-bold-face) "xport, "
5956 "export & pre" (propertize "v" 'face 'markdown-bold-face) "iew, "
5957 (propertize "c" 'face 'markdown-bold-face) "heck refs, "
5958 "C-h = more")))
5960 (defvar markdown-mode-style-map
5961 (let ((map (make-keymap (markdown--style-map-prompt))))
5962 (define-key map (kbd "1") 'markdown-insert-header-atx-1)
5963 (define-key map (kbd "2") 'markdown-insert-header-atx-2)
5964 (define-key map (kbd "3") 'markdown-insert-header-atx-3)
5965 (define-key map (kbd "4") 'markdown-insert-header-atx-4)
5966 (define-key map (kbd "5") 'markdown-insert-header-atx-5)
5967 (define-key map (kbd "6") 'markdown-insert-header-atx-6)
5968 (define-key map (kbd "!") 'markdown-insert-header-setext-1)
5969 (define-key map (kbd "@") 'markdown-insert-header-setext-2)
5970 (define-key map (kbd "b") 'markdown-insert-bold)
5971 (define-key map (kbd "c") 'markdown-insert-code)
5972 (define-key map (kbd "C") 'markdown-insert-gfm-code-block)
5973 (define-key map (kbd "f") 'markdown-insert-footnote)
5974 (define-key map (kbd "h") 'markdown-insert-header-dwim)
5975 (define-key map (kbd "H") 'markdown-insert-header-setext-dwim)
5976 (define-key map (kbd "i") 'markdown-insert-italic)
5977 (define-key map (kbd "k") 'markdown-insert-kbd)
5978 (define-key map (kbd "l") 'markdown-insert-link)
5979 (define-key map (kbd "p") 'markdown-insert-pre)
5980 (define-key map (kbd "P") 'markdown-pre-region)
5981 (define-key map (kbd "q") 'markdown-insert-blockquote)
5982 (define-key map (kbd "s") 'markdown-insert-strike-through)
5983 (define-key map (kbd "Q") 'markdown-blockquote-region)
5984 (define-key map (kbd "w") 'markdown-insert-wiki-link)
5985 (define-key map (kbd "-") 'markdown-insert-hr)
5986 (define-key map (kbd "[") 'markdown-insert-gfm-checkbox)
5987 ;; Deprecated keys that may be removed in a future version
5988 (define-key map (kbd "e") 'markdown-insert-italic)
5989 map)
5990 "Keymap for Markdown text styling commands.")
5992 (defvar markdown-mode-command-map
5993 (let ((map (make-keymap (markdown--command-map-prompt))))
5994 (define-key map (kbd "m") 'markdown-other-window)
5995 (define-key map (kbd "p") 'markdown-preview)
5996 (define-key map (kbd "e") 'markdown-export)
5997 (define-key map (kbd "v") 'markdown-export-and-preview)
5998 (define-key map (kbd "o") 'markdown-open)
5999 (define-key map (kbd "l") 'markdown-live-preview-mode)
6000 (define-key map (kbd "w") 'markdown-kill-ring-save)
6001 (define-key map (kbd "c") 'markdown-check-refs)
6002 (define-key map (kbd "n") 'markdown-cleanup-list-numbers)
6003 (define-key map (kbd "]") 'markdown-complete-buffer)
6004 (define-key map (kbd "^") 'markdown-table-sort-lines)
6005 (define-key map (kbd "|") 'markdown-table-convert-region)
6006 (define-key map (kbd "t") 'markdown-table-transpose)
6007 map)
6008 "Keymap for Markdown buffer-wide commands.")
6010 (defvar markdown-mode-map
6011 (let ((map (make-keymap)))
6012 ;; Markup insertion & removal
6013 (define-key map (kbd "C-c C-s") markdown-mode-style-map)
6014 (define-key map (kbd "C-c C-l") 'markdown-insert-link)
6015 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
6016 ;; Promotion, demotion, and cycling
6017 (define-key map (kbd "C-c C--") 'markdown-promote)
6018 (define-key map (kbd "C-c C-=") 'markdown-demote)
6019 (define-key map (kbd "C-c C-]") 'markdown-complete)
6020 ;; Following and doing things
6021 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
6022 (define-key map (kbd "C-c C-d") 'markdown-do)
6023 (define-key map (kbd "C-c '") 'markdown-edit-code-block)
6024 ;; Indentation
6025 (define-key map (kbd "C-m") 'markdown-enter-key)
6026 (define-key map (kbd "DEL") 'markdown-outdent-or-delete)
6027 (define-key map (kbd "C-c >") 'markdown-indent-region)
6028 (define-key map (kbd "C-c <") 'markdown-outdent-region)
6029 ;; Visibility cycling
6030 (define-key map (kbd "TAB") 'markdown-tab)
6031 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
6032 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
6033 (define-key map (kbd "<backtab>") 'markdown-shifttab)
6034 ;; Heading and list navigation
6035 (define-key map (kbd "C-c C-n") 'markdown-outline-next)
6036 (define-key map (kbd "C-c C-p") 'markdown-outline-previous)
6037 (define-key map (kbd "C-c C-f") 'markdown-outline-next-same-level)
6038 (define-key map (kbd "C-c C-b") 'markdown-outline-previous-same-level)
6039 (define-key map (kbd "C-c C-u") 'markdown-outline-up)
6040 ;; Buffer-wide commands
6041 (define-key map (kbd "C-c C-c") markdown-mode-command-map)
6042 ;; Subtree, list, and table editing
6043 (define-key map (kbd "C-c <up>") 'markdown-move-up)
6044 (define-key map (kbd "C-c <down>") 'markdown-move-down)
6045 (define-key map (kbd "C-c <left>") 'markdown-promote)
6046 (define-key map (kbd "C-c <right>") 'markdown-demote)
6047 (define-key map (kbd "C-c S-<up>") 'markdown-table-delete-row)
6048 (define-key map (kbd "C-c S-<down>") 'markdown-table-insert-row)
6049 (define-key map (kbd "C-c S-<left>") 'markdown-table-delete-column)
6050 (define-key map (kbd "C-c S-<right>") 'markdown-table-insert-column)
6051 (define-key map (kbd "C-c C-M-h") 'markdown-mark-subtree)
6052 (define-key map (kbd "C-x n s") 'markdown-narrow-to-subtree)
6053 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
6054 (define-key map (kbd "C-c C-j") 'markdown-insert-list-item)
6055 ;; Paragraphs (Markdown context aware)
6056 (define-key map [remap backward-paragraph] 'markdown-backward-paragraph)
6057 (define-key map [remap forward-paragraph] 'markdown-forward-paragraph)
6058 (define-key map [remap mark-paragraph] 'markdown-mark-paragraph)
6059 ;; Blocks (one or more paragraphs)
6060 (define-key map (kbd "C-M-{") 'markdown-backward-block)
6061 (define-key map (kbd "C-M-}") 'markdown-forward-block)
6062 (define-key map (kbd "C-c M-h") 'markdown-mark-block)
6063 (define-key map (kbd "C-x n b") 'markdown-narrow-to-block)
6064 ;; Pages (top-level sections)
6065 (define-key map [remap backward-page] 'markdown-backward-page)
6066 (define-key map [remap forward-page] 'markdown-forward-page)
6067 (define-key map [remap mark-page] 'markdown-mark-page)
6068 (define-key map [remap narrow-to-page] 'markdown-narrow-to-page)
6069 ;; Link Movement
6070 (define-key map (kbd "M-n") 'markdown-next-link)
6071 (define-key map (kbd "M-p") 'markdown-previous-link)
6072 ;; Toggling functionality
6073 (define-key map (kbd "C-c C-x C-e") 'markdown-toggle-math)
6074 (define-key map (kbd "C-c C-x C-f") 'markdown-toggle-fontify-code-blocks-natively)
6075 (define-key map (kbd "C-c C-x C-i") 'markdown-toggle-inline-images)
6076 (define-key map (kbd "C-c C-x C-l") 'markdown-toggle-url-hiding)
6077 (define-key map (kbd "C-c C-x C-m") 'markdown-toggle-markup-hiding)
6078 ;; Alternative keys (in case of problems with the arrow keys)
6079 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
6080 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
6081 (define-key map (kbd "C-c C-x l") 'markdown-promote)
6082 (define-key map (kbd "C-c C-x r") 'markdown-demote)
6083 ;; Deprecated keys that may be removed in a future version
6084 (define-key map (kbd "C-c C-a L") 'markdown-insert-link) ;; C-c C-l
6085 (define-key map (kbd "C-c C-a l") 'markdown-insert-link) ;; C-c C-l
6086 (define-key map (kbd "C-c C-a r") 'markdown-insert-link) ;; C-c C-l
6087 (define-key map (kbd "C-c C-a u") 'markdown-insert-uri) ;; C-c C-l
6088 (define-key map (kbd "C-c C-a f") 'markdown-insert-footnote)
6089 (define-key map (kbd "C-c C-a w") 'markdown-insert-wiki-link)
6090 (define-key map (kbd "C-c C-t 1") 'markdown-insert-header-atx-1)
6091 (define-key map (kbd "C-c C-t 2") 'markdown-insert-header-atx-2)
6092 (define-key map (kbd "C-c C-t 3") 'markdown-insert-header-atx-3)
6093 (define-key map (kbd "C-c C-t 4") 'markdown-insert-header-atx-4)
6094 (define-key map (kbd "C-c C-t 5") 'markdown-insert-header-atx-5)
6095 (define-key map (kbd "C-c C-t 6") 'markdown-insert-header-atx-6)
6096 (define-key map (kbd "C-c C-t !") 'markdown-insert-header-setext-1)
6097 (define-key map (kbd "C-c C-t @") 'markdown-insert-header-setext-2)
6098 (define-key map (kbd "C-c C-t h") 'markdown-insert-header-dwim)
6099 (define-key map (kbd "C-c C-t H") 'markdown-insert-header-setext-dwim)
6100 (define-key map (kbd "C-c C-t s") 'markdown-insert-header-setext-2)
6101 (define-key map (kbd "C-c C-t t") 'markdown-insert-header-setext-1)
6102 (define-key map (kbd "C-c C-i") 'markdown-insert-image)
6103 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item) ;; C-c C-j
6104 (define-key map (kbd "C-c C-x C-x") 'markdown-toggle-gfm-checkbox) ;; C-c C-d
6105 (define-key map (kbd "C-c -") 'markdown-insert-hr)
6106 map)
6107 "Keymap for Markdown major mode.")
6109 (defvar markdown-mode-mouse-map
6110 (let ((map (make-sparse-keymap)))
6111 (define-key map [follow-link] 'mouse-face)
6112 (define-key map [mouse-2] 'markdown-follow-link-at-point)
6113 map)
6114 "Keymap for following links with mouse.")
6116 (defvar gfm-mode-map
6117 (let ((map (make-sparse-keymap)))
6118 (set-keymap-parent map markdown-mode-map)
6119 (define-key map (kbd "C-c C-s d") 'markdown-insert-strike-through)
6120 (define-key map "`" 'markdown-electric-backquote)
6121 map)
6122 "Keymap for `gfm-mode'.
6123 See also `markdown-mode-map'.")
6125 (defun markdown-tab ()
6126 "Handle TAB key based on context."
6127 (interactive)
6128 (cond
6129 ((markdown-table-at-point-p)
6130 (call-interactively #'markdown-table-forward-cell))
6131 (t (call-interactively #'markdown-cycle))))
6134 ;;; Menu ==================================================================
6136 (easy-menu-define markdown-mode-menu markdown-mode-map
6137 "Menu for Markdown mode"
6138 '("Markdown"
6139 "---"
6140 ("Movement"
6141 ["Jump" markdown-do]
6142 ["Follow Link" markdown-follow-thing-at-point]
6143 ["Next Link" markdown-next-link]
6144 ["Previous Link" markdown-previous-link]
6145 "---"
6146 ["Next Heading or List Item" markdown-outline-next]
6147 ["Previous Heading or List Item" markdown-outline-previous]
6148 ["Next at Same Level" markdown-outline-next-same-level]
6149 ["Previous at Same Level" markdown-outline-previous-same-level]
6150 ["Up to Parent" markdown-outline-up]
6151 "---"
6152 ["Forward Paragraph" markdown-forward-paragraph]
6153 ["Backward Paragraph" markdown-backward-paragraph]
6154 ["Forward Block" markdown-forward-block]
6155 ["Backward Block" markdown-backward-block])
6156 ("Show & Hide"
6157 ["Cycle Heading Visibility" markdown-cycle (markdown-on-heading-p)]
6158 ["Cycle Heading Visibility (Global)" markdown-shifttab]
6159 "---"
6160 ["Narrow to Region" narrow-to-region]
6161 ["Narrow to Block" markdown-narrow-to-block]
6162 ["Narrow to Section" narrow-to-defun]
6163 ["Narrow to Subtree" markdown-narrow-to-subtree]
6164 ["Widen" widen (buffer-narrowed-p)]
6165 "---"
6166 ["Toggle Markup Hiding" markdown-toggle-markup-hiding
6167 :keys "C-c C-x C-m"
6168 :style radio
6169 :selected markdown-hide-markup])
6170 "---"
6171 ("Headings & Structure"
6172 ["Automatic Heading" markdown-insert-header-dwim :keys "C-c C-s h"]
6173 ["Automatic Heading (Setext)" markdown-insert-header-setext-dwim :keys "C-c C-s H"]
6174 ("Specific Heading (atx)"
6175 ["First Level atx" markdown-insert-header-atx-1 :keys "C-c C-s 1"]
6176 ["Second Level atx" markdown-insert-header-atx-2 :keys "C-c C-s 2"]
6177 ["Third Level atx" markdown-insert-header-atx-3 :keys "C-c C-s 3"]
6178 ["Fourth Level atx" markdown-insert-header-atx-4 :keys "C-c C-s 4"]
6179 ["Fifth Level atx" markdown-insert-header-atx-5 :keys "C-c C-s 5"]
6180 ["Sixth Level atx" markdown-insert-header-atx-6 :keys "C-c C-s 6"])
6181 ("Specific Heading (Setext)"
6182 ["First Level Setext" markdown-insert-header-setext-1 :keys "C-c C-s !"]
6183 ["Second Level Setext" markdown-insert-header-setext-2 :keys "C-c C-s @"])
6184 ["Horizontal Rule" markdown-insert-hr :keys "C-c C-s -"]
6185 "---"
6186 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
6187 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
6188 ["Promote Subtree" markdown-promote :keys "C-c <left>"]
6189 ["Demote Subtree" markdown-demote :keys "C-c <right>"])
6190 ("Region & Mark"
6191 ["Indent Region" markdown-indent-region]
6192 ["Outdent Region" markdown-outdent-region]
6193 "--"
6194 ["Mark Paragraph" mark-paragraph]
6195 ["Mark Block" markdown-mark-block]
6196 ["Mark Section" mark-defun]
6197 ["Mark Subtree" markdown-mark-subtree])
6198 ("Lists"
6199 ["Insert List Item" markdown-insert-list-item]
6200 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
6201 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
6202 ["Indent Subtree" markdown-demote :keys "C-c <right>"]
6203 ["Outdent Subtree" markdown-promote :keys "C-c <left>"]
6204 ["Renumber List" markdown-cleanup-list-numbers]
6205 ["Insert Task List Item" markdown-insert-gfm-checkbox :keys "C-c C-x ["]
6206 ["Toggle Task List Item" markdown-toggle-gfm-checkbox (markdown-gfm-task-list-item-at-point) :keys "C-c C-d"])
6207 ("Links & Images"
6208 ["Insert Link" markdown-insert-link]
6209 ["Insert Image" markdown-insert-image]
6210 ["Insert Footnote" markdown-insert-footnote :keys "C-c C-s f"]
6211 ["Insert Wiki Link" markdown-insert-wiki-link :keys "C-c C-s w"]
6212 "---"
6213 ["Check References" markdown-check-refs]
6214 ["Toggle URL Hiding" markdown-toggle-url-hiding
6215 :style radio
6216 :selected markdown-hide-urls]
6217 ["Toggle Inline Images" markdown-toggle-inline-images
6218 :keys "C-c C-x C-i"
6219 :style radio
6220 :selected markdown-inline-image-overlays]
6221 ["Toggle Wiki Links" markdown-toggle-wiki-links
6222 :style radio
6223 :selected markdown-enable-wiki-links])
6224 ("Styles"
6225 ["Bold" markdown-insert-bold]
6226 ["Italic" markdown-insert-italic]
6227 ["Code" markdown-insert-code]
6228 ["Strikethrough" markdown-insert-strike-through]
6229 ["Keyboard" markdown-insert-kbd]
6230 "---"
6231 ["Blockquote" markdown-insert-blockquote]
6232 ["Preformatted" markdown-insert-pre]
6233 ["GFM Code Block" markdown-insert-gfm-code-block]
6234 ["Edit Code Block" markdown-edit-code-block (markdown-code-block-at-point-p)]
6235 "---"
6236 ["Blockquote Region" markdown-blockquote-region]
6237 ["Preformatted Region" markdown-pre-region]
6238 "---"
6239 ["Fontify Code Blocks Natively" markdown-toggle-fontify-code-blocks-natively
6240 :style radio
6241 :selected markdown-fontify-code-blocks-natively]
6242 ["LaTeX Math Support" markdown-toggle-math
6243 :style radio
6244 :selected markdown-enable-math])
6245 "---"
6246 ("Preview & Export"
6247 ["Compile" markdown-other-window]
6248 ["Preview" markdown-preview]
6249 ["Export" markdown-export]
6250 ["Export & View" markdown-export-and-preview]
6251 ["Open" markdown-open]
6252 ["Live Export" markdown-live-preview-mode
6253 :style radio
6254 :selected markdown-live-preview-mode]
6255 ["Kill ring save" markdown-kill-ring-save])
6256 ("Markup Completion and Cycling"
6257 ["Complete Markup" markdown-complete]
6258 ["Promote Element" markdown-promote :keys "C-c C--"]
6259 ["Demote Element" markdown-demote :keys "C-c C-="])
6260 "---"
6261 ["Kill Element" markdown-kill-thing-at-point]
6262 "---"
6263 ("Documentation"
6264 ["Version" markdown-show-version]
6265 ["Homepage" markdown-mode-info]
6266 ["Describe Mode" (describe-function 'markdown-mode)]
6267 ["Guide" (browse-url "https://leanpub.com/markdown-mode")])))
6270 ;;; imenu =====================================================================
6272 (defun markdown-imenu-create-nested-index ()
6273 "Create and return a nested imenu index alist for the current buffer.
6274 See `imenu-create-index-function' and `imenu--index-alist' for details."
6275 (let* ((root '(nil . nil))
6276 cur-alist
6277 (cur-level 0)
6278 (empty-heading "-")
6279 (self-heading ".")
6280 hashes pos level heading)
6281 (save-excursion
6282 (goto-char (point-min))
6283 (while (re-search-forward markdown-regex-header (point-max) t)
6284 (unless (markdown-code-block-at-point-p)
6285 (cond
6286 ((match-string-no-properties 2) ;; level 1 setext
6287 (setq heading (match-string-no-properties 1))
6288 (setq pos (match-beginning 1)
6289 level 1))
6290 ((match-string-no-properties 3) ;; level 2 setext
6291 (setq heading (match-string-no-properties 1))
6292 (setq pos (match-beginning 1)
6293 level 2))
6294 ((setq hashes (markdown-trim-whitespace
6295 (match-string-no-properties 4)))
6296 (setq heading (match-string-no-properties 5)
6297 pos (match-beginning 4)
6298 level (length hashes))))
6299 (let ((alist (list (cons heading pos))))
6300 (cond
6301 ((= cur-level level) ; new sibling
6302 (setcdr cur-alist alist)
6303 (setq cur-alist alist))
6304 ((< cur-level level) ; first child
6305 (dotimes (_ (- level cur-level 1))
6306 (setq alist (list (cons empty-heading alist))))
6307 (if cur-alist
6308 (let* ((parent (car cur-alist))
6309 (self-pos (cdr parent)))
6310 (setcdr parent (cons (cons self-heading self-pos) alist)))
6311 (setcdr root alist)) ; primogenitor
6312 (setq cur-alist alist)
6313 (setq cur-level level))
6314 (t ; new sibling of an ancestor
6315 (let ((sibling-alist (last (cdr root))))
6316 (dotimes (_ (1- level))
6317 (setq sibling-alist (last (cdar sibling-alist))))
6318 (setcdr sibling-alist alist)
6319 (setq cur-alist alist))
6320 (setq cur-level level))))))
6321 (cdr root))))
6323 (defun markdown-imenu-create-flat-index ()
6324 "Create and return a flat imenu index alist for the current buffer.
6325 See `imenu-create-index-function' and `imenu--index-alist' for details."
6326 (let* ((empty-heading "-") index heading pos)
6327 (save-excursion
6328 (goto-char (point-min))
6329 (while (re-search-forward markdown-regex-header (point-max) t)
6330 (when (and (not (markdown-code-block-at-point-p))
6331 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin)))
6332 (cond
6333 ((setq heading (match-string-no-properties 1))
6334 (setq pos (match-beginning 1)))
6335 ((setq heading (match-string-no-properties 5))
6336 (setq pos (match-beginning 4))))
6337 (or (> (length heading) 0)
6338 (setq heading empty-heading))
6339 (setq index (append index (list (cons heading pos))))))
6340 index)))
6343 ;;; References ================================================================
6345 (defun markdown-reference-goto-definition ()
6346 "Jump to the definition of the reference at point or create it."
6347 (interactive)
6348 (when (thing-at-point-looking-at markdown-regex-link-reference)
6349 (let* ((text (match-string-no-properties 3))
6350 (reference (match-string-no-properties 6))
6351 (target (downcase (if (string= reference "") text reference)))
6352 (loc (cadr (save-match-data (markdown-reference-definition target)))))
6353 (if loc
6354 (goto-char loc)
6355 (goto-char (match-beginning 0))
6356 (markdown-insert-reference-definition target)))))
6358 (defun markdown-reference-find-links (reference)
6359 "Return a list of all links for REFERENCE.
6360 REFERENCE should not include the surrounding square brackets.
6361 Elements of the list have the form (text start line), where
6362 text is the link text, start is the location at the beginning of
6363 the link, and line is the line number on which the link appears."
6364 (let* ((ref-quote (regexp-quote reference))
6365 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
6366 ref-quote ref-quote))
6367 links)
6368 (save-excursion
6369 (goto-char (point-min))
6370 (while (re-search-forward regexp nil t)
6371 (let* ((text (or (match-string-no-properties 1)
6372 (match-string-no-properties 2)))
6373 (start (match-beginning 0))
6374 (line (markdown-line-number-at-pos)))
6375 (cl-pushnew (list text start line) links :test #'equal))))
6376 links))
6378 (defun markdown-get-undefined-refs ()
6379 "Return a list of undefined Markdown references.
6380 Result is an alist of pairs (reference . occurrences), where
6381 occurrences is itself another alist of pairs (label . line-number).
6382 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
6383 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
6384 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
6385 (let ((missing))
6386 (save-excursion
6387 (goto-char (point-min))
6388 (while
6389 (re-search-forward markdown-regex-link-reference nil t)
6390 (let* ((text (match-string-no-properties 3))
6391 (reference (match-string-no-properties 6))
6392 (target (downcase (if (string= reference "") text reference))))
6393 (unless (markdown-reference-definition target)
6394 (let ((entry (assoc target missing)))
6395 (if (not entry)
6396 (cl-pushnew
6397 (cons target (list (cons text (markdown-line-number-at-pos))))
6398 missing :test #'equal)
6399 (setcdr entry
6400 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
6401 (reverse missing))))
6403 (defconst markdown-reference-check-buffer
6404 "*Undefined references for %buffer%*"
6405 "Pattern for name of buffer for listing undefined references.
6406 The string %buffer% will be replaced by the corresponding
6407 `markdown-mode' buffer name.")
6409 (defun markdown-reference-check-buffer (&optional buffer-name)
6410 "Name and return buffer for reference checking.
6411 BUFFER-NAME is the name of the main buffer being visited."
6412 (or buffer-name (setq buffer-name (buffer-name)))
6413 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
6414 "%buffer%" buffer-name
6415 markdown-reference-check-buffer))))
6416 (with-current-buffer refbuf
6417 (when view-mode
6418 (View-exit-and-edit))
6419 (use-local-map button-buffer-map)
6420 (erase-buffer))
6421 refbuf))
6423 (defconst markdown-reference-links-buffer
6424 "*Reference links for %buffer%*"
6425 "Pattern for name of buffer for listing references.
6426 The string %buffer% will be replaced by the corresponding buffer name.")
6428 (defun markdown-reference-links-buffer (&optional buffer-name)
6429 "Name, setup, and return a buffer for listing links.
6430 BUFFER-NAME is the name of the main buffer being visited."
6431 (or buffer-name (setq buffer-name (buffer-name)))
6432 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
6433 "%buffer%" buffer-name
6434 markdown-reference-links-buffer))))
6435 (with-current-buffer linkbuf
6436 (when view-mode
6437 (View-exit-and-edit))
6438 (use-local-map button-buffer-map)
6439 (erase-buffer))
6440 linkbuf))
6442 ;; Add an empty Markdown reference definition to buffer
6443 ;; specified in the 'target-buffer property. The reference name is
6444 ;; the button's label.
6445 (define-button-type 'markdown-undefined-reference-button
6446 'help-echo "mouse-1, RET: create definition for undefined reference"
6447 'follow-link t
6448 'face 'bold
6449 'action (lambda (b)
6450 (let ((buffer (button-get b 'target-buffer))
6451 (line (button-get b 'target-line))
6452 (label (button-label b)))
6453 (switch-to-buffer-other-window buffer)
6454 (goto-char (point-min))
6455 (forward-line line)
6456 (markdown-insert-reference-definition label)
6457 (markdown-check-refs t))))
6459 ;; Jump to line in buffer specified by 'target-buffer property.
6460 ;; Line number is button's 'line property.
6461 (define-button-type 'markdown-goto-line-button
6462 'help-echo "mouse-1, RET: go to line"
6463 'follow-link t
6464 'face 'italic
6465 'action (lambda (b)
6466 (message (button-get b 'buffer))
6467 (switch-to-buffer-other-window (button-get b 'target-buffer))
6468 ;; use call-interactively to silence compiler
6469 (let ((current-prefix-arg (button-get b 'target-line)))
6470 (call-interactively 'goto-line))))
6472 ;; Jumps to a particular link at location given by 'target-char
6473 ;; property in buffer given by 'target-buffer property.
6474 (define-button-type 'markdown-location-button
6475 'help-echo "mouse-1, RET: jump to location of link"
6476 'follow-link t
6477 'face 'bold
6478 'action (lambda (b)
6479 (let ((target (button-get b 'target-buffer))
6480 (loc (button-get b 'target-char)))
6481 (kill-buffer-and-window)
6482 (switch-to-buffer target)
6483 (goto-char loc))))
6485 (defun markdown-insert-undefined-reference-button (reference oldbuf)
6486 "Insert a button for creating REFERENCE in buffer OLDBUF.
6487 REFERENCE should be a list of the form (reference . occurrences),
6488 as by `markdown-get-undefined-refs'."
6489 (let ((label (car reference)))
6490 ;; Create a reference button
6491 (insert-button label
6492 :type 'markdown-undefined-reference-button
6493 'target-buffer oldbuf
6494 'target-line (cdr (car (cdr reference))))
6495 (insert " (")
6496 (dolist (occurrence (cdr reference))
6497 (let ((line (cdr occurrence)))
6498 ;; Create a line number button
6499 (insert-button (number-to-string line)
6500 :type 'markdown-goto-line-button
6501 'target-buffer oldbuf
6502 'target-line line)
6503 (insert " ")))
6504 (delete-char -1)
6505 (insert ")")
6506 (newline)))
6508 (defun markdown-insert-link-button (link oldbuf)
6509 "Insert a button for jumping to LINK in buffer OLDBUF.
6510 LINK should be a list of the form (text char line) containing
6511 the link text, location, and line number."
6512 (let ((label (cl-first link))
6513 (char (cl-second link))
6514 (line (cl-third link)))
6515 ;; Create a reference button
6516 (insert-button label
6517 :type 'markdown-location-button
6518 'target-buffer oldbuf
6519 'target-char char)
6520 (insert (format " (line %d)\n" line))))
6522 (defun markdown-reference-goto-link (&optional reference)
6523 "Jump to the location of the first use of REFERENCE."
6524 (interactive)
6525 (unless reference
6526 (if (thing-at-point-looking-at markdown-regex-reference-definition)
6527 (setq reference (match-string-no-properties 2))
6528 (user-error "No reference definition at point")))
6529 (let ((links (markdown-reference-find-links reference)))
6530 (cond ((= (length links) 1)
6531 (goto-char (cadr (car links))))
6532 ((> (length links) 1)
6533 (let ((oldbuf (current-buffer))
6534 (linkbuf (markdown-reference-links-buffer)))
6535 (with-current-buffer linkbuf
6536 (insert "Links using reference " reference ":\n\n")
6537 (dolist (link (reverse links))
6538 (markdown-insert-link-button link oldbuf)))
6539 (view-buffer-other-window linkbuf)
6540 (goto-char (point-min))
6541 (forward-line 2)))
6543 (error "No links for reference %s" reference)))))
6545 (defun markdown-check-refs (&optional silent)
6546 "Show all undefined Markdown references in current `markdown-mode' buffer.
6547 If SILENT is non-nil, do not message anything when no undefined
6548 references found.
6549 Links which have empty reference definitions are considered to be
6550 defined."
6551 (interactive "P")
6552 (when (not (eq major-mode 'markdown-mode))
6553 (user-error "Not available in current mode"))
6554 (let ((oldbuf (current-buffer))
6555 (refs (markdown-get-undefined-refs))
6556 (refbuf (markdown-reference-check-buffer)))
6557 (if (null refs)
6558 (progn
6559 (when (not silent)
6560 (message "No undefined references found"))
6561 (kill-buffer refbuf))
6562 (with-current-buffer refbuf
6563 (insert "The following references are undefined:\n\n")
6564 (dolist (ref refs)
6565 (markdown-insert-undefined-reference-button ref oldbuf))
6566 (view-buffer-other-window refbuf)
6567 (goto-char (point-min))
6568 (forward-line 2)))))
6571 ;;; Lists =====================================================================
6573 (defun markdown-insert-list-item (&optional arg)
6574 "Insert a new list item.
6575 If the point is inside unordered list, insert a bullet mark. If
6576 the point is inside ordered list, insert the next number followed
6577 by a period. Use the previous list item to determine the amount
6578 of whitespace to place before and after list markers.
6580 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
6581 decrease the indentation by one level.
6583 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
6584 increase the indentation by one level."
6585 (interactive "p")
6586 (let (bounds cur-indent marker indent new-indent new-loc)
6587 (save-match-data
6588 ;; Look for a list item on current or previous non-blank line
6589 (save-excursion
6590 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
6591 (not (bobp))
6592 (markdown-cur-line-blank-p))
6593 (forward-line -1)))
6594 (when bounds
6595 (cond ((save-excursion
6596 (skip-chars-backward " \t")
6597 (looking-at-p markdown-regex-list))
6598 (beginning-of-line)
6599 (insert "\n")
6600 (forward-line -1))
6601 ((not (markdown-cur-line-blank-p))
6602 (newline)))
6603 (setq new-loc (point)))
6604 ;; Look ahead for a list item on next non-blank line
6605 (unless bounds
6606 (save-excursion
6607 (while (and (null bounds)
6608 (not (eobp))
6609 (markdown-cur-line-blank-p))
6610 (forward-line)
6611 (setq bounds (markdown-cur-list-item-bounds))))
6612 (when bounds
6613 (setq new-loc (point))
6614 (unless (markdown-cur-line-blank-p)
6615 (newline))))
6616 (if (not bounds)
6617 ;; When not in a list, start a new unordered one
6618 (progn
6619 (unless (markdown-cur-line-blank-p)
6620 (insert "\n"))
6621 (insert markdown-unordered-list-item-prefix))
6622 ;; Compute indentation and marker for new list item
6623 (setq cur-indent (nth 2 bounds))
6624 (setq marker (nth 4 bounds))
6625 ;; If current item is a GFM checkbox, insert new unchecked checkbox.
6626 (when (nth 5 bounds)
6627 (setq marker
6628 (concat marker
6629 (replace-regexp-in-string "[Xx]" " " (nth 5 bounds)))))
6630 (cond
6631 ;; Dedent: decrement indentation, find previous marker.
6632 ((= arg 4)
6633 (setq indent (max (- cur-indent 4) 0))
6634 (let ((prev-bounds
6635 (save-excursion
6636 (goto-char (nth 0 bounds))
6637 (when (markdown-up-list)
6638 (markdown-cur-list-item-bounds)))))
6639 (when prev-bounds
6640 (setq marker (nth 4 prev-bounds)))))
6641 ;; Indent: increment indentation by 4, use same marker.
6642 ((= arg 16) (setq indent (+ cur-indent 4)))
6643 ;; Same level: keep current indentation and marker.
6644 (t (setq indent cur-indent)))
6645 (setq new-indent (make-string indent 32))
6646 (goto-char new-loc)
6647 (cond
6648 ;; Ordered list
6649 ((string-match-p "[0-9]" marker)
6650 (if (= arg 16) ;; starting a new column indented one more level
6651 (insert (concat new-indent "1. "))
6652 ;; Don't use previous match-data
6653 (set-match-data nil)
6654 ;; travel up to the last item and pick the correct number. If
6655 ;; the argument was nil, "new-indent = cur-indent" is the same,
6656 ;; so we don't need special treatment. Neat.
6657 (save-excursion
6658 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
6659 (>= (forward-line -1) 0))))
6660 (let* ((old-prefix (match-string 1))
6661 (old-spacing (match-string 2))
6662 (new-prefix (if old-prefix
6663 (int-to-string (1+ (string-to-number old-prefix)))
6664 "1"))
6665 (space-adjust (- (length old-prefix) (length new-prefix)))
6666 (new-spacing (if (and (match-string 2)
6667 (not (string-match-p "\t" old-spacing))
6668 (< space-adjust 0)
6669 (> space-adjust (- 1 (length (match-string 2)))))
6670 (substring (match-string 2) 0 space-adjust)
6671 (or old-spacing ". "))))
6672 (insert (concat new-indent new-prefix new-spacing)))))
6673 ;; Unordered list, GFM task list, or ordered list with hash mark
6674 ((string-match-p "[\\*\\+-]\\|#\\." marker)
6675 (insert new-indent marker)))))))
6677 (defun markdown-move-list-item-up ()
6678 "Move the current list item up in the list when possible.
6679 In nested lists, move child items with the parent item."
6680 (interactive)
6681 (let (cur prev old)
6682 (when (setq cur (markdown-cur-list-item-bounds))
6683 (setq old (point))
6684 (goto-char (nth 0 cur))
6685 (if (markdown-prev-list-item (nth 3 cur))
6686 (progn
6687 (setq prev (markdown-cur-list-item-bounds))
6688 (condition-case nil
6689 (progn
6690 (transpose-regions (nth 0 prev) (nth 1 prev)
6691 (nth 0 cur) (nth 1 cur) t)
6692 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
6693 ;; Catch error in case regions overlap.
6694 (error (goto-char old))))
6695 (goto-char old)))))
6697 (defun markdown-move-list-item-down ()
6698 "Move the current list item down in the list when possible.
6699 In nested lists, move child items with the parent item."
6700 (interactive)
6701 (let (cur next old)
6702 (when (setq cur (markdown-cur-list-item-bounds))
6703 (setq old (point))
6704 (if (markdown-next-list-item (nth 3 cur))
6705 (progn
6706 (setq next (markdown-cur-list-item-bounds))
6707 (condition-case nil
6708 (progn
6709 (transpose-regions (nth 0 cur) (nth 1 cur)
6710 (nth 0 next) (nth 1 next) nil)
6711 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
6712 ;; Catch error in case regions overlap.
6713 (error (goto-char old))))
6714 (goto-char old)))))
6716 (defun markdown-demote-list-item (&optional bounds)
6717 "Indent (or demote) the current list item.
6718 Optionally, BOUNDS of the current list item may be provided if available.
6719 In nested lists, demote child items as well."
6720 (interactive)
6721 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6722 (save-excursion
6723 (let ((end-marker (set-marker (make-marker) (nth 1 bounds))))
6724 (goto-char (nth 0 bounds))
6725 (while (< (point) end-marker)
6726 (unless (markdown-cur-line-blank-p)
6727 (insert (make-string markdown-list-indent-width ? )))
6728 (forward-line))))))
6730 (defun markdown-promote-list-item (&optional bounds)
6731 "Unindent (or promote) the current list item.
6732 Optionally, BOUNDS of the current list item may be provided if available.
6733 In nested lists, demote child items as well."
6734 (interactive)
6735 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6736 (save-excursion
6737 (save-match-data
6738 (let ((end-marker (set-marker (make-marker) (nth 1 bounds)))
6739 num regexp)
6740 (goto-char (nth 0 bounds))
6741 (when (looking-at (format "^[ ]\\{1,%d\\}"
6742 markdown-list-indent-width))
6743 (setq num (- (match-end 0) (match-beginning 0)))
6744 (setq regexp (format "^[ ]\\{1,%d\\}" num))
6745 (while (and (< (point) end-marker)
6746 (re-search-forward regexp end-marker t))
6747 (replace-match "" nil nil)
6748 (forward-line))))))))
6750 (defun markdown-cleanup-list-numbers-level (&optional pfx)
6751 "Update the numbering for level PFX (as a string of spaces).
6753 Assume that the previously found match was for a numbered item in
6754 a list."
6755 (let ((cpfx pfx)
6756 (idx 0)
6757 (continue t)
6758 (step t)
6759 (sep nil))
6760 (while (and continue (not (eobp)))
6761 (setq step t)
6762 (cond
6763 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
6764 (setq cpfx (match-string-no-properties 1))
6765 (cond
6766 ((string= cpfx pfx)
6767 (save-excursion
6768 (replace-match
6769 (concat pfx (number-to-string (setq idx (1+ idx))) ". ")))
6770 (setq sep nil))
6771 ;; indented a level
6772 ((string< pfx cpfx)
6773 (setq sep (markdown-cleanup-list-numbers-level cpfx))
6774 (setq step nil))
6775 ;; exit the loop
6777 (setq step nil)
6778 (setq continue nil))))
6780 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
6781 (setq cpfx (match-string-no-properties 1))
6782 (cond
6783 ;; reset if separated before
6784 ((string= cpfx pfx) (when sep (setq idx 0)))
6785 ((string< cpfx pfx)
6786 (setq step nil)
6787 (setq continue nil))))
6788 (t (setq sep t)))
6790 (when step
6791 (beginning-of-line)
6792 (setq continue (= (forward-line) 0))))
6793 sep))
6795 (defun markdown-cleanup-list-numbers ()
6796 "Update the numbering of ordered lists."
6797 (interactive)
6798 (save-excursion
6799 (goto-char (point-min))
6800 (markdown-cleanup-list-numbers-level "")))
6803 ;;; Movement ==================================================================
6805 (defun markdown-beginning-of-defun (&optional arg)
6806 "`beginning-of-defun-function' for Markdown.
6807 This is used to find the beginning of the defun and should behave
6808 like ‘beginning-of-defun’, returning non-nil if it found the
6809 beginning of a defun. It moves the point backward, right before a
6810 heading which defines a defun. When ARG is non-nil, repeat that
6811 many times. When ARG is negative, move forward to the ARG-th
6812 following section."
6813 (or arg (setq arg 1))
6814 (when (< arg 0) (end-of-line))
6815 ;; Adjust position for setext headings.
6816 (when (and (thing-at-point-looking-at markdown-regex-header-setext)
6817 (not (= (point) (match-beginning 0)))
6818 (not (markdown-code-block-at-point-p)))
6819 (goto-char (match-end 0)))
6820 (let (found)
6821 ;; Move backward with positive argument.
6822 (while (and (not (bobp)) (> arg 0))
6823 (setq found nil)
6824 (while (and (not found)
6825 (not (bobp))
6826 (re-search-backward markdown-regex-header nil 'move))
6827 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6828 (setq found (match-beginning 0)))
6829 (setq arg (1- arg)))
6830 ;; Move forward with negative argument.
6831 (while (and (not (eobp)) (< arg 0))
6832 (setq found nil)
6833 (while (and (not found)
6834 (not (eobp))
6835 (re-search-forward markdown-regex-header nil 'move))
6836 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6837 (setq found (match-beginning 0)))
6838 (setq arg (1+ arg)))
6839 (when found
6840 (beginning-of-line)
6841 t)))
6843 (defun markdown-end-of-defun ()
6844 "`end-of-defun-function’ for Markdown.
6845 This is used to find the end of the defun at point.
6846 It is called with no argument, right after calling ‘beginning-of-defun-raw’,
6847 so it can assume that point is at the beginning of the defun body.
6848 It should move point to the first position after the defun."
6849 (or (eobp) (forward-char 1))
6850 (let (found)
6851 (while (and (not found)
6852 (not (eobp))
6853 (re-search-forward markdown-regex-header nil 'move))
6854 (when (not (markdown-code-block-at-pos (match-beginning 0)))
6855 (setq found (match-beginning 0))))
6856 (when found
6857 (goto-char found)
6858 (skip-syntax-backward "-"))))
6860 (make-obsolete 'markdown-beginning-of-block 'markdown-beginning-of-text-block "v2.2")
6862 (defun markdown-beginning-of-text-block ()
6863 "Move backward to previous beginning of a plain text block.
6864 This function simply looks for blank lines without considering
6865 the surrounding context in light of Markdown syntax. For that, see
6866 `markdown-backward-block'."
6867 (interactive)
6868 (let ((start (point)))
6869 (if (re-search-backward markdown-regex-block-separator nil t)
6870 (goto-char (match-end 0))
6871 (goto-char (point-min)))
6872 (when (and (= start (point)) (not (bobp)))
6873 (forward-line -1)
6874 (if (re-search-backward markdown-regex-block-separator nil t)
6875 (goto-char (match-end 0))
6876 (goto-char (point-min))))))
6878 (make-obsolete 'markdown-end-of-block 'markdown-end-of-text-block "v2.2")
6880 (defun markdown-end-of-text-block ()
6881 "Move forward to next beginning of a plain text block.
6882 This function simply looks for blank lines without considering
6883 the surrounding context in light of Markdown syntax. For that, see
6884 `markdown-forward-block'."
6885 (interactive)
6886 (beginning-of-line)
6887 (skip-syntax-forward "-")
6888 (when (= (point) (point-min))
6889 (forward-char))
6890 (if (re-search-forward markdown-regex-block-separator nil t)
6891 (goto-char (match-end 0))
6892 (goto-char (point-max)))
6893 (skip-syntax-backward "-")
6894 (forward-line))
6896 (defun markdown-backward-paragraph (&optional arg)
6897 "Move the point to the start of the current paragraph.
6898 With argument ARG, do it ARG times; a negative argument ARG = -N
6899 means move forward N blocks."
6900 (interactive "^p")
6901 (or arg (setq arg 1))
6902 (if (< arg 0)
6903 (markdown-forward-paragraph (- arg))
6904 (dotimes (_ arg)
6905 ;; Skip over whitespace in between paragraphs when moving backward.
6906 (skip-syntax-backward "-")
6907 (beginning-of-line)
6908 ;; Skip over code block endings.
6909 (when (markdown-range-properties-exist
6910 (point-at-bol) (point-at-eol)
6911 '(markdown-gfm-block-end
6912 markdown-tilde-fence-end))
6913 (forward-line -1))
6914 ;; Skip over blank lines inside blockquotes.
6915 (while (and (not (eobp))
6916 (looking-at markdown-regex-blockquote)
6917 (= (length (match-string 3)) 0))
6918 (forward-line -1))
6919 ;; Proceed forward based on the type of block of paragraph.
6920 (let (bounds skip)
6921 (cond
6922 ;; Blockquotes
6923 ((looking-at markdown-regex-blockquote)
6924 (while (and (not (bobp))
6925 (looking-at markdown-regex-blockquote)
6926 (> (length (match-string 3)) 0)) ;; not blank
6927 (forward-line -1))
6928 (forward-line))
6929 ;; List items
6930 ((setq bounds (markdown-cur-list-item-bounds))
6931 (goto-char (nth 0 bounds)))
6932 ;; Other
6934 (while (and (not (bobp))
6935 (not skip)
6936 (not (markdown-cur-line-blank-p))
6937 (not (looking-at markdown-regex-blockquote))
6938 (not (markdown-range-properties-exist
6939 (point-at-bol) (point-at-eol)
6940 '(markdown-gfm-block-end
6941 markdown-tilde-fence-end))))
6942 (setq skip (markdown-range-properties-exist
6943 (point-at-bol) (point-at-eol)
6944 '(markdown-gfm-block-begin
6945 markdown-tilde-fence-begin)))
6946 (forward-line -1))
6947 (unless (bobp)
6948 (forward-line 1))))))))
6950 (defun markdown-forward-paragraph (&optional arg)
6951 "Move forward to the next end of a paragraph.
6952 With argument ARG, do it ARG times; a negative argument ARG = -N
6953 means move backward N blocks."
6954 (interactive "^p")
6955 (or arg (setq arg 1))
6956 (if (< arg 0)
6957 (markdown-backward-paragraph (- arg))
6958 (dotimes (_ arg)
6959 ;; Skip whitespace in between paragraphs.
6960 (when (markdown-cur-line-blank-p)
6961 (skip-syntax-forward "-")
6962 (beginning-of-line))
6963 ;; Proceed forward based on the type of block.
6964 (let (bounds skip)
6965 (cond
6966 ;; Blockquotes
6967 ((looking-at markdown-regex-blockquote)
6968 ;; Skip over blank lines inside blockquotes.
6969 (while (and (not (eobp))
6970 (looking-at markdown-regex-blockquote)
6971 (= (length (match-string 3)) 0))
6972 (forward-line))
6973 ;; Move to end of quoted text block
6974 (while (and (not (eobp))
6975 (looking-at markdown-regex-blockquote)
6976 (> (length (match-string 3)) 0)) ;; not blank
6977 (forward-line)))
6978 ;; List items
6979 ((and (markdown-cur-list-item-bounds)
6980 (setq bounds (markdown-next-list-item-bounds)))
6981 (goto-char (nth 0 bounds)))
6982 ;; Other
6984 (forward-line)
6985 (while (and (not (eobp))
6986 (not skip)
6987 (not (markdown-cur-line-blank-p))
6988 (not (looking-at markdown-regex-blockquote))
6989 (not (markdown-range-properties-exist
6990 (point-at-bol) (point-at-eol)
6991 '(markdown-gfm-block-begin
6992 markdown-tilde-fence-begin))))
6993 (setq skip (markdown-range-properties-exist
6994 (point-at-bol) (point-at-eol)
6995 '(markdown-gfm-block-end
6996 markdown-tilde-fence-end)))
6997 (forward-line))))))))
6999 (defun markdown-backward-block (&optional arg)
7000 "Move the point to the start of the current Markdown block.
7001 Moves across complete code blocks, list items, and blockquotes,
7002 but otherwise stops at blank lines, headers, and horizontal
7003 rules. With argument ARG, do it ARG times; a negative argument
7004 ARG = -N means move forward N blocks."
7005 (interactive "^p")
7006 (or arg (setq arg 1))
7007 (if (< arg 0)
7008 (markdown-forward-block (- arg))
7009 (dotimes (_ arg)
7010 ;; Skip over whitespace in between blocks when moving backward,
7011 ;; unless at a block boundary with no whitespace.
7012 (skip-syntax-backward "-")
7013 (beginning-of-line)
7014 ;; Proceed forward based on the type of block.
7015 (cond
7016 ;; Code blocks
7017 ((and (markdown-code-block-at-pos (point)) ;; this line
7018 (markdown-code-block-at-pos (point-at-bol 0))) ;; previous line
7019 (forward-line -1)
7020 (while (and (markdown-code-block-at-point-p) (not (bobp)))
7021 (forward-line -1))
7022 (forward-line))
7023 ;; Headings
7024 ((markdown-heading-at-point)
7025 (goto-char (match-beginning 0)))
7026 ;; Horizontal rules
7027 ((looking-at markdown-regex-hr))
7028 ;; Blockquotes
7029 ((looking-at markdown-regex-blockquote)
7030 (forward-line -1)
7031 (while (and (looking-at markdown-regex-blockquote)
7032 (not (bobp)))
7033 (forward-line -1))
7034 (forward-line))
7035 ;; List items
7036 ((markdown-cur-list-item-bounds)
7037 (markdown-beginning-of-list))
7038 ;; Other
7040 ;; Move forward in case it is a one line regular paragraph.
7041 (unless (markdown-next-line-blank-p)
7042 (forward-line))
7043 (unless (markdown-prev-line-blank-p)
7044 (markdown-backward-paragraph)))))))
7046 (defun markdown-forward-block (&optional arg)
7047 "Move forward to the next end of a Markdown block.
7048 Moves across complete code blocks, list items, and blockquotes,
7049 but otherwise stops at blank lines, headers, and horizontal
7050 rules. With argument ARG, do it ARG times; a negative argument
7051 ARG = -N means move backward N blocks."
7052 (interactive "^p")
7053 (or arg (setq arg 1))
7054 (if (< arg 0)
7055 (markdown-backward-block (- arg))
7056 (dotimes (_ arg)
7057 ;; Skip over whitespace in between blocks when moving forward.
7058 (if (markdown-cur-line-blank-p)
7059 (skip-syntax-forward "-")
7060 (beginning-of-line))
7061 ;; Proceed forward based on the type of block.
7062 (cond
7063 ;; Code blocks
7064 ((markdown-code-block-at-point-p)
7065 (forward-line)
7066 (while (and (markdown-code-block-at-point-p) (not (eobp)))
7067 (forward-line)))
7068 ;; Headings
7069 ((looking-at markdown-regex-header)
7070 (goto-char (or (match-end 4) (match-end 2) (match-end 3)))
7071 (forward-line))
7072 ;; Horizontal rules
7073 ((looking-at markdown-regex-hr)
7074 (forward-line))
7075 ;; Blockquotes
7076 ((looking-at markdown-regex-blockquote)
7077 (forward-line)
7078 (while (and (looking-at markdown-regex-blockquote) (not (eobp)))
7079 (forward-line)))
7080 ;; List items
7081 ((markdown-cur-list-item-bounds)
7082 (markdown-end-of-list)
7083 (forward-line))
7084 ;; Other
7085 (t (markdown-forward-paragraph))))
7086 (skip-syntax-backward "-")
7087 (unless (eobp)
7088 (forward-char 1))))
7090 (defun markdown-backward-page (&optional count)
7091 "Move backward to boundary of the current toplevel section.
7092 With COUNT, repeat, or go forward if negative."
7093 (interactive "p")
7094 (or count (setq count 1))
7095 (if (< count 0)
7096 (markdown-forward-page (- count))
7097 (skip-syntax-backward "-")
7098 (or (markdown-back-to-heading-over-code-block t t)
7099 (goto-char (point-min)))
7100 (when (looking-at markdown-regex-header)
7101 (let ((level (markdown-outline-level)))
7102 (when (> level 1) (markdown-up-heading level))
7103 (when (> count 1)
7104 (condition-case nil
7105 (markdown-backward-same-level (1- count))
7106 (error (goto-char (point-min)))))))))
7108 (defun markdown-forward-page (&optional count)
7109 "Move forward to boundary of the current toplevel section.
7110 With COUNT, repeat, or go backward if negative."
7111 (interactive "p")
7112 (or count (setq count 1))
7113 (if (< count 0)
7114 (markdown-backward-page (- count))
7115 (if (markdown-back-to-heading-over-code-block t t)
7116 (let ((level (markdown-outline-level)))
7117 (when (> level 1) (markdown-up-heading level))
7118 (condition-case nil
7119 (markdown-forward-same-level count)
7120 (error (goto-char (point-max)))))
7121 (markdown-next-visible-heading 1))))
7123 (defun markdown-next-link ()
7124 "Jump to next inline, reference, or wiki link.
7125 If successful, return point. Otherwise, return nil.
7126 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
7127 (interactive)
7128 (let ((opoint (point)))
7129 (when (or (markdown-link-p) (markdown-wiki-link-p))
7130 ;; At a link already, move past it.
7131 (goto-char (+ (match-end 0) 1)))
7132 ;; Search for the next wiki link and move to the beginning.
7133 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t)
7134 (markdown-code-block-at-point-p)
7135 (< (point) (point-max))))
7136 (if (and (not (eq (point) opoint))
7137 (or (markdown-link-p) (markdown-wiki-link-p)))
7138 ;; Group 1 will move past non-escape character in wiki link regexp.
7139 ;; Go to beginning of group zero for all other link types.
7140 (goto-char (or (match-beginning 1) (match-beginning 0)))
7141 (goto-char opoint)
7142 nil)))
7144 (defun markdown-previous-link ()
7145 "Jump to previous wiki link.
7146 If successful, return point. Otherwise, return nil.
7147 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
7148 (interactive)
7149 (let ((opoint (point)))
7150 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t)
7151 (markdown-code-block-at-point-p)
7152 (> (point) (point-min))))
7153 (if (and (not (eq (point) opoint))
7154 (or (markdown-link-p) (markdown-wiki-link-p)))
7155 (goto-char (or (match-beginning 1) (match-beginning 0)))
7156 (goto-char opoint)
7157 nil)))
7160 ;;; Outline ===================================================================
7162 (defun markdown-move-heading-common (move-fn &optional arg adjust)
7163 "Wrapper for `outline-mode' functions to skip false positives.
7164 MOVE-FN is a function and ARG is its argument. For example,
7165 headings inside preformatted code blocks may match
7166 `outline-regexp' but should not be considered as headings.
7167 When ADJUST is non-nil, adjust the point for interactive calls
7168 to avoid leaving the point at invisible markup. This adjustment
7169 generally should only be done for interactive calls, since other
7170 functions may expect the point to be at the beginning of the
7171 regular expression."
7172 (let ((prev -1) (start (point)))
7173 (if arg (funcall move-fn arg) (funcall move-fn))
7174 (while (and (/= prev (point)) (markdown-code-block-at-point-p))
7175 (setq prev (point))
7176 (if arg (funcall move-fn arg) (funcall move-fn)))
7177 ;; Adjust point for setext headings and invisible text.
7178 (save-match-data
7179 (when (and adjust (thing-at-point-looking-at markdown-regex-header))
7180 (if markdown-hide-markup
7181 ;; Move to beginning of heading text if markup is hidden.
7182 (goto-char (or (match-beginning 1) (match-beginning 5)))
7183 ;; Move to beginning of markup otherwise.
7184 (goto-char (or (match-beginning 1) (match-beginning 4))))))
7185 (if (= (point) start) nil (point))))
7187 (defun markdown-next-visible-heading (arg)
7188 "Move to the next visible heading line of any level.
7189 With argument, repeats or can move backward if negative. ARG is
7190 passed to `outline-next-visible-heading'."
7191 (interactive "p")
7192 (markdown-move-heading-common #'outline-next-visible-heading arg 'adjust))
7194 (defun markdown-previous-visible-heading (arg)
7195 "Move to the previous visible heading line of any level.
7196 With argument, repeats or can move backward if negative. ARG is
7197 passed to `outline-previous-visible-heading'."
7198 (interactive "p")
7199 (markdown-move-heading-common #'outline-previous-visible-heading arg 'adjust))
7201 (defun markdown-next-heading ()
7202 "Move to the next heading line of any level."
7203 (markdown-move-heading-common #'outline-next-heading))
7205 (defun markdown-previous-heading ()
7206 "Move to the previous heading line of any level."
7207 (markdown-move-heading-common #'outline-previous-heading))
7209 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok no-error)
7210 "Move back to the beginning of the previous heading.
7211 Returns t if the point is at a heading, the location if a heading
7212 was found, and nil otherwise.
7213 Only visible heading lines are considered, unless INVISIBLE-OK is
7214 non-nil. Throw an error if there is no previous heading unless
7215 NO-ERROR is non-nil.
7216 Leaves match data intact for `markdown-regex-header'."
7217 (beginning-of-line)
7218 (or (and (markdown-heading-at-point)
7219 (not (markdown-code-block-at-point-p)))
7220 (let (found)
7221 (save-excursion
7222 (while (and (not found)
7223 (re-search-backward markdown-regex-header nil t))
7224 (when (and (or invisible-ok (not (outline-invisible-p)))
7225 (not (markdown-code-block-at-point-p)))
7226 (setq found (point))))
7227 (if (not found)
7228 (unless no-error (user-error "Before first heading"))
7229 (setq found (point))))
7230 (when found (goto-char found)))))
7232 (defun markdown-forward-same-level (arg)
7233 "Move forward to the ARG'th heading at same level as this one.
7234 Stop at the first and last headings of a superior heading."
7235 (interactive "p")
7236 (markdown-back-to-heading-over-code-block)
7237 (markdown-move-heading-common #'outline-forward-same-level arg 'adjust))
7239 (defun markdown-backward-same-level (arg)
7240 "Move backward to the ARG'th heading at same level as this one.
7241 Stop at the first and last headings of a superior heading."
7242 (interactive "p")
7243 (markdown-back-to-heading-over-code-block)
7244 (while (> arg 0)
7245 (let ((point-to-move-to
7246 (save-excursion
7247 (markdown-move-heading-common #'outline-get-last-sibling nil 'adjust))))
7248 (if point-to-move-to
7249 (progn
7250 (goto-char point-to-move-to)
7251 (setq arg (1- arg)))
7252 (user-error "No previous same-level heading")))))
7254 (defun markdown-up-heading (arg)
7255 "Move to the visible heading line of which the present line is a subheading.
7256 With argument, move up ARG levels."
7257 (interactive "p")
7258 (and (called-interactively-p 'any)
7259 (not (eq last-command 'markdown-up-heading)) (push-mark))
7260 (markdown-move-heading-common #'outline-up-heading arg 'adjust))
7262 (defun markdown-back-to-heading (&optional invisible-ok)
7263 "Move to previous heading line, or beg of this line if it's a heading.
7264 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
7265 (markdown-move-heading-common #'outline-back-to-heading invisible-ok))
7267 (defalias 'markdown-end-of-heading 'outline-end-of-heading)
7269 (defun markdown-on-heading-p ()
7270 "Return non-nil if point is on a heading line."
7271 (get-text-property (point-at-bol) 'markdown-heading))
7273 (defun markdown-end-of-subtree (&optional invisible-OK)
7274 "Move to the end of the current subtree.
7275 Only visible heading lines are considered, unless INVISIBLE-OK is
7276 non-nil.
7277 Derived from `org-end-of-subtree'."
7278 (markdown-back-to-heading invisible-OK)
7279 (let ((first t)
7280 (level (markdown-outline-level)))
7281 (while (and (not (eobp))
7282 (or first (> (markdown-outline-level) level)))
7283 (setq first nil)
7284 (markdown-next-heading))
7285 (if (memq (preceding-char) '(?\n ?\^M))
7286 (progn
7287 ;; Go to end of line before heading
7288 (forward-char -1)
7289 (if (memq (preceding-char) '(?\n ?\^M))
7290 ;; leave blank line before heading
7291 (forward-char -1)))))
7292 (point))
7294 (defun markdown-outline-fix-visibility ()
7295 "Hide any false positive headings that should not be shown.
7296 For example, headings inside preformatted code blocks may match
7297 `outline-regexp' but should not be shown as headings when cycling.
7298 Also, the ending --- line in metadata blocks appears to be a
7299 setext header, but should not be folded."
7300 (save-excursion
7301 (goto-char (point-min))
7302 ;; Unhide any false positives in metadata blocks
7303 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin)
7304 (let ((body (progn (forward-line)
7305 (markdown-text-property-at-point
7306 'markdown-yaml-metadata-section))))
7307 (when body
7308 (let ((end (progn (goto-char (cl-second body))
7309 (markdown-text-property-at-point
7310 'markdown-yaml-metadata-end))))
7311 (outline-flag-region (point-min) (1+ (cl-second end)) nil)))))
7312 ;; Hide any false positives in code blocks
7313 (unless (outline-on-heading-p)
7314 (outline-next-visible-heading 1))
7315 (while (< (point) (point-max))
7316 (when (markdown-code-block-at-point-p)
7317 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t))
7318 (outline-next-visible-heading 1))))
7320 (defvar markdown-cycle-global-status 1)
7321 (defvar markdown-cycle-subtree-status nil)
7323 (defun markdown-next-preface ()
7324 (let (finish)
7325 (while (and (not finish) (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
7326 nil 'move))
7327 (unless (markdown-code-block-at-point-p)
7328 (goto-char (match-beginning 0))
7329 (setq finish t))))
7330 (when (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
7331 (forward-char -1)))
7333 (defun markdown-show-entry ()
7334 (save-excursion
7335 (outline-back-to-heading t)
7336 (outline-flag-region (1- (point))
7337 (progn
7338 (markdown-next-preface)
7339 (if (= 1 (- (point-max) (point)))
7340 (point-max)
7341 (point)))
7342 nil)))
7344 ;; This function was originally derived from `org-cycle' from org.el.
7345 (defun markdown-cycle (&optional arg)
7346 "Visibility cycling for Markdown mode.
7347 If ARG is t, perform global visibility cycling. If the point is
7348 at an atx-style header, cycle visibility of the corresponding
7349 subtree. Otherwise, indent the current line or insert a tab,
7350 as appropriate, by calling `indent-for-tab-command'."
7351 (interactive "P")
7352 (cond
7353 ((eq arg t) ;; Global cycling
7354 (cond
7355 ((and (eq last-command this-command)
7356 (eq markdown-cycle-global-status 2))
7357 ;; Move from overview to contents
7358 (markdown-hide-sublevels 1)
7359 (message "CONTENTS")
7360 (setq markdown-cycle-global-status 3)
7361 (markdown-outline-fix-visibility))
7363 ((and (eq last-command this-command)
7364 (eq markdown-cycle-global-status 3))
7365 ;; Move from contents to all
7366 (markdown-show-all)
7367 (message "SHOW ALL")
7368 (setq markdown-cycle-global-status 1))
7371 ;; Defaults to overview
7372 (markdown-hide-body)
7373 (message "OVERVIEW")
7374 (setq markdown-cycle-global-status 2)
7375 (markdown-outline-fix-visibility))))
7377 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
7378 ;; At a heading: rotate between three different views
7379 (markdown-back-to-heading)
7380 (let ((goal-column 0) eoh eol eos)
7381 ;; Determine boundaries
7382 (save-excursion
7383 (markdown-back-to-heading)
7384 (save-excursion
7385 (beginning-of-line 2)
7386 (while (and (not (eobp)) ;; this is like `next-line'
7387 (get-char-property (1- (point)) 'invisible))
7388 (beginning-of-line 2)) (setq eol (point)))
7389 (markdown-end-of-heading) (setq eoh (point))
7390 (markdown-end-of-subtree t)
7391 (skip-chars-forward " \t\n")
7392 (beginning-of-line 1) ; in case this is an item
7393 (setq eos (1- (point))))
7394 ;; Find out what to do next and set `this-command'
7395 (cond
7396 ((= eos eoh)
7397 ;; Nothing is hidden behind this heading
7398 (message "EMPTY ENTRY")
7399 (setq markdown-cycle-subtree-status nil))
7400 ((>= eol eos)
7401 ;; Entire subtree is hidden in one line: open it
7402 (markdown-show-entry)
7403 (markdown-show-children)
7404 (message "CHILDREN")
7405 (setq markdown-cycle-subtree-status 'children))
7406 ((and (eq last-command this-command)
7407 (eq markdown-cycle-subtree-status 'children))
7408 ;; We just showed the children, now show everything.
7409 (markdown-show-subtree)
7410 (message "SUBTREE")
7411 (setq markdown-cycle-subtree-status 'subtree))
7413 ;; Default action: hide the subtree.
7414 (markdown-hide-subtree)
7415 (message "FOLDED")
7416 (setq markdown-cycle-subtree-status 'folded)))))
7419 (indent-for-tab-command))))
7421 (defun markdown-shifttab ()
7422 "Handle S-TAB keybinding based on context.
7423 When in a table, move backward one cell.
7424 Otherwise, cycle global heading visibility by calling
7425 `markdown-cycle' with argument t."
7426 (interactive)
7427 (cond ((markdown-table-at-point-p)
7428 (call-interactively #'markdown-table-backward-cell))
7429 (t (markdown-cycle t))))
7431 (defun markdown-outline-level ()
7432 "Return the depth to which a statement is nested in the outline."
7433 (cond
7434 ((and (match-beginning 0)
7435 (markdown-code-block-at-pos (match-beginning 0)))
7436 7) ;; Only 6 header levels are defined.
7437 ((match-end 2) 1)
7438 ((match-end 3) 2)
7439 ((match-end 4)
7440 (length (markdown-trim-whitespace (match-string-no-properties 4))))))
7442 (defun markdown-promote-subtree (&optional arg)
7443 "Promote the current subtree of ATX headings.
7444 Note that Markdown does not support heading levels higher than
7445 six and therefore level-six headings will not be promoted
7446 further. If ARG is non-nil promote the heading, otherwise
7447 demote."
7448 (interactive "*P")
7449 (save-excursion
7450 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
7451 (re-search-backward markdown-regex-header-atx nil t))
7452 (not (markdown-code-block-at-point-p)))
7453 (let ((level (length (match-string 1)))
7454 (promote-or-demote (if arg 1 -1))
7455 (remove 't))
7456 (markdown-cycle-atx promote-or-demote remove)
7457 (catch 'end-of-subtree
7458 (while (and (markdown-next-heading)
7459 (looking-at markdown-regex-header-atx))
7460 ;; Exit if this not a higher level heading; promote otherwise.
7461 (if (and (looking-at markdown-regex-header-atx)
7462 (<= (length (match-string-no-properties 1)) level))
7463 (throw 'end-of-subtree nil)
7464 (markdown-cycle-atx promote-or-demote remove))))))))
7466 (defun markdown-demote-subtree ()
7467 "Demote the current subtree of ATX headings."
7468 (interactive)
7469 (markdown-promote-subtree t))
7471 (defun markdown-move-subtree-up ()
7472 "Move the current subtree of ATX headings up."
7473 (interactive)
7474 (outline-move-subtree-up 1))
7476 (defun markdown-move-subtree-down ()
7477 "Move the current subtree of ATX headings down."
7478 (interactive)
7479 (outline-move-subtree-down 1))
7481 (defun markdown-outline-next ()
7482 "Move to next list item, when in a list, or next visible heading."
7483 (interactive)
7484 (let ((bounds (markdown-next-list-item-bounds)))
7485 (if bounds
7486 (goto-char (nth 0 bounds))
7487 (markdown-next-visible-heading 1))))
7489 (defun markdown-outline-previous ()
7490 "Move to previous list item, when in a list, or previous visible heading."
7491 (interactive)
7492 (let ((bounds (markdown-prev-list-item-bounds)))
7493 (if bounds
7494 (goto-char (nth 0 bounds))
7495 (markdown-previous-visible-heading 1))))
7497 (defun markdown-outline-next-same-level ()
7498 "Move to next list item or heading of same level."
7499 (interactive)
7500 (let ((bounds (markdown-cur-list-item-bounds)))
7501 (if bounds
7502 (markdown-next-list-item (nth 3 bounds))
7503 (markdown-forward-same-level 1))))
7505 (defun markdown-outline-previous-same-level ()
7506 "Move to previous list item or heading of same level."
7507 (interactive)
7508 (let ((bounds (markdown-cur-list-item-bounds)))
7509 (if bounds
7510 (markdown-prev-list-item (nth 3 bounds))
7511 (markdown-backward-same-level 1))))
7513 (defun markdown-outline-up ()
7514 "Move to previous list item, when in a list, or next heading."
7515 (interactive)
7516 (unless (markdown-up-list)
7517 (markdown-up-heading 1)))
7520 ;;; Marking and Narrowing =====================================================
7522 (defun markdown-mark-paragraph ()
7523 "Put mark at end of this block, point at beginning.
7524 The block marked is the one that contains point or follows point.
7526 Interactively, if this command is repeated or (in Transient Mark
7527 mode) if the mark is active, it marks the next block after the
7528 ones already marked."
7529 (interactive)
7530 (if (or (and (eq last-command this-command) (mark t))
7531 (and transient-mark-mode mark-active))
7532 (set-mark
7533 (save-excursion
7534 (goto-char (mark))
7535 (markdown-forward-paragraph)
7536 (point)))
7537 (let ((beginning-of-defun-function 'markdown-backward-paragraph)
7538 (end-of-defun-function 'markdown-forward-paragraph))
7539 (mark-defun))))
7541 (defun markdown-mark-block ()
7542 "Put mark at end of this block, point at beginning.
7543 The block marked is the one that contains point or follows point.
7545 Interactively, if this command is repeated or (in Transient Mark
7546 mode) if the mark is active, it marks the next block after the
7547 ones already marked."
7548 (interactive)
7549 (if (or (and (eq last-command this-command) (mark t))
7550 (and transient-mark-mode mark-active))
7551 (set-mark
7552 (save-excursion
7553 (goto-char (mark))
7554 (markdown-forward-block)
7555 (point)))
7556 (let ((beginning-of-defun-function 'markdown-backward-block)
7557 (end-of-defun-function 'markdown-forward-block))
7558 (mark-defun))))
7560 (defun markdown-narrow-to-block ()
7561 "Make text outside current block invisible.
7562 The current block is the one that contains point or follows point."
7563 (interactive)
7564 (let ((beginning-of-defun-function 'markdown-backward-block)
7565 (end-of-defun-function 'markdown-forward-block))
7566 (narrow-to-defun)))
7568 (defun markdown-mark-text-block ()
7569 "Put mark at end of this plain text block, point at beginning.
7570 The block marked is the one that contains point or follows point.
7572 Interactively, if this command is repeated or (in Transient Mark
7573 mode) if the mark is active, it marks the next block after the
7574 ones already marked."
7575 (interactive)
7576 (if (or (and (eq last-command this-command) (mark t))
7577 (and transient-mark-mode mark-active))
7578 (set-mark
7579 (save-excursion
7580 (goto-char (mark))
7581 (markdown-end-of-text-block)
7582 (point)))
7583 (let ((beginning-of-defun-function 'markdown-beginning-of-text-block)
7584 (end-of-defun-function 'markdown-end-of-text-block))
7585 (mark-defun))))
7587 (defun markdown-mark-page ()
7588 "Put mark at end of this top level section, point at beginning.
7589 The top level section marked is the one that contains point or
7590 follows point.
7592 Interactively, if this command is repeated or (in Transient Mark
7593 mode) if the mark is active, it marks the next page after the
7594 ones already marked."
7595 (interactive)
7596 (if (or (and (eq last-command this-command) (mark t))
7597 (and transient-mark-mode mark-active))
7598 (set-mark
7599 (save-excursion
7600 (goto-char (mark))
7601 (markdown-forward-page)
7602 (point)))
7603 (let ((beginning-of-defun-function 'markdown-backward-page)
7604 (end-of-defun-function 'markdown-forward-page))
7605 (mark-defun))))
7607 (defun markdown-narrow-to-page ()
7608 "Make text outside current top level section invisible.
7609 The current section is the one that contains point or follows point."
7610 (interactive)
7611 (let ((beginning-of-defun-function 'markdown-backward-page)
7612 (end-of-defun-function 'markdown-forward-page))
7613 (narrow-to-defun)))
7615 (defun markdown-mark-subtree ()
7616 "Mark the current subtree.
7617 This puts point at the start of the current subtree, and mark at the end."
7618 (interactive)
7619 (let ((beg))
7620 (if (markdown-heading-at-point)
7621 (beginning-of-line)
7622 (markdown-previous-visible-heading 1))
7623 (setq beg (point))
7624 (markdown-end-of-subtree)
7625 (push-mark (point) nil t)
7626 (goto-char beg)))
7628 (defun markdown-narrow-to-subtree ()
7629 "Narrow buffer to the current subtree."
7630 (interactive)
7631 (save-excursion
7632 (save-match-data
7633 (narrow-to-region
7634 (progn (markdown-back-to-heading-over-code-block t) (point))
7635 (progn (markdown-end-of-subtree)
7636 (if (and (markdown-heading-at-point) (not (eobp)))
7637 (backward-char 1))
7638 (point))))))
7641 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
7643 (defun markdown-move-up ()
7644 "Move thing at point up.
7645 When in a list item, call `markdown-move-list-item-up'.
7646 When in a table, call `markdown-table-move-row-up'.
7647 Otherwise, move the current heading subtree up with
7648 `markdown-move-subtree-up'."
7649 (interactive)
7650 (cond
7651 ((markdown-list-item-at-point-p)
7652 (call-interactively #'markdown-move-list-item-up))
7653 ((markdown-table-at-point-p)
7654 (call-interactively #'markdown-table-move-row-up))
7656 (call-interactively #'markdown-move-subtree-up))))
7658 (defun markdown-move-down ()
7659 "Move thing at point down.
7660 When in a list item, call `markdown-move-list-item-down'.
7661 Otherwise, move the current heading subtree up with
7662 `markdown-move-subtree-down'."
7663 (interactive)
7664 (cond
7665 ((markdown-list-item-at-point-p)
7666 (call-interactively #'markdown-move-list-item-down))
7667 ((markdown-table-at-point-p)
7668 (call-interactively #'markdown-table-move-row-down))
7670 (call-interactively #'markdown-move-subtree-down))))
7672 (defun markdown-promote ()
7673 "Promote or move element at point to the left.
7674 Depending on the context, this function will promote a heading or
7675 list item at the point, move a table column to the left, or cycle
7676 markup."
7677 (interactive)
7678 (let (bounds)
7679 (cond
7680 ;; Promote atx heading subtree
7681 ((thing-at-point-looking-at markdown-regex-header-atx)
7682 (markdown-promote-subtree))
7683 ;; Promote setext heading
7684 ((thing-at-point-looking-at markdown-regex-header-setext)
7685 (markdown-cycle-setext -1))
7686 ;; Promote horizonal rule
7687 ((thing-at-point-looking-at markdown-regex-hr)
7688 (markdown-cycle-hr -1))
7689 ;; Promote list item
7690 ((setq bounds (markdown-cur-list-item-bounds))
7691 (markdown-promote-list-item bounds))
7692 ;; Move table column to the left
7693 ((markdown-table-at-point-p)
7694 (call-interactively #'markdown-table-move-column-left))
7695 ;; Promote bold
7696 ((thing-at-point-looking-at markdown-regex-bold)
7697 (markdown-cycle-bold))
7698 ;; Promote italic
7699 ((thing-at-point-looking-at markdown-regex-italic)
7700 (markdown-cycle-italic))
7702 (user-error "Nothing to promote at point")))))
7704 (defun markdown-demote ()
7705 "Demote or move element at point to the right.
7706 Depending on the context, this function will demote a heading or
7707 list item at the point, move a table column to the right, or cycle
7708 or remove markup."
7709 (interactive)
7710 (let (bounds)
7711 (cond
7712 ;; Demote atx heading subtree
7713 ((thing-at-point-looking-at markdown-regex-header-atx)
7714 (markdown-demote-subtree))
7715 ;; Demote setext heading
7716 ((thing-at-point-looking-at markdown-regex-header-setext)
7717 (markdown-cycle-setext 1))
7718 ;; Demote horizonal rule
7719 ((thing-at-point-looking-at markdown-regex-hr)
7720 (markdown-cycle-hr 1))
7721 ;; Demote list item
7722 ((setq bounds (markdown-cur-list-item-bounds))
7723 (markdown-demote-list-item bounds))
7724 ;; Move table column to the right
7725 ((markdown-table-at-point-p)
7726 (call-interactively #'markdown-table-move-column-right))
7727 ;; Demote bold
7728 ((thing-at-point-looking-at markdown-regex-bold)
7729 (markdown-cycle-bold))
7730 ;; Demote italic
7731 ((thing-at-point-looking-at markdown-regex-italic)
7732 (markdown-cycle-italic))
7734 (user-error "Nothing to demote at point")))))
7737 ;;; Commands ==================================================================
7739 (defun markdown (&optional output-buffer-name)
7740 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
7741 The output buffer name defaults to `markdown-output-buffer-name'.
7742 Return the name of the output buffer used."
7743 (interactive)
7744 (save-window-excursion
7745 (let ((begin-region)
7746 (end-region))
7747 (if (markdown-use-region-p)
7748 (setq begin-region (region-beginning)
7749 end-region (region-end))
7750 (setq begin-region (point-min)
7751 end-region (point-max)))
7753 (unless output-buffer-name
7754 (setq output-buffer-name markdown-output-buffer-name))
7755 (cond
7756 ;; Handle case when `markdown-command' does not read from stdin
7757 ((and (stringp markdown-command) markdown-command-needs-filename)
7758 (if (not buffer-file-name)
7759 (user-error "Must be visiting a file")
7760 (shell-command (concat markdown-command " "
7761 (shell-quote-argument buffer-file-name))
7762 output-buffer-name)))
7763 ;; Pass region to `markdown-command' via stdin
7765 (let ((buf (get-buffer-create output-buffer-name)))
7766 (with-current-buffer buf
7767 (setq buffer-read-only nil)
7768 (erase-buffer))
7769 (if (stringp markdown-command)
7770 (call-process-region begin-region end-region
7771 shell-file-name nil buf nil
7772 shell-command-switch markdown-command)
7773 (funcall markdown-command begin-region end-region buf))))))
7774 output-buffer-name))
7776 (defun markdown-standalone (&optional output-buffer-name)
7777 "Special function to provide standalone HTML output.
7778 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
7779 (interactive)
7780 (setq output-buffer-name (markdown output-buffer-name))
7781 (with-current-buffer output-buffer-name
7782 (set-buffer output-buffer-name)
7783 (unless (markdown-output-standalone-p)
7784 (markdown-add-xhtml-header-and-footer output-buffer-name))
7785 (goto-char (point-min))
7786 (html-mode))
7787 output-buffer-name)
7789 (defun markdown-other-window (&optional output-buffer-name)
7790 "Run `markdown-command' on current buffer and display in other window.
7791 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7792 that name."
7793 (interactive)
7794 (markdown-display-buffer-other-window
7795 (markdown-standalone output-buffer-name)))
7797 (defun markdown-output-standalone-p ()
7798 "Determine whether `markdown-command' output is standalone XHTML.
7799 Standalone XHTML output is identified by an occurrence of
7800 `markdown-xhtml-standalone-regexp' in the first five lines of output."
7801 (save-excursion
7802 (goto-char (point-min))
7803 (save-match-data
7804 (re-search-forward
7805 markdown-xhtml-standalone-regexp
7806 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
7807 t))))
7809 (defun markdown-stylesheet-link-string (stylesheet-path)
7810 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
7811 stylesheet-path
7812 "\" />"))
7814 (defun markdown-add-xhtml-header-and-footer (title)
7815 "Wrap XHTML header and footer with given TITLE around current buffer."
7816 (goto-char (point-min))
7817 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
7818 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
7819 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
7820 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
7821 "<head>\n<title>")
7822 (insert title)
7823 (insert "</title>\n")
7824 (when (> (length markdown-content-type) 0)
7825 (insert
7826 (format
7827 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
7828 markdown-content-type
7829 (or (and markdown-coding-system
7830 (fboundp 'coding-system-get)
7831 (coding-system-get markdown-coding-system
7832 'mime-charset))
7833 (and (fboundp 'coding-system-get)
7834 (coding-system-get buffer-file-coding-system
7835 'mime-charset))
7836 "iso-8859-1"))))
7837 (if (> (length markdown-css-paths) 0)
7838 (insert (mapconcat #'markdown-stylesheet-link-string
7839 markdown-css-paths "\n")))
7840 (when (> (length markdown-xhtml-header-content) 0)
7841 (insert markdown-xhtml-header-content))
7842 (insert "\n</head>\n\n"
7843 "<body>\n\n")
7844 (goto-char (point-max))
7845 (insert "\n"
7846 "</body>\n"
7847 "</html>\n"))
7849 (defun markdown-preview (&optional output-buffer-name)
7850 "Run `markdown-command' on the current buffer and view output in browser.
7851 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7852 that name."
7853 (interactive)
7854 (browse-url-of-buffer
7855 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
7857 (defun markdown-export-file-name (&optional extension)
7858 "Attempt to generate a filename for Markdown output.
7859 The file extension will be EXTENSION if given, or .html by default.
7860 If the current buffer is visiting a file, we construct a new
7861 output filename based on that filename. Otherwise, return nil."
7862 (when (buffer-file-name)
7863 (unless extension
7864 (setq extension ".html"))
7865 (let ((candidate
7866 (concat
7867 (cond
7868 ((buffer-file-name)
7869 (file-name-sans-extension (buffer-file-name)))
7870 (t (buffer-name)))
7871 extension)))
7872 (cond
7873 ((equal candidate (buffer-file-name))
7874 (concat candidate extension))
7876 candidate)))))
7878 (defun markdown-export (&optional output-file)
7879 "Run Markdown on the current buffer, save to file, and return the filename.
7880 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
7881 generated by `markdown-export-file-name', which will be constructed using the
7882 current filename, but with the extension removed and replaced with .html."
7883 (interactive)
7884 (unless output-file
7885 (setq output-file (markdown-export-file-name ".html")))
7886 (when output-file
7887 (let* ((init-buf (current-buffer))
7888 (init-point (point))
7889 (init-buf-string (buffer-string))
7890 (output-buffer (find-file-noselect output-file))
7891 (output-buffer-name (buffer-name output-buffer)))
7892 (run-hooks 'markdown-before-export-hook)
7893 (markdown-standalone output-buffer-name)
7894 (with-current-buffer output-buffer
7895 (run-hooks 'markdown-after-export-hook)
7896 (save-buffer)
7897 (when markdown-export-kill-buffer (kill-buffer)))
7898 ;; if modified, restore initial buffer
7899 (when (buffer-modified-p init-buf)
7900 (erase-buffer)
7901 (insert init-buf-string)
7902 (save-buffer)
7903 (goto-char init-point))
7904 output-file)))
7906 (defun markdown-export-and-preview ()
7907 "Export to XHTML using `markdown-export' and browse the resulting file."
7908 (interactive)
7909 (browse-url-of-file (markdown-export)))
7911 (defvar markdown-live-preview-buffer nil
7912 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
7913 (make-variable-buffer-local 'markdown-live-preview-buffer)
7915 (defvar markdown-live-preview-source-buffer nil
7916 "Source buffer from which current buffer was generated.
7917 This is the inverse of `markdown-live-preview-buffer'.")
7918 (make-variable-buffer-local 'markdown-live-preview-source-buffer)
7920 (defvar markdown-live-preview-currently-exporting nil)
7922 (defun markdown-live-preview-get-filename ()
7923 "Standardize the filename exported by `markdown-live-preview-export'."
7924 (markdown-export-file-name ".html"))
7926 (defun markdown-live-preview-window-eww (file)
7927 "Preview FILE with eww.
7928 To be used with `markdown-live-preview-window-function'."
7929 (if (require 'eww nil t)
7930 (progn
7931 (eww-open-file file)
7932 (get-buffer "*eww*"))
7933 (error "EWW is not present or not loaded on this version of Emacs")))
7935 (defun markdown-visual-lines-between-points (beg end)
7936 (save-excursion
7937 (goto-char beg)
7938 (cl-loop with count = 0
7939 while (progn (end-of-visual-line)
7940 (and (< (point) end) (line-move-visual 1 t)))
7941 do (cl-incf count)
7942 finally return count)))
7944 (defun markdown-live-preview-window-serialize (buf)
7945 "Get window point and scroll data for all windows displaying BUF."
7946 (when (buffer-live-p buf)
7947 (with-current-buffer buf
7948 (mapcar
7949 (lambda (win)
7950 (with-selected-window win
7951 (let* ((start (window-start))
7952 (pt (window-point))
7953 (pt-or-sym (cond ((= pt (point-min)) 'min)
7954 ((= pt (point-max)) 'max)
7955 (t pt)))
7956 (diff (markdown-visual-lines-between-points
7957 start pt)))
7958 (list win pt-or-sym diff))))
7959 (get-buffer-window-list buf)))))
7961 (defun markdown-get-point-back-lines (pt num-lines)
7962 (save-excursion
7963 (goto-char pt)
7964 (line-move-visual (- num-lines) t)
7965 ;; in testing, can occasionally overshoot the number of lines to traverse
7966 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
7967 (when (> actual-num-lines num-lines)
7968 (line-move-visual (- actual-num-lines num-lines) t)))
7969 (point)))
7971 (defun markdown-live-preview-window-deserialize (window-posns)
7972 "Apply window point and scroll data from WINDOW-POSNS.
7973 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
7974 (cl-destructuring-bind (win pt-or-sym diff) window-posns
7975 (when (window-live-p win)
7976 (with-current-buffer markdown-live-preview-buffer
7977 (set-window-buffer win (current-buffer))
7978 (cl-destructuring-bind (actual-pt actual-diff)
7979 (cl-case pt-or-sym
7980 (min (list (point-min) 0))
7981 (max (list (point-max) diff))
7982 (t (list pt-or-sym diff)))
7983 (set-window-start
7984 win (markdown-get-point-back-lines actual-pt actual-diff))
7985 (set-window-point win actual-pt))))))
7987 (defun markdown-live-preview-export ()
7988 "Export to XHTML using `markdown-export'.
7989 Browse the resulting file within Emacs using
7990 `markdown-live-preview-window-function' Return the buffer
7991 displaying the rendered output."
7992 (interactive)
7993 (let ((filename (markdown-live-preview-get-filename)))
7994 (when filename
7995 (let* ((markdown-live-preview-currently-exporting t)
7996 (cur-buf (current-buffer))
7997 (export-file (markdown-export filename))
7998 ;; get positions in all windows currently displaying output buffer
7999 (window-data
8000 (markdown-live-preview-window-serialize
8001 markdown-live-preview-buffer)))
8002 (save-window-excursion
8003 (let ((output-buffer
8004 (funcall markdown-live-preview-window-function export-file)))
8005 (with-current-buffer output-buffer
8006 (setq markdown-live-preview-source-buffer cur-buf)
8007 (add-hook 'kill-buffer-hook
8008 #'markdown-live-preview-remove-on-kill t t))
8009 (with-current-buffer cur-buf
8010 (setq markdown-live-preview-buffer output-buffer))))
8011 (with-current-buffer cur-buf
8012 ;; reset all windows displaying output buffer to where they were,
8013 ;; now with the new output
8014 (mapc #'markdown-live-preview-window-deserialize window-data)
8015 ;; delete html editing buffer
8016 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
8017 (when (and export-file (file-exists-p export-file)
8018 (eq markdown-live-preview-delete-export
8019 'delete-on-export))
8020 (delete-file export-file))
8021 markdown-live-preview-buffer)))))
8023 (defun markdown-live-preview-remove ()
8024 (when (buffer-live-p markdown-live-preview-buffer)
8025 (kill-buffer markdown-live-preview-buffer))
8026 (setq markdown-live-preview-buffer nil)
8027 ;; if set to 'delete-on-export, the output has already been deleted
8028 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
8029 (let ((outfile-name (markdown-live-preview-get-filename)))
8030 (when (and outfile-name (file-exists-p outfile-name))
8031 (delete-file outfile-name)))))
8033 (defun markdown-get-other-window ()
8034 "Find another window to display preview or output content."
8035 (cond
8036 ((memq markdown-split-window-direction '(vertical below))
8037 (or (window-in-direction 'below) (split-window-vertically)))
8038 ((memq markdown-split-window-direction '(horizontal right))
8039 (or (window-in-direction 'right) (split-window-horizontally)))
8040 (t (split-window-sensibly (get-buffer-window)))))
8042 (defun markdown-display-buffer-other-window (buf)
8043 "Display preview or output buffer BUF in another window."
8044 (let ((cur-buf (current-buffer))
8045 (window (markdown-get-other-window)))
8046 (set-window-buffer window buf)
8047 (set-buffer cur-buf)))
8049 (defun markdown-live-preview-if-markdown ()
8050 (when (and (derived-mode-p 'markdown-mode)
8051 markdown-live-preview-mode)
8052 (unless markdown-live-preview-currently-exporting
8053 (if (buffer-live-p markdown-live-preview-buffer)
8054 (markdown-live-preview-export)
8055 (markdown-display-buffer-other-window
8056 (markdown-live-preview-export))))))
8058 (defun markdown-live-preview-remove-on-kill ()
8059 (cond ((and (derived-mode-p 'markdown-mode)
8060 markdown-live-preview-mode)
8061 (markdown-live-preview-remove))
8062 (markdown-live-preview-source-buffer
8063 (with-current-buffer markdown-live-preview-source-buffer
8064 (setq markdown-live-preview-buffer nil))
8065 (setq markdown-live-preview-source-buffer nil))))
8067 (defun markdown-live-preview-switch-to-output ()
8068 "Switch to output buffer."
8069 (interactive)
8070 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
8071 output buffer in another window."
8072 (if markdown-live-preview-mode
8073 (markdown-display-buffer-other-window (markdown-live-preview-export)))
8074 (markdown-live-preview-mode))
8076 (defun markdown-live-preview-re-export ()
8077 "Re export source buffer."
8078 (interactive)
8079 "If the current buffer is a buffer displaying the exported version of a
8080 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
8081 update this buffer's contents."
8082 (when markdown-live-preview-source-buffer
8083 (with-current-buffer markdown-live-preview-source-buffer
8084 (markdown-live-preview-export))))
8086 (defun markdown-open ()
8087 "Open file for the current buffer with `markdown-open-command'."
8088 (interactive)
8089 (unless markdown-open-command
8090 (user-error "Variable `markdown-open-command' must be set"))
8091 (if (stringp markdown-open-command)
8092 (if (not buffer-file-name)
8093 (user-error "Must be visiting a file")
8094 (save-buffer)
8095 (call-process markdown-open-command nil 0 nil buffer-file-name))
8096 (funcall markdown-open-command))
8097 nil)
8099 (defun markdown-kill-ring-save ()
8100 "Run Markdown on file and store output in the kill ring."
8101 (interactive)
8102 (save-window-excursion
8103 (markdown)
8104 (with-current-buffer markdown-output-buffer-name
8105 (kill-ring-save (point-min) (point-max)))))
8108 ;;; Links =====================================================================
8110 (defun markdown-link-p ()
8111 "Return non-nil when `point' is at a non-wiki link.
8112 See `markdown-wiki-link-p' for more information."
8113 (let ((case-fold-search nil))
8114 (and (not (markdown-wiki-link-p))
8115 (not (markdown-code-block-at-point-p))
8116 (or (thing-at-point-looking-at markdown-regex-link-inline)
8117 (thing-at-point-looking-at markdown-regex-link-reference)
8118 (thing-at-point-looking-at markdown-regex-uri)
8119 (thing-at-point-looking-at markdown-regex-angle-uri)))))
8121 (make-obsolete 'markdown-link-link 'markdown-link-url "v2.3")
8123 (defun markdown-link-at-pos (pos)
8124 "Return properties of link or image at position POS.
8125 Value is a list of elements describing the link:
8126 0. beginning position
8127 1. end position
8128 2. link text
8129 3. URL
8130 4. reference label
8131 5. title text
8132 6. bang (nil or \"!\")"
8133 (save-excursion
8134 (goto-char pos)
8135 (let (begin end text url reference title bang)
8136 (cond
8137 ;; Inline or reference image or link at point.
8138 ((or (thing-at-point-looking-at markdown-regex-link-inline)
8139 (thing-at-point-looking-at markdown-regex-link-reference))
8140 (setq bang (match-string-no-properties 1)
8141 begin (match-beginning 0)
8142 end (match-end 0)
8143 text (match-string-no-properties 3))
8144 (if (char-equal (char-after (match-beginning 5)) ?\[)
8145 ;; Reference link
8146 (setq reference (match-string-no-properties 6))
8147 ;; Inline link
8148 (setq url (match-string-no-properties 6))
8149 (when (match-end 7)
8150 (setq title (substring (match-string-no-properties 7) 1 -1)))))
8151 ;; Angle bracket URI at point.
8152 ((thing-at-point-looking-at markdown-regex-angle-uri)
8153 (setq begin (match-beginning 0)
8154 end (match-end 0)
8155 url (match-string-no-properties 2)))
8156 ;; Plain URI at point.
8157 ((thing-at-point-looking-at markdown-regex-uri)
8158 (setq begin (match-beginning 0)
8159 end (match-end 0)
8160 url (match-string-no-properties 1))))
8161 (list begin end text url reference title bang))))
8163 (defun markdown-link-url ()
8164 "Return the URL part of the regular (non-wiki) link at point.
8165 Works with both inline and reference style links, and with images.
8166 If point is not at a link or the link reference is not defined
8167 returns nil."
8168 (let* ((values (markdown-link-at-pos (point)))
8169 (text (nth 2 values))
8170 (url (nth 3 values))
8171 (ref (nth 4 values)))
8172 (or url (and ref (car (markdown-reference-definition
8173 (downcase (if (string= ref "") text ref))))))))
8175 (defun markdown-follow-link-at-point ()
8176 "Open the current non-wiki link.
8177 If the link is a complete URL, open in browser with `browse-url'.
8178 Otherwise, open with `find-file' after stripping anchor and/or query string.
8179 Translate filenames using `markdown-filename-translate-function'."
8180 (interactive)
8181 (if (markdown-link-p)
8182 (let* ((url (markdown-link-url))
8183 (struct (url-generic-parse-url url))
8184 (full (url-fullness struct))
8185 (file url))
8186 ;; Parse URL, determine fullness, strip query string
8187 (if (fboundp 'url-path-and-query)
8188 (setq file (car (url-path-and-query struct)))
8189 (when (and (setq file (url-filename struct))
8190 (string-match "\\?" file))
8191 (setq file (substring file 0 (match-beginning 0)))))
8192 ;; Open full URLs in browser, files in Emacs
8193 (if full
8194 (browse-url url)
8195 (when (and file (> (length file) 0))
8196 (find-file (funcall markdown-translate-filename-function file)))))
8197 (user-error "Point is not at a Markdown link or URL")))
8199 (defun markdown-fontify-inline-links (last)
8200 "Add text properties to next inline link from point to LAST."
8201 (when (markdown-match-generic-links last nil)
8202 (let* ((link-start (match-beginning 3))
8203 (link-end (match-end 3))
8204 (url-start (match-beginning 6))
8205 (url-end (match-end 6))
8206 (url (match-string-no-properties 6))
8207 (title-start (match-beginning 7))
8208 (title-end (match-end 7))
8209 (title (match-string-no-properties 7))
8210 ;; Markup part
8211 (mp (list 'face 'markdown-markup-face
8212 'invisible 'markdown-markup
8213 'rear-nonsticky t
8214 'font-lock-multiline t))
8215 ;; Link part
8216 (lp (list 'keymap markdown-mode-mouse-map
8217 'face markdown-link-face
8218 'mouse-face 'markdown-highlight-face
8219 'font-lock-multiline t
8220 'help-echo (if title (concat title "\n" url) url)))
8221 ;; URL part
8222 (up (list 'keymap markdown-mode-mouse-map
8223 'face 'markdown-url-face
8224 'invisible 'markdown-markup
8225 'mouse-face 'markdown-highlight-face
8226 'font-lock-multiline t))
8227 ;; URL composition character
8228 (url-char (markdown--first-displayable markdown-url-compose-char))
8229 ;; Title part
8230 (tp (list 'face 'markdown-link-title-face
8231 'invisible 'markdown-markup
8232 'font-lock-multiline t)))
8233 (dolist (g '(1 2 4 5 8))
8234 (when (match-end g)
8235 (add-text-properties (match-beginning g) (match-end g) mp)))
8236 (when link-start (add-text-properties link-start link-end lp))
8237 (when url-start (add-text-properties url-start url-end up))
8238 (when title-start (add-text-properties url-end title-end tp))
8239 (when (and markdown-hide-urls url-start)
8240 (compose-region url-start (or title-end url-end) url-char))
8241 t)))
8243 (defun markdown-fontify-reference-links (last)
8244 "Add text properties to next reference link from point to LAST."
8245 (when (markdown-match-generic-links last t)
8246 (let* ((link-start (match-beginning 3))
8247 (link-end (match-end 3))
8248 (ref-start (match-beginning 6))
8249 (ref-end (match-end 6))
8250 ;; Markup part
8251 (mp (list 'face 'markdown-markup-face
8252 'invisible 'markdown-markup
8253 'rear-nonsticky t
8254 'font-lock-multiline t))
8255 ;; Link part
8256 (lp (list 'keymap markdown-mode-mouse-map
8257 'face markdown-link-face
8258 'mouse-face 'markdown-highlight-face
8259 'font-lock-multiline t
8260 'help-echo (lambda (_ __ pos)
8261 (save-match-data
8262 (save-excursion
8263 (goto-char pos)
8264 (or (markdown-link-url)
8265 "Undefined reference"))))))
8266 ;; URL composition character
8267 (url-char (markdown--first-displayable markdown-url-compose-char))
8268 ;; Reference part
8269 (rp (list 'face 'markdown-reference-face
8270 'invisible 'markdown-markup
8271 'font-lock-multiline t)))
8272 (dolist (g '(1 2 4 5 8))
8273 (when (match-end g)
8274 (add-text-properties (match-beginning g) (match-end g) mp)))
8275 (when link-start (add-text-properties link-start link-end lp))
8276 (when ref-start (add-text-properties ref-start ref-end rp)
8277 (when (and markdown-hide-urls (> (- ref-end ref-start) 2))
8278 (compose-region ref-start ref-end url-char)))
8279 t)))
8281 (defun markdown-fontify-angle-uris (last)
8282 "Add text properties to angle URIs from point to LAST."
8283 (when (markdown-match-angle-uris last)
8284 (let* ((url-start (match-beginning 2))
8285 (url-end (match-end 2))
8286 ;; Markup part
8287 (mp (list 'face 'markdown-markup-face
8288 'invisible 'markdown-markup
8289 'rear-nonsticky t
8290 'font-lock-multiline t))
8291 ;; URI part
8292 (up (list 'keymap markdown-mode-mouse-map
8293 'face 'markdown-plain-url-face
8294 'mouse-face 'markdown-highlight-face
8295 'font-lock-multiline t)))
8296 (dolist (g '(1 3))
8297 (add-text-properties (match-beginning g) (match-end g) mp))
8298 (add-text-properties url-start url-end up)
8299 t)))
8301 (defun markdown-fontify-plain-uris (last)
8302 "Add text properties to plain URLs from point to LAST."
8303 (when (markdown-match-plain-uris last)
8304 (let* ((start (match-beginning 0))
8305 (end (match-end 0))
8306 (props (list 'keymap markdown-mode-mouse-map
8307 'face 'markdown-plain-url-face
8308 'mouse-face 'markdown-highlight-face
8309 'rear-nonsticky t
8310 'font-lock-multiline t)))
8311 (add-text-properties start end props)
8312 t)))
8314 (defun markdown-toggle-url-hiding (&optional arg)
8315 "Toggle the display or hiding of URLs.
8316 With a prefix argument ARG, enable URL hiding if ARG is positive,
8317 and disable it otherwise."
8318 (interactive (list (or current-prefix-arg 'toggle)))
8319 (setq markdown-hide-urls
8320 (if (eq arg 'toggle)
8321 (not markdown-hide-urls)
8322 (> (prefix-numeric-value arg) 0)))
8323 (if markdown-hide-urls
8324 (message "markdown-mode URL hiding enabled")
8325 (message "markdown-mode URL hiding disabled"))
8326 (markdown-reload-extensions))
8329 ;;; WikiLink Following/Markup =================================================
8331 (defun markdown-wiki-link-p ()
8332 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
8333 A true wiki link name matches `markdown-regex-wiki-link' but does
8334 not match the current file name after conversion. This modifies
8335 the data returned by `match-data'. Note that the potential wiki
8336 link name must be available via `match-string'."
8337 (when markdown-enable-wiki-links
8338 (let ((case-fold-search nil))
8339 (and (thing-at-point-looking-at markdown-regex-wiki-link)
8340 (not (markdown-code-block-at-point-p))
8341 (or (not buffer-file-name)
8342 (not (string-equal (buffer-file-name)
8343 (markdown-convert-wiki-link-to-filename
8344 (markdown-wiki-link-link)))))))))
8346 (defun markdown-wiki-link-link ()
8347 "Return the link part of the wiki link using current match data.
8348 The location of the link component depends on the value of
8349 `markdown-wiki-link-alias-first'."
8350 (if markdown-wiki-link-alias-first
8351 (or (match-string-no-properties 5) (match-string-no-properties 3))
8352 (match-string-no-properties 3)))
8354 (defun markdown-wiki-link-alias ()
8355 "Return the alias or text part of the wiki link using current match data.
8356 The location of the alias component depends on the value of
8357 `markdown-wiki-link-alias-first'."
8358 (if markdown-wiki-link-alias-first
8359 (match-string-no-properties 3)
8360 (or (match-string-no-properties 5) (match-string-no-properties 3))))
8362 (defun markdown-convert-wiki-link-to-filename (name)
8363 "Generate a filename from the wiki link NAME.
8364 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
8365 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
8366 and [[test test]] both map to Test-test.ext. Look in the current
8367 directory first, then in subdirectories if
8368 `markdown-wiki-link-search-subdirectories' is non-nil, and then
8369 in parent directories if
8370 `markdown-wiki-link-search-parent-directories' is non-nil."
8371 (let* ((basename (markdown-replace-regexp-in-string
8372 "[[:space:]\n]" markdown-link-space-sub-char name))
8373 (basename (if (eq major-mode 'gfm-mode)
8374 (concat (upcase (substring basename 0 1))
8375 (downcase (substring basename 1 nil)))
8376 basename))
8377 directory extension default candidates dir)
8378 (when buffer-file-name
8379 (setq directory (file-name-directory buffer-file-name)
8380 extension (file-name-extension buffer-file-name)))
8381 (setq default (concat basename
8382 (when extension (concat "." extension))))
8383 (cond
8384 ;; Look in current directory first.
8385 ((or (null buffer-file-name)
8386 (file-exists-p default))
8387 default)
8388 ;; Possibly search in subdirectories, next.
8389 ((and markdown-wiki-link-search-subdirectories
8390 (setq candidates
8391 (markdown-directory-files-recursively
8392 directory (concat "^" default "$"))))
8393 (car candidates))
8394 ;; Possibly search in parent directories as a last resort.
8395 ((and markdown-wiki-link-search-parent-directories
8396 (setq dir (locate-dominating-file directory default)))
8397 (concat dir default))
8398 ;; If nothing is found, return default in current directory.
8399 (t default))))
8401 (defun markdown-follow-wiki-link (name &optional other)
8402 "Follow the wiki link NAME.
8403 Convert the name to a file name and call `find-file'. Ensure that
8404 the new buffer remains in `markdown-mode'. Open the link in another
8405 window when OTHER is non-nil."
8406 (let ((filename (markdown-convert-wiki-link-to-filename name))
8407 (wp (when buffer-file-name
8408 (file-name-directory buffer-file-name))))
8409 (if (not wp)
8410 (user-error "Must be visiting a file")
8411 (when other (other-window 1))
8412 (let ((default-directory wp))
8413 (find-file filename)))
8414 (when (not (eq major-mode 'markdown-mode))
8415 (markdown-mode))))
8417 (defun markdown-follow-wiki-link-at-point (&optional arg)
8418 "Find Wiki Link at point.
8419 With prefix argument ARG, open the file in other window.
8420 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
8421 (interactive "P")
8422 (if (markdown-wiki-link-p)
8423 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
8424 (user-error "Point is not at a Wiki Link")))
8426 (defun markdown-highlight-wiki-link (from to face)
8427 "Highlight the wiki link in the region between FROM and TO using FACE."
8428 (put-text-property from to 'font-lock-face face))
8430 (defun markdown-unfontify-region-wiki-links (from to)
8431 "Remove wiki link faces from the region specified by FROM and TO."
8432 (interactive "*r")
8433 (let ((modified (buffer-modified-p)))
8434 (remove-text-properties from to '(font-lock-face markdown-link-face))
8435 (remove-text-properties from to '(font-lock-face markdown-missing-link-face))
8436 ;; remove-text-properties marks the buffer modified in emacs 24.3,
8437 ;; undo that if it wasn't originally marked modified
8438 (set-buffer-modified-p modified)))
8440 (defun markdown-fontify-region-wiki-links (from to)
8441 "Search region given by FROM and TO for wiki links and fontify them.
8442 If a wiki link is found check to see if the backing file exists
8443 and highlight accordingly."
8444 (goto-char from)
8445 (save-match-data
8446 (while (re-search-forward markdown-regex-wiki-link to t)
8447 (when (not (markdown-code-block-at-point-p))
8448 (let ((highlight-beginning (match-beginning 1))
8449 (highlight-end (match-end 1))
8450 (file-name
8451 (markdown-convert-wiki-link-to-filename
8452 (markdown-wiki-link-link))))
8453 (if (condition-case nil (file-exists-p file-name) (error nil))
8454 (markdown-highlight-wiki-link
8455 highlight-beginning highlight-end markdown-link-face)
8456 (markdown-highlight-wiki-link
8457 highlight-beginning highlight-end markdown-missing-link-face)))))))
8459 (defun markdown-extend-changed-region (from to)
8460 "Extend region given by FROM and TO so that we can fontify all links.
8461 The region is extended to the first newline before and the first
8462 newline after."
8463 ;; start looking for the first new line before 'from
8464 (goto-char from)
8465 (re-search-backward "\n" nil t)
8466 (let ((new-from (point-min))
8467 (new-to (point-max)))
8468 (if (not (= (point) from))
8469 (setq new-from (point)))
8470 ;; do the same thing for the first new line after 'to
8471 (goto-char to)
8472 (re-search-forward "\n" nil t)
8473 (if (not (= (point) to))
8474 (setq new-to (point)))
8475 (cl-values new-from new-to)))
8477 (defun markdown-check-change-for-wiki-link (from to)
8478 "Check region between FROM and TO for wiki links and re-fontify as needed."
8479 (interactive "*r")
8480 (let* ((modified (buffer-modified-p))
8481 (buffer-undo-list t)
8482 (inhibit-read-only t)
8483 (inhibit-point-motion-hooks t)
8484 deactivate-mark
8485 buffer-file-truename)
8486 (unwind-protect
8487 (save-excursion
8488 (save-match-data
8489 (save-restriction
8490 ;; Extend the region to fontify so that it starts
8491 ;; and ends at safe places.
8492 (cl-multiple-value-bind (new-from new-to)
8493 (markdown-extend-changed-region from to)
8494 (goto-char new-from)
8495 ;; Only refontify when the range contains text with a
8496 ;; wiki link face or if the wiki link regexp matches.
8497 (when (or (markdown-range-property-any
8498 new-from new-to 'font-lock-face
8499 (list markdown-link-face
8500 markdown-missing-link-face))
8501 (re-search-forward
8502 markdown-regex-wiki-link new-to t))
8503 ;; Unfontify existing fontification (start from scratch)
8504 (markdown-unfontify-region-wiki-links new-from new-to)
8505 ;; Now do the fontification.
8506 (markdown-fontify-region-wiki-links new-from new-to))))))
8507 (and (not modified)
8508 (buffer-modified-p)
8509 (set-buffer-modified-p nil)))))
8511 (defun markdown-check-change-for-wiki-link-after-change (from to _)
8512 "Check region between FROM and TO for wiki links and re-fontify as needed.
8513 Designed to be used with the `after-change-functions' hook."
8514 (markdown-check-change-for-wiki-link from to))
8516 (defun markdown-fontify-buffer-wiki-links ()
8517 "Refontify all wiki links in the buffer."
8518 (interactive)
8519 (markdown-check-change-for-wiki-link (point-min) (point-max)))
8522 ;;; Following & Doing =========================================================
8524 (defun markdown-follow-thing-at-point (arg)
8525 "Follow thing at point if possible, such as a reference link or wiki link.
8526 Opens inline and reference links in a browser. Opens wiki links
8527 to other files in the current window, or the another window if
8528 ARG is non-nil.
8529 See `markdown-follow-link-at-point' and
8530 `markdown-follow-wiki-link-at-point'."
8531 (interactive "P")
8532 (cond ((markdown-link-p)
8533 (markdown-follow-link-at-point))
8534 ((markdown-wiki-link-p)
8535 (markdown-follow-wiki-link-at-point arg))
8537 (user-error "Nothing to follow at point"))))
8539 (make-obsolete 'markdown-jump 'markdown-do "v2.3")
8541 (defun markdown-do ()
8542 "Do something sensible based on context at point.
8543 Jumps between reference links and definitions; between footnote
8544 markers and footnote text."
8545 (interactive)
8546 (cond
8547 ;; Footnote definition
8548 ((markdown-footnote-text-positions)
8549 (markdown-footnote-return))
8550 ;; Footnote marker
8551 ((markdown-footnote-marker-positions)
8552 (markdown-footnote-goto-text))
8553 ;; Reference link
8554 ((thing-at-point-looking-at markdown-regex-link-reference)
8555 (markdown-reference-goto-definition))
8556 ;; Reference definition
8557 ((thing-at-point-looking-at markdown-regex-reference-definition)
8558 (markdown-reference-goto-link (match-string-no-properties 2)))
8559 ;; GFM task list item
8560 ((markdown-gfm-task-list-item-at-point)
8561 (markdown-toggle-gfm-checkbox))
8562 ;; Align table
8563 ((markdown-table-at-point-p)
8564 (call-interactively #'markdown-table-align))
8565 ;; Otherwise
8567 (markdown-insert-gfm-checkbox))))
8570 ;;; Miscellaneous =============================================================
8572 (defun markdown-compress-whitespace-string (str)
8573 "Compress whitespace in STR and return result.
8574 Leading and trailing whitespace is removed. Sequences of multiple
8575 spaces, tabs, and newlines are replaced with single spaces."
8576 (markdown-replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
8577 (markdown-replace-regexp-in-string "[ \t\n]+" " " str)))
8579 (defun markdown--substitute-command-keys (string)
8580 "Like `substitute-command-keys' but, but prefers control characters.
8581 First pass STRING to `substitute-command-keys' and then
8582 substitute `C-i` for `TAB` and `C-m` for `RET`."
8583 (replace-regexp-in-string
8584 "\\<TAB\\>" "C-i"
8585 (replace-regexp-in-string
8586 "\\<RET\\>" "C-m" (substitute-command-keys string) t) t))
8588 (defun markdown-line-number-at-pos (&optional pos)
8589 "Return (narrowed) buffer line number at position POS.
8590 If POS is nil, use current buffer location.
8591 This is an exact copy of `line-number-at-pos' for use in emacs21."
8592 (let ((opoint (or pos (point))) start)
8593 (save-excursion
8594 (goto-char (point-min))
8595 (setq start (point))
8596 (goto-char opoint)
8597 (forward-line 0)
8598 (1+ (count-lines start (point))))))
8600 (defun markdown-inside-link-p ()
8601 "Return t if point is within a link."
8602 (save-match-data
8603 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
8605 (defun markdown-line-is-reference-definition-p ()
8606 "Return whether the current line is a (non-footnote) reference defition."
8607 (save-excursion
8608 (move-beginning-of-line 1)
8609 (and (looking-at-p markdown-regex-reference-definition)
8610 (not (looking-at-p "[ \t]*\\[^")))))
8612 (defun markdown-adaptive-fill-function ()
8613 "Return prefix for filling paragraph or nil if not determined."
8614 (cond
8615 ;; List item inside blockquote
8616 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
8617 (markdown-replace-regexp-in-string
8618 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
8619 ;; Blockquote
8620 ((looking-at markdown-regex-blockquote)
8621 (buffer-substring-no-properties (match-beginning 0) (match-end 2)))
8622 ;; List items
8623 ((looking-at markdown-regex-list)
8624 (match-string-no-properties 0))
8625 ;; Footnote definition
8626 ((looking-at-p markdown-regex-footnote-definition)
8627 " ") ; four spaces
8628 ;; No match
8629 (t nil)))
8631 (defun markdown-fill-paragraph (&optional justify)
8632 "Fill paragraph at or after point.
8633 This function is like \\[fill-paragraph], but it skips Markdown
8634 code blocks. If the point is in a code block, or just before one,
8635 do not fill. Otherwise, call `fill-paragraph' as usual. If
8636 JUSTIFY is non-nil, justify text as well. Since this function
8637 handles filling itself, it always returns t so that
8638 `fill-paragraph' doesn't run."
8639 (interactive "P")
8640 (unless (or (markdown-code-block-at-point-p)
8641 (save-excursion
8642 (back-to-indentation)
8643 (skip-syntax-forward "-")
8644 (markdown-code-block-at-point-p)))
8645 (fill-paragraph justify))
8648 (make-obsolete 'markdown-fill-forward-paragraph-function
8649 'markdown-fill-forward-paragraph "v2.3")
8651 (defun markdown-fill-forward-paragraph (&optional arg)
8652 "Function used by `fill-paragraph' to move over ARG paragraphs.
8653 This is a `fill-forward-paragraph-function' for `markdown-mode'.
8654 It is called with a single argument specifying the number of
8655 paragraphs to move. Just like `forward-paragraph', it should
8656 return the number of paragraphs left to move."
8657 (or arg (setq arg 1))
8658 (if (> arg 0)
8659 ;; With positive ARG, move across ARG non-code-block paragraphs,
8660 ;; one at a time. When passing a code block, don't decrement ARG.
8661 (while (and (not (eobp))
8662 (> arg 0)
8663 (= (forward-paragraph 1) 0)
8664 (or (markdown-code-block-at-pos (point-at-bol 0))
8665 (setq arg (1- arg)))))
8666 ;; Move backward by one paragraph with negative ARG (always -1).
8667 (let ((start (point)))
8668 (setq arg (forward-paragraph arg))
8669 (while (and (not (eobp))
8670 (progn (move-to-left-margin) (not (eobp)))
8671 (looking-at-p paragraph-separate))
8672 (forward-line 1))
8673 (cond
8674 ;; Move point past whitespace following list marker.
8675 ((looking-at markdown-regex-list)
8676 (goto-char (match-end 0)))
8677 ;; Move point past whitespace following pipe at beginning of line
8678 ;; to handle Pandoc line blocks.
8679 ((looking-at "^|\\s-*")
8680 (goto-char (match-end 0)))
8681 ;; Return point if the paragraph passed was a code block.
8682 ((markdown-code-block-at-pos (point-at-bol 2))
8683 (goto-char start)))))
8684 arg)
8686 (defun markdown--inhibit-electric-quote ()
8687 "Function added to `electric-quote-inhibit-functions'.
8688 Return non-nil if the quote has been inserted inside a code block
8689 or span."
8690 (let ((pos (1- (point))))
8691 (or (markdown-inline-code-at-pos pos)
8692 (markdown-code-block-at-pos pos))))
8695 ;;; Extension Framework =======================================================
8697 (defun markdown-reload-extensions ()
8698 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
8699 (interactive)
8700 (when (member major-mode '(markdown-mode gfm-mode))
8701 ;; Refontify buffer
8702 (when (and font-lock-mode (fboundp 'font-lock-refresh-defaults))
8703 (font-lock-refresh-defaults))
8704 ;; Add or remove hooks related to extensions
8705 (markdown-setup-wiki-link-hooks)))
8707 (defun markdown-handle-local-variables ()
8708 "Run in `hack-local-variables-hook' to update font lock rules.
8709 Checks to see if there is actually a ‘markdown-mode’ file local variable
8710 before regenerating font-lock rules for extensions."
8711 (when (and (boundp 'file-local-variables-alist)
8712 (or (assoc 'markdown-enable-wiki-links file-local-variables-alist)
8713 (assoc 'markdown-enable-math file-local-variables-alist)))
8714 (when (assoc 'markdown-enable-math file-local-variables-alist)
8715 (markdown-toggle-math markdown-enable-math))
8716 (markdown-reload-extensions)))
8719 ;;; Wiki Links ================================================================
8721 (defun markdown-toggle-wiki-links (&optional arg)
8722 "Toggle support for wiki links.
8723 With a prefix argument ARG, enable wiki link support if ARG is positive,
8724 and disable it otherwise."
8725 (interactive (list (or current-prefix-arg 'toggle)))
8726 (setq markdown-enable-wiki-links
8727 (if (eq arg 'toggle)
8728 (not markdown-enable-wiki-links)
8729 (> (prefix-numeric-value arg) 0)))
8730 (if markdown-enable-wiki-links
8731 (message "markdown-mode wiki link support enabled")
8732 (message "markdown-mode wiki link support disabled"))
8733 (markdown-reload-extensions))
8735 (defun markdown-setup-wiki-link-hooks ()
8736 "Add or remove hooks for fontifying wiki links.
8737 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
8738 ;; Anytime text changes make sure it gets fontified correctly
8739 (if (and markdown-enable-wiki-links
8740 markdown-wiki-link-fontify-missing)
8741 (add-hook 'after-change-functions
8742 'markdown-check-change-for-wiki-link-after-change t t)
8743 (remove-hook 'after-change-functions
8744 'markdown-check-change-for-wiki-link-after-change t))
8745 ;; If we left the buffer there is a really good chance we were
8746 ;; creating one of the wiki link documents. Make sure we get
8747 ;; refontified when we come back.
8748 (if (and markdown-enable-wiki-links
8749 markdown-wiki-link-fontify-missing)
8750 (progn
8751 (add-hook 'window-configuration-change-hook
8752 'markdown-fontify-buffer-wiki-links t t)
8753 (markdown-fontify-buffer-wiki-links))
8754 (remove-hook 'window-configuration-change-hook
8755 'markdown-fontify-buffer-wiki-links t)
8756 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
8759 ;;; Math Support ==============================================================
8761 (make-obsolete 'markdown-enable-math 'markdown-toggle-math "v2.1")
8763 (defconst markdown-mode-font-lock-keywords-math
8764 (list
8765 ;; Equation reference (eq:foo)
8766 '("\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" . ((1 markdown-markup-face)
8767 (2 markdown-reference-face)
8768 (3 markdown-markup-face)))
8769 ;; Equation reference \eqref{foo}
8770 '("\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" . ((1 markdown-markup-face)
8771 (2 markdown-reference-face)
8772 (3 markdown-markup-face))))
8773 "Font lock keywords to add and remove when toggling math support.")
8775 (defun markdown-toggle-math (&optional arg)
8776 "Toggle support for inline and display LaTeX math expressions.
8777 With a prefix argument ARG, enable math mode if ARG is positive,
8778 and disable it otherwise. If called from Lisp, enable the mode
8779 if ARG is omitted or nil."
8780 (interactive (list (or current-prefix-arg 'toggle)))
8781 (setq markdown-enable-math
8782 (if (eq arg 'toggle)
8783 (not markdown-enable-math)
8784 (> (prefix-numeric-value arg) 0)))
8785 (if markdown-enable-math
8786 (progn
8787 (font-lock-add-keywords
8788 'markdown-mode markdown-mode-font-lock-keywords-math)
8789 (message "markdown-mode math support enabled"))
8790 (font-lock-remove-keywords
8791 'markdown-mode markdown-mode-font-lock-keywords-math)
8792 (message "markdown-mode math support disabled"))
8793 (markdown-reload-extensions))
8796 ;;; GFM Checkboxes ============================================================
8798 (define-button-type 'markdown-gfm-checkbox-button
8799 'follow-link t
8800 'face 'markdown-gfm-checkbox-face
8801 'mouse-face 'markdown-highlight-face
8802 'action #'markdown-toggle-gfm-checkbox-button)
8804 (defun markdown-gfm-task-list-item-at-point (&optional bounds)
8805 "Return non-nil if there is a GFM task list item at the point.
8806 Optionally, the list item BOUNDS may be given if available, as
8807 returned by `markdown-cur-list-item-bounds'. When a task list item
8808 is found, the return value is the same value returned by
8809 `markdown-cur-list-item-bounds'."
8810 (unless bounds
8811 (setq bounds (markdown-cur-list-item-bounds)))
8812 (> (length (nth 5 bounds)) 0))
8814 (defun markdown-insert-gfm-checkbox ()
8815 "Add GFM checkbox at point.
8816 Returns t if added.
8817 Returns nil if non-applicable."
8818 (interactive)
8819 (let ((bounds (markdown-cur-list-item-bounds)))
8820 (if bounds
8821 (unless (cl-sixth bounds)
8822 (let ((pos (+ (cl-first bounds) (cl-fourth bounds)))
8823 (markup "[ ] "))
8824 (if (< pos (point))
8825 (save-excursion
8826 (goto-char pos)
8827 (insert markup))
8828 (goto-char pos)
8829 (insert markup))
8831 (unless (save-excursion
8832 (back-to-indentation)
8833 (or (markdown-list-item-at-point-p)
8834 (markdown-heading-at-point)
8835 (markdown-in-comment-p)
8836 (markdown-code-block-at-point-p)))
8837 (let ((pos (save-excursion
8838 (back-to-indentation)
8839 (point)))
8840 (markup (concat (or (save-excursion
8841 (beginning-of-line 0)
8842 (cl-fifth (markdown-cur-list-item-bounds)))
8843 markdown-unordered-list-item-prefix)
8844 "[ ] ")))
8845 (if (< pos (point))
8846 (save-excursion
8847 (goto-char pos)
8848 (insert markup))
8849 (goto-char pos)
8850 (insert markup))
8851 t)))))
8853 (defun markdown-toggle-gfm-checkbox ()
8854 "Toggle GFM checkbox at point.
8855 Returns the resulting status as a string, either \"[x]\" or \"[ ]\".
8856 Returns nil if there is no task list item at the point."
8857 (interactive)
8858 (save-match-data
8859 (save-excursion
8860 (let ((bounds (markdown-cur-list-item-bounds)))
8861 (when bounds
8862 ;; Move to beginning of task list item
8863 (goto-char (cl-first bounds))
8864 ;; Advance to column of first non-whitespace after marker
8865 (forward-char (cl-fourth bounds))
8866 (cond ((looking-at "\\[ \\]")
8867 (replace-match
8868 (if markdown-gfm-uppercase-checkbox "[X]" "[x]")
8869 nil t)
8870 (match-string-no-properties 0))
8871 ((looking-at "\\[[xX]\\]")
8872 (replace-match "[ ]" nil t)
8873 (match-string-no-properties 0))))))))
8875 (defun markdown-toggle-gfm-checkbox-button (button)
8876 "Toggle GFM checkbox BUTTON on click."
8877 (save-match-data
8878 (save-excursion
8879 (goto-char (button-start button))
8880 (markdown-toggle-gfm-checkbox))))
8882 (defun markdown-make-gfm-checkboxes-buttons (start end)
8883 "Make GFM checkboxes buttons in region between START and END."
8884 (save-excursion
8885 (goto-char start)
8886 (let ((case-fold-search t))
8887 (save-excursion
8888 (while (re-search-forward markdown-regex-gfm-checkbox end t)
8889 (make-button (match-beginning 1) (match-end 1)
8890 :type 'markdown-gfm-checkbox-button))))))
8892 ;; Called when any modification is made to buffer text.
8893 (defun markdown-gfm-checkbox-after-change-function (beg end _)
8894 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
8895 BEG and END are the limits of scanned region."
8896 (save-excursion
8897 (save-match-data
8898 ;; Rescan between start of line from `beg' and start of line after `end'.
8899 (markdown-make-gfm-checkboxes-buttons
8900 (progn (goto-char beg) (beginning-of-line) (point))
8901 (progn (goto-char end) (forward-line 1) (point))))))
8903 (defun markdown-remove-gfm-checkbox-overlays ()
8904 "Remove all GFM checkbox overlays in buffer."
8905 (save-excursion
8906 (save-restriction
8907 (widen)
8908 (remove-overlays nil nil 'face 'markdown-gfm-checkbox-face))))
8911 ;;; Display inline image =================================================
8913 (defvar markdown-inline-image-overlays nil)
8914 (make-variable-buffer-local 'markdown-inline-image-overlays)
8916 (defun markdown-remove-inline-images ()
8917 "Remove inline image overlays from image links in the buffer.
8918 This can be toggled with `markdown-toggle-inline-images'
8919 or \\[markdown-toggle-inline-images]."
8920 (interactive)
8921 (mapc #'delete-overlay markdown-inline-image-overlays)
8922 (setq markdown-inline-image-overlays nil))
8924 (defun markdown-display-inline-images ()
8925 "Add inline image overlays to image links in the buffer.
8926 This can be toggled with `markdown-toggle-inline-images'
8927 or \\[markdown-toggle-inline-images]."
8928 (interactive)
8929 (unless (display-graphic-p)
8930 (error "Cannot show images"))
8931 (save-excursion
8932 (save-restriction
8933 (widen)
8934 (goto-char (point-min))
8935 (while (re-search-forward markdown-regex-link-inline nil t)
8936 (let ((start (match-beginning 0))
8937 (end (match-end 0))
8938 (file (match-string-no-properties 6)))
8939 (when (file-exists-p file)
8940 (let* ((abspath (if (file-name-absolute-p file)
8941 file
8942 (concat default-directory file)))
8943 (image (create-image abspath)))
8944 (when image
8945 (let ((ov (make-overlay start end)))
8946 (overlay-put ov 'display image)
8947 (overlay-put ov 'face 'default)
8948 (push ov markdown-inline-image-overlays))))))))))
8950 (defun markdown-toggle-inline-images ()
8951 "Toggle inline image overlays in the buffer."
8952 (interactive)
8953 (if markdown-inline-image-overlays
8954 (markdown-remove-inline-images)
8955 (markdown-display-inline-images)))
8958 ;;; GFM Code Block Fontification ==============================================
8960 (defcustom markdown-fontify-code-blocks-natively nil
8961 "When non-nil, fontify code in code blocks using the native major mode.
8962 This only works for fenced code blocks where the language is
8963 specified where we can automatically determine the appropriate
8964 mode to use. The language to mode mapping may be customized by
8965 setting the variable `markdown-code-lang-modes'."
8966 :group 'markdown
8967 :type 'boolean
8968 :safe 'booleanp
8969 :package-version '(markdown-mode . "2.3"))
8971 (defun markdown-toggle-fontify-code-blocks-natively (&optional arg)
8972 "Toggle the native fontification of code blocks.
8973 With a prefix argument ARG, enable if ARG is positive,
8974 and disable otherwise."
8975 (interactive (list (or current-prefix-arg 'toggle)))
8976 (setq markdown-fontify-code-blocks-natively
8977 (if (eq arg 'toggle)
8978 (not markdown-fontify-code-blocks-natively)
8979 (> (prefix-numeric-value arg) 0)))
8980 (if markdown-fontify-code-blocks-natively
8981 (message "markdown-mode native code block fontification enabled")
8982 (message "markdown-mode native code block fontification disabled"))
8983 (markdown-reload-extensions))
8985 ;; This is based on `org-src-lang-modes' from org-src.el
8986 (defcustom markdown-code-lang-modes
8987 '(("ocaml" . tuareg-mode) ("elisp" . emacs-lisp-mode) ("ditaa" . artist-mode)
8988 ("asymptote" . asy-mode) ("dot" . fundamental-mode) ("sqlite" . sql-mode)
8989 ("calc" . fundamental-mode) ("C" . c-mode) ("cpp" . c++-mode)
8990 ("C++" . c++-mode) ("screen" . shell-script-mode) ("shell" . sh-mode)
8991 ("bash" . sh-mode))
8992 "Alist mapping languages to their major mode.
8993 The key is the language name, the value is the major mode. For
8994 many languages this is simple, but for language where this is not
8995 the case, this variable provides a way to simplify things on the
8996 user side. For example, there is no ocaml-mode in Emacs, but the
8997 mode to use is `tuareg-mode'."
8998 :group 'markdown
8999 :type '(repeat
9000 (cons
9001 (string "Language name")
9002 (symbol "Major mode")))
9003 :package-version '(markdown-mode . "2.3"))
9005 (defun markdown-get-lang-mode (lang)
9006 "Return major mode that should be used for LANG.
9007 LANG is a string, and the returned major mode is a symbol."
9008 (cl-find-if
9009 'fboundp
9010 (list (cdr (assoc lang markdown-code-lang-modes))
9011 (cdr (assoc (downcase lang) markdown-code-lang-modes))
9012 (intern (concat lang "-mode"))
9013 (intern (concat (downcase lang) "-mode")))))
9015 (defun markdown-fontify-code-blocks-generic (matcher last)
9016 "Add text properties to next code block from point to LAST.
9017 Use matching function MATCHER."
9018 (when (funcall matcher last)
9019 (save-excursion
9020 (save-match-data
9021 (let* ((start (match-beginning 0))
9022 (end (match-end 0))
9023 ;; Find positions outside opening and closing backquotes.
9024 (bol-prev (progn (goto-char start)
9025 (if (bolp) (point-at-bol 0) (point-at-bol))))
9026 (eol-next (progn (goto-char end)
9027 (if (bolp) (point-at-bol 2) (point-at-bol 3))))
9028 lang)
9029 (if (and markdown-fontify-code-blocks-natively
9030 (setq lang (markdown-code-block-lang)))
9031 (markdown-fontify-code-block-natively lang start end)
9032 (add-text-properties start end '(face markdown-pre-face)))
9033 ;; Set background for block as well as opening and closing lines.
9034 (font-lock-append-text-property
9035 bol-prev eol-next 'face 'markdown-code-face)
9036 ;; Set invisible property for lines before and after, including newline.
9037 (add-text-properties bol-prev start '(invisible markdown-markup))
9038 (add-text-properties end eol-next '(invisible markdown-markup)))))
9041 (defun markdown-fontify-gfm-code-blocks (last)
9042 "Add text properties to next GFM code block from point to LAST."
9043 (markdown-fontify-code-blocks-generic 'markdown-match-gfm-code-blocks last))
9045 (defun markdown-fontify-fenced-code-blocks (last)
9046 "Add text properties to next tilde fenced code block from point to LAST."
9047 (markdown-fontify-code-blocks-generic 'markdown-match-fenced-code-blocks last))
9049 ;; Based on `org-src-font-lock-fontify-block' from org-src.el.
9050 (defun markdown-fontify-code-block-natively (lang start end)
9051 "Fontify given GFM or fenced code block.
9052 This function is called by Emacs for automatic fontification when
9053 `markdown-fontify-code-blocks-natively' is non-nil. LANG is the
9054 language used in the block. START and END specify the block
9055 position."
9056 (let ((lang-mode (markdown-get-lang-mode lang)))
9057 (when (fboundp lang-mode)
9058 (let ((string (buffer-substring-no-properties start end))
9059 (modified (buffer-modified-p))
9060 (markdown-buffer (current-buffer)) pos next)
9061 (remove-text-properties start end '(face nil))
9062 (with-current-buffer
9063 (get-buffer-create
9064 (concat " markdown-code-fontification:" (symbol-name lang-mode)))
9065 ;; Make sure that modification hooks are not inhibited in
9066 ;; the org-src-fontification buffer in case we're called
9067 ;; from `jit-lock-function' (Bug#25132).
9068 (let ((inhibit-modification-hooks nil))
9069 (delete-region (point-min) (point-max))
9070 (insert string " ")) ;; so there's a final property change
9071 (unless (eq major-mode lang-mode) (funcall lang-mode))
9072 (markdown-font-lock-ensure)
9073 (setq pos (point-min))
9074 (while (setq next (next-single-property-change pos 'face))
9075 (let ((val (get-text-property pos 'face)))
9076 (when val
9077 (put-text-property
9078 (+ start (1- pos)) (1- (+ start next)) 'face
9079 val markdown-buffer)))
9080 (setq pos next)))
9081 (add-text-properties
9082 start end
9083 '(font-lock-fontified t fontified t font-lock-multiline t))
9084 (set-buffer-modified-p modified)))))
9086 (require 'edit-indirect nil t)
9087 (defvar edit-indirect-guess-mode-function)
9088 (defvar edit-indirect-after-commit-functions)
9090 (defun markdown--edit-indirect-after-commit-function (_beg end)
9091 "Ensure trailing newlines at the END of code blocks."
9092 (goto-char end)
9093 (unless (eq (char-before) ?\n)
9094 (insert "\n")))
9096 (defun markdown-edit-code-block ()
9097 "Edit Markdown code block in an indirect buffer."
9098 (interactive)
9099 (save-excursion
9100 (if (fboundp 'edit-indirect-region)
9101 (let* ((bounds (markdown-get-enclosing-fenced-block-construct))
9102 (begin (and bounds (goto-char (nth 0 bounds)) (point-at-bol 2)))
9103 (end (and bounds (goto-char (nth 1 bounds)) (point-at-bol 1))))
9104 (if (and begin end)
9105 (let* ((lang (markdown-code-block-lang))
9106 (mode (if lang
9107 (markdown-get-lang-mode lang)
9108 markdown-edit-code-block-default-mode))
9109 (edit-indirect-guess-mode-function
9110 (lambda (_parent-buffer _beg _end)
9111 (funcall mode))))
9112 (edit-indirect-region begin end 'display-buffer))
9113 (user-error "Not inside a GFM or tilde fenced code block")))
9114 (when (y-or-n-p "Package edit-indirect needed to edit code blocks. Install it now? ")
9115 (progn (package-refresh-contents)
9116 (package-install 'edit-indirect)
9117 (markdown-edit-code-block))))))
9120 ;;; Table Editing
9122 ;; These functions were originally adapted from `org-table.el'.
9124 ;; General helper functions
9126 (defmacro markdown--with-gensyms (symbols &rest body)
9127 (declare (debug (sexp body)) (indent 1))
9128 `(let ,(mapcar (lambda (s)
9129 `(,s (make-symbol (concat "--" (symbol-name ',s)))))
9130 symbols)
9131 ,@body))
9133 (defun markdown--split-string (string &optional separators)
9134 "Splits STRING into substrings at SEPARATORS.
9135 SEPARATORS is a regular expression. If nil it defaults to
9136 `split-string-default-separators'. This version returns no empty
9137 strings if there are matches at the beginning and end of string."
9138 (let ((start 0) notfirst list)
9139 (while (and (string-match
9140 (or separators split-string-default-separators)
9141 string
9142 (if (and notfirst
9143 (= start (match-beginning 0))
9144 (< start (length string)))
9145 (1+ start) start))
9146 (< (match-beginning 0) (length string)))
9147 (setq notfirst t)
9148 (or (eq (match-beginning 0) 0)
9149 (and (eq (match-beginning 0) (match-end 0))
9150 (eq (match-beginning 0) start))
9151 (push (substring string start (match-beginning 0)) list))
9152 (setq start (match-end 0)))
9153 (or (eq start (length string))
9154 (push (substring string start) list))
9155 (nreverse list)))
9157 (defun markdown--string-width (s)
9158 "Return width of string S.
9159 This version ignores characters with invisibility property
9160 `markdown-markup'."
9161 (let (b)
9162 (when (or (eq t buffer-invisibility-spec)
9163 (member 'markdown-markup buffer-invisibility-spec))
9164 (while (setq b (text-property-any
9165 0 (length s)
9166 'invisible 'markdown-markup s))
9167 (setq s (concat
9168 (substring s 0 b)
9169 (substring s (or (next-single-property-change
9170 b 'invisible s)
9171 (length s))))))))
9172 (string-width s))
9174 (defun markdown--remove-invisible-markup (s)
9175 "Remove Markdown markup from string S.
9176 This version removes characters with invisibility property
9177 `markdown-markup'."
9178 (let (b)
9179 (while (setq b (text-property-any
9180 0 (length s)
9181 'invisible 'markdown-markup s))
9182 (setq s (concat
9183 (substring s 0 b)
9184 (substring s (or (next-single-property-change
9185 b 'invisible s)
9186 (length s)))))))
9189 ;; Functions for maintaining tables
9191 (defconst markdown-table-line-regexp "^[ \t]*|"
9192 "Regexp matching any line inside a table.")
9194 (defconst markdown-table-hline-regexp "^[ \t]*|[-:]"
9195 "Regexp matching hline inside a table.")
9197 (defconst markdown-table-dline-regexp "^[ \t]*|[^-:]"
9198 "Regexp matching dline inside a table.")
9200 (defconst markdown-table-border-regexp "^[ \t]*[^| \t]"
9201 "Regexp matching any line outside a table.")
9203 (defun markdown-table-at-point-p ()
9204 "Return non-nil when point is inside a table."
9205 (save-excursion
9206 (beginning-of-line)
9207 (and (looking-at-p markdown-table-line-regexp)
9208 (not (markdown-code-block-at-point-p)))))
9210 (defun markdown-table-hline-at-point-p ()
9211 "Return non-nil when point is on a hline in a table.
9212 This function assumes point is on a table."
9213 (save-excursion
9214 (beginning-of-line)
9215 (looking-at-p markdown-table-hline-regexp)))
9217 (defun markdown-table-begin ()
9218 "Find the beginning of the table and return its position.
9219 This function assumes point is on a table."
9220 (cond
9221 ((save-excursion
9222 (and (re-search-backward markdown-table-border-regexp nil t)
9223 (line-beginning-position 2))))
9224 (t (point-min))))
9226 (defun markdown-table-end ()
9227 "Find the end of the table and return its position.
9228 This function assumes point is on a table."
9229 (save-excursion
9230 (cond
9231 ((re-search-forward markdown-table-border-regexp nil t)
9232 (match-beginning 0))
9233 (t (goto-char (point-max))
9234 (skip-chars-backward " \t")
9235 (if (bolp) (point) (line-end-position))))))
9237 (defun markdown-table-get-dline ()
9238 "Return index of the table data line at point.
9239 This function assumes point is on a table."
9240 (let ((pos (point)) (end (markdown-table-end)) (cnt 0))
9241 (save-excursion
9242 (goto-char (markdown-table-begin))
9243 (while (and (re-search-forward
9244 markdown-table-dline-regexp end t)
9245 (setq cnt (1+ cnt))
9246 (< (point-at-eol) pos))))
9247 cnt))
9249 (defun markdown-table-get-column ()
9250 "Return table column at point.
9251 This function assumes point is on a table."
9252 (let ((pos (point)) (cnt 0))
9253 (save-excursion
9254 (beginning-of-line)
9255 (while (search-forward "|" pos t) (setq cnt (1+ cnt))))
9256 cnt))
9258 (defun markdown-table-get-cell (&optional n)
9259 "Return the content of the cell in column N of current row.
9260 N defaults to column at point. This function assumes point is on
9261 a table."
9262 (and n (markdown-table-goto-column n))
9263 (skip-chars-backward "^|\n") (backward-char 1)
9264 (if (looking-at "|[^|\r\n]*")
9265 (let* ((pos (match-beginning 0))
9266 (val (buffer-substring (1+ pos) (match-end 0))))
9267 (goto-char (min (point-at-eol) (+ 2 pos)))
9268 ;; Trim whitespaces
9269 (setq val (replace-regexp-in-string "\\`[ \t]+" "" val)
9270 val (replace-regexp-in-string "[ \t]+\\'" "" val)))
9271 (forward-char 1) ""))
9273 (defun markdown-table-goto-dline (n)
9274 "Go to the Nth data line in the table at point.
9275 Return t when the line exists, nil otherwise. This function
9276 assumes point is on a table."
9277 (goto-char (markdown-table-begin))
9278 (let ((end (markdown-table-end)) (cnt 0))
9279 (while (and (re-search-forward
9280 markdown-table-dline-regexp end t)
9281 (< (setq cnt (1+ cnt)) n)))
9282 (= cnt n)))
9284 (defun markdown-table-goto-column (n &optional on-delim)
9285 "Go to the Nth column in the table line at point.
9286 With optional argument ON-DELIM, stop with point before the left
9287 delimiter of the cell. If there are less than N cells, just go
9288 beyond the last delimiter. This function assumes point is on a
9289 table."
9290 (beginning-of-line 1)
9291 (when (> n 0)
9292 (while (and (> (setq n (1- n)) -1)
9293 (search-forward "|" (point-at-eol) t)))
9294 (if on-delim
9295 (backward-char 1)
9296 (when (looking-at " ") (forward-char 1)))))
9298 (defmacro markdown-table-save-cell (&rest body)
9299 "Save cell at point, execute BODY and restore cell.
9300 This function assumes point is on a table."
9301 (declare (debug (body)))
9302 (markdown--with-gensyms (line column)
9303 `(let ((,line (copy-marker (line-beginning-position)))
9304 (,column (markdown-table-get-column)))
9305 (unwind-protect
9306 (progn ,@body)
9307 (goto-char ,line)
9308 (markdown-table-goto-column ,column)
9309 (set-marker ,line nil)))))
9311 (defun markdown-table-blank-line (s)
9312 "Convert a table line S into a line with blank cells."
9313 (if (string-match "^[ \t]*|-" s)
9314 (setq s (mapconcat
9315 (lambda (x) (if (member x '(?| ?+)) "|" " "))
9316 s ""))
9317 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9318 (setq s (replace-match
9319 (concat "|" (make-string (length (match-string 1 s)) ?\ ) "|")
9320 t t s)))
9323 (defun markdown-table-colfmt (fmtspec)
9324 "Process column alignment specifier FMTSPEC for tables."
9325 (when (stringp fmtspec)
9326 (mapcar (lambda (x)
9327 (cond ((string-match-p "^:.*:$" x) 'c)
9328 ((string-match-p "^:" x) 'l)
9329 ((string-match-p ":$" x) 'r)
9330 (t 'd)))
9331 (markdown--split-string fmtspec "\\s-*|\\s-*"))))
9333 (defun markdown-table-align ()
9334 "Align table at point.
9335 This function assumes point is on a table."
9336 (interactive)
9337 (let ((begin (markdown-table-begin))
9338 (end (copy-marker (markdown-table-end))))
9339 (markdown-table-save-cell
9340 (goto-char begin)
9341 (let* (fmtspec
9342 ;; Store table indent
9343 (indent (progn (looking-at "[ \t]*") (match-string 0)))
9344 ;; Split table in lines and save column format specifier
9345 (lines (mapcar (lambda (l)
9346 (if (string-match-p "\\`[ \t]*|[-:]" l)
9347 (progn (setq fmtspec (or fmtspec l)) nil) l))
9348 (markdown--split-string (buffer-substring begin end) "\n")))
9349 ;; Split lines in cells
9350 (cells (mapcar (lambda (l) (markdown--split-string l "\\s-*|\\s-*"))
9351 (remq nil lines)))
9352 ;; Calculate maximum number of cells in a line
9353 (maxcells (if cells
9354 (apply #'max (mapcar #'length cells))
9355 (user-error "Empty table")))
9356 ;; Empty cells to fill short lines
9357 (emptycells (make-list maxcells "")) maxwidths)
9358 ;; Calculate maximum width for each column
9359 (dotimes (i maxcells)
9360 (let ((column (mapcar (lambda (x) (or (nth i x) "")) cells)))
9361 (push (apply #'max 1 (mapcar #'markdown--string-width column))
9362 maxwidths)))
9363 (setq maxwidths (nreverse maxwidths))
9364 ;; Process column format specifier
9365 (setq fmtspec (markdown-table-colfmt fmtspec))
9366 ;; Compute formats needed for output of table lines
9367 (let ((hfmt (concat indent "|"))
9368 (rfmt (concat indent "|"))
9369 hfmt1 rfmt1 fmt)
9370 (dolist (width maxwidths (setq hfmt (concat (substring hfmt 0 -1) "|")))
9371 (setq fmt (pop fmtspec))
9372 (cond ((equal fmt 'l) (setq hfmt1 ":%s-|" rfmt1 " %%-%ds |"))
9373 ((equal fmt 'r) (setq hfmt1 "-%s:|" rfmt1 " %%%ds |"))
9374 ((equal fmt 'c) (setq hfmt1 ":%s:|" rfmt1 " %%-%ds |"))
9375 (t (setq hfmt1 "-%s-|" rfmt1 " %%-%ds |")))
9376 (setq rfmt (concat rfmt (format rfmt1 width)))
9377 (setq hfmt (concat hfmt (format hfmt1 (make-string width ?-)))))
9378 ;; Replace modified lines only
9379 (dolist (line lines)
9380 (let ((line (if line
9381 (apply #'format rfmt (append (pop cells) emptycells))
9382 hfmt))
9383 (previous (buffer-substring (point) (line-end-position))))
9384 (if (equal previous line)
9385 (forward-line)
9386 (insert line "\n")
9387 (delete-region (point) (line-beginning-position 2))))))
9388 (set-marker end nil)))))
9390 (defun markdown-table-insert-row (&optional arg)
9391 "Insert a new row above the row at point into the table.
9392 With optional argument ARG, insert below the current row."
9393 (interactive "P")
9394 (unless (markdown-table-at-point-p)
9395 (user-error "Not at a table"))
9396 (let* ((line (buffer-substring
9397 (line-beginning-position) (line-end-position)))
9398 (new (markdown-table-blank-line line)))
9399 (beginning-of-line (if arg 2 1))
9400 (unless (bolp) (insert "\n"))
9401 (insert-before-markers new "\n")
9402 (beginning-of-line 0)
9403 (re-search-forward "| ?" (line-end-position) t)))
9405 (defun markdown-table-delete-row ()
9406 "Delete row or horizontal line at point from the table."
9407 (interactive)
9408 (unless (markdown-table-at-point-p)
9409 (user-error "Not at a table"))
9410 (let ((col (current-column)))
9411 (kill-region (point-at-bol)
9412 (min (1+ (point-at-eol)) (point-max)))
9413 (unless (markdown-table-at-point-p) (beginning-of-line 0))
9414 (move-to-column col)))
9416 (defun markdown-table-move-row (&optional up)
9417 "Move table line at point down.
9418 With optional argument UP, move it up."
9419 (interactive "P")
9420 (unless (markdown-table-at-point-p)
9421 (user-error "Not at a table"))
9422 (let* ((col (current-column)) (pos (point))
9423 (tonew (if up 0 2)) txt)
9424 (beginning-of-line tonew)
9425 (unless (markdown-table-at-point-p)
9426 (goto-char pos) (user-error "Cannot move row further"))
9427 (goto-char pos) (beginning-of-line 1) (setq pos (point))
9428 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9429 (delete-region (point) (1+ (point-at-eol)))
9430 (beginning-of-line tonew)
9431 (insert txt) (beginning-of-line 0)
9432 (move-to-column col)))
9434 (defun markdown-table-move-row-up ()
9435 "Move table row at point up."
9436 (interactive)
9437 (markdown-table-move-row 'up))
9439 (defun markdown-table-move-row-down ()
9440 "Move table row at point down."
9441 (interactive)
9442 (markdown-table-move-row nil))
9444 (defun markdown-table-insert-column ()
9445 "Insert a new table column."
9446 (interactive)
9447 (unless (markdown-table-at-point-p)
9448 (user-error "Not at a table"))
9449 (let* ((col (max 1 (markdown-table-get-column)))
9450 (begin (markdown-table-begin))
9451 (end (copy-marker (markdown-table-end))))
9452 (markdown-table-save-cell
9453 (goto-char begin)
9454 (while (< (point) end)
9455 (markdown-table-goto-column col t)
9456 (if (markdown-table-hline-at-point-p)
9457 (insert "|---")
9458 (insert "| "))
9459 (forward-line)))
9460 (set-marker end nil)
9461 (markdown-table-align)))
9463 (defun markdown-table-delete-column ()
9464 "Delete column at point from table."
9465 (interactive)
9466 (unless (markdown-table-at-point-p)
9467 (user-error "Not at a table"))
9468 (let ((col (markdown-table-get-column))
9469 (begin (markdown-table-begin))
9470 (end (copy-marker (markdown-table-end))))
9471 (markdown-table-save-cell
9472 (goto-char begin)
9473 (while (< (point) end)
9474 (markdown-table-goto-column col t)
9475 (and (looking-at "|[^|\n]+|")
9476 (replace-match "|"))
9477 (forward-line)))
9478 (set-marker end nil)
9479 (markdown-table-goto-column (max 1 (1- col)))
9480 (markdown-table-align)))
9482 (defun markdown-table-move-column (&optional left)
9483 "Move table column at point to the right.
9484 With optional argument LEFT, move it to the left."
9485 (interactive "P")
9486 (unless (markdown-table-at-point-p)
9487 (user-error "Not at a table"))
9488 (let* ((col (markdown-table-get-column))
9489 (col1 (if left (1- col) col))
9490 (colpos (if left (1- col) (1+ col)))
9491 (begin (markdown-table-begin))
9492 (end (copy-marker (markdown-table-end))))
9493 (when (and left (= col 1))
9494 (user-error "Cannot move column further left"))
9495 (when (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9496 (user-error "Cannot move column further right"))
9497 (markdown-table-save-cell
9498 (goto-char begin)
9499 (while (< (point) end)
9500 (markdown-table-goto-column col1 t)
9501 (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9502 (replace-match "|\\2|\\1|"))
9503 (forward-line)))
9504 (set-marker end nil)
9505 (markdown-table-goto-column colpos)
9506 (markdown-table-align)))
9508 (defun markdown-table-move-column-left ()
9509 "Move table column at point to the left."
9510 (interactive)
9511 (markdown-table-move-column 'left))
9513 (defun markdown-table-move-column-right ()
9514 "Move table column at point to the right."
9515 (interactive)
9516 (markdown-table-move-column nil))
9518 (defun markdown-table-next-row ()
9519 "Go to the next row (same column) in the table.
9520 Create new table lines if required."
9521 (interactive)
9522 (unless (markdown-table-at-point-p)
9523 (user-error "Not at a table"))
9524 (if (or (looking-at "[ \t]*$")
9525 (save-excursion (skip-chars-backward " \t") (bolp)))
9526 (newline)
9527 (markdown-table-align)
9528 (let ((col (markdown-table-get-column)))
9529 (beginning-of-line 2)
9530 (if (or (not (markdown-table-at-point-p))
9531 (markdown-table-hline-at-point-p))
9532 (progn
9533 (beginning-of-line 0)
9534 (markdown-table-insert-row 'below)))
9535 (markdown-table-goto-column col)
9536 (skip-chars-backward "^|\n\r")
9537 (when (looking-at " ") (forward-char 1)))))
9539 (defun markdown-table-forward-cell ()
9540 "Go to the next cell in the table.
9541 Create new table lines if required."
9542 (interactive)
9543 (unless (markdown-table-at-point-p)
9544 (user-error "Not at a table"))
9545 (markdown-table-align)
9546 (let ((end (markdown-table-end)))
9547 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9548 (condition-case nil
9549 (progn
9550 (re-search-forward "|" end)
9551 (if (looking-at "[ \t]*$")
9552 (re-search-forward "|" end))
9553 (if (and (looking-at "[-:]")
9554 (re-search-forward "^[ \t]*|\\([^-:]\\)" end t))
9555 (goto-char (match-beginning 1)))
9556 (if (looking-at "[-:]")
9557 (progn
9558 (beginning-of-line 0)
9559 (markdown-table-insert-row 'below))
9560 (when (looking-at " ") (forward-char 1))))
9561 (error (markdown-table-insert-row 'below)))))
9563 (defun markdown-table-backward-cell ()
9564 "Go to the previous cell in the table."
9565 (interactive)
9566 (unless (markdown-table-at-point-p)
9567 (user-error "Not at a table"))
9568 (markdown-table-align)
9569 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9570 (condition-case nil
9571 (progn
9572 (re-search-backward "|" (markdown-table-begin))
9573 (re-search-backward "|" (markdown-table-begin)))
9574 (error (user-error "Cannot move to previous table cell")))
9575 (while (looking-at "|\\([-:]\\|[ \t]*$\\)")
9576 (re-search-backward "|" (markdown-table-begin)))
9577 (when (looking-at "| ?") (goto-char (match-end 0))))
9579 (defun markdown-table-transpose ()
9580 "Transpose table at point.
9581 Horizontal separator lines will be eliminated."
9582 (interactive)
9583 (unless (markdown-table-at-point-p)
9584 (user-error "Not at a table"))
9585 (let* ((table (buffer-substring-no-properties
9586 (markdown-table-begin) (markdown-table-end)))
9587 ;; Convert table to a Lisp structure
9588 (table (delq nil
9589 (mapcar
9590 (lambda (x)
9591 (unless (string-match-p
9592 markdown-table-hline-regexp x)
9593 (markdown--split-string x "\\s-*|\\s-*")))
9594 (markdown--split-string table "[ \t]*\n[ \t]*"))))
9595 (dline_old (markdown-table-get-dline))
9596 (col_old (markdown-table-get-column))
9597 (contents (mapcar (lambda (_)
9598 (let ((tp table))
9599 (mapcar
9600 (lambda (_)
9601 (prog1
9602 (pop (car tp))
9603 (setq tp (cdr tp))))
9604 table)))
9605 (car table))))
9606 (goto-char (markdown-table-begin))
9607 (re-search-forward "|") (backward-char)
9608 (delete-region (point) (markdown-table-end))
9609 (insert (mapconcat
9610 (lambda(x)
9611 (concat "| " (mapconcat 'identity x " | " ) " |\n"))
9612 contents ""))
9613 (markdown-table-goto-dline col_old)
9614 (markdown-table-goto-column dline_old))
9615 (markdown-table-align))
9617 (defun markdown-table-sort-lines (&optional sorting-type)
9618 "Sort table lines according to the column at point.
9620 The position of point indicates the column to be used for
9621 sorting, and the range of lines is the range between the nearest
9622 horizontal separator lines, or the entire table of no such lines
9623 exist. If point is before the first column, user will be prompted
9624 for the sorting column. If there is an active region, the mark
9625 specifies the first line and the sorting column, while point
9626 should be in the last line to be included into the sorting.
9628 The command then prompts for the sorting type which can be
9629 alphabetically or numerically. Sorting in reverse order is also
9630 possible.
9632 If SORTING-TYPE is specified when this function is called from a
9633 Lisp program, no prompting will take place. SORTING-TYPE must be
9634 a character, any of (?a ?A ?n ?N) where the capital letters
9635 indicate that sorting should be done in reverse order."
9636 (interactive)
9637 (unless (markdown-table-at-point-p)
9638 (user-error "Not at a table"))
9639 ;; Set sorting type and column used for sorting
9640 (let ((column (let ((c (markdown-table-get-column)))
9641 (cond ((> c 0) c)
9642 ((called-interactively-p 'any)
9643 (read-number "Use column N for sorting: "))
9644 (t 1))))
9645 (sorting-type
9646 (or sorting-type
9647 (read-char-exclusive
9648 "Sort type: [a]lpha [n]umeric (A/N means reversed): "))))
9649 (save-restriction
9650 ;; Narrow buffer to appropriate sorting area
9651 (if (region-active-p)
9652 (narrow-to-region
9653 (save-excursion
9654 (progn
9655 (goto-char (region-beginning)) (line-beginning-position)))
9656 (save-excursion
9657 (progn
9658 (goto-char (region-end)) (line-end-position))))
9659 (let ((start (markdown-table-begin))
9660 (end (markdown-table-end)))
9661 (narrow-to-region
9662 (save-excursion
9663 (if (re-search-backward
9664 markdown-table-hline-regexp start t)
9665 (line-beginning-position 2)
9666 start))
9667 (if (save-excursion (re-search-forward
9668 markdown-table-hline-regexp end t))
9669 (match-beginning 0)
9670 end))))
9671 ;; Determine arguments for `sort-subr'
9672 (let* ((extract-key-from-cell
9673 (cl-case sorting-type
9674 ((?a ?A) #'markdown--remove-invisible-markup) ;; #'identity)
9675 ((?n ?N) #'string-to-number)
9676 (t (user-error "Invalid sorting type: %c" sorting-type))))
9677 (predicate
9678 (cl-case sorting-type
9679 ((?n ?N) #'<)
9680 ((?a ?A) #'string<))))
9681 ;; Sort selected area
9682 (goto-char (point-min))
9683 (sort-subr (memq sorting-type '(?A ?N))
9684 (lambda ()
9685 (forward-line)
9686 (while (and (not (eobp))
9687 (not (looking-at
9688 markdown-table-dline-regexp)))
9689 (forward-line)))
9690 #'end-of-line
9691 (lambda ()
9692 (funcall extract-key-from-cell
9693 (markdown-table-get-cell column)))
9695 predicate)
9696 (goto-char (point-min))))))
9698 (defun markdown-table-convert-region (begin end &optional separator)
9699 "Convert region from BEGIN to END to table with SEPARATOR.
9701 If every line contains at least one TAB character, the function
9702 assumes that the material is tab separated (TSV). If every line
9703 contains a comma, comma-separated values (CSV) are assumed. If
9704 not, lines are split at whitespace into cells.
9706 You can use a prefix argument to force a specific separator:
9707 \\[universal-argument] once forces CSV, \\[universal-argument]
9708 twice forces TAB, and \\[universal-argument] three times will
9709 prompt for a regular expression to match the separator, and a
9710 numeric argument N indicates that at least N consecutive
9711 spaces, or alternatively a TAB should be used as the separator."
9713 (interactive "r\nP")
9714 (let* ((begin (min begin end)) (end (max begin end)) re)
9715 (goto-char begin) (beginning-of-line 1)
9716 (setq begin (point-marker))
9717 (goto-char end)
9718 (if (bolp) (backward-char 1) (end-of-line 1))
9719 (setq end (point-marker))
9720 (when (equal separator '(64))
9721 (setq separator (read-regexp "Regexp for cell separator: ")))
9722 (unless separator
9723 ;; Get the right cell separator
9724 (goto-char begin)
9725 (setq separator
9726 (cond
9727 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
9728 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
9729 (t 1))))
9730 (goto-char begin)
9731 (if (equal separator '(4))
9732 ;; Parse CSV
9733 (while (< (point) end)
9734 (cond
9735 ((looking-at "^") (insert "| "))
9736 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
9737 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
9738 (replace-match "\\1") (if (looking-at "\"") (insert "\"")))
9739 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
9740 ((looking-at "[ \t]*,") (replace-match " | "))
9741 (t (beginning-of-line 2))))
9742 (setq re
9743 (cond
9744 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
9745 ((equal separator '(16)) "^\\|\t")
9746 ((integerp separator)
9747 (if (< separator 1)
9748 (user-error "Cell separator must contain one or more spaces")
9749 (format "^ *\\| *\t *\\| \\{%d,\\}" separator)))
9750 ((stringp separator) (format "^ *\\|%s" separator))
9751 (t (error "Invalid cell separator"))))
9752 (while (re-search-forward re end t) (replace-match "| " t t)))
9753 (goto-char begin)
9754 (markdown-table-align)))
9757 ;;; ElDoc Support
9759 (defun markdown-eldoc-function ()
9760 "Return a helpful string when appropriate based on context.
9761 * Report URL when point is at a hidden URL.
9762 * Report language name when point is a code block with hidden markup."
9763 (cond
9764 ;; Hidden URL or reference for inline link
9765 ((and (or (thing-at-point-looking-at markdown-regex-link-inline)
9766 (thing-at-point-looking-at markdown-regex-link-reference))
9767 (or markdown-hide-urls markdown-hide-markup))
9768 (let* ((imagep (string-equal (match-string 1) "!"))
9769 (edit-keys (markdown--substitute-command-keys
9770 (if imagep
9771 "\\[markdown-insert-image]"
9772 "\\[markdown-insert-link]")))
9773 (edit-str (propertize edit-keys 'face 'font-lock-constant-face))
9774 (referencep (string-equal (match-string 5) "["))
9775 (object (if referencep "reference" "URL")))
9776 (format "Hidden %s (%s to edit): %s" object edit-str
9777 (if referencep
9778 (concat
9779 (propertize "[" 'face 'markdown-markup-face)
9780 (propertize (match-string-no-properties 6)
9781 'face 'markdown-reference-face)
9782 (propertize "]" 'face 'markdown-markup-face))
9783 (propertize (match-string-no-properties 6)
9784 'face 'markdown-url-face)))))
9785 ;; Hidden language name for fenced code blocks
9786 ((and (markdown-code-block-at-point-p)
9787 (not (get-text-property (point) 'markdown-pre))
9788 markdown-hide-markup)
9789 (let ((lang (save-excursion (markdown-code-block-lang))))
9790 (unless lang (setq lang "[unspecified]"))
9791 (format "Hidden code block language: %s (%s to toggle markup)"
9792 (propertize lang 'face 'markdown-language-keyword-face)
9793 (markdown--substitute-command-keys
9794 "\\[markdown-toggle-markup-hiding]"))))))
9797 ;;; Mode Definition ==========================================================
9799 (defun markdown-show-version ()
9800 "Show the version number in the minibuffer."
9801 (interactive)
9802 (message "markdown-mode, version %s" markdown-mode-version))
9804 (defun markdown-mode-info ()
9805 "Open the `markdown-mode' homepage."
9806 (interactive)
9807 (browse-url "https://jblevins.org/projects/markdown-mode/"))
9809 ;;;###autoload
9810 (define-derived-mode markdown-mode text-mode "Markdown"
9811 "Major mode for editing Markdown files."
9812 ;; Natural Markdown tab width
9813 (setq tab-width 4)
9814 ;; Comments
9815 (setq-local comment-start "<!-- ")
9816 (setq-local comment-end " -->")
9817 (setq-local comment-start-skip "<!--[ \t]*")
9818 (setq-local comment-column 0)
9819 (setq-local comment-auto-fill-only-comments nil)
9820 (setq-local comment-use-syntax t)
9821 ;; Syntax
9822 (add-hook 'syntax-propertize-extend-region-functions
9823 #'markdown-syntax-propertize-extend-region)
9824 (add-hook 'jit-lock-after-change-extend-region-functions
9825 #'markdown-font-lock-extend-region-function t t)
9826 (setq-local syntax-propertize-function #'markdown-syntax-propertize)
9827 ;; Font lock.
9828 (setq-local font-lock-defaults nil)
9829 (setq-local font-lock-multiline t)
9830 (setq-local font-lock-extra-managed-props
9831 (append font-lock-extra-managed-props
9832 '(composition display invisible)))
9833 (if markdown-hide-markup
9834 (add-to-invisibility-spec 'markdown-markup)
9835 (remove-from-invisibility-spec 'markdown-markup))
9836 (setq font-lock-defaults
9837 '(markdown-mode-font-lock-keywords-basic
9838 nil nil nil nil
9839 (font-lock-syntactic-face-function . markdown-syntactic-face)))
9840 ;; Wiki links
9841 (markdown-setup-wiki-link-hooks)
9842 ;; Math mode
9843 (when markdown-enable-math (markdown-toggle-math t))
9844 ;; Add a buffer-local hook to reload after file-local variables are read
9845 (add-hook 'hack-local-variables-hook #'markdown-handle-local-variables nil t)
9846 ;; For imenu support
9847 (setq imenu-create-index-function
9848 (if markdown-nested-imenu-heading-index
9849 #'markdown-imenu-create-nested-index
9850 #'markdown-imenu-create-flat-index))
9851 ;; For menu support in XEmacs
9852 (easy-menu-add markdown-mode-menu markdown-mode-map)
9853 ;; Defun movement
9854 (setq-local beginning-of-defun-function #'markdown-beginning-of-defun)
9855 (setq-local end-of-defun-function #'markdown-end-of-defun)
9856 ;; Paragraph filling
9857 (setq-local fill-paragraph-function #'markdown-fill-paragraph)
9858 (setq-local paragraph-start
9859 ;; Should match start of lines that start or separate paragraphs
9860 (mapconcat #'identity
9862 "\f" ; starts with a literal line-feed
9863 "[ \t\f]*$" ; space-only line
9864 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9865 "[ \t]*[*+-][ \t]+" ; unordered list item
9866 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
9867 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
9868 "[ \t]*:[ \t]+" ; definition
9869 "^|" ; table or Pandoc line block
9871 "\\|"))
9872 (setq-local paragraph-separate
9873 ;; Should match lines that separate paragraphs without being
9874 ;; part of any paragraph:
9875 (mapconcat #'identity
9876 '("[ \t\f]*$" ; space-only line
9877 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9878 ;; The following is not ideal, but the Fill customization
9879 ;; options really only handle paragraph-starting prefixes,
9880 ;; not paragraph-ending suffixes:
9881 ".* $" ; line ending in two spaces
9882 "^#+"
9883 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
9884 "\\|"))
9885 (setq-local adaptive-fill-first-line-regexp "\\`[ \t]*[A-Z]?>[ \t]*?\\'")
9886 (setq-local adaptive-fill-regexp "\\s-*")
9887 (setq-local adaptive-fill-function #'markdown-adaptive-fill-function)
9888 (setq-local fill-forward-paragraph-function #'markdown-fill-forward-paragraph)
9889 ;; Outline mode
9890 (setq-local outline-regexp markdown-regex-header)
9891 (setq-local outline-level #'markdown-outline-level)
9892 ;; Cause use of ellipses for invisible text.
9893 (add-to-invisibility-spec '(outline . t))
9894 ;; ElDoc support
9895 (if (eval-when-compile (fboundp 'add-function))
9896 (add-function :before-until (local 'eldoc-documentation-function)
9897 #'markdown-eldoc-function)
9898 (setq-local eldoc-documentation-function #'markdown-eldoc-function))
9899 ;; Inhibiting line-breaking:
9900 ;; Separating out each condition into a separate function so that users can
9901 ;; override if desired (with remove-hook)
9902 (add-hook 'fill-nobreak-predicate
9903 #'markdown-line-is-reference-definition-p nil t)
9904 (add-hook 'fill-nobreak-predicate
9905 #'markdown-pipe-at-bol-p nil t)
9907 ;; Indentation
9908 (setq-local indent-line-function markdown-indent-function)
9910 ;; Flyspell
9911 (setq-local flyspell-generic-check-word-predicate
9912 #'markdown-flyspell-check-word-p)
9914 ;; Electric quoting
9915 (add-hook 'electric-quote-inhibit-functions
9916 #'markdown--inhibit-electric-quote nil :local)
9918 ;; Backwards compatibility with markdown-css-path
9919 (when (boundp 'markdown-css-path)
9920 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
9921 (add-to-list 'markdown-css-paths markdown-css-path))
9923 ;; Prepare hooks for XEmacs compatibility
9924 (when (featurep 'xemacs)
9925 (make-local-hook 'after-change-functions)
9926 (make-local-hook 'font-lock-extend-region-functions)
9927 (make-local-hook 'window-configuration-change-hook))
9929 ;; Make checkboxes buttons
9930 (when markdown-make-gfm-checkboxes-buttons
9931 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
9932 (add-hook 'after-change-functions #'markdown-gfm-checkbox-after-change-function t t)
9933 (add-hook 'change-major-mode-hook #'markdown-remove-gfm-checkbox-overlays t t))
9935 ;; edit-indirect
9936 (add-hook 'edit-indirect-after-commit-functions
9937 #'markdown--edit-indirect-after-commit-function
9938 nil 'local)
9940 ;; Marginalized headings
9941 (when markdown-marginalize-headers
9942 (add-hook 'window-configuration-change-hook
9943 #'markdown-marginalize-update-current nil t))
9945 ;; add live preview export hook
9946 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
9947 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
9949 ;;;###autoload
9950 (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode) t)
9951 ;;;###autoload
9952 (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode) t)
9955 ;;; GitHub Flavored Markdown Mode ============================================
9957 (defvar gfm-mode-hook nil
9958 "Hook run when entering GFM mode.")
9960 (defvar gfm-font-lock-keywords
9961 ;; Basic Markdown features (excluding possibly overridden ones)
9962 markdown-mode-font-lock-keywords-basic
9963 "Default highlighting expressions for GitHub Flavored Markdown mode.")
9965 ;;;###autoload
9966 (define-derived-mode gfm-mode markdown-mode "GFM"
9967 "Major mode for editing GitHub Flavored Markdown files."
9968 (setq markdown-link-space-sub-char "-")
9969 (setq markdown-wiki-link-search-subdirectories t)
9970 (setq-local font-lock-defaults '(gfm-font-lock-keywords))
9971 ;; do the initial link fontification
9972 (markdown-gfm-parse-buffer-for-languages))
9975 ;;; Live Preview Mode ============================================
9976 (define-minor-mode markdown-live-preview-mode
9977 "Toggle native previewing on save for a specific markdown file."
9978 :lighter " MD-Preview"
9979 (if markdown-live-preview-mode
9980 (if (markdown-live-preview-get-filename)
9981 (markdown-display-buffer-other-window (markdown-live-preview-export))
9982 (markdown-live-preview-mode -1)
9983 (user-error "Buffer %s does not visit a file" (current-buffer)))
9984 (markdown-live-preview-remove)))
9987 (provide 'markdown-mode)
9989 ;; Local Variables:
9990 ;; indent-tabs-mode: nil
9991 ;; coding: utf-8
9992 ;; End:
9993 ;;; markdown-mode.el ends here