Make number of spaces after code fence customizable
[markdown-mode.git] / markdown-mode.el
blobb4310b798b77b6cc9ced9313f122103e98b47b00
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.3-dev
10 ;; Package-Requires: ((emacs "24") (cl-lib "0.5"))
11 ;; Keywords: Markdown, GitHub Flavored Markdown, itex
12 ;; URL: http://jblevins.org/projects/markdown-mode/
14 ;; This file is not part of GNU Emacs.
16 ;; This program is free software; you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 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.2, released on
33 ;; May 26, 2017. See the [release notes][] for details.
34 ;; markdown-mode is free software, licensed under the GNU GPL v2.
36 ;; ![Markdown Mode Screenshot](http://jblevins.org/projects/markdown-mode/screenshots/20160108-001.png)
38 ;; [Markdown]: http://daringfireball.net/projects/markdown/
39 ;; [release notes]: http://jblevins.org/projects/markdown-mode/rev-2-2
41 ;;; Documentation:
43 ;; <a href="https://leanpub.com/markdown-mode"><img src="http://jblevins.org/projects/markdown-mode/guide-v2.2.png" align="right" height="350" width="252"></a>
45 ;; Documentation for Markdown Mode is available below, but Emacs is also
46 ;; a self-documenting editor. That means that the source code itself
47 ;; contains additional documentation: each function has its own docstring
48 ;; available via `C-h f` (`describe-function'), individual keybindings
49 ;; can be investigated with `C-h k` (`describe-key'), and a complete list
50 ;; of keybindings is available using `C-h m` (`describe-mode').
52 ;; Additionally, to celebrate Markdown Mode's 10th birthday the package
53 ;; creator is writing a [Guide to Markdown Mode for Emacs][guide]. This
54 ;; ebook will supplement the existing documentation with in-depth
55 ;; discussion of advanced movement and editing commands, configuration
56 ;; examples, tips and tricks, and a survey of other packages that work
57 ;; with Markdown Mode. It will be [published at Leanpub][guide] and
58 ;; possibly available through other channels. Please visit
59 ;; the [book homepage][guide] to sign up to be notified when it is ready
60 ;; and to help determine the price.
62 ;; [guide]: https://leanpub.com/markdown-mode
64 ;;; Installation:
66 ;; The recommended way to install markdown-mode is to install the package
67 ;; from [MELPA Stable](https://stable.melpa.org/#/markdown-mode)
68 ;; using `package.el'. First, configure `package.el' and the MELPA Stable
69 ;; repository by adding the following to your `.emacs', `init.el',
70 ;; or equivalent startup file:
72 ;; ``` Lisp
73 ;; (require 'package)
74 ;; (add-to-list 'package-archives
75 ;; '("melpa-stable" . "https://stable.melpa.org/packages/"))
76 ;; (package-initialize)
77 ;; ```
79 ;; Then, after restarting Emacs or evaluating the above statements, issue
80 ;; the following command: `M-x package-install RET markdown-mode RET`.
81 ;; When installed this way, the major modes `markdown-mode' and `gfm-mode'
82 ;; will be autoloaded and `markdown-mode' will be used for file names
83 ;; ending in either `.md` or `.markdown`.
85 ;; Alternatively, if you manage loading packages with [use-package][]
86 ;; then you can automatically install and configure `markdown-mode' by
87 ;; adding a declaration such as this one to your init file (as an
88 ;; example; adjust settings as desired):
90 ;; ``` Lisp
91 ;; (use-package markdown-mode
92 ;; :ensure t
93 ;; :commands (markdown-mode gfm-mode)
94 ;; :mode (("README\\.md\\'" . gfm-mode)
95 ;; ("\\.md\\'" . markdown-mode)
96 ;; ("\\.markdown\\'" . markdown-mode))
97 ;; :init (setq markdown-command "multimarkdown"))
98 ;; ```
100 ;; [MELPA Stable]: http://stable.melpa.org/
101 ;; [use-package]: https://github.com/jwiegley/use-package
103 ;; **Direct Download**
105 ;; Alternatively you can manually download and install markdown-mode.
106 ;; First, download the [latest stable version][markdown-mode.el] and
107 ;; save the file where Emacs can find it (i.e., a directory in your
108 ;; `load-path'). You can then configure `markdown-mode' and `gfm-mode'
109 ;; to load automatically by adding the following to your init file:
111 ;; ``` Lisp
112 ;; (autoload 'markdown-mode "markdown-mode"
113 ;; "Major mode for editing Markdown files" t)
114 ;; (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode))
115 ;; (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode))
117 ;; (autoload 'gfm-mode "markdown-mode"
118 ;; "Major mode for editing GitHub Flavored Markdown files" t)
119 ;; (add-to-list 'auto-mode-alist '("README\\.md\\'" . gfm-mode))
120 ;; ```
122 ;; [markdown-mode.el]: http://jblevins.org/projects/markdown-mode/markdown-mode.el
124 ;; **Development Version**
126 ;; To follow or contribute to markdown-mode development, you can
127 ;; browse or clone the Git repository
128 ;; [on GitHub](https://github.com/jrblevin/markdown-mode):
130 ;; ```
131 ;; git clone https://github.com/jrblevin/markdown-mode.git
132 ;; ```
134 ;; If you prefer to install and use the development version, which may
135 ;; become unstable at some times, you can either clone the Git
136 ;; repository as above or install markdown-mode from
137 ;; [MELPA](https://melpa.org/#/markdown-mode).
139 ;; If you clone the repository directly, then make sure that Emacs can
140 ;; find it by adding the following line to your startup file:
142 ;; ``` Lisp
143 ;; (add-to-list 'load-path "/path/to/markdown-mode/repository")
144 ;; ```
146 ;; **Packaged Installation**
148 ;; markdown-mode is also available in several package managers. You
149 ;; may want to confirm that the package you install contains the
150 ;; latest stable version first (and please notify the package
151 ;; maintainer if not).
153 ;; * Debian Linux: [elpa-markdown-mode][] and [emacs-goodies-el][]
154 ;; * Ubuntu Linux: [elpa-markdown-mode][elpa-ubuntu] and [emacs-goodies-el][emacs-goodies-el-ubuntu]
155 ;; * RedHat and Fedora Linux: [emacs-goodies][]
156 ;; * NetBSD: [textproc/markdown-mode][]
157 ;; * MacPorts: [markdown-mode.el][macports-package] ([pending][macports-ticket])
158 ;; * FreeBSD: [textproc/markdown-mode.el][freebsd-port]
160 ;; [elpa-markdown-mode]: https://packages.debian.org/sid/lisp/elpa-markdown-mode
161 ;; [elpa-ubuntu]: http://packages.ubuntu.com/search?keywords=elpa-markdown-mode
162 ;; [emacs-goodies-el]: http://packages.debian.org/emacs-goodies-el
163 ;; [emacs-goodies-el-ubuntu]: http://packages.ubuntu.com/search?keywords=emacs-goodies-el
164 ;; [emacs-goodies]: https://apps.fedoraproject.org/packages/emacs-goodies
165 ;; [textproc/markdown-mode]: http://pkgsrc.se/textproc/markdown-mode
166 ;; [macports-package]: https://trac.macports.org/browser/trunk/dports/editors/markdown-mode.el/Portfile
167 ;; [macports-ticket]: http://trac.macports.org/ticket/35716
168 ;; [freebsd-port]: http://svnweb.freebsd.org/ports/head/textproc/markdown-mode.el
170 ;; **Dependencies**
172 ;; To enable editing of code blocks in indirect buffers using `C-c '`,
173 ;; you will need to install the [`edit-indirect'][ei] package.
175 ;; [ei]: https://github.com/Fanael/edit-indirect/
177 ;;; Usage:
179 ;; Keybindings are grouped by prefixes based on their function. For
180 ;; example, the commands for styling text are grouped under `C-c C-s`
181 ;; and commands dealing with headings begin with `C-c C-t` (mnemonic:
182 ;; titling). The primary commands in each group will are described
183 ;; below. You can obtain a list of all keybindings by pressing `C-c
184 ;; C-h`. Movement and shifting commands tend to be associated with
185 ;; paired delimiters such as `M-{` and `M-}` or `C-c <` and `C-c >`.
186 ;; Outline navigation keybindings the same as in `org-mode'. Finally,
187 ;; commands for running Markdown or doing maintenance on an open file
188 ;; are grouped under the `C-c C-c` prefix. The most commonly used
189 ;; commands are described below. You can obtain a list of all
190 ;; keybindings by pressing `C-c C-h`.
192 ;; * Links and Images: `C-c C-l` and `C-c C-i`
194 ;; `C-c C-l` (`markdown-insert-link`) is a general command for
195 ;; inserting new link markup or editing existing link markup. This
196 ;; is especially useful when markup or URL hiding is enabled, so
197 ;; that URLs can't easily be edited directly. This command can be
198 ;; used to insert links of any form: either inline links,
199 ;; reference links, or plain URLs in angle brackets. The URL or
200 ;; `[reference]` label, link text, and optional title are entered
201 ;; through a series of interactive prompts. The type of link is
202 ;; determined by which values are provided:
204 ;; * If both a URL and link text are given, insert an inline link:
205 ;; `[text](url)`.
206 ;; * If both a `[reference]` label and link text are given, insert
207 ;; a reference link: `[text][reference]`.
208 ;; * If only link text is given, insert an implicit reference link:
209 ;; `[text][]`.
210 ;; * If only a URL is given, insert a plain URL link:
211 ;; `<url>`.
213 ;; Similarly, `C-c C-i` (`markdown-insert-image`) is a general
214 ;; command for inserting or editing image markup. As with the link
215 ;; insertion command, through a series interactive prompts you can
216 ;; insert either an inline or reference image:
218 ;; * If both a URL and alt text are given, insert an inline
219 ;; image: `![alt text](url)`.
220 ;; * If both a `[reference]` label and alt text are given,
221 ;; insert a reference link: `![alt text][reference]`.
223 ;; If there is an existing link or image at the point, these
224 ;; command will edit the existing markup rather than inserting new
225 ;; markup. Otherwise, if there is an active region, these commands
226 ;; use the region as either the default URL (if it seems to be a
227 ;; URL) or link text value otherwise. In that case, the region
228 ;; will be deleted and replaced by the link.
230 ;; Note that these functions can be used to convert links and
231 ;; images from one type to another (inline, reference, or plain
232 ;; URL) by selectively adding or removing properties via the
233 ;; interactive prompts.
235 ;; If a reference label is given that is not yet defined, you
236 ;; will be prompted for the URL and optional title and the
237 ;; reference will be inserted according to the value of
238 ;; `markdown-reference-location'. If a title is given, it will be
239 ;; added to the end of the reference definition and will be used
240 ;; to populate the title attribute when converted to HTML.
242 ;; Local images associated with image links may be displayed
243 ;; inline in the buffer by pressing `C-c C-x C-i`
244 ;; (`markdown-toggle-inline-images'). This is a toggle command, so
245 ;; pressing this once again will remove inline images.
247 ;; * Text Styles: `C-c C-s`
249 ;; `C-c C-s i` inserts markup to make a region or word italic. If
250 ;; there is an active region, make the region italic. If the point
251 ;; is at a non-italic word, make the word italic. If the point is
252 ;; at an italic word or phrase, remove the italic markup.
253 ;; Otherwise, simply insert italic delimiters and place the cursor
254 ;; in between them. Similarly, use `C-c C-s b` for bold, `C-c C-s c`
255 ;; for inline code, and `C-c C-s k` for inserting `<kbd>` tags.
257 ;; `C-c C-s q` inserts a blockquote using the active region, if
258 ;; any, or starts a new blockquote. `C-c C-s Q` is a variation
259 ;; which always operates on the region, regardless of whether it
260 ;; is active or not (i.e., when `transient-mark-mode` is off but
261 ;; the mark is set). The appropriate amount of indentation, if
262 ;; any, is calculated automatically given the surrounding context,
263 ;; but may be adjusted later using the region indentation
264 ;; commands.
266 ;; `C-c C-s p` behaves similarly for inserting preformatted code
267 ;; blocks (with `C-c C-s P` being the region-only counterpart)
268 ;; and `C-c C-s C` inserts a GFM style backquote fenced code block.
270 ;; * Headings: `C-c C-s`
272 ;; To insert or replace headings, there are two options. You can
273 ;; insert a specific level heading directly or you can have
274 ;; `markdown-mode' determine the level for you based on the previous
275 ;; heading. As with the other markup commands, the heading
276 ;; insertion commands use the text in the active region, if any,
277 ;; as the heading text. Otherwise, if the current line is not
278 ;; blank, they use the text on the current line. Finally, the
279 ;; setext commands will prompt for heading text if there is no
280 ;; active region and the current line is blank.
282 ;; `C-c C-s h` inserts a heading with automatically chosen type and
283 ;; level (both determined by the previous heading). `C-c C-s H`
284 ;; behaves similarly, but uses setext (underlined) headings when
285 ;; possible, still calculating the level automatically.
286 ;; In cases where the automatically-determined level is not what
287 ;; you intended, the level can be quickly promoted or demoted
288 ;; (as described below). Alternatively, a `C-u` prefix can be
289 ;; given to insert a heading _promoted_ (lower number) by one
290 ;; level or a `C-u C-u` prefix can be given to insert a heading
291 ;; demoted (higher number) by one level.
293 ;; To insert a heading of a specific level and type, use `C-c C-s 1`
294 ;; through `C-c C-s 6` for atx (hash mark) headings and `C-c C-s !` or
295 ;; `C-c C-s @` for setext headings of level one or two, respectively.
296 ;; Note that `!` is `S-1` and `@` is `S-2`.
298 ;; If the point is at a heading, these commands will replace the
299 ;; existing markup in order to update the level and/or type of the
300 ;; heading. To remove the markup of the heading at the point,
301 ;; press `C-c C-k` to kill the heading and press `C-y` to yank the
302 ;; heading text back into the buffer.
304 ;; * Horizontal Rules: `C-c C-s -`
306 ;; `C-c C-s -` inserts a horizontal rule. By default, insert the
307 ;; first string in the list `markdown-hr-strings' (the most
308 ;; prominent rule). With a `C-u` prefix, insert the last string.
309 ;; With a numeric prefix `N`, insert the string in position `N`
310 ;; (counting from 1).
312 ;; * Footnotes: `C-c C-s f`
314 ;; `C-c C-s f` inserts a footnote marker at the point, inserts a
315 ;; footnote definition below, and positions the point for
316 ;; inserting the footnote text. Note that footnotes are an
317 ;; extension to Markdown and are not supported by all processors.
319 ;; * Wiki Links: `C-c C-s w`
321 ;; `C-c C-s w` inserts a wiki link of the form `[[WikiLink]]`. If
322 ;; there is an active region, use the region as the link text. If the
323 ;; point is at a word, use the word as the link text. If there is
324 ;; no active region and the point is not at word, simply insert
325 ;; link markup. Note that wiki links are an extension to Markdown
326 ;; and are not supported by all processors.
328 ;; * Markdown and Maintenance Commands: `C-c C-c`
330 ;; *Compile:* `C-c C-c m` will run Markdown on the current buffer
331 ;; and show the output in another buffer. *Preview*: `C-c C-c p`
332 ;; runs Markdown on the current buffer and previews, stores the
333 ;; output in a temporary file, and displays the file in a browser.
334 ;; *Export:* `C-c C-c e` will run Markdown on the current buffer
335 ;; and save the result in the file `basename.html`, where
336 ;; `basename` is the name of the Markdown file with the extension
337 ;; removed. *Export and View:* press `C-c C-c v` to export the
338 ;; file and view it in a browser. *Open:* `C-c C-c o` will open
339 ;; the Markdown source file directly using `markdown-open-command'.
340 ;; *Live Export*: Press `C-c C-c l` to turn on
341 ;; `markdown-live-preview-mode' to view the exported output
342 ;; side-by-side with the source Markdown. **For all export commands,
343 ;; the output file will be overwritten without notice.**
344 ;; `markdown-live-preview-window-function' can be customized to open
345 ;; in a browser other than `eww'. If you want to force the
346 ;; preview window to appear at the bottom or right, you can
347 ;; customize `markdown-split-window-direction`.
349 ;; To summarize:
351 ;; - `C-c C-c m`: `markdown-command' > `*markdown-output*` buffer.
352 ;; - `C-c C-c p`: `markdown-command' > temporary file > browser.
353 ;; - `C-c C-c e`: `markdown-command' > `basename.html`.
354 ;; - `C-c C-c v`: `markdown-command' > `basename.html` > browser.
355 ;; - `C-c C-c w`: `markdown-command' > kill ring.
356 ;; - `C-c C-c o`: `markdown-open-command'.
357 ;; - `C-c C-c l`: `markdown-live-preview-mode' > `*eww*` buffer.
359 ;; `C-c C-c c` will check for undefined references. If there are
360 ;; any, a small buffer will open with a list of undefined
361 ;; references and the line numbers on which they appear. In Emacs
362 ;; 22 and greater, selecting a reference from this list and
363 ;; pressing `RET` will insert an empty reference definition at the
364 ;; end of the buffer. Similarly, selecting the line number will
365 ;; jump to the corresponding line.
367 ;; `C-c C-c n` renumbers any ordered lists in the buffer that are
368 ;; out of sequence.
370 ;; `C-c C-c ]` completes all headings and normalizes all horizontal
371 ;; rules in the buffer.
373 ;; * Following Links: `C-c C-o`
375 ;; Press `C-c C-o` when the point is on an inline or reference
376 ;; link to open the URL in a browser. When the point is at a
377 ;; wiki link, open it in another buffer (in the current window,
378 ;; or in the other window with the `C-u` prefix). Use `M-p` and
379 ;; `M-n` to quickly jump to the previous or next link of any type.
381 ;; * Doing Things: `C-c C-d`
383 ;; Use `C-c C-d` to do something sensible with the object at the point:
385 ;; - Jumps between reference links and reference definitions.
386 ;; If more than one link uses the same reference label, a
387 ;; window will be shown containing clickable buttons for
388 ;; jumping to each link. Pressing `TAB` or `S-TAB` cycles
389 ;; between buttons in this window.
390 ;; - Jumps between footnote markers and footnote text.
391 ;; - Toggles the completion status of GFM task list items
392 ;; (checkboxes).
394 ;; * Promotion and Demotion: `C-c C--` and `C-c C-=`
396 ;; Headings, horizontal rules, and list items can be promoted and
397 ;; demoted, as well as bold and italic text. For headings,
398 ;; "promotion" means *decreasing* the level (i.e., moving from
399 ;; `<h2>` to `<h1>`) while "demotion" means *increasing* the
400 ;; level. For horizontal rules, promotion and demotion means
401 ;; moving backward or forward through the list of rule strings in
402 ;; `markdown-hr-strings'. For bold and italic text, promotion and
403 ;; demotion means changing the markup from underscores to asterisks.
404 ;; Press `C-c C--` or `C-c <left>` to promote the element at the point
405 ;; if possible.
407 ;; To remember these commands, note that `-` is for decreasing the
408 ;; level (promoting), and `=` (on the same key as `+`) is for
409 ;; increasing the level (demoting). Similarly, the left and right
410 ;; arrow keys indicate the direction that the atx heading markup
411 ;; is moving in when promoting or demoting.
413 ;; * Completion: `C-c C-]`
415 ;; Complete markup is in normalized form, which means, for
416 ;; example, that the underline portion of a setext header is the
417 ;; same length as the heading text, or that the number of leading
418 ;; and trailing hash marks of an atx header are equal and that
419 ;; there is no extra whitespace in the header text. `C-c C-]`
420 ;; completes the markup at the point, if it is determined to be
421 ;; incomplete.
423 ;; * Editing Lists: `M-RET`, `C-c <up>`, `C-c <down>`, `C-c <left>`, and `C-c <right>`
425 ;; New list items can be inserted with `M-RET` or `C-c C-j`. This
426 ;; command determines the appropriate marker (one of the possible
427 ;; unordered list markers or the next number in sequence for an
428 ;; ordered list) and indentation level by examining nearby list
429 ;; items. If there is no list before or after the point, start a
430 ;; new list. As with heading insertion, you may prefix this
431 ;; command by `C-u` to decrease the indentation by one level.
432 ;; Prefix this command by `C-u C-u` to increase the indentation by
433 ;; one level.
435 ;; Existing list items (and their nested sub-items) can be moved
436 ;; up or down with `C-c <up>` or `C-c <down>` and indented or
437 ;; outdented with `C-c <right>` or `C-c <left>`.
439 ;; * Editing Subtrees: `C-c <up>`, `C-c <down>`, `C-c <left>`, and `C-c <right>`
441 ;; Entire subtrees of ATX headings can be promoted and demoted
442 ;; with `C-c <left>` and `C-c <right>`, which are the same keybindings
443 ;; used for promotion and demotion of list items. If the point is in
444 ;; a list item, the operate on the list item. Otherwise, they operate
445 ;; on the current heading subtree. Similarly, subtrees can be
446 ;; moved up and down with `C-c <up>` and `C-c <down>`.
448 ;; These commands currently do not work properly if there are
449 ;; Setext headings in the affected region.
451 ;; Please note the following "boundary" behavior for promotion and
452 ;; demotion. Any level-six headings will not be demoted further
453 ;; (i.e., they remain at level six, since Markdown and HTML define
454 ;; only six levels) and any level-one headings will promoted away
455 ;; entirely (i.e., heading markup will be removed, since a
456 ;; level-zero heading is not defined).
458 ;; * Shifting the Region: `C-c <` and `C-c >`
460 ;; Text in the region can be indented or outdented as a group using
461 ;; `C-c >` to indent to the next indentation point (calculated in
462 ;; the current context), and `C-c <` to outdent to the previous
463 ;; indentation point. These keybindings are the same as those for
464 ;; similar commands in `python-mode'.
466 ;; * Killing Elements: `C-c C-k`
468 ;; Press `C-c C-k` to kill the thing at point and add important
469 ;; text, without markup, to the kill ring. Possible things to
470 ;; kill include (roughly in order of precedece): inline code,
471 ;; headings, horizonal rules, links (add link text to kill ring),
472 ;; images (add alt text to kill ring), angle URIs, email
473 ;; addresses, bold, italics, reference definitions (add URI to
474 ;; kill ring), footnote markers and text (kill both marker and
475 ;; text, add text to kill ring), and list items.
477 ;; * Outline Navigation: `C-c C-n`, `C-c C-p`, `C-c C-f`, `C-c C-b`, and `C-c C-u`
479 ;; These keys are used for hierarchical navigation in lists and
480 ;; headings. When the point is in a list, they move between list
481 ;; items. Otherwise, they move between headings. Use `C-c C-n` and
482 ;; `C-c C-p` to move between the next and previous visible
483 ;; headings or list items of any level. Similarly, `C-c C-f` and
484 ;; `C-c C-b` move to the next and previous visible headings or
485 ;; list items at the same level as the one at the point. Finally,
486 ;; `C-c C-u` will move up to the parent heading or list item.
488 ;; * Movement by Markdown paragraph: `M-{`, `M-}`, and `M-h`
490 ;; Paragraphs in `markdown-mode' are regular paragraphs,
491 ;; paragraphs inside blockquotes, individual list items, headings,
492 ;; etc. These keys are usually bound to `forward-paragraph' and
493 ;; `backward-paragraph', but the built-in Emacs functions are
494 ;; based on simple regular expressions that fail in Markdown
495 ;; files. Instead, they are bound to `markdown-forward-paragraph'
496 ;; and `markdown-backward-paragraph'. To mark a paragraph,
497 ;; you can use `M-h` (`markdown-mark-paragraph').
499 ;; * Movement by Markdown block: `C-M-{`, `C-M-}`, and `C-c M-h`
501 ;; Markdown blocks are regular paragraphs in many cases, but
502 ;; contain many paragraphs in other cases: blocks are considered
503 ;; to be entire lists, entire code blocks, and entire blockquotes.
504 ;; To move backward one block use `C-M-{`
505 ;; (`markdown-beginning-block`) and to move forward use `C-M-}`
506 ;; (`markdown-end-of-block`). To mark a block, use `C-c M-h`
507 ;; (`markdown-mark-block`).
509 ;; * Movement by Defuns: `C-M-a`, `C-M-e`, and `C-M-h`
511 ;; The usual Emacs commands can be used to move by defuns
512 ;; (top-level major definitions). In markdown-mode, a defun is a
513 ;; section. As usual, `C-M-a` will move the point to the
514 ;; beginning of the current or preceding defun, `C-M-e` will move
515 ;; to the end of the current or following defun, and `C-M-h` will
516 ;; put the region around the entire defun.
518 ;; * Miscellaneous Commands:
520 ;; When the [`edit-indirect'][ei] package is installed, `C-c '`
521 ;; (`markdown-edit-code-block`) can be used to edit a code block
522 ;; in an indirect buffer in the native major mode. Press `C-c C-c`
523 ;; to commit changes and return or `C-c C-k` to cancel.
525 ;; As noted, many of the commands above behave differently depending
526 ;; on whether Transient Mark mode is enabled or not. When it makes
527 ;; sense, if Transient Mark mode is on and the region is active, the
528 ;; command applies to the text in the region (e.g., `C-c C-s b` makes the
529 ;; region bold). For users who prefer to work outside of Transient
530 ;; Mark mode, since Emacs 22 it can be enabled temporarily by pressing
531 ;; `C-SPC C-SPC`. When this is not the case, many commands then
532 ;; proceed to look work with the word or line at the point.
534 ;; When applicable, commands that specifically act on the region even
535 ;; outside of Transient Mark mode have the same keybinding as their
536 ;; standard counterpart, but the letter is uppercase. For example,
537 ;; `markdown-insert-blockquote' is bound to `C-c C-s q` and only acts on
538 ;; the region in Transient Mark mode while `markdown-blockquote-region'
539 ;; is bound to `C-c C-s Q` and always applies to the region (when nonempty).
541 ;; Note that these region-specific functions are useful in many
542 ;; cases where it may not be obvious. For example, yanking text from
543 ;; the kill ring sets the mark at the beginning of the yanked text
544 ;; and moves the point to the end. Therefore, the (inactive) region
545 ;; contains the yanked text. So, `C-y` followed by `C-c C-s Q` will
546 ;; yank text and turn it into a blockquote.
548 ;; markdown-mode attempts to be flexible in how it handles
549 ;; indentation. When you press `TAB` repeatedly, the point will cycle
550 ;; through several possible indentation levels corresponding to things
551 ;; you might have in mind when you press `RET` at the end of a line or
552 ;; `TAB`. For example, you may want to start a new list item,
553 ;; continue a list item with hanging indentation, indent for a nested
554 ;; pre block, and so on. Outdenting is handled similarly when backspace
555 ;; is pressed at the beginning of the non-whitespace portion of a line.
557 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
558 ;; visibility cycling for atx- or hash-style headings. There are two
559 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
560 ;; the table of contents view (headings only), outline view (top-level
561 ;; headings only), and the full document view. Pressing `TAB` while the
562 ;; point is at a heading will cycle through levels of visibility for the
563 ;; subtree: completely folded, visible children, and fully visible.
564 ;; Note that mixing hash and underline style headings will give undesired
565 ;; results.
567 ;;; Customization:
569 ;; Although no configuration is *necessary* there are a few things
570 ;; that can be customized. The `M-x customize-mode` command
571 ;; provides an interface to all of the possible customizations:
573 ;; * `markdown-command' - the command used to run Markdown (default:
574 ;; `markdown`). This variable may be customized to pass
575 ;; command-line options to your Markdown processor of choice.
577 ;; * `markdown-command-needs-filename' - set to `t' if
578 ;; `markdown-command' does not accept standard input (default:
579 ;; `nil'). When `nil', `markdown-mode' will pass the Markdown
580 ;; content to `markdown-command' using standard input (`stdin`).
581 ;; When set to `t', `markdown-mode' will pass the name of the file
582 ;; as the final command-line argument to `markdown-command'. Note
583 ;; that in the latter case, you will only be able to run
584 ;; `markdown-command' from buffers which are visiting a file.
586 ;; * `markdown-open-command' - the command used for calling a standalone
587 ;; Markdown previewer which is capable of opening Markdown source files
588 ;; directly (default: `nil'). This command will be called
589 ;; with a single argument, the filename of the current buffer.
590 ;; A representative program is the Mac app [Marked 2][], a
591 ;; live-updating Markdown previewer which can be [called from a
592 ;; simple shell script](http://jblevins.org/log/marked-2-command).
594 ;; * `markdown-hr-strings' - list of strings to use when inserting
595 ;; horizontal rules. Different strings will not be distinguished
596 ;; when converted to HTML--they will all be converted to
597 ;; `<hr/>`--but they may add visual distinction and style to plain
598 ;; text documents. To maintain some notion of promotion and
599 ;; demotion, keep these sorted from largest to smallest.
601 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
602 ;; underscores when inserting bold text instead of two asterisks
603 ;; (default: `nil').
605 ;; * `markdown-italic-underscore' - set to a non-nil value to use
606 ;; underscores when inserting italic text instead of asterisks
607 ;; (default: `nil').
609 ;; * `markdown-asymmetric-header' - set to a non-nil value to use
610 ;; asymmetric header styling, placing header characters only on
611 ;; the left of headers (default: `nil').
613 ;; * `markdown-header-scaling' - set to a non-nil value to use
614 ;; a variable-pitch font for headings where the size corresponds
615 ;; to the level of the heading (default: `nil').
617 ;; * `markdown-header-scaling-values' - list of scaling values,
618 ;; relative to baseline, for headers of levels one through six,
619 ;; used when `markdown-header-scaling' is non-nil
620 ;; (default: `(2.0 1.7 1.4 1.1 1.0 1.0)`).
622 ;; * `markdown-list-indent-width' - depth of indentation for lists
623 ;; when inserting, promoting, and demoting list items (default: 4).
625 ;; * `markdown-indent-function' - the function to use for automatic
626 ;; indentation (default: `markdown-indent-line').
628 ;; * `markdown-indent-on-enter' - Set to a non-nil value to
629 ;; automatically indent new lines when `RET' is pressed.
630 ;; Set to `indent-and-new-item' to additionally continue lists
631 ;; when `RET' is pressed (default: `t').
633 ;; * `markdown-enable-wiki-links' - syntax highlighting for wiki
634 ;; links (default: `nil'). Set this to a non-nil value to turn on
635 ;; wiki link support by default. Wiki link support can be toggled
636 ;; later using the function `markdown-toggle-wiki-links'."
638 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
639 ;; treat aliased wiki links like `[[link text|PageName]]`
640 ;; (default: `t'). When set to nil, they will be treated as
641 ;; `[[PageName|link text]]'.
643 ;; * `markdown-uri-types' - a list of protocol schemes (e.g., "http")
644 ;; for URIs that `markdown-mode' should highlight.
646 ;; * `markdown-enable-math' - font lock for inline and display LaTeX
647 ;; math expressions (default: `nil'). Set this to `t' to turn on
648 ;; math support by default. Math support can be toggled
649 ;; interactively later using `C-c C-x C-e`
650 ;; (`markdown-toggle-math').
652 ;; * `markdown-css-paths' - CSS files to link to in XHTML output
653 ;; (default: `nil`).
655 ;; * `markdown-content-type' - when set to a nonempty string, an
656 ;; `http-equiv` attribute will be included in the XHTML `<head>`
657 ;; block (default: `""`). If needed, the suggested values are
658 ;; `application/xhtml+xml` or `text/html`. See also:
659 ;; `markdown-coding-system'.
661 ;; * `markdown-coding-system' - used for specifying the character
662 ;; set identifier in the `http-equiv` attribute when included
663 ;; (default: `nil'). See `markdown-content-type', which must
664 ;; be set before this variable has any effect. When set to `nil',
665 ;; `buffer-file-coding-system' will be used to automatically
666 ;; determine the coding system string (falling back to
667 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
668 ;; and `iso-latin-1'.
670 ;; * `markdown-xhtml-header-content' - additional content to include
671 ;; in the XHTML `<head>` block (default: `""`).
673 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
674 ;; `markdown-mode' uses to determine whether the output of
675 ;; `markdown-command' is a standalone XHTML document or an XHTML
676 ;; fragment (default: `"^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"`). If
677 ;; this regular expression not matched in the first five lines of
678 ;; output, `markdown-mode' assumes the output is a fragment and
679 ;; adds a header and footer.
681 ;; * `markdown-link-space-sub-char' - a character to replace spaces
682 ;; when mapping wiki links to filenames (default: `"_"`).
683 ;; For example, use an underscore for compatibility with the
684 ;; Python Markdown WikiLinks extension. In `gfm-mode', this is
685 ;; set to `"-"` to conform with GitHub wiki links.
687 ;; * `markdown-reference-location' - where to insert reference
688 ;; definitions (default: `header`). The possible locations are
689 ;; the end of the document (`end`), after the current block
690 ;; (`immediately`), the end of the current subtree (`subtree'),
691 ;; or before the next header (`header`).
693 ;; * `markdown-footnote-location' - where to insert footnote text
694 ;; (default: `end`). The set of location options is the same as
695 ;; for `markdown-reference-location'.
697 ;; * `markdown-nested-imenu-heading-index' - Use nested imenu
698 ;; heading instead of a flat index (default: `t'). A nested
699 ;; index may provide more natural browsing from the menu, but a
700 ;; flat list may allow for faster keyboard navigation via tab
701 ;; completion.
703 ;; * `comment-auto-fill-only-comments' - variable is made
704 ;; buffer-local and set to `nil' by default. In programming
705 ;; language modes, when this variable is non-nil, only comments
706 ;; will be filled by auto-fill-mode. However, comments in
707 ;; Markdown documents are rare and the most users probably intend
708 ;; for the actual content of the document to be filled. Making
709 ;; this variable buffer-local allows `markdown-mode' to override
710 ;; the default behavior induced when the global variable is non-nil.
712 ;; * `markdown-gfm-additional-languages', - additional languages to
713 ;; make available, aside from those predefined in
714 ;; `markdown-gfm-recognized-languages', when inserting GFM code
715 ;; blocks (default: `nil`). Language strings must have be trimmed
716 ;; of whitespace and not contain any curly braces. They may be of
717 ;; arbitrary capitalization, though.
719 ;; * `markdown-gfm-use-electric-backquote' - use
720 ;; `markdown-electric-backquote' for interactive insertion of GFM
721 ;; code blocks when backquote is pressed three times (default: `t`).
723 ;; * `markdown-make-gfm-checkboxes-buttons' - Whether GitHub
724 ;; Flavored Markdown style task lists (checkboxes) should be
725 ;; turned into buttons that can be toggled with mouse-1 or RET. If
726 ;; non-nil (default), then buttons are enabled. This works in
727 ;; `markdown-mode' as well as `gfm-mode'.
729 ;; * `markdown-hide-urls' - Determines whether URL and reference
730 ;; labels are hidden for inline and reference links (default: `nil').
731 ;; When non-nil, inline links will appear in the buffer as
732 ;; `[link](∞)` instead of
733 ;; `[link](http://perhaps.a/very/long/url/)`. To change the
734 ;; placeholder (composition) character used, set the variable
735 ;; `markdown-url-compose-char'. URL hiding can be toggled
736 ;; interactively using `C-c C-x C-l` (`markdown-toggle-url-hiding')
737 ;; or from the Markdown | Links & Images menu.
739 ;; * `markdown-hide-markup' - Determines whether all possible markup
740 ;; is hidden or otherwise beautified (default: `nil'). The actual
741 ;; buffer text remains unchanged, but the display will be altered.
742 ;; Brackets and URLs for links will be hidden, asterisks and
743 ;; underscores for italic and bold text will be hidden, text
744 ;; bullets for unordered lists will be replaced by Unicode
745 ;; bullets, and so on. Since this includes URLs and reference
746 ;; labels, when non-nil this setting supersedes `markdown-hide-urls'.
747 ;; Markup hiding can be toggled using `C-c C-x C-m`
748 ;; (`markdown-toggle-markup-hiding') or from the Markdown | Show &
749 ;; Hide menu.
751 ;; Unicode bullets are used to replace ASCII list item markers.
752 ;; The list of characters used, in order of list level, can be
753 ;; specified by setting the variable `markdown-list-item-bullets'.
754 ;; The placeholder characters used to replace other markup can
755 ;; be changed by customizing the corresponding variables:
756 ;; `markdown-blockquote-display-char',
757 ;; `markdown-hr-display-char', and
758 ;; `markdown-definition-display-char'.
760 ;; * `markdown-fontify-code-blocks-natively' - Whether to fontify
761 ;; code in code blocks using the native major mode. This only
762 ;; works for fenced code blocks where the language is specified
763 ;; where we can automatically determine the appropriate mode to
764 ;; use. The language to mode mapping may be customized by setting
765 ;; the variable `markdown-code-lang-modes'. This can be toggled
766 ;; interactively by pressing `C-c C-x C-f`
767 ;; (`markdown-toggle-fontify-code-blocks-natively').
769 ;; Additionally, the faces used for syntax highlighting can be modified to
770 ;; your liking by issuing `M-x customize-group RET markdown-faces`
771 ;; or by using the "Markdown Faces" link at the bottom of the mode
772 ;; customization screen.
774 ;; [Marked 2]: https://itunes.apple.com/us/app/marked-2/id890031187?mt=12&uo=4&at=11l5Vs&ct=mm
776 ;;; Extensions:
778 ;; Besides supporting the basic Markdown syntax, Markdown Mode also
779 ;; includes syntax highlighting for `[[Wiki Links]]`. This can be
780 ;; enabled by setting `markdown-enable-wiki-links' to a non-nil value.
781 ;; Wiki links may be followed by pressing `C-c C-o` when the point
782 ;; is at a wiki link. Use `M-p` and `M-n` to quickly jump to the
783 ;; previous and next links (including links of other types).
784 ;; Aliased or piped wiki links of the form `[[link text|PageName]]`
785 ;; are also supported. Since some wikis reverse these components, set
786 ;; `markdown-wiki-link-alias-first' to nil to treat them as
787 ;; `[[PageName|link text]]`. If `markdown-wiki-link-fontify-missing'
788 ;; is also non-nil, Markdown Mode will highlight wiki links with
789 ;; missing target file in a different color. By default, Markdown
790 ;; Mode only searches for target files in the current directory.
791 ;; Search in subdirectories can be enabled by setting
792 ;; `markdown-wiki-link-search-subdirectories' to a non-nil value.
793 ;; Sequential parent directory search (as in [Ikiwiki][]) can be
794 ;; enabled by setting `markdown-wiki-link-search-parent-directories'
795 ;; to a non-nil value.
797 ;; [Ikiwiki]: https://ikiwiki.info
799 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
800 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
801 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
802 ;; You can do this either by using `M-x customize-group markdown`
803 ;; or by placing the following in your `.emacs` file:
805 ;; ``` Lisp
806 ;; (setq markdown-command "markdown | smartypants")
807 ;; ```
809 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
811 ;; Syntax highlighting for mathematical expressions written
812 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
813 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
814 ;; either via customize or by placing `(setq markdown-enable-math t)`
815 ;; in `.emacs`, and then restarting Emacs or calling
816 ;; `markdown-reload-extensions'.
818 ;;; GitHub Flavored Markdown (GFM):
820 ;; A [GitHub Flavored Markdown][GFM] mode, `gfm-mode', is also
821 ;; available. The GitHub implementation differs slightly from
822 ;; standard Markdown in that it supports things like different
823 ;; behavior for underscores inside of words, automatic linking of
824 ;; URLs, strikethrough text, and fenced code blocks with an optional
825 ;; language keyword.
827 ;; The GFM-specific features above apply to `README.md` files, wiki
828 ;; pages, and other Markdown-formatted files in repositories on
829 ;; GitHub. GitHub also enables [additional features][GFM comments] for
830 ;; writing on the site (for issues, pull requests, messages, etc.)
831 ;; that are further extensions of GFM. These features include task
832 ;; lists (checkboxes), newlines corresponding to hard line breaks,
833 ;; auto-linked references to issues and commits, wiki links, and so
834 ;; on. To make matters more confusing, although task lists are not
835 ;; part of [GFM proper][GFM], [since 2014][] they are rendered (in a
836 ;; read-only fashion) in all Markdown documents in repositories on the
837 ;; site. These additional extensions are supported to varying degrees
838 ;; by `markdown-mode' and `gfm-mode' as described below.
840 ;; * **URL autolinking:** Both `markdown-mode' and `gfm-mode' support
841 ;; highlighting of URLs without angle brackets.
843 ;; * **Multiple underscores in words:** You must enable `gfm-mode' to
844 ;; toggle support for underscores inside of words. In this mode
845 ;; variable names such as `a_test_variable` will not trigger
846 ;; emphasis (italics).
848 ;; * **Fenced code blocks:** Code blocks quoted with backquotes, with
849 ;; optional programming language keywords, are highlighted in
850 ;; both `markdown-mode' and `gfm-mode'. They can be inserted with
851 ;; `C-c C-s C`. If there is an active region, the text in the
852 ;; region will be placed inside the code block. You will be
853 ;; prompted for the name of the language, but may press enter to
854 ;; continue without naming a language.
856 ;; * **Strikethrough:** Strikethrough text is supported in both
857 ;; `markdown-mode' and `gfm-mode'. It can be inserted (and toggled)
858 ;; using `C-c C-s s`.
860 ;; * **Task lists:** GFM task lists will be rendered as checkboxes
861 ;; (Emacs buttons) in both `markdown-mode' and `gfm-mode' when
862 ;; `markdown-make-gfm-checkboxes-buttons' is set to a non-nil value
863 ;; (and it is set to t by default). These checkboxes can be
864 ;; toggled by clicking `mouse-1`, pressing `RET` over the button,
865 ;; or by pressing `C-c C-d` (`markdown-do`) with the point anywhere
866 ;; in the task list item.
868 ;; * **Wiki links:** Generic wiki links are supported in
869 ;; `markdown-mode', but in `gfm-mode' specifically they will be
870 ;; treated as they are on GitHub: spaces will be replaced by hyphens
871 ;; in filenames and the first letter of the filename will be
872 ;; capitalized. For example, `[[wiki link]]' will map to a file
873 ;; named `Wiki-link` with the same extension as the current file.
874 ;; If a file with this name does not exist in the current directory,
875 ;; the first match in a subdirectory, if any, will be used instead.
877 ;; * **Newlines:** Neither `markdown-mode' nor `gfm-mode' do anything
878 ;; specifically with respect to newline behavior. If you use
879 ;; `gfm-mode' mostly to write text for comments or issues on the
880 ;; GitHub site--where newlines are significant and correspond to
881 ;; hard line breaks--then you may want to enable `visual-line-mode'
882 ;; for line wrapping in buffers. You can do this with a
883 ;; `gfm-mode-hook' as follows:
885 ;; ``` Lisp
886 ;; ;; Use visual-line-mode in gfm-mode
887 ;; (defun my-gfm-mode-hook ()
888 ;; (visual-line-mode 1))
889 ;; (add-hook 'gfm-mode-hook 'my-gfm-mode-hook)
890 ;; ```
892 ;; * **Preview:** GFM-specific preview can be powered by setting
893 ;; `markdown-command' to use [Docter][]. This may also be
894 ;; configured to work with [Marked 2][] for `markdown-open-command'.
896 ;; [GFM]: http://github.github.com/github-flavored-markdown/
897 ;; [GFM comments]: https://help.github.com/articles/writing-on-github/
898 ;; [since 2014]: https://github.com/blog/1825-task-lists-in-all-markdown-documents
899 ;; [Docter]: https://github.com/alampros/Docter
901 ;;; Acknowledgments:
903 ;; markdown-mode has benefited greatly from the efforts of the many
904 ;; volunteers who have sent patches, test cases, bug reports,
905 ;; suggestions, helped with packaging, etc. Thank you for your
906 ;; contributions! See the [contributors graph][contrib] for details.
908 ;; [contrib]: https://github.com/jrblevin/markdown-mode/graphs/contributors
910 ;;; Bugs:
912 ;; markdown-mode is developed and tested primarily for compatibility
913 ;; with GNU Emacs 24.3 and later. If you find any bugs in
914 ;; markdown-mode, please construct a test case or a patch and open a
915 ;; ticket on the [GitHub issue tracker][issues].
917 ;; [issues]: https://github.com/jrblevin/markdown-mode/issues
919 ;;; History:
921 ;; markdown-mode was written and is maintained by Jason Blevins. The
922 ;; first version was released on May 24, 2007.
924 ;; * 2007-05-24: [Version 1.1][]
925 ;; * 2007-05-25: [Version 1.2][]
926 ;; * 2007-06-05: [Version 1.3][]
927 ;; * 2007-06-29: [Version 1.4][]
928 ;; * 2007-10-11: [Version 1.5][]
929 ;; * 2008-06-04: [Version 1.6][]
930 ;; * 2009-10-01: [Version 1.7][]
931 ;; * 2011-08-12: [Version 1.8][]
932 ;; * 2011-08-15: [Version 1.8.1][]
933 ;; * 2013-01-25: [Version 1.9][]
934 ;; * 2013-03-24: [Version 2.0][]
935 ;; * 2016-01-09: [Version 2.1][]
936 ;; * 2017-05-26: [Version 2.2][]
938 ;; [Version 1.1]: http://jblevins.org/projects/markdown-mode/rev-1-1
939 ;; [Version 1.2]: http://jblevins.org/projects/markdown-mode/rev-1-2
940 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
941 ;; [Version 1.4]: http://jblevins.org/projects/markdown-mode/rev-1-4
942 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
943 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
944 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
945 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
946 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
947 ;; [Version 1.9]: http://jblevins.org/projects/markdown-mode/rev-1-9
948 ;; [Version 2.0]: http://jblevins.org/projects/markdown-mode/rev-2-0
949 ;; [Version 2.1]: http://jblevins.org/projects/markdown-mode/rev-2-1
950 ;; [Version 2.2]: http://jblevins.org/projects/markdown-mode/rev-2-2
953 ;;; Code:
955 (require 'easymenu)
956 (require 'outline)
957 (require 'thingatpt)
958 (require 'cl-lib)
959 (require 'url-parse)
960 (require 'button)
961 (require 'color)
963 (defvar jit-lock-start)
964 (defvar jit-lock-end)
965 (defvar flyspell-generic-check-word-predicate)
967 (declare-function eww-open-file "eww")
968 (declare-function url-path-and-query "url-parse")
971 ;;; Constants =================================================================
973 (defconst markdown-mode-version "2.3-dev"
974 "Markdown mode version number.")
976 (defconst markdown-output-buffer-name "*markdown-output*"
977 "Name of temporary buffer for markdown command output.")
979 (defconst markdown-sub-superscript-display
980 '(((raise -0.3) (height 0.7)) ; subscript
981 ((raise 0.3) (height 0.7))) ; superscript
982 "Parameters for sub- and superscript formatting.")
985 ;;; Global Variables ==========================================================
987 (defvar markdown-reference-label-history nil
988 "History of used reference labels.")
990 (defvar markdown-live-preview-mode nil
991 "Sentinel variable for command `markdown-live-preview-mode'.")
993 (defvar markdown-gfm-language-history nil
994 "History list of languages used in the current buffer in GFM code blocks.")
997 ;;; Customizable Variables ====================================================
999 (defvar markdown-mode-hook nil
1000 "Hook run when entering Markdown mode.")
1002 (defvar markdown-before-export-hook nil
1003 "Hook run before running Markdown to export XHTML output.
1004 The hook may modify the buffer, which will be restored to it's
1005 original state after exporting is complete.")
1007 (defvar markdown-after-export-hook nil
1008 "Hook run after XHTML output has been saved.
1009 Any changes to the output buffer made by this hook will be saved.")
1011 (defgroup markdown nil
1012 "Major mode for editing text files in Markdown format."
1013 :prefix "markdown-"
1014 :group 'wp
1015 :link '(url-link "http://jblevins.org/projects/markdown-mode/"))
1017 (defcustom markdown-command "markdown"
1018 "Command to run markdown."
1019 :group 'markdown
1020 :type 'string)
1022 (defcustom markdown-command-needs-filename nil
1023 "Set to non-nil if `markdown-command' does not accept input from stdin.
1024 Instead, it will be passed a filename as the final command line
1025 option. As a result, you will only be able to run Markdown from
1026 buffers which are visiting a file."
1027 :group 'markdown
1028 :type 'boolean)
1030 (defcustom markdown-open-command nil
1031 "Command used for opening Markdown files directly.
1032 For example, a standalone Markdown previewer. This command will
1033 be called with a single argument: the filename of the current
1034 buffer."
1035 :group 'markdown
1036 :type 'string)
1038 (defcustom markdown-hr-strings
1039 '("-------------------------------------------------------------------------------"
1040 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
1041 "---------------------------------------"
1042 "* * * * * * * * * * * * * * * * * * * *"
1043 "---------"
1044 "* * * * *")
1045 "Strings to use when inserting horizontal rules.
1046 The first string in the list will be the default when inserting a
1047 horizontal rule. Strings should be listed in decreasing order of
1048 prominence (as in headings from level one to six) for use with
1049 promotion and demotion functions."
1050 :group 'markdown
1051 :type 'list)
1053 (defcustom markdown-bold-underscore nil
1054 "Use two underscores when inserting bold text instead of two asterisks."
1055 :group 'markdown
1056 :type 'boolean)
1058 (defcustom markdown-italic-underscore nil
1059 "Use underscores when inserting italic text instead of asterisks."
1060 :group 'markdown
1061 :type 'boolean)
1063 (defcustom markdown-asymmetric-header nil
1064 "Determines if atx header style will be asymmetric.
1065 Set to a non-nil value to use asymmetric header styling, placing
1066 header markup only at the beginning of the line. By default,
1067 balanced markup will be inserted at the beginning and end of the
1068 line around the header title."
1069 :group 'markdown
1070 :type 'boolean)
1072 (defcustom markdown-indent-function 'markdown-indent-line
1073 "Function to use to indent."
1074 :group 'markdown
1075 :type 'function)
1077 (defcustom markdown-indent-on-enter t
1078 "Determines indentation behavior when pressing \\[newline].
1079 Possible settings are nil, t, and 'indent-and-new-item.
1081 When non-nil, pressing \\[newline] will call `newline-and-indent'
1082 to indent the following line according to the context using
1083 `markdown-indent-function'. In this case, note that
1084 \\[electric-newline-and-maybe-indent] can still be used to insert
1085 a newline without indentation.
1087 When set to 'indent-and-new-item and the point is in a list item
1088 when \\[newline] is pressed, the list will be continued on the next
1089 line, where a new item will be inserted.
1091 When set to nil, simply call `newline' as usual. In this case,
1092 you can still indent lines using \\[markdown-cycle] and continue
1093 lists with \\[markdown-insert-list-item].
1095 Note that this assumes the variable `electric-indent-mode' is
1096 non-nil (enabled). When it is *disabled*, the behavior of
1097 \\[newline] and `\\[electric-newline-and-maybe-indent]' are
1098 reversed."
1099 :group 'markdown
1100 :type '(choice (const :tag "Don't automatically indent" nil)
1101 (const :tag "Automatically indent" t)
1102 (const :tag "Automatically indent and insert new list items" indent-and-new-item)))
1104 (defcustom markdown-enable-wiki-links nil
1105 "Syntax highlighting for wiki links.
1106 Set this to a non-nil value to turn on wiki link support by default.
1107 Support can be toggled later using the `markdown-toggle-wiki-links'
1108 function or \\[markdown-toggle-wiki-links]."
1109 :group 'markdown
1110 :type 'boolean
1111 :safe 'booleanp
1112 :package-version '(markdown-mode . "2.2"))
1114 (defcustom markdown-wiki-link-alias-first t
1115 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
1116 Otherwise, they will be treated as [[PageName|alias text]]."
1117 :group 'markdown
1118 :type 'boolean
1119 :safe 'booleanp)
1121 (defcustom markdown-wiki-link-search-subdirectories nil
1122 "When non-nil, search for wiki link targets in subdirectories.
1123 This is the default search behavior for GitHub and is
1124 automatically set to t in `gfm-mode'."
1125 :group 'markdown
1126 :type 'boolean
1127 :safe 'booleanp
1128 :package-version '(markdown-mode . "2.2"))
1130 (defcustom markdown-wiki-link-search-parent-directories nil
1131 "When non-nil, search for wiki link targets in parent directories.
1132 This is the default search behavior of Ikiwiki."
1133 :group 'markdown
1134 :type 'boolean
1135 :safe 'booleanp
1136 :package-version '(markdown-mode . "2.2"))
1138 (defcustom markdown-wiki-link-fontify-missing nil
1139 "When non-nil, change wiki link face according to existence of target files.
1140 This is expensive because it requires checking for the file each time the buffer
1141 changes or the user switches windows. It is disabled by default because it may
1142 cause lag when typing on slower machines."
1143 :group 'markdown
1144 :type 'boolean
1145 :safe 'booleanp
1146 :package-version '(markdown-mode . "2.2"))
1148 (defcustom markdown-uri-types
1149 '("acap" "cid" "data" "dav" "fax" "file" "ftp"
1150 "gopher" "http" "https" "imap" "ldap" "mailto"
1151 "mid" "message" "modem" "news" "nfs" "nntp"
1152 "pop" "prospero" "rtsp" "service" "sip" "tel"
1153 "telnet" "tip" "urn" "vemmi" "wais")
1154 "Link types for syntax highlighting of URIs."
1155 :group 'markdown
1156 :type 'list)
1158 (defcustom markdown-url-compose-char
1159 (cond
1160 ((char-displayable-p ?∞) ?∞)
1161 ((char-displayable-p ?…) ?…)
1162 (t ?#))
1163 "Placeholder character for hidden URLs.
1164 Depending on your font, some good choices are …, ⋯, #, ∞, ★, and ⚓."
1165 :type 'character
1166 :safe 'characterp
1167 :package-version '(markdown-mode . "2.3"))
1169 (defcustom markdown-blockquote-display-char
1170 (cond
1171 ((char-displayable-p ?▌) "▌")
1172 ((char-displayable-p ?┃) "┃")
1173 ((char-displayable-p ?│) "│")
1174 ((char-displayable-p ?|) "|")
1175 (t ">"))
1176 "Character for hiding blockquote markup."
1177 :type 'string
1178 :safe 'stringp
1179 :package-version '(markdown-mode . "2.3"))
1181 (defcustom markdown-hr-display-char
1182 (cond ((char-displayable-p ?─) ?─)
1183 ((char-displayable-p ?━) ?━)
1184 (t ?-))
1185 "Character for hiding horizontal rule markup."
1186 :type 'character
1187 :safe 'characterp
1188 :package-version '(markdown-mode . "2.3"))
1190 (defcustom markdown-definition-display-char
1191 (cond ((char-displayable-p ?⁘) ?⁘)
1192 ((char-displayable-p ?⁙) ?⁙)
1193 ((char-displayable-p ?≡) ?≡)
1194 ((char-displayable-p ?⌑) ?⌑)
1195 ((char-displayable-p ?◊) ?◊)
1196 (t nil))
1197 "Character for replacing definition list markup."
1198 :type 'character
1199 :safe 'characterp
1200 :package-version '(markdown-mode . "2.3"))
1202 (defcustom markdown-enable-math nil
1203 "Syntax highlighting for inline LaTeX and itex expressions.
1204 Set this to a non-nil value to turn on math support by default.
1205 Math support can be enabled, disabled, or toggled later using
1206 `markdown-toggle-math' or \\[markdown-toggle-math]."
1207 :group 'markdown
1208 :type 'boolean
1209 :safe 'booleanp)
1210 (make-variable-buffer-local 'markdown-enable-math)
1212 (defcustom markdown-css-paths nil
1213 "URL of CSS file to link to in the output XHTML."
1214 :group 'markdown
1215 :type 'list)
1217 (defcustom markdown-content-type ""
1218 "Content type string for the http-equiv header in XHTML output.
1219 When set to a non-empty string, insert the http-equiv attribute.
1220 Otherwise, this attribute is omitted."
1221 :group 'markdown
1222 :type 'string)
1224 (defcustom markdown-coding-system nil
1225 "Character set string for the http-equiv header in XHTML output.
1226 Defaults to `buffer-file-coding-system' (and falling back to
1227 `iso-8859-1' when not available). Common settings are `utf-8'
1228 and `iso-latin-1'. Use `list-coding-systems' for more choices."
1229 :group 'markdown
1230 :type 'coding-system)
1232 (defcustom markdown-xhtml-header-content ""
1233 "Additional content to include in the XHTML <head> block."
1234 :group 'markdown
1235 :type 'string)
1237 (defcustom markdown-xhtml-standalone-regexp
1238 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
1239 "Regexp indicating whether `markdown-command' output is standalone XHTML."
1240 :group 'markdown
1241 :type 'regexp)
1243 (defcustom markdown-link-space-sub-char "_"
1244 "Character to use instead of spaces when mapping wiki links to filenames."
1245 :group 'markdown
1246 :type 'string)
1248 (defcustom markdown-reference-location 'header
1249 "Position where new reference definitions are inserted in the document."
1250 :group 'markdown
1251 :type '(choice (const :tag "At the end of the document" end)
1252 (const :tag "Immediately after the current block" immediately)
1253 (const :tag "At the end of the subtree" subtree)
1254 (const :tag "Before next header" header)))
1256 (defcustom markdown-footnote-location 'end
1257 "Position where new footnotes are inserted in the document."
1258 :group 'markdown
1259 :type '(choice (const :tag "At the end of the document" end)
1260 (const :tag "Immediately after the current block" immediately)
1261 (const :tag "At the end of the subtree" subtree)
1262 (const :tag "Before next header" header)))
1264 (defcustom markdown-unordered-list-item-prefix " * "
1265 "String inserted before unordered list items."
1266 :group 'markdown
1267 :type 'string)
1269 (defcustom markdown-nested-imenu-heading-index t
1270 "Use nested or flat imenu heading index.
1271 A nested index may provide more natural browsing from the menu,
1272 but a flat list may allow for faster keyboard navigation via tab
1273 completion."
1274 :group 'markdown
1275 :type 'boolean
1276 :safe 'booleanp
1277 :package-version '(markdown-mode . "2.2"))
1279 (defcustom markdown-make-gfm-checkboxes-buttons t
1280 "When non-nil, make GFM checkboxes into buttons."
1281 :group 'markdown
1282 :type 'boolean)
1284 (defcustom markdown-use-pandoc-style-yaml-metadata nil
1285 "When non-nil, allow YAML metadata anywhere in the document."
1286 :group 'markdown
1287 :type 'boolean)
1289 (defcustom markdown-split-window-direction 'any
1290 "Preference for splitting windows for static and live preview.
1291 The default value is 'any, which instructs Emacs to use
1292 `split-window-sensibly' to automatically choose how to split
1293 windows based on the values of `split-width-threshold' and
1294 `split-height-threshold' and the available windows. To force
1295 vertically split (left and right) windows, set this to 'vertical
1296 or 'right. To force horizontally split (top and bottom) windows,
1297 set this to 'horizontal or 'below."
1298 :group 'markdown
1299 :type '(choice (const :tag "Automatic" any)
1300 (const :tag "Right (vertical)" right)
1301 (const :tag "Below (horizontal)" below))
1302 :package-version '(markdown-mode . "2.2"))
1304 (defcustom markdown-live-preview-window-function
1305 'markdown-live-preview-window-eww
1306 "Function to display preview of Markdown output within Emacs.
1307 Function must update the buffer containing the preview and return
1308 the buffer."
1309 :group 'markdown
1310 :type 'function)
1312 (defcustom markdown-live-preview-delete-export 'delete-on-destroy
1313 "Delete exported HTML file when using `markdown-live-preview-export'.
1314 If set to 'delete-on-export, delete on every export. When set to
1315 'delete-on-destroy delete when quitting from command
1316 `markdown-live-preview-mode'. Never delete if set to nil."
1317 :group 'markdown
1318 :type '(choice
1319 (const :tag "Delete on every export" delete-on-export)
1320 (const :tag "Delete when quitting live preview" delete-on-destroy)
1321 (const :tag "Never delete" nil)))
1323 (defcustom markdown-list-indent-width 4
1324 "Depth of indentation for markdown lists.
1325 Used in `markdown-demote-list-item' and
1326 `markdown-promote-list-item'."
1327 :group 'markdown
1328 :type 'integer)
1330 (defcustom markdown-gfm-additional-languages nil
1331 "Extra languages made available when inserting GFM code blocks.
1332 Language strings must have be trimmed of whitespace and not
1333 contain any curly braces. They may be of arbitrary
1334 capitalization, though."
1335 :group 'markdown
1336 :type '(repeat (string :validate markdown-validate-language-string)))
1338 (defcustom markdown-gfm-use-electric-backquote t
1339 "Use `markdown-electric-backquote' when backquote is hit three times."
1340 :group 'markdown
1341 :type 'boolean)
1343 (defcustom markdown-gfm-downcase-languages t
1344 "If non-nil, downcase suggested languages.
1345 This applies to insertions done with
1346 `markdown-electric-backquote'."
1347 :group 'markdown
1348 :type 'boolean)
1350 (defcustom markdown-hide-urls nil
1351 "Hide URLs of inline links and reference tags of reference links.
1352 Such URLs will be replaced by a single customizable
1353 character (∞), or `markdown-url-compose-char', but are still part
1354 of the buffer. Links can be edited interactively with
1355 \\[markdown-insert-link] or, for example, by deleting the final
1356 parenthesis to remove the invisibility property. You can also
1357 hover your mouse pointer over the link text to see the URL.
1358 Set this to a non-nil value to turn this feature on by default.
1359 You can interactively set the value of this variable by calling
1360 `markdown-toggle-url-hiding', pressing \\[markdown-toggle-url-hiding],
1361 or from the menu Markdown > Links & Images menu."
1362 :group 'markdown
1363 :type 'boolean
1364 :safe 'booleanp
1365 :package-version '(markdown-mode . "2.3"))
1366 (make-variable-buffer-local 'markdown-hide-urls)
1369 ;;; Regular Expressions =======================================================
1371 (defconst markdown-regex-comment-start
1372 "<!--"
1373 "Regular expression matches HTML comment opening.")
1375 (defconst markdown-regex-comment-end
1376 "--[ \t]*>"
1377 "Regular expression matches HTML comment closing.")
1379 (defconst markdown-regex-link-inline
1380 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)\\((\\)\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?\\()\\)"
1381 "Regular expression for a [text](file) or an image link ![text](file).
1382 Group 1 matches the leading exclamation point (optional).
1383 Group 2 matches the opening square bracket.
1384 Group 3 matches the text inside the square brackets.
1385 Group 4 matches the closing square bracket.
1386 Group 5 matches the opening parenthesis.
1387 Group 6 matches the URL.
1388 Group 7 matches the title (optional).
1389 Group 8 matches the closing parenthesis.")
1391 (defconst markdown-regex-link-reference
1392 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)[ ]?\\(\\[\\)\\([^]]*?\\)\\(\\]\\)"
1393 "Regular expression for a reference link [text][id].
1394 Group 1 matches the leading exclamation point (optional).
1395 Group 2 matches the opening square bracket for the link text.
1396 Group 3 matches the text inside the square brackets.
1397 Group 4 matches the closing square bracket for the link text.
1398 Group 5 matches the opening square bracket for the reference label.
1399 Group 6 matches the reference label.
1400 Group 7 matches the closing square bracket for the reference label.")
1402 (defconst markdown-regex-reference-definition
1403 "^ \\{0,3\\}\\(\\[\\)\\([^]\n]+?\\)\\(\\]\\)\\(:\\)\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
1404 "Regular expression for a reference definition.
1405 Group 1 matches the opening square bracket.
1406 Group 2 matches the reference label.
1407 Group 3 matches the closing square bracket.
1408 Group 4 matches the colon.
1409 Group 5 matches the URL.
1410 Group 6 matches the title attribute (optional).")
1412 (defconst markdown-regex-footnote
1413 "\\(\\[\\^\\)\\(.+?\\)\\(\\]\\)"
1414 "Regular expression for a footnote marker [^fn].
1415 Group 1 matches the opening square bracket and carat.
1416 Group 2 matches only the label, without the surrounding markup.
1417 Group 3 matches the closing square bracket.")
1419 (defconst markdown-regex-header
1420 "^\\(?:\\([^\r\n\t -].*\\)\n\\(?:\\(=+\\)\\|\\(-+\\)\\)\\|\\(#+[ \t]+\\)\\(.*?\\)\\([ \t]*#*\\)\\)$"
1421 "Regexp identifying Markdown headings.
1422 Group 1 matches the text of a setext heading.
1423 Group 2 matches the underline of a level-1 setext heading.
1424 Group 3 matches the underline of a level-2 setext heading.
1425 Group 4 matches the opening hash marks of an atx heading and whitespace.
1426 Group 5 matches the text, without surrounding whitespace, of an atx heading.
1427 Group 6 matches the closing whitespace and hash marks of an atx heading.")
1429 (defconst markdown-regex-header-setext
1430 "^\\([^\r\n\t -].*\\)\n\\(=+\\|-+\\)$"
1431 "Regular expression for generic setext-style (underline) headers.")
1433 (defconst markdown-regex-header-atx
1434 "^\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1435 "Regular expression for generic atx-style (hash mark) headers.")
1437 (defconst markdown-regex-hr
1438 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1439 "Regular expression for matching Markdown horizontal rules.")
1441 (defconst markdown-regex-code
1442 "\\(?:\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(?:.\\|\n[^\n]\\)*?[^`]\\)\\(\\2\\)\\)\\(?:[^`]\\|\\'\\)"
1443 "Regular expression for matching inline code fragments.
1445 Group 1 matches the entire code fragment including the backquotes.
1446 Group 2 matches the opening backquotes.
1447 Group 3 matches the code fragment itself, without backquotes.
1448 Group 4 matches the closing backquotes.
1450 The leading, unnumbered group ensures that the leading backquote
1451 character is not escaped.
1452 The last group, also unnumbered, requires that the character
1453 following the code fragment is not a backquote.
1454 Note that \\(?:.\\|\n[^\n]\\) matches any character, including newlines,
1455 but not two newlines in a row.")
1457 (defconst markdown-regex-kbd
1458 "\\(<kbd>\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(</kbd>\\)"
1459 "Regular expression for matching <kbd> tags.
1460 Groups 1 and 3 match the opening and closing tags.
1461 Group 2 matches the key sequence.")
1463 (defconst markdown-regex-gfm-code-block-open
1464 "^[[:blank:]]*\\(```\\)\\([[:blank:]]*{?[[:blank:]]*\\)\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$"
1465 "Regular expression matching opening of GFM code blocks.
1466 Group 1 matches the opening three backquotes and any following whitespace.
1467 Group 2 matches the opening brace (optional) and surrounding whitespace.
1468 Group 3 matches the language identifier (optional).
1469 Group 4 matches the info string (optional).
1470 Group 5 matches the closing brace (optional), whitespace, and newline.
1471 Groups need to agree with `markdown-regex-tilde-fence-begin'.")
1473 (defconst markdown-regex-gfm-code-block-close
1474 "^[[:blank:]]*\\(```\\)\\(\\s *?\\)$"
1475 "Regular expression matching closing of GFM code blocks.
1476 Group 1 matches the closing three backquotes.
1477 Group 2 matches any whitespace and the final newline.")
1479 (defconst markdown-regex-pre
1480 "^\\( \\|\t\\).*$"
1481 "Regular expression for matching preformatted text sections.")
1483 (defconst markdown-regex-list
1484 "^\\([ \t]*\\)\\([0-9#]+\\.\\|[\\*\\+:-]\\)\\([ \t]+\\)"
1485 "Regular expression for matching list items.")
1487 (defconst markdown-regex-bold
1488 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1489 "Regular expression for matching bold text.
1490 Group 1 matches the character before the opening asterisk or
1491 underscore, if any, ensuring that it is not a backslash escape.
1492 Group 2 matches the entire expression, including delimiters.
1493 Groups 3 and 5 matches the opening and closing delimiters.
1494 Group 4 matches the text inside the delimiters.")
1496 (defconst markdown-regex-italic
1497 "\\(?:^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1498 "Regular expression for matching italic text.
1499 The leading unnumbered matches the character before the opening
1500 asterisk or underscore, if any, ensuring that it is not a
1501 backslash escape.
1502 Group 1 matches the entire expression, including delimiters.
1503 Groups 2 and 4 matches the opening and closing delimiters.
1504 Group 3 matches the text inside the delimiters.")
1506 (defconst markdown-regex-strike-through
1507 "\\(^\\|[^\\]\\)\\(\\(~~\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(~~\\)\\)"
1508 "Regular expression for matching strike-through text.
1509 Group 1 matches the character before the opening tilde, if any,
1510 ensuring that it is not a backslash escape.
1511 Group 2 matches the entire expression, including delimiters.
1512 Groups 3 and 5 matches the opening and closing delimiters.
1513 Group 4 matches the text inside the delimiters.")
1515 (defconst markdown-regex-gfm-italic
1516 "\\(?:^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\2\\|[^ ]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1517 "Regular expression for matching italic text in GitHub Flavored Markdown.
1518 Underscores in words are not treated as special.
1519 Group 1 matches the entire expression, including delimiters.
1520 Groups 2 and 4 matches the opening and closing delimiters.
1521 Group 3 matches the text inside the delimiters.")
1523 (defconst markdown-regex-blockquote
1524 "^[ \t]*\\([A-Z]?>\\)\\([ \t]*\\)\\(.*\\)$"
1525 "Regular expression for matching blockquote lines.
1526 Also accounts for a potential capital letter preceding the angle
1527 bracket, for use with Leanpub blocks (asides, warnings, info
1528 blocks, etc.).
1529 Group 1 matches the leading angle bracket.
1530 Group 2 matches the separating whitespace.
1531 Group 3 matches the text.")
1533 (defconst markdown-regex-line-break
1534 "[^ \n\t][ \t]*\\( \\)$"
1535 "Regular expression for matching line breaks.")
1537 (defconst markdown-regex-wiki-link
1538 "\\(?:^\\|[^\\]\\)\\(\\(\\[\\[\\)\\([^]|]+\\)\\(?:\\(|\\)\\([^]]+\\)\\)?\\(\\]\\]\\)\\)"
1539 "Regular expression for matching wiki links.
1540 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1541 wiki links of the form [[PageName|link text]].
1542 The meanings of the first and second components depend
1543 on the value of `markdown-wiki-link-alias-first'.
1545 Group 1 matches the entire link.
1546 Group 2 matches the opening square brackets.
1547 Group 3 matches the first component of the wiki link.
1548 Group 4 matches the pipe separator, when present.
1549 Group 5 matches the second component of the wiki link, when present.
1550 Group 6 matches the closing square brackets.")
1552 (defconst markdown-regex-uri
1553 (concat "\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+\\)")
1554 "Regular expression for matching inline URIs.")
1556 (defconst markdown-regex-angle-uri
1557 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1558 "Regular expression for matching inline URIs in angle brackets.")
1560 (defconst markdown-regex-email
1561 "<\\(\\(?:\\sw\\|\\s_\\|\\s.\\)+@\\(?:\\sw\\|\\s_\\|\\s.\\)+\\)>"
1562 "Regular expression for matching inline email addresses.")
1564 (defsubst markdown-make-regex-link-generic ()
1565 "Make regular expression for matching any recognized link."
1566 (concat "\\(?:" markdown-regex-link-inline
1567 (when markdown-enable-wiki-links
1568 (concat "\\|" markdown-regex-wiki-link))
1569 "\\|" markdown-regex-link-reference
1570 "\\|" markdown-regex-angle-uri "\\)"))
1572 (defconst markdown-regex-gfm-checkbox
1573 " \\(\\[[ xX]\\]\\) "
1574 "Regular expression for matching GFM checkboxes.
1575 Group 1 matches the text to become a button.")
1577 (defconst markdown-regex-block-separator
1578 "\n[\n\t\f ]*\n"
1579 "Regular expression for matching block boundaries.")
1581 (defconst markdown-regex-block-separator-noindent
1582 (concat "\\(\\`\\|\\(" markdown-regex-block-separator "\\)[^\n\t\f ]\\)")
1583 "Regexp for block separators before lines with no indentation.")
1585 (defconst markdown-regex-math-inline-single
1586 "\\(?:^\\|[^\\]\\)\\(\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\)"
1587 "Regular expression for itex $..$ math mode expressions.
1588 Groups 1 and 3 match the opening and closing dollar signs.
1589 Group 3 matches the mathematical expression contained within.")
1591 (defconst markdown-regex-math-inline-double
1592 "\\(?:^\\|[^\\]\\)\\(\\$\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\$\\)"
1593 "Regular expression for itex $$..$$ math mode expressions.
1594 Groups 1 and 3 match opening and closing dollar signs.
1595 Group 3 matches the mathematical expression contained within.")
1597 (defconst markdown-regex-math-display
1598 "^\\(\\\\\\[\\)\\(\\(?:.\\|\n\\)*?\\)?\\(\\\\\\]\\)$"
1599 "Regular expression for itex \[..\] display mode expressions.
1600 Groups 1 and 3 match the opening and closing delimiters.
1601 Group 2 matches the mathematical expression contained within.")
1603 (defsubst markdown-make-tilde-fence-regex (num-tildes &optional end-of-line)
1604 "Return regexp matching a tilde code fence at least NUM-TILDES long.
1605 END-OF-LINE is the regexp construct to indicate end of line; $ if
1606 missing."
1607 (format "%s%d%s%s" "^[[:blank:]]*\\([~]\\{" num-tildes ",\\}\\)"
1608 (or end-of-line "$")))
1610 (defconst markdown-regex-tilde-fence-begin
1611 (markdown-make-tilde-fence-regex
1612 3 "\\([[:blank:]]*{?\\)[[:blank:]]*\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$")
1613 "Regular expression for matching tilde-fenced code blocks.
1614 Group 1 matches the opening tildes.
1615 Group 2 matches (optional) opening brace and surrounding whitespace.
1616 Group 3 matches the language identifier (optional).
1617 Group 4 matches the info string (optional).
1618 Group 5 matches the closing brace (optional) and any surrounding whitespace.
1619 Groups need to agree with `markdown-regex-gfm-code-block-open'.")
1621 (defconst markdown-regex-declarative-metadata
1622 "^\\([[:alpha:]][[:alpha:] _-]*?\\)\\([:=][ \t]*\\)\\(.*\\)$"
1623 "Regular expression for matching declarative metadata statements.
1624 This matches MultiMarkdown metadata as well as YAML and TOML
1625 assignments such as the following:
1627 variable: value
1631 variable = value")
1633 (defconst markdown-regex-pandoc-metadata
1634 "^\\(%\\)\\([ \t]*\\)\\(.*\\(?:\n[ \t]+.*\\)*\\)"
1635 "Regular expression for matching Pandoc metadata.")
1637 (defconst markdown-regex-yaml-metadata-border
1638 "\\(-\\{3\\}\\)$"
1639 "Regular expression for matching YAML metadata.")
1641 (defconst markdown-regex-yaml-pandoc-metadata-end-border
1642 "^\\(\\.\\{3\\}\\|\\-\\{3\\}\\)$"
1643 "Regular expression for matching YAML metadata end borders.")
1645 (defsubst markdown-get-yaml-metadata-start-border ()
1646 "Return YAML metadata start border depending upon whether Pandoc is used."
1647 (concat
1648 (if markdown-use-pandoc-style-yaml-metadata "^" "\\`")
1649 markdown-regex-yaml-metadata-border))
1651 (defsubst markdown-get-yaml-metadata-end-border (_)
1652 "Return YAML metadata end border depending upon whether Pandoc is used."
1653 (if markdown-use-pandoc-style-yaml-metadata
1654 markdown-regex-yaml-pandoc-metadata-end-border
1655 markdown-regex-yaml-metadata-border))
1657 (defconst markdown-regex-inline-attributes
1658 "[ \t]*\\({:?\\)[ \t]*\\(\\(#[[:alpha:]_.:-]+\\|\\.[[:alpha:]_.:-]+\\|\\w+=['\"]?[^\n'\"]*['\"]?\\),?[ \t]*\\)+\\(}\\)[ \t]*$"
1659 "Regular expression for matching inline identifiers or attribute lists.
1660 Compatible with Pandoc, Python Markdown, PHP Markdown Extra, and Leanpub.")
1662 (defconst markdown-regex-leanpub-sections
1663 (concat
1664 "^\\({\\)\\("
1665 (regexp-opt '("frontmatter" "mainmatter" "backmatter" "appendix" "pagebreak"))
1666 "\\)\\(}\\)[ \t]*\n")
1667 "Regular expression for Leanpub section markers and related syntax.")
1669 (defconst markdown-regex-sub-superscript
1670 "\\(?:^\\|[^\\~^]\\)\\(\\([~^]\\)\\([[:alnum:]]+\\)\\(\\2\\)\\)"
1671 "The regular expression matching a sub- or superscript.
1672 The leading un-numbered group matches the character before the
1673 opening tilde or carat, if any, ensuring that it is not a
1674 backslash escape, carat, or tilde.
1675 Group 1 matches the entire expression, including markup.
1676 Group 2 matches the opening markup--a tilde or carat.
1677 Group 3 matches the text inside the delimiters.
1678 Group 4 matches the closing markup--a tilde or carat.")
1680 (defconst markdown-regex-include
1681 "^\\(<<\\)\\(?:\\(\\[\\)\\(.*\\)\\(\\]\\)\\)?\\(?:\\((\\)\\(.*\\)\\()\\)\\)?\\(?:\\({\\)\\(.*\\)\\(}\\)\\)?$"
1682 "Regular expression matching common forms of include syntax.
1683 Marked 2, Leanpub, and other processors support some of these forms:
1685 <<[sections/section1.md]
1686 <<(folder/filename)
1687 <<[Code title](folder/filename)
1688 <<{folder/raw_file.html}
1690 Group 1 matches the opening two angle brackets.
1691 Groups 2-4 match the opening square bracket, the text inside,
1692 and the closing square bracket, respectively.
1693 Groups 5-7 match the opening parenthesis, the text inside, and
1694 the closing parenthesis.
1695 Groups 8-10 match the opening brace, the text inside, and the brace.")
1697 (defconst markdown-regex-pandoc-inline-footnote
1698 "\\(\\^\\)\\(\\[\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(\\]\\)"
1699 "Regular expression for Pandoc inline footnote^[footnote text].
1700 Group 1 matches the opening caret.
1701 Group 2 matches the opening square bracket.
1702 Group 3 matches the footnote text, without the surrounding markup.
1703 Group 4 matches the closing square bracket.")
1706 ;;; Syntax ====================================================================
1708 (defsubst markdown-in-comment-p (&optional pos)
1709 "Return non-nil if POS is in a comment.
1710 If POS is not given, use point instead."
1711 (nth 4 (syntax-ppss pos)))
1713 (defun markdown-syntax-propertize-extend-region (start end)
1714 "Extend START to END region to include an entire block of text.
1715 This helps improve syntax analysis for block constructs.
1716 Returns a cons (NEW-START . NEW-END) or nil if no adjustment should be made.
1717 Function is called repeatedly until it returns nil. For details, see
1718 `syntax-propertize-extend-region-functions'."
1719 (save-match-data
1720 (save-excursion
1721 (let* ((new-start (progn (goto-char start)
1722 (skip-chars-forward "\n")
1723 (if (re-search-backward "\n\n" nil t)
1724 (min start (match-end 0))
1725 (point-min))))
1726 (new-end (progn (goto-char end)
1727 (skip-chars-backward "\n")
1728 (if (re-search-forward "\n\n" nil t)
1729 (max end (match-beginning 0))
1730 (point-max))))
1731 (code-match (markdown-code-block-at-pos new-start))
1732 (new-start (or (and code-match (cl-first code-match)) new-start))
1733 (code-match (and (< end (point-max)) (markdown-code-block-at-pos end)))
1734 (new-end (or (and code-match (cl-second code-match)) new-end)))
1735 (unless (and (eq new-start start) (eq new-end end))
1736 (cons new-start (min new-end (point-max))))))))
1738 (defun markdown-font-lock-extend-region-function (start end _)
1739 "Used in `jit-lock-after-change-extend-region-functions'.
1740 Delegates to `markdown-syntax-propertize-extend-region'. START
1741 and END are the previous region to refontify."
1742 (let ((res (markdown-syntax-propertize-extend-region start end)))
1743 (when res
1744 ;; syntax-propertize-function is not called when character at
1745 ;; (point-max) is deleted, but font-lock-extend-region-functions
1746 ;; are called. Force a syntax property update in that case.
1747 (when (= end (point-max))
1748 ;; This function is called in a buffer modification hook.
1749 ;; `markdown-syntax-propertize' doesn't save the match data,
1750 ;; so we have to do it here.
1751 (save-match-data
1752 (markdown-syntax-propertize (car res) (cdr res))))
1753 (setq jit-lock-start (car res)
1754 jit-lock-end (cdr res)))))
1756 (defun markdown-syntax-propertize-pre-blocks (start end)
1757 "Match preformatted text blocks from START to END."
1758 (save-excursion
1759 (goto-char start)
1760 (let ((levels (markdown-calculate-list-levels))
1761 indent pre-regexp close-regexp open close)
1762 (while (and (< (point) end) (not close))
1763 ;; Search for a region with sufficient indentation
1764 (if (null levels)
1765 (setq indent 1)
1766 (setq indent (1+ (length levels))))
1767 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1768 (setq close-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1770 (cond
1771 ;; If not at the beginning of a line, move forward
1772 ((not (bolp)) (forward-line))
1773 ;; Move past blank lines
1774 ((markdown-cur-line-blank) (forward-line))
1775 ;; At headers and horizontal rules, reset levels
1776 ((markdown-new-baseline) (forward-line) (setq levels nil))
1777 ;; If the current line has sufficient indentation, mark out pre block
1778 ;; The opening should be preceded by a blank line.
1779 ((and (looking-at pre-regexp)
1780 (markdown-prev-line-blank-p))
1781 (setq open (match-beginning 0))
1782 (while (and (or (looking-at-p pre-regexp) (markdown-cur-line-blank))
1783 (not (eobp)))
1784 (forward-line))
1785 (skip-syntax-backward "-")
1786 (setq close (point)))
1787 ;; If current line has a list marker, update levels, move to end of block
1788 ((looking-at markdown-regex-list)
1789 (setq levels (markdown-update-list-levels
1790 (match-string 2) (current-indentation) levels))
1791 (markdown-end-of-text-block))
1792 ;; If this is the end of the indentation level, adjust levels accordingly.
1793 ;; Only match end of indentation level if levels is not the empty list.
1794 ((and (car levels) (looking-at-p close-regexp))
1795 (setq levels (markdown-update-list-levels
1796 nil (current-indentation) levels))
1797 (markdown-end-of-text-block))
1798 (t (markdown-end-of-text-block))))
1800 (when (and open close)
1801 ;; Set text property data
1802 (put-text-property open close 'markdown-pre (list open close))
1803 ;; Recursively search again
1804 (markdown-syntax-propertize-pre-blocks (point) end)))))
1806 (defconst markdown-fenced-block-pairs
1807 `(((,markdown-regex-tilde-fence-begin markdown-tilde-fence-begin)
1808 (markdown-make-tilde-fence-regex markdown-tilde-fence-end)
1809 markdown-fenced-code)
1810 ((markdown-get-yaml-metadata-start-border markdown-yaml-metadata-begin)
1811 (markdown-get-yaml-metadata-end-border markdown-yaml-metadata-end)
1812 markdown-yaml-metadata-section)
1813 ((,markdown-regex-gfm-code-block-open markdown-gfm-block-begin)
1814 (,markdown-regex-gfm-code-block-close markdown-gfm-block-end)
1815 markdown-gfm-code))
1816 "Mapping of regular expressions to \"fenced-block\" constructs.
1817 These constructs are distinguished by having a distinctive start
1818 and end pattern, both of which take up an entire line of text,
1819 but no special pattern to identify text within the fenced
1820 blocks (unlike blockquotes and indented-code sections).
1822 Each element within this list takes the form:
1824 ((START-REGEX-OR-FUN START-PROPERTY)
1825 (END-REGEX-OR-FUN END-PROPERTY)
1826 MIDDLE-PROPERTY)
1828 Each *-REGEX-OR-FUN element can be a regular expression as a string, or a
1829 function which evaluates to same. Functions for START-REGEX-OR-FUN accept no
1830 arguments, but functions for END-REGEX-OR-FUN accept a single numerical argument
1831 which is the length of the first group of the START-REGEX-OR-FUN match, which
1832 can be ignored if unnecessary. `markdown-maybe-funcall-regexp' is used to
1833 evaluate these into \"real\" regexps.
1835 The *-PROPERTY elements are the text properties applied to each part of the
1836 block construct when it is matched using
1837 `markdown-syntax-propertize-fenced-block-constructs'. START-PROPERTY is applied
1838 to the text matching START-REGEX-OR-FUN, END-PROPERTY to END-REGEX-OR-FUN, and
1839 MIDDLE-PROPERTY to the text in between the two. The value of *-PROPERTY is the
1840 `match-data' when the regexp was matched to the text. In the case of
1841 MIDDLE-PROPERTY, the value is a false match data of the form '(begin end), with
1842 begin and end set to the edges of the \"middle\" text. This makes fontification
1843 easier.")
1845 (defun markdown-text-property-at-point (prop)
1846 (get-text-property (point) prop))
1848 (defsubst markdown-maybe-funcall-regexp (object &optional arg)
1849 (cond ((functionp object)
1850 (if arg (funcall object arg) (funcall object)))
1851 ((stringp object) object)
1852 (t (error "Object cannot be turned into regex"))))
1854 (defsubst markdown-get-start-fence-regexp ()
1855 "Return regexp to find all \"start\" sections of fenced block constructs.
1856 Which construct is actually contained in the match must be found separately."
1857 (mapconcat
1858 #'identity
1859 (mapcar (lambda (entry) (markdown-maybe-funcall-regexp (caar entry)))
1860 markdown-fenced-block-pairs)
1861 "\\|"))
1863 (defun markdown-get-fenced-block-begin-properties ()
1864 (cl-mapcar (lambda (entry) (cl-cadar entry)) markdown-fenced-block-pairs))
1866 (defun markdown-get-fenced-block-end-properties ()
1867 (cl-mapcar (lambda (entry) (cl-cadadr entry)) markdown-fenced-block-pairs))
1869 (defun markdown-get-fenced-block-middle-properties ()
1870 (cl-mapcar #'cl-third markdown-fenced-block-pairs))
1872 (defun markdown-find-previous-prop (prop &optional lim)
1873 "Find previous place where property PROP is non-nil, up to LIM.
1874 Return a cons of (pos . property). pos is point if point contains
1875 non-nil PROP."
1876 (let ((res
1877 (if (get-text-property (point) prop) (point)
1878 (previous-single-property-change
1879 (point) prop nil (or lim (point-min))))))
1880 (when (and (not (get-text-property res prop))
1881 (> res (point-min))
1882 (get-text-property (1- res) prop))
1883 (cl-decf res))
1884 (when (and res (get-text-property res prop)) (cons res prop))))
1886 (defun markdown-find-next-prop (prop &optional lim)
1887 "Find next place where property PROP is non-nil, up to LIM.
1888 Return a cons of (POS . PROPERTY) where POS is point if point
1889 contains non-nil PROP."
1890 (let ((res
1891 (if (get-text-property (point) prop) (point)
1892 (next-single-property-change
1893 (point) prop nil (or lim (point-max))))))
1894 (when (and res (get-text-property res prop)) (cons res prop))))
1896 (defun markdown-min-of-seq (map-fn seq)
1897 "Apply MAP-FN to SEQ and return element of SEQ with minimum value of MAP-FN."
1898 (cl-loop for el in seq
1899 with min = 1.0e+INF ; infinity
1900 with min-el = nil
1901 do (let ((res (funcall map-fn el)))
1902 (when (< res min)
1903 (setq min res)
1904 (setq min-el el)))
1905 finally return min-el))
1907 (defun markdown-max-of-seq (map-fn seq)
1908 "Apply MAP-FN to SEQ and return element of SEQ with maximum value of MAP-FN."
1909 (cl-loop for el in seq
1910 with max = -1.0e+INF ; negative infinity
1911 with max-el = nil
1912 do (let ((res (funcall map-fn el)))
1913 (when (and res (> res max))
1914 (setq max res)
1915 (setq max-el el)))
1916 finally return max-el))
1918 (defun markdown-find-previous-block ()
1919 "Find previous block.
1920 Detect whether `markdown-syntax-propertize-fenced-block-constructs' was
1921 unable to propertize the entire block, but was able to propertize the beginning
1922 of the block. If so, return a cons of (pos . property) where the beginning of
1923 the block was propertized."
1924 (let ((start-pt (point))
1925 (closest-open
1926 (markdown-max-of-seq
1927 #'car
1928 (cl-remove-if
1929 #'null
1930 (cl-mapcar
1931 #'markdown-find-previous-prop
1932 (markdown-get-fenced-block-begin-properties))))))
1933 (when closest-open
1934 (let* ((length-of-open-match
1935 (let ((match-d
1936 (get-text-property (car closest-open) (cdr closest-open))))
1937 (- (cl-fourth match-d) (cl-third match-d))))
1938 (end-regexp
1939 (markdown-maybe-funcall-regexp
1940 (cl-caadr
1941 (cl-find-if
1942 (lambda (entry) (eq (cl-cadar entry) (cdr closest-open)))
1943 markdown-fenced-block-pairs))
1944 length-of-open-match))
1945 (end-prop-loc
1946 (save-excursion
1947 (save-match-data
1948 (goto-char (car closest-open))
1949 (and (re-search-forward end-regexp start-pt t)
1950 (match-beginning 0))))))
1951 (and (not end-prop-loc) closest-open)))))
1953 (defun markdown-get-fenced-block-from-start (prop)
1954 "Return limits of an enclosing fenced block from its start, using PROP.
1955 Return value is a list usable as `match-data'."
1956 (catch 'no-rest-of-block
1957 (let* ((correct-entry
1958 (cl-find-if
1959 (lambda (entry) (eq (cl-cadar entry) prop))
1960 markdown-fenced-block-pairs))
1961 (begin-of-begin (cl-first (markdown-text-property-at-point prop)))
1962 (middle-prop (cl-third correct-entry))
1963 (end-prop (cl-cadadr correct-entry))
1964 (end-of-end
1965 (save-excursion
1966 (goto-char (match-end 0)) ; end of begin
1967 (unless (eobp) (forward-char))
1968 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
1969 (if (not mid-prop-v) ; no middle
1970 (progn
1971 ;; try to find end by advancing one
1972 (let ((end-prop-v
1973 (markdown-text-property-at-point end-prop)))
1974 (if end-prop-v (cl-second end-prop-v)
1975 (throw 'no-rest-of-block nil))))
1976 (set-match-data mid-prop-v)
1977 (goto-char (match-end 0)) ; end of middle
1978 (beginning-of-line) ; into end
1979 (cl-second (markdown-text-property-at-point end-prop)))))))
1980 (list begin-of-begin end-of-end))))
1982 (defun markdown-get-fenced-block-from-middle (prop)
1983 "Return limits of an enclosing fenced block from its middle, using PROP.
1984 Return value is a list usable as `match-data'."
1985 (let* ((correct-entry
1986 (cl-find-if
1987 (lambda (entry) (eq (cl-third entry) prop))
1988 markdown-fenced-block-pairs))
1989 (begin-prop (cl-cadar correct-entry))
1990 (begin-of-begin
1991 (save-excursion
1992 (goto-char (match-beginning 0))
1993 (unless (bobp) (forward-line -1))
1994 (beginning-of-line)
1995 (cl-first (markdown-text-property-at-point begin-prop))))
1996 (end-prop (cl-cadadr correct-entry))
1997 (end-of-end
1998 (save-excursion
1999 (goto-char (match-end 0))
2000 (beginning-of-line)
2001 (cl-second (markdown-text-property-at-point end-prop)))))
2002 (list begin-of-begin end-of-end)))
2004 (defun markdown-get-fenced-block-from-end (prop)
2005 "Return limits of an enclosing fenced block from its end, using PROP.
2006 Return value is a list usable as `match-data'."
2007 (let* ((correct-entry
2008 (cl-find-if
2009 (lambda (entry) (eq (cl-cadadr entry) prop))
2010 markdown-fenced-block-pairs))
2011 (end-of-end (cl-second (markdown-text-property-at-point prop)))
2012 (middle-prop (cl-third correct-entry))
2013 (begin-prop (cl-cadar correct-entry))
2014 (begin-of-begin
2015 (save-excursion
2016 (goto-char (match-beginning 0)) ; beginning of end
2017 (unless (bobp) (backward-char)) ; into middle
2018 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
2019 (if (not mid-prop-v)
2020 (progn
2021 (beginning-of-line)
2022 (cl-first (markdown-text-property-at-point begin-prop)))
2023 (set-match-data mid-prop-v)
2024 (goto-char (match-beginning 0)) ; beginning of middle
2025 (unless (bobp) (forward-line -1)) ; into beginning
2026 (beginning-of-line)
2027 (cl-first (markdown-text-property-at-point begin-prop)))))))
2028 (list begin-of-begin end-of-end)))
2030 (defun markdown-get-enclosing-fenced-block-construct (&optional pos)
2031 "Get \"fake\" match data for block enclosing POS.
2032 Returns fake match data which encloses the start, middle, and end
2033 of the block construct enclosing POS, if it exists. Used in
2034 `markdown-code-block-at-pos'."
2035 (save-excursion
2036 (when pos (goto-char pos))
2037 (beginning-of-line)
2038 (car
2039 (cl-remove-if
2040 #'null
2041 (cl-mapcar
2042 (lambda (fun-and-prop)
2043 (cl-destructuring-bind (fun prop) fun-and-prop
2044 (when prop
2045 (save-match-data
2046 (set-match-data (markdown-text-property-at-point prop))
2047 (funcall fun prop)))))
2048 `((markdown-get-fenced-block-from-start
2049 ,(cl-find-if
2050 #'markdown-text-property-at-point
2051 (markdown-get-fenced-block-begin-properties)))
2052 (markdown-get-fenced-block-from-middle
2053 ,(cl-find-if
2054 #'markdown-text-property-at-point
2055 (markdown-get-fenced-block-middle-properties)))
2056 (markdown-get-fenced-block-from-end
2057 ,(cl-find-if
2058 #'markdown-text-property-at-point
2059 (markdown-get-fenced-block-end-properties)))))))))
2061 (defun markdown-propertize-end-match (reg end fence-spec middle-begin)
2062 "Get match for REG up to END, if exists, and propertize appropriately.
2063 FENCE-SPEC is an entry in `markdown-fenced-block-pairs' and
2064 MIDDLE-BEGIN is the start of the \"middle\" section of the block."
2065 (when (re-search-forward reg end t)
2066 (let ((close-begin (match-beginning 0)) ; Start of closing line.
2067 (close-end (match-end 0)) ; End of closing line.
2068 (close-data (match-data t))) ; Match data for closing line.
2069 ;; Propertize middle section of fenced block.
2070 (put-text-property middle-begin close-begin
2071 (cl-third fence-spec)
2072 (list middle-begin close-begin))
2073 ;; Propertize closing line of fenced block.
2074 (put-text-property close-begin close-end
2075 (cl-cadadr fence-spec) close-data))))
2077 (defun markdown-syntax-propertize-fenced-block-constructs (start end)
2078 "Propertize according to `markdown-fenced-block-pairs' from START to END.
2079 If unable to propertize an entire block (if the start of a block is within START
2080 and END, but the end of the block is not), propertize the start section of a
2081 block, then in a subsequent call propertize both middle and end by finding the
2082 start which was previously propertized."
2083 (let ((start-reg (markdown-get-start-fence-regexp)))
2084 (save-excursion
2085 (goto-char start)
2086 ;; start from previous unclosed block, if exists
2087 (let ((prev-begin-block (markdown-find-previous-block)))
2088 (when prev-begin-block
2089 (let* ((correct-entry
2090 (cl-find-if (lambda (entry)
2091 (eq (cdr prev-begin-block) (cl-cadar entry)))
2092 markdown-fenced-block-pairs))
2093 (enclosed-text-start (1+ (car prev-begin-block)))
2094 (start-length
2095 (save-excursion
2096 (goto-char (car prev-begin-block))
2097 (string-match
2098 (markdown-maybe-funcall-regexp
2099 (caar correct-entry))
2100 (buffer-substring
2101 (point-at-bol) (point-at-eol)))
2102 (- (match-end 1) (match-beginning 1))))
2103 (end-reg (markdown-maybe-funcall-regexp
2104 (cl-caadr correct-entry) start-length)))
2105 (markdown-propertize-end-match
2106 end-reg end correct-entry enclosed-text-start))))
2107 ;; find all new blocks within region
2108 (while (re-search-forward start-reg end t)
2109 ;; we assume the opening constructs take up (only) an entire line,
2110 ;; so we re-check the current line
2111 (let* ((cur-line (buffer-substring (point-at-bol) (point-at-eol)))
2112 ;; find entry in `markdown-fenced-block-pairs' corresponding
2113 ;; to regex which was matched
2114 (correct-entry
2115 (cl-find-if
2116 (lambda (fenced-pair)
2117 (string-match-p
2118 (markdown-maybe-funcall-regexp (caar fenced-pair))
2119 cur-line))
2120 markdown-fenced-block-pairs))
2121 (enclosed-text-start
2122 (save-excursion (1+ (point-at-eol))))
2123 (end-reg
2124 (markdown-maybe-funcall-regexp
2125 (cl-caadr correct-entry)
2126 (if (and (match-beginning 1) (match-end 1))
2127 (- (match-end 1) (match-beginning 1))
2128 0))))
2129 ;; get correct match data
2130 (save-excursion
2131 (beginning-of-line)
2132 (re-search-forward
2133 (markdown-maybe-funcall-regexp (caar correct-entry))
2134 (point-at-eol)))
2135 ;; mark starting, even if ending is outside of region
2136 (put-text-property (match-beginning 0) (match-end 0)
2137 (cl-cadar correct-entry) (match-data t))
2138 (markdown-propertize-end-match
2139 end-reg end correct-entry enclosed-text-start))))))
2141 (defun markdown-syntax-propertize-blockquotes (start end)
2142 "Match blockquotes from START to END."
2143 (save-excursion
2144 (goto-char start)
2145 (while (and (re-search-forward markdown-regex-blockquote end t)
2146 (not (markdown-code-block-at-pos (match-beginning 0))))
2147 (put-text-property (match-beginning 0) (match-end 0)
2148 'markdown-blockquote
2149 (match-data t)))))
2151 (defun markdown-syntax-propertize-hrs (start end)
2152 "Match horizontal rules from START to END."
2153 (save-excursion
2154 (goto-char start)
2155 (while (re-search-forward markdown-regex-hr end t)
2156 (unless (or (markdown-on-heading-p)
2157 (markdown-code-block-at-point-p))
2158 (put-text-property (match-beginning 0) (match-end 0)
2159 'markdown-hr
2160 (match-data t))))))
2162 (defun markdown-syntax-propertize-yaml-metadata (start end)
2163 (save-excursion
2164 (goto-char start)
2165 (cl-loop
2166 while (re-search-forward markdown-regex-declarative-metadata end t)
2167 do (when (get-text-property (match-beginning 0)
2168 'markdown-yaml-metadata-section)
2169 (put-text-property (match-beginning 1) (match-end 1)
2170 'markdown-metadata-key (match-data t))
2171 (put-text-property (match-beginning 2) (match-end 2)
2172 'markdown-metadata-markup (match-data t))
2173 (put-text-property (match-beginning 3) (match-end 3)
2174 'markdown-metadata-value (match-data t))))))
2176 (defun markdown-syntax-propertize-headings (start end)
2177 "Match headings of type SYMBOL with REGEX from START to END."
2178 (goto-char start)
2179 (while (re-search-forward markdown-regex-header end t)
2180 (unless (markdown-code-block-at-pos (match-beginning 0))
2181 (put-text-property
2182 (match-beginning 0) (match-end 0) 'markdown-heading
2183 (match-data t))
2184 (put-text-property
2185 (match-beginning 0) (match-end 0)
2186 (cond ((match-string-no-properties 2) 'markdown-heading-1-setext)
2187 ((match-string-no-properties 3) 'markdown-heading-2-setext)
2188 (t (let ((atx-level (length (markdown-trim-whitespace
2189 (match-string-no-properties 4)))))
2190 (intern (format "markdown-heading-%d-atx" atx-level)))))
2191 (match-data t)))))
2193 (defun markdown-syntax-propertize-comments (start end)
2194 "Match HTML comments from the START to END."
2195 (let* ((in-comment (markdown-in-comment-p)))
2196 (goto-char start)
2197 (cond
2198 ;; Comment start
2199 ((and (not in-comment)
2200 (re-search-forward markdown-regex-comment-start end t)
2201 (not (markdown-inline-code-at-point-p))
2202 (not (markdown-code-block-at-point-p)))
2203 (let ((open-beg (match-beginning 0)))
2204 (put-text-property open-beg (1+ open-beg)
2205 'syntax-table (string-to-syntax "<"))
2206 (markdown-syntax-propertize-comments
2207 (min (1+ (match-end 0)) end (point-max)) end)))
2208 ;; Comment end
2209 ((and in-comment
2210 (re-search-forward markdown-regex-comment-end end t))
2211 (put-text-property (1- (match-end 0)) (match-end 0)
2212 'syntax-table (string-to-syntax ">"))
2213 (markdown-syntax-propertize-comments
2214 (min (1+ (match-end 0)) end (point-max)) end))
2215 ;; Nothing found
2216 (t nil))))
2218 (defvar markdown--syntax-properties
2219 (list 'markdown-tilde-fence-begin nil
2220 'markdown-tilde-fence-end nil
2221 'markdown-fenced-code nil
2222 'markdown-yaml-metadata-begin nil
2223 'markdown-yaml-metadata-end nil
2224 'markdown-yaml-metadata-section nil
2225 'markdown-gfm-block-begin nil
2226 'markdown-gfm-block-end nil
2227 'markdown-gfm-code nil
2228 'markdown-pre nil
2229 'markdown-blockquote nil
2230 'markdown-hr nil
2231 'markdown-heading nil
2232 'markdown-heading-1-setext nil
2233 'markdown-heading-2-setext nil
2234 'markdown-heading-1-atx nil
2235 'markdown-heading-2-atx nil
2236 'markdown-heading-3-atx nil
2237 'markdown-heading-4-atx nil
2238 'markdown-heading-5-atx nil
2239 'markdown-heading-6-atx nil
2240 'markdown-metadata-key nil
2241 'markdown-metadata-value nil
2242 'markdown-metadata-markup nil)
2243 "Property list of all Markdown syntactic properties.")
2245 (defun markdown-syntax-propertize (start end)
2246 "Function used as `syntax-propertize-function'.
2247 START and END delimit region to propertize."
2248 (with-silent-modifications
2249 (save-excursion
2250 (remove-text-properties start end markdown--syntax-properties)
2251 (markdown-syntax-propertize-fenced-block-constructs start end)
2252 (markdown-syntax-propertize-yaml-metadata start end)
2253 (markdown-syntax-propertize-pre-blocks start end)
2254 (markdown-syntax-propertize-blockquotes start end)
2255 (markdown-syntax-propertize-headings start end)
2256 (markdown-syntax-propertize-hrs start end)
2257 (markdown-syntax-propertize-comments start end))))
2260 ;;; Markup Hiding
2262 (defconst markdown-markup-properties
2263 '(face markdown-markup-face invisible markdown-markup)
2264 "List of properties and values to apply to markup.")
2266 (defconst markdown-language-keyword-properties
2267 '(face markdown-language-keyword-face invisible markdown-markup)
2268 "List of properties and values to apply to code block language names.")
2270 (defconst markdown-language-info-properties
2271 '(face markdown-language-info-face invisible markdown-markup)
2272 "List of properties and values to apply to code block language info strings.")
2274 (defconst markdown-include-title-properties
2275 '(face markdown-link-title-face invisible markdown-markup)
2276 "List of properties and values to apply to included code titles.")
2278 (defconst markdown-inline-footnote-properties
2279 '(face nil display ((raise 0.2) (height 0.8)))
2280 "Properties to apply to footnote markers and inline footnotes.")
2282 (defcustom markdown-hide-markup nil
2283 "Determines whether markup in the buffer will be hidden.
2284 When set to nil, all markup is displayed in the buffer as it
2285 appears in the file. An exception is when `markdown-hide-urls'
2286 is non-nil.
2287 Set this to a non-nil value to turn this feature on by default.
2288 You can interactively toggle the value of this variable with
2289 `markdown-toggle-markup-hiding', \\[markdown-toggle-markup-hiding],
2290 or from the Markdown > Show & Hide menu."
2291 :group 'markdown
2292 :type 'boolean
2293 :safe 'booleanp
2294 :package-version '(markdown-mode . "2.3"))
2295 (make-variable-buffer-local 'markdown-hide-markup)
2297 (defun markdown-toggle-markup-hiding (&optional arg)
2298 "Toggle the display or hiding of markup.
2299 With a prefix argument ARG, enable markup hiding if ARG is positive,
2300 and disable it otherwise."
2301 (interactive (list (or current-prefix-arg 'toggle)))
2302 (setq markdown-hide-markup
2303 (if (eq arg 'toggle)
2304 (not markdown-hide-markup)
2305 (> (prefix-numeric-value arg) 0)))
2306 (if markdown-hide-markup
2307 (progn (add-to-invisibility-spec 'markdown-markup)
2308 (message "markdown-mode markup hiding enabled"))
2309 (progn (remove-from-invisibility-spec 'markdown-markup)
2310 (message "markdown-mode markup hiding disabled")))
2311 (markdown-reload-extensions))
2314 ;;; Font Lock =================================================================
2316 (require 'font-lock)
2318 (defvar markdown-italic-face 'markdown-italic-face
2319 "Face name to use for italic text.")
2321 (defvar markdown-bold-face 'markdown-bold-face
2322 "Face name to use for bold text.")
2324 (defvar markdown-strike-through-face 'markdown-strike-through-face
2325 "Face name to use for strike-through text.")
2327 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
2328 "Face name to use as a base for header delimiters.")
2330 (defvar markdown-header-rule-face 'markdown-header-rule-face
2331 "Face name to use as a base for header rules.")
2333 (defvar markdown-header-face 'markdown-header-face
2334 "Face name to use as a base for headers.")
2336 (defvar markdown-header-face-1 'markdown-header-face-1
2337 "Face name to use for level-1 headers.")
2339 (defvar markdown-header-face-2 'markdown-header-face-2
2340 "Face name to use for level-2 headers.")
2342 (defvar markdown-header-face-3 'markdown-header-face-3
2343 "Face name to use for level-3 headers.")
2345 (defvar markdown-header-face-4 'markdown-header-face-4
2346 "Face name to use for level-4 headers.")
2348 (defvar markdown-header-face-5 'markdown-header-face-5
2349 "Face name to use for level-5 headers.")
2351 (defvar markdown-header-face-6 'markdown-header-face-6
2352 "Face name to use for level-6 headers.")
2354 (defvar markdown-inline-code-face 'markdown-inline-code-face
2355 "Face name to use for inline code.")
2357 (defvar markdown-list-face 'markdown-list-face
2358 "Face name to use for list markers.")
2360 (defvar markdown-blockquote-face 'markdown-blockquote-face
2361 "Face name to use for blockquote.")
2363 (defvar markdown-pre-face 'markdown-pre-face
2364 "Face name to use for preformatted text.")
2366 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
2367 "Face name to use for programming language identifiers.")
2369 (defvar markdown-language-info-face 'markdown-language-info-face
2370 "Face name to use for programming info strings.")
2372 (defvar markdown-link-face 'markdown-link-face
2373 "Face name to use for links.")
2375 (defvar markdown-missing-link-face 'markdown-missing-link-face
2376 "Face name to use for links where the linked file does not exist.")
2378 (defvar markdown-reference-face 'markdown-reference-face
2379 "Face name to use for reference.")
2381 (defvar markdown-footnote-marker-face 'markdown-footnote-marker-face
2382 "Face name to use for footnote markers.")
2384 (defvar markdown-url-face 'markdown-url-face
2385 "Face name to use for URLs.")
2387 (defvar markdown-link-title-face 'markdown-link-title-face
2388 "Face name to use for reference link titles.")
2390 (defvar markdown-line-break-face 'markdown-line-break-face
2391 "Face name to use for hard line breaks.")
2393 (defvar markdown-comment-face 'markdown-comment-face
2394 "Face name to use for HTML comments.")
2396 (defvar markdown-math-face 'markdown-math-face
2397 "Face name to use for LaTeX expressions.")
2399 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
2400 "Face name to use for metadata keys.")
2402 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
2403 "Face name to use for metadata values.")
2405 (defvar markdown-gfm-checkbox-face 'markdown-gfm-checkbox-face
2406 "Face name to use for GFM checkboxes.")
2408 (defvar markdown-highlight-face 'markdown-highlight-face
2409 "Face name to use for mouse highlighting.")
2411 (defvar markdown-markup-face 'markdown-markup-face
2412 "Face name to use for markup elements.")
2414 (defgroup markdown-faces nil
2415 "Faces used in Markdown Mode"
2416 :group 'markdown
2417 :group 'faces)
2419 (defface markdown-italic-face
2420 '((t (:inherit italic)))
2421 "Face for italic text."
2422 :group 'markdown-faces)
2424 (defface markdown-bold-face
2425 '((t (:inherit bold)))
2426 "Face for bold text."
2427 :group 'markdown-faces)
2429 (defface markdown-strike-through-face
2430 '((t (:strike-through t)))
2431 "Face for strike-through text."
2432 :group 'markdown-faces)
2434 (defface markdown-markup-face
2435 '((t (:inherit shadow :slant normal :weight normal)))
2436 "Face for markup elements."
2437 :group 'markdown-faces)
2439 (defface markdown-header-rule-face
2440 '((t (:inherit markdown-markup-face)))
2441 "Base face for headers rules."
2442 :group 'markdown-faces)
2444 (defface markdown-header-delimiter-face
2445 '((t (:inherit markdown-markup-face)))
2446 "Base face for headers hash delimiter."
2447 :group 'markdown-faces)
2449 (defface markdown-list-face
2450 '((t (:inherit markdown-markup-face)))
2451 "Face for list item markers."
2452 :group 'markdown-faces)
2454 (defface markdown-blockquote-face
2455 '((t (:inherit font-lock-doc-face)))
2456 "Face for blockquote sections."
2457 :group 'markdown-faces)
2459 (defface markdown-code-face
2460 `((t (:inherit fixed-pitch)))
2461 "Face for inline code, pre blocks, and fenced code blocks."
2462 :group 'markdown-faces)
2464 (defface markdown-inline-code-face
2465 '((t (:inherit markdown-code-face font-lock-constant-face)))
2466 "Face for inline code."
2467 :group 'markdown-faces)
2469 (defface markdown-pre-face
2470 '((t (:inherit (markdown-code-face font-lock-constant-face))))
2471 "Face for preformatted text."
2472 :group 'markdown-faces)
2474 (defface markdown-language-keyword-face
2475 '((t (:inherit font-lock-type-face)))
2476 "Face for programming language identifiers."
2477 :group 'markdown-faces)
2479 (defface markdown-language-info-face
2480 '((t (:inherit font-lock-string-face)))
2481 "Face for programming language info strings."
2482 :group 'markdown-faces)
2484 (defface markdown-link-face
2485 '((t (:inherit link)))
2486 "Face for links."
2487 :group 'markdown-faces)
2489 (defface markdown-missing-link-face
2490 '((t (:inherit font-lock-warning-face)))
2491 "Face for missing links."
2492 :group 'markdown-faces)
2494 (defface markdown-reference-face
2495 '((t (:inherit markdown-markup-face)))
2496 "Face for link references."
2497 :group 'markdown-faces)
2499 (define-obsolete-face-alias 'markdown-footnote-face
2500 'markdown-footnote-marker-face "v2.3")
2502 (defface markdown-footnote-marker-face
2503 '((t (:inherit markdown-markup-face)))
2504 "Face for footnote markers."
2505 :group 'markdown-faces)
2507 (defface markdown-footnote-text-face
2508 '((t (:inherit font-lock-comment-face)))
2509 "Face for footnote text."
2510 :group 'markdown-faces)
2512 (defface markdown-url-face
2513 '((t (:inherit font-lock-string-face)))
2514 "Face for URLs that are part of markup.
2515 For example, this applies to URLs in inline links:
2516 [link text](http://example.com/)."
2517 :group 'markdown-faces)
2519 (defface markdown-plain-url-face
2520 '((t (:inherit markdown-link-face)))
2521 "Face for URLs that are also links.
2522 For example, this applies to plain angle bracket URLs:
2523 <http://example.com/>."
2524 :group 'markdown-faces)
2526 (defface markdown-link-title-face
2527 '((t (:inherit font-lock-comment-face)))
2528 "Face for reference link titles."
2529 :group 'markdown-faces)
2531 (defface markdown-line-break-face
2532 '((t (:inherit font-lock-constant-face :underline t)))
2533 "Face for hard line breaks."
2534 :group 'markdown-faces)
2536 (defface markdown-comment-face
2537 '((t (:inherit font-lock-comment-face)))
2538 "Face for HTML comments."
2539 :group 'markdown-faces)
2541 (defface markdown-math-face
2542 '((t (:inherit font-lock-string-face)))
2543 "Face for LaTeX expressions."
2544 :group 'markdown-faces)
2546 (defface markdown-metadata-key-face
2547 '((t (:inherit font-lock-variable-name-face)))
2548 "Face for metadata keys."
2549 :group 'markdown-faces)
2551 (defface markdown-metadata-value-face
2552 '((t (:inherit font-lock-string-face)))
2553 "Face for metadata values."
2554 :group 'markdown-faces)
2556 (defface markdown-gfm-checkbox-face
2557 '((t (:inherit font-lock-builtin-face)))
2558 "Face for GFM checkboxes."
2559 :group 'markdown-faces)
2561 (defface markdown-highlight-face
2562 '((t (:inherit highlight)))
2563 "Face for mouse highlighting."
2564 :group 'markdown-faces)
2566 (defface markdown-hr-face
2567 '((t (:inherit markdown-markup-face)))
2568 "Face for horizontal rules."
2569 :group 'markdown-faces)
2571 (defcustom markdown-header-scaling nil
2572 "Whether to use variable-height faces for headers.
2573 When non-nil, `markdown-header-face' will inherit from
2574 `variable-pitch' and the scaling values in
2575 `markdown-header-scaling-values' will be applied to
2576 headers of levels one through six respectively."
2577 :type 'boolean
2578 :initialize 'custom-initialize-default
2579 :set (lambda (symbol value)
2580 (set-default symbol value)
2581 (markdown-update-header-faces value))
2582 :group 'markdown-faces
2583 :package-version '(markdown-mode . "2.2"))
2585 (defcustom markdown-header-scaling-values
2586 '(2.0 1.7 1.4 1.1 1.0 1.0)
2587 "List of scaling values for headers of level one through six.
2588 Used when `markdown-header-scaling' is non-nil."
2589 :type 'list
2590 :initialize 'custom-initialize-default
2591 :set (lambda (symbol value)
2592 (set-default symbol value)
2593 (markdown-update-header-faces markdown-header-scaling value))
2594 :group 'markdown-faces)
2596 (defun markdown-make-header-faces ()
2597 "Build the faces used for Markdown headers."
2598 (let ((inherit-faces '(font-lock-function-name-face)))
2599 (when markdown-header-scaling
2600 (setq inherit-faces (cons 'variable-pitch inherit-faces)))
2601 (defface markdown-header-face
2602 `((t (:inherit ,inherit-faces :weight bold)))
2603 "Base face for headers."
2604 :group 'markdown-faces))
2605 (dotimes (num 6)
2606 (let* ((num1 (1+ num))
2607 (face-name (intern (format "markdown-header-face-%s" num1)))
2608 (scale (if markdown-header-scaling
2609 (float (nth num markdown-header-scaling-values))
2610 1.0)))
2611 (eval
2612 `(defface ,face-name
2613 '((t (:inherit markdown-header-face :height ,scale)))
2614 (format "Face for level %s headers.
2615 You probably don't want to customize this face directly. Instead
2616 you can customize the base face `markdown-header-face' or the
2617 variable-height variable `markdown-header-scaling'." ,num1)
2618 :group 'markdown-faces)))))
2620 (markdown-make-header-faces)
2622 (defun markdown-update-header-faces (&optional scaling scaling-values)
2623 "Update header faces, depending on if header SCALING is desired.
2624 If so, use given list of SCALING-VALUES relative to the baseline
2625 size of `markdown-header-face'."
2626 (dotimes (num 6)
2627 (let* ((face-name (intern (format "markdown-header-face-%s" (1+ num))))
2628 (scale (cond ((not scaling) 1.0)
2629 (scaling-values (float (nth num scaling-values)))
2630 (t (float (nth num markdown-header-scaling-values))))))
2631 (unless (get face-name 'saved-face) ; Don't update customized faces
2632 (set-face-attribute face-name nil :height scale)))))
2634 (defun markdown-update-code-face ()
2635 "Generate `markdown-code-face' for code block backgrounds.
2636 When using a light-background theme, darken the background slightly for
2637 code blocks. Similarly, when using a dark-background theme, lighten it
2638 slightly. If the face has been customized already, leave it alone."
2639 ;; Don't update customized faces
2640 (unless (get 'markdown-code-face 'saved-face)
2641 (let ((bg (face-background 'default)))
2642 (when (and bg (not (equal bg "unspecified-bg")))
2643 (set-face-attribute
2644 'markdown-code-face nil
2645 :background
2646 (cl-case (cdr (assq 'background-mode (frame-parameters)))
2647 ('light (color-darken-name bg 3))
2648 ('dark (color-lighten-name bg 3))))))))
2650 (defun markdown-syntactic-face (state)
2651 "Return font-lock face for characters with given STATE.
2652 See `font-lock-syntactic-face-function' for details."
2653 (let ((in-comment (nth 4 state)))
2654 (cond
2655 (in-comment 'markdown-comment-face)
2656 (t nil))))
2658 (defcustom markdown-list-item-bullets
2659 '("●" "◎" "○" "◆" "◇" "►" "•")
2660 "List of bullets to use for unordered lists.
2661 It can contain any number of symbols, which will be repeated.
2662 Depending on your font, some reasonable choices are:
2663 ♥ ● ◇ ✚ ✜ ☯ ◆ ♠ ♣ ♦ ❀ ◆ ◖ ▶ ► • ★ ▸."
2664 :group 'markdown
2665 :type '(repeat (string :tag "Bullet character"))
2666 :package-version '(markdown-mode . "2.3"))
2668 (defvar markdown-mode-font-lock-keywords-basic
2669 `((markdown-match-yaml-metadata-begin . ((1 markdown-markup-face)))
2670 (markdown-match-yaml-metadata-end . ((1 markdown-markup-face)))
2671 (markdown-match-yaml-metadata-key . ((1 markdown-metadata-key-face)
2672 (2 markdown-markup-face)
2673 (3 markdown-metadata-value-face)))
2674 (markdown-match-gfm-open-code-blocks . ((1 markdown-markup-properties)
2675 (2 markdown-markup-properties nil t)
2676 (3 markdown-language-keyword-properties nil t)
2677 (4 markdown-language-info-properties nil t)
2678 (5 markdown-markup-properties nil t)))
2679 (markdown-match-gfm-close-code-blocks . ((0 markdown-markup-properties)))
2680 (markdown-fontify-gfm-code-blocks)
2681 (markdown-match-fenced-start-code-block . ((1 markdown-markup-properties)
2682 (2 markdown-markup-properties nil t)
2683 (3 markdown-language-keyword-properties nil t)
2684 (4 markdown-language-info-properties nil t)
2685 (5 markdown-markup-properties nil t)))
2686 (markdown-match-fenced-end-code-block . ((0 markdown-markup-properties)))
2687 (markdown-fontify-fenced-code-blocks)
2688 (markdown-match-pre-blocks . ((0 markdown-pre-face)))
2689 (markdown-fontify-headings)
2690 (markdown-match-declarative-metadata . ((1 markdown-metadata-key-face)
2691 (2 markdown-markup-face)
2692 (3 markdown-metadata-value-face)))
2693 (markdown-match-pandoc-metadata . ((1 markdown-markup-face)
2694 (2 markdown-markup-face)
2695 (3 markdown-metadata-value-face)))
2696 (markdown-fontify-hrs)
2697 (markdown-match-code . ((1 markdown-markup-properties prepend)
2698 (2 markdown-inline-code-face prepend)
2699 (3 markdown-markup-properties prepend)))
2700 (,markdown-regex-kbd . ((1 markdown-markup-properties)
2701 (2 markdown-inline-code-face)
2702 (3 markdown-markup-properties)))
2703 (markdown-fontify-angle-uris)
2704 (,markdown-regex-email . 'markdown-plain-url-face)
2705 (markdown-fontify-list-items)
2706 (,markdown-regex-footnote . ((0 markdown-inline-footnote-properties)
2707 (1 markdown-markup-properties) ; [^
2708 (2 markdown-footnote-marker-face) ; label
2709 (3 markdown-markup-properties))) ; ]
2710 (,markdown-regex-pandoc-inline-footnote . ((0 markdown-inline-footnote-properties)
2711 (1 markdown-markup-properties) ; ^
2712 (2 markdown-markup-properties) ; [
2713 (3 'markdown-footnote-text-face) ; text
2714 (4 markdown-markup-properties))) ; ]
2715 (markdown-match-includes . ((1 markdown-markup-properties)
2716 (2 markdown-markup-properties nil t)
2717 (3 markdown-include-title-properties nil t)
2718 (4 markdown-markup-properties nil t)
2719 (5 markdown-markup-properties)
2720 (6 'markdown-url-face)
2721 (7 markdown-markup-properties)))
2722 (markdown-fontify-inline-links)
2723 (markdown-fontify-reference-links)
2724 (,markdown-regex-reference-definition . ((1 markdown-markup-face) ; [
2725 (2 markdown-reference-face) ; label
2726 (3 markdown-markup-face) ; ]
2727 (4 markdown-markup-face) ; :
2728 (5 markdown-url-face) ; url
2729 (6 markdown-link-title-face))) ; "title" (optional)
2730 (markdown-fontify-plain-uris)
2731 ;; Math mode $..$
2732 (markdown-match-math-single . ((1 markdown-markup-face prepend)
2733 (2 markdown-math-face append)
2734 (3 markdown-markup-face prepend)))
2735 ;; Math mode $$..$$
2736 (markdown-match-math-double . ((1 markdown-markup-face prepend)
2737 (2 markdown-math-face append)
2738 (3 markdown-markup-face prepend)))
2739 (markdown-match-bold . ((1 markdown-markup-properties prepend)
2740 (2 markdown-bold-face append)
2741 (3 markdown-markup-properties prepend)))
2742 (markdown-match-italic . ((1 markdown-markup-properties prepend)
2743 (2 markdown-italic-face append)
2744 (3 markdown-markup-properties prepend)))
2745 (,markdown-regex-strike-through . ((3 markdown-markup-properties)
2746 (4 markdown-strike-through-face)
2747 (5 markdown-markup-properties)))
2748 (,markdown-regex-line-break . (1 markdown-line-break-face prepend))
2749 (markdown-fontify-sub-superscripts)
2750 (markdown-match-inline-attributes . ((0 markdown-markup-properties prepend)))
2751 (markdown-match-leanpub-sections . ((0 markdown-markup-properties)))
2752 (markdown-fontify-blockquotes))
2753 "Syntax highlighting for Markdown files.")
2755 (defvar markdown-mode-font-lock-keywords nil
2756 "Default highlighting expressions for Markdown mode.
2757 This variable is defined as a buffer-local variable for dynamic
2758 extension support.")
2760 ;; Footnotes
2761 (defvar markdown-footnote-counter 0
2762 "Counter for footnote numbers.")
2763 (make-variable-buffer-local 'markdown-footnote-counter)
2765 (defconst markdown-footnote-chars
2766 "[[:alnum:]-]"
2767 "Regular expression matching any character that is allowed in a footnote identifier.")
2769 (defconst markdown-regex-footnote-definition
2770 (concat "^ \\{0,3\\}\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:\\(?:[ \t]+\\|$\\)")
2771 "Regular expression matching a footnote definition, capturing the label.")
2774 ;;; Compatibility =============================================================
2776 (defun markdown-replace-regexp-in-string (regexp rep string)
2777 "Replace ocurrences of REGEXP with REP in STRING.
2778 This is a compatibility wrapper to provide `replace-regexp-in-string'
2779 in XEmacs 21."
2780 (if (featurep 'xemacs)
2781 (replace-in-string string regexp rep)
2782 (replace-regexp-in-string regexp rep string)))
2784 ;; `markdown-use-region-p' is a compatibility function which checks
2785 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
2786 (eval-and-compile
2787 (cond
2788 ;; Emacs 24 and newer
2789 ((fboundp 'use-region-p)
2790 (defalias 'markdown-use-region-p 'use-region-p))
2791 ;; XEmacs
2792 ((fboundp 'region-active-p)
2793 (defalias 'markdown-use-region-p 'region-active-p))))
2795 ;; Use new names for outline-mode functions in Emacs 25 and later.
2796 (eval-and-compile
2797 (defalias 'markdown-hide-sublevels
2798 (if (fboundp 'outline-hide-sublevels)
2799 'outline-hide-sublevels
2800 'hide-sublevels))
2801 (defalias 'markdown-show-all
2802 (if (fboundp 'outline-show-all)
2803 'outline-show-all
2804 'show-all))
2805 (defalias 'markdown-hide-body
2806 (if (fboundp 'outline-hide-body)
2807 'outline-hide-body
2808 'hide-body))
2809 (defalias 'markdown-show-children
2810 (if (fboundp 'outline-show-children)
2811 'outline-show-children
2812 'show-children))
2813 (defalias 'markdown-show-subtree
2814 (if (fboundp 'outline-show-subtree)
2815 'outline-show-subtree
2816 'show-subtree))
2817 (defalias 'markdown-hide-subtree
2818 (if (fboundp 'outline-hide-subtree)
2819 'outline-hide-subtree
2820 'hide-subtree)))
2822 ;; Provide directory-name-p to Emacs 24
2823 (defsubst markdown-directory-name-p (name)
2824 "Return non-nil if NAME ends with a directory separator character.
2825 Taken from `directory-name-p' from Emacs 25 and provided here for
2826 backwards compatibility."
2827 (let ((len (length name))
2828 (lastc ?.))
2829 (if (> len 0)
2830 (setq lastc (aref name (1- len))))
2831 (or (= lastc ?/)
2832 (and (memq system-type '(windows-nt ms-dos))
2833 (= lastc ?\\)))))
2835 ;; Provide a function to find files recursively in Emacs 24.
2836 (defalias 'markdown-directory-files-recursively
2837 (if (fboundp 'directory-files-recursively)
2838 'directory-files-recursively
2839 (lambda (dir regexp)
2840 "Return list of all files under DIR that have file names matching REGEXP.
2841 This function works recursively. Files are returned in \"depth first\"
2842 order, and files from each directory are sorted in alphabetical order.
2843 Each file name appears in the returned list in its absolute form.
2844 Based on `directory-files-recursively' from Emacs 25 and provided
2845 here for backwards compatibility."
2846 (let ((result nil)
2847 (files nil)
2848 ;; When DIR is "/", remote file names like "/method:" could
2849 ;; also be offered. We shall suppress them.
2850 (tramp-mode (and tramp-mode (file-remote-p (expand-file-name dir)))))
2851 (dolist (file (sort (file-name-all-completions "" dir)
2852 'string<))
2853 (unless (member file '("./" "../"))
2854 (if (markdown-directory-name-p file)
2855 (let* ((leaf (substring file 0 (1- (length file))))
2856 (full-file (expand-file-name leaf dir)))
2857 (setq result
2858 (nconc result (markdown-directory-files-recursively
2859 full-file regexp))))
2860 (when (string-match-p regexp file)
2861 (push (expand-file-name file dir) files)))))
2862 (nconc result (nreverse files))))))
2864 (defun markdown-flyspell-check-word-p ()
2865 "Return t if `flyspell' should check word just before point.
2866 Used for `flyspell-generic-check-word-predicate'."
2867 (save-excursion
2868 (goto-char (1- (point)))
2869 (not (or (markdown-code-block-at-point-p)
2870 (markdown-inline-code-at-point-p)
2871 (markdown-in-comment-p)
2872 (let ((faces (get-text-property (point) 'face)))
2873 (if (listp faces)
2874 (or (memq 'markdown-reference-face faces)
2875 (memq 'markdown-markup-face faces)
2876 (memq 'markdown-plain-url-face faces)
2877 (memq 'markdown-inline-code-face faces)
2878 (memq 'markdown-url-face faces))
2879 (memq faces '(markdown-reference-face
2880 markdown-markup-face
2881 markdown-plain-url-face
2882 markdown-inline-code-face
2883 markdown-url-face))))))))
2885 (defun markdown-font-lock-ensure ()
2886 "Provide `font-lock-ensure' in Emacs 24."
2887 (if (fboundp 'font-lock-ensure)
2888 (font-lock-ensure)
2889 (with-no-warnings
2890 ;; Suppress warning about non-interactive use of
2891 ;; `font-lock-fontify-buffer' in Emacs 25.
2892 (font-lock-fontify-buffer))))
2895 ;;; Markdown Parsing Functions ================================================
2897 (defun markdown-cur-line-blank (&optional predicate)
2898 "Return t if the current line is blank and nil otherwise.
2899 When PREDICATE is non-nil, don't modify the match data."
2900 (save-excursion
2901 (beginning-of-line)
2902 (let ((regexp "^\\s *$"))
2903 (if predicate
2904 (looking-at-p regexp)
2905 (looking-at regexp)))))
2907 (defun markdown-cur-line-blank-p ()
2908 "Same as `markdown-cur-line-blank', but does not change the match data."
2909 (markdown-cur-line-blank t))
2911 (defun markdown-prev-line-blank (&optional predicate)
2912 "Return t if the previous line is blank and nil otherwise.
2913 If we are at the first line, then consider the previous line to be blank.
2914 When PREDICATE is non-nil, don't modify the match data."
2915 (or (= (line-beginning-position) (point-min))
2916 (save-excursion
2917 (forward-line -1)
2918 (markdown-cur-line-blank predicate))))
2920 (defun markdown-prev-line-blank-p ()
2921 "Same as `markdown-prev-line-blank', but does not change the match data."
2922 (markdown-prev-line-blank t))
2924 (defun markdown-next-line-blank (&optional predicate)
2925 "Return t if the next line is blank and nil otherwise.
2926 If we are at the last line, then consider the next line to be blank.
2927 When PREDICATE is non-nil, don't modify the match data."
2928 (or (= (line-end-position) (point-max))
2929 (save-excursion
2930 (forward-line 1)
2931 (markdown-cur-line-blank predicate))))
2933 (defun markdown-next-line-blank-p ()
2934 "Same as `markdown-next-line-blank', but does not change the match data."
2935 (markdown-next-line-blank t))
2937 (defun markdown-prev-line-indent ()
2938 "Return the number of leading whitespace characters in the previous line.
2939 Return 0 if the current line is the first line in the buffer."
2940 (save-excursion
2941 (if (= (line-beginning-position) (point-min))
2943 (forward-line -1)
2944 (current-indentation))))
2946 (defun markdown-next-line-indent ()
2947 "Return the number of leading whitespace characters in the next line.
2948 Return 0 if line is the last line in the buffer."
2949 (save-excursion
2950 (if (= (line-end-position) (point-max))
2952 (forward-line 1)
2953 (current-indentation))))
2955 (defun markdown-cur-non-list-indent ()
2956 "Return beginning position of list item text (not including the list marker).
2957 Return nil if the current line is not the beginning of a list item."
2958 (save-match-data
2959 (save-excursion
2960 (beginning-of-line)
2961 (when (re-search-forward markdown-regex-list (line-end-position) t)
2962 (current-column)))))
2964 (defun markdown-prev-non-list-indent ()
2965 "Return position of the first non-list-marker on the previous line."
2966 (save-excursion
2967 (forward-line -1)
2968 (markdown-cur-non-list-indent)))
2970 (defun markdown-new-baseline ()
2971 "Determine if the current line begins a new baseline level."
2972 (save-excursion
2973 (beginning-of-line)
2974 (or (looking-at markdown-regex-header)
2975 (looking-at markdown-regex-hr)
2976 (and (null (markdown-cur-non-list-indent))
2977 (= (current-indentation) 0)
2978 (markdown-prev-line-blank)))))
2980 (defun markdown-search-backward-baseline ()
2981 "Search backward baseline point with no indentation and not a list item."
2982 (end-of-line)
2983 (let (stop)
2984 (while (not (or stop (bobp)))
2985 (re-search-backward markdown-regex-block-separator-noindent nil t)
2986 (when (match-end 2)
2987 (goto-char (match-end 2))
2988 (cond
2989 ((markdown-new-baseline)
2990 (setq stop t))
2991 ((looking-at-p markdown-regex-list)
2992 (setq stop nil))
2993 (t (setq stop t)))))))
2995 (defun markdown-update-list-levels (marker indent levels)
2996 "Update list levels given list MARKER, block INDENT, and current LEVELS.
2997 Here, MARKER is a string representing the type of list, INDENT is an integer
2998 giving the indentation, in spaces, of the current block, and LEVELS is a
2999 list of the indentation levels of parent list items. When LEVELS is nil,
3000 it means we are at baseline (not inside of a nested list)."
3001 (cond
3002 ;; New list item at baseline.
3003 ((and marker (null levels))
3004 (setq levels (list indent)))
3005 ;; List item with greater indentation (four or more spaces).
3006 ;; Increase list level.
3007 ((and marker (>= indent (+ (car levels) 4)))
3008 (setq levels (cons indent levels)))
3009 ;; List item with greater or equal indentation (less than four spaces).
3010 ;; Do not increase list level.
3011 ((and marker (>= indent (car levels)))
3012 levels)
3013 ;; Lesser indentation level.
3014 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
3015 ;; indentation could move back more than one list level). Note
3016 ;; that this block need not be the beginning of list item.
3017 ((< indent (car levels))
3018 (while (and (> (length levels) 1)
3019 (< indent (+ (cadr levels) 4)))
3020 (setq levels (cdr levels)))
3021 levels)
3022 ;; Otherwise, do nothing.
3023 (t levels)))
3025 (defun markdown-calculate-list-levels ()
3026 "Calculate list levels at point.
3027 Return a list of the form (n1 n2 n3 ...) where n1 is the
3028 indentation of the deepest nested list item in the branch of
3029 the list at the point, n2 is the indentation of the parent
3030 list item, and so on. The depth of the list item is therefore
3031 the length of the returned list. If the point is not at or
3032 immediately after a list item, return nil."
3033 (save-excursion
3034 (let ((first (point)) levels indent pre-regexp)
3035 ;; Find a baseline point with zero list indentation
3036 (markdown-search-backward-baseline)
3037 ;; Search for all list items between baseline and LOC
3038 (while (and (< (point) first)
3039 (re-search-forward markdown-regex-list first t))
3040 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
3041 (beginning-of-line)
3042 (cond
3043 ;; Make sure this is not a header or hr
3044 ((markdown-new-baseline) (setq levels nil))
3045 ;; Make sure this is not a line from a pre block
3046 ((looking-at-p pre-regexp))
3047 ;; If not, then update levels
3049 (setq indent (current-indentation))
3050 (setq levels (markdown-update-list-levels (match-string 2)
3051 indent levels))))
3052 (end-of-line))
3053 levels)))
3055 (defun markdown-prev-list-item (level)
3056 "Search backward from point for a list item with indentation LEVEL.
3057 Set point to the beginning of the item, and return point, or nil
3058 upon failure."
3059 (let (bounds indent prev)
3060 (setq prev (point))
3061 (forward-line -1)
3062 (setq indent (current-indentation))
3063 (while
3064 (cond
3065 ;; List item
3066 ((and (looking-at-p markdown-regex-list)
3067 (setq bounds (markdown-cur-list-item-bounds)))
3068 (cond
3069 ;; Stop and return point at item of equal indentation
3070 ((= (nth 3 bounds) level)
3071 (setq prev (point))
3072 nil)
3073 ;; Stop and return nil at item with lesser indentation
3074 ((< (nth 3 bounds) level)
3075 (setq prev nil)
3076 nil)
3077 ;; Stop at beginning of buffer
3078 ((bobp) (setq prev nil))
3079 ;; Continue at item with greater indentation
3080 ((> (nth 3 bounds) level) t)))
3081 ;; Stop at beginning of buffer
3082 ((bobp) (setq prev nil))
3083 ;; Continue if current line is blank
3084 ((markdown-cur-line-blank-p) t)
3085 ;; Continue while indentation is the same or greater
3086 ((>= indent level) t)
3087 ;; Stop if current indentation is less than list item
3088 ;; and the next is blank
3089 ((and (< indent level)
3090 (markdown-next-line-blank-p))
3091 (setq prev nil))
3092 ;; Stop at a header
3093 ((looking-at-p markdown-regex-header) (setq prev nil))
3094 ;; Stop at a horizontal rule
3095 ((looking-at-p markdown-regex-hr) (setq prev nil))
3096 ;; Otherwise, continue.
3097 (t t))
3098 (forward-line -1)
3099 (setq indent (current-indentation)))
3100 prev))
3102 (defun markdown-next-list-item (level)
3103 "Search forward from point for the next list item with indentation LEVEL.
3104 Set point to the beginning of the item, and return point, or nil
3105 upon failure."
3106 (let (bounds indent next)
3107 (setq next (point))
3108 (if (looking-at markdown-regex-header-setext)
3109 (goto-char (match-end 0)))
3110 (forward-line)
3111 (setq indent (current-indentation))
3112 (while
3113 (cond
3114 ;; Stop at end of the buffer.
3115 ((eobp) nil)
3116 ;; Continue if the current line is blank
3117 ((markdown-cur-line-blank-p) t)
3118 ;; List item
3119 ((and (looking-at-p markdown-regex-list)
3120 (setq bounds (markdown-cur-list-item-bounds)))
3121 (cond
3122 ;; Continue at item with greater indentation
3123 ((> (nth 3 bounds) level) t)
3124 ;; Stop and return point at item of equal indentation
3125 ((= (nth 3 bounds) level)
3126 (setq next (point))
3127 nil)
3128 ;; Stop and return nil at item with lesser indentation
3129 ((< (nth 3 bounds) level)
3130 (setq next nil)
3131 nil)))
3132 ;; Continue while indentation is the same or greater
3133 ((>= indent level) t)
3134 ;; Stop if current indentation is less than list item
3135 ;; and the previous line was blank.
3136 ((and (< indent level)
3137 (markdown-prev-line-blank-p))
3138 (setq next nil))
3139 ;; Stop at a header
3140 ((looking-at-p markdown-regex-header) (setq next nil))
3141 ;; Stop at a horizontal rule
3142 ((looking-at-p markdown-regex-hr) (setq next nil))
3143 ;; Otherwise, continue.
3144 (t t))
3145 (forward-line)
3146 (setq indent (current-indentation)))
3147 next))
3149 (defun markdown-cur-list-item-end (level)
3150 "Move to the end of the current list item with nonlist indentation LEVEL.
3151 If the point is not in a list item, do nothing."
3152 (let (indent)
3153 (forward-line)
3154 (setq indent (current-indentation))
3155 (while
3156 (cond
3157 ;; Stop at end of the buffer.
3158 ((eobp) nil)
3159 ;; Continue if the current line is blank
3160 ((markdown-cur-line-blank-p) t)
3161 ;; Continue while indentation is the same or greater
3162 ((>= indent level) t)
3163 ;; Stop if current indentation is less than list item
3164 ;; and the previous line was blank.
3165 ((and (< indent level)
3166 (markdown-prev-line-blank-p))
3167 nil)
3168 ;; Stop at a new list item of the same or lesser indentation
3169 ((looking-at-p markdown-regex-list) nil)
3170 ;; Stop at a header
3171 ((looking-at-p markdown-regex-header) nil)
3172 ;; Stop at a horizontal rule
3173 ((looking-at-p markdown-regex-hr) nil)
3174 ;; Otherwise, continue.
3175 (t t))
3176 (forward-line)
3177 (setq indent (current-indentation)))
3178 ;; Don't skip over whitespace for empty list items (marker and
3179 ;; whitespace only), just move to end of whitespace.
3180 (if (looking-back (concat markdown-regex-list "\\s-*") nil)
3181 (goto-char (match-end 3))
3182 (skip-syntax-backward "-"))))
3184 (defun markdown-cur-list-item-bounds ()
3185 "Return bounds and indentation of the current list item.
3186 Return a list of the following form:
3188 (begin end indent nonlist-indent marker checkbox)
3190 The named components are:
3192 - begin: Position of beginning of list item, including leading indentation.
3193 - end: Position of the end of the list item, including list item text.
3194 - indent: Number of characters of indentation before list marker (an integer).
3195 - nonlist-indent: Number characters of indentation, list
3196 marker, and whitespace following list marker (an integer).
3197 - marker: String containing the list marker and following whitespace
3198 (e.g., \"- \" or \"* \").
3199 - checkbox: String containing the GFM checkbox portion, if any,
3200 including any trailing whitespace before the text
3201 begins (e.g., \"[x] \").
3203 As an example, for the following unordered list item
3205 - item
3207 the returned list would be
3209 (1 14 3 5 \"- \" nil)
3211 If the point is not inside a list item, return nil.
3212 Leave match data intact for `markdown-regex-list'."
3213 (save-excursion
3214 (let ((cur (point)))
3215 (end-of-line)
3216 (when (re-search-backward markdown-regex-list nil t)
3217 (let* ((begin (match-beginning 0))
3218 (indent (length (match-string-no-properties 1)))
3219 (nonlist-indent (length (match-string 0)))
3220 (marker (concat (match-string-no-properties 2)
3221 (match-string-no-properties 3)))
3222 (checkbox (progn (goto-char (match-end 0))
3223 (when (looking-at "\\[[xX ]\\]\\s-*")
3224 (match-string-no-properties 0))))
3225 (end (save-match-data
3226 (markdown-cur-list-item-end nonlist-indent)
3227 (point))))
3228 (when (and (>= cur begin) (<= cur end) nonlist-indent)
3229 (list begin end indent nonlist-indent marker checkbox)))))))
3231 (defun markdown-list-item-at-point-p ()
3232 "Return t if there is a list item at the point and nil otherwise."
3233 (save-match-data (markdown-cur-list-item-bounds)))
3235 (defun markdown-prev-list-item-bounds ()
3236 "Return bounds of previous item in the same list of any level.
3237 The return value has the same form as that of
3238 `markdown-cur-list-item-bounds'."
3239 (save-excursion
3240 (let ((cur-bounds (markdown-cur-list-item-bounds))
3241 (beginning-of-list (save-excursion (markdown-beginning-of-list)))
3242 stop)
3243 (when cur-bounds
3244 (goto-char (nth 0 cur-bounds))
3245 (while (and (not stop) (not (bobp))
3246 (re-search-backward markdown-regex-list
3247 beginning-of-list t))
3248 (unless (or (looking-at markdown-regex-hr)
3249 (markdown-code-block-at-point-p))
3250 (setq stop (point))))
3251 (markdown-cur-list-item-bounds)))))
3253 (defun markdown-next-list-item-bounds ()
3254 "Return bounds of next item in the same list of any level.
3255 The return value has the same form as that of
3256 `markdown-cur-list-item-bounds'."
3257 (save-excursion
3258 (let ((cur-bounds (markdown-cur-list-item-bounds))
3259 (end-of-list (save-excursion (markdown-end-of-list)))
3260 stop)
3261 (when cur-bounds
3262 (goto-char (nth 0 cur-bounds))
3263 (end-of-line)
3264 (while (and (not stop) (not (eobp))
3265 (re-search-forward markdown-regex-list
3266 end-of-list t))
3267 (unless (or (looking-at markdown-regex-hr)
3268 (markdown-code-block-at-point-p))
3269 (setq stop (point))))
3270 (when stop
3271 (markdown-cur-list-item-bounds))))))
3273 (defun markdown-beginning-of-list ()
3274 "Move point to beginning of list at point, if any."
3275 (interactive)
3276 (let ((orig-point (point))
3277 (list-begin (save-excursion
3278 (markdown-search-backward-baseline)
3279 ;; Stop at next list item, regardless of the indentation.
3280 (markdown-next-list-item (point-max))
3281 (when (looking-at markdown-regex-list)
3282 (point)))))
3283 (when (and list-begin (<= list-begin orig-point))
3284 (goto-char list-begin))))
3286 (defun markdown-end-of-list ()
3287 "Move point to end of list at point, if any."
3288 (interactive)
3289 (let ((start (point))
3290 (end (save-excursion
3291 (when (markdown-beginning-of-list)
3292 ;; Items can't have nonlist-indent <= 1, so this
3293 ;; moves past all list items.
3294 (markdown-next-list-item 1)
3295 (skip-syntax-backward "-")
3296 (unless (eobp) (forward-char 1))
3297 (point)))))
3298 (when (and end (>= end start))
3299 (goto-char end))))
3301 (defun markdown-up-list ()
3302 "Move point to beginning of parent list item."
3303 (interactive)
3304 (let ((cur-bounds (markdown-cur-list-item-bounds)))
3305 (when cur-bounds
3306 (markdown-prev-list-item (1- (nth 3 cur-bounds)))
3307 (let ((up-bounds (markdown-cur-list-item-bounds)))
3308 (when (and up-bounds (< (nth 3 up-bounds) (nth 3 cur-bounds)))
3309 (point))))))
3311 (defun markdown-bounds-of-thing-at-point (thing)
3312 "Call `bounds-of-thing-at-point' for THING with slight modifications.
3313 Does not include trailing newlines when THING is 'line. Handles the
3314 end of buffer case by setting both endpoints equal to the value of
3315 `point-max', since an empty region will trigger empty markup insertion.
3316 Return bounds of form (beg . end) if THING is found, or nil otherwise."
3317 (let* ((bounds (bounds-of-thing-at-point thing))
3318 (a (car bounds))
3319 (b (cdr bounds)))
3320 (when bounds
3321 (when (eq thing 'line)
3322 (cond ((and (eobp) (markdown-cur-line-blank-p))
3323 (setq a b))
3324 ((char-equal (char-before b) ?\^J)
3325 (setq b (1- b)))))
3326 (cons a b))))
3328 (defun markdown-reference-definition (reference)
3329 "Find out whether Markdown REFERENCE is defined.
3330 REFERENCE should not include the square brackets.
3331 When REFERENCE is defined, return a list of the form (text start end)
3332 containing the definition text itself followed by the start and end
3333 locations of the text. Otherwise, return nil.
3334 Leave match data for `markdown-regex-reference-definition'
3335 intact additional processing."
3336 (let ((reference (downcase reference)))
3337 (save-excursion
3338 (goto-char (point-min))
3339 (catch 'found
3340 (while (re-search-forward markdown-regex-reference-definition nil t)
3341 (when (string= reference (downcase (match-string-no-properties 2)))
3342 (throw 'found
3343 (list (match-string-no-properties 5)
3344 (match-beginning 5) (match-end 5)))))))))
3346 (defun markdown-get-defined-references ()
3347 "Return a list of all defined reference labels (not including square brackets)."
3348 (save-excursion
3349 (goto-char (point-min))
3350 (let (refs)
3351 (while (re-search-forward markdown-regex-reference-definition nil t)
3352 (let ((target (match-string-no-properties 2)))
3353 (cl-pushnew target refs :test #'equal)))
3354 (reverse refs))))
3356 (defun markdown-get-used-uris ()
3357 "Return a list of all used URIs in the buffer."
3358 (save-excursion
3359 (goto-char (point-min))
3360 (let (uris)
3361 (while (re-search-forward
3362 (concat "\\(?:" markdown-regex-link-inline
3363 "\\|" markdown-regex-angle-uri
3364 "\\|" markdown-regex-uri
3365 "\\|" markdown-regex-email
3366 "\\)")
3367 nil t)
3368 (unless (or (markdown-inline-code-at-point-p)
3369 (markdown-code-block-at-point-p))
3370 (cl-pushnew (or (match-string-no-properties 6)
3371 (match-string-no-properties 10)
3372 (match-string-no-properties 12)
3373 (match-string-no-properties 13))
3374 uris :test #'equal)))
3375 (reverse uris))))
3377 (defun markdown-inline-code-at-pos (pos)
3378 "Return non-nil if there is an inline code fragment at POS.
3379 Return nil otherwise. Set match data according to
3380 `markdown-match-code' upon success.
3381 This function searches the block for a code fragment that
3382 contains the point using `markdown-match-code'. We do this
3383 because `thing-at-point-looking-at' does not work reliably with
3384 `markdown-regex-code'.
3386 The match data is set as follows:
3387 Group 1 matches the opening backquotes.
3388 Group 2 matches the code fragment itself, without backquotes.
3389 Group 3 matches the closing backquotes."
3390 (save-excursion
3391 (goto-char pos)
3392 (let ((old-point (point))
3393 (end-of-block (progn (markdown-end-of-text-block) (point)))
3394 found)
3395 (markdown-beginning-of-text-block)
3396 (while (and (markdown-match-code end-of-block)
3397 (setq found t)
3398 (< (match-end 0) old-point)))
3399 (and found ; matched something
3400 (<= (match-beginning 0) old-point) ; match contains old-point
3401 (>= (match-end 0) old-point)))))
3403 (defun markdown-inline-code-at-pos-p (pos)
3404 "Return non-nil if there is an inline code fragment at POS.
3405 Like `markdown-inline-code-at-pos`, but preserves match data."
3406 (save-match-data (markdown-inline-code-at-pos pos)))
3408 (defun markdown-inline-code-at-point ()
3409 "Return non-nil if the point is at an inline code fragment.
3410 See `markdown-inline-code-at-pos' for details."
3411 (markdown-inline-code-at-pos (point)))
3413 (defun markdown-inline-code-at-point-p ()
3414 "Return non-nil if there is inline code at the point.
3415 This is a predicate function counterpart to
3416 `markdown-inline-code-at-point' which does not modify the match
3417 data. See `markdown-code-block-at-point-p' for code blocks."
3418 (save-match-data (markdown-inline-code-at-pos (point))))
3420 (make-obsolete 'markdown-code-at-point-p 'markdown-inline-code-at-point-p "v2.2")
3422 (defun markdown-code-block-at-pos (pos)
3423 "Return match data list if there is a code block at POS.
3424 Uses text properties at the beginning of the line position.
3425 This includes pre blocks, tilde-fenced code blocks, and GFM
3426 quoted code blocks. Return nil otherwise."
3427 (setq pos (save-excursion (goto-char pos) (point-at-bol)))
3428 (or (get-text-property pos 'markdown-pre)
3429 (markdown-get-enclosing-fenced-block-construct pos)
3430 ;; polymode removes text properties set by markdown-mode, so
3431 ;; check if `poly-markdown-mode' is active and whether the
3432 ;; `chunkmode' property is non-nil at POS.
3433 (and (bound-and-true-p poly-markdown-mode)
3434 (get-text-property pos 'chunkmode))))
3436 ;; Function was renamed to emphasize that it does not modify match-data.
3437 (defalias 'markdown-code-block-at-point 'markdown-code-block-at-point-p)
3439 (defun markdown-code-block-at-point-p ()
3440 "Return non-nil if there is a code block at the point.
3441 This includes pre blocks, tilde-fenced code blocks, and GFM
3442 quoted code blocks. This function does not modify the match
3443 data. See `markdown-inline-code-at-point-p' for inline code."
3444 (save-match-data (markdown-code-block-at-pos (point))))
3446 (defun markdown-heading-at-point ()
3447 "Return non-nil if there is a heading at the point.
3448 Set match data for `markdown-regex-header'."
3449 (let ((match-data (get-text-property (point) 'markdown-heading)))
3450 (when match-data
3451 (set-match-data match-data)
3452 t)))
3454 (defun markdown-pipe-at-bol-p ()
3455 "Return non-nil if the line begins with a pipe symbol.
3456 This may be useful for tables and Pandoc's line_blocks extension."
3457 (char-equal (char-after (point-at-bol)) ?|))
3460 ;;; Markdown Font Lock Matching Functions =====================================
3462 (defun markdown-range-property-any (begin end prop prop-values)
3463 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
3464 Also returns t if PROP is a list containing one of the PROP-VALUES.
3465 Return nil otherwise."
3466 (let (props)
3467 (catch 'found
3468 (dolist (loc (number-sequence begin end))
3469 (when (setq props (get-text-property loc prop))
3470 (cond ((listp props)
3471 ;; props is a list, check for membership
3472 (dolist (val prop-values)
3473 (when (memq val props) (throw 'found loc))))
3475 ;; props is a scalar, check for equality
3476 (dolist (val prop-values)
3477 (when (eq val props) (throw 'found loc))))))))))
3479 (defun markdown-range-properties-exist (begin end props)
3480 (cl-loop
3481 for loc in (number-sequence begin end)
3482 with result = nil
3483 while (not
3484 (setq result
3485 (cl-some (lambda (prop) (get-text-property loc prop)) props)))
3486 finally return result))
3488 (defun markdown-match-inline-generic (regex last &optional faceless)
3489 "Match inline REGEX from the point to LAST.
3490 When FACELESS is non-nil, do not return matches where faces have been applied."
3491 (when (re-search-forward regex last t)
3492 (let ((bounds (markdown-code-block-at-pos (match-beginning 1)))
3493 (face (and faceless (text-property-not-all
3494 (match-beginning 0) (match-end 0) 'face nil))))
3495 (cond
3496 ;; In code block: move past it and recursively search again
3497 (bounds
3498 (when (< (goto-char (cl-second bounds)) last)
3499 (markdown-match-inline-generic regex last faceless)))
3500 ;; When faces are found in the match range, skip over the match and
3501 ;; recursively search again.
3502 (face
3503 (when (< (goto-char (match-end 0)) last)
3504 (markdown-match-inline-generic regex last faceless)))
3505 ;; Keep match data and return t when in bounds.
3507 (<= (match-end 0) last))))))
3509 (defun markdown-match-code (last)
3510 "Match inline code fragments from point to LAST."
3511 (unless (bobp)
3512 (backward-char 1))
3513 (when (markdown-match-inline-generic markdown-regex-code last)
3514 (let ((begin (match-beginning 1))
3515 (end (match-end 1))
3516 (open-begin (match-beginning 2))
3517 (open-end (match-end 2))
3518 (code-begin (match-beginning 3))
3519 (code-end (match-end 3))
3520 (close-begin (match-beginning 4))
3521 (close-end (match-end 4)))
3522 (if (or (markdown-in-comment-p begin)
3523 (markdown-in-comment-p end)
3524 (markdown-code-block-at-pos begin))
3525 (progn (goto-char (min (1+ begin) last))
3526 (when (< (point) last)
3527 (markdown-match-code last)))
3528 (set-match-data (list begin end
3529 open-begin open-end
3530 code-begin code-end
3531 close-begin close-end))
3532 t))))
3534 (defun markdown-match-bold (last)
3535 "Match inline bold from the point to LAST."
3536 (when (markdown-match-inline-generic markdown-regex-bold last)
3537 (let ((begin (match-beginning 2))
3538 (end (match-end 2)))
3539 (if (or (markdown-inline-code-at-pos-p begin)
3540 (markdown-inline-code-at-pos-p end)
3541 (markdown-in-comment-p)
3542 (markdown-range-property-any
3543 begin begin 'face '(markdown-url-face
3544 markdown-plain-url-face))
3545 (markdown-range-property-any
3546 begin end 'face '(markdown-inline-code-face
3547 markdown-math-face)))
3548 (progn (goto-char (min (1+ begin) last))
3549 (when (< (point) last)
3550 (markdown-match-italic last)))
3551 (set-match-data (list (match-beginning 2) (match-end 2)
3552 (match-beginning 3) (match-end 3)
3553 (match-beginning 4) (match-end 4)
3554 (match-beginning 5) (match-end 5)))
3555 t))))
3557 (defun markdown-match-italic (last)
3558 "Match inline italics from the point to LAST."
3559 (let ((regex (if (eq major-mode 'gfm-mode)
3560 markdown-regex-gfm-italic markdown-regex-italic)))
3561 (when (markdown-match-inline-generic regex last)
3562 (let ((begin (match-beginning 1))
3563 (end (match-end 1)))
3564 (if (or (markdown-inline-code-at-pos-p begin)
3565 (markdown-inline-code-at-pos-p end)
3566 (markdown-in-comment-p)
3567 (markdown-range-property-any
3568 begin begin 'face '(markdown-url-face
3569 markdown-plain-url-face))
3570 (markdown-range-property-any
3571 begin end 'face '(markdown-inline-code-face
3572 markdown-bold-face
3573 markdown-list-face
3574 markdown-math-face)))
3575 (progn (goto-char (min (1+ begin) last))
3576 (when (< (point) last)
3577 (markdown-match-italic last)))
3578 (set-match-data (list (match-beginning 1) (match-end 1)
3579 (match-beginning 2) (match-end 2)
3580 (match-beginning 3) (match-end 3)
3581 (match-beginning 4) (match-end 4)))
3582 t)))))
3584 (defun markdown-match-math-generic (regex last)
3585 "Match REGEX from point to LAST.
3586 REGEX is either `markdown-regex-math-inline-single' for matching
3587 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
3588 (when (and markdown-enable-math (markdown-match-inline-generic regex last))
3589 (let ((begin (match-beginning 1)) (end (match-end 1)))
3590 (prog1
3591 (if (or (markdown-range-property-any
3592 begin end 'face (list markdown-inline-code-face
3593 markdown-bold-face))
3594 (markdown-range-properties-exist
3595 begin end
3596 (markdown-get-fenced-block-middle-properties)))
3597 (markdown-match-math-generic regex last)
3599 (goto-char (1+ (match-end 0)))))))
3601 (defun markdown-match-list-items (last)
3602 "Match list items from point to LAST."
3603 (when (markdown-match-inline-generic markdown-regex-list last)
3604 (let ((begin (match-beginning 2))
3605 (end (match-end 2)))
3606 (if (or (markdown-range-property-any
3607 begin end 'face (list markdown-inline-code-face
3608 markdown-bold-face
3609 markdown-math-face))
3610 (markdown-range-properties-exist begin end '(markdown-hr))
3611 (markdown-in-comment-p))
3612 (progn (goto-char (min (1+ (match-end 0)) last))
3613 (markdown-match-list-items last))
3614 (set-match-data (list (match-beginning 0) (match-end 0)
3615 (match-beginning 1) (match-end 1)
3616 (match-beginning 2) (match-end 2)))
3617 (goto-char (1+ (match-end 0)))))))
3619 (defun markdown-match-math-single (last)
3620 "Match single quoted $..$ math from point to LAST."
3621 (markdown-match-math-generic markdown-regex-math-inline-single last))
3623 (defun markdown-match-math-double (last)
3624 "Match double quoted $$..$$ math from point to LAST."
3625 (markdown-match-math-generic markdown-regex-math-inline-double last))
3627 (defun markdown-match-propertized-text (property last)
3628 "Match text with PROPERTY from point to LAST.
3629 Restore match data previously stored in PROPERTY."
3630 (let ((saved (get-text-property (point) property))
3631 pos)
3632 (unless saved
3633 (setq pos (next-single-char-property-change (point) property nil last))
3634 (setq saved (get-text-property pos property)))
3635 (when saved
3636 (set-match-data saved)
3637 ;; Step at least one character beyond point. Otherwise
3638 ;; `font-lock-fontify-keywords-region' infloops.
3639 (goto-char (min (1+ (max (match-end 0) (point)))
3640 (point-max)))
3641 saved)))
3643 (defun markdown-match-pre-blocks (last)
3644 "Match preformatted blocks from point to LAST.
3645 Use data stored in 'markdown-pre text property during syntax
3646 analysis."
3647 (markdown-match-propertized-text 'markdown-pre last))
3649 (defun markdown-match-gfm-code-blocks (last)
3650 "Match GFM quoted code blocks from point to LAST.
3651 Use data stored in 'markdown-gfm-code text property during syntax
3652 analysis."
3653 (markdown-match-propertized-text 'markdown-gfm-code last))
3655 (defun markdown-match-gfm-open-code-blocks (last)
3656 (markdown-match-propertized-text 'markdown-gfm-block-begin last))
3658 (defun markdown-match-gfm-close-code-blocks (last)
3659 (markdown-match-propertized-text 'markdown-gfm-block-end last))
3661 (defun markdown-match-fenced-code-blocks (last)
3662 "Match fenced code blocks from the point to LAST."
3663 (markdown-match-propertized-text 'markdown-fenced-code last))
3665 (defun markdown-match-fenced-start-code-block (last)
3666 (markdown-match-propertized-text 'markdown-tilde-fence-begin last))
3668 (defun markdown-match-fenced-end-code-block (last)
3669 (markdown-match-propertized-text 'markdown-tilde-fence-end last))
3671 (defun markdown-match-blockquotes (last)
3672 "Match blockquotes from point to LAST.
3673 Use data stored in 'markdown-blockquote text property during syntax
3674 analysis."
3675 (markdown-match-propertized-text 'markdown-blockquote last))
3677 (defun markdown-match-hr (last)
3678 "Match horizontal rules comments from the point to LAST."
3679 (markdown-match-propertized-text 'markdown-hr last))
3681 (defun markdown-match-comments (last)
3682 "Match HTML comments from the point to LAST."
3683 (when (and (skip-syntax-forward "^<" last))
3684 (let ((beg (point)))
3685 (when (and (skip-syntax-forward "^>" last) (< (point) last))
3686 (forward-char)
3687 (set-match-data (list beg (point)))
3688 t))))
3690 (defun markdown-match-generic-links (last ref)
3691 "Match inline links from point to LAST.
3692 When REF is non-nil, match reference links instead of standard
3693 links with URLs."
3694 ;; Search for the next potential link (not in a code block).
3695 (while (and (progn
3696 ;; Clear match data to test for a match after functions returns.
3697 (set-match-data nil)
3698 (re-search-forward "\\(!\\)?\\(\\[\\)" last 'limit))
3699 ;; Keep searching if this is in a code block, inline
3700 ;; code, or a comment, or if it is include syntax.
3701 (or (markdown-code-block-at-point-p)
3702 (markdown-inline-code-at-pos-p (match-beginning 0))
3703 (markdown-inline-code-at-pos-p (match-end 0))
3704 (markdown-in-comment-p)
3705 (and (char-equal (char-after (point-at-bol)) ?<)
3706 (char-equal (char-after (1+ (point-at-bol))) ?<)))
3707 (< (point) last)))
3708 ;; Match opening exclamation point (optional) and left bracket.
3709 (when (match-beginning 2)
3710 (let* ((bang (match-beginning 1))
3711 (first-begin (match-beginning 2))
3712 ;; Find end of block to prevent matching across blocks.
3713 (end-of-block (save-excursion
3714 (progn
3715 (goto-char (match-beginning 2))
3716 (markdown-end-of-text-block)
3717 (point))))
3718 ;; Move over balanced expressions to closing right bracket.
3719 ;; Catch unbalanced expression errors and return nil.
3720 (first-end (condition-case nil
3721 (and (goto-char first-begin)
3722 (scan-sexps (point) 1))
3723 (error nil)))
3724 ;; Continue with point at CONT-POINT upon failure.
3725 (cont-point (min (1+ first-begin) last))
3726 second-begin second-end url-begin url-end
3727 title-begin title-end)
3728 ;; When bracket found, in range, and followed by a left paren/bracket...
3729 (when (and first-end (< first-end end-of-block) (goto-char first-end)
3730 (char-equal (char-after (point)) (if ref ?\[ ?\()))
3731 ;; Scan across balanced expressions for closing parenthesis/bracket.
3732 (setq second-begin (point)
3733 second-end (condition-case nil
3734 (scan-sexps (point) 1)
3735 (error nil)))
3736 ;; Check that closing parenthesis/bracket is in range.
3737 (if (and second-end (<= second-end end-of-block) (<= second-end last))
3738 (progn
3739 ;; Search for (optional) title inside closing parenthesis
3740 (when (and (not ref) (search-forward "\"" second-end t))
3741 (setq title-begin (1- (point))
3742 title-end (and (goto-char second-end)
3743 (search-backward "\"" (1+ title-begin) t))
3744 title-end (and title-end (1+ title-end))))
3745 ;; Store URL/reference range
3746 (setq url-begin (1+ second-begin)
3747 url-end (1- (or title-begin second-end)))
3748 ;; Set match data, move point beyond link, and return
3749 (set-match-data
3750 (list (or bang first-begin) second-end ; 0 - all
3751 bang (and bang (1+ bang)) ; 1 - bang
3752 first-begin (1+ first-begin) ; 2 - markup
3753 (1+ first-begin) (1- first-end) ; 3 - link text
3754 (1- first-end) first-end ; 4 - markup
3755 second-begin (1+ second-begin) ; 5 - markup
3756 url-begin url-end ; 6 - url/reference
3757 title-begin title-end ; 7 - title
3758 (1- second-end) second-end)) ; 8 - markup
3759 ;; Nullify cont-point and leave point at end and
3760 (setq cont-point nil)
3761 (goto-char second-end))
3762 ;; If no closing parenthesis in range, update continuation point
3763 (setq cont-point (min end-of-block second-begin))))
3764 (cond
3765 ;; On failure, continue searching at cont-point
3766 ((and cont-point (< cont-point last))
3767 (goto-char cont-point)
3768 (markdown-match-generic-links last ref))
3769 ;; No more text, return nil
3770 ((and cont-point (= cont-point last))
3771 nil)
3772 ;; Return t if a match occurred
3773 (t t)))))
3775 (defun markdown-match-inline-links (last)
3776 "Match standard inline links from point to LAST."
3777 (markdown-match-generic-links last nil))
3779 (defun markdown-match-reference-links (last)
3780 "Match inline reference links from point to LAST."
3781 (markdown-match-generic-links last t))
3783 (defun markdown-match-angle-uris (last)
3784 "Match angle bracket URIs from point to LAST."
3785 (when (markdown-match-inline-generic markdown-regex-angle-uri last)
3786 (goto-char (1+ (match-end 0)))))
3788 (defun markdown-match-plain-uris (last)
3789 "Match plain URIs from point to LAST."
3790 (when (markdown-match-inline-generic markdown-regex-uri last t)
3791 (goto-char (1+ (match-end 0)))))
3793 (defun markdown-get-match-boundaries (start-header end-header last &optional pos)
3794 (save-excursion
3795 (goto-char (or pos (point-min)))
3796 (cl-loop
3797 with cur-result = nil
3798 and st-hdr = (or start-header "\\`")
3799 and end-hdr = (or end-header "\n\n\\|\n\\'\\|\\'")
3800 while (and (< (point) last)
3801 (re-search-forward st-hdr last t)
3802 (progn
3803 (setq cur-result (match-data))
3804 (re-search-forward end-hdr nil t)))
3805 collect (list cur-result (match-data)))))
3807 (defvar markdown-conditional-search-function #'re-search-forward
3808 "Conditional search function used in `markdown-search-until-condition'.
3809 Made into a variable to allow for dynamic let-binding.")
3811 (defun markdown-search-until-condition (condition &rest args)
3812 (let (ret)
3813 (while (and (not ret) (apply markdown-conditional-search-function args))
3814 (setq ret (funcall condition)))
3815 ret))
3817 (defun markdown-match-generic-metadata
3818 (regexp last &optional start-header end-header)
3819 "Match generic metadata specified by REGEXP from the point to LAST.
3820 If START-HEADER is nil, we assume metadata can only occur at the
3821 very top of a file (\"\\`\"). If END-HEADER is nil, we assume it
3822 is \"\n\n\""
3823 (let* ((header-bounds
3824 (markdown-get-match-boundaries start-header end-header last))
3825 (enclosing-header
3826 (cl-find-if ; just take first if multiple
3827 (lambda (match-bounds)
3828 (cl-destructuring-bind (begin end) (cl-second match-bounds)
3829 (and (< (point) begin)
3830 (save-excursion (re-search-forward regexp end t)))))
3831 header-bounds))
3832 (header-begin
3833 (when enclosing-header (cl-second (cl-first enclosing-header))))
3834 (header-end
3835 (when enclosing-header (cl-first (cl-second enclosing-header)))))
3836 (cond ((null enclosing-header)
3837 ;; Don't match anything outside of a header.
3838 nil)
3839 ((markdown-search-until-condition
3840 (lambda () (> (point) header-begin)) regexp (min last header-end) t)
3841 ;; If a metadata item is found, it may span several lines.
3842 (let ((key-beginning (match-beginning 1))
3843 (key-end (match-end 1))
3844 (markup-begin (match-beginning 2))
3845 (markup-end (match-end 2))
3846 (value-beginning (match-beginning 3)))
3847 (set-match-data (list key-beginning (point) ; complete metadata
3848 key-beginning key-end ; key
3849 markup-begin markup-end ; markup
3850 value-beginning (point))) ; value
3852 (t nil))))
3854 (defun markdown-match-declarative-metadata (last)
3855 "Match declarative metadata from the point to LAST."
3856 (markdown-match-generic-metadata markdown-regex-declarative-metadata last))
3858 (defun markdown-match-pandoc-metadata (last)
3859 "Match Pandoc metadata from the point to LAST."
3860 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
3862 (defun markdown-match-yaml-metadata-begin (last)
3863 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last))
3865 (defun markdown-match-yaml-metadata-end (last)
3866 (markdown-match-propertized-text 'markdown-yaml-metadata-end last))
3868 (defun markdown-match-yaml-metadata-key (last)
3869 (markdown-match-propertized-text 'markdown-metadata-key last))
3871 (defun markdown-match-inline-attributes (last)
3872 "Match inline attributes from point to LAST."
3873 (when (markdown-match-inline-generic markdown-regex-inline-attributes last)
3874 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
3875 (markdown-inline-code-at-pos-p (match-end 0))
3876 (markdown-in-comment-p))
3877 t)))
3879 (defun markdown-match-leanpub-sections (last)
3880 "Match Leanpub section markers from point to LAST."
3881 (when (markdown-match-inline-generic markdown-regex-leanpub-sections last)
3882 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
3883 (markdown-inline-code-at-pos-p (match-end 0))
3884 (markdown-in-comment-p))
3885 t)))
3887 (defun markdown-match-includes (last)
3888 "Match include statements from point to LAST.
3889 Sets match data for the following seven groups:
3890 Group 1: opening two angle brackets
3891 Group 2: opening title delimiter (optional)
3892 Group 3: title text (optional)
3893 Group 4: closing title delimiter (optional)
3894 Group 5: opening filename delimiter
3895 Group 6: filename
3896 Group 7: closing filename delimiter"
3897 (when (markdown-match-inline-generic markdown-regex-include last)
3898 (let ((valid (not (or (markdown-in-comment-p (match-beginning 0))
3899 (markdown-in-comment-p (match-end 0))
3900 (markdown-code-block-at-pos (match-beginning 0))))))
3901 (cond
3902 ;; Parentheses and maybe square brackets, but no curly braces:
3903 ;; match optional title in square brackets and file in parentheses.
3904 ((and valid (match-beginning 5)
3905 (not (match-beginning 8)))
3906 (set-match-data (list (match-beginning 1) (match-end 7)
3907 (match-beginning 1) (match-end 1)
3908 (match-beginning 2) (match-end 2)
3909 (match-beginning 3) (match-end 3)
3910 (match-beginning 4) (match-end 4)
3911 (match-beginning 5) (match-end 5)
3912 (match-beginning 6) (match-end 6)
3913 (match-beginning 7) (match-end 7))))
3914 ;; Only square brackets present: match file in square brackets.
3915 ((and valid (match-beginning 2)
3916 (not (match-beginning 5))
3917 (not (match-beginning 7)))
3918 (set-match-data (list (match-beginning 1) (match-end 4)
3919 (match-beginning 1) (match-end 1)
3920 nil nil
3921 nil nil
3922 nil nil
3923 (match-beginning 2) (match-end 2)
3924 (match-beginning 3) (match-end 3)
3925 (match-beginning 4) (match-end 4))))
3926 ;; Only curly braces present: match file in curly braces.
3927 ((and valid (match-beginning 8)
3928 (not (match-beginning 2))
3929 (not (match-beginning 5)))
3930 (set-match-data (list (match-beginning 1) (match-end 10)
3931 (match-beginning 1) (match-end 1)
3932 nil nil
3933 nil nil
3934 nil nil
3935 (match-beginning 8) (match-end 8)
3936 (match-beginning 9) (match-end 9)
3937 (match-beginning 10) (match-end 10))))
3939 ;; Not a valid match, move to next line and search again.
3940 (forward-line)
3941 (when (< (point) last)
3942 (setq valid (markdown-match-includes last)))))
3943 valid)))
3946 ;;; Markdown Font Fontification Functions =====================================
3948 (defun markdown-fontify-headings (last)
3949 "Add text properties to headings from point to LAST."
3950 (when (markdown-match-propertized-text 'markdown-heading last)
3951 (let* ((level (markdown-outline-level))
3952 (heading-face
3953 (intern (format "markdown-header-face-%d" level)))
3954 (heading-props `(face ,heading-face))
3955 (markup-props `(face markdown-header-delimiter-face
3956 ,@(when markdown-hide-markup `(display ""))))
3957 (rule-props `(face markdown-header-rule-face
3958 ,@(when markdown-hide-markup `(display "")))))
3959 (if (match-end 1)
3960 ;; Setext heading
3961 (progn (add-text-properties
3962 (match-beginning 1) (match-end 1) heading-props)
3963 (if (= level 1)
3964 (add-text-properties
3965 (match-beginning 2) (match-end 2) rule-props)
3966 (add-text-properties
3967 (match-beginning 3) (match-end 3) rule-props)))
3968 ;; atx heading
3969 (add-text-properties
3970 (match-beginning 4) (match-end 4) markup-props)
3971 (add-text-properties
3972 (match-beginning 5) (match-end 5) heading-props)
3973 (when (match-end 6)
3974 (add-text-properties
3975 (match-beginning 6) (match-end 6) markup-props))))
3978 (defun markdown-fontify-blockquotes (last)
3979 "Apply font-lock properties to blockquotes from point to LAST."
3980 (when (markdown-match-blockquotes last)
3981 (add-text-properties
3982 (match-beginning 1) (match-end 1)
3983 (if markdown-hide-markup
3984 `(face markdown-blockquote-face
3985 display ,markdown-blockquote-display-char)
3986 `(face markdown-markup-face
3987 ,@(when markdown-hide-markup
3988 `(display ,markdown-blockquote-display-char)))))
3989 (font-lock-append-text-property
3990 (match-beginning 0) (match-end 0) 'face 'markdown-blockquote-face)
3993 (defun markdown-fontify-list-items (last)
3994 "Apply font-lock properties to list markers from point to LAST."
3995 (when (markdown-match-list-items last)
3996 (let* ((indent (length (match-string-no-properties 1)))
3997 (level (/ indent 4)) ;; level = 0, 1, 2, ...
3998 (bullet (nth (mod level (length markdown-list-item-bullets))
3999 markdown-list-item-bullets)))
4000 (add-text-properties
4001 (match-beginning 2) (match-end 2) '(face markdown-list-face))
4002 (when markdown-hide-markup
4003 (cond
4004 ;; Unordered lists
4005 ((string-match-p "[\\*\\+-]" (match-string 2))
4006 (add-text-properties
4007 (match-beginning 2) (match-end 2) `(display ,bullet)))
4008 ;; Definition lists
4009 ((string-equal ":" (match-string 2))
4010 (add-text-properties
4011 (match-beginning 2) (match-end 2)
4012 `(display ,(char-to-string markdown-definition-display-char)))))))
4015 (defun markdown-fontify-hrs (last)
4016 "Add text properties to horizontal rules from point to LAST."
4017 (when (markdown-match-hr last)
4018 (add-text-properties
4019 (match-beginning 0) (match-end 0)
4020 `(face markdown-hr-face
4021 font-lock-multiline t
4022 ,@(when markdown-hide-markup
4023 `(display ,(make-string
4024 (window-body-width) markdown-hr-display-char)))))
4027 (defun markdown-fontify-sub-superscripts (last)
4028 "Apply text properties to sub- and superscripts from point to LAST."
4029 (when (markdown-search-until-condition
4030 (lambda () (and (not (markdown-code-block-at-point-p))
4031 (not (markdown-inline-code-at-point-p))
4032 (not (markdown-in-comment-p))))
4033 markdown-regex-sub-superscript last t)
4034 (let* ((subscript-p (string= (match-string 2) "~"))
4035 (index (if subscript-p 0 1))
4036 (mp (list 'face 'markdown-markup-face
4037 'invisible 'markdown-markup)))
4038 (when markdown-hide-markup
4039 (put-text-property (match-beginning 3) (match-end 3)
4040 'display
4041 (nth index markdown-sub-superscript-display)))
4042 (add-text-properties (match-beginning 2) (match-end 2) mp)
4043 (add-text-properties (match-beginning 4) (match-end 4) mp)
4044 t)))
4047 ;;; Syntax Table ==============================================================
4049 (defvar markdown-mode-syntax-table
4050 (let ((tab (make-syntax-table text-mode-syntax-table)))
4051 (modify-syntax-entry ?\" "." tab)
4052 tab)
4053 "Syntax table for `markdown-mode'.")
4056 ;;; Element Insertion =========================================================
4058 (defun markdown-ensure-blank-line-before ()
4059 "If previous line is not already blank, insert a blank line before point."
4060 (unless (bolp) (insert "\n"))
4061 (unless (or (bobp) (looking-back "\n\\s-*\n" nil)) (insert "\n")))
4063 (defun markdown-ensure-blank-line-after ()
4064 "If following line is not already blank, insert a blank line after point.
4065 Return the point where it was originally."
4066 (save-excursion
4067 (unless (eolp) (insert "\n"))
4068 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
4070 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
4071 "Insert the strings S1 and S2, wrapping around region or THING.
4072 If a region is specified by the optional BEG and END arguments,
4073 wrap the strings S1 and S2 around that region.
4074 If there is an active region, wrap the strings S1 and S2 around
4075 the region. If there is not an active region but the point is at
4076 THING, wrap that thing (which defaults to word). Otherwise, just
4077 insert S1 and S2 and place the cursor in between. Return the
4078 bounds of the entire wrapped string, or nil if nothing was wrapped
4079 and S1 and S2 were only inserted."
4080 (let (a b bounds new-point)
4081 (cond
4082 ;; Given region
4083 ((and beg end)
4084 (setq a beg
4085 b end
4086 new-point (+ (point) (length s1))))
4087 ;; Active region
4088 ((markdown-use-region-p)
4089 (setq a (region-beginning)
4090 b (region-end)
4091 new-point (+ (point) (length s1))))
4092 ;; Thing (word) at point
4093 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
4094 (setq a (car bounds)
4095 b (cdr bounds)
4096 new-point (+ (point) (length s1))))
4097 ;; No active region and no word
4099 (setq a (point)
4100 b (point))))
4101 (goto-char b)
4102 (insert s2)
4103 (goto-char a)
4104 (insert s1)
4105 (when new-point (goto-char new-point))
4106 (if (= a b)
4108 (setq b (+ b (length s1) (length s2)))
4109 (cons a b))))
4111 (defun markdown-point-after-unwrap (cur prefix suffix)
4112 "Return desired position of point after an unwrapping operation.
4113 CUR gives the position of the point before the operation.
4114 Additionally, two cons cells must be provided. PREFIX gives the
4115 bounds of the prefix string and SUFFIX gives the bounds of the
4116 suffix string."
4117 (cond ((< cur (cdr prefix)) (car prefix))
4118 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
4119 ((<= cur (cdr suffix))
4120 (- cur (+ (- (cdr prefix) (car prefix))
4121 (- cur (car suffix)))))
4122 (t cur)))
4124 (defun markdown-unwrap-thing-at-point (regexp all text)
4125 "Remove prefix and suffix of thing at point and reposition the point.
4126 When the thing at point matches REGEXP, replace the subexpression
4127 ALL with the string in subexpression TEXT. Reposition the point
4128 in an appropriate location accounting for the removal of prefix
4129 and suffix strings. Return new bounds of string from group TEXT.
4130 When REGEXP is nil, assumes match data is already set."
4131 (when (or (null regexp)
4132 (thing-at-point-looking-at regexp))
4133 (let ((cur (point))
4134 (prefix (cons (match-beginning all) (match-beginning text)))
4135 (suffix (cons (match-end text) (match-end all)))
4136 (bounds (cons (match-beginning text) (match-end text))))
4137 ;; Replace the thing at point
4138 (replace-match (match-string text) t t nil all)
4139 ;; Reposition the point
4140 (goto-char (markdown-point-after-unwrap cur prefix suffix))
4141 ;; Adjust bounds
4142 (setq bounds (cons (car prefix)
4143 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
4145 (defun markdown-unwrap-things-in-region (beg end regexp all text)
4146 "Remove prefix and suffix of all things in region from BEG to END.
4147 When a thing in the region matches REGEXP, replace the
4148 subexpression ALL with the string in subexpression TEXT.
4149 Return a cons cell containing updated bounds for the region."
4150 (save-excursion
4151 (goto-char beg)
4152 (let ((removed 0) len-all len-text)
4153 (while (re-search-forward regexp (- end removed) t)
4154 (setq len-all (length (match-string-no-properties all)))
4155 (setq len-text (length (match-string-no-properties text)))
4156 (setq removed (+ removed (- len-all len-text)))
4157 (replace-match (match-string text) t t nil all))
4158 (cons beg (- end removed)))))
4160 (defun markdown-insert-hr (arg)
4161 "Insert or replace a horizonal rule.
4162 By default, use the first element of `markdown-hr-strings'. When
4163 ARG is non-nil, as when given a prefix, select a different
4164 element as follows. When prefixed with \\[universal-argument],
4165 use the last element of `markdown-hr-strings' instead. When
4166 prefixed with an integer from 1 to the length of
4167 `markdown-hr-strings', use the element in that position instead."
4168 (interactive "*P")
4169 (when (thing-at-point-looking-at markdown-regex-hr)
4170 (delete-region (match-beginning 0) (match-end 0)))
4171 (markdown-ensure-blank-line-before)
4172 (cond ((equal arg '(4))
4173 (insert (car (reverse markdown-hr-strings))))
4174 ((and (integerp arg) (> arg 0)
4175 (<= arg (length markdown-hr-strings)))
4176 (insert (nth (1- arg) markdown-hr-strings)))
4178 (insert (car markdown-hr-strings))))
4179 (markdown-ensure-blank-line-after))
4181 (defun markdown-insert-bold ()
4182 "Insert markup to make a region or word bold.
4183 If there is an active region, make the region bold. If the point
4184 is at a non-bold word, make the word bold. If the point is at a
4185 bold word or phrase, remove the bold markup. Otherwise, simply
4186 insert bold delimiters and place the cursor in between them."
4187 (interactive)
4188 (let ((delim (if markdown-bold-underscore "__" "**")))
4189 (if (markdown-use-region-p)
4190 ;; Active region
4191 (let ((bounds (markdown-unwrap-things-in-region
4192 (region-beginning) (region-end)
4193 markdown-regex-bold 2 4)))
4194 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4195 ;; Bold markup removal, bold word at point, or empty markup insertion
4196 (if (thing-at-point-looking-at markdown-regex-bold)
4197 (markdown-unwrap-thing-at-point nil 2 4)
4198 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4200 (defun markdown-insert-italic ()
4201 "Insert markup to make a region or word italic.
4202 If there is an active region, make the region italic. If the point
4203 is at a non-italic word, make the word italic. If the point is at an
4204 italic word or phrase, remove the italic markup. Otherwise, simply
4205 insert italic delimiters and place the cursor in between them."
4206 (interactive)
4207 (let ((delim (if markdown-italic-underscore "_" "*")))
4208 (if (markdown-use-region-p)
4209 ;; Active region
4210 (let ((bounds (markdown-unwrap-things-in-region
4211 (region-beginning) (region-end)
4212 markdown-regex-italic 1 3)))
4213 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4214 ;; Italic markup removal, italic word at point, or empty markup insertion
4215 (if (thing-at-point-looking-at markdown-regex-italic)
4216 (markdown-unwrap-thing-at-point nil 1 3)
4217 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4219 (defun markdown-insert-strike-through ()
4220 "Insert markup to make a region or word strikethrough.
4221 If there is an active region, make the region strikethrough. If the point
4222 is at a non-bold word, make the word strikethrough. If the point is at a
4223 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
4224 simply insert bold delimiters and place the cursor in between them."
4225 (interactive)
4226 (let ((delim "~~"))
4227 (if (markdown-use-region-p)
4228 ;; Active region
4229 (let ((bounds (markdown-unwrap-things-in-region
4230 (region-beginning) (region-end)
4231 markdown-regex-strike-through 2 4)))
4232 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4233 ;; Strikethrough markup removal, strikethrough word at point, or empty markup insertion
4234 (if (thing-at-point-looking-at markdown-regex-strike-through)
4235 (markdown-unwrap-thing-at-point nil 2 4)
4236 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4238 (defun markdown-insert-code ()
4239 "Insert markup to make a region or word an inline code fragment.
4240 If there is an active region, make the region an inline code
4241 fragment. If the point is at a word, make the word an inline
4242 code fragment. Otherwise, simply insert code delimiters and
4243 place the cursor in between them."
4244 (interactive)
4245 (if (markdown-use-region-p)
4246 ;; Active region
4247 (let ((bounds (markdown-unwrap-things-in-region
4248 (region-beginning) (region-end)
4249 markdown-regex-code 1 3)))
4250 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
4251 ;; Code markup removal, code markup for word, or empty markup insertion
4252 (if (markdown-inline-code-at-point)
4253 (markdown-unwrap-thing-at-point nil 0 2)
4254 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
4256 (defun markdown-insert-kbd ()
4257 "Insert markup to wrap region or word in <kbd> tags.
4258 If there is an active region, use the region. If the point is at
4259 a word, use the word. Otherwise, simply insert <kbd> tags and
4260 place the cursor in between them."
4261 (interactive)
4262 (if (markdown-use-region-p)
4263 ;; Active region
4264 (let ((bounds (markdown-unwrap-things-in-region
4265 (region-beginning) (region-end)
4266 markdown-regex-kbd 0 2)))
4267 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil (car bounds) (cdr bounds)))
4268 ;; Markup removal, markup for word, or empty markup insertion
4269 (if (thing-at-point-looking-at markdown-regex-kbd)
4270 (markdown-unwrap-thing-at-point nil 0 2)
4271 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil))))
4273 (defun markdown-insert-inline-link (text url &optional title)
4274 "Insert an inline link with TEXT pointing to URL.
4275 Optionally, the user can provide a TITLE."
4276 (let ((cur (point)))
4277 (setq title (and title (concat " \"" title "\"")))
4278 (insert (concat "[" text "](" url title ")"))
4279 (cond ((not text) (goto-char (+ 1 cur)))
4280 ((not url) (goto-char (+ 3 (length text) cur))))))
4282 (defun markdown-insert-inline-image (text url &optional title)
4283 "Insert an inline link with alt TEXT pointing to URL.
4284 Optionally, also provide a TITLE."
4285 (let ((cur (point)))
4286 (setq title (and title (concat " \"" title "\"")))
4287 (insert (concat "![" text "](" url title ")"))
4288 (cond ((not text) (goto-char (+ 2 cur)))
4289 ((not url) (goto-char (+ 4 (length text) cur))))))
4291 (defun markdown-insert-reference-link (text label &optional url title)
4292 "Insert a reference link and, optionally, a reference definition.
4293 The link TEXT will be inserted followed by the optional LABEL.
4294 If a URL is given, also insert a definition for the reference
4295 LABEL according to `markdown-reference-location'. If a TITLE is
4296 given, it will be added to the end of the reference definition
4297 and will be used to populate the title attribute when converted
4298 to XHTML. If URL is nil, insert only the link portion (for
4299 example, when a reference label is already defined)."
4300 (insert (concat "[" text "][" label "]"))
4301 (when url
4302 (markdown-insert-reference-definition
4303 (if (string-equal label "") text label)
4304 url title)))
4306 (defun markdown-insert-reference-image (text label &optional url title)
4307 "Insert a reference image and, optionally, a reference definition.
4308 The alt TEXT will be inserted followed by the optional LABEL.
4309 If a URL is given, also insert a definition for the reference
4310 LABEL according to `markdown-reference-location'. If a TITLE is
4311 given, it will be added to the end of the reference definition
4312 and will be used to populate the title attribute when converted
4313 to XHTML. If URL is nil, insert only the link portion (for
4314 example, when a reference label is already defined)."
4315 (insert (concat "![" text "][" label "]"))
4316 (when url
4317 (markdown-insert-reference-definition
4318 (if (string-equal label "") text label)
4319 url title)))
4321 (defun markdown-insert-reference-definition (label &optional url title)
4322 "Add definition for reference LABEL with URL and TITLE.
4323 LABEL is a Markdown reference label without square brackets.
4324 URL and TITLE are optional. When given, the TITLE will
4325 be used to populate the title attribute when converted to XHTML."
4326 ;; END specifies where to leave the point upon return
4327 (let ((end (point)))
4328 (cl-case markdown-reference-location
4329 (end (goto-char (point-max)))
4330 (immediately (markdown-end-of-text-block))
4331 (subtree (markdown-end-of-subtree))
4332 (header (markdown-end-of-defun)))
4333 (unless (or (markdown-cur-line-blank-p)
4334 (thing-at-point-looking-at markdown-regex-reference-definition))
4335 (insert "\n"))
4336 (insert "\n[" label "]: ")
4337 (if url
4338 (insert url)
4339 ;; When no URL is given, leave cursor at END following the colon
4340 (setq end (point)))
4341 (when (> (length title) 0)
4342 (insert " \"" title "\""))
4343 (unless (looking-at-p "\n")
4344 (insert "\n"))
4345 (goto-char end)
4346 (when url
4347 (message
4348 (markdown--substitute-command-keys
4349 "Reference [%s] was defined, press \\[markdown-do] to jump there")
4350 label))))
4352 (define-obsolete-function-alias
4353 'markdown-insert-inline-link-dwim 'markdown-insert-link "v2.3")
4354 (define-obsolete-function-alias
4355 'markdown-insert-reference-link-dwim 'markdown-insert-link "v2.3")
4357 (defun markdown--insert-link-or-image (image)
4358 "Interactively insert new or update an existing link or image.
4359 When IMAGE is non-nil, insert an image. Otherwise, insert a link.
4360 This is an internal function called by
4361 `markdown-insert-link' and `markdown-insert-image'."
4362 (cl-multiple-value-bind (begin end text uri ref title)
4363 (if (markdown-use-region-p)
4364 ;; Use region as either link text or URL as appropriate.
4365 (let ((region (buffer-substring-no-properties
4366 (region-beginning) (region-end))))
4367 (if (string-match markdown-regex-uri region)
4368 ;; Region contains a URL; use it as such.
4369 (list (region-beginning) (region-end)
4370 nil (match-string 0 region) nil nil)
4371 ;; Region doesn't contain a URL, so use it as text.
4372 (list (region-beginning) (region-end)
4373 region nil nil nil)))
4374 ;; Extract and use properties of existing link, if any.
4375 (markdown-link-at-pos (point)))
4376 (let* ((ref (when ref (concat "[" ref "]")))
4377 (defined-refs (append
4378 (mapcar (lambda (ref) (concat "[" ref "]"))
4379 (markdown-get-defined-references))))
4380 (used-uris (markdown-get-used-uris))
4381 (uri-or-ref (completing-read
4382 "URL or [reference]: "
4383 (append defined-refs used-uris)
4384 nil nil (or uri ref)))
4385 (ref (cond ((string-match "\\`\\[\\(.*\\)\\]\\'" uri-or-ref)
4386 (match-string 1 uri-or-ref))
4387 ((string-equal "" uri-or-ref)
4388 "")))
4389 (uri (unless ref uri-or-ref))
4390 (text-prompt (if image
4391 "Alt text: "
4392 (if ref
4393 "Link text: "
4394 "Link text (blank for plain URL): ")))
4395 (text (read-string text-prompt text))
4396 (text (if (= (length text) 0) nil text))
4397 (plainp (and uri (not text)))
4398 (implicitp (string-equal ref ""))
4399 (ref (if implicitp text ref))
4400 (definedp (and ref (markdown-reference-definition ref)))
4401 (ref-url (unless (or uri definedp)
4402 (completing-read "Reference URL: " used-uris)))
4403 (title (unless (or plainp definedp)
4404 (read-string "Title (tooltip text, optional): " title)))
4405 (title (if (= (length title) 0) nil title)))
4406 (when (and image implicitp)
4407 (user-error "Reference required: implicit image references are invalid"))
4408 (when (and begin end)
4409 (delete-region begin end))
4410 (cond
4411 ((and (not image) uri text)
4412 (markdown-insert-inline-link text uri title))
4413 ((and image uri text)
4414 (markdown-insert-inline-image text uri title))
4415 ((and ref text)
4416 (if image
4417 (markdown-insert-reference-image text (unless implicitp ref) nil title)
4418 (markdown-insert-reference-link text (unless implicitp ref) nil title))
4419 (unless definedp
4420 (markdown-insert-reference-definition ref ref-url title)))
4421 ((and (not image) uri)
4422 (markdown-insert-uri uri))))))
4424 (defun markdown-insert-link ()
4425 "Insert new or update an existing link, with interactive prompts.
4426 If the point is at an existing link or URL, update the link text,
4427 URL, reference label, and/or title. Otherwise, insert a new link.
4428 The type of link inserted (inline, reference, or plain URL)
4429 depends on which values are provided:
4431 * If a URL and TEXT are given, insert an inline link: [TEXT](URL).
4432 * If [REF] and TEXT are given, insert a reference link: [TEXT][REF].
4433 * If only TEXT is given, insert an implicit reference link: [TEXT][].
4434 * If only a URL is given, insert a plain link: <URL>.
4436 In other words, to create an implicit reference link, leave the
4437 URL prompt empty and to create a plain URL link, leave the link
4438 text empty.
4440 If there is an active region, use the text as the default URL, if
4441 it seems to be a URL, or link text value otherwise.
4443 If a given reference is not defined, this function will
4444 additionally prompt for the URL and optional title. In this case,
4445 the reference definition is placed at the location determined by
4446 `markdown-reference-location'.
4448 Through updating the link, this function can be used to convert a
4449 link of one type (inline, reference, or plain) to another type by
4450 selectively adding or removing information via the prompts."
4451 (interactive)
4452 (markdown--insert-link-or-image nil))
4454 (defun markdown-insert-image ()
4455 "Insert new or update an existing image, with interactive prompts.
4456 If the point is at an existing image, update the alt text, URL,
4457 reference label, and/or title. Otherwise, insert a new image.
4458 The type of image inserted (inline or reference) depends on which
4459 values are provided:
4461 * If a URL and ALT-TEXT are given, insert an inline image:
4462 ![ALT-TEXT](URL).
4463 * If [REF] and ALT-TEXT are given, insert a reference image:
4464 ![ALT-TEXT][REF].
4466 If there is an active region, use the text as the default URL, if
4467 it seems to be a URL, or alt text value otherwise.
4469 If a given reference is not defined, this function will
4470 additionally prompt for the URL and optional title. In this case,
4471 the reference definition is placed at the location determined by
4472 `markdown-reference-location'.
4474 Through updating the image, this function can be used to convert an
4475 image of one type (inline or reference) to another type by
4476 selectively adding or removing information via the prompts."
4477 (interactive)
4478 (markdown--insert-link-or-image t))
4480 (defun markdown-insert-uri (&optional uri)
4481 "Insert markup for an inline URI.
4482 If there is an active region, use it as the URI. If the point is
4483 at a URI, wrap it with angle brackets. If the point is at an
4484 inline URI, remove the angle brackets. Otherwise, simply insert
4485 angle brackets place the point between them."
4486 (interactive)
4487 (if (markdown-use-region-p)
4488 ;; Active region
4489 (let ((bounds (markdown-unwrap-things-in-region
4490 (region-beginning) (region-end)
4491 markdown-regex-angle-uri 0 2)))
4492 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
4493 ;; Markup removal, URI at point, new URI, or empty markup insertion
4494 (if (thing-at-point-looking-at markdown-regex-angle-uri)
4495 (markdown-unwrap-thing-at-point nil 0 2)
4496 (if uri
4497 (insert "<" uri ">")
4498 (markdown-wrap-or-insert "<" ">" 'url nil nil)))))
4500 (defun markdown-insert-wiki-link ()
4501 "Insert a wiki link of the form [[WikiLink]].
4502 If there is an active region, use the region as the link text.
4503 If the point is at a word, use the word as the link text. If
4504 there is no active region and the point is not at word, simply
4505 insert link markup."
4506 (interactive)
4507 (if (markdown-use-region-p)
4508 ;; Active region
4509 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
4510 ;; Markup removal, wiki link at at point, or empty markup insertion
4511 (if (thing-at-point-looking-at markdown-regex-wiki-link)
4512 (if (or markdown-wiki-link-alias-first
4513 (null (match-string 5)))
4514 (markdown-unwrap-thing-at-point nil 1 3)
4515 (markdown-unwrap-thing-at-point nil 1 5))
4516 (markdown-wrap-or-insert "[[" "]]"))))
4518 (defun markdown-remove-header ()
4519 "Remove header markup if point is at a header.
4520 Return bounds of remaining header text if a header was removed
4521 and nil otherwise."
4522 (interactive "*")
4523 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
4524 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
4526 (defun markdown-insert-header (&optional level text setext)
4527 "Insert or replace header markup.
4528 The level of the header is specified by LEVEL and header text is
4529 given by TEXT. LEVEL must be an integer from 1 and 6, and the
4530 default value is 1.
4531 When TEXT is nil, the header text is obtained as follows.
4532 If there is an active region, it is used as the header text.
4533 Otherwise, the current line will be used as the header text.
4534 If there is not an active region and the point is at a header,
4535 remove the header markup and replace with level N header.
4536 Otherwise, insert empty header markup and place the cursor in
4537 between.
4538 The style of the header will be atx (hash marks) unless
4539 SETEXT is non-nil, in which case a setext-style (underlined)
4540 header will be inserted."
4541 (interactive "p\nsHeader text: ")
4542 (setq level (min (max (or level 1) 1) (if setext 2 6)))
4543 ;; Determine header text if not given
4544 (when (null text)
4545 (if (markdown-use-region-p)
4546 ;; Active region
4547 (setq text (delete-and-extract-region (region-beginning) (region-end)))
4548 ;; No active region
4549 (markdown-remove-header)
4550 (setq text (delete-and-extract-region
4551 (line-beginning-position) (line-end-position)))
4552 (when (and setext (string-match-p "^[ \t]*$" text))
4553 (setq text (read-string "Header text: "))))
4554 (setq text (markdown-compress-whitespace-string text)))
4555 ;; Insertion with given text
4556 (markdown-ensure-blank-line-before)
4557 (let (hdr)
4558 (cond (setext
4559 (setq hdr (make-string (string-width text) (if (= level 2) ?- ?=)))
4560 (insert text "\n" hdr))
4562 (setq hdr (make-string level ?#))
4563 (insert hdr " " text)
4564 (when (null markdown-asymmetric-header) (insert " " hdr)))))
4565 (markdown-ensure-blank-line-after)
4566 ;; Leave point at end of text
4567 (cond (setext
4568 (backward-char (1+ (string-width text))))
4569 ((null markdown-asymmetric-header)
4570 (backward-char (1+ level)))))
4572 (defun markdown-insert-header-dwim (&optional arg setext)
4573 "Insert or replace header markup.
4574 The level and type of the header are determined automatically by
4575 the type and level of the previous header, unless a prefix
4576 argument is given via ARG.
4577 With a numeric prefix valued 1 to 6, insert a header of the given
4578 level, with the type being determined automatically (note that
4579 only level 1 or 2 setext headers are possible).
4581 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
4582 promote the heading by one level.
4583 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
4584 demote the heading by one level.
4585 When SETEXT is non-nil, prefer setext-style headers when
4586 possible (levels one and two).
4588 When there is an active region, use it for the header text. When
4589 the point is at an existing header, change the type and level
4590 according to the rules above.
4591 Otherwise, if the line is not empty, create a header using the
4592 text on the current line as the header text.
4593 Finally, if the point is on a blank line, insert empty header
4594 markup (atx) or prompt for text (setext).
4595 See `markdown-insert-header' for more details about how the
4596 header text is determined."
4597 (interactive "*P")
4598 (let (level)
4599 (save-excursion
4600 (when (or (thing-at-point-looking-at markdown-regex-header)
4601 (re-search-backward markdown-regex-header nil t))
4602 ;; level of current or previous header
4603 (setq level (markdown-outline-level))
4604 ;; match group 1 indicates a setext header
4605 (setq setext (match-end 1))))
4606 ;; check prefix argument
4607 (cond
4608 ((and (equal arg '(4)) level (> level 1)) ;; C-u
4609 (cl-decf level))
4610 ((and (equal arg '(16)) level (< level 6)) ;; C-u C-u
4611 (cl-incf level))
4612 (arg ;; numeric prefix
4613 (setq level (prefix-numeric-value arg))))
4614 ;; setext headers must be level one or two
4615 (and level (setq setext (and setext (<= level 2))))
4616 ;; insert the heading
4617 (markdown-insert-header level nil setext)))
4619 (defun markdown-insert-header-setext-dwim (&optional arg)
4620 "Insert or replace header markup, with preference for setext.
4621 See `markdown-insert-header-dwim' for details, including how ARG is handled."
4622 (interactive "*P")
4623 (markdown-insert-header-dwim arg t))
4625 (defun markdown-insert-header-atx-1 ()
4626 "Insert a first level atx-style (hash mark) header.
4627 See `markdown-insert-header'."
4628 (interactive "*")
4629 (markdown-insert-header 1 nil nil))
4631 (defun markdown-insert-header-atx-2 ()
4632 "Insert a level two atx-style (hash mark) header.
4633 See `markdown-insert-header'."
4634 (interactive "*")
4635 (markdown-insert-header 2 nil nil))
4637 (defun markdown-insert-header-atx-3 ()
4638 "Insert a level three atx-style (hash mark) header.
4639 See `markdown-insert-header'."
4640 (interactive "*")
4641 (markdown-insert-header 3 nil nil))
4643 (defun markdown-insert-header-atx-4 ()
4644 "Insert a level four atx-style (hash mark) header.
4645 See `markdown-insert-header'."
4646 (interactive "*")
4647 (markdown-insert-header 4 nil nil))
4649 (defun markdown-insert-header-atx-5 ()
4650 "Insert a level five atx-style (hash mark) header.
4651 See `markdown-insert-header'."
4652 (interactive "*")
4653 (markdown-insert-header 5 nil nil))
4655 (defun markdown-insert-header-atx-6 ()
4656 "Insert a sixth level atx-style (hash mark) header.
4657 See `markdown-insert-header'."
4658 (interactive "*")
4659 (markdown-insert-header 6 nil nil))
4661 (defun markdown-insert-header-setext-1 ()
4662 "Insert a setext-style (underlined) first-level header.
4663 See `markdown-insert-header'."
4664 (interactive "*")
4665 (markdown-insert-header 1 nil t))
4667 (defun markdown-insert-header-setext-2 ()
4668 "Insert a setext-style (underlined) second-level header.
4669 See `markdown-insert-header'."
4670 (interactive "*")
4671 (markdown-insert-header 2 nil t))
4673 (defun markdown-blockquote-indentation (loc)
4674 "Return string containing necessary indentation for a blockquote at LOC.
4675 Also see `markdown-pre-indentation'."
4676 (save-excursion
4677 (goto-char loc)
4678 (let* ((list-level (length (markdown-calculate-list-levels)))
4679 (indent ""))
4680 (dotimes (_ list-level indent)
4681 (setq indent (concat indent " "))))))
4683 (defun markdown-insert-blockquote ()
4684 "Start a blockquote section (or blockquote the region).
4685 If Transient Mark mode is on and a region is active, it is used as
4686 the blockquote text."
4687 (interactive)
4688 (if (markdown-use-region-p)
4689 (markdown-blockquote-region (region-beginning) (region-end))
4690 (markdown-ensure-blank-line-before)
4691 (insert (markdown-blockquote-indentation (point)) "> ")
4692 (markdown-ensure-blank-line-after)))
4694 (defun markdown-block-region (beg end prefix)
4695 "Format the region using a block prefix.
4696 Arguments BEG and END specify the beginning and end of the
4697 region. The characters PREFIX will appear at the beginning
4698 of each line."
4699 (save-excursion
4700 (let* ((end-marker (make-marker))
4701 (beg-marker (make-marker)))
4702 ;; Ensure blank line after and remove extra whitespace
4703 (goto-char end)
4704 (skip-syntax-backward "-")
4705 (set-marker end-marker (point))
4706 (delete-horizontal-space)
4707 (markdown-ensure-blank-line-after)
4708 ;; Ensure blank line before and remove extra whitespace
4709 (goto-char beg)
4710 (skip-syntax-forward "-")
4711 (delete-horizontal-space)
4712 (markdown-ensure-blank-line-before)
4713 (set-marker beg-marker (point))
4714 ;; Insert PREFIX before each line
4715 (goto-char beg-marker)
4716 (while (and (< (line-beginning-position) end-marker)
4717 (not (eobp)))
4718 (insert prefix)
4719 (forward-line)))))
4721 (defun markdown-blockquote-region (beg end)
4722 "Blockquote the region.
4723 Arguments BEG and END specify the beginning and end of the region."
4724 (interactive "*r")
4725 (markdown-block-region
4726 beg end (concat (markdown-blockquote-indentation
4727 (max (point-min) (1- beg))) "> ")))
4729 (defun markdown-pre-indentation (loc)
4730 "Return string containing necessary whitespace for a pre block at LOC.
4731 Also see `markdown-blockquote-indentation'."
4732 (save-excursion
4733 (goto-char loc)
4734 (let* ((list-level (length (markdown-calculate-list-levels)))
4735 indent)
4736 (dotimes (_ (1+ list-level) indent)
4737 (setq indent (concat indent " "))))))
4739 (defun markdown-insert-pre ()
4740 "Start a preformatted section (or apply to the region).
4741 If Transient Mark mode is on and a region is active, it is marked
4742 as preformatted text."
4743 (interactive)
4744 (if (markdown-use-region-p)
4745 (markdown-pre-region (region-beginning) (region-end))
4746 (markdown-ensure-blank-line-before)
4747 (insert (markdown-pre-indentation (point)))
4748 (markdown-ensure-blank-line-after)))
4750 (defun markdown-pre-region (beg end)
4751 "Format the region as preformatted text.
4752 Arguments BEG and END specify the beginning and end of the region."
4753 (interactive "*r")
4754 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
4755 (markdown-block-region beg end indent)))
4757 (defun markdown-electric-backquote (arg)
4758 "Insert a backquote.
4759 The numeric prefix argument ARG says how many times to repeat the insertion.
4760 Call `markdown-insert-gfm-code-block' interactively
4761 if three backquotes inserted at the beginning of line."
4762 (interactive "*P")
4763 (self-insert-command (prefix-numeric-value arg))
4764 (when (and markdown-gfm-use-electric-backquote (looking-back "^```" nil))
4765 (replace-match "")
4766 (call-interactively #'markdown-insert-gfm-code-block)))
4768 (defconst markdown-gfm-recognized-languages
4769 ;; To reproduce/update, evaluate the let-form in
4770 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
4771 ;; but with appropriate use of a keyboard macro, indenting and filling it
4772 ;; properly is pretty fast.
4773 '("1C-Enterprise" "ABAP" "ABNF" "AGS-Script" "AMPL" "ANTLR"
4774 "API-Blueprint" "APL" "ASN.1" "ASP" "ATS" "ActionScript" "Ada" "Agda"
4775 "Alloy" "Alpine-Abuild" "Ant-Build-System" "ApacheConf" "Apex"
4776 "Apollo-Guidance-Computer" "AppleScript" "Arc" "Arduino" "AsciiDoc"
4777 "AspectJ" "Assembly" "Augeas" "AutoHotkey" "AutoIt" "Awk" "Batchfile"
4778 "Befunge" "Bison" "BitBake" "Blade" "BlitzBasic" "BlitzMax" "Bluespec"
4779 "Boo" "Brainfuck" "Brightscript" "Bro" "C#" "C++" "C-ObjDump"
4780 "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "COLLADA" "CSON" "CSS" "CSV"
4781 "CWeb" "Cap'n-Proto" "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK"
4782 "Cirru" "Clarion" "Clean" "Click" "Clojure" "Closure-Templates"
4783 "CoffeeScript" "ColdFusion" "ColdFusion-CFC" "Common-Lisp"
4784 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal"
4785 "Csound" "Csound-Document" "Csound-Score" "Cuda" "Cycript" "Cython"
4786 "D-ObjDump" "DIGITAL-Command-Language" "DM" "DNS-Zone" "DTrace"
4787 "Darcs-Patch" "Dart" "Diff" "Dockerfile" "Dogescript" "Dylan" "EBNF"
4788 "ECL" "ECLiPSe" "EJS" "EQ" "Eagle" "Ecere-Projects" "Eiffel" "Elixir"
4789 "Elm" "Emacs-Lisp" "EmberScript" "Erlang" "F#" "FLUX" "Factor" "Fancy"
4790 "Fantom" "Filebench-WML" "Filterscript" "Formatted" "Forth" "Fortran"
4791 "FreeMarker" "Frege" "G-code" "GAMS" "GAP" "GCC-Machine-Description"
4792 "GDB" "GDScript" "GLSL" "GN" "Game-Maker-Language" "Genie" "Genshi"
4793 "Gentoo-Ebuild" "Gentoo-Eclass" "Gettext-Catalog" "Gherkin" "Glyph"
4794 "Gnuplot" "Go" "Golo" "Gosu" "Grace" "Gradle" "Grammatical-Framework"
4795 "Graph-Modeling-Language" "GraphQL" "Graphviz-(DOT)" "Groovy"
4796 "Groovy-Server-Pages" "HCL" "HLSL" "HTML" "HTML+Django" "HTML+ECR"
4797 "HTML+EEX" "HTML+ERB" "HTML+PHP" "HTTP" "Hack" "Haml" "Handlebars"
4798 "Harbour" "Haskell" "Haxe" "Hy" "HyPhy" "IDL" "IGOR-Pro" "INI"
4799 "IRC-log" "Idris" "Inform-7" "Inno-Setup" "Io" "Ioke" "Isabelle"
4800 "Isabelle-ROOT" "JFlex" "JSON" "JSON5" "JSONLD" "JSONiq" "JSX"
4801 "Jasmin" "Java" "Java-Server-Pages" "JavaScript" "Jison" "Jison-Lex"
4802 "Jolie" "Julia" "Jupyter-Notebook" "KRL" "KiCad" "Kit" "Kotlin" "LFE"
4803 "LLVM" "LOLCODE" "LSL" "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex"
4804 "LilyPond" "Limbo" "Linker-Script" "Linux-Kernel-Module" "Liquid"
4805 "Literate-Agda" "Literate-CoffeeScript" "Literate-Haskell"
4806 "LiveScript" "Logos" "Logtalk" "LookML" "LoomScript" "Lua" "M4"
4807 "M4Sugar" "MAXScript" "MQL4" "MQL5" "MTML" "MUF" "Makefile" "Mako"
4808 "Markdown" "Marko" "Mask" "Mathematica" "Matlab" "Maven-POM" "Max"
4809 "MediaWiki" "Mercury" "Meson" "Metal" "MiniD" "Mirah" "Modelica"
4810 "Modula-2" "Module-Management-System" "Monkey" "Moocode" "MoonScript"
4811 "Myghty" "NCL" "NL" "NSIS" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo"
4812 "NewLisp" "Nginx" "Nim" "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml"
4813 "ObjDump" "Objective-C" "Objective-C++" "Objective-J" "Omgrofl" "Opa"
4814 "Opal" "OpenCL" "OpenEdge-ABL" "OpenRC-runscript" "OpenSCAD"
4815 "OpenType-Feature-File" "Org" "Ox" "Oxygene" "Oz" "P4" "PAWN" "PHP"
4816 "PLSQL" "PLpgSQL" "POV-Ray-SDL" "Pan" "Papyrus" "Parrot"
4817 "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal" "Pep8"
4818 "Perl" "Perl6" "Pic" "Pickle" "PicoLisp" "PigLatin" "Pike" "Pod"
4819 "PogoScript" "Pony" "PostScript" "PowerBuilder" "PowerShell"
4820 "Processing" "Prolog" "Propeller-Spin" "Protocol-Buffer" "Public-Key"
4821 "Pug" "Puppet" "Pure-Data" "PureBasic" "PureScript" "Python"
4822 "Python-console" "Python-traceback" "QML" "QMake" "RAML" "RDoc"
4823 "REALbasic" "REXX" "RHTML" "RMarkdown" "RPM-Spec" "RUNOFF" "Racket"
4824 "Ragel" "Rascal" "Raw-token-data" "Reason" "Rebol" "Red" "Redcode"
4825 "Regular-Expression" "Ren'Py" "RenderScript" "RobotFramework" "Roff"
4826 "Rouge" "Ruby" "Rust" "SAS" "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL"
4827 "SRecode-Template" "STON" "SVG" "Sage" "SaltStack" "Sass" "Scala"
4828 "Scaml" "Scheme" "Scilab" "Self" "ShaderLab" "Shell" "ShellSession"
4829 "Shen" "Slash" "Slim" "Smali" "Smalltalk" "Smarty" "SourcePawn"
4830 "Spline-Font-Database" "Squirrel" "Stan" "Standard-ML" "Stata"
4831 "Stylus" "SubRip-Text" "Sublime-Text-Config" "SuperCollider" "Swift"
4832 "SystemVerilog" "TI-Program" "TLA" "TOML" "TXL" "Tcl" "Tcsh" "TeX"
4833 "Tea" "Terra" "Text" "Textile" "Thrift" "Turing" "Turtle" "Twig"
4834 "Type-Language" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset"
4835 "Unix-Assembly" "Uno" "UnrealScript" "UrWeb" "VCL" "VHDL" "Vala"
4836 "Verilog" "Vim-script" "Visual-Basic" "Volt" "Vue"
4837 "Wavefront-Material" "Wavefront-Object" "Web-Ontology-Language"
4838 "WebAssembly" "WebIDL" "World-of-Warcraft-Addon-Data" "X10" "XC"
4839 "XCompose" "XML" "XPages" "XProc" "XQuery" "XS" "XSLT" "Xojo" "Xtend"
4840 "YAML" "YANG" "Yacc" "Zephir" "Zimpl" "desktop" "eC" "edn" "fish"
4841 "mupad" "nesC" "ooc" "reStructuredText" "wisp" "xBase")
4842 "Language specifiers recognized by GitHub's syntax highlighting features.")
4844 (defvar markdown-gfm-used-languages nil
4845 "Language names used in GFM code blocks.")
4846 (make-variable-buffer-local 'markdown-gfm-used-languages)
4848 (defun markdown-trim-whitespace (str)
4849 (markdown-replace-regexp-in-string
4850 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str))
4852 (defun markdown-clean-language-string (str)
4853 (markdown-replace-regexp-in-string
4854 "{\\.?\\|}" "" (markdown-trim-whitespace str)))
4856 (defun markdown-validate-language-string (widget)
4857 (let ((str (widget-value widget)))
4858 (unless (string= str (markdown-clean-language-string str))
4859 (widget-put widget :error (format "Invalid language spec: '%s'" str))
4860 widget)))
4862 (defun markdown-gfm-get-corpus ()
4863 "Create corpus of recognized GFM code block languages for the given buffer."
4864 (let ((given-corpus (append markdown-gfm-additional-languages
4865 markdown-gfm-recognized-languages)))
4866 (append
4867 markdown-gfm-used-languages
4868 (if markdown-gfm-downcase-languages (cl-mapcar #'downcase given-corpus)
4869 given-corpus))))
4871 (defun markdown-gfm-add-used-language (lang)
4872 "Clean LANG and add to list of used languages."
4873 (setq markdown-gfm-used-languages
4874 (cons lang (remove lang markdown-gfm-used-languages))))
4876 (defcustom markdown-spaces-after-code-fence 1
4877 "Number of space characters to insert after a code fence.
4878 \\<gfm-mode-map>\\[markdown-insert-gfm-code-block] inserts this many spaces between an
4879 opening code fence and an info string."
4880 :group 'markdown
4881 :type 'integer
4882 :safe #'natnump
4883 :package-version '(markdown-mode . "2.3"))
4885 (defun markdown-insert-gfm-code-block (&optional lang)
4886 "Insert GFM code block for language LANG.
4887 If LANG is nil, the language will be queried from user. If a
4888 region is active, wrap this region with the markup instead. If
4889 the region boundaries are not on empty lines, these are added
4890 automatically in order to have the correct markup."
4891 (interactive
4892 (list (let ((completion-ignore-case nil))
4893 (condition-case nil
4894 (markdown-clean-language-string
4895 (completing-read
4896 "Programming language: "
4897 (markdown-gfm-get-corpus)
4898 nil 'confirm (car markdown-gfm-used-languages)
4899 'markdown-gfm-language-history))
4900 (quit "")))))
4901 (unless (string= lang "") (markdown-gfm-add-used-language lang))
4902 (when (> (length lang) 0)
4903 (setq lang (concat (make-string markdown-spaces-after-code-fence ?\s)
4904 lang)))
4905 (if (markdown-use-region-p)
4906 (let ((b (region-beginning)) (e (region-end)))
4907 (goto-char e)
4908 ;; if we're on a blank line, don't newline, otherwise the ```
4909 ;; should go on its own line
4910 (unless (looking-back "\n" nil)
4911 (newline))
4912 (insert "```")
4913 (markdown-ensure-blank-line-after)
4914 (goto-char b)
4915 ;; if we're on a blank line, insert the quotes here, otherwise
4916 ;; add a new line first
4917 (unless (looking-at-p "\n")
4918 (newline)
4919 (forward-line -1))
4920 (markdown-ensure-blank-line-before)
4921 (insert "```" lang))
4922 (markdown-ensure-blank-line-before)
4923 (insert "```" lang "\n\n```")
4924 (markdown-ensure-blank-line-after)
4925 (forward-line -1)))
4927 (defun markdown-code-block-lang (&optional pos-prop)
4928 "Return the language name for a GFM or tilde fenced code block.
4929 The beginning of the block may be described by POS-PROP,
4930 a cons of (pos . prop) giving the position and property
4931 at the beginning of the block."
4932 (or pos-prop
4933 (setq pos-prop
4934 (markdown-max-of-seq
4935 #'car
4936 (cl-remove-if
4937 #'null
4938 (cl-mapcar
4939 #'markdown-find-previous-prop
4940 (markdown-get-fenced-block-begin-properties))))))
4941 (when pos-prop
4942 (goto-char (car pos-prop))
4943 (set-match-data (get-text-property (point) (cdr pos-prop)))
4944 ;; Note: Hard-coded group number assumes tilde
4945 ;; and GFM fenced code regexp groups agree.
4946 (let ((begin (match-beginning 3))
4947 (end (match-end 3)))
4948 (when (and begin end)
4949 ;; Fix language strings beginning with periods, like ".ruby".
4950 (when (eq (char-after begin) ?.)
4951 (setq begin (1+ begin)))
4952 (buffer-substring-no-properties begin end)))))
4954 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer)
4955 (with-current-buffer (or buffer (current-buffer))
4956 (save-excursion
4957 (goto-char (point-min))
4958 (cl-loop
4959 with prop = 'markdown-gfm-block-begin
4960 for pos-prop = (markdown-find-next-prop prop)
4961 while pos-prop
4962 for lang = (markdown-code-block-lang pos-prop)
4963 do (progn (when lang (markdown-gfm-add-used-language lang))
4964 (goto-char (next-single-property-change (point) prop)))))))
4967 ;;; Footnotes ==================================================================
4969 (defun markdown-footnote-counter-inc ()
4970 "Increment `markdown-footnote-counter' and return the new value."
4971 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
4972 (save-excursion
4973 (goto-char (point-min))
4974 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
4975 (point-max) t)
4976 (let ((fn (string-to-number (match-string 1))))
4977 (when (> fn markdown-footnote-counter)
4978 (setq markdown-footnote-counter fn))))))
4979 (cl-incf markdown-footnote-counter))
4981 (defun markdown-insert-footnote ()
4982 "Insert footnote with a new number and move point to footnote definition."
4983 (interactive)
4984 (let ((fn (markdown-footnote-counter-inc)))
4985 (insert (format "[^%d]" fn))
4986 (markdown-footnote-text-find-new-location)
4987 (markdown-ensure-blank-line-before)
4988 (unless (markdown-cur-line-blank-p)
4989 (insert "\n"))
4990 (insert (format "[^%d]: " fn))
4991 (markdown-ensure-blank-line-after)))
4993 (defun markdown-footnote-text-find-new-location ()
4994 "Position the cursor at the proper location for a new footnote text."
4995 (cond
4996 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
4997 ((eq markdown-footnote-location 'immediately) (markdown-end-of-text-block))
4998 ((eq markdown-footnote-location 'subtree) (markdown-end-of-subtree))
4999 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
5001 (defun markdown-footnote-kill ()
5002 "Kill the footnote at point.
5003 The footnote text is killed (and added to the kill ring), the
5004 footnote marker is deleted. Point has to be either at the
5005 footnote marker or in the footnote text."
5006 (interactive)
5007 (let ((marker-pos nil)
5008 (skip-deleting-marker nil)
5009 (starting-footnote-text-positions
5010 (markdown-footnote-text-positions)))
5011 (when starting-footnote-text-positions
5012 ;; We're starting in footnote text, so mark our return position and jump
5013 ;; to the marker if possible.
5014 (let ((marker-pos (markdown-footnote-find-marker
5015 (cl-first starting-footnote-text-positions))))
5016 (if marker-pos
5017 (goto-char (1- marker-pos))
5018 ;; If there isn't a marker, we still want to kill the text.
5019 (setq skip-deleting-marker t))))
5020 ;; Either we didn't start in the text, or we started in the text and jumped
5021 ;; to the marker. We want to assume we're at the marker now and error if
5022 ;; we're not.
5023 (unless skip-deleting-marker
5024 (let ((marker (markdown-footnote-delete-marker)))
5025 (unless marker
5026 (error "Not at a footnote"))
5027 ;; Even if we knew the text position before, it changed when we deleted
5028 ;; the label.
5029 (setq marker-pos (cl-second marker))
5030 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker))))
5031 (unless new-text-pos
5032 (error "No text for footnote `%s'" (cl-first marker)))
5033 (goto-char new-text-pos))))
5034 (let ((pos (markdown-footnote-kill-text)))
5035 (goto-char (if starting-footnote-text-positions
5037 marker-pos)))))
5039 (defun markdown-footnote-delete-marker ()
5040 "Delete a footnote marker at point.
5041 Returns a list (ID START) containing the footnote ID and the
5042 start position of the marker before deletion. If no footnote
5043 marker was deleted, this function returns NIL."
5044 (let ((marker (markdown-footnote-marker-positions)))
5045 (when marker
5046 (delete-region (cl-second marker) (cl-third marker))
5047 (butlast marker))))
5049 (defun markdown-footnote-kill-text ()
5050 "Kill footnote text at point.
5051 Returns the start position of the footnote text before deletion,
5052 or NIL if point was not inside a footnote text.
5054 The killed text is placed in the kill ring (without the footnote
5055 number)."
5056 (let ((fn (markdown-footnote-text-positions)))
5057 (when fn
5058 (let ((text (delete-and-extract-region (cl-second fn) (cl-third fn))))
5059 (string-match (concat "\\[\\" (cl-first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
5060 (kill-new (match-string 1 text))
5061 (when (and (markdown-cur-line-blank-p)
5062 (markdown-prev-line-blank-p)
5063 (not (bobp)))
5064 (delete-region (1- (point)) (point)))
5065 (cl-second fn)))))
5067 (defun markdown-footnote-goto-text ()
5068 "Jump to the text of the footnote at point."
5069 (interactive)
5070 (let ((fn (car (markdown-footnote-marker-positions))))
5071 (unless fn
5072 (user-error "Not at a footnote marker"))
5073 (let ((new-pos (markdown-footnote-find-text fn)))
5074 (unless new-pos
5075 (error "No definition found for footnote `%s'" fn))
5076 (goto-char new-pos))))
5078 (defun markdown-footnote-return ()
5079 "Return from a footnote to its footnote number in the main text."
5080 (interactive)
5081 (let ((fn (save-excursion
5082 (car (markdown-footnote-text-positions)))))
5083 (unless fn
5084 (user-error "Not in a footnote"))
5085 (let ((new-pos (markdown-footnote-find-marker fn)))
5086 (unless new-pos
5087 (error "Footnote marker `%s' not found" fn))
5088 (goto-char new-pos))))
5090 (defun markdown-footnote-find-marker (id)
5091 "Find the location of the footnote marker with ID.
5092 The actual buffer position returned is the position directly
5093 following the marker's closing bracket. If no marker is found,
5094 NIL is returned."
5095 (save-excursion
5096 (goto-char (point-min))
5097 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
5098 (skip-chars-backward "^]")
5099 (point))))
5101 (defun markdown-footnote-find-text (id)
5102 "Find the location of the text of footnote ID.
5103 The actual buffer position returned is the position of the first
5104 character of the text, after the footnote's identifier. If no
5105 footnote text is found, NIL is returned."
5106 (save-excursion
5107 (goto-char (point-min))
5108 (when (re-search-forward (concat "^ \\{0,3\\}\\[" id "\\]:") nil t)
5109 (skip-chars-forward "[ \t]")
5110 (point))))
5112 (defun markdown-footnote-marker-positions ()
5113 "Return the position and ID of the footnote marker point is on.
5114 The return value is a list (ID START END). If point is not on a
5115 footnote, NIL is returned."
5116 ;; first make sure we're at a footnote marker
5117 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
5118 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
5119 (save-excursion
5120 ;; move point between [ and ^:
5121 (if (looking-at-p "\\[")
5122 (forward-char 1)
5123 (skip-chars-backward "^["))
5124 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
5125 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
5127 (defun markdown-footnote-text-positions ()
5128 "Return the start and end positions of the footnote text point is in.
5129 The exact return value is a list of three elements: (ID START END).
5130 The start position is the position of the opening bracket
5131 of the footnote id. The end position is directly after the
5132 newline that ends the footnote. If point is not in a footnote,
5133 NIL is returned instead."
5134 (save-excursion
5135 (let (result)
5136 (move-beginning-of-line 1)
5137 ;; Try to find the label. If we haven't found the label and we're at a blank
5138 ;; or indented line, back up if possible.
5139 (while (and
5140 (not (and (looking-at markdown-regex-footnote-definition)
5141 (setq result (list (match-string 1) (point)))))
5142 (and (not (bobp))
5143 (or (markdown-cur-line-blank-p)
5144 (>= (current-indentation) 4))))
5145 (forward-line -1))
5146 (when result
5147 ;; Advance if there is a next line that is either blank or indented.
5148 ;; (Need to check if we're on the last line, because
5149 ;; markdown-next-line-blank-p returns true for last line in buffer.)
5150 (while (and (/= (line-end-position) (point-max))
5151 (or (markdown-next-line-blank-p)
5152 (>= (markdown-next-line-indent) 4)))
5153 (forward-line))
5154 ;; Move back while the current line is blank.
5155 (while (markdown-cur-line-blank-p)
5156 (forward-line -1))
5157 ;; Advance to capture this line and a single trailing newline (if there
5158 ;; is one).
5159 (forward-line)
5160 (append result (list (point)))))))
5163 ;;; Element Removal ===========================================================
5165 (defun markdown-kill-thing-at-point ()
5166 "Kill thing at point and add important text, without markup, to kill ring.
5167 Possible things to kill include (roughly in order of precedence):
5168 inline code, headers, horizonal rules, links (add link text to
5169 kill ring), images (add alt text to kill ring), angle uri, email
5170 addresses, bold, italics, reference definition (add URI to kill
5171 ring), footnote markers and text (kill both marker and text, add
5172 text to kill ring), and list items."
5173 (interactive "*")
5174 (let (val)
5175 (cond
5176 ;; Inline code
5177 ((markdown-inline-code-at-point)
5178 (kill-new (match-string 2))
5179 (delete-region (match-beginning 0) (match-end 0)))
5180 ;; ATX header
5181 ((thing-at-point-looking-at markdown-regex-header-atx)
5182 (kill-new (match-string 2))
5183 (delete-region (match-beginning 0) (match-end 0)))
5184 ;; Setext header
5185 ((thing-at-point-looking-at markdown-regex-header-setext)
5186 (kill-new (match-string 1))
5187 (delete-region (match-beginning 0) (match-end 0)))
5188 ;; Horizonal rule
5189 ((thing-at-point-looking-at markdown-regex-hr)
5190 (kill-new (match-string 0))
5191 (delete-region (match-beginning 0) (match-end 0)))
5192 ;; Inline link or image (add link or alt text to kill ring)
5193 ((thing-at-point-looking-at markdown-regex-link-inline)
5194 (kill-new (match-string 3))
5195 (delete-region (match-beginning 0) (match-end 0)))
5196 ;; Reference link or image (add link or alt text to kill ring)
5197 ((thing-at-point-looking-at markdown-regex-link-reference)
5198 (kill-new (match-string 3))
5199 (delete-region (match-beginning 0) (match-end 0)))
5200 ;; Angle URI (add URL to kill ring)
5201 ((thing-at-point-looking-at markdown-regex-angle-uri)
5202 (kill-new (match-string 2))
5203 (delete-region (match-beginning 0) (match-end 0)))
5204 ;; Email address in angle brackets (add email address to kill ring)
5205 ((thing-at-point-looking-at markdown-regex-email)
5206 (kill-new (match-string 1))
5207 (delete-region (match-beginning 0) (match-end 0)))
5208 ;; Wiki link (add alias text to kill ring)
5209 ((and markdown-enable-wiki-links
5210 (thing-at-point-looking-at markdown-regex-wiki-link))
5211 (kill-new (markdown-wiki-link-alias))
5212 (delete-region (match-beginning 1) (match-end 1)))
5213 ;; Bold
5214 ((thing-at-point-looking-at markdown-regex-bold)
5215 (kill-new (match-string 4))
5216 (delete-region (match-beginning 2) (match-end 2)))
5217 ;; Italics
5218 ((thing-at-point-looking-at markdown-regex-italic)
5219 (kill-new (match-string 3))
5220 (delete-region (match-beginning 1) (match-end 1)))
5221 ;; Strikethrough
5222 ((thing-at-point-looking-at markdown-regex-strike-through)
5223 (kill-new (match-string 4))
5224 (delete-region (match-beginning 2) (match-end 2)))
5225 ;; Footnote marker (add footnote text to kill ring)
5226 ((thing-at-point-looking-at markdown-regex-footnote)
5227 (markdown-footnote-kill))
5228 ;; Footnote text (add footnote text to kill ring)
5229 ((setq val (markdown-footnote-text-positions))
5230 (markdown-footnote-kill))
5231 ;; Reference definition (add URL to kill ring)
5232 ((thing-at-point-looking-at markdown-regex-reference-definition)
5233 (kill-new (match-string 5))
5234 (delete-region (match-beginning 0) (match-end 0)))
5235 ;; List item
5236 ((setq val (markdown-cur-list-item-bounds))
5237 (kill-new (delete-and-extract-region (cl-first val) (cl-second val))))
5239 (user-error "Nothing found at point to kill")))))
5242 ;;; Indentation ====================================================================
5244 (defun markdown-indent-find-next-position (cur-pos positions)
5245 "Return the position after the index of CUR-POS in POSITIONS.
5246 Positions are calculated by `markdown-calc-indents'."
5247 (while (and positions
5248 (not (equal cur-pos (car positions))))
5249 (setq positions (cdr positions)))
5250 (or (cadr positions) 0))
5252 (define-obsolete-function-alias 'markdown-exdent-find-next-position
5253 'markdown-outdent-find-next-position "v2.3")
5255 (defun markdown-outdent-find-next-position (cur-pos positions)
5256 "Return the maximal element that precedes CUR-POS from POSITIONS.
5257 Positions are calculated by `markdown-calc-indents'."
5258 (let ((result 0))
5259 (dolist (i positions)
5260 (when (< i cur-pos)
5261 (setq result (max result i))))
5262 result))
5264 (defun markdown-indent-line ()
5265 "Indent the current line using some heuristics.
5266 If the _previous_ command was either `markdown-enter-key' or
5267 `markdown-cycle', then we should cycle to the next
5268 reasonable indentation position. Otherwise, we could have been
5269 called directly by `markdown-enter-key', by an initial call of
5270 `markdown-cycle', or indirectly by `auto-fill-mode'. In
5271 these cases, indent to the default position.
5272 Positions are calculated by `markdown-calc-indents'."
5273 (interactive)
5274 (let ((positions (markdown-calc-indents))
5275 (cursor-pos (current-column))
5276 (_ (back-to-indentation))
5277 (cur-pos (current-column)))
5278 (if (not (equal this-command 'markdown-cycle))
5279 (indent-line-to (car positions))
5280 (setq positions (sort (delete-dups positions) '<))
5281 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions))
5282 (new-cursor-pos
5283 (if (< cur-pos next-pos)
5284 (+ cursor-pos (- next-pos cur-pos))
5285 (- cursor-pos cur-pos))))
5286 (indent-line-to next-pos)
5287 (move-to-column new-cursor-pos)))))
5289 (defun markdown-calc-indents ()
5290 "Return a list of indentation columns to cycle through.
5291 The first element in the returned list should be considered the
5292 default indentation level. This function does not worry about
5293 duplicate positions, which are handled up by calling functions."
5294 (let (pos prev-line-pos positions)
5296 ;; Indentation of previous line
5297 (setq prev-line-pos (markdown-prev-line-indent))
5298 (setq positions (cons prev-line-pos positions))
5300 ;; Indentation of previous non-list-marker text
5301 (when (setq pos (markdown-prev-non-list-indent))
5302 (setq positions (cons pos positions)))
5304 ;; Indentation required for a pre block in current context
5305 (setq pos (length (markdown-pre-indentation (point))))
5306 (setq positions (cons pos positions))
5308 ;; Indentation of the previous line + tab-width
5309 (if prev-line-pos
5310 (setq positions (cons (+ prev-line-pos tab-width) positions))
5311 (setq positions (cons tab-width positions)))
5313 ;; Indentation of the previous line - tab-width
5314 (if (and prev-line-pos (> prev-line-pos tab-width))
5315 (setq positions (cons (- prev-line-pos tab-width) positions)))
5317 ;; Indentation of all preceeding list markers (when in a list)
5318 (when (setq pos (markdown-calculate-list-levels))
5319 (setq positions (append pos positions)))
5321 ;; First column
5322 (setq positions (cons 0 positions))
5324 ;; Return reversed list
5325 (reverse positions)))
5327 (defun markdown-enter-key ()
5328 "Handle RET according to value of `markdown-indent-on-enter'.
5329 When it is nil, simply call `newline'. Otherwise, indent the next line
5330 following RET using `markdown-indent-line'. Furthermore, when it
5331 is set to 'indent-and-new-item and the point is in a list item,
5332 start a new item with the same indentation. If the point is in an
5333 empty list item, remove it (so that pressing RET twice when in a
5334 list simply adds a blank line)."
5335 (interactive)
5336 (if (not markdown-indent-on-enter)
5337 (newline)
5338 (let (bounds)
5339 (if (and (memq markdown-indent-on-enter '(indent-and-new-item))
5340 (setq bounds (markdown-cur-list-item-bounds)))
5341 (let ((beg (cl-first bounds))
5342 (end (cl-second bounds))
5343 (length (cl-fourth bounds)))
5344 ;; Point is in a list item
5345 (if (= (- end beg) length)
5346 ;; Delete blank list
5347 (progn
5348 (delete-region beg end)
5349 (newline)
5350 (markdown-indent-line))
5351 (call-interactively #'markdown-insert-list-item)))
5352 ;; Point is not in a list
5353 (newline)
5354 (markdown-indent-line)))))
5356 (define-obsolete-function-alias 'markdown-exdent-or-delete
5357 'markdown-outdent-or-delete "v2.3")
5359 (defun markdown-outdent-or-delete (arg)
5360 "Handle BACKSPACE by cycling through indentation points.
5361 When BACKSPACE is pressed, if there is only whitespace
5362 before the current point, then outdent the line one level.
5363 Otherwise, do normal delete by repeating
5364 `backward-delete-char-untabify' ARG times."
5365 (interactive "*p")
5366 (if (use-region-p)
5367 (backward-delete-char-untabify arg)
5368 (let ((cur-pos (current-column))
5369 (start-of-indention (save-excursion
5370 (back-to-indentation)
5371 (current-column)))
5372 (positions (markdown-calc-indents)))
5373 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
5374 (indent-line-to (markdown-outdent-find-next-position cur-pos positions))
5375 (backward-delete-char-untabify arg)))))
5377 (defun markdown-find-leftmost-column (beg end)
5378 "Find the leftmost column in the region from BEG to END."
5379 (let ((mincol 1000))
5380 (save-excursion
5381 (goto-char beg)
5382 (while (< (point) end)
5383 (back-to-indentation)
5384 (unless (looking-at-p "[ \t]*$")
5385 (setq mincol (min mincol (current-column))))
5386 (forward-line 1)
5388 mincol))
5390 (defun markdown-indent-region (beg end arg)
5391 "Indent the region from BEG to END using some heuristics.
5392 When ARG is non-nil, outdent the region instead.
5393 See `markdown-indent-line' and `markdown-indent-line'."
5394 (interactive "*r\nP")
5395 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
5396 (leftmostcol (markdown-find-leftmost-column beg end))
5397 (next-pos (if arg
5398 (markdown-outdent-find-next-position leftmostcol positions)
5399 (markdown-indent-find-next-position leftmostcol positions))))
5400 (indent-rigidly beg end (- next-pos leftmostcol))
5401 (setq deactivate-mark nil)))
5403 (define-obsolete-function-alias 'markdown-exdent-region
5404 'markdown-outdent-region "v2.3")
5406 (defun markdown-outdent-region (beg end)
5407 "Call `markdown-indent-region' on region from BEG to END with prefix."
5408 (interactive "*r")
5409 (markdown-indent-region beg end t))
5412 ;;; Markup Completion =========================================================
5414 (defconst markdown-complete-alist
5415 '((markdown-regex-header-atx . markdown-complete-atx)
5416 (markdown-regex-header-setext . markdown-complete-setext)
5417 (markdown-regex-hr . markdown-complete-hr))
5418 "Association list of form (regexp . function) for markup completion.")
5420 (defun markdown-incomplete-atx-p ()
5421 "Return t if ATX header markup is incomplete and nil otherwise.
5422 Assumes match data is available for `markdown-regex-header-atx'.
5423 Checks that the number of trailing hash marks equals the number of leading
5424 hash marks, that there is only a single space before and after the text,
5425 and that there is no extraneous whitespace in the text."
5427 ;; Number of starting and ending hash marks differs
5428 (not (= (length (match-string 1)) (length (match-string 3))))
5429 ;; When the header text is not empty...
5430 (and (> (length (match-string 2)) 0)
5431 ;; ...if there are extra leading, trailing, or interior spaces
5432 (or (not (= (match-beginning 2) (1+ (match-end 1))))
5433 (not (= (match-beginning 3) (1+ (match-end 2))))
5434 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
5435 ;; When the header text is empty...
5436 (and (= (length (match-string 2)) 0)
5437 ;; ...if there are too many or too few spaces
5438 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
5440 (defun markdown-complete-atx ()
5441 "Complete and normalize ATX headers.
5442 Add or remove hash marks to the end of the header to match the
5443 beginning. Ensure that there is only a single space between hash
5444 marks and header text. Removes extraneous whitespace from header text.
5445 Assumes match data is available for `markdown-regex-header-atx'.
5446 Return nil if markup was complete and non-nil if markup was completed."
5447 (when (markdown-incomplete-atx-p)
5448 (let* ((new-marker (make-marker))
5449 (new-marker (set-marker new-marker (match-end 2))))
5450 ;; Hash marks and spacing at end
5451 (goto-char (match-end 2))
5452 (delete-region (match-end 2) (match-end 3))
5453 (insert " " (match-string 1))
5454 ;; Remove extraneous whitespace from title
5455 (replace-match (markdown-compress-whitespace-string (match-string 2))
5456 t t nil 2)
5457 ;; Spacing at beginning
5458 (goto-char (match-end 1))
5459 (delete-region (match-end 1) (match-beginning 2))
5460 (insert " ")
5461 ;; Leave point at end of text
5462 (goto-char new-marker))))
5464 (defun markdown-incomplete-setext-p ()
5465 "Return t if setext header markup is incomplete and nil otherwise.
5466 Assumes match data is available for `markdown-regex-header-setext'.
5467 Checks that length of underline matches text and that there is no
5468 extraneous whitespace in the text."
5469 (or (not (= (length (match-string 1)) (length (match-string 2))))
5470 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
5472 (defun markdown-complete-setext ()
5473 "Complete and normalize setext headers.
5474 Add or remove underline characters to match length of header
5475 text. Removes extraneous whitespace from header text. Assumes
5476 match data is available for `markdown-regex-header-setext'.
5477 Return nil if markup was complete and non-nil if markup was completed."
5478 (when (markdown-incomplete-setext-p)
5479 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
5480 (char (char-after (match-beginning 2)))
5481 (level (if (char-equal char ?-) 2 1)))
5482 (goto-char (match-beginning 0))
5483 (delete-region (match-beginning 0) (match-end 0))
5484 (markdown-insert-header level text t)
5485 t)))
5487 (defun markdown-incomplete-hr-p ()
5488 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
5489 Assumes match data is available for `markdown-regex-hr'."
5490 (not (member (match-string 0) markdown-hr-strings)))
5492 (defun markdown-complete-hr ()
5493 "Complete horizontal rules.
5494 If horizontal rule string is a member of `markdown-hr-strings',
5495 do nothing. Otherwise, replace with the car of
5496 `markdown-hr-strings'.
5497 Assumes match data is available for `markdown-regex-hr'.
5498 Return nil if markup was complete and non-nil if markup was completed."
5499 (when (markdown-incomplete-hr-p)
5500 (replace-match (car markdown-hr-strings))
5503 (defun markdown-complete ()
5504 "Complete markup of object near point or in region when active.
5505 Handle all objects in `markdown-complete-alist', in order.
5506 See `markdown-complete-at-point' and `markdown-complete-region'."
5507 (interactive "*")
5508 (if (markdown-use-region-p)
5509 (markdown-complete-region (region-beginning) (region-end))
5510 (markdown-complete-at-point)))
5512 (defun markdown-complete-at-point ()
5513 "Complete markup of object near point.
5514 Handle all elements of `markdown-complete-alist' in order."
5515 (interactive "*")
5516 (let ((list markdown-complete-alist) found changed)
5517 (while list
5518 (let ((regexp (eval (caar list)))
5519 (function (cdar list)))
5520 (setq list (cdr list))
5521 (when (thing-at-point-looking-at regexp)
5522 (setq found t)
5523 (setq changed (funcall function))
5524 (setq list nil))))
5525 (if found
5526 (or changed (user-error "Markup at point is complete"))
5527 (user-error "Nothing to complete at point"))))
5529 (defun markdown-complete-region (beg end)
5530 "Complete markup of objects in region from BEG to END.
5531 Handle all objects in `markdown-complete-alist', in order. Each
5532 match is checked to ensure that a previous regexp does not also
5533 match."
5534 (interactive "*r")
5535 (let ((end-marker (set-marker (make-marker) end))
5536 previous)
5537 (dolist (element markdown-complete-alist)
5538 (let ((regexp (eval (car element)))
5539 (function (cdr element)))
5540 (goto-char beg)
5541 (while (re-search-forward regexp end-marker 'limit)
5542 (when (match-string 0)
5543 ;; Make sure this is not a match for any of the preceding regexps.
5544 ;; This prevents mistaking an HR for a Setext subheading.
5545 (let (match)
5546 (save-match-data
5547 (dolist (prev-regexp previous)
5548 (or match (setq match (looking-back prev-regexp nil)))))
5549 (unless match
5550 (save-excursion (funcall function))))))
5551 (cl-pushnew regexp previous :test #'equal)))
5552 previous))
5554 (defun markdown-complete-buffer ()
5555 "Complete markup for all objects in the current buffer."
5556 (interactive "*")
5557 (markdown-complete-region (point-min) (point-max)))
5560 ;;; Markup Cycling ============================================================
5562 (defun markdown-cycle-atx (arg &optional remove)
5563 "Cycle ATX header markup.
5564 Promote header (decrease level) when ARG is 1 and demote
5565 header (increase level) if arg is -1. When REMOVE is non-nil,
5566 remove the header when the level reaches zero and stop cycling
5567 when it reaches six. Otherwise, perform a proper cycling through
5568 levels one through six. Assumes match data is available for
5569 `markdown-regex-header-atx'."
5570 (let* ((old-level (length (match-string 1)))
5571 (new-level (+ old-level arg))
5572 (text (match-string 2)))
5573 (when (not remove)
5574 (setq new-level (% new-level 6))
5575 (setq new-level (cond ((= new-level 0) 6)
5576 ((< new-level 0) (+ new-level 6))
5577 (t new-level))))
5578 (cond
5579 ((= new-level 0)
5580 (markdown-unwrap-thing-at-point nil 0 2))
5581 ((<= new-level 6)
5582 (goto-char (match-beginning 0))
5583 (delete-region (match-beginning 0) (match-end 0))
5584 (markdown-insert-header new-level text nil)))))
5586 (defun markdown-cycle-setext (arg &optional remove)
5587 "Cycle setext header markup.
5588 Promote header (increase level) when ARG is 1 and demote
5589 header (decrease level or remove) if arg is -1. When demoting a
5590 level-two setext header, replace with a level-three atx header.
5591 When REMOVE is non-nil, remove the header when the level reaches
5592 zero. Otherwise, cycle back to a level six atx header. Assumes
5593 match data is available for `markdown-regex-header-setext'."
5594 (let* ((char (char-after (match-beginning 2)))
5595 (old-level (if (char-equal char ?=) 1 2))
5596 (new-level (+ old-level arg)))
5597 (when (and (not remove) (= new-level 0))
5598 (setq new-level 6))
5599 (cond
5600 ((= new-level 0)
5601 (markdown-unwrap-thing-at-point nil 0 1))
5602 ((<= new-level 2)
5603 (markdown-insert-header new-level nil t))
5604 ((<= new-level 6)
5605 (markdown-insert-header new-level nil nil)))))
5607 (defun markdown-cycle-hr (arg &optional remove)
5608 "Cycle string used for horizontal rule from `markdown-hr-strings'.
5609 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
5610 backwards (promote). When REMOVE is non-nil, remove the hr instead
5611 of cycling when the end of the list is reached.
5612 Assumes match data is available for `markdown-regex-hr'."
5613 (let* ((strings (if (= arg -1)
5614 (reverse markdown-hr-strings)
5615 markdown-hr-strings))
5616 (tail (member (match-string 0) strings))
5617 (new (or (cadr tail)
5618 (if remove
5619 (if (= arg 1)
5621 (car tail))
5622 (car strings)))))
5623 (replace-match new)))
5625 (defun markdown-cycle-bold ()
5626 "Cycle bold markup between underscores and asterisks.
5627 Assumes match data is available for `markdown-regex-bold'."
5628 (save-excursion
5629 (let* ((old-delim (match-string 3))
5630 (new-delim (if (string-equal old-delim "**") "__" "**")))
5631 (replace-match new-delim t t nil 3)
5632 (replace-match new-delim t t nil 5))))
5634 (defun markdown-cycle-italic ()
5635 "Cycle italic markup between underscores and asterisks.
5636 Assumes match data is available for `markdown-regex-italic'."
5637 (save-excursion
5638 (let* ((old-delim (match-string 2))
5639 (new-delim (if (string-equal old-delim "*") "_" "*")))
5640 (replace-match new-delim t t nil 2)
5641 (replace-match new-delim t t nil 4))))
5644 ;;; Keymap ====================================================================
5646 (defun markdown--style-map-prompt ()
5647 "Return a formatted prompt for Markdown markup insertion."
5648 (concat
5649 "Markdown: "
5650 (propertize "bold" 'face 'markdown-bold-face) ", "
5651 (propertize "italic" 'face 'markdown-italic-face) ", "
5652 (propertize "code" 'face 'markdown-inline-code-face) ", "
5653 (propertize "C = GFM code" 'face 'markdown-code-face) ", "
5654 (propertize "pre" 'face 'markdown-pre-face) ", "
5655 (propertize "footnote" 'face 'markdown-footnote-text-face) ", "
5656 (propertize "q = blockquote" 'face 'markdown-blockquote-face) ", "
5657 (propertize "h & 1-6 = heading" 'face 'markdown-header-face) ", "
5658 (propertize "- = hr" 'face 'markdown-hr-face) ", "
5659 "C-h = more"))
5661 (defvar markdown-mode-style-map
5662 (let ((map (make-keymap (markdown--style-map-prompt))))
5663 (define-key map (kbd "1") 'markdown-insert-header-atx-1)
5664 (define-key map (kbd "2") 'markdown-insert-header-atx-2)
5665 (define-key map (kbd "3") 'markdown-insert-header-atx-3)
5666 (define-key map (kbd "4") 'markdown-insert-header-atx-4)
5667 (define-key map (kbd "5") 'markdown-insert-header-atx-5)
5668 (define-key map (kbd "6") 'markdown-insert-header-atx-6)
5669 (define-key map (kbd "!") 'markdown-insert-header-setext-1)
5670 (define-key map (kbd "@") 'markdown-insert-header-setext-2)
5671 (define-key map (kbd "b") 'markdown-insert-bold)
5672 (define-key map (kbd "c") 'markdown-insert-code)
5673 (define-key map (kbd "C") 'markdown-insert-gfm-code-block)
5674 (define-key map (kbd "f") 'markdown-insert-footnote)
5675 (define-key map (kbd "h") 'markdown-insert-header-dwim)
5676 (define-key map (kbd "H") 'markdown-insert-header-setext-dwim)
5677 (define-key map (kbd "i") 'markdown-insert-italic)
5678 (define-key map (kbd "k") 'markdown-insert-kbd)
5679 (define-key map (kbd "l") 'markdown-insert-link)
5680 (define-key map (kbd "p") 'markdown-insert-pre)
5681 (define-key map (kbd "P") 'markdown-pre-region)
5682 (define-key map (kbd "q") 'markdown-insert-blockquote)
5683 (define-key map (kbd "s") 'markdown-insert-strike-through)
5684 (define-key map (kbd "Q") 'markdown-blockquote-region)
5685 (define-key map (kbd "w") 'markdown-insert-wiki-link)
5686 (define-key map (kbd "-") 'markdown-insert-hr)
5687 ;; Deprecated keys that may be removed in a future version
5688 (define-key map (kbd "e") 'markdown-insert-italic)
5689 map)
5690 "Keymap for Markdown text styling commands.")
5692 (defvar markdown-mode-map
5693 (let ((map (make-keymap)))
5694 ;; Markup insertion & removal
5695 (define-key map (kbd "C-c C-s") markdown-mode-style-map)
5696 (define-key map (kbd "C-c C-l") 'markdown-insert-link)
5697 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
5698 ;; Promotion, demotion, and cycling
5699 (define-key map (kbd "C-c C--") 'markdown-promote)
5700 (define-key map (kbd "C-c C-=") 'markdown-demote)
5701 (define-key map (kbd "C-c C-]") 'markdown-complete)
5702 ;; Following and doing things
5703 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
5704 (define-key map (kbd "C-c C-d") 'markdown-do)
5705 ;; Indentation
5706 (define-key map (kbd "C-m") 'markdown-enter-key)
5707 (define-key map (kbd "DEL") 'markdown-outdent-or-delete)
5708 (define-key map (kbd "C-c >") 'markdown-indent-region)
5709 (define-key map (kbd "C-c <") 'markdown-outdent-region)
5710 ;; Visibility cycling
5711 (define-key map (kbd "TAB") 'markdown-cycle)
5712 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
5713 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
5714 (define-key map (kbd "<backtab>") 'markdown-shifttab)
5715 ;; Heading and list navigation
5716 (define-key map (kbd "C-c C-n") 'markdown-outline-next)
5717 (define-key map (kbd "C-c C-p") 'markdown-outline-previous)
5718 (define-key map (kbd "C-c C-f") 'markdown-outline-next-same-level)
5719 (define-key map (kbd "C-c C-b") 'markdown-outline-previous-same-level)
5720 (define-key map (kbd "C-c C-u") 'markdown-outline-up)
5721 ;; Buffer-wide commands
5722 (define-key map (kbd "C-c C-c m") 'markdown-other-window)
5723 (define-key map (kbd "C-c C-c p") 'markdown-preview)
5724 (define-key map (kbd "C-c C-c e") 'markdown-export)
5725 (define-key map (kbd "C-c C-c v") 'markdown-export-and-preview)
5726 (define-key map (kbd "C-c C-c o") 'markdown-open)
5727 (define-key map (kbd "C-c C-c l") 'markdown-live-preview-mode)
5728 (define-key map (kbd "C-c C-c w") 'markdown-kill-ring-save)
5729 (define-key map (kbd "C-c C-c c") 'markdown-check-refs)
5730 (define-key map (kbd "C-c C-c n") 'markdown-cleanup-list-numbers)
5731 (define-key map (kbd "C-c C-c ]") 'markdown-complete-buffer)
5732 (define-key map (kbd "C-c '") 'markdown-edit-code-block)
5733 ;; Subtree and list editing
5734 (define-key map (kbd "C-c <up>") 'markdown-move-up)
5735 (define-key map (kbd "C-c <down>") 'markdown-move-down)
5736 (define-key map (kbd "C-c <left>") 'markdown-promote)
5737 (define-key map (kbd "C-c <right>") 'markdown-demote)
5738 (define-key map (kbd "C-c C-M-h") 'markdown-mark-subtree)
5739 (define-key map (kbd "C-x n s") 'markdown-narrow-to-subtree)
5740 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
5741 (define-key map (kbd "C-c C-j") 'markdown-insert-list-item)
5742 ;; Paragraphs (Markdown context aware)
5743 (define-key map [remap backward-paragraph] 'markdown-backward-paragraph)
5744 (define-key map [remap forward-paragraph] 'markdown-forward-paragraph)
5745 (define-key map [remap mark-paragraph] 'markdown-mark-paragraph)
5746 ;; Blocks (one or more paragraphs)
5747 (define-key map (kbd "C-M-{") 'markdown-backward-block)
5748 (define-key map (kbd "C-M-}") 'markdown-forward-block)
5749 (define-key map (kbd "C-c M-h") 'markdown-mark-block)
5750 (define-key map (kbd "C-x n b") 'markdown-narrow-to-block)
5751 ;; Pages (top-level sections)
5752 (define-key map [remap backward-page] 'markdown-backward-page)
5753 (define-key map [remap forward-page] 'markdown-forward-page)
5754 (define-key map [remap mark-page] 'markdown-mark-page)
5755 (define-key map [remap narrow-to-page] 'markdown-narrow-to-page)
5756 ;; Link Movement
5757 (define-key map (kbd "M-n") 'markdown-next-link)
5758 (define-key map (kbd "M-p") 'markdown-previous-link)
5759 ;; Toggling functionality
5760 (define-key map (kbd "C-c C-x C-e") 'markdown-toggle-math)
5761 (define-key map (kbd "C-c C-x C-f") 'markdown-toggle-fontify-code-blocks-natively)
5762 (define-key map (kbd "C-c C-x C-i") 'markdown-toggle-inline-images)
5763 (define-key map (kbd "C-c C-x C-l") 'markdown-toggle-url-hiding)
5764 (define-key map (kbd "C-c C-x C-m") 'markdown-toggle-markup-hiding)
5765 ;; Alternative keys (in case of problems with the arrow keys)
5766 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
5767 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
5768 (define-key map (kbd "C-c C-x l") 'markdown-promote)
5769 (define-key map (kbd "C-c C-x r") 'markdown-demote)
5770 ;; Deprecated keys that may be removed in a future version
5771 (define-key map (kbd "C-c C-a L") 'markdown-insert-link) ;; C-c C-l
5772 (define-key map (kbd "C-c C-a l") 'markdown-insert-link) ;; C-c C-l
5773 (define-key map (kbd "C-c C-a r") 'markdown-insert-link) ;; C-c C-l
5774 (define-key map (kbd "C-c C-a u") 'markdown-insert-uri) ;; C-c C-l
5775 (define-key map (kbd "C-c C-a f") 'markdown-insert-footnote)
5776 (define-key map (kbd "C-c C-a w") 'markdown-insert-wiki-link)
5777 (define-key map (kbd "C-c C-t 1") 'markdown-insert-header-atx-1)
5778 (define-key map (kbd "C-c C-t 2") 'markdown-insert-header-atx-2)
5779 (define-key map (kbd "C-c C-t 3") 'markdown-insert-header-atx-3)
5780 (define-key map (kbd "C-c C-t 4") 'markdown-insert-header-atx-4)
5781 (define-key map (kbd "C-c C-t 5") 'markdown-insert-header-atx-5)
5782 (define-key map (kbd "C-c C-t 6") 'markdown-insert-header-atx-6)
5783 (define-key map (kbd "C-c C-t !") 'markdown-insert-header-setext-1)
5784 (define-key map (kbd "C-c C-t @") 'markdown-insert-header-setext-2)
5785 (define-key map (kbd "C-c C-t h") 'markdown-insert-header-dwim)
5786 (define-key map (kbd "C-c C-t H") 'markdown-insert-header-setext-dwim)
5787 (define-key map (kbd "C-c C-t s") 'markdown-insert-header-setext-2)
5788 (define-key map (kbd "C-c C-t t") 'markdown-insert-header-setext-1)
5789 (define-key map (kbd "C-c C-i") 'markdown-insert-image)
5790 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item) ;; C-c C-j
5791 (define-key map (kbd "C-c C-x C-x") 'markdown-toggle-gfm-checkbox) ;; C-c C-d
5792 (define-key map (kbd "C-c -") 'markdown-insert-hr)
5793 map)
5794 "Keymap for Markdown major mode.")
5796 (defvar markdown-mode-mouse-map
5797 (let ((map (make-sparse-keymap)))
5798 (define-key map [follow-link] 'mouse-face)
5799 (define-key map [mouse-2] 'markdown-follow-link-at-point)
5800 map)
5801 "Keymap for following links with mouse.")
5803 (defvar gfm-mode-map
5804 (let ((map (make-sparse-keymap)))
5805 (set-keymap-parent map markdown-mode-map)
5806 (define-key map (kbd "C-c C-s d") 'markdown-insert-strike-through)
5807 (define-key map "`" 'markdown-electric-backquote)
5808 map)
5809 "Keymap for `gfm-mode'.
5810 See also `markdown-mode-map'.")
5813 ;;; Menu ==================================================================
5815 (easy-menu-define markdown-mode-menu markdown-mode-map
5816 "Menu for Markdown mode"
5817 '("Markdown"
5818 "---"
5819 ("Movement"
5820 ["Jump" markdown-do]
5821 ["Follow Link" markdown-follow-thing-at-point]
5822 ["Next Link" markdown-next-link]
5823 ["Previous Link" markdown-previous-link]
5824 "---"
5825 ["Next Heading or List Item" markdown-outline-next]
5826 ["Previous Heading or List Item" markdown-outline-previous]
5827 ["Next at Same Level" markdown-outline-next-same-level]
5828 ["Previous at Same Level" markdown-outline-previous-same-level]
5829 ["Up to Parent" markdown-outline-up]
5830 "---"
5831 ["Forward Paragraph" markdown-forward-paragraph]
5832 ["Backward Paragraph" markdown-backward-paragraph]
5833 ["Forward Block" markdown-forward-block]
5834 ["Backward Block" markdown-backward-block])
5835 ("Show & Hide"
5836 ["Cycle Heading Visibility" markdown-cycle (markdown-on-heading-p)]
5837 ["Cycle Heading Visibility (Global)" markdown-shifttab]
5838 "---"
5839 ["Narrow to Region" narrow-to-region]
5840 ["Narrow to Block" markdown-narrow-to-block]
5841 ["Narrow to Section" narrow-to-defun]
5842 ["Narrow to Subtree" markdown-narrow-to-subtree]
5843 ["Widen" widen (buffer-narrowed-p)]
5844 "---"
5845 ["Toggle Markup Hiding" markdown-toggle-markup-hiding
5846 :keys "C-c C-x C-m"
5847 :style radio
5848 :selected markdown-hide-markup])
5849 "---"
5850 ("Headings & Structure"
5851 ["Automatic Heading" markdown-insert-header-dwim :keys "C-c C-s h"]
5852 ["Automatic Heading (Setext)" markdown-insert-header-setext-dwim :keys "C-c C-s H"]
5853 ("Specific Heading (atx)"
5854 ["First Level atx" markdown-insert-header-atx-1 :keys "C-c C-s 1"]
5855 ["Second Level atx" markdown-insert-header-atx-2 :keys "C-c C-s 2"]
5856 ["Third Level atx" markdown-insert-header-atx-3 :keys "C-c C-s 3"]
5857 ["Fourth Level atx" markdown-insert-header-atx-4 :keys "C-c C-s 4"]
5858 ["Fifth Level atx" markdown-insert-header-atx-5 :keys "C-c C-s 5"]
5859 ["Sixth Level atx" markdown-insert-header-atx-6 :keys "C-c C-s 6"])
5860 ("Specific Heading (Setext)"
5861 ["First Level Setext" markdown-insert-header-setext-1 :keys "C-c C-s !"]
5862 ["Second Level Setext" markdown-insert-header-setext-2 :keys "C-c C-s @"])
5863 ["Horizontal Rule" markdown-insert-hr :keys "C-c C-s -"]
5864 "---"
5865 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
5866 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
5867 ["Promote Subtree" markdown-promote :keys "C-c <left>"]
5868 ["Demote Subtree" markdown-demote :keys "C-c <right>"])
5869 ("Region & Mark"
5870 ["Indent Region" markdown-indent-region]
5871 ["Outdent Region" markdown-outdent-region]
5872 "--"
5873 ["Mark Paragraph" mark-paragraph]
5874 ["Mark Block" markdown-mark-block]
5875 ["Mark Section" mark-defun]
5876 ["Mark Subtree" markdown-mark-subtree])
5877 ("Lists"
5878 ["Insert List Item" markdown-insert-list-item]
5879 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
5880 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
5881 ["Indent Subtree" markdown-demote :keys "C-c <right>"]
5882 ["Outdent Subtree" markdown-promote :keys "C-c <left>"]
5883 ["Renumber List" markdown-cleanup-list-numbers]
5884 ["Toggle Task List Item" markdown-toggle-gfm-checkbox :keys "C-c C-d"])
5885 ("Links & Images"
5886 ["Insert Link" markdown-insert-link]
5887 ["Insert Image" markdown-insert-image]
5888 ["Insert Footnote" markdown-insert-footnote :keys "C-c C-s f"]
5889 ["Insert Wiki Link" markdown-insert-wiki-link :keys "C-c C-s w"]
5890 "---"
5891 ["Check References" markdown-check-refs]
5892 ["Toggle URL Hiding" markdown-toggle-url-hiding
5893 :style radio
5894 :selected markdown-hide-urls]
5895 ["Toggle Inline Images" markdown-toggle-inline-images
5896 :keys "C-c C-x C-i"
5897 :style radio
5898 :selected markdown-inline-image-overlays]
5899 ["Toggle Wiki Links" markdown-toggle-wiki-links
5900 :style radio
5901 :selected markdown-enable-wiki-links])
5902 ("Styles"
5903 ["Bold" markdown-insert-bold]
5904 ["Italic" markdown-insert-italic]
5905 ["Code" markdown-insert-code]
5906 ["Strikethrough" markdown-insert-strike-through]
5907 ["Keyboard" markdown-insert-kbd]
5908 "---"
5909 ["Blockquote" markdown-insert-blockquote]
5910 ["Preformatted" markdown-insert-pre]
5911 ["GFM Code Block" markdown-insert-gfm-code-block]
5912 ["Edit Code Block" markdown-edit-code-block (markdown-code-block-at-point-p)]
5913 "---"
5914 ["Blockquote Region" markdown-blockquote-region]
5915 ["Preformatted Region" markdown-pre-region]
5916 "---"
5917 ["Fontify Code Blocks Natively" markdown-toggle-fontify-code-blocks-natively
5918 :style radio
5919 :selected markdown-fontify-code-blocks-natively]
5920 ["LaTeX Math Support" markdown-toggle-math
5921 :style radio
5922 :selected markdown-enable-math])
5923 "---"
5924 ("Preview & Export"
5925 ["Compile" markdown-other-window]
5926 ["Preview" markdown-preview]
5927 ["Export" markdown-export]
5928 ["Export & View" markdown-export-and-preview]
5929 ["Open" markdown-open]
5930 ["Live Export" markdown-live-preview-mode
5931 :style radio
5932 :selected markdown-live-preview-mode]
5933 ["Kill ring save" markdown-kill-ring-save])
5934 ("Markup Completion and Cycling"
5935 ["Complete Markup" markdown-complete]
5936 ["Promote Element" markdown-promote :keys "C-c C--"]
5937 ["Demote Element" markdown-demote :keys "C-c C-="])
5938 "---"
5939 ["Kill Element" markdown-kill-thing-at-point]
5940 "---"
5941 ("Documentation"
5942 ["Version" markdown-show-version]
5943 ["Homepage" markdown-mode-info]
5944 ["Describe Mode" (describe-function 'markdown-mode)]
5945 ["Guide" (browse-url "https://leanpub.com/markdown-mode")])))
5948 ;;; imenu =====================================================================
5950 (defun markdown-imenu-create-nested-index ()
5951 "Create and return a nested imenu index alist for the current buffer.
5952 See `imenu-create-index-function' and `imenu--index-alist' for details."
5953 (let* ((root '(nil . nil))
5954 cur-alist
5955 (cur-level 0)
5956 (empty-heading "-")
5957 (self-heading ".")
5958 hashes pos level heading)
5959 (save-excursion
5960 (goto-char (point-min))
5961 (while (re-search-forward markdown-regex-header (point-max) t)
5962 (unless (markdown-code-block-at-point-p)
5963 (cond
5964 ((match-string-no-properties 2) ;; level 1 setext
5965 (setq heading (match-string-no-properties 1))
5966 (setq pos (match-beginning 1)
5967 level 1))
5968 ((match-string-no-properties 3) ;; level 2 setext
5969 (setq heading (match-string-no-properties 1))
5970 (setq pos (match-beginning 1)
5971 level 2))
5972 ((setq hashes (markdown-trim-whitespace
5973 (match-string-no-properties 4)))
5974 (setq heading (match-string-no-properties 5)
5975 pos (match-beginning 4)
5976 level (length hashes))))
5977 (let ((alist (list (cons heading pos))))
5978 (cond
5979 ((= cur-level level) ; new sibling
5980 (setcdr cur-alist alist)
5981 (setq cur-alist alist))
5982 ((< cur-level level) ; first child
5983 (dotimes (_ (- level cur-level 1))
5984 (setq alist (list (cons empty-heading alist))))
5985 (if cur-alist
5986 (let* ((parent (car cur-alist))
5987 (self-pos (cdr parent)))
5988 (setcdr parent (cons (cons self-heading self-pos) alist)))
5989 (setcdr root alist)) ; primogenitor
5990 (setq cur-alist alist)
5991 (setq cur-level level))
5992 (t ; new sibling of an ancestor
5993 (let ((sibling-alist (last (cdr root))))
5994 (dotimes (_ (1- level))
5995 (setq sibling-alist (last (cdar sibling-alist))))
5996 (setcdr sibling-alist alist)
5997 (setq cur-alist alist))
5998 (setq cur-level level))))))
5999 (cdr root))))
6001 (defun markdown-imenu-create-flat-index ()
6002 "Create and return a flat imenu index alist for the current buffer.
6003 See `imenu-create-index-function' and `imenu--index-alist' for details."
6004 (let* ((empty-heading "-") index heading pos)
6005 (save-excursion
6006 (goto-char (point-min))
6007 (while (re-search-forward markdown-regex-header (point-max) t)
6008 (when (and (not (markdown-code-block-at-point-p))
6009 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin)))
6010 (cond
6011 ((setq heading (match-string-no-properties 1))
6012 (setq pos (match-beginning 1)))
6013 ((setq heading (match-string-no-properties 5))
6014 (setq pos (match-beginning 4))))
6015 (or (> (length heading) 0)
6016 (setq heading empty-heading))
6017 (setq index (append index (list (cons heading pos))))))
6018 index)))
6021 ;;; References ================================================================
6023 (defun markdown-reference-goto-definition ()
6024 "Jump to the definition of the reference at point or create it."
6025 (interactive)
6026 (when (thing-at-point-looking-at markdown-regex-link-reference)
6027 (let* ((text (match-string-no-properties 3))
6028 (reference (match-string-no-properties 6))
6029 (target (downcase (if (string= reference "") text reference)))
6030 (loc (cadr (save-match-data (markdown-reference-definition target)))))
6031 (if loc
6032 (goto-char loc)
6033 (goto-char (match-beginning 0))
6034 (markdown-insert-reference-definition target)))))
6036 (defun markdown-reference-find-links (reference)
6037 "Return a list of all links for REFERENCE.
6038 REFERENCE should not include the surrounding square brackets.
6039 Elements of the list have the form (text start line), where
6040 text is the link text, start is the location at the beginning of
6041 the link, and line is the line number on which the link appears."
6042 (let* ((ref-quote (regexp-quote reference))
6043 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
6044 ref-quote ref-quote))
6045 links)
6046 (save-excursion
6047 (goto-char (point-min))
6048 (while (re-search-forward regexp nil t)
6049 (let* ((text (or (match-string-no-properties 1)
6050 (match-string-no-properties 2)))
6051 (start (match-beginning 0))
6052 (line (markdown-line-number-at-pos)))
6053 (cl-pushnew (list text start line) links :test #'equal))))
6054 links))
6056 (defun markdown-get-undefined-refs ()
6057 "Return a list of undefined Markdown references.
6058 Result is an alist of pairs (reference . occurrences), where
6059 occurrences is itself another alist of pairs (label . line-number).
6060 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
6061 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
6062 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
6063 (let ((missing))
6064 (save-excursion
6065 (goto-char (point-min))
6066 (while
6067 (re-search-forward markdown-regex-link-reference nil t)
6068 (let* ((text (match-string-no-properties 3))
6069 (reference (match-string-no-properties 6))
6070 (target (downcase (if (string= reference "") text reference))))
6071 (unless (markdown-reference-definition target)
6072 (let ((entry (assoc target missing)))
6073 (if (not entry)
6074 (cl-pushnew
6075 (cons target (list (cons text (markdown-line-number-at-pos))))
6076 missing :test #'equal)
6077 (setcdr entry
6078 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
6079 (reverse missing))))
6081 (defconst markdown-reference-check-buffer
6082 "*Undefined references for %buffer%*"
6083 "Pattern for name of buffer for listing undefined references.
6084 The string %buffer% will be replaced by the corresponding
6085 `markdown-mode' buffer name.")
6087 (defun markdown-reference-check-buffer (&optional buffer-name)
6088 "Name and return buffer for reference checking.
6089 BUFFER-NAME is the name of the main buffer being visited."
6090 (or buffer-name (setq buffer-name (buffer-name)))
6091 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
6092 "%buffer%" buffer-name
6093 markdown-reference-check-buffer))))
6094 (with-current-buffer refbuf
6095 (when view-mode
6096 (View-exit-and-edit))
6097 (use-local-map button-buffer-map)
6098 (erase-buffer))
6099 refbuf))
6101 (defconst markdown-reference-links-buffer
6102 "*Reference links for %buffer%*"
6103 "Pattern for name of buffer for listing references.
6104 The string %buffer% will be replaced by the corresponding buffer name.")
6106 (defun markdown-reference-links-buffer (&optional buffer-name)
6107 "Name, setup, and return a buffer for listing links.
6108 BUFFER-NAME is the name of the main buffer being visited."
6109 (or buffer-name (setq buffer-name (buffer-name)))
6110 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
6111 "%buffer%" buffer-name
6112 markdown-reference-links-buffer))))
6113 (with-current-buffer linkbuf
6114 (when view-mode
6115 (View-exit-and-edit))
6116 (use-local-map button-buffer-map)
6117 (erase-buffer))
6118 linkbuf))
6120 ;; Add an empty Markdown reference definition to buffer
6121 ;; specified in the 'target-buffer property. The reference name is
6122 ;; the button's label.
6123 (define-button-type 'markdown-undefined-reference-button
6124 'help-echo "mouse-1, RET: create definition for undefined reference"
6125 'follow-link t
6126 'face 'bold
6127 'action (lambda (b)
6128 (let ((buffer (button-get b 'target-buffer))
6129 (line (button-get b 'target-line))
6130 (label (button-label b)))
6131 (switch-to-buffer-other-window buffer)
6132 (goto-char (point-min))
6133 (forward-line line)
6134 (markdown-insert-reference-definition label)
6135 (markdown-check-refs t))))
6137 ;; Jump to line in buffer specified by 'target-buffer property.
6138 ;; Line number is button's 'line property.
6139 (define-button-type 'markdown-goto-line-button
6140 'help-echo "mouse-1, RET: go to line"
6141 'follow-link t
6142 'face 'italic
6143 'action (lambda (b)
6144 (message (button-get b 'buffer))
6145 (switch-to-buffer-other-window (button-get b 'target-buffer))
6146 ;; use call-interactively to silence compiler
6147 (let ((current-prefix-arg (button-get b 'target-line)))
6148 (call-interactively 'goto-line))))
6150 ;; Jumps to a particular link at location given by 'target-char
6151 ;; property in buffer given by 'target-buffer property.
6152 (define-button-type 'markdown-location-button
6153 'help-echo "mouse-1, RET: jump to location of link"
6154 'follow-link t
6155 'face 'bold
6156 'action (lambda (b)
6157 (let ((target (button-get b 'target-buffer))
6158 (loc (button-get b 'target-char)))
6159 (kill-buffer-and-window)
6160 (switch-to-buffer target)
6161 (goto-char loc))))
6163 (defun markdown-insert-undefined-reference-button (reference oldbuf)
6164 "Insert a button for creating REFERENCE in buffer OLDBUF.
6165 REFERENCE should be a list of the form (reference . occurrences),
6166 as by `markdown-get-undefined-refs'."
6167 (let ((label (car reference)))
6168 ;; Create a reference button
6169 (insert-button label
6170 :type 'markdown-undefined-reference-button
6171 'target-buffer oldbuf
6172 'target-line (cdr (car (cdr reference))))
6173 (insert " (")
6174 (dolist (occurrence (cdr reference))
6175 (let ((line (cdr occurrence)))
6176 ;; Create a line number button
6177 (insert-button (number-to-string line)
6178 :type 'markdown-goto-line-button
6179 'target-buffer oldbuf
6180 'target-line line)
6181 (insert " ")))
6182 (delete-char -1)
6183 (insert ")")
6184 (newline)))
6186 (defun markdown-insert-link-button (link oldbuf)
6187 "Insert a button for jumping to LINK in buffer OLDBUF.
6188 LINK should be a list of the form (text char line) containing
6189 the link text, location, and line number."
6190 (let ((label (cl-first link))
6191 (char (cl-second link))
6192 (line (cl-third link)))
6193 ;; Create a reference button
6194 (insert-button label
6195 :type 'markdown-location-button
6196 'target-buffer oldbuf
6197 'target-char char)
6198 (insert (format " (line %d)\n" line))))
6200 (defun markdown-reference-goto-link (&optional reference)
6201 "Jump to the location of the first use of REFERENCE."
6202 (interactive)
6203 (unless reference
6204 (if (thing-at-point-looking-at markdown-regex-reference-definition)
6205 (setq reference (match-string-no-properties 2))
6206 (user-error "No reference definition at point")))
6207 (let ((links (markdown-reference-find-links reference)))
6208 (cond ((= (length links) 1)
6209 (goto-char (cadr (car links))))
6210 ((> (length links) 1)
6211 (let ((oldbuf (current-buffer))
6212 (linkbuf (markdown-reference-links-buffer)))
6213 (with-current-buffer linkbuf
6214 (insert "Links using reference " reference ":\n\n")
6215 (dolist (link (reverse links))
6216 (markdown-insert-link-button link oldbuf)))
6217 (view-buffer-other-window linkbuf)
6218 (goto-char (point-min))
6219 (forward-line 2)))
6221 (error "No links for reference %s" reference)))))
6223 (defun markdown-check-refs (&optional silent)
6224 "Show all undefined Markdown references in current `markdown-mode' buffer.
6225 If SILENT is non-nil, do not message anything when no undefined
6226 references found.
6227 Links which have empty reference definitions are considered to be
6228 defined."
6229 (interactive "P")
6230 (when (not (eq major-mode 'markdown-mode))
6231 (user-error "Not available in current mode"))
6232 (let ((oldbuf (current-buffer))
6233 (refs (markdown-get-undefined-refs))
6234 (refbuf (markdown-reference-check-buffer)))
6235 (if (null refs)
6236 (progn
6237 (when (not silent)
6238 (message "No undefined references found"))
6239 (kill-buffer refbuf))
6240 (with-current-buffer refbuf
6241 (insert "The following references are undefined:\n\n")
6242 (dolist (ref refs)
6243 (markdown-insert-undefined-reference-button ref oldbuf))
6244 (view-buffer-other-window refbuf)
6245 (goto-char (point-min))
6246 (forward-line 2)))))
6249 ;;; Lists =====================================================================
6251 (defun markdown-insert-list-item (&optional arg)
6252 "Insert a new list item.
6253 If the point is inside unordered list, insert a bullet mark. If
6254 the point is inside ordered list, insert the next number followed
6255 by a period. Use the previous list item to determine the amount
6256 of whitespace to place before and after list markers.
6258 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
6259 decrease the indentation by one level.
6261 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
6262 increase the indentation by one level."
6263 (interactive "p")
6264 (let (bounds cur-indent marker indent new-indent new-loc)
6265 (save-match-data
6266 ;; Look for a list item on current or previous non-blank line
6267 (save-excursion
6268 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
6269 (not (bobp))
6270 (markdown-cur-line-blank-p))
6271 (forward-line -1)))
6272 (when bounds
6273 (cond ((save-excursion
6274 (skip-chars-backward " \t")
6275 (looking-at-p markdown-regex-list))
6276 (beginning-of-line)
6277 (insert "\n")
6278 (forward-line -1))
6279 ((not (markdown-cur-line-blank-p))
6280 (newline)))
6281 (setq new-loc (point)))
6282 ;; Look ahead for a list item on next non-blank line
6283 (unless bounds
6284 (save-excursion
6285 (while (and (null bounds)
6286 (not (eobp))
6287 (markdown-cur-line-blank-p))
6288 (forward-line)
6289 (setq bounds (markdown-cur-list-item-bounds))))
6290 (when bounds
6291 (setq new-loc (point))
6292 (unless (markdown-cur-line-blank-p)
6293 (newline))))
6294 (if (not bounds)
6295 ;; When not in a list, start a new unordered one
6296 (progn
6297 (unless (markdown-cur-line-blank-p)
6298 (insert "\n"))
6299 (insert markdown-unordered-list-item-prefix))
6300 ;; Compute indentation and marker for new list item
6301 (setq cur-indent (nth 2 bounds))
6302 (setq marker (nth 4 bounds))
6303 ;; If current item is a GFM checkbox, insert new unchecked checkbox.
6304 (when (nth 5 bounds)
6305 (setq marker
6306 (concat marker
6307 (replace-regexp-in-string "[Xx]" " " (nth 5 bounds)))))
6308 (cond
6309 ;; Dedent: decrement indentation, find previous marker.
6310 ((= arg 4)
6311 (setq indent (max (- cur-indent 4) 0))
6312 (let ((prev-bounds
6313 (save-excursion
6314 (goto-char (nth 0 bounds))
6315 (when (markdown-up-list)
6316 (markdown-cur-list-item-bounds)))))
6317 (when prev-bounds
6318 (setq marker (nth 4 prev-bounds)))))
6319 ;; Indent: increment indentation by 4, use same marker.
6320 ((= arg 16) (setq indent (+ cur-indent 4)))
6321 ;; Same level: keep current indentation and marker.
6322 (t (setq indent cur-indent)))
6323 (setq new-indent (make-string indent 32))
6324 (goto-char new-loc)
6325 (cond
6326 ;; Ordered list
6327 ((string-match-p "[0-9]" marker)
6328 (if (= arg 16) ;; starting a new column indented one more level
6329 (insert (concat new-indent "1. "))
6330 ;; Don't use previous match-data
6331 (set-match-data nil)
6332 ;; travel up to the last item and pick the correct number. If
6333 ;; the argument was nil, "new-indent = cur-indent" is the same,
6334 ;; so we don't need special treatment. Neat.
6335 (save-excursion
6336 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
6337 (>= (forward-line -1) 0))))
6338 (let* ((old-prefix (match-string 1))
6339 (old-spacing (match-string 2))
6340 (new-prefix (if old-prefix
6341 (int-to-string (1+ (string-to-number old-prefix)))
6342 "1"))
6343 (space-adjust (- (length old-prefix) (length new-prefix)))
6344 (new-spacing (if (and (match-string 2)
6345 (not (string-match-p "\t" old-spacing))
6346 (< space-adjust 0)
6347 (> space-adjust (- 1 (length (match-string 2)))))
6348 (substring (match-string 2) 0 space-adjust)
6349 (or old-spacing ". "))))
6350 (insert (concat new-indent new-prefix new-spacing)))))
6351 ;; Unordered list, GFM task list, or ordered list with hash mark
6352 ((string-match-p "[\\*\\+-]\\|#\\." marker)
6353 (insert new-indent marker)))))))
6355 (defun markdown-move-list-item-up ()
6356 "Move the current list item up in the list when possible.
6357 In nested lists, move child items with the parent item."
6358 (interactive)
6359 (let (cur prev old)
6360 (when (setq cur (markdown-cur-list-item-bounds))
6361 (setq old (point))
6362 (goto-char (nth 0 cur))
6363 (if (markdown-prev-list-item (nth 3 cur))
6364 (progn
6365 (setq prev (markdown-cur-list-item-bounds))
6366 (condition-case nil
6367 (progn
6368 (transpose-regions (nth 0 prev) (nth 1 prev)
6369 (nth 0 cur) (nth 1 cur) t)
6370 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
6371 ;; Catch error in case regions overlap.
6372 (error (goto-char old))))
6373 (goto-char old)))))
6375 (defun markdown-move-list-item-down ()
6376 "Move the current list item down in the list when possible.
6377 In nested lists, move child items with the parent item."
6378 (interactive)
6379 (let (cur next old)
6380 (when (setq cur (markdown-cur-list-item-bounds))
6381 (setq old (point))
6382 (if (markdown-next-list-item (nth 3 cur))
6383 (progn
6384 (setq next (markdown-cur-list-item-bounds))
6385 (condition-case nil
6386 (progn
6387 (transpose-regions (nth 0 cur) (nth 1 cur)
6388 (nth 0 next) (nth 1 next) nil)
6389 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
6390 ;; Catch error in case regions overlap.
6391 (error (goto-char old))))
6392 (goto-char old)))))
6394 (defun markdown-demote-list-item (&optional bounds)
6395 "Indent (or demote) the current list item.
6396 Optionally, BOUNDS of the current list item may be provided if available.
6397 In nested lists, demote child items as well."
6398 (interactive)
6399 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6400 (save-excursion
6401 (let ((end-marker (set-marker (make-marker) (nth 1 bounds))))
6402 (goto-char (nth 0 bounds))
6403 (while (< (point) end-marker)
6404 (unless (markdown-cur-line-blank-p)
6405 (insert (make-string markdown-list-indent-width ? )))
6406 (forward-line))))))
6408 (defun markdown-promote-list-item (&optional bounds)
6409 "Unindent (or promote) the current list item.
6410 Optionally, BOUNDS of the current list item may be provided if available.
6411 In nested lists, demote child items as well."
6412 (interactive)
6413 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6414 (save-excursion
6415 (save-match-data
6416 (let ((end-marker (set-marker (make-marker) (nth 1 bounds)))
6417 num regexp)
6418 (goto-char (nth 0 bounds))
6419 (when (looking-at (format "^[ ]\\{1,%d\\}"
6420 markdown-list-indent-width))
6421 (setq num (- (match-end 0) (match-beginning 0)))
6422 (setq regexp (format "^[ ]\\{1,%d\\}" num))
6423 (while (and (< (point) end-marker)
6424 (re-search-forward regexp end-marker t))
6425 (replace-match "" nil nil)
6426 (forward-line))))))))
6428 (defun markdown-cleanup-list-numbers-level (&optional pfx)
6429 "Update the numbering for level PFX (as a string of spaces).
6431 Assume that the previously found match was for a numbered item in
6432 a list."
6433 (let ((cpfx pfx)
6434 (idx 0)
6435 (continue t)
6436 (step t)
6437 (sep nil))
6438 (while (and continue (not (eobp)))
6439 (setq step t)
6440 (cond
6441 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
6442 (setq cpfx (match-string-no-properties 1))
6443 (cond
6444 ((string= cpfx pfx)
6445 (save-excursion
6446 (replace-match
6447 (concat pfx (number-to-string (setq idx (1+ idx))) ". ")))
6448 (setq sep nil))
6449 ;; indented a level
6450 ((string< pfx cpfx)
6451 (setq sep (markdown-cleanup-list-numbers-level cpfx))
6452 (setq step nil))
6453 ;; exit the loop
6455 (setq step nil)
6456 (setq continue nil))))
6458 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
6459 (setq cpfx (match-string-no-properties 1))
6460 (cond
6461 ;; reset if separated before
6462 ((string= cpfx pfx) (when sep (setq idx 0)))
6463 ((string< cpfx pfx)
6464 (setq step nil)
6465 (setq continue nil))))
6466 (t (setq sep t)))
6468 (when step
6469 (beginning-of-line)
6470 (setq continue (= (forward-line) 0))))
6471 sep))
6473 (defun markdown-cleanup-list-numbers ()
6474 "Update the numbering of ordered lists."
6475 (interactive)
6476 (save-excursion
6477 (goto-char (point-min))
6478 (markdown-cleanup-list-numbers-level "")))
6481 ;;; Movement ==================================================================
6483 (defun markdown-beginning-of-defun (&optional arg)
6484 "`beginning-of-defun-function' for Markdown.
6485 This is used to find the beginning of the defun and should behave
6486 like ‘beginning-of-defun’, returning non-nil if it found the
6487 beginning of a defun. It moves the point backward, right before a
6488 heading which defines a defun. When ARG is non-nil, repeat that
6489 many times. When ARG is negative, move forward to the ARG-th
6490 following section."
6491 (or arg (setq arg 1))
6492 (when (< arg 0) (end-of-line))
6493 ;; Adjust position for setext headings.
6494 (when (and (thing-at-point-looking-at markdown-regex-header-setext)
6495 (not (= (point) (match-beginning 0)))
6496 (not (markdown-code-block-at-point-p)))
6497 (goto-char (match-end 0)))
6498 (let (found)
6499 ;; Move backward with positive argument.
6500 (while (and (not (bobp)) (> arg 0))
6501 (setq found nil)
6502 (while (and (not found)
6503 (not (bobp))
6504 (re-search-backward markdown-regex-header nil 'move))
6505 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6506 (setq found (match-beginning 0)))
6507 (setq arg (1- arg)))
6508 ;; Move forward with negative argument.
6509 (while (and (not (eobp)) (< arg 0))
6510 (setq found nil)
6511 (while (and (not found)
6512 (not (eobp))
6513 (re-search-forward markdown-regex-header nil 'move))
6514 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6515 (setq found (match-beginning 0)))
6516 (setq arg (1+ arg)))
6517 (when found
6518 (beginning-of-line)
6519 t)))
6521 (defun markdown-end-of-defun ()
6522 "`end-of-defun-function’ for Markdown.
6523 This is used to find the end of the defun at point.
6524 It is called with no argument, right after calling ‘beginning-of-defun-raw’,
6525 so it can assume that point is at the beginning of the defun body.
6526 It should move point to the first position after the defun."
6527 (or (eobp) (forward-char 1))
6528 (let (found)
6529 (while (and (not found)
6530 (not (eobp))
6531 (re-search-forward markdown-regex-header nil 'move))
6532 (when (not (markdown-code-block-at-pos (match-beginning 0)))
6533 (setq found (match-beginning 0))))
6534 (when found
6535 (goto-char found)
6536 (skip-syntax-backward "-"))))
6538 (make-obsolete 'markdown-beginning-of-block 'markdown-beginning-of-text-block "v2.2")
6540 (defun markdown-beginning-of-text-block ()
6541 "Move backward to previous beginning of a plain text block.
6542 This function simply looks for blank lines without considering
6543 the surrounding context in light of Markdown syntax. For that, see
6544 `markdown-backward-block'."
6545 (interactive)
6546 (let ((start (point)))
6547 (if (re-search-backward markdown-regex-block-separator nil t)
6548 (goto-char (match-end 0))
6549 (goto-char (point-min)))
6550 (when (and (= start (point)) (not (bobp)))
6551 (forward-line -1)
6552 (if (re-search-backward markdown-regex-block-separator nil t)
6553 (goto-char (match-end 0))
6554 (goto-char (point-min))))))
6556 (make-obsolete 'markdown-end-of-block 'markdown-end-of-text-block "v2.2")
6558 (defun markdown-end-of-text-block ()
6559 "Move forward to next beginning of a plain text block.
6560 This function simply looks for blank lines without considering
6561 the surrounding context in light of Markdown syntax. For that, see
6562 `markdown-forward-block'."
6563 (interactive)
6564 (beginning-of-line)
6565 (skip-syntax-forward "-")
6566 (when (= (point) (point-min))
6567 (forward-char))
6568 (if (re-search-forward markdown-regex-block-separator nil t)
6569 (goto-char (match-end 0))
6570 (goto-char (point-max)))
6571 (skip-syntax-backward "-")
6572 (forward-line))
6574 (defun markdown-backward-paragraph (&optional arg)
6575 "Move the point to the start of the current paragraph.
6576 With argument ARG, do it ARG times; a negative argument ARG = -N
6577 means move forward N blocks."
6578 (interactive "p")
6579 (or arg (setq arg 1))
6580 (if (< arg 0)
6581 (markdown-forward-paragraph (- arg))
6582 (dotimes (_ arg)
6583 ;; Skip over whitespace in between paragraphs when moving backward.
6584 (skip-syntax-backward "-")
6585 (beginning-of-line)
6586 ;; Skip over code block endings.
6587 (when (markdown-range-properties-exist
6588 (point-at-bol) (point-at-eol)
6589 '(markdown-gfm-block-end
6590 markdown-tilde-fence-end))
6591 (forward-line -1))
6592 ;; Skip over blank lines inside blockquotes.
6593 (while (and (not (eobp))
6594 (looking-at markdown-regex-blockquote)
6595 (= (length (match-string 3)) 0))
6596 (forward-line -1))
6597 ;; Proceed forward based on the type of block of paragraph.
6598 (let (bounds skip)
6599 (cond
6600 ;; Blockquotes
6601 ((looking-at markdown-regex-blockquote)
6602 (while (and (not (bobp))
6603 (looking-at markdown-regex-blockquote)
6604 (> (length (match-string 3)) 0)) ;; not blank
6605 (forward-line -1))
6606 (forward-line))
6607 ;; List items
6608 ((setq bounds (markdown-cur-list-item-bounds))
6609 (goto-char (nth 0 bounds)))
6610 ;; Other
6612 (while (and (not (bobp))
6613 (not skip)
6614 (not (markdown-cur-line-blank-p))
6615 (not (looking-at markdown-regex-blockquote))
6616 (not (markdown-range-properties-exist
6617 (point-at-bol) (point-at-eol)
6618 '(markdown-gfm-block-end
6619 markdown-tilde-fence-end))))
6620 (setq skip (markdown-range-properties-exist
6621 (point-at-bol) (point-at-eol)
6622 '(markdown-gfm-block-begin
6623 markdown-tilde-fence-begin)))
6624 (forward-line -1))
6625 (unless (bobp)
6626 (forward-line 1))))))))
6628 (defun markdown-forward-paragraph (&optional arg)
6629 "Move forward to the next end of a paragraph.
6630 With argument ARG, do it ARG times; a negative argument ARG = -N
6631 means move backward N blocks."
6632 (interactive "p")
6633 (or arg (setq arg 1))
6634 (if (< arg 0)
6635 (markdown-backward-paragraph (- arg))
6636 (dotimes (_ arg)
6637 ;; Skip whitespace in between paragraphs.
6638 (when (markdown-cur-line-blank-p)
6639 (skip-syntax-forward "-")
6640 (beginning-of-line))
6641 ;; Proceed forward based on the type of block.
6642 (let (bounds skip)
6643 (cond
6644 ;; Blockquotes
6645 ((looking-at markdown-regex-blockquote)
6646 ;; Skip over blank lines inside blockquotes.
6647 (while (and (not (eobp))
6648 (looking-at markdown-regex-blockquote)
6649 (= (length (match-string 3)) 0))
6650 (forward-line))
6651 ;; Move to end of quoted text block
6652 (while (and (not (eobp))
6653 (looking-at markdown-regex-blockquote)
6654 (> (length (match-string 3)) 0)) ;; not blank
6655 (forward-line)))
6656 ;; List items
6657 ((and (markdown-cur-list-item-bounds)
6658 (setq bounds (markdown-next-list-item-bounds)))
6659 (goto-char (nth 0 bounds)))
6660 ;; Other
6662 (forward-line)
6663 (while (and (not (eobp))
6664 (not skip)
6665 (not (markdown-cur-line-blank-p))
6666 (not (looking-at markdown-regex-blockquote))
6667 (not (markdown-range-properties-exist
6668 (point-at-bol) (point-at-eol)
6669 '(markdown-gfm-block-begin
6670 markdown-tilde-fence-begin))))
6671 (setq skip (markdown-range-properties-exist
6672 (point-at-bol) (point-at-eol)
6673 '(markdown-gfm-block-end
6674 markdown-tilde-fence-end)))
6675 (forward-line))))))))
6677 (defun markdown-backward-block (&optional arg)
6678 "Move the point to the start of the current Markdown block.
6679 Moves across complete code blocks, list items, and blockquotes,
6680 but otherwise stops at blank lines, headers, and horizontal
6681 rules. With argument ARG, do it ARG times; a negative argument
6682 ARG = -N means move forward N blocks."
6683 (interactive "p")
6684 (or arg (setq arg 1))
6685 (if (< arg 0)
6686 (markdown-forward-block (- arg))
6687 (dotimes (_ arg)
6688 ;; Skip over whitespace in between blocks when moving backward,
6689 ;; unless at a block boundary with no whitespace.
6690 (skip-syntax-backward "-")
6691 (beginning-of-line)
6692 ;; Proceed forward based on the type of block.
6693 (cond
6694 ;; Code blocks
6695 ((and (markdown-code-block-at-pos (point)) ;; this line
6696 (markdown-code-block-at-pos (point-at-bol 0))) ;; previous line
6697 (forward-line -1)
6698 (while (and (markdown-code-block-at-point-p) (not (bobp)))
6699 (forward-line -1))
6700 (forward-line))
6701 ;; Headings
6702 ((markdown-heading-at-point)
6703 (goto-char (match-beginning 0)))
6704 ;; Horizontal rules
6705 ((looking-at markdown-regex-hr))
6706 ;; Blockquotes
6707 ((looking-at markdown-regex-blockquote)
6708 (forward-line -1)
6709 (while (and (looking-at markdown-regex-blockquote)
6710 (not (bobp)))
6711 (forward-line -1))
6712 (forward-line))
6713 ;; List items
6714 ((markdown-cur-list-item-bounds)
6715 (markdown-beginning-of-list))
6716 ;; Other
6718 ;; Move forward in case it is a one line regular paragraph.
6719 (unless (markdown-next-line-blank-p)
6720 (forward-line))
6721 (unless (markdown-prev-line-blank-p)
6722 (markdown-backward-paragraph)))))))
6724 (defun markdown-forward-block (&optional arg)
6725 "Move forward to the next end of a Markdown block.
6726 Moves across complete code blocks, list items, and blockquotes,
6727 but otherwise stops at blank lines, headers, and horizontal
6728 rules. With argument ARG, do it ARG times; a negative argument
6729 ARG = -N means move backward N blocks."
6730 (interactive "p")
6731 (or arg (setq arg 1))
6732 (if (< arg 0)
6733 (markdown-backward-block (- arg))
6734 (dotimes (_ arg)
6735 ;; Skip over whitespace in between blocks when moving forward.
6736 (if (markdown-cur-line-blank-p)
6737 (skip-syntax-forward "-")
6738 (beginning-of-line))
6739 ;; Proceed forward based on the type of block.
6740 (cond
6741 ;; Code blocks
6742 ((markdown-code-block-at-point-p)
6743 (forward-line)
6744 (while (and (markdown-code-block-at-point-p) (not (eobp)))
6745 (forward-line)))
6746 ;; Headings
6747 ((looking-at markdown-regex-header)
6748 (goto-char (or (match-end 4) (match-end 2) (match-end 3)))
6749 (forward-line))
6750 ;; Horizontal rules
6751 ((looking-at markdown-regex-hr)
6752 (forward-line))
6753 ;; Blockquotes
6754 ((looking-at markdown-regex-blockquote)
6755 (forward-line)
6756 (while (and (looking-at markdown-regex-blockquote) (not (eobp)))
6757 (forward-line)))
6758 ;; List items
6759 ((markdown-cur-list-item-bounds)
6760 (markdown-end-of-list)
6761 (forward-line))
6762 ;; Other
6763 (t (markdown-forward-paragraph))))
6764 (skip-syntax-backward "-")
6765 (unless (eobp)
6766 (forward-char 1))))
6768 (defun markdown-backward-page (&optional count)
6769 "Move backward to boundary of the current toplevel section.
6770 With COUNT, repeat, or go forward if negative."
6771 (interactive "p")
6772 (or count (setq count 1))
6773 (if (< count 0)
6774 (markdown-forward-page (- count))
6775 (skip-syntax-backward "-")
6776 (or (markdown-back-to-heading-over-code-block t t)
6777 (goto-char (point-min)))
6778 (when (looking-at markdown-regex-header)
6779 (let ((level (markdown-outline-level)))
6780 (when (> level 1) (markdown-up-heading level))
6781 (when (> count 1)
6782 (condition-case nil
6783 (markdown-backward-same-level (1- count))
6784 (error (goto-char (point-min)))))))))
6786 (defun markdown-forward-page (&optional count)
6787 "Move forward to boundary of the current toplevel section.
6788 With COUNT, repeat, or go backward if negative."
6789 (interactive "p")
6790 (or count (setq count 1))
6791 (if (< count 0)
6792 (markdown-backward-page (- count))
6793 (if (markdown-back-to-heading-over-code-block t t)
6794 (let ((level (markdown-outline-level)))
6795 (when (> level 1) (markdown-up-heading level))
6796 (condition-case nil
6797 (markdown-forward-same-level count)
6798 (error (goto-char (point-max)))))
6799 (markdown-next-visible-heading 1))))
6801 (defun markdown-next-link ()
6802 "Jump to next inline, reference, or wiki link.
6803 If successful, return point. Otherwise, return nil.
6804 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
6805 (interactive)
6806 (let ((opoint (point)))
6807 (when (or (markdown-link-p) (markdown-wiki-link-p))
6808 ;; At a link already, move past it.
6809 (goto-char (+ (match-end 0) 1)))
6810 ;; Search for the next wiki link and move to the beginning.
6811 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t)
6812 (markdown-code-block-at-point-p)
6813 (< (point) (point-max))))
6814 (if (and (not (eq (point) opoint))
6815 (or (markdown-link-p) (markdown-wiki-link-p)))
6816 ;; Group 1 will move past non-escape character in wiki link regexp.
6817 ;; Go to beginning of group zero for all other link types.
6818 (goto-char (or (match-beginning 1) (match-beginning 0)))
6819 (goto-char opoint)
6820 nil)))
6822 (defun markdown-previous-link ()
6823 "Jump to previous wiki link.
6824 If successful, return point. Otherwise, return nil.
6825 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
6826 (interactive)
6827 (let ((opoint (point)))
6828 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t)
6829 (markdown-code-block-at-point-p)
6830 (> (point) (point-min))))
6831 (if (and (not (eq (point) opoint))
6832 (or (markdown-link-p) (markdown-wiki-link-p)))
6833 (goto-char (or (match-beginning 1) (match-beginning 0)))
6834 (goto-char opoint)
6835 nil)))
6838 ;;; Outline ===================================================================
6840 (defun markdown-move-heading-common (move-fn &optional arg adjust)
6841 "Wrapper for `outline-mode' functions to skip false positives.
6842 MOVE-FN is a function and ARG is its argument. For example,
6843 headings inside preformatted code blocks may match
6844 `outline-regexp' but should not be considered as headings.
6845 When ADJUST is non-nil, adjust the point for interactive calls
6846 to avoid leaving the point at invisible markup. This adjustment
6847 generally should only be done for interactive calls, since other
6848 functions may expect the point to be at the beginning of the
6849 regular expression."
6850 (let ((prev -1) (start (point)))
6851 (if arg (funcall move-fn arg) (funcall move-fn))
6852 (while (and (/= prev (point)) (markdown-code-block-at-point-p))
6853 (setq prev (point))
6854 (if arg (funcall move-fn arg) (funcall move-fn)))
6855 ;; Adjust point for setext headings and invisible text.
6856 (save-match-data
6857 (when (and adjust (thing-at-point-looking-at markdown-regex-header))
6858 (if markdown-hide-markup
6859 ;; Move to beginning of heading text if markup is hidden.
6860 (goto-char (or (match-beginning 1) (match-beginning 5)))
6861 ;; Move to beginning of markup otherwise.
6862 (goto-char (or (match-beginning 1) (match-beginning 4))))))
6863 (if (= (point) start) nil (point))))
6865 (defun markdown-next-visible-heading (arg)
6866 "Move to the next visible heading line of any level.
6867 With argument, repeats or can move backward if negative. ARG is
6868 passed to `outline-next-visible-heading'."
6869 (interactive "p")
6870 (markdown-move-heading-common #'outline-next-visible-heading arg 'adjust))
6872 (defun markdown-previous-visible-heading (arg)
6873 "Move to the previous visible heading line of any level.
6874 With argument, repeats or can move backward if negative. ARG is
6875 passed to `outline-previous-visible-heading'."
6876 (interactive "p")
6877 (markdown-move-heading-common #'outline-previous-visible-heading arg 'adjust))
6879 (defun markdown-next-heading ()
6880 "Move to the next heading line of any level."
6881 (markdown-move-heading-common #'outline-next-heading))
6883 (defun markdown-previous-heading ()
6884 "Move to the previous heading line of any level."
6885 (markdown-move-heading-common #'outline-previous-heading))
6887 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok no-error)
6888 "Move back to the beginning of the previous heading.
6889 Returns t if the point is at a heading, the location if a heading
6890 was found, and nil otherwise.
6891 Only visible heading lines are considered, unless INVISIBLE-OK is
6892 non-nil. Throw an error if there is no previous heading unless
6893 NO-ERROR is non-nil.
6894 Leaves match data intact for `markdown-regex-header'."
6895 (beginning-of-line)
6896 (or (and (markdown-heading-at-point)
6897 (not (markdown-code-block-at-point-p)))
6898 (let (found)
6899 (save-excursion
6900 (while (and (not found)
6901 (re-search-backward markdown-regex-header nil t))
6902 (when (and (or invisible-ok (not (outline-invisible-p)))
6903 (not (markdown-code-block-at-point-p)))
6904 (setq found (point))))
6905 (if (not found)
6906 (unless no-error (user-error "Before first heading"))
6907 (setq found (point))))
6908 (when found (goto-char found)))))
6910 (defun markdown-forward-same-level (arg)
6911 "Move forward to the ARG'th heading at same level as this one.
6912 Stop at the first and last headings of a superior heading."
6913 (interactive "p")
6914 (markdown-back-to-heading-over-code-block)
6915 (markdown-move-heading-common #'outline-forward-same-level arg 'adjust))
6917 (defun markdown-backward-same-level (arg)
6918 "Move backward to the ARG'th heading at same level as this one.
6919 Stop at the first and last headings of a superior heading."
6920 (interactive "p")
6921 (markdown-back-to-heading-over-code-block)
6922 (while (> arg 0)
6923 (let ((point-to-move-to
6924 (save-excursion
6925 (markdown-move-heading-common #'outline-get-last-sibling nil 'adjust))))
6926 (if point-to-move-to
6927 (progn
6928 (goto-char point-to-move-to)
6929 (setq arg (1- arg)))
6930 (user-error "No previous same-level heading")))))
6932 (defun markdown-up-heading (arg)
6933 "Move to the visible heading line of which the present line is a subheading.
6934 With argument, move up ARG levels."
6935 (interactive "p")
6936 (and (called-interactively-p 'any)
6937 (not (eq last-command 'markdown-up-heading)) (push-mark))
6938 (markdown-move-heading-common #'outline-up-heading arg 'adjust))
6940 (defun markdown-back-to-heading (&optional invisible-ok)
6941 "Move to previous heading line, or beg of this line if it's a heading.
6942 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
6943 (markdown-move-heading-common #'outline-back-to-heading invisible-ok))
6945 (defalias 'markdown-end-of-heading 'outline-end-of-heading)
6947 (defun markdown-on-heading-p ()
6948 "Return non-nil if point is on a heading line."
6949 (get-text-property (point-at-bol) 'markdown-heading))
6951 (defun markdown-end-of-subtree (&optional invisible-OK)
6952 "Move to the end of the current subtree.
6953 Only visible heading lines are considered, unless INVISIBLE-OK is
6954 non-nil.
6955 Derived from `org-end-of-subtree'."
6956 (markdown-back-to-heading invisible-OK)
6957 (let ((first t)
6958 (level (markdown-outline-level)))
6959 (while (and (not (eobp))
6960 (or first (> (markdown-outline-level) level)))
6961 (setq first nil)
6962 (markdown-next-heading))
6963 (if (memq (preceding-char) '(?\n ?\^M))
6964 (progn
6965 ;; Go to end of line before heading
6966 (forward-char -1)
6967 (if (memq (preceding-char) '(?\n ?\^M))
6968 ;; leave blank line before heading
6969 (forward-char -1)))))
6970 (point))
6972 (defun markdown-outline-fix-visibility ()
6973 "Hide any false positive headings that should not be shown.
6974 For example, headings inside preformatted code blocks may match
6975 `outline-regexp' but should not be shown as headings when cycling.
6976 Also, the ending --- line in metadata blocks appears to be a
6977 setext header, but should not be folded."
6978 (save-excursion
6979 (goto-char (point-min))
6980 ;; Unhide any false positives in metadata blocks
6981 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin)
6982 (let ((body (progn (forward-line)
6983 (markdown-text-property-at-point
6984 'markdown-yaml-metadata-section))))
6985 (when body
6986 (let ((end (progn (goto-char (cl-second body))
6987 (markdown-text-property-at-point
6988 'markdown-yaml-metadata-end))))
6989 (outline-flag-region (point-min) (1+ (cl-second end)) nil)))))
6990 ;; Hide any false positives in code blocks
6991 (unless (outline-on-heading-p)
6992 (outline-next-visible-heading 1))
6993 (while (< (point) (point-max))
6994 (when (markdown-code-block-at-point-p)
6995 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t))
6996 (outline-next-visible-heading 1))))
6998 (defvar markdown-cycle-global-status 1)
6999 (defvar markdown-cycle-subtree-status nil)
7001 (defun markdown-next-preface ()
7002 (let (finish)
7003 (while (and (not finish) (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
7004 nil 'move))
7005 (unless (markdown-code-block-at-point-p)
7006 (goto-char (match-beginning 0))
7007 (setq finish t))))
7008 (when (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
7009 (forward-char -1)))
7011 (defun markdown-show-entry ()
7012 (save-excursion
7013 (outline-back-to-heading t)
7014 (outline-flag-region (1- (point))
7015 (progn
7016 (markdown-next-preface)
7017 (if (= 1 (- (point-max) (point)))
7018 (point-max)
7019 (point)))
7020 nil)))
7022 ;; This function was originally derived from `org-cycle' from org.el.
7023 (defun markdown-cycle (&optional arg)
7024 "Visibility cycling for Markdown mode.
7025 If ARG is t, perform global visibility cycling. If the point is
7026 at an atx-style header, cycle visibility of the corresponding
7027 subtree. Otherwise, indent the current line or insert a tab,
7028 as appropriate, by calling `indent-for-tab-command'."
7029 (interactive "P")
7030 (cond
7031 ((eq arg t) ;; Global cycling
7032 (cond
7033 ((and (eq last-command this-command)
7034 (eq markdown-cycle-global-status 2))
7035 ;; Move from overview to contents
7036 (markdown-hide-sublevels 1)
7037 (message "CONTENTS")
7038 (setq markdown-cycle-global-status 3)
7039 (markdown-outline-fix-visibility))
7041 ((and (eq last-command this-command)
7042 (eq markdown-cycle-global-status 3))
7043 ;; Move from contents to all
7044 (markdown-show-all)
7045 (message "SHOW ALL")
7046 (setq markdown-cycle-global-status 1))
7049 ;; Defaults to overview
7050 (markdown-hide-body)
7051 (message "OVERVIEW")
7052 (setq markdown-cycle-global-status 2)
7053 (markdown-outline-fix-visibility))))
7055 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
7056 ;; At a heading: rotate between three different views
7057 (markdown-back-to-heading)
7058 (let ((goal-column 0) eoh eol eos)
7059 ;; Determine boundaries
7060 (save-excursion
7061 (markdown-back-to-heading)
7062 (save-excursion
7063 (beginning-of-line 2)
7064 (while (and (not (eobp)) ;; this is like `next-line'
7065 (get-char-property (1- (point)) 'invisible))
7066 (beginning-of-line 2)) (setq eol (point)))
7067 (markdown-end-of-heading) (setq eoh (point))
7068 (markdown-end-of-subtree t)
7069 (skip-chars-forward " \t\n")
7070 (beginning-of-line 1) ; in case this is an item
7071 (setq eos (1- (point))))
7072 ;; Find out what to do next and set `this-command'
7073 (cond
7074 ((= eos eoh)
7075 ;; Nothing is hidden behind this heading
7076 (message "EMPTY ENTRY")
7077 (setq markdown-cycle-subtree-status nil))
7078 ((>= eol eos)
7079 ;; Entire subtree is hidden in one line: open it
7080 (markdown-show-entry)
7081 (markdown-show-children)
7082 (message "CHILDREN")
7083 (setq markdown-cycle-subtree-status 'children))
7084 ((and (eq last-command this-command)
7085 (eq markdown-cycle-subtree-status 'children))
7086 ;; We just showed the children, now show everything.
7087 (markdown-show-subtree)
7088 (message "SUBTREE")
7089 (setq markdown-cycle-subtree-status 'subtree))
7091 ;; Default action: hide the subtree.
7092 (markdown-hide-subtree)
7093 (message "FOLDED")
7094 (setq markdown-cycle-subtree-status 'folded)))))
7097 (indent-for-tab-command))))
7099 (defun markdown-shifttab ()
7100 "Global visibility cycling.
7101 Calls `markdown-cycle' with argument t."
7102 (interactive)
7103 (markdown-cycle t))
7105 (defun markdown-outline-level ()
7106 "Return the depth to which a statement is nested in the outline."
7107 (cond
7108 ((markdown-code-block-at-point-p) 7) ;; Only 6 header levels are defined.
7109 ((match-end 2) 1)
7110 ((match-end 3) 2)
7111 ((match-end 4)
7112 (length (markdown-trim-whitespace (match-string-no-properties 4))))))
7114 (defun markdown-promote-subtree (&optional arg)
7115 "Promote the current subtree of ATX headings.
7116 Note that Markdown does not support heading levels higher than
7117 six and therefore level-six headings will not be promoted
7118 further. If ARG is non-nil promote the heading, otherwise
7119 demote."
7120 (interactive "*P")
7121 (save-excursion
7122 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
7123 (re-search-backward markdown-regex-header-atx nil t))
7124 (not (markdown-code-block-at-point-p)))
7125 (let ((level (length (match-string 1)))
7126 (promote-or-demote (if arg 1 -1))
7127 (remove 't))
7128 (markdown-cycle-atx promote-or-demote remove)
7129 (catch 'end-of-subtree
7130 (while (and (markdown-next-heading)
7131 (looking-at markdown-regex-header-atx))
7132 ;; Exit if this not a higher level heading; promote otherwise.
7133 (if (and (looking-at markdown-regex-header-atx)
7134 (<= (length (match-string-no-properties 1)) level))
7135 (throw 'end-of-subtree nil)
7136 (markdown-cycle-atx promote-or-demote remove))))))))
7138 (defun markdown-demote-subtree ()
7139 "Demote the current subtree of ATX headings."
7140 (interactive)
7141 (markdown-promote-subtree t))
7143 (defun markdown-move-subtree-up ()
7144 "Move the current subtree of ATX headings up."
7145 (interactive)
7146 (outline-move-subtree-up 1))
7148 (defun markdown-move-subtree-down ()
7149 "Move the current subtree of ATX headings down."
7150 (interactive)
7151 (outline-move-subtree-down 1))
7153 (defun markdown-outline-next ()
7154 "Move to next list item, when in a list, or next visible heading."
7155 (interactive)
7156 (let ((bounds (markdown-next-list-item-bounds)))
7157 (if bounds
7158 (goto-char (nth 0 bounds))
7159 (markdown-next-visible-heading 1))))
7161 (defun markdown-outline-previous ()
7162 "Move to previous list item, when in a list, or previous visible heading."
7163 (interactive)
7164 (let ((bounds (markdown-prev-list-item-bounds)))
7165 (if bounds
7166 (goto-char (nth 0 bounds))
7167 (markdown-previous-visible-heading 1))))
7169 (defun markdown-outline-next-same-level ()
7170 "Move to next list item or heading of same level."
7171 (interactive)
7172 (let ((bounds (markdown-cur-list-item-bounds)))
7173 (if bounds
7174 (markdown-next-list-item (nth 3 bounds))
7175 (markdown-forward-same-level 1))))
7177 (defun markdown-outline-previous-same-level ()
7178 "Move to previous list item or heading of same level."
7179 (interactive)
7180 (let ((bounds (markdown-cur-list-item-bounds)))
7181 (if bounds
7182 (markdown-prev-list-item (nth 3 bounds))
7183 (markdown-backward-same-level 1))))
7185 (defun markdown-outline-up ()
7186 "Move to previous list item, when in a list, or next heading."
7187 (interactive)
7188 (unless (markdown-up-list)
7189 (markdown-up-heading 1)))
7192 ;;; Marking and Narrowing =====================================================
7194 (defun markdown-mark-paragraph ()
7195 "Put mark at end of this block, point at beginning.
7196 The block marked is the one that contains point or follows point.
7198 Interactively, if this command is repeated or (in Transient Mark
7199 mode) if the mark is active, it marks the next block after the
7200 ones already marked."
7201 (interactive)
7202 (if (or (and (eq last-command this-command) (mark t))
7203 (and transient-mark-mode mark-active))
7204 (set-mark
7205 (save-excursion
7206 (goto-char (mark))
7207 (markdown-forward-paragraph)
7208 (point)))
7209 (let ((beginning-of-defun-function 'markdown-backward-paragraph)
7210 (end-of-defun-function 'markdown-forward-paragraph))
7211 (mark-defun))))
7213 (defun markdown-mark-block ()
7214 "Put mark at end of this block, point at beginning.
7215 The block marked is the one that contains point or follows point.
7217 Interactively, if this command is repeated or (in Transient Mark
7218 mode) if the mark is active, it marks the next block after the
7219 ones already marked."
7220 (interactive)
7221 (if (or (and (eq last-command this-command) (mark t))
7222 (and transient-mark-mode mark-active))
7223 (set-mark
7224 (save-excursion
7225 (goto-char (mark))
7226 (markdown-forward-block)
7227 (point)))
7228 (let ((beginning-of-defun-function 'markdown-backward-block)
7229 (end-of-defun-function 'markdown-forward-block))
7230 (mark-defun))))
7232 (defun markdown-narrow-to-block ()
7233 "Make text outside current block invisible.
7234 The current block is the one that contains point or follows point."
7235 (interactive)
7236 (let ((beginning-of-defun-function 'markdown-backward-block)
7237 (end-of-defun-function 'markdown-forward-block))
7238 (narrow-to-defun)))
7240 (defun markdown-mark-text-block ()
7241 "Put mark at end of this plain text block, point at beginning.
7242 The block marked is the one that contains point or follows point.
7244 Interactively, if this command is repeated or (in Transient Mark
7245 mode) if the mark is active, it marks the next block after the
7246 ones already marked."
7247 (interactive)
7248 (if (or (and (eq last-command this-command) (mark t))
7249 (and transient-mark-mode mark-active))
7250 (set-mark
7251 (save-excursion
7252 (goto-char (mark))
7253 (markdown-end-of-text-block)
7254 (point)))
7255 (let ((beginning-of-defun-function 'markdown-beginning-of-text-block)
7256 (end-of-defun-function 'markdown-end-of-text-block))
7257 (mark-defun))))
7259 (defun markdown-mark-page ()
7260 "Put mark at end of this top level section, point at beginning.
7261 The top level section marked is the one that contains point or
7262 follows point.
7264 Interactively, if this command is repeated or (in Transient Mark
7265 mode) if the mark is active, it marks the next page after the
7266 ones already marked."
7267 (interactive)
7268 (if (or (and (eq last-command this-command) (mark t))
7269 (and transient-mark-mode mark-active))
7270 (set-mark
7271 (save-excursion
7272 (goto-char (mark))
7273 (markdown-forward-page)
7274 (point)))
7275 (let ((beginning-of-defun-function 'markdown-backward-page)
7276 (end-of-defun-function 'markdown-forward-page))
7277 (mark-defun))))
7279 (defun markdown-narrow-to-page ()
7280 "Make text outside current top level section invisible.
7281 The current section is the one that contains point or follows point."
7282 (interactive)
7283 (let ((beginning-of-defun-function 'markdown-backward-page)
7284 (end-of-defun-function 'markdown-forward-page))
7285 (narrow-to-defun)))
7287 (defun markdown-mark-subtree ()
7288 "Mark the current subtree.
7289 This puts point at the start of the current subtree, and mark at the end."
7290 (interactive)
7291 (let ((beg))
7292 (if (markdown-heading-at-point)
7293 (beginning-of-line)
7294 (markdown-previous-visible-heading 1))
7295 (setq beg (point))
7296 (markdown-end-of-subtree)
7297 (push-mark (point) nil t)
7298 (goto-char beg)))
7300 (defun markdown-narrow-to-subtree ()
7301 "Narrow buffer to the current subtree."
7302 (interactive)
7303 (save-excursion
7304 (save-match-data
7305 (narrow-to-region
7306 (progn (markdown-back-to-heading-over-code-block t) (point))
7307 (progn (markdown-end-of-subtree)
7308 (if (and (markdown-heading-at-point) (not (eobp)))
7309 (backward-char 1))
7310 (point))))))
7313 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
7315 (defun markdown-move-up ()
7316 "Move thing at point up.
7317 When in a list item, call `markdown-move-list-item-up'.
7318 Otherwise, move the current heading subtree up with
7319 `markdown-move-subtree-up'."
7320 (interactive)
7321 (cond
7322 ((markdown-list-item-at-point-p)
7323 (markdown-move-list-item-up))
7325 (markdown-move-subtree-up))))
7327 (defun markdown-move-down ()
7328 "Move thing at point down.
7329 When in a list item, call `markdown-move-list-item-down'.
7330 Otherwise, move the current heading subtree up with
7331 `markdown-move-subtree-down'."
7332 (interactive)
7333 (cond
7334 ((markdown-list-item-at-point-p)
7335 (markdown-move-list-item-down))
7337 (markdown-move-subtree-down))))
7339 (defun markdown-promote ()
7340 "Either promote header or list item at point or cycle markup.
7341 See `markdown-cycle-atx', `markdown-cycle-setext', and
7342 `markdown-promote-list-item'."
7343 (interactive)
7344 (let (bounds)
7345 (cond
7346 ;; Promote atx heading subtree
7347 ((thing-at-point-looking-at markdown-regex-header-atx)
7348 (markdown-promote-subtree))
7349 ;; Promote setext heading
7350 ((thing-at-point-looking-at markdown-regex-header-setext)
7351 (markdown-cycle-setext -1))
7352 ;; Promote horizonal rule
7353 ((thing-at-point-looking-at markdown-regex-hr)
7354 (markdown-cycle-hr -1))
7355 ;; Promote list item
7356 ((setq bounds (markdown-cur-list-item-bounds))
7357 (markdown-promote-list-item bounds))
7358 ;; Promote bold
7359 ((thing-at-point-looking-at markdown-regex-bold)
7360 (markdown-cycle-bold))
7361 ;; Promote italic
7362 ((thing-at-point-looking-at markdown-regex-italic)
7363 (markdown-cycle-italic))
7365 (user-error "Nothing to promote at point")))))
7367 (defun markdown-demote ()
7368 "Either demote header or list item at point or cycle or remove markup.
7369 See `markdown-cycle-atx', `markdown-cycle-setext', and
7370 `markdown-demote-list-item'."
7371 (interactive)
7372 (let (bounds)
7373 (cond
7374 ;; Demote atx heading subtree
7375 ((thing-at-point-looking-at markdown-regex-header-atx)
7376 (markdown-demote-subtree))
7377 ;; Demote setext heading
7378 ((thing-at-point-looking-at markdown-regex-header-setext)
7379 (markdown-cycle-setext 1))
7380 ;; Demote horizonal rule
7381 ((thing-at-point-looking-at markdown-regex-hr)
7382 (markdown-cycle-hr 1))
7383 ;; Demote list item
7384 ((setq bounds (markdown-cur-list-item-bounds))
7385 (markdown-demote-list-item bounds))
7386 ;; Demote bold
7387 ((thing-at-point-looking-at markdown-regex-bold)
7388 (markdown-cycle-bold))
7389 ;; Demote italic
7390 ((thing-at-point-looking-at markdown-regex-italic)
7391 (markdown-cycle-italic))
7393 (user-error "Nothing to demote at point")))))
7396 ;;; Commands ==================================================================
7398 (defun markdown (&optional output-buffer-name)
7399 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
7400 The output buffer name defaults to `markdown-output-buffer-name'.
7401 Return the name of the output buffer used."
7402 (interactive)
7403 (save-window-excursion
7404 (let ((begin-region)
7405 (end-region))
7406 (if (markdown-use-region-p)
7407 (setq begin-region (region-beginning)
7408 end-region (region-end))
7409 (setq begin-region (point-min)
7410 end-region (point-max)))
7412 (unless output-buffer-name
7413 (setq output-buffer-name markdown-output-buffer-name))
7414 (cond
7415 ;; Handle case when `markdown-command' does not read from stdin
7416 (markdown-command-needs-filename
7417 (if (not buffer-file-name)
7418 (user-error "Must be visiting a file")
7419 (shell-command (concat markdown-command " "
7420 (shell-quote-argument buffer-file-name))
7421 output-buffer-name)))
7422 ;; Pass region to `markdown-command' via stdin
7424 (let ((buf (get-buffer-create output-buffer-name)))
7425 (with-current-buffer buf
7426 (setq buffer-read-only nil)
7427 (erase-buffer))
7428 (call-process-region begin-region end-region
7429 shell-file-name nil buf nil
7430 shell-command-switch markdown-command)))))
7431 output-buffer-name))
7433 (defun markdown-standalone (&optional output-buffer-name)
7434 "Special function to provide standalone HTML output.
7435 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
7436 (interactive)
7437 (setq output-buffer-name (markdown output-buffer-name))
7438 (with-current-buffer output-buffer-name
7439 (set-buffer output-buffer-name)
7440 (unless (markdown-output-standalone-p)
7441 (markdown-add-xhtml-header-and-footer output-buffer-name))
7442 (goto-char (point-min))
7443 (html-mode))
7444 output-buffer-name)
7446 (defun markdown-other-window (&optional output-buffer-name)
7447 "Run `markdown-command' on current buffer and display in other window.
7448 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7449 that name."
7450 (interactive)
7451 (markdown-display-buffer-other-window
7452 (markdown-standalone output-buffer-name)))
7454 (defun markdown-output-standalone-p ()
7455 "Determine whether `markdown-command' output is standalone XHTML.
7456 Standalone XHTML output is identified by an occurrence of
7457 `markdown-xhtml-standalone-regexp' in the first five lines of output."
7458 (save-excursion
7459 (goto-char (point-min))
7460 (save-match-data
7461 (re-search-forward
7462 markdown-xhtml-standalone-regexp
7463 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
7464 t))))
7466 (defun markdown-stylesheet-link-string (stylesheet-path)
7467 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
7468 stylesheet-path
7469 "\" />"))
7471 (defun markdown-add-xhtml-header-and-footer (title)
7472 "Wrap XHTML header and footer with given TITLE around current buffer."
7473 (goto-char (point-min))
7474 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
7475 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
7476 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
7477 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
7478 "<head>\n<title>")
7479 (insert title)
7480 (insert "</title>\n")
7481 (when (> (length markdown-content-type) 0)
7482 (insert
7483 (format
7484 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
7485 markdown-content-type
7486 (or (and markdown-coding-system
7487 (fboundp 'coding-system-get)
7488 (coding-system-get markdown-coding-system
7489 'mime-charset))
7490 (and (fboundp 'coding-system-get)
7491 (coding-system-get buffer-file-coding-system
7492 'mime-charset))
7493 "iso-8859-1"))))
7494 (if (> (length markdown-css-paths) 0)
7495 (insert (mapconcat #'markdown-stylesheet-link-string
7496 markdown-css-paths "\n")))
7497 (when (> (length markdown-xhtml-header-content) 0)
7498 (insert markdown-xhtml-header-content))
7499 (insert "\n</head>\n\n"
7500 "<body>\n\n")
7501 (goto-char (point-max))
7502 (insert "\n"
7503 "</body>\n"
7504 "</html>\n"))
7506 (defun markdown-preview (&optional output-buffer-name)
7507 "Run `markdown-command' on the current buffer and view output in browser.
7508 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7509 that name."
7510 (interactive)
7511 (browse-url-of-buffer
7512 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
7514 (defun markdown-export-file-name (&optional extension)
7515 "Attempt to generate a filename for Markdown output.
7516 The file extension will be EXTENSION if given, or .html by default.
7517 If the current buffer is visiting a file, we construct a new
7518 output filename based on that filename. Otherwise, return nil."
7519 (when (buffer-file-name)
7520 (unless extension
7521 (setq extension ".html"))
7522 (let ((candidate
7523 (concat
7524 (cond
7525 ((buffer-file-name)
7526 (file-name-sans-extension (buffer-file-name)))
7527 (t (buffer-name)))
7528 extension)))
7529 (cond
7530 ((equal candidate (buffer-file-name))
7531 (concat candidate extension))
7533 candidate)))))
7535 (defun markdown-export (&optional output-file)
7536 "Run Markdown on the current buffer, save to file, and return the filename.
7537 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
7538 generated by `markdown-export-file-name', which will be constructed using the
7539 current filename, but with the extension removed and replaced with .html."
7540 (interactive)
7541 (unless output-file
7542 (setq output-file (markdown-export-file-name ".html")))
7543 (when output-file
7544 (let* ((init-buf (current-buffer))
7545 (init-point (point))
7546 (init-buf-string (buffer-string))
7547 (output-buffer (find-file-noselect output-file))
7548 (output-buffer-name (buffer-name output-buffer)))
7549 (run-hooks 'markdown-before-export-hook)
7550 (markdown-standalone output-buffer-name)
7551 (with-current-buffer output-buffer
7552 (run-hooks 'markdown-after-export-hook)
7553 (save-buffer))
7554 ;; if modified, restore initial buffer
7555 (when (buffer-modified-p init-buf)
7556 (erase-buffer)
7557 (insert init-buf-string)
7558 (save-buffer)
7559 (goto-char init-point))
7560 output-file)))
7562 (defun markdown-export-and-preview ()
7563 "Export to XHTML using `markdown-export' and browse the resulting file."
7564 (interactive)
7565 (browse-url-of-file (markdown-export)))
7567 (defvar markdown-live-preview-buffer nil
7568 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
7569 (make-variable-buffer-local 'markdown-live-preview-buffer)
7571 (defvar markdown-live-preview-source-buffer nil
7572 "Source buffer from which current buffer was generated.
7573 This is the inverse of `markdown-live-preview-buffer'.")
7574 (make-variable-buffer-local 'markdown-live-preview-source-buffer)
7576 (defvar markdown-live-preview-currently-exporting nil)
7578 (defun markdown-live-preview-get-filename ()
7579 "Standardize the filename exported by `markdown-live-preview-export'."
7580 (markdown-export-file-name ".html"))
7582 (defun markdown-live-preview-window-eww (file)
7583 "Preview FILE with eww.
7584 To be used with `markdown-live-preview-window-function'."
7585 (if (require 'eww nil t)
7586 (progn
7587 (eww-open-file file)
7588 (get-buffer "*eww*"))
7589 (error "EWW is not present or not loaded on this version of Emacs")))
7591 (defun markdown-visual-lines-between-points (beg end)
7592 (save-excursion
7593 (goto-char beg)
7594 (cl-loop with count = 0
7595 while (progn (end-of-visual-line)
7596 (and (< (point) end) (line-move-visual 1 t)))
7597 do (cl-incf count)
7598 finally return count)))
7600 (defun markdown-live-preview-window-serialize (buf)
7601 "Get window point and scroll data for all windows displaying BUF."
7602 (when (buffer-live-p buf)
7603 (with-current-buffer buf
7604 (mapcar
7605 (lambda (win)
7606 (with-selected-window win
7607 (let* ((start (window-start))
7608 (pt (window-point))
7609 (pt-or-sym (cond ((= pt (point-min)) 'min)
7610 ((= pt (point-max)) 'max)
7611 (t pt)))
7612 (diff (markdown-visual-lines-between-points
7613 start pt)))
7614 (list win pt-or-sym diff))))
7615 (get-buffer-window-list buf)))))
7617 (defun markdown-get-point-back-lines (pt num-lines)
7618 (save-excursion
7619 (goto-char pt)
7620 (line-move-visual (- num-lines) t)
7621 ;; in testing, can occasionally overshoot the number of lines to traverse
7622 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
7623 (when (> actual-num-lines num-lines)
7624 (line-move-visual (- actual-num-lines num-lines) t)))
7625 (point)))
7627 (defun markdown-live-preview-window-deserialize (window-posns)
7628 "Apply window point and scroll data from WINDOW-POSNS.
7629 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
7630 (cl-destructuring-bind (win pt-or-sym diff) window-posns
7631 (when (window-live-p win)
7632 (with-current-buffer markdown-live-preview-buffer
7633 (set-window-buffer win (current-buffer))
7634 (cl-destructuring-bind (actual-pt actual-diff)
7635 (cl-case pt-or-sym
7636 (min (list (point-min) 0))
7637 (max (list (point-max) diff))
7638 (t (list pt-or-sym diff)))
7639 (set-window-start
7640 win (markdown-get-point-back-lines actual-pt actual-diff))
7641 (set-window-point win actual-pt))))))
7643 (defun markdown-live-preview-export ()
7644 "Export to XHTML using `markdown-export'.
7645 Browse the resulting file within Emacs using
7646 `markdown-live-preview-window-function' Return the buffer
7647 displaying the rendered output."
7648 (interactive)
7649 (let ((filename (markdown-live-preview-get-filename)))
7650 (when filename
7651 (let* ((markdown-live-preview-currently-exporting t)
7652 (cur-buf (current-buffer))
7653 (export-file (markdown-export filename))
7654 ;; get positions in all windows currently displaying output buffer
7655 (window-data
7656 (markdown-live-preview-window-serialize
7657 markdown-live-preview-buffer)))
7658 (save-window-excursion
7659 (let ((output-buffer
7660 (funcall markdown-live-preview-window-function export-file)))
7661 (with-current-buffer output-buffer
7662 (setq markdown-live-preview-source-buffer cur-buf)
7663 (add-hook 'kill-buffer-hook
7664 #'markdown-live-preview-remove-on-kill t t))
7665 (with-current-buffer cur-buf
7666 (setq markdown-live-preview-buffer output-buffer))))
7667 (with-current-buffer cur-buf
7668 ;; reset all windows displaying output buffer to where they were,
7669 ;; now with the new output
7670 (mapc #'markdown-live-preview-window-deserialize window-data)
7671 ;; delete html editing buffer
7672 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
7673 (when (and export-file (file-exists-p export-file)
7674 (eq markdown-live-preview-delete-export
7675 'delete-on-export))
7676 (delete-file export-file))
7677 markdown-live-preview-buffer)))))
7679 (defun markdown-live-preview-remove ()
7680 (when (buffer-live-p markdown-live-preview-buffer)
7681 (kill-buffer markdown-live-preview-buffer))
7682 (setq markdown-live-preview-buffer nil)
7683 ;; if set to 'delete-on-export, the output has already been deleted
7684 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
7685 (let ((outfile-name (markdown-live-preview-get-filename)))
7686 (when (and outfile-name (file-exists-p outfile-name))
7687 (delete-file outfile-name)))))
7689 (defun markdown-get-other-window ()
7690 "Find another window to display preview or output content."
7691 (cond
7692 ((memq markdown-split-window-direction '(vertical below))
7693 (or (window-in-direction 'below) (split-window-vertically)))
7694 ((memq markdown-split-window-direction '(horizontal right))
7695 (or (window-in-direction 'right) (split-window-horizontally)))
7696 (t (split-window-sensibly (get-buffer-window)))))
7698 (defun markdown-display-buffer-other-window (buf)
7699 "Display preview or output buffer BUF in another window."
7700 (let ((cur-buf (current-buffer))
7701 (window (markdown-get-other-window)))
7702 (set-window-buffer window buf)
7703 (set-buffer cur-buf)))
7705 (defun markdown-live-preview-if-markdown ()
7706 (when (and (derived-mode-p 'markdown-mode)
7707 markdown-live-preview-mode)
7708 (unless markdown-live-preview-currently-exporting
7709 (if (buffer-live-p markdown-live-preview-buffer)
7710 (markdown-live-preview-export)
7711 (markdown-display-buffer-other-window
7712 (markdown-live-preview-export))))))
7714 (defun markdown-live-preview-remove-on-kill ()
7715 (cond ((and (derived-mode-p 'markdown-mode)
7716 markdown-live-preview-mode)
7717 (markdown-live-preview-remove))
7718 (markdown-live-preview-source-buffer
7719 (with-current-buffer markdown-live-preview-source-buffer
7720 (setq markdown-live-preview-buffer nil))
7721 (setq markdown-live-preview-source-buffer nil))))
7723 (defun markdown-live-preview-switch-to-output ()
7724 "Switch to output buffer."
7725 (interactive)
7726 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
7727 output buffer in another window."
7728 (if markdown-live-preview-mode
7729 (markdown-display-buffer-other-window (markdown-live-preview-export)))
7730 (markdown-live-preview-mode))
7732 (defun markdown-live-preview-re-export ()
7733 "Re export source buffer."
7734 (interactive)
7735 "If the current buffer is a buffer displaying the exported version of a
7736 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
7737 update this buffer's contents."
7738 (when markdown-live-preview-source-buffer
7739 (with-current-buffer markdown-live-preview-source-buffer
7740 (markdown-live-preview-export))))
7742 (defun markdown-open ()
7743 "Open file for the current buffer with `markdown-open-command'."
7744 (interactive)
7745 (if (not markdown-open-command)
7746 (user-error "Variable `markdown-open-command' must be set")
7747 (if (not buffer-file-name)
7748 (user-error "Must be visiting a file")
7749 (call-process markdown-open-command
7750 nil nil nil buffer-file-name))))
7752 (defun markdown-kill-ring-save ()
7753 "Run Markdown on file and store output in the kill ring."
7754 (interactive)
7755 (save-window-excursion
7756 (markdown)
7757 (with-current-buffer markdown-output-buffer-name
7758 (kill-ring-save (point-min) (point-max)))))
7761 ;;; Links =====================================================================
7763 (defun markdown-link-p ()
7764 "Return non-nil when `point' is at a non-wiki link.
7765 See `markdown-wiki-link-p' for more information."
7766 (let ((case-fold-search nil))
7767 (and (not (markdown-wiki-link-p))
7768 (not (markdown-code-block-at-point-p))
7769 (or (thing-at-point-looking-at markdown-regex-link-inline)
7770 (thing-at-point-looking-at markdown-regex-link-reference)
7771 (thing-at-point-looking-at markdown-regex-uri)
7772 (thing-at-point-looking-at markdown-regex-angle-uri)))))
7774 (make-obsolete 'markdown-link-link 'markdown-link-url "v2.3")
7776 (defun markdown-link-at-pos (pos)
7777 "Return properties of link or image at position POS.
7778 Value is a list of elements describing the link:
7779 0. beginning position
7780 1. end position
7781 2. link text
7782 3. URL
7783 4. reference label
7784 5. title text
7785 6. bang (nil or \"!\")"
7786 (save-excursion
7787 (goto-char pos)
7788 (let (begin end text url reference title bang)
7789 (cond
7790 ;; Inline or reference image or link at point.
7791 ((or (thing-at-point-looking-at markdown-regex-link-inline)
7792 (thing-at-point-looking-at markdown-regex-link-reference))
7793 (setq bang (match-string-no-properties 1)
7794 begin (match-beginning 0)
7795 end (match-end 0)
7796 text (match-string-no-properties 3))
7797 (if (char-equal (char-after (match-beginning 5)) ?\[)
7798 ;; Reference link
7799 (setq reference (match-string-no-properties 6))
7800 ;; Inline link
7801 (setq url (match-string-no-properties 6))
7802 (when (match-end 7)
7803 (setq title (substring (match-string-no-properties 7) 1 -1)))))
7804 ;; Angle bracket URI at point.
7805 ((thing-at-point-looking-at markdown-regex-angle-uri)
7806 (setq begin (match-beginning 0)
7807 end (match-end 0)
7808 url (match-string-no-properties 2)))
7809 ;; Plain URI at point.
7810 ((thing-at-point-looking-at markdown-regex-uri)
7811 (setq begin (match-beginning 0)
7812 end (match-end 0)
7813 url (match-string-no-properties 1))))
7814 (list begin end text url reference title bang))))
7816 (defun markdown-link-url ()
7817 "Return the URL part of the regular (non-wiki) link at point.
7818 Works with both inline and reference style links, and with images.
7819 If point is not at a link or the link reference is not defined
7820 returns nil."
7821 (let* ((values (markdown-link-at-pos (point)))
7822 (text (nth 2 values))
7823 (url (nth 3 values))
7824 (ref (nth 4 values)))
7825 (or url (and ref (car (markdown-reference-definition
7826 (downcase (if (string= ref "") text ref))))))))
7828 (defun markdown-follow-link-at-point ()
7829 "Open the current non-wiki link.
7830 If the link is a complete URL, open in browser with `browse-url'.
7831 Otherwise, open with `find-file' after stripping anchor and/or query string."
7832 (interactive)
7833 (if (markdown-link-p)
7834 (let* ((url (markdown-link-url))
7835 (struct (url-generic-parse-url url))
7836 (full (url-fullness struct))
7837 (file url))
7838 ;; Parse URL, determine fullness, strip query string
7839 (if (fboundp 'url-path-and-query)
7840 (setq file (car (url-path-and-query struct)))
7841 (when (and (setq file (url-filename struct))
7842 (string-match "\\?" file))
7843 (setq file (substring file 0 (match-beginning 0)))))
7844 ;; Open full URLs in browser, files in Emacs
7845 (if full
7846 (browse-url url)
7847 (when (and file (> (length file) 0)) (find-file file))))
7848 (user-error "Point is not at a Markdown link or URL")))
7850 (defun markdown-fontify-inline-links (last)
7851 "Add text properties to next inline link from point to LAST."
7852 (when (markdown-match-generic-links last nil)
7853 (let* ((link-start (match-beginning 3))
7854 (link-end (match-end 3))
7855 (url-start (match-beginning 6))
7856 (url-end (match-end 6))
7857 (url (match-string-no-properties 6))
7858 (title-start (match-beginning 7))
7859 (title-end (match-end 7))
7860 (title (match-string-no-properties 7))
7861 ;; Markup part
7862 (mp (list 'face 'markdown-markup-face
7863 'invisible 'markdown-markup
7864 'font-lock-multiline t))
7865 ;; Link part
7866 (lp (list 'keymap markdown-mode-mouse-map
7867 'face markdown-link-face
7868 'mouse-face 'markdown-highlight-face
7869 'font-lock-multiline t
7870 'help-echo (if title (concat title "\n" url) url)))
7871 ;; URL part
7872 (up (list 'keymap markdown-mode-mouse-map
7873 'face 'markdown-url-face
7874 'invisible 'markdown-markup
7875 'mouse-face 'markdown-highlight-face
7876 'font-lock-multiline t))
7877 ;; Title part
7878 (tp (list 'face 'markdown-link-title-face
7879 'invisible 'markdown-markup
7880 'font-lock-multiline t)))
7881 (dolist (g '(1 2 4 5 8))
7882 (when (match-end g)
7883 (add-text-properties (match-beginning g) (match-end g) mp)))
7884 (when link-start (add-text-properties link-start link-end lp))
7885 (when url-start (add-text-properties url-start url-end up))
7886 (when title-start (add-text-properties url-end title-end tp))
7887 (when (and markdown-hide-urls url-start)
7888 (compose-region url-start (or title-end url-end)
7889 markdown-url-compose-char))
7890 t)))
7892 (defun markdown-fontify-reference-links (last)
7893 "Add text properties to next reference link from point to LAST."
7894 (when (markdown-match-generic-links last t)
7895 (let* ((link-start (match-beginning 3))
7896 (link-end (match-end 3))
7897 (ref-start (match-beginning 6))
7898 (ref-end (match-end 6))
7899 ;; Markup part
7900 (mp (list 'face 'markdown-markup-face
7901 'invisible 'markdown-markup
7902 'font-lock-multiline t))
7903 ;; Link part
7904 (lp (list 'keymap markdown-mode-mouse-map
7905 'face markdown-link-face
7906 'mouse-face 'markdown-highlight-face
7907 'font-lock-multiline t
7908 'help-echo (lambda (_ __ pos)
7909 (save-match-data
7910 (save-excursion
7911 (goto-char pos)
7912 (or (markdown-link-url)
7913 "Undefined reference"))))))
7914 ;; Reference part
7915 (rp (list 'face 'markdown-reference-face
7916 'invisible 'markdown-markup
7917 'font-lock-multiline t)))
7918 (dolist (g '(1 2 4 5 8))
7919 (when (match-end g)
7920 (add-text-properties (match-beginning g) (match-end g) mp)))
7921 (when link-start (add-text-properties link-start link-end lp))
7922 (when ref-start (add-text-properties ref-start ref-end rp)
7923 (when (and markdown-hide-urls (> (- ref-end ref-start) 2))
7924 (compose-region ref-start ref-end markdown-url-compose-char)))
7925 t)))
7927 (defun markdown-fontify-angle-uris (last)
7928 "Add text properties to angle URIs from point to LAST."
7929 (when (markdown-match-angle-uris last)
7930 (let* ((url-start (match-beginning 2))
7931 (url-end (match-end 2))
7932 ;; Markup part
7933 (mp (list 'face 'markdown-markup-face
7934 'invisible 'markdown-markup
7935 'font-lock-multiline t))
7936 ;; URI part
7937 (up (list 'keymap markdown-mode-mouse-map
7938 'face 'markdown-plain-url-face
7939 'mouse-face 'markdown-highlight-face
7940 'font-lock-multiline t)))
7941 (dolist (g '(1 3))
7942 (add-text-properties (match-beginning g) (match-end g) mp))
7943 (add-text-properties url-start url-end up)
7944 t)))
7946 (defun markdown-fontify-plain-uris (last)
7947 "Add text properties to plain URLs from point to LAST."
7948 (when (markdown-match-plain-uris last)
7949 (let* ((start (match-beginning 0))
7950 (end (match-end 0))
7951 (props (list 'keymap markdown-mode-mouse-map
7952 'face 'markdown-plain-url-face
7953 'mouse-face 'markdown-highlight-face
7954 'font-lock-multiline t)))
7955 (add-text-properties start end props)
7956 t)))
7958 (defun markdown-toggle-url-hiding (&optional arg)
7959 "Toggle the display or hiding of URLs.
7960 With a prefix argument ARG, enable URL hiding if ARG is positive,
7961 and disable it otherwise."
7962 (interactive (list (or current-prefix-arg 'toggle)))
7963 (setq markdown-hide-urls
7964 (if (eq arg 'toggle)
7965 (not markdown-hide-urls)
7966 (> (prefix-numeric-value arg) 0)))
7967 (if markdown-hide-urls
7968 (message "markdown-mode URL hiding enabled")
7969 (message "markdown-mode URL hiding disabled"))
7970 (markdown-reload-extensions))
7973 ;;; WikiLink Following/Markup =================================================
7975 (defun markdown-wiki-link-p ()
7976 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
7977 A true wiki link name matches `markdown-regex-wiki-link' but does
7978 not match the current file name after conversion. This modifies
7979 the data returned by `match-data'. Note that the potential wiki
7980 link name must be available via `match-string'."
7981 (when markdown-enable-wiki-links
7982 (let ((case-fold-search nil))
7983 (and (thing-at-point-looking-at markdown-regex-wiki-link)
7984 (not (markdown-code-block-at-point-p))
7985 (or (not buffer-file-name)
7986 (not (string-equal (buffer-file-name)
7987 (markdown-convert-wiki-link-to-filename
7988 (markdown-wiki-link-link)))))))))
7990 (defun markdown-wiki-link-link ()
7991 "Return the link part of the wiki link using current match data.
7992 The location of the link component depends on the value of
7993 `markdown-wiki-link-alias-first'."
7994 (if markdown-wiki-link-alias-first
7995 (or (match-string-no-properties 5) (match-string-no-properties 3))
7996 (match-string-no-properties 3)))
7998 (defun markdown-wiki-link-alias ()
7999 "Return the alias or text part of the wiki link using current match data.
8000 The location of the alias component depends on the value of
8001 `markdown-wiki-link-alias-first'."
8002 (if markdown-wiki-link-alias-first
8003 (match-string-no-properties 3)
8004 (or (match-string-no-properties 5) (match-string-no-properties 3))))
8006 (defun markdown-convert-wiki-link-to-filename (name)
8007 "Generate a filename from the wiki link NAME.
8008 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
8009 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
8010 and [[test test]] both map to Test-test.ext. Look in the current
8011 directory first, then in subdirectories if
8012 `markdown-wiki-link-search-subdirectories' is non-nil, and then
8013 in parent directories if
8014 `markdown-wiki-link-search-parent-directories' is non-nil."
8015 (let* ((basename (markdown-replace-regexp-in-string
8016 "[[:space:]\n]" markdown-link-space-sub-char name))
8017 (basename (if (eq major-mode 'gfm-mode)
8018 (concat (upcase (substring basename 0 1))
8019 (downcase (substring basename 1 nil)))
8020 basename))
8021 directory extension default candidates dir)
8022 (when buffer-file-name
8023 (setq directory (file-name-directory buffer-file-name)
8024 extension (file-name-extension buffer-file-name)))
8025 (setq default (concat basename
8026 (when extension (concat "." extension))))
8027 (cond
8028 ;; Look in current directory first.
8029 ((or (null buffer-file-name)
8030 (file-exists-p default))
8031 default)
8032 ;; Possibly search in subdirectories, next.
8033 ((and markdown-wiki-link-search-subdirectories
8034 (setq candidates
8035 (markdown-directory-files-recursively
8036 directory (concat "^" default "$"))))
8037 (car candidates))
8038 ;; Possibly search in parent directories as a last resort.
8039 ((and markdown-wiki-link-search-parent-directories
8040 (setq dir (locate-dominating-file directory default)))
8041 (concat dir default))
8042 ;; If nothing is found, return default in current directory.
8043 (t default))))
8045 (defun markdown-follow-wiki-link (name &optional other)
8046 "Follow the wiki link NAME.
8047 Convert the name to a file name and call `find-file'. Ensure that
8048 the new buffer remains in `markdown-mode'. Open the link in another
8049 window when OTHER is non-nil."
8050 (let ((filename (markdown-convert-wiki-link-to-filename name))
8051 (wp (when buffer-file-name
8052 (file-name-directory buffer-file-name))))
8053 (if (not wp)
8054 (user-error "Must be visiting a file")
8055 (when other (other-window 1))
8056 (let ((default-directory wp))
8057 (find-file filename)))
8058 (when (not (eq major-mode 'markdown-mode))
8059 (markdown-mode))))
8061 (defun markdown-follow-wiki-link-at-point (&optional arg)
8062 "Find Wiki Link at point.
8063 With prefix argument ARG, open the file in other window.
8064 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
8065 (interactive "P")
8066 (if (markdown-wiki-link-p)
8067 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
8068 (user-error "Point is not at a Wiki Link")))
8070 (defun markdown-highlight-wiki-link (from to face)
8071 "Highlight the wiki link in the region between FROM and TO using FACE."
8072 (put-text-property from to 'font-lock-face face))
8074 (defun markdown-unfontify-region-wiki-links (from to)
8075 "Remove wiki link faces from the region specified by FROM and TO."
8076 (interactive "*r")
8077 (let ((modified (buffer-modified-p)))
8078 (remove-text-properties from to '(font-lock-face markdown-link-face))
8079 (remove-text-properties from to '(font-lock-face markdown-missing-link-face))
8080 ;; remove-text-properties marks the buffer modified in emacs 24.3,
8081 ;; undo that if it wasn't originally marked modified
8082 (set-buffer-modified-p modified)))
8084 (defun markdown-fontify-region-wiki-links (from to)
8085 "Search region given by FROM and TO for wiki links and fontify them.
8086 If a wiki link is found check to see if the backing file exists
8087 and highlight accordingly."
8088 (goto-char from)
8089 (save-match-data
8090 (while (re-search-forward markdown-regex-wiki-link to t)
8091 (when (not (markdown-code-block-at-point-p))
8092 (let ((highlight-beginning (match-beginning 1))
8093 (highlight-end (match-end 1))
8094 (file-name
8095 (markdown-convert-wiki-link-to-filename
8096 (markdown-wiki-link-link))))
8097 (if (condition-case nil (file-exists-p file-name) (error nil))
8098 (markdown-highlight-wiki-link
8099 highlight-beginning highlight-end markdown-link-face)
8100 (markdown-highlight-wiki-link
8101 highlight-beginning highlight-end markdown-missing-link-face)))))))
8103 (defun markdown-extend-changed-region (from to)
8104 "Extend region given by FROM and TO so that we can fontify all links.
8105 The region is extended to the first newline before and the first
8106 newline after."
8107 ;; start looking for the first new line before 'from
8108 (goto-char from)
8109 (re-search-backward "\n" nil t)
8110 (let ((new-from (point-min))
8111 (new-to (point-max)))
8112 (if (not (= (point) from))
8113 (setq new-from (point)))
8114 ;; do the same thing for the first new line after 'to
8115 (goto-char to)
8116 (re-search-forward "\n" nil t)
8117 (if (not (= (point) to))
8118 (setq new-to (point)))
8119 (cl-values new-from new-to)))
8121 (defun markdown-check-change-for-wiki-link (from to)
8122 "Check region between FROM and TO for wiki links and re-fontify as needed."
8123 (interactive "*r")
8124 (let* ((modified (buffer-modified-p))
8125 (buffer-undo-list t)
8126 (inhibit-read-only t)
8127 (inhibit-point-motion-hooks t)
8128 deactivate-mark
8129 buffer-file-truename)
8130 (unwind-protect
8131 (save-excursion
8132 (save-match-data
8133 (save-restriction
8134 ;; Extend the region to fontify so that it starts
8135 ;; and ends at safe places.
8136 (cl-multiple-value-bind (new-from new-to)
8137 (markdown-extend-changed-region from to)
8138 (goto-char new-from)
8139 ;; Only refontify when the range contains text with a
8140 ;; wiki link face or if the wiki link regexp matches.
8141 (when (or (markdown-range-property-any
8142 new-from new-to 'font-lock-face
8143 (list markdown-link-face
8144 markdown-missing-link-face))
8145 (re-search-forward
8146 markdown-regex-wiki-link new-to t))
8147 ;; Unfontify existing fontification (start from scratch)
8148 (markdown-unfontify-region-wiki-links new-from new-to)
8149 ;; Now do the fontification.
8150 (markdown-fontify-region-wiki-links new-from new-to))))))
8151 (and (not modified)
8152 (buffer-modified-p)
8153 (set-buffer-modified-p nil)))))
8155 (defun markdown-check-change-for-wiki-link-after-change (from to _)
8156 "Check region between FROM and TO for wiki links and re-fontify as needed.
8157 Designed to be used with the `after-change-functions' hook."
8158 (markdown-check-change-for-wiki-link from to))
8160 (defun markdown-fontify-buffer-wiki-links ()
8161 "Refontify all wiki links in the buffer."
8162 (interactive)
8163 (markdown-check-change-for-wiki-link (point-min) (point-max)))
8166 ;;; Following & Doing =========================================================
8168 (defun markdown-follow-thing-at-point (arg)
8169 "Follow thing at point if possible, such as a reference link or wiki link.
8170 Opens inline and reference links in a browser. Opens wiki links
8171 to other files in the current window, or the another window if
8172 ARG is non-nil.
8173 See `markdown-follow-link-at-point' and
8174 `markdown-follow-wiki-link-at-point'."
8175 (interactive "P")
8176 (cond ((markdown-link-p)
8177 (markdown-follow-link-at-point))
8178 ((markdown-wiki-link-p)
8179 (markdown-follow-wiki-link-at-point arg))
8181 (user-error "Nothing to follow at point"))))
8183 (make-obsolete 'markdown-jump 'markdown-do "v2.3")
8185 (defun markdown-do ()
8186 "Do something sensible based on context at point.
8187 Jumps between reference links and definitions; between footnote
8188 markers and footnote text."
8189 (interactive)
8190 (cond
8191 ;; Footnote definition
8192 ((markdown-footnote-text-positions)
8193 (markdown-footnote-return))
8194 ;; Footnote marker
8195 ((markdown-footnote-marker-positions)
8196 (markdown-footnote-goto-text))
8197 ;; Reference link
8198 ((thing-at-point-looking-at markdown-regex-link-reference)
8199 (markdown-reference-goto-definition))
8200 ;; Reference definition
8201 ((thing-at-point-looking-at markdown-regex-reference-definition)
8202 (markdown-reference-goto-link (match-string-no-properties 2)))
8203 ;; GFM task list item
8204 ((markdown-gfm-task-list-item-at-point)
8205 (markdown-toggle-gfm-checkbox))
8206 ;; Otherwise
8208 (user-error "Nothing to do in context at point"))))
8211 ;;; Miscellaneous =============================================================
8213 (defun markdown-compress-whitespace-string (str)
8214 "Compress whitespace in STR and return result.
8215 Leading and trailing whitespace is removed. Sequences of multiple
8216 spaces, tabs, and newlines are replaced with single spaces."
8217 (markdown-replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
8218 (markdown-replace-regexp-in-string "[ \t\n]+" " " str)))
8220 (defun markdown--substitute-command-keys (string)
8221 "Like `substitute-command-keys' but, but prefers control characters.
8222 First pass STRING to `substitute-command-keys' and then
8223 substitute `C-i` for `TAB` and `C-m` for `RET`."
8224 (replace-regexp-in-string
8225 "\\<TAB\\>" "C-i"
8226 (replace-regexp-in-string
8227 "\\<RET\\>" "C-m" (substitute-command-keys string) t) t))
8229 (defun markdown-line-number-at-pos (&optional pos)
8230 "Return (narrowed) buffer line number at position POS.
8231 If POS is nil, use current buffer location.
8232 This is an exact copy of `line-number-at-pos' for use in emacs21."
8233 (let ((opoint (or pos (point))) start)
8234 (save-excursion
8235 (goto-char (point-min))
8236 (setq start (point))
8237 (goto-char opoint)
8238 (forward-line 0)
8239 (1+ (count-lines start (point))))))
8241 (defun markdown-inside-link-p ()
8242 "Return t if point is within a link."
8243 (save-match-data
8244 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
8246 (defun markdown-line-is-reference-definition-p ()
8247 "Return whether the current line is a (non-footnote) reference defition."
8248 (save-excursion
8249 (move-beginning-of-line 1)
8250 (and (looking-at-p markdown-regex-reference-definition)
8251 (not (looking-at-p "[ \t]*\\[^")))))
8253 (defun markdown-adaptive-fill-function ()
8254 "Return prefix for filling paragraph or nil if not determined."
8255 (cond
8256 ;; List item inside blockquote
8257 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
8258 (markdown-replace-regexp-in-string
8259 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
8260 ;; Blockquote
8261 ((looking-at markdown-regex-blockquote)
8262 (buffer-substring-no-properties (match-beginning 0) (match-end 2)))
8263 ;; List items
8264 ((looking-at markdown-regex-list)
8265 (match-string-no-properties 0))
8266 ;; Footnote definition
8267 ((looking-at-p markdown-regex-footnote-definition)
8268 " ") ; four spaces
8269 ;; No match
8270 (t nil)))
8272 (defun markdown-fill-paragraph (&optional justify)
8273 "Fill paragraph at or after point.
8274 This function is like \\[fill-paragraph], but it skips Markdown
8275 code blocks. If the point is in a code block, or just before one,
8276 do not fill. Otherwise, call `fill-paragraph' as usual. If
8277 JUSTIFY is non-nil, justify text as well. Since this function
8278 handles filling itself, it always returns t so that
8279 `fill-paragraph' doesn't run."
8280 (interactive "P")
8281 (unless (or (markdown-code-block-at-point-p)
8282 (save-excursion
8283 (back-to-indentation)
8284 (skip-syntax-forward "-")
8285 (markdown-code-block-at-point-p)))
8286 (fill-paragraph justify))
8289 (make-obsolete 'markdown-fill-forward-paragraph-function
8290 'markdown-fill-forward-paragraph "v2.3")
8292 (defun markdown-fill-forward-paragraph (&optional arg)
8293 "Function used by `fill-paragraph' to move over ARG paragraphs.
8294 This is a `fill-forward-paragraph-function' for `markdown-mode'.
8295 It is called with a single argument specifying the number of
8296 paragraphs to move. Just like `forward-paragraph', it should
8297 return the number of paragraphs left to move."
8298 (or arg (setq arg 1))
8299 (if (> arg 0)
8300 ;; With positive ARG, move across ARG non-code-block paragraphs,
8301 ;; one at a time. When passing a code block, don't decrement ARG.
8302 (while (and (not (eobp))
8303 (> arg 0)
8304 (= (forward-paragraph 1) 0)
8305 (or (markdown-code-block-at-pos (point-at-bol 0))
8306 (setq arg (1- arg)))))
8307 ;; Move backward by one paragraph with negative ARG (always -1).
8308 (let ((start (point)))
8309 (setq arg (forward-paragraph arg))
8310 (while (and (not (eobp))
8311 (progn (move-to-left-margin) (not (eobp)))
8312 (looking-at-p paragraph-separate))
8313 (forward-line 1))
8314 (cond
8315 ;; Move point past whitespace following list marker.
8316 ((looking-at markdown-regex-list)
8317 (goto-char (match-end 0)))
8318 ;; Move point past whitespace following pipe at beginning of line
8319 ;; to handle Pandoc line blocks.
8320 ((looking-at "^|\\s-*")
8321 (goto-char (match-end 0)))
8322 ;; Return point if the paragraph passed was a code block.
8323 ((markdown-code-block-at-pos (point-at-bol 2))
8324 (goto-char start)))))
8325 arg)
8327 (defun markdown--inhibit-electric-quote ()
8328 "Function added to `electric-quote-inhibit-functions'.
8329 Return non-nil if the quote has been inserted inside a code block
8330 or span."
8331 (let ((pos (1- (point))))
8332 (or (markdown-inline-code-at-pos pos)
8333 (markdown-code-block-at-pos pos))))
8336 ;;; Extension Framework =======================================================
8338 (defun markdown-reload-extensions ()
8339 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
8340 (interactive)
8341 (when (member major-mode '(markdown-mode gfm-mode))
8342 ;; Update font lock keywords with extensions
8343 (setq markdown-mode-font-lock-keywords
8344 (append
8345 (markdown-mode-font-lock-keywords-math)
8346 markdown-mode-font-lock-keywords-basic
8347 (markdown-mode-font-lock-keywords-wiki-links)))
8348 ;; Update font lock defaults
8349 (setq font-lock-defaults
8350 '(markdown-mode-font-lock-keywords
8351 nil nil nil nil
8352 (font-lock-syntactic-face-function . markdown-syntactic-face)))
8353 ;; Refontify buffer
8354 (when (and font-lock-mode (fboundp 'font-lock-refresh-defaults))
8355 (font-lock-refresh-defaults))
8357 ;; Add or remove hooks related to extensions
8358 (markdown-setup-wiki-link-hooks)))
8360 (defun markdown-handle-local-variables ()
8361 "Run in `hack-local-variables-hook' to update font lock rules.
8362 Checks to see if there is actually a ‘markdown-mode’ file local variable
8363 before regenerating font-lock rules for extensions."
8364 (when (and (boundp 'file-local-variables-alist)
8365 (assoc 'markdown-enable-wiki-links file-local-variables-alist)
8366 (assoc 'markdown-enable-math file-local-variables-alist))
8367 (markdown-reload-extensions)))
8370 ;;; Wiki Links ================================================================
8372 (defun markdown-toggle-wiki-links (&optional arg)
8373 "Toggle support for wiki links.
8374 With a prefix argument ARG, enable wiki link support if ARG is positive,
8375 and disable it otherwise."
8376 (interactive (list (or current-prefix-arg 'toggle)))
8377 (setq markdown-enable-wiki-links
8378 (if (eq arg 'toggle)
8379 (not markdown-enable-wiki-links)
8380 (> (prefix-numeric-value arg) 0)))
8381 (if markdown-enable-wiki-links
8382 (message "markdown-mode wiki link support enabled")
8383 (message "markdown-mode wiki link support disabled"))
8384 (markdown-reload-extensions))
8386 (defun markdown-setup-wiki-link-hooks ()
8387 "Add or remove hooks for fontifying wiki links.
8388 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
8389 ;; Anytime text changes make sure it gets fontified correctly
8390 (if (and markdown-enable-wiki-links
8391 markdown-wiki-link-fontify-missing)
8392 (add-hook 'after-change-functions
8393 'markdown-check-change-for-wiki-link-after-change t t)
8394 (remove-hook 'after-change-functions
8395 'markdown-check-change-for-wiki-link-after-change t))
8396 ;; If we left the buffer there is a really good chance we were
8397 ;; creating one of the wiki link documents. Make sure we get
8398 ;; refontified when we come back.
8399 (if (and markdown-enable-wiki-links
8400 markdown-wiki-link-fontify-missing)
8401 (progn
8402 (add-hook 'window-configuration-change-hook
8403 'markdown-fontify-buffer-wiki-links t t)
8404 (markdown-fontify-buffer-wiki-links))
8405 (remove-hook 'window-configuration-change-hook
8406 'markdown-fontify-buffer-wiki-links t)
8407 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
8409 (defun markdown-mode-font-lock-keywords-wiki-links ()
8410 "Return wiki-link lock keywords if support is enabled.
8411 If `markdown-wiki-link-fontify-missing' is also enabled, we use
8412 hooks in `markdown-setup-wiki-link-hooks' for fontification instead."
8413 (when (and markdown-enable-wiki-links
8414 (not markdown-wiki-link-fontify-missing))
8415 (list
8416 (cons markdown-regex-wiki-link '((1 markdown-link-face prepend))))))
8419 ;;; Math Support ==============================================================
8421 (make-obsolete 'markdown-enable-math 'markdown-toggle-math "v2.1")
8423 (defun markdown-toggle-math (&optional arg)
8424 "Toggle support for inline and display LaTeX math expressions.
8425 With a prefix argument ARG, enable math mode if ARG is positive,
8426 and disable it otherwise. If called from Lisp, enable the mode
8427 if ARG is omitted or nil."
8428 (interactive (list (or current-prefix-arg 'toggle)))
8429 (setq markdown-enable-math
8430 (if (eq arg 'toggle)
8431 (not markdown-enable-math)
8432 (> (prefix-numeric-value arg) 0)))
8433 (if markdown-enable-math
8434 (message "markdown-mode math support enabled")
8435 (message "markdown-mode math support disabled"))
8436 (markdown-reload-extensions))
8438 (defun markdown-mode-font-lock-keywords-math ()
8439 "Return math font lock keywords if support is enabled."
8440 (when markdown-enable-math
8441 (list
8442 ;; Display mode equations with brackets: \[ \]
8443 (cons markdown-regex-math-display '((1 markdown-markup-face prepend)
8444 (2 markdown-math-face append)
8445 (3 markdown-markup-face prepend)))
8446 ;; Equation reference (eq:foo)
8447 (cons "\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" '((1 markdown-markup-face)
8448 (2 markdown-reference-face)
8449 (3 markdown-markup-face)))
8450 ;; Equation reference \eqref{foo}
8451 (cons "\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" '((1 markdown-markup-face)
8452 (2 markdown-reference-face)
8453 (3 markdown-markup-face))))))
8456 ;;; GFM Checkboxes ============================================================
8458 (define-button-type 'markdown-gfm-checkbox-button
8459 'follow-link t
8460 'face 'markdown-gfm-checkbox-face
8461 'mouse-face 'markdown-highlight-face
8462 'action #'markdown-toggle-gfm-checkbox-button)
8464 (defun markdown-gfm-task-list-item-at-point (&optional bounds)
8465 "Return non-nil if there is a GFM task list item at the point.
8466 Optionally, the list item BOUNDS may be given if available, as
8467 returned by `markdown-cur-list-item-bounds'. When a task list item
8468 is found, the return value is the same value returned by
8469 `markdown-cur-list-item-bounds'."
8470 (unless bounds
8471 (setq bounds (markdown-cur-list-item-bounds)))
8472 (> (length (nth 5 bounds)) 0))
8474 (defun markdown-toggle-gfm-checkbox ()
8475 "Toggle GFM checkbox at point.
8476 Returns the resulting status as a string, either \"[x]\" or \"[ ]\".
8477 Returns nil if there is no task list item at the point."
8478 (interactive)
8479 (save-match-data
8480 (save-excursion
8481 (let ((bounds (markdown-cur-list-item-bounds)))
8482 (when bounds
8483 ;; Move to beginning of task list item
8484 (goto-char (cl-first bounds))
8485 ;; Advance to column of first non-whitespace after marker
8486 (forward-char (cl-fourth bounds))
8487 (cond ((looking-at "\\[ \\]")
8488 (replace-match "[x]" nil t)
8489 (match-string-no-properties 0))
8490 ((looking-at "\\[[xX]\\]")
8491 (replace-match "[ ]" nil t)
8492 (match-string-no-properties 0))))))))
8494 (defun markdown-toggle-gfm-checkbox-button (button)
8495 "Toggle GFM checkbox BUTTON on click."
8496 (save-match-data
8497 (save-excursion
8498 (goto-char (button-start button))
8499 (markdown-toggle-gfm-checkbox))))
8501 (defun markdown-make-gfm-checkboxes-buttons (start end)
8502 "Make GFM checkboxes buttons in region between START and END."
8503 (save-excursion
8504 (goto-char start)
8505 (let ((case-fold-search t))
8506 (save-excursion
8507 (while (re-search-forward markdown-regex-gfm-checkbox end t)
8508 (make-button (match-beginning 1) (match-end 1)
8509 :type 'markdown-gfm-checkbox-button))))))
8511 ;; Called when any modification is made to buffer text.
8512 (defun markdown-gfm-checkbox-after-change-function (beg end _)
8513 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
8514 BEG and END are the limits of scanned region."
8515 (save-excursion
8516 (save-match-data
8517 ;; Rescan between start of line from `beg' and start of line after `end'.
8518 (markdown-make-gfm-checkboxes-buttons
8519 (progn (goto-char beg) (beginning-of-line) (point))
8520 (progn (goto-char end) (forward-line 1) (point))))))
8523 ;;; Display inline image =================================================
8525 (defvar markdown-inline-image-overlays nil)
8526 (make-variable-buffer-local 'markdown-inline-image-overlays)
8528 (defun markdown-remove-inline-images ()
8529 "Remove inline image overlays from image links in the buffer.
8530 This can be toggled with `markdown-toggle-inline-images'
8531 or \\[markdown-toggle-inline-images]."
8532 (interactive)
8533 (mapc #'delete-overlay markdown-inline-image-overlays)
8534 (setq markdown-inline-image-overlays nil))
8536 (defun markdown-display-inline-images ()
8537 "Add inline image overlays to image links in the buffer.
8538 This can be toggled with `markdown-toggle-inline-images'
8539 or \\[markdown-toggle-inline-images]."
8540 (interactive)
8541 (unless (display-graphic-p)
8542 (error "Cannot show images"))
8543 (save-excursion
8544 (save-restriction
8545 (widen)
8546 (goto-char (point-min))
8547 (while (re-search-forward markdown-regex-link-inline nil t)
8548 (let ((start (match-beginning 0))
8549 (end (match-end 0))
8550 (file (match-string-no-properties 6)))
8551 (when (file-exists-p file)
8552 (let* ((abspath (if (file-name-absolute-p file)
8553 file
8554 (concat default-directory file)))
8555 (image (create-image abspath)))
8556 (when image
8557 (let ((ov (make-overlay start end)))
8558 (overlay-put ov 'display image)
8559 (overlay-put ov 'face 'default)
8560 (push ov markdown-inline-image-overlays))))))))))
8562 (defun markdown-toggle-inline-images ()
8563 "Toggle inline image overlays in the buffer."
8564 (interactive)
8565 (if markdown-inline-image-overlays
8566 (markdown-remove-inline-images)
8567 (markdown-display-inline-images)))
8570 ;;; GFM Code Block Fontification ==============================================
8572 (defcustom markdown-fontify-code-blocks-natively nil
8573 "When non-nil, fontify code in code blocks using the native major mode.
8574 This only works for fenced code blocks where the language is
8575 specified where we can automatically determine the appropriate
8576 mode to use. The language to mode mapping may be customized by
8577 setting the variable `markdown-code-lang-modes'."
8578 :group 'markdown
8579 :type 'boolean
8580 :safe 'booleanp
8581 :package-version '(markdown-mode . "2.3"))
8583 (defun markdown-toggle-fontify-code-blocks-natively (&optional arg)
8584 "Toggle the native fontification of code blocks.
8585 With a prefix argument ARG, enable if ARG is positive,
8586 and disable otherwise."
8587 (interactive (list (or current-prefix-arg 'toggle)))
8588 (setq markdown-fontify-code-blocks-natively
8589 (if (eq arg 'toggle)
8590 (not markdown-fontify-code-blocks-natively)
8591 (> (prefix-numeric-value arg) 0)))
8592 (if markdown-fontify-code-blocks-natively
8593 (message "markdown-mode native code block fontification enabled")
8594 (message "markdown-mode native code block fontification disabled"))
8595 (markdown-reload-extensions))
8597 ;; This is based on `org-src-lang-modes' from org-src.el
8598 (defcustom markdown-code-lang-modes
8599 '(("ocaml" . tuareg-mode) ("elisp" . emacs-lisp-mode) ("ditaa" . artist-mode)
8600 ("asymptote" . asy-mode) ("dot" . fundamental-mode) ("sqlite" . sql-mode)
8601 ("calc" . fundamental-mode) ("C" . c-mode) ("cpp" . c++-mode)
8602 ("C++" . c++-mode) ("screen" . shell-script-mode) ("shell" . sh-mode)
8603 ("bash" . sh-mode))
8604 "Alist mapping languages to their major mode.
8605 The key is the language name, the value is the major mode. For
8606 many languages this is simple, but for language where this is not
8607 the case, this variable provides a way to simplify things on the
8608 user side. For example, there is no ocaml-mode in Emacs, but the
8609 mode to use is `tuareg-mode'."
8610 :group 'markdown
8611 :type '(repeat
8612 (cons
8613 (string "Language name")
8614 (symbol "Major mode")))
8615 :package-version '(markdown-mode . "2.3"))
8617 (defun markdown-get-lang-mode (lang)
8618 "Return major mode that should be used for LANG.
8619 LANG is a string, and the returned major mode is a symbol."
8620 (cl-find-if
8621 'fboundp
8622 (list (cdr (assoc lang markdown-code-lang-modes))
8623 (cdr (assoc (downcase lang) markdown-code-lang-modes))
8624 (intern (concat lang "-mode"))
8625 (intern (concat (downcase lang) "-mode")))))
8627 (defun markdown-fontify-code-blocks-generic (matcher last)
8628 "Add text properties to next code block from point to LAST.
8629 Use matching function MATCHER."
8630 (when (funcall matcher last)
8631 (save-excursion
8632 (save-match-data
8633 (let* ((start (match-beginning 0))
8634 (end (match-end 0))
8635 ;; Find positions outside opening and closing backquotes.
8636 (bol-prev (progn (goto-char start)
8637 (if (bolp) (point-at-bol 0) (point-at-bol))))
8638 (eol-next (progn (goto-char end)
8639 (if (bolp) (point-at-bol 2) (point-at-bol 3))))
8640 lang)
8641 (if (and markdown-fontify-code-blocks-natively
8642 (setq lang (markdown-code-block-lang)))
8643 (markdown-fontify-code-block-natively lang start end)
8644 (add-text-properties start end '(face markdown-pre-face)))
8645 ;; Set background for block as well as opening and closing lines.
8646 (font-lock-append-text-property
8647 bol-prev eol-next 'face 'markdown-code-face)
8648 ;; Set invisible property for lines before and after, including newline.
8649 (add-text-properties bol-prev start '(invisible markdown-markup))
8650 (add-text-properties end eol-next '(invisible markdown-markup)))))
8653 (defun markdown-fontify-gfm-code-blocks (last)
8654 "Add text properties to next GFM code block from point to LAST."
8655 (markdown-fontify-code-blocks-generic 'markdown-match-gfm-code-blocks last))
8657 (defun markdown-fontify-fenced-code-blocks (last)
8658 "Add text properties to next tilde fenced code block from point to LAST."
8659 (markdown-fontify-code-blocks-generic 'markdown-match-fenced-code-blocks last))
8661 ;; Based on `org-src-font-lock-fontify-block' from org-src.el.
8662 (defun markdown-fontify-code-block-natively (lang start end)
8663 "Fontify given GFM or fenced code block.
8664 This function is called by Emacs for automatic fontification when
8665 `markdown-fontify-code-blocks-natively' is non-nil. LANG is the
8666 language used in the block. START and END specify the block
8667 position."
8668 (let ((lang-mode (markdown-get-lang-mode lang)))
8669 (when (fboundp lang-mode)
8670 (let ((string (buffer-substring-no-properties start end))
8671 (modified (buffer-modified-p))
8672 (markdown-buffer (current-buffer)) pos next)
8673 (remove-text-properties start end '(face nil))
8674 (with-current-buffer
8675 (get-buffer-create
8676 (concat " markdown-code-fontification:" (symbol-name lang-mode)))
8677 ;; Make sure that modification hooks are not inhibited in
8678 ;; the org-src-fontification buffer in case we're called
8679 ;; from `jit-lock-function' (Bug#25132).
8680 (let ((inhibit-modification-hooks nil))
8681 (delete-region (point-min) (point-max))
8682 (insert string " ")) ;; so there's a final property change
8683 (unless (eq major-mode lang-mode) (funcall lang-mode))
8684 (markdown-font-lock-ensure)
8685 (setq pos (point-min))
8686 (while (setq next (next-single-property-change pos 'face))
8687 (let ((val (get-text-property pos 'face)))
8688 (when val
8689 (put-text-property
8690 (+ start (1- pos)) (1- (+ start next)) 'face
8691 val markdown-buffer)))
8692 (setq pos next)))
8693 (add-text-properties
8694 start end
8695 '(font-lock-fontified t fontified t font-lock-multiline t))
8696 (set-buffer-modified-p modified)))))
8698 (require 'edit-indirect nil t)
8699 (defvar edit-indirect-guess-mode-function)
8701 (defun markdown-edit-code-block ()
8702 "Edit Markdown code block in an indirect buffer."
8703 (interactive)
8704 (save-excursion
8705 (if (fboundp 'edit-indirect-region)
8706 (let* ((bounds (markdown-get-enclosing-fenced-block-construct))
8707 (begin (and bounds (goto-char (nth 0 bounds)) (point-at-bol 2)))
8708 (end (and bounds (goto-char (nth 1 bounds)) (point-at-bol 1))))
8709 (if (and begin end)
8710 (let* ((lang (markdown-code-block-lang))
8711 (mode (and lang (markdown-get-lang-mode lang)))
8712 (edit-indirect-guess-mode-function
8713 (lambda (_parent-buffer _beg _end)
8714 (funcall mode))))
8715 (edit-indirect-region begin end 'display-buffer))
8716 (user-error "Not inside a GFM or tilde fenced code block")))
8717 (when (y-or-n-p "Package edit-indirect needed to edit code blocks. Install it now? ")
8718 (progn (package-refresh-contents)
8719 (package-install 'edit-indirect)
8720 (markdown-edit-code-block))))))
8723 ;;; ElDoc Support
8725 (defun markdown-eldoc-function ()
8726 "Return a helpful string when appropriate based on context.
8727 * Report URL when point is at a hidden URL.
8728 * Report language name when point is a code block with hidden markup."
8729 (cond
8730 ;; Hidden URL or reference for inline link
8731 ((and (or (thing-at-point-looking-at markdown-regex-link-inline)
8732 (thing-at-point-looking-at markdown-regex-link-reference))
8733 (or markdown-hide-urls markdown-hide-markup))
8734 (let* ((imagep (string-equal (match-string 1) "!"))
8735 (edit-keys (markdown--substitute-command-keys
8736 (if imagep
8737 "\\[markdown-insert-image]"
8738 "\\[markdown-insert-link]")))
8739 (edit-str (propertize edit-keys 'face 'font-lock-constant-face))
8740 (referencep (string-equal (match-string 5) "["))
8741 (object (if referencep "reference" "URL")))
8742 (format "Hidden %s (%s to edit): %s" object edit-str
8743 (if referencep
8744 (concat
8745 (propertize "[" 'face 'markdown-markup-face)
8746 (propertize (match-string-no-properties 6)
8747 'face 'markdown-reference-face)
8748 (propertize "]" 'face 'markdown-markup-face))
8749 (propertize (match-string-no-properties 6)
8750 'face 'markdown-url-face)))))
8751 ;; Hidden language name for fenced code blocks
8752 ((and (markdown-code-block-at-point-p)
8753 (not (get-text-property (point) 'markdown-pre))
8754 markdown-hide-markup)
8755 (let ((lang (save-excursion (markdown-code-block-lang))))
8756 (unless lang (setq lang "[unspecified]"))
8757 (format "Hidden code block language: %s (%s to toggle markup)"
8758 (propertize lang 'face 'markdown-language-keyword-face)
8759 (markdown--substitute-command-keys
8760 "\\[markdown-toggle-markup-hiding]"))))))
8763 ;;; Mode Definition ==========================================================
8765 (defun markdown-show-version ()
8766 "Show the version number in the minibuffer."
8767 (interactive)
8768 (message "markdown-mode, version %s" markdown-mode-version))
8770 (defun markdown-mode-info ()
8771 "Open the `markdown-mode' homepage."
8772 (interactive)
8773 (browse-url "http://jblevins.org/projects/markdown-mode/"))
8775 ;;;###autoload
8776 (define-derived-mode markdown-mode text-mode "Markdown"
8777 "Major mode for editing Markdown files."
8778 ;; Natural Markdown tab width
8779 (setq tab-width 4)
8780 ;; Comments
8781 (setq-local comment-start "<!-- ")
8782 (setq-local comment-end " -->")
8783 (setq-local comment-start-skip "<!--[ \t]*")
8784 (setq-local comment-column 0)
8785 (setq-local comment-auto-fill-only-comments nil)
8786 (setq-local comment-use-syntax t)
8787 ;; Syntax
8788 (add-hook 'syntax-propertize-extend-region-functions
8789 #'markdown-syntax-propertize-extend-region)
8790 (add-hook 'jit-lock-after-change-extend-region-functions
8791 #'markdown-font-lock-extend-region-function t t)
8792 (setq-local syntax-propertize-function #'markdown-syntax-propertize)
8793 ;; Font lock.
8794 (setq-local markdown-mode-font-lock-keywords nil)
8795 (setq-local font-lock-defaults nil)
8796 (setq-local font-lock-multiline t)
8797 (setq-local font-lock-extra-managed-props
8798 (append font-lock-extra-managed-props
8799 '(composition display invisible)))
8800 (if markdown-hide-markup
8801 (add-to-invisibility-spec 'markdown-markup)
8802 (remove-from-invisibility-spec 'markdown-markup))
8803 (markdown-update-code-face)
8804 ;; Reload extensions
8805 (markdown-reload-extensions)
8806 ;; Add a buffer-local hook to reload after file-local variables are read
8807 (add-hook 'hack-local-variables-hook #'markdown-handle-local-variables nil t)
8808 ;; For imenu support
8809 (setq imenu-create-index-function
8810 (if markdown-nested-imenu-heading-index
8811 #'markdown-imenu-create-nested-index
8812 #'markdown-imenu-create-flat-index))
8813 ;; For menu support in XEmacs
8814 (easy-menu-add markdown-mode-menu markdown-mode-map)
8815 ;; Defun movement
8816 (setq-local beginning-of-defun-function #'markdown-beginning-of-defun)
8817 (setq-local end-of-defun-function #'markdown-end-of-defun)
8818 ;; Paragraph filling
8819 (setq-local fill-paragraph-function #'markdown-fill-paragraph)
8820 (setq-local paragraph-start
8821 ;; Should match start of lines that start or separate paragraphs
8822 (mapconcat #'identity
8824 "\f" ; starts with a literal line-feed
8825 "[ \t\f]*$" ; space-only line
8826 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
8827 "[ \t]*[*+-][ \t]+" ; unordered list item
8828 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
8829 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
8830 "[ \t]*:[ \t]+" ; definition
8831 "^|" ; table or Pandoc line block
8833 "\\|"))
8834 (setq-local paragraph-separate
8835 ;; Should match lines that separate paragraphs without being
8836 ;; part of any paragraph:
8837 (mapconcat #'identity
8838 '("[ \t\f]*$" ; space-only line
8839 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
8840 ;; The following is not ideal, but the Fill customization
8841 ;; options really only handle paragraph-starting prefixes,
8842 ;; not paragraph-ending suffixes:
8843 ".* $" ; line ending in two spaces
8844 "^#+"
8845 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
8846 "\\|"))
8847 (setq-local adaptive-fill-first-line-regexp "\\`[ \t]*[A-Z]?>[ \t]*?\\'")
8848 (setq-local adaptive-fill-regexp "\\s-*")
8849 (setq-local adaptive-fill-function #'markdown-adaptive-fill-function)
8850 (setq-local fill-forward-paragraph-function #'markdown-fill-forward-paragraph)
8851 ;; Outline mode
8852 (setq-local outline-regexp markdown-regex-header)
8853 (setq-local outline-level #'markdown-outline-level)
8854 ;; Cause use of ellipses for invisible text.
8855 (add-to-invisibility-spec '(outline . t))
8856 ;; ElDoc support
8857 (if (eval-when-compile (fboundp 'add-function))
8858 (add-function :before-until (local 'eldoc-documentation-function)
8859 #'markdown-eldoc-function)
8860 (setq-local eldoc-documentation-function #'markdown-eldoc-function))
8861 ;; Inhibiting line-breaking:
8862 ;; Separating out each condition into a separate function so that users can
8863 ;; override if desired (with remove-hook)
8864 (add-hook 'fill-nobreak-predicate
8865 #'markdown-inside-link-p nil t)
8866 (add-hook 'fill-nobreak-predicate
8867 #'markdown-line-is-reference-definition-p nil t)
8868 (add-hook 'fill-nobreak-predicate
8869 #'markdown-pipe-at-bol-p nil t)
8871 ;; Indentation
8872 (setq-local indent-line-function markdown-indent-function)
8874 ;; Flyspell
8875 (setq-local flyspell-generic-check-word-predicate
8876 #'markdown-flyspell-check-word-p)
8878 ;; Electric quoting
8879 (add-hook 'electric-quote-inhibit-functions
8880 #'markdown--inhibit-electric-quote nil :local)
8882 ;; Backwards compatibility with markdown-css-path
8883 (when (boundp 'markdown-css-path)
8884 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
8885 (add-to-list 'markdown-css-paths markdown-css-path))
8887 ;; Prepare hooks for XEmacs compatibility
8888 (when (featurep 'xemacs)
8889 (make-local-hook 'after-change-functions)
8890 (make-local-hook 'font-lock-extend-region-functions)
8891 (make-local-hook 'window-configuration-change-hook))
8893 ;; Make checkboxes buttons
8894 (when markdown-make-gfm-checkboxes-buttons
8895 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
8896 (add-hook 'after-change-functions #'markdown-gfm-checkbox-after-change-function t t))
8898 ;; add live preview export hook
8899 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
8900 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
8902 ;;;###autoload
8903 (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode) t)
8904 ;;;###autoload
8905 (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode) t)
8908 ;;; GitHub Flavored Markdown Mode ============================================
8910 (defvar gfm-mode-hook nil
8911 "Hook run when entering GFM mode.")
8913 (defvar gfm-font-lock-keywords
8914 ;; Basic Markdown features (excluding possibly overridden ones)
8915 markdown-mode-font-lock-keywords-basic
8916 "Default highlighting expressions for GitHub Flavored Markdown mode.")
8918 ;;;###autoload
8919 (define-derived-mode gfm-mode markdown-mode "GFM"
8920 "Major mode for editing GitHub Flavored Markdown files."
8921 (setq markdown-link-space-sub-char "-")
8922 (setq markdown-wiki-link-search-subdirectories t)
8923 (setq-local font-lock-defaults '(gfm-font-lock-keywords))
8924 ;; do the initial link fontification
8925 (markdown-gfm-parse-buffer-for-languages))
8928 ;;; Live Preview Mode ============================================
8929 (define-minor-mode markdown-live-preview-mode
8930 "Toggle native previewing on save for a specific markdown file."
8931 :lighter " MD-Preview"
8932 (if markdown-live-preview-mode
8933 (if (markdown-live-preview-get-filename)
8934 (markdown-display-buffer-other-window (markdown-live-preview-export))
8935 (markdown-live-preview-mode -1)
8936 (user-error "Buffer %s does not visit a file" (current-buffer)))
8937 (markdown-live-preview-remove)))
8940 (provide 'markdown-mode)
8941 ;; Local Variables:
8942 ;; indent-tabs-mode: nil
8943 ;; End:
8944 ;;; markdown-mode.el ends here