markdown-mode 2.0
[markdown-mode.git] / markdown-mode.el
blob78b2965ee368a802bfaa9d04a889b644ef971499
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
29 ;; Version: 2.0
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)
38 ;; any later version.
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.
50 ;;; Commentary:
52 ;; markdown-mode is a major mode for editing [Markdown][]-formatted
53 ;; text files in GNU Emacs. markdown-mode is free software, licensed
54 ;; under the GNU GPL.
56 ;; [Markdown]: http://daringfireball.net/projects/markdown/
58 ;; The latest stable version is markdown-mode 2.0, released on March 24, 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/20130131-002.png
66 ;; [release notes]: http://jblevins.org/projects/markdown-mode/rev-2-0
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
93 ;; by running
95 ;; git clone git://jblevins.org/git/markdown-mode.git
97 ;; [devel.el]: http://jblevins.org/git/markdown-mode.git/plain/markdown-mode.el
99 ;;; Installation:
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.
115 ;;; Usage:
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
185 ;; image.
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). Alternatively, a `C-u` prefix can be
223 ;; given to insert a heading promoted by one level or a `C-u C-u`
224 ;; prefix can be given to insert a heading demoted by one level.
226 ;; To insert a heading of a specific level and type, use `C-c C-t 1`
227 ;; through `C-c C-t 6` for atx (hash mark) headings and `C-c C-t !` or
228 ;; `C-c C-t @` for setext headings of level one or two, respectively.
229 ;; Note that `!` is `S-1` and `@` is `S-2`.
231 ;; If the point is at a heading, these commands will replace the
232 ;; existing markup in order to update the level and/or type of the
233 ;; heading. To remove the markup of the heading at the point,
234 ;; press `C-c C-k` to kill the heading and press `C-y` to yank the
235 ;; heading text back into the buffer.
237 ;; * Horizontal Rules: `C-c -`
239 ;; `C-c -` inserts a horizontal rule. By default, insert the
240 ;; first string in the list `markdown-hr-strings' (the most
241 ;; prominent rule). With a `C-u` prefix, insert the last string.
242 ;; With a numeric prefix `N`, insert the string in position `N`
243 ;; (counting from 1).
245 ;; * Markdown and Maintenance Commands: `C-c C-c`
247 ;; *Compile:* `C-c C-c m` will run Markdown on the current buffer
248 ;; and show the output in another buffer. *Preview*: `C-c C-c p`
249 ;; runs Markdown on the current buffer and previews, stores the
250 ;; output in a temporary file, and displays the file in a browser.
251 ;; *Export:* `C-c C-c e` will run Markdown on the current buffer
252 ;; and save the result in the file `basename.html`, where
253 ;; `basename` is the name of the Markdown file with the extension
254 ;; removed. *Export and View:* press `C-c C-c v` to export the
255 ;; file and view it in a browser. **For both export commands, the
256 ;; output file will be overwritten without notice.**
257 ;; *Open:* `C-c C-c o` will open the Markdown source file directly
258 ;; using `markdown-open-command'.
260 ;; To summarize:
262 ;; - `C-c C-c m`: `markdown-command' > `*markdown-output*` buffer.
263 ;; - `C-c C-c p`: `markdown-command' > temporary file > browser.
264 ;; - `C-c C-c e`: `markdown-command' > `basename.html`.
265 ;; - `C-c C-c v`: `markdown-command' > `basename.html` > browser.
266 ;; - `C-c C-c w`: `markdown-command' > kill ring.
267 ;; - `C-c C-c o`: `markdown-open-command'.
269 ;; `C-c C-c c` will check for undefined references. If there are
270 ;; any, a small buffer will open with a list of undefined
271 ;; references and the line numbers on which they appear. In Emacs
272 ;; 22 and greater, selecting a reference from this list and
273 ;; pressing `RET` will insert an empty reference definition at the
274 ;; end of the buffer. Similarly, selecting the line number will
275 ;; jump to the corresponding line.
277 ;; `C-c C-c n` renumbers any ordered lists in the buffer that are
278 ;; out of sequence.
280 ;; `C-c C-c ]` completes all headings and normalizes all horizontal
281 ;; rules in the buffer.
283 ;; * Following Links: `C-c C-o`
285 ;; Press `C-c C-o` when the point is on an inline or reference
286 ;; link to open the URL in a browser. When the point is at a
287 ;; wiki link, open it in another buffer (in the current window,
288 ;; or in the other window with the `C-u` prefix). Use `M-p` and
289 ;; `M-n` to quickly jump to the previous or next link of any type.
291 ;; * Jumping: `C-c C-j`
293 ;; Use `C-c C-j` to jump from the object at point to its counterpart
294 ;; elsewhere in the text, when possible. Jumps between reference
295 ;; links and definitions; between footnote markers and footnote
296 ;; text. If more than one link uses the same reference name, a
297 ;; new buffer will be created containing clickable buttons for jumping
298 ;; to each link. You may press `TAB` or `S-TAB` to jump between
299 ;; buttons in this window.
301 ;; * Promotion and Demotion: `C-c C--` and `C-c C-=`
303 ;; Headings, horizontal rules, and list items can be promoted and
304 ;; demoted, as well as bold and italic text. For headings,
305 ;; "promotion" means *decreasing* the level (i.e., moving from
306 ;; `<h2>` to `<h1>`) while "demotion" means *increasing* the
307 ;; level. For horizontal rules, promotion and demotion means
308 ;; moving backward or forward through the list of rule strings in
309 ;; `markdown-hr-strings'. For bold and italic text, promotion and
310 ;; demotion means changing the markup from underscores to asterisks.
311 ;; Press `C-c C--` or `M-LEFT` to promote the element at the point
312 ;; if possible.
314 ;; To remember these commands, note that `-` is for decreasing the
315 ;; level (promoting), and `=` (on the same key as `+`) is for
316 ;; increasing the level (demoting). Similarly, the left and right
317 ;; arrow keys indicate the direction that the atx heading markup
318 ;; is moving in when promoting or demoting.
320 ;; * Completion: `C-c C-]`
322 ;; Complete markup is in normalized form, which means, for
323 ;; example, that the underline portion of a setext header is the
324 ;; same length as the heading text, or that the number of leading
325 ;; and trailing hash marks of an atx header are equal and that
326 ;; there is no extra whitespace in the header text. `C-c C-]`
327 ;; completes the markup at the point, if it is determined to be
328 ;; incomplete.
330 ;; * Editing Lists: `M-RET`, `M-UP`, `M-DOWN`, `M-LEFT`, and `M-RIGHT`
332 ;; New list items can be inserted with `M-RET`. This command
333 ;; determines the appropriate marker (one of the possible
334 ;; unordered list markers or the next number in sequence for an
335 ;; ordered list) and indentation level by examining nearby list
336 ;; items. If there is no list before or after the point, start a
337 ;; new list. Prefix this command by `C-u` to decrease the
338 ;; indentation by one level. Prefix this command by `C-u C-u` to
339 ;; increase the indentation by one level.
341 ;; Existing list items can be moved up or down with `M-UP` or
342 ;; `M-DOWN` and indented or exdented with `M-RIGHT` or `M-LEFT`.
344 ;; * Shifting the Region: `C-c <` and `C-c >`
346 ;; Text in the region can be indented or exdented as a group using
347 ;; `C-c >` to indent to the next indentation point (calculated in
348 ;; the current context), and `C-c <` to exdent to the previous
349 ;; indentation point. These keybindings are the same as those for
350 ;; similar commands in `python-mode'.
352 ;; * Killing Elements: `C-c C-k`
354 ;; Press `C-c C-k` to kill the thing at point and add important
355 ;; text, without markup, to the kill ring. Possible things to
356 ;; kill include (roughly in order of precedece): inline code,
357 ;; headings, horizonal rules, links (add link text to kill ring),
358 ;; images (add alt text to kill ring), angle URIs, email
359 ;; addresses, bold, italics, reference definitions (add URI to
360 ;; kill ring), footnote markers and text (kill both marker and
361 ;; text, add text to kill ring), and list items.
363 ;; * Outline Navigation: `C-c C-n`, `C-c C-p`, `C-c C-f`, `C-c C-b`, and `C-c C-u`
365 ;; Navigation between headings is possible using `outline-mode'.
366 ;; Use `C-c C-n` and `C-c C-p` to move between the next and previous
367 ;; visible headings. Similarly, `C-c C-f` and `C-c C-b` move to the
368 ;; next and previous visible headings at the same level as the one
369 ;; at the point. Finally, `C-c C-u` will move up to a lower-level
370 ;; (higher precedence) visible heading.
372 ;; * Movement by Paragraph or Block: `M-{` and `M-}`
374 ;; The definition of a "paragraph" is slightly different in
375 ;; markdown-mode than, say, text-mode, because markdown-mode
376 ;; supports filling for list items and respects hard line breaks,
377 ;; both of which break paragraphs. So, markdown-mode overrides
378 ;; the usual paragraph navigation commands `M-{` and `M-}` so that
379 ;; with a `C-u` prefix, these commands jump to the beginning or
380 ;; end of an entire block of text, respectively, where "blocks"
381 ;; are separated by one or more lines.
383 ;; * Movement by Defun: `C-M-a`, `C-M-e`, and `C-M-h`
385 ;; The usual Emacs commands can be used to move by defuns
386 ;; (top-level major definitions). In markdown-mode, a defun is a
387 ;; section. As usual, `C-M-a` will move the point to the
388 ;; beginning of the current or preceding defun, `C-M-e` will move
389 ;; to the end of the current or following defun, and `C-M-h` will
390 ;; put the region around the entire defun.
392 ;; As noted, many of the commands above behave differently depending
393 ;; on whether Transient Mark mode is enabled or not. When it makes
394 ;; sense, if Transient Mark mode is on and the region is active, the
395 ;; command applies to the text in the region (e.g., `C-c C-s s` makes the
396 ;; region bold). For users who prefer to work outside of Transient
397 ;; Mark mode, since Emacs 22 it can be enabled temporarily by pressing
398 ;; `C-SPC C-SPC`. When this is not the case, many commands then
399 ;; proceed to look work with the word or line at the point.
401 ;; When applicable, commands that specifically act on the region even
402 ;; outside of Transient Mark mode have the same keybinding as their
403 ;; standard counterpart, but the letter is uppercase. For example,
404 ;; `markdown-insert-blockquote' is bound to `C-c C-s b` and only acts on
405 ;; the region in Transient Mark mode while `markdown-blockquote-region'
406 ;; is bound to `C-c C-s B` and always applies to the region (when nonempty).
408 ;; Note that these region-specific functions are useful in many
409 ;; cases where it may not be obvious. For example, yanking text from
410 ;; the kill ring sets the mark at the beginning of the yanked text
411 ;; and moves the point to the end. Therefore, the (inactive) region
412 ;; contains the yanked text. So, `C-y` followed by `C-c C-s C-b` will
413 ;; yank text and turn it into a blockquote.
415 ;; markdown-mode attempts to be flexible in how it handles
416 ;; indentation. When you press `TAB` repeatedly, the point will cycle
417 ;; through several possible indentation levels corresponding to things
418 ;; you might have in mind when you press `RET` at the end of a line or
419 ;; `TAB`. For example, you may want to start a new list item,
420 ;; continue a list item with hanging indentation, indent for a nested
421 ;; pre block, and so on. Exdention is handled similarly when backspace
422 ;; is pressed at the beginning of the non-whitespace portion of a line.
424 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
425 ;; visibility cycling for atx- or hash-style headings. There are two
426 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
427 ;; the table of contents view (headings only), outline view (top-level
428 ;; headings only), and the full document view. Pressing `TAB` while the
429 ;; point is at a heading will cycle through levels of visibility for the
430 ;; subtree: completely folded, visible children, and fully visible.
431 ;; Note that mixing hash and underline style headings will give undesired
432 ;; results.
434 ;;; Customization:
436 ;; Although no configuration is *necessary* there are a few things
437 ;; that can be customized. The `M-x customize-mode` command
438 ;; provides an interface to all of the possible customizations:
440 ;; * `markdown-command' - the command used to run Markdown (default:
441 ;; `markdown`). This variable may be customized to pass
442 ;; command-line options to your Markdown processor of choice.
444 ;; * `markdown-command-needs-filename' - set to `t' if
445 ;; `markdown-command' does not accept standard input (default:
446 ;; `nil'). When `nil', `markdown-mode' will pass the Markdown
447 ;; content to `markdown-command' using standard input (`stdin`).
448 ;; When set to `t', `markdown-mode' will pass the name of the file
449 ;; as the final command-line argument to `markdown-command'. Note
450 ;; that in the latter case, you will only be able to run
451 ;; `markdown-command' from buffers which are visiting a file.
453 ;; * `markdown-open-command' - the command used for calling a standalone
454 ;; Markdown previewer which is capable of opening Markdown source files
455 ;; directly (default: `nil'). This command will be called
456 ;; with a single argument, the filename of the current buffer.
457 ;; A representative program is the Mac app [Marked][], a
458 ;; live-updating MultiMarkdown previewer which has a command line
459 ;; utility at `/usr/local/bin/mark`.
461 ;; * `markdown-hr-strings' - list of strings to use when inserting
462 ;; horizontal rules. Different strings will not be distinguished
463 ;; when converted to HTML--they will all be converted to
464 ;; `<hr/>`--but they may add visual distinction and style to plain
465 ;; text documents. To maintain some notion of promotion and
466 ;; demotion, keep these sorted from largest to smallest.
468 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
469 ;; underscores for bold instead of two asterisks (default: `nil').
471 ;; * `markdown-italic-underscore' - set to a non-nil value to use
472 ;; underscores for italic instead of asterisks (default: `nil').
474 ;; * `markdown-indent-function' - the function to use for automatic
475 ;; indentation (default: `markdown-indent-line').
477 ;; * `markdown-indent-on-enter' - set to a non-nil value to
478 ;; automatically indent new lines when the enter key is pressed
479 ;; (default: `t')
481 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
482 ;; treat aliased wiki links like `[[link text|PageName]]`
483 ;; (default: `t'). When set to nil, they will be treated as
484 ;; `[[PageName|link text]]'.
486 ;; * `markdown-uri-types' - a list of protocol schemes (e.g., "http")
487 ;; for URIs that `markdown-mode' should highlight.
489 ;; * `markdown-enable-math' - syntax highlighting for LaTeX
490 ;; fragments (default: `nil'). Set this to `t' to turn on math
491 ;; support by default. Math support can be toggled later using
492 ;; the function `markdown-enable-math'."
494 ;; * `markdown-css-path' - CSS file to link to in XHTML output
495 ;; (default: `""`).
497 ;; * `markdown-content-type' - when set to a nonempty string, an
498 ;; `http-equiv` attribute will be included in the XHTML `<head>`
499 ;; block (default: `""`). If needed, the suggested values are
500 ;; `application/xhtml+xml` or `text/html`. See also:
501 ;; `markdown-coding-system'.
503 ;; * `markdown-coding-system' - used for specifying the character
504 ;; set identifier in the `http-equiv` attribute when included
505 ;; (default: `nil'). See `markdown-content-type', which must
506 ;; be set before this variable has any effect. When set to `nil',
507 ;; `buffer-file-coding-system' will be used to automatically
508 ;; determine the coding system string (falling back to
509 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
510 ;; and `iso-latin-1'.
512 ;; * `markdown-xhtml-header-content' - additional content to include
513 ;; in the XHTML `<head>` block (default: `""`).
515 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
516 ;; `markdown-mode' uses to determine whether the output of
517 ;; `markdown-command' is a standalone XHTML document or an XHTML
518 ;; fragment (default: `"^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"`). If
519 ;; this regular expression not matched in the first five lines of
520 ;; output, `markdown-mode' assumes the output is a fragment and
521 ;; adds a header and footer.
523 ;; * `markdown-link-space-sub-char' - a character to replace spaces
524 ;; when mapping wiki links to filenames (default: `"_"`).
525 ;; For example, use an underscore for compatibility with the
526 ;; Python Markdown WikiLinks extension. In `gfm-mode', this is
527 ;; set to `"-"` to conform with GitHub wiki links.
529 ;; * `markdown-reference-location' - where to insert reference
530 ;; definitions (default: `header`). The possible locations are
531 ;; the end of the document (`end`), after the current block
532 ;; (`immediately`), before the next header (`header`).
534 ;; * `markdown-footnote-location' - where to insert footnote text
535 ;; (default: `end`). The set of location options is the same as
536 ;; for `markdown-reference-location'.
538 ;; Additionally, the faces used for syntax highlighting can be modified to
539 ;; your liking by issuing `M-x customize-group RET markdown-faces`
540 ;; or by using the "Markdown Faces" link at the bottom of the mode
541 ;; customization screen.
543 ;; [Marked]: https://itunes.apple.com/us/app/marked/id448925439?ls=1&mt=12&partnerId=30&siteID=GpHp3Acs1Yo
545 ;;; Extensions:
547 ;; Besides supporting the basic Markdown syntax, markdown-mode also
548 ;; includes syntax highlighting for `[[Wiki Links]]` by default. Wiki
549 ;; links may be followed by pressing `C-c C-o` when the point
550 ;; is at a wiki link. Use `M-p` and `M-n` to quickly jump to the
551 ;; previous and next links (including links of other types).
552 ;; Aliased or piped wiki links of the form `[[link text|PageName]]`
553 ;; are also supported. Since some wikis reverse these components, set
554 ;; `markdown-wiki-link-alias-first' to nil to treat them as
555 ;; `[[PageName|link text]]`.
557 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
558 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
559 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
560 ;; You can do this either by using `M-x customize-group markdown`
561 ;; or by placing the following in your `.emacs` file:
563 ;; (defun markdown-custom ()
564 ;; "markdown-mode-hook"
565 ;; (setq markdown-command "markdown | smartypants"))
566 ;; (add-hook 'markdown-mode-hook '(lambda() (markdown-custom)))
568 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
570 ;; Syntax highlighting for mathematical expressions written
571 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
572 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
573 ;; either via customize or by placing `(setq markdown-enable-math t)`
574 ;; in `.emacs`, and then restarting Emacs or calling
575 ;; `markdown-reload-extensions'.
577 ;;; GitHub Flavored Markdown:
579 ;; A [GitHub Flavored Markdown][GFM] (GFM) mode, `gfm-mode', is also
580 ;; available. The GitHub implementation of differs slightly from
581 ;; standard Markdown. The most important differences are that
582 ;; newlines are significant, triggering hard line breaks, and that
583 ;; underscores inside of words (e.g., variable names) need not be
584 ;; escaped. As such, `gfm-mode' turns off `auto-fill-mode' and turns
585 ;; on `visual-line-mode' (or `longlines-mode' if `visual-line-mode' is
586 ;; not available). Underscores inside of words (such as
587 ;; test_variable) will not trigger emphasis.
589 ;; Wiki links in this mode will be treated as on GitHub, with hyphens
590 ;; replacing spaces in filenames and where the first letter of the
591 ;; filename capitalized. For example, `[[wiki link]]' will map to a
592 ;; file named `Wiki-link` with the same extension as the current file.
594 ;; GFM code blocks, with optional programming language keywords, will
595 ;; be highlighted. They can be inserted with `C-c C-s P`. If there
596 ;; is an active region, the text in the region will be placed inside
597 ;; the code block. You will be prompted for the name of the language,
598 ;; but may press enter to continue without naming a language.
600 ;; For a more complete GitHub-flavored markdown experience, consider
601 ;; adding README.md to your `auto-mode-alist':
603 ;; (add-to-list 'auto-mode-alist '("README\\.md\\'" . gfm-mode))
605 ;; For GFM preview can be powered by setting `markdown-command' to
606 ;; use [Docter][]. This may also be configured to work with [Marked][]
607 ;; for `markdown-open-command'.
609 ;; [GFM]: http://github.github.com/github-flavored-markdown/
610 ;; [Docter]: https://github.com/alampros/Docter
612 ;;; Acknowledgments:
614 ;; markdown-mode has benefited greatly from the efforts of the
615 ;; following people:
617 ;; * Cyril Brulebois <cyril.brulebois@enst-bretagne.fr> for Debian packaging.
618 ;; * Conal Elliott <conal@conal.net> for a font-lock regexp patch.
619 ;; * Edward O'Connor <hober0@gmail.com> for a font-lock regexp fix and
620 ;; GitHub Flavored Markdown mode (`gfm-mode').
621 ;; * Greg Bognar <greg_bognar@hms.harvard.edu> for menus and running
622 ;; `markdown' with an active region.
623 ;; * Daniel Burrows <dburrows@debian.org> for filing Debian bug #456592.
624 ;; * Peter S. Galbraith <psg@debian.org> for maintaining `emacs-goodies-el`.
625 ;; * Dmitry Dzhus <mail@sphinx.net.ru> for undefined reference checking.
626 ;; * Carsten Dominik <carsten@orgmode.org> for `org-mode', from which the
627 ;; visibility cycling functionality was derived, and for a bug fix
628 ;; related to `orgtbl-mode'.
629 ;; * Bryan Kyle <bryan.kyle@gmail.com> for indentation code.
630 ;; * Ben Voui <intrigeri@boum.org> for font-lock face customizations.
631 ;; * Ankit Solanki <ankit.solanki@gmail.com> for `longlines.el`
632 ;; compatibility and custom CSS.
633 ;; * Hilko Bengen <bengen@debian.org> for proper XHTML output.
634 ;; * Jose A. Ortega Ruiz <jao@gnu.org> for Emacs 23 fixes.
635 ;; * Nelson Minar <nelson@santafe.edu> for `html-helper-mode', from which
636 ;; comment matching functions were derived.
637 ;; * Alec Resnick <alec@sproutward.org> for bug reports.
638 ;; * Joost Kremers <joostkremers@fastmail.fm> for footnote-handling
639 ;; functions, bug reports regarding indentation, and
640 ;; fixes for byte-compilation warnings.
641 ;; * Peter Williams <pezra@barelyenough.org> for `fill-paragraph'
642 ;; enhancements.
643 ;; * George Ogata <george.ogata@gmail.com> for fixing several
644 ;; byte-compilation warnings.
645 ;; * Eric Merritt <ericbmerritt@gmail.com> for wiki link features.
646 ;; * Philippe Ivaldi <pivaldi@sfr.fr> for XHTML preview
647 ;; customizations and XHTML export.
648 ;; * Jeremiah Dodds <jeremiah.dodds@gmail.com> for supporting
649 ;; Markdown processors which do not accept input from stdin.
650 ;; * Werner Dittmann <werner.dittmann@t-online.de> for bug reports
651 ;; regarding the `cl` dependency and `auto-fill-mode' and indentation.
652 ;; * Scott Pfister <scott.pfister@gmail.com> for generalizing the space
653 ;; substitution character for mapping wiki links to filenames.
654 ;; * Marcin Kasperski <marcin.kasperski@mekk.waw.pl> for a patch to
655 ;; escape shell commands.
656 ;; * Christopher J. Madsen <cjm@cjmweb.net> for patches to fix a match
657 ;; data bug and to prefer `visual-line-mode' in `gfm-mode'.
658 ;; * Shigeru Fukaya <shigeru.fukaya@gmail.com> for better adherence to
659 ;; Emacs Lisp coding conventions.
660 ;; * Donald Ephraim Curtis <dcurtis@milkbox.net> for fixing the `fill-paragraph'
661 ;; regexp, refactoring the compilation and preview functions,
662 ;; heading font-lock generalizations, list renumbering,
663 ;; and kill ring save.
664 ;; * Kevin Porter <kportertx@gmail.com> for wiki link handling in `gfm-mode'.
665 ;; * Max Penet <max.penet@gmail.com> and Peter Eisentraut <peter_e@gmx.net>
666 ;; for an autoload token for `gfm-mode'.
667 ;; * Ian Yang <me@iany.me> for improving the reference definition regex.
668 ;; * Akinori Musha <knu@idaemons.org> for an imenu index function.
669 ;; * Michael Sperber <sperber@deinprogramm.de> for XEmacs fixes.
670 ;; * Francois Gannaz <francois.gannaz@free.fr> for suggesting charset
671 ;; declaration in XHTML output.
672 ;; * Zhenlei Jia <zhenlei.jia@gmail.com> for smart exdention function.
673 ;; * Matus Goljer <dota.keys@gmail.com> for improved wiki link following
674 ;; and GFM code block insertion.
675 ;; * Peter Jones <pjones@pmade.com> for link following functions.
676 ;; * Bryan Fink <bryan.fink@gmail.com> for a bug report regarding
677 ;; externally modified files.
678 ;; * Vegard Vesterheim <vegard.vesterheim@uninett.no> for a bug fix
679 ;; related to `orgtbl-mode'.
680 ;; * Makoto Motohashi <mkt.motohashi@gmail.com> for before- and after-
681 ;; export hooks and unit test improvements.
682 ;; * Michael Dwyer <mdwyer@ehtech.in> for `gfm-mode' underscore regexp.
683 ;; * Chris Lott <chris@chrislott.org> for suggesting reference label
684 ;; completion.
686 ;;; Bugs:
688 ;; Although markdown-mode is developed and tested primarily using
689 ;; GNU Emacs 24, compatibility with earlier Emacsen is also a
690 ;; priority.
692 ;; If you find any bugs in markdown-mode, please construct a test case
693 ;; or a patch and email me at <jrblevin@sdf.org>.
695 ;;; History:
697 ;; markdown-mode was written and is maintained by Jason Blevins. The
698 ;; first version was released on May 24, 2007.
700 ;; * 2007-05-24: Version 1.1
701 ;; * 2007-05-25: Version 1.2
702 ;; * 2007-06-05: [Version 1.3][]
703 ;; * 2007-06-29: Version 1.4
704 ;; * 2007-10-11: [Version 1.5][]
705 ;; * 2008-06-04: [Version 1.6][]
706 ;; * 2009-10-01: [Version 1.7][]
707 ;; * 2011-08-12: [Version 1.8][]
708 ;; * 2011-08-15: [Version 1.8.1][]
709 ;; * 2013-01-25: [Version 1.9][]
710 ;; * 2013-03-18: [Version 2.0][]
712 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
713 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
714 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
715 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
716 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
717 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
718 ;; [Version 1.9]: http://jblevins.org/projects/markdown-mode/rev-1-9
719 ;; [Version 2.0]: http://jblevins.org/projects/markdown-mode/rev-2-0
722 ;;; Code:
724 (require 'easymenu)
725 (require 'outline)
726 (require 'thingatpt)
727 (eval-when-compile (require 'cl))
730 ;;; Constants =================================================================
732 (defconst markdown-mode-version "2.0"
733 "Markdown mode version number.")
735 (defconst markdown-output-buffer-name "*markdown-output*"
736 "Name of temporary buffer for markdown command output.")
739 ;;; Global Variables ==========================================================
741 (defvar markdown-reference-label-history nil
742 "History of used reference labels.")
745 ;;; Customizable Variables ====================================================
747 (defvar markdown-mode-hook nil
748 "Hook run when entering Markdown mode.")
750 (defvar markdown-before-export-hook nil
751 "Hook run before running Markdown to export XHTML output.
752 The hook may modify the buffer, which will be restored to it's
753 original state after exporting is complete.")
755 (defvar markdown-after-export-hook nil
756 "Hook run after XHTML output has been saved.
757 Any changes to the output buffer made by this hook will be saved.")
759 (defgroup markdown nil
760 "Major mode for editing text files in Markdown format."
761 :prefix "markdown-"
762 :group 'wp
763 :link '(url-link "http://jblevins.org/projects/markdown-mode/"))
765 (defcustom markdown-command "markdown"
766 "Command to run markdown."
767 :group 'markdown
768 :type 'string)
770 (defcustom markdown-command-needs-filename nil
771 "Set to non-nil if `markdown-command' does not accept input from stdin.
772 Instead, it will be passed a filename as the final command line
773 option. As a result, you will only be able to run Markdown from
774 buffers which are visiting a file."
775 :group 'markdown
776 :type 'boolean)
778 (defcustom markdown-open-command nil
779 "Command used for opening Markdown files directly.
780 For example, a standalone Markdown previewer. This command will
781 be called with a single argument: the filename of the current
782 buffer."
783 :group 'markdown
784 :type 'string)
786 (defcustom markdown-hr-strings
787 '("-------------------------------------------------------------------------------"
788 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
789 "---------------------------------------"
790 "* * * * * * * * * * * * * * * * * * * *"
791 "---------"
792 "* * * * *")
793 "Strings to use when inserting horizontal rules.
794 The first string in the list will be the default when inserting a
795 horizontal rule. Strings should be listed in decreasing order of
796 prominence (as in headings from level one to six) for use with
797 promotion and demotion functions."
798 :group 'markdown
799 :type 'list)
801 (defcustom markdown-bold-underscore nil
802 "Use two underscores for bold instead of two asterisks."
803 :group 'markdown
804 :type 'boolean)
806 (defcustom markdown-italic-underscore nil
807 "Use underscores for italic instead of asterisks."
808 :group 'markdown
809 :type 'boolean)
811 (defcustom markdown-indent-function 'markdown-indent-line
812 "Function to use to indent."
813 :group 'markdown
814 :type 'function)
816 (defcustom markdown-indent-on-enter t
817 "Automatically indent new lines when enter key is pressed.
818 When this variable is set to t, pressing RET will call
819 `newline-and-indent'. When set to nil, define RET to call
820 `newline' as usual. In the latter case, you can still use
821 auto-indentation by pressing \\[newline-and-indent]."
822 :group 'markdown
823 :type 'boolean)
825 (defcustom markdown-wiki-link-alias-first t
826 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
827 Otherwise, they will be treated as [[PageName|alias text]]."
828 :group 'markdown
829 :type 'boolean)
831 (defcustom markdown-uri-types
832 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
833 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
834 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
835 "Link types for syntax highlighting of URIs."
836 :group 'markdown
837 :type 'list)
839 (defcustom markdown-enable-math nil
840 "Syntax highlighting for inline LaTeX and itex expressions.
841 Set this to a non-nil value to turn on math support by default.
842 Math support can be toggled later using `markdown-enable-math'
843 or \\[markdown-enable-math]."
844 :group 'markdown
845 :type 'boolean
846 :safe 'booleanp)
848 (defcustom markdown-css-path ""
849 "URL of CSS file to link to in the output XHTML."
850 :group 'markdown
851 :type 'string)
853 (defcustom markdown-content-type ""
854 "Content type string for the http-equiv header in XHTML output.
855 When set to a non-empty string, insert the http-equiv attribute.
856 Otherwise, this attribute is omitted."
857 :group 'markdown
858 :type 'string)
860 (defcustom markdown-coding-system nil
861 "Character set string for the http-equiv header in XHTML output.
862 Defaults to `buffer-file-coding-system' (and falling back to
863 `iso-8859-1' when not available). Common settings are `utf-8'
864 and `iso-latin-1'. Use `list-coding-systems' for more choices."
865 :group 'markdown
866 :type 'coding-system)
868 (defcustom markdown-xhtml-header-content ""
869 "Additional content to include in the XHTML <head> block."
870 :group 'markdown
871 :type 'string)
873 (defcustom markdown-xhtml-standalone-regexp
874 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
875 "Regexp indicating whether `markdown-command' output is standalone XHTML."
876 :group 'markdown
877 :type 'regexp)
879 (defcustom markdown-link-space-sub-char "_"
880 "Character to use instead of spaces when mapping wiki links to filenames."
881 :group 'markdown
882 :type 'string)
884 (defcustom markdown-reference-location 'header
885 "Position where new reference definitions are inserted in the document."
886 :group 'markdown
887 :type '(choice (const :tag "At the end of the document" end)
888 (const :tag "Immediately after the current block" immediately)
889 (const :tag "Before next header" header)))
891 (defcustom markdown-footnote-location 'end
892 "Position where new footnotes are inserted in the document."
893 :group 'markdown
894 :type '(choice (const :tag "At the end of the document" end)
895 (const :tag "Immediately after the current block" immediately)
896 (const :tag "Before next header" header)))
899 ;;; Font Lock =================================================================
901 (require 'font-lock)
903 (defvar markdown-italic-face 'markdown-italic-face
904 "Face name to use for italic text.")
906 (defvar markdown-bold-face 'markdown-bold-face
907 "Face name to use for bold text.")
909 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
910 "Face name to use as a base for header delimiters.")
912 (defvar markdown-header-rule-face 'markdown-header-rule-face
913 "Face name to use as a base for header rules.")
915 (defvar markdown-header-face 'markdown-header-face
916 "Face name to use as a base for headers.")
918 (defvar markdown-header-face-1 'markdown-header-face-1
919 "Face name to use for level-1 headers.")
921 (defvar markdown-header-face-2 'markdown-header-face-2
922 "Face name to use for level-2 headers.")
924 (defvar markdown-header-face-3 'markdown-header-face-3
925 "Face name to use for level-3 headers.")
927 (defvar markdown-header-face-4 'markdown-header-face-4
928 "Face name to use for level-4 headers.")
930 (defvar markdown-header-face-5 'markdown-header-face-5
931 "Face name to use for level-5 headers.")
933 (defvar markdown-header-face-6 'markdown-header-face-6
934 "Face name to use for level-6 headers.")
936 (defvar markdown-inline-code-face 'markdown-inline-code-face
937 "Face name to use for inline code.")
939 (defvar markdown-list-face 'markdown-list-face
940 "Face name to use for list markers.")
942 (defvar markdown-blockquote-face 'markdown-blockquote-face
943 "Face name to use for blockquote.")
945 (defvar markdown-pre-face 'markdown-pre-face
946 "Face name to use for preformatted text.")
948 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
949 "Face name to use for programming language identifiers.")
951 (defvar markdown-link-face 'markdown-link-face
952 "Face name to use for links.")
954 (defvar markdown-missing-link-face 'markdown-missing-link-face
955 "Face name to use for links where the linked file does not exist.")
957 (defvar markdown-reference-face 'markdown-reference-face
958 "Face name to use for reference.")
960 (defvar markdown-footnote-face 'markdown-footnote-face
961 "Face name to use for footnote identifiers.")
963 (defvar markdown-url-face 'markdown-url-face
964 "Face name to use for URLs.")
966 (defvar markdown-link-title-face 'markdown-link-title-face
967 "Face name to use for reference link titles.")
969 (defvar markdown-line-break-face 'markdown-line-break-face
970 "Face name to use for hard line breaks.")
972 (defvar markdown-comment-face 'markdown-comment-face
973 "Face name to use for HTML comments.")
975 (defvar markdown-math-face 'markdown-math-face
976 "Face name to use for LaTeX expressions.")
978 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
979 "Face name to use for metadata keys.")
981 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
982 "Face name to use for metadata values.")
984 (defgroup markdown-faces nil
985 "Faces used in Markdown Mode"
986 :group 'markdown
987 :group 'faces)
989 (defface markdown-italic-face
990 '((t (:inherit font-lock-variable-name-face :slant italic)))
991 "Face for italic text."
992 :group 'markdown-faces)
994 (defface markdown-bold-face
995 '((t (:inherit font-lock-variable-name-face :weight bold)))
996 "Face for bold text."
997 :group 'markdown-faces)
999 (defface markdown-header-rule-face
1000 '((t (:inherit font-lock-function-name-face :weight bold)))
1001 "Base face for headers rules."
1002 :group 'markdown-faces)
1004 (defface markdown-header-delimiter-face
1005 '((t (:inherit font-lock-function-name-face :weight bold)))
1006 "Base face for headers hash delimiter."
1007 :group 'markdown-faces)
1009 (defface markdown-header-face
1010 '((t (:inherit font-lock-function-name-face :weight bold)))
1011 "Base face for headers."
1012 :group 'markdown-faces)
1014 (defface markdown-header-face-1
1015 '((t (:inherit markdown-header-face)))
1016 "Face for level-1 headers."
1017 :group 'markdown-faces)
1019 (defface markdown-header-face-2
1020 '((t (:inherit markdown-header-face)))
1021 "Face for level-2 headers."
1022 :group 'markdown-faces)
1024 (defface markdown-header-face-3
1025 '((t (:inherit markdown-header-face)))
1026 "Face for level-3 headers."
1027 :group 'markdown-faces)
1029 (defface markdown-header-face-4
1030 '((t (:inherit markdown-header-face)))
1031 "Face for level-4 headers."
1032 :group 'markdown-faces)
1034 (defface markdown-header-face-5
1035 '((t (:inherit markdown-header-face)))
1036 "Face for level-5 headers."
1037 :group 'markdown-faces)
1039 (defface markdown-header-face-6
1040 '((t (:inherit markdown-header-face)))
1041 "Face for level-6 headers."
1042 :group 'markdown-faces)
1044 (defface markdown-inline-code-face
1045 '((t (:inherit font-lock-constant-face)))
1046 "Face for inline code."
1047 :group 'markdown-faces)
1049 (defface markdown-list-face
1050 '((t (:inherit font-lock-builtin-face)))
1051 "Face for list item markers."
1052 :group 'markdown-faces)
1054 (defface markdown-blockquote-face
1055 '((t (:inherit font-lock-doc-face)))
1056 "Face for blockquote sections."
1057 :group 'markdown-faces)
1059 (defface markdown-pre-face
1060 '((t (:inherit font-lock-constant-face)))
1061 "Face for preformatted text."
1062 :group 'markdown-faces)
1064 (defface markdown-language-keyword-face
1065 '((t (:inherit font-lock-type-face)))
1066 "Face for programming language identifiers."
1067 :group 'markdown-faces)
1069 (defface markdown-link-face
1070 '((t (:inherit font-lock-keyword-face)))
1071 "Face for links."
1072 :group 'markdown-faces)
1074 (defface markdown-missing-link-face
1075 '((t (:inherit font-lock-warning-face)))
1076 "Face for missing links."
1077 :group 'markdown-faces)
1079 (defface markdown-reference-face
1080 '((t (:inherit font-lock-type-face)))
1081 "Face for link references."
1082 :group 'markdown-faces)
1084 (defface markdown-footnote-face
1085 '((t (:inherit font-lock-keyword-face)))
1086 "Face for footnote markers."
1087 :group 'markdown-faces)
1089 (defface markdown-url-face
1090 '((t (:inherit font-lock-string-face)))
1091 "Face for URLs."
1092 :group 'markdown-faces)
1094 (defface markdown-link-title-face
1095 '((t (:inherit font-lock-comment-face)))
1096 "Face for reference link titles."
1097 :group 'markdown-faces)
1099 (defface markdown-line-break-face
1100 '((t (:inherit font-lock-constant-face :underline t)))
1101 "Face for hard line breaks."
1102 :group 'markdown-faces)
1104 (defface markdown-comment-face
1105 '((t (:inherit font-lock-comment-face)))
1106 "Face for HTML comments."
1107 :group 'markdown-faces)
1109 (defface markdown-math-face
1110 '((t (:inherit font-lock-string-face)))
1111 "Face for LaTeX expressions."
1112 :group 'markdown-faces)
1114 (defface markdown-metadata-key-face
1115 '((t (:inherit font-lock-variable-name-face)))
1116 "Face for metadata keys."
1117 :group 'markdown-faces)
1119 (defface markdown-metadata-value-face
1120 '((t (:inherit font-lock-string-face)))
1121 "Face for metadata values."
1122 :group 'markdown-faces)
1124 (defconst markdown-regex-link-inline
1125 "\\(!\\)?\\(\\[\\([^]^][^]]*\\|\\)\\]\\)\\((\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?)\\)"
1126 "Regular expression for a [text](file) or an image link ![text](file).
1127 Group 1 matches the leading exclamation point, if any.
1128 Group 2 matchs the entire square bracket term, including the text.
1129 Group 3 matches the text inside the square brackets.
1130 Group 4 matches the entire parenthesis term, including the URL and title.
1131 Group 5 matches the URL.
1132 Group 6 matches (optional) title.")
1134 (defconst markdown-regex-link-reference
1135 "\\(!\\)?\\(\\[\\([^]^][^]]*\\|\\)\\]\\)[ ]?\\(\\[\\([^]]*?\\)\\]\\)"
1136 "Regular expression for a reference link [text][id].
1137 Group 1 matches the leading exclamation point, if any.
1138 Group 2 matchs the entire first square bracket term, including the text.
1139 Group 3 matches the text inside the square brackets.
1140 Group 4 matches the entire second square bracket term.
1141 Group 5 matches the reference label.")
1143 (defconst markdown-regex-reference-definition
1144 "^ \\{0,3\\}\\(\\[[^\n]+?\\]\\):\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
1145 "Regular expression for a link definition [id]: ...")
1147 (defconst markdown-regex-footnote
1148 "\\(\\[\\^.+?\\]\\)"
1149 "Regular expression for a footnote marker [^fn].")
1151 (defconst markdown-regex-header
1152 "^\\(?:\\(.+\\)\n\\(=+\\)\\|\\(.+\\)\n\\(-+\\)\\|\\(#+\\)\\s-*\\(.*?\\)\\s-*?\\(#*\\)\\)$"
1153 "Regexp identifying Markdown headers.")
1155 (defconst markdown-regex-header-1-atx
1156 "^\\(#\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1157 "Regular expression for level 1 atx-style (hash mark) headers.")
1159 (defconst markdown-regex-header-2-atx
1160 "^\\(##\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1161 "Regular expression for level 2 atx-style (hash mark) headers.")
1163 (defconst markdown-regex-header-3-atx
1164 "^\\(###\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1165 "Regular expression for level 3 atx-style (hash mark) headers.")
1167 (defconst markdown-regex-header-4-atx
1168 "^\\(####\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1169 "Regular expression for level 4 atx-style (hash mark) headers.")
1171 (defconst markdown-regex-header-5-atx
1172 "^\\(#####\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1173 "Regular expression for level 5 atx-style (hash mark) headers.")
1175 (defconst markdown-regex-header-6-atx
1176 "^\\(######\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1177 "Regular expression for level 6 atx-style (hash mark) headers.")
1179 (defconst markdown-regex-header-1-setext
1180 "^\\(.*\\)\n\\(=+\\)$"
1181 "Regular expression for level 1 setext-style (underline) headers.")
1183 (defconst markdown-regex-header-2-setext
1184 "^\\(.*\\)\n\\(-+\\)$"
1185 "Regular expression for level 2 setext-style (underline) headers.")
1187 (defconst markdown-regex-header-setext
1188 "^\\(.+\\)\n\\(\\(?:=\\|-\\)+\\)$"
1189 "Regular expression for generic setext-style (underline) headers.")
1191 (defconst markdown-regex-header-atx
1192 "^\\(#+\\)[ \t]*\\(.*?\\)[ \t]*\\(#*\\)$"
1193 "Regular expression for generic atx-style (hash mark) headers.")
1195 (defconst markdown-regex-hr
1196 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1197 "Regular expression for matching Markdown horizontal rules.")
1199 (defconst markdown-regex-code
1200 "\\(\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(.\\|\n[^\n]\\)*?[^`]\\)\\3\\)\\([^`]\\|\\'\\)"
1201 "Regular expression for matching inline code fragments.
1203 The first group ensures that the leading backquote character
1204 is not escaped. The group \\(.\\|\n[^\n]\\) matches any
1205 character, including newlines, but not two newlines in a row.
1206 The final group requires that the character following the code
1207 fragment is not a backquote.")
1209 (defconst markdown-regex-pre
1210 "^\\( \\|\t\\).*$"
1211 "Regular expression for matching preformatted text sections.")
1213 (defconst markdown-regex-list
1214 "^\\([ \t]*\\)\\([0-9]+\\.\\|[\\*\\+-]\\)\\([ \t]+\\)"
1215 "Regular expression for matching list items.")
1217 (defconst markdown-regex-bold
1218 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1219 "Regular expression for matching bold text.
1220 Group 1 matches the character before the opening asterisk or
1221 underscore, if any, ensuring that it is not a backslash escape.
1222 Group 2 matches the entire expression, including delimiters.
1223 Groups 3 and 5 matches the opening and closing delimiters.
1224 Group 4 matches the text inside the delimiters.")
1226 (defconst markdown-regex-italic
1227 "\\(^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1228 "Regular expression for matching italic text.
1229 Group 1 matches the character before the opening asterisk or
1230 underscore, if any, ensuring that it is not a backslash escape.
1231 Group 2 matches the entire expression, including delimiters.
1232 Groups 3 and 5 matches the opening and closing delimiters.
1233 Group 4 matches the text inside the delimiters.")
1235 (defconst markdown-regex-gfm-italic
1236 "\\(^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\3\\|[^ ]\\(.\\|\n[^\n]\\)*?[^\\ ]\\3\\)\\)"
1237 "Regular expression for matching italic text in GitHub-flavored Markdown.
1238 Underscores in words are not treated as special.")
1240 (defconst markdown-regex-blockquote
1241 "^[ \t]*\\(>\\).*$"
1242 "Regular expression for matching blockquote lines.")
1244 (defconst markdown-regex-line-break
1245 "[^ \n\t][ \t]*\\( \\)$"
1246 "Regular expression for matching line breaks.")
1248 (defconst markdown-regex-wiki-link
1249 "\\(?:^\\|[^\\]\\)\\(\\[\\[\\([^]|]+\\)\\(|\\([^]]+\\)\\)?\\]\\]\\)"
1250 "Regular expression for matching wiki links.
1251 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1252 wiki links of the form [[PageName|link text]]. In this regular
1253 expression, group 1 matches the entire link, including square
1254 brackets, group 2 matches the first component of the wiki link
1255 and group 4 matches the second component, after the pipe, when
1256 present. The meanings of the first and second components depend
1257 on the value of `markdown-wiki-link-alias-first'.")
1259 (defconst markdown-regex-uri
1260 (concat (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+")
1261 "Regular expression for matching inline URIs.")
1263 (defconst markdown-regex-angle-uri
1264 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1265 "Regular expression for matching inline URIs in angle brackets.")
1267 (defconst markdown-regex-email
1268 "<\\(\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+\\)>"
1269 "Regular expression for matching inline email addresses.")
1271 (defconst markdown-regex-link-generic
1272 (concat "\\(?:" markdown-regex-wiki-link
1273 "\\|" markdown-regex-link-inline
1274 "\\|" markdown-regex-link-reference
1275 "\\|" markdown-regex-angle-uri "\\)")
1276 "Regular expression for matching any recognized link.")
1278 (defconst markdown-regex-block-separator
1279 "\\(\\`\\|\\(\n[ \t]*\n\\)[^\n \t]\\)"
1280 "Regular expression for matching block boundaries.")
1282 (defconst markdown-regex-math-inline
1283 "\\(^\\|[^\\]\\)\\(\\$\\($\\([^\\$]\\|\\\\.\\)*\\$\\|\\([^\\$]\\|\\\\.\\)*\\)\\$\\)"
1284 "Regular expression for itex $..$ or $$..$$ math mode expressions.")
1286 (defconst markdown-regex-math-display
1287 "^\\\\\\[\\(.\\|\n\\)*?\\\\\\]$"
1288 "Regular expression for itex \[..\] display mode expressions.")
1290 (defconst markdown-regex-multimarkdown-metadata
1291 "^\\([[:alpha:]][[:alpha:] _-]*?\\):[ \t]*\\(.*\\)$"
1292 "Regular expression for matching MultiMarkdown metadata.")
1294 (defconst markdown-regex-pandoc-metadata
1295 "^\\(%\\)[ \t]*\\(.*\\)$"
1296 "Regular expression for matching Pandoc metadata.")
1298 (defvar markdown-mode-font-lock-keywords-basic
1299 (list
1300 (cons 'markdown-match-pre-blocks '((0 markdown-pre-face)))
1301 (cons 'markdown-match-fenced-code-blocks '((0 markdown-pre-face)))
1302 (cons markdown-regex-blockquote 'markdown-blockquote-face)
1303 (cons markdown-regex-header-1-setext '((1 markdown-header-face-1)
1304 (2 markdown-header-rule-face)))
1305 (cons markdown-regex-header-2-setext '((1 markdown-header-face-2)
1306 (2 markdown-header-rule-face)))
1307 (cons markdown-regex-header-6-atx '((1 markdown-header-delimiter-face)
1308 (2 markdown-header-face-6)
1309 (3 markdown-header-delimiter-face)))
1310 (cons markdown-regex-header-5-atx '((1 markdown-header-delimiter-face)
1311 (2 markdown-header-face-5)
1312 (3 markdown-header-delimiter-face)))
1313 (cons markdown-regex-header-4-atx '((1 markdown-header-delimiter-face)
1314 (2 markdown-header-face-4)
1315 (3 markdown-header-delimiter-face)))
1316 (cons markdown-regex-header-3-atx '((1 markdown-header-delimiter-face)
1317 (2 markdown-header-face-3)
1318 (3 markdown-header-delimiter-face)))
1319 (cons markdown-regex-header-2-atx '((1 markdown-header-delimiter-face)
1320 (2 markdown-header-face-2)
1321 (3 markdown-header-delimiter-face)))
1322 (cons markdown-regex-header-1-atx '((1 markdown-header-delimiter-face)
1323 (2 markdown-header-face-1)
1324 (3 markdown-header-delimiter-face)))
1325 (cons 'markdown-match-multimarkdown-metadata '((1 markdown-metadata-key-face)
1326 (2 markdown-metadata-value-face)))
1327 (cons 'markdown-match-pandoc-metadata '((1 markdown-comment-face)
1328 (2 markdown-metadata-value-face)))
1329 (cons markdown-regex-hr 'markdown-header-face)
1330 (cons 'markdown-match-comments '((0 markdown-comment-face)))
1331 (cons 'markdown-match-code '((0 markdown-inline-code-face)))
1332 (cons markdown-regex-angle-uri 'markdown-link-face)
1333 (cons markdown-regex-uri 'markdown-link-face)
1334 (cons markdown-regex-email 'markdown-link-face)
1335 (cons markdown-regex-list '(2 markdown-list-face))
1336 (cons markdown-regex-footnote 'markdown-footnote-face)
1337 (cons markdown-regex-link-inline '((1 markdown-link-face t t)
1338 (2 markdown-link-face t)
1339 (4 markdown-url-face t)
1340 (6 markdown-link-title-face t t)))
1341 (cons markdown-regex-link-reference '((1 markdown-link-face t t)
1342 (2 markdown-link-face t)
1343 (4 markdown-reference-face t)))
1344 (cons markdown-regex-reference-definition '((1 markdown-reference-face t)
1345 (2 markdown-url-face t)
1346 (3 markdown-link-title-face t)))
1347 (cons markdown-regex-bold '(2 markdown-bold-face))
1348 (cons markdown-regex-line-break '(1 markdown-line-break-face prepend))
1350 "Syntax highlighting for Markdown files.")
1352 (defvar markdown-mode-font-lock-keywords-core
1353 (list
1354 (cons markdown-regex-italic '(2 markdown-italic-face))
1356 "Additional syntax highlighting for Markdown files.
1357 Includes features which are overridden by some variants.")
1359 (defconst markdown-mode-font-lock-keywords-math
1360 (list
1361 ;; Math mode $..$ or $$..$$
1362 (cons markdown-regex-math-inline '(2 markdown-math-face))
1363 ;; Display mode equations with brackets: \[ \]
1364 (cons markdown-regex-math-display 'markdown-math-face)
1365 ;; Equation reference (eq:foo)
1366 (cons "(eq:[[:alnum:]:_]+)" 'markdown-reference-face)
1367 ;; Equation reference \eqref{foo}
1368 (cons "\\\\eqref{[[:alnum:]:_]+}" 'markdown-reference-face))
1369 "Syntax highlighting for LaTeX and itex fragments.")
1371 (defvar markdown-mode-font-lock-keywords nil
1372 "Default highlighting expressions for Markdown mode.
1373 This variable is defined as a buffer-local variable for dynamic
1374 extension support.")
1376 ;; Footnotes
1377 (defvar markdown-footnote-counter 0
1378 "Counter for footnote numbers.")
1379 (make-variable-buffer-local 'markdown-footnote-counter)
1381 (defconst markdown-footnote-chars
1382 "[[:alnum:]-]"
1383 "Regular expression maching any character that is allowed in a footnote identifier.")
1386 ;;; Compatibility =============================================================
1388 (defun markdown-replace-regexp-in-string (regexp rep string)
1389 "Replace ocurrences of REGEXP with REP in STRING.
1390 This is a compatibility wrapper to provide `replace-regexp-in-string'
1391 in XEmacs 21."
1392 (if (featurep 'xemacs)
1393 (replace-in-string string regexp rep)
1394 (replace-regexp-in-string regexp rep string)))
1396 ;; `markdown-use-region-p' is a compatibility function which checks
1397 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
1398 (eval-and-compile
1399 (cond
1400 ;; Emacs 23 and newer
1401 ((fboundp 'use-region-p)
1402 (defalias 'markdown-use-region-p 'use-region-p))
1403 ;; Older Emacsen
1404 ((and (boundp 'transient-mark-mode) (boundp 'mark-active))
1405 (defun markdown-use-region-p ()
1406 "Compatibility wrapper to provide `use-region-p'."
1407 (and transient-mark-mode mark-active)))
1408 ;; XEmacs
1409 ((fboundp 'region-active-p)
1410 (defalias 'markdown-use-region-p 'region-active-p))))
1412 (defun markdown-use-buttons-p ()
1413 "Determine whether this Emacs supports buttons."
1414 (or (featurep 'button) (locate-library "button")))
1417 ;;; Markdown Parsing Functions ================================================
1419 (defun markdown-cur-line-blank-p ()
1420 "Return t if the current line is blank and nil otherwise."
1421 (save-excursion
1422 (beginning-of-line)
1423 (re-search-forward "^\\s *$" (line-end-position) t)))
1425 (defun markdown-prev-line-blank-p ()
1426 "Return t if the previous line is blank and nil otherwise.
1427 If we are at the first line, then consider the previous line to be blank."
1428 (or (= (line-beginning-position) (point-min))
1429 (save-excursion
1430 (forward-line -1)
1431 (markdown-cur-line-blank-p))))
1433 (defun markdown-next-line-blank-p ()
1434 "Return t if the next line is blank and nil otherwise.
1435 If we are at the last line, then consider the next line to be blank."
1436 (or (= (line-end-position) (point-max))
1437 (save-excursion
1438 (forward-line 1)
1439 (markdown-cur-line-blank-p))))
1441 (defun markdown-prev-line-indent-p ()
1442 "Return t if the previous line is indented and nil otherwise."
1443 (save-excursion
1444 (forward-line -1)
1445 (goto-char (line-beginning-position))
1446 (if (re-search-forward "^\\s " (line-end-position) t) t)))
1448 (defun markdown-cur-line-indent ()
1449 "Return the number of leading whitespace characters in the current line."
1450 (save-match-data
1451 (save-excursion
1452 (goto-char (line-beginning-position))
1453 (re-search-forward "^[ \t]+" (line-end-position) t)
1454 (current-column))))
1456 (defun markdown-prev-line-indent ()
1457 "Return the number of leading whitespace characters in the previous line."
1458 (save-excursion
1459 (forward-line -1)
1460 (markdown-cur-line-indent)))
1462 (defun markdown-next-line-indent ()
1463 "Return the number of leading whitespace characters in the next line."
1464 (save-excursion
1465 (forward-line 1)
1466 (markdown-cur-line-indent)))
1468 (defun markdown-cur-non-list-indent ()
1469 "Return beginning position of list item text (not including the list marker).
1470 Return nil if the current line is not the beginning of a list item."
1471 (save-match-data
1472 (save-excursion
1473 (beginning-of-line)
1474 (when (re-search-forward markdown-regex-list (line-end-position) t)
1475 (current-column)))))
1477 (defun markdown-prev-non-list-indent ()
1478 "Return position of the first non-list-marker on the previous line."
1479 (save-excursion
1480 (forward-line -1)
1481 (markdown-cur-non-list-indent)))
1483 (defun markdown-new-baseline-p ()
1484 "Determine if the current line begins a new baseline level."
1485 (save-excursion
1486 (beginning-of-line)
1487 (save-match-data
1488 (or (looking-at markdown-regex-header)
1489 (looking-at markdown-regex-hr)
1490 (and (null (markdown-cur-non-list-indent))
1491 (= (markdown-cur-line-indent) 0)
1492 (markdown-prev-line-blank-p))))))
1494 (defun markdown-search-backward-baseline ()
1495 "Search backward baseline point with no indentation and not a list item."
1496 (end-of-line)
1497 (let (stop)
1498 (while (not (or stop (bobp)))
1499 (re-search-backward markdown-regex-block-separator nil t)
1500 (when (match-end 2)
1501 (goto-char (match-end 2))
1502 (cond
1503 ((markdown-new-baseline-p)
1504 (setq stop t))
1505 ((looking-at markdown-regex-list)
1506 (setq stop nil))
1507 (t (setq stop t)))))))
1509 (defun markdown-update-list-levels (marker indent levels)
1510 "Update list levels given list MARKER, block INDENT, and current LEVELS.
1511 Here, MARKER is a string representing the type of list, INDENT is an integer
1512 giving the indentation, in spaces, of the current block, and LEVELS is a
1513 list of the indentation levels of parent list items. When LEVELS is nil,
1514 it means we are at baseline (not inside of a nested list)."
1515 (cond
1516 ;; New list item at baseline.
1517 ((and marker (null levels))
1518 (setq levels (list indent)))
1519 ;; List item with greater indentation (four or more spaces).
1520 ;; Increase list level.
1521 ((and marker (>= indent (+ (car levels) 4)))
1522 (setq levels (cons indent levels)))
1523 ;; List item with greater or equal indentation (less than four spaces).
1524 ;; Do not increase list level.
1525 ((and marker (>= indent (car levels)))
1526 levels)
1527 ;; Lesser indentation level.
1528 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
1529 ;; indentation could move back more than one list level). Note
1530 ;; that this block need not be the beginning of list item.
1531 ((< indent (car levels))
1532 (while (and (> (length levels) 1)
1533 (< indent (+ (cadr levels) 4)))
1534 (setq levels (cdr levels)))
1535 levels)
1536 ;; Otherwise, do nothing.
1537 (t levels)))
1539 (defun markdown-calculate-list-levels ()
1540 "Calculate list levels at point.
1541 Return a list of the form (n1 n2 n3 ...) where n1 is the
1542 indentation of the deepest nested list item in the branch of
1543 the list at the point, n2 is the indentation of the parent
1544 list item, and so on. The depth of the list item is therefore
1545 the length of the returned list. If the point is not at or
1546 immediately after a list item, return nil."
1547 (save-excursion
1548 (let ((first (point)) levels indent pre-regexp)
1549 ;; Find a baseline point with zero list indentation
1550 (markdown-search-backward-baseline)
1551 ;; Search for all list items between baseline and LOC
1552 (while (and (< (point) first)
1553 (re-search-forward markdown-regex-list first t))
1554 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
1555 (beginning-of-line)
1556 (cond
1557 ;; Make sure this is not a header or hr
1558 ((markdown-new-baseline-p) (setq levels nil))
1559 ;; Make sure this is not a line from a pre block
1560 ((looking-at pre-regexp))
1561 ;; If not, then update levels
1563 (setq indent (markdown-cur-line-indent))
1564 (setq levels (markdown-update-list-levels (match-string 2)
1565 indent levels))))
1566 (end-of-line))
1567 levels)))
1569 (defun markdown-prev-list-item (level)
1570 "Search backward from point for a list item with indentation LEVEL.
1571 Set point to the beginning of the item, and return point, or nil
1572 upon failure."
1573 (let (bounds indent prev)
1574 (setq prev (point))
1575 (forward-line -1)
1576 (setq indent (markdown-cur-line-indent))
1577 (while
1578 (cond
1579 ;; Stop at beginning of buffer
1580 ((bobp) (setq prev nil))
1581 ;; Continue if current line is blank
1582 ((markdown-cur-line-blank-p) t)
1583 ;; List item
1584 ((and (looking-at markdown-regex-list)
1585 (setq bounds (markdown-cur-list-item-bounds)))
1586 (cond
1587 ;; Continue at item with greater indentation
1588 ((> (nth 3 bounds) level) t)
1589 ;; Stop and return point at item of equal indentation
1590 ((= (nth 3 bounds) level)
1591 (setq prev (point))
1592 nil)
1593 ;; Stop and return nil at item with lesser indentation
1594 ((< (nth 3 bounds) level)
1595 (setq prev nil)
1596 nil)))
1597 ;; Continue while indentation is the same or greater
1598 ((>= indent level) t)
1599 ;; Stop if current indentation is less than list item
1600 ;; and the next is blank
1601 ((and (< indent level)
1602 (markdown-next-line-blank-p))
1603 (setq prev nil))
1604 ;; Stop at a header
1605 ((looking-at markdown-regex-header) (setq prev nil))
1606 ;; Stop at a horizontal rule
1607 ((looking-at markdown-regex-hr) (setq prev nil))
1608 ;; Otherwise, continue.
1609 (t t))
1610 (forward-line -1)
1611 (setq indent (markdown-cur-line-indent)))
1612 prev))
1614 (defun markdown-next-list-item (level)
1615 "Search forward from point for the next list item with indentation LEVEL.
1616 Set point to the beginning of the item, and return point, or nil
1617 upon failure."
1618 (let (bounds indent prev next)
1619 (setq next (point))
1620 (forward-line)
1621 (setq indent (markdown-cur-line-indent))
1622 (while
1623 (cond
1624 ;; Stop at end of the buffer.
1625 ((eobp) (setq prev nil))
1626 ;; Continue if the current line is blank
1627 ((markdown-cur-line-blank-p) t)
1628 ;; List item
1629 ((and (looking-at markdown-regex-list)
1630 (setq bounds (markdown-cur-list-item-bounds)))
1631 (cond
1632 ;; Continue at item with greater indentation
1633 ((> (nth 3 bounds) level) t)
1634 ;; Stop and return point at item of equal indentation
1635 ((= (nth 3 bounds) level)
1636 (setq next (point))
1637 nil)
1638 ;; Stop and return nil at item with lesser indentation
1639 ((< (nth 3 bounds) level)
1640 (setq next nil)
1641 nil)))
1642 ;; Continue while indentation is the same or greater
1643 ((>= indent level) t)
1644 ;; Stop if current indentation is less than list item
1645 ;; and the previous line was blank.
1646 ((and (< indent level)
1647 (markdown-prev-line-blank-p))
1648 (setq next nil))
1649 ;; Stop at a header
1650 ((looking-at markdown-regex-header) (setq next nil))
1651 ;; Stop at a horizontal rule
1652 ((looking-at markdown-regex-hr) (setq next nil))
1653 ;; Otherwise, continue.
1654 (t t))
1655 (forward-line)
1656 (setq indent (markdown-cur-line-indent)))
1657 next))
1659 (defun markdown-cur-list-item-end (level)
1660 "Move to the end of the current list item with nonlist indentation LEVEL.
1661 If the point is not in a list item, do nothing."
1662 (let (indent)
1663 (forward-line)
1664 (setq indent (markdown-cur-line-indent))
1665 (while
1666 (cond
1667 ;; Stop at end of the buffer.
1668 ((eobp) nil)
1669 ;; Continue if the current line is blank
1670 ((markdown-cur-line-blank-p) t)
1671 ;; Continue while indentation is the same or greater
1672 ((>= indent level) t)
1673 ;; Stop if current indentation is less than list item
1674 ;; and the previous line was blank.
1675 ((and (< indent level)
1676 (markdown-prev-line-blank-p))
1677 nil)
1678 ;; Stop at a new list item of the same or lesser indentation
1679 ((looking-at markdown-regex-list) nil)
1680 ;; Stop at a header
1681 ((looking-at markdown-regex-header) nil)
1682 ;; Stop at a horizontal rule
1683 ((looking-at markdown-regex-hr) nil)
1684 ;; Otherwise, continue.
1685 (t t))
1686 (forward-line)
1687 (setq indent (markdown-cur-line-indent)))
1688 ;; Don't skip over whitespace for empty list items (marker and
1689 ;; whitespace only), just move to end of whitespace.
1690 (if (looking-back (concat markdown-regex-list "\\s-*"))
1691 (goto-char (match-end 3))
1692 (skip-syntax-backward "-"))))
1694 (defun markdown-cur-list-item-bounds ()
1695 "Return bounds and indentation of the current list item.
1696 Return a list of the form (begin end indent nonlist-indent marker).
1697 If the point is not inside a list item, return nil.
1698 Leave match data intact for `markdown-regex-list'."
1699 (let (cur prev-begin prev-end indent nonlist-indent marker)
1700 ;; Store current location
1701 (setq cur (point))
1702 ;; Verify that cur is between beginning and end of item
1703 (save-excursion
1704 (end-of-line)
1705 (when (re-search-backward markdown-regex-list nil t)
1706 (setq prev-begin (match-beginning 0))
1707 (setq indent (length (match-string 1)))
1708 (setq nonlist-indent (length (match-string 0)))
1709 (setq marker (concat (match-string 2) (match-string 3)))
1710 (save-match-data
1711 (markdown-cur-list-item-end nonlist-indent)
1712 (setq prev-end (point)))
1713 (when (and (>= cur prev-begin)
1714 (<= cur prev-end)
1715 nonlist-indent)
1716 (list prev-begin prev-end indent nonlist-indent marker))))))
1718 (defun markdown-bounds-of-thing-at-point (thing)
1719 "Call `bounds-of-thing-at-point' for THING with slight modifications.
1720 Does not include trailing newlines when THING is 'line. Handles the
1721 end of buffer case by setting both endpoints equal to the value of
1722 `point-max', since an empty region will trigger empty markup insertion.
1723 Return bounds of form (beg . end) if THING is found, or nil otherwise."
1724 (let* ((bounds (bounds-of-thing-at-point thing))
1725 (a (car bounds))
1726 (b (cdr bounds)))
1727 (when bounds
1728 (when (eq thing 'line)
1729 (cond ((and (eobp) (markdown-cur-line-blank-p))
1730 (setq a b))
1731 ((char-equal (char-before b) ?\^J)
1732 (setq b (1- b)))))
1733 (cons a b))))
1735 (defun markdown-reference-definition (reference)
1736 "Find out whether Markdown REFERENCE is defined.
1737 REFERENCE should include the square brackets, like [this].
1738 When REFERENCE is defined, return a list of the form (text start end)
1739 containing the definition text itself followed by the start and end
1740 locations of the text. Otherwise, return nil.
1741 Leave match data for `markdown-regex-reference-definition'
1742 intact additional processing."
1743 (let ((reference (downcase reference)))
1744 (save-excursion
1745 (goto-char (point-min))
1746 (catch 'found
1747 (while (re-search-forward markdown-regex-reference-definition nil t)
1748 (when (string= reference (downcase (match-string-no-properties 1)))
1749 (throw 'found
1750 (list (match-string-no-properties 2)
1751 (match-beginning 2) (match-end 2)))))))))
1753 (defun markdown-get-defined-references ()
1754 "Return a list of all defined reference labels (including square brackets)."
1755 (save-excursion
1756 (goto-char (point-min))
1757 (let (refs)
1758 (while (re-search-forward markdown-regex-reference-definition nil t)
1759 (let ((target (match-string-no-properties 1)))
1760 (add-to-list 'refs target t)))
1761 refs)))
1763 (defun markdown-code-at-point-p ()
1764 "Return non-nil if the point is at an inline code fragment.
1765 Return nil otherwise. Set match data according to
1766 `markdown-match-code' upon success.
1767 This function searches the block for a code fragment that
1768 contains the point using `markdown-match-code'. We do this
1769 because `thing-at-point-looking-at' does not work reliably with
1770 `markdown-regex-code'."
1771 (interactive)
1772 (save-excursion
1773 (let ((old-point (point))
1774 (end-of-block (progn (markdown-end-of-block) (point)))
1775 found)
1776 (markdown-beginning-of-block)
1777 (while (and (markdown-match-code end-of-block)
1778 (setq found t)
1779 (< (match-end 0) old-point)))
1780 (and found ; matched something
1781 (<= (match-beginning 0) old-point) ; match contains old-point
1782 (>= (match-end 0) old-point)))))
1785 ;;; Markdown Font Lock Matching Functions =====================================
1787 (defun markdown-match-comments (last)
1788 "Match HTML comments from the point to LAST."
1789 (cond ((search-forward "<!--" last t)
1790 (backward-char 4)
1791 (let ((beg (point)))
1792 (cond ((search-forward-regexp "--[ \t]*>" last t)
1793 (set-match-data (list beg (point)))
1795 (t nil))))
1796 (t nil)))
1798 (defun markdown-match-code (last)
1799 "Match inline code from the point to LAST."
1800 (unless (bobp)
1801 (backward-char 1))
1802 (cond ((re-search-forward markdown-regex-code last t)
1803 (set-match-data (list (match-beginning 2) (match-end 2)
1804 (match-beginning 4) (match-end 4)))
1805 (goto-char (match-end 0))
1807 (t (forward-char 2) nil)))
1809 (defun markdown-match-pre-blocks (last)
1810 "Match Markdown pre blocks from point to LAST."
1811 (let ((levels (markdown-calculate-list-levels))
1812 indent pre-regexp end-regexp begin end stop)
1813 (while (and (< (point) last) (not end))
1814 ;; Search for a region with sufficient indentation
1815 (if (null levels)
1816 (setq indent 1)
1817 (setq indent (1+ (length levels))))
1818 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1819 (setq end-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1821 (cond
1822 ;; If not at the beginning of a line, move forward
1823 ((not (bolp)) (forward-line))
1824 ;; Move past blank lines
1825 ((markdown-cur-line-blank-p) (forward-line))
1826 ;; At headers and horizontal rules, reset levels
1827 ((markdown-new-baseline-p) (forward-line) (setq levels nil))
1828 ;; If the current line has sufficient indentation, mark out pre block
1829 ((looking-at pre-regexp)
1830 (setq begin (match-beginning 0))
1831 (while (and (or (looking-at pre-regexp) (markdown-cur-line-blank-p))
1832 (not (eobp)))
1833 (forward-line))
1834 (setq end (point)))
1835 ;; If current line has a list marker, update levels, move to end of block
1836 ((looking-at markdown-regex-list)
1837 (setq levels (markdown-update-list-levels
1838 (match-string 2) (markdown-cur-line-indent) levels))
1839 (markdown-end-of-block-element))
1840 ;; If this is the end of the indentation level, adjust levels accordingly.
1841 ;; Only match end of indentation level if levels is not the empty list.
1842 ((and (car levels) (looking-at end-regexp))
1843 (setq levels (markdown-update-list-levels
1844 nil (markdown-cur-line-indent) levels))
1845 (markdown-end-of-block-element))
1846 (t (markdown-end-of-block-element))))
1848 (if (not (and begin end))
1849 ;; Return nil if no pre block was found
1851 ;; Set match data and return t upon success
1852 (set-match-data (list begin end))
1853 t)))
1855 (defun markdown-match-fenced-code-blocks (last)
1856 "Match fenced code blocks from the point to LAST."
1857 (cond ((search-forward-regexp "^\\([~]\\{3,\\}\\)" last t)
1858 (beginning-of-line)
1859 (let ((beg (point)))
1860 (forward-line)
1861 (cond ((search-forward-regexp
1862 (concat "^" (match-string 1) "~*") last t)
1863 (set-match-data (list beg (point)))
1865 (t nil))))
1866 (t nil)))
1868 (defun markdown-match-gfm-code-blocks (last)
1869 "Match GFM quoted code blocks from point to LAST."
1870 (let (open lang body close all)
1871 (cond ((and (eq major-mode 'gfm-mode)
1872 (search-forward-regexp "^\\(```\\)\\(\\w+\\)?$" last t))
1873 (beginning-of-line)
1874 (setq open (list (match-beginning 1) (match-end 1))
1875 lang (list (match-beginning 2) (match-end 2)))
1876 (forward-line)
1877 (setq body (list (point)))
1878 (cond ((search-forward-regexp "^```$" last t)
1879 (setq body (reverse (cons (1- (match-beginning 0)) body))
1880 close (list (match-beginning 0) (match-end 0))
1881 all (list (car open) (match-end 0)))
1882 (set-match-data (append all open lang body close))
1884 (t nil)))
1885 (t nil))))
1887 (defun markdown-match-generic-metadata (regexp last)
1888 "Match generic metadata specified by REGEXP from the point to LAST."
1889 (let ((header-end (save-excursion
1890 (goto-char (point-min))
1891 (if (re-search-forward "\n\n" (point-max) t)
1892 (match-beginning 0)
1893 (point-max)))))
1894 (cond ((>= (point) header-end)
1895 ;; Don't match anything outside of the header.
1896 nil)
1897 ((re-search-forward regexp (min last header-end) t)
1898 ;; If a metadata item is found, it may span several lines.
1899 (let ((key-beginning (match-beginning 1))
1900 (key-end (match-end 1))
1901 (value-beginning (match-beginning 2)))
1902 (while (and (not (looking-at regexp))
1903 (not (> (point) (min last header-end)))
1904 (not (eobp)))
1905 (forward-line))
1906 (unless (eobp)
1907 (forward-line -1)
1908 (end-of-line))
1909 (set-match-data (list key-beginning (point) ; complete metadata
1910 key-beginning key-end ; key
1911 value-beginning (point))) ; value
1913 (t nil))))
1915 (defun markdown-match-multimarkdown-metadata (last)
1916 "Match MultiMarkdown metadata from the point to LAST."
1917 (markdown-match-generic-metadata markdown-regex-multimarkdown-metadata last))
1919 (defun markdown-match-pandoc-metadata (last)
1920 "Match Pandoc metadata from the point to LAST."
1921 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
1923 (defun markdown-font-lock-extend-region ()
1924 "Extend the search region to include an entire block of text.
1925 This helps improve font locking for block constructs such as pre blocks."
1926 ;; Avoid compiler warnings about these global variables from font-lock.el.
1927 ;; See the documentation for variable `font-lock-extend-region-functions'.
1928 (eval-when-compile (defvar font-lock-beg) (defvar font-lock-end))
1929 (save-excursion
1930 (goto-char font-lock-beg)
1931 (unless (looking-back "\n\n")
1932 (let ((found (or (re-search-backward "\n\n" nil t) (point-min))))
1933 (goto-char font-lock-end)
1934 (when (re-search-forward "\n\n" nil t)
1935 (setq font-lock-end (match-beginning 0))
1936 (setq font-lock-beg found))))))
1939 ;;; Syntax Table ==============================================================
1941 (defvar markdown-mode-syntax-table
1942 (let ((tab (make-syntax-table text-mode-syntax-table)))
1943 (modify-syntax-entry ?\" "." tab)
1944 tab)
1945 "Syntax table for `markdown-mode'.")
1948 ;;; Element Insertion =========================================================
1950 (defun markdown-ensure-blank-line-before ()
1951 "If previous line is not already blank, insert a blank line before point."
1952 (unless (bolp) (insert "\n"))
1953 (unless (or (bobp) (looking-back "\n\\s-*\n")) (insert "\n")))
1955 (defun markdown-ensure-blank-line-after ()
1956 "If following line is not already blank, insert a blank line after point.
1957 Return the point where it was originally."
1958 (save-excursion
1959 (unless (eolp) (insert "\n"))
1960 (unless (or (eobp) (looking-at "\n\\s-*\n")) (insert "\n"))))
1962 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
1963 "Insert the strings S1 and S2, wrapping around region or THING.
1964 If a region is specified by the optional BEG and END arguments,
1965 wrap the strings S1 and S2 around that region.
1966 If there is an active region, wrap the strings S1 and S2 around
1967 the region. If there is not an active region but the point is at
1968 THING, wrap that thing (which defaults to word). Otherwise, just
1969 insert S1 and S2 and place the cursor in between. Return the
1970 bounds of the entire wrapped string, or nil if nothing was wrapped
1971 and S1 and S2 were only inserted."
1972 (let (a b bounds new-point)
1973 (cond
1974 ;; Given region
1975 ((and beg end)
1976 (setq a beg
1977 b end
1978 new-point (+ (point) (length s1))))
1979 ;; Active region
1980 ((markdown-use-region-p)
1981 (setq a (region-beginning)
1982 b (region-end)
1983 new-point (+ (point) (length s1))))
1984 ;; Thing (word) at point
1985 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
1986 (setq a (car bounds)
1987 b (cdr bounds)
1988 new-point (+ (point) (length s1))))
1989 ;; No active region and no word
1991 (setq a (point)
1992 b (point))))
1993 (goto-char b)
1994 (insert s2)
1995 (goto-char a)
1996 (insert s1)
1997 (when new-point (goto-char new-point))
1998 (if (= a b)
2000 (setq b (+ b (length s1) (length s2)))
2001 (cons a b))))
2003 (defun markdown-point-after-unwrap (cur prefix suffix)
2004 "Return desired position of point after an unwrapping operation.
2005 CUR gives the position of the point before the operation.
2006 Additionally, two cons cells must be provided. PREFIX gives the
2007 bounds of the prefix string and SUFFIX gives the bounds of the
2008 suffix string."
2009 (cond ((< cur (cdr prefix)) (car prefix))
2010 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
2011 ((<= cur (cdr suffix))
2012 (- cur (+ (- (cdr prefix) (car prefix))
2013 (- cur (car suffix)))))
2014 (t cur)))
2016 (defun markdown-unwrap-thing-at-point (regexp all text)
2017 "Remove prefix and suffix of thing at point and reposition the point.
2018 When the thing at point matches REGEXP, replace the subexpression
2019 ALL with the string in subexpression TEXT. Reposition the point
2020 in an appropriate location accounting for the removal of prefix
2021 and suffix strings. Return new bounds of string from group TEXT.
2022 When REGEXP is nil, assumes match data is already set."
2023 (when (or (null regexp)
2024 (thing-at-point-looking-at regexp))
2025 (let ((cur (point))
2026 (prefix (cons (match-beginning all) (match-beginning text)))
2027 (suffix (cons (match-end text) (match-end all)))
2028 (bounds (cons (match-beginning text) (match-end text))))
2029 ;; Replace the thing at point
2030 (replace-match (match-string text) t t nil all)
2031 ;; Reposition the point
2032 (goto-char (markdown-point-after-unwrap cur prefix suffix))
2033 ;; Adjust bounds
2034 (setq bounds (cons (car prefix)
2035 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
2037 (defun markdown-unwrap-things-in-region (beg end regexp all text)
2038 "Remove prefix and suffix of all things in region from BEG to END.
2039 When a thing in the region matches REGEXP, replace the
2040 subexpression ALL with the string in subexpression TEXT.
2041 Return a cons cell containing updated bounds for the region."
2042 (save-excursion
2043 (goto-char beg)
2044 (let ((removed 0) len-all len-text)
2045 (while (re-search-forward regexp (- end removed) t)
2046 (setq len-all (length (match-string-no-properties all)))
2047 (setq len-text (length (match-string-no-properties text)))
2048 (setq removed (+ removed (- len-all len-text)))
2049 (replace-match (match-string text) t t nil all))
2050 (cons beg (- end removed)))))
2052 (defun markdown-insert-hr (arg)
2053 "Insert or replace a horizonal rule.
2054 By default, use the first element of `markdown-hr-strings'. When
2055 ARG is non-nil, as when given a prefix, select a different
2056 element as follows. When prefixed with \\[universal-argument],
2057 use the last element of `markdown-hr-strings' instead. When
2058 prefixed with an integer from 1 to the length of
2059 `markdown-hr-strings', use the element in that position instead."
2060 (interactive "*P")
2061 (when (thing-at-point-looking-at markdown-regex-hr)
2062 (delete-region (match-beginning 0) (match-end 0)))
2063 (markdown-ensure-blank-line-before)
2064 (cond ((equal arg '(4))
2065 (insert (car (reverse markdown-hr-strings))))
2066 ((and (integerp arg) (> arg 0)
2067 (<= arg (length markdown-hr-strings)))
2068 (insert (nth (1- arg) markdown-hr-strings)))
2070 (insert (car markdown-hr-strings))))
2071 (markdown-ensure-blank-line-after))
2073 (defun markdown-insert-bold ()
2074 "Insert markup to make a region or word bold.
2075 If there is an active region, make the region bold. If the point
2076 is at a non-bold word, make the word bold. If the point is at a
2077 bold word or phrase, remove the bold markup. Otherwise, simply
2078 insert bold delimiters and place the cursor in between them."
2079 (interactive)
2080 (let ((delim (if markdown-bold-underscore "__" "**")))
2081 (if (markdown-use-region-p)
2082 ;; Active region
2083 (let ((bounds (markdown-unwrap-things-in-region
2084 (region-beginning) (region-end)
2085 markdown-regex-bold 2 4)))
2086 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
2087 ;; Bold markup removal, bold word at point, or empty markup insertion
2088 (if (thing-at-point-looking-at markdown-regex-bold)
2089 (markdown-unwrap-thing-at-point nil 2 4)
2090 (markdown-wrap-or-insert delim delim 'word nil nil)))))
2092 (defun markdown-insert-italic ()
2093 "Insert markup to make a region or word italic.
2094 If there is an active region, make the region italic. If the point
2095 is at a non-italic word, make the word italic. If the point is at an
2096 italic word or phrase, remove the italic markup. Otherwise, simply
2097 insert italic delimiters and place the cursor in between them."
2098 (interactive)
2099 (let ((delim (if markdown-italic-underscore "_" "*")))
2100 (if (markdown-use-region-p)
2101 ;; Active region
2102 (let ((bounds (markdown-unwrap-things-in-region
2103 (region-beginning) (region-end)
2104 markdown-regex-italic 2 4)))
2105 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
2106 ;; Italic markup removal, italic word at point, or empty markup insertion
2107 (if (thing-at-point-looking-at markdown-regex-italic)
2108 (markdown-unwrap-thing-at-point nil 2 4)
2109 (markdown-wrap-or-insert delim delim 'word nil nil)))))
2111 (defun markdown-insert-code ()
2112 "Insert markup to make a region or word an inline code fragment.
2113 If there is an active region, make the region an inline code
2114 fragment. If the point is at a word, make the word an inline
2115 code fragment. Otherwise, simply insert code delimiters and
2116 place the cursor in between them."
2117 (interactive)
2118 (if (markdown-use-region-p)
2119 ;; Active region
2120 (let ((bounds (markdown-unwrap-things-in-region
2121 (region-beginning) (region-end)
2122 markdown-regex-code 2 4)))
2123 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
2124 ;; Code markup removal, code markup for word, or empty markup insertion
2125 (if (markdown-code-at-point-p)
2126 (markdown-unwrap-thing-at-point nil 0 1)
2127 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
2129 (defun markdown-insert-link ()
2130 "Insert an inline link, using region or word as link text if possible.
2131 If there is an active region, use the region as the link text. If the
2132 point is at a word, use the word as the link text. In these cases, the
2133 point will be left at the position for inserting a URL. If there is no
2134 active region and the point is not at word, simply insert link markup and
2135 place the point in the position to enter link text."
2136 (interactive)
2137 (let ((bounds (markdown-wrap-or-insert "[" "]()")))
2138 (when bounds
2139 (goto-char (- (cdr bounds) 1)))))
2141 (defun markdown-insert-reference-link (text label &optional url title)
2142 "Insert a reference link and, optionally, a reference definition.
2143 The link TEXT will be inserted followed by the optional LABEL.
2144 If a URL is given, also insert a definition for the reference
2145 LABEL according to `markdown-reference-location'. If a TITLE is
2146 given, it will be added to the end of the reference definition
2147 and will be used to populate the title attribute when converted
2148 to XHTML. If URL is nil, insert only the link portion (for
2149 example, when a reference label is already defined)."
2150 (insert (concat "[" text "][" label "]"))
2151 (when url
2152 (let ((end (point))
2153 (label (if (> (length label) 0) label text)))
2154 (cond
2155 ((eq markdown-reference-location 'end) (goto-char (point-max)))
2156 ((eq markdown-reference-location 'immediately) (markdown-end-of-block))
2157 ((eq markdown-reference-location 'header) (markdown-end-of-defun)))
2158 (unless (markdown-cur-line-blank-p) (insert "\n"))
2159 (insert "\n[" label "]: " url)
2160 (unless (> (length url) 0)
2161 (setq end (point)))
2162 (when (> (length title) 0)
2163 (insert " \"" title "\""))
2164 (insert "\n")
2165 (unless (or (eobp) (looking-at "\n"))
2166 (insert "\n"))
2167 (goto-char end)
2168 (when (> (length url) 0)
2169 (message
2170 (substitute-command-keys
2171 "Defined reference [%s], press \\[markdown-jump] to jump there")
2172 (or label text))))))
2174 (defun markdown-insert-reference-link-dwim ()
2175 "Insert a reference link of the form [text][label] at point.
2176 If there is an active region, the text in the region will be used
2177 as the link text. If the point is at a word, it will be used as
2178 the link text. Otherwise, the link text will be read from the
2179 minibuffer. The link label will be read from the minibuffer in
2180 both cases, with completion from the set of currently defined
2181 references. To create an implicit reference link, press RET to
2182 accept the default, an empty label. If the entered referenced
2183 label is not defined, additionally prompt for the URL
2184 and (optional) title. The reference definition is placed at the
2185 location determined by `markdown-reference-location'."
2186 (interactive)
2187 (let* ((defined-labels (mapcar (lambda (x) (substring x 1 -1))
2188 (markdown-get-defined-references)))
2189 (bounds (or (and (markdown-use-region-p)
2190 (cons (region-beginning) (region-end)))
2191 (markdown-bounds-of-thing-at-point 'word)))
2192 (text (if bounds
2193 (buffer-substring (car bounds) (cdr bounds))
2194 (read-string "Link Text: ")))
2195 (label (completing-read
2196 "Link Label (default: none): " defined-labels
2197 nil nil nil 'markdown-reference-label-history nil))
2198 (ref (markdown-reference-definition
2199 (concat "[" (if (> (length label) 0) label text) "]")))
2200 (url (unless ref (read-string "Link URL: ")))
2201 (title (when (> (length url) 0)
2202 (read-string "Link Title (optional): "))))
2203 (when bounds (delete-region (car bounds) (cdr bounds)))
2204 (markdown-insert-reference-link text label url title)))
2206 (defun markdown-insert-uri ()
2207 "Insert markup for an inline URI.
2208 If there is an active region, use it as the URI. If the point is
2209 at a URI, wrap it with angle brackets. If the point is at an
2210 inline URI, remove the angle brackets. Otherwise, simply insert
2211 angle brackets place the point between them."
2212 (interactive)
2213 (if (markdown-use-region-p)
2214 ;; Active region
2215 (let ((bounds (markdown-unwrap-things-in-region
2216 (region-beginning) (region-end)
2217 markdown-regex-angle-uri 0 2)))
2218 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
2219 ;; Markup removal, URI at point, or empty markup insertion
2220 (if (thing-at-point-looking-at markdown-regex-angle-uri)
2221 (markdown-unwrap-thing-at-point nil 0 2)
2222 (markdown-wrap-or-insert "<" ">" 'url nil nil))))
2224 (defun markdown-insert-wiki-link ()
2225 "Insert a wiki link of the form [[WikiLink]].
2226 If there is an active region, use the region as the link text.
2227 If the point is at a word, use the word as the link text. If
2228 there is no active region and the point is not at word, simply
2229 insert link markup."
2230 (interactive)
2231 (if (markdown-use-region-p)
2232 ;; Active region
2233 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
2234 ;; Markup removal, wiki link at at point, or empty markup insertion
2235 (if (thing-at-point-looking-at markdown-regex-wiki-link)
2236 (if (or markdown-wiki-link-alias-first
2237 (null (match-string 4)))
2238 (markdown-unwrap-thing-at-point nil 1 2)
2239 (markdown-unwrap-thing-at-point nil 1 4))
2240 (markdown-wrap-or-insert "[[" "]]"))))
2242 (defun markdown-insert-image (&optional arg)
2243 "Insert image markup using region or word as alt text if possible.
2244 If there is an active region, use the region as the alt text. If the
2245 point is at a word, use the word as the alt text. In these cases, the
2246 point will be left at the position for inserting a URL. If there is no
2247 active region and the point is not at word, simply insert image markup and
2248 place the point in the position to enter alt text. If ARG is nil, insert
2249 inline image markup. Otherwise, insert reference image markup."
2250 (interactive "*P")
2251 (let ((bounds (if arg
2252 (markdown-wrap-or-insert "![" "][]")
2253 (markdown-wrap-or-insert "![" "]()"))))
2254 (when bounds
2255 (goto-char (- (cdr bounds) 1)))))
2257 (defun markdown-insert-reference-image ()
2258 "Insert reference-style image markup using region or word as alt text.
2259 Calls `markdown-insert-image' with prefix argument."
2260 (interactive)
2261 (markdown-insert-image t))
2263 (defun markdown-remove-header ()
2264 "Remove header markup if point is at a header.
2265 Return bounds of remaining header text if a header was removed
2266 and nil otherwise."
2267 (interactive "*")
2268 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
2269 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
2271 (defun markdown-insert-header (&optional level text setext)
2272 "Insert or replace header markup.
2273 The level of the header is specified by LEVEL and header text is
2274 given by TEXT. LEVEL must be an integer from 1 and 6, and the
2275 default value is 1.
2276 When TEXT is nil, the header text is obtained as follows.
2277 If there is an active region, it is used as the header text.
2278 Otherwise, the current line will be used as the header text.
2279 If there is not an active region and the point is at a header,
2280 remove the header markup and replace with level N header.
2281 Otherwise, insert empty header markup and place the cursor in
2282 between.
2283 The style of the header will be atx (hash marks) unless
2284 SETEXT is non-nil, in which case a setext-style (underlined)
2285 header will be inserted."
2286 (interactive "p\nsHeader text: ")
2287 (setq level (min (max (or level 1) 1) (if setext 2 6)))
2288 ;; Determine header text if not given
2289 (when (null text)
2290 (if (markdown-use-region-p)
2291 ;; Active region
2292 (setq text (delete-and-extract-region (region-beginning) (region-end)))
2293 ;; No active region
2294 (markdown-remove-header)
2295 (setq text (delete-and-extract-region
2296 (line-beginning-position) (line-end-position)))
2297 (when (and setext (string-match "^[ \t]*$" text))
2298 (setq text (read-string "Header text: "))))
2299 (setq text (markdown-compress-whitespace-string text)))
2300 ;; Insertion with given text
2301 (markdown-ensure-blank-line-before)
2302 (let (hdr)
2303 (cond (setext
2304 (setq hdr (make-string (length text) (if (= level 2) ?- ?=)))
2305 (insert text "\n" hdr))
2307 (setq hdr (make-string level ?#))
2308 (insert hdr " " text " " hdr))))
2309 (markdown-ensure-blank-line-after)
2310 ;; Leave point at end of text
2311 (if setext
2312 (backward-char (1+ (length text)))
2313 (backward-char (1+ level))))
2315 (defun markdown-insert-header-dwim (&optional arg setext)
2316 "Insert or replace header markup.
2317 The level and type of the header are determined automatically by
2318 the type and level of the previous header, unless a prefix
2319 argument is given via ARG.
2320 With a numeric prefix valued 1 to 6, insert a header of the given
2321 level, with the type being determined automatically (note that
2322 only level 1 or 2 setext headers are possible).
2324 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
2325 promote the heading by one level.
2326 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
2327 demote the heading by one level.
2328 When SETEXT is non-nil, prefer setext-style headers when
2329 possible (levels one and two).
2331 When there is an active region, use it for the header text. When
2332 the point is at an existing header, change the type and level
2333 according to the rules above.
2334 Otherwise, if the line is not empty, create a header using the
2335 text on the current line as the header text.
2336 Finally, if the point is on a blank line, insert empty header
2337 markup (atx) or prompt for text (setext).
2338 See `markdown-insert-header' for more details about how the
2339 header text is determined."
2340 (interactive "*P")
2341 (let (level)
2342 (save-excursion
2343 (when (re-search-backward markdown-regex-header nil t)
2344 ;; level of previous header
2345 (setq level (markdown-outline-level))
2346 ;; match groups 1 and 2 indicate setext headers
2347 (setq setext (or setext (match-end 1) (match-end 3)))))
2348 ;; check prefix argument
2349 (cond
2350 ((and (equal arg '(4)) (> level 1)) ;; C-u
2351 (decf level))
2352 ((and (equal arg '(16)) (< level 6)) ;; C-u C-u
2353 (incf level))
2354 (arg ;; numeric prefix
2355 (setq level (prefix-numeric-value arg))))
2356 ;; setext headers must be level one or two
2357 (and level (setq setext (and setext (<= level 2))))
2358 ;; insert the heading
2359 (markdown-insert-header level nil setext)))
2361 (defun markdown-insert-header-setext-dwim (&optional arg)
2362 "Insert or replace header markup, with preference for setext.
2363 See `markdown-insert-header-dwim' for details, including how ARG is handled."
2364 (interactive "*P")
2365 (markdown-insert-header-dwim arg t))
2367 (defun markdown-insert-header-atx-1 ()
2368 "Insert a first level atx-style (hash mark) header.
2369 See `markdown-insert-header'."
2370 (interactive "*")
2371 (markdown-insert-header 1 nil nil))
2373 (defun markdown-insert-header-atx-2 ()
2374 "Insert a level two atx-style (hash mark) header.
2375 See `markdown-insert-header'."
2376 (interactive "*")
2377 (markdown-insert-header 2 nil nil))
2379 (defun markdown-insert-header-atx-3 ()
2380 "Insert a level three atx-style (hash mark) header.
2381 See `markdown-insert-header'."
2382 (interactive "*")
2383 (markdown-insert-header 3 nil nil))
2385 (defun markdown-insert-header-atx-4 ()
2386 "Insert a level four atx-style (hash mark) header.
2387 See `markdown-insert-header'."
2388 (interactive "*")
2389 (markdown-insert-header 4 nil nil))
2391 (defun markdown-insert-header-atx-5 ()
2392 "Insert a level five atx-style (hash mark) header.
2393 See `markdown-insert-header'."
2394 (interactive "*")
2395 (markdown-insert-header 5 nil nil))
2397 (defun markdown-insert-header-atx-6 ()
2398 "Insert a sixth level atx-style (hash mark) header.
2399 See `markdown-insert-header'."
2400 (interactive "*")
2401 (markdown-insert-header 6 nil nil))
2403 (defun markdown-insert-header-setext-1 ()
2404 "Insert a setext-style (underlined) first-level header.
2405 See `markdown-insert-header'."
2406 (interactive "*")
2407 (markdown-insert-header 1 nil t))
2409 (defun markdown-insert-header-setext-2 ()
2410 "Insert a setext-style (underlined) second-level header.
2411 See `markdown-insert-header'."
2412 (interactive "*")
2413 (markdown-insert-header 2 nil t))
2415 (defun markdown-blockquote-indentation (loc)
2416 "Return string containing necessary indentation for a blockquote at LOC.
2417 Also see `markdown-pre-indentation'."
2418 (save-excursion
2419 (goto-char loc)
2420 (let* ((list-level (length (markdown-calculate-list-levels)))
2421 (indent ""))
2422 (dotimes (count list-level indent)
2423 (setq indent (concat indent " "))))))
2425 (defun markdown-insert-blockquote ()
2426 "Start a blockquote section (or blockquote the region).
2427 If Transient Mark mode is on and a region is active, it is used as
2428 the blockquote text."
2429 (interactive)
2430 (if (markdown-use-region-p)
2431 (markdown-blockquote-region (region-beginning) (region-end))
2432 (markdown-ensure-blank-line-before)
2433 (insert (markdown-blockquote-indentation (point)) "> ")
2434 (markdown-ensure-blank-line-after)))
2436 (defun markdown-block-region (beg end prefix)
2437 "Format the region using a block prefix.
2438 Arguments BEG and END specify the beginning and end of the
2439 region. The characters PREFIX will appear at the beginning
2440 of each line."
2441 (save-excursion
2442 (let* ((end-marker (make-marker))
2443 (beg-marker (make-marker)))
2444 ;; Ensure blank line after and remove extra whitespace
2445 (goto-char end)
2446 (skip-syntax-backward "-")
2447 (set-marker end-marker (point))
2448 (delete-horizontal-space)
2449 (markdown-ensure-blank-line-after)
2450 ;; Ensure blank line before and remove extra whitespace
2451 (goto-char beg)
2452 (skip-syntax-forward "-")
2453 (delete-horizontal-space)
2454 (markdown-ensure-blank-line-before)
2455 (set-marker beg-marker (point))
2456 ;; Insert PREFIX before each line
2457 (goto-char beg-marker)
2458 (while (and (< (line-beginning-position) end-marker)
2459 (not (eobp)))
2460 (insert prefix)
2461 (forward-line)))))
2463 (defun markdown-blockquote-region (beg end)
2464 "Blockquote the region.
2465 Arguments BEG and END specify the beginning and end of the region."
2466 (interactive "*r")
2467 (markdown-block-region
2468 beg end (concat (markdown-blockquote-indentation
2469 (max (point-min) (1- beg))) "> ")))
2471 (defun markdown-pre-indentation (loc)
2472 "Return string containing necessary whitespace for a pre block at LOC.
2473 Also see `markdown-blockquote-indentation'."
2474 (save-excursion
2475 (goto-char loc)
2476 (let* ((list-level (length (markdown-calculate-list-levels)))
2477 indent)
2478 (dotimes (count (1+ list-level) indent)
2479 (setq indent (concat indent " "))))))
2481 (defun markdown-insert-pre ()
2482 "Start a preformatted section (or apply to the region).
2483 If Transient Mark mode is on and a region is active, it is marked
2484 as preformatted text."
2485 (interactive)
2486 (if (markdown-use-region-p)
2487 (markdown-pre-region (region-beginning) (region-end))
2488 (markdown-ensure-blank-line-before)
2489 (insert (markdown-pre-indentation (point)))
2490 (markdown-ensure-blank-line-after)))
2492 (defun markdown-pre-region (beg end)
2493 "Format the region as preformatted text.
2494 Arguments BEG and END specify the beginning and end of the region."
2495 (interactive "*r")
2496 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
2497 (markdown-block-region beg end indent)))
2499 (defun markdown-insert-gfm-code-block (&optional lang)
2500 "Insert GFM code block for language LANG.
2501 If LANG is nil, the language will be queried from user. If a
2502 region is active, wrap this region with the markup instead. If
2503 the region boundaries are not on empty lines, these are added
2504 automatically in order to have the correct markup."
2505 (interactive "sProgramming language [none]: ")
2506 (if (markdown-use-region-p)
2507 (let ((b (region-beginning)) (e (region-end)))
2508 (goto-char e)
2509 ;; if we're on a blank line, don't newline, otherwise the ```
2510 ;; should go on its own line
2511 (unless (looking-back "\n")
2512 (newline))
2513 (insert "```")
2514 (markdown-ensure-blank-line-after)
2515 (goto-char b)
2516 ;; if we're on a blank line, insert the quotes here, otherwise
2517 ;; add a new line first
2518 (unless (looking-at "\n")
2519 (newline)
2520 (forward-line -1))
2521 (markdown-ensure-blank-line-before)
2522 (insert "```" lang))
2523 (markdown-ensure-blank-line-before)
2524 (insert "```" lang)
2525 (newline 2)
2526 (insert "```")
2527 (markdown-ensure-blank-line-after)
2528 (forward-line -1)))
2531 ;;; Footnotes ======================================================================
2533 (defun markdown-footnote-counter-inc ()
2534 "Increment `markdown-footnote-counter' and return the new value."
2535 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
2536 (save-excursion
2537 (goto-char (point-min))
2538 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
2539 (point-max) t)
2540 (let ((fn (string-to-number (match-string 1))))
2541 (when (> fn markdown-footnote-counter)
2542 (setq markdown-footnote-counter fn))))))
2543 (incf markdown-footnote-counter))
2545 (defun markdown-insert-footnote ()
2546 "Insert footnote with a new number and move point to footnote definition."
2547 (interactive)
2548 (let ((fn (markdown-footnote-counter-inc)))
2549 (insert (format "[^%d]" fn))
2550 (markdown-footnote-text-find-new-location)
2551 (markdown-ensure-blank-line-before)
2552 (unless (markdown-cur-line-blank-p)
2553 (insert "\n"))
2554 (insert (format "[^%d]: " fn))
2555 (markdown-ensure-blank-line-after)))
2557 (defun markdown-footnote-text-find-new-location ()
2558 "Position the cursor at the proper location for a new footnote text."
2559 (cond
2560 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
2561 ((eq markdown-footnote-location 'immediately) (markdown-end-of-block))
2562 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
2564 (defun markdown-footnote-kill ()
2565 "Kill the footnote at point.
2566 The footnote text is killed (and added to the kill ring), the
2567 footnote marker is deleted. Point has to be either at the
2568 footnote marker or in the footnote text."
2569 (interactive)
2570 (let (return-pos)
2571 (when (markdown-footnote-text-positions) ; if we're in a footnote text
2572 (markdown-footnote-return) ; we first move to the marker
2573 (setq return-pos 'text)) ; and remember our return position
2574 (let ((marker (markdown-footnote-delete-marker)))
2575 (unless marker
2576 (error "Not at a footnote"))
2577 (let ((text-pos (markdown-footnote-find-text (car marker))))
2578 (unless text-pos
2579 (error "No text for footnote `%s'" (car marker)))
2580 (goto-char text-pos)
2581 (let ((pos (markdown-footnote-kill-text)))
2582 (setq return-pos
2583 (if (and pos (eq return-pos 'text))
2585 (cadr marker))))))
2586 (goto-char return-pos)))
2588 (defun markdown-footnote-delete-marker ()
2589 "Delete a footnote marker at point.
2590 Returns a list (ID START) containing the footnote ID and the
2591 start position of the marker before deletion. If no footnote
2592 marker was deleted, this function returns NIL."
2593 (let ((marker (markdown-footnote-marker-positions)))
2594 (when marker
2595 (delete-region (second marker) (third marker))
2596 (butlast marker))))
2598 (defun markdown-footnote-kill-text ()
2599 "Kill footnote text at point.
2600 Returns the start position of the footnote text before deletion,
2601 or NIL if point was not inside a footnote text.
2603 The killed text is placed in the kill ring (without the footnote
2604 number)."
2605 (let ((fn (markdown-footnote-text-positions)))
2606 (when fn
2607 (let ((text (delete-and-extract-region (second fn) (third fn))))
2608 (string-match (concat "\\[\\" (first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
2609 (kill-new (match-string 1 text))
2610 (when (and (markdown-cur-line-blank-p)
2611 (markdown-prev-line-blank-p))
2612 (delete-region (1- (point)) (point)))
2613 (second fn)))))
2615 (defun markdown-footnote-goto-text ()
2616 "Jump to the text of the footnote at point."
2617 (interactive)
2618 (let ((fn (car (markdown-footnote-marker-positions))))
2619 (unless fn
2620 (error "Not at a footnote marker"))
2621 (let ((new-pos (markdown-footnote-find-text fn)))
2622 (unless new-pos
2623 (error "No definition found for footnote `%s'" fn))
2624 (goto-char new-pos))))
2626 (defun markdown-footnote-return ()
2627 "Return from a footnote to its footnote number in the main text."
2628 (interactive)
2629 (let ((fn (save-excursion
2630 (car (markdown-footnote-text-positions)))))
2631 (unless fn
2632 (error "Not in a footnote"))
2633 (let ((new-pos (markdown-footnote-find-marker fn)))
2634 (unless new-pos
2635 (error "Footnote marker `%s' not found" fn))
2636 (goto-char new-pos))))
2638 (defun markdown-footnote-find-marker (id)
2639 "Find the location of the footnote marker with ID.
2640 The actual buffer position returned is the position directly
2641 following the marker's closing bracket. If no marker is found,
2642 NIL is returned."
2643 (save-excursion
2644 (goto-char (point-min))
2645 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
2646 (skip-chars-backward "^]")
2647 (point))))
2649 (defun markdown-footnote-find-text (id)
2650 "Find the location of the text of footnote ID.
2651 The actual buffer position returned is the position of the first
2652 character of the text, after the footnote's identifier. If no
2653 footnote text is found, NIL is returned."
2654 (save-excursion
2655 (goto-char (point-min))
2656 (when (re-search-forward (concat "^\\[" id "\\]:") nil t)
2657 (skip-chars-forward "[ \t]")
2658 (point))))
2660 (defun markdown-footnote-marker-positions ()
2661 "Return the position and ID of the footnote marker point is on.
2662 The return value is a list (ID START END). If point is not on a
2663 footnote, NIL is returned."
2664 ;; first make sure we're at a footnote marker
2665 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
2666 (looking-at (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
2667 (save-excursion
2668 ;; move point between [ and ^:
2669 (if (looking-at "\\[")
2670 (forward-char 1)
2671 (skip-chars-backward "^["))
2672 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
2673 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
2675 (defun markdown-footnote-text-positions ()
2676 "Return the start and end positions of the footnote text point is in.
2677 The exact return value is a list of three elements: (ID START END).
2678 The start position is the position of the opening bracket
2679 of the footnote id. The end position is directly after the
2680 newline that ends the footnote. If point is not in a footnote,
2681 NIL is returned instead."
2682 (save-excursion
2683 (let ((fn (progn
2684 (backward-paragraph)
2685 ;; if we're in a multiparagraph footnote, we need to back up further
2686 (while (>= (markdown-next-line-indent) 4)
2687 (backward-paragraph))
2688 (forward-line)
2689 (if (looking-at (concat "^\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:"))
2690 (list (match-string 1) (point))))))
2691 (when fn
2692 (while (progn
2693 (forward-paragraph)
2694 (>= (markdown-next-line-indent) 4)))
2695 (append fn (list (point)))))))
2698 ;;; Element Removal ===========================================================
2700 (defun markdown-kill-thing-at-point ()
2701 "Kill thing at point and add important text, without markup, to kill ring.
2702 Possible things to kill include (roughly in order of precedence):
2703 inline code, headers, horizonal rules, links (add link text to
2704 kill ring), images (add alt text to kill ring), angle uri, email
2705 addresses, bold, italics, reference definition (add URI to kill
2706 ring), footnote markers and text (kill both marker and text, add
2707 text to kill ring), and list items."
2708 (interactive "*")
2709 (let (val tmp)
2710 (cond
2711 ;; Inline code
2712 ((markdown-code-at-point-p)
2713 (kill-new (match-string 1))
2714 (delete-region (match-beginning 0) (match-end 0)))
2715 ;; ATX header
2716 ((thing-at-point-looking-at markdown-regex-header-atx)
2717 (kill-new (match-string 2))
2718 (delete-region (match-beginning 0) (match-end 0)))
2719 ;; Setext header
2720 ((thing-at-point-looking-at markdown-regex-header-setext)
2721 (kill-new (match-string 1))
2722 (delete-region (match-beginning 0) (match-end 0)))
2723 ;; Horizonal rule
2724 ((thing-at-point-looking-at markdown-regex-hr)
2725 (kill-new (match-string 0))
2726 (delete-region (match-beginning 0) (match-end 0)))
2727 ;; Inline link or image (add link or alt text to kill ring)
2728 ((thing-at-point-looking-at markdown-regex-link-inline)
2729 (kill-new (match-string 3))
2730 (delete-region (match-beginning 0) (match-end 0)))
2731 ;; Reference link or image (add link or alt text to kill ring)
2732 ((thing-at-point-looking-at markdown-regex-link-reference)
2733 (kill-new (match-string 3))
2734 (delete-region (match-beginning 0) (match-end 0)))
2735 ;; Angle URI (add URL to kill ring)
2736 ((thing-at-point-looking-at markdown-regex-angle-uri)
2737 (kill-new (match-string 2))
2738 (delete-region (match-beginning 0) (match-end 0)))
2739 ;; Email address in angle brackets (add email address to kill ring)
2740 ((thing-at-point-looking-at markdown-regex-email)
2741 (kill-new (match-string 1))
2742 (delete-region (match-beginning 0) (match-end 0)))
2743 ;; Wiki link (add alias text to kill ring)
2744 ((thing-at-point-looking-at markdown-regex-wiki-link)
2745 (kill-new (markdown-wiki-link-alias))
2746 (delete-region (match-beginning 1) (match-end 1)))
2747 ;; Bold
2748 ((thing-at-point-looking-at markdown-regex-bold)
2749 (kill-new (match-string 4))
2750 (delete-region (match-beginning 2) (match-end 2)))
2751 ;; Italics
2752 ((thing-at-point-looking-at markdown-regex-italic)
2753 (kill-new (match-string 4))
2754 (delete-region (match-beginning 2) (match-end 2)))
2755 ;; Footnote marker (add footnote text to kill ring)
2756 ((thing-at-point-looking-at markdown-regex-footnote)
2757 (markdown-footnote-kill))
2758 ;; Footnote text (add footnote text to kill ring)
2759 ((setq val (markdown-footnote-text-positions))
2760 (markdown-footnote-kill))
2761 ;; Reference definition (add URL to kill ring)
2762 ((thing-at-point-looking-at markdown-regex-reference-definition)
2763 (kill-new (match-string 2))
2764 (delete-region (match-beginning 0) (match-end 0)))
2765 ;; List item
2766 ((setq val (markdown-cur-list-item-bounds))
2767 (kill-new (delete-and-extract-region (first val) (second val))))
2769 (error "Nothing found at point to kill")))))
2772 ;;; Indentation ====================================================================
2774 (defun markdown-indent-find-next-position (cur-pos positions)
2775 "Return the position after the index of CUR-POS in POSITIONS.
2776 Positions are calculated by `markdown-calc-indents'."
2777 (while (and positions
2778 (not (equal cur-pos (car positions))))
2779 (setq positions (cdr positions)))
2780 (or (cadr positions) 0))
2782 (defun markdown-exdent-find-next-position (cur-pos positions)
2783 "Return the maximal element that precedes CUR-POS from POSITIONS.
2784 Positions are calculated by `markdown-calc-indents'."
2785 (let ((result 0))
2786 (dolist (i positions)
2787 (when (< i cur-pos)
2788 (setq result (max result i))))
2789 result))
2791 (defun markdown-indent-line ()
2792 "Indent the current line using some heuristics.
2793 If the _previous_ command was either `markdown-enter-key' or
2794 `markdown-cycle', then we should cycle to the next
2795 reasonable indentation position. Otherwise, we could have been
2796 called directly by `markdown-enter-key', by an initial call of
2797 `markdown-cycle', or indirectly by `auto-fill-mode'. In
2798 these cases, indent to the default position.
2799 Positions are calculated by `markdown-calc-indents'."
2800 (interactive)
2801 (let ((positions (markdown-calc-indents))
2802 (cur-pos (current-column)))
2803 (if (not (equal this-command 'markdown-cycle))
2804 (indent-line-to (car positions))
2805 (setq positions (sort (delete-dups positions) '<))
2806 (indent-line-to
2807 (markdown-indent-find-next-position cur-pos positions)))))
2809 (defun markdown-calc-indents ()
2810 "Return a list of indentation columns to cycle through.
2811 The first element in the returned list should be considered the
2812 default indentation level. This function does not worry about
2813 duplicate positions, which are handled up by calling functions."
2814 (let (pos prev-line-pos positions)
2816 ;; Indentation of previous line
2817 (setq prev-line-pos (markdown-prev-line-indent))
2818 (setq positions (cons prev-line-pos positions))
2820 ;; Indentation of previous non-list-marker text
2821 (when (setq pos (markdown-prev-non-list-indent))
2822 (setq positions (cons pos positions)))
2824 ;; Indentation required for a pre block in current context
2825 (setq pos (length (markdown-pre-indentation (point))))
2826 (setq positions (cons pos positions))
2828 ;; Indentation of the previous line + tab-width
2829 (if prev-line-pos
2830 (setq positions (cons (+ prev-line-pos tab-width) positions))
2831 (setq positions (cons tab-width positions)))
2833 ;; Indentation of the previous line - tab-width
2834 (if (and prev-line-pos (> prev-line-pos tab-width))
2835 (setq positions (cons (- prev-line-pos tab-width) positions)))
2837 ;; Indentation of all preceeding list markers (when in a list)
2838 (when (setq pos (markdown-calculate-list-levels))
2839 (setq positions (append pos positions)))
2841 ;; First column
2842 (setq positions (cons 0 positions))
2844 ;; Return reversed list
2845 (reverse positions)))
2847 (defun markdown-enter-key ()
2848 "Handle RET according to to the value of `markdown-indent-on-enter'."
2849 (interactive)
2850 (if markdown-indent-on-enter
2851 (newline-and-indent)
2852 (newline)))
2854 (defun markdown-exdent-or-delete (arg)
2855 "Handle BACKSPACE by cycling through indentation points.
2856 When BACKSPACE is pressed, if there is only whitespace
2857 before the current point, then exdent the line one level.
2858 Otherwise, do normal delete by repeating
2859 `backward-delete-char-untabify' ARG times."
2860 (interactive "*p")
2861 (let ((cur-pos (current-column))
2862 (start-of-indention (save-excursion
2863 (back-to-indentation)
2864 (current-column)))
2865 (positions (markdown-calc-indents)))
2866 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
2867 (indent-line-to (markdown-exdent-find-next-position cur-pos positions))
2868 (backward-delete-char-untabify arg))))
2870 (defun markdown-find-leftmost-column (beg end)
2871 "Find the leftmost column in the region from BEG to END."
2872 (let ((mincol 1000))
2873 (save-excursion
2874 (goto-char beg)
2875 (while (< (point) end)
2876 (back-to-indentation)
2877 (unless (looking-at "[ \t]*$")
2878 (setq mincol (min mincol (current-column))))
2879 (forward-line 1)
2881 mincol))
2883 (defun markdown-indent-region (beg end arg)
2884 "Indent the region from BEG to END using some heuristics.
2885 When ARG is non-nil, exdent the region instead.
2886 See `markdown-indent-line' and `markdown-indent-line'."
2887 (interactive "*r\nP")
2888 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
2889 (leftmostcol (markdown-find-leftmost-column beg end))
2890 (next-pos (if arg
2891 (markdown-exdent-find-next-position leftmostcol positions)
2892 (markdown-indent-find-next-position leftmostcol positions))))
2893 (indent-rigidly beg end (- next-pos leftmostcol))
2894 (setq deactivate-mark nil)))
2896 (defun markdown-exdent-region (beg end)
2897 "Call `markdown-indent-region' on region from BEG to END with prefix."
2898 (interactive "*r")
2899 (markdown-indent-region (region-beginning) (region-end) t))
2902 ;;; Markup Completion =========================================================
2904 (defconst markdown-complete-alist
2905 '((markdown-regex-header-atx . markdown-complete-atx)
2906 (markdown-regex-header-setext . markdown-complete-setext)
2907 (markdown-regex-hr . markdown-complete-hr))
2908 "Association list of form (regexp . function) for markup completion.")
2910 (defun markdown-incomplete-atx-p ()
2911 "Return t if ATX header markup is incomplete and nil otherwise.
2912 Assumes match data is available for `markdown-regex-header-atx'.
2913 Checks that the number of trailing hash marks equals the number of leading
2914 hash marks, that there is only a single space before and after the text,
2915 and that there is no extraneous whitespace in the text."
2916 (save-match-data
2918 ;; Number of starting and ending hash marks differs
2919 (not (= (length (match-string 1)) (length (match-string 3))))
2920 ;; When the header text is not empty...
2921 (and (> (length (match-string 2)) 0)
2922 ;; ...if there are extra leading, trailing, or interior spaces
2923 (or (not (= (match-beginning 2) (1+ (match-end 1))))
2924 (not (= (match-beginning 3) (1+ (match-end 2))))
2925 (string-match "[ \t\n]\\{2\\}" (match-string 2))))
2926 ;; When the header text is empty...
2927 (and (= (length (match-string 2)) 0)
2928 ;; ...if there are too many or too few spaces
2929 (not (= (match-beginning 3) (+ (match-end 1) 2)))))))
2931 (defun markdown-complete-atx ()
2932 "Complete and normalize ATX headers.
2933 Add or remove hash marks to the end of the header to match the
2934 beginning. Ensure that there is only a single space between hash
2935 marks and header text. Removes extraneous whitespace from header text.
2936 Assumes match data is available for `markdown-regex-header-atx'.
2937 Return nil if markup was complete and non-nil if markup was completed."
2938 (when (markdown-incomplete-atx-p)
2939 (let* ((new-marker (make-marker))
2940 (new-marker (set-marker new-marker (match-end 2))))
2941 ;; Hash marks and spacing at end
2942 (goto-char (match-end 2))
2943 (delete-region (match-end 2) (match-end 3))
2944 (insert " " (match-string 1))
2945 ;; Remove extraneous whitespace from title
2946 (replace-match (markdown-compress-whitespace-string (match-string 2))
2947 t t nil 2)
2948 ;; Spacing at beginning
2949 (goto-char (match-end 1))
2950 (delete-region (match-end 1) (match-beginning 2))
2951 (insert " ")
2952 ;; Leave point at end of text
2953 (goto-char new-marker))))
2955 (defun markdown-incomplete-setext-p ()
2956 "Return t if setext header markup is incomplete and nil otherwise.
2957 Assumes match data is available for `markdown-regex-header-setext'.
2958 Checks that length of underline matches text and that there is no
2959 extraneous whitespace in the text."
2960 (save-match-data
2961 (or (not (= (length (match-string 1)) (length (match-string 2))))
2962 (string-match "[ \t\n]\\{2\\}" (match-string 1)))))
2964 (defun markdown-complete-setext ()
2965 "Complete and normalize setext headers.
2966 Add or remove underline characters to match length of header
2967 text. Removes extraneous whitespace from header text. Assumes
2968 match data is available for `markdown-regex-header-setext'.
2969 Return nil if markup was complete and non-nil if markup was completed."
2970 (when (markdown-incomplete-setext-p)
2971 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
2972 (char (char-after (match-beginning 2)))
2973 (level (if (char-equal char ?-) 2 1)))
2974 (goto-char (match-beginning 0))
2975 (delete-region (match-beginning 0) (match-end 0))
2976 (markdown-insert-header level text t)
2977 t)))
2979 (defun markdown-incomplete-hr-p ()
2980 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
2981 Assumes match data is available for `markdown-regex-hr'."
2982 (not (member (match-string 0) markdown-hr-strings)))
2984 (defun markdown-complete-hr ()
2985 "Complete horizontal rules.
2986 If horizontal rule string is a member of `markdown-hr-strings',
2987 do nothing. Otherwise, replace with the car of
2988 `markdown-hr-strings'.
2989 Assumes match data is available for `markdown-regex-hr'.
2990 Return nil if markup was complete and non-nil if markup was completed."
2991 (when (markdown-incomplete-hr-p)
2992 (replace-match (car markdown-hr-strings))
2995 (defun markdown-complete ()
2996 "Complete markup of object near point or in region when active.
2997 Handle all objects in `markdown-complete-alist', in order.
2998 See `markdown-complete-at-point' and `markdown-complete-region'."
2999 (interactive "*")
3000 (if (markdown-use-region-p)
3001 (markdown-complete-region (region-beginning) (region-end))
3002 (markdown-complete-at-point)))
3004 (defun markdown-complete-at-point ()
3005 "Complete markup of object near point.
3006 Handle all elements of `markdown-complete-alist' in order."
3007 (interactive "*")
3008 (let ((list markdown-complete-alist) found changed)
3009 (while list
3010 (let ((regexp (eval (caar list)))
3011 (function (cdar list)))
3012 (setq list (cdr list))
3013 (when (thing-at-point-looking-at regexp)
3014 (setq found t)
3015 (setq changed (funcall function))
3016 (setq list nil))))
3017 (if found
3018 (or changed (error "Markup at point is complete"))
3019 (error "Nothing to complete at point"))))
3021 (defun markdown-complete-region (beg end)
3022 "Complete markup of objects in region from BEG to END.
3023 Handle all objects in `markdown-complete-alist', in
3024 order."
3025 (interactive "*r")
3026 (let ((end-marker (set-marker (make-marker) end)))
3027 (dolist (element markdown-complete-alist)
3028 (let ((regexp (eval (car element)))
3029 (function (cdr element)))
3030 (goto-char beg)
3031 (while (re-search-forward regexp end-marker 'limit)
3032 (save-excursion (funcall function)))))))
3034 (defun markdown-complete-buffer ()
3035 "Complete markup for all objects in the current buffer."
3036 (interactive "*")
3037 (markdown-complete-region (point-min) (point-max)))
3040 ;;; Markup Cycling ============================================================
3042 (defun markdown-cycle-atx (arg &optional remove)
3043 "Cycle ATX header markup.
3044 Promote header (decrease level) when ARG is 1 and demote
3045 header (increase level) if arg is -1. When REMOVE is non-nil,
3046 remove the header when the level reaches zero and stop cycling
3047 when it reaches six. Otherwise, perform a proper cycling through
3048 levels one through six. Assumes match data is available for
3049 `markdown-regex-header-atx'."
3050 (let* ((old-level (length (match-string 1)))
3051 (new-level (+ old-level arg))
3052 (text (match-string 2)))
3053 (when (not remove)
3054 (setq new-level (% new-level 6))
3055 (setq new-level (cond ((= new-level 0) 6)
3056 ((< new-level 0) (+ new-level 6))
3057 (t new-level))))
3058 (cond
3059 ((= new-level 0)
3060 (markdown-unwrap-thing-at-point nil 0 2))
3061 ((<= new-level 6)
3062 (goto-char (match-beginning 0))
3063 (delete-region (match-beginning 0) (match-end 0))
3064 (markdown-insert-header new-level text nil)))))
3066 (defun markdown-cycle-setext (arg &optional remove)
3067 "Cycle setext header markup.
3068 Promote header (increase level) when ARG is 1 and demote
3069 header (decrease level or remove) if arg is -1. When demoting a
3070 level-two setext header, replace with a level-three atx header.
3071 When REMOVE is non-nil, remove the header when the level reaches
3072 zero. Otherwise, cycle back to a level six atx header. Assumes
3073 match data is available for `markdown-regex-header-setext'."
3074 (let* ((char (char-after (match-beginning 2)))
3075 (old-level (if (char-equal char ?=) 1 2))
3076 (new-level (+ old-level arg))
3077 (text (match-string 1)))
3078 (when (and (not remove) (= new-level 0))
3079 (setq new-level 6))
3080 (cond
3081 ((= new-level 0)
3082 (markdown-unwrap-thing-at-point nil 0 1))
3083 ((<= new-level 2)
3084 (markdown-insert-header new-level nil t))
3085 ((<= new-level 6)
3086 (markdown-insert-header new-level nil nil)))))
3088 (defun markdown-cycle-hr (arg &optional remove)
3089 "Cycle string used for horizontal rule from `markdown-hr-strings'.
3090 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
3091 backwards (promote). When REMOVE is non-nil, remove the hr instead
3092 of cycling when the end of the list is reached.
3093 Assumes match data is available for `markdown-regex-hr'."
3094 (let* ((strings (if (= arg -1)
3095 (reverse markdown-hr-strings)
3096 markdown-hr-strings))
3097 (tail (member (match-string 0) strings))
3098 (new (or (cadr tail)
3099 (if remove
3100 (if (= arg 1)
3102 (car tail))
3103 (car strings)))))
3104 (replace-match new)))
3106 (defun markdown-cycle-bold ()
3107 "Cycle bold markup between underscores and asterisks.
3108 Assumes match data is available for `markdown-regex-bold'."
3109 (save-excursion
3110 (let* ((old-delim (match-string 3))
3111 (new-delim (if (string-equal old-delim "**") "__" "**")))
3112 (replace-match new-delim t t nil 3)
3113 (replace-match new-delim t t nil 5))))
3115 (defun markdown-cycle-italic ()
3116 "Cycle italic markup between underscores and asterisks.
3117 Assumes match data is available for `markdown-regex-italic'."
3118 (save-excursion
3119 (let* ((old-delim (match-string 3))
3120 (new-delim (if (string-equal old-delim "*") "_" "*")))
3121 (replace-match new-delim t t nil 3)
3122 (replace-match new-delim t t nil 5))))
3125 ;;; Keymap ====================================================================
3127 (defvar markdown-mode-map
3128 (let ((map (make-keymap)))
3129 ;; Element insertion
3130 (define-key map "\C-c\C-al" 'markdown-insert-link)
3131 (define-key map "\C-c\C-aL" 'markdown-insert-reference-link-dwim)
3132 (define-key map "\C-c\C-au" 'markdown-insert-uri)
3133 (define-key map "\C-c\C-af" 'markdown-insert-footnote)
3134 (define-key map "\C-c\C-aw" 'markdown-insert-wiki-link)
3135 (define-key map "\C-c\C-ii" 'markdown-insert-image)
3136 (define-key map "\C-c\C-iI" 'markdown-insert-reference-image)
3137 (define-key map "\C-c\C-th" 'markdown-insert-header-dwim)
3138 (define-key map "\C-c\C-tH" 'markdown-insert-header-setext-dwim)
3139 (define-key map "\C-c\C-t1" 'markdown-insert-header-atx-1)
3140 (define-key map "\C-c\C-t2" 'markdown-insert-header-atx-2)
3141 (define-key map "\C-c\C-t3" 'markdown-insert-header-atx-3)
3142 (define-key map "\C-c\C-t4" 'markdown-insert-header-atx-4)
3143 (define-key map "\C-c\C-t5" 'markdown-insert-header-atx-5)
3144 (define-key map "\C-c\C-t6" 'markdown-insert-header-atx-6)
3145 (define-key map "\C-c\C-t!" 'markdown-insert-header-setext-1)
3146 (define-key map "\C-c\C-t@" 'markdown-insert-header-setext-2)
3147 (define-key map "\C-c\C-ss" 'markdown-insert-bold)
3148 (define-key map "\C-c\C-se" 'markdown-insert-italic)
3149 (define-key map "\C-c\C-sc" 'markdown-insert-code)
3150 (define-key map "\C-c\C-sb" 'markdown-insert-blockquote)
3151 (define-key map "\C-c\C-s\C-b" 'markdown-blockquote-region)
3152 (define-key map "\C-c\C-sp" 'markdown-insert-pre)
3153 (define-key map "\C-c\C-s\C-p" 'markdown-pre-region)
3154 (define-key map "\C-c-" 'markdown-insert-hr)
3155 ;; Element insertion (deprecated)
3156 (define-key map "\C-c\C-ar" 'markdown-insert-reference-link-dwim)
3157 (define-key map "\C-c\C-tt" 'markdown-insert-header-setext-1)
3158 (define-key map "\C-c\C-ts" 'markdown-insert-header-setext-2)
3159 ;; Element removal
3160 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
3161 ;; Promotion, Demotion, Completion, and Cycling
3162 (define-key map (kbd "C-c C--") 'markdown-promote)
3163 (define-key map (kbd "C-c C-=") 'markdown-demote)
3164 (define-key map (kbd "C-c C-]") 'markdown-complete)
3165 ;; Following and Jumping
3166 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
3167 (define-key map (kbd "C-c C-j") 'markdown-jump)
3168 ;; Indentation
3169 (define-key map (kbd "C-m") 'markdown-enter-key)
3170 (define-key map (kbd "<backspace>") 'markdown-exdent-or-delete)
3171 (define-key map (kbd "C-c >") 'markdown-indent-region)
3172 (define-key map (kbd "C-c <") 'markdown-exdent-region)
3173 ;; Visibility cycling
3174 (define-key map (kbd "<tab>") 'markdown-cycle)
3175 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
3176 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
3177 (define-key map (kbd "<backtab>") 'markdown-shifttab)
3178 ;; Header navigation
3179 (define-key map (kbd "C-c C-n") 'outline-next-visible-heading)
3180 (define-key map (kbd "C-c C-p") 'outline-previous-visible-heading)
3181 (define-key map (kbd "C-c C-f") 'outline-forward-same-level)
3182 (define-key map (kbd "C-c C-b") 'outline-backward-same-level)
3183 (define-key map (kbd "C-c C-u") 'outline-up-heading)
3184 ;; Buffer-wide commands
3185 (define-key map (kbd "C-c C-c m") 'markdown-other-window)
3186 (define-key map (kbd "C-c C-c p") 'markdown-preview)
3187 (define-key map (kbd "C-c C-c e") 'markdown-export)
3188 (define-key map (kbd "C-c C-c v") 'markdown-export-and-preview)
3189 (define-key map (kbd "C-c C-c o") 'markdown-open)
3190 (define-key map (kbd "C-c C-c w") 'markdown-kill-ring-save)
3191 (define-key map (kbd "C-c C-c c") 'markdown-check-refs)
3192 (define-key map (kbd "C-c C-c n") 'markdown-cleanup-list-numbers)
3193 (define-key map (kbd "C-c C-c ]") 'markdown-complete-buffer)
3194 ;; List editing
3195 (define-key map (kbd "M-<up>") 'markdown-move-up)
3196 (define-key map (kbd "M-<down>") 'markdown-move-down)
3197 (define-key map (kbd "M-<left>") 'markdown-promote)
3198 (define-key map (kbd "M-<right>") 'markdown-demote)
3199 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
3200 ;; Movement
3201 (define-key map (kbd "M-{") 'markdown-backward-paragraph)
3202 (define-key map (kbd "M-}") 'markdown-forward-paragraph)
3203 (define-key map (kbd "M-n") 'markdown-next-link)
3204 (define-key map (kbd "M-p") 'markdown-previous-link)
3205 ;; Alternative keys (in case of problems with the arrow keys)
3206 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
3207 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
3208 (define-key map (kbd "C-c C-x l") 'markdown-promote)
3209 (define-key map (kbd "C-c C-x r") 'markdown-demote)
3210 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item)
3211 map)
3212 "Keymap for Markdown major mode.")
3214 (defvar gfm-mode-map
3215 (let ((map (make-sparse-keymap)))
3216 (set-keymap-parent map markdown-mode-map)
3217 (define-key map (kbd "C-c C-s P") 'markdown-insert-gfm-code-block)
3218 map)
3219 "Keymap for `gfm-mode'.
3220 See also `markdown-mode-map'.")
3223 ;;; Menu ==================================================================
3225 (easy-menu-define markdown-mode-menu markdown-mode-map
3226 "Menu for Markdown mode"
3227 '("Markdown"
3228 ("Show/Hide"
3229 ["Cycle visibility" markdown-cycle (outline-on-heading-p)]
3230 ["Cycle global visibility" markdown-shifttab])
3231 "---"
3232 ["Compile" markdown-other-window]
3233 ["Preview" markdown-preview]
3234 ["Export" markdown-export]
3235 ["Export & View" markdown-export-and-preview]
3236 ["Open" markdown-open]
3237 ["Kill ring save" markdown-kill-ring-save]
3238 "---"
3239 ("Headings"
3240 ["Automatic" markdown-insert-header-dwim]
3241 ["Automatic (prefer setext)" markdown-insert-header-setext-dwim]
3242 "---"
3243 ["First level setext" markdown-insert-header-setext-1]
3244 ["Second level setext" markdown-insert-header-setext-2]
3245 "---"
3246 ["First level atx" markdown-insert-header-atx-1]
3247 ["Second level atx" markdown-insert-header-atx-2]
3248 ["Third level atx" markdown-insert-header-atx-3]
3249 ["Fourth level atx" markdown-insert-header-atx-4]
3250 ["Fifth level atx" markdown-insert-header-atx-5]
3251 ["Sixth level atx" markdown-insert-header-atx-6])
3252 "---"
3253 ["Bold" markdown-insert-bold]
3254 ["Italic" markdown-insert-italic]
3255 ["Blockquote" markdown-insert-blockquote]
3256 ["Preformatted" markdown-insert-pre]
3257 ["Code" markdown-insert-code]
3258 "---"
3259 ["Insert inline link" markdown-insert-link]
3260 ["Insert reference link" markdown-insert-reference-link-dwim]
3261 ["Insert URL" markdown-insert-uri]
3262 ["Insert inline image" markdown-insert-image]
3263 ["Insert reference image" markdown-insert-reference-image]
3264 ["Insert list item" markdown-insert-list-item]
3265 ["Insert horizontal rule" markdown-insert-hr]
3266 ["Insert footnote" markdown-insert-footnote]
3267 ["Kill element" markdown-kill-thing-at-point]
3268 "---"
3269 ["Jump" markdown-jump]
3270 ["Follow link" markdown-follow-thing-at-point]
3271 ("Outline"
3272 ["Next visible heading" outline-next-visible-heading]
3273 ["Previous visible heading" outline-previous-visible-heading]
3274 ["Forward same level" outline-forward-same-level]
3275 ["Backward same level" outline-backward-same-level]
3276 ["Up to parent heading" outline-up-heading])
3277 "---"
3278 ("Completion and Cycling"
3279 ["Complete" markdown-complete]
3280 ["Promote" markdown-promote]
3281 ["Demote" markdown-demote])
3282 ("List editing"
3283 ["Indent list item" markdown-demote]
3284 ["Exdent list item" markdown-promote])
3285 ("Region shifting"
3286 ["Indent region" markdown-indent-region]
3287 ["Exdent region" markdown-exdent-region])
3288 "---"
3289 ["Check references" markdown-check-refs]
3290 ["Clean up list numbering" markdown-cleanup-list-numbers]
3291 ["Complete markup" markdown-complete-buffer]
3292 "---"
3293 ["Version" markdown-show-version]
3297 ;;; imenu =====================================================================
3299 (defun markdown-imenu-create-index ()
3300 "Create and return an imenu index alist for the current buffer.
3301 See `imenu-create-index-function' and `imenu--index-alist' for details."
3302 (let* ((root '(nil . nil))
3303 cur-alist
3304 (cur-level 0)
3305 (empty-heading "-")
3306 (self-heading ".")
3307 hashes pos level heading)
3308 (save-excursion
3309 (goto-char (point-min))
3310 (while (re-search-forward markdown-regex-header (point-max) t)
3311 (cond
3312 ((setq heading (match-string-no-properties 1))
3313 (setq pos (match-beginning 1)
3314 level 1))
3315 ((setq heading (match-string-no-properties 3))
3316 (setq pos (match-beginning 3)
3317 level 2))
3318 ((setq hashes (match-string-no-properties 5))
3319 (setq heading (match-string-no-properties 6)
3320 pos (match-beginning 5)
3321 level (length hashes))))
3322 (let ((alist (list (cons heading pos))))
3323 (cond
3324 ((= cur-level level) ; new sibling
3325 (setcdr cur-alist alist)
3326 (setq cur-alist alist))
3327 ((< cur-level level) ; first child
3328 (dotimes (i (- level cur-level 1))
3329 (setq alist (list (cons empty-heading alist))))
3330 (if cur-alist
3331 (let* ((parent (car cur-alist))
3332 (self-pos (cdr parent)))
3333 (setcdr parent (cons (cons self-heading self-pos) alist)))
3334 (setcdr root alist)) ; primogenitor
3335 (setq cur-alist alist)
3336 (setq cur-level level))
3337 (t ; new sibling of an ancestor
3338 (let ((sibling-alist (last (cdr root))))
3339 (dotimes (i (1- level))
3340 (setq sibling-alist (last (cdar sibling-alist))))
3341 (setcdr sibling-alist alist)
3342 (setq cur-alist alist))
3343 (setq cur-level level)))))
3344 (cdr root))))
3347 ;;; References ================================================================
3349 (defun markdown-insert-reference-definition (ref &optional buffer)
3350 "Add blank REF definition to the end of BUFFER.
3351 REF is a Markdown reference in square brackets, like \"[lisp-history]\"."
3352 (or buffer (setq buffer (current-buffer)))
3353 (with-current-buffer buffer
3354 (goto-char (point-max))
3355 (indent-new-comment-line)
3356 (insert (concat ref ": "))))
3358 (defun markdown-reference-goto-definition ()
3359 "Jump to the definition of the reference at point or create it."
3360 (interactive)
3361 (when (thing-at-point-looking-at markdown-regex-link-reference)
3362 (let* ((text (match-string-no-properties 2))
3363 (reference (match-string-no-properties 4))
3364 (target (downcase (if (string= reference "[]") text reference)))
3365 (loc (cadr (markdown-reference-definition target))))
3366 (if loc
3367 (goto-char loc)
3368 (markdown-insert-reference-definition target (current-buffer))))))
3370 (defun markdown-reference-find-links (reference)
3371 "Return a list of all links for REFERENCE.
3372 REFERENCE should include the surrounding square brackets like [this].
3373 Elements of the list have the form (text start line), where
3374 text is the link text, start is the location at the beginning of
3375 the link, and line is the line number on which the link appears."
3376 (let* ((ref-quote (regexp-quote (substring reference 1 -1)))
3377 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
3378 ref-quote ref-quote))
3379 links)
3380 (save-excursion
3381 (goto-char (point-min))
3382 (while (re-search-forward regexp nil t)
3383 (let* ((text (or (match-string-no-properties 1)
3384 (match-string-no-properties 2)))
3385 (start (match-beginning 0))
3386 (line (markdown-line-number-at-pos)))
3387 (add-to-list 'links (list text start line)))))
3388 links))
3390 (defun markdown-get-undefined-refs ()
3391 "Return a list of undefined Markdown references.
3392 Result is an alist of pairs (reference . occurrences), where
3393 occurrences is itself another alist of pairs (label . line-number).
3394 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
3395 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
3396 \((\"[emacs]\" (\"[Nice editor]\" . 12) (\"[GNU Emacs]\" . 45)) (\"[elisp]\" (\"[manual]\" . 127)))."
3397 (let ((missing))
3398 (save-excursion
3399 (goto-char (point-min))
3400 (while
3401 (re-search-forward markdown-regex-link-reference nil t)
3402 (let* ((text (match-string-no-properties 2))
3403 (reference (match-string-no-properties 4))
3404 (target (downcase (if (string= reference "[]") text reference))))
3405 (unless (markdown-reference-definition target)
3406 (let ((entry (assoc target missing)))
3407 (if (not entry)
3408 (add-to-list 'missing (cons target
3409 (list (cons text (markdown-line-number-at-pos)))) t)
3410 (setcdr entry
3411 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
3412 missing)))
3414 (defconst markdown-reference-check-buffer
3415 "*Undefined references for %buffer%*"
3416 "Pattern for name of buffer for listing undefined references.
3417 The string %buffer% will be replaced by the corresponding
3418 `markdown-mode' buffer name.")
3420 (defun markdown-reference-check-buffer (&optional buffer-name)
3421 "Name and return buffer for reference checking.
3422 BUFFER-NAME is the name of the main buffer being visited."
3423 (or buffer-name (setq buffer-name (buffer-name)))
3424 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
3425 "%buffer%" buffer-name
3426 markdown-reference-check-buffer))))
3427 (with-current-buffer refbuf
3428 (when view-mode
3429 (View-exit-and-edit))
3430 (use-local-map button-buffer-map)
3431 (erase-buffer))
3432 refbuf))
3434 (defconst markdown-reference-links-buffer
3435 "*Reference links for %buffer%*"
3436 "Pattern for name of buffer for listing references.
3437 The string %buffer% will be replaced by the corresponding buffer name.")
3439 (defun markdown-reference-links-buffer (&optional buffer-name)
3440 "Name, setup, and return a buffer for listing links.
3441 BUFFER-NAME is the name of the main buffer being visited."
3442 (or buffer-name (setq buffer-name (buffer-name)))
3443 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
3444 "%buffer%" buffer-name
3445 markdown-reference-links-buffer))))
3446 (with-current-buffer linkbuf
3447 (when view-mode
3448 (View-exit-and-edit))
3449 (use-local-map button-buffer-map)
3450 (erase-buffer))
3451 linkbuf))
3453 (when (markdown-use-buttons-p)
3454 ;; Add an empty Markdown reference definition to the end of buffer
3455 ;; specified in the 'target-buffer property. The reference name is
3456 ;; the button's label.
3457 (define-button-type 'markdown-undefined-reference-button
3458 'help-echo "mouse-1, RET: create definition for undefined reference"
3459 'follow-link t
3460 'face 'bold
3461 'action (lambda (b)
3462 (let ((buffer (button-get b 'target-buffer)))
3463 (markdown-insert-reference-definition (button-label b) buffer)
3464 (switch-to-buffer-other-window buffer)
3465 (goto-char (point-max))
3466 (markdown-check-refs t))))
3468 ;; Jump to line in buffer specified by 'target-buffer property.
3469 ;; Line number is button's 'line property.
3470 (define-button-type 'markdown-goto-line-button
3471 'help-echo "mouse-1, RET: go to line"
3472 'follow-link t
3473 'face 'italic
3474 'action (lambda (b)
3475 (message (button-get b 'buffer))
3476 (switch-to-buffer-other-window (button-get b 'target-buffer))
3477 ;; use call-interactively to silence compiler
3478 (let ((current-prefix-arg (button-get b 'target-line)))
3479 (call-interactively 'goto-line))))
3481 ;; Jumps to a particular link at location given by 'target-char
3482 ;; property in buffer given by 'target-buffer property.
3483 (define-button-type 'markdown-link-button
3484 'help-echo "mouse-1, RET: jump to location of link"
3485 'follow-link t
3486 'face 'bold
3487 'action (lambda (b)
3488 (let ((target (button-get b 'target-buffer))
3489 (loc (button-get b 'target-char)))
3490 (kill-buffer-and-window)
3491 (switch-to-buffer target)
3492 (goto-char loc)))))
3494 (defun markdown-insert-undefined-reference-button (reference oldbuf)
3495 "Insert a button for creating REFERENCE in buffer OLDBUF.
3496 REFERENCE should be a list of the form (reference . occurrences),
3497 as by `markdown-get-undefined-refs'."
3498 (let ((label (car reference)))
3499 (if (markdown-use-buttons-p)
3500 ;; Create a reference button in Emacs 22
3501 (insert-button label
3502 :type 'markdown-undefined-reference-button
3503 'target-buffer oldbuf)
3504 ;; Insert reference as text in Emacs < 22
3505 (insert label))
3506 (insert " (")
3507 (dolist (occurrence (cdr reference))
3508 (let ((line (cdr occurrence)))
3509 (if (markdown-use-buttons-p)
3510 ;; Create a line number button in Emacs 22
3511 (insert-button (number-to-string line)
3512 :type 'markdown-goto-line-button
3513 'target-buffer oldbuf
3514 'target-line line)
3515 ;; Insert line number as text in Emacs < 22
3516 (insert (number-to-string line)))
3517 (insert " ")))
3518 (delete-char -1)
3519 (insert ")")
3520 (newline)))
3522 (defun markdown-insert-link-button (link oldbuf)
3523 "Insert a button for jumping to LINK in buffer OLDBUF.
3524 LINK should be a list of the form (text char line) containing
3525 the link text, location, and line number."
3526 (let ((label (first link))
3527 (char (second link))
3528 (line (third link)))
3529 (if (markdown-use-buttons-p)
3530 ;; Create a reference button in Emacs 22
3531 (insert-button label
3532 :type 'markdown-link-button
3533 'target-buffer oldbuf
3534 'target-char char)
3535 ;; Insert reference as text in Emacs < 22
3536 (insert label))
3537 (insert (format " (line %d)\n" line))))
3539 (defun markdown-reference-goto-link (&optional reference)
3540 "Jump to the location of the first use of REFERENCE."
3541 (interactive)
3542 (unless reference
3543 (if (thing-at-point-looking-at markdown-regex-reference-definition)
3544 (setq reference (match-string-no-properties 1))
3545 (error "No reference definition at point")))
3546 (let ((links (markdown-reference-find-links reference)))
3547 (cond ((= (length links) 1)
3548 (goto-char (cadr (car links))))
3549 ((> (length links) 1)
3550 (let ((oldbuf (current-buffer))
3551 (linkbuf (markdown-reference-links-buffer)))
3552 (with-current-buffer linkbuf
3553 (insert "Links using reference " reference ":\n\n")
3554 (dolist (link (reverse links))
3555 (markdown-insert-link-button link oldbuf)))
3556 (view-buffer-other-window linkbuf)
3557 (goto-char (point-min))
3558 (forward-line 2)))
3560 (error "No links for reference %s" reference)))))
3562 (defun markdown-check-refs (&optional silent)
3563 "Show all undefined Markdown references in current `markdown-mode' buffer.
3564 If SILENT is non-nil, do not message anything when no undefined
3565 references found.
3566 Links which have empty reference definitions are considered to be
3567 defined."
3568 (interactive "P")
3569 (when (not (eq major-mode 'markdown-mode))
3570 (error "Not available in current mode"))
3571 (let ((oldbuf (current-buffer))
3572 (refs (markdown-get-undefined-refs))
3573 (refbuf (markdown-reference-check-buffer)))
3574 (if (null refs)
3575 (progn
3576 (when (not silent)
3577 (message "No undefined references found"))
3578 (kill-buffer refbuf))
3579 (with-current-buffer refbuf
3580 (insert "The following references are undefined:\n\n")
3581 (dolist (ref refs)
3582 (markdown-insert-undefined-reference-button ref oldbuf))
3583 (view-buffer-other-window refbuf)
3584 (goto-char (point-min))
3585 (forward-line 2)))))
3588 ;;; Lists =====================================================================
3590 (defun markdown-insert-list-item (&optional arg)
3591 "Insert a new list item.
3592 If the point is inside unordered list, insert a bullet mark. If
3593 the point is inside ordered list, insert the next number followed
3594 by a period. Use the previous list item to determine the amount
3595 of whitespace to place before and after list markers.
3597 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
3598 decrease the indentation by one level.
3600 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
3601 increase the indentation by one level."
3602 (interactive "p")
3603 (let (bounds item-indent marker indent new-indent new-loc)
3604 (save-match-data
3605 ;; Look for a list item on current or previous non-blank line
3606 (save-excursion
3607 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
3608 (not (bobp))
3609 (markdown-cur-line-blank-p))
3610 (forward-line -1)))
3611 (when bounds
3612 (cond ((save-excursion
3613 (skip-chars-backward " \t")
3614 (looking-at markdown-regex-list))
3615 (beginning-of-line)
3616 (insert "\n")
3617 (forward-line -1))
3618 ((not (markdown-cur-line-blank-p))
3619 (newline)))
3620 (setq new-loc (point)))
3621 ;; Look ahead for a list item on next non-blank line
3622 (unless bounds
3623 (save-excursion
3624 (while (and (null bounds)
3625 (not (eobp))
3626 (markdown-cur-line-blank-p))
3627 (forward-line)
3628 (setq bounds (markdown-cur-list-item-bounds))))
3629 (when bounds
3630 (setq new-loc (point))
3631 (unless (markdown-cur-line-blank-p)
3632 (newline))))
3633 (if (not bounds)
3634 ;; When not in a list, start a new unordered one
3635 (progn
3636 (unless (markdown-cur-line-blank-p)
3637 (insert "\n"))
3638 (insert "* "))
3639 ;; Compute indentation for a new list item
3640 (setq item-indent (nth 2 bounds))
3641 (setq marker (nth 4 bounds))
3642 (setq indent (cond
3643 ((= arg 4) (max (- item-indent 4) 0))
3644 ((= arg 16) (+ item-indent 4))
3645 (t item-indent)))
3646 (setq new-indent (make-string indent 32))
3647 (goto-char new-loc)
3648 (cond
3649 ;; Ordered list
3650 ((string-match "[0-9]" marker)
3651 (if (= arg 16) ;; starting a new column indented one more level
3652 (insert (concat new-indent "1. "))
3653 ;; travel up to the last item and pick the correct number. If
3654 ;; the argument was nil, "new-indent = item-indent" is the same,
3655 ;; so we don't need special treatment. Neat.
3656 (save-excursion
3657 (while (not (looking-at (concat new-indent "\\([0-9]+\\)\\.")))
3658 (forward-line -1)))
3659 (insert (concat new-indent
3660 (int-to-string (1+ (string-to-number (match-string 1))))
3661 ". "))))
3662 ;; Unordered list
3663 ((string-match "[\\*\\+-]" marker)
3664 (insert new-indent marker)))))))
3666 (defun markdown-move-list-item-up ()
3667 "Move the current list item up in the list when possible."
3668 (interactive)
3669 (let (cur prev old)
3670 (when (setq cur (markdown-cur-list-item-bounds))
3671 (setq old (point))
3672 (goto-char (nth 0 cur))
3673 (if (markdown-prev-list-item (nth 3 cur))
3674 (progn
3675 (setq prev (markdown-cur-list-item-bounds))
3676 (condition-case nil
3677 (progn
3678 (transpose-regions (nth 0 prev) (nth 1 prev)
3679 (nth 0 cur) (nth 1 cur) t)
3680 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
3681 ;; Catch error in case regions overlap.
3682 (error (goto-char old))))
3683 (goto-char old)))))
3685 (defun markdown-move-list-item-down ()
3686 "Move the current list item down in the list when possible."
3687 (interactive)
3688 (let (cur next old)
3689 (when (setq cur (markdown-cur-list-item-bounds))
3690 (setq old (point))
3691 (if (markdown-next-list-item (nth 3 cur))
3692 (progn
3693 (setq next (markdown-cur-list-item-bounds))
3694 (condition-case nil
3695 (progn
3696 (transpose-regions (nth 0 cur) (nth 1 cur)
3697 (nth 0 next) (nth 1 next) nil)
3698 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
3699 ;; Catch error in case regions overlap.
3700 (error (goto-char old))))
3701 (goto-char old)))))
3703 (defun markdown-demote-list-item (&optional bounds)
3704 "Indent (or demote) the current list item.
3705 Optionally, BOUNDS of the current list item may be provided if available."
3706 (interactive)
3707 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
3708 (save-excursion
3709 (save-match-data
3710 (let* ((end-marker (make-marker))
3711 (end-marker (set-marker end-marker (nth 1 bounds))))
3712 (goto-char (nth 0 bounds))
3713 (while (< (point) end-marker)
3714 (unless (markdown-cur-line-blank-p)
3715 (insert " "))
3716 (forward-line)))))))
3718 (defun markdown-promote-list-item (&optional bounds)
3719 "Unindent (or promote) the current list item.
3720 Optionally, BOUNDS of the current list item may be provided if available."
3721 (interactive)
3722 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
3723 (save-excursion
3724 (save-match-data
3725 (let* ((end-marker (make-marker))
3726 (end-marker (set-marker end-marker (nth 1 bounds)))
3727 num regexp)
3728 (goto-char (nth 0 bounds))
3729 (when (looking-at "^[ ]\\{1,4\\}")
3730 (setq num (- (match-end 0) (match-beginning 0)))
3731 (setq regexp (format "^[ ]\\{1,%d\\}" num))
3732 (while (and (< (point) end-marker)
3733 (re-search-forward regexp end-marker t))
3734 (replace-match "" nil nil)
3735 (forward-line))))))))
3737 (defun markdown-cleanup-list-numbers-level (&optional pfx)
3738 "Update the numbering for level PFX (as a string of spaces).
3740 Assume that the previously found match was for a numbered item in
3741 a list."
3742 (let ((cpfx pfx)
3743 (idx 0)
3744 (continue t)
3745 (step t)
3746 (sep nil))
3747 (while (and continue (not (eobp)))
3748 (setq step t)
3749 (cond
3750 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
3751 (setq cpfx (match-string-no-properties 1))
3752 (cond
3753 ((string= cpfx pfx)
3754 (replace-match
3755 (concat pfx (number-to-string (setq idx (1+ idx))) ". "))
3756 (setq sep nil))
3757 ;; indented a level
3758 ((string< pfx cpfx)
3759 (setq sep (markdown-cleanup-list-numbers-level cpfx))
3760 (setq step nil))
3761 ;; exit the loop
3763 (setq step nil)
3764 (setq continue nil))))
3766 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
3767 (setq cpfx (match-string-no-properties 1))
3768 (cond
3769 ;; reset if separated before
3770 ((string= cpfx pfx) (when sep (setq idx 0)))
3771 ((string< cpfx pfx)
3772 (setq step nil)
3773 (setq continue nil))))
3774 (t (setq sep t)))
3776 (when step
3777 (beginning-of-line)
3778 (setq continue (= (forward-line) 0))))
3779 sep))
3781 (defun markdown-cleanup-list-numbers ()
3782 "Update the numbering of ordered lists."
3783 (interactive)
3784 (save-excursion
3785 (goto-char (point-min))
3786 (markdown-cleanup-list-numbers-level "")))
3789 ;;; Outline ===================================================================
3791 (defvar markdown-cycle-global-status 1)
3792 (defvar markdown-cycle-subtree-status nil)
3794 (defun markdown-end-of-subtree (&optional invisible-OK)
3795 "Move to the end of the current subtree.
3796 Only visible heading lines are considered, unless INVISIBLE-OK is
3797 non-nil.
3798 Derived from `org-end-of-subtree'."
3799 (outline-back-to-heading invisible-OK)
3800 (let ((first t)
3801 (level (funcall outline-level)))
3802 (while (and (not (eobp))
3803 (or first (> (funcall outline-level) level)))
3804 (setq first nil)
3805 (outline-next-heading))
3806 (if (memq (preceding-char) '(?\n ?\^M))
3807 (progn
3808 ;; Go to end of line before heading
3809 (forward-char -1)
3810 (if (memq (preceding-char) '(?\n ?\^M))
3811 ;; leave blank line before heading
3812 (forward-char -1)))))
3813 (point))
3815 (defun markdown-cycle (&optional arg)
3816 "Visibility cycling for Markdown mode.
3817 If ARG is t, perform global visibility cycling. If the point is
3818 at an atx-style header, cycle visibility of the corresponding
3819 subtree. Otherwise, insert a tab using `indent-relative'.
3820 Derived from `org-cycle'."
3821 (interactive "P")
3822 (cond
3823 ((eq arg t) ;; Global cycling
3824 (cond
3825 ((and (eq last-command this-command)
3826 (eq markdown-cycle-global-status 2))
3827 ;; Move from overview to contents
3828 (hide-sublevels 1)
3829 (message "CONTENTS")
3830 (setq markdown-cycle-global-status 3))
3832 ((and (eq last-command this-command)
3833 (eq markdown-cycle-global-status 3))
3834 ;; Move from contents to all
3835 (show-all)
3836 (message "SHOW ALL")
3837 (setq markdown-cycle-global-status 1))
3840 ;; Defaults to overview
3841 (hide-body)
3842 (message "OVERVIEW")
3843 (setq markdown-cycle-global-status 2))))
3845 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3846 ;; At a heading: rotate between three different views
3847 (outline-back-to-heading)
3848 (let ((goal-column 0) eoh eol eos)
3849 ;; Determine boundaries
3850 (save-excursion
3851 (outline-back-to-heading)
3852 (save-excursion
3853 (beginning-of-line 2)
3854 (while (and (not (eobp)) ;; this is like `next-line'
3855 (get-char-property (1- (point)) 'invisible))
3856 (beginning-of-line 2)) (setq eol (point)))
3857 (outline-end-of-heading) (setq eoh (point))
3858 (markdown-end-of-subtree t)
3859 (skip-chars-forward " \t\n")
3860 (beginning-of-line 1) ; in case this is an item
3861 (setq eos (1- (point))))
3862 ;; Find out what to do next and set `this-command'
3863 (cond
3864 ((= eos eoh)
3865 ;; Nothing is hidden behind this heading
3866 (message "EMPTY ENTRY")
3867 (setq markdown-cycle-subtree-status nil))
3868 ((>= eol eos)
3869 ;; Entire subtree is hidden in one line: open it
3870 (show-entry)
3871 (show-children)
3872 (message "CHILDREN")
3873 (setq markdown-cycle-subtree-status 'children))
3874 ((and (eq last-command this-command)
3875 (eq markdown-cycle-subtree-status 'children))
3876 ;; We just showed the children, now show everything.
3877 (show-subtree)
3878 (message "SUBTREE")
3879 (setq markdown-cycle-subtree-status 'subtree))
3881 ;; Default action: hide the subtree.
3882 (hide-subtree)
3883 (message "FOLDED")
3884 (setq markdown-cycle-subtree-status 'folded)))))
3887 (indent-for-tab-command))))
3889 (defun markdown-shifttab ()
3890 "Global visibility cycling.
3891 Calls `markdown-cycle' with argument t."
3892 (interactive)
3893 (markdown-cycle t))
3895 (defun markdown-outline-level ()
3896 "Return the depth to which a statement is nested in the outline."
3897 (cond
3898 ((match-end 1) 1)
3899 ((match-end 3) 2)
3900 ((- (match-end 5) (match-beginning 5)))))
3903 ;;; Movement ==================================================================
3905 (defun markdown-beginning-of-defun (&optional arg)
3906 "`beginning-of-defun-function' for Markdown.
3907 Move backward to the beginning of the current or previous section.
3908 When ARG is non-nil, repeat that many times. When ARG is negative,
3909 move forward to the ARG-th following section."
3910 (interactive "P")
3911 (or arg (setq arg 1))
3912 (or (re-search-backward markdown-regex-header nil t arg)
3913 (goto-char (point-min))))
3915 (defun markdown-end-of-defun (&optional arg)
3916 "`end-of-defun-function' for Markdown.
3917 Move forward to the end of the current or following section.
3918 When ARG is non-nil, repeat that many times. When ARG is negative,
3919 move back to the ARG-th preceding section."
3920 (interactive "P")
3921 (or arg (setq arg 1))
3922 (when (looking-at markdown-regex-header)
3923 (goto-char (match-beginning 0))
3924 (forward-char 1))
3925 (if (re-search-forward markdown-regex-header nil t arg)
3926 (goto-char (match-beginning 0))
3927 (goto-char (point-max)))
3928 (skip-syntax-backward "-"))
3930 (defun markdown-beginning-of-block ()
3931 "Move the point to the start of the previous text block."
3932 (interactive)
3933 (if (re-search-backward markdown-regex-block-separator nil t)
3934 (goto-char (or (match-end 2) (match-end 0)))
3935 (goto-char (point-min))))
3937 (defun markdown-end-of-block ()
3938 "Move the point to the start of the next text block."
3939 (interactive)
3940 (beginning-of-line)
3941 (skip-syntax-forward "-")
3942 (when (= (point) (point-min))
3943 (forward-char))
3944 (if (re-search-forward markdown-regex-block-separator nil t)
3945 (goto-char (or (match-end 2) (match-end 0)))
3946 (goto-char (point-max)))
3947 (skip-syntax-backward "-")
3948 (forward-line))
3950 (defun markdown-forward-paragraph (arg)
3951 "Move forward one or more paragraphs or by one block.
3952 When ARG is nil or a numeric prefix, call `forward-paragraph'
3953 with ARG. When called with \\[universal-argument], call
3954 `markdown-end-of-block' instead."
3955 (interactive "P")
3956 (or arg (setq arg 1))
3957 (cond ((integerp arg)
3958 (forward-paragraph arg))
3959 ((equal arg '(4))
3960 (markdown-end-of-block))))
3962 (defun markdown-backward-paragraph (arg)
3963 "Move backward one or more paragraphs or by one block.
3964 When ARG is nil or a numeric prefix, call `backward-paragraph'
3965 with ARG. When called with \\[universal-argument], call
3966 `markdown-beginning-of-block' instead."
3967 (interactive "P")
3968 (or arg (setq arg 1))
3969 (cond ((integerp arg)
3970 (backward-paragraph arg))
3971 ((equal arg '(4))
3972 (markdown-beginning-of-block))))
3974 (defun markdown-end-of-block-element ()
3975 "Move the point to the start of the next block unit.
3976 Stops at blank lines, list items, headers, and horizontal rules."
3977 (interactive)
3978 (forward-line)
3979 (while (and (or (not (markdown-prev-line-blank-p))
3980 (markdown-cur-line-blank-p))
3981 (not (or (looking-at markdown-regex-list)
3982 (looking-at markdown-regex-header)
3983 (looking-at markdown-regex-hr)))
3984 (not (eobp)))
3985 (forward-line)))
3987 (defun markdown-next-link ()
3988 "Jump to next inline, reference, or wiki link.
3989 If successful, return point. Otherwise, return nil.
3990 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
3991 (interactive)
3992 (let ((opoint (point)))
3993 (when (or (markdown-link-p) (markdown-wiki-link-p))
3994 ;; At a link already, move past it.
3995 (goto-char (+ (match-end 0) 1)))
3996 ;; Search for the next wiki link and move to the beginning.
3997 (if (re-search-forward markdown-regex-link-generic nil t)
3998 ;; Group 1 will move past non-escape character in wiki link regexp.
3999 ;; Go to beginning of group zero for all other link types.
4000 (goto-char (or (match-beginning 1) (match-beginning 0)))
4001 (goto-char opoint)
4002 nil)))
4004 (defun markdown-previous-link ()
4005 "Jump to previous wiki link.
4006 If successful, return point. Otherwise, return nil.
4007 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
4008 (interactive)
4009 (if (re-search-backward markdown-regex-link-generic nil t)
4010 (goto-char (or (match-beginning 1) (match-beginning 0)))
4011 nil))
4014 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
4016 (defun markdown-move-up ()
4017 "Move list item up.
4018 Calls `markdown-move-list-item-up'."
4019 (interactive)
4020 (markdown-move-list-item-up))
4022 (defun markdown-move-down ()
4023 "Move list item down.
4024 Calls `markdown-move-list-item-down'."
4025 (interactive)
4026 (markdown-move-list-item-down))
4028 (defun markdown-promote ()
4029 "Either promote header or list item at point or cycle markup.
4030 See `markdown-cycle-atx', `markdown-cycle-setext', and
4031 `markdown-promote-list-item'."
4032 (interactive)
4033 (let (bounds)
4034 (cond
4035 ;; Promote atx header
4036 ((thing-at-point-looking-at markdown-regex-header-atx)
4037 (markdown-cycle-atx -1))
4038 ;; Promote setext header
4039 ((thing-at-point-looking-at markdown-regex-header-setext)
4040 (markdown-cycle-setext -1))
4041 ;; Promote horizonal rule
4042 ((thing-at-point-looking-at markdown-regex-hr)
4043 (markdown-cycle-hr -1))
4044 ;; Promote list item
4045 ((setq bounds (markdown-cur-list-item-bounds))
4046 (markdown-promote-list-item))
4047 ;; Promote bold
4048 ((thing-at-point-looking-at markdown-regex-bold)
4049 (markdown-cycle-bold))
4050 ;; Promote italic
4051 ((thing-at-point-looking-at markdown-regex-italic)
4052 (markdown-cycle-italic))
4054 (error "Nothing to promote at point")))))
4056 (defun markdown-demote ()
4057 "Either demote header or list item at point or cycle or remove markup.
4058 See `markdown-cycle-atx', `markdown-cycle-setext', and
4059 `markdown-demote-list-item'."
4060 (interactive)
4061 (let (bounds)
4062 (cond
4063 ;; Demote atx header
4064 ((thing-at-point-looking-at markdown-regex-header-atx)
4065 (markdown-cycle-atx 1))
4066 ;; Demote setext header
4067 ((thing-at-point-looking-at markdown-regex-header-setext)
4068 (markdown-cycle-setext 1))
4069 ;; Demote horizonal rule
4070 ((thing-at-point-looking-at markdown-regex-hr)
4071 (markdown-cycle-hr 1))
4072 ;; Demote list item
4073 ((setq bounds (markdown-cur-list-item-bounds))
4074 (markdown-demote-list-item))
4075 ;; Demote bold
4076 ((thing-at-point-looking-at markdown-regex-bold)
4077 (markdown-cycle-bold))
4078 ;; Demote italic
4079 ((thing-at-point-looking-at markdown-regex-italic)
4080 (markdown-cycle-italic))
4082 (error "Nothing to demote at point")))))
4085 ;;; Commands ==================================================================
4087 (defun markdown (&optional output-buffer-name)
4088 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
4089 The output buffer name defaults to `markdown-output-buffer-name'.
4090 Return the name of the output buffer used."
4091 (interactive)
4092 (save-window-excursion
4093 (let ((begin-region)
4094 (end-region))
4095 (if (markdown-use-region-p)
4096 (setq begin-region (region-beginning)
4097 end-region (region-end))
4098 (setq begin-region (point-min)
4099 end-region (point-max)))
4101 (unless output-buffer-name
4102 (setq output-buffer-name markdown-output-buffer-name))
4104 (cond
4105 ;; Handle case when `markdown-command' does not read from stdin
4106 (markdown-command-needs-filename
4107 (if (not buffer-file-name)
4108 (error "Must be visiting a file")
4109 (shell-command (concat markdown-command " "
4110 (shell-quote-argument buffer-file-name))
4111 output-buffer-name)))
4112 ;; Pass region to `markdown-command' via stdin
4114 (shell-command-on-region begin-region end-region markdown-command
4115 output-buffer-name))))
4116 output-buffer-name))
4118 (defun markdown-standalone (&optional output-buffer-name)
4119 "Special function to provide standalone HTML output.
4120 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
4121 (interactive)
4122 (setq output-buffer-name (markdown output-buffer-name))
4123 (with-current-buffer output-buffer-name
4124 (set-buffer output-buffer-name)
4125 (goto-char (point-min))
4126 (unless (markdown-output-standalone-p)
4127 (markdown-add-xhtml-header-and-footer output-buffer-name))
4128 (html-mode))
4129 output-buffer-name)
4131 (defun markdown-other-window (&optional output-buffer-name)
4132 "Run `markdown-command' on current buffer and display in other window.
4133 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
4134 that name."
4135 (interactive)
4136 (display-buffer (markdown-standalone output-buffer-name)))
4138 (defun markdown-output-standalone-p ()
4139 "Determine whether `markdown-command' output is standalone XHTML.
4140 Standalone XHTML output is identified by an occurrence of
4141 `markdown-xhtml-standalone-regexp' in the first five lines of output."
4142 (re-search-forward
4143 markdown-xhtml-standalone-regexp
4144 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
4147 (defun markdown-add-xhtml-header-and-footer (title)
4148 "Wrap XHTML header and footer with given TITLE around current buffer."
4149 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
4150 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
4151 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
4152 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
4153 "<head>\n<title>")
4154 (insert title)
4155 (insert "</title>\n")
4156 (when (> (length markdown-content-type) 0)
4157 (insert
4158 (format
4159 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
4160 markdown-content-type
4161 (or (and markdown-coding-system
4162 (fboundp 'coding-system-get)
4163 (coding-system-get markdown-coding-system
4164 'mime-charset))
4165 (and (fboundp 'coding-system-get)
4166 (coding-system-get buffer-file-coding-system
4167 'mime-charset))
4168 "iso-8859-1"))))
4169 (if (> (length markdown-css-path) 0)
4170 (insert "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
4171 markdown-css-path
4172 "\" />\n"))
4173 (when (> (length markdown-xhtml-header-content) 0)
4174 (insert markdown-xhtml-header-content))
4175 (insert "\n</head>\n\n"
4176 "<body>\n\n")
4177 (goto-char (point-max))
4178 (insert "\n"
4179 "</body>\n"
4180 "</html>\n"))
4182 (defun markdown-preview (&optional output-buffer-name)
4183 "Run `markdown-command' on the current buffer and view output in browser.
4184 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
4185 that name."
4186 (interactive)
4187 (browse-url-of-buffer (markdown markdown-output-buffer-name)))
4189 (defun markdown-export-file-name (&optional extension)
4190 "Attempt to generate a filename for Markdown output.
4191 The file extension will be EXTENSION if given, or .html by default.
4192 If the current buffer is visiting a file, we construct a new
4193 output filename based on that filename. Otherwise, return nil."
4194 (when (buffer-file-name)
4195 (unless extension
4196 (setq extension ".html"))
4197 (concat
4198 (cond
4199 ((buffer-file-name)
4200 (file-name-sans-extension (buffer-file-name)))
4201 (t (buffer-name)))
4202 extension)))
4204 (defun markdown-export (&optional output-file)
4205 "Run Markdown on the current buffer, save to file, and return the filename.
4206 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
4207 generated by `markdown-export-file-name', which will be constructed using the
4208 current filename, but with the extension removed and replaced with .html."
4209 (interactive)
4210 (unless output-file
4211 (setq output-file (markdown-export-file-name ".html")))
4212 (when output-file
4213 (let* ((init-buf (current-buffer))
4214 (init-point (point))
4215 (init-buf-string (buffer-string))
4216 (output-buffer (find-file-noselect output-file))
4217 (output-buffer-name (buffer-name output-buffer)))
4218 (run-hooks 'markdown-before-export-hook)
4219 (markdown-standalone output-buffer-name)
4220 (with-current-buffer output-buffer
4221 (run-hooks 'markdown-after-export-hook)
4222 (save-buffer))
4223 ;; if modified, restore initial buffer
4224 (when (buffer-modified-p init-buf)
4225 (erase-buffer)
4226 (insert init-buf-string)
4227 (save-buffer)
4228 (goto-char init-point))
4229 output-file)))
4231 (defun markdown-export-and-preview ()
4232 "Export to XHTML using `markdown-export' and browse the resulting file."
4233 (interactive)
4234 (browse-url (markdown-export)))
4236 (defun markdown-open ()
4237 "Open file for the current buffer with `markdown-open-command'."
4238 (interactive)
4239 (if (not markdown-open-command)
4240 (error "Variable `markdown-open-command' must be set")
4241 (if (not buffer-file-name)
4242 (error "Must be visiting a file")
4243 (call-process markdown-open-command
4244 nil nil nil buffer-file-name))))
4246 (defun markdown-kill-ring-save ()
4247 "Run Markdown on file and store output in the kill ring."
4248 (interactive)
4249 (save-window-excursion
4250 (markdown)
4251 (with-current-buffer markdown-output-buffer-name
4252 (kill-ring-save (point-min) (point-max)))))
4255 ;;; Links =====================================================================
4257 (defun markdown-link-p ()
4258 "Return non-nil when `point' is at a non-wiki link.
4259 See `markdown-wiki-link-p' for more information."
4260 (let ((case-fold-search nil))
4261 (and (not (markdown-wiki-link-p))
4262 (or (thing-at-point-looking-at markdown-regex-link-inline)
4263 (thing-at-point-looking-at markdown-regex-link-reference)
4264 (thing-at-point-looking-at markdown-regex-uri)
4265 (thing-at-point-looking-at markdown-regex-angle-uri)))))
4267 (defun markdown-link-link ()
4268 "Return the link part of the regular (non-wiki) link at point.
4269 Works with both inline and reference style links. If point is
4270 not at a link or the link reference is not defined returns nil."
4271 (cond
4272 ((thing-at-point-looking-at markdown-regex-link-inline)
4273 (match-string-no-properties 5))
4274 ((thing-at-point-looking-at markdown-regex-link-reference)
4275 (let* ((text (match-string-no-properties 2))
4276 (reference (match-string-no-properties 4))
4277 (target (downcase (if (string= reference "[]") text reference))))
4278 (car (markdown-reference-definition target))))
4279 ((thing-at-point-looking-at markdown-regex-uri)
4280 (match-string-no-properties 0))
4281 ((thing-at-point-looking-at markdown-regex-angle-uri)
4282 (match-string-no-properties 2))
4283 (t nil)))
4285 (defun markdown-follow-link-at-point ()
4286 "Open the current non-wiki link in a browser."
4287 (interactive)
4288 (if (markdown-link-p) (browse-url (markdown-link-link))
4289 (error "Point is not at a Markdown link or URI")))
4292 ;;; WikiLink Following/Markup =================================================
4294 (defun markdown-wiki-link-p ()
4295 "Return non-nil when `point' is at a true wiki link.
4296 A true wiki link name matches `markdown-regex-wiki-link' but does not
4297 match the current file name after conversion. This modifies the data
4298 returned by `match-data'. Note that the potential wiki link name must
4299 be available via `match-string'."
4300 (let ((case-fold-search nil))
4301 (and (thing-at-point-looking-at markdown-regex-wiki-link)
4302 (or (not buffer-file-name)
4303 (not (string-equal (buffer-file-name)
4304 (markdown-convert-wiki-link-to-filename
4305 (markdown-wiki-link-link)))))
4306 (not (save-match-data
4307 (save-excursion))))))
4309 (defun markdown-wiki-link-link ()
4310 "Return the link part of the wiki link using current match data.
4311 The location of the link component depends on the value of
4312 `markdown-wiki-link-alias-first'."
4313 (if markdown-wiki-link-alias-first
4314 (or (match-string-no-properties 4) (match-string-no-properties 2))
4315 (match-string-no-properties 2)))
4317 (defun markdown-wiki-link-alias ()
4318 "Return the alias or text part of the wiki link using current match data.
4319 The location of the alias component depends on the value of
4320 `markdown-wiki-link-alias-first'."
4321 (if markdown-wiki-link-alias-first
4322 (match-string-no-properties 2)
4323 (or (match-string-no-properties 4) (match-string-no-properties 2))))
4325 (defun markdown-convert-wiki-link-to-filename (name)
4326 "Generate a filename from the wiki link NAME.
4327 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
4328 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
4329 and [[test test]] both map to Test-test.ext."
4330 (let ((basename (markdown-replace-regexp-in-string
4331 "[[:space:]\n]" markdown-link-space-sub-char name)))
4332 (when (eq major-mode 'gfm-mode)
4333 (setq basename (concat (upcase (substring basename 0 1))
4334 (downcase (substring basename 1 nil)))))
4335 (concat basename
4336 (if (buffer-file-name)
4337 (concat "."
4338 (file-name-extension (buffer-file-name)))))))
4340 (defun markdown-follow-wiki-link (name &optional other)
4341 "Follow the wiki link NAME.
4342 Convert the name to a file name and call `find-file'. Ensure that
4343 the new buffer remains in `markdown-mode'. Open the link in another
4344 window when OTHER is non-nil."
4345 (let ((filename (markdown-convert-wiki-link-to-filename name))
4346 (wp (file-name-directory buffer-file-name)))
4347 (when other (other-window 1))
4348 (find-file (concat wp filename)))
4349 (when (not (eq major-mode 'markdown-mode))
4350 (markdown-mode)))
4352 (defun markdown-follow-wiki-link-at-point (&optional arg)
4353 "Find Wiki Link at point.
4354 With prefix argument ARG, open the file in other window.
4355 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
4356 (interactive "P")
4357 (if (markdown-wiki-link-p)
4358 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
4359 (error "Point is not at a Wiki Link")))
4361 (defun markdown-highlight-wiki-link (from to face)
4362 "Highlight the wiki link in the region between FROM and TO using FACE."
4363 (put-text-property from to 'font-lock-face face))
4365 (defun markdown-unfontify-region-wiki-links (from to)
4366 "Remove wiki link faces from the region specified by FROM and TO."
4367 (interactive "nfrom: \nnto: ")
4368 (remove-text-properties from to '(font-lock-face markdown-link-face))
4369 (remove-text-properties from to '(font-lock-face markdown-missing-link-face)))
4371 (defun markdown-fontify-region-wiki-links (from to)
4372 "Search region given by FROM and TO for wiki links and fontify them.
4373 If a wiki link is found check to see if the backing file exists
4374 and highlight accordingly."
4375 (goto-char from)
4376 (save-match-data
4377 (while (re-search-forward markdown-regex-wiki-link to t)
4378 (let ((highlight-beginning (match-beginning 1))
4379 (highlight-end (match-end 1))
4380 (file-name
4381 (markdown-convert-wiki-link-to-filename
4382 (markdown-wiki-link-link))))
4383 (if (file-exists-p file-name)
4384 (markdown-highlight-wiki-link
4385 highlight-beginning highlight-end markdown-link-face)
4386 (markdown-highlight-wiki-link
4387 highlight-beginning highlight-end markdown-link-face)
4388 (markdown-highlight-wiki-link
4389 highlight-beginning highlight-end markdown-missing-link-face))))))
4391 (defun markdown-extend-changed-region (from to)
4392 "Extend region given by FROM and TO so that we can fontify all links.
4393 The region is extended to the first newline before and the first
4394 newline after."
4395 ;; start looking for the first new line before 'from
4396 (goto-char from)
4397 (re-search-backward "\n" nil t)
4398 (let ((new-from (point-min))
4399 (new-to (point-max)))
4400 (if (not (= (point) from))
4401 (setq new-from (point)))
4402 ;; do the same thing for the first new line after 'to
4403 (goto-char to)
4404 (re-search-forward "\n" nil t)
4405 (if (not (= (point) to))
4406 (setq new-to (point)))
4407 (values new-from new-to)))
4409 (defun markdown-check-change-for-wiki-link (from to change)
4410 "Check region between FROM and TO for wiki links and re-fontfy as needed.
4411 Designed to be used with the `after-change-functions' hook.
4412 CHANGE is the number of bytes of pre-change text replaced by the
4413 given range."
4414 (interactive "nfrom: \nnto: \nnchange: ")
4415 (let* ((modified (buffer-modified-p))
4416 (buffer-undo-list t)
4417 (inhibit-read-only t)
4418 (inhibit-point-motion-hooks t)
4419 deactivate-mark
4420 buffer-file-truename)
4421 (unwind-protect
4422 (save-excursion
4423 (save-match-data
4424 (save-restriction
4425 ;; Extend the region to fontify so that it starts
4426 ;; and ends at safe places.
4427 (multiple-value-bind (new-from new-to)
4428 (markdown-extend-changed-region from to)
4429 ;; Unfontify existing fontification (start from scratch)
4430 (markdown-unfontify-region-wiki-links new-from new-to)
4431 ;; Now do the fontification.
4432 (markdown-fontify-region-wiki-links new-from new-to)))))
4433 (and (not modified)
4434 (buffer-modified-p)
4435 (set-buffer-modified-p nil)))))
4437 (defun markdown-fontify-buffer-wiki-links ()
4438 "Refontify all wiki links in the buffer."
4439 (interactive)
4440 (markdown-check-change-for-wiki-link (point-min) (point-max) 0))
4443 ;;; Following and Jumping =====================================================
4445 (defun markdown-follow-thing-at-point (arg)
4446 "Follow thing at point if possible, such as a reference link or wiki link.
4447 Opens inline and reference links in a browser. Opens wiki links
4448 to other files in the current window, or the another window if
4449 ARG is non-nil.
4450 See `markdown-follow-link-at-point' and
4451 `markdown-follow-wiki-link-at-point'."
4452 (interactive "P")
4453 (cond ((markdown-link-p)
4454 (markdown-follow-link-at-point))
4455 ((markdown-wiki-link-p)
4456 (markdown-follow-wiki-link-at-point arg))
4458 (error "Nothing to follow at point"))))
4460 (defun markdown-jump ()
4461 "Jump to another location based on context at point.
4462 Jumps between reference links and definitions; between footnote
4463 markers and footnote text."
4464 (interactive)
4465 (cond ((markdown-footnote-text-positions)
4466 (markdown-footnote-return))
4467 ((markdown-footnote-marker-positions)
4468 (markdown-footnote-goto-text))
4469 ((thing-at-point-looking-at markdown-regex-link-reference)
4470 (markdown-reference-goto-definition))
4471 ((thing-at-point-looking-at markdown-regex-reference-definition)
4472 (markdown-reference-goto-link (match-string-no-properties 1)))
4474 (error "Nothing to jump to from context at point"))))
4477 ;;; Miscellaneous =============================================================
4479 (defun markdown-compress-whitespace-string (str)
4480 "Compress whitespace in STR and return result.
4481 Leading and trailing whitespace is removed. Sequences of multiple
4482 spaces, tabs, and newlines are replaced with single spaces."
4483 (replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
4484 (replace-regexp-in-string "[ \t\n]+" " " str)))
4486 (defun markdown-line-number-at-pos (&optional pos)
4487 "Return (narrowed) buffer line number at position POS.
4488 If POS is nil, use current buffer location.
4489 This is an exact copy of `line-number-at-pos' for use in emacs21."
4490 (let ((opoint (or pos (point))) start)
4491 (save-excursion
4492 (goto-char (point-min))
4493 (setq start (point))
4494 (goto-char opoint)
4495 (forward-line 0)
4496 (1+ (count-lines start (point))))))
4498 (defun markdown-nobreak-p ()
4499 "Return nil if it is acceptable to break the current line at the point."
4500 ;; inside in square brackets (e.g., link anchor text)
4501 (looking-back "\\[[^]]*"))
4503 (defun markdown-adaptive-fill-function ()
4504 "Return prefix for filling paragraph or nil if not determined."
4505 (cond
4506 ;; List item inside blockquote
4507 ((looking-at "^[ \t]*>[ \t]*\\([0-9]+\\.\\|[*+-]\\)[ \t]+")
4508 (replace-regexp-in-string
4509 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
4510 ;; Blockquote
4511 ((looking-at "^[ \t]*>[ \t]*")
4512 (match-string-no-properties 0))
4513 ;; List items
4514 ((looking-at markdown-regex-list)
4515 (match-string-no-properties 0))
4516 ;; No match
4517 (t nil)))
4520 ;;; Extensions ================================================================
4522 (defun markdown-reload-extensions ()
4523 "Check settings, update font-lock keywords, and re-fontify buffer."
4524 (interactive)
4525 (when (eq major-mode 'markdown-mode)
4526 (setq markdown-mode-font-lock-keywords
4527 (append
4528 (when markdown-enable-math
4529 markdown-mode-font-lock-keywords-math)
4530 markdown-mode-font-lock-keywords-basic
4531 markdown-mode-font-lock-keywords-core))
4532 (setq font-lock-defaults '(markdown-mode-font-lock-keywords))
4533 (font-lock-refresh-defaults)))
4535 (defun markdown-enable-math (&optional arg)
4536 "Toggle support for inline and display LaTeX math expressions.
4537 With a prefix argument ARG, enable math mode if ARG is positive,
4538 and disable it otherwise. If called from Lisp, enable the mode
4539 if ARG is omitted or nil."
4540 (interactive (list (or current-prefix-arg 'toggle)))
4541 (setq markdown-enable-math
4542 (if (eq arg 'toggle)
4543 (not markdown-enable-math)
4544 (> (prefix-numeric-value arg) 0)))
4545 (if markdown-enable-math
4546 (message "markdown-mode math support enabled")
4547 (message "markdown-mode math support disabled"))
4548 (markdown-reload-extensions))
4551 ;;; Mode Definition ==========================================================
4553 (defun markdown-show-version ()
4554 "Show the version number in the minibuffer."
4555 (interactive)
4556 (message "markdown-mode, version %s" markdown-mode-version))
4558 ;;;###autoload
4559 (define-derived-mode markdown-mode text-mode "Markdown"
4560 "Major mode for editing Markdown files."
4561 ;; Natural Markdown tab width
4562 (setq tab-width 4)
4563 ;; Comments
4564 (make-local-variable 'comment-start)
4565 (setq comment-start "<!-- ")
4566 (make-local-variable 'comment-end)
4567 (setq comment-end " -->")
4568 (make-local-variable 'comment-start-skip)
4569 (setq comment-start-skip "<!--[ \t]*")
4570 (make-local-variable 'comment-column)
4571 (setq comment-column 0)
4572 ;; Font lock.
4573 (set (make-local-variable 'markdown-mode-font-lock-keywords) nil)
4574 (set (make-local-variable 'font-lock-defaults) nil)
4575 (set (make-local-variable 'font-lock-multiline) t)
4576 (markdown-reload-extensions)
4577 ;; Extensions
4578 (make-local-variable 'markdown-enable-math)
4579 (add-hook 'hack-local-variables-hook 'markdown-reload-extensions)
4580 ;; For imenu support
4581 (setq imenu-create-index-function 'markdown-imenu-create-index)
4582 ;; For menu support in XEmacs
4583 (easy-menu-add markdown-mode-menu markdown-mode-map)
4584 ;; Defun movement
4585 (set (make-local-variable 'beginning-of-defun-function)
4586 'markdown-beginning-of-defun)
4587 (set (make-local-variable 'end-of-defun-function)
4588 'markdown-end-of-defun)
4589 ;; Paragraph filling
4590 (set (make-local-variable 'paragraph-start)
4591 "\f\\|[ \t]*$\\|[ \t]*[*+-] \\|[ \t]*[0-9]+\\.\\|[ \t]*: ")
4592 (set (make-local-variable 'paragraph-separate)
4593 "\\(?:[ \t\f]\\|.* \\)*$")
4594 (set (make-local-variable 'adaptive-fill-first-line-regexp)
4595 "\\`[ \t]*>[ \t]*?\\'")
4596 (set (make-local-variable 'adaptive-fill-function)
4597 'markdown-adaptive-fill-function)
4598 ;; Outline mode
4599 (make-local-variable 'outline-regexp)
4600 (setq outline-regexp markdown-regex-header)
4601 (make-local-variable 'outline-level)
4602 (setq outline-level 'markdown-outline-level)
4603 ;; Cause use of ellipses for invisible text.
4604 (add-to-invisibility-spec '(outline . t))
4605 ;; Indentation and filling
4606 (make-local-variable 'fill-nobreak-predicate)
4607 (add-hook 'fill-nobreak-predicate 'markdown-nobreak-p)
4608 (setq indent-line-function markdown-indent-function)
4610 ;; Prepare hooks for XEmacs compatibility
4611 (when (featurep 'xemacs)
4612 (make-local-hook 'after-change-functions)
4613 (make-local-hook 'font-lock-extend-region-functions)
4614 (make-local-hook 'window-configuration-change-hook))
4616 ;; Multiline font lock
4617 (add-hook 'font-lock-extend-region-functions
4618 'markdown-font-lock-extend-region)
4620 ;; Anytime text changes make sure it gets fontified correctly
4621 (add-hook 'after-change-functions 'markdown-check-change-for-wiki-link t t)
4623 ;; If we left the buffer there is a really good chance we were
4624 ;; creating one of the wiki link documents. Make sure we get
4625 ;; refontified when we come back.
4626 (add-hook 'window-configuration-change-hook
4627 'markdown-fontify-buffer-wiki-links t t)
4629 ;; do the initial link fontification
4630 (markdown-fontify-buffer-wiki-links))
4632 ;;(add-to-list 'auto-mode-alist '("\\.text$" . markdown-mode))
4635 ;;; GitHub Flavored Markdown Mode ============================================
4637 (defvar gfm-font-lock-keywords
4638 (append
4639 ;; GFM features to match first
4640 (list
4641 (cons 'markdown-match-gfm-code-blocks '((1 markdown-pre-face)
4642 (2 markdown-language-keyword-face)
4643 (3 markdown-pre-face)
4644 (4 markdown-pre-face))))
4645 ;; Basic Markdown features (excluding possibly overridden ones)
4646 markdown-mode-font-lock-keywords-basic
4647 ;; GFM features to match last
4648 (list
4649 (cons markdown-regex-gfm-italic '(2 markdown-italic-face))))
4650 "Default highlighting expressions for GitHub-flavored Markdown mode.")
4652 ;;;###autoload
4653 (define-derived-mode gfm-mode markdown-mode "GFM"
4654 "Major mode for editing GitHub Flavored Markdown files."
4655 (setq markdown-link-space-sub-char "-")
4656 (set (make-local-variable 'font-lock-defaults)
4657 '(gfm-font-lock-keywords))
4658 (auto-fill-mode 0)
4659 ;; Use visual-line-mode if available, fall back to longlines-mode:
4660 (if (fboundp 'visual-line-mode)
4661 (visual-line-mode 1)
4662 (longlines-mode 1))
4663 ;; do the initial link fontification
4664 (markdown-fontify-buffer-wiki-links))
4667 (provide 'markdown-mode)
4669 ;;; markdown-mode.el ends here