Re-introduce markdown-prev-line-blank and for efficiency
[markdown-mode.git] / markdown-mode.el
blob62ba5ff8eac3edc36ddfe434c14bc2d1381404e2
1 ;;; markdown-mode.el --- Major mode for Markdown-formatted text -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2007-2017 Jason R. Blevins and markdown-mode
4 ;; contributors (see the commit log for details).
6 ;; Author: Jason R. Blevins <jblevins@xbeta.org>
7 ;; Maintainer: Jason R. Blevins <jblevins@xbeta.org>
8 ;; Created: May 24, 2007
9 ;; Version: 2.4-dev
10 ;; Package-Requires: ((emacs "24") (cl-lib "0.5"))
11 ;; Keywords: Markdown, GitHub Flavored Markdown, itex
12 ;; URL: https://jblevins.org/projects/markdown-mode/
14 ;; This file is not part of GNU Emacs.
16 ;; This program is free software; you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation, either version 3 of the License, or
19 ;; (at your option) any later version.
21 ;; This program is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
29 ;;; Commentary:
31 ;; markdown-mode is a major mode for editing [Markdown][]-formatted
32 ;; text. The latest stable version is markdown-mode 2.3, released on
33 ;; August 31, 2017. See the [release notes][] for details.
34 ;; markdown-mode is free software, licensed under the GNU GPL,
35 ;; version 3 or later.
37 ;; ![Markdown Mode Screenshot](https://jblevins.org/projects/markdown-mode/screenshots/20170818-001.png)
39 ;; [Markdown]: http://daringfireball.net/projects/markdown/
40 ;; [release notes]: https://jblevins.org/projects/markdown-mode/rev-2-3
42 ;;; Documentation:
44 ;; <a href="https://leanpub.com/markdown-mode">
45 ;; <img src="https://jblevins.org/projects/markdown-mode/guide-v2.3.png" align="right" height="350" width="231">
46 ;; </a>
48 ;; The primary documentation for Markdown Mode is available below, and
49 ;; is generated from comments in the source code. For a more in-depth
50 ;; treatment, the [_Guide to Markdown Mode for Emacs_][guide] covers
51 ;; Markdown syntax, advanced movement and editing in Emacs,
52 ;; extensions, configuration examples, tips and tricks, and a survey
53 ;; of other packages that work with Markdown Mode. Finally, Emacs is
54 ;; also a self-documenting editor. This means that the source code
55 ;; itself contains additional documentation: each function has its own
56 ;; docstring available via `C-h f` (`describe-function'), individual
57 ;; keybindings can be investigated with `C-h k` (`describe-key'), and
58 ;; a complete list of keybindings is available using `C-h m`
59 ;; (`describe-mode').
61 ;; [guide]: https://leanpub.com/markdown-mode
63 ;;; Installation:
65 ;; _Note:_ To use all of the features of `markdown-mode', you'll need
66 ;; to install the Emacs package itself and also have a local Markdown
67 ;; processor installed (e.g., Markdown.pl, MultiMarkdown, or Pandoc).
68 ;; The external processor is not required for editing, but will be
69 ;; used for rendering HTML for preview and export. After installing
70 ;; the Emacs package, be sure to configure `markdown-command' to point
71 ;; to the preferred Markdown executable on your system. See the
72 ;; Customization section below for more details.
74 ;; The recommended way to install `markdown-mode' is to install the package
75 ;; from [MELPA Stable](https://stable.melpa.org/#/markdown-mode)
76 ;; using `package.el'. First, configure `package.el' and the MELPA Stable
77 ;; repository by adding the following to your `.emacs', `init.el',
78 ;; or equivalent startup file:
80 ;; ``` Lisp
81 ;; (require 'package)
82 ;; (add-to-list 'package-archives
83 ;; '("melpa-stable" . "https://stable.melpa.org/packages/"))
84 ;; (package-initialize)
85 ;; ```
87 ;; Then, after restarting Emacs or evaluating the above statements, issue
88 ;; the following command: `M-x package-install RET markdown-mode RET`.
89 ;; When installed this way, the major modes `markdown-mode' and `gfm-mode'
90 ;; will be autoloaded and `markdown-mode' will be used for file names
91 ;; ending in either `.md` or `.markdown`.
93 ;; Alternatively, if you manage loading packages with [use-package][]
94 ;; then you can automatically install and configure `markdown-mode' by
95 ;; adding a declaration such as this one to your init file (as an
96 ;; example; adjust settings as desired):
98 ;; ``` Lisp
99 ;; (use-package markdown-mode
100 ;; :ensure t
101 ;; :commands (markdown-mode gfm-mode)
102 ;; :mode (("README\\.md\\'" . gfm-mode)
103 ;; ("\\.md\\'" . markdown-mode)
104 ;; ("\\.markdown\\'" . markdown-mode))
105 ;; :init (setq markdown-command "multimarkdown"))
106 ;; ```
108 ;; [MELPA Stable]: http://stable.melpa.org/
109 ;; [use-package]: https://github.com/jwiegley/use-package
111 ;; **Direct Download**
113 ;; Alternatively you can manually download and install markdown-mode.
114 ;; First, download the [latest stable version][markdown-mode.el] and
115 ;; save the file where Emacs can find it (i.e., a directory in your
116 ;; `load-path'). You can then configure `markdown-mode' and `gfm-mode'
117 ;; to load automatically by adding the following to your init file:
119 ;; ``` Lisp
120 ;; (autoload 'markdown-mode "markdown-mode"
121 ;; "Major mode for editing Markdown files" t)
122 ;; (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode))
123 ;; (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode))
125 ;; (autoload 'gfm-mode "markdown-mode"
126 ;; "Major mode for editing GitHub Flavored Markdown files" t)
127 ;; (add-to-list 'auto-mode-alist '("README\\.md\\'" . gfm-mode))
128 ;; ```
130 ;; [markdown-mode.el]: https://jblevins.org/projects/markdown-mode/markdown-mode.el
132 ;; **Development Version**
134 ;; To follow or contribute to markdown-mode development, you can
135 ;; browse or clone the Git repository
136 ;; [on GitHub](https://github.com/jrblevin/markdown-mode):
138 ;; ```
139 ;; git clone https://github.com/jrblevin/markdown-mode.git
140 ;; ```
142 ;; If you prefer to install and use the development version, which may
143 ;; become unstable at some times, you can either clone the Git
144 ;; repository as above or install markdown-mode from
145 ;; [MELPA](https://melpa.org/#/markdown-mode).
147 ;; If you clone the repository directly, then make sure that Emacs can
148 ;; find it by adding the following line to your startup file:
150 ;; ``` Lisp
151 ;; (add-to-list 'load-path "/path/to/markdown-mode/repository")
152 ;; ```
154 ;; **Packaged Installation**
156 ;; markdown-mode is also available in several package managers. You
157 ;; may want to confirm that the package you install contains the
158 ;; latest stable version first (and please notify the package
159 ;; maintainer if not).
161 ;; * Debian Linux: [elpa-markdown-mode][] and [emacs-goodies-el][]
162 ;; * Ubuntu Linux: [elpa-markdown-mode][elpa-ubuntu] and [emacs-goodies-el][emacs-goodies-el-ubuntu]
163 ;; * RedHat and Fedora Linux: [emacs-goodies][]
164 ;; * NetBSD: [textproc/markdown-mode][]
165 ;; * MacPorts: [markdown-mode.el][macports-package] ([pending][macports-ticket])
166 ;; * FreeBSD: [textproc/markdown-mode.el][freebsd-port]
168 ;; [elpa-markdown-mode]: https://packages.debian.org/sid/lisp/elpa-markdown-mode
169 ;; [elpa-ubuntu]: http://packages.ubuntu.com/search?keywords=elpa-markdown-mode
170 ;; [emacs-goodies-el]: http://packages.debian.org/emacs-goodies-el
171 ;; [emacs-goodies-el-ubuntu]: http://packages.ubuntu.com/search?keywords=emacs-goodies-el
172 ;; [emacs-goodies]: https://apps.fedoraproject.org/packages/emacs-goodies
173 ;; [textproc/markdown-mode]: http://pkgsrc.se/textproc/markdown-mode
174 ;; [macports-package]: https://trac.macports.org/browser/trunk/dports/editors/markdown-mode.el/Portfile
175 ;; [macports-ticket]: http://trac.macports.org/ticket/35716
176 ;; [freebsd-port]: http://svnweb.freebsd.org/ports/head/textproc/markdown-mode.el
178 ;; **Dependencies**
180 ;; To enable editing of code blocks in indirect buffers using `C-c '`,
181 ;; you will need to install the [`edit-indirect'][ei] package.
183 ;; [ei]: https://github.com/Fanael/edit-indirect/
185 ;;; Usage:
187 ;; Keybindings are grouped by prefixes based on their function. For
188 ;; example, the commands for styling text are grouped under `C-c C-s`
189 ;; and toggle commands begin with `C-c C-x`. The primary commands in
190 ;; each group will are described below. You can obtain a list of all
191 ;; keybindings by pressing `C-c C-h`. Movement and shifting commands
192 ;; tend to be associated with paired delimiters such as `M-{` and
193 ;; `M-}` or `C-c <` and `C-c >`. Outline navigation keybindings the
194 ;; same as in `org-mode'. Finally, commands for running Markdown or
195 ;; doing maintenance on an open file are grouped under the `C-c C-c`
196 ;; prefix. The most commonly used commands are described below. You
197 ;; can obtain a list of all keybindings by pressing `C-c C-h`.
199 ;; * Links and Images: `C-c C-l` and `C-c C-i`
201 ;; `C-c C-l` (`markdown-insert-link`) is a general command for
202 ;; inserting new link markup or editing existing link markup. This
203 ;; is especially useful when markup or URL hiding is enabled, so
204 ;; that URLs can't easily be edited directly. This command can be
205 ;; used to insert links of any form: either inline links,
206 ;; reference links, or plain URLs in angle brackets. The URL or
207 ;; `[reference]` label, link text, and optional title are entered
208 ;; through a series of interactive prompts. The type of link is
209 ;; determined by which values are provided:
211 ;; * If both a URL and link text are given, insert an inline link:
212 ;; `[text](url)`.
213 ;; * If both a `[reference]` label and link text are given, insert
214 ;; a reference link: `[text][reference]`.
215 ;; * If only link text is given, insert an implicit reference link:
216 ;; `[text][]`.
217 ;; * If only a URL is given, insert a plain URL link:
218 ;; `<url>`.
220 ;; Similarly, `C-c C-i` (`markdown-insert-image`) is a general
221 ;; command for inserting or editing image markup. As with the link
222 ;; insertion command, through a series interactive prompts you can
223 ;; insert either an inline or reference image:
225 ;; * If both a URL and alt text are given, insert an inline
226 ;; image: `![alt text](url)`.
227 ;; * If both a `[reference]` label and alt text are given,
228 ;; insert a reference link: `![alt text][reference]`.
230 ;; If there is an existing link or image at the point, these
231 ;; command will edit the existing markup rather than inserting new
232 ;; markup. Otherwise, if there is an active region, these commands
233 ;; use the region as either the default URL (if it seems to be a
234 ;; URL) or link text value otherwise. In that case, the region
235 ;; will be deleted and replaced by the link.
237 ;; Note that these functions can be used to convert links and
238 ;; images from one type to another (inline, reference, or plain
239 ;; URL) by selectively adding or removing properties via the
240 ;; interactive prompts.
242 ;; If a reference label is given that is not yet defined, you
243 ;; will be prompted for the URL and optional title and the
244 ;; reference will be inserted according to the value of
245 ;; `markdown-reference-location'. If a title is given, it will be
246 ;; added to the end of the reference definition and will be used
247 ;; to populate the title attribute when converted to HTML.
249 ;; Local images associated with image links may be displayed
250 ;; inline in the buffer by pressing `C-c C-x C-i`
251 ;; (`markdown-toggle-inline-images'). This is a toggle command, so
252 ;; pressing this once again will remove inline images. Large
253 ;; images may be scaled down to fit in the buffer using
254 ;; `markdown-max-image-size', a cons cell of the form
255 ;; `(max-width . max-height)`. Resizing requires Emacs to be
256 ;; built with ImageMagick support.
258 ;; * Text Styles: `C-c C-s`
260 ;; `C-c C-s i` inserts markup to make a region or word italic. If
261 ;; there is an active region, make the region italic. If the point
262 ;; is at a non-italic word, make the word italic. If the point is
263 ;; at an italic word or phrase, remove the italic markup.
264 ;; Otherwise, simply insert italic delimiters and place the point
265 ;; in between them. Similarly, use `C-c C-s b` for bold, `C-c C-s c`
266 ;; for inline code, and `C-c C-s k` for inserting `<kbd>` tags.
268 ;; `C-c C-s q` inserts a blockquote using the active region, if
269 ;; any, or starts a new blockquote. `C-c C-s Q` is a variation
270 ;; which always operates on the region, regardless of whether it
271 ;; is active or not (i.e., when `transient-mark-mode` is off but
272 ;; the mark is set). The appropriate amount of indentation, if
273 ;; any, is calculated automatically given the surrounding context,
274 ;; but may be adjusted later using the region indentation
275 ;; commands.
277 ;; `C-c C-s p` behaves similarly for inserting preformatted code
278 ;; blocks (with `C-c C-s P` being the region-only counterpart)
279 ;; and `C-c C-s C` inserts a GFM style backquote fenced code block.
281 ;; * Headings: `C-c C-s`
283 ;; To insert or replace headings, there are two options. You can
284 ;; insert a specific level heading directly or you can have
285 ;; `markdown-mode' determine the level for you based on the previous
286 ;; heading. As with the other markup commands, the heading
287 ;; insertion commands use the text in the active region, if any,
288 ;; as the heading text. Otherwise, if the current line is not
289 ;; blank, they use the text on the current line. Finally, the
290 ;; setext commands will prompt for heading text if there is no
291 ;; active region and the current line is blank.
293 ;; `C-c C-s h` inserts a heading with automatically chosen type and
294 ;; level (both determined by the previous heading). `C-c C-s H`
295 ;; behaves similarly, but uses setext (underlined) headings when
296 ;; possible, still calculating the level automatically.
297 ;; In cases where the automatically-determined level is not what
298 ;; you intended, the level can be quickly promoted or demoted
299 ;; (as described below). Alternatively, a `C-u` prefix can be
300 ;; given to insert a heading _promoted_ (lower number) by one
301 ;; level or a `C-u C-u` prefix can be given to insert a heading
302 ;; demoted (higher number) by one level.
304 ;; To insert a heading of a specific level and type, use `C-c C-s 1`
305 ;; through `C-c C-s 6` for atx (hash mark) headings and `C-c C-s !` or
306 ;; `C-c C-s @` for setext headings of level one or two, respectively.
307 ;; Note that `!` is `S-1` and `@` is `S-2`.
309 ;; If the point is at a heading, these commands will replace the
310 ;; existing markup in order to update the level and/or type of the
311 ;; heading. To remove the markup of the heading at the point,
312 ;; press `C-c C-k` to kill the heading and press `C-y` to yank the
313 ;; heading text back into the buffer.
315 ;; * Horizontal Rules: `C-c C-s -`
317 ;; `C-c C-s -` inserts a horizontal rule. By default, insert the
318 ;; first string in the list `markdown-hr-strings' (the most
319 ;; prominent rule). With a `C-u` prefix, insert the last string.
320 ;; With a numeric prefix `N`, insert the string in position `N`
321 ;; (counting from 1).
323 ;; * Footnotes: `C-c C-s f`
325 ;; `C-c C-s f` inserts a footnote marker at the point, inserts a
326 ;; footnote definition below, and positions the point for
327 ;; inserting the footnote text. Note that footnotes are an
328 ;; extension to Markdown and are not supported by all processors.
330 ;; * Wiki Links: `C-c C-s w`
332 ;; `C-c C-s w` inserts a wiki link of the form `[[WikiLink]]`. If
333 ;; there is an active region, use the region as the link text. If the
334 ;; point is at a word, use the word as the link text. If there is
335 ;; no active region and the point is not at word, simply insert
336 ;; link markup. Note that wiki links are an extension to Markdown
337 ;; and are not supported by all processors.
339 ;; * Markdown and Maintenance Commands: `C-c C-c`
341 ;; *Compile:* `C-c C-c m` will run Markdown on the current buffer
342 ;; and show the output in another buffer. *Preview*: `C-c C-c p`
343 ;; runs Markdown on the current buffer and previews, stores the
344 ;; output in a temporary file, and displays the file in a browser.
345 ;; *Export:* `C-c C-c e` will run Markdown on the current buffer
346 ;; and save the result in the file `basename.html`, where
347 ;; `basename` is the name of the Markdown file with the extension
348 ;; removed. *Export and View:* press `C-c C-c v` to export the
349 ;; file and view it in a browser. *Open:* `C-c C-c o` will open
350 ;; the Markdown source file directly using `markdown-open-command'.
351 ;; *Live Export*: Press `C-c C-c l` to turn on
352 ;; `markdown-live-preview-mode' to view the exported output
353 ;; side-by-side with the source Markdown. **For all export commands,
354 ;; the output file will be overwritten without notice.**
355 ;; `markdown-live-preview-window-function' can be customized to open
356 ;; in a browser other than `eww'. If you want to force the
357 ;; preview window to appear at the bottom or right, you can
358 ;; customize `markdown-split-window-direction'.
360 ;; To summarize:
362 ;; - `C-c C-c m`: `markdown-command' > `*markdown-output*` buffer.
363 ;; - `C-c C-c p`: `markdown-command' > temporary file > browser.
364 ;; - `C-c C-c e`: `markdown-command' > `basename.html`.
365 ;; - `C-c C-c v`: `markdown-command' > `basename.html` > browser.
366 ;; - `C-c C-c w`: `markdown-command' > kill ring.
367 ;; - `C-c C-c o`: `markdown-open-command'.
368 ;; - `C-c C-c l`: `markdown-live-preview-mode' > `*eww*` buffer.
370 ;; `C-c C-c c` will check for undefined references. If there are
371 ;; any, a small buffer will open with a list of undefined
372 ;; references and the line numbers on which they appear. In Emacs
373 ;; 22 and greater, selecting a reference from this list and
374 ;; pressing `RET` will insert an empty reference definition at the
375 ;; end of the buffer. Similarly, selecting the line number will
376 ;; jump to the corresponding line.
378 ;; `C-c C-c n` renumbers any ordered lists in the buffer that are
379 ;; out of sequence.
381 ;; `C-c C-c ]` completes all headings and normalizes all horizontal
382 ;; rules in the buffer.
384 ;; * Following Links: `C-c C-o`
386 ;; Press `C-c C-o` when the point is on an inline or reference
387 ;; link to open the URL in a browser. When the point is at a
388 ;; wiki link, open it in another buffer (in the current window,
389 ;; or in the other window with the `C-u` prefix). Use `M-p` and
390 ;; `M-n` to quickly jump to the previous or next link of any type.
392 ;; * Doing Things: `C-c C-d`
394 ;; Use `C-c C-d` to do something sensible with the object at the point:
396 ;; - Jumps between reference links and reference definitions.
397 ;; If more than one link uses the same reference label, a
398 ;; window will be shown containing clickable buttons for
399 ;; jumping to each link. Pressing `TAB` or `S-TAB` cycles
400 ;; between buttons in this window.
401 ;; - Jumps between footnote markers and footnote text.
402 ;; - Toggles the completion status of GFM task list items
403 ;; (checkboxes).
404 ;; - Re-aligns table columns.
406 ;; * Promotion and Demotion: `C-c C--` and `C-c C-=`
408 ;; Headings, horizontal rules, and list items can be promoted and
409 ;; demoted, as well as bold and italic text. For headings,
410 ;; "promotion" means *decreasing* the level (i.e., moving from
411 ;; `<h2>` to `<h1>`) while "demotion" means *increasing* the
412 ;; level. For horizontal rules, promotion and demotion means
413 ;; moving backward or forward through the list of rule strings in
414 ;; `markdown-hr-strings'. For bold and italic text, promotion and
415 ;; demotion means changing the markup from underscores to asterisks.
416 ;; Press `C-c C--` or `C-c LEFT` to promote the element at the point
417 ;; if possible.
419 ;; To remember these commands, note that `-` is for decreasing the
420 ;; level (promoting), and `=` (on the same key as `+`) is for
421 ;; increasing the level (demoting). Similarly, the left and right
422 ;; arrow keys indicate the direction that the atx heading markup
423 ;; is moving in when promoting or demoting.
425 ;; * Completion: `C-c C-]`
427 ;; Complete markup is in normalized form, which means, for
428 ;; example, that the underline portion of a setext header is the
429 ;; same length as the heading text, or that the number of leading
430 ;; and trailing hash marks of an atx header are equal and that
431 ;; there is no extra whitespace in the header text. `C-c C-]`
432 ;; completes the markup at the point, if it is determined to be
433 ;; incomplete.
435 ;; * Editing Lists: `M-RET`, `C-c UP`, `C-c DOWN`, `C-c LEFT`, and `C-c RIGHT`
437 ;; New list items can be inserted with `M-RET` or `C-c C-j`. This
438 ;; command determines the appropriate marker (one of the possible
439 ;; unordered list markers or the next number in sequence for an
440 ;; ordered list) and indentation level by examining nearby list
441 ;; items. If there is no list before or after the point, start a
442 ;; new list. As with heading insertion, you may prefix this
443 ;; command by `C-u` to decrease the indentation by one level.
444 ;; Prefix this command by `C-u C-u` to increase the indentation by
445 ;; one level.
447 ;; Existing list items (and their nested sub-items) can be moved
448 ;; up or down with `C-c UP` or `C-c DOWN` and indented or
449 ;; outdented with `C-c RIGHT` or `C-c LEFT`.
451 ;; * Editing Subtrees: `C-c UP`, `C-c DOWN`, `C-c LEFT`, and `C-c RIGHT`
453 ;; Entire subtrees of ATX headings can be promoted and demoted
454 ;; with `C-c LEFT` and `C-c RIGHT`, which are the same keybindings
455 ;; used for promotion and demotion of list items. If the point is in
456 ;; a list item, the operate on the list item. Otherwise, they operate
457 ;; on the current heading subtree. Similarly, subtrees can be
458 ;; moved up and down with `C-c UP` and `C-c DOWN`.
460 ;; These commands currently do not work properly if there are
461 ;; Setext headings in the affected region.
463 ;; Please note the following "boundary" behavior for promotion and
464 ;; demotion. Any level-six headings will not be demoted further
465 ;; (i.e., they remain at level six, since Markdown and HTML define
466 ;; only six levels) and any level-one headings will promoted away
467 ;; entirely (i.e., heading markup will be removed, since a
468 ;; level-zero heading is not defined).
470 ;; * Shifting the Region: `C-c <` and `C-c >`
472 ;; Text in the region can be indented or outdented as a group using
473 ;; `C-c >` to indent to the next indentation point (calculated in
474 ;; the current context), and `C-c <` to outdent to the previous
475 ;; indentation point. These keybindings are the same as those for
476 ;; similar commands in `python-mode'.
478 ;; * Killing Elements: `C-c C-k`
480 ;; Press `C-c C-k` to kill the thing at point and add important
481 ;; text, without markup, to the kill ring. Possible things to
482 ;; kill include (roughly in order of precedece): inline code,
483 ;; headings, horizonal rules, links (add link text to kill ring),
484 ;; images (add alt text to kill ring), angle URIs, email
485 ;; addresses, bold, italics, reference definitions (add URI to
486 ;; kill ring), footnote markers and text (kill both marker and
487 ;; text, add text to kill ring), and list items.
489 ;; * Outline Navigation: `C-c C-n`, `C-c C-p`, `C-c C-f`, `C-c C-b`, and `C-c C-u`
491 ;; These keys are used for hierarchical navigation in lists and
492 ;; headings. When the point is in a list, they move between list
493 ;; items. Otherwise, they move between headings. Use `C-c C-n` and
494 ;; `C-c C-p` to move between the next and previous visible
495 ;; headings or list items of any level. Similarly, `C-c C-f` and
496 ;; `C-c C-b` move to the next and previous visible headings or
497 ;; list items at the same level as the one at the point. Finally,
498 ;; `C-c C-u` will move up to the parent heading or list item.
500 ;; * Movement by Markdown paragraph: `M-{`, `M-}`, and `M-h`
502 ;; Paragraphs in `markdown-mode' are regular paragraphs,
503 ;; paragraphs inside blockquotes, individual list items, headings,
504 ;; etc. These keys are usually bound to `forward-paragraph' and
505 ;; `backward-paragraph', but the built-in Emacs functions are
506 ;; based on simple regular expressions that fail in Markdown
507 ;; files. Instead, they are bound to `markdown-forward-paragraph'
508 ;; and `markdown-backward-paragraph'. To mark a paragraph,
509 ;; you can use `M-h` (`markdown-mark-paragraph').
511 ;; * Movement by Markdown block: `C-M-{`, `C-M-}`, and `C-c M-h`
513 ;; Markdown blocks are regular paragraphs in many cases, but
514 ;; contain many paragraphs in other cases: blocks are considered
515 ;; to be entire lists, entire code blocks, and entire blockquotes.
516 ;; To move backward one block use `C-M-{`
517 ;; (`markdown-beginning-block`) and to move forward use `C-M-}`
518 ;; (`markdown-end-of-block`). To mark a block, use `C-c M-h`
519 ;; (`markdown-mark-block`).
521 ;; * Movement by Defuns: `C-M-a`, `C-M-e`, and `C-M-h`
523 ;; The usual Emacs commands can be used to move by defuns
524 ;; (top-level major definitions). In markdown-mode, a defun is a
525 ;; section. As usual, `C-M-a` will move the point to the
526 ;; beginning of the current or preceding defun, `C-M-e` will move
527 ;; to the end of the current or following defun, and `C-M-h` will
528 ;; put the region around the entire defun.
530 ;; * Table Editing:
532 ;; Markdown Mode includes support for editing tables, which
533 ;; have the following basic format:
535 ;; | Right | Left | Center | Default |
536 ;; |------:|:-----|:------:|---------|
537 ;; | 12 | 12 | 12 | 12 |
538 ;; | 123 | 123 | 123 | 123 |
539 ;; | 1 | 1 | 1 | 1 |
541 ;; The first line contains column headers. The second line
542 ;; contains a separator line between the headers and the content.
543 ;; Each following line is a row in the table. Columns are always
544 ;; separated by the pipe character. The colons indicate column
545 ;; alignment.
547 ;; A table is re-aligned automatically each time you press `TAB`
548 ;; or `RET` inside the table. `TAB` also moves to the next
549 ;; field (`RET` to the next row) and creates new table rows at
550 ;; the end of the table or before horizontal separator lines. The
551 ;; indentation of the table is set by the first line. Column
552 ;; centering inside Emacs is not supported.
554 ;; Beginning pipe characters are required for proper detection of
555 ;; table borders inside Emacs. Any line starting with `|-` or `|:`
556 ;; is considered as a horizontal separator line and will be
557 ;; expanded on the next re-align to span the whole table width. No
558 ;; padding is allowed between the beginning pipe character and
559 ;; header separator symbol. So, to create the above table, you
560 ;; would only type
562 ;; |Right|Left|Center|Default|
563 ;; |-
565 ;; and then press `TAB` to align the table and start filling in
566 ;; cells.
568 ;; Then you can jump with `TAB` from one cell to the next or with
569 ;; `S-TAB` to the previous one. `RET` will jump to the to the
570 ;; next cell in the same column, and create a new row if there is
571 ;; no such cell or if the next row is beyond a separator line.
573 ;; You can also convert selected region to a table. Basic editing
574 ;; capabilities include inserting, deleting, and moving of columns
575 ;; and rows, and table re-alignment, sorting, transposition:
577 ;; - `C-c UP` or `C-c DOWN` - Move the current row up or down.
578 ;; - `C-c LEFT` or `C-c RIGHT` - Move the current column left or right.
579 ;; - `C-c S-UP` - Kill the current row.
580 ;; - `C-c S-DOWN` - Insert a row above the current row. With a
581 ;; prefix argument, row line is created below the current one.
582 ;; - `C-c S-LEFT` - Kill the current column.
583 ;; - `C-c S-RIGHT` - Insert a new column to the left of the current one.
584 ;; - `C-c C-d` - Re-align the current table (`markdown-do`).
585 ;; - `C-c C-c ^` - Sort the rows of a table by a specified column.
586 ;; This command prompts you for the column number and a sort
587 ;; method (alphabetical or numerical, optionally in reverse).
588 ;; - `C-c C-c |` - Convert the region to a table. This function
589 ;; attempts to recognize comma, tab, and space separated data
590 ;; and then splits the data into cells accordingly.
591 ;; - `C-c C-c t` - Transpose table at point.
593 ;; The table editing functions try to handle markup hiding
594 ;; correctly when calculating column widths, however, columns
595 ;; containing hidden markup may not always be aligned properly.
597 ;; * Miscellaneous Commands:
599 ;; When the [`edit-indirect'][ei] package is installed, `C-c '`
600 ;; (`markdown-edit-code-block`) can be used to edit a code block
601 ;; in an indirect buffer in the native major mode. Press `C-c C-c`
602 ;; to commit changes and return or `C-c C-k` to cancel. You can
603 ;; also give a prefix argument to the insertion command, as in
604 ;; `C-u C-c C-s C`, to edit the code block in an indirect buffer
605 ;; upon insertion.
607 ;; As noted, many of the commands above behave differently depending
608 ;; on whether Transient Mark mode is enabled or not. When it makes
609 ;; sense, if Transient Mark mode is on and the region is active, the
610 ;; command applies to the text in the region (e.g., `C-c C-s b` makes the
611 ;; region bold). For users who prefer to work outside of Transient
612 ;; Mark mode, since Emacs 22 it can be enabled temporarily by pressing
613 ;; `C-SPC C-SPC`. When this is not the case, many commands then
614 ;; proceed to look work with the word or line at the point.
616 ;; When applicable, commands that specifically act on the region even
617 ;; outside of Transient Mark mode have the same keybinding as their
618 ;; standard counterpart, but the letter is uppercase. For example,
619 ;; `markdown-insert-blockquote' is bound to `C-c C-s q` and only acts on
620 ;; the region in Transient Mark mode while `markdown-blockquote-region'
621 ;; is bound to `C-c C-s Q` and always applies to the region (when nonempty).
623 ;; Note that these region-specific functions are useful in many
624 ;; cases where it may not be obvious. For example, yanking text from
625 ;; the kill ring sets the mark at the beginning of the yanked text
626 ;; and moves the point to the end. Therefore, the (inactive) region
627 ;; contains the yanked text. So, `C-y` followed by `C-c C-s Q` will
628 ;; yank text and turn it into a blockquote.
630 ;; markdown-mode attempts to be flexible in how it handles
631 ;; indentation. When you press `TAB` repeatedly, the point will cycle
632 ;; through several possible indentation levels corresponding to things
633 ;; you might have in mind when you press `RET` at the end of a line or
634 ;; `TAB`. For example, you may want to start a new list item,
635 ;; continue a list item with hanging indentation, indent for a nested
636 ;; pre block, and so on. Outdenting is handled similarly when backspace
637 ;; is pressed at the beginning of the non-whitespace portion of a line.
639 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
640 ;; visibility cycling for atx- or hash-style headings. There are two
641 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
642 ;; the table of contents view (headings only), outline view (top-level
643 ;; headings only), and the full document view. Pressing `TAB` while the
644 ;; point is at a heading will cycle through levels of visibility for the
645 ;; subtree: completely folded, visible children, and fully visible.
646 ;; Note that mixing hash and underline style headings will give undesired
647 ;; results.
649 ;;; Customization:
651 ;; Although no configuration is *necessary* there are a few things
652 ;; that can be customized. The `M-x customize-mode` command
653 ;; provides an interface to all of the possible customizations:
655 ;; * `markdown-command' - the command used to run Markdown (default:
656 ;; `markdown`). This variable may be customized to pass
657 ;; command-line options to your Markdown processor of choice. It can
658 ;; also be a function; in this case `markdown' will call it with three
659 ;; arguments: the beginning and end of the region to process, and
660 ;; a buffer to write the output to.
662 ;; * `markdown-command-needs-filename' - set to `t' if
663 ;; `markdown-command' does not accept standard input (default:
664 ;; `nil'). When `nil', `markdown-mode' will pass the Markdown
665 ;; content to `markdown-command' using standard input (`stdin`).
666 ;; When set to `t', `markdown-mode' will pass the name of the file
667 ;; as the final command-line argument to `markdown-command'. Note
668 ;; that in the latter case, you will only be able to run
669 ;; `markdown-command' from buffers which are visiting a file. If
670 ;; `markdown-command' is a function, `markdown-command-needs-filename'
671 ;; is ignored.
673 ;; * `markdown-open-command' - the command used for calling a standalone
674 ;; Markdown previewer which is capable of opening Markdown source files
675 ;; directly (default: `nil'). This command will be called
676 ;; with a single argument, the filename of the current buffer.
677 ;; A representative program is the Mac app [Marked 2][], a
678 ;; live-updating Markdown previewer which can be [called from a
679 ;; simple shell script](https://jblevins.org/log/marked-2-command).
680 ;; This variable can also be a function; in this case `markdown-open'
681 ;; will call it without arguments to preview the current buffer.
683 ;; * `markdown-hr-strings' - list of strings to use when inserting
684 ;; horizontal rules. Different strings will not be distinguished
685 ;; when converted to HTML--they will all be converted to
686 ;; `<hr/>`--but they may add visual distinction and style to plain
687 ;; text documents. To maintain some notion of promotion and
688 ;; demotion, keep these sorted from largest to smallest.
690 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
691 ;; underscores when inserting bold text instead of two asterisks
692 ;; (default: `nil').
694 ;; * `markdown-italic-underscore' - set to a non-nil value to use
695 ;; underscores when inserting italic text instead of asterisks
696 ;; (default: `nil').
698 ;; * `markdown-asymmetric-header' - set to a non-nil value to use
699 ;; asymmetric header styling, placing header characters only on
700 ;; the left of headers (default: `nil').
702 ;; * `markdown-header-scaling' - set to a non-nil value to use
703 ;; a variable-pitch font for headings where the size corresponds
704 ;; to the level of the heading (default: `nil').
706 ;; * `markdown-header-scaling-values' - list of scaling values,
707 ;; relative to baseline, for headers of levels one through six,
708 ;; used when `markdown-header-scaling' is non-nil
709 ;; (default: `(2.0 1.7 1.4 1.1 1.0 1.0)`).
711 ;; * `markdown-marginalize-headers' - put opening atx header markup
712 ;; in the left margin when non-nil (default: `nil').
714 ;; * `markdown-marginalize-headers-margin-width' - width of margin
715 ;; used for marginalized headers (default: 6).
717 ;; * `markdown-list-indent-width' - depth of indentation for lists
718 ;; when inserting, promoting, and demoting list items (default: 4).
720 ;; * `markdown-indent-function' - the function to use for automatic
721 ;; indentation (default: `markdown-indent-line').
723 ;; * `markdown-indent-on-enter' - Set to a non-nil value to
724 ;; automatically indent new lines when `RET` is pressed.
725 ;; Set to `indent-and-new-item' to additionally continue lists
726 ;; when `RET` is pressed (default: `t').
728 ;; * `markdown-enable-wiki-links' - syntax highlighting for wiki
729 ;; links (default: `nil'). Set this to a non-nil value to turn on
730 ;; wiki link support by default. Wiki link support can be toggled
731 ;; later using the function `markdown-toggle-wiki-links'."
733 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
734 ;; treat aliased wiki links like `[[link text|PageName]]`
735 ;; (default: `t'). When set to nil, they will be treated as
736 ;; `[[PageName|link text]]'.
738 ;; * `markdown-uri-types' - a list of protocol schemes (e.g., "http")
739 ;; for URIs that `markdown-mode' should highlight.
741 ;; * `markdown-enable-math' - font lock for inline and display LaTeX
742 ;; math expressions (default: `nil'). Set this to `t' to turn on
743 ;; math support by default. Math support can be toggled
744 ;; interactively later using `C-c C-x C-e`
745 ;; (`markdown-toggle-math').
747 ;; * `markdown-enable-html' - font lock for HTML tags and attributes
748 ;; (default: `t').
750 ;; * `markdown-css-paths' - CSS files to link to in XHTML output
751 ;; (default: `nil`).
753 ;; * `markdown-content-type' - when set to a nonempty string, an
754 ;; `http-equiv` attribute will be included in the XHTML `<head>`
755 ;; block (default: `""`). If needed, the suggested values are
756 ;; `application/xhtml+xml` or `text/html`. See also:
757 ;; `markdown-coding-system'.
759 ;; * `markdown-coding-system' - used for specifying the character
760 ;; set identifier in the `http-equiv` attribute when included
761 ;; (default: `nil'). See `markdown-content-type', which must
762 ;; be set before this variable has any effect. When set to `nil',
763 ;; `buffer-file-coding-system' will be used to automatically
764 ;; determine the coding system string (falling back to
765 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
766 ;; and `iso-latin-1'.
768 ;; * `markdown-xhtml-header-content' - additional content to include
769 ;; in the XHTML `<head>` block (default: `""`).
771 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
772 ;; `markdown-mode' uses to determine whether the output of
773 ;; `markdown-command' is a standalone XHTML document or an XHTML
774 ;; fragment (default: `"^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"`). If
775 ;; this regular expression not matched in the first five lines of
776 ;; output, `markdown-mode' assumes the output is a fragment and
777 ;; adds a header and footer.
779 ;; * `markdown-link-space-sub-char' - a character to replace spaces
780 ;; when mapping wiki links to filenames (default: `"_"`).
781 ;; For example, use an underscore for compatibility with the
782 ;; Python Markdown WikiLinks extension. In `gfm-mode', this is
783 ;; set to `"-"` to conform with GitHub wiki links.
785 ;; * `markdown-reference-location' - where to insert reference
786 ;; definitions (default: `header`). The possible locations are
787 ;; the end of the document (`end`), after the current block
788 ;; (`immediately`), the end of the current subtree (`subtree'),
789 ;; or before the next header (`header`).
791 ;; * `markdown-footnote-location' - where to insert footnote text
792 ;; (default: `end`). The set of location options is the same as
793 ;; for `markdown-reference-location'.
795 ;; * `markdown-nested-imenu-heading-index' - Use nested imenu
796 ;; heading instead of a flat index (default: `t'). A nested
797 ;; index may provide more natural browsing from the menu, but a
798 ;; flat list may allow for faster keyboard navigation via tab
799 ;; completion.
801 ;; * `comment-auto-fill-only-comments' - variable is made
802 ;; buffer-local and set to `nil' by default. In programming
803 ;; language modes, when this variable is non-nil, only comments
804 ;; will be filled by auto-fill-mode. However, comments in
805 ;; Markdown documents are rare and the most users probably intend
806 ;; for the actual content of the document to be filled. Making
807 ;; this variable buffer-local allows `markdown-mode' to override
808 ;; the default behavior induced when the global variable is non-nil.
810 ;; * `markdown-gfm-additional-languages', - additional languages to
811 ;; make available, aside from those predefined in
812 ;; `markdown-gfm-recognized-languages', when inserting GFM code
813 ;; blocks (default: `nil`). Language strings must have be trimmed
814 ;; of whitespace and not contain any curly braces. They may be of
815 ;; arbitrary capitalization, though.
817 ;; * `markdown-gfm-use-electric-backquote' - use
818 ;; `markdown-electric-backquote' for interactive insertion of GFM
819 ;; code blocks when backquote is pressed three times (default: `t`).
821 ;; * `markdown-make-gfm-checkboxes-buttons' - Whether GitHub
822 ;; Flavored Markdown style task lists (checkboxes) should be
823 ;; turned into buttons that can be toggled with mouse-1 or RET. If
824 ;; non-nil (default), then buttons are enabled. This works in
825 ;; `markdown-mode' as well as `gfm-mode'.
827 ;; * `markdown-hide-urls' - Determines whether URL and reference
828 ;; labels are hidden for inline and reference links (default: `nil').
829 ;; When non-nil, inline links will appear in the buffer as
830 ;; `[link](∞)` instead of
831 ;; `[link](http://perhaps.a/very/long/url/)`. To change the
832 ;; placeholder (composition) character used, set the variable
833 ;; `markdown-url-compose-char'. URL hiding can be toggled
834 ;; interactively using `C-c C-x C-l` (`markdown-toggle-url-hiding')
835 ;; or from the Markdown | Links & Images menu.
837 ;; * `markdown-hide-markup' - Determines whether all possible markup
838 ;; is hidden or otherwise beautified (default: `nil'). The actual
839 ;; buffer text remains unchanged, but the display will be altered.
840 ;; Brackets and URLs for links will be hidden, asterisks and
841 ;; underscores for italic and bold text will be hidden, text
842 ;; bullets for unordered lists will be replaced by Unicode
843 ;; bullets, and so on. Since this includes URLs and reference
844 ;; labels, when non-nil this setting supersedes `markdown-hide-urls'.
845 ;; Markup hiding can be toggled using `C-c C-x C-m`
846 ;; (`markdown-toggle-markup-hiding') or from the Markdown | Show &
847 ;; Hide menu.
849 ;; Unicode bullets are used to replace ASCII list item markers.
850 ;; The list of characters used, in order of list level, can be
851 ;; specified by setting the variable `markdown-list-item-bullets'.
852 ;; The placeholder characters used to replace other markup can
853 ;; be changed by customizing the corresponding variables:
854 ;; `markdown-blockquote-display-char',
855 ;; `markdown-hr-display-char', and
856 ;; `markdown-definition-display-char'.
858 ;; * `markdown-fontify-code-blocks-natively' - Whether to fontify
859 ;; code in code blocks using the native major mode. This only
860 ;; works for fenced code blocks where the language is specified
861 ;; where we can automatically determine the appropriate mode to
862 ;; use. The language to mode mapping may be customized by setting
863 ;; the variable `markdown-code-lang-modes'. This can be toggled
864 ;; interactively by pressing `C-c C-x C-f`
865 ;; (`markdown-toggle-fontify-code-blocks-natively').
867 ;; * `markdown-gfm-uppercase-checkbox' - When non-nil, complete GFM
868 ;; task list items with `[X]` instead of `[x]` (default: `nil').
869 ;; This is useful for compatibility with `org-mode', which doesn't
870 ;; recognize the lowercase variant.
872 ;; * `markdown-translate-filename-function' - A function to be used to
873 ;; translate filenames in links.
875 ;; Additionally, the faces used for syntax highlighting can be modified to
876 ;; your liking by issuing `M-x customize-group RET markdown-faces`
877 ;; or by using the "Markdown Faces" link at the bottom of the mode
878 ;; customization screen.
880 ;; [Marked 2]: https://itunes.apple.com/us/app/marked-2/id890031187?mt=12&uo=4&at=11l5Vs&ct=mm
882 ;;; Extensions:
884 ;; Besides supporting the basic Markdown syntax, Markdown Mode also
885 ;; includes syntax highlighting for `[[Wiki Links]]`. This can be
886 ;; enabled by setting `markdown-enable-wiki-links' to a non-nil value.
887 ;; Wiki links may be followed by pressing `C-c C-o` when the point
888 ;; is at a wiki link. Use `M-p` and `M-n` to quickly jump to the
889 ;; previous and next links (including links of other types).
890 ;; Aliased or piped wiki links of the form `[[link text|PageName]]`
891 ;; are also supported. Since some wikis reverse these components, set
892 ;; `markdown-wiki-link-alias-first' to nil to treat them as
893 ;; `[[PageName|link text]]`. If `markdown-wiki-link-fontify-missing'
894 ;; is also non-nil, Markdown Mode will highlight wiki links with
895 ;; missing target file in a different color. By default, Markdown
896 ;; Mode only searches for target files in the current directory.
897 ;; Search in subdirectories can be enabled by setting
898 ;; `markdown-wiki-link-search-subdirectories' to a non-nil value.
899 ;; Sequential parent directory search (as in [Ikiwiki][]) can be
900 ;; enabled by setting `markdown-wiki-link-search-parent-directories'
901 ;; to a non-nil value.
903 ;; [Ikiwiki]: https://ikiwiki.info
905 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
906 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
907 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
908 ;; You can do this either by using `M-x customize-group markdown`
909 ;; or by placing the following in your `.emacs` file:
911 ;; ``` Lisp
912 ;; (setq markdown-command "markdown | smartypants")
913 ;; ```
915 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
917 ;; Syntax highlighting for mathematical expressions written
918 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
919 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
920 ;; either via customize or by placing `(setq markdown-enable-math t)`
921 ;; in `.emacs`, and then restarting Emacs or calling
922 ;; `markdown-reload-extensions'.
924 ;;; GitHub Flavored Markdown (GFM):
926 ;; A [GitHub Flavored Markdown][GFM] mode, `gfm-mode', is also
927 ;; available. The GitHub implementation differs slightly from
928 ;; standard Markdown in that it supports things like different
929 ;; behavior for underscores inside of words, automatic linking of
930 ;; URLs, strikethrough text, and fenced code blocks with an optional
931 ;; language keyword.
933 ;; The GFM-specific features above apply to `README.md` files, wiki
934 ;; pages, and other Markdown-formatted files in repositories on
935 ;; GitHub. GitHub also enables [additional features][GFM comments] for
936 ;; writing on the site (for issues, pull requests, messages, etc.)
937 ;; that are further extensions of GFM. These features include task
938 ;; lists (checkboxes), newlines corresponding to hard line breaks,
939 ;; auto-linked references to issues and commits, wiki links, and so
940 ;; on. To make matters more confusing, although task lists are not
941 ;; part of [GFM proper][GFM], [since 2014][] they are rendered (in a
942 ;; read-only fashion) in all Markdown documents in repositories on the
943 ;; site. These additional extensions are supported to varying degrees
944 ;; by `markdown-mode' and `gfm-mode' as described below.
946 ;; * **URL autolinking:** Both `markdown-mode' and `gfm-mode' support
947 ;; highlighting of URLs without angle brackets.
949 ;; * **Multiple underscores in words:** You must enable `gfm-mode' to
950 ;; toggle support for underscores inside of words. In this mode
951 ;; variable names such as `a_test_variable` will not trigger
952 ;; emphasis (italics).
954 ;; * **Fenced code blocks:** Code blocks quoted with backquotes, with
955 ;; optional programming language keywords, are highlighted in
956 ;; both `markdown-mode' and `gfm-mode'. They can be inserted with
957 ;; `C-c C-s C`. If there is an active region, the text in the
958 ;; region will be placed inside the code block. You will be
959 ;; prompted for the name of the language, but may press enter to
960 ;; continue without naming a language.
962 ;; * **Strikethrough:** Strikethrough text is supported in both
963 ;; `markdown-mode' and `gfm-mode'. It can be inserted (and toggled)
964 ;; using `C-c C-s s`.
966 ;; * **Task lists:** GFM task lists will be rendered as checkboxes
967 ;; (Emacs buttons) in both `markdown-mode' and `gfm-mode' when
968 ;; `markdown-make-gfm-checkboxes-buttons' is set to a non-nil value
969 ;; (and it is set to t by default). These checkboxes can be
970 ;; toggled by clicking `mouse-1`, pressing `RET` over the button,
971 ;; or by pressing `C-c C-d` (`markdown-do`) with the point anywhere
972 ;; in the task list item. A normal list item can be turned to a
973 ;; check list item by the same command, or more specifically
974 ;; `C-c C-s [` (`markdown-insert-gfm-checkbox`).
976 ;; * **Wiki links:** Generic wiki links are supported in
977 ;; `markdown-mode', but in `gfm-mode' specifically they will be
978 ;; treated as they are on GitHub: spaces will be replaced by hyphens
979 ;; in filenames and the first letter of the filename will be
980 ;; capitalized. For example, `[[wiki link]]' will map to a file
981 ;; named `Wiki-link` with the same extension as the current file.
982 ;; If a file with this name does not exist in the current directory,
983 ;; the first match in a subdirectory, if any, will be used instead.
985 ;; * **Newlines:** Neither `markdown-mode' nor `gfm-mode' do anything
986 ;; specifically with respect to newline behavior. If you use
987 ;; `gfm-mode' mostly to write text for comments or issues on the
988 ;; GitHub site--where newlines are significant and correspond to
989 ;; hard line breaks--then you may want to enable `visual-line-mode'
990 ;; for line wrapping in buffers. You can do this with a
991 ;; `gfm-mode-hook' as follows:
993 ;; ``` Lisp
994 ;; ;; Use visual-line-mode in gfm-mode
995 ;; (defun my-gfm-mode-hook ()
996 ;; (visual-line-mode 1))
997 ;; (add-hook 'gfm-mode-hook 'my-gfm-mode-hook)
998 ;; ```
1000 ;; * **Preview:** GFM-specific preview can be powered by setting
1001 ;; `markdown-command' to use [Docter][]. This may also be
1002 ;; configured to work with [Marked 2][] for `markdown-open-command'.
1004 ;; [GFM]: http://github.github.com/github-flavored-markdown/
1005 ;; [GFM comments]: https://help.github.com/articles/writing-on-github/
1006 ;; [since 2014]: https://github.com/blog/1825-task-lists-in-all-markdown-documents
1007 ;; [Docter]: https://github.com/alampros/Docter
1009 ;;; Acknowledgments:
1011 ;; markdown-mode has benefited greatly from the efforts of the many
1012 ;; volunteers who have sent patches, test cases, bug reports,
1013 ;; suggestions, helped with packaging, etc. Thank you for your
1014 ;; contributions! See the [contributors graph][contrib] for details.
1016 ;; [contrib]: https://github.com/jrblevin/markdown-mode/graphs/contributors
1018 ;;; Bugs:
1020 ;; markdown-mode is developed and tested primarily for compatibility
1021 ;; with GNU Emacs 24.3 and later. If you find any bugs in
1022 ;; markdown-mode, please construct a test case or a patch and open a
1023 ;; ticket on the [GitHub issue tracker][issues]. See the
1024 ;; contributing guidelines in `CONTRIBUTING.md` for details on
1025 ;; creating pull requests.
1027 ;; [issues]: https://github.com/jrblevin/markdown-mode/issues
1029 ;;; History:
1031 ;; markdown-mode was written and is maintained by Jason Blevins. The
1032 ;; first version was released on May 24, 2007.
1034 ;; * 2007-05-24: [Version 1.1][]
1035 ;; * 2007-05-25: [Version 1.2][]
1036 ;; * 2007-06-05: [Version 1.3][]
1037 ;; * 2007-06-29: [Version 1.4][]
1038 ;; * 2007-10-11: [Version 1.5][]
1039 ;; * 2008-06-04: [Version 1.6][]
1040 ;; * 2009-10-01: [Version 1.7][]
1041 ;; * 2011-08-12: [Version 1.8][]
1042 ;; * 2011-08-15: [Version 1.8.1][]
1043 ;; * 2013-01-25: [Version 1.9][]
1044 ;; * 2013-03-24: [Version 2.0][]
1045 ;; * 2016-01-09: [Version 2.1][]
1046 ;; * 2017-05-26: [Version 2.2][]
1047 ;; * 2017-08-31: [Version 2.3][]
1049 ;; [Version 1.1]: https://jblevins.org/projects/markdown-mode/rev-1-1
1050 ;; [Version 1.2]: https://jblevins.org/projects/markdown-mode/rev-1-2
1051 ;; [Version 1.3]: https://jblevins.org/projects/markdown-mode/rev-1-3
1052 ;; [Version 1.4]: https://jblevins.org/projects/markdown-mode/rev-1-4
1053 ;; [Version 1.5]: https://jblevins.org/projects/markdown-mode/rev-1-5
1054 ;; [Version 1.6]: https://jblevins.org/projects/markdown-mode/rev-1-6
1055 ;; [Version 1.7]: https://jblevins.org/projects/markdown-mode/rev-1-7
1056 ;; [Version 1.8]: https://jblevins.org/projects/markdown-mode/rev-1-8
1057 ;; [Version 1.8.1]: https://jblevins.org/projects/markdown-mode/rev-1-8-1
1058 ;; [Version 1.9]: https://jblevins.org/projects/markdown-mode/rev-1-9
1059 ;; [Version 2.0]: https://jblevins.org/projects/markdown-mode/rev-2-0
1060 ;; [Version 2.1]: https://jblevins.org/projects/markdown-mode/rev-2-1
1061 ;; [Version 2.2]: https://jblevins.org/projects/markdown-mode/rev-2-2
1062 ;; [Version 2.3]: https://jblevins.org/projects/markdown-mode/rev-2-3
1065 ;;; Code:
1067 (require 'easymenu)
1068 (require 'outline)
1069 (require 'thingatpt)
1070 (require 'cl-lib)
1071 (require 'url-parse)
1072 (require 'button)
1073 (require 'color)
1074 (require 'rx)
1076 (defvar jit-lock-start)
1077 (defvar jit-lock-end)
1078 (defvar flyspell-generic-check-word-predicate)
1080 (declare-function eww-open-file "eww")
1081 (declare-function url-path-and-query "url-parse")
1084 ;;; Constants =================================================================
1086 (defconst markdown-mode-version "2.4-dev"
1087 "Markdown mode version number.")
1089 (defconst markdown-output-buffer-name "*markdown-output*"
1090 "Name of temporary buffer for markdown command output.")
1092 (defconst markdown-sub-superscript-display
1093 '(((raise -0.3) (height 0.7)) ; subscript
1094 ((raise 0.3) (height 0.7))) ; superscript
1095 "Parameters for sub- and superscript formatting.")
1098 ;;; Global Variables ==========================================================
1100 (defvar markdown-reference-label-history nil
1101 "History of used reference labels.")
1103 (defvar markdown-live-preview-mode nil
1104 "Sentinel variable for command `markdown-live-preview-mode'.")
1106 (defvar markdown-gfm-language-history nil
1107 "History list of languages used in the current buffer in GFM code blocks.")
1110 ;;; Customizable Variables ====================================================
1112 (defvar markdown-mode-hook nil
1113 "Hook run when entering Markdown mode.")
1115 (defvar markdown-before-export-hook nil
1116 "Hook run before running Markdown to export XHTML output.
1117 The hook may modify the buffer, which will be restored to it's
1118 original state after exporting is complete.")
1120 (defvar markdown-after-export-hook nil
1121 "Hook run after XHTML output has been saved.
1122 Any changes to the output buffer made by this hook will be saved.")
1124 (defgroup markdown nil
1125 "Major mode for editing text files in Markdown format."
1126 :prefix "markdown-"
1127 :group 'wp
1128 :link '(url-link "https://jblevins.org/projects/markdown-mode/"))
1130 (defcustom markdown-command "markdown"
1131 "Command to run markdown."
1132 :group 'markdown
1133 :type '(choice (string :tag "Shell command") function))
1135 (defcustom markdown-command-needs-filename nil
1136 "Set to non-nil if `markdown-command' does not accept input from stdin.
1137 Instead, it will be passed a filename as the final command line
1138 option. As a result, you will only be able to run Markdown from
1139 buffers which are visiting a file."
1140 :group 'markdown
1141 :type 'boolean)
1143 (defcustom markdown-open-command nil
1144 "Command used for opening Markdown files directly.
1145 For example, a standalone Markdown previewer. This command will
1146 be called with a single argument: the filename of the current
1147 buffer. It can also be a function, which will be called without
1148 arguments."
1149 :group 'markdown
1150 :type '(choice file function (const :tag "None" nil)))
1152 (defcustom markdown-hr-strings
1153 '("-------------------------------------------------------------------------------"
1154 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
1155 "---------------------------------------"
1156 "* * * * * * * * * * * * * * * * * * * *"
1157 "---------"
1158 "* * * * *")
1159 "Strings to use when inserting horizontal rules.
1160 The first string in the list will be the default when inserting a
1161 horizontal rule. Strings should be listed in decreasing order of
1162 prominence (as in headings from level one to six) for use with
1163 promotion and demotion functions."
1164 :group 'markdown
1165 :type '(repeat string))
1167 (defcustom markdown-bold-underscore nil
1168 "Use two underscores when inserting bold text instead of two asterisks."
1169 :group 'markdown
1170 :type 'boolean)
1172 (defcustom markdown-italic-underscore nil
1173 "Use underscores when inserting italic text instead of asterisks."
1174 :group 'markdown
1175 :type 'boolean)
1177 (defcustom markdown-marginalize-headers nil
1178 "When non-nil, put opening atx header markup in a left margin.
1180 This setting goes well with `markdown-asymmetric-header'. But
1181 sadly it conflicts with `linum-mode' since they both use the
1182 same margin."
1183 :group 'markdown
1184 :type 'boolean
1185 :safe 'booleanp
1186 :package-version '(markdown-mode . "2.4"))
1188 (defcustom markdown-marginalize-headers-margin-width 6
1189 "Character width of margin used for marginalized headers.
1190 The default value is based on there being six heading levels
1191 defined by Markdown and HTML. Increasing this produces extra
1192 whitespace on the left. Decreasing it may be preferred when
1193 fewer than six nested heading levels are used."
1194 :group 'markdown
1195 :type 'natnump
1196 :safe 'natnump
1197 :package-version '(markdown-mode . "2.4"))
1199 (defcustom markdown-asymmetric-header nil
1200 "Determines if atx header style will be asymmetric.
1201 Set to a non-nil value to use asymmetric header styling, placing
1202 header markup only at the beginning of the line. By default,
1203 balanced markup will be inserted at the beginning and end of the
1204 line around the header title."
1205 :group 'markdown
1206 :type 'boolean)
1208 (defcustom markdown-indent-function 'markdown-indent-line
1209 "Function to use to indent."
1210 :group 'markdown
1211 :type 'function)
1213 (defcustom markdown-indent-on-enter t
1214 "Determines indentation behavior when pressing \\[newline].
1215 Possible settings are nil, t, and 'indent-and-new-item.
1217 When non-nil, pressing \\[newline] will call `newline-and-indent'
1218 to indent the following line according to the context using
1219 `markdown-indent-function'. In this case, note that
1220 \\[electric-newline-and-maybe-indent] can still be used to insert
1221 a newline without indentation.
1223 When set to 'indent-and-new-item and the point is in a list item
1224 when \\[newline] is pressed, the list will be continued on the next
1225 line, where a new item will be inserted.
1227 When set to nil, simply call `newline' as usual. In this case,
1228 you can still indent lines using \\[markdown-cycle] and continue
1229 lists with \\[markdown-insert-list-item].
1231 Note that this assumes the variable `electric-indent-mode' is
1232 non-nil (enabled). When it is *disabled*, the behavior of
1233 \\[newline] and `\\[electric-newline-and-maybe-indent]' are
1234 reversed."
1235 :group 'markdown
1236 :type '(choice (const :tag "Don't automatically indent" nil)
1237 (const :tag "Automatically indent" t)
1238 (const :tag "Automatically indent and insert new list items" indent-and-new-item)))
1240 (defcustom markdown-enable-wiki-links nil
1241 "Syntax highlighting for wiki links.
1242 Set this to a non-nil value to turn on wiki link support by default.
1243 Support can be toggled later using the `markdown-toggle-wiki-links'
1244 function or \\[markdown-toggle-wiki-links]."
1245 :group 'markdown
1246 :type 'boolean
1247 :safe 'booleanp
1248 :package-version '(markdown-mode . "2.2"))
1250 (defcustom markdown-wiki-link-alias-first t
1251 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
1252 Otherwise, they will be treated as [[PageName|alias text]]."
1253 :group 'markdown
1254 :type 'boolean
1255 :safe 'booleanp)
1257 (defcustom markdown-wiki-link-search-subdirectories nil
1258 "When non-nil, search for wiki link targets in subdirectories.
1259 This is the default search behavior for GitHub and is
1260 automatically set to t in `gfm-mode'."
1261 :group 'markdown
1262 :type 'boolean
1263 :safe 'booleanp
1264 :package-version '(markdown-mode . "2.2"))
1266 (defcustom markdown-wiki-link-search-parent-directories nil
1267 "When non-nil, search for wiki link targets in parent directories.
1268 This is the default search behavior of Ikiwiki."
1269 :group 'markdown
1270 :type 'boolean
1271 :safe 'booleanp
1272 :package-version '(markdown-mode . "2.2"))
1274 (defcustom markdown-wiki-link-fontify-missing nil
1275 "When non-nil, change wiki link face according to existence of target files.
1276 This is expensive because it requires checking for the file each time the buffer
1277 changes or the user switches windows. It is disabled by default because it may
1278 cause lag when typing on slower machines."
1279 :group 'markdown
1280 :type 'boolean
1281 :safe 'booleanp
1282 :package-version '(markdown-mode . "2.2"))
1284 (defcustom markdown-uri-types
1285 '("acap" "cid" "data" "dav" "fax" "file" "ftp"
1286 "gopher" "http" "https" "imap" "ldap" "mailto"
1287 "mid" "message" "modem" "news" "nfs" "nntp"
1288 "pop" "prospero" "rtsp" "service" "sip" "tel"
1289 "telnet" "tip" "urn" "vemmi" "wais")
1290 "Link types for syntax highlighting of URIs."
1291 :group 'markdown
1292 :type '(repeat (string :tag "URI scheme")))
1294 (defcustom markdown-url-compose-char
1295 '(?∞ ?… ?⋯ ?# ?★ ?⚓)
1296 "Placeholder character for hidden URLs.
1297 This may be a single character or a list of characters. In case
1298 of a list, the first one that satisfies `char-displayable-p' will
1299 be used."
1300 :type '(choice
1301 (character :tag "Single URL replacement character")
1302 (repeat :tag "List of possible URL replacement characters"
1303 character))
1304 :package-version '(markdown-mode . "2.3"))
1306 (defcustom markdown-blockquote-display-char
1307 '("▌" "┃" ">")
1308 "String to display when hiding blockquote markup.
1309 This may be a single string or a list of string. In case of a
1310 list, the first one that satisfies `char-displayable-p' will be
1311 used."
1312 :type 'string
1313 :type '(choice
1314 (string :tag "Single blockquote display string")
1315 (repeat :tag "List of possible blockquote display strings" string))
1316 :package-version '(markdown-mode . "2.3"))
1318 (defcustom markdown-hr-display-char
1319 '(?─ ?━ ?-)
1320 "Character for hiding horizontal rule markup.
1321 This may be a single character or a list of characters. In case
1322 of a list, the first one that satisfies `char-displayable-p' will
1323 be used."
1324 :group 'markdown
1325 :type '(choice
1326 (character :tag "Single HR display character")
1327 (repeat :tag "List of possible HR display characters" character))
1328 :package-version '(markdown-mode . "2.3"))
1330 (defcustom markdown-definition-display-char
1331 '(?⁘ ?⁙ ?≡ ?⌑ ?◊ ?:)
1332 "Character for replacing definition list markup.
1333 This may be a single character or a list of characters. In case
1334 of a list, the first one that satisfies `char-displayable-p' will
1335 be used."
1336 :type '(choice
1337 (character :tag "Single definition list character")
1338 (repeat :tag "List of possible definition list characters" character))
1339 :package-version '(markdown-mode . "2.3"))
1341 (defcustom markdown-enable-math nil
1342 "Syntax highlighting for inline LaTeX and itex expressions.
1343 Set this to a non-nil value to turn on math support by default.
1344 Math support can be enabled, disabled, or toggled later using
1345 `markdown-toggle-math' or \\[markdown-toggle-math]."
1346 :group 'markdown
1347 :type 'boolean
1348 :safe 'booleanp)
1349 (make-variable-buffer-local 'markdown-enable-math)
1351 (defcustom markdown-enable-html t
1352 "Enable font-lock support for HTML tags and attributes."
1353 :group 'markdown
1354 :type 'boolean
1355 :safe 'booleanp
1356 :package-version '(markdown-mode . "2.4"))
1358 (defcustom markdown-css-paths nil
1359 "URL of CSS file to link to in the output XHTML."
1360 :group 'markdown
1361 :type '(repeat (string :tag "CSS File Path")))
1363 (defcustom markdown-content-type ""
1364 "Content type string for the http-equiv header in XHTML output.
1365 When set to a non-empty string, insert the http-equiv attribute.
1366 Otherwise, this attribute is omitted."
1367 :group 'markdown
1368 :type 'string)
1370 (defcustom markdown-coding-system nil
1371 "Character set string for the http-equiv header in XHTML output.
1372 Defaults to `buffer-file-coding-system' (and falling back to
1373 `iso-8859-1' when not available). Common settings are `utf-8'
1374 and `iso-latin-1'. Use `list-coding-systems' for more choices."
1375 :group 'markdown
1376 :type 'coding-system)
1378 (defcustom markdown-export-kill-buffer t
1379 "Kill output buffer after HTML export.
1380 When non-nil, kill the HTML output buffer after
1381 exporting with `markdown-export'."
1382 :group 'markdown
1383 :type 'boolean
1384 :safe 'booleanp
1385 :package-version '(markdown-mode . "2.4"))
1387 (defcustom markdown-xhtml-header-content ""
1388 "Additional content to include in the XHTML <head> block."
1389 :group 'markdown
1390 :type 'string)
1392 (defcustom markdown-xhtml-standalone-regexp
1393 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
1394 "Regexp indicating whether `markdown-command' output is standalone XHTML."
1395 :group 'markdown
1396 :type 'regexp)
1398 (defcustom markdown-link-space-sub-char "_"
1399 "Character to use instead of spaces when mapping wiki links to filenames."
1400 :group 'markdown
1401 :type 'string)
1403 (defcustom markdown-reference-location 'header
1404 "Position where new reference definitions are inserted in the document."
1405 :group 'markdown
1406 :type '(choice (const :tag "At the end of the document" end)
1407 (const :tag "Immediately after the current block" immediately)
1408 (const :tag "At the end of the subtree" subtree)
1409 (const :tag "Before next header" header)))
1411 (defcustom markdown-footnote-location 'end
1412 "Position where new footnotes are inserted in the document."
1413 :group 'markdown
1414 :type '(choice (const :tag "At the end of the document" end)
1415 (const :tag "Immediately after the current block" immediately)
1416 (const :tag "At the end of the subtree" subtree)
1417 (const :tag "Before next header" header)))
1419 (defcustom markdown-footnote-display '((raise 0.2) (height 0.8))
1420 "Display specification for footnote markers and inline footnotes.
1421 By default, footnote text is reduced in size and raised. Set to
1422 nil to disable this."
1423 :group 'markdown
1424 :type '(choice (sexp :tag "Display specification")
1425 (const :tag "Don't set display property" nil))
1426 :package-version '(markdown-mode . "2.4"))
1428 (defcustom markdown-sub-superscript-display
1429 '(((raise -0.3) (height 0.7)) . ((raise 0.3) (height 0.7)))
1430 "Display specification for subscript and superscripts.
1431 The car is used for subscript, the cdr is used for superscripts."
1432 :group 'markdown
1433 :type '(cons (choice (sexp :tag "Subscript form")
1434 (const :tag "No lowering" nil))
1435 (choice (sexp :tag "Superscript form")
1436 (const :tag "No raising" nil)))
1437 :package-version '(markdown-mode . "2.4"))
1439 (defcustom markdown-unordered-list-item-prefix " * "
1440 "String inserted before unordered list items."
1441 :group 'markdown
1442 :type 'string)
1444 (defcustom markdown-nested-imenu-heading-index t
1445 "Use nested or flat imenu heading index.
1446 A nested index may provide more natural browsing from the menu,
1447 but a flat list may allow for faster keyboard navigation via tab
1448 completion."
1449 :group 'markdown
1450 :type 'boolean
1451 :safe 'booleanp
1452 :package-version '(markdown-mode . "2.2"))
1454 (defcustom markdown-make-gfm-checkboxes-buttons t
1455 "When non-nil, make GFM checkboxes into buttons."
1456 :group 'markdown
1457 :type 'boolean)
1459 (defcustom markdown-use-pandoc-style-yaml-metadata nil
1460 "When non-nil, allow YAML metadata anywhere in the document."
1461 :group 'markdown
1462 :type 'boolean)
1464 (defcustom markdown-split-window-direction 'any
1465 "Preference for splitting windows for static and live preview.
1466 The default value is 'any, which instructs Emacs to use
1467 `split-window-sensibly' to automatically choose how to split
1468 windows based on the values of `split-width-threshold' and
1469 `split-height-threshold' and the available windows. To force
1470 vertically split (left and right) windows, set this to 'vertical
1471 or 'right. To force horizontally split (top and bottom) windows,
1472 set this to 'horizontal or 'below."
1473 :group 'markdown
1474 :type '(choice (const :tag "Automatic" any)
1475 (const :tag "Right (vertical)" right)
1476 (const :tag "Below (horizontal)" below))
1477 :package-version '(markdown-mode . "2.2"))
1479 (defcustom markdown-live-preview-window-function
1480 'markdown-live-preview-window-eww
1481 "Function to display preview of Markdown output within Emacs.
1482 Function must update the buffer containing the preview and return
1483 the buffer."
1484 :group 'markdown
1485 :type 'function)
1487 (defcustom markdown-live-preview-delete-export 'delete-on-destroy
1488 "Delete exported HTML file when using `markdown-live-preview-export'.
1489 If set to 'delete-on-export, delete on every export. When set to
1490 'delete-on-destroy delete when quitting from command
1491 `markdown-live-preview-mode'. Never delete if set to nil."
1492 :group 'markdown
1493 :type '(choice
1494 (const :tag "Delete on every export" delete-on-export)
1495 (const :tag "Delete when quitting live preview" delete-on-destroy)
1496 (const :tag "Never delete" nil)))
1498 (defcustom markdown-list-indent-width 4
1499 "Depth of indentation for markdown lists.
1500 Used in `markdown-demote-list-item' and
1501 `markdown-promote-list-item'."
1502 :group 'markdown
1503 :type 'integer)
1505 (defcustom markdown-enable-prefix-prompts t
1506 "Display prompts for certain prefix commands.
1507 Set to nil to disable these prompts."
1508 :group 'markdown
1509 :type 'boolean
1510 :safe 'booleanp
1511 :package-version '(markdown-mode . "2.3"))
1513 (defcustom markdown-gfm-additional-languages nil
1514 "Extra languages made available when inserting GFM code blocks.
1515 Language strings must have be trimmed of whitespace and not
1516 contain any curly braces. They may be of arbitrary
1517 capitalization, though."
1518 :group 'markdown
1519 :type '(repeat (string :validate markdown-validate-language-string)))
1521 (defcustom markdown-gfm-use-electric-backquote t
1522 "Use `markdown-electric-backquote' when backquote is hit three times."
1523 :group 'markdown
1524 :type 'boolean)
1526 (defcustom markdown-gfm-downcase-languages t
1527 "If non-nil, downcase suggested languages.
1528 This applies to insertions done with
1529 `markdown-electric-backquote'."
1530 :group 'markdown
1531 :type 'boolean)
1533 (defcustom markdown-edit-code-block-default-mode 'normal-mode
1534 "Default mode to use for editing code blocks.
1535 This mode is used when automatic detection fails, such as for GFM
1536 code blocks with no language specified."
1537 :group 'markdown
1538 :type 'symbol
1539 :package-version '(markdown-mode . "2.4"))
1541 (defcustom markdown-gfm-uppercase-checkbox nil
1542 "If non-nil, use [X] for completed checkboxes, [x] otherwise."
1543 :group 'markdown
1544 :type 'boolean
1545 :safe 'booleanp)
1547 (defcustom markdown-hide-urls nil
1548 "Hide URLs of inline links and reference tags of reference links.
1549 Such URLs will be replaced by a single customizable
1550 character, defined by `markdown-url-compose-char', but are still part
1551 of the buffer. Links can be edited interactively with
1552 \\[markdown-insert-link] or, for example, by deleting the final
1553 parenthesis to remove the invisibility property. You can also
1554 hover your mouse pointer over the link text to see the URL.
1555 Set this to a non-nil value to turn this feature on by default.
1556 You can interactively set the value of this variable by calling
1557 `markdown-toggle-url-hiding', pressing \\[markdown-toggle-url-hiding],
1558 or from the menu Markdown > Links & Images menu."
1559 :group 'markdown
1560 :type 'boolean
1561 :safe 'booleanp
1562 :package-version '(markdown-mode . "2.3"))
1563 (make-variable-buffer-local 'markdown-hide-urls)
1565 (defcustom markdown-translate-filename-function #'identity
1566 "Function to use to translate filenames when following links.
1567 \\<markdown-mode-map>\\[markdown-follow-thing-at-point] and \\[markdown-follow-link-at-point]
1568 call this function with the filename as only argument whenever
1569 they encounter a filename (instead of a URL) to be visited and
1570 use its return value instead of the filename in the link. For
1571 example, if absolute filenames are actually relative to a server
1572 root directory, you can set
1573 `markdown-translate-filename-function' to a function that
1574 prepends the root directory to the given filename."
1575 :group 'markdown
1576 :type 'function
1577 :risky t
1578 :package-version '(markdown-mode . "2.4"))
1580 (defcustom markdown-max-image-size nil
1581 "Maximum width and height for displayed inline images.
1582 This variable may be nil or a cons cell (MAX-WIDTH . MAX-HEIGHT).
1583 When nil, use the actual size. Otherwise, use ImageMagick to
1584 resize larger images to be of the given maximum dimensions. This
1585 requires Emacs to be built with ImageMagick support."
1586 :group 'markdown
1587 :package-version '(markdown-mode . "2.4")
1588 :type '(choice
1589 (const :tag "Use actual image width" nil)
1590 (cons (choice (sexp :tag "Maximum width in pixels")
1591 (const :tag "No maximum width" nil))
1592 (choice (sexp :tag "Maximum height in pixels")
1593 (const :tag "No maximum height" nil)))))
1596 ;;; Regular Expressions =======================================================
1598 (defconst markdown-regex-comment-start
1599 "<!--"
1600 "Regular expression matches HTML comment opening.")
1602 (defconst markdown-regex-comment-end
1603 "--[ \t]*>"
1604 "Regular expression matches HTML comment closing.")
1606 (defconst markdown-regex-link-inline
1607 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)\\((\\)\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?\\()\\)"
1608 "Regular expression for a [text](file) or an image link ![text](file).
1609 Group 1 matches the leading exclamation point (optional).
1610 Group 2 matches the opening square bracket.
1611 Group 3 matches the text inside the square brackets.
1612 Group 4 matches the closing square bracket.
1613 Group 5 matches the opening parenthesis.
1614 Group 6 matches the URL.
1615 Group 7 matches the title (optional).
1616 Group 8 matches the closing parenthesis.")
1618 (defconst markdown-regex-link-reference
1619 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)[ ]?\\(\\[\\)\\([^]]*?\\)\\(\\]\\)"
1620 "Regular expression for a reference link [text][id].
1621 Group 1 matches the leading exclamation point (optional).
1622 Group 2 matches the opening square bracket for the link text.
1623 Group 3 matches the text inside the square brackets.
1624 Group 4 matches the closing square bracket for the link text.
1625 Group 5 matches the opening square bracket for the reference label.
1626 Group 6 matches the reference label.
1627 Group 7 matches the closing square bracket for the reference label.")
1629 (defconst markdown-regex-reference-definition
1630 "^ \\{0,3\\}\\(\\[\\)\\([^]\n]+?\\)\\(\\]\\)\\(:\\)\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
1631 "Regular expression for a reference definition.
1632 Group 1 matches the opening square bracket.
1633 Group 2 matches the reference label.
1634 Group 3 matches the closing square bracket.
1635 Group 4 matches the colon.
1636 Group 5 matches the URL.
1637 Group 6 matches the title attribute (optional).")
1639 (defconst markdown-regex-footnote
1640 "\\(\\[\\^\\)\\(.+?\\)\\(\\]\\)"
1641 "Regular expression for a footnote marker [^fn].
1642 Group 1 matches the opening square bracket and carat.
1643 Group 2 matches only the label, without the surrounding markup.
1644 Group 3 matches the closing square bracket.")
1646 (defconst markdown-regex-header
1647 "^\\(?:\\([^\r\n\t -].*\\)\n\\(?:\\(=+\\)\\|\\(-+\\)\\)\\|\\(#+[ \t]+\\)\\(.*?\\)\\([ \t]*#*\\)\\)$"
1648 "Regexp identifying Markdown headings.
1649 Group 1 matches the text of a setext heading.
1650 Group 2 matches the underline of a level-1 setext heading.
1651 Group 3 matches the underline of a level-2 setext heading.
1652 Group 4 matches the opening hash marks of an atx heading and whitespace.
1653 Group 5 matches the text, without surrounding whitespace, of an atx heading.
1654 Group 6 matches the closing whitespace and hash marks of an atx heading.")
1656 (defconst markdown-regex-header-setext
1657 "^\\([^\r\n\t -].*\\)\n\\(=+\\|-+\\)$"
1658 "Regular expression for generic setext-style (underline) headers.")
1660 (defconst markdown-regex-header-atx
1661 "^\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1662 "Regular expression for generic atx-style (hash mark) headers.")
1664 (defconst markdown-regex-hr
1665 (rx line-start
1666 (group (or (and (repeat 3 (and "*" (? " "))) (* (any "* ")))
1667 (and (repeat 3 (and "-" (? " "))) (* (any "- ")))
1668 (and (repeat 3 (and "_" (? " "))) (* (any "_ ")))))
1669 line-end)
1670 "Regular expression for matching Markdown horizontal rules.")
1672 (defconst markdown-regex-code
1673 "\\(?:\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(?:.\\|\n[^\n]\\)*?[^`]\\)\\(\\2\\)\\)\\(?:[^`]\\|\\'\\)"
1674 "Regular expression for matching inline code fragments.
1676 Group 1 matches the entire code fragment including the backquotes.
1677 Group 2 matches the opening backquotes.
1678 Group 3 matches the code fragment itself, without backquotes.
1679 Group 4 matches the closing backquotes.
1681 The leading, unnumbered group ensures that the leading backquote
1682 character is not escaped.
1683 The last group, also unnumbered, requires that the character
1684 following the code fragment is not a backquote.
1685 Note that \\(?:.\\|\n[^\n]\\) matches any character, including newlines,
1686 but not two newlines in a row.")
1688 (defconst markdown-regex-kbd
1689 "\\(<kbd>\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(</kbd>\\)"
1690 "Regular expression for matching <kbd> tags.
1691 Groups 1 and 3 match the opening and closing tags.
1692 Group 2 matches the key sequence.")
1694 (defconst markdown-regex-gfm-code-block-open
1695 "^[[:blank:]]*\\(```\\)\\([[:blank:]]*{?[[:blank:]]*\\)\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$"
1696 "Regular expression matching opening of GFM code blocks.
1697 Group 1 matches the opening three backquotes and any following whitespace.
1698 Group 2 matches the opening brace (optional) and surrounding whitespace.
1699 Group 3 matches the language identifier (optional).
1700 Group 4 matches the info string (optional).
1701 Group 5 matches the closing brace (optional), whitespace, and newline.
1702 Groups need to agree with `markdown-regex-tilde-fence-begin'.")
1704 (defconst markdown-regex-gfm-code-block-close
1705 "^[[:blank:]]*\\(```\\)\\(\\s *?\\)$"
1706 "Regular expression matching closing of GFM code blocks.
1707 Group 1 matches the closing three backquotes.
1708 Group 2 matches any whitespace and the final newline.")
1710 (defconst markdown-regex-pre
1711 "^\\( \\|\t\\).*$"
1712 "Regular expression for matching preformatted text sections.")
1714 (defconst markdown-regex-list
1715 (rx line-start
1716 ;; 1. Leading whitespace
1717 (group (* blank))
1718 ;; 2. List marker: a numeral, bullet, or colon
1719 (group (or (and (+ (any "0-9#")) ".")
1720 (any "*+:-")))
1721 ;; 3. Trailing whitespace
1722 (group (+ blank))
1723 ;; 4. Optional checkbox for GFM task list items
1724 (opt (group (and "[" (any " xX") "]" (* blank)))))
1725 "Regular expression for matching list items.")
1727 (defconst markdown-regex-bold
1728 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1729 "Regular expression for matching bold text.
1730 Group 1 matches the character before the opening asterisk or
1731 underscore, if any, ensuring that it is not a backslash escape.
1732 Group 2 matches the entire expression, including delimiters.
1733 Groups 3 and 5 matches the opening and closing delimiters.
1734 Group 4 matches the text inside the delimiters.")
1736 (defconst markdown-regex-italic
1737 "\\(?:^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t*]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1738 "Regular expression for matching italic text.
1739 The leading unnumbered matches the character before the opening
1740 asterisk or underscore, if any, ensuring that it is not a
1741 backslash escape.
1742 Group 1 matches the entire expression, including delimiters.
1743 Groups 2 and 4 matches the opening and closing delimiters.
1744 Group 3 matches the text inside the delimiters.")
1746 (defconst markdown-regex-strike-through
1747 "\\(^\\|[^\\]\\)\\(\\(~~\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(~~\\)\\)"
1748 "Regular expression for matching strike-through text.
1749 Group 1 matches the character before the opening tilde, if any,
1750 ensuring that it is not a backslash escape.
1751 Group 2 matches the entire expression, including delimiters.
1752 Groups 3 and 5 matches the opening and closing delimiters.
1753 Group 4 matches the text inside the delimiters.")
1755 (defconst markdown-regex-gfm-italic
1756 "\\(?:^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\2\\|[^ ]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1757 "Regular expression for matching italic text in GitHub Flavored Markdown.
1758 Underscores in words are not treated as special.
1759 Group 1 matches the entire expression, including delimiters.
1760 Groups 2 and 4 matches the opening and closing delimiters.
1761 Group 3 matches the text inside the delimiters.")
1763 (defconst markdown-regex-blockquote
1764 "^[ \t]*\\([A-Z]?>\\)\\([ \t]*\\)\\(.*\\)$"
1765 "Regular expression for matching blockquote lines.
1766 Also accounts for a potential capital letter preceding the angle
1767 bracket, for use with Leanpub blocks (asides, warnings, info
1768 blocks, etc.).
1769 Group 1 matches the leading angle bracket.
1770 Group 2 matches the separating whitespace.
1771 Group 3 matches the text.")
1773 (defconst markdown-regex-line-break
1774 "[^ \n\t][ \t]*\\( \\)$"
1775 "Regular expression for matching line breaks.")
1777 (defconst markdown-regex-wiki-link
1778 "\\(?:^\\|[^\\]\\)\\(\\(\\[\\[\\)\\([^]|]+\\)\\(?:\\(|\\)\\([^]]+\\)\\)?\\(\\]\\]\\)\\)"
1779 "Regular expression for matching wiki links.
1780 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1781 wiki links of the form [[PageName|link text]].
1782 The meanings of the first and second components depend
1783 on the value of `markdown-wiki-link-alias-first'.
1785 Group 1 matches the entire link.
1786 Group 2 matches the opening square brackets.
1787 Group 3 matches the first component of the wiki link.
1788 Group 4 matches the pipe separator, when present.
1789 Group 5 matches the second component of the wiki link, when present.
1790 Group 6 matches the closing square brackets.")
1792 (defconst markdown-regex-uri
1793 (concat "\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+\\)")
1794 "Regular expression for matching inline URIs.")
1796 (defconst markdown-regex-angle-uri
1797 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1798 "Regular expression for matching inline URIs in angle brackets.")
1800 (defconst markdown-regex-email
1801 "<\\(\\(?:\\sw\\|\\s_\\|\\s.\\)+@\\(?:\\sw\\|\\s_\\|\\s.\\)+\\)>"
1802 "Regular expression for matching inline email addresses.")
1804 (defsubst markdown-make-regex-link-generic ()
1805 "Make regular expression for matching any recognized link."
1806 (concat "\\(?:" markdown-regex-link-inline
1807 (when markdown-enable-wiki-links
1808 (concat "\\|" markdown-regex-wiki-link))
1809 "\\|" markdown-regex-link-reference
1810 "\\|" markdown-regex-angle-uri "\\)"))
1812 (defconst markdown-regex-gfm-checkbox
1813 " \\(\\[[ xX]\\]\\) "
1814 "Regular expression for matching GFM checkboxes.
1815 Group 1 matches the text to become a button.")
1817 (defconst markdown-regex-blank-line
1818 "^[[:blank:]]*$"
1819 "Regular expression that matches a blank line.")
1821 (defconst markdown-regex-block-separator
1822 "\n[\n\t\f ]*\n"
1823 "Regular expression for matching block boundaries.")
1825 (defconst markdown-regex-block-separator-noindent
1826 (concat "\\(\\`\\|\\(" markdown-regex-block-separator "\\)[^\n\t\f ]\\)")
1827 "Regexp for block separators before lines with no indentation.")
1829 (defconst markdown-regex-math-inline-single
1830 "\\(?:^\\|[^\\]\\)\\(\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\)"
1831 "Regular expression for itex $..$ math mode expressions.
1832 Groups 1 and 3 match the opening and closing dollar signs.
1833 Group 2 matches the mathematical expression contained within.")
1835 (defconst markdown-regex-math-inline-double
1836 "\\(?:^\\|[^\\]\\)\\(\\$\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\$\\)"
1837 "Regular expression for itex $$..$$ math mode expressions.
1838 Groups 1 and 3 match opening and closing dollar signs.
1839 Group 2 matches the mathematical expression contained within.")
1841 (defconst markdown-regex-math-display
1842 (rx line-start (* blank)
1843 (group (group (repeat 1 2 "\\")) "[")
1844 (group (*? anything))
1845 (group (backref 2) "]")
1846 line-end)
1847 "Regular expression for \[..\] or \\[..\\] display math.
1848 Groups 1 and 4 match the opening and closing markup.
1849 Group 3 matches the mathematical expression contained within.
1850 Group 2 matches the opening slashes, and is used internally to
1851 match the closing slashes.")
1853 (defsubst markdown-make-tilde-fence-regex (num-tildes &optional end-of-line)
1854 "Return regexp matching a tilde code fence at least NUM-TILDES long.
1855 END-OF-LINE is the regexp construct to indicate end of line; $ if
1856 missing."
1857 (format "%s%d%s%s" "^[[:blank:]]*\\([~]\\{" num-tildes ",\\}\\)"
1858 (or end-of-line "$")))
1860 (defconst markdown-regex-tilde-fence-begin
1861 (markdown-make-tilde-fence-regex
1862 3 "\\([[:blank:]]*{?\\)[[:blank:]]*\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$")
1863 "Regular expression for matching tilde-fenced code blocks.
1864 Group 1 matches the opening tildes.
1865 Group 2 matches (optional) opening brace and surrounding whitespace.
1866 Group 3 matches the language identifier (optional).
1867 Group 4 matches the info string (optional).
1868 Group 5 matches the closing brace (optional) and any surrounding whitespace.
1869 Groups need to agree with `markdown-regex-gfm-code-block-open'.")
1871 (defconst markdown-regex-declarative-metadata
1872 "^\\([[:alpha:]][[:alpha:] _-]*?\\)\\([:=][ \t]*\\)\\(.*\\)$"
1873 "Regular expression for matching declarative metadata statements.
1874 This matches MultiMarkdown metadata as well as YAML and TOML
1875 assignments such as the following:
1877 variable: value
1881 variable = value")
1883 (defconst markdown-regex-pandoc-metadata
1884 "^\\(%\\)\\([ \t]*\\)\\(.*\\(?:\n[ \t]+.*\\)*\\)"
1885 "Regular expression for matching Pandoc metadata.")
1887 (defconst markdown-regex-yaml-metadata-border
1888 "\\(-\\{3\\}\\)$"
1889 "Regular expression for matching YAML metadata.")
1891 (defconst markdown-regex-yaml-pandoc-metadata-end-border
1892 "^\\(\\.\\{3\\}\\|\\-\\{3\\}\\)$"
1893 "Regular expression for matching YAML metadata end borders.")
1895 (defsubst markdown-get-yaml-metadata-start-border ()
1896 "Return YAML metadata start border depending upon whether Pandoc is used."
1897 (concat
1898 (if markdown-use-pandoc-style-yaml-metadata "^" "\\`")
1899 markdown-regex-yaml-metadata-border))
1901 (defsubst markdown-get-yaml-metadata-end-border (_)
1902 "Return YAML metadata end border depending upon whether Pandoc is used."
1903 (if markdown-use-pandoc-style-yaml-metadata
1904 markdown-regex-yaml-pandoc-metadata-end-border
1905 markdown-regex-yaml-metadata-border))
1907 (defconst markdown-regex-inline-attributes
1908 "[ \t]*\\({:?\\)[ \t]*\\(\\(#[[:alpha:]_.:-]+\\|\\.[[:alpha:]_.:-]+\\|\\w+=['\"]?[^\n'\"]*['\"]?\\),?[ \t]*\\)+\\(}\\)[ \t]*$"
1909 "Regular expression for matching inline identifiers or attribute lists.
1910 Compatible with Pandoc, Python Markdown, PHP Markdown Extra, and Leanpub.")
1912 (defconst markdown-regex-leanpub-sections
1913 (concat
1914 "^\\({\\)\\("
1915 (regexp-opt '("frontmatter" "mainmatter" "backmatter" "appendix" "pagebreak"))
1916 "\\)\\(}\\)[ \t]*\n")
1917 "Regular expression for Leanpub section markers and related syntax.")
1919 (defconst markdown-regex-sub-superscript
1920 "\\(?:^\\|[^\\~^]\\)\\(\\([~^]\\)\\([[:alnum:]]+\\)\\(\\2\\)\\)"
1921 "The regular expression matching a sub- or superscript.
1922 The leading un-numbered group matches the character before the
1923 opening tilde or carat, if any, ensuring that it is not a
1924 backslash escape, carat, or tilde.
1925 Group 1 matches the entire expression, including markup.
1926 Group 2 matches the opening markup--a tilde or carat.
1927 Group 3 matches the text inside the delimiters.
1928 Group 4 matches the closing markup--a tilde or carat.")
1930 (defconst markdown-regex-include
1931 "^\\(<<\\)\\(?:\\(\\[\\)\\(.*\\)\\(\\]\\)\\)?\\(?:\\((\\)\\(.*\\)\\()\\)\\)?\\(?:\\({\\)\\(.*\\)\\(}\\)\\)?$"
1932 "Regular expression matching common forms of include syntax.
1933 Marked 2, Leanpub, and other processors support some of these forms:
1935 <<[sections/section1.md]
1936 <<(folder/filename)
1937 <<[Code title](folder/filename)
1938 <<{folder/raw_file.html}
1940 Group 1 matches the opening two angle brackets.
1941 Groups 2-4 match the opening square bracket, the text inside,
1942 and the closing square bracket, respectively.
1943 Groups 5-7 match the opening parenthesis, the text inside, and
1944 the closing parenthesis.
1945 Groups 8-10 match the opening brace, the text inside, and the brace.")
1947 (defconst markdown-regex-pandoc-inline-footnote
1948 "\\(\\^\\)\\(\\[\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(\\]\\)"
1949 "Regular expression for Pandoc inline footnote^[footnote text].
1950 Group 1 matches the opening caret.
1951 Group 2 matches the opening square bracket.
1952 Group 3 matches the footnote text, without the surrounding markup.
1953 Group 4 matches the closing square bracket.")
1955 (defconst markdown-regex-html-attr
1956 "\\(\\<[[:alpha:]:-]+\\>\\)\\(\\s-*\\(=\\)\\s-*\\(\".*?\"\\|'.*?'\\|[^'\">[:space:]]+\\)?\\)?"
1957 "Regular expression for matching HTML attributes and values.
1958 Group 1 matches the attribute name.
1959 Group 2 matches the following whitespace, equals sign, and value, if any.
1960 Group 3 matches the equals sign, if any.
1961 Group 4 matches single-, double-, or un-quoted attribute values.")
1963 (defconst markdown-regex-html-tag
1964 (concat "\\(</?\\)\\(\\w+\\)\\(\\(\\s-+" markdown-regex-html-attr
1965 "\\)+\\s-*\\|\\s-*\\)\\(/?>\\)")
1966 "Regular expression for matching HTML tags.
1967 Groups 1 and 9 match the beginning and ending angle brackets and slashes.
1968 Group 2 matches the tag name.
1969 Group 3 matches all attributes and whitespace following the tag name.")
1971 (defconst markdown-regex-html-entity
1972 "\\(&#?[[:alnum:]]+;\\)"
1973 "Regular expression for matching HTML entities.")
1976 ;;; Syntax ====================================================================
1978 (defsubst markdown-in-comment-p (&optional pos)
1979 "Return non-nil if POS is in a comment.
1980 If POS is not given, use point instead."
1981 (get-text-property (or pos (point)) 'markdown-comment))
1983 (defun markdown-syntax-propertize-extend-region (start end)
1984 "Extend START to END region to include an entire block of text.
1985 This helps improve syntax analysis for block constructs.
1986 Returns a cons (NEW-START . NEW-END) or nil if no adjustment should be made.
1987 Function is called repeatedly until it returns nil. For details, see
1988 `syntax-propertize-extend-region-functions'."
1989 (save-match-data
1990 (save-excursion
1991 (let* ((new-start (progn (goto-char start)
1992 (skip-chars-forward "\n")
1993 (if (re-search-backward "\n\n" nil t)
1994 (min start (match-end 0))
1995 (point-min))))
1996 (new-end (progn (goto-char end)
1997 (skip-chars-backward "\n")
1998 (if (re-search-forward "\n\n" nil t)
1999 (max end (match-beginning 0))
2000 (point-max))))
2001 (code-match (markdown--code-block-at-pos-no-syntax new-start))
2002 (new-start (or (and code-match (cl-first code-match)) new-start))
2003 (code-match (and (< end (point-max))
2004 (markdown--code-block-at-pos-no-syntax end)))
2005 (new-end (or (and code-match (cl-second code-match)) new-end)))
2006 (unless (and (eq new-start start) (eq new-end end))
2007 (cons new-start (min new-end (point-max))))))))
2009 (defun markdown-font-lock-extend-region-function (start end _)
2010 "Used in `jit-lock-after-change-extend-region-functions'.
2011 Delegates to `markdown-syntax-propertize-extend-region'. START
2012 and END are the previous region to refontify."
2013 (let ((res (markdown-syntax-propertize-extend-region start end)))
2014 (when res
2015 ;; syntax-propertize-function is not called when character at
2016 ;; (point-max) is deleted, but font-lock-extend-region-functions
2017 ;; are called. Force a syntax property update in that case.
2018 (when (= end (point-max))
2019 ;; This function is called in a buffer modification hook.
2020 ;; `markdown-syntax-propertize' doesn't save the match data,
2021 ;; so we have to do it here.
2022 (save-match-data
2023 (markdown-syntax-propertize (car res) (cdr res))))
2024 (setq jit-lock-start (car res)
2025 jit-lock-end (cdr res)))))
2027 (defun markdown--cur-list-item-bounds ()
2028 "Return a list describing the list item at point.
2029 Assumes that match data is set for `markdown-regex-list'. See the
2030 documentation for `markdown-cur-list-item-bounds' for the format of
2031 the returned list."
2032 (save-excursion
2033 (let* ((begin (match-beginning 0))
2034 (indent (length (match-string-no-properties 1)))
2035 (nonlist-indent (- (match-end 3) (match-beginning 0)))
2036 (marker (buffer-substring-no-properties
2037 (match-beginning 2) (match-end 3)))
2038 (checkbox (match-string-no-properties 4))
2039 (end (markdown-cur-list-item-end nonlist-indent)))
2040 (list begin end indent nonlist-indent marker checkbox))))
2042 (defun markdown--append-list-item-bounds (marker indent cur-bounds bounds)
2043 "Update list item BOUNDS given list MARKER, block INDENT, and CUR-BOUNDS.
2044 Here, MARKER is a string representing the type of list and INDENT
2045 is an integer giving the indentation, in spaces, of the current
2046 block. CUR-BOUNDS is a list of the form returned by
2047 `markdown-cur-list-item-bounds' and BOUNDS is a list of bounds
2048 values for parent list items. When BOUNDS is nil, it means we are
2049 at baseline (not inside of a nested list)."
2050 (let ((prev-indent (or (cl-third (car bounds)) 0)))
2051 (cond
2052 ;; New list item at baseline.
2053 ((and marker (null bounds))
2054 (list cur-bounds))
2055 ;; List item with greater indentation (four or more spaces).
2056 ;; Increase list level by consing CUR-BOUNDS onto BOUNDS.
2057 ((and marker (>= indent (+ prev-indent 4)))
2058 (cons cur-bounds bounds))
2059 ;; List item with greater or equal indentation (less than four spaces).
2060 ;; Keep list level the same by replacing the car of BOUNDS.
2061 ((and marker (>= indent prev-indent))
2062 (cons cur-bounds (cdr bounds)))
2063 ;; Lesser indentation level.
2064 ;; Pop appropriate number of elements off BOUNDS list (e.g., lesser
2065 ;; indentation could move back more than one list level). Note
2066 ;; that this block need not be the beginning of list item.
2067 ((< indent prev-indent)
2068 (while (and (> (length bounds) 1)
2069 (setq prev-indent (cl-third (cadr bounds)))
2070 (< indent (+ prev-indent 4)))
2071 (setq bounds (cdr bounds)))
2072 (cons cur-bounds bounds))
2073 ;; Otherwise, do nothing.
2074 (t bounds))))
2076 (defun markdown-syntax-propertize-list-items (start end)
2077 "Propertize list items from START to END.
2078 Stores nested list item information in the `markdown-list-item'
2079 text property to make later syntax analysis easier. The value of
2080 this property is a list with elements of the form (begin . end)
2081 giving the bounds of the current and parent list items."
2082 (save-excursion
2083 (goto-char start)
2084 (let (bounds level pre-regexp)
2085 ;; Find a baseline point with zero list indentation
2086 (markdown-search-backward-baseline)
2087 ;; Search for all list items between baseline and END
2088 (while (and (< (point) end)
2089 (re-search-forward markdown-regex-list end t))
2090 ;; Level of list nesting
2091 (setq level (length bounds))
2092 ;; Pre blocks need to be indented one level past the list level
2093 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ level)))
2094 (beginning-of-line)
2095 (cond
2096 ;; Reset at headings, horizontal rules, and top-level blank lines.
2097 ;; Propertize baseline when in range.
2098 ((markdown-new-baseline)
2099 (setq bounds nil))
2100 ;; Make sure this is not a line from a pre block
2101 ((looking-at-p pre-regexp))
2102 ;; If not, then update levels and propertize list item when in range.
2104 (let* ((indent (current-indentation))
2105 (cur-bounds (markdown--cur-list-item-bounds))
2106 (first (cl-first cur-bounds))
2107 (last (cl-second cur-bounds))
2108 (marker (cl-fifth cur-bounds)))
2109 (setq bounds (markdown--append-list-item-bounds
2110 marker indent cur-bounds bounds))
2111 (when (and (<= start (point)) (<= (point) end))
2112 (put-text-property first last 'markdown-list-item bounds)))))
2113 (end-of-line)))))
2115 (defun markdown-syntax-propertize-pre-blocks (start end)
2116 "Match preformatted text blocks from START to END."
2117 (save-excursion
2118 (goto-char start)
2119 (let ((levels (markdown-calculate-list-levels))
2120 indent pre-regexp close-regexp open close)
2121 (while (and (< (point) end) (not close))
2122 ;; Search for a region with sufficient indentation
2123 (if (null levels)
2124 (setq indent 1)
2125 (setq indent (1+ (length levels))))
2126 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
2127 (setq close-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
2129 (cond
2130 ;; If not at the beginning of a line, move forward
2131 ((not (bolp)) (forward-line))
2132 ;; Move past blank lines
2133 ((markdown-cur-line-blank-p) (forward-line))
2134 ;; At headers and horizontal rules, reset levels
2135 ((markdown-new-baseline) (forward-line) (setq levels nil))
2136 ;; If the current line has sufficient indentation, mark out pre block
2137 ;; The opening should be preceded by a blank line.
2138 ((and (markdown-prev-line-blank) (looking-at pre-regexp))
2139 (setq open (match-beginning 0))
2140 (while (and (or (looking-at-p pre-regexp) (markdown-cur-line-blank-p))
2141 (not (eobp)))
2142 (forward-line))
2143 (skip-syntax-backward "-")
2144 (setq close (point)))
2145 ;; If current line has a list marker, update levels, move to end of block
2146 ((looking-at markdown-regex-list)
2147 (setq levels (markdown-update-list-levels
2148 (match-string 2) (current-indentation) levels))
2149 (markdown-end-of-text-block))
2150 ;; If this is the end of the indentation level, adjust levels accordingly.
2151 ;; Only match end of indentation level if levels is not the empty list.
2152 ((and (car levels) (looking-at-p close-regexp))
2153 (setq levels (markdown-update-list-levels
2154 nil (current-indentation) levels))
2155 (markdown-end-of-text-block))
2156 (t (markdown-end-of-text-block))))
2158 (when (and open close)
2159 ;; Set text property data
2160 (put-text-property open close 'markdown-pre (list open close))
2161 ;; Recursively search again
2162 (markdown-syntax-propertize-pre-blocks (point) end)))))
2164 (defconst markdown-fenced-block-pairs
2165 `(((,markdown-regex-tilde-fence-begin markdown-tilde-fence-begin)
2166 (markdown-make-tilde-fence-regex markdown-tilde-fence-end)
2167 markdown-fenced-code)
2168 ((markdown-get-yaml-metadata-start-border markdown-yaml-metadata-begin)
2169 (markdown-get-yaml-metadata-end-border markdown-yaml-metadata-end)
2170 markdown-yaml-metadata-section)
2171 ((,markdown-regex-gfm-code-block-open markdown-gfm-block-begin)
2172 (,markdown-regex-gfm-code-block-close markdown-gfm-block-end)
2173 markdown-gfm-code))
2174 "Mapping of regular expressions to \"fenced-block\" constructs.
2175 These constructs are distinguished by having a distinctive start
2176 and end pattern, both of which take up an entire line of text,
2177 but no special pattern to identify text within the fenced
2178 blocks (unlike blockquotes and indented-code sections).
2180 Each element within this list takes the form:
2182 ((START-REGEX-OR-FUN START-PROPERTY)
2183 (END-REGEX-OR-FUN END-PROPERTY)
2184 MIDDLE-PROPERTY)
2186 Each *-REGEX-OR-FUN element can be a regular expression as a string, or a
2187 function which evaluates to same. Functions for START-REGEX-OR-FUN accept no
2188 arguments, but functions for END-REGEX-OR-FUN accept a single numerical argument
2189 which is the length of the first group of the START-REGEX-OR-FUN match, which
2190 can be ignored if unnecessary. `markdown-maybe-funcall-regexp' is used to
2191 evaluate these into \"real\" regexps.
2193 The *-PROPERTY elements are the text properties applied to each part of the
2194 block construct when it is matched using
2195 `markdown-syntax-propertize-fenced-block-constructs'. START-PROPERTY is applied
2196 to the text matching START-REGEX-OR-FUN, END-PROPERTY to END-REGEX-OR-FUN, and
2197 MIDDLE-PROPERTY to the text in between the two. The value of *-PROPERTY is the
2198 `match-data' when the regexp was matched to the text. In the case of
2199 MIDDLE-PROPERTY, the value is a false match data of the form '(begin end), with
2200 begin and end set to the edges of the \"middle\" text. This makes fontification
2201 easier.")
2203 (defun markdown-text-property-at-point (prop)
2204 (get-text-property (point) prop))
2206 (defsubst markdown-maybe-funcall-regexp (object &optional arg)
2207 (cond ((functionp object)
2208 (if arg (funcall object arg) (funcall object)))
2209 ((stringp object) object)
2210 (t (error "Object cannot be turned into regex"))))
2212 (defsubst markdown-get-start-fence-regexp ()
2213 "Return regexp to find all \"start\" sections of fenced block constructs.
2214 Which construct is actually contained in the match must be found separately."
2215 (mapconcat
2216 #'identity
2217 (mapcar (lambda (entry) (markdown-maybe-funcall-regexp (caar entry)))
2218 markdown-fenced-block-pairs)
2219 "\\|"))
2221 (defun markdown-get-fenced-block-begin-properties ()
2222 (cl-mapcar (lambda (entry) (cl-cadar entry)) markdown-fenced-block-pairs))
2224 (defun markdown-get-fenced-block-end-properties ()
2225 (cl-mapcar (lambda (entry) (cl-cadadr entry)) markdown-fenced-block-pairs))
2227 (defun markdown-get-fenced-block-middle-properties ()
2228 (cl-mapcar #'cl-third markdown-fenced-block-pairs))
2230 (defun markdown-find-previous-prop (prop &optional lim)
2231 "Find previous place where property PROP is non-nil, up to LIM.
2232 Return a cons of (pos . property). pos is point if point contains
2233 non-nil PROP."
2234 (let ((res
2235 (if (get-text-property (point) prop) (point)
2236 (previous-single-property-change
2237 (point) prop nil (or lim (point-min))))))
2238 (when (and (not (get-text-property res prop))
2239 (> res (point-min))
2240 (get-text-property (1- res) prop))
2241 (cl-decf res))
2242 (when (and res (get-text-property res prop)) (cons res prop))))
2244 (defun markdown-find-next-prop (prop &optional lim)
2245 "Find next place where property PROP is non-nil, up to LIM.
2246 Return a cons of (POS . PROPERTY) where POS is point if point
2247 contains non-nil PROP."
2248 (let ((res
2249 (if (get-text-property (point) prop) (point)
2250 (next-single-property-change
2251 (point) prop nil (or lim (point-max))))))
2252 (when (and res (get-text-property res prop)) (cons res prop))))
2254 (defun markdown-min-of-seq (map-fn seq)
2255 "Apply MAP-FN to SEQ and return element of SEQ with minimum value of MAP-FN."
2256 (cl-loop for el in seq
2257 with min = 1.0e+INF ; infinity
2258 with min-el = nil
2259 do (let ((res (funcall map-fn el)))
2260 (when (< res min)
2261 (setq min res)
2262 (setq min-el el)))
2263 finally return min-el))
2265 (defun markdown-max-of-seq (map-fn seq)
2266 "Apply MAP-FN to SEQ and return element of SEQ with maximum value of MAP-FN."
2267 (cl-loop for el in seq
2268 with max = -1.0e+INF ; negative infinity
2269 with max-el = nil
2270 do (let ((res (funcall map-fn el)))
2271 (when (and res (> res max))
2272 (setq max res)
2273 (setq max-el el)))
2274 finally return max-el))
2276 (defun markdown-find-previous-block ()
2277 "Find previous block.
2278 Detect whether `markdown-syntax-propertize-fenced-block-constructs' was
2279 unable to propertize the entire block, but was able to propertize the beginning
2280 of the block. If so, return a cons of (pos . property) where the beginning of
2281 the block was propertized."
2282 (let ((start-pt (point))
2283 (closest-open
2284 (markdown-max-of-seq
2285 #'car
2286 (cl-remove-if
2287 #'null
2288 (cl-mapcar
2289 #'markdown-find-previous-prop
2290 (markdown-get-fenced-block-begin-properties))))))
2291 (when closest-open
2292 (let* ((length-of-open-match
2293 (let ((match-d
2294 (get-text-property (car closest-open) (cdr closest-open))))
2295 (- (cl-fourth match-d) (cl-third match-d))))
2296 (end-regexp
2297 (markdown-maybe-funcall-regexp
2298 (cl-caadr
2299 (cl-find-if
2300 (lambda (entry) (eq (cl-cadar entry) (cdr closest-open)))
2301 markdown-fenced-block-pairs))
2302 length-of-open-match))
2303 (end-prop-loc
2304 (save-excursion
2305 (save-match-data
2306 (goto-char (car closest-open))
2307 (and (re-search-forward end-regexp start-pt t)
2308 (match-beginning 0))))))
2309 (and (not end-prop-loc) closest-open)))))
2311 (defun markdown-get-fenced-block-from-start (prop)
2312 "Return limits of an enclosing fenced block from its start, using PROP.
2313 Return value is a list usable as `match-data'."
2314 (catch 'no-rest-of-block
2315 (let* ((correct-entry
2316 (cl-find-if
2317 (lambda (entry) (eq (cl-cadar entry) prop))
2318 markdown-fenced-block-pairs))
2319 (begin-of-begin (cl-first (markdown-text-property-at-point prop)))
2320 (middle-prop (cl-third correct-entry))
2321 (end-prop (cl-cadadr correct-entry))
2322 (end-of-end
2323 (save-excursion
2324 (goto-char (match-end 0)) ; end of begin
2325 (unless (eobp) (forward-char))
2326 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
2327 (if (not mid-prop-v) ; no middle
2328 (progn
2329 ;; try to find end by advancing one
2330 (let ((end-prop-v
2331 (markdown-text-property-at-point end-prop)))
2332 (if end-prop-v (cl-second end-prop-v)
2333 (throw 'no-rest-of-block nil))))
2334 (set-match-data mid-prop-v)
2335 (goto-char (match-end 0)) ; end of middle
2336 (beginning-of-line) ; into end
2337 (cl-second (markdown-text-property-at-point end-prop)))))))
2338 (list begin-of-begin end-of-end))))
2340 (defun markdown-get-fenced-block-from-middle (prop)
2341 "Return limits of an enclosing fenced block from its middle, using PROP.
2342 Return value is a list usable as `match-data'."
2343 (let* ((correct-entry
2344 (cl-find-if
2345 (lambda (entry) (eq (cl-third entry) prop))
2346 markdown-fenced-block-pairs))
2347 (begin-prop (cl-cadar correct-entry))
2348 (begin-of-begin
2349 (save-excursion
2350 (goto-char (match-beginning 0))
2351 (unless (bobp) (forward-line -1))
2352 (beginning-of-line)
2353 (cl-first (markdown-text-property-at-point begin-prop))))
2354 (end-prop (cl-cadadr correct-entry))
2355 (end-of-end
2356 (save-excursion
2357 (goto-char (match-end 0))
2358 (beginning-of-line)
2359 (cl-second (markdown-text-property-at-point end-prop)))))
2360 (list begin-of-begin end-of-end)))
2362 (defun markdown-get-fenced-block-from-end (prop)
2363 "Return limits of an enclosing fenced block from its end, using PROP.
2364 Return value is a list usable as `match-data'."
2365 (let* ((correct-entry
2366 (cl-find-if
2367 (lambda (entry) (eq (cl-cadadr entry) prop))
2368 markdown-fenced-block-pairs))
2369 (end-of-end (cl-second (markdown-text-property-at-point prop)))
2370 (middle-prop (cl-third correct-entry))
2371 (begin-prop (cl-cadar correct-entry))
2372 (begin-of-begin
2373 (save-excursion
2374 (goto-char (match-beginning 0)) ; beginning of end
2375 (unless (bobp) (backward-char)) ; into middle
2376 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
2377 (if (not mid-prop-v)
2378 (progn
2379 (beginning-of-line)
2380 (cl-first (markdown-text-property-at-point begin-prop)))
2381 (set-match-data mid-prop-v)
2382 (goto-char (match-beginning 0)) ; beginning of middle
2383 (unless (bobp) (forward-line -1)) ; into beginning
2384 (beginning-of-line)
2385 (cl-first (markdown-text-property-at-point begin-prop)))))))
2386 (list begin-of-begin end-of-end)))
2388 (defun markdown-get-enclosing-fenced-block-construct (&optional pos)
2389 "Get \"fake\" match data for block enclosing POS.
2390 Returns fake match data which encloses the start, middle, and end
2391 of the block construct enclosing POS, if it exists. Used in
2392 `markdown-code-block-at-pos'."
2393 (save-excursion
2394 (when pos (goto-char pos))
2395 (beginning-of-line)
2396 (car
2397 (cl-remove-if
2398 #'null
2399 (cl-mapcar
2400 (lambda (fun-and-prop)
2401 (cl-destructuring-bind (fun prop) fun-and-prop
2402 (when prop
2403 (save-match-data
2404 (set-match-data (markdown-text-property-at-point prop))
2405 (funcall fun prop)))))
2406 `((markdown-get-fenced-block-from-start
2407 ,(cl-find-if
2408 #'markdown-text-property-at-point
2409 (markdown-get-fenced-block-begin-properties)))
2410 (markdown-get-fenced-block-from-middle
2411 ,(cl-find-if
2412 #'markdown-text-property-at-point
2413 (markdown-get-fenced-block-middle-properties)))
2414 (markdown-get-fenced-block-from-end
2415 ,(cl-find-if
2416 #'markdown-text-property-at-point
2417 (markdown-get-fenced-block-end-properties)))))))))
2419 (defun markdown-propertize-end-match (reg end fence-spec middle-begin)
2420 "Get match for REG up to END, if exists, and propertize appropriately.
2421 FENCE-SPEC is an entry in `markdown-fenced-block-pairs' and
2422 MIDDLE-BEGIN is the start of the \"middle\" section of the block."
2423 (when (re-search-forward reg end t)
2424 (let ((close-begin (match-beginning 0)) ; Start of closing line.
2425 (close-end (match-end 0)) ; End of closing line.
2426 (close-data (match-data t))) ; Match data for closing line.
2427 ;; Propertize middle section of fenced block.
2428 (put-text-property middle-begin close-begin
2429 (cl-third fence-spec)
2430 (list middle-begin close-begin))
2431 ;; If the block is a YAML block, propertize the declarations inside
2432 (markdown-syntax-propertize-yaml-metadata middle-begin close-begin)
2433 ;; Propertize closing line of fenced block.
2434 (put-text-property close-begin close-end
2435 (cl-cadadr fence-spec) close-data))))
2437 (defun markdown-syntax-propertize-fenced-block-constructs (start end)
2438 "Propertize according to `markdown-fenced-block-pairs' from START to END.
2439 If unable to propertize an entire block (if the start of a block is within START
2440 and END, but the end of the block is not), propertize the start section of a
2441 block, then in a subsequent call propertize both middle and end by finding the
2442 start which was previously propertized."
2443 (let ((start-reg (markdown-get-start-fence-regexp)))
2444 (save-excursion
2445 (goto-char start)
2446 ;; start from previous unclosed block, if exists
2447 (let ((prev-begin-block (markdown-find-previous-block)))
2448 (when prev-begin-block
2449 (let* ((correct-entry
2450 (cl-find-if (lambda (entry)
2451 (eq (cdr prev-begin-block) (cl-cadar entry)))
2452 markdown-fenced-block-pairs))
2453 (enclosed-text-start (1+ (car prev-begin-block)))
2454 (start-length
2455 (save-excursion
2456 (goto-char (car prev-begin-block))
2457 (string-match
2458 (markdown-maybe-funcall-regexp
2459 (caar correct-entry))
2460 (buffer-substring
2461 (point-at-bol) (point-at-eol)))
2462 (- (match-end 1) (match-beginning 1))))
2463 (end-reg (markdown-maybe-funcall-regexp
2464 (cl-caadr correct-entry) start-length)))
2465 (markdown-propertize-end-match
2466 end-reg end correct-entry enclosed-text-start))))
2467 ;; find all new blocks within region
2468 (while (re-search-forward start-reg end t)
2469 ;; we assume the opening constructs take up (only) an entire line,
2470 ;; so we re-check the current line
2471 (let* ((cur-line (buffer-substring (point-at-bol) (point-at-eol)))
2472 ;; find entry in `markdown-fenced-block-pairs' corresponding
2473 ;; to regex which was matched
2474 (correct-entry
2475 (cl-find-if
2476 (lambda (fenced-pair)
2477 (string-match-p
2478 (markdown-maybe-funcall-regexp (caar fenced-pair))
2479 cur-line))
2480 markdown-fenced-block-pairs))
2481 (enclosed-text-start
2482 (save-excursion (1+ (point-at-eol))))
2483 (end-reg
2484 (markdown-maybe-funcall-regexp
2485 (cl-caadr correct-entry)
2486 (if (and (match-beginning 1) (match-end 1))
2487 (- (match-end 1) (match-beginning 1))
2488 0))))
2489 ;; get correct match data
2490 (save-excursion
2491 (beginning-of-line)
2492 (re-search-forward
2493 (markdown-maybe-funcall-regexp (caar correct-entry))
2494 (point-at-eol)))
2495 ;; mark starting, even if ending is outside of region
2496 (put-text-property (match-beginning 0) (match-end 0)
2497 (cl-cadar correct-entry) (match-data t))
2498 (markdown-propertize-end-match
2499 end-reg end correct-entry enclosed-text-start))))))
2501 (defun markdown-syntax-propertize-blockquotes (start end)
2502 "Match blockquotes from START to END."
2503 (save-excursion
2504 (goto-char start)
2505 (while (and (re-search-forward markdown-regex-blockquote end t)
2506 (not (markdown-code-block-at-pos (match-beginning 0))))
2507 (put-text-property (match-beginning 0) (match-end 0)
2508 'markdown-blockquote
2509 (match-data t)))))
2511 (defun markdown-syntax-propertize-hrs (start end)
2512 "Match horizontal rules from START to END."
2513 (save-excursion
2514 (goto-char start)
2515 (while (re-search-forward markdown-regex-hr end t)
2516 (unless (or (markdown-on-heading-p)
2517 (markdown-code-block-at-point-p))
2518 (put-text-property (match-beginning 0) (match-end 0)
2519 'markdown-hr
2520 (match-data t))))))
2522 (defun markdown-syntax-propertize-yaml-metadata (start end)
2523 "Propertize elements inside YAML metadata blocks from START to END.
2524 Assumes region from START and END is already known to be the interior
2525 region of a YAML metadata block as propertized by
2526 `markdown-syntax-propertize-fenced-block-constructs'."
2527 (save-excursion
2528 (goto-char start)
2529 (cl-loop
2530 while (re-search-forward markdown-regex-declarative-metadata end t)
2531 do (progn
2532 (put-text-property (match-beginning 1) (match-end 1)
2533 'markdown-metadata-key (match-data t))
2534 (put-text-property (match-beginning 2) (match-end 2)
2535 'markdown-metadata-markup (match-data t))
2536 (put-text-property (match-beginning 3) (match-end 3)
2537 'markdown-metadata-value (match-data t))))))
2539 (defun markdown-syntax-propertize-headings (start end)
2540 "Match headings of type SYMBOL with REGEX from START to END."
2541 (goto-char start)
2542 (while (re-search-forward markdown-regex-header end t)
2543 (unless (markdown-code-block-at-pos (match-beginning 0))
2544 (put-text-property
2545 (match-beginning 0) (match-end 0) 'markdown-heading
2546 (match-data t))
2547 (put-text-property
2548 (match-beginning 0) (match-end 0)
2549 (cond ((match-string-no-properties 2) 'markdown-heading-1-setext)
2550 ((match-string-no-properties 3) 'markdown-heading-2-setext)
2551 (t (let ((atx-level (length (markdown-trim-whitespace
2552 (match-string-no-properties 4)))))
2553 (intern (format "markdown-heading-%d-atx" atx-level)))))
2554 (match-data t)))))
2556 (defun markdown-syntax-propertize-comments (start end)
2557 "Match HTML comments from the START to END."
2558 (let* ((in-comment (nth 4 (syntax-ppss))))
2559 (goto-char start)
2560 (cond
2561 ;; Comment start
2562 ((and (not in-comment)
2563 (re-search-forward markdown-regex-comment-start end t)
2564 (not (markdown-inline-code-at-point-p))
2565 (not (markdown-code-block-at-point-p)))
2566 (let ((open-beg (match-beginning 0)))
2567 (put-text-property open-beg (1+ open-beg)
2568 'syntax-table (string-to-syntax "<"))
2569 (markdown-syntax-propertize-comments
2570 (min (1+ (match-end 0)) end (point-max)) end)))
2571 ;; Comment end
2572 ((and in-comment
2573 (re-search-forward markdown-regex-comment-end end t))
2574 (let ((comment-end (match-end 0))
2575 (comment-begin (nth 8 (syntax-ppss))))
2576 (put-text-property (1- comment-end) comment-end
2577 'syntax-table (string-to-syntax ">"))
2578 (put-text-property comment-begin comment-end
2579 'markdown-comment (list comment-begin comment-end))
2580 (markdown-syntax-propertize-comments
2581 (min (1+ comment-end) end (point-max)) end)))
2582 ;; Nothing found
2583 (t nil))))
2585 (defvar markdown--syntax-properties
2586 (list 'markdown-tilde-fence-begin nil
2587 'markdown-tilde-fence-end nil
2588 'markdown-fenced-code nil
2589 'markdown-yaml-metadata-begin nil
2590 'markdown-yaml-metadata-end nil
2591 'markdown-yaml-metadata-section nil
2592 'markdown-gfm-block-begin nil
2593 'markdown-gfm-block-end nil
2594 'markdown-gfm-code nil
2595 'markdown-list-item nil
2596 'markdown-pre nil
2597 'markdown-blockquote nil
2598 'markdown-hr nil
2599 'markdown-comment nil
2600 'markdown-heading nil
2601 'markdown-heading-1-setext nil
2602 'markdown-heading-2-setext nil
2603 'markdown-heading-1-atx nil
2604 'markdown-heading-2-atx nil
2605 'markdown-heading-3-atx nil
2606 'markdown-heading-4-atx nil
2607 'markdown-heading-5-atx nil
2608 'markdown-heading-6-atx nil
2609 'markdown-metadata-key nil
2610 'markdown-metadata-value nil
2611 'markdown-metadata-markup nil)
2612 "Property list of all Markdown syntactic properties.")
2614 (defun markdown-syntax-propertize (start end)
2615 "Function used as `syntax-propertize-function'.
2616 START and END delimit region to propertize."
2617 (with-silent-modifications
2618 (save-excursion
2619 (remove-text-properties start end markdown--syntax-properties)
2620 (markdown-syntax-propertize-fenced-block-constructs start end)
2621 (markdown-syntax-propertize-list-items start end)
2622 (markdown-syntax-propertize-pre-blocks start end)
2623 (markdown-syntax-propertize-blockquotes start end)
2624 (markdown-syntax-propertize-headings start end)
2625 (markdown-syntax-propertize-hrs start end)
2626 (markdown-syntax-propertize-comments start end))))
2629 ;;; Markup Hiding
2631 (defconst markdown-markup-properties
2632 '(face markdown-markup-face invisible markdown-markup)
2633 "List of properties and values to apply to markup.")
2635 (defconst markdown-language-keyword-properties
2636 '(face markdown-language-keyword-face invisible markdown-markup)
2637 "List of properties and values to apply to code block language names.")
2639 (defconst markdown-language-info-properties
2640 '(face markdown-language-info-face invisible markdown-markup)
2641 "List of properties and values to apply to code block language info strings.")
2643 (defconst markdown-include-title-properties
2644 '(face markdown-link-title-face invisible markdown-markup)
2645 "List of properties and values to apply to included code titles.")
2647 (defcustom markdown-hide-markup nil
2648 "Determines whether markup in the buffer will be hidden.
2649 When set to nil, all markup is displayed in the buffer as it
2650 appears in the file. An exception is when `markdown-hide-urls'
2651 is non-nil.
2652 Set this to a non-nil value to turn this feature on by default.
2653 You can interactively toggle the value of this variable with
2654 `markdown-toggle-markup-hiding', \\[markdown-toggle-markup-hiding],
2655 or from the Markdown > Show & Hide menu.
2657 Markup hiding works by adding text properties to positions in the
2658 buffer---either the `invisible' property or the `display' property
2659 in cases where alternative glyphs are used (e.g., list bullets).
2660 This does not, however, affect printing or other output.
2661 Functions such as `htmlfontify-buffer' and `ps-print-buffer' will
2662 not honor these text properties. For printing, it would be better
2663 to first convert to HTML or PDF (e.g,. using Pandoc)."
2664 :group 'markdown
2665 :type 'boolean
2666 :safe 'booleanp
2667 :package-version '(markdown-mode . "2.3"))
2668 (make-variable-buffer-local 'markdown-hide-markup)
2670 (defun markdown-toggle-markup-hiding (&optional arg)
2671 "Toggle the display or hiding of markup.
2672 With a prefix argument ARG, enable markup hiding if ARG is positive,
2673 and disable it otherwise.
2674 See `markdown-hide-markup' for additional details."
2675 (interactive (list (or current-prefix-arg 'toggle)))
2676 (setq markdown-hide-markup
2677 (if (eq arg 'toggle)
2678 (not markdown-hide-markup)
2679 (> (prefix-numeric-value arg) 0)))
2680 (if markdown-hide-markup
2681 (progn (add-to-invisibility-spec 'markdown-markup)
2682 (message "markdown-mode markup hiding enabled"))
2683 (progn (remove-from-invisibility-spec 'markdown-markup)
2684 (message "markdown-mode markup hiding disabled")))
2685 (markdown-reload-extensions))
2688 ;;; Font Lock =================================================================
2690 (require 'font-lock)
2692 (defvar markdown-italic-face 'markdown-italic-face
2693 "Face name to use for italic text.")
2695 (defvar markdown-bold-face 'markdown-bold-face
2696 "Face name to use for bold text.")
2698 (defvar markdown-strike-through-face 'markdown-strike-through-face
2699 "Face name to use for strike-through text.")
2701 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
2702 "Face name to use as a base for header delimiters.")
2704 (defvar markdown-header-rule-face 'markdown-header-rule-face
2705 "Face name to use as a base for header rules.")
2707 (defvar markdown-header-face 'markdown-header-face
2708 "Face name to use as a base for headers.")
2710 (defvar markdown-header-face-1 'markdown-header-face-1
2711 "Face name to use for level-1 headers.")
2713 (defvar markdown-header-face-2 'markdown-header-face-2
2714 "Face name to use for level-2 headers.")
2716 (defvar markdown-header-face-3 'markdown-header-face-3
2717 "Face name to use for level-3 headers.")
2719 (defvar markdown-header-face-4 'markdown-header-face-4
2720 "Face name to use for level-4 headers.")
2722 (defvar markdown-header-face-5 'markdown-header-face-5
2723 "Face name to use for level-5 headers.")
2725 (defvar markdown-header-face-6 'markdown-header-face-6
2726 "Face name to use for level-6 headers.")
2728 (defvar markdown-inline-code-face 'markdown-inline-code-face
2729 "Face name to use for inline code.")
2731 (defvar markdown-list-face 'markdown-list-face
2732 "Face name to use for list markers.")
2734 (defvar markdown-blockquote-face 'markdown-blockquote-face
2735 "Face name to use for blockquote.")
2737 (defvar markdown-pre-face 'markdown-pre-face
2738 "Face name to use for preformatted text.")
2740 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
2741 "Face name to use for programming language identifiers.")
2743 (defvar markdown-language-info-face 'markdown-language-info-face
2744 "Face name to use for programming info strings.")
2746 (defvar markdown-link-face 'markdown-link-face
2747 "Face name to use for links.")
2749 (defvar markdown-missing-link-face 'markdown-missing-link-face
2750 "Face name to use for links where the linked file does not exist.")
2752 (defvar markdown-reference-face 'markdown-reference-face
2753 "Face name to use for reference.")
2755 (defvar markdown-footnote-marker-face 'markdown-footnote-marker-face
2756 "Face name to use for footnote markers.")
2758 (defvar markdown-url-face 'markdown-url-face
2759 "Face name to use for URLs.")
2761 (defvar markdown-link-title-face 'markdown-link-title-face
2762 "Face name to use for reference link titles.")
2764 (defvar markdown-line-break-face 'markdown-line-break-face
2765 "Face name to use for hard line breaks.")
2767 (defvar markdown-comment-face 'markdown-comment-face
2768 "Face name to use for HTML comments.")
2770 (defvar markdown-math-face 'markdown-math-face
2771 "Face name to use for LaTeX expressions.")
2773 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
2774 "Face name to use for metadata keys.")
2776 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
2777 "Face name to use for metadata values.")
2779 (defvar markdown-gfm-checkbox-face 'markdown-gfm-checkbox-face
2780 "Face name to use for GFM checkboxes.")
2782 (defvar markdown-highlight-face 'markdown-highlight-face
2783 "Face name to use for mouse highlighting.")
2785 (defvar markdown-markup-face 'markdown-markup-face
2786 "Face name to use for markup elements.")
2788 (defgroup markdown-faces nil
2789 "Faces used in Markdown Mode"
2790 :group 'markdown
2791 :group 'faces)
2793 (defface markdown-italic-face
2794 '((t (:inherit italic)))
2795 "Face for italic text."
2796 :group 'markdown-faces)
2798 (defface markdown-bold-face
2799 '((t (:inherit bold)))
2800 "Face for bold text."
2801 :group 'markdown-faces)
2803 (defface markdown-strike-through-face
2804 '((t (:strike-through t)))
2805 "Face for strike-through text."
2806 :group 'markdown-faces)
2808 (defface markdown-markup-face
2809 '((t (:inherit shadow :slant normal :weight normal)))
2810 "Face for markup elements."
2811 :group 'markdown-faces)
2813 (defface markdown-header-rule-face
2814 '((t (:inherit markdown-markup-face)))
2815 "Base face for headers rules."
2816 :group 'markdown-faces)
2818 (defface markdown-header-delimiter-face
2819 '((t (:inherit markdown-markup-face)))
2820 "Base face for headers hash delimiter."
2821 :group 'markdown-faces)
2823 (defface markdown-list-face
2824 '((t (:inherit markdown-markup-face)))
2825 "Face for list item markers."
2826 :group 'markdown-faces)
2828 (defface markdown-blockquote-face
2829 '((t (:inherit font-lock-doc-face)))
2830 "Face for blockquote sections."
2831 :group 'markdown-faces)
2833 (defface markdown-code-face
2834 '((t (:inherit fixed-pitch)))
2835 "Face for inline code, pre blocks, and fenced code blocks.
2836 This may be used, for example, to add a contrasting background to
2837 inline code fragments and code blocks."
2838 :group 'markdown-faces)
2840 (defface markdown-inline-code-face
2841 '((t (:inherit (markdown-code-face font-lock-constant-face))))
2842 "Face for inline code."
2843 :group 'markdown-faces)
2845 (defface markdown-pre-face
2846 '((t (:inherit (markdown-code-face font-lock-constant-face))))
2847 "Face for preformatted text."
2848 :group 'markdown-faces)
2850 (defface markdown-table-face
2851 '((t (:inherit (markdown-code-face))))
2852 "Face for tables."
2853 :group 'markdown-faces)
2855 (defface markdown-language-keyword-face
2856 '((t (:inherit font-lock-type-face)))
2857 "Face for programming language identifiers."
2858 :group 'markdown-faces)
2860 (defface markdown-language-info-face
2861 '((t (:inherit font-lock-string-face)))
2862 "Face for programming language info strings."
2863 :group 'markdown-faces)
2865 (defface markdown-link-face
2866 '((t (:inherit link)))
2867 "Face for links."
2868 :group 'markdown-faces)
2870 (defface markdown-missing-link-face
2871 '((t (:inherit font-lock-warning-face)))
2872 "Face for missing links."
2873 :group 'markdown-faces)
2875 (defface markdown-reference-face
2876 '((t (:inherit markdown-markup-face)))
2877 "Face for link references."
2878 :group 'markdown-faces)
2880 (define-obsolete-face-alias 'markdown-footnote-face
2881 'markdown-footnote-marker-face "v2.3")
2883 (defface markdown-footnote-marker-face
2884 '((t (:inherit markdown-markup-face)))
2885 "Face for footnote markers."
2886 :group 'markdown-faces)
2888 (defface markdown-footnote-text-face
2889 '((t (:inherit font-lock-comment-face)))
2890 "Face for footnote text."
2891 :group 'markdown-faces)
2893 (defface markdown-url-face
2894 '((t (:inherit font-lock-string-face)))
2895 "Face for URLs that are part of markup.
2896 For example, this applies to URLs in inline links:
2897 [link text](http://example.com/)."
2898 :group 'markdown-faces)
2900 (defface markdown-plain-url-face
2901 '((t (:inherit markdown-link-face)))
2902 "Face for URLs that are also links.
2903 For example, this applies to plain angle bracket URLs:
2904 <http://example.com/>."
2905 :group 'markdown-faces)
2907 (defface markdown-link-title-face
2908 '((t (:inherit font-lock-comment-face)))
2909 "Face for reference link titles."
2910 :group 'markdown-faces)
2912 (defface markdown-line-break-face
2913 '((t (:inherit font-lock-constant-face :underline t)))
2914 "Face for hard line breaks."
2915 :group 'markdown-faces)
2917 (defface markdown-comment-face
2918 '((t (:inherit font-lock-comment-face)))
2919 "Face for HTML comments."
2920 :group 'markdown-faces)
2922 (defface markdown-math-face
2923 '((t (:inherit font-lock-string-face)))
2924 "Face for LaTeX expressions."
2925 :group 'markdown-faces)
2927 (defface markdown-metadata-key-face
2928 '((t (:inherit font-lock-variable-name-face)))
2929 "Face for metadata keys."
2930 :group 'markdown-faces)
2932 (defface markdown-metadata-value-face
2933 '((t (:inherit font-lock-string-face)))
2934 "Face for metadata values."
2935 :group 'markdown-faces)
2937 (defface markdown-gfm-checkbox-face
2938 '((t (:inherit font-lock-builtin-face)))
2939 "Face for GFM checkboxes."
2940 :group 'markdown-faces)
2942 (defface markdown-highlight-face
2943 '((t (:inherit highlight)))
2944 "Face for mouse highlighting."
2945 :group 'markdown-faces)
2947 (defface markdown-hr-face
2948 '((t (:inherit markdown-markup-face)))
2949 "Face for horizontal rules."
2950 :group 'markdown-faces)
2952 (defface markdown-html-tag-name-face
2953 '((t (:inherit font-lock-type-face)))
2954 "Face for HTML tag names."
2955 :group 'markdown-faces)
2957 (defface markdown-html-tag-delimiter-face
2958 '((t (:inherit markdown-markup-face)))
2959 "Face for HTML tag delimiters."
2960 :group 'markdown-faces)
2962 (defface markdown-html-attr-name-face
2963 '((t (:inherit font-lock-variable-name-face)))
2964 "Face for HTML attribute names."
2965 :group 'markdown-faces)
2967 (defface markdown-html-attr-value-face
2968 '((t (:inherit font-lock-string-face)))
2969 "Face for HTML attribute values."
2970 :group 'markdown-faces)
2972 (defface markdown-html-entity-face
2973 '((t (:inherit font-lock-variable-name-face)))
2974 "Face for HTML entities."
2975 :group 'markdown-faces)
2977 (defcustom markdown-header-scaling nil
2978 "Whether to use variable-height faces for headers.
2979 When non-nil, `markdown-header-face' will inherit from
2980 `variable-pitch' and the scaling values in
2981 `markdown-header-scaling-values' will be applied to
2982 headers of levels one through six respectively."
2983 :type 'boolean
2984 :initialize 'custom-initialize-default
2985 :set (lambda (symbol value)
2986 (set-default symbol value)
2987 (markdown-update-header-faces value))
2988 :group 'markdown-faces
2989 :package-version '(markdown-mode . "2.2"))
2991 (defcustom markdown-header-scaling-values
2992 '(2.0 1.7 1.4 1.1 1.0 1.0)
2993 "List of scaling values for headers of level one through six.
2994 Used when `markdown-header-scaling' is non-nil."
2995 :type 'list
2996 :initialize 'custom-initialize-default
2997 :set (lambda (symbol value)
2998 (set-default symbol value)
2999 (markdown-update-header-faces markdown-header-scaling value))
3000 :group 'markdown-faces)
3002 (defun markdown-make-header-faces ()
3003 "Build the faces used for Markdown headers."
3004 (let ((inherit-faces '(font-lock-function-name-face)))
3005 (when markdown-header-scaling
3006 (setq inherit-faces (cons 'variable-pitch inherit-faces)))
3007 (defface markdown-header-face
3008 `((t (:inherit ,inherit-faces :weight bold)))
3009 "Base face for headers."
3010 :group 'markdown-faces))
3011 (dotimes (num 6)
3012 (let* ((num1 (1+ num))
3013 (face-name (intern (format "markdown-header-face-%s" num1)))
3014 (scale (if markdown-header-scaling
3015 (float (nth num markdown-header-scaling-values))
3016 1.0)))
3017 (eval
3018 `(defface ,face-name
3019 '((t (:inherit markdown-header-face :height ,scale)))
3020 (format "Face for level %s headers.
3021 You probably don't want to customize this face directly. Instead
3022 you can customize the base face `markdown-header-face' or the
3023 variable-height variable `markdown-header-scaling'." ,num1)
3024 :group 'markdown-faces)))))
3026 (markdown-make-header-faces)
3028 (defun markdown-update-header-faces (&optional scaling scaling-values)
3029 "Update header faces, depending on if header SCALING is desired.
3030 If so, use given list of SCALING-VALUES relative to the baseline
3031 size of `markdown-header-face'."
3032 (dotimes (num 6)
3033 (let* ((face-name (intern (format "markdown-header-face-%s" (1+ num))))
3034 (scale (cond ((not scaling) 1.0)
3035 (scaling-values (float (nth num scaling-values)))
3036 (t (float (nth num markdown-header-scaling-values))))))
3037 (unless (get face-name 'saved-face) ; Don't update customized faces
3038 (set-face-attribute face-name nil :height scale)))))
3040 (defun markdown-syntactic-face (state)
3041 "Return font-lock face for characters with given STATE.
3042 See `font-lock-syntactic-face-function' for details."
3043 (let ((in-comment (nth 4 state)))
3044 (cond
3045 (in-comment 'markdown-comment-face)
3046 (t nil))))
3048 (defcustom markdown-list-item-bullets
3049 '("●" "◎" "○" "◆" "◇" "►" "•")
3050 "List of bullets to use for unordered lists.
3051 It can contain any number of symbols, which will be repeated.
3052 Depending on your font, some reasonable choices are:
3053 ♥ ● ◇ ✚ ✜ ☯ ◆ ♠ ♣ ♦ ❀ ◆ ◖ ▶ ► • ★ ▸."
3054 :group 'markdown
3055 :type '(repeat (string :tag "Bullet character"))
3056 :package-version '(markdown-mode . "2.3"))
3058 (defun markdown--footnote-marker-properties ()
3059 "Return a font-lock facespec expression for footnote marker text."
3060 `(face markdown-footnote-marker-face
3061 ,@(when markdown-hide-markup
3062 `(display ,markdown-footnote-display))))
3064 (defun markdown--pandoc-inline-footnote-properties ()
3065 "Return a font-lock facespec expression for Pandoc inline footnote text."
3066 `(face markdown-footnote-text-face
3067 ,@(when markdown-hide-markup
3068 `(display ,markdown-footnote-display))))
3070 (defvar markdown-mode-font-lock-keywords-basic
3071 `((markdown-match-yaml-metadata-begin . ((1 markdown-markup-face)))
3072 (markdown-match-yaml-metadata-end . ((1 markdown-markup-face)))
3073 (markdown-match-yaml-metadata-key . ((1 markdown-metadata-key-face)
3074 (2 markdown-markup-face)
3075 (3 markdown-metadata-value-face)))
3076 (markdown-match-gfm-open-code-blocks . ((1 markdown-markup-properties)
3077 (2 markdown-markup-properties nil t)
3078 (3 markdown-language-keyword-properties nil t)
3079 (4 markdown-language-info-properties nil t)
3080 (5 markdown-markup-properties nil t)))
3081 (markdown-match-gfm-close-code-blocks . ((0 markdown-markup-properties)))
3082 (markdown-fontify-gfm-code-blocks)
3083 (markdown-fontify-tables)
3084 (markdown-match-fenced-start-code-block . ((1 markdown-markup-properties)
3085 (2 markdown-markup-properties nil t)
3086 (3 markdown-language-keyword-properties nil t)
3087 (4 markdown-language-info-properties nil t)
3088 (5 markdown-markup-properties nil t)))
3089 (markdown-match-fenced-end-code-block . ((0 markdown-markup-properties)))
3090 (markdown-fontify-fenced-code-blocks)
3091 (markdown-match-pre-blocks . ((0 markdown-pre-face)))
3092 (markdown-fontify-headings)
3093 (markdown-match-declarative-metadata . ((1 markdown-metadata-key-face)
3094 (2 markdown-markup-face)
3095 (3 markdown-metadata-value-face)))
3096 (markdown-match-pandoc-metadata . ((1 markdown-markup-face)
3097 (2 markdown-markup-face)
3098 (3 markdown-metadata-value-face)))
3099 (markdown-fontify-hrs)
3100 (markdown-match-code . ((1 markdown-markup-properties prepend)
3101 (2 markdown-inline-code-face prepend)
3102 (3 markdown-markup-properties prepend)))
3103 (,markdown-regex-kbd . ((1 markdown-markup-properties)
3104 (2 markdown-inline-code-face)
3105 (3 markdown-markup-properties)))
3106 (markdown-fontify-angle-uris)
3107 (,markdown-regex-email . 'markdown-plain-url-face)
3108 (markdown-match-html-tag . ((1 'markdown-html-tag-delimiter-face t)
3109 (2 'markdown-html-tag-name-face t)
3110 (3 'markdown-html-tag-delimiter-face t)
3111 ;; Anchored matcher for HTML tag attributes
3112 (,markdown-regex-html-attr
3113 ;; Before searching, move past tag
3114 ;; name; set limit at tag close.
3115 (progn
3116 (goto-char (match-end 2)) (match-end 3))
3118 . ((1 'markdown-html-attr-name-face)
3119 (3 'markdown-html-tag-delimiter-face nil t)
3120 (4 'markdown-html-attr-value-face nil t)))))
3121 (,markdown-regex-html-entity . 'markdown-html-entity-face)
3122 (markdown-fontify-list-items)
3123 (,markdown-regex-footnote . ((1 markdown-markup-properties) ; [^
3124 (2 (markdown--footnote-marker-properties)) ; label
3125 (3 markdown-markup-properties))) ; ]
3126 (,markdown-regex-pandoc-inline-footnote . ((1 markdown-markup-properties) ; ^
3127 (2 markdown-markup-properties) ; [
3128 (3 (markdown--pandoc-inline-footnote-properties)) ; text
3129 (4 markdown-markup-properties))) ; ]
3130 (markdown-match-includes . ((1 markdown-markup-properties)
3131 (2 markdown-markup-properties nil t)
3132 (3 markdown-include-title-properties nil t)
3133 (4 markdown-markup-properties nil t)
3134 (5 markdown-markup-properties)
3135 (6 'markdown-url-face)
3136 (7 markdown-markup-properties)))
3137 (markdown-fontify-inline-links)
3138 (markdown-fontify-reference-links)
3139 (,markdown-regex-reference-definition . ((1 markdown-markup-face) ; [
3140 (2 markdown-reference-face) ; label
3141 (3 markdown-markup-face) ; ]
3142 (4 markdown-markup-face) ; :
3143 (5 markdown-url-face) ; url
3144 (6 markdown-link-title-face))) ; "title" (optional)
3145 (markdown-fontify-plain-uris)
3146 ;; Math mode $..$
3147 (markdown-match-math-single . ((1 markdown-markup-face prepend)
3148 (2 markdown-math-face append)
3149 (3 markdown-markup-face prepend)))
3150 ;; Math mode $$..$$
3151 (markdown-match-math-double . ((1 markdown-markup-face prepend)
3152 (2 markdown-math-face append)
3153 (3 markdown-markup-face prepend)))
3154 ;; Math mode \[..\] and \\[..\\]
3155 (markdown-match-math-display . ((1 markdown-markup-face prepend)
3156 (3 markdown-math-face append)
3157 (4 markdown-markup-face prepend)))
3158 (markdown-match-bold . ((1 markdown-markup-properties prepend)
3159 (2 markdown-bold-face append)
3160 (3 markdown-markup-properties prepend)))
3161 (markdown-match-italic . ((1 markdown-markup-properties prepend)
3162 (2 markdown-italic-face append)
3163 (3 markdown-markup-properties prepend)))
3164 (,markdown-regex-strike-through . ((3 markdown-markup-properties)
3165 (4 markdown-strike-through-face)
3166 (5 markdown-markup-properties)))
3167 (,markdown-regex-line-break . (1 markdown-line-break-face prepend))
3168 (markdown-fontify-sub-superscripts)
3169 (markdown-match-inline-attributes . ((0 markdown-markup-properties prepend)))
3170 (markdown-match-leanpub-sections . ((0 markdown-markup-properties)))
3171 (markdown-fontify-blockquotes)
3172 (markdown-match-wiki-link . ((0 markdown-link-face prepend))))
3173 "Syntax highlighting for Markdown files.")
3175 ;; Footnotes
3176 (defvar markdown-footnote-counter 0
3177 "Counter for footnote numbers.")
3178 (make-variable-buffer-local 'markdown-footnote-counter)
3180 (defconst markdown-footnote-chars
3181 "[[:alnum:]-]"
3182 "Regular expression matching any character that is allowed in a footnote identifier.")
3184 (defconst markdown-regex-footnote-definition
3185 (concat "^ \\{0,3\\}\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:\\(?:[ \t]+\\|$\\)")
3186 "Regular expression matching a footnote definition, capturing the label.")
3189 ;;; Compatibility =============================================================
3191 (defun markdown-replace-regexp-in-string (regexp rep string)
3192 "Replace ocurrences of REGEXP with REP in STRING.
3193 This is a compatibility wrapper to provide `replace-regexp-in-string'
3194 in XEmacs 21."
3195 (if (featurep 'xemacs)
3196 (replace-in-string string regexp rep)
3197 (replace-regexp-in-string regexp rep string)))
3199 ;; `markdown-use-region-p' is a compatibility function which checks
3200 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
3201 (eval-and-compile
3202 (cond
3203 ;; Emacs 24 and newer
3204 ((fboundp 'use-region-p)
3205 (defalias 'markdown-use-region-p 'use-region-p))
3206 ;; XEmacs
3207 ((fboundp 'region-active-p)
3208 (defalias 'markdown-use-region-p 'region-active-p))))
3210 ;; Use new names for outline-mode functions in Emacs 25 and later.
3211 (eval-and-compile
3212 (defalias 'markdown-hide-sublevels
3213 (if (fboundp 'outline-hide-sublevels)
3214 'outline-hide-sublevels
3215 'hide-sublevels))
3216 (defalias 'markdown-show-all
3217 (if (fboundp 'outline-show-all)
3218 'outline-show-all
3219 'show-all))
3220 (defalias 'markdown-hide-body
3221 (if (fboundp 'outline-hide-body)
3222 'outline-hide-body
3223 'hide-body))
3224 (defalias 'markdown-show-children
3225 (if (fboundp 'outline-show-children)
3226 'outline-show-children
3227 'show-children))
3228 (defalias 'markdown-show-subtree
3229 (if (fboundp 'outline-show-subtree)
3230 'outline-show-subtree
3231 'show-subtree))
3232 (defalias 'markdown-hide-subtree
3233 (if (fboundp 'outline-hide-subtree)
3234 'outline-hide-subtree
3235 'hide-subtree)))
3237 ;; Provide directory-name-p to Emacs 24
3238 (defsubst markdown-directory-name-p (name)
3239 "Return non-nil if NAME ends with a directory separator character.
3240 Taken from `directory-name-p' from Emacs 25 and provided here for
3241 backwards compatibility."
3242 (let ((len (length name))
3243 (lastc ?.))
3244 (if (> len 0)
3245 (setq lastc (aref name (1- len))))
3246 (or (= lastc ?/)
3247 (and (memq system-type '(windows-nt ms-dos))
3248 (= lastc ?\\)))))
3250 ;; Provide a function to find files recursively in Emacs 24.
3251 (defalias 'markdown-directory-files-recursively
3252 (if (fboundp 'directory-files-recursively)
3253 'directory-files-recursively
3254 (lambda (dir regexp)
3255 "Return list of all files under DIR that have file names matching REGEXP.
3256 This function works recursively. Files are returned in \"depth first\"
3257 order, and files from each directory are sorted in alphabetical order.
3258 Each file name appears in the returned list in its absolute form.
3259 Based on `directory-files-recursively' from Emacs 25 and provided
3260 here for backwards compatibility."
3261 (let ((result nil)
3262 (files nil)
3263 ;; When DIR is "/", remote file names like "/method:" could
3264 ;; also be offered. We shall suppress them.
3265 (tramp-mode (and tramp-mode (file-remote-p (expand-file-name dir)))))
3266 (dolist (file (sort (file-name-all-completions "" dir)
3267 'string<))
3268 (unless (member file '("./" "../"))
3269 (if (markdown-directory-name-p file)
3270 (let* ((leaf (substring file 0 (1- (length file))))
3271 (full-file (expand-file-name leaf dir)))
3272 (setq result
3273 (nconc result (markdown-directory-files-recursively
3274 full-file regexp))))
3275 (when (string-match-p regexp file)
3276 (push (expand-file-name file dir) files)))))
3277 (nconc result (nreverse files))))))
3279 (defun markdown-flyspell-check-word-p ()
3280 "Return t if `flyspell' should check word just before point.
3281 Used for `flyspell-generic-check-word-predicate'."
3282 (save-excursion
3283 (goto-char (1- (point)))
3284 (not (or (markdown-code-block-at-point-p)
3285 (markdown-inline-code-at-point-p)
3286 (markdown-in-comment-p)
3287 (let ((faces (get-text-property (point) 'face)))
3288 (if (listp faces)
3289 (or (memq 'markdown-reference-face faces)
3290 (memq 'markdown-markup-face faces)
3291 (memq 'markdown-plain-url-face faces)
3292 (memq 'markdown-inline-code-face faces)
3293 (memq 'markdown-url-face faces))
3294 (memq faces '(markdown-reference-face
3295 markdown-markup-face
3296 markdown-plain-url-face
3297 markdown-inline-code-face
3298 markdown-url-face))))))))
3300 (defun markdown-font-lock-ensure ()
3301 "Provide `font-lock-ensure' in Emacs 24."
3302 (if (fboundp 'font-lock-ensure)
3303 (font-lock-ensure)
3304 (with-no-warnings
3305 ;; Suppress warning about non-interactive use of
3306 ;; `font-lock-fontify-buffer' in Emacs 25.
3307 (font-lock-fontify-buffer))))
3310 ;;; Markdown Parsing Functions ================================================
3312 (define-obsolete-function-alias
3313 'markdown-cur-line-blank 'markdown-cur-line-blank-p "v2.4")
3314 (define-obsolete-function-alias
3315 'markdown-next-line-blank 'markdown-next-line-blank-p "v2.4")
3317 (defun markdown-cur-line-blank-p ()
3318 "Return t if the current line is blank and nil otherwise."
3319 (save-excursion
3320 (beginning-of-line)
3321 (looking-at-p markdown-regex-blank-line)))
3323 (defun markdown-prev-line-blank ()
3324 "Return t if the previous line is blank and nil otherwise.
3325 If we are at the first line, then consider the previous line to be blank."
3326 (or (= (line-beginning-position) (point-min))
3327 (save-excursion
3328 (forward-line -1)
3329 (looking-at markdown-regex-blank-line))))
3331 (defun markdown-prev-line-blank-p ()
3332 "Like `markdown-prev-line-blank', but preserve `match-data'."
3333 (save-match-data (markdown-prev-line-blank)))
3335 (defun markdown-next-line-blank-p ()
3336 "Return t if the next line is blank and nil otherwise.
3337 If we are at the last line, then consider the next line to be blank."
3338 (or (= (line-end-position) (point-max))
3339 (save-excursion
3340 (forward-line 1)
3341 (markdown-cur-line-blank-p))))
3343 (defun markdown-prev-line-indent ()
3344 "Return the number of leading whitespace characters in the previous line.
3345 Return 0 if the current line is the first line in the buffer."
3346 (save-excursion
3347 (if (= (line-beginning-position) (point-min))
3349 (forward-line -1)
3350 (current-indentation))))
3352 (defun markdown-next-line-indent ()
3353 "Return the number of leading whitespace characters in the next line.
3354 Return 0 if line is the last line in the buffer."
3355 (save-excursion
3356 (if (= (line-end-position) (point-max))
3358 (forward-line 1)
3359 (current-indentation))))
3361 (defun markdown-new-baseline ()
3362 "Determine if the current line begins a new baseline level.
3363 Assume point is positioned at beginning of line."
3364 (or (looking-at markdown-regex-header)
3365 (looking-at markdown-regex-hr)
3366 (and (= (current-indentation) 0)
3367 (not (looking-at markdown-regex-list))
3368 (markdown-prev-line-blank))))
3370 (defun markdown-search-backward-baseline ()
3371 "Search backward baseline point with no indentation and not a list item."
3372 (end-of-line)
3373 (let (stop)
3374 (while (not (or stop (bobp)))
3375 (re-search-backward markdown-regex-block-separator-noindent nil t)
3376 (when (match-end 2)
3377 (goto-char (match-end 2))
3378 (cond
3379 ((markdown-new-baseline)
3380 (setq stop t))
3381 ((looking-at-p markdown-regex-list)
3382 (setq stop nil))
3383 (t (setq stop t)))))))
3385 (defun markdown-update-list-levels (marker indent levels)
3386 "Update list levels given list MARKER, block INDENT, and current LEVELS.
3387 Here, MARKER is a string representing the type of list, INDENT is an integer
3388 giving the indentation, in spaces, of the current block, and LEVELS is a
3389 list of the indentation levels of parent list items. When LEVELS is nil,
3390 it means we are at baseline (not inside of a nested list)."
3391 (cond
3392 ;; New list item at baseline.
3393 ((and marker (null levels))
3394 (setq levels (list indent)))
3395 ;; List item with greater indentation (four or more spaces).
3396 ;; Increase list level.
3397 ((and marker (>= indent (+ (car levels) 4)))
3398 (setq levels (cons indent levels)))
3399 ;; List item with greater or equal indentation (less than four spaces).
3400 ;; Do not increase list level.
3401 ((and marker (>= indent (car levels)))
3402 levels)
3403 ;; Lesser indentation level.
3404 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
3405 ;; indentation could move back more than one list level). Note
3406 ;; that this block need not be the beginning of list item.
3407 ((< indent (car levels))
3408 (while (and (> (length levels) 1)
3409 (< indent (+ (cadr levels) 4)))
3410 (setq levels (cdr levels)))
3411 levels)
3412 ;; Otherwise, do nothing.
3413 (t levels)))
3415 (defun markdown-calculate-list-levels ()
3416 "Calculate list levels at point.
3417 Return a list of the form (n1 n2 n3 ...) where n1 is the
3418 indentation of the deepest nested list item in the branch of
3419 the list at the point, n2 is the indentation of the parent
3420 list item, and so on. The depth of the list item is therefore
3421 the length of the returned list. If the point is not at or
3422 immediately after a list item, return nil."
3423 (save-excursion
3424 (let ((first (point)) levels indent pre-regexp)
3425 ;; Find a baseline point with zero list indentation
3426 (markdown-search-backward-baseline)
3427 ;; Search for all list items between baseline and LOC
3428 (while (and (< (point) first)
3429 (re-search-forward markdown-regex-list first t))
3430 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
3431 (beginning-of-line)
3432 (cond
3433 ;; Make sure this is not a header or hr
3434 ((markdown-new-baseline) (setq levels nil))
3435 ;; Make sure this is not a line from a pre block
3436 ((looking-at-p pre-regexp))
3437 ;; If not, then update levels
3439 (setq indent (current-indentation))
3440 (setq levels (markdown-update-list-levels (match-string 2)
3441 indent levels))))
3442 (end-of-line))
3443 levels)))
3445 (defun markdown-prev-list-item (level)
3446 "Search backward from point for a list item with indentation LEVEL.
3447 Set point to the beginning of the item, and return point, or nil
3448 upon failure."
3449 (let (bounds indent prev)
3450 (setq prev (point))
3451 (forward-line -1)
3452 (setq indent (current-indentation))
3453 (while
3454 (cond
3455 ;; List item
3456 ((and (looking-at-p markdown-regex-list)
3457 (setq bounds (markdown-cur-list-item-bounds)))
3458 (cond
3459 ;; Stop and return point at item of equal indentation
3460 ((= (nth 3 bounds) level)
3461 (setq prev (point))
3462 nil)
3463 ;; Stop and return nil at item with lesser indentation
3464 ((< (nth 3 bounds) level)
3465 (setq prev nil)
3466 nil)
3467 ;; Stop at beginning of buffer
3468 ((bobp) (setq prev nil))
3469 ;; Continue at item with greater indentation
3470 ((> (nth 3 bounds) level) t)))
3471 ;; Stop at beginning of buffer
3472 ((bobp) (setq prev nil))
3473 ;; Continue if current line is blank
3474 ((markdown-cur-line-blank-p) t)
3475 ;; Continue while indentation is the same or greater
3476 ((>= indent level) t)
3477 ;; Stop if current indentation is less than list item
3478 ;; and the next is blank
3479 ((and (< indent level)
3480 (markdown-next-line-blank-p))
3481 (setq prev nil))
3482 ;; Stop at a header
3483 ((looking-at-p markdown-regex-header) (setq prev nil))
3484 ;; Stop at a horizontal rule
3485 ((looking-at-p markdown-regex-hr) (setq prev nil))
3486 ;; Otherwise, continue.
3487 (t t))
3488 (forward-line -1)
3489 (setq indent (current-indentation)))
3490 prev))
3492 (defun markdown-next-list-item (level)
3493 "Search forward from point for the next list item with indentation LEVEL.
3494 Set point to the beginning of the item, and return point, or nil
3495 upon failure."
3496 (let (bounds indent next)
3497 (setq next (point))
3498 (if (looking-at markdown-regex-header-setext)
3499 (goto-char (match-end 0)))
3500 (forward-line)
3501 (setq indent (current-indentation))
3502 (while
3503 (cond
3504 ;; Stop at end of the buffer.
3505 ((eobp) nil)
3506 ;; Continue if the current line is blank
3507 ((markdown-cur-line-blank-p) t)
3508 ;; List item
3509 ((and (looking-at-p markdown-regex-list)
3510 (setq bounds (markdown-cur-list-item-bounds)))
3511 (cond
3512 ;; Continue at item with greater indentation
3513 ((> (nth 3 bounds) level) t)
3514 ;; Stop and return point at item of equal indentation
3515 ((= (nth 3 bounds) level)
3516 (setq next (point))
3517 nil)
3518 ;; Stop and return nil at item with lesser indentation
3519 ((< (nth 3 bounds) level)
3520 (setq next nil)
3521 nil)))
3522 ;; Continue while indentation is the same or greater
3523 ((>= indent level) t)
3524 ;; Stop if current indentation is less than list item
3525 ;; and the previous line was blank.
3526 ((and (< indent level)
3527 (markdown-prev-line-blank-p))
3528 (setq next nil))
3529 ;; Stop at a header
3530 ((looking-at-p markdown-regex-header) (setq next nil))
3531 ;; Stop at a horizontal rule
3532 ((looking-at-p markdown-regex-hr) (setq next nil))
3533 ;; Otherwise, continue.
3534 (t t))
3535 (forward-line)
3536 (setq indent (current-indentation)))
3537 next))
3539 (defun markdown-cur-list-item-end (level)
3540 "Move to end of list item with pre-marker indentation LEVEL.
3541 Return the point at the end when a list item was found at the
3542 original point. If the point is not in a list item, do nothing."
3543 (let (indent)
3544 (forward-line)
3545 (setq indent (current-indentation))
3546 (while
3547 (cond
3548 ;; Stop at end of the buffer.
3549 ((eobp) nil)
3550 ;; Continue if the current line is blank
3551 ((looking-at-p markdown-regex-blank-line) t)
3552 ;; Continue while indentation is the same or greater
3553 ((>= indent level) t)
3554 ;; Stop if current indentation is less than list item
3555 ;; and the previous line was blank.
3556 ((and (< indent level)
3557 (markdown-prev-line-blank-p))
3558 nil)
3559 ;; Stop at a new list item of the same or lesser indentation
3560 ((looking-at-p markdown-regex-list) nil)
3561 ;; Stop at a header
3562 ((looking-at-p markdown-regex-header) nil)
3563 ;; Stop at a horizontal rule
3564 ((looking-at-p markdown-regex-hr) nil)
3565 ;; Otherwise, continue.
3566 (t t))
3567 (forward-line)
3568 (setq indent (current-indentation)))
3569 ;; Don't skip over whitespace for empty list items (marker and
3570 ;; whitespace only), just move to end of whitespace.
3571 (save-match-data
3572 (if (looking-back (concat markdown-regex-list "\\s-*") (point-at-bol))
3573 (goto-char (match-end 3))
3574 (skip-chars-backward " \t\n")))
3575 (point)))
3577 (defun markdown-cur-list-item-bounds ()
3578 "Return bounds for list item at point.
3579 Return a list of the following form:
3581 (begin end indent nonlist-indent marker checkbox)
3583 The named components are:
3585 - begin: Position of beginning of list item, including leading indentation.
3586 - end: Position of the end of the list item, including list item text.
3587 - indent: Number of characters of indentation before list marker (an integer).
3588 - nonlist-indent: Number characters of indentation, list
3589 marker, and whitespace following list marker (an integer).
3590 - marker: String containing the list marker and following whitespace
3591 (e.g., \"- \" or \"* \").
3592 - checkbox: String containing the GFM checkbox portion, if any,
3593 including any trailing whitespace before the text
3594 begins (e.g., \"[x] \").
3596 As an example, for the following unordered list item
3598 - item
3600 the returned list would be
3602 (1 14 3 5 \"- \" nil)
3604 If the point is not inside a list item, return nil."
3605 (car (get-text-property (point-at-bol) 'markdown-list-item)))
3607 (defun markdown-list-item-at-point-p ()
3608 "Return t if there is a list item at the point and nil otherwise."
3609 (save-match-data (markdown-cur-list-item-bounds)))
3611 (defun markdown-prev-list-item-bounds ()
3612 "Return bounds of previous item in the same list of any level.
3613 The return value has the same form as that of
3614 `markdown-cur-list-item-bounds'."
3615 (save-excursion
3616 (let ((cur-bounds (markdown-cur-list-item-bounds))
3617 (beginning-of-list (save-excursion (markdown-beginning-of-list)))
3618 stop)
3619 (when cur-bounds
3620 (goto-char (nth 0 cur-bounds))
3621 (while (and (not stop) (not (bobp))
3622 (re-search-backward markdown-regex-list
3623 beginning-of-list t))
3624 (unless (or (looking-at markdown-regex-hr)
3625 (markdown-code-block-at-point-p))
3626 (setq stop (point))))
3627 (markdown-cur-list-item-bounds)))))
3629 (defun markdown-next-list-item-bounds ()
3630 "Return bounds of next item in the same list of any level.
3631 The return value has the same form as that of
3632 `markdown-cur-list-item-bounds'."
3633 (save-excursion
3634 (let ((cur-bounds (markdown-cur-list-item-bounds))
3635 (end-of-list (save-excursion (markdown-end-of-list)))
3636 stop)
3637 (when cur-bounds
3638 (goto-char (nth 0 cur-bounds))
3639 (end-of-line)
3640 (while (and (not stop) (not (eobp))
3641 (re-search-forward markdown-regex-list
3642 end-of-list t))
3643 (unless (or (looking-at markdown-regex-hr)
3644 (markdown-code-block-at-point-p))
3645 (setq stop (point))))
3646 (when stop
3647 (markdown-cur-list-item-bounds))))))
3649 (defun markdown-beginning-of-list ()
3650 "Move point to beginning of list at point, if any."
3651 (interactive)
3652 (let ((orig-point (point))
3653 (list-begin (save-excursion
3654 (markdown-search-backward-baseline)
3655 ;; Stop at next list item, regardless of the indentation.
3656 (markdown-next-list-item (point-max))
3657 (when (looking-at markdown-regex-list)
3658 (point)))))
3659 (when (and list-begin (<= list-begin orig-point))
3660 (goto-char list-begin))))
3662 (defun markdown-end-of-list ()
3663 "Move point to end of list at point, if any."
3664 (interactive)
3665 (let ((start (point))
3666 (end (save-excursion
3667 (when (markdown-beginning-of-list)
3668 ;; Items can't have nonlist-indent <= 1, so this
3669 ;; moves past all list items.
3670 (markdown-next-list-item 1)
3671 (skip-syntax-backward "-")
3672 (unless (eobp) (forward-char 1))
3673 (point)))))
3674 (when (and end (>= end start))
3675 (goto-char end))))
3677 (defun markdown-up-list ()
3678 "Move point to beginning of parent list item."
3679 (interactive)
3680 (let ((cur-bounds (markdown-cur-list-item-bounds)))
3681 (when cur-bounds
3682 (markdown-prev-list-item (1- (nth 3 cur-bounds)))
3683 (let ((up-bounds (markdown-cur-list-item-bounds)))
3684 (when (and up-bounds (< (nth 3 up-bounds) (nth 3 cur-bounds)))
3685 (point))))))
3687 (defun markdown-bounds-of-thing-at-point (thing)
3688 "Call `bounds-of-thing-at-point' for THING with slight modifications.
3689 Does not include trailing newlines when THING is 'line. Handles the
3690 end of buffer case by setting both endpoints equal to the value of
3691 `point-max', since an empty region will trigger empty markup insertion.
3692 Return bounds of form (beg . end) if THING is found, or nil otherwise."
3693 (let* ((bounds (bounds-of-thing-at-point thing))
3694 (a (car bounds))
3695 (b (cdr bounds)))
3696 (when bounds
3697 (when (eq thing 'line)
3698 (cond ((and (eobp) (markdown-cur-line-blank-p))
3699 (setq a b))
3700 ((char-equal (char-before b) ?\^J)
3701 (setq b (1- b)))))
3702 (cons a b))))
3704 (defun markdown-reference-definition (reference)
3705 "Find out whether Markdown REFERENCE is defined.
3706 REFERENCE should not include the square brackets.
3707 When REFERENCE is defined, return a list of the form (text start end)
3708 containing the definition text itself followed by the start and end
3709 locations of the text. Otherwise, return nil.
3710 Leave match data for `markdown-regex-reference-definition'
3711 intact additional processing."
3712 (let ((reference (downcase reference)))
3713 (save-excursion
3714 (goto-char (point-min))
3715 (catch 'found
3716 (while (re-search-forward markdown-regex-reference-definition nil t)
3717 (when (string= reference (downcase (match-string-no-properties 2)))
3718 (throw 'found
3719 (list (match-string-no-properties 5)
3720 (match-beginning 5) (match-end 5)))))))))
3722 (defun markdown-get-defined-references ()
3723 "Return a list of all defined reference labels (not including square brackets)."
3724 (save-excursion
3725 (goto-char (point-min))
3726 (let (refs)
3727 (while (re-search-forward markdown-regex-reference-definition nil t)
3728 (let ((target (match-string-no-properties 2)))
3729 (cl-pushnew target refs :test #'equal)))
3730 (reverse refs))))
3732 (defun markdown-get-used-uris ()
3733 "Return a list of all used URIs in the buffer."
3734 (save-excursion
3735 (goto-char (point-min))
3736 (let (uris)
3737 (while (re-search-forward
3738 (concat "\\(?:" markdown-regex-link-inline
3739 "\\|" markdown-regex-angle-uri
3740 "\\|" markdown-regex-uri
3741 "\\|" markdown-regex-email
3742 "\\)")
3743 nil t)
3744 (unless (or (markdown-inline-code-at-point-p)
3745 (markdown-code-block-at-point-p))
3746 (cl-pushnew (or (match-string-no-properties 6)
3747 (match-string-no-properties 10)
3748 (match-string-no-properties 12)
3749 (match-string-no-properties 13))
3750 uris :test #'equal)))
3751 (reverse uris))))
3753 (defun markdown-inline-code-at-pos (pos)
3754 "Return non-nil if there is an inline code fragment at POS.
3755 Return nil otherwise. Set match data according to
3756 `markdown-match-code' upon success.
3757 This function searches the block for a code fragment that
3758 contains the point using `markdown-match-code'. We do this
3759 because `thing-at-point-looking-at' does not work reliably with
3760 `markdown-regex-code'.
3762 The match data is set as follows:
3763 Group 1 matches the opening backquotes.
3764 Group 2 matches the code fragment itself, without backquotes.
3765 Group 3 matches the closing backquotes."
3766 (save-excursion
3767 (goto-char pos)
3768 (let ((old-point (point))
3769 (end-of-block (progn (markdown-end-of-text-block) (point)))
3770 found)
3771 (markdown-beginning-of-text-block)
3772 (while (and (markdown-match-code end-of-block)
3773 (setq found t)
3774 (< (match-end 0) old-point)))
3775 (and found ; matched something
3776 (<= (match-beginning 0) old-point) ; match contains old-point
3777 (>= (match-end 0) old-point)))))
3779 (defun markdown-inline-code-at-pos-p (pos)
3780 "Return non-nil if there is an inline code fragment at POS.
3781 Like `markdown-inline-code-at-pos`, but preserves match data."
3782 (save-match-data (markdown-inline-code-at-pos pos)))
3784 (defun markdown-inline-code-at-point ()
3785 "Return non-nil if the point is at an inline code fragment.
3786 See `markdown-inline-code-at-pos' for details."
3787 (markdown-inline-code-at-pos (point)))
3789 (defun markdown-inline-code-at-point-p ()
3790 "Return non-nil if there is inline code at the point.
3791 This is a predicate function counterpart to
3792 `markdown-inline-code-at-point' which does not modify the match
3793 data. See `markdown-code-block-at-point-p' for code blocks."
3794 (save-match-data (markdown-inline-code-at-pos (point))))
3796 (make-obsolete 'markdown-code-at-point-p 'markdown-inline-code-at-point-p "v2.2")
3798 (defun markdown--code-block-at-pos-no-syntax (pos)
3799 "Return match data list if there may be a code block at POS.
3800 This includes pre blocks, tilde-fenced code blocks, and GFM
3801 quoted code blocks. Return nil otherwise. This function does not
3802 use text properties, which have not yet been set during the
3803 syntax propertization phase."
3804 (setq pos (save-excursion (goto-char pos) (point-at-bol)))
3805 (or (looking-at-p markdown-regex-pre)
3806 (markdown-get-enclosing-fenced-block-construct pos)))
3808 (defun markdown-code-block-at-pos (pos)
3809 "Return match data list if there is a code block at POS.
3810 This includes pre blocks, tilde-fenced code blocks, and GFM
3811 quoted code blocks. Return nil otherwise. This function uses
3812 cached text properties at the beginning of the line position for
3813 performance reasons, but therefore it must run after the syntax
3814 propertization phase."
3815 (setq pos (save-excursion (goto-char pos) (point-at-bol)))
3816 (or (get-text-property pos 'markdown-pre)
3817 ;;(markdown-get-enclosing-fenced-block-construct pos)
3818 (when (markdown-range-properties-exist
3819 pos pos '(markdown-gfm-block-begin
3820 markdown-gfm-code
3821 markdown-gfm-block-end
3822 markdown-tilde-fence-begin
3823 markdown-fenced-code
3824 markdown-tilde-fence-end
3825 markdown-yaml-metadata-begin
3826 markdown-yaml-metadata-section
3827 markdown-yaml-metadata-end))
3828 (markdown-get-enclosing-fenced-block-construct pos))
3829 ;; polymode removes text properties set by markdown-mode, so
3830 ;; check if `poly-markdown-mode' is active and whether the
3831 ;; `chunkmode' property is non-nil at POS.
3832 (and (bound-and-true-p poly-markdown-mode)
3833 (get-text-property pos 'chunkmode))))
3835 ;; Function was renamed to emphasize that it does not modify match-data.
3836 (defalias 'markdown-code-block-at-point 'markdown-code-block-at-point-p)
3838 (defun markdown-code-block-at-point-p ()
3839 "Return non-nil if there is a code block at the point.
3840 This includes pre blocks, tilde-fenced code blocks, and GFM
3841 quoted code blocks. This function does not modify the match
3842 data. See `markdown-inline-code-at-point-p' for inline code."
3843 (save-match-data (markdown-code-block-at-pos (point))))
3845 (defun markdown-heading-at-point ()
3846 "Return non-nil if there is a heading at the point.
3847 Set match data for `markdown-regex-header'."
3848 (let ((match-data (get-text-property (point) 'markdown-heading)))
3849 (when match-data
3850 (set-match-data match-data)
3851 t)))
3853 (defun markdown-pipe-at-bol-p ()
3854 "Return non-nil if the line begins with a pipe symbol.
3855 This may be useful for tables and Pandoc's line_blocks extension."
3856 (char-equal (char-after (point-at-bol)) ?|))
3859 ;;; Markdown Font Lock Matching Functions =====================================
3861 (defun markdown-range-property-any (begin end prop prop-values)
3862 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
3863 Also returns t if PROP is a list containing one of the PROP-VALUES.
3864 Return nil otherwise."
3865 (let (props)
3866 (catch 'found
3867 (dolist (loc (number-sequence begin end))
3868 (when (setq props (get-text-property loc prop))
3869 (cond ((listp props)
3870 ;; props is a list, check for membership
3871 (dolist (val prop-values)
3872 (when (memq val props) (throw 'found loc))))
3874 ;; props is a scalar, check for equality
3875 (dolist (val prop-values)
3876 (when (eq val props) (throw 'found loc))))))))))
3878 (defun markdown-range-properties-exist (begin end props)
3879 (cl-loop
3880 for loc in (number-sequence begin end)
3881 with result = nil
3882 while (not
3883 (setq result
3884 (cl-some (lambda (prop) (get-text-property loc prop)) props)))
3885 finally return result))
3887 (defun markdown-match-inline-generic (regex last &optional faceless)
3888 "Match inline REGEX from the point to LAST.
3889 When FACELESS is non-nil, do not return matches where faces have been applied."
3890 (when (re-search-forward regex last t)
3891 (let ((bounds (markdown-code-block-at-pos (match-beginning 1)))
3892 (face (and faceless (text-property-not-all
3893 (match-beginning 0) (match-end 0) 'face nil))))
3894 (cond
3895 ;; In code block: move past it and recursively search again
3896 (bounds
3897 (when (< (goto-char (cl-second bounds)) last)
3898 (markdown-match-inline-generic regex last faceless)))
3899 ;; When faces are found in the match range, skip over the match and
3900 ;; recursively search again.
3901 (face
3902 (when (< (goto-char (match-end 0)) last)
3903 (markdown-match-inline-generic regex last faceless)))
3904 ;; Keep match data and return t when in bounds.
3906 (<= (match-end 0) last))))))
3908 (defun markdown-match-code (last)
3909 "Match inline code fragments from point to LAST."
3910 (unless (bobp)
3911 (backward-char 1))
3912 (when (markdown-search-until-condition
3913 (lambda ()
3914 (and
3915 ;; Advance point in case of failure, but without exceeding last.
3916 (goto-char (min (1+ (match-beginning 1)) last))
3917 (not (markdown-in-comment-p (match-beginning 1)))
3918 (not (markdown-in-comment-p (match-end 1)))
3919 (not (markdown-code-block-at-pos (match-beginning 1)))))
3920 markdown-regex-code last t)
3921 (set-match-data (list (match-beginning 1) (match-end 1)
3922 (match-beginning 2) (match-end 2)
3923 (match-beginning 3) (match-end 3)
3924 (match-beginning 4) (match-end 4)))
3925 (goto-char (min (1+ (match-end 0)) last (point-max)))
3928 (defun markdown-match-bold (last)
3929 "Match inline bold from the point to LAST."
3930 (when (markdown-match-inline-generic markdown-regex-bold last)
3931 (let ((begin (match-beginning 2))
3932 (end (match-end 2)))
3933 (if (or (markdown-inline-code-at-pos-p begin)
3934 (markdown-inline-code-at-pos-p end)
3935 (markdown-in-comment-p)
3936 (markdown-range-property-any
3937 begin begin 'face '(markdown-url-face
3938 markdown-plain-url-face))
3939 (markdown-range-property-any
3940 begin end 'face '(markdown-hr-face
3941 markdown-math-face)))
3942 (progn (goto-char (min (1+ begin) last))
3943 (when (< (point) last)
3944 (markdown-match-italic last)))
3945 (set-match-data (list (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 t))))
3951 (defun markdown-match-italic (last)
3952 "Match inline italics from the point to LAST."
3953 (let ((regex (if (eq major-mode 'gfm-mode)
3954 markdown-regex-gfm-italic markdown-regex-italic)))
3955 (when (markdown-match-inline-generic regex last)
3956 (let ((begin (match-beginning 1))
3957 (end (match-end 1)))
3958 (if (or (markdown-inline-code-at-pos-p begin)
3959 (markdown-inline-code-at-pos-p end)
3960 (markdown-in-comment-p)
3961 (markdown-range-property-any
3962 begin begin 'face '(markdown-url-face
3963 markdown-plain-url-face))
3964 (markdown-range-property-any
3965 begin end 'face '(markdown-bold-face
3966 markdown-list-face
3967 markdown-hr-face
3968 markdown-math-face)))
3969 (progn (goto-char (min (1+ begin) last))
3970 (when (< (point) last)
3971 (markdown-match-italic last)))
3972 (set-match-data (list (match-beginning 1) (match-end 1)
3973 (match-beginning 2) (match-end 2)
3974 (match-beginning 3) (match-end 3)
3975 (match-beginning 4) (match-end 4)))
3976 t)))))
3978 (defun markdown-match-math-generic (regex last)
3979 "Match REGEX from point to LAST.
3980 REGEX is either `markdown-regex-math-inline-single' for matching
3981 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
3982 (when (and markdown-enable-math (markdown-match-inline-generic regex last))
3983 (let ((begin (match-beginning 1)) (end (match-end 1)))
3984 (prog1
3985 (if (or (markdown-range-property-any
3986 begin end 'face (list markdown-inline-code-face
3987 markdown-bold-face))
3988 (markdown-range-properties-exist
3989 begin end
3990 (markdown-get-fenced-block-middle-properties)))
3991 (markdown-match-math-generic regex last)
3993 (goto-char (1+ (match-end 0)))))))
3995 (defun markdown-match-list-items (last)
3996 "Match list items from point to LAST."
3997 (when (markdown-match-inline-generic markdown-regex-list last)
3998 (let ((begin (match-beginning 2))
3999 (end (match-end 2)))
4000 (if (or (markdown-range-property-any
4001 begin end 'face (list markdown-inline-code-face
4002 markdown-bold-face
4003 markdown-math-face))
4004 (markdown-range-properties-exist begin end '(markdown-hr))
4005 (markdown-in-comment-p))
4006 (progn (goto-char (min (1+ (match-end 0)) last))
4007 (markdown-match-list-items last))
4008 (set-match-data (list (match-beginning 0) (match-end 0)
4009 (match-beginning 1) (match-end 1)
4010 (match-beginning 2) (match-end 2)))
4011 (goto-char (1+ (match-end 0)))))))
4013 (defun markdown-match-math-single (last)
4014 "Match single quoted $..$ math from point to LAST."
4015 (markdown-match-math-generic markdown-regex-math-inline-single last))
4017 (defun markdown-match-math-double (last)
4018 "Match double quoted $$..$$ math from point to LAST."
4019 (markdown-match-math-generic markdown-regex-math-inline-double last))
4021 (defun markdown-match-math-display (last)
4022 "Match bracketed display math \[..\] and \\[..\\] from point to LAST."
4023 (markdown-match-math-generic markdown-regex-math-display last))
4025 (defun markdown-match-propertized-text (property last)
4026 "Match text with PROPERTY from point to LAST.
4027 Restore match data previously stored in PROPERTY."
4028 (let ((saved (get-text-property (point) property))
4029 pos)
4030 (unless saved
4031 (setq pos (next-single-char-property-change (point) property nil last))
4032 (setq saved (get-text-property pos property)))
4033 (when saved
4034 (set-match-data saved)
4035 ;; Step at least one character beyond point. Otherwise
4036 ;; `font-lock-fontify-keywords-region' infloops.
4037 (goto-char (min (1+ (max (match-end 0) (point)))
4038 (point-max)))
4039 saved)))
4041 (defun markdown-match-pre-blocks (last)
4042 "Match preformatted blocks from point to LAST.
4043 Use data stored in 'markdown-pre text property during syntax
4044 analysis."
4045 (markdown-match-propertized-text 'markdown-pre last))
4047 (defun markdown-match-gfm-code-blocks (last)
4048 "Match GFM quoted code blocks from point to LAST.
4049 Use data stored in 'markdown-gfm-code text property during syntax
4050 analysis."
4051 (markdown-match-propertized-text 'markdown-gfm-code last))
4053 (defun markdown-match-gfm-open-code-blocks (last)
4054 (markdown-match-propertized-text 'markdown-gfm-block-begin last))
4056 (defun markdown-match-gfm-close-code-blocks (last)
4057 (markdown-match-propertized-text 'markdown-gfm-block-end last))
4059 (defun markdown-match-fenced-code-blocks (last)
4060 "Match fenced code blocks from the point to LAST."
4061 (markdown-match-propertized-text 'markdown-fenced-code last))
4063 (defun markdown-match-fenced-start-code-block (last)
4064 (markdown-match-propertized-text 'markdown-tilde-fence-begin last))
4066 (defun markdown-match-fenced-end-code-block (last)
4067 (markdown-match-propertized-text 'markdown-tilde-fence-end last))
4069 (defun markdown-match-blockquotes (last)
4070 "Match blockquotes from point to LAST.
4071 Use data stored in 'markdown-blockquote text property during syntax
4072 analysis."
4073 (markdown-match-propertized-text 'markdown-blockquote last))
4075 (defun markdown-match-hr (last)
4076 "Match horizontal rules comments from the point to LAST."
4077 (markdown-match-propertized-text 'markdown-hr last))
4079 (defun markdown-match-comments (last)
4080 "Match HTML comments from the point to LAST."
4081 (when (and (skip-syntax-forward "^<" last))
4082 (let ((beg (point)))
4083 (when (and (skip-syntax-forward "^>" last) (< (point) last))
4084 (forward-char)
4085 (set-match-data (list beg (point)))
4086 t))))
4088 (defun markdown-match-generic-links (last ref)
4089 "Match inline links from point to LAST.
4090 When REF is non-nil, match reference links instead of standard
4091 links with URLs."
4092 ;; Search for the next potential link (not in a code block).
4093 (while (and (progn
4094 ;; Clear match data to test for a match after functions returns.
4095 (set-match-data nil)
4096 ;; Preliminary regular expression search so we can return
4097 ;; quickly upon failure. This doesn't handle malformed links
4098 ;; or nested square brackets well, so if it passes we back up
4099 ;; continue with a more precise search.
4100 (re-search-forward
4101 (if ref
4102 markdown-regex-link-reference
4103 markdown-regex-link-inline)
4104 last 'limit))
4105 ;; Keep searching if this is in a code block, inline
4106 ;; code, or a comment, or if it is include syntax.
4107 (or (markdown-code-block-at-point-p)
4108 (markdown-inline-code-at-pos-p (match-beginning 0))
4109 (markdown-inline-code-at-pos-p (match-end 0))
4110 (markdown-in-comment-p)
4111 (and (char-equal (char-after (point-at-bol)) ?<)
4112 (char-equal (char-after (1+ (point-at-bol))) ?<)))
4113 (< (point) last)))
4114 ;; Match opening exclamation point (optional) and left bracket.
4115 (when (match-beginning 2)
4116 (let* ((bang (match-beginning 1))
4117 (first-begin (match-beginning 2))
4118 ;; Find end of block to prevent matching across blocks.
4119 (end-of-block (save-excursion
4120 (progn
4121 (goto-char (match-beginning 2))
4122 (markdown-end-of-text-block)
4123 (point))))
4124 ;; Move over balanced expressions to closing right bracket.
4125 ;; Catch unbalanced expression errors and return nil.
4126 (first-end (condition-case nil
4127 (and (goto-char first-begin)
4128 (scan-sexps (point) 1))
4129 (error nil)))
4130 ;; Continue with point at CONT-POINT upon failure.
4131 (cont-point (min (1+ first-begin) last))
4132 second-begin second-end url-begin url-end
4133 title-begin title-end)
4134 ;; When bracket found, in range, and followed by a left paren/bracket...
4135 (when (and first-end (< first-end end-of-block) (goto-char first-end)
4136 (char-equal (char-after (point)) (if ref ?\[ ?\()))
4137 ;; Scan across balanced expressions for closing parenthesis/bracket.
4138 (setq second-begin (point)
4139 second-end (condition-case nil
4140 (scan-sexps (point) 1)
4141 (error nil)))
4142 ;; Check that closing parenthesis/bracket is in range.
4143 (if (and second-end (<= second-end end-of-block) (<= second-end last))
4144 (progn
4145 ;; Search for (optional) title inside closing parenthesis
4146 (when (and (not ref) (search-forward "\"" second-end t))
4147 (setq title-begin (1- (point))
4148 title-end (and (goto-char second-end)
4149 (search-backward "\"" (1+ title-begin) t))
4150 title-end (and title-end (1+ title-end))))
4151 ;; Store URL/reference range
4152 (setq url-begin (1+ second-begin)
4153 url-end (1- (or title-begin second-end)))
4154 ;; Set match data, move point beyond link, and return
4155 (set-match-data
4156 (list (or bang first-begin) second-end ; 0 - all
4157 bang (and bang (1+ bang)) ; 1 - bang
4158 first-begin (1+ first-begin) ; 2 - markup
4159 (1+ first-begin) (1- first-end) ; 3 - link text
4160 (1- first-end) first-end ; 4 - markup
4161 second-begin (1+ second-begin) ; 5 - markup
4162 url-begin url-end ; 6 - url/reference
4163 title-begin title-end ; 7 - title
4164 (1- second-end) second-end)) ; 8 - markup
4165 ;; Nullify cont-point and leave point at end and
4166 (setq cont-point nil)
4167 (goto-char second-end))
4168 ;; If no closing parenthesis in range, update continuation point
4169 (setq cont-point (min end-of-block second-begin))))
4170 (cond
4171 ;; On failure, continue searching at cont-point
4172 ((and cont-point (< cont-point last))
4173 (goto-char cont-point)
4174 (markdown-match-generic-links last ref))
4175 ;; No more text, return nil
4176 ((and cont-point (= cont-point last))
4177 nil)
4178 ;; Return t if a match occurred
4179 (t t)))))
4181 (defun markdown-match-inline-links (last)
4182 "Match standard inline links from point to LAST."
4183 (markdown-match-generic-links last nil))
4185 (defun markdown-match-reference-links (last)
4186 "Match inline reference links from point to LAST."
4187 (markdown-match-generic-links last t))
4189 (defun markdown-match-angle-uris (last)
4190 "Match angle bracket URIs from point to LAST."
4191 (when (markdown-match-inline-generic markdown-regex-angle-uri last)
4192 (goto-char (1+ (match-end 0)))))
4194 (defun markdown-match-plain-uris (last)
4195 "Match plain URIs from point to LAST."
4196 (when (markdown-match-inline-generic markdown-regex-uri last t)
4197 (goto-char (1+ (match-end 0)))))
4199 (defvar markdown-conditional-search-function #'re-search-forward
4200 "Conditional search function used in `markdown-search-until-condition'.
4201 Made into a variable to allow for dynamic let-binding.")
4203 (defun markdown-search-until-condition (condition &rest args)
4204 (let (ret)
4205 (while (and (not ret) (apply markdown-conditional-search-function args))
4206 (setq ret (funcall condition)))
4207 ret))
4209 (defun markdown-match-generic-metadata (regexp last)
4210 "Match metadata declarations specified by REGEXP from point to LAST.
4211 These declarations must appear inside a metadata block that begins at
4212 the beginning of the buffer and ends with a blank line (or the end of
4213 the buffer)."
4214 (let* ((first (point))
4215 (end-re "\n[ \t]*\n\\|\n\\'\\|\\'")
4216 (block-begin (goto-char 1))
4217 (block-end (re-search-forward end-re nil t)))
4218 (if (and block-end (> first block-end))
4219 ;; Don't match declarations if there is no metadata block or if
4220 ;; the point is beyond the block. Move point to point-max to
4221 ;; prevent additional searches and return return nil since nothing
4222 ;; was found.
4223 (progn (goto-char (point-max)) nil)
4224 ;; If a block was found that begins before LAST and ends after
4225 ;; point, search for declarations inside it. If the starting is
4226 ;; before the beginning of the block, start there. Otherwise,
4227 ;; move back to FIRST.
4228 (goto-char (if (< first block-begin) block-begin first))
4229 (if (re-search-forward regexp (min last block-end) t)
4230 ;; If a metadata declaration is found, set match-data and return t.
4231 (let ((key-beginning (match-beginning 1))
4232 (key-end (match-end 1))
4233 (markup-begin (match-beginning 2))
4234 (markup-end (match-end 2))
4235 (value-beginning (match-beginning 3)))
4236 (set-match-data (list key-beginning (point) ; complete metadata
4237 key-beginning key-end ; key
4238 markup-begin markup-end ; markup
4239 value-beginning (point))) ; value
4241 ;; Otherwise, move the point to last and return nil
4242 (goto-char last)
4243 nil))))
4245 (defun markdown-match-declarative-metadata (last)
4246 "Match declarative metadata from the point to LAST."
4247 (markdown-match-generic-metadata markdown-regex-declarative-metadata last))
4249 (defun markdown-match-pandoc-metadata (last)
4250 "Match Pandoc metadata from the point to LAST."
4251 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
4253 (defun markdown-match-yaml-metadata-begin (last)
4254 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last))
4256 (defun markdown-match-yaml-metadata-end (last)
4257 (markdown-match-propertized-text 'markdown-yaml-metadata-end last))
4259 (defun markdown-match-yaml-metadata-key (last)
4260 (markdown-match-propertized-text 'markdown-metadata-key last))
4262 (defun markdown-match-wiki-link (last)
4263 "Match wiki links from point to LAST."
4264 (when (and markdown-enable-wiki-links
4265 (not markdown-wiki-link-fontify-missing)
4266 (markdown-match-inline-generic markdown-regex-wiki-link last))
4267 (let ((begin (match-beginning 1)) (end (match-end 1)))
4268 (if (or (markdown-in-comment-p begin)
4269 (markdown-in-comment-p end)
4270 (markdown-inline-code-at-pos-p begin)
4271 (markdown-inline-code-at-pos-p end)
4272 (markdown-code-block-at-pos begin))
4273 (progn (goto-char (min (1+ begin) last))
4274 (when (< (point) last)
4275 (markdown-match-wiki-link last)))
4276 (set-match-data (list begin end))
4277 t))))
4279 (defun markdown-match-inline-attributes (last)
4280 "Match inline attributes from point to LAST."
4281 (when (markdown-match-inline-generic markdown-regex-inline-attributes last)
4282 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
4283 (markdown-inline-code-at-pos-p (match-end 0))
4284 (markdown-in-comment-p))
4285 t)))
4287 (defun markdown-match-leanpub-sections (last)
4288 "Match Leanpub section markers from point to LAST."
4289 (when (markdown-match-inline-generic markdown-regex-leanpub-sections last)
4290 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
4291 (markdown-inline-code-at-pos-p (match-end 0))
4292 (markdown-in-comment-p))
4293 t)))
4295 (defun markdown-match-includes (last)
4296 "Match include statements from point to LAST.
4297 Sets match data for the following seven groups:
4298 Group 1: opening two angle brackets
4299 Group 2: opening title delimiter (optional)
4300 Group 3: title text (optional)
4301 Group 4: closing title delimiter (optional)
4302 Group 5: opening filename delimiter
4303 Group 6: filename
4304 Group 7: closing filename delimiter"
4305 (when (markdown-match-inline-generic markdown-regex-include last)
4306 (let ((valid (not (or (markdown-in-comment-p (match-beginning 0))
4307 (markdown-in-comment-p (match-end 0))
4308 (markdown-code-block-at-pos (match-beginning 0))))))
4309 (cond
4310 ;; Parentheses and maybe square brackets, but no curly braces:
4311 ;; match optional title in square brackets and file in parentheses.
4312 ((and valid (match-beginning 5)
4313 (not (match-beginning 8)))
4314 (set-match-data (list (match-beginning 1) (match-end 7)
4315 (match-beginning 1) (match-end 1)
4316 (match-beginning 2) (match-end 2)
4317 (match-beginning 3) (match-end 3)
4318 (match-beginning 4) (match-end 4)
4319 (match-beginning 5) (match-end 5)
4320 (match-beginning 6) (match-end 6)
4321 (match-beginning 7) (match-end 7))))
4322 ;; Only square brackets present: match file in square brackets.
4323 ((and valid (match-beginning 2)
4324 (not (match-beginning 5))
4325 (not (match-beginning 7)))
4326 (set-match-data (list (match-beginning 1) (match-end 4)
4327 (match-beginning 1) (match-end 1)
4328 nil nil
4329 nil nil
4330 nil nil
4331 (match-beginning 2) (match-end 2)
4332 (match-beginning 3) (match-end 3)
4333 (match-beginning 4) (match-end 4))))
4334 ;; Only curly braces present: match file in curly braces.
4335 ((and valid (match-beginning 8)
4336 (not (match-beginning 2))
4337 (not (match-beginning 5)))
4338 (set-match-data (list (match-beginning 1) (match-end 10)
4339 (match-beginning 1) (match-end 1)
4340 nil nil
4341 nil nil
4342 nil nil
4343 (match-beginning 8) (match-end 8)
4344 (match-beginning 9) (match-end 9)
4345 (match-beginning 10) (match-end 10))))
4347 ;; Not a valid match, move to next line and search again.
4348 (forward-line)
4349 (when (< (point) last)
4350 (setq valid (markdown-match-includes last)))))
4351 valid)))
4353 (defun markdown-match-html-tag (last)
4354 "Match HTML tags from point to LAST."
4355 (when (and markdown-enable-html
4356 (markdown-match-inline-generic markdown-regex-html-tag last t))
4357 (set-match-data (list (match-beginning 0) (match-end 0)
4358 (match-beginning 1) (match-end 1)
4359 (match-beginning 2) (match-end 2)
4360 (match-beginning 9) (match-end 9)))
4364 ;;; Markdown Font Fontification Functions =====================================
4366 (defun markdown--first-displayable (seq)
4367 "Return the first displayable character or string in SEQ.
4368 SEQ may be an atom or a sequence."
4369 (let ((seq (if (listp seq) seq (list seq))))
4370 (cond ((stringp (car seq))
4371 (cl-find-if
4372 (lambda (str)
4373 (and (mapcar #'char-displayable-p (string-to-list str))))
4374 seq))
4375 ((characterp (car seq))
4376 (cl-find-if #'char-displayable-p seq)))))
4378 (defun markdown--marginalize-string (level)
4379 "Generate atx markup string of given LEVEL for left margin."
4380 (let ((margin-left-space-count
4381 (- markdown-marginalize-headers-margin-width level)))
4382 (concat (make-string margin-left-space-count ? )
4383 (make-string level ?#))))
4385 (defun markdown-marginalize-update-current ()
4386 "Update the window configuration to create a left margin."
4387 ;; Emacs 25 or later is needed for window-font-width and default-font-width.
4388 (if (and (fboundp 'window-font-width) (fboundp 'default-font-width))
4389 (let* ((header-delimiter-font-width
4390 (window-font-width nil 'markdown-header-delimiter-face))
4391 (margin-pixel-width (* markdown-marginalize-headers-margin-width
4392 header-delimiter-font-width))
4393 (margin-char-width (/ margin-pixel-width (default-font-width))))
4394 (set-window-margins nil margin-char-width))
4395 ;; As a fallback, simply set margin based on character count.
4396 (set-window-margins nil markdown-marginalize-headers-margin-width)))
4398 (defun markdown-fontify-headings (last)
4399 "Add text properties to headings from point to LAST."
4400 (when (markdown-match-propertized-text 'markdown-heading last)
4401 (let* ((level (markdown-outline-level))
4402 (heading-face
4403 (intern (format "markdown-header-face-%d" level)))
4404 (heading-props `(face ,heading-face))
4405 (left-markup-props
4406 `(face markdown-header-delimiter-face
4407 ,@(cond
4408 (markdown-hide-markup
4409 `(display ""))
4410 (markdown-marginalize-headers
4411 `(display ((margin left-margin)
4412 ,(markdown--marginalize-string level)))))))
4413 (right-markup-props
4414 `(face markdown-header-delimiter-face
4415 ,@(when markdown-hide-markup `(display ""))))
4416 (rule-props `(face markdown-header-rule-face
4417 ,@(when markdown-hide-markup `(display "")))))
4418 (if (match-end 1)
4419 ;; Setext heading
4420 (progn (add-text-properties
4421 (match-beginning 1) (match-end 1) heading-props)
4422 (if (= level 1)
4423 (add-text-properties
4424 (match-beginning 2) (match-end 2) rule-props)
4425 (add-text-properties
4426 (match-beginning 3) (match-end 3) rule-props)))
4427 ;; atx heading
4428 (add-text-properties
4429 (match-beginning 4) (match-end 4) left-markup-props)
4430 (add-text-properties
4431 (match-beginning 5) (match-end 5) heading-props)
4432 (when (match-end 6)
4433 (add-text-properties
4434 (match-beginning 6) (match-end 6) right-markup-props))))
4437 (defun markdown-fontify-tables (last)
4438 (when (and (re-search-forward "|" last t)
4439 (markdown-table-at-point-p))
4440 (font-lock-append-text-property
4441 (line-beginning-position) (min (1+ (line-end-position)) (point-max))
4442 'face 'markdown-table-face)
4443 (forward-line 1)
4446 (defun markdown-fontify-blockquotes (last)
4447 "Apply font-lock properties to blockquotes from point to LAST."
4448 (when (markdown-match-blockquotes last)
4449 (let ((display-string
4450 (markdown--first-displayable markdown-blockquote-display-char)))
4451 (add-text-properties
4452 (match-beginning 1) (match-end 1)
4453 (if markdown-hide-markup
4454 `(face markdown-blockquote-face display ,display-string)
4455 `(face markdown-markup-face)))
4456 (font-lock-append-text-property
4457 (match-beginning 0) (match-end 0) 'face 'markdown-blockquote-face)
4458 t)))
4460 (defun markdown-fontify-list-items (last)
4461 "Apply font-lock properties to list markers from point to LAST."
4462 (when (markdown-match-list-items last)
4463 (let* ((indent (length (match-string-no-properties 1)))
4464 (level (/ indent 4)) ;; level = 0, 1, 2, ...
4465 (bullet (nth (mod level (length markdown-list-item-bullets))
4466 markdown-list-item-bullets)))
4467 (add-text-properties
4468 (match-beginning 2) (match-end 2) '(face markdown-list-face))
4469 (when markdown-hide-markup
4470 (cond
4471 ;; Unordered lists
4472 ((string-match-p "[\\*\\+-]" (match-string 2))
4473 (add-text-properties
4474 (match-beginning 2) (match-end 2) `(display ,bullet)))
4475 ;; Definition lists
4476 ((string-equal ":" (match-string 2))
4477 (let ((display-string
4478 (char-to-string (markdown--first-displayable
4479 markdown-definition-display-char))))
4480 (add-text-properties (match-beginning 2) (match-end 2)
4481 `(display ,display-string)))))))
4484 (defun markdown-fontify-hrs (last)
4485 "Add text properties to horizontal rules from point to LAST."
4486 (when (markdown-match-hr last)
4487 (let ((hr-char (markdown--first-displayable markdown-hr-display-char)))
4488 (add-text-properties
4489 (match-beginning 0) (match-end 0)
4490 `(face markdown-hr-face
4491 font-lock-multiline t
4492 ,@(when (and markdown-hide-markup hr-char)
4493 `(display ,(make-string
4494 (window-body-width) hr-char)))))
4495 t)))
4497 (defun markdown-fontify-sub-superscripts (last)
4498 "Apply text properties to sub- and superscripts from point to LAST."
4499 (when (markdown-search-until-condition
4500 (lambda () (and (not (markdown-code-block-at-point-p))
4501 (not (markdown-inline-code-at-point-p))
4502 (not (markdown-in-comment-p))))
4503 markdown-regex-sub-superscript last t)
4504 (let* ((subscript-p (string= (match-string 2) "~"))
4505 (props
4506 (if subscript-p
4507 (car markdown-sub-superscript-display)
4508 (cdr markdown-sub-superscript-display)))
4509 (mp (list 'face 'markdown-markup-face
4510 'invisible 'markdown-markup)))
4511 (when markdown-hide-markup
4512 (put-text-property (match-beginning 3) (match-end 3)
4513 'display props))
4514 (add-text-properties (match-beginning 2) (match-end 2) mp)
4515 (add-text-properties (match-beginning 4) (match-end 4) mp)
4516 t)))
4519 ;;; Syntax Table ==============================================================
4521 (defvar markdown-mode-syntax-table
4522 (let ((tab (make-syntax-table text-mode-syntax-table)))
4523 (modify-syntax-entry ?\" "." tab)
4524 tab)
4525 "Syntax table for `markdown-mode'.")
4528 ;;; Element Insertion =========================================================
4530 (defun markdown-ensure-blank-line-before ()
4531 "If previous line is not already blank, insert a blank line before point."
4532 (unless (bolp) (insert "\n"))
4533 (unless (or (bobp) (looking-back "\n\\s-*\n" nil)) (insert "\n")))
4535 (defun markdown-ensure-blank-line-after ()
4536 "If following line is not already blank, insert a blank line after point.
4537 Return the point where it was originally."
4538 (save-excursion
4539 (unless (eolp) (insert "\n"))
4540 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
4542 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
4543 "Insert the strings S1 and S2, wrapping around region or THING.
4544 If a region is specified by the optional BEG and END arguments,
4545 wrap the strings S1 and S2 around that region.
4546 If there is an active region, wrap the strings S1 and S2 around
4547 the region. If there is not an active region but the point is at
4548 THING, wrap that thing (which defaults to word). Otherwise, just
4549 insert S1 and S2 and place the point in between. Return the
4550 bounds of the entire wrapped string, or nil if nothing was wrapped
4551 and S1 and S2 were only inserted."
4552 (let (a b bounds new-point)
4553 (cond
4554 ;; Given region
4555 ((and beg end)
4556 (setq a beg
4557 b end
4558 new-point (+ (point) (length s1))))
4559 ;; Active region
4560 ((markdown-use-region-p)
4561 (setq a (region-beginning)
4562 b (region-end)
4563 new-point (+ (point) (length s1))))
4564 ;; Thing (word) at point
4565 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
4566 (setq a (car bounds)
4567 b (cdr bounds)
4568 new-point (+ (point) (length s1))))
4569 ;; No active region and no word
4571 (setq a (point)
4572 b (point))))
4573 (goto-char b)
4574 (insert s2)
4575 (goto-char a)
4576 (insert s1)
4577 (when new-point (goto-char new-point))
4578 (if (= a b)
4580 (setq b (+ b (length s1) (length s2)))
4581 (cons a b))))
4583 (defun markdown-point-after-unwrap (cur prefix suffix)
4584 "Return desired position of point after an unwrapping operation.
4585 CUR gives the position of the point before the operation.
4586 Additionally, two cons cells must be provided. PREFIX gives the
4587 bounds of the prefix string and SUFFIX gives the bounds of the
4588 suffix string."
4589 (cond ((< cur (cdr prefix)) (car prefix))
4590 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
4591 ((<= cur (cdr suffix))
4592 (- cur (+ (- (cdr prefix) (car prefix))
4593 (- cur (car suffix)))))
4594 (t cur)))
4596 (defun markdown-unwrap-thing-at-point (regexp all text)
4597 "Remove prefix and suffix of thing at point and reposition the point.
4598 When the thing at point matches REGEXP, replace the subexpression
4599 ALL with the string in subexpression TEXT. Reposition the point
4600 in an appropriate location accounting for the removal of prefix
4601 and suffix strings. Return new bounds of string from group TEXT.
4602 When REGEXP is nil, assumes match data is already set."
4603 (when (or (null regexp)
4604 (thing-at-point-looking-at regexp))
4605 (let ((cur (point))
4606 (prefix (cons (match-beginning all) (match-beginning text)))
4607 (suffix (cons (match-end text) (match-end all)))
4608 (bounds (cons (match-beginning text) (match-end text))))
4609 ;; Replace the thing at point
4610 (replace-match (match-string text) t t nil all)
4611 ;; Reposition the point
4612 (goto-char (markdown-point-after-unwrap cur prefix suffix))
4613 ;; Adjust bounds
4614 (setq bounds (cons (car prefix)
4615 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
4617 (defun markdown-unwrap-things-in-region (beg end regexp all text)
4618 "Remove prefix and suffix of all things in region from BEG to END.
4619 When a thing in the region matches REGEXP, replace the
4620 subexpression ALL with the string in subexpression TEXT.
4621 Return a cons cell containing updated bounds for the region."
4622 (save-excursion
4623 (goto-char beg)
4624 (let ((removed 0) len-all len-text)
4625 (while (re-search-forward regexp (- end removed) t)
4626 (setq len-all (length (match-string-no-properties all)))
4627 (setq len-text (length (match-string-no-properties text)))
4628 (setq removed (+ removed (- len-all len-text)))
4629 (replace-match (match-string text) t t nil all))
4630 (cons beg (- end removed)))))
4632 (defun markdown-insert-hr (arg)
4633 "Insert or replace a horizonal rule.
4634 By default, use the first element of `markdown-hr-strings'. When
4635 ARG is non-nil, as when given a prefix, select a different
4636 element as follows. When prefixed with \\[universal-argument],
4637 use the last element of `markdown-hr-strings' instead. When
4638 prefixed with an integer from 1 to the length of
4639 `markdown-hr-strings', use the element in that position instead."
4640 (interactive "*P")
4641 (when (thing-at-point-looking-at markdown-regex-hr)
4642 (delete-region (match-beginning 0) (match-end 0)))
4643 (markdown-ensure-blank-line-before)
4644 (cond ((equal arg '(4))
4645 (insert (car (reverse markdown-hr-strings))))
4646 ((and (integerp arg) (> arg 0)
4647 (<= arg (length markdown-hr-strings)))
4648 (insert (nth (1- arg) markdown-hr-strings)))
4650 (insert (car markdown-hr-strings))))
4651 (markdown-ensure-blank-line-after))
4653 (defun markdown-insert-bold ()
4654 "Insert markup to make a region or word bold.
4655 If there is an active region, make the region bold. If the point
4656 is at a non-bold word, make the word bold. If the point is at a
4657 bold word or phrase, remove the bold markup. Otherwise, simply
4658 insert bold delimiters and place the point in between them."
4659 (interactive)
4660 (let ((delim (if markdown-bold-underscore "__" "**")))
4661 (if (markdown-use-region-p)
4662 ;; Active region
4663 (let ((bounds (markdown-unwrap-things-in-region
4664 (region-beginning) (region-end)
4665 markdown-regex-bold 2 4)))
4666 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4667 ;; Bold markup removal, bold word at point, or empty markup insertion
4668 (if (thing-at-point-looking-at markdown-regex-bold)
4669 (markdown-unwrap-thing-at-point nil 2 4)
4670 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4672 (defun markdown-insert-italic ()
4673 "Insert markup to make a region or word italic.
4674 If there is an active region, make the region italic. If the point
4675 is at a non-italic word, make the word italic. If the point is at an
4676 italic word or phrase, remove the italic markup. Otherwise, simply
4677 insert italic delimiters and place the point in between them."
4678 (interactive)
4679 (let ((delim (if markdown-italic-underscore "_" "*")))
4680 (if (markdown-use-region-p)
4681 ;; Active region
4682 (let ((bounds (markdown-unwrap-things-in-region
4683 (region-beginning) (region-end)
4684 markdown-regex-italic 1 3)))
4685 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4686 ;; Italic markup removal, italic word at point, or empty markup insertion
4687 (if (thing-at-point-looking-at markdown-regex-italic)
4688 (markdown-unwrap-thing-at-point nil 1 3)
4689 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4691 (defun markdown-insert-strike-through ()
4692 "Insert markup to make a region or word strikethrough.
4693 If there is an active region, make the region strikethrough. If the point
4694 is at a non-bold word, make the word strikethrough. If the point is at a
4695 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
4696 simply insert bold delimiters and place the point in between them."
4697 (interactive)
4698 (let ((delim "~~"))
4699 (if (markdown-use-region-p)
4700 ;; Active region
4701 (let ((bounds (markdown-unwrap-things-in-region
4702 (region-beginning) (region-end)
4703 markdown-regex-strike-through 2 4)))
4704 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4705 ;; Strikethrough markup removal, strikethrough word at point, or empty markup insertion
4706 (if (thing-at-point-looking-at markdown-regex-strike-through)
4707 (markdown-unwrap-thing-at-point nil 2 4)
4708 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4710 (defun markdown-insert-code ()
4711 "Insert markup to make a region or word an inline code fragment.
4712 If there is an active region, make the region an inline code
4713 fragment. If the point is at a word, make the word an inline
4714 code fragment. Otherwise, simply insert code delimiters and
4715 place the point in between them."
4716 (interactive)
4717 (if (markdown-use-region-p)
4718 ;; Active region
4719 (let ((bounds (markdown-unwrap-things-in-region
4720 (region-beginning) (region-end)
4721 markdown-regex-code 1 3)))
4722 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
4723 ;; Code markup removal, code markup for word, or empty markup insertion
4724 (if (markdown-inline-code-at-point)
4725 (markdown-unwrap-thing-at-point nil 0 2)
4726 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
4728 (defun markdown-insert-kbd ()
4729 "Insert markup to wrap region or word in <kbd> tags.
4730 If there is an active region, use the region. If the point is at
4731 a word, use the word. Otherwise, simply insert <kbd> tags and
4732 place the point in between them."
4733 (interactive)
4734 (if (markdown-use-region-p)
4735 ;; Active region
4736 (let ((bounds (markdown-unwrap-things-in-region
4737 (region-beginning) (region-end)
4738 markdown-regex-kbd 0 2)))
4739 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil (car bounds) (cdr bounds)))
4740 ;; Markup removal, markup for word, or empty markup insertion
4741 (if (thing-at-point-looking-at markdown-regex-kbd)
4742 (markdown-unwrap-thing-at-point nil 0 2)
4743 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil))))
4745 (defun markdown-insert-inline-link (text url &optional title)
4746 "Insert an inline link with TEXT pointing to URL.
4747 Optionally, the user can provide a TITLE."
4748 (let ((cur (point)))
4749 (setq title (and title (concat " \"" title "\"")))
4750 (insert (concat "[" text "](" url title ")"))
4751 (cond ((not text) (goto-char (+ 1 cur)))
4752 ((not url) (goto-char (+ 3 (length text) cur))))))
4754 (defun markdown-insert-inline-image (text url &optional title)
4755 "Insert an inline link with alt TEXT pointing to URL.
4756 Optionally, also provide a TITLE."
4757 (let ((cur (point)))
4758 (setq title (and title (concat " \"" title "\"")))
4759 (insert (concat "![" text "](" url title ")"))
4760 (cond ((not text) (goto-char (+ 2 cur)))
4761 ((not url) (goto-char (+ 4 (length text) cur))))))
4763 (defun markdown-insert-reference-link (text label &optional url title)
4764 "Insert a reference link and, optionally, a reference definition.
4765 The link TEXT will be inserted followed by the optional LABEL.
4766 If a URL is given, also insert a definition for the reference
4767 LABEL according to `markdown-reference-location'. If a TITLE is
4768 given, it will be added to the end of the reference definition
4769 and will be used to populate the title attribute when converted
4770 to XHTML. If URL is nil, insert only the link portion (for
4771 example, when a reference label is already defined)."
4772 (insert (concat "[" text "][" label "]"))
4773 (when url
4774 (markdown-insert-reference-definition
4775 (if (string-equal label "") text label)
4776 url title)))
4778 (defun markdown-insert-reference-image (text label &optional url title)
4779 "Insert a reference image and, optionally, a reference definition.
4780 The alt TEXT will be inserted followed by the optional LABEL.
4781 If a URL is given, also insert a definition for the reference
4782 LABEL according to `markdown-reference-location'. If a TITLE is
4783 given, it will be added to the end of the reference definition
4784 and will be used to populate the title attribute when converted
4785 to XHTML. If URL is nil, insert only the link portion (for
4786 example, when a reference label is already defined)."
4787 (insert (concat "![" text "][" label "]"))
4788 (when url
4789 (markdown-insert-reference-definition
4790 (if (string-equal label "") text label)
4791 url title)))
4793 (defun markdown-insert-reference-definition (label &optional url title)
4794 "Add definition for reference LABEL with URL and TITLE.
4795 LABEL is a Markdown reference label without square brackets.
4796 URL and TITLE are optional. When given, the TITLE will
4797 be used to populate the title attribute when converted to XHTML."
4798 ;; END specifies where to leave the point upon return
4799 (let ((end (point)))
4800 (cl-case markdown-reference-location
4801 (end (goto-char (point-max)))
4802 (immediately (markdown-end-of-text-block))
4803 (subtree (markdown-end-of-subtree))
4804 (header (markdown-end-of-defun)))
4805 ;; Skip backwards over local variables. This logic is similar to the one
4806 ;; used in ‘hack-local-variables’.
4807 (when (and enable-local-variables (eobp))
4808 (search-backward "\n\f" (max (- (point) 3000) (point-min)) :move)
4809 (when (let ((case-fold-search t))
4810 (search-forward "Local Variables:" nil :move))
4811 (beginning-of-line 0)
4812 (when (eq (char-before) ?\n) (backward-char))))
4813 (unless (or (markdown-cur-line-blank-p)
4814 (thing-at-point-looking-at markdown-regex-reference-definition))
4815 (insert "\n"))
4816 (insert "\n[" label "]: ")
4817 (if url
4818 (insert url)
4819 ;; When no URL is given, leave point at END following the colon
4820 (setq end (point)))
4821 (when (> (length title) 0)
4822 (insert " \"" title "\""))
4823 (unless (looking-at-p "\n")
4824 (insert "\n"))
4825 (goto-char end)
4826 (when url
4827 (message
4828 (markdown--substitute-command-keys
4829 "Reference [%s] was defined, press \\[markdown-do] to jump there")
4830 label))))
4832 (define-obsolete-function-alias
4833 'markdown-insert-inline-link-dwim 'markdown-insert-link "v2.3")
4834 (define-obsolete-function-alias
4835 'markdown-insert-reference-link-dwim 'markdown-insert-link "v2.3")
4837 (defun markdown--insert-link-or-image (image)
4838 "Interactively insert new or update an existing link or image.
4839 When IMAGE is non-nil, insert an image. Otherwise, insert a link.
4840 This is an internal function called by
4841 `markdown-insert-link' and `markdown-insert-image'."
4842 (cl-multiple-value-bind (begin end text uri ref title)
4843 (if (markdown-use-region-p)
4844 ;; Use region as either link text or URL as appropriate.
4845 (let ((region (buffer-substring-no-properties
4846 (region-beginning) (region-end))))
4847 (if (string-match markdown-regex-uri region)
4848 ;; Region contains a URL; use it as such.
4849 (list (region-beginning) (region-end)
4850 nil (match-string 0 region) nil nil)
4851 ;; Region doesn't contain a URL, so use it as text.
4852 (list (region-beginning) (region-end)
4853 region nil nil nil)))
4854 ;; Extract and use properties of existing link, if any.
4855 (markdown-link-at-pos (point)))
4856 (let* ((ref (when ref (concat "[" ref "]")))
4857 (defined-refs (append
4858 (mapcar (lambda (ref) (concat "[" ref "]"))
4859 (markdown-get-defined-references))))
4860 (used-uris (markdown-get-used-uris))
4861 (uri-or-ref (completing-read
4862 "URL or [reference]: "
4863 (append defined-refs used-uris)
4864 nil nil (or uri ref)))
4865 (ref (cond ((string-match "\\`\\[\\(.*\\)\\]\\'" uri-or-ref)
4866 (match-string 1 uri-or-ref))
4867 ((string-equal "" uri-or-ref)
4868 "")))
4869 (uri (unless ref uri-or-ref))
4870 (text-prompt (if image
4871 "Alt text: "
4872 (if ref
4873 "Link text: "
4874 "Link text (blank for plain URL): ")))
4875 (text (read-string text-prompt text))
4876 (text (if (= (length text) 0) nil text))
4877 (plainp (and uri (not text)))
4878 (implicitp (string-equal ref ""))
4879 (ref (if implicitp text ref))
4880 (definedp (and ref (markdown-reference-definition ref)))
4881 (ref-url (unless (or uri definedp)
4882 (completing-read "Reference URL: " used-uris)))
4883 (title (unless (or plainp definedp)
4884 (read-string "Title (tooltip text, optional): " title)))
4885 (title (if (= (length title) 0) nil title)))
4886 (when (and image implicitp)
4887 (user-error "Reference required: implicit image references are invalid"))
4888 (when (and begin end)
4889 (delete-region begin end))
4890 (cond
4891 ((and (not image) uri text)
4892 (markdown-insert-inline-link text uri title))
4893 ((and image uri text)
4894 (markdown-insert-inline-image text uri title))
4895 ((and ref text)
4896 (if image
4897 (markdown-insert-reference-image text (unless implicitp ref) nil title)
4898 (markdown-insert-reference-link text (unless implicitp ref) nil title))
4899 (unless definedp
4900 (markdown-insert-reference-definition ref ref-url title)))
4901 ((and (not image) uri)
4902 (markdown-insert-uri uri))))))
4904 (defun markdown-insert-link ()
4905 "Insert new or update an existing link, with interactive prompts.
4906 If the point is at an existing link or URL, update the link text,
4907 URL, reference label, and/or title. Otherwise, insert a new link.
4908 The type of link inserted (inline, reference, or plain URL)
4909 depends on which values are provided:
4911 * If a URL and TEXT are given, insert an inline link: [TEXT](URL).
4912 * If [REF] and TEXT are given, insert a reference link: [TEXT][REF].
4913 * If only TEXT is given, insert an implicit reference link: [TEXT][].
4914 * If only a URL is given, insert a plain link: <URL>.
4916 In other words, to create an implicit reference link, leave the
4917 URL prompt empty and to create a plain URL link, leave the link
4918 text empty.
4920 If there is an active region, use the text as the default URL, if
4921 it seems to be a URL, or link text value otherwise.
4923 If a given reference is not defined, this function will
4924 additionally prompt for the URL and optional title. In this case,
4925 the reference definition is placed at the location determined by
4926 `markdown-reference-location'.
4928 Through updating the link, this function can be used to convert a
4929 link of one type (inline, reference, or plain) to another type by
4930 selectively adding or removing information via the prompts."
4931 (interactive)
4932 (markdown--insert-link-or-image nil))
4934 (defun markdown-insert-image ()
4935 "Insert new or update an existing image, with interactive prompts.
4936 If the point is at an existing image, update the alt text, URL,
4937 reference label, and/or title. Otherwise, insert a new image.
4938 The type of image inserted (inline or reference) depends on which
4939 values are provided:
4941 * If a URL and ALT-TEXT are given, insert an inline image:
4942 ![ALT-TEXT](URL).
4943 * If [REF] and ALT-TEXT are given, insert a reference image:
4944 ![ALT-TEXT][REF].
4946 If there is an active region, use the text as the default URL, if
4947 it seems to be a URL, or alt text value otherwise.
4949 If a given reference is not defined, this function will
4950 additionally prompt for the URL and optional title. In this case,
4951 the reference definition is placed at the location determined by
4952 `markdown-reference-location'.
4954 Through updating the image, this function can be used to convert an
4955 image of one type (inline or reference) to another type by
4956 selectively adding or removing information via the prompts."
4957 (interactive)
4958 (markdown--insert-link-or-image t))
4960 (defun markdown-insert-uri (&optional uri)
4961 "Insert markup for an inline URI.
4962 If there is an active region, use it as the URI. If the point is
4963 at a URI, wrap it with angle brackets. If the point is at an
4964 inline URI, remove the angle brackets. Otherwise, simply insert
4965 angle brackets place the point between them."
4966 (interactive)
4967 (if (markdown-use-region-p)
4968 ;; Active region
4969 (let ((bounds (markdown-unwrap-things-in-region
4970 (region-beginning) (region-end)
4971 markdown-regex-angle-uri 0 2)))
4972 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
4973 ;; Markup removal, URI at point, new URI, or empty markup insertion
4974 (if (thing-at-point-looking-at markdown-regex-angle-uri)
4975 (markdown-unwrap-thing-at-point nil 0 2)
4976 (if uri
4977 (insert "<" uri ">")
4978 (markdown-wrap-or-insert "<" ">" 'url nil nil)))))
4980 (defun markdown-insert-wiki-link ()
4981 "Insert a wiki link of the form [[WikiLink]].
4982 If there is an active region, use the region as the link text.
4983 If the point is at a word, use the word as the link text. If
4984 there is no active region and the point is not at word, simply
4985 insert link markup."
4986 (interactive)
4987 (if (markdown-use-region-p)
4988 ;; Active region
4989 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
4990 ;; Markup removal, wiki link at at point, or empty markup insertion
4991 (if (thing-at-point-looking-at markdown-regex-wiki-link)
4992 (if (or markdown-wiki-link-alias-first
4993 (null (match-string 5)))
4994 (markdown-unwrap-thing-at-point nil 1 3)
4995 (markdown-unwrap-thing-at-point nil 1 5))
4996 (markdown-wrap-or-insert "[[" "]]"))))
4998 (defun markdown-remove-header ()
4999 "Remove header markup if point is at a header.
5000 Return bounds of remaining header text if a header was removed
5001 and nil otherwise."
5002 (interactive "*")
5003 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
5004 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
5006 (defun markdown-insert-header (&optional level text setext)
5007 "Insert or replace header markup.
5008 The level of the header is specified by LEVEL and header text is
5009 given by TEXT. LEVEL must be an integer from 1 and 6, and the
5010 default value is 1.
5011 When TEXT is nil, the header text is obtained as follows.
5012 If there is an active region, it is used as the header text.
5013 Otherwise, the current line will be used as the header text.
5014 If there is not an active region and the point is at a header,
5015 remove the header markup and replace with level N header.
5016 Otherwise, insert empty header markup and place the point in
5017 between.
5018 The style of the header will be atx (hash marks) unless
5019 SETEXT is non-nil, in which case a setext-style (underlined)
5020 header will be inserted."
5021 (interactive "p\nsHeader text: ")
5022 (setq level (min (max (or level 1) 1) (if setext 2 6)))
5023 ;; Determine header text if not given
5024 (when (null text)
5025 (if (markdown-use-region-p)
5026 ;; Active region
5027 (setq text (delete-and-extract-region (region-beginning) (region-end)))
5028 ;; No active region
5029 (markdown-remove-header)
5030 (setq text (delete-and-extract-region
5031 (line-beginning-position) (line-end-position)))
5032 (when (and setext (string-match-p "^[ \t]*$" text))
5033 (setq text (read-string "Header text: "))))
5034 (setq text (markdown-compress-whitespace-string text)))
5035 ;; Insertion with given text
5036 (markdown-ensure-blank-line-before)
5037 (let (hdr)
5038 (cond (setext
5039 (setq hdr (make-string (string-width text) (if (= level 2) ?- ?=)))
5040 (insert text "\n" hdr))
5042 (setq hdr (make-string level ?#))
5043 (insert hdr " " text)
5044 (when (null markdown-asymmetric-header) (insert " " hdr)))))
5045 (markdown-ensure-blank-line-after)
5046 ;; Leave point at end of text
5047 (cond (setext
5048 (backward-char (1+ (string-width text))))
5049 ((null markdown-asymmetric-header)
5050 (backward-char (1+ level)))))
5052 (defun markdown-insert-header-dwim (&optional arg setext)
5053 "Insert or replace header markup.
5054 The level and type of the header are determined automatically by
5055 the type and level of the previous header, unless a prefix
5056 argument is given via ARG.
5057 With a numeric prefix valued 1 to 6, insert a header of the given
5058 level, with the type being determined automatically (note that
5059 only level 1 or 2 setext headers are possible).
5061 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
5062 promote the heading by one level.
5063 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
5064 demote the heading by one level.
5065 When SETEXT is non-nil, prefer setext-style headers when
5066 possible (levels one and two).
5068 When there is an active region, use it for the header text. When
5069 the point is at an existing header, change the type and level
5070 according to the rules above.
5071 Otherwise, if the line is not empty, create a header using the
5072 text on the current line as the header text.
5073 Finally, if the point is on a blank line, insert empty header
5074 markup (atx) or prompt for text (setext).
5075 See `markdown-insert-header' for more details about how the
5076 header text is determined."
5077 (interactive "*P")
5078 (let (level)
5079 (save-excursion
5080 (when (or (thing-at-point-looking-at markdown-regex-header)
5081 (re-search-backward markdown-regex-header nil t))
5082 ;; level of current or previous header
5083 (setq level (markdown-outline-level))
5084 ;; match group 1 indicates a setext header
5085 (setq setext (match-end 1))))
5086 ;; check prefix argument
5087 (cond
5088 ((and (equal arg '(4)) level (> level 1)) ;; C-u
5089 (cl-decf level))
5090 ((and (equal arg '(16)) level (< level 6)) ;; C-u C-u
5091 (cl-incf level))
5092 (arg ;; numeric prefix
5093 (setq level (prefix-numeric-value arg))))
5094 ;; setext headers must be level one or two
5095 (and level (setq setext (and setext (<= level 2))))
5096 ;; insert the heading
5097 (markdown-insert-header level nil setext)))
5099 (defun markdown-insert-header-setext-dwim (&optional arg)
5100 "Insert or replace header markup, with preference for setext.
5101 See `markdown-insert-header-dwim' for details, including how ARG is handled."
5102 (interactive "*P")
5103 (markdown-insert-header-dwim arg t))
5105 (defun markdown-insert-header-atx-1 ()
5106 "Insert a first level atx-style (hash mark) header.
5107 See `markdown-insert-header'."
5108 (interactive "*")
5109 (markdown-insert-header 1 nil nil))
5111 (defun markdown-insert-header-atx-2 ()
5112 "Insert a level two atx-style (hash mark) header.
5113 See `markdown-insert-header'."
5114 (interactive "*")
5115 (markdown-insert-header 2 nil nil))
5117 (defun markdown-insert-header-atx-3 ()
5118 "Insert a level three atx-style (hash mark) header.
5119 See `markdown-insert-header'."
5120 (interactive "*")
5121 (markdown-insert-header 3 nil nil))
5123 (defun markdown-insert-header-atx-4 ()
5124 "Insert a level four atx-style (hash mark) header.
5125 See `markdown-insert-header'."
5126 (interactive "*")
5127 (markdown-insert-header 4 nil nil))
5129 (defun markdown-insert-header-atx-5 ()
5130 "Insert a level five atx-style (hash mark) header.
5131 See `markdown-insert-header'."
5132 (interactive "*")
5133 (markdown-insert-header 5 nil nil))
5135 (defun markdown-insert-header-atx-6 ()
5136 "Insert a sixth level atx-style (hash mark) header.
5137 See `markdown-insert-header'."
5138 (interactive "*")
5139 (markdown-insert-header 6 nil nil))
5141 (defun markdown-insert-header-setext-1 ()
5142 "Insert a setext-style (underlined) first-level header.
5143 See `markdown-insert-header'."
5144 (interactive "*")
5145 (markdown-insert-header 1 nil t))
5147 (defun markdown-insert-header-setext-2 ()
5148 "Insert a setext-style (underlined) second-level header.
5149 See `markdown-insert-header'."
5150 (interactive "*")
5151 (markdown-insert-header 2 nil t))
5153 (defun markdown-blockquote-indentation (loc)
5154 "Return string containing necessary indentation for a blockquote at LOC.
5155 Also see `markdown-pre-indentation'."
5156 (save-excursion
5157 (goto-char loc)
5158 (let* ((list-level (length (markdown-calculate-list-levels)))
5159 (indent ""))
5160 (dotimes (_ list-level indent)
5161 (setq indent (concat indent " "))))))
5163 (defun markdown-insert-blockquote ()
5164 "Start a blockquote section (or blockquote the region).
5165 If Transient Mark mode is on and a region is active, it is used as
5166 the blockquote text."
5167 (interactive)
5168 (if (markdown-use-region-p)
5169 (markdown-blockquote-region (region-beginning) (region-end))
5170 (markdown-ensure-blank-line-before)
5171 (insert (markdown-blockquote-indentation (point)) "> ")
5172 (markdown-ensure-blank-line-after)))
5174 (defun markdown-block-region (beg end prefix)
5175 "Format the region using a block prefix.
5176 Arguments BEG and END specify the beginning and end of the
5177 region. The characters PREFIX will appear at the beginning
5178 of each line."
5179 (save-excursion
5180 (let* ((end-marker (make-marker))
5181 (beg-marker (make-marker))
5182 (prefix-without-trailing-whitespace
5183 (replace-regexp-in-string (rx (+ blank) eos) "" prefix)))
5184 ;; Ensure blank line after and remove extra whitespace
5185 (goto-char end)
5186 (skip-syntax-backward "-")
5187 (set-marker end-marker (point))
5188 (delete-horizontal-space)
5189 (markdown-ensure-blank-line-after)
5190 ;; Ensure blank line before and remove extra whitespace
5191 (goto-char beg)
5192 (skip-syntax-forward "-")
5193 (delete-horizontal-space)
5194 (markdown-ensure-blank-line-before)
5195 (set-marker beg-marker (point))
5196 ;; Insert PREFIX before each line
5197 (goto-char beg-marker)
5198 (while (and (< (line-beginning-position) end-marker)
5199 (not (eobp)))
5200 ;; Don’t insert trailing whitespace.
5201 (insert (if (eolp) prefix-without-trailing-whitespace prefix))
5202 (forward-line)))))
5204 (defun markdown-blockquote-region (beg end)
5205 "Blockquote the region.
5206 Arguments BEG and END specify the beginning and end of the region."
5207 (interactive "*r")
5208 (markdown-block-region
5209 beg end (concat (markdown-blockquote-indentation
5210 (max (point-min) (1- beg))) "> ")))
5212 (defun markdown-pre-indentation (loc)
5213 "Return string containing necessary whitespace for a pre block at LOC.
5214 Also see `markdown-blockquote-indentation'."
5215 (save-excursion
5216 (goto-char loc)
5217 (let* ((list-level (length (markdown-calculate-list-levels)))
5218 indent)
5219 (dotimes (_ (1+ list-level) indent)
5220 (setq indent (concat indent " "))))))
5222 (defun markdown-insert-pre ()
5223 "Start a preformatted section (or apply to the region).
5224 If Transient Mark mode is on and a region is active, it is marked
5225 as preformatted text."
5226 (interactive)
5227 (if (markdown-use-region-p)
5228 (markdown-pre-region (region-beginning) (region-end))
5229 (markdown-ensure-blank-line-before)
5230 (insert (markdown-pre-indentation (point)))
5231 (markdown-ensure-blank-line-after)))
5233 (defun markdown-pre-region (beg end)
5234 "Format the region as preformatted text.
5235 Arguments BEG and END specify the beginning and end of the region."
5236 (interactive "*r")
5237 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
5238 (markdown-block-region beg end indent)))
5240 (defun markdown-electric-backquote (arg)
5241 "Insert a backquote.
5242 The numeric prefix argument ARG says how many times to repeat the insertion.
5243 Call `markdown-insert-gfm-code-block' interactively
5244 if three backquotes inserted at the beginning of line."
5245 (interactive "*P")
5246 (self-insert-command (prefix-numeric-value arg))
5247 (when (and markdown-gfm-use-electric-backquote (looking-back "^```" nil))
5248 (replace-match "")
5249 (call-interactively #'markdown-insert-gfm-code-block)))
5251 (defconst markdown-gfm-recognized-languages
5252 ;; To reproduce/update, evaluate the let-form in
5253 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
5254 ;; but with appropriate use of a keyboard macro, indenting and filling it
5255 ;; properly is pretty fast.
5256 '("1C-Enterprise" "ABAP" "ABNF" "AGS-Script" "AMPL" "ANTLR"
5257 "API-Blueprint" "APL" "ASN.1" "ASP" "ATS" "ActionScript" "Ada" "Agda"
5258 "Alloy" "Alpine-Abuild" "Ant-Build-System" "ApacheConf" "Apex"
5259 "Apollo-Guidance-Computer" "AppleScript" "Arc" "Arduino" "AsciiDoc"
5260 "AspectJ" "Assembly" "Augeas" "AutoHotkey" "AutoIt" "Awk" "Batchfile"
5261 "Befunge" "Bison" "BitBake" "Blade" "BlitzBasic" "BlitzMax" "Bluespec"
5262 "Boo" "Brainfuck" "Brightscript" "Bro" "C#" "C++" "C-ObjDump"
5263 "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "COLLADA" "CSON" "CSS" "CSV"
5264 "CWeb" "Cap'n-Proto" "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK"
5265 "Cirru" "Clarion" "Clean" "Click" "Clojure" "Closure-Templates"
5266 "CoffeeScript" "ColdFusion" "ColdFusion-CFC" "Common-Lisp"
5267 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal"
5268 "Csound" "Csound-Document" "Csound-Score" "Cuda" "Cycript" "Cython"
5269 "D-ObjDump" "DIGITAL-Command-Language" "DM" "DNS-Zone" "DTrace"
5270 "Darcs-Patch" "Dart" "Diff" "Dockerfile" "Dogescript" "Dylan" "EBNF"
5271 "ECL" "ECLiPSe" "EJS" "EQ" "Eagle" "Ecere-Projects" "Eiffel" "Elixir"
5272 "Elm" "Emacs-Lisp" "EmberScript" "Erlang" "F#" "FLUX" "Factor" "Fancy"
5273 "Fantom" "Filebench-WML" "Filterscript" "Formatted" "Forth" "Fortran"
5274 "FreeMarker" "Frege" "G-code" "GAMS" "GAP" "GCC-Machine-Description"
5275 "GDB" "GDScript" "GLSL" "GN" "Game-Maker-Language" "Genie" "Genshi"
5276 "Gentoo-Ebuild" "Gentoo-Eclass" "Gettext-Catalog" "Gherkin" "Glyph"
5277 "Gnuplot" "Go" "Golo" "Gosu" "Grace" "Gradle" "Grammatical-Framework"
5278 "Graph-Modeling-Language" "GraphQL" "Graphviz-(DOT)" "Groovy"
5279 "Groovy-Server-Pages" "HCL" "HLSL" "HTML" "HTML+Django" "HTML+ECR"
5280 "HTML+EEX" "HTML+ERB" "HTML+PHP" "HTTP" "Hack" "Haml" "Handlebars"
5281 "Harbour" "Haskell" "Haxe" "Hy" "HyPhy" "IDL" "IGOR-Pro" "INI"
5282 "IRC-log" "Idris" "Inform-7" "Inno-Setup" "Io" "Ioke" "Isabelle"
5283 "Isabelle-ROOT" "JFlex" "JSON" "JSON5" "JSONLD" "JSONiq" "JSX"
5284 "Jasmin" "Java" "Java-Server-Pages" "JavaScript" "Jison" "Jison-Lex"
5285 "Jolie" "Julia" "Jupyter-Notebook" "KRL" "KiCad" "Kit" "Kotlin" "LFE"
5286 "LLVM" "LOLCODE" "LSL" "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex"
5287 "LilyPond" "Limbo" "Linker-Script" "Linux-Kernel-Module" "Liquid"
5288 "Literate-Agda" "Literate-CoffeeScript" "Literate-Haskell"
5289 "LiveScript" "Logos" "Logtalk" "LookML" "LoomScript" "Lua" "M4"
5290 "M4Sugar" "MAXScript" "MQL4" "MQL5" "MTML" "MUF" "Makefile" "Mako"
5291 "Markdown" "Marko" "Mask" "Mathematica" "Matlab" "Maven-POM" "Max"
5292 "MediaWiki" "Mercury" "Meson" "Metal" "MiniD" "Mirah" "Modelica"
5293 "Modula-2" "Module-Management-System" "Monkey" "Moocode" "MoonScript"
5294 "Myghty" "NCL" "NL" "NSIS" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo"
5295 "NewLisp" "Nginx" "Nim" "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml"
5296 "ObjDump" "Objective-C" "Objective-C++" "Objective-J" "Omgrofl" "Opa"
5297 "Opal" "OpenCL" "OpenEdge-ABL" "OpenRC-runscript" "OpenSCAD"
5298 "OpenType-Feature-File" "Org" "Ox" "Oxygene" "Oz" "P4" "PAWN" "PHP"
5299 "PLSQL" "PLpgSQL" "POV-Ray-SDL" "Pan" "Papyrus" "Parrot"
5300 "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal" "Pep8"
5301 "Perl" "Perl6" "Pic" "Pickle" "PicoLisp" "PigLatin" "Pike" "Pod"
5302 "PogoScript" "Pony" "PostScript" "PowerBuilder" "PowerShell"
5303 "Processing" "Prolog" "Propeller-Spin" "Protocol-Buffer" "Public-Key"
5304 "Pug" "Puppet" "Pure-Data" "PureBasic" "PureScript" "Python"
5305 "Python-console" "Python-traceback" "QML" "QMake" "RAML" "RDoc"
5306 "REALbasic" "REXX" "RHTML" "RMarkdown" "RPM-Spec" "RUNOFF" "Racket"
5307 "Ragel" "Rascal" "Raw-token-data" "Reason" "Rebol" "Red" "Redcode"
5308 "Regular-Expression" "Ren'Py" "RenderScript" "RobotFramework" "Roff"
5309 "Rouge" "Ruby" "Rust" "SAS" "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL"
5310 "SRecode-Template" "STON" "SVG" "Sage" "SaltStack" "Sass" "Scala"
5311 "Scaml" "Scheme" "Scilab" "Self" "ShaderLab" "Shell" "ShellSession"
5312 "Shen" "Slash" "Slim" "Smali" "Smalltalk" "Smarty" "SourcePawn"
5313 "Spline-Font-Database" "Squirrel" "Stan" "Standard-ML" "Stata"
5314 "Stylus" "SubRip-Text" "Sublime-Text-Config" "SuperCollider" "Swift"
5315 "SystemVerilog" "TI-Program" "TLA" "TOML" "TXL" "Tcl" "Tcsh" "TeX"
5316 "Tea" "Terra" "Text" "Textile" "Thrift" "Turing" "Turtle" "Twig"
5317 "Type-Language" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset"
5318 "Unix-Assembly" "Uno" "UnrealScript" "UrWeb" "VCL" "VHDL" "Vala"
5319 "Verilog" "Vim-script" "Visual-Basic" "Volt" "Vue"
5320 "Wavefront-Material" "Wavefront-Object" "Web-Ontology-Language"
5321 "WebAssembly" "WebIDL" "World-of-Warcraft-Addon-Data" "X10" "XC"
5322 "XCompose" "XML" "XPages" "XProc" "XQuery" "XS" "XSLT" "Xojo" "Xtend"
5323 "YAML" "YANG" "Yacc" "Zephir" "Zimpl" "desktop" "eC" "edn" "fish"
5324 "mupad" "nesC" "ooc" "reStructuredText" "wisp" "xBase")
5325 "Language specifiers recognized by GitHub's syntax highlighting features.")
5327 (defvar markdown-gfm-used-languages nil
5328 "Language names used in GFM code blocks.")
5329 (make-variable-buffer-local 'markdown-gfm-used-languages)
5331 (defun markdown-trim-whitespace (str)
5332 (markdown-replace-regexp-in-string
5333 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str))
5335 (defun markdown-clean-language-string (str)
5336 (markdown-replace-regexp-in-string
5337 "{\\.?\\|}" "" (markdown-trim-whitespace str)))
5339 (defun markdown-validate-language-string (widget)
5340 (let ((str (widget-value widget)))
5341 (unless (string= str (markdown-clean-language-string str))
5342 (widget-put widget :error (format "Invalid language spec: '%s'" str))
5343 widget)))
5345 (defun markdown-gfm-get-corpus ()
5346 "Create corpus of recognized GFM code block languages for the given buffer."
5347 (let ((given-corpus (append markdown-gfm-additional-languages
5348 markdown-gfm-recognized-languages)))
5349 (append
5350 markdown-gfm-used-languages
5351 (if markdown-gfm-downcase-languages (cl-mapcar #'downcase given-corpus)
5352 given-corpus))))
5354 (defun markdown-gfm-add-used-language (lang)
5355 "Clean LANG and add to list of used languages."
5356 (setq markdown-gfm-used-languages
5357 (cons lang (remove lang markdown-gfm-used-languages))))
5359 (defcustom markdown-spaces-after-code-fence 1
5360 "Number of space characters to insert after a code fence.
5361 \\<gfm-mode-map>\\[markdown-insert-gfm-code-block] inserts this many spaces between an
5362 opening code fence and an info string."
5363 :group 'markdown
5364 :type 'integer
5365 :safe #'natnump
5366 :package-version '(markdown-mode . "2.3"))
5368 (defun markdown-insert-gfm-code-block (&optional lang edit)
5369 "Insert GFM code block for language LANG.
5370 If LANG is nil, the language will be queried from user. If a
5371 region is active, wrap this region with the markup instead. If
5372 the region boundaries are not on empty lines, these are added
5373 automatically in order to have the correct markup. When EDIT is
5374 non-nil (e.g., when \\[universal-argument] is given), edit the
5375 code block in an indirect buffer after insertion."
5376 (interactive
5377 (list (let ((completion-ignore-case nil))
5378 (condition-case nil
5379 (markdown-clean-language-string
5380 (completing-read
5381 "Programming language: "
5382 (markdown-gfm-get-corpus)
5383 nil 'confirm (car markdown-gfm-used-languages)
5384 'markdown-gfm-language-history))
5385 (quit "")))
5386 current-prefix-arg))
5387 (unless (string= lang "") (markdown-gfm-add-used-language lang))
5388 (when (> (length lang) 0)
5389 (setq lang (concat (make-string markdown-spaces-after-code-fence ?\s)
5390 lang)))
5391 (if (markdown-use-region-p)
5392 (let* ((b (region-beginning)) (e (region-end)) end
5393 (indent (progn (goto-char b) (current-indentation))))
5394 (goto-char e)
5395 ;; if we're on a blank line, don't newline, otherwise the ```
5396 ;; should go on its own line
5397 (unless (looking-back "\n" nil)
5398 (newline))
5399 (indent-to indent)
5400 (insert "```")
5401 (markdown-ensure-blank-line-after)
5402 (setq end (point))
5403 (goto-char b)
5404 ;; if we're on a blank line, insert the quotes here, otherwise
5405 ;; add a new line first
5406 (unless (looking-at-p "\n")
5407 (newline)
5408 (forward-line -1))
5409 (markdown-ensure-blank-line-before)
5410 (indent-to indent)
5411 (insert "```" lang)
5412 (markdown-syntax-propertize-fenced-block-constructs (point-at-bol) end))
5413 (let ((indent (current-indentation)) start)
5414 (delete-horizontal-space :backward-only)
5415 (markdown-ensure-blank-line-before)
5416 (indent-to indent)
5417 (setq start (point))
5418 (insert "```" lang "\n")
5419 (indent-to indent)
5420 (unless edit (insert ?\n))
5421 (indent-to indent)
5422 (insert "```")
5423 (markdown-ensure-blank-line-after)
5424 (markdown-syntax-propertize-fenced-block-constructs start (point)))
5425 (end-of-line 0)
5426 (when edit (markdown-edit-code-block))))
5428 (defun markdown-code-block-lang (&optional pos-prop)
5429 "Return the language name for a GFM or tilde fenced code block.
5430 The beginning of the block may be described by POS-PROP,
5431 a cons of (pos . prop) giving the position and property
5432 at the beginning of the block."
5433 (or pos-prop
5434 (setq pos-prop
5435 (markdown-max-of-seq
5436 #'car
5437 (cl-remove-if
5438 #'null
5439 (cl-mapcar
5440 #'markdown-find-previous-prop
5441 (markdown-get-fenced-block-begin-properties))))))
5442 (when pos-prop
5443 (goto-char (car pos-prop))
5444 (set-match-data (get-text-property (point) (cdr pos-prop)))
5445 ;; Note: Hard-coded group number assumes tilde
5446 ;; and GFM fenced code regexp groups agree.
5447 (let ((begin (match-beginning 3))
5448 (end (match-end 3)))
5449 (when (and begin end)
5450 ;; Fix language strings beginning with periods, like ".ruby".
5451 (when (eq (char-after begin) ?.)
5452 (setq begin (1+ begin)))
5453 (buffer-substring-no-properties begin end)))))
5455 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer)
5456 (with-current-buffer (or buffer (current-buffer))
5457 (save-excursion
5458 (goto-char (point-min))
5459 (cl-loop
5460 with prop = 'markdown-gfm-block-begin
5461 for pos-prop = (markdown-find-next-prop prop)
5462 while pos-prop
5463 for lang = (markdown-code-block-lang pos-prop)
5464 do (progn (when lang (markdown-gfm-add-used-language lang))
5465 (goto-char (next-single-property-change (point) prop)))))))
5468 ;;; Footnotes ==================================================================
5470 (defun markdown-footnote-counter-inc ()
5471 "Increment `markdown-footnote-counter' and return the new value."
5472 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
5473 (save-excursion
5474 (goto-char (point-min))
5475 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
5476 (point-max) t)
5477 (let ((fn (string-to-number (match-string 1))))
5478 (when (> fn markdown-footnote-counter)
5479 (setq markdown-footnote-counter fn))))))
5480 (cl-incf markdown-footnote-counter))
5482 (defun markdown-insert-footnote ()
5483 "Insert footnote with a new number and move point to footnote definition."
5484 (interactive)
5485 (let ((fn (markdown-footnote-counter-inc)))
5486 (insert (format "[^%d]" fn))
5487 (markdown-footnote-text-find-new-location)
5488 (markdown-ensure-blank-line-before)
5489 (unless (markdown-cur-line-blank-p)
5490 (insert "\n"))
5491 (insert (format "[^%d]: " fn))
5492 (markdown-ensure-blank-line-after)))
5494 (defun markdown-footnote-text-find-new-location ()
5495 "Position the point at the proper location for a new footnote text."
5496 (cond
5497 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
5498 ((eq markdown-footnote-location 'immediately) (markdown-end-of-text-block))
5499 ((eq markdown-footnote-location 'subtree) (markdown-end-of-subtree))
5500 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
5502 (defun markdown-footnote-kill ()
5503 "Kill the footnote at point.
5504 The footnote text is killed (and added to the kill ring), the
5505 footnote marker is deleted. Point has to be either at the
5506 footnote marker or in the footnote text."
5507 (interactive)
5508 (let ((marker-pos nil)
5509 (skip-deleting-marker nil)
5510 (starting-footnote-text-positions
5511 (markdown-footnote-text-positions)))
5512 (when starting-footnote-text-positions
5513 ;; We're starting in footnote text, so mark our return position and jump
5514 ;; to the marker if possible.
5515 (let ((marker-pos (markdown-footnote-find-marker
5516 (cl-first starting-footnote-text-positions))))
5517 (if marker-pos
5518 (goto-char (1- marker-pos))
5519 ;; If there isn't a marker, we still want to kill the text.
5520 (setq skip-deleting-marker t))))
5521 ;; Either we didn't start in the text, or we started in the text and jumped
5522 ;; to the marker. We want to assume we're at the marker now and error if
5523 ;; we're not.
5524 (unless skip-deleting-marker
5525 (let ((marker (markdown-footnote-delete-marker)))
5526 (unless marker
5527 (error "Not at a footnote"))
5528 ;; Even if we knew the text position before, it changed when we deleted
5529 ;; the label.
5530 (setq marker-pos (cl-second marker))
5531 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker))))
5532 (unless new-text-pos
5533 (error "No text for footnote `%s'" (cl-first marker)))
5534 (goto-char new-text-pos))))
5535 (let ((pos (markdown-footnote-kill-text)))
5536 (goto-char (if starting-footnote-text-positions
5538 marker-pos)))))
5540 (defun markdown-footnote-delete-marker ()
5541 "Delete a footnote marker at point.
5542 Returns a list (ID START) containing the footnote ID and the
5543 start position of the marker before deletion. If no footnote
5544 marker was deleted, this function returns NIL."
5545 (let ((marker (markdown-footnote-marker-positions)))
5546 (when marker
5547 (delete-region (cl-second marker) (cl-third marker))
5548 (butlast marker))))
5550 (defun markdown-footnote-kill-text ()
5551 "Kill footnote text at point.
5552 Returns the start position of the footnote text before deletion,
5553 or NIL if point was not inside a footnote text.
5555 The killed text is placed in the kill ring (without the footnote
5556 number)."
5557 (let ((fn (markdown-footnote-text-positions)))
5558 (when fn
5559 (let ((text (delete-and-extract-region (cl-second fn) (cl-third fn))))
5560 (string-match (concat "\\[\\" (cl-first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
5561 (kill-new (match-string 1 text))
5562 (when (and (markdown-cur-line-blank-p)
5563 (markdown-prev-line-blank-p)
5564 (not (bobp)))
5565 (delete-region (1- (point)) (point)))
5566 (cl-second fn)))))
5568 (defun markdown-footnote-goto-text ()
5569 "Jump to the text of the footnote at point."
5570 (interactive)
5571 (let ((fn (car (markdown-footnote-marker-positions))))
5572 (unless fn
5573 (user-error "Not at a footnote marker"))
5574 (let ((new-pos (markdown-footnote-find-text fn)))
5575 (unless new-pos
5576 (error "No definition found for footnote `%s'" fn))
5577 (goto-char new-pos))))
5579 (defun markdown-footnote-return ()
5580 "Return from a footnote to its footnote number in the main text."
5581 (interactive)
5582 (let ((fn (save-excursion
5583 (car (markdown-footnote-text-positions)))))
5584 (unless fn
5585 (user-error "Not in a footnote"))
5586 (let ((new-pos (markdown-footnote-find-marker fn)))
5587 (unless new-pos
5588 (error "Footnote marker `%s' not found" fn))
5589 (goto-char new-pos))))
5591 (defun markdown-footnote-find-marker (id)
5592 "Find the location of the footnote marker with ID.
5593 The actual buffer position returned is the position directly
5594 following the marker's closing bracket. If no marker is found,
5595 NIL is returned."
5596 (save-excursion
5597 (goto-char (point-min))
5598 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
5599 (skip-chars-backward "^]")
5600 (point))))
5602 (defun markdown-footnote-find-text (id)
5603 "Find the location of the text of footnote ID.
5604 The actual buffer position returned is the position of the first
5605 character of the text, after the footnote's identifier. If no
5606 footnote text is found, NIL is returned."
5607 (save-excursion
5608 (goto-char (point-min))
5609 (when (re-search-forward (concat "^ \\{0,3\\}\\[" id "\\]:") nil t)
5610 (skip-chars-forward "[ \t]")
5611 (point))))
5613 (defun markdown-footnote-marker-positions ()
5614 "Return the position and ID of the footnote marker point is on.
5615 The return value is a list (ID START END). If point is not on a
5616 footnote, NIL is returned."
5617 ;; first make sure we're at a footnote marker
5618 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
5619 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
5620 (save-excursion
5621 ;; move point between [ and ^:
5622 (if (looking-at-p "\\[")
5623 (forward-char 1)
5624 (skip-chars-backward "^["))
5625 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
5626 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
5628 (defun markdown-footnote-text-positions ()
5629 "Return the start and end positions of the footnote text point is in.
5630 The exact return value is a list of three elements: (ID START END).
5631 The start position is the position of the opening bracket
5632 of the footnote id. The end position is directly after the
5633 newline that ends the footnote. If point is not in a footnote,
5634 NIL is returned instead."
5635 (save-excursion
5636 (let (result)
5637 (move-beginning-of-line 1)
5638 ;; Try to find the label. If we haven't found the label and we're at a blank
5639 ;; or indented line, back up if possible.
5640 (while (and
5641 (not (and (looking-at markdown-regex-footnote-definition)
5642 (setq result (list (match-string 1) (point)))))
5643 (and (not (bobp))
5644 (or (markdown-cur-line-blank-p)
5645 (>= (current-indentation) 4))))
5646 (forward-line -1))
5647 (when result
5648 ;; Advance if there is a next line that is either blank or indented.
5649 ;; (Need to check if we're on the last line, because
5650 ;; markdown-next-line-blank-p returns true for last line in buffer.)
5651 (while (and (/= (line-end-position) (point-max))
5652 (or (markdown-next-line-blank-p)
5653 (>= (markdown-next-line-indent) 4)))
5654 (forward-line))
5655 ;; Move back while the current line is blank.
5656 (while (markdown-cur-line-blank-p)
5657 (forward-line -1))
5658 ;; Advance to capture this line and a single trailing newline (if there
5659 ;; is one).
5660 (forward-line)
5661 (append result (list (point)))))))
5664 ;;; Element Removal ===========================================================
5666 (defun markdown-kill-thing-at-point ()
5667 "Kill thing at point and add important text, without markup, to kill ring.
5668 Possible things to kill include (roughly in order of precedence):
5669 inline code, headers, horizonal rules, links (add link text to
5670 kill ring), images (add alt text to kill ring), angle uri, email
5671 addresses, bold, italics, reference definition (add URI to kill
5672 ring), footnote markers and text (kill both marker and text, add
5673 text to kill ring), and list items."
5674 (interactive "*")
5675 (let (val)
5676 (cond
5677 ;; Inline code
5678 ((markdown-inline-code-at-point)
5679 (kill-new (match-string 2))
5680 (delete-region (match-beginning 0) (match-end 0)))
5681 ;; ATX header
5682 ((thing-at-point-looking-at markdown-regex-header-atx)
5683 (kill-new (match-string 2))
5684 (delete-region (match-beginning 0) (match-end 0)))
5685 ;; Setext header
5686 ((thing-at-point-looking-at markdown-regex-header-setext)
5687 (kill-new (match-string 1))
5688 (delete-region (match-beginning 0) (match-end 0)))
5689 ;; Horizonal rule
5690 ((thing-at-point-looking-at markdown-regex-hr)
5691 (kill-new (match-string 0))
5692 (delete-region (match-beginning 0) (match-end 0)))
5693 ;; Inline link or image (add link or alt text to kill ring)
5694 ((thing-at-point-looking-at markdown-regex-link-inline)
5695 (kill-new (match-string 3))
5696 (delete-region (match-beginning 0) (match-end 0)))
5697 ;; Reference link or image (add link or alt text to kill ring)
5698 ((thing-at-point-looking-at markdown-regex-link-reference)
5699 (kill-new (match-string 3))
5700 (delete-region (match-beginning 0) (match-end 0)))
5701 ;; Angle URI (add URL to kill ring)
5702 ((thing-at-point-looking-at markdown-regex-angle-uri)
5703 (kill-new (match-string 2))
5704 (delete-region (match-beginning 0) (match-end 0)))
5705 ;; Email address in angle brackets (add email address to kill ring)
5706 ((thing-at-point-looking-at markdown-regex-email)
5707 (kill-new (match-string 1))
5708 (delete-region (match-beginning 0) (match-end 0)))
5709 ;; Wiki link (add alias text to kill ring)
5710 ((and markdown-enable-wiki-links
5711 (thing-at-point-looking-at markdown-regex-wiki-link))
5712 (kill-new (markdown-wiki-link-alias))
5713 (delete-region (match-beginning 1) (match-end 1)))
5714 ;; Bold
5715 ((thing-at-point-looking-at markdown-regex-bold)
5716 (kill-new (match-string 4))
5717 (delete-region (match-beginning 2) (match-end 2)))
5718 ;; Italics
5719 ((thing-at-point-looking-at markdown-regex-italic)
5720 (kill-new (match-string 3))
5721 (delete-region (match-beginning 1) (match-end 1)))
5722 ;; Strikethrough
5723 ((thing-at-point-looking-at markdown-regex-strike-through)
5724 (kill-new (match-string 4))
5725 (delete-region (match-beginning 2) (match-end 2)))
5726 ;; Footnote marker (add footnote text to kill ring)
5727 ((thing-at-point-looking-at markdown-regex-footnote)
5728 (markdown-footnote-kill))
5729 ;; Footnote text (add footnote text to kill ring)
5730 ((setq val (markdown-footnote-text-positions))
5731 (markdown-footnote-kill))
5732 ;; Reference definition (add URL to kill ring)
5733 ((thing-at-point-looking-at markdown-regex-reference-definition)
5734 (kill-new (match-string 5))
5735 (delete-region (match-beginning 0) (match-end 0)))
5736 ;; List item
5737 ((setq val (markdown-cur-list-item-bounds))
5738 (kill-new (delete-and-extract-region (cl-first val) (cl-second val))))
5740 (user-error "Nothing found at point to kill")))))
5743 ;;; Indentation ====================================================================
5745 (defun markdown-indent-find-next-position (cur-pos positions)
5746 "Return the position after the index of CUR-POS in POSITIONS.
5747 Positions are calculated by `markdown-calc-indents'."
5748 (while (and positions
5749 (not (equal cur-pos (car positions))))
5750 (setq positions (cdr positions)))
5751 (or (cadr positions) 0))
5753 (define-obsolete-function-alias 'markdown-exdent-find-next-position
5754 'markdown-outdent-find-next-position "v2.3")
5756 (defun markdown-outdent-find-next-position (cur-pos positions)
5757 "Return the maximal element that precedes CUR-POS from POSITIONS.
5758 Positions are calculated by `markdown-calc-indents'."
5759 (let ((result 0))
5760 (dolist (i positions)
5761 (when (< i cur-pos)
5762 (setq result (max result i))))
5763 result))
5765 (defun markdown-indent-line ()
5766 "Indent the current line using some heuristics.
5767 If the _previous_ command was either `markdown-enter-key' or
5768 `markdown-cycle', then we should cycle to the next
5769 reasonable indentation position. Otherwise, we could have been
5770 called directly by `markdown-enter-key', by an initial call of
5771 `markdown-cycle', or indirectly by `auto-fill-mode'. In
5772 these cases, indent to the default position.
5773 Positions are calculated by `markdown-calc-indents'."
5774 (interactive)
5775 (let ((positions (markdown-calc-indents))
5776 (point-pos (current-column))
5777 (_ (back-to-indentation))
5778 (cur-pos (current-column)))
5779 (if (not (equal this-command 'markdown-cycle))
5780 (indent-line-to (car positions))
5781 (setq positions (sort (delete-dups positions) '<))
5782 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions))
5783 (new-point-pos (max (+ point-pos (- next-pos cur-pos)) 0)))
5784 (indent-line-to next-pos)
5785 (move-to-column new-point-pos)))))
5787 (defun markdown-calc-indents ()
5788 "Return a list of indentation columns to cycle through.
5789 The first element in the returned list should be considered the
5790 default indentation level. This function does not worry about
5791 duplicate positions, which are handled up by calling functions."
5792 (let (pos prev-line-pos positions)
5794 ;; Indentation of previous line
5795 (setq prev-line-pos (markdown-prev-line-indent))
5796 (setq positions (cons prev-line-pos positions))
5798 ;; Indentation of previous non-list-marker text
5799 (when (setq pos (save-excursion
5800 (forward-line -1)
5801 (when (looking-at markdown-regex-list)
5802 (- (match-end 3) (match-beginning 0)))))
5803 (setq positions (cons pos positions)))
5805 ;; Indentation required for a pre block in current context
5806 (setq pos (length (markdown-pre-indentation (point))))
5807 (setq positions (cons pos positions))
5809 ;; Indentation of the previous line + tab-width
5810 (if prev-line-pos
5811 (setq positions (cons (+ prev-line-pos tab-width) positions))
5812 (setq positions (cons tab-width positions)))
5814 ;; Indentation of the previous line - tab-width
5815 (if (and prev-line-pos (> prev-line-pos tab-width))
5816 (setq positions (cons (- prev-line-pos tab-width) positions)))
5818 ;; Indentation of all preceeding list markers (when in a list)
5819 (when (setq pos (markdown-calculate-list-levels))
5820 (setq positions (append pos positions)))
5822 ;; First column
5823 (setq positions (cons 0 positions))
5825 ;; Return reversed list
5826 (reverse positions)))
5828 (defun markdown-enter-key ()
5829 "Handle RET depending on the context.
5830 If the point is at a table, move to the next row. Otherwise,
5831 indent according to value of `markdown-indent-on-enter'.
5832 When it is nil, simply call `newline'. Otherwise, indent the next line
5833 following RET using `markdown-indent-line'. Furthermore, when it
5834 is set to 'indent-and-new-item and the point is in a list item,
5835 start a new item with the same indentation. If the point is in an
5836 empty list item, remove it (so that pressing RET twice when in a
5837 list simply adds a blank line)."
5838 (interactive)
5839 (cond
5840 ;; Table
5841 ((markdown-table-at-point-p)
5842 (call-interactively #'markdown-table-next-row))
5843 ;; Indent non-table text
5844 (markdown-indent-on-enter
5845 (let (bounds)
5846 (if (and (memq markdown-indent-on-enter '(indent-and-new-item))
5847 (setq bounds (markdown-cur-list-item-bounds)))
5848 (let ((beg (cl-first bounds))
5849 (end (cl-second bounds))
5850 (length (cl-fourth bounds)))
5851 ;; Point is in a list item
5852 (if (= (- end beg) length)
5853 ;; Delete blank list
5854 (progn
5855 (delete-region beg end)
5856 (newline)
5857 (markdown-indent-line))
5858 (call-interactively #'markdown-insert-list-item)))
5859 ;; Point is not in a list
5860 (newline)
5861 (markdown-indent-line))))
5862 ;; Insert a raw newline
5863 (t (newline))))
5865 (define-obsolete-function-alias 'markdown-exdent-or-delete
5866 'markdown-outdent-or-delete "v2.3")
5868 (defun markdown-outdent-or-delete (arg)
5869 "Handle BACKSPACE by cycling through indentation points.
5870 When BACKSPACE is pressed, if there is only whitespace
5871 before the current point, then outdent the line one level.
5872 Otherwise, do normal delete by repeating
5873 `backward-delete-char-untabify' ARG times."
5874 (interactive "*p")
5875 (if (use-region-p)
5876 (backward-delete-char-untabify arg)
5877 (let ((cur-pos (current-column))
5878 (start-of-indention (save-excursion
5879 (back-to-indentation)
5880 (current-column)))
5881 (positions (markdown-calc-indents)))
5882 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
5883 (indent-line-to (markdown-outdent-find-next-position cur-pos positions))
5884 (backward-delete-char-untabify arg)))))
5886 (defun markdown-find-leftmost-column (beg end)
5887 "Find the leftmost column in the region from BEG to END."
5888 (let ((mincol 1000))
5889 (save-excursion
5890 (goto-char beg)
5891 (while (< (point) end)
5892 (back-to-indentation)
5893 (unless (looking-at-p "[ \t]*$")
5894 (setq mincol (min mincol (current-column))))
5895 (forward-line 1)
5897 mincol))
5899 (defun markdown-indent-region (beg end arg)
5900 "Indent the region from BEG to END using some heuristics.
5901 When ARG is non-nil, outdent the region instead.
5902 See `markdown-indent-line' and `markdown-indent-line'."
5903 (interactive "*r\nP")
5904 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
5905 (leftmostcol (markdown-find-leftmost-column beg end))
5906 (next-pos (if arg
5907 (markdown-outdent-find-next-position leftmostcol positions)
5908 (markdown-indent-find-next-position leftmostcol positions))))
5909 (indent-rigidly beg end (- next-pos leftmostcol))
5910 (setq deactivate-mark nil)))
5912 (define-obsolete-function-alias 'markdown-exdent-region
5913 'markdown-outdent-region "v2.3")
5915 (defun markdown-outdent-region (beg end)
5916 "Call `markdown-indent-region' on region from BEG to END with prefix."
5917 (interactive "*r")
5918 (markdown-indent-region beg end t))
5921 ;;; Markup Completion =========================================================
5923 (defconst markdown-complete-alist
5924 '((markdown-regex-header-atx . markdown-complete-atx)
5925 (markdown-regex-header-setext . markdown-complete-setext)
5926 (markdown-regex-hr . markdown-complete-hr))
5927 "Association list of form (regexp . function) for markup completion.")
5929 (defun markdown-incomplete-atx-p ()
5930 "Return t if ATX header markup is incomplete and nil otherwise.
5931 Assumes match data is available for `markdown-regex-header-atx'.
5932 Checks that the number of trailing hash marks equals the number of leading
5933 hash marks, that there is only a single space before and after the text,
5934 and that there is no extraneous whitespace in the text."
5936 ;; Number of starting and ending hash marks differs
5937 (not (= (length (match-string 1)) (length (match-string 3))))
5938 ;; When the header text is not empty...
5939 (and (> (length (match-string 2)) 0)
5940 ;; ...if there are extra leading, trailing, or interior spaces
5941 (or (not (= (match-beginning 2) (1+ (match-end 1))))
5942 (not (= (match-beginning 3) (1+ (match-end 2))))
5943 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
5944 ;; When the header text is empty...
5945 (and (= (length (match-string 2)) 0)
5946 ;; ...if there are too many or too few spaces
5947 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
5949 (defun markdown-complete-atx ()
5950 "Complete and normalize ATX headers.
5951 Add or remove hash marks to the end of the header to match the
5952 beginning. Ensure that there is only a single space between hash
5953 marks and header text. Removes extraneous whitespace from header text.
5954 Assumes match data is available for `markdown-regex-header-atx'.
5955 Return nil if markup was complete and non-nil if markup was completed."
5956 (when (markdown-incomplete-atx-p)
5957 (let* ((new-marker (make-marker))
5958 (new-marker (set-marker new-marker (match-end 2))))
5959 ;; Hash marks and spacing at end
5960 (goto-char (match-end 2))
5961 (delete-region (match-end 2) (match-end 3))
5962 (insert " " (match-string 1))
5963 ;; Remove extraneous whitespace from title
5964 (replace-match (markdown-compress-whitespace-string (match-string 2))
5965 t t nil 2)
5966 ;; Spacing at beginning
5967 (goto-char (match-end 1))
5968 (delete-region (match-end 1) (match-beginning 2))
5969 (insert " ")
5970 ;; Leave point at end of text
5971 (goto-char new-marker))))
5973 (defun markdown-incomplete-setext-p ()
5974 "Return t if setext header markup is incomplete and nil otherwise.
5975 Assumes match data is available for `markdown-regex-header-setext'.
5976 Checks that length of underline matches text and that there is no
5977 extraneous whitespace in the text."
5978 (or (not (= (length (match-string 1)) (length (match-string 2))))
5979 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
5981 (defun markdown-complete-setext ()
5982 "Complete and normalize setext headers.
5983 Add or remove underline characters to match length of header
5984 text. Removes extraneous whitespace from header text. Assumes
5985 match data is available for `markdown-regex-header-setext'.
5986 Return nil if markup was complete and non-nil if markup was completed."
5987 (when (markdown-incomplete-setext-p)
5988 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
5989 (char (char-after (match-beginning 2)))
5990 (level (if (char-equal char ?-) 2 1)))
5991 (goto-char (match-beginning 0))
5992 (delete-region (match-beginning 0) (match-end 0))
5993 (markdown-insert-header level text t)
5994 t)))
5996 (defun markdown-incomplete-hr-p ()
5997 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
5998 Assumes match data is available for `markdown-regex-hr'."
5999 (not (member (match-string 0) markdown-hr-strings)))
6001 (defun markdown-complete-hr ()
6002 "Complete horizontal rules.
6003 If horizontal rule string is a member of `markdown-hr-strings',
6004 do nothing. Otherwise, replace with the car of
6005 `markdown-hr-strings'.
6006 Assumes match data is available for `markdown-regex-hr'.
6007 Return nil if markup was complete and non-nil if markup was completed."
6008 (when (markdown-incomplete-hr-p)
6009 (replace-match (car markdown-hr-strings))
6012 (defun markdown-complete ()
6013 "Complete markup of object near point or in region when active.
6014 Handle all objects in `markdown-complete-alist', in order.
6015 See `markdown-complete-at-point' and `markdown-complete-region'."
6016 (interactive "*")
6017 (if (markdown-use-region-p)
6018 (markdown-complete-region (region-beginning) (region-end))
6019 (markdown-complete-at-point)))
6021 (defun markdown-complete-at-point ()
6022 "Complete markup of object near point.
6023 Handle all elements of `markdown-complete-alist' in order."
6024 (interactive "*")
6025 (let ((list markdown-complete-alist) found changed)
6026 (while list
6027 (let ((regexp (eval (caar list)))
6028 (function (cdar list)))
6029 (setq list (cdr list))
6030 (when (thing-at-point-looking-at regexp)
6031 (setq found t)
6032 (setq changed (funcall function))
6033 (setq list nil))))
6034 (if found
6035 (or changed (user-error "Markup at point is complete"))
6036 (user-error "Nothing to complete at point"))))
6038 (defun markdown-complete-region (beg end)
6039 "Complete markup of objects in region from BEG to END.
6040 Handle all objects in `markdown-complete-alist', in order. Each
6041 match is checked to ensure that a previous regexp does not also
6042 match."
6043 (interactive "*r")
6044 (let ((end-marker (set-marker (make-marker) end))
6045 previous)
6046 (dolist (element markdown-complete-alist)
6047 (let ((regexp (eval (car element)))
6048 (function (cdr element)))
6049 (goto-char beg)
6050 (while (re-search-forward regexp end-marker 'limit)
6051 (when (match-string 0)
6052 ;; Make sure this is not a match for any of the preceding regexps.
6053 ;; This prevents mistaking an HR for a Setext subheading.
6054 (let (match)
6055 (save-match-data
6056 (dolist (prev-regexp previous)
6057 (or match (setq match (looking-back prev-regexp nil)))))
6058 (unless match
6059 (save-excursion (funcall function))))))
6060 (cl-pushnew regexp previous :test #'equal)))
6061 previous))
6063 (defun markdown-complete-buffer ()
6064 "Complete markup for all objects in the current buffer."
6065 (interactive "*")
6066 (markdown-complete-region (point-min) (point-max)))
6069 ;;; Markup Cycling ============================================================
6071 (defun markdown-cycle-atx (arg &optional remove)
6072 "Cycle ATX header markup.
6073 Promote header (decrease level) when ARG is 1 and demote
6074 header (increase level) if arg is -1. When REMOVE is non-nil,
6075 remove the header when the level reaches zero and stop cycling
6076 when it reaches six. Otherwise, perform a proper cycling through
6077 levels one through six. Assumes match data is available for
6078 `markdown-regex-header-atx'."
6079 (let* ((old-level (length (match-string 1)))
6080 (new-level (+ old-level arg))
6081 (text (match-string 2)))
6082 (when (not remove)
6083 (setq new-level (% new-level 6))
6084 (setq new-level (cond ((= new-level 0) 6)
6085 ((< new-level 0) (+ new-level 6))
6086 (t new-level))))
6087 (cond
6088 ((= new-level 0)
6089 (markdown-unwrap-thing-at-point nil 0 2))
6090 ((<= new-level 6)
6091 (goto-char (match-beginning 0))
6092 (delete-region (match-beginning 0) (match-end 0))
6093 (markdown-insert-header new-level text nil)))))
6095 (defun markdown-cycle-setext (arg &optional remove)
6096 "Cycle setext header markup.
6097 Promote header (increase level) when ARG is 1 and demote
6098 header (decrease level or remove) if arg is -1. When demoting a
6099 level-two setext header, replace with a level-three atx header.
6100 When REMOVE is non-nil, remove the header when the level reaches
6101 zero. Otherwise, cycle back to a level six atx header. Assumes
6102 match data is available for `markdown-regex-header-setext'."
6103 (let* ((char (char-after (match-beginning 2)))
6104 (old-level (if (char-equal char ?=) 1 2))
6105 (new-level (+ old-level arg)))
6106 (when (and (not remove) (= new-level 0))
6107 (setq new-level 6))
6108 (cond
6109 ((= new-level 0)
6110 (markdown-unwrap-thing-at-point nil 0 1))
6111 ((<= new-level 2)
6112 (markdown-insert-header new-level nil t))
6113 ((<= new-level 6)
6114 (markdown-insert-header new-level nil nil)))))
6116 (defun markdown-cycle-hr (arg &optional remove)
6117 "Cycle string used for horizontal rule from `markdown-hr-strings'.
6118 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
6119 backwards (promote). When REMOVE is non-nil, remove the hr instead
6120 of cycling when the end of the list is reached.
6121 Assumes match data is available for `markdown-regex-hr'."
6122 (let* ((strings (if (= arg -1)
6123 (reverse markdown-hr-strings)
6124 markdown-hr-strings))
6125 (tail (member (match-string 0) strings))
6126 (new (or (cadr tail)
6127 (if remove
6128 (if (= arg 1)
6130 (car tail))
6131 (car strings)))))
6132 (replace-match new)))
6134 (defun markdown-cycle-bold ()
6135 "Cycle bold markup between underscores and asterisks.
6136 Assumes match data is available for `markdown-regex-bold'."
6137 (save-excursion
6138 (let* ((old-delim (match-string 3))
6139 (new-delim (if (string-equal old-delim "**") "__" "**")))
6140 (replace-match new-delim t t nil 3)
6141 (replace-match new-delim t t nil 5))))
6143 (defun markdown-cycle-italic ()
6144 "Cycle italic markup between underscores and asterisks.
6145 Assumes match data is available for `markdown-regex-italic'."
6146 (save-excursion
6147 (let* ((old-delim (match-string 2))
6148 (new-delim (if (string-equal old-delim "*") "_" "*")))
6149 (replace-match new-delim t t nil 2)
6150 (replace-match new-delim t t nil 4))))
6153 ;;; Keymap ====================================================================
6155 (defun markdown--style-map-prompt ()
6156 "Return a formatted prompt for Markdown markup insertion."
6157 (when markdown-enable-prefix-prompts
6158 (concat
6159 "Markdown: "
6160 (propertize "bold" 'face 'markdown-bold-face) ", "
6161 (propertize "italic" 'face 'markdown-italic-face) ", "
6162 (propertize "code" 'face 'markdown-inline-code-face) ", "
6163 (propertize "C = GFM code" 'face 'markdown-code-face) ", "
6164 (propertize "pre" 'face 'markdown-pre-face) ", "
6165 (propertize "footnote" 'face 'markdown-footnote-text-face) ", "
6166 (propertize "q = blockquote" 'face 'markdown-blockquote-face) ", "
6167 (propertize "h & 1-6 = heading" 'face 'markdown-header-face) ", "
6168 (propertize "- = hr" 'face 'markdown-hr-face) ", "
6169 "C-h = more")))
6171 (defun markdown--command-map-prompt ()
6172 "Return prompt for Markdown buffer-wide commands."
6173 (when markdown-enable-prefix-prompts
6174 (concat
6175 "Command: "
6176 (propertize "m" 'face 'markdown-bold-face) "arkdown, "
6177 (propertize "p" 'face 'markdown-bold-face) "review, "
6178 (propertize "o" 'face 'markdown-bold-face) "pen, "
6179 (propertize "e" 'face 'markdown-bold-face) "xport, "
6180 "export & pre" (propertize "v" 'face 'markdown-bold-face) "iew, "
6181 (propertize "c" 'face 'markdown-bold-face) "heck refs, "
6182 "C-h = more")))
6184 (defvar markdown-mode-style-map
6185 (let ((map (make-keymap (markdown--style-map-prompt))))
6186 (define-key map (kbd "1") 'markdown-insert-header-atx-1)
6187 (define-key map (kbd "2") 'markdown-insert-header-atx-2)
6188 (define-key map (kbd "3") 'markdown-insert-header-atx-3)
6189 (define-key map (kbd "4") 'markdown-insert-header-atx-4)
6190 (define-key map (kbd "5") 'markdown-insert-header-atx-5)
6191 (define-key map (kbd "6") 'markdown-insert-header-atx-6)
6192 (define-key map (kbd "!") 'markdown-insert-header-setext-1)
6193 (define-key map (kbd "@") 'markdown-insert-header-setext-2)
6194 (define-key map (kbd "b") 'markdown-insert-bold)
6195 (define-key map (kbd "c") 'markdown-insert-code)
6196 (define-key map (kbd "C") 'markdown-insert-gfm-code-block)
6197 (define-key map (kbd "f") 'markdown-insert-footnote)
6198 (define-key map (kbd "h") 'markdown-insert-header-dwim)
6199 (define-key map (kbd "H") 'markdown-insert-header-setext-dwim)
6200 (define-key map (kbd "i") 'markdown-insert-italic)
6201 (define-key map (kbd "k") 'markdown-insert-kbd)
6202 (define-key map (kbd "l") 'markdown-insert-link)
6203 (define-key map (kbd "p") 'markdown-insert-pre)
6204 (define-key map (kbd "P") 'markdown-pre-region)
6205 (define-key map (kbd "q") 'markdown-insert-blockquote)
6206 (define-key map (kbd "s") 'markdown-insert-strike-through)
6207 (define-key map (kbd "Q") 'markdown-blockquote-region)
6208 (define-key map (kbd "w") 'markdown-insert-wiki-link)
6209 (define-key map (kbd "-") 'markdown-insert-hr)
6210 (define-key map (kbd "[") 'markdown-insert-gfm-checkbox)
6211 ;; Deprecated keys that may be removed in a future version
6212 (define-key map (kbd "e") 'markdown-insert-italic)
6213 map)
6214 "Keymap for Markdown text styling commands.")
6216 (defvar markdown-mode-command-map
6217 (let ((map (make-keymap (markdown--command-map-prompt))))
6218 (define-key map (kbd "m") 'markdown-other-window)
6219 (define-key map (kbd "p") 'markdown-preview)
6220 (define-key map (kbd "e") 'markdown-export)
6221 (define-key map (kbd "v") 'markdown-export-and-preview)
6222 (define-key map (kbd "o") 'markdown-open)
6223 (define-key map (kbd "l") 'markdown-live-preview-mode)
6224 (define-key map (kbd "w") 'markdown-kill-ring-save)
6225 (define-key map (kbd "c") 'markdown-check-refs)
6226 (define-key map (kbd "n") 'markdown-cleanup-list-numbers)
6227 (define-key map (kbd "]") 'markdown-complete-buffer)
6228 (define-key map (kbd "^") 'markdown-table-sort-lines)
6229 (define-key map (kbd "|") 'markdown-table-convert-region)
6230 (define-key map (kbd "t") 'markdown-table-transpose)
6231 map)
6232 "Keymap for Markdown buffer-wide commands.")
6234 (defvar markdown-mode-map
6235 (let ((map (make-keymap)))
6236 ;; Markup insertion & removal
6237 (define-key map (kbd "C-c C-s") markdown-mode-style-map)
6238 (define-key map (kbd "C-c C-l") 'markdown-insert-link)
6239 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
6240 ;; Promotion, demotion, and cycling
6241 (define-key map (kbd "C-c C--") 'markdown-promote)
6242 (define-key map (kbd "C-c C-=") 'markdown-demote)
6243 (define-key map (kbd "C-c C-]") 'markdown-complete)
6244 ;; Following and doing things
6245 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
6246 (define-key map (kbd "C-c C-d") 'markdown-do)
6247 (define-key map (kbd "C-c '") 'markdown-edit-code-block)
6248 ;; Indentation
6249 (define-key map (kbd "C-m") 'markdown-enter-key)
6250 (define-key map (kbd "DEL") 'markdown-outdent-or-delete)
6251 (define-key map (kbd "C-c >") 'markdown-indent-region)
6252 (define-key map (kbd "C-c <") 'markdown-outdent-region)
6253 ;; Visibility cycling
6254 (define-key map (kbd "TAB") 'markdown-cycle)
6255 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
6256 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
6257 (define-key map (kbd "<backtab>") 'markdown-shifttab)
6258 ;; Heading and list navigation
6259 (define-key map (kbd "C-c C-n") 'markdown-outline-next)
6260 (define-key map (kbd "C-c C-p") 'markdown-outline-previous)
6261 (define-key map (kbd "C-c C-f") 'markdown-outline-next-same-level)
6262 (define-key map (kbd "C-c C-b") 'markdown-outline-previous-same-level)
6263 (define-key map (kbd "C-c C-u") 'markdown-outline-up)
6264 ;; Buffer-wide commands
6265 (define-key map (kbd "C-c C-c") markdown-mode-command-map)
6266 ;; Subtree, list, and table editing
6267 (define-key map (kbd "C-c <up>") 'markdown-move-up)
6268 (define-key map (kbd "C-c <down>") 'markdown-move-down)
6269 (define-key map (kbd "C-c <left>") 'markdown-promote)
6270 (define-key map (kbd "C-c <right>") 'markdown-demote)
6271 (define-key map (kbd "C-c S-<up>") 'markdown-table-delete-row)
6272 (define-key map (kbd "C-c S-<down>") 'markdown-table-insert-row)
6273 (define-key map (kbd "C-c S-<left>") 'markdown-table-delete-column)
6274 (define-key map (kbd "C-c S-<right>") 'markdown-table-insert-column)
6275 (define-key map (kbd "C-c C-M-h") 'markdown-mark-subtree)
6276 (define-key map (kbd "C-x n s") 'markdown-narrow-to-subtree)
6277 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
6278 (define-key map (kbd "C-c C-j") 'markdown-insert-list-item)
6279 ;; Paragraphs (Markdown context aware)
6280 (define-key map [remap backward-paragraph] 'markdown-backward-paragraph)
6281 (define-key map [remap forward-paragraph] 'markdown-forward-paragraph)
6282 (define-key map [remap mark-paragraph] 'markdown-mark-paragraph)
6283 ;; Blocks (one or more paragraphs)
6284 (define-key map (kbd "C-M-{") 'markdown-backward-block)
6285 (define-key map (kbd "C-M-}") 'markdown-forward-block)
6286 (define-key map (kbd "C-c M-h") 'markdown-mark-block)
6287 (define-key map (kbd "C-x n b") 'markdown-narrow-to-block)
6288 ;; Pages (top-level sections)
6289 (define-key map [remap backward-page] 'markdown-backward-page)
6290 (define-key map [remap forward-page] 'markdown-forward-page)
6291 (define-key map [remap mark-page] 'markdown-mark-page)
6292 (define-key map [remap narrow-to-page] 'markdown-narrow-to-page)
6293 ;; Link Movement
6294 (define-key map (kbd "M-n") 'markdown-next-link)
6295 (define-key map (kbd "M-p") 'markdown-previous-link)
6296 ;; Toggling functionality
6297 (define-key map (kbd "C-c C-x C-e") 'markdown-toggle-math)
6298 (define-key map (kbd "C-c C-x C-f") 'markdown-toggle-fontify-code-blocks-natively)
6299 (define-key map (kbd "C-c C-x C-i") 'markdown-toggle-inline-images)
6300 (define-key map (kbd "C-c C-x C-l") 'markdown-toggle-url-hiding)
6301 (define-key map (kbd "C-c C-x C-m") 'markdown-toggle-markup-hiding)
6302 ;; Alternative keys (in case of problems with the arrow keys)
6303 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
6304 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
6305 (define-key map (kbd "C-c C-x l") 'markdown-promote)
6306 (define-key map (kbd "C-c C-x r") 'markdown-demote)
6307 ;; Deprecated keys that may be removed in a future version
6308 (define-key map (kbd "C-c C-a L") 'markdown-insert-link) ;; C-c C-l
6309 (define-key map (kbd "C-c C-a l") 'markdown-insert-link) ;; C-c C-l
6310 (define-key map (kbd "C-c C-a r") 'markdown-insert-link) ;; C-c C-l
6311 (define-key map (kbd "C-c C-a u") 'markdown-insert-uri) ;; C-c C-l
6312 (define-key map (kbd "C-c C-a f") 'markdown-insert-footnote)
6313 (define-key map (kbd "C-c C-a w") 'markdown-insert-wiki-link)
6314 (define-key map (kbd "C-c C-t 1") 'markdown-insert-header-atx-1)
6315 (define-key map (kbd "C-c C-t 2") 'markdown-insert-header-atx-2)
6316 (define-key map (kbd "C-c C-t 3") 'markdown-insert-header-atx-3)
6317 (define-key map (kbd "C-c C-t 4") 'markdown-insert-header-atx-4)
6318 (define-key map (kbd "C-c C-t 5") 'markdown-insert-header-atx-5)
6319 (define-key map (kbd "C-c C-t 6") 'markdown-insert-header-atx-6)
6320 (define-key map (kbd "C-c C-t !") 'markdown-insert-header-setext-1)
6321 (define-key map (kbd "C-c C-t @") 'markdown-insert-header-setext-2)
6322 (define-key map (kbd "C-c C-t h") 'markdown-insert-header-dwim)
6323 (define-key map (kbd "C-c C-t H") 'markdown-insert-header-setext-dwim)
6324 (define-key map (kbd "C-c C-t s") 'markdown-insert-header-setext-2)
6325 (define-key map (kbd "C-c C-t t") 'markdown-insert-header-setext-1)
6326 (define-key map (kbd "C-c C-i") 'markdown-insert-image)
6327 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item) ;; C-c C-j
6328 (define-key map (kbd "C-c C-x C-x") 'markdown-toggle-gfm-checkbox) ;; C-c C-d
6329 (define-key map (kbd "C-c -") 'markdown-insert-hr)
6330 map)
6331 "Keymap for Markdown major mode.")
6333 (defvar markdown-mode-mouse-map
6334 (let ((map (make-sparse-keymap)))
6335 (define-key map [follow-link] 'mouse-face)
6336 (define-key map [mouse-2] 'markdown-follow-link-at-point)
6337 map)
6338 "Keymap for following links with mouse.")
6340 (defvar gfm-mode-map
6341 (let ((map (make-sparse-keymap)))
6342 (set-keymap-parent map markdown-mode-map)
6343 (define-key map (kbd "C-c C-s d") 'markdown-insert-strike-through)
6344 (define-key map "`" 'markdown-electric-backquote)
6345 map)
6346 "Keymap for `gfm-mode'.
6347 See also `markdown-mode-map'.")
6350 ;;; Menu ==================================================================
6352 (easy-menu-define markdown-mode-menu markdown-mode-map
6353 "Menu for Markdown mode"
6354 '("Markdown"
6355 "---"
6356 ("Movement"
6357 ["Jump" markdown-do]
6358 ["Follow Link" markdown-follow-thing-at-point]
6359 ["Next Link" markdown-next-link]
6360 ["Previous Link" markdown-previous-link]
6361 "---"
6362 ["Next Heading or List Item" markdown-outline-next]
6363 ["Previous Heading or List Item" markdown-outline-previous]
6364 ["Next at Same Level" markdown-outline-next-same-level]
6365 ["Previous at Same Level" markdown-outline-previous-same-level]
6366 ["Up to Parent" markdown-outline-up]
6367 "---"
6368 ["Forward Paragraph" markdown-forward-paragraph]
6369 ["Backward Paragraph" markdown-backward-paragraph]
6370 ["Forward Block" markdown-forward-block]
6371 ["Backward Block" markdown-backward-block])
6372 ("Show & Hide"
6373 ["Cycle Heading Visibility" markdown-cycle (markdown-on-heading-p)]
6374 ["Cycle Heading Visibility (Global)" markdown-shifttab]
6375 "---"
6376 ["Narrow to Region" narrow-to-region]
6377 ["Narrow to Block" markdown-narrow-to-block]
6378 ["Narrow to Section" narrow-to-defun]
6379 ["Narrow to Subtree" markdown-narrow-to-subtree]
6380 ["Widen" widen (buffer-narrowed-p)]
6381 "---"
6382 ["Toggle Markup Hiding" markdown-toggle-markup-hiding
6383 :keys "C-c C-x C-m"
6384 :style radio
6385 :selected markdown-hide-markup])
6386 "---"
6387 ("Headings & Structure"
6388 ["Automatic Heading" markdown-insert-header-dwim :keys "C-c C-s h"]
6389 ["Automatic Heading (Setext)" markdown-insert-header-setext-dwim :keys "C-c C-s H"]
6390 ("Specific Heading (atx)"
6391 ["First Level atx" markdown-insert-header-atx-1 :keys "C-c C-s 1"]
6392 ["Second Level atx" markdown-insert-header-atx-2 :keys "C-c C-s 2"]
6393 ["Third Level atx" markdown-insert-header-atx-3 :keys "C-c C-s 3"]
6394 ["Fourth Level atx" markdown-insert-header-atx-4 :keys "C-c C-s 4"]
6395 ["Fifth Level atx" markdown-insert-header-atx-5 :keys "C-c C-s 5"]
6396 ["Sixth Level atx" markdown-insert-header-atx-6 :keys "C-c C-s 6"])
6397 ("Specific Heading (Setext)"
6398 ["First Level Setext" markdown-insert-header-setext-1 :keys "C-c C-s !"]
6399 ["Second Level Setext" markdown-insert-header-setext-2 :keys "C-c C-s @"])
6400 ["Horizontal Rule" markdown-insert-hr :keys "C-c C-s -"]
6401 "---"
6402 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
6403 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
6404 ["Promote Subtree" markdown-promote :keys "C-c <left>"]
6405 ["Demote Subtree" markdown-demote :keys "C-c <right>"])
6406 ("Region & Mark"
6407 ["Indent Region" markdown-indent-region]
6408 ["Outdent Region" markdown-outdent-region]
6409 "--"
6410 ["Mark Paragraph" mark-paragraph]
6411 ["Mark Block" markdown-mark-block]
6412 ["Mark Section" mark-defun]
6413 ["Mark Subtree" markdown-mark-subtree])
6414 ("Lists"
6415 ["Insert List Item" markdown-insert-list-item]
6416 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
6417 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
6418 ["Indent Subtree" markdown-demote :keys "C-c <right>"]
6419 ["Outdent Subtree" markdown-promote :keys "C-c <left>"]
6420 ["Renumber List" markdown-cleanup-list-numbers]
6421 ["Insert Task List Item" markdown-insert-gfm-checkbox :keys "C-c C-x ["]
6422 ["Toggle Task List Item" markdown-toggle-gfm-checkbox (markdown-gfm-task-list-item-at-point) :keys "C-c C-d"])
6423 ("Links & Images"
6424 ["Insert Link" markdown-insert-link]
6425 ["Insert Image" markdown-insert-image]
6426 ["Insert Footnote" markdown-insert-footnote :keys "C-c C-s f"]
6427 ["Insert Wiki Link" markdown-insert-wiki-link :keys "C-c C-s w"]
6428 "---"
6429 ["Check References" markdown-check-refs]
6430 ["Toggle URL Hiding" markdown-toggle-url-hiding
6431 :style radio
6432 :selected markdown-hide-urls]
6433 ["Toggle Inline Images" markdown-toggle-inline-images
6434 :keys "C-c C-x C-i"
6435 :style radio
6436 :selected markdown-inline-image-overlays]
6437 ["Toggle Wiki Links" markdown-toggle-wiki-links
6438 :style radio
6439 :selected markdown-enable-wiki-links])
6440 ("Styles"
6441 ["Bold" markdown-insert-bold]
6442 ["Italic" markdown-insert-italic]
6443 ["Code" markdown-insert-code]
6444 ["Strikethrough" markdown-insert-strike-through]
6445 ["Keyboard" markdown-insert-kbd]
6446 "---"
6447 ["Blockquote" markdown-insert-blockquote]
6448 ["Preformatted" markdown-insert-pre]
6449 ["GFM Code Block" markdown-insert-gfm-code-block]
6450 ["Edit Code Block" markdown-edit-code-block (markdown-code-block-at-point-p)]
6451 "---"
6452 ["Blockquote Region" markdown-blockquote-region]
6453 ["Preformatted Region" markdown-pre-region]
6454 "---"
6455 ["Fontify Code Blocks Natively" markdown-toggle-fontify-code-blocks-natively
6456 :style radio
6457 :selected markdown-fontify-code-blocks-natively]
6458 ["LaTeX Math Support" markdown-toggle-math
6459 :style radio
6460 :selected markdown-enable-math])
6461 "---"
6462 ("Preview & Export"
6463 ["Compile" markdown-other-window]
6464 ["Preview" markdown-preview]
6465 ["Export" markdown-export]
6466 ["Export & View" markdown-export-and-preview]
6467 ["Open" markdown-open]
6468 ["Live Export" markdown-live-preview-mode
6469 :style radio
6470 :selected markdown-live-preview-mode]
6471 ["Kill ring save" markdown-kill-ring-save])
6472 ("Markup Completion and Cycling"
6473 ["Complete Markup" markdown-complete]
6474 ["Promote Element" markdown-promote :keys "C-c C--"]
6475 ["Demote Element" markdown-demote :keys "C-c C-="])
6476 "---"
6477 ["Kill Element" markdown-kill-thing-at-point]
6478 "---"
6479 ("Documentation"
6480 ["Version" markdown-show-version]
6481 ["Homepage" markdown-mode-info]
6482 ["Describe Mode" (describe-function 'markdown-mode)]
6483 ["Guide" (browse-url "https://leanpub.com/markdown-mode")])))
6486 ;;; imenu =====================================================================
6488 (defun markdown-imenu-create-nested-index ()
6489 "Create and return a nested imenu index alist for the current buffer.
6490 See `imenu-create-index-function' and `imenu--index-alist' for details."
6491 (let* ((root '(nil . nil))
6492 cur-alist
6493 (cur-level 0)
6494 (empty-heading "-")
6495 (self-heading ".")
6496 hashes pos level heading)
6497 (save-excursion
6498 (goto-char (point-min))
6499 (while (re-search-forward markdown-regex-header (point-max) t)
6500 (unless (markdown-code-block-at-point-p)
6501 (cond
6502 ((match-string-no-properties 2) ;; level 1 setext
6503 (setq heading (match-string-no-properties 1))
6504 (setq pos (match-beginning 1)
6505 level 1))
6506 ((match-string-no-properties 3) ;; level 2 setext
6507 (setq heading (match-string-no-properties 1))
6508 (setq pos (match-beginning 1)
6509 level 2))
6510 ((setq hashes (markdown-trim-whitespace
6511 (match-string-no-properties 4)))
6512 (setq heading (match-string-no-properties 5)
6513 pos (match-beginning 4)
6514 level (length hashes))))
6515 (let ((alist (list (cons heading pos))))
6516 (cond
6517 ((= cur-level level) ; new sibling
6518 (setcdr cur-alist alist)
6519 (setq cur-alist alist))
6520 ((< cur-level level) ; first child
6521 (dotimes (_ (- level cur-level 1))
6522 (setq alist (list (cons empty-heading alist))))
6523 (if cur-alist
6524 (let* ((parent (car cur-alist))
6525 (self-pos (cdr parent)))
6526 (setcdr parent (cons (cons self-heading self-pos) alist)))
6527 (setcdr root alist)) ; primogenitor
6528 (setq cur-alist alist)
6529 (setq cur-level level))
6530 (t ; new sibling of an ancestor
6531 (let ((sibling-alist (last (cdr root))))
6532 (dotimes (_ (1- level))
6533 (setq sibling-alist (last (cdar sibling-alist))))
6534 (setcdr sibling-alist alist)
6535 (setq cur-alist alist))
6536 (setq cur-level level))))))
6537 (cdr root))))
6539 (defun markdown-imenu-create-flat-index ()
6540 "Create and return a flat imenu index alist for the current buffer.
6541 See `imenu-create-index-function' and `imenu--index-alist' for details."
6542 (let* ((empty-heading "-") index heading pos)
6543 (save-excursion
6544 (goto-char (point-min))
6545 (while (re-search-forward markdown-regex-header (point-max) t)
6546 (when (and (not (markdown-code-block-at-point-p))
6547 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin)))
6548 (cond
6549 ((setq heading (match-string-no-properties 1))
6550 (setq pos (match-beginning 1)))
6551 ((setq heading (match-string-no-properties 5))
6552 (setq pos (match-beginning 4))))
6553 (or (> (length heading) 0)
6554 (setq heading empty-heading))
6555 (setq index (append index (list (cons heading pos))))))
6556 index)))
6559 ;;; References ================================================================
6561 (defun markdown-reference-goto-definition ()
6562 "Jump to the definition of the reference at point or create it."
6563 (interactive)
6564 (when (thing-at-point-looking-at markdown-regex-link-reference)
6565 (let* ((text (match-string-no-properties 3))
6566 (reference (match-string-no-properties 6))
6567 (target (downcase (if (string= reference "") text reference)))
6568 (loc (cadr (save-match-data (markdown-reference-definition target)))))
6569 (if loc
6570 (goto-char loc)
6571 (goto-char (match-beginning 0))
6572 (markdown-insert-reference-definition target)))))
6574 (defun markdown-reference-find-links (reference)
6575 "Return a list of all links for REFERENCE.
6576 REFERENCE should not include the surrounding square brackets.
6577 Elements of the list have the form (text start line), where
6578 text is the link text, start is the location at the beginning of
6579 the link, and line is the line number on which the link appears."
6580 (let* ((ref-quote (regexp-quote reference))
6581 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
6582 ref-quote ref-quote))
6583 links)
6584 (save-excursion
6585 (goto-char (point-min))
6586 (while (re-search-forward regexp nil t)
6587 (let* ((text (or (match-string-no-properties 1)
6588 (match-string-no-properties 2)))
6589 (start (match-beginning 0))
6590 (line (markdown-line-number-at-pos)))
6591 (cl-pushnew (list text start line) links :test #'equal))))
6592 links))
6594 (defun markdown-get-undefined-refs ()
6595 "Return a list of undefined Markdown references.
6596 Result is an alist of pairs (reference . occurrences), where
6597 occurrences is itself another alist of pairs (label . line-number).
6598 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
6599 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
6600 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
6601 (let ((missing))
6602 (save-excursion
6603 (goto-char (point-min))
6604 (while
6605 (re-search-forward markdown-regex-link-reference nil t)
6606 (let* ((text (match-string-no-properties 3))
6607 (reference (match-string-no-properties 6))
6608 (target (downcase (if (string= reference "") text reference))))
6609 (unless (markdown-reference-definition target)
6610 (let ((entry (assoc target missing)))
6611 (if (not entry)
6612 (cl-pushnew
6613 (cons target (list (cons text (markdown-line-number-at-pos))))
6614 missing :test #'equal)
6615 (setcdr entry
6616 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
6617 (reverse missing))))
6619 (defconst markdown-reference-check-buffer
6620 "*Undefined references for %buffer%*"
6621 "Pattern for name of buffer for listing undefined references.
6622 The string %buffer% will be replaced by the corresponding
6623 `markdown-mode' buffer name.")
6625 (defun markdown-reference-check-buffer (&optional buffer-name)
6626 "Name and return buffer for reference checking.
6627 BUFFER-NAME is the name of the main buffer being visited."
6628 (or buffer-name (setq buffer-name (buffer-name)))
6629 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
6630 "%buffer%" buffer-name
6631 markdown-reference-check-buffer))))
6632 (with-current-buffer refbuf
6633 (when view-mode
6634 (View-exit-and-edit))
6635 (use-local-map button-buffer-map)
6636 (erase-buffer))
6637 refbuf))
6639 (defconst markdown-reference-links-buffer
6640 "*Reference links for %buffer%*"
6641 "Pattern for name of buffer for listing references.
6642 The string %buffer% will be replaced by the corresponding buffer name.")
6644 (defun markdown-reference-links-buffer (&optional buffer-name)
6645 "Name, setup, and return a buffer for listing links.
6646 BUFFER-NAME is the name of the main buffer being visited."
6647 (or buffer-name (setq buffer-name (buffer-name)))
6648 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
6649 "%buffer%" buffer-name
6650 markdown-reference-links-buffer))))
6651 (with-current-buffer linkbuf
6652 (when view-mode
6653 (View-exit-and-edit))
6654 (use-local-map button-buffer-map)
6655 (erase-buffer))
6656 linkbuf))
6658 ;; Add an empty Markdown reference definition to buffer
6659 ;; specified in the 'target-buffer property. The reference name is
6660 ;; the button's label.
6661 (define-button-type 'markdown-undefined-reference-button
6662 'help-echo "mouse-1, RET: create definition for undefined reference"
6663 'follow-link t
6664 'face 'bold
6665 'action (lambda (b)
6666 (let ((buffer (button-get b 'target-buffer))
6667 (line (button-get b 'target-line))
6668 (label (button-label b)))
6669 (switch-to-buffer-other-window buffer)
6670 (goto-char (point-min))
6671 (forward-line line)
6672 (markdown-insert-reference-definition label)
6673 (markdown-check-refs t))))
6675 ;; Jump to line in buffer specified by 'target-buffer property.
6676 ;; Line number is button's 'line property.
6677 (define-button-type 'markdown-goto-line-button
6678 'help-echo "mouse-1, RET: go to line"
6679 'follow-link t
6680 'face 'italic
6681 'action (lambda (b)
6682 (message (button-get b 'buffer))
6683 (switch-to-buffer-other-window (button-get b 'target-buffer))
6684 ;; use call-interactively to silence compiler
6685 (let ((current-prefix-arg (button-get b 'target-line)))
6686 (call-interactively 'goto-line))))
6688 ;; Jumps to a particular link at location given by 'target-char
6689 ;; property in buffer given by 'target-buffer property.
6690 (define-button-type 'markdown-location-button
6691 'help-echo "mouse-1, RET: jump to location of link"
6692 'follow-link t
6693 'face 'bold
6694 'action (lambda (b)
6695 (let ((target (button-get b 'target-buffer))
6696 (loc (button-get b 'target-char)))
6697 (kill-buffer-and-window)
6698 (switch-to-buffer target)
6699 (goto-char loc))))
6701 (defun markdown-insert-undefined-reference-button (reference oldbuf)
6702 "Insert a button for creating REFERENCE in buffer OLDBUF.
6703 REFERENCE should be a list of the form (reference . occurrences),
6704 as by `markdown-get-undefined-refs'."
6705 (let ((label (car reference)))
6706 ;; Create a reference button
6707 (insert-button label
6708 :type 'markdown-undefined-reference-button
6709 'target-buffer oldbuf
6710 'target-line (cdr (car (cdr reference))))
6711 (insert " (")
6712 (dolist (occurrence (cdr reference))
6713 (let ((line (cdr occurrence)))
6714 ;; Create a line number button
6715 (insert-button (number-to-string line)
6716 :type 'markdown-goto-line-button
6717 'target-buffer oldbuf
6718 'target-line line)
6719 (insert " ")))
6720 (delete-char -1)
6721 (insert ")")
6722 (newline)))
6724 (defun markdown-insert-link-button (link oldbuf)
6725 "Insert a button for jumping to LINK in buffer OLDBUF.
6726 LINK should be a list of the form (text char line) containing
6727 the link text, location, and line number."
6728 (let ((label (cl-first link))
6729 (char (cl-second link))
6730 (line (cl-third link)))
6731 ;; Create a reference button
6732 (insert-button label
6733 :type 'markdown-location-button
6734 'target-buffer oldbuf
6735 'target-char char)
6736 (insert (format " (line %d)\n" line))))
6738 (defun markdown-reference-goto-link (&optional reference)
6739 "Jump to the location of the first use of REFERENCE."
6740 (interactive)
6741 (unless reference
6742 (if (thing-at-point-looking-at markdown-regex-reference-definition)
6743 (setq reference (match-string-no-properties 2))
6744 (user-error "No reference definition at point")))
6745 (let ((links (markdown-reference-find-links reference)))
6746 (cond ((= (length links) 1)
6747 (goto-char (cadr (car links))))
6748 ((> (length links) 1)
6749 (let ((oldbuf (current-buffer))
6750 (linkbuf (markdown-reference-links-buffer)))
6751 (with-current-buffer linkbuf
6752 (insert "Links using reference " reference ":\n\n")
6753 (dolist (link (reverse links))
6754 (markdown-insert-link-button link oldbuf)))
6755 (view-buffer-other-window linkbuf)
6756 (goto-char (point-min))
6757 (forward-line 2)))
6759 (error "No links for reference %s" reference)))))
6761 (defun markdown-check-refs (&optional silent)
6762 "Show all undefined Markdown references in current `markdown-mode' buffer.
6763 If SILENT is non-nil, do not message anything when no undefined
6764 references found.
6765 Links which have empty reference definitions are considered to be
6766 defined."
6767 (interactive "P")
6768 (when (not (eq major-mode 'markdown-mode))
6769 (user-error "Not available in current mode"))
6770 (let ((oldbuf (current-buffer))
6771 (refs (markdown-get-undefined-refs))
6772 (refbuf (markdown-reference-check-buffer)))
6773 (if (null refs)
6774 (progn
6775 (when (not silent)
6776 (message "No undefined references found"))
6777 (kill-buffer refbuf))
6778 (with-current-buffer refbuf
6779 (insert "The following references are undefined:\n\n")
6780 (dolist (ref refs)
6781 (markdown-insert-undefined-reference-button ref oldbuf))
6782 (view-buffer-other-window refbuf)
6783 (goto-char (point-min))
6784 (forward-line 2)))))
6787 ;;; Lists =====================================================================
6789 (defun markdown-insert-list-item (&optional arg)
6790 "Insert a new list item.
6791 If the point is inside unordered list, insert a bullet mark. If
6792 the point is inside ordered list, insert the next number followed
6793 by a period. Use the previous list item to determine the amount
6794 of whitespace to place before and after list markers.
6796 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
6797 decrease the indentation by one level.
6799 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
6800 increase the indentation by one level."
6801 (interactive "p")
6802 (let (bounds cur-indent marker indent new-indent new-loc)
6803 (save-match-data
6804 ;; Look for a list item on current or previous non-blank line
6805 (save-excursion
6806 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
6807 (not (bobp))
6808 (markdown-cur-line-blank-p))
6809 (forward-line -1)))
6810 (when bounds
6811 (cond ((save-excursion
6812 (skip-chars-backward " \t")
6813 (looking-at-p markdown-regex-list))
6814 (beginning-of-line)
6815 (insert "\n")
6816 (forward-line -1))
6817 ((not (markdown-cur-line-blank-p))
6818 (newline)))
6819 (setq new-loc (point)))
6820 ;; Look ahead for a list item on next non-blank line
6821 (unless bounds
6822 (save-excursion
6823 (while (and (null bounds)
6824 (not (eobp))
6825 (markdown-cur-line-blank-p))
6826 (forward-line)
6827 (setq bounds (markdown-cur-list-item-bounds))))
6828 (when bounds
6829 (setq new-loc (point))
6830 (unless (markdown-cur-line-blank-p)
6831 (newline))))
6832 (if (not bounds)
6833 ;; When not in a list, start a new unordered one
6834 (progn
6835 (unless (markdown-cur-line-blank-p)
6836 (insert "\n"))
6837 (insert markdown-unordered-list-item-prefix))
6838 ;; Compute indentation and marker for new list item
6839 (setq cur-indent (nth 2 bounds))
6840 (setq marker (nth 4 bounds))
6841 ;; If current item is a GFM checkbox, insert new unchecked checkbox.
6842 (when (nth 5 bounds)
6843 (setq marker
6844 (concat marker
6845 (replace-regexp-in-string "[Xx]" " " (nth 5 bounds)))))
6846 (cond
6847 ;; Dedent: decrement indentation, find previous marker.
6848 ((= arg 4)
6849 (setq indent (max (- cur-indent 4) 0))
6850 (let ((prev-bounds
6851 (save-excursion
6852 (goto-char (nth 0 bounds))
6853 (when (markdown-up-list)
6854 (markdown-cur-list-item-bounds)))))
6855 (when prev-bounds
6856 (setq marker (nth 4 prev-bounds)))))
6857 ;; Indent: increment indentation by 4, use same marker.
6858 ((= arg 16) (setq indent (+ cur-indent 4)))
6859 ;; Same level: keep current indentation and marker.
6860 (t (setq indent cur-indent)))
6861 (setq new-indent (make-string indent 32))
6862 (goto-char new-loc)
6863 (cond
6864 ;; Ordered list
6865 ((string-match-p "[0-9]" marker)
6866 (if (= arg 16) ;; starting a new column indented one more level
6867 (insert (concat new-indent "1. "))
6868 ;; Don't use previous match-data
6869 (set-match-data nil)
6870 ;; travel up to the last item and pick the correct number. If
6871 ;; the argument was nil, "new-indent = cur-indent" is the same,
6872 ;; so we don't need special treatment. Neat.
6873 (save-excursion
6874 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
6875 (>= (forward-line -1) 0))))
6876 (let* ((old-prefix (match-string 1))
6877 (old-spacing (match-string 2))
6878 (new-prefix (if old-prefix
6879 (int-to-string (1+ (string-to-number old-prefix)))
6880 "1"))
6881 (space-adjust (- (length old-prefix) (length new-prefix)))
6882 (new-spacing (if (and (match-string 2)
6883 (not (string-match-p "\t" old-spacing))
6884 (< space-adjust 0)
6885 (> space-adjust (- 1 (length (match-string 2)))))
6886 (substring (match-string 2) 0 space-adjust)
6887 (or old-spacing ". "))))
6888 (insert (concat new-indent new-prefix new-spacing)))))
6889 ;; Unordered list, GFM task list, or ordered list with hash mark
6890 ((string-match-p "[\\*\\+-]\\|#\\." marker)
6891 (insert new-indent marker))))
6892 ;; Propertize the newly inserted list item now
6893 (markdown-syntax-propertize-list-items (point-at-bol) (point-at-eol)))))
6895 (defun markdown-move-list-item-up ()
6896 "Move the current list item up in the list when possible.
6897 In nested lists, move child items with the parent item."
6898 (interactive)
6899 (let (cur prev old)
6900 (when (setq cur (markdown-cur-list-item-bounds))
6901 (setq old (point))
6902 (goto-char (nth 0 cur))
6903 (if (markdown-prev-list-item (nth 3 cur))
6904 (progn
6905 (setq prev (markdown-cur-list-item-bounds))
6906 (condition-case nil
6907 (progn
6908 (transpose-regions (nth 0 prev) (nth 1 prev)
6909 (nth 0 cur) (nth 1 cur) t)
6910 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
6911 ;; Catch error in case regions overlap.
6912 (error (goto-char old))))
6913 (goto-char old)))))
6915 (defun markdown-move-list-item-down ()
6916 "Move the current list item down in the list when possible.
6917 In nested lists, move child items with the parent item."
6918 (interactive)
6919 (let (cur next old)
6920 (when (setq cur (markdown-cur-list-item-bounds))
6921 (setq old (point))
6922 (if (markdown-next-list-item (nth 3 cur))
6923 (progn
6924 (setq next (markdown-cur-list-item-bounds))
6925 (condition-case nil
6926 (progn
6927 (transpose-regions (nth 0 cur) (nth 1 cur)
6928 (nth 0 next) (nth 1 next) nil)
6929 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
6930 ;; Catch error in case regions overlap.
6931 (error (goto-char old))))
6932 (goto-char old)))))
6934 (defun markdown-demote-list-item (&optional bounds)
6935 "Indent (or demote) the current list item.
6936 Optionally, BOUNDS of the current list item may be provided if available.
6937 In nested lists, demote child items as well."
6938 (interactive)
6939 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6940 (save-excursion
6941 (let* ((item-start (set-marker (make-marker) (nth 0 bounds)))
6942 (item-end (set-marker (make-marker) (nth 1 bounds)))
6943 (list-start (progn (markdown-beginning-of-list)
6944 (set-marker (make-marker) (point))))
6945 (list-end (progn (markdown-end-of-list)
6946 (set-marker (make-marker) (point)))))
6947 (goto-char item-start)
6948 (while (< (point) item-end)
6949 (unless (markdown-cur-line-blank-p)
6950 (insert (make-string markdown-list-indent-width ? )))
6951 (forward-line))
6952 (markdown-syntax-propertize-list-items list-start list-end)))))
6954 (defun markdown-promote-list-item (&optional bounds)
6955 "Unindent (or promote) the current list item.
6956 Optionally, BOUNDS of the current list item may be provided if available.
6957 In nested lists, demote child items as well."
6958 (interactive)
6959 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6960 (save-excursion
6961 (save-match-data
6962 (let ((item-start (set-marker (make-marker) (nth 0 bounds)))
6963 (item-end (set-marker (make-marker) (nth 1 bounds)))
6964 (list-start (progn (markdown-beginning-of-list)
6965 (set-marker (make-marker) (point))))
6966 (list-end (progn (markdown-end-of-list)
6967 (set-marker (make-marker) (point))))
6968 num regexp)
6969 (goto-char item-start)
6970 (when (looking-at (format "^[ ]\\{1,%d\\}"
6971 markdown-list-indent-width))
6972 (setq num (- (match-end 0) (match-beginning 0)))
6973 (setq regexp (format "^[ ]\\{1,%d\\}" num))
6974 (while (and (< (point) item-end)
6975 (re-search-forward regexp item-end t))
6976 (replace-match "" nil nil)
6977 (forward-line))
6978 (markdown-syntax-propertize-list-items list-start list-end)))))))
6980 (defun markdown-cleanup-list-numbers-level (&optional pfx)
6981 "Update the numbering for level PFX (as a string of spaces).
6983 Assume that the previously found match was for a numbered item in
6984 a list."
6985 (let ((cpfx pfx)
6986 (idx 0)
6987 (continue t)
6988 (step t)
6989 (sep nil))
6990 (while (and continue (not (eobp)))
6991 (setq step t)
6992 (cond
6993 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
6994 (setq cpfx (match-string-no-properties 1))
6995 (cond
6996 ((string= cpfx pfx)
6997 (save-excursion
6998 (replace-match
6999 (concat pfx (number-to-string (setq idx (1+ idx))) ". ")))
7000 (setq sep nil))
7001 ;; indented a level
7002 ((string< pfx cpfx)
7003 (setq sep (markdown-cleanup-list-numbers-level cpfx))
7004 (setq step nil))
7005 ;; exit the loop
7007 (setq step nil)
7008 (setq continue nil))))
7010 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
7011 (setq cpfx (match-string-no-properties 1))
7012 (cond
7013 ;; reset if separated before
7014 ((string= cpfx pfx) (when sep (setq idx 0)))
7015 ((string< cpfx pfx)
7016 (setq step nil)
7017 (setq continue nil))))
7018 (t (setq sep t)))
7020 (when step
7021 (beginning-of-line)
7022 (setq continue (= (forward-line) 0))))
7023 sep))
7025 (defun markdown-cleanup-list-numbers ()
7026 "Update the numbering of ordered lists."
7027 (interactive)
7028 (save-excursion
7029 (goto-char (point-min))
7030 (markdown-cleanup-list-numbers-level "")))
7033 ;;; Movement ==================================================================
7035 (defun markdown-beginning-of-defun (&optional arg)
7036 "`beginning-of-defun-function' for Markdown.
7037 This is used to find the beginning of the defun and should behave
7038 like ‘beginning-of-defun’, returning non-nil if it found the
7039 beginning of a defun. It moves the point backward, right before a
7040 heading which defines a defun. When ARG is non-nil, repeat that
7041 many times. When ARG is negative, move forward to the ARG-th
7042 following section."
7043 (or arg (setq arg 1))
7044 (when (< arg 0) (end-of-line))
7045 ;; Adjust position for setext headings.
7046 (when (and (thing-at-point-looking-at markdown-regex-header-setext)
7047 (not (= (point) (match-beginning 0)))
7048 (not (markdown-code-block-at-point-p)))
7049 (goto-char (match-end 0)))
7050 (let (found)
7051 ;; Move backward with positive argument.
7052 (while (and (not (bobp)) (> arg 0))
7053 (setq found nil)
7054 (while (and (not found)
7055 (not (bobp))
7056 (re-search-backward markdown-regex-header nil 'move))
7057 (when (not (markdown-code-block-at-pos (match-beginning 0))))
7058 (setq found (match-beginning 0)))
7059 (setq arg (1- arg)))
7060 ;; Move forward with negative argument.
7061 (while (and (not (eobp)) (< arg 0))
7062 (setq found nil)
7063 (while (and (not found)
7064 (not (eobp))
7065 (re-search-forward markdown-regex-header nil 'move))
7066 (when (not (markdown-code-block-at-pos (match-beginning 0))))
7067 (setq found (match-beginning 0)))
7068 (setq arg (1+ arg)))
7069 (when found
7070 (beginning-of-line)
7071 t)))
7073 (defun markdown-end-of-defun ()
7074 "`end-of-defun-function’ for Markdown.
7075 This is used to find the end of the defun at point.
7076 It is called with no argument, right after calling ‘beginning-of-defun-raw’,
7077 so it can assume that point is at the beginning of the defun body.
7078 It should move point to the first position after the defun."
7079 (or (eobp) (forward-char 1))
7080 (let (found)
7081 (while (and (not found)
7082 (not (eobp))
7083 (re-search-forward markdown-regex-header nil 'move))
7084 (when (not (markdown-code-block-at-pos (match-beginning 0)))
7085 (setq found (match-beginning 0))))
7086 (when found
7087 (goto-char found)
7088 (skip-syntax-backward "-"))))
7090 (make-obsolete 'markdown-beginning-of-block 'markdown-beginning-of-text-block "v2.2")
7092 (defun markdown-beginning-of-text-block ()
7093 "Move backward to previous beginning of a plain text block.
7094 This function simply looks for blank lines without considering
7095 the surrounding context in light of Markdown syntax. For that, see
7096 `markdown-backward-block'."
7097 (interactive)
7098 (let ((start (point)))
7099 (if (re-search-backward markdown-regex-block-separator nil t)
7100 (goto-char (match-end 0))
7101 (goto-char (point-min)))
7102 (when (and (= start (point)) (not (bobp)))
7103 (forward-line -1)
7104 (if (re-search-backward markdown-regex-block-separator nil t)
7105 (goto-char (match-end 0))
7106 (goto-char (point-min))))))
7108 (make-obsolete 'markdown-end-of-block 'markdown-end-of-text-block "v2.2")
7110 (defun markdown-end-of-text-block ()
7111 "Move forward to next beginning of a plain text block.
7112 This function simply looks for blank lines without considering
7113 the surrounding context in light of Markdown syntax. For that, see
7114 `markdown-forward-block'."
7115 (interactive)
7116 (beginning-of-line)
7117 (skip-chars-forward " \t\n")
7118 (when (= (point) (point-min))
7119 (forward-char))
7120 (if (re-search-forward markdown-regex-block-separator nil t)
7121 (goto-char (match-end 0))
7122 (goto-char (point-max)))
7123 (skip-chars-backward " \t\n")
7124 (forward-line))
7126 (defun markdown-backward-paragraph (&optional arg)
7127 "Move the point to the start of the current paragraph.
7128 With argument ARG, do it ARG times; a negative argument ARG = -N
7129 means move forward N blocks."
7130 (interactive "^p")
7131 (or arg (setq arg 1))
7132 (if (< arg 0)
7133 (markdown-forward-paragraph (- arg))
7134 (dotimes (_ arg)
7135 ;; Skip over whitespace in between paragraphs when moving backward.
7136 (skip-chars-backward " \t\n")
7137 (beginning-of-line)
7138 ;; Skip over code block endings.
7139 (when (markdown-range-properties-exist
7140 (point-at-bol) (point-at-eol)
7141 '(markdown-gfm-block-end
7142 markdown-tilde-fence-end))
7143 (forward-line -1))
7144 ;; Skip over blank lines inside blockquotes.
7145 (while (and (not (eobp))
7146 (looking-at markdown-regex-blockquote)
7147 (= (length (match-string 3)) 0))
7148 (forward-line -1))
7149 ;; Proceed forward based on the type of block of paragraph.
7150 (let (bounds skip)
7151 (cond
7152 ;; Blockquotes
7153 ((looking-at markdown-regex-blockquote)
7154 (while (and (not (bobp))
7155 (looking-at markdown-regex-blockquote)
7156 (> (length (match-string 3)) 0)) ;; not blank
7157 (forward-line -1))
7158 (forward-line))
7159 ;; List items
7160 ((setq bounds (markdown-cur-list-item-bounds))
7161 (goto-char (nth 0 bounds)))
7162 ;; Other
7164 (while (and (not (bobp))
7165 (not skip)
7166 (not (markdown-cur-line-blank-p))
7167 (not (looking-at markdown-regex-blockquote))
7168 (not (markdown-range-properties-exist
7169 (point-at-bol) (point-at-eol)
7170 '(markdown-gfm-block-end
7171 markdown-tilde-fence-end))))
7172 (setq skip (markdown-range-properties-exist
7173 (point-at-bol) (point-at-eol)
7174 '(markdown-gfm-block-begin
7175 markdown-tilde-fence-begin)))
7176 (forward-line -1))
7177 (unless (bobp)
7178 (forward-line 1))))))))
7180 (defun markdown-forward-paragraph (&optional arg)
7181 "Move forward to the next end of a paragraph.
7182 With argument ARG, do it ARG times; a negative argument ARG = -N
7183 means move backward N blocks."
7184 (interactive "^p")
7185 (or arg (setq arg 1))
7186 (if (< arg 0)
7187 (markdown-backward-paragraph (- arg))
7188 (dotimes (_ arg)
7189 ;; Skip whitespace in between paragraphs.
7190 (when (markdown-cur-line-blank-p)
7191 (skip-syntax-forward "-")
7192 (beginning-of-line))
7193 ;; Proceed forward based on the type of block.
7194 (let (bounds skip)
7195 (cond
7196 ;; Blockquotes
7197 ((looking-at markdown-regex-blockquote)
7198 ;; Skip over blank lines inside blockquotes.
7199 (while (and (not (eobp))
7200 (looking-at markdown-regex-blockquote)
7201 (= (length (match-string 3)) 0))
7202 (forward-line))
7203 ;; Move to end of quoted text block
7204 (while (and (not (eobp))
7205 (looking-at markdown-regex-blockquote)
7206 (> (length (match-string 3)) 0)) ;; not blank
7207 (forward-line)))
7208 ;; List items
7209 ((and (markdown-cur-list-item-bounds)
7210 (setq bounds (markdown-next-list-item-bounds)))
7211 (goto-char (nth 0 bounds)))
7212 ;; Other
7214 (forward-line)
7215 (while (and (not (eobp))
7216 (not skip)
7217 (not (markdown-cur-line-blank-p))
7218 (not (looking-at markdown-regex-blockquote))
7219 (not (markdown-range-properties-exist
7220 (point-at-bol) (point-at-eol)
7221 '(markdown-gfm-block-begin
7222 markdown-tilde-fence-begin))))
7223 (setq skip (markdown-range-properties-exist
7224 (point-at-bol) (point-at-eol)
7225 '(markdown-gfm-block-end
7226 markdown-tilde-fence-end)))
7227 (forward-line))))))))
7229 (defun markdown-backward-block (&optional arg)
7230 "Move the point to the start of the current Markdown block.
7231 Moves across complete code blocks, list items, and blockquotes,
7232 but otherwise stops at blank lines, headers, and horizontal
7233 rules. With argument ARG, do it ARG times; a negative argument
7234 ARG = -N means move forward N blocks."
7235 (interactive "^p")
7236 (or arg (setq arg 1))
7237 (if (< arg 0)
7238 (markdown-forward-block (- arg))
7239 (dotimes (_ arg)
7240 ;; Skip over whitespace in between blocks when moving backward,
7241 ;; unless at a block boundary with no whitespace.
7242 (skip-syntax-backward "-")
7243 (beginning-of-line)
7244 ;; Proceed forward based on the type of block.
7245 (cond
7246 ;; Code blocks
7247 ((and (markdown-code-block-at-pos (point)) ;; this line
7248 (markdown-code-block-at-pos (point-at-bol 0))) ;; previous line
7249 (forward-line -1)
7250 (while (and (markdown-code-block-at-point-p) (not (bobp)))
7251 (forward-line -1))
7252 (forward-line))
7253 ;; Headings
7254 ((markdown-heading-at-point)
7255 (goto-char (match-beginning 0)))
7256 ;; Horizontal rules
7257 ((looking-at markdown-regex-hr))
7258 ;; Blockquotes
7259 ((looking-at markdown-regex-blockquote)
7260 (forward-line -1)
7261 (while (and (looking-at markdown-regex-blockquote)
7262 (not (bobp)))
7263 (forward-line -1))
7264 (forward-line))
7265 ;; List items
7266 ((markdown-cur-list-item-bounds)
7267 (markdown-beginning-of-list))
7268 ;; Other
7270 ;; Move forward in case it is a one line regular paragraph.
7271 (unless (markdown-next-line-blank-p)
7272 (forward-line))
7273 (unless (markdown-prev-line-blank-p)
7274 (markdown-backward-paragraph)))))))
7276 (defun markdown-forward-block (&optional arg)
7277 "Move forward to the next end of a Markdown block.
7278 Moves across complete code blocks, list items, and blockquotes,
7279 but otherwise stops at blank lines, headers, and horizontal
7280 rules. With argument ARG, do it ARG times; a negative argument
7281 ARG = -N means move backward N blocks."
7282 (interactive "^p")
7283 (or arg (setq arg 1))
7284 (if (< arg 0)
7285 (markdown-backward-block (- arg))
7286 (dotimes (_ arg)
7287 ;; Skip over whitespace in between blocks when moving forward.
7288 (if (markdown-cur-line-blank-p)
7289 (skip-syntax-forward "-")
7290 (beginning-of-line))
7291 ;; Proceed forward based on the type of block.
7292 (cond
7293 ;; Code blocks
7294 ((markdown-code-block-at-point-p)
7295 (forward-line)
7296 (while (and (markdown-code-block-at-point-p) (not (eobp)))
7297 (forward-line)))
7298 ;; Headings
7299 ((looking-at markdown-regex-header)
7300 (goto-char (or (match-end 4) (match-end 2) (match-end 3)))
7301 (forward-line))
7302 ;; Horizontal rules
7303 ((looking-at markdown-regex-hr)
7304 (forward-line))
7305 ;; Blockquotes
7306 ((looking-at markdown-regex-blockquote)
7307 (forward-line)
7308 (while (and (looking-at markdown-regex-blockquote) (not (eobp)))
7309 (forward-line)))
7310 ;; List items
7311 ((markdown-cur-list-item-bounds)
7312 (markdown-end-of-list)
7313 (forward-line))
7314 ;; Other
7315 (t (markdown-forward-paragraph))))
7316 (skip-syntax-backward "-")
7317 (unless (eobp)
7318 (forward-char 1))))
7320 (defun markdown-backward-page (&optional count)
7321 "Move backward to boundary of the current toplevel section.
7322 With COUNT, repeat, or go forward if negative."
7323 (interactive "p")
7324 (or count (setq count 1))
7325 (if (< count 0)
7326 (markdown-forward-page (- count))
7327 (skip-syntax-backward "-")
7328 (or (markdown-back-to-heading-over-code-block t t)
7329 (goto-char (point-min)))
7330 (when (looking-at markdown-regex-header)
7331 (let ((level (markdown-outline-level)))
7332 (when (> level 1) (markdown-up-heading level))
7333 (when (> count 1)
7334 (condition-case nil
7335 (markdown-backward-same-level (1- count))
7336 (error (goto-char (point-min)))))))))
7338 (defun markdown-forward-page (&optional count)
7339 "Move forward to boundary of the current toplevel section.
7340 With COUNT, repeat, or go backward if negative."
7341 (interactive "p")
7342 (or count (setq count 1))
7343 (if (< count 0)
7344 (markdown-backward-page (- count))
7345 (if (markdown-back-to-heading-over-code-block t t)
7346 (let ((level (markdown-outline-level)))
7347 (when (> level 1) (markdown-up-heading level))
7348 (condition-case nil
7349 (markdown-forward-same-level count)
7350 (error (goto-char (point-max)))))
7351 (markdown-next-visible-heading 1))))
7353 (defun markdown-next-link ()
7354 "Jump to next inline, reference, or wiki link.
7355 If successful, return point. Otherwise, return nil.
7356 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
7357 (interactive)
7358 (let ((opoint (point)))
7359 (when (or (markdown-link-p) (markdown-wiki-link-p))
7360 ;; At a link already, move past it.
7361 (goto-char (+ (match-end 0) 1)))
7362 ;; Search for the next wiki link and move to the beginning.
7363 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t)
7364 (markdown-code-block-at-point-p)
7365 (< (point) (point-max))))
7366 (if (and (not (eq (point) opoint))
7367 (or (markdown-link-p) (markdown-wiki-link-p)))
7368 ;; Group 1 will move past non-escape character in wiki link regexp.
7369 ;; Go to beginning of group zero for all other link types.
7370 (goto-char (or (match-beginning 1) (match-beginning 0)))
7371 (goto-char opoint)
7372 nil)))
7374 (defun markdown-previous-link ()
7375 "Jump to previous wiki link.
7376 If successful, return point. Otherwise, return nil.
7377 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
7378 (interactive)
7379 (let ((opoint (point)))
7380 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t)
7381 (markdown-code-block-at-point-p)
7382 (> (point) (point-min))))
7383 (if (and (not (eq (point) opoint))
7384 (or (markdown-link-p) (markdown-wiki-link-p)))
7385 (goto-char (or (match-beginning 1) (match-beginning 0)))
7386 (goto-char opoint)
7387 nil)))
7390 ;;; Outline ===================================================================
7392 (defun markdown-move-heading-common (move-fn &optional arg adjust)
7393 "Wrapper for `outline-mode' functions to skip false positives.
7394 MOVE-FN is a function and ARG is its argument. For example,
7395 headings inside preformatted code blocks may match
7396 `outline-regexp' but should not be considered as headings.
7397 When ADJUST is non-nil, adjust the point for interactive calls
7398 to avoid leaving the point at invisible markup. This adjustment
7399 generally should only be done for interactive calls, since other
7400 functions may expect the point to be at the beginning of the
7401 regular expression."
7402 (let ((prev -1) (start (point)))
7403 (if arg (funcall move-fn arg) (funcall move-fn))
7404 (while (and (/= prev (point)) (markdown-code-block-at-point-p))
7405 (setq prev (point))
7406 (if arg (funcall move-fn arg) (funcall move-fn)))
7407 ;; Adjust point for setext headings and invisible text.
7408 (save-match-data
7409 (when (and adjust (thing-at-point-looking-at markdown-regex-header))
7410 (if markdown-hide-markup
7411 ;; Move to beginning of heading text if markup is hidden.
7412 (goto-char (or (match-beginning 1) (match-beginning 5)))
7413 ;; Move to beginning of markup otherwise.
7414 (goto-char (or (match-beginning 1) (match-beginning 4))))))
7415 (if (= (point) start) nil (point))))
7417 (defun markdown-next-visible-heading (arg)
7418 "Move to the next visible heading line of any level.
7419 With argument, repeats or can move backward if negative. ARG is
7420 passed to `outline-next-visible-heading'."
7421 (interactive "p")
7422 (markdown-move-heading-common #'outline-next-visible-heading arg 'adjust))
7424 (defun markdown-previous-visible-heading (arg)
7425 "Move to the previous visible heading line of any level.
7426 With argument, repeats or can move backward if negative. ARG is
7427 passed to `outline-previous-visible-heading'."
7428 (interactive "p")
7429 (markdown-move-heading-common #'outline-previous-visible-heading arg 'adjust))
7431 (defun markdown-next-heading ()
7432 "Move to the next heading line of any level."
7433 (markdown-move-heading-common #'outline-next-heading))
7435 (defun markdown-previous-heading ()
7436 "Move to the previous heading line of any level."
7437 (markdown-move-heading-common #'outline-previous-heading))
7439 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok no-error)
7440 "Move back to the beginning of the previous heading.
7441 Returns t if the point is at a heading, the location if a heading
7442 was found, and nil otherwise.
7443 Only visible heading lines are considered, unless INVISIBLE-OK is
7444 non-nil. Throw an error if there is no previous heading unless
7445 NO-ERROR is non-nil.
7446 Leaves match data intact for `markdown-regex-header'."
7447 (beginning-of-line)
7448 (or (and (markdown-heading-at-point)
7449 (not (markdown-code-block-at-point-p)))
7450 (let (found)
7451 (save-excursion
7452 (while (and (not found)
7453 (re-search-backward markdown-regex-header nil t))
7454 (when (and (or invisible-ok (not (outline-invisible-p)))
7455 (not (markdown-code-block-at-point-p)))
7456 (setq found (point))))
7457 (if (not found)
7458 (unless no-error (user-error "Before first heading"))
7459 (setq found (point))))
7460 (when found (goto-char found)))))
7462 (defun markdown-forward-same-level (arg)
7463 "Move forward to the ARG'th heading at same level as this one.
7464 Stop at the first and last headings of a superior heading."
7465 (interactive "p")
7466 (markdown-back-to-heading-over-code-block)
7467 (markdown-move-heading-common #'outline-forward-same-level arg 'adjust))
7469 (defun markdown-backward-same-level (arg)
7470 "Move backward to the ARG'th heading at same level as this one.
7471 Stop at the first and last headings of a superior heading."
7472 (interactive "p")
7473 (markdown-back-to-heading-over-code-block)
7474 (while (> arg 0)
7475 (let ((point-to-move-to
7476 (save-excursion
7477 (markdown-move-heading-common #'outline-get-last-sibling nil 'adjust))))
7478 (if point-to-move-to
7479 (progn
7480 (goto-char point-to-move-to)
7481 (setq arg (1- arg)))
7482 (user-error "No previous same-level heading")))))
7484 (defun markdown-up-heading (arg)
7485 "Move to the visible heading line of which the present line is a subheading.
7486 With argument, move up ARG levels."
7487 (interactive "p")
7488 (and (called-interactively-p 'any)
7489 (not (eq last-command 'markdown-up-heading)) (push-mark))
7490 (markdown-move-heading-common #'outline-up-heading arg 'adjust))
7492 (defun markdown-back-to-heading (&optional invisible-ok)
7493 "Move to previous heading line, or beg of this line if it's a heading.
7494 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
7495 (markdown-move-heading-common #'outline-back-to-heading invisible-ok))
7497 (defalias 'markdown-end-of-heading 'outline-end-of-heading)
7499 (defun markdown-on-heading-p ()
7500 "Return non-nil if point is on a heading line."
7501 (get-text-property (point-at-bol) 'markdown-heading))
7503 (defun markdown-end-of-subtree (&optional invisible-OK)
7504 "Move to the end of the current subtree.
7505 Only visible heading lines are considered, unless INVISIBLE-OK is
7506 non-nil.
7507 Derived from `org-end-of-subtree'."
7508 (markdown-back-to-heading invisible-OK)
7509 (let ((first t)
7510 (level (markdown-outline-level)))
7511 (while (and (not (eobp))
7512 (or first (> (markdown-outline-level) level)))
7513 (setq first nil)
7514 (markdown-next-heading))
7515 (if (memq (preceding-char) '(?\n ?\^M))
7516 (progn
7517 ;; Go to end of line before heading
7518 (forward-char -1)
7519 (if (memq (preceding-char) '(?\n ?\^M))
7520 ;; leave blank line before heading
7521 (forward-char -1)))))
7522 (point))
7524 (defun markdown-outline-fix-visibility ()
7525 "Hide any false positive headings that should not be shown.
7526 For example, headings inside preformatted code blocks may match
7527 `outline-regexp' but should not be shown as headings when cycling.
7528 Also, the ending --- line in metadata blocks appears to be a
7529 setext header, but should not be folded."
7530 (save-excursion
7531 (goto-char (point-min))
7532 ;; Unhide any false positives in metadata blocks
7533 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin)
7534 (let ((body (progn (forward-line)
7535 (markdown-text-property-at-point
7536 'markdown-yaml-metadata-section))))
7537 (when body
7538 (let ((end (progn (goto-char (cl-second body))
7539 (markdown-text-property-at-point
7540 'markdown-yaml-metadata-end))))
7541 (outline-flag-region (point-min) (1+ (cl-second end)) nil)))))
7542 ;; Hide any false positives in code blocks
7543 (unless (outline-on-heading-p)
7544 (outline-next-visible-heading 1))
7545 (while (< (point) (point-max))
7546 (when (markdown-code-block-at-point-p)
7547 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t))
7548 (outline-next-visible-heading 1))))
7550 (defvar markdown-cycle-global-status 1)
7551 (defvar markdown-cycle-subtree-status nil)
7553 (defun markdown-next-preface ()
7554 (let (finish)
7555 (while (and (not finish) (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
7556 nil 'move))
7557 (unless (markdown-code-block-at-point-p)
7558 (goto-char (match-beginning 0))
7559 (setq finish t))))
7560 (when (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
7561 (forward-char -1)))
7563 (defun markdown-show-entry ()
7564 (save-excursion
7565 (outline-back-to-heading t)
7566 (outline-flag-region (1- (point))
7567 (progn
7568 (markdown-next-preface)
7569 (if (= 1 (- (point-max) (point)))
7570 (point-max)
7571 (point)))
7572 nil)))
7574 ;; This function was originally derived from `org-cycle' from org.el.
7575 (defun markdown-cycle (&optional arg)
7576 "Visibility cycling for Markdown mode.
7577 If ARG is t, perform global visibility cycling. If the point is
7578 at an atx-style header, cycle visibility of the corresponding
7579 subtree. Otherwise, indent the current line or insert a tab,
7580 as appropriate, by calling `indent-for-tab-command'."
7581 (interactive "P")
7582 (cond
7584 ;; Global cycling
7585 ((eq arg t)
7586 (cond
7587 ;; Move from overview to contents
7588 ((and (eq last-command this-command)
7589 (eq markdown-cycle-global-status 2))
7590 (markdown-hide-sublevels 1)
7591 (message "CONTENTS")
7592 (setq markdown-cycle-global-status 3)
7593 (markdown-outline-fix-visibility))
7594 ;; Move from contents to all
7595 ((and (eq last-command this-command)
7596 (eq markdown-cycle-global-status 3))
7597 (markdown-show-all)
7598 (message "SHOW ALL")
7599 (setq markdown-cycle-global-status 1))
7600 ;; Defaults to overview
7602 (markdown-hide-body)
7603 (message "OVERVIEW")
7604 (setq markdown-cycle-global-status 2)
7605 (markdown-outline-fix-visibility))))
7607 ;; At a heading: rotate between three different views
7608 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
7609 (markdown-back-to-heading)
7610 (let ((goal-column 0) eoh eol eos)
7611 ;; Determine boundaries
7612 (save-excursion
7613 (markdown-back-to-heading)
7614 (save-excursion
7615 (beginning-of-line 2)
7616 (while (and (not (eobp)) ;; this is like `next-line'
7617 (get-char-property (1- (point)) 'invisible))
7618 (beginning-of-line 2)) (setq eol (point)))
7619 (markdown-end-of-heading) (setq eoh (point))
7620 (markdown-end-of-subtree t)
7621 (skip-chars-forward " \t\n")
7622 (beginning-of-line 1) ; in case this is an item
7623 (setq eos (1- (point))))
7624 ;; Find out what to do next and set `this-command'
7625 (cond
7626 ;; Nothing is hidden behind this heading
7627 ((= eos eoh)
7628 (message "EMPTY ENTRY")
7629 (setq markdown-cycle-subtree-status nil))
7630 ;; Entire subtree is hidden in one line: open it
7631 ((>= eol eos)
7632 (markdown-show-entry)
7633 (markdown-show-children)
7634 (message "CHILDREN")
7635 (setq markdown-cycle-subtree-status 'children))
7636 ;; We just showed the children, now show everything.
7637 ((and (eq last-command this-command)
7638 (eq markdown-cycle-subtree-status 'children))
7639 (markdown-show-subtree)
7640 (message "SUBTREE")
7641 (setq markdown-cycle-subtree-status 'subtree))
7642 ;; Default action: hide the subtree.
7644 (markdown-hide-subtree)
7645 (message "FOLDED")
7646 (setq markdown-cycle-subtree-status 'folded)))))
7648 ;; In a table, move forward by one cell
7649 ((markdown-table-at-point-p)
7650 (call-interactively #'markdown-table-forward-cell))
7652 ;; Otherwise, indent as appropriate
7654 (indent-for-tab-command))))
7656 (defun markdown-shifttab ()
7657 "Handle S-TAB keybinding based on context.
7658 When in a table, move backward one cell.
7659 Otherwise, cycle global heading visibility by calling
7660 `markdown-cycle' with argument t."
7661 (interactive)
7662 (cond ((markdown-table-at-point-p)
7663 (call-interactively #'markdown-table-backward-cell))
7664 (t (markdown-cycle t))))
7666 (defun markdown-outline-level ()
7667 "Return the depth to which a statement is nested in the outline."
7668 (cond
7669 ((and (match-beginning 0)
7670 (markdown-code-block-at-pos (match-beginning 0)))
7671 7) ;; Only 6 header levels are defined.
7672 ((match-end 2) 1)
7673 ((match-end 3) 2)
7674 ((match-end 4)
7675 (length (markdown-trim-whitespace (match-string-no-properties 4))))))
7677 (defun markdown-promote-subtree (&optional arg)
7678 "Promote the current subtree of ATX headings.
7679 Note that Markdown does not support heading levels higher than
7680 six and therefore level-six headings will not be promoted
7681 further. If ARG is non-nil promote the heading, otherwise
7682 demote."
7683 (interactive "*P")
7684 (save-excursion
7685 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
7686 (re-search-backward markdown-regex-header-atx nil t))
7687 (not (markdown-code-block-at-point-p)))
7688 (let ((level (length (match-string 1)))
7689 (promote-or-demote (if arg 1 -1))
7690 (remove 't))
7691 (markdown-cycle-atx promote-or-demote remove)
7692 (catch 'end-of-subtree
7693 (while (and (markdown-next-heading)
7694 (looking-at markdown-regex-header-atx))
7695 ;; Exit if this not a higher level heading; promote otherwise.
7696 (if (and (looking-at markdown-regex-header-atx)
7697 (<= (length (match-string-no-properties 1)) level))
7698 (throw 'end-of-subtree nil)
7699 (markdown-cycle-atx promote-or-demote remove))))))))
7701 (defun markdown-demote-subtree ()
7702 "Demote the current subtree of ATX headings."
7703 (interactive)
7704 (markdown-promote-subtree t))
7706 (defun markdown-move-subtree-up ()
7707 "Move the current subtree of ATX headings up."
7708 (interactive)
7709 (outline-move-subtree-up 1))
7711 (defun markdown-move-subtree-down ()
7712 "Move the current subtree of ATX headings down."
7713 (interactive)
7714 (outline-move-subtree-down 1))
7716 (defun markdown-outline-next ()
7717 "Move to next list item, when in a list, or next visible heading."
7718 (interactive)
7719 (let ((bounds (markdown-next-list-item-bounds)))
7720 (if bounds
7721 (goto-char (nth 0 bounds))
7722 (markdown-next-visible-heading 1))))
7724 (defun markdown-outline-previous ()
7725 "Move to previous list item, when in a list, or previous visible heading."
7726 (interactive)
7727 (let ((bounds (markdown-prev-list-item-bounds)))
7728 (if bounds
7729 (goto-char (nth 0 bounds))
7730 (markdown-previous-visible-heading 1))))
7732 (defun markdown-outline-next-same-level ()
7733 "Move to next list item or heading of same level."
7734 (interactive)
7735 (let ((bounds (markdown-cur-list-item-bounds)))
7736 (if bounds
7737 (markdown-next-list-item (nth 3 bounds))
7738 (markdown-forward-same-level 1))))
7740 (defun markdown-outline-previous-same-level ()
7741 "Move to previous list item or heading of same level."
7742 (interactive)
7743 (let ((bounds (markdown-cur-list-item-bounds)))
7744 (if bounds
7745 (markdown-prev-list-item (nth 3 bounds))
7746 (markdown-backward-same-level 1))))
7748 (defun markdown-outline-up ()
7749 "Move to previous list item, when in a list, or next heading."
7750 (interactive)
7751 (unless (markdown-up-list)
7752 (markdown-up-heading 1)))
7755 ;;; Marking and Narrowing =====================================================
7757 (defun markdown-mark-paragraph ()
7758 "Put mark at end of this block, point at beginning.
7759 The block marked is the one that contains point or follows point.
7761 Interactively, if this command is repeated or (in Transient Mark
7762 mode) if the mark is active, it marks the next block after the
7763 ones already marked."
7764 (interactive)
7765 (if (or (and (eq last-command this-command) (mark t))
7766 (and transient-mark-mode mark-active))
7767 (set-mark
7768 (save-excursion
7769 (goto-char (mark))
7770 (markdown-forward-paragraph)
7771 (point)))
7772 (let ((beginning-of-defun-function 'markdown-backward-paragraph)
7773 (end-of-defun-function 'markdown-forward-paragraph))
7774 (mark-defun))))
7776 (defun markdown-mark-block ()
7777 "Put mark at end of this block, point at beginning.
7778 The block marked is the one that contains point or follows point.
7780 Interactively, if this command is repeated or (in Transient Mark
7781 mode) if the mark is active, it marks the next block after the
7782 ones already marked."
7783 (interactive)
7784 (if (or (and (eq last-command this-command) (mark t))
7785 (and transient-mark-mode mark-active))
7786 (set-mark
7787 (save-excursion
7788 (goto-char (mark))
7789 (markdown-forward-block)
7790 (point)))
7791 (let ((beginning-of-defun-function 'markdown-backward-block)
7792 (end-of-defun-function 'markdown-forward-block))
7793 (mark-defun))))
7795 (defun markdown-narrow-to-block ()
7796 "Make text outside current block invisible.
7797 The current block is the one that contains point or follows point."
7798 (interactive)
7799 (let ((beginning-of-defun-function 'markdown-backward-block)
7800 (end-of-defun-function 'markdown-forward-block))
7801 (narrow-to-defun)))
7803 (defun markdown-mark-text-block ()
7804 "Put mark at end of this plain text block, point at beginning.
7805 The block marked is the one that contains point or follows point.
7807 Interactively, if this command is repeated or (in Transient Mark
7808 mode) if the mark is active, it marks the next block after the
7809 ones already marked."
7810 (interactive)
7811 (if (or (and (eq last-command this-command) (mark t))
7812 (and transient-mark-mode mark-active))
7813 (set-mark
7814 (save-excursion
7815 (goto-char (mark))
7816 (markdown-end-of-text-block)
7817 (point)))
7818 (let ((beginning-of-defun-function 'markdown-beginning-of-text-block)
7819 (end-of-defun-function 'markdown-end-of-text-block))
7820 (mark-defun))))
7822 (defun markdown-mark-page ()
7823 "Put mark at end of this top level section, point at beginning.
7824 The top level section marked is the one that contains point or
7825 follows point.
7827 Interactively, if this command is repeated or (in Transient Mark
7828 mode) if the mark is active, it marks the next page after the
7829 ones already marked."
7830 (interactive)
7831 (if (or (and (eq last-command this-command) (mark t))
7832 (and transient-mark-mode mark-active))
7833 (set-mark
7834 (save-excursion
7835 (goto-char (mark))
7836 (markdown-forward-page)
7837 (point)))
7838 (let ((beginning-of-defun-function 'markdown-backward-page)
7839 (end-of-defun-function 'markdown-forward-page))
7840 (mark-defun))))
7842 (defun markdown-narrow-to-page ()
7843 "Make text outside current top level section invisible.
7844 The current section is the one that contains point or follows point."
7845 (interactive)
7846 (let ((beginning-of-defun-function 'markdown-backward-page)
7847 (end-of-defun-function 'markdown-forward-page))
7848 (narrow-to-defun)))
7850 (defun markdown-mark-subtree ()
7851 "Mark the current subtree.
7852 This puts point at the start of the current subtree, and mark at the end."
7853 (interactive)
7854 (let ((beg))
7855 (if (markdown-heading-at-point)
7856 (beginning-of-line)
7857 (markdown-previous-visible-heading 1))
7858 (setq beg (point))
7859 (markdown-end-of-subtree)
7860 (push-mark (point) nil t)
7861 (goto-char beg)))
7863 (defun markdown-narrow-to-subtree ()
7864 "Narrow buffer to the current subtree."
7865 (interactive)
7866 (save-excursion
7867 (save-match-data
7868 (narrow-to-region
7869 (progn (markdown-back-to-heading-over-code-block t) (point))
7870 (progn (markdown-end-of-subtree)
7871 (if (and (markdown-heading-at-point) (not (eobp)))
7872 (backward-char 1))
7873 (point))))))
7876 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
7878 (defun markdown-move-up ()
7879 "Move thing at point up.
7880 When in a list item, call `markdown-move-list-item-up'.
7881 When in a table, call `markdown-table-move-row-up'.
7882 Otherwise, move the current heading subtree up with
7883 `markdown-move-subtree-up'."
7884 (interactive)
7885 (cond
7886 ((markdown-list-item-at-point-p)
7887 (call-interactively #'markdown-move-list-item-up))
7888 ((markdown-table-at-point-p)
7889 (call-interactively #'markdown-table-move-row-up))
7891 (call-interactively #'markdown-move-subtree-up))))
7893 (defun markdown-move-down ()
7894 "Move thing at point down.
7895 When in a list item, call `markdown-move-list-item-down'.
7896 Otherwise, move the current heading subtree up with
7897 `markdown-move-subtree-down'."
7898 (interactive)
7899 (cond
7900 ((markdown-list-item-at-point-p)
7901 (call-interactively #'markdown-move-list-item-down))
7902 ((markdown-table-at-point-p)
7903 (call-interactively #'markdown-table-move-row-down))
7905 (call-interactively #'markdown-move-subtree-down))))
7907 (defun markdown-promote ()
7908 "Promote or move element at point to the left.
7909 Depending on the context, this function will promote a heading or
7910 list item at the point, move a table column to the left, or cycle
7911 markup."
7912 (interactive)
7913 (let (bounds)
7914 (cond
7915 ;; Promote atx heading subtree
7916 ((thing-at-point-looking-at markdown-regex-header-atx)
7917 (markdown-promote-subtree))
7918 ;; Promote setext heading
7919 ((thing-at-point-looking-at markdown-regex-header-setext)
7920 (markdown-cycle-setext -1))
7921 ;; Promote horizonal rule
7922 ((thing-at-point-looking-at markdown-regex-hr)
7923 (markdown-cycle-hr -1))
7924 ;; Promote list item
7925 ((setq bounds (markdown-cur-list-item-bounds))
7926 (markdown-promote-list-item bounds))
7927 ;; Move table column to the left
7928 ((markdown-table-at-point-p)
7929 (call-interactively #'markdown-table-move-column-left))
7930 ;; Promote bold
7931 ((thing-at-point-looking-at markdown-regex-bold)
7932 (markdown-cycle-bold))
7933 ;; Promote italic
7934 ((thing-at-point-looking-at markdown-regex-italic)
7935 (markdown-cycle-italic))
7937 (user-error "Nothing to promote at point")))))
7939 (defun markdown-demote ()
7940 "Demote or move element at point to the right.
7941 Depending on the context, this function will demote a heading or
7942 list item at the point, move a table column to the right, or cycle
7943 or remove markup."
7944 (interactive)
7945 (let (bounds)
7946 (cond
7947 ;; Demote atx heading subtree
7948 ((thing-at-point-looking-at markdown-regex-header-atx)
7949 (markdown-demote-subtree))
7950 ;; Demote setext heading
7951 ((thing-at-point-looking-at markdown-regex-header-setext)
7952 (markdown-cycle-setext 1))
7953 ;; Demote horizonal rule
7954 ((thing-at-point-looking-at markdown-regex-hr)
7955 (markdown-cycle-hr 1))
7956 ;; Demote list item
7957 ((setq bounds (markdown-cur-list-item-bounds))
7958 (markdown-demote-list-item bounds))
7959 ;; Move table column to the right
7960 ((markdown-table-at-point-p)
7961 (call-interactively #'markdown-table-move-column-right))
7962 ;; Demote bold
7963 ((thing-at-point-looking-at markdown-regex-bold)
7964 (markdown-cycle-bold))
7965 ;; Demote italic
7966 ((thing-at-point-looking-at markdown-regex-italic)
7967 (markdown-cycle-italic))
7969 (user-error "Nothing to demote at point")))))
7972 ;;; Commands ==================================================================
7974 (defun markdown (&optional output-buffer-name)
7975 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
7976 The output buffer name defaults to `markdown-output-buffer-name'.
7977 Return the name of the output buffer used."
7978 (interactive)
7979 (save-window-excursion
7980 (let ((begin-region)
7981 (end-region))
7982 (if (markdown-use-region-p)
7983 (setq begin-region (region-beginning)
7984 end-region (region-end))
7985 (setq begin-region (point-min)
7986 end-region (point-max)))
7988 (unless output-buffer-name
7989 (setq output-buffer-name markdown-output-buffer-name))
7990 (cond
7991 ;; Handle case when `markdown-command' does not read from stdin
7992 ((and (stringp markdown-command) markdown-command-needs-filename)
7993 (if (not buffer-file-name)
7994 (user-error "Must be visiting a file")
7995 (shell-command (concat markdown-command " "
7996 (shell-quote-argument buffer-file-name))
7997 output-buffer-name)))
7998 ;; Pass region to `markdown-command' via stdin
8000 (let ((buf (get-buffer-create output-buffer-name)))
8001 (with-current-buffer buf
8002 (setq buffer-read-only nil)
8003 (erase-buffer))
8004 (if (stringp markdown-command)
8005 (call-process-region begin-region end-region
8006 shell-file-name nil buf nil
8007 shell-command-switch markdown-command)
8008 (funcall markdown-command begin-region end-region buf))))))
8009 output-buffer-name))
8011 (defun markdown-standalone (&optional output-buffer-name)
8012 "Special function to provide standalone HTML output.
8013 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
8014 (interactive)
8015 (setq output-buffer-name (markdown output-buffer-name))
8016 (with-current-buffer output-buffer-name
8017 (set-buffer output-buffer-name)
8018 (unless (markdown-output-standalone-p)
8019 (markdown-add-xhtml-header-and-footer output-buffer-name))
8020 (goto-char (point-min))
8021 (html-mode))
8022 output-buffer-name)
8024 (defun markdown-other-window (&optional output-buffer-name)
8025 "Run `markdown-command' on current buffer and display in other window.
8026 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
8027 that name."
8028 (interactive)
8029 (markdown-display-buffer-other-window
8030 (markdown-standalone output-buffer-name)))
8032 (defun markdown-output-standalone-p ()
8033 "Determine whether `markdown-command' output is standalone XHTML.
8034 Standalone XHTML output is identified by an occurrence of
8035 `markdown-xhtml-standalone-regexp' in the first five lines of output."
8036 (save-excursion
8037 (goto-char (point-min))
8038 (save-match-data
8039 (re-search-forward
8040 markdown-xhtml-standalone-regexp
8041 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
8042 t))))
8044 (defun markdown-stylesheet-link-string (stylesheet-path)
8045 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
8046 stylesheet-path
8047 "\" />"))
8049 (defun markdown-add-xhtml-header-and-footer (title)
8050 "Wrap XHTML header and footer with given TITLE around current buffer."
8051 (goto-char (point-min))
8052 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
8053 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
8054 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
8055 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
8056 "<head>\n<title>")
8057 (insert title)
8058 (insert "</title>\n")
8059 (when (> (length markdown-content-type) 0)
8060 (insert
8061 (format
8062 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
8063 markdown-content-type
8064 (or (and markdown-coding-system
8065 (fboundp 'coding-system-get)
8066 (coding-system-get markdown-coding-system
8067 'mime-charset))
8068 (and (fboundp 'coding-system-get)
8069 (coding-system-get buffer-file-coding-system
8070 'mime-charset))
8071 "iso-8859-1"))))
8072 (if (> (length markdown-css-paths) 0)
8073 (insert (mapconcat #'markdown-stylesheet-link-string
8074 markdown-css-paths "\n")))
8075 (when (> (length markdown-xhtml-header-content) 0)
8076 (insert markdown-xhtml-header-content))
8077 (insert "\n</head>\n\n"
8078 "<body>\n\n")
8079 (goto-char (point-max))
8080 (insert "\n"
8081 "</body>\n"
8082 "</html>\n"))
8084 (defun markdown-preview (&optional output-buffer-name)
8085 "Run `markdown-command' on the current buffer and view output in browser.
8086 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
8087 that name."
8088 (interactive)
8089 (browse-url-of-buffer
8090 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
8092 (defun markdown-export-file-name (&optional extension)
8093 "Attempt to generate a filename for Markdown output.
8094 The file extension will be EXTENSION if given, or .html by default.
8095 If the current buffer is visiting a file, we construct a new
8096 output filename based on that filename. Otherwise, return nil."
8097 (when (buffer-file-name)
8098 (unless extension
8099 (setq extension ".html"))
8100 (let ((candidate
8101 (concat
8102 (cond
8103 ((buffer-file-name)
8104 (file-name-sans-extension (buffer-file-name)))
8105 (t (buffer-name)))
8106 extension)))
8107 (cond
8108 ((equal candidate (buffer-file-name))
8109 (concat candidate extension))
8111 candidate)))))
8113 (defun markdown-export (&optional output-file)
8114 "Run Markdown on the current buffer, save to file, and return the filename.
8115 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
8116 generated by `markdown-export-file-name', which will be constructed using the
8117 current filename, but with the extension removed and replaced with .html."
8118 (interactive)
8119 (unless output-file
8120 (setq output-file (markdown-export-file-name ".html")))
8121 (when output-file
8122 (let* ((init-buf (current-buffer))
8123 (init-point (point))
8124 (init-buf-string (buffer-string))
8125 (output-buffer (find-file-noselect output-file))
8126 (output-buffer-name (buffer-name output-buffer)))
8127 (run-hooks 'markdown-before-export-hook)
8128 (markdown-standalone output-buffer-name)
8129 (with-current-buffer output-buffer
8130 (run-hooks 'markdown-after-export-hook)
8131 (save-buffer)
8132 (when markdown-export-kill-buffer (kill-buffer)))
8133 ;; if modified, restore initial buffer
8134 (when (buffer-modified-p init-buf)
8135 (erase-buffer)
8136 (insert init-buf-string)
8137 (save-buffer)
8138 (goto-char init-point))
8139 output-file)))
8141 (defun markdown-export-and-preview ()
8142 "Export to XHTML using `markdown-export' and browse the resulting file."
8143 (interactive)
8144 (browse-url-of-file (markdown-export)))
8146 (defvar markdown-live-preview-buffer nil
8147 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
8148 (make-variable-buffer-local 'markdown-live-preview-buffer)
8150 (defvar markdown-live-preview-source-buffer nil
8151 "Source buffer from which current buffer was generated.
8152 This is the inverse of `markdown-live-preview-buffer'.")
8153 (make-variable-buffer-local 'markdown-live-preview-source-buffer)
8155 (defvar markdown-live-preview-currently-exporting nil)
8157 (defun markdown-live-preview-get-filename ()
8158 "Standardize the filename exported by `markdown-live-preview-export'."
8159 (markdown-export-file-name ".html"))
8161 (defun markdown-live-preview-window-eww (file)
8162 "Preview FILE with eww.
8163 To be used with `markdown-live-preview-window-function'."
8164 (if (require 'eww nil t)
8165 (progn
8166 (eww-open-file file)
8167 (get-buffer "*eww*"))
8168 (error "EWW is not present or not loaded on this version of Emacs")))
8170 (defun markdown-visual-lines-between-points (beg end)
8171 (save-excursion
8172 (goto-char beg)
8173 (cl-loop with count = 0
8174 while (progn (end-of-visual-line)
8175 (and (< (point) end) (line-move-visual 1 t)))
8176 do (cl-incf count)
8177 finally return count)))
8179 (defun markdown-live-preview-window-serialize (buf)
8180 "Get window point and scroll data for all windows displaying BUF."
8181 (when (buffer-live-p buf)
8182 (with-current-buffer buf
8183 (mapcar
8184 (lambda (win)
8185 (with-selected-window win
8186 (let* ((start (window-start))
8187 (pt (window-point))
8188 (pt-or-sym (cond ((= pt (point-min)) 'min)
8189 ((= pt (point-max)) 'max)
8190 (t pt)))
8191 (diff (markdown-visual-lines-between-points
8192 start pt)))
8193 (list win pt-or-sym diff))))
8194 (get-buffer-window-list buf)))))
8196 (defun markdown-get-point-back-lines (pt num-lines)
8197 (save-excursion
8198 (goto-char pt)
8199 (line-move-visual (- num-lines) t)
8200 ;; in testing, can occasionally overshoot the number of lines to traverse
8201 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
8202 (when (> actual-num-lines num-lines)
8203 (line-move-visual (- actual-num-lines num-lines) t)))
8204 (point)))
8206 (defun markdown-live-preview-window-deserialize (window-posns)
8207 "Apply window point and scroll data from WINDOW-POSNS.
8208 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
8209 (cl-destructuring-bind (win pt-or-sym diff) window-posns
8210 (when (window-live-p win)
8211 (with-current-buffer markdown-live-preview-buffer
8212 (set-window-buffer win (current-buffer))
8213 (cl-destructuring-bind (actual-pt actual-diff)
8214 (cl-case pt-or-sym
8215 (min (list (point-min) 0))
8216 (max (list (point-max) diff))
8217 (t (list pt-or-sym diff)))
8218 (set-window-start
8219 win (markdown-get-point-back-lines actual-pt actual-diff))
8220 (set-window-point win actual-pt))))))
8222 (defun markdown-live-preview-export ()
8223 "Export to XHTML using `markdown-export'.
8224 Browse the resulting file within Emacs using
8225 `markdown-live-preview-window-function' Return the buffer
8226 displaying the rendered output."
8227 (interactive)
8228 (let ((filename (markdown-live-preview-get-filename)))
8229 (when filename
8230 (let* ((markdown-live-preview-currently-exporting t)
8231 (cur-buf (current-buffer))
8232 (export-file (markdown-export filename))
8233 ;; get positions in all windows currently displaying output buffer
8234 (window-data
8235 (markdown-live-preview-window-serialize
8236 markdown-live-preview-buffer)))
8237 (save-window-excursion
8238 (let ((output-buffer
8239 (funcall markdown-live-preview-window-function export-file)))
8240 (with-current-buffer output-buffer
8241 (setq markdown-live-preview-source-buffer cur-buf)
8242 (add-hook 'kill-buffer-hook
8243 #'markdown-live-preview-remove-on-kill t t))
8244 (with-current-buffer cur-buf
8245 (setq markdown-live-preview-buffer output-buffer))))
8246 (with-current-buffer cur-buf
8247 ;; reset all windows displaying output buffer to where they were,
8248 ;; now with the new output
8249 (mapc #'markdown-live-preview-window-deserialize window-data)
8250 ;; delete html editing buffer
8251 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
8252 (when (and export-file (file-exists-p export-file)
8253 (eq markdown-live-preview-delete-export
8254 'delete-on-export))
8255 (delete-file export-file))
8256 markdown-live-preview-buffer)))))
8258 (defun markdown-live-preview-remove ()
8259 (when (buffer-live-p markdown-live-preview-buffer)
8260 (kill-buffer markdown-live-preview-buffer))
8261 (setq markdown-live-preview-buffer nil)
8262 ;; if set to 'delete-on-export, the output has already been deleted
8263 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
8264 (let ((outfile-name (markdown-live-preview-get-filename)))
8265 (when (and outfile-name (file-exists-p outfile-name))
8266 (delete-file outfile-name)))))
8268 (defun markdown-get-other-window ()
8269 "Find another window to display preview or output content."
8270 (cond
8271 ((memq markdown-split-window-direction '(vertical below))
8272 (or (window-in-direction 'below) (split-window-vertically)))
8273 ((memq markdown-split-window-direction '(horizontal right))
8274 (or (window-in-direction 'right) (split-window-horizontally)))
8275 (t (split-window-sensibly (get-buffer-window)))))
8277 (defun markdown-display-buffer-other-window (buf)
8278 "Display preview or output buffer BUF in another window."
8279 (let ((cur-buf (current-buffer))
8280 (window (markdown-get-other-window)))
8281 (set-window-buffer window buf)
8282 (set-buffer cur-buf)))
8284 (defun markdown-live-preview-if-markdown ()
8285 (when (and (derived-mode-p 'markdown-mode)
8286 markdown-live-preview-mode)
8287 (unless markdown-live-preview-currently-exporting
8288 (if (buffer-live-p markdown-live-preview-buffer)
8289 (markdown-live-preview-export)
8290 (markdown-display-buffer-other-window
8291 (markdown-live-preview-export))))))
8293 (defun markdown-live-preview-remove-on-kill ()
8294 (cond ((and (derived-mode-p 'markdown-mode)
8295 markdown-live-preview-mode)
8296 (markdown-live-preview-remove))
8297 (markdown-live-preview-source-buffer
8298 (with-current-buffer markdown-live-preview-source-buffer
8299 (setq markdown-live-preview-buffer nil))
8300 (setq markdown-live-preview-source-buffer nil))))
8302 (defun markdown-live-preview-switch-to-output ()
8303 "Switch to output buffer."
8304 (interactive)
8305 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
8306 output buffer in another window."
8307 (if markdown-live-preview-mode
8308 (markdown-display-buffer-other-window (markdown-live-preview-export)))
8309 (markdown-live-preview-mode))
8311 (defun markdown-live-preview-re-export ()
8312 "Re export source buffer."
8313 (interactive)
8314 "If the current buffer is a buffer displaying the exported version of a
8315 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
8316 update this buffer's contents."
8317 (when markdown-live-preview-source-buffer
8318 (with-current-buffer markdown-live-preview-source-buffer
8319 (markdown-live-preview-export))))
8321 (defun markdown-open ()
8322 "Open file for the current buffer with `markdown-open-command'."
8323 (interactive)
8324 (unless markdown-open-command
8325 (user-error "Variable `markdown-open-command' must be set"))
8326 (if (stringp markdown-open-command)
8327 (if (not buffer-file-name)
8328 (user-error "Must be visiting a file")
8329 (save-buffer)
8330 (call-process markdown-open-command nil 0 nil buffer-file-name))
8331 (funcall markdown-open-command))
8332 nil)
8334 (defun markdown-kill-ring-save ()
8335 "Run Markdown on file and store output in the kill ring."
8336 (interactive)
8337 (save-window-excursion
8338 (markdown)
8339 (with-current-buffer markdown-output-buffer-name
8340 (kill-ring-save (point-min) (point-max)))))
8343 ;;; Links =====================================================================
8345 (defun markdown-link-p ()
8346 "Return non-nil when `point' is at a non-wiki link.
8347 See `markdown-wiki-link-p' for more information."
8348 (let ((case-fold-search nil))
8349 (and (not (markdown-wiki-link-p))
8350 (not (markdown-code-block-at-point-p))
8351 (or (thing-at-point-looking-at markdown-regex-link-inline)
8352 (thing-at-point-looking-at markdown-regex-link-reference)
8353 (thing-at-point-looking-at markdown-regex-uri)
8354 (thing-at-point-looking-at markdown-regex-angle-uri)))))
8356 (make-obsolete 'markdown-link-link 'markdown-link-url "v2.3")
8358 (defun markdown-link-at-pos (pos)
8359 "Return properties of link or image at position POS.
8360 Value is a list of elements describing the link:
8361 0. beginning position
8362 1. end position
8363 2. link text
8364 3. URL
8365 4. reference label
8366 5. title text
8367 6. bang (nil or \"!\")"
8368 (save-excursion
8369 (goto-char pos)
8370 (let (begin end text url reference title bang)
8371 (cond
8372 ;; Inline or reference image or link at point.
8373 ((or (thing-at-point-looking-at markdown-regex-link-inline)
8374 (thing-at-point-looking-at markdown-regex-link-reference))
8375 (setq bang (match-string-no-properties 1)
8376 begin (match-beginning 0)
8377 end (match-end 0)
8378 text (match-string-no-properties 3))
8379 (if (char-equal (char-after (match-beginning 5)) ?\[)
8380 ;; Reference link
8381 (setq reference (match-string-no-properties 6))
8382 ;; Inline link
8383 (setq url (match-string-no-properties 6))
8384 (when (match-end 7)
8385 (setq title (substring (match-string-no-properties 7) 1 -1)))))
8386 ;; Angle bracket URI at point.
8387 ((thing-at-point-looking-at markdown-regex-angle-uri)
8388 (setq begin (match-beginning 0)
8389 end (match-end 0)
8390 url (match-string-no-properties 2)))
8391 ;; Plain URI at point.
8392 ((thing-at-point-looking-at markdown-regex-uri)
8393 (setq begin (match-beginning 0)
8394 end (match-end 0)
8395 url (match-string-no-properties 1))))
8396 (list begin end text url reference title bang))))
8398 (defun markdown-link-url ()
8399 "Return the URL part of the regular (non-wiki) link at point.
8400 Works with both inline and reference style links, and with images.
8401 If point is not at a link or the link reference is not defined
8402 returns nil."
8403 (let* ((values (markdown-link-at-pos (point)))
8404 (text (nth 2 values))
8405 (url (nth 3 values))
8406 (ref (nth 4 values)))
8407 (or url (and ref (car (markdown-reference-definition
8408 (downcase (if (string= ref "") text ref))))))))
8410 (defun markdown-follow-link-at-point ()
8411 "Open the current non-wiki link.
8412 If the link is a complete URL, open in browser with `browse-url'.
8413 Otherwise, open with `find-file' after stripping anchor and/or query string.
8414 Translate filenames using `markdown-filename-translate-function'."
8415 (interactive)
8416 (if (markdown-link-p)
8417 (let* ((url (markdown-link-url))
8418 (struct (url-generic-parse-url url))
8419 (full (url-fullness struct))
8420 (file url))
8421 ;; Parse URL, determine fullness, strip query string
8422 (if (fboundp 'url-path-and-query)
8423 (setq file (car (url-path-and-query struct)))
8424 (when (and (setq file (url-filename struct))
8425 (string-match "\\?" file))
8426 (setq file (substring file 0 (match-beginning 0)))))
8427 ;; Open full URLs in browser, files in Emacs
8428 (if full
8429 (browse-url url)
8430 (when (and file (> (length file) 0))
8431 (find-file (funcall markdown-translate-filename-function file)))))
8432 (user-error "Point is not at a Markdown link or URL")))
8434 (defun markdown-fontify-inline-links (last)
8435 "Add text properties to next inline link from point to LAST."
8436 (when (markdown-match-generic-links last nil)
8437 (let* ((link-start (match-beginning 3))
8438 (link-end (match-end 3))
8439 (url-start (match-beginning 6))
8440 (url-end (match-end 6))
8441 (url (match-string-no-properties 6))
8442 (title-start (match-beginning 7))
8443 (title-end (match-end 7))
8444 (title (match-string-no-properties 7))
8445 ;; Markup part
8446 (mp (list 'face 'markdown-markup-face
8447 'invisible 'markdown-markup
8448 'rear-nonsticky t
8449 'font-lock-multiline t))
8450 ;; Link part
8451 (lp (list 'keymap markdown-mode-mouse-map
8452 'face markdown-link-face
8453 'mouse-face 'markdown-highlight-face
8454 'font-lock-multiline t
8455 'help-echo (if title (concat title "\n" url) url)))
8456 ;; URL part
8457 (up (list 'keymap markdown-mode-mouse-map
8458 'face 'markdown-url-face
8459 'invisible 'markdown-markup
8460 'mouse-face 'markdown-highlight-face
8461 'font-lock-multiline t))
8462 ;; URL composition character
8463 (url-char (markdown--first-displayable markdown-url-compose-char))
8464 ;; Title part
8465 (tp (list 'face 'markdown-link-title-face
8466 'invisible 'markdown-markup
8467 'font-lock-multiline t)))
8468 (dolist (g '(1 2 4 5 8))
8469 (when (match-end g)
8470 (add-text-properties (match-beginning g) (match-end g) mp)))
8471 (when link-start (add-text-properties link-start link-end lp))
8472 (when url-start (add-text-properties url-start url-end up))
8473 (when title-start (add-text-properties url-end title-end tp))
8474 (when (and markdown-hide-urls url-start)
8475 (compose-region url-start (or title-end url-end) url-char))
8476 t)))
8478 (defun markdown-fontify-reference-links (last)
8479 "Add text properties to next reference link from point to LAST."
8480 (when (markdown-match-generic-links last t)
8481 (let* ((link-start (match-beginning 3))
8482 (link-end (match-end 3))
8483 (ref-start (match-beginning 6))
8484 (ref-end (match-end 6))
8485 ;; Markup part
8486 (mp (list 'face 'markdown-markup-face
8487 'invisible 'markdown-markup
8488 'rear-nonsticky t
8489 'font-lock-multiline t))
8490 ;; Link part
8491 (lp (list 'keymap markdown-mode-mouse-map
8492 'face markdown-link-face
8493 'mouse-face 'markdown-highlight-face
8494 'font-lock-multiline t
8495 'help-echo (lambda (_ __ pos)
8496 (save-match-data
8497 (save-excursion
8498 (goto-char pos)
8499 (or (markdown-link-url)
8500 "Undefined reference"))))))
8501 ;; URL composition character
8502 (url-char (markdown--first-displayable markdown-url-compose-char))
8503 ;; Reference part
8504 (rp (list 'face 'markdown-reference-face
8505 'invisible 'markdown-markup
8506 'font-lock-multiline t)))
8507 (dolist (g '(1 2 4 5 8))
8508 (when (match-end g)
8509 (add-text-properties (match-beginning g) (match-end g) mp)))
8510 (when link-start (add-text-properties link-start link-end lp))
8511 (when ref-start (add-text-properties ref-start ref-end rp)
8512 (when (and markdown-hide-urls (> (- ref-end ref-start) 2))
8513 (compose-region ref-start ref-end url-char)))
8514 t)))
8516 (defun markdown-fontify-angle-uris (last)
8517 "Add text properties to angle URIs from point to LAST."
8518 (when (markdown-match-angle-uris last)
8519 (let* ((url-start (match-beginning 2))
8520 (url-end (match-end 2))
8521 ;; Markup part
8522 (mp (list 'face 'markdown-markup-face
8523 'invisible 'markdown-markup
8524 'rear-nonsticky t
8525 'font-lock-multiline t))
8526 ;; URI part
8527 (up (list 'keymap markdown-mode-mouse-map
8528 'face 'markdown-plain-url-face
8529 'mouse-face 'markdown-highlight-face
8530 'font-lock-multiline t)))
8531 (dolist (g '(1 3))
8532 (add-text-properties (match-beginning g) (match-end g) mp))
8533 (add-text-properties url-start url-end up)
8534 t)))
8536 (defun markdown-fontify-plain-uris (last)
8537 "Add text properties to plain URLs from point to LAST."
8538 (when (markdown-match-plain-uris last)
8539 (let* ((start (match-beginning 0))
8540 (end (match-end 0))
8541 (props (list 'keymap markdown-mode-mouse-map
8542 'face 'markdown-plain-url-face
8543 'mouse-face 'markdown-highlight-face
8544 'rear-nonsticky t
8545 'font-lock-multiline t)))
8546 (add-text-properties start end props)
8547 t)))
8549 (defun markdown-toggle-url-hiding (&optional arg)
8550 "Toggle the display or hiding of URLs.
8551 With a prefix argument ARG, enable URL hiding if ARG is positive,
8552 and disable it otherwise."
8553 (interactive (list (or current-prefix-arg 'toggle)))
8554 (setq markdown-hide-urls
8555 (if (eq arg 'toggle)
8556 (not markdown-hide-urls)
8557 (> (prefix-numeric-value arg) 0)))
8558 (if markdown-hide-urls
8559 (message "markdown-mode URL hiding enabled")
8560 (message "markdown-mode URL hiding disabled"))
8561 (markdown-reload-extensions))
8564 ;;; WikiLink Following/Markup =================================================
8566 (defun markdown-wiki-link-p ()
8567 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
8568 A true wiki link name matches `markdown-regex-wiki-link' but does
8569 not match the current file name after conversion. This modifies
8570 the data returned by `match-data'. Note that the potential wiki
8571 link name must be available via `match-string'."
8572 (when markdown-enable-wiki-links
8573 (let ((case-fold-search nil))
8574 (and (thing-at-point-looking-at markdown-regex-wiki-link)
8575 (not (markdown-code-block-at-point-p))
8576 (or (not buffer-file-name)
8577 (not (string-equal (buffer-file-name)
8578 (markdown-convert-wiki-link-to-filename
8579 (markdown-wiki-link-link)))))))))
8581 (defun markdown-wiki-link-link ()
8582 "Return the link part of the wiki link using current match data.
8583 The location of the link component depends on the value of
8584 `markdown-wiki-link-alias-first'."
8585 (if markdown-wiki-link-alias-first
8586 (or (match-string-no-properties 5) (match-string-no-properties 3))
8587 (match-string-no-properties 3)))
8589 (defun markdown-wiki-link-alias ()
8590 "Return the alias or text part of the wiki link using current match data.
8591 The location of the alias component depends on the value of
8592 `markdown-wiki-link-alias-first'."
8593 (if markdown-wiki-link-alias-first
8594 (match-string-no-properties 3)
8595 (or (match-string-no-properties 5) (match-string-no-properties 3))))
8597 (defun markdown-convert-wiki-link-to-filename (name)
8598 "Generate a filename from the wiki link NAME.
8599 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
8600 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
8601 and [[test test]] both map to Test-test.ext. Look in the current
8602 directory first, then in subdirectories if
8603 `markdown-wiki-link-search-subdirectories' is non-nil, and then
8604 in parent directories if
8605 `markdown-wiki-link-search-parent-directories' is non-nil."
8606 (let* ((basename (markdown-replace-regexp-in-string
8607 "[[:space:]\n]" markdown-link-space-sub-char name))
8608 (basename (if (eq major-mode 'gfm-mode)
8609 (concat (upcase (substring basename 0 1))
8610 (downcase (substring basename 1 nil)))
8611 basename))
8612 directory extension default candidates dir)
8613 (when buffer-file-name
8614 (setq directory (file-name-directory buffer-file-name)
8615 extension (file-name-extension buffer-file-name)))
8616 (setq default (concat basename
8617 (when extension (concat "." extension))))
8618 (cond
8619 ;; Look in current directory first.
8620 ((or (null buffer-file-name)
8621 (file-exists-p default))
8622 default)
8623 ;; Possibly search in subdirectories, next.
8624 ((and markdown-wiki-link-search-subdirectories
8625 (setq candidates
8626 (markdown-directory-files-recursively
8627 directory (concat "^" default "$"))))
8628 (car candidates))
8629 ;; Possibly search in parent directories as a last resort.
8630 ((and markdown-wiki-link-search-parent-directories
8631 (setq dir (locate-dominating-file directory default)))
8632 (concat dir default))
8633 ;; If nothing is found, return default in current directory.
8634 (t default))))
8636 (defun markdown-follow-wiki-link (name &optional other)
8637 "Follow the wiki link NAME.
8638 Convert the name to a file name and call `find-file'. Ensure that
8639 the new buffer remains in `markdown-mode'. Open the link in another
8640 window when OTHER is non-nil."
8641 (let ((filename (markdown-convert-wiki-link-to-filename name))
8642 (wp (when buffer-file-name
8643 (file-name-directory buffer-file-name))))
8644 (if (not wp)
8645 (user-error "Must be visiting a file")
8646 (when other (other-window 1))
8647 (let ((default-directory wp))
8648 (find-file filename)))
8649 (when (not (eq major-mode 'markdown-mode))
8650 (markdown-mode))))
8652 (defun markdown-follow-wiki-link-at-point (&optional arg)
8653 "Find Wiki Link at point.
8654 With prefix argument ARG, open the file in other window.
8655 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
8656 (interactive "P")
8657 (if (markdown-wiki-link-p)
8658 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
8659 (user-error "Point is not at a Wiki Link")))
8661 (defun markdown-highlight-wiki-link (from to face)
8662 "Highlight the wiki link in the region between FROM and TO using FACE."
8663 (put-text-property from to 'font-lock-face face))
8665 (defun markdown-unfontify-region-wiki-links (from to)
8666 "Remove wiki link faces from the region specified by FROM and TO."
8667 (interactive "*r")
8668 (let ((modified (buffer-modified-p)))
8669 (remove-text-properties from to '(font-lock-face markdown-link-face))
8670 (remove-text-properties from to '(font-lock-face markdown-missing-link-face))
8671 ;; remove-text-properties marks the buffer modified in emacs 24.3,
8672 ;; undo that if it wasn't originally marked modified
8673 (set-buffer-modified-p modified)))
8675 (defun markdown-fontify-region-wiki-links (from to)
8676 "Search region given by FROM and TO for wiki links and fontify them.
8677 If a wiki link is found check to see if the backing file exists
8678 and highlight accordingly."
8679 (goto-char from)
8680 (save-match-data
8681 (while (re-search-forward markdown-regex-wiki-link to t)
8682 (when (not (markdown-code-block-at-point-p))
8683 (let ((highlight-beginning (match-beginning 1))
8684 (highlight-end (match-end 1))
8685 (file-name
8686 (markdown-convert-wiki-link-to-filename
8687 (markdown-wiki-link-link))))
8688 (if (condition-case nil (file-exists-p file-name) (error nil))
8689 (markdown-highlight-wiki-link
8690 highlight-beginning highlight-end markdown-link-face)
8691 (markdown-highlight-wiki-link
8692 highlight-beginning highlight-end markdown-missing-link-face)))))))
8694 (defun markdown-extend-changed-region (from to)
8695 "Extend region given by FROM and TO so that we can fontify all links.
8696 The region is extended to the first newline before and the first
8697 newline after."
8698 ;; start looking for the first new line before 'from
8699 (goto-char from)
8700 (re-search-backward "\n" nil t)
8701 (let ((new-from (point-min))
8702 (new-to (point-max)))
8703 (if (not (= (point) from))
8704 (setq new-from (point)))
8705 ;; do the same thing for the first new line after 'to
8706 (goto-char to)
8707 (re-search-forward "\n" nil t)
8708 (if (not (= (point) to))
8709 (setq new-to (point)))
8710 (cl-values new-from new-to)))
8712 (defun markdown-check-change-for-wiki-link (from to)
8713 "Check region between FROM and TO for wiki links and re-fontify as needed."
8714 (interactive "*r")
8715 (let* ((modified (buffer-modified-p))
8716 (buffer-undo-list t)
8717 (inhibit-read-only t)
8718 (inhibit-point-motion-hooks t)
8719 deactivate-mark
8720 buffer-file-truename)
8721 (unwind-protect
8722 (save-excursion
8723 (save-match-data
8724 (save-restriction
8725 ;; Extend the region to fontify so that it starts
8726 ;; and ends at safe places.
8727 (cl-multiple-value-bind (new-from new-to)
8728 (markdown-extend-changed-region from to)
8729 (goto-char new-from)
8730 ;; Only refontify when the range contains text with a
8731 ;; wiki link face or if the wiki link regexp matches.
8732 (when (or (markdown-range-property-any
8733 new-from new-to 'font-lock-face
8734 (list markdown-link-face
8735 markdown-missing-link-face))
8736 (re-search-forward
8737 markdown-regex-wiki-link new-to t))
8738 ;; Unfontify existing fontification (start from scratch)
8739 (markdown-unfontify-region-wiki-links new-from new-to)
8740 ;; Now do the fontification.
8741 (markdown-fontify-region-wiki-links new-from new-to))))))
8742 (and (not modified)
8743 (buffer-modified-p)
8744 (set-buffer-modified-p nil)))))
8746 (defun markdown-check-change-for-wiki-link-after-change (from to _)
8747 "Check region between FROM and TO for wiki links and re-fontify as needed.
8748 Designed to be used with the `after-change-functions' hook."
8749 (markdown-check-change-for-wiki-link from to))
8751 (defun markdown-fontify-buffer-wiki-links ()
8752 "Refontify all wiki links in the buffer."
8753 (interactive)
8754 (markdown-check-change-for-wiki-link (point-min) (point-max)))
8757 ;;; Following & Doing =========================================================
8759 (defun markdown-follow-thing-at-point (arg)
8760 "Follow thing at point if possible, such as a reference link or wiki link.
8761 Opens inline and reference links in a browser. Opens wiki links
8762 to other files in the current window, or the another window if
8763 ARG is non-nil.
8764 See `markdown-follow-link-at-point' and
8765 `markdown-follow-wiki-link-at-point'."
8766 (interactive "P")
8767 (cond ((markdown-link-p)
8768 (markdown-follow-link-at-point))
8769 ((markdown-wiki-link-p)
8770 (markdown-follow-wiki-link-at-point arg))
8772 (user-error "Nothing to follow at point"))))
8774 (make-obsolete 'markdown-jump 'markdown-do "v2.3")
8776 (defun markdown-do ()
8777 "Do something sensible based on context at point.
8778 Jumps between reference links and definitions; between footnote
8779 markers and footnote text."
8780 (interactive)
8781 (cond
8782 ;; Footnote definition
8783 ((markdown-footnote-text-positions)
8784 (markdown-footnote-return))
8785 ;; Footnote marker
8786 ((markdown-footnote-marker-positions)
8787 (markdown-footnote-goto-text))
8788 ;; Reference link
8789 ((thing-at-point-looking-at markdown-regex-link-reference)
8790 (markdown-reference-goto-definition))
8791 ;; Reference definition
8792 ((thing-at-point-looking-at markdown-regex-reference-definition)
8793 (markdown-reference-goto-link (match-string-no-properties 2)))
8794 ;; GFM task list item
8795 ((markdown-gfm-task-list-item-at-point)
8796 (markdown-toggle-gfm-checkbox))
8797 ;; Align table
8798 ((markdown-table-at-point-p)
8799 (call-interactively #'markdown-table-align))
8800 ;; Otherwise
8802 (markdown-insert-gfm-checkbox))))
8805 ;;; Miscellaneous =============================================================
8807 (defun markdown-compress-whitespace-string (str)
8808 "Compress whitespace in STR and return result.
8809 Leading and trailing whitespace is removed. Sequences of multiple
8810 spaces, tabs, and newlines are replaced with single spaces."
8811 (markdown-replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
8812 (markdown-replace-regexp-in-string "[ \t\n]+" " " str)))
8814 (defun markdown--substitute-command-keys (string)
8815 "Like `substitute-command-keys' but, but prefers control characters.
8816 First pass STRING to `substitute-command-keys' and then
8817 substitute `C-i` for `TAB` and `C-m` for `RET`."
8818 (replace-regexp-in-string
8819 "\\<TAB\\>" "C-i"
8820 (replace-regexp-in-string
8821 "\\<RET\\>" "C-m" (substitute-command-keys string) t) t))
8823 (defun markdown-line-number-at-pos (&optional pos)
8824 "Return (narrowed) buffer line number at position POS.
8825 If POS is nil, use current buffer location.
8826 This is an exact copy of `line-number-at-pos' for use in emacs21."
8827 (let ((opoint (or pos (point))) start)
8828 (save-excursion
8829 (goto-char (point-min))
8830 (setq start (point))
8831 (goto-char opoint)
8832 (forward-line 0)
8833 (1+ (count-lines start (point))))))
8835 (defun markdown-inside-link-p ()
8836 "Return t if point is within a link."
8837 (save-match-data
8838 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
8840 (defun markdown-line-is-reference-definition-p ()
8841 "Return whether the current line is a (non-footnote) reference defition."
8842 (save-excursion
8843 (move-beginning-of-line 1)
8844 (and (looking-at-p markdown-regex-reference-definition)
8845 (not (looking-at-p "[ \t]*\\[^")))))
8847 (defun markdown-adaptive-fill-function ()
8848 "Return prefix for filling paragraph or nil if not determined."
8849 (cond
8850 ;; List item inside blockquote
8851 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
8852 (markdown-replace-regexp-in-string
8853 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
8854 ;; Blockquote
8855 ((looking-at markdown-regex-blockquote)
8856 (buffer-substring-no-properties (match-beginning 0) (match-end 2)))
8857 ;; List items
8858 ((looking-at markdown-regex-list)
8859 (match-string-no-properties 0))
8860 ;; Footnote definition
8861 ((looking-at-p markdown-regex-footnote-definition)
8862 " ") ; four spaces
8863 ;; No match
8864 (t nil)))
8866 (defun markdown-fill-paragraph (&optional justify)
8867 "Fill paragraph at or after point.
8868 This function is like \\[fill-paragraph], but it skips Markdown
8869 code blocks. If the point is in a code block, or just before one,
8870 do not fill. Otherwise, call `fill-paragraph' as usual. If
8871 JUSTIFY is non-nil, justify text as well. Since this function
8872 handles filling itself, it always returns t so that
8873 `fill-paragraph' doesn't run."
8874 (interactive "P")
8875 (unless (or (markdown-code-block-at-point-p)
8876 (save-excursion
8877 (back-to-indentation)
8878 (skip-syntax-forward "-")
8879 (markdown-code-block-at-point-p)))
8880 (fill-paragraph justify))
8883 (make-obsolete 'markdown-fill-forward-paragraph-function
8884 'markdown-fill-forward-paragraph "v2.3")
8886 (defun markdown-fill-forward-paragraph (&optional arg)
8887 "Function used by `fill-paragraph' to move over ARG paragraphs.
8888 This is a `fill-forward-paragraph-function' for `markdown-mode'.
8889 It is called with a single argument specifying the number of
8890 paragraphs to move. Just like `forward-paragraph', it should
8891 return the number of paragraphs left to move."
8892 (or arg (setq arg 1))
8893 (if (> arg 0)
8894 ;; With positive ARG, move across ARG non-code-block paragraphs,
8895 ;; one at a time. When passing a code block, don't decrement ARG.
8896 (while (and (not (eobp))
8897 (> arg 0)
8898 (= (forward-paragraph 1) 0)
8899 (or (markdown-code-block-at-pos (point-at-bol 0))
8900 (setq arg (1- arg)))))
8901 ;; Move backward by one paragraph with negative ARG (always -1).
8902 (let ((start (point)))
8903 (setq arg (forward-paragraph arg))
8904 (while (and (not (eobp))
8905 (progn (move-to-left-margin) (not (eobp)))
8906 (looking-at-p paragraph-separate))
8907 (forward-line 1))
8908 (cond
8909 ;; Move point past whitespace following list marker.
8910 ((looking-at markdown-regex-list)
8911 (goto-char (match-end 0)))
8912 ;; Move point past whitespace following pipe at beginning of line
8913 ;; to handle Pandoc line blocks.
8914 ((looking-at "^|\\s-*")
8915 (goto-char (match-end 0)))
8916 ;; Return point if the paragraph passed was a code block.
8917 ((markdown-code-block-at-pos (point-at-bol 2))
8918 (goto-char start)))))
8919 arg)
8921 (defun markdown--inhibit-electric-quote ()
8922 "Function added to `electric-quote-inhibit-functions'.
8923 Return non-nil if the quote has been inserted inside a code block
8924 or span."
8925 (let ((pos (1- (point))))
8926 (or (markdown-inline-code-at-pos pos)
8927 (markdown-code-block-at-pos pos))))
8930 ;;; Extension Framework =======================================================
8932 (defun markdown-reload-extensions ()
8933 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
8934 (interactive)
8935 (when (member major-mode '(markdown-mode gfm-mode))
8936 ;; Refontify buffer
8937 (if (eval-when-compile (fboundp 'font-lock-flush))
8938 ;; Use font-lock-flush in Emacs >= 25.1
8939 (font-lock-flush)
8940 ;; Backwards compatibility for Emacs 24.3-24.5
8941 (when (and font-lock-mode (fboundp 'font-lock-refresh-defaults))
8942 (font-lock-refresh-defaults)))
8943 ;; Add or remove hooks related to extensions
8944 (markdown-setup-wiki-link-hooks)))
8946 (defun markdown-handle-local-variables ()
8947 "Run in `hack-local-variables-hook' to update font lock rules.
8948 Checks to see if there is actually a ‘markdown-mode’ file local variable
8949 before regenerating font-lock rules for extensions."
8950 (when (and (boundp 'file-local-variables-alist)
8951 (or (assoc 'markdown-enable-wiki-links file-local-variables-alist)
8952 (assoc 'markdown-enable-math file-local-variables-alist)))
8953 (when (assoc 'markdown-enable-math file-local-variables-alist)
8954 (markdown-toggle-math markdown-enable-math))
8955 (markdown-reload-extensions)))
8958 ;;; Wiki Links ================================================================
8960 (defun markdown-toggle-wiki-links (&optional arg)
8961 "Toggle support for wiki links.
8962 With a prefix argument ARG, enable wiki link support if ARG is positive,
8963 and disable it otherwise."
8964 (interactive (list (or current-prefix-arg 'toggle)))
8965 (setq markdown-enable-wiki-links
8966 (if (eq arg 'toggle)
8967 (not markdown-enable-wiki-links)
8968 (> (prefix-numeric-value arg) 0)))
8969 (if markdown-enable-wiki-links
8970 (message "markdown-mode wiki link support enabled")
8971 (message "markdown-mode wiki link support disabled"))
8972 (markdown-reload-extensions))
8974 (defun markdown-setup-wiki-link-hooks ()
8975 "Add or remove hooks for fontifying wiki links.
8976 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
8977 ;; Anytime text changes make sure it gets fontified correctly
8978 (if (and markdown-enable-wiki-links
8979 markdown-wiki-link-fontify-missing)
8980 (add-hook 'after-change-functions
8981 'markdown-check-change-for-wiki-link-after-change t t)
8982 (remove-hook 'after-change-functions
8983 'markdown-check-change-for-wiki-link-after-change t))
8984 ;; If we left the buffer there is a really good chance we were
8985 ;; creating one of the wiki link documents. Make sure we get
8986 ;; refontified when we come back.
8987 (if (and markdown-enable-wiki-links
8988 markdown-wiki-link-fontify-missing)
8989 (progn
8990 (add-hook 'window-configuration-change-hook
8991 'markdown-fontify-buffer-wiki-links t t)
8992 (markdown-fontify-buffer-wiki-links))
8993 (remove-hook 'window-configuration-change-hook
8994 'markdown-fontify-buffer-wiki-links t)
8995 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
8998 ;;; Math Support ==============================================================
9000 (make-obsolete 'markdown-enable-math 'markdown-toggle-math "v2.1")
9002 (defconst markdown-mode-font-lock-keywords-math
9003 (list
9004 ;; Equation reference (eq:foo)
9005 '("\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" . ((1 markdown-markup-face)
9006 (2 markdown-reference-face)
9007 (3 markdown-markup-face)))
9008 ;; Equation reference \eqref{foo}
9009 '("\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" . ((1 markdown-markup-face)
9010 (2 markdown-reference-face)
9011 (3 markdown-markup-face))))
9012 "Font lock keywords to add and remove when toggling math support.")
9014 (defun markdown-toggle-math (&optional arg)
9015 "Toggle support for inline and display LaTeX math expressions.
9016 With a prefix argument ARG, enable math mode if ARG is positive,
9017 and disable it otherwise. If called from Lisp, enable the mode
9018 if ARG is omitted or nil."
9019 (interactive (list (or current-prefix-arg 'toggle)))
9020 (setq markdown-enable-math
9021 (if (eq arg 'toggle)
9022 (not markdown-enable-math)
9023 (> (prefix-numeric-value arg) 0)))
9024 (if markdown-enable-math
9025 (progn
9026 (font-lock-add-keywords
9027 'markdown-mode markdown-mode-font-lock-keywords-math)
9028 (message "markdown-mode math support enabled"))
9029 (font-lock-remove-keywords
9030 'markdown-mode markdown-mode-font-lock-keywords-math)
9031 (message "markdown-mode math support disabled"))
9032 (markdown-reload-extensions))
9035 ;;; GFM Checkboxes ============================================================
9037 (define-button-type 'markdown-gfm-checkbox-button
9038 'follow-link t
9039 'face 'markdown-gfm-checkbox-face
9040 'mouse-face 'markdown-highlight-face
9041 'action #'markdown-toggle-gfm-checkbox-button)
9043 (defun markdown-gfm-task-list-item-at-point (&optional bounds)
9044 "Return non-nil if there is a GFM task list item at the point.
9045 Optionally, the list item BOUNDS may be given if available, as
9046 returned by `markdown-cur-list-item-bounds'. When a task list item
9047 is found, the return value is the same value returned by
9048 `markdown-cur-list-item-bounds'."
9049 (unless bounds
9050 (setq bounds (markdown-cur-list-item-bounds)))
9051 (> (length (nth 5 bounds)) 0))
9053 (defun markdown-insert-gfm-checkbox ()
9054 "Add GFM checkbox at point.
9055 Returns t if added.
9056 Returns nil if non-applicable."
9057 (interactive)
9058 (let ((bounds (markdown-cur-list-item-bounds)))
9059 (if bounds
9060 (unless (cl-sixth bounds)
9061 (let ((pos (+ (cl-first bounds) (cl-fourth bounds)))
9062 (markup "[ ] "))
9063 (if (< pos (point))
9064 (save-excursion
9065 (goto-char pos)
9066 (insert markup))
9067 (goto-char pos)
9068 (insert markup))
9069 (syntax-propertize (+ (cl-second bounds) 4))
9071 (unless (save-excursion
9072 (back-to-indentation)
9073 (or (markdown-list-item-at-point-p)
9074 (markdown-heading-at-point)
9075 (markdown-in-comment-p)
9076 (markdown-code-block-at-point-p)))
9077 (let ((pos (save-excursion
9078 (back-to-indentation)
9079 (point)))
9080 (markup (concat (or (save-excursion
9081 (beginning-of-line 0)
9082 (cl-fifth (markdown-cur-list-item-bounds)))
9083 markdown-unordered-list-item-prefix)
9084 "[ ] ")))
9085 (if (< pos (point))
9086 (save-excursion
9087 (goto-char pos)
9088 (insert markup))
9089 (goto-char pos)
9090 (insert markup))
9091 (syntax-propertize (point-at-eol))
9092 t)))))
9094 (defun markdown-toggle-gfm-checkbox ()
9095 "Toggle GFM checkbox at point.
9096 Returns the resulting status as a string, either \"[x]\" or \"[ ]\".
9097 Returns nil if there is no task list item at the point."
9098 (interactive)
9099 (save-match-data
9100 (save-excursion
9101 (let ((bounds (markdown-cur-list-item-bounds)))
9102 (when bounds
9103 ;; Move to beginning of task list item
9104 (goto-char (cl-first bounds))
9105 ;; Advance to column of first non-whitespace after marker
9106 (forward-char (cl-fourth bounds))
9107 (cond ((looking-at "\\[ \\]")
9108 (replace-match
9109 (if markdown-gfm-uppercase-checkbox "[X]" "[x]")
9110 nil t)
9111 (match-string-no-properties 0))
9112 ((looking-at "\\[[xX]\\]")
9113 (replace-match "[ ]" nil t)
9114 (match-string-no-properties 0))))))))
9116 (defun markdown-toggle-gfm-checkbox-button (button)
9117 "Toggle GFM checkbox BUTTON on click."
9118 (save-match-data
9119 (save-excursion
9120 (goto-char (button-start button))
9121 (markdown-toggle-gfm-checkbox))))
9123 (defun markdown-make-gfm-checkboxes-buttons (start end)
9124 "Make GFM checkboxes buttons in region between START and END."
9125 (save-excursion
9126 (goto-char start)
9127 (let ((case-fold-search t))
9128 (save-excursion
9129 (while (re-search-forward markdown-regex-gfm-checkbox end t)
9130 (make-button (match-beginning 1) (match-end 1)
9131 :type 'markdown-gfm-checkbox-button))))))
9133 ;; Called when any modification is made to buffer text.
9134 (defun markdown-gfm-checkbox-after-change-function (beg end _)
9135 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
9136 BEG and END are the limits of scanned region."
9137 (save-excursion
9138 (save-match-data
9139 ;; Rescan between start of line from `beg' and start of line after `end'.
9140 (markdown-make-gfm-checkboxes-buttons
9141 (progn (goto-char beg) (beginning-of-line) (point))
9142 (progn (goto-char end) (forward-line 1) (point))))))
9144 (defun markdown-remove-gfm-checkbox-overlays ()
9145 "Remove all GFM checkbox overlays in buffer."
9146 (save-excursion
9147 (save-restriction
9148 (widen)
9149 (remove-overlays nil nil 'face 'markdown-gfm-checkbox-face))))
9152 ;;; Display inline image =================================================
9154 (defvar markdown-inline-image-overlays nil)
9155 (make-variable-buffer-local 'markdown-inline-image-overlays)
9157 (defun markdown-remove-inline-images ()
9158 "Remove inline image overlays from image links in the buffer.
9159 This can be toggled with `markdown-toggle-inline-images'
9160 or \\[markdown-toggle-inline-images]."
9161 (interactive)
9162 (mapc #'delete-overlay markdown-inline-image-overlays)
9163 (setq markdown-inline-image-overlays nil))
9165 (defun markdown-display-inline-images ()
9166 "Add inline image overlays to image links in the buffer.
9167 This can be toggled with `markdown-toggle-inline-images'
9168 or \\[markdown-toggle-inline-images]."
9169 (interactive)
9170 (unless (display-images-p)
9171 (error "Cannot show images"))
9172 (save-excursion
9173 (save-restriction
9174 (widen)
9175 (goto-char (point-min))
9176 (while (re-search-forward markdown-regex-link-inline nil t)
9177 (let ((start (match-beginning 0))
9178 (end (match-end 0))
9179 (file (match-string-no-properties 6)))
9180 (when (file-exists-p file)
9181 (let* ((abspath (if (file-name-absolute-p file)
9182 file
9183 (concat default-directory file)))
9184 (image
9185 (if (and markdown-max-image-size
9186 (image-type-available-p 'imagemagick))
9187 (create-image
9188 abspath 'imagemagick nil
9189 :max-width (car markdown-max-image-size)
9190 :max-height (cdr markdown-max-image-size))
9191 (create-image abspath))))
9192 (when image
9193 (let ((ov (make-overlay start end)))
9194 (overlay-put ov 'display image)
9195 (overlay-put ov 'face 'default)
9196 (push ov markdown-inline-image-overlays))))))))))
9198 (defun markdown-toggle-inline-images ()
9199 "Toggle inline image overlays in the buffer."
9200 (interactive)
9201 (if markdown-inline-image-overlays
9202 (markdown-remove-inline-images)
9203 (markdown-display-inline-images)))
9206 ;;; GFM Code Block Fontification ==============================================
9208 (defcustom markdown-fontify-code-blocks-natively nil
9209 "When non-nil, fontify code in code blocks using the native major mode.
9210 This only works for fenced code blocks where the language is
9211 specified where we can automatically determine the appropriate
9212 mode to use. The language to mode mapping may be customized by
9213 setting the variable `markdown-code-lang-modes'."
9214 :group 'markdown
9215 :type 'boolean
9216 :safe 'booleanp
9217 :package-version '(markdown-mode . "2.3"))
9219 (defun markdown-toggle-fontify-code-blocks-natively (&optional arg)
9220 "Toggle the native fontification of code blocks.
9221 With a prefix argument ARG, enable if ARG is positive,
9222 and disable otherwise."
9223 (interactive (list (or current-prefix-arg 'toggle)))
9224 (setq markdown-fontify-code-blocks-natively
9225 (if (eq arg 'toggle)
9226 (not markdown-fontify-code-blocks-natively)
9227 (> (prefix-numeric-value arg) 0)))
9228 (if markdown-fontify-code-blocks-natively
9229 (message "markdown-mode native code block fontification enabled")
9230 (message "markdown-mode native code block fontification disabled"))
9231 (markdown-reload-extensions))
9233 ;; This is based on `org-src-lang-modes' from org-src.el
9234 (defcustom markdown-code-lang-modes
9235 '(("ocaml" . tuareg-mode) ("elisp" . emacs-lisp-mode) ("ditaa" . artist-mode)
9236 ("asymptote" . asy-mode) ("dot" . fundamental-mode) ("sqlite" . sql-mode)
9237 ("calc" . fundamental-mode) ("C" . c-mode) ("cpp" . c++-mode)
9238 ("C++" . c++-mode) ("screen" . shell-script-mode) ("shell" . sh-mode)
9239 ("bash" . sh-mode))
9240 "Alist mapping languages to their major mode.
9241 The key is the language name, the value is the major mode. For
9242 many languages this is simple, but for language where this is not
9243 the case, this variable provides a way to simplify things on the
9244 user side. For example, there is no ocaml-mode in Emacs, but the
9245 mode to use is `tuareg-mode'."
9246 :group 'markdown
9247 :type '(repeat
9248 (cons
9249 (string "Language name")
9250 (symbol "Major mode")))
9251 :package-version '(markdown-mode . "2.3"))
9253 (defun markdown-get-lang-mode (lang)
9254 "Return major mode that should be used for LANG.
9255 LANG is a string, and the returned major mode is a symbol."
9256 (cl-find-if
9257 'fboundp
9258 (list (cdr (assoc lang markdown-code-lang-modes))
9259 (cdr (assoc (downcase lang) markdown-code-lang-modes))
9260 (intern (concat lang "-mode"))
9261 (intern (concat (downcase lang) "-mode")))))
9263 (defun markdown-fontify-code-blocks-generic (matcher last)
9264 "Add text properties to next code block from point to LAST.
9265 Use matching function MATCHER."
9266 (when (funcall matcher last)
9267 (save-excursion
9268 (save-match-data
9269 (let* ((start (match-beginning 0))
9270 (end (match-end 0))
9271 ;; Find positions outside opening and closing backquotes.
9272 (bol-prev (progn (goto-char start)
9273 (if (bolp) (point-at-bol 0) (point-at-bol))))
9274 (eol-next (progn (goto-char end)
9275 (if (bolp) (point-at-bol 2) (point-at-bol 3))))
9276 lang)
9277 (if (and markdown-fontify-code-blocks-natively
9278 (setq lang (markdown-code-block-lang)))
9279 (markdown-fontify-code-block-natively lang start end)
9280 (add-text-properties start end '(face markdown-pre-face)))
9281 ;; Set background for block as well as opening and closing lines.
9282 (font-lock-append-text-property
9283 bol-prev eol-next 'face 'markdown-code-face)
9284 ;; Set invisible property for lines before and after, including newline.
9285 (add-text-properties bol-prev start '(invisible markdown-markup))
9286 (add-text-properties end eol-next '(invisible markdown-markup)))))
9289 (defun markdown-fontify-gfm-code-blocks (last)
9290 "Add text properties to next GFM code block from point to LAST."
9291 (markdown-fontify-code-blocks-generic 'markdown-match-gfm-code-blocks last))
9293 (defun markdown-fontify-fenced-code-blocks (last)
9294 "Add text properties to next tilde fenced code block from point to LAST."
9295 (markdown-fontify-code-blocks-generic 'markdown-match-fenced-code-blocks last))
9297 ;; Based on `org-src-font-lock-fontify-block' from org-src.el.
9298 (defun markdown-fontify-code-block-natively (lang start end)
9299 "Fontify given GFM or fenced code block.
9300 This function is called by Emacs for automatic fontification when
9301 `markdown-fontify-code-blocks-natively' is non-nil. LANG is the
9302 language used in the block. START and END specify the block
9303 position."
9304 (let ((lang-mode (markdown-get-lang-mode lang)))
9305 (when (fboundp lang-mode)
9306 (let ((string (buffer-substring-no-properties start end))
9307 (modified (buffer-modified-p))
9308 (markdown-buffer (current-buffer)) pos next)
9309 (remove-text-properties start end '(face nil))
9310 (with-current-buffer
9311 (get-buffer-create
9312 (concat " markdown-code-fontification:" (symbol-name lang-mode)))
9313 ;; Make sure that modification hooks are not inhibited in
9314 ;; the org-src-fontification buffer in case we're called
9315 ;; from `jit-lock-function' (Bug#25132).
9316 (let ((inhibit-modification-hooks nil))
9317 (delete-region (point-min) (point-max))
9318 (insert string " ")) ;; so there's a final property change
9319 (unless (eq major-mode lang-mode) (funcall lang-mode))
9320 (markdown-font-lock-ensure)
9321 (setq pos (point-min))
9322 (while (setq next (next-single-property-change pos 'face))
9323 (let ((val (get-text-property pos 'face)))
9324 (when val
9325 (put-text-property
9326 (+ start (1- pos)) (1- (+ start next)) 'face
9327 val markdown-buffer)))
9328 (setq pos next)))
9329 (add-text-properties
9330 start end
9331 '(font-lock-fontified t fontified t font-lock-multiline t))
9332 (set-buffer-modified-p modified)))))
9334 (require 'edit-indirect nil t)
9335 (defvar edit-indirect-guess-mode-function)
9336 (defvar edit-indirect-after-commit-functions)
9338 (defun markdown--edit-indirect-after-commit-function (_beg end)
9339 "Ensure trailing newlines at the END of code blocks."
9340 (goto-char end)
9341 (unless (eq (char-before) ?\n)
9342 (insert "\n")))
9344 (defun markdown-edit-code-block ()
9345 "Edit Markdown code block in an indirect buffer."
9346 (interactive)
9347 (save-excursion
9348 (if (fboundp 'edit-indirect-region)
9349 (let* ((bounds (markdown-get-enclosing-fenced-block-construct))
9350 (begin (and bounds (goto-char (nth 0 bounds)) (point-at-bol 2)))
9351 (end (and bounds (goto-char (nth 1 bounds)) (point-at-bol 1))))
9352 (if (and begin end)
9353 (let* ((lang (markdown-code-block-lang))
9354 (mode (or (and lang (markdown-get-lang-mode lang))
9355 markdown-edit-code-block-default-mode))
9356 (edit-indirect-guess-mode-function
9357 (lambda (_parent-buffer _beg _end)
9358 (funcall mode))))
9359 (edit-indirect-region begin end 'display-buffer))
9360 (user-error "Not inside a GFM or tilde fenced code block")))
9361 (when (y-or-n-p "Package edit-indirect needed to edit code blocks. Install it now? ")
9362 (progn (package-refresh-contents)
9363 (package-install 'edit-indirect)
9364 (markdown-edit-code-block))))))
9367 ;;; Table Editing
9369 ;; These functions were originally adapted from `org-table.el'.
9371 ;; General helper functions
9373 (defmacro markdown--with-gensyms (symbols &rest body)
9374 (declare (debug (sexp body)) (indent 1))
9375 `(let ,(mapcar (lambda (s)
9376 `(,s (make-symbol (concat "--" (symbol-name ',s)))))
9377 symbols)
9378 ,@body))
9380 (defun markdown--split-string (string &optional separators)
9381 "Splits STRING into substrings at SEPARATORS.
9382 SEPARATORS is a regular expression. If nil it defaults to
9383 `split-string-default-separators'. This version returns no empty
9384 strings if there are matches at the beginning and end of string."
9385 (let ((start 0) notfirst list)
9386 (while (and (string-match
9387 (or separators split-string-default-separators)
9388 string
9389 (if (and notfirst
9390 (= start (match-beginning 0))
9391 (< start (length string)))
9392 (1+ start) start))
9393 (< (match-beginning 0) (length string)))
9394 (setq notfirst t)
9395 (or (eq (match-beginning 0) 0)
9396 (and (eq (match-beginning 0) (match-end 0))
9397 (eq (match-beginning 0) start))
9398 (push (substring string start (match-beginning 0)) list))
9399 (setq start (match-end 0)))
9400 (or (eq start (length string))
9401 (push (substring string start) list))
9402 (nreverse list)))
9404 (defun markdown--string-width (s)
9405 "Return width of string S.
9406 This version ignores characters with invisibility property
9407 `markdown-markup'."
9408 (let (b)
9409 (when (or (eq t buffer-invisibility-spec)
9410 (member 'markdown-markup buffer-invisibility-spec))
9411 (while (setq b (text-property-any
9412 0 (length s)
9413 'invisible 'markdown-markup s))
9414 (setq s (concat
9415 (substring s 0 b)
9416 (substring s (or (next-single-property-change
9417 b 'invisible s)
9418 (length s))))))))
9419 (string-width s))
9421 (defun markdown--remove-invisible-markup (s)
9422 "Remove Markdown markup from string S.
9423 This version removes characters with invisibility property
9424 `markdown-markup'."
9425 (let (b)
9426 (while (setq b (text-property-any
9427 0 (length s)
9428 'invisible 'markdown-markup s))
9429 (setq s (concat
9430 (substring s 0 b)
9431 (substring s (or (next-single-property-change
9432 b 'invisible s)
9433 (length s)))))))
9436 ;; Functions for maintaining tables
9438 (defvar markdown-table-at-point-p-function nil
9439 "Function to decide if point is inside a table.
9441 The indirection serves to differentiate between standard markdown
9442 tables and gfm tables which are less strict about the markup.")
9444 (defconst markdown-table-line-regexp "^[ \t]*|"
9445 "Regexp matching any line inside a table.")
9447 (defconst markdown-table-hline-regexp "^[ \t]*|[-:]"
9448 "Regexp matching hline inside a table.")
9450 (defconst markdown-table-dline-regexp "^[ \t]*|[^-:]"
9451 "Regexp matching dline inside a table.")
9453 (defun markdown-table-at-point-p ()
9454 "Return non-nil when point is inside a table."
9455 (if (functionp markdown-table-at-point-p-function)
9456 (funcall markdown-table-at-point-p-function)
9457 (markdown--table-at-point-p)))
9459 (defun markdown--table-at-point-p ()
9460 "Return non-nil when point is inside a table."
9461 (save-excursion
9462 (beginning-of-line)
9463 (and (looking-at-p markdown-table-line-regexp)
9464 (not (markdown-code-block-at-point-p)))))
9466 (defconst gfm-table-line-regexp "^.?*|"
9467 "Regexp matching any line inside a table.")
9469 (defconst gfm-table-hline-regexp "^-+\\(|-\\)+"
9470 "Regexp matching hline inside a table.")
9472 ;; GFM simplified tables syntax is as follows:
9473 ;; - A header line for the column names, this is any text
9474 ;; separated by `|'.
9475 ;; - Followed by a string -|-|- ..., the number of dashes is optional
9476 ;; but must be higher than 1. The number of separators should match
9477 ;; the number of columns.
9478 ;; - Followed by the rows of data, which has the same format as the
9479 ;; header line.
9480 ;; Example:
9482 ;; foo | bar
9483 ;; ------|---------
9484 ;; bar | baz
9485 ;; bar | baz
9486 (defun gfm--table-at-point-p ()
9487 "Return non-nil when point is inside a gfm-compatible table."
9488 (or (markdown--table-at-point-p)
9489 (save-excursion
9490 (beginning-of-line)
9491 (when (looking-at-p gfm-table-line-regexp)
9492 ;; we might be at the first line of the table, check if the
9493 ;; line below is the hline
9494 (or (save-excursion
9495 (forward-line 1)
9496 (looking-at-p gfm-table-hline-regexp))
9497 ;; go up to find the header
9498 (catch 'done
9499 (while (looking-at-p gfm-table-line-regexp)
9500 (when (looking-at-p gfm-table-hline-regexp)
9501 (throw 'done t))
9502 (forward-line -1))
9503 nil))))))
9505 (defun markdown-table-hline-at-point-p ()
9506 "Return non-nil when point is on a hline in a table.
9507 This function assumes point is on a table."
9508 (save-excursion
9509 (beginning-of-line)
9510 (looking-at-p markdown-table-hline-regexp)))
9512 (defun markdown-table-begin ()
9513 "Find the beginning of the table and return its position.
9514 This function assumes point is on a table."
9515 (save-excursion
9516 (while (and (not (bobp))
9517 (markdown-table-at-point-p))
9518 (forward-line -1))
9519 (unless (eobp)
9520 (forward-line 1))
9521 (point)))
9523 (defun markdown-table-end ()
9524 "Find the end of the table and return its position.
9525 This function assumes point is on a table."
9526 (save-excursion
9527 (while (and (not (eobp))
9528 (markdown-table-at-point-p))
9529 (forward-line 1))
9530 (point)))
9532 (defun markdown-table-get-dline ()
9533 "Return index of the table data line at point.
9534 This function assumes point is on a table."
9535 (let ((pos (point)) (end (markdown-table-end)) (cnt 0))
9536 (save-excursion
9537 (goto-char (markdown-table-begin))
9538 (while (and (re-search-forward
9539 markdown-table-dline-regexp end t)
9540 (setq cnt (1+ cnt))
9541 (< (point-at-eol) pos))))
9542 cnt))
9544 (defun markdown-table-get-column ()
9545 "Return table column at point.
9546 This function assumes point is on a table."
9547 (let ((pos (point)) (cnt 0))
9548 (save-excursion
9549 (beginning-of-line)
9550 (while (search-forward "|" pos t) (setq cnt (1+ cnt))))
9551 cnt))
9553 (defun markdown-table-get-cell (&optional n)
9554 "Return the content of the cell in column N of current row.
9555 N defaults to column at point. This function assumes point is on
9556 a table."
9557 (and n (markdown-table-goto-column n))
9558 (skip-chars-backward "^|\n") (backward-char 1)
9559 (if (looking-at "|[^|\r\n]*")
9560 (let* ((pos (match-beginning 0))
9561 (val (buffer-substring (1+ pos) (match-end 0))))
9562 (goto-char (min (point-at-eol) (+ 2 pos)))
9563 ;; Trim whitespaces
9564 (setq val (replace-regexp-in-string "\\`[ \t]+" "" val)
9565 val (replace-regexp-in-string "[ \t]+\\'" "" val)))
9566 (forward-char 1) ""))
9568 (defun markdown-table-goto-dline (n)
9569 "Go to the Nth data line in the table at point.
9570 Return t when the line exists, nil otherwise. This function
9571 assumes point is on a table."
9572 (goto-char (markdown-table-begin))
9573 (let ((end (markdown-table-end)) (cnt 0))
9574 (while (and (re-search-forward
9575 markdown-table-dline-regexp end t)
9576 (< (setq cnt (1+ cnt)) n)))
9577 (= cnt n)))
9579 (defun markdown-table-goto-column (n &optional on-delim)
9580 "Go to the Nth column in the table line at point.
9581 With optional argument ON-DELIM, stop with point before the left
9582 delimiter of the cell. If there are less than N cells, just go
9583 beyond the last delimiter. This function assumes point is on a
9584 table."
9585 (beginning-of-line 1)
9586 (when (> n 0)
9587 (while (and (> (setq n (1- n)) -1)
9588 (search-forward "|" (point-at-eol) t)))
9589 (if on-delim
9590 (backward-char 1)
9591 (when (looking-at " ") (forward-char 1)))))
9593 (defmacro markdown-table-save-cell (&rest body)
9594 "Save cell at point, execute BODY and restore cell.
9595 This function assumes point is on a table."
9596 (declare (debug (body)))
9597 (markdown--with-gensyms (line column)
9598 `(let ((,line (copy-marker (line-beginning-position)))
9599 (,column (markdown-table-get-column)))
9600 (unwind-protect
9601 (progn ,@body)
9602 (goto-char ,line)
9603 (markdown-table-goto-column ,column)
9604 (set-marker ,line nil)))))
9606 (defun markdown-table-blank-line (s)
9607 "Convert a table line S into a line with blank cells."
9608 (if (string-match "^[ \t]*|-" s)
9609 (setq s (mapconcat
9610 (lambda (x) (if (member x '(?| ?+)) "|" " "))
9611 s ""))
9612 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9613 (setq s (replace-match
9614 (concat "|" (make-string (length (match-string 1 s)) ?\ ) "|")
9615 t t s)))
9618 (defun markdown-table-colfmt (fmtspec)
9619 "Process column alignment specifier FMTSPEC for tables."
9620 (when (stringp fmtspec)
9621 (mapcar (lambda (x)
9622 (cond ((string-match-p "^:.*:$" x) 'c)
9623 ((string-match-p "^:" x) 'l)
9624 ((string-match-p ":$" x) 'r)
9625 (t 'd)))
9626 (markdown--split-string fmtspec "\\s-*|\\s-*"))))
9628 (defun markdown-table-align ()
9629 "Align table at point.
9630 This function assumes point is on a table."
9631 (interactive)
9632 (let ((begin (markdown-table-begin))
9633 (end (copy-marker (markdown-table-end))))
9634 (markdown-table-save-cell
9635 (goto-char begin)
9636 (let* (fmtspec
9637 ;; Store table indent
9638 (indent (progn (looking-at "[ \t]*") (match-string 0)))
9639 ;; Split table in lines and save column format specifier
9640 (lines (mapcar (lambda (l)
9641 (if (string-match-p "\\`[ \t]*|[-:]" l)
9642 (progn (setq fmtspec (or fmtspec l)) nil) l))
9643 (markdown--split-string (buffer-substring begin end) "\n")))
9644 ;; Split lines in cells
9645 (cells (mapcar (lambda (l) (markdown--split-string l "\\s-*|\\s-*"))
9646 (remq nil lines)))
9647 ;; Calculate maximum number of cells in a line
9648 (maxcells (if cells
9649 (apply #'max (mapcar #'length cells))
9650 (user-error "Empty table")))
9651 ;; Empty cells to fill short lines
9652 (emptycells (make-list maxcells "")) maxwidths)
9653 ;; Calculate maximum width for each column
9654 (dotimes (i maxcells)
9655 (let ((column (mapcar (lambda (x) (or (nth i x) "")) cells)))
9656 (push (apply #'max 1 (mapcar #'markdown--string-width column))
9657 maxwidths)))
9658 (setq maxwidths (nreverse maxwidths))
9659 ;; Process column format specifier
9660 (setq fmtspec (markdown-table-colfmt fmtspec))
9661 ;; Compute formats needed for output of table lines
9662 (let ((hfmt (concat indent "|"))
9663 (rfmt (concat indent "|"))
9664 hfmt1 rfmt1 fmt)
9665 (dolist (width maxwidths (setq hfmt (concat (substring hfmt 0 -1) "|")))
9666 (setq fmt (pop fmtspec))
9667 (cond ((equal fmt 'l) (setq hfmt1 ":%s-|" rfmt1 " %%-%ds |"))
9668 ((equal fmt 'r) (setq hfmt1 "-%s:|" rfmt1 " %%%ds |"))
9669 ((equal fmt 'c) (setq hfmt1 ":%s:|" rfmt1 " %%-%ds |"))
9670 (t (setq hfmt1 "-%s-|" rfmt1 " %%-%ds |")))
9671 (setq rfmt (concat rfmt (format rfmt1 width)))
9672 (setq hfmt (concat hfmt (format hfmt1 (make-string width ?-)))))
9673 ;; Replace modified lines only
9674 (dolist (line lines)
9675 (let ((line (if line
9676 (apply #'format rfmt (append (pop cells) emptycells))
9677 hfmt))
9678 (previous (buffer-substring (point) (line-end-position))))
9679 (if (equal previous line)
9680 (forward-line)
9681 (insert line "\n")
9682 (delete-region (point) (line-beginning-position 2))))))
9683 (set-marker end nil)))))
9685 (defun markdown-table-insert-row (&optional arg)
9686 "Insert a new row above the row at point into the table.
9687 With optional argument ARG, insert below the current row."
9688 (interactive "P")
9689 (unless (markdown-table-at-point-p)
9690 (user-error "Not at a table"))
9691 (let* ((line (buffer-substring
9692 (line-beginning-position) (line-end-position)))
9693 (new (markdown-table-blank-line line)))
9694 (beginning-of-line (if arg 2 1))
9695 (unless (bolp) (insert "\n"))
9696 (insert-before-markers new "\n")
9697 (beginning-of-line 0)
9698 (re-search-forward "| ?" (line-end-position) t)))
9700 (defun markdown-table-delete-row ()
9701 "Delete row or horizontal line at point from the table."
9702 (interactive)
9703 (unless (markdown-table-at-point-p)
9704 (user-error "Not at a table"))
9705 (let ((col (current-column)))
9706 (kill-region (point-at-bol)
9707 (min (1+ (point-at-eol)) (point-max)))
9708 (unless (markdown-table-at-point-p) (beginning-of-line 0))
9709 (move-to-column col)))
9711 (defun markdown-table-move-row (&optional up)
9712 "Move table line at point down.
9713 With optional argument UP, move it up."
9714 (interactive "P")
9715 (unless (markdown-table-at-point-p)
9716 (user-error "Not at a table"))
9717 (let* ((col (current-column)) (pos (point))
9718 (tonew (if up 0 2)) txt)
9719 (beginning-of-line tonew)
9720 (unless (markdown-table-at-point-p)
9721 (goto-char pos) (user-error "Cannot move row further"))
9722 (goto-char pos) (beginning-of-line 1) (setq pos (point))
9723 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9724 (delete-region (point) (1+ (point-at-eol)))
9725 (beginning-of-line tonew)
9726 (insert txt) (beginning-of-line 0)
9727 (move-to-column col)))
9729 (defun markdown-table-move-row-up ()
9730 "Move table row at point up."
9731 (interactive)
9732 (markdown-table-move-row 'up))
9734 (defun markdown-table-move-row-down ()
9735 "Move table row at point down."
9736 (interactive)
9737 (markdown-table-move-row nil))
9739 (defun markdown-table-insert-column ()
9740 "Insert a new table column."
9741 (interactive)
9742 (unless (markdown-table-at-point-p)
9743 (user-error "Not at a table"))
9744 (let* ((col (max 1 (markdown-table-get-column)))
9745 (begin (markdown-table-begin))
9746 (end (copy-marker (markdown-table-end))))
9747 (markdown-table-save-cell
9748 (goto-char begin)
9749 (while (< (point) end)
9750 (markdown-table-goto-column col t)
9751 (if (markdown-table-hline-at-point-p)
9752 (insert "|---")
9753 (insert "| "))
9754 (forward-line)))
9755 (set-marker end nil)
9756 (markdown-table-align)))
9758 (defun markdown-table-delete-column ()
9759 "Delete column at point from table."
9760 (interactive)
9761 (unless (markdown-table-at-point-p)
9762 (user-error "Not at a table"))
9763 (let ((col (markdown-table-get-column))
9764 (begin (markdown-table-begin))
9765 (end (copy-marker (markdown-table-end))))
9766 (markdown-table-save-cell
9767 (goto-char begin)
9768 (while (< (point) end)
9769 (markdown-table-goto-column col t)
9770 (and (looking-at "|[^|\n]+|")
9771 (replace-match "|"))
9772 (forward-line)))
9773 (set-marker end nil)
9774 (markdown-table-goto-column (max 1 (1- col)))
9775 (markdown-table-align)))
9777 (defun markdown-table-move-column (&optional left)
9778 "Move table column at point to the right.
9779 With optional argument LEFT, move it to the left."
9780 (interactive "P")
9781 (unless (markdown-table-at-point-p)
9782 (user-error "Not at a table"))
9783 (let* ((col (markdown-table-get-column))
9784 (col1 (if left (1- col) col))
9785 (colpos (if left (1- col) (1+ col)))
9786 (begin (markdown-table-begin))
9787 (end (copy-marker (markdown-table-end))))
9788 (when (and left (= col 1))
9789 (user-error "Cannot move column further left"))
9790 (when (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9791 (user-error "Cannot move column further right"))
9792 (markdown-table-save-cell
9793 (goto-char begin)
9794 (while (< (point) end)
9795 (markdown-table-goto-column col1 t)
9796 (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9797 (replace-match "|\\2|\\1|"))
9798 (forward-line)))
9799 (set-marker end nil)
9800 (markdown-table-goto-column colpos)
9801 (markdown-table-align)))
9803 (defun markdown-table-move-column-left ()
9804 "Move table column at point to the left."
9805 (interactive)
9806 (markdown-table-move-column 'left))
9808 (defun markdown-table-move-column-right ()
9809 "Move table column at point to the right."
9810 (interactive)
9811 (markdown-table-move-column nil))
9813 (defun markdown-table-next-row ()
9814 "Go to the next row (same column) in the table.
9815 Create new table lines if required."
9816 (interactive)
9817 (unless (markdown-table-at-point-p)
9818 (user-error "Not at a table"))
9819 (if (or (looking-at "[ \t]*$")
9820 (save-excursion (skip-chars-backward " \t") (bolp)))
9821 (newline)
9822 (markdown-table-align)
9823 (let ((col (markdown-table-get-column)))
9824 (beginning-of-line 2)
9825 (if (or (not (markdown-table-at-point-p))
9826 (markdown-table-hline-at-point-p))
9827 (progn
9828 (beginning-of-line 0)
9829 (markdown-table-insert-row 'below)))
9830 (markdown-table-goto-column col)
9831 (skip-chars-backward "^|\n\r")
9832 (when (looking-at " ") (forward-char 1)))))
9834 (defun markdown-table-forward-cell ()
9835 "Go to the next cell in the table.
9836 Create new table lines if required."
9837 (interactive)
9838 (unless (markdown-table-at-point-p)
9839 (user-error "Not at a table"))
9840 (markdown-table-align)
9841 (let ((end (markdown-table-end)))
9842 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9843 (condition-case nil
9844 (progn
9845 (re-search-forward "|" end)
9846 (if (looking-at "[ \t]*$")
9847 (re-search-forward "|" end))
9848 (if (and (looking-at "[-:]")
9849 (re-search-forward "^[ \t]*|\\([^-:]\\)" end t))
9850 (goto-char (match-beginning 1)))
9851 (if (looking-at "[-:]")
9852 (progn
9853 (beginning-of-line 0)
9854 (markdown-table-insert-row 'below))
9855 (when (looking-at " ") (forward-char 1))))
9856 (error (markdown-table-insert-row 'below)))))
9858 (defun markdown-table-backward-cell ()
9859 "Go to the previous cell in the table."
9860 (interactive)
9861 (unless (markdown-table-at-point-p)
9862 (user-error "Not at a table"))
9863 (markdown-table-align)
9864 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9865 (condition-case nil
9866 (progn
9867 (re-search-backward "|" (markdown-table-begin))
9868 (re-search-backward "|" (markdown-table-begin)))
9869 (error (user-error "Cannot move to previous table cell")))
9870 (while (looking-at "|\\([-:]\\|[ \t]*$\\)")
9871 (re-search-backward "|" (markdown-table-begin)))
9872 (when (looking-at "| ?") (goto-char (match-end 0))))
9874 (defun markdown-table-transpose ()
9875 "Transpose table at point.
9876 Horizontal separator lines will be eliminated."
9877 (interactive)
9878 (unless (markdown-table-at-point-p)
9879 (user-error "Not at a table"))
9880 (let* ((table (buffer-substring-no-properties
9881 (markdown-table-begin) (markdown-table-end)))
9882 ;; Convert table to a Lisp structure
9883 (table (delq nil
9884 (mapcar
9885 (lambda (x)
9886 (unless (string-match-p
9887 markdown-table-hline-regexp x)
9888 (markdown--split-string x "\\s-*|\\s-*")))
9889 (markdown--split-string table "[ \t]*\n[ \t]*"))))
9890 (dline_old (markdown-table-get-dline))
9891 (col_old (markdown-table-get-column))
9892 (contents (mapcar (lambda (_)
9893 (let ((tp table))
9894 (mapcar
9895 (lambda (_)
9896 (prog1
9897 (pop (car tp))
9898 (setq tp (cdr tp))))
9899 table)))
9900 (car table))))
9901 (goto-char (markdown-table-begin))
9902 (re-search-forward "|") (backward-char)
9903 (delete-region (point) (markdown-table-end))
9904 (insert (mapconcat
9905 (lambda(x)
9906 (concat "| " (mapconcat 'identity x " | " ) " |\n"))
9907 contents ""))
9908 (markdown-table-goto-dline col_old)
9909 (markdown-table-goto-column dline_old))
9910 (markdown-table-align))
9912 (defun markdown-table-sort-lines (&optional sorting-type)
9913 "Sort table lines according to the column at point.
9915 The position of point indicates the column to be used for
9916 sorting, and the range of lines is the range between the nearest
9917 horizontal separator lines, or the entire table of no such lines
9918 exist. If point is before the first column, user will be prompted
9919 for the sorting column. If there is an active region, the mark
9920 specifies the first line and the sorting column, while point
9921 should be in the last line to be included into the sorting.
9923 The command then prompts for the sorting type which can be
9924 alphabetically or numerically. Sorting in reverse order is also
9925 possible.
9927 If SORTING-TYPE is specified when this function is called from a
9928 Lisp program, no prompting will take place. SORTING-TYPE must be
9929 a character, any of (?a ?A ?n ?N) where the capital letters
9930 indicate that sorting should be done in reverse order."
9931 (interactive)
9932 (unless (markdown-table-at-point-p)
9933 (user-error "Not at a table"))
9934 ;; Set sorting type and column used for sorting
9935 (let ((column (let ((c (markdown-table-get-column)))
9936 (cond ((> c 0) c)
9937 ((called-interactively-p 'any)
9938 (read-number "Use column N for sorting: "))
9939 (t 1))))
9940 (sorting-type
9941 (or sorting-type
9942 (read-char-exclusive
9943 "Sort type: [a]lpha [n]umeric (A/N means reversed): "))))
9944 (save-restriction
9945 ;; Narrow buffer to appropriate sorting area
9946 (if (region-active-p)
9947 (narrow-to-region
9948 (save-excursion
9949 (progn
9950 (goto-char (region-beginning)) (line-beginning-position)))
9951 (save-excursion
9952 (progn
9953 (goto-char (region-end)) (line-end-position))))
9954 (let ((start (markdown-table-begin))
9955 (end (markdown-table-end)))
9956 (narrow-to-region
9957 (save-excursion
9958 (if (re-search-backward
9959 markdown-table-hline-regexp start t)
9960 (line-beginning-position 2)
9961 start))
9962 (if (save-excursion (re-search-forward
9963 markdown-table-hline-regexp end t))
9964 (match-beginning 0)
9965 end))))
9966 ;; Determine arguments for `sort-subr'
9967 (let* ((extract-key-from-cell
9968 (cl-case sorting-type
9969 ((?a ?A) #'markdown--remove-invisible-markup) ;; #'identity)
9970 ((?n ?N) #'string-to-number)
9971 (t (user-error "Invalid sorting type: %c" sorting-type))))
9972 (predicate
9973 (cl-case sorting-type
9974 ((?n ?N) #'<)
9975 ((?a ?A) #'string<))))
9976 ;; Sort selected area
9977 (goto-char (point-min))
9978 (sort-subr (memq sorting-type '(?A ?N))
9979 (lambda ()
9980 (forward-line)
9981 (while (and (not (eobp))
9982 (not (looking-at
9983 markdown-table-dline-regexp)))
9984 (forward-line)))
9985 #'end-of-line
9986 (lambda ()
9987 (funcall extract-key-from-cell
9988 (markdown-table-get-cell column)))
9990 predicate)
9991 (goto-char (point-min))))))
9993 (defun markdown-table-convert-region (begin end &optional separator)
9994 "Convert region from BEGIN to END to table with SEPARATOR.
9996 If every line contains at least one TAB character, the function
9997 assumes that the material is tab separated (TSV). If every line
9998 contains a comma, comma-separated values (CSV) are assumed. If
9999 not, lines are split at whitespace into cells.
10001 You can use a prefix argument to force a specific separator:
10002 \\[universal-argument] once forces CSV, \\[universal-argument]
10003 twice forces TAB, and \\[universal-argument] three times will
10004 prompt for a regular expression to match the separator, and a
10005 numeric argument N indicates that at least N consecutive
10006 spaces, or alternatively a TAB should be used as the separator."
10008 (interactive "r\nP")
10009 (let* ((begin (min begin end)) (end (max begin end)) re)
10010 (goto-char begin) (beginning-of-line 1)
10011 (setq begin (point-marker))
10012 (goto-char end)
10013 (if (bolp) (backward-char 1) (end-of-line 1))
10014 (setq end (point-marker))
10015 (when (equal separator '(64))
10016 (setq separator (read-regexp "Regexp for cell separator: ")))
10017 (unless separator
10018 ;; Get the right cell separator
10019 (goto-char begin)
10020 (setq separator
10021 (cond
10022 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
10023 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
10024 (t 1))))
10025 (goto-char begin)
10026 (if (equal separator '(4))
10027 ;; Parse CSV
10028 (while (< (point) end)
10029 (cond
10030 ((looking-at "^") (insert "| "))
10031 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
10032 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
10033 (replace-match "\\1") (if (looking-at "\"") (insert "\"")))
10034 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
10035 ((looking-at "[ \t]*,") (replace-match " | "))
10036 (t (beginning-of-line 2))))
10037 (setq re
10038 (cond
10039 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
10040 ((equal separator '(16)) "^\\|\t")
10041 ((integerp separator)
10042 (if (< separator 1)
10043 (user-error "Cell separator must contain one or more spaces")
10044 (format "^ *\\| *\t *\\| \\{%d,\\}" separator)))
10045 ((stringp separator) (format "^ *\\|%s" separator))
10046 (t (error "Invalid cell separator"))))
10047 (while (re-search-forward re end t) (replace-match "| " t t)))
10048 (goto-char begin)
10049 (markdown-table-align)))
10052 ;;; ElDoc Support
10054 (defun markdown-eldoc-function ()
10055 "Return a helpful string when appropriate based on context.
10056 * Report URL when point is at a hidden URL.
10057 * Report language name when point is a code block with hidden markup."
10058 (cond
10059 ;; Hidden URL or reference for inline link
10060 ((and (or (thing-at-point-looking-at markdown-regex-link-inline)
10061 (thing-at-point-looking-at markdown-regex-link-reference))
10062 (or markdown-hide-urls markdown-hide-markup))
10063 (let* ((imagep (string-equal (match-string 1) "!"))
10064 (edit-keys (markdown--substitute-command-keys
10065 (if imagep
10066 "\\[markdown-insert-image]"
10067 "\\[markdown-insert-link]")))
10068 (edit-str (propertize edit-keys 'face 'font-lock-constant-face))
10069 (referencep (string-equal (match-string 5) "["))
10070 (object (if referencep "reference" "URL")))
10071 (format "Hidden %s (%s to edit): %s" object edit-str
10072 (if referencep
10073 (concat
10074 (propertize "[" 'face 'markdown-markup-face)
10075 (propertize (match-string-no-properties 6)
10076 'face 'markdown-reference-face)
10077 (propertize "]" 'face 'markdown-markup-face))
10078 (propertize (match-string-no-properties 6)
10079 'face 'markdown-url-face)))))
10080 ;; Hidden language name for fenced code blocks
10081 ((and (markdown-code-block-at-point-p)
10082 (not (get-text-property (point) 'markdown-pre))
10083 markdown-hide-markup)
10084 (let ((lang (save-excursion (markdown-code-block-lang))))
10085 (unless lang (setq lang "[unspecified]"))
10086 (format "Hidden code block language: %s (%s to toggle markup)"
10087 (propertize lang 'face 'markdown-language-keyword-face)
10088 (markdown--substitute-command-keys
10089 "\\[markdown-toggle-markup-hiding]"))))))
10092 ;;; Mode Definition ==========================================================
10094 (defun markdown-show-version ()
10095 "Show the version number in the minibuffer."
10096 (interactive)
10097 (message "markdown-mode, version %s" markdown-mode-version))
10099 (defun markdown-mode-info ()
10100 "Open the `markdown-mode' homepage."
10101 (interactive)
10102 (browse-url "https://jblevins.org/projects/markdown-mode/"))
10104 ;;;###autoload
10105 (define-derived-mode markdown-mode text-mode "Markdown"
10106 "Major mode for editing Markdown files."
10107 ;; Natural Markdown tab width
10108 (setq tab-width 4)
10109 ;; Comments
10110 (setq-local comment-start "<!-- ")
10111 (setq-local comment-end " -->")
10112 (setq-local comment-start-skip "<!--[ \t]*")
10113 (setq-local comment-column 0)
10114 (setq-local comment-auto-fill-only-comments nil)
10115 (setq-local comment-use-syntax t)
10116 ;; Syntax
10117 (add-hook 'syntax-propertize-extend-region-functions
10118 #'markdown-syntax-propertize-extend-region)
10119 (add-hook 'jit-lock-after-change-extend-region-functions
10120 #'markdown-font-lock-extend-region-function t t)
10121 (setq-local syntax-propertize-function #'markdown-syntax-propertize)
10122 (syntax-propertize (point-max)) ;; Propertize before hooks run, etc.
10123 ;; Font lock.
10124 (setq-local font-lock-defaults nil)
10125 (setq-local font-lock-multiline t)
10126 (setq-local font-lock-extra-managed-props
10127 (append font-lock-extra-managed-props
10128 '(composition display invisible)))
10129 (if markdown-hide-markup
10130 (add-to-invisibility-spec 'markdown-markup)
10131 (remove-from-invisibility-spec 'markdown-markup))
10132 (setq font-lock-defaults
10133 '(markdown-mode-font-lock-keywords-basic
10134 nil nil nil nil
10135 (font-lock-syntactic-face-function . markdown-syntactic-face)))
10136 ;; Wiki links
10137 (markdown-setup-wiki-link-hooks)
10138 ;; Math mode
10139 (when markdown-enable-math (markdown-toggle-math t))
10140 ;; Add a buffer-local hook to reload after file-local variables are read
10141 (add-hook 'hack-local-variables-hook #'markdown-handle-local-variables nil t)
10142 ;; For imenu support
10143 (setq imenu-create-index-function
10144 (if markdown-nested-imenu-heading-index
10145 #'markdown-imenu-create-nested-index
10146 #'markdown-imenu-create-flat-index))
10147 ;; For menu support in XEmacs
10148 (easy-menu-add markdown-mode-menu markdown-mode-map)
10149 ;; Defun movement
10150 (setq-local beginning-of-defun-function #'markdown-beginning-of-defun)
10151 (setq-local end-of-defun-function #'markdown-end-of-defun)
10152 ;; Paragraph filling
10153 (setq-local fill-paragraph-function #'markdown-fill-paragraph)
10154 (setq-local paragraph-start
10155 ;; Should match start of lines that start or separate paragraphs
10156 (mapconcat #'identity
10158 "\f" ; starts with a literal line-feed
10159 "[ \t\f]*$" ; space-only line
10160 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
10161 "[ \t]*[*+-][ \t]+" ; unordered list item
10162 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
10163 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
10164 "[ \t]*:[ \t]+" ; definition
10165 "^|" ; table or Pandoc line block
10167 "\\|"))
10168 (setq-local paragraph-separate
10169 ;; Should match lines that separate paragraphs without being
10170 ;; part of any paragraph:
10171 (mapconcat #'identity
10172 '("[ \t\f]*$" ; space-only line
10173 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
10174 ;; The following is not ideal, but the Fill customization
10175 ;; options really only handle paragraph-starting prefixes,
10176 ;; not paragraph-ending suffixes:
10177 ".* $" ; line ending in two spaces
10178 "^#+"
10179 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
10180 "\\|"))
10181 (setq-local adaptive-fill-first-line-regexp "\\`[ \t]*[A-Z]?>[ \t]*?\\'")
10182 (setq-local adaptive-fill-regexp "\\s-*")
10183 (setq-local adaptive-fill-function #'markdown-adaptive-fill-function)
10184 (setq-local fill-forward-paragraph-function #'markdown-fill-forward-paragraph)
10185 ;; Outline mode
10186 (setq-local outline-regexp markdown-regex-header)
10187 (setq-local outline-level #'markdown-outline-level)
10188 ;; Cause use of ellipses for invisible text.
10189 (add-to-invisibility-spec '(outline . t))
10190 ;; ElDoc support
10191 (if (eval-when-compile (fboundp 'add-function))
10192 (add-function :before-until (local 'eldoc-documentation-function)
10193 #'markdown-eldoc-function)
10194 (setq-local eldoc-documentation-function #'markdown-eldoc-function))
10195 ;; Inhibiting line-breaking:
10196 ;; Separating out each condition into a separate function so that users can
10197 ;; override if desired (with remove-hook)
10198 (add-hook 'fill-nobreak-predicate
10199 #'markdown-line-is-reference-definition-p nil t)
10200 (add-hook 'fill-nobreak-predicate
10201 #'markdown-pipe-at-bol-p nil t)
10203 ;; Indentation
10204 (setq-local indent-line-function markdown-indent-function)
10206 ;; Flyspell
10207 (setq-local flyspell-generic-check-word-predicate
10208 #'markdown-flyspell-check-word-p)
10210 ;; Electric quoting
10211 (add-hook 'electric-quote-inhibit-functions
10212 #'markdown--inhibit-electric-quote nil :local)
10214 ;; Backwards compatibility with markdown-css-path
10215 (when (boundp 'markdown-css-path)
10216 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
10217 (add-to-list 'markdown-css-paths markdown-css-path))
10219 ;; Prepare hooks for XEmacs compatibility
10220 (when (featurep 'xemacs)
10221 (make-local-hook 'after-change-functions)
10222 (make-local-hook 'font-lock-extend-region-functions)
10223 (make-local-hook 'window-configuration-change-hook))
10225 ;; Make checkboxes buttons
10226 (when markdown-make-gfm-checkboxes-buttons
10227 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
10228 (add-hook 'after-change-functions #'markdown-gfm-checkbox-after-change-function t t)
10229 (add-hook 'change-major-mode-hook #'markdown-remove-gfm-checkbox-overlays t t))
10231 ;; edit-indirect
10232 (add-hook 'edit-indirect-after-commit-functions
10233 #'markdown--edit-indirect-after-commit-function
10234 nil 'local)
10236 ;; Marginalized headings
10237 (when markdown-marginalize-headers
10238 (add-hook 'window-configuration-change-hook
10239 #'markdown-marginalize-update-current nil t))
10241 ;; add live preview export hook
10242 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
10243 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
10245 ;;;###autoload
10246 (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode) t)
10247 ;;;###autoload
10248 (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode) t)
10251 ;;; GitHub Flavored Markdown Mode ============================================
10253 (defvar gfm-mode-hook nil
10254 "Hook run when entering GFM mode.")
10256 (defvar gfm-font-lock-keywords
10257 ;; Basic Markdown features (excluding possibly overridden ones)
10258 markdown-mode-font-lock-keywords-basic
10259 "Default highlighting expressions for GitHub Flavored Markdown mode.")
10261 ;;;###autoload
10262 (define-derived-mode gfm-mode markdown-mode "GFM"
10263 "Major mode for editing GitHub Flavored Markdown files."
10264 (setq markdown-link-space-sub-char "-")
10265 (setq markdown-wiki-link-search-subdirectories t)
10266 (setq-local font-lock-defaults '(gfm-font-lock-keywords))
10267 (setq-local markdown-table-at-point-p-function 'gfm--table-at-point-p)
10268 ;; do the initial link fontification
10269 (markdown-gfm-parse-buffer-for-languages))
10272 ;;; Live Preview Mode ============================================
10273 (define-minor-mode markdown-live-preview-mode
10274 "Toggle native previewing on save for a specific markdown file."
10275 :lighter " MD-Preview"
10276 (if markdown-live-preview-mode
10277 (if (markdown-live-preview-get-filename)
10278 (markdown-display-buffer-other-window (markdown-live-preview-export))
10279 (markdown-live-preview-mode -1)
10280 (user-error "Buffer %s does not visit a file" (current-buffer)))
10281 (markdown-live-preview-remove)))
10284 (provide 'markdown-mode)
10286 ;; Local Variables:
10287 ;; indent-tabs-mode: nil
10288 ;; coding: utf-8
10289 ;; End:
10290 ;;; markdown-mode.el ends here