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 <jrblevin@sdf.org>
7 ;; Maintainer: Jason R. Blevins <jrblevin@sdf.org>
8 ;; Created: May 24, 2007
10 ;; Package-Requires: ((emacs "24") (cl-lib "0.5"))
11 ;; Keywords: Markdown, GitHub Flavored Markdown, itex
12 ;; URL: http://jblevins.org/projects/markdown-mode/
14 ;; This file is not part of GNU Emacs.
16 ;; This program is free software; you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation; either version 2, or (at your option)
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, write to the Free Software
28 ;; Foundation, Inc., 51 Franklin Street, Fifth Floor,
29 ;; Boston, MA 02110-1301, USA.
33 ;; markdown-mode is a major mode for editing [Markdown][]-formatted
34 ;; text. The latest stable version is markdown-mode 2.1, released on
35 ;; January 9, 2016. See the [release notes][] for details.
36 ;; markdown-mode is free software, licensed under the GNU GPL.
38 ;; ![Markdown Mode Screenshot](http://jblevins.org/projects/markdown-mode/screenshots/20160108-001.png)
40 ;; [Markdown]: http://daringfireball.net/projects/markdown/
41 ;; [release notes]: http://jblevins.org/projects/markdown-mode/rev-2-1
45 ;; The recommended way to install markdown-mode is to install the package
46 ;; from [MELPA Stable](https://stable.melpa.org/#/markdown-mode)
47 ;; using `package.el'. First, configure `package.el' and the MELPA Stable
48 ;; repository by adding the following to your `.emacs', `init.el',
49 ;; or equivalent startup file:
52 ;; (add-to-list 'package-archives
53 ;; '("melpa-stable" . "https://stable.melpa.org/packages/"))
54 ;; (package-initialize)
56 ;; Then, after restarting Emacs or evaluating the above statements, issue
57 ;; the following command: `M-x package-install RET markdown-mode RET`.
58 ;; When installed this way, the major modes `markdown-mode' and `gfm-mode'
59 ;; will be autoloaded and `markdown-mode' will be used for file names
60 ;; ending in either `.md` or `.markdown`.
62 ;; Alternatively, if you manage loading packages with [use-package][]
63 ;; then you can automatically install and configure `markdown-mode' by
64 ;; adding a declaration such as this one to your init file (as an
65 ;; example; adjust settings as desired):
67 ;; (use-package markdown-mode
69 ;; :commands (markdown-mode gfm-mode)
70 ;; :mode (("README\\.md\\'" . gfm-mode)
71 ;; ("\\.md\\'" . markdown-mode)
72 ;; ("\\.markdown\\'" . markdown-mode))
73 ;; :init (setq markdown-command "multimarkdown"))
75 ;; [MELPA Stable]: http://stable.melpa.org/
76 ;; [use-package]: https://github.com/jwiegley/use-package
78 ;; **Direct Download**
80 ;; Alternatively you can manually download and install markdown-mode.
81 ;; First, download the [latest stable version][markdown-mode.el] and
82 ;; save the file where Emacs can find it (i.e., a directory in your
83 ;; `load-path'). You can then configure `markdown-mode' and `gfm-mode'
84 ;; to load automatically by adding the following to your init file:
86 ;; (autoload 'markdown-mode "markdown-mode"
87 ;; "Major mode for editing Markdown files" t)
88 ;; (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode))
89 ;; (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode))
91 ;; (autoload 'gfm-mode "markdown-mode"
92 ;; "Major mode for editing GitHub Flavored Markdown files" t)
93 ;; (add-to-list 'auto-mode-alist '("README\\.md\\'" . gfm-mode))
95 ;; [markdown-mode.el]: http://jblevins.org/projects/markdown-mode/markdown-mode.el
97 ;; **Development Version**
99 ;; To follow or contribute to markdown-mode development, you can
100 ;; browse or clone the Git repository
101 ;; [on GitHub](https://github.com/jrblevin/markdown-mode):
103 ;; git clone https://github.com/jrblevin/markdown-mode.git
105 ;; If you prefer to install and use the development version, which may
106 ;; become unstable at some times, you can either clone the Git
107 ;; repository as above or install markdown-mode from
108 ;; [MELPA](https://melpa.org/#/markdown-mode).
110 ;; If you clone the repository directly, then make sure that Emacs can
111 ;; find it by adding the following line to your startup file:
113 ;; (add-to-list 'load-path "/path/to/markdown-mode/repository")
115 ;; **Packaged Installation**
117 ;; markdown-mode is also available in several package managers. You
118 ;; may want to confirm that the package you install contains the
119 ;; latest stable version first (and please notify the package
120 ;; maintainer if not).
122 ;; * Debian Linux: [elpa-markdown-mode][] and [emacs-goodies-el][]
123 ;; * Ubuntu Linux: [elpa-markdown-mode][elpa-ubuntu] and [emacs-goodies-el][emacs-goodies-el-ubuntu]
124 ;; * RedHat and Fedora Linux: [emacs-goodies][]
125 ;; * NetBSD: [textproc/markdown-mode][]
126 ;; * MacPorts: [markdown-mode.el][macports-package] ([pending][macports-ticket])
127 ;; * FreeBSD: [textproc/markdown-mode.el][freebsd-port]
129 ;; [elpa-markdown-mode]: https://packages.debian.org/sid/lisp/elpa-markdown-mode
130 ;; [elpa-ubuntu]: http://packages.ubuntu.com/search?keywords=elpa-markdown-mode
131 ;; [emacs-goodies-el]: http://packages.debian.org/emacs-goodies-el
132 ;; [emacs-goodies-el-ubuntu]: http://packages.ubuntu.com/search?keywords=emacs-goodies-el
133 ;; [emacs-goodies]: https://apps.fedoraproject.org/packages/emacs-goodies
134 ;; [textproc/markdown-mode]: http://pkgsrc.se/textproc/markdown-mode
135 ;; [macports-package]: https://trac.macports.org/browser/trunk/dports/editors/markdown-mode.el/Portfile
136 ;; [macports-ticket]: http://trac.macports.org/ticket/35716
137 ;; [freebsd-port]: http://svnweb.freebsd.org/ports/head/textproc/markdown-mode.el
141 ;; `markdown-mode' depends on `cl-lib', which has been bundled with
142 ;; GNU Emacs since 24.3. Users of GNU Emacs 24.1 and 24.2 can install
143 ;; `cl-lib' with `package.el'.
147 ;; Keybindings are grouped by prefixes based on their function. For
148 ;; example, the commands for inserting links are grouped under `C-c
149 ;; C-a`, where the `C-a` is a mnemonic for the HTML `<a>` tag. In
150 ;; other cases, the connection to HTML is not direct. For example,
151 ;; commands dealing with headings begin with `C-c C-t` (mnemonic:
152 ;; titling). The primary commands in each group will are described
153 ;; below. You can obtain a list of all keybindings by pressing `C-c
154 ;; C-h`. Movement and shifting commands tend to be associated with
155 ;; paired delimiters such as `M-{` and `M-}` or `C-c <` and `C-c >`.
156 ;; Outline navigation keybindings the same as in `org-mode'. Finally,
157 ;; commands for running Markdown or doing maintenance on an open file
158 ;; are grouped under the `C-c C-c` prefix. The most commonly used
159 ;; commands are described below. You can obtain a list of all
160 ;; keybindings by pressing `C-c C-h`.
162 ;; * Hyperlinks: `C-c C-a`
164 ;; In this group, `C-c C-a l` inserts an inline link of the form
165 ;; `[text](url)`. The link text is determined as follows. First,
166 ;; if there is an active region (i.e., when transient mark mode is
167 ;; on and the mark is active), use it as the link text. Second,
168 ;; if the point is at a word, use that word as the link text. In
169 ;; these two cases, the original text will be replaced with the
170 ;; link and point will be left at the position for inserting a
171 ;; URL. Otherwise, insert empty link markup and place the point
172 ;; for inserting the link text.
174 ;; `C-c C-a L` inserts a reference link of the form `[text][label]`
175 ;; and, optionally, a corresponding reference label definition.
176 ;; The link text is determined in the same way as with an inline
177 ;; link (using the region, when active, or the word at the point),
178 ;; but instead of inserting empty markup as a last resort, the
179 ;; link text will be read from the minibuffer. The reference
180 ;; label will be read from the minibuffer in both cases, with
181 ;; completion from the set of currently defined references. To
182 ;; create an implicit reference link, press `RET` to accept the
183 ;; default, an empty label. If the entered referenced label is
184 ;; not defined, additionally prompt for the URL and (optional)
185 ;; title. If a URL is provided, a reference definition will be
186 ;; inserted in accordance with `markdown-reference-location'.
187 ;; If a title is given, it will be added to the end of the
188 ;; reference definition and will be used to populate the title
189 ;; attribute when converted to XHTML.
191 ;; `C-c C-a u` inserts a bare url, delimited by angle brackets. When
192 ;; there is an active region, the text in the region is used as the
193 ;; URL. If the point is at a URL, that url is used. Otherwise,
194 ;; insert angle brackets and position the point in between them
195 ;; for inserting the URL.
197 ;; `C-c C-a f` inserts a footnote marker at the point, inserts a
198 ;; footnote definition below, and positions the point for
199 ;; inserting the footnote text. Note that footnotes are an
200 ;; extension to Markdown and are not supported by all processors.
202 ;; `C-c C-a w` behaves much like the inline link insertion command
203 ;; and inserts a wiki link of the form `[[WikiLink]]`. If there
204 ;; is an active region, use the region as the link text. If the
205 ;; point is at a word, use the word as the link text. If there is
206 ;; no active region and the point is not at word, simply insert
207 ;; link markup. Note that wiki links are an extension to Markdown
208 ;; and are not supported by all processors.
210 ;; * Images: `C-c C-i`
212 ;; `C-c C-i i` inserts markup for an inline image, using the
213 ;; active region or the word at point, if any, as the alt text.
214 ;; `C-c C-i I` behaves similarly and inserts a reference-style
217 ;; Local images associated with image links may be displayed
218 ;; inline in the buffer by pressing `C-c C-i C-t`
219 ;; (`markdown-toggle-inline-images'). This is a toggle command, so
220 ;; pressing this once again will remove inline images.
222 ;; * Styles: `C-c C-s`
224 ;; `C-c C-s e` inserts markup to make a region or word italic (`e`
225 ;; for `<em>` or emphasis). If there is an active region, make
226 ;; the region italic. If the point is at a non-italic word, make
227 ;; the word italic. If the point is at an italic word or phrase,
228 ;; remove the italic markup. Otherwise, simply insert italic
229 ;; delimiters and place the cursor in between them. Similarly,
230 ;; use `C-c C-s s` for bold (`<strong>`), `C-c C-s c` for
231 ;; inline code (`<code>`), and `C-c C-s k` for inserting `<kbd>`
234 ;; `C-c C-s b` inserts a blockquote using the active region, if any,
235 ;; or starts a new blockquote. `C-c C-s C-b` is a variation which
236 ;; always operates on the region, regardless of whether it is
237 ;; active or not. The appropriate amount of indentation, if any,
238 ;; is calculated automatically given the surrounding context, but
239 ;; may be adjusted later using the region indentation commands.
241 ;; `C-c C-s p` behaves similarly for inserting preformatted code
242 ;; blocks, with `C-c C-s C-p` being the region-only counterpart.
244 ;; * Headings: `C-c C-t`
246 ;; All heading insertion commands use the text in the active
247 ;; region, if any, as the heading text. Otherwise, if the current
248 ;; line is not blank, they use the text on the current line.
249 ;; Finally, the setext commands will prompt for heading text if
250 ;; there is no active region and the current line is blank.
252 ;; `C-c C-t h` inserts a heading with automatically chosen type and
253 ;; level (both determined by the previous heading). `C-c C-t H`
254 ;; behaves similarly, but uses setext (underlined) headings when
255 ;; possible, still calculating the level automatically.
256 ;; In cases where the automatically-determined level is not what
257 ;; you intended, the level can be quickly promoted or demoted
258 ;; (as described below). Alternatively, a `C-u` prefix can be
259 ;; given to insert a heading promoted by one level or a `C-u C-u`
260 ;; prefix can be given to insert a heading demoted by one level.
262 ;; To insert a heading of a specific level and type, use `C-c C-t 1`
263 ;; through `C-c C-t 6` for atx (hash mark) headings and `C-c C-t !` or
264 ;; `C-c C-t @` for setext headings of level one or two, respectively.
265 ;; Note that `!` is `S-1` and `@` is `S-2`.
267 ;; If the point is at a heading, these commands will replace the
268 ;; existing markup in order to update the level and/or type of the
269 ;; heading. To remove the markup of the heading at the point,
270 ;; press `C-c C-k` to kill the heading and press `C-y` to yank the
271 ;; heading text back into the buffer.
273 ;; * Horizontal Rules: `C-c -`
275 ;; `C-c -` inserts a horizontal rule. By default, insert the
276 ;; first string in the list `markdown-hr-strings' (the most
277 ;; prominent rule). With a `C-u` prefix, insert the last string.
278 ;; With a numeric prefix `N`, insert the string in position `N`
279 ;; (counting from 1).
281 ;; * Markdown and Maintenance Commands: `C-c C-c`
283 ;; *Compile:* `C-c C-c m` will run Markdown on the current buffer
284 ;; and show the output in another buffer. *Preview*: `C-c C-c p`
285 ;; runs Markdown on the current buffer and previews, stores the
286 ;; output in a temporary file, and displays the file in a browser.
287 ;; *Export:* `C-c C-c e` will run Markdown on the current buffer
288 ;; and save the result in the file `basename.html`, where
289 ;; `basename` is the name of the Markdown file with the extension
290 ;; removed. *Export and View:* press `C-c C-c v` to export the
291 ;; file and view it in a browser. *Open:* `C-c C-c o` will open
292 ;; the Markdown source file directly using `markdown-open-command'.
293 ;; *Live Export*: Press `C-c C-c l` to turn on
294 ;; `markdown-live-preview-mode' to view the exported output
295 ;; side-by-side with the source Markdown. **For all export commands,
296 ;; the output file will be overwritten without notice.**
297 ;; `markdown-live-preview-window-function' can be customized to open
298 ;; in a browser other than `eww'. If you want to force the
299 ;; preview window to appear at the bottom or right, you can
300 ;; customize `markdown-split-window-direction`.
304 ;; - `C-c C-c m`: `markdown-command' > `*markdown-output*` buffer.
305 ;; - `C-c C-c p`: `markdown-command' > temporary file > browser.
306 ;; - `C-c C-c e`: `markdown-command' > `basename.html`.
307 ;; - `C-c C-c v`: `markdown-command' > `basename.html` > browser.
308 ;; - `C-c C-c w`: `markdown-command' > kill ring.
309 ;; - `C-c C-c o`: `markdown-open-command'.
310 ;; - `C-c C-c l`: `markdown-live-preview-mode' > `*eww*` buffer.
312 ;; `C-c C-c c` will check for undefined references. If there are
313 ;; any, a small buffer will open with a list of undefined
314 ;; references and the line numbers on which they appear. In Emacs
315 ;; 22 and greater, selecting a reference from this list and
316 ;; pressing `RET` will insert an empty reference definition at the
317 ;; end of the buffer. Similarly, selecting the line number will
318 ;; jump to the corresponding line.
320 ;; `C-c C-c n` renumbers any ordered lists in the buffer that are
323 ;; `C-c C-c ]` completes all headings and normalizes all horizontal
324 ;; rules in the buffer.
326 ;; * Following Links: `C-c C-o`
328 ;; Press `C-c C-o` when the point is on an inline or reference
329 ;; link to open the URL in a browser. When the point is at a
330 ;; wiki link, open it in another buffer (in the current window,
331 ;; or in the other window with the `C-u` prefix). Use `M-p` and
332 ;; `M-n` to quickly jump to the previous or next link of any type.
334 ;; * Jumping: `C-c C-l`
336 ;; Use `C-c C-l` to jump from the object at point to its counterpart
337 ;; elsewhere in the text, when possible. Jumps between reference
338 ;; links and definitions; between footnote markers and footnote
339 ;; text. If more than one link uses the same reference name, a
340 ;; new buffer will be created containing clickable buttons for jumping
341 ;; to each link. You may press `TAB` or `S-TAB` to jump between
342 ;; buttons in this window.
344 ;; * Promotion and Demotion: `C-c C--` and `C-c C-=`
346 ;; Headings, horizontal rules, and list items can be promoted and
347 ;; demoted, as well as bold and italic text. For headings,
348 ;; "promotion" means *decreasing* the level (i.e., moving from
349 ;; `<h2>` to `<h1>`) while "demotion" means *increasing* the
350 ;; level. For horizontal rules, promotion and demotion means
351 ;; moving backward or forward through the list of rule strings in
352 ;; `markdown-hr-strings'. For bold and italic text, promotion and
353 ;; demotion means changing the markup from underscores to asterisks.
354 ;; Press `C-c C--` or `M-LEFT` to promote the element at the point
357 ;; To remember these commands, note that `-` is for decreasing the
358 ;; level (promoting), and `=` (on the same key as `+`) is for
359 ;; increasing the level (demoting). Similarly, the left and right
360 ;; arrow keys indicate the direction that the atx heading markup
361 ;; is moving in when promoting or demoting.
363 ;; * Completion: `C-c C-]`
365 ;; Complete markup is in normalized form, which means, for
366 ;; example, that the underline portion of a setext header is the
367 ;; same length as the heading text, or that the number of leading
368 ;; and trailing hash marks of an atx header are equal and that
369 ;; there is no extra whitespace in the header text. `C-c C-]`
370 ;; completes the markup at the point, if it is determined to be
373 ;; * Editing Lists: `M-RET`, `M-UP`, `M-DOWN`, `M-LEFT`, and `M-RIGHT`
375 ;; New list items can be inserted with `M-RET` or `C-c C-j`. This
376 ;; command determines the appropriate marker (one of the possible
377 ;; unordered list markers or the next number in sequence for an
378 ;; ordered list) and indentation level by examining nearby list
379 ;; items. If there is no list before or after the point, start a
380 ;; new list. Prefix this command by `C-u` to decrease the
381 ;; indentation by one level. Prefix this command by `C-u C-u` to
382 ;; increase the indentation by one level.
384 ;; Existing list items can be moved up or down with `M-UP` or
385 ;; `M-DOWN` and indented or exdented with `M-RIGHT` or `M-LEFT`.
387 ;; * Editing Subtrees: `M-S-UP`, `M-S-DOWN`, `M-S-LEFT`, and `M-S-RIGHT`
389 ;; Entire subtrees of ATX headings can be promoted and demoted
390 ;; with `M-S-LEFT` and `M-S-RIGHT`, which mirror the bindings
391 ;; for promotion and demotion of list items. Similarly, subtrees
392 ;; can be moved up and down with `M-S-UP` and `M-S-DOWN`.
394 ;; Please note the following "boundary" behavior for promotion and
395 ;; demotion. Any level-six headings will not be demoted further
396 ;; (i.e., they remain at level six, since Markdown and HTML define
397 ;; only six levels) and any level-one headings will promoted away
398 ;; entirely (i.e., heading markup will be removed, since a
399 ;; level-zero heading is not defined).
401 ;; * Shifting the Region: `C-c <` and `C-c >`
403 ;; Text in the region can be indented or exdented as a group using
404 ;; `C-c >` to indent to the next indentation point (calculated in
405 ;; the current context), and `C-c <` to exdent to the previous
406 ;; indentation point. These keybindings are the same as those for
407 ;; similar commands in `python-mode'.
409 ;; * Killing Elements: `C-c C-k`
411 ;; Press `C-c C-k` to kill the thing at point and add important
412 ;; text, without markup, to the kill ring. Possible things to
413 ;; kill include (roughly in order of precedece): inline code,
414 ;; headings, horizonal rules, links (add link text to kill ring),
415 ;; images (add alt text to kill ring), angle URIs, email
416 ;; addresses, bold, italics, reference definitions (add URI to
417 ;; kill ring), footnote markers and text (kill both marker and
418 ;; text, add text to kill ring), and list items.
420 ;; * Outline Navigation: `C-c C-n`, `C-c C-p`, `C-c C-f`, `C-c C-b`, and `C-c C-u`
422 ;; Navigation between headings is possible using `outline-mode'.
423 ;; Use `C-c C-n` and `C-c C-p` to move between the next and previous
424 ;; visible headings. Similarly, `C-c C-f` and `C-c C-b` move to the
425 ;; next and previous visible headings at the same level as the one
426 ;; at the point. Finally, `C-c C-u` will move up to a lower-level
427 ;; (higher precedence) visible heading.
429 ;; * Movement by Paragraph or Block: `M-{` and `M-}`
431 ;; The definition of a "paragraph" is slightly different in
432 ;; markdown-mode than, say, text-mode, because markdown-mode
433 ;; supports filling for list items and respects hard line breaks,
434 ;; both of which break paragraphs. So, markdown-mode overrides
435 ;; the usual paragraph navigation commands `M-{` and `M-}` so that
436 ;; with a `C-u` prefix, these commands jump to the beginning or
437 ;; end of an entire block of text, respectively, where "blocks"
438 ;; are separated by one or more lines.
440 ;; * Movement by Defun: `C-M-a`, `C-M-e`, and `C-M-h`
442 ;; The usual Emacs commands can be used to move by defuns
443 ;; (top-level major definitions). In markdown-mode, a defun is a
444 ;; section. As usual, `C-M-a` will move the point to the
445 ;; beginning of the current or preceding defun, `C-M-e` will move
446 ;; to the end of the current or following defun, and `C-M-h` will
447 ;; put the region around the entire defun.
449 ;; As noted, many of the commands above behave differently depending
450 ;; on whether Transient Mark mode is enabled or not. When it makes
451 ;; sense, if Transient Mark mode is on and the region is active, the
452 ;; command applies to the text in the region (e.g., `C-c C-s s` makes the
453 ;; region bold). For users who prefer to work outside of Transient
454 ;; Mark mode, since Emacs 22 it can be enabled temporarily by pressing
455 ;; `C-SPC C-SPC`. When this is not the case, many commands then
456 ;; proceed to look work with the word or line at the point.
458 ;; When applicable, commands that specifically act on the region even
459 ;; outside of Transient Mark mode have the same keybinding as their
460 ;; standard counterpart, but the letter is uppercase. For example,
461 ;; `markdown-insert-blockquote' is bound to `C-c C-s b` and only acts on
462 ;; the region in Transient Mark mode while `markdown-blockquote-region'
463 ;; is bound to `C-c C-s B` and always applies to the region (when nonempty).
465 ;; Note that these region-specific functions are useful in many
466 ;; cases where it may not be obvious. For example, yanking text from
467 ;; the kill ring sets the mark at the beginning of the yanked text
468 ;; and moves the point to the end. Therefore, the (inactive) region
469 ;; contains the yanked text. So, `C-y` followed by `C-c C-s C-b` will
470 ;; yank text and turn it into a blockquote.
472 ;; markdown-mode attempts to be flexible in how it handles
473 ;; indentation. When you press `TAB` repeatedly, the point will cycle
474 ;; through several possible indentation levels corresponding to things
475 ;; you might have in mind when you press `RET` at the end of a line or
476 ;; `TAB`. For example, you may want to start a new list item,
477 ;; continue a list item with hanging indentation, indent for a nested
478 ;; pre block, and so on. Exdention is handled similarly when backspace
479 ;; is pressed at the beginning of the non-whitespace portion of a line.
481 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
482 ;; visibility cycling for atx- or hash-style headings. There are two
483 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
484 ;; the table of contents view (headings only), outline view (top-level
485 ;; headings only), and the full document view. Pressing `TAB` while the
486 ;; point is at a heading will cycle through levels of visibility for the
487 ;; subtree: completely folded, visible children, and fully visible.
488 ;; Note that mixing hash and underline style headings will give undesired
493 ;; Although no configuration is *necessary* there are a few things
494 ;; that can be customized. The `M-x customize-mode` command
495 ;; provides an interface to all of the possible customizations:
497 ;; * `markdown-command' - the command used to run Markdown (default:
498 ;; `markdown`). This variable may be customized to pass
499 ;; command-line options to your Markdown processor of choice.
501 ;; * `markdown-command-needs-filename' - set to `t' if
502 ;; `markdown-command' does not accept standard input (default:
503 ;; `nil'). When `nil', `markdown-mode' will pass the Markdown
504 ;; content to `markdown-command' using standard input (`stdin`).
505 ;; When set to `t', `markdown-mode' will pass the name of the file
506 ;; as the final command-line argument to `markdown-command'. Note
507 ;; that in the latter case, you will only be able to run
508 ;; `markdown-command' from buffers which are visiting a file.
510 ;; * `markdown-open-command' - the command used for calling a standalone
511 ;; Markdown previewer which is capable of opening Markdown source files
512 ;; directly (default: `nil'). This command will be called
513 ;; with a single argument, the filename of the current buffer.
514 ;; A representative program is the Mac app [Marked 2][], a
515 ;; live-updating Markdown previewer which can be [called from a
516 ;; simple shell script](http://jblevins.org/log/marked-2-command).
518 ;; * `markdown-hr-strings' - list of strings to use when inserting
519 ;; horizontal rules. Different strings will not be distinguished
520 ;; when converted to HTML--they will all be converted to
521 ;; `<hr/>`--but they may add visual distinction and style to plain
522 ;; text documents. To maintain some notion of promotion and
523 ;; demotion, keep these sorted from largest to smallest.
525 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
526 ;; underscores when inserting bold text instead of two asterisks
529 ;; * `markdown-italic-underscore' - set to a non-nil value to use
530 ;; underscores when inserting italic text instead of asterisks
533 ;; * `markdown-asymmetric-header' - set to a non-nil value to use
534 ;; asymmetric header styling, placing header characters only on
535 ;; the left of headers (default: `nil').
537 ;; * `markdown-header-scaling' - set to a non-nil value to use
538 ;; a variable-pitch font for headings where the size corresponds
539 ;; to the level of the heading (default: `nil').
541 ;; * `markdown-header-scaling-values' - list of scaling values,
542 ;; relative to baseline, for headers of levels one through six,
543 ;; used when `markdown-header-scaling' is non-nil
544 ;; (default: `(list 1.8 1.4 1.2 1.0 1.0 1.0)`).
546 ;; * `markdown-list-indent-width' - depth of indentation for lists
547 ;; when inserting, promoting, and demoting list items (default: 4).
549 ;; * `markdown-indent-function' - the function to use for automatic
550 ;; indentation (default: `markdown-indent-line').
552 ;; * `markdown-indent-on-enter' - set to a non-nil value to
553 ;; automatically indent new lines and/or continue lists when the
554 ;; enter key is pressed (default: `t')
556 ;; * `markdown-enable-wiki-links' - syntax highlighting for wiki
557 ;; links (default: `nil'). Set this to a non-nil value to turn on
558 ;; wiki link support by default. Wiki link support can be toggled
559 ;; later using the function `markdown-toggle-wiki-links'."
561 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
562 ;; treat aliased wiki links like `[[link text|PageName]]`
563 ;; (default: `t'). When set to nil, they will be treated as
564 ;; `[[PageName|link text]]'.
566 ;; * `markdown-uri-types' - a list of protocol schemes (e.g., "http")
567 ;; for URIs that `markdown-mode' should highlight.
569 ;; * `markdown-enable-math' - syntax highlighting for LaTeX
570 ;; fragments (default: `nil'). Set this to `t' to turn on math
571 ;; support by default. Math support can be enabled, disabled, or
572 ;; toggled later using the function `markdown-toggle-math'."
574 ;; * `markdown-css-paths' - CSS files to link to in XHTML output
577 ;; * `markdown-content-type' - when set to a nonempty string, an
578 ;; `http-equiv` attribute will be included in the XHTML `<head>`
579 ;; block (default: `""`). If needed, the suggested values are
580 ;; `application/xhtml+xml` or `text/html`. See also:
581 ;; `markdown-coding-system'.
583 ;; * `markdown-coding-system' - used for specifying the character
584 ;; set identifier in the `http-equiv` attribute when included
585 ;; (default: `nil'). See `markdown-content-type', which must
586 ;; be set before this variable has any effect. When set to `nil',
587 ;; `buffer-file-coding-system' will be used to automatically
588 ;; determine the coding system string (falling back to
589 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
590 ;; and `iso-latin-1'.
592 ;; * `markdown-xhtml-header-content' - additional content to include
593 ;; in the XHTML `<head>` block (default: `""`).
595 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
596 ;; `markdown-mode' uses to determine whether the output of
597 ;; `markdown-command' is a standalone XHTML document or an XHTML
598 ;; fragment (default: `"^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"`). If
599 ;; this regular expression not matched in the first five lines of
600 ;; output, `markdown-mode' assumes the output is a fragment and
601 ;; adds a header and footer.
603 ;; * `markdown-link-space-sub-char' - a character to replace spaces
604 ;; when mapping wiki links to filenames (default: `"_"`).
605 ;; For example, use an underscore for compatibility with the
606 ;; Python Markdown WikiLinks extension. In `gfm-mode', this is
607 ;; set to `"-"` to conform with GitHub wiki links.
609 ;; * `markdown-reference-location' - where to insert reference
610 ;; definitions (default: `header`). The possible locations are
611 ;; the end of the document (`end`), after the current block
612 ;; (`immediately`), before the next header (`header`).
614 ;; * `markdown-footnote-location' - where to insert footnote text
615 ;; (default: `end`). The set of location options is the same as
616 ;; for `markdown-reference-location'.
618 ;; * `markdown-nested-imenu-heading-index' - Use nested imenu
619 ;; heading instead of a flat index (default: `nil'). A nested
620 ;; index may provide more natural browsing from the menu, but a
621 ;; flat list may allow for faster keyboard navigation via tab
624 ;; * `comment-auto-fill-only-comments' - variable is made
625 ;; buffer-local and set to `nil' by default. In programming
626 ;; language modes, when this variable is non-nil, only comments
627 ;; will be filled by auto-fill-mode. However, comments in
628 ;; Markdown documents are rare and the most users probably intend
629 ;; for the actual content of the document to be filled. Making
630 ;; this variable buffer-local allows `markdown-mode' to override
631 ;; the default behavior induced when the global variable is non-nil.
633 ;; * `markdown-gfm-additional-languages', - additional languages to
634 ;; make available, aside from those predefined in
635 ;; `markdown-gfm-recognized-languages', when inserting GFM code
636 ;; blocks (default: `nil`). Language strings must have be trimmed
637 ;; of whitespace and not contain any curly braces. They may be of
638 ;; arbitrary capitalization, though.
640 ;; * `markdown-gfm-use-electric-backquote' - use
641 ;; `markdown-electric-backquote' for interactive insertion of GFM
642 ;; code blocks when backquote is pressed three times (default: `t`).
644 ;; * `markdown-make-gfm-checkboxes-buttons' - Whether GitHub
645 ;; Flavored Markdown style task lists (checkboxes) should be
646 ;; turned into buttons that can be toggled with mouse-1 or RET. If
647 ;; non-nil (default), then buttons are enabled. This works in
648 ;; `markdown-mode' as well as `gfm-mode'.
650 ;; Additionally, the faces used for syntax highlighting can be modified to
651 ;; your liking by issuing `M-x customize-group RET markdown-faces`
652 ;; or by using the "Markdown Faces" link at the bottom of the mode
653 ;; customization screen.
655 ;; [Marked 2]: https://itunes.apple.com/us/app/marked-2/id890031187?mt=12&uo=4&at=11l5Vs&ct=mm
659 ;; Besides supporting the basic Markdown syntax, Markdown Mode also
660 ;; includes syntax highlighting for `[[Wiki Links]]`. This can be
661 ;; enabled by setting `markdown-enable-wiki-links' to a non-nil value.
662 ;; Wiki links may be followed by pressing `C-c C-o` when the point
663 ;; is at a wiki link. Use `M-p` and `M-n` to quickly jump to the
664 ;; previous and next links (including links of other types).
665 ;; Aliased or piped wiki links of the form `[[link text|PageName]]`
666 ;; are also supported. Since some wikis reverse these components, set
667 ;; `markdown-wiki-link-alias-first' to nil to treat them as
668 ;; `[[PageName|link text]]`. If `markdown-wiki-link-fontify-missing'
669 ;; is also non-nil, Markdown Mode will highlight wiki links with
670 ;; missing target file in a different color. By default, Markdown
671 ;; Mode only searches for target files in the current directory.
672 ;; Search in subdirectories can be enabled by setting
673 ;; `markdown-wiki-link-search-subdirectories' to a non-nil value.
674 ;; Sequential parent directory search (as in [Ikiwiki][]) can be
675 ;; enabled by setting `markdown-wiki-link-search-parent-directories'
676 ;; to a non-nil value.
678 ;; [Ikiwiki]: https://ikiwiki.info
680 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
681 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
682 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
683 ;; You can do this either by using `M-x customize-group markdown`
684 ;; or by placing the following in your `.emacs` file:
686 ;; (setq markdown-command "markdown | smartypants")
688 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
690 ;; Syntax highlighting for mathematical expressions written
691 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
692 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
693 ;; either via customize or by placing `(setq markdown-enable-math t)`
694 ;; in `.emacs`, and then restarting Emacs or calling
695 ;; `markdown-reload-extensions'.
697 ;;; GitHub Flavored Markdown (GFM):
699 ;; A [GitHub Flavored Markdown][GFM] mode, `gfm-mode', is also
700 ;; available. The GitHub implementation differs slightly from
701 ;; standard Markdown in that it supports things like different
702 ;; behavior for underscores inside of words, automatic linking of
703 ;; URLs, strikethrough text, and fenced code blocks with an optional
706 ;; The GFM-specific features above apply to `README.md` files, wiki
707 ;; pages, and other Markdown-formatted files in repositories on
708 ;; GitHub. GitHub also enables [additional features][GFM comments] for
709 ;; writing on the site (for issues, pull requests, messages, etc.)
710 ;; that are further extensions of GFM. These features include task
711 ;; lists (checkboxes), newlines corresponding to hard line breaks,
712 ;; auto-linked references to issues and commits, wiki links, and so
713 ;; on. To make matters more confusing, although task lists are not
714 ;; part of [GFM proper][GFM], [since 2014][] they are rendered (in a
715 ;; read-only fashion) in all Markdown documents in repositories on the
716 ;; site. These additional extensions are supported to varying degrees
717 ;; by `markdown-mode' and `gfm-mode' as described below.
719 ;; * **URL autolinking:** Both `markdown-mode' and `gfm-mode' support
720 ;; highlighting of URLs without angle brackets.
722 ;; * **Multiple underscores in words:** You must enable `gfm-mode' to
723 ;; toggle support for underscores inside of words. In this mode
724 ;; variable names such as `a_test_variable` will not trigger
725 ;; emphasis (italics).
727 ;; * **Fenced code blocks:** Code blocks quoted with backticks, with
728 ;; optional programming language keywords, are highlighted in
729 ;; both `markdown-mode' and `gfm-mode'. They can be inserted with
730 ;; `C-c C-s P`. If there is an active region, the text in the
731 ;; region will be placed inside the code block. You will be
732 ;; prompted for the name of the language, but may press enter to
733 ;; continue without naming a language.
735 ;; * **Strikethrough:** Strikethrough text is only supported in
736 ;; `gfm-mode' and can be inserted (and toggled) using `C-c C-s d`.
737 ;; Following the mnemonics for the other style keybindings, the
738 ;; letter `d` coincides with the HTML tag `<del>`.
740 ;; * **Task lists:** GFM task lists will be rendered as checkboxes
741 ;; (Emacs buttons) in both `markdown-mode' and `gfm-mode' when
742 ;; `markdown-make-gfm-checkboxes-buttons' is set to a non-nil value
743 ;; (and it is set to t by default). These checkboxes can be
744 ;; toggled by clicking `mouse-1`, pressing `RET` over the button,
745 ;; or by pressing `C-c C-x C-x` with the point anywhere in the task
748 ;; * **Wiki links:** Generic wiki links are supported in
749 ;; `markdown-mode', but in `gfm-mode' specifically they will be
750 ;; treated as they are on GitHub: spaces will be replaced by hyphens
751 ;; in filenames and the first letter of the filename will be
752 ;; capitalized. For example, `[[wiki link]]' will map to a file
753 ;; named `Wiki-link` with the same extension as the current file.
754 ;; If a file with this name does not exist in the current directory,
755 ;; the first match in a subdirectory, if any, will be used instead.
757 ;; * **Newlines:** Neither `markdown-mode' nor `gfm-mode' do anything
758 ;; specifically with respect to newline behavior. If you use
759 ;; `gfm-mode' mostly to write text for comments or issues on the
760 ;; GitHub site--where newlines are significant and correspond to
761 ;; hard line breaks--then you may want to enable `visual-line-mode'
762 ;; for line wrapping in buffers. You can do this with a
763 ;; `gfm-mode-hook' as follows:
765 ;; ;; Use visual-line-mode in gfm-mode
766 ;; (defun my-gfm-mode-hook ()
767 ;; (visual-line-mode 1))
768 ;; (add-hook 'gfm-mode-hook 'my-gfm-mode-hook)
770 ;; * **Preview:** GFM-specific preview can be powered by setting
771 ;; `markdown-command' to use [Docter][]. This may also be
772 ;; configured to work with [Marked 2][] for `markdown-open-command'.
774 ;; [GFM]: http://github.github.com/github-flavored-markdown/
775 ;; [GFM comments]: https://help.github.com/articles/writing-on-github/
776 ;; [since 2014]: https://github.com/blog/1825-task-lists-in-all-markdown-documents
777 ;; [Docter]: https://github.com/alampros/Docter
781 ;; markdown-mode has benefited greatly from the efforts of the many
782 ;; volunteers who have sent patches, test cases, bug reports,
783 ;; suggestions, helped with packaging, etc. Thank you for your
784 ;; contributions! See the [contributors graph][contrib] for details.
786 ;; [contrib]: https://github.com/jrblevin/markdown-mode/graphs/contributors
790 ;; markdown-mode is developed and tested primarily for compatibility
791 ;; with GNU Emacs 24.3 and later. If you find any bugs in
792 ;; markdown-mode, please construct a test case or a patch and open a
793 ;; ticket on the [GitHub issue tracker][issues].
795 ;; [issues]: https://github.com/jrblevin/markdown-mode/issues
799 ;; markdown-mode was written and is maintained by Jason Blevins. The
800 ;; first version was released on May 24, 2007.
802 ;; * 2007-05-24: [Version 1.1][]
803 ;; * 2007-05-25: [Version 1.2][]
804 ;; * 2007-06-05: [Version 1.3][]
805 ;; * 2007-06-29: [Version 1.4][]
806 ;; * 2007-10-11: [Version 1.5][]
807 ;; * 2008-06-04: [Version 1.6][]
808 ;; * 2009-10-01: [Version 1.7][]
809 ;; * 2011-08-12: [Version 1.8][]
810 ;; * 2011-08-15: [Version 1.8.1][]
811 ;; * 2013-01-25: [Version 1.9][]
812 ;; * 2013-03-24: [Version 2.0][]
813 ;; * 2016-01-09: [Version 2.1][]
815 ;; [Version 1.1]: http://jblevins.org/projects/markdown-mode/rev-1-1
816 ;; [Version 1.2]: http://jblevins.org/projects/markdown-mode/rev-1-2
817 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
818 ;; [Version 1.4]: http://jblevins.org/projects/markdown-mode/rev-1-4
819 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
820 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
821 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
822 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
823 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
824 ;; [Version 1.9]: http://jblevins.org/projects/markdown-mode/rev-1-9
825 ;; [Version 2.0]: http://jblevins.org/projects/markdown-mode/rev-2-0
826 ;; [Version 2.1]: http://jblevins.org/projects/markdown-mode/rev-2-1
837 (defvar jit-lock-start
)
838 (defvar jit-lock-end
)
840 (declare-function eww-open-file
"eww")
841 (declare-function url-path-and-query
"url-parse")
844 ;;; Constants =================================================================
846 (defconst markdown-mode-version
"2.1"
847 "Markdown mode version number.")
849 (defconst markdown-output-buffer-name
"*markdown-output*"
850 "Name of temporary buffer for markdown command output.")
853 ;;; Global Variables ==========================================================
855 (defvar markdown-reference-label-history nil
856 "History of used reference labels.")
858 (defvar markdown-live-preview-mode nil
859 "Sentinel variable for command `markdown-live-preview-mode'.")
861 (defvar markdown-gfm-language-history nil
862 "History list of languages used in the current buffer in GFM code blocks.")
865 ;;; Customizable Variables ====================================================
867 (defvar markdown-mode-hook nil
868 "Hook run when entering Markdown mode.")
870 (defvar markdown-before-export-hook nil
871 "Hook run before running Markdown to export XHTML output.
872 The hook may modify the buffer, which will be restored to it's
873 original state after exporting is complete.")
875 (defvar markdown-after-export-hook nil
876 "Hook run after XHTML output has been saved.
877 Any changes to the output buffer made by this hook will be saved.")
879 (defgroup markdown nil
880 "Major mode for editing text files in Markdown format."
883 :link
'(url-link "http://jblevins.org/projects/markdown-mode/"))
885 (defcustom markdown-command
"markdown"
886 "Command to run markdown."
890 (defcustom markdown-command-needs-filename nil
891 "Set to non-nil if `markdown-command' does not accept input from stdin.
892 Instead, it will be passed a filename as the final command line
893 option. As a result, you will only be able to run Markdown from
894 buffers which are visiting a file."
898 (defcustom markdown-open-command nil
899 "Command used for opening Markdown files directly.
900 For example, a standalone Markdown previewer. This command will
901 be called with a single argument: the filename of the current
906 (defcustom markdown-hr-strings
907 '("-------------------------------------------------------------------------------"
908 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
909 "---------------------------------------"
910 "* * * * * * * * * * * * * * * * * * * *"
913 "Strings to use when inserting horizontal rules.
914 The first string in the list will be the default when inserting a
915 horizontal rule. Strings should be listed in decreasing order of
916 prominence (as in headings from level one to six) for use with
917 promotion and demotion functions."
921 (defcustom markdown-bold-underscore nil
922 "Use two underscores when inserting bold text instead of two asterisks."
926 (defcustom markdown-italic-underscore nil
927 "Use underscores when inserting italic text instead of asterisks."
931 (defcustom markdown-asymmetric-header nil
932 "Determines if atx header style will be asymmetric.
933 Set to a non-nil value to use asymmetric header styling, placing
934 header markup only at the beginning of the line. By default,
935 balanced markup will be inserted at the beginning and end of the
936 line around the header title."
940 (defcustom markdown-indent-function
'markdown-indent-line
941 "Function to use to indent."
945 (defcustom markdown-indent-on-enter t
946 "Indent new lines and continue lists when enter is pressed.
947 When this variable is set to t, pressing RET will call
948 `newline-and-indent' and will continue a list. When set to nil,
949 define RET to call `newline' as usual. In the latter case, you
950 can still use auto-indentation by pressing
951 \\[newline-and-indent] or continue lists with
952 \\[markdown-insert-list-item]."
956 (defcustom markdown-enable-wiki-links nil
957 "Syntax highlighting for wiki links.
958 Set this to a non-nil value to turn on wiki link support by default.
959 Support can be toggled later using the `markdown-toggle-wiki-links'
960 function or \\[markdown-toggle-wiki-links]."
965 (defcustom markdown-wiki-link-alias-first t
966 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
967 Otherwise, they will be treated as [[PageName|alias text]]."
972 (defcustom markdown-wiki-link-search-subdirectories nil
973 "When non-nil, search for wiki link targets in subdirectories.
974 This is the default search behavior for GitHub and is
975 automatically set to t in `gfm-mode'."
980 (defcustom markdown-wiki-link-search-parent-directories nil
981 "When non-nil, search for wiki link targets in parent directories.
982 This is the default search behavior of Ikiwiki."
987 (defcustom markdown-wiki-link-fontify-missing nil
988 "When non-nil, change wiki link face according to existence of target files.
989 This is expensive because it requires checking for the file each time the buffer
990 changes or the user switches windows. It is disabled by default because it may
991 cause lag when typing on slower machines."
996 (defcustom markdown-uri-types
997 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
998 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
999 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
1000 "Link types for syntax highlighting of URIs."
1004 (defcustom markdown-enable-math nil
1005 "Syntax highlighting for inline LaTeX and itex expressions.
1006 Set this to a non-nil value to turn on math support by default.
1007 Math support can be enabled, disabled, or toggled later using
1008 `markdown-toggle-math' or \\[markdown-toggle-math]."
1013 (defcustom markdown-css-paths nil
1014 "URL of CSS file to link to in the output XHTML."
1018 (defcustom markdown-content-type
""
1019 "Content type string for the http-equiv header in XHTML output.
1020 When set to a non-empty string, insert the http-equiv attribute.
1021 Otherwise, this attribute is omitted."
1025 (defcustom markdown-coding-system nil
1026 "Character set string for the http-equiv header in XHTML output.
1027 Defaults to `buffer-file-coding-system' (and falling back to
1028 `iso-8859-1' when not available). Common settings are `utf-8'
1029 and `iso-latin-1'. Use `list-coding-systems' for more choices."
1031 :type
'coding-system
)
1033 (defcustom markdown-xhtml-header-content
""
1034 "Additional content to include in the XHTML <head> block."
1038 (defcustom markdown-xhtml-standalone-regexp
1039 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
1040 "Regexp indicating whether `markdown-command' output is standalone XHTML."
1044 (defcustom markdown-link-space-sub-char
"_"
1045 "Character to use instead of spaces when mapping wiki links to filenames."
1049 (defcustom markdown-reference-location
'header
1050 "Position where new reference definitions are inserted in the document."
1052 :type
'(choice (const :tag
"At the end of the document" end
)
1053 (const :tag
"Immediately after the current block" immediately
)
1054 (const :tag
"Before next header" header
)))
1056 (defcustom markdown-footnote-location
'end
1057 "Position where new footnotes are inserted in the document."
1059 :type
'(choice (const :tag
"At the end of the document" end
)
1060 (const :tag
"Immediately after the current block" immediately
)
1061 (const :tag
"Before next header" header
)))
1063 (defcustom markdown-unordered-list-item-prefix
" * "
1064 "String inserted before unordered list items."
1068 (defcustom markdown-nested-imenu-heading-index nil
1069 "Use nested or flat imenu heading index.
1070 A nested index may provide more natural browsing from the menu,
1071 but a flat list may allow for faster keyboard navigation via tab
1076 (defcustom markdown-make-gfm-checkboxes-buttons t
1077 "When non-nil, make GFM checkboxes into buttons."
1081 (defcustom markdown-use-pandoc-style-yaml-metadata nil
1082 "When non-nil, allow yaml metadata anywhere in the document."
1086 (defcustom markdown-split-window-direction
'any
1087 "Preference for splitting windows for static and live preview.
1088 The default value is 'any, which instructs Emacs to use
1089 `split-window-sensibly' to automatically choose how to split
1090 windows based on the values of `split-width-threshold' and
1091 `split-height-threshold' and the available windows. To force
1092 vertically split (left and right) windows, set this to 'vertical
1093 or 'right. To force horizontally split (top and bottom) windows,
1094 set this to 'horizontal or 'below."
1098 (defcustom markdown-live-preview-window-function
1099 'markdown-live-preview-window-eww
1100 "Function to display preview of Markdown output within Emacs.
1101 Function must update the buffer containing the preview and return
1106 (defcustom markdown-live-preview-delete-export
'delete-on-destroy
1107 "Delete exported html file when using `markdown-live-preview-export'.
1108 If set to 'delete-on-export, delete on every export. When set to
1109 'delete-on-destroy delete when quitting from command
1110 `markdown-live-preview-mode'. Never delete if set to nil."
1114 (defcustom markdown-list-indent-width
4
1115 "Depth of indentation for markdown lists.
1116 Used in `markdown-demote-list-item' and
1117 `markdown-promote-list-item'."
1121 (defcustom markdown-gfm-additional-languages nil
1122 "Extra languages made available when inserting GFM code blocks.
1123 Language strings must have be trimmed of whitespace and not
1124 contain any curly braces. They may be of arbitrary
1125 capitalization, though."
1127 :type
'(repeat (string :validate markdown-validate-language-string
)))
1129 (defcustom markdown-gfm-use-electric-backquote t
1130 "Use `markdown-electric-backquote' when backquote is hit three times."
1134 (defcustom markdown-gfm-downcase-languages t
1135 "If non-nil, downcase suggested languages.
1136 This applies to insertions done with
1137 `markdown-electric-backquote'."
1142 ;;; Regular Expressions =======================================================
1144 (defconst markdown-regex-comment-start
1146 "Regular expression matches HTML comment opening.")
1148 (defconst markdown-regex-comment-end
1150 "Regular expression matches HTML comment closing.")
1152 (defconst markdown-regex-link-inline
1153 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)\\((\\)\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?\\()\\)"
1154 "Regular expression for a [text](file) or an image link ![text](file).
1155 Group 1 matches the leading exclamation point (optional).
1156 Group 2 matches the opening square bracket.
1157 Group 3 matches the text inside the square brackets.
1158 Group 4 matches the closing square bracket.
1159 Group 5 matches the opening parenthesis.
1160 Group 6 matches the URL.
1161 Group 7 matches the title (optional).
1162 Group 8 matches the closing parenthesis.")
1164 (defconst markdown-regex-link-reference
1165 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)[ ]?\\(\\[\\)\\([^]]*?\\)\\(\\]\\)"
1166 "Regular expression for a reference link [text][id].
1167 Group 1 matches the leading exclamation point (optional).
1168 Group 2 matches the opening square bracket for the link text.
1169 Group 3 matches the text inside the square brackets.
1170 Group 4 matches the closing square bracket for the link text.
1171 Group 5 matches the opening square bracket for the reference label.
1172 Group 6 matches the reference label.
1173 Group 7 matches the closing square bracket for the reference label.")
1175 (defconst markdown-regex-reference-definition
1176 "^ \\{0,3\\}\\(\\[\\)\\([^]\n]+?\\)\\(\\]\\)\\(:\\)\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
1177 "Regular expression for a reference definition.
1178 Group 1 matches the opening square bracket.
1179 Group 2 matches the reference label.
1180 Group 3 matches the closing square bracket.
1181 Group 4 matches the colon.
1182 Group 5 matches the URL.
1183 Group 6 matches the title attribute (optional).")
1185 (defconst markdown-regex-footnote
1186 "\\(\\[\\^\\)\\(.+?\\)\\(\\]\\)"
1187 "Regular expression for a footnote marker [^fn].
1188 Group 1 matches the opening square bracket and carat.
1189 Group 2 matches only the label, without the surrounding markup.
1190 Group 3 matches the closing square bracket.")
1192 (defconst markdown-regex-header
1193 "^\\(?:\\([^\r\n\t -].*\\)\n\\(?:\\(=+\\)\\|\\(-+\\)\\)\\|\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)\\)$"
1194 "Regexp identifying Markdown headings.
1195 Group 1 matches the text of a setext heading.
1196 Group 2 matches the underline of a level-1 setext heading.
1197 Group 3 matches the underline of a level-2 setext heading.
1198 Group 4 matches the opening hash marks of an atx heading.
1199 Group 5 matches the text, without surrounding whitespace, of an atx heading.
1200 Group 6 matches the closing hash marks of an atx heading.")
1202 (defconst markdown-regex-header-setext
1203 "^\\([^\r\n\t -].*\\)\n\\(=+\\|-+\\)$"
1204 "Regular expression for generic setext-style (underline) headers.")
1206 (defconst markdown-regex-header-atx
1207 "^\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1208 "Regular expression for generic atx-style (hash mark) headers.")
1210 (defconst markdown-regex-hr
1211 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1212 "Regular expression for matching Markdown horizontal rules.")
1214 (defconst markdown-regex-code
1215 "\\(?:\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(?:.\\|\n[^\n]\\)*?[^`]\\)\\(\\2\\)\\)\\(?:[^`]\\|\\'\\)"
1216 "Regular expression for matching inline code fragments.
1218 Group 1 matches the entire code fragment including the backticks.
1219 Group 2 matches the opening backticks.
1220 Group 3 matches the code fragment itself, without backticks.
1221 Group 4 matches the closing backticks.
1223 The leading, unnumbered group ensures that the leading backquote
1224 character is not escaped.
1225 The last group, also unnumbered, requires that the character
1226 following the code fragment is not a backquote.
1227 Note that \\(?:.\\|\n[^\n]\\) matches any character, including newlines,
1228 but not two newlines in a row.")
1230 (defconst markdown-regex-kbd
1231 "\\(<kbd>\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(</kbd>\\)"
1232 "Regular expression for matching <kbd> tags.
1233 Groups 1 and 3 match the opening and closing tags.
1234 Group 2 matches the key sequence.")
1236 (defconst markdown-regex-gfm-code-block-open
1237 "^[[:blank:]]*\\(```\\)[[:blank:]]*\\({\\)?[[:blank:]]*\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?[[:blank:]]*\\(}\\)?[[:blank:]]*$"
1238 "Regular expression matching opening of GFM code blocks.
1239 Group 1 matches the opening three backticks.
1240 Group 2 matches the opening brace (optional).
1241 Group 3 matches the language identifier (optional).
1242 Group 4 matches the info string (optional).
1243 Group 5 matches the closing brace (optional).
1244 Groups need to agree with `markdown-regex-tilde-fence-begin'.")
1246 (defconst markdown-regex-gfm-code-block-close
1247 "^[[:blank:]]*\\(```\\)\\s *?$"
1248 "Regular expression matching closing of GFM code blocks.
1249 Group 1 matches the closing three backticks.")
1251 (defconst markdown-regex-pre
1253 "Regular expression for matching preformatted text sections.")
1255 (defconst markdown-regex-list
1256 "^\\([ \t]*\\)\\([0-9#]+\\.\\|[\\*\\+:-]\\)\\([ \t]+\\)"
1257 "Regular expression for matching list items.")
1259 (defconst markdown-regex-bold
1260 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1261 "Regular expression for matching bold text.
1262 Group 1 matches the character before the opening asterisk or
1263 underscore, if any, ensuring that it is not a backslash escape.
1264 Group 2 matches the entire expression, including delimiters.
1265 Groups 3 and 5 matches the opening and closing delimiters.
1266 Group 4 matches the text inside the delimiters.")
1268 (defconst markdown-regex-italic
1269 "\\(?:^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1270 "Regular expression for matching italic text.
1271 The leading unnumbered matches the character before the opening
1272 asterisk or underscore, if any, ensuring that it is not a
1274 Group 1 matches the entire expression, including delimiters.
1275 Groups 2 and 4 matches the opening and closing delimiters.
1276 Group 3 matches the text inside the delimiters.")
1278 (defconst markdown-regex-strike-through
1279 "\\(^\\|[^\\]\\)\\(\\(~~\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(~~\\)\\)"
1280 "Regular expression for matching strike-through text.
1281 Group 1 matches the character before the opening tilde, if any,
1282 ensuring that it is not a backslash escape.
1283 Group 2 matches the entire expression, including delimiters.
1284 Groups 3 and 5 matches the opening and closing delimiters.
1285 Group 4 matches the text inside the delimiters.")
1287 (defconst markdown-regex-gfm-italic
1288 "\\(?:^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\2\\|[^ ]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1289 "Regular expression for matching italic text in GitHub Flavored Markdown.
1290 Underscores in words are not treated as special.
1291 Group 1 matches the entire expression, including delimiters.
1292 Groups 2 and 4 matches the opening and closing delimiters.
1293 Group 3 matches the text inside the delimiters.")
1295 (defconst markdown-regex-blockquote
1296 "^[ \t]*\\(>\\)\\(.*\\)$"
1297 "Regular expression for matching blockquote lines.
1298 Group 1 matches the leading angle bracket.
1299 Group 2 matches the text.")
1301 (defconst markdown-regex-line-break
1302 "[^ \n\t][ \t]*\\( \\)$"
1303 "Regular expression for matching line breaks.")
1305 (defconst markdown-regex-wiki-link
1306 "\\(?:^\\|[^\\]\\)\\(\\(\\[\\[\\)\\([^]|]+\\)\\(?:\\(|\\)\\([^]]+\\)\\)?\\(\\]\\]\\)\\)"
1307 "Regular expression for matching wiki links.
1308 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1309 wiki links of the form [[PageName|link text]].
1310 The meanings of the first and second components depend
1311 on the value of `markdown-wiki-link-alias-first'.
1313 Group 1 matches the entire link.
1314 Group 2 matches the opening square brackets.
1315 Group 3 matches the first component of the wiki link.
1316 Group 4 matches the pipe separator, when present.
1317 Group 5 matches the second component of the wiki link, when present.
1318 Group 6 matches the closing square brackets.")
1320 (defconst markdown-regex-uri
1321 (concat (regexp-opt markdown-uri-types
) ":[^]\t\n\r<>,;() ]+")
1322 "Regular expression for matching inline URIs.")
1324 (defconst markdown-regex-angle-uri
1325 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types
) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1326 "Regular expression for matching inline URIs in angle brackets.")
1328 (defconst markdown-regex-email
1329 "<\\(\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+\\)>"
1330 "Regular expression for matching inline email addresses.")
1332 (defsubst markdown-make-regex-link-generic
()
1333 "Make regular expression for matching any recognized link."
1334 (concat "\\(?:" markdown-regex-link-inline
1335 (when markdown-enable-wiki-links
1336 (concat "\\|" markdown-regex-wiki-link
))
1337 "\\|" markdown-regex-link-reference
1338 "\\|" markdown-regex-angle-uri
"\\)"))
1340 (defconst markdown-regex-gfm-checkbox
1341 " \\(\\[[ xX]\\]\\) "
1342 "Regular expression for matching GFM checkboxes.
1343 Group 1 matches the text to become a button.")
1345 (defconst markdown-regex-block-separator
1346 "\\(\\`\\|\\(\n[ \t]*\n\\)[^\n \t]\\)"
1347 "Regular expression for matching block boundaries.")
1349 (defconst markdown-regex-math-inline-single
1350 "\\(?:^\\|[^\\]\\)\\(\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\)"
1351 "Regular expression for itex $..$ math mode expressions.
1352 Groups 1 and 3 match the opening and closing dollar signs.
1353 Group 3 matches the mathematical expression contained within.")
1355 (defconst markdown-regex-math-inline-double
1356 "\\(?:^\\|[^\\]\\)\\(\\$\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\$\\)"
1357 "Regular expression for itex $$..$$ math mode expressions.
1358 Groups 1 and 3 match opening and closing dollar signs.
1359 Group 3 matches the mathematical expression contained within.")
1361 (defconst markdown-regex-math-display
1362 "^\\(\\\\\\[\\)\\(\\(?:.\\|\n\\)*?\\)?\\(\\\\\\]\\)$"
1363 "Regular expression for itex \[..\] display mode expressions.
1364 Groups 1 and 3 match the opening and closing delimiters.
1365 Group 2 matches the mathematical expression contained within.")
1367 (defsubst markdown-make-tilde-fence-regex
(num-tildes &optional end-of-line
)
1368 "Return regexp matching a tilde code fence at least NUM-TILDES long.
1369 END-OF-LINE is the regexp construct to indicate end of line; $ if
1371 (format "%s%d%s%s" "^[[:blank:]]*\\([~]\\{" num-tildes
",\\}\\)"
1372 (or end-of-line
"$")))
1374 (defconst markdown-regex-tilde-fence-begin
1375 (markdown-make-tilde-fence-regex
1376 3 "[[:blank:]]*\\({\\)?[[:blank:]]*\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?[[:blank:]]*\\(}\\)?[[:blank:]]*$")
1377 "Regular expression for matching tilde-fenced code blocks.
1378 Group 1 matches the opening tildes.
1379 Group 2 matches the opening brace (optional).
1380 Group 3 matches the language identifier (optional).
1381 Group 4 matches the info string (optional).
1382 Group 5 matches the closing brace (optional).
1383 Groups need to agree with `markdown-regex-gfm-code-block-open'.")
1385 (defconst markdown-regex-declarative-metadata
1386 "^\\([[:alpha:]][[:alpha:] _-]*?\\)\\([:=][ \t]*\\)\\(.*\\)$"
1387 "Regular expression for matching declarative metadata statements.
1388 This matches MultiMarkdown metadata as well as YAML and TOML
1389 assignments such as the following:
1397 (defconst markdown-regex-pandoc-metadata
1398 "^\\(%\\)\\([ \t]*\\)\\(.*\\(?:\n[ \t]+.*\\)*\\)"
1399 "Regular expression for matching Pandoc metadata.")
1401 (defconst markdown-regex-yaml-metadata-border
1403 "Regular expression for matching yaml metadata.")
1405 (defconst markdown-regex-yaml-pandoc-metadata-end-border
1406 "^\\(\\.\\{3\\}\\|\\-\\{3\\}\\)$"
1407 "Regular expression for matching yaml metadata end borders.")
1409 (defsubst markdown-get-yaml-metadata-start-border
()
1410 "Return yaml metadata start border depending upon whether Pandoc is used."
1412 (if markdown-use-pandoc-style-yaml-metadata
"^" "\\`")
1413 markdown-regex-yaml-metadata-border
))
1415 (defsubst markdown-get-yaml-metadata-end-border
(_)
1416 "Return yaml metadata end border depending upon whether Pandoc is used."
1417 (if markdown-use-pandoc-style-yaml-metadata
1418 markdown-regex-yaml-pandoc-metadata-end-border
1419 markdown-regex-yaml-metadata-border
))
1422 ;;; Syntax ====================================================================
1424 (defun markdown-syntax-propertize-extend-region (start end
)
1425 "Extend START to END region to include an entire block of text.
1426 This helps improve syntax analysis for block constructs.
1427 Returns a cons (NEW-START . NEW-END) or nil if no adjustment should be made.
1428 Function is called repeatedly until it returns nil. For details, see
1429 `syntax-propertize-extend-region-functions'."
1432 (let* ((new-start (progn (goto-char start
)
1433 (if (re-search-backward
1434 markdown-regex-block-separator nil t
)
1435 (min start
(match-end 0))
1437 (new-end (progn (goto-char end
)
1438 (if (re-search-forward
1439 markdown-regex-block-separator nil t
)
1440 (max end
(match-beginning 0))
1442 (code-match (markdown-code-block-at-pos new-start
))
1443 (new-start (or (and code-match
(cl-first code-match
)) new-start
))
1444 (code-match (markdown-code-block-at-pos end
))
1445 (new-end (or (and code-match
(cl-second code-match
)) new-end
)))
1446 (unless (and (eq new-start start
) (eq new-end end
))
1447 (cons new-start
(min new-end
(point-max))))))))
1449 (defun markdown-font-lock-extend-region-function (start end _
)
1450 "Used in `jit-lock-after-change-extend-region-functions'.
1451 Delegates to `markdown-syntax-propertize-extend-region'. START
1452 and END are the previous region to refontify."
1453 (let ((res (markdown-syntax-propertize-extend-region start end
)))
1455 (setq jit-lock-start
(car res
)
1456 jit-lock-end
(cdr res
)))))
1458 (defun markdown-syntax-propertize-pre-blocks (start end
)
1459 "Match preformatted text blocks from START to END."
1462 (let ((levels (markdown-calculate-list-levels))
1463 indent pre-regexp close-regexp open close
)
1464 (while (and (< (point) end
) (not close
))
1465 ;; Search for a region with sufficient indentation
1468 (setq indent
(1+ (length levels
))))
1469 (setq pre-regexp
(format "^\\( \\|\t\\)\\{%d\\}" indent
))
1470 (setq close-regexp
(format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent
)))
1473 ;; If not at the beginning of a line, move forward
1474 ((not (bolp)) (forward-line))
1475 ;; Move past blank lines
1476 ((markdown-cur-line-blank-p) (forward-line))
1477 ;; At headers and horizontal rules, reset levels
1478 ((markdown-new-baseline-p) (forward-line) (setq levels nil
))
1479 ;; If the current line has sufficient indentation, mark out pre block
1480 ;; The opening should be preceded by a blank line.
1481 ((and (looking-at pre-regexp
)
1482 (save-match-data (markdown-prev-line-blank-p)))
1483 (setq open
(match-beginning 0))
1484 (while (and (or (looking-at-p pre-regexp
) (markdown-cur-line-blank-p))
1487 (skip-syntax-backward "-")
1488 (setq close
(point)))
1489 ;; If current line has a list marker, update levels, move to end of block
1490 ((looking-at markdown-regex-list
)
1491 (setq levels
(markdown-update-list-levels
1492 (match-string 2) (current-indentation) levels
))
1493 (markdown-end-of-block-element))
1494 ;; If this is the end of the indentation level, adjust levels accordingly.
1495 ;; Only match end of indentation level if levels is not the empty list.
1496 ((and (car levels
) (looking-at-p close-regexp
))
1497 (setq levels
(markdown-update-list-levels
1498 nil
(current-indentation) levels
))
1499 (markdown-end-of-block-element))
1500 (t (markdown-end-of-block-element))))
1502 (when (and open close
)
1503 ;; Set text property data
1504 (put-text-property open close
'markdown-pre
(list open close
))
1505 ;; Recursively search again
1506 (markdown-syntax-propertize-pre-blocks (point) end
)))))
1508 (defconst markdown-fenced-block-pairs
1509 `(((,markdown-regex-tilde-fence-begin markdown-tilde-fence-begin
)
1510 (markdown-make-tilde-fence-regex markdown-tilde-fence-end
)
1511 markdown-fenced-code
)
1512 ((markdown-get-yaml-metadata-start-border markdown-yaml-metadata-begin
)
1513 (markdown-get-yaml-metadata-end-border markdown-yaml-metadata-end
)
1514 markdown-yaml-metadata-section
)
1515 ((,markdown-regex-gfm-code-block-open markdown-gfm-block-begin
)
1516 (,markdown-regex-gfm-code-block-close markdown-gfm-block-end
)
1518 "Mapping of regular expressions to \"fenced-block\" constructs.
1519 These constructs are distinguished by having a distinctive start
1520 and end pattern, both of which take up an entire line of text,
1521 but no special pattern to identify text within the fenced
1522 blocks (unlike blockquotes and indented-code sections).
1524 Each element within this list takes the form:
1526 ((START-REGEX-OR-FUN START-PROPERTY)
1527 (END-REGEX-OR-FUN END-PROPERTY)
1530 Each *-REGEX-OR-FUN element can be a regular expression as a string, or a
1531 function which evaluates to same. Functions for START-REGEX-OR-FUN accept no
1532 arguments, but functions for END-REGEX-OR-FUN accept a single numerical argument
1533 which is the length of the first group of the START-REGEX-OR-FUN match, which
1534 can be ignored if unnecessary. `markdown-maybe-funcall-regexp' is used to
1535 evaluate these into \"real\" regexps.
1537 The *-PROPERTY elements are the text properties applied to each part of the
1538 block construct when it is matched using
1539 `markdown-syntax-propertize-fenced-block-constructs'. START-PROPERTY is applied
1540 to the text matching START-REGEX-OR-FUN, END-PROPERTY to END-REGEX-OR-FUN, and
1541 MIDDLE-PROPERTY to the text in between the two. The value of *-PROPERTY is the
1542 `match-data' when the regexp was matched to the text. In the case of
1543 MIDDLE-PROPERTY, the value is a false match data of the form '(begin end), with
1544 begin and end set to the edges of the \"middle\" text. This makes fontification
1547 (defun markdown-text-property-at-point (prop)
1548 (get-text-property (point) prop
))
1550 (defsubst markdown-maybe-funcall-regexp
(object &optional arg
)
1551 (cond ((functionp object
)
1552 (if arg
(funcall object arg
) (funcall object
)))
1553 ((stringp object
) object
)
1554 (t (error "Object cannot be turned into regex"))))
1556 (defsubst markdown-get-start-fence-regexp
()
1557 "Return regexp to find all \"start\" sections of fenced block constructs.
1558 Which construct is actually contained in the match must be found separately."
1561 ;; FIXME: Why `cl-mapcar' rather than `mapcar'?
1562 (cl-mapcar (lambda (entry) (markdown-maybe-funcall-regexp (caar entry
)))
1563 markdown-fenced-block-pairs
)
1566 (defun markdown-get-fenced-block-begin-properties ()
1567 (cl-mapcar (lambda (entry) (cl-cadar entry
)) markdown-fenced-block-pairs
))
1569 (defun markdown-get-fenced-block-end-properties ()
1570 (cl-mapcar (lambda (entry) (cl-cadadr entry
)) markdown-fenced-block-pairs
))
1572 (defun markdown-get-fenced-block-middle-properties ()
1573 (cl-mapcar #'cl-third markdown-fenced-block-pairs
))
1575 (defun markdown-find-previous-prop (prop &optional lim
)
1576 "Find previous place where property PROP is non-nil, up to LIM.
1577 Return a cons of (pos . property). pos is point if point contains
1580 (if (get-text-property (point) prop
) (point)
1581 (previous-single-property-change
1582 (point) prop nil
(or lim
(point-min))))))
1583 (when (and (not (get-text-property res prop
))
1585 (get-text-property (1- res
) prop
))
1587 (when (and res
(get-text-property res prop
)) (cons res prop
))))
1589 (defun markdown-find-next-prop (prop &optional lim
)
1590 "Find next place where property PROP is non-nil, up to LIM.
1591 Return a cons of (POS . PROPERTY) where POS is point if point
1592 contains non-nil PROP."
1594 (if (get-text-property (point) prop
) (point)
1595 (next-single-property-change
1596 (point) prop nil
(or lim
(point-max))))))
1597 (when (and res
(get-text-property res prop
)) (cons res prop
))))
1599 (defun markdown-min-of-seq (map-fn seq
)
1600 "Apply MAP-FN to SEQ and return element of SEQ with minimum value of MAP-FN."
1601 (cl-loop for el in seq
1602 with min
= 1.0e
+INF
; infinity
1604 do
(let ((res (funcall map-fn el
)))
1608 finally return min-el
))
1610 (defun markdown-find-previous-block ()
1611 "Find previous block.
1612 Detect whether `markdown-syntax-propertize-fenced-block-constructs' was
1613 unable to propertize the entire block, but was able to propertize the beginning
1614 of the block. If so, return a cons of (pos . property) where the beginning of
1615 the block was propertized."
1616 (let ((start-pt (point))
1618 (markdown-min-of-seq
1623 #'markdown-find-previous-prop
1624 (markdown-get-fenced-block-begin-properties))))))
1626 (let* ((length-of-open-match
1628 (get-text-property (car closest-open
) (cdr closest-open
))))
1629 (- (cl-fourth match-d
) (cl-third match-d
))))
1631 (markdown-maybe-funcall-regexp
1634 (lambda (entry) (eq (cl-cadar entry
) (cdr closest-open
)))
1635 markdown-fenced-block-pairs
))
1636 length-of-open-match
))
1640 (goto-char (car closest-open
))
1641 (and (re-search-forward end-regexp start-pt t
)
1642 (match-beginning 0))))))
1643 (and (not end-prop-loc
) closest-open
)))))
1645 (defun markdown-get-fenced-block-from-start (prop)
1646 "Return limits of an enclosing fenced block from its start, using PROP.
1647 Return value is a list usable as `match-data'."
1648 (catch 'no-rest-of-block
1649 (let* ((correct-entry
1651 (lambda (entry) (eq (cl-cadar entry
) prop
))
1652 markdown-fenced-block-pairs
))
1653 (begin-of-begin (cl-first (markdown-text-property-at-point prop
)))
1654 (middle-prop (cl-third correct-entry
))
1655 (end-prop (cl-cadadr correct-entry
))
1658 (goto-char (match-end 0)) ; end of begin
1659 (unless (eobp) (forward-char))
1660 (let ((mid-prop-v (markdown-text-property-at-point middle-prop
)))
1661 (if (not mid-prop-v
) ; no middle
1663 ;; try to find end by advancing one
1665 (markdown-text-property-at-point end-prop
)))
1666 (if end-prop-v
(cl-second end-prop-v
)
1667 (throw 'no-rest-of-block nil
))))
1668 (set-match-data mid-prop-v
)
1669 (goto-char (match-end 0)) ; end of middle
1670 (beginning-of-line) ; into end
1671 (cl-second (markdown-text-property-at-point end-prop
)))))))
1672 (list begin-of-begin end-of-end
))))
1674 (defun markdown-get-fenced-block-from-middle (prop)
1675 "Return limits of an enclosing fenced block from its middle, using PROP.
1676 Return value is a list usable as `match-data'."
1677 (let* ((correct-entry
1679 (lambda (entry) (eq (cl-third entry
) prop
))
1680 markdown-fenced-block-pairs
))
1681 (begin-prop (cl-cadar correct-entry
))
1684 (goto-char (match-beginning 0))
1685 (unless (bobp) (forward-line -
1))
1687 (cl-first (markdown-text-property-at-point begin-prop
))))
1688 (end-prop (cl-cadadr correct-entry
))
1691 (goto-char (match-end 0))
1693 (cl-second (markdown-text-property-at-point end-prop
)))))
1694 (list begin-of-begin end-of-end
)))
1696 (defun markdown-get-fenced-block-from-end (prop)
1697 "Return limits of an enclosing fenced block from its end, using PROP.
1698 Return value is a list usable as `match-data'."
1699 (let* ((correct-entry
1701 (lambda (entry) (eq (cl-cadadr entry
) prop
))
1702 markdown-fenced-block-pairs
))
1703 (end-of-end (cl-second (markdown-text-property-at-point prop
)))
1704 (middle-prop (cl-third correct-entry
))
1705 (begin-prop (cl-cadar correct-entry
))
1708 (goto-char (match-beginning 0)) ; beginning of end
1709 (unless (bobp) (backward-char)) ; into middle
1710 (let ((mid-prop-v (markdown-text-property-at-point middle-prop
)))
1711 (if (not mid-prop-v
)
1714 (cl-first (markdown-text-property-at-point begin-prop
)))
1715 (set-match-data mid-prop-v
)
1716 (goto-char (match-beginning 0)) ; beginning of middle
1717 (unless (bobp) (forward-line -
1)) ; into beginning
1719 (cl-first (markdown-text-property-at-point begin-prop
)))))))
1720 (list begin-of-begin end-of-end
)))
1722 (defun markdown-get-enclosing-fenced-block-construct (&optional pos
)
1723 "Get \"fake\" match data for block enclosing POS.
1724 Returns fake match data which encloses the start, middle, and end
1725 of the block construct enclosing POS, if it exists. Used in
1726 `markdown-code-block-at-pos'."
1728 (when pos
(goto-char pos
))
1734 (lambda (fun-and-prop)
1735 (cl-destructuring-bind (fun prop
) fun-and-prop
1738 (set-match-data (markdown-text-property-at-point prop
))
1739 (funcall fun prop
)))))
1740 `((markdown-get-fenced-block-from-start
1742 #'markdown-text-property-at-point
1743 (markdown-get-fenced-block-begin-properties)))
1744 (markdown-get-fenced-block-from-middle
1746 #'markdown-text-property-at-point
1747 (markdown-get-fenced-block-middle-properties)))
1748 (markdown-get-fenced-block-from-end
1750 #'markdown-text-property-at-point
1751 (markdown-get-fenced-block-end-properties)))))))))
1753 (defun markdown-propertize-end-match (reg end correct-entry enclosed-text-start
)
1754 "Get match for REG up to END, if exists, and propertize appropriately.
1755 CORRECT-ENTRY is an entry in `markdown-fenced-block-pairs' and
1756 ENCLOSED-TEXT-START is the start of the \"middle\" section of the block."
1757 (when (re-search-forward reg end t
)
1758 (put-text-property (match-beginning 0) (match-end 0)
1759 (cl-cadadr correct-entry
) (match-data t
))
1761 enclosed-text-start
(match-beginning 0) (cl-third correct-entry
)
1762 (list enclosed-text-start
(match-beginning 0)))))
1764 (defun markdown-syntax-propertize-fenced-block-constructs (start end
)
1765 "Propertize according to `markdown-fenced-block-pairs' from START to END.
1766 If unable to propertize an entire block (if the start of a block is within START
1767 and END, but the end of the block is not), propertize the start section of a
1768 block, then in a subsequent call propertize both middle and end by finding the
1769 start which was previously propertized."
1770 (let ((start-reg (markdown-get-start-fence-regexp)))
1773 ;; start from previous unclosed block, if exists
1774 (let ((prev-begin-block (markdown-find-previous-block)))
1775 (when prev-begin-block
1776 (let* ((correct-entry
1777 (cl-find-if (lambda (entry)
1778 (eq (cdr prev-begin-block
) (cl-cadar entry
)))
1779 markdown-fenced-block-pairs
))
1780 (enclosed-text-start (1+ (car prev-begin-block
)))
1783 (goto-char (car prev-begin-block
))
1785 (markdown-maybe-funcall-regexp
1786 (caar correct-entry
))
1788 (point-at-bol) (point-at-eol)))
1789 (- (match-end 1) (match-beginning 1))))
1790 (end-reg (markdown-maybe-funcall-regexp
1791 (cl-caadr correct-entry
) start-length
)))
1792 (markdown-propertize-end-match
1793 end-reg end correct-entry enclosed-text-start
))))
1794 ;; find all new blocks within region
1795 (while (re-search-forward start-reg end t
)
1796 ;; we assume the opening constructs take up (only) an entire line,
1797 ;; so we re-check the current line
1798 (let* ((cur-line (buffer-substring (point-at-bol) (point-at-eol)))
1799 ;; find entry in `markdown-fenced-block-pairs' corresponding
1800 ;; to regex which was matched
1803 (lambda (fenced-pair)
1805 (markdown-maybe-funcall-regexp (caar fenced-pair
))
1807 markdown-fenced-block-pairs
))
1808 (enclosed-text-start
1809 (save-excursion (1+ (point-at-eol))))
1811 (markdown-maybe-funcall-regexp
1812 (cl-caadr correct-entry
)
1813 (if (and (match-beginning 1) (match-end 1))
1814 (- (match-end 1) (match-beginning 1))
1816 ;; get correct match data
1820 (markdown-maybe-funcall-regexp (caar correct-entry
))
1822 ;; mark starting, even if ending is outside of region
1823 (put-text-property (match-beginning 0) (match-end 0)
1824 (cl-cadar correct-entry
) (match-data t
))
1825 (markdown-propertize-end-match
1826 end-reg end correct-entry enclosed-text-start
))))))
1828 (defun markdown-syntax-propertize-blockquotes (start end
)
1829 "Match blockquotes from START to END."
1832 (while (and (re-search-forward markdown-regex-blockquote end t
)
1833 (not (markdown-code-block-at-pos (match-beginning 0))))
1834 (put-text-property (match-beginning 0) (match-end 0)
1835 'markdown-blockquote
1838 (defun markdown-syntax-propertize-yaml-metadata (start end
)
1842 while
(re-search-forward markdown-regex-declarative-metadata end t
)
1843 do
(when (get-text-property (match-beginning 0)
1844 'markdown-yaml-metadata-section
)
1845 (put-text-property (match-beginning 1) (match-end 1)
1846 'markdown-metadata-key
(match-data t
))
1847 (put-text-property (match-beginning 2) (match-end 2)
1848 'markdown-metadata-markup
(match-data t
))
1849 (put-text-property (match-beginning 3) (match-end 3)
1850 'markdown-metadata-value
(match-data t
))))))
1852 (defun markdown-syntax-propertize-headings (start end
)
1853 "Match headings of type SYMBOL with REGEX from START to END."
1855 (while (re-search-forward markdown-regex-header end t
)
1856 (unless (markdown-code-block-at-pos (match-beginning 0))
1858 (match-beginning 0) (match-end 0) 'markdown-heading t
)
1860 (match-beginning 0) (match-end 0)
1861 (cond ((match-string-no-properties 2) 'markdown-heading-1-setext
)
1862 ((match-string-no-properties 3) 'markdown-heading-2-setext
)
1863 (t (let ((atx-level (length (match-string-no-properties 4))))
1864 (intern (format "markdown-heading-%d-atx" atx-level
)))))
1867 (defun markdown-syntax-propertize-comments (start end
)
1868 "Match HTML comments from the START to END."
1869 (let* ((state (syntax-ppss)) (in-comment (nth 4 state
)))
1873 ((and (not in-comment
)
1874 (re-search-forward markdown-regex-comment-start end t
)
1875 (not (markdown-inline-code-at-point-p))
1876 (not (markdown-code-block-at-point-p)))
1877 (let ((open-beg (match-beginning 0)))
1878 (put-text-property open-beg
(1+ open-beg
)
1879 'syntax-table
(string-to-syntax "<"))
1880 (markdown-syntax-propertize-comments
1881 (min (1+ (match-end 0)) end
(point-max)) end
)))
1884 (re-search-forward markdown-regex-comment-end end t
))
1885 (put-text-property (1- (match-end 0)) (match-end 0)
1886 'syntax-table
(string-to-syntax ">"))
1887 (markdown-syntax-propertize-comments
1888 (min (1+ (match-end 0)) end
(point-max)) end
))
1892 (defvar markdown--syntax-properties
1893 (list 'markdown-tilde-fence-begin nil
1894 'markdown-tilde-fence-end nil
1895 'markdown-fenced-code nil
1896 'markdown-yaml-metadata-begin nil
1897 'markdown-yaml-metadata-end nil
1898 'markdown-yaml-metadata-section nil
1899 'markdown-gfm-block-begin nil
1900 'markdown-gfm-block-end nil
1901 'markdown-gfm-code nil
1903 'markdown-blockquote nil
1904 'markdown-heading nil
1905 'markdown-heading-1-setext nil
1906 'markdown-heading-2-setext nil
1907 'markdown-heading-1-atx nil
1908 'markdown-heading-2-atx nil
1909 'markdown-heading-3-atx nil
1910 'markdown-heading-4-atx nil
1911 'markdown-heading-5-atx nil
1912 'markdown-heading-6-atx nil
1913 'markdown-metadata-key nil
1914 'markdown-metadata-value nil
1915 'markdown-metadata-markup nil
)
1916 "Property list of all known markdown syntactic properties.")
1918 (defun markdown-syntax-propertize (start end
)
1919 "Function used as `syntax-propertize-function'.
1920 START and END delimit region to propertize."
1921 (with-silent-modifications
1923 (remove-text-properties start end markdown--syntax-properties
)
1924 (markdown-syntax-propertize-fenced-block-constructs start end
)
1925 (markdown-syntax-propertize-yaml-metadata start end
)
1926 (markdown-syntax-propertize-pre-blocks start end
)
1927 (markdown-syntax-propertize-blockquotes start end
)
1928 (markdown-syntax-propertize-headings start end
)
1929 (markdown-syntax-propertize-comments start end
))))
1932 ;;; Font Lock =================================================================
1934 (require 'font-lock
)
1936 (defvar markdown-italic-face
'markdown-italic-face
1937 "Face name to use for italic text.")
1939 (defvar markdown-bold-face
'markdown-bold-face
1940 "Face name to use for bold text.")
1942 (defvar markdown-strike-through-face
'markdown-strike-through-face
1943 "Face name to use for strike-through text.")
1945 (defvar markdown-header-delimiter-face
'markdown-header-delimiter-face
1946 "Face name to use as a base for header delimiters.")
1948 (defvar markdown-header-rule-face
'markdown-header-rule-face
1949 "Face name to use as a base for header rules.")
1951 (defvar markdown-header-face
'markdown-header-face
1952 "Face name to use as a base for headers.")
1954 (defvar markdown-header-face-1
'markdown-header-face-1
1955 "Face name to use for level-1 headers.")
1957 (defvar markdown-header-face-2
'markdown-header-face-2
1958 "Face name to use for level-2 headers.")
1960 (defvar markdown-header-face-3
'markdown-header-face-3
1961 "Face name to use for level-3 headers.")
1963 (defvar markdown-header-face-4
'markdown-header-face-4
1964 "Face name to use for level-4 headers.")
1966 (defvar markdown-header-face-5
'markdown-header-face-5
1967 "Face name to use for level-5 headers.")
1969 (defvar markdown-header-face-6
'markdown-header-face-6
1970 "Face name to use for level-6 headers.")
1972 (defvar markdown-inline-code-face
'markdown-inline-code-face
1973 "Face name to use for inline code.")
1975 (defvar markdown-list-face
'markdown-list-face
1976 "Face name to use for list markers.")
1978 (defvar markdown-blockquote-face
'markdown-blockquote-face
1979 "Face name to use for blockquote.")
1981 (defvar markdown-pre-face
'markdown-pre-face
1982 "Face name to use for preformatted text.")
1984 (defvar markdown-language-keyword-face
'markdown-language-keyword-face
1985 "Face name to use for programming language identifiers.")
1987 (defvar markdown-language-info-face
'markdown-language-info-face
1988 "Face name to use for programming info strings.")
1990 (defvar markdown-link-face
'markdown-link-face
1991 "Face name to use for links.")
1993 (defvar markdown-missing-link-face
'markdown-missing-link-face
1994 "Face name to use for links where the linked file does not exist.")
1996 (defvar markdown-reference-face
'markdown-reference-face
1997 "Face name to use for reference.")
1999 (defvar markdown-footnote-face
'markdown-footnote-face
2000 "Face name to use for footnote identifiers.")
2002 (defvar markdown-url-face
'markdown-url-face
2003 "Face name to use for URLs.")
2005 (defvar markdown-link-title-face
'markdown-link-title-face
2006 "Face name to use for reference link titles.")
2008 (defvar markdown-line-break-face
'markdown-line-break-face
2009 "Face name to use for hard line breaks.")
2011 (defvar markdown-comment-face
'markdown-comment-face
2012 "Face name to use for HTML comments.")
2014 (defvar markdown-math-face
'markdown-math-face
2015 "Face name to use for LaTeX expressions.")
2017 (defvar markdown-metadata-key-face
'markdown-metadata-key-face
2018 "Face name to use for metadata keys.")
2020 (defvar markdown-metadata-value-face
'markdown-metadata-value-face
2021 "Face name to use for metadata values.")
2023 (defvar markdown-gfm-checkbox-face
'markdown-gfm-checkbox-face
2024 "Face name to use for GFM checkboxes.")
2026 (defvar markdown-highlight-face
'markdown-highlight-face
2027 "Face name to use for mouse highlighting.")
2029 (defvar markdown-markup-face
'markdown-markup-face
2030 "Face name to use for markup elements.")
2032 (defgroup markdown-faces nil
2033 "Faces used in Markdown Mode"
2037 (defface markdown-italic-face
2038 '((t (:inherit font-lock-variable-name-face
:slant italic
:weight normal
)))
2039 "Face for italic text."
2040 :group
'markdown-faces
)
2042 (defface markdown-bold-face
2043 '((t (:inherit font-lock-variable-name-face
:weight bold
:slant normal
)))
2044 "Face for bold text."
2045 :group
'markdown-faces
)
2047 (defface markdown-strike-through-face
2048 '((t (:inherit font-lock-variable-name-face
:strike-through t
)))
2049 "Face for strike-through text."
2050 :group
'markdown-faces
)
2052 (defface markdown-markup-face
2053 '((t (:inherit shadow
:slant normal
:weight normal
)))
2054 "Face for markup elements."
2055 :group
'markdown-faces
)
2057 (defface markdown-header-rule-face
2058 '((t (:inherit markdown-markup-face
)))
2059 "Base face for headers rules."
2060 :group
'markdown-faces
)
2062 (defface markdown-header-delimiter-face
2063 '((t (:inherit markdown-markup-face
)))
2064 "Base face for headers hash delimiter."
2065 :group
'markdown-faces
)
2067 (defface markdown-inline-code-face
2068 '((t (:inherit font-lock-constant-face
)))
2069 "Face for inline code."
2070 :group
'markdown-faces
)
2072 (defface markdown-list-face
2073 '((t (:inherit markdown-markup-face
)))
2074 "Face for list item markers."
2075 :group
'markdown-faces
)
2077 (defface markdown-blockquote-face
2078 '((t (:inherit font-lock-doc-face
)))
2079 "Face for blockquote sections."
2080 :group
'markdown-faces
)
2082 (defface markdown-pre-face
2083 '((t (:inherit font-lock-constant-face
)))
2084 "Face for preformatted text."
2085 :group
'markdown-faces
)
2087 (defface markdown-language-keyword-face
2088 '((t (:inherit font-lock-type-face
)))
2089 "Face for programming language identifiers."
2090 :group
'markdown-faces
)
2092 (defface markdown-language-info-face
2093 '((t (:inherit font-lock-string-face
)))
2094 "Face for programming language info strings."
2095 :group
'markdown-faces
)
2097 (defface markdown-link-face
2098 '((t (:inherit font-lock-keyword-face
)))
2100 :group
'markdown-faces
)
2102 (defface markdown-missing-link-face
2103 '((t (:inherit font-lock-warning-face
)))
2104 "Face for missing links."
2105 :group
'markdown-faces
)
2107 (defface markdown-reference-face
2108 '((t (:inherit markdown-markup-face
)))
2109 "Face for link references."
2110 :group
'markdown-faces
)
2112 (defface markdown-footnote-face
2113 '((t (:inherit markdown-markup-face
)))
2114 "Face for footnote markers."
2115 :group
'markdown-faces
)
2117 (defface markdown-url-face
2118 '((t (:inherit font-lock-string-face
)))
2120 :group
'markdown-faces
)
2122 (defface markdown-link-title-face
2123 '((t (:inherit font-lock-comment-face
)))
2124 "Face for reference link titles."
2125 :group
'markdown-faces
)
2127 (defface markdown-line-break-face
2128 '((t (:inherit font-lock-constant-face
:underline t
)))
2129 "Face for hard line breaks."
2130 :group
'markdown-faces
)
2132 (defface markdown-comment-face
2133 '((t (:inherit font-lock-comment-face
)))
2134 "Face for HTML comments."
2135 :group
'markdown-faces
)
2137 (defface markdown-math-face
2138 '((t (:inherit font-lock-string-face
)))
2139 "Face for LaTeX expressions."
2140 :group
'markdown-faces
)
2142 (defface markdown-metadata-key-face
2143 '((t (:inherit font-lock-variable-name-face
)))
2144 "Face for metadata keys."
2145 :group
'markdown-faces
)
2147 (defface markdown-metadata-value-face
2148 '((t (:inherit font-lock-string-face
)))
2149 "Face for metadata values."
2150 :group
'markdown-faces
)
2152 (defface markdown-gfm-checkbox-face
2153 '((t (:inherit font-lock-builtin-face
)))
2154 "Face for GFM checkboxes."
2155 :group
'markdown-faces
)
2157 (defface markdown-highlight-face
2158 '((t (:inherit highlight
)))
2159 "Face for mouse highlighting."
2160 :group
'markdown-faces
)
2162 (defcustom markdown-header-scaling nil
2163 "Whether to use variable-height faces for headers.
2164 When non-nil, `markdown-header-face' will inherit from
2165 `variable-pitch' and the scaling values in
2166 `markdown-header-scaling-values' will be applied to
2167 headers of levels one through six respectively."
2169 :initialize
'custom-initialize-default
2170 :set
(lambda (symbol value
)
2171 (set-default symbol value
)
2172 (markdown-update-header-faces value
))
2173 :group
'markdown-faces
)
2175 (defcustom markdown-header-scaling-values
2176 '(1.8
1.4 1.2 1.0 1.0 1.0)
2177 "List of scaling values for headers of level one through six.
2178 Used when `markdown-header-scaling' is non-nil."
2180 :initialize
'custom-initialize-default
2181 :set
(lambda (symbol value
)
2182 (set-default symbol value
)
2183 (markdown-update-header-faces markdown-header-scaling value
))
2184 :group
'markdown-faces
)
2186 (defun markdown-make-header-faces ()
2187 "Build the faces used for Markdown headers."
2188 (let ((inherit-faces '(font-lock-function-name-face)))
2189 (when markdown-header-scaling
2190 (setq inherit-faces
(cons 'variable-pitch inherit-faces
)))
2191 (defface markdown-header-face
2192 `((t (:inherit
,inherit-faces
:weight bold
)))
2193 "Base face for headers."
2194 :group
'markdown-faces
))
2196 (let* ((num1 (1+ num
))
2197 (face-name (intern (format "markdown-header-face-%s" num1
)))
2198 (scale (if markdown-header-scaling
2199 (float (nth num markdown-header-scaling-values
))
2202 `(defface ,face-name
2203 '((t (:inherit markdown-header-face
:height
,scale
)))
2204 (format "Face for level %s headers.
2206 You probably don't want to customize this face directly. Instead
2207 you can customize the base face `markdown-header-face' or the
2208 variable-height variable `markdown-header-scaling'." ,num1
)
2209 :group
'markdown-faces
)))))
2211 (markdown-make-header-faces)
2213 (defun markdown-update-header-faces (&optional scaling scaling-values
)
2214 "Update header faces, depending on if header SCALING is desired.
2215 If so, use given list of SCALING-VALUES relative to the baseline
2216 size of `markdown-header-face'."
2218 (let* ((face-name (intern (format "markdown-header-face-%s" (1+ num
))))
2219 (scale (cond ((not scaling
) 1.0)
2220 (scaling-values (float (nth num scaling-values
)))
2221 (t (float (nth num markdown-header-scaling-values
))))))
2222 (unless (get face-name
'saved-face
) ; Don't update customized faces
2223 (set-face-attribute face-name nil
:height scale
)))))
2225 (defun markdown-syntactic-face (state)
2226 "Return font-lock face for characters with given STATE.
2227 See `font-lock-syntactic-face-function' for details."
2228 (let ((in-comment (nth 4 state
)))
2230 (in-comment 'markdown-comment-face
)
2233 (defvar markdown-mode-font-lock-keywords-basic
2234 `((markdown-match-yaml-metadata-begin .
((1 markdown-markup-face
)))
2235 (markdown-match-yaml-metadata-end .
((1 markdown-markup-face
)))
2236 (markdown-match-yaml-metadata-key .
((1 markdown-metadata-key-face
)
2237 (2 markdown-markup-face
)
2238 (3 markdown-metadata-value-face
)))
2239 (markdown-match-gfm-open-code-blocks .
((1 markdown-markup-face
)
2240 (2 markdown-markup-face nil t
)
2241 (3 markdown-language-keyword-face nil t
)
2242 (4 markdown-language-info-face nil t
)
2243 (5 markdown-markup-face nil t
)))
2244 (markdown-match-gfm-close-code-blocks .
((1 markdown-markup-face
)))
2245 (markdown-match-gfm-code-blocks .
((0 markdown-pre-face
)))
2246 (markdown-match-fenced-start-code-block .
((1 markdown-markup-face
)
2247 (2 markdown-markup-face nil t
)
2248 (3 markdown-language-keyword-face nil t
)
2249 (4 markdown-language-info-face nil t
)
2250 (5 markdown-markup-face nil t
)))
2251 (markdown-match-fenced-end-code-block .
((0 markdown-markup-face
)))
2252 (markdown-match-fenced-code-blocks .
((0 markdown-pre-face
)))
2253 (markdown-match-pre-blocks .
((0 markdown-pre-face
)))
2254 (markdown-match-blockquotes .
((1 markdown-markup-face
)
2255 (2 markdown-blockquote-face
)))
2256 (markdown-match-heading-1-setext .
((1 markdown-header-face-1
)
2257 (2 markdown-header-rule-face
)))
2258 (markdown-match-heading-2-setext .
((1 markdown-header-face-2
)
2259 (3 markdown-header-rule-face
)))
2260 (markdown-match-heading-6-atx .
((4 markdown-header-delimiter-face
)
2261 (5 markdown-header-face-6
)
2262 (6 markdown-header-delimiter-face
)))
2263 (markdown-match-heading-5-atx .
((4 markdown-header-delimiter-face
)
2264 (5 markdown-header-face-5
)
2265 (6 markdown-header-delimiter-face
)))
2266 (markdown-match-heading-4-atx .
((4 markdown-header-delimiter-face
)
2267 (5 markdown-header-face-4
)
2268 (6 markdown-header-delimiter-face
)))
2269 (markdown-match-heading-3-atx .
((4 markdown-header-delimiter-face
)
2270 (5 markdown-header-face-3
)
2271 (6 markdown-header-delimiter-face
)))
2272 (markdown-match-heading-2-atx .
((4 markdown-header-delimiter-face
)
2273 (5 markdown-header-face-2
)
2274 (6 markdown-header-delimiter-face
)))
2275 (markdown-match-heading-1-atx .
((4 markdown-header-delimiter-face
)
2276 (5 markdown-header-face-1
)
2277 (6 markdown-header-delimiter-face
)))
2278 (markdown-match-declarative-metadata .
((1 markdown-metadata-key-face
)
2279 (2 markdown-markup-face
)
2280 (3 markdown-metadata-value-face
)))
2281 (markdown-match-pandoc-metadata .
((1 markdown-markup-face
)
2282 (2 markdown-markup-face
)
2283 (3 markdown-metadata-value-face
)))
2284 (markdown-match-hr . markdown-header-delimiter-face
)
2285 (markdown-match-code .
((1 markdown-markup-face
)
2286 (2 markdown-inline-code-face
)
2287 (3 markdown-markup-face
)))
2288 (,markdown-regex-kbd .
((1 markdown-markup-face
)
2289 (2 markdown-inline-code-face
)
2290 (3 markdown-markup-face
)))
2291 (,markdown-regex-angle-uri .
((1 markdown-markup-face
)
2292 (2 markdown-link-face
)
2293 (3 markdown-markup-face
)))
2294 (,markdown-regex-list .
(2 markdown-list-face
))
2295 (,markdown-regex-footnote .
((1 markdown-markup-face
) ; [^
2296 (2 markdown-footnote-face
) ; label
2297 (3 markdown-markup-face
))) ; ]
2298 (,markdown-regex-link-inline .
((1 markdown-markup-face nil t
) ; ! (optional)
2299 (2 markdown-markup-face
) ; [
2300 (3 markdown-link-face
) ; text
2301 (4 markdown-markup-face
) ; ]
2302 (5 markdown-markup-face
) ; (
2303 (6 markdown-url-face
) ; url
2304 (7 markdown-link-title-face nil t
) ; "title" (optional)
2305 (8 markdown-markup-face
))) ; )
2306 (,markdown-regex-link-reference .
((1 markdown-markup-face nil t
) ; ! (optional)
2307 (2 markdown-markup-face
) ; [
2308 (3 markdown-link-face
) ; text
2309 (4 markdown-markup-face
) ; ]
2310 (5 markdown-markup-face
) ; [
2311 (6 markdown-reference-face
) ; label
2312 (7 markdown-markup-face
))) ; ]
2313 (,markdown-regex-reference-definition .
((1 markdown-markup-face
) ; [
2314 (2 markdown-reference-face
) ; label
2315 (3 markdown-markup-face
) ; ]
2316 (4 markdown-markup-face
) ; :
2317 (5 markdown-url-face
) ; url
2318 (6 markdown-link-title-face
))) ; "title" (optional)
2320 (markdown-match-math-single .
((1 markdown-markup-face prepend
)
2321 (2 markdown-math-face append
)
2322 (3 markdown-markup-face prepend
)))
2324 (markdown-match-math-double .
((1 markdown-markup-face prepend
)
2325 (2 markdown-math-face append
)
2326 (3 markdown-markup-face prepend
)))
2327 (markdown-match-bold .
((1 markdown-markup-face prepend
)
2328 (2 markdown-bold-face append
)
2329 (3 markdown-markup-face prepend
)))
2330 (markdown-match-italic .
((1 markdown-markup-face prepend
)
2331 (2 markdown-italic-face append
)
2332 (3 markdown-markup-face prepend
)))
2333 (,markdown-regex-uri . markdown-link-face
)
2334 (,markdown-regex-email . markdown-link-face
)
2335 (,markdown-regex-line-break .
(1 markdown-line-break-face prepend
)))
2337 "Syntax highlighting for Markdown files.")
2339 (defvar markdown-mode-font-lock-keywords nil
2340 "Default highlighting expressions for Markdown mode.
2341 This variable is defined as a buffer-local variable for dynamic
2342 extension support.")
2345 (defvar markdown-footnote-counter
0
2346 "Counter for footnote numbers.")
2347 (make-variable-buffer-local 'markdown-footnote-counter
)
2349 (defconst markdown-footnote-chars
2351 "Regular expression matching any character that is allowed in a footnote identifier.")
2353 (defconst markdown-regex-footnote-definition
2354 (concat "^\\[\\(\\^" markdown-footnote-chars
"*?\\)\\]:\\(?:[ \t]+\\|$\\)")
2355 "Regular expression matching a footnote definition, capturing the label.")
2358 ;;; Compatibility =============================================================
2360 (defun markdown-replace-regexp-in-string (regexp rep string
)
2361 "Replace ocurrences of REGEXP with REP in STRING.
2362 This is a compatibility wrapper to provide `replace-regexp-in-string'
2364 (if (featurep 'xemacs
)
2365 (replace-in-string string regexp rep
)
2366 (replace-regexp-in-string regexp rep string
)))
2368 ;; `markdown-use-region-p' is a compatibility function which checks
2369 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
2372 ;; Emacs 24 and newer
2373 ((fboundp 'use-region-p
)
2374 (defalias 'markdown-use-region-p
'use-region-p
))
2376 ((fboundp 'region-active-p
)
2377 (defalias 'markdown-use-region-p
'region-active-p
))))
2379 (defun markdown-use-buttons-p ()
2380 "Determine whether this Emacs supports buttons."
2381 (or (featurep 'button
) (locate-library "button")))
2383 ;; Use new names for outline-mode functions in Emacs 25 and later.
2385 (defalias 'markdown-hide-sublevels
2386 (if (fboundp 'outline-hide-sublevels
)
2387 'outline-hide-sublevels
2389 (defalias 'markdown-show-all
2390 (if (fboundp 'outline-show-all
)
2393 (defalias 'markdown-hide-body
2394 (if (fboundp 'outline-hide-body
)
2397 (defalias 'markdown-show-children
2398 (if (fboundp 'outline-show-children
)
2399 'outline-show-children
2401 (defalias 'markdown-show-subtree
2402 (if (fboundp 'outline-show-subtree
)
2403 'outline-show-subtree
2405 (defalias 'markdown-hide-subtree
2406 (if (fboundp 'outline-hide-subtree
)
2407 'outline-hide-subtree
2410 ;; Provide directory-name-p to Emacs 24
2411 (defsubst markdown-directory-name-p
(name)
2412 "Return non-nil if NAME ends with a directory separator character.
2413 Taken from `directory-name-p' from Emacs 25 and provided here for
2414 backwards compatibility."
2415 (let ((len (length name
))
2418 (setq lastc
(aref name
(1- len
))))
2420 (and (memq system-type
'(windows-nt ms-dos
))
2423 ;; Provide a function to find files recursively in Emacs 24.
2424 (defalias 'markdown-directory-files-recursively
2425 (if (fboundp 'directory-files-recursively
)
2426 'directory-files-recursively
2427 (lambda (dir regexp
)
2428 "Return list of all files under DIR that have file names matching REGEXP.
2429 This function works recursively. Files are returned in \"depth first\"
2430 order, and files from each directory are sorted in alphabetical order.
2431 Each file name appears in the returned list in its absolute form.
2432 Based on `directory-files-recursively' from Emacs 25 and provided
2433 here for backwards compatibility."
2436 ;; When DIR is "/", remote file names like "/method:" could
2437 ;; also be offered. We shall suppress them.
2438 (tramp-mode (and tramp-mode
(file-remote-p (expand-file-name dir
)))))
2439 (dolist (file (sort (file-name-all-completions "" dir
)
2441 (unless (member file
'("./" "../"))
2442 (if (markdown-directory-name-p file
)
2443 (let* ((leaf (substring file
0 (1- (length file
))))
2444 (full-file (expand-file-name leaf dir
)))
2446 (nconc result
(markdown-directory-files-recursively
2447 full-file regexp
))))
2448 (when (string-match regexp file
)
2449 (push (expand-file-name file dir
) files
)))))
2450 (nconc result
(nreverse files
))))))
2453 ;;; Markdown Parsing Functions ================================================
2455 (defun markdown-cur-line-blank-p ()
2456 "Return t if the current line is blank and nil otherwise."
2459 (looking-at-p "^\\s *$")))
2461 (defun markdown-prev-line-blank-p ()
2462 "Return t if the previous line is blank and nil otherwise.
2463 If we are at the first line, then consider the previous line to be blank."
2464 (or (= (line-beginning-position) (point-min))
2467 (markdown-cur-line-blank-p))))
2469 (defun markdown-next-line-blank-p ()
2470 "Return t if the next line is blank and nil otherwise.
2471 If we are at the last line, then consider the next line to be blank."
2472 (or (= (line-end-position) (point-max))
2475 (markdown-cur-line-blank-p))))
2477 (defun markdown-prev-line-indent ()
2478 "Return the number of leading whitespace characters in the previous line.
2479 Return 0 if the current line is the first line in the buffer."
2481 (if (= (line-beginning-position) (point-min))
2484 (current-indentation))))
2486 (defun markdown-next-line-indent ()
2487 "Return the number of leading whitespace characters in the next line.
2488 Return 0 if line is the last line in the buffer."
2490 (if (= (line-end-position) (point-max))
2493 (current-indentation))))
2495 (defun markdown-cur-non-list-indent ()
2496 "Return beginning position of list item text (not including the list marker).
2497 Return nil if the current line is not the beginning of a list item."
2501 (when (re-search-forward markdown-regex-list
(line-end-position) t
)
2502 (current-column)))))
2504 (defun markdown-prev-non-list-indent ()
2505 "Return position of the first non-list-marker on the previous line."
2508 (markdown-cur-non-list-indent)))
2510 (defun markdown-new-baseline-p ()
2511 "Determine if the current line begins a new baseline level."
2514 (or (looking-at-p markdown-regex-header
)
2515 (looking-at-p markdown-regex-hr
)
2516 (and (null (markdown-cur-non-list-indent))
2517 (= (current-indentation) 0)
2518 (markdown-prev-line-blank-p)))))
2520 (defun markdown-search-backward-baseline ()
2521 "Search backward baseline point with no indentation and not a list item."
2524 (while (not (or stop
(bobp)))
2525 (re-search-backward markdown-regex-block-separator nil t
)
2527 (goto-char (match-end 2))
2529 ((markdown-new-baseline-p)
2531 ((looking-at-p markdown-regex-list
)
2533 (t (setq stop t
)))))))
2535 (defun markdown-update-list-levels (marker indent levels
)
2536 "Update list levels given list MARKER, block INDENT, and current LEVELS.
2537 Here, MARKER is a string representing the type of list, INDENT is an integer
2538 giving the indentation, in spaces, of the current block, and LEVELS is a
2539 list of the indentation levels of parent list items. When LEVELS is nil,
2540 it means we are at baseline (not inside of a nested list)."
2542 ;; New list item at baseline.
2543 ((and marker
(null levels
))
2544 (setq levels
(list indent
)))
2545 ;; List item with greater indentation (four or more spaces).
2546 ;; Increase list level.
2547 ((and marker
(>= indent
(+ (car levels
) 4)))
2548 (setq levels
(cons indent levels
)))
2549 ;; List item with greater or equal indentation (less than four spaces).
2550 ;; Do not increase list level.
2551 ((and marker
(>= indent
(car levels
)))
2553 ;; Lesser indentation level.
2554 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
2555 ;; indentation could move back more than one list level). Note
2556 ;; that this block need not be the beginning of list item.
2557 ((< indent
(car levels
))
2558 (while (and (> (length levels
) 1)
2559 (< indent
(+ (cadr levels
) 4)))
2560 (setq levels
(cdr levels
)))
2562 ;; Otherwise, do nothing.
2565 (defun markdown-calculate-list-levels ()
2566 "Calculate list levels at point.
2567 Return a list of the form (n1 n2 n3 ...) where n1 is the
2568 indentation of the deepest nested list item in the branch of
2569 the list at the point, n2 is the indentation of the parent
2570 list item, and so on. The depth of the list item is therefore
2571 the length of the returned list. If the point is not at or
2572 immediately after a list item, return nil."
2574 (let ((first (point)) levels indent pre-regexp
)
2575 ;; Find a baseline point with zero list indentation
2576 (markdown-search-backward-baseline)
2577 ;; Search for all list items between baseline and LOC
2578 (while (and (< (point) first
)
2579 (re-search-forward markdown-regex-list first t
))
2580 (setq pre-regexp
(format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels
))))
2583 ;; Make sure this is not a header or hr
2584 ((markdown-new-baseline-p) (setq levels nil
))
2585 ;; Make sure this is not a line from a pre block
2586 ((looking-at-p pre-regexp
))
2587 ;; If not, then update levels
2589 (setq indent
(current-indentation))
2590 (setq levels
(markdown-update-list-levels (match-string 2)
2595 (defun markdown-prev-list-item (level)
2596 "Search backward from point for a list item with indentation LEVEL.
2597 Set point to the beginning of the item, and return point, or nil
2599 (let (bounds indent prev
)
2602 (setq indent
(current-indentation))
2606 ((and (looking-at-p markdown-regex-list
)
2607 (setq bounds
(markdown-cur-list-item-bounds)))
2609 ;; Stop and return point at item of lesser or equal indentation
2610 ((<= (nth 3 bounds
) level
)
2613 ;; Stop at beginning of buffer
2614 ((bobp) (setq prev nil
))
2615 ;; Continue at item with greater indentation
2616 ((> (nth 3 bounds
) level
) t
)))
2617 ;; Stop at beginning of buffer
2618 ((bobp) (setq prev nil
))
2619 ;; Continue if current line is blank
2620 ((markdown-cur-line-blank-p) t
)
2621 ;; Continue while indentation is the same or greater
2622 ((>= indent level
) t
)
2623 ;; Stop if current indentation is less than list item
2624 ;; and the next is blank
2625 ((and (< indent level
)
2626 (markdown-next-line-blank-p))
2629 ((looking-at-p markdown-regex-header
) (setq prev nil
))
2630 ;; Stop at a horizontal rule
2631 ((looking-at-p markdown-regex-hr
) (setq prev nil
))
2632 ;; Otherwise, continue.
2635 (setq indent
(current-indentation)))
2638 (defun markdown-next-list-item (level)
2639 "Search forward from point for the next list item with indentation LEVEL.
2640 Set point to the beginning of the item, and return point, or nil
2642 (let (bounds indent next
)
2645 (setq indent
(current-indentation))
2648 ;; Stop at end of the buffer.
2650 ;; Continue if the current line is blank
2651 ((markdown-cur-line-blank-p) t
)
2653 ((and (looking-at-p markdown-regex-list
)
2654 (setq bounds
(markdown-cur-list-item-bounds)))
2656 ;; Continue at item with greater indentation
2657 ((> (nth 3 bounds
) level
) t
)
2658 ;; Stop and return point at item of equal indentation
2659 ((= (nth 3 bounds
) level
)
2662 ;; Stop and return nil at item with lesser indentation
2663 ((< (nth 3 bounds
) level
)
2666 ;; Continue while indentation is the same or greater
2667 ((>= indent level
) t
)
2668 ;; Stop if current indentation is less than list item
2669 ;; and the previous line was blank.
2670 ((and (< indent level
)
2671 (markdown-prev-line-blank-p))
2674 ((looking-at-p markdown-regex-header
) (setq next nil
))
2675 ;; Stop at a horizontal rule
2676 ((looking-at-p markdown-regex-hr
) (setq next nil
))
2677 ;; Otherwise, continue.
2680 (setq indent
(current-indentation)))
2683 (defun markdown-cur-list-item-end (level)
2684 "Move to the end of the current list item with nonlist indentation LEVEL.
2685 If the point is not in a list item, do nothing."
2688 (setq indent
(current-indentation))
2691 ;; Stop at end of the buffer.
2693 ;; Continue if the current line is blank
2694 ((markdown-cur-line-blank-p) t
)
2695 ;; Continue while indentation is the same or greater
2696 ((>= indent level
) t
)
2697 ;; Stop if current indentation is less than list item
2698 ;; and the previous line was blank.
2699 ((and (< indent level
)
2700 (markdown-prev-line-blank-p))
2702 ;; Stop at a new list item of the same or lesser indentation
2703 ((looking-at-p markdown-regex-list
) nil
)
2705 ((looking-at-p markdown-regex-header
) nil
)
2706 ;; Stop at a horizontal rule
2707 ((looking-at-p markdown-regex-hr
) nil
)
2708 ;; Otherwise, continue.
2711 (setq indent
(current-indentation)))
2712 ;; Don't skip over whitespace for empty list items (marker and
2713 ;; whitespace only), just move to end of whitespace.
2714 (if (looking-back (concat markdown-regex-list
"\\s-*") nil
)
2715 (goto-char (match-end 3))
2716 (skip-syntax-backward "-"))))
2718 (defun markdown-cur-list-item-bounds ()
2719 "Return bounds and indentation of the current list item.
2720 Return a list of the form (begin end indent nonlist-indent marker).
2721 If the point is not inside a list item, return nil.
2722 Leave match data intact for `markdown-regex-list'."
2723 (let (cur prev-begin prev-end indent nonlist-indent marker
)
2724 ;; Store current location
2726 ;; Verify that cur is between beginning and end of item
2729 (when (re-search-backward markdown-regex-list nil t
)
2730 (setq prev-begin
(match-beginning 0))
2731 (setq indent
(length (match-string 1)))
2732 (setq nonlist-indent
(length (match-string 0)))
2733 (setq marker
(concat (match-string 2) (match-string 3)))
2735 (markdown-cur-list-item-end nonlist-indent
)
2736 (setq prev-end
(point)))
2737 (when (and (>= cur prev-begin
)
2740 (list prev-begin prev-end indent nonlist-indent marker
))))))
2742 (defun markdown-bounds-of-thing-at-point (thing)
2743 "Call `bounds-of-thing-at-point' for THING with slight modifications.
2744 Does not include trailing newlines when THING is 'line. Handles the
2745 end of buffer case by setting both endpoints equal to the value of
2746 `point-max', since an empty region will trigger empty markup insertion.
2747 Return bounds of form (beg . end) if THING is found, or nil otherwise."
2748 (let* ((bounds (bounds-of-thing-at-point thing
))
2752 (when (eq thing
'line
)
2753 (cond ((and (eobp) (markdown-cur-line-blank-p))
2755 ((char-equal (char-before b
) ?\^J
)
2759 (defun markdown-reference-definition (reference)
2760 "Find out whether Markdown REFERENCE is defined.
2761 REFERENCE should not include the square brackets.
2762 When REFERENCE is defined, return a list of the form (text start end)
2763 containing the definition text itself followed by the start and end
2764 locations of the text. Otherwise, return nil.
2765 Leave match data for `markdown-regex-reference-definition'
2766 intact additional processing."
2767 (let ((reference (downcase reference
)))
2769 (goto-char (point-min))
2771 (while (re-search-forward markdown-regex-reference-definition nil t
)
2772 (when (string= reference
(downcase (match-string-no-properties 2)))
2774 (list (match-string-no-properties 5)
2775 (match-beginning 5) (match-end 5)))))))))
2777 (defun markdown-get-defined-references ()
2778 "Return a list of all defined reference labels (not including square brackets)."
2780 (goto-char (point-min))
2782 (while (re-search-forward markdown-regex-reference-definition nil t
)
2783 (let ((target (match-string-no-properties 2)))
2784 (cl-pushnew target refs
:test
#'equal
)))
2787 (defun markdown-inline-code-at-point ()
2788 "Return non-nil if the point is at an inline code fragment.
2789 Return nil otherwise. Set match data according to
2790 `markdown-match-code' upon success.
2791 This function searches the block for a code fragment that
2792 contains the point using `markdown-match-code'. We do this
2793 because `thing-at-point-looking-at' does not work reliably with
2794 `markdown-regex-code'.
2796 The match data is set as follows:
2797 Group 1 matches the opening backticks.
2798 Group 2 matches the code fragment itself, without backticks.
2799 Group 3 matches the closing backticks."
2801 (let ((old-point (point))
2802 (end-of-block (progn (markdown-end-of-block) (point)))
2804 (markdown-beginning-of-block)
2805 (while (and (markdown-match-code end-of-block
)
2807 (< (match-end 0) old-point
)))
2808 (and found
; matched something
2809 (<= (match-beginning 0) old-point
) ; match contains old-point
2810 (>= (match-end 0) old-point
)))))
2812 (defun markdown-inline-code-at-point-p ()
2813 "Return non-nil if there is inline code at the point.
2814 This is a predicate function counterpart to
2815 `markdown-inline-code-at-point' which does not modify the match
2816 data. See `markdown-code-block-at-point-p' for code blocks."
2817 (save-match-data (markdown-inline-code-at-point)))
2819 (make-obsolete 'markdown-code-at-point-p
'markdown-inline-code-at-point-p
"2017-05-10")
2821 (defun markdown-code-block-at-pos (pos)
2822 "Return match data list if there is a code block at POS.
2823 This includes pre blocks, tilde-fenced code blocks, and GFM
2824 quoted code blocks. Return nil otherwise."
2825 (or (get-text-property pos
'markdown-pre
)
2826 (markdown-get-enclosing-fenced-block-construct pos
)
2827 ;; polymode removes text properties set by markdown-mode, so
2828 ;; check if `poly-markdown-mode' is active and whether the
2829 ;; `chunkmode' property is non-nil at POS.
2830 (and (bound-and-true-p poly-markdown-mode
)
2831 (get-text-property pos
'chunkmode
))))
2833 (defun markdown-code-block-at-point ()
2834 "Return match data if the point is inside a code block.
2835 This includes pre blocks, tilde-fenced code blocks, and
2836 GFM quoted code blocks. Calls `markdown-code-block-at-pos'."
2837 (markdown-code-block-at-pos (point)))
2839 (defun markdown-code-block-at-point-p ()
2840 "Return non-nil if there is a code block at the point.
2841 This includes pre blocks, tilde-fenced code blocks, and GFM
2842 quoted code blocks. This is a predicate function counterpart to
2843 `markdown-code-block-at-point' which does not modify the match
2844 data. See `markdown-inline-code-at-point-p' for inline code."
2845 (save-match-data (markdown-code-block-at-point)))
2848 ;;; Markdown Font Lock Matching Functions =====================================
2850 (defun markdown-range-property-any (begin end prop prop-values
)
2851 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
2852 Also returns t if PROP is a list containing one of the PROP-VALUES.
2853 Return nil otherwise."
2856 (dolist (loc (number-sequence begin end
))
2857 (when (setq props
(get-char-property loc prop
))
2858 (cond ((listp props
)
2859 ;; props is a list, check for membership
2860 (dolist (val prop-values
)
2861 (when (memq val props
) (throw 'found loc
))))
2863 ;; props is a scalar, check for equality
2864 (dolist (val prop-values
)
2865 (when (eq val props
) (throw 'found loc
))))))))))
2867 (defun markdown-range-properties-exist (begin end props
)
2869 for loc in
(number-sequence begin end
)
2873 (cl-some (lambda (prop) (get-char-property loc prop
)) props
)))
2874 finally return result
))
2876 (defun markdown-match-inline-generic (regex last
)
2877 "Match inline REGEX from the point to LAST."
2878 (when (re-search-forward regex last t
)
2879 (let ((bounds (markdown-code-block-at-pos (match-beginning 1))))
2881 ;; Not in a code block: keep match data and return t when in bounds
2882 (<= (match-end 0) last
)
2883 ;; In code block: move past it and recursively search again
2884 (when (< (goto-char (nth 1 bounds
)) last
)
2885 (markdown-match-inline-generic regex last
))))))
2887 (defun markdown-match-code (last)
2888 "Match inline code fragments from point to LAST."
2891 (when (markdown-match-inline-generic markdown-regex-code last
)
2892 (set-match-data (list (match-beginning 1) (match-end 1)
2893 (match-beginning 2) (match-end 2)
2894 (match-beginning 3) (match-end 3)
2895 (match-beginning 4) (match-end 4)))
2896 (goto-char (1+ (match-end 0)))))
2898 (defun markdown-match-bold (last)
2899 "Match inline bold from the point to LAST."
2900 (when (markdown-match-inline-generic markdown-regex-bold last
)
2901 (let ((begin (match-beginning 2)) (end (match-end 2)))
2903 ((markdown-range-property-any
2904 begin end
'face
(list markdown-inline-code-face
2905 markdown-math-face
))
2906 (goto-char (1+ (match-end 0)))
2907 (markdown-match-bold last
))
2909 (set-match-data (list (match-beginning 2) (match-end 2)
2910 (match-beginning 3) (match-end 3)
2911 (match-beginning 4) (match-end 4)
2912 (match-beginning 5) (match-end 5)))
2913 (goto-char (1+ (match-end 0))))))))
2915 (defun markdown-match-italic (last)
2916 "Match inline italics from the point to LAST."
2917 (let ((regex (if (eq major-mode
'gfm-mode
)
2918 markdown-regex-gfm-italic markdown-regex-italic
)))
2919 (when (markdown-match-inline-generic regex last
)
2920 (let ((begin (match-beginning 1)) (end (match-end 1)))
2922 ((markdown-range-property-any
2923 begin begin
'face
(list markdown-url-face
))
2924 ;; Italics shouldn't begin inside a URL due to an underscore
2925 (goto-char (min (1+ (match-end 0)) last
))
2926 (markdown-match-italic last
))
2927 ((markdown-range-property-any
2928 begin end
'face
(list markdown-inline-code-face
2931 markdown-math-face
))
2932 (goto-char (1+ (match-end 0)))
2933 (markdown-match-italic last
))
2935 (set-match-data (list (match-beginning 1) (match-end 1)
2936 (match-beginning 2) (match-end 2)
2937 (match-beginning 3) (match-end 3)
2938 (match-beginning 4) (match-end 4)))
2939 (goto-char (1+ (match-end 0)))))))))
2941 (defun markdown-match-math-generic (regex last
)
2942 "Match REGEX from point to LAST.
2943 REGEX is either `markdown-regex-math-inline-single' for matching
2944 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
2945 (when (and markdown-enable-math
(markdown-match-inline-generic regex last
))
2946 (let ((begin (match-beginning 1)) (end (match-end 1)))
2948 (if (or (markdown-range-property-any
2949 begin end
'face
(list markdown-inline-code-face
2950 markdown-bold-face
))
2951 (markdown-range-properties-exist
2953 (markdown-get-fenced-block-middle-properties)))
2954 (markdown-match-math-generic regex last
)
2956 (goto-char (1+ (match-end 0)))))))
2958 (defun markdown-match-math-single (last)
2959 "Match single quoted $..$ math from point to LAST."
2960 (markdown-match-math-generic markdown-regex-math-inline-single last
))
2962 (defun markdown-match-math-double (last)
2963 "Match double quoted $$..$$ math from point to LAST."
2964 (markdown-match-math-generic markdown-regex-math-inline-double last
))
2966 (defun markdown-match-propertized-text (property last
)
2967 "Match text with PROPERTY from point to LAST.
2968 Restore match data previously stored in PROPERTY."
2969 (let ((saved (get-text-property (point) property
))
2972 (setq pos
(next-single-char-property-change (point) property nil last
))
2973 (setq saved
(get-text-property pos property
)))
2975 (set-match-data saved
)
2976 ;; Step at least one character beyond point. Otherwise
2977 ;; `font-lock-fontify-keywords-region' infloops.
2978 (goto-char (min (1+ (max (match-end 0) (point)))
2982 (defun markdown-match-pre-blocks (last)
2983 "Match preformatted blocks from point to LAST.
2984 Use data stored in 'markdown-pre text property during syntax
2986 (markdown-match-propertized-text 'markdown-pre last
))
2988 (defun markdown-match-gfm-code-blocks (last)
2989 "Match GFM quoted code blocks from point to LAST.
2990 Use data stored in 'markdown-gfm-code text property during syntax
2992 (markdown-match-propertized-text 'markdown-gfm-code last
))
2994 (defun markdown-match-gfm-open-code-blocks (last)
2995 (markdown-match-propertized-text 'markdown-gfm-block-begin last
))
2997 (defun markdown-match-gfm-close-code-blocks (last)
2998 (markdown-match-propertized-text 'markdown-gfm-block-end last
))
3000 (defun markdown-match-fenced-code-blocks (last)
3001 "Match fenced code blocks from the point to LAST."
3002 (markdown-match-propertized-text 'markdown-fenced-code last
))
3004 (defun markdown-match-fenced-start-code-block (last)
3005 (markdown-match-propertized-text 'markdown-tilde-fence-begin last
))
3007 (defun markdown-match-fenced-end-code-block (last)
3008 (markdown-match-propertized-text 'markdown-tilde-fence-end last
))
3010 (defun markdown-match-blockquotes (last)
3011 "Match blockquotes from point to LAST.
3012 Use data stored in 'markdown-blockquote text property during syntax
3014 (markdown-match-propertized-text 'markdown-blockquote last
))
3016 (defun markdown-match-heading-1-setext (last)
3017 "Match level 1 setext headings from point to LAST."
3018 (markdown-match-propertized-text 'markdown-heading-1-setext last
))
3020 (defun markdown-match-heading-2-setext (last)
3021 "Match level 2 setext headings from point to LAST."
3022 (markdown-match-propertized-text 'markdown-heading-2-setext last
))
3024 (defun markdown-match-heading-1-atx (last)
3025 "Match level 1 ATX headings from point to LAST."
3026 (markdown-match-propertized-text 'markdown-heading-1-atx last
))
3028 (defun markdown-match-heading-2-atx (last)
3029 "Match level 2 ATX headings from point to LAST."
3030 (markdown-match-propertized-text 'markdown-heading-2-atx last
))
3032 (defun markdown-match-heading-3-atx (last)
3033 "Match level 3 ATX headings from point to LAST."
3034 (markdown-match-propertized-text 'markdown-heading-3-atx last
))
3036 (defun markdown-match-heading-4-atx (last)
3037 "Match level 4 ATX headings from point to LAST."
3038 (markdown-match-propertized-text 'markdown-heading-4-atx last
))
3040 (defun markdown-match-heading-5-atx (last)
3041 "Match level 5 ATX headings from point to LAST."
3042 (markdown-match-propertized-text 'markdown-heading-5-atx last
))
3044 (defun markdown-match-heading-6-atx (last)
3045 "Match level 6 ATX headings from point to LAST."
3046 (markdown-match-propertized-text 'markdown-heading-6-atx last
))
3048 (defun markdown-match-hr (last)
3049 "Match horizontal rules comments from the point to LAST."
3050 (while (and (re-search-forward markdown-regex-hr last t
)
3051 (or (markdown-on-heading-p)
3052 (markdown-code-block-at-point))
3053 (< (match-end 0) last
))
3056 (cond ((looking-at-p markdown-regex-hr
)
3061 (defun markdown-match-comments (last)
3062 "Match HTML comments from the point to LAST."
3063 (when (and (skip-syntax-forward "^<" last
))
3064 (let ((beg (point)))
3065 (when (and (skip-syntax-forward "^>" last
) (< (point) last
))
3067 (set-match-data (list beg
(point)))
3070 (defun markdown-get-match-boundaries (start-header end-header last
&optional pos
)
3072 (goto-char (or pos
(point-min)))
3074 with cur-result
= nil
3075 and st-hdr
= (or start-header
"\\`")
3076 and end-hdr
= (or end-header
"\n\n\\|\n\\'\\|\\'")
3077 while
(and (< (point) last
)
3078 (re-search-forward st-hdr last t
)
3080 (setq cur-result
(match-data))
3081 (re-search-forward end-hdr nil t
)))
3082 collect
(list cur-result
(match-data)))))
3084 (defvar markdown-conditional-search-function
#'re-search-forward
3085 "Conditional search function used in `markdown-search-until-condition'.
3086 Made into a variable to allow for dynamic let-binding.")
3088 (defun markdown-search-until-condition (condition &rest args
)
3090 (while (and (not ret
) (apply markdown-conditional-search-function args
))
3091 (setq ret
(funcall condition
)))
3094 (defun markdown-match-generic-metadata
3095 (regexp last
&optional start-header end-header
)
3096 "Match generic metadata specified by REGEXP from the point to LAST.
3097 If START-HEADER is nil, we assume metadata can only occur at the
3098 very top of a file (\"\\`\"). If END-HEADER is nil, we assume it
3100 (let* ((header-bounds
3101 (markdown-get-match-boundaries start-header end-header last
))
3103 (cl-find-if ; just take first if multiple
3104 (lambda (match-bounds)
3105 (cl-destructuring-bind (begin end
) (cl-second match-bounds
)
3106 (and (< (point) begin
)
3107 (save-excursion (re-search-forward regexp end t
)))))
3110 (when enclosing-header
(cl-second (cl-first enclosing-header
))))
3112 (when enclosing-header
(cl-first (cl-second enclosing-header
)))))
3113 (cond ((null enclosing-header
)
3114 ;; Don't match anything outside of a header.
3116 ((markdown-search-until-condition
3117 (lambda () (> (point) header-begin
)) regexp
(min last header-end
) t
)
3118 ;; If a metadata item is found, it may span several lines.
3119 (let ((key-beginning (match-beginning 1))
3120 (key-end (match-end 1))
3121 (markup-begin (match-beginning 2))
3122 (markup-end (match-end 2))
3123 (value-beginning (match-beginning 3)))
3124 (set-match-data (list key-beginning
(point) ; complete metadata
3125 key-beginning key-end
; key
3126 markup-begin markup-end
; markup
3127 value-beginning
(point))) ; value
3131 (defun markdown-match-declarative-metadata (last)
3132 "Match declarative metadata from the point to LAST."
3133 (markdown-match-generic-metadata markdown-regex-declarative-metadata last
))
3135 (defun markdown-match-pandoc-metadata (last)
3136 "Match Pandoc metadata from the point to LAST."
3137 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last
))
3139 (defun markdown-match-yaml-metadata-begin (last)
3140 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last
))
3142 (defun markdown-match-yaml-metadata-end (last)
3143 (markdown-match-propertized-text 'markdown-yaml-metadata-end last
))
3145 (defun markdown-match-yaml-metadata-key (last)
3146 (markdown-match-propertized-text 'markdown-metadata-key last
))
3149 ;;; Syntax Table ==============================================================
3151 (defvar markdown-mode-syntax-table
3152 (let ((tab (make-syntax-table text-mode-syntax-table
)))
3153 (modify-syntax-entry ?
\" "." tab
)
3155 "Syntax table for `markdown-mode'.")
3158 ;;; Element Insertion =========================================================
3160 (defun markdown-ensure-blank-line-before ()
3161 "If previous line is not already blank, insert a blank line before point."
3162 (unless (bolp) (insert "\n"))
3163 (unless (or (bobp) (looking-back "\n\\s-*\n" nil
)) (insert "\n")))
3165 (defun markdown-ensure-blank-line-after ()
3166 "If following line is not already blank, insert a blank line after point.
3167 Return the point where it was originally."
3169 (unless (eolp) (insert "\n"))
3170 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
3172 (defun markdown-wrap-or-insert (s1 s2
&optional thing beg end
)
3173 "Insert the strings S1 and S2, wrapping around region or THING.
3174 If a region is specified by the optional BEG and END arguments,
3175 wrap the strings S1 and S2 around that region.
3176 If there is an active region, wrap the strings S1 and S2 around
3177 the region. If there is not an active region but the point is at
3178 THING, wrap that thing (which defaults to word). Otherwise, just
3179 insert S1 and S2 and place the cursor in between. Return the
3180 bounds of the entire wrapped string, or nil if nothing was wrapped
3181 and S1 and S2 were only inserted."
3182 (let (a b bounds new-point
)
3188 new-point
(+ (point) (length s1
))))
3190 ((markdown-use-region-p)
3191 (setq a
(region-beginning)
3193 new-point
(+ (point) (length s1
))))
3194 ;; Thing (word) at point
3195 ((setq bounds
(markdown-bounds-of-thing-at-point (or thing
'word
)))
3196 (setq a
(car bounds
)
3198 new-point
(+ (point) (length s1
))))
3199 ;; No active region and no word
3207 (when new-point
(goto-char new-point
))
3210 (setq b
(+ b
(length s1
) (length s2
)))
3213 (defun markdown-point-after-unwrap (cur prefix suffix
)
3214 "Return desired position of point after an unwrapping operation.
3215 CUR gives the position of the point before the operation.
3216 Additionally, two cons cells must be provided. PREFIX gives the
3217 bounds of the prefix string and SUFFIX gives the bounds of the
3219 (cond ((< cur
(cdr prefix
)) (car prefix
))
3220 ((< cur
(car suffix
)) (- cur
(- (cdr prefix
) (car prefix
))))
3221 ((<= cur
(cdr suffix
))
3222 (- cur
(+ (- (cdr prefix
) (car prefix
))
3223 (- cur
(car suffix
)))))
3226 (defun markdown-unwrap-thing-at-point (regexp all text
)
3227 "Remove prefix and suffix of thing at point and reposition the point.
3228 When the thing at point matches REGEXP, replace the subexpression
3229 ALL with the string in subexpression TEXT. Reposition the point
3230 in an appropriate location accounting for the removal of prefix
3231 and suffix strings. Return new bounds of string from group TEXT.
3232 When REGEXP is nil, assumes match data is already set."
3233 (when (or (null regexp
)
3234 (thing-at-point-looking-at regexp
))
3236 (prefix (cons (match-beginning all
) (match-beginning text
)))
3237 (suffix (cons (match-end text
) (match-end all
)))
3238 (bounds (cons (match-beginning text
) (match-end text
))))
3239 ;; Replace the thing at point
3240 (replace-match (match-string text
) t t nil all
)
3241 ;; Reposition the point
3242 (goto-char (markdown-point-after-unwrap cur prefix suffix
))
3244 (setq bounds
(cons (car prefix
)
3245 (- (cdr bounds
) (- (cdr prefix
) (car prefix
))))))))
3247 (defun markdown-unwrap-things-in-region (beg end regexp all text
)
3248 "Remove prefix and suffix of all things in region from BEG to END.
3249 When a thing in the region matches REGEXP, replace the
3250 subexpression ALL with the string in subexpression TEXT.
3251 Return a cons cell containing updated bounds for the region."
3254 (let ((removed 0) len-all len-text
)
3255 (while (re-search-forward regexp
(- end removed
) t
)
3256 (setq len-all
(length (match-string-no-properties all
)))
3257 (setq len-text
(length (match-string-no-properties text
)))
3258 (setq removed
(+ removed
(- len-all len-text
)))
3259 (replace-match (match-string text
) t t nil all
))
3260 (cons beg
(- end removed
)))))
3262 (defun markdown-insert-hr (arg)
3263 "Insert or replace a horizonal rule.
3264 By default, use the first element of `markdown-hr-strings'. When
3265 ARG is non-nil, as when given a prefix, select a different
3266 element as follows. When prefixed with \\[universal-argument],
3267 use the last element of `markdown-hr-strings' instead. When
3268 prefixed with an integer from 1 to the length of
3269 `markdown-hr-strings', use the element in that position instead."
3271 (when (thing-at-point-looking-at markdown-regex-hr
)
3272 (delete-region (match-beginning 0) (match-end 0)))
3273 (markdown-ensure-blank-line-before)
3274 (cond ((equal arg
'(4))
3275 (insert (car (reverse markdown-hr-strings
))))
3276 ((and (integerp arg
) (> arg
0)
3277 (<= arg
(length markdown-hr-strings
)))
3278 (insert (nth (1- arg
) markdown-hr-strings
)))
3280 (insert (car markdown-hr-strings
))))
3281 (markdown-ensure-blank-line-after))
3283 (defun markdown-insert-bold ()
3284 "Insert markup to make a region or word bold.
3285 If there is an active region, make the region bold. If the point
3286 is at a non-bold word, make the word bold. If the point is at a
3287 bold word or phrase, remove the bold markup. Otherwise, simply
3288 insert bold delimiters and place the cursor in between them."
3290 (let ((delim (if markdown-bold-underscore
"__" "**")))
3291 (if (markdown-use-region-p)
3293 (let ((bounds (markdown-unwrap-things-in-region
3294 (region-beginning) (region-end)
3295 markdown-regex-bold
2 4)))
3296 (markdown-wrap-or-insert delim delim nil
(car bounds
) (cdr bounds
)))
3297 ;; Bold markup removal, bold word at point, or empty markup insertion
3298 (if (thing-at-point-looking-at markdown-regex-bold
)
3299 (markdown-unwrap-thing-at-point nil
2 4)
3300 (markdown-wrap-or-insert delim delim
'word nil nil
)))))
3302 (defun markdown-insert-italic ()
3303 "Insert markup to make a region or word italic.
3304 If there is an active region, make the region italic. If the point
3305 is at a non-italic word, make the word italic. If the point is at an
3306 italic word or phrase, remove the italic markup. Otherwise, simply
3307 insert italic delimiters and place the cursor in between them."
3309 (let ((delim (if markdown-italic-underscore
"_" "*")))
3310 (if (markdown-use-region-p)
3312 (let ((bounds (markdown-unwrap-things-in-region
3313 (region-beginning) (region-end)
3314 markdown-regex-italic
1 3)))
3315 (markdown-wrap-or-insert delim delim nil
(car bounds
) (cdr bounds
)))
3316 ;; Italic markup removal, italic word at point, or empty markup insertion
3317 (if (thing-at-point-looking-at markdown-regex-italic
)
3318 (markdown-unwrap-thing-at-point nil
1 3)
3319 (markdown-wrap-or-insert delim delim
'word nil nil
)))))
3321 (defun markdown-insert-strike-through ()
3322 "Insert markup to make a region or word strikethrough.
3323 If there is an active region, make the region strikethrough. If the point
3324 is at a non-bold word, make the word strikethrough. If the point is at a
3325 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
3326 simply insert bold delimiters and place the cursor in between them."
3329 (if (markdown-use-region-p)
3331 (let ((bounds (markdown-unwrap-things-in-region
3332 (region-beginning) (region-end)
3333 markdown-regex-strike-through
2 4)))
3334 (markdown-wrap-or-insert delim delim nil
(car bounds
) (cdr bounds
)))
3335 ;; Strikethrough markup removal, strikethrough word at point, or empty markup insertion
3336 (if (thing-at-point-looking-at markdown-regex-strike-through
)
3337 (markdown-unwrap-thing-at-point nil
2 4)
3338 (markdown-wrap-or-insert delim delim
'word nil nil
)))))
3340 (defun markdown-insert-code ()
3341 "Insert markup to make a region or word an inline code fragment.
3342 If there is an active region, make the region an inline code
3343 fragment. If the point is at a word, make the word an inline
3344 code fragment. Otherwise, simply insert code delimiters and
3345 place the cursor in between them."
3347 (if (markdown-use-region-p)
3349 (let ((bounds (markdown-unwrap-things-in-region
3350 (region-beginning) (region-end)
3351 markdown-regex-code
1 3)))
3352 (markdown-wrap-or-insert "`" "`" nil
(car bounds
) (cdr bounds
)))
3353 ;; Code markup removal, code markup for word, or empty markup insertion
3354 (if (markdown-inline-code-at-point)
3355 (markdown-unwrap-thing-at-point nil
0 2)
3356 (markdown-wrap-or-insert "`" "`" 'word nil nil
))))
3358 (defun markdown-insert-kbd ()
3359 "Insert markup to wrap region or word in <kbd> tags.
3360 If there is an active region, use the region. If the point is at
3361 a word, use the word. Otherwise, simply insert <kbd> tags and
3362 place the cursor in between them."
3364 (if (markdown-use-region-p)
3366 (let ((bounds (markdown-unwrap-things-in-region
3367 (region-beginning) (region-end)
3368 markdown-regex-kbd
0 2)))
3369 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil
(car bounds
) (cdr bounds
)))
3370 ;; Markup removal, markup for word, or empty markup insertion
3371 (if (thing-at-point-looking-at markdown-regex-kbd
)
3372 (markdown-unwrap-thing-at-point nil
0 2)
3373 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil
))))
3375 (defun markdown-insert-inline-link (text url
&optional title
)
3376 "Insert an inline link with TEXT pointing to URL.
3377 Optionally, the user can provide a TITLE."
3378 (let ((cur (point)))
3379 (setq title
(and title
(concat " \"" title
"\"")))
3380 (insert (concat "[" text
"](" url title
")"))
3381 (cond ((not text
) (goto-char (+ 1 cur
)))
3382 ((not url
) (goto-char (+ 3 (length text
) cur
))))))
3384 (defun markdown-insert-inline-link-dwim ()
3385 "Insert an inline link of the form [link](url) at point.
3386 If there is an active region, the text in the region will be used
3387 as the URL, if it appears to be a URL, or else as the link text.
3388 If the point is at a URL, use it to create a new link. If the
3389 point is at a reference link, convert it to an inline link. If
3390 the point is at a word, use the word as the link text. In these
3391 cases, the point will be left at the position for inserting a
3392 URL. If there is no active region and the point is not at word,
3393 simply insert link markup and place the point in the position to
3397 ;; If there is an active region, remove existing links in the
3398 ;; region and use resulting region as link text for a new link.
3399 ((markdown-use-region-p)
3400 (let* ((bounds (markdown-unwrap-things-in-region
3401 (region-beginning) (region-end)
3402 markdown-regex-link-inline
0 3))
3403 (text (buffer-substring (car bounds
) (cdr bounds
))))
3404 (delete-region (car bounds
) (cdr bounds
))
3405 (markdown-insert-inline-link text nil
)))
3406 ;; If there is an inline link at the point, remove it and add the
3407 ;; link text to the kill ring.
3408 ((thing-at-point-looking-at markdown-regex-link-inline
)
3409 (kill-new (match-string 3))
3410 (delete-region (match-beginning 0) (match-end 0)))
3411 ;; If there is an angle URL at the point, use it for a new link.
3412 ((thing-at-point-looking-at markdown-regex-angle-uri
)
3413 (let ((url (match-string 2)))
3414 (delete-region (match-beginning 0) (match-end 0))
3415 (markdown-insert-inline-link nil url
)))
3416 ;; If there is a plain URL at the point, use it for a new link.
3417 ((thing-at-point-looking-at markdown-regex-uri
)
3418 (let ((url (match-string 0)))
3419 (delete-region (match-beginning 0) (match-end 0))
3420 (markdown-insert-inline-link nil url
)))
3421 ;; If there is a reference link at point, convert to inline link.
3422 ((thing-at-point-looking-at markdown-regex-link-reference
)
3423 (let ((beg (match-beginning 0))
3425 (text (match-string 3))
3426 (url (markdown-link-link)))
3427 (delete-region beg end
)
3428 (markdown-insert-inline-link text url
)))
3429 ;; Otherwise, insert a link
3430 (t (let ((bounds (markdown-wrap-or-insert "[" "]()")))
3432 (goto-char (- (cdr bounds
) 1)))))))
3434 (defun markdown-insert-reference-link (text label
&optional url title
)
3435 "Insert a reference link and, optionally, a reference definition.
3436 The link TEXT will be inserted followed by the optional LABEL.
3437 If a URL is given, also insert a definition for the reference
3438 LABEL according to `markdown-reference-location'. If a TITLE is
3439 given, it will be added to the end of the reference definition
3440 and will be used to populate the title attribute when converted
3441 to XHTML. If URL is nil, insert only the link portion (for
3442 example, when a reference label is already defined)."
3443 (insert (concat "[" text
"][" label
"]"))
3445 (markdown-insert-reference-definition
3446 (if (string-equal label
"") text label
)
3449 (defun markdown-insert-reference-definition (label &optional url title
)
3450 "Add definition for reference LABEL with URL and TITLE.
3451 LABEL is a Markdown reference label without square brackets.
3452 URL and TITLE are optional. When given, the TITLE will
3453 be used to populate the title attribute when converted to XHTML."
3454 ;; END specifies where to leave the point upon return
3455 (let ((end (point)))
3456 (cl-case markdown-reference-location
3457 (end (goto-char (point-max)))
3458 (immediately (markdown-end-of-block))
3459 (header (markdown-end-of-defun)))
3460 (unless (markdown-cur-line-blank-p) (insert "\n"))
3461 (insert "\n[" label
"]: ")
3464 ;; When no URL is given, leave cursor at END following the colon
3466 (when (> (length title
) 0)
3467 (insert " \"" title
"\""))
3468 (unless (looking-at-p "\n")
3473 (substitute-command-keys
3474 "Defined reference [%s], press \\[markdown-jump] to jump there")
3477 (defun markdown-insert-reference-link-dwim ()
3478 "Insert a reference link of the form [text][label] at point.
3479 If there is an active region, the text in the region will be used
3480 as the link text. If the point is at an inline link, it will be
3481 converted to a reference link. If the point is at a word, it will
3482 be used as the link text. Otherwise, the link text will be read from
3483 the minibuffer. The link label will be read from the minibuffer in
3484 both cases, with completion from the set of currently defined
3485 references. To create an implicit reference link, press RET to
3486 accept the default, an empty label. If the entered referenced
3487 label is not defined, additionally prompt for the URL
3488 and (optional) title. The reference definition is placed at the
3489 location determined by `markdown-reference-location'."
3491 (let* ((defined-labels (markdown-get-defined-references))
3492 (switch (thing-at-point-looking-at markdown-regex-link-inline
))
3493 (bounds (cond ((markdown-use-region-p)
3494 (cons (region-beginning) (region-end)))
3496 (cons (match-beginning 0) (match-end 0)))
3498 (markdown-bounds-of-thing-at-point 'word
))))
3499 (text (cond (switch (match-string 3))
3500 (bounds (buffer-substring (car bounds
) (cdr bounds
)))
3501 (t (read-string "Link Text: "))))
3502 (label (completing-read
3503 "Link Label (default: none): " defined-labels
3504 nil nil nil
'markdown-reference-label-history nil
))
3505 (ref (save-match-data
3506 (markdown-reference-definition
3507 (if (> (length label
) 0) label text
))))
3508 (url (cond (ref nil
)
3509 (switch (match-string 6))
3510 (t (read-string "Link URL: "))))
3512 ((= (length url
) 0) nil
)
3513 (switch (if (> (length (match-string 7)) 2)
3514 (substring (match-string 7) 1 -
1)
3516 (t (read-string "Link Title (optional): ")))))
3517 (when bounds
(delete-region (car bounds
) (cdr bounds
)))
3518 (markdown-insert-reference-link text label url title
)))
3520 (defun markdown-insert-uri ()
3521 "Insert markup for an inline URI.
3522 If there is an active region, use it as the URI. If the point is
3523 at a URI, wrap it with angle brackets. If the point is at an
3524 inline URI, remove the angle brackets. Otherwise, simply insert
3525 angle brackets place the point between them."
3527 (if (markdown-use-region-p)
3529 (let ((bounds (markdown-unwrap-things-in-region
3530 (region-beginning) (region-end)
3531 markdown-regex-angle-uri
0 2)))
3532 (markdown-wrap-or-insert "<" ">" nil
(car bounds
) (cdr bounds
)))
3533 ;; Markup removal, URI at point, or empty markup insertion
3534 (if (thing-at-point-looking-at markdown-regex-angle-uri
)
3535 (markdown-unwrap-thing-at-point nil
0 2)
3536 (markdown-wrap-or-insert "<" ">" 'url nil nil
))))
3538 (defun markdown-insert-wiki-link ()
3539 "Insert a wiki link of the form [[WikiLink]].
3540 If there is an active region, use the region as the link text.
3541 If the point is at a word, use the word as the link text. If
3542 there is no active region and the point is not at word, simply
3543 insert link markup."
3545 (if (markdown-use-region-p)
3547 (markdown-wrap-or-insert "[[" "]]" nil
(region-beginning) (region-end))
3548 ;; Markup removal, wiki link at at point, or empty markup insertion
3549 (if (thing-at-point-looking-at markdown-regex-wiki-link
)
3550 (if (or markdown-wiki-link-alias-first
3551 (null (match-string 5)))
3552 (markdown-unwrap-thing-at-point nil
1 3)
3553 (markdown-unwrap-thing-at-point nil
1 5))
3554 (markdown-wrap-or-insert "[[" "]]"))))
3556 (defun markdown-insert-image (&optional arg
)
3557 "Insert image markup using region or word as alt text if possible.
3558 If there is an active region, use the region as the alt text. If the
3559 point is at a word, use the word as the alt text. In these cases, the
3560 point will be left at the position for inserting a URL. If there is no
3561 active region and the point is not at word, simply insert image markup and
3562 place the point in the position to enter alt text. If ARG is nil, insert
3563 inline image markup. Otherwise, insert reference image markup."
3565 (let ((bounds (if arg
3566 (markdown-wrap-or-insert "![" "][]")
3567 (markdown-wrap-or-insert "![" "]()"))))
3569 (goto-char (- (cdr bounds
) 1)))))
3571 (defun markdown-insert-reference-image ()
3572 "Insert reference-style image markup using region or word as alt text.
3573 Calls `markdown-insert-image' with prefix argument."
3575 (markdown-insert-image t
))
3577 (defun markdown-remove-header ()
3578 "Remove header markup if point is at a header.
3579 Return bounds of remaining header text if a header was removed
3582 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx
0 2)
3583 (markdown-unwrap-thing-at-point markdown-regex-header-setext
0 1)))
3585 (defun markdown-insert-header (&optional level text setext
)
3586 "Insert or replace header markup.
3587 The level of the header is specified by LEVEL and header text is
3588 given by TEXT. LEVEL must be an integer from 1 and 6, and the
3590 When TEXT is nil, the header text is obtained as follows.
3591 If there is an active region, it is used as the header text.
3592 Otherwise, the current line will be used as the header text.
3593 If there is not an active region and the point is at a header,
3594 remove the header markup and replace with level N header.
3595 Otherwise, insert empty header markup and place the cursor in
3597 The style of the header will be atx (hash marks) unless
3598 SETEXT is non-nil, in which case a setext-style (underlined)
3599 header will be inserted."
3600 (interactive "p\nsHeader text: ")
3601 (setq level
(min (max (or level
1) 1) (if setext
2 6)))
3602 ;; Determine header text if not given
3604 (if (markdown-use-region-p)
3606 (setq text
(delete-and-extract-region (region-beginning) (region-end)))
3608 (markdown-remove-header)
3609 (setq text
(delete-and-extract-region
3610 (line-beginning-position) (line-end-position)))
3611 (when (and setext
(string-match-p "^[ \t]*$" text
))
3612 (setq text
(read-string "Header text: "))))
3613 (setq text
(markdown-compress-whitespace-string text
)))
3614 ;; Insertion with given text
3615 (markdown-ensure-blank-line-before)
3618 (setq hdr
(make-string (string-width text
) (if (= level
2) ?- ?
=)))
3619 (insert text
"\n" hdr
))
3621 (setq hdr
(make-string level ?
#))
3622 (insert hdr
" " text
)
3623 (when (null markdown-asymmetric-header
) (insert " " hdr
)))))
3624 (markdown-ensure-blank-line-after)
3625 ;; Leave point at end of text
3627 (backward-char (1+ (string-width text
))))
3628 ((null markdown-asymmetric-header
)
3629 (backward-char (1+ level
)))))
3631 (defun markdown-insert-header-dwim (&optional arg setext
)
3632 "Insert or replace header markup.
3633 The level and type of the header are determined automatically by
3634 the type and level of the previous header, unless a prefix
3635 argument is given via ARG.
3636 With a numeric prefix valued 1 to 6, insert a header of the given
3637 level, with the type being determined automatically (note that
3638 only level 1 or 2 setext headers are possible).
3640 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
3641 promote the heading by one level.
3642 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
3643 demote the heading by one level.
3644 When SETEXT is non-nil, prefer setext-style headers when
3645 possible (levels one and two).
3647 When there is an active region, use it for the header text. When
3648 the point is at an existing header, change the type and level
3649 according to the rules above.
3650 Otherwise, if the line is not empty, create a header using the
3651 text on the current line as the header text.
3652 Finally, if the point is on a blank line, insert empty header
3653 markup (atx) or prompt for text (setext).
3654 See `markdown-insert-header' for more details about how the
3655 header text is determined."
3659 (when (or (thing-at-point-looking-at markdown-regex-header
)
3660 (re-search-backward markdown-regex-header nil t
))
3661 ;; level of current or previous header
3662 (setq level
(markdown-outline-level))
3663 ;; match group 1 indicates a setext header
3664 (setq setext
(match-end 1))))
3665 ;; check prefix argument
3667 ((and (equal arg
'(4)) level
(> level
1)) ;; C-u
3669 ((and (equal arg
'(16)) level
(< level
6)) ;; C-u C-u
3671 (arg ;; numeric prefix
3672 (setq level
(prefix-numeric-value arg
))))
3673 ;; setext headers must be level one or two
3674 (and level
(setq setext
(and setext
(<= level
2))))
3675 ;; insert the heading
3676 (markdown-insert-header level nil setext
)))
3678 (defun markdown-insert-header-setext-dwim (&optional arg
)
3679 "Insert or replace header markup, with preference for setext.
3680 See `markdown-insert-header-dwim' for details, including how ARG is handled."
3682 (markdown-insert-header-dwim arg t
))
3684 (defun markdown-insert-header-atx-1 ()
3685 "Insert a first level atx-style (hash mark) header.
3686 See `markdown-insert-header'."
3688 (markdown-insert-header 1 nil nil
))
3690 (defun markdown-insert-header-atx-2 ()
3691 "Insert a level two atx-style (hash mark) header.
3692 See `markdown-insert-header'."
3694 (markdown-insert-header 2 nil nil
))
3696 (defun markdown-insert-header-atx-3 ()
3697 "Insert a level three atx-style (hash mark) header.
3698 See `markdown-insert-header'."
3700 (markdown-insert-header 3 nil nil
))
3702 (defun markdown-insert-header-atx-4 ()
3703 "Insert a level four atx-style (hash mark) header.
3704 See `markdown-insert-header'."
3706 (markdown-insert-header 4 nil nil
))
3708 (defun markdown-insert-header-atx-5 ()
3709 "Insert a level five atx-style (hash mark) header.
3710 See `markdown-insert-header'."
3712 (markdown-insert-header 5 nil nil
))
3714 (defun markdown-insert-header-atx-6 ()
3715 "Insert a sixth level atx-style (hash mark) header.
3716 See `markdown-insert-header'."
3718 (markdown-insert-header 6 nil nil
))
3720 (defun markdown-insert-header-setext-1 ()
3721 "Insert a setext-style (underlined) first-level header.
3722 See `markdown-insert-header'."
3724 (markdown-insert-header 1 nil t
))
3726 (defun markdown-insert-header-setext-2 ()
3727 "Insert a setext-style (underlined) second-level header.
3728 See `markdown-insert-header'."
3730 (markdown-insert-header 2 nil t
))
3732 (defun markdown-blockquote-indentation (loc)
3733 "Return string containing necessary indentation for a blockquote at LOC.
3734 Also see `markdown-pre-indentation'."
3737 (let* ((list-level (length (markdown-calculate-list-levels)))
3739 (dotimes (_ list-level indent
)
3740 (setq indent
(concat indent
" "))))))
3742 (defun markdown-insert-blockquote ()
3743 "Start a blockquote section (or blockquote the region).
3744 If Transient Mark mode is on and a region is active, it is used as
3745 the blockquote text."
3747 (if (markdown-use-region-p)
3748 (markdown-blockquote-region (region-beginning) (region-end))
3749 (markdown-ensure-blank-line-before)
3750 (insert (markdown-blockquote-indentation (point)) "> ")
3751 (markdown-ensure-blank-line-after)))
3753 (defun markdown-block-region (beg end prefix
)
3754 "Format the region using a block prefix.
3755 Arguments BEG and END specify the beginning and end of the
3756 region. The characters PREFIX will appear at the beginning
3759 (let* ((end-marker (make-marker))
3760 (beg-marker (make-marker)))
3761 ;; Ensure blank line after and remove extra whitespace
3763 (skip-syntax-backward "-")
3764 (set-marker end-marker
(point))
3765 (delete-horizontal-space)
3766 (markdown-ensure-blank-line-after)
3767 ;; Ensure blank line before and remove extra whitespace
3769 (skip-syntax-forward "-")
3770 (delete-horizontal-space)
3771 (markdown-ensure-blank-line-before)
3772 (set-marker beg-marker
(point))
3773 ;; Insert PREFIX before each line
3774 (goto-char beg-marker
)
3775 (while (and (< (line-beginning-position) end-marker
)
3780 (defun markdown-blockquote-region (beg end
)
3781 "Blockquote the region.
3782 Arguments BEG and END specify the beginning and end of the region."
3784 (markdown-block-region
3785 beg end
(concat (markdown-blockquote-indentation
3786 (max (point-min) (1- beg
))) "> ")))
3788 (defun markdown-pre-indentation (loc)
3789 "Return string containing necessary whitespace for a pre block at LOC.
3790 Also see `markdown-blockquote-indentation'."
3793 (let* ((list-level (length (markdown-calculate-list-levels)))
3795 (dotimes (_ (1+ list-level
) indent
)
3796 (setq indent
(concat indent
" "))))))
3798 (defun markdown-insert-pre ()
3799 "Start a preformatted section (or apply to the region).
3800 If Transient Mark mode is on and a region is active, it is marked
3801 as preformatted text."
3803 (if (markdown-use-region-p)
3804 (markdown-pre-region (region-beginning) (region-end))
3805 (markdown-ensure-blank-line-before)
3806 (insert (markdown-pre-indentation (point)))
3807 (markdown-ensure-blank-line-after)))
3809 (defun markdown-pre-region (beg end
)
3810 "Format the region as preformatted text.
3811 Arguments BEG and END specify the beginning and end of the region."
3813 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg
)))))
3814 (markdown-block-region beg end indent
)))
3816 (defun markdown-electric-backquote (arg)
3817 "Insert a backquote.
3818 The numeric prefix argument ARG says how many times to repeat the insertion.
3819 Call `markdown-insert-gfm-code-block' interactively
3820 if three backquotes inserted at the beginning of line."
3822 (self-insert-command (prefix-numeric-value arg
))
3823 (when (and markdown-gfm-use-electric-backquote
(looking-back "^```" nil
))
3825 (call-interactively #'markdown-insert-gfm-code-block
)))
3827 (defconst markdown-gfm-recognized-languages
3828 ;; to reproduce/update, evaluate the let-form in
3829 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
3830 ;; but with appropriate use of a keyboard macro, indenting and filling it
3831 ;; properly is pretty fast.
3832 '("ABAP" "AGS-Script" "AMPL" "ANTLR" "API-Blueprint" "APL" "ASP" "ATS"
3833 "ActionScript" "Ada" "Agda" "Alloy" "Ant-Build-System" "ApacheConf" "Apex"
3834 "AppleScript" "Arc" "Arduino" "AsciiDoc" "AspectJ" "Assembly" "Augeas"
3835 "AutoHotkey" "AutoIt" "Awk" "Batchfile" "Befunge" "Bison" "BitBake"
3836 "BlitzBasic" "BlitzMax" "Bluespec" "Boo" "Brainfuck" "Brightscript" "Bro" "C#"
3837 "C++" "C-ObjDump" "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "CSS" "Cap'n-Proto"
3838 "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK" "Cirru" "Clarion" "Clean"
3839 "Click" "Clojure" "CoffeeScript" "ColdFusion" "ColdFusion-CFC" "Common-Lisp"
3840 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal" "Cucumber"
3841 "Cuda" "Cycript" "Cython" "D-ObjDump" "DIGITAL-Command-Language" "DM"
3842 "DNS-Zone" "DTrace" "Darcs-Patch" "Dart" "Diff" "Dockerfile" "Dogescript"
3843 "Dylan" "ECL" "ECLiPSe" "Eagle" "Ecere-Projects" "Eiffel" "Elixir" "Elm"
3844 "Emacs-Lisp" "EmberScript" "Erlang" "F#" "FLUX" "FORTRAN" "Factor" "Fancy"
3845 "Fantom" "Filterscript" "Formatted" "Forth" "FreeMarker" "Frege" "G-code"
3846 "GAMS" "GAP" "GAS" "GDScript" "GLSL" "Game-Maker-Language" "Genshi"
3847 "Gentoo-Ebuild" "Gentoo-Eclass" "Gettext-Catalog" "Glyph" "Gnuplot" "Go"
3848 "Golo" "Gosu" "Grace" "Gradle" "Grammatical-Framework"
3849 "Graph-Modeling-Language" "Graphviz-(DOT)" "Groff" "Groovy"
3850 "Groovy-Server-Pages" "HCL" "HTML" "HTML+Django" "HTML+EEX" "HTML+ERB"
3851 "HTML+PHP" "HTTP" "Hack" "Haml" "Handlebars" "Harbour" "Haskell" "Haxe" "Hy"
3852 "HyPhy" "IDL" "IGOR-Pro" "INI" "IRC-log" "Idris" "Inform-7" "Inno-Setup" "Io"
3853 "Ioke" "Isabelle" "Isabelle-ROOT" "JFlex" "JSON" "JSON5" "JSONLD" "JSONiq"
3854 "JSX" "Jade" "Jasmin" "Java" "Java-Server-Pages" "JavaScript" "Julia"
3855 "Jupyter-Notebook" "KRL" "KiCad" "Kit" "Kotlin" "LFE" "LLVM" "LOLCODE" "LSL"
3856 "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex" "LilyPond" "Limbo"
3857 "Linker-Script" "Linux-Kernel-Module" "Liquid" "Literate-Agda"
3858 "Literate-CoffeeScript" "Literate-Haskell" "LiveScript" "Logos" "Logtalk"
3859 "LookML" "LoomScript" "Lua" "MAXScript" "MTML" "MUF" "Makefile" "Mako"
3860 "Markdown" "Mask" "Mathematica" "Matlab" "Maven-POM" "Max" "MediaWiki"
3861 "Mercury" "Metal" "MiniD" "Mirah" "Modelica" "Modula-2"
3862 "Module-Management-System" "Monkey" "Moocode" "MoonScript" "Myghty" "NCL" "NL"
3863 "NSIS" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo" "NewLisp" "Nginx" "Nimrod"
3864 "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml" "ObjDump" "Objective-C"
3865 "Objective-C++" "Objective-J" "Omgrofl" "Opa" "Opal" "OpenCL" "OpenEdge-ABL"
3866 "OpenSCAD" "Org" "Ox" "Oxygene" "Oz" "PAWN" "PHP" "PLSQL" "PLpgSQL" "Pan"
3867 "Papyrus" "Parrot" "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal"
3868 "Perl" "Perl6" "Pickle" "PicoLisp" "PigLatin" "Pike" "Pod" "PogoScript" "Pony"
3869 "PostScript" "PowerShell" "Processing" "Prolog" "Propeller-Spin"
3870 "Protocol-Buffer" "Public-Key" "Puppet" "Pure-Data" "PureBasic" "PureScript"
3871 "Python" "Python-traceback" "QML" "QMake" "RAML" "RDoc" "REALbasic" "RHTML"
3872 "RMarkdown" "Racket" "Ragel-in-Ruby-Host" "Raw-token-data" "Rebol" "Red"
3873 "Redcode" "Ren'Py" "RenderScript" "RobotFramework" "Rouge" "Ruby" "Rust" "SAS"
3874 "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL" "STON" "SVG" "Sage" "SaltStack"
3875 "Sass" "Scala" "Scaml" "Scheme" "Scilab" "Self" "Shell" "ShellSession" "Shen"
3876 "Slash" "Slim" "Smali" "Smalltalk" "Smarty" "SourcePawn" "Squirrel" "Stan"
3877 "Standard-ML" "Stata" "Stylus" "SuperCollider" "Swift" "SystemVerilog" "TOML"
3878 "TXL" "Tcl" "Tcsh" "TeX" "Tea" "Text" "Textile" "Thrift" "Turing" "Turtle"
3879 "Twig" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset" "UnrealScript"
3880 "UrWeb" "VCL" "VHDL" "Vala" "Verilog" "VimL" "Visual-Basic" "Volt" "Vue"
3881 "Web-Ontology-Language" "WebIDL" "X10" "XC" "XML" "XPages" "XProc" "XQuery"
3882 "XS" "XSLT" "Xojo" "Xtend" "YAML" "Yacc" "Zephir" "Zimpl" "desktop" "eC" "edn"
3883 "fish" "mupad" "nesC" "ooc" "reStructuredText" "wisp" "xBase")
3884 "Language specifiers recognized by GitHub's syntax highlighting features.")
3886 (defvar markdown-gfm-used-languages nil
3887 "Language names used in GFM code blocks.")
3888 (make-variable-buffer-local 'markdown-gfm-used-languages
)
3890 (defun markdown-trim-whitespace (str)
3891 (markdown-replace-regexp-in-string
3892 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str
))
3894 (defun markdown-clean-language-string (str)
3895 (markdown-replace-regexp-in-string
3896 "{\\.?\\|}" "" (markdown-trim-whitespace str
)))
3898 (defun markdown-validate-language-string (widget)
3899 (let ((str (widget-value widget
)))
3900 (unless (string= str
(markdown-clean-language-string str
))
3901 (widget-put widget
:error
(format "Invalid language spec: '%s'" str
))
3904 (defun markdown-gfm-get-corpus ()
3905 "Create corpus of recognized GFM code block languages for the given buffer."
3906 (let ((given-corpus (append markdown-gfm-additional-languages
3907 markdown-gfm-recognized-languages
)))
3909 markdown-gfm-used-languages
3910 (if markdown-gfm-downcase-languages
(cl-mapcar #'downcase given-corpus
)
3913 (defun markdown-gfm-add-used-language (lang)
3914 "Clean LANG and add to list of used languages."
3915 (setq markdown-gfm-used-languages
3916 (cons lang
(remove lang markdown-gfm-used-languages
))))
3918 (defun markdown-insert-gfm-code-block (&optional lang
)
3919 "Insert GFM code block for language LANG.
3920 If LANG is nil, the language will be queried from user. If a
3921 region is active, wrap this region with the markup instead. If
3922 the region boundaries are not on empty lines, these are added
3923 automatically in order to have the correct markup."
3925 (list (let ((completion-ignore-case nil
))
3927 (markdown-clean-language-string
3929 "Programming language: "
3930 (markdown-gfm-get-corpus)
3931 nil
'confirm
(car markdown-gfm-used-languages
)
3932 'markdown-gfm-language-history
))
3934 (unless (string= lang
"") (markdown-gfm-add-used-language lang
))
3935 (when (> (length lang
) 0) (setq lang
(concat " " lang
)))
3936 (if (markdown-use-region-p)
3937 (let ((b (region-beginning)) (e (region-end)))
3939 ;; if we're on a blank line, don't newline, otherwise the ```
3940 ;; should go on its own line
3941 (unless (looking-back "\n" nil
)
3944 (markdown-ensure-blank-line-after)
3946 ;; if we're on a blank line, insert the quotes here, otherwise
3947 ;; add a new line first
3948 (unless (looking-at-p "\n")
3951 (markdown-ensure-blank-line-before)
3952 (insert "```" lang
))
3953 (markdown-ensure-blank-line-before)
3954 (insert "```" lang
"\n\n```")
3955 (markdown-ensure-blank-line-after)
3958 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer
)
3959 (with-current-buffer (or buffer
(current-buffer))
3961 (goto-char (point-min))
3963 with prop
= 'markdown-gfm-block-begin
3964 for pos-prop
= (markdown-find-next-prop prop
)
3967 (goto-char (car pos-prop
))
3969 (set-match-data (get-text-property (point) prop
))
3970 ;; Note: Hard-coded group number assumes tilde
3971 ;; and GFM fenced code regexp groups agree.
3972 (when (and (match-beginning 3) (match-end 3))
3973 (buffer-substring-no-properties
3974 (match-beginning 3) (match-end 3)))))
3975 do
(progn (when lang
(markdown-gfm-add-used-language lang
))
3976 (goto-char (next-single-property-change (point) prop
)))))))
3979 ;;; Footnotes ==================================================================
3981 (defun markdown-footnote-counter-inc ()
3982 "Increment `markdown-footnote-counter' and return the new value."
3983 (when (= markdown-footnote-counter
0) ; hasn't been updated in this buffer yet.
3985 (goto-char (point-min))
3986 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars
"*?\\)\\]:")
3988 (let ((fn (string-to-number (match-string 1))))
3989 (when (> fn markdown-footnote-counter
)
3990 (setq markdown-footnote-counter fn
))))))
3991 (cl-incf markdown-footnote-counter
))
3993 (defun markdown-insert-footnote ()
3994 "Insert footnote with a new number and move point to footnote definition."
3996 (let ((fn (markdown-footnote-counter-inc)))
3997 (insert (format "[^%d]" fn
))
3998 (markdown-footnote-text-find-new-location)
3999 (markdown-ensure-blank-line-before)
4000 (unless (markdown-cur-line-blank-p)
4002 (insert (format "[^%d]: " fn
))
4003 (markdown-ensure-blank-line-after)))
4005 (defun markdown-footnote-text-find-new-location ()
4006 "Position the cursor at the proper location for a new footnote text."
4008 ((eq markdown-footnote-location
'end
) (goto-char (point-max)))
4009 ((eq markdown-footnote-location
'immediately
) (markdown-end-of-block))
4010 ((eq markdown-footnote-location
'header
) (markdown-end-of-defun))))
4012 (defun markdown-footnote-kill ()
4013 "Kill the footnote at point.
4014 The footnote text is killed (and added to the kill ring), the
4015 footnote marker is deleted. Point has to be either at the
4016 footnote marker or in the footnote text."
4018 (let ((marker-pos nil
)
4019 (skip-deleting-marker nil
)
4020 (starting-footnote-text-positions
4021 (markdown-footnote-text-positions)))
4022 (when starting-footnote-text-positions
4023 ;; We're starting in footnote text, so mark our return position and jump
4024 ;; to the marker if possible.
4025 (let ((marker-pos (markdown-footnote-find-marker
4026 (cl-first starting-footnote-text-positions
))))
4028 (goto-char (1- marker-pos
))
4029 ;; If there isn't a marker, we still want to kill the text.
4030 (setq skip-deleting-marker t
))))
4031 ;; Either we didn't start in the text, or we started in the text and jumped
4032 ;; to the marker. We want to assume we're at the marker now and error if
4034 (unless skip-deleting-marker
4035 (let ((marker (markdown-footnote-delete-marker)))
4037 (error "Not at a footnote"))
4038 ;; Even if we knew the text position before, it changed when we deleted
4040 (setq marker-pos
(cl-second marker
))
4041 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker
))))
4042 (unless new-text-pos
4043 (error "No text for footnote `%s'" (cl-first marker
)))
4044 (goto-char new-text-pos
))))
4045 (let ((pos (markdown-footnote-kill-text)))
4046 (goto-char (if starting-footnote-text-positions
4050 (defun markdown-footnote-delete-marker ()
4051 "Delete a footnote marker at point.
4052 Returns a list (ID START) containing the footnote ID and the
4053 start position of the marker before deletion. If no footnote
4054 marker was deleted, this function returns NIL."
4055 (let ((marker (markdown-footnote-marker-positions)))
4057 (delete-region (cl-second marker
) (cl-third marker
))
4060 (defun markdown-footnote-kill-text ()
4061 "Kill footnote text at point.
4062 Returns the start position of the footnote text before deletion,
4063 or NIL if point was not inside a footnote text.
4065 The killed text is placed in the kill ring (without the footnote
4067 (let ((fn (markdown-footnote-text-positions)))
4069 (let ((text (delete-and-extract-region (cl-second fn
) (cl-third fn
))))
4070 (string-match (concat "\\[\\" (cl-first fn
) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text
)
4071 (kill-new (match-string 1 text
))
4072 (when (and (markdown-cur-line-blank-p)
4073 (markdown-prev-line-blank-p)
4075 (delete-region (1- (point)) (point)))
4078 (defun markdown-footnote-goto-text ()
4079 "Jump to the text of the footnote at point."
4081 (let ((fn (car (markdown-footnote-marker-positions))))
4083 (error "Not at a footnote marker"))
4084 (let ((new-pos (markdown-footnote-find-text fn
)))
4086 (error "No definition found for footnote `%s'" fn
))
4087 (goto-char new-pos
))))
4089 (defun markdown-footnote-return ()
4090 "Return from a footnote to its footnote number in the main text."
4092 (let ((fn (save-excursion
4093 (car (markdown-footnote-text-positions)))))
4095 (error "Not in a footnote"))
4096 (let ((new-pos (markdown-footnote-find-marker fn
)))
4098 (error "Footnote marker `%s' not found" fn
))
4099 (goto-char new-pos
))))
4101 (defun markdown-footnote-find-marker (id)
4102 "Find the location of the footnote marker with ID.
4103 The actual buffer position returned is the position directly
4104 following the marker's closing bracket. If no marker is found,
4107 (goto-char (point-min))
4108 (when (re-search-forward (concat "\\[" id
"\\]\\([^:]\\|\\'\\)") nil t
)
4109 (skip-chars-backward "^]")
4112 (defun markdown-footnote-find-text (id)
4113 "Find the location of the text of footnote ID.
4114 The actual buffer position returned is the position of the first
4115 character of the text, after the footnote's identifier. If no
4116 footnote text is found, NIL is returned."
4118 (goto-char (point-min))
4119 (when (re-search-forward (concat "^\\[" id
"\\]:") nil t
)
4120 (skip-chars-forward "[ \t]")
4123 (defun markdown-footnote-marker-positions ()
4124 "Return the position and ID of the footnote marker point is on.
4125 The return value is a list (ID START END). If point is not on a
4126 footnote, NIL is returned."
4127 ;; first make sure we're at a footnote marker
4128 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars
"*\\]?") (line-beginning-position))
4129 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars
"*?\\]")))
4131 ;; move point between [ and ^:
4132 (if (looking-at-p "\\[")
4134 (skip-chars-backward "^["))
4135 (looking-at (concat "\\(\\^" markdown-footnote-chars
"*?\\)\\]"))
4136 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
4138 (defun markdown-footnote-text-positions ()
4139 "Return the start and end positions of the footnote text point is in.
4140 The exact return value is a list of three elements: (ID START END).
4141 The start position is the position of the opening bracket
4142 of the footnote id. The end position is directly after the
4143 newline that ends the footnote. If point is not in a footnote,
4144 NIL is returned instead."
4147 (move-beginning-of-line 1)
4148 ;; Try to find the label. If we haven't found the label and we're at a blank
4149 ;; or indented line, back up if possible.
4151 (not (and (looking-at markdown-regex-footnote-definition
)
4152 (setq result
(list (match-string 1) (point)))))
4154 (or (markdown-cur-line-blank-p)
4155 (>= (current-indentation) 4))))
4158 ;; Advance if there is a next line that is either blank or indented.
4159 ;; (Need to check if we're on the last line, because
4160 ;; markdown-next-line-blank-p returns true for last line in buffer.)
4161 (while (and (/= (line-end-position) (point-max))
4162 (or (markdown-next-line-blank-p)
4163 (>= (markdown-next-line-indent) 4)))
4165 ;; Move back while the current line is blank.
4166 (while (markdown-cur-line-blank-p)
4168 ;; Advance to capture this line and a single trailing newline (if there
4171 (append result
(list (point)))))))
4174 ;;; Element Removal ===========================================================
4176 (defun markdown-kill-thing-at-point ()
4177 "Kill thing at point and add important text, without markup, to kill ring.
4178 Possible things to kill include (roughly in order of precedence):
4179 inline code, headers, horizonal rules, links (add link text to
4180 kill ring), images (add alt text to kill ring), angle uri, email
4181 addresses, bold, italics, reference definition (add URI to kill
4182 ring), footnote markers and text (kill both marker and text, add
4183 text to kill ring), and list items."
4188 ((markdown-inline-code-at-point)
4189 (kill-new (match-string 2))
4190 (delete-region (match-beginning 0) (match-end 0)))
4192 ((thing-at-point-looking-at markdown-regex-header-atx
)
4193 (kill-new (match-string 2))
4194 (delete-region (match-beginning 0) (match-end 0)))
4196 ((thing-at-point-looking-at markdown-regex-header-setext
)
4197 (kill-new (match-string 1))
4198 (delete-region (match-beginning 0) (match-end 0)))
4200 ((thing-at-point-looking-at markdown-regex-hr
)
4201 (kill-new (match-string 0))
4202 (delete-region (match-beginning 0) (match-end 0)))
4203 ;; Inline link or image (add link or alt text to kill ring)
4204 ((thing-at-point-looking-at markdown-regex-link-inline
)
4205 (kill-new (match-string 3))
4206 (delete-region (match-beginning 0) (match-end 0)))
4207 ;; Reference link or image (add link or alt text to kill ring)
4208 ((thing-at-point-looking-at markdown-regex-link-reference
)
4209 (kill-new (match-string 3))
4210 (delete-region (match-beginning 0) (match-end 0)))
4211 ;; Angle URI (add URL to kill ring)
4212 ((thing-at-point-looking-at markdown-regex-angle-uri
)
4213 (kill-new (match-string 2))
4214 (delete-region (match-beginning 0) (match-end 0)))
4215 ;; Email address in angle brackets (add email address to kill ring)
4216 ((thing-at-point-looking-at markdown-regex-email
)
4217 (kill-new (match-string 1))
4218 (delete-region (match-beginning 0) (match-end 0)))
4219 ;; Wiki link (add alias text to kill ring)
4220 ((and markdown-enable-wiki-links
4221 (thing-at-point-looking-at markdown-regex-wiki-link
))
4222 (kill-new (markdown-wiki-link-alias))
4223 (delete-region (match-beginning 1) (match-end 1)))
4225 ((thing-at-point-looking-at markdown-regex-bold
)
4226 (kill-new (match-string 4))
4227 (delete-region (match-beginning 2) (match-end 2)))
4229 ((thing-at-point-looking-at markdown-regex-italic
)
4230 (kill-new (match-string 3))
4231 (delete-region (match-beginning 1) (match-end 1)))
4233 ((thing-at-point-looking-at markdown-regex-strike-through
)
4234 (kill-new (match-string 4))
4235 (delete-region (match-beginning 2) (match-end 2)))
4236 ;; Footnote marker (add footnote text to kill ring)
4237 ((thing-at-point-looking-at markdown-regex-footnote
)
4238 (markdown-footnote-kill))
4239 ;; Footnote text (add footnote text to kill ring)
4240 ((setq val
(markdown-footnote-text-positions))
4241 (markdown-footnote-kill))
4242 ;; Reference definition (add URL to kill ring)
4243 ((thing-at-point-looking-at markdown-regex-reference-definition
)
4244 (kill-new (match-string 5))
4245 (delete-region (match-beginning 0) (match-end 0)))
4247 ((setq val
(markdown-cur-list-item-bounds))
4248 (kill-new (delete-and-extract-region (cl-first val
) (cl-second val
))))
4250 (error "Nothing found at point to kill")))))
4253 ;;; Indentation ====================================================================
4255 (defun markdown-indent-find-next-position (cur-pos positions
)
4256 "Return the position after the index of CUR-POS in POSITIONS.
4257 Positions are calculated by `markdown-calc-indents'."
4258 (while (and positions
4259 (not (equal cur-pos
(car positions
))))
4260 (setq positions
(cdr positions
)))
4261 (or (cadr positions
) 0))
4263 (defun markdown-exdent-find-next-position (cur-pos positions
)
4264 "Return the maximal element that precedes CUR-POS from POSITIONS.
4265 Positions are calculated by `markdown-calc-indents'."
4267 (dolist (i positions
)
4269 (setq result
(max result i
))))
4272 (defun markdown-indent-line ()
4273 "Indent the current line using some heuristics.
4274 If the _previous_ command was either `markdown-enter-key' or
4275 `markdown-cycle', then we should cycle to the next
4276 reasonable indentation position. Otherwise, we could have been
4277 called directly by `markdown-enter-key', by an initial call of
4278 `markdown-cycle', or indirectly by `auto-fill-mode'. In
4279 these cases, indent to the default position.
4280 Positions are calculated by `markdown-calc-indents'."
4282 (let ((positions (markdown-calc-indents))
4283 (cursor-pos (current-column))
4284 (_ (back-to-indentation))
4285 (cur-pos (current-column)))
4286 (if (not (equal this-command
'markdown-cycle
))
4287 (indent-line-to (car positions
))
4288 (setq positions
(sort (delete-dups positions
) '<))
4289 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions
))
4291 (if (< cur-pos next-pos
)
4292 (+ cursor-pos
(- next-pos cur-pos
))
4293 (- cursor-pos cur-pos
))))
4294 (indent-line-to next-pos
)
4295 (move-to-column new-cursor-pos
)))))
4297 (defun markdown-calc-indents ()
4298 "Return a list of indentation columns to cycle through.
4299 The first element in the returned list should be considered the
4300 default indentation level. This function does not worry about
4301 duplicate positions, which are handled up by calling functions."
4302 (let (pos prev-line-pos positions
)
4304 ;; Indentation of previous line
4305 (setq prev-line-pos
(markdown-prev-line-indent))
4306 (setq positions
(cons prev-line-pos positions
))
4308 ;; Indentation of previous non-list-marker text
4309 (when (setq pos
(markdown-prev-non-list-indent))
4310 (setq positions
(cons pos positions
)))
4312 ;; Indentation required for a pre block in current context
4313 (setq pos
(length (markdown-pre-indentation (point))))
4314 (setq positions
(cons pos positions
))
4316 ;; Indentation of the previous line + tab-width
4318 (setq positions
(cons (+ prev-line-pos tab-width
) positions
))
4319 (setq positions
(cons tab-width positions
)))
4321 ;; Indentation of the previous line - tab-width
4322 (if (and prev-line-pos
(> prev-line-pos tab-width
))
4323 (setq positions
(cons (- prev-line-pos tab-width
) positions
)))
4325 ;; Indentation of all preceeding list markers (when in a list)
4326 (when (setq pos
(markdown-calculate-list-levels))
4327 (setq positions
(append pos positions
)))
4330 (setq positions
(cons 0 positions
))
4332 ;; Return reversed list
4333 (reverse positions
)))
4335 (defun markdown-enter-key ()
4336 "Handle RET according to customized settings.
4337 When `markdown-indent-on-enter' is nil, this is equivalent to
4338 `newline'. Otherwise, indent following RET and when the point is
4339 in a list item, start a new item with the same indentation. If
4340 the point is in an empty list item, remove it."
4342 (if (not markdown-indent-on-enter
)
4344 (let ((bounds (markdown-cur-list-item-bounds)))
4346 (let ((beg (cl-first bounds
))
4347 (end (cl-second bounds
))
4348 (length (cl-fourth bounds
)))
4349 ;; Point is in a list item
4350 (if (= (- end beg
) length
)
4351 ;; Delete blank list
4353 (delete-region beg end
)
4355 (markdown-indent-line))
4356 (call-interactively #'markdown-insert-list-item
)))
4357 ;; Point is not in a list
4359 (markdown-indent-line)))))
4361 (defun markdown-exdent-or-delete (arg)
4362 "Handle BACKSPACE by cycling through indentation points.
4363 When BACKSPACE is pressed, if there is only whitespace
4364 before the current point, then exdent the line one level.
4365 Otherwise, do normal delete by repeating
4366 `backward-delete-char-untabify' ARG times."
4369 (backward-delete-char-untabify arg
)
4370 (let ((cur-pos (current-column))
4371 (start-of-indention (save-excursion
4372 (back-to-indentation)
4374 (positions (markdown-calc-indents)))
4375 (if (and (> cur-pos
0) (= cur-pos start-of-indention
))
4376 (indent-line-to (markdown-exdent-find-next-position cur-pos positions
))
4377 (backward-delete-char-untabify arg
)))))
4379 (defun markdown-find-leftmost-column (beg end
)
4380 "Find the leftmost column in the region from BEG to END."
4381 (let ((mincol 1000))
4384 (while (< (point) end
)
4385 (back-to-indentation)
4386 (unless (looking-at-p "[ \t]*$")
4387 (setq mincol
(min mincol
(current-column))))
4392 (defun markdown-indent-region (beg end arg
)
4393 "Indent the region from BEG to END using some heuristics.
4394 When ARG is non-nil, exdent the region instead.
4395 See `markdown-indent-line' and `markdown-indent-line'."
4396 (interactive "*r\nP")
4397 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
4398 (leftmostcol (markdown-find-leftmost-column beg end
))
4400 (markdown-exdent-find-next-position leftmostcol positions
)
4401 (markdown-indent-find-next-position leftmostcol positions
))))
4402 (indent-rigidly beg end
(- next-pos leftmostcol
))
4403 (setq deactivate-mark nil
)))
4405 (defun markdown-exdent-region (beg end
)
4406 "Call `markdown-indent-region' on region from BEG to END with prefix."
4408 (markdown-indent-region beg end t
))
4411 ;;; Markup Completion =========================================================
4413 (defconst markdown-complete-alist
4414 '((markdown-regex-header-atx . markdown-complete-atx
)
4415 (markdown-regex-header-setext . markdown-complete-setext
)
4416 (markdown-regex-hr . markdown-complete-hr
))
4417 "Association list of form (regexp . function) for markup completion.")
4419 (defun markdown-incomplete-atx-p ()
4420 "Return t if ATX header markup is incomplete and nil otherwise.
4421 Assumes match data is available for `markdown-regex-header-atx'.
4422 Checks that the number of trailing hash marks equals the number of leading
4423 hash marks, that there is only a single space before and after the text,
4424 and that there is no extraneous whitespace in the text."
4426 ;; Number of starting and ending hash marks differs
4427 (not (= (length (match-string 1)) (length (match-string 3))))
4428 ;; When the header text is not empty...
4429 (and (> (length (match-string 2)) 0)
4430 ;; ...if there are extra leading, trailing, or interior spaces
4431 (or (not (= (match-beginning 2) (1+ (match-end 1))))
4432 (not (= (match-beginning 3) (1+ (match-end 2))))
4433 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
4434 ;; When the header text is empty...
4435 (and (= (length (match-string 2)) 0)
4436 ;; ...if there are too many or too few spaces
4437 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
4439 (defun markdown-complete-atx ()
4440 "Complete and normalize ATX headers.
4441 Add or remove hash marks to the end of the header to match the
4442 beginning. Ensure that there is only a single space between hash
4443 marks and header text. Removes extraneous whitespace from header text.
4444 Assumes match data is available for `markdown-regex-header-atx'.
4445 Return nil if markup was complete and non-nil if markup was completed."
4446 (when (markdown-incomplete-atx-p)
4447 (let* ((new-marker (make-marker))
4448 (new-marker (set-marker new-marker
(match-end 2))))
4449 ;; Hash marks and spacing at end
4450 (goto-char (match-end 2))
4451 (delete-region (match-end 2) (match-end 3))
4452 (insert " " (match-string 1))
4453 ;; Remove extraneous whitespace from title
4454 (replace-match (markdown-compress-whitespace-string (match-string 2))
4456 ;; Spacing at beginning
4457 (goto-char (match-end 1))
4458 (delete-region (match-end 1) (match-beginning 2))
4460 ;; Leave point at end of text
4461 (goto-char new-marker
))))
4463 (defun markdown-incomplete-setext-p ()
4464 "Return t if setext header markup is incomplete and nil otherwise.
4465 Assumes match data is available for `markdown-regex-header-setext'.
4466 Checks that length of underline matches text and that there is no
4467 extraneous whitespace in the text."
4468 (or (not (= (length (match-string 1)) (length (match-string 2))))
4469 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
4471 (defun markdown-complete-setext ()
4472 "Complete and normalize setext headers.
4473 Add or remove underline characters to match length of header
4474 text. Removes extraneous whitespace from header text. Assumes
4475 match data is available for `markdown-regex-header-setext'.
4476 Return nil if markup was complete and non-nil if markup was completed."
4477 (when (markdown-incomplete-setext-p)
4478 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
4479 (char (char-after (match-beginning 2)))
4480 (level (if (char-equal char ?-
) 2 1)))
4481 (goto-char (match-beginning 0))
4482 (delete-region (match-beginning 0) (match-end 0))
4483 (markdown-insert-header level text t
)
4486 (defun markdown-incomplete-hr-p ()
4487 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
4488 Assumes match data is available for `markdown-regex-hr'."
4489 (not (member (match-string 0) markdown-hr-strings
)))
4491 (defun markdown-complete-hr ()
4492 "Complete horizontal rules.
4493 If horizontal rule string is a member of `markdown-hr-strings',
4494 do nothing. Otherwise, replace with the car of
4495 `markdown-hr-strings'.
4496 Assumes match data is available for `markdown-regex-hr'.
4497 Return nil if markup was complete and non-nil if markup was completed."
4498 (when (markdown-incomplete-hr-p)
4499 (replace-match (car markdown-hr-strings
))
4502 (defun markdown-complete ()
4503 "Complete markup of object near point or in region when active.
4504 Handle all objects in `markdown-complete-alist', in order.
4505 See `markdown-complete-at-point' and `markdown-complete-region'."
4507 (if (markdown-use-region-p)
4508 (markdown-complete-region (region-beginning) (region-end))
4509 (markdown-complete-at-point)))
4511 (defun markdown-complete-at-point ()
4512 "Complete markup of object near point.
4513 Handle all elements of `markdown-complete-alist' in order."
4515 (let ((list markdown-complete-alist
) found changed
)
4517 (let ((regexp (eval (caar list
)))
4518 (function (cdar list
)))
4519 (setq list
(cdr list
))
4520 (when (thing-at-point-looking-at regexp
)
4522 (setq changed
(funcall function
))
4525 (or changed
(error "Markup at point is complete"))
4526 (error "Nothing to complete at point"))))
4528 (defun markdown-complete-region (beg end
)
4529 "Complete markup of objects in region from BEG to END.
4530 Handle all objects in `markdown-complete-alist', in order. Each
4531 match is checked to ensure that a previous regexp does not also
4534 (let ((end-marker (set-marker (make-marker) end
))
4536 (dolist (element markdown-complete-alist
)
4537 (let ((regexp (eval (car element
)))
4538 (function (cdr element
)))
4540 (while (re-search-forward regexp end-marker
'limit
)
4541 (when (match-string 0)
4542 ;; Make sure this is not a match for any of the preceding regexps.
4543 ;; This prevents mistaking an HR for a Setext subheading.
4546 (dolist (prev-regexp previous
)
4547 (or match
(setq match
(looking-back prev-regexp nil
)))))
4549 (save-excursion (funcall function
))))))
4550 (cl-pushnew regexp previous
:test
#'equal
)))
4553 (defun markdown-complete-buffer ()
4554 "Complete markup for all objects in the current buffer."
4556 (markdown-complete-region (point-min) (point-max)))
4559 ;;; Markup Cycling ============================================================
4561 (defun markdown-cycle-atx (arg &optional remove
)
4562 "Cycle ATX header markup.
4563 Promote header (decrease level) when ARG is 1 and demote
4564 header (increase level) if arg is -1. When REMOVE is non-nil,
4565 remove the header when the level reaches zero and stop cycling
4566 when it reaches six. Otherwise, perform a proper cycling through
4567 levels one through six. Assumes match data is available for
4568 `markdown-regex-header-atx'."
4569 (let* ((old-level (length (match-string 1)))
4570 (new-level (+ old-level arg
))
4571 (text (match-string 2)))
4573 (setq new-level
(% new-level
6))
4574 (setq new-level
(cond ((= new-level
0) 6)
4575 ((< new-level
0) (+ new-level
6))
4579 (markdown-unwrap-thing-at-point nil
0 2))
4581 (goto-char (match-beginning 0))
4582 (delete-region (match-beginning 0) (match-end 0))
4583 (markdown-insert-header new-level text nil
)))))
4585 (defun markdown-cycle-setext (arg &optional remove
)
4586 "Cycle setext header markup.
4587 Promote header (increase level) when ARG is 1 and demote
4588 header (decrease level or remove) if arg is -1. When demoting a
4589 level-two setext header, replace with a level-three atx header.
4590 When REMOVE is non-nil, remove the header when the level reaches
4591 zero. Otherwise, cycle back to a level six atx header. Assumes
4592 match data is available for `markdown-regex-header-setext'."
4593 (let* ((char (char-after (match-beginning 2)))
4594 (old-level (if (char-equal char ?
=) 1 2))
4595 (new-level (+ old-level arg
)))
4596 (when (and (not remove
) (= new-level
0))
4600 (markdown-unwrap-thing-at-point nil
0 1))
4602 (markdown-insert-header new-level nil t
))
4604 (markdown-insert-header new-level nil nil
)))))
4606 (defun markdown-cycle-hr (arg &optional remove
)
4607 "Cycle string used for horizontal rule from `markdown-hr-strings'.
4608 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
4609 backwards (promote). When REMOVE is non-nil, remove the hr instead
4610 of cycling when the end of the list is reached.
4611 Assumes match data is available for `markdown-regex-hr'."
4612 (let* ((strings (if (= arg -
1)
4613 (reverse markdown-hr-strings
)
4614 markdown-hr-strings
))
4615 (tail (member (match-string 0) strings
))
4616 (new (or (cadr tail
)
4622 (replace-match new
)))
4624 (defun markdown-cycle-bold ()
4625 "Cycle bold markup between underscores and asterisks.
4626 Assumes match data is available for `markdown-regex-bold'."
4628 (let* ((old-delim (match-string 3))
4629 (new-delim (if (string-equal old-delim
"**") "__" "**")))
4630 (replace-match new-delim t t nil
3)
4631 (replace-match new-delim t t nil
5))))
4633 (defun markdown-cycle-italic ()
4634 "Cycle italic markup between underscores and asterisks.
4635 Assumes match data is available for `markdown-regex-italic'."
4637 (let* ((old-delim (match-string 2))
4638 (new-delim (if (string-equal old-delim
"*") "_" "*")))
4639 (replace-match new-delim t t nil
2)
4640 (replace-match new-delim t t nil
4))))
4643 ;;; Keymap ====================================================================
4645 (defvar markdown-mode-map
4646 (let ((map (make-keymap)))
4647 ;; Element insertion
4648 (define-key map
"\C-c\C-al" 'markdown-insert-inline-link-dwim
)
4649 (define-key map
"\C-c\C-aL" 'markdown-insert-reference-link-dwim
)
4650 (define-key map
"\C-c\C-au" 'markdown-insert-uri
)
4651 (define-key map
"\C-c\C-af" 'markdown-insert-footnote
)
4652 (define-key map
"\C-c\C-aw" 'markdown-insert-wiki-link
)
4653 (define-key map
"\C-c\C-ii" 'markdown-insert-image
)
4654 (define-key map
"\C-c\C-iI" 'markdown-insert-reference-image
)
4655 (define-key map
"\C-c\C-i\C-t" 'markdown-toggle-inline-images
)
4656 (define-key map
"\C-c\C-th" 'markdown-insert-header-dwim
)
4657 (define-key map
"\C-c\C-tH" 'markdown-insert-header-setext-dwim
)
4658 (define-key map
"\C-c\C-t1" 'markdown-insert-header-atx-1
)
4659 (define-key map
"\C-c\C-t2" 'markdown-insert-header-atx-2
)
4660 (define-key map
"\C-c\C-t3" 'markdown-insert-header-atx-3
)
4661 (define-key map
"\C-c\C-t4" 'markdown-insert-header-atx-4
)
4662 (define-key map
"\C-c\C-t5" 'markdown-insert-header-atx-5
)
4663 (define-key map
"\C-c\C-t6" 'markdown-insert-header-atx-6
)
4664 (define-key map
"\C-c\C-t!" 'markdown-insert-header-setext-1
)
4665 (define-key map
"\C-c\C-t@" 'markdown-insert-header-setext-2
)
4666 (define-key map
"\C-c\C-ss" 'markdown-insert-bold
)
4667 (define-key map
"\C-c\C-se" 'markdown-insert-italic
)
4668 (define-key map
"\C-c\C-sc" 'markdown-insert-code
)
4669 (define-key map
"\C-c\C-sb" 'markdown-insert-blockquote
)
4670 (define-key map
"\C-c\C-sk" 'markdown-insert-kbd
)
4671 (define-key map
"\C-c\C-s\C-b" 'markdown-blockquote-region
)
4672 (define-key map
"\C-c\C-sp" 'markdown-insert-pre
)
4673 (define-key map
"\C-c\C-s\C-p" 'markdown-pre-region
)
4674 (define-key map
"\C-c\C-sP" 'markdown-insert-gfm-code-block
)
4675 (define-key map
"\C-c-" 'markdown-insert-hr
)
4676 ;; Element insertion (deprecated)
4677 (define-key map
"\C-c\C-ar" 'markdown-insert-reference-link-dwim
)
4678 (define-key map
"\C-c\C-tt" 'markdown-insert-header-setext-1
)
4679 (define-key map
"\C-c\C-ts" 'markdown-insert-header-setext-2
)
4681 (define-key map
(kbd "C-c C-k") 'markdown-kill-thing-at-point
)
4682 ;; Promotion, Demotion, Completion, and Cycling
4683 (define-key map
(kbd "C-c C--") 'markdown-promote
)
4684 (define-key map
(kbd "C-c C-=") 'markdown-demote
)
4685 (define-key map
(kbd "C-c C-]") 'markdown-complete
)
4686 ;; Following and Jumping
4687 (define-key map
(kbd "C-c C-o") 'markdown-follow-thing-at-point
)
4688 (define-key map
(kbd "C-c C-l") 'markdown-jump
)
4690 (define-key map
(kbd "C-m") 'markdown-enter-key
)
4691 (define-key map
(kbd "DEL") 'markdown-exdent-or-delete
)
4692 (define-key map
(kbd "C-c >") 'markdown-indent-region
)
4693 (define-key map
(kbd "C-c <") 'markdown-exdent-region
)
4694 ;; Visibility cycling
4695 (define-key map
(kbd "TAB") 'markdown-cycle
)
4696 (define-key map
(kbd "<S-iso-lefttab>") 'markdown-shifttab
)
4697 (define-key map
(kbd "<S-tab>") 'markdown-shifttab
)
4698 (define-key map
(kbd "<backtab>") 'markdown-shifttab
)
4699 ;; Header navigation
4700 (define-key map
(kbd "C-c C-n") 'markdown-next-visible-heading
)
4701 (define-key map
(kbd "C-c C-p") 'markdown-previous-visible-heading
)
4702 (define-key map
(kbd "C-c C-f") 'markdown-forward-same-level
)
4703 (define-key map
(kbd "C-c C-b") 'markdown-backward-same-level
)
4704 (define-key map
(kbd "C-c C-u") 'markdown-up-heading
)
4705 ;; Buffer-wide commands
4706 (define-key map
(kbd "C-c C-c m") 'markdown-other-window
)
4707 (define-key map
(kbd "C-c C-c p") 'markdown-preview
)
4708 (define-key map
(kbd "C-c C-c e") 'markdown-export
)
4709 (define-key map
(kbd "C-c C-c v") 'markdown-export-and-preview
)
4710 (define-key map
(kbd "C-c C-c o") 'markdown-open
)
4711 (define-key map
(kbd "C-c C-c l") 'markdown-live-preview-mode
)
4712 (define-key map
(kbd "C-c C-c w") 'markdown-kill-ring-save
)
4713 (define-key map
(kbd "C-c C-c c") 'markdown-check-refs
)
4714 (define-key map
(kbd "C-c C-c n") 'markdown-cleanup-list-numbers
)
4715 (define-key map
(kbd "C-c C-c ]") 'markdown-complete-buffer
)
4717 (define-key map
(kbd "M-<up>") 'markdown-move-up
)
4718 (define-key map
(kbd "M-<down>") 'markdown-move-down
)
4719 (define-key map
(kbd "M-<left>") 'markdown-promote
)
4720 (define-key map
(kbd "M-<right>") 'markdown-demote
)
4721 (define-key map
(kbd "M-<return>") 'markdown-insert-list-item
)
4722 (define-key map
(kbd "C-c C-j") 'markdown-insert-list-item
)
4724 (define-key map
(kbd "M-S-<up>") 'markdown-move-subtree-up
)
4725 (define-key map
(kbd "M-S-<down>") 'markdown-move-subtree-down
)
4726 (define-key map
(kbd "M-S-<left>") 'markdown-promote-subtree
)
4727 (define-key map
(kbd "M-S-<right>") 'markdown-demote-subtree
)
4729 (define-key map
(kbd "M-{") 'markdown-backward-paragraph
)
4730 (define-key map
(kbd "M-}") 'markdown-forward-paragraph
)
4731 (define-key map
(kbd "M-n") 'markdown-next-link
)
4732 (define-key map
(kbd "M-p") 'markdown-previous-link
)
4733 ;; Alternative keys (in case of problems with the arrow keys)
4734 (define-key map
(kbd "C-c C-x u") 'markdown-move-up
)
4735 (define-key map
(kbd "C-c C-x d") 'markdown-move-down
)
4736 (define-key map
(kbd "C-c C-x l") 'markdown-promote
)
4737 (define-key map
(kbd "C-c C-x r") 'markdown-demote
)
4738 (define-key map
(kbd "C-c C-x m") 'markdown-insert-list-item
)
4739 (define-key map
(kbd "C-c C-x C-x") 'markdown-toggle-gfm-checkbox
)
4741 "Keymap for Markdown major mode.")
4743 (defvar gfm-mode-map
4744 (let ((map (make-sparse-keymap)))
4745 (set-keymap-parent map markdown-mode-map
)
4746 (define-key map
(kbd "C-c C-s d") 'markdown-insert-strike-through
)
4747 (define-key map
"`" 'markdown-electric-backquote
)
4749 "Keymap for `gfm-mode'.
4750 See also `markdown-mode-map'.")
4753 ;;; Menu ==================================================================
4755 (easy-menu-define markdown-mode-menu markdown-mode-map
4756 "Menu for Markdown mode"
4760 ["Jump" markdown-jump
]
4761 ["Follow Link" markdown-follow-thing-at-point
]
4762 ["Next Link" markdown-next-link
]
4763 ["Previous Link" markdown-previous-link
]
4765 ["Next Visible Heading" markdown-next-visible-heading
]
4766 ["Previous Visible Heading" markdown-previous-visible-heading
]
4767 ["Forward Same Level" markdown-forward-same-level
]
4768 ["Backward Same Level" markdown-backward-same-level
]
4769 ["Up to Parent Heading" markdown-up-heading
]
4771 ["Forward Paragraph" markdown-forward-paragraph
]
4772 ["Backward Paragraph" markdown-backward-paragraph
])
4774 ["Cycle Visibility" markdown-cycle
(markdown-on-heading-p)]
4775 ["Cycle Visibility Globally" markdown-shifttab
])
4777 ("Headings & Structure"
4778 ["Automatic Heading" markdown-insert-header-dwim
]
4779 ["Automatic Heading (Setext)" markdown-insert-header-setext-dwim
]
4780 ("Specific Heading (atx)"
4781 ["First Level Setext" markdown-insert-header-setext-1
]
4782 ["Second Level Setext" markdown-insert-header-setext-2
])
4783 ("Specific Heading (Setext)"
4784 ["First Level atx" markdown-insert-header-atx-1
]
4785 ["Second Level atx" markdown-insert-header-atx-2
]
4786 ["Third Level atx" markdown-insert-header-atx-3
]
4787 ["Fourth Level atx" markdown-insert-header-atx-4
]
4788 ["Fifth Level atx" markdown-insert-header-atx-5
]
4789 ["Sixth Level atx" markdown-insert-header-atx-6
])
4790 ["Horizontal Rule" markdown-insert-hr
]
4792 ["Move Subtree Up" markdown-move-subtree-up
:keys
"M-S-<up>"]
4793 ["Move Subtree Down" markdown-move-subtree-down
:keys
"M-S-<down>"]
4794 ["Promote Subtree" markdown-promote-subtree
:keys
"M-S-<left>"]
4795 ["Demote Subtree" markdown-demote-subtree
:keys
"M-S-<right>"]
4796 ["Promote Header" markdown-promote
:keys
"M-<left>"]
4797 ["Demote Header" markdown-demote
:keys
"M-<right>"])
4799 ["Indent Region" markdown-indent-region
]
4800 ["Exdent Region" markdown-exdent-region
])
4802 ["Insert List Item" markdown-insert-list-item
]
4803 ["Move List Item Up" markdown-move-up
:keys
"M-<up>"]
4804 ["Move List Item Down" markdown-move-down
:keys
"M-<down>"]
4805 ["Exdent List Item" markdown-promote
:keys
"M-<left>"]
4806 ["Indent List Item" markdown-demote
:keys
"M-<right>"]
4807 ["Renumber List" markdown-cleanup-list-numbers
]
4808 ["Toggle Task List Item" markdown-toggle-gfm-checkbox
])
4810 ["Plain URL" markdown-insert-uri
]
4811 ["Inline Link" markdown-insert-inline-link-dwim
]
4812 ["Inline Image" markdown-insert-image
]
4813 ["Reference Link" markdown-insert-reference-link-dwim
]
4814 ["Reference Image" markdown-insert-reference-image
]
4815 ["Footnote" markdown-insert-footnote
]
4816 ["Wiki Link" markdown-insert-wiki-link
]
4818 ["Check References" markdown-check-refs
]
4819 ["Toggle Inline Images" markdown-toggle-inline-images
4821 :selected markdown-inline-image-overlays
])
4823 ["Bold" markdown-insert-bold
]
4824 ["Italic" markdown-insert-italic
]
4825 ["Code" markdown-insert-code
]
4826 ["Strikethrough" markdown-insert-strike-through
]
4827 ["Keyboard" markdown-insert-kbd
]
4829 ["Blockquote" markdown-insert-blockquote
]
4830 ["Preformatted" markdown-insert-pre
]
4831 ["GFM Code Block" markdown-insert-gfm-code-block
]
4833 ["Blockquote Region" markdown-blockquote-region
]
4834 ["Preformatted Region" markdown-pre-region
]
4836 ["Enable LaTeX math" markdown-toggle-math
4838 :selected markdown-enable-math
])
4841 ["Compile" markdown-other-window
]
4842 ["Preview" markdown-preview
]
4843 ["Export" markdown-export
]
4844 ["Export & View" markdown-export-and-preview
]
4845 ["Open" markdown-open
]
4846 ["Live Export" markdown-live-preview-mode
4848 :selected markdown-live-preview-mode
]
4849 ["Kill ring save" markdown-kill-ring-save
])
4850 ("Markup Completion and Cycling"
4851 ["Complete Markup" markdown-complete
]
4852 ["Promote Element" markdown-promote
]
4853 ["Demote Element" markdown-demote
])
4855 ["Kill Element" markdown-kill-thing-at-point
]
4858 ["Version" markdown-show-version
]
4859 ["Homepage" markdown-mode-info
]
4860 ["Describe Mode" (describe-function 'markdown-mode
)])))
4863 ;;; imenu =====================================================================
4865 (defun markdown-imenu-create-nested-index ()
4866 "Create and return a nested imenu index alist for the current buffer.
4867 See `imenu-create-index-function' and `imenu--index-alist' for details."
4868 (let* ((root '(nil . nil
))
4873 hashes pos level heading
)
4875 (goto-char (point-min))
4876 (while (re-search-forward markdown-regex-header
(point-max) t
)
4877 (unless (markdown-code-block-at-point)
4879 ((match-string-no-properties 2) ;; level 1 setext
4880 (setq heading
(match-string-no-properties 1))
4881 (setq pos
(match-beginning 1)
4883 ((match-string-no-properties 3) ;; level 2 setext
4884 (setq heading
(match-string-no-properties 1))
4885 (setq pos
(match-beginning 1)
4887 ((setq hashes
(match-string-no-properties 4))
4888 (setq heading
(match-string-no-properties 5)
4889 pos
(match-beginning 4)
4890 level
(length hashes
))))
4891 (let ((alist (list (cons heading pos
))))
4893 ((= cur-level level
) ; new sibling
4894 (setcdr cur-alist alist
)
4895 (setq cur-alist alist
))
4896 ((< cur-level level
) ; first child
4897 (dotimes (_ (- level cur-level
1))
4898 (setq alist
(list (cons empty-heading alist
))))
4900 (let* ((parent (car cur-alist
))
4901 (self-pos (cdr parent
)))
4902 (setcdr parent
(cons (cons self-heading self-pos
) alist
)))
4903 (setcdr root alist
)) ; primogenitor
4904 (setq cur-alist alist
)
4905 (setq cur-level level
))
4906 (t ; new sibling of an ancestor
4907 (let ((sibling-alist (last (cdr root
))))
4908 (dotimes (_ (1- level
))
4909 (setq sibling-alist
(last (cdar sibling-alist
))))
4910 (setcdr sibling-alist alist
)
4911 (setq cur-alist alist
))
4912 (setq cur-level level
))))))
4915 (defun markdown-imenu-create-flat-index ()
4916 "Create and return a flat imenu index alist for the current buffer.
4917 See `imenu-create-index-function' and `imenu--index-alist' for details."
4918 (let* ((empty-heading "-") index heading pos
)
4920 (goto-char (point-min))
4921 (while (re-search-forward markdown-regex-header
(point-max) t
)
4922 (when (and (not (markdown-code-block-at-point))
4923 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin
)))
4925 ((setq heading
(match-string-no-properties 1))
4926 (setq pos
(match-beginning 1)))
4927 ((setq heading
(match-string-no-properties 5))
4928 (setq pos
(match-beginning 4))))
4929 (or (> (length heading
) 0)
4930 (setq heading empty-heading
))
4931 (setq index
(append index
(list (cons heading pos
))))))
4935 ;;; References ================================================================
4937 (defun markdown-reference-goto-definition ()
4938 "Jump to the definition of the reference at point or create it."
4940 (when (thing-at-point-looking-at markdown-regex-link-reference
)
4941 (let* ((text (match-string-no-properties 3))
4942 (reference (match-string-no-properties 6))
4943 (target (downcase (if (string= reference
"") text reference
)))
4944 (loc (cadr (markdown-reference-definition target
))))
4947 (goto-char (match-beginning 0))
4948 (markdown-insert-reference-definition target
)))))
4950 (defun markdown-reference-find-links (reference)
4951 "Return a list of all links for REFERENCE.
4952 REFERENCE should not include the surrounding square brackets.
4953 Elements of the list have the form (text start line), where
4954 text is the link text, start is the location at the beginning of
4955 the link, and line is the line number on which the link appears."
4956 (let* ((ref-quote (regexp-quote reference
))
4957 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
4958 ref-quote ref-quote
))
4961 (goto-char (point-min))
4962 (while (re-search-forward regexp nil t
)
4963 (let* ((text (or (match-string-no-properties 1)
4964 (match-string-no-properties 2)))
4965 (start (match-beginning 0))
4966 (line (markdown-line-number-at-pos)))
4967 (cl-pushnew (list text start line
) links
:test
#'equal
))))
4970 (defun markdown-get-undefined-refs ()
4971 "Return a list of undefined Markdown references.
4972 Result is an alist of pairs (reference . occurrences), where
4973 occurrences is itself another alist of pairs (label . line-number).
4974 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
4975 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
4976 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
4979 (goto-char (point-min))
4981 (re-search-forward markdown-regex-link-reference nil t
)
4982 (let* ((text (match-string-no-properties 3))
4983 (reference (match-string-no-properties 6))
4984 (target (downcase (if (string= reference
"") text reference
))))
4985 (unless (markdown-reference-definition target
)
4986 (let ((entry (assoc target missing
)))
4989 (cons target
(list (cons text
(markdown-line-number-at-pos))))
4990 missing
:test
#'equal
)
4992 (append (cdr entry
) (list (cons text
(markdown-line-number-at-pos))))))))))
4993 (reverse missing
))))
4995 (defconst markdown-reference-check-buffer
4996 "*Undefined references for %buffer%*"
4997 "Pattern for name of buffer for listing undefined references.
4998 The string %buffer% will be replaced by the corresponding
4999 `markdown-mode' buffer name.")
5001 (defun markdown-reference-check-buffer (&optional buffer-name
)
5002 "Name and return buffer for reference checking.
5003 BUFFER-NAME is the name of the main buffer being visited."
5004 (or buffer-name
(setq buffer-name
(buffer-name)))
5005 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
5006 "%buffer%" buffer-name
5007 markdown-reference-check-buffer
))))
5008 (with-current-buffer refbuf
5010 (View-exit-and-edit))
5011 (use-local-map button-buffer-map
)
5015 (defconst markdown-reference-links-buffer
5016 "*Reference links for %buffer%*"
5017 "Pattern for name of buffer for listing references.
5018 The string %buffer% will be replaced by the corresponding buffer name.")
5020 (defun markdown-reference-links-buffer (&optional buffer-name
)
5021 "Name, setup, and return a buffer for listing links.
5022 BUFFER-NAME is the name of the main buffer being visited."
5023 (or buffer-name
(setq buffer-name
(buffer-name)))
5024 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
5025 "%buffer%" buffer-name
5026 markdown-reference-links-buffer
))))
5027 (with-current-buffer linkbuf
5029 (View-exit-and-edit))
5030 (use-local-map button-buffer-map
)
5034 (when (markdown-use-buttons-p)
5035 ;; Add an empty Markdown reference definition to buffer
5036 ;; specified in the 'target-buffer property. The reference name is
5037 ;; the button's label.
5038 (define-button-type 'markdown-undefined-reference-button
5039 'help-echo
"mouse-1, RET: create definition for undefined reference"
5043 (let ((buffer (button-get b
'target-buffer
))
5044 (line (button-get b
'target-line
))
5045 (label (button-label b
)))
5046 (switch-to-buffer-other-window buffer
)
5047 (goto-char (point-min))
5049 (markdown-insert-reference-definition label
)
5050 (markdown-check-refs t
))))
5052 ;; Jump to line in buffer specified by 'target-buffer property.
5053 ;; Line number is button's 'line property.
5054 (define-button-type 'markdown-goto-line-button
5055 'help-echo
"mouse-1, RET: go to line"
5059 (message (button-get b
'buffer
))
5060 (switch-to-buffer-other-window (button-get b
'target-buffer
))
5061 ;; use call-interactively to silence compiler
5062 (let ((current-prefix-arg (button-get b
'target-line
)))
5063 (call-interactively 'goto-line
))))
5065 ;; Jumps to a particular link at location given by 'target-char
5066 ;; property in buffer given by 'target-buffer property.
5067 (define-button-type 'markdown-link-button
5068 'help-echo
"mouse-1, RET: jump to location of link"
5072 (let ((target (button-get b
'target-buffer
))
5073 (loc (button-get b
'target-char
)))
5074 (kill-buffer-and-window)
5075 (switch-to-buffer target
)
5078 (defun markdown-insert-undefined-reference-button (reference oldbuf
)
5079 "Insert a button for creating REFERENCE in buffer OLDBUF.
5080 REFERENCE should be a list of the form (reference . occurrences),
5081 as by `markdown-get-undefined-refs'."
5082 (let ((label (car reference
)))
5083 (if (markdown-use-buttons-p)
5084 ;; Create a reference button in Emacs 22
5085 (insert-button label
5086 :type
'markdown-undefined-reference-button
5087 'target-buffer oldbuf
5088 'target-line
(cdr (car (cdr reference
))))
5089 ;; Insert reference as text in Emacs < 22
5092 (dolist (occurrence (cdr reference
))
5093 (let ((line (cdr occurrence
)))
5094 (if (markdown-use-buttons-p)
5095 ;; Create a line number button in Emacs 22
5096 (insert-button (number-to-string line
)
5097 :type
'markdown-goto-line-button
5098 'target-buffer oldbuf
5100 ;; Insert line number as text in Emacs < 22
5101 (insert (number-to-string line
)))
5107 (defun markdown-insert-link-button (link oldbuf
)
5108 "Insert a button for jumping to LINK in buffer OLDBUF.
5109 LINK should be a list of the form (text char line) containing
5110 the link text, location, and line number."
5111 (let ((label (cl-first link
))
5112 (char (cl-second link
))
5113 (line (cl-third link
)))
5114 (if (markdown-use-buttons-p)
5115 ;; Create a reference button in Emacs 22
5116 (insert-button label
5117 :type
'markdown-link-button
5118 'target-buffer oldbuf
5120 ;; Insert reference as text in Emacs < 22
5122 (insert (format " (line %d)\n" line
))))
5124 (defun markdown-reference-goto-link (&optional reference
)
5125 "Jump to the location of the first use of REFERENCE."
5128 (if (thing-at-point-looking-at markdown-regex-reference-definition
)
5129 (setq reference
(match-string-no-properties 2))
5130 (error "No reference definition at point")))
5131 (let ((links (markdown-reference-find-links reference
)))
5132 (cond ((= (length links
) 1)
5133 (goto-char (cadr (car links
))))
5134 ((> (length links
) 1)
5135 (let ((oldbuf (current-buffer))
5136 (linkbuf (markdown-reference-links-buffer)))
5137 (with-current-buffer linkbuf
5138 (insert "Links using reference " reference
":\n\n")
5139 (dolist (link (reverse links
))
5140 (markdown-insert-link-button link oldbuf
)))
5141 (view-buffer-other-window linkbuf
)
5142 (goto-char (point-min))
5145 (error "No links for reference %s" reference
)))))
5147 (defun markdown-check-refs (&optional silent
)
5148 "Show all undefined Markdown references in current `markdown-mode' buffer.
5149 If SILENT is non-nil, do not message anything when no undefined
5151 Links which have empty reference definitions are considered to be
5154 (when (not (eq major-mode
'markdown-mode
))
5155 (error "Not available in current mode"))
5156 (let ((oldbuf (current-buffer))
5157 (refs (markdown-get-undefined-refs))
5158 (refbuf (markdown-reference-check-buffer)))
5162 (message "No undefined references found"))
5163 (kill-buffer refbuf
))
5164 (with-current-buffer refbuf
5165 (insert "The following references are undefined:\n\n")
5167 (markdown-insert-undefined-reference-button ref oldbuf
))
5168 (view-buffer-other-window refbuf
)
5169 (goto-char (point-min))
5170 (forward-line 2)))))
5173 ;;; Lists =====================================================================
5175 (defun markdown-insert-list-item (&optional arg
)
5176 "Insert a new list item.
5177 If the point is inside unordered list, insert a bullet mark. If
5178 the point is inside ordered list, insert the next number followed
5179 by a period. Use the previous list item to determine the amount
5180 of whitespace to place before and after list markers.
5182 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
5183 decrease the indentation by one level.
5185 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
5186 increase the indentation by one level."
5188 (let (bounds cur-indent marker indent new-indent new-loc
)
5190 ;; Look for a list item on current or previous non-blank line
5192 (while (and (not (setq bounds
(markdown-cur-list-item-bounds)))
5194 (markdown-cur-line-blank-p))
5197 (cond ((save-excursion
5198 (skip-chars-backward " \t")
5199 (looking-at-p markdown-regex-list
))
5203 ((not (markdown-cur-line-blank-p))
5205 (setq new-loc
(point)))
5206 ;; Look ahead for a list item on next non-blank line
5209 (while (and (null bounds
)
5211 (markdown-cur-line-blank-p))
5213 (setq bounds
(markdown-cur-list-item-bounds))))
5215 (setq new-loc
(point))
5216 (unless (markdown-cur-line-blank-p)
5219 ;; When not in a list, start a new unordered one
5221 (unless (markdown-cur-line-blank-p)
5223 (insert markdown-unordered-list-item-prefix
))
5224 ;; Compute indentation and marker for new list item
5225 (setq cur-indent
(nth 2 bounds
))
5226 (setq marker
(nth 4 bounds
))
5228 ;; Dedent: decrement indentation, find previous marker.
5230 (setq indent
(max (- cur-indent
4) 0))
5233 (when (markdown-prev-list-item (- (nth 3 bounds
) 1))
5234 (markdown-cur-list-item-bounds)))))
5236 (setq marker
(nth 4 prev-bounds
)))))
5237 ;; Indent: increment indentation by 4, use same marker.
5238 ((= arg
16) (setq indent
(+ cur-indent
4)))
5239 ;; Same level: keep current indentation and marker.
5240 (t (setq indent cur-indent
)))
5241 (setq new-indent
(make-string indent
32))
5245 ((string-match-p "[0-9]" marker
)
5246 (if (= arg
16) ;; starting a new column indented one more level
5247 (insert (concat new-indent
"1. "))
5248 ;; Don't use previous match-data
5249 (set-match-data nil
)
5250 ;; travel up to the last item and pick the correct number. If
5251 ;; the argument was nil, "new-indent = cur-indent" is the same,
5252 ;; so we don't need special treatment. Neat.
5254 (while (and (not (looking-at (concat new-indent
"\\([0-9]+\\)\\(\\.[ \t]*\\)")))
5255 (>= (forward-line -
1) 0))))
5256 (let* ((old-prefix (match-string 1))
5257 (old-spacing (match-string 2))
5258 (new-prefix (if old-prefix
5259 (int-to-string (1+ (string-to-number old-prefix
)))
5261 (space-adjust (- (length old-prefix
) (length new-prefix
)))
5262 (new-spacing (if (and (match-string 2)
5263 (not (string-match-p "\t" old-spacing
))
5265 (> space-adjust
(- 1 (length (match-string 2)))))
5266 (substring (match-string 2) 0 space-adjust
)
5267 (or old-spacing
". "))))
5268 (insert (concat new-indent new-prefix new-spacing
)))))
5269 ;; Unordered list, or ordered list with hash mark
5270 ((string-match-p "[\\*\\+-]\\|#\\." marker
)
5271 (insert new-indent marker
)))))))
5273 (defun markdown-move-list-item-up ()
5274 "Move the current list item up in the list when possible."
5277 (when (setq cur
(markdown-cur-list-item-bounds))
5279 (goto-char (nth 0 cur
))
5280 (if (markdown-prev-list-item (nth 3 cur
))
5282 (setq prev
(markdown-cur-list-item-bounds))
5285 (transpose-regions (nth 0 prev
) (nth 1 prev
)
5286 (nth 0 cur
) (nth 1 cur
) t
)
5287 (goto-char (+ (nth 0 prev
) (- old
(nth 0 cur
)))))
5288 ;; Catch error in case regions overlap.
5289 (error (goto-char old
))))
5292 (defun markdown-move-list-item-down ()
5293 "Move the current list item down in the list when possible."
5296 (when (setq cur
(markdown-cur-list-item-bounds))
5298 (if (markdown-next-list-item (nth 3 cur
))
5300 (setq next
(markdown-cur-list-item-bounds))
5303 (transpose-regions (nth 0 cur
) (nth 1 cur
)
5304 (nth 0 next
) (nth 1 next
) nil
)
5305 (goto-char (+ old
(- (nth 1 next
) (nth 1 cur
)))))
5306 ;; Catch error in case regions overlap.
5307 (error (goto-char old
))))
5310 (defun markdown-demote-list-item (&optional bounds
)
5311 "Indent (or demote) the current list item.
5312 Optionally, BOUNDS of the current list item may be provided if available."
5314 (when (or bounds
(setq bounds
(markdown-cur-list-item-bounds)))
5316 (let ((end-marker (set-marker (make-marker) (nth 1 bounds
))))
5317 (goto-char (nth 0 bounds
))
5318 (while (< (point) end-marker
)
5319 (unless (markdown-cur-line-blank-p)
5320 (insert (make-string markdown-list-indent-width ?
)))
5323 (defun markdown-promote-list-item (&optional bounds
)
5324 "Unindent (or promote) the current list item.
5325 Optionally, BOUNDS of the current list item may be provided if available."
5327 (when (or bounds
(setq bounds
(markdown-cur-list-item-bounds)))
5330 (let ((end-marker (set-marker (make-marker) (nth 1 bounds
)))
5332 (goto-char (nth 0 bounds
))
5333 (when (looking-at (format "^[ ]\\{1,%d\\}"
5334 markdown-list-indent-width
))
5335 (setq num
(- (match-end 0) (match-beginning 0)))
5336 (setq regexp
(format "^[ ]\\{1,%d\\}" num
))
5337 (while (and (< (point) end-marker
)
5338 (re-search-forward regexp end-marker t
))
5339 (replace-match "" nil nil
)
5340 (forward-line))))))))
5342 (defun markdown-cleanup-list-numbers-level (&optional pfx
)
5343 "Update the numbering for level PFX (as a string of spaces).
5345 Assume that the previously found match was for a numbered item in
5352 (while (and continue
(not (eobp)))
5355 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
5356 (setq cpfx
(match-string-no-properties 1))
5361 (concat pfx
(number-to-string (setq idx
(1+ idx
))) ". ")))
5365 (setq sep
(markdown-cleanup-list-numbers-level cpfx
))
5370 (setq continue nil
))))
5372 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
5373 (setq cpfx
(match-string-no-properties 1))
5375 ;; reset if separated before
5376 ((string= cpfx pfx
) (when sep
(setq idx
0)))
5379 (setq continue nil
))))
5384 (setq continue
(= (forward-line) 0))))
5387 (defun markdown-cleanup-list-numbers ()
5388 "Update the numbering of ordered lists."
5391 (goto-char (point-min))
5392 (markdown-cleanup-list-numbers-level "")))
5395 ;;; Movement ==================================================================
5397 (defun markdown-beginning-of-defun (&optional arg
)
5398 "`beginning-of-defun-function' for Markdown.
5399 Move backward to the beginning of the current or previous section.
5400 When ARG is non-nil, repeat that many times. When ARG is negative,
5401 move forward to the ARG-th following section."
5403 (or arg
(setq arg
1))
5405 (or (re-search-backward markdown-regex-header nil t arg
)
5406 (goto-char (point-min))))
5408 (defun markdown-end-of-defun (&optional arg
)
5409 "`end-of-defun-function' for Markdown.
5410 Move forward to the end of the current or following section.
5411 When ARG is non-nil, repeat that many times. When ARG is negative,
5412 move back to the ARG-th preceding section."
5414 (or arg
(setq arg
1))
5415 (when (looking-at markdown-regex-header
)
5416 (goto-char (match-beginning 0))
5418 (if (re-search-forward markdown-regex-header nil t arg
)
5419 (goto-char (match-beginning 0))
5420 (goto-char (point-max)))
5421 (skip-syntax-backward "-"))
5423 (defun markdown-beginning-of-block ()
5424 "Move the point to the start of the previous text block."
5426 (if (re-search-backward markdown-regex-block-separator nil t
)
5427 (goto-char (or (match-end 2) (match-end 0)))
5428 (goto-char (point-min))))
5430 (defun markdown-end-of-block ()
5431 "Move the point to the start of the next text block."
5434 (skip-syntax-forward "-")
5435 (when (= (point) (point-min))
5437 (if (re-search-forward markdown-regex-block-separator nil t
)
5438 (goto-char (or (match-end 2) (match-end 0)))
5439 (goto-char (point-max)))
5440 (skip-syntax-backward "-")
5443 (defun markdown-forward-paragraph (arg)
5444 "Move forward one or more paragraphs or by one block.
5445 When ARG is nil or a numeric prefix, call `forward-paragraph'
5446 with ARG. When called with \\[universal-argument], call
5447 `markdown-end-of-block' instead."
5449 (or arg
(setq arg
1))
5450 (cond ((integerp arg
)
5451 (forward-paragraph arg
))
5453 (markdown-end-of-block))))
5455 (defun markdown-backward-paragraph (arg)
5456 "Move backward one or more paragraphs or by one block.
5457 When ARG is nil or a numeric prefix, call `backward-paragraph'
5458 with ARG. When called with \\[universal-argument], call
5459 `markdown-beginning-of-block' instead."
5461 (or arg
(setq arg
1))
5462 (cond ((integerp arg
)
5463 (backward-paragraph arg
))
5465 (markdown-beginning-of-block))))
5467 (defun markdown-end-of-block-element ()
5468 "Move the point to the start of the next block unit.
5469 Stops at blank lines, list items, headers, and horizontal rules."
5472 (while (and (or (not (markdown-prev-line-blank-p))
5473 (markdown-cur-line-blank-p))
5474 (not (or (looking-at-p markdown-regex-list
)
5475 (looking-at-p markdown-regex-header
)
5476 (looking-at-p markdown-regex-hr
)))
5480 (defun markdown-next-link ()
5481 "Jump to next inline, reference, or wiki link.
5482 If successful, return point. Otherwise, return nil.
5483 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
5485 (let ((opoint (point)))
5486 (when (or (markdown-link-p) (markdown-wiki-link-p))
5487 ;; At a link already, move past it.
5488 (goto-char (+ (match-end 0) 1)))
5489 ;; Search for the next wiki link and move to the beginning.
5490 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t
)
5491 (markdown-code-block-at-point)
5492 (< (point) (point-max))))
5493 (if (and (not (eq (point) opoint
))
5494 (or (markdown-link-p) (markdown-wiki-link-p)))
5495 ;; Group 1 will move past non-escape character in wiki link regexp.
5496 ;; Go to beginning of group zero for all other link types.
5497 (goto-char (or (match-beginning 1) (match-beginning 0)))
5501 (defun markdown-previous-link ()
5502 "Jump to previous wiki link.
5503 If successful, return point. Otherwise, return nil.
5504 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
5506 (let ((opoint (point)))
5507 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t
)
5508 (markdown-code-block-at-point)
5509 (> (point) (point-min))))
5510 (if (and (not (eq (point) opoint
))
5511 (or (markdown-link-p) (markdown-wiki-link-p)))
5512 (goto-char (or (match-beginning 1) (match-beginning 0)))
5517 ;;; Outline ===================================================================
5519 (defun markdown-move-heading-common (move-fn &optional arg
)
5520 "Wrapper for `outline-mode' functions to skip false positives.
5521 MOVE-FN is a function and ARG is its argument. For example,
5522 headings inside preformatted code blocks may match
5523 `outline-regexp' but should not be considered as headings."
5524 (let ((prev -
1) (start (point)))
5525 (if arg
(funcall move-fn arg
) (funcall move-fn
))
5526 (while (and (/= prev
(point)) (markdown-code-block-at-point))
5528 (if arg
(funcall move-fn arg
) (funcall move-fn
)))
5529 (if (= (point) start
) nil
(point))))
5531 (defun markdown-next-visible-heading (arg)
5532 "Move to the next visible heading line of any level.
5533 With argument, repeats or can move backward if negative. ARG is
5534 passed to `outline-next-visible-heading'."
5536 (markdown-move-heading-common 'outline-next-visible-heading arg
))
5538 (defun markdown-previous-visible-heading (arg)
5539 "Move to the previous visible heading line of any level.
5540 With argument, repeats or can move backward if negative. ARG is
5541 passed to `outline-previous-visible-heading'."
5543 (markdown-move-heading-common 'outline-previous-visible-heading arg
))
5545 (defun markdown-next-heading ()
5546 "Move to the next heading line of any level."
5547 (markdown-move-heading-common 'outline-next-heading
))
5549 (defun markdown-previous-heading ()
5550 "Move to the previous heading line of any level."
5551 (markdown-move-heading-common 'outline-previous-heading
))
5553 (defun markdown-forward-same-level (arg)
5554 "Move forward to the ARG'th heading at same level as this one.
5555 Stop at the first and last headings of a superior heading."
5557 (markdown-move-heading-common 'outline-forward-same-level arg
))
5559 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok
)
5561 (or (and (outline-on-heading-p invisible-ok
)
5562 (not (markdown-code-block-at-point)))
5563 (let ((header-re (concat "^\\(?:" outline-regexp
"\\)"))
5568 (while (and (not finish
) (re-search-backward header-re nil t
))
5569 (when (and (or invisible-ok
(not (outline-invisible-p)))
5570 (not (markdown-code-block-at-point)))
5573 (error "Before first heading")
5574 (setq found
(point))))))
5578 (defun markdown-backward-same-level (arg)
5579 "Move backward to the ARG'th heading at same level as this one.
5580 Stop at the first and last headings of a superior heading."
5582 (markdown-back-to-heading-over-code-block)
5584 (let ((point-to-move-to (save-excursion
5585 (outline-get-last-sibling))))
5586 (if point-to-move-to
5588 (goto-char point-to-move-to
)
5589 (setq arg
(1- arg
)))
5590 (error "No previous same-level heading")))))
5592 (defun markdown-up-heading (arg)
5593 "Move to the visible heading line of which the present line is a subheading.
5594 With argument, move up ARG levels."
5596 (and (called-interactively-p 'any
)
5597 (not (eq last-command
'markdown-up-heading
)) (push-mark))
5598 (markdown-move-heading-common 'outline-up-heading arg
))
5600 (defun markdown-back-to-heading (&optional invisible-ok
)
5601 "Move to previous heading line, or beg of this line if it's a heading.
5602 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
5603 (markdown-move-heading-common 'outline-back-to-heading invisible-ok
))
5605 (defalias 'markdown-end-of-heading
'outline-end-of-heading
)
5607 (defun markdown-on-heading-p ()
5608 "Return t if point is on a (visible) heading line."
5609 (get-text-property (point) 'markdown-heading
))
5611 (defun markdown-end-of-subtree (&optional invisible-OK
)
5612 "Move to the end of the current subtree.
5613 Only visible heading lines are considered, unless INVISIBLE-OK is
5615 Derived from `org-end-of-subtree'."
5616 (markdown-back-to-heading invisible-OK
)
5618 (level (markdown-outline-level)))
5619 (while (and (not (eobp))
5620 (or first
(> (markdown-outline-level) level
)))
5622 (markdown-next-heading))
5623 (if (memq (preceding-char) '(?
\n ?\^M
))
5625 ;; Go to end of line before heading
5627 (if (memq (preceding-char) '(?
\n ?\^M
))
5628 ;; leave blank line before heading
5629 (forward-char -
1)))))
5632 (defun markdown-outline-fix-visibility ()
5633 "Hide any false positive headings that should not be shown.
5634 For example, headings inside preformatted code blocks may match
5635 `outline-regexp' but should not be shown as headings when cycling.
5636 Also, the ending --- line in metadata blocks appears to be a
5637 setext header, but should not be folded."
5639 (goto-char (point-min))
5640 ;; Unhide any false positives in metadata blocks
5641 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin
)
5642 (let ((body (progn (forward-line)
5643 (markdown-text-property-at-point
5644 'markdown-yaml-metadata-section
))))
5646 (let ((end (progn (goto-char (cl-second body
))
5647 (markdown-text-property-at-point
5648 'markdown-yaml-metadata-end
))))
5649 (outline-flag-region (point-min) (1+ (cl-second end
)) nil
)))))
5650 ;; Hide any false positives in code blocks
5651 (unless (outline-on-heading-p)
5652 (outline-next-visible-heading 1))
5653 (while (< (point) (point-max))
5654 (when (markdown-code-block-at-point)
5655 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t
))
5656 (outline-next-visible-heading 1))))
5658 (defvar markdown-cycle-global-status
1)
5659 (defvar markdown-cycle-subtree-status nil
)
5661 (defun markdown-next-preface ()
5663 (while (and (not finish
) (re-search-forward (concat "\n\\(?:" outline-regexp
"\\)")
5665 (unless (markdown-code-block-at-point)
5666 (goto-char (match-beginning 0))
5668 (when (and (bolp) (or outline-blank-line
(eobp)) (not (bobp)))
5671 (defun markdown-show-entry ()
5673 (outline-back-to-heading t
)
5674 (outline-flag-region (1- (point))
5676 (markdown-next-preface)
5677 (if (= 1 (- (point-max) (point)))
5682 (defun markdown-cycle (&optional arg
)
5683 "Visibility cycling for Markdown mode.
5684 If ARG is t, perform global visibility cycling. If the point is
5685 at an atx-style header, cycle visibility of the corresponding
5686 subtree. Otherwise, insert a tab using `indent-relative'.
5687 Derived from `org-cycle'."
5690 ((eq arg t
) ;; Global cycling
5692 ((and (eq last-command this-command
)
5693 (eq markdown-cycle-global-status
2))
5694 ;; Move from overview to contents
5695 (markdown-hide-sublevels 1)
5696 (message "CONTENTS")
5697 (setq markdown-cycle-global-status
3)
5698 (markdown-outline-fix-visibility))
5700 ((and (eq last-command this-command
)
5701 (eq markdown-cycle-global-status
3))
5702 ;; Move from contents to all
5704 (message "SHOW ALL")
5705 (setq markdown-cycle-global-status
1))
5708 ;; Defaults to overview
5709 (markdown-hide-body)
5710 (message "OVERVIEW")
5711 (setq markdown-cycle-global-status
2)
5712 (markdown-outline-fix-visibility))))
5714 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
5715 ;; At a heading: rotate between three different views
5716 (markdown-back-to-heading)
5717 (let ((goal-column 0) eoh eol eos
)
5718 ;; Determine boundaries
5720 (markdown-back-to-heading)
5722 (beginning-of-line 2)
5723 (while (and (not (eobp)) ;; this is like `next-line'
5724 (get-char-property (1- (point)) 'invisible
))
5725 (beginning-of-line 2)) (setq eol
(point)))
5726 (markdown-end-of-heading) (setq eoh
(point))
5727 (markdown-end-of-subtree t
)
5728 (skip-chars-forward " \t\n")
5729 (beginning-of-line 1) ; in case this is an item
5730 (setq eos
(1- (point))))
5731 ;; Find out what to do next and set `this-command'
5734 ;; Nothing is hidden behind this heading
5735 (message "EMPTY ENTRY")
5736 (setq markdown-cycle-subtree-status nil
))
5738 ;; Entire subtree is hidden in one line: open it
5739 (markdown-show-entry)
5740 (markdown-show-children)
5741 (message "CHILDREN")
5742 (setq markdown-cycle-subtree-status
'children
))
5743 ((and (eq last-command this-command
)
5744 (eq markdown-cycle-subtree-status
'children
))
5745 ;; We just showed the children, now show everything.
5746 (markdown-show-subtree)
5748 (setq markdown-cycle-subtree-status
'subtree
))
5750 ;; Default action: hide the subtree.
5751 (markdown-hide-subtree)
5753 (setq markdown-cycle-subtree-status
'folded
)))))
5756 (indent-for-tab-command))))
5758 (defun markdown-shifttab ()
5759 "Global visibility cycling.
5760 Calls `markdown-cycle' with argument t."
5764 (defun markdown-outline-level ()
5765 "Return the depth to which a statement is nested in the outline."
5767 ((markdown-code-block-at-point-p) 7) ;; Only 6 header levels are defined.
5770 ((match-end 4) (- (match-end 4) (match-beginning 4)))))
5772 (defun markdown-promote-subtree (&optional arg
)
5773 "Promote the current subtree of ATX headings.
5774 Note that Markdown does not support heading levels higher than
5775 six and therefore level-six headings will not be promoted
5776 further. If ARG is non-nil promote the heading, otherwise
5780 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx
)
5781 (re-search-backward markdown-regex-header-atx nil t
))
5782 (not (markdown-code-block-at-point)))
5783 (let ((level (length (match-string 1)))
5784 (promote-or-demote (if arg
1 -
1))
5786 (markdown-cycle-atx promote-or-demote remove
)
5787 (catch 'end-of-subtree
5788 (while (markdown-next-heading)
5789 ;; Exit if this not a higher level heading; promote otherwise.
5790 (if (and (looking-at markdown-regex-header-atx
)
5791 (<= (length (match-string-no-properties 1)) level
))
5792 (throw 'end-of-subtree nil
)
5793 (markdown-cycle-atx promote-or-demote remove
))))))))
5795 (defun markdown-demote-subtree ()
5796 "Demote the current subtree of ATX headings."
5798 (markdown-promote-subtree t
))
5800 (defun markdown-move-subtree-up ()
5801 "Move the current subtree of ATX headings up."
5803 (outline-move-subtree-up 1))
5805 (defun markdown-move-subtree-down ()
5806 "Move the current subtree of ATX headings down."
5808 (outline-move-subtree-down 1))
5811 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
5813 (defun markdown-move-up ()
5815 Calls `markdown-move-list-item-up'."
5817 (markdown-move-list-item-up))
5819 (defun markdown-move-down ()
5820 "Move list item down.
5821 Calls `markdown-move-list-item-down'."
5823 (markdown-move-list-item-down))
5825 (defun markdown-promote ()
5826 "Either promote header or list item at point or cycle markup.
5827 See `markdown-cycle-atx', `markdown-cycle-setext', and
5828 `markdown-promote-list-item'."
5832 ;; Promote atx header
5833 ((thing-at-point-looking-at markdown-regex-header-atx
)
5834 (markdown-cycle-atx -
1))
5835 ;; Promote setext header
5836 ((thing-at-point-looking-at markdown-regex-header-setext
)
5837 (markdown-cycle-setext -
1))
5838 ;; Promote horizonal rule
5839 ((thing-at-point-looking-at markdown-regex-hr
)
5840 (markdown-cycle-hr -
1))
5841 ;; Promote list item
5842 ((setq bounds
(markdown-cur-list-item-bounds))
5843 (markdown-promote-list-item bounds
))
5845 ((thing-at-point-looking-at markdown-regex-bold
)
5846 (markdown-cycle-bold))
5848 ((thing-at-point-looking-at markdown-regex-italic
)
5849 (markdown-cycle-italic))
5851 (error "Nothing to promote at point")))))
5853 (defun markdown-demote ()
5854 "Either demote header or list item at point or cycle or remove markup.
5855 See `markdown-cycle-atx', `markdown-cycle-setext', and
5856 `markdown-demote-list-item'."
5860 ;; Demote atx header
5861 ((thing-at-point-looking-at markdown-regex-header-atx
)
5862 (markdown-cycle-atx 1))
5863 ;; Demote setext header
5864 ((thing-at-point-looking-at markdown-regex-header-setext
)
5865 (markdown-cycle-setext 1))
5866 ;; Demote horizonal rule
5867 ((thing-at-point-looking-at markdown-regex-hr
)
5868 (markdown-cycle-hr 1))
5870 ((setq bounds
(markdown-cur-list-item-bounds))
5871 (markdown-demote-list-item bounds
))
5873 ((thing-at-point-looking-at markdown-regex-bold
)
5874 (markdown-cycle-bold))
5876 ((thing-at-point-looking-at markdown-regex-italic
)
5877 (markdown-cycle-italic))
5879 (error "Nothing to demote at point")))))
5882 ;;; Commands ==================================================================
5884 (defun markdown (&optional output-buffer-name
)
5885 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
5886 The output buffer name defaults to `markdown-output-buffer-name'.
5887 Return the name of the output buffer used."
5889 (save-window-excursion
5890 (let ((begin-region)
5892 (if (markdown-use-region-p)
5893 (setq begin-region
(region-beginning)
5894 end-region
(region-end))
5895 (setq begin-region
(point-min)
5896 end-region
(point-max)))
5898 (unless output-buffer-name
5899 (setq output-buffer-name markdown-output-buffer-name
))
5901 ;; Handle case when `markdown-command' does not read from stdin
5902 (markdown-command-needs-filename
5903 (if (not buffer-file-name
)
5904 (error "Must be visiting a file")
5905 (shell-command (concat markdown-command
" "
5906 (shell-quote-argument buffer-file-name
))
5907 output-buffer-name
)))
5908 ;; Pass region to `markdown-command' via stdin
5910 (let ((buf (get-buffer-create output-buffer-name
)))
5911 (with-current-buffer buf
5912 (setq buffer-read-only nil
)
5914 (call-process-region begin-region end-region
5915 shell-file-name nil buf nil
5916 shell-command-switch markdown-command
)))))
5917 output-buffer-name
))
5919 (defun markdown-standalone (&optional output-buffer-name
)
5920 "Special function to provide standalone HTML output.
5921 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
5923 (setq output-buffer-name
(markdown output-buffer-name
))
5924 (with-current-buffer output-buffer-name
5925 (set-buffer output-buffer-name
)
5926 (unless (markdown-output-standalone-p)
5927 (markdown-add-xhtml-header-and-footer output-buffer-name
))
5928 (goto-char (point-min))
5932 (defun markdown-other-window (&optional output-buffer-name
)
5933 "Run `markdown-command' on current buffer and display in other window.
5934 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
5937 (markdown-display-buffer-other-window
5938 (markdown-standalone output-buffer-name
)))
5940 (defun markdown-output-standalone-p ()
5941 "Determine whether `markdown-command' output is standalone XHTML.
5942 Standalone XHTML output is identified by an occurrence of
5943 `markdown-xhtml-standalone-regexp' in the first five lines of output."
5945 (goto-char (point-min))
5947 markdown-xhtml-standalone-regexp
5948 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
5951 (defun markdown-stylesheet-link-string (stylesheet-path)
5952 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
5956 (defun markdown-add-xhtml-header-and-footer (title)
5957 "Wrap XHTML header and footer with given TITLE around current buffer."
5958 (goto-char (point-min))
5959 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
5960 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
5961 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
5962 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
5965 (insert "</title>\n")
5966 (when (> (length markdown-content-type
) 0)
5969 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
5970 markdown-content-type
5971 (or (and markdown-coding-system
5972 (fboundp 'coding-system-get
)
5973 (coding-system-get markdown-coding-system
5975 (and (fboundp 'coding-system-get
)
5976 (coding-system-get buffer-file-coding-system
5979 (if (> (length markdown-css-paths
) 0)
5980 (insert (mapconcat #'markdown-stylesheet-link-string
5981 markdown-css-paths
"\n")))
5982 (when (> (length markdown-xhtml-header-content
) 0)
5983 (insert markdown-xhtml-header-content
))
5984 (insert "\n</head>\n\n"
5986 (goto-char (point-max))
5991 (defun markdown-preview (&optional output-buffer-name
)
5992 "Run `markdown-command' on the current buffer and view output in browser.
5993 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
5996 (browse-url-of-buffer
5997 (markdown-standalone (or output-buffer-name markdown-output-buffer-name
))))
5999 (defun markdown-export-file-name (&optional extension
)
6000 "Attempt to generate a filename for Markdown output.
6001 The file extension will be EXTENSION if given, or .html by default.
6002 If the current buffer is visiting a file, we construct a new
6003 output filename based on that filename. Otherwise, return nil."
6004 (when (buffer-file-name)
6006 (setq extension
".html"))
6011 (file-name-sans-extension (buffer-file-name)))
6015 ((equal candidate
(buffer-file-name))
6016 (concat candidate extension
))
6020 (defun markdown-export (&optional output-file
)
6021 "Run Markdown on the current buffer, save to file, and return the filename.
6022 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
6023 generated by `markdown-export-file-name', which will be constructed using the
6024 current filename, but with the extension removed and replaced with .html."
6027 (setq output-file
(markdown-export-file-name ".html")))
6029 (let* ((init-buf (current-buffer))
6030 (init-point (point))
6031 (init-buf-string (buffer-string))
6032 (output-buffer (find-file-noselect output-file
))
6033 (output-buffer-name (buffer-name output-buffer
)))
6034 (run-hooks 'markdown-before-export-hook
)
6035 (markdown-standalone output-buffer-name
)
6036 (with-current-buffer output-buffer
6037 (run-hooks 'markdown-after-export-hook
)
6039 ;; if modified, restore initial buffer
6040 (when (buffer-modified-p init-buf
)
6042 (insert init-buf-string
)
6044 (goto-char init-point
))
6047 (defun markdown-export-and-preview ()
6048 "Export to XHTML using `markdown-export' and browse the resulting file."
6050 (browse-url-of-file (markdown-export)))
6052 (defvar markdown-live-preview-buffer nil
6053 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
6054 (make-variable-buffer-local 'markdown-live-preview-buffer
)
6056 (defvar markdown-live-preview-source-buffer nil
6057 "Source buffer from which current buffer was generated.
6058 This is the inverse of `markdown-live-preview-buffer'.")
6059 (make-variable-buffer-local 'markdown-live-preview-source-buffer
)
6061 (defvar markdown-live-preview-currently-exporting nil
)
6063 (defun markdown-live-preview-get-filename ()
6064 "Standardize the filename exported by `markdown-live-preview-export'."
6065 (markdown-export-file-name ".html"))
6067 (defun markdown-live-preview-window-eww (file)
6068 "Preview FILE with eww.
6069 To be used with `markdown-live-preview-window-function'."
6070 (if (require 'eww nil t
)
6072 (eww-open-file file
)
6073 (get-buffer "*eww*"))
6074 (error "EWW is not present or not loaded on this version of Emacs")))
6076 (defun markdown-visual-lines-between-points (beg end
)
6079 (cl-loop with count
= 0
6080 while
(progn (end-of-visual-line)
6081 (and (< (point) end
) (line-move-visual 1 t
)))
6083 finally return count
)))
6085 (defun markdown-live-preview-window-serialize (buf)
6086 "Get window point and scroll data for all windows displaying BUF."
6087 (when (buffer-live-p buf
)
6088 (with-current-buffer buf
6091 (with-selected-window win
6092 (let* ((start (window-start))
6094 (pt-or-sym (cond ((= pt
(point-min)) 'min
)
6095 ((= pt
(point-max)) 'max
)
6097 (diff (markdown-visual-lines-between-points
6099 (list win pt-or-sym diff
))))
6100 (get-buffer-window-list buf
)))))
6102 (defun markdown-get-point-back-lines (pt num-lines
)
6105 (line-move-visual (- num-lines
) t
)
6106 ;; in testing, can occasionally overshoot the number of lines to traverse
6107 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt
)))
6108 (when (> actual-num-lines num-lines
)
6109 (line-move-visual (- actual-num-lines num-lines
) t
)))
6112 (defun markdown-live-preview-window-deserialize (window-posns)
6113 "Apply window point and scroll data from WINDOW-POSNS.
6114 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
6115 (cl-destructuring-bind (win pt-or-sym diff
) window-posns
6116 (when (window-live-p win
)
6117 (with-current-buffer markdown-live-preview-buffer
6118 (set-window-buffer win
(current-buffer))
6119 (cl-destructuring-bind (actual-pt actual-diff
)
6121 (min (list (point-min) 0))
6122 (max (list (point-max) diff
))
6123 (t (list pt-or-sym diff
)))
6125 win
(markdown-get-point-back-lines actual-pt actual-diff
))
6126 (set-window-point win actual-pt
))))))
6128 (defun markdown-live-preview-export ()
6129 "Export to XHTML using `markdown-export'.
6130 Browse the resulting file within Emacs using
6131 `markdown-live-preview-window-function' Return the buffer
6132 displaying the rendered output."
6134 (let* ((markdown-live-preview-currently-exporting t
)
6135 (cur-buf (current-buffer))
6136 (export-file (markdown-export (markdown-live-preview-get-filename)))
6137 ;; get positions in all windows currently displaying output buffer
6139 (markdown-live-preview-window-serialize
6140 markdown-live-preview-buffer
)))
6141 (save-window-excursion
6142 (let ((output-buffer
6143 (funcall markdown-live-preview-window-function export-file
)))
6144 (with-current-buffer output-buffer
6145 (setq markdown-live-preview-source-buffer cur-buf
)
6146 (add-hook 'kill-buffer-hook
6147 #'markdown-live-preview-remove-on-kill t t
))
6148 (with-current-buffer cur-buf
6149 (setq markdown-live-preview-buffer output-buffer
))))
6150 (with-current-buffer cur-buf
6151 ;; reset all windows displaying output buffer to where they were,
6152 ;; now with the new output
6153 (mapc #'markdown-live-preview-window-deserialize window-data
)
6154 ;; delete html editing buffer
6155 (let ((buf (get-file-buffer export-file
))) (when buf
(kill-buffer buf
)))
6156 (when (and export-file
(file-exists-p export-file
)
6157 (eq markdown-live-preview-delete-export
6159 (delete-file export-file
))
6160 markdown-live-preview-buffer
)))
6162 (defun markdown-live-preview-remove ()
6163 (when (buffer-live-p markdown-live-preview-buffer
)
6164 (kill-buffer markdown-live-preview-buffer
))
6165 (setq markdown-live-preview-buffer nil
)
6166 ;; if set to 'delete-on-export, the output has already been deleted
6167 (when (eq markdown-live-preview-delete-export
'delete-on-destroy
)
6168 (let ((outfile-name (markdown-live-preview-get-filename)))
6169 (when (file-exists-p outfile-name
)
6170 (delete-file outfile-name
)))))
6172 (defun markdown-display-buffer-other-window (buf)
6173 (let ((cur-buf (current-buffer))
6174 split-width-threshold split-height-threshold
)
6175 (cond ((memq markdown-split-window-direction
'(vertical below
))
6176 (setq split-width-threshold nil
)
6177 (setq split-height-threshold
0))
6178 ((memq markdown-split-window-direction
'(horizontal right
))
6179 (setq split-width-threshold
0)
6180 (setq split-height-threshold nil
)))
6181 (switch-to-buffer-other-window buf
)
6182 (set-buffer cur-buf
)))
6184 (defun markdown-live-preview-if-markdown ()
6185 (when (and (derived-mode-p 'markdown-mode
)
6186 markdown-live-preview-mode
)
6187 (unless markdown-live-preview-currently-exporting
6188 (if (buffer-live-p markdown-live-preview-buffer
)
6189 (markdown-live-preview-export)
6190 (markdown-display-buffer-other-window
6191 (markdown-live-preview-export))))))
6193 (defun markdown-live-preview-remove-on-kill ()
6194 (cond ((and (derived-mode-p 'markdown-mode
)
6195 markdown-live-preview-mode
)
6196 (markdown-live-preview-remove))
6197 (markdown-live-preview-source-buffer
6198 (with-current-buffer markdown-live-preview-source-buffer
6199 (setq markdown-live-preview-buffer nil
))
6200 (setq markdown-live-preview-source-buffer nil
))))
6202 (defun markdown-live-preview-switch-to-output ()
6203 "Switch to output buffer."
6205 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
6206 output buffer in another window."
6207 (if markdown-live-preview-mode
6208 (markdown-display-buffer-other-window (markdown-live-preview-export)))
6209 (markdown-live-preview-mode))
6211 (defun markdown-live-preview-re-export ()
6212 "Re export source buffer."
6214 "If the current buffer is a buffer displaying the exported version of a
6215 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
6216 update this buffer's contents."
6217 (when markdown-live-preview-source-buffer
6218 (with-current-buffer markdown-live-preview-source-buffer
6219 (markdown-live-preview-export))))
6221 (defun markdown-open ()
6222 "Open file for the current buffer with `markdown-open-command'."
6224 (if (not markdown-open-command
)
6225 (error "Variable `markdown-open-command' must be set")
6226 (if (not buffer-file-name
)
6227 (error "Must be visiting a file")
6228 (call-process markdown-open-command
6229 nil nil nil buffer-file-name
))))
6231 (defun markdown-kill-ring-save ()
6232 "Run Markdown on file and store output in the kill ring."
6234 (save-window-excursion
6236 (with-current-buffer markdown-output-buffer-name
6237 (kill-ring-save (point-min) (point-max)))))
6240 ;;; Links =====================================================================
6242 (defun markdown-link-p ()
6243 "Return non-nil when `point' is at a non-wiki link.
6244 See `markdown-wiki-link-p' for more information."
6245 (let ((case-fold-search nil
))
6246 (and (not (markdown-wiki-link-p))
6247 (not (markdown-code-block-at-point))
6248 (or (thing-at-point-looking-at markdown-regex-link-inline
)
6249 (thing-at-point-looking-at markdown-regex-link-reference
)
6250 (thing-at-point-looking-at markdown-regex-uri
)
6251 (thing-at-point-looking-at markdown-regex-angle-uri
)))))
6253 (defun markdown-link-link ()
6254 "Return the link part of the regular (non-wiki) link at point.
6255 Works with both inline and reference style links. If point is
6256 not at a link or the link reference is not defined returns nil."
6258 ((thing-at-point-looking-at markdown-regex-link-inline
)
6259 (match-string-no-properties 6))
6260 ((thing-at-point-looking-at markdown-regex-link-reference
)
6261 (let* ((text (match-string-no-properties 3))
6262 (reference (match-string-no-properties 6))
6263 (target (downcase (if (string= reference
"") text reference
))))
6264 (car (markdown-reference-definition target
))))
6265 ((thing-at-point-looking-at markdown-regex-uri
)
6266 (match-string-no-properties 0))
6267 ((thing-at-point-looking-at markdown-regex-angle-uri
)
6268 (match-string-no-properties 2))
6271 (defun markdown-follow-link-at-point ()
6272 "Open the current non-wiki link.
6273 If the link is a complete URL, open in browser with `browse-url'.
6274 Otherwise, open with `find-file' after stripping anchor and/or query string."
6276 (if (markdown-link-p)
6277 (let* ((link (markdown-link-link))
6278 (struct (url-generic-parse-url link
))
6279 (full (url-fullness struct
))
6281 ;; Parse URL, determine fullness, strip query string
6282 (if (fboundp 'url-path-and-query
)
6283 (setq file
(car (url-path-and-query struct
)))
6284 (when (and (setq file
(url-filename struct
))
6285 (string-match "\\?" file
))
6286 (setq file
(substring file
0 (match-beginning 0)))))
6287 ;; Open full URLs in browser, files in Emacs
6290 (when (and file
(> (length file
) 0)) (find-file file
))))
6291 (error "Point is not at a Markdown link or URI")))
6294 ;;; WikiLink Following/Markup =================================================
6296 (defun markdown-wiki-link-p ()
6297 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
6298 A true wiki link name matches `markdown-regex-wiki-link' but does
6299 not match the current file name after conversion. This modifies
6300 the data returned by `match-data'. Note that the potential wiki
6301 link name must be available via `match-string'."
6302 (when markdown-enable-wiki-links
6303 (let ((case-fold-search nil
))
6304 (and (thing-at-point-looking-at markdown-regex-wiki-link
)
6305 (not (markdown-code-block-at-point))
6306 (or (not buffer-file-name
)
6307 (not (string-equal (buffer-file-name)
6308 (markdown-convert-wiki-link-to-filename
6309 (markdown-wiki-link-link)))))))))
6311 (defun markdown-wiki-link-link ()
6312 "Return the link part of the wiki link using current match data.
6313 The location of the link component depends on the value of
6314 `markdown-wiki-link-alias-first'."
6315 (if markdown-wiki-link-alias-first
6316 (or (match-string-no-properties 5) (match-string-no-properties 3))
6317 (match-string-no-properties 3)))
6319 (defun markdown-wiki-link-alias ()
6320 "Return the alias or text part of the wiki link using current match data.
6321 The location of the alias component depends on the value of
6322 `markdown-wiki-link-alias-first'."
6323 (if markdown-wiki-link-alias-first
6324 (match-string-no-properties 3)
6325 (or (match-string-no-properties 5) (match-string-no-properties 3))))
6327 (defun markdown-convert-wiki-link-to-filename (name)
6328 "Generate a filename from the wiki link NAME.
6329 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
6330 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
6331 and [[test test]] both map to Test-test.ext. Look in the current
6332 directory first, then in subdirectories if
6333 `markdown-wiki-link-search-subdirectories' is non-nil, and then
6334 in parent directories if
6335 `markdown-wiki-link-search-parent-directories' is non-nil."
6336 (let* ((basename (markdown-replace-regexp-in-string
6337 "[[:space:]\n]" markdown-link-space-sub-char name
))
6338 (basename (if (eq major-mode
'gfm-mode
)
6339 (concat (upcase (substring basename
0 1))
6340 (downcase (substring basename
1 nil
)))
6342 directory extension default candidates dir
)
6343 (when buffer-file-name
6344 (setq directory
(file-name-directory buffer-file-name
)
6345 extension
(file-name-extension buffer-file-name
)))
6346 (setq default
(concat basename
6347 (when extension
(concat "." extension
))))
6349 ;; Look in current directory first.
6350 ((or (null buffer-file-name
)
6351 (file-exists-p default
))
6353 ;; Possibly search in subdirectories, next.
6354 ((and markdown-wiki-link-search-subdirectories
6356 (markdown-directory-files-recursively
6357 directory
(concat "^" default
"$"))))
6359 ;; Possibly search in parent directories as a last resort.
6360 ((and markdown-wiki-link-search-parent-directories
6361 (setq dir
(locate-dominating-file directory default
)))
6362 (concat dir default
))
6363 ;; If nothing is found, return default in current directory.
6366 (defun markdown-follow-wiki-link (name &optional other
)
6367 "Follow the wiki link NAME.
6368 Convert the name to a file name and call `find-file'. Ensure that
6369 the new buffer remains in `markdown-mode'. Open the link in another
6370 window when OTHER is non-nil."
6371 (let ((filename (markdown-convert-wiki-link-to-filename name
))
6372 (wp (when buffer-file-name
6373 (file-name-directory buffer-file-name
))))
6375 (error "Must be visiting a file")
6376 (when other
(other-window 1))
6377 (let ((default-directory wp
))
6378 (find-file filename
)))
6379 (when (not (eq major-mode
'markdown-mode
))
6382 (defun markdown-follow-wiki-link-at-point (&optional arg
)
6383 "Find Wiki Link at point.
6384 With prefix argument ARG, open the file in other window.
6385 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
6387 (if (markdown-wiki-link-p)
6388 (markdown-follow-wiki-link (markdown-wiki-link-link) arg
)
6389 (error "Point is not at a Wiki Link")))
6391 (defun markdown-highlight-wiki-link (from to face
)
6392 "Highlight the wiki link in the region between FROM and TO using FACE."
6393 (put-text-property from to
'font-lock-face face
))
6395 (defun markdown-unfontify-region-wiki-links (from to
)
6396 "Remove wiki link faces from the region specified by FROM and TO."
6398 (let ((modified (buffer-modified-p)))
6399 (remove-text-properties from to
'(font-lock-face markdown-link-face
))
6400 (remove-text-properties from to
'(font-lock-face markdown-missing-link-face
))
6401 ;; remove-text-properties marks the buffer modified in emacs 24.3,
6402 ;; undo that if it wasn't originally marked modified
6403 (set-buffer-modified-p modified
)))
6405 (defun markdown-fontify-region-wiki-links (from to
)
6406 "Search region given by FROM and TO for wiki links and fontify them.
6407 If a wiki link is found check to see if the backing file exists
6408 and highlight accordingly."
6411 (while (re-search-forward markdown-regex-wiki-link to t
)
6412 (when (not (markdown-code-block-at-point))
6413 (let ((highlight-beginning (match-beginning 1))
6414 (highlight-end (match-end 1))
6416 (markdown-convert-wiki-link-to-filename
6417 (markdown-wiki-link-link))))
6418 (if (condition-case nil
(file-exists-p file-name
) (error nil
))
6419 (markdown-highlight-wiki-link
6420 highlight-beginning highlight-end markdown-link-face
)
6421 (markdown-highlight-wiki-link
6422 highlight-beginning highlight-end markdown-missing-link-face
)))))))
6424 (defun markdown-extend-changed-region (from to
)
6425 "Extend region given by FROM and TO so that we can fontify all links.
6426 The region is extended to the first newline before and the first
6428 ;; start looking for the first new line before 'from
6430 (re-search-backward "\n" nil t
)
6431 (let ((new-from (point-min))
6432 (new-to (point-max)))
6433 (if (not (= (point) from
))
6434 (setq new-from
(point)))
6435 ;; do the same thing for the first new line after 'to
6437 (re-search-forward "\n" nil t
)
6438 (if (not (= (point) to
))
6439 (setq new-to
(point)))
6440 (cl-values new-from new-to
)))
6442 (defun markdown-check-change-for-wiki-link (from to
)
6443 "Check region between FROM and TO for wiki links and re-fontify as needed."
6445 (let* ((modified (buffer-modified-p))
6446 (buffer-undo-list t
)
6447 (inhibit-read-only t
)
6448 (inhibit-point-motion-hooks t
)
6450 buffer-file-truename
)
6455 ;; Extend the region to fontify so that it starts
6456 ;; and ends at safe places.
6457 (cl-multiple-value-bind (new-from new-to
)
6458 (markdown-extend-changed-region from to
)
6459 (goto-char new-from
)
6460 ;; Only refontify when the range contains text with a
6461 ;; wiki link face or if the wiki link regexp matches.
6462 (when (or (markdown-range-property-any
6463 new-from new-to
'font-lock-face
6464 (list markdown-link-face
6465 markdown-missing-link-face
))
6467 markdown-regex-wiki-link new-to t
))
6468 ;; Unfontify existing fontification (start from scratch)
6469 (markdown-unfontify-region-wiki-links new-from new-to
)
6470 ;; Now do the fontification.
6471 (markdown-fontify-region-wiki-links new-from new-to
))))))
6474 (set-buffer-modified-p nil
)))))
6476 (defun markdown-check-change-for-wiki-link-after-change (from to _
)
6477 "Check region between FROM and TO for wiki links and re-fontify as needed.
6478 Designed to be used with the `after-change-functions' hook."
6479 (markdown-check-change-for-wiki-link from to
))
6481 (defun markdown-fontify-buffer-wiki-links ()
6482 "Refontify all wiki links in the buffer."
6484 (markdown-check-change-for-wiki-link (point-min) (point-max)))
6487 ;;; Following and Jumping =====================================================
6489 (defun markdown-follow-thing-at-point (arg)
6490 "Follow thing at point if possible, such as a reference link or wiki link.
6491 Opens inline and reference links in a browser. Opens wiki links
6492 to other files in the current window, or the another window if
6494 See `markdown-follow-link-at-point' and
6495 `markdown-follow-wiki-link-at-point'."
6497 (cond ((markdown-link-p)
6498 (markdown-follow-link-at-point))
6499 ((markdown-wiki-link-p)
6500 (markdown-follow-wiki-link-at-point arg
))
6502 (error "Nothing to follow at point"))))
6504 (defun markdown-jump ()
6505 "Jump to another location based on context at point.
6506 Jumps between reference links and definitions; between footnote
6507 markers and footnote text."
6509 (cond ((markdown-footnote-text-positions)
6510 (markdown-footnote-return))
6511 ((markdown-footnote-marker-positions)
6512 (markdown-footnote-goto-text))
6513 ((thing-at-point-looking-at markdown-regex-link-reference
)
6514 (markdown-reference-goto-definition))
6515 ((thing-at-point-looking-at markdown-regex-reference-definition
)
6516 (markdown-reference-goto-link (match-string-no-properties 2)))
6518 (error "Nothing to jump to from context at point"))))
6521 ;;; Miscellaneous =============================================================
6523 (defun markdown-compress-whitespace-string (str)
6524 "Compress whitespace in STR and return result.
6525 Leading and trailing whitespace is removed. Sequences of multiple
6526 spaces, tabs, and newlines are replaced with single spaces."
6527 (markdown-replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
6528 (markdown-replace-regexp-in-string "[ \t\n]+" " " str
)))
6530 (defun markdown-line-number-at-pos (&optional pos
)
6531 "Return (narrowed) buffer line number at position POS.
6532 If POS is nil, use current buffer location.
6533 This is an exact copy of `line-number-at-pos' for use in emacs21."
6534 (let ((opoint (or pos
(point))) start
)
6536 (goto-char (point-min))
6537 (setq start
(point))
6540 (1+ (count-lines start
(point))))))
6542 (defun markdown-inside-link-p ()
6543 "Return t if point is within a link."
6545 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
6547 (defun markdown-line-is-reference-definition-p ()
6548 "Return whether the current line is a (non-footnote) reference defition."
6550 (move-beginning-of-line 1)
6551 (and (looking-at-p markdown-regex-reference-definition
)
6552 (not (looking-at-p "[ \t]*\\[^")))))
6554 (defun markdown-adaptive-fill-function ()
6555 "Return prefix for filling paragraph or nil if not determined."
6557 ;; List item inside blockquote
6558 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
6559 (markdown-replace-regexp-in-string
6560 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
6562 ((looking-at "^[ \t]*>[ \t]*")
6563 (match-string-no-properties 0))
6565 ((looking-at markdown-regex-list
)
6566 (match-string-no-properties 0))
6567 ((looking-at-p markdown-regex-footnote-definition
)
6572 (defun markdown-fill-paragraph (&optional justify
)
6573 "Fill paragraph at or after point.
6574 This function is like \\[fill-paragraph], but it skips Markdown
6575 code blocks. If the point is in a code block, or just before one,
6576 do not fill. Otherwise, call `fill-paragraph' as usual. If
6577 JUSTIFY is non-nil, justify text as well. Since this function
6578 handles filling itself, it always returns t so that
6579 `fill-paragraph' doesn't run."
6581 (unless (or (markdown-code-block-at-point-p)
6583 (back-to-indentation)
6584 (skip-syntax-forward "-")
6585 (markdown-code-block-at-point-p)))
6586 (fill-paragraph justify
))
6589 (defun markdown-fill-forward-paragraph-function (&optional arg
)
6590 "Function used by `fill-paragraph' to move over ARG paragraphs.
6591 This is a `fill-forward-paragraph-function' for `markdown-mode'.
6592 It is called with a single argument specifying the number of
6593 paragraphs to move. Just like `forward-paragraph', it should
6594 return the number of paragraphs left to move."
6595 (let* ((arg (or arg
1))
6596 (paragraphs-remaining (forward-paragraph arg
))
6599 (while (and (not (eobp))
6600 (progn (move-to-left-margin) (not (eobp)))
6601 (looking-at-p paragraph-separate
))
6603 (if (looking-at markdown-regex-list
)
6604 (forward-char (length (match-string 0)))
6606 paragraphs-remaining
))
6609 ;;; Extension Framework =======================================================
6611 (defun markdown-reload-extensions ()
6612 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
6614 (when (eq major-mode
'markdown-mode
)
6615 ;; Update font lock keywords with extensions
6616 (setq markdown-mode-font-lock-keywords
6618 (markdown-mode-font-lock-keywords-math)
6619 markdown-mode-font-lock-keywords-basic
6620 (markdown-mode-font-lock-keywords-wiki-links)))
6621 ;; Update font lock defaults
6622 (setq font-lock-defaults
6623 '(markdown-mode-font-lock-keywords
6625 (font-lock-syntactic-face-function . markdown-syntactic-face
)))
6627 (when (and font-lock-mode
(fboundp 'font-lock-refresh-defaults
))
6628 (font-lock-refresh-defaults))
6630 ;; Add or remove hooks related to extensions
6631 (markdown-setup-wiki-link-hooks)))
6633 (defun markdown-handle-local-variables ()
6634 "Run in `hack-local-variables-hook' to update font lock rules.
6635 Checks to see if there is actually a ‘markdown-mode’ file local variable
6636 before regenerating font-lock rules for extensions."
6637 (when (and (boundp 'file-local-variables-alist
)
6638 (assoc 'markdown-enable-wiki-links file-local-variables-alist
)
6639 (assoc 'markdown-enable-math file-local-variables-alist
))
6640 (markdown-reload-extensions)))
6643 ;;; Wiki Links ================================================================
6645 (defun markdown-toggle-wiki-links (&optional arg
)
6646 "Toggle support for wiki links.
6647 With a prefix argument ARG, enable wiki link support if ARG is positive,
6648 and disable it otherwise."
6649 (interactive (list (or current-prefix-arg
'toggle
)))
6650 (setq markdown-enable-wiki-links
6651 (if (eq arg
'toggle
)
6652 (not markdown-enable-wiki-links
)
6653 (> (prefix-numeric-value arg
) 0)))
6654 (if markdown-enable-wiki-links
6655 (message "markdown-mode wiki link support enabled")
6656 (message "markdown-mode wiki link support disabled"))
6657 (markdown-reload-extensions))
6659 (defun markdown-setup-wiki-link-hooks ()
6660 "Add or remove hooks for fontifying wiki links.
6661 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
6662 ;; Anytime text changes make sure it gets fontified correctly
6663 (if (and markdown-enable-wiki-links
6664 markdown-wiki-link-fontify-missing
)
6665 (add-hook 'after-change-functions
6666 'markdown-check-change-for-wiki-link-after-change t t
)
6667 (remove-hook 'after-change-functions
6668 'markdown-check-change-for-wiki-link-after-change t
))
6669 ;; If we left the buffer there is a really good chance we were
6670 ;; creating one of the wiki link documents. Make sure we get
6671 ;; refontified when we come back.
6672 (if (and markdown-enable-wiki-links
6673 markdown-wiki-link-fontify-missing
)
6675 (add-hook 'window-configuration-change-hook
6676 'markdown-fontify-buffer-wiki-links t t
)
6677 (markdown-fontify-buffer-wiki-links))
6678 (remove-hook 'window-configuration-change-hook
6679 'markdown-fontify-buffer-wiki-links t
)
6680 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
6682 (defun markdown-mode-font-lock-keywords-wiki-links ()
6683 "Return wiki-link lock keywords if support is enabled.
6684 If `markdown-wiki-link-fontify-missing' is also enabled, we use
6685 hooks in `markdown-setup-wiki-link-hooks' for fontification instead."
6686 (when (and markdown-enable-wiki-links
6687 (not markdown-wiki-link-fontify-missing
))
6689 (cons markdown-regex-wiki-link
'((1 markdown-link-face prepend
))))))
6692 ;;; Math Support ==============================================================
6694 (make-obsolete 'markdown-enable-math
'markdown-toggle-math
"v2.1")
6696 (defun markdown-toggle-math (&optional arg
)
6697 "Toggle support for inline and display LaTeX math expressions.
6698 With a prefix argument ARG, enable math mode if ARG is positive,
6699 and disable it otherwise. If called from Lisp, enable the mode
6700 if ARG is omitted or nil."
6701 (interactive (list (or current-prefix-arg
'toggle
)))
6702 (setq markdown-enable-math
6703 (if (eq arg
'toggle
)
6704 (not markdown-enable-math
)
6705 (> (prefix-numeric-value arg
) 0)))
6706 (if markdown-enable-math
6707 (message "markdown-mode math support enabled")
6708 (message "markdown-mode math support disabled"))
6709 (markdown-reload-extensions))
6711 (defun markdown-mode-font-lock-keywords-math ()
6712 "Return math font lock keywords if support is enabled."
6713 (when markdown-enable-math
6715 ;; Display mode equations with brackets: \[ \]
6716 (cons markdown-regex-math-display
'((1 markdown-markup-face prepend
)
6717 (2 markdown-math-face append
)
6718 (3 markdown-markup-face prepend
)))
6719 ;; Equation reference (eq:foo)
6720 (cons "\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" '((1 markdown-markup-face
)
6721 (2 markdown-reference-face
)
6722 (3 markdown-markup-face
)))
6723 ;; Equation reference \eqref{foo}
6724 (cons "\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" '((1 markdown-markup-face
)
6725 (2 markdown-reference-face
)
6726 (3 markdown-markup-face
))))))
6729 ;;; GFM Checkboxes ============================================================
6733 (define-button-type 'markdown-gfm-checkbox-button
6735 'face
'markdown-gfm-checkbox-face
6736 'mouse-face
'markdown-highlight-face
6737 'action
#'markdown-toggle-gfm-checkbox-button
)
6739 (defun markdown-toggle-gfm-checkbox ()
6740 "Toggle GFM checkbox at point."
6744 (let ((bounds (markdown-cur-list-item-bounds)))
6746 ;; Move to beginning of task list item
6747 (goto-char (cl-first bounds
))
6748 ;; Advance to column of first non-whitespace after marker
6749 (forward-char (cl-fourth bounds
))
6750 (cond ((looking-at "\\[ \\]")
6751 (replace-match "[x]" nil t
))
6752 ((looking-at "\\[[xX]\\]")
6753 (replace-match "[ ]" nil t
))))))))
6755 (defun markdown-toggle-gfm-checkbox-button (button)
6756 "Toggle GFM checkbox BUTTON on click."
6759 (goto-char (button-start button
))
6760 (markdown-toggle-gfm-checkbox))))
6762 (defun markdown-make-gfm-checkboxes-buttons (start end
)
6763 "Make GFM checkboxes buttons in region between START and END."
6766 (let ((case-fold-search t
))
6768 (while (re-search-forward markdown-regex-gfm-checkbox end t
)
6769 (make-button (match-beginning 1) (match-end 1)
6770 :type
'markdown-gfm-checkbox-button
))))))
6772 ;; Called when any modification is made to buffer text.
6773 (defun markdown-gfm-checkbox-after-change-function (beg end _
)
6774 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
6775 BEG and END are the limits of scanned region."
6778 ;; Rescan between start of line from `beg' and start of line after `end'.
6779 (markdown-make-gfm-checkboxes-buttons
6780 (progn (goto-char beg
) (beginning-of-line) (point))
6781 (progn (goto-char end
) (forward-line 1) (point))))))
6784 ;;; Display inline image =================================================
6786 (defvar markdown-inline-image-overlays nil
)
6787 (make-variable-buffer-local 'markdown-inline-image-overlays
)
6789 (defun markdown-remove-inline-images ()
6790 "Remove inline image overlays from image links in the buffer.
6791 This can be toggled with `markdown-toggle-inline-images'
6792 or \\[markdown-toggle-inline-images]."
6794 (mapc #'delete-overlay markdown-inline-image-overlays
)
6795 (setq markdown-inline-image-overlays nil
))
6797 (defun markdown-display-inline-images ()
6798 "Add inline image overlays to image links in the buffer.
6799 This can be toggled with `markdown-toggle-inline-images'
6800 or \\[markdown-toggle-inline-images]."
6802 (unless (display-graphic-p)
6803 (error "Cannot show images"))
6807 (goto-char (point-min))
6808 (while (re-search-forward markdown-regex-link-inline nil t
)
6809 (let ((start (match-beginning 0))
6811 (file (match-string-no-properties 6)))
6812 (when (file-exists-p file
)
6813 (let* ((abspath (if (file-name-absolute-p file
)
6815 (concat default-directory file
)))
6816 (image (create-image abspath
)))
6818 (let ((ov (make-overlay start end
)))
6819 (overlay-put ov
'display image
)
6820 (overlay-put ov
'face
'default
)
6821 (push ov markdown-inline-image-overlays
))))))))))
6823 (defun markdown-toggle-inline-images ()
6824 "Toggle inline image overlays in the buffer."
6826 (if markdown-inline-image-overlays
6827 (markdown-remove-inline-images)
6828 (markdown-display-inline-images)))
6831 ;;; Mode Definition ==========================================================
6833 (defun markdown-show-version ()
6834 "Show the version number in the minibuffer."
6836 (message "markdown-mode, version %s" markdown-mode-version
))
6838 (defun markdown-mode-info ()
6839 "Open the `markdown-mode' homepage."
6841 (browse-url "http://jblevins.org/projects/markdown-mode/"))
6844 (define-derived-mode markdown-mode text-mode
"Markdown"
6845 "Major mode for editing Markdown files."
6846 ;; Natural Markdown tab width
6849 (make-local-variable 'comment-start
)
6850 (setq comment-start
"<!-- ")
6851 (make-local-variable 'comment-end
)
6852 (setq comment-end
" -->")
6853 (make-local-variable 'comment-start-skip
)
6854 (setq comment-start-skip
"<!--[ \t]*")
6855 (make-local-variable 'comment-column
)
6856 (setq comment-column
0)
6857 (set (make-local-variable 'comment-auto-fill-only-comments
) nil
)
6859 (add-hook 'syntax-propertize-extend-region-functions
6860 'markdown-syntax-propertize-extend-region
)
6861 (add-hook 'jit-lock-after-change-extend-region-functions
6862 'markdown-font-lock-extend-region-function t t
)
6863 (set (make-local-variable 'syntax-propertize-function
)
6864 'markdown-syntax-propertize
)
6866 (set (make-local-variable 'markdown-mode-font-lock-keywords
) nil
)
6867 (set (make-local-variable 'font-lock-defaults
) nil
)
6868 (set (make-local-variable 'font-lock-multiline
) t
)
6870 (make-local-variable 'markdown-enable-math
)
6871 ;; Reload extensions
6872 (markdown-reload-extensions)
6873 ;; Add a buffer-local hook to reload after file-local variables are read
6874 (add-hook 'hack-local-variables-hook
'markdown-handle-local-variables nil t
)
6875 ;; For imenu support
6876 (setq imenu-create-index-function
6877 (if markdown-nested-imenu-heading-index
6878 'markdown-imenu-create-nested-index
6879 'markdown-imenu-create-flat-index
))
6880 ;; For menu support in XEmacs
6881 (easy-menu-add markdown-mode-menu markdown-mode-map
)
6883 (set (make-local-variable 'beginning-of-defun-function
)
6884 'markdown-beginning-of-defun
)
6885 (set (make-local-variable 'end-of-defun-function
)
6886 'markdown-end-of-defun
)
6887 ;; Paragraph filling
6888 (set (make-local-variable 'fill-paragraph-function
)
6889 'markdown-fill-paragraph
)
6891 ;; Should match start of lines that start or separate paragraphs
6892 (make-local-variable 'paragraph-start
)
6893 (mapconcat #'identity
6895 "\f" ; starts with a literal line-feed
6896 "[ \t\f]*$" ; space-only line
6897 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
6898 "[ \t]*[*+-][ \t]+" ; unordered list item
6899 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
6900 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
6901 "[ \t]*:[ \t]+" ; definition
6905 ;; Should match lines that separate paragraphs without being
6906 ;; part of any paragraph:
6907 (make-local-variable 'paragraph-separate
)
6908 (mapconcat #'identity
6909 '("[ \t\f]*$" ; space-only line
6910 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
6911 ;; The following is not ideal, but the Fill customization
6912 ;; options really only handle paragraph-starting prefixes,
6913 ;; not paragraph-ending suffixes:
6914 ".* $" ; line ending in two spaces
6916 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
6918 (set (make-local-variable 'adaptive-fill-first-line-regexp
)
6919 "\\`[ \t]*>[ \t]*?\\'")
6920 (set (make-local-variable 'adaptive-fill-regexp
) "\\s-*")
6921 (set (make-local-variable 'adaptive-fill-function
)
6922 'markdown-adaptive-fill-function
)
6923 (set (make-local-variable 'fill-forward-paragraph-function
)
6924 'markdown-fill-forward-paragraph-function
)
6926 (make-local-variable 'outline-regexp
)
6927 (setq outline-regexp markdown-regex-header
)
6928 (make-local-variable 'outline-level
)
6929 (setq outline-level
'markdown-outline-level
)
6930 ;; Cause use of ellipses for invisible text.
6931 (add-to-invisibility-spec '(outline . t
))
6933 ;; Inhibiting line-breaking:
6934 ;; Separating out each condition into a separate function so that users can
6935 ;; override if desired (with remove-hook)
6936 (add-hook 'fill-nobreak-predicate
6937 'markdown-inside-link-p nil t
)
6938 (add-hook 'fill-nobreak-predicate
6939 'markdown-line-is-reference-definition-p nil t
)
6942 (setq indent-line-function markdown-indent-function
)
6944 ;; Backwards compatibility with markdown-css-path
6945 (when (boundp 'markdown-css-path
)
6946 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
6947 (add-to-list 'markdown-css-paths markdown-css-path
))
6949 ;; Prepare hooks for XEmacs compatibility
6950 (when (featurep 'xemacs
)
6951 (make-local-hook 'after-change-functions
)
6952 (make-local-hook 'font-lock-extend-region-functions
)
6953 (make-local-hook 'window-configuration-change-hook
))
6955 ;; Initial syntax analysis
6956 (markdown-syntax-propertize (point-min) (point-max))
6958 ;; Make checkboxes buttons
6959 (when markdown-make-gfm-checkboxes-buttons
6960 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
6961 (add-hook 'after-change-functions
'markdown-gfm-checkbox-after-change-function t t
))
6963 ;; add live preview export hook
6964 (add-hook 'after-save-hook
#'markdown-live-preview-if-markdown t t
)
6965 (add-hook 'kill-buffer-hook
#'markdown-live-preview-remove-on-kill t t
))
6968 (add-to-list 'auto-mode-alist
'("\\.markdown\\'" . markdown-mode
) t
)
6970 (add-to-list 'auto-mode-alist
'("\\.md\\'" . markdown-mode
) t
)
6973 ;;; GitHub Flavored Markdown Mode ============================================
6975 (defvar gfm-mode-hook nil
6976 "Hook run when entering GFM mode.")
6978 (defvar gfm-font-lock-keywords
6980 ;; GFM features to match first
6982 (cons markdown-regex-strike-through
'((3 markdown-markup-face
)
6983 (4 markdown-strike-through-face
)
6984 (5 markdown-markup-face
))))
6985 ;; Basic Markdown features (excluding possibly overridden ones)
6986 markdown-mode-font-lock-keywords-basic
)
6987 "Default highlighting expressions for GitHub Flavored Markdown mode.")
6990 (define-derived-mode gfm-mode markdown-mode
"GFM"
6991 "Major mode for editing GitHub Flavored Markdown files."
6992 (setq markdown-link-space-sub-char
"-")
6993 (setq markdown-wiki-link-search-subdirectories t
)
6994 (set (make-local-variable 'font-lock-defaults
)
6995 '(gfm-font-lock-keywords))
6996 ;; do the initial link fontification
6997 (markdown-gfm-parse-buffer-for-languages))
7000 ;;; Live Preview Mode ============================================
7001 (define-minor-mode markdown-live-preview-mode
7002 "Toggle native previewing on save for a specific markdown file."
7003 :lighter
" MD-Preview"
7004 (if markdown-live-preview-mode
7005 (markdown-display-buffer-other-window (markdown-live-preview-export))
7006 (markdown-live-preview-remove)))
7009 (provide 'markdown-mode
)
7011 ;; indent-tabs-mode: nil
7013 ;;; markdown-mode.el ends here