Use markdown-table-at-point-p to detect table borders.
[markdown-mode.git] / markdown-mode.el
blob717525cdef8c86e05011a5d0dec590c37736101a
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-enable-html' - font lock for HTML tags and attributes
744 ;; (default: `t').
746 ;; * `markdown-css-paths' - CSS files to link to in XHTML output
747 ;; (default: `nil`).
749 ;; * `markdown-content-type' - when set to a nonempty string, an
750 ;; `http-equiv` attribute will be included in the XHTML `<head>`
751 ;; block (default: `""`). If needed, the suggested values are
752 ;; `application/xhtml+xml` or `text/html`. See also:
753 ;; `markdown-coding-system'.
755 ;; * `markdown-coding-system' - used for specifying the character
756 ;; set identifier in the `http-equiv` attribute when included
757 ;; (default: `nil'). See `markdown-content-type', which must
758 ;; be set before this variable has any effect. When set to `nil',
759 ;; `buffer-file-coding-system' will be used to automatically
760 ;; determine the coding system string (falling back to
761 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
762 ;; and `iso-latin-1'.
764 ;; * `markdown-xhtml-header-content' - additional content to include
765 ;; in the XHTML `<head>` block (default: `""`).
767 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
768 ;; `markdown-mode' uses to determine whether the output of
769 ;; `markdown-command' is a standalone XHTML document or an XHTML
770 ;; fragment (default: `"^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"`). If
771 ;; this regular expression not matched in the first five lines of
772 ;; output, `markdown-mode' assumes the output is a fragment and
773 ;; adds a header and footer.
775 ;; * `markdown-link-space-sub-char' - a character to replace spaces
776 ;; when mapping wiki links to filenames (default: `"_"`).
777 ;; For example, use an underscore for compatibility with the
778 ;; Python Markdown WikiLinks extension. In `gfm-mode', this is
779 ;; set to `"-"` to conform with GitHub wiki links.
781 ;; * `markdown-reference-location' - where to insert reference
782 ;; definitions (default: `header`). The possible locations are
783 ;; the end of the document (`end`), after the current block
784 ;; (`immediately`), the end of the current subtree (`subtree'),
785 ;; or before the next header (`header`).
787 ;; * `markdown-footnote-location' - where to insert footnote text
788 ;; (default: `end`). The set of location options is the same as
789 ;; for `markdown-reference-location'.
791 ;; * `markdown-nested-imenu-heading-index' - Use nested imenu
792 ;; heading instead of a flat index (default: `t'). A nested
793 ;; index may provide more natural browsing from the menu, but a
794 ;; flat list may allow for faster keyboard navigation via tab
795 ;; completion.
797 ;; * `comment-auto-fill-only-comments' - variable is made
798 ;; buffer-local and set to `nil' by default. In programming
799 ;; language modes, when this variable is non-nil, only comments
800 ;; will be filled by auto-fill-mode. However, comments in
801 ;; Markdown documents are rare and the most users probably intend
802 ;; for the actual content of the document to be filled. Making
803 ;; this variable buffer-local allows `markdown-mode' to override
804 ;; the default behavior induced when the global variable is non-nil.
806 ;; * `markdown-gfm-additional-languages', - additional languages to
807 ;; make available, aside from those predefined in
808 ;; `markdown-gfm-recognized-languages', when inserting GFM code
809 ;; blocks (default: `nil`). Language strings must have be trimmed
810 ;; of whitespace and not contain any curly braces. They may be of
811 ;; arbitrary capitalization, though.
813 ;; * `markdown-gfm-use-electric-backquote' - use
814 ;; `markdown-electric-backquote' for interactive insertion of GFM
815 ;; code blocks when backquote is pressed three times (default: `t`).
817 ;; * `markdown-make-gfm-checkboxes-buttons' - Whether GitHub
818 ;; Flavored Markdown style task lists (checkboxes) should be
819 ;; turned into buttons that can be toggled with mouse-1 or RET. If
820 ;; non-nil (default), then buttons are enabled. This works in
821 ;; `markdown-mode' as well as `gfm-mode'.
823 ;; * `markdown-hide-urls' - Determines whether URL and reference
824 ;; labels are hidden for inline and reference links (default: `nil').
825 ;; When non-nil, inline links will appear in the buffer as
826 ;; `[link](∞)` instead of
827 ;; `[link](http://perhaps.a/very/long/url/)`. To change the
828 ;; placeholder (composition) character used, set the variable
829 ;; `markdown-url-compose-char'. URL hiding can be toggled
830 ;; interactively using `C-c C-x C-l` (`markdown-toggle-url-hiding')
831 ;; or from the Markdown | Links & Images menu.
833 ;; * `markdown-hide-markup' - Determines whether all possible markup
834 ;; is hidden or otherwise beautified (default: `nil'). The actual
835 ;; buffer text remains unchanged, but the display will be altered.
836 ;; Brackets and URLs for links will be hidden, asterisks and
837 ;; underscores for italic and bold text will be hidden, text
838 ;; bullets for unordered lists will be replaced by Unicode
839 ;; bullets, and so on. Since this includes URLs and reference
840 ;; labels, when non-nil this setting supersedes `markdown-hide-urls'.
841 ;; Markup hiding can be toggled using `C-c C-x C-m`
842 ;; (`markdown-toggle-markup-hiding') or from the Markdown | Show &
843 ;; Hide menu.
845 ;; Unicode bullets are used to replace ASCII list item markers.
846 ;; The list of characters used, in order of list level, can be
847 ;; specified by setting the variable `markdown-list-item-bullets'.
848 ;; The placeholder characters used to replace other markup can
849 ;; be changed by customizing the corresponding variables:
850 ;; `markdown-blockquote-display-char',
851 ;; `markdown-hr-display-char', and
852 ;; `markdown-definition-display-char'.
854 ;; * `markdown-fontify-code-blocks-natively' - Whether to fontify
855 ;; code in code blocks using the native major mode. This only
856 ;; works for fenced code blocks where the language is specified
857 ;; where we can automatically determine the appropriate mode to
858 ;; use. The language to mode mapping may be customized by setting
859 ;; the variable `markdown-code-lang-modes'. This can be toggled
860 ;; interactively by pressing `C-c C-x C-f`
861 ;; (`markdown-toggle-fontify-code-blocks-natively').
863 ;; * `markdown-gfm-uppercase-checkbox' - When non-nil, complete GFM
864 ;; task list items with `[X]` instead of `[x]` (default: `nil').
865 ;; This is useful for compatibility with `org-mode', which doesn't
866 ;; recognize the lowercase variant.
868 ;; * `markdown-translate-filename-function' - A function to be used to
869 ;; translate filenames in links.
871 ;; Additionally, the faces used for syntax highlighting can be modified to
872 ;; your liking by issuing `M-x customize-group RET markdown-faces`
873 ;; or by using the "Markdown Faces" link at the bottom of the mode
874 ;; customization screen.
876 ;; [Marked 2]: https://itunes.apple.com/us/app/marked-2/id890031187?mt=12&uo=4&at=11l5Vs&ct=mm
878 ;;; Extensions:
880 ;; Besides supporting the basic Markdown syntax, Markdown Mode also
881 ;; includes syntax highlighting for `[[Wiki Links]]`. This can be
882 ;; enabled by setting `markdown-enable-wiki-links' to a non-nil value.
883 ;; Wiki links may be followed by pressing `C-c C-o` when the point
884 ;; is at a wiki link. Use `M-p` and `M-n` to quickly jump to the
885 ;; previous and next links (including links of other types).
886 ;; Aliased or piped wiki links of the form `[[link text|PageName]]`
887 ;; are also supported. Since some wikis reverse these components, set
888 ;; `markdown-wiki-link-alias-first' to nil to treat them as
889 ;; `[[PageName|link text]]`. If `markdown-wiki-link-fontify-missing'
890 ;; is also non-nil, Markdown Mode will highlight wiki links with
891 ;; missing target file in a different color. By default, Markdown
892 ;; Mode only searches for target files in the current directory.
893 ;; Search in subdirectories can be enabled by setting
894 ;; `markdown-wiki-link-search-subdirectories' to a non-nil value.
895 ;; Sequential parent directory search (as in [Ikiwiki][]) can be
896 ;; enabled by setting `markdown-wiki-link-search-parent-directories'
897 ;; to a non-nil value.
899 ;; [Ikiwiki]: https://ikiwiki.info
901 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
902 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
903 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
904 ;; You can do this either by using `M-x customize-group markdown`
905 ;; or by placing the following in your `.emacs` file:
907 ;; ``` Lisp
908 ;; (setq markdown-command "markdown | smartypants")
909 ;; ```
911 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
913 ;; Syntax highlighting for mathematical expressions written
914 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
915 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
916 ;; either via customize or by placing `(setq markdown-enable-math t)`
917 ;; in `.emacs`, and then restarting Emacs or calling
918 ;; `markdown-reload-extensions'.
920 ;;; GitHub Flavored Markdown (GFM):
922 ;; A [GitHub Flavored Markdown][GFM] mode, `gfm-mode', is also
923 ;; available. The GitHub implementation differs slightly from
924 ;; standard Markdown in that it supports things like different
925 ;; behavior for underscores inside of words, automatic linking of
926 ;; URLs, strikethrough text, and fenced code blocks with an optional
927 ;; language keyword.
929 ;; The GFM-specific features above apply to `README.md` files, wiki
930 ;; pages, and other Markdown-formatted files in repositories on
931 ;; GitHub. GitHub also enables [additional features][GFM comments] for
932 ;; writing on the site (for issues, pull requests, messages, etc.)
933 ;; that are further extensions of GFM. These features include task
934 ;; lists (checkboxes), newlines corresponding to hard line breaks,
935 ;; auto-linked references to issues and commits, wiki links, and so
936 ;; on. To make matters more confusing, although task lists are not
937 ;; part of [GFM proper][GFM], [since 2014][] they are rendered (in a
938 ;; read-only fashion) in all Markdown documents in repositories on the
939 ;; site. These additional extensions are supported to varying degrees
940 ;; by `markdown-mode' and `gfm-mode' as described below.
942 ;; * **URL autolinking:** Both `markdown-mode' and `gfm-mode' support
943 ;; highlighting of URLs without angle brackets.
945 ;; * **Multiple underscores in words:** You must enable `gfm-mode' to
946 ;; toggle support for underscores inside of words. In this mode
947 ;; variable names such as `a_test_variable` will not trigger
948 ;; emphasis (italics).
950 ;; * **Fenced code blocks:** Code blocks quoted with backquotes, with
951 ;; optional programming language keywords, are highlighted in
952 ;; both `markdown-mode' and `gfm-mode'. They can be inserted with
953 ;; `C-c C-s C`. If there is an active region, the text in the
954 ;; region will be placed inside the code block. You will be
955 ;; prompted for the name of the language, but may press enter to
956 ;; continue without naming a language.
958 ;; * **Strikethrough:** Strikethrough text is supported in both
959 ;; `markdown-mode' and `gfm-mode'. It can be inserted (and toggled)
960 ;; using `C-c C-s s`.
962 ;; * **Task lists:** GFM task lists will be rendered as checkboxes
963 ;; (Emacs buttons) in both `markdown-mode' and `gfm-mode' when
964 ;; `markdown-make-gfm-checkboxes-buttons' is set to a non-nil value
965 ;; (and it is set to t by default). These checkboxes can be
966 ;; toggled by clicking `mouse-1`, pressing `RET` over the button,
967 ;; or by pressing `C-c C-d` (`markdown-do`) with the point anywhere
968 ;; in the task list item. A normal list item can be turned to a
969 ;; check list item by the same command, or more specifically
970 ;; `C-c C-s [` (`markdown-insert-gfm-checkbox`).
972 ;; * **Wiki links:** Generic wiki links are supported in
973 ;; `markdown-mode', but in `gfm-mode' specifically they will be
974 ;; treated as they are on GitHub: spaces will be replaced by hyphens
975 ;; in filenames and the first letter of the filename will be
976 ;; capitalized. For example, `[[wiki link]]' will map to a file
977 ;; named `Wiki-link` with the same extension as the current file.
978 ;; If a file with this name does not exist in the current directory,
979 ;; the first match in a subdirectory, if any, will be used instead.
981 ;; * **Newlines:** Neither `markdown-mode' nor `gfm-mode' do anything
982 ;; specifically with respect to newline behavior. If you use
983 ;; `gfm-mode' mostly to write text for comments or issues on the
984 ;; GitHub site--where newlines are significant and correspond to
985 ;; hard line breaks--then you may want to enable `visual-line-mode'
986 ;; for line wrapping in buffers. You can do this with a
987 ;; `gfm-mode-hook' as follows:
989 ;; ``` Lisp
990 ;; ;; Use visual-line-mode in gfm-mode
991 ;; (defun my-gfm-mode-hook ()
992 ;; (visual-line-mode 1))
993 ;; (add-hook 'gfm-mode-hook 'my-gfm-mode-hook)
994 ;; ```
996 ;; * **Preview:** GFM-specific preview can be powered by setting
997 ;; `markdown-command' to use [Docter][]. This may also be
998 ;; configured to work with [Marked 2][] for `markdown-open-command'.
1000 ;; [GFM]: http://github.github.com/github-flavored-markdown/
1001 ;; [GFM comments]: https://help.github.com/articles/writing-on-github/
1002 ;; [since 2014]: https://github.com/blog/1825-task-lists-in-all-markdown-documents
1003 ;; [Docter]: https://github.com/alampros/Docter
1005 ;;; Acknowledgments:
1007 ;; markdown-mode has benefited greatly from the efforts of the many
1008 ;; volunteers who have sent patches, test cases, bug reports,
1009 ;; suggestions, helped with packaging, etc. Thank you for your
1010 ;; contributions! See the [contributors graph][contrib] for details.
1012 ;; [contrib]: https://github.com/jrblevin/markdown-mode/graphs/contributors
1014 ;;; Bugs:
1016 ;; markdown-mode is developed and tested primarily for compatibility
1017 ;; with GNU Emacs 24.3 and later. If you find any bugs in
1018 ;; markdown-mode, please construct a test case or a patch and open a
1019 ;; ticket on the [GitHub issue tracker][issues]. See the
1020 ;; contributing guidelines in `CONTRIBUTING.md` for details on
1021 ;; creating pull requests.
1023 ;; [issues]: https://github.com/jrblevin/markdown-mode/issues
1025 ;;; History:
1027 ;; markdown-mode was written and is maintained by Jason Blevins. The
1028 ;; first version was released on May 24, 2007.
1030 ;; * 2007-05-24: [Version 1.1][]
1031 ;; * 2007-05-25: [Version 1.2][]
1032 ;; * 2007-06-05: [Version 1.3][]
1033 ;; * 2007-06-29: [Version 1.4][]
1034 ;; * 2007-10-11: [Version 1.5][]
1035 ;; * 2008-06-04: [Version 1.6][]
1036 ;; * 2009-10-01: [Version 1.7][]
1037 ;; * 2011-08-12: [Version 1.8][]
1038 ;; * 2011-08-15: [Version 1.8.1][]
1039 ;; * 2013-01-25: [Version 1.9][]
1040 ;; * 2013-03-24: [Version 2.0][]
1041 ;; * 2016-01-09: [Version 2.1][]
1042 ;; * 2017-05-26: [Version 2.2][]
1043 ;; * 2017-08-31: [Version 2.3][]
1045 ;; [Version 1.1]: https://jblevins.org/projects/markdown-mode/rev-1-1
1046 ;; [Version 1.2]: https://jblevins.org/projects/markdown-mode/rev-1-2
1047 ;; [Version 1.3]: https://jblevins.org/projects/markdown-mode/rev-1-3
1048 ;; [Version 1.4]: https://jblevins.org/projects/markdown-mode/rev-1-4
1049 ;; [Version 1.5]: https://jblevins.org/projects/markdown-mode/rev-1-5
1050 ;; [Version 1.6]: https://jblevins.org/projects/markdown-mode/rev-1-6
1051 ;; [Version 1.7]: https://jblevins.org/projects/markdown-mode/rev-1-7
1052 ;; [Version 1.8]: https://jblevins.org/projects/markdown-mode/rev-1-8
1053 ;; [Version 1.8.1]: https://jblevins.org/projects/markdown-mode/rev-1-8-1
1054 ;; [Version 1.9]: https://jblevins.org/projects/markdown-mode/rev-1-9
1055 ;; [Version 2.0]: https://jblevins.org/projects/markdown-mode/rev-2-0
1056 ;; [Version 2.1]: https://jblevins.org/projects/markdown-mode/rev-2-1
1057 ;; [Version 2.2]: https://jblevins.org/projects/markdown-mode/rev-2-2
1058 ;; [Version 2.3]: https://jblevins.org/projects/markdown-mode/rev-2-3
1061 ;;; Code:
1063 (require 'easymenu)
1064 (require 'outline)
1065 (require 'thingatpt)
1066 (require 'cl-lib)
1067 (require 'url-parse)
1068 (require 'button)
1069 (require 'color)
1070 (require 'rx)
1072 (defvar jit-lock-start)
1073 (defvar jit-lock-end)
1074 (defvar flyspell-generic-check-word-predicate)
1076 (declare-function eww-open-file "eww")
1077 (declare-function url-path-and-query "url-parse")
1080 ;;; Constants =================================================================
1082 (defconst markdown-mode-version "2.4-dev"
1083 "Markdown mode version number.")
1085 (defconst markdown-output-buffer-name "*markdown-output*"
1086 "Name of temporary buffer for markdown command output.")
1088 (defconst markdown-sub-superscript-display
1089 '(((raise -0.3) (height 0.7)) ; subscript
1090 ((raise 0.3) (height 0.7))) ; superscript
1091 "Parameters for sub- and superscript formatting.")
1094 ;;; Global Variables ==========================================================
1096 (defvar markdown-reference-label-history nil
1097 "History of used reference labels.")
1099 (defvar markdown-live-preview-mode nil
1100 "Sentinel variable for command `markdown-live-preview-mode'.")
1102 (defvar markdown-gfm-language-history nil
1103 "History list of languages used in the current buffer in GFM code blocks.")
1106 ;;; Customizable Variables ====================================================
1108 (defvar markdown-mode-hook nil
1109 "Hook run when entering Markdown mode.")
1111 (defvar markdown-before-export-hook nil
1112 "Hook run before running Markdown to export XHTML output.
1113 The hook may modify the buffer, which will be restored to it's
1114 original state after exporting is complete.")
1116 (defvar markdown-after-export-hook nil
1117 "Hook run after XHTML output has been saved.
1118 Any changes to the output buffer made by this hook will be saved.")
1120 (defgroup markdown nil
1121 "Major mode for editing text files in Markdown format."
1122 :prefix "markdown-"
1123 :group 'wp
1124 :link '(url-link "https://jblevins.org/projects/markdown-mode/"))
1126 (defcustom markdown-command "markdown"
1127 "Command to run markdown."
1128 :group 'markdown
1129 :type '(choice (string :tag "Shell command") function))
1131 (defcustom markdown-command-needs-filename nil
1132 "Set to non-nil if `markdown-command' does not accept input from stdin.
1133 Instead, it will be passed a filename as the final command line
1134 option. As a result, you will only be able to run Markdown from
1135 buffers which are visiting a file."
1136 :group 'markdown
1137 :type 'boolean)
1139 (defcustom markdown-open-command nil
1140 "Command used for opening Markdown files directly.
1141 For example, a standalone Markdown previewer. This command will
1142 be called with a single argument: the filename of the current
1143 buffer. It can also be a function, which will be called without
1144 arguments."
1145 :group 'markdown
1146 :type '(choice file function (const :tag "None" nil)))
1148 (defcustom markdown-hr-strings
1149 '("-------------------------------------------------------------------------------"
1150 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
1151 "---------------------------------------"
1152 "* * * * * * * * * * * * * * * * * * * *"
1153 "---------"
1154 "* * * * *")
1155 "Strings to use when inserting horizontal rules.
1156 The first string in the list will be the default when inserting a
1157 horizontal rule. Strings should be listed in decreasing order of
1158 prominence (as in headings from level one to six) for use with
1159 promotion and demotion functions."
1160 :group 'markdown
1161 :type '(repeat string))
1163 (defcustom markdown-bold-underscore nil
1164 "Use two underscores when inserting bold text instead of two asterisks."
1165 :group 'markdown
1166 :type 'boolean)
1168 (defcustom markdown-italic-underscore nil
1169 "Use underscores when inserting italic text instead of asterisks."
1170 :group 'markdown
1171 :type 'boolean)
1173 (defcustom markdown-marginalize-headers nil
1174 "When non-nil, put opening atx header markup in a left margin.
1176 This setting goes well with `markdown-asymmetric-header'. But
1177 sadly it conflicts with `linum-mode' since they both use the
1178 same margin."
1179 :group 'markdown
1180 :type 'boolean
1181 :safe 'booleanp
1182 :package-version '(markdown-mode . "2.4"))
1184 (defcustom markdown-marginalize-headers-margin-width 6
1185 "Character width of margin used for marginalized headers.
1186 The default value is based on there being six heading levels
1187 defined by Markdown and HTML. Increasing this produces extra
1188 whitespace on the left. Decreasing it may be preferred when
1189 fewer than six nested heading levels are used."
1190 :group 'markdown
1191 :type 'natnump
1192 :safe 'natnump
1193 :package-version '(markdown-mode . "2.4"))
1195 (defcustom markdown-asymmetric-header nil
1196 "Determines if atx header style will be asymmetric.
1197 Set to a non-nil value to use asymmetric header styling, placing
1198 header markup only at the beginning of the line. By default,
1199 balanced markup will be inserted at the beginning and end of the
1200 line around the header title."
1201 :group 'markdown
1202 :type 'boolean)
1204 (defcustom markdown-indent-function 'markdown-indent-line
1205 "Function to use to indent."
1206 :group 'markdown
1207 :type 'function)
1209 (defcustom markdown-indent-on-enter t
1210 "Determines indentation behavior when pressing \\[newline].
1211 Possible settings are nil, t, and 'indent-and-new-item.
1213 When non-nil, pressing \\[newline] will call `newline-and-indent'
1214 to indent the following line according to the context using
1215 `markdown-indent-function'. In this case, note that
1216 \\[electric-newline-and-maybe-indent] can still be used to insert
1217 a newline without indentation.
1219 When set to 'indent-and-new-item and the point is in a list item
1220 when \\[newline] is pressed, the list will be continued on the next
1221 line, where a new item will be inserted.
1223 When set to nil, simply call `newline' as usual. In this case,
1224 you can still indent lines using \\[markdown-cycle] and continue
1225 lists with \\[markdown-insert-list-item].
1227 Note that this assumes the variable `electric-indent-mode' is
1228 non-nil (enabled). When it is *disabled*, the behavior of
1229 \\[newline] and `\\[electric-newline-and-maybe-indent]' are
1230 reversed."
1231 :group 'markdown
1232 :type '(choice (const :tag "Don't automatically indent" nil)
1233 (const :tag "Automatically indent" t)
1234 (const :tag "Automatically indent and insert new list items" indent-and-new-item)))
1236 (defcustom markdown-enable-wiki-links nil
1237 "Syntax highlighting for wiki links.
1238 Set this to a non-nil value to turn on wiki link support by default.
1239 Support can be toggled later using the `markdown-toggle-wiki-links'
1240 function or \\[markdown-toggle-wiki-links]."
1241 :group 'markdown
1242 :type 'boolean
1243 :safe 'booleanp
1244 :package-version '(markdown-mode . "2.2"))
1246 (defcustom markdown-wiki-link-alias-first t
1247 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
1248 Otherwise, they will be treated as [[PageName|alias text]]."
1249 :group 'markdown
1250 :type 'boolean
1251 :safe 'booleanp)
1253 (defcustom markdown-wiki-link-search-subdirectories nil
1254 "When non-nil, search for wiki link targets in subdirectories.
1255 This is the default search behavior for GitHub and is
1256 automatically set to t in `gfm-mode'."
1257 :group 'markdown
1258 :type 'boolean
1259 :safe 'booleanp
1260 :package-version '(markdown-mode . "2.2"))
1262 (defcustom markdown-wiki-link-search-parent-directories nil
1263 "When non-nil, search for wiki link targets in parent directories.
1264 This is the default search behavior of Ikiwiki."
1265 :group 'markdown
1266 :type 'boolean
1267 :safe 'booleanp
1268 :package-version '(markdown-mode . "2.2"))
1270 (defcustom markdown-wiki-link-fontify-missing nil
1271 "When non-nil, change wiki link face according to existence of target files.
1272 This is expensive because it requires checking for the file each time the buffer
1273 changes or the user switches windows. It is disabled by default because it may
1274 cause lag when typing on slower machines."
1275 :group 'markdown
1276 :type 'boolean
1277 :safe 'booleanp
1278 :package-version '(markdown-mode . "2.2"))
1280 (defcustom markdown-uri-types
1281 '("acap" "cid" "data" "dav" "fax" "file" "ftp"
1282 "gopher" "http" "https" "imap" "ldap" "mailto"
1283 "mid" "message" "modem" "news" "nfs" "nntp"
1284 "pop" "prospero" "rtsp" "service" "sip" "tel"
1285 "telnet" "tip" "urn" "vemmi" "wais")
1286 "Link types for syntax highlighting of URIs."
1287 :group 'markdown
1288 :type '(repeat (string :tag "URI scheme")))
1290 (defcustom markdown-url-compose-char
1291 '(?∞ ?… ?⋯ ?# ?★ ?⚓)
1292 "Placeholder character for hidden URLs.
1293 This may be a single character or a list of characters. In case
1294 of a list, the first one that satisfies `char-displayable-p' will
1295 be used."
1296 :type '(choice
1297 (character :tag "Single URL replacement character")
1298 (repeat :tag "List of possible URL replacement characters"
1299 character))
1300 :package-version '(markdown-mode . "2.3"))
1302 (defcustom markdown-blockquote-display-char
1303 '("▌" "┃" ">")
1304 "String to display when hiding blockquote markup.
1305 This may be a single string or a list of string. In case of a
1306 list, the first one that satisfies `char-displayable-p' will be
1307 used."
1308 :type 'string
1309 :type '(choice
1310 (string :tag "Single blockquote display string")
1311 (repeat :tag "List of possible blockquote display strings" string))
1312 :package-version '(markdown-mode . "2.3"))
1314 (defcustom markdown-hr-display-char
1315 '(?─ ?━ ?-)
1316 "Character for hiding horizontal rule markup.
1317 This may be a single character or a list of characters. In case
1318 of a list, the first one that satisfies `char-displayable-p' will
1319 be used."
1320 :group 'markdown
1321 :type '(choice
1322 (character :tag "Single HR display character")
1323 (repeat :tag "List of possible HR display characters" character))
1324 :package-version '(markdown-mode . "2.3"))
1326 (defcustom markdown-definition-display-char
1327 '(?⁘ ?⁙ ?≡ ?⌑ ?◊ ?:)
1328 "Character for replacing definition list markup.
1329 This may be a single character or a list of characters. In case
1330 of a list, the first one that satisfies `char-displayable-p' will
1331 be used."
1332 :type '(choice
1333 (character :tag "Single definition list character")
1334 (repeat :tag "List of possible definition list characters" character))
1335 :package-version '(markdown-mode . "2.3"))
1337 (defcustom markdown-enable-math nil
1338 "Syntax highlighting for inline LaTeX and itex expressions.
1339 Set this to a non-nil value to turn on math support by default.
1340 Math support can be enabled, disabled, or toggled later using
1341 `markdown-toggle-math' or \\[markdown-toggle-math]."
1342 :group 'markdown
1343 :type 'boolean
1344 :safe 'booleanp)
1345 (make-variable-buffer-local 'markdown-enable-math)
1347 (defcustom markdown-enable-html t
1348 "Enable font-lock support for HTML tags and attributes."
1349 :group 'markdown
1350 :type 'boolean
1351 :safe 'booleanp
1352 :package-version '(markdown-mode . "2.4"))
1354 (defcustom markdown-css-paths nil
1355 "URL of CSS file to link to in the output XHTML."
1356 :group 'markdown
1357 :type '(repeat (string :tag "CSS File Path")))
1359 (defcustom markdown-content-type ""
1360 "Content type string for the http-equiv header in XHTML output.
1361 When set to a non-empty string, insert the http-equiv attribute.
1362 Otherwise, this attribute is omitted."
1363 :group 'markdown
1364 :type 'string)
1366 (defcustom markdown-coding-system nil
1367 "Character set string for the http-equiv header in XHTML output.
1368 Defaults to `buffer-file-coding-system' (and falling back to
1369 `iso-8859-1' when not available). Common settings are `utf-8'
1370 and `iso-latin-1'. Use `list-coding-systems' for more choices."
1371 :group 'markdown
1372 :type 'coding-system)
1374 (defcustom markdown-export-kill-buffer t
1375 "Kill output buffer after HTML export.
1376 When non-nil, kill the HTML output buffer after
1377 exporting with `markdown-export'."
1378 :group 'markdown
1379 :type 'boolean
1380 :safe 'booleanp
1381 :package-version '(markdown-mode . "2.4"))
1383 (defcustom markdown-xhtml-header-content ""
1384 "Additional content to include in the XHTML <head> block."
1385 :group 'markdown
1386 :type 'string)
1388 (defcustom markdown-xhtml-standalone-regexp
1389 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
1390 "Regexp indicating whether `markdown-command' output is standalone XHTML."
1391 :group 'markdown
1392 :type 'regexp)
1394 (defcustom markdown-link-space-sub-char "_"
1395 "Character to use instead of spaces when mapping wiki links to filenames."
1396 :group 'markdown
1397 :type 'string)
1399 (defcustom markdown-reference-location 'header
1400 "Position where new reference definitions are inserted in the document."
1401 :group 'markdown
1402 :type '(choice (const :tag "At the end of the document" end)
1403 (const :tag "Immediately after the current block" immediately)
1404 (const :tag "At the end of the subtree" subtree)
1405 (const :tag "Before next header" header)))
1407 (defcustom markdown-footnote-location 'end
1408 "Position where new footnotes are inserted in the document."
1409 :group 'markdown
1410 :type '(choice (const :tag "At the end of the document" end)
1411 (const :tag "Immediately after the current block" immediately)
1412 (const :tag "At the end of the subtree" subtree)
1413 (const :tag "Before next header" header)))
1415 (defcustom markdown-unordered-list-item-prefix " * "
1416 "String inserted before unordered list items."
1417 :group 'markdown
1418 :type 'string)
1420 (defcustom markdown-nested-imenu-heading-index t
1421 "Use nested or flat imenu heading index.
1422 A nested index may provide more natural browsing from the menu,
1423 but a flat list may allow for faster keyboard navigation via tab
1424 completion."
1425 :group 'markdown
1426 :type 'boolean
1427 :safe 'booleanp
1428 :package-version '(markdown-mode . "2.2"))
1430 (defcustom markdown-make-gfm-checkboxes-buttons t
1431 "When non-nil, make GFM checkboxes into buttons."
1432 :group 'markdown
1433 :type 'boolean)
1435 (defcustom markdown-use-pandoc-style-yaml-metadata nil
1436 "When non-nil, allow YAML metadata anywhere in the document."
1437 :group 'markdown
1438 :type 'boolean)
1440 (defcustom markdown-split-window-direction 'any
1441 "Preference for splitting windows for static and live preview.
1442 The default value is 'any, which instructs Emacs to use
1443 `split-window-sensibly' to automatically choose how to split
1444 windows based on the values of `split-width-threshold' and
1445 `split-height-threshold' and the available windows. To force
1446 vertically split (left and right) windows, set this to 'vertical
1447 or 'right. To force horizontally split (top and bottom) windows,
1448 set this to 'horizontal or 'below."
1449 :group 'markdown
1450 :type '(choice (const :tag "Automatic" any)
1451 (const :tag "Right (vertical)" right)
1452 (const :tag "Below (horizontal)" below))
1453 :package-version '(markdown-mode . "2.2"))
1455 (defcustom markdown-live-preview-window-function
1456 'markdown-live-preview-window-eww
1457 "Function to display preview of Markdown output within Emacs.
1458 Function must update the buffer containing the preview and return
1459 the buffer."
1460 :group 'markdown
1461 :type 'function)
1463 (defcustom markdown-live-preview-delete-export 'delete-on-destroy
1464 "Delete exported HTML file when using `markdown-live-preview-export'.
1465 If set to 'delete-on-export, delete on every export. When set to
1466 'delete-on-destroy delete when quitting from command
1467 `markdown-live-preview-mode'. Never delete if set to nil."
1468 :group 'markdown
1469 :type '(choice
1470 (const :tag "Delete on every export" delete-on-export)
1471 (const :tag "Delete when quitting live preview" delete-on-destroy)
1472 (const :tag "Never delete" nil)))
1474 (defcustom markdown-list-indent-width 4
1475 "Depth of indentation for markdown lists.
1476 Used in `markdown-demote-list-item' and
1477 `markdown-promote-list-item'."
1478 :group 'markdown
1479 :type 'integer)
1481 (defcustom markdown-enable-prefix-prompts t
1482 "Display prompts for certain prefix commands.
1483 Set to nil to disable these prompts."
1484 :group 'markdown
1485 :type 'boolean
1486 :safe 'booleanp
1487 :package-version '(markdown-mode . "2.3"))
1489 (defcustom markdown-gfm-additional-languages nil
1490 "Extra languages made available when inserting GFM code blocks.
1491 Language strings must have be trimmed of whitespace and not
1492 contain any curly braces. They may be of arbitrary
1493 capitalization, though."
1494 :group 'markdown
1495 :type '(repeat (string :validate markdown-validate-language-string)))
1497 (defcustom markdown-gfm-use-electric-backquote t
1498 "Use `markdown-electric-backquote' when backquote is hit three times."
1499 :group 'markdown
1500 :type 'boolean)
1502 (defcustom markdown-gfm-downcase-languages t
1503 "If non-nil, downcase suggested languages.
1504 This applies to insertions done with
1505 `markdown-electric-backquote'."
1506 :group 'markdown
1507 :type 'boolean)
1509 (defcustom markdown-edit-code-block-default-mode 'normal-mode
1510 "Default mode to use for editing code blocks.
1511 This mode is used when automatic detection fails, such as for GFM
1512 code blocks with no language specified."
1513 :group 'markdown
1514 :type 'symbol
1515 :package-version '(markdown-mode . "2.4"))
1517 (defcustom markdown-gfm-uppercase-checkbox nil
1518 "If non-nil, use [X] for completed checkboxes, [x] otherwise."
1519 :group 'markdown
1520 :type 'boolean
1521 :safe 'booleanp)
1523 (defcustom markdown-hide-urls nil
1524 "Hide URLs of inline links and reference tags of reference links.
1525 Such URLs will be replaced by a single customizable
1526 character, defined by `markdown-url-compose-char', but are still part
1527 of the buffer. Links can be edited interactively with
1528 \\[markdown-insert-link] or, for example, by deleting the final
1529 parenthesis to remove the invisibility property. You can also
1530 hover your mouse pointer over the link text to see the URL.
1531 Set this to a non-nil value to turn this feature on by default.
1532 You can interactively set the value of this variable by calling
1533 `markdown-toggle-url-hiding', pressing \\[markdown-toggle-url-hiding],
1534 or from the menu Markdown > Links & Images menu."
1535 :group 'markdown
1536 :type 'boolean
1537 :safe 'booleanp
1538 :package-version '(markdown-mode . "2.3"))
1539 (make-variable-buffer-local 'markdown-hide-urls)
1541 (defcustom markdown-translate-filename-function #'identity
1542 "Function to use to translate filenames when following links.
1543 \\<markdown-mode-map>\\[markdown-follow-thing-at-point] and \\[markdown-follow-link-at-point]
1544 call this function with the filename as only argument whenever
1545 they encounter a filename (instead of a URL) to be visited and
1546 use its return value instead of the filename in the link. For
1547 example, if absolute filenames are actually relative to a server
1548 root directory, you can set
1549 `markdown-translate-filename-function' to a function that
1550 prepends the root directory to the given filename."
1551 :group 'markdown
1552 :type 'function
1553 :risky t
1554 :package-version '(markdown-mode . "2.4"))
1557 ;;; Regular Expressions =======================================================
1559 (defconst markdown-regex-comment-start
1560 "<!--"
1561 "Regular expression matches HTML comment opening.")
1563 (defconst markdown-regex-comment-end
1564 "--[ \t]*>"
1565 "Regular expression matches HTML comment closing.")
1567 (defconst markdown-regex-link-inline
1568 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)\\((\\)\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?\\()\\)"
1569 "Regular expression for a [text](file) or an image link ![text](file).
1570 Group 1 matches the leading exclamation point (optional).
1571 Group 2 matches the opening square bracket.
1572 Group 3 matches the text inside the square brackets.
1573 Group 4 matches the closing square bracket.
1574 Group 5 matches the opening parenthesis.
1575 Group 6 matches the URL.
1576 Group 7 matches the title (optional).
1577 Group 8 matches the closing parenthesis.")
1579 (defconst markdown-regex-link-reference
1580 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)[ ]?\\(\\[\\)\\([^]]*?\\)\\(\\]\\)"
1581 "Regular expression for a reference link [text][id].
1582 Group 1 matches the leading exclamation point (optional).
1583 Group 2 matches the opening square bracket for the link text.
1584 Group 3 matches the text inside the square brackets.
1585 Group 4 matches the closing square bracket for the link text.
1586 Group 5 matches the opening square bracket for the reference label.
1587 Group 6 matches the reference label.
1588 Group 7 matches the closing square bracket for the reference label.")
1590 (defconst markdown-regex-reference-definition
1591 "^ \\{0,3\\}\\(\\[\\)\\([^]\n]+?\\)\\(\\]\\)\\(:\\)\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
1592 "Regular expression for a reference definition.
1593 Group 1 matches the opening square bracket.
1594 Group 2 matches the reference label.
1595 Group 3 matches the closing square bracket.
1596 Group 4 matches the colon.
1597 Group 5 matches the URL.
1598 Group 6 matches the title attribute (optional).")
1600 (defconst markdown-regex-footnote
1601 "\\(\\[\\^\\)\\(.+?\\)\\(\\]\\)"
1602 "Regular expression for a footnote marker [^fn].
1603 Group 1 matches the opening square bracket and carat.
1604 Group 2 matches only the label, without the surrounding markup.
1605 Group 3 matches the closing square bracket.")
1607 (defconst markdown-regex-header
1608 "^\\(?:\\([^\r\n\t -].*\\)\n\\(?:\\(=+\\)\\|\\(-+\\)\\)\\|\\(#+[ \t]+\\)\\(.*?\\)\\([ \t]*#*\\)\\)$"
1609 "Regexp identifying Markdown headings.
1610 Group 1 matches the text of a setext heading.
1611 Group 2 matches the underline of a level-1 setext heading.
1612 Group 3 matches the underline of a level-2 setext heading.
1613 Group 4 matches the opening hash marks of an atx heading and whitespace.
1614 Group 5 matches the text, without surrounding whitespace, of an atx heading.
1615 Group 6 matches the closing whitespace and hash marks of an atx heading.")
1617 (defconst markdown-regex-header-setext
1618 "^\\([^\r\n\t -].*\\)\n\\(=+\\|-+\\)$"
1619 "Regular expression for generic setext-style (underline) headers.")
1621 (defconst markdown-regex-header-atx
1622 "^\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1623 "Regular expression for generic atx-style (hash mark) headers.")
1625 (defconst markdown-regex-hr
1626 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1627 "Regular expression for matching Markdown horizontal rules.")
1629 (defconst markdown-regex-code
1630 "\\(?:\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(?:.\\|\n[^\n]\\)*?[^`]\\)\\(\\2\\)\\)\\(?:[^`]\\|\\'\\)"
1631 "Regular expression for matching inline code fragments.
1633 Group 1 matches the entire code fragment including the backquotes.
1634 Group 2 matches the opening backquotes.
1635 Group 3 matches the code fragment itself, without backquotes.
1636 Group 4 matches the closing backquotes.
1638 The leading, unnumbered group ensures that the leading backquote
1639 character is not escaped.
1640 The last group, also unnumbered, requires that the character
1641 following the code fragment is not a backquote.
1642 Note that \\(?:.\\|\n[^\n]\\) matches any character, including newlines,
1643 but not two newlines in a row.")
1645 (defconst markdown-regex-kbd
1646 "\\(<kbd>\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(</kbd>\\)"
1647 "Regular expression for matching <kbd> tags.
1648 Groups 1 and 3 match the opening and closing tags.
1649 Group 2 matches the key sequence.")
1651 (defconst markdown-regex-gfm-code-block-open
1652 "^[[:blank:]]*\\(```\\)\\([[:blank:]]*{?[[:blank:]]*\\)\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$"
1653 "Regular expression matching opening of GFM code blocks.
1654 Group 1 matches the opening three backquotes and any following whitespace.
1655 Group 2 matches the opening brace (optional) and surrounding whitespace.
1656 Group 3 matches the language identifier (optional).
1657 Group 4 matches the info string (optional).
1658 Group 5 matches the closing brace (optional), whitespace, and newline.
1659 Groups need to agree with `markdown-regex-tilde-fence-begin'.")
1661 (defconst markdown-regex-gfm-code-block-close
1662 "^[[:blank:]]*\\(```\\)\\(\\s *?\\)$"
1663 "Regular expression matching closing of GFM code blocks.
1664 Group 1 matches the closing three backquotes.
1665 Group 2 matches any whitespace and the final newline.")
1667 (defconst markdown-regex-pre
1668 "^\\( \\|\t\\).*$"
1669 "Regular expression for matching preformatted text sections.")
1671 (defconst markdown-regex-list
1672 "^\\([ \t]*\\)\\([0-9#]+\\.\\|[\\*\\+:-]\\)\\([ \t]+\\)"
1673 "Regular expression for matching list items.")
1675 (defconst markdown-regex-bold
1676 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1677 "Regular expression for matching bold text.
1678 Group 1 matches the character before the opening asterisk or
1679 underscore, if any, ensuring that it is not a backslash escape.
1680 Group 2 matches the entire expression, including delimiters.
1681 Groups 3 and 5 matches the opening and closing delimiters.
1682 Group 4 matches the text inside the delimiters.")
1684 (defconst markdown-regex-italic
1685 "\\(?:^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t*]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1686 "Regular expression for matching italic text.
1687 The leading unnumbered matches the character before the opening
1688 asterisk or underscore, if any, ensuring that it is not a
1689 backslash escape.
1690 Group 1 matches the entire expression, including delimiters.
1691 Groups 2 and 4 matches the opening and closing delimiters.
1692 Group 3 matches the text inside the delimiters.")
1694 (defconst markdown-regex-strike-through
1695 "\\(^\\|[^\\]\\)\\(\\(~~\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(~~\\)\\)"
1696 "Regular expression for matching strike-through text.
1697 Group 1 matches the character before the opening tilde, if any,
1698 ensuring that it is not a backslash escape.
1699 Group 2 matches the entire expression, including delimiters.
1700 Groups 3 and 5 matches the opening and closing delimiters.
1701 Group 4 matches the text inside the delimiters.")
1703 (defconst markdown-regex-gfm-italic
1704 "\\(?:^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\2\\|[^ ]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1705 "Regular expression for matching italic text in GitHub Flavored Markdown.
1706 Underscores in words are not treated as special.
1707 Group 1 matches the entire expression, including delimiters.
1708 Groups 2 and 4 matches the opening and closing delimiters.
1709 Group 3 matches the text inside the delimiters.")
1711 (defconst markdown-regex-blockquote
1712 "^[ \t]*\\([A-Z]?>\\)\\([ \t]*\\)\\(.*\\)$"
1713 "Regular expression for matching blockquote lines.
1714 Also accounts for a potential capital letter preceding the angle
1715 bracket, for use with Leanpub blocks (asides, warnings, info
1716 blocks, etc.).
1717 Group 1 matches the leading angle bracket.
1718 Group 2 matches the separating whitespace.
1719 Group 3 matches the text.")
1721 (defconst markdown-regex-line-break
1722 "[^ \n\t][ \t]*\\( \\)$"
1723 "Regular expression for matching line breaks.")
1725 (defconst markdown-regex-wiki-link
1726 "\\(?:^\\|[^\\]\\)\\(\\(\\[\\[\\)\\([^]|]+\\)\\(?:\\(|\\)\\([^]]+\\)\\)?\\(\\]\\]\\)\\)"
1727 "Regular expression for matching wiki links.
1728 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1729 wiki links of the form [[PageName|link text]].
1730 The meanings of the first and second components depend
1731 on the value of `markdown-wiki-link-alias-first'.
1733 Group 1 matches the entire link.
1734 Group 2 matches the opening square brackets.
1735 Group 3 matches the first component of the wiki link.
1736 Group 4 matches the pipe separator, when present.
1737 Group 5 matches the second component of the wiki link, when present.
1738 Group 6 matches the closing square brackets.")
1740 (defconst markdown-regex-uri
1741 (concat "\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+\\)")
1742 "Regular expression for matching inline URIs.")
1744 (defconst markdown-regex-angle-uri
1745 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1746 "Regular expression for matching inline URIs in angle brackets.")
1748 (defconst markdown-regex-email
1749 "<\\(\\(?:\\sw\\|\\s_\\|\\s.\\)+@\\(?:\\sw\\|\\s_\\|\\s.\\)+\\)>"
1750 "Regular expression for matching inline email addresses.")
1752 (defsubst markdown-make-regex-link-generic ()
1753 "Make regular expression for matching any recognized link."
1754 (concat "\\(?:" markdown-regex-link-inline
1755 (when markdown-enable-wiki-links
1756 (concat "\\|" markdown-regex-wiki-link))
1757 "\\|" markdown-regex-link-reference
1758 "\\|" markdown-regex-angle-uri "\\)"))
1760 (defconst markdown-regex-gfm-checkbox
1761 " \\(\\[[ xX]\\]\\) "
1762 "Regular expression for matching GFM checkboxes.
1763 Group 1 matches the text to become a button.")
1765 (defconst markdown-regex-block-separator
1766 "\n[\n\t\f ]*\n"
1767 "Regular expression for matching block boundaries.")
1769 (defconst markdown-regex-block-separator-noindent
1770 (concat "\\(\\`\\|\\(" markdown-regex-block-separator "\\)[^\n\t\f ]\\)")
1771 "Regexp for block separators before lines with no indentation.")
1773 (defconst markdown-regex-math-inline-single
1774 "\\(?:^\\|[^\\]\\)\\(\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\)"
1775 "Regular expression for itex $..$ math mode expressions.
1776 Groups 1 and 3 match the opening and closing dollar signs.
1777 Group 2 matches the mathematical expression contained within.")
1779 (defconst markdown-regex-math-inline-double
1780 "\\(?:^\\|[^\\]\\)\\(\\$\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\$\\)"
1781 "Regular expression for itex $$..$$ math mode expressions.
1782 Groups 1 and 3 match opening and closing dollar signs.
1783 Group 2 matches the mathematical expression contained within.")
1785 (defconst markdown-regex-math-display
1786 (rx line-start
1787 (group (group (repeat 1 2 "\\")) "[")
1788 (group (*? anything))
1789 (group (backref 2) "]")
1790 line-end)
1791 "Regular expression for \[..\] or \\[..\\] display math.
1792 Groups 1 and 4 match the opening and closing markup.
1793 Group 3 matches the mathematical expression contained within.
1794 Group 2 matches the opening slashes, and is used internally to
1795 match the closing slashes.")
1797 (defsubst markdown-make-tilde-fence-regex (num-tildes &optional end-of-line)
1798 "Return regexp matching a tilde code fence at least NUM-TILDES long.
1799 END-OF-LINE is the regexp construct to indicate end of line; $ if
1800 missing."
1801 (format "%s%d%s%s" "^[[:blank:]]*\\([~]\\{" num-tildes ",\\}\\)"
1802 (or end-of-line "$")))
1804 (defconst markdown-regex-tilde-fence-begin
1805 (markdown-make-tilde-fence-regex
1806 3 "\\([[:blank:]]*{?\\)[[:blank:]]*\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$")
1807 "Regular expression for matching tilde-fenced code blocks.
1808 Group 1 matches the opening tildes.
1809 Group 2 matches (optional) opening brace and surrounding whitespace.
1810 Group 3 matches the language identifier (optional).
1811 Group 4 matches the info string (optional).
1812 Group 5 matches the closing brace (optional) and any surrounding whitespace.
1813 Groups need to agree with `markdown-regex-gfm-code-block-open'.")
1815 (defconst markdown-regex-declarative-metadata
1816 "^\\([[:alpha:]][[:alpha:] _-]*?\\)\\([:=][ \t]*\\)\\(.*\\)$"
1817 "Regular expression for matching declarative metadata statements.
1818 This matches MultiMarkdown metadata as well as YAML and TOML
1819 assignments such as the following:
1821 variable: value
1825 variable = value")
1827 (defconst markdown-regex-pandoc-metadata
1828 "^\\(%\\)\\([ \t]*\\)\\(.*\\(?:\n[ \t]+.*\\)*\\)"
1829 "Regular expression for matching Pandoc metadata.")
1831 (defconst markdown-regex-yaml-metadata-border
1832 "\\(-\\{3\\}\\)$"
1833 "Regular expression for matching YAML metadata.")
1835 (defconst markdown-regex-yaml-pandoc-metadata-end-border
1836 "^\\(\\.\\{3\\}\\|\\-\\{3\\}\\)$"
1837 "Regular expression for matching YAML metadata end borders.")
1839 (defsubst markdown-get-yaml-metadata-start-border ()
1840 "Return YAML metadata start border depending upon whether Pandoc is used."
1841 (concat
1842 (if markdown-use-pandoc-style-yaml-metadata "^" "\\`")
1843 markdown-regex-yaml-metadata-border))
1845 (defsubst markdown-get-yaml-metadata-end-border (_)
1846 "Return YAML metadata end border depending upon whether Pandoc is used."
1847 (if markdown-use-pandoc-style-yaml-metadata
1848 markdown-regex-yaml-pandoc-metadata-end-border
1849 markdown-regex-yaml-metadata-border))
1851 (defconst markdown-regex-inline-attributes
1852 "[ \t]*\\({:?\\)[ \t]*\\(\\(#[[:alpha:]_.:-]+\\|\\.[[:alpha:]_.:-]+\\|\\w+=['\"]?[^\n'\"]*['\"]?\\),?[ \t]*\\)+\\(}\\)[ \t]*$"
1853 "Regular expression for matching inline identifiers or attribute lists.
1854 Compatible with Pandoc, Python Markdown, PHP Markdown Extra, and Leanpub.")
1856 (defconst markdown-regex-leanpub-sections
1857 (concat
1858 "^\\({\\)\\("
1859 (regexp-opt '("frontmatter" "mainmatter" "backmatter" "appendix" "pagebreak"))
1860 "\\)\\(}\\)[ \t]*\n")
1861 "Regular expression for Leanpub section markers and related syntax.")
1863 (defconst markdown-regex-sub-superscript
1864 "\\(?:^\\|[^\\~^]\\)\\(\\([~^]\\)\\([[:alnum:]]+\\)\\(\\2\\)\\)"
1865 "The regular expression matching a sub- or superscript.
1866 The leading un-numbered group matches the character before the
1867 opening tilde or carat, if any, ensuring that it is not a
1868 backslash escape, carat, or tilde.
1869 Group 1 matches the entire expression, including markup.
1870 Group 2 matches the opening markup--a tilde or carat.
1871 Group 3 matches the text inside the delimiters.
1872 Group 4 matches the closing markup--a tilde or carat.")
1874 (defconst markdown-regex-include
1875 "^\\(<<\\)\\(?:\\(\\[\\)\\(.*\\)\\(\\]\\)\\)?\\(?:\\((\\)\\(.*\\)\\()\\)\\)?\\(?:\\({\\)\\(.*\\)\\(}\\)\\)?$"
1876 "Regular expression matching common forms of include syntax.
1877 Marked 2, Leanpub, and other processors support some of these forms:
1879 <<[sections/section1.md]
1880 <<(folder/filename)
1881 <<[Code title](folder/filename)
1882 <<{folder/raw_file.html}
1884 Group 1 matches the opening two angle brackets.
1885 Groups 2-4 match the opening square bracket, the text inside,
1886 and the closing square bracket, respectively.
1887 Groups 5-7 match the opening parenthesis, the text inside, and
1888 the closing parenthesis.
1889 Groups 8-10 match the opening brace, the text inside, and the brace.")
1891 (defconst markdown-regex-pandoc-inline-footnote
1892 "\\(\\^\\)\\(\\[\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(\\]\\)"
1893 "Regular expression for Pandoc inline footnote^[footnote text].
1894 Group 1 matches the opening caret.
1895 Group 2 matches the opening square bracket.
1896 Group 3 matches the footnote text, without the surrounding markup.
1897 Group 4 matches the closing square bracket.")
1899 (defconst markdown-regex-html-attr
1900 "\\(\\<[[:alpha:]:-]+\\>\\)\\(\\s-*\\(=\\)\\s-*\\(\".*?\"\\|'.*?'\\|[^'\">[:space:]]+\\)?\\)?"
1901 "Regular expression for matching HTML attributes and values.
1902 Group 1 matches the attribute name.
1903 Group 2 matches the following whitespace, equals sign, and value, if any.
1904 Group 3 matches the equals sign, if any.
1905 Group 4 matches single-, double-, or un-quoted attribute values.")
1907 (defconst markdown-regex-html-tag
1908 (concat "\\(</?\\)\\(\\w+\\)\\(\\(\\s-+" markdown-regex-html-attr
1909 "\\)+\\s-*\\|\\s-*\\)\\(/?>\\)")
1910 "Regular expression for matching HTML tags.
1911 Groups 1 and 9 match the beginning and ending angle brackets and slashes.
1912 Group 2 matches the tag name.
1913 Group 3 matches all attributes and whitespace following the tag name.")
1915 (defconst markdown-regex-html-entity
1916 "\\(&#?[[:alnum:]]+;\\)"
1917 "Regular expression for matching HTML entities.")
1920 ;;; Syntax ====================================================================
1922 (defsubst markdown-in-comment-p (&optional pos)
1923 "Return non-nil if POS is in a comment.
1924 If POS is not given, use point instead."
1925 (nth 4 (syntax-ppss pos)))
1927 (defun markdown-syntax-propertize-extend-region (start end)
1928 "Extend START to END region to include an entire block of text.
1929 This helps improve syntax analysis for block constructs.
1930 Returns a cons (NEW-START . NEW-END) or nil if no adjustment should be made.
1931 Function is called repeatedly until it returns nil. For details, see
1932 `syntax-propertize-extend-region-functions'."
1933 (save-match-data
1934 (save-excursion
1935 (let* ((new-start (progn (goto-char start)
1936 (skip-chars-forward "\n")
1937 (if (re-search-backward "\n\n" nil t)
1938 (min start (match-end 0))
1939 (point-min))))
1940 (new-end (progn (goto-char end)
1941 (skip-chars-backward "\n")
1942 (if (re-search-forward "\n\n" nil t)
1943 (max end (match-beginning 0))
1944 (point-max))))
1945 (code-match (markdown-code-block-at-pos new-start))
1946 (new-start (or (and code-match (cl-first code-match)) new-start))
1947 (code-match (and (< end (point-max)) (markdown-code-block-at-pos end)))
1948 (new-end (or (and code-match (cl-second code-match)) new-end)))
1949 (unless (and (eq new-start start) (eq new-end end))
1950 (cons new-start (min new-end (point-max))))))))
1952 (defun markdown-font-lock-extend-region-function (start end _)
1953 "Used in `jit-lock-after-change-extend-region-functions'.
1954 Delegates to `markdown-syntax-propertize-extend-region'. START
1955 and END are the previous region to refontify."
1956 (let ((res (markdown-syntax-propertize-extend-region start end)))
1957 (when res
1958 ;; syntax-propertize-function is not called when character at
1959 ;; (point-max) is deleted, but font-lock-extend-region-functions
1960 ;; are called. Force a syntax property update in that case.
1961 (when (= end (point-max))
1962 ;; This function is called in a buffer modification hook.
1963 ;; `markdown-syntax-propertize' doesn't save the match data,
1964 ;; so we have to do it here.
1965 (save-match-data
1966 (markdown-syntax-propertize (car res) (cdr res))))
1967 (setq jit-lock-start (car res)
1968 jit-lock-end (cdr res)))))
1970 (defun markdown-syntax-propertize-pre-blocks (start end)
1971 "Match preformatted text blocks from START to END."
1972 (save-excursion
1973 (goto-char start)
1974 (let ((levels (markdown-calculate-list-levels))
1975 indent pre-regexp close-regexp open close)
1976 (while (and (< (point) end) (not close))
1977 ;; Search for a region with sufficient indentation
1978 (if (null levels)
1979 (setq indent 1)
1980 (setq indent (1+ (length levels))))
1981 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1982 (setq close-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1984 (cond
1985 ;; If not at the beginning of a line, move forward
1986 ((not (bolp)) (forward-line))
1987 ;; Move past blank lines
1988 ((markdown-cur-line-blank) (forward-line))
1989 ;; At headers and horizontal rules, reset levels
1990 ((markdown-new-baseline) (forward-line) (setq levels nil))
1991 ;; If the current line has sufficient indentation, mark out pre block
1992 ;; The opening should be preceded by a blank line.
1993 ((and (looking-at pre-regexp)
1994 (markdown-prev-line-blank-p))
1995 (setq open (match-beginning 0))
1996 (while (and (or (looking-at-p pre-regexp) (markdown-cur-line-blank))
1997 (not (eobp)))
1998 (forward-line))
1999 (skip-syntax-backward "-")
2000 (setq close (point)))
2001 ;; If current line has a list marker, update levels, move to end of block
2002 ((looking-at markdown-regex-list)
2003 (setq levels (markdown-update-list-levels
2004 (match-string 2) (current-indentation) levels))
2005 (markdown-end-of-text-block))
2006 ;; If this is the end of the indentation level, adjust levels accordingly.
2007 ;; Only match end of indentation level if levels is not the empty list.
2008 ((and (car levels) (looking-at-p close-regexp))
2009 (setq levels (markdown-update-list-levels
2010 nil (current-indentation) levels))
2011 (markdown-end-of-text-block))
2012 (t (markdown-end-of-text-block))))
2014 (when (and open close)
2015 ;; Set text property data
2016 (put-text-property open close 'markdown-pre (list open close))
2017 ;; Recursively search again
2018 (markdown-syntax-propertize-pre-blocks (point) end)))))
2020 (defconst markdown-fenced-block-pairs
2021 `(((,markdown-regex-tilde-fence-begin markdown-tilde-fence-begin)
2022 (markdown-make-tilde-fence-regex markdown-tilde-fence-end)
2023 markdown-fenced-code)
2024 ((markdown-get-yaml-metadata-start-border markdown-yaml-metadata-begin)
2025 (markdown-get-yaml-metadata-end-border markdown-yaml-metadata-end)
2026 markdown-yaml-metadata-section)
2027 ((,markdown-regex-gfm-code-block-open markdown-gfm-block-begin)
2028 (,markdown-regex-gfm-code-block-close markdown-gfm-block-end)
2029 markdown-gfm-code))
2030 "Mapping of regular expressions to \"fenced-block\" constructs.
2031 These constructs are distinguished by having a distinctive start
2032 and end pattern, both of which take up an entire line of text,
2033 but no special pattern to identify text within the fenced
2034 blocks (unlike blockquotes and indented-code sections).
2036 Each element within this list takes the form:
2038 ((START-REGEX-OR-FUN START-PROPERTY)
2039 (END-REGEX-OR-FUN END-PROPERTY)
2040 MIDDLE-PROPERTY)
2042 Each *-REGEX-OR-FUN element can be a regular expression as a string, or a
2043 function which evaluates to same. Functions for START-REGEX-OR-FUN accept no
2044 arguments, but functions for END-REGEX-OR-FUN accept a single numerical argument
2045 which is the length of the first group of the START-REGEX-OR-FUN match, which
2046 can be ignored if unnecessary. `markdown-maybe-funcall-regexp' is used to
2047 evaluate these into \"real\" regexps.
2049 The *-PROPERTY elements are the text properties applied to each part of the
2050 block construct when it is matched using
2051 `markdown-syntax-propertize-fenced-block-constructs'. START-PROPERTY is applied
2052 to the text matching START-REGEX-OR-FUN, END-PROPERTY to END-REGEX-OR-FUN, and
2053 MIDDLE-PROPERTY to the text in between the two. The value of *-PROPERTY is the
2054 `match-data' when the regexp was matched to the text. In the case of
2055 MIDDLE-PROPERTY, the value is a false match data of the form '(begin end), with
2056 begin and end set to the edges of the \"middle\" text. This makes fontification
2057 easier.")
2059 (defun markdown-text-property-at-point (prop)
2060 (get-text-property (point) prop))
2062 (defsubst markdown-maybe-funcall-regexp (object &optional arg)
2063 (cond ((functionp object)
2064 (if arg (funcall object arg) (funcall object)))
2065 ((stringp object) object)
2066 (t (error "Object cannot be turned into regex"))))
2068 (defsubst markdown-get-start-fence-regexp ()
2069 "Return regexp to find all \"start\" sections of fenced block constructs.
2070 Which construct is actually contained in the match must be found separately."
2071 (mapconcat
2072 #'identity
2073 (mapcar (lambda (entry) (markdown-maybe-funcall-regexp (caar entry)))
2074 markdown-fenced-block-pairs)
2075 "\\|"))
2077 (defun markdown-get-fenced-block-begin-properties ()
2078 (cl-mapcar (lambda (entry) (cl-cadar entry)) markdown-fenced-block-pairs))
2080 (defun markdown-get-fenced-block-end-properties ()
2081 (cl-mapcar (lambda (entry) (cl-cadadr entry)) markdown-fenced-block-pairs))
2083 (defun markdown-get-fenced-block-middle-properties ()
2084 (cl-mapcar #'cl-third markdown-fenced-block-pairs))
2086 (defun markdown-find-previous-prop (prop &optional lim)
2087 "Find previous place where property PROP is non-nil, up to LIM.
2088 Return a cons of (pos . property). pos is point if point contains
2089 non-nil PROP."
2090 (let ((res
2091 (if (get-text-property (point) prop) (point)
2092 (previous-single-property-change
2093 (point) prop nil (or lim (point-min))))))
2094 (when (and (not (get-text-property res prop))
2095 (> res (point-min))
2096 (get-text-property (1- res) prop))
2097 (cl-decf res))
2098 (when (and res (get-text-property res prop)) (cons res prop))))
2100 (defun markdown-find-next-prop (prop &optional lim)
2101 "Find next place where property PROP is non-nil, up to LIM.
2102 Return a cons of (POS . PROPERTY) where POS is point if point
2103 contains non-nil PROP."
2104 (let ((res
2105 (if (get-text-property (point) prop) (point)
2106 (next-single-property-change
2107 (point) prop nil (or lim (point-max))))))
2108 (when (and res (get-text-property res prop)) (cons res prop))))
2110 (defun markdown-min-of-seq (map-fn seq)
2111 "Apply MAP-FN to SEQ and return element of SEQ with minimum value of MAP-FN."
2112 (cl-loop for el in seq
2113 with min = 1.0e+INF ; infinity
2114 with min-el = nil
2115 do (let ((res (funcall map-fn el)))
2116 (when (< res min)
2117 (setq min res)
2118 (setq min-el el)))
2119 finally return min-el))
2121 (defun markdown-max-of-seq (map-fn seq)
2122 "Apply MAP-FN to SEQ and return element of SEQ with maximum value of MAP-FN."
2123 (cl-loop for el in seq
2124 with max = -1.0e+INF ; negative infinity
2125 with max-el = nil
2126 do (let ((res (funcall map-fn el)))
2127 (when (and res (> res max))
2128 (setq max res)
2129 (setq max-el el)))
2130 finally return max-el))
2132 (defun markdown-find-previous-block ()
2133 "Find previous block.
2134 Detect whether `markdown-syntax-propertize-fenced-block-constructs' was
2135 unable to propertize the entire block, but was able to propertize the beginning
2136 of the block. If so, return a cons of (pos . property) where the beginning of
2137 the block was propertized."
2138 (let ((start-pt (point))
2139 (closest-open
2140 (markdown-max-of-seq
2141 #'car
2142 (cl-remove-if
2143 #'null
2144 (cl-mapcar
2145 #'markdown-find-previous-prop
2146 (markdown-get-fenced-block-begin-properties))))))
2147 (when closest-open
2148 (let* ((length-of-open-match
2149 (let ((match-d
2150 (get-text-property (car closest-open) (cdr closest-open))))
2151 (- (cl-fourth match-d) (cl-third match-d))))
2152 (end-regexp
2153 (markdown-maybe-funcall-regexp
2154 (cl-caadr
2155 (cl-find-if
2156 (lambda (entry) (eq (cl-cadar entry) (cdr closest-open)))
2157 markdown-fenced-block-pairs))
2158 length-of-open-match))
2159 (end-prop-loc
2160 (save-excursion
2161 (save-match-data
2162 (goto-char (car closest-open))
2163 (and (re-search-forward end-regexp start-pt t)
2164 (match-beginning 0))))))
2165 (and (not end-prop-loc) closest-open)))))
2167 (defun markdown-get-fenced-block-from-start (prop)
2168 "Return limits of an enclosing fenced block from its start, using PROP.
2169 Return value is a list usable as `match-data'."
2170 (catch 'no-rest-of-block
2171 (let* ((correct-entry
2172 (cl-find-if
2173 (lambda (entry) (eq (cl-cadar entry) prop))
2174 markdown-fenced-block-pairs))
2175 (begin-of-begin (cl-first (markdown-text-property-at-point prop)))
2176 (middle-prop (cl-third correct-entry))
2177 (end-prop (cl-cadadr correct-entry))
2178 (end-of-end
2179 (save-excursion
2180 (goto-char (match-end 0)) ; end of begin
2181 (unless (eobp) (forward-char))
2182 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
2183 (if (not mid-prop-v) ; no middle
2184 (progn
2185 ;; try to find end by advancing one
2186 (let ((end-prop-v
2187 (markdown-text-property-at-point end-prop)))
2188 (if end-prop-v (cl-second end-prop-v)
2189 (throw 'no-rest-of-block nil))))
2190 (set-match-data mid-prop-v)
2191 (goto-char (match-end 0)) ; end of middle
2192 (beginning-of-line) ; into end
2193 (cl-second (markdown-text-property-at-point end-prop)))))))
2194 (list begin-of-begin end-of-end))))
2196 (defun markdown-get-fenced-block-from-middle (prop)
2197 "Return limits of an enclosing fenced block from its middle, using PROP.
2198 Return value is a list usable as `match-data'."
2199 (let* ((correct-entry
2200 (cl-find-if
2201 (lambda (entry) (eq (cl-third entry) prop))
2202 markdown-fenced-block-pairs))
2203 (begin-prop (cl-cadar correct-entry))
2204 (begin-of-begin
2205 (save-excursion
2206 (goto-char (match-beginning 0))
2207 (unless (bobp) (forward-line -1))
2208 (beginning-of-line)
2209 (cl-first (markdown-text-property-at-point begin-prop))))
2210 (end-prop (cl-cadadr correct-entry))
2211 (end-of-end
2212 (save-excursion
2213 (goto-char (match-end 0))
2214 (beginning-of-line)
2215 (cl-second (markdown-text-property-at-point end-prop)))))
2216 (list begin-of-begin end-of-end)))
2218 (defun markdown-get-fenced-block-from-end (prop)
2219 "Return limits of an enclosing fenced block from its end, using PROP.
2220 Return value is a list usable as `match-data'."
2221 (let* ((correct-entry
2222 (cl-find-if
2223 (lambda (entry) (eq (cl-cadadr entry) prop))
2224 markdown-fenced-block-pairs))
2225 (end-of-end (cl-second (markdown-text-property-at-point prop)))
2226 (middle-prop (cl-third correct-entry))
2227 (begin-prop (cl-cadar correct-entry))
2228 (begin-of-begin
2229 (save-excursion
2230 (goto-char (match-beginning 0)) ; beginning of end
2231 (unless (bobp) (backward-char)) ; into middle
2232 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
2233 (if (not mid-prop-v)
2234 (progn
2235 (beginning-of-line)
2236 (cl-first (markdown-text-property-at-point begin-prop)))
2237 (set-match-data mid-prop-v)
2238 (goto-char (match-beginning 0)) ; beginning of middle
2239 (unless (bobp) (forward-line -1)) ; into beginning
2240 (beginning-of-line)
2241 (cl-first (markdown-text-property-at-point begin-prop)))))))
2242 (list begin-of-begin end-of-end)))
2244 (defun markdown-get-enclosing-fenced-block-construct (&optional pos)
2245 "Get \"fake\" match data for block enclosing POS.
2246 Returns fake match data which encloses the start, middle, and end
2247 of the block construct enclosing POS, if it exists. Used in
2248 `markdown-code-block-at-pos'."
2249 (save-excursion
2250 (when pos (goto-char pos))
2251 (beginning-of-line)
2252 (car
2253 (cl-remove-if
2254 #'null
2255 (cl-mapcar
2256 (lambda (fun-and-prop)
2257 (cl-destructuring-bind (fun prop) fun-and-prop
2258 (when prop
2259 (save-match-data
2260 (set-match-data (markdown-text-property-at-point prop))
2261 (funcall fun prop)))))
2262 `((markdown-get-fenced-block-from-start
2263 ,(cl-find-if
2264 #'markdown-text-property-at-point
2265 (markdown-get-fenced-block-begin-properties)))
2266 (markdown-get-fenced-block-from-middle
2267 ,(cl-find-if
2268 #'markdown-text-property-at-point
2269 (markdown-get-fenced-block-middle-properties)))
2270 (markdown-get-fenced-block-from-end
2271 ,(cl-find-if
2272 #'markdown-text-property-at-point
2273 (markdown-get-fenced-block-end-properties)))))))))
2275 (defun markdown-propertize-end-match (reg end fence-spec middle-begin)
2276 "Get match for REG up to END, if exists, and propertize appropriately.
2277 FENCE-SPEC is an entry in `markdown-fenced-block-pairs' and
2278 MIDDLE-BEGIN is the start of the \"middle\" section of the block."
2279 (when (re-search-forward reg end t)
2280 (let ((close-begin (match-beginning 0)) ; Start of closing line.
2281 (close-end (match-end 0)) ; End of closing line.
2282 (close-data (match-data t))) ; Match data for closing line.
2283 ;; Propertize middle section of fenced block.
2284 (put-text-property middle-begin close-begin
2285 (cl-third fence-spec)
2286 (list middle-begin close-begin))
2287 ;; Propertize closing line of fenced block.
2288 (put-text-property close-begin close-end
2289 (cl-cadadr fence-spec) close-data))))
2291 (defun markdown-syntax-propertize-fenced-block-constructs (start end)
2292 "Propertize according to `markdown-fenced-block-pairs' from START to END.
2293 If unable to propertize an entire block (if the start of a block is within START
2294 and END, but the end of the block is not), propertize the start section of a
2295 block, then in a subsequent call propertize both middle and end by finding the
2296 start which was previously propertized."
2297 (let ((start-reg (markdown-get-start-fence-regexp)))
2298 (save-excursion
2299 (goto-char start)
2300 ;; start from previous unclosed block, if exists
2301 (let ((prev-begin-block (markdown-find-previous-block)))
2302 (when prev-begin-block
2303 (let* ((correct-entry
2304 (cl-find-if (lambda (entry)
2305 (eq (cdr prev-begin-block) (cl-cadar entry)))
2306 markdown-fenced-block-pairs))
2307 (enclosed-text-start (1+ (car prev-begin-block)))
2308 (start-length
2309 (save-excursion
2310 (goto-char (car prev-begin-block))
2311 (string-match
2312 (markdown-maybe-funcall-regexp
2313 (caar correct-entry))
2314 (buffer-substring
2315 (point-at-bol) (point-at-eol)))
2316 (- (match-end 1) (match-beginning 1))))
2317 (end-reg (markdown-maybe-funcall-regexp
2318 (cl-caadr correct-entry) start-length)))
2319 (markdown-propertize-end-match
2320 end-reg end correct-entry enclosed-text-start))))
2321 ;; find all new blocks within region
2322 (while (re-search-forward start-reg end t)
2323 ;; we assume the opening constructs take up (only) an entire line,
2324 ;; so we re-check the current line
2325 (let* ((cur-line (buffer-substring (point-at-bol) (point-at-eol)))
2326 ;; find entry in `markdown-fenced-block-pairs' corresponding
2327 ;; to regex which was matched
2328 (correct-entry
2329 (cl-find-if
2330 (lambda (fenced-pair)
2331 (string-match-p
2332 (markdown-maybe-funcall-regexp (caar fenced-pair))
2333 cur-line))
2334 markdown-fenced-block-pairs))
2335 (enclosed-text-start
2336 (save-excursion (1+ (point-at-eol))))
2337 (end-reg
2338 (markdown-maybe-funcall-regexp
2339 (cl-caadr correct-entry)
2340 (if (and (match-beginning 1) (match-end 1))
2341 (- (match-end 1) (match-beginning 1))
2342 0))))
2343 ;; get correct match data
2344 (save-excursion
2345 (beginning-of-line)
2346 (re-search-forward
2347 (markdown-maybe-funcall-regexp (caar correct-entry))
2348 (point-at-eol)))
2349 ;; mark starting, even if ending is outside of region
2350 (put-text-property (match-beginning 0) (match-end 0)
2351 (cl-cadar correct-entry) (match-data t))
2352 (markdown-propertize-end-match
2353 end-reg end correct-entry enclosed-text-start))))))
2355 (defun markdown-syntax-propertize-blockquotes (start end)
2356 "Match blockquotes from START to END."
2357 (save-excursion
2358 (goto-char start)
2359 (while (and (re-search-forward markdown-regex-blockquote end t)
2360 (not (markdown-code-block-at-pos (match-beginning 0))))
2361 (put-text-property (match-beginning 0) (match-end 0)
2362 'markdown-blockquote
2363 (match-data t)))))
2365 (defun markdown-syntax-propertize-hrs (start end)
2366 "Match horizontal rules from START to END."
2367 (save-excursion
2368 (goto-char start)
2369 (while (re-search-forward markdown-regex-hr end t)
2370 (unless (or (markdown-on-heading-p)
2371 (markdown-code-block-at-point-p))
2372 (put-text-property (match-beginning 0) (match-end 0)
2373 'markdown-hr
2374 (match-data t))))))
2376 (defun markdown-syntax-propertize-yaml-metadata (start end)
2377 (save-excursion
2378 (goto-char start)
2379 (cl-loop
2380 while (re-search-forward markdown-regex-declarative-metadata end t)
2381 do (when (get-text-property (match-beginning 0)
2382 'markdown-yaml-metadata-section)
2383 (put-text-property (match-beginning 1) (match-end 1)
2384 'markdown-metadata-key (match-data t))
2385 (put-text-property (match-beginning 2) (match-end 2)
2386 'markdown-metadata-markup (match-data t))
2387 (put-text-property (match-beginning 3) (match-end 3)
2388 'markdown-metadata-value (match-data t))))))
2390 (defun markdown-syntax-propertize-headings (start end)
2391 "Match headings of type SYMBOL with REGEX from START to END."
2392 (goto-char start)
2393 (while (re-search-forward markdown-regex-header end t)
2394 (unless (markdown-code-block-at-pos (match-beginning 0))
2395 (put-text-property
2396 (match-beginning 0) (match-end 0) 'markdown-heading
2397 (match-data t))
2398 (put-text-property
2399 (match-beginning 0) (match-end 0)
2400 (cond ((match-string-no-properties 2) 'markdown-heading-1-setext)
2401 ((match-string-no-properties 3) 'markdown-heading-2-setext)
2402 (t (let ((atx-level (length (markdown-trim-whitespace
2403 (match-string-no-properties 4)))))
2404 (intern (format "markdown-heading-%d-atx" atx-level)))))
2405 (match-data t)))))
2407 (defun markdown-syntax-propertize-comments (start end)
2408 "Match HTML comments from the START to END."
2409 (let* ((in-comment (markdown-in-comment-p)))
2410 (goto-char start)
2411 (cond
2412 ;; Comment start
2413 ((and (not in-comment)
2414 (re-search-forward markdown-regex-comment-start end t)
2415 (not (markdown-inline-code-at-point-p))
2416 (not (markdown-code-block-at-point-p)))
2417 (let ((open-beg (match-beginning 0)))
2418 (put-text-property open-beg (1+ open-beg)
2419 'syntax-table (string-to-syntax "<"))
2420 (markdown-syntax-propertize-comments
2421 (min (1+ (match-end 0)) end (point-max)) end)))
2422 ;; Comment end
2423 ((and in-comment
2424 (re-search-forward markdown-regex-comment-end end t))
2425 (put-text-property (1- (match-end 0)) (match-end 0)
2426 'syntax-table (string-to-syntax ">"))
2427 (markdown-syntax-propertize-comments
2428 (min (1+ (match-end 0)) end (point-max)) end))
2429 ;; Nothing found
2430 (t nil))))
2432 (defvar markdown--syntax-properties
2433 (list 'markdown-tilde-fence-begin nil
2434 'markdown-tilde-fence-end nil
2435 'markdown-fenced-code nil
2436 'markdown-yaml-metadata-begin nil
2437 'markdown-yaml-metadata-end nil
2438 'markdown-yaml-metadata-section nil
2439 'markdown-gfm-block-begin nil
2440 'markdown-gfm-block-end nil
2441 'markdown-gfm-code nil
2442 'markdown-pre nil
2443 'markdown-blockquote nil
2444 'markdown-hr nil
2445 'markdown-heading nil
2446 'markdown-heading-1-setext nil
2447 'markdown-heading-2-setext nil
2448 'markdown-heading-1-atx nil
2449 'markdown-heading-2-atx nil
2450 'markdown-heading-3-atx nil
2451 'markdown-heading-4-atx nil
2452 'markdown-heading-5-atx nil
2453 'markdown-heading-6-atx nil
2454 'markdown-metadata-key nil
2455 'markdown-metadata-value nil
2456 'markdown-metadata-markup nil)
2457 "Property list of all Markdown syntactic properties.")
2459 (defun markdown-syntax-propertize (start end)
2460 "Function used as `syntax-propertize-function'.
2461 START and END delimit region to propertize."
2462 (with-silent-modifications
2463 (save-excursion
2464 (remove-text-properties start end markdown--syntax-properties)
2465 (markdown-syntax-propertize-fenced-block-constructs start end)
2466 (markdown-syntax-propertize-yaml-metadata start end)
2467 (markdown-syntax-propertize-pre-blocks start end)
2468 (markdown-syntax-propertize-blockquotes start end)
2469 (markdown-syntax-propertize-headings start end)
2470 (markdown-syntax-propertize-hrs start end)
2471 (markdown-syntax-propertize-comments start end))))
2474 ;;; Markup Hiding
2476 (defconst markdown-markup-properties
2477 '(face markdown-markup-face invisible markdown-markup)
2478 "List of properties and values to apply to markup.")
2480 (defconst markdown-language-keyword-properties
2481 '(face markdown-language-keyword-face invisible markdown-markup)
2482 "List of properties and values to apply to code block language names.")
2484 (defconst markdown-language-info-properties
2485 '(face markdown-language-info-face invisible markdown-markup)
2486 "List of properties and values to apply to code block language info strings.")
2488 (defconst markdown-include-title-properties
2489 '(face markdown-link-title-face invisible markdown-markup)
2490 "List of properties and values to apply to included code titles.")
2492 (defconst markdown-inline-footnote-properties
2493 '(face nil display ((raise 0.2) (height 0.8)))
2494 "Properties to apply to footnote markers and inline footnotes.")
2496 (defcustom markdown-hide-markup nil
2497 "Determines whether markup in the buffer will be hidden.
2498 When set to nil, all markup is displayed in the buffer as it
2499 appears in the file. An exception is when `markdown-hide-urls'
2500 is non-nil.
2501 Set this to a non-nil value to turn this feature on by default.
2502 You can interactively toggle the value of this variable with
2503 `markdown-toggle-markup-hiding', \\[markdown-toggle-markup-hiding],
2504 or from the Markdown > Show & Hide menu.
2506 Markup hiding works by adding text properties to positions in the
2507 buffer---either the `invisible' property or the `display' property
2508 in cases where alternative glyphs are used (e.g., list bullets).
2509 This does not, however, affect printing or other output.
2510 Functions such as `htmlfontify-buffer' and `ps-print-buffer' will
2511 not honor these text properties. For printing, it would be better
2512 to first convert to HTML or PDF (e.g,. using Pandoc)."
2513 :group 'markdown
2514 :type 'boolean
2515 :safe 'booleanp
2516 :package-version '(markdown-mode . "2.3"))
2517 (make-variable-buffer-local 'markdown-hide-markup)
2519 (defun markdown-toggle-markup-hiding (&optional arg)
2520 "Toggle the display or hiding of markup.
2521 With a prefix argument ARG, enable markup hiding if ARG is positive,
2522 and disable it otherwise.
2523 See `markdown-hide-markup' for additional details."
2524 (interactive (list (or current-prefix-arg 'toggle)))
2525 (setq markdown-hide-markup
2526 (if (eq arg 'toggle)
2527 (not markdown-hide-markup)
2528 (> (prefix-numeric-value arg) 0)))
2529 (if markdown-hide-markup
2530 (progn (add-to-invisibility-spec 'markdown-markup)
2531 (message "markdown-mode markup hiding enabled"))
2532 (progn (remove-from-invisibility-spec 'markdown-markup)
2533 (message "markdown-mode markup hiding disabled")))
2534 (markdown-reload-extensions))
2537 ;;; Font Lock =================================================================
2539 (require 'font-lock)
2541 (defvar markdown-italic-face 'markdown-italic-face
2542 "Face name to use for italic text.")
2544 (defvar markdown-bold-face 'markdown-bold-face
2545 "Face name to use for bold text.")
2547 (defvar markdown-strike-through-face 'markdown-strike-through-face
2548 "Face name to use for strike-through text.")
2550 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
2551 "Face name to use as a base for header delimiters.")
2553 (defvar markdown-header-rule-face 'markdown-header-rule-face
2554 "Face name to use as a base for header rules.")
2556 (defvar markdown-header-face 'markdown-header-face
2557 "Face name to use as a base for headers.")
2559 (defvar markdown-header-face-1 'markdown-header-face-1
2560 "Face name to use for level-1 headers.")
2562 (defvar markdown-header-face-2 'markdown-header-face-2
2563 "Face name to use for level-2 headers.")
2565 (defvar markdown-header-face-3 'markdown-header-face-3
2566 "Face name to use for level-3 headers.")
2568 (defvar markdown-header-face-4 'markdown-header-face-4
2569 "Face name to use for level-4 headers.")
2571 (defvar markdown-header-face-5 'markdown-header-face-5
2572 "Face name to use for level-5 headers.")
2574 (defvar markdown-header-face-6 'markdown-header-face-6
2575 "Face name to use for level-6 headers.")
2577 (defvar markdown-inline-code-face 'markdown-inline-code-face
2578 "Face name to use for inline code.")
2580 (defvar markdown-list-face 'markdown-list-face
2581 "Face name to use for list markers.")
2583 (defvar markdown-blockquote-face 'markdown-blockquote-face
2584 "Face name to use for blockquote.")
2586 (defvar markdown-pre-face 'markdown-pre-face
2587 "Face name to use for preformatted text.")
2589 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
2590 "Face name to use for programming language identifiers.")
2592 (defvar markdown-language-info-face 'markdown-language-info-face
2593 "Face name to use for programming info strings.")
2595 (defvar markdown-link-face 'markdown-link-face
2596 "Face name to use for links.")
2598 (defvar markdown-missing-link-face 'markdown-missing-link-face
2599 "Face name to use for links where the linked file does not exist.")
2601 (defvar markdown-reference-face 'markdown-reference-face
2602 "Face name to use for reference.")
2604 (defvar markdown-footnote-marker-face 'markdown-footnote-marker-face
2605 "Face name to use for footnote markers.")
2607 (defvar markdown-url-face 'markdown-url-face
2608 "Face name to use for URLs.")
2610 (defvar markdown-link-title-face 'markdown-link-title-face
2611 "Face name to use for reference link titles.")
2613 (defvar markdown-line-break-face 'markdown-line-break-face
2614 "Face name to use for hard line breaks.")
2616 (defvar markdown-comment-face 'markdown-comment-face
2617 "Face name to use for HTML comments.")
2619 (defvar markdown-math-face 'markdown-math-face
2620 "Face name to use for LaTeX expressions.")
2622 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
2623 "Face name to use for metadata keys.")
2625 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
2626 "Face name to use for metadata values.")
2628 (defvar markdown-gfm-checkbox-face 'markdown-gfm-checkbox-face
2629 "Face name to use for GFM checkboxes.")
2631 (defvar markdown-highlight-face 'markdown-highlight-face
2632 "Face name to use for mouse highlighting.")
2634 (defvar markdown-markup-face 'markdown-markup-face
2635 "Face name to use for markup elements.")
2637 (defgroup markdown-faces nil
2638 "Faces used in Markdown Mode"
2639 :group 'markdown
2640 :group 'faces)
2642 (defface markdown-italic-face
2643 '((t (:inherit italic)))
2644 "Face for italic text."
2645 :group 'markdown-faces)
2647 (defface markdown-bold-face
2648 '((t (:inherit bold)))
2649 "Face for bold text."
2650 :group 'markdown-faces)
2652 (defface markdown-strike-through-face
2653 '((t (:strike-through t)))
2654 "Face for strike-through text."
2655 :group 'markdown-faces)
2657 (defface markdown-markup-face
2658 '((t (:inherit shadow :slant normal :weight normal)))
2659 "Face for markup elements."
2660 :group 'markdown-faces)
2662 (defface markdown-header-rule-face
2663 '((t (:inherit markdown-markup-face)))
2664 "Base face for headers rules."
2665 :group 'markdown-faces)
2667 (defface markdown-header-delimiter-face
2668 '((t (:inherit markdown-markup-face)))
2669 "Base face for headers hash delimiter."
2670 :group 'markdown-faces)
2672 (defface markdown-list-face
2673 '((t (:inherit markdown-markup-face)))
2674 "Face for list item markers."
2675 :group 'markdown-faces)
2677 (defface markdown-blockquote-face
2678 '((t (:inherit font-lock-doc-face)))
2679 "Face for blockquote sections."
2680 :group 'markdown-faces)
2682 (defface markdown-code-face
2683 '((t (:inherit fixed-pitch)))
2684 "Face for inline code, pre blocks, and fenced code blocks.
2685 This may be used, for example, to add a contrasting background to
2686 inline code fragments and code blocks."
2687 :group 'markdown-faces)
2689 (defface markdown-inline-code-face
2690 '((t (:inherit (markdown-code-face font-lock-constant-face))))
2691 "Face for inline code."
2692 :group 'markdown-faces)
2694 (defface markdown-pre-face
2695 '((t (:inherit (markdown-code-face font-lock-constant-face))))
2696 "Face for preformatted text."
2697 :group 'markdown-faces)
2699 (defface markdown-table-face
2700 '((t (:inherit (markdown-code-face))))
2701 "Face for tables."
2702 :group 'markdown-faces)
2704 (defface markdown-language-keyword-face
2705 '((t (:inherit font-lock-type-face)))
2706 "Face for programming language identifiers."
2707 :group 'markdown-faces)
2709 (defface markdown-language-info-face
2710 '((t (:inherit font-lock-string-face)))
2711 "Face for programming language info strings."
2712 :group 'markdown-faces)
2714 (defface markdown-link-face
2715 '((t (:inherit link)))
2716 "Face for links."
2717 :group 'markdown-faces)
2719 (defface markdown-missing-link-face
2720 '((t (:inherit font-lock-warning-face)))
2721 "Face for missing links."
2722 :group 'markdown-faces)
2724 (defface markdown-reference-face
2725 '((t (:inherit markdown-markup-face)))
2726 "Face for link references."
2727 :group 'markdown-faces)
2729 (define-obsolete-face-alias 'markdown-footnote-face
2730 'markdown-footnote-marker-face "v2.3")
2732 (defface markdown-footnote-marker-face
2733 '((t (:inherit markdown-markup-face)))
2734 "Face for footnote markers."
2735 :group 'markdown-faces)
2737 (defface markdown-footnote-text-face
2738 '((t (:inherit font-lock-comment-face)))
2739 "Face for footnote text."
2740 :group 'markdown-faces)
2742 (defface markdown-url-face
2743 '((t (:inherit font-lock-string-face)))
2744 "Face for URLs that are part of markup.
2745 For example, this applies to URLs in inline links:
2746 [link text](http://example.com/)."
2747 :group 'markdown-faces)
2749 (defface markdown-plain-url-face
2750 '((t (:inherit markdown-link-face)))
2751 "Face for URLs that are also links.
2752 For example, this applies to plain angle bracket URLs:
2753 <http://example.com/>."
2754 :group 'markdown-faces)
2756 (defface markdown-link-title-face
2757 '((t (:inherit font-lock-comment-face)))
2758 "Face for reference link titles."
2759 :group 'markdown-faces)
2761 (defface markdown-line-break-face
2762 '((t (:inherit font-lock-constant-face :underline t)))
2763 "Face for hard line breaks."
2764 :group 'markdown-faces)
2766 (defface markdown-comment-face
2767 '((t (:inherit font-lock-comment-face)))
2768 "Face for HTML comments."
2769 :group 'markdown-faces)
2771 (defface markdown-math-face
2772 '((t (:inherit font-lock-string-face)))
2773 "Face for LaTeX expressions."
2774 :group 'markdown-faces)
2776 (defface markdown-metadata-key-face
2777 '((t (:inherit font-lock-variable-name-face)))
2778 "Face for metadata keys."
2779 :group 'markdown-faces)
2781 (defface markdown-metadata-value-face
2782 '((t (:inherit font-lock-string-face)))
2783 "Face for metadata values."
2784 :group 'markdown-faces)
2786 (defface markdown-gfm-checkbox-face
2787 '((t (:inherit font-lock-builtin-face)))
2788 "Face for GFM checkboxes."
2789 :group 'markdown-faces)
2791 (defface markdown-highlight-face
2792 '((t (:inherit highlight)))
2793 "Face for mouse highlighting."
2794 :group 'markdown-faces)
2796 (defface markdown-hr-face
2797 '((t (:inherit markdown-markup-face)))
2798 "Face for horizontal rules."
2799 :group 'markdown-faces)
2801 (defface markdown-html-tag-name-face
2802 '((t (:inherit font-lock-type-face)))
2803 "Face for HTML tag names."
2804 :group 'markdown-faces)
2806 (defface markdown-html-tag-delimiter-face
2807 '((t (:inherit markdown-markup-face)))
2808 "Face for HTML tag delimiters."
2809 :group 'markdown-faces)
2811 (defface markdown-html-attr-name-face
2812 '((t (:inherit font-lock-variable-name-face)))
2813 "Face for HTML attribute names."
2814 :group 'markdown-faces)
2816 (defface markdown-html-attr-value-face
2817 '((t (:inherit font-lock-string-face)))
2818 "Face for HTML attribute values."
2819 :group 'markdown-faces)
2821 (defface markdown-html-entity-face
2822 '((t (:inherit font-lock-variable-name-face)))
2823 "Face for HTML entities."
2824 :group 'markdown-faces)
2826 (defcustom markdown-header-scaling nil
2827 "Whether to use variable-height faces for headers.
2828 When non-nil, `markdown-header-face' will inherit from
2829 `variable-pitch' and the scaling values in
2830 `markdown-header-scaling-values' will be applied to
2831 headers of levels one through six respectively."
2832 :type 'boolean
2833 :initialize 'custom-initialize-default
2834 :set (lambda (symbol value)
2835 (set-default symbol value)
2836 (markdown-update-header-faces value))
2837 :group 'markdown-faces
2838 :package-version '(markdown-mode . "2.2"))
2840 (defcustom markdown-header-scaling-values
2841 '(2.0 1.7 1.4 1.1 1.0 1.0)
2842 "List of scaling values for headers of level one through six.
2843 Used when `markdown-header-scaling' is non-nil."
2844 :type 'list
2845 :initialize 'custom-initialize-default
2846 :set (lambda (symbol value)
2847 (set-default symbol value)
2848 (markdown-update-header-faces markdown-header-scaling value))
2849 :group 'markdown-faces)
2851 (defun markdown-make-header-faces ()
2852 "Build the faces used for Markdown headers."
2853 (let ((inherit-faces '(font-lock-function-name-face)))
2854 (when markdown-header-scaling
2855 (setq inherit-faces (cons 'variable-pitch inherit-faces)))
2856 (defface markdown-header-face
2857 `((t (:inherit ,inherit-faces :weight bold)))
2858 "Base face for headers."
2859 :group 'markdown-faces))
2860 (dotimes (num 6)
2861 (let* ((num1 (1+ num))
2862 (face-name (intern (format "markdown-header-face-%s" num1)))
2863 (scale (if markdown-header-scaling
2864 (float (nth num markdown-header-scaling-values))
2865 1.0)))
2866 (eval
2867 `(defface ,face-name
2868 '((t (:inherit markdown-header-face :height ,scale)))
2869 (format "Face for level %s headers.
2870 You probably don't want to customize this face directly. Instead
2871 you can customize the base face `markdown-header-face' or the
2872 variable-height variable `markdown-header-scaling'." ,num1)
2873 :group 'markdown-faces)))))
2875 (markdown-make-header-faces)
2877 (defun markdown-update-header-faces (&optional scaling scaling-values)
2878 "Update header faces, depending on if header SCALING is desired.
2879 If so, use given list of SCALING-VALUES relative to the baseline
2880 size of `markdown-header-face'."
2881 (dotimes (num 6)
2882 (let* ((face-name (intern (format "markdown-header-face-%s" (1+ num))))
2883 (scale (cond ((not scaling) 1.0)
2884 (scaling-values (float (nth num scaling-values)))
2885 (t (float (nth num markdown-header-scaling-values))))))
2886 (unless (get face-name 'saved-face) ; Don't update customized faces
2887 (set-face-attribute face-name nil :height scale)))))
2889 (defun markdown-syntactic-face (state)
2890 "Return font-lock face for characters with given STATE.
2891 See `font-lock-syntactic-face-function' for details."
2892 (let ((in-comment (nth 4 state)))
2893 (cond
2894 (in-comment 'markdown-comment-face)
2895 (t nil))))
2897 (defcustom markdown-list-item-bullets
2898 '("●" "◎" "○" "◆" "◇" "►" "•")
2899 "List of bullets to use for unordered lists.
2900 It can contain any number of symbols, which will be repeated.
2901 Depending on your font, some reasonable choices are:
2902 ♥ ● ◇ ✚ ✜ ☯ ◆ ♠ ♣ ♦ ❀ ◆ ◖ ▶ ► • ★ ▸."
2903 :group 'markdown
2904 :type '(repeat (string :tag "Bullet character"))
2905 :package-version '(markdown-mode . "2.3"))
2907 (defvar markdown-mode-font-lock-keywords-basic
2908 `((markdown-match-yaml-metadata-begin . ((1 markdown-markup-face)))
2909 (markdown-match-yaml-metadata-end . ((1 markdown-markup-face)))
2910 (markdown-match-yaml-metadata-key . ((1 markdown-metadata-key-face)
2911 (2 markdown-markup-face)
2912 (3 markdown-metadata-value-face)))
2913 (markdown-match-gfm-open-code-blocks . ((1 markdown-markup-properties)
2914 (2 markdown-markup-properties nil t)
2915 (3 markdown-language-keyword-properties nil t)
2916 (4 markdown-language-info-properties nil t)
2917 (5 markdown-markup-properties nil t)))
2918 (markdown-match-gfm-close-code-blocks . ((0 markdown-markup-properties)))
2919 (markdown-fontify-gfm-code-blocks)
2920 (markdown-fontify-tables)
2921 (markdown-match-fenced-start-code-block . ((1 markdown-markup-properties)
2922 (2 markdown-markup-properties nil t)
2923 (3 markdown-language-keyword-properties nil t)
2924 (4 markdown-language-info-properties nil t)
2925 (5 markdown-markup-properties nil t)))
2926 (markdown-match-fenced-end-code-block . ((0 markdown-markup-properties)))
2927 (markdown-fontify-fenced-code-blocks)
2928 (markdown-match-pre-blocks . ((0 markdown-pre-face)))
2929 (markdown-fontify-headings)
2930 (markdown-match-declarative-metadata . ((1 markdown-metadata-key-face)
2931 (2 markdown-markup-face)
2932 (3 markdown-metadata-value-face)))
2933 (markdown-match-pandoc-metadata . ((1 markdown-markup-face)
2934 (2 markdown-markup-face)
2935 (3 markdown-metadata-value-face)))
2936 (markdown-fontify-hrs)
2937 (markdown-match-code . ((1 markdown-markup-properties prepend)
2938 (2 markdown-inline-code-face prepend)
2939 (3 markdown-markup-properties prepend)))
2940 (,markdown-regex-kbd . ((1 markdown-markup-properties)
2941 (2 markdown-inline-code-face)
2942 (3 markdown-markup-properties)))
2943 (markdown-fontify-angle-uris)
2944 (,markdown-regex-email . 'markdown-plain-url-face)
2945 (markdown-match-html-tag . ((1 'markdown-html-tag-delimiter-face t)
2946 (2 'markdown-html-tag-name-face t)
2947 (3 'markdown-html-tag-delimiter-face t)
2948 ;; Anchored matcher for HTML tag attributes
2949 (,markdown-regex-html-attr
2950 ;; Before searching, move past tag
2951 ;; name; set limit at tag close.
2952 (progn
2953 (goto-char (match-end 2)) (match-end 3))
2955 . ((1 'markdown-html-attr-name-face)
2956 (3 'markdown-html-tag-delimiter-face nil t)
2957 (4 'markdown-html-attr-value-face nil t)))))
2958 (,markdown-regex-html-entity . 'markdown-html-entity-face)
2959 (markdown-fontify-list-items)
2960 (,markdown-regex-footnote . ((0 markdown-inline-footnote-properties)
2961 (1 markdown-markup-properties) ; [^
2962 (2 markdown-footnote-marker-face) ; label
2963 (3 markdown-markup-properties))) ; ]
2964 (,markdown-regex-pandoc-inline-footnote . ((0 markdown-inline-footnote-properties)
2965 (1 markdown-markup-properties) ; ^
2966 (2 markdown-markup-properties) ; [
2967 (3 'markdown-footnote-text-face) ; text
2968 (4 markdown-markup-properties))) ; ]
2969 (markdown-match-includes . ((1 markdown-markup-properties)
2970 (2 markdown-markup-properties nil t)
2971 (3 markdown-include-title-properties nil t)
2972 (4 markdown-markup-properties nil t)
2973 (5 markdown-markup-properties)
2974 (6 'markdown-url-face)
2975 (7 markdown-markup-properties)))
2976 (markdown-fontify-inline-links)
2977 (markdown-fontify-reference-links)
2978 (,markdown-regex-reference-definition . ((1 markdown-markup-face) ; [
2979 (2 markdown-reference-face) ; label
2980 (3 markdown-markup-face) ; ]
2981 (4 markdown-markup-face) ; :
2982 (5 markdown-url-face) ; url
2983 (6 markdown-link-title-face))) ; "title" (optional)
2984 (markdown-fontify-plain-uris)
2985 ;; Math mode $..$
2986 (markdown-match-math-single . ((1 markdown-markup-face prepend)
2987 (2 markdown-math-face append)
2988 (3 markdown-markup-face prepend)))
2989 ;; Math mode $$..$$
2990 (markdown-match-math-double . ((1 markdown-markup-face prepend)
2991 (2 markdown-math-face append)
2992 (3 markdown-markup-face prepend)))
2993 ;; Math mode \[..\] and \\[..\\]
2994 (markdown-match-math-display . ((1 markdown-markup-face prepend)
2995 (3 markdown-math-face append)
2996 (4 markdown-markup-face prepend)))
2997 (markdown-match-bold . ((1 markdown-markup-properties prepend)
2998 (2 markdown-bold-face append)
2999 (3 markdown-markup-properties prepend)))
3000 (markdown-match-italic . ((1 markdown-markup-properties prepend)
3001 (2 markdown-italic-face append)
3002 (3 markdown-markup-properties prepend)))
3003 (,markdown-regex-strike-through . ((3 markdown-markup-properties)
3004 (4 markdown-strike-through-face)
3005 (5 markdown-markup-properties)))
3006 (,markdown-regex-line-break . (1 markdown-line-break-face prepend))
3007 (markdown-fontify-sub-superscripts)
3008 (markdown-match-inline-attributes . ((0 markdown-markup-properties prepend)))
3009 (markdown-match-leanpub-sections . ((0 markdown-markup-properties)))
3010 (markdown-fontify-blockquotes)
3011 (markdown-match-wiki-link . ((0 markdown-link-face prepend))))
3012 "Syntax highlighting for Markdown files.")
3014 ;; Footnotes
3015 (defvar markdown-footnote-counter 0
3016 "Counter for footnote numbers.")
3017 (make-variable-buffer-local 'markdown-footnote-counter)
3019 (defconst markdown-footnote-chars
3020 "[[:alnum:]-]"
3021 "Regular expression matching any character that is allowed in a footnote identifier.")
3023 (defconst markdown-regex-footnote-definition
3024 (concat "^ \\{0,3\\}\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:\\(?:[ \t]+\\|$\\)")
3025 "Regular expression matching a footnote definition, capturing the label.")
3028 ;;; Compatibility =============================================================
3030 (defun markdown-replace-regexp-in-string (regexp rep string)
3031 "Replace ocurrences of REGEXP with REP in STRING.
3032 This is a compatibility wrapper to provide `replace-regexp-in-string'
3033 in XEmacs 21."
3034 (if (featurep 'xemacs)
3035 (replace-in-string string regexp rep)
3036 (replace-regexp-in-string regexp rep string)))
3038 ;; `markdown-use-region-p' is a compatibility function which checks
3039 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
3040 (eval-and-compile
3041 (cond
3042 ;; Emacs 24 and newer
3043 ((fboundp 'use-region-p)
3044 (defalias 'markdown-use-region-p 'use-region-p))
3045 ;; XEmacs
3046 ((fboundp 'region-active-p)
3047 (defalias 'markdown-use-region-p 'region-active-p))))
3049 ;; Use new names for outline-mode functions in Emacs 25 and later.
3050 (eval-and-compile
3051 (defalias 'markdown-hide-sublevels
3052 (if (fboundp 'outline-hide-sublevels)
3053 'outline-hide-sublevels
3054 'hide-sublevels))
3055 (defalias 'markdown-show-all
3056 (if (fboundp 'outline-show-all)
3057 'outline-show-all
3058 'show-all))
3059 (defalias 'markdown-hide-body
3060 (if (fboundp 'outline-hide-body)
3061 'outline-hide-body
3062 'hide-body))
3063 (defalias 'markdown-show-children
3064 (if (fboundp 'outline-show-children)
3065 'outline-show-children
3066 'show-children))
3067 (defalias 'markdown-show-subtree
3068 (if (fboundp 'outline-show-subtree)
3069 'outline-show-subtree
3070 'show-subtree))
3071 (defalias 'markdown-hide-subtree
3072 (if (fboundp 'outline-hide-subtree)
3073 'outline-hide-subtree
3074 'hide-subtree)))
3076 ;; Provide directory-name-p to Emacs 24
3077 (defsubst markdown-directory-name-p (name)
3078 "Return non-nil if NAME ends with a directory separator character.
3079 Taken from `directory-name-p' from Emacs 25 and provided here for
3080 backwards compatibility."
3081 (let ((len (length name))
3082 (lastc ?.))
3083 (if (> len 0)
3084 (setq lastc (aref name (1- len))))
3085 (or (= lastc ?/)
3086 (and (memq system-type '(windows-nt ms-dos))
3087 (= lastc ?\\)))))
3089 ;; Provide a function to find files recursively in Emacs 24.
3090 (defalias 'markdown-directory-files-recursively
3091 (if (fboundp 'directory-files-recursively)
3092 'directory-files-recursively
3093 (lambda (dir regexp)
3094 "Return list of all files under DIR that have file names matching REGEXP.
3095 This function works recursively. Files are returned in \"depth first\"
3096 order, and files from each directory are sorted in alphabetical order.
3097 Each file name appears in the returned list in its absolute form.
3098 Based on `directory-files-recursively' from Emacs 25 and provided
3099 here for backwards compatibility."
3100 (let ((result nil)
3101 (files nil)
3102 ;; When DIR is "/", remote file names like "/method:" could
3103 ;; also be offered. We shall suppress them.
3104 (tramp-mode (and tramp-mode (file-remote-p (expand-file-name dir)))))
3105 (dolist (file (sort (file-name-all-completions "" dir)
3106 'string<))
3107 (unless (member file '("./" "../"))
3108 (if (markdown-directory-name-p file)
3109 (let* ((leaf (substring file 0 (1- (length file))))
3110 (full-file (expand-file-name leaf dir)))
3111 (setq result
3112 (nconc result (markdown-directory-files-recursively
3113 full-file regexp))))
3114 (when (string-match-p regexp file)
3115 (push (expand-file-name file dir) files)))))
3116 (nconc result (nreverse files))))))
3118 (defun markdown-flyspell-check-word-p ()
3119 "Return t if `flyspell' should check word just before point.
3120 Used for `flyspell-generic-check-word-predicate'."
3121 (save-excursion
3122 (goto-char (1- (point)))
3123 (not (or (markdown-code-block-at-point-p)
3124 (markdown-inline-code-at-point-p)
3125 (markdown-in-comment-p)
3126 (let ((faces (get-text-property (point) 'face)))
3127 (if (listp faces)
3128 (or (memq 'markdown-reference-face faces)
3129 (memq 'markdown-markup-face faces)
3130 (memq 'markdown-plain-url-face faces)
3131 (memq 'markdown-inline-code-face faces)
3132 (memq 'markdown-url-face faces))
3133 (memq faces '(markdown-reference-face
3134 markdown-markup-face
3135 markdown-plain-url-face
3136 markdown-inline-code-face
3137 markdown-url-face))))))))
3139 (defun markdown-font-lock-ensure ()
3140 "Provide `font-lock-ensure' in Emacs 24."
3141 (if (fboundp 'font-lock-ensure)
3142 (font-lock-ensure)
3143 (with-no-warnings
3144 ;; Suppress warning about non-interactive use of
3145 ;; `font-lock-fontify-buffer' in Emacs 25.
3146 (font-lock-fontify-buffer))))
3149 ;;; Markdown Parsing Functions ================================================
3151 (defun markdown-cur-line-blank (&optional predicate)
3152 "Return t if the current line is blank and nil otherwise.
3153 When PREDICATE is non-nil, don't modify the match data."
3154 (save-excursion
3155 (beginning-of-line)
3156 (let ((regexp "^\\s *$"))
3157 (if predicate
3158 (looking-at-p regexp)
3159 (looking-at regexp)))))
3161 (defun markdown-cur-line-blank-p ()
3162 "Same as `markdown-cur-line-blank', but does not change the match data."
3163 (markdown-cur-line-blank t))
3165 (defun markdown-prev-line-blank (&optional predicate)
3166 "Return t if the previous line is blank and nil otherwise.
3167 If we are at the first line, then consider the previous line to be blank.
3168 When PREDICATE is non-nil, don't modify the match data."
3169 (or (= (line-beginning-position) (point-min))
3170 (save-excursion
3171 (forward-line -1)
3172 (markdown-cur-line-blank predicate))))
3174 (defun markdown-prev-line-blank-p ()
3175 "Same as `markdown-prev-line-blank', but does not change the match data."
3176 (markdown-prev-line-blank t))
3178 (defun markdown-next-line-blank (&optional predicate)
3179 "Return t if the next line is blank and nil otherwise.
3180 If we are at the last line, then consider the next line to be blank.
3181 When PREDICATE is non-nil, don't modify the match data."
3182 (or (= (line-end-position) (point-max))
3183 (save-excursion
3184 (forward-line 1)
3185 (markdown-cur-line-blank predicate))))
3187 (defun markdown-next-line-blank-p ()
3188 "Same as `markdown-next-line-blank', but does not change the match data."
3189 (markdown-next-line-blank t))
3191 (defun markdown-prev-line-indent ()
3192 "Return the number of leading whitespace characters in the previous line.
3193 Return 0 if the current line is the first line in the buffer."
3194 (save-excursion
3195 (if (= (line-beginning-position) (point-min))
3197 (forward-line -1)
3198 (current-indentation))))
3200 (defun markdown-next-line-indent ()
3201 "Return the number of leading whitespace characters in the next line.
3202 Return 0 if line is the last line in the buffer."
3203 (save-excursion
3204 (if (= (line-end-position) (point-max))
3206 (forward-line 1)
3207 (current-indentation))))
3209 (defun markdown-cur-non-list-indent ()
3210 "Return beginning position of list item text (not including the list marker).
3211 Return nil if the current line is not the beginning of a list item."
3212 (save-match-data
3213 (save-excursion
3214 (beginning-of-line)
3215 (when (re-search-forward markdown-regex-list (line-end-position) t)
3216 (current-column)))))
3218 (defun markdown-prev-non-list-indent ()
3219 "Return position of the first non-list-marker on the previous line."
3220 (save-excursion
3221 (forward-line -1)
3222 (markdown-cur-non-list-indent)))
3224 (defun markdown-new-baseline ()
3225 "Determine if the current line begins a new baseline level."
3226 (save-excursion
3227 (beginning-of-line)
3228 (or (looking-at markdown-regex-header)
3229 (looking-at markdown-regex-hr)
3230 (and (null (markdown-cur-non-list-indent))
3231 (= (current-indentation) 0)
3232 (markdown-prev-line-blank)))))
3234 (defun markdown-search-backward-baseline ()
3235 "Search backward baseline point with no indentation and not a list item."
3236 (end-of-line)
3237 (let (stop)
3238 (while (not (or stop (bobp)))
3239 (re-search-backward markdown-regex-block-separator-noindent nil t)
3240 (when (match-end 2)
3241 (goto-char (match-end 2))
3242 (cond
3243 ((markdown-new-baseline)
3244 (setq stop t))
3245 ((looking-at-p markdown-regex-list)
3246 (setq stop nil))
3247 (t (setq stop t)))))))
3249 (defun markdown-update-list-levels (marker indent levels)
3250 "Update list levels given list MARKER, block INDENT, and current LEVELS.
3251 Here, MARKER is a string representing the type of list, INDENT is an integer
3252 giving the indentation, in spaces, of the current block, and LEVELS is a
3253 list of the indentation levels of parent list items. When LEVELS is nil,
3254 it means we are at baseline (not inside of a nested list)."
3255 (cond
3256 ;; New list item at baseline.
3257 ((and marker (null levels))
3258 (setq levels (list indent)))
3259 ;; List item with greater indentation (four or more spaces).
3260 ;; Increase list level.
3261 ((and marker (>= indent (+ (car levels) 4)))
3262 (setq levels (cons indent levels)))
3263 ;; List item with greater or equal indentation (less than four spaces).
3264 ;; Do not increase list level.
3265 ((and marker (>= indent (car levels)))
3266 levels)
3267 ;; Lesser indentation level.
3268 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
3269 ;; indentation could move back more than one list level). Note
3270 ;; that this block need not be the beginning of list item.
3271 ((< indent (car levels))
3272 (while (and (> (length levels) 1)
3273 (< indent (+ (cadr levels) 4)))
3274 (setq levels (cdr levels)))
3275 levels)
3276 ;; Otherwise, do nothing.
3277 (t levels)))
3279 (defun markdown-calculate-list-levels ()
3280 "Calculate list levels at point.
3281 Return a list of the form (n1 n2 n3 ...) where n1 is the
3282 indentation of the deepest nested list item in the branch of
3283 the list at the point, n2 is the indentation of the parent
3284 list item, and so on. The depth of the list item is therefore
3285 the length of the returned list. If the point is not at or
3286 immediately after a list item, return nil."
3287 (save-excursion
3288 (let ((first (point)) levels indent pre-regexp)
3289 ;; Find a baseline point with zero list indentation
3290 (markdown-search-backward-baseline)
3291 ;; Search for all list items between baseline and LOC
3292 (while (and (< (point) first)
3293 (re-search-forward markdown-regex-list first t))
3294 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
3295 (beginning-of-line)
3296 (cond
3297 ;; Make sure this is not a header or hr
3298 ((markdown-new-baseline) (setq levels nil))
3299 ;; Make sure this is not a line from a pre block
3300 ((looking-at-p pre-regexp))
3301 ;; If not, then update levels
3303 (setq indent (current-indentation))
3304 (setq levels (markdown-update-list-levels (match-string 2)
3305 indent levels))))
3306 (end-of-line))
3307 levels)))
3309 (defun markdown-prev-list-item (level)
3310 "Search backward from point for a list item with indentation LEVEL.
3311 Set point to the beginning of the item, and return point, or nil
3312 upon failure."
3313 (let (bounds indent prev)
3314 (setq prev (point))
3315 (forward-line -1)
3316 (setq indent (current-indentation))
3317 (while
3318 (cond
3319 ;; List item
3320 ((and (looking-at-p markdown-regex-list)
3321 (setq bounds (markdown-cur-list-item-bounds)))
3322 (cond
3323 ;; Stop and return point at item of equal indentation
3324 ((= (nth 3 bounds) level)
3325 (setq prev (point))
3326 nil)
3327 ;; Stop and return nil at item with lesser indentation
3328 ((< (nth 3 bounds) level)
3329 (setq prev nil)
3330 nil)
3331 ;; Stop at beginning of buffer
3332 ((bobp) (setq prev nil))
3333 ;; Continue at item with greater indentation
3334 ((> (nth 3 bounds) level) t)))
3335 ;; Stop at beginning of buffer
3336 ((bobp) (setq prev nil))
3337 ;; Continue if current line is blank
3338 ((markdown-cur-line-blank-p) t)
3339 ;; Continue while indentation is the same or greater
3340 ((>= indent level) t)
3341 ;; Stop if current indentation is less than list item
3342 ;; and the next is blank
3343 ((and (< indent level)
3344 (markdown-next-line-blank-p))
3345 (setq prev nil))
3346 ;; Stop at a header
3347 ((looking-at-p markdown-regex-header) (setq prev nil))
3348 ;; Stop at a horizontal rule
3349 ((looking-at-p markdown-regex-hr) (setq prev nil))
3350 ;; Otherwise, continue.
3351 (t t))
3352 (forward-line -1)
3353 (setq indent (current-indentation)))
3354 prev))
3356 (defun markdown-next-list-item (level)
3357 "Search forward from point for the next list item with indentation LEVEL.
3358 Set point to the beginning of the item, and return point, or nil
3359 upon failure."
3360 (let (bounds indent next)
3361 (setq next (point))
3362 (if (looking-at markdown-regex-header-setext)
3363 (goto-char (match-end 0)))
3364 (forward-line)
3365 (setq indent (current-indentation))
3366 (while
3367 (cond
3368 ;; Stop at end of the buffer.
3369 ((eobp) nil)
3370 ;; Continue if the current line is blank
3371 ((markdown-cur-line-blank-p) t)
3372 ;; List item
3373 ((and (looking-at-p markdown-regex-list)
3374 (setq bounds (markdown-cur-list-item-bounds)))
3375 (cond
3376 ;; Continue at item with greater indentation
3377 ((> (nth 3 bounds) level) t)
3378 ;; Stop and return point at item of equal indentation
3379 ((= (nth 3 bounds) level)
3380 (setq next (point))
3381 nil)
3382 ;; Stop and return nil at item with lesser indentation
3383 ((< (nth 3 bounds) level)
3384 (setq next nil)
3385 nil)))
3386 ;; Continue while indentation is the same or greater
3387 ((>= indent level) t)
3388 ;; Stop if current indentation is less than list item
3389 ;; and the previous line was blank.
3390 ((and (< indent level)
3391 (markdown-prev-line-blank-p))
3392 (setq next nil))
3393 ;; Stop at a header
3394 ((looking-at-p markdown-regex-header) (setq next nil))
3395 ;; Stop at a horizontal rule
3396 ((looking-at-p markdown-regex-hr) (setq next nil))
3397 ;; Otherwise, continue.
3398 (t t))
3399 (forward-line)
3400 (setq indent (current-indentation)))
3401 next))
3403 (defun markdown-cur-list-item-end (level)
3404 "Move to the end of the current list item with nonlist indentation LEVEL.
3405 If the point is not in a list item, do nothing."
3406 (let (indent)
3407 (forward-line)
3408 (setq indent (current-indentation))
3409 (while
3410 (cond
3411 ;; Stop at end of the buffer.
3412 ((eobp) nil)
3413 ;; Continue if the current line is blank
3414 ((markdown-cur-line-blank-p) t)
3415 ;; Continue while indentation is the same or greater
3416 ((>= indent level) t)
3417 ;; Stop if current indentation is less than list item
3418 ;; and the previous line was blank.
3419 ((and (< indent level)
3420 (markdown-prev-line-blank-p))
3421 nil)
3422 ;; Stop at a new list item of the same or lesser indentation
3423 ((looking-at-p markdown-regex-list) nil)
3424 ;; Stop at a header
3425 ((looking-at-p markdown-regex-header) nil)
3426 ;; Stop at a horizontal rule
3427 ((looking-at-p markdown-regex-hr) nil)
3428 ;; Otherwise, continue.
3429 (t t))
3430 (forward-line)
3431 (setq indent (current-indentation)))
3432 ;; Don't skip over whitespace for empty list items (marker and
3433 ;; whitespace only), just move to end of whitespace.
3434 (if (looking-back (concat markdown-regex-list "\\s-*") nil)
3435 (goto-char (match-end 3))
3436 (skip-syntax-backward "-"))))
3438 (defun markdown-cur-list-item-bounds ()
3439 "Return bounds and indentation of the current list item.
3440 Return a list of the following form:
3442 (begin end indent nonlist-indent marker checkbox)
3444 The named components are:
3446 - begin: Position of beginning of list item, including leading indentation.
3447 - end: Position of the end of the list item, including list item text.
3448 - indent: Number of characters of indentation before list marker (an integer).
3449 - nonlist-indent: Number characters of indentation, list
3450 marker, and whitespace following list marker (an integer).
3451 - marker: String containing the list marker and following whitespace
3452 (e.g., \"- \" or \"* \").
3453 - checkbox: String containing the GFM checkbox portion, if any,
3454 including any trailing whitespace before the text
3455 begins (e.g., \"[x] \").
3457 As an example, for the following unordered list item
3459 - item
3461 the returned list would be
3463 (1 14 3 5 \"- \" nil)
3465 If the point is not inside a list item, return nil.
3466 Leave match data intact for `markdown-regex-list'."
3467 (save-excursion
3468 (let ((cur (point)))
3469 (end-of-line)
3470 (when (re-search-backward markdown-regex-list nil t)
3471 (let* ((begin (match-beginning 0))
3472 (indent (length (match-string-no-properties 1)))
3473 (nonlist-indent (length (match-string 0)))
3474 (marker (concat (match-string-no-properties 2)
3475 (match-string-no-properties 3)))
3476 (checkbox (progn (goto-char (match-end 0))
3477 (when (looking-at "\\[[xX ]\\]\\s-*")
3478 (match-string-no-properties 0))))
3479 (end (save-match-data
3480 (markdown-cur-list-item-end nonlist-indent)
3481 (point))))
3482 (when (and (>= cur begin) (<= cur end) nonlist-indent)
3483 (list begin end indent nonlist-indent marker checkbox)))))))
3485 (defun markdown-list-item-at-point-p ()
3486 "Return t if there is a list item at the point and nil otherwise."
3487 (save-match-data (markdown-cur-list-item-bounds)))
3489 (defun markdown-prev-list-item-bounds ()
3490 "Return bounds of previous item in the same list of any level.
3491 The return value has the same form as that of
3492 `markdown-cur-list-item-bounds'."
3493 (save-excursion
3494 (let ((cur-bounds (markdown-cur-list-item-bounds))
3495 (beginning-of-list (save-excursion (markdown-beginning-of-list)))
3496 stop)
3497 (when cur-bounds
3498 (goto-char (nth 0 cur-bounds))
3499 (while (and (not stop) (not (bobp))
3500 (re-search-backward markdown-regex-list
3501 beginning-of-list t))
3502 (unless (or (looking-at markdown-regex-hr)
3503 (markdown-code-block-at-point-p))
3504 (setq stop (point))))
3505 (markdown-cur-list-item-bounds)))))
3507 (defun markdown-next-list-item-bounds ()
3508 "Return bounds of next item in the same list of any level.
3509 The return value has the same form as that of
3510 `markdown-cur-list-item-bounds'."
3511 (save-excursion
3512 (let ((cur-bounds (markdown-cur-list-item-bounds))
3513 (end-of-list (save-excursion (markdown-end-of-list)))
3514 stop)
3515 (when cur-bounds
3516 (goto-char (nth 0 cur-bounds))
3517 (end-of-line)
3518 (while (and (not stop) (not (eobp))
3519 (re-search-forward markdown-regex-list
3520 end-of-list t))
3521 (unless (or (looking-at markdown-regex-hr)
3522 (markdown-code-block-at-point-p))
3523 (setq stop (point))))
3524 (when stop
3525 (markdown-cur-list-item-bounds))))))
3527 (defun markdown-beginning-of-list ()
3528 "Move point to beginning of list at point, if any."
3529 (interactive)
3530 (let ((orig-point (point))
3531 (list-begin (save-excursion
3532 (markdown-search-backward-baseline)
3533 ;; Stop at next list item, regardless of the indentation.
3534 (markdown-next-list-item (point-max))
3535 (when (looking-at markdown-regex-list)
3536 (point)))))
3537 (when (and list-begin (<= list-begin orig-point))
3538 (goto-char list-begin))))
3540 (defun markdown-end-of-list ()
3541 "Move point to end of list at point, if any."
3542 (interactive)
3543 (let ((start (point))
3544 (end (save-excursion
3545 (when (markdown-beginning-of-list)
3546 ;; Items can't have nonlist-indent <= 1, so this
3547 ;; moves past all list items.
3548 (markdown-next-list-item 1)
3549 (skip-syntax-backward "-")
3550 (unless (eobp) (forward-char 1))
3551 (point)))))
3552 (when (and end (>= end start))
3553 (goto-char end))))
3555 (defun markdown-up-list ()
3556 "Move point to beginning of parent list item."
3557 (interactive)
3558 (let ((cur-bounds (markdown-cur-list-item-bounds)))
3559 (when cur-bounds
3560 (markdown-prev-list-item (1- (nth 3 cur-bounds)))
3561 (let ((up-bounds (markdown-cur-list-item-bounds)))
3562 (when (and up-bounds (< (nth 3 up-bounds) (nth 3 cur-bounds)))
3563 (point))))))
3565 (defun markdown-bounds-of-thing-at-point (thing)
3566 "Call `bounds-of-thing-at-point' for THING with slight modifications.
3567 Does not include trailing newlines when THING is 'line. Handles the
3568 end of buffer case by setting both endpoints equal to the value of
3569 `point-max', since an empty region will trigger empty markup insertion.
3570 Return bounds of form (beg . end) if THING is found, or nil otherwise."
3571 (let* ((bounds (bounds-of-thing-at-point thing))
3572 (a (car bounds))
3573 (b (cdr bounds)))
3574 (when bounds
3575 (when (eq thing 'line)
3576 (cond ((and (eobp) (markdown-cur-line-blank-p))
3577 (setq a b))
3578 ((char-equal (char-before b) ?\^J)
3579 (setq b (1- b)))))
3580 (cons a b))))
3582 (defun markdown-reference-definition (reference)
3583 "Find out whether Markdown REFERENCE is defined.
3584 REFERENCE should not include the square brackets.
3585 When REFERENCE is defined, return a list of the form (text start end)
3586 containing the definition text itself followed by the start and end
3587 locations of the text. Otherwise, return nil.
3588 Leave match data for `markdown-regex-reference-definition'
3589 intact additional processing."
3590 (let ((reference (downcase reference)))
3591 (save-excursion
3592 (goto-char (point-min))
3593 (catch 'found
3594 (while (re-search-forward markdown-regex-reference-definition nil t)
3595 (when (string= reference (downcase (match-string-no-properties 2)))
3596 (throw 'found
3597 (list (match-string-no-properties 5)
3598 (match-beginning 5) (match-end 5)))))))))
3600 (defun markdown-get-defined-references ()
3601 "Return a list of all defined reference labels (not including square brackets)."
3602 (save-excursion
3603 (goto-char (point-min))
3604 (let (refs)
3605 (while (re-search-forward markdown-regex-reference-definition nil t)
3606 (let ((target (match-string-no-properties 2)))
3607 (cl-pushnew target refs :test #'equal)))
3608 (reverse refs))))
3610 (defun markdown-get-used-uris ()
3611 "Return a list of all used URIs in the buffer."
3612 (save-excursion
3613 (goto-char (point-min))
3614 (let (uris)
3615 (while (re-search-forward
3616 (concat "\\(?:" markdown-regex-link-inline
3617 "\\|" markdown-regex-angle-uri
3618 "\\|" markdown-regex-uri
3619 "\\|" markdown-regex-email
3620 "\\)")
3621 nil t)
3622 (unless (or (markdown-inline-code-at-point-p)
3623 (markdown-code-block-at-point-p))
3624 (cl-pushnew (or (match-string-no-properties 6)
3625 (match-string-no-properties 10)
3626 (match-string-no-properties 12)
3627 (match-string-no-properties 13))
3628 uris :test #'equal)))
3629 (reverse uris))))
3631 (defun markdown-inline-code-at-pos (pos)
3632 "Return non-nil if there is an inline code fragment at POS.
3633 Return nil otherwise. Set match data according to
3634 `markdown-match-code' upon success.
3635 This function searches the block for a code fragment that
3636 contains the point using `markdown-match-code'. We do this
3637 because `thing-at-point-looking-at' does not work reliably with
3638 `markdown-regex-code'.
3640 The match data is set as follows:
3641 Group 1 matches the opening backquotes.
3642 Group 2 matches the code fragment itself, without backquotes.
3643 Group 3 matches the closing backquotes."
3644 (save-excursion
3645 (goto-char pos)
3646 (let ((old-point (point))
3647 (end-of-block (progn (markdown-end-of-text-block) (point)))
3648 found)
3649 (markdown-beginning-of-text-block)
3650 (while (and (markdown-match-code end-of-block)
3651 (setq found t)
3652 (< (match-end 0) old-point)))
3653 (and found ; matched something
3654 (<= (match-beginning 0) old-point) ; match contains old-point
3655 (>= (match-end 0) old-point)))))
3657 (defun markdown-inline-code-at-pos-p (pos)
3658 "Return non-nil if there is an inline code fragment at POS.
3659 Like `markdown-inline-code-at-pos`, but preserves match data."
3660 (save-match-data (markdown-inline-code-at-pos pos)))
3662 (defun markdown-inline-code-at-point ()
3663 "Return non-nil if the point is at an inline code fragment.
3664 See `markdown-inline-code-at-pos' for details."
3665 (markdown-inline-code-at-pos (point)))
3667 (defun markdown-inline-code-at-point-p ()
3668 "Return non-nil if there is inline code at the point.
3669 This is a predicate function counterpart to
3670 `markdown-inline-code-at-point' which does not modify the match
3671 data. See `markdown-code-block-at-point-p' for code blocks."
3672 (save-match-data (markdown-inline-code-at-pos (point))))
3674 (make-obsolete 'markdown-code-at-point-p 'markdown-inline-code-at-point-p "v2.2")
3676 (defun markdown-code-block-at-pos (pos)
3677 "Return match data list if there is a code block at POS.
3678 Uses text properties at the beginning of the line position.
3679 This includes pre blocks, tilde-fenced code blocks, and GFM
3680 quoted code blocks. Return nil otherwise."
3681 (setq pos (save-excursion (goto-char pos) (point-at-bol)))
3682 (or (get-text-property pos 'markdown-pre)
3683 (markdown-get-enclosing-fenced-block-construct pos)
3684 ;; polymode removes text properties set by markdown-mode, so
3685 ;; check if `poly-markdown-mode' is active and whether the
3686 ;; `chunkmode' property is non-nil at POS.
3687 (and (bound-and-true-p poly-markdown-mode)
3688 (get-text-property pos 'chunkmode))))
3690 ;; Function was renamed to emphasize that it does not modify match-data.
3691 (defalias 'markdown-code-block-at-point 'markdown-code-block-at-point-p)
3693 (defun markdown-code-block-at-point-p ()
3694 "Return non-nil if there is a code block at the point.
3695 This includes pre blocks, tilde-fenced code blocks, and GFM
3696 quoted code blocks. This function does not modify the match
3697 data. See `markdown-inline-code-at-point-p' for inline code."
3698 (save-match-data (markdown-code-block-at-pos (point))))
3700 (defun markdown-heading-at-point ()
3701 "Return non-nil if there is a heading at the point.
3702 Set match data for `markdown-regex-header'."
3703 (let ((match-data (get-text-property (point) 'markdown-heading)))
3704 (when match-data
3705 (set-match-data match-data)
3706 t)))
3708 (defun markdown-pipe-at-bol-p ()
3709 "Return non-nil if the line begins with a pipe symbol.
3710 This may be useful for tables and Pandoc's line_blocks extension."
3711 (char-equal (char-after (point-at-bol)) ?|))
3714 ;;; Markdown Font Lock Matching Functions =====================================
3716 (defun markdown-range-property-any (begin end prop prop-values)
3717 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
3718 Also returns t if PROP is a list containing one of the PROP-VALUES.
3719 Return nil otherwise."
3720 (let (props)
3721 (catch 'found
3722 (dolist (loc (number-sequence begin end))
3723 (when (setq props (get-text-property loc prop))
3724 (cond ((listp props)
3725 ;; props is a list, check for membership
3726 (dolist (val prop-values)
3727 (when (memq val props) (throw 'found loc))))
3729 ;; props is a scalar, check for equality
3730 (dolist (val prop-values)
3731 (when (eq val props) (throw 'found loc))))))))))
3733 (defun markdown-range-properties-exist (begin end props)
3734 (cl-loop
3735 for loc in (number-sequence begin end)
3736 with result = nil
3737 while (not
3738 (setq result
3739 (cl-some (lambda (prop) (get-text-property loc prop)) props)))
3740 finally return result))
3742 (defun markdown-match-inline-generic (regex last &optional faceless)
3743 "Match inline REGEX from the point to LAST.
3744 When FACELESS is non-nil, do not return matches where faces have been applied."
3745 (when (re-search-forward regex last t)
3746 (let ((bounds (markdown-code-block-at-pos (match-beginning 1)))
3747 (face (and faceless (text-property-not-all
3748 (match-beginning 0) (match-end 0) 'face nil))))
3749 (cond
3750 ;; In code block: move past it and recursively search again
3751 (bounds
3752 (when (< (goto-char (cl-second bounds)) last)
3753 (markdown-match-inline-generic regex last faceless)))
3754 ;; When faces are found in the match range, skip over the match and
3755 ;; recursively search again.
3756 (face
3757 (when (< (goto-char (match-end 0)) last)
3758 (markdown-match-inline-generic regex last faceless)))
3759 ;; Keep match data and return t when in bounds.
3761 (<= (match-end 0) last))))))
3763 (defun markdown-match-code (last)
3764 "Match inline code fragments from point to LAST."
3765 (unless (bobp)
3766 (backward-char 1))
3767 (when (markdown-match-inline-generic markdown-regex-code last)
3768 (let ((begin (match-beginning 1))
3769 (end (match-end 1))
3770 (open-begin (match-beginning 2))
3771 (open-end (match-end 2))
3772 (code-begin (match-beginning 3))
3773 (code-end (match-end 3))
3774 (close-begin (match-beginning 4))
3775 (close-end (match-end 4)))
3776 (if (or (markdown-in-comment-p begin)
3777 (markdown-in-comment-p end)
3778 (markdown-code-block-at-pos begin))
3779 (progn (goto-char (min (1+ begin) last))
3780 (when (< (point) last)
3781 (markdown-match-code last)))
3782 (set-match-data (list begin end
3783 open-begin open-end
3784 code-begin code-end
3785 close-begin close-end))
3786 t))))
3788 (defun markdown-match-bold (last)
3789 "Match inline bold from the point to LAST."
3790 (when (markdown-match-inline-generic markdown-regex-bold last)
3791 (let ((begin (match-beginning 2))
3792 (end (match-end 2)))
3793 (if (or (markdown-inline-code-at-pos-p begin)
3794 (markdown-inline-code-at-pos-p end)
3795 (markdown-in-comment-p)
3796 (markdown-range-property-any
3797 begin begin 'face '(markdown-url-face
3798 markdown-plain-url-face))
3799 (markdown-range-property-any
3800 begin end 'face '(markdown-math-face)))
3801 (progn (goto-char (min (1+ begin) last))
3802 (when (< (point) last)
3803 (markdown-match-italic last)))
3804 (set-match-data (list (match-beginning 2) (match-end 2)
3805 (match-beginning 3) (match-end 3)
3806 (match-beginning 4) (match-end 4)
3807 (match-beginning 5) (match-end 5)))
3808 t))))
3810 (defun markdown-match-italic (last)
3811 "Match inline italics from the point to LAST."
3812 (let ((regex (if (eq major-mode 'gfm-mode)
3813 markdown-regex-gfm-italic markdown-regex-italic)))
3814 (when (markdown-match-inline-generic regex last)
3815 (let ((begin (match-beginning 1))
3816 (end (match-end 1)))
3817 (if (or (markdown-inline-code-at-pos-p begin)
3818 (markdown-inline-code-at-pos-p end)
3819 (markdown-in-comment-p)
3820 (markdown-range-property-any
3821 begin begin 'face '(markdown-url-face
3822 markdown-plain-url-face))
3823 (markdown-range-property-any
3824 begin end 'face '(markdown-bold-face
3825 markdown-list-face
3826 markdown-math-face)))
3827 (progn (goto-char (min (1+ begin) last))
3828 (when (< (point) last)
3829 (markdown-match-italic last)))
3830 (set-match-data (list (match-beginning 1) (match-end 1)
3831 (match-beginning 2) (match-end 2)
3832 (match-beginning 3) (match-end 3)
3833 (match-beginning 4) (match-end 4)))
3834 t)))))
3836 (defun markdown-match-math-generic (regex last)
3837 "Match REGEX from point to LAST.
3838 REGEX is either `markdown-regex-math-inline-single' for matching
3839 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
3840 (when (and markdown-enable-math (markdown-match-inline-generic regex last))
3841 (let ((begin (match-beginning 1)) (end (match-end 1)))
3842 (prog1
3843 (if (or (markdown-range-property-any
3844 begin end 'face (list markdown-inline-code-face
3845 markdown-bold-face))
3846 (markdown-range-properties-exist
3847 begin end
3848 (markdown-get-fenced-block-middle-properties)))
3849 (markdown-match-math-generic regex last)
3851 (goto-char (1+ (match-end 0)))))))
3853 (defun markdown-match-list-items (last)
3854 "Match list items from point to LAST."
3855 (when (markdown-match-inline-generic markdown-regex-list last)
3856 (let ((begin (match-beginning 2))
3857 (end (match-end 2)))
3858 (if (or (markdown-range-property-any
3859 begin end 'face (list markdown-inline-code-face
3860 markdown-bold-face
3861 markdown-math-face))
3862 (markdown-range-properties-exist begin end '(markdown-hr))
3863 (markdown-in-comment-p))
3864 (progn (goto-char (min (1+ (match-end 0)) last))
3865 (markdown-match-list-items last))
3866 (set-match-data (list (match-beginning 0) (match-end 0)
3867 (match-beginning 1) (match-end 1)
3868 (match-beginning 2) (match-end 2)))
3869 (goto-char (1+ (match-end 0)))))))
3871 (defun markdown-match-math-single (last)
3872 "Match single quoted $..$ math from point to LAST."
3873 (markdown-match-math-generic markdown-regex-math-inline-single last))
3875 (defun markdown-match-math-double (last)
3876 "Match double quoted $$..$$ math from point to LAST."
3877 (markdown-match-math-generic markdown-regex-math-inline-double last))
3879 (defun markdown-match-math-display (last)
3880 "Match bracketed display math \[..\] and \\[..\\] from point to LAST."
3881 (markdown-match-math-generic markdown-regex-math-display last))
3883 (defun markdown-match-propertized-text (property last)
3884 "Match text with PROPERTY from point to LAST.
3885 Restore match data previously stored in PROPERTY."
3886 (let ((saved (get-text-property (point) property))
3887 pos)
3888 (unless saved
3889 (setq pos (next-single-char-property-change (point) property nil last))
3890 (setq saved (get-text-property pos property)))
3891 (when saved
3892 (set-match-data saved)
3893 ;; Step at least one character beyond point. Otherwise
3894 ;; `font-lock-fontify-keywords-region' infloops.
3895 (goto-char (min (1+ (max (match-end 0) (point)))
3896 (point-max)))
3897 saved)))
3899 (defun markdown-match-pre-blocks (last)
3900 "Match preformatted blocks from point to LAST.
3901 Use data stored in 'markdown-pre text property during syntax
3902 analysis."
3903 (markdown-match-propertized-text 'markdown-pre last))
3905 (defun markdown-match-gfm-code-blocks (last)
3906 "Match GFM quoted code blocks from point to LAST.
3907 Use data stored in 'markdown-gfm-code text property during syntax
3908 analysis."
3909 (markdown-match-propertized-text 'markdown-gfm-code last))
3911 (defun markdown-match-gfm-open-code-blocks (last)
3912 (markdown-match-propertized-text 'markdown-gfm-block-begin last))
3914 (defun markdown-match-gfm-close-code-blocks (last)
3915 (markdown-match-propertized-text 'markdown-gfm-block-end last))
3917 (defun markdown-match-fenced-code-blocks (last)
3918 "Match fenced code blocks from the point to LAST."
3919 (markdown-match-propertized-text 'markdown-fenced-code last))
3921 (defun markdown-match-fenced-start-code-block (last)
3922 (markdown-match-propertized-text 'markdown-tilde-fence-begin last))
3924 (defun markdown-match-fenced-end-code-block (last)
3925 (markdown-match-propertized-text 'markdown-tilde-fence-end last))
3927 (defun markdown-match-blockquotes (last)
3928 "Match blockquotes from point to LAST.
3929 Use data stored in 'markdown-blockquote text property during syntax
3930 analysis."
3931 (markdown-match-propertized-text 'markdown-blockquote last))
3933 (defun markdown-match-hr (last)
3934 "Match horizontal rules comments from the point to LAST."
3935 (markdown-match-propertized-text 'markdown-hr last))
3937 (defun markdown-match-comments (last)
3938 "Match HTML comments from the point to LAST."
3939 (when (and (skip-syntax-forward "^<" last))
3940 (let ((beg (point)))
3941 (when (and (skip-syntax-forward "^>" last) (< (point) last))
3942 (forward-char)
3943 (set-match-data (list beg (point)))
3944 t))))
3946 (defun markdown-match-generic-links (last ref)
3947 "Match inline links from point to LAST.
3948 When REF is non-nil, match reference links instead of standard
3949 links with URLs."
3950 ;; Search for the next potential link (not in a code block).
3951 (while (and (progn
3952 ;; Clear match data to test for a match after functions returns.
3953 (set-match-data nil)
3954 (re-search-forward "\\(!\\)?\\(\\[\\)" last 'limit))
3955 ;; Keep searching if this is in a code block, inline
3956 ;; code, or a comment, or if it is include syntax.
3957 (or (markdown-code-block-at-point-p)
3958 (markdown-inline-code-at-pos-p (match-beginning 0))
3959 (markdown-inline-code-at-pos-p (match-end 0))
3960 (markdown-in-comment-p)
3961 (and (char-equal (char-after (point-at-bol)) ?<)
3962 (char-equal (char-after (1+ (point-at-bol))) ?<)))
3963 (< (point) last)))
3964 ;; Match opening exclamation point (optional) and left bracket.
3965 (when (match-beginning 2)
3966 (let* ((bang (match-beginning 1))
3967 (first-begin (match-beginning 2))
3968 ;; Find end of block to prevent matching across blocks.
3969 (end-of-block (save-excursion
3970 (progn
3971 (goto-char (match-beginning 2))
3972 (markdown-end-of-text-block)
3973 (point))))
3974 ;; Move over balanced expressions to closing right bracket.
3975 ;; Catch unbalanced expression errors and return nil.
3976 (first-end (condition-case nil
3977 (and (goto-char first-begin)
3978 (scan-sexps (point) 1))
3979 (error nil)))
3980 ;; Continue with point at CONT-POINT upon failure.
3981 (cont-point (min (1+ first-begin) last))
3982 second-begin second-end url-begin url-end
3983 title-begin title-end)
3984 ;; When bracket found, in range, and followed by a left paren/bracket...
3985 (when (and first-end (< first-end end-of-block) (goto-char first-end)
3986 (char-equal (char-after (point)) (if ref ?\[ ?\()))
3987 ;; Scan across balanced expressions for closing parenthesis/bracket.
3988 (setq second-begin (point)
3989 second-end (condition-case nil
3990 (scan-sexps (point) 1)
3991 (error nil)))
3992 ;; Check that closing parenthesis/bracket is in range.
3993 (if (and second-end (<= second-end end-of-block) (<= second-end last))
3994 (progn
3995 ;; Search for (optional) title inside closing parenthesis
3996 (when (and (not ref) (search-forward "\"" second-end t))
3997 (setq title-begin (1- (point))
3998 title-end (and (goto-char second-end)
3999 (search-backward "\"" (1+ title-begin) t))
4000 title-end (and title-end (1+ title-end))))
4001 ;; Store URL/reference range
4002 (setq url-begin (1+ second-begin)
4003 url-end (1- (or title-begin second-end)))
4004 ;; Set match data, move point beyond link, and return
4005 (set-match-data
4006 (list (or bang first-begin) second-end ; 0 - all
4007 bang (and bang (1+ bang)) ; 1 - bang
4008 first-begin (1+ first-begin) ; 2 - markup
4009 (1+ first-begin) (1- first-end) ; 3 - link text
4010 (1- first-end) first-end ; 4 - markup
4011 second-begin (1+ second-begin) ; 5 - markup
4012 url-begin url-end ; 6 - url/reference
4013 title-begin title-end ; 7 - title
4014 (1- second-end) second-end)) ; 8 - markup
4015 ;; Nullify cont-point and leave point at end and
4016 (setq cont-point nil)
4017 (goto-char second-end))
4018 ;; If no closing parenthesis in range, update continuation point
4019 (setq cont-point (min end-of-block second-begin))))
4020 (cond
4021 ;; On failure, continue searching at cont-point
4022 ((and cont-point (< cont-point last))
4023 (goto-char cont-point)
4024 (markdown-match-generic-links last ref))
4025 ;; No more text, return nil
4026 ((and cont-point (= cont-point last))
4027 nil)
4028 ;; Return t if a match occurred
4029 (t t)))))
4031 (defun markdown-match-inline-links (last)
4032 "Match standard inline links from point to LAST."
4033 (markdown-match-generic-links last nil))
4035 (defun markdown-match-reference-links (last)
4036 "Match inline reference links from point to LAST."
4037 (markdown-match-generic-links last t))
4039 (defun markdown-match-angle-uris (last)
4040 "Match angle bracket URIs from point to LAST."
4041 (when (markdown-match-inline-generic markdown-regex-angle-uri last)
4042 (goto-char (1+ (match-end 0)))))
4044 (defun markdown-match-plain-uris (last)
4045 "Match plain URIs from point to LAST."
4046 (when (markdown-match-inline-generic markdown-regex-uri last t)
4047 (goto-char (1+ (match-end 0)))))
4049 (defvar markdown-conditional-search-function #'re-search-forward
4050 "Conditional search function used in `markdown-search-until-condition'.
4051 Made into a variable to allow for dynamic let-binding.")
4053 (defun markdown-search-until-condition (condition &rest args)
4054 (let (ret)
4055 (while (and (not ret) (apply markdown-conditional-search-function args))
4056 (setq ret (funcall condition)))
4057 ret))
4059 (defun markdown-match-generic-metadata
4060 (regexp last &optional block-begin-re block-end-re)
4061 "Match metadata declarations specified by REGEXP from point to LAST.
4062 These declarations must appear inside a metadata block specified
4063 by BLOCK-BEGIN-RE and BLOCK-END-RE. BLOCK-BEGIN-RE is a regular
4064 expression denoting the beginning of a metadata block. If it is
4065 nil, we assume metadata can only appear at the beginning of the
4066 buffer. Similarly, BLOCK-END-RE is a regular expression denoting
4067 the end of a metadata block. If it is nil, assume blocks end with
4068 a blank line or the end of the buffer. There may be at most one such
4069 block in a file. Subsequent blocks will be ignored."
4070 (let* ((first (point))
4071 (begin-re (or block-begin-re "\\`"))
4072 (end-re (or block-end-re "\n[ \t]*\n\\|\n\\'\\|\\'"))
4074 ;; (prev-block-begin (when (re-search-backward begin-re (point-min) t) (match-end 0)))
4075 ;; (next-block-begin (when (re-search-forward begin-re last t) (match-end 0)))
4076 ;; (block-begin (or prev-block-begin next-block-begin))
4078 (block-begin (when (or (re-search-backward begin-re (point-min) t)
4079 (re-search-forward begin-re last t))
4080 (match-end 0)))
4082 (block-end (and block-begin (goto-char block-begin)
4083 (re-search-forward end-re nil t))))
4084 (cond
4085 ;; Don't match declarations if there is no metadata block or if
4086 ;; the point is beyond the block. Move point to point-max to
4087 ;; prevent additional searches and return return nil since nothing
4088 ;; was found.
4089 ((or (null block-begin) (and block-end (> first block-end)))
4090 (goto-char (point-max))
4091 nil)
4092 ;; No declarations to match if a block was found but not in
4093 ;; range. Move point to LAST, to resume there, and return nil.
4094 ((> block-begin last)
4095 (goto-char last)
4096 nil)
4097 ;; If a block was found that begins before LAST and ends after
4098 ;; point, search for declarations inside it.
4100 ;; If the starting is before the beginning of the block, start
4101 ;; there. Otherwise, move back to FIRST.
4102 (goto-char (if (< first block-begin) block-begin first))
4103 (if (re-search-forward regexp (min last block-end) t)
4104 ;; If a metadata declaration is found, set match-data and return t.
4105 (let ((key-beginning (match-beginning 1))
4106 (key-end (match-end 1))
4107 (markup-begin (match-beginning 2))
4108 (markup-end (match-end 2))
4109 (value-beginning (match-beginning 3)))
4110 (set-match-data (list key-beginning (point) ; complete metadata
4111 key-beginning key-end ; key
4112 markup-begin markup-end ; markup
4113 value-beginning (point))) ; value
4115 ;; Otherwise, move the point to last and return nil
4116 (goto-char last)
4117 nil)))))
4119 (defun markdown-match-declarative-metadata (last)
4120 "Match declarative metadata from the point to LAST."
4121 (markdown-match-generic-metadata markdown-regex-declarative-metadata last))
4123 (defun markdown-match-pandoc-metadata (last)
4124 "Match Pandoc metadata from the point to LAST."
4125 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
4127 (defun markdown-match-yaml-metadata-begin (last)
4128 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last))
4130 (defun markdown-match-yaml-metadata-end (last)
4131 (markdown-match-propertized-text 'markdown-yaml-metadata-end last))
4133 (defun markdown-match-yaml-metadata-key (last)
4134 (markdown-match-propertized-text 'markdown-metadata-key last))
4136 (defun markdown-match-wiki-link (last)
4137 "Match wiki links from point to LAST."
4138 (when (and markdown-enable-wiki-links
4139 (not markdown-wiki-link-fontify-missing)
4140 (markdown-match-inline-generic markdown-regex-wiki-link last))
4141 (let ((begin (match-beginning 1)) (end (match-end 1)))
4142 (if (or (markdown-in-comment-p begin)
4143 (markdown-in-comment-p end)
4144 (markdown-inline-code-at-pos-p begin)
4145 (markdown-inline-code-at-pos-p end)
4146 (markdown-code-block-at-pos begin))
4147 (progn (goto-char (min (1+ begin) last))
4148 (when (< (point) last)
4149 (markdown-match-wiki-link last)))
4150 (set-match-data (list begin end))
4151 t))))
4153 (defun markdown-match-inline-attributes (last)
4154 "Match inline attributes from point to LAST."
4155 (when (markdown-match-inline-generic markdown-regex-inline-attributes last)
4156 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
4157 (markdown-inline-code-at-pos-p (match-end 0))
4158 (markdown-in-comment-p))
4159 t)))
4161 (defun markdown-match-leanpub-sections (last)
4162 "Match Leanpub section markers from point to LAST."
4163 (when (markdown-match-inline-generic markdown-regex-leanpub-sections last)
4164 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
4165 (markdown-inline-code-at-pos-p (match-end 0))
4166 (markdown-in-comment-p))
4167 t)))
4169 (defun markdown-match-includes (last)
4170 "Match include statements from point to LAST.
4171 Sets match data for the following seven groups:
4172 Group 1: opening two angle brackets
4173 Group 2: opening title delimiter (optional)
4174 Group 3: title text (optional)
4175 Group 4: closing title delimiter (optional)
4176 Group 5: opening filename delimiter
4177 Group 6: filename
4178 Group 7: closing filename delimiter"
4179 (when (markdown-match-inline-generic markdown-regex-include last)
4180 (let ((valid (not (or (markdown-in-comment-p (match-beginning 0))
4181 (markdown-in-comment-p (match-end 0))
4182 (markdown-code-block-at-pos (match-beginning 0))))))
4183 (cond
4184 ;; Parentheses and maybe square brackets, but no curly braces:
4185 ;; match optional title in square brackets and file in parentheses.
4186 ((and valid (match-beginning 5)
4187 (not (match-beginning 8)))
4188 (set-match-data (list (match-beginning 1) (match-end 7)
4189 (match-beginning 1) (match-end 1)
4190 (match-beginning 2) (match-end 2)
4191 (match-beginning 3) (match-end 3)
4192 (match-beginning 4) (match-end 4)
4193 (match-beginning 5) (match-end 5)
4194 (match-beginning 6) (match-end 6)
4195 (match-beginning 7) (match-end 7))))
4196 ;; Only square brackets present: match file in square brackets.
4197 ((and valid (match-beginning 2)
4198 (not (match-beginning 5))
4199 (not (match-beginning 7)))
4200 (set-match-data (list (match-beginning 1) (match-end 4)
4201 (match-beginning 1) (match-end 1)
4202 nil nil
4203 nil nil
4204 nil nil
4205 (match-beginning 2) (match-end 2)
4206 (match-beginning 3) (match-end 3)
4207 (match-beginning 4) (match-end 4))))
4208 ;; Only curly braces present: match file in curly braces.
4209 ((and valid (match-beginning 8)
4210 (not (match-beginning 2))
4211 (not (match-beginning 5)))
4212 (set-match-data (list (match-beginning 1) (match-end 10)
4213 (match-beginning 1) (match-end 1)
4214 nil nil
4215 nil nil
4216 nil nil
4217 (match-beginning 8) (match-end 8)
4218 (match-beginning 9) (match-end 9)
4219 (match-beginning 10) (match-end 10))))
4221 ;; Not a valid match, move to next line and search again.
4222 (forward-line)
4223 (when (< (point) last)
4224 (setq valid (markdown-match-includes last)))))
4225 valid)))
4227 (defun markdown-match-html-tag (last)
4228 "Match HTML tags from point to LAST."
4229 (when (and markdown-enable-html
4230 (markdown-match-inline-generic markdown-regex-html-tag last t))
4231 (set-match-data (list (match-beginning 0) (match-end 0)
4232 (match-beginning 1) (match-end 1)
4233 (match-beginning 2) (match-end 2)
4234 (match-beginning 9) (match-end 9)))
4238 ;;; Markdown Font Fontification Functions =====================================
4240 (defun markdown--first-displayable (seq)
4241 "Return the first displayable character or string in SEQ.
4242 SEQ may be an atom or a sequence."
4243 (let ((seq (if (listp seq) seq (list seq))))
4244 (cond ((stringp (car seq))
4245 (cl-find-if
4246 (lambda (str)
4247 (and (mapcar #'char-displayable-p (string-to-list str))))
4248 seq))
4249 ((characterp (car seq))
4250 (cl-find-if #'char-displayable-p seq)))))
4252 (defun markdown--marginalize-string (level)
4253 "Generate atx markup string of given LEVEL for left margin."
4254 (let ((margin-left-space-count
4255 (- markdown-marginalize-headers-margin-width level)))
4256 (concat (make-string margin-left-space-count ? )
4257 (make-string level ?#))))
4259 (defun markdown-marginalize-update-current ()
4260 "Update the window configuration to create a left margin."
4261 ;; Emacs 25 or later is needed for window-font-width and default-font-width.
4262 (if (and (fboundp 'window-font-width) (fboundp 'default-font-width))
4263 (let* ((header-delimiter-font-width
4264 (window-font-width nil 'markdown-header-delimiter-face))
4265 (margin-pixel-width (* markdown-marginalize-headers-margin-width
4266 header-delimiter-font-width))
4267 (margin-char-width (/ margin-pixel-width (default-font-width))))
4268 (set-window-margins nil margin-char-width))
4269 ;; As a fallback, simply set margin based on character count.
4270 (set-window-margins nil markdown-marginalize-headers-margin-width)))
4272 (defun markdown-fontify-headings (last)
4273 "Add text properties to headings from point to LAST."
4274 (when (markdown-match-propertized-text 'markdown-heading last)
4275 (let* ((level (markdown-outline-level))
4276 (heading-face
4277 (intern (format "markdown-header-face-%d" level)))
4278 (heading-props `(face ,heading-face))
4279 (left-markup-props
4280 `(face markdown-header-delimiter-face
4281 ,@(cond
4282 (markdown-hide-markup
4283 `(display ""))
4284 (markdown-marginalize-headers
4285 `(display ((margin left-margin)
4286 ,(markdown--marginalize-string level)))))))
4287 (right-markup-props
4288 `(face markdown-header-delimiter-face
4289 ,@(when markdown-hide-markup `(display ""))))
4290 (rule-props `(face markdown-header-rule-face
4291 ,@(when markdown-hide-markup `(display "")))))
4292 (if (match-end 1)
4293 ;; Setext heading
4294 (progn (add-text-properties
4295 (match-beginning 1) (match-end 1) heading-props)
4296 (if (= level 1)
4297 (add-text-properties
4298 (match-beginning 2) (match-end 2) rule-props)
4299 (add-text-properties
4300 (match-beginning 3) (match-end 3) rule-props)))
4301 ;; atx heading
4302 (add-text-properties
4303 (match-beginning 4) (match-end 4) left-markup-props)
4304 (add-text-properties
4305 (match-beginning 5) (match-end 5) heading-props)
4306 (when (match-end 6)
4307 (add-text-properties
4308 (match-beginning 6) (match-end 6) right-markup-props))))
4311 (defun markdown-fontify-tables (last)
4312 (when (and (re-search-forward "|" last t)
4313 (markdown-table-at-point-p))
4314 (font-lock-append-text-property
4315 (line-beginning-position) (min (1+ (line-end-position)) (point-max))
4316 'face 'markdown-table-face)
4317 (forward-line 1)
4320 (defun markdown-fontify-blockquotes (last)
4321 "Apply font-lock properties to blockquotes from point to LAST."
4322 (when (markdown-match-blockquotes last)
4323 (let ((display-string
4324 (markdown--first-displayable markdown-blockquote-display-char)))
4325 (add-text-properties
4326 (match-beginning 1) (match-end 1)
4327 (if markdown-hide-markup
4328 `(face markdown-blockquote-face display ,display-string)
4329 `(face markdown-markup-face)))
4330 (font-lock-append-text-property
4331 (match-beginning 0) (match-end 0) 'face 'markdown-blockquote-face)
4332 t)))
4334 (defun markdown-fontify-list-items (last)
4335 "Apply font-lock properties to list markers from point to LAST."
4336 (when (markdown-match-list-items last)
4337 (let* ((indent (length (match-string-no-properties 1)))
4338 (level (/ indent 4)) ;; level = 0, 1, 2, ...
4339 (bullet (nth (mod level (length markdown-list-item-bullets))
4340 markdown-list-item-bullets)))
4341 (add-text-properties
4342 (match-beginning 2) (match-end 2) '(face markdown-list-face))
4343 (when markdown-hide-markup
4344 (cond
4345 ;; Unordered lists
4346 ((string-match-p "[\\*\\+-]" (match-string 2))
4347 (add-text-properties
4348 (match-beginning 2) (match-end 2) `(display ,bullet)))
4349 ;; Definition lists
4350 ((string-equal ":" (match-string 2))
4351 (let ((display-string
4352 (char-to-string (markdown--first-displayable
4353 markdown-definition-display-char))))
4354 (add-text-properties (match-beginning 2) (match-end 2)
4355 `(display ,display-string)))))))
4358 (defun markdown-fontify-hrs (last)
4359 "Add text properties to horizontal rules from point to LAST."
4360 (when (markdown-match-hr last)
4361 (let ((hr-char (markdown--first-displayable markdown-hr-display-char)))
4362 (add-text-properties
4363 (match-beginning 0) (match-end 0)
4364 `(face markdown-hr-face
4365 font-lock-multiline t
4366 ,@(when (and markdown-hide-markup hr-char)
4367 `(display ,(make-string
4368 (window-body-width) hr-char)))))
4369 t)))
4371 (defun markdown-fontify-sub-superscripts (last)
4372 "Apply text properties to sub- and superscripts from point to LAST."
4373 (when (markdown-search-until-condition
4374 (lambda () (and (not (markdown-code-block-at-point-p))
4375 (not (markdown-inline-code-at-point-p))
4376 (not (markdown-in-comment-p))))
4377 markdown-regex-sub-superscript last t)
4378 (let* ((subscript-p (string= (match-string 2) "~"))
4379 (index (if subscript-p 0 1))
4380 (mp (list 'face 'markdown-markup-face
4381 'invisible 'markdown-markup)))
4382 (when markdown-hide-markup
4383 (put-text-property (match-beginning 3) (match-end 3)
4384 'display
4385 (nth index markdown-sub-superscript-display)))
4386 (add-text-properties (match-beginning 2) (match-end 2) mp)
4387 (add-text-properties (match-beginning 4) (match-end 4) mp)
4388 t)))
4391 ;;; Syntax Table ==============================================================
4393 (defvar markdown-mode-syntax-table
4394 (let ((tab (make-syntax-table text-mode-syntax-table)))
4395 (modify-syntax-entry ?\" "." tab)
4396 tab)
4397 "Syntax table for `markdown-mode'.")
4400 ;;; Element Insertion =========================================================
4402 (defun markdown-ensure-blank-line-before ()
4403 "If previous line is not already blank, insert a blank line before point."
4404 (unless (bolp) (insert "\n"))
4405 (unless (or (bobp) (looking-back "\n\\s-*\n" nil)) (insert "\n")))
4407 (defun markdown-ensure-blank-line-after ()
4408 "If following line is not already blank, insert a blank line after point.
4409 Return the point where it was originally."
4410 (save-excursion
4411 (unless (eolp) (insert "\n"))
4412 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
4414 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
4415 "Insert the strings S1 and S2, wrapping around region or THING.
4416 If a region is specified by the optional BEG and END arguments,
4417 wrap the strings S1 and S2 around that region.
4418 If there is an active region, wrap the strings S1 and S2 around
4419 the region. If there is not an active region but the point is at
4420 THING, wrap that thing (which defaults to word). Otherwise, just
4421 insert S1 and S2 and place the point in between. Return the
4422 bounds of the entire wrapped string, or nil if nothing was wrapped
4423 and S1 and S2 were only inserted."
4424 (let (a b bounds new-point)
4425 (cond
4426 ;; Given region
4427 ((and beg end)
4428 (setq a beg
4429 b end
4430 new-point (+ (point) (length s1))))
4431 ;; Active region
4432 ((markdown-use-region-p)
4433 (setq a (region-beginning)
4434 b (region-end)
4435 new-point (+ (point) (length s1))))
4436 ;; Thing (word) at point
4437 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
4438 (setq a (car bounds)
4439 b (cdr bounds)
4440 new-point (+ (point) (length s1))))
4441 ;; No active region and no word
4443 (setq a (point)
4444 b (point))))
4445 (goto-char b)
4446 (insert s2)
4447 (goto-char a)
4448 (insert s1)
4449 (when new-point (goto-char new-point))
4450 (if (= a b)
4452 (setq b (+ b (length s1) (length s2)))
4453 (cons a b))))
4455 (defun markdown-point-after-unwrap (cur prefix suffix)
4456 "Return desired position of point after an unwrapping operation.
4457 CUR gives the position of the point before the operation.
4458 Additionally, two cons cells must be provided. PREFIX gives the
4459 bounds of the prefix string and SUFFIX gives the bounds of the
4460 suffix string."
4461 (cond ((< cur (cdr prefix)) (car prefix))
4462 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
4463 ((<= cur (cdr suffix))
4464 (- cur (+ (- (cdr prefix) (car prefix))
4465 (- cur (car suffix)))))
4466 (t cur)))
4468 (defun markdown-unwrap-thing-at-point (regexp all text)
4469 "Remove prefix and suffix of thing at point and reposition the point.
4470 When the thing at point matches REGEXP, replace the subexpression
4471 ALL with the string in subexpression TEXT. Reposition the point
4472 in an appropriate location accounting for the removal of prefix
4473 and suffix strings. Return new bounds of string from group TEXT.
4474 When REGEXP is nil, assumes match data is already set."
4475 (when (or (null regexp)
4476 (thing-at-point-looking-at regexp))
4477 (let ((cur (point))
4478 (prefix (cons (match-beginning all) (match-beginning text)))
4479 (suffix (cons (match-end text) (match-end all)))
4480 (bounds (cons (match-beginning text) (match-end text))))
4481 ;; Replace the thing at point
4482 (replace-match (match-string text) t t nil all)
4483 ;; Reposition the point
4484 (goto-char (markdown-point-after-unwrap cur prefix suffix))
4485 ;; Adjust bounds
4486 (setq bounds (cons (car prefix)
4487 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
4489 (defun markdown-unwrap-things-in-region (beg end regexp all text)
4490 "Remove prefix and suffix of all things in region from BEG to END.
4491 When a thing in the region matches REGEXP, replace the
4492 subexpression ALL with the string in subexpression TEXT.
4493 Return a cons cell containing updated bounds for the region."
4494 (save-excursion
4495 (goto-char beg)
4496 (let ((removed 0) len-all len-text)
4497 (while (re-search-forward regexp (- end removed) t)
4498 (setq len-all (length (match-string-no-properties all)))
4499 (setq len-text (length (match-string-no-properties text)))
4500 (setq removed (+ removed (- len-all len-text)))
4501 (replace-match (match-string text) t t nil all))
4502 (cons beg (- end removed)))))
4504 (defun markdown-insert-hr (arg)
4505 "Insert or replace a horizonal rule.
4506 By default, use the first element of `markdown-hr-strings'. When
4507 ARG is non-nil, as when given a prefix, select a different
4508 element as follows. When prefixed with \\[universal-argument],
4509 use the last element of `markdown-hr-strings' instead. When
4510 prefixed with an integer from 1 to the length of
4511 `markdown-hr-strings', use the element in that position instead."
4512 (interactive "*P")
4513 (when (thing-at-point-looking-at markdown-regex-hr)
4514 (delete-region (match-beginning 0) (match-end 0)))
4515 (markdown-ensure-blank-line-before)
4516 (cond ((equal arg '(4))
4517 (insert (car (reverse markdown-hr-strings))))
4518 ((and (integerp arg) (> arg 0)
4519 (<= arg (length markdown-hr-strings)))
4520 (insert (nth (1- arg) markdown-hr-strings)))
4522 (insert (car markdown-hr-strings))))
4523 (markdown-ensure-blank-line-after))
4525 (defun markdown-insert-bold ()
4526 "Insert markup to make a region or word bold.
4527 If there is an active region, make the region bold. If the point
4528 is at a non-bold word, make the word bold. If the point is at a
4529 bold word or phrase, remove the bold markup. Otherwise, simply
4530 insert bold delimiters and place the point in between them."
4531 (interactive)
4532 (let ((delim (if markdown-bold-underscore "__" "**")))
4533 (if (markdown-use-region-p)
4534 ;; Active region
4535 (let ((bounds (markdown-unwrap-things-in-region
4536 (region-beginning) (region-end)
4537 markdown-regex-bold 2 4)))
4538 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4539 ;; Bold markup removal, bold word at point, or empty markup insertion
4540 (if (thing-at-point-looking-at markdown-regex-bold)
4541 (markdown-unwrap-thing-at-point nil 2 4)
4542 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4544 (defun markdown-insert-italic ()
4545 "Insert markup to make a region or word italic.
4546 If there is an active region, make the region italic. If the point
4547 is at a non-italic word, make the word italic. If the point is at an
4548 italic word or phrase, remove the italic markup. Otherwise, simply
4549 insert italic delimiters and place the point in between them."
4550 (interactive)
4551 (let ((delim (if markdown-italic-underscore "_" "*")))
4552 (if (markdown-use-region-p)
4553 ;; Active region
4554 (let ((bounds (markdown-unwrap-things-in-region
4555 (region-beginning) (region-end)
4556 markdown-regex-italic 1 3)))
4557 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4558 ;; Italic markup removal, italic word at point, or empty markup insertion
4559 (if (thing-at-point-looking-at markdown-regex-italic)
4560 (markdown-unwrap-thing-at-point nil 1 3)
4561 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4563 (defun markdown-insert-strike-through ()
4564 "Insert markup to make a region or word strikethrough.
4565 If there is an active region, make the region strikethrough. If the point
4566 is at a non-bold word, make the word strikethrough. If the point is at a
4567 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
4568 simply insert bold delimiters and place the point in between them."
4569 (interactive)
4570 (let ((delim "~~"))
4571 (if (markdown-use-region-p)
4572 ;; Active region
4573 (let ((bounds (markdown-unwrap-things-in-region
4574 (region-beginning) (region-end)
4575 markdown-regex-strike-through 2 4)))
4576 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4577 ;; Strikethrough markup removal, strikethrough word at point, or empty markup insertion
4578 (if (thing-at-point-looking-at markdown-regex-strike-through)
4579 (markdown-unwrap-thing-at-point nil 2 4)
4580 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4582 (defun markdown-insert-code ()
4583 "Insert markup to make a region or word an inline code fragment.
4584 If there is an active region, make the region an inline code
4585 fragment. If the point is at a word, make the word an inline
4586 code fragment. Otherwise, simply insert code delimiters and
4587 place the point in between them."
4588 (interactive)
4589 (if (markdown-use-region-p)
4590 ;; Active region
4591 (let ((bounds (markdown-unwrap-things-in-region
4592 (region-beginning) (region-end)
4593 markdown-regex-code 1 3)))
4594 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
4595 ;; Code markup removal, code markup for word, or empty markup insertion
4596 (if (markdown-inline-code-at-point)
4597 (markdown-unwrap-thing-at-point nil 0 2)
4598 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
4600 (defun markdown-insert-kbd ()
4601 "Insert markup to wrap region or word in <kbd> tags.
4602 If there is an active region, use the region. If the point is at
4603 a word, use the word. Otherwise, simply insert <kbd> tags and
4604 place the point in between them."
4605 (interactive)
4606 (if (markdown-use-region-p)
4607 ;; Active region
4608 (let ((bounds (markdown-unwrap-things-in-region
4609 (region-beginning) (region-end)
4610 markdown-regex-kbd 0 2)))
4611 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil (car bounds) (cdr bounds)))
4612 ;; Markup removal, markup for word, or empty markup insertion
4613 (if (thing-at-point-looking-at markdown-regex-kbd)
4614 (markdown-unwrap-thing-at-point nil 0 2)
4615 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil))))
4617 (defun markdown-insert-inline-link (text url &optional title)
4618 "Insert an inline link with TEXT pointing to URL.
4619 Optionally, the user can provide a TITLE."
4620 (let ((cur (point)))
4621 (setq title (and title (concat " \"" title "\"")))
4622 (insert (concat "[" text "](" url title ")"))
4623 (cond ((not text) (goto-char (+ 1 cur)))
4624 ((not url) (goto-char (+ 3 (length text) cur))))))
4626 (defun markdown-insert-inline-image (text url &optional title)
4627 "Insert an inline link with alt TEXT pointing to URL.
4628 Optionally, also provide a TITLE."
4629 (let ((cur (point)))
4630 (setq title (and title (concat " \"" title "\"")))
4631 (insert (concat "![" text "](" url title ")"))
4632 (cond ((not text) (goto-char (+ 2 cur)))
4633 ((not url) (goto-char (+ 4 (length text) cur))))))
4635 (defun markdown-insert-reference-link (text label &optional url title)
4636 "Insert a reference link and, optionally, a reference definition.
4637 The link TEXT will be inserted followed by the optional LABEL.
4638 If a URL is given, also insert a definition for the reference
4639 LABEL according to `markdown-reference-location'. If a TITLE is
4640 given, it will be added to the end of the reference definition
4641 and will be used to populate the title attribute when converted
4642 to XHTML. If URL is nil, insert only the link portion (for
4643 example, when a reference label is already defined)."
4644 (insert (concat "[" text "][" label "]"))
4645 (when url
4646 (markdown-insert-reference-definition
4647 (if (string-equal label "") text label)
4648 url title)))
4650 (defun markdown-insert-reference-image (text label &optional url title)
4651 "Insert a reference image and, optionally, a reference definition.
4652 The alt TEXT will be inserted followed by the optional LABEL.
4653 If a URL is given, also insert a definition for the reference
4654 LABEL according to `markdown-reference-location'. If a TITLE is
4655 given, it will be added to the end of the reference definition
4656 and will be used to populate the title attribute when converted
4657 to XHTML. If URL is nil, insert only the link portion (for
4658 example, when a reference label is already defined)."
4659 (insert (concat "![" text "][" label "]"))
4660 (when url
4661 (markdown-insert-reference-definition
4662 (if (string-equal label "") text label)
4663 url title)))
4665 (defun markdown-insert-reference-definition (label &optional url title)
4666 "Add definition for reference LABEL with URL and TITLE.
4667 LABEL is a Markdown reference label without square brackets.
4668 URL and TITLE are optional. When given, the TITLE will
4669 be used to populate the title attribute when converted to XHTML."
4670 ;; END specifies where to leave the point upon return
4671 (let ((end (point)))
4672 (cl-case markdown-reference-location
4673 (end (goto-char (point-max)))
4674 (immediately (markdown-end-of-text-block))
4675 (subtree (markdown-end-of-subtree))
4676 (header (markdown-end-of-defun)))
4677 ;; Skip backwards over local variables. This logic is similar to the one
4678 ;; used in ‘hack-local-variables’.
4679 (when (and enable-local-variables (eobp))
4680 (search-backward "\n\f" (max (- (point) 3000) (point-min)) :move)
4681 (when (let ((case-fold-search t))
4682 (search-forward "Local Variables:" nil :move))
4683 (beginning-of-line 0)
4684 (when (eq (char-before) ?\n) (backward-char))))
4685 (unless (or (markdown-cur-line-blank-p)
4686 (thing-at-point-looking-at markdown-regex-reference-definition))
4687 (insert "\n"))
4688 (insert "\n[" label "]: ")
4689 (if url
4690 (insert url)
4691 ;; When no URL is given, leave point at END following the colon
4692 (setq end (point)))
4693 (when (> (length title) 0)
4694 (insert " \"" title "\""))
4695 (unless (looking-at-p "\n")
4696 (insert "\n"))
4697 (goto-char end)
4698 (when url
4699 (message
4700 (markdown--substitute-command-keys
4701 "Reference [%s] was defined, press \\[markdown-do] to jump there")
4702 label))))
4704 (define-obsolete-function-alias
4705 'markdown-insert-inline-link-dwim 'markdown-insert-link "v2.3")
4706 (define-obsolete-function-alias
4707 'markdown-insert-reference-link-dwim 'markdown-insert-link "v2.3")
4709 (defun markdown--insert-link-or-image (image)
4710 "Interactively insert new or update an existing link or image.
4711 When IMAGE is non-nil, insert an image. Otherwise, insert a link.
4712 This is an internal function called by
4713 `markdown-insert-link' and `markdown-insert-image'."
4714 (cl-multiple-value-bind (begin end text uri ref title)
4715 (if (markdown-use-region-p)
4716 ;; Use region as either link text or URL as appropriate.
4717 (let ((region (buffer-substring-no-properties
4718 (region-beginning) (region-end))))
4719 (if (string-match markdown-regex-uri region)
4720 ;; Region contains a URL; use it as such.
4721 (list (region-beginning) (region-end)
4722 nil (match-string 0 region) nil nil)
4723 ;; Region doesn't contain a URL, so use it as text.
4724 (list (region-beginning) (region-end)
4725 region nil nil nil)))
4726 ;; Extract and use properties of existing link, if any.
4727 (markdown-link-at-pos (point)))
4728 (let* ((ref (when ref (concat "[" ref "]")))
4729 (defined-refs (append
4730 (mapcar (lambda (ref) (concat "[" ref "]"))
4731 (markdown-get-defined-references))))
4732 (used-uris (markdown-get-used-uris))
4733 (uri-or-ref (completing-read
4734 "URL or [reference]: "
4735 (append defined-refs used-uris)
4736 nil nil (or uri ref)))
4737 (ref (cond ((string-match "\\`\\[\\(.*\\)\\]\\'" uri-or-ref)
4738 (match-string 1 uri-or-ref))
4739 ((string-equal "" uri-or-ref)
4740 "")))
4741 (uri (unless ref uri-or-ref))
4742 (text-prompt (if image
4743 "Alt text: "
4744 (if ref
4745 "Link text: "
4746 "Link text (blank for plain URL): ")))
4747 (text (read-string text-prompt text))
4748 (text (if (= (length text) 0) nil text))
4749 (plainp (and uri (not text)))
4750 (implicitp (string-equal ref ""))
4751 (ref (if implicitp text ref))
4752 (definedp (and ref (markdown-reference-definition ref)))
4753 (ref-url (unless (or uri definedp)
4754 (completing-read "Reference URL: " used-uris)))
4755 (title (unless (or plainp definedp)
4756 (read-string "Title (tooltip text, optional): " title)))
4757 (title (if (= (length title) 0) nil title)))
4758 (when (and image implicitp)
4759 (user-error "Reference required: implicit image references are invalid"))
4760 (when (and begin end)
4761 (delete-region begin end))
4762 (cond
4763 ((and (not image) uri text)
4764 (markdown-insert-inline-link text uri title))
4765 ((and image uri text)
4766 (markdown-insert-inline-image text uri title))
4767 ((and ref text)
4768 (if image
4769 (markdown-insert-reference-image text (unless implicitp ref) nil title)
4770 (markdown-insert-reference-link text (unless implicitp ref) nil title))
4771 (unless definedp
4772 (markdown-insert-reference-definition ref ref-url title)))
4773 ((and (not image) uri)
4774 (markdown-insert-uri uri))))))
4776 (defun markdown-insert-link ()
4777 "Insert new or update an existing link, with interactive prompts.
4778 If the point is at an existing link or URL, update the link text,
4779 URL, reference label, and/or title. Otherwise, insert a new link.
4780 The type of link inserted (inline, reference, or plain URL)
4781 depends on which values are provided:
4783 * If a URL and TEXT are given, insert an inline link: [TEXT](URL).
4784 * If [REF] and TEXT are given, insert a reference link: [TEXT][REF].
4785 * If only TEXT is given, insert an implicit reference link: [TEXT][].
4786 * If only a URL is given, insert a plain link: <URL>.
4788 In other words, to create an implicit reference link, leave the
4789 URL prompt empty and to create a plain URL link, leave the link
4790 text empty.
4792 If there is an active region, use the text as the default URL, if
4793 it seems to be a URL, or link text value otherwise.
4795 If a given reference is not defined, this function will
4796 additionally prompt for the URL and optional title. In this case,
4797 the reference definition is placed at the location determined by
4798 `markdown-reference-location'.
4800 Through updating the link, this function can be used to convert a
4801 link of one type (inline, reference, or plain) to another type by
4802 selectively adding or removing information via the prompts."
4803 (interactive)
4804 (markdown--insert-link-or-image nil))
4806 (defun markdown-insert-image ()
4807 "Insert new or update an existing image, with interactive prompts.
4808 If the point is at an existing image, update the alt text, URL,
4809 reference label, and/or title. Otherwise, insert a new image.
4810 The type of image inserted (inline or reference) depends on which
4811 values are provided:
4813 * If a URL and ALT-TEXT are given, insert an inline image:
4814 ![ALT-TEXT](URL).
4815 * If [REF] and ALT-TEXT are given, insert a reference image:
4816 ![ALT-TEXT][REF].
4818 If there is an active region, use the text as the default URL, if
4819 it seems to be a URL, or alt text value otherwise.
4821 If a given reference is not defined, this function will
4822 additionally prompt for the URL and optional title. In this case,
4823 the reference definition is placed at the location determined by
4824 `markdown-reference-location'.
4826 Through updating the image, this function can be used to convert an
4827 image of one type (inline or reference) to another type by
4828 selectively adding or removing information via the prompts."
4829 (interactive)
4830 (markdown--insert-link-or-image t))
4832 (defun markdown-insert-uri (&optional uri)
4833 "Insert markup for an inline URI.
4834 If there is an active region, use it as the URI. If the point is
4835 at a URI, wrap it with angle brackets. If the point is at an
4836 inline URI, remove the angle brackets. Otherwise, simply insert
4837 angle brackets place the point between them."
4838 (interactive)
4839 (if (markdown-use-region-p)
4840 ;; Active region
4841 (let ((bounds (markdown-unwrap-things-in-region
4842 (region-beginning) (region-end)
4843 markdown-regex-angle-uri 0 2)))
4844 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
4845 ;; Markup removal, URI at point, new URI, or empty markup insertion
4846 (if (thing-at-point-looking-at markdown-regex-angle-uri)
4847 (markdown-unwrap-thing-at-point nil 0 2)
4848 (if uri
4849 (insert "<" uri ">")
4850 (markdown-wrap-or-insert "<" ">" 'url nil nil)))))
4852 (defun markdown-insert-wiki-link ()
4853 "Insert a wiki link of the form [[WikiLink]].
4854 If there is an active region, use the region as the link text.
4855 If the point is at a word, use the word as the link text. If
4856 there is no active region and the point is not at word, simply
4857 insert link markup."
4858 (interactive)
4859 (if (markdown-use-region-p)
4860 ;; Active region
4861 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
4862 ;; Markup removal, wiki link at at point, or empty markup insertion
4863 (if (thing-at-point-looking-at markdown-regex-wiki-link)
4864 (if (or markdown-wiki-link-alias-first
4865 (null (match-string 5)))
4866 (markdown-unwrap-thing-at-point nil 1 3)
4867 (markdown-unwrap-thing-at-point nil 1 5))
4868 (markdown-wrap-or-insert "[[" "]]"))))
4870 (defun markdown-remove-header ()
4871 "Remove header markup if point is at a header.
4872 Return bounds of remaining header text if a header was removed
4873 and nil otherwise."
4874 (interactive "*")
4875 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
4876 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
4878 (defun markdown-insert-header (&optional level text setext)
4879 "Insert or replace header markup.
4880 The level of the header is specified by LEVEL and header text is
4881 given by TEXT. LEVEL must be an integer from 1 and 6, and the
4882 default value is 1.
4883 When TEXT is nil, the header text is obtained as follows.
4884 If there is an active region, it is used as the header text.
4885 Otherwise, the current line will be used as the header text.
4886 If there is not an active region and the point is at a header,
4887 remove the header markup and replace with level N header.
4888 Otherwise, insert empty header markup and place the point in
4889 between.
4890 The style of the header will be atx (hash marks) unless
4891 SETEXT is non-nil, in which case a setext-style (underlined)
4892 header will be inserted."
4893 (interactive "p\nsHeader text: ")
4894 (setq level (min (max (or level 1) 1) (if setext 2 6)))
4895 ;; Determine header text if not given
4896 (when (null text)
4897 (if (markdown-use-region-p)
4898 ;; Active region
4899 (setq text (delete-and-extract-region (region-beginning) (region-end)))
4900 ;; No active region
4901 (markdown-remove-header)
4902 (setq text (delete-and-extract-region
4903 (line-beginning-position) (line-end-position)))
4904 (when (and setext (string-match-p "^[ \t]*$" text))
4905 (setq text (read-string "Header text: "))))
4906 (setq text (markdown-compress-whitespace-string text)))
4907 ;; Insertion with given text
4908 (markdown-ensure-blank-line-before)
4909 (let (hdr)
4910 (cond (setext
4911 (setq hdr (make-string (string-width text) (if (= level 2) ?- ?=)))
4912 (insert text "\n" hdr))
4914 (setq hdr (make-string level ?#))
4915 (insert hdr " " text)
4916 (when (null markdown-asymmetric-header) (insert " " hdr)))))
4917 (markdown-ensure-blank-line-after)
4918 ;; Leave point at end of text
4919 (cond (setext
4920 (backward-char (1+ (string-width text))))
4921 ((null markdown-asymmetric-header)
4922 (backward-char (1+ level)))))
4924 (defun markdown-insert-header-dwim (&optional arg setext)
4925 "Insert or replace header markup.
4926 The level and type of the header are determined automatically by
4927 the type and level of the previous header, unless a prefix
4928 argument is given via ARG.
4929 With a numeric prefix valued 1 to 6, insert a header of the given
4930 level, with the type being determined automatically (note that
4931 only level 1 or 2 setext headers are possible).
4933 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
4934 promote the heading by one level.
4935 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
4936 demote the heading by one level.
4937 When SETEXT is non-nil, prefer setext-style headers when
4938 possible (levels one and two).
4940 When there is an active region, use it for the header text. When
4941 the point is at an existing header, change the type and level
4942 according to the rules above.
4943 Otherwise, if the line is not empty, create a header using the
4944 text on the current line as the header text.
4945 Finally, if the point is on a blank line, insert empty header
4946 markup (atx) or prompt for text (setext).
4947 See `markdown-insert-header' for more details about how the
4948 header text is determined."
4949 (interactive "*P")
4950 (let (level)
4951 (save-excursion
4952 (when (or (thing-at-point-looking-at markdown-regex-header)
4953 (re-search-backward markdown-regex-header nil t))
4954 ;; level of current or previous header
4955 (setq level (markdown-outline-level))
4956 ;; match group 1 indicates a setext header
4957 (setq setext (match-end 1))))
4958 ;; check prefix argument
4959 (cond
4960 ((and (equal arg '(4)) level (> level 1)) ;; C-u
4961 (cl-decf level))
4962 ((and (equal arg '(16)) level (< level 6)) ;; C-u C-u
4963 (cl-incf level))
4964 (arg ;; numeric prefix
4965 (setq level (prefix-numeric-value arg))))
4966 ;; setext headers must be level one or two
4967 (and level (setq setext (and setext (<= level 2))))
4968 ;; insert the heading
4969 (markdown-insert-header level nil setext)))
4971 (defun markdown-insert-header-setext-dwim (&optional arg)
4972 "Insert or replace header markup, with preference for setext.
4973 See `markdown-insert-header-dwim' for details, including how ARG is handled."
4974 (interactive "*P")
4975 (markdown-insert-header-dwim arg t))
4977 (defun markdown-insert-header-atx-1 ()
4978 "Insert a first level atx-style (hash mark) header.
4979 See `markdown-insert-header'."
4980 (interactive "*")
4981 (markdown-insert-header 1 nil nil))
4983 (defun markdown-insert-header-atx-2 ()
4984 "Insert a level two atx-style (hash mark) header.
4985 See `markdown-insert-header'."
4986 (interactive "*")
4987 (markdown-insert-header 2 nil nil))
4989 (defun markdown-insert-header-atx-3 ()
4990 "Insert a level three atx-style (hash mark) header.
4991 See `markdown-insert-header'."
4992 (interactive "*")
4993 (markdown-insert-header 3 nil nil))
4995 (defun markdown-insert-header-atx-4 ()
4996 "Insert a level four atx-style (hash mark) header.
4997 See `markdown-insert-header'."
4998 (interactive "*")
4999 (markdown-insert-header 4 nil nil))
5001 (defun markdown-insert-header-atx-5 ()
5002 "Insert a level five atx-style (hash mark) header.
5003 See `markdown-insert-header'."
5004 (interactive "*")
5005 (markdown-insert-header 5 nil nil))
5007 (defun markdown-insert-header-atx-6 ()
5008 "Insert a sixth level atx-style (hash mark) header.
5009 See `markdown-insert-header'."
5010 (interactive "*")
5011 (markdown-insert-header 6 nil nil))
5013 (defun markdown-insert-header-setext-1 ()
5014 "Insert a setext-style (underlined) first-level header.
5015 See `markdown-insert-header'."
5016 (interactive "*")
5017 (markdown-insert-header 1 nil t))
5019 (defun markdown-insert-header-setext-2 ()
5020 "Insert a setext-style (underlined) second-level header.
5021 See `markdown-insert-header'."
5022 (interactive "*")
5023 (markdown-insert-header 2 nil t))
5025 (defun markdown-blockquote-indentation (loc)
5026 "Return string containing necessary indentation for a blockquote at LOC.
5027 Also see `markdown-pre-indentation'."
5028 (save-excursion
5029 (goto-char loc)
5030 (let* ((list-level (length (markdown-calculate-list-levels)))
5031 (indent ""))
5032 (dotimes (_ list-level indent)
5033 (setq indent (concat indent " "))))))
5035 (defun markdown-insert-blockquote ()
5036 "Start a blockquote section (or blockquote the region).
5037 If Transient Mark mode is on and a region is active, it is used as
5038 the blockquote text."
5039 (interactive)
5040 (if (markdown-use-region-p)
5041 (markdown-blockquote-region (region-beginning) (region-end))
5042 (markdown-ensure-blank-line-before)
5043 (insert (markdown-blockquote-indentation (point)) "> ")
5044 (markdown-ensure-blank-line-after)))
5046 (defun markdown-block-region (beg end prefix)
5047 "Format the region using a block prefix.
5048 Arguments BEG and END specify the beginning and end of the
5049 region. The characters PREFIX will appear at the beginning
5050 of each line."
5051 (save-excursion
5052 (let* ((end-marker (make-marker))
5053 (beg-marker (make-marker))
5054 (prefix-without-trailing-whitespace
5055 (replace-regexp-in-string (rx (+ blank) eos) "" prefix)))
5056 ;; Ensure blank line after and remove extra whitespace
5057 (goto-char end)
5058 (skip-syntax-backward "-")
5059 (set-marker end-marker (point))
5060 (delete-horizontal-space)
5061 (markdown-ensure-blank-line-after)
5062 ;; Ensure blank line before and remove extra whitespace
5063 (goto-char beg)
5064 (skip-syntax-forward "-")
5065 (delete-horizontal-space)
5066 (markdown-ensure-blank-line-before)
5067 (set-marker beg-marker (point))
5068 ;; Insert PREFIX before each line
5069 (goto-char beg-marker)
5070 (while (and (< (line-beginning-position) end-marker)
5071 (not (eobp)))
5072 ;; Don’t insert trailing whitespace.
5073 (insert (if (eolp) prefix-without-trailing-whitespace prefix))
5074 (forward-line)))))
5076 (defun markdown-blockquote-region (beg end)
5077 "Blockquote the region.
5078 Arguments BEG and END specify the beginning and end of the region."
5079 (interactive "*r")
5080 (markdown-block-region
5081 beg end (concat (markdown-blockquote-indentation
5082 (max (point-min) (1- beg))) "> ")))
5084 (defun markdown-pre-indentation (loc)
5085 "Return string containing necessary whitespace for a pre block at LOC.
5086 Also see `markdown-blockquote-indentation'."
5087 (save-excursion
5088 (goto-char loc)
5089 (let* ((list-level (length (markdown-calculate-list-levels)))
5090 indent)
5091 (dotimes (_ (1+ list-level) indent)
5092 (setq indent (concat indent " "))))))
5094 (defun markdown-insert-pre ()
5095 "Start a preformatted section (or apply to the region).
5096 If Transient Mark mode is on and a region is active, it is marked
5097 as preformatted text."
5098 (interactive)
5099 (if (markdown-use-region-p)
5100 (markdown-pre-region (region-beginning) (region-end))
5101 (markdown-ensure-blank-line-before)
5102 (insert (markdown-pre-indentation (point)))
5103 (markdown-ensure-blank-line-after)))
5105 (defun markdown-pre-region (beg end)
5106 "Format the region as preformatted text.
5107 Arguments BEG and END specify the beginning and end of the region."
5108 (interactive "*r")
5109 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
5110 (markdown-block-region beg end indent)))
5112 (defun markdown-electric-backquote (arg)
5113 "Insert a backquote.
5114 The numeric prefix argument ARG says how many times to repeat the insertion.
5115 Call `markdown-insert-gfm-code-block' interactively
5116 if three backquotes inserted at the beginning of line."
5117 (interactive "*P")
5118 (self-insert-command (prefix-numeric-value arg))
5119 (when (and markdown-gfm-use-electric-backquote (looking-back "^```" nil))
5120 (replace-match "")
5121 (call-interactively #'markdown-insert-gfm-code-block)))
5123 (defconst markdown-gfm-recognized-languages
5124 ;; To reproduce/update, evaluate the let-form in
5125 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
5126 ;; but with appropriate use of a keyboard macro, indenting and filling it
5127 ;; properly is pretty fast.
5128 '("1C-Enterprise" "ABAP" "ABNF" "AGS-Script" "AMPL" "ANTLR"
5129 "API-Blueprint" "APL" "ASN.1" "ASP" "ATS" "ActionScript" "Ada" "Agda"
5130 "Alloy" "Alpine-Abuild" "Ant-Build-System" "ApacheConf" "Apex"
5131 "Apollo-Guidance-Computer" "AppleScript" "Arc" "Arduino" "AsciiDoc"
5132 "AspectJ" "Assembly" "Augeas" "AutoHotkey" "AutoIt" "Awk" "Batchfile"
5133 "Befunge" "Bison" "BitBake" "Blade" "BlitzBasic" "BlitzMax" "Bluespec"
5134 "Boo" "Brainfuck" "Brightscript" "Bro" "C#" "C++" "C-ObjDump"
5135 "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "COLLADA" "CSON" "CSS" "CSV"
5136 "CWeb" "Cap'n-Proto" "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK"
5137 "Cirru" "Clarion" "Clean" "Click" "Clojure" "Closure-Templates"
5138 "CoffeeScript" "ColdFusion" "ColdFusion-CFC" "Common-Lisp"
5139 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal"
5140 "Csound" "Csound-Document" "Csound-Score" "Cuda" "Cycript" "Cython"
5141 "D-ObjDump" "DIGITAL-Command-Language" "DM" "DNS-Zone" "DTrace"
5142 "Darcs-Patch" "Dart" "Diff" "Dockerfile" "Dogescript" "Dylan" "EBNF"
5143 "ECL" "ECLiPSe" "EJS" "EQ" "Eagle" "Ecere-Projects" "Eiffel" "Elixir"
5144 "Elm" "Emacs-Lisp" "EmberScript" "Erlang" "F#" "FLUX" "Factor" "Fancy"
5145 "Fantom" "Filebench-WML" "Filterscript" "Formatted" "Forth" "Fortran"
5146 "FreeMarker" "Frege" "G-code" "GAMS" "GAP" "GCC-Machine-Description"
5147 "GDB" "GDScript" "GLSL" "GN" "Game-Maker-Language" "Genie" "Genshi"
5148 "Gentoo-Ebuild" "Gentoo-Eclass" "Gettext-Catalog" "Gherkin" "Glyph"
5149 "Gnuplot" "Go" "Golo" "Gosu" "Grace" "Gradle" "Grammatical-Framework"
5150 "Graph-Modeling-Language" "GraphQL" "Graphviz-(DOT)" "Groovy"
5151 "Groovy-Server-Pages" "HCL" "HLSL" "HTML" "HTML+Django" "HTML+ECR"
5152 "HTML+EEX" "HTML+ERB" "HTML+PHP" "HTTP" "Hack" "Haml" "Handlebars"
5153 "Harbour" "Haskell" "Haxe" "Hy" "HyPhy" "IDL" "IGOR-Pro" "INI"
5154 "IRC-log" "Idris" "Inform-7" "Inno-Setup" "Io" "Ioke" "Isabelle"
5155 "Isabelle-ROOT" "JFlex" "JSON" "JSON5" "JSONLD" "JSONiq" "JSX"
5156 "Jasmin" "Java" "Java-Server-Pages" "JavaScript" "Jison" "Jison-Lex"
5157 "Jolie" "Julia" "Jupyter-Notebook" "KRL" "KiCad" "Kit" "Kotlin" "LFE"
5158 "LLVM" "LOLCODE" "LSL" "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex"
5159 "LilyPond" "Limbo" "Linker-Script" "Linux-Kernel-Module" "Liquid"
5160 "Literate-Agda" "Literate-CoffeeScript" "Literate-Haskell"
5161 "LiveScript" "Logos" "Logtalk" "LookML" "LoomScript" "Lua" "M4"
5162 "M4Sugar" "MAXScript" "MQL4" "MQL5" "MTML" "MUF" "Makefile" "Mako"
5163 "Markdown" "Marko" "Mask" "Mathematica" "Matlab" "Maven-POM" "Max"
5164 "MediaWiki" "Mercury" "Meson" "Metal" "MiniD" "Mirah" "Modelica"
5165 "Modula-2" "Module-Management-System" "Monkey" "Moocode" "MoonScript"
5166 "Myghty" "NCL" "NL" "NSIS" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo"
5167 "NewLisp" "Nginx" "Nim" "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml"
5168 "ObjDump" "Objective-C" "Objective-C++" "Objective-J" "Omgrofl" "Opa"
5169 "Opal" "OpenCL" "OpenEdge-ABL" "OpenRC-runscript" "OpenSCAD"
5170 "OpenType-Feature-File" "Org" "Ox" "Oxygene" "Oz" "P4" "PAWN" "PHP"
5171 "PLSQL" "PLpgSQL" "POV-Ray-SDL" "Pan" "Papyrus" "Parrot"
5172 "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal" "Pep8"
5173 "Perl" "Perl6" "Pic" "Pickle" "PicoLisp" "PigLatin" "Pike" "Pod"
5174 "PogoScript" "Pony" "PostScript" "PowerBuilder" "PowerShell"
5175 "Processing" "Prolog" "Propeller-Spin" "Protocol-Buffer" "Public-Key"
5176 "Pug" "Puppet" "Pure-Data" "PureBasic" "PureScript" "Python"
5177 "Python-console" "Python-traceback" "QML" "QMake" "RAML" "RDoc"
5178 "REALbasic" "REXX" "RHTML" "RMarkdown" "RPM-Spec" "RUNOFF" "Racket"
5179 "Ragel" "Rascal" "Raw-token-data" "Reason" "Rebol" "Red" "Redcode"
5180 "Regular-Expression" "Ren'Py" "RenderScript" "RobotFramework" "Roff"
5181 "Rouge" "Ruby" "Rust" "SAS" "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL"
5182 "SRecode-Template" "STON" "SVG" "Sage" "SaltStack" "Sass" "Scala"
5183 "Scaml" "Scheme" "Scilab" "Self" "ShaderLab" "Shell" "ShellSession"
5184 "Shen" "Slash" "Slim" "Smali" "Smalltalk" "Smarty" "SourcePawn"
5185 "Spline-Font-Database" "Squirrel" "Stan" "Standard-ML" "Stata"
5186 "Stylus" "SubRip-Text" "Sublime-Text-Config" "SuperCollider" "Swift"
5187 "SystemVerilog" "TI-Program" "TLA" "TOML" "TXL" "Tcl" "Tcsh" "TeX"
5188 "Tea" "Terra" "Text" "Textile" "Thrift" "Turing" "Turtle" "Twig"
5189 "Type-Language" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset"
5190 "Unix-Assembly" "Uno" "UnrealScript" "UrWeb" "VCL" "VHDL" "Vala"
5191 "Verilog" "Vim-script" "Visual-Basic" "Volt" "Vue"
5192 "Wavefront-Material" "Wavefront-Object" "Web-Ontology-Language"
5193 "WebAssembly" "WebIDL" "World-of-Warcraft-Addon-Data" "X10" "XC"
5194 "XCompose" "XML" "XPages" "XProc" "XQuery" "XS" "XSLT" "Xojo" "Xtend"
5195 "YAML" "YANG" "Yacc" "Zephir" "Zimpl" "desktop" "eC" "edn" "fish"
5196 "mupad" "nesC" "ooc" "reStructuredText" "wisp" "xBase")
5197 "Language specifiers recognized by GitHub's syntax highlighting features.")
5199 (defvar markdown-gfm-used-languages nil
5200 "Language names used in GFM code blocks.")
5201 (make-variable-buffer-local 'markdown-gfm-used-languages)
5203 (defun markdown-trim-whitespace (str)
5204 (markdown-replace-regexp-in-string
5205 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str))
5207 (defun markdown-clean-language-string (str)
5208 (markdown-replace-regexp-in-string
5209 "{\\.?\\|}" "" (markdown-trim-whitespace str)))
5211 (defun markdown-validate-language-string (widget)
5212 (let ((str (widget-value widget)))
5213 (unless (string= str (markdown-clean-language-string str))
5214 (widget-put widget :error (format "Invalid language spec: '%s'" str))
5215 widget)))
5217 (defun markdown-gfm-get-corpus ()
5218 "Create corpus of recognized GFM code block languages for the given buffer."
5219 (let ((given-corpus (append markdown-gfm-additional-languages
5220 markdown-gfm-recognized-languages)))
5221 (append
5222 markdown-gfm-used-languages
5223 (if markdown-gfm-downcase-languages (cl-mapcar #'downcase given-corpus)
5224 given-corpus))))
5226 (defun markdown-gfm-add-used-language (lang)
5227 "Clean LANG and add to list of used languages."
5228 (setq markdown-gfm-used-languages
5229 (cons lang (remove lang markdown-gfm-used-languages))))
5231 (defcustom markdown-spaces-after-code-fence 1
5232 "Number of space characters to insert after a code fence.
5233 \\<gfm-mode-map>\\[markdown-insert-gfm-code-block] inserts this many spaces between an
5234 opening code fence and an info string."
5235 :group 'markdown
5236 :type 'integer
5237 :safe #'natnump
5238 :package-version '(markdown-mode . "2.3"))
5240 (defun markdown-insert-gfm-code-block (&optional lang edit)
5241 "Insert GFM code block for language LANG.
5242 If LANG is nil, the language will be queried from user. If a
5243 region is active, wrap this region with the markup instead. If
5244 the region boundaries are not on empty lines, these are added
5245 automatically in order to have the correct markup. When EDIT is
5246 non-nil (e.g., when \\[universal-argument] is given), edit the
5247 code block in an indirect buffer after insertion."
5248 (interactive
5249 (list (let ((completion-ignore-case nil))
5250 (condition-case nil
5251 (markdown-clean-language-string
5252 (completing-read
5253 "Programming language: "
5254 (markdown-gfm-get-corpus)
5255 nil 'confirm (car markdown-gfm-used-languages)
5256 'markdown-gfm-language-history))
5257 (quit "")))
5258 current-prefix-arg))
5259 (unless (string= lang "") (markdown-gfm-add-used-language lang))
5260 (when (> (length lang) 0)
5261 (setq lang (concat (make-string markdown-spaces-after-code-fence ?\s)
5262 lang)))
5263 (if (markdown-use-region-p)
5264 (let* ((b (region-beginning)) (e (region-end)) end
5265 (indent (progn (goto-char b) (current-indentation))))
5266 (goto-char e)
5267 ;; if we're on a blank line, don't newline, otherwise the ```
5268 ;; should go on its own line
5269 (unless (looking-back "\n" nil)
5270 (newline))
5271 (indent-to indent)
5272 (insert "```")
5273 (markdown-ensure-blank-line-after)
5274 (setq end (point))
5275 (goto-char b)
5276 ;; if we're on a blank line, insert the quotes here, otherwise
5277 ;; add a new line first
5278 (unless (looking-at-p "\n")
5279 (newline)
5280 (forward-line -1))
5281 (markdown-ensure-blank-line-before)
5282 (indent-to indent)
5283 (insert "```" lang)
5284 (markdown-syntax-propertize-fenced-block-constructs (point-at-bol) end))
5285 (let ((indent (current-indentation)) start)
5286 (delete-horizontal-space :backward-only)
5287 (markdown-ensure-blank-line-before)
5288 (indent-to indent)
5289 (setq start (point))
5290 (insert "```" lang "\n")
5291 (indent-to indent)
5292 (unless edit (insert ?\n))
5293 (indent-to indent)
5294 (insert "```")
5295 (markdown-ensure-blank-line-after)
5296 (markdown-syntax-propertize-fenced-block-constructs start (point)))
5297 (end-of-line 0)
5298 (when edit (markdown-edit-code-block))))
5300 (defun markdown-code-block-lang (&optional pos-prop)
5301 "Return the language name for a GFM or tilde fenced code block.
5302 The beginning of the block may be described by POS-PROP,
5303 a cons of (pos . prop) giving the position and property
5304 at the beginning of the block."
5305 (or pos-prop
5306 (setq pos-prop
5307 (markdown-max-of-seq
5308 #'car
5309 (cl-remove-if
5310 #'null
5311 (cl-mapcar
5312 #'markdown-find-previous-prop
5313 (markdown-get-fenced-block-begin-properties))))))
5314 (when pos-prop
5315 (goto-char (car pos-prop))
5316 (set-match-data (get-text-property (point) (cdr pos-prop)))
5317 ;; Note: Hard-coded group number assumes tilde
5318 ;; and GFM fenced code regexp groups agree.
5319 (let ((begin (match-beginning 3))
5320 (end (match-end 3)))
5321 (when (and begin end)
5322 ;; Fix language strings beginning with periods, like ".ruby".
5323 (when (eq (char-after begin) ?.)
5324 (setq begin (1+ begin)))
5325 (buffer-substring-no-properties begin end)))))
5327 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer)
5328 (with-current-buffer (or buffer (current-buffer))
5329 (save-excursion
5330 (goto-char (point-min))
5331 (cl-loop
5332 with prop = 'markdown-gfm-block-begin
5333 for pos-prop = (markdown-find-next-prop prop)
5334 while pos-prop
5335 for lang = (markdown-code-block-lang pos-prop)
5336 do (progn (when lang (markdown-gfm-add-used-language lang))
5337 (goto-char (next-single-property-change (point) prop)))))))
5340 ;;; Footnotes ==================================================================
5342 (defun markdown-footnote-counter-inc ()
5343 "Increment `markdown-footnote-counter' and return the new value."
5344 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
5345 (save-excursion
5346 (goto-char (point-min))
5347 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
5348 (point-max) t)
5349 (let ((fn (string-to-number (match-string 1))))
5350 (when (> fn markdown-footnote-counter)
5351 (setq markdown-footnote-counter fn))))))
5352 (cl-incf markdown-footnote-counter))
5354 (defun markdown-insert-footnote ()
5355 "Insert footnote with a new number and move point to footnote definition."
5356 (interactive)
5357 (let ((fn (markdown-footnote-counter-inc)))
5358 (insert (format "[^%d]" fn))
5359 (markdown-footnote-text-find-new-location)
5360 (markdown-ensure-blank-line-before)
5361 (unless (markdown-cur-line-blank-p)
5362 (insert "\n"))
5363 (insert (format "[^%d]: " fn))
5364 (markdown-ensure-blank-line-after)))
5366 (defun markdown-footnote-text-find-new-location ()
5367 "Position the point at the proper location for a new footnote text."
5368 (cond
5369 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
5370 ((eq markdown-footnote-location 'immediately) (markdown-end-of-text-block))
5371 ((eq markdown-footnote-location 'subtree) (markdown-end-of-subtree))
5372 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
5374 (defun markdown-footnote-kill ()
5375 "Kill the footnote at point.
5376 The footnote text is killed (and added to the kill ring), the
5377 footnote marker is deleted. Point has to be either at the
5378 footnote marker or in the footnote text."
5379 (interactive)
5380 (let ((marker-pos nil)
5381 (skip-deleting-marker nil)
5382 (starting-footnote-text-positions
5383 (markdown-footnote-text-positions)))
5384 (when starting-footnote-text-positions
5385 ;; We're starting in footnote text, so mark our return position and jump
5386 ;; to the marker if possible.
5387 (let ((marker-pos (markdown-footnote-find-marker
5388 (cl-first starting-footnote-text-positions))))
5389 (if marker-pos
5390 (goto-char (1- marker-pos))
5391 ;; If there isn't a marker, we still want to kill the text.
5392 (setq skip-deleting-marker t))))
5393 ;; Either we didn't start in the text, or we started in the text and jumped
5394 ;; to the marker. We want to assume we're at the marker now and error if
5395 ;; we're not.
5396 (unless skip-deleting-marker
5397 (let ((marker (markdown-footnote-delete-marker)))
5398 (unless marker
5399 (error "Not at a footnote"))
5400 ;; Even if we knew the text position before, it changed when we deleted
5401 ;; the label.
5402 (setq marker-pos (cl-second marker))
5403 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker))))
5404 (unless new-text-pos
5405 (error "No text for footnote `%s'" (cl-first marker)))
5406 (goto-char new-text-pos))))
5407 (let ((pos (markdown-footnote-kill-text)))
5408 (goto-char (if starting-footnote-text-positions
5410 marker-pos)))))
5412 (defun markdown-footnote-delete-marker ()
5413 "Delete a footnote marker at point.
5414 Returns a list (ID START) containing the footnote ID and the
5415 start position of the marker before deletion. If no footnote
5416 marker was deleted, this function returns NIL."
5417 (let ((marker (markdown-footnote-marker-positions)))
5418 (when marker
5419 (delete-region (cl-second marker) (cl-third marker))
5420 (butlast marker))))
5422 (defun markdown-footnote-kill-text ()
5423 "Kill footnote text at point.
5424 Returns the start position of the footnote text before deletion,
5425 or NIL if point was not inside a footnote text.
5427 The killed text is placed in the kill ring (without the footnote
5428 number)."
5429 (let ((fn (markdown-footnote-text-positions)))
5430 (when fn
5431 (let ((text (delete-and-extract-region (cl-second fn) (cl-third fn))))
5432 (string-match (concat "\\[\\" (cl-first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
5433 (kill-new (match-string 1 text))
5434 (when (and (markdown-cur-line-blank-p)
5435 (markdown-prev-line-blank-p)
5436 (not (bobp)))
5437 (delete-region (1- (point)) (point)))
5438 (cl-second fn)))))
5440 (defun markdown-footnote-goto-text ()
5441 "Jump to the text of the footnote at point."
5442 (interactive)
5443 (let ((fn (car (markdown-footnote-marker-positions))))
5444 (unless fn
5445 (user-error "Not at a footnote marker"))
5446 (let ((new-pos (markdown-footnote-find-text fn)))
5447 (unless new-pos
5448 (error "No definition found for footnote `%s'" fn))
5449 (goto-char new-pos))))
5451 (defun markdown-footnote-return ()
5452 "Return from a footnote to its footnote number in the main text."
5453 (interactive)
5454 (let ((fn (save-excursion
5455 (car (markdown-footnote-text-positions)))))
5456 (unless fn
5457 (user-error "Not in a footnote"))
5458 (let ((new-pos (markdown-footnote-find-marker fn)))
5459 (unless new-pos
5460 (error "Footnote marker `%s' not found" fn))
5461 (goto-char new-pos))))
5463 (defun markdown-footnote-find-marker (id)
5464 "Find the location of the footnote marker with ID.
5465 The actual buffer position returned is the position directly
5466 following the marker's closing bracket. If no marker is found,
5467 NIL is returned."
5468 (save-excursion
5469 (goto-char (point-min))
5470 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
5471 (skip-chars-backward "^]")
5472 (point))))
5474 (defun markdown-footnote-find-text (id)
5475 "Find the location of the text of footnote ID.
5476 The actual buffer position returned is the position of the first
5477 character of the text, after the footnote's identifier. If no
5478 footnote text is found, NIL is returned."
5479 (save-excursion
5480 (goto-char (point-min))
5481 (when (re-search-forward (concat "^ \\{0,3\\}\\[" id "\\]:") nil t)
5482 (skip-chars-forward "[ \t]")
5483 (point))))
5485 (defun markdown-footnote-marker-positions ()
5486 "Return the position and ID of the footnote marker point is on.
5487 The return value is a list (ID START END). If point is not on a
5488 footnote, NIL is returned."
5489 ;; first make sure we're at a footnote marker
5490 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
5491 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
5492 (save-excursion
5493 ;; move point between [ and ^:
5494 (if (looking-at-p "\\[")
5495 (forward-char 1)
5496 (skip-chars-backward "^["))
5497 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
5498 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
5500 (defun markdown-footnote-text-positions ()
5501 "Return the start and end positions of the footnote text point is in.
5502 The exact return value is a list of three elements: (ID START END).
5503 The start position is the position of the opening bracket
5504 of the footnote id. The end position is directly after the
5505 newline that ends the footnote. If point is not in a footnote,
5506 NIL is returned instead."
5507 (save-excursion
5508 (let (result)
5509 (move-beginning-of-line 1)
5510 ;; Try to find the label. If we haven't found the label and we're at a blank
5511 ;; or indented line, back up if possible.
5512 (while (and
5513 (not (and (looking-at markdown-regex-footnote-definition)
5514 (setq result (list (match-string 1) (point)))))
5515 (and (not (bobp))
5516 (or (markdown-cur-line-blank-p)
5517 (>= (current-indentation) 4))))
5518 (forward-line -1))
5519 (when result
5520 ;; Advance if there is a next line that is either blank or indented.
5521 ;; (Need to check if we're on the last line, because
5522 ;; markdown-next-line-blank-p returns true for last line in buffer.)
5523 (while (and (/= (line-end-position) (point-max))
5524 (or (markdown-next-line-blank-p)
5525 (>= (markdown-next-line-indent) 4)))
5526 (forward-line))
5527 ;; Move back while the current line is blank.
5528 (while (markdown-cur-line-blank-p)
5529 (forward-line -1))
5530 ;; Advance to capture this line and a single trailing newline (if there
5531 ;; is one).
5532 (forward-line)
5533 (append result (list (point)))))))
5536 ;;; Element Removal ===========================================================
5538 (defun markdown-kill-thing-at-point ()
5539 "Kill thing at point and add important text, without markup, to kill ring.
5540 Possible things to kill include (roughly in order of precedence):
5541 inline code, headers, horizonal rules, links (add link text to
5542 kill ring), images (add alt text to kill ring), angle uri, email
5543 addresses, bold, italics, reference definition (add URI to kill
5544 ring), footnote markers and text (kill both marker and text, add
5545 text to kill ring), and list items."
5546 (interactive "*")
5547 (let (val)
5548 (cond
5549 ;; Inline code
5550 ((markdown-inline-code-at-point)
5551 (kill-new (match-string 2))
5552 (delete-region (match-beginning 0) (match-end 0)))
5553 ;; ATX header
5554 ((thing-at-point-looking-at markdown-regex-header-atx)
5555 (kill-new (match-string 2))
5556 (delete-region (match-beginning 0) (match-end 0)))
5557 ;; Setext header
5558 ((thing-at-point-looking-at markdown-regex-header-setext)
5559 (kill-new (match-string 1))
5560 (delete-region (match-beginning 0) (match-end 0)))
5561 ;; Horizonal rule
5562 ((thing-at-point-looking-at markdown-regex-hr)
5563 (kill-new (match-string 0))
5564 (delete-region (match-beginning 0) (match-end 0)))
5565 ;; Inline link or image (add link or alt text to kill ring)
5566 ((thing-at-point-looking-at markdown-regex-link-inline)
5567 (kill-new (match-string 3))
5568 (delete-region (match-beginning 0) (match-end 0)))
5569 ;; Reference link or image (add link or alt text to kill ring)
5570 ((thing-at-point-looking-at markdown-regex-link-reference)
5571 (kill-new (match-string 3))
5572 (delete-region (match-beginning 0) (match-end 0)))
5573 ;; Angle URI (add URL to kill ring)
5574 ((thing-at-point-looking-at markdown-regex-angle-uri)
5575 (kill-new (match-string 2))
5576 (delete-region (match-beginning 0) (match-end 0)))
5577 ;; Email address in angle brackets (add email address to kill ring)
5578 ((thing-at-point-looking-at markdown-regex-email)
5579 (kill-new (match-string 1))
5580 (delete-region (match-beginning 0) (match-end 0)))
5581 ;; Wiki link (add alias text to kill ring)
5582 ((and markdown-enable-wiki-links
5583 (thing-at-point-looking-at markdown-regex-wiki-link))
5584 (kill-new (markdown-wiki-link-alias))
5585 (delete-region (match-beginning 1) (match-end 1)))
5586 ;; Bold
5587 ((thing-at-point-looking-at markdown-regex-bold)
5588 (kill-new (match-string 4))
5589 (delete-region (match-beginning 2) (match-end 2)))
5590 ;; Italics
5591 ((thing-at-point-looking-at markdown-regex-italic)
5592 (kill-new (match-string 3))
5593 (delete-region (match-beginning 1) (match-end 1)))
5594 ;; Strikethrough
5595 ((thing-at-point-looking-at markdown-regex-strike-through)
5596 (kill-new (match-string 4))
5597 (delete-region (match-beginning 2) (match-end 2)))
5598 ;; Footnote marker (add footnote text to kill ring)
5599 ((thing-at-point-looking-at markdown-regex-footnote)
5600 (markdown-footnote-kill))
5601 ;; Footnote text (add footnote text to kill ring)
5602 ((setq val (markdown-footnote-text-positions))
5603 (markdown-footnote-kill))
5604 ;; Reference definition (add URL to kill ring)
5605 ((thing-at-point-looking-at markdown-regex-reference-definition)
5606 (kill-new (match-string 5))
5607 (delete-region (match-beginning 0) (match-end 0)))
5608 ;; List item
5609 ((setq val (markdown-cur-list-item-bounds))
5610 (kill-new (delete-and-extract-region (cl-first val) (cl-second val))))
5612 (user-error "Nothing found at point to kill")))))
5615 ;;; Indentation ====================================================================
5617 (defun markdown-indent-find-next-position (cur-pos positions)
5618 "Return the position after the index of CUR-POS in POSITIONS.
5619 Positions are calculated by `markdown-calc-indents'."
5620 (while (and positions
5621 (not (equal cur-pos (car positions))))
5622 (setq positions (cdr positions)))
5623 (or (cadr positions) 0))
5625 (define-obsolete-function-alias 'markdown-exdent-find-next-position
5626 'markdown-outdent-find-next-position "v2.3")
5628 (defun markdown-outdent-find-next-position (cur-pos positions)
5629 "Return the maximal element that precedes CUR-POS from POSITIONS.
5630 Positions are calculated by `markdown-calc-indents'."
5631 (let ((result 0))
5632 (dolist (i positions)
5633 (when (< i cur-pos)
5634 (setq result (max result i))))
5635 result))
5637 (defun markdown-indent-line ()
5638 "Indent the current line using some heuristics.
5639 If the _previous_ command was either `markdown-enter-key' or
5640 `markdown-cycle', then we should cycle to the next
5641 reasonable indentation position. Otherwise, we could have been
5642 called directly by `markdown-enter-key', by an initial call of
5643 `markdown-cycle', or indirectly by `auto-fill-mode'. In
5644 these cases, indent to the default position.
5645 Positions are calculated by `markdown-calc-indents'."
5646 (interactive)
5647 (let ((positions (markdown-calc-indents))
5648 (point-pos (current-column))
5649 (_ (back-to-indentation))
5650 (cur-pos (current-column)))
5651 (if (not (equal this-command 'markdown-cycle))
5652 (indent-line-to (car positions))
5653 (setq positions (sort (delete-dups positions) '<))
5654 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions))
5655 (new-point-pos (max (+ point-pos (- next-pos cur-pos)) 0)))
5656 (indent-line-to next-pos)
5657 (move-to-column new-point-pos)))))
5659 (defun markdown-calc-indents ()
5660 "Return a list of indentation columns to cycle through.
5661 The first element in the returned list should be considered the
5662 default indentation level. This function does not worry about
5663 duplicate positions, which are handled up by calling functions."
5664 (let (pos prev-line-pos positions)
5666 ;; Indentation of previous line
5667 (setq prev-line-pos (markdown-prev-line-indent))
5668 (setq positions (cons prev-line-pos positions))
5670 ;; Indentation of previous non-list-marker text
5671 (when (setq pos (markdown-prev-non-list-indent))
5672 (setq positions (cons pos positions)))
5674 ;; Indentation required for a pre block in current context
5675 (setq pos (length (markdown-pre-indentation (point))))
5676 (setq positions (cons pos positions))
5678 ;; Indentation of the previous line + tab-width
5679 (if prev-line-pos
5680 (setq positions (cons (+ prev-line-pos tab-width) positions))
5681 (setq positions (cons tab-width positions)))
5683 ;; Indentation of the previous line - tab-width
5684 (if (and prev-line-pos (> prev-line-pos tab-width))
5685 (setq positions (cons (- prev-line-pos tab-width) positions)))
5687 ;; Indentation of all preceeding list markers (when in a list)
5688 (when (setq pos (markdown-calculate-list-levels))
5689 (setq positions (append pos positions)))
5691 ;; First column
5692 (setq positions (cons 0 positions))
5694 ;; Return reversed list
5695 (reverse positions)))
5697 (defun markdown-enter-key ()
5698 "Handle RET depending on the context.
5699 If the point is at a table, move to the next row. Otherwise,
5700 indent according to value of `markdown-indent-on-enter'.
5701 When it is nil, simply call `newline'. Otherwise, indent the next line
5702 following RET using `markdown-indent-line'. Furthermore, when it
5703 is set to 'indent-and-new-item and the point is in a list item,
5704 start a new item with the same indentation. If the point is in an
5705 empty list item, remove it (so that pressing RET twice when in a
5706 list simply adds a blank line)."
5707 (interactive)
5708 (cond
5709 ;; Table
5710 ((markdown-table-at-point-p)
5711 (call-interactively #'markdown-table-next-row))
5712 ;; Indent non-table text
5713 (markdown-indent-on-enter
5714 (let (bounds)
5715 (if (and (memq markdown-indent-on-enter '(indent-and-new-item))
5716 (setq bounds (markdown-cur-list-item-bounds)))
5717 (let ((beg (cl-first bounds))
5718 (end (cl-second bounds))
5719 (length (cl-fourth bounds)))
5720 ;; Point is in a list item
5721 (if (= (- end beg) length)
5722 ;; Delete blank list
5723 (progn
5724 (delete-region beg end)
5725 (newline)
5726 (markdown-indent-line))
5727 (call-interactively #'markdown-insert-list-item)))
5728 ;; Point is not in a list
5729 (newline)
5730 (markdown-indent-line))))
5731 ;; Insert a raw newline
5732 (t (newline))))
5734 (define-obsolete-function-alias 'markdown-exdent-or-delete
5735 'markdown-outdent-or-delete "v2.3")
5737 (defun markdown-outdent-or-delete (arg)
5738 "Handle BACKSPACE by cycling through indentation points.
5739 When BACKSPACE is pressed, if there is only whitespace
5740 before the current point, then outdent the line one level.
5741 Otherwise, do normal delete by repeating
5742 `backward-delete-char-untabify' ARG times."
5743 (interactive "*p")
5744 (if (use-region-p)
5745 (backward-delete-char-untabify arg)
5746 (let ((cur-pos (current-column))
5747 (start-of-indention (save-excursion
5748 (back-to-indentation)
5749 (current-column)))
5750 (positions (markdown-calc-indents)))
5751 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
5752 (indent-line-to (markdown-outdent-find-next-position cur-pos positions))
5753 (backward-delete-char-untabify arg)))))
5755 (defun markdown-find-leftmost-column (beg end)
5756 "Find the leftmost column in the region from BEG to END."
5757 (let ((mincol 1000))
5758 (save-excursion
5759 (goto-char beg)
5760 (while (< (point) end)
5761 (back-to-indentation)
5762 (unless (looking-at-p "[ \t]*$")
5763 (setq mincol (min mincol (current-column))))
5764 (forward-line 1)
5766 mincol))
5768 (defun markdown-indent-region (beg end arg)
5769 "Indent the region from BEG to END using some heuristics.
5770 When ARG is non-nil, outdent the region instead.
5771 See `markdown-indent-line' and `markdown-indent-line'."
5772 (interactive "*r\nP")
5773 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
5774 (leftmostcol (markdown-find-leftmost-column beg end))
5775 (next-pos (if arg
5776 (markdown-outdent-find-next-position leftmostcol positions)
5777 (markdown-indent-find-next-position leftmostcol positions))))
5778 (indent-rigidly beg end (- next-pos leftmostcol))
5779 (setq deactivate-mark nil)))
5781 (define-obsolete-function-alias 'markdown-exdent-region
5782 'markdown-outdent-region "v2.3")
5784 (defun markdown-outdent-region (beg end)
5785 "Call `markdown-indent-region' on region from BEG to END with prefix."
5786 (interactive "*r")
5787 (markdown-indent-region beg end t))
5790 ;;; Markup Completion =========================================================
5792 (defconst markdown-complete-alist
5793 '((markdown-regex-header-atx . markdown-complete-atx)
5794 (markdown-regex-header-setext . markdown-complete-setext)
5795 (markdown-regex-hr . markdown-complete-hr))
5796 "Association list of form (regexp . function) for markup completion.")
5798 (defun markdown-incomplete-atx-p ()
5799 "Return t if ATX header markup is incomplete and nil otherwise.
5800 Assumes match data is available for `markdown-regex-header-atx'.
5801 Checks that the number of trailing hash marks equals the number of leading
5802 hash marks, that there is only a single space before and after the text,
5803 and that there is no extraneous whitespace in the text."
5805 ;; Number of starting and ending hash marks differs
5806 (not (= (length (match-string 1)) (length (match-string 3))))
5807 ;; When the header text is not empty...
5808 (and (> (length (match-string 2)) 0)
5809 ;; ...if there are extra leading, trailing, or interior spaces
5810 (or (not (= (match-beginning 2) (1+ (match-end 1))))
5811 (not (= (match-beginning 3) (1+ (match-end 2))))
5812 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
5813 ;; When the header text is empty...
5814 (and (= (length (match-string 2)) 0)
5815 ;; ...if there are too many or too few spaces
5816 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
5818 (defun markdown-complete-atx ()
5819 "Complete and normalize ATX headers.
5820 Add or remove hash marks to the end of the header to match the
5821 beginning. Ensure that there is only a single space between hash
5822 marks and header text. Removes extraneous whitespace from header text.
5823 Assumes match data is available for `markdown-regex-header-atx'.
5824 Return nil if markup was complete and non-nil if markup was completed."
5825 (when (markdown-incomplete-atx-p)
5826 (let* ((new-marker (make-marker))
5827 (new-marker (set-marker new-marker (match-end 2))))
5828 ;; Hash marks and spacing at end
5829 (goto-char (match-end 2))
5830 (delete-region (match-end 2) (match-end 3))
5831 (insert " " (match-string 1))
5832 ;; Remove extraneous whitespace from title
5833 (replace-match (markdown-compress-whitespace-string (match-string 2))
5834 t t nil 2)
5835 ;; Spacing at beginning
5836 (goto-char (match-end 1))
5837 (delete-region (match-end 1) (match-beginning 2))
5838 (insert " ")
5839 ;; Leave point at end of text
5840 (goto-char new-marker))))
5842 (defun markdown-incomplete-setext-p ()
5843 "Return t if setext header markup is incomplete and nil otherwise.
5844 Assumes match data is available for `markdown-regex-header-setext'.
5845 Checks that length of underline matches text and that there is no
5846 extraneous whitespace in the text."
5847 (or (not (= (length (match-string 1)) (length (match-string 2))))
5848 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
5850 (defun markdown-complete-setext ()
5851 "Complete and normalize setext headers.
5852 Add or remove underline characters to match length of header
5853 text. Removes extraneous whitespace from header text. Assumes
5854 match data is available for `markdown-regex-header-setext'.
5855 Return nil if markup was complete and non-nil if markup was completed."
5856 (when (markdown-incomplete-setext-p)
5857 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
5858 (char (char-after (match-beginning 2)))
5859 (level (if (char-equal char ?-) 2 1)))
5860 (goto-char (match-beginning 0))
5861 (delete-region (match-beginning 0) (match-end 0))
5862 (markdown-insert-header level text t)
5863 t)))
5865 (defun markdown-incomplete-hr-p ()
5866 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
5867 Assumes match data is available for `markdown-regex-hr'."
5868 (not (member (match-string 0) markdown-hr-strings)))
5870 (defun markdown-complete-hr ()
5871 "Complete horizontal rules.
5872 If horizontal rule string is a member of `markdown-hr-strings',
5873 do nothing. Otherwise, replace with the car of
5874 `markdown-hr-strings'.
5875 Assumes match data is available for `markdown-regex-hr'.
5876 Return nil if markup was complete and non-nil if markup was completed."
5877 (when (markdown-incomplete-hr-p)
5878 (replace-match (car markdown-hr-strings))
5881 (defun markdown-complete ()
5882 "Complete markup of object near point or in region when active.
5883 Handle all objects in `markdown-complete-alist', in order.
5884 See `markdown-complete-at-point' and `markdown-complete-region'."
5885 (interactive "*")
5886 (if (markdown-use-region-p)
5887 (markdown-complete-region (region-beginning) (region-end))
5888 (markdown-complete-at-point)))
5890 (defun markdown-complete-at-point ()
5891 "Complete markup of object near point.
5892 Handle all elements of `markdown-complete-alist' in order."
5893 (interactive "*")
5894 (let ((list markdown-complete-alist) found changed)
5895 (while list
5896 (let ((regexp (eval (caar list)))
5897 (function (cdar list)))
5898 (setq list (cdr list))
5899 (when (thing-at-point-looking-at regexp)
5900 (setq found t)
5901 (setq changed (funcall function))
5902 (setq list nil))))
5903 (if found
5904 (or changed (user-error "Markup at point is complete"))
5905 (user-error "Nothing to complete at point"))))
5907 (defun markdown-complete-region (beg end)
5908 "Complete markup of objects in region from BEG to END.
5909 Handle all objects in `markdown-complete-alist', in order. Each
5910 match is checked to ensure that a previous regexp does not also
5911 match."
5912 (interactive "*r")
5913 (let ((end-marker (set-marker (make-marker) end))
5914 previous)
5915 (dolist (element markdown-complete-alist)
5916 (let ((regexp (eval (car element)))
5917 (function (cdr element)))
5918 (goto-char beg)
5919 (while (re-search-forward regexp end-marker 'limit)
5920 (when (match-string 0)
5921 ;; Make sure this is not a match for any of the preceding regexps.
5922 ;; This prevents mistaking an HR for a Setext subheading.
5923 (let (match)
5924 (save-match-data
5925 (dolist (prev-regexp previous)
5926 (or match (setq match (looking-back prev-regexp nil)))))
5927 (unless match
5928 (save-excursion (funcall function))))))
5929 (cl-pushnew regexp previous :test #'equal)))
5930 previous))
5932 (defun markdown-complete-buffer ()
5933 "Complete markup for all objects in the current buffer."
5934 (interactive "*")
5935 (markdown-complete-region (point-min) (point-max)))
5938 ;;; Markup Cycling ============================================================
5940 (defun markdown-cycle-atx (arg &optional remove)
5941 "Cycle ATX header markup.
5942 Promote header (decrease level) when ARG is 1 and demote
5943 header (increase level) if arg is -1. When REMOVE is non-nil,
5944 remove the header when the level reaches zero and stop cycling
5945 when it reaches six. Otherwise, perform a proper cycling through
5946 levels one through six. Assumes match data is available for
5947 `markdown-regex-header-atx'."
5948 (let* ((old-level (length (match-string 1)))
5949 (new-level (+ old-level arg))
5950 (text (match-string 2)))
5951 (when (not remove)
5952 (setq new-level (% new-level 6))
5953 (setq new-level (cond ((= new-level 0) 6)
5954 ((< new-level 0) (+ new-level 6))
5955 (t new-level))))
5956 (cond
5957 ((= new-level 0)
5958 (markdown-unwrap-thing-at-point nil 0 2))
5959 ((<= new-level 6)
5960 (goto-char (match-beginning 0))
5961 (delete-region (match-beginning 0) (match-end 0))
5962 (markdown-insert-header new-level text nil)))))
5964 (defun markdown-cycle-setext (arg &optional remove)
5965 "Cycle setext header markup.
5966 Promote header (increase level) when ARG is 1 and demote
5967 header (decrease level or remove) if arg is -1. When demoting a
5968 level-two setext header, replace with a level-three atx header.
5969 When REMOVE is non-nil, remove the header when the level reaches
5970 zero. Otherwise, cycle back to a level six atx header. Assumes
5971 match data is available for `markdown-regex-header-setext'."
5972 (let* ((char (char-after (match-beginning 2)))
5973 (old-level (if (char-equal char ?=) 1 2))
5974 (new-level (+ old-level arg)))
5975 (when (and (not remove) (= new-level 0))
5976 (setq new-level 6))
5977 (cond
5978 ((= new-level 0)
5979 (markdown-unwrap-thing-at-point nil 0 1))
5980 ((<= new-level 2)
5981 (markdown-insert-header new-level nil t))
5982 ((<= new-level 6)
5983 (markdown-insert-header new-level nil nil)))))
5985 (defun markdown-cycle-hr (arg &optional remove)
5986 "Cycle string used for horizontal rule from `markdown-hr-strings'.
5987 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
5988 backwards (promote). When REMOVE is non-nil, remove the hr instead
5989 of cycling when the end of the list is reached.
5990 Assumes match data is available for `markdown-regex-hr'."
5991 (let* ((strings (if (= arg -1)
5992 (reverse markdown-hr-strings)
5993 markdown-hr-strings))
5994 (tail (member (match-string 0) strings))
5995 (new (or (cadr tail)
5996 (if remove
5997 (if (= arg 1)
5999 (car tail))
6000 (car strings)))))
6001 (replace-match new)))
6003 (defun markdown-cycle-bold ()
6004 "Cycle bold markup between underscores and asterisks.
6005 Assumes match data is available for `markdown-regex-bold'."
6006 (save-excursion
6007 (let* ((old-delim (match-string 3))
6008 (new-delim (if (string-equal old-delim "**") "__" "**")))
6009 (replace-match new-delim t t nil 3)
6010 (replace-match new-delim t t nil 5))))
6012 (defun markdown-cycle-italic ()
6013 "Cycle italic markup between underscores and asterisks.
6014 Assumes match data is available for `markdown-regex-italic'."
6015 (save-excursion
6016 (let* ((old-delim (match-string 2))
6017 (new-delim (if (string-equal old-delim "*") "_" "*")))
6018 (replace-match new-delim t t nil 2)
6019 (replace-match new-delim t t nil 4))))
6022 ;;; Keymap ====================================================================
6024 (defun markdown--style-map-prompt ()
6025 "Return a formatted prompt for Markdown markup insertion."
6026 (when markdown-enable-prefix-prompts
6027 (concat
6028 "Markdown: "
6029 (propertize "bold" 'face 'markdown-bold-face) ", "
6030 (propertize "italic" 'face 'markdown-italic-face) ", "
6031 (propertize "code" 'face 'markdown-inline-code-face) ", "
6032 (propertize "C = GFM code" 'face 'markdown-code-face) ", "
6033 (propertize "pre" 'face 'markdown-pre-face) ", "
6034 (propertize "footnote" 'face 'markdown-footnote-text-face) ", "
6035 (propertize "q = blockquote" 'face 'markdown-blockquote-face) ", "
6036 (propertize "h & 1-6 = heading" 'face 'markdown-header-face) ", "
6037 (propertize "- = hr" 'face 'markdown-hr-face) ", "
6038 "C-h = more")))
6040 (defun markdown--command-map-prompt ()
6041 "Return prompt for Markdown buffer-wide commands."
6042 (when markdown-enable-prefix-prompts
6043 (concat
6044 "Command: "
6045 (propertize "m" 'face 'markdown-bold-face) "arkdown, "
6046 (propertize "p" 'face 'markdown-bold-face) "review, "
6047 (propertize "o" 'face 'markdown-bold-face) "pen, "
6048 (propertize "e" 'face 'markdown-bold-face) "xport, "
6049 "export & pre" (propertize "v" 'face 'markdown-bold-face) "iew, "
6050 (propertize "c" 'face 'markdown-bold-face) "heck refs, "
6051 "C-h = more")))
6053 (defvar markdown-mode-style-map
6054 (let ((map (make-keymap (markdown--style-map-prompt))))
6055 (define-key map (kbd "1") 'markdown-insert-header-atx-1)
6056 (define-key map (kbd "2") 'markdown-insert-header-atx-2)
6057 (define-key map (kbd "3") 'markdown-insert-header-atx-3)
6058 (define-key map (kbd "4") 'markdown-insert-header-atx-4)
6059 (define-key map (kbd "5") 'markdown-insert-header-atx-5)
6060 (define-key map (kbd "6") 'markdown-insert-header-atx-6)
6061 (define-key map (kbd "!") 'markdown-insert-header-setext-1)
6062 (define-key map (kbd "@") 'markdown-insert-header-setext-2)
6063 (define-key map (kbd "b") 'markdown-insert-bold)
6064 (define-key map (kbd "c") 'markdown-insert-code)
6065 (define-key map (kbd "C") 'markdown-insert-gfm-code-block)
6066 (define-key map (kbd "f") 'markdown-insert-footnote)
6067 (define-key map (kbd "h") 'markdown-insert-header-dwim)
6068 (define-key map (kbd "H") 'markdown-insert-header-setext-dwim)
6069 (define-key map (kbd "i") 'markdown-insert-italic)
6070 (define-key map (kbd "k") 'markdown-insert-kbd)
6071 (define-key map (kbd "l") 'markdown-insert-link)
6072 (define-key map (kbd "p") 'markdown-insert-pre)
6073 (define-key map (kbd "P") 'markdown-pre-region)
6074 (define-key map (kbd "q") 'markdown-insert-blockquote)
6075 (define-key map (kbd "s") 'markdown-insert-strike-through)
6076 (define-key map (kbd "Q") 'markdown-blockquote-region)
6077 (define-key map (kbd "w") 'markdown-insert-wiki-link)
6078 (define-key map (kbd "-") 'markdown-insert-hr)
6079 (define-key map (kbd "[") 'markdown-insert-gfm-checkbox)
6080 ;; Deprecated keys that may be removed in a future version
6081 (define-key map (kbd "e") 'markdown-insert-italic)
6082 map)
6083 "Keymap for Markdown text styling commands.")
6085 (defvar markdown-mode-command-map
6086 (let ((map (make-keymap (markdown--command-map-prompt))))
6087 (define-key map (kbd "m") 'markdown-other-window)
6088 (define-key map (kbd "p") 'markdown-preview)
6089 (define-key map (kbd "e") 'markdown-export)
6090 (define-key map (kbd "v") 'markdown-export-and-preview)
6091 (define-key map (kbd "o") 'markdown-open)
6092 (define-key map (kbd "l") 'markdown-live-preview-mode)
6093 (define-key map (kbd "w") 'markdown-kill-ring-save)
6094 (define-key map (kbd "c") 'markdown-check-refs)
6095 (define-key map (kbd "n") 'markdown-cleanup-list-numbers)
6096 (define-key map (kbd "]") 'markdown-complete-buffer)
6097 (define-key map (kbd "^") 'markdown-table-sort-lines)
6098 (define-key map (kbd "|") 'markdown-table-convert-region)
6099 (define-key map (kbd "t") 'markdown-table-transpose)
6100 map)
6101 "Keymap for Markdown buffer-wide commands.")
6103 (defvar markdown-mode-map
6104 (let ((map (make-keymap)))
6105 ;; Markup insertion & removal
6106 (define-key map (kbd "C-c C-s") markdown-mode-style-map)
6107 (define-key map (kbd "C-c C-l") 'markdown-insert-link)
6108 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
6109 ;; Promotion, demotion, and cycling
6110 (define-key map (kbd "C-c C--") 'markdown-promote)
6111 (define-key map (kbd "C-c C-=") 'markdown-demote)
6112 (define-key map (kbd "C-c C-]") 'markdown-complete)
6113 ;; Following and doing things
6114 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
6115 (define-key map (kbd "C-c C-d") 'markdown-do)
6116 (define-key map (kbd "C-c '") 'markdown-edit-code-block)
6117 ;; Indentation
6118 (define-key map (kbd "C-m") 'markdown-enter-key)
6119 (define-key map (kbd "DEL") 'markdown-outdent-or-delete)
6120 (define-key map (kbd "C-c >") 'markdown-indent-region)
6121 (define-key map (kbd "C-c <") 'markdown-outdent-region)
6122 ;; Visibility cycling
6123 (define-key map (kbd "TAB") 'markdown-cycle)
6124 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
6125 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
6126 (define-key map (kbd "<backtab>") 'markdown-shifttab)
6127 ;; Heading and list navigation
6128 (define-key map (kbd "C-c C-n") 'markdown-outline-next)
6129 (define-key map (kbd "C-c C-p") 'markdown-outline-previous)
6130 (define-key map (kbd "C-c C-f") 'markdown-outline-next-same-level)
6131 (define-key map (kbd "C-c C-b") 'markdown-outline-previous-same-level)
6132 (define-key map (kbd "C-c C-u") 'markdown-outline-up)
6133 ;; Buffer-wide commands
6134 (define-key map (kbd "C-c C-c") markdown-mode-command-map)
6135 ;; Subtree, list, and table editing
6136 (define-key map (kbd "C-c <up>") 'markdown-move-up)
6137 (define-key map (kbd "C-c <down>") 'markdown-move-down)
6138 (define-key map (kbd "C-c <left>") 'markdown-promote)
6139 (define-key map (kbd "C-c <right>") 'markdown-demote)
6140 (define-key map (kbd "C-c S-<up>") 'markdown-table-delete-row)
6141 (define-key map (kbd "C-c S-<down>") 'markdown-table-insert-row)
6142 (define-key map (kbd "C-c S-<left>") 'markdown-table-delete-column)
6143 (define-key map (kbd "C-c S-<right>") 'markdown-table-insert-column)
6144 (define-key map (kbd "C-c C-M-h") 'markdown-mark-subtree)
6145 (define-key map (kbd "C-x n s") 'markdown-narrow-to-subtree)
6146 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
6147 (define-key map (kbd "C-c C-j") 'markdown-insert-list-item)
6148 ;; Paragraphs (Markdown context aware)
6149 (define-key map [remap backward-paragraph] 'markdown-backward-paragraph)
6150 (define-key map [remap forward-paragraph] 'markdown-forward-paragraph)
6151 (define-key map [remap mark-paragraph] 'markdown-mark-paragraph)
6152 ;; Blocks (one or more paragraphs)
6153 (define-key map (kbd "C-M-{") 'markdown-backward-block)
6154 (define-key map (kbd "C-M-}") 'markdown-forward-block)
6155 (define-key map (kbd "C-c M-h") 'markdown-mark-block)
6156 (define-key map (kbd "C-x n b") 'markdown-narrow-to-block)
6157 ;; Pages (top-level sections)
6158 (define-key map [remap backward-page] 'markdown-backward-page)
6159 (define-key map [remap forward-page] 'markdown-forward-page)
6160 (define-key map [remap mark-page] 'markdown-mark-page)
6161 (define-key map [remap narrow-to-page] 'markdown-narrow-to-page)
6162 ;; Link Movement
6163 (define-key map (kbd "M-n") 'markdown-next-link)
6164 (define-key map (kbd "M-p") 'markdown-previous-link)
6165 ;; Toggling functionality
6166 (define-key map (kbd "C-c C-x C-e") 'markdown-toggle-math)
6167 (define-key map (kbd "C-c C-x C-f") 'markdown-toggle-fontify-code-blocks-natively)
6168 (define-key map (kbd "C-c C-x C-i") 'markdown-toggle-inline-images)
6169 (define-key map (kbd "C-c C-x C-l") 'markdown-toggle-url-hiding)
6170 (define-key map (kbd "C-c C-x C-m") 'markdown-toggle-markup-hiding)
6171 ;; Alternative keys (in case of problems with the arrow keys)
6172 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
6173 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
6174 (define-key map (kbd "C-c C-x l") 'markdown-promote)
6175 (define-key map (kbd "C-c C-x r") 'markdown-demote)
6176 ;; Deprecated keys that may be removed in a future version
6177 (define-key map (kbd "C-c C-a L") 'markdown-insert-link) ;; C-c C-l
6178 (define-key map (kbd "C-c C-a l") 'markdown-insert-link) ;; C-c C-l
6179 (define-key map (kbd "C-c C-a r") 'markdown-insert-link) ;; C-c C-l
6180 (define-key map (kbd "C-c C-a u") 'markdown-insert-uri) ;; C-c C-l
6181 (define-key map (kbd "C-c C-a f") 'markdown-insert-footnote)
6182 (define-key map (kbd "C-c C-a w") 'markdown-insert-wiki-link)
6183 (define-key map (kbd "C-c C-t 1") 'markdown-insert-header-atx-1)
6184 (define-key map (kbd "C-c C-t 2") 'markdown-insert-header-atx-2)
6185 (define-key map (kbd "C-c C-t 3") 'markdown-insert-header-atx-3)
6186 (define-key map (kbd "C-c C-t 4") 'markdown-insert-header-atx-4)
6187 (define-key map (kbd "C-c C-t 5") 'markdown-insert-header-atx-5)
6188 (define-key map (kbd "C-c C-t 6") 'markdown-insert-header-atx-6)
6189 (define-key map (kbd "C-c C-t !") 'markdown-insert-header-setext-1)
6190 (define-key map (kbd "C-c C-t @") 'markdown-insert-header-setext-2)
6191 (define-key map (kbd "C-c C-t h") 'markdown-insert-header-dwim)
6192 (define-key map (kbd "C-c C-t H") 'markdown-insert-header-setext-dwim)
6193 (define-key map (kbd "C-c C-t s") 'markdown-insert-header-setext-2)
6194 (define-key map (kbd "C-c C-t t") 'markdown-insert-header-setext-1)
6195 (define-key map (kbd "C-c C-i") 'markdown-insert-image)
6196 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item) ;; C-c C-j
6197 (define-key map (kbd "C-c C-x C-x") 'markdown-toggle-gfm-checkbox) ;; C-c C-d
6198 (define-key map (kbd "C-c -") 'markdown-insert-hr)
6199 map)
6200 "Keymap for Markdown major mode.")
6202 (defvar markdown-mode-mouse-map
6203 (let ((map (make-sparse-keymap)))
6204 (define-key map [follow-link] 'mouse-face)
6205 (define-key map [mouse-2] 'markdown-follow-link-at-point)
6206 map)
6207 "Keymap for following links with mouse.")
6209 (defvar gfm-mode-map
6210 (let ((map (make-sparse-keymap)))
6211 (set-keymap-parent map markdown-mode-map)
6212 (define-key map (kbd "C-c C-s d") 'markdown-insert-strike-through)
6213 (define-key map "`" 'markdown-electric-backquote)
6214 map)
6215 "Keymap for `gfm-mode'.
6216 See also `markdown-mode-map'.")
6219 ;;; Menu ==================================================================
6221 (easy-menu-define markdown-mode-menu markdown-mode-map
6222 "Menu for Markdown mode"
6223 '("Markdown"
6224 "---"
6225 ("Movement"
6226 ["Jump" markdown-do]
6227 ["Follow Link" markdown-follow-thing-at-point]
6228 ["Next Link" markdown-next-link]
6229 ["Previous Link" markdown-previous-link]
6230 "---"
6231 ["Next Heading or List Item" markdown-outline-next]
6232 ["Previous Heading or List Item" markdown-outline-previous]
6233 ["Next at Same Level" markdown-outline-next-same-level]
6234 ["Previous at Same Level" markdown-outline-previous-same-level]
6235 ["Up to Parent" markdown-outline-up]
6236 "---"
6237 ["Forward Paragraph" markdown-forward-paragraph]
6238 ["Backward Paragraph" markdown-backward-paragraph]
6239 ["Forward Block" markdown-forward-block]
6240 ["Backward Block" markdown-backward-block])
6241 ("Show & Hide"
6242 ["Cycle Heading Visibility" markdown-cycle (markdown-on-heading-p)]
6243 ["Cycle Heading Visibility (Global)" markdown-shifttab]
6244 "---"
6245 ["Narrow to Region" narrow-to-region]
6246 ["Narrow to Block" markdown-narrow-to-block]
6247 ["Narrow to Section" narrow-to-defun]
6248 ["Narrow to Subtree" markdown-narrow-to-subtree]
6249 ["Widen" widen (buffer-narrowed-p)]
6250 "---"
6251 ["Toggle Markup Hiding" markdown-toggle-markup-hiding
6252 :keys "C-c C-x C-m"
6253 :style radio
6254 :selected markdown-hide-markup])
6255 "---"
6256 ("Headings & Structure"
6257 ["Automatic Heading" markdown-insert-header-dwim :keys "C-c C-s h"]
6258 ["Automatic Heading (Setext)" markdown-insert-header-setext-dwim :keys "C-c C-s H"]
6259 ("Specific Heading (atx)"
6260 ["First Level atx" markdown-insert-header-atx-1 :keys "C-c C-s 1"]
6261 ["Second Level atx" markdown-insert-header-atx-2 :keys "C-c C-s 2"]
6262 ["Third Level atx" markdown-insert-header-atx-3 :keys "C-c C-s 3"]
6263 ["Fourth Level atx" markdown-insert-header-atx-4 :keys "C-c C-s 4"]
6264 ["Fifth Level atx" markdown-insert-header-atx-5 :keys "C-c C-s 5"]
6265 ["Sixth Level atx" markdown-insert-header-atx-6 :keys "C-c C-s 6"])
6266 ("Specific Heading (Setext)"
6267 ["First Level Setext" markdown-insert-header-setext-1 :keys "C-c C-s !"]
6268 ["Second Level Setext" markdown-insert-header-setext-2 :keys "C-c C-s @"])
6269 ["Horizontal Rule" markdown-insert-hr :keys "C-c C-s -"]
6270 "---"
6271 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
6272 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
6273 ["Promote Subtree" markdown-promote :keys "C-c <left>"]
6274 ["Demote Subtree" markdown-demote :keys "C-c <right>"])
6275 ("Region & Mark"
6276 ["Indent Region" markdown-indent-region]
6277 ["Outdent Region" markdown-outdent-region]
6278 "--"
6279 ["Mark Paragraph" mark-paragraph]
6280 ["Mark Block" markdown-mark-block]
6281 ["Mark Section" mark-defun]
6282 ["Mark Subtree" markdown-mark-subtree])
6283 ("Lists"
6284 ["Insert List Item" markdown-insert-list-item]
6285 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
6286 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
6287 ["Indent Subtree" markdown-demote :keys "C-c <right>"]
6288 ["Outdent Subtree" markdown-promote :keys "C-c <left>"]
6289 ["Renumber List" markdown-cleanup-list-numbers]
6290 ["Insert Task List Item" markdown-insert-gfm-checkbox :keys "C-c C-x ["]
6291 ["Toggle Task List Item" markdown-toggle-gfm-checkbox (markdown-gfm-task-list-item-at-point) :keys "C-c C-d"])
6292 ("Links & Images"
6293 ["Insert Link" markdown-insert-link]
6294 ["Insert Image" markdown-insert-image]
6295 ["Insert Footnote" markdown-insert-footnote :keys "C-c C-s f"]
6296 ["Insert Wiki Link" markdown-insert-wiki-link :keys "C-c C-s w"]
6297 "---"
6298 ["Check References" markdown-check-refs]
6299 ["Toggle URL Hiding" markdown-toggle-url-hiding
6300 :style radio
6301 :selected markdown-hide-urls]
6302 ["Toggle Inline Images" markdown-toggle-inline-images
6303 :keys "C-c C-x C-i"
6304 :style radio
6305 :selected markdown-inline-image-overlays]
6306 ["Toggle Wiki Links" markdown-toggle-wiki-links
6307 :style radio
6308 :selected markdown-enable-wiki-links])
6309 ("Styles"
6310 ["Bold" markdown-insert-bold]
6311 ["Italic" markdown-insert-italic]
6312 ["Code" markdown-insert-code]
6313 ["Strikethrough" markdown-insert-strike-through]
6314 ["Keyboard" markdown-insert-kbd]
6315 "---"
6316 ["Blockquote" markdown-insert-blockquote]
6317 ["Preformatted" markdown-insert-pre]
6318 ["GFM Code Block" markdown-insert-gfm-code-block]
6319 ["Edit Code Block" markdown-edit-code-block (markdown-code-block-at-point-p)]
6320 "---"
6321 ["Blockquote Region" markdown-blockquote-region]
6322 ["Preformatted Region" markdown-pre-region]
6323 "---"
6324 ["Fontify Code Blocks Natively" markdown-toggle-fontify-code-blocks-natively
6325 :style radio
6326 :selected markdown-fontify-code-blocks-natively]
6327 ["LaTeX Math Support" markdown-toggle-math
6328 :style radio
6329 :selected markdown-enable-math])
6330 "---"
6331 ("Preview & Export"
6332 ["Compile" markdown-other-window]
6333 ["Preview" markdown-preview]
6334 ["Export" markdown-export]
6335 ["Export & View" markdown-export-and-preview]
6336 ["Open" markdown-open]
6337 ["Live Export" markdown-live-preview-mode
6338 :style radio
6339 :selected markdown-live-preview-mode]
6340 ["Kill ring save" markdown-kill-ring-save])
6341 ("Markup Completion and Cycling"
6342 ["Complete Markup" markdown-complete]
6343 ["Promote Element" markdown-promote :keys "C-c C--"]
6344 ["Demote Element" markdown-demote :keys "C-c C-="])
6345 "---"
6346 ["Kill Element" markdown-kill-thing-at-point]
6347 "---"
6348 ("Documentation"
6349 ["Version" markdown-show-version]
6350 ["Homepage" markdown-mode-info]
6351 ["Describe Mode" (describe-function 'markdown-mode)]
6352 ["Guide" (browse-url "https://leanpub.com/markdown-mode")])))
6355 ;;; imenu =====================================================================
6357 (defun markdown-imenu-create-nested-index ()
6358 "Create and return a nested imenu index alist for the current buffer.
6359 See `imenu-create-index-function' and `imenu--index-alist' for details."
6360 (let* ((root '(nil . nil))
6361 cur-alist
6362 (cur-level 0)
6363 (empty-heading "-")
6364 (self-heading ".")
6365 hashes pos level heading)
6366 (save-excursion
6367 (goto-char (point-min))
6368 (while (re-search-forward markdown-regex-header (point-max) t)
6369 (unless (markdown-code-block-at-point-p)
6370 (cond
6371 ((match-string-no-properties 2) ;; level 1 setext
6372 (setq heading (match-string-no-properties 1))
6373 (setq pos (match-beginning 1)
6374 level 1))
6375 ((match-string-no-properties 3) ;; level 2 setext
6376 (setq heading (match-string-no-properties 1))
6377 (setq pos (match-beginning 1)
6378 level 2))
6379 ((setq hashes (markdown-trim-whitespace
6380 (match-string-no-properties 4)))
6381 (setq heading (match-string-no-properties 5)
6382 pos (match-beginning 4)
6383 level (length hashes))))
6384 (let ((alist (list (cons heading pos))))
6385 (cond
6386 ((= cur-level level) ; new sibling
6387 (setcdr cur-alist alist)
6388 (setq cur-alist alist))
6389 ((< cur-level level) ; first child
6390 (dotimes (_ (- level cur-level 1))
6391 (setq alist (list (cons empty-heading alist))))
6392 (if cur-alist
6393 (let* ((parent (car cur-alist))
6394 (self-pos (cdr parent)))
6395 (setcdr parent (cons (cons self-heading self-pos) alist)))
6396 (setcdr root alist)) ; primogenitor
6397 (setq cur-alist alist)
6398 (setq cur-level level))
6399 (t ; new sibling of an ancestor
6400 (let ((sibling-alist (last (cdr root))))
6401 (dotimes (_ (1- level))
6402 (setq sibling-alist (last (cdar sibling-alist))))
6403 (setcdr sibling-alist alist)
6404 (setq cur-alist alist))
6405 (setq cur-level level))))))
6406 (cdr root))))
6408 (defun markdown-imenu-create-flat-index ()
6409 "Create and return a flat imenu index alist for the current buffer.
6410 See `imenu-create-index-function' and `imenu--index-alist' for details."
6411 (let* ((empty-heading "-") index heading pos)
6412 (save-excursion
6413 (goto-char (point-min))
6414 (while (re-search-forward markdown-regex-header (point-max) t)
6415 (when (and (not (markdown-code-block-at-point-p))
6416 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin)))
6417 (cond
6418 ((setq heading (match-string-no-properties 1))
6419 (setq pos (match-beginning 1)))
6420 ((setq heading (match-string-no-properties 5))
6421 (setq pos (match-beginning 4))))
6422 (or (> (length heading) 0)
6423 (setq heading empty-heading))
6424 (setq index (append index (list (cons heading pos))))))
6425 index)))
6428 ;;; References ================================================================
6430 (defun markdown-reference-goto-definition ()
6431 "Jump to the definition of the reference at point or create it."
6432 (interactive)
6433 (when (thing-at-point-looking-at markdown-regex-link-reference)
6434 (let* ((text (match-string-no-properties 3))
6435 (reference (match-string-no-properties 6))
6436 (target (downcase (if (string= reference "") text reference)))
6437 (loc (cadr (save-match-data (markdown-reference-definition target)))))
6438 (if loc
6439 (goto-char loc)
6440 (goto-char (match-beginning 0))
6441 (markdown-insert-reference-definition target)))))
6443 (defun markdown-reference-find-links (reference)
6444 "Return a list of all links for REFERENCE.
6445 REFERENCE should not include the surrounding square brackets.
6446 Elements of the list have the form (text start line), where
6447 text is the link text, start is the location at the beginning of
6448 the link, and line is the line number on which the link appears."
6449 (let* ((ref-quote (regexp-quote reference))
6450 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
6451 ref-quote ref-quote))
6452 links)
6453 (save-excursion
6454 (goto-char (point-min))
6455 (while (re-search-forward regexp nil t)
6456 (let* ((text (or (match-string-no-properties 1)
6457 (match-string-no-properties 2)))
6458 (start (match-beginning 0))
6459 (line (markdown-line-number-at-pos)))
6460 (cl-pushnew (list text start line) links :test #'equal))))
6461 links))
6463 (defun markdown-get-undefined-refs ()
6464 "Return a list of undefined Markdown references.
6465 Result is an alist of pairs (reference . occurrences), where
6466 occurrences is itself another alist of pairs (label . line-number).
6467 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
6468 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
6469 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
6470 (let ((missing))
6471 (save-excursion
6472 (goto-char (point-min))
6473 (while
6474 (re-search-forward markdown-regex-link-reference nil t)
6475 (let* ((text (match-string-no-properties 3))
6476 (reference (match-string-no-properties 6))
6477 (target (downcase (if (string= reference "") text reference))))
6478 (unless (markdown-reference-definition target)
6479 (let ((entry (assoc target missing)))
6480 (if (not entry)
6481 (cl-pushnew
6482 (cons target (list (cons text (markdown-line-number-at-pos))))
6483 missing :test #'equal)
6484 (setcdr entry
6485 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
6486 (reverse missing))))
6488 (defconst markdown-reference-check-buffer
6489 "*Undefined references for %buffer%*"
6490 "Pattern for name of buffer for listing undefined references.
6491 The string %buffer% will be replaced by the corresponding
6492 `markdown-mode' buffer name.")
6494 (defun markdown-reference-check-buffer (&optional buffer-name)
6495 "Name and return buffer for reference checking.
6496 BUFFER-NAME is the name of the main buffer being visited."
6497 (or buffer-name (setq buffer-name (buffer-name)))
6498 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
6499 "%buffer%" buffer-name
6500 markdown-reference-check-buffer))))
6501 (with-current-buffer refbuf
6502 (when view-mode
6503 (View-exit-and-edit))
6504 (use-local-map button-buffer-map)
6505 (erase-buffer))
6506 refbuf))
6508 (defconst markdown-reference-links-buffer
6509 "*Reference links for %buffer%*"
6510 "Pattern for name of buffer for listing references.
6511 The string %buffer% will be replaced by the corresponding buffer name.")
6513 (defun markdown-reference-links-buffer (&optional buffer-name)
6514 "Name, setup, and return a buffer for listing links.
6515 BUFFER-NAME is the name of the main buffer being visited."
6516 (or buffer-name (setq buffer-name (buffer-name)))
6517 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
6518 "%buffer%" buffer-name
6519 markdown-reference-links-buffer))))
6520 (with-current-buffer linkbuf
6521 (when view-mode
6522 (View-exit-and-edit))
6523 (use-local-map button-buffer-map)
6524 (erase-buffer))
6525 linkbuf))
6527 ;; Add an empty Markdown reference definition to buffer
6528 ;; specified in the 'target-buffer property. The reference name is
6529 ;; the button's label.
6530 (define-button-type 'markdown-undefined-reference-button
6531 'help-echo "mouse-1, RET: create definition for undefined reference"
6532 'follow-link t
6533 'face 'bold
6534 'action (lambda (b)
6535 (let ((buffer (button-get b 'target-buffer))
6536 (line (button-get b 'target-line))
6537 (label (button-label b)))
6538 (switch-to-buffer-other-window buffer)
6539 (goto-char (point-min))
6540 (forward-line line)
6541 (markdown-insert-reference-definition label)
6542 (markdown-check-refs t))))
6544 ;; Jump to line in buffer specified by 'target-buffer property.
6545 ;; Line number is button's 'line property.
6546 (define-button-type 'markdown-goto-line-button
6547 'help-echo "mouse-1, RET: go to line"
6548 'follow-link t
6549 'face 'italic
6550 'action (lambda (b)
6551 (message (button-get b 'buffer))
6552 (switch-to-buffer-other-window (button-get b 'target-buffer))
6553 ;; use call-interactively to silence compiler
6554 (let ((current-prefix-arg (button-get b 'target-line)))
6555 (call-interactively 'goto-line))))
6557 ;; Jumps to a particular link at location given by 'target-char
6558 ;; property in buffer given by 'target-buffer property.
6559 (define-button-type 'markdown-location-button
6560 'help-echo "mouse-1, RET: jump to location of link"
6561 'follow-link t
6562 'face 'bold
6563 'action (lambda (b)
6564 (let ((target (button-get b 'target-buffer))
6565 (loc (button-get b 'target-char)))
6566 (kill-buffer-and-window)
6567 (switch-to-buffer target)
6568 (goto-char loc))))
6570 (defun markdown-insert-undefined-reference-button (reference oldbuf)
6571 "Insert a button for creating REFERENCE in buffer OLDBUF.
6572 REFERENCE should be a list of the form (reference . occurrences),
6573 as by `markdown-get-undefined-refs'."
6574 (let ((label (car reference)))
6575 ;; Create a reference button
6576 (insert-button label
6577 :type 'markdown-undefined-reference-button
6578 'target-buffer oldbuf
6579 'target-line (cdr (car (cdr reference))))
6580 (insert " (")
6581 (dolist (occurrence (cdr reference))
6582 (let ((line (cdr occurrence)))
6583 ;; Create a line number button
6584 (insert-button (number-to-string line)
6585 :type 'markdown-goto-line-button
6586 'target-buffer oldbuf
6587 'target-line line)
6588 (insert " ")))
6589 (delete-char -1)
6590 (insert ")")
6591 (newline)))
6593 (defun markdown-insert-link-button (link oldbuf)
6594 "Insert a button for jumping to LINK in buffer OLDBUF.
6595 LINK should be a list of the form (text char line) containing
6596 the link text, location, and line number."
6597 (let ((label (cl-first link))
6598 (char (cl-second link))
6599 (line (cl-third link)))
6600 ;; Create a reference button
6601 (insert-button label
6602 :type 'markdown-location-button
6603 'target-buffer oldbuf
6604 'target-char char)
6605 (insert (format " (line %d)\n" line))))
6607 (defun markdown-reference-goto-link (&optional reference)
6608 "Jump to the location of the first use of REFERENCE."
6609 (interactive)
6610 (unless reference
6611 (if (thing-at-point-looking-at markdown-regex-reference-definition)
6612 (setq reference (match-string-no-properties 2))
6613 (user-error "No reference definition at point")))
6614 (let ((links (markdown-reference-find-links reference)))
6615 (cond ((= (length links) 1)
6616 (goto-char (cadr (car links))))
6617 ((> (length links) 1)
6618 (let ((oldbuf (current-buffer))
6619 (linkbuf (markdown-reference-links-buffer)))
6620 (with-current-buffer linkbuf
6621 (insert "Links using reference " reference ":\n\n")
6622 (dolist (link (reverse links))
6623 (markdown-insert-link-button link oldbuf)))
6624 (view-buffer-other-window linkbuf)
6625 (goto-char (point-min))
6626 (forward-line 2)))
6628 (error "No links for reference %s" reference)))))
6630 (defun markdown-check-refs (&optional silent)
6631 "Show all undefined Markdown references in current `markdown-mode' buffer.
6632 If SILENT is non-nil, do not message anything when no undefined
6633 references found.
6634 Links which have empty reference definitions are considered to be
6635 defined."
6636 (interactive "P")
6637 (when (not (eq major-mode 'markdown-mode))
6638 (user-error "Not available in current mode"))
6639 (let ((oldbuf (current-buffer))
6640 (refs (markdown-get-undefined-refs))
6641 (refbuf (markdown-reference-check-buffer)))
6642 (if (null refs)
6643 (progn
6644 (when (not silent)
6645 (message "No undefined references found"))
6646 (kill-buffer refbuf))
6647 (with-current-buffer refbuf
6648 (insert "The following references are undefined:\n\n")
6649 (dolist (ref refs)
6650 (markdown-insert-undefined-reference-button ref oldbuf))
6651 (view-buffer-other-window refbuf)
6652 (goto-char (point-min))
6653 (forward-line 2)))))
6656 ;;; Lists =====================================================================
6658 (defun markdown-insert-list-item (&optional arg)
6659 "Insert a new list item.
6660 If the point is inside unordered list, insert a bullet mark. If
6661 the point is inside ordered list, insert the next number followed
6662 by a period. Use the previous list item to determine the amount
6663 of whitespace to place before and after list markers.
6665 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
6666 decrease the indentation by one level.
6668 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
6669 increase the indentation by one level."
6670 (interactive "p")
6671 (let (bounds cur-indent marker indent new-indent new-loc)
6672 (save-match-data
6673 ;; Look for a list item on current or previous non-blank line
6674 (save-excursion
6675 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
6676 (not (bobp))
6677 (markdown-cur-line-blank-p))
6678 (forward-line -1)))
6679 (when bounds
6680 (cond ((save-excursion
6681 (skip-chars-backward " \t")
6682 (looking-at-p markdown-regex-list))
6683 (beginning-of-line)
6684 (insert "\n")
6685 (forward-line -1))
6686 ((not (markdown-cur-line-blank-p))
6687 (newline)))
6688 (setq new-loc (point)))
6689 ;; Look ahead for a list item on next non-blank line
6690 (unless bounds
6691 (save-excursion
6692 (while (and (null bounds)
6693 (not (eobp))
6694 (markdown-cur-line-blank-p))
6695 (forward-line)
6696 (setq bounds (markdown-cur-list-item-bounds))))
6697 (when bounds
6698 (setq new-loc (point))
6699 (unless (markdown-cur-line-blank-p)
6700 (newline))))
6701 (if (not bounds)
6702 ;; When not in a list, start a new unordered one
6703 (progn
6704 (unless (markdown-cur-line-blank-p)
6705 (insert "\n"))
6706 (insert markdown-unordered-list-item-prefix))
6707 ;; Compute indentation and marker for new list item
6708 (setq cur-indent (nth 2 bounds))
6709 (setq marker (nth 4 bounds))
6710 ;; If current item is a GFM checkbox, insert new unchecked checkbox.
6711 (when (nth 5 bounds)
6712 (setq marker
6713 (concat marker
6714 (replace-regexp-in-string "[Xx]" " " (nth 5 bounds)))))
6715 (cond
6716 ;; Dedent: decrement indentation, find previous marker.
6717 ((= arg 4)
6718 (setq indent (max (- cur-indent 4) 0))
6719 (let ((prev-bounds
6720 (save-excursion
6721 (goto-char (nth 0 bounds))
6722 (when (markdown-up-list)
6723 (markdown-cur-list-item-bounds)))))
6724 (when prev-bounds
6725 (setq marker (nth 4 prev-bounds)))))
6726 ;; Indent: increment indentation by 4, use same marker.
6727 ((= arg 16) (setq indent (+ cur-indent 4)))
6728 ;; Same level: keep current indentation and marker.
6729 (t (setq indent cur-indent)))
6730 (setq new-indent (make-string indent 32))
6731 (goto-char new-loc)
6732 (cond
6733 ;; Ordered list
6734 ((string-match-p "[0-9]" marker)
6735 (if (= arg 16) ;; starting a new column indented one more level
6736 (insert (concat new-indent "1. "))
6737 ;; Don't use previous match-data
6738 (set-match-data nil)
6739 ;; travel up to the last item and pick the correct number. If
6740 ;; the argument was nil, "new-indent = cur-indent" is the same,
6741 ;; so we don't need special treatment. Neat.
6742 (save-excursion
6743 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
6744 (>= (forward-line -1) 0))))
6745 (let* ((old-prefix (match-string 1))
6746 (old-spacing (match-string 2))
6747 (new-prefix (if old-prefix
6748 (int-to-string (1+ (string-to-number old-prefix)))
6749 "1"))
6750 (space-adjust (- (length old-prefix) (length new-prefix)))
6751 (new-spacing (if (and (match-string 2)
6752 (not (string-match-p "\t" old-spacing))
6753 (< space-adjust 0)
6754 (> space-adjust (- 1 (length (match-string 2)))))
6755 (substring (match-string 2) 0 space-adjust)
6756 (or old-spacing ". "))))
6757 (insert (concat new-indent new-prefix new-spacing)))))
6758 ;; Unordered list, GFM task list, or ordered list with hash mark
6759 ((string-match-p "[\\*\\+-]\\|#\\." marker)
6760 (insert new-indent marker)))))))
6762 (defun markdown-move-list-item-up ()
6763 "Move the current list item up in the list when possible.
6764 In nested lists, move child items with the parent item."
6765 (interactive)
6766 (let (cur prev old)
6767 (when (setq cur (markdown-cur-list-item-bounds))
6768 (setq old (point))
6769 (goto-char (nth 0 cur))
6770 (if (markdown-prev-list-item (nth 3 cur))
6771 (progn
6772 (setq prev (markdown-cur-list-item-bounds))
6773 (condition-case nil
6774 (progn
6775 (transpose-regions (nth 0 prev) (nth 1 prev)
6776 (nth 0 cur) (nth 1 cur) t)
6777 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
6778 ;; Catch error in case regions overlap.
6779 (error (goto-char old))))
6780 (goto-char old)))))
6782 (defun markdown-move-list-item-down ()
6783 "Move the current list item down in the list when possible.
6784 In nested lists, move child items with the parent item."
6785 (interactive)
6786 (let (cur next old)
6787 (when (setq cur (markdown-cur-list-item-bounds))
6788 (setq old (point))
6789 (if (markdown-next-list-item (nth 3 cur))
6790 (progn
6791 (setq next (markdown-cur-list-item-bounds))
6792 (condition-case nil
6793 (progn
6794 (transpose-regions (nth 0 cur) (nth 1 cur)
6795 (nth 0 next) (nth 1 next) nil)
6796 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
6797 ;; Catch error in case regions overlap.
6798 (error (goto-char old))))
6799 (goto-char old)))))
6801 (defun markdown-demote-list-item (&optional bounds)
6802 "Indent (or demote) the current list item.
6803 Optionally, BOUNDS of the current list item may be provided if available.
6804 In nested lists, demote child items as well."
6805 (interactive)
6806 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6807 (save-excursion
6808 (let ((end-marker (set-marker (make-marker) (nth 1 bounds))))
6809 (goto-char (nth 0 bounds))
6810 (while (< (point) end-marker)
6811 (unless (markdown-cur-line-blank-p)
6812 (insert (make-string markdown-list-indent-width ? )))
6813 (forward-line))))))
6815 (defun markdown-promote-list-item (&optional bounds)
6816 "Unindent (or promote) the current list item.
6817 Optionally, BOUNDS of the current list item may be provided if available.
6818 In nested lists, demote child items as well."
6819 (interactive)
6820 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6821 (save-excursion
6822 (save-match-data
6823 (let ((end-marker (set-marker (make-marker) (nth 1 bounds)))
6824 num regexp)
6825 (goto-char (nth 0 bounds))
6826 (when (looking-at (format "^[ ]\\{1,%d\\}"
6827 markdown-list-indent-width))
6828 (setq num (- (match-end 0) (match-beginning 0)))
6829 (setq regexp (format "^[ ]\\{1,%d\\}" num))
6830 (while (and (< (point) end-marker)
6831 (re-search-forward regexp end-marker t))
6832 (replace-match "" nil nil)
6833 (forward-line))))))))
6835 (defun markdown-cleanup-list-numbers-level (&optional pfx)
6836 "Update the numbering for level PFX (as a string of spaces).
6838 Assume that the previously found match was for a numbered item in
6839 a list."
6840 (let ((cpfx pfx)
6841 (idx 0)
6842 (continue t)
6843 (step t)
6844 (sep nil))
6845 (while (and continue (not (eobp)))
6846 (setq step t)
6847 (cond
6848 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
6849 (setq cpfx (match-string-no-properties 1))
6850 (cond
6851 ((string= cpfx pfx)
6852 (save-excursion
6853 (replace-match
6854 (concat pfx (number-to-string (setq idx (1+ idx))) ". ")))
6855 (setq sep nil))
6856 ;; indented a level
6857 ((string< pfx cpfx)
6858 (setq sep (markdown-cleanup-list-numbers-level cpfx))
6859 (setq step nil))
6860 ;; exit the loop
6862 (setq step nil)
6863 (setq continue nil))))
6865 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
6866 (setq cpfx (match-string-no-properties 1))
6867 (cond
6868 ;; reset if separated before
6869 ((string= cpfx pfx) (when sep (setq idx 0)))
6870 ((string< cpfx pfx)
6871 (setq step nil)
6872 (setq continue nil))))
6873 (t (setq sep t)))
6875 (when step
6876 (beginning-of-line)
6877 (setq continue (= (forward-line) 0))))
6878 sep))
6880 (defun markdown-cleanup-list-numbers ()
6881 "Update the numbering of ordered lists."
6882 (interactive)
6883 (save-excursion
6884 (goto-char (point-min))
6885 (markdown-cleanup-list-numbers-level "")))
6888 ;;; Movement ==================================================================
6890 (defun markdown-beginning-of-defun (&optional arg)
6891 "`beginning-of-defun-function' for Markdown.
6892 This is used to find the beginning of the defun and should behave
6893 like ‘beginning-of-defun’, returning non-nil if it found the
6894 beginning of a defun. It moves the point backward, right before a
6895 heading which defines a defun. When ARG is non-nil, repeat that
6896 many times. When ARG is negative, move forward to the ARG-th
6897 following section."
6898 (or arg (setq arg 1))
6899 (when (< arg 0) (end-of-line))
6900 ;; Adjust position for setext headings.
6901 (when (and (thing-at-point-looking-at markdown-regex-header-setext)
6902 (not (= (point) (match-beginning 0)))
6903 (not (markdown-code-block-at-point-p)))
6904 (goto-char (match-end 0)))
6905 (let (found)
6906 ;; Move backward with positive argument.
6907 (while (and (not (bobp)) (> arg 0))
6908 (setq found nil)
6909 (while (and (not found)
6910 (not (bobp))
6911 (re-search-backward markdown-regex-header nil 'move))
6912 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6913 (setq found (match-beginning 0)))
6914 (setq arg (1- arg)))
6915 ;; Move forward with negative argument.
6916 (while (and (not (eobp)) (< arg 0))
6917 (setq found nil)
6918 (while (and (not found)
6919 (not (eobp))
6920 (re-search-forward markdown-regex-header nil 'move))
6921 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6922 (setq found (match-beginning 0)))
6923 (setq arg (1+ arg)))
6924 (when found
6925 (beginning-of-line)
6926 t)))
6928 (defun markdown-end-of-defun ()
6929 "`end-of-defun-function’ for Markdown.
6930 This is used to find the end of the defun at point.
6931 It is called with no argument, right after calling ‘beginning-of-defun-raw’,
6932 so it can assume that point is at the beginning of the defun body.
6933 It should move point to the first position after the defun."
6934 (or (eobp) (forward-char 1))
6935 (let (found)
6936 (while (and (not found)
6937 (not (eobp))
6938 (re-search-forward markdown-regex-header nil 'move))
6939 (when (not (markdown-code-block-at-pos (match-beginning 0)))
6940 (setq found (match-beginning 0))))
6941 (when found
6942 (goto-char found)
6943 (skip-syntax-backward "-"))))
6945 (make-obsolete 'markdown-beginning-of-block 'markdown-beginning-of-text-block "v2.2")
6947 (defun markdown-beginning-of-text-block ()
6948 "Move backward to previous beginning of a plain text block.
6949 This function simply looks for blank lines without considering
6950 the surrounding context in light of Markdown syntax. For that, see
6951 `markdown-backward-block'."
6952 (interactive)
6953 (let ((start (point)))
6954 (if (re-search-backward markdown-regex-block-separator nil t)
6955 (goto-char (match-end 0))
6956 (goto-char (point-min)))
6957 (when (and (= start (point)) (not (bobp)))
6958 (forward-line -1)
6959 (if (re-search-backward markdown-regex-block-separator nil t)
6960 (goto-char (match-end 0))
6961 (goto-char (point-min))))))
6963 (make-obsolete 'markdown-end-of-block 'markdown-end-of-text-block "v2.2")
6965 (defun markdown-end-of-text-block ()
6966 "Move forward to next beginning of a plain text block.
6967 This function simply looks for blank lines without considering
6968 the surrounding context in light of Markdown syntax. For that, see
6969 `markdown-forward-block'."
6970 (interactive)
6971 (beginning-of-line)
6972 (skip-syntax-forward "-")
6973 (when (= (point) (point-min))
6974 (forward-char))
6975 (if (re-search-forward markdown-regex-block-separator nil t)
6976 (goto-char (match-end 0))
6977 (goto-char (point-max)))
6978 (skip-syntax-backward "-")
6979 (forward-line))
6981 (defun markdown-backward-paragraph (&optional arg)
6982 "Move the point to the start of the current paragraph.
6983 With argument ARG, do it ARG times; a negative argument ARG = -N
6984 means move forward N blocks."
6985 (interactive "^p")
6986 (or arg (setq arg 1))
6987 (if (< arg 0)
6988 (markdown-forward-paragraph (- arg))
6989 (dotimes (_ arg)
6990 ;; Skip over whitespace in between paragraphs when moving backward.
6991 (skip-syntax-backward "-")
6992 (beginning-of-line)
6993 ;; Skip over code block endings.
6994 (when (markdown-range-properties-exist
6995 (point-at-bol) (point-at-eol)
6996 '(markdown-gfm-block-end
6997 markdown-tilde-fence-end))
6998 (forward-line -1))
6999 ;; Skip over blank lines inside blockquotes.
7000 (while (and (not (eobp))
7001 (looking-at markdown-regex-blockquote)
7002 (= (length (match-string 3)) 0))
7003 (forward-line -1))
7004 ;; Proceed forward based on the type of block of paragraph.
7005 (let (bounds skip)
7006 (cond
7007 ;; Blockquotes
7008 ((looking-at markdown-regex-blockquote)
7009 (while (and (not (bobp))
7010 (looking-at markdown-regex-blockquote)
7011 (> (length (match-string 3)) 0)) ;; not blank
7012 (forward-line -1))
7013 (forward-line))
7014 ;; List items
7015 ((setq bounds (markdown-cur-list-item-bounds))
7016 (goto-char (nth 0 bounds)))
7017 ;; Other
7019 (while (and (not (bobp))
7020 (not skip)
7021 (not (markdown-cur-line-blank-p))
7022 (not (looking-at markdown-regex-blockquote))
7023 (not (markdown-range-properties-exist
7024 (point-at-bol) (point-at-eol)
7025 '(markdown-gfm-block-end
7026 markdown-tilde-fence-end))))
7027 (setq skip (markdown-range-properties-exist
7028 (point-at-bol) (point-at-eol)
7029 '(markdown-gfm-block-begin
7030 markdown-tilde-fence-begin)))
7031 (forward-line -1))
7032 (unless (bobp)
7033 (forward-line 1))))))))
7035 (defun markdown-forward-paragraph (&optional arg)
7036 "Move forward to the next end of a paragraph.
7037 With argument ARG, do it ARG times; a negative argument ARG = -N
7038 means move backward N blocks."
7039 (interactive "^p")
7040 (or arg (setq arg 1))
7041 (if (< arg 0)
7042 (markdown-backward-paragraph (- arg))
7043 (dotimes (_ arg)
7044 ;; Skip whitespace in between paragraphs.
7045 (when (markdown-cur-line-blank-p)
7046 (skip-syntax-forward "-")
7047 (beginning-of-line))
7048 ;; Proceed forward based on the type of block.
7049 (let (bounds skip)
7050 (cond
7051 ;; Blockquotes
7052 ((looking-at markdown-regex-blockquote)
7053 ;; Skip over blank lines inside blockquotes.
7054 (while (and (not (eobp))
7055 (looking-at markdown-regex-blockquote)
7056 (= (length (match-string 3)) 0))
7057 (forward-line))
7058 ;; Move to end of quoted text block
7059 (while (and (not (eobp))
7060 (looking-at markdown-regex-blockquote)
7061 (> (length (match-string 3)) 0)) ;; not blank
7062 (forward-line)))
7063 ;; List items
7064 ((and (markdown-cur-list-item-bounds)
7065 (setq bounds (markdown-next-list-item-bounds)))
7066 (goto-char (nth 0 bounds)))
7067 ;; Other
7069 (forward-line)
7070 (while (and (not (eobp))
7071 (not skip)
7072 (not (markdown-cur-line-blank-p))
7073 (not (looking-at markdown-regex-blockquote))
7074 (not (markdown-range-properties-exist
7075 (point-at-bol) (point-at-eol)
7076 '(markdown-gfm-block-begin
7077 markdown-tilde-fence-begin))))
7078 (setq skip (markdown-range-properties-exist
7079 (point-at-bol) (point-at-eol)
7080 '(markdown-gfm-block-end
7081 markdown-tilde-fence-end)))
7082 (forward-line))))))))
7084 (defun markdown-backward-block (&optional arg)
7085 "Move the point to the start of the current Markdown block.
7086 Moves across complete code blocks, list items, and blockquotes,
7087 but otherwise stops at blank lines, headers, and horizontal
7088 rules. With argument ARG, do it ARG times; a negative argument
7089 ARG = -N means move forward N blocks."
7090 (interactive "^p")
7091 (or arg (setq arg 1))
7092 (if (< arg 0)
7093 (markdown-forward-block (- arg))
7094 (dotimes (_ arg)
7095 ;; Skip over whitespace in between blocks when moving backward,
7096 ;; unless at a block boundary with no whitespace.
7097 (skip-syntax-backward "-")
7098 (beginning-of-line)
7099 ;; Proceed forward based on the type of block.
7100 (cond
7101 ;; Code blocks
7102 ((and (markdown-code-block-at-pos (point)) ;; this line
7103 (markdown-code-block-at-pos (point-at-bol 0))) ;; previous line
7104 (forward-line -1)
7105 (while (and (markdown-code-block-at-point-p) (not (bobp)))
7106 (forward-line -1))
7107 (forward-line))
7108 ;; Headings
7109 ((markdown-heading-at-point)
7110 (goto-char (match-beginning 0)))
7111 ;; Horizontal rules
7112 ((looking-at markdown-regex-hr))
7113 ;; Blockquotes
7114 ((looking-at markdown-regex-blockquote)
7115 (forward-line -1)
7116 (while (and (looking-at markdown-regex-blockquote)
7117 (not (bobp)))
7118 (forward-line -1))
7119 (forward-line))
7120 ;; List items
7121 ((markdown-cur-list-item-bounds)
7122 (markdown-beginning-of-list))
7123 ;; Other
7125 ;; Move forward in case it is a one line regular paragraph.
7126 (unless (markdown-next-line-blank-p)
7127 (forward-line))
7128 (unless (markdown-prev-line-blank-p)
7129 (markdown-backward-paragraph)))))))
7131 (defun markdown-forward-block (&optional arg)
7132 "Move forward to the next end of a Markdown block.
7133 Moves across complete code blocks, list items, and blockquotes,
7134 but otherwise stops at blank lines, headers, and horizontal
7135 rules. With argument ARG, do it ARG times; a negative argument
7136 ARG = -N means move backward N blocks."
7137 (interactive "^p")
7138 (or arg (setq arg 1))
7139 (if (< arg 0)
7140 (markdown-backward-block (- arg))
7141 (dotimes (_ arg)
7142 ;; Skip over whitespace in between blocks when moving forward.
7143 (if (markdown-cur-line-blank-p)
7144 (skip-syntax-forward "-")
7145 (beginning-of-line))
7146 ;; Proceed forward based on the type of block.
7147 (cond
7148 ;; Code blocks
7149 ((markdown-code-block-at-point-p)
7150 (forward-line)
7151 (while (and (markdown-code-block-at-point-p) (not (eobp)))
7152 (forward-line)))
7153 ;; Headings
7154 ((looking-at markdown-regex-header)
7155 (goto-char (or (match-end 4) (match-end 2) (match-end 3)))
7156 (forward-line))
7157 ;; Horizontal rules
7158 ((looking-at markdown-regex-hr)
7159 (forward-line))
7160 ;; Blockquotes
7161 ((looking-at markdown-regex-blockquote)
7162 (forward-line)
7163 (while (and (looking-at markdown-regex-blockquote) (not (eobp)))
7164 (forward-line)))
7165 ;; List items
7166 ((markdown-cur-list-item-bounds)
7167 (markdown-end-of-list)
7168 (forward-line))
7169 ;; Other
7170 (t (markdown-forward-paragraph))))
7171 (skip-syntax-backward "-")
7172 (unless (eobp)
7173 (forward-char 1))))
7175 (defun markdown-backward-page (&optional count)
7176 "Move backward to boundary of the current toplevel section.
7177 With COUNT, repeat, or go forward if negative."
7178 (interactive "p")
7179 (or count (setq count 1))
7180 (if (< count 0)
7181 (markdown-forward-page (- count))
7182 (skip-syntax-backward "-")
7183 (or (markdown-back-to-heading-over-code-block t t)
7184 (goto-char (point-min)))
7185 (when (looking-at markdown-regex-header)
7186 (let ((level (markdown-outline-level)))
7187 (when (> level 1) (markdown-up-heading level))
7188 (when (> count 1)
7189 (condition-case nil
7190 (markdown-backward-same-level (1- count))
7191 (error (goto-char (point-min)))))))))
7193 (defun markdown-forward-page (&optional count)
7194 "Move forward to boundary of the current toplevel section.
7195 With COUNT, repeat, or go backward if negative."
7196 (interactive "p")
7197 (or count (setq count 1))
7198 (if (< count 0)
7199 (markdown-backward-page (- count))
7200 (if (markdown-back-to-heading-over-code-block t t)
7201 (let ((level (markdown-outline-level)))
7202 (when (> level 1) (markdown-up-heading level))
7203 (condition-case nil
7204 (markdown-forward-same-level count)
7205 (error (goto-char (point-max)))))
7206 (markdown-next-visible-heading 1))))
7208 (defun markdown-next-link ()
7209 "Jump to next inline, reference, or wiki link.
7210 If successful, return point. Otherwise, return nil.
7211 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
7212 (interactive)
7213 (let ((opoint (point)))
7214 (when (or (markdown-link-p) (markdown-wiki-link-p))
7215 ;; At a link already, move past it.
7216 (goto-char (+ (match-end 0) 1)))
7217 ;; Search for the next wiki link and move to the beginning.
7218 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t)
7219 (markdown-code-block-at-point-p)
7220 (< (point) (point-max))))
7221 (if (and (not (eq (point) opoint))
7222 (or (markdown-link-p) (markdown-wiki-link-p)))
7223 ;; Group 1 will move past non-escape character in wiki link regexp.
7224 ;; Go to beginning of group zero for all other link types.
7225 (goto-char (or (match-beginning 1) (match-beginning 0)))
7226 (goto-char opoint)
7227 nil)))
7229 (defun markdown-previous-link ()
7230 "Jump to previous wiki link.
7231 If successful, return point. Otherwise, return nil.
7232 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
7233 (interactive)
7234 (let ((opoint (point)))
7235 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t)
7236 (markdown-code-block-at-point-p)
7237 (> (point) (point-min))))
7238 (if (and (not (eq (point) opoint))
7239 (or (markdown-link-p) (markdown-wiki-link-p)))
7240 (goto-char (or (match-beginning 1) (match-beginning 0)))
7241 (goto-char opoint)
7242 nil)))
7245 ;;; Outline ===================================================================
7247 (defun markdown-move-heading-common (move-fn &optional arg adjust)
7248 "Wrapper for `outline-mode' functions to skip false positives.
7249 MOVE-FN is a function and ARG is its argument. For example,
7250 headings inside preformatted code blocks may match
7251 `outline-regexp' but should not be considered as headings.
7252 When ADJUST is non-nil, adjust the point for interactive calls
7253 to avoid leaving the point at invisible markup. This adjustment
7254 generally should only be done for interactive calls, since other
7255 functions may expect the point to be at the beginning of the
7256 regular expression."
7257 (let ((prev -1) (start (point)))
7258 (if arg (funcall move-fn arg) (funcall move-fn))
7259 (while (and (/= prev (point)) (markdown-code-block-at-point-p))
7260 (setq prev (point))
7261 (if arg (funcall move-fn arg) (funcall move-fn)))
7262 ;; Adjust point for setext headings and invisible text.
7263 (save-match-data
7264 (when (and adjust (thing-at-point-looking-at markdown-regex-header))
7265 (if markdown-hide-markup
7266 ;; Move to beginning of heading text if markup is hidden.
7267 (goto-char (or (match-beginning 1) (match-beginning 5)))
7268 ;; Move to beginning of markup otherwise.
7269 (goto-char (or (match-beginning 1) (match-beginning 4))))))
7270 (if (= (point) start) nil (point))))
7272 (defun markdown-next-visible-heading (arg)
7273 "Move to the next visible heading line of any level.
7274 With argument, repeats or can move backward if negative. ARG is
7275 passed to `outline-next-visible-heading'."
7276 (interactive "p")
7277 (markdown-move-heading-common #'outline-next-visible-heading arg 'adjust))
7279 (defun markdown-previous-visible-heading (arg)
7280 "Move to the previous visible heading line of any level.
7281 With argument, repeats or can move backward if negative. ARG is
7282 passed to `outline-previous-visible-heading'."
7283 (interactive "p")
7284 (markdown-move-heading-common #'outline-previous-visible-heading arg 'adjust))
7286 (defun markdown-next-heading ()
7287 "Move to the next heading line of any level."
7288 (markdown-move-heading-common #'outline-next-heading))
7290 (defun markdown-previous-heading ()
7291 "Move to the previous heading line of any level."
7292 (markdown-move-heading-common #'outline-previous-heading))
7294 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok no-error)
7295 "Move back to the beginning of the previous heading.
7296 Returns t if the point is at a heading, the location if a heading
7297 was found, and nil otherwise.
7298 Only visible heading lines are considered, unless INVISIBLE-OK is
7299 non-nil. Throw an error if there is no previous heading unless
7300 NO-ERROR is non-nil.
7301 Leaves match data intact for `markdown-regex-header'."
7302 (beginning-of-line)
7303 (or (and (markdown-heading-at-point)
7304 (not (markdown-code-block-at-point-p)))
7305 (let (found)
7306 (save-excursion
7307 (while (and (not found)
7308 (re-search-backward markdown-regex-header nil t))
7309 (when (and (or invisible-ok (not (outline-invisible-p)))
7310 (not (markdown-code-block-at-point-p)))
7311 (setq found (point))))
7312 (if (not found)
7313 (unless no-error (user-error "Before first heading"))
7314 (setq found (point))))
7315 (when found (goto-char found)))))
7317 (defun markdown-forward-same-level (arg)
7318 "Move forward to the ARG'th heading at same level as this one.
7319 Stop at the first and last headings of a superior heading."
7320 (interactive "p")
7321 (markdown-back-to-heading-over-code-block)
7322 (markdown-move-heading-common #'outline-forward-same-level arg 'adjust))
7324 (defun markdown-backward-same-level (arg)
7325 "Move backward to the ARG'th heading at same level as this one.
7326 Stop at the first and last headings of a superior heading."
7327 (interactive "p")
7328 (markdown-back-to-heading-over-code-block)
7329 (while (> arg 0)
7330 (let ((point-to-move-to
7331 (save-excursion
7332 (markdown-move-heading-common #'outline-get-last-sibling nil 'adjust))))
7333 (if point-to-move-to
7334 (progn
7335 (goto-char point-to-move-to)
7336 (setq arg (1- arg)))
7337 (user-error "No previous same-level heading")))))
7339 (defun markdown-up-heading (arg)
7340 "Move to the visible heading line of which the present line is a subheading.
7341 With argument, move up ARG levels."
7342 (interactive "p")
7343 (and (called-interactively-p 'any)
7344 (not (eq last-command 'markdown-up-heading)) (push-mark))
7345 (markdown-move-heading-common #'outline-up-heading arg 'adjust))
7347 (defun markdown-back-to-heading (&optional invisible-ok)
7348 "Move to previous heading line, or beg of this line if it's a heading.
7349 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
7350 (markdown-move-heading-common #'outline-back-to-heading invisible-ok))
7352 (defalias 'markdown-end-of-heading 'outline-end-of-heading)
7354 (defun markdown-on-heading-p ()
7355 "Return non-nil if point is on a heading line."
7356 (get-text-property (point-at-bol) 'markdown-heading))
7358 (defun markdown-end-of-subtree (&optional invisible-OK)
7359 "Move to the end of the current subtree.
7360 Only visible heading lines are considered, unless INVISIBLE-OK is
7361 non-nil.
7362 Derived from `org-end-of-subtree'."
7363 (markdown-back-to-heading invisible-OK)
7364 (let ((first t)
7365 (level (markdown-outline-level)))
7366 (while (and (not (eobp))
7367 (or first (> (markdown-outline-level) level)))
7368 (setq first nil)
7369 (markdown-next-heading))
7370 (if (memq (preceding-char) '(?\n ?\^M))
7371 (progn
7372 ;; Go to end of line before heading
7373 (forward-char -1)
7374 (if (memq (preceding-char) '(?\n ?\^M))
7375 ;; leave blank line before heading
7376 (forward-char -1)))))
7377 (point))
7379 (defun markdown-outline-fix-visibility ()
7380 "Hide any false positive headings that should not be shown.
7381 For example, headings inside preformatted code blocks may match
7382 `outline-regexp' but should not be shown as headings when cycling.
7383 Also, the ending --- line in metadata blocks appears to be a
7384 setext header, but should not be folded."
7385 (save-excursion
7386 (goto-char (point-min))
7387 ;; Unhide any false positives in metadata blocks
7388 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin)
7389 (let ((body (progn (forward-line)
7390 (markdown-text-property-at-point
7391 'markdown-yaml-metadata-section))))
7392 (when body
7393 (let ((end (progn (goto-char (cl-second body))
7394 (markdown-text-property-at-point
7395 'markdown-yaml-metadata-end))))
7396 (outline-flag-region (point-min) (1+ (cl-second end)) nil)))))
7397 ;; Hide any false positives in code blocks
7398 (unless (outline-on-heading-p)
7399 (outline-next-visible-heading 1))
7400 (while (< (point) (point-max))
7401 (when (markdown-code-block-at-point-p)
7402 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t))
7403 (outline-next-visible-heading 1))))
7405 (defvar markdown-cycle-global-status 1)
7406 (defvar markdown-cycle-subtree-status nil)
7408 (defun markdown-next-preface ()
7409 (let (finish)
7410 (while (and (not finish) (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
7411 nil 'move))
7412 (unless (markdown-code-block-at-point-p)
7413 (goto-char (match-beginning 0))
7414 (setq finish t))))
7415 (when (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
7416 (forward-char -1)))
7418 (defun markdown-show-entry ()
7419 (save-excursion
7420 (outline-back-to-heading t)
7421 (outline-flag-region (1- (point))
7422 (progn
7423 (markdown-next-preface)
7424 (if (= 1 (- (point-max) (point)))
7425 (point-max)
7426 (point)))
7427 nil)))
7429 ;; This function was originally derived from `org-cycle' from org.el.
7430 (defun markdown-cycle (&optional arg)
7431 "Visibility cycling for Markdown mode.
7432 If ARG is t, perform global visibility cycling. If the point is
7433 at an atx-style header, cycle visibility of the corresponding
7434 subtree. Otherwise, indent the current line or insert a tab,
7435 as appropriate, by calling `indent-for-tab-command'."
7436 (interactive "P")
7437 (cond
7439 ;; Global cycling
7440 ((eq arg t)
7441 (cond
7442 ;; Move from overview to contents
7443 ((and (eq last-command this-command)
7444 (eq markdown-cycle-global-status 2))
7445 (markdown-hide-sublevels 1)
7446 (message "CONTENTS")
7447 (setq markdown-cycle-global-status 3)
7448 (markdown-outline-fix-visibility))
7449 ;; Move from contents to all
7450 ((and (eq last-command this-command)
7451 (eq markdown-cycle-global-status 3))
7452 (markdown-show-all)
7453 (message "SHOW ALL")
7454 (setq markdown-cycle-global-status 1))
7455 ;; Defaults to overview
7457 (markdown-hide-body)
7458 (message "OVERVIEW")
7459 (setq markdown-cycle-global-status 2)
7460 (markdown-outline-fix-visibility))))
7462 ;; At a heading: rotate between three different views
7463 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
7464 (markdown-back-to-heading)
7465 (let ((goal-column 0) eoh eol eos)
7466 ;; Determine boundaries
7467 (save-excursion
7468 (markdown-back-to-heading)
7469 (save-excursion
7470 (beginning-of-line 2)
7471 (while (and (not (eobp)) ;; this is like `next-line'
7472 (get-char-property (1- (point)) 'invisible))
7473 (beginning-of-line 2)) (setq eol (point)))
7474 (markdown-end-of-heading) (setq eoh (point))
7475 (markdown-end-of-subtree t)
7476 (skip-chars-forward " \t\n")
7477 (beginning-of-line 1) ; in case this is an item
7478 (setq eos (1- (point))))
7479 ;; Find out what to do next and set `this-command'
7480 (cond
7481 ;; Nothing is hidden behind this heading
7482 ((= eos eoh)
7483 (message "EMPTY ENTRY")
7484 (setq markdown-cycle-subtree-status nil))
7485 ;; Entire subtree is hidden in one line: open it
7486 ((>= eol eos)
7487 (markdown-show-entry)
7488 (markdown-show-children)
7489 (message "CHILDREN")
7490 (setq markdown-cycle-subtree-status 'children))
7491 ;; We just showed the children, now show everything.
7492 ((and (eq last-command this-command)
7493 (eq markdown-cycle-subtree-status 'children))
7494 (markdown-show-subtree)
7495 (message "SUBTREE")
7496 (setq markdown-cycle-subtree-status 'subtree))
7497 ;; Default action: hide the subtree.
7499 (markdown-hide-subtree)
7500 (message "FOLDED")
7501 (setq markdown-cycle-subtree-status 'folded)))))
7503 ;; In a table, move forward by one cell
7504 ((markdown-table-at-point-p)
7505 (call-interactively #'markdown-table-forward-cell))
7507 ;; Otherwise, indent as appropriate
7509 (indent-for-tab-command))))
7511 (defun markdown-shifttab ()
7512 "Handle S-TAB keybinding based on context.
7513 When in a table, move backward one cell.
7514 Otherwise, cycle global heading visibility by calling
7515 `markdown-cycle' with argument t."
7516 (interactive)
7517 (cond ((markdown-table-at-point-p)
7518 (call-interactively #'markdown-table-backward-cell))
7519 (t (markdown-cycle t))))
7521 (defun markdown-outline-level ()
7522 "Return the depth to which a statement is nested in the outline."
7523 (cond
7524 ((and (match-beginning 0)
7525 (markdown-code-block-at-pos (match-beginning 0)))
7526 7) ;; Only 6 header levels are defined.
7527 ((match-end 2) 1)
7528 ((match-end 3) 2)
7529 ((match-end 4)
7530 (length (markdown-trim-whitespace (match-string-no-properties 4))))))
7532 (defun markdown-promote-subtree (&optional arg)
7533 "Promote the current subtree of ATX headings.
7534 Note that Markdown does not support heading levels higher than
7535 six and therefore level-six headings will not be promoted
7536 further. If ARG is non-nil promote the heading, otherwise
7537 demote."
7538 (interactive "*P")
7539 (save-excursion
7540 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
7541 (re-search-backward markdown-regex-header-atx nil t))
7542 (not (markdown-code-block-at-point-p)))
7543 (let ((level (length (match-string 1)))
7544 (promote-or-demote (if arg 1 -1))
7545 (remove 't))
7546 (markdown-cycle-atx promote-or-demote remove)
7547 (catch 'end-of-subtree
7548 (while (and (markdown-next-heading)
7549 (looking-at markdown-regex-header-atx))
7550 ;; Exit if this not a higher level heading; promote otherwise.
7551 (if (and (looking-at markdown-regex-header-atx)
7552 (<= (length (match-string-no-properties 1)) level))
7553 (throw 'end-of-subtree nil)
7554 (markdown-cycle-atx promote-or-demote remove))))))))
7556 (defun markdown-demote-subtree ()
7557 "Demote the current subtree of ATX headings."
7558 (interactive)
7559 (markdown-promote-subtree t))
7561 (defun markdown-move-subtree-up ()
7562 "Move the current subtree of ATX headings up."
7563 (interactive)
7564 (outline-move-subtree-up 1))
7566 (defun markdown-move-subtree-down ()
7567 "Move the current subtree of ATX headings down."
7568 (interactive)
7569 (outline-move-subtree-down 1))
7571 (defun markdown-outline-next ()
7572 "Move to next list item, when in a list, or next visible heading."
7573 (interactive)
7574 (let ((bounds (markdown-next-list-item-bounds)))
7575 (if bounds
7576 (goto-char (nth 0 bounds))
7577 (markdown-next-visible-heading 1))))
7579 (defun markdown-outline-previous ()
7580 "Move to previous list item, when in a list, or previous visible heading."
7581 (interactive)
7582 (let ((bounds (markdown-prev-list-item-bounds)))
7583 (if bounds
7584 (goto-char (nth 0 bounds))
7585 (markdown-previous-visible-heading 1))))
7587 (defun markdown-outline-next-same-level ()
7588 "Move to next list item or heading of same level."
7589 (interactive)
7590 (let ((bounds (markdown-cur-list-item-bounds)))
7591 (if bounds
7592 (markdown-next-list-item (nth 3 bounds))
7593 (markdown-forward-same-level 1))))
7595 (defun markdown-outline-previous-same-level ()
7596 "Move to previous list item or heading of same level."
7597 (interactive)
7598 (let ((bounds (markdown-cur-list-item-bounds)))
7599 (if bounds
7600 (markdown-prev-list-item (nth 3 bounds))
7601 (markdown-backward-same-level 1))))
7603 (defun markdown-outline-up ()
7604 "Move to previous list item, when in a list, or next heading."
7605 (interactive)
7606 (unless (markdown-up-list)
7607 (markdown-up-heading 1)))
7610 ;;; Marking and Narrowing =====================================================
7612 (defun markdown-mark-paragraph ()
7613 "Put mark at end of this block, point at beginning.
7614 The block marked is the one that contains point or follows point.
7616 Interactively, if this command is repeated or (in Transient Mark
7617 mode) if the mark is active, it marks the next block after the
7618 ones already marked."
7619 (interactive)
7620 (if (or (and (eq last-command this-command) (mark t))
7621 (and transient-mark-mode mark-active))
7622 (set-mark
7623 (save-excursion
7624 (goto-char (mark))
7625 (markdown-forward-paragraph)
7626 (point)))
7627 (let ((beginning-of-defun-function 'markdown-backward-paragraph)
7628 (end-of-defun-function 'markdown-forward-paragraph))
7629 (mark-defun))))
7631 (defun markdown-mark-block ()
7632 "Put mark at end of this block, point at beginning.
7633 The block marked is the one that contains point or follows point.
7635 Interactively, if this command is repeated or (in Transient Mark
7636 mode) if the mark is active, it marks the next block after the
7637 ones already marked."
7638 (interactive)
7639 (if (or (and (eq last-command this-command) (mark t))
7640 (and transient-mark-mode mark-active))
7641 (set-mark
7642 (save-excursion
7643 (goto-char (mark))
7644 (markdown-forward-block)
7645 (point)))
7646 (let ((beginning-of-defun-function 'markdown-backward-block)
7647 (end-of-defun-function 'markdown-forward-block))
7648 (mark-defun))))
7650 (defun markdown-narrow-to-block ()
7651 "Make text outside current block invisible.
7652 The current block is the one that contains point or follows point."
7653 (interactive)
7654 (let ((beginning-of-defun-function 'markdown-backward-block)
7655 (end-of-defun-function 'markdown-forward-block))
7656 (narrow-to-defun)))
7658 (defun markdown-mark-text-block ()
7659 "Put mark at end of this plain text block, point at beginning.
7660 The block marked is the one that contains point or follows point.
7662 Interactively, if this command is repeated or (in Transient Mark
7663 mode) if the mark is active, it marks the next block after the
7664 ones already marked."
7665 (interactive)
7666 (if (or (and (eq last-command this-command) (mark t))
7667 (and transient-mark-mode mark-active))
7668 (set-mark
7669 (save-excursion
7670 (goto-char (mark))
7671 (markdown-end-of-text-block)
7672 (point)))
7673 (let ((beginning-of-defun-function 'markdown-beginning-of-text-block)
7674 (end-of-defun-function 'markdown-end-of-text-block))
7675 (mark-defun))))
7677 (defun markdown-mark-page ()
7678 "Put mark at end of this top level section, point at beginning.
7679 The top level section marked is the one that contains point or
7680 follows point.
7682 Interactively, if this command is repeated or (in Transient Mark
7683 mode) if the mark is active, it marks the next page after the
7684 ones already marked."
7685 (interactive)
7686 (if (or (and (eq last-command this-command) (mark t))
7687 (and transient-mark-mode mark-active))
7688 (set-mark
7689 (save-excursion
7690 (goto-char (mark))
7691 (markdown-forward-page)
7692 (point)))
7693 (let ((beginning-of-defun-function 'markdown-backward-page)
7694 (end-of-defun-function 'markdown-forward-page))
7695 (mark-defun))))
7697 (defun markdown-narrow-to-page ()
7698 "Make text outside current top level section invisible.
7699 The current section is the one that contains point or follows point."
7700 (interactive)
7701 (let ((beginning-of-defun-function 'markdown-backward-page)
7702 (end-of-defun-function 'markdown-forward-page))
7703 (narrow-to-defun)))
7705 (defun markdown-mark-subtree ()
7706 "Mark the current subtree.
7707 This puts point at the start of the current subtree, and mark at the end."
7708 (interactive)
7709 (let ((beg))
7710 (if (markdown-heading-at-point)
7711 (beginning-of-line)
7712 (markdown-previous-visible-heading 1))
7713 (setq beg (point))
7714 (markdown-end-of-subtree)
7715 (push-mark (point) nil t)
7716 (goto-char beg)))
7718 (defun markdown-narrow-to-subtree ()
7719 "Narrow buffer to the current subtree."
7720 (interactive)
7721 (save-excursion
7722 (save-match-data
7723 (narrow-to-region
7724 (progn (markdown-back-to-heading-over-code-block t) (point))
7725 (progn (markdown-end-of-subtree)
7726 (if (and (markdown-heading-at-point) (not (eobp)))
7727 (backward-char 1))
7728 (point))))))
7731 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
7733 (defun markdown-move-up ()
7734 "Move thing at point up.
7735 When in a list item, call `markdown-move-list-item-up'.
7736 When in a table, call `markdown-table-move-row-up'.
7737 Otherwise, move the current heading subtree up with
7738 `markdown-move-subtree-up'."
7739 (interactive)
7740 (cond
7741 ((markdown-list-item-at-point-p)
7742 (call-interactively #'markdown-move-list-item-up))
7743 ((markdown-table-at-point-p)
7744 (call-interactively #'markdown-table-move-row-up))
7746 (call-interactively #'markdown-move-subtree-up))))
7748 (defun markdown-move-down ()
7749 "Move thing at point down.
7750 When in a list item, call `markdown-move-list-item-down'.
7751 Otherwise, move the current heading subtree up with
7752 `markdown-move-subtree-down'."
7753 (interactive)
7754 (cond
7755 ((markdown-list-item-at-point-p)
7756 (call-interactively #'markdown-move-list-item-down))
7757 ((markdown-table-at-point-p)
7758 (call-interactively #'markdown-table-move-row-down))
7760 (call-interactively #'markdown-move-subtree-down))))
7762 (defun markdown-promote ()
7763 "Promote or move element at point to the left.
7764 Depending on the context, this function will promote a heading or
7765 list item at the point, move a table column to the left, or cycle
7766 markup."
7767 (interactive)
7768 (let (bounds)
7769 (cond
7770 ;; Promote atx heading subtree
7771 ((thing-at-point-looking-at markdown-regex-header-atx)
7772 (markdown-promote-subtree))
7773 ;; Promote setext heading
7774 ((thing-at-point-looking-at markdown-regex-header-setext)
7775 (markdown-cycle-setext -1))
7776 ;; Promote horizonal rule
7777 ((thing-at-point-looking-at markdown-regex-hr)
7778 (markdown-cycle-hr -1))
7779 ;; Promote list item
7780 ((setq bounds (markdown-cur-list-item-bounds))
7781 (markdown-promote-list-item bounds))
7782 ;; Move table column to the left
7783 ((markdown-table-at-point-p)
7784 (call-interactively #'markdown-table-move-column-left))
7785 ;; Promote bold
7786 ((thing-at-point-looking-at markdown-regex-bold)
7787 (markdown-cycle-bold))
7788 ;; Promote italic
7789 ((thing-at-point-looking-at markdown-regex-italic)
7790 (markdown-cycle-italic))
7792 (user-error "Nothing to promote at point")))))
7794 (defun markdown-demote ()
7795 "Demote or move element at point to the right.
7796 Depending on the context, this function will demote a heading or
7797 list item at the point, move a table column to the right, or cycle
7798 or remove markup."
7799 (interactive)
7800 (let (bounds)
7801 (cond
7802 ;; Demote atx heading subtree
7803 ((thing-at-point-looking-at markdown-regex-header-atx)
7804 (markdown-demote-subtree))
7805 ;; Demote setext heading
7806 ((thing-at-point-looking-at markdown-regex-header-setext)
7807 (markdown-cycle-setext 1))
7808 ;; Demote horizonal rule
7809 ((thing-at-point-looking-at markdown-regex-hr)
7810 (markdown-cycle-hr 1))
7811 ;; Demote list item
7812 ((setq bounds (markdown-cur-list-item-bounds))
7813 (markdown-demote-list-item bounds))
7814 ;; Move table column to the right
7815 ((markdown-table-at-point-p)
7816 (call-interactively #'markdown-table-move-column-right))
7817 ;; Demote bold
7818 ((thing-at-point-looking-at markdown-regex-bold)
7819 (markdown-cycle-bold))
7820 ;; Demote italic
7821 ((thing-at-point-looking-at markdown-regex-italic)
7822 (markdown-cycle-italic))
7824 (user-error "Nothing to demote at point")))))
7827 ;;; Commands ==================================================================
7829 (defun markdown (&optional output-buffer-name)
7830 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
7831 The output buffer name defaults to `markdown-output-buffer-name'.
7832 Return the name of the output buffer used."
7833 (interactive)
7834 (save-window-excursion
7835 (let ((begin-region)
7836 (end-region))
7837 (if (markdown-use-region-p)
7838 (setq begin-region (region-beginning)
7839 end-region (region-end))
7840 (setq begin-region (point-min)
7841 end-region (point-max)))
7843 (unless output-buffer-name
7844 (setq output-buffer-name markdown-output-buffer-name))
7845 (cond
7846 ;; Handle case when `markdown-command' does not read from stdin
7847 ((and (stringp markdown-command) markdown-command-needs-filename)
7848 (if (not buffer-file-name)
7849 (user-error "Must be visiting a file")
7850 (shell-command (concat markdown-command " "
7851 (shell-quote-argument buffer-file-name))
7852 output-buffer-name)))
7853 ;; Pass region to `markdown-command' via stdin
7855 (let ((buf (get-buffer-create output-buffer-name)))
7856 (with-current-buffer buf
7857 (setq buffer-read-only nil)
7858 (erase-buffer))
7859 (if (stringp markdown-command)
7860 (call-process-region begin-region end-region
7861 shell-file-name nil buf nil
7862 shell-command-switch markdown-command)
7863 (funcall markdown-command begin-region end-region buf))))))
7864 output-buffer-name))
7866 (defun markdown-standalone (&optional output-buffer-name)
7867 "Special function to provide standalone HTML output.
7868 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
7869 (interactive)
7870 (setq output-buffer-name (markdown output-buffer-name))
7871 (with-current-buffer output-buffer-name
7872 (set-buffer output-buffer-name)
7873 (unless (markdown-output-standalone-p)
7874 (markdown-add-xhtml-header-and-footer output-buffer-name))
7875 (goto-char (point-min))
7876 (html-mode))
7877 output-buffer-name)
7879 (defun markdown-other-window (&optional output-buffer-name)
7880 "Run `markdown-command' on current buffer and display in other window.
7881 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7882 that name."
7883 (interactive)
7884 (markdown-display-buffer-other-window
7885 (markdown-standalone output-buffer-name)))
7887 (defun markdown-output-standalone-p ()
7888 "Determine whether `markdown-command' output is standalone XHTML.
7889 Standalone XHTML output is identified by an occurrence of
7890 `markdown-xhtml-standalone-regexp' in the first five lines of output."
7891 (save-excursion
7892 (goto-char (point-min))
7893 (save-match-data
7894 (re-search-forward
7895 markdown-xhtml-standalone-regexp
7896 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
7897 t))))
7899 (defun markdown-stylesheet-link-string (stylesheet-path)
7900 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
7901 stylesheet-path
7902 "\" />"))
7904 (defun markdown-add-xhtml-header-and-footer (title)
7905 "Wrap XHTML header and footer with given TITLE around current buffer."
7906 (goto-char (point-min))
7907 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
7908 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
7909 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
7910 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
7911 "<head>\n<title>")
7912 (insert title)
7913 (insert "</title>\n")
7914 (when (> (length markdown-content-type) 0)
7915 (insert
7916 (format
7917 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
7918 markdown-content-type
7919 (or (and markdown-coding-system
7920 (fboundp 'coding-system-get)
7921 (coding-system-get markdown-coding-system
7922 'mime-charset))
7923 (and (fboundp 'coding-system-get)
7924 (coding-system-get buffer-file-coding-system
7925 'mime-charset))
7926 "iso-8859-1"))))
7927 (if (> (length markdown-css-paths) 0)
7928 (insert (mapconcat #'markdown-stylesheet-link-string
7929 markdown-css-paths "\n")))
7930 (when (> (length markdown-xhtml-header-content) 0)
7931 (insert markdown-xhtml-header-content))
7932 (insert "\n</head>\n\n"
7933 "<body>\n\n")
7934 (goto-char (point-max))
7935 (insert "\n"
7936 "</body>\n"
7937 "</html>\n"))
7939 (defun markdown-preview (&optional output-buffer-name)
7940 "Run `markdown-command' on the current buffer and view output in browser.
7941 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7942 that name."
7943 (interactive)
7944 (browse-url-of-buffer
7945 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
7947 (defun markdown-export-file-name (&optional extension)
7948 "Attempt to generate a filename for Markdown output.
7949 The file extension will be EXTENSION if given, or .html by default.
7950 If the current buffer is visiting a file, we construct a new
7951 output filename based on that filename. Otherwise, return nil."
7952 (when (buffer-file-name)
7953 (unless extension
7954 (setq extension ".html"))
7955 (let ((candidate
7956 (concat
7957 (cond
7958 ((buffer-file-name)
7959 (file-name-sans-extension (buffer-file-name)))
7960 (t (buffer-name)))
7961 extension)))
7962 (cond
7963 ((equal candidate (buffer-file-name))
7964 (concat candidate extension))
7966 candidate)))))
7968 (defun markdown-export (&optional output-file)
7969 "Run Markdown on the current buffer, save to file, and return the filename.
7970 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
7971 generated by `markdown-export-file-name', which will be constructed using the
7972 current filename, but with the extension removed and replaced with .html."
7973 (interactive)
7974 (unless output-file
7975 (setq output-file (markdown-export-file-name ".html")))
7976 (when output-file
7977 (let* ((init-buf (current-buffer))
7978 (init-point (point))
7979 (init-buf-string (buffer-string))
7980 (output-buffer (find-file-noselect output-file))
7981 (output-buffer-name (buffer-name output-buffer)))
7982 (run-hooks 'markdown-before-export-hook)
7983 (markdown-standalone output-buffer-name)
7984 (with-current-buffer output-buffer
7985 (run-hooks 'markdown-after-export-hook)
7986 (save-buffer)
7987 (when markdown-export-kill-buffer (kill-buffer)))
7988 ;; if modified, restore initial buffer
7989 (when (buffer-modified-p init-buf)
7990 (erase-buffer)
7991 (insert init-buf-string)
7992 (save-buffer)
7993 (goto-char init-point))
7994 output-file)))
7996 (defun markdown-export-and-preview ()
7997 "Export to XHTML using `markdown-export' and browse the resulting file."
7998 (interactive)
7999 (browse-url-of-file (markdown-export)))
8001 (defvar markdown-live-preview-buffer nil
8002 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
8003 (make-variable-buffer-local 'markdown-live-preview-buffer)
8005 (defvar markdown-live-preview-source-buffer nil
8006 "Source buffer from which current buffer was generated.
8007 This is the inverse of `markdown-live-preview-buffer'.")
8008 (make-variable-buffer-local 'markdown-live-preview-source-buffer)
8010 (defvar markdown-live-preview-currently-exporting nil)
8012 (defun markdown-live-preview-get-filename ()
8013 "Standardize the filename exported by `markdown-live-preview-export'."
8014 (markdown-export-file-name ".html"))
8016 (defun markdown-live-preview-window-eww (file)
8017 "Preview FILE with eww.
8018 To be used with `markdown-live-preview-window-function'."
8019 (if (require 'eww nil t)
8020 (progn
8021 (eww-open-file file)
8022 (get-buffer "*eww*"))
8023 (error "EWW is not present or not loaded on this version of Emacs")))
8025 (defun markdown-visual-lines-between-points (beg end)
8026 (save-excursion
8027 (goto-char beg)
8028 (cl-loop with count = 0
8029 while (progn (end-of-visual-line)
8030 (and (< (point) end) (line-move-visual 1 t)))
8031 do (cl-incf count)
8032 finally return count)))
8034 (defun markdown-live-preview-window-serialize (buf)
8035 "Get window point and scroll data for all windows displaying BUF."
8036 (when (buffer-live-p buf)
8037 (with-current-buffer buf
8038 (mapcar
8039 (lambda (win)
8040 (with-selected-window win
8041 (let* ((start (window-start))
8042 (pt (window-point))
8043 (pt-or-sym (cond ((= pt (point-min)) 'min)
8044 ((= pt (point-max)) 'max)
8045 (t pt)))
8046 (diff (markdown-visual-lines-between-points
8047 start pt)))
8048 (list win pt-or-sym diff))))
8049 (get-buffer-window-list buf)))))
8051 (defun markdown-get-point-back-lines (pt num-lines)
8052 (save-excursion
8053 (goto-char pt)
8054 (line-move-visual (- num-lines) t)
8055 ;; in testing, can occasionally overshoot the number of lines to traverse
8056 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
8057 (when (> actual-num-lines num-lines)
8058 (line-move-visual (- actual-num-lines num-lines) t)))
8059 (point)))
8061 (defun markdown-live-preview-window-deserialize (window-posns)
8062 "Apply window point and scroll data from WINDOW-POSNS.
8063 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
8064 (cl-destructuring-bind (win pt-or-sym diff) window-posns
8065 (when (window-live-p win)
8066 (with-current-buffer markdown-live-preview-buffer
8067 (set-window-buffer win (current-buffer))
8068 (cl-destructuring-bind (actual-pt actual-diff)
8069 (cl-case pt-or-sym
8070 (min (list (point-min) 0))
8071 (max (list (point-max) diff))
8072 (t (list pt-or-sym diff)))
8073 (set-window-start
8074 win (markdown-get-point-back-lines actual-pt actual-diff))
8075 (set-window-point win actual-pt))))))
8077 (defun markdown-live-preview-export ()
8078 "Export to XHTML using `markdown-export'.
8079 Browse the resulting file within Emacs using
8080 `markdown-live-preview-window-function' Return the buffer
8081 displaying the rendered output."
8082 (interactive)
8083 (let ((filename (markdown-live-preview-get-filename)))
8084 (when filename
8085 (let* ((markdown-live-preview-currently-exporting t)
8086 (cur-buf (current-buffer))
8087 (export-file (markdown-export filename))
8088 ;; get positions in all windows currently displaying output buffer
8089 (window-data
8090 (markdown-live-preview-window-serialize
8091 markdown-live-preview-buffer)))
8092 (save-window-excursion
8093 (let ((output-buffer
8094 (funcall markdown-live-preview-window-function export-file)))
8095 (with-current-buffer output-buffer
8096 (setq markdown-live-preview-source-buffer cur-buf)
8097 (add-hook 'kill-buffer-hook
8098 #'markdown-live-preview-remove-on-kill t t))
8099 (with-current-buffer cur-buf
8100 (setq markdown-live-preview-buffer output-buffer))))
8101 (with-current-buffer cur-buf
8102 ;; reset all windows displaying output buffer to where they were,
8103 ;; now with the new output
8104 (mapc #'markdown-live-preview-window-deserialize window-data)
8105 ;; delete html editing buffer
8106 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
8107 (when (and export-file (file-exists-p export-file)
8108 (eq markdown-live-preview-delete-export
8109 'delete-on-export))
8110 (delete-file export-file))
8111 markdown-live-preview-buffer)))))
8113 (defun markdown-live-preview-remove ()
8114 (when (buffer-live-p markdown-live-preview-buffer)
8115 (kill-buffer markdown-live-preview-buffer))
8116 (setq markdown-live-preview-buffer nil)
8117 ;; if set to 'delete-on-export, the output has already been deleted
8118 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
8119 (let ((outfile-name (markdown-live-preview-get-filename)))
8120 (when (and outfile-name (file-exists-p outfile-name))
8121 (delete-file outfile-name)))))
8123 (defun markdown-get-other-window ()
8124 "Find another window to display preview or output content."
8125 (cond
8126 ((memq markdown-split-window-direction '(vertical below))
8127 (or (window-in-direction 'below) (split-window-vertically)))
8128 ((memq markdown-split-window-direction '(horizontal right))
8129 (or (window-in-direction 'right) (split-window-horizontally)))
8130 (t (split-window-sensibly (get-buffer-window)))))
8132 (defun markdown-display-buffer-other-window (buf)
8133 "Display preview or output buffer BUF in another window."
8134 (let ((cur-buf (current-buffer))
8135 (window (markdown-get-other-window)))
8136 (set-window-buffer window buf)
8137 (set-buffer cur-buf)))
8139 (defun markdown-live-preview-if-markdown ()
8140 (when (and (derived-mode-p 'markdown-mode)
8141 markdown-live-preview-mode)
8142 (unless markdown-live-preview-currently-exporting
8143 (if (buffer-live-p markdown-live-preview-buffer)
8144 (markdown-live-preview-export)
8145 (markdown-display-buffer-other-window
8146 (markdown-live-preview-export))))))
8148 (defun markdown-live-preview-remove-on-kill ()
8149 (cond ((and (derived-mode-p 'markdown-mode)
8150 markdown-live-preview-mode)
8151 (markdown-live-preview-remove))
8152 (markdown-live-preview-source-buffer
8153 (with-current-buffer markdown-live-preview-source-buffer
8154 (setq markdown-live-preview-buffer nil))
8155 (setq markdown-live-preview-source-buffer nil))))
8157 (defun markdown-live-preview-switch-to-output ()
8158 "Switch to output buffer."
8159 (interactive)
8160 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
8161 output buffer in another window."
8162 (if markdown-live-preview-mode
8163 (markdown-display-buffer-other-window (markdown-live-preview-export)))
8164 (markdown-live-preview-mode))
8166 (defun markdown-live-preview-re-export ()
8167 "Re export source buffer."
8168 (interactive)
8169 "If the current buffer is a buffer displaying the exported version of a
8170 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
8171 update this buffer's contents."
8172 (when markdown-live-preview-source-buffer
8173 (with-current-buffer markdown-live-preview-source-buffer
8174 (markdown-live-preview-export))))
8176 (defun markdown-open ()
8177 "Open file for the current buffer with `markdown-open-command'."
8178 (interactive)
8179 (unless markdown-open-command
8180 (user-error "Variable `markdown-open-command' must be set"))
8181 (if (stringp markdown-open-command)
8182 (if (not buffer-file-name)
8183 (user-error "Must be visiting a file")
8184 (save-buffer)
8185 (call-process markdown-open-command nil 0 nil buffer-file-name))
8186 (funcall markdown-open-command))
8187 nil)
8189 (defun markdown-kill-ring-save ()
8190 "Run Markdown on file and store output in the kill ring."
8191 (interactive)
8192 (save-window-excursion
8193 (markdown)
8194 (with-current-buffer markdown-output-buffer-name
8195 (kill-ring-save (point-min) (point-max)))))
8198 ;;; Links =====================================================================
8200 (defun markdown-link-p ()
8201 "Return non-nil when `point' is at a non-wiki link.
8202 See `markdown-wiki-link-p' for more information."
8203 (let ((case-fold-search nil))
8204 (and (not (markdown-wiki-link-p))
8205 (not (markdown-code-block-at-point-p))
8206 (or (thing-at-point-looking-at markdown-regex-link-inline)
8207 (thing-at-point-looking-at markdown-regex-link-reference)
8208 (thing-at-point-looking-at markdown-regex-uri)
8209 (thing-at-point-looking-at markdown-regex-angle-uri)))))
8211 (make-obsolete 'markdown-link-link 'markdown-link-url "v2.3")
8213 (defun markdown-link-at-pos (pos)
8214 "Return properties of link or image at position POS.
8215 Value is a list of elements describing the link:
8216 0. beginning position
8217 1. end position
8218 2. link text
8219 3. URL
8220 4. reference label
8221 5. title text
8222 6. bang (nil or \"!\")"
8223 (save-excursion
8224 (goto-char pos)
8225 (let (begin end text url reference title bang)
8226 (cond
8227 ;; Inline or reference image or link at point.
8228 ((or (thing-at-point-looking-at markdown-regex-link-inline)
8229 (thing-at-point-looking-at markdown-regex-link-reference))
8230 (setq bang (match-string-no-properties 1)
8231 begin (match-beginning 0)
8232 end (match-end 0)
8233 text (match-string-no-properties 3))
8234 (if (char-equal (char-after (match-beginning 5)) ?\[)
8235 ;; Reference link
8236 (setq reference (match-string-no-properties 6))
8237 ;; Inline link
8238 (setq url (match-string-no-properties 6))
8239 (when (match-end 7)
8240 (setq title (substring (match-string-no-properties 7) 1 -1)))))
8241 ;; Angle bracket URI at point.
8242 ((thing-at-point-looking-at markdown-regex-angle-uri)
8243 (setq begin (match-beginning 0)
8244 end (match-end 0)
8245 url (match-string-no-properties 2)))
8246 ;; Plain URI at point.
8247 ((thing-at-point-looking-at markdown-regex-uri)
8248 (setq begin (match-beginning 0)
8249 end (match-end 0)
8250 url (match-string-no-properties 1))))
8251 (list begin end text url reference title bang))))
8253 (defun markdown-link-url ()
8254 "Return the URL part of the regular (non-wiki) link at point.
8255 Works with both inline and reference style links, and with images.
8256 If point is not at a link or the link reference is not defined
8257 returns nil."
8258 (let* ((values (markdown-link-at-pos (point)))
8259 (text (nth 2 values))
8260 (url (nth 3 values))
8261 (ref (nth 4 values)))
8262 (or url (and ref (car (markdown-reference-definition
8263 (downcase (if (string= ref "") text ref))))))))
8265 (defun markdown-follow-link-at-point ()
8266 "Open the current non-wiki link.
8267 If the link is a complete URL, open in browser with `browse-url'.
8268 Otherwise, open with `find-file' after stripping anchor and/or query string.
8269 Translate filenames using `markdown-filename-translate-function'."
8270 (interactive)
8271 (if (markdown-link-p)
8272 (let* ((url (markdown-link-url))
8273 (struct (url-generic-parse-url url))
8274 (full (url-fullness struct))
8275 (file url))
8276 ;; Parse URL, determine fullness, strip query string
8277 (if (fboundp 'url-path-and-query)
8278 (setq file (car (url-path-and-query struct)))
8279 (when (and (setq file (url-filename struct))
8280 (string-match "\\?" file))
8281 (setq file (substring file 0 (match-beginning 0)))))
8282 ;; Open full URLs in browser, files in Emacs
8283 (if full
8284 (browse-url url)
8285 (when (and file (> (length file) 0))
8286 (find-file (funcall markdown-translate-filename-function file)))))
8287 (user-error "Point is not at a Markdown link or URL")))
8289 (defun markdown-fontify-inline-links (last)
8290 "Add text properties to next inline link from point to LAST."
8291 (when (markdown-match-generic-links last nil)
8292 (let* ((link-start (match-beginning 3))
8293 (link-end (match-end 3))
8294 (url-start (match-beginning 6))
8295 (url-end (match-end 6))
8296 (url (match-string-no-properties 6))
8297 (title-start (match-beginning 7))
8298 (title-end (match-end 7))
8299 (title (match-string-no-properties 7))
8300 ;; Markup part
8301 (mp (list 'face 'markdown-markup-face
8302 'invisible 'markdown-markup
8303 'rear-nonsticky t
8304 'font-lock-multiline t))
8305 ;; Link part
8306 (lp (list 'keymap markdown-mode-mouse-map
8307 'face markdown-link-face
8308 'mouse-face 'markdown-highlight-face
8309 'font-lock-multiline t
8310 'help-echo (if title (concat title "\n" url) url)))
8311 ;; URL part
8312 (up (list 'keymap markdown-mode-mouse-map
8313 'face 'markdown-url-face
8314 'invisible 'markdown-markup
8315 'mouse-face 'markdown-highlight-face
8316 'font-lock-multiline t))
8317 ;; URL composition character
8318 (url-char (markdown--first-displayable markdown-url-compose-char))
8319 ;; Title part
8320 (tp (list 'face 'markdown-link-title-face
8321 'invisible 'markdown-markup
8322 'font-lock-multiline t)))
8323 (dolist (g '(1 2 4 5 8))
8324 (when (match-end g)
8325 (add-text-properties (match-beginning g) (match-end g) mp)))
8326 (when link-start (add-text-properties link-start link-end lp))
8327 (when url-start (add-text-properties url-start url-end up))
8328 (when title-start (add-text-properties url-end title-end tp))
8329 (when (and markdown-hide-urls url-start)
8330 (compose-region url-start (or title-end url-end) url-char))
8331 t)))
8333 (defun markdown-fontify-reference-links (last)
8334 "Add text properties to next reference link from point to LAST."
8335 (when (markdown-match-generic-links last t)
8336 (let* ((link-start (match-beginning 3))
8337 (link-end (match-end 3))
8338 (ref-start (match-beginning 6))
8339 (ref-end (match-end 6))
8340 ;; Markup part
8341 (mp (list 'face 'markdown-markup-face
8342 'invisible 'markdown-markup
8343 'rear-nonsticky t
8344 'font-lock-multiline t))
8345 ;; Link part
8346 (lp (list 'keymap markdown-mode-mouse-map
8347 'face markdown-link-face
8348 'mouse-face 'markdown-highlight-face
8349 'font-lock-multiline t
8350 'help-echo (lambda (_ __ pos)
8351 (save-match-data
8352 (save-excursion
8353 (goto-char pos)
8354 (or (markdown-link-url)
8355 "Undefined reference"))))))
8356 ;; URL composition character
8357 (url-char (markdown--first-displayable markdown-url-compose-char))
8358 ;; Reference part
8359 (rp (list 'face 'markdown-reference-face
8360 'invisible 'markdown-markup
8361 'font-lock-multiline t)))
8362 (dolist (g '(1 2 4 5 8))
8363 (when (match-end g)
8364 (add-text-properties (match-beginning g) (match-end g) mp)))
8365 (when link-start (add-text-properties link-start link-end lp))
8366 (when ref-start (add-text-properties ref-start ref-end rp)
8367 (when (and markdown-hide-urls (> (- ref-end ref-start) 2))
8368 (compose-region ref-start ref-end url-char)))
8369 t)))
8371 (defun markdown-fontify-angle-uris (last)
8372 "Add text properties to angle URIs from point to LAST."
8373 (when (markdown-match-angle-uris last)
8374 (let* ((url-start (match-beginning 2))
8375 (url-end (match-end 2))
8376 ;; Markup part
8377 (mp (list 'face 'markdown-markup-face
8378 'invisible 'markdown-markup
8379 'rear-nonsticky t
8380 'font-lock-multiline t))
8381 ;; URI part
8382 (up (list 'keymap markdown-mode-mouse-map
8383 'face 'markdown-plain-url-face
8384 'mouse-face 'markdown-highlight-face
8385 'font-lock-multiline t)))
8386 (dolist (g '(1 3))
8387 (add-text-properties (match-beginning g) (match-end g) mp))
8388 (add-text-properties url-start url-end up)
8389 t)))
8391 (defun markdown-fontify-plain-uris (last)
8392 "Add text properties to plain URLs from point to LAST."
8393 (when (markdown-match-plain-uris last)
8394 (let* ((start (match-beginning 0))
8395 (end (match-end 0))
8396 (props (list 'keymap markdown-mode-mouse-map
8397 'face 'markdown-plain-url-face
8398 'mouse-face 'markdown-highlight-face
8399 'rear-nonsticky t
8400 'font-lock-multiline t)))
8401 (add-text-properties start end props)
8402 t)))
8404 (defun markdown-toggle-url-hiding (&optional arg)
8405 "Toggle the display or hiding of URLs.
8406 With a prefix argument ARG, enable URL hiding if ARG is positive,
8407 and disable it otherwise."
8408 (interactive (list (or current-prefix-arg 'toggle)))
8409 (setq markdown-hide-urls
8410 (if (eq arg 'toggle)
8411 (not markdown-hide-urls)
8412 (> (prefix-numeric-value arg) 0)))
8413 (if markdown-hide-urls
8414 (message "markdown-mode URL hiding enabled")
8415 (message "markdown-mode URL hiding disabled"))
8416 (markdown-reload-extensions))
8419 ;;; WikiLink Following/Markup =================================================
8421 (defun markdown-wiki-link-p ()
8422 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
8423 A true wiki link name matches `markdown-regex-wiki-link' but does
8424 not match the current file name after conversion. This modifies
8425 the data returned by `match-data'. Note that the potential wiki
8426 link name must be available via `match-string'."
8427 (when markdown-enable-wiki-links
8428 (let ((case-fold-search nil))
8429 (and (thing-at-point-looking-at markdown-regex-wiki-link)
8430 (not (markdown-code-block-at-point-p))
8431 (or (not buffer-file-name)
8432 (not (string-equal (buffer-file-name)
8433 (markdown-convert-wiki-link-to-filename
8434 (markdown-wiki-link-link)))))))))
8436 (defun markdown-wiki-link-link ()
8437 "Return the link part of the wiki link using current match data.
8438 The location of the link component depends on the value of
8439 `markdown-wiki-link-alias-first'."
8440 (if markdown-wiki-link-alias-first
8441 (or (match-string-no-properties 5) (match-string-no-properties 3))
8442 (match-string-no-properties 3)))
8444 (defun markdown-wiki-link-alias ()
8445 "Return the alias or text part of the wiki link using current match data.
8446 The location of the alias component depends on the value of
8447 `markdown-wiki-link-alias-first'."
8448 (if markdown-wiki-link-alias-first
8449 (match-string-no-properties 3)
8450 (or (match-string-no-properties 5) (match-string-no-properties 3))))
8452 (defun markdown-convert-wiki-link-to-filename (name)
8453 "Generate a filename from the wiki link NAME.
8454 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
8455 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
8456 and [[test test]] both map to Test-test.ext. Look in the current
8457 directory first, then in subdirectories if
8458 `markdown-wiki-link-search-subdirectories' is non-nil, and then
8459 in parent directories if
8460 `markdown-wiki-link-search-parent-directories' is non-nil."
8461 (let* ((basename (markdown-replace-regexp-in-string
8462 "[[:space:]\n]" markdown-link-space-sub-char name))
8463 (basename (if (eq major-mode 'gfm-mode)
8464 (concat (upcase (substring basename 0 1))
8465 (downcase (substring basename 1 nil)))
8466 basename))
8467 directory extension default candidates dir)
8468 (when buffer-file-name
8469 (setq directory (file-name-directory buffer-file-name)
8470 extension (file-name-extension buffer-file-name)))
8471 (setq default (concat basename
8472 (when extension (concat "." extension))))
8473 (cond
8474 ;; Look in current directory first.
8475 ((or (null buffer-file-name)
8476 (file-exists-p default))
8477 default)
8478 ;; Possibly search in subdirectories, next.
8479 ((and markdown-wiki-link-search-subdirectories
8480 (setq candidates
8481 (markdown-directory-files-recursively
8482 directory (concat "^" default "$"))))
8483 (car candidates))
8484 ;; Possibly search in parent directories as a last resort.
8485 ((and markdown-wiki-link-search-parent-directories
8486 (setq dir (locate-dominating-file directory default)))
8487 (concat dir default))
8488 ;; If nothing is found, return default in current directory.
8489 (t default))))
8491 (defun markdown-follow-wiki-link (name &optional other)
8492 "Follow the wiki link NAME.
8493 Convert the name to a file name and call `find-file'. Ensure that
8494 the new buffer remains in `markdown-mode'. Open the link in another
8495 window when OTHER is non-nil."
8496 (let ((filename (markdown-convert-wiki-link-to-filename name))
8497 (wp (when buffer-file-name
8498 (file-name-directory buffer-file-name))))
8499 (if (not wp)
8500 (user-error "Must be visiting a file")
8501 (when other (other-window 1))
8502 (let ((default-directory wp))
8503 (find-file filename)))
8504 (when (not (eq major-mode 'markdown-mode))
8505 (markdown-mode))))
8507 (defun markdown-follow-wiki-link-at-point (&optional arg)
8508 "Find Wiki Link at point.
8509 With prefix argument ARG, open the file in other window.
8510 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
8511 (interactive "P")
8512 (if (markdown-wiki-link-p)
8513 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
8514 (user-error "Point is not at a Wiki Link")))
8516 (defun markdown-highlight-wiki-link (from to face)
8517 "Highlight the wiki link in the region between FROM and TO using FACE."
8518 (put-text-property from to 'font-lock-face face))
8520 (defun markdown-unfontify-region-wiki-links (from to)
8521 "Remove wiki link faces from the region specified by FROM and TO."
8522 (interactive "*r")
8523 (let ((modified (buffer-modified-p)))
8524 (remove-text-properties from to '(font-lock-face markdown-link-face))
8525 (remove-text-properties from to '(font-lock-face markdown-missing-link-face))
8526 ;; remove-text-properties marks the buffer modified in emacs 24.3,
8527 ;; undo that if it wasn't originally marked modified
8528 (set-buffer-modified-p modified)))
8530 (defun markdown-fontify-region-wiki-links (from to)
8531 "Search region given by FROM and TO for wiki links and fontify them.
8532 If a wiki link is found check to see if the backing file exists
8533 and highlight accordingly."
8534 (goto-char from)
8535 (save-match-data
8536 (while (re-search-forward markdown-regex-wiki-link to t)
8537 (when (not (markdown-code-block-at-point-p))
8538 (let ((highlight-beginning (match-beginning 1))
8539 (highlight-end (match-end 1))
8540 (file-name
8541 (markdown-convert-wiki-link-to-filename
8542 (markdown-wiki-link-link))))
8543 (if (condition-case nil (file-exists-p file-name) (error nil))
8544 (markdown-highlight-wiki-link
8545 highlight-beginning highlight-end markdown-link-face)
8546 (markdown-highlight-wiki-link
8547 highlight-beginning highlight-end markdown-missing-link-face)))))))
8549 (defun markdown-extend-changed-region (from to)
8550 "Extend region given by FROM and TO so that we can fontify all links.
8551 The region is extended to the first newline before and the first
8552 newline after."
8553 ;; start looking for the first new line before 'from
8554 (goto-char from)
8555 (re-search-backward "\n" nil t)
8556 (let ((new-from (point-min))
8557 (new-to (point-max)))
8558 (if (not (= (point) from))
8559 (setq new-from (point)))
8560 ;; do the same thing for the first new line after 'to
8561 (goto-char to)
8562 (re-search-forward "\n" nil t)
8563 (if (not (= (point) to))
8564 (setq new-to (point)))
8565 (cl-values new-from new-to)))
8567 (defun markdown-check-change-for-wiki-link (from to)
8568 "Check region between FROM and TO for wiki links and re-fontify as needed."
8569 (interactive "*r")
8570 (let* ((modified (buffer-modified-p))
8571 (buffer-undo-list t)
8572 (inhibit-read-only t)
8573 (inhibit-point-motion-hooks t)
8574 deactivate-mark
8575 buffer-file-truename)
8576 (unwind-protect
8577 (save-excursion
8578 (save-match-data
8579 (save-restriction
8580 ;; Extend the region to fontify so that it starts
8581 ;; and ends at safe places.
8582 (cl-multiple-value-bind (new-from new-to)
8583 (markdown-extend-changed-region from to)
8584 (goto-char new-from)
8585 ;; Only refontify when the range contains text with a
8586 ;; wiki link face or if the wiki link regexp matches.
8587 (when (or (markdown-range-property-any
8588 new-from new-to 'font-lock-face
8589 (list markdown-link-face
8590 markdown-missing-link-face))
8591 (re-search-forward
8592 markdown-regex-wiki-link new-to t))
8593 ;; Unfontify existing fontification (start from scratch)
8594 (markdown-unfontify-region-wiki-links new-from new-to)
8595 ;; Now do the fontification.
8596 (markdown-fontify-region-wiki-links new-from new-to))))))
8597 (and (not modified)
8598 (buffer-modified-p)
8599 (set-buffer-modified-p nil)))))
8601 (defun markdown-check-change-for-wiki-link-after-change (from to _)
8602 "Check region between FROM and TO for wiki links and re-fontify as needed.
8603 Designed to be used with the `after-change-functions' hook."
8604 (markdown-check-change-for-wiki-link from to))
8606 (defun markdown-fontify-buffer-wiki-links ()
8607 "Refontify all wiki links in the buffer."
8608 (interactive)
8609 (markdown-check-change-for-wiki-link (point-min) (point-max)))
8612 ;;; Following & Doing =========================================================
8614 (defun markdown-follow-thing-at-point (arg)
8615 "Follow thing at point if possible, such as a reference link or wiki link.
8616 Opens inline and reference links in a browser. Opens wiki links
8617 to other files in the current window, or the another window if
8618 ARG is non-nil.
8619 See `markdown-follow-link-at-point' and
8620 `markdown-follow-wiki-link-at-point'."
8621 (interactive "P")
8622 (cond ((markdown-link-p)
8623 (markdown-follow-link-at-point))
8624 ((markdown-wiki-link-p)
8625 (markdown-follow-wiki-link-at-point arg))
8627 (user-error "Nothing to follow at point"))))
8629 (make-obsolete 'markdown-jump 'markdown-do "v2.3")
8631 (defun markdown-do ()
8632 "Do something sensible based on context at point.
8633 Jumps between reference links and definitions; between footnote
8634 markers and footnote text."
8635 (interactive)
8636 (cond
8637 ;; Footnote definition
8638 ((markdown-footnote-text-positions)
8639 (markdown-footnote-return))
8640 ;; Footnote marker
8641 ((markdown-footnote-marker-positions)
8642 (markdown-footnote-goto-text))
8643 ;; Reference link
8644 ((thing-at-point-looking-at markdown-regex-link-reference)
8645 (markdown-reference-goto-definition))
8646 ;; Reference definition
8647 ((thing-at-point-looking-at markdown-regex-reference-definition)
8648 (markdown-reference-goto-link (match-string-no-properties 2)))
8649 ;; GFM task list item
8650 ((markdown-gfm-task-list-item-at-point)
8651 (markdown-toggle-gfm-checkbox))
8652 ;; Align table
8653 ((markdown-table-at-point-p)
8654 (call-interactively #'markdown-table-align))
8655 ;; Otherwise
8657 (markdown-insert-gfm-checkbox))))
8660 ;;; Miscellaneous =============================================================
8662 (defun markdown-compress-whitespace-string (str)
8663 "Compress whitespace in STR and return result.
8664 Leading and trailing whitespace is removed. Sequences of multiple
8665 spaces, tabs, and newlines are replaced with single spaces."
8666 (markdown-replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
8667 (markdown-replace-regexp-in-string "[ \t\n]+" " " str)))
8669 (defun markdown--substitute-command-keys (string)
8670 "Like `substitute-command-keys' but, but prefers control characters.
8671 First pass STRING to `substitute-command-keys' and then
8672 substitute `C-i` for `TAB` and `C-m` for `RET`."
8673 (replace-regexp-in-string
8674 "\\<TAB\\>" "C-i"
8675 (replace-regexp-in-string
8676 "\\<RET\\>" "C-m" (substitute-command-keys string) t) t))
8678 (defun markdown-line-number-at-pos (&optional pos)
8679 "Return (narrowed) buffer line number at position POS.
8680 If POS is nil, use current buffer location.
8681 This is an exact copy of `line-number-at-pos' for use in emacs21."
8682 (let ((opoint (or pos (point))) start)
8683 (save-excursion
8684 (goto-char (point-min))
8685 (setq start (point))
8686 (goto-char opoint)
8687 (forward-line 0)
8688 (1+ (count-lines start (point))))))
8690 (defun markdown-inside-link-p ()
8691 "Return t if point is within a link."
8692 (save-match-data
8693 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
8695 (defun markdown-line-is-reference-definition-p ()
8696 "Return whether the current line is a (non-footnote) reference defition."
8697 (save-excursion
8698 (move-beginning-of-line 1)
8699 (and (looking-at-p markdown-regex-reference-definition)
8700 (not (looking-at-p "[ \t]*\\[^")))))
8702 (defun markdown-adaptive-fill-function ()
8703 "Return prefix for filling paragraph or nil if not determined."
8704 (cond
8705 ;; List item inside blockquote
8706 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
8707 (markdown-replace-regexp-in-string
8708 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
8709 ;; Blockquote
8710 ((looking-at markdown-regex-blockquote)
8711 (buffer-substring-no-properties (match-beginning 0) (match-end 2)))
8712 ;; List items
8713 ((looking-at markdown-regex-list)
8714 (match-string-no-properties 0))
8715 ;; Footnote definition
8716 ((looking-at-p markdown-regex-footnote-definition)
8717 " ") ; four spaces
8718 ;; No match
8719 (t nil)))
8721 (defun markdown-fill-paragraph (&optional justify)
8722 "Fill paragraph at or after point.
8723 This function is like \\[fill-paragraph], but it skips Markdown
8724 code blocks. If the point is in a code block, or just before one,
8725 do not fill. Otherwise, call `fill-paragraph' as usual. If
8726 JUSTIFY is non-nil, justify text as well. Since this function
8727 handles filling itself, it always returns t so that
8728 `fill-paragraph' doesn't run."
8729 (interactive "P")
8730 (unless (or (markdown-code-block-at-point-p)
8731 (save-excursion
8732 (back-to-indentation)
8733 (skip-syntax-forward "-")
8734 (markdown-code-block-at-point-p)))
8735 (fill-paragraph justify))
8738 (make-obsolete 'markdown-fill-forward-paragraph-function
8739 'markdown-fill-forward-paragraph "v2.3")
8741 (defun markdown-fill-forward-paragraph (&optional arg)
8742 "Function used by `fill-paragraph' to move over ARG paragraphs.
8743 This is a `fill-forward-paragraph-function' for `markdown-mode'.
8744 It is called with a single argument specifying the number of
8745 paragraphs to move. Just like `forward-paragraph', it should
8746 return the number of paragraphs left to move."
8747 (or arg (setq arg 1))
8748 (if (> arg 0)
8749 ;; With positive ARG, move across ARG non-code-block paragraphs,
8750 ;; one at a time. When passing a code block, don't decrement ARG.
8751 (while (and (not (eobp))
8752 (> arg 0)
8753 (= (forward-paragraph 1) 0)
8754 (or (markdown-code-block-at-pos (point-at-bol 0))
8755 (setq arg (1- arg)))))
8756 ;; Move backward by one paragraph with negative ARG (always -1).
8757 (let ((start (point)))
8758 (setq arg (forward-paragraph arg))
8759 (while (and (not (eobp))
8760 (progn (move-to-left-margin) (not (eobp)))
8761 (looking-at-p paragraph-separate))
8762 (forward-line 1))
8763 (cond
8764 ;; Move point past whitespace following list marker.
8765 ((looking-at markdown-regex-list)
8766 (goto-char (match-end 0)))
8767 ;; Move point past whitespace following pipe at beginning of line
8768 ;; to handle Pandoc line blocks.
8769 ((looking-at "^|\\s-*")
8770 (goto-char (match-end 0)))
8771 ;; Return point if the paragraph passed was a code block.
8772 ((markdown-code-block-at-pos (point-at-bol 2))
8773 (goto-char start)))))
8774 arg)
8776 (defun markdown--inhibit-electric-quote ()
8777 "Function added to `electric-quote-inhibit-functions'.
8778 Return non-nil if the quote has been inserted inside a code block
8779 or span."
8780 (let ((pos (1- (point))))
8781 (or (markdown-inline-code-at-pos pos)
8782 (markdown-code-block-at-pos pos))))
8785 ;;; Extension Framework =======================================================
8787 (defun markdown-reload-extensions ()
8788 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
8789 (interactive)
8790 (when (member major-mode '(markdown-mode gfm-mode))
8791 ;; Refontify buffer
8792 (if (eval-when-compile (fboundp 'font-lock-flush))
8793 ;; Use font-lock-flush in Emacs >= 25.1
8794 (font-lock-flush)
8795 ;; Backwards compatibility for Emacs 24.3-24.5
8796 (when (and font-lock-mode (fboundp 'font-lock-refresh-defaults))
8797 (font-lock-refresh-defaults)))
8798 ;; Add or remove hooks related to extensions
8799 (markdown-setup-wiki-link-hooks)))
8801 (defun markdown-handle-local-variables ()
8802 "Run in `hack-local-variables-hook' to update font lock rules.
8803 Checks to see if there is actually a ‘markdown-mode’ file local variable
8804 before regenerating font-lock rules for extensions."
8805 (when (and (boundp 'file-local-variables-alist)
8806 (or (assoc 'markdown-enable-wiki-links file-local-variables-alist)
8807 (assoc 'markdown-enable-math file-local-variables-alist)))
8808 (when (assoc 'markdown-enable-math file-local-variables-alist)
8809 (markdown-toggle-math markdown-enable-math))
8810 (markdown-reload-extensions)))
8813 ;;; Wiki Links ================================================================
8815 (defun markdown-toggle-wiki-links (&optional arg)
8816 "Toggle support for wiki links.
8817 With a prefix argument ARG, enable wiki link support if ARG is positive,
8818 and disable it otherwise."
8819 (interactive (list (or current-prefix-arg 'toggle)))
8820 (setq markdown-enable-wiki-links
8821 (if (eq arg 'toggle)
8822 (not markdown-enable-wiki-links)
8823 (> (prefix-numeric-value arg) 0)))
8824 (if markdown-enable-wiki-links
8825 (message "markdown-mode wiki link support enabled")
8826 (message "markdown-mode wiki link support disabled"))
8827 (markdown-reload-extensions))
8829 (defun markdown-setup-wiki-link-hooks ()
8830 "Add or remove hooks for fontifying wiki links.
8831 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
8832 ;; Anytime text changes make sure it gets fontified correctly
8833 (if (and markdown-enable-wiki-links
8834 markdown-wiki-link-fontify-missing)
8835 (add-hook 'after-change-functions
8836 'markdown-check-change-for-wiki-link-after-change t t)
8837 (remove-hook 'after-change-functions
8838 'markdown-check-change-for-wiki-link-after-change t))
8839 ;; If we left the buffer there is a really good chance we were
8840 ;; creating one of the wiki link documents. Make sure we get
8841 ;; refontified when we come back.
8842 (if (and markdown-enable-wiki-links
8843 markdown-wiki-link-fontify-missing)
8844 (progn
8845 (add-hook 'window-configuration-change-hook
8846 'markdown-fontify-buffer-wiki-links t t)
8847 (markdown-fontify-buffer-wiki-links))
8848 (remove-hook 'window-configuration-change-hook
8849 'markdown-fontify-buffer-wiki-links t)
8850 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
8853 ;;; Math Support ==============================================================
8855 (make-obsolete 'markdown-enable-math 'markdown-toggle-math "v2.1")
8857 (defconst markdown-mode-font-lock-keywords-math
8858 (list
8859 ;; Equation reference (eq:foo)
8860 '("\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" . ((1 markdown-markup-face)
8861 (2 markdown-reference-face)
8862 (3 markdown-markup-face)))
8863 ;; Equation reference \eqref{foo}
8864 '("\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" . ((1 markdown-markup-face)
8865 (2 markdown-reference-face)
8866 (3 markdown-markup-face))))
8867 "Font lock keywords to add and remove when toggling math support.")
8869 (defun markdown-toggle-math (&optional arg)
8870 "Toggle support for inline and display LaTeX math expressions.
8871 With a prefix argument ARG, enable math mode if ARG is positive,
8872 and disable it otherwise. If called from Lisp, enable the mode
8873 if ARG is omitted or nil."
8874 (interactive (list (or current-prefix-arg 'toggle)))
8875 (setq markdown-enable-math
8876 (if (eq arg 'toggle)
8877 (not markdown-enable-math)
8878 (> (prefix-numeric-value arg) 0)))
8879 (if markdown-enable-math
8880 (progn
8881 (font-lock-add-keywords
8882 'markdown-mode markdown-mode-font-lock-keywords-math)
8883 (message "markdown-mode math support enabled"))
8884 (font-lock-remove-keywords
8885 'markdown-mode markdown-mode-font-lock-keywords-math)
8886 (message "markdown-mode math support disabled"))
8887 (markdown-reload-extensions))
8890 ;;; GFM Checkboxes ============================================================
8892 (define-button-type 'markdown-gfm-checkbox-button
8893 'follow-link t
8894 'face 'markdown-gfm-checkbox-face
8895 'mouse-face 'markdown-highlight-face
8896 'action #'markdown-toggle-gfm-checkbox-button)
8898 (defun markdown-gfm-task-list-item-at-point (&optional bounds)
8899 "Return non-nil if there is a GFM task list item at the point.
8900 Optionally, the list item BOUNDS may be given if available, as
8901 returned by `markdown-cur-list-item-bounds'. When a task list item
8902 is found, the return value is the same value returned by
8903 `markdown-cur-list-item-bounds'."
8904 (unless bounds
8905 (setq bounds (markdown-cur-list-item-bounds)))
8906 (> (length (nth 5 bounds)) 0))
8908 (defun markdown-insert-gfm-checkbox ()
8909 "Add GFM checkbox at point.
8910 Returns t if added.
8911 Returns nil if non-applicable."
8912 (interactive)
8913 (let ((bounds (markdown-cur-list-item-bounds)))
8914 (if bounds
8915 (unless (cl-sixth bounds)
8916 (let ((pos (+ (cl-first bounds) (cl-fourth bounds)))
8917 (markup "[ ] "))
8918 (if (< pos (point))
8919 (save-excursion
8920 (goto-char pos)
8921 (insert markup))
8922 (goto-char pos)
8923 (insert markup))
8925 (unless (save-excursion
8926 (back-to-indentation)
8927 (or (markdown-list-item-at-point-p)
8928 (markdown-heading-at-point)
8929 (markdown-in-comment-p)
8930 (markdown-code-block-at-point-p)))
8931 (let ((pos (save-excursion
8932 (back-to-indentation)
8933 (point)))
8934 (markup (concat (or (save-excursion
8935 (beginning-of-line 0)
8936 (cl-fifth (markdown-cur-list-item-bounds)))
8937 markdown-unordered-list-item-prefix)
8938 "[ ] ")))
8939 (if (< pos (point))
8940 (save-excursion
8941 (goto-char pos)
8942 (insert markup))
8943 (goto-char pos)
8944 (insert markup))
8945 t)))))
8947 (defun markdown-toggle-gfm-checkbox ()
8948 "Toggle GFM checkbox at point.
8949 Returns the resulting status as a string, either \"[x]\" or \"[ ]\".
8950 Returns nil if there is no task list item at the point."
8951 (interactive)
8952 (save-match-data
8953 (save-excursion
8954 (let ((bounds (markdown-cur-list-item-bounds)))
8955 (when bounds
8956 ;; Move to beginning of task list item
8957 (goto-char (cl-first bounds))
8958 ;; Advance to column of first non-whitespace after marker
8959 (forward-char (cl-fourth bounds))
8960 (cond ((looking-at "\\[ \\]")
8961 (replace-match
8962 (if markdown-gfm-uppercase-checkbox "[X]" "[x]")
8963 nil t)
8964 (match-string-no-properties 0))
8965 ((looking-at "\\[[xX]\\]")
8966 (replace-match "[ ]" nil t)
8967 (match-string-no-properties 0))))))))
8969 (defun markdown-toggle-gfm-checkbox-button (button)
8970 "Toggle GFM checkbox BUTTON on click."
8971 (save-match-data
8972 (save-excursion
8973 (goto-char (button-start button))
8974 (markdown-toggle-gfm-checkbox))))
8976 (defun markdown-make-gfm-checkboxes-buttons (start end)
8977 "Make GFM checkboxes buttons in region between START and END."
8978 (save-excursion
8979 (goto-char start)
8980 (let ((case-fold-search t))
8981 (save-excursion
8982 (while (re-search-forward markdown-regex-gfm-checkbox end t)
8983 (make-button (match-beginning 1) (match-end 1)
8984 :type 'markdown-gfm-checkbox-button))))))
8986 ;; Called when any modification is made to buffer text.
8987 (defun markdown-gfm-checkbox-after-change-function (beg end _)
8988 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
8989 BEG and END are the limits of scanned region."
8990 (save-excursion
8991 (save-match-data
8992 ;; Rescan between start of line from `beg' and start of line after `end'.
8993 (markdown-make-gfm-checkboxes-buttons
8994 (progn (goto-char beg) (beginning-of-line) (point))
8995 (progn (goto-char end) (forward-line 1) (point))))))
8997 (defun markdown-remove-gfm-checkbox-overlays ()
8998 "Remove all GFM checkbox overlays in buffer."
8999 (save-excursion
9000 (save-restriction
9001 (widen)
9002 (remove-overlays nil nil 'face 'markdown-gfm-checkbox-face))))
9005 ;;; Display inline image =================================================
9007 (defvar markdown-inline-image-overlays nil)
9008 (make-variable-buffer-local 'markdown-inline-image-overlays)
9010 (defun markdown-remove-inline-images ()
9011 "Remove inline image overlays from image links in the buffer.
9012 This can be toggled with `markdown-toggle-inline-images'
9013 or \\[markdown-toggle-inline-images]."
9014 (interactive)
9015 (mapc #'delete-overlay markdown-inline-image-overlays)
9016 (setq markdown-inline-image-overlays nil))
9018 (defun markdown-display-inline-images ()
9019 "Add inline image overlays to image links in the buffer.
9020 This can be toggled with `markdown-toggle-inline-images'
9021 or \\[markdown-toggle-inline-images]."
9022 (interactive)
9023 (unless (display-graphic-p)
9024 (error "Cannot show images"))
9025 (save-excursion
9026 (save-restriction
9027 (widen)
9028 (goto-char (point-min))
9029 (while (re-search-forward markdown-regex-link-inline nil t)
9030 (let ((start (match-beginning 0))
9031 (end (match-end 0))
9032 (file (match-string-no-properties 6)))
9033 (when (file-exists-p file)
9034 (let* ((abspath (if (file-name-absolute-p file)
9035 file
9036 (concat default-directory file)))
9037 (image (create-image abspath)))
9038 (when image
9039 (let ((ov (make-overlay start end)))
9040 (overlay-put ov 'display image)
9041 (overlay-put ov 'face 'default)
9042 (push ov markdown-inline-image-overlays))))))))))
9044 (defun markdown-toggle-inline-images ()
9045 "Toggle inline image overlays in the buffer."
9046 (interactive)
9047 (if markdown-inline-image-overlays
9048 (markdown-remove-inline-images)
9049 (markdown-display-inline-images)))
9052 ;;; GFM Code Block Fontification ==============================================
9054 (defcustom markdown-fontify-code-blocks-natively nil
9055 "When non-nil, fontify code in code blocks using the native major mode.
9056 This only works for fenced code blocks where the language is
9057 specified where we can automatically determine the appropriate
9058 mode to use. The language to mode mapping may be customized by
9059 setting the variable `markdown-code-lang-modes'."
9060 :group 'markdown
9061 :type 'boolean
9062 :safe 'booleanp
9063 :package-version '(markdown-mode . "2.3"))
9065 (defun markdown-toggle-fontify-code-blocks-natively (&optional arg)
9066 "Toggle the native fontification of code blocks.
9067 With a prefix argument ARG, enable if ARG is positive,
9068 and disable otherwise."
9069 (interactive (list (or current-prefix-arg 'toggle)))
9070 (setq markdown-fontify-code-blocks-natively
9071 (if (eq arg 'toggle)
9072 (not markdown-fontify-code-blocks-natively)
9073 (> (prefix-numeric-value arg) 0)))
9074 (if markdown-fontify-code-blocks-natively
9075 (message "markdown-mode native code block fontification enabled")
9076 (message "markdown-mode native code block fontification disabled"))
9077 (markdown-reload-extensions))
9079 ;; This is based on `org-src-lang-modes' from org-src.el
9080 (defcustom markdown-code-lang-modes
9081 '(("ocaml" . tuareg-mode) ("elisp" . emacs-lisp-mode) ("ditaa" . artist-mode)
9082 ("asymptote" . asy-mode) ("dot" . fundamental-mode) ("sqlite" . sql-mode)
9083 ("calc" . fundamental-mode) ("C" . c-mode) ("cpp" . c++-mode)
9084 ("C++" . c++-mode) ("screen" . shell-script-mode) ("shell" . sh-mode)
9085 ("bash" . sh-mode))
9086 "Alist mapping languages to their major mode.
9087 The key is the language name, the value is the major mode. For
9088 many languages this is simple, but for language where this is not
9089 the case, this variable provides a way to simplify things on the
9090 user side. For example, there is no ocaml-mode in Emacs, but the
9091 mode to use is `tuareg-mode'."
9092 :group 'markdown
9093 :type '(repeat
9094 (cons
9095 (string "Language name")
9096 (symbol "Major mode")))
9097 :package-version '(markdown-mode . "2.3"))
9099 (defun markdown-get-lang-mode (lang)
9100 "Return major mode that should be used for LANG.
9101 LANG is a string, and the returned major mode is a symbol."
9102 (cl-find-if
9103 'fboundp
9104 (list (cdr (assoc lang markdown-code-lang-modes))
9105 (cdr (assoc (downcase lang) markdown-code-lang-modes))
9106 (intern (concat lang "-mode"))
9107 (intern (concat (downcase lang) "-mode")))))
9109 (defun markdown-fontify-code-blocks-generic (matcher last)
9110 "Add text properties to next code block from point to LAST.
9111 Use matching function MATCHER."
9112 (when (funcall matcher last)
9113 (save-excursion
9114 (save-match-data
9115 (let* ((start (match-beginning 0))
9116 (end (match-end 0))
9117 ;; Find positions outside opening and closing backquotes.
9118 (bol-prev (progn (goto-char start)
9119 (if (bolp) (point-at-bol 0) (point-at-bol))))
9120 (eol-next (progn (goto-char end)
9121 (if (bolp) (point-at-bol 2) (point-at-bol 3))))
9122 lang)
9123 (if (and markdown-fontify-code-blocks-natively
9124 (setq lang (markdown-code-block-lang)))
9125 (markdown-fontify-code-block-natively lang start end)
9126 (add-text-properties start end '(face markdown-pre-face)))
9127 ;; Set background for block as well as opening and closing lines.
9128 (font-lock-append-text-property
9129 bol-prev eol-next 'face 'markdown-code-face)
9130 ;; Set invisible property for lines before and after, including newline.
9131 (add-text-properties bol-prev start '(invisible markdown-markup))
9132 (add-text-properties end eol-next '(invisible markdown-markup)))))
9135 (defun markdown-fontify-gfm-code-blocks (last)
9136 "Add text properties to next GFM code block from point to LAST."
9137 (markdown-fontify-code-blocks-generic 'markdown-match-gfm-code-blocks last))
9139 (defun markdown-fontify-fenced-code-blocks (last)
9140 "Add text properties to next tilde fenced code block from point to LAST."
9141 (markdown-fontify-code-blocks-generic 'markdown-match-fenced-code-blocks last))
9143 ;; Based on `org-src-font-lock-fontify-block' from org-src.el.
9144 (defun markdown-fontify-code-block-natively (lang start end)
9145 "Fontify given GFM or fenced code block.
9146 This function is called by Emacs for automatic fontification when
9147 `markdown-fontify-code-blocks-natively' is non-nil. LANG is the
9148 language used in the block. START and END specify the block
9149 position."
9150 (let ((lang-mode (markdown-get-lang-mode lang)))
9151 (when (fboundp lang-mode)
9152 (let ((string (buffer-substring-no-properties start end))
9153 (modified (buffer-modified-p))
9154 (markdown-buffer (current-buffer)) pos next)
9155 (remove-text-properties start end '(face nil))
9156 (with-current-buffer
9157 (get-buffer-create
9158 (concat " markdown-code-fontification:" (symbol-name lang-mode)))
9159 ;; Make sure that modification hooks are not inhibited in
9160 ;; the org-src-fontification buffer in case we're called
9161 ;; from `jit-lock-function' (Bug#25132).
9162 (let ((inhibit-modification-hooks nil))
9163 (delete-region (point-min) (point-max))
9164 (insert string " ")) ;; so there's a final property change
9165 (unless (eq major-mode lang-mode) (funcall lang-mode))
9166 (markdown-font-lock-ensure)
9167 (setq pos (point-min))
9168 (while (setq next (next-single-property-change pos 'face))
9169 (let ((val (get-text-property pos 'face)))
9170 (when val
9171 (put-text-property
9172 (+ start (1- pos)) (1- (+ start next)) 'face
9173 val markdown-buffer)))
9174 (setq pos next)))
9175 (add-text-properties
9176 start end
9177 '(font-lock-fontified t fontified t font-lock-multiline t))
9178 (set-buffer-modified-p modified)))))
9180 (require 'edit-indirect nil t)
9181 (defvar edit-indirect-guess-mode-function)
9182 (defvar edit-indirect-after-commit-functions)
9184 (defun markdown--edit-indirect-after-commit-function (_beg end)
9185 "Ensure trailing newlines at the END of code blocks."
9186 (goto-char end)
9187 (unless (eq (char-before) ?\n)
9188 (insert "\n")))
9190 (defun markdown-edit-code-block ()
9191 "Edit Markdown code block in an indirect buffer."
9192 (interactive)
9193 (save-excursion
9194 (if (fboundp 'edit-indirect-region)
9195 (let* ((bounds (markdown-get-enclosing-fenced-block-construct))
9196 (begin (and bounds (goto-char (nth 0 bounds)) (point-at-bol 2)))
9197 (end (and bounds (goto-char (nth 1 bounds)) (point-at-bol 1))))
9198 (if (and begin end)
9199 (let* ((lang (markdown-code-block-lang))
9200 (mode (or (and lang (markdown-get-lang-mode lang))
9201 markdown-edit-code-block-default-mode))
9202 (edit-indirect-guess-mode-function
9203 (lambda (_parent-buffer _beg _end)
9204 (funcall mode))))
9205 (edit-indirect-region begin end 'display-buffer))
9206 (user-error "Not inside a GFM or tilde fenced code block")))
9207 (when (y-or-n-p "Package edit-indirect needed to edit code blocks. Install it now? ")
9208 (progn (package-refresh-contents)
9209 (package-install 'edit-indirect)
9210 (markdown-edit-code-block))))))
9213 ;;; Table Editing
9215 ;; These functions were originally adapted from `org-table.el'.
9217 ;; General helper functions
9219 (defmacro markdown--with-gensyms (symbols &rest body)
9220 (declare (debug (sexp body)) (indent 1))
9221 `(let ,(mapcar (lambda (s)
9222 `(,s (make-symbol (concat "--" (symbol-name ',s)))))
9223 symbols)
9224 ,@body))
9226 (defun markdown--split-string (string &optional separators)
9227 "Splits STRING into substrings at SEPARATORS.
9228 SEPARATORS is a regular expression. If nil it defaults to
9229 `split-string-default-separators'. This version returns no empty
9230 strings if there are matches at the beginning and end of string."
9231 (let ((start 0) notfirst list)
9232 (while (and (string-match
9233 (or separators split-string-default-separators)
9234 string
9235 (if (and notfirst
9236 (= start (match-beginning 0))
9237 (< start (length string)))
9238 (1+ start) start))
9239 (< (match-beginning 0) (length string)))
9240 (setq notfirst t)
9241 (or (eq (match-beginning 0) 0)
9242 (and (eq (match-beginning 0) (match-end 0))
9243 (eq (match-beginning 0) start))
9244 (push (substring string start (match-beginning 0)) list))
9245 (setq start (match-end 0)))
9246 (or (eq start (length string))
9247 (push (substring string start) list))
9248 (nreverse list)))
9250 (defun markdown--string-width (s)
9251 "Return width of string S.
9252 This version ignores characters with invisibility property
9253 `markdown-markup'."
9254 (let (b)
9255 (when (or (eq t buffer-invisibility-spec)
9256 (member 'markdown-markup buffer-invisibility-spec))
9257 (while (setq b (text-property-any
9258 0 (length s)
9259 'invisible 'markdown-markup s))
9260 (setq s (concat
9261 (substring s 0 b)
9262 (substring s (or (next-single-property-change
9263 b 'invisible s)
9264 (length s))))))))
9265 (string-width s))
9267 (defun markdown--remove-invisible-markup (s)
9268 "Remove Markdown markup from string S.
9269 This version removes characters with invisibility property
9270 `markdown-markup'."
9271 (let (b)
9272 (while (setq b (text-property-any
9273 0 (length s)
9274 'invisible 'markdown-markup s))
9275 (setq s (concat
9276 (substring s 0 b)
9277 (substring s (or (next-single-property-change
9278 b 'invisible s)
9279 (length s)))))))
9282 ;; Functions for maintaining tables
9284 (defvar markdown-table-at-point-p-function nil
9285 "Function to decide if point is inside a table.
9287 The indirection serves to differentiate between standard markdown
9288 tables and gfm tables which are less strict about the markup.")
9290 (defconst markdown-table-line-regexp "^[ \t]*|"
9291 "Regexp matching any line inside a table.")
9293 (defconst markdown-table-hline-regexp "^[ \t]*|[-:]"
9294 "Regexp matching hline inside a table.")
9296 (defconst markdown-table-dline-regexp "^[ \t]*|[^-:]"
9297 "Regexp matching dline inside a table.")
9299 (defun markdown-table-at-point-p ()
9300 "Return non-nil when point is inside a table."
9301 (if (functionp markdown-table-at-point-p-function)
9302 (funcall markdown-table-at-point-p-function)
9303 (markdown--table-at-point-p)))
9305 (defun markdown--table-at-point-p ()
9306 "Return non-nil when point is inside a table."
9307 (save-excursion
9308 (beginning-of-line)
9309 (and (looking-at-p markdown-table-line-regexp)
9310 (not (markdown-code-block-at-point-p)))))
9312 (defconst gfm-table-line-regexp "^.?*|"
9313 "Regexp matching any line inside a table.")
9315 (defconst gfm-table-hline-regexp "^-+\\(|-\\)+"
9316 "Regexp matching hline inside a table.")
9318 ;; GFM simplified tables syntax is as follows:
9319 ;; - A header line for the column names, this is any text
9320 ;; separated by `|'.
9321 ;; - Followed by a string -|-|- ..., the number of dashes is optional
9322 ;; but must be higher than 1. The number of separators should match
9323 ;; the number of columns.
9324 ;; - Followed by the rows of data, which has the same format as the
9325 ;; header line.
9326 ;; Example:
9328 ;; foo | bar
9329 ;; ------|---------
9330 ;; bar | baz
9331 ;; bar | baz
9332 (defun gfm--table-at-point-p ()
9333 "Return non-nil when point is inside a gfm-compatible table."
9334 (or (markdown--table-at-point-p)
9335 (save-excursion
9336 (beginning-of-line)
9337 (when (looking-at-p gfm-table-line-regexp)
9338 ;; we might be at the first line of the table, check if the
9339 ;; line below is the hline
9340 (or (save-excursion
9341 (forward-line 1)
9342 (looking-at-p gfm-table-hline-regexp))
9343 ;; go up to find the header
9344 (catch 'done
9345 (while (looking-at-p gfm-table-line-regexp)
9346 (when (looking-at-p gfm-table-hline-regexp)
9347 (throw 'done t))
9348 (forward-line -1))
9349 nil))))))
9351 (defun markdown-table-hline-at-point-p ()
9352 "Return non-nil when point is on a hline in a table.
9353 This function assumes point is on a table."
9354 (save-excursion
9355 (beginning-of-line)
9356 (looking-at-p markdown-table-hline-regexp)))
9358 (defun markdown-table-begin ()
9359 "Find the beginning of the table and return its position.
9360 This function assumes point is on a table."
9361 (save-excursion
9362 (while (and (not (bobp))
9363 (markdown-table-at-point-p))
9364 (forward-line -1))
9365 (unless (bobp)
9366 (forward-line 1))
9367 (point)))
9369 (defun markdown-table-end ()
9370 "Find the end of the table and return its position.
9371 This function assumes point is on a table."
9372 (save-excursion
9373 (while (and (not (eobp))
9374 (markdown-table-at-point-p))
9375 (forward-line 1))
9376 (point)))
9378 (defun markdown-table-get-dline ()
9379 "Return index of the table data line at point.
9380 This function assumes point is on a table."
9381 (let ((pos (point)) (end (markdown-table-end)) (cnt 0))
9382 (save-excursion
9383 (goto-char (markdown-table-begin))
9384 (while (and (re-search-forward
9385 markdown-table-dline-regexp end t)
9386 (setq cnt (1+ cnt))
9387 (< (point-at-eol) pos))))
9388 cnt))
9390 (defun markdown-table-get-column ()
9391 "Return table column at point.
9392 This function assumes point is on a table."
9393 (let ((pos (point)) (cnt 0))
9394 (save-excursion
9395 (beginning-of-line)
9396 (while (search-forward "|" pos t) (setq cnt (1+ cnt))))
9397 cnt))
9399 (defun markdown-table-get-cell (&optional n)
9400 "Return the content of the cell in column N of current row.
9401 N defaults to column at point. This function assumes point is on
9402 a table."
9403 (and n (markdown-table-goto-column n))
9404 (skip-chars-backward "^|\n") (backward-char 1)
9405 (if (looking-at "|[^|\r\n]*")
9406 (let* ((pos (match-beginning 0))
9407 (val (buffer-substring (1+ pos) (match-end 0))))
9408 (goto-char (min (point-at-eol) (+ 2 pos)))
9409 ;; Trim whitespaces
9410 (setq val (replace-regexp-in-string "\\`[ \t]+" "" val)
9411 val (replace-regexp-in-string "[ \t]+\\'" "" val)))
9412 (forward-char 1) ""))
9414 (defun markdown-table-goto-dline (n)
9415 "Go to the Nth data line in the table at point.
9416 Return t when the line exists, nil otherwise. This function
9417 assumes point is on a table."
9418 (goto-char (markdown-table-begin))
9419 (let ((end (markdown-table-end)) (cnt 0))
9420 (while (and (re-search-forward
9421 markdown-table-dline-regexp end t)
9422 (< (setq cnt (1+ cnt)) n)))
9423 (= cnt n)))
9425 (defun markdown-table-goto-column (n &optional on-delim)
9426 "Go to the Nth column in the table line at point.
9427 With optional argument ON-DELIM, stop with point before the left
9428 delimiter of the cell. If there are less than N cells, just go
9429 beyond the last delimiter. This function assumes point is on a
9430 table."
9431 (beginning-of-line 1)
9432 (when (> n 0)
9433 (while (and (> (setq n (1- n)) -1)
9434 (search-forward "|" (point-at-eol) t)))
9435 (if on-delim
9436 (backward-char 1)
9437 (when (looking-at " ") (forward-char 1)))))
9439 (defmacro markdown-table-save-cell (&rest body)
9440 "Save cell at point, execute BODY and restore cell.
9441 This function assumes point is on a table."
9442 (declare (debug (body)))
9443 (markdown--with-gensyms (line column)
9444 `(let ((,line (copy-marker (line-beginning-position)))
9445 (,column (markdown-table-get-column)))
9446 (unwind-protect
9447 (progn ,@body)
9448 (goto-char ,line)
9449 (markdown-table-goto-column ,column)
9450 (set-marker ,line nil)))))
9452 (defun markdown-table-blank-line (s)
9453 "Convert a table line S into a line with blank cells."
9454 (if (string-match "^[ \t]*|-" s)
9455 (setq s (mapconcat
9456 (lambda (x) (if (member x '(?| ?+)) "|" " "))
9457 s ""))
9458 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9459 (setq s (replace-match
9460 (concat "|" (make-string (length (match-string 1 s)) ?\ ) "|")
9461 t t s)))
9464 (defun markdown-table-colfmt (fmtspec)
9465 "Process column alignment specifier FMTSPEC for tables."
9466 (when (stringp fmtspec)
9467 (mapcar (lambda (x)
9468 (cond ((string-match-p "^:.*:$" x) 'c)
9469 ((string-match-p "^:" x) 'l)
9470 ((string-match-p ":$" x) 'r)
9471 (t 'd)))
9472 (markdown--split-string fmtspec "\\s-*|\\s-*"))))
9474 (defun markdown-table-align ()
9475 "Align table at point.
9476 This function assumes point is on a table."
9477 (interactive)
9478 (let ((begin (markdown-table-begin))
9479 (end (copy-marker (markdown-table-end))))
9480 (markdown-table-save-cell
9481 (goto-char begin)
9482 (let* (fmtspec
9483 ;; Store table indent
9484 (indent (progn (looking-at "[ \t]*") (match-string 0)))
9485 ;; Split table in lines and save column format specifier
9486 (lines (mapcar (lambda (l)
9487 (if (string-match-p "\\`[ \t]*|[-:]" l)
9488 (progn (setq fmtspec (or fmtspec l)) nil) l))
9489 (markdown--split-string (buffer-substring begin end) "\n")))
9490 ;; Split lines in cells
9491 (cells (mapcar (lambda (l) (markdown--split-string l "\\s-*|\\s-*"))
9492 (remq nil lines)))
9493 ;; Calculate maximum number of cells in a line
9494 (maxcells (if cells
9495 (apply #'max (mapcar #'length cells))
9496 (user-error "Empty table")))
9497 ;; Empty cells to fill short lines
9498 (emptycells (make-list maxcells "")) maxwidths)
9499 ;; Calculate maximum width for each column
9500 (dotimes (i maxcells)
9501 (let ((column (mapcar (lambda (x) (or (nth i x) "")) cells)))
9502 (push (apply #'max 1 (mapcar #'markdown--string-width column))
9503 maxwidths)))
9504 (setq maxwidths (nreverse maxwidths))
9505 ;; Process column format specifier
9506 (setq fmtspec (markdown-table-colfmt fmtspec))
9507 ;; Compute formats needed for output of table lines
9508 (let ((hfmt (concat indent "|"))
9509 (rfmt (concat indent "|"))
9510 hfmt1 rfmt1 fmt)
9511 (dolist (width maxwidths (setq hfmt (concat (substring hfmt 0 -1) "|")))
9512 (setq fmt (pop fmtspec))
9513 (cond ((equal fmt 'l) (setq hfmt1 ":%s-|" rfmt1 " %%-%ds |"))
9514 ((equal fmt 'r) (setq hfmt1 "-%s:|" rfmt1 " %%%ds |"))
9515 ((equal fmt 'c) (setq hfmt1 ":%s:|" rfmt1 " %%-%ds |"))
9516 (t (setq hfmt1 "-%s-|" rfmt1 " %%-%ds |")))
9517 (setq rfmt (concat rfmt (format rfmt1 width)))
9518 (setq hfmt (concat hfmt (format hfmt1 (make-string width ?-)))))
9519 ;; Replace modified lines only
9520 (dolist (line lines)
9521 (let ((line (if line
9522 (apply #'format rfmt (append (pop cells) emptycells))
9523 hfmt))
9524 (previous (buffer-substring (point) (line-end-position))))
9525 (if (equal previous line)
9526 (forward-line)
9527 (insert line "\n")
9528 (delete-region (point) (line-beginning-position 2))))))
9529 (set-marker end nil)))))
9531 (defun markdown-table-insert-row (&optional arg)
9532 "Insert a new row above the row at point into the table.
9533 With optional argument ARG, insert below the current row."
9534 (interactive "P")
9535 (unless (markdown-table-at-point-p)
9536 (user-error "Not at a table"))
9537 (let* ((line (buffer-substring
9538 (line-beginning-position) (line-end-position)))
9539 (new (markdown-table-blank-line line)))
9540 (beginning-of-line (if arg 2 1))
9541 (unless (bolp) (insert "\n"))
9542 (insert-before-markers new "\n")
9543 (beginning-of-line 0)
9544 (re-search-forward "| ?" (line-end-position) t)))
9546 (defun markdown-table-delete-row ()
9547 "Delete row or horizontal line at point from the table."
9548 (interactive)
9549 (unless (markdown-table-at-point-p)
9550 (user-error "Not at a table"))
9551 (let ((col (current-column)))
9552 (kill-region (point-at-bol)
9553 (min (1+ (point-at-eol)) (point-max)))
9554 (unless (markdown-table-at-point-p) (beginning-of-line 0))
9555 (move-to-column col)))
9557 (defun markdown-table-move-row (&optional up)
9558 "Move table line at point down.
9559 With optional argument UP, move it up."
9560 (interactive "P")
9561 (unless (markdown-table-at-point-p)
9562 (user-error "Not at a table"))
9563 (let* ((col (current-column)) (pos (point))
9564 (tonew (if up 0 2)) txt)
9565 (beginning-of-line tonew)
9566 (unless (markdown-table-at-point-p)
9567 (goto-char pos) (user-error "Cannot move row further"))
9568 (goto-char pos) (beginning-of-line 1) (setq pos (point))
9569 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9570 (delete-region (point) (1+ (point-at-eol)))
9571 (beginning-of-line tonew)
9572 (insert txt) (beginning-of-line 0)
9573 (move-to-column col)))
9575 (defun markdown-table-move-row-up ()
9576 "Move table row at point up."
9577 (interactive)
9578 (markdown-table-move-row 'up))
9580 (defun markdown-table-move-row-down ()
9581 "Move table row at point down."
9582 (interactive)
9583 (markdown-table-move-row nil))
9585 (defun markdown-table-insert-column ()
9586 "Insert a new table column."
9587 (interactive)
9588 (unless (markdown-table-at-point-p)
9589 (user-error "Not at a table"))
9590 (let* ((col (max 1 (markdown-table-get-column)))
9591 (begin (markdown-table-begin))
9592 (end (copy-marker (markdown-table-end))))
9593 (markdown-table-save-cell
9594 (goto-char begin)
9595 (while (< (point) end)
9596 (markdown-table-goto-column col t)
9597 (if (markdown-table-hline-at-point-p)
9598 (insert "|---")
9599 (insert "| "))
9600 (forward-line)))
9601 (set-marker end nil)
9602 (markdown-table-align)))
9604 (defun markdown-table-delete-column ()
9605 "Delete column at point from table."
9606 (interactive)
9607 (unless (markdown-table-at-point-p)
9608 (user-error "Not at a table"))
9609 (let ((col (markdown-table-get-column))
9610 (begin (markdown-table-begin))
9611 (end (copy-marker (markdown-table-end))))
9612 (markdown-table-save-cell
9613 (goto-char begin)
9614 (while (< (point) end)
9615 (markdown-table-goto-column col t)
9616 (and (looking-at "|[^|\n]+|")
9617 (replace-match "|"))
9618 (forward-line)))
9619 (set-marker end nil)
9620 (markdown-table-goto-column (max 1 (1- col)))
9621 (markdown-table-align)))
9623 (defun markdown-table-move-column (&optional left)
9624 "Move table column at point to the right.
9625 With optional argument LEFT, move it to the left."
9626 (interactive "P")
9627 (unless (markdown-table-at-point-p)
9628 (user-error "Not at a table"))
9629 (let* ((col (markdown-table-get-column))
9630 (col1 (if left (1- col) col))
9631 (colpos (if left (1- col) (1+ col)))
9632 (begin (markdown-table-begin))
9633 (end (copy-marker (markdown-table-end))))
9634 (when (and left (= col 1))
9635 (user-error "Cannot move column further left"))
9636 (when (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9637 (user-error "Cannot move column further right"))
9638 (markdown-table-save-cell
9639 (goto-char begin)
9640 (while (< (point) end)
9641 (markdown-table-goto-column col1 t)
9642 (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9643 (replace-match "|\\2|\\1|"))
9644 (forward-line)))
9645 (set-marker end nil)
9646 (markdown-table-goto-column colpos)
9647 (markdown-table-align)))
9649 (defun markdown-table-move-column-left ()
9650 "Move table column at point to the left."
9651 (interactive)
9652 (markdown-table-move-column 'left))
9654 (defun markdown-table-move-column-right ()
9655 "Move table column at point to the right."
9656 (interactive)
9657 (markdown-table-move-column nil))
9659 (defun markdown-table-next-row ()
9660 "Go to the next row (same column) in the table.
9661 Create new table lines if required."
9662 (interactive)
9663 (unless (markdown-table-at-point-p)
9664 (user-error "Not at a table"))
9665 (if (or (looking-at "[ \t]*$")
9666 (save-excursion (skip-chars-backward " \t") (bolp)))
9667 (newline)
9668 (markdown-table-align)
9669 (let ((col (markdown-table-get-column)))
9670 (beginning-of-line 2)
9671 (if (or (not (markdown-table-at-point-p))
9672 (markdown-table-hline-at-point-p))
9673 (progn
9674 (beginning-of-line 0)
9675 (markdown-table-insert-row 'below)))
9676 (markdown-table-goto-column col)
9677 (skip-chars-backward "^|\n\r")
9678 (when (looking-at " ") (forward-char 1)))))
9680 (defun markdown-table-forward-cell ()
9681 "Go to the next cell in the table.
9682 Create new table lines if required."
9683 (interactive)
9684 (unless (markdown-table-at-point-p)
9685 (user-error "Not at a table"))
9686 (markdown-table-align)
9687 (let ((end (markdown-table-end)))
9688 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9689 (condition-case nil
9690 (progn
9691 (re-search-forward "|" end)
9692 (if (looking-at "[ \t]*$")
9693 (re-search-forward "|" end))
9694 (if (and (looking-at "[-:]")
9695 (re-search-forward "^[ \t]*|\\([^-:]\\)" end t))
9696 (goto-char (match-beginning 1)))
9697 (if (looking-at "[-:]")
9698 (progn
9699 (beginning-of-line 0)
9700 (markdown-table-insert-row 'below))
9701 (when (looking-at " ") (forward-char 1))))
9702 (error (markdown-table-insert-row 'below)))))
9704 (defun markdown-table-backward-cell ()
9705 "Go to the previous cell in the table."
9706 (interactive)
9707 (unless (markdown-table-at-point-p)
9708 (user-error "Not at a table"))
9709 (markdown-table-align)
9710 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9711 (condition-case nil
9712 (progn
9713 (re-search-backward "|" (markdown-table-begin))
9714 (re-search-backward "|" (markdown-table-begin)))
9715 (error (user-error "Cannot move to previous table cell")))
9716 (while (looking-at "|\\([-:]\\|[ \t]*$\\)")
9717 (re-search-backward "|" (markdown-table-begin)))
9718 (when (looking-at "| ?") (goto-char (match-end 0))))
9720 (defun markdown-table-transpose ()
9721 "Transpose table at point.
9722 Horizontal separator lines will be eliminated."
9723 (interactive)
9724 (unless (markdown-table-at-point-p)
9725 (user-error "Not at a table"))
9726 (let* ((table (buffer-substring-no-properties
9727 (markdown-table-begin) (markdown-table-end)))
9728 ;; Convert table to a Lisp structure
9729 (table (delq nil
9730 (mapcar
9731 (lambda (x)
9732 (unless (string-match-p
9733 markdown-table-hline-regexp x)
9734 (markdown--split-string x "\\s-*|\\s-*")))
9735 (markdown--split-string table "[ \t]*\n[ \t]*"))))
9736 (dline_old (markdown-table-get-dline))
9737 (col_old (markdown-table-get-column))
9738 (contents (mapcar (lambda (_)
9739 (let ((tp table))
9740 (mapcar
9741 (lambda (_)
9742 (prog1
9743 (pop (car tp))
9744 (setq tp (cdr tp))))
9745 table)))
9746 (car table))))
9747 (goto-char (markdown-table-begin))
9748 (re-search-forward "|") (backward-char)
9749 (delete-region (point) (markdown-table-end))
9750 (insert (mapconcat
9751 (lambda(x)
9752 (concat "| " (mapconcat 'identity x " | " ) " |\n"))
9753 contents ""))
9754 (markdown-table-goto-dline col_old)
9755 (markdown-table-goto-column dline_old))
9756 (markdown-table-align))
9758 (defun markdown-table-sort-lines (&optional sorting-type)
9759 "Sort table lines according to the column at point.
9761 The position of point indicates the column to be used for
9762 sorting, and the range of lines is the range between the nearest
9763 horizontal separator lines, or the entire table of no such lines
9764 exist. If point is before the first column, user will be prompted
9765 for the sorting column. If there is an active region, the mark
9766 specifies the first line and the sorting column, while point
9767 should be in the last line to be included into the sorting.
9769 The command then prompts for the sorting type which can be
9770 alphabetically or numerically. Sorting in reverse order is also
9771 possible.
9773 If SORTING-TYPE is specified when this function is called from a
9774 Lisp program, no prompting will take place. SORTING-TYPE must be
9775 a character, any of (?a ?A ?n ?N) where the capital letters
9776 indicate that sorting should be done in reverse order."
9777 (interactive)
9778 (unless (markdown-table-at-point-p)
9779 (user-error "Not at a table"))
9780 ;; Set sorting type and column used for sorting
9781 (let ((column (let ((c (markdown-table-get-column)))
9782 (cond ((> c 0) c)
9783 ((called-interactively-p 'any)
9784 (read-number "Use column N for sorting: "))
9785 (t 1))))
9786 (sorting-type
9787 (or sorting-type
9788 (read-char-exclusive
9789 "Sort type: [a]lpha [n]umeric (A/N means reversed): "))))
9790 (save-restriction
9791 ;; Narrow buffer to appropriate sorting area
9792 (if (region-active-p)
9793 (narrow-to-region
9794 (save-excursion
9795 (progn
9796 (goto-char (region-beginning)) (line-beginning-position)))
9797 (save-excursion
9798 (progn
9799 (goto-char (region-end)) (line-end-position))))
9800 (let ((start (markdown-table-begin))
9801 (end (markdown-table-end)))
9802 (narrow-to-region
9803 (save-excursion
9804 (if (re-search-backward
9805 markdown-table-hline-regexp start t)
9806 (line-beginning-position 2)
9807 start))
9808 (if (save-excursion (re-search-forward
9809 markdown-table-hline-regexp end t))
9810 (match-beginning 0)
9811 end))))
9812 ;; Determine arguments for `sort-subr'
9813 (let* ((extract-key-from-cell
9814 (cl-case sorting-type
9815 ((?a ?A) #'markdown--remove-invisible-markup) ;; #'identity)
9816 ((?n ?N) #'string-to-number)
9817 (t (user-error "Invalid sorting type: %c" sorting-type))))
9818 (predicate
9819 (cl-case sorting-type
9820 ((?n ?N) #'<)
9821 ((?a ?A) #'string<))))
9822 ;; Sort selected area
9823 (goto-char (point-min))
9824 (sort-subr (memq sorting-type '(?A ?N))
9825 (lambda ()
9826 (forward-line)
9827 (while (and (not (eobp))
9828 (not (looking-at
9829 markdown-table-dline-regexp)))
9830 (forward-line)))
9831 #'end-of-line
9832 (lambda ()
9833 (funcall extract-key-from-cell
9834 (markdown-table-get-cell column)))
9836 predicate)
9837 (goto-char (point-min))))))
9839 (defun markdown-table-convert-region (begin end &optional separator)
9840 "Convert region from BEGIN to END to table with SEPARATOR.
9842 If every line contains at least one TAB character, the function
9843 assumes that the material is tab separated (TSV). If every line
9844 contains a comma, comma-separated values (CSV) are assumed. If
9845 not, lines are split at whitespace into cells.
9847 You can use a prefix argument to force a specific separator:
9848 \\[universal-argument] once forces CSV, \\[universal-argument]
9849 twice forces TAB, and \\[universal-argument] three times will
9850 prompt for a regular expression to match the separator, and a
9851 numeric argument N indicates that at least N consecutive
9852 spaces, or alternatively a TAB should be used as the separator."
9854 (interactive "r\nP")
9855 (let* ((begin (min begin end)) (end (max begin end)) re)
9856 (goto-char begin) (beginning-of-line 1)
9857 (setq begin (point-marker))
9858 (goto-char end)
9859 (if (bolp) (backward-char 1) (end-of-line 1))
9860 (setq end (point-marker))
9861 (when (equal separator '(64))
9862 (setq separator (read-regexp "Regexp for cell separator: ")))
9863 (unless separator
9864 ;; Get the right cell separator
9865 (goto-char begin)
9866 (setq separator
9867 (cond
9868 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
9869 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
9870 (t 1))))
9871 (goto-char begin)
9872 (if (equal separator '(4))
9873 ;; Parse CSV
9874 (while (< (point) end)
9875 (cond
9876 ((looking-at "^") (insert "| "))
9877 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
9878 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
9879 (replace-match "\\1") (if (looking-at "\"") (insert "\"")))
9880 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
9881 ((looking-at "[ \t]*,") (replace-match " | "))
9882 (t (beginning-of-line 2))))
9883 (setq re
9884 (cond
9885 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
9886 ((equal separator '(16)) "^\\|\t")
9887 ((integerp separator)
9888 (if (< separator 1)
9889 (user-error "Cell separator must contain one or more spaces")
9890 (format "^ *\\| *\t *\\| \\{%d,\\}" separator)))
9891 ((stringp separator) (format "^ *\\|%s" separator))
9892 (t (error "Invalid cell separator"))))
9893 (while (re-search-forward re end t) (replace-match "| " t t)))
9894 (goto-char begin)
9895 (markdown-table-align)))
9898 ;;; ElDoc Support
9900 (defun markdown-eldoc-function ()
9901 "Return a helpful string when appropriate based on context.
9902 * Report URL when point is at a hidden URL.
9903 * Report language name when point is a code block with hidden markup."
9904 (cond
9905 ;; Hidden URL or reference for inline link
9906 ((and (or (thing-at-point-looking-at markdown-regex-link-inline)
9907 (thing-at-point-looking-at markdown-regex-link-reference))
9908 (or markdown-hide-urls markdown-hide-markup))
9909 (let* ((imagep (string-equal (match-string 1) "!"))
9910 (edit-keys (markdown--substitute-command-keys
9911 (if imagep
9912 "\\[markdown-insert-image]"
9913 "\\[markdown-insert-link]")))
9914 (edit-str (propertize edit-keys 'face 'font-lock-constant-face))
9915 (referencep (string-equal (match-string 5) "["))
9916 (object (if referencep "reference" "URL")))
9917 (format "Hidden %s (%s to edit): %s" object edit-str
9918 (if referencep
9919 (concat
9920 (propertize "[" 'face 'markdown-markup-face)
9921 (propertize (match-string-no-properties 6)
9922 'face 'markdown-reference-face)
9923 (propertize "]" 'face 'markdown-markup-face))
9924 (propertize (match-string-no-properties 6)
9925 'face 'markdown-url-face)))))
9926 ;; Hidden language name for fenced code blocks
9927 ((and (markdown-code-block-at-point-p)
9928 (not (get-text-property (point) 'markdown-pre))
9929 markdown-hide-markup)
9930 (let ((lang (save-excursion (markdown-code-block-lang))))
9931 (unless lang (setq lang "[unspecified]"))
9932 (format "Hidden code block language: %s (%s to toggle markup)"
9933 (propertize lang 'face 'markdown-language-keyword-face)
9934 (markdown--substitute-command-keys
9935 "\\[markdown-toggle-markup-hiding]"))))))
9938 ;;; Mode Definition ==========================================================
9940 (defun markdown-show-version ()
9941 "Show the version number in the minibuffer."
9942 (interactive)
9943 (message "markdown-mode, version %s" markdown-mode-version))
9945 (defun markdown-mode-info ()
9946 "Open the `markdown-mode' homepage."
9947 (interactive)
9948 (browse-url "https://jblevins.org/projects/markdown-mode/"))
9950 ;;;###autoload
9951 (define-derived-mode markdown-mode text-mode "Markdown"
9952 "Major mode for editing Markdown files."
9953 ;; Natural Markdown tab width
9954 (setq tab-width 4)
9955 ;; Comments
9956 (setq-local comment-start "<!-- ")
9957 (setq-local comment-end " -->")
9958 (setq-local comment-start-skip "<!--[ \t]*")
9959 (setq-local comment-column 0)
9960 (setq-local comment-auto-fill-only-comments nil)
9961 (setq-local comment-use-syntax t)
9962 ;; Syntax
9963 (add-hook 'syntax-propertize-extend-region-functions
9964 #'markdown-syntax-propertize-extend-region)
9965 (add-hook 'jit-lock-after-change-extend-region-functions
9966 #'markdown-font-lock-extend-region-function t t)
9967 (setq-local syntax-propertize-function #'markdown-syntax-propertize)
9968 ;; Font lock.
9969 (setq-local font-lock-defaults nil)
9970 (setq-local font-lock-multiline t)
9971 (setq-local font-lock-extra-managed-props
9972 (append font-lock-extra-managed-props
9973 '(composition display invisible)))
9974 (if markdown-hide-markup
9975 (add-to-invisibility-spec 'markdown-markup)
9976 (remove-from-invisibility-spec 'markdown-markup))
9977 (setq font-lock-defaults
9978 '(markdown-mode-font-lock-keywords-basic
9979 nil nil nil nil
9980 (font-lock-syntactic-face-function . markdown-syntactic-face)))
9981 ;; Wiki links
9982 (markdown-setup-wiki-link-hooks)
9983 ;; Math mode
9984 (when markdown-enable-math (markdown-toggle-math t))
9985 ;; Add a buffer-local hook to reload after file-local variables are read
9986 (add-hook 'hack-local-variables-hook #'markdown-handle-local-variables nil t)
9987 ;; For imenu support
9988 (setq imenu-create-index-function
9989 (if markdown-nested-imenu-heading-index
9990 #'markdown-imenu-create-nested-index
9991 #'markdown-imenu-create-flat-index))
9992 ;; For menu support in XEmacs
9993 (easy-menu-add markdown-mode-menu markdown-mode-map)
9994 ;; Defun movement
9995 (setq-local beginning-of-defun-function #'markdown-beginning-of-defun)
9996 (setq-local end-of-defun-function #'markdown-end-of-defun)
9997 ;; Paragraph filling
9998 (setq-local fill-paragraph-function #'markdown-fill-paragraph)
9999 (setq-local paragraph-start
10000 ;; Should match start of lines that start or separate paragraphs
10001 (mapconcat #'identity
10003 "\f" ; starts with a literal line-feed
10004 "[ \t\f]*$" ; space-only line
10005 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
10006 "[ \t]*[*+-][ \t]+" ; unordered list item
10007 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
10008 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
10009 "[ \t]*:[ \t]+" ; definition
10010 "^|" ; table or Pandoc line block
10012 "\\|"))
10013 (setq-local paragraph-separate
10014 ;; Should match lines that separate paragraphs without being
10015 ;; part of any paragraph:
10016 (mapconcat #'identity
10017 '("[ \t\f]*$" ; space-only line
10018 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
10019 ;; The following is not ideal, but the Fill customization
10020 ;; options really only handle paragraph-starting prefixes,
10021 ;; not paragraph-ending suffixes:
10022 ".* $" ; line ending in two spaces
10023 "^#+"
10024 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
10025 "\\|"))
10026 (setq-local adaptive-fill-first-line-regexp "\\`[ \t]*[A-Z]?>[ \t]*?\\'")
10027 (setq-local adaptive-fill-regexp "\\s-*")
10028 (setq-local adaptive-fill-function #'markdown-adaptive-fill-function)
10029 (setq-local fill-forward-paragraph-function #'markdown-fill-forward-paragraph)
10030 ;; Outline mode
10031 (setq-local outline-regexp markdown-regex-header)
10032 (setq-local outline-level #'markdown-outline-level)
10033 ;; Cause use of ellipses for invisible text.
10034 (add-to-invisibility-spec '(outline . t))
10035 ;; ElDoc support
10036 (if (eval-when-compile (fboundp 'add-function))
10037 (add-function :before-until (local 'eldoc-documentation-function)
10038 #'markdown-eldoc-function)
10039 (setq-local eldoc-documentation-function #'markdown-eldoc-function))
10040 ;; Inhibiting line-breaking:
10041 ;; Separating out each condition into a separate function so that users can
10042 ;; override if desired (with remove-hook)
10043 (add-hook 'fill-nobreak-predicate
10044 #'markdown-line-is-reference-definition-p nil t)
10045 (add-hook 'fill-nobreak-predicate
10046 #'markdown-pipe-at-bol-p nil t)
10048 ;; Indentation
10049 (setq-local indent-line-function markdown-indent-function)
10051 ;; Flyspell
10052 (setq-local flyspell-generic-check-word-predicate
10053 #'markdown-flyspell-check-word-p)
10055 ;; Electric quoting
10056 (add-hook 'electric-quote-inhibit-functions
10057 #'markdown--inhibit-electric-quote nil :local)
10059 ;; Backwards compatibility with markdown-css-path
10060 (when (boundp 'markdown-css-path)
10061 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
10062 (add-to-list 'markdown-css-paths markdown-css-path))
10064 ;; Prepare hooks for XEmacs compatibility
10065 (when (featurep 'xemacs)
10066 (make-local-hook 'after-change-functions)
10067 (make-local-hook 'font-lock-extend-region-functions)
10068 (make-local-hook 'window-configuration-change-hook))
10070 ;; Make checkboxes buttons
10071 (when markdown-make-gfm-checkboxes-buttons
10072 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
10073 (add-hook 'after-change-functions #'markdown-gfm-checkbox-after-change-function t t)
10074 (add-hook 'change-major-mode-hook #'markdown-remove-gfm-checkbox-overlays t t))
10076 ;; edit-indirect
10077 (add-hook 'edit-indirect-after-commit-functions
10078 #'markdown--edit-indirect-after-commit-function
10079 nil 'local)
10081 ;; Marginalized headings
10082 (when markdown-marginalize-headers
10083 (add-hook 'window-configuration-change-hook
10084 #'markdown-marginalize-update-current nil t))
10086 ;; add live preview export hook
10087 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
10088 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
10090 ;;;###autoload
10091 (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode) t)
10092 ;;;###autoload
10093 (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode) t)
10096 ;;; GitHub Flavored Markdown Mode ============================================
10098 (defvar gfm-mode-hook nil
10099 "Hook run when entering GFM mode.")
10101 (defvar gfm-font-lock-keywords
10102 ;; Basic Markdown features (excluding possibly overridden ones)
10103 markdown-mode-font-lock-keywords-basic
10104 "Default highlighting expressions for GitHub Flavored Markdown mode.")
10106 ;;;###autoload
10107 (define-derived-mode gfm-mode markdown-mode "GFM"
10108 "Major mode for editing GitHub Flavored Markdown files."
10109 (setq markdown-link-space-sub-char "-")
10110 (setq markdown-wiki-link-search-subdirectories t)
10111 (setq-local font-lock-defaults '(gfm-font-lock-keywords))
10112 (setq-local markdown-table-at-point-p-function 'gfm--table-at-point-p)
10113 ;; do the initial link fontification
10114 (markdown-gfm-parse-buffer-for-languages))
10117 ;;; Live Preview Mode ============================================
10118 (define-minor-mode markdown-live-preview-mode
10119 "Toggle native previewing on save for a specific markdown file."
10120 :lighter " MD-Preview"
10121 (if markdown-live-preview-mode
10122 (if (markdown-live-preview-get-filename)
10123 (markdown-display-buffer-other-window (markdown-live-preview-export))
10124 (markdown-live-preview-mode -1)
10125 (user-error "Buffer %s does not visit a file" (current-buffer)))
10126 (markdown-live-preview-remove)))
10129 (provide 'markdown-mode)
10131 ;; Local Variables:
10132 ;; indent-tabs-mode: nil
10133 ;; coding: utf-8
10134 ;; End:
10135 ;;; markdown-mode.el ends here