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