Font lock for HTML entities
[markdown-mode.git] / markdown-mode.el
blob251883edfad0242e0a598e46248a1dfbb9f0a2f7
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 point
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 This may be a single string or a list of string. In case of a
1303 list, the first one that satisfies `char-displayable-p' will be
1304 used."
1305 :type 'string
1306 :type '(choice
1307 (string :tag "Single blockquote display string")
1308 (repeat :tag "List of possible blockquote display strings" string))
1309 :package-version '(markdown-mode . "2.3"))
1311 (defcustom markdown-hr-display-char
1312 '(?─ ?━ ?-)
1313 "Character for hiding horizontal rule markup.
1314 This may be a single character or a list of characters. In case
1315 of a list, the first one that satisfies `char-displayable-p' will
1316 be used."
1317 :group 'markdown
1318 :type '(choice
1319 (character :tag "Single HR display character")
1320 (repeat :tag "List of possible HR display characters" character))
1321 :package-version '(markdown-mode . "2.3"))
1323 (defcustom markdown-definition-display-char
1324 '(?⁘ ?⁙ ?≡ ?⌑ ?◊ ?:)
1325 "Character for replacing definition list markup.
1326 This may be a single character or a list of characters. In case
1327 of a list, the first one that satisfies `char-displayable-p' will
1328 be used."
1329 :type '(choice
1330 (character :tag "Single definition list character")
1331 (repeat :tag "List of possible definition list characters" character))
1332 :package-version '(markdown-mode . "2.3"))
1334 (defcustom markdown-enable-math nil
1335 "Syntax highlighting for inline LaTeX and itex expressions.
1336 Set this to a non-nil value to turn on math support by default.
1337 Math support can be enabled, disabled, or toggled later using
1338 `markdown-toggle-math' or \\[markdown-toggle-math]."
1339 :group 'markdown
1340 :type 'boolean
1341 :safe 'booleanp)
1342 (make-variable-buffer-local 'markdown-enable-math)
1344 (defcustom markdown-css-paths nil
1345 "URL of CSS file to link to in the output XHTML."
1346 :group 'markdown
1347 :type '(repeat (string :tag "CSS File Path")))
1349 (defcustom markdown-content-type ""
1350 "Content type string for the http-equiv header in XHTML output.
1351 When set to a non-empty string, insert the http-equiv attribute.
1352 Otherwise, this attribute is omitted."
1353 :group 'markdown
1354 :type 'string)
1356 (defcustom markdown-coding-system nil
1357 "Character set string for the http-equiv header in XHTML output.
1358 Defaults to `buffer-file-coding-system' (and falling back to
1359 `iso-8859-1' when not available). Common settings are `utf-8'
1360 and `iso-latin-1'. Use `list-coding-systems' for more choices."
1361 :group 'markdown
1362 :type 'coding-system)
1364 (defcustom markdown-export-kill-buffer t
1365 "Kill output buffer after HTML export.
1366 When non-nil, kill the HTML output buffer after
1367 exporting with `markdown-export'."
1368 :group 'markdown
1369 :type 'boolean
1370 :safe 'booleanp
1371 :package-version '(markdown-mode . "2.4"))
1373 (defcustom markdown-xhtml-header-content ""
1374 "Additional content to include in the XHTML <head> block."
1375 :group 'markdown
1376 :type 'string)
1378 (defcustom markdown-xhtml-standalone-regexp
1379 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
1380 "Regexp indicating whether `markdown-command' output is standalone XHTML."
1381 :group 'markdown
1382 :type 'regexp)
1384 (defcustom markdown-link-space-sub-char "_"
1385 "Character to use instead of spaces when mapping wiki links to filenames."
1386 :group 'markdown
1387 :type 'string)
1389 (defcustom markdown-reference-location 'header
1390 "Position where new reference definitions are inserted in the document."
1391 :group 'markdown
1392 :type '(choice (const :tag "At the end of the document" end)
1393 (const :tag "Immediately after the current block" immediately)
1394 (const :tag "At the end of the subtree" subtree)
1395 (const :tag "Before next header" header)))
1397 (defcustom markdown-footnote-location 'end
1398 "Position where new footnotes are inserted in the document."
1399 :group 'markdown
1400 :type '(choice (const :tag "At the end of the document" end)
1401 (const :tag "Immediately after the current block" immediately)
1402 (const :tag "At the end of the subtree" subtree)
1403 (const :tag "Before next header" header)))
1405 (defcustom markdown-unordered-list-item-prefix " * "
1406 "String inserted before unordered list items."
1407 :group 'markdown
1408 :type 'string)
1410 (defcustom markdown-nested-imenu-heading-index t
1411 "Use nested or flat imenu heading index.
1412 A nested index may provide more natural browsing from the menu,
1413 but a flat list may allow for faster keyboard navigation via tab
1414 completion."
1415 :group 'markdown
1416 :type 'boolean
1417 :safe 'booleanp
1418 :package-version '(markdown-mode . "2.2"))
1420 (defcustom markdown-make-gfm-checkboxes-buttons t
1421 "When non-nil, make GFM checkboxes into buttons."
1422 :group 'markdown
1423 :type 'boolean)
1425 (defcustom markdown-use-pandoc-style-yaml-metadata nil
1426 "When non-nil, allow YAML metadata anywhere in the document."
1427 :group 'markdown
1428 :type 'boolean)
1430 (defcustom markdown-split-window-direction 'any
1431 "Preference for splitting windows for static and live preview.
1432 The default value is 'any, which instructs Emacs to use
1433 `split-window-sensibly' to automatically choose how to split
1434 windows based on the values of `split-width-threshold' and
1435 `split-height-threshold' and the available windows. To force
1436 vertically split (left and right) windows, set this to 'vertical
1437 or 'right. To force horizontally split (top and bottom) windows,
1438 set this to 'horizontal or 'below."
1439 :group 'markdown
1440 :type '(choice (const :tag "Automatic" any)
1441 (const :tag "Right (vertical)" right)
1442 (const :tag "Below (horizontal)" below))
1443 :package-version '(markdown-mode . "2.2"))
1445 (defcustom markdown-live-preview-window-function
1446 'markdown-live-preview-window-eww
1447 "Function to display preview of Markdown output within Emacs.
1448 Function must update the buffer containing the preview and return
1449 the buffer."
1450 :group 'markdown
1451 :type 'function)
1453 (defcustom markdown-live-preview-delete-export 'delete-on-destroy
1454 "Delete exported HTML file when using `markdown-live-preview-export'.
1455 If set to 'delete-on-export, delete on every export. When set to
1456 'delete-on-destroy delete when quitting from command
1457 `markdown-live-preview-mode'. Never delete if set to nil."
1458 :group 'markdown
1459 :type '(choice
1460 (const :tag "Delete on every export" delete-on-export)
1461 (const :tag "Delete when quitting live preview" delete-on-destroy)
1462 (const :tag "Never delete" nil)))
1464 (defcustom markdown-list-indent-width 4
1465 "Depth of indentation for markdown lists.
1466 Used in `markdown-demote-list-item' and
1467 `markdown-promote-list-item'."
1468 :group 'markdown
1469 :type 'integer)
1471 (defcustom markdown-enable-prefix-prompts t
1472 "Display prompts for certain prefix commands.
1473 Set to nil to disable these prompts."
1474 :group 'markdown
1475 :type 'boolean
1476 :safe 'booleanp
1477 :package-version '(markdown-mode . "2.3"))
1479 (defcustom markdown-gfm-additional-languages nil
1480 "Extra languages made available when inserting GFM code blocks.
1481 Language strings must have be trimmed of whitespace and not
1482 contain any curly braces. They may be of arbitrary
1483 capitalization, though."
1484 :group 'markdown
1485 :type '(repeat (string :validate markdown-validate-language-string)))
1487 (defcustom markdown-gfm-use-electric-backquote t
1488 "Use `markdown-electric-backquote' when backquote is hit three times."
1489 :group 'markdown
1490 :type 'boolean)
1492 (defcustom markdown-gfm-downcase-languages t
1493 "If non-nil, downcase suggested languages.
1494 This applies to insertions done with
1495 `markdown-electric-backquote'."
1496 :group 'markdown
1497 :type 'boolean)
1499 (defcustom markdown-edit-code-block-default-mode 'normal-mode
1500 "Default mode to use for editing code blocks.
1501 This mode is used when automatic detection fails, such as for GFM
1502 code blocks with no language specified."
1503 :group 'markdown
1504 :type 'symbol
1505 :package-version '(markdown-mode . "2.4"))
1507 (defcustom markdown-gfm-uppercase-checkbox nil
1508 "If non-nil, use [X] for completed checkboxes, [x] otherwise."
1509 :group 'markdown
1510 :type 'boolean
1511 :safe 'booleanp)
1513 (defcustom markdown-hide-urls nil
1514 "Hide URLs of inline links and reference tags of reference links.
1515 Such URLs will be replaced by a single customizable
1516 character, defined by `markdown-url-compose-char', but are still part
1517 of the buffer. Links can be edited interactively with
1518 \\[markdown-insert-link] or, for example, by deleting the final
1519 parenthesis to remove the invisibility property. You can also
1520 hover your mouse pointer over the link text to see the URL.
1521 Set this to a non-nil value to turn this feature on by default.
1522 You can interactively set the value of this variable by calling
1523 `markdown-toggle-url-hiding', pressing \\[markdown-toggle-url-hiding],
1524 or from the menu Markdown > Links & Images menu."
1525 :group 'markdown
1526 :type 'boolean
1527 :safe 'booleanp
1528 :package-version '(markdown-mode . "2.3"))
1529 (make-variable-buffer-local 'markdown-hide-urls)
1531 (defcustom markdown-translate-filename-function #'identity
1532 "Function to use to translate filenames when following links.
1533 \\<markdown-mode-map>\\[markdown-follow-thing-at-point] and \\[markdown-follow-link-at-point]
1534 call this function with the filename as only argument whenever
1535 they encounter a filename (instead of a URL) to be visited and
1536 use its return value instead of the filename in the link. For
1537 example, if absolute filenames are actually relative to a server
1538 root directory, you can set
1539 `markdown-translate-filename-function' to a function that
1540 prepends the root directory to the given filename."
1541 :group 'markdown
1542 :type 'function
1543 :risky t
1544 :package-version '(markdown-mode . "2.4"))
1547 ;;; Regular Expressions =======================================================
1549 (defconst markdown-regex-comment-start
1550 "<!--"
1551 "Regular expression matches HTML comment opening.")
1553 (defconst markdown-regex-comment-end
1554 "--[ \t]*>"
1555 "Regular expression matches HTML comment closing.")
1557 (defconst markdown-regex-link-inline
1558 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)\\((\\)\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?\\()\\)"
1559 "Regular expression for a [text](file) or an image link ![text](file).
1560 Group 1 matches the leading exclamation point (optional).
1561 Group 2 matches the opening square bracket.
1562 Group 3 matches the text inside the square brackets.
1563 Group 4 matches the closing square bracket.
1564 Group 5 matches the opening parenthesis.
1565 Group 6 matches the URL.
1566 Group 7 matches the title (optional).
1567 Group 8 matches the closing parenthesis.")
1569 (defconst markdown-regex-link-reference
1570 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)[ ]?\\(\\[\\)\\([^]]*?\\)\\(\\]\\)"
1571 "Regular expression for a reference link [text][id].
1572 Group 1 matches the leading exclamation point (optional).
1573 Group 2 matches the opening square bracket for the link text.
1574 Group 3 matches the text inside the square brackets.
1575 Group 4 matches the closing square bracket for the link text.
1576 Group 5 matches the opening square bracket for the reference label.
1577 Group 6 matches the reference label.
1578 Group 7 matches the closing square bracket for the reference label.")
1580 (defconst markdown-regex-reference-definition
1581 "^ \\{0,3\\}\\(\\[\\)\\([^]\n]+?\\)\\(\\]\\)\\(:\\)\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
1582 "Regular expression for a reference definition.
1583 Group 1 matches the opening square bracket.
1584 Group 2 matches the reference label.
1585 Group 3 matches the closing square bracket.
1586 Group 4 matches the colon.
1587 Group 5 matches the URL.
1588 Group 6 matches the title attribute (optional).")
1590 (defconst markdown-regex-footnote
1591 "\\(\\[\\^\\)\\(.+?\\)\\(\\]\\)"
1592 "Regular expression for a footnote marker [^fn].
1593 Group 1 matches the opening square bracket and carat.
1594 Group 2 matches only the label, without the surrounding markup.
1595 Group 3 matches the closing square bracket.")
1597 (defconst markdown-regex-header
1598 "^\\(?:\\([^\r\n\t -].*\\)\n\\(?:\\(=+\\)\\|\\(-+\\)\\)\\|\\(#+[ \t]+\\)\\(.*?\\)\\([ \t]*#*\\)\\)$"
1599 "Regexp identifying Markdown headings.
1600 Group 1 matches the text of a setext heading.
1601 Group 2 matches the underline of a level-1 setext heading.
1602 Group 3 matches the underline of a level-2 setext heading.
1603 Group 4 matches the opening hash marks of an atx heading and whitespace.
1604 Group 5 matches the text, without surrounding whitespace, of an atx heading.
1605 Group 6 matches the closing whitespace and hash marks of an atx heading.")
1607 (defconst markdown-regex-header-setext
1608 "^\\([^\r\n\t -].*\\)\n\\(=+\\|-+\\)$"
1609 "Regular expression for generic setext-style (underline) headers.")
1611 (defconst markdown-regex-header-atx
1612 "^\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1613 "Regular expression for generic atx-style (hash mark) headers.")
1615 (defconst markdown-regex-hr
1616 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1617 "Regular expression for matching Markdown horizontal rules.")
1619 (defconst markdown-regex-code
1620 "\\(?:\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(?:.\\|\n[^\n]\\)*?[^`]\\)\\(\\2\\)\\)\\(?:[^`]\\|\\'\\)"
1621 "Regular expression for matching inline code fragments.
1623 Group 1 matches the entire code fragment including the backquotes.
1624 Group 2 matches the opening backquotes.
1625 Group 3 matches the code fragment itself, without backquotes.
1626 Group 4 matches the closing backquotes.
1628 The leading, unnumbered group ensures that the leading backquote
1629 character is not escaped.
1630 The last group, also unnumbered, requires that the character
1631 following the code fragment is not a backquote.
1632 Note that \\(?:.\\|\n[^\n]\\) matches any character, including newlines,
1633 but not two newlines in a row.")
1635 (defconst markdown-regex-kbd
1636 "\\(<kbd>\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(</kbd>\\)"
1637 "Regular expression for matching <kbd> tags.
1638 Groups 1 and 3 match the opening and closing tags.
1639 Group 2 matches the key sequence.")
1641 (defconst markdown-regex-gfm-code-block-open
1642 "^[[:blank:]]*\\(```\\)\\([[:blank:]]*{?[[:blank:]]*\\)\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$"
1643 "Regular expression matching opening of GFM code blocks.
1644 Group 1 matches the opening three backquotes and any following whitespace.
1645 Group 2 matches the opening brace (optional) and surrounding whitespace.
1646 Group 3 matches the language identifier (optional).
1647 Group 4 matches the info string (optional).
1648 Group 5 matches the closing brace (optional), whitespace, and newline.
1649 Groups need to agree with `markdown-regex-tilde-fence-begin'.")
1651 (defconst markdown-regex-gfm-code-block-close
1652 "^[[:blank:]]*\\(```\\)\\(\\s *?\\)$"
1653 "Regular expression matching closing of GFM code blocks.
1654 Group 1 matches the closing three backquotes.
1655 Group 2 matches any whitespace and the final newline.")
1657 (defconst markdown-regex-pre
1658 "^\\( \\|\t\\).*$"
1659 "Regular expression for matching preformatted text sections.")
1661 (defconst markdown-regex-list
1662 "^\\([ \t]*\\)\\([0-9#]+\\.\\|[\\*\\+:-]\\)\\([ \t]+\\)"
1663 "Regular expression for matching list items.")
1665 (defconst markdown-regex-bold
1666 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1667 "Regular expression for matching bold text.
1668 Group 1 matches the character before the opening asterisk or
1669 underscore, if any, ensuring that it is not a backslash escape.
1670 Group 2 matches the entire expression, including delimiters.
1671 Groups 3 and 5 matches the opening and closing delimiters.
1672 Group 4 matches the text inside the delimiters.")
1674 (defconst markdown-regex-italic
1675 "\\(?:^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t*]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1676 "Regular expression for matching italic text.
1677 The leading unnumbered matches the character before the opening
1678 asterisk or underscore, if any, ensuring that it is not a
1679 backslash escape.
1680 Group 1 matches the entire expression, including delimiters.
1681 Groups 2 and 4 matches the opening and closing delimiters.
1682 Group 3 matches the text inside the delimiters.")
1684 (defconst markdown-regex-strike-through
1685 "\\(^\\|[^\\]\\)\\(\\(~~\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(~~\\)\\)"
1686 "Regular expression for matching strike-through text.
1687 Group 1 matches the character before the opening tilde, if any,
1688 ensuring that it is not a backslash escape.
1689 Group 2 matches the entire expression, including delimiters.
1690 Groups 3 and 5 matches the opening and closing delimiters.
1691 Group 4 matches the text inside the delimiters.")
1693 (defconst markdown-regex-gfm-italic
1694 "\\(?:^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\2\\|[^ ]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1695 "Regular expression for matching italic text in GitHub Flavored Markdown.
1696 Underscores in words are not treated as special.
1697 Group 1 matches the entire expression, including delimiters.
1698 Groups 2 and 4 matches the opening and closing delimiters.
1699 Group 3 matches the text inside the delimiters.")
1701 (defconst markdown-regex-blockquote
1702 "^[ \t]*\\([A-Z]?>\\)\\([ \t]*\\)\\(.*\\)$"
1703 "Regular expression for matching blockquote lines.
1704 Also accounts for a potential capital letter preceding the angle
1705 bracket, for use with Leanpub blocks (asides, warnings, info
1706 blocks, etc.).
1707 Group 1 matches the leading angle bracket.
1708 Group 2 matches the separating whitespace.
1709 Group 3 matches the text.")
1711 (defconst markdown-regex-line-break
1712 "[^ \n\t][ \t]*\\( \\)$"
1713 "Regular expression for matching line breaks.")
1715 (defconst markdown-regex-wiki-link
1716 "\\(?:^\\|[^\\]\\)\\(\\(\\[\\[\\)\\([^]|]+\\)\\(?:\\(|\\)\\([^]]+\\)\\)?\\(\\]\\]\\)\\)"
1717 "Regular expression for matching wiki links.
1718 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1719 wiki links of the form [[PageName|link text]].
1720 The meanings of the first and second components depend
1721 on the value of `markdown-wiki-link-alias-first'.
1723 Group 1 matches the entire link.
1724 Group 2 matches the opening square brackets.
1725 Group 3 matches the first component of the wiki link.
1726 Group 4 matches the pipe separator, when present.
1727 Group 5 matches the second component of the wiki link, when present.
1728 Group 6 matches the closing square brackets.")
1730 (defconst markdown-regex-uri
1731 (concat "\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+\\)")
1732 "Regular expression for matching inline URIs.")
1734 (defconst markdown-regex-angle-uri
1735 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1736 "Regular expression for matching inline URIs in angle brackets.")
1738 (defconst markdown-regex-email
1739 "<\\(\\(?:\\sw\\|\\s_\\|\\s.\\)+@\\(?:\\sw\\|\\s_\\|\\s.\\)+\\)>"
1740 "Regular expression for matching inline email addresses.")
1742 (defsubst markdown-make-regex-link-generic ()
1743 "Make regular expression for matching any recognized link."
1744 (concat "\\(?:" markdown-regex-link-inline
1745 (when markdown-enable-wiki-links
1746 (concat "\\|" markdown-regex-wiki-link))
1747 "\\|" markdown-regex-link-reference
1748 "\\|" markdown-regex-angle-uri "\\)"))
1750 (defconst markdown-regex-gfm-checkbox
1751 " \\(\\[[ xX]\\]\\) "
1752 "Regular expression for matching GFM checkboxes.
1753 Group 1 matches the text to become a button.")
1755 (defconst markdown-regex-block-separator
1756 "\n[\n\t\f ]*\n"
1757 "Regular expression for matching block boundaries.")
1759 (defconst markdown-regex-block-separator-noindent
1760 (concat "\\(\\`\\|\\(" markdown-regex-block-separator "\\)[^\n\t\f ]\\)")
1761 "Regexp for block separators before lines with no indentation.")
1763 (defconst markdown-regex-math-inline-single
1764 "\\(?:^\\|[^\\]\\)\\(\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\)"
1765 "Regular expression for itex $..$ math mode expressions.
1766 Groups 1 and 3 match the opening and closing dollar signs.
1767 Group 2 matches the mathematical expression contained within.")
1769 (defconst markdown-regex-math-inline-double
1770 "\\(?:^\\|[^\\]\\)\\(\\$\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\$\\)"
1771 "Regular expression for itex $$..$$ math mode expressions.
1772 Groups 1 and 3 match opening and closing dollar signs.
1773 Group 2 matches the mathematical expression contained within.")
1775 (defconst markdown-regex-math-display
1776 (rx line-start
1777 (group (group (repeat 1 2 "\\")) "[")
1778 (group (*? anything))
1779 (group (backref 2) "]")
1780 line-end)
1781 "Regular expression for \[..\] or \\[..\\] display math.
1782 Groups 1 and 4 match the opening and closing markup.
1783 Group 3 matches the mathematical expression contained within.
1784 Group 2 matches the opening slashes, and is used internally to
1785 match the closing slashes.")
1787 (defsubst markdown-make-tilde-fence-regex (num-tildes &optional end-of-line)
1788 "Return regexp matching a tilde code fence at least NUM-TILDES long.
1789 END-OF-LINE is the regexp construct to indicate end of line; $ if
1790 missing."
1791 (format "%s%d%s%s" "^[[:blank:]]*\\([~]\\{" num-tildes ",\\}\\)"
1792 (or end-of-line "$")))
1794 (defconst markdown-regex-tilde-fence-begin
1795 (markdown-make-tilde-fence-regex
1796 3 "\\([[:blank:]]*{?\\)[[:blank:]]*\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$")
1797 "Regular expression for matching tilde-fenced code blocks.
1798 Group 1 matches the opening tildes.
1799 Group 2 matches (optional) opening brace and surrounding whitespace.
1800 Group 3 matches the language identifier (optional).
1801 Group 4 matches the info string (optional).
1802 Group 5 matches the closing brace (optional) and any surrounding whitespace.
1803 Groups need to agree with `markdown-regex-gfm-code-block-open'.")
1805 (defconst markdown-regex-declarative-metadata
1806 "^\\([[:alpha:]][[:alpha:] _-]*?\\)\\([:=][ \t]*\\)\\(.*\\)$"
1807 "Regular expression for matching declarative metadata statements.
1808 This matches MultiMarkdown metadata as well as YAML and TOML
1809 assignments such as the following:
1811 variable: value
1815 variable = value")
1817 (defconst markdown-regex-pandoc-metadata
1818 "^\\(%\\)\\([ \t]*\\)\\(.*\\(?:\n[ \t]+.*\\)*\\)"
1819 "Regular expression for matching Pandoc metadata.")
1821 (defconst markdown-regex-yaml-metadata-border
1822 "\\(-\\{3\\}\\)$"
1823 "Regular expression for matching YAML metadata.")
1825 (defconst markdown-regex-yaml-pandoc-metadata-end-border
1826 "^\\(\\.\\{3\\}\\|\\-\\{3\\}\\)$"
1827 "Regular expression for matching YAML metadata end borders.")
1829 (defsubst markdown-get-yaml-metadata-start-border ()
1830 "Return YAML metadata start border depending upon whether Pandoc is used."
1831 (concat
1832 (if markdown-use-pandoc-style-yaml-metadata "^" "\\`")
1833 markdown-regex-yaml-metadata-border))
1835 (defsubst markdown-get-yaml-metadata-end-border (_)
1836 "Return YAML metadata end border depending upon whether Pandoc is used."
1837 (if markdown-use-pandoc-style-yaml-metadata
1838 markdown-regex-yaml-pandoc-metadata-end-border
1839 markdown-regex-yaml-metadata-border))
1841 (defconst markdown-regex-inline-attributes
1842 "[ \t]*\\({:?\\)[ \t]*\\(\\(#[[:alpha:]_.:-]+\\|\\.[[:alpha:]_.:-]+\\|\\w+=['\"]?[^\n'\"]*['\"]?\\),?[ \t]*\\)+\\(}\\)[ \t]*$"
1843 "Regular expression for matching inline identifiers or attribute lists.
1844 Compatible with Pandoc, Python Markdown, PHP Markdown Extra, and Leanpub.")
1846 (defconst markdown-regex-leanpub-sections
1847 (concat
1848 "^\\({\\)\\("
1849 (regexp-opt '("frontmatter" "mainmatter" "backmatter" "appendix" "pagebreak"))
1850 "\\)\\(}\\)[ \t]*\n")
1851 "Regular expression for Leanpub section markers and related syntax.")
1853 (defconst markdown-regex-sub-superscript
1854 "\\(?:^\\|[^\\~^]\\)\\(\\([~^]\\)\\([[:alnum:]]+\\)\\(\\2\\)\\)"
1855 "The regular expression matching a sub- or superscript.
1856 The leading un-numbered group matches the character before the
1857 opening tilde or carat, if any, ensuring that it is not a
1858 backslash escape, carat, or tilde.
1859 Group 1 matches the entire expression, including markup.
1860 Group 2 matches the opening markup--a tilde or carat.
1861 Group 3 matches the text inside the delimiters.
1862 Group 4 matches the closing markup--a tilde or carat.")
1864 (defconst markdown-regex-include
1865 "^\\(<<\\)\\(?:\\(\\[\\)\\(.*\\)\\(\\]\\)\\)?\\(?:\\((\\)\\(.*\\)\\()\\)\\)?\\(?:\\({\\)\\(.*\\)\\(}\\)\\)?$"
1866 "Regular expression matching common forms of include syntax.
1867 Marked 2, Leanpub, and other processors support some of these forms:
1869 <<[sections/section1.md]
1870 <<(folder/filename)
1871 <<[Code title](folder/filename)
1872 <<{folder/raw_file.html}
1874 Group 1 matches the opening two angle brackets.
1875 Groups 2-4 match the opening square bracket, the text inside,
1876 and the closing square bracket, respectively.
1877 Groups 5-7 match the opening parenthesis, the text inside, and
1878 the closing parenthesis.
1879 Groups 8-10 match the opening brace, the text inside, and the brace.")
1881 (defconst markdown-regex-pandoc-inline-footnote
1882 "\\(\\^\\)\\(\\[\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(\\]\\)"
1883 "Regular expression for Pandoc inline footnote^[footnote text].
1884 Group 1 matches the opening caret.
1885 Group 2 matches the opening square bracket.
1886 Group 3 matches the footnote text, without the surrounding markup.
1887 Group 4 matches the closing square bracket.")
1889 (defconst markdown-regex-html-entity
1890 "\\(&#?[[:alnum:]]+;\\)"
1891 "Regular expression for matching HTML entities.")
1894 ;;; Syntax ====================================================================
1896 (defsubst markdown-in-comment-p (&optional pos)
1897 "Return non-nil if POS is in a comment.
1898 If POS is not given, use point instead."
1899 (nth 4 (syntax-ppss pos)))
1901 (defun markdown-syntax-propertize-extend-region (start end)
1902 "Extend START to END region to include an entire block of text.
1903 This helps improve syntax analysis for block constructs.
1904 Returns a cons (NEW-START . NEW-END) or nil if no adjustment should be made.
1905 Function is called repeatedly until it returns nil. For details, see
1906 `syntax-propertize-extend-region-functions'."
1907 (save-match-data
1908 (save-excursion
1909 (let* ((new-start (progn (goto-char start)
1910 (skip-chars-forward "\n")
1911 (if (re-search-backward "\n\n" nil t)
1912 (min start (match-end 0))
1913 (point-min))))
1914 (new-end (progn (goto-char end)
1915 (skip-chars-backward "\n")
1916 (if (re-search-forward "\n\n" nil t)
1917 (max end (match-beginning 0))
1918 (point-max))))
1919 (code-match (markdown-code-block-at-pos new-start))
1920 (new-start (or (and code-match (cl-first code-match)) new-start))
1921 (code-match (and (< end (point-max)) (markdown-code-block-at-pos end)))
1922 (new-end (or (and code-match (cl-second code-match)) new-end)))
1923 (unless (and (eq new-start start) (eq new-end end))
1924 (cons new-start (min new-end (point-max))))))))
1926 (defun markdown-font-lock-extend-region-function (start end _)
1927 "Used in `jit-lock-after-change-extend-region-functions'.
1928 Delegates to `markdown-syntax-propertize-extend-region'. START
1929 and END are the previous region to refontify."
1930 (let ((res (markdown-syntax-propertize-extend-region start end)))
1931 (when res
1932 ;; syntax-propertize-function is not called when character at
1933 ;; (point-max) is deleted, but font-lock-extend-region-functions
1934 ;; are called. Force a syntax property update in that case.
1935 (when (= end (point-max))
1936 ;; This function is called in a buffer modification hook.
1937 ;; `markdown-syntax-propertize' doesn't save the match data,
1938 ;; so we have to do it here.
1939 (save-match-data
1940 (markdown-syntax-propertize (car res) (cdr res))))
1941 (setq jit-lock-start (car res)
1942 jit-lock-end (cdr res)))))
1944 (defun markdown-syntax-propertize-pre-blocks (start end)
1945 "Match preformatted text blocks from START to END."
1946 (save-excursion
1947 (goto-char start)
1948 (let ((levels (markdown-calculate-list-levels))
1949 indent pre-regexp close-regexp open close)
1950 (while (and (< (point) end) (not close))
1951 ;; Search for a region with sufficient indentation
1952 (if (null levels)
1953 (setq indent 1)
1954 (setq indent (1+ (length levels))))
1955 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1956 (setq close-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1958 (cond
1959 ;; If not at the beginning of a line, move forward
1960 ((not (bolp)) (forward-line))
1961 ;; Move past blank lines
1962 ((markdown-cur-line-blank) (forward-line))
1963 ;; At headers and horizontal rules, reset levels
1964 ((markdown-new-baseline) (forward-line) (setq levels nil))
1965 ;; If the current line has sufficient indentation, mark out pre block
1966 ;; The opening should be preceded by a blank line.
1967 ((and (looking-at pre-regexp)
1968 (markdown-prev-line-blank-p))
1969 (setq open (match-beginning 0))
1970 (while (and (or (looking-at-p pre-regexp) (markdown-cur-line-blank))
1971 (not (eobp)))
1972 (forward-line))
1973 (skip-syntax-backward "-")
1974 (setq close (point)))
1975 ;; If current line has a list marker, update levels, move to end of block
1976 ((looking-at markdown-regex-list)
1977 (setq levels (markdown-update-list-levels
1978 (match-string 2) (current-indentation) levels))
1979 (markdown-end-of-text-block))
1980 ;; If this is the end of the indentation level, adjust levels accordingly.
1981 ;; Only match end of indentation level if levels is not the empty list.
1982 ((and (car levels) (looking-at-p close-regexp))
1983 (setq levels (markdown-update-list-levels
1984 nil (current-indentation) levels))
1985 (markdown-end-of-text-block))
1986 (t (markdown-end-of-text-block))))
1988 (when (and open close)
1989 ;; Set text property data
1990 (put-text-property open close 'markdown-pre (list open close))
1991 ;; Recursively search again
1992 (markdown-syntax-propertize-pre-blocks (point) end)))))
1994 (defconst markdown-fenced-block-pairs
1995 `(((,markdown-regex-tilde-fence-begin markdown-tilde-fence-begin)
1996 (markdown-make-tilde-fence-regex markdown-tilde-fence-end)
1997 markdown-fenced-code)
1998 ((markdown-get-yaml-metadata-start-border markdown-yaml-metadata-begin)
1999 (markdown-get-yaml-metadata-end-border markdown-yaml-metadata-end)
2000 markdown-yaml-metadata-section)
2001 ((,markdown-regex-gfm-code-block-open markdown-gfm-block-begin)
2002 (,markdown-regex-gfm-code-block-close markdown-gfm-block-end)
2003 markdown-gfm-code))
2004 "Mapping of regular expressions to \"fenced-block\" constructs.
2005 These constructs are distinguished by having a distinctive start
2006 and end pattern, both of which take up an entire line of text,
2007 but no special pattern to identify text within the fenced
2008 blocks (unlike blockquotes and indented-code sections).
2010 Each element within this list takes the form:
2012 ((START-REGEX-OR-FUN START-PROPERTY)
2013 (END-REGEX-OR-FUN END-PROPERTY)
2014 MIDDLE-PROPERTY)
2016 Each *-REGEX-OR-FUN element can be a regular expression as a string, or a
2017 function which evaluates to same. Functions for START-REGEX-OR-FUN accept no
2018 arguments, but functions for END-REGEX-OR-FUN accept a single numerical argument
2019 which is the length of the first group of the START-REGEX-OR-FUN match, which
2020 can be ignored if unnecessary. `markdown-maybe-funcall-regexp' is used to
2021 evaluate these into \"real\" regexps.
2023 The *-PROPERTY elements are the text properties applied to each part of the
2024 block construct when it is matched using
2025 `markdown-syntax-propertize-fenced-block-constructs'. START-PROPERTY is applied
2026 to the text matching START-REGEX-OR-FUN, END-PROPERTY to END-REGEX-OR-FUN, and
2027 MIDDLE-PROPERTY to the text in between the two. The value of *-PROPERTY is the
2028 `match-data' when the regexp was matched to the text. In the case of
2029 MIDDLE-PROPERTY, the value is a false match data of the form '(begin end), with
2030 begin and end set to the edges of the \"middle\" text. This makes fontification
2031 easier.")
2033 (defun markdown-text-property-at-point (prop)
2034 (get-text-property (point) prop))
2036 (defsubst markdown-maybe-funcall-regexp (object &optional arg)
2037 (cond ((functionp object)
2038 (if arg (funcall object arg) (funcall object)))
2039 ((stringp object) object)
2040 (t (error "Object cannot be turned into regex"))))
2042 (defsubst markdown-get-start-fence-regexp ()
2043 "Return regexp to find all \"start\" sections of fenced block constructs.
2044 Which construct is actually contained in the match must be found separately."
2045 (mapconcat
2046 #'identity
2047 (mapcar (lambda (entry) (markdown-maybe-funcall-regexp (caar entry)))
2048 markdown-fenced-block-pairs)
2049 "\\|"))
2051 (defun markdown-get-fenced-block-begin-properties ()
2052 (cl-mapcar (lambda (entry) (cl-cadar entry)) markdown-fenced-block-pairs))
2054 (defun markdown-get-fenced-block-end-properties ()
2055 (cl-mapcar (lambda (entry) (cl-cadadr entry)) markdown-fenced-block-pairs))
2057 (defun markdown-get-fenced-block-middle-properties ()
2058 (cl-mapcar #'cl-third markdown-fenced-block-pairs))
2060 (defun markdown-find-previous-prop (prop &optional lim)
2061 "Find previous place where property PROP is non-nil, up to LIM.
2062 Return a cons of (pos . property). pos is point if point contains
2063 non-nil PROP."
2064 (let ((res
2065 (if (get-text-property (point) prop) (point)
2066 (previous-single-property-change
2067 (point) prop nil (or lim (point-min))))))
2068 (when (and (not (get-text-property res prop))
2069 (> res (point-min))
2070 (get-text-property (1- res) prop))
2071 (cl-decf res))
2072 (when (and res (get-text-property res prop)) (cons res prop))))
2074 (defun markdown-find-next-prop (prop &optional lim)
2075 "Find next place where property PROP is non-nil, up to LIM.
2076 Return a cons of (POS . PROPERTY) where POS is point if point
2077 contains non-nil PROP."
2078 (let ((res
2079 (if (get-text-property (point) prop) (point)
2080 (next-single-property-change
2081 (point) prop nil (or lim (point-max))))))
2082 (when (and res (get-text-property res prop)) (cons res prop))))
2084 (defun markdown-min-of-seq (map-fn seq)
2085 "Apply MAP-FN to SEQ and return element of SEQ with minimum value of MAP-FN."
2086 (cl-loop for el in seq
2087 with min = 1.0e+INF ; infinity
2088 with min-el = nil
2089 do (let ((res (funcall map-fn el)))
2090 (when (< res min)
2091 (setq min res)
2092 (setq min-el el)))
2093 finally return min-el))
2095 (defun markdown-max-of-seq (map-fn seq)
2096 "Apply MAP-FN to SEQ and return element of SEQ with maximum value of MAP-FN."
2097 (cl-loop for el in seq
2098 with max = -1.0e+INF ; negative infinity
2099 with max-el = nil
2100 do (let ((res (funcall map-fn el)))
2101 (when (and res (> res max))
2102 (setq max res)
2103 (setq max-el el)))
2104 finally return max-el))
2106 (defun markdown-find-previous-block ()
2107 "Find previous block.
2108 Detect whether `markdown-syntax-propertize-fenced-block-constructs' was
2109 unable to propertize the entire block, but was able to propertize the beginning
2110 of the block. If so, return a cons of (pos . property) where the beginning of
2111 the block was propertized."
2112 (let ((start-pt (point))
2113 (closest-open
2114 (markdown-max-of-seq
2115 #'car
2116 (cl-remove-if
2117 #'null
2118 (cl-mapcar
2119 #'markdown-find-previous-prop
2120 (markdown-get-fenced-block-begin-properties))))))
2121 (when closest-open
2122 (let* ((length-of-open-match
2123 (let ((match-d
2124 (get-text-property (car closest-open) (cdr closest-open))))
2125 (- (cl-fourth match-d) (cl-third match-d))))
2126 (end-regexp
2127 (markdown-maybe-funcall-regexp
2128 (cl-caadr
2129 (cl-find-if
2130 (lambda (entry) (eq (cl-cadar entry) (cdr closest-open)))
2131 markdown-fenced-block-pairs))
2132 length-of-open-match))
2133 (end-prop-loc
2134 (save-excursion
2135 (save-match-data
2136 (goto-char (car closest-open))
2137 (and (re-search-forward end-regexp start-pt t)
2138 (match-beginning 0))))))
2139 (and (not end-prop-loc) closest-open)))))
2141 (defun markdown-get-fenced-block-from-start (prop)
2142 "Return limits of an enclosing fenced block from its start, using PROP.
2143 Return value is a list usable as `match-data'."
2144 (catch 'no-rest-of-block
2145 (let* ((correct-entry
2146 (cl-find-if
2147 (lambda (entry) (eq (cl-cadar entry) prop))
2148 markdown-fenced-block-pairs))
2149 (begin-of-begin (cl-first (markdown-text-property-at-point prop)))
2150 (middle-prop (cl-third correct-entry))
2151 (end-prop (cl-cadadr correct-entry))
2152 (end-of-end
2153 (save-excursion
2154 (goto-char (match-end 0)) ; end of begin
2155 (unless (eobp) (forward-char))
2156 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
2157 (if (not mid-prop-v) ; no middle
2158 (progn
2159 ;; try to find end by advancing one
2160 (let ((end-prop-v
2161 (markdown-text-property-at-point end-prop)))
2162 (if end-prop-v (cl-second end-prop-v)
2163 (throw 'no-rest-of-block nil))))
2164 (set-match-data mid-prop-v)
2165 (goto-char (match-end 0)) ; end of middle
2166 (beginning-of-line) ; into end
2167 (cl-second (markdown-text-property-at-point end-prop)))))))
2168 (list begin-of-begin end-of-end))))
2170 (defun markdown-get-fenced-block-from-middle (prop)
2171 "Return limits of an enclosing fenced block from its middle, using PROP.
2172 Return value is a list usable as `match-data'."
2173 (let* ((correct-entry
2174 (cl-find-if
2175 (lambda (entry) (eq (cl-third entry) prop))
2176 markdown-fenced-block-pairs))
2177 (begin-prop (cl-cadar correct-entry))
2178 (begin-of-begin
2179 (save-excursion
2180 (goto-char (match-beginning 0))
2181 (unless (bobp) (forward-line -1))
2182 (beginning-of-line)
2183 (cl-first (markdown-text-property-at-point begin-prop))))
2184 (end-prop (cl-cadadr correct-entry))
2185 (end-of-end
2186 (save-excursion
2187 (goto-char (match-end 0))
2188 (beginning-of-line)
2189 (cl-second (markdown-text-property-at-point end-prop)))))
2190 (list begin-of-begin end-of-end)))
2192 (defun markdown-get-fenced-block-from-end (prop)
2193 "Return limits of an enclosing fenced block from its end, using PROP.
2194 Return value is a list usable as `match-data'."
2195 (let* ((correct-entry
2196 (cl-find-if
2197 (lambda (entry) (eq (cl-cadadr entry) prop))
2198 markdown-fenced-block-pairs))
2199 (end-of-end (cl-second (markdown-text-property-at-point prop)))
2200 (middle-prop (cl-third correct-entry))
2201 (begin-prop (cl-cadar correct-entry))
2202 (begin-of-begin
2203 (save-excursion
2204 (goto-char (match-beginning 0)) ; beginning of end
2205 (unless (bobp) (backward-char)) ; into middle
2206 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
2207 (if (not mid-prop-v)
2208 (progn
2209 (beginning-of-line)
2210 (cl-first (markdown-text-property-at-point begin-prop)))
2211 (set-match-data mid-prop-v)
2212 (goto-char (match-beginning 0)) ; beginning of middle
2213 (unless (bobp) (forward-line -1)) ; into beginning
2214 (beginning-of-line)
2215 (cl-first (markdown-text-property-at-point begin-prop)))))))
2216 (list begin-of-begin end-of-end)))
2218 (defun markdown-get-enclosing-fenced-block-construct (&optional pos)
2219 "Get \"fake\" match data for block enclosing POS.
2220 Returns fake match data which encloses the start, middle, and end
2221 of the block construct enclosing POS, if it exists. Used in
2222 `markdown-code-block-at-pos'."
2223 (save-excursion
2224 (when pos (goto-char pos))
2225 (beginning-of-line)
2226 (car
2227 (cl-remove-if
2228 #'null
2229 (cl-mapcar
2230 (lambda (fun-and-prop)
2231 (cl-destructuring-bind (fun prop) fun-and-prop
2232 (when prop
2233 (save-match-data
2234 (set-match-data (markdown-text-property-at-point prop))
2235 (funcall fun prop)))))
2236 `((markdown-get-fenced-block-from-start
2237 ,(cl-find-if
2238 #'markdown-text-property-at-point
2239 (markdown-get-fenced-block-begin-properties)))
2240 (markdown-get-fenced-block-from-middle
2241 ,(cl-find-if
2242 #'markdown-text-property-at-point
2243 (markdown-get-fenced-block-middle-properties)))
2244 (markdown-get-fenced-block-from-end
2245 ,(cl-find-if
2246 #'markdown-text-property-at-point
2247 (markdown-get-fenced-block-end-properties)))))))))
2249 (defun markdown-propertize-end-match (reg end fence-spec middle-begin)
2250 "Get match for REG up to END, if exists, and propertize appropriately.
2251 FENCE-SPEC is an entry in `markdown-fenced-block-pairs' and
2252 MIDDLE-BEGIN is the start of the \"middle\" section of the block."
2253 (when (re-search-forward reg end t)
2254 (let ((close-begin (match-beginning 0)) ; Start of closing line.
2255 (close-end (match-end 0)) ; End of closing line.
2256 (close-data (match-data t))) ; Match data for closing line.
2257 ;; Propertize middle section of fenced block.
2258 (put-text-property middle-begin close-begin
2259 (cl-third fence-spec)
2260 (list middle-begin close-begin))
2261 ;; Propertize closing line of fenced block.
2262 (put-text-property close-begin close-end
2263 (cl-cadadr fence-spec) close-data))))
2265 (defun markdown-syntax-propertize-fenced-block-constructs (start end)
2266 "Propertize according to `markdown-fenced-block-pairs' from START to END.
2267 If unable to propertize an entire block (if the start of a block is within START
2268 and END, but the end of the block is not), propertize the start section of a
2269 block, then in a subsequent call propertize both middle and end by finding the
2270 start which was previously propertized."
2271 (let ((start-reg (markdown-get-start-fence-regexp)))
2272 (save-excursion
2273 (goto-char start)
2274 ;; start from previous unclosed block, if exists
2275 (let ((prev-begin-block (markdown-find-previous-block)))
2276 (when prev-begin-block
2277 (let* ((correct-entry
2278 (cl-find-if (lambda (entry)
2279 (eq (cdr prev-begin-block) (cl-cadar entry)))
2280 markdown-fenced-block-pairs))
2281 (enclosed-text-start (1+ (car prev-begin-block)))
2282 (start-length
2283 (save-excursion
2284 (goto-char (car prev-begin-block))
2285 (string-match
2286 (markdown-maybe-funcall-regexp
2287 (caar correct-entry))
2288 (buffer-substring
2289 (point-at-bol) (point-at-eol)))
2290 (- (match-end 1) (match-beginning 1))))
2291 (end-reg (markdown-maybe-funcall-regexp
2292 (cl-caadr correct-entry) start-length)))
2293 (markdown-propertize-end-match
2294 end-reg end correct-entry enclosed-text-start))))
2295 ;; find all new blocks within region
2296 (while (re-search-forward start-reg end t)
2297 ;; we assume the opening constructs take up (only) an entire line,
2298 ;; so we re-check the current line
2299 (let* ((cur-line (buffer-substring (point-at-bol) (point-at-eol)))
2300 ;; find entry in `markdown-fenced-block-pairs' corresponding
2301 ;; to regex which was matched
2302 (correct-entry
2303 (cl-find-if
2304 (lambda (fenced-pair)
2305 (string-match-p
2306 (markdown-maybe-funcall-regexp (caar fenced-pair))
2307 cur-line))
2308 markdown-fenced-block-pairs))
2309 (enclosed-text-start
2310 (save-excursion (1+ (point-at-eol))))
2311 (end-reg
2312 (markdown-maybe-funcall-regexp
2313 (cl-caadr correct-entry)
2314 (if (and (match-beginning 1) (match-end 1))
2315 (- (match-end 1) (match-beginning 1))
2316 0))))
2317 ;; get correct match data
2318 (save-excursion
2319 (beginning-of-line)
2320 (re-search-forward
2321 (markdown-maybe-funcall-regexp (caar correct-entry))
2322 (point-at-eol)))
2323 ;; mark starting, even if ending is outside of region
2324 (put-text-property (match-beginning 0) (match-end 0)
2325 (cl-cadar correct-entry) (match-data t))
2326 (markdown-propertize-end-match
2327 end-reg end correct-entry enclosed-text-start))))))
2329 (defun markdown-syntax-propertize-blockquotes (start end)
2330 "Match blockquotes from START to END."
2331 (save-excursion
2332 (goto-char start)
2333 (while (and (re-search-forward markdown-regex-blockquote end t)
2334 (not (markdown-code-block-at-pos (match-beginning 0))))
2335 (put-text-property (match-beginning 0) (match-end 0)
2336 'markdown-blockquote
2337 (match-data t)))))
2339 (defun markdown-syntax-propertize-hrs (start end)
2340 "Match horizontal rules from START to END."
2341 (save-excursion
2342 (goto-char start)
2343 (while (re-search-forward markdown-regex-hr end t)
2344 (unless (or (markdown-on-heading-p)
2345 (markdown-code-block-at-point-p))
2346 (put-text-property (match-beginning 0) (match-end 0)
2347 'markdown-hr
2348 (match-data t))))))
2350 (defun markdown-syntax-propertize-yaml-metadata (start end)
2351 (save-excursion
2352 (goto-char start)
2353 (cl-loop
2354 while (re-search-forward markdown-regex-declarative-metadata end t)
2355 do (when (get-text-property (match-beginning 0)
2356 'markdown-yaml-metadata-section)
2357 (put-text-property (match-beginning 1) (match-end 1)
2358 'markdown-metadata-key (match-data t))
2359 (put-text-property (match-beginning 2) (match-end 2)
2360 'markdown-metadata-markup (match-data t))
2361 (put-text-property (match-beginning 3) (match-end 3)
2362 'markdown-metadata-value (match-data t))))))
2364 (defun markdown-syntax-propertize-headings (start end)
2365 "Match headings of type SYMBOL with REGEX from START to END."
2366 (goto-char start)
2367 (while (re-search-forward markdown-regex-header end t)
2368 (unless (markdown-code-block-at-pos (match-beginning 0))
2369 (put-text-property
2370 (match-beginning 0) (match-end 0) 'markdown-heading
2371 (match-data t))
2372 (put-text-property
2373 (match-beginning 0) (match-end 0)
2374 (cond ((match-string-no-properties 2) 'markdown-heading-1-setext)
2375 ((match-string-no-properties 3) 'markdown-heading-2-setext)
2376 (t (let ((atx-level (length (markdown-trim-whitespace
2377 (match-string-no-properties 4)))))
2378 (intern (format "markdown-heading-%d-atx" atx-level)))))
2379 (match-data t)))))
2381 (defun markdown-syntax-propertize-comments (start end)
2382 "Match HTML comments from the START to END."
2383 (let* ((in-comment (markdown-in-comment-p)))
2384 (goto-char start)
2385 (cond
2386 ;; Comment start
2387 ((and (not in-comment)
2388 (re-search-forward markdown-regex-comment-start end t)
2389 (not (markdown-inline-code-at-point-p))
2390 (not (markdown-code-block-at-point-p)))
2391 (let ((open-beg (match-beginning 0)))
2392 (put-text-property open-beg (1+ open-beg)
2393 'syntax-table (string-to-syntax "<"))
2394 (markdown-syntax-propertize-comments
2395 (min (1+ (match-end 0)) end (point-max)) end)))
2396 ;; Comment end
2397 ((and in-comment
2398 (re-search-forward markdown-regex-comment-end end t))
2399 (put-text-property (1- (match-end 0)) (match-end 0)
2400 'syntax-table (string-to-syntax ">"))
2401 (markdown-syntax-propertize-comments
2402 (min (1+ (match-end 0)) end (point-max)) end))
2403 ;; Nothing found
2404 (t nil))))
2406 (defvar markdown--syntax-properties
2407 (list 'markdown-tilde-fence-begin nil
2408 'markdown-tilde-fence-end nil
2409 'markdown-fenced-code nil
2410 'markdown-yaml-metadata-begin nil
2411 'markdown-yaml-metadata-end nil
2412 'markdown-yaml-metadata-section nil
2413 'markdown-gfm-block-begin nil
2414 'markdown-gfm-block-end nil
2415 'markdown-gfm-code nil
2416 'markdown-pre nil
2417 'markdown-blockquote nil
2418 'markdown-hr nil
2419 'markdown-heading nil
2420 'markdown-heading-1-setext nil
2421 'markdown-heading-2-setext nil
2422 'markdown-heading-1-atx nil
2423 'markdown-heading-2-atx nil
2424 'markdown-heading-3-atx nil
2425 'markdown-heading-4-atx nil
2426 'markdown-heading-5-atx nil
2427 'markdown-heading-6-atx nil
2428 'markdown-metadata-key nil
2429 'markdown-metadata-value nil
2430 'markdown-metadata-markup nil)
2431 "Property list of all Markdown syntactic properties.")
2433 (defun markdown-syntax-propertize (start end)
2434 "Function used as `syntax-propertize-function'.
2435 START and END delimit region to propertize."
2436 (with-silent-modifications
2437 (save-excursion
2438 (remove-text-properties start end markdown--syntax-properties)
2439 (markdown-syntax-propertize-fenced-block-constructs start end)
2440 (markdown-syntax-propertize-yaml-metadata start end)
2441 (markdown-syntax-propertize-pre-blocks start end)
2442 (markdown-syntax-propertize-blockquotes start end)
2443 (markdown-syntax-propertize-headings start end)
2444 (markdown-syntax-propertize-hrs start end)
2445 (markdown-syntax-propertize-comments start end))))
2448 ;;; Markup Hiding
2450 (defconst markdown-markup-properties
2451 '(face markdown-markup-face invisible markdown-markup)
2452 "List of properties and values to apply to markup.")
2454 (defconst markdown-language-keyword-properties
2455 '(face markdown-language-keyword-face invisible markdown-markup)
2456 "List of properties and values to apply to code block language names.")
2458 (defconst markdown-language-info-properties
2459 '(face markdown-language-info-face invisible markdown-markup)
2460 "List of properties and values to apply to code block language info strings.")
2462 (defconst markdown-include-title-properties
2463 '(face markdown-link-title-face invisible markdown-markup)
2464 "List of properties and values to apply to included code titles.")
2466 (defconst markdown-inline-footnote-properties
2467 '(face nil display ((raise 0.2) (height 0.8)))
2468 "Properties to apply to footnote markers and inline footnotes.")
2470 (defcustom markdown-hide-markup nil
2471 "Determines whether markup in the buffer will be hidden.
2472 When set to nil, all markup is displayed in the buffer as it
2473 appears in the file. An exception is when `markdown-hide-urls'
2474 is non-nil.
2475 Set this to a non-nil value to turn this feature on by default.
2476 You can interactively toggle the value of this variable with
2477 `markdown-toggle-markup-hiding', \\[markdown-toggle-markup-hiding],
2478 or from the Markdown > Show & Hide menu.
2480 Markup hiding works by adding text properties to positions in the
2481 buffer---either the `invisible' property or the `display' property
2482 in cases where alternative glyphs are used (e.g., list bullets).
2483 This does not, however, affect printing or other output.
2484 Functions such as `htmlfontify-buffer' and `ps-print-buffer' will
2485 not honor these text properties. For printing, it would be better
2486 to first convert to HTML or PDF (e.g,. using Pandoc)."
2487 :group 'markdown
2488 :type 'boolean
2489 :safe 'booleanp
2490 :package-version '(markdown-mode . "2.3"))
2491 (make-variable-buffer-local 'markdown-hide-markup)
2493 (defun markdown-toggle-markup-hiding (&optional arg)
2494 "Toggle the display or hiding of markup.
2495 With a prefix argument ARG, enable markup hiding if ARG is positive,
2496 and disable it otherwise.
2497 See `markdown-hide-markup' for additional details."
2498 (interactive (list (or current-prefix-arg 'toggle)))
2499 (setq markdown-hide-markup
2500 (if (eq arg 'toggle)
2501 (not markdown-hide-markup)
2502 (> (prefix-numeric-value arg) 0)))
2503 (if markdown-hide-markup
2504 (progn (add-to-invisibility-spec 'markdown-markup)
2505 (message "markdown-mode markup hiding enabled"))
2506 (progn (remove-from-invisibility-spec 'markdown-markup)
2507 (message "markdown-mode markup hiding disabled")))
2508 (markdown-reload-extensions))
2511 ;;; Font Lock =================================================================
2513 (require 'font-lock)
2515 (defvar markdown-italic-face 'markdown-italic-face
2516 "Face name to use for italic text.")
2518 (defvar markdown-bold-face 'markdown-bold-face
2519 "Face name to use for bold text.")
2521 (defvar markdown-strike-through-face 'markdown-strike-through-face
2522 "Face name to use for strike-through text.")
2524 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
2525 "Face name to use as a base for header delimiters.")
2527 (defvar markdown-header-rule-face 'markdown-header-rule-face
2528 "Face name to use as a base for header rules.")
2530 (defvar markdown-header-face 'markdown-header-face
2531 "Face name to use as a base for headers.")
2533 (defvar markdown-header-face-1 'markdown-header-face-1
2534 "Face name to use for level-1 headers.")
2536 (defvar markdown-header-face-2 'markdown-header-face-2
2537 "Face name to use for level-2 headers.")
2539 (defvar markdown-header-face-3 'markdown-header-face-3
2540 "Face name to use for level-3 headers.")
2542 (defvar markdown-header-face-4 'markdown-header-face-4
2543 "Face name to use for level-4 headers.")
2545 (defvar markdown-header-face-5 'markdown-header-face-5
2546 "Face name to use for level-5 headers.")
2548 (defvar markdown-header-face-6 'markdown-header-face-6
2549 "Face name to use for level-6 headers.")
2551 (defvar markdown-inline-code-face 'markdown-inline-code-face
2552 "Face name to use for inline code.")
2554 (defvar markdown-list-face 'markdown-list-face
2555 "Face name to use for list markers.")
2557 (defvar markdown-blockquote-face 'markdown-blockquote-face
2558 "Face name to use for blockquote.")
2560 (defvar markdown-pre-face 'markdown-pre-face
2561 "Face name to use for preformatted text.")
2563 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
2564 "Face name to use for programming language identifiers.")
2566 (defvar markdown-language-info-face 'markdown-language-info-face
2567 "Face name to use for programming info strings.")
2569 (defvar markdown-link-face 'markdown-link-face
2570 "Face name to use for links.")
2572 (defvar markdown-missing-link-face 'markdown-missing-link-face
2573 "Face name to use for links where the linked file does not exist.")
2575 (defvar markdown-reference-face 'markdown-reference-face
2576 "Face name to use for reference.")
2578 (defvar markdown-footnote-marker-face 'markdown-footnote-marker-face
2579 "Face name to use for footnote markers.")
2581 (defvar markdown-url-face 'markdown-url-face
2582 "Face name to use for URLs.")
2584 (defvar markdown-link-title-face 'markdown-link-title-face
2585 "Face name to use for reference link titles.")
2587 (defvar markdown-line-break-face 'markdown-line-break-face
2588 "Face name to use for hard line breaks.")
2590 (defvar markdown-comment-face 'markdown-comment-face
2591 "Face name to use for HTML comments.")
2593 (defvar markdown-math-face 'markdown-math-face
2594 "Face name to use for LaTeX expressions.")
2596 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
2597 "Face name to use for metadata keys.")
2599 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
2600 "Face name to use for metadata values.")
2602 (defvar markdown-gfm-checkbox-face 'markdown-gfm-checkbox-face
2603 "Face name to use for GFM checkboxes.")
2605 (defvar markdown-highlight-face 'markdown-highlight-face
2606 "Face name to use for mouse highlighting.")
2608 (defvar markdown-markup-face 'markdown-markup-face
2609 "Face name to use for markup elements.")
2611 (defgroup markdown-faces nil
2612 "Faces used in Markdown Mode"
2613 :group 'markdown
2614 :group 'faces)
2616 (defface markdown-italic-face
2617 '((t (:inherit italic)))
2618 "Face for italic text."
2619 :group 'markdown-faces)
2621 (defface markdown-bold-face
2622 '((t (:inherit bold)))
2623 "Face for bold text."
2624 :group 'markdown-faces)
2626 (defface markdown-strike-through-face
2627 '((t (:strike-through t)))
2628 "Face for strike-through text."
2629 :group 'markdown-faces)
2631 (defface markdown-markup-face
2632 '((t (:inherit shadow :slant normal :weight normal)))
2633 "Face for markup elements."
2634 :group 'markdown-faces)
2636 (defface markdown-header-rule-face
2637 '((t (:inherit markdown-markup-face)))
2638 "Base face for headers rules."
2639 :group 'markdown-faces)
2641 (defface markdown-header-delimiter-face
2642 '((t (:inherit markdown-markup-face)))
2643 "Base face for headers hash delimiter."
2644 :group 'markdown-faces)
2646 (defface markdown-list-face
2647 '((t (:inherit markdown-markup-face)))
2648 "Face for list item markers."
2649 :group 'markdown-faces)
2651 (defface markdown-blockquote-face
2652 '((t (:inherit font-lock-doc-face)))
2653 "Face for blockquote sections."
2654 :group 'markdown-faces)
2656 (defface markdown-code-face
2657 '((t (:inherit fixed-pitch)))
2658 "Face for inline code, pre blocks, and fenced code blocks.
2659 This may be used, for example, to add a contrasting background to
2660 inline code fragments and code blocks."
2661 :group 'markdown-faces)
2663 (defface markdown-inline-code-face
2664 '((t (:inherit (markdown-code-face font-lock-constant-face))))
2665 "Face for inline code."
2666 :group 'markdown-faces)
2668 (defface markdown-pre-face
2669 '((t (:inherit (markdown-code-face font-lock-constant-face))))
2670 "Face for preformatted text."
2671 :group 'markdown-faces)
2673 (defface markdown-language-keyword-face
2674 '((t (:inherit font-lock-type-face)))
2675 "Face for programming language identifiers."
2676 :group 'markdown-faces)
2678 (defface markdown-language-info-face
2679 '((t (:inherit font-lock-string-face)))
2680 "Face for programming language info strings."
2681 :group 'markdown-faces)
2683 (defface markdown-link-face
2684 '((t (:inherit link)))
2685 "Face for links."
2686 :group 'markdown-faces)
2688 (defface markdown-missing-link-face
2689 '((t (:inherit font-lock-warning-face)))
2690 "Face for missing links."
2691 :group 'markdown-faces)
2693 (defface markdown-reference-face
2694 '((t (:inherit markdown-markup-face)))
2695 "Face for link references."
2696 :group 'markdown-faces)
2698 (define-obsolete-face-alias 'markdown-footnote-face
2699 'markdown-footnote-marker-face "v2.3")
2701 (defface markdown-footnote-marker-face
2702 '((t (:inherit markdown-markup-face)))
2703 "Face for footnote markers."
2704 :group 'markdown-faces)
2706 (defface markdown-footnote-text-face
2707 '((t (:inherit font-lock-comment-face)))
2708 "Face for footnote text."
2709 :group 'markdown-faces)
2711 (defface markdown-url-face
2712 '((t (:inherit font-lock-string-face)))
2713 "Face for URLs that are part of markup.
2714 For example, this applies to URLs in inline links:
2715 [link text](http://example.com/)."
2716 :group 'markdown-faces)
2718 (defface markdown-plain-url-face
2719 '((t (:inherit markdown-link-face)))
2720 "Face for URLs that are also links.
2721 For example, this applies to plain angle bracket URLs:
2722 <http://example.com/>."
2723 :group 'markdown-faces)
2725 (defface markdown-link-title-face
2726 '((t (:inherit font-lock-comment-face)))
2727 "Face for reference link titles."
2728 :group 'markdown-faces)
2730 (defface markdown-line-break-face
2731 '((t (:inherit font-lock-constant-face :underline t)))
2732 "Face for hard line breaks."
2733 :group 'markdown-faces)
2735 (defface markdown-comment-face
2736 '((t (:inherit font-lock-comment-face)))
2737 "Face for HTML comments."
2738 :group 'markdown-faces)
2740 (defface markdown-math-face
2741 '((t (:inherit font-lock-string-face)))
2742 "Face for LaTeX expressions."
2743 :group 'markdown-faces)
2745 (defface markdown-metadata-key-face
2746 '((t (:inherit font-lock-variable-name-face)))
2747 "Face for metadata keys."
2748 :group 'markdown-faces)
2750 (defface markdown-metadata-value-face
2751 '((t (:inherit font-lock-string-face)))
2752 "Face for metadata values."
2753 :group 'markdown-faces)
2755 (defface markdown-gfm-checkbox-face
2756 '((t (:inherit font-lock-builtin-face)))
2757 "Face for GFM checkboxes."
2758 :group 'markdown-faces)
2760 (defface markdown-highlight-face
2761 '((t (:inherit highlight)))
2762 "Face for mouse highlighting."
2763 :group 'markdown-faces)
2765 (defface markdown-hr-face
2766 '((t (:inherit markdown-markup-face)))
2767 "Face for horizontal rules."
2768 :group 'markdown-faces)
2770 (defface markdown-html-entity-face
2771 '((t (:inherit font-lock-variable-name-face)))
2772 "Face for HTML entities."
2773 :group 'markdown-faces)
2775 (defcustom markdown-header-scaling nil
2776 "Whether to use variable-height faces for headers.
2777 When non-nil, `markdown-header-face' will inherit from
2778 `variable-pitch' and the scaling values in
2779 `markdown-header-scaling-values' will be applied to
2780 headers of levels one through six respectively."
2781 :type 'boolean
2782 :initialize 'custom-initialize-default
2783 :set (lambda (symbol value)
2784 (set-default symbol value)
2785 (markdown-update-header-faces value))
2786 :group 'markdown-faces
2787 :package-version '(markdown-mode . "2.2"))
2789 (defcustom markdown-header-scaling-values
2790 '(2.0 1.7 1.4 1.1 1.0 1.0)
2791 "List of scaling values for headers of level one through six.
2792 Used when `markdown-header-scaling' is non-nil."
2793 :type 'list
2794 :initialize 'custom-initialize-default
2795 :set (lambda (symbol value)
2796 (set-default symbol value)
2797 (markdown-update-header-faces markdown-header-scaling value))
2798 :group 'markdown-faces)
2800 (defun markdown-make-header-faces ()
2801 "Build the faces used for Markdown headers."
2802 (let ((inherit-faces '(font-lock-function-name-face)))
2803 (when markdown-header-scaling
2804 (setq inherit-faces (cons 'variable-pitch inherit-faces)))
2805 (defface markdown-header-face
2806 `((t (:inherit ,inherit-faces :weight bold)))
2807 "Base face for headers."
2808 :group 'markdown-faces))
2809 (dotimes (num 6)
2810 (let* ((num1 (1+ num))
2811 (face-name (intern (format "markdown-header-face-%s" num1)))
2812 (scale (if markdown-header-scaling
2813 (float (nth num markdown-header-scaling-values))
2814 1.0)))
2815 (eval
2816 `(defface ,face-name
2817 '((t (:inherit markdown-header-face :height ,scale)))
2818 (format "Face for level %s headers.
2819 You probably don't want to customize this face directly. Instead
2820 you can customize the base face `markdown-header-face' or the
2821 variable-height variable `markdown-header-scaling'." ,num1)
2822 :group 'markdown-faces)))))
2824 (markdown-make-header-faces)
2826 (defun markdown-update-header-faces (&optional scaling scaling-values)
2827 "Update header faces, depending on if header SCALING is desired.
2828 If so, use given list of SCALING-VALUES relative to the baseline
2829 size of `markdown-header-face'."
2830 (dotimes (num 6)
2831 (let* ((face-name (intern (format "markdown-header-face-%s" (1+ num))))
2832 (scale (cond ((not scaling) 1.0)
2833 (scaling-values (float (nth num scaling-values)))
2834 (t (float (nth num markdown-header-scaling-values))))))
2835 (unless (get face-name 'saved-face) ; Don't update customized faces
2836 (set-face-attribute face-name nil :height scale)))))
2838 (defun markdown-syntactic-face (state)
2839 "Return font-lock face for characters with given STATE.
2840 See `font-lock-syntactic-face-function' for details."
2841 (let ((in-comment (nth 4 state)))
2842 (cond
2843 (in-comment 'markdown-comment-face)
2844 (t nil))))
2846 (defcustom markdown-list-item-bullets
2847 '("●" "◎" "○" "◆" "◇" "►" "•")
2848 "List of bullets to use for unordered lists.
2849 It can contain any number of symbols, which will be repeated.
2850 Depending on your font, some reasonable choices are:
2851 ♥ ● ◇ ✚ ✜ ☯ ◆ ♠ ♣ ♦ ❀ ◆ ◖ ▶ ► • ★ ▸."
2852 :group 'markdown
2853 :type '(repeat (string :tag "Bullet character"))
2854 :package-version '(markdown-mode . "2.3"))
2856 (defvar markdown-mode-font-lock-keywords-basic
2857 `((markdown-match-yaml-metadata-begin . ((1 markdown-markup-face)))
2858 (markdown-match-yaml-metadata-end . ((1 markdown-markup-face)))
2859 (markdown-match-yaml-metadata-key . ((1 markdown-metadata-key-face)
2860 (2 markdown-markup-face)
2861 (3 markdown-metadata-value-face)))
2862 (markdown-match-gfm-open-code-blocks . ((1 markdown-markup-properties)
2863 (2 markdown-markup-properties nil t)
2864 (3 markdown-language-keyword-properties nil t)
2865 (4 markdown-language-info-properties nil t)
2866 (5 markdown-markup-properties nil t)))
2867 (markdown-match-gfm-close-code-blocks . ((0 markdown-markup-properties)))
2868 (markdown-fontify-gfm-code-blocks)
2869 (markdown-match-fenced-start-code-block . ((1 markdown-markup-properties)
2870 (2 markdown-markup-properties nil t)
2871 (3 markdown-language-keyword-properties nil t)
2872 (4 markdown-language-info-properties nil t)
2873 (5 markdown-markup-properties nil t)))
2874 (markdown-match-fenced-end-code-block . ((0 markdown-markup-properties)))
2875 (markdown-fontify-fenced-code-blocks)
2876 (markdown-match-pre-blocks . ((0 markdown-pre-face)))
2877 (markdown-fontify-headings)
2878 (markdown-match-declarative-metadata . ((1 markdown-metadata-key-face)
2879 (2 markdown-markup-face)
2880 (3 markdown-metadata-value-face)))
2881 (markdown-match-pandoc-metadata . ((1 markdown-markup-face)
2882 (2 markdown-markup-face)
2883 (3 markdown-metadata-value-face)))
2884 (markdown-fontify-hrs)
2885 (markdown-match-code . ((1 markdown-markup-properties prepend)
2886 (2 markdown-inline-code-face prepend)
2887 (3 markdown-markup-properties prepend)))
2888 (,markdown-regex-kbd . ((1 markdown-markup-properties)
2889 (2 markdown-inline-code-face)
2890 (3 markdown-markup-properties)))
2891 (markdown-fontify-angle-uris)
2892 (,markdown-regex-email . 'markdown-plain-url-face)
2893 (markdown-fontify-list-items)
2894 (,markdown-regex-footnote . ((0 markdown-inline-footnote-properties)
2895 (1 markdown-markup-properties) ; [^
2896 (2 markdown-footnote-marker-face) ; label
2897 (3 markdown-markup-properties))) ; ]
2898 (,markdown-regex-pandoc-inline-footnote . ((0 markdown-inline-footnote-properties)
2899 (1 markdown-markup-properties) ; ^
2900 (2 markdown-markup-properties) ; [
2901 (3 'markdown-footnote-text-face) ; text
2902 (4 markdown-markup-properties))) ; ]
2903 (markdown-match-includes . ((1 markdown-markup-properties)
2904 (2 markdown-markup-properties nil t)
2905 (3 markdown-include-title-properties nil t)
2906 (4 markdown-markup-properties nil t)
2907 (5 markdown-markup-properties)
2908 (6 'markdown-url-face)
2909 (7 markdown-markup-properties)))
2910 (markdown-fontify-inline-links)
2911 (markdown-fontify-reference-links)
2912 (,markdown-regex-reference-definition . ((1 markdown-markup-face) ; [
2913 (2 markdown-reference-face) ; label
2914 (3 markdown-markup-face) ; ]
2915 (4 markdown-markup-face) ; :
2916 (5 markdown-url-face) ; url
2917 (6 markdown-link-title-face))) ; "title" (optional)
2918 (markdown-fontify-plain-uris)
2919 ;; Math mode $..$
2920 (markdown-match-math-single . ((1 markdown-markup-face prepend)
2921 (2 markdown-math-face append)
2922 (3 markdown-markup-face prepend)))
2923 ;; Math mode $$..$$
2924 (markdown-match-math-double . ((1 markdown-markup-face prepend)
2925 (2 markdown-math-face append)
2926 (3 markdown-markup-face prepend)))
2927 ;; Math mode \[..\] and \\[..\\]
2928 (markdown-match-math-display . ((1 markdown-markup-face prepend)
2929 (3 markdown-math-face append)
2930 (4 markdown-markup-face prepend)))
2931 (markdown-match-bold . ((1 markdown-markup-properties prepend)
2932 (2 markdown-bold-face append)
2933 (3 markdown-markup-properties prepend)))
2934 (markdown-match-italic . ((1 markdown-markup-properties prepend)
2935 (2 markdown-italic-face append)
2936 (3 markdown-markup-properties prepend)))
2937 (,markdown-regex-strike-through . ((3 markdown-markup-properties)
2938 (4 markdown-strike-through-face)
2939 (5 markdown-markup-properties)))
2940 (,markdown-regex-line-break . (1 markdown-line-break-face prepend))
2941 (markdown-fontify-sub-superscripts)
2942 (markdown-match-inline-attributes . ((0 markdown-markup-properties prepend)))
2943 (markdown-match-leanpub-sections . ((0 markdown-markup-properties)))
2944 (markdown-fontify-blockquotes)
2945 (markdown-match-wiki-link . ((0 markdown-link-face prepend))))
2946 "Syntax highlighting for Markdown files.")
2948 ;; Footnotes
2949 (defvar markdown-footnote-counter 0
2950 "Counter for footnote numbers.")
2951 (make-variable-buffer-local 'markdown-footnote-counter)
2953 (defconst markdown-footnote-chars
2954 "[[:alnum:]-]"
2955 "Regular expression matching any character that is allowed in a footnote identifier.")
2957 (defconst markdown-regex-footnote-definition
2958 (concat "^ \\{0,3\\}\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:\\(?:[ \t]+\\|$\\)")
2959 "Regular expression matching a footnote definition, capturing the label.")
2962 ;;; Compatibility =============================================================
2964 (defun markdown-replace-regexp-in-string (regexp rep string)
2965 "Replace ocurrences of REGEXP with REP in STRING.
2966 This is a compatibility wrapper to provide `replace-regexp-in-string'
2967 in XEmacs 21."
2968 (if (featurep 'xemacs)
2969 (replace-in-string string regexp rep)
2970 (replace-regexp-in-string regexp rep string)))
2972 ;; `markdown-use-region-p' is a compatibility function which checks
2973 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
2974 (eval-and-compile
2975 (cond
2976 ;; Emacs 24 and newer
2977 ((fboundp 'use-region-p)
2978 (defalias 'markdown-use-region-p 'use-region-p))
2979 ;; XEmacs
2980 ((fboundp 'region-active-p)
2981 (defalias 'markdown-use-region-p 'region-active-p))))
2983 ;; Use new names for outline-mode functions in Emacs 25 and later.
2984 (eval-and-compile
2985 (defalias 'markdown-hide-sublevels
2986 (if (fboundp 'outline-hide-sublevels)
2987 'outline-hide-sublevels
2988 'hide-sublevels))
2989 (defalias 'markdown-show-all
2990 (if (fboundp 'outline-show-all)
2991 'outline-show-all
2992 'show-all))
2993 (defalias 'markdown-hide-body
2994 (if (fboundp 'outline-hide-body)
2995 'outline-hide-body
2996 'hide-body))
2997 (defalias 'markdown-show-children
2998 (if (fboundp 'outline-show-children)
2999 'outline-show-children
3000 'show-children))
3001 (defalias 'markdown-show-subtree
3002 (if (fboundp 'outline-show-subtree)
3003 'outline-show-subtree
3004 'show-subtree))
3005 (defalias 'markdown-hide-subtree
3006 (if (fboundp 'outline-hide-subtree)
3007 'outline-hide-subtree
3008 'hide-subtree)))
3010 ;; Provide directory-name-p to Emacs 24
3011 (defsubst markdown-directory-name-p (name)
3012 "Return non-nil if NAME ends with a directory separator character.
3013 Taken from `directory-name-p' from Emacs 25 and provided here for
3014 backwards compatibility."
3015 (let ((len (length name))
3016 (lastc ?.))
3017 (if (> len 0)
3018 (setq lastc (aref name (1- len))))
3019 (or (= lastc ?/)
3020 (and (memq system-type '(windows-nt ms-dos))
3021 (= lastc ?\\)))))
3023 ;; Provide a function to find files recursively in Emacs 24.
3024 (defalias 'markdown-directory-files-recursively
3025 (if (fboundp 'directory-files-recursively)
3026 'directory-files-recursively
3027 (lambda (dir regexp)
3028 "Return list of all files under DIR that have file names matching REGEXP.
3029 This function works recursively. Files are returned in \"depth first\"
3030 order, and files from each directory are sorted in alphabetical order.
3031 Each file name appears in the returned list in its absolute form.
3032 Based on `directory-files-recursively' from Emacs 25 and provided
3033 here for backwards compatibility."
3034 (let ((result nil)
3035 (files nil)
3036 ;; When DIR is "/", remote file names like "/method:" could
3037 ;; also be offered. We shall suppress them.
3038 (tramp-mode (and tramp-mode (file-remote-p (expand-file-name dir)))))
3039 (dolist (file (sort (file-name-all-completions "" dir)
3040 'string<))
3041 (unless (member file '("./" "../"))
3042 (if (markdown-directory-name-p file)
3043 (let* ((leaf (substring file 0 (1- (length file))))
3044 (full-file (expand-file-name leaf dir)))
3045 (setq result
3046 (nconc result (markdown-directory-files-recursively
3047 full-file regexp))))
3048 (when (string-match-p regexp file)
3049 (push (expand-file-name file dir) files)))))
3050 (nconc result (nreverse files))))))
3052 (defun markdown-flyspell-check-word-p ()
3053 "Return t if `flyspell' should check word just before point.
3054 Used for `flyspell-generic-check-word-predicate'."
3055 (save-excursion
3056 (goto-char (1- (point)))
3057 (not (or (markdown-code-block-at-point-p)
3058 (markdown-inline-code-at-point-p)
3059 (markdown-in-comment-p)
3060 (let ((faces (get-text-property (point) 'face)))
3061 (if (listp faces)
3062 (or (memq 'markdown-reference-face faces)
3063 (memq 'markdown-markup-face faces)
3064 (memq 'markdown-plain-url-face faces)
3065 (memq 'markdown-inline-code-face faces)
3066 (memq 'markdown-url-face faces))
3067 (memq faces '(markdown-reference-face
3068 markdown-markup-face
3069 markdown-plain-url-face
3070 markdown-inline-code-face
3071 markdown-url-face))))))))
3073 (defun markdown-font-lock-ensure ()
3074 "Provide `font-lock-ensure' in Emacs 24."
3075 (if (fboundp 'font-lock-ensure)
3076 (font-lock-ensure)
3077 (with-no-warnings
3078 ;; Suppress warning about non-interactive use of
3079 ;; `font-lock-fontify-buffer' in Emacs 25.
3080 (font-lock-fontify-buffer))))
3083 ;;; Markdown Parsing Functions ================================================
3085 (defun markdown-cur-line-blank (&optional predicate)
3086 "Return t if the current line is blank and nil otherwise.
3087 When PREDICATE is non-nil, don't modify the match data."
3088 (save-excursion
3089 (beginning-of-line)
3090 (let ((regexp "^\\s *$"))
3091 (if predicate
3092 (looking-at-p regexp)
3093 (looking-at regexp)))))
3095 (defun markdown-cur-line-blank-p ()
3096 "Same as `markdown-cur-line-blank', but does not change the match data."
3097 (markdown-cur-line-blank t))
3099 (defun markdown-prev-line-blank (&optional predicate)
3100 "Return t if the previous line is blank and nil otherwise.
3101 If we are at the first line, then consider the previous line to be blank.
3102 When PREDICATE is non-nil, don't modify the match data."
3103 (or (= (line-beginning-position) (point-min))
3104 (save-excursion
3105 (forward-line -1)
3106 (markdown-cur-line-blank predicate))))
3108 (defun markdown-prev-line-blank-p ()
3109 "Same as `markdown-prev-line-blank', but does not change the match data."
3110 (markdown-prev-line-blank t))
3112 (defun markdown-next-line-blank (&optional predicate)
3113 "Return t if the next line is blank and nil otherwise.
3114 If we are at the last line, then consider the next line to be blank.
3115 When PREDICATE is non-nil, don't modify the match data."
3116 (or (= (line-end-position) (point-max))
3117 (save-excursion
3118 (forward-line 1)
3119 (markdown-cur-line-blank predicate))))
3121 (defun markdown-next-line-blank-p ()
3122 "Same as `markdown-next-line-blank', but does not change the match data."
3123 (markdown-next-line-blank t))
3125 (defun markdown-prev-line-indent ()
3126 "Return the number of leading whitespace characters in the previous line.
3127 Return 0 if the current line is the first line in the buffer."
3128 (save-excursion
3129 (if (= (line-beginning-position) (point-min))
3131 (forward-line -1)
3132 (current-indentation))))
3134 (defun markdown-next-line-indent ()
3135 "Return the number of leading whitespace characters in the next line.
3136 Return 0 if line is the last line in the buffer."
3137 (save-excursion
3138 (if (= (line-end-position) (point-max))
3140 (forward-line 1)
3141 (current-indentation))))
3143 (defun markdown-cur-non-list-indent ()
3144 "Return beginning position of list item text (not including the list marker).
3145 Return nil if the current line is not the beginning of a list item."
3146 (save-match-data
3147 (save-excursion
3148 (beginning-of-line)
3149 (when (re-search-forward markdown-regex-list (line-end-position) t)
3150 (current-column)))))
3152 (defun markdown-prev-non-list-indent ()
3153 "Return position of the first non-list-marker on the previous line."
3154 (save-excursion
3155 (forward-line -1)
3156 (markdown-cur-non-list-indent)))
3158 (defun markdown-new-baseline ()
3159 "Determine if the current line begins a new baseline level."
3160 (save-excursion
3161 (beginning-of-line)
3162 (or (looking-at markdown-regex-header)
3163 (looking-at markdown-regex-hr)
3164 (and (null (markdown-cur-non-list-indent))
3165 (= (current-indentation) 0)
3166 (markdown-prev-line-blank)))))
3168 (defun markdown-search-backward-baseline ()
3169 "Search backward baseline point with no indentation and not a list item."
3170 (end-of-line)
3171 (let (stop)
3172 (while (not (or stop (bobp)))
3173 (re-search-backward markdown-regex-block-separator-noindent nil t)
3174 (when (match-end 2)
3175 (goto-char (match-end 2))
3176 (cond
3177 ((markdown-new-baseline)
3178 (setq stop t))
3179 ((looking-at-p markdown-regex-list)
3180 (setq stop nil))
3181 (t (setq stop t)))))))
3183 (defun markdown-update-list-levels (marker indent levels)
3184 "Update list levels given list MARKER, block INDENT, and current LEVELS.
3185 Here, MARKER is a string representing the type of list, INDENT is an integer
3186 giving the indentation, in spaces, of the current block, and LEVELS is a
3187 list of the indentation levels of parent list items. When LEVELS is nil,
3188 it means we are at baseline (not inside of a nested list)."
3189 (cond
3190 ;; New list item at baseline.
3191 ((and marker (null levels))
3192 (setq levels (list indent)))
3193 ;; List item with greater indentation (four or more spaces).
3194 ;; Increase list level.
3195 ((and marker (>= indent (+ (car levels) 4)))
3196 (setq levels (cons indent levels)))
3197 ;; List item with greater or equal indentation (less than four spaces).
3198 ;; Do not increase list level.
3199 ((and marker (>= indent (car levels)))
3200 levels)
3201 ;; Lesser indentation level.
3202 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
3203 ;; indentation could move back more than one list level). Note
3204 ;; that this block need not be the beginning of list item.
3205 ((< indent (car levels))
3206 (while (and (> (length levels) 1)
3207 (< indent (+ (cadr levels) 4)))
3208 (setq levels (cdr levels)))
3209 levels)
3210 ;; Otherwise, do nothing.
3211 (t levels)))
3213 (defun markdown-calculate-list-levels ()
3214 "Calculate list levels at point.
3215 Return a list of the form (n1 n2 n3 ...) where n1 is the
3216 indentation of the deepest nested list item in the branch of
3217 the list at the point, n2 is the indentation of the parent
3218 list item, and so on. The depth of the list item is therefore
3219 the length of the returned list. If the point is not at or
3220 immediately after a list item, return nil."
3221 (save-excursion
3222 (let ((first (point)) levels indent pre-regexp)
3223 ;; Find a baseline point with zero list indentation
3224 (markdown-search-backward-baseline)
3225 ;; Search for all list items between baseline and LOC
3226 (while (and (< (point) first)
3227 (re-search-forward markdown-regex-list first t))
3228 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
3229 (beginning-of-line)
3230 (cond
3231 ;; Make sure this is not a header or hr
3232 ((markdown-new-baseline) (setq levels nil))
3233 ;; Make sure this is not a line from a pre block
3234 ((looking-at-p pre-regexp))
3235 ;; If not, then update levels
3237 (setq indent (current-indentation))
3238 (setq levels (markdown-update-list-levels (match-string 2)
3239 indent levels))))
3240 (end-of-line))
3241 levels)))
3243 (defun markdown-prev-list-item (level)
3244 "Search backward from point for a list item with indentation LEVEL.
3245 Set point to the beginning of the item, and return point, or nil
3246 upon failure."
3247 (let (bounds indent prev)
3248 (setq prev (point))
3249 (forward-line -1)
3250 (setq indent (current-indentation))
3251 (while
3252 (cond
3253 ;; List item
3254 ((and (looking-at-p markdown-regex-list)
3255 (setq bounds (markdown-cur-list-item-bounds)))
3256 (cond
3257 ;; Stop and return point at item of equal indentation
3258 ((= (nth 3 bounds) level)
3259 (setq prev (point))
3260 nil)
3261 ;; Stop and return nil at item with lesser indentation
3262 ((< (nth 3 bounds) level)
3263 (setq prev nil)
3264 nil)
3265 ;; Stop at beginning of buffer
3266 ((bobp) (setq prev nil))
3267 ;; Continue at item with greater indentation
3268 ((> (nth 3 bounds) level) t)))
3269 ;; Stop at beginning of buffer
3270 ((bobp) (setq prev nil))
3271 ;; Continue if current line is blank
3272 ((markdown-cur-line-blank-p) t)
3273 ;; Continue while indentation is the same or greater
3274 ((>= indent level) t)
3275 ;; Stop if current indentation is less than list item
3276 ;; and the next is blank
3277 ((and (< indent level)
3278 (markdown-next-line-blank-p))
3279 (setq prev nil))
3280 ;; Stop at a header
3281 ((looking-at-p markdown-regex-header) (setq prev nil))
3282 ;; Stop at a horizontal rule
3283 ((looking-at-p markdown-regex-hr) (setq prev nil))
3284 ;; Otherwise, continue.
3285 (t t))
3286 (forward-line -1)
3287 (setq indent (current-indentation)))
3288 prev))
3290 (defun markdown-next-list-item (level)
3291 "Search forward from point for the next list item with indentation LEVEL.
3292 Set point to the beginning of the item, and return point, or nil
3293 upon failure."
3294 (let (bounds indent next)
3295 (setq next (point))
3296 (if (looking-at markdown-regex-header-setext)
3297 (goto-char (match-end 0)))
3298 (forward-line)
3299 (setq indent (current-indentation))
3300 (while
3301 (cond
3302 ;; Stop at end of the buffer.
3303 ((eobp) nil)
3304 ;; Continue if the current line is blank
3305 ((markdown-cur-line-blank-p) t)
3306 ;; List item
3307 ((and (looking-at-p markdown-regex-list)
3308 (setq bounds (markdown-cur-list-item-bounds)))
3309 (cond
3310 ;; Continue at item with greater indentation
3311 ((> (nth 3 bounds) level) t)
3312 ;; Stop and return point at item of equal indentation
3313 ((= (nth 3 bounds) level)
3314 (setq next (point))
3315 nil)
3316 ;; Stop and return nil at item with lesser indentation
3317 ((< (nth 3 bounds) level)
3318 (setq next nil)
3319 nil)))
3320 ;; Continue while indentation is the same or greater
3321 ((>= indent level) t)
3322 ;; Stop if current indentation is less than list item
3323 ;; and the previous line was blank.
3324 ((and (< indent level)
3325 (markdown-prev-line-blank-p))
3326 (setq next nil))
3327 ;; Stop at a header
3328 ((looking-at-p markdown-regex-header) (setq next nil))
3329 ;; Stop at a horizontal rule
3330 ((looking-at-p markdown-regex-hr) (setq next nil))
3331 ;; Otherwise, continue.
3332 (t t))
3333 (forward-line)
3334 (setq indent (current-indentation)))
3335 next))
3337 (defun markdown-cur-list-item-end (level)
3338 "Move to the end of the current list item with nonlist indentation LEVEL.
3339 If the point is not in a list item, do nothing."
3340 (let (indent)
3341 (forward-line)
3342 (setq indent (current-indentation))
3343 (while
3344 (cond
3345 ;; Stop at end of the buffer.
3346 ((eobp) nil)
3347 ;; Continue if the current line is blank
3348 ((markdown-cur-line-blank-p) t)
3349 ;; Continue while indentation is the same or greater
3350 ((>= indent level) t)
3351 ;; Stop if current indentation is less than list item
3352 ;; and the previous line was blank.
3353 ((and (< indent level)
3354 (markdown-prev-line-blank-p))
3355 nil)
3356 ;; Stop at a new list item of the same or lesser indentation
3357 ((looking-at-p markdown-regex-list) nil)
3358 ;; Stop at a header
3359 ((looking-at-p markdown-regex-header) nil)
3360 ;; Stop at a horizontal rule
3361 ((looking-at-p markdown-regex-hr) nil)
3362 ;; Otherwise, continue.
3363 (t t))
3364 (forward-line)
3365 (setq indent (current-indentation)))
3366 ;; Don't skip over whitespace for empty list items (marker and
3367 ;; whitespace only), just move to end of whitespace.
3368 (if (looking-back (concat markdown-regex-list "\\s-*") nil)
3369 (goto-char (match-end 3))
3370 (skip-syntax-backward "-"))))
3372 (defun markdown-cur-list-item-bounds ()
3373 "Return bounds and indentation of the current list item.
3374 Return a list of the following form:
3376 (begin end indent nonlist-indent marker checkbox)
3378 The named components are:
3380 - begin: Position of beginning of list item, including leading indentation.
3381 - end: Position of the end of the list item, including list item text.
3382 - indent: Number of characters of indentation before list marker (an integer).
3383 - nonlist-indent: Number characters of indentation, list
3384 marker, and whitespace following list marker (an integer).
3385 - marker: String containing the list marker and following whitespace
3386 (e.g., \"- \" or \"* \").
3387 - checkbox: String containing the GFM checkbox portion, if any,
3388 including any trailing whitespace before the text
3389 begins (e.g., \"[x] \").
3391 As an example, for the following unordered list item
3393 - item
3395 the returned list would be
3397 (1 14 3 5 \"- \" nil)
3399 If the point is not inside a list item, return nil.
3400 Leave match data intact for `markdown-regex-list'."
3401 (save-excursion
3402 (let ((cur (point)))
3403 (end-of-line)
3404 (when (re-search-backward markdown-regex-list nil t)
3405 (let* ((begin (match-beginning 0))
3406 (indent (length (match-string-no-properties 1)))
3407 (nonlist-indent (length (match-string 0)))
3408 (marker (concat (match-string-no-properties 2)
3409 (match-string-no-properties 3)))
3410 (checkbox (progn (goto-char (match-end 0))
3411 (when (looking-at "\\[[xX ]\\]\\s-*")
3412 (match-string-no-properties 0))))
3413 (end (save-match-data
3414 (markdown-cur-list-item-end nonlist-indent)
3415 (point))))
3416 (when (and (>= cur begin) (<= cur end) nonlist-indent)
3417 (list begin end indent nonlist-indent marker checkbox)))))))
3419 (defun markdown-list-item-at-point-p ()
3420 "Return t if there is a list item at the point and nil otherwise."
3421 (save-match-data (markdown-cur-list-item-bounds)))
3423 (defun markdown-prev-list-item-bounds ()
3424 "Return bounds of previous item in the same list of any level.
3425 The return value has the same form as that of
3426 `markdown-cur-list-item-bounds'."
3427 (save-excursion
3428 (let ((cur-bounds (markdown-cur-list-item-bounds))
3429 (beginning-of-list (save-excursion (markdown-beginning-of-list)))
3430 stop)
3431 (when cur-bounds
3432 (goto-char (nth 0 cur-bounds))
3433 (while (and (not stop) (not (bobp))
3434 (re-search-backward markdown-regex-list
3435 beginning-of-list t))
3436 (unless (or (looking-at markdown-regex-hr)
3437 (markdown-code-block-at-point-p))
3438 (setq stop (point))))
3439 (markdown-cur-list-item-bounds)))))
3441 (defun markdown-next-list-item-bounds ()
3442 "Return bounds of next item in the same list of any level.
3443 The return value has the same form as that of
3444 `markdown-cur-list-item-bounds'."
3445 (save-excursion
3446 (let ((cur-bounds (markdown-cur-list-item-bounds))
3447 (end-of-list (save-excursion (markdown-end-of-list)))
3448 stop)
3449 (when cur-bounds
3450 (goto-char (nth 0 cur-bounds))
3451 (end-of-line)
3452 (while (and (not stop) (not (eobp))
3453 (re-search-forward markdown-regex-list
3454 end-of-list t))
3455 (unless (or (looking-at markdown-regex-hr)
3456 (markdown-code-block-at-point-p))
3457 (setq stop (point))))
3458 (when stop
3459 (markdown-cur-list-item-bounds))))))
3461 (defun markdown-beginning-of-list ()
3462 "Move point to beginning of list at point, if any."
3463 (interactive)
3464 (let ((orig-point (point))
3465 (list-begin (save-excursion
3466 (markdown-search-backward-baseline)
3467 ;; Stop at next list item, regardless of the indentation.
3468 (markdown-next-list-item (point-max))
3469 (when (looking-at markdown-regex-list)
3470 (point)))))
3471 (when (and list-begin (<= list-begin orig-point))
3472 (goto-char list-begin))))
3474 (defun markdown-end-of-list ()
3475 "Move point to end of list at point, if any."
3476 (interactive)
3477 (let ((start (point))
3478 (end (save-excursion
3479 (when (markdown-beginning-of-list)
3480 ;; Items can't have nonlist-indent <= 1, so this
3481 ;; moves past all list items.
3482 (markdown-next-list-item 1)
3483 (skip-syntax-backward "-")
3484 (unless (eobp) (forward-char 1))
3485 (point)))))
3486 (when (and end (>= end start))
3487 (goto-char end))))
3489 (defun markdown-up-list ()
3490 "Move point to beginning of parent list item."
3491 (interactive)
3492 (let ((cur-bounds (markdown-cur-list-item-bounds)))
3493 (when cur-bounds
3494 (markdown-prev-list-item (1- (nth 3 cur-bounds)))
3495 (let ((up-bounds (markdown-cur-list-item-bounds)))
3496 (when (and up-bounds (< (nth 3 up-bounds) (nth 3 cur-bounds)))
3497 (point))))))
3499 (defun markdown-bounds-of-thing-at-point (thing)
3500 "Call `bounds-of-thing-at-point' for THING with slight modifications.
3501 Does not include trailing newlines when THING is 'line. Handles the
3502 end of buffer case by setting both endpoints equal to the value of
3503 `point-max', since an empty region will trigger empty markup insertion.
3504 Return bounds of form (beg . end) if THING is found, or nil otherwise."
3505 (let* ((bounds (bounds-of-thing-at-point thing))
3506 (a (car bounds))
3507 (b (cdr bounds)))
3508 (when bounds
3509 (when (eq thing 'line)
3510 (cond ((and (eobp) (markdown-cur-line-blank-p))
3511 (setq a b))
3512 ((char-equal (char-before b) ?\^J)
3513 (setq b (1- b)))))
3514 (cons a b))))
3516 (defun markdown-reference-definition (reference)
3517 "Find out whether Markdown REFERENCE is defined.
3518 REFERENCE should not include the square brackets.
3519 When REFERENCE is defined, return a list of the form (text start end)
3520 containing the definition text itself followed by the start and end
3521 locations of the text. Otherwise, return nil.
3522 Leave match data for `markdown-regex-reference-definition'
3523 intact additional processing."
3524 (let ((reference (downcase reference)))
3525 (save-excursion
3526 (goto-char (point-min))
3527 (catch 'found
3528 (while (re-search-forward markdown-regex-reference-definition nil t)
3529 (when (string= reference (downcase (match-string-no-properties 2)))
3530 (throw 'found
3531 (list (match-string-no-properties 5)
3532 (match-beginning 5) (match-end 5)))))))))
3534 (defun markdown-get-defined-references ()
3535 "Return a list of all defined reference labels (not including square brackets)."
3536 (save-excursion
3537 (goto-char (point-min))
3538 (let (refs)
3539 (while (re-search-forward markdown-regex-reference-definition nil t)
3540 (let ((target (match-string-no-properties 2)))
3541 (cl-pushnew target refs :test #'equal)))
3542 (reverse refs))))
3544 (defun markdown-get-used-uris ()
3545 "Return a list of all used URIs in the buffer."
3546 (save-excursion
3547 (goto-char (point-min))
3548 (let (uris)
3549 (while (re-search-forward
3550 (concat "\\(?:" markdown-regex-link-inline
3551 "\\|" markdown-regex-angle-uri
3552 "\\|" markdown-regex-uri
3553 "\\|" markdown-regex-email
3554 "\\)")
3555 nil t)
3556 (unless (or (markdown-inline-code-at-point-p)
3557 (markdown-code-block-at-point-p))
3558 (cl-pushnew (or (match-string-no-properties 6)
3559 (match-string-no-properties 10)
3560 (match-string-no-properties 12)
3561 (match-string-no-properties 13))
3562 uris :test #'equal)))
3563 (reverse uris))))
3565 (defun markdown-inline-code-at-pos (pos)
3566 "Return non-nil if there is an inline code fragment at POS.
3567 Return nil otherwise. Set match data according to
3568 `markdown-match-code' upon success.
3569 This function searches the block for a code fragment that
3570 contains the point using `markdown-match-code'. We do this
3571 because `thing-at-point-looking-at' does not work reliably with
3572 `markdown-regex-code'.
3574 The match data is set as follows:
3575 Group 1 matches the opening backquotes.
3576 Group 2 matches the code fragment itself, without backquotes.
3577 Group 3 matches the closing backquotes."
3578 (save-excursion
3579 (goto-char pos)
3580 (let ((old-point (point))
3581 (end-of-block (progn (markdown-end-of-text-block) (point)))
3582 found)
3583 (markdown-beginning-of-text-block)
3584 (while (and (markdown-match-code end-of-block)
3585 (setq found t)
3586 (< (match-end 0) old-point)))
3587 (and found ; matched something
3588 (<= (match-beginning 0) old-point) ; match contains old-point
3589 (>= (match-end 0) old-point)))))
3591 (defun markdown-inline-code-at-pos-p (pos)
3592 "Return non-nil if there is an inline code fragment at POS.
3593 Like `markdown-inline-code-at-pos`, but preserves match data."
3594 (save-match-data (markdown-inline-code-at-pos pos)))
3596 (defun markdown-inline-code-at-point ()
3597 "Return non-nil if the point is at an inline code fragment.
3598 See `markdown-inline-code-at-pos' for details."
3599 (markdown-inline-code-at-pos (point)))
3601 (defun markdown-inline-code-at-point-p ()
3602 "Return non-nil if there is inline code at the point.
3603 This is a predicate function counterpart to
3604 `markdown-inline-code-at-point' which does not modify the match
3605 data. See `markdown-code-block-at-point-p' for code blocks."
3606 (save-match-data (markdown-inline-code-at-pos (point))))
3608 (make-obsolete 'markdown-code-at-point-p 'markdown-inline-code-at-point-p "v2.2")
3610 (defun markdown-code-block-at-pos (pos)
3611 "Return match data list if there is a code block at POS.
3612 Uses text properties at the beginning of the line position.
3613 This includes pre blocks, tilde-fenced code blocks, and GFM
3614 quoted code blocks. Return nil otherwise."
3615 (setq pos (save-excursion (goto-char pos) (point-at-bol)))
3616 (or (get-text-property pos 'markdown-pre)
3617 (markdown-get-enclosing-fenced-block-construct pos)
3618 ;; polymode removes text properties set by markdown-mode, so
3619 ;; check if `poly-markdown-mode' is active and whether the
3620 ;; `chunkmode' property is non-nil at POS.
3621 (and (bound-and-true-p poly-markdown-mode)
3622 (get-text-property pos 'chunkmode))))
3624 ;; Function was renamed to emphasize that it does not modify match-data.
3625 (defalias 'markdown-code-block-at-point 'markdown-code-block-at-point-p)
3627 (defun markdown-code-block-at-point-p ()
3628 "Return non-nil if there is a code block at the point.
3629 This includes pre blocks, tilde-fenced code blocks, and GFM
3630 quoted code blocks. This function does not modify the match
3631 data. See `markdown-inline-code-at-point-p' for inline code."
3632 (save-match-data (markdown-code-block-at-pos (point))))
3634 (defun markdown-heading-at-point ()
3635 "Return non-nil if there is a heading at the point.
3636 Set match data for `markdown-regex-header'."
3637 (let ((match-data (get-text-property (point) 'markdown-heading)))
3638 (when match-data
3639 (set-match-data match-data)
3640 t)))
3642 (defun markdown-pipe-at-bol-p ()
3643 "Return non-nil if the line begins with a pipe symbol.
3644 This may be useful for tables and Pandoc's line_blocks extension."
3645 (char-equal (char-after (point-at-bol)) ?|))
3648 ;;; Markdown Font Lock Matching Functions =====================================
3650 (defun markdown-range-property-any (begin end prop prop-values)
3651 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
3652 Also returns t if PROP is a list containing one of the PROP-VALUES.
3653 Return nil otherwise."
3654 (let (props)
3655 (catch 'found
3656 (dolist (loc (number-sequence begin end))
3657 (when (setq props (get-text-property loc prop))
3658 (cond ((listp props)
3659 ;; props is a list, check for membership
3660 (dolist (val prop-values)
3661 (when (memq val props) (throw 'found loc))))
3663 ;; props is a scalar, check for equality
3664 (dolist (val prop-values)
3665 (when (eq val props) (throw 'found loc))))))))))
3667 (defun markdown-range-properties-exist (begin end props)
3668 (cl-loop
3669 for loc in (number-sequence begin end)
3670 with result = nil
3671 while (not
3672 (setq result
3673 (cl-some (lambda (prop) (get-text-property loc prop)) props)))
3674 finally return result))
3676 (defun markdown-match-inline-generic (regex last &optional faceless)
3677 "Match inline REGEX from the point to LAST.
3678 When FACELESS is non-nil, do not return matches where faces have been applied."
3679 (when (re-search-forward regex last t)
3680 (let ((bounds (markdown-code-block-at-pos (match-beginning 1)))
3681 (face (and faceless (text-property-not-all
3682 (match-beginning 0) (match-end 0) 'face nil))))
3683 (cond
3684 ;; In code block: move past it and recursively search again
3685 (bounds
3686 (when (< (goto-char (cl-second bounds)) last)
3687 (markdown-match-inline-generic regex last faceless)))
3688 ;; When faces are found in the match range, skip over the match and
3689 ;; recursively search again.
3690 (face
3691 (when (< (goto-char (match-end 0)) last)
3692 (markdown-match-inline-generic regex last faceless)))
3693 ;; Keep match data and return t when in bounds.
3695 (<= (match-end 0) last))))))
3697 (defun markdown-match-code (last)
3698 "Match inline code fragments from point to LAST."
3699 (unless (bobp)
3700 (backward-char 1))
3701 (when (markdown-match-inline-generic markdown-regex-code last)
3702 (let ((begin (match-beginning 1))
3703 (end (match-end 1))
3704 (open-begin (match-beginning 2))
3705 (open-end (match-end 2))
3706 (code-begin (match-beginning 3))
3707 (code-end (match-end 3))
3708 (close-begin (match-beginning 4))
3709 (close-end (match-end 4)))
3710 (if (or (markdown-in-comment-p begin)
3711 (markdown-in-comment-p end)
3712 (markdown-code-block-at-pos begin))
3713 (progn (goto-char (min (1+ begin) last))
3714 (when (< (point) last)
3715 (markdown-match-code last)))
3716 (set-match-data (list begin end
3717 open-begin open-end
3718 code-begin code-end
3719 close-begin close-end))
3720 t))))
3722 (defun markdown-match-bold (last)
3723 "Match inline bold from the point to LAST."
3724 (when (markdown-match-inline-generic markdown-regex-bold last)
3725 (let ((begin (match-beginning 2))
3726 (end (match-end 2)))
3727 (if (or (markdown-inline-code-at-pos-p begin)
3728 (markdown-inline-code-at-pos-p end)
3729 (markdown-in-comment-p)
3730 (markdown-range-property-any
3731 begin begin 'face '(markdown-url-face
3732 markdown-plain-url-face))
3733 (markdown-range-property-any
3734 begin end 'face '(markdown-math-face)))
3735 (progn (goto-char (min (1+ begin) last))
3736 (when (< (point) last)
3737 (markdown-match-italic last)))
3738 (set-match-data (list (match-beginning 2) (match-end 2)
3739 (match-beginning 3) (match-end 3)
3740 (match-beginning 4) (match-end 4)
3741 (match-beginning 5) (match-end 5)))
3742 t))))
3744 (defun markdown-match-italic (last)
3745 "Match inline italics from the point to LAST."
3746 (let ((regex (if (eq major-mode 'gfm-mode)
3747 markdown-regex-gfm-italic markdown-regex-italic)))
3748 (when (markdown-match-inline-generic regex last)
3749 (let ((begin (match-beginning 1))
3750 (end (match-end 1)))
3751 (if (or (markdown-inline-code-at-pos-p begin)
3752 (markdown-inline-code-at-pos-p end)
3753 (markdown-in-comment-p)
3754 (markdown-range-property-any
3755 begin begin 'face '(markdown-url-face
3756 markdown-plain-url-face))
3757 (markdown-range-property-any
3758 begin end 'face '(markdown-bold-face
3759 markdown-list-face
3760 markdown-math-face)))
3761 (progn (goto-char (min (1+ begin) last))
3762 (when (< (point) last)
3763 (markdown-match-italic last)))
3764 (set-match-data (list (match-beginning 1) (match-end 1)
3765 (match-beginning 2) (match-end 2)
3766 (match-beginning 3) (match-end 3)
3767 (match-beginning 4) (match-end 4)))
3768 t)))))
3770 (defun markdown-match-math-generic (regex last)
3771 "Match REGEX from point to LAST.
3772 REGEX is either `markdown-regex-math-inline-single' for matching
3773 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
3774 (when (and markdown-enable-math (markdown-match-inline-generic regex last))
3775 (let ((begin (match-beginning 1)) (end (match-end 1)))
3776 (prog1
3777 (if (or (markdown-range-property-any
3778 begin end 'face (list markdown-inline-code-face
3779 markdown-bold-face))
3780 (markdown-range-properties-exist
3781 begin end
3782 (markdown-get-fenced-block-middle-properties)))
3783 (markdown-match-math-generic regex last)
3785 (goto-char (1+ (match-end 0)))))))
3787 (defun markdown-match-list-items (last)
3788 "Match list items from point to LAST."
3789 (when (markdown-match-inline-generic markdown-regex-list last)
3790 (let ((begin (match-beginning 2))
3791 (end (match-end 2)))
3792 (if (or (markdown-range-property-any
3793 begin end 'face (list markdown-inline-code-face
3794 markdown-bold-face
3795 markdown-math-face))
3796 (markdown-range-properties-exist begin end '(markdown-hr))
3797 (markdown-in-comment-p))
3798 (progn (goto-char (min (1+ (match-end 0)) last))
3799 (markdown-match-list-items last))
3800 (set-match-data (list (match-beginning 0) (match-end 0)
3801 (match-beginning 1) (match-end 1)
3802 (match-beginning 2) (match-end 2)))
3803 (goto-char (1+ (match-end 0)))))))
3805 (defun markdown-match-math-single (last)
3806 "Match single quoted $..$ math from point to LAST."
3807 (markdown-match-math-generic markdown-regex-math-inline-single last))
3809 (defun markdown-match-math-double (last)
3810 "Match double quoted $$..$$ math from point to LAST."
3811 (markdown-match-math-generic markdown-regex-math-inline-double last))
3813 (defun markdown-match-math-display (last)
3814 "Match bracketed display math \[..\] and \\[..\\] from point to LAST."
3815 (markdown-match-math-generic markdown-regex-math-display last))
3817 (defun markdown-match-propertized-text (property last)
3818 "Match text with PROPERTY from point to LAST.
3819 Restore match data previously stored in PROPERTY."
3820 (let ((saved (get-text-property (point) property))
3821 pos)
3822 (unless saved
3823 (setq pos (next-single-char-property-change (point) property nil last))
3824 (setq saved (get-text-property pos property)))
3825 (when saved
3826 (set-match-data saved)
3827 ;; Step at least one character beyond point. Otherwise
3828 ;; `font-lock-fontify-keywords-region' infloops.
3829 (goto-char (min (1+ (max (match-end 0) (point)))
3830 (point-max)))
3831 saved)))
3833 (defun markdown-match-pre-blocks (last)
3834 "Match preformatted blocks from point to LAST.
3835 Use data stored in 'markdown-pre text property during syntax
3836 analysis."
3837 (markdown-match-propertized-text 'markdown-pre last))
3839 (defun markdown-match-gfm-code-blocks (last)
3840 "Match GFM quoted code blocks from point to LAST.
3841 Use data stored in 'markdown-gfm-code text property during syntax
3842 analysis."
3843 (markdown-match-propertized-text 'markdown-gfm-code last))
3845 (defun markdown-match-gfm-open-code-blocks (last)
3846 (markdown-match-propertized-text 'markdown-gfm-block-begin last))
3848 (defun markdown-match-gfm-close-code-blocks (last)
3849 (markdown-match-propertized-text 'markdown-gfm-block-end last))
3851 (defun markdown-match-fenced-code-blocks (last)
3852 "Match fenced code blocks from the point to LAST."
3853 (markdown-match-propertized-text 'markdown-fenced-code last))
3855 (defun markdown-match-fenced-start-code-block (last)
3856 (markdown-match-propertized-text 'markdown-tilde-fence-begin last))
3858 (defun markdown-match-fenced-end-code-block (last)
3859 (markdown-match-propertized-text 'markdown-tilde-fence-end last))
3861 (defun markdown-match-blockquotes (last)
3862 "Match blockquotes from point to LAST.
3863 Use data stored in 'markdown-blockquote text property during syntax
3864 analysis."
3865 (markdown-match-propertized-text 'markdown-blockquote last))
3867 (defun markdown-match-hr (last)
3868 "Match horizontal rules comments from the point to LAST."
3869 (markdown-match-propertized-text 'markdown-hr last))
3871 (defun markdown-match-comments (last)
3872 "Match HTML comments from the point to LAST."
3873 (when (and (skip-syntax-forward "^<" last))
3874 (let ((beg (point)))
3875 (when (and (skip-syntax-forward "^>" last) (< (point) last))
3876 (forward-char)
3877 (set-match-data (list beg (point)))
3878 t))))
3880 (defun markdown-match-generic-links (last ref)
3881 "Match inline links from point to LAST.
3882 When REF is non-nil, match reference links instead of standard
3883 links with URLs."
3884 ;; Search for the next potential link (not in a code block).
3885 (while (and (progn
3886 ;; Clear match data to test for a match after functions returns.
3887 (set-match-data nil)
3888 (re-search-forward "\\(!\\)?\\(\\[\\)" last 'limit))
3889 ;; Keep searching if this is in a code block, inline
3890 ;; code, or a comment, or if it is include syntax.
3891 (or (markdown-code-block-at-point-p)
3892 (markdown-inline-code-at-pos-p (match-beginning 0))
3893 (markdown-inline-code-at-pos-p (match-end 0))
3894 (markdown-in-comment-p)
3895 (and (char-equal (char-after (point-at-bol)) ?<)
3896 (char-equal (char-after (1+ (point-at-bol))) ?<)))
3897 (< (point) last)))
3898 ;; Match opening exclamation point (optional) and left bracket.
3899 (when (match-beginning 2)
3900 (let* ((bang (match-beginning 1))
3901 (first-begin (match-beginning 2))
3902 ;; Find end of block to prevent matching across blocks.
3903 (end-of-block (save-excursion
3904 (progn
3905 (goto-char (match-beginning 2))
3906 (markdown-end-of-text-block)
3907 (point))))
3908 ;; Move over balanced expressions to closing right bracket.
3909 ;; Catch unbalanced expression errors and return nil.
3910 (first-end (condition-case nil
3911 (and (goto-char first-begin)
3912 (scan-sexps (point) 1))
3913 (error nil)))
3914 ;; Continue with point at CONT-POINT upon failure.
3915 (cont-point (min (1+ first-begin) last))
3916 second-begin second-end url-begin url-end
3917 title-begin title-end)
3918 ;; When bracket found, in range, and followed by a left paren/bracket...
3919 (when (and first-end (< first-end end-of-block) (goto-char first-end)
3920 (char-equal (char-after (point)) (if ref ?\[ ?\()))
3921 ;; Scan across balanced expressions for closing parenthesis/bracket.
3922 (setq second-begin (point)
3923 second-end (condition-case nil
3924 (scan-sexps (point) 1)
3925 (error nil)))
3926 ;; Check that closing parenthesis/bracket is in range.
3927 (if (and second-end (<= second-end end-of-block) (<= second-end last))
3928 (progn
3929 ;; Search for (optional) title inside closing parenthesis
3930 (when (and (not ref) (search-forward "\"" second-end t))
3931 (setq title-begin (1- (point))
3932 title-end (and (goto-char second-end)
3933 (search-backward "\"" (1+ title-begin) t))
3934 title-end (and title-end (1+ title-end))))
3935 ;; Store URL/reference range
3936 (setq url-begin (1+ second-begin)
3937 url-end (1- (or title-begin second-end)))
3938 ;; Set match data, move point beyond link, and return
3939 (set-match-data
3940 (list (or bang first-begin) second-end ; 0 - all
3941 bang (and bang (1+ bang)) ; 1 - bang
3942 first-begin (1+ first-begin) ; 2 - markup
3943 (1+ first-begin) (1- first-end) ; 3 - link text
3944 (1- first-end) first-end ; 4 - markup
3945 second-begin (1+ second-begin) ; 5 - markup
3946 url-begin url-end ; 6 - url/reference
3947 title-begin title-end ; 7 - title
3948 (1- second-end) second-end)) ; 8 - markup
3949 ;; Nullify cont-point and leave point at end and
3950 (setq cont-point nil)
3951 (goto-char second-end))
3952 ;; If no closing parenthesis in range, update continuation point
3953 (setq cont-point (min end-of-block second-begin))))
3954 (cond
3955 ;; On failure, continue searching at cont-point
3956 ((and cont-point (< cont-point last))
3957 (goto-char cont-point)
3958 (markdown-match-generic-links last ref))
3959 ;; No more text, return nil
3960 ((and cont-point (= cont-point last))
3961 nil)
3962 ;; Return t if a match occurred
3963 (t t)))))
3965 (defun markdown-match-inline-links (last)
3966 "Match standard inline links from point to LAST."
3967 (markdown-match-generic-links last nil))
3969 (defun markdown-match-reference-links (last)
3970 "Match inline reference links from point to LAST."
3971 (markdown-match-generic-links last t))
3973 (defun markdown-match-angle-uris (last)
3974 "Match angle bracket URIs from point to LAST."
3975 (when (markdown-match-inline-generic markdown-regex-angle-uri last)
3976 (goto-char (1+ (match-end 0)))))
3978 (defun markdown-match-plain-uris (last)
3979 "Match plain URIs from point to LAST."
3980 (when (markdown-match-inline-generic markdown-regex-uri last t)
3981 (goto-char (1+ (match-end 0)))))
3983 (defvar markdown-conditional-search-function #'re-search-forward
3984 "Conditional search function used in `markdown-search-until-condition'.
3985 Made into a variable to allow for dynamic let-binding.")
3987 (defun markdown-search-until-condition (condition &rest args)
3988 (let (ret)
3989 (while (and (not ret) (apply markdown-conditional-search-function args))
3990 (setq ret (funcall condition)))
3991 ret))
3993 (defun markdown-match-generic-metadata
3994 (regexp last &optional block-begin-re block-end-re)
3995 "Match metadata declarations specified by REGEXP from point to LAST.
3996 These declarations must appear inside a metadata block specified
3997 by BLOCK-BEGIN-RE and BLOCK-END-RE. BLOCK-BEGIN-RE is a regular
3998 expression denoting the beginning of a metadata block. If it is
3999 nil, we assume metadata can only appear at the beginning of the
4000 buffer. Similarly, BLOCK-END-RE is a regular expression denoting
4001 the end of a metadata block. If it is nil, assume blocks end with
4002 a blank line or the end of the buffer. There may be at most one such
4003 block in a file. Subsequent blocks will be ignored."
4004 (let* ((first (point))
4005 (begin-re (or block-begin-re "\\`"))
4006 (end-re (or block-end-re "\n[ \t]*\n\\|\n\\'\\|\\'"))
4008 ;; (prev-block-begin (when (re-search-backward begin-re (point-min) t) (match-end 0)))
4009 ;; (next-block-begin (when (re-search-forward begin-re last t) (match-end 0)))
4010 ;; (block-begin (or prev-block-begin next-block-begin))
4012 (block-begin (when (or (re-search-backward begin-re (point-min) t)
4013 (re-search-forward begin-re last t))
4014 (match-end 0)))
4016 (block-end (and block-begin (goto-char block-begin)
4017 (re-search-forward end-re nil t))))
4018 (cond
4019 ;; Don't match declarations if there is no metadata block or if
4020 ;; the point is beyond the block. Move point to point-max to
4021 ;; prevent additional searches and return return nil since nothing
4022 ;; was found.
4023 ((or (null block-begin) (and block-end (> first block-end)))
4024 (goto-char (point-max))
4025 nil)
4026 ;; No declarations to match if a block was found but not in
4027 ;; range. Move point to LAST, to resume there, and return nil.
4028 ((> block-begin last)
4029 (goto-char last)
4030 nil)
4031 ;; If a block was found that begins before LAST and ends after
4032 ;; point, search for declarations inside it.
4034 ;; If the starting is before the beginning of the block, start
4035 ;; there. Otherwise, move back to FIRST.
4036 (goto-char (if (< first block-begin) block-begin first))
4037 (if (re-search-forward regexp (min last block-end) t)
4038 ;; If a metadata declaration is found, set match-data and return t.
4039 (let ((key-beginning (match-beginning 1))
4040 (key-end (match-end 1))
4041 (markup-begin (match-beginning 2))
4042 (markup-end (match-end 2))
4043 (value-beginning (match-beginning 3)))
4044 (set-match-data (list key-beginning (point) ; complete metadata
4045 key-beginning key-end ; key
4046 markup-begin markup-end ; markup
4047 value-beginning (point))) ; value
4049 ;; Otherwise, move the point to last and return nil
4050 (goto-char last)
4051 nil)))))
4053 (defun markdown-match-declarative-metadata (last)
4054 "Match declarative metadata from the point to LAST."
4055 (markdown-match-generic-metadata markdown-regex-declarative-metadata last))
4057 (defun markdown-match-pandoc-metadata (last)
4058 "Match Pandoc metadata from the point to LAST."
4059 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
4061 (defun markdown-match-yaml-metadata-begin (last)
4062 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last))
4064 (defun markdown-match-yaml-metadata-end (last)
4065 (markdown-match-propertized-text 'markdown-yaml-metadata-end last))
4067 (defun markdown-match-yaml-metadata-key (last)
4068 (markdown-match-propertized-text 'markdown-metadata-key last))
4070 (defun markdown-match-wiki-link (last)
4071 "Match wiki links from point to LAST."
4072 (when (and markdown-enable-wiki-links
4073 (not markdown-wiki-link-fontify-missing)
4074 (markdown-match-inline-generic markdown-regex-wiki-link last))
4075 (let ((begin (match-beginning 1)) (end (match-end 1)))
4076 (if (or (markdown-in-comment-p begin)
4077 (markdown-in-comment-p end)
4078 (markdown-inline-code-at-pos-p begin)
4079 (markdown-inline-code-at-pos-p end)
4080 (markdown-code-block-at-pos begin))
4081 (progn (goto-char (min (1+ begin) last))
4082 (when (< (point) last)
4083 (markdown-match-wiki-link last)))
4084 (set-match-data (list begin end))
4085 t))))
4087 (defun markdown-match-inline-attributes (last)
4088 "Match inline attributes from point to LAST."
4089 (when (markdown-match-inline-generic markdown-regex-inline-attributes last)
4090 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
4091 (markdown-inline-code-at-pos-p (match-end 0))
4092 (markdown-in-comment-p))
4093 t)))
4095 (defun markdown-match-leanpub-sections (last)
4096 "Match Leanpub section markers from point to LAST."
4097 (when (markdown-match-inline-generic markdown-regex-leanpub-sections last)
4098 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
4099 (markdown-inline-code-at-pos-p (match-end 0))
4100 (markdown-in-comment-p))
4101 t)))
4103 (defun markdown-match-includes (last)
4104 "Match include statements from point to LAST.
4105 Sets match data for the following seven groups:
4106 Group 1: opening two angle brackets
4107 Group 2: opening title delimiter (optional)
4108 Group 3: title text (optional)
4109 Group 4: closing title delimiter (optional)
4110 Group 5: opening filename delimiter
4111 Group 6: filename
4112 Group 7: closing filename delimiter"
4113 (when (markdown-match-inline-generic markdown-regex-include last)
4114 (let ((valid (not (or (markdown-in-comment-p (match-beginning 0))
4115 (markdown-in-comment-p (match-end 0))
4116 (markdown-code-block-at-pos (match-beginning 0))))))
4117 (cond
4118 ;; Parentheses and maybe square brackets, but no curly braces:
4119 ;; match optional title in square brackets and file in parentheses.
4120 ((and valid (match-beginning 5)
4121 (not (match-beginning 8)))
4122 (set-match-data (list (match-beginning 1) (match-end 7)
4123 (match-beginning 1) (match-end 1)
4124 (match-beginning 2) (match-end 2)
4125 (match-beginning 3) (match-end 3)
4126 (match-beginning 4) (match-end 4)
4127 (match-beginning 5) (match-end 5)
4128 (match-beginning 6) (match-end 6)
4129 (match-beginning 7) (match-end 7))))
4130 ;; Only square brackets present: match file in square brackets.
4131 ((and valid (match-beginning 2)
4132 (not (match-beginning 5))
4133 (not (match-beginning 7)))
4134 (set-match-data (list (match-beginning 1) (match-end 4)
4135 (match-beginning 1) (match-end 1)
4136 nil nil
4137 nil nil
4138 nil nil
4139 (match-beginning 2) (match-end 2)
4140 (match-beginning 3) (match-end 3)
4141 (match-beginning 4) (match-end 4))))
4142 ;; Only curly braces present: match file in curly braces.
4143 ((and valid (match-beginning 8)
4144 (not (match-beginning 2))
4145 (not (match-beginning 5)))
4146 (set-match-data (list (match-beginning 1) (match-end 10)
4147 (match-beginning 1) (match-end 1)
4148 nil nil
4149 nil nil
4150 nil nil
4151 (match-beginning 8) (match-end 8)
4152 (match-beginning 9) (match-end 9)
4153 (match-beginning 10) (match-end 10))))
4155 ;; Not a valid match, move to next line and search again.
4156 (forward-line)
4157 (when (< (point) last)
4158 (setq valid (markdown-match-includes last)))))
4159 valid)))
4162 ;;; Markdown Font Fontification Functions =====================================
4164 (defun markdown--first-displayable (seq)
4165 "Return the first displayable character or string in SEQ.
4166 SEQ may be an atom or a sequence."
4167 (let ((seq (if (listp seq) seq (list seq))))
4168 (cond ((stringp (car seq))
4169 (cl-find-if
4170 (lambda (str)
4171 (and (mapcar #'char-displayable-p (string-to-list str))))
4172 seq))
4173 ((characterp (car seq))
4174 (cl-find-if #'char-displayable-p seq)))))
4176 (defun markdown--marginalize-string (level)
4177 "Generate atx markup string of given LEVEL for left margin."
4178 (let ((margin-left-space-count
4179 (- markdown-marginalize-headers-margin-width level)))
4180 (concat (make-string margin-left-space-count ? )
4181 (make-string level ?#))))
4183 (defun markdown-marginalize-update-current ()
4184 "Update the window configuration to create a left margin."
4185 ;; Emacs 25 or later is needed for window-font-width and default-font-width.
4186 (if (and (fboundp 'window-font-width) (fboundp 'default-font-width))
4187 (let* ((header-delimiter-font-width
4188 (window-font-width nil 'markdown-header-delimiter-face))
4189 (margin-pixel-width (* markdown-marginalize-headers-margin-width
4190 header-delimiter-font-width))
4191 (margin-char-width (/ margin-pixel-width (default-font-width))))
4192 (set-window-margins nil margin-char-width))
4193 ;; As a fallback, simply set margin based on character count.
4194 (set-window-margins nil markdown-marginalize-headers-margin-width)))
4196 (defun markdown-fontify-headings (last)
4197 "Add text properties to headings from point to LAST."
4198 (when (markdown-match-propertized-text 'markdown-heading last)
4199 (let* ((level (markdown-outline-level))
4200 (heading-face
4201 (intern (format "markdown-header-face-%d" level)))
4202 (heading-props `(face ,heading-face))
4203 (left-markup-props
4204 `(face markdown-header-delimiter-face
4205 ,@(cond
4206 (markdown-hide-markup
4207 `(display ""))
4208 (markdown-marginalize-headers
4209 `(display ((margin left-margin)
4210 ,(markdown--marginalize-string level)))))))
4211 (right-markup-props
4212 `(face markdown-header-delimiter-face
4213 ,@(when markdown-hide-markup `(display ""))))
4214 (rule-props `(face markdown-header-rule-face
4215 ,@(when markdown-hide-markup `(display "")))))
4216 (if (match-end 1)
4217 ;; Setext heading
4218 (progn (add-text-properties
4219 (match-beginning 1) (match-end 1) heading-props)
4220 (if (= level 1)
4221 (add-text-properties
4222 (match-beginning 2) (match-end 2) rule-props)
4223 (add-text-properties
4224 (match-beginning 3) (match-end 3) rule-props)))
4225 ;; atx heading
4226 (add-text-properties
4227 (match-beginning 4) (match-end 4) left-markup-props)
4228 (add-text-properties
4229 (match-beginning 5) (match-end 5) heading-props)
4230 (when (match-end 6)
4231 (add-text-properties
4232 (match-beginning 6) (match-end 6) right-markup-props))))
4235 (defun markdown-fontify-blockquotes (last)
4236 "Apply font-lock properties to blockquotes from point to LAST."
4237 (when (markdown-match-blockquotes last)
4238 (let ((display-string
4239 (markdown--first-displayable markdown-blockquote-display-char)))
4240 (add-text-properties
4241 (match-beginning 1) (match-end 1)
4242 (if markdown-hide-markup
4243 `(face markdown-blockquote-face display ,display-string)
4244 `(face markdown-markup-face)))
4245 (font-lock-append-text-property
4246 (match-beginning 0) (match-end 0) 'face 'markdown-blockquote-face)
4247 t)))
4249 (defun markdown-fontify-list-items (last)
4250 "Apply font-lock properties to list markers from point to LAST."
4251 (when (markdown-match-list-items last)
4252 (let* ((indent (length (match-string-no-properties 1)))
4253 (level (/ indent 4)) ;; level = 0, 1, 2, ...
4254 (bullet (nth (mod level (length markdown-list-item-bullets))
4255 markdown-list-item-bullets)))
4256 (add-text-properties
4257 (match-beginning 2) (match-end 2) '(face markdown-list-face))
4258 (when markdown-hide-markup
4259 (cond
4260 ;; Unordered lists
4261 ((string-match-p "[\\*\\+-]" (match-string 2))
4262 (add-text-properties
4263 (match-beginning 2) (match-end 2) `(display ,bullet)))
4264 ;; Definition lists
4265 ((string-equal ":" (match-string 2))
4266 (let ((display-string
4267 (char-to-string (markdown--first-displayable
4268 markdown-definition-display-char))))
4269 (add-text-properties (match-beginning 2) (match-end 2)
4270 `(display ,display-string)))))))
4273 (defun markdown-fontify-hrs (last)
4274 "Add text properties to horizontal rules from point to LAST."
4275 (when (markdown-match-hr last)
4276 (let ((hr-char (markdown--first-displayable markdown-hr-display-char)))
4277 (add-text-properties
4278 (match-beginning 0) (match-end 0)
4279 `(face markdown-hr-face
4280 font-lock-multiline t
4281 ,@(when (and markdown-hide-markup hr-char)
4282 `(display ,(make-string
4283 (window-body-width) hr-char)))))
4284 t)))
4286 (defun markdown-fontify-sub-superscripts (last)
4287 "Apply text properties to sub- and superscripts from point to LAST."
4288 (when (markdown-search-until-condition
4289 (lambda () (and (not (markdown-code-block-at-point-p))
4290 (not (markdown-inline-code-at-point-p))
4291 (not (markdown-in-comment-p))))
4292 markdown-regex-sub-superscript last t)
4293 (let* ((subscript-p (string= (match-string 2) "~"))
4294 (index (if subscript-p 0 1))
4295 (mp (list 'face 'markdown-markup-face
4296 'invisible 'markdown-markup)))
4297 (when markdown-hide-markup
4298 (put-text-property (match-beginning 3) (match-end 3)
4299 'display
4300 (nth index markdown-sub-superscript-display)))
4301 (add-text-properties (match-beginning 2) (match-end 2) mp)
4302 (add-text-properties (match-beginning 4) (match-end 4) mp)
4303 t)))
4306 ;;; Syntax Table ==============================================================
4308 (defvar markdown-mode-syntax-table
4309 (let ((tab (make-syntax-table text-mode-syntax-table)))
4310 (modify-syntax-entry ?\" "." tab)
4311 tab)
4312 "Syntax table for `markdown-mode'.")
4315 ;;; Element Insertion =========================================================
4317 (defun markdown-ensure-blank-line-before ()
4318 "If previous line is not already blank, insert a blank line before point."
4319 (unless (bolp) (insert "\n"))
4320 (unless (or (bobp) (looking-back "\n\\s-*\n" nil)) (insert "\n")))
4322 (defun markdown-ensure-blank-line-after ()
4323 "If following line is not already blank, insert a blank line after point.
4324 Return the point where it was originally."
4325 (save-excursion
4326 (unless (eolp) (insert "\n"))
4327 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
4329 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
4330 "Insert the strings S1 and S2, wrapping around region or THING.
4331 If a region is specified by the optional BEG and END arguments,
4332 wrap the strings S1 and S2 around that region.
4333 If there is an active region, wrap the strings S1 and S2 around
4334 the region. If there is not an active region but the point is at
4335 THING, wrap that thing (which defaults to word). Otherwise, just
4336 insert S1 and S2 and place the point in between. Return the
4337 bounds of the entire wrapped string, or nil if nothing was wrapped
4338 and S1 and S2 were only inserted."
4339 (let (a b bounds new-point)
4340 (cond
4341 ;; Given region
4342 ((and beg end)
4343 (setq a beg
4344 b end
4345 new-point (+ (point) (length s1))))
4346 ;; Active region
4347 ((markdown-use-region-p)
4348 (setq a (region-beginning)
4349 b (region-end)
4350 new-point (+ (point) (length s1))))
4351 ;; Thing (word) at point
4352 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
4353 (setq a (car bounds)
4354 b (cdr bounds)
4355 new-point (+ (point) (length s1))))
4356 ;; No active region and no word
4358 (setq a (point)
4359 b (point))))
4360 (goto-char b)
4361 (insert s2)
4362 (goto-char a)
4363 (insert s1)
4364 (when new-point (goto-char new-point))
4365 (if (= a b)
4367 (setq b (+ b (length s1) (length s2)))
4368 (cons a b))))
4370 (defun markdown-point-after-unwrap (cur prefix suffix)
4371 "Return desired position of point after an unwrapping operation.
4372 CUR gives the position of the point before the operation.
4373 Additionally, two cons cells must be provided. PREFIX gives the
4374 bounds of the prefix string and SUFFIX gives the bounds of the
4375 suffix string."
4376 (cond ((< cur (cdr prefix)) (car prefix))
4377 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
4378 ((<= cur (cdr suffix))
4379 (- cur (+ (- (cdr prefix) (car prefix))
4380 (- cur (car suffix)))))
4381 (t cur)))
4383 (defun markdown-unwrap-thing-at-point (regexp all text)
4384 "Remove prefix and suffix of thing at point and reposition the point.
4385 When the thing at point matches REGEXP, replace the subexpression
4386 ALL with the string in subexpression TEXT. Reposition the point
4387 in an appropriate location accounting for the removal of prefix
4388 and suffix strings. Return new bounds of string from group TEXT.
4389 When REGEXP is nil, assumes match data is already set."
4390 (when (or (null regexp)
4391 (thing-at-point-looking-at regexp))
4392 (let ((cur (point))
4393 (prefix (cons (match-beginning all) (match-beginning text)))
4394 (suffix (cons (match-end text) (match-end all)))
4395 (bounds (cons (match-beginning text) (match-end text))))
4396 ;; Replace the thing at point
4397 (replace-match (match-string text) t t nil all)
4398 ;; Reposition the point
4399 (goto-char (markdown-point-after-unwrap cur prefix suffix))
4400 ;; Adjust bounds
4401 (setq bounds (cons (car prefix)
4402 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
4404 (defun markdown-unwrap-things-in-region (beg end regexp all text)
4405 "Remove prefix and suffix of all things in region from BEG to END.
4406 When a thing in the region matches REGEXP, replace the
4407 subexpression ALL with the string in subexpression TEXT.
4408 Return a cons cell containing updated bounds for the region."
4409 (save-excursion
4410 (goto-char beg)
4411 (let ((removed 0) len-all len-text)
4412 (while (re-search-forward regexp (- end removed) t)
4413 (setq len-all (length (match-string-no-properties all)))
4414 (setq len-text (length (match-string-no-properties text)))
4415 (setq removed (+ removed (- len-all len-text)))
4416 (replace-match (match-string text) t t nil all))
4417 (cons beg (- end removed)))))
4419 (defun markdown-insert-hr (arg)
4420 "Insert or replace a horizonal rule.
4421 By default, use the first element of `markdown-hr-strings'. When
4422 ARG is non-nil, as when given a prefix, select a different
4423 element as follows. When prefixed with \\[universal-argument],
4424 use the last element of `markdown-hr-strings' instead. When
4425 prefixed with an integer from 1 to the length of
4426 `markdown-hr-strings', use the element in that position instead."
4427 (interactive "*P")
4428 (when (thing-at-point-looking-at markdown-regex-hr)
4429 (delete-region (match-beginning 0) (match-end 0)))
4430 (markdown-ensure-blank-line-before)
4431 (cond ((equal arg '(4))
4432 (insert (car (reverse markdown-hr-strings))))
4433 ((and (integerp arg) (> arg 0)
4434 (<= arg (length markdown-hr-strings)))
4435 (insert (nth (1- arg) markdown-hr-strings)))
4437 (insert (car markdown-hr-strings))))
4438 (markdown-ensure-blank-line-after))
4440 (defun markdown-insert-bold ()
4441 "Insert markup to make a region or word bold.
4442 If there is an active region, make the region bold. If the point
4443 is at a non-bold word, make the word bold. If the point is at a
4444 bold word or phrase, remove the bold markup. Otherwise, simply
4445 insert bold delimiters and place the point in between them."
4446 (interactive)
4447 (let ((delim (if markdown-bold-underscore "__" "**")))
4448 (if (markdown-use-region-p)
4449 ;; Active region
4450 (let ((bounds (markdown-unwrap-things-in-region
4451 (region-beginning) (region-end)
4452 markdown-regex-bold 2 4)))
4453 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4454 ;; Bold markup removal, bold word at point, or empty markup insertion
4455 (if (thing-at-point-looking-at markdown-regex-bold)
4456 (markdown-unwrap-thing-at-point nil 2 4)
4457 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4459 (defun markdown-insert-italic ()
4460 "Insert markup to make a region or word italic.
4461 If there is an active region, make the region italic. If the point
4462 is at a non-italic word, make the word italic. If the point is at an
4463 italic word or phrase, remove the italic markup. Otherwise, simply
4464 insert italic delimiters and place the point in between them."
4465 (interactive)
4466 (let ((delim (if markdown-italic-underscore "_" "*")))
4467 (if (markdown-use-region-p)
4468 ;; Active region
4469 (let ((bounds (markdown-unwrap-things-in-region
4470 (region-beginning) (region-end)
4471 markdown-regex-italic 1 3)))
4472 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4473 ;; Italic markup removal, italic word at point, or empty markup insertion
4474 (if (thing-at-point-looking-at markdown-regex-italic)
4475 (markdown-unwrap-thing-at-point nil 1 3)
4476 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4478 (defun markdown-insert-strike-through ()
4479 "Insert markup to make a region or word strikethrough.
4480 If there is an active region, make the region strikethrough. If the point
4481 is at a non-bold word, make the word strikethrough. If the point is at a
4482 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
4483 simply insert bold delimiters and place the point in between them."
4484 (interactive)
4485 (let ((delim "~~"))
4486 (if (markdown-use-region-p)
4487 ;; Active region
4488 (let ((bounds (markdown-unwrap-things-in-region
4489 (region-beginning) (region-end)
4490 markdown-regex-strike-through 2 4)))
4491 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4492 ;; Strikethrough markup removal, strikethrough word at point, or empty markup insertion
4493 (if (thing-at-point-looking-at markdown-regex-strike-through)
4494 (markdown-unwrap-thing-at-point nil 2 4)
4495 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4497 (defun markdown-insert-code ()
4498 "Insert markup to make a region or word an inline code fragment.
4499 If there is an active region, make the region an inline code
4500 fragment. If the point is at a word, make the word an inline
4501 code fragment. Otherwise, simply insert code delimiters and
4502 place the point in between them."
4503 (interactive)
4504 (if (markdown-use-region-p)
4505 ;; Active region
4506 (let ((bounds (markdown-unwrap-things-in-region
4507 (region-beginning) (region-end)
4508 markdown-regex-code 1 3)))
4509 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
4510 ;; Code markup removal, code markup for word, or empty markup insertion
4511 (if (markdown-inline-code-at-point)
4512 (markdown-unwrap-thing-at-point nil 0 2)
4513 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
4515 (defun markdown-insert-kbd ()
4516 "Insert markup to wrap region or word in <kbd> tags.
4517 If there is an active region, use the region. If the point is at
4518 a word, use the word. Otherwise, simply insert <kbd> tags and
4519 place the point in between them."
4520 (interactive)
4521 (if (markdown-use-region-p)
4522 ;; Active region
4523 (let ((bounds (markdown-unwrap-things-in-region
4524 (region-beginning) (region-end)
4525 markdown-regex-kbd 0 2)))
4526 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil (car bounds) (cdr bounds)))
4527 ;; Markup removal, markup for word, or empty markup insertion
4528 (if (thing-at-point-looking-at markdown-regex-kbd)
4529 (markdown-unwrap-thing-at-point nil 0 2)
4530 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil))))
4532 (defun markdown-insert-inline-link (text url &optional title)
4533 "Insert an inline link with TEXT pointing to URL.
4534 Optionally, the user can provide a TITLE."
4535 (let ((cur (point)))
4536 (setq title (and title (concat " \"" title "\"")))
4537 (insert (concat "[" text "](" url title ")"))
4538 (cond ((not text) (goto-char (+ 1 cur)))
4539 ((not url) (goto-char (+ 3 (length text) cur))))))
4541 (defun markdown-insert-inline-image (text url &optional title)
4542 "Insert an inline link with alt TEXT pointing to URL.
4543 Optionally, also provide a TITLE."
4544 (let ((cur (point)))
4545 (setq title (and title (concat " \"" title "\"")))
4546 (insert (concat "![" text "](" url title ")"))
4547 (cond ((not text) (goto-char (+ 2 cur)))
4548 ((not url) (goto-char (+ 4 (length text) cur))))))
4550 (defun markdown-insert-reference-link (text label &optional url title)
4551 "Insert a reference link and, optionally, a reference definition.
4552 The link TEXT will be inserted followed by the optional LABEL.
4553 If a URL is given, also insert a definition for the reference
4554 LABEL according to `markdown-reference-location'. If a TITLE is
4555 given, it will be added to the end of the reference definition
4556 and will be used to populate the title attribute when converted
4557 to XHTML. If URL is nil, insert only the link portion (for
4558 example, when a reference label is already defined)."
4559 (insert (concat "[" text "][" label "]"))
4560 (when url
4561 (markdown-insert-reference-definition
4562 (if (string-equal label "") text label)
4563 url title)))
4565 (defun markdown-insert-reference-image (text label &optional url title)
4566 "Insert a reference image and, optionally, a reference definition.
4567 The alt TEXT will be inserted followed by the optional LABEL.
4568 If a URL is given, also insert a definition for the reference
4569 LABEL according to `markdown-reference-location'. If a TITLE is
4570 given, it will be added to the end of the reference definition
4571 and will be used to populate the title attribute when converted
4572 to XHTML. If URL is nil, insert only the link portion (for
4573 example, when a reference label is already defined)."
4574 (insert (concat "![" text "][" label "]"))
4575 (when url
4576 (markdown-insert-reference-definition
4577 (if (string-equal label "") text label)
4578 url title)))
4580 (defun markdown-insert-reference-definition (label &optional url title)
4581 "Add definition for reference LABEL with URL and TITLE.
4582 LABEL is a Markdown reference label without square brackets.
4583 URL and TITLE are optional. When given, the TITLE will
4584 be used to populate the title attribute when converted to XHTML."
4585 ;; END specifies where to leave the point upon return
4586 (let ((end (point)))
4587 (cl-case markdown-reference-location
4588 (end (goto-char (point-max)))
4589 (immediately (markdown-end-of-text-block))
4590 (subtree (markdown-end-of-subtree))
4591 (header (markdown-end-of-defun)))
4592 ;; Skip backwards over local variables. This logic is similar to the one
4593 ;; used in ‘hack-local-variables’.
4594 (when (and enable-local-variables (eobp))
4595 (search-backward "\n\f" (max (- (point) 3000) (point-min)) :move)
4596 (when (let ((case-fold-search t))
4597 (search-forward "Local Variables:" nil :move))
4598 (beginning-of-line 0)
4599 (when (eq (char-before) ?\n) (backward-char))))
4600 (unless (or (markdown-cur-line-blank-p)
4601 (thing-at-point-looking-at markdown-regex-reference-definition))
4602 (insert "\n"))
4603 (insert "\n[" label "]: ")
4604 (if url
4605 (insert url)
4606 ;; When no URL is given, leave point at END following the colon
4607 (setq end (point)))
4608 (when (> (length title) 0)
4609 (insert " \"" title "\""))
4610 (unless (looking-at-p "\n")
4611 (insert "\n"))
4612 (goto-char end)
4613 (when url
4614 (message
4615 (markdown--substitute-command-keys
4616 "Reference [%s] was defined, press \\[markdown-do] to jump there")
4617 label))))
4619 (define-obsolete-function-alias
4620 'markdown-insert-inline-link-dwim 'markdown-insert-link "v2.3")
4621 (define-obsolete-function-alias
4622 'markdown-insert-reference-link-dwim 'markdown-insert-link "v2.3")
4624 (defun markdown--insert-link-or-image (image)
4625 "Interactively insert new or update an existing link or image.
4626 When IMAGE is non-nil, insert an image. Otherwise, insert a link.
4627 This is an internal function called by
4628 `markdown-insert-link' and `markdown-insert-image'."
4629 (cl-multiple-value-bind (begin end text uri ref title)
4630 (if (markdown-use-region-p)
4631 ;; Use region as either link text or URL as appropriate.
4632 (let ((region (buffer-substring-no-properties
4633 (region-beginning) (region-end))))
4634 (if (string-match markdown-regex-uri region)
4635 ;; Region contains a URL; use it as such.
4636 (list (region-beginning) (region-end)
4637 nil (match-string 0 region) nil nil)
4638 ;; Region doesn't contain a URL, so use it as text.
4639 (list (region-beginning) (region-end)
4640 region nil nil nil)))
4641 ;; Extract and use properties of existing link, if any.
4642 (markdown-link-at-pos (point)))
4643 (let* ((ref (when ref (concat "[" ref "]")))
4644 (defined-refs (append
4645 (mapcar (lambda (ref) (concat "[" ref "]"))
4646 (markdown-get-defined-references))))
4647 (used-uris (markdown-get-used-uris))
4648 (uri-or-ref (completing-read
4649 "URL or [reference]: "
4650 (append defined-refs used-uris)
4651 nil nil (or uri ref)))
4652 (ref (cond ((string-match "\\`\\[\\(.*\\)\\]\\'" uri-or-ref)
4653 (match-string 1 uri-or-ref))
4654 ((string-equal "" uri-or-ref)
4655 "")))
4656 (uri (unless ref uri-or-ref))
4657 (text-prompt (if image
4658 "Alt text: "
4659 (if ref
4660 "Link text: "
4661 "Link text (blank for plain URL): ")))
4662 (text (read-string text-prompt text))
4663 (text (if (= (length text) 0) nil text))
4664 (plainp (and uri (not text)))
4665 (implicitp (string-equal ref ""))
4666 (ref (if implicitp text ref))
4667 (definedp (and ref (markdown-reference-definition ref)))
4668 (ref-url (unless (or uri definedp)
4669 (completing-read "Reference URL: " used-uris)))
4670 (title (unless (or plainp definedp)
4671 (read-string "Title (tooltip text, optional): " title)))
4672 (title (if (= (length title) 0) nil title)))
4673 (when (and image implicitp)
4674 (user-error "Reference required: implicit image references are invalid"))
4675 (when (and begin end)
4676 (delete-region begin end))
4677 (cond
4678 ((and (not image) uri text)
4679 (markdown-insert-inline-link text uri title))
4680 ((and image uri text)
4681 (markdown-insert-inline-image text uri title))
4682 ((and ref text)
4683 (if image
4684 (markdown-insert-reference-image text (unless implicitp ref) nil title)
4685 (markdown-insert-reference-link text (unless implicitp ref) nil title))
4686 (unless definedp
4687 (markdown-insert-reference-definition ref ref-url title)))
4688 ((and (not image) uri)
4689 (markdown-insert-uri uri))))))
4691 (defun markdown-insert-link ()
4692 "Insert new or update an existing link, with interactive prompts.
4693 If the point is at an existing link or URL, update the link text,
4694 URL, reference label, and/or title. Otherwise, insert a new link.
4695 The type of link inserted (inline, reference, or plain URL)
4696 depends on which values are provided:
4698 * If a URL and TEXT are given, insert an inline link: [TEXT](URL).
4699 * If [REF] and TEXT are given, insert a reference link: [TEXT][REF].
4700 * If only TEXT is given, insert an implicit reference link: [TEXT][].
4701 * If only a URL is given, insert a plain link: <URL>.
4703 In other words, to create an implicit reference link, leave the
4704 URL prompt empty and to create a plain URL link, leave the link
4705 text empty.
4707 If there is an active region, use the text as the default URL, if
4708 it seems to be a URL, or link text value otherwise.
4710 If a given reference is not defined, this function will
4711 additionally prompt for the URL and optional title. In this case,
4712 the reference definition is placed at the location determined by
4713 `markdown-reference-location'.
4715 Through updating the link, this function can be used to convert a
4716 link of one type (inline, reference, or plain) to another type by
4717 selectively adding or removing information via the prompts."
4718 (interactive)
4719 (markdown--insert-link-or-image nil))
4721 (defun markdown-insert-image ()
4722 "Insert new or update an existing image, with interactive prompts.
4723 If the point is at an existing image, update the alt text, URL,
4724 reference label, and/or title. Otherwise, insert a new image.
4725 The type of image inserted (inline or reference) depends on which
4726 values are provided:
4728 * If a URL and ALT-TEXT are given, insert an inline image:
4729 ![ALT-TEXT](URL).
4730 * If [REF] and ALT-TEXT are given, insert a reference image:
4731 ![ALT-TEXT][REF].
4733 If there is an active region, use the text as the default URL, if
4734 it seems to be a URL, or alt text value otherwise.
4736 If a given reference is not defined, this function will
4737 additionally prompt for the URL and optional title. In this case,
4738 the reference definition is placed at the location determined by
4739 `markdown-reference-location'.
4741 Through updating the image, this function can be used to convert an
4742 image of one type (inline or reference) to another type by
4743 selectively adding or removing information via the prompts."
4744 (interactive)
4745 (markdown--insert-link-or-image t))
4747 (defun markdown-insert-uri (&optional uri)
4748 "Insert markup for an inline URI.
4749 If there is an active region, use it as the URI. If the point is
4750 at a URI, wrap it with angle brackets. If the point is at an
4751 inline URI, remove the angle brackets. Otherwise, simply insert
4752 angle brackets place the point between them."
4753 (interactive)
4754 (if (markdown-use-region-p)
4755 ;; Active region
4756 (let ((bounds (markdown-unwrap-things-in-region
4757 (region-beginning) (region-end)
4758 markdown-regex-angle-uri 0 2)))
4759 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
4760 ;; Markup removal, URI at point, new URI, or empty markup insertion
4761 (if (thing-at-point-looking-at markdown-regex-angle-uri)
4762 (markdown-unwrap-thing-at-point nil 0 2)
4763 (if uri
4764 (insert "<" uri ">")
4765 (markdown-wrap-or-insert "<" ">" 'url nil nil)))))
4767 (defun markdown-insert-wiki-link ()
4768 "Insert a wiki link of the form [[WikiLink]].
4769 If there is an active region, use the region as the link text.
4770 If the point is at a word, use the word as the link text. If
4771 there is no active region and the point is not at word, simply
4772 insert link markup."
4773 (interactive)
4774 (if (markdown-use-region-p)
4775 ;; Active region
4776 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
4777 ;; Markup removal, wiki link at at point, or empty markup insertion
4778 (if (thing-at-point-looking-at markdown-regex-wiki-link)
4779 (if (or markdown-wiki-link-alias-first
4780 (null (match-string 5)))
4781 (markdown-unwrap-thing-at-point nil 1 3)
4782 (markdown-unwrap-thing-at-point nil 1 5))
4783 (markdown-wrap-or-insert "[[" "]]"))))
4785 (defun markdown-remove-header ()
4786 "Remove header markup if point is at a header.
4787 Return bounds of remaining header text if a header was removed
4788 and nil otherwise."
4789 (interactive "*")
4790 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
4791 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
4793 (defun markdown-insert-header (&optional level text setext)
4794 "Insert or replace header markup.
4795 The level of the header is specified by LEVEL and header text is
4796 given by TEXT. LEVEL must be an integer from 1 and 6, and the
4797 default value is 1.
4798 When TEXT is nil, the header text is obtained as follows.
4799 If there is an active region, it is used as the header text.
4800 Otherwise, the current line will be used as the header text.
4801 If there is not an active region and the point is at a header,
4802 remove the header markup and replace with level N header.
4803 Otherwise, insert empty header markup and place the point in
4804 between.
4805 The style of the header will be atx (hash marks) unless
4806 SETEXT is non-nil, in which case a setext-style (underlined)
4807 header will be inserted."
4808 (interactive "p\nsHeader text: ")
4809 (setq level (min (max (or level 1) 1) (if setext 2 6)))
4810 ;; Determine header text if not given
4811 (when (null text)
4812 (if (markdown-use-region-p)
4813 ;; Active region
4814 (setq text (delete-and-extract-region (region-beginning) (region-end)))
4815 ;; No active region
4816 (markdown-remove-header)
4817 (setq text (delete-and-extract-region
4818 (line-beginning-position) (line-end-position)))
4819 (when (and setext (string-match-p "^[ \t]*$" text))
4820 (setq text (read-string "Header text: "))))
4821 (setq text (markdown-compress-whitespace-string text)))
4822 ;; Insertion with given text
4823 (markdown-ensure-blank-line-before)
4824 (let (hdr)
4825 (cond (setext
4826 (setq hdr (make-string (string-width text) (if (= level 2) ?- ?=)))
4827 (insert text "\n" hdr))
4829 (setq hdr (make-string level ?#))
4830 (insert hdr " " text)
4831 (when (null markdown-asymmetric-header) (insert " " hdr)))))
4832 (markdown-ensure-blank-line-after)
4833 ;; Leave point at end of text
4834 (cond (setext
4835 (backward-char (1+ (string-width text))))
4836 ((null markdown-asymmetric-header)
4837 (backward-char (1+ level)))))
4839 (defun markdown-insert-header-dwim (&optional arg setext)
4840 "Insert or replace header markup.
4841 The level and type of the header are determined automatically by
4842 the type and level of the previous header, unless a prefix
4843 argument is given via ARG.
4844 With a numeric prefix valued 1 to 6, insert a header of the given
4845 level, with the type being determined automatically (note that
4846 only level 1 or 2 setext headers are possible).
4848 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
4849 promote the heading by one level.
4850 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
4851 demote the heading by one level.
4852 When SETEXT is non-nil, prefer setext-style headers when
4853 possible (levels one and two).
4855 When there is an active region, use it for the header text. When
4856 the point is at an existing header, change the type and level
4857 according to the rules above.
4858 Otherwise, if the line is not empty, create a header using the
4859 text on the current line as the header text.
4860 Finally, if the point is on a blank line, insert empty header
4861 markup (atx) or prompt for text (setext).
4862 See `markdown-insert-header' for more details about how the
4863 header text is determined."
4864 (interactive "*P")
4865 (let (level)
4866 (save-excursion
4867 (when (or (thing-at-point-looking-at markdown-regex-header)
4868 (re-search-backward markdown-regex-header nil t))
4869 ;; level of current or previous header
4870 (setq level (markdown-outline-level))
4871 ;; match group 1 indicates a setext header
4872 (setq setext (match-end 1))))
4873 ;; check prefix argument
4874 (cond
4875 ((and (equal arg '(4)) level (> level 1)) ;; C-u
4876 (cl-decf level))
4877 ((and (equal arg '(16)) level (< level 6)) ;; C-u C-u
4878 (cl-incf level))
4879 (arg ;; numeric prefix
4880 (setq level (prefix-numeric-value arg))))
4881 ;; setext headers must be level one or two
4882 (and level (setq setext (and setext (<= level 2))))
4883 ;; insert the heading
4884 (markdown-insert-header level nil setext)))
4886 (defun markdown-insert-header-setext-dwim (&optional arg)
4887 "Insert or replace header markup, with preference for setext.
4888 See `markdown-insert-header-dwim' for details, including how ARG is handled."
4889 (interactive "*P")
4890 (markdown-insert-header-dwim arg t))
4892 (defun markdown-insert-header-atx-1 ()
4893 "Insert a first level atx-style (hash mark) header.
4894 See `markdown-insert-header'."
4895 (interactive "*")
4896 (markdown-insert-header 1 nil nil))
4898 (defun markdown-insert-header-atx-2 ()
4899 "Insert a level two atx-style (hash mark) header.
4900 See `markdown-insert-header'."
4901 (interactive "*")
4902 (markdown-insert-header 2 nil nil))
4904 (defun markdown-insert-header-atx-3 ()
4905 "Insert a level three atx-style (hash mark) header.
4906 See `markdown-insert-header'."
4907 (interactive "*")
4908 (markdown-insert-header 3 nil nil))
4910 (defun markdown-insert-header-atx-4 ()
4911 "Insert a level four atx-style (hash mark) header.
4912 See `markdown-insert-header'."
4913 (interactive "*")
4914 (markdown-insert-header 4 nil nil))
4916 (defun markdown-insert-header-atx-5 ()
4917 "Insert a level five atx-style (hash mark) header.
4918 See `markdown-insert-header'."
4919 (interactive "*")
4920 (markdown-insert-header 5 nil nil))
4922 (defun markdown-insert-header-atx-6 ()
4923 "Insert a sixth level atx-style (hash mark) header.
4924 See `markdown-insert-header'."
4925 (interactive "*")
4926 (markdown-insert-header 6 nil nil))
4928 (defun markdown-insert-header-setext-1 ()
4929 "Insert a setext-style (underlined) first-level header.
4930 See `markdown-insert-header'."
4931 (interactive "*")
4932 (markdown-insert-header 1 nil t))
4934 (defun markdown-insert-header-setext-2 ()
4935 "Insert a setext-style (underlined) second-level header.
4936 See `markdown-insert-header'."
4937 (interactive "*")
4938 (markdown-insert-header 2 nil t))
4940 (defun markdown-blockquote-indentation (loc)
4941 "Return string containing necessary indentation for a blockquote at LOC.
4942 Also see `markdown-pre-indentation'."
4943 (save-excursion
4944 (goto-char loc)
4945 (let* ((list-level (length (markdown-calculate-list-levels)))
4946 (indent ""))
4947 (dotimes (_ list-level indent)
4948 (setq indent (concat indent " "))))))
4950 (defun markdown-insert-blockquote ()
4951 "Start a blockquote section (or blockquote the region).
4952 If Transient Mark mode is on and a region is active, it is used as
4953 the blockquote text."
4954 (interactive)
4955 (if (markdown-use-region-p)
4956 (markdown-blockquote-region (region-beginning) (region-end))
4957 (markdown-ensure-blank-line-before)
4958 (insert (markdown-blockquote-indentation (point)) "> ")
4959 (markdown-ensure-blank-line-after)))
4961 (defun markdown-block-region (beg end prefix)
4962 "Format the region using a block prefix.
4963 Arguments BEG and END specify the beginning and end of the
4964 region. The characters PREFIX will appear at the beginning
4965 of each line."
4966 (save-excursion
4967 (let* ((end-marker (make-marker))
4968 (beg-marker (make-marker))
4969 (prefix-without-trailing-whitespace
4970 (replace-regexp-in-string (rx (+ blank) eos) "" prefix)))
4971 ;; Ensure blank line after and remove extra whitespace
4972 (goto-char end)
4973 (skip-syntax-backward "-")
4974 (set-marker end-marker (point))
4975 (delete-horizontal-space)
4976 (markdown-ensure-blank-line-after)
4977 ;; Ensure blank line before and remove extra whitespace
4978 (goto-char beg)
4979 (skip-syntax-forward "-")
4980 (delete-horizontal-space)
4981 (markdown-ensure-blank-line-before)
4982 (set-marker beg-marker (point))
4983 ;; Insert PREFIX before each line
4984 (goto-char beg-marker)
4985 (while (and (< (line-beginning-position) end-marker)
4986 (not (eobp)))
4987 ;; Don’t insert trailing whitespace.
4988 (insert (if (eolp) prefix-without-trailing-whitespace prefix))
4989 (forward-line)))))
4991 (defun markdown-blockquote-region (beg end)
4992 "Blockquote the region.
4993 Arguments BEG and END specify the beginning and end of the region."
4994 (interactive "*r")
4995 (markdown-block-region
4996 beg end (concat (markdown-blockquote-indentation
4997 (max (point-min) (1- beg))) "> ")))
4999 (defun markdown-pre-indentation (loc)
5000 "Return string containing necessary whitespace for a pre block at LOC.
5001 Also see `markdown-blockquote-indentation'."
5002 (save-excursion
5003 (goto-char loc)
5004 (let* ((list-level (length (markdown-calculate-list-levels)))
5005 indent)
5006 (dotimes (_ (1+ list-level) indent)
5007 (setq indent (concat indent " "))))))
5009 (defun markdown-insert-pre ()
5010 "Start a preformatted section (or apply to the region).
5011 If Transient Mark mode is on and a region is active, it is marked
5012 as preformatted text."
5013 (interactive)
5014 (if (markdown-use-region-p)
5015 (markdown-pre-region (region-beginning) (region-end))
5016 (markdown-ensure-blank-line-before)
5017 (insert (markdown-pre-indentation (point)))
5018 (markdown-ensure-blank-line-after)))
5020 (defun markdown-pre-region (beg end)
5021 "Format the region as preformatted text.
5022 Arguments BEG and END specify the beginning and end of the region."
5023 (interactive "*r")
5024 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
5025 (markdown-block-region beg end indent)))
5027 (defun markdown-electric-backquote (arg)
5028 "Insert a backquote.
5029 The numeric prefix argument ARG says how many times to repeat the insertion.
5030 Call `markdown-insert-gfm-code-block' interactively
5031 if three backquotes inserted at the beginning of line."
5032 (interactive "*P")
5033 (self-insert-command (prefix-numeric-value arg))
5034 (when (and markdown-gfm-use-electric-backquote (looking-back "^```" nil))
5035 (replace-match "")
5036 (call-interactively #'markdown-insert-gfm-code-block)))
5038 (defconst markdown-gfm-recognized-languages
5039 ;; To reproduce/update, evaluate the let-form in
5040 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
5041 ;; but with appropriate use of a keyboard macro, indenting and filling it
5042 ;; properly is pretty fast.
5043 '("1C-Enterprise" "ABAP" "ABNF" "AGS-Script" "AMPL" "ANTLR"
5044 "API-Blueprint" "APL" "ASN.1" "ASP" "ATS" "ActionScript" "Ada" "Agda"
5045 "Alloy" "Alpine-Abuild" "Ant-Build-System" "ApacheConf" "Apex"
5046 "Apollo-Guidance-Computer" "AppleScript" "Arc" "Arduino" "AsciiDoc"
5047 "AspectJ" "Assembly" "Augeas" "AutoHotkey" "AutoIt" "Awk" "Batchfile"
5048 "Befunge" "Bison" "BitBake" "Blade" "BlitzBasic" "BlitzMax" "Bluespec"
5049 "Boo" "Brainfuck" "Brightscript" "Bro" "C#" "C++" "C-ObjDump"
5050 "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "COLLADA" "CSON" "CSS" "CSV"
5051 "CWeb" "Cap'n-Proto" "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK"
5052 "Cirru" "Clarion" "Clean" "Click" "Clojure" "Closure-Templates"
5053 "CoffeeScript" "ColdFusion" "ColdFusion-CFC" "Common-Lisp"
5054 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal"
5055 "Csound" "Csound-Document" "Csound-Score" "Cuda" "Cycript" "Cython"
5056 "D-ObjDump" "DIGITAL-Command-Language" "DM" "DNS-Zone" "DTrace"
5057 "Darcs-Patch" "Dart" "Diff" "Dockerfile" "Dogescript" "Dylan" "EBNF"
5058 "ECL" "ECLiPSe" "EJS" "EQ" "Eagle" "Ecere-Projects" "Eiffel" "Elixir"
5059 "Elm" "Emacs-Lisp" "EmberScript" "Erlang" "F#" "FLUX" "Factor" "Fancy"
5060 "Fantom" "Filebench-WML" "Filterscript" "Formatted" "Forth" "Fortran"
5061 "FreeMarker" "Frege" "G-code" "GAMS" "GAP" "GCC-Machine-Description"
5062 "GDB" "GDScript" "GLSL" "GN" "Game-Maker-Language" "Genie" "Genshi"
5063 "Gentoo-Ebuild" "Gentoo-Eclass" "Gettext-Catalog" "Gherkin" "Glyph"
5064 "Gnuplot" "Go" "Golo" "Gosu" "Grace" "Gradle" "Grammatical-Framework"
5065 "Graph-Modeling-Language" "GraphQL" "Graphviz-(DOT)" "Groovy"
5066 "Groovy-Server-Pages" "HCL" "HLSL" "HTML" "HTML+Django" "HTML+ECR"
5067 "HTML+EEX" "HTML+ERB" "HTML+PHP" "HTTP" "Hack" "Haml" "Handlebars"
5068 "Harbour" "Haskell" "Haxe" "Hy" "HyPhy" "IDL" "IGOR-Pro" "INI"
5069 "IRC-log" "Idris" "Inform-7" "Inno-Setup" "Io" "Ioke" "Isabelle"
5070 "Isabelle-ROOT" "JFlex" "JSON" "JSON5" "JSONLD" "JSONiq" "JSX"
5071 "Jasmin" "Java" "Java-Server-Pages" "JavaScript" "Jison" "Jison-Lex"
5072 "Jolie" "Julia" "Jupyter-Notebook" "KRL" "KiCad" "Kit" "Kotlin" "LFE"
5073 "LLVM" "LOLCODE" "LSL" "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex"
5074 "LilyPond" "Limbo" "Linker-Script" "Linux-Kernel-Module" "Liquid"
5075 "Literate-Agda" "Literate-CoffeeScript" "Literate-Haskell"
5076 "LiveScript" "Logos" "Logtalk" "LookML" "LoomScript" "Lua" "M4"
5077 "M4Sugar" "MAXScript" "MQL4" "MQL5" "MTML" "MUF" "Makefile" "Mako"
5078 "Markdown" "Marko" "Mask" "Mathematica" "Matlab" "Maven-POM" "Max"
5079 "MediaWiki" "Mercury" "Meson" "Metal" "MiniD" "Mirah" "Modelica"
5080 "Modula-2" "Module-Management-System" "Monkey" "Moocode" "MoonScript"
5081 "Myghty" "NCL" "NL" "NSIS" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo"
5082 "NewLisp" "Nginx" "Nim" "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml"
5083 "ObjDump" "Objective-C" "Objective-C++" "Objective-J" "Omgrofl" "Opa"
5084 "Opal" "OpenCL" "OpenEdge-ABL" "OpenRC-runscript" "OpenSCAD"
5085 "OpenType-Feature-File" "Org" "Ox" "Oxygene" "Oz" "P4" "PAWN" "PHP"
5086 "PLSQL" "PLpgSQL" "POV-Ray-SDL" "Pan" "Papyrus" "Parrot"
5087 "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal" "Pep8"
5088 "Perl" "Perl6" "Pic" "Pickle" "PicoLisp" "PigLatin" "Pike" "Pod"
5089 "PogoScript" "Pony" "PostScript" "PowerBuilder" "PowerShell"
5090 "Processing" "Prolog" "Propeller-Spin" "Protocol-Buffer" "Public-Key"
5091 "Pug" "Puppet" "Pure-Data" "PureBasic" "PureScript" "Python"
5092 "Python-console" "Python-traceback" "QML" "QMake" "RAML" "RDoc"
5093 "REALbasic" "REXX" "RHTML" "RMarkdown" "RPM-Spec" "RUNOFF" "Racket"
5094 "Ragel" "Rascal" "Raw-token-data" "Reason" "Rebol" "Red" "Redcode"
5095 "Regular-Expression" "Ren'Py" "RenderScript" "RobotFramework" "Roff"
5096 "Rouge" "Ruby" "Rust" "SAS" "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL"
5097 "SRecode-Template" "STON" "SVG" "Sage" "SaltStack" "Sass" "Scala"
5098 "Scaml" "Scheme" "Scilab" "Self" "ShaderLab" "Shell" "ShellSession"
5099 "Shen" "Slash" "Slim" "Smali" "Smalltalk" "Smarty" "SourcePawn"
5100 "Spline-Font-Database" "Squirrel" "Stan" "Standard-ML" "Stata"
5101 "Stylus" "SubRip-Text" "Sublime-Text-Config" "SuperCollider" "Swift"
5102 "SystemVerilog" "TI-Program" "TLA" "TOML" "TXL" "Tcl" "Tcsh" "TeX"
5103 "Tea" "Terra" "Text" "Textile" "Thrift" "Turing" "Turtle" "Twig"
5104 "Type-Language" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset"
5105 "Unix-Assembly" "Uno" "UnrealScript" "UrWeb" "VCL" "VHDL" "Vala"
5106 "Verilog" "Vim-script" "Visual-Basic" "Volt" "Vue"
5107 "Wavefront-Material" "Wavefront-Object" "Web-Ontology-Language"
5108 "WebAssembly" "WebIDL" "World-of-Warcraft-Addon-Data" "X10" "XC"
5109 "XCompose" "XML" "XPages" "XProc" "XQuery" "XS" "XSLT" "Xojo" "Xtend"
5110 "YAML" "YANG" "Yacc" "Zephir" "Zimpl" "desktop" "eC" "edn" "fish"
5111 "mupad" "nesC" "ooc" "reStructuredText" "wisp" "xBase")
5112 "Language specifiers recognized by GitHub's syntax highlighting features.")
5114 (defvar markdown-gfm-used-languages nil
5115 "Language names used in GFM code blocks.")
5116 (make-variable-buffer-local 'markdown-gfm-used-languages)
5118 (defun markdown-trim-whitespace (str)
5119 (markdown-replace-regexp-in-string
5120 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str))
5122 (defun markdown-clean-language-string (str)
5123 (markdown-replace-regexp-in-string
5124 "{\\.?\\|}" "" (markdown-trim-whitespace str)))
5126 (defun markdown-validate-language-string (widget)
5127 (let ((str (widget-value widget)))
5128 (unless (string= str (markdown-clean-language-string str))
5129 (widget-put widget :error (format "Invalid language spec: '%s'" str))
5130 widget)))
5132 (defun markdown-gfm-get-corpus ()
5133 "Create corpus of recognized GFM code block languages for the given buffer."
5134 (let ((given-corpus (append markdown-gfm-additional-languages
5135 markdown-gfm-recognized-languages)))
5136 (append
5137 markdown-gfm-used-languages
5138 (if markdown-gfm-downcase-languages (cl-mapcar #'downcase given-corpus)
5139 given-corpus))))
5141 (defun markdown-gfm-add-used-language (lang)
5142 "Clean LANG and add to list of used languages."
5143 (setq markdown-gfm-used-languages
5144 (cons lang (remove lang markdown-gfm-used-languages))))
5146 (defcustom markdown-spaces-after-code-fence 1
5147 "Number of space characters to insert after a code fence.
5148 \\<gfm-mode-map>\\[markdown-insert-gfm-code-block] inserts this many spaces between an
5149 opening code fence and an info string."
5150 :group 'markdown
5151 :type 'integer
5152 :safe #'natnump
5153 :package-version '(markdown-mode . "2.3"))
5155 (defun markdown-insert-gfm-code-block (&optional lang edit)
5156 "Insert GFM code block for language LANG.
5157 If LANG is nil, the language will be queried from user. If a
5158 region is active, wrap this region with the markup instead. If
5159 the region boundaries are not on empty lines, these are added
5160 automatically in order to have the correct markup. When EDIT is
5161 non-nil (e.g., when \\[universal-argument] is given), edit the
5162 code block in an indirect buffer after insertion."
5163 (interactive
5164 (list (let ((completion-ignore-case nil))
5165 (condition-case nil
5166 (markdown-clean-language-string
5167 (completing-read
5168 "Programming language: "
5169 (markdown-gfm-get-corpus)
5170 nil 'confirm (car markdown-gfm-used-languages)
5171 'markdown-gfm-language-history))
5172 (quit "")))
5173 current-prefix-arg))
5174 (unless (string= lang "") (markdown-gfm-add-used-language lang))
5175 (when (> (length lang) 0)
5176 (setq lang (concat (make-string markdown-spaces-after-code-fence ?\s)
5177 lang)))
5178 (if (markdown-use-region-p)
5179 (let* ((b (region-beginning)) (e (region-end)) end
5180 (indent (progn (goto-char b) (current-indentation))))
5181 (goto-char e)
5182 ;; if we're on a blank line, don't newline, otherwise the ```
5183 ;; should go on its own line
5184 (unless (looking-back "\n" nil)
5185 (newline))
5186 (indent-to indent)
5187 (insert "```")
5188 (markdown-ensure-blank-line-after)
5189 (setq end (point))
5190 (goto-char b)
5191 ;; if we're on a blank line, insert the quotes here, otherwise
5192 ;; add a new line first
5193 (unless (looking-at-p "\n")
5194 (newline)
5195 (forward-line -1))
5196 (markdown-ensure-blank-line-before)
5197 (indent-to indent)
5198 (insert "```" lang)
5199 (markdown-syntax-propertize-fenced-block-constructs (point-at-bol) end))
5200 (let ((indent (current-indentation)) start)
5201 (delete-horizontal-space :backward-only)
5202 (markdown-ensure-blank-line-before)
5203 (indent-to indent)
5204 (setq start (point))
5205 (insert "```" lang "\n")
5206 (indent-to indent)
5207 (unless edit (insert ?\n))
5208 (indent-to indent)
5209 (insert "```")
5210 (markdown-ensure-blank-line-after)
5211 (markdown-syntax-propertize-fenced-block-constructs start (point)))
5212 (end-of-line 0)
5213 (when edit (markdown-edit-code-block))))
5215 (defun markdown-code-block-lang (&optional pos-prop)
5216 "Return the language name for a GFM or tilde fenced code block.
5217 The beginning of the block may be described by POS-PROP,
5218 a cons of (pos . prop) giving the position and property
5219 at the beginning of the block."
5220 (or pos-prop
5221 (setq pos-prop
5222 (markdown-max-of-seq
5223 #'car
5224 (cl-remove-if
5225 #'null
5226 (cl-mapcar
5227 #'markdown-find-previous-prop
5228 (markdown-get-fenced-block-begin-properties))))))
5229 (when pos-prop
5230 (goto-char (car pos-prop))
5231 (set-match-data (get-text-property (point) (cdr pos-prop)))
5232 ;; Note: Hard-coded group number assumes tilde
5233 ;; and GFM fenced code regexp groups agree.
5234 (let ((begin (match-beginning 3))
5235 (end (match-end 3)))
5236 (when (and begin end)
5237 ;; Fix language strings beginning with periods, like ".ruby".
5238 (when (eq (char-after begin) ?.)
5239 (setq begin (1+ begin)))
5240 (buffer-substring-no-properties begin end)))))
5242 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer)
5243 (with-current-buffer (or buffer (current-buffer))
5244 (save-excursion
5245 (goto-char (point-min))
5246 (cl-loop
5247 with prop = 'markdown-gfm-block-begin
5248 for pos-prop = (markdown-find-next-prop prop)
5249 while pos-prop
5250 for lang = (markdown-code-block-lang pos-prop)
5251 do (progn (when lang (markdown-gfm-add-used-language lang))
5252 (goto-char (next-single-property-change (point) prop)))))))
5255 ;;; Footnotes ==================================================================
5257 (defun markdown-footnote-counter-inc ()
5258 "Increment `markdown-footnote-counter' and return the new value."
5259 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
5260 (save-excursion
5261 (goto-char (point-min))
5262 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
5263 (point-max) t)
5264 (let ((fn (string-to-number (match-string 1))))
5265 (when (> fn markdown-footnote-counter)
5266 (setq markdown-footnote-counter fn))))))
5267 (cl-incf markdown-footnote-counter))
5269 (defun markdown-insert-footnote ()
5270 "Insert footnote with a new number and move point to footnote definition."
5271 (interactive)
5272 (let ((fn (markdown-footnote-counter-inc)))
5273 (insert (format "[^%d]" fn))
5274 (markdown-footnote-text-find-new-location)
5275 (markdown-ensure-blank-line-before)
5276 (unless (markdown-cur-line-blank-p)
5277 (insert "\n"))
5278 (insert (format "[^%d]: " fn))
5279 (markdown-ensure-blank-line-after)))
5281 (defun markdown-footnote-text-find-new-location ()
5282 "Position the point at the proper location for a new footnote text."
5283 (cond
5284 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
5285 ((eq markdown-footnote-location 'immediately) (markdown-end-of-text-block))
5286 ((eq markdown-footnote-location 'subtree) (markdown-end-of-subtree))
5287 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
5289 (defun markdown-footnote-kill ()
5290 "Kill the footnote at point.
5291 The footnote text is killed (and added to the kill ring), the
5292 footnote marker is deleted. Point has to be either at the
5293 footnote marker or in the footnote text."
5294 (interactive)
5295 (let ((marker-pos nil)
5296 (skip-deleting-marker nil)
5297 (starting-footnote-text-positions
5298 (markdown-footnote-text-positions)))
5299 (when starting-footnote-text-positions
5300 ;; We're starting in footnote text, so mark our return position and jump
5301 ;; to the marker if possible.
5302 (let ((marker-pos (markdown-footnote-find-marker
5303 (cl-first starting-footnote-text-positions))))
5304 (if marker-pos
5305 (goto-char (1- marker-pos))
5306 ;; If there isn't a marker, we still want to kill the text.
5307 (setq skip-deleting-marker t))))
5308 ;; Either we didn't start in the text, or we started in the text and jumped
5309 ;; to the marker. We want to assume we're at the marker now and error if
5310 ;; we're not.
5311 (unless skip-deleting-marker
5312 (let ((marker (markdown-footnote-delete-marker)))
5313 (unless marker
5314 (error "Not at a footnote"))
5315 ;; Even if we knew the text position before, it changed when we deleted
5316 ;; the label.
5317 (setq marker-pos (cl-second marker))
5318 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker))))
5319 (unless new-text-pos
5320 (error "No text for footnote `%s'" (cl-first marker)))
5321 (goto-char new-text-pos))))
5322 (let ((pos (markdown-footnote-kill-text)))
5323 (goto-char (if starting-footnote-text-positions
5325 marker-pos)))))
5327 (defun markdown-footnote-delete-marker ()
5328 "Delete a footnote marker at point.
5329 Returns a list (ID START) containing the footnote ID and the
5330 start position of the marker before deletion. If no footnote
5331 marker was deleted, this function returns NIL."
5332 (let ((marker (markdown-footnote-marker-positions)))
5333 (when marker
5334 (delete-region (cl-second marker) (cl-third marker))
5335 (butlast marker))))
5337 (defun markdown-footnote-kill-text ()
5338 "Kill footnote text at point.
5339 Returns the start position of the footnote text before deletion,
5340 or NIL if point was not inside a footnote text.
5342 The killed text is placed in the kill ring (without the footnote
5343 number)."
5344 (let ((fn (markdown-footnote-text-positions)))
5345 (when fn
5346 (let ((text (delete-and-extract-region (cl-second fn) (cl-third fn))))
5347 (string-match (concat "\\[\\" (cl-first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
5348 (kill-new (match-string 1 text))
5349 (when (and (markdown-cur-line-blank-p)
5350 (markdown-prev-line-blank-p)
5351 (not (bobp)))
5352 (delete-region (1- (point)) (point)))
5353 (cl-second fn)))))
5355 (defun markdown-footnote-goto-text ()
5356 "Jump to the text of the footnote at point."
5357 (interactive)
5358 (let ((fn (car (markdown-footnote-marker-positions))))
5359 (unless fn
5360 (user-error "Not at a footnote marker"))
5361 (let ((new-pos (markdown-footnote-find-text fn)))
5362 (unless new-pos
5363 (error "No definition found for footnote `%s'" fn))
5364 (goto-char new-pos))))
5366 (defun markdown-footnote-return ()
5367 "Return from a footnote to its footnote number in the main text."
5368 (interactive)
5369 (let ((fn (save-excursion
5370 (car (markdown-footnote-text-positions)))))
5371 (unless fn
5372 (user-error "Not in a footnote"))
5373 (let ((new-pos (markdown-footnote-find-marker fn)))
5374 (unless new-pos
5375 (error "Footnote marker `%s' not found" fn))
5376 (goto-char new-pos))))
5378 (defun markdown-footnote-find-marker (id)
5379 "Find the location of the footnote marker with ID.
5380 The actual buffer position returned is the position directly
5381 following the marker's closing bracket. If no marker is found,
5382 NIL is returned."
5383 (save-excursion
5384 (goto-char (point-min))
5385 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
5386 (skip-chars-backward "^]")
5387 (point))))
5389 (defun markdown-footnote-find-text (id)
5390 "Find the location of the text of footnote ID.
5391 The actual buffer position returned is the position of the first
5392 character of the text, after the footnote's identifier. If no
5393 footnote text is found, NIL is returned."
5394 (save-excursion
5395 (goto-char (point-min))
5396 (when (re-search-forward (concat "^ \\{0,3\\}\\[" id "\\]:") nil t)
5397 (skip-chars-forward "[ \t]")
5398 (point))))
5400 (defun markdown-footnote-marker-positions ()
5401 "Return the position and ID of the footnote marker point is on.
5402 The return value is a list (ID START END). If point is not on a
5403 footnote, NIL is returned."
5404 ;; first make sure we're at a footnote marker
5405 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
5406 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
5407 (save-excursion
5408 ;; move point between [ and ^:
5409 (if (looking-at-p "\\[")
5410 (forward-char 1)
5411 (skip-chars-backward "^["))
5412 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
5413 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
5415 (defun markdown-footnote-text-positions ()
5416 "Return the start and end positions of the footnote text point is in.
5417 The exact return value is a list of three elements: (ID START END).
5418 The start position is the position of the opening bracket
5419 of the footnote id. The end position is directly after the
5420 newline that ends the footnote. If point is not in a footnote,
5421 NIL is returned instead."
5422 (save-excursion
5423 (let (result)
5424 (move-beginning-of-line 1)
5425 ;; Try to find the label. If we haven't found the label and we're at a blank
5426 ;; or indented line, back up if possible.
5427 (while (and
5428 (not (and (looking-at markdown-regex-footnote-definition)
5429 (setq result (list (match-string 1) (point)))))
5430 (and (not (bobp))
5431 (or (markdown-cur-line-blank-p)
5432 (>= (current-indentation) 4))))
5433 (forward-line -1))
5434 (when result
5435 ;; Advance if there is a next line that is either blank or indented.
5436 ;; (Need to check if we're on the last line, because
5437 ;; markdown-next-line-blank-p returns true for last line in buffer.)
5438 (while (and (/= (line-end-position) (point-max))
5439 (or (markdown-next-line-blank-p)
5440 (>= (markdown-next-line-indent) 4)))
5441 (forward-line))
5442 ;; Move back while the current line is blank.
5443 (while (markdown-cur-line-blank-p)
5444 (forward-line -1))
5445 ;; Advance to capture this line and a single trailing newline (if there
5446 ;; is one).
5447 (forward-line)
5448 (append result (list (point)))))))
5451 ;;; Element Removal ===========================================================
5453 (defun markdown-kill-thing-at-point ()
5454 "Kill thing at point and add important text, without markup, to kill ring.
5455 Possible things to kill include (roughly in order of precedence):
5456 inline code, headers, horizonal rules, links (add link text to
5457 kill ring), images (add alt text to kill ring), angle uri, email
5458 addresses, bold, italics, reference definition (add URI to kill
5459 ring), footnote markers and text (kill both marker and text, add
5460 text to kill ring), and list items."
5461 (interactive "*")
5462 (let (val)
5463 (cond
5464 ;; Inline code
5465 ((markdown-inline-code-at-point)
5466 (kill-new (match-string 2))
5467 (delete-region (match-beginning 0) (match-end 0)))
5468 ;; ATX header
5469 ((thing-at-point-looking-at markdown-regex-header-atx)
5470 (kill-new (match-string 2))
5471 (delete-region (match-beginning 0) (match-end 0)))
5472 ;; Setext header
5473 ((thing-at-point-looking-at markdown-regex-header-setext)
5474 (kill-new (match-string 1))
5475 (delete-region (match-beginning 0) (match-end 0)))
5476 ;; Horizonal rule
5477 ((thing-at-point-looking-at markdown-regex-hr)
5478 (kill-new (match-string 0))
5479 (delete-region (match-beginning 0) (match-end 0)))
5480 ;; Inline link or image (add link or alt text to kill ring)
5481 ((thing-at-point-looking-at markdown-regex-link-inline)
5482 (kill-new (match-string 3))
5483 (delete-region (match-beginning 0) (match-end 0)))
5484 ;; Reference link or image (add link or alt text to kill ring)
5485 ((thing-at-point-looking-at markdown-regex-link-reference)
5486 (kill-new (match-string 3))
5487 (delete-region (match-beginning 0) (match-end 0)))
5488 ;; Angle URI (add URL to kill ring)
5489 ((thing-at-point-looking-at markdown-regex-angle-uri)
5490 (kill-new (match-string 2))
5491 (delete-region (match-beginning 0) (match-end 0)))
5492 ;; Email address in angle brackets (add email address to kill ring)
5493 ((thing-at-point-looking-at markdown-regex-email)
5494 (kill-new (match-string 1))
5495 (delete-region (match-beginning 0) (match-end 0)))
5496 ;; Wiki link (add alias text to kill ring)
5497 ((and markdown-enable-wiki-links
5498 (thing-at-point-looking-at markdown-regex-wiki-link))
5499 (kill-new (markdown-wiki-link-alias))
5500 (delete-region (match-beginning 1) (match-end 1)))
5501 ;; Bold
5502 ((thing-at-point-looking-at markdown-regex-bold)
5503 (kill-new (match-string 4))
5504 (delete-region (match-beginning 2) (match-end 2)))
5505 ;; Italics
5506 ((thing-at-point-looking-at markdown-regex-italic)
5507 (kill-new (match-string 3))
5508 (delete-region (match-beginning 1) (match-end 1)))
5509 ;; Strikethrough
5510 ((thing-at-point-looking-at markdown-regex-strike-through)
5511 (kill-new (match-string 4))
5512 (delete-region (match-beginning 2) (match-end 2)))
5513 ;; Footnote marker (add footnote text to kill ring)
5514 ((thing-at-point-looking-at markdown-regex-footnote)
5515 (markdown-footnote-kill))
5516 ;; Footnote text (add footnote text to kill ring)
5517 ((setq val (markdown-footnote-text-positions))
5518 (markdown-footnote-kill))
5519 ;; Reference definition (add URL to kill ring)
5520 ((thing-at-point-looking-at markdown-regex-reference-definition)
5521 (kill-new (match-string 5))
5522 (delete-region (match-beginning 0) (match-end 0)))
5523 ;; List item
5524 ((setq val (markdown-cur-list-item-bounds))
5525 (kill-new (delete-and-extract-region (cl-first val) (cl-second val))))
5527 (user-error "Nothing found at point to kill")))))
5530 ;;; Indentation ====================================================================
5532 (defun markdown-indent-find-next-position (cur-pos positions)
5533 "Return the position after the index of CUR-POS in POSITIONS.
5534 Positions are calculated by `markdown-calc-indents'."
5535 (while (and positions
5536 (not (equal cur-pos (car positions))))
5537 (setq positions (cdr positions)))
5538 (or (cadr positions) 0))
5540 (define-obsolete-function-alias 'markdown-exdent-find-next-position
5541 'markdown-outdent-find-next-position "v2.3")
5543 (defun markdown-outdent-find-next-position (cur-pos positions)
5544 "Return the maximal element that precedes CUR-POS from POSITIONS.
5545 Positions are calculated by `markdown-calc-indents'."
5546 (let ((result 0))
5547 (dolist (i positions)
5548 (when (< i cur-pos)
5549 (setq result (max result i))))
5550 result))
5552 (defun markdown-indent-line ()
5553 "Indent the current line using some heuristics.
5554 If the _previous_ command was either `markdown-enter-key' or
5555 `markdown-cycle', then we should cycle to the next
5556 reasonable indentation position. Otherwise, we could have been
5557 called directly by `markdown-enter-key', by an initial call of
5558 `markdown-cycle', or indirectly by `auto-fill-mode'. In
5559 these cases, indent to the default position.
5560 Positions are calculated by `markdown-calc-indents'."
5561 (interactive)
5562 (let ((positions (markdown-calc-indents))
5563 (point-pos (current-column))
5564 (_ (back-to-indentation))
5565 (cur-pos (current-column)))
5566 (if (not (equal this-command 'markdown-cycle))
5567 (indent-line-to (car positions))
5568 (setq positions (sort (delete-dups positions) '<))
5569 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions))
5570 (new-point-pos (max (+ point-pos (- next-pos cur-pos)) 0)))
5571 (indent-line-to next-pos)
5572 (move-to-column new-point-pos)))))
5574 (defun markdown-calc-indents ()
5575 "Return a list of indentation columns to cycle through.
5576 The first element in the returned list should be considered the
5577 default indentation level. This function does not worry about
5578 duplicate positions, which are handled up by calling functions."
5579 (let (pos prev-line-pos positions)
5581 ;; Indentation of previous line
5582 (setq prev-line-pos (markdown-prev-line-indent))
5583 (setq positions (cons prev-line-pos positions))
5585 ;; Indentation of previous non-list-marker text
5586 (when (setq pos (markdown-prev-non-list-indent))
5587 (setq positions (cons pos positions)))
5589 ;; Indentation required for a pre block in current context
5590 (setq pos (length (markdown-pre-indentation (point))))
5591 (setq positions (cons pos positions))
5593 ;; Indentation of the previous line + tab-width
5594 (if prev-line-pos
5595 (setq positions (cons (+ prev-line-pos tab-width) positions))
5596 (setq positions (cons tab-width positions)))
5598 ;; Indentation of the previous line - tab-width
5599 (if (and prev-line-pos (> prev-line-pos tab-width))
5600 (setq positions (cons (- prev-line-pos tab-width) positions)))
5602 ;; Indentation of all preceeding list markers (when in a list)
5603 (when (setq pos (markdown-calculate-list-levels))
5604 (setq positions (append pos positions)))
5606 ;; First column
5607 (setq positions (cons 0 positions))
5609 ;; Return reversed list
5610 (reverse positions)))
5612 (defun markdown-enter-key ()
5613 "Handle RET depending on the context.
5614 If the point is at a table, move to the next row. Otherwise,
5615 indent according to value of `markdown-indent-on-enter'.
5616 When it is nil, simply call `newline'. Otherwise, indent the next line
5617 following RET using `markdown-indent-line'. Furthermore, when it
5618 is set to 'indent-and-new-item and the point is in a list item,
5619 start a new item with the same indentation. If the point is in an
5620 empty list item, remove it (so that pressing RET twice when in a
5621 list simply adds a blank line)."
5622 (interactive)
5623 (cond
5624 ;; Table
5625 ((markdown-table-at-point-p)
5626 (call-interactively #'markdown-table-next-row))
5627 ;; Indent non-table text
5628 (markdown-indent-on-enter
5629 (let (bounds)
5630 (if (and (memq markdown-indent-on-enter '(indent-and-new-item))
5631 (setq bounds (markdown-cur-list-item-bounds)))
5632 (let ((beg (cl-first bounds))
5633 (end (cl-second bounds))
5634 (length (cl-fourth bounds)))
5635 ;; Point is in a list item
5636 (if (= (- end beg) length)
5637 ;; Delete blank list
5638 (progn
5639 (delete-region beg end)
5640 (newline)
5641 (markdown-indent-line))
5642 (call-interactively #'markdown-insert-list-item)))
5643 ;; Point is not in a list
5644 (newline)
5645 (markdown-indent-line))))
5646 ;; Insert a raw newline
5647 (t (newline))))
5649 (define-obsolete-function-alias 'markdown-exdent-or-delete
5650 'markdown-outdent-or-delete "v2.3")
5652 (defun markdown-outdent-or-delete (arg)
5653 "Handle BACKSPACE by cycling through indentation points.
5654 When BACKSPACE is pressed, if there is only whitespace
5655 before the current point, then outdent the line one level.
5656 Otherwise, do normal delete by repeating
5657 `backward-delete-char-untabify' ARG times."
5658 (interactive "*p")
5659 (if (use-region-p)
5660 (backward-delete-char-untabify arg)
5661 (let ((cur-pos (current-column))
5662 (start-of-indention (save-excursion
5663 (back-to-indentation)
5664 (current-column)))
5665 (positions (markdown-calc-indents)))
5666 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
5667 (indent-line-to (markdown-outdent-find-next-position cur-pos positions))
5668 (backward-delete-char-untabify arg)))))
5670 (defun markdown-find-leftmost-column (beg end)
5671 "Find the leftmost column in the region from BEG to END."
5672 (let ((mincol 1000))
5673 (save-excursion
5674 (goto-char beg)
5675 (while (< (point) end)
5676 (back-to-indentation)
5677 (unless (looking-at-p "[ \t]*$")
5678 (setq mincol (min mincol (current-column))))
5679 (forward-line 1)
5681 mincol))
5683 (defun markdown-indent-region (beg end arg)
5684 "Indent the region from BEG to END using some heuristics.
5685 When ARG is non-nil, outdent the region instead.
5686 See `markdown-indent-line' and `markdown-indent-line'."
5687 (interactive "*r\nP")
5688 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
5689 (leftmostcol (markdown-find-leftmost-column beg end))
5690 (next-pos (if arg
5691 (markdown-outdent-find-next-position leftmostcol positions)
5692 (markdown-indent-find-next-position leftmostcol positions))))
5693 (indent-rigidly beg end (- next-pos leftmostcol))
5694 (setq deactivate-mark nil)))
5696 (define-obsolete-function-alias 'markdown-exdent-region
5697 'markdown-outdent-region "v2.3")
5699 (defun markdown-outdent-region (beg end)
5700 "Call `markdown-indent-region' on region from BEG to END with prefix."
5701 (interactive "*r")
5702 (markdown-indent-region beg end t))
5705 ;;; Markup Completion =========================================================
5707 (defconst markdown-complete-alist
5708 '((markdown-regex-header-atx . markdown-complete-atx)
5709 (markdown-regex-header-setext . markdown-complete-setext)
5710 (markdown-regex-hr . markdown-complete-hr))
5711 "Association list of form (regexp . function) for markup completion.")
5713 (defun markdown-incomplete-atx-p ()
5714 "Return t if ATX header markup is incomplete and nil otherwise.
5715 Assumes match data is available for `markdown-regex-header-atx'.
5716 Checks that the number of trailing hash marks equals the number of leading
5717 hash marks, that there is only a single space before and after the text,
5718 and that there is no extraneous whitespace in the text."
5720 ;; Number of starting and ending hash marks differs
5721 (not (= (length (match-string 1)) (length (match-string 3))))
5722 ;; When the header text is not empty...
5723 (and (> (length (match-string 2)) 0)
5724 ;; ...if there are extra leading, trailing, or interior spaces
5725 (or (not (= (match-beginning 2) (1+ (match-end 1))))
5726 (not (= (match-beginning 3) (1+ (match-end 2))))
5727 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
5728 ;; When the header text is empty...
5729 (and (= (length (match-string 2)) 0)
5730 ;; ...if there are too many or too few spaces
5731 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
5733 (defun markdown-complete-atx ()
5734 "Complete and normalize ATX headers.
5735 Add or remove hash marks to the end of the header to match the
5736 beginning. Ensure that there is only a single space between hash
5737 marks and header text. Removes extraneous whitespace from header text.
5738 Assumes match data is available for `markdown-regex-header-atx'.
5739 Return nil if markup was complete and non-nil if markup was completed."
5740 (when (markdown-incomplete-atx-p)
5741 (let* ((new-marker (make-marker))
5742 (new-marker (set-marker new-marker (match-end 2))))
5743 ;; Hash marks and spacing at end
5744 (goto-char (match-end 2))
5745 (delete-region (match-end 2) (match-end 3))
5746 (insert " " (match-string 1))
5747 ;; Remove extraneous whitespace from title
5748 (replace-match (markdown-compress-whitespace-string (match-string 2))
5749 t t nil 2)
5750 ;; Spacing at beginning
5751 (goto-char (match-end 1))
5752 (delete-region (match-end 1) (match-beginning 2))
5753 (insert " ")
5754 ;; Leave point at end of text
5755 (goto-char new-marker))))
5757 (defun markdown-incomplete-setext-p ()
5758 "Return t if setext header markup is incomplete and nil otherwise.
5759 Assumes match data is available for `markdown-regex-header-setext'.
5760 Checks that length of underline matches text and that there is no
5761 extraneous whitespace in the text."
5762 (or (not (= (length (match-string 1)) (length (match-string 2))))
5763 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
5765 (defun markdown-complete-setext ()
5766 "Complete and normalize setext headers.
5767 Add or remove underline characters to match length of header
5768 text. Removes extraneous whitespace from header text. Assumes
5769 match data is available for `markdown-regex-header-setext'.
5770 Return nil if markup was complete and non-nil if markup was completed."
5771 (when (markdown-incomplete-setext-p)
5772 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
5773 (char (char-after (match-beginning 2)))
5774 (level (if (char-equal char ?-) 2 1)))
5775 (goto-char (match-beginning 0))
5776 (delete-region (match-beginning 0) (match-end 0))
5777 (markdown-insert-header level text t)
5778 t)))
5780 (defun markdown-incomplete-hr-p ()
5781 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
5782 Assumes match data is available for `markdown-regex-hr'."
5783 (not (member (match-string 0) markdown-hr-strings)))
5785 (defun markdown-complete-hr ()
5786 "Complete horizontal rules.
5787 If horizontal rule string is a member of `markdown-hr-strings',
5788 do nothing. Otherwise, replace with the car of
5789 `markdown-hr-strings'.
5790 Assumes match data is available for `markdown-regex-hr'.
5791 Return nil if markup was complete and non-nil if markup was completed."
5792 (when (markdown-incomplete-hr-p)
5793 (replace-match (car markdown-hr-strings))
5796 (defun markdown-complete ()
5797 "Complete markup of object near point or in region when active.
5798 Handle all objects in `markdown-complete-alist', in order.
5799 See `markdown-complete-at-point' and `markdown-complete-region'."
5800 (interactive "*")
5801 (if (markdown-use-region-p)
5802 (markdown-complete-region (region-beginning) (region-end))
5803 (markdown-complete-at-point)))
5805 (defun markdown-complete-at-point ()
5806 "Complete markup of object near point.
5807 Handle all elements of `markdown-complete-alist' in order."
5808 (interactive "*")
5809 (let ((list markdown-complete-alist) found changed)
5810 (while list
5811 (let ((regexp (eval (caar list)))
5812 (function (cdar list)))
5813 (setq list (cdr list))
5814 (when (thing-at-point-looking-at regexp)
5815 (setq found t)
5816 (setq changed (funcall function))
5817 (setq list nil))))
5818 (if found
5819 (or changed (user-error "Markup at point is complete"))
5820 (user-error "Nothing to complete at point"))))
5822 (defun markdown-complete-region (beg end)
5823 "Complete markup of objects in region from BEG to END.
5824 Handle all objects in `markdown-complete-alist', in order. Each
5825 match is checked to ensure that a previous regexp does not also
5826 match."
5827 (interactive "*r")
5828 (let ((end-marker (set-marker (make-marker) end))
5829 previous)
5830 (dolist (element markdown-complete-alist)
5831 (let ((regexp (eval (car element)))
5832 (function (cdr element)))
5833 (goto-char beg)
5834 (while (re-search-forward regexp end-marker 'limit)
5835 (when (match-string 0)
5836 ;; Make sure this is not a match for any of the preceding regexps.
5837 ;; This prevents mistaking an HR for a Setext subheading.
5838 (let (match)
5839 (save-match-data
5840 (dolist (prev-regexp previous)
5841 (or match (setq match (looking-back prev-regexp nil)))))
5842 (unless match
5843 (save-excursion (funcall function))))))
5844 (cl-pushnew regexp previous :test #'equal)))
5845 previous))
5847 (defun markdown-complete-buffer ()
5848 "Complete markup for all objects in the current buffer."
5849 (interactive "*")
5850 (markdown-complete-region (point-min) (point-max)))
5853 ;;; Markup Cycling ============================================================
5855 (defun markdown-cycle-atx (arg &optional remove)
5856 "Cycle ATX header markup.
5857 Promote header (decrease level) when ARG is 1 and demote
5858 header (increase level) if arg is -1. When REMOVE is non-nil,
5859 remove the header when the level reaches zero and stop cycling
5860 when it reaches six. Otherwise, perform a proper cycling through
5861 levels one through six. Assumes match data is available for
5862 `markdown-regex-header-atx'."
5863 (let* ((old-level (length (match-string 1)))
5864 (new-level (+ old-level arg))
5865 (text (match-string 2)))
5866 (when (not remove)
5867 (setq new-level (% new-level 6))
5868 (setq new-level (cond ((= new-level 0) 6)
5869 ((< new-level 0) (+ new-level 6))
5870 (t new-level))))
5871 (cond
5872 ((= new-level 0)
5873 (markdown-unwrap-thing-at-point nil 0 2))
5874 ((<= new-level 6)
5875 (goto-char (match-beginning 0))
5876 (delete-region (match-beginning 0) (match-end 0))
5877 (markdown-insert-header new-level text nil)))))
5879 (defun markdown-cycle-setext (arg &optional remove)
5880 "Cycle setext header markup.
5881 Promote header (increase level) when ARG is 1 and demote
5882 header (decrease level or remove) if arg is -1. When demoting a
5883 level-two setext header, replace with a level-three atx header.
5884 When REMOVE is non-nil, remove the header when the level reaches
5885 zero. Otherwise, cycle back to a level six atx header. Assumes
5886 match data is available for `markdown-regex-header-setext'."
5887 (let* ((char (char-after (match-beginning 2)))
5888 (old-level (if (char-equal char ?=) 1 2))
5889 (new-level (+ old-level arg)))
5890 (when (and (not remove) (= new-level 0))
5891 (setq new-level 6))
5892 (cond
5893 ((= new-level 0)
5894 (markdown-unwrap-thing-at-point nil 0 1))
5895 ((<= new-level 2)
5896 (markdown-insert-header new-level nil t))
5897 ((<= new-level 6)
5898 (markdown-insert-header new-level nil nil)))))
5900 (defun markdown-cycle-hr (arg &optional remove)
5901 "Cycle string used for horizontal rule from `markdown-hr-strings'.
5902 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
5903 backwards (promote). When REMOVE is non-nil, remove the hr instead
5904 of cycling when the end of the list is reached.
5905 Assumes match data is available for `markdown-regex-hr'."
5906 (let* ((strings (if (= arg -1)
5907 (reverse markdown-hr-strings)
5908 markdown-hr-strings))
5909 (tail (member (match-string 0) strings))
5910 (new (or (cadr tail)
5911 (if remove
5912 (if (= arg 1)
5914 (car tail))
5915 (car strings)))))
5916 (replace-match new)))
5918 (defun markdown-cycle-bold ()
5919 "Cycle bold markup between underscores and asterisks.
5920 Assumes match data is available for `markdown-regex-bold'."
5921 (save-excursion
5922 (let* ((old-delim (match-string 3))
5923 (new-delim (if (string-equal old-delim "**") "__" "**")))
5924 (replace-match new-delim t t nil 3)
5925 (replace-match new-delim t t nil 5))))
5927 (defun markdown-cycle-italic ()
5928 "Cycle italic markup between underscores and asterisks.
5929 Assumes match data is available for `markdown-regex-italic'."
5930 (save-excursion
5931 (let* ((old-delim (match-string 2))
5932 (new-delim (if (string-equal old-delim "*") "_" "*")))
5933 (replace-match new-delim t t nil 2)
5934 (replace-match new-delim t t nil 4))))
5937 ;;; Keymap ====================================================================
5939 (defun markdown--style-map-prompt ()
5940 "Return a formatted prompt for Markdown markup insertion."
5941 (when markdown-enable-prefix-prompts
5942 (concat
5943 "Markdown: "
5944 (propertize "bold" 'face 'markdown-bold-face) ", "
5945 (propertize "italic" 'face 'markdown-italic-face) ", "
5946 (propertize "code" 'face 'markdown-inline-code-face) ", "
5947 (propertize "C = GFM code" 'face 'markdown-code-face) ", "
5948 (propertize "pre" 'face 'markdown-pre-face) ", "
5949 (propertize "footnote" 'face 'markdown-footnote-text-face) ", "
5950 (propertize "q = blockquote" 'face 'markdown-blockquote-face) ", "
5951 (propertize "h & 1-6 = heading" 'face 'markdown-header-face) ", "
5952 (propertize "- = hr" 'face 'markdown-hr-face) ", "
5953 "C-h = more")))
5955 (defun markdown--command-map-prompt ()
5956 "Return prompt for Markdown buffer-wide commands."
5957 (when markdown-enable-prefix-prompts
5958 (concat
5959 "Command: "
5960 (propertize "m" 'face 'markdown-bold-face) "arkdown, "
5961 (propertize "p" 'face 'markdown-bold-face) "review, "
5962 (propertize "o" 'face 'markdown-bold-face) "pen, "
5963 (propertize "e" 'face 'markdown-bold-face) "xport, "
5964 "export & pre" (propertize "v" 'face 'markdown-bold-face) "iew, "
5965 (propertize "c" 'face 'markdown-bold-face) "heck refs, "
5966 "C-h = more")))
5968 (defvar markdown-mode-style-map
5969 (let ((map (make-keymap (markdown--style-map-prompt))))
5970 (define-key map (kbd "1") 'markdown-insert-header-atx-1)
5971 (define-key map (kbd "2") 'markdown-insert-header-atx-2)
5972 (define-key map (kbd "3") 'markdown-insert-header-atx-3)
5973 (define-key map (kbd "4") 'markdown-insert-header-atx-4)
5974 (define-key map (kbd "5") 'markdown-insert-header-atx-5)
5975 (define-key map (kbd "6") 'markdown-insert-header-atx-6)
5976 (define-key map (kbd "!") 'markdown-insert-header-setext-1)
5977 (define-key map (kbd "@") 'markdown-insert-header-setext-2)
5978 (define-key map (kbd "b") 'markdown-insert-bold)
5979 (define-key map (kbd "c") 'markdown-insert-code)
5980 (define-key map (kbd "C") 'markdown-insert-gfm-code-block)
5981 (define-key map (kbd "f") 'markdown-insert-footnote)
5982 (define-key map (kbd "h") 'markdown-insert-header-dwim)
5983 (define-key map (kbd "H") 'markdown-insert-header-setext-dwim)
5984 (define-key map (kbd "i") 'markdown-insert-italic)
5985 (define-key map (kbd "k") 'markdown-insert-kbd)
5986 (define-key map (kbd "l") 'markdown-insert-link)
5987 (define-key map (kbd "p") 'markdown-insert-pre)
5988 (define-key map (kbd "P") 'markdown-pre-region)
5989 (define-key map (kbd "q") 'markdown-insert-blockquote)
5990 (define-key map (kbd "s") 'markdown-insert-strike-through)
5991 (define-key map (kbd "Q") 'markdown-blockquote-region)
5992 (define-key map (kbd "w") 'markdown-insert-wiki-link)
5993 (define-key map (kbd "-") 'markdown-insert-hr)
5994 (define-key map (kbd "[") 'markdown-insert-gfm-checkbox)
5995 ;; Deprecated keys that may be removed in a future version
5996 (define-key map (kbd "e") 'markdown-insert-italic)
5997 map)
5998 "Keymap for Markdown text styling commands.")
6000 (defvar markdown-mode-command-map
6001 (let ((map (make-keymap (markdown--command-map-prompt))))
6002 (define-key map (kbd "m") 'markdown-other-window)
6003 (define-key map (kbd "p") 'markdown-preview)
6004 (define-key map (kbd "e") 'markdown-export)
6005 (define-key map (kbd "v") 'markdown-export-and-preview)
6006 (define-key map (kbd "o") 'markdown-open)
6007 (define-key map (kbd "l") 'markdown-live-preview-mode)
6008 (define-key map (kbd "w") 'markdown-kill-ring-save)
6009 (define-key map (kbd "c") 'markdown-check-refs)
6010 (define-key map (kbd "n") 'markdown-cleanup-list-numbers)
6011 (define-key map (kbd "]") 'markdown-complete-buffer)
6012 (define-key map (kbd "^") 'markdown-table-sort-lines)
6013 (define-key map (kbd "|") 'markdown-table-convert-region)
6014 (define-key map (kbd "t") 'markdown-table-transpose)
6015 map)
6016 "Keymap for Markdown buffer-wide commands.")
6018 (defvar markdown-mode-map
6019 (let ((map (make-keymap)))
6020 ;; Markup insertion & removal
6021 (define-key map (kbd "C-c C-s") markdown-mode-style-map)
6022 (define-key map (kbd "C-c C-l") 'markdown-insert-link)
6023 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
6024 ;; Promotion, demotion, and cycling
6025 (define-key map (kbd "C-c C--") 'markdown-promote)
6026 (define-key map (kbd "C-c C-=") 'markdown-demote)
6027 (define-key map (kbd "C-c C-]") 'markdown-complete)
6028 ;; Following and doing things
6029 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
6030 (define-key map (kbd "C-c C-d") 'markdown-do)
6031 (define-key map (kbd "C-c '") 'markdown-edit-code-block)
6032 ;; Indentation
6033 (define-key map (kbd "C-m") 'markdown-enter-key)
6034 (define-key map (kbd "DEL") 'markdown-outdent-or-delete)
6035 (define-key map (kbd "C-c >") 'markdown-indent-region)
6036 (define-key map (kbd "C-c <") 'markdown-outdent-region)
6037 ;; Visibility cycling
6038 (define-key map (kbd "TAB") 'markdown-cycle)
6039 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
6040 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
6041 (define-key map (kbd "<backtab>") 'markdown-shifttab)
6042 ;; Heading and list navigation
6043 (define-key map (kbd "C-c C-n") 'markdown-outline-next)
6044 (define-key map (kbd "C-c C-p") 'markdown-outline-previous)
6045 (define-key map (kbd "C-c C-f") 'markdown-outline-next-same-level)
6046 (define-key map (kbd "C-c C-b") 'markdown-outline-previous-same-level)
6047 (define-key map (kbd "C-c C-u") 'markdown-outline-up)
6048 ;; Buffer-wide commands
6049 (define-key map (kbd "C-c C-c") markdown-mode-command-map)
6050 ;; Subtree, list, and table editing
6051 (define-key map (kbd "C-c <up>") 'markdown-move-up)
6052 (define-key map (kbd "C-c <down>") 'markdown-move-down)
6053 (define-key map (kbd "C-c <left>") 'markdown-promote)
6054 (define-key map (kbd "C-c <right>") 'markdown-demote)
6055 (define-key map (kbd "C-c S-<up>") 'markdown-table-delete-row)
6056 (define-key map (kbd "C-c S-<down>") 'markdown-table-insert-row)
6057 (define-key map (kbd "C-c S-<left>") 'markdown-table-delete-column)
6058 (define-key map (kbd "C-c S-<right>") 'markdown-table-insert-column)
6059 (define-key map (kbd "C-c C-M-h") 'markdown-mark-subtree)
6060 (define-key map (kbd "C-x n s") 'markdown-narrow-to-subtree)
6061 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
6062 (define-key map (kbd "C-c C-j") 'markdown-insert-list-item)
6063 ;; Paragraphs (Markdown context aware)
6064 (define-key map [remap backward-paragraph] 'markdown-backward-paragraph)
6065 (define-key map [remap forward-paragraph] 'markdown-forward-paragraph)
6066 (define-key map [remap mark-paragraph] 'markdown-mark-paragraph)
6067 ;; Blocks (one or more paragraphs)
6068 (define-key map (kbd "C-M-{") 'markdown-backward-block)
6069 (define-key map (kbd "C-M-}") 'markdown-forward-block)
6070 (define-key map (kbd "C-c M-h") 'markdown-mark-block)
6071 (define-key map (kbd "C-x n b") 'markdown-narrow-to-block)
6072 ;; Pages (top-level sections)
6073 (define-key map [remap backward-page] 'markdown-backward-page)
6074 (define-key map [remap forward-page] 'markdown-forward-page)
6075 (define-key map [remap mark-page] 'markdown-mark-page)
6076 (define-key map [remap narrow-to-page] 'markdown-narrow-to-page)
6077 ;; Link Movement
6078 (define-key map (kbd "M-n") 'markdown-next-link)
6079 (define-key map (kbd "M-p") 'markdown-previous-link)
6080 ;; Toggling functionality
6081 (define-key map (kbd "C-c C-x C-e") 'markdown-toggle-math)
6082 (define-key map (kbd "C-c C-x C-f") 'markdown-toggle-fontify-code-blocks-natively)
6083 (define-key map (kbd "C-c C-x C-i") 'markdown-toggle-inline-images)
6084 (define-key map (kbd "C-c C-x C-l") 'markdown-toggle-url-hiding)
6085 (define-key map (kbd "C-c C-x C-m") 'markdown-toggle-markup-hiding)
6086 ;; Alternative keys (in case of problems with the arrow keys)
6087 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
6088 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
6089 (define-key map (kbd "C-c C-x l") 'markdown-promote)
6090 (define-key map (kbd "C-c C-x r") 'markdown-demote)
6091 ;; Deprecated keys that may be removed in a future version
6092 (define-key map (kbd "C-c C-a L") 'markdown-insert-link) ;; C-c C-l
6093 (define-key map (kbd "C-c C-a l") 'markdown-insert-link) ;; C-c C-l
6094 (define-key map (kbd "C-c C-a r") 'markdown-insert-link) ;; C-c C-l
6095 (define-key map (kbd "C-c C-a u") 'markdown-insert-uri) ;; C-c C-l
6096 (define-key map (kbd "C-c C-a f") 'markdown-insert-footnote)
6097 (define-key map (kbd "C-c C-a w") 'markdown-insert-wiki-link)
6098 (define-key map (kbd "C-c C-t 1") 'markdown-insert-header-atx-1)
6099 (define-key map (kbd "C-c C-t 2") 'markdown-insert-header-atx-2)
6100 (define-key map (kbd "C-c C-t 3") 'markdown-insert-header-atx-3)
6101 (define-key map (kbd "C-c C-t 4") 'markdown-insert-header-atx-4)
6102 (define-key map (kbd "C-c C-t 5") 'markdown-insert-header-atx-5)
6103 (define-key map (kbd "C-c C-t 6") 'markdown-insert-header-atx-6)
6104 (define-key map (kbd "C-c C-t !") 'markdown-insert-header-setext-1)
6105 (define-key map (kbd "C-c C-t @") 'markdown-insert-header-setext-2)
6106 (define-key map (kbd "C-c C-t h") 'markdown-insert-header-dwim)
6107 (define-key map (kbd "C-c C-t H") 'markdown-insert-header-setext-dwim)
6108 (define-key map (kbd "C-c C-t s") 'markdown-insert-header-setext-2)
6109 (define-key map (kbd "C-c C-t t") 'markdown-insert-header-setext-1)
6110 (define-key map (kbd "C-c C-i") 'markdown-insert-image)
6111 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item) ;; C-c C-j
6112 (define-key map (kbd "C-c C-x C-x") 'markdown-toggle-gfm-checkbox) ;; C-c C-d
6113 (define-key map (kbd "C-c -") 'markdown-insert-hr)
6114 map)
6115 "Keymap for Markdown major mode.")
6117 (defvar markdown-mode-mouse-map
6118 (let ((map (make-sparse-keymap)))
6119 (define-key map [follow-link] 'mouse-face)
6120 (define-key map [mouse-2] 'markdown-follow-link-at-point)
6121 map)
6122 "Keymap for following links with mouse.")
6124 (defvar gfm-mode-map
6125 (let ((map (make-sparse-keymap)))
6126 (set-keymap-parent map markdown-mode-map)
6127 (define-key map (kbd "C-c C-s d") 'markdown-insert-strike-through)
6128 (define-key map "`" 'markdown-electric-backquote)
6129 map)
6130 "Keymap for `gfm-mode'.
6131 See also `markdown-mode-map'.")
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
7354 ;; Global cycling
7355 ((eq arg t)
7356 (cond
7357 ;; Move from overview to contents
7358 ((and (eq last-command this-command)
7359 (eq markdown-cycle-global-status 2))
7360 (markdown-hide-sublevels 1)
7361 (message "CONTENTS")
7362 (setq markdown-cycle-global-status 3)
7363 (markdown-outline-fix-visibility))
7364 ;; Move from contents to all
7365 ((and (eq last-command this-command)
7366 (eq markdown-cycle-global-status 3))
7367 (markdown-show-all)
7368 (message "SHOW ALL")
7369 (setq markdown-cycle-global-status 1))
7370 ;; Defaults to overview
7372 (markdown-hide-body)
7373 (message "OVERVIEW")
7374 (setq markdown-cycle-global-status 2)
7375 (markdown-outline-fix-visibility))))
7377 ;; At a heading: rotate between three different views
7378 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
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 ;; Nothing is hidden behind this heading
7397 ((= eos eoh)
7398 (message "EMPTY ENTRY")
7399 (setq markdown-cycle-subtree-status nil))
7400 ;; Entire subtree is hidden in one line: open it
7401 ((>= eol eos)
7402 (markdown-show-entry)
7403 (markdown-show-children)
7404 (message "CHILDREN")
7405 (setq markdown-cycle-subtree-status 'children))
7406 ;; We just showed the children, now show everything.
7407 ((and (eq last-command this-command)
7408 (eq markdown-cycle-subtree-status 'children))
7409 (markdown-show-subtree)
7410 (message "SUBTREE")
7411 (setq markdown-cycle-subtree-status 'subtree))
7412 ;; Default action: hide the subtree.
7414 (markdown-hide-subtree)
7415 (message "FOLDED")
7416 (setq markdown-cycle-subtree-status 'folded)))))
7418 ;; In a table, move forward by one cell
7419 ((markdown-table-at-point-p)
7420 (call-interactively #'markdown-table-forward-cell))
7422 ;; Otherwise, indent as appropriate
7424 (indent-for-tab-command))))
7426 (defun markdown-shifttab ()
7427 "Handle S-TAB keybinding based on context.
7428 When in a table, move backward one cell.
7429 Otherwise, cycle global heading visibility by calling
7430 `markdown-cycle' with argument t."
7431 (interactive)
7432 (cond ((markdown-table-at-point-p)
7433 (call-interactively #'markdown-table-backward-cell))
7434 (t (markdown-cycle t))))
7436 (defun markdown-outline-level ()
7437 "Return the depth to which a statement is nested in the outline."
7438 (cond
7439 ((and (match-beginning 0)
7440 (markdown-code-block-at-pos (match-beginning 0)))
7441 7) ;; Only 6 header levels are defined.
7442 ((match-end 2) 1)
7443 ((match-end 3) 2)
7444 ((match-end 4)
7445 (length (markdown-trim-whitespace (match-string-no-properties 4))))))
7447 (defun markdown-promote-subtree (&optional arg)
7448 "Promote the current subtree of ATX headings.
7449 Note that Markdown does not support heading levels higher than
7450 six and therefore level-six headings will not be promoted
7451 further. If ARG is non-nil promote the heading, otherwise
7452 demote."
7453 (interactive "*P")
7454 (save-excursion
7455 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
7456 (re-search-backward markdown-regex-header-atx nil t))
7457 (not (markdown-code-block-at-point-p)))
7458 (let ((level (length (match-string 1)))
7459 (promote-or-demote (if arg 1 -1))
7460 (remove 't))
7461 (markdown-cycle-atx promote-or-demote remove)
7462 (catch 'end-of-subtree
7463 (while (and (markdown-next-heading)
7464 (looking-at markdown-regex-header-atx))
7465 ;; Exit if this not a higher level heading; promote otherwise.
7466 (if (and (looking-at markdown-regex-header-atx)
7467 (<= (length (match-string-no-properties 1)) level))
7468 (throw 'end-of-subtree nil)
7469 (markdown-cycle-atx promote-or-demote remove))))))))
7471 (defun markdown-demote-subtree ()
7472 "Demote the current subtree of ATX headings."
7473 (interactive)
7474 (markdown-promote-subtree t))
7476 (defun markdown-move-subtree-up ()
7477 "Move the current subtree of ATX headings up."
7478 (interactive)
7479 (outline-move-subtree-up 1))
7481 (defun markdown-move-subtree-down ()
7482 "Move the current subtree of ATX headings down."
7483 (interactive)
7484 (outline-move-subtree-down 1))
7486 (defun markdown-outline-next ()
7487 "Move to next list item, when in a list, or next visible heading."
7488 (interactive)
7489 (let ((bounds (markdown-next-list-item-bounds)))
7490 (if bounds
7491 (goto-char (nth 0 bounds))
7492 (markdown-next-visible-heading 1))))
7494 (defun markdown-outline-previous ()
7495 "Move to previous list item, when in a list, or previous visible heading."
7496 (interactive)
7497 (let ((bounds (markdown-prev-list-item-bounds)))
7498 (if bounds
7499 (goto-char (nth 0 bounds))
7500 (markdown-previous-visible-heading 1))))
7502 (defun markdown-outline-next-same-level ()
7503 "Move to next list item or heading of same level."
7504 (interactive)
7505 (let ((bounds (markdown-cur-list-item-bounds)))
7506 (if bounds
7507 (markdown-next-list-item (nth 3 bounds))
7508 (markdown-forward-same-level 1))))
7510 (defun markdown-outline-previous-same-level ()
7511 "Move to previous list item or heading of same level."
7512 (interactive)
7513 (let ((bounds (markdown-cur-list-item-bounds)))
7514 (if bounds
7515 (markdown-prev-list-item (nth 3 bounds))
7516 (markdown-backward-same-level 1))))
7518 (defun markdown-outline-up ()
7519 "Move to previous list item, when in a list, or next heading."
7520 (interactive)
7521 (unless (markdown-up-list)
7522 (markdown-up-heading 1)))
7525 ;;; Marking and Narrowing =====================================================
7527 (defun markdown-mark-paragraph ()
7528 "Put mark at end of this block, point at beginning.
7529 The block marked is the one that contains point or follows point.
7531 Interactively, if this command is repeated or (in Transient Mark
7532 mode) if the mark is active, it marks the next block after the
7533 ones already marked."
7534 (interactive)
7535 (if (or (and (eq last-command this-command) (mark t))
7536 (and transient-mark-mode mark-active))
7537 (set-mark
7538 (save-excursion
7539 (goto-char (mark))
7540 (markdown-forward-paragraph)
7541 (point)))
7542 (let ((beginning-of-defun-function 'markdown-backward-paragraph)
7543 (end-of-defun-function 'markdown-forward-paragraph))
7544 (mark-defun))))
7546 (defun markdown-mark-block ()
7547 "Put mark at end of this block, point at beginning.
7548 The block marked is the one that contains point or follows point.
7550 Interactively, if this command is repeated or (in Transient Mark
7551 mode) if the mark is active, it marks the next block after the
7552 ones already marked."
7553 (interactive)
7554 (if (or (and (eq last-command this-command) (mark t))
7555 (and transient-mark-mode mark-active))
7556 (set-mark
7557 (save-excursion
7558 (goto-char (mark))
7559 (markdown-forward-block)
7560 (point)))
7561 (let ((beginning-of-defun-function 'markdown-backward-block)
7562 (end-of-defun-function 'markdown-forward-block))
7563 (mark-defun))))
7565 (defun markdown-narrow-to-block ()
7566 "Make text outside current block invisible.
7567 The current block is the one that contains point or follows point."
7568 (interactive)
7569 (let ((beginning-of-defun-function 'markdown-backward-block)
7570 (end-of-defun-function 'markdown-forward-block))
7571 (narrow-to-defun)))
7573 (defun markdown-mark-text-block ()
7574 "Put mark at end of this plain text block, point at beginning.
7575 The block marked is the one that contains point or follows point.
7577 Interactively, if this command is repeated or (in Transient Mark
7578 mode) if the mark is active, it marks the next block after the
7579 ones already marked."
7580 (interactive)
7581 (if (or (and (eq last-command this-command) (mark t))
7582 (and transient-mark-mode mark-active))
7583 (set-mark
7584 (save-excursion
7585 (goto-char (mark))
7586 (markdown-end-of-text-block)
7587 (point)))
7588 (let ((beginning-of-defun-function 'markdown-beginning-of-text-block)
7589 (end-of-defun-function 'markdown-end-of-text-block))
7590 (mark-defun))))
7592 (defun markdown-mark-page ()
7593 "Put mark at end of this top level section, point at beginning.
7594 The top level section marked is the one that contains point or
7595 follows point.
7597 Interactively, if this command is repeated or (in Transient Mark
7598 mode) if the mark is active, it marks the next page after the
7599 ones already marked."
7600 (interactive)
7601 (if (or (and (eq last-command this-command) (mark t))
7602 (and transient-mark-mode mark-active))
7603 (set-mark
7604 (save-excursion
7605 (goto-char (mark))
7606 (markdown-forward-page)
7607 (point)))
7608 (let ((beginning-of-defun-function 'markdown-backward-page)
7609 (end-of-defun-function 'markdown-forward-page))
7610 (mark-defun))))
7612 (defun markdown-narrow-to-page ()
7613 "Make text outside current top level section invisible.
7614 The current section is the one that contains point or follows point."
7615 (interactive)
7616 (let ((beginning-of-defun-function 'markdown-backward-page)
7617 (end-of-defun-function 'markdown-forward-page))
7618 (narrow-to-defun)))
7620 (defun markdown-mark-subtree ()
7621 "Mark the current subtree.
7622 This puts point at the start of the current subtree, and mark at the end."
7623 (interactive)
7624 (let ((beg))
7625 (if (markdown-heading-at-point)
7626 (beginning-of-line)
7627 (markdown-previous-visible-heading 1))
7628 (setq beg (point))
7629 (markdown-end-of-subtree)
7630 (push-mark (point) nil t)
7631 (goto-char beg)))
7633 (defun markdown-narrow-to-subtree ()
7634 "Narrow buffer to the current subtree."
7635 (interactive)
7636 (save-excursion
7637 (save-match-data
7638 (narrow-to-region
7639 (progn (markdown-back-to-heading-over-code-block t) (point))
7640 (progn (markdown-end-of-subtree)
7641 (if (and (markdown-heading-at-point) (not (eobp)))
7642 (backward-char 1))
7643 (point))))))
7646 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
7648 (defun markdown-move-up ()
7649 "Move thing at point up.
7650 When in a list item, call `markdown-move-list-item-up'.
7651 When in a table, call `markdown-table-move-row-up'.
7652 Otherwise, move the current heading subtree up with
7653 `markdown-move-subtree-up'."
7654 (interactive)
7655 (cond
7656 ((markdown-list-item-at-point-p)
7657 (call-interactively #'markdown-move-list-item-up))
7658 ((markdown-table-at-point-p)
7659 (call-interactively #'markdown-table-move-row-up))
7661 (call-interactively #'markdown-move-subtree-up))))
7663 (defun markdown-move-down ()
7664 "Move thing at point down.
7665 When in a list item, call `markdown-move-list-item-down'.
7666 Otherwise, move the current heading subtree up with
7667 `markdown-move-subtree-down'."
7668 (interactive)
7669 (cond
7670 ((markdown-list-item-at-point-p)
7671 (call-interactively #'markdown-move-list-item-down))
7672 ((markdown-table-at-point-p)
7673 (call-interactively #'markdown-table-move-row-down))
7675 (call-interactively #'markdown-move-subtree-down))))
7677 (defun markdown-promote ()
7678 "Promote or move element at point to the left.
7679 Depending on the context, this function will promote a heading or
7680 list item at the point, move a table column to the left, or cycle
7681 markup."
7682 (interactive)
7683 (let (bounds)
7684 (cond
7685 ;; Promote atx heading subtree
7686 ((thing-at-point-looking-at markdown-regex-header-atx)
7687 (markdown-promote-subtree))
7688 ;; Promote setext heading
7689 ((thing-at-point-looking-at markdown-regex-header-setext)
7690 (markdown-cycle-setext -1))
7691 ;; Promote horizonal rule
7692 ((thing-at-point-looking-at markdown-regex-hr)
7693 (markdown-cycle-hr -1))
7694 ;; Promote list item
7695 ((setq bounds (markdown-cur-list-item-bounds))
7696 (markdown-promote-list-item bounds))
7697 ;; Move table column to the left
7698 ((markdown-table-at-point-p)
7699 (call-interactively #'markdown-table-move-column-left))
7700 ;; Promote bold
7701 ((thing-at-point-looking-at markdown-regex-bold)
7702 (markdown-cycle-bold))
7703 ;; Promote italic
7704 ((thing-at-point-looking-at markdown-regex-italic)
7705 (markdown-cycle-italic))
7707 (user-error "Nothing to promote at point")))))
7709 (defun markdown-demote ()
7710 "Demote or move element at point to the right.
7711 Depending on the context, this function will demote a heading or
7712 list item at the point, move a table column to the right, or cycle
7713 or remove markup."
7714 (interactive)
7715 (let (bounds)
7716 (cond
7717 ;; Demote atx heading subtree
7718 ((thing-at-point-looking-at markdown-regex-header-atx)
7719 (markdown-demote-subtree))
7720 ;; Demote setext heading
7721 ((thing-at-point-looking-at markdown-regex-header-setext)
7722 (markdown-cycle-setext 1))
7723 ;; Demote horizonal rule
7724 ((thing-at-point-looking-at markdown-regex-hr)
7725 (markdown-cycle-hr 1))
7726 ;; Demote list item
7727 ((setq bounds (markdown-cur-list-item-bounds))
7728 (markdown-demote-list-item bounds))
7729 ;; Move table column to the right
7730 ((markdown-table-at-point-p)
7731 (call-interactively #'markdown-table-move-column-right))
7732 ;; Demote bold
7733 ((thing-at-point-looking-at markdown-regex-bold)
7734 (markdown-cycle-bold))
7735 ;; Demote italic
7736 ((thing-at-point-looking-at markdown-regex-italic)
7737 (markdown-cycle-italic))
7739 (user-error "Nothing to demote at point")))))
7742 ;;; Commands ==================================================================
7744 (defun markdown (&optional output-buffer-name)
7745 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
7746 The output buffer name defaults to `markdown-output-buffer-name'.
7747 Return the name of the output buffer used."
7748 (interactive)
7749 (save-window-excursion
7750 (let ((begin-region)
7751 (end-region))
7752 (if (markdown-use-region-p)
7753 (setq begin-region (region-beginning)
7754 end-region (region-end))
7755 (setq begin-region (point-min)
7756 end-region (point-max)))
7758 (unless output-buffer-name
7759 (setq output-buffer-name markdown-output-buffer-name))
7760 (cond
7761 ;; Handle case when `markdown-command' does not read from stdin
7762 ((and (stringp markdown-command) markdown-command-needs-filename)
7763 (if (not buffer-file-name)
7764 (user-error "Must be visiting a file")
7765 (shell-command (concat markdown-command " "
7766 (shell-quote-argument buffer-file-name))
7767 output-buffer-name)))
7768 ;; Pass region to `markdown-command' via stdin
7770 (let ((buf (get-buffer-create output-buffer-name)))
7771 (with-current-buffer buf
7772 (setq buffer-read-only nil)
7773 (erase-buffer))
7774 (if (stringp markdown-command)
7775 (call-process-region begin-region end-region
7776 shell-file-name nil buf nil
7777 shell-command-switch markdown-command)
7778 (funcall markdown-command begin-region end-region buf))))))
7779 output-buffer-name))
7781 (defun markdown-standalone (&optional output-buffer-name)
7782 "Special function to provide standalone HTML output.
7783 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
7784 (interactive)
7785 (setq output-buffer-name (markdown output-buffer-name))
7786 (with-current-buffer output-buffer-name
7787 (set-buffer output-buffer-name)
7788 (unless (markdown-output-standalone-p)
7789 (markdown-add-xhtml-header-and-footer output-buffer-name))
7790 (goto-char (point-min))
7791 (html-mode))
7792 output-buffer-name)
7794 (defun markdown-other-window (&optional output-buffer-name)
7795 "Run `markdown-command' on current buffer and display in other window.
7796 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7797 that name."
7798 (interactive)
7799 (markdown-display-buffer-other-window
7800 (markdown-standalone output-buffer-name)))
7802 (defun markdown-output-standalone-p ()
7803 "Determine whether `markdown-command' output is standalone XHTML.
7804 Standalone XHTML output is identified by an occurrence of
7805 `markdown-xhtml-standalone-regexp' in the first five lines of output."
7806 (save-excursion
7807 (goto-char (point-min))
7808 (save-match-data
7809 (re-search-forward
7810 markdown-xhtml-standalone-regexp
7811 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
7812 t))))
7814 (defun markdown-stylesheet-link-string (stylesheet-path)
7815 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
7816 stylesheet-path
7817 "\" />"))
7819 (defun markdown-add-xhtml-header-and-footer (title)
7820 "Wrap XHTML header and footer with given TITLE around current buffer."
7821 (goto-char (point-min))
7822 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
7823 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
7824 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
7825 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
7826 "<head>\n<title>")
7827 (insert title)
7828 (insert "</title>\n")
7829 (when (> (length markdown-content-type) 0)
7830 (insert
7831 (format
7832 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
7833 markdown-content-type
7834 (or (and markdown-coding-system
7835 (fboundp 'coding-system-get)
7836 (coding-system-get markdown-coding-system
7837 'mime-charset))
7838 (and (fboundp 'coding-system-get)
7839 (coding-system-get buffer-file-coding-system
7840 'mime-charset))
7841 "iso-8859-1"))))
7842 (if (> (length markdown-css-paths) 0)
7843 (insert (mapconcat #'markdown-stylesheet-link-string
7844 markdown-css-paths "\n")))
7845 (when (> (length markdown-xhtml-header-content) 0)
7846 (insert markdown-xhtml-header-content))
7847 (insert "\n</head>\n\n"
7848 "<body>\n\n")
7849 (goto-char (point-max))
7850 (insert "\n"
7851 "</body>\n"
7852 "</html>\n"))
7854 (defun markdown-preview (&optional output-buffer-name)
7855 "Run `markdown-command' on the current buffer and view output in browser.
7856 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7857 that name."
7858 (interactive)
7859 (browse-url-of-buffer
7860 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
7862 (defun markdown-export-file-name (&optional extension)
7863 "Attempt to generate a filename for Markdown output.
7864 The file extension will be EXTENSION if given, or .html by default.
7865 If the current buffer is visiting a file, we construct a new
7866 output filename based on that filename. Otherwise, return nil."
7867 (when (buffer-file-name)
7868 (unless extension
7869 (setq extension ".html"))
7870 (let ((candidate
7871 (concat
7872 (cond
7873 ((buffer-file-name)
7874 (file-name-sans-extension (buffer-file-name)))
7875 (t (buffer-name)))
7876 extension)))
7877 (cond
7878 ((equal candidate (buffer-file-name))
7879 (concat candidate extension))
7881 candidate)))))
7883 (defun markdown-export (&optional output-file)
7884 "Run Markdown on the current buffer, save to file, and return the filename.
7885 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
7886 generated by `markdown-export-file-name', which will be constructed using the
7887 current filename, but with the extension removed and replaced with .html."
7888 (interactive)
7889 (unless output-file
7890 (setq output-file (markdown-export-file-name ".html")))
7891 (when output-file
7892 (let* ((init-buf (current-buffer))
7893 (init-point (point))
7894 (init-buf-string (buffer-string))
7895 (output-buffer (find-file-noselect output-file))
7896 (output-buffer-name (buffer-name output-buffer)))
7897 (run-hooks 'markdown-before-export-hook)
7898 (markdown-standalone output-buffer-name)
7899 (with-current-buffer output-buffer
7900 (run-hooks 'markdown-after-export-hook)
7901 (save-buffer)
7902 (when markdown-export-kill-buffer (kill-buffer)))
7903 ;; if modified, restore initial buffer
7904 (when (buffer-modified-p init-buf)
7905 (erase-buffer)
7906 (insert init-buf-string)
7907 (save-buffer)
7908 (goto-char init-point))
7909 output-file)))
7911 (defun markdown-export-and-preview ()
7912 "Export to XHTML using `markdown-export' and browse the resulting file."
7913 (interactive)
7914 (browse-url-of-file (markdown-export)))
7916 (defvar markdown-live-preview-buffer nil
7917 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
7918 (make-variable-buffer-local 'markdown-live-preview-buffer)
7920 (defvar markdown-live-preview-source-buffer nil
7921 "Source buffer from which current buffer was generated.
7922 This is the inverse of `markdown-live-preview-buffer'.")
7923 (make-variable-buffer-local 'markdown-live-preview-source-buffer)
7925 (defvar markdown-live-preview-currently-exporting nil)
7927 (defun markdown-live-preview-get-filename ()
7928 "Standardize the filename exported by `markdown-live-preview-export'."
7929 (markdown-export-file-name ".html"))
7931 (defun markdown-live-preview-window-eww (file)
7932 "Preview FILE with eww.
7933 To be used with `markdown-live-preview-window-function'."
7934 (if (require 'eww nil t)
7935 (progn
7936 (eww-open-file file)
7937 (get-buffer "*eww*"))
7938 (error "EWW is not present or not loaded on this version of Emacs")))
7940 (defun markdown-visual-lines-between-points (beg end)
7941 (save-excursion
7942 (goto-char beg)
7943 (cl-loop with count = 0
7944 while (progn (end-of-visual-line)
7945 (and (< (point) end) (line-move-visual 1 t)))
7946 do (cl-incf count)
7947 finally return count)))
7949 (defun markdown-live-preview-window-serialize (buf)
7950 "Get window point and scroll data for all windows displaying BUF."
7951 (when (buffer-live-p buf)
7952 (with-current-buffer buf
7953 (mapcar
7954 (lambda (win)
7955 (with-selected-window win
7956 (let* ((start (window-start))
7957 (pt (window-point))
7958 (pt-or-sym (cond ((= pt (point-min)) 'min)
7959 ((= pt (point-max)) 'max)
7960 (t pt)))
7961 (diff (markdown-visual-lines-between-points
7962 start pt)))
7963 (list win pt-or-sym diff))))
7964 (get-buffer-window-list buf)))))
7966 (defun markdown-get-point-back-lines (pt num-lines)
7967 (save-excursion
7968 (goto-char pt)
7969 (line-move-visual (- num-lines) t)
7970 ;; in testing, can occasionally overshoot the number of lines to traverse
7971 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
7972 (when (> actual-num-lines num-lines)
7973 (line-move-visual (- actual-num-lines num-lines) t)))
7974 (point)))
7976 (defun markdown-live-preview-window-deserialize (window-posns)
7977 "Apply window point and scroll data from WINDOW-POSNS.
7978 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
7979 (cl-destructuring-bind (win pt-or-sym diff) window-posns
7980 (when (window-live-p win)
7981 (with-current-buffer markdown-live-preview-buffer
7982 (set-window-buffer win (current-buffer))
7983 (cl-destructuring-bind (actual-pt actual-diff)
7984 (cl-case pt-or-sym
7985 (min (list (point-min) 0))
7986 (max (list (point-max) diff))
7987 (t (list pt-or-sym diff)))
7988 (set-window-start
7989 win (markdown-get-point-back-lines actual-pt actual-diff))
7990 (set-window-point win actual-pt))))))
7992 (defun markdown-live-preview-export ()
7993 "Export to XHTML using `markdown-export'.
7994 Browse the resulting file within Emacs using
7995 `markdown-live-preview-window-function' Return the buffer
7996 displaying the rendered output."
7997 (interactive)
7998 (let ((filename (markdown-live-preview-get-filename)))
7999 (when filename
8000 (let* ((markdown-live-preview-currently-exporting t)
8001 (cur-buf (current-buffer))
8002 (export-file (markdown-export filename))
8003 ;; get positions in all windows currently displaying output buffer
8004 (window-data
8005 (markdown-live-preview-window-serialize
8006 markdown-live-preview-buffer)))
8007 (save-window-excursion
8008 (let ((output-buffer
8009 (funcall markdown-live-preview-window-function export-file)))
8010 (with-current-buffer output-buffer
8011 (setq markdown-live-preview-source-buffer cur-buf)
8012 (add-hook 'kill-buffer-hook
8013 #'markdown-live-preview-remove-on-kill t t))
8014 (with-current-buffer cur-buf
8015 (setq markdown-live-preview-buffer output-buffer))))
8016 (with-current-buffer cur-buf
8017 ;; reset all windows displaying output buffer to where they were,
8018 ;; now with the new output
8019 (mapc #'markdown-live-preview-window-deserialize window-data)
8020 ;; delete html editing buffer
8021 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
8022 (when (and export-file (file-exists-p export-file)
8023 (eq markdown-live-preview-delete-export
8024 'delete-on-export))
8025 (delete-file export-file))
8026 markdown-live-preview-buffer)))))
8028 (defun markdown-live-preview-remove ()
8029 (when (buffer-live-p markdown-live-preview-buffer)
8030 (kill-buffer markdown-live-preview-buffer))
8031 (setq markdown-live-preview-buffer nil)
8032 ;; if set to 'delete-on-export, the output has already been deleted
8033 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
8034 (let ((outfile-name (markdown-live-preview-get-filename)))
8035 (when (and outfile-name (file-exists-p outfile-name))
8036 (delete-file outfile-name)))))
8038 (defun markdown-get-other-window ()
8039 "Find another window to display preview or output content."
8040 (cond
8041 ((memq markdown-split-window-direction '(vertical below))
8042 (or (window-in-direction 'below) (split-window-vertically)))
8043 ((memq markdown-split-window-direction '(horizontal right))
8044 (or (window-in-direction 'right) (split-window-horizontally)))
8045 (t (split-window-sensibly (get-buffer-window)))))
8047 (defun markdown-display-buffer-other-window (buf)
8048 "Display preview or output buffer BUF in another window."
8049 (let ((cur-buf (current-buffer))
8050 (window (markdown-get-other-window)))
8051 (set-window-buffer window buf)
8052 (set-buffer cur-buf)))
8054 (defun markdown-live-preview-if-markdown ()
8055 (when (and (derived-mode-p 'markdown-mode)
8056 markdown-live-preview-mode)
8057 (unless markdown-live-preview-currently-exporting
8058 (if (buffer-live-p markdown-live-preview-buffer)
8059 (markdown-live-preview-export)
8060 (markdown-display-buffer-other-window
8061 (markdown-live-preview-export))))))
8063 (defun markdown-live-preview-remove-on-kill ()
8064 (cond ((and (derived-mode-p 'markdown-mode)
8065 markdown-live-preview-mode)
8066 (markdown-live-preview-remove))
8067 (markdown-live-preview-source-buffer
8068 (with-current-buffer markdown-live-preview-source-buffer
8069 (setq markdown-live-preview-buffer nil))
8070 (setq markdown-live-preview-source-buffer nil))))
8072 (defun markdown-live-preview-switch-to-output ()
8073 "Switch to output buffer."
8074 (interactive)
8075 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
8076 output buffer in another window."
8077 (if markdown-live-preview-mode
8078 (markdown-display-buffer-other-window (markdown-live-preview-export)))
8079 (markdown-live-preview-mode))
8081 (defun markdown-live-preview-re-export ()
8082 "Re export source buffer."
8083 (interactive)
8084 "If the current buffer is a buffer displaying the exported version of a
8085 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
8086 update this buffer's contents."
8087 (when markdown-live-preview-source-buffer
8088 (with-current-buffer markdown-live-preview-source-buffer
8089 (markdown-live-preview-export))))
8091 (defun markdown-open ()
8092 "Open file for the current buffer with `markdown-open-command'."
8093 (interactive)
8094 (unless markdown-open-command
8095 (user-error "Variable `markdown-open-command' must be set"))
8096 (if (stringp markdown-open-command)
8097 (if (not buffer-file-name)
8098 (user-error "Must be visiting a file")
8099 (save-buffer)
8100 (call-process markdown-open-command nil 0 nil buffer-file-name))
8101 (funcall markdown-open-command))
8102 nil)
8104 (defun markdown-kill-ring-save ()
8105 "Run Markdown on file and store output in the kill ring."
8106 (interactive)
8107 (save-window-excursion
8108 (markdown)
8109 (with-current-buffer markdown-output-buffer-name
8110 (kill-ring-save (point-min) (point-max)))))
8113 ;;; Links =====================================================================
8115 (defun markdown-link-p ()
8116 "Return non-nil when `point' is at a non-wiki link.
8117 See `markdown-wiki-link-p' for more information."
8118 (let ((case-fold-search nil))
8119 (and (not (markdown-wiki-link-p))
8120 (not (markdown-code-block-at-point-p))
8121 (or (thing-at-point-looking-at markdown-regex-link-inline)
8122 (thing-at-point-looking-at markdown-regex-link-reference)
8123 (thing-at-point-looking-at markdown-regex-uri)
8124 (thing-at-point-looking-at markdown-regex-angle-uri)))))
8126 (make-obsolete 'markdown-link-link 'markdown-link-url "v2.3")
8128 (defun markdown-link-at-pos (pos)
8129 "Return properties of link or image at position POS.
8130 Value is a list of elements describing the link:
8131 0. beginning position
8132 1. end position
8133 2. link text
8134 3. URL
8135 4. reference label
8136 5. title text
8137 6. bang (nil or \"!\")"
8138 (save-excursion
8139 (goto-char pos)
8140 (let (begin end text url reference title bang)
8141 (cond
8142 ;; Inline or reference image or link at point.
8143 ((or (thing-at-point-looking-at markdown-regex-link-inline)
8144 (thing-at-point-looking-at markdown-regex-link-reference))
8145 (setq bang (match-string-no-properties 1)
8146 begin (match-beginning 0)
8147 end (match-end 0)
8148 text (match-string-no-properties 3))
8149 (if (char-equal (char-after (match-beginning 5)) ?\[)
8150 ;; Reference link
8151 (setq reference (match-string-no-properties 6))
8152 ;; Inline link
8153 (setq url (match-string-no-properties 6))
8154 (when (match-end 7)
8155 (setq title (substring (match-string-no-properties 7) 1 -1)))))
8156 ;; Angle bracket URI at point.
8157 ((thing-at-point-looking-at markdown-regex-angle-uri)
8158 (setq begin (match-beginning 0)
8159 end (match-end 0)
8160 url (match-string-no-properties 2)))
8161 ;; Plain URI at point.
8162 ((thing-at-point-looking-at markdown-regex-uri)
8163 (setq begin (match-beginning 0)
8164 end (match-end 0)
8165 url (match-string-no-properties 1))))
8166 (list begin end text url reference title bang))))
8168 (defun markdown-link-url ()
8169 "Return the URL part of the regular (non-wiki) link at point.
8170 Works with both inline and reference style links, and with images.
8171 If point is not at a link or the link reference is not defined
8172 returns nil."
8173 (let* ((values (markdown-link-at-pos (point)))
8174 (text (nth 2 values))
8175 (url (nth 3 values))
8176 (ref (nth 4 values)))
8177 (or url (and ref (car (markdown-reference-definition
8178 (downcase (if (string= ref "") text ref))))))))
8180 (defun markdown-follow-link-at-point ()
8181 "Open the current non-wiki link.
8182 If the link is a complete URL, open in browser with `browse-url'.
8183 Otherwise, open with `find-file' after stripping anchor and/or query string.
8184 Translate filenames using `markdown-filename-translate-function'."
8185 (interactive)
8186 (if (markdown-link-p)
8187 (let* ((url (markdown-link-url))
8188 (struct (url-generic-parse-url url))
8189 (full (url-fullness struct))
8190 (file url))
8191 ;; Parse URL, determine fullness, strip query string
8192 (if (fboundp 'url-path-and-query)
8193 (setq file (car (url-path-and-query struct)))
8194 (when (and (setq file (url-filename struct))
8195 (string-match "\\?" file))
8196 (setq file (substring file 0 (match-beginning 0)))))
8197 ;; Open full URLs in browser, files in Emacs
8198 (if full
8199 (browse-url url)
8200 (when (and file (> (length file) 0))
8201 (find-file (funcall markdown-translate-filename-function file)))))
8202 (user-error "Point is not at a Markdown link or URL")))
8204 (defun markdown-fontify-inline-links (last)
8205 "Add text properties to next inline link from point to LAST."
8206 (when (markdown-match-generic-links last nil)
8207 (let* ((link-start (match-beginning 3))
8208 (link-end (match-end 3))
8209 (url-start (match-beginning 6))
8210 (url-end (match-end 6))
8211 (url (match-string-no-properties 6))
8212 (title-start (match-beginning 7))
8213 (title-end (match-end 7))
8214 (title (match-string-no-properties 7))
8215 ;; Markup part
8216 (mp (list 'face 'markdown-markup-face
8217 'invisible 'markdown-markup
8218 'rear-nonsticky t
8219 'font-lock-multiline t))
8220 ;; Link part
8221 (lp (list 'keymap markdown-mode-mouse-map
8222 'face markdown-link-face
8223 'mouse-face 'markdown-highlight-face
8224 'font-lock-multiline t
8225 'help-echo (if title (concat title "\n" url) url)))
8226 ;; URL part
8227 (up (list 'keymap markdown-mode-mouse-map
8228 'face 'markdown-url-face
8229 'invisible 'markdown-markup
8230 'mouse-face 'markdown-highlight-face
8231 'font-lock-multiline t))
8232 ;; URL composition character
8233 (url-char (markdown--first-displayable markdown-url-compose-char))
8234 ;; Title part
8235 (tp (list 'face 'markdown-link-title-face
8236 'invisible 'markdown-markup
8237 'font-lock-multiline t)))
8238 (dolist (g '(1 2 4 5 8))
8239 (when (match-end g)
8240 (add-text-properties (match-beginning g) (match-end g) mp)))
8241 (when link-start (add-text-properties link-start link-end lp))
8242 (when url-start (add-text-properties url-start url-end up))
8243 (when title-start (add-text-properties url-end title-end tp))
8244 (when (and markdown-hide-urls url-start)
8245 (compose-region url-start (or title-end url-end) url-char))
8246 t)))
8248 (defun markdown-fontify-reference-links (last)
8249 "Add text properties to next reference link from point to LAST."
8250 (when (markdown-match-generic-links last t)
8251 (let* ((link-start (match-beginning 3))
8252 (link-end (match-end 3))
8253 (ref-start (match-beginning 6))
8254 (ref-end (match-end 6))
8255 ;; Markup part
8256 (mp (list 'face 'markdown-markup-face
8257 'invisible 'markdown-markup
8258 'rear-nonsticky t
8259 'font-lock-multiline t))
8260 ;; Link part
8261 (lp (list 'keymap markdown-mode-mouse-map
8262 'face markdown-link-face
8263 'mouse-face 'markdown-highlight-face
8264 'font-lock-multiline t
8265 'help-echo (lambda (_ __ pos)
8266 (save-match-data
8267 (save-excursion
8268 (goto-char pos)
8269 (or (markdown-link-url)
8270 "Undefined reference"))))))
8271 ;; URL composition character
8272 (url-char (markdown--first-displayable markdown-url-compose-char))
8273 ;; Reference part
8274 (rp (list 'face 'markdown-reference-face
8275 'invisible 'markdown-markup
8276 'font-lock-multiline t)))
8277 (dolist (g '(1 2 4 5 8))
8278 (when (match-end g)
8279 (add-text-properties (match-beginning g) (match-end g) mp)))
8280 (when link-start (add-text-properties link-start link-end lp))
8281 (when ref-start (add-text-properties ref-start ref-end rp)
8282 (when (and markdown-hide-urls (> (- ref-end ref-start) 2))
8283 (compose-region ref-start ref-end url-char)))
8284 t)))
8286 (defun markdown-fontify-angle-uris (last)
8287 "Add text properties to angle URIs from point to LAST."
8288 (when (markdown-match-angle-uris last)
8289 (let* ((url-start (match-beginning 2))
8290 (url-end (match-end 2))
8291 ;; Markup part
8292 (mp (list 'face 'markdown-markup-face
8293 'invisible 'markdown-markup
8294 'rear-nonsticky t
8295 'font-lock-multiline t))
8296 ;; URI part
8297 (up (list 'keymap markdown-mode-mouse-map
8298 'face 'markdown-plain-url-face
8299 'mouse-face 'markdown-highlight-face
8300 'font-lock-multiline t)))
8301 (dolist (g '(1 3))
8302 (add-text-properties (match-beginning g) (match-end g) mp))
8303 (add-text-properties url-start url-end up)
8304 t)))
8306 (defun markdown-fontify-plain-uris (last)
8307 "Add text properties to plain URLs from point to LAST."
8308 (when (markdown-match-plain-uris last)
8309 (let* ((start (match-beginning 0))
8310 (end (match-end 0))
8311 (props (list 'keymap markdown-mode-mouse-map
8312 'face 'markdown-plain-url-face
8313 'mouse-face 'markdown-highlight-face
8314 'rear-nonsticky t
8315 'font-lock-multiline t)))
8316 (add-text-properties start end props)
8317 t)))
8319 (defun markdown-toggle-url-hiding (&optional arg)
8320 "Toggle the display or hiding of URLs.
8321 With a prefix argument ARG, enable URL hiding if ARG is positive,
8322 and disable it otherwise."
8323 (interactive (list (or current-prefix-arg 'toggle)))
8324 (setq markdown-hide-urls
8325 (if (eq arg 'toggle)
8326 (not markdown-hide-urls)
8327 (> (prefix-numeric-value arg) 0)))
8328 (if markdown-hide-urls
8329 (message "markdown-mode URL hiding enabled")
8330 (message "markdown-mode URL hiding disabled"))
8331 (markdown-reload-extensions))
8334 ;;; WikiLink Following/Markup =================================================
8336 (defun markdown-wiki-link-p ()
8337 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
8338 A true wiki link name matches `markdown-regex-wiki-link' but does
8339 not match the current file name after conversion. This modifies
8340 the data returned by `match-data'. Note that the potential wiki
8341 link name must be available via `match-string'."
8342 (when markdown-enable-wiki-links
8343 (let ((case-fold-search nil))
8344 (and (thing-at-point-looking-at markdown-regex-wiki-link)
8345 (not (markdown-code-block-at-point-p))
8346 (or (not buffer-file-name)
8347 (not (string-equal (buffer-file-name)
8348 (markdown-convert-wiki-link-to-filename
8349 (markdown-wiki-link-link)))))))))
8351 (defun markdown-wiki-link-link ()
8352 "Return the link part of the wiki link using current match data.
8353 The location of the link component depends on the value of
8354 `markdown-wiki-link-alias-first'."
8355 (if markdown-wiki-link-alias-first
8356 (or (match-string-no-properties 5) (match-string-no-properties 3))
8357 (match-string-no-properties 3)))
8359 (defun markdown-wiki-link-alias ()
8360 "Return the alias or text part of the wiki link using current match data.
8361 The location of the alias component depends on the value of
8362 `markdown-wiki-link-alias-first'."
8363 (if markdown-wiki-link-alias-first
8364 (match-string-no-properties 3)
8365 (or (match-string-no-properties 5) (match-string-no-properties 3))))
8367 (defun markdown-convert-wiki-link-to-filename (name)
8368 "Generate a filename from the wiki link NAME.
8369 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
8370 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
8371 and [[test test]] both map to Test-test.ext. Look in the current
8372 directory first, then in subdirectories if
8373 `markdown-wiki-link-search-subdirectories' is non-nil, and then
8374 in parent directories if
8375 `markdown-wiki-link-search-parent-directories' is non-nil."
8376 (let* ((basename (markdown-replace-regexp-in-string
8377 "[[:space:]\n]" markdown-link-space-sub-char name))
8378 (basename (if (eq major-mode 'gfm-mode)
8379 (concat (upcase (substring basename 0 1))
8380 (downcase (substring basename 1 nil)))
8381 basename))
8382 directory extension default candidates dir)
8383 (when buffer-file-name
8384 (setq directory (file-name-directory buffer-file-name)
8385 extension (file-name-extension buffer-file-name)))
8386 (setq default (concat basename
8387 (when extension (concat "." extension))))
8388 (cond
8389 ;; Look in current directory first.
8390 ((or (null buffer-file-name)
8391 (file-exists-p default))
8392 default)
8393 ;; Possibly search in subdirectories, next.
8394 ((and markdown-wiki-link-search-subdirectories
8395 (setq candidates
8396 (markdown-directory-files-recursively
8397 directory (concat "^" default "$"))))
8398 (car candidates))
8399 ;; Possibly search in parent directories as a last resort.
8400 ((and markdown-wiki-link-search-parent-directories
8401 (setq dir (locate-dominating-file directory default)))
8402 (concat dir default))
8403 ;; If nothing is found, return default in current directory.
8404 (t default))))
8406 (defun markdown-follow-wiki-link (name &optional other)
8407 "Follow the wiki link NAME.
8408 Convert the name to a file name and call `find-file'. Ensure that
8409 the new buffer remains in `markdown-mode'. Open the link in another
8410 window when OTHER is non-nil."
8411 (let ((filename (markdown-convert-wiki-link-to-filename name))
8412 (wp (when buffer-file-name
8413 (file-name-directory buffer-file-name))))
8414 (if (not wp)
8415 (user-error "Must be visiting a file")
8416 (when other (other-window 1))
8417 (let ((default-directory wp))
8418 (find-file filename)))
8419 (when (not (eq major-mode 'markdown-mode))
8420 (markdown-mode))))
8422 (defun markdown-follow-wiki-link-at-point (&optional arg)
8423 "Find Wiki Link at point.
8424 With prefix argument ARG, open the file in other window.
8425 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
8426 (interactive "P")
8427 (if (markdown-wiki-link-p)
8428 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
8429 (user-error "Point is not at a Wiki Link")))
8431 (defun markdown-highlight-wiki-link (from to face)
8432 "Highlight the wiki link in the region between FROM and TO using FACE."
8433 (put-text-property from to 'font-lock-face face))
8435 (defun markdown-unfontify-region-wiki-links (from to)
8436 "Remove wiki link faces from the region specified by FROM and TO."
8437 (interactive "*r")
8438 (let ((modified (buffer-modified-p)))
8439 (remove-text-properties from to '(font-lock-face markdown-link-face))
8440 (remove-text-properties from to '(font-lock-face markdown-missing-link-face))
8441 ;; remove-text-properties marks the buffer modified in emacs 24.3,
8442 ;; undo that if it wasn't originally marked modified
8443 (set-buffer-modified-p modified)))
8445 (defun markdown-fontify-region-wiki-links (from to)
8446 "Search region given by FROM and TO for wiki links and fontify them.
8447 If a wiki link is found check to see if the backing file exists
8448 and highlight accordingly."
8449 (goto-char from)
8450 (save-match-data
8451 (while (re-search-forward markdown-regex-wiki-link to t)
8452 (when (not (markdown-code-block-at-point-p))
8453 (let ((highlight-beginning (match-beginning 1))
8454 (highlight-end (match-end 1))
8455 (file-name
8456 (markdown-convert-wiki-link-to-filename
8457 (markdown-wiki-link-link))))
8458 (if (condition-case nil (file-exists-p file-name) (error nil))
8459 (markdown-highlight-wiki-link
8460 highlight-beginning highlight-end markdown-link-face)
8461 (markdown-highlight-wiki-link
8462 highlight-beginning highlight-end markdown-missing-link-face)))))))
8464 (defun markdown-extend-changed-region (from to)
8465 "Extend region given by FROM and TO so that we can fontify all links.
8466 The region is extended to the first newline before and the first
8467 newline after."
8468 ;; start looking for the first new line before 'from
8469 (goto-char from)
8470 (re-search-backward "\n" nil t)
8471 (let ((new-from (point-min))
8472 (new-to (point-max)))
8473 (if (not (= (point) from))
8474 (setq new-from (point)))
8475 ;; do the same thing for the first new line after 'to
8476 (goto-char to)
8477 (re-search-forward "\n" nil t)
8478 (if (not (= (point) to))
8479 (setq new-to (point)))
8480 (cl-values new-from new-to)))
8482 (defun markdown-check-change-for-wiki-link (from to)
8483 "Check region between FROM and TO for wiki links and re-fontify as needed."
8484 (interactive "*r")
8485 (let* ((modified (buffer-modified-p))
8486 (buffer-undo-list t)
8487 (inhibit-read-only t)
8488 (inhibit-point-motion-hooks t)
8489 deactivate-mark
8490 buffer-file-truename)
8491 (unwind-protect
8492 (save-excursion
8493 (save-match-data
8494 (save-restriction
8495 ;; Extend the region to fontify so that it starts
8496 ;; and ends at safe places.
8497 (cl-multiple-value-bind (new-from new-to)
8498 (markdown-extend-changed-region from to)
8499 (goto-char new-from)
8500 ;; Only refontify when the range contains text with a
8501 ;; wiki link face or if the wiki link regexp matches.
8502 (when (or (markdown-range-property-any
8503 new-from new-to 'font-lock-face
8504 (list markdown-link-face
8505 markdown-missing-link-face))
8506 (re-search-forward
8507 markdown-regex-wiki-link new-to t))
8508 ;; Unfontify existing fontification (start from scratch)
8509 (markdown-unfontify-region-wiki-links new-from new-to)
8510 ;; Now do the fontification.
8511 (markdown-fontify-region-wiki-links new-from new-to))))))
8512 (and (not modified)
8513 (buffer-modified-p)
8514 (set-buffer-modified-p nil)))))
8516 (defun markdown-check-change-for-wiki-link-after-change (from to _)
8517 "Check region between FROM and TO for wiki links and re-fontify as needed.
8518 Designed to be used with the `after-change-functions' hook."
8519 (markdown-check-change-for-wiki-link from to))
8521 (defun markdown-fontify-buffer-wiki-links ()
8522 "Refontify all wiki links in the buffer."
8523 (interactive)
8524 (markdown-check-change-for-wiki-link (point-min) (point-max)))
8527 ;;; Following & Doing =========================================================
8529 (defun markdown-follow-thing-at-point (arg)
8530 "Follow thing at point if possible, such as a reference link or wiki link.
8531 Opens inline and reference links in a browser. Opens wiki links
8532 to other files in the current window, or the another window if
8533 ARG is non-nil.
8534 See `markdown-follow-link-at-point' and
8535 `markdown-follow-wiki-link-at-point'."
8536 (interactive "P")
8537 (cond ((markdown-link-p)
8538 (markdown-follow-link-at-point))
8539 ((markdown-wiki-link-p)
8540 (markdown-follow-wiki-link-at-point arg))
8542 (user-error "Nothing to follow at point"))))
8544 (make-obsolete 'markdown-jump 'markdown-do "v2.3")
8546 (defun markdown-do ()
8547 "Do something sensible based on context at point.
8548 Jumps between reference links and definitions; between footnote
8549 markers and footnote text."
8550 (interactive)
8551 (cond
8552 ;; Footnote definition
8553 ((markdown-footnote-text-positions)
8554 (markdown-footnote-return))
8555 ;; Footnote marker
8556 ((markdown-footnote-marker-positions)
8557 (markdown-footnote-goto-text))
8558 ;; Reference link
8559 ((thing-at-point-looking-at markdown-regex-link-reference)
8560 (markdown-reference-goto-definition))
8561 ;; Reference definition
8562 ((thing-at-point-looking-at markdown-regex-reference-definition)
8563 (markdown-reference-goto-link (match-string-no-properties 2)))
8564 ;; GFM task list item
8565 ((markdown-gfm-task-list-item-at-point)
8566 (markdown-toggle-gfm-checkbox))
8567 ;; Align table
8568 ((markdown-table-at-point-p)
8569 (call-interactively #'markdown-table-align))
8570 ;; Otherwise
8572 (markdown-insert-gfm-checkbox))))
8575 ;;; Miscellaneous =============================================================
8577 (defun markdown-compress-whitespace-string (str)
8578 "Compress whitespace in STR and return result.
8579 Leading and trailing whitespace is removed. Sequences of multiple
8580 spaces, tabs, and newlines are replaced with single spaces."
8581 (markdown-replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
8582 (markdown-replace-regexp-in-string "[ \t\n]+" " " str)))
8584 (defun markdown--substitute-command-keys (string)
8585 "Like `substitute-command-keys' but, but prefers control characters.
8586 First pass STRING to `substitute-command-keys' and then
8587 substitute `C-i` for `TAB` and `C-m` for `RET`."
8588 (replace-regexp-in-string
8589 "\\<TAB\\>" "C-i"
8590 (replace-regexp-in-string
8591 "\\<RET\\>" "C-m" (substitute-command-keys string) t) t))
8593 (defun markdown-line-number-at-pos (&optional pos)
8594 "Return (narrowed) buffer line number at position POS.
8595 If POS is nil, use current buffer location.
8596 This is an exact copy of `line-number-at-pos' for use in emacs21."
8597 (let ((opoint (or pos (point))) start)
8598 (save-excursion
8599 (goto-char (point-min))
8600 (setq start (point))
8601 (goto-char opoint)
8602 (forward-line 0)
8603 (1+ (count-lines start (point))))))
8605 (defun markdown-inside-link-p ()
8606 "Return t if point is within a link."
8607 (save-match-data
8608 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
8610 (defun markdown-line-is-reference-definition-p ()
8611 "Return whether the current line is a (non-footnote) reference defition."
8612 (save-excursion
8613 (move-beginning-of-line 1)
8614 (and (looking-at-p markdown-regex-reference-definition)
8615 (not (looking-at-p "[ \t]*\\[^")))))
8617 (defun markdown-adaptive-fill-function ()
8618 "Return prefix for filling paragraph or nil if not determined."
8619 (cond
8620 ;; List item inside blockquote
8621 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
8622 (markdown-replace-regexp-in-string
8623 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
8624 ;; Blockquote
8625 ((looking-at markdown-regex-blockquote)
8626 (buffer-substring-no-properties (match-beginning 0) (match-end 2)))
8627 ;; List items
8628 ((looking-at markdown-regex-list)
8629 (match-string-no-properties 0))
8630 ;; Footnote definition
8631 ((looking-at-p markdown-regex-footnote-definition)
8632 " ") ; four spaces
8633 ;; No match
8634 (t nil)))
8636 (defun markdown-fill-paragraph (&optional justify)
8637 "Fill paragraph at or after point.
8638 This function is like \\[fill-paragraph], but it skips Markdown
8639 code blocks. If the point is in a code block, or just before one,
8640 do not fill. Otherwise, call `fill-paragraph' as usual. If
8641 JUSTIFY is non-nil, justify text as well. Since this function
8642 handles filling itself, it always returns t so that
8643 `fill-paragraph' doesn't run."
8644 (interactive "P")
8645 (unless (or (markdown-code-block-at-point-p)
8646 (save-excursion
8647 (back-to-indentation)
8648 (skip-syntax-forward "-")
8649 (markdown-code-block-at-point-p)))
8650 (fill-paragraph justify))
8653 (make-obsolete 'markdown-fill-forward-paragraph-function
8654 'markdown-fill-forward-paragraph "v2.3")
8656 (defun markdown-fill-forward-paragraph (&optional arg)
8657 "Function used by `fill-paragraph' to move over ARG paragraphs.
8658 This is a `fill-forward-paragraph-function' for `markdown-mode'.
8659 It is called with a single argument specifying the number of
8660 paragraphs to move. Just like `forward-paragraph', it should
8661 return the number of paragraphs left to move."
8662 (or arg (setq arg 1))
8663 (if (> arg 0)
8664 ;; With positive ARG, move across ARG non-code-block paragraphs,
8665 ;; one at a time. When passing a code block, don't decrement ARG.
8666 (while (and (not (eobp))
8667 (> arg 0)
8668 (= (forward-paragraph 1) 0)
8669 (or (markdown-code-block-at-pos (point-at-bol 0))
8670 (setq arg (1- arg)))))
8671 ;; Move backward by one paragraph with negative ARG (always -1).
8672 (let ((start (point)))
8673 (setq arg (forward-paragraph arg))
8674 (while (and (not (eobp))
8675 (progn (move-to-left-margin) (not (eobp)))
8676 (looking-at-p paragraph-separate))
8677 (forward-line 1))
8678 (cond
8679 ;; Move point past whitespace following list marker.
8680 ((looking-at markdown-regex-list)
8681 (goto-char (match-end 0)))
8682 ;; Move point past whitespace following pipe at beginning of line
8683 ;; to handle Pandoc line blocks.
8684 ((looking-at "^|\\s-*")
8685 (goto-char (match-end 0)))
8686 ;; Return point if the paragraph passed was a code block.
8687 ((markdown-code-block-at-pos (point-at-bol 2))
8688 (goto-char start)))))
8689 arg)
8691 (defun markdown--inhibit-electric-quote ()
8692 "Function added to `electric-quote-inhibit-functions'.
8693 Return non-nil if the quote has been inserted inside a code block
8694 or span."
8695 (let ((pos (1- (point))))
8696 (or (markdown-inline-code-at-pos pos)
8697 (markdown-code-block-at-pos pos))))
8700 ;;; Extension Framework =======================================================
8702 (defun markdown-reload-extensions ()
8703 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
8704 (interactive)
8705 (when (member major-mode '(markdown-mode gfm-mode))
8706 ;; Refontify buffer
8707 (if (eval-when-compile (fboundp 'font-lock-flush))
8708 ;; Use font-lock-flush in Emacs >= 25.1
8709 (font-lock-flush)
8710 ;; Backwards compatibility for Emacs 24.3-24.5
8711 (when (and font-lock-mode (fboundp 'font-lock-refresh-defaults))
8712 (font-lock-refresh-defaults)))
8713 ;; Add or remove hooks related to extensions
8714 (markdown-setup-wiki-link-hooks)))
8716 (defun markdown-handle-local-variables ()
8717 "Run in `hack-local-variables-hook' to update font lock rules.
8718 Checks to see if there is actually a ‘markdown-mode’ file local variable
8719 before regenerating font-lock rules for extensions."
8720 (when (and (boundp 'file-local-variables-alist)
8721 (or (assoc 'markdown-enable-wiki-links file-local-variables-alist)
8722 (assoc 'markdown-enable-math file-local-variables-alist)))
8723 (when (assoc 'markdown-enable-math file-local-variables-alist)
8724 (markdown-toggle-math markdown-enable-math))
8725 (markdown-reload-extensions)))
8728 ;;; Wiki Links ================================================================
8730 (defun markdown-toggle-wiki-links (&optional arg)
8731 "Toggle support for wiki links.
8732 With a prefix argument ARG, enable wiki link support if ARG is positive,
8733 and disable it otherwise."
8734 (interactive (list (or current-prefix-arg 'toggle)))
8735 (setq markdown-enable-wiki-links
8736 (if (eq arg 'toggle)
8737 (not markdown-enable-wiki-links)
8738 (> (prefix-numeric-value arg) 0)))
8739 (if markdown-enable-wiki-links
8740 (message "markdown-mode wiki link support enabled")
8741 (message "markdown-mode wiki link support disabled"))
8742 (markdown-reload-extensions))
8744 (defun markdown-setup-wiki-link-hooks ()
8745 "Add or remove hooks for fontifying wiki links.
8746 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
8747 ;; Anytime text changes make sure it gets fontified correctly
8748 (if (and markdown-enable-wiki-links
8749 markdown-wiki-link-fontify-missing)
8750 (add-hook 'after-change-functions
8751 'markdown-check-change-for-wiki-link-after-change t t)
8752 (remove-hook 'after-change-functions
8753 'markdown-check-change-for-wiki-link-after-change t))
8754 ;; If we left the buffer there is a really good chance we were
8755 ;; creating one of the wiki link documents. Make sure we get
8756 ;; refontified when we come back.
8757 (if (and markdown-enable-wiki-links
8758 markdown-wiki-link-fontify-missing)
8759 (progn
8760 (add-hook 'window-configuration-change-hook
8761 'markdown-fontify-buffer-wiki-links t t)
8762 (markdown-fontify-buffer-wiki-links))
8763 (remove-hook 'window-configuration-change-hook
8764 'markdown-fontify-buffer-wiki-links t)
8765 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
8768 ;;; Math Support ==============================================================
8770 (make-obsolete 'markdown-enable-math 'markdown-toggle-math "v2.1")
8772 (defconst markdown-mode-font-lock-keywords-math
8773 (list
8774 ;; Equation reference (eq:foo)
8775 '("\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" . ((1 markdown-markup-face)
8776 (2 markdown-reference-face)
8777 (3 markdown-markup-face)))
8778 ;; Equation reference \eqref{foo}
8779 '("\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" . ((1 markdown-markup-face)
8780 (2 markdown-reference-face)
8781 (3 markdown-markup-face))))
8782 "Font lock keywords to add and remove when toggling math support.")
8784 (defun markdown-toggle-math (&optional arg)
8785 "Toggle support for inline and display LaTeX math expressions.
8786 With a prefix argument ARG, enable math mode if ARG is positive,
8787 and disable it otherwise. If called from Lisp, enable the mode
8788 if ARG is omitted or nil."
8789 (interactive (list (or current-prefix-arg 'toggle)))
8790 (setq markdown-enable-math
8791 (if (eq arg 'toggle)
8792 (not markdown-enable-math)
8793 (> (prefix-numeric-value arg) 0)))
8794 (if markdown-enable-math
8795 (progn
8796 (font-lock-add-keywords
8797 'markdown-mode markdown-mode-font-lock-keywords-math)
8798 (message "markdown-mode math support enabled"))
8799 (font-lock-remove-keywords
8800 'markdown-mode markdown-mode-font-lock-keywords-math)
8801 (message "markdown-mode math support disabled"))
8802 (markdown-reload-extensions))
8805 ;;; GFM Checkboxes ============================================================
8807 (define-button-type 'markdown-gfm-checkbox-button
8808 'follow-link t
8809 'face 'markdown-gfm-checkbox-face
8810 'mouse-face 'markdown-highlight-face
8811 'action #'markdown-toggle-gfm-checkbox-button)
8813 (defun markdown-gfm-task-list-item-at-point (&optional bounds)
8814 "Return non-nil if there is a GFM task list item at the point.
8815 Optionally, the list item BOUNDS may be given if available, as
8816 returned by `markdown-cur-list-item-bounds'. When a task list item
8817 is found, the return value is the same value returned by
8818 `markdown-cur-list-item-bounds'."
8819 (unless bounds
8820 (setq bounds (markdown-cur-list-item-bounds)))
8821 (> (length (nth 5 bounds)) 0))
8823 (defun markdown-insert-gfm-checkbox ()
8824 "Add GFM checkbox at point.
8825 Returns t if added.
8826 Returns nil if non-applicable."
8827 (interactive)
8828 (let ((bounds (markdown-cur-list-item-bounds)))
8829 (if bounds
8830 (unless (cl-sixth bounds)
8831 (let ((pos (+ (cl-first bounds) (cl-fourth bounds)))
8832 (markup "[ ] "))
8833 (if (< pos (point))
8834 (save-excursion
8835 (goto-char pos)
8836 (insert markup))
8837 (goto-char pos)
8838 (insert markup))
8840 (unless (save-excursion
8841 (back-to-indentation)
8842 (or (markdown-list-item-at-point-p)
8843 (markdown-heading-at-point)
8844 (markdown-in-comment-p)
8845 (markdown-code-block-at-point-p)))
8846 (let ((pos (save-excursion
8847 (back-to-indentation)
8848 (point)))
8849 (markup (concat (or (save-excursion
8850 (beginning-of-line 0)
8851 (cl-fifth (markdown-cur-list-item-bounds)))
8852 markdown-unordered-list-item-prefix)
8853 "[ ] ")))
8854 (if (< pos (point))
8855 (save-excursion
8856 (goto-char pos)
8857 (insert markup))
8858 (goto-char pos)
8859 (insert markup))
8860 t)))))
8862 (defun markdown-toggle-gfm-checkbox ()
8863 "Toggle GFM checkbox at point.
8864 Returns the resulting status as a string, either \"[x]\" or \"[ ]\".
8865 Returns nil if there is no task list item at the point."
8866 (interactive)
8867 (save-match-data
8868 (save-excursion
8869 (let ((bounds (markdown-cur-list-item-bounds)))
8870 (when bounds
8871 ;; Move to beginning of task list item
8872 (goto-char (cl-first bounds))
8873 ;; Advance to column of first non-whitespace after marker
8874 (forward-char (cl-fourth bounds))
8875 (cond ((looking-at "\\[ \\]")
8876 (replace-match
8877 (if markdown-gfm-uppercase-checkbox "[X]" "[x]")
8878 nil t)
8879 (match-string-no-properties 0))
8880 ((looking-at "\\[[xX]\\]")
8881 (replace-match "[ ]" nil t)
8882 (match-string-no-properties 0))))))))
8884 (defun markdown-toggle-gfm-checkbox-button (button)
8885 "Toggle GFM checkbox BUTTON on click."
8886 (save-match-data
8887 (save-excursion
8888 (goto-char (button-start button))
8889 (markdown-toggle-gfm-checkbox))))
8891 (defun markdown-make-gfm-checkboxes-buttons (start end)
8892 "Make GFM checkboxes buttons in region between START and END."
8893 (save-excursion
8894 (goto-char start)
8895 (let ((case-fold-search t))
8896 (save-excursion
8897 (while (re-search-forward markdown-regex-gfm-checkbox end t)
8898 (make-button (match-beginning 1) (match-end 1)
8899 :type 'markdown-gfm-checkbox-button))))))
8901 ;; Called when any modification is made to buffer text.
8902 (defun markdown-gfm-checkbox-after-change-function (beg end _)
8903 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
8904 BEG and END are the limits of scanned region."
8905 (save-excursion
8906 (save-match-data
8907 ;; Rescan between start of line from `beg' and start of line after `end'.
8908 (markdown-make-gfm-checkboxes-buttons
8909 (progn (goto-char beg) (beginning-of-line) (point))
8910 (progn (goto-char end) (forward-line 1) (point))))))
8912 (defun markdown-remove-gfm-checkbox-overlays ()
8913 "Remove all GFM checkbox overlays in buffer."
8914 (save-excursion
8915 (save-restriction
8916 (widen)
8917 (remove-overlays nil nil 'face 'markdown-gfm-checkbox-face))))
8920 ;;; Display inline image =================================================
8922 (defvar markdown-inline-image-overlays nil)
8923 (make-variable-buffer-local 'markdown-inline-image-overlays)
8925 (defun markdown-remove-inline-images ()
8926 "Remove inline image overlays from image links in the buffer.
8927 This can be toggled with `markdown-toggle-inline-images'
8928 or \\[markdown-toggle-inline-images]."
8929 (interactive)
8930 (mapc #'delete-overlay markdown-inline-image-overlays)
8931 (setq markdown-inline-image-overlays nil))
8933 (defun markdown-display-inline-images ()
8934 "Add inline image overlays to image links in the buffer.
8935 This can be toggled with `markdown-toggle-inline-images'
8936 or \\[markdown-toggle-inline-images]."
8937 (interactive)
8938 (unless (display-graphic-p)
8939 (error "Cannot show images"))
8940 (save-excursion
8941 (save-restriction
8942 (widen)
8943 (goto-char (point-min))
8944 (while (re-search-forward markdown-regex-link-inline nil t)
8945 (let ((start (match-beginning 0))
8946 (end (match-end 0))
8947 (file (match-string-no-properties 6)))
8948 (when (file-exists-p file)
8949 (let* ((abspath (if (file-name-absolute-p file)
8950 file
8951 (concat default-directory file)))
8952 (image (create-image abspath)))
8953 (when image
8954 (let ((ov (make-overlay start end)))
8955 (overlay-put ov 'display image)
8956 (overlay-put ov 'face 'default)
8957 (push ov markdown-inline-image-overlays))))))))))
8959 (defun markdown-toggle-inline-images ()
8960 "Toggle inline image overlays in the buffer."
8961 (interactive)
8962 (if markdown-inline-image-overlays
8963 (markdown-remove-inline-images)
8964 (markdown-display-inline-images)))
8967 ;;; GFM Code Block Fontification ==============================================
8969 (defcustom markdown-fontify-code-blocks-natively nil
8970 "When non-nil, fontify code in code blocks using the native major mode.
8971 This only works for fenced code blocks where the language is
8972 specified where we can automatically determine the appropriate
8973 mode to use. The language to mode mapping may be customized by
8974 setting the variable `markdown-code-lang-modes'."
8975 :group 'markdown
8976 :type 'boolean
8977 :safe 'booleanp
8978 :package-version '(markdown-mode . "2.3"))
8980 (defun markdown-toggle-fontify-code-blocks-natively (&optional arg)
8981 "Toggle the native fontification of code blocks.
8982 With a prefix argument ARG, enable if ARG is positive,
8983 and disable otherwise."
8984 (interactive (list (or current-prefix-arg 'toggle)))
8985 (setq markdown-fontify-code-blocks-natively
8986 (if (eq arg 'toggle)
8987 (not markdown-fontify-code-blocks-natively)
8988 (> (prefix-numeric-value arg) 0)))
8989 (if markdown-fontify-code-blocks-natively
8990 (message "markdown-mode native code block fontification enabled")
8991 (message "markdown-mode native code block fontification disabled"))
8992 (markdown-reload-extensions))
8994 ;; This is based on `org-src-lang-modes' from org-src.el
8995 (defcustom markdown-code-lang-modes
8996 '(("ocaml" . tuareg-mode) ("elisp" . emacs-lisp-mode) ("ditaa" . artist-mode)
8997 ("asymptote" . asy-mode) ("dot" . fundamental-mode) ("sqlite" . sql-mode)
8998 ("calc" . fundamental-mode) ("C" . c-mode) ("cpp" . c++-mode)
8999 ("C++" . c++-mode) ("screen" . shell-script-mode) ("shell" . sh-mode)
9000 ("bash" . sh-mode))
9001 "Alist mapping languages to their major mode.
9002 The key is the language name, the value is the major mode. For
9003 many languages this is simple, but for language where this is not
9004 the case, this variable provides a way to simplify things on the
9005 user side. For example, there is no ocaml-mode in Emacs, but the
9006 mode to use is `tuareg-mode'."
9007 :group 'markdown
9008 :type '(repeat
9009 (cons
9010 (string "Language name")
9011 (symbol "Major mode")))
9012 :package-version '(markdown-mode . "2.3"))
9014 (defun markdown-get-lang-mode (lang)
9015 "Return major mode that should be used for LANG.
9016 LANG is a string, and the returned major mode is a symbol."
9017 (cl-find-if
9018 'fboundp
9019 (list (cdr (assoc lang markdown-code-lang-modes))
9020 (cdr (assoc (downcase lang) markdown-code-lang-modes))
9021 (intern (concat lang "-mode"))
9022 (intern (concat (downcase lang) "-mode")))))
9024 (defun markdown-fontify-code-blocks-generic (matcher last)
9025 "Add text properties to next code block from point to LAST.
9026 Use matching function MATCHER."
9027 (when (funcall matcher last)
9028 (save-excursion
9029 (save-match-data
9030 (let* ((start (match-beginning 0))
9031 (end (match-end 0))
9032 ;; Find positions outside opening and closing backquotes.
9033 (bol-prev (progn (goto-char start)
9034 (if (bolp) (point-at-bol 0) (point-at-bol))))
9035 (eol-next (progn (goto-char end)
9036 (if (bolp) (point-at-bol 2) (point-at-bol 3))))
9037 lang)
9038 (if (and markdown-fontify-code-blocks-natively
9039 (setq lang (markdown-code-block-lang)))
9040 (markdown-fontify-code-block-natively lang start end)
9041 (add-text-properties start end '(face markdown-pre-face)))
9042 ;; Set background for block as well as opening and closing lines.
9043 (font-lock-append-text-property
9044 bol-prev eol-next 'face 'markdown-code-face)
9045 ;; Set invisible property for lines before and after, including newline.
9046 (add-text-properties bol-prev start '(invisible markdown-markup))
9047 (add-text-properties end eol-next '(invisible markdown-markup)))))
9050 (defun markdown-fontify-gfm-code-blocks (last)
9051 "Add text properties to next GFM code block from point to LAST."
9052 (markdown-fontify-code-blocks-generic 'markdown-match-gfm-code-blocks last))
9054 (defun markdown-fontify-fenced-code-blocks (last)
9055 "Add text properties to next tilde fenced code block from point to LAST."
9056 (markdown-fontify-code-blocks-generic 'markdown-match-fenced-code-blocks last))
9058 ;; Based on `org-src-font-lock-fontify-block' from org-src.el.
9059 (defun markdown-fontify-code-block-natively (lang start end)
9060 "Fontify given GFM or fenced code block.
9061 This function is called by Emacs for automatic fontification when
9062 `markdown-fontify-code-blocks-natively' is non-nil. LANG is the
9063 language used in the block. START and END specify the block
9064 position."
9065 (let ((lang-mode (markdown-get-lang-mode lang)))
9066 (when (fboundp lang-mode)
9067 (let ((string (buffer-substring-no-properties start end))
9068 (modified (buffer-modified-p))
9069 (markdown-buffer (current-buffer)) pos next)
9070 (remove-text-properties start end '(face nil))
9071 (with-current-buffer
9072 (get-buffer-create
9073 (concat " markdown-code-fontification:" (symbol-name lang-mode)))
9074 ;; Make sure that modification hooks are not inhibited in
9075 ;; the org-src-fontification buffer in case we're called
9076 ;; from `jit-lock-function' (Bug#25132).
9077 (let ((inhibit-modification-hooks nil))
9078 (delete-region (point-min) (point-max))
9079 (insert string " ")) ;; so there's a final property change
9080 (unless (eq major-mode lang-mode) (funcall lang-mode))
9081 (markdown-font-lock-ensure)
9082 (setq pos (point-min))
9083 (while (setq next (next-single-property-change pos 'face))
9084 (let ((val (get-text-property pos 'face)))
9085 (when val
9086 (put-text-property
9087 (+ start (1- pos)) (1- (+ start next)) 'face
9088 val markdown-buffer)))
9089 (setq pos next)))
9090 (add-text-properties
9091 start end
9092 '(font-lock-fontified t fontified t font-lock-multiline t))
9093 (set-buffer-modified-p modified)))))
9095 (require 'edit-indirect nil t)
9096 (defvar edit-indirect-guess-mode-function)
9097 (defvar edit-indirect-after-commit-functions)
9099 (defun markdown--edit-indirect-after-commit-function (_beg end)
9100 "Ensure trailing newlines at the END of code blocks."
9101 (goto-char end)
9102 (unless (eq (char-before) ?\n)
9103 (insert "\n")))
9105 (defun markdown-edit-code-block ()
9106 "Edit Markdown code block in an indirect buffer."
9107 (interactive)
9108 (save-excursion
9109 (if (fboundp 'edit-indirect-region)
9110 (let* ((bounds (markdown-get-enclosing-fenced-block-construct))
9111 (begin (and bounds (goto-char (nth 0 bounds)) (point-at-bol 2)))
9112 (end (and bounds (goto-char (nth 1 bounds)) (point-at-bol 1))))
9113 (if (and begin end)
9114 (let* ((lang (markdown-code-block-lang))
9115 (mode (if lang
9116 (markdown-get-lang-mode lang)
9117 markdown-edit-code-block-default-mode))
9118 (edit-indirect-guess-mode-function
9119 (lambda (_parent-buffer _beg _end)
9120 (funcall mode))))
9121 (edit-indirect-region begin end 'display-buffer))
9122 (user-error "Not inside a GFM or tilde fenced code block")))
9123 (when (y-or-n-p "Package edit-indirect needed to edit code blocks. Install it now? ")
9124 (progn (package-refresh-contents)
9125 (package-install 'edit-indirect)
9126 (markdown-edit-code-block))))))
9129 ;;; Table Editing
9131 ;; These functions were originally adapted from `org-table.el'.
9133 ;; General helper functions
9135 (defmacro markdown--with-gensyms (symbols &rest body)
9136 (declare (debug (sexp body)) (indent 1))
9137 `(let ,(mapcar (lambda (s)
9138 `(,s (make-symbol (concat "--" (symbol-name ',s)))))
9139 symbols)
9140 ,@body))
9142 (defun markdown--split-string (string &optional separators)
9143 "Splits STRING into substrings at SEPARATORS.
9144 SEPARATORS is a regular expression. If nil it defaults to
9145 `split-string-default-separators'. This version returns no empty
9146 strings if there are matches at the beginning and end of string."
9147 (let ((start 0) notfirst list)
9148 (while (and (string-match
9149 (or separators split-string-default-separators)
9150 string
9151 (if (and notfirst
9152 (= start (match-beginning 0))
9153 (< start (length string)))
9154 (1+ start) start))
9155 (< (match-beginning 0) (length string)))
9156 (setq notfirst t)
9157 (or (eq (match-beginning 0) 0)
9158 (and (eq (match-beginning 0) (match-end 0))
9159 (eq (match-beginning 0) start))
9160 (push (substring string start (match-beginning 0)) list))
9161 (setq start (match-end 0)))
9162 (or (eq start (length string))
9163 (push (substring string start) list))
9164 (nreverse list)))
9166 (defun markdown--string-width (s)
9167 "Return width of string S.
9168 This version ignores characters with invisibility property
9169 `markdown-markup'."
9170 (let (b)
9171 (when (or (eq t buffer-invisibility-spec)
9172 (member 'markdown-markup buffer-invisibility-spec))
9173 (while (setq b (text-property-any
9174 0 (length s)
9175 'invisible 'markdown-markup s))
9176 (setq s (concat
9177 (substring s 0 b)
9178 (substring s (or (next-single-property-change
9179 b 'invisible s)
9180 (length s))))))))
9181 (string-width s))
9183 (defun markdown--remove-invisible-markup (s)
9184 "Remove Markdown markup from string S.
9185 This version removes characters with invisibility property
9186 `markdown-markup'."
9187 (let (b)
9188 (while (setq b (text-property-any
9189 0 (length s)
9190 'invisible 'markdown-markup s))
9191 (setq s (concat
9192 (substring s 0 b)
9193 (substring s (or (next-single-property-change
9194 b 'invisible s)
9195 (length s)))))))
9198 ;; Functions for maintaining tables
9200 (defconst markdown-table-line-regexp "^[ \t]*|"
9201 "Regexp matching any line inside a table.")
9203 (defconst markdown-table-hline-regexp "^[ \t]*|[-:]"
9204 "Regexp matching hline inside a table.")
9206 (defconst markdown-table-dline-regexp "^[ \t]*|[^-:]"
9207 "Regexp matching dline inside a table.")
9209 (defconst markdown-table-border-regexp "^[ \t]*[^| \t]"
9210 "Regexp matching any line outside a table.")
9212 (defun markdown-table-at-point-p ()
9213 "Return non-nil when point is inside a table."
9214 (save-excursion
9215 (beginning-of-line)
9216 (and (looking-at-p markdown-table-line-regexp)
9217 (not (markdown-code-block-at-point-p)))))
9219 (defun markdown-table-hline-at-point-p ()
9220 "Return non-nil when point is on a hline in a table.
9221 This function assumes point is on a table."
9222 (save-excursion
9223 (beginning-of-line)
9224 (looking-at-p markdown-table-hline-regexp)))
9226 (defun markdown-table-begin ()
9227 "Find the beginning of the table and return its position.
9228 This function assumes point is on a table."
9229 (cond
9230 ((save-excursion
9231 (and (re-search-backward markdown-table-border-regexp nil t)
9232 (line-beginning-position 2))))
9233 (t (point-min))))
9235 (defun markdown-table-end ()
9236 "Find the end of the table and return its position.
9237 This function assumes point is on a table."
9238 (save-excursion
9239 (cond
9240 ((re-search-forward markdown-table-border-regexp nil t)
9241 (match-beginning 0))
9242 (t (goto-char (point-max))
9243 (skip-chars-backward " \t")
9244 (if (bolp) (point) (line-end-position))))))
9246 (defun markdown-table-get-dline ()
9247 "Return index of the table data line at point.
9248 This function assumes point is on a table."
9249 (let ((pos (point)) (end (markdown-table-end)) (cnt 0))
9250 (save-excursion
9251 (goto-char (markdown-table-begin))
9252 (while (and (re-search-forward
9253 markdown-table-dline-regexp end t)
9254 (setq cnt (1+ cnt))
9255 (< (point-at-eol) pos))))
9256 cnt))
9258 (defun markdown-table-get-column ()
9259 "Return table column at point.
9260 This function assumes point is on a table."
9261 (let ((pos (point)) (cnt 0))
9262 (save-excursion
9263 (beginning-of-line)
9264 (while (search-forward "|" pos t) (setq cnt (1+ cnt))))
9265 cnt))
9267 (defun markdown-table-get-cell (&optional n)
9268 "Return the content of the cell in column N of current row.
9269 N defaults to column at point. This function assumes point is on
9270 a table."
9271 (and n (markdown-table-goto-column n))
9272 (skip-chars-backward "^|\n") (backward-char 1)
9273 (if (looking-at "|[^|\r\n]*")
9274 (let* ((pos (match-beginning 0))
9275 (val (buffer-substring (1+ pos) (match-end 0))))
9276 (goto-char (min (point-at-eol) (+ 2 pos)))
9277 ;; Trim whitespaces
9278 (setq val (replace-regexp-in-string "\\`[ \t]+" "" val)
9279 val (replace-regexp-in-string "[ \t]+\\'" "" val)))
9280 (forward-char 1) ""))
9282 (defun markdown-table-goto-dline (n)
9283 "Go to the Nth data line in the table at point.
9284 Return t when the line exists, nil otherwise. This function
9285 assumes point is on a table."
9286 (goto-char (markdown-table-begin))
9287 (let ((end (markdown-table-end)) (cnt 0))
9288 (while (and (re-search-forward
9289 markdown-table-dline-regexp end t)
9290 (< (setq cnt (1+ cnt)) n)))
9291 (= cnt n)))
9293 (defun markdown-table-goto-column (n &optional on-delim)
9294 "Go to the Nth column in the table line at point.
9295 With optional argument ON-DELIM, stop with point before the left
9296 delimiter of the cell. If there are less than N cells, just go
9297 beyond the last delimiter. This function assumes point is on a
9298 table."
9299 (beginning-of-line 1)
9300 (when (> n 0)
9301 (while (and (> (setq n (1- n)) -1)
9302 (search-forward "|" (point-at-eol) t)))
9303 (if on-delim
9304 (backward-char 1)
9305 (when (looking-at " ") (forward-char 1)))))
9307 (defmacro markdown-table-save-cell (&rest body)
9308 "Save cell at point, execute BODY and restore cell.
9309 This function assumes point is on a table."
9310 (declare (debug (body)))
9311 (markdown--with-gensyms (line column)
9312 `(let ((,line (copy-marker (line-beginning-position)))
9313 (,column (markdown-table-get-column)))
9314 (unwind-protect
9315 (progn ,@body)
9316 (goto-char ,line)
9317 (markdown-table-goto-column ,column)
9318 (set-marker ,line nil)))))
9320 (defun markdown-table-blank-line (s)
9321 "Convert a table line S into a line with blank cells."
9322 (if (string-match "^[ \t]*|-" s)
9323 (setq s (mapconcat
9324 (lambda (x) (if (member x '(?| ?+)) "|" " "))
9325 s ""))
9326 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9327 (setq s (replace-match
9328 (concat "|" (make-string (length (match-string 1 s)) ?\ ) "|")
9329 t t s)))
9332 (defun markdown-table-colfmt (fmtspec)
9333 "Process column alignment specifier FMTSPEC for tables."
9334 (when (stringp fmtspec)
9335 (mapcar (lambda (x)
9336 (cond ((string-match-p "^:.*:$" x) 'c)
9337 ((string-match-p "^:" x) 'l)
9338 ((string-match-p ":$" x) 'r)
9339 (t 'd)))
9340 (markdown--split-string fmtspec "\\s-*|\\s-*"))))
9342 (defun markdown-table-align ()
9343 "Align table at point.
9344 This function assumes point is on a table."
9345 (interactive)
9346 (let ((begin (markdown-table-begin))
9347 (end (copy-marker (markdown-table-end))))
9348 (markdown-table-save-cell
9349 (goto-char begin)
9350 (let* (fmtspec
9351 ;; Store table indent
9352 (indent (progn (looking-at "[ \t]*") (match-string 0)))
9353 ;; Split table in lines and save column format specifier
9354 (lines (mapcar (lambda (l)
9355 (if (string-match-p "\\`[ \t]*|[-:]" l)
9356 (progn (setq fmtspec (or fmtspec l)) nil) l))
9357 (markdown--split-string (buffer-substring begin end) "\n")))
9358 ;; Split lines in cells
9359 (cells (mapcar (lambda (l) (markdown--split-string l "\\s-*|\\s-*"))
9360 (remq nil lines)))
9361 ;; Calculate maximum number of cells in a line
9362 (maxcells (if cells
9363 (apply #'max (mapcar #'length cells))
9364 (user-error "Empty table")))
9365 ;; Empty cells to fill short lines
9366 (emptycells (make-list maxcells "")) maxwidths)
9367 ;; Calculate maximum width for each column
9368 (dotimes (i maxcells)
9369 (let ((column (mapcar (lambda (x) (or (nth i x) "")) cells)))
9370 (push (apply #'max 1 (mapcar #'markdown--string-width column))
9371 maxwidths)))
9372 (setq maxwidths (nreverse maxwidths))
9373 ;; Process column format specifier
9374 (setq fmtspec (markdown-table-colfmt fmtspec))
9375 ;; Compute formats needed for output of table lines
9376 (let ((hfmt (concat indent "|"))
9377 (rfmt (concat indent "|"))
9378 hfmt1 rfmt1 fmt)
9379 (dolist (width maxwidths (setq hfmt (concat (substring hfmt 0 -1) "|")))
9380 (setq fmt (pop fmtspec))
9381 (cond ((equal fmt 'l) (setq hfmt1 ":%s-|" rfmt1 " %%-%ds |"))
9382 ((equal fmt 'r) (setq hfmt1 "-%s:|" rfmt1 " %%%ds |"))
9383 ((equal fmt 'c) (setq hfmt1 ":%s:|" rfmt1 " %%-%ds |"))
9384 (t (setq hfmt1 "-%s-|" rfmt1 " %%-%ds |")))
9385 (setq rfmt (concat rfmt (format rfmt1 width)))
9386 (setq hfmt (concat hfmt (format hfmt1 (make-string width ?-)))))
9387 ;; Replace modified lines only
9388 (dolist (line lines)
9389 (let ((line (if line
9390 (apply #'format rfmt (append (pop cells) emptycells))
9391 hfmt))
9392 (previous (buffer-substring (point) (line-end-position))))
9393 (if (equal previous line)
9394 (forward-line)
9395 (insert line "\n")
9396 (delete-region (point) (line-beginning-position 2))))))
9397 (set-marker end nil)))))
9399 (defun markdown-table-insert-row (&optional arg)
9400 "Insert a new row above the row at point into the table.
9401 With optional argument ARG, insert below the current row."
9402 (interactive "P")
9403 (unless (markdown-table-at-point-p)
9404 (user-error "Not at a table"))
9405 (let* ((line (buffer-substring
9406 (line-beginning-position) (line-end-position)))
9407 (new (markdown-table-blank-line line)))
9408 (beginning-of-line (if arg 2 1))
9409 (unless (bolp) (insert "\n"))
9410 (insert-before-markers new "\n")
9411 (beginning-of-line 0)
9412 (re-search-forward "| ?" (line-end-position) t)))
9414 (defun markdown-table-delete-row ()
9415 "Delete row or horizontal line at point from the table."
9416 (interactive)
9417 (unless (markdown-table-at-point-p)
9418 (user-error "Not at a table"))
9419 (let ((col (current-column)))
9420 (kill-region (point-at-bol)
9421 (min (1+ (point-at-eol)) (point-max)))
9422 (unless (markdown-table-at-point-p) (beginning-of-line 0))
9423 (move-to-column col)))
9425 (defun markdown-table-move-row (&optional up)
9426 "Move table line at point down.
9427 With optional argument UP, move it up."
9428 (interactive "P")
9429 (unless (markdown-table-at-point-p)
9430 (user-error "Not at a table"))
9431 (let* ((col (current-column)) (pos (point))
9432 (tonew (if up 0 2)) txt)
9433 (beginning-of-line tonew)
9434 (unless (markdown-table-at-point-p)
9435 (goto-char pos) (user-error "Cannot move row further"))
9436 (goto-char pos) (beginning-of-line 1) (setq pos (point))
9437 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9438 (delete-region (point) (1+ (point-at-eol)))
9439 (beginning-of-line tonew)
9440 (insert txt) (beginning-of-line 0)
9441 (move-to-column col)))
9443 (defun markdown-table-move-row-up ()
9444 "Move table row at point up."
9445 (interactive)
9446 (markdown-table-move-row 'up))
9448 (defun markdown-table-move-row-down ()
9449 "Move table row at point down."
9450 (interactive)
9451 (markdown-table-move-row nil))
9453 (defun markdown-table-insert-column ()
9454 "Insert a new table column."
9455 (interactive)
9456 (unless (markdown-table-at-point-p)
9457 (user-error "Not at a table"))
9458 (let* ((col (max 1 (markdown-table-get-column)))
9459 (begin (markdown-table-begin))
9460 (end (copy-marker (markdown-table-end))))
9461 (markdown-table-save-cell
9462 (goto-char begin)
9463 (while (< (point) end)
9464 (markdown-table-goto-column col t)
9465 (if (markdown-table-hline-at-point-p)
9466 (insert "|---")
9467 (insert "| "))
9468 (forward-line)))
9469 (set-marker end nil)
9470 (markdown-table-align)))
9472 (defun markdown-table-delete-column ()
9473 "Delete column at point from table."
9474 (interactive)
9475 (unless (markdown-table-at-point-p)
9476 (user-error "Not at a table"))
9477 (let ((col (markdown-table-get-column))
9478 (begin (markdown-table-begin))
9479 (end (copy-marker (markdown-table-end))))
9480 (markdown-table-save-cell
9481 (goto-char begin)
9482 (while (< (point) end)
9483 (markdown-table-goto-column col t)
9484 (and (looking-at "|[^|\n]+|")
9485 (replace-match "|"))
9486 (forward-line)))
9487 (set-marker end nil)
9488 (markdown-table-goto-column (max 1 (1- col)))
9489 (markdown-table-align)))
9491 (defun markdown-table-move-column (&optional left)
9492 "Move table column at point to the right.
9493 With optional argument LEFT, move it to the left."
9494 (interactive "P")
9495 (unless (markdown-table-at-point-p)
9496 (user-error "Not at a table"))
9497 (let* ((col (markdown-table-get-column))
9498 (col1 (if left (1- col) col))
9499 (colpos (if left (1- col) (1+ col)))
9500 (begin (markdown-table-begin))
9501 (end (copy-marker (markdown-table-end))))
9502 (when (and left (= col 1))
9503 (user-error "Cannot move column further left"))
9504 (when (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9505 (user-error "Cannot move column further right"))
9506 (markdown-table-save-cell
9507 (goto-char begin)
9508 (while (< (point) end)
9509 (markdown-table-goto-column col1 t)
9510 (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9511 (replace-match "|\\2|\\1|"))
9512 (forward-line)))
9513 (set-marker end nil)
9514 (markdown-table-goto-column colpos)
9515 (markdown-table-align)))
9517 (defun markdown-table-move-column-left ()
9518 "Move table column at point to the left."
9519 (interactive)
9520 (markdown-table-move-column 'left))
9522 (defun markdown-table-move-column-right ()
9523 "Move table column at point to the right."
9524 (interactive)
9525 (markdown-table-move-column nil))
9527 (defun markdown-table-next-row ()
9528 "Go to the next row (same column) in the table.
9529 Create new table lines if required."
9530 (interactive)
9531 (unless (markdown-table-at-point-p)
9532 (user-error "Not at a table"))
9533 (if (or (looking-at "[ \t]*$")
9534 (save-excursion (skip-chars-backward " \t") (bolp)))
9535 (newline)
9536 (markdown-table-align)
9537 (let ((col (markdown-table-get-column)))
9538 (beginning-of-line 2)
9539 (if (or (not (markdown-table-at-point-p))
9540 (markdown-table-hline-at-point-p))
9541 (progn
9542 (beginning-of-line 0)
9543 (markdown-table-insert-row 'below)))
9544 (markdown-table-goto-column col)
9545 (skip-chars-backward "^|\n\r")
9546 (when (looking-at " ") (forward-char 1)))))
9548 (defun markdown-table-forward-cell ()
9549 "Go to the next cell in the table.
9550 Create new table lines if required."
9551 (interactive)
9552 (unless (markdown-table-at-point-p)
9553 (user-error "Not at a table"))
9554 (markdown-table-align)
9555 (let ((end (markdown-table-end)))
9556 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9557 (condition-case nil
9558 (progn
9559 (re-search-forward "|" end)
9560 (if (looking-at "[ \t]*$")
9561 (re-search-forward "|" end))
9562 (if (and (looking-at "[-:]")
9563 (re-search-forward "^[ \t]*|\\([^-:]\\)" end t))
9564 (goto-char (match-beginning 1)))
9565 (if (looking-at "[-:]")
9566 (progn
9567 (beginning-of-line 0)
9568 (markdown-table-insert-row 'below))
9569 (when (looking-at " ") (forward-char 1))))
9570 (error (markdown-table-insert-row 'below)))))
9572 (defun markdown-table-backward-cell ()
9573 "Go to the previous cell in the table."
9574 (interactive)
9575 (unless (markdown-table-at-point-p)
9576 (user-error "Not at a table"))
9577 (markdown-table-align)
9578 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9579 (condition-case nil
9580 (progn
9581 (re-search-backward "|" (markdown-table-begin))
9582 (re-search-backward "|" (markdown-table-begin)))
9583 (error (user-error "Cannot move to previous table cell")))
9584 (while (looking-at "|\\([-:]\\|[ \t]*$\\)")
9585 (re-search-backward "|" (markdown-table-begin)))
9586 (when (looking-at "| ?") (goto-char (match-end 0))))
9588 (defun markdown-table-transpose ()
9589 "Transpose table at point.
9590 Horizontal separator lines will be eliminated."
9591 (interactive)
9592 (unless (markdown-table-at-point-p)
9593 (user-error "Not at a table"))
9594 (let* ((table (buffer-substring-no-properties
9595 (markdown-table-begin) (markdown-table-end)))
9596 ;; Convert table to a Lisp structure
9597 (table (delq nil
9598 (mapcar
9599 (lambda (x)
9600 (unless (string-match-p
9601 markdown-table-hline-regexp x)
9602 (markdown--split-string x "\\s-*|\\s-*")))
9603 (markdown--split-string table "[ \t]*\n[ \t]*"))))
9604 (dline_old (markdown-table-get-dline))
9605 (col_old (markdown-table-get-column))
9606 (contents (mapcar (lambda (_)
9607 (let ((tp table))
9608 (mapcar
9609 (lambda (_)
9610 (prog1
9611 (pop (car tp))
9612 (setq tp (cdr tp))))
9613 table)))
9614 (car table))))
9615 (goto-char (markdown-table-begin))
9616 (re-search-forward "|") (backward-char)
9617 (delete-region (point) (markdown-table-end))
9618 (insert (mapconcat
9619 (lambda(x)
9620 (concat "| " (mapconcat 'identity x " | " ) " |\n"))
9621 contents ""))
9622 (markdown-table-goto-dline col_old)
9623 (markdown-table-goto-column dline_old))
9624 (markdown-table-align))
9626 (defun markdown-table-sort-lines (&optional sorting-type)
9627 "Sort table lines according to the column at point.
9629 The position of point indicates the column to be used for
9630 sorting, and the range of lines is the range between the nearest
9631 horizontal separator lines, or the entire table of no such lines
9632 exist. If point is before the first column, user will be prompted
9633 for the sorting column. If there is an active region, the mark
9634 specifies the first line and the sorting column, while point
9635 should be in the last line to be included into the sorting.
9637 The command then prompts for the sorting type which can be
9638 alphabetically or numerically. Sorting in reverse order is also
9639 possible.
9641 If SORTING-TYPE is specified when this function is called from a
9642 Lisp program, no prompting will take place. SORTING-TYPE must be
9643 a character, any of (?a ?A ?n ?N) where the capital letters
9644 indicate that sorting should be done in reverse order."
9645 (interactive)
9646 (unless (markdown-table-at-point-p)
9647 (user-error "Not at a table"))
9648 ;; Set sorting type and column used for sorting
9649 (let ((column (let ((c (markdown-table-get-column)))
9650 (cond ((> c 0) c)
9651 ((called-interactively-p 'any)
9652 (read-number "Use column N for sorting: "))
9653 (t 1))))
9654 (sorting-type
9655 (or sorting-type
9656 (read-char-exclusive
9657 "Sort type: [a]lpha [n]umeric (A/N means reversed): "))))
9658 (save-restriction
9659 ;; Narrow buffer to appropriate sorting area
9660 (if (region-active-p)
9661 (narrow-to-region
9662 (save-excursion
9663 (progn
9664 (goto-char (region-beginning)) (line-beginning-position)))
9665 (save-excursion
9666 (progn
9667 (goto-char (region-end)) (line-end-position))))
9668 (let ((start (markdown-table-begin))
9669 (end (markdown-table-end)))
9670 (narrow-to-region
9671 (save-excursion
9672 (if (re-search-backward
9673 markdown-table-hline-regexp start t)
9674 (line-beginning-position 2)
9675 start))
9676 (if (save-excursion (re-search-forward
9677 markdown-table-hline-regexp end t))
9678 (match-beginning 0)
9679 end))))
9680 ;; Determine arguments for `sort-subr'
9681 (let* ((extract-key-from-cell
9682 (cl-case sorting-type
9683 ((?a ?A) #'markdown--remove-invisible-markup) ;; #'identity)
9684 ((?n ?N) #'string-to-number)
9685 (t (user-error "Invalid sorting type: %c" sorting-type))))
9686 (predicate
9687 (cl-case sorting-type
9688 ((?n ?N) #'<)
9689 ((?a ?A) #'string<))))
9690 ;; Sort selected area
9691 (goto-char (point-min))
9692 (sort-subr (memq sorting-type '(?A ?N))
9693 (lambda ()
9694 (forward-line)
9695 (while (and (not (eobp))
9696 (not (looking-at
9697 markdown-table-dline-regexp)))
9698 (forward-line)))
9699 #'end-of-line
9700 (lambda ()
9701 (funcall extract-key-from-cell
9702 (markdown-table-get-cell column)))
9704 predicate)
9705 (goto-char (point-min))))))
9707 (defun markdown-table-convert-region (begin end &optional separator)
9708 "Convert region from BEGIN to END to table with SEPARATOR.
9710 If every line contains at least one TAB character, the function
9711 assumes that the material is tab separated (TSV). If every line
9712 contains a comma, comma-separated values (CSV) are assumed. If
9713 not, lines are split at whitespace into cells.
9715 You can use a prefix argument to force a specific separator:
9716 \\[universal-argument] once forces CSV, \\[universal-argument]
9717 twice forces TAB, and \\[universal-argument] three times will
9718 prompt for a regular expression to match the separator, and a
9719 numeric argument N indicates that at least N consecutive
9720 spaces, or alternatively a TAB should be used as the separator."
9722 (interactive "r\nP")
9723 (let* ((begin (min begin end)) (end (max begin end)) re)
9724 (goto-char begin) (beginning-of-line 1)
9725 (setq begin (point-marker))
9726 (goto-char end)
9727 (if (bolp) (backward-char 1) (end-of-line 1))
9728 (setq end (point-marker))
9729 (when (equal separator '(64))
9730 (setq separator (read-regexp "Regexp for cell separator: ")))
9731 (unless separator
9732 ;; Get the right cell separator
9733 (goto-char begin)
9734 (setq separator
9735 (cond
9736 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
9737 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
9738 (t 1))))
9739 (goto-char begin)
9740 (if (equal separator '(4))
9741 ;; Parse CSV
9742 (while (< (point) end)
9743 (cond
9744 ((looking-at "^") (insert "| "))
9745 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
9746 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
9747 (replace-match "\\1") (if (looking-at "\"") (insert "\"")))
9748 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
9749 ((looking-at "[ \t]*,") (replace-match " | "))
9750 (t (beginning-of-line 2))))
9751 (setq re
9752 (cond
9753 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
9754 ((equal separator '(16)) "^\\|\t")
9755 ((integerp separator)
9756 (if (< separator 1)
9757 (user-error "Cell separator must contain one or more spaces")
9758 (format "^ *\\| *\t *\\| \\{%d,\\}" separator)))
9759 ((stringp separator) (format "^ *\\|%s" separator))
9760 (t (error "Invalid cell separator"))))
9761 (while (re-search-forward re end t) (replace-match "| " t t)))
9762 (goto-char begin)
9763 (markdown-table-align)))
9766 ;;; ElDoc Support
9768 (defun markdown-eldoc-function ()
9769 "Return a helpful string when appropriate based on context.
9770 * Report URL when point is at a hidden URL.
9771 * Report language name when point is a code block with hidden markup."
9772 (cond
9773 ;; Hidden URL or reference for inline link
9774 ((and (or (thing-at-point-looking-at markdown-regex-link-inline)
9775 (thing-at-point-looking-at markdown-regex-link-reference))
9776 (or markdown-hide-urls markdown-hide-markup))
9777 (let* ((imagep (string-equal (match-string 1) "!"))
9778 (edit-keys (markdown--substitute-command-keys
9779 (if imagep
9780 "\\[markdown-insert-image]"
9781 "\\[markdown-insert-link]")))
9782 (edit-str (propertize edit-keys 'face 'font-lock-constant-face))
9783 (referencep (string-equal (match-string 5) "["))
9784 (object (if referencep "reference" "URL")))
9785 (format "Hidden %s (%s to edit): %s" object edit-str
9786 (if referencep
9787 (concat
9788 (propertize "[" 'face 'markdown-markup-face)
9789 (propertize (match-string-no-properties 6)
9790 'face 'markdown-reference-face)
9791 (propertize "]" 'face 'markdown-markup-face))
9792 (propertize (match-string-no-properties 6)
9793 'face 'markdown-url-face)))))
9794 ;; Hidden language name for fenced code blocks
9795 ((and (markdown-code-block-at-point-p)
9796 (not (get-text-property (point) 'markdown-pre))
9797 markdown-hide-markup)
9798 (let ((lang (save-excursion (markdown-code-block-lang))))
9799 (unless lang (setq lang "[unspecified]"))
9800 (format "Hidden code block language: %s (%s to toggle markup)"
9801 (propertize lang 'face 'markdown-language-keyword-face)
9802 (markdown--substitute-command-keys
9803 "\\[markdown-toggle-markup-hiding]"))))))
9806 ;;; Mode Definition ==========================================================
9808 (defun markdown-show-version ()
9809 "Show the version number in the minibuffer."
9810 (interactive)
9811 (message "markdown-mode, version %s" markdown-mode-version))
9813 (defun markdown-mode-info ()
9814 "Open the `markdown-mode' homepage."
9815 (interactive)
9816 (browse-url "https://jblevins.org/projects/markdown-mode/"))
9818 ;;;###autoload
9819 (define-derived-mode markdown-mode text-mode "Markdown"
9820 "Major mode for editing Markdown files."
9821 ;; Natural Markdown tab width
9822 (setq tab-width 4)
9823 ;; Comments
9824 (setq-local comment-start "<!-- ")
9825 (setq-local comment-end " -->")
9826 (setq-local comment-start-skip "<!--[ \t]*")
9827 (setq-local comment-column 0)
9828 (setq-local comment-auto-fill-only-comments nil)
9829 (setq-local comment-use-syntax t)
9830 ;; Syntax
9831 (add-hook 'syntax-propertize-extend-region-functions
9832 #'markdown-syntax-propertize-extend-region)
9833 (add-hook 'jit-lock-after-change-extend-region-functions
9834 #'markdown-font-lock-extend-region-function t t)
9835 (setq-local syntax-propertize-function #'markdown-syntax-propertize)
9836 ;; Font lock.
9837 (setq-local font-lock-defaults nil)
9838 (setq-local font-lock-multiline t)
9839 (setq-local font-lock-extra-managed-props
9840 (append font-lock-extra-managed-props
9841 '(composition display invisible)))
9842 (if markdown-hide-markup
9843 (add-to-invisibility-spec 'markdown-markup)
9844 (remove-from-invisibility-spec 'markdown-markup))
9845 (setq font-lock-defaults
9846 '(markdown-mode-font-lock-keywords-basic
9847 nil nil nil nil
9848 (font-lock-syntactic-face-function . markdown-syntactic-face)))
9849 ;; Wiki links
9850 (markdown-setup-wiki-link-hooks)
9851 ;; Math mode
9852 (when markdown-enable-math (markdown-toggle-math t))
9853 ;; Add a buffer-local hook to reload after file-local variables are read
9854 (add-hook 'hack-local-variables-hook #'markdown-handle-local-variables nil t)
9855 ;; For imenu support
9856 (setq imenu-create-index-function
9857 (if markdown-nested-imenu-heading-index
9858 #'markdown-imenu-create-nested-index
9859 #'markdown-imenu-create-flat-index))
9860 ;; For menu support in XEmacs
9861 (easy-menu-add markdown-mode-menu markdown-mode-map)
9862 ;; Defun movement
9863 (setq-local beginning-of-defun-function #'markdown-beginning-of-defun)
9864 (setq-local end-of-defun-function #'markdown-end-of-defun)
9865 ;; Paragraph filling
9866 (setq-local fill-paragraph-function #'markdown-fill-paragraph)
9867 (setq-local paragraph-start
9868 ;; Should match start of lines that start or separate paragraphs
9869 (mapconcat #'identity
9871 "\f" ; starts with a literal line-feed
9872 "[ \t\f]*$" ; space-only line
9873 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9874 "[ \t]*[*+-][ \t]+" ; unordered list item
9875 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
9876 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
9877 "[ \t]*:[ \t]+" ; definition
9878 "^|" ; table or Pandoc line block
9880 "\\|"))
9881 (setq-local paragraph-separate
9882 ;; Should match lines that separate paragraphs without being
9883 ;; part of any paragraph:
9884 (mapconcat #'identity
9885 '("[ \t\f]*$" ; space-only line
9886 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9887 ;; The following is not ideal, but the Fill customization
9888 ;; options really only handle paragraph-starting prefixes,
9889 ;; not paragraph-ending suffixes:
9890 ".* $" ; line ending in two spaces
9891 "^#+"
9892 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
9893 "\\|"))
9894 (setq-local adaptive-fill-first-line-regexp "\\`[ \t]*[A-Z]?>[ \t]*?\\'")
9895 (setq-local adaptive-fill-regexp "\\s-*")
9896 (setq-local adaptive-fill-function #'markdown-adaptive-fill-function)
9897 (setq-local fill-forward-paragraph-function #'markdown-fill-forward-paragraph)
9898 ;; Outline mode
9899 (setq-local outline-regexp markdown-regex-header)
9900 (setq-local outline-level #'markdown-outline-level)
9901 ;; Cause use of ellipses for invisible text.
9902 (add-to-invisibility-spec '(outline . t))
9903 ;; ElDoc support
9904 (if (eval-when-compile (fboundp 'add-function))
9905 (add-function :before-until (local 'eldoc-documentation-function)
9906 #'markdown-eldoc-function)
9907 (setq-local eldoc-documentation-function #'markdown-eldoc-function))
9908 ;; Inhibiting line-breaking:
9909 ;; Separating out each condition into a separate function so that users can
9910 ;; override if desired (with remove-hook)
9911 (add-hook 'fill-nobreak-predicate
9912 #'markdown-line-is-reference-definition-p nil t)
9913 (add-hook 'fill-nobreak-predicate
9914 #'markdown-pipe-at-bol-p nil t)
9916 ;; Indentation
9917 (setq-local indent-line-function markdown-indent-function)
9919 ;; Flyspell
9920 (setq-local flyspell-generic-check-word-predicate
9921 #'markdown-flyspell-check-word-p)
9923 ;; Electric quoting
9924 (add-hook 'electric-quote-inhibit-functions
9925 #'markdown--inhibit-electric-quote nil :local)
9927 ;; Backwards compatibility with markdown-css-path
9928 (when (boundp 'markdown-css-path)
9929 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
9930 (add-to-list 'markdown-css-paths markdown-css-path))
9932 ;; Prepare hooks for XEmacs compatibility
9933 (when (featurep 'xemacs)
9934 (make-local-hook 'after-change-functions)
9935 (make-local-hook 'font-lock-extend-region-functions)
9936 (make-local-hook 'window-configuration-change-hook))
9938 ;; Make checkboxes buttons
9939 (when markdown-make-gfm-checkboxes-buttons
9940 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
9941 (add-hook 'after-change-functions #'markdown-gfm-checkbox-after-change-function t t)
9942 (add-hook 'change-major-mode-hook #'markdown-remove-gfm-checkbox-overlays t t))
9944 ;; edit-indirect
9945 (add-hook 'edit-indirect-after-commit-functions
9946 #'markdown--edit-indirect-after-commit-function
9947 nil 'local)
9949 ;; Marginalized headings
9950 (when markdown-marginalize-headers
9951 (add-hook 'window-configuration-change-hook
9952 #'markdown-marginalize-update-current nil t))
9954 ;; add live preview export hook
9955 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
9956 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
9958 ;;;###autoload
9959 (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode) t)
9960 ;;;###autoload
9961 (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode) t)
9964 ;;; GitHub Flavored Markdown Mode ============================================
9966 (defvar gfm-mode-hook nil
9967 "Hook run when entering GFM mode.")
9969 (defvar gfm-font-lock-keywords
9970 ;; Basic Markdown features (excluding possibly overridden ones)
9971 markdown-mode-font-lock-keywords-basic
9972 "Default highlighting expressions for GitHub Flavored Markdown mode.")
9974 ;;;###autoload
9975 (define-derived-mode gfm-mode markdown-mode "GFM"
9976 "Major mode for editing GitHub Flavored Markdown files."
9977 (setq markdown-link-space-sub-char "-")
9978 (setq markdown-wiki-link-search-subdirectories t)
9979 (setq-local font-lock-defaults '(gfm-font-lock-keywords))
9980 ;; do the initial link fontification
9981 (markdown-gfm-parse-buffer-for-languages))
9984 ;;; Live Preview Mode ============================================
9985 (define-minor-mode markdown-live-preview-mode
9986 "Toggle native previewing on save for a specific markdown file."
9987 :lighter " MD-Preview"
9988 (if markdown-live-preview-mode
9989 (if (markdown-live-preview-get-filename)
9990 (markdown-display-buffer-other-window (markdown-live-preview-export))
9991 (markdown-live-preview-mode -1)
9992 (user-error "Buffer %s does not visit a file" (current-buffer)))
9993 (markdown-live-preview-remove)))
9996 (provide 'markdown-mode)
9998 ;; Local Variables:
9999 ;; indent-tabs-mode: nil
10000 ;; coding: utf-8
10001 ;; End:
10002 ;;; markdown-mode.el ends here