1 ;;; markdown-mode.el --- Emacs Major mode for Markdown-formatted text files
3 ;; Copyright (C) 2007-2013 Jason R. Blevins <jrblevin@sdf.org>
4 ;; Copyright (C) 2007, 2009 Edward O'Connor <ted@oconnor.cx>
5 ;; Copyright (C) 2007 Conal Elliott <conal@conal.net>
6 ;; Copyright (C) 2008 Greg Bognar <greg_bognar@hms.harvard.edu>
7 ;; Copyright (C) 2008 Dmitry Dzhus <mail@sphinx.net.ru>
8 ;; Copyright (C) 2008 Bryan Kyle <bryan.kyle@gmail.com>
9 ;; Copyright (C) 2008 Ben Voui <intrigeri@boum.org>
10 ;; Copyright (C) 2009 Ankit Solanki <ankit.solanki@gmail.com>
11 ;; Copyright (C) 2009 Hilko Bengen <bengen@debian.org>
12 ;; Copyright (C) 2009 Peter Williams <pezra@barelyenough.org>
13 ;; Copyright (C) 2010 George Ogata <george.ogata@gmail.com>
14 ;; Copyright (C) 2011 Eric Merritt <ericbmerritt@gmail.com>
15 ;; Copyright (C) 2011 Philippe Ivaldi <pivaldi@sfr.fr>
16 ;; Copyright (C) 2011 Jeremiah Dodds <jeremiah.dodds@gmail.com>
17 ;; Copyright (C) 2011 Christopher J. Madsen <cjm@cjmweb.net>
18 ;; Copyright (C) 2011 Shigeru Fukaya <shigeru.fukaya@gmail.com>
19 ;; Copyright (C) 2011 Joost Kremers <joostkremers@fastmail.fm>
20 ;; Copyright (C) 2011-2012 Donald Ephraim Curtis <dcurtis@milkbox.net>
21 ;; Copyright (C) 2012 Akinori Musha <knu@idaemons.org>
22 ;; Copyright (C) 2012 Zhenlei Jia <zhenlei.jia@gmail.com>
23 ;; Copyright (C) 2012 Peter Jones <pjones@pmade.com>
24 ;; Copyright (C) 2013 Matus Goljer <dota.keys@gmail.com>
26 ;; Author: Jason R. Blevins <jrblevin@sdf.org>
27 ;; Maintainer: Jason R. Blevins <jrblevin@sdf.org>
28 ;; Created: May 24, 2007
30 ;; Keywords: Markdown, GitHub Flavored Markdown, itex
31 ;; URL: http://jblevins.org/projects/markdown-mode/
33 ;; This file is not part of GNU Emacs.
35 ;; This program is free software; you can redistribute it and/or modify
36 ;; it under the terms of the GNU General Public License as published by
37 ;; the Free Software Foundation; either version 2, or (at your option)
40 ;; This program is distributed in the hope that it will be useful,
41 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
42 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
43 ;; GNU General Public License for more details.
45 ;; You should have received a copy of the GNU General Public License
46 ;; along with this program; if not, write to the Free Software
47 ;; Foundation, Inc., 51 Franklin Street, Fifth Floor,
48 ;; Boston, MA 02110-1301, USA.
52 ;; markdown-mode is a major mode for editing [Markdown][]-formatted
53 ;; text files in GNU Emacs. markdown-mode is free software, licensed
56 ;; [Markdown]: http://daringfireball.net/projects/markdown/
58 ;; The latest stable version is markdown-mode 1.9, released on January 25, 2013:
60 ;; * [markdown-mode.el][]
61 ;; * [Screenshot][][^theme]
62 ;; * [Release notes][]
64 ;; [markdown-mode.el]: http://jblevins.org/projects/markdown-mode/markdown-mode.el
65 ;; [screenshot]: http://jblevins.org/projects/markdown-mode/screenshots/20110812-001.png
66 ;; [release notes]: http://jblevins.org/projects/markdown-mode/rev-1-9
68 ;; [^theme]: The theme used in the screenshot is
69 ;; [color-theme-twilight](https://github.com/crafterm/twilight-emacs).
71 ;; markdown-mode is also available in several package managers, including:
73 ;; * Debian and Ubuntu Linux: [emacs-goodies-el][]
74 ;; * RedHat and Fedora Linux: [emacs-goodies][]
75 ;; * OpenBSD: [textproc/markdown-mode][]
76 ;; * Arch Linux (AUR): [emacs-markdown-mode-git][]
77 ;; * MacPorts: [markdown-mode.el][macports-package] ([pending][macports-ticket])
78 ;; * FreeBSD: [textproc/markdown-mode.el][freebsd-port]
80 ;; [emacs-goodies-el]: http://packages.debian.org/emacs-goodies-el
81 ;; [emacs-goodies]: https://admin.fedoraproject.org/pkgdb/acls/name/emacs-goodies
82 ;; [textproc/markdown-mode]: http://pkgsrc.se/textproc/markdown-mode
83 ;; [emacs-markdown-mode-git]: http://aur.archlinux.org/packages.php?ID=30389
84 ;; [macports-package]: https://trac.macports.org/browser/trunk/dports/editors/markdown-mode.el/Portfile
85 ;; [macports-ticket]: http://trac.macports.org/ticket/35716
86 ;; [freebsd-port]: http://svnweb.freebsd.org/ports/head/textproc/markdown-mode.el
88 ;; The latest development version can be downloaded directly
89 ;; ([markdown-mode.el][devel.el]) or it can be obtained from the
90 ;; (browsable and clonable) Git repository at
91 ;; <http://jblevins.org/git/markdown-mode.git>. The entire repository,
92 ;; including the full project history, can be cloned via the Git protocol
95 ;; git clone git://jblevins.org/git/markdown-mode.git
97 ;; [devel.el]: http://jblevins.org/git/markdown-mode.git/plain/markdown-mode.el
101 ;; Make sure to place `markdown-mode.el` somewhere in the load-path and add
102 ;; the following lines to your `.emacs` file to associate markdown-mode
103 ;; with `.text`, `.markdown`, and `.md` files:
105 ;; (autoload 'markdown-mode "markdown-mode"
106 ;; "Major mode for editing Markdown files" t)
107 ;; (add-to-list 'auto-mode-alist '("\\.text\\'" . markdown-mode))
108 ;; (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode))
109 ;; (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode))
111 ;; There is no official Markdown file extension, nor is there even a
112 ;; _de facto_ standard, so you can easily add, change, or remove any
113 ;; of the file extensions above as needed.
117 ;; Keybindings are grouped by prefixes based on their function. For
118 ;; example, the commands for inserting links are grouped under `C-c
119 ;; C-a`, where the `C-a` is a mnemonic for the HTML `<a>` tag. In
120 ;; other cases, the connection to HTML is not direct. For example,
121 ;; commands dealing with headings begin with `C-c C-t` (mnemonic:
122 ;; titling). The primary commands in each group will are described
123 ;; below. You can obtain a list of all keybindings by pressing `C-c
124 ;; C-h`. Movement and shifting commands tend to be associated with
125 ;; paired delimiters such as `M-{` and `M-}` or `C-c <` and `C-c >`.
126 ;; Outline navigation keybindings the same as in `org-mode'. Finally,
127 ;; commands for running Markdown or doing maintenance on an open file
128 ;; are grouped under the `C-c C-c` prefix. The most commonly used
129 ;; commands are described below. You can obtain a list of all
130 ;; keybindings by pressing `C-c C-h`.
132 ;; * Hyperlinks: `C-c C-a`
134 ;; In this group, `C-c C-a l` inserts an inline link of the form
135 ;; `[text](url)`. The link text is determined as follows. First,
136 ;; if there is an active region (i.e., when transient mark mode is
137 ;; on and the mark is active), use it as the link text. Second,
138 ;; if the point is at a word, use that word as the link text. In
139 ;; these two cases, the original text will be replaced with the
140 ;; link and point will be left at the position for inserting a
141 ;; URL. Otherwise, insert empty link markup and place the point
142 ;; for inserting the link text.
144 ;; `C-c C-a L` inserts a reference link of the form `[text][label]`
145 ;; and, optionally, a corresponding reference label definition.
146 ;; The link text is determined in the same way as with an inline
147 ;; link (using the region, when active, or the word at the point),
148 ;; but instead of inserting empty markup as a last resort, the
149 ;; link text will be read from the minibuffer. The reference
150 ;; label will be read from the minibuffer in both cases, with
151 ;; completion from the set of currently defined references. To
152 ;; create an implicit reference link, press `RET` to accept the
153 ;; default, an empty label. If the entered referenced label is
154 ;; not defined, additionally prompt for the URL and (optional)
155 ;; title. If a URL is provided, a reference definition will be
156 ;; inserted in accordance with `markdown-reference-location'.
157 ;; If a title is given, it will be added to the end of the
158 ;; reference definition and will be used to populate the title
159 ;; attribute when converted to XHTML.
161 ;; `C-c C-a u` inserts a bare url, delimited by angle brackets. When
162 ;; there is an active region, the text in the region is used as the
163 ;; URL. If the point is at a URL, that url is used. Otherwise,
164 ;; insert angle brackets and position the point in between them
165 ;; for inserting the URL.
167 ;; `C-c C-a f` inserts a footnote marker at the point, inserts a
168 ;; footnote definition below, and positions the point for
169 ;; inserting the footnote text. Note that footnotes are an
170 ;; extension to Markdown and are not supported by all processors.
172 ;; `C-c C-a w` behaves much like the inline link insertion command
173 ;; and inserts a wiki link of the form `[[WikiLink]]`. If there
174 ;; is an active region, use the region as the link text. If the
175 ;; point is at a word, use the word as the link text. If there is
176 ;; no active region and the point is not at word, simply insert
177 ;; link markup. Note that wiki links are an extension to Markdown
178 ;; and are not supported by all processors.
180 ;; * Images: `C-c C-i`
182 ;; `C-c C-i i` inserts markup for an inline image, using the
183 ;; active region or the word at point, if any, as the alt text.
184 ;; `C-c C-i I` behaves similarly and inserts a reference-style
187 ;; * Styles: `C-c C-s`
189 ;; `C-c C-s e` inserts markup to make a region or word italic (`e`
190 ;; for `<em>` or emphasis). If there is an active region, make
191 ;; the region italic. If the point is at a non-italic word, make
192 ;; the word italic. If the point is at an italic word or phrase,
193 ;; remove the italic markup. Otherwise, simply insert italic
194 ;; delimiters and place the cursor in between them. Similarly,
195 ;; use `C-c C-s s` for bold (`<strong>`) and `C-c C-s c` for
196 ;; inline code (`<code>`).
198 ;; `C-c C-s b` inserts a blockquote using the active region, if any,
199 ;; or starts a new blockquote. `C-c C-s C-b` is a variation which
200 ;; always operates on the region, regardless of whether it is
201 ;; active or not. The appropriate amount of indentation, if any,
202 ;; is calculated automatically given the surrounding context, but
203 ;; may be adjusted later using the region indentation commands.
205 ;; `C-c C-s p` behaves similarly for inserting preformatted code
206 ;; blocks, with `C-c C-s C-p` being the region-only counterpart.
208 ;; * Headings: `C-c C-t`
210 ;; All heading insertion commands use the text in the active
211 ;; region, if any, as the heading text. Otherwise, if the current
212 ;; line is not blank, they use the text on the current line.
213 ;; Finally, the setext commands will prompt for heading text if
214 ;; there is no active region and the current line is blank.
216 ;; `C-c C-t h` inserts a heading with automatically chosen type and
217 ;; level (both determined by the previous heading). `C-c C-t H`
218 ;; behaves similarly, but uses setext (underlined) headings when
219 ;; possible, still calculating the level automatically.
220 ;; In cases where the automatically-determined level is not what
221 ;; you intended, the level can be quickly promoted or demoted
222 ;; (as described below).
224 ;; To insert a heading of a specific level and type, use `C-c C-t 1`
225 ;; through `C-c C-t 6` for atx (hash mark) headings and `C-c C-t !` or
226 ;; `C-c C-t @` for setext headings of level one or two, respectively.
227 ;; Note that `!` is `S-1` and `@` is `S-2`.
229 ;; If the point is at a heading, these commands will replace the
230 ;; existing markup in order to update the level and/or type of the
231 ;; heading. To remove the markup of the heading at the point,
232 ;; press `C-c C-k` to kill the heading and press `C-y` to yank the
233 ;; heading text back into the buffer.
235 ;; * Horizontal Rules: `C-c -`
237 ;; `C-c -` inserts a horizontal rule. By default, insert the
238 ;; first string in the list `markdown-hr-strings' (the most
239 ;; prominent rule). With a `C-u` prefix, insert the last string.
240 ;; With a numeric prefix `N`, insert the string in position `N`
241 ;; (counting from 1).
243 ;; * Markdown and Maintenance Commands: `C-c C-c`
245 ;; *Compile:* `C-c C-c m` will run Markdown on the current buffer
246 ;; and show the output in another buffer. *Preview*: `C-c C-c p`
247 ;; runs Markdown on the current buffer and previews, stores the
248 ;; output in a temporary file, and displays the file in a browser.
249 ;; *Export:* `C-c C-c e` will run Markdown on the current buffer
250 ;; and save the result in the file `basename.html`, where
251 ;; `basename` is the name of the Markdown file with the extension
252 ;; removed. *Export and View:* press `C-c C-c v` to export the
253 ;; file and view it in a browser. **For both export commands, the
254 ;; output file will be overwritten without notice.**
255 ;; *Open:* `C-c C-c o` will open the Markdown source file directly
256 ;; using `markdown-open-command'.
260 ;; - `C-c C-c m`: `markdown-command' > `*markdown-output*` buffer.
261 ;; - `C-c C-c p`: `markdown-command' > temporary file > browser.
262 ;; - `C-c C-c e`: `markdown-command' > `basename.html`.
263 ;; - `C-c C-c v`: `markdown-command' > `basename.html` > browser.
264 ;; - `C-c C-c w`: `markdown-command' > kill ring.
265 ;; - `C-c C-c o`: `markdown-open-command'.
267 ;; `C-c C-c c` will check for undefined references. If there are
268 ;; any, a small buffer will open with a list of undefined
269 ;; references and the line numbers on which they appear. In Emacs
270 ;; 22 and greater, selecting a reference from this list and
271 ;; pressing `RET` will insert an empty reference definition at the
272 ;; end of the buffer. Similarly, selecting the line number will
273 ;; jump to the corresponding line.
275 ;; `C-c C-c n` renumbers any ordered lists in the buffer that are
278 ;; `C-c C-c ]` completes all headings and normalizes all horizontal
279 ;; rules in the buffer.
281 ;; * Following Links: `C-c C-o`
283 ;; Press `C-c C-o` when the point is on an inline or reference
284 ;; link to open the URL in a browser. When the point is at a
285 ;; wiki link, open it in another buffer (in the current window,
286 ;; or in the other window with the `C-u` prefix). Use `M-p` and
287 ;; `M-n` to quickly jump to the previous or next link of any type.
289 ;; * Jumping: `C-c C-j`
291 ;; Use `C-c C-j` to jump from the object at point to its counterpart
292 ;; elsewhere in the text, when possible. Jumps between reference
293 ;; links and definitions; between footnote markers and footnote
294 ;; text. If more than one link uses the same reference name, a
295 ;; new buffer will be created containing clickable buttons for jumping
296 ;; to each link. You may press `TAB` or `S-TAB` to jump between
297 ;; buttons in this window.
299 ;; * Promotion and Demotion: `C-c C--` and `C-c C-=`
301 ;; Headings, horizontal rules, and list items can be promoted and
302 ;; demoted, as well as bold and italic text. For headings,
303 ;; "promotion" means *decreasing* the level (i.e., moving from
304 ;; `<h2>` to `<h1>`) while "demotion" means *increasing* the
305 ;; level. For horizontal rules, promotion and demotion means
306 ;; moving backward or forward through the list of rule strings in
307 ;; `markdown-hr-strings'. For bold and italic text, promotion and
308 ;; demotion means changing the markup from underscores to asterisks.
309 ;; Press `C-c C--` or `M-LEFT` to promote the element at the point
312 ;; To remember these commands, note that `-` is for decreasing the
313 ;; level (promoting), and `=` (on the same key as `+`) is for
314 ;; increasing the level (demoting). Similarly, the left and right
315 ;; arrow keys indicate the direction that the atx heading markup
316 ;; is moving in when promoting or demoting.
318 ;; * Completion: `C-c C-]`
320 ;; Complete markup is in normalized form, which means, for
321 ;; example, that the underline portion of a setext header is the
322 ;; same length as the heading text, or that the number of leading
323 ;; and trailing hash marks of an atx header are equal and that
324 ;; there is no extra whitespace in the header text. `C-c C-]`
325 ;; completes the markup at the point, if it is determined to be
328 ;; * Editing Lists: `M-RET`, `M-UP`, `M-DOWN`, `M-LEFT`, and `M-RIGHT`
330 ;; New list items can be inserted with `M-RET`. This command
331 ;; determines the appropriate marker (one of the possible
332 ;; unordered list markers or the next number in sequence for an
333 ;; ordered list) and indentation level by examining nearby list
334 ;; items. If there is no list before or after the point, start a
335 ;; new list. Prefix this command by `C-u` to decrease the
336 ;; indentation by one level. Prefix this command by `C-u C-u` to
337 ;; increase the indentation by one level.
339 ;; Existing list items can be moved up or down with `M-UP` or
340 ;; `M-DOWN` and indented or exdented with `M-RIGHT` or `M-LEFT`.
342 ;; * Shifting the Region: `C-c <` and `C-c >`
344 ;; Text in the region can be indented or exdented as a group using
345 ;; `C-c >` to indent to the next indentation point (calculated in
346 ;; the current context), and `C-c <` to exdent to the previous
347 ;; indentation point. These keybindings are the same as those for
348 ;; similar commands in `python-mode'.
350 ;; * Killing Elements: `C-c C-k`
352 ;; Press `C-c C-k` to kill the thing at point and add important
353 ;; text, without markup, to the kill ring. Possible things to
354 ;; kill include (roughly in order of precedece): inline code,
355 ;; headings, horizonal rules, links (add link text to kill ring),
356 ;; images (add alt text to kill ring), angle URIs, email
357 ;; addresses, bold, italics, reference definitions (add URI to
358 ;; kill ring), footnote markers and text (kill both marker and
359 ;; text, add text to kill ring), and list items.
361 ;; * Outline Navigation: `C-c C-n`, `C-c C-p`, `C-c C-f`, `C-c C-b`, and `C-c C-u`
363 ;; Navigation between headings is possible using `outline-mode'.
364 ;; Use `C-c C-n` and `C-c C-p` to move between the next and previous
365 ;; visible headings. Similarly, `C-c C-f` and `C-c C-b` move to the
366 ;; next and previous visible headings at the same level as the one
367 ;; at the point. Finally, `C-c C-u` will move up to a lower-level
368 ;; (higher precedence) visible heading.
370 ;; * Movement by Paragraph or Block: `M-{` and `M-}`
372 ;; The definition of a "paragraph" is slightly different in
373 ;; markdown-mode than, say, text-mode, because markdown-mode
374 ;; supports filling for list items and respects hard line breaks,
375 ;; both of which break paragraphs. So, markdown-mode overrides
376 ;; the usual paragraph navigation commands `M-{` and `M-}` so that
377 ;; with a `C-u` prefix, these commands jump to the beginning or
378 ;; end of an entire block of text, respectively, where "blocks"
379 ;; are separated by one or more lines.
381 ;; * Movement by Defun: `C-M-a`, `C-M-e`, and `C-M-h`
383 ;; The usual Emacs commands can be used to move by defuns
384 ;; (top-level major definitions). In markdown-mode, a defun is a
385 ;; section. As usual, `C-M-a` will move the point to the
386 ;; beginning of the current or preceding defun, `C-M-e` will move
387 ;; to the end of the current or following defun, and `C-M-h` will
388 ;; put the region around the entire defun.
390 ;; As noted, many of the commands above behave differently depending
391 ;; on whether Transient Mark mode is enabled or not. When it makes
392 ;; sense, if Transient Mark mode is on and the region is active, the
393 ;; command applies to the text in the region (e.g., `C-c C-s s` makes the
394 ;; region bold). For users who prefer to work outside of Transient
395 ;; Mark mode, since Emacs 22 it can be enabled temporarily by pressing
396 ;; `C-SPC C-SPC`. When this is not the case, many commands then
397 ;; proceed to look work with the word or line at the point.
399 ;; When applicable, commands that specifically act on the region even
400 ;; outside of Transient Mark mode have the same keybinding as their
401 ;; standard counterpart, but the letter is uppercase. For example,
402 ;; `markdown-insert-blockquote' is bound to `C-c C-s b` and only acts on
403 ;; the region in Transient Mark mode while `markdown-blockquote-region'
404 ;; is bound to `C-c C-s B` and always applies to the region (when nonempty).
406 ;; Note that these region-specific functions are useful in many
407 ;; cases where it may not be obvious. For example, yanking text from
408 ;; the kill ring sets the mark at the beginning of the yanked text
409 ;; and moves the point to the end. Therefore, the (inactive) region
410 ;; contains the yanked text. So, `C-y` followed by `C-c C-s C-b` will
411 ;; yank text and turn it into a blockquote.
413 ;; markdown-mode attempts to be flexible in how it handles
414 ;; indentation. When you press `TAB` repeatedly, the point will cycle
415 ;; through several possible indentation levels corresponding to things
416 ;; you might have in mind when you press `RET` at the end of a line or
417 ;; `TAB`. For example, you may want to start a new list item,
418 ;; continue a list item with hanging indentation, indent for a nested
419 ;; pre block, and so on. Exdention is handled similarly when backspace
420 ;; is pressed at the beginning of the non-whitespace portion of a line.
422 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
423 ;; visibility cycling for atx- or hash-style headings. There are two
424 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
425 ;; the table of contents view (headings only), outline view (top-level
426 ;; headings only), and the full document view. Pressing `TAB` while the
427 ;; point is at a heading will cycle through levels of visibility for the
428 ;; subtree: completely folded, visible children, and fully visible.
429 ;; Note that mixing hash and underline style headings will give undesired
434 ;; Although no configuration is *necessary* there are a few things
435 ;; that can be customized. The `M-x customize-mode` command
436 ;; provides an interface to all of the possible customizations:
438 ;; * `markdown-command' - the command used to run Markdown (default:
439 ;; `markdown`). This variable may be customized to pass
440 ;; command-line options to your Markdown processor of choice.
442 ;; * `markdown-command-needs-filename' - set to `t' if
443 ;; `markdown-command' does not accept standard input (default:
444 ;; `nil'). When `nil', `markdown-mode' will pass the Markdown
445 ;; content to `markdown-command' using standard input (`stdin`).
446 ;; When set to `t', `markdown-mode' will pass the name of the file
447 ;; as the final command-line argument to `markdown-command'. Note
448 ;; that in the latter case, you will only be able to run
449 ;; `markdown-command' from buffers which are visiting a file.
451 ;; * `markdown-open-command' - the command used for calling a standalone
452 ;; Markdown previewer which is capable of opening Markdown source files
453 ;; directly (default: `nil'). This command will be called
454 ;; with a single argument, the filename of the current buffer.
455 ;; A representative program is the Mac app [Marked][], a
456 ;; live-updating MultiMarkdown previewer which has a command line
457 ;; utility at `/usr/local/bin/mark`.
459 ;; * `markdown-hr-strings' - list of strings to use when inserting
460 ;; horizontal rules. Different strings will not be distinguished
461 ;; when converted to HTML--they will all be converted to
462 ;; `<hr/>`--but they may add visual distinction and style to plain
463 ;; text documents. To maintain some notion of promotion and
464 ;; demotion, keep these sorted from largest to smallest.
466 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
467 ;; underscores for bold instead of two asterisks (default: `nil').
469 ;; * `markdown-italic-underscore' - set to a non-nil value to use
470 ;; underscores for italic instead of asterisks (default: `nil').
472 ;; * `markdown-indent-function' - the function to use for automatic
473 ;; indentation (default: `markdown-indent-line').
475 ;; * `markdown-indent-on-enter' - set to a non-nil value to
476 ;; automatically indent new lines when the enter key is pressed
479 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
480 ;; treat aliased wiki links like `[[link text|PageName]]`
481 ;; (default: `t'). When set to nil, they will be treated as
482 ;; `[[PageName|link text]]'.
484 ;; * `markdown-uri-types' - a list of protocol schemes (e.g., "http")
485 ;; for URIs that `markdown-mode' should highlight.
487 ;; * `markdown-enable-math' - syntax highlighting for LaTeX
488 ;; fragments (default: `nil'). Set this to `t' to turn on math
489 ;; support by default. Math support can be toggled later using
490 ;; the function `markdown-enable-math'."
492 ;; * `markdown-css-path' - CSS file to link to in XHTML output
495 ;; * `markdown-content-type' - when set to a nonempty string, an
496 ;; `http-equiv` attribute will be included in the XHTML `<head>`
497 ;; block (default: `""`). If needed, the suggested values are
498 ;; `application/xhtml+xml` or `text/html`.
500 ;; * `markdown-coding-system' - used for specifying the character
501 ;; set identifier in the `http-equiv` attribute (see
502 ;; `markdown-content-type') (default: `nil'). When set to `nil',
503 ;; `buffer-file-coding-system' will be used (and falling back to
504 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
505 ;; and `iso-latin-1'.
507 ;; * `markdown-xhtml-header-content' - additional content to include
508 ;; in the XHTML `<head>` block (default: `""`).
510 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
511 ;; `markdown-mode' uses to determine whether the output of
512 ;; `markdown-command' is a standalone XHTML document or an XHTML
513 ;; fragment (default: `"^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"`). If
514 ;; this regular expression not matched in the first five lines of
515 ;; output, `markdown-mode' assumes the output is a fragment and
516 ;; adds a header and footer.
518 ;; * `markdown-link-space-sub-char' - a character to replace spaces
519 ;; when mapping wiki links to filenames (default: `"_"`).
520 ;; For example, use an underscore for compatibility with the
521 ;; Python Markdown WikiLinks extension. In `gfm-mode', this is
522 ;; set to `"-"` to conform with GitHub wiki links.
524 ;; * `markdown-reference-location' - where to insert reference
525 ;; definitions (default: `header`). The possible locations are
526 ;; the end of the document (`end`), after the current block
527 ;; (`immediately`), before the next header (`header`).
529 ;; * `markdown-footnote-location' - where to insert footnote text
530 ;; (default: `end`). The set of location options is the same as
531 ;; for `markdown-reference-location'.
533 ;; Additionally, the faces used for syntax highlighting can be modified to
534 ;; your liking by issuing `M-x customize-group RET markdown-faces`
535 ;; or by using the "Markdown Faces" link at the bottom of the mode
536 ;; customization screen.
538 ;; [Marked]: https://itunes.apple.com/us/app/marked/id448925439?ls=1&mt=12&partnerId=30&siteID=GpHp3Acs1Yo
542 ;; Besides supporting the basic Markdown syntax, markdown-mode also
543 ;; includes syntax highlighting for `[[Wiki Links]]` by default. Wiki
544 ;; links may be followed by pressing `C-c C-o` when the point
545 ;; is at a wiki link. Use `M-p` and `M-n` to quickly jump to the
546 ;; previous and next links (including links of other types).
547 ;; Aliased or piped wiki links of the form `[[link text|PageName]]`
548 ;; are also supported. Since some wikis reverse these components, set
549 ;; `markdown-wiki-link-alias-first' to nil to treat them as
550 ;; `[[PageName|link text]]`.
552 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
553 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
554 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
555 ;; You can do this either by using `M-x customize-group markdown`
556 ;; or by placing the following in your `.emacs` file:
558 ;; (defun markdown-custom ()
559 ;; "markdown-mode-hook"
560 ;; (setq markdown-command "markdown | smartypants"))
561 ;; (add-hook 'markdown-mode-hook '(lambda() (markdown-custom)))
563 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
565 ;; Syntax highlighting for mathematical expressions written
566 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
567 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
568 ;; either via customize or by placing `(setq markdown-enable-math t)`
569 ;; in `.emacs`, and then restarting Emacs or calling
570 ;; `markdown-reload-extensions'.
572 ;;; GitHub Flavored Markdown:
574 ;; A [GitHub Flavored Markdown][GFM] (GFM) mode, `gfm-mode', is also
575 ;; available. The GitHub implementation of differs slightly from
576 ;; standard Markdown. The most important differences are that
577 ;; newlines are significant, triggering hard line breaks, and that
578 ;; underscores inside of words (e.g., variable names) need not be
579 ;; escaped. As such, `gfm-mode' turns off `auto-fill-mode' and turns
580 ;; on `visual-line-mode' (or `longlines-mode' if `visual-line-mode' is
581 ;; not available). Underscores inside of words (such as
582 ;; test_variable) will not trigger emphasis.
584 ;; Wiki links in this mode will be treated as on GitHub, with hyphens
585 ;; replacing spaces in filenames and where the first letter of the
586 ;; filename capitalized. For example, `[[wiki link]]' will map to a
587 ;; file named `Wiki-link` with the same extension as the current file.
589 ;; GFM code blocks, with optional programming language keywords, will
590 ;; be highlighted. They can be inserted with `C-c C-s P`. If there
591 ;; is an active region, the text in the region will be placed inside
592 ;; the code block. You will be prompted for the name of the language,
593 ;; but may press enter to continue without naming a language.
595 ;; For a more complete GitHub-flavored markdown experience, consider
596 ;; adding README.md to your `auto-mode-alist':
598 ;; (add-to-list 'auto-mode-alist '("README\\.md\\'" . gfm-mode))
600 ;; For GFM preview can be powered by setting `markdown-command' to
601 ;; use [Docter][]. This may also be configured to work with [Marked][]
602 ;; for `markdown-open-command'.
604 ;; [GFM]: http://github.github.com/github-flavored-markdown/
605 ;; [Docter]: https://github.com/alampros/Docter
609 ;; markdown-mode has benefited greatly from the efforts of the
612 ;; * Cyril Brulebois <cyril.brulebois@enst-bretagne.fr> for Debian packaging.
613 ;; * Conal Elliott <conal@conal.net> for a font-lock regexp patch.
614 ;; * Edward O'Connor <hober0@gmail.com> for a font-lock regexp fix and
615 ;; GitHub Flavored Markdown mode (`gfm-mode').
616 ;; * Greg Bognar <greg_bognar@hms.harvard.edu> for menus and running
617 ;; `markdown' with an active region.
618 ;; * Daniel Burrows <dburrows@debian.org> for filing Debian bug #456592.
619 ;; * Peter S. Galbraith <psg@debian.org> for maintaining `emacs-goodies-el`.
620 ;; * Dmitry Dzhus <mail@sphinx.net.ru> for undefined reference checking.
621 ;; * Carsten Dominik <carsten@orgmode.org> for `org-mode', from which the
622 ;; visibility cycling functionality was derived, and for a bug fix
623 ;; related to `orgtbl-mode'.
624 ;; * Bryan Kyle <bryan.kyle@gmail.com> for indentation code.
625 ;; * Ben Voui <intrigeri@boum.org> for font-lock face customizations.
626 ;; * Ankit Solanki <ankit.solanki@gmail.com> for `longlines.el`
627 ;; compatibility and custom CSS.
628 ;; * Hilko Bengen <bengen@debian.org> for proper XHTML output.
629 ;; * Jose A. Ortega Ruiz <jao@gnu.org> for Emacs 23 fixes.
630 ;; * Nelson Minar <nelson@santafe.edu> for `html-helper-mode', from which
631 ;; comment matching functions were derived.
632 ;; * Alec Resnick <alec@sproutward.org> for bug reports.
633 ;; * Joost Kremers <joostkremers@fastmail.fm> for footnote-handling
634 ;; functions, bug reports regarding indentation, and
635 ;; fixes for byte-compilation warnings.
636 ;; * Peter Williams <pezra@barelyenough.org> for `fill-paragraph'
638 ;; * George Ogata <george.ogata@gmail.com> for fixing several
639 ;; byte-compilation warnings.
640 ;; * Eric Merritt <ericbmerritt@gmail.com> for wiki link features.
641 ;; * Philippe Ivaldi <pivaldi@sfr.fr> for XHTML preview
642 ;; customizations and XHTML export.
643 ;; * Jeremiah Dodds <jeremiah.dodds@gmail.com> for supporting
644 ;; Markdown processors which do not accept input from stdin.
645 ;; * Werner Dittmann <werner.dittmann@t-online.de> for bug reports
646 ;; regarding the `cl` dependency and `auto-fill-mode' and indentation.
647 ;; * Scott Pfister <scott.pfister@gmail.com> for generalizing the space
648 ;; substitution character for mapping wiki links to filenames.
649 ;; * Marcin Kasperski <marcin.kasperski@mekk.waw.pl> for a patch to
650 ;; escape shell commands.
651 ;; * Christopher J. Madsen <cjm@cjmweb.net> for patches to fix a match
652 ;; data bug and to prefer `visual-line-mode' in `gfm-mode'.
653 ;; * Shigeru Fukaya <shigeru.fukaya@gmail.com> for better adherence to
654 ;; Emacs Lisp coding conventions.
655 ;; * Donald Ephraim Curtis <dcurtis@milkbox.net> for fixing the `fill-paragraph'
656 ;; regexp, refactoring the compilation and preview functions,
657 ;; heading font-lock generalizations, list renumbering,
658 ;; and kill ring save.
659 ;; * Kevin Porter <kportertx@gmail.com> for wiki link handling in `gfm-mode'.
660 ;; * Max Penet <max.penet@gmail.com> and Peter Eisentraut <peter_e@gmx.net>
661 ;; for an autoload token for `gfm-mode'.
662 ;; * Ian Yang <me@iany.me> for improving the reference definition regex.
663 ;; * Akinori Musha <knu@idaemons.org> for an imenu index function.
664 ;; * Michael Sperber <sperber@deinprogramm.de> for XEmacs fixes.
665 ;; * Francois Gannaz <francois.gannaz@free.fr> for suggesting charset
666 ;; declaration in XHTML output.
667 ;; * Zhenlei Jia <zhenlei.jia@gmail.com> for smart exdention function.
668 ;; * Matus Goljer <dota.keys@gmail.com> for improved wiki link following
669 ;; and GFM code block insertion.
670 ;; * Peter Jones <pjones@pmade.com> for link following functions.
671 ;; * Bryan Fink <bryan.fink@gmail.com> for a bug report regarding
672 ;; externally modified files.
673 ;; * Vegard Vesterheim <vegard.vesterheim@uninett.no> for a bug fix
674 ;; related to `orgtbl-mode'.
675 ;; * Makoto Motohashi <mkt.motohashi@gmail.com> for before- and after-
676 ;; export hooks and unit test improvements.
677 ;; * Michael Dwyer <mdwyer@ehtech.in> for `gfm-mode' underscore regexp.
678 ;; * Chris Lott <chris@chrislott.org> for suggesting reference label
683 ;; Although markdown-mode is developed and tested primarily using
684 ;; GNU Emacs 24, compatibility with earlier Emacsen is also a
687 ;; If you find any bugs in markdown-mode, please construct a test case
688 ;; or a patch and email me at <jrblevin@sdf.org>.
692 ;; markdown-mode was written and is maintained by Jason Blevins. The
693 ;; first version was released on May 24, 2007.
695 ;; * 2007-05-24: Version 1.1
696 ;; * 2007-05-25: Version 1.2
697 ;; * 2007-06-05: [Version 1.3][]
698 ;; * 2007-06-29: Version 1.4
699 ;; * 2007-10-11: [Version 1.5][]
700 ;; * 2008-06-04: [Version 1.6][]
701 ;; * 2009-10-01: [Version 1.7][]
702 ;; * 2011-08-12: [Version 1.8][]
703 ;; * 2011-08-15: [Version 1.8.1][]
704 ;; * 2013-01-25: [Version 1.9][]
706 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
707 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
708 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
709 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
710 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
711 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
712 ;; [Version 1.9]: http://jblevins.org/projects/markdown-mode/rev-1-9
719 (eval-when-compile (require 'cl
))
722 ;;; Constants =================================================================
724 (defconst markdown-mode-version
"2.0-pre"
725 "Markdown mode version number.")
727 (defconst markdown-output-buffer-name
"*markdown-output*"
728 "Name of temporary buffer for markdown command output.")
731 ;;; Global Variables ==========================================================
733 (defvar markdown-reference-label-history nil
734 "History of used reference labels.")
737 ;;; Customizable Variables ====================================================
739 (defvar markdown-mode-hook nil
740 "Hook run when entering Markdown mode.")
742 (defvar markdown-before-export-hook nil
743 "Hook run before running Markdown to export XHTML output.
744 The hook may modify the buffer, which will be restored to it's
745 original state after exporting is complete.")
747 (defvar markdown-after-export-hook nil
748 "Hook run after XHTML output has been saved.
749 Any changes to the output buffer made by this hook will be saved.")
751 (defgroup markdown nil
752 "Major mode for editing text files in Markdown format."
755 :link
'(url-link "http://jblevins.org/projects/markdown-mode/"))
757 (defcustom markdown-command
"markdown"
758 "Command to run markdown."
762 (defcustom markdown-command-needs-filename nil
763 "Set to non-nil if `markdown-command' does not accept input from stdin.
764 Instead, it will be passed a filename as the final command line
765 option. As a result, you will only be able to run Markdown from
766 buffers which are visiting a file."
770 (defcustom markdown-open-command nil
771 "Command used for opening Markdown files directly.
772 For example, a standalone Markdown previewer. This command will
773 be called with a single argument: the filename of the current
778 (defcustom markdown-hr-strings
779 '("-------------------------------------------------------------------------------"
780 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
781 "---------------------------------------"
782 "* * * * * * * * * * * * * * * * * * * *"
785 "Strings to use when inserting horizontal rules.
786 The first string in the list will be the default when inserting a
787 horizontal rule. Strings should be listed in decreasing order of
788 prominence (as in headings from level one to six) for use with
789 promotion and demotion functions."
793 (defcustom markdown-bold-underscore nil
794 "Use two underscores for bold instead of two asterisks."
798 (defcustom markdown-italic-underscore nil
799 "Use underscores for italic instead of asterisks."
803 (defcustom markdown-indent-function
'markdown-indent-line
804 "Function to use to indent."
808 (defcustom markdown-indent-on-enter t
809 "Automatically indent new lines when enter key is pressed.
810 When this variable is set to t, pressing RET will call
811 `newline-and-indent'. When set to nil, define RET to call
812 `newline' as usual. In the latter case, you can still use
813 auto-indentation by pressing \\[newline-and-indent]."
817 (defcustom markdown-wiki-link-alias-first t
818 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
819 Otherwise, they will be treated as [[PageName|alias text]]."
823 (defcustom markdown-uri-types
824 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
825 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
826 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
827 "Link types for syntax highlighting of URIs."
831 (defcustom markdown-enable-math nil
832 "Syntax highlighting for inline LaTeX and itex expressions.
833 Set this to a non-nil value to turn on math support by default.
834 Math support can be toggled later using `markdown-enable-math'
835 or \\[markdown-enable-math]."
840 (defcustom markdown-css-path
""
841 "URL of CSS file to link to in the output XHTML."
845 (defcustom markdown-content-type
""
846 "Content type string for the http-equiv header in XHTML output.
847 When set to a non-empty string, insert the http-equiv attribute.
848 Otherwise, this attribute is omitted."
852 (defcustom markdown-coding-system nil
853 "Character set string for the http-equiv header in XHTML output.
854 Defaults to `buffer-file-coding-system' (and falling back to
855 `iso-8859-1' when not available). Common settings are `utf-8'
856 and `iso-latin-1'. Use `list-coding-systems' for more choices."
858 :type
'coding-system
)
860 (defcustom markdown-xhtml-header-content
""
861 "Additional content to include in the XHTML <head> block."
865 (defcustom markdown-xhtml-standalone-regexp
866 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
867 "Regexp indicating whether `markdown-command' output is standalone XHTML."
871 (defcustom markdown-link-space-sub-char
"_"
872 "Character to use instead of spaces when mapping wiki links to filenames."
876 (defcustom markdown-reference-location
'header
877 "Position where new reference definitions are inserted in the document."
879 :type
'(choice (const :tag
"At the end of the document" end
)
880 (const :tag
"Immediately after the current block" immediately
)
881 (const :tag
"Before next header" header
)))
883 (defcustom markdown-footnote-location
'end
884 "Position where new footnotes are inserted in the document."
886 :type
'(choice (const :tag
"At the end of the document" end
)
887 (const :tag
"Immediately after the current block" immediately
)
888 (const :tag
"Before next header" header
)))
891 ;;; Font Lock =================================================================
895 (defvar markdown-italic-face
'markdown-italic-face
896 "Face name to use for italic text.")
898 (defvar markdown-bold-face
'markdown-bold-face
899 "Face name to use for bold text.")
901 (defvar markdown-header-delimiter-face
'markdown-header-delimiter-face
902 "Face name to use as a base for header delimiters.")
904 (defvar markdown-header-rule-face
'markdown-header-rule-face
905 "Face name to use as a base for header rules.")
907 (defvar markdown-header-face
'markdown-header-face
908 "Face name to use as a base for headers.")
910 (defvar markdown-header-face-1
'markdown-header-face-1
911 "Face name to use for level-1 headers.")
913 (defvar markdown-header-face-2
'markdown-header-face-2
914 "Face name to use for level-2 headers.")
916 (defvar markdown-header-face-3
'markdown-header-face-3
917 "Face name to use for level-3 headers.")
919 (defvar markdown-header-face-4
'markdown-header-face-4
920 "Face name to use for level-4 headers.")
922 (defvar markdown-header-face-5
'markdown-header-face-5
923 "Face name to use for level-5 headers.")
925 (defvar markdown-header-face-6
'markdown-header-face-6
926 "Face name to use for level-6 headers.")
928 (defvar markdown-inline-code-face
'markdown-inline-code-face
929 "Face name to use for inline code.")
931 (defvar markdown-list-face
'markdown-list-face
932 "Face name to use for list markers.")
934 (defvar markdown-blockquote-face
'markdown-blockquote-face
935 "Face name to use for blockquote.")
937 (defvar markdown-pre-face
'markdown-pre-face
938 "Face name to use for preformatted text.")
940 (defvar markdown-language-keyword-face
'markdown-language-keyword-face
941 "Face name to use for programming language identifiers.")
943 (defvar markdown-link-face
'markdown-link-face
944 "Face name to use for links.")
946 (defvar markdown-missing-link-face
'markdown-missing-link-face
947 "Face name to use for links where the linked file does not exist.")
949 (defvar markdown-reference-face
'markdown-reference-face
950 "Face name to use for reference.")
952 (defvar markdown-footnote-face
'markdown-footnote-face
953 "Face name to use for footnote identifiers.")
955 (defvar markdown-url-face
'markdown-url-face
956 "Face name to use for URLs.")
958 (defvar markdown-link-title-face
'markdown-link-title-face
959 "Face name to use for reference link titles.")
961 (defvar markdown-line-break-face
'markdown-line-break-face
962 "Face name to use for hard line breaks.")
964 (defvar markdown-comment-face
'markdown-comment-face
965 "Face name to use for HTML comments.")
967 (defvar markdown-math-face
'markdown-math-face
968 "Face name to use for LaTeX expressions.")
970 (defvar markdown-metadata-key-face
'markdown-metadata-key-face
971 "Face name to use for metadata keys.")
973 (defvar markdown-metadata-value-face
'markdown-metadata-value-face
974 "Face name to use for metadata values.")
976 (defgroup markdown-faces nil
977 "Faces used in Markdown Mode"
981 (defface markdown-italic-face
982 '((t (:inherit font-lock-variable-name-face
:slant italic
)))
983 "Face for italic text."
984 :group
'markdown-faces
)
986 (defface markdown-bold-face
987 '((t (:inherit font-lock-variable-name-face
:weight bold
)))
988 "Face for bold text."
989 :group
'markdown-faces
)
991 (defface markdown-header-rule-face
992 '((t (:inherit font-lock-function-name-face
:weight bold
)))
993 "Base face for headers rules."
994 :group
'markdown-faces
)
996 (defface markdown-header-delimiter-face
997 '((t (:inherit font-lock-function-name-face
:weight bold
)))
998 "Base face for headers hash delimiter."
999 :group
'markdown-faces
)
1001 (defface markdown-header-face
1002 '((t (:inherit font-lock-function-name-face
:weight bold
)))
1003 "Base face for headers."
1004 :group
'markdown-faces
)
1006 (defface markdown-header-face-1
1007 '((t (:inherit markdown-header-face
)))
1008 "Face for level-1 headers."
1009 :group
'markdown-faces
)
1011 (defface markdown-header-face-2
1012 '((t (:inherit markdown-header-face
)))
1013 "Face for level-2 headers."
1014 :group
'markdown-faces
)
1016 (defface markdown-header-face-3
1017 '((t (:inherit markdown-header-face
)))
1018 "Face for level-3 headers."
1019 :group
'markdown-faces
)
1021 (defface markdown-header-face-4
1022 '((t (:inherit markdown-header-face
)))
1023 "Face for level-4 headers."
1024 :group
'markdown-faces
)
1026 (defface markdown-header-face-5
1027 '((t (:inherit markdown-header-face
)))
1028 "Face for level-5 headers."
1029 :group
'markdown-faces
)
1031 (defface markdown-header-face-6
1032 '((t (:inherit markdown-header-face
)))
1033 "Face for level-6 headers."
1034 :group
'markdown-faces
)
1036 (defface markdown-inline-code-face
1037 '((t (:inherit font-lock-constant-face
)))
1038 "Face for inline code."
1039 :group
'markdown-faces
)
1041 (defface markdown-list-face
1042 '((t (:inherit font-lock-builtin-face
)))
1043 "Face for list item markers."
1044 :group
'markdown-faces
)
1046 (defface markdown-blockquote-face
1047 '((t (:inherit font-lock-doc-face
)))
1048 "Face for blockquote sections."
1049 :group
'markdown-faces
)
1051 (defface markdown-pre-face
1052 '((t (:inherit font-lock-constant-face
)))
1053 "Face for preformatted text."
1054 :group
'markdown-faces
)
1056 (defface markdown-language-keyword-face
1057 '((t (:inherit font-lock-type-face
)))
1058 "Face for programming language identifiers."
1059 :group
'markdown-faces
)
1061 (defface markdown-link-face
1062 '((t (:inherit font-lock-keyword-face
)))
1064 :group
'markdown-faces
)
1066 (defface markdown-missing-link-face
1067 '((t (:inherit font-lock-warning-face
)))
1068 "Face for missing links."
1069 :group
'markdown-faces
)
1071 (defface markdown-reference-face
1072 '((t (:inherit font-lock-type-face
)))
1073 "Face for link references."
1074 :group
'markdown-faces
)
1076 (defface markdown-footnote-face
1077 '((t (:inherit font-lock-keyword-face
)))
1078 "Face for footnote markers."
1079 :group
'markdown-faces
)
1081 (defface markdown-url-face
1082 '((t (:inherit font-lock-string-face
)))
1084 :group
'markdown-faces
)
1086 (defface markdown-link-title-face
1087 '((t (:inherit font-lock-comment-face
)))
1088 "Face for reference link titles."
1089 :group
'markdown-faces
)
1091 (defface markdown-line-break-face
1092 '((t (:inherit font-lock-constant-face
:underline t
)))
1093 "Face for hard line breaks."
1094 :group
'markdown-faces
)
1096 (defface markdown-comment-face
1097 '((t (:inherit font-lock-comment-face
)))
1098 "Face for HTML comments."
1099 :group
'markdown-faces
)
1101 (defface markdown-math-face
1102 '((t (:inherit font-lock-string-face
)))
1103 "Face for LaTeX expressions."
1104 :group
'markdown-faces
)
1106 (defface markdown-metadata-key-face
1107 '((t (:inherit font-lock-variable-name-face
)))
1108 "Face for metadata keys."
1109 :group
'markdown-faces
)
1111 (defface markdown-metadata-value-face
1112 '((t (:inherit font-lock-string-face
)))
1113 "Face for metadata values."
1114 :group
'markdown-faces
)
1116 (defconst markdown-regex-link-inline
1117 "\\(!\\)?\\(\\[\\([^]^][^]]*\\|\\)\\]\\)\\((\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?)\\)"
1118 "Regular expression for a [text](file) or an image link ![text](file).
1119 Group 1 matches the leading exclamation point, if any.
1120 Group 2 matchs the entire square bracket term, including the text.
1121 Group 3 matches the text inside the square brackets.
1122 Group 4 matches the entire parenthesis term, including the URL and title.
1123 Group 5 matches the URL.
1124 Group 6 matches (optional) title.")
1126 (defconst markdown-regex-link-reference
1127 "\\(!\\)?\\(\\[\\([^]^][^]]*\\|\\)\\]\\)[ ]?\\(\\[\\([^]]*?\\)\\]\\)"
1128 "Regular expression for a reference link [text][id].
1129 Group 1 matches the leading exclamation point, if any.
1130 Group 2 matchs the entire first square bracket term, including the text.
1131 Group 3 matches the text inside the square brackets.
1132 Group 4 matches the entire second square bracket term.
1133 Group 5 matches the reference label.")
1135 (defconst markdown-regex-reference-definition
1136 "^ \\{0,3\\}\\(\\[[^\n]+?\\]\\):\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
1137 "Regular expression for a link definition [id]: ...")
1139 (defconst markdown-regex-footnote
1140 "\\(\\[\\^.+?\\]\\)"
1141 "Regular expression for a footnote marker [^fn].")
1143 (defconst markdown-regex-header
1144 "^\\(?:\\(.+\\)\n\\(=+\\)\\|\\(.+\\)\n\\(-+\\)\\|\\(#+\\)\\s-*\\(.*?\\)\\s-*?\\(#*\\)\\)$"
1145 "Regexp identifying Markdown headers.")
1147 (defconst markdown-regex-header-1-atx
1148 "^\\(#\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1149 "Regular expression for level 1 atx-style (hash mark) headers.")
1151 (defconst markdown-regex-header-2-atx
1152 "^\\(##\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1153 "Regular expression for level 2 atx-style (hash mark) headers.")
1155 (defconst markdown-regex-header-3-atx
1156 "^\\(###\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1157 "Regular expression for level 3 atx-style (hash mark) headers.")
1159 (defconst markdown-regex-header-4-atx
1160 "^\\(####\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1161 "Regular expression for level 4 atx-style (hash mark) headers.")
1163 (defconst markdown-regex-header-5-atx
1164 "^\\(#####\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1165 "Regular expression for level 5 atx-style (hash mark) headers.")
1167 (defconst markdown-regex-header-6-atx
1168 "^\\(######\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1169 "Regular expression for level 6 atx-style (hash mark) headers.")
1171 (defconst markdown-regex-header-1-setext
1172 "^\\(.*\\)\n\\(=+\\)$"
1173 "Regular expression for level 1 setext-style (underline) headers.")
1175 (defconst markdown-regex-header-2-setext
1176 "^\\(.*\\)\n\\(-+\\)$"
1177 "Regular expression for level 2 setext-style (underline) headers.")
1179 (defconst markdown-regex-header-setext
1180 "^\\(.+\\)\n\\(\\(?:=\\|-\\)+\\)$"
1181 "Regular expression for generic setext-style (underline) headers.")
1183 (defconst markdown-regex-header-atx
1184 "^\\(#+\\)[ \t]*\\(.*?\\)[ \t]*\\(#*\\)$"
1185 "Regular expression for generic atx-style (hash mark) headers.")
1187 (defconst markdown-regex-hr
1188 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1189 "Regular expression for matching Markdown horizontal rules.")
1191 (defconst markdown-regex-code
1192 "\\(\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(.\\|\n[^\n]\\)*?[^`]\\)\\3\\)\\([^`]\\|\\'\\)"
1193 "Regular expression for matching inline code fragments.
1195 The first group ensures that the leading backquote character
1196 is not escaped. The group \\(.\\|\n[^\n]\\) matches any
1197 character, including newlines, but not two newlines in a row.
1198 The final group requires that the character following the code
1199 fragment is not a backquote.")
1201 (defconst markdown-regex-pre
1203 "Regular expression for matching preformatted text sections.")
1205 (defconst markdown-regex-list
1206 "^\\([ \t]*\\)\\([0-9]+\\.\\|[\\*\\+-]\\)\\([ \t]+\\)"
1207 "Regular expression for matching list items.")
1209 (defconst markdown-regex-bold
1210 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1211 "Regular expression for matching bold text.
1212 Group 1 matches the character before the opening asterisk or
1213 underscore, if any, ensuring that it is not a backslash escape.
1214 Group 2 matches the entire expression, including delimiters.
1215 Groups 3 and 5 matches the opening and closing delimiters.
1216 Group 4 matches the text inside the delimiters.")
1218 (defconst markdown-regex-italic
1219 "\\(^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1220 "Regular expression for matching italic text.
1221 Group 1 matches the character before the opening asterisk or
1222 underscore, if any, ensuring that it is not a backslash escape.
1223 Group 2 matches the entire expression, including delimiters.
1224 Groups 3 and 5 matches the opening and closing delimiters.
1225 Group 4 matches the text inside the delimiters.")
1227 (defconst markdown-regex-gfm-italic
1228 "\\(^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\3\\|[^ ]\\(.\\|\n[^\n]\\)*?[^\\ ]\\3\\)\\)"
1229 "Regular expression for matching italic text in GitHub-flavored Markdown.
1230 Underscores in words are not treated as special.")
1232 (defconst markdown-regex-blockquote
1234 "Regular expression for matching blockquote lines.")
1236 (defconst markdown-regex-line-break
1237 "[^ \n\t][ \t]*\\( \\)$"
1238 "Regular expression for matching line breaks.")
1240 (defconst markdown-regex-wiki-link
1241 "\\(?:^\\|[^\\]\\)\\(\\[\\[\\([^]|]+\\)\\(|\\([^]]+\\)\\)?\\]\\]\\)"
1242 "Regular expression for matching wiki links.
1243 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1244 wiki links of the form [[PageName|link text]]. In this regular
1245 expression, group 1 matches the entire link, including square
1246 brackets, group 2 matches the first component of the wiki link
1247 and group 4 matches the second component, after the pipe, when
1248 present. The meanings of the first and second components depend
1249 on the value of `markdown-wiki-link-alias-first'.")
1251 (defconst markdown-regex-uri
1252 (concat (regexp-opt markdown-uri-types
) ":[^]\t\n\r<>,;() ]+")
1253 "Regular expression for matching inline URIs.")
1255 (defconst markdown-regex-angle-uri
1256 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types
) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1257 "Regular expression for matching inline URIs in angle brackets.")
1259 (defconst markdown-regex-email
1260 "<\\(\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+\\)>"
1261 "Regular expression for matching inline email addresses.")
1263 (defconst markdown-regex-link-generic
1264 (concat "\\(?:" markdown-regex-wiki-link
1265 "\\|" markdown-regex-link-inline
1266 "\\|" markdown-regex-link-reference
1267 "\\|" markdown-regex-angle-uri
"\\)")
1268 "Regular expression for matching any recognized link.")
1270 (defconst markdown-regex-block-separator
1271 "\\(\\`\\|\\(\n[ \t]*\n\\)[^\n \t]\\)"
1272 "Regular expression for matching block boundaries.")
1274 (defconst markdown-regex-math-inline
1275 "\\(^\\|[^\\]\\)\\(\\$\\($\\([^\\$]\\|\\\\.\\)*\\$\\|\\([^\\$]\\|\\\\.\\)*\\)\\$\\)"
1276 "Regular expression for itex $..$ or $$..$$ math mode expressions.")
1278 (defconst markdown-regex-math-display
1279 "^\\\\\\[\\(.\\|\n\\)*?\\\\\\]$"
1280 "Regular expression for itex \[..\] display mode expressions.")
1282 (defconst markdown-regex-multimarkdown-metadata
1283 "^\\([[:alpha:]][[:alpha:] _-]*?\\):[ \t]*\\(.*\\)$"
1284 "Regular expression for matching MultiMarkdown metadata.")
1286 (defconst markdown-regex-pandoc-metadata
1287 "^\\(%\\)[ \t]*\\(.*\\)$"
1288 "Regular expression for matching Pandoc metadata.")
1290 (defvar markdown-mode-font-lock-keywords-basic
1292 (cons 'markdown-match-pre-blocks
'((0 markdown-pre-face
)))
1293 (cons 'markdown-match-fenced-code-blocks
'((0 markdown-pre-face
)))
1294 (cons markdown-regex-blockquote
'markdown-blockquote-face
)
1295 (cons markdown-regex-header-1-setext
'((1 markdown-header-face-1
)
1296 (2 markdown-header-rule-face
)))
1297 (cons markdown-regex-header-2-setext
'((1 markdown-header-face-2
)
1298 (2 markdown-header-rule-face
)))
1299 (cons markdown-regex-header-6-atx
'((1 markdown-header-delimiter-face
)
1300 (2 markdown-header-face-6
)
1301 (3 markdown-header-delimiter-face
)))
1302 (cons markdown-regex-header-5-atx
'((1 markdown-header-delimiter-face
)
1303 (2 markdown-header-face-5
)
1304 (3 markdown-header-delimiter-face
)))
1305 (cons markdown-regex-header-4-atx
'((1 markdown-header-delimiter-face
)
1306 (2 markdown-header-face-4
)
1307 (3 markdown-header-delimiter-face
)))
1308 (cons markdown-regex-header-3-atx
'((1 markdown-header-delimiter-face
)
1309 (2 markdown-header-face-3
)
1310 (3 markdown-header-delimiter-face
)))
1311 (cons markdown-regex-header-2-atx
'((1 markdown-header-delimiter-face
)
1312 (2 markdown-header-face-2
)
1313 (3 markdown-header-delimiter-face
)))
1314 (cons markdown-regex-header-1-atx
'((1 markdown-header-delimiter-face
)
1315 (2 markdown-header-face-1
)
1316 (3 markdown-header-delimiter-face
)))
1317 (cons 'markdown-match-multimarkdown-metadata
'((1 markdown-metadata-key-face
)
1318 (2 markdown-metadata-value-face
)))
1319 (cons 'markdown-match-pandoc-metadata
'((1 markdown-comment-face
)
1320 (2 markdown-metadata-value-face
)))
1321 (cons markdown-regex-hr
'markdown-header-face
)
1322 (cons 'markdown-match-comments
'((0 markdown-comment-face
)))
1323 (cons 'markdown-match-code
'((0 markdown-inline-code-face
)))
1324 (cons markdown-regex-angle-uri
'markdown-link-face
)
1325 (cons markdown-regex-uri
'markdown-link-face
)
1326 (cons markdown-regex-email
'markdown-link-face
)
1327 (cons markdown-regex-list
'(2 markdown-list-face
))
1328 (cons markdown-regex-footnote
'markdown-footnote-face
)
1329 (cons markdown-regex-link-inline
'((1 markdown-link-face t t
)
1330 (2 markdown-link-face t
)
1331 (4 markdown-url-face t
)
1332 (6 markdown-link-title-face t t
)))
1333 (cons markdown-regex-link-reference
'((1 markdown-link-face t t
)
1334 (2 markdown-link-face t
)
1335 (4 markdown-reference-face t
)))
1336 (cons markdown-regex-reference-definition
'((1 markdown-reference-face t
)
1337 (2 markdown-url-face t
)
1338 (3 markdown-link-title-face t
)))
1339 (cons markdown-regex-bold
'(2 markdown-bold-face
))
1340 (cons markdown-regex-line-break
'(1 markdown-line-break-face prepend
))
1342 "Syntax highlighting for Markdown files.")
1344 (defvar markdown-mode-font-lock-keywords-core
1346 (cons markdown-regex-italic
'(2 markdown-italic-face
))
1348 "Additional syntax highlighting for Markdown files.
1349 Includes features which are overridden by some variants.")
1351 (defconst markdown-mode-font-lock-keywords-math
1353 ;; Math mode $..$ or $$..$$
1354 (cons markdown-regex-math-inline
'(2 markdown-math-face
))
1355 ;; Display mode equations with brackets: \[ \]
1356 (cons markdown-regex-math-display
'markdown-math-face
)
1357 ;; Equation reference (eq:foo)
1358 (cons "(eq:[[:alnum:]:_]+)" 'markdown-reference-face
)
1359 ;; Equation reference \eqref{foo}
1360 (cons "\\\\eqref{[[:alnum:]:_]+}" 'markdown-reference-face
))
1361 "Syntax highlighting for LaTeX and itex fragments.")
1363 (defvar markdown-mode-font-lock-keywords nil
1364 "Default highlighting expressions for Markdown mode.
1365 This variable is defined as a buffer-local variable for dynamic
1366 extension support.")
1369 (defvar markdown-footnote-counter
0
1370 "Counter for footnote numbers.")
1371 (make-variable-buffer-local 'markdown-footnote-counter
)
1373 (defconst markdown-footnote-chars
1375 "Regular expression maching any character that is allowed in a footnote identifier.")
1378 ;;; Compatibility =============================================================
1380 (defun markdown-replace-regexp-in-string (regexp rep string
)
1381 "Replace ocurrences of REGEXP with REP in STRING.
1382 This is a compatibility wrapper to provide `replace-regexp-in-string'
1384 (if (featurep 'xemacs
)
1385 (replace-in-string string regexp rep
)
1386 (replace-regexp-in-string regexp rep string
)))
1388 ;; `markdown-use-region-p' is a compatibility function which checks
1389 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
1392 ;; Emacs 23 and newer
1393 ((fboundp 'use-region-p
)
1394 (defalias 'markdown-use-region-p
'use-region-p
))
1396 ((and (boundp 'transient-mark-mode
) (boundp 'mark-active
))
1397 (defun markdown-use-region-p ()
1398 "Compatibility wrapper to provide `use-region-p'."
1399 (and transient-mark-mode mark-active
)))
1401 ((fboundp 'region-active-p
)
1402 (defalias 'markdown-use-region-p
'region-active-p
))))
1404 (defun markdown-use-buttons-p ()
1405 "Determine whether this Emacs supports buttons."
1406 (or (featurep 'button
) (locate-library "button")))
1409 ;;; Markdown Parsing Functions ================================================
1411 (defun markdown-cur-line-blank-p ()
1412 "Return t if the current line is blank and nil otherwise."
1415 (re-search-forward "^\\s *$" (line-end-position) t
)))
1417 (defun markdown-prev-line-blank-p ()
1418 "Return t if the previous line is blank and nil otherwise.
1419 If we are at the first line, then consider the previous line to be blank."
1420 (or (= (line-beginning-position) (point-min))
1423 (markdown-cur-line-blank-p))))
1425 (defun markdown-next-line-blank-p ()
1426 "Return t if the next line is blank and nil otherwise.
1427 If we are at the last line, then consider the next line to be blank."
1428 (or (= (line-end-position) (point-max))
1431 (markdown-cur-line-blank-p))))
1433 (defun markdown-prev-line-indent-p ()
1434 "Return t if the previous line is indented and nil otherwise."
1437 (goto-char (line-beginning-position))
1438 (if (re-search-forward "^\\s " (line-end-position) t
) t
)))
1440 (defun markdown-cur-line-indent ()
1441 "Return the number of leading whitespace characters in the current line."
1444 (goto-char (line-beginning-position))
1445 (re-search-forward "^[ \t]+" (line-end-position) t
)
1448 (defun markdown-prev-line-indent ()
1449 "Return the number of leading whitespace characters in the previous line."
1452 (markdown-cur-line-indent)))
1454 (defun markdown-next-line-indent ()
1455 "Return the number of leading whitespace characters in the next line."
1458 (markdown-cur-line-indent)))
1460 (defun markdown-cur-non-list-indent ()
1461 "Return beginning position of list item text (not including the list marker).
1462 Return nil if the current line is not the beginning of a list item."
1466 (when (re-search-forward markdown-regex-list
(line-end-position) t
)
1467 (current-column)))))
1469 (defun markdown-prev-non-list-indent ()
1470 "Return position of the first non-list-marker on the previous line."
1473 (markdown-cur-non-list-indent)))
1475 (defun markdown-new-baseline-p ()
1476 "Determine if the current line begins a new baseline level."
1480 (or (looking-at markdown-regex-header
)
1481 (looking-at markdown-regex-hr
)
1482 (and (null (markdown-cur-non-list-indent))
1483 (= (markdown-cur-line-indent) 0)
1484 (markdown-prev-line-blank-p))))))
1486 (defun markdown-search-backward-baseline ()
1487 "Search backward baseline point with no indentation and not a list item."
1490 (while (not (or stop
(bobp)))
1491 (re-search-backward markdown-regex-block-separator nil t
)
1493 (goto-char (match-end 2))
1495 ((markdown-new-baseline-p)
1497 ((looking-at markdown-regex-list
)
1499 (t (setq stop t
)))))))
1501 (defun markdown-update-list-levels (marker indent levels
)
1502 "Update list levels given list MARKER, block INDENT, and current LEVELS.
1503 Here, MARKER is a string representing the type of list, INDENT is an integer
1504 giving the indentation, in spaces, of the current block, and LEVELS is a
1505 list of the indentation levels of parent list items. When LEVELS is nil,
1506 it means we are at baseline (not inside of a nested list)."
1508 ;; New list item at baseline.
1509 ((and marker
(null levels
))
1510 (setq levels
(list indent
)))
1511 ;; List item with greater indentation (four or more spaces).
1512 ;; Increase list level.
1513 ((and marker
(>= indent
(+ (car levels
) 4)))
1514 (setq levels
(cons indent levels
)))
1515 ;; List item with greater or equal indentation (less than four spaces).
1516 ;; Do not increase list level.
1517 ((and marker
(>= indent
(car levels
)))
1519 ;; Lesser indentation level.
1520 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
1521 ;; indentation could move back more than one list level). Note
1522 ;; that this block need not be the beginning of list item.
1523 ((< indent
(car levels
))
1524 (while (and (> (length levels
) 1)
1525 (< indent
(+ (cadr levels
) 4)))
1526 (setq levels
(cdr levels
)))
1528 ;; Otherwise, do nothing.
1531 (defun markdown-calculate-list-levels ()
1532 "Calculate list levels at point.
1533 Return a list of the form (n1 n2 n3 ...) where n1 is the
1534 indentation of the deepest nested list item in the branch of
1535 the list at the point, n2 is the indentation of the parent
1536 list item, and so on. The depth of the list item is therefore
1537 the length of the returned list. If the point is not at or
1538 immediately after a list item, return nil."
1540 (let ((first (point)) levels indent pre-regexp
)
1541 ;; Find a baseline point with zero list indentation
1542 (markdown-search-backward-baseline)
1543 ;; Search for all list items between baseline and LOC
1544 (while (and (< (point) first
)
1545 (re-search-forward markdown-regex-list first t
))
1546 (setq pre-regexp
(format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels
))))
1549 ;; Make sure this is not a header or hr
1550 ((markdown-new-baseline-p) (setq levels nil
))
1551 ;; Make sure this is not a line from a pre block
1552 ((looking-at pre-regexp
))
1553 ;; If not, then update levels
1555 (setq indent
(markdown-cur-line-indent))
1556 (setq levels
(markdown-update-list-levels (match-string 2)
1561 (defun markdown-prev-list-item (level)
1562 "Search backward from point for a list item with indentation LEVEL.
1563 Set point to the beginning of the item, and return point, or nil
1565 (let (bounds indent prev
)
1568 (setq indent
(markdown-cur-line-indent))
1571 ;; Stop at beginning of buffer
1572 ((bobp) (setq prev nil
))
1573 ;; Continue if current line is blank
1574 ((markdown-cur-line-blank-p) t
)
1576 ((and (looking-at markdown-regex-list
)
1577 (setq bounds
(markdown-cur-list-item-bounds)))
1579 ;; Continue at item with greater indentation
1580 ((> (nth 3 bounds
) level
) t
)
1581 ;; Stop and return point at item of equal indentation
1582 ((= (nth 3 bounds
) level
)
1585 ;; Stop and return nil at item with lesser indentation
1586 ((< (nth 3 bounds
) level
)
1589 ;; Continue while indentation is the same or greater
1590 ((>= indent level
) t
)
1591 ;; Stop if current indentation is less than list item
1592 ;; and the next is blank
1593 ((and (< indent level
)
1594 (markdown-next-line-blank-p))
1597 ((looking-at markdown-regex-header
) (setq prev nil
))
1598 ;; Stop at a horizontal rule
1599 ((looking-at markdown-regex-hr
) (setq prev nil
))
1600 ;; Otherwise, continue.
1603 (setq indent
(markdown-cur-line-indent)))
1606 (defun markdown-next-list-item (level)
1607 "Search forward from point for the next list item with indentation LEVEL.
1608 Set point to the beginning of the item, and return point, or nil
1610 (let (bounds indent prev next
)
1613 (setq indent
(markdown-cur-line-indent))
1616 ;; Stop at end of the buffer.
1617 ((eobp) (setq prev nil
))
1618 ;; Continue if the current line is blank
1619 ((markdown-cur-line-blank-p) t
)
1621 ((and (looking-at markdown-regex-list
)
1622 (setq bounds
(markdown-cur-list-item-bounds)))
1624 ;; Continue at item with greater indentation
1625 ((> (nth 3 bounds
) level
) t
)
1626 ;; Stop and return point at item of equal indentation
1627 ((= (nth 3 bounds
) level
)
1630 ;; Stop and return nil at item with lesser indentation
1631 ((< (nth 3 bounds
) level
)
1634 ;; Continue while indentation is the same or greater
1635 ((>= indent level
) t
)
1636 ;; Stop if current indentation is less than list item
1637 ;; and the previous line was blank.
1638 ((and (< indent level
)
1639 (markdown-prev-line-blank-p))
1642 ((looking-at markdown-regex-header
) (setq next nil
))
1643 ;; Stop at a horizontal rule
1644 ((looking-at markdown-regex-hr
) (setq next nil
))
1645 ;; Otherwise, continue.
1648 (setq indent
(markdown-cur-line-indent)))
1651 (defun markdown-cur-list-item-end (level)
1652 "Move to the end of the current list item with nonlist indentation LEVEL.
1653 If the point is not in a list item, do nothing."
1656 (setq indent
(markdown-cur-line-indent))
1659 ;; Stop at end of the buffer.
1661 ;; Continue if the current line is blank
1662 ((markdown-cur-line-blank-p) t
)
1663 ;; Continue while indentation is the same or greater
1664 ((>= indent level
) t
)
1665 ;; Stop if current indentation is less than list item
1666 ;; and the previous line was blank.
1667 ((and (< indent level
)
1668 (markdown-prev-line-blank-p))
1670 ;; Stop at a new list item of the same or lesser indentation
1671 ((looking-at markdown-regex-list
) nil
)
1673 ((looking-at markdown-regex-header
) nil
)
1674 ;; Stop at a horizontal rule
1675 ((looking-at markdown-regex-hr
) nil
)
1676 ;; Otherwise, continue.
1679 (setq indent
(markdown-cur-line-indent)))
1680 ;; Don't skip over whitespace for empty list items (marker and
1681 ;; whitespace only), just move to end of whitespace.
1682 (if (looking-back (concat markdown-regex-list
"\\s-*"))
1683 (goto-char (match-end 3))
1684 (skip-syntax-backward "-"))))
1686 (defun markdown-cur-list-item-bounds ()
1687 "Return bounds and indentation of the current list item.
1688 Return a list of the form (begin end indent nonlist-indent marker).
1689 If the point is not inside a list item, return nil.
1690 Leave match data intact for `markdown-regex-list'."
1691 (let (cur prev-begin prev-end indent nonlist-indent marker
)
1692 ;; Store current location
1694 ;; Verify that cur is between beginning and end of item
1697 (when (re-search-backward markdown-regex-list nil t
)
1698 (setq prev-begin
(match-beginning 0))
1699 (setq indent
(length (match-string 1)))
1700 (setq nonlist-indent
(length (match-string 0)))
1701 (setq marker
(concat (match-string 2) (match-string 3)))
1703 (markdown-cur-list-item-end nonlist-indent
)
1704 (setq prev-end
(point)))
1705 (when (and (>= cur prev-begin
)
1708 (list prev-begin prev-end indent nonlist-indent marker
))))))
1710 (defun markdown-bounds-of-thing-at-point (thing)
1711 "Call `bounds-of-thing-at-point' for THING with slight modifications.
1712 Does not include trailing newlines when THING is 'line. Handles the
1713 end of buffer case by setting both endpoints equal to the value of
1714 `point-max', since an empty region will trigger empty markup insertion.
1715 Return bounds of form (beg . end) if THING is found, or nil otherwise."
1716 (let* ((bounds (bounds-of-thing-at-point thing
))
1720 (when (eq thing
'line
)
1721 (cond ((and (eobp) (markdown-cur-line-blank-p))
1723 ((char-equal (char-before b
) ?\^J
)
1727 (defun markdown-reference-definition (reference)
1728 "Find out whether Markdown REFERENCE is defined.
1729 REFERENCE should include the square brackets, like [this].
1730 When REFERENCE is defined, return a list of the form (text start end)
1731 containing the definition text itself followed by the start and end
1732 locations of the text. Otherwise, return nil.
1733 Leave match data for `markdown-regex-reference-definition'
1734 intact additional processing."
1735 (let ((reference (downcase reference
)))
1737 (goto-char (point-min))
1739 (while (re-search-forward markdown-regex-reference-definition nil t
)
1740 (when (string= reference
(downcase (match-string-no-properties 1)))
1742 (list (match-string-no-properties 2)
1743 (match-beginning 2) (match-end 2)))))))))
1745 (defun markdown-get-defined-references ()
1746 "Return a list of all defined reference labels (including square brackets)."
1748 (goto-char (point-min))
1750 (while (re-search-forward markdown-regex-reference-definition nil t
)
1751 (let ((target (match-string-no-properties 1)))
1752 (add-to-list 'refs target t
)))
1755 (defun markdown-code-at-point-p ()
1756 "Return non-nil if the point is at an inline code fragment.
1757 Return nil otherwise. Set match data according to
1758 `markdown-match-code' upon success.
1759 This function searches the block for a code fragment that
1760 contains the point using `markdown-match-code'. We do this
1761 because `thing-at-point-looking-at' does not work reliably with
1762 `markdown-regex-code'."
1765 (let ((old-point (point))
1766 (end-of-block (progn (markdown-end-of-block) (point)))
1768 (markdown-beginning-of-block)
1769 (while (and (markdown-match-code end-of-block
)
1771 (< (match-end 0) old-point
)))
1772 (and found
; matched something
1773 (<= (match-beginning 0) old-point
) ; match contains old-point
1774 (>= (match-end 0) old-point
)))))
1777 ;;; Markdown Font Lock Matching Functions =====================================
1779 (defun markdown-match-comments (last)
1780 "Match HTML comments from the point to LAST."
1781 (cond ((search-forward "<!--" last t
)
1783 (let ((beg (point)))
1784 (cond ((search-forward-regexp "--[ \t]*>" last t
)
1785 (set-match-data (list beg
(point)))
1790 (defun markdown-match-code (last)
1791 "Match inline code from the point to LAST."
1794 (cond ((re-search-forward markdown-regex-code last t
)
1795 (set-match-data (list (match-beginning 2) (match-end 2)
1796 (match-beginning 4) (match-end 4)))
1797 (goto-char (match-end 0))
1799 (t (forward-char 2) nil
)))
1801 (defun markdown-match-pre-blocks (last)
1802 "Match Markdown pre blocks from point to LAST."
1803 (let ((levels (markdown-calculate-list-levels))
1804 indent pre-regexp end-regexp begin end stop
)
1805 (while (and (< (point) last
) (not end
))
1806 ;; Search for a region with sufficient indentation
1809 (setq indent
(1+ (length levels
))))
1810 (setq pre-regexp
(format "^\\( \\|\t\\)\\{%d\\}" indent
))
1811 (setq end-regexp
(format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent
)))
1814 ;; If not at the beginning of a line, move forward
1815 ((not (bolp)) (forward-line))
1816 ;; Move past blank lines
1817 ((markdown-cur-line-blank-p) (forward-line))
1818 ;; At headers and horizontal rules, reset levels
1819 ((markdown-new-baseline-p) (forward-line) (setq levels nil
))
1820 ;; If the current line has sufficient indentation, mark out pre block
1821 ((looking-at pre-regexp
)
1822 (setq begin
(match-beginning 0))
1823 (while (and (or (looking-at pre-regexp
) (markdown-cur-line-blank-p))
1827 ;; If current line has a list marker, update levels, move to end of block
1828 ((looking-at markdown-regex-list
)
1829 (setq levels
(markdown-update-list-levels
1830 (match-string 2) (markdown-cur-line-indent) levels
))
1831 (markdown-end-of-block-element))
1832 ;; If this is the end of the indentation level, adjust levels accordingly.
1833 ;; Only match end of indentation level if levels is not the empty list.
1834 ((and (car levels
) (looking-at end-regexp
))
1835 (setq levels
(markdown-update-list-levels
1836 nil
(markdown-cur-line-indent) levels
))
1837 (markdown-end-of-block-element))
1838 (t (markdown-end-of-block-element))))
1840 (if (not (and begin end
))
1841 ;; Return nil if no pre block was found
1843 ;; Set match data and return t upon success
1844 (set-match-data (list begin end
))
1847 (defun markdown-match-fenced-code-blocks (last)
1848 "Match fenced code blocks from the point to LAST."
1849 (cond ((search-forward-regexp "^\\([~]\\{3,\\}\\)" last t
)
1851 (let ((beg (point)))
1853 (cond ((search-forward-regexp
1854 (concat "^" (match-string 1) "~*") last t
)
1855 (set-match-data (list beg
(point)))
1860 (defun markdown-match-gfm-code-blocks (last)
1861 "Match GFM quoted code blocks from point to LAST."
1862 (let (open lang body close all
)
1863 (cond ((and (eq major-mode
'gfm-mode
)
1864 (search-forward-regexp "^\\(```\\)\\(\\w+\\)?$" last t
))
1866 (setq open
(list (match-beginning 1) (match-end 1))
1867 lang
(list (match-beginning 2) (match-end 2)))
1869 (setq body
(list (point)))
1870 (cond ((search-forward-regexp "^```$" last t
)
1871 (setq body
(reverse (cons (1- (match-beginning 0)) body
))
1872 close
(list (match-beginning 0) (match-end 0))
1873 all
(list (car open
) (match-end 0)))
1874 (set-match-data (append all open lang body close
))
1879 (defun markdown-match-generic-metadata (regexp last
)
1880 "Match generic metadata specified by REGEXP from the point to LAST."
1881 (let ((header-end (save-excursion
1882 (goto-char (point-min))
1883 (if (re-search-forward "\n\n" (point-max) t
)
1886 (cond ((>= (point) header-end
)
1887 ;; Don't match anything outside of the header.
1889 ((re-search-forward regexp
(min last header-end
) t
)
1890 ;; If a metadata item is found, it may span several lines.
1891 (let ((key-beginning (match-beginning 1))
1892 (key-end (match-end 1))
1893 (value-beginning (match-beginning 2)))
1894 (while (and (not (looking-at regexp
))
1895 (not (> (point) (min last header-end
)))
1901 (set-match-data (list key-beginning
(point) ; complete metadata
1902 key-beginning key-end
; key
1903 value-beginning
(point))) ; value
1907 (defun markdown-match-multimarkdown-metadata (last)
1908 "Match MultiMarkdown metadata from the point to LAST."
1909 (markdown-match-generic-metadata markdown-regex-multimarkdown-metadata last
))
1911 (defun markdown-match-pandoc-metadata (last)
1912 "Match Pandoc metadata from the point to LAST."
1913 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last
))
1915 (defun markdown-font-lock-extend-region ()
1916 "Extend the search region to include an entire block of text.
1917 This helps improve font locking for block constructs such as pre blocks."
1918 ;; Avoid compiler warnings about these global variables from font-lock.el.
1919 ;; See the documentation for variable `font-lock-extend-region-functions'.
1920 (eval-when-compile (defvar font-lock-beg
) (defvar font-lock-end
))
1922 (goto-char font-lock-beg
)
1923 (let ((found (or (re-search-backward "\n\n" nil t
) (point-min))))
1924 (goto-char font-lock-end
)
1925 (when (re-search-forward "\n\n" nil t
)
1927 (setq font-lock-end
(point)))
1928 (setq font-lock-beg found
))))
1931 ;;; Syntax Table ==============================================================
1933 (defvar markdown-mode-syntax-table
1934 (let ((tab (make-syntax-table text-mode-syntax-table
)))
1935 (modify-syntax-entry ?
\" "." tab
)
1937 "Syntax table for `markdown-mode'.")
1940 ;;; Element Insertion =========================================================
1942 (defun markdown-ensure-blank-line-before ()
1943 "If previous line is not already blank, insert a blank line before point."
1944 (unless (bolp) (insert "\n"))
1945 (unless (or (bobp) (looking-back "\n\\s-*\n")) (insert "\n")))
1947 (defun markdown-ensure-blank-line-after ()
1948 "If following line is not already blank, insert a blank line after point.
1949 Return the point where it was originally."
1951 (unless (eolp) (insert "\n"))
1952 (unless (or (eobp) (looking-at "\n\\s-*\n")) (insert "\n"))))
1954 (defun markdown-wrap-or-insert (s1 s2
&optional thing beg end
)
1955 "Insert the strings S1 and S2, wrapping around region or THING.
1956 If a region is specified by the optional BEG and END arguments,
1957 wrap the strings S1 and S2 around that region.
1958 If there is an active region, wrap the strings S1 and S2 around
1959 the region. If there is not an active region but the point is at
1960 THING, wrap that thing (which defaults to word). Otherwise, just
1961 insert S1 and S2 and place the cursor in between. Return the
1962 bounds of the entire wrapped string, or nil if nothing was wrapped
1963 and S1 and S2 were only inserted."
1964 (let (a b bounds new-point
)
1970 new-point
(+ (point) (length s1
))))
1972 ((markdown-use-region-p)
1973 (setq a
(region-beginning)
1975 new-point
(+ (point) (length s1
))))
1976 ;; Thing (word) at point
1977 ((setq bounds
(markdown-bounds-of-thing-at-point (or thing
'word
)))
1978 (setq a
(car bounds
)
1980 new-point
(+ (point) (length s1
))))
1981 ;; No active region and no word
1989 (when new-point
(goto-char new-point
))
1992 (setq b
(+ b
(length s1
) (length s2
)))
1995 (defun markdown-point-after-unwrap (cur prefix suffix
)
1996 "Return desired position of point after an unwrapping operation.
1997 CUR gives the position of the point before the operation.
1998 Additionally, two cons cells must be provided. PREFIX gives the
1999 bounds of the prefix string and SUFFIX gives the bounds of the
2001 (cond ((< cur
(cdr prefix
)) (car prefix
))
2002 ((< cur
(car suffix
)) (- cur
(- (cdr prefix
) (car prefix
))))
2003 ((<= cur
(cdr suffix
))
2004 (- cur
(+ (- (cdr prefix
) (car prefix
))
2005 (- cur
(car suffix
)))))
2008 (defun markdown-unwrap-thing-at-point (regexp all text
)
2009 "Remove prefix and suffix of thing at point and reposition the point.
2010 When the thing at point matches REGEXP, replace the subexpression
2011 ALL with the string in subexpression TEXT. Reposition the point
2012 in an appropriate location accounting for the removal of prefix
2013 and suffix strings. Return new bounds of string from group TEXT.
2014 When REGEXP is nil, assumes match data is already set."
2015 (when (or (null regexp
)
2016 (thing-at-point-looking-at regexp
))
2018 (prefix (cons (match-beginning all
) (match-beginning text
)))
2019 (suffix (cons (match-end text
) (match-end all
)))
2020 (bounds (cons (match-beginning text
) (match-end text
))))
2021 ;; Replace the thing at point
2022 (replace-match (match-string text
) t t nil all
)
2023 ;; Reposition the point
2024 (goto-char (markdown-point-after-unwrap cur prefix suffix
))
2026 (setq bounds
(cons (car prefix
)
2027 (- (cdr bounds
) (- (cdr prefix
) (car prefix
))))))))
2029 (defun markdown-unwrap-things-in-region (beg end regexp all text
)
2030 "Remove prefix and suffix of all things in region from BEG to END.
2031 When a thing in the region matches REGEXP, replace the
2032 subexpression ALL with the string in subexpression TEXT.
2033 Return a cons cell containing updated bounds for the region."
2036 (let ((removed 0) len-all len-text
)
2037 (while (re-search-forward regexp
(- end removed
) t
)
2038 (setq len-all
(length (match-string-no-properties all
)))
2039 (setq len-text
(length (match-string-no-properties text
)))
2040 (setq removed
(+ removed
(- len-all len-text
)))
2041 (replace-match (match-string text
) t t nil all
))
2042 (cons beg
(- end removed
)))))
2044 (defun markdown-insert-hr (arg)
2045 "Insert or replace a horizonal rule.
2046 By default, use the first element of `markdown-hr-strings'. When
2047 ARG is non-nil, as when given a prefix, select a different
2048 element as follows. When prefixed with \\[universal-argument],
2049 use the last element of `markdown-hr-strings' instead. When
2050 prefixed with an integer from 1 to the length of
2051 `markdown-hr-strings', use the element in that position instead."
2053 (when (thing-at-point-looking-at markdown-regex-hr
)
2054 (delete-region (match-beginning 0) (match-end 0)))
2055 (markdown-ensure-blank-line-before)
2056 (cond ((equal arg
'(4))
2057 (insert (car (reverse markdown-hr-strings
))))
2058 ((and (integerp arg
) (> arg
0)
2059 (<= arg
(length markdown-hr-strings
)))
2060 (insert (nth (1- arg
) markdown-hr-strings
)))
2062 (insert (car markdown-hr-strings
))))
2063 (markdown-ensure-blank-line-after))
2065 (defun markdown-insert-bold ()
2066 "Insert markup to make a region or word bold.
2067 If there is an active region, make the region bold. If the point
2068 is at a non-bold word, make the word bold. If the point is at a
2069 bold word or phrase, remove the bold markup. Otherwise, simply
2070 insert bold delimiters and place the cursor in between them."
2072 (let ((delim (if markdown-bold-underscore
"__" "**")))
2073 (if (markdown-use-region-p)
2075 (let ((bounds (markdown-unwrap-things-in-region
2076 (region-beginning) (region-end)
2077 markdown-regex-bold
2 4)))
2078 (markdown-wrap-or-insert delim delim nil
(car bounds
) (cdr bounds
)))
2079 ;; Bold markup removal, bold word at point, or empty markup insertion
2080 (if (thing-at-point-looking-at markdown-regex-bold
)
2081 (markdown-unwrap-thing-at-point nil
2 4)
2082 (markdown-wrap-or-insert delim delim
'word nil nil
)))))
2084 (defun markdown-insert-italic ()
2085 "Insert markup to make a region or word italic.
2086 If there is an active region, make the region italic. If the point
2087 is at a non-italic word, make the word italic. If the point is at an
2088 italic word or phrase, remove the italic markup. Otherwise, simply
2089 insert italic delimiters and place the cursor in between them."
2091 (let ((delim (if markdown-italic-underscore
"_" "*")))
2092 (if (markdown-use-region-p)
2094 (let ((bounds (markdown-unwrap-things-in-region
2095 (region-beginning) (region-end)
2096 markdown-regex-italic
2 4)))
2097 (markdown-wrap-or-insert delim delim nil
(car bounds
) (cdr bounds
)))
2098 ;; Italic markup removal, italic word at point, or empty markup insertion
2099 (if (thing-at-point-looking-at markdown-regex-italic
)
2100 (markdown-unwrap-thing-at-point nil
2 4)
2101 (markdown-wrap-or-insert delim delim
'word nil nil
)))))
2103 (defun markdown-insert-code ()
2104 "Insert markup to make a region or word an inline code fragment.
2105 If there is an active region, make the region an inline code
2106 fragment. If the point is at a word, make the word an inline
2107 code fragment. Otherwise, simply insert code delimiters and
2108 place the cursor in between them."
2110 (if (markdown-use-region-p)
2112 (let ((bounds (markdown-unwrap-things-in-region
2113 (region-beginning) (region-end)
2114 markdown-regex-code
2 4)))
2115 (markdown-wrap-or-insert "`" "`" nil
(car bounds
) (cdr bounds
)))
2116 ;; Code markup removal, code markup for word, or empty markup insertion
2117 (if (markdown-code-at-point-p)
2118 (markdown-unwrap-thing-at-point nil
0 1)
2119 (markdown-wrap-or-insert "`" "`" 'word nil nil
))))
2121 (defun markdown-insert-link ()
2122 "Insert an inline link, using region or word as link text if possible.
2123 If there is an active region, use the region as the link text. If the
2124 point is at a word, use the word as the link text. In these cases, the
2125 point will be left at the position for inserting a URL. If there is no
2126 active region and the point is not at word, simply insert link markup and
2127 place the point in the position to enter link text."
2129 (let ((bounds (markdown-wrap-or-insert "[" "]()")))
2131 (goto-char (- (cdr bounds
) 1)))))
2133 (defun markdown-insert-reference-link (text label
&optional url title
)
2134 "Insert a reference link and, optionally, a reference definition.
2135 The link TEXT will be inserted followed by the optional LABEL.
2136 If a URL is given, also insert a definition for the reference
2137 LABEL according to `markdown-reference-location'. If a TITLE is
2138 given, it will be added to the end of the reference definition
2139 and will be used to populate the title attribute when converted
2140 to XHTML. If URL is nil, insert only the link portion (for
2141 example, when a reference label is already defined)."
2142 (insert (concat "[" text
"][" label
"]"))
2145 (label (if (> (length label
) 0) label text
)))
2147 ((eq markdown-reference-location
'end
) (goto-char (point-max)))
2148 ((eq markdown-reference-location
'immediately
) (markdown-end-of-block))
2149 ((eq markdown-reference-location
'header
) (markdown-end-of-defun)))
2150 (unless (markdown-cur-line-blank-p) (insert "\n"))
2151 (insert "\n[" label
"]: " url
)
2152 (unless (> (length url
) 0)
2154 (when (> (length title
) 0)
2155 (insert " \"" title
"\""))
2157 (unless (or (eobp) (looking-at "\n"))
2160 (when (> (length url
) 0)
2162 (substitute-command-keys
2163 "Defined reference [%s], press \\[markdown-jump] to jump there")
2164 (or label text
))))))
2166 (defun markdown-insert-reference-link-dwim ()
2167 "Insert a reference link of the form [text][label] at point.
2168 If there is an active region, the text in the region will be used
2169 as the link text. If the point is at a word, it will be used as
2170 the link text. Otherwise, the link text will be read from the
2171 minibuffer. The link label will be read from the minibuffer in
2172 both cases, with completion from the set of currently defined
2173 references. To create an implicit reference link, press RET to
2174 accept the default, an empty label. If the entered referenced
2175 label is not defined, additionally prompt for the URL
2176 and (optional) title. The reference definition is placed at the
2177 location determined by `markdown-reference-location'."
2179 (let* ((defined-labels (mapcar (lambda (x) (substring x
1 -
1))
2180 (markdown-get-defined-references)))
2181 (bounds (or (and (markdown-use-region-p)
2182 (cons (region-beginning) (region-end)))
2183 (markdown-bounds-of-thing-at-point 'word
)))
2185 (buffer-substring (car bounds
) (cdr bounds
))
2186 (read-string "Link Text: ")))
2187 (label (completing-read
2188 "Link Label (default: none): " defined-labels
2189 nil nil nil
'markdown-reference-label-history nil
))
2190 (ref (markdown-reference-definition
2191 (concat "[" (if (> (length label
) 0) label text
) "]")))
2192 (url (unless ref
(read-string "Link URL: ")))
2193 (title (when (> (length url
) 0)
2194 (read-string "Link Title (optional): "))))
2195 (when bounds
(delete-region (car bounds
) (cdr bounds
)))
2196 (markdown-insert-reference-link text label url title
)))
2198 (defun markdown-insert-uri ()
2199 "Insert markup for an inline URI.
2200 If there is an active region, use it as the URI. If the point is
2201 at a URI, wrap it with angle brackets. If the point is at an
2202 inline URI, remove the angle brackets. Otherwise, simply insert
2203 angle brackets place the point between them."
2205 (if (markdown-use-region-p)
2207 (let ((bounds (markdown-unwrap-things-in-region
2208 (region-beginning) (region-end)
2209 markdown-regex-angle-uri
0 2)))
2210 (markdown-wrap-or-insert "<" ">" nil
(car bounds
) (cdr bounds
)))
2211 ;; Markup removal, URI at point, or empty markup insertion
2212 (if (thing-at-point-looking-at markdown-regex-angle-uri
)
2213 (markdown-unwrap-thing-at-point nil
0 2)
2214 (markdown-wrap-or-insert "<" ">" 'url nil nil
))))
2216 (defun markdown-insert-wiki-link ()
2217 "Insert a wiki link of the form [[WikiLink]].
2218 If there is an active region, use the region as the link text.
2219 If the point is at a word, use the word as the link text. If
2220 there is no active region and the point is not at word, simply
2221 insert link markup."
2223 (if (markdown-use-region-p)
2225 (markdown-wrap-or-insert "[[" "]]" nil
(region-beginning) (region-end))
2226 ;; Markup removal, wiki link at at point, or empty markup insertion
2227 (if (thing-at-point-looking-at markdown-regex-wiki-link
)
2228 (if (or markdown-wiki-link-alias-first
2229 (null (match-string 4)))
2230 (markdown-unwrap-thing-at-point nil
1 2)
2231 (markdown-unwrap-thing-at-point nil
1 4))
2232 (markdown-wrap-or-insert "[[" "]]"))))
2234 (defun markdown-insert-image (&optional arg
)
2235 "Insert image markup using region or word as alt text if possible.
2236 If there is an active region, use the region as the alt text. If the
2237 point is at a word, use the word as the alt text. In these cases, the
2238 point will be left at the position for inserting a URL. If there is no
2239 active region and the point is not at word, simply insert image markup and
2240 place the point in the position to enter alt text. If ARG is nil, insert
2241 inline image markup. Otherwise, insert reference image markup."
2243 (let ((bounds (if arg
2244 (markdown-wrap-or-insert "![" "][]")
2245 (markdown-wrap-or-insert "![" "]()"))))
2247 (goto-char (- (cdr bounds
) 1)))))
2249 (defun markdown-insert-reference-image ()
2250 "Insert reference-style image markup using region or word as alt text.
2251 Calls `markdown-insert-image' with prefix argument."
2253 (markdown-insert-image t
))
2255 (defun markdown-remove-header ()
2256 "Remove header markup if point is at a header.
2257 Return bounds of remaining header text if a header was removed
2260 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx
0 2)
2261 (markdown-unwrap-thing-at-point markdown-regex-header-setext
0 1)))
2263 (defun markdown-insert-header (&optional level text setext
)
2264 "Insert or replace header markup.
2265 The level of the header is specified by LEVEL and header text is
2266 given by TEXT. LEVEL must be an integer from 1 and 6, and the
2268 When TEXT is nil, the header text is obtained as follows.
2269 If there is an active region, it is used as the header text.
2270 Otherwise, the current line will be used as the header text.
2271 If there is not an active region and the point is at a header,
2272 remove the header markup and replace with level N header.
2273 Otherwise, insert empty header markup and place the cursor in
2275 The style of the header will be atx (hash marks) unless
2276 SETEXT is non-nil, in which case a setext-style (underlined)
2277 header will be inserted."
2278 (interactive "p\nsHeader text: ")
2279 (setq level
(min (max (or level
1) 1) (if setext
2 6)))
2280 ;; Determine header text if not given
2282 (if (markdown-use-region-p)
2284 (setq text
(delete-and-extract-region (region-beginning) (region-end)))
2286 (markdown-remove-header)
2287 (setq text
(delete-and-extract-region
2288 (line-beginning-position) (line-end-position)))
2289 (when (and setext
(string-match "^[ \t]*$" text
))
2290 (setq text
(read-string "Header text: "))))
2291 (setq text
(markdown-compress-whitespace-string text
)))
2292 ;; Insertion with given text
2293 (markdown-ensure-blank-line-before)
2296 (setq hdr
(make-string (length text
) (if (= level
2) ?- ?
=)))
2297 (insert text
"\n" hdr
))
2299 (setq hdr
(make-string level ?
#))
2300 (insert hdr
" " text
" " hdr
))))
2301 (markdown-ensure-blank-line-after)
2302 ;; Leave point at end of text
2304 (backward-char (1+ (length text
)))
2305 (backward-char (1+ level
))))
2307 (defun markdown-insert-header-dwim (&optional arg setext
)
2308 "Insert or replace header markup.
2309 The level and type of the header are determined automatically by
2310 the type and level of the previous header, unless a prefix
2311 argument is given via ARG.
2312 With a numeric prefix valued 1 to 6, insert a header of the given
2313 level, with the type being determined automatically (note that
2314 only level 1 or 2 setext headers are possible).
2315 With \\[universal-argument], insert a level-one setext header.
2316 With \\[universal-argument] \\[universal-argument], insert a
2317 level two setext header.
2318 When SETEXT is non-nil, prefer setext-style headers when
2319 possible (levels one and two).
2321 When there is an active region, use it for the header text. When
2322 the point is at an existing header, change the type and level
2323 according to the rules above.
2324 Otherwise, if the line is not empty, create a header using the
2325 text on the current line as the header text.
2326 Finally, if the point is on a blank line, insert empty header
2327 markup (atx) or prompt for text (setext).
2328 See `markdown-insert-header' for more details about how the
2329 header text is determined."
2332 (cond ((equal arg
'(4)) ; level-one setext with C-u
2335 ((equal arg
'(16)) ; level-two setext with C-u C-u
2338 (t ; automatic with numeric override
2340 (when (re-search-backward markdown-regex-header nil t
)
2341 ;; level of previous header
2342 (setq level
(markdown-outline-level))
2343 ;; match groups 1 and 2 indicate setext headers
2344 (setq setext
(or setext
(match-end 1) (match-end 3)))))
2345 ;; use prefix if given, or level of previous header
2346 (setq level
(if arg
(prefix-numeric-value arg
) level
))
2347 ;; setext headers must be level one or two
2348 (and level
(setq setext
(and setext
(<= level
2))))))
2349 (markdown-insert-header level nil setext
)))
2351 (defun markdown-insert-header-setext-dwim (&optional arg
)
2352 "Insert or replace header markup, with preference for setext.
2353 See `markdown-insert-header-dwim' for details, including how ARG is handled."
2355 (markdown-insert-header-dwim arg t
))
2357 (defun markdown-insert-header-atx-1 ()
2358 "Insert a first level atx-style (hash mark) header.
2359 See `markdown-insert-header'."
2361 (markdown-insert-header 1 nil nil
))
2363 (defun markdown-insert-header-atx-2 ()
2364 "Insert a level two atx-style (hash mark) header.
2365 See `markdown-insert-header'."
2367 (markdown-insert-header 2 nil nil
))
2369 (defun markdown-insert-header-atx-3 ()
2370 "Insert a level three atx-style (hash mark) header.
2371 See `markdown-insert-header'."
2373 (markdown-insert-header 3 nil nil
))
2375 (defun markdown-insert-header-atx-4 ()
2376 "Insert a level four atx-style (hash mark) header.
2377 See `markdown-insert-header'."
2379 (markdown-insert-header 4 nil nil
))
2381 (defun markdown-insert-header-atx-5 ()
2382 "Insert a level five atx-style (hash mark) header.
2383 See `markdown-insert-header'."
2385 (markdown-insert-header 5 nil nil
))
2387 (defun markdown-insert-header-atx-6 ()
2388 "Insert a sixth level atx-style (hash mark) header.
2389 See `markdown-insert-header'."
2391 (markdown-insert-header 6 nil nil
))
2393 (defun markdown-insert-header-setext-1 ()
2394 "Insert a setext-style (underlined) first-level header.
2395 See `markdown-insert-header'."
2397 (markdown-insert-header 1 nil t
))
2399 (defun markdown-insert-header-setext-2 ()
2400 "Insert a setext-style (underlined) second-level header.
2401 See `markdown-insert-header'."
2403 (markdown-insert-header 2 nil t
))
2405 (defun markdown-blockquote-indentation (loc)
2406 "Return string containing necessary indentation for a blockquote at LOC.
2407 Also see `markdown-pre-indentation'."
2410 (let* ((list-level (length (markdown-calculate-list-levels)))
2412 (dotimes (count list-level indent
)
2413 (setq indent
(concat indent
" "))))))
2415 (defun markdown-insert-blockquote ()
2416 "Start a blockquote section (or blockquote the region).
2417 If Transient Mark mode is on and a region is active, it is used as
2418 the blockquote text."
2420 (if (markdown-use-region-p)
2421 (markdown-blockquote-region (region-beginning) (region-end))
2422 (markdown-ensure-blank-line-before)
2423 (insert (markdown-blockquote-indentation (point)) "> ")
2424 (markdown-ensure-blank-line-after)))
2426 (defun markdown-block-region (beg end prefix
)
2427 "Format the region using a block prefix.
2428 Arguments BEG and END specify the beginning and end of the
2429 region. The characters PREFIX will appear at the beginning
2432 (let* ((end-marker (make-marker))
2433 (beg-marker (make-marker)))
2434 ;; Ensure blank line after and remove extra whitespace
2436 (skip-syntax-backward "-")
2437 (set-marker end-marker
(point))
2438 (delete-horizontal-space)
2439 (markdown-ensure-blank-line-after)
2440 ;; Ensure blank line before and remove extra whitespace
2442 (skip-syntax-forward "-")
2443 (delete-horizontal-space)
2444 (markdown-ensure-blank-line-before)
2445 (set-marker beg-marker
(point))
2446 ;; Insert PREFIX before each line
2447 (goto-char beg-marker
)
2448 (while (and (< (line-beginning-position) end-marker
)
2453 (defun markdown-blockquote-region (beg end
)
2454 "Blockquote the region.
2455 Arguments BEG and END specify the beginning and end of the region."
2457 (markdown-block-region
2458 beg end
(concat (markdown-blockquote-indentation
2459 (max (point-min) (1- beg
))) "> ")))
2461 (defun markdown-pre-indentation (loc)
2462 "Return string containing necessary whitespace for a pre block at LOC.
2463 Also see `markdown-blockquote-indentation'."
2466 (let* ((list-level (length (markdown-calculate-list-levels)))
2468 (dotimes (count (1+ list-level
) indent
)
2469 (setq indent
(concat indent
" "))))))
2471 (defun markdown-insert-pre ()
2472 "Start a preformatted section (or apply to the region).
2473 If Transient Mark mode is on and a region is active, it is marked
2474 as preformatted text."
2476 (if (markdown-use-region-p)
2477 (markdown-pre-region (region-beginning) (region-end))
2478 (markdown-ensure-blank-line-before)
2479 (insert (markdown-pre-indentation (point)))
2480 (markdown-ensure-blank-line-after)))
2482 (defun markdown-pre-region (beg end
)
2483 "Format the region as preformatted text.
2484 Arguments BEG and END specify the beginning and end of the region."
2486 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg
)))))
2487 (markdown-block-region beg end indent
)))
2489 (defun markdown-insert-gfm-code-block (&optional lang
)
2490 "Insert GFM code block for language LANG.
2491 If LANG is nil, the language will be queried from user. If a
2492 region is active, wrap this region with the markup instead. If
2493 the region boundaries are not on empty lines, these are added
2494 automatically in order to have the correct markup."
2495 (interactive "sProgramming language [none]: ")
2496 (if (markdown-use-region-p)
2497 (let ((b (region-beginning)) (e (region-end)))
2499 ;; if we're on a blank line, don't newline, otherwise the ```
2500 ;; should go on its own line
2501 (unless (looking-back "\n")
2504 (markdown-ensure-blank-line-after)
2506 ;; if we're on a blank line, insert the quotes here, otherwise
2507 ;; add a new line first
2508 (unless (looking-at "\n")
2511 (markdown-ensure-blank-line-before)
2512 (insert "```" lang
))
2513 (markdown-ensure-blank-line-before)
2517 (markdown-ensure-blank-line-after)
2521 ;;; Footnotes ======================================================================
2523 (defun markdown-footnote-counter-inc ()
2524 "Increment `markdown-footnote-counter' and return the new value."
2525 (when (= markdown-footnote-counter
0) ; hasn't been updated in this buffer yet.
2527 (goto-char (point-min))
2528 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars
"*?\\)\\]:")
2530 (let ((fn (string-to-number (match-string 1))))
2531 (when (> fn markdown-footnote-counter
)
2532 (setq markdown-footnote-counter fn
))))))
2533 (incf markdown-footnote-counter
))
2535 (defun markdown-insert-footnote ()
2536 "Insert footnote with a new number and move point to footnote definition."
2538 (let ((fn (markdown-footnote-counter-inc)))
2539 (insert (format "[^%d]" fn
))
2540 (markdown-footnote-text-find-new-location)
2541 (markdown-ensure-blank-line-before)
2542 (unless (markdown-cur-line-blank-p)
2544 (insert (format "[^%d]: " fn
))
2545 (markdown-ensure-blank-line-after)))
2547 (defun markdown-footnote-text-find-new-location ()
2548 "Position the cursor at the proper location for a new footnote text."
2550 ((eq markdown-footnote-location
'end
) (goto-char (point-max)))
2551 ((eq markdown-footnote-location
'immediately
) (markdown-end-of-block))
2552 ((eq markdown-footnote-location
'header
) (markdown-end-of-defun))))
2554 (defun markdown-footnote-kill ()
2555 "Kill the footnote at point.
2556 The footnote text is killed (and added to the kill ring), the
2557 footnote marker is deleted. Point has to be either at the
2558 footnote marker or in the footnote text."
2561 (when (markdown-footnote-text-positions) ; if we're in a footnote text
2562 (markdown-footnote-return) ; we first move to the marker
2563 (setq return-pos
'text
)) ; and remember our return position
2564 (let ((marker (markdown-footnote-delete-marker)))
2566 (error "Not at a footnote"))
2567 (let ((text-pos (markdown-footnote-find-text (car marker
))))
2569 (error "No text for footnote `%s'" (car marker
)))
2570 (goto-char text-pos
)
2571 (let ((pos (markdown-footnote-kill-text)))
2573 (if (and pos
(eq return-pos
'text
))
2576 (goto-char return-pos
)))
2578 (defun markdown-footnote-delete-marker ()
2579 "Delete a footnote marker at point.
2580 Returns a list (ID START) containing the footnote ID and the
2581 start position of the marker before deletion. If no footnote
2582 marker was deleted, this function returns NIL."
2583 (let ((marker (markdown-footnote-marker-positions)))
2585 (delete-region (second marker
) (third marker
))
2588 (defun markdown-footnote-kill-text ()
2589 "Kill footnote text at point.
2590 Returns the start position of the footnote text before deletion,
2591 or NIL if point was not inside a footnote text.
2593 The killed text is placed in the kill ring (without the footnote
2595 (let ((fn (markdown-footnote-text-positions)))
2597 (let ((text (delete-and-extract-region (second fn
) (third fn
))))
2598 (string-match (concat "\\[\\" (first fn
) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text
)
2599 (kill-new (match-string 1 text
))
2600 (when (and (markdown-cur-line-blank-p)
2601 (markdown-prev-line-blank-p))
2602 (delete-region (1- (point)) (point)))
2605 (defun markdown-footnote-goto-text ()
2606 "Jump to the text of the footnote at point."
2608 (let ((fn (car (markdown-footnote-marker-positions))))
2610 (error "Not at a footnote marker"))
2611 (let ((new-pos (markdown-footnote-find-text fn
)))
2613 (error "No definition found for footnote `%s'" fn
))
2614 (goto-char new-pos
))))
2616 (defun markdown-footnote-return ()
2617 "Return from a footnote to its footnote number in the main text."
2619 (let ((fn (save-excursion
2620 (car (markdown-footnote-text-positions)))))
2622 (error "Not in a footnote"))
2623 (let ((new-pos (markdown-footnote-find-marker fn
)))
2625 (error "Footnote marker `%s' not found" fn
))
2626 (goto-char new-pos
))))
2628 (defun markdown-footnote-find-marker (id)
2629 "Find the location of the footnote marker with ID.
2630 The actual buffer position returned is the position directly
2631 following the marker's closing bracket. If no marker is found,
2634 (goto-char (point-min))
2635 (when (re-search-forward (concat "\\[" id
"\\]\\([^:]\\|\\'\\)") nil t
)
2636 (skip-chars-backward "^]")
2639 (defun markdown-footnote-find-text (id)
2640 "Find the location of the text of footnote ID.
2641 The actual buffer position returned is the position of the first
2642 character of the text, after the footnote's identifier. If no
2643 footnote text is found, NIL is returned."
2645 (goto-char (point-min))
2646 (when (re-search-forward (concat "^\\[" id
"\\]:") nil t
)
2647 (skip-chars-forward "[ \t]")
2650 (defun markdown-footnote-marker-positions ()
2651 "Return the position and ID of the footnote marker point is on.
2652 The return value is a list (ID START END). If point is not on a
2653 footnote, NIL is returned."
2654 ;; first make sure we're at a footnote marker
2655 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars
"*\\]?") (line-beginning-position))
2656 (looking-at (concat "\\[?\\^" markdown-footnote-chars
"*?\\]")))
2658 ;; move point between [ and ^:
2659 (if (looking-at "\\[")
2661 (skip-chars-backward "^["))
2662 (looking-at (concat "\\(\\^" markdown-footnote-chars
"*?\\)\\]"))
2663 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
2665 (defun markdown-footnote-text-positions ()
2666 "Return the start and end positions of the footnote text point is in.
2667 The exact return value is a list of three elements: (ID START END).
2668 The start position is the position of the opening bracket
2669 of the footnote id. The end position is directly after the
2670 newline that ends the footnote. If point is not in a footnote,
2671 NIL is returned instead."
2674 (backward-paragraph)
2675 ;; if we're in a multiparagraph footnote, we need to back up further
2676 (while (>= (markdown-next-line-indent) 4)
2677 (backward-paragraph))
2679 (if (looking-at (concat "^\\[\\(\\^" markdown-footnote-chars
"*?\\)\\]:"))
2680 (list (match-string 1) (point))))))
2684 (>= (markdown-next-line-indent) 4)))
2685 (append fn
(list (point)))))))
2688 ;;; Element Removal ===========================================================
2690 (defun markdown-kill-thing-at-point ()
2691 "Kill thing at point and add important text, without markup, to kill ring.
2692 Possible things to kill include (roughly in order of precedence):
2693 inline code, headers, horizonal rules, links (add link text to
2694 kill ring), images (add alt text to kill ring), angle uri, email
2695 addresses, bold, italics, reference definition (add URI to kill
2696 ring), footnote markers and text (kill both marker and text, add
2697 text to kill ring), and list items."
2702 ((markdown-code-at-point-p)
2703 (kill-new (match-string 1))
2704 (delete-region (match-beginning 0) (match-end 0)))
2706 ((thing-at-point-looking-at markdown-regex-header-atx
)
2707 (kill-new (match-string 2))
2708 (delete-region (match-beginning 0) (match-end 0)))
2710 ((thing-at-point-looking-at markdown-regex-header-setext
)
2711 (kill-new (match-string 1))
2712 (delete-region (match-beginning 0) (match-end 0)))
2714 ((thing-at-point-looking-at markdown-regex-hr
)
2715 (kill-new (match-string 0))
2716 (delete-region (match-beginning 0) (match-end 0)))
2717 ;; Inline link or image (add link or alt text to kill ring)
2718 ((thing-at-point-looking-at markdown-regex-link-inline
)
2719 (kill-new (match-string 3))
2720 (delete-region (match-beginning 0) (match-end 0)))
2721 ;; Reference link or image (add link or alt text to kill ring)
2722 ((thing-at-point-looking-at markdown-regex-link-reference
)
2723 (kill-new (match-string 3))
2724 (delete-region (match-beginning 0) (match-end 0)))
2725 ;; Angle URI (add URL to kill ring)
2726 ((thing-at-point-looking-at markdown-regex-angle-uri
)
2727 (kill-new (match-string 2))
2728 (delete-region (match-beginning 0) (match-end 0)))
2729 ;; Email address in angle brackets (add email address to kill ring)
2730 ((thing-at-point-looking-at markdown-regex-email
)
2731 (kill-new (match-string 1))
2732 (delete-region (match-beginning 0) (match-end 0)))
2733 ;; Wiki link (add alias text to kill ring)
2734 ((thing-at-point-looking-at markdown-regex-wiki-link
)
2735 (kill-new (markdown-wiki-link-alias))
2736 (delete-region (match-beginning 1) (match-end 1)))
2738 ((thing-at-point-looking-at markdown-regex-bold
)
2739 (kill-new (match-string 4))
2740 (delete-region (match-beginning 2) (match-end 2)))
2742 ((thing-at-point-looking-at markdown-regex-italic
)
2743 (kill-new (match-string 4))
2744 (delete-region (match-beginning 2) (match-end 2)))
2745 ;; Footnote marker (add footnote text to kill ring)
2746 ((thing-at-point-looking-at markdown-regex-footnote
)
2747 (markdown-footnote-kill))
2748 ;; Footnote text (add footnote text to kill ring)
2749 ((setq val
(markdown-footnote-text-positions))
2750 (markdown-footnote-kill))
2751 ;; Reference definition (add URL to kill ring)
2752 ((thing-at-point-looking-at markdown-regex-reference-definition
)
2753 (kill-new (match-string 2))
2754 (delete-region (match-beginning 0) (match-end 0)))
2756 ((setq val
(markdown-cur-list-item-bounds))
2757 (kill-new (delete-and-extract-region (first val
) (second val
))))
2759 (error "Nothing found at point to kill")))))
2762 ;;; Indentation ====================================================================
2764 (defun markdown-indent-find-next-position (cur-pos positions
)
2765 "Return the position after the index of CUR-POS in POSITIONS.
2766 Positions are calculated by `markdown-calc-indents'."
2767 (while (and positions
2768 (not (equal cur-pos
(car positions
))))
2769 (setq positions
(cdr positions
)))
2770 (or (cadr positions
) 0))
2772 (defun markdown-exdent-find-next-position (cur-pos positions
)
2773 "Return the maximal element that precedes CUR-POS from POSITIONS.
2774 Positions are calculated by `markdown-calc-indents'."
2776 (dolist (i positions
)
2778 (setq result
(max result i
))))
2781 (defun markdown-indent-line ()
2782 "Indent the current line using some heuristics.
2783 If the _previous_ command was either `markdown-enter-key' or
2784 `markdown-cycle', then we should cycle to the next
2785 reasonable indentation position. Otherwise, we could have been
2786 called directly by `markdown-enter-key', by an initial call of
2787 `markdown-cycle', or indirectly by `auto-fill-mode'. In
2788 these cases, indent to the default position.
2789 Positions are calculated by `markdown-calc-indents'."
2791 (let ((positions (markdown-calc-indents))
2792 (cur-pos (current-column)))
2793 (if (not (equal this-command
'markdown-cycle
))
2794 (indent-line-to (car positions
))
2795 (setq positions
(sort (delete-dups positions
) '<))
2797 (markdown-indent-find-next-position cur-pos positions
)))))
2799 (defun markdown-calc-indents ()
2800 "Return a list of indentation columns to cycle through.
2801 The first element in the returned list should be considered the
2802 default indentation level. This function does not worry about
2803 duplicate positions, which are handled up by calling functions."
2804 (let (pos prev-line-pos positions
)
2806 ;; Indentation of previous line
2807 (setq prev-line-pos
(markdown-prev-line-indent))
2808 (setq positions
(cons prev-line-pos positions
))
2810 ;; Indentation of previous non-list-marker text
2811 (when (setq pos
(markdown-prev-non-list-indent))
2812 (setq positions
(cons pos positions
)))
2814 ;; Indentation required for a pre block in current context
2815 (setq pos
(length (markdown-pre-indentation (point))))
2816 (setq positions
(cons pos positions
))
2818 ;; Indentation of the previous line + tab-width
2820 (setq positions
(cons (+ prev-line-pos tab-width
) positions
))
2821 (setq positions
(cons tab-width positions
)))
2823 ;; Indentation of the previous line - tab-width
2824 (if (and prev-line-pos
(> prev-line-pos tab-width
))
2825 (setq positions
(cons (- prev-line-pos tab-width
) positions
)))
2827 ;; Indentation of all preceeding list markers (when in a list)
2828 (when (setq pos
(markdown-calculate-list-levels))
2829 (setq positions
(append pos positions
)))
2832 (setq positions
(cons 0 positions
))
2834 ;; Return reversed list
2835 (reverse positions
)))
2837 (defun markdown-enter-key ()
2838 "Handle RET according to to the value of `markdown-indent-on-enter'."
2840 (if markdown-indent-on-enter
2841 (newline-and-indent)
2844 (defun markdown-exdent-or-delete (arg)
2845 "Handle BACKSPACE by cycling through indentation points.
2846 When BACKSPACE is pressed, if there is only whitespace
2847 before the current point, then exdent the line one level.
2848 Otherwise, do normal delete by repeating
2849 `backward-delete-char-untabify' ARG times."
2851 (let ((cur-pos (current-column))
2852 (start-of-indention (save-excursion
2853 (back-to-indentation)
2855 (positions (markdown-calc-indents)))
2856 (if (and (> cur-pos
0) (= cur-pos start-of-indention
))
2857 (indent-line-to (markdown-exdent-find-next-position cur-pos positions
))
2858 (backward-delete-char-untabify arg
))))
2860 (defun markdown-find-leftmost-column (beg end
)
2861 "Find the leftmost column in the region from BEG to END."
2862 (let ((mincol 1000))
2865 (while (< (point) end
)
2866 (back-to-indentation)
2867 (unless (looking-at "[ \t]*$")
2868 (setq mincol
(min mincol
(current-column))))
2873 (defun markdown-indent-region (beg end arg
)
2874 "Indent the region from BEG to END using some heuristics.
2875 When ARG is non-nil, exdent the region instead.
2876 See `markdown-indent-line' and `markdown-indent-line'."
2877 (interactive "*r\nP")
2878 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
2879 (leftmostcol (markdown-find-leftmost-column beg end
))
2881 (markdown-exdent-find-next-position leftmostcol positions
)
2882 (markdown-indent-find-next-position leftmostcol positions
))))
2883 (indent-rigidly beg end
(- next-pos leftmostcol
))
2884 (setq deactivate-mark nil
)))
2886 (defun markdown-exdent-region (beg end
)
2887 "Call `markdown-indent-region' on region from BEG to END with prefix."
2889 (markdown-indent-region (region-beginning) (region-end) t
))
2892 ;;; Markup Completion =========================================================
2894 (defconst markdown-complete-alist
2895 '((markdown-regex-header-atx . markdown-complete-atx
)
2896 (markdown-regex-header-setext . markdown-complete-setext
)
2897 (markdown-regex-hr . markdown-complete-hr
))
2898 "Association list of form (regexp . function) for markup completion.")
2900 (defun markdown-incomplete-atx-p ()
2901 "Return t if ATX header markup is incomplete and nil otherwise.
2902 Assumes match data is available for `markdown-regex-header-atx'.
2903 Checks that the number of trailing hash marks equals the number of leading
2904 hash marks, that there is only a single space before and after the text,
2905 and that there is no extraneous whitespace in the text."
2908 ;; Number of starting and ending hash marks differs
2909 (not (= (length (match-string 1)) (length (match-string 3))))
2910 ;; When the header text is not empty...
2911 (and (> (length (match-string 2)) 0)
2912 ;; ...if there are extra leading, trailing, or interior spaces
2913 (or (not (= (match-beginning 2) (1+ (match-end 1))))
2914 (not (= (match-beginning 3) (1+ (match-end 2))))
2915 (string-match "[ \t\n]\\{2\\}" (match-string 2))))
2916 ;; When the header text is empty...
2917 (and (= (length (match-string 2)) 0)
2918 ;; ...if there are too many or too few spaces
2919 (not (= (match-beginning 3) (+ (match-end 1) 2)))))))
2921 (defun markdown-complete-atx ()
2922 "Complete and normalize ATX headers.
2923 Add or remove hash marks to the end of the header to match the
2924 beginning. Ensure that there is only a single space between hash
2925 marks and header text. Removes extraneous whitespace from header text.
2926 Assumes match data is available for `markdown-regex-header-atx'.
2927 Return nil if markup was complete and non-nil if markup was completed."
2928 (when (markdown-incomplete-atx-p)
2929 (let* ((new-marker (make-marker))
2930 (new-marker (set-marker new-marker
(match-end 2))))
2931 ;; Hash marks and spacing at end
2932 (goto-char (match-end 2))
2933 (delete-region (match-end 2) (match-end 3))
2934 (insert " " (match-string 1))
2935 ;; Remove extraneous whitespace from title
2936 (replace-match (markdown-compress-whitespace-string (match-string 2))
2938 ;; Spacing at beginning
2939 (goto-char (match-end 1))
2940 (delete-region (match-end 1) (match-beginning 2))
2942 ;; Leave point at end of text
2943 (goto-char new-marker
))))
2945 (defun markdown-incomplete-setext-p ()
2946 "Return t if setext header markup is incomplete and nil otherwise.
2947 Assumes match data is available for `markdown-regex-header-setext'.
2948 Checks that length of underline matches text and that there is no
2949 extraneous whitespace in the text."
2951 (or (not (= (length (match-string 1)) (length (match-string 2))))
2952 (string-match "[ \t\n]\\{2\\}" (match-string 1)))))
2954 (defun markdown-complete-setext ()
2955 "Complete and normalize setext headers.
2956 Add or remove underline characters to match length of header
2957 text. Removes extraneous whitespace from header text. Assumes
2958 match data is available for `markdown-regex-header-setext'.
2959 Return nil if markup was complete and non-nil if markup was completed."
2960 (when (markdown-incomplete-setext-p)
2961 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
2962 (char (char-after (match-beginning 2)))
2963 (level (if (char-equal char ?-
) 2 1)))
2964 (goto-char (match-beginning 0))
2965 (delete-region (match-beginning 0) (match-end 0))
2966 (markdown-insert-header level text t
)
2969 (defun markdown-incomplete-hr-p ()
2970 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
2971 Assumes match data is available for `markdown-regex-hr'."
2972 (not (member (match-string 0) markdown-hr-strings
)))
2974 (defun markdown-complete-hr ()
2975 "Complete horizontal rules.
2976 If horizontal rule string is a member of `markdown-hr-strings',
2977 do nothing. Otherwise, replace with the car of
2978 `markdown-hr-strings'.
2979 Assumes match data is available for `markdown-regex-hr'.
2980 Return nil if markup was complete and non-nil if markup was completed."
2981 (when (markdown-incomplete-hr-p)
2982 (replace-match (car markdown-hr-strings
))
2985 (defun markdown-complete ()
2986 "Complete markup of object near point or in region when active.
2987 Handle all objects in `markdown-complete-alist', in order.
2988 See `markdown-complete-at-point' and `markdown-complete-region'."
2990 (if (markdown-use-region-p)
2991 (markdown-complete-region (region-beginning) (region-end))
2992 (markdown-complete-at-point)))
2994 (defun markdown-complete-at-point ()
2995 "Complete markup of object near point.
2996 Handle all elements of `markdown-complete-alist' in order."
2998 (let ((list markdown-complete-alist
) found changed
)
3000 (let ((regexp (eval (caar list
)))
3001 (function (cdar list
)))
3002 (setq list
(cdr list
))
3003 (when (thing-at-point-looking-at regexp
)
3005 (setq changed
(funcall function
))
3008 (or changed
(error "Markup at point is complete"))
3009 (error "Nothing to complete at point"))))
3011 (defun markdown-complete-region (beg end
)
3012 "Complete markup of objects in region from BEG to END.
3013 Handle all objects in `markdown-complete-alist', in
3016 (let ((end-marker (set-marker (make-marker) end
)))
3017 (dolist (element markdown-complete-alist
)
3018 (let ((regexp (eval (car element
)))
3019 (function (cdr element
)))
3021 (while (re-search-forward regexp end-marker
'limit
)
3022 (save-excursion (funcall function
)))))))
3024 (defun markdown-complete-buffer ()
3025 "Complete markup for all objects in the current buffer."
3027 (markdown-complete-region (point-min) (point-max)))
3030 ;;; Markup Cycling ============================================================
3032 (defun markdown-cycle-atx (arg &optional remove
)
3033 "Cycle ATX header markup.
3034 Promote header (decrease level) when ARG is 1 and demote
3035 header (increase level) if arg is -1. When REMOVE is non-nil,
3036 remove the header when the level reaches zero and stop cycling
3037 when it reaches six. Otherwise, perform a proper cycling through
3038 levels one through six. Assumes match data is available for
3039 `markdown-regex-header-atx'."
3040 (let* ((old-level (length (match-string 1)))
3041 (new-level (+ old-level arg
))
3042 (text (match-string 2)))
3044 (setq new-level
(% new-level
6))
3045 (setq new-level
(cond ((= new-level
0) 6)
3046 ((< new-level
0) (+ new-level
6))
3050 (markdown-unwrap-thing-at-point nil
0 2))
3052 (goto-char (match-beginning 0))
3053 (delete-region (match-beginning 0) (match-end 0))
3054 (markdown-insert-header new-level text nil
)))))
3056 (defun markdown-cycle-setext (arg &optional remove
)
3057 "Cycle setext header markup.
3058 Promote header (increase level) when ARG is 1 and demote
3059 header (decrease level or remove) if arg is -1. When demoting a
3060 level-two setext header, replace with a level-three atx header.
3061 When REMOVE is non-nil, remove the header when the level reaches
3062 zero. Otherwise, cycle back to a level six atx header. Assumes
3063 match data is available for `markdown-regex-header-setext'."
3064 (let* ((char (char-after (match-beginning 2)))
3065 (old-level (if (char-equal char ?
=) 1 2))
3066 (new-level (+ old-level arg
))
3067 (text (match-string 1)))
3068 (when (and (not remove
) (= new-level
0))
3072 (markdown-unwrap-thing-at-point nil
0 1))
3074 (markdown-insert-header new-level nil t
))
3076 (markdown-insert-header new-level nil nil
)))))
3078 (defun markdown-cycle-hr (arg &optional remove
)
3079 "Cycle string used for horizontal rule from `markdown-hr-strings'.
3080 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
3081 backwards (promote). When REMOVE is non-nil, remove the hr instead
3082 of cycling when the end of the list is reached.
3083 Assumes match data is available for `markdown-regex-hr'."
3084 (let* ((strings (if (= arg -
1)
3085 (reverse markdown-hr-strings
)
3086 markdown-hr-strings
))
3087 (tail (member (match-string 0) strings
))
3088 (new (or (cadr tail
)
3094 (replace-match new
)))
3096 (defun markdown-cycle-bold ()
3097 "Cycle bold markup between underscores and asterisks.
3098 Assumes match data is available for `markdown-regex-bold'."
3100 (let* ((old-delim (match-string 3))
3101 (new-delim (if (string-equal old-delim
"**") "__" "**")))
3102 (replace-match new-delim t t nil
3)
3103 (replace-match new-delim t t nil
5))))
3105 (defun markdown-cycle-italic ()
3106 "Cycle italic markup between underscores and asterisks.
3107 Assumes match data is available for `markdown-regex-italic'."
3109 (let* ((old-delim (match-string 3))
3110 (new-delim (if (string-equal old-delim
"*") "_" "*")))
3111 (replace-match new-delim t t nil
3)
3112 (replace-match new-delim t t nil
5))))
3115 ;;; Keymap ====================================================================
3117 (defvar markdown-mode-map
3118 (let ((map (make-keymap)))
3119 ;; Element insertion
3120 (define-key map
"\C-c\C-al" 'markdown-insert-link
)
3121 (define-key map
"\C-c\C-aL" 'markdown-insert-reference-link-dwim
)
3122 (define-key map
"\C-c\C-au" 'markdown-insert-uri
)
3123 (define-key map
"\C-c\C-af" 'markdown-insert-footnote
)
3124 (define-key map
"\C-c\C-aw" 'markdown-insert-wiki-link
)
3125 (define-key map
"\C-c\C-ii" 'markdown-insert-image
)
3126 (define-key map
"\C-c\C-iI" 'markdown-insert-reference-image
)
3127 (define-key map
"\C-c\C-th" 'markdown-insert-header-dwim
)
3128 (define-key map
"\C-c\C-tH" 'markdown-insert-header-setext-dwim
)
3129 (define-key map
"\C-c\C-t1" 'markdown-insert-header-atx-1
)
3130 (define-key map
"\C-c\C-t2" 'markdown-insert-header-atx-2
)
3131 (define-key map
"\C-c\C-t3" 'markdown-insert-header-atx-3
)
3132 (define-key map
"\C-c\C-t4" 'markdown-insert-header-atx-4
)
3133 (define-key map
"\C-c\C-t5" 'markdown-insert-header-atx-5
)
3134 (define-key map
"\C-c\C-t6" 'markdown-insert-header-atx-6
)
3135 (define-key map
"\C-c\C-t!" 'markdown-insert-header-setext-1
)
3136 (define-key map
"\C-c\C-t@" 'markdown-insert-header-setext-2
)
3137 (define-key map
"\C-c\C-ss" 'markdown-insert-bold
)
3138 (define-key map
"\C-c\C-se" 'markdown-insert-italic
)
3139 (define-key map
"\C-c\C-sc" 'markdown-insert-code
)
3140 (define-key map
"\C-c\C-sb" 'markdown-insert-blockquote
)
3141 (define-key map
"\C-c\C-s\C-b" 'markdown-blockquote-region
)
3142 (define-key map
"\C-c\C-sp" 'markdown-insert-pre
)
3143 (define-key map
"\C-c\C-s\C-p" 'markdown-pre-region
)
3144 (define-key map
"\C-c-" 'markdown-insert-hr
)
3145 ;; Element insertion (deprecated)
3146 (define-key map
"\C-c\C-ar" 'markdown-insert-reference-link-dwim
)
3147 (define-key map
"\C-c\C-tt" 'markdown-insert-header-setext-1
)
3148 (define-key map
"\C-c\C-ts" 'markdown-insert-header-setext-2
)
3150 (define-key map
(kbd "C-c C-k") 'markdown-kill-thing-at-point
)
3151 ;; Promotion, Demotion, Completion, and Cycling
3152 (define-key map
(kbd "C-c C--") 'markdown-promote
)
3153 (define-key map
(kbd "C-c C-=") 'markdown-demote
)
3154 (define-key map
(kbd "C-c C-]") 'markdown-complete
)
3155 ;; Following and Jumping
3156 (define-key map
(kbd "C-c C-o") 'markdown-follow-thing-at-point
)
3157 (define-key map
(kbd "C-c C-j") 'markdown-jump
)
3159 (define-key map
(kbd "C-m") 'markdown-enter-key
)
3160 (define-key map
(kbd "<backspace>") 'markdown-exdent-or-delete
)
3161 (define-key map
(kbd "C-c >") 'markdown-indent-region
)
3162 (define-key map
(kbd "C-c <") 'markdown-exdent-region
)
3163 ;; Visibility cycling
3164 (define-key map
(kbd "<tab>") 'markdown-cycle
)
3165 (define-key map
(kbd "<S-iso-lefttab>") 'markdown-shifttab
)
3166 (define-key map
(kbd "<S-tab>") 'markdown-shifttab
)
3167 (define-key map
(kbd "<backtab>") 'markdown-shifttab
)
3168 ;; Header navigation
3169 (define-key map
(kbd "C-c C-n") 'outline-next-visible-heading
)
3170 (define-key map
(kbd "C-c C-p") 'outline-previous-visible-heading
)
3171 (define-key map
(kbd "C-c C-f") 'outline-forward-same-level
)
3172 (define-key map
(kbd "C-c C-b") 'outline-backward-same-level
)
3173 (define-key map
(kbd "C-c C-u") 'outline-up-heading
)
3174 ;; Buffer-wide commands
3175 (define-key map
(kbd "C-c C-c m") 'markdown-other-window
)
3176 (define-key map
(kbd "C-c C-c p") 'markdown-preview
)
3177 (define-key map
(kbd "C-c C-c e") 'markdown-export
)
3178 (define-key map
(kbd "C-c C-c v") 'markdown-export-and-preview
)
3179 (define-key map
(kbd "C-c C-c o") 'markdown-open
)
3180 (define-key map
(kbd "C-c C-c w") 'markdown-kill-ring-save
)
3181 (define-key map
(kbd "C-c C-c c") 'markdown-check-refs
)
3182 (define-key map
(kbd "C-c C-c n") 'markdown-cleanup-list-numbers
)
3183 (define-key map
(kbd "C-c C-c ]") 'markdown-complete-buffer
)
3185 (define-key map
(kbd "M-<up>") 'markdown-move-up
)
3186 (define-key map
(kbd "M-<down>") 'markdown-move-down
)
3187 (define-key map
(kbd "M-<left>") 'markdown-promote
)
3188 (define-key map
(kbd "M-<right>") 'markdown-demote
)
3189 (define-key map
(kbd "M-<return>") 'markdown-insert-list-item
)
3191 (define-key map
(kbd "M-{") 'markdown-backward-paragraph
)
3192 (define-key map
(kbd "M-}") 'markdown-forward-paragraph
)
3193 (define-key map
(kbd "M-n") 'markdown-next-link
)
3194 (define-key map
(kbd "M-p") 'markdown-previous-link
)
3195 ;; Alternative keys (in case of problems with the arrow keys)
3196 (define-key map
(kbd "C-c C-x u") 'markdown-move-up
)
3197 (define-key map
(kbd "C-c C-x d") 'markdown-move-down
)
3198 (define-key map
(kbd "C-c C-x l") 'markdown-promote
)
3199 (define-key map
(kbd "C-c C-x r") 'markdown-demote
)
3200 (define-key map
(kbd "C-c C-x m") 'markdown-insert-list-item
)
3202 "Keymap for Markdown major mode.")
3204 (defvar gfm-mode-map
3205 (let ((map (make-sparse-keymap)))
3206 (set-keymap-parent map markdown-mode-map
)
3207 (define-key map
(kbd "C-c C-s P") 'markdown-insert-gfm-code-block
)
3209 "Keymap for `gfm-mode'.
3210 See also `markdown-mode-map'.")
3213 ;;; Menu ==================================================================
3215 (easy-menu-define markdown-mode-menu markdown-mode-map
3216 "Menu for Markdown mode"
3219 ["Cycle visibility" markdown-cycle
(outline-on-heading-p)]
3220 ["Cycle global visibility" markdown-shifttab
])
3222 ["Compile" markdown-other-window
]
3223 ["Preview" markdown-preview
]
3224 ["Export" markdown-export
]
3225 ["Export & View" markdown-export-and-preview
]
3226 ["Open" markdown-open
]
3227 ["Kill ring save" markdown-kill-ring-save
]
3230 ["Automatic" markdown-insert-header-dwim
]
3231 ["Automatic (prefer setext)" markdown-insert-header-setext-dwim
]
3233 ["First level setext" markdown-insert-header-setext-1
]
3234 ["Second level setext" markdown-insert-header-setext-2
]
3236 ["First level atx" markdown-insert-header-atx-1
]
3237 ["Second level atx" markdown-insert-header-atx-2
]
3238 ["Third level atx" markdown-insert-header-atx-3
]
3239 ["Fourth level atx" markdown-insert-header-atx-4
]
3240 ["Fifth level atx" markdown-insert-header-atx-5
]
3241 ["Sixth level atx" markdown-insert-header-atx-6
])
3243 ["Bold" markdown-insert-bold
]
3244 ["Italic" markdown-insert-italic
]
3245 ["Blockquote" markdown-insert-blockquote
]
3246 ["Preformatted" markdown-insert-pre
]
3247 ["Code" markdown-insert-code
]
3249 ["Insert inline link" markdown-insert-link
]
3250 ["Insert reference link" markdown-insert-reference-link-dwim
]
3251 ["Insert URL" markdown-insert-uri
]
3252 ["Insert inline image" markdown-insert-image
]
3253 ["Insert reference image" markdown-insert-reference-image
]
3254 ["Insert list item" markdown-insert-list-item
]
3255 ["Insert horizontal rule" markdown-insert-hr
]
3256 ["Insert footnote" markdown-insert-footnote
]
3257 ["Kill element" markdown-kill-thing-at-point
]
3259 ["Jump" markdown-jump
]
3260 ["Follow link" markdown-follow-thing-at-point
]
3262 ["Next visible heading" outline-next-visible-heading
]
3263 ["Previous visible heading" outline-previous-visible-heading
]
3264 ["Forward same level" outline-forward-same-level
]
3265 ["Backward same level" outline-backward-same-level
]
3266 ["Up to parent heading" outline-up-heading
])
3268 ("Completion and Cycling"
3269 ["Complete" markdown-complete
]
3270 ["Promote" markdown-promote
]
3271 ["Demote" markdown-demote
])
3273 ["Indent list item" markdown-demote
]
3274 ["Exdent list item" markdown-promote
])
3276 ["Indent region" markdown-indent-region
]
3277 ["Exdent region" markdown-exdent-region
])
3279 ["Check references" markdown-check-refs
]
3280 ["Clean up list numbering" markdown-cleanup-list-numbers
]
3281 ["Complete markup" markdown-complete-buffer
]
3283 ["Version" markdown-show-version
]
3287 ;;; imenu =====================================================================
3289 (defun markdown-imenu-create-index ()
3290 "Create and return an imenu index alist for the current buffer.
3291 See `imenu-create-index-function' and `imenu--index-alist' for details."
3292 (let* ((root '(nil . nil
))
3297 hashes pos level heading
)
3299 (goto-char (point-min))
3300 (while (re-search-forward markdown-regex-header
(point-max) t
)
3302 ((setq heading
(match-string-no-properties 1))
3303 (setq pos
(match-beginning 1)
3305 ((setq heading
(match-string-no-properties 3))
3306 (setq pos
(match-beginning 3)
3308 ((setq hashes
(match-string-no-properties 5))
3309 (setq heading
(match-string-no-properties 6)
3310 pos
(match-beginning 5)
3311 level
(length hashes
))))
3312 (let ((alist (list (cons heading pos
))))
3314 ((= cur-level level
) ; new sibling
3315 (setcdr cur-alist alist
)
3316 (setq cur-alist alist
))
3317 ((< cur-level level
) ; first child
3318 (dotimes (i (- level cur-level
1))
3319 (setq alist
(list (cons empty-heading alist
))))
3321 (let* ((parent (car cur-alist
))
3322 (self-pos (cdr parent
)))
3323 (setcdr parent
(cons (cons self-heading self-pos
) alist
)))
3324 (setcdr root alist
)) ; primogenitor
3325 (setq cur-alist alist
)
3326 (setq cur-level level
))
3327 (t ; new sibling of an ancestor
3328 (let ((sibling-alist (last (cdr root
))))
3329 (dotimes (i (1- level
))
3330 (setq sibling-alist
(last (cdar sibling-alist
))))
3331 (setcdr sibling-alist alist
)
3332 (setq cur-alist alist
))
3333 (setq cur-level level
)))))
3337 ;;; References ================================================================
3339 (defun markdown-insert-reference-definition (ref &optional buffer
)
3340 "Add blank REF definition to the end of BUFFER.
3341 REF is a Markdown reference in square brackets, like \"[lisp-history]\"."
3342 (or buffer
(setq buffer
(current-buffer)))
3343 (with-current-buffer buffer
3344 (goto-char (point-max))
3345 (indent-new-comment-line)
3346 (insert (concat ref
": "))))
3348 (defun markdown-reference-goto-definition ()
3349 "Jump to the definition of the reference at point or create it."
3351 (when (thing-at-point-looking-at markdown-regex-link-reference
)
3352 (let* ((text (match-string-no-properties 2))
3353 (reference (match-string-no-properties 4))
3354 (target (downcase (if (string= reference
"[]") text reference
)))
3355 (loc (cadr (markdown-reference-definition target
))))
3358 (markdown-insert-reference-definition target
(current-buffer))))))
3360 (defun markdown-reference-find-links (reference)
3361 "Return a list of all links for REFERENCE.
3362 REFERENCE should include the surrounding square brackets like [this].
3363 Elements of the list have the form (text start line), where
3364 text is the link text, start is the location at the beginning of
3365 the link, and line is the line number on which the link appears."
3366 (let* ((ref-quote (regexp-quote (substring reference
1 -
1)))
3367 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
3368 ref-quote ref-quote
))
3371 (goto-char (point-min))
3372 (while (re-search-forward regexp nil t
)
3373 (let* ((text (or (match-string-no-properties 1)
3374 (match-string-no-properties 2)))
3375 (start (match-beginning 0))
3376 (line (markdown-line-number-at-pos)))
3377 (add-to-list 'links
(list text start line
)))))
3380 (defun markdown-get-undefined-refs ()
3381 "Return a list of undefined Markdown references.
3382 Result is an alist of pairs (reference . occurrences), where
3383 occurrences is itself another alist of pairs (label . line-number).
3384 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
3385 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
3386 \((\"[emacs]\" (\"[Nice editor]\" . 12) (\"[GNU Emacs]\" . 45)) (\"[elisp]\" (\"[manual]\" . 127)))."
3389 (goto-char (point-min))
3391 (re-search-forward markdown-regex-link-reference nil t
)
3392 (let* ((text (match-string-no-properties 2))
3393 (reference (match-string-no-properties 4))
3394 (target (downcase (if (string= reference
"[]") text reference
))))
3395 (unless (markdown-reference-definition target
)
3396 (let ((entry (assoc target missing
)))
3398 (add-to-list 'missing
(cons target
3399 (list (cons text
(markdown-line-number-at-pos)))) t
)
3401 (append (cdr entry
) (list (cons text
(markdown-line-number-at-pos))))))))))
3404 (defconst markdown-reference-check-buffer
3405 "*Undefined references for %buffer%*"
3406 "Pattern for name of buffer for listing undefined references.
3407 The string %buffer% will be replaced by the corresponding
3408 `markdown-mode' buffer name.")
3410 (defun markdown-reference-check-buffer (&optional buffer-name
)
3411 "Name and return buffer for reference checking.
3412 BUFFER-NAME is the name of the main buffer being visited."
3413 (or buffer-name
(setq buffer-name
(buffer-name)))
3414 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
3415 "%buffer%" buffer-name
3416 markdown-reference-check-buffer
))))
3417 (with-current-buffer refbuf
3419 (View-exit-and-edit))
3420 (use-local-map button-buffer-map
)
3424 (defconst markdown-reference-links-buffer
3425 "*Reference links for %buffer%*"
3426 "Pattern for name of buffer for listing references.
3427 The string %buffer% will be replaced by the corresponding buffer name.")
3429 (defun markdown-reference-links-buffer (&optional buffer-name
)
3430 "Name, setup, and return a buffer for listing links.
3431 BUFFER-NAME is the name of the main buffer being visited."
3432 (or buffer-name
(setq buffer-name
(buffer-name)))
3433 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
3434 "%buffer%" buffer-name
3435 markdown-reference-links-buffer
))))
3436 (with-current-buffer linkbuf
3438 (View-exit-and-edit))
3439 (use-local-map button-buffer-map
)
3443 (when (markdown-use-buttons-p)
3444 ;; Add an empty Markdown reference definition to the end of buffer
3445 ;; specified in the 'target-buffer property. The reference name is
3446 ;; the button's label.
3447 (define-button-type 'markdown-undefined-reference-button
3448 'help-echo
"mouse-1, RET: create definition for undefined reference"
3452 (let ((buffer (button-get b
'target-buffer
)))
3453 (markdown-insert-reference-definition (button-label b
) buffer
)
3454 (switch-to-buffer-other-window buffer
)
3455 (goto-char (point-max))
3456 (markdown-check-refs t
))))
3458 ;; Jump to line in buffer specified by 'target-buffer property.
3459 ;; Line number is button's 'line property.
3460 (define-button-type 'markdown-goto-line-button
3461 'help-echo
"mouse-1, RET: go to line"
3465 (message (button-get b
'buffer
))
3466 (switch-to-buffer-other-window (button-get b
'target-buffer
))
3467 ;; use call-interactively to silence compiler
3468 (let ((current-prefix-arg (button-get b
'target-line
)))
3469 (call-interactively 'goto-line
))))
3471 ;; Jumps to a particular link at location given by 'target-char
3472 ;; property in buffer given by 'target-buffer property.
3473 (define-button-type 'markdown-link-button
3474 'help-echo
"mouse-1, RET: jump to location of link"
3478 (let ((target (button-get b
'target-buffer
))
3479 (loc (button-get b
'target-char
)))
3480 (kill-buffer-and-window)
3481 (switch-to-buffer target
)
3484 (defun markdown-insert-undefined-reference-button (reference oldbuf
)
3485 "Insert a button for creating REFERENCE in buffer OLDBUF.
3486 REFERENCE should be a list of the form (reference . occurrences),
3487 as by `markdown-get-undefined-refs'."
3488 (let ((label (car reference
)))
3489 (if (markdown-use-buttons-p)
3490 ;; Create a reference button in Emacs 22
3491 (insert-button label
3492 :type
'markdown-undefined-reference-button
3493 'target-buffer oldbuf
)
3494 ;; Insert reference as text in Emacs < 22
3497 (dolist (occurrence (cdr reference
))
3498 (let ((line (cdr occurrence
)))
3499 (if (markdown-use-buttons-p)
3500 ;; Create a line number button in Emacs 22
3501 (insert-button (number-to-string line
)
3502 :type
'markdown-goto-line-button
3503 'target-buffer oldbuf
3505 ;; Insert line number as text in Emacs < 22
3506 (insert (number-to-string line
)))
3512 (defun markdown-insert-link-button (link oldbuf
)
3513 "Insert a button for jumping to LINK in buffer OLDBUF.
3514 LINK should be a list of the form (text char line) containing
3515 the link text, location, and line number."
3516 (let ((label (first link
))
3517 (char (second link
))
3518 (line (third link
)))
3519 (if (markdown-use-buttons-p)
3520 ;; Create a reference button in Emacs 22
3521 (insert-button label
3522 :type
'markdown-link-button
3523 'target-buffer oldbuf
3525 ;; Insert reference as text in Emacs < 22
3527 (insert (format " (line %d)\n" line
))))
3529 (defun markdown-reference-goto-link (&optional reference
)
3530 "Jump to the location of the first use of REFERENCE."
3533 (if (thing-at-point-looking-at markdown-regex-reference-definition
)
3534 (setq reference
(match-string-no-properties 1))
3535 (error "No reference definition at point")))
3536 (let ((links (markdown-reference-find-links reference
)))
3537 (cond ((= (length links
) 1)
3538 (goto-char (cadr (car links
))))
3539 ((> (length links
) 1)
3540 (let ((oldbuf (current-buffer))
3541 (linkbuf (markdown-reference-links-buffer)))
3542 (with-current-buffer linkbuf
3543 (insert "Links using reference " reference
":\n\n")
3544 (dolist (link (reverse links
))
3545 (markdown-insert-link-button link oldbuf
)))
3546 (view-buffer-other-window linkbuf
)
3547 (goto-char (point-min))
3550 (error "No links for reference %s" reference
)))))
3552 (defun markdown-check-refs (&optional silent
)
3553 "Show all undefined Markdown references in current `markdown-mode' buffer.
3554 If SILENT is non-nil, do not message anything when no undefined
3556 Links which have empty reference definitions are considered to be
3559 (when (not (eq major-mode
'markdown-mode
))
3560 (error "Not available in current mode"))
3561 (let ((oldbuf (current-buffer))
3562 (refs (markdown-get-undefined-refs))
3563 (refbuf (markdown-reference-check-buffer)))
3567 (message "No undefined references found"))
3568 (kill-buffer refbuf
))
3569 (with-current-buffer refbuf
3570 (insert "The following references are undefined:\n\n")
3572 (markdown-insert-undefined-reference-button ref oldbuf
))
3573 (view-buffer-other-window refbuf
)
3574 (goto-char (point-min))
3575 (forward-line 2)))))
3578 ;;; Lists =====================================================================
3580 (defun markdown-insert-list-item (&optional arg
)
3581 "Insert a new list item.
3582 If the point is inside unordered list, insert a bullet mark. If
3583 the point is inside ordered list, insert the next number followed
3584 by a period. Use the previous list item to determine the amount
3585 of whitespace to place before and after list markers.
3587 With a \\[universal-argument] prefix (i.e., when ARG is 4),
3588 decrease the indentation by one level.
3590 With two \\[universal-argument] prefixes (i.e., when ARG is 16),
3591 increase the indentation by one level."
3593 (let (bounds item-indent marker indent new-indent new-loc
)
3595 ;; Look for a list item on current or previous non-blank line
3597 (while (and (not (setq bounds
(markdown-cur-list-item-bounds)))
3599 (markdown-cur-line-blank-p))
3602 (cond ((save-excursion
3603 (skip-chars-backward " \t")
3604 (looking-at markdown-regex-list
))
3608 ((not (markdown-cur-line-blank-p))
3610 (setq new-loc
(point)))
3611 ;; Look ahead for a list item on next non-blank line
3614 (while (and (null bounds
)
3616 (markdown-cur-line-blank-p))
3618 (setq bounds
(markdown-cur-list-item-bounds))))
3620 (setq new-loc
(point))
3621 (unless (markdown-cur-line-blank-p)
3624 ;; When not in a list, start a new unordered one
3626 (unless (markdown-cur-line-blank-p)
3629 ;; Compute indentation for a new list item
3630 (setq item-indent
(nth 2 bounds
))
3631 (setq marker
(nth 4 bounds
))
3633 ((= arg
4) (max (- item-indent
4) 0))
3634 ((= arg
16) (+ item-indent
4))
3636 (setq new-indent
(make-string indent
32))
3640 ((string-match "[0-9]" marker
)
3641 (if (= arg
16) ;; starting a new column indented one more level
3642 (insert (concat new-indent
"1. "))
3643 ;; travel up to the last item and pick the correct number. If
3644 ;; the argument was nil, "new-indent = item-indent" is the same,
3645 ;; so we don't need special treatment. Neat.
3647 (while (not (looking-at (concat new-indent
"\\([0-9]+\\)\\.")))
3649 (insert (concat new-indent
3650 (int-to-string (1+ (string-to-number (match-string 1))))
3653 ((string-match "[\\*\\+-]" marker
)
3654 (insert new-indent marker
)))))))
3656 (defun markdown-move-list-item-up ()
3657 "Move the current list item up in the list when possible."
3660 (when (setq cur
(markdown-cur-list-item-bounds))
3662 (goto-char (nth 0 cur
))
3663 (if (markdown-prev-list-item (nth 3 cur
))
3665 (setq prev
(markdown-cur-list-item-bounds))
3668 (transpose-regions (nth 0 prev
) (nth 1 prev
)
3669 (nth 0 cur
) (nth 1 cur
) t
)
3670 (goto-char (+ (nth 0 prev
) (- old
(nth 0 cur
)))))
3671 ;; Catch error in case regions overlap.
3672 (error (goto-char old
))))
3675 (defun markdown-move-list-item-down ()
3676 "Move the current list item down in the list when possible."
3679 (when (setq cur
(markdown-cur-list-item-bounds))
3681 (if (markdown-next-list-item (nth 3 cur
))
3683 (setq next
(markdown-cur-list-item-bounds))
3686 (transpose-regions (nth 0 cur
) (nth 1 cur
)
3687 (nth 0 next
) (nth 1 next
) nil
)
3688 (goto-char (+ old
(- (nth 1 next
) (nth 1 cur
)))))
3689 ;; Catch error in case regions overlap.
3690 (error (goto-char old
))))
3693 (defun markdown-demote-list-item (&optional bounds
)
3694 "Indent (or demote) the current list item.
3695 Optionally, BOUNDS of the current list item may be provided if available."
3697 (when (or bounds
(setq bounds
(markdown-cur-list-item-bounds)))
3700 (let* ((end-marker (make-marker))
3701 (end-marker (set-marker end-marker
(nth 1 bounds
))))
3702 (goto-char (nth 0 bounds
))
3703 (while (< (point) end-marker
)
3704 (unless (markdown-cur-line-blank-p)
3706 (forward-line)))))))
3708 (defun markdown-promote-list-item (&optional bounds
)
3709 "Unindent (or promote) the current list item.
3710 Optionally, BOUNDS of the current list item may be provided if available."
3712 (when (or bounds
(setq bounds
(markdown-cur-list-item-bounds)))
3715 (let* ((end-marker (make-marker))
3716 (end-marker (set-marker end-marker
(nth 1 bounds
)))
3718 (goto-char (nth 0 bounds
))
3719 (when (looking-at "^[ ]\\{1,4\\}")
3720 (setq num
(- (match-end 0) (match-beginning 0)))
3721 (setq regexp
(format "^[ ]\\{1,%d\\}" num
))
3722 (while (and (< (point) end-marker
)
3723 (re-search-forward regexp end-marker t
))
3724 (replace-match "" nil nil
)
3725 (forward-line))))))))
3727 (defun markdown-cleanup-list-numbers-level (&optional pfx
)
3728 "Update the numbering for level PFX (as a string of spaces).
3730 Assume that the previously found match was for a numbered item in
3737 (while (and continue
(not (eobp)))
3740 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
3741 (setq cpfx
(match-string-no-properties 1))
3745 (concat pfx
(number-to-string (setq idx
(1+ idx
))) ". "))
3749 (setq sep
(markdown-cleanup-list-numbers-level cpfx
))
3754 (setq continue nil
))))
3756 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
3757 (setq cpfx
(match-string-no-properties 1))
3759 ;; reset if separated before
3760 ((string= cpfx pfx
) (when sep
(setq idx
0)))
3763 (setq continue nil
))))
3768 (setq continue
(= (forward-line) 0))))
3771 (defun markdown-cleanup-list-numbers ()
3772 "Update the numbering of ordered lists."
3775 (goto-char (point-min))
3776 (markdown-cleanup-list-numbers-level "")))
3779 ;;; Outline ===================================================================
3781 (defvar markdown-cycle-global-status
1)
3782 (defvar markdown-cycle-subtree-status nil
)
3784 (defun markdown-end-of-subtree (&optional invisible-OK
)
3785 "Move to the end of the current subtree.
3786 Only visible heading lines are considered, unless INVISIBLE-OK is
3788 Derived from `org-end-of-subtree'."
3789 (outline-back-to-heading invisible-OK
)
3791 (level (funcall outline-level
)))
3792 (while (and (not (eobp))
3793 (or first
(> (funcall outline-level
) level
)))
3795 (outline-next-heading))
3796 (if (memq (preceding-char) '(?
\n ?\^M
))
3798 ;; Go to end of line before heading
3800 (if (memq (preceding-char) '(?
\n ?\^M
))
3801 ;; leave blank line before heading
3802 (forward-char -
1)))))
3805 (defun markdown-cycle (&optional arg
)
3806 "Visibility cycling for Markdown mode.
3807 If ARG is t, perform global visibility cycling. If the point is
3808 at an atx-style header, cycle visibility of the corresponding
3809 subtree. Otherwise, insert a tab using `indent-relative'.
3810 Derived from `org-cycle'."
3813 ((eq arg t
) ;; Global cycling
3815 ((and (eq last-command this-command
)
3816 (eq markdown-cycle-global-status
2))
3817 ;; Move from overview to contents
3819 (message "CONTENTS")
3820 (setq markdown-cycle-global-status
3))
3822 ((and (eq last-command this-command
)
3823 (eq markdown-cycle-global-status
3))
3824 ;; Move from contents to all
3826 (message "SHOW ALL")
3827 (setq markdown-cycle-global-status
1))
3830 ;; Defaults to overview
3832 (message "OVERVIEW")
3833 (setq markdown-cycle-global-status
2))))
3835 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp
))
3836 ;; At a heading: rotate between three different views
3837 (outline-back-to-heading)
3838 (let ((goal-column 0) eoh eol eos
)
3839 ;; Determine boundaries
3841 (outline-back-to-heading)
3843 (beginning-of-line 2)
3844 (while (and (not (eobp)) ;; this is like `next-line'
3845 (get-char-property (1- (point)) 'invisible
))
3846 (beginning-of-line 2)) (setq eol
(point)))
3847 (outline-end-of-heading) (setq eoh
(point))
3848 (markdown-end-of-subtree t
)
3849 (skip-chars-forward " \t\n")
3850 (beginning-of-line 1) ; in case this is an item
3851 (setq eos
(1- (point))))
3852 ;; Find out what to do next and set `this-command'
3855 ;; Nothing is hidden behind this heading
3856 (message "EMPTY ENTRY")
3857 (setq markdown-cycle-subtree-status nil
))
3859 ;; Entire subtree is hidden in one line: open it
3862 (message "CHILDREN")
3863 (setq markdown-cycle-subtree-status
'children
))
3864 ((and (eq last-command this-command
)
3865 (eq markdown-cycle-subtree-status
'children
))
3866 ;; We just showed the children, now show everything.
3869 (setq markdown-cycle-subtree-status
'subtree
))
3871 ;; Default action: hide the subtree.
3874 (setq markdown-cycle-subtree-status
'folded
)))))
3877 (indent-for-tab-command))))
3879 (defun markdown-shifttab ()
3880 "Global visibility cycling.
3881 Calls `markdown-cycle' with argument t."
3885 (defun markdown-outline-level ()
3886 "Return the depth to which a statement is nested in the outline."
3890 ((- (match-end 5) (match-beginning 5)))))
3893 ;;; Movement ==================================================================
3895 (defun markdown-beginning-of-defun (&optional arg
)
3896 "`beginning-of-defun-function' for Markdown.
3897 Move backward to the beginning of the current or previous section.
3898 When ARG is non-nil, repeat that many times. When ARG is negative,
3899 move forward to the ARG-th following section."
3901 (or arg
(setq arg
1))
3902 (or (re-search-backward markdown-regex-header nil t arg
)
3903 (goto-char (point-min))))
3905 (defun markdown-end-of-defun (&optional arg
)
3906 "`end-of-defun-function' for Markdown.
3907 Move forward to the end of the current or following section.
3908 When ARG is non-nil, repeat that many times. When ARG is negative,
3909 move back to the ARG-th preceding section."
3911 (or arg
(setq arg
1))
3912 (when (looking-at markdown-regex-header
)
3913 (goto-char (match-beginning 0))
3915 (if (re-search-forward markdown-regex-header nil t arg
)
3916 (goto-char (match-beginning 0))
3917 (goto-char (point-max)))
3918 (skip-syntax-backward "-"))
3920 (defun markdown-beginning-of-block ()
3921 "Move the point to the start of the previous text block."
3923 (if (re-search-backward markdown-regex-block-separator nil t
)
3924 (goto-char (or (match-end 2) (match-end 0)))
3925 (goto-char (point-min))))
3927 (defun markdown-end-of-block ()
3928 "Move the point to the start of the next text block."
3931 (skip-syntax-forward "-")
3932 (when (= (point) (point-min))
3934 (if (re-search-forward markdown-regex-block-separator nil t
)
3935 (goto-char (or (match-end 2) (match-end 0)))
3936 (goto-char (point-max)))
3937 (skip-syntax-backward "-")
3940 (defun markdown-forward-paragraph (arg)
3941 "Move forward one or more paragraphs or by one block.
3942 When ARG is nil or a numeric prefix, call `forward-paragraph'
3943 with ARG. When called with \\[universal-argument], call
3944 `markdown-end-of-block' instead."
3946 (or arg
(setq arg
1))
3947 (cond ((integerp arg
)
3948 (forward-paragraph arg
))
3950 (markdown-end-of-block 1))))
3952 (defun markdown-backward-paragraph (arg)
3953 "Move backward one or more paragraphs or by one block.
3954 When ARG is nil or a numeric prefix, call `backward-paragraph'
3955 with ARG. When called with \\[universal-argument], call
3956 `markdown-beginning-of-block' instead."
3958 (or arg
(setq arg
1))
3959 (cond ((integerp arg
)
3960 (backward-paragraph arg
))
3962 (markdown-beginning-of-block 1))))
3964 (defun markdown-end-of-block-element ()
3965 "Move the point to the start of the next block unit.
3966 Stops at blank lines, list items, headers, and horizontal rules."
3969 (while (and (or (not (markdown-prev-line-blank-p))
3970 (markdown-cur-line-blank-p))
3971 (not (or (looking-at markdown-regex-list
)
3972 (looking-at markdown-regex-header
)
3973 (looking-at markdown-regex-hr
)))
3977 (defun markdown-next-link ()
3978 "Jump to next inline, reference, or wiki link.
3979 If successful, return point. Otherwise, return nil.
3980 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
3982 (let ((opoint (point)))
3983 (when (or (markdown-link-p) (markdown-wiki-link-p))
3984 ;; At a link already, move past it.
3985 (goto-char (+ (match-end 0) 1)))
3986 ;; Search for the next wiki link and move to the beginning.
3987 (if (re-search-forward markdown-regex-link-generic nil t
)
3988 ;; Group 1 will move past non-escape character in wiki link regexp.
3989 ;; Go to beginning of group zero for all other link types.
3990 (goto-char (or (match-beginning 1) (match-beginning 0)))
3994 (defun markdown-previous-link ()
3995 "Jump to previous wiki link.
3996 If successful, return point. Otherwise, return nil.
3997 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
3999 (if (re-search-backward markdown-regex-link-generic nil t
)
4000 (goto-char (or (match-beginning 1) (match-beginning 0)))
4004 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
4006 (defun markdown-move-up ()
4008 Calls `markdown-move-list-item-up'."
4010 (markdown-move-list-item-up))
4012 (defun markdown-move-down ()
4013 "Move list item down.
4014 Calls `markdown-move-list-item-down'."
4016 (markdown-move-list-item-down))
4018 (defun markdown-promote ()
4019 "Either promote header or list item at point or cycle markup.
4020 See `markdown-cycle-atx', `markdown-cycle-setext', and
4021 `markdown-promote-list-item'."
4025 ;; Promote atx header
4026 ((thing-at-point-looking-at markdown-regex-header-atx
)
4027 (markdown-cycle-atx -
1))
4028 ;; Promote setext header
4029 ((thing-at-point-looking-at markdown-regex-header-setext
)
4030 (markdown-cycle-setext -
1))
4031 ;; Promote horizonal rule
4032 ((thing-at-point-looking-at markdown-regex-hr
)
4033 (markdown-cycle-hr -
1))
4034 ;; Promote list item
4035 ((setq bounds
(markdown-cur-list-item-bounds))
4036 (markdown-promote-list-item))
4038 ((thing-at-point-looking-at markdown-regex-bold
)
4039 (markdown-cycle-bold))
4041 ((thing-at-point-looking-at markdown-regex-italic
)
4042 (markdown-cycle-italic))
4044 (error "Nothing to promote at point")))))
4046 (defun markdown-demote ()
4047 "Either demote header or list item at point or cycle or remove markup.
4048 See `markdown-cycle-atx', `markdown-cycle-setext', and
4049 `markdown-demote-list-item'."
4053 ;; Demote atx header
4054 ((thing-at-point-looking-at markdown-regex-header-atx
)
4055 (markdown-cycle-atx 1))
4056 ;; Demote setext header
4057 ((thing-at-point-looking-at markdown-regex-header-setext
)
4058 (markdown-cycle-setext 1))
4059 ;; Demote horizonal rule
4060 ((thing-at-point-looking-at markdown-regex-hr
)
4061 (markdown-cycle-hr 1))
4063 ((setq bounds
(markdown-cur-list-item-bounds))
4064 (markdown-demote-list-item))
4066 ((thing-at-point-looking-at markdown-regex-bold
)
4067 (markdown-cycle-bold))
4069 ((thing-at-point-looking-at markdown-regex-italic
)
4070 (markdown-cycle-italic))
4072 (error "Nothing to demote at point")))))
4075 ;;; Commands ==================================================================
4077 (defun markdown (&optional output-buffer-name
)
4078 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
4079 The output buffer name defaults to `markdown-output-buffer-name'.
4080 Return the name of the output buffer used."
4082 (save-window-excursion
4083 (let ((begin-region)
4085 (if (markdown-use-region-p)
4086 (setq begin-region
(region-beginning)
4087 end-region
(region-end))
4088 (setq begin-region
(point-min)
4089 end-region
(point-max)))
4091 (unless output-buffer-name
4092 (setq output-buffer-name markdown-output-buffer-name
))
4095 ;; Handle case when `markdown-command' does not read from stdin
4096 (markdown-command-needs-filename
4097 (if (not buffer-file-name
)
4098 (error "Must be visiting a file")
4099 (shell-command (concat markdown-command
" "
4100 (shell-quote-argument buffer-file-name
))
4101 output-buffer-name
)))
4102 ;; Pass region to `markdown-command' via stdin
4104 (shell-command-on-region begin-region end-region markdown-command
4105 output-buffer-name
))))
4106 output-buffer-name
))
4108 (defun markdown-standalone (&optional output-buffer-name
)
4109 "Special function to provide standalone HTML output.
4110 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
4112 (setq output-buffer-name
(markdown output-buffer-name
))
4113 (with-current-buffer output-buffer-name
4114 (set-buffer output-buffer-name
)
4115 (goto-char (point-min))
4116 (unless (markdown-output-standalone-p)
4117 (markdown-add-xhtml-header-and-footer output-buffer-name
))
4121 (defun markdown-other-window (&optional output-buffer-name
)
4122 "Run `markdown-command' on current buffer and display in other window.
4123 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
4126 (display-buffer (markdown-standalone output-buffer-name
)))
4128 (defun markdown-output-standalone-p ()
4129 "Determine whether `markdown-command' output is standalone XHTML.
4130 Standalone XHTML output is identified by an occurrence of
4131 `markdown-xhtml-standalone-regexp' in the first five lines of output."
4133 markdown-xhtml-standalone-regexp
4134 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
4137 (defun markdown-add-xhtml-header-and-footer (title)
4138 "Wrap XHTML header and footer with given TITLE around current buffer."
4139 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
4140 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
4141 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
4142 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
4145 (insert "</title>\n")
4146 (when (> (length markdown-content-type
) 0)
4149 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
4150 markdown-content-type
4151 (or (and markdown-coding-system
4152 (fboundp 'coding-system-get
)
4153 (coding-system-get markdown-coding-system
4155 (and (fboundp 'coding-system-get
)
4156 (coding-system-get buffer-file-coding-system
4159 (if (> (length markdown-css-path
) 0)
4160 (insert "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
4163 (when (> (length markdown-xhtml-header-content
) 0)
4164 (insert markdown-xhtml-header-content
))
4165 (insert "\n</head>\n\n"
4167 (goto-char (point-max))
4172 (defun markdown-preview (&optional output-buffer-name
)
4173 "Run `markdown-command' on the current buffer and view output in browser.
4174 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
4177 (browse-url-of-buffer (markdown markdown-output-buffer-name
)))
4179 (defun markdown-export-file-name (&optional extension
)
4180 "Attempt to generate a filename for Markdown output.
4181 The file extension will be EXTENSION if given, or .html by default.
4182 If the current buffer is visiting a file, we construct a new
4183 output filename based on that filename. Otherwise, return nil."
4184 (when (buffer-file-name)
4186 (setq extension
".html"))
4190 (file-name-sans-extension (buffer-file-name)))
4194 (defun markdown-export (&optional output-file
)
4195 "Run Markdown on the current buffer, save to file, and return the filename.
4196 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
4197 generated by `markdown-export-file-name', which will be constructed using the
4198 current filename, but with the extension removed and replaced with .html."
4201 (setq output-file
(markdown-export-file-name ".html")))
4203 (let* ((init-buf (current-buffer))
4204 (init-point (point))
4205 (init-buf-string (buffer-string))
4206 (output-buffer (find-file-noselect output-file
))
4207 (output-buffer-name (buffer-name output-buffer
)))
4208 (run-hooks 'markdown-before-export-hook
)
4209 (markdown-standalone output-buffer-name
)
4210 (with-current-buffer output-buffer
4211 (run-hooks 'markdown-after-export-hook
)
4213 ;; if modified, restore initial buffer
4214 (when (buffer-modified-p init-buf
)
4216 (insert init-buf-string
)
4218 (goto-char init-point
))
4221 (defun markdown-export-and-preview ()
4222 "Export to XHTML using `markdown-export' and browse the resulting file."
4224 (browse-url (markdown-export)))
4226 (defun markdown-open ()
4227 "Open file for the current buffer with `markdown-open-command'."
4229 (if (not markdown-open-command
)
4230 (error "Variable `markdown-open-command' must be set")
4231 (if (not buffer-file-name
)
4232 (error "Must be visiting a file")
4233 (call-process markdown-open-command
4234 nil nil nil buffer-file-name
))))
4236 (defun markdown-kill-ring-save ()
4237 "Run Markdown on file and store output in the kill ring."
4239 (save-window-excursion
4241 (with-current-buffer markdown-output-buffer-name
4242 (kill-ring-save (point-min) (point-max)))))
4245 ;;; Links =====================================================================
4247 (require 'thingatpt
)
4249 (defun markdown-link-p ()
4250 "Return non-nil when `point' is at a non-wiki link.
4251 See `markdown-wiki-link-p' for more information."
4252 (let ((case-fold-search nil
))
4253 (and (not (markdown-wiki-link-p))
4254 (or (thing-at-point-looking-at markdown-regex-link-inline
)
4255 (thing-at-point-looking-at markdown-regex-link-reference
)
4256 (thing-at-point-looking-at markdown-regex-uri
)
4257 (thing-at-point-looking-at markdown-regex-angle-uri
)))))
4259 (defun markdown-link-link ()
4260 "Return the link part of the regular (non-wiki) link at point.
4261 Works with both inline and reference style links. If point is
4262 not at a link or the link reference is not defined returns nil."
4264 ((thing-at-point-looking-at markdown-regex-link-inline
)
4265 (match-string-no-properties 5))
4266 ((thing-at-point-looking-at markdown-regex-link-reference
)
4267 (let* ((text (match-string-no-properties 2))
4268 (reference (match-string-no-properties 4))
4269 (target (downcase (if (string= reference
"[]") text reference
))))
4270 (car (markdown-reference-definition target
))))
4271 ((thing-at-point-looking-at markdown-regex-uri
)
4272 (match-string-no-properties 0))
4273 ((thing-at-point-looking-at markdown-regex-angle-uri
)
4274 (match-string-no-properties 2))
4277 (defun markdown-follow-link-at-point ()
4278 "Open the current non-wiki link in a browser."
4280 (if (markdown-link-p) (browse-url (markdown-link-link))
4281 (error "Point is not at a Markdown link or URI")))
4284 ;;; WikiLink Following/Markup =================================================
4286 (defun markdown-wiki-link-p ()
4287 "Return non-nil when `point' is at a true wiki link.
4288 A true wiki link name matches `markdown-regex-wiki-link' but does not
4289 match the current file name after conversion. This modifies the data
4290 returned by `match-data'. Note that the potential wiki link name must
4291 be available via `match-string'."
4292 (let ((case-fold-search nil
))
4293 (and (thing-at-point-looking-at markdown-regex-wiki-link
)
4294 (or (not buffer-file-name
)
4295 (not (string-equal (buffer-file-name)
4296 (markdown-convert-wiki-link-to-filename
4297 (markdown-wiki-link-link)))))
4298 (not (save-match-data
4299 (save-excursion))))))
4301 (defun markdown-wiki-link-link ()
4302 "Return the link part of the wiki link using current match data.
4303 The location of the link component depends on the value of
4304 `markdown-wiki-link-alias-first'."
4305 (if markdown-wiki-link-alias-first
4306 (or (match-string-no-properties 4) (match-string-no-properties 2))
4307 (match-string-no-properties 2)))
4309 (defun markdown-wiki-link-alias ()
4310 "Return the alias or text part of the wiki link using current match data.
4311 The location of the alias component depends on the value of
4312 `markdown-wiki-link-alias-first'."
4313 (if markdown-wiki-link-alias-first
4314 (match-string-no-properties 2)
4315 (or (match-string-no-properties 4) (match-string-no-properties 2))))
4317 (defun markdown-convert-wiki-link-to-filename (name)
4318 "Generate a filename from the wiki link NAME.
4319 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
4320 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
4321 and [[test test]] both map to Test-test.ext."
4322 (let ((basename (markdown-replace-regexp-in-string
4323 "[[:space:]\n]" markdown-link-space-sub-char name
)))
4324 (when (eq major-mode
'gfm-mode
)
4325 (setq basename
(concat (upcase (substring basename
0 1))
4326 (downcase (substring basename
1 nil
)))))
4328 (if (buffer-file-name)
4330 (file-name-extension (buffer-file-name)))))))
4332 (defun markdown-follow-wiki-link (name &optional other
)
4333 "Follow the wiki link NAME.
4334 Convert the name to a file name and call `find-file'. Ensure that
4335 the new buffer remains in `markdown-mode'. Open the link in another
4336 window when OTHER is non-nil."
4337 (let ((filename (markdown-convert-wiki-link-to-filename name
))
4338 (wp (file-name-directory buffer-file-name
)))
4339 (when other
(other-window 1))
4340 (find-file (concat wp filename
)))
4341 (when (not (eq major-mode
'markdown-mode
))
4344 (defun markdown-follow-wiki-link-at-point (&optional arg
)
4345 "Find Wiki Link at point.
4346 With prefix argument ARG, open the file in other window.
4347 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
4349 (if (markdown-wiki-link-p)
4350 (markdown-follow-wiki-link (markdown-wiki-link-link) arg
)
4351 (error "Point is not at a Wiki Link")))
4353 (defun markdown-highlight-wiki-link (from to face
)
4354 "Highlight the wiki link in the region between FROM and TO using FACE."
4355 (put-text-property from to
'font-lock-face face
))
4357 (defun markdown-unfontify-region-wiki-links (from to
)
4358 "Remove wiki link faces from the region specified by FROM and TO."
4359 (interactive "nfrom: \nnto: ")
4360 (remove-text-properties from to
'(font-lock-face markdown-link-face
))
4361 (remove-text-properties from to
'(font-lock-face markdown-missing-link-face
)))
4363 (defun markdown-fontify-region-wiki-links (from to
)
4364 "Search region given by FROM and TO for wiki links and fontify them.
4365 If a wiki link is found check to see if the backing file exists
4366 and highlight accordingly."
4369 (while (re-search-forward markdown-regex-wiki-link to t
)
4370 (let ((highlight-beginning (match-beginning 1))
4371 (highlight-end (match-end 1))
4373 (markdown-convert-wiki-link-to-filename
4374 (markdown-wiki-link-link))))
4375 (if (file-exists-p file-name
)
4376 (markdown-highlight-wiki-link
4377 highlight-beginning highlight-end markdown-link-face
)
4378 (markdown-highlight-wiki-link
4379 highlight-beginning highlight-end markdown-link-face
)
4380 (markdown-highlight-wiki-link
4381 highlight-beginning highlight-end markdown-missing-link-face
))))))
4383 (defun markdown-extend-changed-region (from to
)
4384 "Extend region given by FROM and TO so that we can fontify all links.
4385 The region is extended to the first newline before and the first
4387 ;; start looking for the first new line before 'from
4389 (re-search-backward "\n" nil t
)
4390 (let ((new-from (point-min))
4391 (new-to (point-max)))
4392 (if (not (= (point) from
))
4393 (setq new-from
(point)))
4394 ;; do the same thing for the first new line after 'to
4396 (re-search-forward "\n" nil t
)
4397 (if (not (= (point) to
))
4398 (setq new-to
(point)))
4399 (values new-from new-to
)))
4401 (defun markdown-check-change-for-wiki-link (from to change
)
4402 "Check region between FROM and TO for wiki links and re-fontfy as needed.
4403 Designed to be used with the `after-change-functions' hook.
4404 CHANGE is the number of bytes of pre-change text replaced by the
4406 (interactive "nfrom: \nnto: \nnchange: ")
4407 (let* ((modified (buffer-modified-p))
4408 (buffer-undo-list t
)
4409 (inhibit-read-only t
)
4410 (inhibit-point-motion-hooks t
)
4412 buffer-file-truename
)
4417 ;; Extend the region to fontify so that it starts
4418 ;; and ends at safe places.
4419 (multiple-value-bind (new-from new-to
)
4420 (markdown-extend-changed-region from to
)
4421 ;; Unfontify existing fontification (start from scratch)
4422 (markdown-unfontify-region-wiki-links new-from new-to
)
4423 ;; Now do the fontification.
4424 (markdown-fontify-region-wiki-links new-from new-to
)))))
4427 (set-buffer-modified-p nil
)))))
4429 (defun markdown-fontify-buffer-wiki-links ()
4430 "Refontify all wiki links in the buffer."
4432 (markdown-check-change-for-wiki-link (point-min) (point-max) 0))
4435 ;;; Following and Jumping =====================================================
4437 (defun markdown-follow-thing-at-point (arg)
4438 "Follow thing at point if possible, such as a reference link or wiki link.
4439 Opens inline and reference links in a browser. Opens wiki links
4440 to other files in the current window, or the another window if
4442 See `markdown-follow-link-at-point' and
4443 `markdown-follow-wiki-link-at-point'."
4445 (cond ((markdown-link-p)
4446 (markdown-follow-link-at-point))
4447 ((markdown-wiki-link-p)
4448 (markdown-follow-wiki-link-at-point arg
))
4450 (error "Nothing to follow at point"))))
4452 (defun markdown-jump ()
4453 "Jump to another location based on context at point.
4454 Jumps between reference links and definitions; between footnote
4455 markers and footnote text."
4457 (cond ((markdown-footnote-text-positions)
4458 (markdown-footnote-return))
4459 ((markdown-footnote-marker-positions)
4460 (markdown-footnote-goto-text))
4461 ((thing-at-point-looking-at markdown-regex-link-reference
)
4462 (markdown-reference-goto-definition))
4463 ((thing-at-point-looking-at markdown-regex-reference-definition
)
4464 (markdown-reference-goto-link (match-string-no-properties 1)))
4466 (error "Nothing to jump to from context at point"))))
4469 ;;; Miscellaneous =============================================================
4471 (defun markdown-compress-whitespace-string (str)
4472 "Compress whitespace in STR and return result.
4473 Leading and trailing whitespace is removed. Sequences of multiple
4474 spaces, tabs, and newlines are replaced with single spaces."
4475 (replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
4476 (replace-regexp-in-string "[ \t\n]+" " " str
)))
4478 (defun markdown-line-number-at-pos (&optional pos
)
4479 "Return (narrowed) buffer line number at position POS.
4480 If POS is nil, use current buffer location.
4481 This is an exact copy of `line-number-at-pos' for use in emacs21."
4482 (let ((opoint (or pos
(point))) start
)
4484 (goto-char (point-min))
4485 (setq start
(point))
4488 (1+ (count-lines start
(point))))))
4490 (defun markdown-nobreak-p ()
4491 "Return nil if it is acceptable to break the current line at the point."
4492 ;; inside in square brackets (e.g., link anchor text)
4493 (looking-back "\\[[^]]*"))
4495 (defun markdown-adaptive-fill-function ()
4496 "Return prefix for filling paragraph or nil if not determined."
4498 ;; List item inside blockquote
4499 ((looking-at "^[ \t]*>[ \t]*\\([0-9]+\\.\\|[*+-]\\)[ \t]+")
4500 (replace-regexp-in-string
4501 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
4503 ((looking-at "^[ \t]*>[ \t]*")
4504 (match-string-no-properties 0))
4506 ((looking-at markdown-regex-list
)
4507 (match-string-no-properties 0))
4512 ;;; Extensions ================================================================
4514 (defun markdown-reload-extensions ()
4515 "Check settings, update font-lock keywords, and re-fontify buffer."
4517 (when (eq major-mode
'markdown-mode
)
4518 (setq markdown-mode-font-lock-keywords
4520 (when markdown-enable-math
4521 markdown-mode-font-lock-keywords-math
)
4522 markdown-mode-font-lock-keywords-basic
4523 markdown-mode-font-lock-keywords-core
))
4524 (setq font-lock-defaults
'(markdown-mode-font-lock-keywords))
4525 (font-lock-refresh-defaults)))
4527 (defun markdown-enable-math (&optional arg
)
4528 "Toggle support for inline and display LaTeX math expressions.
4529 With a prefix argument ARG, enable math mode if ARG is positive,
4530 and disable it otherwise. If called from Lisp, enable the mode
4531 if ARG is omitted or nil."
4532 (interactive (list (or current-prefix-arg
'toggle
)))
4533 (setq markdown-enable-math
4534 (if (eq arg
'toggle
)
4535 (not markdown-enable-math
)
4536 (> (prefix-numeric-value arg
) 0)))
4537 (if markdown-enable-math
4538 (message "markdown-mode math support enabled")
4539 (message "markdown-mode math support disabled"))
4540 (markdown-reload-extensions))
4543 ;;; Mode Definition ==========================================================
4545 (defun markdown-show-version ()
4546 "Show the version number in the minibuffer."
4548 (message "markdown-mode, version %s" markdown-mode-version
))
4551 (define-derived-mode markdown-mode text-mode
"Markdown"
4552 "Major mode for editing Markdown files."
4553 ;; Natural Markdown tab width
4556 (make-local-variable 'comment-start
)
4557 (setq comment-start
"<!-- ")
4558 (make-local-variable 'comment-end
)
4559 (setq comment-end
" -->")
4560 (make-local-variable 'comment-start-skip
)
4561 (setq comment-start-skip
"<!--[ \t]*")
4562 (make-local-variable 'comment-column
)
4563 (setq comment-column
0)
4565 (set (make-local-variable 'markdown-mode-font-lock-keywords
) nil
)
4566 (set (make-local-variable 'font-lock-defaults
) nil
)
4567 (set (make-local-variable 'font-lock-multiline
) t
)
4568 (markdown-reload-extensions)
4570 (make-local-variable 'markdown-enable-math
)
4571 (add-hook 'hack-local-variables-hook
'markdown-reload-extensions
)
4572 ;; For imenu support
4573 (setq imenu-create-index-function
'markdown-imenu-create-index
)
4574 ;; For menu support in XEmacs
4575 (easy-menu-add markdown-mode-menu markdown-mode-map
)
4577 (set (make-local-variable 'beginning-of-defun-function
)
4578 'markdown-beginning-of-defun
)
4579 (set (make-local-variable 'end-of-defun-function
)
4580 'markdown-end-of-defun
)
4581 ;; Paragraph filling
4582 (set (make-local-variable 'paragraph-start
)
4583 "\f\\|[ \t]*$\\|[ \t]*[*+-] \\|[ \t]*[0-9]+\\.\\|[ \t]*: ")
4584 (set (make-local-variable 'paragraph-separate
)
4585 "\\(?:[ \t\f]\\|.* \\)*$")
4586 (set (make-local-variable 'adaptive-fill-first-line-regexp
)
4587 "\\`[ \t]*>[ \t]*?\\'")
4588 (set (make-local-variable 'adaptive-fill-function
)
4589 'markdown-adaptive-fill-function
)
4591 (make-local-variable 'outline-regexp
)
4592 (setq outline-regexp markdown-regex-header
)
4593 (make-local-variable 'outline-level
)
4594 (setq outline-level
'markdown-outline-level
)
4595 ;; Cause use of ellipses for invisible text.
4596 (add-to-invisibility-spec '(outline . t
))
4597 ;; Indentation and filling
4598 (make-local-variable 'fill-nobreak-predicate
)
4599 (add-hook 'fill-nobreak-predicate
'markdown-nobreak-p
)
4600 (setq indent-line-function markdown-indent-function
)
4602 ;; Prepare hooks for XEmacs compatibility
4603 (when (featurep 'xemacs
)
4604 (make-local-hook 'after-change-functions
)
4605 (make-local-hook 'font-lock-extend-region-functions
)
4606 (make-local-hook 'window-configuration-change-hook
))
4608 ;; Multiline font lock
4609 (add-hook 'font-lock-extend-region-functions
4610 'markdown-font-lock-extend-region
)
4612 ;; Anytime text changes make sure it gets fontified correctly
4613 (add-hook 'after-change-functions
'markdown-check-change-for-wiki-link t t
)
4615 ;; If we left the buffer there is a really good chance we were
4616 ;; creating one of the wiki link documents. Make sure we get
4617 ;; refontified when we come back.
4618 (add-hook 'window-configuration-change-hook
4619 'markdown-fontify-buffer-wiki-links t t
)
4621 ;; do the initial link fontification
4622 (markdown-fontify-buffer-wiki-links))
4624 ;;(add-to-list 'auto-mode-alist '("\\.text$" . markdown-mode))
4627 ;;; GitHub Flavored Markdown Mode ============================================
4629 (defvar gfm-font-lock-keywords
4631 ;; GFM features to match first
4633 (cons 'markdown-match-gfm-code-blocks
'((1 markdown-pre-face
)
4634 (2 markdown-language-keyword-face
)
4635 (3 markdown-pre-face
)
4636 (4 markdown-pre-face
))))
4637 ;; Basic Markdown features (excluding possibly overridden ones)
4638 markdown-mode-font-lock-keywords-basic
4639 ;; GFM features to match last
4641 (cons markdown-regex-gfm-italic
'(2 markdown-italic-face
))))
4642 "Default highlighting expressions for GitHub-flavored Markdown mode.")
4645 (define-derived-mode gfm-mode markdown-mode
"GFM"
4646 "Major mode for editing GitHub Flavored Markdown files."
4647 (setq markdown-link-space-sub-char
"-")
4648 (set (make-local-variable 'font-lock-defaults
)
4649 '(gfm-font-lock-keywords))
4651 ;; Use visual-line-mode if available, fall back to longlines-mode:
4652 (if (fboundp 'visual-line-mode
)
4653 (visual-line-mode 1)
4655 ;; do the initial link fontification
4656 (markdown-fontify-buffer-wiki-links))
4659 (provide 'markdown-mode
)
4661 ;;; markdown-mode.el ends here