Fix customization types
[markdown-mode.git] / markdown-mode.el
blob822e3337b5c7f86b65b0b11bc70b73f500cd6c9a
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
10 ;; Package-Requires: ((emacs "24") (cl-lib "0.5"))
11 ;; Keywords: Markdown, GitHub Flavored Markdown, itex
12 ;; URL: https://jblevins.org/projects/markdown-mode/
14 ;; This file is not part of GNU Emacs.
16 ;; This program is free software; you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
21 ;; This program is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
29 ;;; Commentary:
31 ;; markdown-mode is a major mode for editing [Markdown][]-formatted
32 ;; text. The latest stable version is markdown-mode 2.3, released on
33 ;; August 31, 2017. See the [release notes][] for details.
34 ;; markdown-mode is free software, licensed under the GNU GPL,
35 ;; version 3 or later.
37 ;; ![Markdown Mode Screenshot](https://jblevins.org/projects/markdown-mode/screenshots/20170818-001.png)
39 ;; [Markdown]: http://daringfireball.net/projects/markdown/
40 ;; [release notes]: https://jblevins.org/projects/markdown-mode/rev-2-3
42 ;;; Documentation:
44 ;; <a href="https://leanpub.com/markdown-mode">
45 ;; <img src="https://jblevins.org/projects/markdown-mode/guide-v2.3.png" align="right" height="350" width="231">
46 ;; </a>
48 ;; The primary documentation for Markdown Mode is available below, and
49 ;; is generated from comments in the source code. For a more in-depth
50 ;; treatment, the [_Guide to Markdown Mode for Emacs_][guide] covers
51 ;; Markdown syntax, advanced movement and editing in Emacs,
52 ;; extensions, configuration examples, tips and tricks, and a survey
53 ;; of other packages that work with Markdown Mode. Finally, Emacs is
54 ;; also a self-documenting editor. This means that the source code
55 ;; itself contains additional documentation: each function has its own
56 ;; docstring available via `C-h f` (`describe-function'), individual
57 ;; keybindings can be investigated with `C-h k` (`describe-key'), and
58 ;; a complete list of keybindings is available using `C-h m`
59 ;; (`describe-mode').
61 ;; [guide]: https://leanpub.com/markdown-mode
63 ;;; Installation:
65 ;; _Note:_ To use all of the features of `markdown-mode', you'll need
66 ;; to install the Emacs package itself and also have a local Markdown
67 ;; processor installed (e.g., Markdown.pl, MultiMarkdown, or Pandoc).
68 ;; The external processor is not required for editing, but will be
69 ;; used for rendering HTML for preview and export. After installing
70 ;; the Emacs package, be sure to configure `markdown-command' to point
71 ;; to the preferred Markdown executable on your system. See the
72 ;; Customization section below for more details.
74 ;; The recommended way to install `markdown-mode' is to install the package
75 ;; from [MELPA Stable](https://stable.melpa.org/#/markdown-mode)
76 ;; using `package.el'. First, configure `package.el' and the MELPA Stable
77 ;; repository by adding the following to your `.emacs', `init.el',
78 ;; or equivalent startup file:
80 ;; ``` Lisp
81 ;; (require 'package)
82 ;; (add-to-list 'package-archives
83 ;; '("melpa-stable" . "https://stable.melpa.org/packages/"))
84 ;; (package-initialize)
85 ;; ```
87 ;; Then, after restarting Emacs or evaluating the above statements, issue
88 ;; the following command: `M-x package-install RET markdown-mode RET`.
89 ;; When installed this way, the major modes `markdown-mode' and `gfm-mode'
90 ;; will be autoloaded and `markdown-mode' will be used for file names
91 ;; ending in either `.md` or `.markdown`.
93 ;; Alternatively, if you manage loading packages with [use-package][]
94 ;; then you can automatically install and configure `markdown-mode' by
95 ;; adding a declaration such as this one to your init file (as an
96 ;; example; adjust settings as desired):
98 ;; ``` Lisp
99 ;; (use-package markdown-mode
100 ;; :ensure t
101 ;; :commands (markdown-mode gfm-mode)
102 ;; :mode (("README\\.md\\'" . gfm-mode)
103 ;; ("\\.md\\'" . markdown-mode)
104 ;; ("\\.markdown\\'" . markdown-mode))
105 ;; :init (setq markdown-command "multimarkdown"))
106 ;; ```
108 ;; [MELPA Stable]: http://stable.melpa.org/
109 ;; [use-package]: https://github.com/jwiegley/use-package
111 ;; **Direct Download**
113 ;; Alternatively you can manually download and install markdown-mode.
114 ;; First, download the [latest stable version][markdown-mode.el] and
115 ;; save the file where Emacs can find it (i.e., a directory in your
116 ;; `load-path'). You can then configure `markdown-mode' and `gfm-mode'
117 ;; to load automatically by adding the following to your init file:
119 ;; ``` Lisp
120 ;; (autoload 'markdown-mode "markdown-mode"
121 ;; "Major mode for editing Markdown files" t)
122 ;; (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode))
123 ;; (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode))
125 ;; (autoload 'gfm-mode "markdown-mode"
126 ;; "Major mode for editing GitHub Flavored Markdown files" t)
127 ;; (add-to-list 'auto-mode-alist '("README\\.md\\'" . gfm-mode))
128 ;; ```
130 ;; [markdown-mode.el]: https://jblevins.org/projects/markdown-mode/markdown-mode.el
132 ;; **Development Version**
134 ;; To follow or contribute to markdown-mode development, you can
135 ;; browse or clone the Git repository
136 ;; [on GitHub](https://github.com/jrblevin/markdown-mode):
138 ;; ```
139 ;; git clone https://github.com/jrblevin/markdown-mode.git
140 ;; ```
142 ;; If you prefer to install and use the development version, which may
143 ;; become unstable at some times, you can either clone the Git
144 ;; repository as above or install markdown-mode from
145 ;; [MELPA](https://melpa.org/#/markdown-mode).
147 ;; If you clone the repository directly, then make sure that Emacs can
148 ;; find it by adding the following line to your startup file:
150 ;; ``` Lisp
151 ;; (add-to-list 'load-path "/path/to/markdown-mode/repository")
152 ;; ```
154 ;; **Packaged Installation**
156 ;; markdown-mode is also available in several package managers. You
157 ;; may want to confirm that the package you install contains the
158 ;; latest stable version first (and please notify the package
159 ;; maintainer if not).
161 ;; * Debian Linux: [elpa-markdown-mode][] and [emacs-goodies-el][]
162 ;; * Ubuntu Linux: [elpa-markdown-mode][elpa-ubuntu] and [emacs-goodies-el][emacs-goodies-el-ubuntu]
163 ;; * RedHat and Fedora Linux: [emacs-goodies][]
164 ;; * NetBSD: [textproc/markdown-mode][]
165 ;; * MacPorts: [markdown-mode.el][macports-package] ([pending][macports-ticket])
166 ;; * FreeBSD: [textproc/markdown-mode.el][freebsd-port]
168 ;; [elpa-markdown-mode]: https://packages.debian.org/sid/lisp/elpa-markdown-mode
169 ;; [elpa-ubuntu]: http://packages.ubuntu.com/search?keywords=elpa-markdown-mode
170 ;; [emacs-goodies-el]: http://packages.debian.org/emacs-goodies-el
171 ;; [emacs-goodies-el-ubuntu]: http://packages.ubuntu.com/search?keywords=emacs-goodies-el
172 ;; [emacs-goodies]: https://apps.fedoraproject.org/packages/emacs-goodies
173 ;; [textproc/markdown-mode]: http://pkgsrc.se/textproc/markdown-mode
174 ;; [macports-package]: https://trac.macports.org/browser/trunk/dports/editors/markdown-mode.el/Portfile
175 ;; [macports-ticket]: http://trac.macports.org/ticket/35716
176 ;; [freebsd-port]: http://svnweb.freebsd.org/ports/head/textproc/markdown-mode.el
178 ;; **Dependencies**
180 ;; To enable editing of code blocks in indirect buffers using `C-c '`,
181 ;; you will need to install the [`edit-indirect'][ei] package.
183 ;; [ei]: https://github.com/Fanael/edit-indirect/
185 ;;; Usage:
187 ;; Keybindings are grouped by prefixes based on their function. For
188 ;; example, the commands for styling text are grouped under `C-c C-s`
189 ;; and toggle commands begin with `C-c C-x`. The primary commands in
190 ;; each group will are described below. You can obtain a list of all
191 ;; keybindings by pressing `C-c C-h`. Movement and shifting commands
192 ;; tend to be associated with paired delimiters such as `M-{` and
193 ;; `M-}` or `C-c <` and `C-c >`. Outline navigation keybindings the
194 ;; same as in `org-mode'. Finally, commands for running Markdown or
195 ;; doing maintenance on an open file are grouped under the `C-c C-c`
196 ;; prefix. The most commonly used commands are described below. You
197 ;; can obtain a list of all keybindings by pressing `C-c C-h`.
199 ;; * Links and Images: `C-c C-l` and `C-c C-i`
201 ;; `C-c C-l` (`markdown-insert-link`) is a general command for
202 ;; inserting new link markup or editing existing link markup. This
203 ;; is especially useful when markup or URL hiding is enabled, so
204 ;; that URLs can't easily be edited directly. This command can be
205 ;; used to insert links of any form: either inline links,
206 ;; reference links, or plain URLs in angle brackets. The URL or
207 ;; `[reference]` label, link text, and optional title are entered
208 ;; through a series of interactive prompts. The type of link is
209 ;; determined by which values are provided:
211 ;; * If both a URL and link text are given, insert an inline link:
212 ;; `[text](url)`.
213 ;; * If both a `[reference]` label and link text are given, insert
214 ;; a reference link: `[text][reference]`.
215 ;; * If only link text is given, insert an implicit reference link:
216 ;; `[text][]`.
217 ;; * If only a URL is given, insert a plain URL link:
218 ;; `<url>`.
220 ;; Similarly, `C-c C-i` (`markdown-insert-image`) is a general
221 ;; command for inserting or editing image markup. As with the link
222 ;; insertion command, through a series interactive prompts you can
223 ;; insert either an inline or reference image:
225 ;; * If both a URL and alt text are given, insert an inline
226 ;; image: `![alt text](url)`.
227 ;; * If both a `[reference]` label and alt text are given,
228 ;; insert a reference link: `![alt text][reference]`.
230 ;; If there is an existing link or image at the point, these
231 ;; command will edit the existing markup rather than inserting new
232 ;; markup. Otherwise, if there is an active region, these commands
233 ;; use the region as either the default URL (if it seems to be a
234 ;; URL) or link text value otherwise. In that case, the region
235 ;; will be deleted and replaced by the link.
237 ;; Note that these functions can be used to convert links and
238 ;; images from one type to another (inline, reference, or plain
239 ;; URL) by selectively adding or removing properties via the
240 ;; interactive prompts.
242 ;; If a reference label is given that is not yet defined, you
243 ;; will be prompted for the URL and optional title and the
244 ;; reference will be inserted according to the value of
245 ;; `markdown-reference-location'. If a title is given, it will be
246 ;; added to the end of the reference definition and will be used
247 ;; to populate the title attribute when converted to HTML.
249 ;; Local images associated with image links may be displayed
250 ;; inline in the buffer by pressing `C-c C-x C-i`
251 ;; (`markdown-toggle-inline-images'). This is a toggle command, so
252 ;; pressing this once again will remove inline images.
254 ;; * Text Styles: `C-c C-s`
256 ;; `C-c C-s i` inserts markup to make a region or word italic. If
257 ;; there is an active region, make the region italic. If the point
258 ;; is at a non-italic word, make the word italic. If the point is
259 ;; at an italic word or phrase, remove the italic markup.
260 ;; Otherwise, simply insert italic delimiters and place the cursor
261 ;; in between them. Similarly, use `C-c C-s b` for bold, `C-c C-s c`
262 ;; for inline code, and `C-c C-s k` for inserting `<kbd>` tags.
264 ;; `C-c C-s q` inserts a blockquote using the active region, if
265 ;; any, or starts a new blockquote. `C-c C-s Q` is a variation
266 ;; which always operates on the region, regardless of whether it
267 ;; is active or not (i.e., when `transient-mark-mode` is off but
268 ;; the mark is set). The appropriate amount of indentation, if
269 ;; any, is calculated automatically given the surrounding context,
270 ;; but may be adjusted later using the region indentation
271 ;; commands.
273 ;; `C-c C-s p` behaves similarly for inserting preformatted code
274 ;; blocks (with `C-c C-s P` being the region-only counterpart)
275 ;; and `C-c C-s C` inserts a GFM style backquote fenced code block.
277 ;; * Headings: `C-c C-s`
279 ;; To insert or replace headings, there are two options. You can
280 ;; insert a specific level heading directly or you can have
281 ;; `markdown-mode' determine the level for you based on the previous
282 ;; heading. As with the other markup commands, the heading
283 ;; insertion commands use the text in the active region, if any,
284 ;; as the heading text. Otherwise, if the current line is not
285 ;; blank, they use the text on the current line. Finally, the
286 ;; setext commands will prompt for heading text if there is no
287 ;; active region and the current line is blank.
289 ;; `C-c C-s h` inserts a heading with automatically chosen type and
290 ;; level (both determined by the previous heading). `C-c C-s H`
291 ;; behaves similarly, but uses setext (underlined) headings when
292 ;; possible, still calculating the level automatically.
293 ;; In cases where the automatically-determined level is not what
294 ;; you intended, the level can be quickly promoted or demoted
295 ;; (as described below). Alternatively, a `C-u` prefix can be
296 ;; given to insert a heading _promoted_ (lower number) by one
297 ;; level or a `C-u C-u` prefix can be given to insert a heading
298 ;; demoted (higher number) by one level.
300 ;; To insert a heading of a specific level and type, use `C-c C-s 1`
301 ;; through `C-c C-s 6` for atx (hash mark) headings and `C-c C-s !` or
302 ;; `C-c C-s @` for setext headings of level one or two, respectively.
303 ;; Note that `!` is `S-1` and `@` is `S-2`.
305 ;; If the point is at a heading, these commands will replace the
306 ;; existing markup in order to update the level and/or type of the
307 ;; heading. To remove the markup of the heading at the point,
308 ;; press `C-c C-k` to kill the heading and press `C-y` to yank the
309 ;; heading text back into the buffer.
311 ;; * Horizontal Rules: `C-c C-s -`
313 ;; `C-c C-s -` inserts a horizontal rule. By default, insert the
314 ;; first string in the list `markdown-hr-strings' (the most
315 ;; prominent rule). With a `C-u` prefix, insert the last string.
316 ;; With a numeric prefix `N`, insert the string in position `N`
317 ;; (counting from 1).
319 ;; * Footnotes: `C-c C-s f`
321 ;; `C-c C-s f` inserts a footnote marker at the point, inserts a
322 ;; footnote definition below, and positions the point for
323 ;; inserting the footnote text. Note that footnotes are an
324 ;; extension to Markdown and are not supported by all processors.
326 ;; * Wiki Links: `C-c C-s w`
328 ;; `C-c C-s w` inserts a wiki link of the form `[[WikiLink]]`. If
329 ;; there is an active region, use the region as the link text. If the
330 ;; point is at a word, use the word as the link text. If there is
331 ;; no active region and the point is not at word, simply insert
332 ;; link markup. Note that wiki links are an extension to Markdown
333 ;; and are not supported by all processors.
335 ;; * Markdown and Maintenance Commands: `C-c C-c`
337 ;; *Compile:* `C-c C-c m` will run Markdown on the current buffer
338 ;; and show the output in another buffer. *Preview*: `C-c C-c p`
339 ;; runs Markdown on the current buffer and previews, stores the
340 ;; output in a temporary file, and displays the file in a browser.
341 ;; *Export:* `C-c C-c e` will run Markdown on the current buffer
342 ;; and save the result in the file `basename.html`, where
343 ;; `basename` is the name of the Markdown file with the extension
344 ;; removed. *Export and View:* press `C-c C-c v` to export the
345 ;; file and view it in a browser. *Open:* `C-c C-c o` will open
346 ;; the Markdown source file directly using `markdown-open-command'.
347 ;; *Live Export*: Press `C-c C-c l` to turn on
348 ;; `markdown-live-preview-mode' to view the exported output
349 ;; side-by-side with the source Markdown. **For all export commands,
350 ;; the output file will be overwritten without notice.**
351 ;; `markdown-live-preview-window-function' can be customized to open
352 ;; in a browser other than `eww'. If you want to force the
353 ;; preview window to appear at the bottom or right, you can
354 ;; customize `markdown-split-window-direction'.
356 ;; To summarize:
358 ;; - `C-c C-c m`: `markdown-command' > `*markdown-output*` buffer.
359 ;; - `C-c C-c p`: `markdown-command' > temporary file > browser.
360 ;; - `C-c C-c e`: `markdown-command' > `basename.html`.
361 ;; - `C-c C-c v`: `markdown-command' > `basename.html` > browser.
362 ;; - `C-c C-c w`: `markdown-command' > kill ring.
363 ;; - `C-c C-c o`: `markdown-open-command'.
364 ;; - `C-c C-c l`: `markdown-live-preview-mode' > `*eww*` buffer.
366 ;; `C-c C-c c` will check for undefined references. If there are
367 ;; any, a small buffer will open with a list of undefined
368 ;; references and the line numbers on which they appear. In Emacs
369 ;; 22 and greater, selecting a reference from this list and
370 ;; pressing `RET` will insert an empty reference definition at the
371 ;; end of the buffer. Similarly, selecting the line number will
372 ;; jump to the corresponding line.
374 ;; `C-c C-c n` renumbers any ordered lists in the buffer that are
375 ;; out of sequence.
377 ;; `C-c C-c ]` completes all headings and normalizes all horizontal
378 ;; rules in the buffer.
380 ;; * Following Links: `C-c C-o`
382 ;; Press `C-c C-o` when the point is on an inline or reference
383 ;; link to open the URL in a browser. When the point is at a
384 ;; wiki link, open it in another buffer (in the current window,
385 ;; or in the other window with the `C-u` prefix). Use `M-p` and
386 ;; `M-n` to quickly jump to the previous or next link of any type.
388 ;; * Doing Things: `C-c C-d`
390 ;; Use `C-c C-d` to do something sensible with the object at the point:
392 ;; - Jumps between reference links and reference definitions.
393 ;; If more than one link uses the same reference label, a
394 ;; window will be shown containing clickable buttons for
395 ;; jumping to each link. Pressing `TAB` or `S-TAB` cycles
396 ;; between buttons in this window.
397 ;; - Jumps between footnote markers and footnote text.
398 ;; - Toggles the completion status of GFM task list items
399 ;; (checkboxes).
401 ;; * Promotion and Demotion: `C-c C--` and `C-c C-=`
403 ;; Headings, horizontal rules, and list items can be promoted and
404 ;; demoted, as well as bold and italic text. For headings,
405 ;; "promotion" means *decreasing* the level (i.e., moving from
406 ;; `<h2>` to `<h1>`) while "demotion" means *increasing* the
407 ;; level. For horizontal rules, promotion and demotion means
408 ;; moving backward or forward through the list of rule strings in
409 ;; `markdown-hr-strings'. For bold and italic text, promotion and
410 ;; demotion means changing the markup from underscores to asterisks.
411 ;; Press `C-c C--` or `C-c LEFT` to promote the element at the point
412 ;; if possible.
414 ;; To remember these commands, note that `-` is for decreasing the
415 ;; level (promoting), and `=` (on the same key as `+`) is for
416 ;; increasing the level (demoting). Similarly, the left and right
417 ;; arrow keys indicate the direction that the atx heading markup
418 ;; is moving in when promoting or demoting.
420 ;; * Completion: `C-c C-]`
422 ;; Complete markup is in normalized form, which means, for
423 ;; example, that the underline portion of a setext header is the
424 ;; same length as the heading text, or that the number of leading
425 ;; and trailing hash marks of an atx header are equal and that
426 ;; there is no extra whitespace in the header text. `C-c C-]`
427 ;; completes the markup at the point, if it is determined to be
428 ;; incomplete.
430 ;; * Editing Lists: `M-RET`, `C-c UP`, `C-c DOWN`, `C-c LEFT`, and `C-c RIGHT`
432 ;; New list items can be inserted with `M-RET` or `C-c C-j`. This
433 ;; command determines the appropriate marker (one of the possible
434 ;; unordered list markers or the next number in sequence for an
435 ;; ordered list) and indentation level by examining nearby list
436 ;; items. If there is no list before or after the point, start a
437 ;; new list. As with heading insertion, you may prefix this
438 ;; command by `C-u` to decrease the indentation by one level.
439 ;; Prefix this command by `C-u C-u` to increase the indentation by
440 ;; one level.
442 ;; Existing list items (and their nested sub-items) can be moved
443 ;; up or down with `C-c UP` or `C-c DOWN` and indented or
444 ;; outdented with `C-c RIGHT` or `C-c LEFT`.
446 ;; * Editing Subtrees: `C-c UP`, `C-c DOWN`, `C-c LEFT`, and `C-c RIGHT`
448 ;; Entire subtrees of ATX headings can be promoted and demoted
449 ;; with `C-c LEFT` and `C-c RIGHT`, which are the same keybindings
450 ;; used for promotion and demotion of list items. If the point is in
451 ;; a list item, the operate on the list item. Otherwise, they operate
452 ;; on the current heading subtree. Similarly, subtrees can be
453 ;; moved up and down with `C-c UP` and `C-c DOWN`.
455 ;; These commands currently do not work properly if there are
456 ;; Setext headings in the affected region.
458 ;; Please note the following "boundary" behavior for promotion and
459 ;; demotion. Any level-six headings will not be demoted further
460 ;; (i.e., they remain at level six, since Markdown and HTML define
461 ;; only six levels) and any level-one headings will promoted away
462 ;; entirely (i.e., heading markup will be removed, since a
463 ;; level-zero heading is not defined).
465 ;; * Shifting the Region: `C-c <` and `C-c >`
467 ;; Text in the region can be indented or outdented as a group using
468 ;; `C-c >` to indent to the next indentation point (calculated in
469 ;; the current context), and `C-c <` to outdent to the previous
470 ;; indentation point. These keybindings are the same as those for
471 ;; similar commands in `python-mode'.
473 ;; * Killing Elements: `C-c C-k`
475 ;; Press `C-c C-k` to kill the thing at point and add important
476 ;; text, without markup, to the kill ring. Possible things to
477 ;; kill include (roughly in order of precedece): inline code,
478 ;; headings, horizonal rules, links (add link text to kill ring),
479 ;; images (add alt text to kill ring), angle URIs, email
480 ;; addresses, bold, italics, reference definitions (add URI to
481 ;; kill ring), footnote markers and text (kill both marker and
482 ;; text, add text to kill ring), and list items.
484 ;; * Outline Navigation: `C-c C-n`, `C-c C-p`, `C-c C-f`, `C-c C-b`, and `C-c C-u`
486 ;; These keys are used for hierarchical navigation in lists and
487 ;; headings. When the point is in a list, they move between list
488 ;; items. Otherwise, they move between headings. Use `C-c C-n` and
489 ;; `C-c C-p` to move between the next and previous visible
490 ;; headings or list items of any level. Similarly, `C-c C-f` and
491 ;; `C-c C-b` move to the next and previous visible headings or
492 ;; list items at the same level as the one at the point. Finally,
493 ;; `C-c C-u` will move up to the parent heading or list item.
495 ;; * Movement by Markdown paragraph: `M-{`, `M-}`, and `M-h`
497 ;; Paragraphs in `markdown-mode' are regular paragraphs,
498 ;; paragraphs inside blockquotes, individual list items, headings,
499 ;; etc. These keys are usually bound to `forward-paragraph' and
500 ;; `backward-paragraph', but the built-in Emacs functions are
501 ;; based on simple regular expressions that fail in Markdown
502 ;; files. Instead, they are bound to `markdown-forward-paragraph'
503 ;; and `markdown-backward-paragraph'. To mark a paragraph,
504 ;; you can use `M-h` (`markdown-mark-paragraph').
506 ;; * Movement by Markdown block: `C-M-{`, `C-M-}`, and `C-c M-h`
508 ;; Markdown blocks are regular paragraphs in many cases, but
509 ;; contain many paragraphs in other cases: blocks are considered
510 ;; to be entire lists, entire code blocks, and entire blockquotes.
511 ;; To move backward one block use `C-M-{`
512 ;; (`markdown-beginning-block`) and to move forward use `C-M-}`
513 ;; (`markdown-end-of-block`). To mark a block, use `C-c M-h`
514 ;; (`markdown-mark-block`).
516 ;; * Movement by Defuns: `C-M-a`, `C-M-e`, and `C-M-h`
518 ;; The usual Emacs commands can be used to move by defuns
519 ;; (top-level major definitions). In markdown-mode, a defun is a
520 ;; section. As usual, `C-M-a` will move the point to the
521 ;; beginning of the current or preceding defun, `C-M-e` will move
522 ;; to the end of the current or following defun, and `C-M-h` will
523 ;; put the region around the entire defun.
525 ;; * Miscellaneous Commands:
527 ;; When the [`edit-indirect'][ei] package is installed, `C-c '`
528 ;; (`markdown-edit-code-block`) can be used to edit a code block
529 ;; in an indirect buffer in the native major mode. Press `C-c C-c`
530 ;; to commit changes and return or `C-c C-k` to cancel.
532 ;; As noted, many of the commands above behave differently depending
533 ;; on whether Transient Mark mode is enabled or not. When it makes
534 ;; sense, if Transient Mark mode is on and the region is active, the
535 ;; command applies to the text in the region (e.g., `C-c C-s b` makes the
536 ;; region bold). For users who prefer to work outside of Transient
537 ;; Mark mode, since Emacs 22 it can be enabled temporarily by pressing
538 ;; `C-SPC C-SPC`. When this is not the case, many commands then
539 ;; proceed to look work with the word or line at the point.
541 ;; When applicable, commands that specifically act on the region even
542 ;; outside of Transient Mark mode have the same keybinding as their
543 ;; standard counterpart, but the letter is uppercase. For example,
544 ;; `markdown-insert-blockquote' is bound to `C-c C-s q` and only acts on
545 ;; the region in Transient Mark mode while `markdown-blockquote-region'
546 ;; is bound to `C-c C-s Q` and always applies to the region (when nonempty).
548 ;; Note that these region-specific functions are useful in many
549 ;; cases where it may not be obvious. For example, yanking text from
550 ;; the kill ring sets the mark at the beginning of the yanked text
551 ;; and moves the point to the end. Therefore, the (inactive) region
552 ;; contains the yanked text. So, `C-y` followed by `C-c C-s Q` will
553 ;; yank text and turn it into a blockquote.
555 ;; markdown-mode attempts to be flexible in how it handles
556 ;; indentation. When you press `TAB` repeatedly, the point will cycle
557 ;; through several possible indentation levels corresponding to things
558 ;; you might have in mind when you press `RET` at the end of a line or
559 ;; `TAB`. For example, you may want to start a new list item,
560 ;; continue a list item with hanging indentation, indent for a nested
561 ;; pre block, and so on. Outdenting is handled similarly when backspace
562 ;; is pressed at the beginning of the non-whitespace portion of a line.
564 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
565 ;; visibility cycling for atx- or hash-style headings. There are two
566 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
567 ;; the table of contents view (headings only), outline view (top-level
568 ;; headings only), and the full document view. Pressing `TAB` while the
569 ;; point is at a heading will cycle through levels of visibility for the
570 ;; subtree: completely folded, visible children, and fully visible.
571 ;; Note that mixing hash and underline style headings will give undesired
572 ;; results.
574 ;;; Customization:
576 ;; Although no configuration is *necessary* there are a few things
577 ;; that can be customized. The `M-x customize-mode` command
578 ;; provides an interface to all of the possible customizations:
580 ;; * `markdown-command' - the command used to run Markdown (default:
581 ;; `markdown`). This variable may be customized to pass
582 ;; command-line options to your Markdown processor of choice.
584 ;; * `markdown-command-needs-filename' - set to `t' if
585 ;; `markdown-command' does not accept standard input (default:
586 ;; `nil'). When `nil', `markdown-mode' will pass the Markdown
587 ;; content to `markdown-command' using standard input (`stdin`).
588 ;; When set to `t', `markdown-mode' will pass the name of the file
589 ;; as the final command-line argument to `markdown-command'. Note
590 ;; that in the latter case, you will only be able to run
591 ;; `markdown-command' from buffers which are visiting a file.
593 ;; * `markdown-open-command' - the command used for calling a standalone
594 ;; Markdown previewer which is capable of opening Markdown source files
595 ;; directly (default: `nil'). This command will be called
596 ;; with a single argument, the filename of the current buffer.
597 ;; A representative program is the Mac app [Marked 2][], a
598 ;; live-updating Markdown previewer which can be [called from a
599 ;; simple shell script](https://jblevins.org/log/marked-2-command).
601 ;; * `markdown-hr-strings' - list of strings to use when inserting
602 ;; horizontal rules. Different strings will not be distinguished
603 ;; when converted to HTML--they will all be converted to
604 ;; `<hr/>`--but they may add visual distinction and style to plain
605 ;; text documents. To maintain some notion of promotion and
606 ;; demotion, keep these sorted from largest to smallest.
608 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
609 ;; underscores when inserting bold text instead of two asterisks
610 ;; (default: `nil').
612 ;; * `markdown-italic-underscore' - set to a non-nil value to use
613 ;; underscores when inserting italic text instead of asterisks
614 ;; (default: `nil').
616 ;; * `markdown-asymmetric-header' - set to a non-nil value to use
617 ;; asymmetric header styling, placing header characters only on
618 ;; the left of headers (default: `nil').
620 ;; * `markdown-header-scaling' - set to a non-nil value to use
621 ;; a variable-pitch font for headings where the size corresponds
622 ;; to the level of the heading (default: `nil').
624 ;; * `markdown-header-scaling-values' - list of scaling values,
625 ;; relative to baseline, for headers of levels one through six,
626 ;; used when `markdown-header-scaling' is non-nil
627 ;; (default: `(2.0 1.7 1.4 1.1 1.0 1.0)`).
629 ;; * `markdown-list-indent-width' - depth of indentation for lists
630 ;; when inserting, promoting, and demoting list items (default: 4).
632 ;; * `markdown-indent-function' - the function to use for automatic
633 ;; indentation (default: `markdown-indent-line').
635 ;; * `markdown-indent-on-enter' - Set to a non-nil value to
636 ;; automatically indent new lines when `RET' is pressed.
637 ;; Set to `indent-and-new-item' to additionally continue lists
638 ;; when `RET' is pressed (default: `t').
640 ;; * `markdown-enable-wiki-links' - syntax highlighting for wiki
641 ;; links (default: `nil'). Set this to a non-nil value to turn on
642 ;; wiki link support by default. Wiki link support can be toggled
643 ;; later using the function `markdown-toggle-wiki-links'."
645 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
646 ;; treat aliased wiki links like `[[link text|PageName]]`
647 ;; (default: `t'). When set to nil, they will be treated as
648 ;; `[[PageName|link text]]'.
650 ;; * `markdown-uri-types' - a list of protocol schemes (e.g., "http")
651 ;; for URIs that `markdown-mode' should highlight.
653 ;; * `markdown-enable-math' - font lock for inline and display LaTeX
654 ;; math expressions (default: `nil'). Set this to `t' to turn on
655 ;; math support by default. Math support can be toggled
656 ;; interactively later using `C-c C-x C-e`
657 ;; (`markdown-toggle-math').
659 ;; * `markdown-css-paths' - CSS files to link to in XHTML output
660 ;; (default: `nil`).
662 ;; * `markdown-content-type' - when set to a nonempty string, an
663 ;; `http-equiv` attribute will be included in the XHTML `<head>`
664 ;; block (default: `""`). If needed, the suggested values are
665 ;; `application/xhtml+xml` or `text/html`. See also:
666 ;; `markdown-coding-system'.
668 ;; * `markdown-coding-system' - used for specifying the character
669 ;; set identifier in the `http-equiv` attribute when included
670 ;; (default: `nil'). See `markdown-content-type', which must
671 ;; be set before this variable has any effect. When set to `nil',
672 ;; `buffer-file-coding-system' will be used to automatically
673 ;; determine the coding system string (falling back to
674 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
675 ;; and `iso-latin-1'.
677 ;; * `markdown-xhtml-header-content' - additional content to include
678 ;; in the XHTML `<head>` block (default: `""`).
680 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
681 ;; `markdown-mode' uses to determine whether the output of
682 ;; `markdown-command' is a standalone XHTML document or an XHTML
683 ;; fragment (default: `"^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"`). If
684 ;; this regular expression not matched in the first five lines of
685 ;; output, `markdown-mode' assumes the output is a fragment and
686 ;; adds a header and footer.
688 ;; * `markdown-link-space-sub-char' - a character to replace spaces
689 ;; when mapping wiki links to filenames (default: `"_"`).
690 ;; For example, use an underscore for compatibility with the
691 ;; Python Markdown WikiLinks extension. In `gfm-mode', this is
692 ;; set to `"-"` to conform with GitHub wiki links.
694 ;; * `markdown-reference-location' - where to insert reference
695 ;; definitions (default: `header`). The possible locations are
696 ;; the end of the document (`end`), after the current block
697 ;; (`immediately`), the end of the current subtree (`subtree'),
698 ;; or before the next header (`header`).
700 ;; * `markdown-footnote-location' - where to insert footnote text
701 ;; (default: `end`). The set of location options is the same as
702 ;; for `markdown-reference-location'.
704 ;; * `markdown-nested-imenu-heading-index' - Use nested imenu
705 ;; heading instead of a flat index (default: `t'). A nested
706 ;; index may provide more natural browsing from the menu, but a
707 ;; flat list may allow for faster keyboard navigation via tab
708 ;; completion.
710 ;; * `comment-auto-fill-only-comments' - variable is made
711 ;; buffer-local and set to `nil' by default. In programming
712 ;; language modes, when this variable is non-nil, only comments
713 ;; will be filled by auto-fill-mode. However, comments in
714 ;; Markdown documents are rare and the most users probably intend
715 ;; for the actual content of the document to be filled. Making
716 ;; this variable buffer-local allows `markdown-mode' to override
717 ;; the default behavior induced when the global variable is non-nil.
719 ;; * `markdown-gfm-additional-languages', - additional languages to
720 ;; make available, aside from those predefined in
721 ;; `markdown-gfm-recognized-languages', when inserting GFM code
722 ;; blocks (default: `nil`). Language strings must have be trimmed
723 ;; of whitespace and not contain any curly braces. They may be of
724 ;; arbitrary capitalization, though.
726 ;; * `markdown-gfm-use-electric-backquote' - use
727 ;; `markdown-electric-backquote' for interactive insertion of GFM
728 ;; code blocks when backquote is pressed three times (default: `t`).
730 ;; * `markdown-make-gfm-checkboxes-buttons' - Whether GitHub
731 ;; Flavored Markdown style task lists (checkboxes) should be
732 ;; turned into buttons that can be toggled with mouse-1 or RET. If
733 ;; non-nil (default), then buttons are enabled. This works in
734 ;; `markdown-mode' as well as `gfm-mode'.
736 ;; * `markdown-hide-urls' - Determines whether URL and reference
737 ;; labels are hidden for inline and reference links (default: `nil').
738 ;; When non-nil, inline links will appear in the buffer as
739 ;; `[link](∞)` instead of
740 ;; `[link](http://perhaps.a/very/long/url/)`. To change the
741 ;; placeholder (composition) character used, set the variable
742 ;; `markdown-url-compose-char'. URL hiding can be toggled
743 ;; interactively using `C-c C-x C-l` (`markdown-toggle-url-hiding')
744 ;; or from the Markdown | Links & Images menu.
746 ;; * `markdown-hide-markup' - Determines whether all possible markup
747 ;; is hidden or otherwise beautified (default: `nil'). The actual
748 ;; buffer text remains unchanged, but the display will be altered.
749 ;; Brackets and URLs for links will be hidden, asterisks and
750 ;; underscores for italic and bold text will be hidden, text
751 ;; bullets for unordered lists will be replaced by Unicode
752 ;; bullets, and so on. Since this includes URLs and reference
753 ;; labels, when non-nil this setting supersedes `markdown-hide-urls'.
754 ;; Markup hiding can be toggled using `C-c C-x C-m`
755 ;; (`markdown-toggle-markup-hiding') or from the Markdown | Show &
756 ;; Hide menu.
758 ;; Unicode bullets are used to replace ASCII list item markers.
759 ;; The list of characters used, in order of list level, can be
760 ;; specified by setting the variable `markdown-list-item-bullets'.
761 ;; The placeholder characters used to replace other markup can
762 ;; be changed by customizing the corresponding variables:
763 ;; `markdown-blockquote-display-char',
764 ;; `markdown-hr-display-char', and
765 ;; `markdown-definition-display-char'.
767 ;; * `markdown-fontify-code-blocks-natively' - Whether to fontify
768 ;; code in code blocks using the native major mode. This only
769 ;; works for fenced code blocks where the language is specified
770 ;; where we can automatically determine the appropriate mode to
771 ;; use. The language to mode mapping may be customized by setting
772 ;; the variable `markdown-code-lang-modes'. This can be toggled
773 ;; interactively by pressing `C-c C-x C-f`
774 ;; (`markdown-toggle-fontify-code-blocks-natively').
776 ;; * `markdown-gfm-uppercase-checkbox' - When non-nil, complete GFM
777 ;; task list items with `[X]` instead of `[x]` (default: `nil').
778 ;; This is useful for compatibility with `org-mode', which doesn't
779 ;; recognize the lowercase variant.
781 ;; Additionally, the faces used for syntax highlighting can be modified to
782 ;; your liking by issuing `M-x customize-group RET markdown-faces`
783 ;; or by using the "Markdown Faces" link at the bottom of the mode
784 ;; customization screen.
786 ;; [Marked 2]: https://itunes.apple.com/us/app/marked-2/id890031187?mt=12&uo=4&at=11l5Vs&ct=mm
788 ;;; Extensions:
790 ;; Besides supporting the basic Markdown syntax, Markdown Mode also
791 ;; includes syntax highlighting for `[[Wiki Links]]`. This can be
792 ;; enabled by setting `markdown-enable-wiki-links' to a non-nil value.
793 ;; Wiki links may be followed by pressing `C-c C-o` when the point
794 ;; is at a wiki link. Use `M-p` and `M-n` to quickly jump to the
795 ;; previous and next links (including links of other types).
796 ;; Aliased or piped wiki links of the form `[[link text|PageName]]`
797 ;; are also supported. Since some wikis reverse these components, set
798 ;; `markdown-wiki-link-alias-first' to nil to treat them as
799 ;; `[[PageName|link text]]`. If `markdown-wiki-link-fontify-missing'
800 ;; is also non-nil, Markdown Mode will highlight wiki links with
801 ;; missing target file in a different color. By default, Markdown
802 ;; Mode only searches for target files in the current directory.
803 ;; Search in subdirectories can be enabled by setting
804 ;; `markdown-wiki-link-search-subdirectories' to a non-nil value.
805 ;; Sequential parent directory search (as in [Ikiwiki][]) can be
806 ;; enabled by setting `markdown-wiki-link-search-parent-directories'
807 ;; to a non-nil value.
809 ;; [Ikiwiki]: https://ikiwiki.info
811 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
812 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
813 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
814 ;; You can do this either by using `M-x customize-group markdown`
815 ;; or by placing the following in your `.emacs` file:
817 ;; ``` Lisp
818 ;; (setq markdown-command "markdown | smartypants")
819 ;; ```
821 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
823 ;; Syntax highlighting for mathematical expressions written
824 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
825 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
826 ;; either via customize or by placing `(setq markdown-enable-math t)`
827 ;; in `.emacs`, and then restarting Emacs or calling
828 ;; `markdown-reload-extensions'.
830 ;;; GitHub Flavored Markdown (GFM):
832 ;; A [GitHub Flavored Markdown][GFM] mode, `gfm-mode', is also
833 ;; available. The GitHub implementation differs slightly from
834 ;; standard Markdown in that it supports things like different
835 ;; behavior for underscores inside of words, automatic linking of
836 ;; URLs, strikethrough text, and fenced code blocks with an optional
837 ;; language keyword.
839 ;; The GFM-specific features above apply to `README.md` files, wiki
840 ;; pages, and other Markdown-formatted files in repositories on
841 ;; GitHub. GitHub also enables [additional features][GFM comments] for
842 ;; writing on the site (for issues, pull requests, messages, etc.)
843 ;; that are further extensions of GFM. These features include task
844 ;; lists (checkboxes), newlines corresponding to hard line breaks,
845 ;; auto-linked references to issues and commits, wiki links, and so
846 ;; on. To make matters more confusing, although task lists are not
847 ;; part of [GFM proper][GFM], [since 2014][] they are rendered (in a
848 ;; read-only fashion) in all Markdown documents in repositories on the
849 ;; site. These additional extensions are supported to varying degrees
850 ;; by `markdown-mode' and `gfm-mode' as described below.
852 ;; * **URL autolinking:** Both `markdown-mode' and `gfm-mode' support
853 ;; highlighting of URLs without angle brackets.
855 ;; * **Multiple underscores in words:** You must enable `gfm-mode' to
856 ;; toggle support for underscores inside of words. In this mode
857 ;; variable names such as `a_test_variable` will not trigger
858 ;; emphasis (italics).
860 ;; * **Fenced code blocks:** Code blocks quoted with backquotes, with
861 ;; optional programming language keywords, are highlighted in
862 ;; both `markdown-mode' and `gfm-mode'. They can be inserted with
863 ;; `C-c C-s C`. If there is an active region, the text in the
864 ;; region will be placed inside the code block. You will be
865 ;; prompted for the name of the language, but may press enter to
866 ;; continue without naming a language.
868 ;; * **Strikethrough:** Strikethrough text is supported in both
869 ;; `markdown-mode' and `gfm-mode'. It can be inserted (and toggled)
870 ;; using `C-c C-s s`.
872 ;; * **Task lists:** GFM task lists will be rendered as checkboxes
873 ;; (Emacs buttons) in both `markdown-mode' and `gfm-mode' when
874 ;; `markdown-make-gfm-checkboxes-buttons' is set to a non-nil value
875 ;; (and it is set to t by default). These checkboxes can be
876 ;; toggled by clicking `mouse-1`, pressing `RET` over the button,
877 ;; or by pressing `C-c C-d` (`markdown-do`) with the point anywhere
878 ;; in the task list item.
880 ;; * **Wiki links:** Generic wiki links are supported in
881 ;; `markdown-mode', but in `gfm-mode' specifically they will be
882 ;; treated as they are on GitHub: spaces will be replaced by hyphens
883 ;; in filenames and the first letter of the filename will be
884 ;; capitalized. For example, `[[wiki link]]' will map to a file
885 ;; named `Wiki-link` with the same extension as the current file.
886 ;; If a file with this name does not exist in the current directory,
887 ;; the first match in a subdirectory, if any, will be used instead.
889 ;; * **Newlines:** Neither `markdown-mode' nor `gfm-mode' do anything
890 ;; specifically with respect to newline behavior. If you use
891 ;; `gfm-mode' mostly to write text for comments or issues on the
892 ;; GitHub site--where newlines are significant and correspond to
893 ;; hard line breaks--then you may want to enable `visual-line-mode'
894 ;; for line wrapping in buffers. You can do this with a
895 ;; `gfm-mode-hook' as follows:
897 ;; ``` Lisp
898 ;; ;; Use visual-line-mode in gfm-mode
899 ;; (defun my-gfm-mode-hook ()
900 ;; (visual-line-mode 1))
901 ;; (add-hook 'gfm-mode-hook 'my-gfm-mode-hook)
902 ;; ```
904 ;; * **Preview:** GFM-specific preview can be powered by setting
905 ;; `markdown-command' to use [Docter][]. This may also be
906 ;; configured to work with [Marked 2][] for `markdown-open-command'.
908 ;; [GFM]: http://github.github.com/github-flavored-markdown/
909 ;; [GFM comments]: https://help.github.com/articles/writing-on-github/
910 ;; [since 2014]: https://github.com/blog/1825-task-lists-in-all-markdown-documents
911 ;; [Docter]: https://github.com/alampros/Docter
913 ;;; Acknowledgments:
915 ;; markdown-mode has benefited greatly from the efforts of the many
916 ;; volunteers who have sent patches, test cases, bug reports,
917 ;; suggestions, helped with packaging, etc. Thank you for your
918 ;; contributions! See the [contributors graph][contrib] for details.
920 ;; [contrib]: https://github.com/jrblevin/markdown-mode/graphs/contributors
922 ;;; Bugs:
924 ;; markdown-mode is developed and tested primarily for compatibility
925 ;; with GNU Emacs 24.3 and later. If you find any bugs in
926 ;; markdown-mode, please construct a test case or a patch and open a
927 ;; ticket on the [GitHub issue tracker][issues]. See the
928 ;; contributing guidelines in `CONTRIBUTING.md` for details on
929 ;; creating pull requests.
931 ;; [issues]: https://github.com/jrblevin/markdown-mode/issues
933 ;;; History:
935 ;; markdown-mode was written and is maintained by Jason Blevins. The
936 ;; first version was released on May 24, 2007.
938 ;; * 2007-05-24: [Version 1.1][]
939 ;; * 2007-05-25: [Version 1.2][]
940 ;; * 2007-06-05: [Version 1.3][]
941 ;; * 2007-06-29: [Version 1.4][]
942 ;; * 2007-10-11: [Version 1.5][]
943 ;; * 2008-06-04: [Version 1.6][]
944 ;; * 2009-10-01: [Version 1.7][]
945 ;; * 2011-08-12: [Version 1.8][]
946 ;; * 2011-08-15: [Version 1.8.1][]
947 ;; * 2013-01-25: [Version 1.9][]
948 ;; * 2013-03-24: [Version 2.0][]
949 ;; * 2016-01-09: [Version 2.1][]
950 ;; * 2017-05-26: [Version 2.2][]
951 ;; * 2017-08-31: [Version 2.3][]
953 ;; [Version 1.1]: https://jblevins.org/projects/markdown-mode/rev-1-1
954 ;; [Version 1.2]: https://jblevins.org/projects/markdown-mode/rev-1-2
955 ;; [Version 1.3]: https://jblevins.org/projects/markdown-mode/rev-1-3
956 ;; [Version 1.4]: https://jblevins.org/projects/markdown-mode/rev-1-4
957 ;; [Version 1.5]: https://jblevins.org/projects/markdown-mode/rev-1-5
958 ;; [Version 1.6]: https://jblevins.org/projects/markdown-mode/rev-1-6
959 ;; [Version 1.7]: https://jblevins.org/projects/markdown-mode/rev-1-7
960 ;; [Version 1.8]: https://jblevins.org/projects/markdown-mode/rev-1-8
961 ;; [Version 1.8.1]: https://jblevins.org/projects/markdown-mode/rev-1-8-1
962 ;; [Version 1.9]: https://jblevins.org/projects/markdown-mode/rev-1-9
963 ;; [Version 2.0]: https://jblevins.org/projects/markdown-mode/rev-2-0
964 ;; [Version 2.1]: https://jblevins.org/projects/markdown-mode/rev-2-1
965 ;; [Version 2.2]: https://jblevins.org/projects/markdown-mode/rev-2-2
966 ;; [Version 2.3]: https://jblevins.org/projects/markdown-mode/rev-2-3
969 ;;; Code:
971 (require 'easymenu)
972 (require 'outline)
973 (require 'thingatpt)
974 (require 'cl-lib)
975 (require 'url-parse)
976 (require 'button)
977 (require 'color)
979 (defvar jit-lock-start)
980 (defvar jit-lock-end)
981 (defvar flyspell-generic-check-word-predicate)
983 (declare-function eww-open-file "eww")
984 (declare-function url-path-and-query "url-parse")
987 ;;; Constants =================================================================
989 (defconst markdown-mode-version "2.3"
990 "Markdown mode version number.")
992 (defconst markdown-output-buffer-name "*markdown-output*"
993 "Name of temporary buffer for markdown command output.")
995 (defconst markdown-sub-superscript-display
996 '(((raise -0.3) (height 0.7)) ; subscript
997 ((raise 0.3) (height 0.7))) ; superscript
998 "Parameters for sub- and superscript formatting.")
1001 ;;; Global Variables ==========================================================
1003 (defvar markdown-reference-label-history nil
1004 "History of used reference labels.")
1006 (defvar markdown-live-preview-mode nil
1007 "Sentinel variable for command `markdown-live-preview-mode'.")
1009 (defvar markdown-gfm-language-history nil
1010 "History list of languages used in the current buffer in GFM code blocks.")
1013 ;;; Customizable Variables ====================================================
1015 (defvar markdown-mode-hook nil
1016 "Hook run when entering Markdown mode.")
1018 (defvar markdown-before-export-hook nil
1019 "Hook run before running Markdown to export XHTML output.
1020 The hook may modify the buffer, which will be restored to it's
1021 original state after exporting is complete.")
1023 (defvar markdown-after-export-hook nil
1024 "Hook run after XHTML output has been saved.
1025 Any changes to the output buffer made by this hook will be saved.")
1027 (defgroup markdown nil
1028 "Major mode for editing text files in Markdown format."
1029 :prefix "markdown-"
1030 :group 'wp
1031 :link '(url-link "https://jblevins.org/projects/markdown-mode/"))
1033 (defcustom markdown-command "markdown"
1034 "Command to run markdown."
1035 :group 'markdown
1036 :type 'string)
1038 (defcustom markdown-command-needs-filename nil
1039 "Set to non-nil if `markdown-command' does not accept input from stdin.
1040 Instead, it will be passed a filename as the final command line
1041 option. As a result, you will only be able to run Markdown from
1042 buffers which are visiting a file."
1043 :group 'markdown
1044 :type 'boolean)
1046 (defcustom markdown-open-command nil
1047 "Command used for opening Markdown files directly.
1048 For example, a standalone Markdown previewer. This command will
1049 be called with a single argument: the filename of the current
1050 buffer."
1051 :group 'markdown
1052 :type '(choice file (const :tag "None" nil)))
1054 (defcustom markdown-hr-strings
1055 '("-------------------------------------------------------------------------------"
1056 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
1057 "---------------------------------------"
1058 "* * * * * * * * * * * * * * * * * * * *"
1059 "---------"
1060 "* * * * *")
1061 "Strings to use when inserting horizontal rules.
1062 The first string in the list will be the default when inserting a
1063 horizontal rule. Strings should be listed in decreasing order of
1064 prominence (as in headings from level one to six) for use with
1065 promotion and demotion functions."
1066 :group 'markdown
1067 :type '(repeat string))
1069 (defcustom markdown-bold-underscore nil
1070 "Use two underscores when inserting bold text instead of two asterisks."
1071 :group 'markdown
1072 :type 'boolean)
1074 (defcustom markdown-italic-underscore nil
1075 "Use underscores when inserting italic text instead of asterisks."
1076 :group 'markdown
1077 :type 'boolean)
1079 (defcustom markdown-asymmetric-header nil
1080 "Determines if atx header style will be asymmetric.
1081 Set to a non-nil value to use asymmetric header styling, placing
1082 header markup only at the beginning of the line. By default,
1083 balanced markup will be inserted at the beginning and end of the
1084 line around the header title."
1085 :group 'markdown
1086 :type 'boolean)
1088 (defcustom markdown-indent-function 'markdown-indent-line
1089 "Function to use to indent."
1090 :group 'markdown
1091 :type 'function)
1093 (defcustom markdown-indent-on-enter t
1094 "Determines indentation behavior when pressing \\[newline].
1095 Possible settings are nil, t, and 'indent-and-new-item.
1097 When non-nil, pressing \\[newline] will call `newline-and-indent'
1098 to indent the following line according to the context using
1099 `markdown-indent-function'. In this case, note that
1100 \\[electric-newline-and-maybe-indent] can still be used to insert
1101 a newline without indentation.
1103 When set to 'indent-and-new-item and the point is in a list item
1104 when \\[newline] is pressed, the list will be continued on the next
1105 line, where a new item will be inserted.
1107 When set to nil, simply call `newline' as usual. In this case,
1108 you can still indent lines using \\[markdown-cycle] and continue
1109 lists with \\[markdown-insert-list-item].
1111 Note that this assumes the variable `electric-indent-mode' is
1112 non-nil (enabled). When it is *disabled*, the behavior of
1113 \\[newline] and `\\[electric-newline-and-maybe-indent]' are
1114 reversed."
1115 :group 'markdown
1116 :type '(choice (const :tag "Don't automatically indent" nil)
1117 (const :tag "Automatically indent" t)
1118 (const :tag "Automatically indent and insert new list items" indent-and-new-item)))
1120 (defcustom markdown-enable-wiki-links nil
1121 "Syntax highlighting for wiki links.
1122 Set this to a non-nil value to turn on wiki link support by default.
1123 Support can be toggled later using the `markdown-toggle-wiki-links'
1124 function or \\[markdown-toggle-wiki-links]."
1125 :group 'markdown
1126 :type 'boolean
1127 :safe 'booleanp
1128 :package-version '(markdown-mode . "2.2"))
1130 (defcustom markdown-wiki-link-alias-first t
1131 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
1132 Otherwise, they will be treated as [[PageName|alias text]]."
1133 :group 'markdown
1134 :type 'boolean
1135 :safe 'booleanp)
1137 (defcustom markdown-wiki-link-search-subdirectories nil
1138 "When non-nil, search for wiki link targets in subdirectories.
1139 This is the default search behavior for GitHub and is
1140 automatically set to t in `gfm-mode'."
1141 :group 'markdown
1142 :type 'boolean
1143 :safe 'booleanp
1144 :package-version '(markdown-mode . "2.2"))
1146 (defcustom markdown-wiki-link-search-parent-directories nil
1147 "When non-nil, search for wiki link targets in parent directories.
1148 This is the default search behavior of Ikiwiki."
1149 :group 'markdown
1150 :type 'boolean
1151 :safe 'booleanp
1152 :package-version '(markdown-mode . "2.2"))
1154 (defcustom markdown-wiki-link-fontify-missing nil
1155 "When non-nil, change wiki link face according to existence of target files.
1156 This is expensive because it requires checking for the file each time the buffer
1157 changes or the user switches windows. It is disabled by default because it may
1158 cause lag when typing on slower machines."
1159 :group 'markdown
1160 :type 'boolean
1161 :safe 'booleanp
1162 :package-version '(markdown-mode . "2.2"))
1164 (defcustom markdown-uri-types
1165 '("acap" "cid" "data" "dav" "fax" "file" "ftp"
1166 "gopher" "http" "https" "imap" "ldap" "mailto"
1167 "mid" "message" "modem" "news" "nfs" "nntp"
1168 "pop" "prospero" "rtsp" "service" "sip" "tel"
1169 "telnet" "tip" "urn" "vemmi" "wais")
1170 "Link types for syntax highlighting of URIs."
1171 :group 'markdown
1172 :type '(repeat (string :tag "URI scheme")))
1174 (defcustom markdown-url-compose-char
1175 (cond
1176 ((char-displayable-p ?∞) ?∞)
1177 ((char-displayable-p ?…) ?…)
1178 (t ?#))
1179 "Placeholder character for hidden URLs.
1180 Depending on your font, some good choices are …, ⋯, #, ∞, ★, and ⚓."
1181 :type 'character
1182 :safe 'characterp
1183 :package-version '(markdown-mode . "2.3"))
1185 (defcustom markdown-blockquote-display-char
1186 (cond
1187 ((char-displayable-p ?▌) "▌")
1188 ((char-displayable-p ?┃) "┃")
1189 ((char-displayable-p ?│) "│")
1190 ((char-displayable-p ?|) "|")
1191 (t ">"))
1192 "Character for hiding blockquote markup."
1193 :type 'string
1194 :safe 'stringp
1195 :package-version '(markdown-mode . "2.3"))
1197 (defcustom markdown-hr-display-char
1198 (cond ((char-displayable-p ?─) ?─)
1199 ((char-displayable-p ?━) ?━)
1200 (t ?-))
1201 "Character for hiding horizontal rule markup."
1202 :type 'character
1203 :safe 'characterp
1204 :package-version '(markdown-mode . "2.3"))
1206 (defcustom markdown-definition-display-char
1207 (cond ((char-displayable-p ?⁘) ?⁘)
1208 ((char-displayable-p ?⁙) ?⁙)
1209 ((char-displayable-p ?≡) ?≡)
1210 ((char-displayable-p ?⌑) ?⌑)
1211 ((char-displayable-p ?◊) ?◊)
1212 (t nil))
1213 "Character for replacing definition list markup."
1214 :type 'character
1215 :safe 'characterp
1216 :package-version '(markdown-mode . "2.3"))
1218 (defcustom markdown-enable-math nil
1219 "Syntax highlighting for inline LaTeX and itex expressions.
1220 Set this to a non-nil value to turn on math support by default.
1221 Math support can be enabled, disabled, or toggled later using
1222 `markdown-toggle-math' or \\[markdown-toggle-math]."
1223 :group 'markdown
1224 :type 'boolean
1225 :safe 'booleanp)
1226 (make-variable-buffer-local 'markdown-enable-math)
1228 (defcustom markdown-css-paths nil
1229 "URL of CSS file to link to in the output XHTML."
1230 :group 'markdown
1231 :type 'list)
1233 (defcustom markdown-content-type ""
1234 "Content type string for the http-equiv header in XHTML output.
1235 When set to a non-empty string, insert the http-equiv attribute.
1236 Otherwise, this attribute is omitted."
1237 :group 'markdown
1238 :type 'string)
1240 (defcustom markdown-coding-system nil
1241 "Character set string for the http-equiv header in XHTML output.
1242 Defaults to `buffer-file-coding-system' (and falling back to
1243 `iso-8859-1' when not available). Common settings are `utf-8'
1244 and `iso-latin-1'. Use `list-coding-systems' for more choices."
1245 :group 'markdown
1246 :type 'coding-system)
1248 (defcustom markdown-xhtml-header-content ""
1249 "Additional content to include in the XHTML <head> block."
1250 :group 'markdown
1251 :type 'string)
1253 (defcustom markdown-xhtml-standalone-regexp
1254 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
1255 "Regexp indicating whether `markdown-command' output is standalone XHTML."
1256 :group 'markdown
1257 :type 'regexp)
1259 (defcustom markdown-link-space-sub-char "_"
1260 "Character to use instead of spaces when mapping wiki links to filenames."
1261 :group 'markdown
1262 :type 'string)
1264 (defcustom markdown-reference-location 'header
1265 "Position where new reference definitions are inserted in the document."
1266 :group 'markdown
1267 :type '(choice (const :tag "At the end of the document" end)
1268 (const :tag "Immediately after the current block" immediately)
1269 (const :tag "At the end of the subtree" subtree)
1270 (const :tag "Before next header" header)))
1272 (defcustom markdown-footnote-location 'end
1273 "Position where new footnotes are inserted in the document."
1274 :group 'markdown
1275 :type '(choice (const :tag "At the end of the document" end)
1276 (const :tag "Immediately after the current block" immediately)
1277 (const :tag "At the end of the subtree" subtree)
1278 (const :tag "Before next header" header)))
1280 (defcustom markdown-unordered-list-item-prefix " * "
1281 "String inserted before unordered list items."
1282 :group 'markdown
1283 :type 'string)
1285 (defcustom markdown-nested-imenu-heading-index t
1286 "Use nested or flat imenu heading index.
1287 A nested index may provide more natural browsing from the menu,
1288 but a flat list may allow for faster keyboard navigation via tab
1289 completion."
1290 :group 'markdown
1291 :type 'boolean
1292 :safe 'booleanp
1293 :package-version '(markdown-mode . "2.2"))
1295 (defcustom markdown-make-gfm-checkboxes-buttons t
1296 "When non-nil, make GFM checkboxes into buttons."
1297 :group 'markdown
1298 :type 'boolean)
1300 (defcustom markdown-use-pandoc-style-yaml-metadata nil
1301 "When non-nil, allow YAML metadata anywhere in the document."
1302 :group 'markdown
1303 :type 'boolean)
1305 (defcustom markdown-split-window-direction 'any
1306 "Preference for splitting windows for static and live preview.
1307 The default value is 'any, which instructs Emacs to use
1308 `split-window-sensibly' to automatically choose how to split
1309 windows based on the values of `split-width-threshold' and
1310 `split-height-threshold' and the available windows. To force
1311 vertically split (left and right) windows, set this to 'vertical
1312 or 'right. To force horizontally split (top and bottom) windows,
1313 set this to 'horizontal or 'below."
1314 :group 'markdown
1315 :type '(choice (const :tag "Automatic" any)
1316 (const :tag "Right (vertical)" right)
1317 (const :tag "Below (horizontal)" below))
1318 :package-version '(markdown-mode . "2.2"))
1320 (defcustom markdown-live-preview-window-function
1321 'markdown-live-preview-window-eww
1322 "Function to display preview of Markdown output within Emacs.
1323 Function must update the buffer containing the preview and return
1324 the buffer."
1325 :group 'markdown
1326 :type 'function)
1328 (defcustom markdown-live-preview-delete-export 'delete-on-destroy
1329 "Delete exported HTML file when using `markdown-live-preview-export'.
1330 If set to 'delete-on-export, delete on every export. When set to
1331 'delete-on-destroy delete when quitting from command
1332 `markdown-live-preview-mode'. Never delete if set to nil."
1333 :group 'markdown
1334 :type '(choice
1335 (const :tag "Delete on every export" delete-on-export)
1336 (const :tag "Delete when quitting live preview" delete-on-destroy)
1337 (const :tag "Never delete" nil)))
1339 (defcustom markdown-list-indent-width 4
1340 "Depth of indentation for markdown lists.
1341 Used in `markdown-demote-list-item' and
1342 `markdown-promote-list-item'."
1343 :group 'markdown
1344 :type 'integer)
1346 (defcustom markdown-enable-prefix-prompts t
1347 "Display prompts for certain prefix commands.
1348 Set to nil to disable these prompts."
1349 :group 'markdown
1350 :type 'boolean
1351 :safe 'booleanp
1352 :package-version '(markdown-mode . "2.3"))
1354 (defcustom markdown-gfm-additional-languages nil
1355 "Extra languages made available when inserting GFM code blocks.
1356 Language strings must have be trimmed of whitespace and not
1357 contain any curly braces. They may be of arbitrary
1358 capitalization, though."
1359 :group 'markdown
1360 :type '(repeat (string :validate markdown-validate-language-string)))
1362 (defcustom markdown-gfm-use-electric-backquote t
1363 "Use `markdown-electric-backquote' when backquote is hit three times."
1364 :group 'markdown
1365 :type 'boolean)
1367 (defcustom markdown-gfm-downcase-languages t
1368 "If non-nil, downcase suggested languages.
1369 This applies to insertions done with
1370 `markdown-electric-backquote'."
1371 :group 'markdown
1372 :type 'boolean)
1374 (defcustom markdown-gfm-uppercase-checkbox nil
1375 "If non-nil, use [X] for completed checkboxes, [x] otherwise."
1376 :group 'markdown
1377 :type 'boolean
1378 :safe 'booleanp)
1380 (defcustom markdown-hide-urls nil
1381 "Hide URLs of inline links and reference tags of reference links.
1382 Such URLs will be replaced by a single customizable
1383 character (∞), or `markdown-url-compose-char', but are still part
1384 of the buffer. Links can be edited interactively with
1385 \\[markdown-insert-link] or, for example, by deleting the final
1386 parenthesis to remove the invisibility property. You can also
1387 hover your mouse pointer over the link text to see the URL.
1388 Set this to a non-nil value to turn this feature on by default.
1389 You can interactively set the value of this variable by calling
1390 `markdown-toggle-url-hiding', pressing \\[markdown-toggle-url-hiding],
1391 or from the menu Markdown > Links & Images menu."
1392 :group 'markdown
1393 :type 'boolean
1394 :safe 'booleanp
1395 :package-version '(markdown-mode . "2.3"))
1396 (make-variable-buffer-local 'markdown-hide-urls)
1399 ;;; Regular Expressions =======================================================
1401 (defconst markdown-regex-comment-start
1402 "<!--"
1403 "Regular expression matches HTML comment opening.")
1405 (defconst markdown-regex-comment-end
1406 "--[ \t]*>"
1407 "Regular expression matches HTML comment closing.")
1409 (defconst markdown-regex-link-inline
1410 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)\\((\\)\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?\\()\\)"
1411 "Regular expression for a [text](file) or an image link ![text](file).
1412 Group 1 matches the leading exclamation point (optional).
1413 Group 2 matches the opening square bracket.
1414 Group 3 matches the text inside the square brackets.
1415 Group 4 matches the closing square bracket.
1416 Group 5 matches the opening parenthesis.
1417 Group 6 matches the URL.
1418 Group 7 matches the title (optional).
1419 Group 8 matches the closing parenthesis.")
1421 (defconst markdown-regex-link-reference
1422 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)[ ]?\\(\\[\\)\\([^]]*?\\)\\(\\]\\)"
1423 "Regular expression for a reference link [text][id].
1424 Group 1 matches the leading exclamation point (optional).
1425 Group 2 matches the opening square bracket for the link text.
1426 Group 3 matches the text inside the square brackets.
1427 Group 4 matches the closing square bracket for the link text.
1428 Group 5 matches the opening square bracket for the reference label.
1429 Group 6 matches the reference label.
1430 Group 7 matches the closing square bracket for the reference label.")
1432 (defconst markdown-regex-reference-definition
1433 "^ \\{0,3\\}\\(\\[\\)\\([^]\n]+?\\)\\(\\]\\)\\(:\\)\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
1434 "Regular expression for a reference definition.
1435 Group 1 matches the opening square bracket.
1436 Group 2 matches the reference label.
1437 Group 3 matches the closing square bracket.
1438 Group 4 matches the colon.
1439 Group 5 matches the URL.
1440 Group 6 matches the title attribute (optional).")
1442 (defconst markdown-regex-footnote
1443 "\\(\\[\\^\\)\\(.+?\\)\\(\\]\\)"
1444 "Regular expression for a footnote marker [^fn].
1445 Group 1 matches the opening square bracket and carat.
1446 Group 2 matches only the label, without the surrounding markup.
1447 Group 3 matches the closing square bracket.")
1449 (defconst markdown-regex-header
1450 "^\\(?:\\([^\r\n\t -].*\\)\n\\(?:\\(=+\\)\\|\\(-+\\)\\)\\|\\(#+[ \t]+\\)\\(.*?\\)\\([ \t]*#*\\)\\)$"
1451 "Regexp identifying Markdown headings.
1452 Group 1 matches the text of a setext heading.
1453 Group 2 matches the underline of a level-1 setext heading.
1454 Group 3 matches the underline of a level-2 setext heading.
1455 Group 4 matches the opening hash marks of an atx heading and whitespace.
1456 Group 5 matches the text, without surrounding whitespace, of an atx heading.
1457 Group 6 matches the closing whitespace and hash marks of an atx heading.")
1459 (defconst markdown-regex-header-setext
1460 "^\\([^\r\n\t -].*\\)\n\\(=+\\|-+\\)$"
1461 "Regular expression for generic setext-style (underline) headers.")
1463 (defconst markdown-regex-header-atx
1464 "^\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1465 "Regular expression for generic atx-style (hash mark) headers.")
1467 (defconst markdown-regex-hr
1468 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1469 "Regular expression for matching Markdown horizontal rules.")
1471 (defconst markdown-regex-code
1472 "\\(?:\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(?:.\\|\n[^\n]\\)*?[^`]\\)\\(\\2\\)\\)\\(?:[^`]\\|\\'\\)"
1473 "Regular expression for matching inline code fragments.
1475 Group 1 matches the entire code fragment including the backquotes.
1476 Group 2 matches the opening backquotes.
1477 Group 3 matches the code fragment itself, without backquotes.
1478 Group 4 matches the closing backquotes.
1480 The leading, unnumbered group ensures that the leading backquote
1481 character is not escaped.
1482 The last group, also unnumbered, requires that the character
1483 following the code fragment is not a backquote.
1484 Note that \\(?:.\\|\n[^\n]\\) matches any character, including newlines,
1485 but not two newlines in a row.")
1487 (defconst markdown-regex-kbd
1488 "\\(<kbd>\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(</kbd>\\)"
1489 "Regular expression for matching <kbd> tags.
1490 Groups 1 and 3 match the opening and closing tags.
1491 Group 2 matches the key sequence.")
1493 (defconst markdown-regex-gfm-code-block-open
1494 "^[[:blank:]]*\\(```\\)\\([[:blank:]]*{?[[:blank:]]*\\)\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$"
1495 "Regular expression matching opening of GFM code blocks.
1496 Group 1 matches the opening three backquotes and any following whitespace.
1497 Group 2 matches the opening brace (optional) and surrounding whitespace.
1498 Group 3 matches the language identifier (optional).
1499 Group 4 matches the info string (optional).
1500 Group 5 matches the closing brace (optional), whitespace, and newline.
1501 Groups need to agree with `markdown-regex-tilde-fence-begin'.")
1503 (defconst markdown-regex-gfm-code-block-close
1504 "^[[:blank:]]*\\(```\\)\\(\\s *?\\)$"
1505 "Regular expression matching closing of GFM code blocks.
1506 Group 1 matches the closing three backquotes.
1507 Group 2 matches any whitespace and the final newline.")
1509 (defconst markdown-regex-pre
1510 "^\\( \\|\t\\).*$"
1511 "Regular expression for matching preformatted text sections.")
1513 (defconst markdown-regex-list
1514 "^\\([ \t]*\\)\\([0-9#]+\\.\\|[\\*\\+:-]\\)\\([ \t]+\\)"
1515 "Regular expression for matching list items.")
1517 (defconst markdown-regex-bold
1518 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1519 "Regular expression for matching bold text.
1520 Group 1 matches the character before the opening asterisk or
1521 underscore, if any, ensuring that it is not a backslash escape.
1522 Group 2 matches the entire expression, including delimiters.
1523 Groups 3 and 5 matches the opening and closing delimiters.
1524 Group 4 matches the text inside the delimiters.")
1526 (defconst markdown-regex-italic
1527 "\\(?:^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1528 "Regular expression for matching italic text.
1529 The leading unnumbered matches the character before the opening
1530 asterisk or underscore, if any, ensuring that it is not a
1531 backslash escape.
1532 Group 1 matches the entire expression, including delimiters.
1533 Groups 2 and 4 matches the opening and closing delimiters.
1534 Group 3 matches the text inside the delimiters.")
1536 (defconst markdown-regex-strike-through
1537 "\\(^\\|[^\\]\\)\\(\\(~~\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(~~\\)\\)"
1538 "Regular expression for matching strike-through text.
1539 Group 1 matches the character before the opening tilde, if any,
1540 ensuring that it is not a backslash escape.
1541 Group 2 matches the entire expression, including delimiters.
1542 Groups 3 and 5 matches the opening and closing delimiters.
1543 Group 4 matches the text inside the delimiters.")
1545 (defconst markdown-regex-gfm-italic
1546 "\\(?:^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\2\\|[^ ]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1547 "Regular expression for matching italic text in GitHub Flavored Markdown.
1548 Underscores in words are not treated as special.
1549 Group 1 matches the entire expression, including delimiters.
1550 Groups 2 and 4 matches the opening and closing delimiters.
1551 Group 3 matches the text inside the delimiters.")
1553 (defconst markdown-regex-blockquote
1554 "^[ \t]*\\([A-Z]?>\\)\\([ \t]*\\)\\(.*\\)$"
1555 "Regular expression for matching blockquote lines.
1556 Also accounts for a potential capital letter preceding the angle
1557 bracket, for use with Leanpub blocks (asides, warnings, info
1558 blocks, etc.).
1559 Group 1 matches the leading angle bracket.
1560 Group 2 matches the separating whitespace.
1561 Group 3 matches the text.")
1563 (defconst markdown-regex-line-break
1564 "[^ \n\t][ \t]*\\( \\)$"
1565 "Regular expression for matching line breaks.")
1567 (defconst markdown-regex-wiki-link
1568 "\\(?:^\\|[^\\]\\)\\(\\(\\[\\[\\)\\([^]|]+\\)\\(?:\\(|\\)\\([^]]+\\)\\)?\\(\\]\\]\\)\\)"
1569 "Regular expression for matching wiki links.
1570 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1571 wiki links of the form [[PageName|link text]].
1572 The meanings of the first and second components depend
1573 on the value of `markdown-wiki-link-alias-first'.
1575 Group 1 matches the entire link.
1576 Group 2 matches the opening square brackets.
1577 Group 3 matches the first component of the wiki link.
1578 Group 4 matches the pipe separator, when present.
1579 Group 5 matches the second component of the wiki link, when present.
1580 Group 6 matches the closing square brackets.")
1582 (defconst markdown-regex-uri
1583 (concat "\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+\\)")
1584 "Regular expression for matching inline URIs.")
1586 (defconst markdown-regex-angle-uri
1587 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1588 "Regular expression for matching inline URIs in angle brackets.")
1590 (defconst markdown-regex-email
1591 "<\\(\\(?:\\sw\\|\\s_\\|\\s.\\)+@\\(?:\\sw\\|\\s_\\|\\s.\\)+\\)>"
1592 "Regular expression for matching inline email addresses.")
1594 (defsubst markdown-make-regex-link-generic ()
1595 "Make regular expression for matching any recognized link."
1596 (concat "\\(?:" markdown-regex-link-inline
1597 (when markdown-enable-wiki-links
1598 (concat "\\|" markdown-regex-wiki-link))
1599 "\\|" markdown-regex-link-reference
1600 "\\|" markdown-regex-angle-uri "\\)"))
1602 (defconst markdown-regex-gfm-checkbox
1603 " \\(\\[[ xX]\\]\\) "
1604 "Regular expression for matching GFM checkboxes.
1605 Group 1 matches the text to become a button.")
1607 (defconst markdown-regex-block-separator
1608 "\n[\n\t\f ]*\n"
1609 "Regular expression for matching block boundaries.")
1611 (defconst markdown-regex-block-separator-noindent
1612 (concat "\\(\\`\\|\\(" markdown-regex-block-separator "\\)[^\n\t\f ]\\)")
1613 "Regexp for block separators before lines with no indentation.")
1615 (defconst markdown-regex-math-inline-single
1616 "\\(?:^\\|[^\\]\\)\\(\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\)"
1617 "Regular expression for itex $..$ math mode expressions.
1618 Groups 1 and 3 match the opening and closing dollar signs.
1619 Group 3 matches the mathematical expression contained within.")
1621 (defconst markdown-regex-math-inline-double
1622 "\\(?:^\\|[^\\]\\)\\(\\$\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\$\\)"
1623 "Regular expression for itex $$..$$ math mode expressions.
1624 Groups 1 and 3 match opening and closing dollar signs.
1625 Group 3 matches the mathematical expression contained within.")
1627 (defconst markdown-regex-math-display
1628 "^\\(\\\\\\[\\)\\(\\(?:.\\|\n\\)*?\\)?\\(\\\\\\]\\)$"
1629 "Regular expression for itex \[..\] display mode expressions.
1630 Groups 1 and 3 match the opening and closing delimiters.
1631 Group 2 matches the mathematical expression contained within.")
1633 (defsubst markdown-make-tilde-fence-regex (num-tildes &optional end-of-line)
1634 "Return regexp matching a tilde code fence at least NUM-TILDES long.
1635 END-OF-LINE is the regexp construct to indicate end of line; $ if
1636 missing."
1637 (format "%s%d%s%s" "^[[:blank:]]*\\([~]\\{" num-tildes ",\\}\\)"
1638 (or end-of-line "$")))
1640 (defconst markdown-regex-tilde-fence-begin
1641 (markdown-make-tilde-fence-regex
1642 3 "\\([[:blank:]]*{?\\)[[:blank:]]*\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$")
1643 "Regular expression for matching tilde-fenced code blocks.
1644 Group 1 matches the opening tildes.
1645 Group 2 matches (optional) opening brace and surrounding whitespace.
1646 Group 3 matches the language identifier (optional).
1647 Group 4 matches the info string (optional).
1648 Group 5 matches the closing brace (optional) and any surrounding whitespace.
1649 Groups need to agree with `markdown-regex-gfm-code-block-open'.")
1651 (defconst markdown-regex-declarative-metadata
1652 "^\\([[:alpha:]][[:alpha:] _-]*?\\)\\([:=][ \t]*\\)\\(.*\\)$"
1653 "Regular expression for matching declarative metadata statements.
1654 This matches MultiMarkdown metadata as well as YAML and TOML
1655 assignments such as the following:
1657 variable: value
1661 variable = value")
1663 (defconst markdown-regex-pandoc-metadata
1664 "^\\(%\\)\\([ \t]*\\)\\(.*\\(?:\n[ \t]+.*\\)*\\)"
1665 "Regular expression for matching Pandoc metadata.")
1667 (defconst markdown-regex-yaml-metadata-border
1668 "\\(-\\{3\\}\\)$"
1669 "Regular expression for matching YAML metadata.")
1671 (defconst markdown-regex-yaml-pandoc-metadata-end-border
1672 "^\\(\\.\\{3\\}\\|\\-\\{3\\}\\)$"
1673 "Regular expression for matching YAML metadata end borders.")
1675 (defsubst markdown-get-yaml-metadata-start-border ()
1676 "Return YAML metadata start border depending upon whether Pandoc is used."
1677 (concat
1678 (if markdown-use-pandoc-style-yaml-metadata "^" "\\`")
1679 markdown-regex-yaml-metadata-border))
1681 (defsubst markdown-get-yaml-metadata-end-border (_)
1682 "Return YAML metadata end border depending upon whether Pandoc is used."
1683 (if markdown-use-pandoc-style-yaml-metadata
1684 markdown-regex-yaml-pandoc-metadata-end-border
1685 markdown-regex-yaml-metadata-border))
1687 (defconst markdown-regex-inline-attributes
1688 "[ \t]*\\({:?\\)[ \t]*\\(\\(#[[:alpha:]_.:-]+\\|\\.[[:alpha:]_.:-]+\\|\\w+=['\"]?[^\n'\"]*['\"]?\\),?[ \t]*\\)+\\(}\\)[ \t]*$"
1689 "Regular expression for matching inline identifiers or attribute lists.
1690 Compatible with Pandoc, Python Markdown, PHP Markdown Extra, and Leanpub.")
1692 (defconst markdown-regex-leanpub-sections
1693 (concat
1694 "^\\({\\)\\("
1695 (regexp-opt '("frontmatter" "mainmatter" "backmatter" "appendix" "pagebreak"))
1696 "\\)\\(}\\)[ \t]*\n")
1697 "Regular expression for Leanpub section markers and related syntax.")
1699 (defconst markdown-regex-sub-superscript
1700 "\\(?:^\\|[^\\~^]\\)\\(\\([~^]\\)\\([[:alnum:]]+\\)\\(\\2\\)\\)"
1701 "The regular expression matching a sub- or superscript.
1702 The leading un-numbered group matches the character before the
1703 opening tilde or carat, if any, ensuring that it is not a
1704 backslash escape, carat, or tilde.
1705 Group 1 matches the entire expression, including markup.
1706 Group 2 matches the opening markup--a tilde or carat.
1707 Group 3 matches the text inside the delimiters.
1708 Group 4 matches the closing markup--a tilde or carat.")
1710 (defconst markdown-regex-include
1711 "^\\(<<\\)\\(?:\\(\\[\\)\\(.*\\)\\(\\]\\)\\)?\\(?:\\((\\)\\(.*\\)\\()\\)\\)?\\(?:\\({\\)\\(.*\\)\\(}\\)\\)?$"
1712 "Regular expression matching common forms of include syntax.
1713 Marked 2, Leanpub, and other processors support some of these forms:
1715 <<[sections/section1.md]
1716 <<(folder/filename)
1717 <<[Code title](folder/filename)
1718 <<{folder/raw_file.html}
1720 Group 1 matches the opening two angle brackets.
1721 Groups 2-4 match the opening square bracket, the text inside,
1722 and the closing square bracket, respectively.
1723 Groups 5-7 match the opening parenthesis, the text inside, and
1724 the closing parenthesis.
1725 Groups 8-10 match the opening brace, the text inside, and the brace.")
1727 (defconst markdown-regex-pandoc-inline-footnote
1728 "\\(\\^\\)\\(\\[\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(\\]\\)"
1729 "Regular expression for Pandoc inline footnote^[footnote text].
1730 Group 1 matches the opening caret.
1731 Group 2 matches the opening square bracket.
1732 Group 3 matches the footnote text, without the surrounding markup.
1733 Group 4 matches the closing square bracket.")
1736 ;;; Syntax ====================================================================
1738 (defsubst markdown-in-comment-p (&optional pos)
1739 "Return non-nil if POS is in a comment.
1740 If POS is not given, use point instead."
1741 (nth 4 (syntax-ppss pos)))
1743 (defun markdown-syntax-propertize-extend-region (start end)
1744 "Extend START to END region to include an entire block of text.
1745 This helps improve syntax analysis for block constructs.
1746 Returns a cons (NEW-START . NEW-END) or nil if no adjustment should be made.
1747 Function is called repeatedly until it returns nil. For details, see
1748 `syntax-propertize-extend-region-functions'."
1749 (save-match-data
1750 (save-excursion
1751 (let* ((new-start (progn (goto-char start)
1752 (skip-chars-forward "\n")
1753 (if (re-search-backward "\n\n" nil t)
1754 (min start (match-end 0))
1755 (point-min))))
1756 (new-end (progn (goto-char end)
1757 (skip-chars-backward "\n")
1758 (if (re-search-forward "\n\n" nil t)
1759 (max end (match-beginning 0))
1760 (point-max))))
1761 (code-match (markdown-code-block-at-pos new-start))
1762 (new-start (or (and code-match (cl-first code-match)) new-start))
1763 (code-match (and (< end (point-max)) (markdown-code-block-at-pos end)))
1764 (new-end (or (and code-match (cl-second code-match)) new-end)))
1765 (unless (and (eq new-start start) (eq new-end end))
1766 (cons new-start (min new-end (point-max))))))))
1768 (defun markdown-font-lock-extend-region-function (start end _)
1769 "Used in `jit-lock-after-change-extend-region-functions'.
1770 Delegates to `markdown-syntax-propertize-extend-region'. START
1771 and END are the previous region to refontify."
1772 (let ((res (markdown-syntax-propertize-extend-region start end)))
1773 (when res
1774 ;; syntax-propertize-function is not called when character at
1775 ;; (point-max) is deleted, but font-lock-extend-region-functions
1776 ;; are called. Force a syntax property update in that case.
1777 (when (= end (point-max))
1778 ;; This function is called in a buffer modification hook.
1779 ;; `markdown-syntax-propertize' doesn't save the match data,
1780 ;; so we have to do it here.
1781 (save-match-data
1782 (markdown-syntax-propertize (car res) (cdr res))))
1783 (setq jit-lock-start (car res)
1784 jit-lock-end (cdr res)))))
1786 (defun markdown-syntax-propertize-pre-blocks (start end)
1787 "Match preformatted text blocks from START to END."
1788 (save-excursion
1789 (goto-char start)
1790 (let ((levels (markdown-calculate-list-levels))
1791 indent pre-regexp close-regexp open close)
1792 (while (and (< (point) end) (not close))
1793 ;; Search for a region with sufficient indentation
1794 (if (null levels)
1795 (setq indent 1)
1796 (setq indent (1+ (length levels))))
1797 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1798 (setq close-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1800 (cond
1801 ;; If not at the beginning of a line, move forward
1802 ((not (bolp)) (forward-line))
1803 ;; Move past blank lines
1804 ((markdown-cur-line-blank) (forward-line))
1805 ;; At headers and horizontal rules, reset levels
1806 ((markdown-new-baseline) (forward-line) (setq levels nil))
1807 ;; If the current line has sufficient indentation, mark out pre block
1808 ;; The opening should be preceded by a blank line.
1809 ((and (looking-at pre-regexp)
1810 (markdown-prev-line-blank-p))
1811 (setq open (match-beginning 0))
1812 (while (and (or (looking-at-p pre-regexp) (markdown-cur-line-blank))
1813 (not (eobp)))
1814 (forward-line))
1815 (skip-syntax-backward "-")
1816 (setq close (point)))
1817 ;; If current line has a list marker, update levels, move to end of block
1818 ((looking-at markdown-regex-list)
1819 (setq levels (markdown-update-list-levels
1820 (match-string 2) (current-indentation) levels))
1821 (markdown-end-of-text-block))
1822 ;; If this is the end of the indentation level, adjust levels accordingly.
1823 ;; Only match end of indentation level if levels is not the empty list.
1824 ((and (car levels) (looking-at-p close-regexp))
1825 (setq levels (markdown-update-list-levels
1826 nil (current-indentation) levels))
1827 (markdown-end-of-text-block))
1828 (t (markdown-end-of-text-block))))
1830 (when (and open close)
1831 ;; Set text property data
1832 (put-text-property open close 'markdown-pre (list open close))
1833 ;; Recursively search again
1834 (markdown-syntax-propertize-pre-blocks (point) end)))))
1836 (defconst markdown-fenced-block-pairs
1837 `(((,markdown-regex-tilde-fence-begin markdown-tilde-fence-begin)
1838 (markdown-make-tilde-fence-regex markdown-tilde-fence-end)
1839 markdown-fenced-code)
1840 ((markdown-get-yaml-metadata-start-border markdown-yaml-metadata-begin)
1841 (markdown-get-yaml-metadata-end-border markdown-yaml-metadata-end)
1842 markdown-yaml-metadata-section)
1843 ((,markdown-regex-gfm-code-block-open markdown-gfm-block-begin)
1844 (,markdown-regex-gfm-code-block-close markdown-gfm-block-end)
1845 markdown-gfm-code))
1846 "Mapping of regular expressions to \"fenced-block\" constructs.
1847 These constructs are distinguished by having a distinctive start
1848 and end pattern, both of which take up an entire line of text,
1849 but no special pattern to identify text within the fenced
1850 blocks (unlike blockquotes and indented-code sections).
1852 Each element within this list takes the form:
1854 ((START-REGEX-OR-FUN START-PROPERTY)
1855 (END-REGEX-OR-FUN END-PROPERTY)
1856 MIDDLE-PROPERTY)
1858 Each *-REGEX-OR-FUN element can be a regular expression as a string, or a
1859 function which evaluates to same. Functions for START-REGEX-OR-FUN accept no
1860 arguments, but functions for END-REGEX-OR-FUN accept a single numerical argument
1861 which is the length of the first group of the START-REGEX-OR-FUN match, which
1862 can be ignored if unnecessary. `markdown-maybe-funcall-regexp' is used to
1863 evaluate these into \"real\" regexps.
1865 The *-PROPERTY elements are the text properties applied to each part of the
1866 block construct when it is matched using
1867 `markdown-syntax-propertize-fenced-block-constructs'. START-PROPERTY is applied
1868 to the text matching START-REGEX-OR-FUN, END-PROPERTY to END-REGEX-OR-FUN, and
1869 MIDDLE-PROPERTY to the text in between the two. The value of *-PROPERTY is the
1870 `match-data' when the regexp was matched to the text. In the case of
1871 MIDDLE-PROPERTY, the value is a false match data of the form '(begin end), with
1872 begin and end set to the edges of the \"middle\" text. This makes fontification
1873 easier.")
1875 (defun markdown-text-property-at-point (prop)
1876 (get-text-property (point) prop))
1878 (defsubst markdown-maybe-funcall-regexp (object &optional arg)
1879 (cond ((functionp object)
1880 (if arg (funcall object arg) (funcall object)))
1881 ((stringp object) object)
1882 (t (error "Object cannot be turned into regex"))))
1884 (defsubst markdown-get-start-fence-regexp ()
1885 "Return regexp to find all \"start\" sections of fenced block constructs.
1886 Which construct is actually contained in the match must be found separately."
1887 (mapconcat
1888 #'identity
1889 (mapcar (lambda (entry) (markdown-maybe-funcall-regexp (caar entry)))
1890 markdown-fenced-block-pairs)
1891 "\\|"))
1893 (defun markdown-get-fenced-block-begin-properties ()
1894 (cl-mapcar (lambda (entry) (cl-cadar entry)) markdown-fenced-block-pairs))
1896 (defun markdown-get-fenced-block-end-properties ()
1897 (cl-mapcar (lambda (entry) (cl-cadadr entry)) markdown-fenced-block-pairs))
1899 (defun markdown-get-fenced-block-middle-properties ()
1900 (cl-mapcar #'cl-third markdown-fenced-block-pairs))
1902 (defun markdown-find-previous-prop (prop &optional lim)
1903 "Find previous place where property PROP is non-nil, up to LIM.
1904 Return a cons of (pos . property). pos is point if point contains
1905 non-nil PROP."
1906 (let ((res
1907 (if (get-text-property (point) prop) (point)
1908 (previous-single-property-change
1909 (point) prop nil (or lim (point-min))))))
1910 (when (and (not (get-text-property res prop))
1911 (> res (point-min))
1912 (get-text-property (1- res) prop))
1913 (cl-decf res))
1914 (when (and res (get-text-property res prop)) (cons res prop))))
1916 (defun markdown-find-next-prop (prop &optional lim)
1917 "Find next place where property PROP is non-nil, up to LIM.
1918 Return a cons of (POS . PROPERTY) where POS is point if point
1919 contains non-nil PROP."
1920 (let ((res
1921 (if (get-text-property (point) prop) (point)
1922 (next-single-property-change
1923 (point) prop nil (or lim (point-max))))))
1924 (when (and res (get-text-property res prop)) (cons res prop))))
1926 (defun markdown-min-of-seq (map-fn seq)
1927 "Apply MAP-FN to SEQ and return element of SEQ with minimum value of MAP-FN."
1928 (cl-loop for el in seq
1929 with min = 1.0e+INF ; infinity
1930 with min-el = nil
1931 do (let ((res (funcall map-fn el)))
1932 (when (< res min)
1933 (setq min res)
1934 (setq min-el el)))
1935 finally return min-el))
1937 (defun markdown-max-of-seq (map-fn seq)
1938 "Apply MAP-FN to SEQ and return element of SEQ with maximum value of MAP-FN."
1939 (cl-loop for el in seq
1940 with max = -1.0e+INF ; negative infinity
1941 with max-el = nil
1942 do (let ((res (funcall map-fn el)))
1943 (when (and res (> res max))
1944 (setq max res)
1945 (setq max-el el)))
1946 finally return max-el))
1948 (defun markdown-find-previous-block ()
1949 "Find previous block.
1950 Detect whether `markdown-syntax-propertize-fenced-block-constructs' was
1951 unable to propertize the entire block, but was able to propertize the beginning
1952 of the block. If so, return a cons of (pos . property) where the beginning of
1953 the block was propertized."
1954 (let ((start-pt (point))
1955 (closest-open
1956 (markdown-max-of-seq
1957 #'car
1958 (cl-remove-if
1959 #'null
1960 (cl-mapcar
1961 #'markdown-find-previous-prop
1962 (markdown-get-fenced-block-begin-properties))))))
1963 (when closest-open
1964 (let* ((length-of-open-match
1965 (let ((match-d
1966 (get-text-property (car closest-open) (cdr closest-open))))
1967 (- (cl-fourth match-d) (cl-third match-d))))
1968 (end-regexp
1969 (markdown-maybe-funcall-regexp
1970 (cl-caadr
1971 (cl-find-if
1972 (lambda (entry) (eq (cl-cadar entry) (cdr closest-open)))
1973 markdown-fenced-block-pairs))
1974 length-of-open-match))
1975 (end-prop-loc
1976 (save-excursion
1977 (save-match-data
1978 (goto-char (car closest-open))
1979 (and (re-search-forward end-regexp start-pt t)
1980 (match-beginning 0))))))
1981 (and (not end-prop-loc) closest-open)))))
1983 (defun markdown-get-fenced-block-from-start (prop)
1984 "Return limits of an enclosing fenced block from its start, using PROP.
1985 Return value is a list usable as `match-data'."
1986 (catch 'no-rest-of-block
1987 (let* ((correct-entry
1988 (cl-find-if
1989 (lambda (entry) (eq (cl-cadar entry) prop))
1990 markdown-fenced-block-pairs))
1991 (begin-of-begin (cl-first (markdown-text-property-at-point prop)))
1992 (middle-prop (cl-third correct-entry))
1993 (end-prop (cl-cadadr correct-entry))
1994 (end-of-end
1995 (save-excursion
1996 (goto-char (match-end 0)) ; end of begin
1997 (unless (eobp) (forward-char))
1998 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
1999 (if (not mid-prop-v) ; no middle
2000 (progn
2001 ;; try to find end by advancing one
2002 (let ((end-prop-v
2003 (markdown-text-property-at-point end-prop)))
2004 (if end-prop-v (cl-second end-prop-v)
2005 (throw 'no-rest-of-block nil))))
2006 (set-match-data mid-prop-v)
2007 (goto-char (match-end 0)) ; end of middle
2008 (beginning-of-line) ; into end
2009 (cl-second (markdown-text-property-at-point end-prop)))))))
2010 (list begin-of-begin end-of-end))))
2012 (defun markdown-get-fenced-block-from-middle (prop)
2013 "Return limits of an enclosing fenced block from its middle, using PROP.
2014 Return value is a list usable as `match-data'."
2015 (let* ((correct-entry
2016 (cl-find-if
2017 (lambda (entry) (eq (cl-third entry) prop))
2018 markdown-fenced-block-pairs))
2019 (begin-prop (cl-cadar correct-entry))
2020 (begin-of-begin
2021 (save-excursion
2022 (goto-char (match-beginning 0))
2023 (unless (bobp) (forward-line -1))
2024 (beginning-of-line)
2025 (cl-first (markdown-text-property-at-point begin-prop))))
2026 (end-prop (cl-cadadr correct-entry))
2027 (end-of-end
2028 (save-excursion
2029 (goto-char (match-end 0))
2030 (beginning-of-line)
2031 (cl-second (markdown-text-property-at-point end-prop)))))
2032 (list begin-of-begin end-of-end)))
2034 (defun markdown-get-fenced-block-from-end (prop)
2035 "Return limits of an enclosing fenced block from its end, using PROP.
2036 Return value is a list usable as `match-data'."
2037 (let* ((correct-entry
2038 (cl-find-if
2039 (lambda (entry) (eq (cl-cadadr entry) prop))
2040 markdown-fenced-block-pairs))
2041 (end-of-end (cl-second (markdown-text-property-at-point prop)))
2042 (middle-prop (cl-third correct-entry))
2043 (begin-prop (cl-cadar correct-entry))
2044 (begin-of-begin
2045 (save-excursion
2046 (goto-char (match-beginning 0)) ; beginning of end
2047 (unless (bobp) (backward-char)) ; into middle
2048 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
2049 (if (not mid-prop-v)
2050 (progn
2051 (beginning-of-line)
2052 (cl-first (markdown-text-property-at-point begin-prop)))
2053 (set-match-data mid-prop-v)
2054 (goto-char (match-beginning 0)) ; beginning of middle
2055 (unless (bobp) (forward-line -1)) ; into beginning
2056 (beginning-of-line)
2057 (cl-first (markdown-text-property-at-point begin-prop)))))))
2058 (list begin-of-begin end-of-end)))
2060 (defun markdown-get-enclosing-fenced-block-construct (&optional pos)
2061 "Get \"fake\" match data for block enclosing POS.
2062 Returns fake match data which encloses the start, middle, and end
2063 of the block construct enclosing POS, if it exists. Used in
2064 `markdown-code-block-at-pos'."
2065 (save-excursion
2066 (when pos (goto-char pos))
2067 (beginning-of-line)
2068 (car
2069 (cl-remove-if
2070 #'null
2071 (cl-mapcar
2072 (lambda (fun-and-prop)
2073 (cl-destructuring-bind (fun prop) fun-and-prop
2074 (when prop
2075 (save-match-data
2076 (set-match-data (markdown-text-property-at-point prop))
2077 (funcall fun prop)))))
2078 `((markdown-get-fenced-block-from-start
2079 ,(cl-find-if
2080 #'markdown-text-property-at-point
2081 (markdown-get-fenced-block-begin-properties)))
2082 (markdown-get-fenced-block-from-middle
2083 ,(cl-find-if
2084 #'markdown-text-property-at-point
2085 (markdown-get-fenced-block-middle-properties)))
2086 (markdown-get-fenced-block-from-end
2087 ,(cl-find-if
2088 #'markdown-text-property-at-point
2089 (markdown-get-fenced-block-end-properties)))))))))
2091 (defun markdown-propertize-end-match (reg end fence-spec middle-begin)
2092 "Get match for REG up to END, if exists, and propertize appropriately.
2093 FENCE-SPEC is an entry in `markdown-fenced-block-pairs' and
2094 MIDDLE-BEGIN is the start of the \"middle\" section of the block."
2095 (when (re-search-forward reg end t)
2096 (let ((close-begin (match-beginning 0)) ; Start of closing line.
2097 (close-end (match-end 0)) ; End of closing line.
2098 (close-data (match-data t))) ; Match data for closing line.
2099 ;; Propertize middle section of fenced block.
2100 (put-text-property middle-begin close-begin
2101 (cl-third fence-spec)
2102 (list middle-begin close-begin))
2103 ;; Propertize closing line of fenced block.
2104 (put-text-property close-begin close-end
2105 (cl-cadadr fence-spec) close-data))))
2107 (defun markdown-syntax-propertize-fenced-block-constructs (start end)
2108 "Propertize according to `markdown-fenced-block-pairs' from START to END.
2109 If unable to propertize an entire block (if the start of a block is within START
2110 and END, but the end of the block is not), propertize the start section of a
2111 block, then in a subsequent call propertize both middle and end by finding the
2112 start which was previously propertized."
2113 (let ((start-reg (markdown-get-start-fence-regexp)))
2114 (save-excursion
2115 (goto-char start)
2116 ;; start from previous unclosed block, if exists
2117 (let ((prev-begin-block (markdown-find-previous-block)))
2118 (when prev-begin-block
2119 (let* ((correct-entry
2120 (cl-find-if (lambda (entry)
2121 (eq (cdr prev-begin-block) (cl-cadar entry)))
2122 markdown-fenced-block-pairs))
2123 (enclosed-text-start (1+ (car prev-begin-block)))
2124 (start-length
2125 (save-excursion
2126 (goto-char (car prev-begin-block))
2127 (string-match
2128 (markdown-maybe-funcall-regexp
2129 (caar correct-entry))
2130 (buffer-substring
2131 (point-at-bol) (point-at-eol)))
2132 (- (match-end 1) (match-beginning 1))))
2133 (end-reg (markdown-maybe-funcall-regexp
2134 (cl-caadr correct-entry) start-length)))
2135 (markdown-propertize-end-match
2136 end-reg end correct-entry enclosed-text-start))))
2137 ;; find all new blocks within region
2138 (while (re-search-forward start-reg end t)
2139 ;; we assume the opening constructs take up (only) an entire line,
2140 ;; so we re-check the current line
2141 (let* ((cur-line (buffer-substring (point-at-bol) (point-at-eol)))
2142 ;; find entry in `markdown-fenced-block-pairs' corresponding
2143 ;; to regex which was matched
2144 (correct-entry
2145 (cl-find-if
2146 (lambda (fenced-pair)
2147 (string-match-p
2148 (markdown-maybe-funcall-regexp (caar fenced-pair))
2149 cur-line))
2150 markdown-fenced-block-pairs))
2151 (enclosed-text-start
2152 (save-excursion (1+ (point-at-eol))))
2153 (end-reg
2154 (markdown-maybe-funcall-regexp
2155 (cl-caadr correct-entry)
2156 (if (and (match-beginning 1) (match-end 1))
2157 (- (match-end 1) (match-beginning 1))
2158 0))))
2159 ;; get correct match data
2160 (save-excursion
2161 (beginning-of-line)
2162 (re-search-forward
2163 (markdown-maybe-funcall-regexp (caar correct-entry))
2164 (point-at-eol)))
2165 ;; mark starting, even if ending is outside of region
2166 (put-text-property (match-beginning 0) (match-end 0)
2167 (cl-cadar correct-entry) (match-data t))
2168 (markdown-propertize-end-match
2169 end-reg end correct-entry enclosed-text-start))))))
2171 (defun markdown-syntax-propertize-blockquotes (start end)
2172 "Match blockquotes from START to END."
2173 (save-excursion
2174 (goto-char start)
2175 (while (and (re-search-forward markdown-regex-blockquote end t)
2176 (not (markdown-code-block-at-pos (match-beginning 0))))
2177 (put-text-property (match-beginning 0) (match-end 0)
2178 'markdown-blockquote
2179 (match-data t)))))
2181 (defun markdown-syntax-propertize-hrs (start end)
2182 "Match horizontal rules from START to END."
2183 (save-excursion
2184 (goto-char start)
2185 (while (re-search-forward markdown-regex-hr end t)
2186 (unless (or (markdown-on-heading-p)
2187 (markdown-code-block-at-point-p))
2188 (put-text-property (match-beginning 0) (match-end 0)
2189 'markdown-hr
2190 (match-data t))))))
2192 (defun markdown-syntax-propertize-yaml-metadata (start end)
2193 (save-excursion
2194 (goto-char start)
2195 (cl-loop
2196 while (re-search-forward markdown-regex-declarative-metadata end t)
2197 do (when (get-text-property (match-beginning 0)
2198 'markdown-yaml-metadata-section)
2199 (put-text-property (match-beginning 1) (match-end 1)
2200 'markdown-metadata-key (match-data t))
2201 (put-text-property (match-beginning 2) (match-end 2)
2202 'markdown-metadata-markup (match-data t))
2203 (put-text-property (match-beginning 3) (match-end 3)
2204 'markdown-metadata-value (match-data t))))))
2206 (defun markdown-syntax-propertize-headings (start end)
2207 "Match headings of type SYMBOL with REGEX from START to END."
2208 (goto-char start)
2209 (while (re-search-forward markdown-regex-header end t)
2210 (unless (markdown-code-block-at-pos (match-beginning 0))
2211 (put-text-property
2212 (match-beginning 0) (match-end 0) 'markdown-heading
2213 (match-data t))
2214 (put-text-property
2215 (match-beginning 0) (match-end 0)
2216 (cond ((match-string-no-properties 2) 'markdown-heading-1-setext)
2217 ((match-string-no-properties 3) 'markdown-heading-2-setext)
2218 (t (let ((atx-level (length (markdown-trim-whitespace
2219 (match-string-no-properties 4)))))
2220 (intern (format "markdown-heading-%d-atx" atx-level)))))
2221 (match-data t)))))
2223 (defun markdown-syntax-propertize-comments (start end)
2224 "Match HTML comments from the START to END."
2225 (let* ((in-comment (markdown-in-comment-p)))
2226 (goto-char start)
2227 (cond
2228 ;; Comment start
2229 ((and (not in-comment)
2230 (re-search-forward markdown-regex-comment-start end t)
2231 (not (markdown-inline-code-at-point-p))
2232 (not (markdown-code-block-at-point-p)))
2233 (let ((open-beg (match-beginning 0)))
2234 (put-text-property open-beg (1+ open-beg)
2235 'syntax-table (string-to-syntax "<"))
2236 (markdown-syntax-propertize-comments
2237 (min (1+ (match-end 0)) end (point-max)) end)))
2238 ;; Comment end
2239 ((and in-comment
2240 (re-search-forward markdown-regex-comment-end end t))
2241 (put-text-property (1- (match-end 0)) (match-end 0)
2242 'syntax-table (string-to-syntax ">"))
2243 (markdown-syntax-propertize-comments
2244 (min (1+ (match-end 0)) end (point-max)) end))
2245 ;; Nothing found
2246 (t nil))))
2248 (defvar markdown--syntax-properties
2249 (list 'markdown-tilde-fence-begin nil
2250 'markdown-tilde-fence-end nil
2251 'markdown-fenced-code nil
2252 'markdown-yaml-metadata-begin nil
2253 'markdown-yaml-metadata-end nil
2254 'markdown-yaml-metadata-section nil
2255 'markdown-gfm-block-begin nil
2256 'markdown-gfm-block-end nil
2257 'markdown-gfm-code nil
2258 'markdown-pre nil
2259 'markdown-blockquote nil
2260 'markdown-hr nil
2261 'markdown-heading nil
2262 'markdown-heading-1-setext nil
2263 'markdown-heading-2-setext nil
2264 'markdown-heading-1-atx nil
2265 'markdown-heading-2-atx nil
2266 'markdown-heading-3-atx nil
2267 'markdown-heading-4-atx nil
2268 'markdown-heading-5-atx nil
2269 'markdown-heading-6-atx nil
2270 'markdown-metadata-key nil
2271 'markdown-metadata-value nil
2272 'markdown-metadata-markup nil)
2273 "Property list of all Markdown syntactic properties.")
2275 (defun markdown-syntax-propertize (start end)
2276 "Function used as `syntax-propertize-function'.
2277 START and END delimit region to propertize."
2278 (with-silent-modifications
2279 (save-excursion
2280 (remove-text-properties start end markdown--syntax-properties)
2281 (markdown-syntax-propertize-fenced-block-constructs start end)
2282 (markdown-syntax-propertize-yaml-metadata start end)
2283 (markdown-syntax-propertize-pre-blocks start end)
2284 (markdown-syntax-propertize-blockquotes start end)
2285 (markdown-syntax-propertize-headings start end)
2286 (markdown-syntax-propertize-hrs start end)
2287 (markdown-syntax-propertize-comments start end))))
2290 ;;; Markup Hiding
2292 (defconst markdown-markup-properties
2293 '(face markdown-markup-face invisible markdown-markup)
2294 "List of properties and values to apply to markup.")
2296 (defconst markdown-language-keyword-properties
2297 '(face markdown-language-keyword-face invisible markdown-markup)
2298 "List of properties and values to apply to code block language names.")
2300 (defconst markdown-language-info-properties
2301 '(face markdown-language-info-face invisible markdown-markup)
2302 "List of properties and values to apply to code block language info strings.")
2304 (defconst markdown-include-title-properties
2305 '(face markdown-link-title-face invisible markdown-markup)
2306 "List of properties and values to apply to included code titles.")
2308 (defconst markdown-inline-footnote-properties
2309 '(face nil display ((raise 0.2) (height 0.8)))
2310 "Properties to apply to footnote markers and inline footnotes.")
2312 (defcustom markdown-hide-markup nil
2313 "Determines whether markup in the buffer will be hidden.
2314 When set to nil, all markup is displayed in the buffer as it
2315 appears in the file. An exception is when `markdown-hide-urls'
2316 is non-nil.
2317 Set this to a non-nil value to turn this feature on by default.
2318 You can interactively toggle the value of this variable with
2319 `markdown-toggle-markup-hiding', \\[markdown-toggle-markup-hiding],
2320 or from the Markdown > Show & Hide menu.
2322 Markup hiding works by adding text properties to positions in the
2323 buffer---either the `invisible' property or the `display' property
2324 in cases where alternative glyphs are used (e.g., list bullets).
2325 This does not, however, affect printing or other output.
2326 Functions such as `htmlfontify-buffer' and `ps-print-buffer' will
2327 not honor these text properties. For printing, it would be better
2328 to first convert to HTML or PDF (e.g,. using Pandoc)."
2329 :group 'markdown
2330 :type 'boolean
2331 :safe 'booleanp
2332 :package-version '(markdown-mode . "2.3"))
2333 (make-variable-buffer-local 'markdown-hide-markup)
2335 (defun markdown-toggle-markup-hiding (&optional arg)
2336 "Toggle the display or hiding of markup.
2337 With a prefix argument ARG, enable markup hiding if ARG is positive,
2338 and disable it otherwise.
2339 See `markdown-hide-markup' for additional details."
2340 (interactive (list (or current-prefix-arg 'toggle)))
2341 (setq markdown-hide-markup
2342 (if (eq arg 'toggle)
2343 (not markdown-hide-markup)
2344 (> (prefix-numeric-value arg) 0)))
2345 (if markdown-hide-markup
2346 (progn (add-to-invisibility-spec 'markdown-markup)
2347 (message "markdown-mode markup hiding enabled"))
2348 (progn (remove-from-invisibility-spec 'markdown-markup)
2349 (message "markdown-mode markup hiding disabled")))
2350 (markdown-reload-extensions))
2353 ;;; Font Lock =================================================================
2355 (require 'font-lock)
2357 (defvar markdown-italic-face 'markdown-italic-face
2358 "Face name to use for italic text.")
2360 (defvar markdown-bold-face 'markdown-bold-face
2361 "Face name to use for bold text.")
2363 (defvar markdown-strike-through-face 'markdown-strike-through-face
2364 "Face name to use for strike-through text.")
2366 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
2367 "Face name to use as a base for header delimiters.")
2369 (defvar markdown-header-rule-face 'markdown-header-rule-face
2370 "Face name to use as a base for header rules.")
2372 (defvar markdown-header-face 'markdown-header-face
2373 "Face name to use as a base for headers.")
2375 (defvar markdown-header-face-1 'markdown-header-face-1
2376 "Face name to use for level-1 headers.")
2378 (defvar markdown-header-face-2 'markdown-header-face-2
2379 "Face name to use for level-2 headers.")
2381 (defvar markdown-header-face-3 'markdown-header-face-3
2382 "Face name to use for level-3 headers.")
2384 (defvar markdown-header-face-4 'markdown-header-face-4
2385 "Face name to use for level-4 headers.")
2387 (defvar markdown-header-face-5 'markdown-header-face-5
2388 "Face name to use for level-5 headers.")
2390 (defvar markdown-header-face-6 'markdown-header-face-6
2391 "Face name to use for level-6 headers.")
2393 (defvar markdown-inline-code-face 'markdown-inline-code-face
2394 "Face name to use for inline code.")
2396 (defvar markdown-list-face 'markdown-list-face
2397 "Face name to use for list markers.")
2399 (defvar markdown-blockquote-face 'markdown-blockquote-face
2400 "Face name to use for blockquote.")
2402 (defvar markdown-pre-face 'markdown-pre-face
2403 "Face name to use for preformatted text.")
2405 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
2406 "Face name to use for programming language identifiers.")
2408 (defvar markdown-language-info-face 'markdown-language-info-face
2409 "Face name to use for programming info strings.")
2411 (defvar markdown-link-face 'markdown-link-face
2412 "Face name to use for links.")
2414 (defvar markdown-missing-link-face 'markdown-missing-link-face
2415 "Face name to use for links where the linked file does not exist.")
2417 (defvar markdown-reference-face 'markdown-reference-face
2418 "Face name to use for reference.")
2420 (defvar markdown-footnote-marker-face 'markdown-footnote-marker-face
2421 "Face name to use for footnote markers.")
2423 (defvar markdown-url-face 'markdown-url-face
2424 "Face name to use for URLs.")
2426 (defvar markdown-link-title-face 'markdown-link-title-face
2427 "Face name to use for reference link titles.")
2429 (defvar markdown-line-break-face 'markdown-line-break-face
2430 "Face name to use for hard line breaks.")
2432 (defvar markdown-comment-face 'markdown-comment-face
2433 "Face name to use for HTML comments.")
2435 (defvar markdown-math-face 'markdown-math-face
2436 "Face name to use for LaTeX expressions.")
2438 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
2439 "Face name to use for metadata keys.")
2441 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
2442 "Face name to use for metadata values.")
2444 (defvar markdown-gfm-checkbox-face 'markdown-gfm-checkbox-face
2445 "Face name to use for GFM checkboxes.")
2447 (defvar markdown-highlight-face 'markdown-highlight-face
2448 "Face name to use for mouse highlighting.")
2450 (defvar markdown-markup-face 'markdown-markup-face
2451 "Face name to use for markup elements.")
2453 (defgroup markdown-faces nil
2454 "Faces used in Markdown Mode"
2455 :group 'markdown
2456 :group 'faces)
2458 (defface markdown-italic-face
2459 '((t (:inherit italic)))
2460 "Face for italic text."
2461 :group 'markdown-faces)
2463 (defface markdown-bold-face
2464 '((t (:inherit bold)))
2465 "Face for bold text."
2466 :group 'markdown-faces)
2468 (defface markdown-strike-through-face
2469 '((t (:strike-through t)))
2470 "Face for strike-through text."
2471 :group 'markdown-faces)
2473 (defface markdown-markup-face
2474 '((t (:inherit shadow :slant normal :weight normal)))
2475 "Face for markup elements."
2476 :group 'markdown-faces)
2478 (defface markdown-header-rule-face
2479 '((t (:inherit markdown-markup-face)))
2480 "Base face for headers rules."
2481 :group 'markdown-faces)
2483 (defface markdown-header-delimiter-face
2484 '((t (:inherit markdown-markup-face)))
2485 "Base face for headers hash delimiter."
2486 :group 'markdown-faces)
2488 (defface markdown-list-face
2489 '((t (:inherit markdown-markup-face)))
2490 "Face for list item markers."
2491 :group 'markdown-faces)
2493 (defface markdown-blockquote-face
2494 '((t (:inherit font-lock-doc-face)))
2495 "Face for blockquote sections."
2496 :group 'markdown-faces)
2498 (defface markdown-code-face
2499 (let* ((default-bg (or (face-background 'default) "unspecified-bg"))
2500 (light-bg (if (equal default-bg "unspecified-bg")
2501 "unspecified-bg"
2502 (color-darken-name default-bg 3)))
2503 (dark-bg (if (equal default-bg "unspecified-bg")
2504 "unspecified-bg"
2505 (color-lighten-name default-bg 3))))
2506 `((default :inherit fixed-pitch)
2507 (((type graphic) (class color) (background dark)) (:background ,dark-bg))
2508 (((type graphic) (class color) (background light)) (:background ,light-bg))))
2509 "Face for inline code, pre blocks, and fenced code blocks."
2510 :group 'markdown-faces)
2512 (defface markdown-code-face
2513 `((t (:inherit fixed-pitch)))
2514 "Face for inline code, pre blocks, and fenced code blocks."
2515 :group 'markdown-faces)
2517 (defface markdown-inline-code-face
2518 '((t (:inherit markdown-code-face font-lock-constant-face)))
2519 "Face for inline code."
2520 :group 'markdown-faces)
2522 (defface markdown-pre-face
2523 '((t (:inherit (markdown-code-face font-lock-constant-face))))
2524 "Face for preformatted text."
2525 :group 'markdown-faces)
2527 (defface markdown-language-keyword-face
2528 '((t (:inherit font-lock-type-face)))
2529 "Face for programming language identifiers."
2530 :group 'markdown-faces)
2532 (defface markdown-language-info-face
2533 '((t (:inherit font-lock-string-face)))
2534 "Face for programming language info strings."
2535 :group 'markdown-faces)
2537 (defface markdown-link-face
2538 '((t (:inherit link)))
2539 "Face for links."
2540 :group 'markdown-faces)
2542 (defface markdown-missing-link-face
2543 '((t (:inherit font-lock-warning-face)))
2544 "Face for missing links."
2545 :group 'markdown-faces)
2547 (defface markdown-reference-face
2548 '((t (:inherit markdown-markup-face)))
2549 "Face for link references."
2550 :group 'markdown-faces)
2552 (define-obsolete-face-alias 'markdown-footnote-face
2553 'markdown-footnote-marker-face "v2.3")
2555 (defface markdown-footnote-marker-face
2556 '((t (:inherit markdown-markup-face)))
2557 "Face for footnote markers."
2558 :group 'markdown-faces)
2560 (defface markdown-footnote-text-face
2561 '((t (:inherit font-lock-comment-face)))
2562 "Face for footnote text."
2563 :group 'markdown-faces)
2565 (defface markdown-url-face
2566 '((t (:inherit font-lock-string-face)))
2567 "Face for URLs that are part of markup.
2568 For example, this applies to URLs in inline links:
2569 [link text](http://example.com/)."
2570 :group 'markdown-faces)
2572 (defface markdown-plain-url-face
2573 '((t (:inherit markdown-link-face)))
2574 "Face for URLs that are also links.
2575 For example, this applies to plain angle bracket URLs:
2576 <http://example.com/>."
2577 :group 'markdown-faces)
2579 (defface markdown-link-title-face
2580 '((t (:inherit font-lock-comment-face)))
2581 "Face for reference link titles."
2582 :group 'markdown-faces)
2584 (defface markdown-line-break-face
2585 '((t (:inherit font-lock-constant-face :underline t)))
2586 "Face for hard line breaks."
2587 :group 'markdown-faces)
2589 (defface markdown-comment-face
2590 '((t (:inherit font-lock-comment-face)))
2591 "Face for HTML comments."
2592 :group 'markdown-faces)
2594 (defface markdown-math-face
2595 '((t (:inherit font-lock-string-face)))
2596 "Face for LaTeX expressions."
2597 :group 'markdown-faces)
2599 (defface markdown-metadata-key-face
2600 '((t (:inherit font-lock-variable-name-face)))
2601 "Face for metadata keys."
2602 :group 'markdown-faces)
2604 (defface markdown-metadata-value-face
2605 '((t (:inherit font-lock-string-face)))
2606 "Face for metadata values."
2607 :group 'markdown-faces)
2609 (defface markdown-gfm-checkbox-face
2610 '((t (:inherit font-lock-builtin-face)))
2611 "Face for GFM checkboxes."
2612 :group 'markdown-faces)
2614 (defface markdown-highlight-face
2615 '((t (:inherit highlight)))
2616 "Face for mouse highlighting."
2617 :group 'markdown-faces)
2619 (defface markdown-hr-face
2620 '((t (:inherit markdown-markup-face)))
2621 "Face for horizontal rules."
2622 :group 'markdown-faces)
2624 (defcustom markdown-header-scaling nil
2625 "Whether to use variable-height faces for headers.
2626 When non-nil, `markdown-header-face' will inherit from
2627 `variable-pitch' and the scaling values in
2628 `markdown-header-scaling-values' will be applied to
2629 headers of levels one through six respectively."
2630 :type 'boolean
2631 :initialize 'custom-initialize-default
2632 :set (lambda (symbol value)
2633 (set-default symbol value)
2634 (markdown-update-header-faces value))
2635 :group 'markdown-faces
2636 :package-version '(markdown-mode . "2.2"))
2638 (defcustom markdown-header-scaling-values
2639 '(2.0 1.7 1.4 1.1 1.0 1.0)
2640 "List of scaling values for headers of level one through six.
2641 Used when `markdown-header-scaling' is non-nil."
2642 :type 'list
2643 :initialize 'custom-initialize-default
2644 :set (lambda (symbol value)
2645 (set-default symbol value)
2646 (markdown-update-header-faces markdown-header-scaling value))
2647 :group 'markdown-faces)
2649 (defun markdown-make-header-faces ()
2650 "Build the faces used for Markdown headers."
2651 (let ((inherit-faces '(font-lock-function-name-face)))
2652 (when markdown-header-scaling
2653 (setq inherit-faces (cons 'variable-pitch inherit-faces)))
2654 (defface markdown-header-face
2655 `((t (:inherit ,inherit-faces :weight bold)))
2656 "Base face for headers."
2657 :group 'markdown-faces))
2658 (dotimes (num 6)
2659 (let* ((num1 (1+ num))
2660 (face-name (intern (format "markdown-header-face-%s" num1)))
2661 (scale (if markdown-header-scaling
2662 (float (nth num markdown-header-scaling-values))
2663 1.0)))
2664 (eval
2665 `(defface ,face-name
2666 '((t (:inherit markdown-header-face :height ,scale)))
2667 (format "Face for level %s headers.
2668 You probably don't want to customize this face directly. Instead
2669 you can customize the base face `markdown-header-face' or the
2670 variable-height variable `markdown-header-scaling'." ,num1)
2671 :group 'markdown-faces)))))
2673 (markdown-make-header-faces)
2675 (defun markdown-update-header-faces (&optional scaling scaling-values)
2676 "Update header faces, depending on if header SCALING is desired.
2677 If so, use given list of SCALING-VALUES relative to the baseline
2678 size of `markdown-header-face'."
2679 (dotimes (num 6)
2680 (let* ((face-name (intern (format "markdown-header-face-%s" (1+ num))))
2681 (scale (cond ((not scaling) 1.0)
2682 (scaling-values (float (nth num scaling-values)))
2683 (t (float (nth num markdown-header-scaling-values))))))
2684 (unless (get face-name 'saved-face) ; Don't update customized faces
2685 (set-face-attribute face-name nil :height scale)))))
2687 (defun markdown-syntactic-face (state)
2688 "Return font-lock face for characters with given STATE.
2689 See `font-lock-syntactic-face-function' for details."
2690 (let ((in-comment (nth 4 state)))
2691 (cond
2692 (in-comment 'markdown-comment-face)
2693 (t nil))))
2695 (defcustom markdown-list-item-bullets
2696 '("●" "◎" "○" "◆" "◇" "►" "•")
2697 "List of bullets to use for unordered lists.
2698 It can contain any number of symbols, which will be repeated.
2699 Depending on your font, some reasonable choices are:
2700 ♥ ● ◇ ✚ ✜ ☯ ◆ ♠ ♣ ♦ ❀ ◆ ◖ ▶ ► • ★ ▸."
2701 :group 'markdown
2702 :type '(repeat (string :tag "Bullet character"))
2703 :package-version '(markdown-mode . "2.3"))
2705 (defvar markdown-mode-font-lock-keywords-basic
2706 `((markdown-match-yaml-metadata-begin . ((1 markdown-markup-face)))
2707 (markdown-match-yaml-metadata-end . ((1 markdown-markup-face)))
2708 (markdown-match-yaml-metadata-key . ((1 markdown-metadata-key-face)
2709 (2 markdown-markup-face)
2710 (3 markdown-metadata-value-face)))
2711 (markdown-match-gfm-open-code-blocks . ((1 markdown-markup-properties)
2712 (2 markdown-markup-properties nil t)
2713 (3 markdown-language-keyword-properties nil t)
2714 (4 markdown-language-info-properties nil t)
2715 (5 markdown-markup-properties nil t)))
2716 (markdown-match-gfm-close-code-blocks . ((0 markdown-markup-properties)))
2717 (markdown-fontify-gfm-code-blocks)
2718 (markdown-match-fenced-start-code-block . ((1 markdown-markup-properties)
2719 (2 markdown-markup-properties nil t)
2720 (3 markdown-language-keyword-properties nil t)
2721 (4 markdown-language-info-properties nil t)
2722 (5 markdown-markup-properties nil t)))
2723 (markdown-match-fenced-end-code-block . ((0 markdown-markup-properties)))
2724 (markdown-fontify-fenced-code-blocks)
2725 (markdown-match-pre-blocks . ((0 markdown-pre-face)))
2726 (markdown-fontify-headings)
2727 (markdown-match-declarative-metadata . ((1 markdown-metadata-key-face)
2728 (2 markdown-markup-face)
2729 (3 markdown-metadata-value-face)))
2730 (markdown-match-pandoc-metadata . ((1 markdown-markup-face)
2731 (2 markdown-markup-face)
2732 (3 markdown-metadata-value-face)))
2733 (markdown-fontify-hrs)
2734 (markdown-match-code . ((1 markdown-markup-properties prepend)
2735 (2 markdown-inline-code-face prepend)
2736 (3 markdown-markup-properties prepend)))
2737 (,markdown-regex-kbd . ((1 markdown-markup-properties)
2738 (2 markdown-inline-code-face)
2739 (3 markdown-markup-properties)))
2740 (markdown-fontify-angle-uris)
2741 (,markdown-regex-email . 'markdown-plain-url-face)
2742 (markdown-fontify-list-items)
2743 (,markdown-regex-footnote . ((0 markdown-inline-footnote-properties)
2744 (1 markdown-markup-properties) ; [^
2745 (2 markdown-footnote-marker-face) ; label
2746 (3 markdown-markup-properties))) ; ]
2747 (,markdown-regex-pandoc-inline-footnote . ((0 markdown-inline-footnote-properties)
2748 (1 markdown-markup-properties) ; ^
2749 (2 markdown-markup-properties) ; [
2750 (3 'markdown-footnote-text-face) ; text
2751 (4 markdown-markup-properties))) ; ]
2752 (markdown-match-includes . ((1 markdown-markup-properties)
2753 (2 markdown-markup-properties nil t)
2754 (3 markdown-include-title-properties nil t)
2755 (4 markdown-markup-properties nil t)
2756 (5 markdown-markup-properties)
2757 (6 'markdown-url-face)
2758 (7 markdown-markup-properties)))
2759 (markdown-fontify-inline-links)
2760 (markdown-fontify-reference-links)
2761 (,markdown-regex-reference-definition . ((1 markdown-markup-face) ; [
2762 (2 markdown-reference-face) ; label
2763 (3 markdown-markup-face) ; ]
2764 (4 markdown-markup-face) ; :
2765 (5 markdown-url-face) ; url
2766 (6 markdown-link-title-face))) ; "title" (optional)
2767 (markdown-fontify-plain-uris)
2768 ;; Math mode $..$
2769 (markdown-match-math-single . ((1 markdown-markup-face prepend)
2770 (2 markdown-math-face append)
2771 (3 markdown-markup-face prepend)))
2772 ;; Math mode $$..$$
2773 (markdown-match-math-double . ((1 markdown-markup-face prepend)
2774 (2 markdown-math-face append)
2775 (3 markdown-markup-face prepend)))
2776 (markdown-match-bold . ((1 markdown-markup-properties prepend)
2777 (2 markdown-bold-face append)
2778 (3 markdown-markup-properties prepend)))
2779 (markdown-match-italic . ((1 markdown-markup-properties prepend)
2780 (2 markdown-italic-face append)
2781 (3 markdown-markup-properties prepend)))
2782 (,markdown-regex-strike-through . ((3 markdown-markup-properties)
2783 (4 markdown-strike-through-face)
2784 (5 markdown-markup-properties)))
2785 (,markdown-regex-line-break . (1 markdown-line-break-face prepend))
2786 (markdown-fontify-sub-superscripts)
2787 (markdown-match-inline-attributes . ((0 markdown-markup-properties prepend)))
2788 (markdown-match-leanpub-sections . ((0 markdown-markup-properties)))
2789 (markdown-fontify-blockquotes))
2790 "Syntax highlighting for Markdown files.")
2792 (defvar markdown-mode-font-lock-keywords nil
2793 "Default highlighting expressions for Markdown mode.
2794 This variable is defined as a buffer-local variable for dynamic
2795 extension support.")
2797 ;; Footnotes
2798 (defvar markdown-footnote-counter 0
2799 "Counter for footnote numbers.")
2800 (make-variable-buffer-local 'markdown-footnote-counter)
2802 (defconst markdown-footnote-chars
2803 "[[:alnum:]-]"
2804 "Regular expression matching any character that is allowed in a footnote identifier.")
2806 (defconst markdown-regex-footnote-definition
2807 (concat "^ \\{0,3\\}\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:\\(?:[ \t]+\\|$\\)")
2808 "Regular expression matching a footnote definition, capturing the label.")
2811 ;;; Compatibility =============================================================
2813 (defun markdown-replace-regexp-in-string (regexp rep string)
2814 "Replace ocurrences of REGEXP with REP in STRING.
2815 This is a compatibility wrapper to provide `replace-regexp-in-string'
2816 in XEmacs 21."
2817 (if (featurep 'xemacs)
2818 (replace-in-string string regexp rep)
2819 (replace-regexp-in-string regexp rep string)))
2821 ;; `markdown-use-region-p' is a compatibility function which checks
2822 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
2823 (eval-and-compile
2824 (cond
2825 ;; Emacs 24 and newer
2826 ((fboundp 'use-region-p)
2827 (defalias 'markdown-use-region-p 'use-region-p))
2828 ;; XEmacs
2829 ((fboundp 'region-active-p)
2830 (defalias 'markdown-use-region-p 'region-active-p))))
2832 ;; Use new names for outline-mode functions in Emacs 25 and later.
2833 (eval-and-compile
2834 (defalias 'markdown-hide-sublevels
2835 (if (fboundp 'outline-hide-sublevels)
2836 'outline-hide-sublevels
2837 'hide-sublevels))
2838 (defalias 'markdown-show-all
2839 (if (fboundp 'outline-show-all)
2840 'outline-show-all
2841 'show-all))
2842 (defalias 'markdown-hide-body
2843 (if (fboundp 'outline-hide-body)
2844 'outline-hide-body
2845 'hide-body))
2846 (defalias 'markdown-show-children
2847 (if (fboundp 'outline-show-children)
2848 'outline-show-children
2849 'show-children))
2850 (defalias 'markdown-show-subtree
2851 (if (fboundp 'outline-show-subtree)
2852 'outline-show-subtree
2853 'show-subtree))
2854 (defalias 'markdown-hide-subtree
2855 (if (fboundp 'outline-hide-subtree)
2856 'outline-hide-subtree
2857 'hide-subtree)))
2859 ;; Provide directory-name-p to Emacs 24
2860 (defsubst markdown-directory-name-p (name)
2861 "Return non-nil if NAME ends with a directory separator character.
2862 Taken from `directory-name-p' from Emacs 25 and provided here for
2863 backwards compatibility."
2864 (let ((len (length name))
2865 (lastc ?.))
2866 (if (> len 0)
2867 (setq lastc (aref name (1- len))))
2868 (or (= lastc ?/)
2869 (and (memq system-type '(windows-nt ms-dos))
2870 (= lastc ?\\)))))
2872 ;; Provide a function to find files recursively in Emacs 24.
2873 (defalias 'markdown-directory-files-recursively
2874 (if (fboundp 'directory-files-recursively)
2875 'directory-files-recursively
2876 (lambda (dir regexp)
2877 "Return list of all files under DIR that have file names matching REGEXP.
2878 This function works recursively. Files are returned in \"depth first\"
2879 order, and files from each directory are sorted in alphabetical order.
2880 Each file name appears in the returned list in its absolute form.
2881 Based on `directory-files-recursively' from Emacs 25 and provided
2882 here for backwards compatibility."
2883 (let ((result nil)
2884 (files nil)
2885 ;; When DIR is "/", remote file names like "/method:" could
2886 ;; also be offered. We shall suppress them.
2887 (tramp-mode (and tramp-mode (file-remote-p (expand-file-name dir)))))
2888 (dolist (file (sort (file-name-all-completions "" dir)
2889 'string<))
2890 (unless (member file '("./" "../"))
2891 (if (markdown-directory-name-p file)
2892 (let* ((leaf (substring file 0 (1- (length file))))
2893 (full-file (expand-file-name leaf dir)))
2894 (setq result
2895 (nconc result (markdown-directory-files-recursively
2896 full-file regexp))))
2897 (when (string-match-p regexp file)
2898 (push (expand-file-name file dir) files)))))
2899 (nconc result (nreverse files))))))
2901 (defun markdown-flyspell-check-word-p ()
2902 "Return t if `flyspell' should check word just before point.
2903 Used for `flyspell-generic-check-word-predicate'."
2904 (save-excursion
2905 (goto-char (1- (point)))
2906 (not (or (markdown-code-block-at-point-p)
2907 (markdown-inline-code-at-point-p)
2908 (markdown-in-comment-p)
2909 (let ((faces (get-text-property (point) 'face)))
2910 (if (listp faces)
2911 (or (memq 'markdown-reference-face faces)
2912 (memq 'markdown-markup-face faces)
2913 (memq 'markdown-plain-url-face faces)
2914 (memq 'markdown-inline-code-face faces)
2915 (memq 'markdown-url-face faces))
2916 (memq faces '(markdown-reference-face
2917 markdown-markup-face
2918 markdown-plain-url-face
2919 markdown-inline-code-face
2920 markdown-url-face))))))))
2922 (defun markdown-font-lock-ensure ()
2923 "Provide `font-lock-ensure' in Emacs 24."
2924 (if (fboundp 'font-lock-ensure)
2925 (font-lock-ensure)
2926 (with-no-warnings
2927 ;; Suppress warning about non-interactive use of
2928 ;; `font-lock-fontify-buffer' in Emacs 25.
2929 (font-lock-fontify-buffer))))
2932 ;;; Markdown Parsing Functions ================================================
2934 (defun markdown-cur-line-blank (&optional predicate)
2935 "Return t if the current line is blank and nil otherwise.
2936 When PREDICATE is non-nil, don't modify the match data."
2937 (save-excursion
2938 (beginning-of-line)
2939 (let ((regexp "^\\s *$"))
2940 (if predicate
2941 (looking-at-p regexp)
2942 (looking-at regexp)))))
2944 (defun markdown-cur-line-blank-p ()
2945 "Same as `markdown-cur-line-blank', but does not change the match data."
2946 (markdown-cur-line-blank t))
2948 (defun markdown-prev-line-blank (&optional predicate)
2949 "Return t if the previous line is blank and nil otherwise.
2950 If we are at the first line, then consider the previous line to be blank.
2951 When PREDICATE is non-nil, don't modify the match data."
2952 (or (= (line-beginning-position) (point-min))
2953 (save-excursion
2954 (forward-line -1)
2955 (markdown-cur-line-blank predicate))))
2957 (defun markdown-prev-line-blank-p ()
2958 "Same as `markdown-prev-line-blank', but does not change the match data."
2959 (markdown-prev-line-blank t))
2961 (defun markdown-next-line-blank (&optional predicate)
2962 "Return t if the next line is blank and nil otherwise.
2963 If we are at the last line, then consider the next line to be blank.
2964 When PREDICATE is non-nil, don't modify the match data."
2965 (or (= (line-end-position) (point-max))
2966 (save-excursion
2967 (forward-line 1)
2968 (markdown-cur-line-blank predicate))))
2970 (defun markdown-next-line-blank-p ()
2971 "Same as `markdown-next-line-blank', but does not change the match data."
2972 (markdown-next-line-blank t))
2974 (defun markdown-prev-line-indent ()
2975 "Return the number of leading whitespace characters in the previous line.
2976 Return 0 if the current line is the first line in the buffer."
2977 (save-excursion
2978 (if (= (line-beginning-position) (point-min))
2980 (forward-line -1)
2981 (current-indentation))))
2983 (defun markdown-next-line-indent ()
2984 "Return the number of leading whitespace characters in the next line.
2985 Return 0 if line is the last line in the buffer."
2986 (save-excursion
2987 (if (= (line-end-position) (point-max))
2989 (forward-line 1)
2990 (current-indentation))))
2992 (defun markdown-cur-non-list-indent ()
2993 "Return beginning position of list item text (not including the list marker).
2994 Return nil if the current line is not the beginning of a list item."
2995 (save-match-data
2996 (save-excursion
2997 (beginning-of-line)
2998 (when (re-search-forward markdown-regex-list (line-end-position) t)
2999 (current-column)))))
3001 (defun markdown-prev-non-list-indent ()
3002 "Return position of the first non-list-marker on the previous line."
3003 (save-excursion
3004 (forward-line -1)
3005 (markdown-cur-non-list-indent)))
3007 (defun markdown-new-baseline ()
3008 "Determine if the current line begins a new baseline level."
3009 (save-excursion
3010 (beginning-of-line)
3011 (or (looking-at markdown-regex-header)
3012 (looking-at markdown-regex-hr)
3013 (and (null (markdown-cur-non-list-indent))
3014 (= (current-indentation) 0)
3015 (markdown-prev-line-blank)))))
3017 (defun markdown-search-backward-baseline ()
3018 "Search backward baseline point with no indentation and not a list item."
3019 (end-of-line)
3020 (let (stop)
3021 (while (not (or stop (bobp)))
3022 (re-search-backward markdown-regex-block-separator-noindent nil t)
3023 (when (match-end 2)
3024 (goto-char (match-end 2))
3025 (cond
3026 ((markdown-new-baseline)
3027 (setq stop t))
3028 ((looking-at-p markdown-regex-list)
3029 (setq stop nil))
3030 (t (setq stop t)))))))
3032 (defun markdown-update-list-levels (marker indent levels)
3033 "Update list levels given list MARKER, block INDENT, and current LEVELS.
3034 Here, MARKER is a string representing the type of list, INDENT is an integer
3035 giving the indentation, in spaces, of the current block, and LEVELS is a
3036 list of the indentation levels of parent list items. When LEVELS is nil,
3037 it means we are at baseline (not inside of a nested list)."
3038 (cond
3039 ;; New list item at baseline.
3040 ((and marker (null levels))
3041 (setq levels (list indent)))
3042 ;; List item with greater indentation (four or more spaces).
3043 ;; Increase list level.
3044 ((and marker (>= indent (+ (car levels) 4)))
3045 (setq levels (cons indent levels)))
3046 ;; List item with greater or equal indentation (less than four spaces).
3047 ;; Do not increase list level.
3048 ((and marker (>= indent (car levels)))
3049 levels)
3050 ;; Lesser indentation level.
3051 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
3052 ;; indentation could move back more than one list level). Note
3053 ;; that this block need not be the beginning of list item.
3054 ((< indent (car levels))
3055 (while (and (> (length levels) 1)
3056 (< indent (+ (cadr levels) 4)))
3057 (setq levels (cdr levels)))
3058 levels)
3059 ;; Otherwise, do nothing.
3060 (t levels)))
3062 (defun markdown-calculate-list-levels ()
3063 "Calculate list levels at point.
3064 Return a list of the form (n1 n2 n3 ...) where n1 is the
3065 indentation of the deepest nested list item in the branch of
3066 the list at the point, n2 is the indentation of the parent
3067 list item, and so on. The depth of the list item is therefore
3068 the length of the returned list. If the point is not at or
3069 immediately after a list item, return nil."
3070 (save-excursion
3071 (let ((first (point)) levels indent pre-regexp)
3072 ;; Find a baseline point with zero list indentation
3073 (markdown-search-backward-baseline)
3074 ;; Search for all list items between baseline and LOC
3075 (while (and (< (point) first)
3076 (re-search-forward markdown-regex-list first t))
3077 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
3078 (beginning-of-line)
3079 (cond
3080 ;; Make sure this is not a header or hr
3081 ((markdown-new-baseline) (setq levels nil))
3082 ;; Make sure this is not a line from a pre block
3083 ((looking-at-p pre-regexp))
3084 ;; If not, then update levels
3086 (setq indent (current-indentation))
3087 (setq levels (markdown-update-list-levels (match-string 2)
3088 indent levels))))
3089 (end-of-line))
3090 levels)))
3092 (defun markdown-prev-list-item (level)
3093 "Search backward from point for a list item with indentation LEVEL.
3094 Set point to the beginning of the item, and return point, or nil
3095 upon failure."
3096 (let (bounds indent prev)
3097 (setq prev (point))
3098 (forward-line -1)
3099 (setq indent (current-indentation))
3100 (while
3101 (cond
3102 ;; List item
3103 ((and (looking-at-p markdown-regex-list)
3104 (setq bounds (markdown-cur-list-item-bounds)))
3105 (cond
3106 ;; Stop and return point at item of equal indentation
3107 ((= (nth 3 bounds) level)
3108 (setq prev (point))
3109 nil)
3110 ;; Stop and return nil at item with lesser indentation
3111 ((< (nth 3 bounds) level)
3112 (setq prev nil)
3113 nil)
3114 ;; Stop at beginning of buffer
3115 ((bobp) (setq prev nil))
3116 ;; Continue at item with greater indentation
3117 ((> (nth 3 bounds) level) t)))
3118 ;; Stop at beginning of buffer
3119 ((bobp) (setq prev nil))
3120 ;; Continue if current line is blank
3121 ((markdown-cur-line-blank-p) t)
3122 ;; Continue while indentation is the same or greater
3123 ((>= indent level) t)
3124 ;; Stop if current indentation is less than list item
3125 ;; and the next is blank
3126 ((and (< indent level)
3127 (markdown-next-line-blank-p))
3128 (setq prev nil))
3129 ;; Stop at a header
3130 ((looking-at-p markdown-regex-header) (setq prev nil))
3131 ;; Stop at a horizontal rule
3132 ((looking-at-p markdown-regex-hr) (setq prev nil))
3133 ;; Otherwise, continue.
3134 (t t))
3135 (forward-line -1)
3136 (setq indent (current-indentation)))
3137 prev))
3139 (defun markdown-next-list-item (level)
3140 "Search forward from point for the next list item with indentation LEVEL.
3141 Set point to the beginning of the item, and return point, or nil
3142 upon failure."
3143 (let (bounds indent next)
3144 (setq next (point))
3145 (if (looking-at markdown-regex-header-setext)
3146 (goto-char (match-end 0)))
3147 (forward-line)
3148 (setq indent (current-indentation))
3149 (while
3150 (cond
3151 ;; Stop at end of the buffer.
3152 ((eobp) nil)
3153 ;; Continue if the current line is blank
3154 ((markdown-cur-line-blank-p) t)
3155 ;; List item
3156 ((and (looking-at-p markdown-regex-list)
3157 (setq bounds (markdown-cur-list-item-bounds)))
3158 (cond
3159 ;; Continue at item with greater indentation
3160 ((> (nth 3 bounds) level) t)
3161 ;; Stop and return point at item of equal indentation
3162 ((= (nth 3 bounds) level)
3163 (setq next (point))
3164 nil)
3165 ;; Stop and return nil at item with lesser indentation
3166 ((< (nth 3 bounds) level)
3167 (setq next nil)
3168 nil)))
3169 ;; Continue while indentation is the same or greater
3170 ((>= indent level) t)
3171 ;; Stop if current indentation is less than list item
3172 ;; and the previous line was blank.
3173 ((and (< indent level)
3174 (markdown-prev-line-blank-p))
3175 (setq next nil))
3176 ;; Stop at a header
3177 ((looking-at-p markdown-regex-header) (setq next nil))
3178 ;; Stop at a horizontal rule
3179 ((looking-at-p markdown-regex-hr) (setq next nil))
3180 ;; Otherwise, continue.
3181 (t t))
3182 (forward-line)
3183 (setq indent (current-indentation)))
3184 next))
3186 (defun markdown-cur-list-item-end (level)
3187 "Move to the end of the current list item with nonlist indentation LEVEL.
3188 If the point is not in a list item, do nothing."
3189 (let (indent)
3190 (forward-line)
3191 (setq indent (current-indentation))
3192 (while
3193 (cond
3194 ;; Stop at end of the buffer.
3195 ((eobp) nil)
3196 ;; Continue if the current line is blank
3197 ((markdown-cur-line-blank-p) t)
3198 ;; Continue while indentation is the same or greater
3199 ((>= indent level) t)
3200 ;; Stop if current indentation is less than list item
3201 ;; and the previous line was blank.
3202 ((and (< indent level)
3203 (markdown-prev-line-blank-p))
3204 nil)
3205 ;; Stop at a new list item of the same or lesser indentation
3206 ((looking-at-p markdown-regex-list) nil)
3207 ;; Stop at a header
3208 ((looking-at-p markdown-regex-header) nil)
3209 ;; Stop at a horizontal rule
3210 ((looking-at-p markdown-regex-hr) nil)
3211 ;; Otherwise, continue.
3212 (t t))
3213 (forward-line)
3214 (setq indent (current-indentation)))
3215 ;; Don't skip over whitespace for empty list items (marker and
3216 ;; whitespace only), just move to end of whitespace.
3217 (if (looking-back (concat markdown-regex-list "\\s-*") nil)
3218 (goto-char (match-end 3))
3219 (skip-syntax-backward "-"))))
3221 (defun markdown-cur-list-item-bounds ()
3222 "Return bounds and indentation of the current list item.
3223 Return a list of the following form:
3225 (begin end indent nonlist-indent marker checkbox)
3227 The named components are:
3229 - begin: Position of beginning of list item, including leading indentation.
3230 - end: Position of the end of the list item, including list item text.
3231 - indent: Number of characters of indentation before list marker (an integer).
3232 - nonlist-indent: Number characters of indentation, list
3233 marker, and whitespace following list marker (an integer).
3234 - marker: String containing the list marker and following whitespace
3235 (e.g., \"- \" or \"* \").
3236 - checkbox: String containing the GFM checkbox portion, if any,
3237 including any trailing whitespace before the text
3238 begins (e.g., \"[x] \").
3240 As an example, for the following unordered list item
3242 - item
3244 the returned list would be
3246 (1 14 3 5 \"- \" nil)
3248 If the point is not inside a list item, return nil.
3249 Leave match data intact for `markdown-regex-list'."
3250 (save-excursion
3251 (let ((cur (point)))
3252 (end-of-line)
3253 (when (re-search-backward markdown-regex-list nil t)
3254 (let* ((begin (match-beginning 0))
3255 (indent (length (match-string-no-properties 1)))
3256 (nonlist-indent (length (match-string 0)))
3257 (marker (concat (match-string-no-properties 2)
3258 (match-string-no-properties 3)))
3259 (checkbox (progn (goto-char (match-end 0))
3260 (when (looking-at "\\[[xX ]\\]\\s-*")
3261 (match-string-no-properties 0))))
3262 (end (save-match-data
3263 (markdown-cur-list-item-end nonlist-indent)
3264 (point))))
3265 (when (and (>= cur begin) (<= cur end) nonlist-indent)
3266 (list begin end indent nonlist-indent marker checkbox)))))))
3268 (defun markdown-list-item-at-point-p ()
3269 "Return t if there is a list item at the point and nil otherwise."
3270 (save-match-data (markdown-cur-list-item-bounds)))
3272 (defun markdown-prev-list-item-bounds ()
3273 "Return bounds of previous item in the same list of any level.
3274 The return value has the same form as that of
3275 `markdown-cur-list-item-bounds'."
3276 (save-excursion
3277 (let ((cur-bounds (markdown-cur-list-item-bounds))
3278 (beginning-of-list (save-excursion (markdown-beginning-of-list)))
3279 stop)
3280 (when cur-bounds
3281 (goto-char (nth 0 cur-bounds))
3282 (while (and (not stop) (not (bobp))
3283 (re-search-backward markdown-regex-list
3284 beginning-of-list t))
3285 (unless (or (looking-at markdown-regex-hr)
3286 (markdown-code-block-at-point-p))
3287 (setq stop (point))))
3288 (markdown-cur-list-item-bounds)))))
3290 (defun markdown-next-list-item-bounds ()
3291 "Return bounds of next item in the same list of any level.
3292 The return value has the same form as that of
3293 `markdown-cur-list-item-bounds'."
3294 (save-excursion
3295 (let ((cur-bounds (markdown-cur-list-item-bounds))
3296 (end-of-list (save-excursion (markdown-end-of-list)))
3297 stop)
3298 (when cur-bounds
3299 (goto-char (nth 0 cur-bounds))
3300 (end-of-line)
3301 (while (and (not stop) (not (eobp))
3302 (re-search-forward markdown-regex-list
3303 end-of-list t))
3304 (unless (or (looking-at markdown-regex-hr)
3305 (markdown-code-block-at-point-p))
3306 (setq stop (point))))
3307 (when stop
3308 (markdown-cur-list-item-bounds))))))
3310 (defun markdown-beginning-of-list ()
3311 "Move point to beginning of list at point, if any."
3312 (interactive)
3313 (let ((orig-point (point))
3314 (list-begin (save-excursion
3315 (markdown-search-backward-baseline)
3316 ;; Stop at next list item, regardless of the indentation.
3317 (markdown-next-list-item (point-max))
3318 (when (looking-at markdown-regex-list)
3319 (point)))))
3320 (when (and list-begin (<= list-begin orig-point))
3321 (goto-char list-begin))))
3323 (defun markdown-end-of-list ()
3324 "Move point to end of list at point, if any."
3325 (interactive)
3326 (let ((start (point))
3327 (end (save-excursion
3328 (when (markdown-beginning-of-list)
3329 ;; Items can't have nonlist-indent <= 1, so this
3330 ;; moves past all list items.
3331 (markdown-next-list-item 1)
3332 (skip-syntax-backward "-")
3333 (unless (eobp) (forward-char 1))
3334 (point)))))
3335 (when (and end (>= end start))
3336 (goto-char end))))
3338 (defun markdown-up-list ()
3339 "Move point to beginning of parent list item."
3340 (interactive)
3341 (let ((cur-bounds (markdown-cur-list-item-bounds)))
3342 (when cur-bounds
3343 (markdown-prev-list-item (1- (nth 3 cur-bounds)))
3344 (let ((up-bounds (markdown-cur-list-item-bounds)))
3345 (when (and up-bounds (< (nth 3 up-bounds) (nth 3 cur-bounds)))
3346 (point))))))
3348 (defun markdown-bounds-of-thing-at-point (thing)
3349 "Call `bounds-of-thing-at-point' for THING with slight modifications.
3350 Does not include trailing newlines when THING is 'line. Handles the
3351 end of buffer case by setting both endpoints equal to the value of
3352 `point-max', since an empty region will trigger empty markup insertion.
3353 Return bounds of form (beg . end) if THING is found, or nil otherwise."
3354 (let* ((bounds (bounds-of-thing-at-point thing))
3355 (a (car bounds))
3356 (b (cdr bounds)))
3357 (when bounds
3358 (when (eq thing 'line)
3359 (cond ((and (eobp) (markdown-cur-line-blank-p))
3360 (setq a b))
3361 ((char-equal (char-before b) ?\^J)
3362 (setq b (1- b)))))
3363 (cons a b))))
3365 (defun markdown-reference-definition (reference)
3366 "Find out whether Markdown REFERENCE is defined.
3367 REFERENCE should not include the square brackets.
3368 When REFERENCE is defined, return a list of the form (text start end)
3369 containing the definition text itself followed by the start and end
3370 locations of the text. Otherwise, return nil.
3371 Leave match data for `markdown-regex-reference-definition'
3372 intact additional processing."
3373 (let ((reference (downcase reference)))
3374 (save-excursion
3375 (goto-char (point-min))
3376 (catch 'found
3377 (while (re-search-forward markdown-regex-reference-definition nil t)
3378 (when (string= reference (downcase (match-string-no-properties 2)))
3379 (throw 'found
3380 (list (match-string-no-properties 5)
3381 (match-beginning 5) (match-end 5)))))))))
3383 (defun markdown-get-defined-references ()
3384 "Return a list of all defined reference labels (not including square brackets)."
3385 (save-excursion
3386 (goto-char (point-min))
3387 (let (refs)
3388 (while (re-search-forward markdown-regex-reference-definition nil t)
3389 (let ((target (match-string-no-properties 2)))
3390 (cl-pushnew target refs :test #'equal)))
3391 (reverse refs))))
3393 (defun markdown-get-used-uris ()
3394 "Return a list of all used URIs in the buffer."
3395 (save-excursion
3396 (goto-char (point-min))
3397 (let (uris)
3398 (while (re-search-forward
3399 (concat "\\(?:" markdown-regex-link-inline
3400 "\\|" markdown-regex-angle-uri
3401 "\\|" markdown-regex-uri
3402 "\\|" markdown-regex-email
3403 "\\)")
3404 nil t)
3405 (unless (or (markdown-inline-code-at-point-p)
3406 (markdown-code-block-at-point-p))
3407 (cl-pushnew (or (match-string-no-properties 6)
3408 (match-string-no-properties 10)
3409 (match-string-no-properties 12)
3410 (match-string-no-properties 13))
3411 uris :test #'equal)))
3412 (reverse uris))))
3414 (defun markdown-inline-code-at-pos (pos)
3415 "Return non-nil if there is an inline code fragment at POS.
3416 Return nil otherwise. Set match data according to
3417 `markdown-match-code' upon success.
3418 This function searches the block for a code fragment that
3419 contains the point using `markdown-match-code'. We do this
3420 because `thing-at-point-looking-at' does not work reliably with
3421 `markdown-regex-code'.
3423 The match data is set as follows:
3424 Group 1 matches the opening backquotes.
3425 Group 2 matches the code fragment itself, without backquotes.
3426 Group 3 matches the closing backquotes."
3427 (save-excursion
3428 (goto-char pos)
3429 (let ((old-point (point))
3430 (end-of-block (progn (markdown-end-of-text-block) (point)))
3431 found)
3432 (markdown-beginning-of-text-block)
3433 (while (and (markdown-match-code end-of-block)
3434 (setq found t)
3435 (< (match-end 0) old-point)))
3436 (and found ; matched something
3437 (<= (match-beginning 0) old-point) ; match contains old-point
3438 (>= (match-end 0) old-point)))))
3440 (defun markdown-inline-code-at-pos-p (pos)
3441 "Return non-nil if there is an inline code fragment at POS.
3442 Like `markdown-inline-code-at-pos`, but preserves match data."
3443 (save-match-data (markdown-inline-code-at-pos pos)))
3445 (defun markdown-inline-code-at-point ()
3446 "Return non-nil if the point is at an inline code fragment.
3447 See `markdown-inline-code-at-pos' for details."
3448 (markdown-inline-code-at-pos (point)))
3450 (defun markdown-inline-code-at-point-p ()
3451 "Return non-nil if there is inline code at the point.
3452 This is a predicate function counterpart to
3453 `markdown-inline-code-at-point' which does not modify the match
3454 data. See `markdown-code-block-at-point-p' for code blocks."
3455 (save-match-data (markdown-inline-code-at-pos (point))))
3457 (make-obsolete 'markdown-code-at-point-p 'markdown-inline-code-at-point-p "v2.2")
3459 (defun markdown-code-block-at-pos (pos)
3460 "Return match data list if there is a code block at POS.
3461 Uses text properties at the beginning of the line position.
3462 This includes pre blocks, tilde-fenced code blocks, and GFM
3463 quoted code blocks. Return nil otherwise."
3464 (setq pos (save-excursion (goto-char pos) (point-at-bol)))
3465 (or (get-text-property pos 'markdown-pre)
3466 (markdown-get-enclosing-fenced-block-construct pos)
3467 ;; polymode removes text properties set by markdown-mode, so
3468 ;; check if `poly-markdown-mode' is active and whether the
3469 ;; `chunkmode' property is non-nil at POS.
3470 (and (bound-and-true-p poly-markdown-mode)
3471 (get-text-property pos 'chunkmode))))
3473 ;; Function was renamed to emphasize that it does not modify match-data.
3474 (defalias 'markdown-code-block-at-point 'markdown-code-block-at-point-p)
3476 (defun markdown-code-block-at-point-p ()
3477 "Return non-nil if there is a code block at the point.
3478 This includes pre blocks, tilde-fenced code blocks, and GFM
3479 quoted code blocks. This function does not modify the match
3480 data. See `markdown-inline-code-at-point-p' for inline code."
3481 (save-match-data (markdown-code-block-at-pos (point))))
3483 (defun markdown-heading-at-point ()
3484 "Return non-nil if there is a heading at the point.
3485 Set match data for `markdown-regex-header'."
3486 (let ((match-data (get-text-property (point) 'markdown-heading)))
3487 (when match-data
3488 (set-match-data match-data)
3489 t)))
3491 (defun markdown-pipe-at-bol-p ()
3492 "Return non-nil if the line begins with a pipe symbol.
3493 This may be useful for tables and Pandoc's line_blocks extension."
3494 (char-equal (char-after (point-at-bol)) ?|))
3497 ;;; Markdown Font Lock Matching Functions =====================================
3499 (defun markdown-range-property-any (begin end prop prop-values)
3500 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
3501 Also returns t if PROP is a list containing one of the PROP-VALUES.
3502 Return nil otherwise."
3503 (let (props)
3504 (catch 'found
3505 (dolist (loc (number-sequence begin end))
3506 (when (setq props (get-text-property loc prop))
3507 (cond ((listp props)
3508 ;; props is a list, check for membership
3509 (dolist (val prop-values)
3510 (when (memq val props) (throw 'found loc))))
3512 ;; props is a scalar, check for equality
3513 (dolist (val prop-values)
3514 (when (eq val props) (throw 'found loc))))))))))
3516 (defun markdown-range-properties-exist (begin end props)
3517 (cl-loop
3518 for loc in (number-sequence begin end)
3519 with result = nil
3520 while (not
3521 (setq result
3522 (cl-some (lambda (prop) (get-text-property loc prop)) props)))
3523 finally return result))
3525 (defun markdown-match-inline-generic (regex last &optional faceless)
3526 "Match inline REGEX from the point to LAST.
3527 When FACELESS is non-nil, do not return matches where faces have been applied."
3528 (when (re-search-forward regex last t)
3529 (let ((bounds (markdown-code-block-at-pos (match-beginning 1)))
3530 (face (and faceless (text-property-not-all
3531 (match-beginning 0) (match-end 0) 'face nil))))
3532 (cond
3533 ;; In code block: move past it and recursively search again
3534 (bounds
3535 (when (< (goto-char (cl-second bounds)) last)
3536 (markdown-match-inline-generic regex last faceless)))
3537 ;; When faces are found in the match range, skip over the match and
3538 ;; recursively search again.
3539 (face
3540 (when (< (goto-char (match-end 0)) last)
3541 (markdown-match-inline-generic regex last faceless)))
3542 ;; Keep match data and return t when in bounds.
3544 (<= (match-end 0) last))))))
3546 (defun markdown-match-code (last)
3547 "Match inline code fragments from point to LAST."
3548 (unless (bobp)
3549 (backward-char 1))
3550 (when (markdown-match-inline-generic markdown-regex-code last)
3551 (let ((begin (match-beginning 1))
3552 (end (match-end 1))
3553 (open-begin (match-beginning 2))
3554 (open-end (match-end 2))
3555 (code-begin (match-beginning 3))
3556 (code-end (match-end 3))
3557 (close-begin (match-beginning 4))
3558 (close-end (match-end 4)))
3559 (if (or (markdown-in-comment-p begin)
3560 (markdown-in-comment-p end)
3561 (markdown-code-block-at-pos begin))
3562 (progn (goto-char (min (1+ begin) last))
3563 (when (< (point) last)
3564 (markdown-match-code last)))
3565 (set-match-data (list begin end
3566 open-begin open-end
3567 code-begin code-end
3568 close-begin close-end))
3569 t))))
3571 (defun markdown-match-bold (last)
3572 "Match inline bold from the point to LAST."
3573 (when (markdown-match-inline-generic markdown-regex-bold last)
3574 (let ((begin (match-beginning 2))
3575 (end (match-end 2)))
3576 (if (or (markdown-inline-code-at-pos-p begin)
3577 (markdown-inline-code-at-pos-p end)
3578 (markdown-in-comment-p)
3579 (markdown-range-property-any
3580 begin begin 'face '(markdown-url-face
3581 markdown-plain-url-face))
3582 (markdown-range-property-any
3583 begin end 'face '(markdown-inline-code-face
3584 markdown-math-face)))
3585 (progn (goto-char (min (1+ begin) last))
3586 (when (< (point) last)
3587 (markdown-match-italic last)))
3588 (set-match-data (list (match-beginning 2) (match-end 2)
3589 (match-beginning 3) (match-end 3)
3590 (match-beginning 4) (match-end 4)
3591 (match-beginning 5) (match-end 5)))
3592 t))))
3594 (defun markdown-match-italic (last)
3595 "Match inline italics from the point to LAST."
3596 (let ((regex (if (eq major-mode 'gfm-mode)
3597 markdown-regex-gfm-italic markdown-regex-italic)))
3598 (when (markdown-match-inline-generic regex last)
3599 (let ((begin (match-beginning 1))
3600 (end (match-end 1)))
3601 (if (or (markdown-inline-code-at-pos-p begin)
3602 (markdown-inline-code-at-pos-p end)
3603 (markdown-in-comment-p)
3604 (markdown-range-property-any
3605 begin begin 'face '(markdown-url-face
3606 markdown-plain-url-face))
3607 (markdown-range-property-any
3608 begin end 'face '(markdown-inline-code-face
3609 markdown-bold-face
3610 markdown-list-face
3611 markdown-math-face)))
3612 (progn (goto-char (min (1+ begin) last))
3613 (when (< (point) last)
3614 (markdown-match-italic last)))
3615 (set-match-data (list (match-beginning 1) (match-end 1)
3616 (match-beginning 2) (match-end 2)
3617 (match-beginning 3) (match-end 3)
3618 (match-beginning 4) (match-end 4)))
3619 t)))))
3621 (defun markdown-match-math-generic (regex last)
3622 "Match REGEX from point to LAST.
3623 REGEX is either `markdown-regex-math-inline-single' for matching
3624 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
3625 (when (and markdown-enable-math (markdown-match-inline-generic regex last))
3626 (let ((begin (match-beginning 1)) (end (match-end 1)))
3627 (prog1
3628 (if (or (markdown-range-property-any
3629 begin end 'face (list markdown-inline-code-face
3630 markdown-bold-face))
3631 (markdown-range-properties-exist
3632 begin end
3633 (markdown-get-fenced-block-middle-properties)))
3634 (markdown-match-math-generic regex last)
3636 (goto-char (1+ (match-end 0)))))))
3638 (defun markdown-match-list-items (last)
3639 "Match list items from point to LAST."
3640 (when (markdown-match-inline-generic markdown-regex-list last)
3641 (let ((begin (match-beginning 2))
3642 (end (match-end 2)))
3643 (if (or (markdown-range-property-any
3644 begin end 'face (list markdown-inline-code-face
3645 markdown-bold-face
3646 markdown-math-face))
3647 (markdown-range-properties-exist begin end '(markdown-hr))
3648 (markdown-in-comment-p))
3649 (progn (goto-char (min (1+ (match-end 0)) last))
3650 (markdown-match-list-items last))
3651 (set-match-data (list (match-beginning 0) (match-end 0)
3652 (match-beginning 1) (match-end 1)
3653 (match-beginning 2) (match-end 2)))
3654 (goto-char (1+ (match-end 0)))))))
3656 (defun markdown-match-math-single (last)
3657 "Match single quoted $..$ math from point to LAST."
3658 (markdown-match-math-generic markdown-regex-math-inline-single last))
3660 (defun markdown-match-math-double (last)
3661 "Match double quoted $$..$$ math from point to LAST."
3662 (markdown-match-math-generic markdown-regex-math-inline-double last))
3664 (defun markdown-match-propertized-text (property last)
3665 "Match text with PROPERTY from point to LAST.
3666 Restore match data previously stored in PROPERTY."
3667 (let ((saved (get-text-property (point) property))
3668 pos)
3669 (unless saved
3670 (setq pos (next-single-char-property-change (point) property nil last))
3671 (setq saved (get-text-property pos property)))
3672 (when saved
3673 (set-match-data saved)
3674 ;; Step at least one character beyond point. Otherwise
3675 ;; `font-lock-fontify-keywords-region' infloops.
3676 (goto-char (min (1+ (max (match-end 0) (point)))
3677 (point-max)))
3678 saved)))
3680 (defun markdown-match-pre-blocks (last)
3681 "Match preformatted blocks from point to LAST.
3682 Use data stored in 'markdown-pre text property during syntax
3683 analysis."
3684 (markdown-match-propertized-text 'markdown-pre last))
3686 (defun markdown-match-gfm-code-blocks (last)
3687 "Match GFM quoted code blocks from point to LAST.
3688 Use data stored in 'markdown-gfm-code text property during syntax
3689 analysis."
3690 (markdown-match-propertized-text 'markdown-gfm-code last))
3692 (defun markdown-match-gfm-open-code-blocks (last)
3693 (markdown-match-propertized-text 'markdown-gfm-block-begin last))
3695 (defun markdown-match-gfm-close-code-blocks (last)
3696 (markdown-match-propertized-text 'markdown-gfm-block-end last))
3698 (defun markdown-match-fenced-code-blocks (last)
3699 "Match fenced code blocks from the point to LAST."
3700 (markdown-match-propertized-text 'markdown-fenced-code last))
3702 (defun markdown-match-fenced-start-code-block (last)
3703 (markdown-match-propertized-text 'markdown-tilde-fence-begin last))
3705 (defun markdown-match-fenced-end-code-block (last)
3706 (markdown-match-propertized-text 'markdown-tilde-fence-end last))
3708 (defun markdown-match-blockquotes (last)
3709 "Match blockquotes from point to LAST.
3710 Use data stored in 'markdown-blockquote text property during syntax
3711 analysis."
3712 (markdown-match-propertized-text 'markdown-blockquote last))
3714 (defun markdown-match-hr (last)
3715 "Match horizontal rules comments from the point to LAST."
3716 (markdown-match-propertized-text 'markdown-hr last))
3718 (defun markdown-match-comments (last)
3719 "Match HTML comments from the point to LAST."
3720 (when (and (skip-syntax-forward "^<" last))
3721 (let ((beg (point)))
3722 (when (and (skip-syntax-forward "^>" last) (< (point) last))
3723 (forward-char)
3724 (set-match-data (list beg (point)))
3725 t))))
3727 (defun markdown-match-generic-links (last ref)
3728 "Match inline links from point to LAST.
3729 When REF is non-nil, match reference links instead of standard
3730 links with URLs."
3731 ;; Search for the next potential link (not in a code block).
3732 (while (and (progn
3733 ;; Clear match data to test for a match after functions returns.
3734 (set-match-data nil)
3735 (re-search-forward "\\(!\\)?\\(\\[\\)" last 'limit))
3736 ;; Keep searching if this is in a code block, inline
3737 ;; code, or a comment, or if it is include syntax.
3738 (or (markdown-code-block-at-point-p)
3739 (markdown-inline-code-at-pos-p (match-beginning 0))
3740 (markdown-inline-code-at-pos-p (match-end 0))
3741 (markdown-in-comment-p)
3742 (and (char-equal (char-after (point-at-bol)) ?<)
3743 (char-equal (char-after (1+ (point-at-bol))) ?<)))
3744 (< (point) last)))
3745 ;; Match opening exclamation point (optional) and left bracket.
3746 (when (match-beginning 2)
3747 (let* ((bang (match-beginning 1))
3748 (first-begin (match-beginning 2))
3749 ;; Find end of block to prevent matching across blocks.
3750 (end-of-block (save-excursion
3751 (progn
3752 (goto-char (match-beginning 2))
3753 (markdown-end-of-text-block)
3754 (point))))
3755 ;; Move over balanced expressions to closing right bracket.
3756 ;; Catch unbalanced expression errors and return nil.
3757 (first-end (condition-case nil
3758 (and (goto-char first-begin)
3759 (scan-sexps (point) 1))
3760 (error nil)))
3761 ;; Continue with point at CONT-POINT upon failure.
3762 (cont-point (min (1+ first-begin) last))
3763 second-begin second-end url-begin url-end
3764 title-begin title-end)
3765 ;; When bracket found, in range, and followed by a left paren/bracket...
3766 (when (and first-end (< first-end end-of-block) (goto-char first-end)
3767 (char-equal (char-after (point)) (if ref ?\[ ?\()))
3768 ;; Scan across balanced expressions for closing parenthesis/bracket.
3769 (setq second-begin (point)
3770 second-end (condition-case nil
3771 (scan-sexps (point) 1)
3772 (error nil)))
3773 ;; Check that closing parenthesis/bracket is in range.
3774 (if (and second-end (<= second-end end-of-block) (<= second-end last))
3775 (progn
3776 ;; Search for (optional) title inside closing parenthesis
3777 (when (and (not ref) (search-forward "\"" second-end t))
3778 (setq title-begin (1- (point))
3779 title-end (and (goto-char second-end)
3780 (search-backward "\"" (1+ title-begin) t))
3781 title-end (and title-end (1+ title-end))))
3782 ;; Store URL/reference range
3783 (setq url-begin (1+ second-begin)
3784 url-end (1- (or title-begin second-end)))
3785 ;; Set match data, move point beyond link, and return
3786 (set-match-data
3787 (list (or bang first-begin) second-end ; 0 - all
3788 bang (and bang (1+ bang)) ; 1 - bang
3789 first-begin (1+ first-begin) ; 2 - markup
3790 (1+ first-begin) (1- first-end) ; 3 - link text
3791 (1- first-end) first-end ; 4 - markup
3792 second-begin (1+ second-begin) ; 5 - markup
3793 url-begin url-end ; 6 - url/reference
3794 title-begin title-end ; 7 - title
3795 (1- second-end) second-end)) ; 8 - markup
3796 ;; Nullify cont-point and leave point at end and
3797 (setq cont-point nil)
3798 (goto-char second-end))
3799 ;; If no closing parenthesis in range, update continuation point
3800 (setq cont-point (min end-of-block second-begin))))
3801 (cond
3802 ;; On failure, continue searching at cont-point
3803 ((and cont-point (< cont-point last))
3804 (goto-char cont-point)
3805 (markdown-match-generic-links last ref))
3806 ;; No more text, return nil
3807 ((and cont-point (= cont-point last))
3808 nil)
3809 ;; Return t if a match occurred
3810 (t t)))))
3812 (defun markdown-match-inline-links (last)
3813 "Match standard inline links from point to LAST."
3814 (markdown-match-generic-links last nil))
3816 (defun markdown-match-reference-links (last)
3817 "Match inline reference links from point to LAST."
3818 (markdown-match-generic-links last t))
3820 (defun markdown-match-angle-uris (last)
3821 "Match angle bracket URIs from point to LAST."
3822 (when (markdown-match-inline-generic markdown-regex-angle-uri last)
3823 (goto-char (1+ (match-end 0)))))
3825 (defun markdown-match-plain-uris (last)
3826 "Match plain URIs from point to LAST."
3827 (when (markdown-match-inline-generic markdown-regex-uri last t)
3828 (goto-char (1+ (match-end 0)))))
3830 (defun markdown-get-match-boundaries (start-header end-header last &optional pos)
3831 (save-excursion
3832 (goto-char (or pos (point-min)))
3833 (cl-loop
3834 with cur-result = nil
3835 and st-hdr = (or start-header "\\`")
3836 and end-hdr = (or end-header "\n\n\\|\n\\'\\|\\'")
3837 while (and (< (point) last)
3838 (re-search-forward st-hdr last t)
3839 (progn
3840 (setq cur-result (match-data))
3841 (re-search-forward end-hdr nil t)))
3842 collect (list cur-result (match-data)))))
3844 (defvar markdown-conditional-search-function #'re-search-forward
3845 "Conditional search function used in `markdown-search-until-condition'.
3846 Made into a variable to allow for dynamic let-binding.")
3848 (defun markdown-search-until-condition (condition &rest args)
3849 (let (ret)
3850 (while (and (not ret) (apply markdown-conditional-search-function args))
3851 (setq ret (funcall condition)))
3852 ret))
3854 (defun markdown-match-generic-metadata
3855 (regexp last &optional start-header end-header)
3856 "Match generic metadata specified by REGEXP from the point to LAST.
3857 If START-HEADER is nil, we assume metadata can only occur at the
3858 very top of a file (\"\\`\"). If END-HEADER is nil, we assume it
3859 is \"\n\n\""
3860 (let* ((header-bounds
3861 (markdown-get-match-boundaries start-header end-header last))
3862 (enclosing-header
3863 (cl-find-if ; just take first if multiple
3864 (lambda (match-bounds)
3865 (cl-destructuring-bind (begin end) (cl-second match-bounds)
3866 (and (< (point) begin)
3867 (save-excursion (re-search-forward regexp end t)))))
3868 header-bounds))
3869 (header-begin
3870 (when enclosing-header (cl-second (cl-first enclosing-header))))
3871 (header-end
3872 (when enclosing-header (cl-first (cl-second enclosing-header)))))
3873 (cond ((null enclosing-header)
3874 ;; Don't match anything outside of a header.
3875 nil)
3876 ((markdown-search-until-condition
3877 (lambda () (> (point) header-begin)) regexp (min last header-end) t)
3878 ;; If a metadata item is found, it may span several lines.
3879 (let ((key-beginning (match-beginning 1))
3880 (key-end (match-end 1))
3881 (markup-begin (match-beginning 2))
3882 (markup-end (match-end 2))
3883 (value-beginning (match-beginning 3)))
3884 (set-match-data (list key-beginning (point) ; complete metadata
3885 key-beginning key-end ; key
3886 markup-begin markup-end ; markup
3887 value-beginning (point))) ; value
3889 (t nil))))
3891 (defun markdown-match-declarative-metadata (last)
3892 "Match declarative metadata from the point to LAST."
3893 (markdown-match-generic-metadata markdown-regex-declarative-metadata last))
3895 (defun markdown-match-pandoc-metadata (last)
3896 "Match Pandoc metadata from the point to LAST."
3897 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
3899 (defun markdown-match-yaml-metadata-begin (last)
3900 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last))
3902 (defun markdown-match-yaml-metadata-end (last)
3903 (markdown-match-propertized-text 'markdown-yaml-metadata-end last))
3905 (defun markdown-match-yaml-metadata-key (last)
3906 (markdown-match-propertized-text 'markdown-metadata-key last))
3908 (defun markdown-match-inline-attributes (last)
3909 "Match inline attributes from point to LAST."
3910 (when (markdown-match-inline-generic markdown-regex-inline-attributes last)
3911 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
3912 (markdown-inline-code-at-pos-p (match-end 0))
3913 (markdown-in-comment-p))
3914 t)))
3916 (defun markdown-match-leanpub-sections (last)
3917 "Match Leanpub section markers from point to LAST."
3918 (when (markdown-match-inline-generic markdown-regex-leanpub-sections last)
3919 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
3920 (markdown-inline-code-at-pos-p (match-end 0))
3921 (markdown-in-comment-p))
3922 t)))
3924 (defun markdown-match-includes (last)
3925 "Match include statements from point to LAST.
3926 Sets match data for the following seven groups:
3927 Group 1: opening two angle brackets
3928 Group 2: opening title delimiter (optional)
3929 Group 3: title text (optional)
3930 Group 4: closing title delimiter (optional)
3931 Group 5: opening filename delimiter
3932 Group 6: filename
3933 Group 7: closing filename delimiter"
3934 (when (markdown-match-inline-generic markdown-regex-include last)
3935 (let ((valid (not (or (markdown-in-comment-p (match-beginning 0))
3936 (markdown-in-comment-p (match-end 0))
3937 (markdown-code-block-at-pos (match-beginning 0))))))
3938 (cond
3939 ;; Parentheses and maybe square brackets, but no curly braces:
3940 ;; match optional title in square brackets and file in parentheses.
3941 ((and valid (match-beginning 5)
3942 (not (match-beginning 8)))
3943 (set-match-data (list (match-beginning 1) (match-end 7)
3944 (match-beginning 1) (match-end 1)
3945 (match-beginning 2) (match-end 2)
3946 (match-beginning 3) (match-end 3)
3947 (match-beginning 4) (match-end 4)
3948 (match-beginning 5) (match-end 5)
3949 (match-beginning 6) (match-end 6)
3950 (match-beginning 7) (match-end 7))))
3951 ;; Only square brackets present: match file in square brackets.
3952 ((and valid (match-beginning 2)
3953 (not (match-beginning 5))
3954 (not (match-beginning 7)))
3955 (set-match-data (list (match-beginning 1) (match-end 4)
3956 (match-beginning 1) (match-end 1)
3957 nil nil
3958 nil nil
3959 nil nil
3960 (match-beginning 2) (match-end 2)
3961 (match-beginning 3) (match-end 3)
3962 (match-beginning 4) (match-end 4))))
3963 ;; Only curly braces present: match file in curly braces.
3964 ((and valid (match-beginning 8)
3965 (not (match-beginning 2))
3966 (not (match-beginning 5)))
3967 (set-match-data (list (match-beginning 1) (match-end 10)
3968 (match-beginning 1) (match-end 1)
3969 nil nil
3970 nil nil
3971 nil nil
3972 (match-beginning 8) (match-end 8)
3973 (match-beginning 9) (match-end 9)
3974 (match-beginning 10) (match-end 10))))
3976 ;; Not a valid match, move to next line and search again.
3977 (forward-line)
3978 (when (< (point) last)
3979 (setq valid (markdown-match-includes last)))))
3980 valid)))
3983 ;;; Markdown Font Fontification Functions =====================================
3985 (defun markdown-fontify-headings (last)
3986 "Add text properties to headings from point to LAST."
3987 (when (markdown-match-propertized-text 'markdown-heading last)
3988 (let* ((level (markdown-outline-level))
3989 (heading-face
3990 (intern (format "markdown-header-face-%d" level)))
3991 (heading-props `(face ,heading-face))
3992 (markup-props `(face markdown-header-delimiter-face
3993 ,@(when markdown-hide-markup `(display ""))))
3994 (rule-props `(face markdown-header-rule-face
3995 ,@(when markdown-hide-markup `(display "")))))
3996 (if (match-end 1)
3997 ;; Setext heading
3998 (progn (add-text-properties
3999 (match-beginning 1) (match-end 1) heading-props)
4000 (if (= level 1)
4001 (add-text-properties
4002 (match-beginning 2) (match-end 2) rule-props)
4003 (add-text-properties
4004 (match-beginning 3) (match-end 3) rule-props)))
4005 ;; atx heading
4006 (add-text-properties
4007 (match-beginning 4) (match-end 4) markup-props)
4008 (add-text-properties
4009 (match-beginning 5) (match-end 5) heading-props)
4010 (when (match-end 6)
4011 (add-text-properties
4012 (match-beginning 6) (match-end 6) markup-props))))
4015 (defun markdown-fontify-blockquotes (last)
4016 "Apply font-lock properties to blockquotes from point to LAST."
4017 (when (markdown-match-blockquotes last)
4018 (add-text-properties
4019 (match-beginning 1) (match-end 1)
4020 (if markdown-hide-markup
4021 `(face markdown-blockquote-face
4022 display ,markdown-blockquote-display-char)
4023 `(face markdown-markup-face
4024 ,@(when markdown-hide-markup
4025 `(display ,markdown-blockquote-display-char)))))
4026 (font-lock-append-text-property
4027 (match-beginning 0) (match-end 0) 'face 'markdown-blockquote-face)
4030 (defun markdown-fontify-list-items (last)
4031 "Apply font-lock properties to list markers from point to LAST."
4032 (when (markdown-match-list-items last)
4033 (let* ((indent (length (match-string-no-properties 1)))
4034 (level (/ indent 4)) ;; level = 0, 1, 2, ...
4035 (bullet (nth (mod level (length markdown-list-item-bullets))
4036 markdown-list-item-bullets)))
4037 (add-text-properties
4038 (match-beginning 2) (match-end 2) '(face markdown-list-face))
4039 (when markdown-hide-markup
4040 (cond
4041 ;; Unordered lists
4042 ((string-match-p "[\\*\\+-]" (match-string 2))
4043 (add-text-properties
4044 (match-beginning 2) (match-end 2) `(display ,bullet)))
4045 ;; Definition lists
4046 ((string-equal ":" (match-string 2))
4047 (add-text-properties
4048 (match-beginning 2) (match-end 2)
4049 `(display ,(char-to-string markdown-definition-display-char)))))))
4052 (defun markdown-fontify-hrs (last)
4053 "Add text properties to horizontal rules from point to LAST."
4054 (when (markdown-match-hr last)
4055 (add-text-properties
4056 (match-beginning 0) (match-end 0)
4057 `(face markdown-hr-face
4058 font-lock-multiline t
4059 ,@(when markdown-hide-markup
4060 `(display ,(make-string
4061 (window-body-width) markdown-hr-display-char)))))
4064 (defun markdown-fontify-sub-superscripts (last)
4065 "Apply text properties to sub- and superscripts from point to LAST."
4066 (when (markdown-search-until-condition
4067 (lambda () (and (not (markdown-code-block-at-point-p))
4068 (not (markdown-inline-code-at-point-p))
4069 (not (markdown-in-comment-p))))
4070 markdown-regex-sub-superscript last t)
4071 (let* ((subscript-p (string= (match-string 2) "~"))
4072 (index (if subscript-p 0 1))
4073 (mp (list 'face 'markdown-markup-face
4074 'invisible 'markdown-markup)))
4075 (when markdown-hide-markup
4076 (put-text-property (match-beginning 3) (match-end 3)
4077 'display
4078 (nth index markdown-sub-superscript-display)))
4079 (add-text-properties (match-beginning 2) (match-end 2) mp)
4080 (add-text-properties (match-beginning 4) (match-end 4) mp)
4081 t)))
4084 ;;; Syntax Table ==============================================================
4086 (defvar markdown-mode-syntax-table
4087 (let ((tab (make-syntax-table text-mode-syntax-table)))
4088 (modify-syntax-entry ?\" "." tab)
4089 tab)
4090 "Syntax table for `markdown-mode'.")
4093 ;;; Element Insertion =========================================================
4095 (defun markdown-ensure-blank-line-before ()
4096 "If previous line is not already blank, insert a blank line before point."
4097 (unless (bolp) (insert "\n"))
4098 (unless (or (bobp) (looking-back "\n\\s-*\n" nil)) (insert "\n")))
4100 (defun markdown-ensure-blank-line-after ()
4101 "If following line is not already blank, insert a blank line after point.
4102 Return the point where it was originally."
4103 (save-excursion
4104 (unless (eolp) (insert "\n"))
4105 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
4107 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
4108 "Insert the strings S1 and S2, wrapping around region or THING.
4109 If a region is specified by the optional BEG and END arguments,
4110 wrap the strings S1 and S2 around that region.
4111 If there is an active region, wrap the strings S1 and S2 around
4112 the region. If there is not an active region but the point is at
4113 THING, wrap that thing (which defaults to word). Otherwise, just
4114 insert S1 and S2 and place the cursor in between. Return the
4115 bounds of the entire wrapped string, or nil if nothing was wrapped
4116 and S1 and S2 were only inserted."
4117 (let (a b bounds new-point)
4118 (cond
4119 ;; Given region
4120 ((and beg end)
4121 (setq a beg
4122 b end
4123 new-point (+ (point) (length s1))))
4124 ;; Active region
4125 ((markdown-use-region-p)
4126 (setq a (region-beginning)
4127 b (region-end)
4128 new-point (+ (point) (length s1))))
4129 ;; Thing (word) at point
4130 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
4131 (setq a (car bounds)
4132 b (cdr bounds)
4133 new-point (+ (point) (length s1))))
4134 ;; No active region and no word
4136 (setq a (point)
4137 b (point))))
4138 (goto-char b)
4139 (insert s2)
4140 (goto-char a)
4141 (insert s1)
4142 (when new-point (goto-char new-point))
4143 (if (= a b)
4145 (setq b (+ b (length s1) (length s2)))
4146 (cons a b))))
4148 (defun markdown-point-after-unwrap (cur prefix suffix)
4149 "Return desired position of point after an unwrapping operation.
4150 CUR gives the position of the point before the operation.
4151 Additionally, two cons cells must be provided. PREFIX gives the
4152 bounds of the prefix string and SUFFIX gives the bounds of the
4153 suffix string."
4154 (cond ((< cur (cdr prefix)) (car prefix))
4155 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
4156 ((<= cur (cdr suffix))
4157 (- cur (+ (- (cdr prefix) (car prefix))
4158 (- cur (car suffix)))))
4159 (t cur)))
4161 (defun markdown-unwrap-thing-at-point (regexp all text)
4162 "Remove prefix and suffix of thing at point and reposition the point.
4163 When the thing at point matches REGEXP, replace the subexpression
4164 ALL with the string in subexpression TEXT. Reposition the point
4165 in an appropriate location accounting for the removal of prefix
4166 and suffix strings. Return new bounds of string from group TEXT.
4167 When REGEXP is nil, assumes match data is already set."
4168 (when (or (null regexp)
4169 (thing-at-point-looking-at regexp))
4170 (let ((cur (point))
4171 (prefix (cons (match-beginning all) (match-beginning text)))
4172 (suffix (cons (match-end text) (match-end all)))
4173 (bounds (cons (match-beginning text) (match-end text))))
4174 ;; Replace the thing at point
4175 (replace-match (match-string text) t t nil all)
4176 ;; Reposition the point
4177 (goto-char (markdown-point-after-unwrap cur prefix suffix))
4178 ;; Adjust bounds
4179 (setq bounds (cons (car prefix)
4180 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
4182 (defun markdown-unwrap-things-in-region (beg end regexp all text)
4183 "Remove prefix and suffix of all things in region from BEG to END.
4184 When a thing in the region matches REGEXP, replace the
4185 subexpression ALL with the string in subexpression TEXT.
4186 Return a cons cell containing updated bounds for the region."
4187 (save-excursion
4188 (goto-char beg)
4189 (let ((removed 0) len-all len-text)
4190 (while (re-search-forward regexp (- end removed) t)
4191 (setq len-all (length (match-string-no-properties all)))
4192 (setq len-text (length (match-string-no-properties text)))
4193 (setq removed (+ removed (- len-all len-text)))
4194 (replace-match (match-string text) t t nil all))
4195 (cons beg (- end removed)))))
4197 (defun markdown-insert-hr (arg)
4198 "Insert or replace a horizonal rule.
4199 By default, use the first element of `markdown-hr-strings'. When
4200 ARG is non-nil, as when given a prefix, select a different
4201 element as follows. When prefixed with \\[universal-argument],
4202 use the last element of `markdown-hr-strings' instead. When
4203 prefixed with an integer from 1 to the length of
4204 `markdown-hr-strings', use the element in that position instead."
4205 (interactive "*P")
4206 (when (thing-at-point-looking-at markdown-regex-hr)
4207 (delete-region (match-beginning 0) (match-end 0)))
4208 (markdown-ensure-blank-line-before)
4209 (cond ((equal arg '(4))
4210 (insert (car (reverse markdown-hr-strings))))
4211 ((and (integerp arg) (> arg 0)
4212 (<= arg (length markdown-hr-strings)))
4213 (insert (nth (1- arg) markdown-hr-strings)))
4215 (insert (car markdown-hr-strings))))
4216 (markdown-ensure-blank-line-after))
4218 (defun markdown-insert-bold ()
4219 "Insert markup to make a region or word bold.
4220 If there is an active region, make the region bold. If the point
4221 is at a non-bold word, make the word bold. If the point is at a
4222 bold word or phrase, remove the bold markup. Otherwise, simply
4223 insert bold delimiters and place the cursor in between them."
4224 (interactive)
4225 (let ((delim (if markdown-bold-underscore "__" "**")))
4226 (if (markdown-use-region-p)
4227 ;; Active region
4228 (let ((bounds (markdown-unwrap-things-in-region
4229 (region-beginning) (region-end)
4230 markdown-regex-bold 2 4)))
4231 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4232 ;; Bold markup removal, bold word at point, or empty markup insertion
4233 (if (thing-at-point-looking-at markdown-regex-bold)
4234 (markdown-unwrap-thing-at-point nil 2 4)
4235 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4237 (defun markdown-insert-italic ()
4238 "Insert markup to make a region or word italic.
4239 If there is an active region, make the region italic. If the point
4240 is at a non-italic word, make the word italic. If the point is at an
4241 italic word or phrase, remove the italic markup. Otherwise, simply
4242 insert italic delimiters and place the cursor in between them."
4243 (interactive)
4244 (let ((delim (if markdown-italic-underscore "_" "*")))
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-italic 1 3)))
4250 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4251 ;; Italic markup removal, italic word at point, or empty markup insertion
4252 (if (thing-at-point-looking-at markdown-regex-italic)
4253 (markdown-unwrap-thing-at-point nil 1 3)
4254 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4256 (defun markdown-insert-strike-through ()
4257 "Insert markup to make a region or word strikethrough.
4258 If there is an active region, make the region strikethrough. If the point
4259 is at a non-bold word, make the word strikethrough. If the point is at a
4260 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
4261 simply insert bold delimiters and place the cursor in between them."
4262 (interactive)
4263 (let ((delim "~~"))
4264 (if (markdown-use-region-p)
4265 ;; Active region
4266 (let ((bounds (markdown-unwrap-things-in-region
4267 (region-beginning) (region-end)
4268 markdown-regex-strike-through 2 4)))
4269 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4270 ;; Strikethrough markup removal, strikethrough word at point, or empty markup insertion
4271 (if (thing-at-point-looking-at markdown-regex-strike-through)
4272 (markdown-unwrap-thing-at-point nil 2 4)
4273 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4275 (defun markdown-insert-code ()
4276 "Insert markup to make a region or word an inline code fragment.
4277 If there is an active region, make the region an inline code
4278 fragment. If the point is at a word, make the word an inline
4279 code fragment. Otherwise, simply insert code delimiters and
4280 place the cursor in between them."
4281 (interactive)
4282 (if (markdown-use-region-p)
4283 ;; Active region
4284 (let ((bounds (markdown-unwrap-things-in-region
4285 (region-beginning) (region-end)
4286 markdown-regex-code 1 3)))
4287 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
4288 ;; Code markup removal, code markup for word, or empty markup insertion
4289 (if (markdown-inline-code-at-point)
4290 (markdown-unwrap-thing-at-point nil 0 2)
4291 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
4293 (defun markdown-insert-kbd ()
4294 "Insert markup to wrap region or word in <kbd> tags.
4295 If there is an active region, use the region. If the point is at
4296 a word, use the word. Otherwise, simply insert <kbd> tags and
4297 place the cursor in between them."
4298 (interactive)
4299 (if (markdown-use-region-p)
4300 ;; Active region
4301 (let ((bounds (markdown-unwrap-things-in-region
4302 (region-beginning) (region-end)
4303 markdown-regex-kbd 0 2)))
4304 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil (car bounds) (cdr bounds)))
4305 ;; Markup removal, markup for word, or empty markup insertion
4306 (if (thing-at-point-looking-at markdown-regex-kbd)
4307 (markdown-unwrap-thing-at-point nil 0 2)
4308 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil))))
4310 (defun markdown-insert-inline-link (text url &optional title)
4311 "Insert an inline link with TEXT pointing to URL.
4312 Optionally, the user can provide a TITLE."
4313 (let ((cur (point)))
4314 (setq title (and title (concat " \"" title "\"")))
4315 (insert (concat "[" text "](" url title ")"))
4316 (cond ((not text) (goto-char (+ 1 cur)))
4317 ((not url) (goto-char (+ 3 (length text) cur))))))
4319 (defun markdown-insert-inline-image (text url &optional title)
4320 "Insert an inline link with alt TEXT pointing to URL.
4321 Optionally, also provide a TITLE."
4322 (let ((cur (point)))
4323 (setq title (and title (concat " \"" title "\"")))
4324 (insert (concat "![" text "](" url title ")"))
4325 (cond ((not text) (goto-char (+ 2 cur)))
4326 ((not url) (goto-char (+ 4 (length text) cur))))))
4328 (defun markdown-insert-reference-link (text label &optional url title)
4329 "Insert a reference link and, optionally, a reference definition.
4330 The link TEXT will be inserted followed by the optional LABEL.
4331 If a URL is given, also insert a definition for the reference
4332 LABEL according to `markdown-reference-location'. If a TITLE is
4333 given, it will be added to the end of the reference definition
4334 and will be used to populate the title attribute when converted
4335 to XHTML. If URL is nil, insert only the link portion (for
4336 example, when a reference label is already defined)."
4337 (insert (concat "[" text "][" label "]"))
4338 (when url
4339 (markdown-insert-reference-definition
4340 (if (string-equal label "") text label)
4341 url title)))
4343 (defun markdown-insert-reference-image (text label &optional url title)
4344 "Insert a reference image and, optionally, a reference definition.
4345 The alt TEXT will be inserted followed by the optional LABEL.
4346 If a URL is given, also insert a definition for the reference
4347 LABEL according to `markdown-reference-location'. If a TITLE is
4348 given, it will be added to the end of the reference definition
4349 and will be used to populate the title attribute when converted
4350 to XHTML. If URL is nil, insert only the link portion (for
4351 example, when a reference label is already defined)."
4352 (insert (concat "![" text "][" label "]"))
4353 (when url
4354 (markdown-insert-reference-definition
4355 (if (string-equal label "") text label)
4356 url title)))
4358 (defun markdown-insert-reference-definition (label &optional url title)
4359 "Add definition for reference LABEL with URL and TITLE.
4360 LABEL is a Markdown reference label without square brackets.
4361 URL and TITLE are optional. When given, the TITLE will
4362 be used to populate the title attribute when converted to XHTML."
4363 ;; END specifies where to leave the point upon return
4364 (let ((end (point)))
4365 (cl-case markdown-reference-location
4366 (end (goto-char (point-max)))
4367 (immediately (markdown-end-of-text-block))
4368 (subtree (markdown-end-of-subtree))
4369 (header (markdown-end-of-defun)))
4370 (unless (or (markdown-cur-line-blank-p)
4371 (thing-at-point-looking-at markdown-regex-reference-definition))
4372 (insert "\n"))
4373 (insert "\n[" label "]: ")
4374 (if url
4375 (insert url)
4376 ;; When no URL is given, leave cursor at END following the colon
4377 (setq end (point)))
4378 (when (> (length title) 0)
4379 (insert " \"" title "\""))
4380 (unless (looking-at-p "\n")
4381 (insert "\n"))
4382 (goto-char end)
4383 (when url
4384 (message
4385 (markdown--substitute-command-keys
4386 "Reference [%s] was defined, press \\[markdown-do] to jump there")
4387 label))))
4389 (define-obsolete-function-alias
4390 'markdown-insert-inline-link-dwim 'markdown-insert-link "v2.3")
4391 (define-obsolete-function-alias
4392 'markdown-insert-reference-link-dwim 'markdown-insert-link "v2.3")
4394 (defun markdown--insert-link-or-image (image)
4395 "Interactively insert new or update an existing link or image.
4396 When IMAGE is non-nil, insert an image. Otherwise, insert a link.
4397 This is an internal function called by
4398 `markdown-insert-link' and `markdown-insert-image'."
4399 (cl-multiple-value-bind (begin end text uri ref title)
4400 (if (markdown-use-region-p)
4401 ;; Use region as either link text or URL as appropriate.
4402 (let ((region (buffer-substring-no-properties
4403 (region-beginning) (region-end))))
4404 (if (string-match markdown-regex-uri region)
4405 ;; Region contains a URL; use it as such.
4406 (list (region-beginning) (region-end)
4407 nil (match-string 0 region) nil nil)
4408 ;; Region doesn't contain a URL, so use it as text.
4409 (list (region-beginning) (region-end)
4410 region nil nil nil)))
4411 ;; Extract and use properties of existing link, if any.
4412 (markdown-link-at-pos (point)))
4413 (let* ((ref (when ref (concat "[" ref "]")))
4414 (defined-refs (append
4415 (mapcar (lambda (ref) (concat "[" ref "]"))
4416 (markdown-get-defined-references))))
4417 (used-uris (markdown-get-used-uris))
4418 (uri-or-ref (completing-read
4419 "URL or [reference]: "
4420 (append defined-refs used-uris)
4421 nil nil (or uri ref)))
4422 (ref (cond ((string-match "\\`\\[\\(.*\\)\\]\\'" uri-or-ref)
4423 (match-string 1 uri-or-ref))
4424 ((string-equal "" uri-or-ref)
4425 "")))
4426 (uri (unless ref uri-or-ref))
4427 (text-prompt (if image
4428 "Alt text: "
4429 (if ref
4430 "Link text: "
4431 "Link text (blank for plain URL): ")))
4432 (text (read-string text-prompt text))
4433 (text (if (= (length text) 0) nil text))
4434 (plainp (and uri (not text)))
4435 (implicitp (string-equal ref ""))
4436 (ref (if implicitp text ref))
4437 (definedp (and ref (markdown-reference-definition ref)))
4438 (ref-url (unless (or uri definedp)
4439 (completing-read "Reference URL: " used-uris)))
4440 (title (unless (or plainp definedp)
4441 (read-string "Title (tooltip text, optional): " title)))
4442 (title (if (= (length title) 0) nil title)))
4443 (when (and image implicitp)
4444 (user-error "Reference required: implicit image references are invalid"))
4445 (when (and begin end)
4446 (delete-region begin end))
4447 (cond
4448 ((and (not image) uri text)
4449 (markdown-insert-inline-link text uri title))
4450 ((and image uri text)
4451 (markdown-insert-inline-image text uri title))
4452 ((and ref text)
4453 (if image
4454 (markdown-insert-reference-image text (unless implicitp ref) nil title)
4455 (markdown-insert-reference-link text (unless implicitp ref) nil title))
4456 (unless definedp
4457 (markdown-insert-reference-definition ref ref-url title)))
4458 ((and (not image) uri)
4459 (markdown-insert-uri uri))))))
4461 (defun markdown-insert-link ()
4462 "Insert new or update an existing link, with interactive prompts.
4463 If the point is at an existing link or URL, update the link text,
4464 URL, reference label, and/or title. Otherwise, insert a new link.
4465 The type of link inserted (inline, reference, or plain URL)
4466 depends on which values are provided:
4468 * If a URL and TEXT are given, insert an inline link: [TEXT](URL).
4469 * If [REF] and TEXT are given, insert a reference link: [TEXT][REF].
4470 * If only TEXT is given, insert an implicit reference link: [TEXT][].
4471 * If only a URL is given, insert a plain link: <URL>.
4473 In other words, to create an implicit reference link, leave the
4474 URL prompt empty and to create a plain URL link, leave the link
4475 text empty.
4477 If there is an active region, use the text as the default URL, if
4478 it seems to be a URL, or link text value otherwise.
4480 If a given reference is not defined, this function will
4481 additionally prompt for the URL and optional title. In this case,
4482 the reference definition is placed at the location determined by
4483 `markdown-reference-location'.
4485 Through updating the link, this function can be used to convert a
4486 link of one type (inline, reference, or plain) to another type by
4487 selectively adding or removing information via the prompts."
4488 (interactive)
4489 (markdown--insert-link-or-image nil))
4491 (defun markdown-insert-image ()
4492 "Insert new or update an existing image, with interactive prompts.
4493 If the point is at an existing image, update the alt text, URL,
4494 reference label, and/or title. Otherwise, insert a new image.
4495 The type of image inserted (inline or reference) depends on which
4496 values are provided:
4498 * If a URL and ALT-TEXT are given, insert an inline image:
4499 ![ALT-TEXT](URL).
4500 * If [REF] and ALT-TEXT are given, insert a reference image:
4501 ![ALT-TEXT][REF].
4503 If there is an active region, use the text as the default URL, if
4504 it seems to be a URL, or alt text value otherwise.
4506 If a given reference is not defined, this function will
4507 additionally prompt for the URL and optional title. In this case,
4508 the reference definition is placed at the location determined by
4509 `markdown-reference-location'.
4511 Through updating the image, this function can be used to convert an
4512 image of one type (inline or reference) to another type by
4513 selectively adding or removing information via the prompts."
4514 (interactive)
4515 (markdown--insert-link-or-image t))
4517 (defun markdown-insert-uri (&optional uri)
4518 "Insert markup for an inline URI.
4519 If there is an active region, use it as the URI. If the point is
4520 at a URI, wrap it with angle brackets. If the point is at an
4521 inline URI, remove the angle brackets. Otherwise, simply insert
4522 angle brackets place the point between them."
4523 (interactive)
4524 (if (markdown-use-region-p)
4525 ;; Active region
4526 (let ((bounds (markdown-unwrap-things-in-region
4527 (region-beginning) (region-end)
4528 markdown-regex-angle-uri 0 2)))
4529 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
4530 ;; Markup removal, URI at point, new URI, or empty markup insertion
4531 (if (thing-at-point-looking-at markdown-regex-angle-uri)
4532 (markdown-unwrap-thing-at-point nil 0 2)
4533 (if uri
4534 (insert "<" uri ">")
4535 (markdown-wrap-or-insert "<" ">" 'url nil nil)))))
4537 (defun markdown-insert-wiki-link ()
4538 "Insert a wiki link of the form [[WikiLink]].
4539 If there is an active region, use the region as the link text.
4540 If the point is at a word, use the word as the link text. If
4541 there is no active region and the point is not at word, simply
4542 insert link markup."
4543 (interactive)
4544 (if (markdown-use-region-p)
4545 ;; Active region
4546 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
4547 ;; Markup removal, wiki link at at point, or empty markup insertion
4548 (if (thing-at-point-looking-at markdown-regex-wiki-link)
4549 (if (or markdown-wiki-link-alias-first
4550 (null (match-string 5)))
4551 (markdown-unwrap-thing-at-point nil 1 3)
4552 (markdown-unwrap-thing-at-point nil 1 5))
4553 (markdown-wrap-or-insert "[[" "]]"))))
4555 (defun markdown-remove-header ()
4556 "Remove header markup if point is at a header.
4557 Return bounds of remaining header text if a header was removed
4558 and nil otherwise."
4559 (interactive "*")
4560 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
4561 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
4563 (defun markdown-insert-header (&optional level text setext)
4564 "Insert or replace header markup.
4565 The level of the header is specified by LEVEL and header text is
4566 given by TEXT. LEVEL must be an integer from 1 and 6, and the
4567 default value is 1.
4568 When TEXT is nil, the header text is obtained as follows.
4569 If there is an active region, it is used as the header text.
4570 Otherwise, the current line will be used as the header text.
4571 If there is not an active region and the point is at a header,
4572 remove the header markup and replace with level N header.
4573 Otherwise, insert empty header markup and place the cursor in
4574 between.
4575 The style of the header will be atx (hash marks) unless
4576 SETEXT is non-nil, in which case a setext-style (underlined)
4577 header will be inserted."
4578 (interactive "p\nsHeader text: ")
4579 (setq level (min (max (or level 1) 1) (if setext 2 6)))
4580 ;; Determine header text if not given
4581 (when (null text)
4582 (if (markdown-use-region-p)
4583 ;; Active region
4584 (setq text (delete-and-extract-region (region-beginning) (region-end)))
4585 ;; No active region
4586 (markdown-remove-header)
4587 (setq text (delete-and-extract-region
4588 (line-beginning-position) (line-end-position)))
4589 (when (and setext (string-match-p "^[ \t]*$" text))
4590 (setq text (read-string "Header text: "))))
4591 (setq text (markdown-compress-whitespace-string text)))
4592 ;; Insertion with given text
4593 (markdown-ensure-blank-line-before)
4594 (let (hdr)
4595 (cond (setext
4596 (setq hdr (make-string (string-width text) (if (= level 2) ?- ?=)))
4597 (insert text "\n" hdr))
4599 (setq hdr (make-string level ?#))
4600 (insert hdr " " text)
4601 (when (null markdown-asymmetric-header) (insert " " hdr)))))
4602 (markdown-ensure-blank-line-after)
4603 ;; Leave point at end of text
4604 (cond (setext
4605 (backward-char (1+ (string-width text))))
4606 ((null markdown-asymmetric-header)
4607 (backward-char (1+ level)))))
4609 (defun markdown-insert-header-dwim (&optional arg setext)
4610 "Insert or replace header markup.
4611 The level and type of the header are determined automatically by
4612 the type and level of the previous header, unless a prefix
4613 argument is given via ARG.
4614 With a numeric prefix valued 1 to 6, insert a header of the given
4615 level, with the type being determined automatically (note that
4616 only level 1 or 2 setext headers are possible).
4618 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
4619 promote the heading by one level.
4620 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
4621 demote the heading by one level.
4622 When SETEXT is non-nil, prefer setext-style headers when
4623 possible (levels one and two).
4625 When there is an active region, use it for the header text. When
4626 the point is at an existing header, change the type and level
4627 according to the rules above.
4628 Otherwise, if the line is not empty, create a header using the
4629 text on the current line as the header text.
4630 Finally, if the point is on a blank line, insert empty header
4631 markup (atx) or prompt for text (setext).
4632 See `markdown-insert-header' for more details about how the
4633 header text is determined."
4634 (interactive "*P")
4635 (let (level)
4636 (save-excursion
4637 (when (or (thing-at-point-looking-at markdown-regex-header)
4638 (re-search-backward markdown-regex-header nil t))
4639 ;; level of current or previous header
4640 (setq level (markdown-outline-level))
4641 ;; match group 1 indicates a setext header
4642 (setq setext (match-end 1))))
4643 ;; check prefix argument
4644 (cond
4645 ((and (equal arg '(4)) level (> level 1)) ;; C-u
4646 (cl-decf level))
4647 ((and (equal arg '(16)) level (< level 6)) ;; C-u C-u
4648 (cl-incf level))
4649 (arg ;; numeric prefix
4650 (setq level (prefix-numeric-value arg))))
4651 ;; setext headers must be level one or two
4652 (and level (setq setext (and setext (<= level 2))))
4653 ;; insert the heading
4654 (markdown-insert-header level nil setext)))
4656 (defun markdown-insert-header-setext-dwim (&optional arg)
4657 "Insert or replace header markup, with preference for setext.
4658 See `markdown-insert-header-dwim' for details, including how ARG is handled."
4659 (interactive "*P")
4660 (markdown-insert-header-dwim arg t))
4662 (defun markdown-insert-header-atx-1 ()
4663 "Insert a first level atx-style (hash mark) header.
4664 See `markdown-insert-header'."
4665 (interactive "*")
4666 (markdown-insert-header 1 nil nil))
4668 (defun markdown-insert-header-atx-2 ()
4669 "Insert a level two atx-style (hash mark) header.
4670 See `markdown-insert-header'."
4671 (interactive "*")
4672 (markdown-insert-header 2 nil nil))
4674 (defun markdown-insert-header-atx-3 ()
4675 "Insert a level three atx-style (hash mark) header.
4676 See `markdown-insert-header'."
4677 (interactive "*")
4678 (markdown-insert-header 3 nil nil))
4680 (defun markdown-insert-header-atx-4 ()
4681 "Insert a level four atx-style (hash mark) header.
4682 See `markdown-insert-header'."
4683 (interactive "*")
4684 (markdown-insert-header 4 nil nil))
4686 (defun markdown-insert-header-atx-5 ()
4687 "Insert a level five atx-style (hash mark) header.
4688 See `markdown-insert-header'."
4689 (interactive "*")
4690 (markdown-insert-header 5 nil nil))
4692 (defun markdown-insert-header-atx-6 ()
4693 "Insert a sixth level atx-style (hash mark) header.
4694 See `markdown-insert-header'."
4695 (interactive "*")
4696 (markdown-insert-header 6 nil nil))
4698 (defun markdown-insert-header-setext-1 ()
4699 "Insert a setext-style (underlined) first-level header.
4700 See `markdown-insert-header'."
4701 (interactive "*")
4702 (markdown-insert-header 1 nil t))
4704 (defun markdown-insert-header-setext-2 ()
4705 "Insert a setext-style (underlined) second-level header.
4706 See `markdown-insert-header'."
4707 (interactive "*")
4708 (markdown-insert-header 2 nil t))
4710 (defun markdown-blockquote-indentation (loc)
4711 "Return string containing necessary indentation for a blockquote at LOC.
4712 Also see `markdown-pre-indentation'."
4713 (save-excursion
4714 (goto-char loc)
4715 (let* ((list-level (length (markdown-calculate-list-levels)))
4716 (indent ""))
4717 (dotimes (_ list-level indent)
4718 (setq indent (concat indent " "))))))
4720 (defun markdown-insert-blockquote ()
4721 "Start a blockquote section (or blockquote the region).
4722 If Transient Mark mode is on and a region is active, it is used as
4723 the blockquote text."
4724 (interactive)
4725 (if (markdown-use-region-p)
4726 (markdown-blockquote-region (region-beginning) (region-end))
4727 (markdown-ensure-blank-line-before)
4728 (insert (markdown-blockquote-indentation (point)) "> ")
4729 (markdown-ensure-blank-line-after)))
4731 (defun markdown-block-region (beg end prefix)
4732 "Format the region using a block prefix.
4733 Arguments BEG and END specify the beginning and end of the
4734 region. The characters PREFIX will appear at the beginning
4735 of each line."
4736 (save-excursion
4737 (let* ((end-marker (make-marker))
4738 (beg-marker (make-marker)))
4739 ;; Ensure blank line after and remove extra whitespace
4740 (goto-char end)
4741 (skip-syntax-backward "-")
4742 (set-marker end-marker (point))
4743 (delete-horizontal-space)
4744 (markdown-ensure-blank-line-after)
4745 ;; Ensure blank line before and remove extra whitespace
4746 (goto-char beg)
4747 (skip-syntax-forward "-")
4748 (delete-horizontal-space)
4749 (markdown-ensure-blank-line-before)
4750 (set-marker beg-marker (point))
4751 ;; Insert PREFIX before each line
4752 (goto-char beg-marker)
4753 (while (and (< (line-beginning-position) end-marker)
4754 (not (eobp)))
4755 (insert prefix)
4756 (forward-line)))))
4758 (defun markdown-blockquote-region (beg end)
4759 "Blockquote the region.
4760 Arguments BEG and END specify the beginning and end of the region."
4761 (interactive "*r")
4762 (markdown-block-region
4763 beg end (concat (markdown-blockquote-indentation
4764 (max (point-min) (1- beg))) "> ")))
4766 (defun markdown-pre-indentation (loc)
4767 "Return string containing necessary whitespace for a pre block at LOC.
4768 Also see `markdown-blockquote-indentation'."
4769 (save-excursion
4770 (goto-char loc)
4771 (let* ((list-level (length (markdown-calculate-list-levels)))
4772 indent)
4773 (dotimes (_ (1+ list-level) indent)
4774 (setq indent (concat indent " "))))))
4776 (defun markdown-insert-pre ()
4777 "Start a preformatted section (or apply to the region).
4778 If Transient Mark mode is on and a region is active, it is marked
4779 as preformatted text."
4780 (interactive)
4781 (if (markdown-use-region-p)
4782 (markdown-pre-region (region-beginning) (region-end))
4783 (markdown-ensure-blank-line-before)
4784 (insert (markdown-pre-indentation (point)))
4785 (markdown-ensure-blank-line-after)))
4787 (defun markdown-pre-region (beg end)
4788 "Format the region as preformatted text.
4789 Arguments BEG and END specify the beginning and end of the region."
4790 (interactive "*r")
4791 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
4792 (markdown-block-region beg end indent)))
4794 (defun markdown-electric-backquote (arg)
4795 "Insert a backquote.
4796 The numeric prefix argument ARG says how many times to repeat the insertion.
4797 Call `markdown-insert-gfm-code-block' interactively
4798 if three backquotes inserted at the beginning of line."
4799 (interactive "*P")
4800 (self-insert-command (prefix-numeric-value arg))
4801 (when (and markdown-gfm-use-electric-backquote (looking-back "^```" nil))
4802 (replace-match "")
4803 (call-interactively #'markdown-insert-gfm-code-block)))
4805 (defconst markdown-gfm-recognized-languages
4806 ;; To reproduce/update, evaluate the let-form in
4807 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
4808 ;; but with appropriate use of a keyboard macro, indenting and filling it
4809 ;; properly is pretty fast.
4810 '("1C-Enterprise" "ABAP" "ABNF" "AGS-Script" "AMPL" "ANTLR"
4811 "API-Blueprint" "APL" "ASN.1" "ASP" "ATS" "ActionScript" "Ada" "Agda"
4812 "Alloy" "Alpine-Abuild" "Ant-Build-System" "ApacheConf" "Apex"
4813 "Apollo-Guidance-Computer" "AppleScript" "Arc" "Arduino" "AsciiDoc"
4814 "AspectJ" "Assembly" "Augeas" "AutoHotkey" "AutoIt" "Awk" "Batchfile"
4815 "Befunge" "Bison" "BitBake" "Blade" "BlitzBasic" "BlitzMax" "Bluespec"
4816 "Boo" "Brainfuck" "Brightscript" "Bro" "C#" "C++" "C-ObjDump"
4817 "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "COLLADA" "CSON" "CSS" "CSV"
4818 "CWeb" "Cap'n-Proto" "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK"
4819 "Cirru" "Clarion" "Clean" "Click" "Clojure" "Closure-Templates"
4820 "CoffeeScript" "ColdFusion" "ColdFusion-CFC" "Common-Lisp"
4821 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal"
4822 "Csound" "Csound-Document" "Csound-Score" "Cuda" "Cycript" "Cython"
4823 "D-ObjDump" "DIGITAL-Command-Language" "DM" "DNS-Zone" "DTrace"
4824 "Darcs-Patch" "Dart" "Diff" "Dockerfile" "Dogescript" "Dylan" "EBNF"
4825 "ECL" "ECLiPSe" "EJS" "EQ" "Eagle" "Ecere-Projects" "Eiffel" "Elixir"
4826 "Elm" "Emacs-Lisp" "EmberScript" "Erlang" "F#" "FLUX" "Factor" "Fancy"
4827 "Fantom" "Filebench-WML" "Filterscript" "Formatted" "Forth" "Fortran"
4828 "FreeMarker" "Frege" "G-code" "GAMS" "GAP" "GCC-Machine-Description"
4829 "GDB" "GDScript" "GLSL" "GN" "Game-Maker-Language" "Genie" "Genshi"
4830 "Gentoo-Ebuild" "Gentoo-Eclass" "Gettext-Catalog" "Gherkin" "Glyph"
4831 "Gnuplot" "Go" "Golo" "Gosu" "Grace" "Gradle" "Grammatical-Framework"
4832 "Graph-Modeling-Language" "GraphQL" "Graphviz-(DOT)" "Groovy"
4833 "Groovy-Server-Pages" "HCL" "HLSL" "HTML" "HTML+Django" "HTML+ECR"
4834 "HTML+EEX" "HTML+ERB" "HTML+PHP" "HTTP" "Hack" "Haml" "Handlebars"
4835 "Harbour" "Haskell" "Haxe" "Hy" "HyPhy" "IDL" "IGOR-Pro" "INI"
4836 "IRC-log" "Idris" "Inform-7" "Inno-Setup" "Io" "Ioke" "Isabelle"
4837 "Isabelle-ROOT" "JFlex" "JSON" "JSON5" "JSONLD" "JSONiq" "JSX"
4838 "Jasmin" "Java" "Java-Server-Pages" "JavaScript" "Jison" "Jison-Lex"
4839 "Jolie" "Julia" "Jupyter-Notebook" "KRL" "KiCad" "Kit" "Kotlin" "LFE"
4840 "LLVM" "LOLCODE" "LSL" "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex"
4841 "LilyPond" "Limbo" "Linker-Script" "Linux-Kernel-Module" "Liquid"
4842 "Literate-Agda" "Literate-CoffeeScript" "Literate-Haskell"
4843 "LiveScript" "Logos" "Logtalk" "LookML" "LoomScript" "Lua" "M4"
4844 "M4Sugar" "MAXScript" "MQL4" "MQL5" "MTML" "MUF" "Makefile" "Mako"
4845 "Markdown" "Marko" "Mask" "Mathematica" "Matlab" "Maven-POM" "Max"
4846 "MediaWiki" "Mercury" "Meson" "Metal" "MiniD" "Mirah" "Modelica"
4847 "Modula-2" "Module-Management-System" "Monkey" "Moocode" "MoonScript"
4848 "Myghty" "NCL" "NL" "NSIS" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo"
4849 "NewLisp" "Nginx" "Nim" "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml"
4850 "ObjDump" "Objective-C" "Objective-C++" "Objective-J" "Omgrofl" "Opa"
4851 "Opal" "OpenCL" "OpenEdge-ABL" "OpenRC-runscript" "OpenSCAD"
4852 "OpenType-Feature-File" "Org" "Ox" "Oxygene" "Oz" "P4" "PAWN" "PHP"
4853 "PLSQL" "PLpgSQL" "POV-Ray-SDL" "Pan" "Papyrus" "Parrot"
4854 "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal" "Pep8"
4855 "Perl" "Perl6" "Pic" "Pickle" "PicoLisp" "PigLatin" "Pike" "Pod"
4856 "PogoScript" "Pony" "PostScript" "PowerBuilder" "PowerShell"
4857 "Processing" "Prolog" "Propeller-Spin" "Protocol-Buffer" "Public-Key"
4858 "Pug" "Puppet" "Pure-Data" "PureBasic" "PureScript" "Python"
4859 "Python-console" "Python-traceback" "QML" "QMake" "RAML" "RDoc"
4860 "REALbasic" "REXX" "RHTML" "RMarkdown" "RPM-Spec" "RUNOFF" "Racket"
4861 "Ragel" "Rascal" "Raw-token-data" "Reason" "Rebol" "Red" "Redcode"
4862 "Regular-Expression" "Ren'Py" "RenderScript" "RobotFramework" "Roff"
4863 "Rouge" "Ruby" "Rust" "SAS" "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL"
4864 "SRecode-Template" "STON" "SVG" "Sage" "SaltStack" "Sass" "Scala"
4865 "Scaml" "Scheme" "Scilab" "Self" "ShaderLab" "Shell" "ShellSession"
4866 "Shen" "Slash" "Slim" "Smali" "Smalltalk" "Smarty" "SourcePawn"
4867 "Spline-Font-Database" "Squirrel" "Stan" "Standard-ML" "Stata"
4868 "Stylus" "SubRip-Text" "Sublime-Text-Config" "SuperCollider" "Swift"
4869 "SystemVerilog" "TI-Program" "TLA" "TOML" "TXL" "Tcl" "Tcsh" "TeX"
4870 "Tea" "Terra" "Text" "Textile" "Thrift" "Turing" "Turtle" "Twig"
4871 "Type-Language" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset"
4872 "Unix-Assembly" "Uno" "UnrealScript" "UrWeb" "VCL" "VHDL" "Vala"
4873 "Verilog" "Vim-script" "Visual-Basic" "Volt" "Vue"
4874 "Wavefront-Material" "Wavefront-Object" "Web-Ontology-Language"
4875 "WebAssembly" "WebIDL" "World-of-Warcraft-Addon-Data" "X10" "XC"
4876 "XCompose" "XML" "XPages" "XProc" "XQuery" "XS" "XSLT" "Xojo" "Xtend"
4877 "YAML" "YANG" "Yacc" "Zephir" "Zimpl" "desktop" "eC" "edn" "fish"
4878 "mupad" "nesC" "ooc" "reStructuredText" "wisp" "xBase")
4879 "Language specifiers recognized by GitHub's syntax highlighting features.")
4881 (defvar markdown-gfm-used-languages nil
4882 "Language names used in GFM code blocks.")
4883 (make-variable-buffer-local 'markdown-gfm-used-languages)
4885 (defun markdown-trim-whitespace (str)
4886 (markdown-replace-regexp-in-string
4887 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str))
4889 (defun markdown-clean-language-string (str)
4890 (markdown-replace-regexp-in-string
4891 "{\\.?\\|}" "" (markdown-trim-whitespace str)))
4893 (defun markdown-validate-language-string (widget)
4894 (let ((str (widget-value widget)))
4895 (unless (string= str (markdown-clean-language-string str))
4896 (widget-put widget :error (format "Invalid language spec: '%s'" str))
4897 widget)))
4899 (defun markdown-gfm-get-corpus ()
4900 "Create corpus of recognized GFM code block languages for the given buffer."
4901 (let ((given-corpus (append markdown-gfm-additional-languages
4902 markdown-gfm-recognized-languages)))
4903 (append
4904 markdown-gfm-used-languages
4905 (if markdown-gfm-downcase-languages (cl-mapcar #'downcase given-corpus)
4906 given-corpus))))
4908 (defun markdown-gfm-add-used-language (lang)
4909 "Clean LANG and add to list of used languages."
4910 (setq markdown-gfm-used-languages
4911 (cons lang (remove lang markdown-gfm-used-languages))))
4913 (defcustom markdown-spaces-after-code-fence 1
4914 "Number of space characters to insert after a code fence.
4915 \\<gfm-mode-map>\\[markdown-insert-gfm-code-block] inserts this many spaces between an
4916 opening code fence and an info string."
4917 :group 'markdown
4918 :type 'integer
4919 :safe #'natnump
4920 :package-version '(markdown-mode . "2.3"))
4922 (defun markdown-insert-gfm-code-block (&optional lang)
4923 "Insert GFM code block for language LANG.
4924 If LANG is nil, the language will be queried from user. If a
4925 region is active, wrap this region with the markup instead. If
4926 the region boundaries are not on empty lines, these are added
4927 automatically in order to have the correct markup."
4928 (interactive
4929 (list (let ((completion-ignore-case nil))
4930 (condition-case nil
4931 (markdown-clean-language-string
4932 (completing-read
4933 "Programming language: "
4934 (markdown-gfm-get-corpus)
4935 nil 'confirm (car markdown-gfm-used-languages)
4936 'markdown-gfm-language-history))
4937 (quit "")))))
4938 (unless (string= lang "") (markdown-gfm-add-used-language lang))
4939 (when (> (length lang) 0)
4940 (setq lang (concat (make-string markdown-spaces-after-code-fence ?\s)
4941 lang)))
4942 (if (markdown-use-region-p)
4943 (let* ((b (region-beginning)) (e (region-end))
4944 (indent (progn (goto-char b) (current-indentation))))
4945 (goto-char e)
4946 ;; if we're on a blank line, don't newline, otherwise the ```
4947 ;; should go on its own line
4948 (unless (looking-back "\n" nil)
4949 (newline))
4950 (indent-to indent)
4951 (insert "```")
4952 (markdown-ensure-blank-line-after)
4953 (goto-char b)
4954 ;; if we're on a blank line, insert the quotes here, otherwise
4955 ;; add a new line first
4956 (unless (looking-at-p "\n")
4957 (newline)
4958 (forward-line -1))
4959 (markdown-ensure-blank-line-before)
4960 (indent-to indent)
4961 (insert "```" lang))
4962 (let ((indent (current-indentation)))
4963 (delete-horizontal-space :backward-only)
4964 (markdown-ensure-blank-line-before)
4965 (indent-to indent)
4966 (insert "```" lang "\n")
4967 (indent-to indent)
4968 (insert ?\n)
4969 (indent-to indent)
4970 (insert "```")
4971 (markdown-ensure-blank-line-after))
4972 (end-of-line 0)))
4974 (defun markdown-code-block-lang (&optional pos-prop)
4975 "Return the language name for a GFM or tilde fenced code block.
4976 The beginning of the block may be described by POS-PROP,
4977 a cons of (pos . prop) giving the position and property
4978 at the beginning of the block."
4979 (or pos-prop
4980 (setq pos-prop
4981 (markdown-max-of-seq
4982 #'car
4983 (cl-remove-if
4984 #'null
4985 (cl-mapcar
4986 #'markdown-find-previous-prop
4987 (markdown-get-fenced-block-begin-properties))))))
4988 (when pos-prop
4989 (goto-char (car pos-prop))
4990 (set-match-data (get-text-property (point) (cdr pos-prop)))
4991 ;; Note: Hard-coded group number assumes tilde
4992 ;; and GFM fenced code regexp groups agree.
4993 (let ((begin (match-beginning 3))
4994 (end (match-end 3)))
4995 (when (and begin end)
4996 ;; Fix language strings beginning with periods, like ".ruby".
4997 (when (eq (char-after begin) ?.)
4998 (setq begin (1+ begin)))
4999 (buffer-substring-no-properties begin end)))))
5001 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer)
5002 (with-current-buffer (or buffer (current-buffer))
5003 (save-excursion
5004 (goto-char (point-min))
5005 (cl-loop
5006 with prop = 'markdown-gfm-block-begin
5007 for pos-prop = (markdown-find-next-prop prop)
5008 while pos-prop
5009 for lang = (markdown-code-block-lang pos-prop)
5010 do (progn (when lang (markdown-gfm-add-used-language lang))
5011 (goto-char (next-single-property-change (point) prop)))))))
5014 ;;; Footnotes ==================================================================
5016 (defun markdown-footnote-counter-inc ()
5017 "Increment `markdown-footnote-counter' and return the new value."
5018 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
5019 (save-excursion
5020 (goto-char (point-min))
5021 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
5022 (point-max) t)
5023 (let ((fn (string-to-number (match-string 1))))
5024 (when (> fn markdown-footnote-counter)
5025 (setq markdown-footnote-counter fn))))))
5026 (cl-incf markdown-footnote-counter))
5028 (defun markdown-insert-footnote ()
5029 "Insert footnote with a new number and move point to footnote definition."
5030 (interactive)
5031 (let ((fn (markdown-footnote-counter-inc)))
5032 (insert (format "[^%d]" fn))
5033 (markdown-footnote-text-find-new-location)
5034 (markdown-ensure-blank-line-before)
5035 (unless (markdown-cur-line-blank-p)
5036 (insert "\n"))
5037 (insert (format "[^%d]: " fn))
5038 (markdown-ensure-blank-line-after)))
5040 (defun markdown-footnote-text-find-new-location ()
5041 "Position the cursor at the proper location for a new footnote text."
5042 (cond
5043 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
5044 ((eq markdown-footnote-location 'immediately) (markdown-end-of-text-block))
5045 ((eq markdown-footnote-location 'subtree) (markdown-end-of-subtree))
5046 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
5048 (defun markdown-footnote-kill ()
5049 "Kill the footnote at point.
5050 The footnote text is killed (and added to the kill ring), the
5051 footnote marker is deleted. Point has to be either at the
5052 footnote marker or in the footnote text."
5053 (interactive)
5054 (let ((marker-pos nil)
5055 (skip-deleting-marker nil)
5056 (starting-footnote-text-positions
5057 (markdown-footnote-text-positions)))
5058 (when starting-footnote-text-positions
5059 ;; We're starting in footnote text, so mark our return position and jump
5060 ;; to the marker if possible.
5061 (let ((marker-pos (markdown-footnote-find-marker
5062 (cl-first starting-footnote-text-positions))))
5063 (if marker-pos
5064 (goto-char (1- marker-pos))
5065 ;; If there isn't a marker, we still want to kill the text.
5066 (setq skip-deleting-marker t))))
5067 ;; Either we didn't start in the text, or we started in the text and jumped
5068 ;; to the marker. We want to assume we're at the marker now and error if
5069 ;; we're not.
5070 (unless skip-deleting-marker
5071 (let ((marker (markdown-footnote-delete-marker)))
5072 (unless marker
5073 (error "Not at a footnote"))
5074 ;; Even if we knew the text position before, it changed when we deleted
5075 ;; the label.
5076 (setq marker-pos (cl-second marker))
5077 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker))))
5078 (unless new-text-pos
5079 (error "No text for footnote `%s'" (cl-first marker)))
5080 (goto-char new-text-pos))))
5081 (let ((pos (markdown-footnote-kill-text)))
5082 (goto-char (if starting-footnote-text-positions
5084 marker-pos)))))
5086 (defun markdown-footnote-delete-marker ()
5087 "Delete a footnote marker at point.
5088 Returns a list (ID START) containing the footnote ID and the
5089 start position of the marker before deletion. If no footnote
5090 marker was deleted, this function returns NIL."
5091 (let ((marker (markdown-footnote-marker-positions)))
5092 (when marker
5093 (delete-region (cl-second marker) (cl-third marker))
5094 (butlast marker))))
5096 (defun markdown-footnote-kill-text ()
5097 "Kill footnote text at point.
5098 Returns the start position of the footnote text before deletion,
5099 or NIL if point was not inside a footnote text.
5101 The killed text is placed in the kill ring (without the footnote
5102 number)."
5103 (let ((fn (markdown-footnote-text-positions)))
5104 (when fn
5105 (let ((text (delete-and-extract-region (cl-second fn) (cl-third fn))))
5106 (string-match (concat "\\[\\" (cl-first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
5107 (kill-new (match-string 1 text))
5108 (when (and (markdown-cur-line-blank-p)
5109 (markdown-prev-line-blank-p)
5110 (not (bobp)))
5111 (delete-region (1- (point)) (point)))
5112 (cl-second fn)))))
5114 (defun markdown-footnote-goto-text ()
5115 "Jump to the text of the footnote at point."
5116 (interactive)
5117 (let ((fn (car (markdown-footnote-marker-positions))))
5118 (unless fn
5119 (user-error "Not at a footnote marker"))
5120 (let ((new-pos (markdown-footnote-find-text fn)))
5121 (unless new-pos
5122 (error "No definition found for footnote `%s'" fn))
5123 (goto-char new-pos))))
5125 (defun markdown-footnote-return ()
5126 "Return from a footnote to its footnote number in the main text."
5127 (interactive)
5128 (let ((fn (save-excursion
5129 (car (markdown-footnote-text-positions)))))
5130 (unless fn
5131 (user-error "Not in a footnote"))
5132 (let ((new-pos (markdown-footnote-find-marker fn)))
5133 (unless new-pos
5134 (error "Footnote marker `%s' not found" fn))
5135 (goto-char new-pos))))
5137 (defun markdown-footnote-find-marker (id)
5138 "Find the location of the footnote marker with ID.
5139 The actual buffer position returned is the position directly
5140 following the marker's closing bracket. If no marker is found,
5141 NIL is returned."
5142 (save-excursion
5143 (goto-char (point-min))
5144 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
5145 (skip-chars-backward "^]")
5146 (point))))
5148 (defun markdown-footnote-find-text (id)
5149 "Find the location of the text of footnote ID.
5150 The actual buffer position returned is the position of the first
5151 character of the text, after the footnote's identifier. If no
5152 footnote text is found, NIL is returned."
5153 (save-excursion
5154 (goto-char (point-min))
5155 (when (re-search-forward (concat "^ \\{0,3\\}\\[" id "\\]:") nil t)
5156 (skip-chars-forward "[ \t]")
5157 (point))))
5159 (defun markdown-footnote-marker-positions ()
5160 "Return the position and ID of the footnote marker point is on.
5161 The return value is a list (ID START END). If point is not on a
5162 footnote, NIL is returned."
5163 ;; first make sure we're at a footnote marker
5164 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
5165 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
5166 (save-excursion
5167 ;; move point between [ and ^:
5168 (if (looking-at-p "\\[")
5169 (forward-char 1)
5170 (skip-chars-backward "^["))
5171 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
5172 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
5174 (defun markdown-footnote-text-positions ()
5175 "Return the start and end positions of the footnote text point is in.
5176 The exact return value is a list of three elements: (ID START END).
5177 The start position is the position of the opening bracket
5178 of the footnote id. The end position is directly after the
5179 newline that ends the footnote. If point is not in a footnote,
5180 NIL is returned instead."
5181 (save-excursion
5182 (let (result)
5183 (move-beginning-of-line 1)
5184 ;; Try to find the label. If we haven't found the label and we're at a blank
5185 ;; or indented line, back up if possible.
5186 (while (and
5187 (not (and (looking-at markdown-regex-footnote-definition)
5188 (setq result (list (match-string 1) (point)))))
5189 (and (not (bobp))
5190 (or (markdown-cur-line-blank-p)
5191 (>= (current-indentation) 4))))
5192 (forward-line -1))
5193 (when result
5194 ;; Advance if there is a next line that is either blank or indented.
5195 ;; (Need to check if we're on the last line, because
5196 ;; markdown-next-line-blank-p returns true for last line in buffer.)
5197 (while (and (/= (line-end-position) (point-max))
5198 (or (markdown-next-line-blank-p)
5199 (>= (markdown-next-line-indent) 4)))
5200 (forward-line))
5201 ;; Move back while the current line is blank.
5202 (while (markdown-cur-line-blank-p)
5203 (forward-line -1))
5204 ;; Advance to capture this line and a single trailing newline (if there
5205 ;; is one).
5206 (forward-line)
5207 (append result (list (point)))))))
5210 ;;; Element Removal ===========================================================
5212 (defun markdown-kill-thing-at-point ()
5213 "Kill thing at point and add important text, without markup, to kill ring.
5214 Possible things to kill include (roughly in order of precedence):
5215 inline code, headers, horizonal rules, links (add link text to
5216 kill ring), images (add alt text to kill ring), angle uri, email
5217 addresses, bold, italics, reference definition (add URI to kill
5218 ring), footnote markers and text (kill both marker and text, add
5219 text to kill ring), and list items."
5220 (interactive "*")
5221 (let (val)
5222 (cond
5223 ;; Inline code
5224 ((markdown-inline-code-at-point)
5225 (kill-new (match-string 2))
5226 (delete-region (match-beginning 0) (match-end 0)))
5227 ;; ATX header
5228 ((thing-at-point-looking-at markdown-regex-header-atx)
5229 (kill-new (match-string 2))
5230 (delete-region (match-beginning 0) (match-end 0)))
5231 ;; Setext header
5232 ((thing-at-point-looking-at markdown-regex-header-setext)
5233 (kill-new (match-string 1))
5234 (delete-region (match-beginning 0) (match-end 0)))
5235 ;; Horizonal rule
5236 ((thing-at-point-looking-at markdown-regex-hr)
5237 (kill-new (match-string 0))
5238 (delete-region (match-beginning 0) (match-end 0)))
5239 ;; Inline link or image (add link or alt text to kill ring)
5240 ((thing-at-point-looking-at markdown-regex-link-inline)
5241 (kill-new (match-string 3))
5242 (delete-region (match-beginning 0) (match-end 0)))
5243 ;; Reference link or image (add link or alt text to kill ring)
5244 ((thing-at-point-looking-at markdown-regex-link-reference)
5245 (kill-new (match-string 3))
5246 (delete-region (match-beginning 0) (match-end 0)))
5247 ;; Angle URI (add URL to kill ring)
5248 ((thing-at-point-looking-at markdown-regex-angle-uri)
5249 (kill-new (match-string 2))
5250 (delete-region (match-beginning 0) (match-end 0)))
5251 ;; Email address in angle brackets (add email address to kill ring)
5252 ((thing-at-point-looking-at markdown-regex-email)
5253 (kill-new (match-string 1))
5254 (delete-region (match-beginning 0) (match-end 0)))
5255 ;; Wiki link (add alias text to kill ring)
5256 ((and markdown-enable-wiki-links
5257 (thing-at-point-looking-at markdown-regex-wiki-link))
5258 (kill-new (markdown-wiki-link-alias))
5259 (delete-region (match-beginning 1) (match-end 1)))
5260 ;; Bold
5261 ((thing-at-point-looking-at markdown-regex-bold)
5262 (kill-new (match-string 4))
5263 (delete-region (match-beginning 2) (match-end 2)))
5264 ;; Italics
5265 ((thing-at-point-looking-at markdown-regex-italic)
5266 (kill-new (match-string 3))
5267 (delete-region (match-beginning 1) (match-end 1)))
5268 ;; Strikethrough
5269 ((thing-at-point-looking-at markdown-regex-strike-through)
5270 (kill-new (match-string 4))
5271 (delete-region (match-beginning 2) (match-end 2)))
5272 ;; Footnote marker (add footnote text to kill ring)
5273 ((thing-at-point-looking-at markdown-regex-footnote)
5274 (markdown-footnote-kill))
5275 ;; Footnote text (add footnote text to kill ring)
5276 ((setq val (markdown-footnote-text-positions))
5277 (markdown-footnote-kill))
5278 ;; Reference definition (add URL to kill ring)
5279 ((thing-at-point-looking-at markdown-regex-reference-definition)
5280 (kill-new (match-string 5))
5281 (delete-region (match-beginning 0) (match-end 0)))
5282 ;; List item
5283 ((setq val (markdown-cur-list-item-bounds))
5284 (kill-new (delete-and-extract-region (cl-first val) (cl-second val))))
5286 (user-error "Nothing found at point to kill")))))
5289 ;;; Indentation ====================================================================
5291 (defun markdown-indent-find-next-position (cur-pos positions)
5292 "Return the position after the index of CUR-POS in POSITIONS.
5293 Positions are calculated by `markdown-calc-indents'."
5294 (while (and positions
5295 (not (equal cur-pos (car positions))))
5296 (setq positions (cdr positions)))
5297 (or (cadr positions) 0))
5299 (define-obsolete-function-alias 'markdown-exdent-find-next-position
5300 'markdown-outdent-find-next-position "v2.3")
5302 (defun markdown-outdent-find-next-position (cur-pos positions)
5303 "Return the maximal element that precedes CUR-POS from POSITIONS.
5304 Positions are calculated by `markdown-calc-indents'."
5305 (let ((result 0))
5306 (dolist (i positions)
5307 (when (< i cur-pos)
5308 (setq result (max result i))))
5309 result))
5311 (defun markdown-indent-line ()
5312 "Indent the current line using some heuristics.
5313 If the _previous_ command was either `markdown-enter-key' or
5314 `markdown-cycle', then we should cycle to the next
5315 reasonable indentation position. Otherwise, we could have been
5316 called directly by `markdown-enter-key', by an initial call of
5317 `markdown-cycle', or indirectly by `auto-fill-mode'. In
5318 these cases, indent to the default position.
5319 Positions are calculated by `markdown-calc-indents'."
5320 (interactive)
5321 (let ((positions (markdown-calc-indents))
5322 (cursor-pos (current-column))
5323 (_ (back-to-indentation))
5324 (cur-pos (current-column)))
5325 (if (not (equal this-command 'markdown-cycle))
5326 (indent-line-to (car positions))
5327 (setq positions (sort (delete-dups positions) '<))
5328 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions))
5329 (new-cursor-pos
5330 (if (< cur-pos next-pos)
5331 (+ cursor-pos (- next-pos cur-pos))
5332 (- cursor-pos cur-pos))))
5333 (indent-line-to next-pos)
5334 (move-to-column new-cursor-pos)))))
5336 (defun markdown-calc-indents ()
5337 "Return a list of indentation columns to cycle through.
5338 The first element in the returned list should be considered the
5339 default indentation level. This function does not worry about
5340 duplicate positions, which are handled up by calling functions."
5341 (let (pos prev-line-pos positions)
5343 ;; Indentation of previous line
5344 (setq prev-line-pos (markdown-prev-line-indent))
5345 (setq positions (cons prev-line-pos positions))
5347 ;; Indentation of previous non-list-marker text
5348 (when (setq pos (markdown-prev-non-list-indent))
5349 (setq positions (cons pos positions)))
5351 ;; Indentation required for a pre block in current context
5352 (setq pos (length (markdown-pre-indentation (point))))
5353 (setq positions (cons pos positions))
5355 ;; Indentation of the previous line + tab-width
5356 (if prev-line-pos
5357 (setq positions (cons (+ prev-line-pos tab-width) positions))
5358 (setq positions (cons tab-width positions)))
5360 ;; Indentation of the previous line - tab-width
5361 (if (and prev-line-pos (> prev-line-pos tab-width))
5362 (setq positions (cons (- prev-line-pos tab-width) positions)))
5364 ;; Indentation of all preceeding list markers (when in a list)
5365 (when (setq pos (markdown-calculate-list-levels))
5366 (setq positions (append pos positions)))
5368 ;; First column
5369 (setq positions (cons 0 positions))
5371 ;; Return reversed list
5372 (reverse positions)))
5374 (defun markdown-enter-key ()
5375 "Handle RET according to value of `markdown-indent-on-enter'.
5376 When it is nil, simply call `newline'. Otherwise, indent the next line
5377 following RET using `markdown-indent-line'. Furthermore, when it
5378 is set to 'indent-and-new-item and the point is in a list item,
5379 start a new item with the same indentation. If the point is in an
5380 empty list item, remove it (so that pressing RET twice when in a
5381 list simply adds a blank line)."
5382 (interactive)
5383 (if (not markdown-indent-on-enter)
5384 (newline)
5385 (let (bounds)
5386 (if (and (memq markdown-indent-on-enter '(indent-and-new-item))
5387 (setq bounds (markdown-cur-list-item-bounds)))
5388 (let ((beg (cl-first bounds))
5389 (end (cl-second bounds))
5390 (length (cl-fourth bounds)))
5391 ;; Point is in a list item
5392 (if (= (- end beg) length)
5393 ;; Delete blank list
5394 (progn
5395 (delete-region beg end)
5396 (newline)
5397 (markdown-indent-line))
5398 (call-interactively #'markdown-insert-list-item)))
5399 ;; Point is not in a list
5400 (newline)
5401 (markdown-indent-line)))))
5403 (define-obsolete-function-alias 'markdown-exdent-or-delete
5404 'markdown-outdent-or-delete "v2.3")
5406 (defun markdown-outdent-or-delete (arg)
5407 "Handle BACKSPACE by cycling through indentation points.
5408 When BACKSPACE is pressed, if there is only whitespace
5409 before the current point, then outdent the line one level.
5410 Otherwise, do normal delete by repeating
5411 `backward-delete-char-untabify' ARG times."
5412 (interactive "*p")
5413 (if (use-region-p)
5414 (backward-delete-char-untabify arg)
5415 (let ((cur-pos (current-column))
5416 (start-of-indention (save-excursion
5417 (back-to-indentation)
5418 (current-column)))
5419 (positions (markdown-calc-indents)))
5420 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
5421 (indent-line-to (markdown-outdent-find-next-position cur-pos positions))
5422 (backward-delete-char-untabify arg)))))
5424 (defun markdown-find-leftmost-column (beg end)
5425 "Find the leftmost column in the region from BEG to END."
5426 (let ((mincol 1000))
5427 (save-excursion
5428 (goto-char beg)
5429 (while (< (point) end)
5430 (back-to-indentation)
5431 (unless (looking-at-p "[ \t]*$")
5432 (setq mincol (min mincol (current-column))))
5433 (forward-line 1)
5435 mincol))
5437 (defun markdown-indent-region (beg end arg)
5438 "Indent the region from BEG to END using some heuristics.
5439 When ARG is non-nil, outdent the region instead.
5440 See `markdown-indent-line' and `markdown-indent-line'."
5441 (interactive "*r\nP")
5442 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
5443 (leftmostcol (markdown-find-leftmost-column beg end))
5444 (next-pos (if arg
5445 (markdown-outdent-find-next-position leftmostcol positions)
5446 (markdown-indent-find-next-position leftmostcol positions))))
5447 (indent-rigidly beg end (- next-pos leftmostcol))
5448 (setq deactivate-mark nil)))
5450 (define-obsolete-function-alias 'markdown-exdent-region
5451 'markdown-outdent-region "v2.3")
5453 (defun markdown-outdent-region (beg end)
5454 "Call `markdown-indent-region' on region from BEG to END with prefix."
5455 (interactive "*r")
5456 (markdown-indent-region beg end t))
5459 ;;; Markup Completion =========================================================
5461 (defconst markdown-complete-alist
5462 '((markdown-regex-header-atx . markdown-complete-atx)
5463 (markdown-regex-header-setext . markdown-complete-setext)
5464 (markdown-regex-hr . markdown-complete-hr))
5465 "Association list of form (regexp . function) for markup completion.")
5467 (defun markdown-incomplete-atx-p ()
5468 "Return t if ATX header markup is incomplete and nil otherwise.
5469 Assumes match data is available for `markdown-regex-header-atx'.
5470 Checks that the number of trailing hash marks equals the number of leading
5471 hash marks, that there is only a single space before and after the text,
5472 and that there is no extraneous whitespace in the text."
5474 ;; Number of starting and ending hash marks differs
5475 (not (= (length (match-string 1)) (length (match-string 3))))
5476 ;; When the header text is not empty...
5477 (and (> (length (match-string 2)) 0)
5478 ;; ...if there are extra leading, trailing, or interior spaces
5479 (or (not (= (match-beginning 2) (1+ (match-end 1))))
5480 (not (= (match-beginning 3) (1+ (match-end 2))))
5481 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
5482 ;; When the header text is empty...
5483 (and (= (length (match-string 2)) 0)
5484 ;; ...if there are too many or too few spaces
5485 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
5487 (defun markdown-complete-atx ()
5488 "Complete and normalize ATX headers.
5489 Add or remove hash marks to the end of the header to match the
5490 beginning. Ensure that there is only a single space between hash
5491 marks and header text. Removes extraneous whitespace from header text.
5492 Assumes match data is available for `markdown-regex-header-atx'.
5493 Return nil if markup was complete and non-nil if markup was completed."
5494 (when (markdown-incomplete-atx-p)
5495 (let* ((new-marker (make-marker))
5496 (new-marker (set-marker new-marker (match-end 2))))
5497 ;; Hash marks and spacing at end
5498 (goto-char (match-end 2))
5499 (delete-region (match-end 2) (match-end 3))
5500 (insert " " (match-string 1))
5501 ;; Remove extraneous whitespace from title
5502 (replace-match (markdown-compress-whitespace-string (match-string 2))
5503 t t nil 2)
5504 ;; Spacing at beginning
5505 (goto-char (match-end 1))
5506 (delete-region (match-end 1) (match-beginning 2))
5507 (insert " ")
5508 ;; Leave point at end of text
5509 (goto-char new-marker))))
5511 (defun markdown-incomplete-setext-p ()
5512 "Return t if setext header markup is incomplete and nil otherwise.
5513 Assumes match data is available for `markdown-regex-header-setext'.
5514 Checks that length of underline matches text and that there is no
5515 extraneous whitespace in the text."
5516 (or (not (= (length (match-string 1)) (length (match-string 2))))
5517 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
5519 (defun markdown-complete-setext ()
5520 "Complete and normalize setext headers.
5521 Add or remove underline characters to match length of header
5522 text. Removes extraneous whitespace from header text. Assumes
5523 match data is available for `markdown-regex-header-setext'.
5524 Return nil if markup was complete and non-nil if markup was completed."
5525 (when (markdown-incomplete-setext-p)
5526 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
5527 (char (char-after (match-beginning 2)))
5528 (level (if (char-equal char ?-) 2 1)))
5529 (goto-char (match-beginning 0))
5530 (delete-region (match-beginning 0) (match-end 0))
5531 (markdown-insert-header level text t)
5532 t)))
5534 (defun markdown-incomplete-hr-p ()
5535 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
5536 Assumes match data is available for `markdown-regex-hr'."
5537 (not (member (match-string 0) markdown-hr-strings)))
5539 (defun markdown-complete-hr ()
5540 "Complete horizontal rules.
5541 If horizontal rule string is a member of `markdown-hr-strings',
5542 do nothing. Otherwise, replace with the car of
5543 `markdown-hr-strings'.
5544 Assumes match data is available for `markdown-regex-hr'.
5545 Return nil if markup was complete and non-nil if markup was completed."
5546 (when (markdown-incomplete-hr-p)
5547 (replace-match (car markdown-hr-strings))
5550 (defun markdown-complete ()
5551 "Complete markup of object near point or in region when active.
5552 Handle all objects in `markdown-complete-alist', in order.
5553 See `markdown-complete-at-point' and `markdown-complete-region'."
5554 (interactive "*")
5555 (if (markdown-use-region-p)
5556 (markdown-complete-region (region-beginning) (region-end))
5557 (markdown-complete-at-point)))
5559 (defun markdown-complete-at-point ()
5560 "Complete markup of object near point.
5561 Handle all elements of `markdown-complete-alist' in order."
5562 (interactive "*")
5563 (let ((list markdown-complete-alist) found changed)
5564 (while list
5565 (let ((regexp (eval (caar list)))
5566 (function (cdar list)))
5567 (setq list (cdr list))
5568 (when (thing-at-point-looking-at regexp)
5569 (setq found t)
5570 (setq changed (funcall function))
5571 (setq list nil))))
5572 (if found
5573 (or changed (user-error "Markup at point is complete"))
5574 (user-error "Nothing to complete at point"))))
5576 (defun markdown-complete-region (beg end)
5577 "Complete markup of objects in region from BEG to END.
5578 Handle all objects in `markdown-complete-alist', in order. Each
5579 match is checked to ensure that a previous regexp does not also
5580 match."
5581 (interactive "*r")
5582 (let ((end-marker (set-marker (make-marker) end))
5583 previous)
5584 (dolist (element markdown-complete-alist)
5585 (let ((regexp (eval (car element)))
5586 (function (cdr element)))
5587 (goto-char beg)
5588 (while (re-search-forward regexp end-marker 'limit)
5589 (when (match-string 0)
5590 ;; Make sure this is not a match for any of the preceding regexps.
5591 ;; This prevents mistaking an HR for a Setext subheading.
5592 (let (match)
5593 (save-match-data
5594 (dolist (prev-regexp previous)
5595 (or match (setq match (looking-back prev-regexp nil)))))
5596 (unless match
5597 (save-excursion (funcall function))))))
5598 (cl-pushnew regexp previous :test #'equal)))
5599 previous))
5601 (defun markdown-complete-buffer ()
5602 "Complete markup for all objects in the current buffer."
5603 (interactive "*")
5604 (markdown-complete-region (point-min) (point-max)))
5607 ;;; Markup Cycling ============================================================
5609 (defun markdown-cycle-atx (arg &optional remove)
5610 "Cycle ATX header markup.
5611 Promote header (decrease level) when ARG is 1 and demote
5612 header (increase level) if arg is -1. When REMOVE is non-nil,
5613 remove the header when the level reaches zero and stop cycling
5614 when it reaches six. Otherwise, perform a proper cycling through
5615 levels one through six. Assumes match data is available for
5616 `markdown-regex-header-atx'."
5617 (let* ((old-level (length (match-string 1)))
5618 (new-level (+ old-level arg))
5619 (text (match-string 2)))
5620 (when (not remove)
5621 (setq new-level (% new-level 6))
5622 (setq new-level (cond ((= new-level 0) 6)
5623 ((< new-level 0) (+ new-level 6))
5624 (t new-level))))
5625 (cond
5626 ((= new-level 0)
5627 (markdown-unwrap-thing-at-point nil 0 2))
5628 ((<= new-level 6)
5629 (goto-char (match-beginning 0))
5630 (delete-region (match-beginning 0) (match-end 0))
5631 (markdown-insert-header new-level text nil)))))
5633 (defun markdown-cycle-setext (arg &optional remove)
5634 "Cycle setext header markup.
5635 Promote header (increase level) when ARG is 1 and demote
5636 header (decrease level or remove) if arg is -1. When demoting a
5637 level-two setext header, replace with a level-three atx header.
5638 When REMOVE is non-nil, remove the header when the level reaches
5639 zero. Otherwise, cycle back to a level six atx header. Assumes
5640 match data is available for `markdown-regex-header-setext'."
5641 (let* ((char (char-after (match-beginning 2)))
5642 (old-level (if (char-equal char ?=) 1 2))
5643 (new-level (+ old-level arg)))
5644 (when (and (not remove) (= new-level 0))
5645 (setq new-level 6))
5646 (cond
5647 ((= new-level 0)
5648 (markdown-unwrap-thing-at-point nil 0 1))
5649 ((<= new-level 2)
5650 (markdown-insert-header new-level nil t))
5651 ((<= new-level 6)
5652 (markdown-insert-header new-level nil nil)))))
5654 (defun markdown-cycle-hr (arg &optional remove)
5655 "Cycle string used for horizontal rule from `markdown-hr-strings'.
5656 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
5657 backwards (promote). When REMOVE is non-nil, remove the hr instead
5658 of cycling when the end of the list is reached.
5659 Assumes match data is available for `markdown-regex-hr'."
5660 (let* ((strings (if (= arg -1)
5661 (reverse markdown-hr-strings)
5662 markdown-hr-strings))
5663 (tail (member (match-string 0) strings))
5664 (new (or (cadr tail)
5665 (if remove
5666 (if (= arg 1)
5668 (car tail))
5669 (car strings)))))
5670 (replace-match new)))
5672 (defun markdown-cycle-bold ()
5673 "Cycle bold markup between underscores and asterisks.
5674 Assumes match data is available for `markdown-regex-bold'."
5675 (save-excursion
5676 (let* ((old-delim (match-string 3))
5677 (new-delim (if (string-equal old-delim "**") "__" "**")))
5678 (replace-match new-delim t t nil 3)
5679 (replace-match new-delim t t nil 5))))
5681 (defun markdown-cycle-italic ()
5682 "Cycle italic markup between underscores and asterisks.
5683 Assumes match data is available for `markdown-regex-italic'."
5684 (save-excursion
5685 (let* ((old-delim (match-string 2))
5686 (new-delim (if (string-equal old-delim "*") "_" "*")))
5687 (replace-match new-delim t t nil 2)
5688 (replace-match new-delim t t nil 4))))
5691 ;;; Keymap ====================================================================
5693 (defun markdown--style-map-prompt ()
5694 "Return a formatted prompt for Markdown markup insertion."
5695 (when markdown-enable-prefix-prompts
5696 (concat
5697 "Markdown: "
5698 (propertize "bold" 'face 'markdown-bold-face) ", "
5699 (propertize "italic" 'face 'markdown-italic-face) ", "
5700 (propertize "code" 'face 'markdown-inline-code-face) ", "
5701 (propertize "C = GFM code" 'face 'markdown-code-face) ", "
5702 (propertize "pre" 'face 'markdown-pre-face) ", "
5703 (propertize "footnote" 'face 'markdown-footnote-text-face) ", "
5704 (propertize "q = blockquote" 'face 'markdown-blockquote-face) ", "
5705 (propertize "h & 1-6 = heading" 'face 'markdown-header-face) ", "
5706 (propertize "- = hr" 'face 'markdown-hr-face) ", "
5707 "C-h = more")))
5709 (defun markdown--command-map-prompt ()
5710 "Return prompt for Markdown buffer-wide commands."
5711 (when markdown-enable-prefix-prompts
5712 (concat
5713 "Command: "
5714 (propertize "m" 'face 'markdown-bold-face) "arkdown, "
5715 (propertize "p" 'face 'markdown-bold-face) "review, "
5716 (propertize "o" 'face 'markdown-bold-face) "pen, "
5717 (propertize "e" 'face 'markdown-bold-face) "xport, "
5718 "export & pre" (propertize "v" 'face 'markdown-bold-face) "iew, "
5719 (propertize "c" 'face 'markdown-bold-face) "heck refs, "
5720 "C-h = more")))
5722 (defvar markdown-mode-style-map
5723 (let ((map (make-keymap (markdown--style-map-prompt))))
5724 (define-key map (kbd "1") 'markdown-insert-header-atx-1)
5725 (define-key map (kbd "2") 'markdown-insert-header-atx-2)
5726 (define-key map (kbd "3") 'markdown-insert-header-atx-3)
5727 (define-key map (kbd "4") 'markdown-insert-header-atx-4)
5728 (define-key map (kbd "5") 'markdown-insert-header-atx-5)
5729 (define-key map (kbd "6") 'markdown-insert-header-atx-6)
5730 (define-key map (kbd "!") 'markdown-insert-header-setext-1)
5731 (define-key map (kbd "@") 'markdown-insert-header-setext-2)
5732 (define-key map (kbd "b") 'markdown-insert-bold)
5733 (define-key map (kbd "c") 'markdown-insert-code)
5734 (define-key map (kbd "C") 'markdown-insert-gfm-code-block)
5735 (define-key map (kbd "f") 'markdown-insert-footnote)
5736 (define-key map (kbd "h") 'markdown-insert-header-dwim)
5737 (define-key map (kbd "H") 'markdown-insert-header-setext-dwim)
5738 (define-key map (kbd "i") 'markdown-insert-italic)
5739 (define-key map (kbd "k") 'markdown-insert-kbd)
5740 (define-key map (kbd "l") 'markdown-insert-link)
5741 (define-key map (kbd "p") 'markdown-insert-pre)
5742 (define-key map (kbd "P") 'markdown-pre-region)
5743 (define-key map (kbd "q") 'markdown-insert-blockquote)
5744 (define-key map (kbd "s") 'markdown-insert-strike-through)
5745 (define-key map (kbd "Q") 'markdown-blockquote-region)
5746 (define-key map (kbd "w") 'markdown-insert-wiki-link)
5747 (define-key map (kbd "-") 'markdown-insert-hr)
5748 ;; Deprecated keys that may be removed in a future version
5749 (define-key map (kbd "e") 'markdown-insert-italic)
5750 map)
5751 "Keymap for Markdown text styling commands.")
5753 (defvar markdown-mode-command-map
5754 (let ((map (make-keymap (markdown--command-map-prompt))))
5755 (define-key map (kbd "m") 'markdown-other-window)
5756 (define-key map (kbd "p") 'markdown-preview)
5757 (define-key map (kbd "e") 'markdown-export)
5758 (define-key map (kbd "v") 'markdown-export-and-preview)
5759 (define-key map (kbd "o") 'markdown-open)
5760 (define-key map (kbd "l") 'markdown-live-preview-mode)
5761 (define-key map (kbd "w") 'markdown-kill-ring-save)
5762 (define-key map (kbd "c") 'markdown-check-refs)
5763 (define-key map (kbd "n") 'markdown-cleanup-list-numbers)
5764 (define-key map (kbd "]") 'markdown-complete-buffer)
5765 map)
5766 "Keymap for Markdown buffer-wide commands.")
5768 (defvar markdown-mode-map
5769 (let ((map (make-keymap)))
5770 ;; Markup insertion & removal
5771 (define-key map (kbd "C-c C-s") markdown-mode-style-map)
5772 (define-key map (kbd "C-c C-l") 'markdown-insert-link)
5773 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
5774 ;; Promotion, demotion, and cycling
5775 (define-key map (kbd "C-c C--") 'markdown-promote)
5776 (define-key map (kbd "C-c C-=") 'markdown-demote)
5777 (define-key map (kbd "C-c C-]") 'markdown-complete)
5778 ;; Following and doing things
5779 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
5780 (define-key map (kbd "C-c C-d") 'markdown-do)
5781 (define-key map (kbd "C-c '") 'markdown-edit-code-block)
5782 ;; Indentation
5783 (define-key map (kbd "C-m") 'markdown-enter-key)
5784 (define-key map (kbd "DEL") 'markdown-outdent-or-delete)
5785 (define-key map (kbd "C-c >") 'markdown-indent-region)
5786 (define-key map (kbd "C-c <") 'markdown-outdent-region)
5787 ;; Visibility cycling
5788 (define-key map (kbd "TAB") 'markdown-cycle)
5789 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
5790 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
5791 (define-key map (kbd "<backtab>") 'markdown-shifttab)
5792 ;; Heading and list navigation
5793 (define-key map (kbd "C-c C-n") 'markdown-outline-next)
5794 (define-key map (kbd "C-c C-p") 'markdown-outline-previous)
5795 (define-key map (kbd "C-c C-f") 'markdown-outline-next-same-level)
5796 (define-key map (kbd "C-c C-b") 'markdown-outline-previous-same-level)
5797 (define-key map (kbd "C-c C-u") 'markdown-outline-up)
5798 ;; Buffer-wide commands
5799 (define-key map (kbd "C-c C-c") markdown-mode-command-map)
5800 ;; Subtree and list editing
5801 (define-key map (kbd "C-c <up>") 'markdown-move-up)
5802 (define-key map (kbd "C-c <down>") 'markdown-move-down)
5803 (define-key map (kbd "C-c <left>") 'markdown-promote)
5804 (define-key map (kbd "C-c <right>") 'markdown-demote)
5805 (define-key map (kbd "C-c C-M-h") 'markdown-mark-subtree)
5806 (define-key map (kbd "C-x n s") 'markdown-narrow-to-subtree)
5807 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
5808 (define-key map (kbd "C-c C-j") 'markdown-insert-list-item)
5809 ;; Paragraphs (Markdown context aware)
5810 (define-key map [remap backward-paragraph] 'markdown-backward-paragraph)
5811 (define-key map [remap forward-paragraph] 'markdown-forward-paragraph)
5812 (define-key map [remap mark-paragraph] 'markdown-mark-paragraph)
5813 ;; Blocks (one or more paragraphs)
5814 (define-key map (kbd "C-M-{") 'markdown-backward-block)
5815 (define-key map (kbd "C-M-}") 'markdown-forward-block)
5816 (define-key map (kbd "C-c M-h") 'markdown-mark-block)
5817 (define-key map (kbd "C-x n b") 'markdown-narrow-to-block)
5818 ;; Pages (top-level sections)
5819 (define-key map [remap backward-page] 'markdown-backward-page)
5820 (define-key map [remap forward-page] 'markdown-forward-page)
5821 (define-key map [remap mark-page] 'markdown-mark-page)
5822 (define-key map [remap narrow-to-page] 'markdown-narrow-to-page)
5823 ;; Link Movement
5824 (define-key map (kbd "M-n") 'markdown-next-link)
5825 (define-key map (kbd "M-p") 'markdown-previous-link)
5826 ;; Toggling functionality
5827 (define-key map (kbd "C-c C-x C-e") 'markdown-toggle-math)
5828 (define-key map (kbd "C-c C-x C-f") 'markdown-toggle-fontify-code-blocks-natively)
5829 (define-key map (kbd "C-c C-x C-i") 'markdown-toggle-inline-images)
5830 (define-key map (kbd "C-c C-x C-l") 'markdown-toggle-url-hiding)
5831 (define-key map (kbd "C-c C-x C-m") 'markdown-toggle-markup-hiding)
5832 ;; Alternative keys (in case of problems with the arrow keys)
5833 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
5834 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
5835 (define-key map (kbd "C-c C-x l") 'markdown-promote)
5836 (define-key map (kbd "C-c C-x r") 'markdown-demote)
5837 ;; Deprecated keys that may be removed in a future version
5838 (define-key map (kbd "C-c C-a L") 'markdown-insert-link) ;; C-c C-l
5839 (define-key map (kbd "C-c C-a l") 'markdown-insert-link) ;; C-c C-l
5840 (define-key map (kbd "C-c C-a r") 'markdown-insert-link) ;; C-c C-l
5841 (define-key map (kbd "C-c C-a u") 'markdown-insert-uri) ;; C-c C-l
5842 (define-key map (kbd "C-c C-a f") 'markdown-insert-footnote)
5843 (define-key map (kbd "C-c C-a w") 'markdown-insert-wiki-link)
5844 (define-key map (kbd "C-c C-t 1") 'markdown-insert-header-atx-1)
5845 (define-key map (kbd "C-c C-t 2") 'markdown-insert-header-atx-2)
5846 (define-key map (kbd "C-c C-t 3") 'markdown-insert-header-atx-3)
5847 (define-key map (kbd "C-c C-t 4") 'markdown-insert-header-atx-4)
5848 (define-key map (kbd "C-c C-t 5") 'markdown-insert-header-atx-5)
5849 (define-key map (kbd "C-c C-t 6") 'markdown-insert-header-atx-6)
5850 (define-key map (kbd "C-c C-t !") 'markdown-insert-header-setext-1)
5851 (define-key map (kbd "C-c C-t @") 'markdown-insert-header-setext-2)
5852 (define-key map (kbd "C-c C-t h") 'markdown-insert-header-dwim)
5853 (define-key map (kbd "C-c C-t H") 'markdown-insert-header-setext-dwim)
5854 (define-key map (kbd "C-c C-t s") 'markdown-insert-header-setext-2)
5855 (define-key map (kbd "C-c C-t t") 'markdown-insert-header-setext-1)
5856 (define-key map (kbd "C-c C-i") 'markdown-insert-image)
5857 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item) ;; C-c C-j
5858 (define-key map (kbd "C-c C-x C-x") 'markdown-toggle-gfm-checkbox) ;; C-c C-d
5859 (define-key map (kbd "C-c -") 'markdown-insert-hr)
5860 map)
5861 "Keymap for Markdown major mode.")
5863 (defvar markdown-mode-mouse-map
5864 (let ((map (make-sparse-keymap)))
5865 (define-key map [follow-link] 'mouse-face)
5866 (define-key map [mouse-2] 'markdown-follow-link-at-point)
5867 map)
5868 "Keymap for following links with mouse.")
5870 (defvar gfm-mode-map
5871 (let ((map (make-sparse-keymap)))
5872 (set-keymap-parent map markdown-mode-map)
5873 (define-key map (kbd "C-c C-s d") 'markdown-insert-strike-through)
5874 (define-key map "`" 'markdown-electric-backquote)
5875 map)
5876 "Keymap for `gfm-mode'.
5877 See also `markdown-mode-map'.")
5880 ;;; Menu ==================================================================
5882 (easy-menu-define markdown-mode-menu markdown-mode-map
5883 "Menu for Markdown mode"
5884 '("Markdown"
5885 "---"
5886 ("Movement"
5887 ["Jump" markdown-do]
5888 ["Follow Link" markdown-follow-thing-at-point]
5889 ["Next Link" markdown-next-link]
5890 ["Previous Link" markdown-previous-link]
5891 "---"
5892 ["Next Heading or List Item" markdown-outline-next]
5893 ["Previous Heading or List Item" markdown-outline-previous]
5894 ["Next at Same Level" markdown-outline-next-same-level]
5895 ["Previous at Same Level" markdown-outline-previous-same-level]
5896 ["Up to Parent" markdown-outline-up]
5897 "---"
5898 ["Forward Paragraph" markdown-forward-paragraph]
5899 ["Backward Paragraph" markdown-backward-paragraph]
5900 ["Forward Block" markdown-forward-block]
5901 ["Backward Block" markdown-backward-block])
5902 ("Show & Hide"
5903 ["Cycle Heading Visibility" markdown-cycle (markdown-on-heading-p)]
5904 ["Cycle Heading Visibility (Global)" markdown-shifttab]
5905 "---"
5906 ["Narrow to Region" narrow-to-region]
5907 ["Narrow to Block" markdown-narrow-to-block]
5908 ["Narrow to Section" narrow-to-defun]
5909 ["Narrow to Subtree" markdown-narrow-to-subtree]
5910 ["Widen" widen (buffer-narrowed-p)]
5911 "---"
5912 ["Toggle Markup Hiding" markdown-toggle-markup-hiding
5913 :keys "C-c C-x C-m"
5914 :style radio
5915 :selected markdown-hide-markup])
5916 "---"
5917 ("Headings & Structure"
5918 ["Automatic Heading" markdown-insert-header-dwim :keys "C-c C-s h"]
5919 ["Automatic Heading (Setext)" markdown-insert-header-setext-dwim :keys "C-c C-s H"]
5920 ("Specific Heading (atx)"
5921 ["First Level atx" markdown-insert-header-atx-1 :keys "C-c C-s 1"]
5922 ["Second Level atx" markdown-insert-header-atx-2 :keys "C-c C-s 2"]
5923 ["Third Level atx" markdown-insert-header-atx-3 :keys "C-c C-s 3"]
5924 ["Fourth Level atx" markdown-insert-header-atx-4 :keys "C-c C-s 4"]
5925 ["Fifth Level atx" markdown-insert-header-atx-5 :keys "C-c C-s 5"]
5926 ["Sixth Level atx" markdown-insert-header-atx-6 :keys "C-c C-s 6"])
5927 ("Specific Heading (Setext)"
5928 ["First Level Setext" markdown-insert-header-setext-1 :keys "C-c C-s !"]
5929 ["Second Level Setext" markdown-insert-header-setext-2 :keys "C-c C-s @"])
5930 ["Horizontal Rule" markdown-insert-hr :keys "C-c C-s -"]
5931 "---"
5932 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
5933 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
5934 ["Promote Subtree" markdown-promote :keys "C-c <left>"]
5935 ["Demote Subtree" markdown-demote :keys "C-c <right>"])
5936 ("Region & Mark"
5937 ["Indent Region" markdown-indent-region]
5938 ["Outdent Region" markdown-outdent-region]
5939 "--"
5940 ["Mark Paragraph" mark-paragraph]
5941 ["Mark Block" markdown-mark-block]
5942 ["Mark Section" mark-defun]
5943 ["Mark Subtree" markdown-mark-subtree])
5944 ("Lists"
5945 ["Insert List Item" markdown-insert-list-item]
5946 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
5947 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
5948 ["Indent Subtree" markdown-demote :keys "C-c <right>"]
5949 ["Outdent Subtree" markdown-promote :keys "C-c <left>"]
5950 ["Renumber List" markdown-cleanup-list-numbers]
5951 ["Toggle Task List Item" markdown-toggle-gfm-checkbox :keys "C-c C-d"])
5952 ("Links & Images"
5953 ["Insert Link" markdown-insert-link]
5954 ["Insert Image" markdown-insert-image]
5955 ["Insert Footnote" markdown-insert-footnote :keys "C-c C-s f"]
5956 ["Insert Wiki Link" markdown-insert-wiki-link :keys "C-c C-s w"]
5957 "---"
5958 ["Check References" markdown-check-refs]
5959 ["Toggle URL Hiding" markdown-toggle-url-hiding
5960 :style radio
5961 :selected markdown-hide-urls]
5962 ["Toggle Inline Images" markdown-toggle-inline-images
5963 :keys "C-c C-x C-i"
5964 :style radio
5965 :selected markdown-inline-image-overlays]
5966 ["Toggle Wiki Links" markdown-toggle-wiki-links
5967 :style radio
5968 :selected markdown-enable-wiki-links])
5969 ("Styles"
5970 ["Bold" markdown-insert-bold]
5971 ["Italic" markdown-insert-italic]
5972 ["Code" markdown-insert-code]
5973 ["Strikethrough" markdown-insert-strike-through]
5974 ["Keyboard" markdown-insert-kbd]
5975 "---"
5976 ["Blockquote" markdown-insert-blockquote]
5977 ["Preformatted" markdown-insert-pre]
5978 ["GFM Code Block" markdown-insert-gfm-code-block]
5979 ["Edit Code Block" markdown-edit-code-block (markdown-code-block-at-point-p)]
5980 "---"
5981 ["Blockquote Region" markdown-blockquote-region]
5982 ["Preformatted Region" markdown-pre-region]
5983 "---"
5984 ["Fontify Code Blocks Natively" markdown-toggle-fontify-code-blocks-natively
5985 :style radio
5986 :selected markdown-fontify-code-blocks-natively]
5987 ["LaTeX Math Support" markdown-toggle-math
5988 :style radio
5989 :selected markdown-enable-math])
5990 "---"
5991 ("Preview & Export"
5992 ["Compile" markdown-other-window]
5993 ["Preview" markdown-preview]
5994 ["Export" markdown-export]
5995 ["Export & View" markdown-export-and-preview]
5996 ["Open" markdown-open]
5997 ["Live Export" markdown-live-preview-mode
5998 :style radio
5999 :selected markdown-live-preview-mode]
6000 ["Kill ring save" markdown-kill-ring-save])
6001 ("Markup Completion and Cycling"
6002 ["Complete Markup" markdown-complete]
6003 ["Promote Element" markdown-promote :keys "C-c C--"]
6004 ["Demote Element" markdown-demote :keys "C-c C-="])
6005 "---"
6006 ["Kill Element" markdown-kill-thing-at-point]
6007 "---"
6008 ("Documentation"
6009 ["Version" markdown-show-version]
6010 ["Homepage" markdown-mode-info]
6011 ["Describe Mode" (describe-function 'markdown-mode)]
6012 ["Guide" (browse-url "https://leanpub.com/markdown-mode")])))
6015 ;;; imenu =====================================================================
6017 (defun markdown-imenu-create-nested-index ()
6018 "Create and return a nested imenu index alist for the current buffer.
6019 See `imenu-create-index-function' and `imenu--index-alist' for details."
6020 (let* ((root '(nil . nil))
6021 cur-alist
6022 (cur-level 0)
6023 (empty-heading "-")
6024 (self-heading ".")
6025 hashes pos level heading)
6026 (save-excursion
6027 (goto-char (point-min))
6028 (while (re-search-forward markdown-regex-header (point-max) t)
6029 (unless (markdown-code-block-at-point-p)
6030 (cond
6031 ((match-string-no-properties 2) ;; level 1 setext
6032 (setq heading (match-string-no-properties 1))
6033 (setq pos (match-beginning 1)
6034 level 1))
6035 ((match-string-no-properties 3) ;; level 2 setext
6036 (setq heading (match-string-no-properties 1))
6037 (setq pos (match-beginning 1)
6038 level 2))
6039 ((setq hashes (markdown-trim-whitespace
6040 (match-string-no-properties 4)))
6041 (setq heading (match-string-no-properties 5)
6042 pos (match-beginning 4)
6043 level (length hashes))))
6044 (let ((alist (list (cons heading pos))))
6045 (cond
6046 ((= cur-level level) ; new sibling
6047 (setcdr cur-alist alist)
6048 (setq cur-alist alist))
6049 ((< cur-level level) ; first child
6050 (dotimes (_ (- level cur-level 1))
6051 (setq alist (list (cons empty-heading alist))))
6052 (if cur-alist
6053 (let* ((parent (car cur-alist))
6054 (self-pos (cdr parent)))
6055 (setcdr parent (cons (cons self-heading self-pos) alist)))
6056 (setcdr root alist)) ; primogenitor
6057 (setq cur-alist alist)
6058 (setq cur-level level))
6059 (t ; new sibling of an ancestor
6060 (let ((sibling-alist (last (cdr root))))
6061 (dotimes (_ (1- level))
6062 (setq sibling-alist (last (cdar sibling-alist))))
6063 (setcdr sibling-alist alist)
6064 (setq cur-alist alist))
6065 (setq cur-level level))))))
6066 (cdr root))))
6068 (defun markdown-imenu-create-flat-index ()
6069 "Create and return a flat imenu index alist for the current buffer.
6070 See `imenu-create-index-function' and `imenu--index-alist' for details."
6071 (let* ((empty-heading "-") index heading pos)
6072 (save-excursion
6073 (goto-char (point-min))
6074 (while (re-search-forward markdown-regex-header (point-max) t)
6075 (when (and (not (markdown-code-block-at-point-p))
6076 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin)))
6077 (cond
6078 ((setq heading (match-string-no-properties 1))
6079 (setq pos (match-beginning 1)))
6080 ((setq heading (match-string-no-properties 5))
6081 (setq pos (match-beginning 4))))
6082 (or (> (length heading) 0)
6083 (setq heading empty-heading))
6084 (setq index (append index (list (cons heading pos))))))
6085 index)))
6088 ;;; References ================================================================
6090 (defun markdown-reference-goto-definition ()
6091 "Jump to the definition of the reference at point or create it."
6092 (interactive)
6093 (when (thing-at-point-looking-at markdown-regex-link-reference)
6094 (let* ((text (match-string-no-properties 3))
6095 (reference (match-string-no-properties 6))
6096 (target (downcase (if (string= reference "") text reference)))
6097 (loc (cadr (save-match-data (markdown-reference-definition target)))))
6098 (if loc
6099 (goto-char loc)
6100 (goto-char (match-beginning 0))
6101 (markdown-insert-reference-definition target)))))
6103 (defun markdown-reference-find-links (reference)
6104 "Return a list of all links for REFERENCE.
6105 REFERENCE should not include the surrounding square brackets.
6106 Elements of the list have the form (text start line), where
6107 text is the link text, start is the location at the beginning of
6108 the link, and line is the line number on which the link appears."
6109 (let* ((ref-quote (regexp-quote reference))
6110 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
6111 ref-quote ref-quote))
6112 links)
6113 (save-excursion
6114 (goto-char (point-min))
6115 (while (re-search-forward regexp nil t)
6116 (let* ((text (or (match-string-no-properties 1)
6117 (match-string-no-properties 2)))
6118 (start (match-beginning 0))
6119 (line (markdown-line-number-at-pos)))
6120 (cl-pushnew (list text start line) links :test #'equal))))
6121 links))
6123 (defun markdown-get-undefined-refs ()
6124 "Return a list of undefined Markdown references.
6125 Result is an alist of pairs (reference . occurrences), where
6126 occurrences is itself another alist of pairs (label . line-number).
6127 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
6128 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
6129 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
6130 (let ((missing))
6131 (save-excursion
6132 (goto-char (point-min))
6133 (while
6134 (re-search-forward markdown-regex-link-reference nil t)
6135 (let* ((text (match-string-no-properties 3))
6136 (reference (match-string-no-properties 6))
6137 (target (downcase (if (string= reference "") text reference))))
6138 (unless (markdown-reference-definition target)
6139 (let ((entry (assoc target missing)))
6140 (if (not entry)
6141 (cl-pushnew
6142 (cons target (list (cons text (markdown-line-number-at-pos))))
6143 missing :test #'equal)
6144 (setcdr entry
6145 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
6146 (reverse missing))))
6148 (defconst markdown-reference-check-buffer
6149 "*Undefined references for %buffer%*"
6150 "Pattern for name of buffer for listing undefined references.
6151 The string %buffer% will be replaced by the corresponding
6152 `markdown-mode' buffer name.")
6154 (defun markdown-reference-check-buffer (&optional buffer-name)
6155 "Name and return buffer for reference checking.
6156 BUFFER-NAME is the name of the main buffer being visited."
6157 (or buffer-name (setq buffer-name (buffer-name)))
6158 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
6159 "%buffer%" buffer-name
6160 markdown-reference-check-buffer))))
6161 (with-current-buffer refbuf
6162 (when view-mode
6163 (View-exit-and-edit))
6164 (use-local-map button-buffer-map)
6165 (erase-buffer))
6166 refbuf))
6168 (defconst markdown-reference-links-buffer
6169 "*Reference links for %buffer%*"
6170 "Pattern for name of buffer for listing references.
6171 The string %buffer% will be replaced by the corresponding buffer name.")
6173 (defun markdown-reference-links-buffer (&optional buffer-name)
6174 "Name, setup, and return a buffer for listing links.
6175 BUFFER-NAME is the name of the main buffer being visited."
6176 (or buffer-name (setq buffer-name (buffer-name)))
6177 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
6178 "%buffer%" buffer-name
6179 markdown-reference-links-buffer))))
6180 (with-current-buffer linkbuf
6181 (when view-mode
6182 (View-exit-and-edit))
6183 (use-local-map button-buffer-map)
6184 (erase-buffer))
6185 linkbuf))
6187 ;; Add an empty Markdown reference definition to buffer
6188 ;; specified in the 'target-buffer property. The reference name is
6189 ;; the button's label.
6190 (define-button-type 'markdown-undefined-reference-button
6191 'help-echo "mouse-1, RET: create definition for undefined reference"
6192 'follow-link t
6193 'face 'bold
6194 'action (lambda (b)
6195 (let ((buffer (button-get b 'target-buffer))
6196 (line (button-get b 'target-line))
6197 (label (button-label b)))
6198 (switch-to-buffer-other-window buffer)
6199 (goto-char (point-min))
6200 (forward-line line)
6201 (markdown-insert-reference-definition label)
6202 (markdown-check-refs t))))
6204 ;; Jump to line in buffer specified by 'target-buffer property.
6205 ;; Line number is button's 'line property.
6206 (define-button-type 'markdown-goto-line-button
6207 'help-echo "mouse-1, RET: go to line"
6208 'follow-link t
6209 'face 'italic
6210 'action (lambda (b)
6211 (message (button-get b 'buffer))
6212 (switch-to-buffer-other-window (button-get b 'target-buffer))
6213 ;; use call-interactively to silence compiler
6214 (let ((current-prefix-arg (button-get b 'target-line)))
6215 (call-interactively 'goto-line))))
6217 ;; Jumps to a particular link at location given by 'target-char
6218 ;; property in buffer given by 'target-buffer property.
6219 (define-button-type 'markdown-location-button
6220 'help-echo "mouse-1, RET: jump to location of link"
6221 'follow-link t
6222 'face 'bold
6223 'action (lambda (b)
6224 (let ((target (button-get b 'target-buffer))
6225 (loc (button-get b 'target-char)))
6226 (kill-buffer-and-window)
6227 (switch-to-buffer target)
6228 (goto-char loc))))
6230 (defun markdown-insert-undefined-reference-button (reference oldbuf)
6231 "Insert a button for creating REFERENCE in buffer OLDBUF.
6232 REFERENCE should be a list of the form (reference . occurrences),
6233 as by `markdown-get-undefined-refs'."
6234 (let ((label (car reference)))
6235 ;; Create a reference button
6236 (insert-button label
6237 :type 'markdown-undefined-reference-button
6238 'target-buffer oldbuf
6239 'target-line (cdr (car (cdr reference))))
6240 (insert " (")
6241 (dolist (occurrence (cdr reference))
6242 (let ((line (cdr occurrence)))
6243 ;; Create a line number button
6244 (insert-button (number-to-string line)
6245 :type 'markdown-goto-line-button
6246 'target-buffer oldbuf
6247 'target-line line)
6248 (insert " ")))
6249 (delete-char -1)
6250 (insert ")")
6251 (newline)))
6253 (defun markdown-insert-link-button (link oldbuf)
6254 "Insert a button for jumping to LINK in buffer OLDBUF.
6255 LINK should be a list of the form (text char line) containing
6256 the link text, location, and line number."
6257 (let ((label (cl-first link))
6258 (char (cl-second link))
6259 (line (cl-third link)))
6260 ;; Create a reference button
6261 (insert-button label
6262 :type 'markdown-location-button
6263 'target-buffer oldbuf
6264 'target-char char)
6265 (insert (format " (line %d)\n" line))))
6267 (defun markdown-reference-goto-link (&optional reference)
6268 "Jump to the location of the first use of REFERENCE."
6269 (interactive)
6270 (unless reference
6271 (if (thing-at-point-looking-at markdown-regex-reference-definition)
6272 (setq reference (match-string-no-properties 2))
6273 (user-error "No reference definition at point")))
6274 (let ((links (markdown-reference-find-links reference)))
6275 (cond ((= (length links) 1)
6276 (goto-char (cadr (car links))))
6277 ((> (length links) 1)
6278 (let ((oldbuf (current-buffer))
6279 (linkbuf (markdown-reference-links-buffer)))
6280 (with-current-buffer linkbuf
6281 (insert "Links using reference " reference ":\n\n")
6282 (dolist (link (reverse links))
6283 (markdown-insert-link-button link oldbuf)))
6284 (view-buffer-other-window linkbuf)
6285 (goto-char (point-min))
6286 (forward-line 2)))
6288 (error "No links for reference %s" reference)))))
6290 (defun markdown-check-refs (&optional silent)
6291 "Show all undefined Markdown references in current `markdown-mode' buffer.
6292 If SILENT is non-nil, do not message anything when no undefined
6293 references found.
6294 Links which have empty reference definitions are considered to be
6295 defined."
6296 (interactive "P")
6297 (when (not (eq major-mode 'markdown-mode))
6298 (user-error "Not available in current mode"))
6299 (let ((oldbuf (current-buffer))
6300 (refs (markdown-get-undefined-refs))
6301 (refbuf (markdown-reference-check-buffer)))
6302 (if (null refs)
6303 (progn
6304 (when (not silent)
6305 (message "No undefined references found"))
6306 (kill-buffer refbuf))
6307 (with-current-buffer refbuf
6308 (insert "The following references are undefined:\n\n")
6309 (dolist (ref refs)
6310 (markdown-insert-undefined-reference-button ref oldbuf))
6311 (view-buffer-other-window refbuf)
6312 (goto-char (point-min))
6313 (forward-line 2)))))
6316 ;;; Lists =====================================================================
6318 (defun markdown-insert-list-item (&optional arg)
6319 "Insert a new list item.
6320 If the point is inside unordered list, insert a bullet mark. If
6321 the point is inside ordered list, insert the next number followed
6322 by a period. Use the previous list item to determine the amount
6323 of whitespace to place before and after list markers.
6325 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
6326 decrease the indentation by one level.
6328 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
6329 increase the indentation by one level."
6330 (interactive "p")
6331 (let (bounds cur-indent marker indent new-indent new-loc)
6332 (save-match-data
6333 ;; Look for a list item on current or previous non-blank line
6334 (save-excursion
6335 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
6336 (not (bobp))
6337 (markdown-cur-line-blank-p))
6338 (forward-line -1)))
6339 (when bounds
6340 (cond ((save-excursion
6341 (skip-chars-backward " \t")
6342 (looking-at-p markdown-regex-list))
6343 (beginning-of-line)
6344 (insert "\n")
6345 (forward-line -1))
6346 ((not (markdown-cur-line-blank-p))
6347 (newline)))
6348 (setq new-loc (point)))
6349 ;; Look ahead for a list item on next non-blank line
6350 (unless bounds
6351 (save-excursion
6352 (while (and (null bounds)
6353 (not (eobp))
6354 (markdown-cur-line-blank-p))
6355 (forward-line)
6356 (setq bounds (markdown-cur-list-item-bounds))))
6357 (when bounds
6358 (setq new-loc (point))
6359 (unless (markdown-cur-line-blank-p)
6360 (newline))))
6361 (if (not bounds)
6362 ;; When not in a list, start a new unordered one
6363 (progn
6364 (unless (markdown-cur-line-blank-p)
6365 (insert "\n"))
6366 (insert markdown-unordered-list-item-prefix))
6367 ;; Compute indentation and marker for new list item
6368 (setq cur-indent (nth 2 bounds))
6369 (setq marker (nth 4 bounds))
6370 ;; If current item is a GFM checkbox, insert new unchecked checkbox.
6371 (when (nth 5 bounds)
6372 (setq marker
6373 (concat marker
6374 (replace-regexp-in-string "[Xx]" " " (nth 5 bounds)))))
6375 (cond
6376 ;; Dedent: decrement indentation, find previous marker.
6377 ((= arg 4)
6378 (setq indent (max (- cur-indent 4) 0))
6379 (let ((prev-bounds
6380 (save-excursion
6381 (goto-char (nth 0 bounds))
6382 (when (markdown-up-list)
6383 (markdown-cur-list-item-bounds)))))
6384 (when prev-bounds
6385 (setq marker (nth 4 prev-bounds)))))
6386 ;; Indent: increment indentation by 4, use same marker.
6387 ((= arg 16) (setq indent (+ cur-indent 4)))
6388 ;; Same level: keep current indentation and marker.
6389 (t (setq indent cur-indent)))
6390 (setq new-indent (make-string indent 32))
6391 (goto-char new-loc)
6392 (cond
6393 ;; Ordered list
6394 ((string-match-p "[0-9]" marker)
6395 (if (= arg 16) ;; starting a new column indented one more level
6396 (insert (concat new-indent "1. "))
6397 ;; Don't use previous match-data
6398 (set-match-data nil)
6399 ;; travel up to the last item and pick the correct number. If
6400 ;; the argument was nil, "new-indent = cur-indent" is the same,
6401 ;; so we don't need special treatment. Neat.
6402 (save-excursion
6403 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
6404 (>= (forward-line -1) 0))))
6405 (let* ((old-prefix (match-string 1))
6406 (old-spacing (match-string 2))
6407 (new-prefix (if old-prefix
6408 (int-to-string (1+ (string-to-number old-prefix)))
6409 "1"))
6410 (space-adjust (- (length old-prefix) (length new-prefix)))
6411 (new-spacing (if (and (match-string 2)
6412 (not (string-match-p "\t" old-spacing))
6413 (< space-adjust 0)
6414 (> space-adjust (- 1 (length (match-string 2)))))
6415 (substring (match-string 2) 0 space-adjust)
6416 (or old-spacing ". "))))
6417 (insert (concat new-indent new-prefix new-spacing)))))
6418 ;; Unordered list, GFM task list, or ordered list with hash mark
6419 ((string-match-p "[\\*\\+-]\\|#\\." marker)
6420 (insert new-indent marker)))))))
6422 (defun markdown-move-list-item-up ()
6423 "Move the current list item up in the list when possible.
6424 In nested lists, move child items with the parent item."
6425 (interactive)
6426 (let (cur prev old)
6427 (when (setq cur (markdown-cur-list-item-bounds))
6428 (setq old (point))
6429 (goto-char (nth 0 cur))
6430 (if (markdown-prev-list-item (nth 3 cur))
6431 (progn
6432 (setq prev (markdown-cur-list-item-bounds))
6433 (condition-case nil
6434 (progn
6435 (transpose-regions (nth 0 prev) (nth 1 prev)
6436 (nth 0 cur) (nth 1 cur) t)
6437 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
6438 ;; Catch error in case regions overlap.
6439 (error (goto-char old))))
6440 (goto-char old)))))
6442 (defun markdown-move-list-item-down ()
6443 "Move the current list item down in the list when possible.
6444 In nested lists, move child items with the parent item."
6445 (interactive)
6446 (let (cur next old)
6447 (when (setq cur (markdown-cur-list-item-bounds))
6448 (setq old (point))
6449 (if (markdown-next-list-item (nth 3 cur))
6450 (progn
6451 (setq next (markdown-cur-list-item-bounds))
6452 (condition-case nil
6453 (progn
6454 (transpose-regions (nth 0 cur) (nth 1 cur)
6455 (nth 0 next) (nth 1 next) nil)
6456 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
6457 ;; Catch error in case regions overlap.
6458 (error (goto-char old))))
6459 (goto-char old)))))
6461 (defun markdown-demote-list-item (&optional bounds)
6462 "Indent (or demote) the current list item.
6463 Optionally, BOUNDS of the current list item may be provided if available.
6464 In nested lists, demote child items as well."
6465 (interactive)
6466 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6467 (save-excursion
6468 (let ((end-marker (set-marker (make-marker) (nth 1 bounds))))
6469 (goto-char (nth 0 bounds))
6470 (while (< (point) end-marker)
6471 (unless (markdown-cur-line-blank-p)
6472 (insert (make-string markdown-list-indent-width ? )))
6473 (forward-line))))))
6475 (defun markdown-promote-list-item (&optional bounds)
6476 "Unindent (or promote) the current list item.
6477 Optionally, BOUNDS of the current list item may be provided if available.
6478 In nested lists, demote child items as well."
6479 (interactive)
6480 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6481 (save-excursion
6482 (save-match-data
6483 (let ((end-marker (set-marker (make-marker) (nth 1 bounds)))
6484 num regexp)
6485 (goto-char (nth 0 bounds))
6486 (when (looking-at (format "^[ ]\\{1,%d\\}"
6487 markdown-list-indent-width))
6488 (setq num (- (match-end 0) (match-beginning 0)))
6489 (setq regexp (format "^[ ]\\{1,%d\\}" num))
6490 (while (and (< (point) end-marker)
6491 (re-search-forward regexp end-marker t))
6492 (replace-match "" nil nil)
6493 (forward-line))))))))
6495 (defun markdown-cleanup-list-numbers-level (&optional pfx)
6496 "Update the numbering for level PFX (as a string of spaces).
6498 Assume that the previously found match was for a numbered item in
6499 a list."
6500 (let ((cpfx pfx)
6501 (idx 0)
6502 (continue t)
6503 (step t)
6504 (sep nil))
6505 (while (and continue (not (eobp)))
6506 (setq step t)
6507 (cond
6508 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
6509 (setq cpfx (match-string-no-properties 1))
6510 (cond
6511 ((string= cpfx pfx)
6512 (save-excursion
6513 (replace-match
6514 (concat pfx (number-to-string (setq idx (1+ idx))) ". ")))
6515 (setq sep nil))
6516 ;; indented a level
6517 ((string< pfx cpfx)
6518 (setq sep (markdown-cleanup-list-numbers-level cpfx))
6519 (setq step nil))
6520 ;; exit the loop
6522 (setq step nil)
6523 (setq continue nil))))
6525 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
6526 (setq cpfx (match-string-no-properties 1))
6527 (cond
6528 ;; reset if separated before
6529 ((string= cpfx pfx) (when sep (setq idx 0)))
6530 ((string< cpfx pfx)
6531 (setq step nil)
6532 (setq continue nil))))
6533 (t (setq sep t)))
6535 (when step
6536 (beginning-of-line)
6537 (setq continue (= (forward-line) 0))))
6538 sep))
6540 (defun markdown-cleanup-list-numbers ()
6541 "Update the numbering of ordered lists."
6542 (interactive)
6543 (save-excursion
6544 (goto-char (point-min))
6545 (markdown-cleanup-list-numbers-level "")))
6548 ;;; Movement ==================================================================
6550 (defun markdown-beginning-of-defun (&optional arg)
6551 "`beginning-of-defun-function' for Markdown.
6552 This is used to find the beginning of the defun and should behave
6553 like ‘beginning-of-defun’, returning non-nil if it found the
6554 beginning of a defun. It moves the point backward, right before a
6555 heading which defines a defun. When ARG is non-nil, repeat that
6556 many times. When ARG is negative, move forward to the ARG-th
6557 following section."
6558 (or arg (setq arg 1))
6559 (when (< arg 0) (end-of-line))
6560 ;; Adjust position for setext headings.
6561 (when (and (thing-at-point-looking-at markdown-regex-header-setext)
6562 (not (= (point) (match-beginning 0)))
6563 (not (markdown-code-block-at-point-p)))
6564 (goto-char (match-end 0)))
6565 (let (found)
6566 ;; Move backward with positive argument.
6567 (while (and (not (bobp)) (> arg 0))
6568 (setq found nil)
6569 (while (and (not found)
6570 (not (bobp))
6571 (re-search-backward markdown-regex-header nil 'move))
6572 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6573 (setq found (match-beginning 0)))
6574 (setq arg (1- arg)))
6575 ;; Move forward with negative argument.
6576 (while (and (not (eobp)) (< arg 0))
6577 (setq found nil)
6578 (while (and (not found)
6579 (not (eobp))
6580 (re-search-forward markdown-regex-header nil 'move))
6581 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6582 (setq found (match-beginning 0)))
6583 (setq arg (1+ arg)))
6584 (when found
6585 (beginning-of-line)
6586 t)))
6588 (defun markdown-end-of-defun ()
6589 "`end-of-defun-function’ for Markdown.
6590 This is used to find the end of the defun at point.
6591 It is called with no argument, right after calling ‘beginning-of-defun-raw’,
6592 so it can assume that point is at the beginning of the defun body.
6593 It should move point to the first position after the defun."
6594 (or (eobp) (forward-char 1))
6595 (let (found)
6596 (while (and (not found)
6597 (not (eobp))
6598 (re-search-forward markdown-regex-header nil 'move))
6599 (when (not (markdown-code-block-at-pos (match-beginning 0)))
6600 (setq found (match-beginning 0))))
6601 (when found
6602 (goto-char found)
6603 (skip-syntax-backward "-"))))
6605 (make-obsolete 'markdown-beginning-of-block 'markdown-beginning-of-text-block "v2.2")
6607 (defun markdown-beginning-of-text-block ()
6608 "Move backward to previous beginning of a plain text block.
6609 This function simply looks for blank lines without considering
6610 the surrounding context in light of Markdown syntax. For that, see
6611 `markdown-backward-block'."
6612 (interactive)
6613 (let ((start (point)))
6614 (if (re-search-backward markdown-regex-block-separator nil t)
6615 (goto-char (match-end 0))
6616 (goto-char (point-min)))
6617 (when (and (= start (point)) (not (bobp)))
6618 (forward-line -1)
6619 (if (re-search-backward markdown-regex-block-separator nil t)
6620 (goto-char (match-end 0))
6621 (goto-char (point-min))))))
6623 (make-obsolete 'markdown-end-of-block 'markdown-end-of-text-block "v2.2")
6625 (defun markdown-end-of-text-block ()
6626 "Move forward to next beginning of a plain text block.
6627 This function simply looks for blank lines without considering
6628 the surrounding context in light of Markdown syntax. For that, see
6629 `markdown-forward-block'."
6630 (interactive)
6631 (beginning-of-line)
6632 (skip-syntax-forward "-")
6633 (when (= (point) (point-min))
6634 (forward-char))
6635 (if (re-search-forward markdown-regex-block-separator nil t)
6636 (goto-char (match-end 0))
6637 (goto-char (point-max)))
6638 (skip-syntax-backward "-")
6639 (forward-line))
6641 (defun markdown-backward-paragraph (&optional arg)
6642 "Move the point to the start of the current paragraph.
6643 With argument ARG, do it ARG times; a negative argument ARG = -N
6644 means move forward N blocks."
6645 (interactive "^p")
6646 (or arg (setq arg 1))
6647 (if (< arg 0)
6648 (markdown-forward-paragraph (- arg))
6649 (dotimes (_ arg)
6650 ;; Skip over whitespace in between paragraphs when moving backward.
6651 (skip-syntax-backward "-")
6652 (beginning-of-line)
6653 ;; Skip over code block endings.
6654 (when (markdown-range-properties-exist
6655 (point-at-bol) (point-at-eol)
6656 '(markdown-gfm-block-end
6657 markdown-tilde-fence-end))
6658 (forward-line -1))
6659 ;; Skip over blank lines inside blockquotes.
6660 (while (and (not (eobp))
6661 (looking-at markdown-regex-blockquote)
6662 (= (length (match-string 3)) 0))
6663 (forward-line -1))
6664 ;; Proceed forward based on the type of block of paragraph.
6665 (let (bounds skip)
6666 (cond
6667 ;; Blockquotes
6668 ((looking-at markdown-regex-blockquote)
6669 (while (and (not (bobp))
6670 (looking-at markdown-regex-blockquote)
6671 (> (length (match-string 3)) 0)) ;; not blank
6672 (forward-line -1))
6673 (forward-line))
6674 ;; List items
6675 ((setq bounds (markdown-cur-list-item-bounds))
6676 (goto-char (nth 0 bounds)))
6677 ;; Other
6679 (while (and (not (bobp))
6680 (not skip)
6681 (not (markdown-cur-line-blank-p))
6682 (not (looking-at markdown-regex-blockquote))
6683 (not (markdown-range-properties-exist
6684 (point-at-bol) (point-at-eol)
6685 '(markdown-gfm-block-end
6686 markdown-tilde-fence-end))))
6687 (setq skip (markdown-range-properties-exist
6688 (point-at-bol) (point-at-eol)
6689 '(markdown-gfm-block-begin
6690 markdown-tilde-fence-begin)))
6691 (forward-line -1))
6692 (unless (bobp)
6693 (forward-line 1))))))))
6695 (defun markdown-forward-paragraph (&optional arg)
6696 "Move forward to the next end of a paragraph.
6697 With argument ARG, do it ARG times; a negative argument ARG = -N
6698 means move backward N blocks."
6699 (interactive "^p")
6700 (or arg (setq arg 1))
6701 (if (< arg 0)
6702 (markdown-backward-paragraph (- arg))
6703 (dotimes (_ arg)
6704 ;; Skip whitespace in between paragraphs.
6705 (when (markdown-cur-line-blank-p)
6706 (skip-syntax-forward "-")
6707 (beginning-of-line))
6708 ;; Proceed forward based on the type of block.
6709 (let (bounds skip)
6710 (cond
6711 ;; Blockquotes
6712 ((looking-at markdown-regex-blockquote)
6713 ;; Skip over blank lines inside blockquotes.
6714 (while (and (not (eobp))
6715 (looking-at markdown-regex-blockquote)
6716 (= (length (match-string 3)) 0))
6717 (forward-line))
6718 ;; Move to end of quoted text block
6719 (while (and (not (eobp))
6720 (looking-at markdown-regex-blockquote)
6721 (> (length (match-string 3)) 0)) ;; not blank
6722 (forward-line)))
6723 ;; List items
6724 ((and (markdown-cur-list-item-bounds)
6725 (setq bounds (markdown-next-list-item-bounds)))
6726 (goto-char (nth 0 bounds)))
6727 ;; Other
6729 (forward-line)
6730 (while (and (not (eobp))
6731 (not skip)
6732 (not (markdown-cur-line-blank-p))
6733 (not (looking-at markdown-regex-blockquote))
6734 (not (markdown-range-properties-exist
6735 (point-at-bol) (point-at-eol)
6736 '(markdown-gfm-block-begin
6737 markdown-tilde-fence-begin))))
6738 (setq skip (markdown-range-properties-exist
6739 (point-at-bol) (point-at-eol)
6740 '(markdown-gfm-block-end
6741 markdown-tilde-fence-end)))
6742 (forward-line))))))))
6744 (defun markdown-backward-block (&optional arg)
6745 "Move the point to the start of the current Markdown block.
6746 Moves across complete code blocks, list items, and blockquotes,
6747 but otherwise stops at blank lines, headers, and horizontal
6748 rules. With argument ARG, do it ARG times; a negative argument
6749 ARG = -N means move forward N blocks."
6750 (interactive "^p")
6751 (or arg (setq arg 1))
6752 (if (< arg 0)
6753 (markdown-forward-block (- arg))
6754 (dotimes (_ arg)
6755 ;; Skip over whitespace in between blocks when moving backward,
6756 ;; unless at a block boundary with no whitespace.
6757 (skip-syntax-backward "-")
6758 (beginning-of-line)
6759 ;; Proceed forward based on the type of block.
6760 (cond
6761 ;; Code blocks
6762 ((and (markdown-code-block-at-pos (point)) ;; this line
6763 (markdown-code-block-at-pos (point-at-bol 0))) ;; previous line
6764 (forward-line -1)
6765 (while (and (markdown-code-block-at-point-p) (not (bobp)))
6766 (forward-line -1))
6767 (forward-line))
6768 ;; Headings
6769 ((markdown-heading-at-point)
6770 (goto-char (match-beginning 0)))
6771 ;; Horizontal rules
6772 ((looking-at markdown-regex-hr))
6773 ;; Blockquotes
6774 ((looking-at markdown-regex-blockquote)
6775 (forward-line -1)
6776 (while (and (looking-at markdown-regex-blockquote)
6777 (not (bobp)))
6778 (forward-line -1))
6779 (forward-line))
6780 ;; List items
6781 ((markdown-cur-list-item-bounds)
6782 (markdown-beginning-of-list))
6783 ;; Other
6785 ;; Move forward in case it is a one line regular paragraph.
6786 (unless (markdown-next-line-blank-p)
6787 (forward-line))
6788 (unless (markdown-prev-line-blank-p)
6789 (markdown-backward-paragraph)))))))
6791 (defun markdown-forward-block (&optional arg)
6792 "Move forward to the next end of a Markdown block.
6793 Moves across complete code blocks, list items, and blockquotes,
6794 but otherwise stops at blank lines, headers, and horizontal
6795 rules. With argument ARG, do it ARG times; a negative argument
6796 ARG = -N means move backward N blocks."
6797 (interactive "^p")
6798 (or arg (setq arg 1))
6799 (if (< arg 0)
6800 (markdown-backward-block (- arg))
6801 (dotimes (_ arg)
6802 ;; Skip over whitespace in between blocks when moving forward.
6803 (if (markdown-cur-line-blank-p)
6804 (skip-syntax-forward "-")
6805 (beginning-of-line))
6806 ;; Proceed forward based on the type of block.
6807 (cond
6808 ;; Code blocks
6809 ((markdown-code-block-at-point-p)
6810 (forward-line)
6811 (while (and (markdown-code-block-at-point-p) (not (eobp)))
6812 (forward-line)))
6813 ;; Headings
6814 ((looking-at markdown-regex-header)
6815 (goto-char (or (match-end 4) (match-end 2) (match-end 3)))
6816 (forward-line))
6817 ;; Horizontal rules
6818 ((looking-at markdown-regex-hr)
6819 (forward-line))
6820 ;; Blockquotes
6821 ((looking-at markdown-regex-blockquote)
6822 (forward-line)
6823 (while (and (looking-at markdown-regex-blockquote) (not (eobp)))
6824 (forward-line)))
6825 ;; List items
6826 ((markdown-cur-list-item-bounds)
6827 (markdown-end-of-list)
6828 (forward-line))
6829 ;; Other
6830 (t (markdown-forward-paragraph))))
6831 (skip-syntax-backward "-")
6832 (unless (eobp)
6833 (forward-char 1))))
6835 (defun markdown-backward-page (&optional count)
6836 "Move backward to boundary of the current toplevel section.
6837 With COUNT, repeat, or go forward if negative."
6838 (interactive "p")
6839 (or count (setq count 1))
6840 (if (< count 0)
6841 (markdown-forward-page (- count))
6842 (skip-syntax-backward "-")
6843 (or (markdown-back-to-heading-over-code-block t t)
6844 (goto-char (point-min)))
6845 (when (looking-at markdown-regex-header)
6846 (let ((level (markdown-outline-level)))
6847 (when (> level 1) (markdown-up-heading level))
6848 (when (> count 1)
6849 (condition-case nil
6850 (markdown-backward-same-level (1- count))
6851 (error (goto-char (point-min)))))))))
6853 (defun markdown-forward-page (&optional count)
6854 "Move forward to boundary of the current toplevel section.
6855 With COUNT, repeat, or go backward if negative."
6856 (interactive "p")
6857 (or count (setq count 1))
6858 (if (< count 0)
6859 (markdown-backward-page (- count))
6860 (if (markdown-back-to-heading-over-code-block t t)
6861 (let ((level (markdown-outline-level)))
6862 (when (> level 1) (markdown-up-heading level))
6863 (condition-case nil
6864 (markdown-forward-same-level count)
6865 (error (goto-char (point-max)))))
6866 (markdown-next-visible-heading 1))))
6868 (defun markdown-next-link ()
6869 "Jump to next inline, reference, or wiki link.
6870 If successful, return point. Otherwise, return nil.
6871 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
6872 (interactive)
6873 (let ((opoint (point)))
6874 (when (or (markdown-link-p) (markdown-wiki-link-p))
6875 ;; At a link already, move past it.
6876 (goto-char (+ (match-end 0) 1)))
6877 ;; Search for the next wiki link and move to the beginning.
6878 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t)
6879 (markdown-code-block-at-point-p)
6880 (< (point) (point-max))))
6881 (if (and (not (eq (point) opoint))
6882 (or (markdown-link-p) (markdown-wiki-link-p)))
6883 ;; Group 1 will move past non-escape character in wiki link regexp.
6884 ;; Go to beginning of group zero for all other link types.
6885 (goto-char (or (match-beginning 1) (match-beginning 0)))
6886 (goto-char opoint)
6887 nil)))
6889 (defun markdown-previous-link ()
6890 "Jump to previous wiki link.
6891 If successful, return point. Otherwise, return nil.
6892 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
6893 (interactive)
6894 (let ((opoint (point)))
6895 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t)
6896 (markdown-code-block-at-point-p)
6897 (> (point) (point-min))))
6898 (if (and (not (eq (point) opoint))
6899 (or (markdown-link-p) (markdown-wiki-link-p)))
6900 (goto-char (or (match-beginning 1) (match-beginning 0)))
6901 (goto-char opoint)
6902 nil)))
6905 ;;; Outline ===================================================================
6907 (defun markdown-move-heading-common (move-fn &optional arg adjust)
6908 "Wrapper for `outline-mode' functions to skip false positives.
6909 MOVE-FN is a function and ARG is its argument. For example,
6910 headings inside preformatted code blocks may match
6911 `outline-regexp' but should not be considered as headings.
6912 When ADJUST is non-nil, adjust the point for interactive calls
6913 to avoid leaving the point at invisible markup. This adjustment
6914 generally should only be done for interactive calls, since other
6915 functions may expect the point to be at the beginning of the
6916 regular expression."
6917 (let ((prev -1) (start (point)))
6918 (if arg (funcall move-fn arg) (funcall move-fn))
6919 (while (and (/= prev (point)) (markdown-code-block-at-point-p))
6920 (setq prev (point))
6921 (if arg (funcall move-fn arg) (funcall move-fn)))
6922 ;; Adjust point for setext headings and invisible text.
6923 (save-match-data
6924 (when (and adjust (thing-at-point-looking-at markdown-regex-header))
6925 (if markdown-hide-markup
6926 ;; Move to beginning of heading text if markup is hidden.
6927 (goto-char (or (match-beginning 1) (match-beginning 5)))
6928 ;; Move to beginning of markup otherwise.
6929 (goto-char (or (match-beginning 1) (match-beginning 4))))))
6930 (if (= (point) start) nil (point))))
6932 (defun markdown-next-visible-heading (arg)
6933 "Move to the next visible heading line of any level.
6934 With argument, repeats or can move backward if negative. ARG is
6935 passed to `outline-next-visible-heading'."
6936 (interactive "p")
6937 (markdown-move-heading-common #'outline-next-visible-heading arg 'adjust))
6939 (defun markdown-previous-visible-heading (arg)
6940 "Move to the previous visible heading line of any level.
6941 With argument, repeats or can move backward if negative. ARG is
6942 passed to `outline-previous-visible-heading'."
6943 (interactive "p")
6944 (markdown-move-heading-common #'outline-previous-visible-heading arg 'adjust))
6946 (defun markdown-next-heading ()
6947 "Move to the next heading line of any level."
6948 (markdown-move-heading-common #'outline-next-heading))
6950 (defun markdown-previous-heading ()
6951 "Move to the previous heading line of any level."
6952 (markdown-move-heading-common #'outline-previous-heading))
6954 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok no-error)
6955 "Move back to the beginning of the previous heading.
6956 Returns t if the point is at a heading, the location if a heading
6957 was found, and nil otherwise.
6958 Only visible heading lines are considered, unless INVISIBLE-OK is
6959 non-nil. Throw an error if there is no previous heading unless
6960 NO-ERROR is non-nil.
6961 Leaves match data intact for `markdown-regex-header'."
6962 (beginning-of-line)
6963 (or (and (markdown-heading-at-point)
6964 (not (markdown-code-block-at-point-p)))
6965 (let (found)
6966 (save-excursion
6967 (while (and (not found)
6968 (re-search-backward markdown-regex-header nil t))
6969 (when (and (or invisible-ok (not (outline-invisible-p)))
6970 (not (markdown-code-block-at-point-p)))
6971 (setq found (point))))
6972 (if (not found)
6973 (unless no-error (user-error "Before first heading"))
6974 (setq found (point))))
6975 (when found (goto-char found)))))
6977 (defun markdown-forward-same-level (arg)
6978 "Move forward to the ARG'th heading at same level as this one.
6979 Stop at the first and last headings of a superior heading."
6980 (interactive "p")
6981 (markdown-back-to-heading-over-code-block)
6982 (markdown-move-heading-common #'outline-forward-same-level arg 'adjust))
6984 (defun markdown-backward-same-level (arg)
6985 "Move backward to the ARG'th heading at same level as this one.
6986 Stop at the first and last headings of a superior heading."
6987 (interactive "p")
6988 (markdown-back-to-heading-over-code-block)
6989 (while (> arg 0)
6990 (let ((point-to-move-to
6991 (save-excursion
6992 (markdown-move-heading-common #'outline-get-last-sibling nil 'adjust))))
6993 (if point-to-move-to
6994 (progn
6995 (goto-char point-to-move-to)
6996 (setq arg (1- arg)))
6997 (user-error "No previous same-level heading")))))
6999 (defun markdown-up-heading (arg)
7000 "Move to the visible heading line of which the present line is a subheading.
7001 With argument, move up ARG levels."
7002 (interactive "p")
7003 (and (called-interactively-p 'any)
7004 (not (eq last-command 'markdown-up-heading)) (push-mark))
7005 (markdown-move-heading-common #'outline-up-heading arg 'adjust))
7007 (defun markdown-back-to-heading (&optional invisible-ok)
7008 "Move to previous heading line, or beg of this line if it's a heading.
7009 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
7010 (markdown-move-heading-common #'outline-back-to-heading invisible-ok))
7012 (defalias 'markdown-end-of-heading 'outline-end-of-heading)
7014 (defun markdown-on-heading-p ()
7015 "Return non-nil if point is on a heading line."
7016 (get-text-property (point-at-bol) 'markdown-heading))
7018 (defun markdown-end-of-subtree (&optional invisible-OK)
7019 "Move to the end of the current subtree.
7020 Only visible heading lines are considered, unless INVISIBLE-OK is
7021 non-nil.
7022 Derived from `org-end-of-subtree'."
7023 (markdown-back-to-heading invisible-OK)
7024 (let ((first t)
7025 (level (markdown-outline-level)))
7026 (while (and (not (eobp))
7027 (or first (> (markdown-outline-level) level)))
7028 (setq first nil)
7029 (markdown-next-heading))
7030 (if (memq (preceding-char) '(?\n ?\^M))
7031 (progn
7032 ;; Go to end of line before heading
7033 (forward-char -1)
7034 (if (memq (preceding-char) '(?\n ?\^M))
7035 ;; leave blank line before heading
7036 (forward-char -1)))))
7037 (point))
7039 (defun markdown-outline-fix-visibility ()
7040 "Hide any false positive headings that should not be shown.
7041 For example, headings inside preformatted code blocks may match
7042 `outline-regexp' but should not be shown as headings when cycling.
7043 Also, the ending --- line in metadata blocks appears to be a
7044 setext header, but should not be folded."
7045 (save-excursion
7046 (goto-char (point-min))
7047 ;; Unhide any false positives in metadata blocks
7048 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin)
7049 (let ((body (progn (forward-line)
7050 (markdown-text-property-at-point
7051 'markdown-yaml-metadata-section))))
7052 (when body
7053 (let ((end (progn (goto-char (cl-second body))
7054 (markdown-text-property-at-point
7055 'markdown-yaml-metadata-end))))
7056 (outline-flag-region (point-min) (1+ (cl-second end)) nil)))))
7057 ;; Hide any false positives in code blocks
7058 (unless (outline-on-heading-p)
7059 (outline-next-visible-heading 1))
7060 (while (< (point) (point-max))
7061 (when (markdown-code-block-at-point-p)
7062 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t))
7063 (outline-next-visible-heading 1))))
7065 (defvar markdown-cycle-global-status 1)
7066 (defvar markdown-cycle-subtree-status nil)
7068 (defun markdown-next-preface ()
7069 (let (finish)
7070 (while (and (not finish) (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
7071 nil 'move))
7072 (unless (markdown-code-block-at-point-p)
7073 (goto-char (match-beginning 0))
7074 (setq finish t))))
7075 (when (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
7076 (forward-char -1)))
7078 (defun markdown-show-entry ()
7079 (save-excursion
7080 (outline-back-to-heading t)
7081 (outline-flag-region (1- (point))
7082 (progn
7083 (markdown-next-preface)
7084 (if (= 1 (- (point-max) (point)))
7085 (point-max)
7086 (point)))
7087 nil)))
7089 ;; This function was originally derived from `org-cycle' from org.el.
7090 (defun markdown-cycle (&optional arg)
7091 "Visibility cycling for Markdown mode.
7092 If ARG is t, perform global visibility cycling. If the point is
7093 at an atx-style header, cycle visibility of the corresponding
7094 subtree. Otherwise, indent the current line or insert a tab,
7095 as appropriate, by calling `indent-for-tab-command'."
7096 (interactive "P")
7097 (cond
7098 ((eq arg t) ;; Global cycling
7099 (cond
7100 ((and (eq last-command this-command)
7101 (eq markdown-cycle-global-status 2))
7102 ;; Move from overview to contents
7103 (markdown-hide-sublevels 1)
7104 (message "CONTENTS")
7105 (setq markdown-cycle-global-status 3)
7106 (markdown-outline-fix-visibility))
7108 ((and (eq last-command this-command)
7109 (eq markdown-cycle-global-status 3))
7110 ;; Move from contents to all
7111 (markdown-show-all)
7112 (message "SHOW ALL")
7113 (setq markdown-cycle-global-status 1))
7116 ;; Defaults to overview
7117 (markdown-hide-body)
7118 (message "OVERVIEW")
7119 (setq markdown-cycle-global-status 2)
7120 (markdown-outline-fix-visibility))))
7122 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
7123 ;; At a heading: rotate between three different views
7124 (markdown-back-to-heading)
7125 (let ((goal-column 0) eoh eol eos)
7126 ;; Determine boundaries
7127 (save-excursion
7128 (markdown-back-to-heading)
7129 (save-excursion
7130 (beginning-of-line 2)
7131 (while (and (not (eobp)) ;; this is like `next-line'
7132 (get-char-property (1- (point)) 'invisible))
7133 (beginning-of-line 2)) (setq eol (point)))
7134 (markdown-end-of-heading) (setq eoh (point))
7135 (markdown-end-of-subtree t)
7136 (skip-chars-forward " \t\n")
7137 (beginning-of-line 1) ; in case this is an item
7138 (setq eos (1- (point))))
7139 ;; Find out what to do next and set `this-command'
7140 (cond
7141 ((= eos eoh)
7142 ;; Nothing is hidden behind this heading
7143 (message "EMPTY ENTRY")
7144 (setq markdown-cycle-subtree-status nil))
7145 ((>= eol eos)
7146 ;; Entire subtree is hidden in one line: open it
7147 (markdown-show-entry)
7148 (markdown-show-children)
7149 (message "CHILDREN")
7150 (setq markdown-cycle-subtree-status 'children))
7151 ((and (eq last-command this-command)
7152 (eq markdown-cycle-subtree-status 'children))
7153 ;; We just showed the children, now show everything.
7154 (markdown-show-subtree)
7155 (message "SUBTREE")
7156 (setq markdown-cycle-subtree-status 'subtree))
7158 ;; Default action: hide the subtree.
7159 (markdown-hide-subtree)
7160 (message "FOLDED")
7161 (setq markdown-cycle-subtree-status 'folded)))))
7164 (indent-for-tab-command))))
7166 (defun markdown-shifttab ()
7167 "Global visibility cycling.
7168 Calls `markdown-cycle' with argument t."
7169 (interactive)
7170 (markdown-cycle t))
7172 (defun markdown-outline-level ()
7173 "Return the depth to which a statement is nested in the outline."
7174 (cond
7175 ((and (match-beginning 0)
7176 (markdown-code-block-at-pos (match-beginning 0)))
7177 7) ;; Only 6 header levels are defined.
7178 ((match-end 2) 1)
7179 ((match-end 3) 2)
7180 ((match-end 4)
7181 (length (markdown-trim-whitespace (match-string-no-properties 4))))))
7183 (defun markdown-promote-subtree (&optional arg)
7184 "Promote the current subtree of ATX headings.
7185 Note that Markdown does not support heading levels higher than
7186 six and therefore level-six headings will not be promoted
7187 further. If ARG is non-nil promote the heading, otherwise
7188 demote."
7189 (interactive "*P")
7190 (save-excursion
7191 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
7192 (re-search-backward markdown-regex-header-atx nil t))
7193 (not (markdown-code-block-at-point-p)))
7194 (let ((level (length (match-string 1)))
7195 (promote-or-demote (if arg 1 -1))
7196 (remove 't))
7197 (markdown-cycle-atx promote-or-demote remove)
7198 (catch 'end-of-subtree
7199 (while (and (markdown-next-heading)
7200 (looking-at markdown-regex-header-atx))
7201 ;; Exit if this not a higher level heading; promote otherwise.
7202 (if (and (looking-at markdown-regex-header-atx)
7203 (<= (length (match-string-no-properties 1)) level))
7204 (throw 'end-of-subtree nil)
7205 (markdown-cycle-atx promote-or-demote remove))))))))
7207 (defun markdown-demote-subtree ()
7208 "Demote the current subtree of ATX headings."
7209 (interactive)
7210 (markdown-promote-subtree t))
7212 (defun markdown-move-subtree-up ()
7213 "Move the current subtree of ATX headings up."
7214 (interactive)
7215 (outline-move-subtree-up 1))
7217 (defun markdown-move-subtree-down ()
7218 "Move the current subtree of ATX headings down."
7219 (interactive)
7220 (outline-move-subtree-down 1))
7222 (defun markdown-outline-next ()
7223 "Move to next list item, when in a list, or next visible heading."
7224 (interactive)
7225 (let ((bounds (markdown-next-list-item-bounds)))
7226 (if bounds
7227 (goto-char (nth 0 bounds))
7228 (markdown-next-visible-heading 1))))
7230 (defun markdown-outline-previous ()
7231 "Move to previous list item, when in a list, or previous visible heading."
7232 (interactive)
7233 (let ((bounds (markdown-prev-list-item-bounds)))
7234 (if bounds
7235 (goto-char (nth 0 bounds))
7236 (markdown-previous-visible-heading 1))))
7238 (defun markdown-outline-next-same-level ()
7239 "Move to next list item or heading of same level."
7240 (interactive)
7241 (let ((bounds (markdown-cur-list-item-bounds)))
7242 (if bounds
7243 (markdown-next-list-item (nth 3 bounds))
7244 (markdown-forward-same-level 1))))
7246 (defun markdown-outline-previous-same-level ()
7247 "Move to previous list item or heading of same level."
7248 (interactive)
7249 (let ((bounds (markdown-cur-list-item-bounds)))
7250 (if bounds
7251 (markdown-prev-list-item (nth 3 bounds))
7252 (markdown-backward-same-level 1))))
7254 (defun markdown-outline-up ()
7255 "Move to previous list item, when in a list, or next heading."
7256 (interactive)
7257 (unless (markdown-up-list)
7258 (markdown-up-heading 1)))
7261 ;;; Marking and Narrowing =====================================================
7263 (defun markdown-mark-paragraph ()
7264 "Put mark at end of this block, point at beginning.
7265 The block marked is the one that contains point or follows point.
7267 Interactively, if this command is repeated or (in Transient Mark
7268 mode) if the mark is active, it marks the next block after the
7269 ones already marked."
7270 (interactive)
7271 (if (or (and (eq last-command this-command) (mark t))
7272 (and transient-mark-mode mark-active))
7273 (set-mark
7274 (save-excursion
7275 (goto-char (mark))
7276 (markdown-forward-paragraph)
7277 (point)))
7278 (let ((beginning-of-defun-function 'markdown-backward-paragraph)
7279 (end-of-defun-function 'markdown-forward-paragraph))
7280 (mark-defun))))
7282 (defun markdown-mark-block ()
7283 "Put mark at end of this block, point at beginning.
7284 The block marked is the one that contains point or follows point.
7286 Interactively, if this command is repeated or (in Transient Mark
7287 mode) if the mark is active, it marks the next block after the
7288 ones already marked."
7289 (interactive)
7290 (if (or (and (eq last-command this-command) (mark t))
7291 (and transient-mark-mode mark-active))
7292 (set-mark
7293 (save-excursion
7294 (goto-char (mark))
7295 (markdown-forward-block)
7296 (point)))
7297 (let ((beginning-of-defun-function 'markdown-backward-block)
7298 (end-of-defun-function 'markdown-forward-block))
7299 (mark-defun))))
7301 (defun markdown-narrow-to-block ()
7302 "Make text outside current block invisible.
7303 The current block is the one that contains point or follows point."
7304 (interactive)
7305 (let ((beginning-of-defun-function 'markdown-backward-block)
7306 (end-of-defun-function 'markdown-forward-block))
7307 (narrow-to-defun)))
7309 (defun markdown-mark-text-block ()
7310 "Put mark at end of this plain text block, point at beginning.
7311 The block marked is the one that contains point or follows point.
7313 Interactively, if this command is repeated or (in Transient Mark
7314 mode) if the mark is active, it marks the next block after the
7315 ones already marked."
7316 (interactive)
7317 (if (or (and (eq last-command this-command) (mark t))
7318 (and transient-mark-mode mark-active))
7319 (set-mark
7320 (save-excursion
7321 (goto-char (mark))
7322 (markdown-end-of-text-block)
7323 (point)))
7324 (let ((beginning-of-defun-function 'markdown-beginning-of-text-block)
7325 (end-of-defun-function 'markdown-end-of-text-block))
7326 (mark-defun))))
7328 (defun markdown-mark-page ()
7329 "Put mark at end of this top level section, point at beginning.
7330 The top level section marked is the one that contains point or
7331 follows point.
7333 Interactively, if this command is repeated or (in Transient Mark
7334 mode) if the mark is active, it marks the next page after the
7335 ones already marked."
7336 (interactive)
7337 (if (or (and (eq last-command this-command) (mark t))
7338 (and transient-mark-mode mark-active))
7339 (set-mark
7340 (save-excursion
7341 (goto-char (mark))
7342 (markdown-forward-page)
7343 (point)))
7344 (let ((beginning-of-defun-function 'markdown-backward-page)
7345 (end-of-defun-function 'markdown-forward-page))
7346 (mark-defun))))
7348 (defun markdown-narrow-to-page ()
7349 "Make text outside current top level section invisible.
7350 The current section is the one that contains point or follows point."
7351 (interactive)
7352 (let ((beginning-of-defun-function 'markdown-backward-page)
7353 (end-of-defun-function 'markdown-forward-page))
7354 (narrow-to-defun)))
7356 (defun markdown-mark-subtree ()
7357 "Mark the current subtree.
7358 This puts point at the start of the current subtree, and mark at the end."
7359 (interactive)
7360 (let ((beg))
7361 (if (markdown-heading-at-point)
7362 (beginning-of-line)
7363 (markdown-previous-visible-heading 1))
7364 (setq beg (point))
7365 (markdown-end-of-subtree)
7366 (push-mark (point) nil t)
7367 (goto-char beg)))
7369 (defun markdown-narrow-to-subtree ()
7370 "Narrow buffer to the current subtree."
7371 (interactive)
7372 (save-excursion
7373 (save-match-data
7374 (narrow-to-region
7375 (progn (markdown-back-to-heading-over-code-block t) (point))
7376 (progn (markdown-end-of-subtree)
7377 (if (and (markdown-heading-at-point) (not (eobp)))
7378 (backward-char 1))
7379 (point))))))
7382 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
7384 (defun markdown-move-up ()
7385 "Move thing at point up.
7386 When in a list item, call `markdown-move-list-item-up'.
7387 Otherwise, move the current heading subtree up with
7388 `markdown-move-subtree-up'."
7389 (interactive)
7390 (cond
7391 ((markdown-list-item-at-point-p)
7392 (markdown-move-list-item-up))
7394 (markdown-move-subtree-up))))
7396 (defun markdown-move-down ()
7397 "Move thing at point down.
7398 When in a list item, call `markdown-move-list-item-down'.
7399 Otherwise, move the current heading subtree up with
7400 `markdown-move-subtree-down'."
7401 (interactive)
7402 (cond
7403 ((markdown-list-item-at-point-p)
7404 (markdown-move-list-item-down))
7406 (markdown-move-subtree-down))))
7408 (defun markdown-promote ()
7409 "Either promote header or list item at point or cycle markup.
7410 See `markdown-cycle-atx', `markdown-cycle-setext', and
7411 `markdown-promote-list-item'."
7412 (interactive)
7413 (let (bounds)
7414 (cond
7415 ;; Promote atx heading subtree
7416 ((thing-at-point-looking-at markdown-regex-header-atx)
7417 (markdown-promote-subtree))
7418 ;; Promote setext heading
7419 ((thing-at-point-looking-at markdown-regex-header-setext)
7420 (markdown-cycle-setext -1))
7421 ;; Promote horizonal rule
7422 ((thing-at-point-looking-at markdown-regex-hr)
7423 (markdown-cycle-hr -1))
7424 ;; Promote list item
7425 ((setq bounds (markdown-cur-list-item-bounds))
7426 (markdown-promote-list-item bounds))
7427 ;; Promote bold
7428 ((thing-at-point-looking-at markdown-regex-bold)
7429 (markdown-cycle-bold))
7430 ;; Promote italic
7431 ((thing-at-point-looking-at markdown-regex-italic)
7432 (markdown-cycle-italic))
7434 (user-error "Nothing to promote at point")))))
7436 (defun markdown-demote ()
7437 "Either demote header or list item at point or cycle or remove markup.
7438 See `markdown-cycle-atx', `markdown-cycle-setext', and
7439 `markdown-demote-list-item'."
7440 (interactive)
7441 (let (bounds)
7442 (cond
7443 ;; Demote atx heading subtree
7444 ((thing-at-point-looking-at markdown-regex-header-atx)
7445 (markdown-demote-subtree))
7446 ;; Demote setext heading
7447 ((thing-at-point-looking-at markdown-regex-header-setext)
7448 (markdown-cycle-setext 1))
7449 ;; Demote horizonal rule
7450 ((thing-at-point-looking-at markdown-regex-hr)
7451 (markdown-cycle-hr 1))
7452 ;; Demote list item
7453 ((setq bounds (markdown-cur-list-item-bounds))
7454 (markdown-demote-list-item bounds))
7455 ;; Demote bold
7456 ((thing-at-point-looking-at markdown-regex-bold)
7457 (markdown-cycle-bold))
7458 ;; Demote italic
7459 ((thing-at-point-looking-at markdown-regex-italic)
7460 (markdown-cycle-italic))
7462 (user-error "Nothing to demote at point")))))
7465 ;;; Commands ==================================================================
7467 (defun markdown (&optional output-buffer-name)
7468 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
7469 The output buffer name defaults to `markdown-output-buffer-name'.
7470 Return the name of the output buffer used."
7471 (interactive)
7472 (save-window-excursion
7473 (let ((begin-region)
7474 (end-region))
7475 (if (markdown-use-region-p)
7476 (setq begin-region (region-beginning)
7477 end-region (region-end))
7478 (setq begin-region (point-min)
7479 end-region (point-max)))
7481 (unless output-buffer-name
7482 (setq output-buffer-name markdown-output-buffer-name))
7483 (cond
7484 ;; Handle case when `markdown-command' does not read from stdin
7485 (markdown-command-needs-filename
7486 (if (not buffer-file-name)
7487 (user-error "Must be visiting a file")
7488 (shell-command (concat markdown-command " "
7489 (shell-quote-argument buffer-file-name))
7490 output-buffer-name)))
7491 ;; Pass region to `markdown-command' via stdin
7493 (let ((buf (get-buffer-create output-buffer-name)))
7494 (with-current-buffer buf
7495 (setq buffer-read-only nil)
7496 (erase-buffer))
7497 (call-process-region begin-region end-region
7498 shell-file-name nil buf nil
7499 shell-command-switch markdown-command)))))
7500 output-buffer-name))
7502 (defun markdown-standalone (&optional output-buffer-name)
7503 "Special function to provide standalone HTML output.
7504 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
7505 (interactive)
7506 (setq output-buffer-name (markdown output-buffer-name))
7507 (with-current-buffer output-buffer-name
7508 (set-buffer output-buffer-name)
7509 (unless (markdown-output-standalone-p)
7510 (markdown-add-xhtml-header-and-footer output-buffer-name))
7511 (goto-char (point-min))
7512 (html-mode))
7513 output-buffer-name)
7515 (defun markdown-other-window (&optional output-buffer-name)
7516 "Run `markdown-command' on current buffer and display in other window.
7517 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7518 that name."
7519 (interactive)
7520 (markdown-display-buffer-other-window
7521 (markdown-standalone output-buffer-name)))
7523 (defun markdown-output-standalone-p ()
7524 "Determine whether `markdown-command' output is standalone XHTML.
7525 Standalone XHTML output is identified by an occurrence of
7526 `markdown-xhtml-standalone-regexp' in the first five lines of output."
7527 (save-excursion
7528 (goto-char (point-min))
7529 (save-match-data
7530 (re-search-forward
7531 markdown-xhtml-standalone-regexp
7532 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
7533 t))))
7535 (defun markdown-stylesheet-link-string (stylesheet-path)
7536 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
7537 stylesheet-path
7538 "\" />"))
7540 (defun markdown-add-xhtml-header-and-footer (title)
7541 "Wrap XHTML header and footer with given TITLE around current buffer."
7542 (goto-char (point-min))
7543 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
7544 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
7545 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
7546 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
7547 "<head>\n<title>")
7548 (insert title)
7549 (insert "</title>\n")
7550 (when (> (length markdown-content-type) 0)
7551 (insert
7552 (format
7553 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
7554 markdown-content-type
7555 (or (and markdown-coding-system
7556 (fboundp 'coding-system-get)
7557 (coding-system-get markdown-coding-system
7558 'mime-charset))
7559 (and (fboundp 'coding-system-get)
7560 (coding-system-get buffer-file-coding-system
7561 'mime-charset))
7562 "iso-8859-1"))))
7563 (if (> (length markdown-css-paths) 0)
7564 (insert (mapconcat #'markdown-stylesheet-link-string
7565 markdown-css-paths "\n")))
7566 (when (> (length markdown-xhtml-header-content) 0)
7567 (insert markdown-xhtml-header-content))
7568 (insert "\n</head>\n\n"
7569 "<body>\n\n")
7570 (goto-char (point-max))
7571 (insert "\n"
7572 "</body>\n"
7573 "</html>\n"))
7575 (defun markdown-preview (&optional output-buffer-name)
7576 "Run `markdown-command' on the current buffer and view output in browser.
7577 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7578 that name."
7579 (interactive)
7580 (browse-url-of-buffer
7581 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
7583 (defun markdown-export-file-name (&optional extension)
7584 "Attempt to generate a filename for Markdown output.
7585 The file extension will be EXTENSION if given, or .html by default.
7586 If the current buffer is visiting a file, we construct a new
7587 output filename based on that filename. Otherwise, return nil."
7588 (when (buffer-file-name)
7589 (unless extension
7590 (setq extension ".html"))
7591 (let ((candidate
7592 (concat
7593 (cond
7594 ((buffer-file-name)
7595 (file-name-sans-extension (buffer-file-name)))
7596 (t (buffer-name)))
7597 extension)))
7598 (cond
7599 ((equal candidate (buffer-file-name))
7600 (concat candidate extension))
7602 candidate)))))
7604 (defun markdown-export (&optional output-file)
7605 "Run Markdown on the current buffer, save to file, and return the filename.
7606 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
7607 generated by `markdown-export-file-name', which will be constructed using the
7608 current filename, but with the extension removed and replaced with .html."
7609 (interactive)
7610 (unless output-file
7611 (setq output-file (markdown-export-file-name ".html")))
7612 (when output-file
7613 (let* ((init-buf (current-buffer))
7614 (init-point (point))
7615 (init-buf-string (buffer-string))
7616 (output-buffer (find-file-noselect output-file))
7617 (output-buffer-name (buffer-name output-buffer)))
7618 (run-hooks 'markdown-before-export-hook)
7619 (markdown-standalone output-buffer-name)
7620 (with-current-buffer output-buffer
7621 (run-hooks 'markdown-after-export-hook)
7622 (save-buffer))
7623 ;; if modified, restore initial buffer
7624 (when (buffer-modified-p init-buf)
7625 (erase-buffer)
7626 (insert init-buf-string)
7627 (save-buffer)
7628 (goto-char init-point))
7629 output-file)))
7631 (defun markdown-export-and-preview ()
7632 "Export to XHTML using `markdown-export' and browse the resulting file."
7633 (interactive)
7634 (browse-url-of-file (markdown-export)))
7636 (defvar markdown-live-preview-buffer nil
7637 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
7638 (make-variable-buffer-local 'markdown-live-preview-buffer)
7640 (defvar markdown-live-preview-source-buffer nil
7641 "Source buffer from which current buffer was generated.
7642 This is the inverse of `markdown-live-preview-buffer'.")
7643 (make-variable-buffer-local 'markdown-live-preview-source-buffer)
7645 (defvar markdown-live-preview-currently-exporting nil)
7647 (defun markdown-live-preview-get-filename ()
7648 "Standardize the filename exported by `markdown-live-preview-export'."
7649 (markdown-export-file-name ".html"))
7651 (defun markdown-live-preview-window-eww (file)
7652 "Preview FILE with eww.
7653 To be used with `markdown-live-preview-window-function'."
7654 (if (require 'eww nil t)
7655 (progn
7656 (eww-open-file file)
7657 (get-buffer "*eww*"))
7658 (error "EWW is not present or not loaded on this version of Emacs")))
7660 (defun markdown-visual-lines-between-points (beg end)
7661 (save-excursion
7662 (goto-char beg)
7663 (cl-loop with count = 0
7664 while (progn (end-of-visual-line)
7665 (and (< (point) end) (line-move-visual 1 t)))
7666 do (cl-incf count)
7667 finally return count)))
7669 (defun markdown-live-preview-window-serialize (buf)
7670 "Get window point and scroll data for all windows displaying BUF."
7671 (when (buffer-live-p buf)
7672 (with-current-buffer buf
7673 (mapcar
7674 (lambda (win)
7675 (with-selected-window win
7676 (let* ((start (window-start))
7677 (pt (window-point))
7678 (pt-or-sym (cond ((= pt (point-min)) 'min)
7679 ((= pt (point-max)) 'max)
7680 (t pt)))
7681 (diff (markdown-visual-lines-between-points
7682 start pt)))
7683 (list win pt-or-sym diff))))
7684 (get-buffer-window-list buf)))))
7686 (defun markdown-get-point-back-lines (pt num-lines)
7687 (save-excursion
7688 (goto-char pt)
7689 (line-move-visual (- num-lines) t)
7690 ;; in testing, can occasionally overshoot the number of lines to traverse
7691 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
7692 (when (> actual-num-lines num-lines)
7693 (line-move-visual (- actual-num-lines num-lines) t)))
7694 (point)))
7696 (defun markdown-live-preview-window-deserialize (window-posns)
7697 "Apply window point and scroll data from WINDOW-POSNS.
7698 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
7699 (cl-destructuring-bind (win pt-or-sym diff) window-posns
7700 (when (window-live-p win)
7701 (with-current-buffer markdown-live-preview-buffer
7702 (set-window-buffer win (current-buffer))
7703 (cl-destructuring-bind (actual-pt actual-diff)
7704 (cl-case pt-or-sym
7705 (min (list (point-min) 0))
7706 (max (list (point-max) diff))
7707 (t (list pt-or-sym diff)))
7708 (set-window-start
7709 win (markdown-get-point-back-lines actual-pt actual-diff))
7710 (set-window-point win actual-pt))))))
7712 (defun markdown-live-preview-export ()
7713 "Export to XHTML using `markdown-export'.
7714 Browse the resulting file within Emacs using
7715 `markdown-live-preview-window-function' Return the buffer
7716 displaying the rendered output."
7717 (interactive)
7718 (let ((filename (markdown-live-preview-get-filename)))
7719 (when filename
7720 (let* ((markdown-live-preview-currently-exporting t)
7721 (cur-buf (current-buffer))
7722 (export-file (markdown-export filename))
7723 ;; get positions in all windows currently displaying output buffer
7724 (window-data
7725 (markdown-live-preview-window-serialize
7726 markdown-live-preview-buffer)))
7727 (save-window-excursion
7728 (let ((output-buffer
7729 (funcall markdown-live-preview-window-function export-file)))
7730 (with-current-buffer output-buffer
7731 (setq markdown-live-preview-source-buffer cur-buf)
7732 (add-hook 'kill-buffer-hook
7733 #'markdown-live-preview-remove-on-kill t t))
7734 (with-current-buffer cur-buf
7735 (setq markdown-live-preview-buffer output-buffer))))
7736 (with-current-buffer cur-buf
7737 ;; reset all windows displaying output buffer to where they were,
7738 ;; now with the new output
7739 (mapc #'markdown-live-preview-window-deserialize window-data)
7740 ;; delete html editing buffer
7741 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
7742 (when (and export-file (file-exists-p export-file)
7743 (eq markdown-live-preview-delete-export
7744 'delete-on-export))
7745 (delete-file export-file))
7746 markdown-live-preview-buffer)))))
7748 (defun markdown-live-preview-remove ()
7749 (when (buffer-live-p markdown-live-preview-buffer)
7750 (kill-buffer markdown-live-preview-buffer))
7751 (setq markdown-live-preview-buffer nil)
7752 ;; if set to 'delete-on-export, the output has already been deleted
7753 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
7754 (let ((outfile-name (markdown-live-preview-get-filename)))
7755 (when (and outfile-name (file-exists-p outfile-name))
7756 (delete-file outfile-name)))))
7758 (defun markdown-get-other-window ()
7759 "Find another window to display preview or output content."
7760 (cond
7761 ((memq markdown-split-window-direction '(vertical below))
7762 (or (window-in-direction 'below) (split-window-vertically)))
7763 ((memq markdown-split-window-direction '(horizontal right))
7764 (or (window-in-direction 'right) (split-window-horizontally)))
7765 (t (split-window-sensibly (get-buffer-window)))))
7767 (defun markdown-display-buffer-other-window (buf)
7768 "Display preview or output buffer BUF in another window."
7769 (let ((cur-buf (current-buffer))
7770 (window (markdown-get-other-window)))
7771 (set-window-buffer window buf)
7772 (set-buffer cur-buf)))
7774 (defun markdown-live-preview-if-markdown ()
7775 (when (and (derived-mode-p 'markdown-mode)
7776 markdown-live-preview-mode)
7777 (unless markdown-live-preview-currently-exporting
7778 (if (buffer-live-p markdown-live-preview-buffer)
7779 (markdown-live-preview-export)
7780 (markdown-display-buffer-other-window
7781 (markdown-live-preview-export))))))
7783 (defun markdown-live-preview-remove-on-kill ()
7784 (cond ((and (derived-mode-p 'markdown-mode)
7785 markdown-live-preview-mode)
7786 (markdown-live-preview-remove))
7787 (markdown-live-preview-source-buffer
7788 (with-current-buffer markdown-live-preview-source-buffer
7789 (setq markdown-live-preview-buffer nil))
7790 (setq markdown-live-preview-source-buffer nil))))
7792 (defun markdown-live-preview-switch-to-output ()
7793 "Switch to output buffer."
7794 (interactive)
7795 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
7796 output buffer in another window."
7797 (if markdown-live-preview-mode
7798 (markdown-display-buffer-other-window (markdown-live-preview-export)))
7799 (markdown-live-preview-mode))
7801 (defun markdown-live-preview-re-export ()
7802 "Re export source buffer."
7803 (interactive)
7804 "If the current buffer is a buffer displaying the exported version of a
7805 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
7806 update this buffer's contents."
7807 (when markdown-live-preview-source-buffer
7808 (with-current-buffer markdown-live-preview-source-buffer
7809 (markdown-live-preview-export))))
7811 (defun markdown-open ()
7812 "Open file for the current buffer with `markdown-open-command'."
7813 (interactive)
7814 (if (not markdown-open-command)
7815 (user-error "Variable `markdown-open-command' must be set")
7816 (if (not buffer-file-name)
7817 (user-error "Must be visiting a file")
7818 (call-process markdown-open-command
7819 nil nil nil buffer-file-name))))
7821 (defun markdown-kill-ring-save ()
7822 "Run Markdown on file and store output in the kill ring."
7823 (interactive)
7824 (save-window-excursion
7825 (markdown)
7826 (with-current-buffer markdown-output-buffer-name
7827 (kill-ring-save (point-min) (point-max)))))
7830 ;;; Links =====================================================================
7832 (defun markdown-link-p ()
7833 "Return non-nil when `point' is at a non-wiki link.
7834 See `markdown-wiki-link-p' for more information."
7835 (let ((case-fold-search nil))
7836 (and (not (markdown-wiki-link-p))
7837 (not (markdown-code-block-at-point-p))
7838 (or (thing-at-point-looking-at markdown-regex-link-inline)
7839 (thing-at-point-looking-at markdown-regex-link-reference)
7840 (thing-at-point-looking-at markdown-regex-uri)
7841 (thing-at-point-looking-at markdown-regex-angle-uri)))))
7843 (make-obsolete 'markdown-link-link 'markdown-link-url "v2.3")
7845 (defun markdown-link-at-pos (pos)
7846 "Return properties of link or image at position POS.
7847 Value is a list of elements describing the link:
7848 0. beginning position
7849 1. end position
7850 2. link text
7851 3. URL
7852 4. reference label
7853 5. title text
7854 6. bang (nil or \"!\")"
7855 (save-excursion
7856 (goto-char pos)
7857 (let (begin end text url reference title bang)
7858 (cond
7859 ;; Inline or reference image or link at point.
7860 ((or (thing-at-point-looking-at markdown-regex-link-inline)
7861 (thing-at-point-looking-at markdown-regex-link-reference))
7862 (setq bang (match-string-no-properties 1)
7863 begin (match-beginning 0)
7864 end (match-end 0)
7865 text (match-string-no-properties 3))
7866 (if (char-equal (char-after (match-beginning 5)) ?\[)
7867 ;; Reference link
7868 (setq reference (match-string-no-properties 6))
7869 ;; Inline link
7870 (setq url (match-string-no-properties 6))
7871 (when (match-end 7)
7872 (setq title (substring (match-string-no-properties 7) 1 -1)))))
7873 ;; Angle bracket URI at point.
7874 ((thing-at-point-looking-at markdown-regex-angle-uri)
7875 (setq begin (match-beginning 0)
7876 end (match-end 0)
7877 url (match-string-no-properties 2)))
7878 ;; Plain URI at point.
7879 ((thing-at-point-looking-at markdown-regex-uri)
7880 (setq begin (match-beginning 0)
7881 end (match-end 0)
7882 url (match-string-no-properties 1))))
7883 (list begin end text url reference title bang))))
7885 (defun markdown-link-url ()
7886 "Return the URL part of the regular (non-wiki) link at point.
7887 Works with both inline and reference style links, and with images.
7888 If point is not at a link or the link reference is not defined
7889 returns nil."
7890 (let* ((values (markdown-link-at-pos (point)))
7891 (text (nth 2 values))
7892 (url (nth 3 values))
7893 (ref (nth 4 values)))
7894 (or url (and ref (car (markdown-reference-definition
7895 (downcase (if (string= ref "") text ref))))))))
7897 (defun markdown-follow-link-at-point ()
7898 "Open the current non-wiki link.
7899 If the link is a complete URL, open in browser with `browse-url'.
7900 Otherwise, open with `find-file' after stripping anchor and/or query string."
7901 (interactive)
7902 (if (markdown-link-p)
7903 (let* ((url (markdown-link-url))
7904 (struct (url-generic-parse-url url))
7905 (full (url-fullness struct))
7906 (file url))
7907 ;; Parse URL, determine fullness, strip query string
7908 (if (fboundp 'url-path-and-query)
7909 (setq file (car (url-path-and-query struct)))
7910 (when (and (setq file (url-filename struct))
7911 (string-match "\\?" file))
7912 (setq file (substring file 0 (match-beginning 0)))))
7913 ;; Open full URLs in browser, files in Emacs
7914 (if full
7915 (browse-url url)
7916 (when (and file (> (length file) 0)) (find-file file))))
7917 (user-error "Point is not at a Markdown link or URL")))
7919 (defun markdown-fontify-inline-links (last)
7920 "Add text properties to next inline link from point to LAST."
7921 (when (markdown-match-generic-links last nil)
7922 (let* ((link-start (match-beginning 3))
7923 (link-end (match-end 3))
7924 (url-start (match-beginning 6))
7925 (url-end (match-end 6))
7926 (url (match-string-no-properties 6))
7927 (title-start (match-beginning 7))
7928 (title-end (match-end 7))
7929 (title (match-string-no-properties 7))
7930 ;; Markup part
7931 (mp (list 'face 'markdown-markup-face
7932 'invisible 'markdown-markup
7933 'rear-nonsticky t
7934 'font-lock-multiline t))
7935 ;; Link part
7936 (lp (list 'keymap markdown-mode-mouse-map
7937 'face markdown-link-face
7938 'mouse-face 'markdown-highlight-face
7939 'font-lock-multiline t
7940 'help-echo (if title (concat title "\n" url) url)))
7941 ;; URL part
7942 (up (list 'keymap markdown-mode-mouse-map
7943 'face 'markdown-url-face
7944 'invisible 'markdown-markup
7945 'mouse-face 'markdown-highlight-face
7946 'font-lock-multiline t))
7947 ;; Title part
7948 (tp (list 'face 'markdown-link-title-face
7949 'invisible 'markdown-markup
7950 'font-lock-multiline t)))
7951 (dolist (g '(1 2 4 5 8))
7952 (when (match-end g)
7953 (add-text-properties (match-beginning g) (match-end g) mp)))
7954 (when link-start (add-text-properties link-start link-end lp))
7955 (when url-start (add-text-properties url-start url-end up))
7956 (when title-start (add-text-properties url-end title-end tp))
7957 (when (and markdown-hide-urls url-start)
7958 (compose-region url-start (or title-end url-end)
7959 markdown-url-compose-char))
7960 t)))
7962 (defun markdown-fontify-reference-links (last)
7963 "Add text properties to next reference link from point to LAST."
7964 (when (markdown-match-generic-links last t)
7965 (let* ((link-start (match-beginning 3))
7966 (link-end (match-end 3))
7967 (ref-start (match-beginning 6))
7968 (ref-end (match-end 6))
7969 ;; Markup part
7970 (mp (list 'face 'markdown-markup-face
7971 'invisible 'markdown-markup
7972 'rear-nonsticky t
7973 'font-lock-multiline t))
7974 ;; Link part
7975 (lp (list 'keymap markdown-mode-mouse-map
7976 'face markdown-link-face
7977 'mouse-face 'markdown-highlight-face
7978 'font-lock-multiline t
7979 'help-echo (lambda (_ __ pos)
7980 (save-match-data
7981 (save-excursion
7982 (goto-char pos)
7983 (or (markdown-link-url)
7984 "Undefined reference"))))))
7985 ;; Reference part
7986 (rp (list 'face 'markdown-reference-face
7987 'invisible 'markdown-markup
7988 'font-lock-multiline t)))
7989 (dolist (g '(1 2 4 5 8))
7990 (when (match-end g)
7991 (add-text-properties (match-beginning g) (match-end g) mp)))
7992 (when link-start (add-text-properties link-start link-end lp))
7993 (when ref-start (add-text-properties ref-start ref-end rp)
7994 (when (and markdown-hide-urls (> (- ref-end ref-start) 2))
7995 (compose-region ref-start ref-end markdown-url-compose-char)))
7996 t)))
7998 (defun markdown-fontify-angle-uris (last)
7999 "Add text properties to angle URIs from point to LAST."
8000 (when (markdown-match-angle-uris last)
8001 (let* ((url-start (match-beginning 2))
8002 (url-end (match-end 2))
8003 ;; Markup part
8004 (mp (list 'face 'markdown-markup-face
8005 'invisible 'markdown-markup
8006 'rear-nonsticky t
8007 'font-lock-multiline t))
8008 ;; URI part
8009 (up (list 'keymap markdown-mode-mouse-map
8010 'face 'markdown-plain-url-face
8011 'mouse-face 'markdown-highlight-face
8012 'font-lock-multiline t)))
8013 (dolist (g '(1 3))
8014 (add-text-properties (match-beginning g) (match-end g) mp))
8015 (add-text-properties url-start url-end up)
8016 t)))
8018 (defun markdown-fontify-plain-uris (last)
8019 "Add text properties to plain URLs from point to LAST."
8020 (when (markdown-match-plain-uris last)
8021 (let* ((start (match-beginning 0))
8022 (end (match-end 0))
8023 (props (list 'keymap markdown-mode-mouse-map
8024 'face 'markdown-plain-url-face
8025 'mouse-face 'markdown-highlight-face
8026 'rear-nonsticky t
8027 'font-lock-multiline t)))
8028 (add-text-properties start end props)
8029 t)))
8031 (defun markdown-toggle-url-hiding (&optional arg)
8032 "Toggle the display or hiding of URLs.
8033 With a prefix argument ARG, enable URL hiding if ARG is positive,
8034 and disable it otherwise."
8035 (interactive (list (or current-prefix-arg 'toggle)))
8036 (setq markdown-hide-urls
8037 (if (eq arg 'toggle)
8038 (not markdown-hide-urls)
8039 (> (prefix-numeric-value arg) 0)))
8040 (if markdown-hide-urls
8041 (message "markdown-mode URL hiding enabled")
8042 (message "markdown-mode URL hiding disabled"))
8043 (markdown-reload-extensions))
8046 ;;; WikiLink Following/Markup =================================================
8048 (defun markdown-wiki-link-p ()
8049 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
8050 A true wiki link name matches `markdown-regex-wiki-link' but does
8051 not match the current file name after conversion. This modifies
8052 the data returned by `match-data'. Note that the potential wiki
8053 link name must be available via `match-string'."
8054 (when markdown-enable-wiki-links
8055 (let ((case-fold-search nil))
8056 (and (thing-at-point-looking-at markdown-regex-wiki-link)
8057 (not (markdown-code-block-at-point-p))
8058 (or (not buffer-file-name)
8059 (not (string-equal (buffer-file-name)
8060 (markdown-convert-wiki-link-to-filename
8061 (markdown-wiki-link-link)))))))))
8063 (defun markdown-wiki-link-link ()
8064 "Return the link part of the wiki link using current match data.
8065 The location of the link component depends on the value of
8066 `markdown-wiki-link-alias-first'."
8067 (if markdown-wiki-link-alias-first
8068 (or (match-string-no-properties 5) (match-string-no-properties 3))
8069 (match-string-no-properties 3)))
8071 (defun markdown-wiki-link-alias ()
8072 "Return the alias or text part of the wiki link using current match data.
8073 The location of the alias component depends on the value of
8074 `markdown-wiki-link-alias-first'."
8075 (if markdown-wiki-link-alias-first
8076 (match-string-no-properties 3)
8077 (or (match-string-no-properties 5) (match-string-no-properties 3))))
8079 (defun markdown-convert-wiki-link-to-filename (name)
8080 "Generate a filename from the wiki link NAME.
8081 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
8082 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
8083 and [[test test]] both map to Test-test.ext. Look in the current
8084 directory first, then in subdirectories if
8085 `markdown-wiki-link-search-subdirectories' is non-nil, and then
8086 in parent directories if
8087 `markdown-wiki-link-search-parent-directories' is non-nil."
8088 (let* ((basename (markdown-replace-regexp-in-string
8089 "[[:space:]\n]" markdown-link-space-sub-char name))
8090 (basename (if (eq major-mode 'gfm-mode)
8091 (concat (upcase (substring basename 0 1))
8092 (downcase (substring basename 1 nil)))
8093 basename))
8094 directory extension default candidates dir)
8095 (when buffer-file-name
8096 (setq directory (file-name-directory buffer-file-name)
8097 extension (file-name-extension buffer-file-name)))
8098 (setq default (concat basename
8099 (when extension (concat "." extension))))
8100 (cond
8101 ;; Look in current directory first.
8102 ((or (null buffer-file-name)
8103 (file-exists-p default))
8104 default)
8105 ;; Possibly search in subdirectories, next.
8106 ((and markdown-wiki-link-search-subdirectories
8107 (setq candidates
8108 (markdown-directory-files-recursively
8109 directory (concat "^" default "$"))))
8110 (car candidates))
8111 ;; Possibly search in parent directories as a last resort.
8112 ((and markdown-wiki-link-search-parent-directories
8113 (setq dir (locate-dominating-file directory default)))
8114 (concat dir default))
8115 ;; If nothing is found, return default in current directory.
8116 (t default))))
8118 (defun markdown-follow-wiki-link (name &optional other)
8119 "Follow the wiki link NAME.
8120 Convert the name to a file name and call `find-file'. Ensure that
8121 the new buffer remains in `markdown-mode'. Open the link in another
8122 window when OTHER is non-nil."
8123 (let ((filename (markdown-convert-wiki-link-to-filename name))
8124 (wp (when buffer-file-name
8125 (file-name-directory buffer-file-name))))
8126 (if (not wp)
8127 (user-error "Must be visiting a file")
8128 (when other (other-window 1))
8129 (let ((default-directory wp))
8130 (find-file filename)))
8131 (when (not (eq major-mode 'markdown-mode))
8132 (markdown-mode))))
8134 (defun markdown-follow-wiki-link-at-point (&optional arg)
8135 "Find Wiki Link at point.
8136 With prefix argument ARG, open the file in other window.
8137 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
8138 (interactive "P")
8139 (if (markdown-wiki-link-p)
8140 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
8141 (user-error "Point is not at a Wiki Link")))
8143 (defun markdown-highlight-wiki-link (from to face)
8144 "Highlight the wiki link in the region between FROM and TO using FACE."
8145 (put-text-property from to 'font-lock-face face))
8147 (defun markdown-unfontify-region-wiki-links (from to)
8148 "Remove wiki link faces from the region specified by FROM and TO."
8149 (interactive "*r")
8150 (let ((modified (buffer-modified-p)))
8151 (remove-text-properties from to '(font-lock-face markdown-link-face))
8152 (remove-text-properties from to '(font-lock-face markdown-missing-link-face))
8153 ;; remove-text-properties marks the buffer modified in emacs 24.3,
8154 ;; undo that if it wasn't originally marked modified
8155 (set-buffer-modified-p modified)))
8157 (defun markdown-fontify-region-wiki-links (from to)
8158 "Search region given by FROM and TO for wiki links and fontify them.
8159 If a wiki link is found check to see if the backing file exists
8160 and highlight accordingly."
8161 (goto-char from)
8162 (save-match-data
8163 (while (re-search-forward markdown-regex-wiki-link to t)
8164 (when (not (markdown-code-block-at-point-p))
8165 (let ((highlight-beginning (match-beginning 1))
8166 (highlight-end (match-end 1))
8167 (file-name
8168 (markdown-convert-wiki-link-to-filename
8169 (markdown-wiki-link-link))))
8170 (if (condition-case nil (file-exists-p file-name) (error nil))
8171 (markdown-highlight-wiki-link
8172 highlight-beginning highlight-end markdown-link-face)
8173 (markdown-highlight-wiki-link
8174 highlight-beginning highlight-end markdown-missing-link-face)))))))
8176 (defun markdown-extend-changed-region (from to)
8177 "Extend region given by FROM and TO so that we can fontify all links.
8178 The region is extended to the first newline before and the first
8179 newline after."
8180 ;; start looking for the first new line before 'from
8181 (goto-char from)
8182 (re-search-backward "\n" nil t)
8183 (let ((new-from (point-min))
8184 (new-to (point-max)))
8185 (if (not (= (point) from))
8186 (setq new-from (point)))
8187 ;; do the same thing for the first new line after 'to
8188 (goto-char to)
8189 (re-search-forward "\n" nil t)
8190 (if (not (= (point) to))
8191 (setq new-to (point)))
8192 (cl-values new-from new-to)))
8194 (defun markdown-check-change-for-wiki-link (from to)
8195 "Check region between FROM and TO for wiki links and re-fontify as needed."
8196 (interactive "*r")
8197 (let* ((modified (buffer-modified-p))
8198 (buffer-undo-list t)
8199 (inhibit-read-only t)
8200 (inhibit-point-motion-hooks t)
8201 deactivate-mark
8202 buffer-file-truename)
8203 (unwind-protect
8204 (save-excursion
8205 (save-match-data
8206 (save-restriction
8207 ;; Extend the region to fontify so that it starts
8208 ;; and ends at safe places.
8209 (cl-multiple-value-bind (new-from new-to)
8210 (markdown-extend-changed-region from to)
8211 (goto-char new-from)
8212 ;; Only refontify when the range contains text with a
8213 ;; wiki link face or if the wiki link regexp matches.
8214 (when (or (markdown-range-property-any
8215 new-from new-to 'font-lock-face
8216 (list markdown-link-face
8217 markdown-missing-link-face))
8218 (re-search-forward
8219 markdown-regex-wiki-link new-to t))
8220 ;; Unfontify existing fontification (start from scratch)
8221 (markdown-unfontify-region-wiki-links new-from new-to)
8222 ;; Now do the fontification.
8223 (markdown-fontify-region-wiki-links new-from new-to))))))
8224 (and (not modified)
8225 (buffer-modified-p)
8226 (set-buffer-modified-p nil)))))
8228 (defun markdown-check-change-for-wiki-link-after-change (from to _)
8229 "Check region between FROM and TO for wiki links and re-fontify as needed.
8230 Designed to be used with the `after-change-functions' hook."
8231 (markdown-check-change-for-wiki-link from to))
8233 (defun markdown-fontify-buffer-wiki-links ()
8234 "Refontify all wiki links in the buffer."
8235 (interactive)
8236 (markdown-check-change-for-wiki-link (point-min) (point-max)))
8239 ;;; Following & Doing =========================================================
8241 (defun markdown-follow-thing-at-point (arg)
8242 "Follow thing at point if possible, such as a reference link or wiki link.
8243 Opens inline and reference links in a browser. Opens wiki links
8244 to other files in the current window, or the another window if
8245 ARG is non-nil.
8246 See `markdown-follow-link-at-point' and
8247 `markdown-follow-wiki-link-at-point'."
8248 (interactive "P")
8249 (cond ((markdown-link-p)
8250 (markdown-follow-link-at-point))
8251 ((markdown-wiki-link-p)
8252 (markdown-follow-wiki-link-at-point arg))
8254 (user-error "Nothing to follow at point"))))
8256 (make-obsolete 'markdown-jump 'markdown-do "v2.3")
8258 (defun markdown-do ()
8259 "Do something sensible based on context at point.
8260 Jumps between reference links and definitions; between footnote
8261 markers and footnote text."
8262 (interactive)
8263 (cond
8264 ;; Footnote definition
8265 ((markdown-footnote-text-positions)
8266 (markdown-footnote-return))
8267 ;; Footnote marker
8268 ((markdown-footnote-marker-positions)
8269 (markdown-footnote-goto-text))
8270 ;; Reference link
8271 ((thing-at-point-looking-at markdown-regex-link-reference)
8272 (markdown-reference-goto-definition))
8273 ;; Reference definition
8274 ((thing-at-point-looking-at markdown-regex-reference-definition)
8275 (markdown-reference-goto-link (match-string-no-properties 2)))
8276 ;; GFM task list item
8277 ((markdown-gfm-task-list-item-at-point)
8278 (markdown-toggle-gfm-checkbox))
8279 ;; Otherwise
8281 (user-error "Nothing to do in context at point"))))
8284 ;;; Miscellaneous =============================================================
8286 (defun markdown-compress-whitespace-string (str)
8287 "Compress whitespace in STR and return result.
8288 Leading and trailing whitespace is removed. Sequences of multiple
8289 spaces, tabs, and newlines are replaced with single spaces."
8290 (markdown-replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
8291 (markdown-replace-regexp-in-string "[ \t\n]+" " " str)))
8293 (defun markdown--substitute-command-keys (string)
8294 "Like `substitute-command-keys' but, but prefers control characters.
8295 First pass STRING to `substitute-command-keys' and then
8296 substitute `C-i` for `TAB` and `C-m` for `RET`."
8297 (replace-regexp-in-string
8298 "\\<TAB\\>" "C-i"
8299 (replace-regexp-in-string
8300 "\\<RET\\>" "C-m" (substitute-command-keys string) t) t))
8302 (defun markdown-line-number-at-pos (&optional pos)
8303 "Return (narrowed) buffer line number at position POS.
8304 If POS is nil, use current buffer location.
8305 This is an exact copy of `line-number-at-pos' for use in emacs21."
8306 (let ((opoint (or pos (point))) start)
8307 (save-excursion
8308 (goto-char (point-min))
8309 (setq start (point))
8310 (goto-char opoint)
8311 (forward-line 0)
8312 (1+ (count-lines start (point))))))
8314 (defun markdown-inside-link-p ()
8315 "Return t if point is within a link."
8316 (save-match-data
8317 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
8319 (defun markdown-line-is-reference-definition-p ()
8320 "Return whether the current line is a (non-footnote) reference defition."
8321 (save-excursion
8322 (move-beginning-of-line 1)
8323 (and (looking-at-p markdown-regex-reference-definition)
8324 (not (looking-at-p "[ \t]*\\[^")))))
8326 (defun markdown-adaptive-fill-function ()
8327 "Return prefix for filling paragraph or nil if not determined."
8328 (cond
8329 ;; List item inside blockquote
8330 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
8331 (markdown-replace-regexp-in-string
8332 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
8333 ;; Blockquote
8334 ((looking-at markdown-regex-blockquote)
8335 (buffer-substring-no-properties (match-beginning 0) (match-end 2)))
8336 ;; List items
8337 ((looking-at markdown-regex-list)
8338 (match-string-no-properties 0))
8339 ;; Footnote definition
8340 ((looking-at-p markdown-regex-footnote-definition)
8341 " ") ; four spaces
8342 ;; No match
8343 (t nil)))
8345 (defun markdown-fill-paragraph (&optional justify)
8346 "Fill paragraph at or after point.
8347 This function is like \\[fill-paragraph], but it skips Markdown
8348 code blocks. If the point is in a code block, or just before one,
8349 do not fill. Otherwise, call `fill-paragraph' as usual. If
8350 JUSTIFY is non-nil, justify text as well. Since this function
8351 handles filling itself, it always returns t so that
8352 `fill-paragraph' doesn't run."
8353 (interactive "P")
8354 (unless (or (markdown-code-block-at-point-p)
8355 (save-excursion
8356 (back-to-indentation)
8357 (skip-syntax-forward "-")
8358 (markdown-code-block-at-point-p)))
8359 (fill-paragraph justify))
8362 (make-obsolete 'markdown-fill-forward-paragraph-function
8363 'markdown-fill-forward-paragraph "v2.3")
8365 (defun markdown-fill-forward-paragraph (&optional arg)
8366 "Function used by `fill-paragraph' to move over ARG paragraphs.
8367 This is a `fill-forward-paragraph-function' for `markdown-mode'.
8368 It is called with a single argument specifying the number of
8369 paragraphs to move. Just like `forward-paragraph', it should
8370 return the number of paragraphs left to move."
8371 (or arg (setq arg 1))
8372 (if (> arg 0)
8373 ;; With positive ARG, move across ARG non-code-block paragraphs,
8374 ;; one at a time. When passing a code block, don't decrement ARG.
8375 (while (and (not (eobp))
8376 (> arg 0)
8377 (= (forward-paragraph 1) 0)
8378 (or (markdown-code-block-at-pos (point-at-bol 0))
8379 (setq arg (1- arg)))))
8380 ;; Move backward by one paragraph with negative ARG (always -1).
8381 (let ((start (point)))
8382 (setq arg (forward-paragraph arg))
8383 (while (and (not (eobp))
8384 (progn (move-to-left-margin) (not (eobp)))
8385 (looking-at-p paragraph-separate))
8386 (forward-line 1))
8387 (cond
8388 ;; Move point past whitespace following list marker.
8389 ((looking-at markdown-regex-list)
8390 (goto-char (match-end 0)))
8391 ;; Move point past whitespace following pipe at beginning of line
8392 ;; to handle Pandoc line blocks.
8393 ((looking-at "^|\\s-*")
8394 (goto-char (match-end 0)))
8395 ;; Return point if the paragraph passed was a code block.
8396 ((markdown-code-block-at-pos (point-at-bol 2))
8397 (goto-char start)))))
8398 arg)
8400 (defun markdown--inhibit-electric-quote ()
8401 "Function added to `electric-quote-inhibit-functions'.
8402 Return non-nil if the quote has been inserted inside a code block
8403 or span."
8404 (let ((pos (1- (point))))
8405 (or (markdown-inline-code-at-pos pos)
8406 (markdown-code-block-at-pos pos))))
8409 ;;; Extension Framework =======================================================
8411 (defun markdown-reload-extensions ()
8412 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
8413 (interactive)
8414 (when (member major-mode '(markdown-mode gfm-mode))
8415 ;; Update font lock keywords with extensions
8416 (setq markdown-mode-font-lock-keywords
8417 (append
8418 (markdown-mode-font-lock-keywords-math)
8419 markdown-mode-font-lock-keywords-basic
8420 (markdown-mode-font-lock-keywords-wiki-links)))
8421 ;; Update font lock defaults
8422 (setq font-lock-defaults
8423 '(markdown-mode-font-lock-keywords
8424 nil nil nil nil
8425 (font-lock-syntactic-face-function . markdown-syntactic-face)))
8426 ;; Refontify buffer
8427 (when (and font-lock-mode (fboundp 'font-lock-refresh-defaults))
8428 (font-lock-refresh-defaults))
8430 ;; Add or remove hooks related to extensions
8431 (markdown-setup-wiki-link-hooks)))
8433 (defun markdown-handle-local-variables ()
8434 "Run in `hack-local-variables-hook' to update font lock rules.
8435 Checks to see if there is actually a ‘markdown-mode’ file local variable
8436 before regenerating font-lock rules for extensions."
8437 (when (and (boundp 'file-local-variables-alist)
8438 (assoc 'markdown-enable-wiki-links file-local-variables-alist)
8439 (assoc 'markdown-enable-math file-local-variables-alist))
8440 (markdown-reload-extensions)))
8443 ;;; Wiki Links ================================================================
8445 (defun markdown-toggle-wiki-links (&optional arg)
8446 "Toggle support for wiki links.
8447 With a prefix argument ARG, enable wiki link support if ARG is positive,
8448 and disable it otherwise."
8449 (interactive (list (or current-prefix-arg 'toggle)))
8450 (setq markdown-enable-wiki-links
8451 (if (eq arg 'toggle)
8452 (not markdown-enable-wiki-links)
8453 (> (prefix-numeric-value arg) 0)))
8454 (if markdown-enable-wiki-links
8455 (message "markdown-mode wiki link support enabled")
8456 (message "markdown-mode wiki link support disabled"))
8457 (markdown-reload-extensions))
8459 (defun markdown-setup-wiki-link-hooks ()
8460 "Add or remove hooks for fontifying wiki links.
8461 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
8462 ;; Anytime text changes make sure it gets fontified correctly
8463 (if (and markdown-enable-wiki-links
8464 markdown-wiki-link-fontify-missing)
8465 (add-hook 'after-change-functions
8466 'markdown-check-change-for-wiki-link-after-change t t)
8467 (remove-hook 'after-change-functions
8468 'markdown-check-change-for-wiki-link-after-change t))
8469 ;; If we left the buffer there is a really good chance we were
8470 ;; creating one of the wiki link documents. Make sure we get
8471 ;; refontified when we come back.
8472 (if (and markdown-enable-wiki-links
8473 markdown-wiki-link-fontify-missing)
8474 (progn
8475 (add-hook 'window-configuration-change-hook
8476 'markdown-fontify-buffer-wiki-links t t)
8477 (markdown-fontify-buffer-wiki-links))
8478 (remove-hook 'window-configuration-change-hook
8479 'markdown-fontify-buffer-wiki-links t)
8480 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
8482 (defun markdown-mode-font-lock-keywords-wiki-links ()
8483 "Return wiki-link lock keywords if support is enabled.
8484 If `markdown-wiki-link-fontify-missing' is also enabled, we use
8485 hooks in `markdown-setup-wiki-link-hooks' for fontification instead."
8486 (when (and markdown-enable-wiki-links
8487 (not markdown-wiki-link-fontify-missing))
8488 (list
8489 (cons markdown-regex-wiki-link '((1 markdown-link-face prepend))))))
8492 ;;; Math Support ==============================================================
8494 (make-obsolete 'markdown-enable-math 'markdown-toggle-math "v2.1")
8496 (defun markdown-toggle-math (&optional arg)
8497 "Toggle support for inline and display LaTeX math expressions.
8498 With a prefix argument ARG, enable math mode if ARG is positive,
8499 and disable it otherwise. If called from Lisp, enable the mode
8500 if ARG is omitted or nil."
8501 (interactive (list (or current-prefix-arg 'toggle)))
8502 (setq markdown-enable-math
8503 (if (eq arg 'toggle)
8504 (not markdown-enable-math)
8505 (> (prefix-numeric-value arg) 0)))
8506 (if markdown-enable-math
8507 (message "markdown-mode math support enabled")
8508 (message "markdown-mode math support disabled"))
8509 (markdown-reload-extensions))
8511 (defun markdown-mode-font-lock-keywords-math ()
8512 "Return math font lock keywords if support is enabled."
8513 (when markdown-enable-math
8514 (list
8515 ;; Display mode equations with brackets: \[ \]
8516 (cons markdown-regex-math-display '((1 markdown-markup-face prepend)
8517 (2 markdown-math-face append)
8518 (3 markdown-markup-face prepend)))
8519 ;; Equation reference (eq:foo)
8520 (cons "\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" '((1 markdown-markup-face)
8521 (2 markdown-reference-face)
8522 (3 markdown-markup-face)))
8523 ;; Equation reference \eqref{foo}
8524 (cons "\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" '((1 markdown-markup-face)
8525 (2 markdown-reference-face)
8526 (3 markdown-markup-face))))))
8529 ;;; GFM Checkboxes ============================================================
8531 (define-button-type 'markdown-gfm-checkbox-button
8532 'follow-link t
8533 'face 'markdown-gfm-checkbox-face
8534 'mouse-face 'markdown-highlight-face
8535 'action #'markdown-toggle-gfm-checkbox-button)
8537 (defun markdown-gfm-task-list-item-at-point (&optional bounds)
8538 "Return non-nil if there is a GFM task list item at the point.
8539 Optionally, the list item BOUNDS may be given if available, as
8540 returned by `markdown-cur-list-item-bounds'. When a task list item
8541 is found, the return value is the same value returned by
8542 `markdown-cur-list-item-bounds'."
8543 (unless bounds
8544 (setq bounds (markdown-cur-list-item-bounds)))
8545 (> (length (nth 5 bounds)) 0))
8547 (defun markdown-toggle-gfm-checkbox ()
8548 "Toggle GFM checkbox at point.
8549 Returns the resulting status as a string, either \"[x]\" or \"[ ]\".
8550 Returns nil if there is no task list item at the point."
8551 (interactive)
8552 (save-match-data
8553 (save-excursion
8554 (let ((bounds (markdown-cur-list-item-bounds)))
8555 (when bounds
8556 ;; Move to beginning of task list item
8557 (goto-char (cl-first bounds))
8558 ;; Advance to column of first non-whitespace after marker
8559 (forward-char (cl-fourth bounds))
8560 (cond ((looking-at "\\[ \\]")
8561 (replace-match
8562 (if markdown-gfm-uppercase-checkbox "[X]" "[x]")
8563 nil t)
8564 (match-string-no-properties 0))
8565 ((looking-at "\\[[xX]\\]")
8566 (replace-match "[ ]" nil t)
8567 (match-string-no-properties 0))))))))
8569 (defun markdown-toggle-gfm-checkbox-button (button)
8570 "Toggle GFM checkbox BUTTON on click."
8571 (save-match-data
8572 (save-excursion
8573 (goto-char (button-start button))
8574 (markdown-toggle-gfm-checkbox))))
8576 (defun markdown-make-gfm-checkboxes-buttons (start end)
8577 "Make GFM checkboxes buttons in region between START and END."
8578 (save-excursion
8579 (goto-char start)
8580 (let ((case-fold-search t))
8581 (save-excursion
8582 (while (re-search-forward markdown-regex-gfm-checkbox end t)
8583 (make-button (match-beginning 1) (match-end 1)
8584 :type 'markdown-gfm-checkbox-button))))))
8586 ;; Called when any modification is made to buffer text.
8587 (defun markdown-gfm-checkbox-after-change-function (beg end _)
8588 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
8589 BEG and END are the limits of scanned region."
8590 (save-excursion
8591 (save-match-data
8592 ;; Rescan between start of line from `beg' and start of line after `end'.
8593 (markdown-make-gfm-checkboxes-buttons
8594 (progn (goto-char beg) (beginning-of-line) (point))
8595 (progn (goto-char end) (forward-line 1) (point))))))
8597 (defun markdown-remove-gfm-checkbox-overlays ()
8598 "Remove all GFM checkbox overlays in buffer."
8599 (save-excursion
8600 (save-restriction
8601 (widen)
8602 (remove-overlays nil nil 'face 'markdown-gfm-checkbox-face))))
8605 ;;; Display inline image =================================================
8607 (defvar markdown-inline-image-overlays nil)
8608 (make-variable-buffer-local 'markdown-inline-image-overlays)
8610 (defun markdown-remove-inline-images ()
8611 "Remove inline image overlays from image links in the buffer.
8612 This can be toggled with `markdown-toggle-inline-images'
8613 or \\[markdown-toggle-inline-images]."
8614 (interactive)
8615 (mapc #'delete-overlay markdown-inline-image-overlays)
8616 (setq markdown-inline-image-overlays nil))
8618 (defun markdown-display-inline-images ()
8619 "Add inline image overlays to image links in the buffer.
8620 This can be toggled with `markdown-toggle-inline-images'
8621 or \\[markdown-toggle-inline-images]."
8622 (interactive)
8623 (unless (display-graphic-p)
8624 (error "Cannot show images"))
8625 (save-excursion
8626 (save-restriction
8627 (widen)
8628 (goto-char (point-min))
8629 (while (re-search-forward markdown-regex-link-inline nil t)
8630 (let ((start (match-beginning 0))
8631 (end (match-end 0))
8632 (file (match-string-no-properties 6)))
8633 (when (file-exists-p file)
8634 (let* ((abspath (if (file-name-absolute-p file)
8635 file
8636 (concat default-directory file)))
8637 (image (create-image abspath)))
8638 (when image
8639 (let ((ov (make-overlay start end)))
8640 (overlay-put ov 'display image)
8641 (overlay-put ov 'face 'default)
8642 (push ov markdown-inline-image-overlays))))))))))
8644 (defun markdown-toggle-inline-images ()
8645 "Toggle inline image overlays in the buffer."
8646 (interactive)
8647 (if markdown-inline-image-overlays
8648 (markdown-remove-inline-images)
8649 (markdown-display-inline-images)))
8652 ;;; GFM Code Block Fontification ==============================================
8654 (defcustom markdown-fontify-code-blocks-natively nil
8655 "When non-nil, fontify code in code blocks using the native major mode.
8656 This only works for fenced code blocks where the language is
8657 specified where we can automatically determine the appropriate
8658 mode to use. The language to mode mapping may be customized by
8659 setting the variable `markdown-code-lang-modes'."
8660 :group 'markdown
8661 :type 'boolean
8662 :safe 'booleanp
8663 :package-version '(markdown-mode . "2.3"))
8665 (defun markdown-toggle-fontify-code-blocks-natively (&optional arg)
8666 "Toggle the native fontification of code blocks.
8667 With a prefix argument ARG, enable if ARG is positive,
8668 and disable otherwise."
8669 (interactive (list (or current-prefix-arg 'toggle)))
8670 (setq markdown-fontify-code-blocks-natively
8671 (if (eq arg 'toggle)
8672 (not markdown-fontify-code-blocks-natively)
8673 (> (prefix-numeric-value arg) 0)))
8674 (if markdown-fontify-code-blocks-natively
8675 (message "markdown-mode native code block fontification enabled")
8676 (message "markdown-mode native code block fontification disabled"))
8677 (markdown-reload-extensions))
8679 ;; This is based on `org-src-lang-modes' from org-src.el
8680 (defcustom markdown-code-lang-modes
8681 '(("ocaml" . tuareg-mode) ("elisp" . emacs-lisp-mode) ("ditaa" . artist-mode)
8682 ("asymptote" . asy-mode) ("dot" . fundamental-mode) ("sqlite" . sql-mode)
8683 ("calc" . fundamental-mode) ("C" . c-mode) ("cpp" . c++-mode)
8684 ("C++" . c++-mode) ("screen" . shell-script-mode) ("shell" . sh-mode)
8685 ("bash" . sh-mode))
8686 "Alist mapping languages to their major mode.
8687 The key is the language name, the value is the major mode. For
8688 many languages this is simple, but for language where this is not
8689 the case, this variable provides a way to simplify things on the
8690 user side. For example, there is no ocaml-mode in Emacs, but the
8691 mode to use is `tuareg-mode'."
8692 :group 'markdown
8693 :type '(repeat
8694 (cons
8695 (string "Language name")
8696 (symbol "Major mode")))
8697 :package-version '(markdown-mode . "2.3"))
8699 (defun markdown-get-lang-mode (lang)
8700 "Return major mode that should be used for LANG.
8701 LANG is a string, and the returned major mode is a symbol."
8702 (cl-find-if
8703 'fboundp
8704 (list (cdr (assoc lang markdown-code-lang-modes))
8705 (cdr (assoc (downcase lang) markdown-code-lang-modes))
8706 (intern (concat lang "-mode"))
8707 (intern (concat (downcase lang) "-mode")))))
8709 (defun markdown-fontify-code-blocks-generic (matcher last)
8710 "Add text properties to next code block from point to LAST.
8711 Use matching function MATCHER."
8712 (when (funcall matcher last)
8713 (save-excursion
8714 (save-match-data
8715 (let* ((start (match-beginning 0))
8716 (end (match-end 0))
8717 ;; Find positions outside opening and closing backquotes.
8718 (bol-prev (progn (goto-char start)
8719 (if (bolp) (point-at-bol 0) (point-at-bol))))
8720 (eol-next (progn (goto-char end)
8721 (if (bolp) (point-at-bol 2) (point-at-bol 3))))
8722 lang)
8723 (if (and markdown-fontify-code-blocks-natively
8724 (setq lang (markdown-code-block-lang)))
8725 (markdown-fontify-code-block-natively lang start end)
8726 (add-text-properties start end '(face markdown-pre-face)))
8727 ;; Set background for block as well as opening and closing lines.
8728 (font-lock-append-text-property
8729 bol-prev eol-next 'face 'markdown-code-face)
8730 ;; Set invisible property for lines before and after, including newline.
8731 (add-text-properties bol-prev start '(invisible markdown-markup))
8732 (add-text-properties end eol-next '(invisible markdown-markup)))))
8735 (defun markdown-fontify-gfm-code-blocks (last)
8736 "Add text properties to next GFM code block from point to LAST."
8737 (markdown-fontify-code-blocks-generic 'markdown-match-gfm-code-blocks last))
8739 (defun markdown-fontify-fenced-code-blocks (last)
8740 "Add text properties to next tilde fenced code block from point to LAST."
8741 (markdown-fontify-code-blocks-generic 'markdown-match-fenced-code-blocks last))
8743 ;; Based on `org-src-font-lock-fontify-block' from org-src.el.
8744 (defun markdown-fontify-code-block-natively (lang start end)
8745 "Fontify given GFM or fenced code block.
8746 This function is called by Emacs for automatic fontification when
8747 `markdown-fontify-code-blocks-natively' is non-nil. LANG is the
8748 language used in the block. START and END specify the block
8749 position."
8750 (let ((lang-mode (markdown-get-lang-mode lang)))
8751 (when (fboundp lang-mode)
8752 (let ((string (buffer-substring-no-properties start end))
8753 (modified (buffer-modified-p))
8754 (markdown-buffer (current-buffer)) pos next)
8755 (remove-text-properties start end '(face nil))
8756 (with-current-buffer
8757 (get-buffer-create
8758 (concat " markdown-code-fontification:" (symbol-name lang-mode)))
8759 ;; Make sure that modification hooks are not inhibited in
8760 ;; the org-src-fontification buffer in case we're called
8761 ;; from `jit-lock-function' (Bug#25132).
8762 (let ((inhibit-modification-hooks nil))
8763 (delete-region (point-min) (point-max))
8764 (insert string " ")) ;; so there's a final property change
8765 (unless (eq major-mode lang-mode) (funcall lang-mode))
8766 (markdown-font-lock-ensure)
8767 (setq pos (point-min))
8768 (while (setq next (next-single-property-change pos 'face))
8769 (let ((val (get-text-property pos 'face)))
8770 (when val
8771 (put-text-property
8772 (+ start (1- pos)) (1- (+ start next)) 'face
8773 val markdown-buffer)))
8774 (setq pos next)))
8775 (add-text-properties
8776 start end
8777 '(font-lock-fontified t fontified t font-lock-multiline t))
8778 (set-buffer-modified-p modified)))))
8780 (require 'edit-indirect nil t)
8781 (defvar edit-indirect-guess-mode-function)
8782 (defvar edit-indirect-after-commit-functions)
8784 (defun markdown--edit-indirect-after-commit-function (_beg end)
8785 "Ensure trailing newlines at the END of code blocks."
8786 (goto-char end)
8787 (unless (eq (char-before) ?\n)
8788 (insert "\n")))
8790 (defun markdown-edit-code-block ()
8791 "Edit Markdown code block in an indirect buffer."
8792 (interactive)
8793 (save-excursion
8794 (if (fboundp 'edit-indirect-region)
8795 (let* ((bounds (markdown-get-enclosing-fenced-block-construct))
8796 (begin (and bounds (goto-char (nth 0 bounds)) (point-at-bol 2)))
8797 (end (and bounds (goto-char (nth 1 bounds)) (point-at-bol 1))))
8798 (if (and begin end)
8799 (let* ((lang (markdown-code-block-lang))
8800 (mode (and lang (markdown-get-lang-mode lang)))
8801 (edit-indirect-guess-mode-function
8802 (lambda (_parent-buffer _beg _end)
8803 (funcall mode))))
8804 (edit-indirect-region begin end 'display-buffer))
8805 (user-error "Not inside a GFM or tilde fenced code block")))
8806 (when (y-or-n-p "Package edit-indirect needed to edit code blocks. Install it now? ")
8807 (progn (package-refresh-contents)
8808 (package-install 'edit-indirect)
8809 (markdown-edit-code-block))))))
8812 ;;; ElDoc Support
8814 (defun markdown-eldoc-function ()
8815 "Return a helpful string when appropriate based on context.
8816 * Report URL when point is at a hidden URL.
8817 * Report language name when point is a code block with hidden markup."
8818 (cond
8819 ;; Hidden URL or reference for inline link
8820 ((and (or (thing-at-point-looking-at markdown-regex-link-inline)
8821 (thing-at-point-looking-at markdown-regex-link-reference))
8822 (or markdown-hide-urls markdown-hide-markup))
8823 (let* ((imagep (string-equal (match-string 1) "!"))
8824 (edit-keys (markdown--substitute-command-keys
8825 (if imagep
8826 "\\[markdown-insert-image]"
8827 "\\[markdown-insert-link]")))
8828 (edit-str (propertize edit-keys 'face 'font-lock-constant-face))
8829 (referencep (string-equal (match-string 5) "["))
8830 (object (if referencep "reference" "URL")))
8831 (format "Hidden %s (%s to edit): %s" object edit-str
8832 (if referencep
8833 (concat
8834 (propertize "[" 'face 'markdown-markup-face)
8835 (propertize (match-string-no-properties 6)
8836 'face 'markdown-reference-face)
8837 (propertize "]" 'face 'markdown-markup-face))
8838 (propertize (match-string-no-properties 6)
8839 'face 'markdown-url-face)))))
8840 ;; Hidden language name for fenced code blocks
8841 ((and (markdown-code-block-at-point-p)
8842 (not (get-text-property (point) 'markdown-pre))
8843 markdown-hide-markup)
8844 (let ((lang (save-excursion (markdown-code-block-lang))))
8845 (unless lang (setq lang "[unspecified]"))
8846 (format "Hidden code block language: %s (%s to toggle markup)"
8847 (propertize lang 'face 'markdown-language-keyword-face)
8848 (markdown--substitute-command-keys
8849 "\\[markdown-toggle-markup-hiding]"))))))
8852 ;;; Mode Definition ==========================================================
8854 (defun markdown-show-version ()
8855 "Show the version number in the minibuffer."
8856 (interactive)
8857 (message "markdown-mode, version %s" markdown-mode-version))
8859 (defun markdown-mode-info ()
8860 "Open the `markdown-mode' homepage."
8861 (interactive)
8862 (browse-url "https://jblevins.org/projects/markdown-mode/"))
8864 ;;;###autoload
8865 (define-derived-mode markdown-mode text-mode "Markdown"
8866 "Major mode for editing Markdown files."
8867 ;; Natural Markdown tab width
8868 (setq tab-width 4)
8869 ;; Comments
8870 (setq-local comment-start "<!-- ")
8871 (setq-local comment-end " -->")
8872 (setq-local comment-start-skip "<!--[ \t]*")
8873 (setq-local comment-column 0)
8874 (setq-local comment-auto-fill-only-comments nil)
8875 (setq-local comment-use-syntax t)
8876 ;; Syntax
8877 (add-hook 'syntax-propertize-extend-region-functions
8878 #'markdown-syntax-propertize-extend-region)
8879 (add-hook 'jit-lock-after-change-extend-region-functions
8880 #'markdown-font-lock-extend-region-function t t)
8881 (setq-local syntax-propertize-function #'markdown-syntax-propertize)
8882 ;; Font lock.
8883 (setq-local markdown-mode-font-lock-keywords nil)
8884 (setq-local font-lock-defaults nil)
8885 (setq-local font-lock-multiline t)
8886 (setq-local font-lock-extra-managed-props
8887 (append font-lock-extra-managed-props
8888 '(composition display invisible)))
8889 (if markdown-hide-markup
8890 (add-to-invisibility-spec 'markdown-markup)
8891 (remove-from-invisibility-spec 'markdown-markup))
8892 ;; Reload extensions
8893 (markdown-reload-extensions)
8894 ;; Add a buffer-local hook to reload after file-local variables are read
8895 (add-hook 'hack-local-variables-hook #'markdown-handle-local-variables nil t)
8896 ;; For imenu support
8897 (setq imenu-create-index-function
8898 (if markdown-nested-imenu-heading-index
8899 #'markdown-imenu-create-nested-index
8900 #'markdown-imenu-create-flat-index))
8901 ;; For menu support in XEmacs
8902 (easy-menu-add markdown-mode-menu markdown-mode-map)
8903 ;; Defun movement
8904 (setq-local beginning-of-defun-function #'markdown-beginning-of-defun)
8905 (setq-local end-of-defun-function #'markdown-end-of-defun)
8906 ;; Paragraph filling
8907 (setq-local fill-paragraph-function #'markdown-fill-paragraph)
8908 (setq-local paragraph-start
8909 ;; Should match start of lines that start or separate paragraphs
8910 (mapconcat #'identity
8912 "\f" ; starts with a literal line-feed
8913 "[ \t\f]*$" ; space-only line
8914 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
8915 "[ \t]*[*+-][ \t]+" ; unordered list item
8916 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
8917 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
8918 "[ \t]*:[ \t]+" ; definition
8919 "^|" ; table or Pandoc line block
8921 "\\|"))
8922 (setq-local paragraph-separate
8923 ;; Should match lines that separate paragraphs without being
8924 ;; part of any paragraph:
8925 (mapconcat #'identity
8926 '("[ \t\f]*$" ; space-only line
8927 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
8928 ;; The following is not ideal, but the Fill customization
8929 ;; options really only handle paragraph-starting prefixes,
8930 ;; not paragraph-ending suffixes:
8931 ".* $" ; line ending in two spaces
8932 "^#+"
8933 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
8934 "\\|"))
8935 (setq-local adaptive-fill-first-line-regexp "\\`[ \t]*[A-Z]?>[ \t]*?\\'")
8936 (setq-local adaptive-fill-regexp "\\s-*")
8937 (setq-local adaptive-fill-function #'markdown-adaptive-fill-function)
8938 (setq-local fill-forward-paragraph-function #'markdown-fill-forward-paragraph)
8939 ;; Outline mode
8940 (setq-local outline-regexp markdown-regex-header)
8941 (setq-local outline-level #'markdown-outline-level)
8942 ;; Cause use of ellipses for invisible text.
8943 (add-to-invisibility-spec '(outline . t))
8944 ;; ElDoc support
8945 (if (eval-when-compile (fboundp 'add-function))
8946 (add-function :before-until (local 'eldoc-documentation-function)
8947 #'markdown-eldoc-function)
8948 (setq-local eldoc-documentation-function #'markdown-eldoc-function))
8949 ;; Inhibiting line-breaking:
8950 ;; Separating out each condition into a separate function so that users can
8951 ;; override if desired (with remove-hook)
8952 (add-hook 'fill-nobreak-predicate
8953 #'markdown-line-is-reference-definition-p nil t)
8954 (add-hook 'fill-nobreak-predicate
8955 #'markdown-pipe-at-bol-p nil t)
8957 ;; Indentation
8958 (setq-local indent-line-function markdown-indent-function)
8960 ;; Flyspell
8961 (setq-local flyspell-generic-check-word-predicate
8962 #'markdown-flyspell-check-word-p)
8964 ;; Electric quoting
8965 (add-hook 'electric-quote-inhibit-functions
8966 #'markdown--inhibit-electric-quote nil :local)
8968 ;; Backwards compatibility with markdown-css-path
8969 (when (boundp 'markdown-css-path)
8970 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
8971 (add-to-list 'markdown-css-paths markdown-css-path))
8973 ;; Prepare hooks for XEmacs compatibility
8974 (when (featurep 'xemacs)
8975 (make-local-hook 'after-change-functions)
8976 (make-local-hook 'font-lock-extend-region-functions)
8977 (make-local-hook 'window-configuration-change-hook))
8979 ;; Make checkboxes buttons
8980 (when markdown-make-gfm-checkboxes-buttons
8981 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
8982 (add-hook 'after-change-functions #'markdown-gfm-checkbox-after-change-function t t)
8983 (add-hook 'change-major-mode-hook #'markdown-remove-gfm-checkbox-overlays t t))
8985 ;; edit-indirect
8986 (add-hook 'edit-indirect-after-commit-functions
8987 #'markdown--edit-indirect-after-commit-function
8988 nil 'local)
8990 ;; add live preview export hook
8991 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
8992 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
8994 ;;;###autoload
8995 (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode) t)
8996 ;;;###autoload
8997 (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode) t)
9000 ;;; GitHub Flavored Markdown Mode ============================================
9002 (defvar gfm-mode-hook nil
9003 "Hook run when entering GFM mode.")
9005 (defvar gfm-font-lock-keywords
9006 ;; Basic Markdown features (excluding possibly overridden ones)
9007 markdown-mode-font-lock-keywords-basic
9008 "Default highlighting expressions for GitHub Flavored Markdown mode.")
9010 ;;;###autoload
9011 (define-derived-mode gfm-mode markdown-mode "GFM"
9012 "Major mode for editing GitHub Flavored Markdown files."
9013 (setq markdown-link-space-sub-char "-")
9014 (setq markdown-wiki-link-search-subdirectories t)
9015 (setq-local font-lock-defaults '(gfm-font-lock-keywords))
9016 ;; do the initial link fontification
9017 (markdown-gfm-parse-buffer-for-languages))
9020 ;;; Live Preview Mode ============================================
9021 (define-minor-mode markdown-live-preview-mode
9022 "Toggle native previewing on save for a specific markdown file."
9023 :lighter " MD-Preview"
9024 (if markdown-live-preview-mode
9025 (if (markdown-live-preview-get-filename)
9026 (markdown-display-buffer-other-window (markdown-live-preview-export))
9027 (markdown-live-preview-mode -1)
9028 (user-error "Buffer %s does not visit a file" (current-buffer)))
9029 (markdown-live-preview-remove)))
9032 (provide 'markdown-mode)
9034 ;; Local Variables:
9035 ;; indent-tabs-mode: nil
9036 ;; coding: utf-8
9037 ;; End:
9038 ;;; markdown-mode.el ends here