Fix markdown-code-at-point-p false positive
[markdown-mode.git] / markdown-mode.el
blob5094fdc6b4ad46e13c182449b3217ab7441023d6
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 found)
1767 (markdown-beginning-of-block)
1768 (while (and (markdown-match-code end-of-block)
1769 (setq found t)
1770 (< (match-end 0) old-point)))
1771 (and found ; matched something
1772 (<= (match-beginning 0) old-point) ; match contains old-point
1773 (>= (match-end 0) old-point)))))
1776 ;;; Markdown Font Lock Matching Functions =====================================
1778 (defun markdown-match-comments (last)
1779 "Match HTML comments from the point to LAST."
1780 (cond ((search-forward "<!--" last t)
1781 (backward-char 4)
1782 (let ((beg (point)))
1783 (cond ((search-forward-regexp "--[ \t]*>" last t)
1784 (set-match-data (list beg (point)))
1786 (t nil))))
1787 (t nil)))
1789 (defun markdown-match-code (last)
1790 "Match inline code from the point to LAST."
1791 (unless (bobp)
1792 (backward-char 1))
1793 (cond ((re-search-forward markdown-regex-code last t)
1794 (set-match-data (list (match-beginning 2) (match-end 2)
1795 (match-beginning 4) (match-end 4)))
1796 (goto-char (match-end 0))
1798 (t (forward-char 2) nil)))
1800 (defun markdown-match-pre-blocks (last)
1801 "Match Markdown pre blocks from point to LAST."
1802 (let ((levels (markdown-calculate-list-levels))
1803 indent pre-regexp end-regexp begin end stop)
1804 (while (and (< (point) last) (not end))
1805 ;; Search for a region with sufficient indentation
1806 (if (null levels)
1807 (setq indent 1)
1808 (setq indent (1+ (length levels))))
1809 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1810 (setq end-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1812 (cond
1813 ;; If not at the beginning of a line, move forward
1814 ((not (bolp)) (forward-line))
1815 ;; Move past blank lines
1816 ((markdown-cur-line-blank-p) (forward-line))
1817 ;; At headers and horizontal rules, reset levels
1818 ((markdown-new-baseline-p) (forward-line) (setq levels nil))
1819 ;; If the current line has sufficient indentation, mark out pre block
1820 ((looking-at pre-regexp)
1821 (setq begin (match-beginning 0))
1822 (while (and (or (looking-at pre-regexp) (markdown-cur-line-blank-p))
1823 (not (eobp)))
1824 (forward-line))
1825 (setq end (point)))
1826 ;; If current line has a list marker, update levels, move to end of block
1827 ((looking-at markdown-regex-list)
1828 (setq levels (markdown-update-list-levels
1829 (match-string 2) (markdown-cur-line-indent) levels))
1830 (markdown-end-of-block-element))
1831 ;; If this is the end of the indentation level, adjust levels accordingly.
1832 ;; Only match end of indentation level if levels is not the empty list.
1833 ((and (car levels) (looking-at end-regexp))
1834 (setq levels (markdown-update-list-levels
1835 nil (markdown-cur-line-indent) levels))
1836 (markdown-end-of-block-element))
1837 (t (markdown-end-of-block-element))))
1839 (if (not (and begin end))
1840 ;; Return nil if no pre block was found
1842 ;; Set match data and return t upon success
1843 (set-match-data (list begin end))
1844 t)))
1846 (defun markdown-match-fenced-code-blocks (last)
1847 "Match fenced code blocks from the point to LAST."
1848 (cond ((search-forward-regexp "^\\([~]\\{3,\\}\\)" last t)
1849 (beginning-of-line)
1850 (let ((beg (point)))
1851 (forward-line)
1852 (cond ((search-forward-regexp
1853 (concat "^" (match-string 1) "~*") last t)
1854 (set-match-data (list beg (point)))
1856 (t nil))))
1857 (t nil)))
1859 (defun markdown-match-gfm-code-blocks (last)
1860 "Match GFM quoted code blocks from point to LAST."
1861 (let (open lang body close all)
1862 (cond ((and (eq major-mode 'gfm-mode)
1863 (search-forward-regexp "^\\(```\\)\\(\\w+\\)?$" last t))
1864 (beginning-of-line)
1865 (setq open (list (match-beginning 1) (match-end 1))
1866 lang (list (match-beginning 2) (match-end 2)))
1867 (forward-line)
1868 (setq body (list (point)))
1869 (cond ((search-forward-regexp "^```$" last t)
1870 (setq body (reverse (cons (1- (match-beginning 0)) body))
1871 close (list (match-beginning 0) (match-end 0))
1872 all (list (car open) (match-end 0)))
1873 (set-match-data (append all open lang body close))
1875 (t nil)))
1876 (t nil))))
1878 (defun markdown-match-generic-metadata (regexp last)
1879 "Match generic metadata specified by REGEXP from the point to LAST."
1880 (let ((header-end (save-excursion
1881 (goto-char (point-min))
1882 (if (re-search-forward "\n\n" (point-max) t)
1883 (match-beginning 0)
1884 (point-max)))))
1885 (cond ((>= (point) header-end)
1886 ;; Don't match anything outside of the header.
1887 nil)
1888 ((re-search-forward regexp (min last header-end) t)
1889 ;; If a metadata item is found, it may span several lines.
1890 (let ((key-beginning (match-beginning 1))
1891 (key-end (match-end 1))
1892 (value-beginning (match-beginning 2)))
1893 (while (and (not (looking-at regexp))
1894 (not (> (point) (min last header-end)))
1895 (not (eobp)))
1896 (forward-line))
1897 (unless (eobp)
1898 (forward-line -1)
1899 (end-of-line))
1900 (set-match-data (list key-beginning (point) ; complete metadata
1901 key-beginning key-end ; key
1902 value-beginning (point))) ; value
1904 (t nil))))
1906 (defun markdown-match-multimarkdown-metadata (last)
1907 "Match MultiMarkdown metadata from the point to LAST."
1908 (markdown-match-generic-metadata markdown-regex-multimarkdown-metadata last))
1910 (defun markdown-match-pandoc-metadata (last)
1911 "Match Pandoc metadata from the point to LAST."
1912 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
1914 (defun markdown-font-lock-extend-region ()
1915 "Extend the search region to include an entire block of text.
1916 This helps improve font locking for block constructs such as pre blocks."
1917 ;; Avoid compiler warnings about these global variables from font-lock.el.
1918 ;; See the documentation for variable `font-lock-extend-region-functions'.
1919 (eval-when-compile (defvar font-lock-beg) (defvar font-lock-end))
1920 (save-excursion
1921 (goto-char font-lock-beg)
1922 (let ((found (or (re-search-backward "\n\n" nil t) (point-min))))
1923 (goto-char font-lock-end)
1924 (when (re-search-forward "\n\n" nil t)
1925 (beginning-of-line)
1926 (setq font-lock-end (point)))
1927 (setq font-lock-beg found))))
1930 ;;; Syntax Table ==============================================================
1932 (defvar markdown-mode-syntax-table
1933 (let ((tab (make-syntax-table text-mode-syntax-table)))
1934 (modify-syntax-entry ?\" "." tab)
1935 tab)
1936 "Syntax table for `markdown-mode'.")
1939 ;;; Element Insertion =========================================================
1941 (defun markdown-ensure-blank-line-before ()
1942 "If previous line is not already blank, insert a blank line before point."
1943 (unless (bolp) (insert "\n"))
1944 (unless (or (bobp) (looking-back "\n\\s-*\n")) (insert "\n")))
1946 (defun markdown-ensure-blank-line-after ()
1947 "If following line is not already blank, insert a blank line after point.
1948 Return the point where it was originally."
1949 (save-excursion
1950 (unless (eolp) (insert "\n"))
1951 (unless (or (eobp) (looking-at "\n\\s-*\n")) (insert "\n"))))
1953 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
1954 "Insert the strings S1 and S2, wrapping around region or THING.
1955 If a region is specified by the optional BEG and END arguments,
1956 wrap the strings S1 and S2 around that region.
1957 If there is an active region, wrap the strings S1 and S2 around
1958 the region. If there is not an active region but the point is at
1959 THING, wrap that thing (which defaults to word). Otherwise, just
1960 insert S1 and S2 and place the cursor in between. Return the
1961 bounds of the entire wrapped string, or nil if nothing was wrapped
1962 and S1 and S2 were only inserted."
1963 (let (a b bounds new-point)
1964 (cond
1965 ;; Given region
1966 ((and beg end)
1967 (setq a beg
1968 b end
1969 new-point (+ (point) (length s1))))
1970 ;; Active region
1971 ((markdown-use-region-p)
1972 (setq a (region-beginning)
1973 b (region-end)
1974 new-point (+ (point) (length s1))))
1975 ;; Thing (word) at point
1976 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
1977 (setq a (car bounds)
1978 b (cdr bounds)
1979 new-point (+ (point) (length s1))))
1980 ;; No active region and no word
1982 (setq a (point)
1983 b (point))))
1984 (goto-char b)
1985 (insert s2)
1986 (goto-char a)
1987 (insert s1)
1988 (when new-point (goto-char new-point))
1989 (if (= a b)
1991 (setq b (+ b (length s1) (length s2)))
1992 (cons a b))))
1994 (defun markdown-point-after-unwrap (cur prefix suffix)
1995 "Return desired position of point after an unwrapping operation.
1996 CUR gives the position of the point before the operation.
1997 Additionally, two cons cells must be provided. PREFIX gives the
1998 bounds of the prefix string and SUFFIX gives the bounds of the
1999 suffix string."
2000 (cond ((< cur (cdr prefix)) (car prefix))
2001 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
2002 ((<= cur (cdr suffix))
2003 (- cur (+ (- (cdr prefix) (car prefix))
2004 (- cur (car suffix)))))
2005 (t cur)))
2007 (defun markdown-unwrap-thing-at-point (regexp all text)
2008 "Remove prefix and suffix of thing at point and reposition the point.
2009 When the thing at point matches REGEXP, replace the subexpression
2010 ALL with the string in subexpression TEXT. Reposition the point
2011 in an appropriate location accounting for the removal of prefix
2012 and suffix strings. Return new bounds of string from group TEXT.
2013 When REGEXP is nil, assumes match data is already set."
2014 (when (or (null regexp)
2015 (thing-at-point-looking-at regexp))
2016 (let ((cur (point))
2017 (prefix (cons (match-beginning all) (match-beginning text)))
2018 (suffix (cons (match-end text) (match-end all)))
2019 (bounds (cons (match-beginning text) (match-end text))))
2020 ;; Replace the thing at point
2021 (replace-match (match-string text) t t nil all)
2022 ;; Reposition the point
2023 (goto-char (markdown-point-after-unwrap cur prefix suffix))
2024 ;; Adjust bounds
2025 (setq bounds (cons (car prefix)
2026 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
2028 (defun markdown-unwrap-things-in-region (beg end regexp all text)
2029 "Remove prefix and suffix of all things in region from BEG to END.
2030 When a thing in the region matches REGEXP, replace the
2031 subexpression ALL with the string in subexpression TEXT.
2032 Return a cons cell containing updated bounds for the region."
2033 (save-excursion
2034 (goto-char beg)
2035 (let ((removed 0) len-all len-text)
2036 (while (re-search-forward regexp (- end removed) t)
2037 (setq len-all (length (match-string-no-properties all)))
2038 (setq len-text (length (match-string-no-properties text)))
2039 (setq removed (+ removed (- len-all len-text)))
2040 (replace-match (match-string text) t t nil all))
2041 (cons beg (- end removed)))))
2043 (defun markdown-insert-hr (arg)
2044 "Insert or replace a horizonal rule.
2045 By default, use the first element of `markdown-hr-strings'. When
2046 ARG is non-nil, as when given a prefix, select a different
2047 element as follows. When prefixed with \\[universal-argument],
2048 use the last element of `markdown-hr-strings' instead. When
2049 prefixed with an integer from 1 to the length of
2050 `markdown-hr-strings', use the element in that position instead."
2051 (interactive "*P")
2052 (when (thing-at-point-looking-at markdown-regex-hr)
2053 (delete-region (match-beginning 0) (match-end 0)))
2054 (markdown-ensure-blank-line-before)
2055 (cond ((equal arg '(4))
2056 (insert (car (reverse markdown-hr-strings))))
2057 ((and (integerp arg) (> arg 0)
2058 (<= arg (length markdown-hr-strings)))
2059 (insert (nth (1- arg) markdown-hr-strings)))
2061 (insert (car markdown-hr-strings))))
2062 (markdown-ensure-blank-line-after))
2064 (defun markdown-insert-bold ()
2065 "Insert markup to make a region or word bold.
2066 If there is an active region, make the region bold. If the point
2067 is at a non-bold word, make the word bold. If the point is at a
2068 bold word or phrase, remove the bold markup. Otherwise, simply
2069 insert bold delimiters and place the cursor in between them."
2070 (interactive)
2071 (let ((delim (if markdown-bold-underscore "__" "**")))
2072 (if (markdown-use-region-p)
2073 ;; Active region
2074 (let ((bounds (markdown-unwrap-things-in-region
2075 (region-beginning) (region-end)
2076 markdown-regex-bold 2 4)))
2077 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
2078 ;; Bold markup removal, bold word at point, or empty markup insertion
2079 (if (thing-at-point-looking-at markdown-regex-bold)
2080 (markdown-unwrap-thing-at-point nil 2 4)
2081 (markdown-wrap-or-insert delim delim 'word nil nil)))))
2083 (defun markdown-insert-italic ()
2084 "Insert markup to make a region or word italic.
2085 If there is an active region, make the region italic. If the point
2086 is at a non-italic word, make the word italic. If the point is at an
2087 italic word or phrase, remove the italic markup. Otherwise, simply
2088 insert italic delimiters and place the cursor in between them."
2089 (interactive)
2090 (let ((delim (if markdown-italic-underscore "_" "*")))
2091 (if (markdown-use-region-p)
2092 ;; Active region
2093 (let ((bounds (markdown-unwrap-things-in-region
2094 (region-beginning) (region-end)
2095 markdown-regex-italic 2 4)))
2096 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
2097 ;; Italic markup removal, italic word at point, or empty markup insertion
2098 (if (thing-at-point-looking-at markdown-regex-italic)
2099 (markdown-unwrap-thing-at-point nil 2 4)
2100 (markdown-wrap-or-insert delim delim 'word nil nil)))))
2102 (defun markdown-insert-code ()
2103 "Insert markup to make a region or word an inline code fragment.
2104 If there is an active region, make the region an inline code
2105 fragment. If the point is at a word, make the word an inline
2106 code fragment. Otherwise, simply insert code delimiters and
2107 place the cursor in between them."
2108 (interactive)
2109 (if (markdown-use-region-p)
2110 ;; Active region
2111 (let ((bounds (markdown-unwrap-things-in-region
2112 (region-beginning) (region-end)
2113 markdown-regex-code 2 4)))
2114 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
2115 ;; Code markup removal, code markup for word, or empty markup insertion
2116 (if (markdown-code-at-point-p)
2117 (markdown-unwrap-thing-at-point nil 0 1)
2118 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
2120 (defun markdown-insert-link ()
2121 "Insert an inline link, using region or word as link text if possible.
2122 If there is an active region, use the region as the link text. If the
2123 point is at a word, use the word as the link text. In these cases, the
2124 point will be left at the position for inserting a URL. If there is no
2125 active region and the point is not at word, simply insert link markup and
2126 place the point in the position to enter link text."
2127 (interactive)
2128 (let ((bounds (markdown-wrap-or-insert "[" "]()")))
2129 (when bounds
2130 (goto-char (- (cdr bounds) 1)))))
2132 (defun markdown-insert-reference-link (text label &optional url title)
2133 "Insert a reference link and, optionally, a reference definition.
2134 The link TEXT will be inserted followed by the optional LABEL.
2135 If a URL is given, also insert a definition for the reference
2136 LABEL according to `markdown-reference-location'. If a TITLE is
2137 given, it will be added to the end of the reference definition
2138 and will be used to populate the title attribute when converted
2139 to XHTML. If URL is nil, insert only the link portion (for
2140 example, when a reference label is already defined)."
2141 (insert (concat "[" text "][" label "]"))
2142 (when url
2143 (let ((end (point))
2144 (label (if (> (length label) 0) label text)))
2145 (cond
2146 ((eq markdown-reference-location 'end) (goto-char (point-max)))
2147 ((eq markdown-reference-location 'immediately) (markdown-end-of-block))
2148 ((eq markdown-reference-location 'header) (markdown-end-of-defun)))
2149 (unless (markdown-cur-line-blank-p) (insert "\n"))
2150 (insert "\n[" label "]: " url)
2151 (unless (> (length url) 0)
2152 (setq end (point)))
2153 (when (> (length title) 0)
2154 (insert " \"" title "\""))
2155 (insert "\n")
2156 (unless (or (eobp) (looking-at "\n"))
2157 (insert "\n"))
2158 (goto-char end)
2159 (when (> (length url) 0)
2160 (message
2161 (substitute-command-keys
2162 "Defined reference [%s], press \\[markdown-jump] to jump there")
2163 (or label text))))))
2165 (defun markdown-insert-reference-link-dwim ()
2166 "Insert a reference link of the form [text][label] at point.
2167 If there is an active region, the text in the region will be used
2168 as the link text. If the point is at a word, it will be used as
2169 the link text. Otherwise, the link text will be read from the
2170 minibuffer. The link label will be read from the minibuffer in
2171 both cases, with completion from the set of currently defined
2172 references. To create an implicit reference link, press RET to
2173 accept the default, an empty label. If the entered referenced
2174 label is not defined, additionally prompt for the URL
2175 and (optional) title. The reference definition is placed at the
2176 location determined by `markdown-reference-location'."
2177 (interactive)
2178 (let* ((defined-labels (mapcar (lambda (x) (substring x 1 -1))
2179 (markdown-get-defined-references)))
2180 (bounds (or (and (markdown-use-region-p)
2181 (cons (region-beginning) (region-end)))
2182 (markdown-bounds-of-thing-at-point 'word)))
2183 (text (if bounds
2184 (buffer-substring (car bounds) (cdr bounds))
2185 (read-string "Link Text: ")))
2186 (label (completing-read
2187 "Link Label (default: none): " defined-labels
2188 nil nil nil 'markdown-reference-label-history nil))
2189 (ref (markdown-reference-definition
2190 (concat "[" (if (> (length label) 0) label text) "]")))
2191 (url (unless ref (read-string "Link URL: ")))
2192 (title (when (> (length url) 0)
2193 (read-string "Link Title (optional): "))))
2194 (when bounds (delete-region (car bounds) (cdr bounds)))
2195 (markdown-insert-reference-link text label url title)))
2197 (defun markdown-insert-uri ()
2198 "Insert markup for an inline URI.
2199 If there is an active region, use it as the URI. If the point is
2200 at a URI, wrap it with angle brackets. If the point is at an
2201 inline URI, remove the angle brackets. Otherwise, simply insert
2202 angle brackets place the point between them."
2203 (interactive)
2204 (if (markdown-use-region-p)
2205 ;; Active region
2206 (let ((bounds (markdown-unwrap-things-in-region
2207 (region-beginning) (region-end)
2208 markdown-regex-angle-uri 0 2)))
2209 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
2210 ;; Markup removal, URI at point, or empty markup insertion
2211 (if (thing-at-point-looking-at markdown-regex-angle-uri)
2212 (markdown-unwrap-thing-at-point nil 0 2)
2213 (markdown-wrap-or-insert "<" ">" 'url nil nil))))
2215 (defun markdown-insert-wiki-link ()
2216 "Insert a wiki link of the form [[WikiLink]].
2217 If there is an active region, use the region as the link text.
2218 If the point is at a word, use the word as the link text. If
2219 there is no active region and the point is not at word, simply
2220 insert link markup."
2221 (interactive)
2222 (if (markdown-use-region-p)
2223 ;; Active region
2224 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
2225 ;; Markup removal, wiki link at at point, or empty markup insertion
2226 (if (thing-at-point-looking-at markdown-regex-wiki-link)
2227 (if (or markdown-wiki-link-alias-first
2228 (null (match-string 4)))
2229 (markdown-unwrap-thing-at-point nil 1 2)
2230 (markdown-unwrap-thing-at-point nil 1 4))
2231 (markdown-wrap-or-insert "[[" "]]"))))
2233 (defun markdown-insert-image (&optional arg)
2234 "Insert image markup using region or word as alt text if possible.
2235 If there is an active region, use the region as the alt text. If the
2236 point is at a word, use the word as the alt text. In these cases, the
2237 point will be left at the position for inserting a URL. If there is no
2238 active region and the point is not at word, simply insert image markup and
2239 place the point in the position to enter alt text. If ARG is nil, insert
2240 inline image markup. Otherwise, insert reference image markup."
2241 (interactive "*P")
2242 (let ((bounds (if arg
2243 (markdown-wrap-or-insert "![" "][]")
2244 (markdown-wrap-or-insert "![" "]()"))))
2245 (when bounds
2246 (goto-char (- (cdr bounds) 1)))))
2248 (defun markdown-insert-reference-image ()
2249 "Insert reference-style image markup using region or word as alt text.
2250 Calls `markdown-insert-image' with prefix argument."
2251 (interactive)
2252 (markdown-insert-image t))
2254 (defun markdown-remove-header ()
2255 "Remove header markup if point is at a header.
2256 Return bounds of remaining header text if a header was removed
2257 and nil otherwise."
2258 (interactive "*")
2259 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
2260 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
2262 (defun markdown-insert-header (&optional level text setext)
2263 "Insert or replace header markup.
2264 The level of the header is specified by LEVEL and header text is
2265 given by TEXT. LEVEL must be an integer from 1 and 6, and the
2266 default value is 1.
2267 When TEXT is nil, the header text is obtained as follows.
2268 If there is an active region, it is used as the header text.
2269 Otherwise, the current line will be used as the header text.
2270 If there is not an active region and the point is at a header,
2271 remove the header markup and replace with level N header.
2272 Otherwise, insert empty header markup and place the cursor in
2273 between.
2274 The style of the header will be atx (hash marks) unless
2275 SETEXT is non-nil, in which case a setext-style (underlined)
2276 header will be inserted."
2277 (interactive "p\nsHeader text: ")
2278 (setq level (min (max (or level 1) 1) (if setext 2 6)))
2279 ;; Determine header text if not given
2280 (when (null text)
2281 (if (markdown-use-region-p)
2282 ;; Active region
2283 (setq text (delete-and-extract-region (region-beginning) (region-end)))
2284 ;; No active region
2285 (markdown-remove-header)
2286 (setq text (delete-and-extract-region
2287 (line-beginning-position) (line-end-position)))
2288 (when (and setext (string-match "^[ \t]*$" text))
2289 (setq text (read-string "Header text: "))))
2290 (setq text (markdown-compress-whitespace-string text)))
2291 ;; Insertion with given text
2292 (markdown-ensure-blank-line-before)
2293 (let (hdr)
2294 (cond (setext
2295 (setq hdr (make-string (length text) (if (= level 2) ?- ?=)))
2296 (insert text "\n" hdr))
2298 (setq hdr (make-string level ?#))
2299 (insert hdr " " text " " hdr))))
2300 (markdown-ensure-blank-line-after)
2301 ;; Leave point at end of text
2302 (if setext
2303 (backward-char (1+ (length text)))
2304 (backward-char (1+ level))))
2306 (defun markdown-insert-header-dwim (&optional arg setext)
2307 "Insert or replace header markup.
2308 The level and type of the header are determined automatically by
2309 the type and level of the previous header, unless a prefix
2310 argument is given via ARG.
2311 With a numeric prefix valued 1 to 6, insert a header of the given
2312 level, with the type being determined automatically (note that
2313 only level 1 or 2 setext headers are possible).
2314 With \\[universal-argument], insert a level-one setext header.
2315 With \\[universal-argument] \\[universal-argument], insert a
2316 level two setext header.
2317 When SETEXT is non-nil, prefer setext-style headers when
2318 possible (levels one and two).
2320 When there is an active region, use it for the header text. When
2321 the point is at an existing header, change the type and level
2322 according to the rules above.
2323 Otherwise, if the line is not empty, create a header using the
2324 text on the current line as the header text.
2325 Finally, if the point is on a blank line, insert empty header
2326 markup (atx) or prompt for text (setext).
2327 See `markdown-insert-header' for more details about how the
2328 header text is determined."
2329 (interactive "*P")
2330 (let (level)
2331 (cond ((equal arg '(4)) ; level-one setext with C-u
2332 (setq setext t)
2333 (setq level 1))
2334 ((equal arg '(16)) ; level-two setext with C-u C-u
2335 (setq setext t)
2336 (setq level 2))
2337 (t ; automatic with numeric override
2338 (save-excursion
2339 (when (re-search-backward markdown-regex-header nil t)
2340 ;; level of previous header
2341 (setq level (markdown-outline-level))
2342 ;; match groups 1 and 2 indicate setext headers
2343 (setq setext (or setext (match-end 1) (match-end 3)))))
2344 ;; use prefix if given, or level of previous header
2345 (setq level (if arg (prefix-numeric-value arg) level))
2346 ;; setext headers must be level one or two
2347 (and level (setq setext (and setext (<= level 2))))))
2348 (markdown-insert-header level nil setext)))
2350 (defun markdown-insert-header-setext-dwim (&optional arg)
2351 "Insert or replace header markup, with preference for setext.
2352 See `markdown-insert-header-dwim' for details, including how ARG is handled."
2353 (interactive "*P")
2354 (markdown-insert-header-dwim arg t))
2356 (defun markdown-insert-header-atx-1 ()
2357 "Insert a first level atx-style (hash mark) header.
2358 See `markdown-insert-header'."
2359 (interactive "*")
2360 (markdown-insert-header 1 nil nil))
2362 (defun markdown-insert-header-atx-2 ()
2363 "Insert a level two atx-style (hash mark) header.
2364 See `markdown-insert-header'."
2365 (interactive "*")
2366 (markdown-insert-header 2 nil nil))
2368 (defun markdown-insert-header-atx-3 ()
2369 "Insert a level three atx-style (hash mark) header.
2370 See `markdown-insert-header'."
2371 (interactive "*")
2372 (markdown-insert-header 3 nil nil))
2374 (defun markdown-insert-header-atx-4 ()
2375 "Insert a level four atx-style (hash mark) header.
2376 See `markdown-insert-header'."
2377 (interactive "*")
2378 (markdown-insert-header 4 nil nil))
2380 (defun markdown-insert-header-atx-5 ()
2381 "Insert a level five atx-style (hash mark) header.
2382 See `markdown-insert-header'."
2383 (interactive "*")
2384 (markdown-insert-header 5 nil nil))
2386 (defun markdown-insert-header-atx-6 ()
2387 "Insert a sixth level atx-style (hash mark) header.
2388 See `markdown-insert-header'."
2389 (interactive "*")
2390 (markdown-insert-header 6 nil nil))
2392 (defun markdown-insert-header-setext-1 ()
2393 "Insert a setext-style (underlined) first-level header.
2394 See `markdown-insert-header'."
2395 (interactive "*")
2396 (markdown-insert-header 1 nil t))
2398 (defun markdown-insert-header-setext-2 ()
2399 "Insert a setext-style (underlined) second-level header.
2400 See `markdown-insert-header'."
2401 (interactive "*")
2402 (markdown-insert-header 2 nil t))
2404 (defun markdown-blockquote-indentation (loc)
2405 "Return string containing necessary indentation for a blockquote at LOC.
2406 Also see `markdown-pre-indentation'."
2407 (save-excursion
2408 (goto-char loc)
2409 (let* ((list-level (length (markdown-calculate-list-levels)))
2410 (indent ""))
2411 (dotimes (count list-level indent)
2412 (setq indent (concat indent " "))))))
2414 (defun markdown-insert-blockquote ()
2415 "Start a blockquote section (or blockquote the region).
2416 If Transient Mark mode is on and a region is active, it is used as
2417 the blockquote text."
2418 (interactive)
2419 (if (markdown-use-region-p)
2420 (markdown-blockquote-region (region-beginning) (region-end))
2421 (markdown-ensure-blank-line-before)
2422 (insert (markdown-blockquote-indentation (point)) "> ")
2423 (markdown-ensure-blank-line-after)))
2425 (defun markdown-block-region (beg end prefix)
2426 "Format the region using a block prefix.
2427 Arguments BEG and END specify the beginning and end of the
2428 region. The characters PREFIX will appear at the beginning
2429 of each line."
2430 (save-excursion
2431 (let* ((end-marker (make-marker))
2432 (beg-marker (make-marker)))
2433 ;; Ensure blank line after and remove extra whitespace
2434 (goto-char end)
2435 (skip-syntax-backward "-")
2436 (set-marker end-marker (point))
2437 (delete-horizontal-space)
2438 (markdown-ensure-blank-line-after)
2439 ;; Ensure blank line before and remove extra whitespace
2440 (goto-char beg)
2441 (skip-syntax-forward "-")
2442 (delete-horizontal-space)
2443 (markdown-ensure-blank-line-before)
2444 (set-marker beg-marker (point))
2445 ;; Insert PREFIX before each line
2446 (goto-char beg-marker)
2447 (while (and (< (line-beginning-position) end-marker)
2448 (not (eobp)))
2449 (insert prefix)
2450 (forward-line)))))
2452 (defun markdown-blockquote-region (beg end)
2453 "Blockquote the region.
2454 Arguments BEG and END specify the beginning and end of the region."
2455 (interactive "*r")
2456 (markdown-block-region
2457 beg end (concat (markdown-blockquote-indentation
2458 (max (point-min) (1- beg))) "> ")))
2460 (defun markdown-pre-indentation (loc)
2461 "Return string containing necessary whitespace for a pre block at LOC.
2462 Also see `markdown-blockquote-indentation'."
2463 (save-excursion
2464 (goto-char loc)
2465 (let* ((list-level (length (markdown-calculate-list-levels)))
2466 indent)
2467 (dotimes (count (1+ list-level) indent)
2468 (setq indent (concat indent " "))))))
2470 (defun markdown-insert-pre ()
2471 "Start a preformatted section (or apply to the region).
2472 If Transient Mark mode is on and a region is active, it is marked
2473 as preformatted text."
2474 (interactive)
2475 (if (markdown-use-region-p)
2476 (markdown-pre-region (region-beginning) (region-end))
2477 (markdown-ensure-blank-line-before)
2478 (insert (markdown-pre-indentation (point)))
2479 (markdown-ensure-blank-line-after)))
2481 (defun markdown-pre-region (beg end)
2482 "Format the region as preformatted text.
2483 Arguments BEG and END specify the beginning and end of the region."
2484 (interactive "*r")
2485 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
2486 (markdown-block-region beg end indent)))
2488 (defun markdown-insert-gfm-code-block (&optional lang)
2489 "Insert GFM code block for language LANG.
2490 If LANG is nil, the language will be queried from user. If a
2491 region is active, wrap this region with the markup instead. If
2492 the region boundaries are not on empty lines, these are added
2493 automatically in order to have the correct markup."
2494 (interactive "sProgramming language [none]: ")
2495 (if (markdown-use-region-p)
2496 (let ((b (region-beginning)) (e (region-end)))
2497 (goto-char e)
2498 ;; if we're on a blank line, don't newline, otherwise the ```
2499 ;; should go on its own line
2500 (unless (looking-back "\n")
2501 (newline))
2502 (insert "```")
2503 (markdown-ensure-blank-line-after)
2504 (goto-char b)
2505 ;; if we're on a blank line, insert the quotes here, otherwise
2506 ;; add a new line first
2507 (unless (looking-at "\n")
2508 (newline)
2509 (forward-line -1))
2510 (markdown-ensure-blank-line-before)
2511 (insert "```" lang))
2512 (markdown-ensure-blank-line-before)
2513 (insert "```" lang)
2514 (newline 2)
2515 (insert "```")
2516 (markdown-ensure-blank-line-after)
2517 (forward-line -1)))
2520 ;;; Footnotes ======================================================================
2522 (defun markdown-footnote-counter-inc ()
2523 "Increment `markdown-footnote-counter' and return the new value."
2524 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
2525 (save-excursion
2526 (goto-char (point-min))
2527 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
2528 (point-max) t)
2529 (let ((fn (string-to-number (match-string 1))))
2530 (when (> fn markdown-footnote-counter)
2531 (setq markdown-footnote-counter fn))))))
2532 (incf markdown-footnote-counter))
2534 (defun markdown-insert-footnote ()
2535 "Insert footnote with a new number and move point to footnote definition."
2536 (interactive)
2537 (let ((fn (markdown-footnote-counter-inc)))
2538 (insert (format "[^%d]" fn))
2539 (markdown-footnote-text-find-new-location)
2540 (markdown-ensure-blank-line-before)
2541 (unless (markdown-cur-line-blank-p)
2542 (insert "\n"))
2543 (insert (format "[^%d]: " fn))
2544 (markdown-ensure-blank-line-after)))
2546 (defun markdown-footnote-text-find-new-location ()
2547 "Position the cursor at the proper location for a new footnote text."
2548 (cond
2549 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
2550 ((eq markdown-footnote-location 'immediately) (markdown-end-of-block))
2551 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
2553 (defun markdown-footnote-kill ()
2554 "Kill the footnote at point.
2555 The footnote text is killed (and added to the kill ring), the
2556 footnote marker is deleted. Point has to be either at the
2557 footnote marker or in the footnote text."
2558 (interactive)
2559 (let (return-pos)
2560 (when (markdown-footnote-text-positions) ; if we're in a footnote text
2561 (markdown-footnote-return) ; we first move to the marker
2562 (setq return-pos 'text)) ; and remember our return position
2563 (let ((marker (markdown-footnote-delete-marker)))
2564 (unless marker
2565 (error "Not at a footnote"))
2566 (let ((text-pos (markdown-footnote-find-text (car marker))))
2567 (unless text-pos
2568 (error "No text for footnote `%s'" (car marker)))
2569 (goto-char text-pos)
2570 (let ((pos (markdown-footnote-kill-text)))
2571 (setq return-pos
2572 (if (and pos (eq return-pos 'text))
2574 (cadr marker))))))
2575 (goto-char return-pos)))
2577 (defun markdown-footnote-delete-marker ()
2578 "Delete a footnote marker at point.
2579 Returns a list (ID START) containing the footnote ID and the
2580 start position of the marker before deletion. If no footnote
2581 marker was deleted, this function returns NIL."
2582 (let ((marker (markdown-footnote-marker-positions)))
2583 (when marker
2584 (delete-region (second marker) (third marker))
2585 (butlast marker))))
2587 (defun markdown-footnote-kill-text ()
2588 "Kill footnote text at point.
2589 Returns the start position of the footnote text before deletion,
2590 or NIL if point was not inside a footnote text.
2592 The killed text is placed in the kill ring (without the footnote
2593 number)."
2594 (let ((fn (markdown-footnote-text-positions)))
2595 (when fn
2596 (let ((text (delete-and-extract-region (second fn) (third fn))))
2597 (string-match (concat "\\[\\" (first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
2598 (kill-new (match-string 1 text))
2599 (when (and (markdown-cur-line-blank-p)
2600 (markdown-prev-line-blank-p))
2601 (delete-region (1- (point)) (point)))
2602 (second fn)))))
2604 (defun markdown-footnote-goto-text ()
2605 "Jump to the text of the footnote at point."
2606 (interactive)
2607 (let ((fn (car (markdown-footnote-marker-positions))))
2608 (unless fn
2609 (error "Not at a footnote marker"))
2610 (let ((new-pos (markdown-footnote-find-text fn)))
2611 (unless new-pos
2612 (error "No definition found for footnote `%s'" fn))
2613 (goto-char new-pos))))
2615 (defun markdown-footnote-return ()
2616 "Return from a footnote to its footnote number in the main text."
2617 (interactive)
2618 (let ((fn (save-excursion
2619 (car (markdown-footnote-text-positions)))))
2620 (unless fn
2621 (error "Not in a footnote"))
2622 (let ((new-pos (markdown-footnote-find-marker fn)))
2623 (unless new-pos
2624 (error "Footnote marker `%s' not found" fn))
2625 (goto-char new-pos))))
2627 (defun markdown-footnote-find-marker (id)
2628 "Find the location of the footnote marker with ID.
2629 The actual buffer position returned is the position directly
2630 following the marker's closing bracket. If no marker is found,
2631 NIL is returned."
2632 (save-excursion
2633 (goto-char (point-min))
2634 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
2635 (skip-chars-backward "^]")
2636 (point))))
2638 (defun markdown-footnote-find-text (id)
2639 "Find the location of the text of footnote ID.
2640 The actual buffer position returned is the position of the first
2641 character of the text, after the footnote's identifier. If no
2642 footnote text is found, NIL is returned."
2643 (save-excursion
2644 (goto-char (point-min))
2645 (when (re-search-forward (concat "^\\[" id "\\]:") nil t)
2646 (skip-chars-forward "[ \t]")
2647 (point))))
2649 (defun markdown-footnote-marker-positions ()
2650 "Return the position and ID of the footnote marker point is on.
2651 The return value is a list (ID START END). If point is not on a
2652 footnote, NIL is returned."
2653 ;; first make sure we're at a footnote marker
2654 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
2655 (looking-at (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
2656 (save-excursion
2657 ;; move point between [ and ^:
2658 (if (looking-at "\\[")
2659 (forward-char 1)
2660 (skip-chars-backward "^["))
2661 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
2662 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
2664 (defun markdown-footnote-text-positions ()
2665 "Return the start and end positions of the footnote text point is in.
2666 The exact return value is a list of three elements: (ID START END).
2667 The start position is the position of the opening bracket
2668 of the footnote id. The end position is directly after the
2669 newline that ends the footnote. If point is not in a footnote,
2670 NIL is returned instead."
2671 (save-excursion
2672 (let ((fn (progn
2673 (backward-paragraph)
2674 ;; if we're in a multiparagraph footnote, we need to back up further
2675 (while (>= (markdown-next-line-indent) 4)
2676 (backward-paragraph))
2677 (forward-line)
2678 (if (looking-at (concat "^\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:"))
2679 (list (match-string 1) (point))))))
2680 (when fn
2681 (while (progn
2682 (forward-paragraph)
2683 (>= (markdown-next-line-indent) 4)))
2684 (append fn (list (point)))))))
2687 ;;; Element Removal ===========================================================
2689 (defun markdown-kill-thing-at-point ()
2690 "Kill thing at point and add important text, without markup, to kill ring.
2691 Possible things to kill include (roughly in order of precedence):
2692 inline code, headers, horizonal rules, links (add link text to
2693 kill ring), images (add alt text to kill ring), angle uri, email
2694 addresses, bold, italics, reference definition (add URI to kill
2695 ring), footnote markers and text (kill both marker and text, add
2696 text to kill ring), and list items."
2697 (interactive "*")
2698 (let (val tmp)
2699 (cond
2700 ;; Inline code
2701 ((markdown-code-at-point-p)
2702 (kill-new (match-string 1))
2703 (delete-region (match-beginning 0) (match-end 0)))
2704 ;; ATX header
2705 ((thing-at-point-looking-at markdown-regex-header-atx)
2706 (kill-new (match-string 2))
2707 (delete-region (match-beginning 0) (match-end 0)))
2708 ;; Setext header
2709 ((thing-at-point-looking-at markdown-regex-header-setext)
2710 (kill-new (match-string 1))
2711 (delete-region (match-beginning 0) (match-end 0)))
2712 ;; Horizonal rule
2713 ((thing-at-point-looking-at markdown-regex-hr)
2714 (kill-new (match-string 0))
2715 (delete-region (match-beginning 0) (match-end 0)))
2716 ;; Inline link or image (add link or alt text to kill ring)
2717 ((thing-at-point-looking-at markdown-regex-link-inline)
2718 (kill-new (match-string 3))
2719 (delete-region (match-beginning 0) (match-end 0)))
2720 ;; Reference link or image (add link or alt text to kill ring)
2721 ((thing-at-point-looking-at markdown-regex-link-reference)
2722 (kill-new (match-string 3))
2723 (delete-region (match-beginning 0) (match-end 0)))
2724 ;; Angle URI (add URL to kill ring)
2725 ((thing-at-point-looking-at markdown-regex-angle-uri)
2726 (kill-new (match-string 2))
2727 (delete-region (match-beginning 0) (match-end 0)))
2728 ;; Email address in angle brackets (add email address to kill ring)
2729 ((thing-at-point-looking-at markdown-regex-email)
2730 (kill-new (match-string 1))
2731 (delete-region (match-beginning 0) (match-end 0)))
2732 ;; Wiki link (add alias text to kill ring)
2733 ((thing-at-point-looking-at markdown-regex-wiki-link)
2734 (kill-new (markdown-wiki-link-alias))
2735 (delete-region (match-beginning 1) (match-end 1)))
2736 ;; Bold
2737 ((thing-at-point-looking-at markdown-regex-bold)
2738 (kill-new (match-string 4))
2739 (delete-region (match-beginning 2) (match-end 2)))
2740 ;; Italics
2741 ((thing-at-point-looking-at markdown-regex-italic)
2742 (kill-new (match-string 4))
2743 (delete-region (match-beginning 2) (match-end 2)))
2744 ;; Footnote marker (add footnote text to kill ring)
2745 ((thing-at-point-looking-at markdown-regex-footnote)
2746 (markdown-footnote-kill))
2747 ;; Footnote text (add footnote text to kill ring)
2748 ((setq val (markdown-footnote-text-positions))
2749 (markdown-footnote-kill))
2750 ;; Reference definition (add URL to kill ring)
2751 ((thing-at-point-looking-at markdown-regex-reference-definition)
2752 (kill-new (match-string 2))
2753 (delete-region (match-beginning 0) (match-end 0)))
2754 ;; List item
2755 ((setq val (markdown-cur-list-item-bounds))
2756 (kill-new (delete-and-extract-region (first val) (second val))))
2758 (error "Nothing found at point to kill")))))
2761 ;;; Indentation ====================================================================
2763 (defun markdown-indent-find-next-position (cur-pos positions)
2764 "Return the position after the index of CUR-POS in POSITIONS.
2765 Positions are calculated by `markdown-calc-indents'."
2766 (while (and positions
2767 (not (equal cur-pos (car positions))))
2768 (setq positions (cdr positions)))
2769 (or (cadr positions) 0))
2771 (defun markdown-exdent-find-next-position (cur-pos positions)
2772 "Return the maximal element that precedes CUR-POS from POSITIONS.
2773 Positions are calculated by `markdown-calc-indents'."
2774 (let ((result 0))
2775 (dolist (i positions)
2776 (when (< i cur-pos)
2777 (setq result (max result i))))
2778 result))
2780 (defun markdown-indent-line ()
2781 "Indent the current line using some heuristics.
2782 If the _previous_ command was either `markdown-enter-key' or
2783 `markdown-cycle', then we should cycle to the next
2784 reasonable indentation position. Otherwise, we could have been
2785 called directly by `markdown-enter-key', by an initial call of
2786 `markdown-cycle', or indirectly by `auto-fill-mode'. In
2787 these cases, indent to the default position.
2788 Positions are calculated by `markdown-calc-indents'."
2789 (interactive)
2790 (let ((positions (markdown-calc-indents))
2791 (cur-pos (current-column)))
2792 (if (not (equal this-command 'markdown-cycle))
2793 (indent-line-to (car positions))
2794 (setq positions (sort (delete-dups positions) '<))
2795 (indent-line-to
2796 (markdown-indent-find-next-position cur-pos positions)))))
2798 (defun markdown-calc-indents ()
2799 "Return a list of indentation columns to cycle through.
2800 The first element in the returned list should be considered the
2801 default indentation level. This function does not worry about
2802 duplicate positions, which are handled up by calling functions."
2803 (let (pos prev-line-pos positions)
2805 ;; Indentation of previous line
2806 (setq prev-line-pos (markdown-prev-line-indent))
2807 (setq positions (cons prev-line-pos positions))
2809 ;; Indentation of previous non-list-marker text
2810 (when (setq pos (markdown-prev-non-list-indent))
2811 (setq positions (cons pos positions)))
2813 ;; Indentation required for a pre block in current context
2814 (setq pos (length (markdown-pre-indentation (point))))
2815 (setq positions (cons pos positions))
2817 ;; Indentation of the previous line + tab-width
2818 (if prev-line-pos
2819 (setq positions (cons (+ prev-line-pos tab-width) positions))
2820 (setq positions (cons tab-width positions)))
2822 ;; Indentation of the previous line - tab-width
2823 (if (and prev-line-pos (> prev-line-pos tab-width))
2824 (setq positions (cons (- prev-line-pos tab-width) positions)))
2826 ;; Indentation of all preceeding list markers (when in a list)
2827 (when (setq pos (markdown-calculate-list-levels))
2828 (setq positions (append pos positions)))
2830 ;; First column
2831 (setq positions (cons 0 positions))
2833 ;; Return reversed list
2834 (reverse positions)))
2836 (defun markdown-enter-key ()
2837 "Handle RET according to to the value of `markdown-indent-on-enter'."
2838 (interactive)
2839 (if markdown-indent-on-enter
2840 (newline-and-indent)
2841 (newline)))
2843 (defun markdown-exdent-or-delete (arg)
2844 "Handle BACKSPACE by cycling through indentation points.
2845 When BACKSPACE is pressed, if there is only whitespace
2846 before the current point, then exdent the line one level.
2847 Otherwise, do normal delete by repeating
2848 `backward-delete-char-untabify' ARG times."
2849 (interactive "*p")
2850 (let ((cur-pos (current-column))
2851 (start-of-indention (save-excursion
2852 (back-to-indentation)
2853 (current-column)))
2854 (positions (markdown-calc-indents)))
2855 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
2856 (indent-line-to (markdown-exdent-find-next-position cur-pos positions))
2857 (backward-delete-char-untabify arg))))
2859 (defun markdown-find-leftmost-column (beg end)
2860 "Find the leftmost column in the region from BEG to END."
2861 (let ((mincol 1000))
2862 (save-excursion
2863 (goto-char beg)
2864 (while (< (point) end)
2865 (back-to-indentation)
2866 (unless (looking-at "[ \t]*$")
2867 (setq mincol (min mincol (current-column))))
2868 (forward-line 1)
2870 mincol))
2872 (defun markdown-indent-region (beg end arg)
2873 "Indent the region from BEG to END using some heuristics.
2874 When ARG is non-nil, exdent the region instead.
2875 See `markdown-indent-line' and `markdown-indent-line'."
2876 (interactive "*r\nP")
2877 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
2878 (leftmostcol (markdown-find-leftmost-column beg end))
2879 (next-pos (if arg
2880 (markdown-exdent-find-next-position leftmostcol positions)
2881 (markdown-indent-find-next-position leftmostcol positions))))
2882 (indent-rigidly beg end (- next-pos leftmostcol))
2883 (setq deactivate-mark nil)))
2885 (defun markdown-exdent-region (beg end)
2886 "Call `markdown-indent-region' on region from BEG to END with prefix."
2887 (interactive "*r")
2888 (markdown-indent-region (region-beginning) (region-end) t))
2891 ;;; Markup Completion =========================================================
2893 (defconst markdown-complete-alist
2894 '((markdown-regex-header-atx . markdown-complete-atx)
2895 (markdown-regex-header-setext . markdown-complete-setext)
2896 (markdown-regex-hr . markdown-complete-hr))
2897 "Association list of form (regexp . function) for markup completion.")
2899 (defun markdown-incomplete-atx-p ()
2900 "Return t if ATX header markup is incomplete and nil otherwise.
2901 Assumes match data is available for `markdown-regex-header-atx'.
2902 Checks that the number of trailing hash marks equals the number of leading
2903 hash marks, that there is only a single space before and after the text,
2904 and that there is no extraneous whitespace in the text."
2905 (save-match-data
2907 ;; Number of starting and ending hash marks differs
2908 (not (= (length (match-string 1)) (length (match-string 3))))
2909 ;; When the header text is not empty...
2910 (and (> (length (match-string 2)) 0)
2911 ;; ...if there are extra leading, trailing, or interior spaces
2912 (or (not (= (match-beginning 2) (1+ (match-end 1))))
2913 (not (= (match-beginning 3) (1+ (match-end 2))))
2914 (string-match "[ \t\n]\\{2\\}" (match-string 2))))
2915 ;; When the header text is empty...
2916 (and (= (length (match-string 2)) 0)
2917 ;; ...if there are too many or too few spaces
2918 (not (= (match-beginning 3) (+ (match-end 1) 2)))))))
2920 (defun markdown-complete-atx ()
2921 "Complete and normalize ATX headers.
2922 Add or remove hash marks to the end of the header to match the
2923 beginning. Ensure that there is only a single space between hash
2924 marks and header text. Removes extraneous whitespace from header text.
2925 Assumes match data is available for `markdown-regex-header-atx'.
2926 Return nil if markup was complete and non-nil if markup was completed."
2927 (when (markdown-incomplete-atx-p)
2928 (let* ((new-marker (make-marker))
2929 (new-marker (set-marker new-marker (match-end 2))))
2930 ;; Hash marks and spacing at end
2931 (goto-char (match-end 2))
2932 (delete-region (match-end 2) (match-end 3))
2933 (insert " " (match-string 1))
2934 ;; Remove extraneous whitespace from title
2935 (replace-match (markdown-compress-whitespace-string (match-string 2))
2936 t t nil 2)
2937 ;; Spacing at beginning
2938 (goto-char (match-end 1))
2939 (delete-region (match-end 1) (match-beginning 2))
2940 (insert " ")
2941 ;; Leave point at end of text
2942 (goto-char new-marker))))
2944 (defun markdown-incomplete-setext-p ()
2945 "Return t if setext header markup is incomplete and nil otherwise.
2946 Assumes match data is available for `markdown-regex-header-setext'.
2947 Checks that length of underline matches text and that there is no
2948 extraneous whitespace in the text."
2949 (save-match-data
2950 (or (not (= (length (match-string 1)) (length (match-string 2))))
2951 (string-match "[ \t\n]\\{2\\}" (match-string 1)))))
2953 (defun markdown-complete-setext ()
2954 "Complete and normalize setext headers.
2955 Add or remove underline characters to match length of header
2956 text. Removes extraneous whitespace from header text. Assumes
2957 match data is available for `markdown-regex-header-setext'.
2958 Return nil if markup was complete and non-nil if markup was completed."
2959 (when (markdown-incomplete-setext-p)
2960 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
2961 (char (char-after (match-beginning 2)))
2962 (level (if (char-equal char ?-) 2 1)))
2963 (goto-char (match-beginning 0))
2964 (delete-region (match-beginning 0) (match-end 0))
2965 (markdown-insert-header level text t)
2966 t)))
2968 (defun markdown-incomplete-hr-p ()
2969 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
2970 Assumes match data is available for `markdown-regex-hr'."
2971 (not (member (match-string 0) markdown-hr-strings)))
2973 (defun markdown-complete-hr ()
2974 "Complete horizontal rules.
2975 If horizontal rule string is a member of `markdown-hr-strings',
2976 do nothing. Otherwise, replace with the car of
2977 `markdown-hr-strings'.
2978 Assumes match data is available for `markdown-regex-hr'.
2979 Return nil if markup was complete and non-nil if markup was completed."
2980 (when (markdown-incomplete-hr-p)
2981 (replace-match (car markdown-hr-strings))
2984 (defun markdown-complete ()
2985 "Complete markup of object near point or in region when active.
2986 Handle all objects in `markdown-complete-alist', in order.
2987 See `markdown-complete-at-point' and `markdown-complete-region'."
2988 (interactive "*")
2989 (if (markdown-use-region-p)
2990 (markdown-complete-region (region-beginning) (region-end))
2991 (markdown-complete-at-point)))
2993 (defun markdown-complete-at-point ()
2994 "Complete markup of object near point.
2995 Handle all elements of `markdown-complete-alist' in order."
2996 (interactive "*")
2997 (let ((list markdown-complete-alist) found changed)
2998 (while list
2999 (let ((regexp (eval (caar list)))
3000 (function (cdar list)))
3001 (setq list (cdr list))
3002 (when (thing-at-point-looking-at regexp)
3003 (setq found t)
3004 (setq changed (funcall function))
3005 (setq list nil))))
3006 (if found
3007 (or changed (error "Markup at point is complete"))
3008 (error "Nothing to complete at point"))))
3010 (defun markdown-complete-region (beg end)
3011 "Complete markup of objects in region from BEG to END.
3012 Handle all objects in `markdown-complete-alist', in
3013 order."
3014 (interactive "*r")
3015 (let ((end-marker (set-marker (make-marker) end)))
3016 (dolist (element markdown-complete-alist)
3017 (let ((regexp (eval (car element)))
3018 (function (cdr element)))
3019 (goto-char beg)
3020 (while (re-search-forward regexp end-marker 'limit)
3021 (save-excursion (funcall function)))))))
3023 (defun markdown-complete-buffer ()
3024 "Complete markup for all objects in the current buffer."
3025 (interactive "*")
3026 (markdown-complete-region (point-min) (point-max)))
3029 ;;; Markup Cycling ============================================================
3031 (defun markdown-cycle-atx (arg &optional remove)
3032 "Cycle ATX header markup.
3033 Promote header (decrease level) when ARG is 1 and demote
3034 header (increase level) if arg is -1. When REMOVE is non-nil,
3035 remove the header when the level reaches zero and stop cycling
3036 when it reaches six. Otherwise, perform a proper cycling through
3037 levels one through six. Assumes match data is available for
3038 `markdown-regex-header-atx'."
3039 (let* ((old-level (length (match-string 1)))
3040 (new-level (+ old-level arg))
3041 (text (match-string 2)))
3042 (when (not remove)
3043 (setq new-level (% new-level 6))
3044 (setq new-level (cond ((= new-level 0) 6)
3045 ((< new-level 0) (+ new-level 6))
3046 (t new-level))))
3047 (cond
3048 ((= new-level 0)
3049 (markdown-unwrap-thing-at-point nil 0 2))
3050 ((<= new-level 6)
3051 (goto-char (match-beginning 0))
3052 (delete-region (match-beginning 0) (match-end 0))
3053 (markdown-insert-header new-level text nil)))))
3055 (defun markdown-cycle-setext (arg &optional remove)
3056 "Cycle setext header markup.
3057 Promote header (increase level) when ARG is 1 and demote
3058 header (decrease level or remove) if arg is -1. When demoting a
3059 level-two setext header, replace with a level-three atx header.
3060 When REMOVE is non-nil, remove the header when the level reaches
3061 zero. Otherwise, cycle back to a level six atx header. Assumes
3062 match data is available for `markdown-regex-header-setext'."
3063 (let* ((char (char-after (match-beginning 2)))
3064 (old-level (if (char-equal char ?=) 1 2))
3065 (new-level (+ old-level arg))
3066 (text (match-string 1)))
3067 (when (and (not remove) (= new-level 0))
3068 (setq new-level 6))
3069 (cond
3070 ((= new-level 0)
3071 (markdown-unwrap-thing-at-point nil 0 1))
3072 ((<= new-level 2)
3073 (markdown-insert-header new-level nil t))
3074 ((<= new-level 6)
3075 (markdown-insert-header new-level nil nil)))))
3077 (defun markdown-cycle-hr (arg &optional remove)
3078 "Cycle string used for horizontal rule from `markdown-hr-strings'.
3079 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
3080 backwards (promote). When REMOVE is non-nil, remove the hr instead
3081 of cycling when the end of the list is reached.
3082 Assumes match data is available for `markdown-regex-hr'."
3083 (let* ((strings (if (= arg -1)
3084 (reverse markdown-hr-strings)
3085 markdown-hr-strings))
3086 (tail (member (match-string 0) strings))
3087 (new (or (cadr tail)
3088 (if remove
3089 (if (= arg 1)
3091 (car tail))
3092 (car strings)))))
3093 (replace-match new)))
3095 (defun markdown-cycle-bold ()
3096 "Cycle bold markup between underscores and asterisks.
3097 Assumes match data is available for `markdown-regex-bold'."
3098 (save-excursion
3099 (let* ((old-delim (match-string 3))
3100 (new-delim (if (string-equal old-delim "**") "__" "**")))
3101 (replace-match new-delim t t nil 3)
3102 (replace-match new-delim t t nil 5))))
3104 (defun markdown-cycle-italic ()
3105 "Cycle italic markup between underscores and asterisks.
3106 Assumes match data is available for `markdown-regex-italic'."
3107 (save-excursion
3108 (let* ((old-delim (match-string 3))
3109 (new-delim (if (string-equal old-delim "*") "_" "*")))
3110 (replace-match new-delim t t nil 3)
3111 (replace-match new-delim t t nil 5))))
3114 ;;; Keymap ====================================================================
3116 (defvar markdown-mode-map
3117 (let ((map (make-keymap)))
3118 ;; Element insertion
3119 (define-key map "\C-c\C-al" 'markdown-insert-link)
3120 (define-key map "\C-c\C-aL" 'markdown-insert-reference-link-dwim)
3121 (define-key map "\C-c\C-au" 'markdown-insert-uri)
3122 (define-key map "\C-c\C-af" 'markdown-insert-footnote)
3123 (define-key map "\C-c\C-aw" 'markdown-insert-wiki-link)
3124 (define-key map "\C-c\C-ii" 'markdown-insert-image)
3125 (define-key map "\C-c\C-iI" 'markdown-insert-reference-image)
3126 (define-key map "\C-c\C-th" 'markdown-insert-header-dwim)
3127 (define-key map "\C-c\C-tH" 'markdown-insert-header-setext-dwim)
3128 (define-key map "\C-c\C-t1" 'markdown-insert-header-atx-1)
3129 (define-key map "\C-c\C-t2" 'markdown-insert-header-atx-2)
3130 (define-key map "\C-c\C-t3" 'markdown-insert-header-atx-3)
3131 (define-key map "\C-c\C-t4" 'markdown-insert-header-atx-4)
3132 (define-key map "\C-c\C-t5" 'markdown-insert-header-atx-5)
3133 (define-key map "\C-c\C-t6" 'markdown-insert-header-atx-6)
3134 (define-key map "\C-c\C-t!" 'markdown-insert-header-setext-1)
3135 (define-key map "\C-c\C-t@" 'markdown-insert-header-setext-2)
3136 (define-key map "\C-c\C-ss" 'markdown-insert-bold)
3137 (define-key map "\C-c\C-se" 'markdown-insert-italic)
3138 (define-key map "\C-c\C-sc" 'markdown-insert-code)
3139 (define-key map "\C-c\C-sb" 'markdown-insert-blockquote)
3140 (define-key map "\C-c\C-s\C-b" 'markdown-blockquote-region)
3141 (define-key map "\C-c\C-sp" 'markdown-insert-pre)
3142 (define-key map "\C-c\C-s\C-p" 'markdown-pre-region)
3143 (define-key map "\C-c-" 'markdown-insert-hr)
3144 ;; Element insertion (deprecated)
3145 (define-key map "\C-c\C-ar" 'markdown-insert-reference-link-dwim)
3146 (define-key map "\C-c\C-tt" 'markdown-insert-header-setext-1)
3147 (define-key map "\C-c\C-ts" 'markdown-insert-header-setext-2)
3148 ;; Element removal
3149 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
3150 ;; Promotion, Demotion, Completion, and Cycling
3151 (define-key map (kbd "C-c C--") 'markdown-promote)
3152 (define-key map (kbd "C-c C-=") 'markdown-demote)
3153 (define-key map (kbd "C-c C-]") 'markdown-complete)
3154 ;; Following and Jumping
3155 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
3156 (define-key map (kbd "C-c C-j") 'markdown-jump)
3157 ;; Indentation
3158 (define-key map (kbd "C-m") 'markdown-enter-key)
3159 (define-key map (kbd "<backspace>") 'markdown-exdent-or-delete)
3160 (define-key map (kbd "C-c >") 'markdown-indent-region)
3161 (define-key map (kbd "C-c <") 'markdown-exdent-region)
3162 ;; Visibility cycling
3163 (define-key map (kbd "<tab>") 'markdown-cycle)
3164 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
3165 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
3166 (define-key map (kbd "<backtab>") 'markdown-shifttab)
3167 ;; Header navigation
3168 (define-key map (kbd "C-c C-n") 'outline-next-visible-heading)
3169 (define-key map (kbd "C-c C-p") 'outline-previous-visible-heading)
3170 (define-key map (kbd "C-c C-f") 'outline-forward-same-level)
3171 (define-key map (kbd "C-c C-b") 'outline-backward-same-level)
3172 (define-key map (kbd "C-c C-u") 'outline-up-heading)
3173 ;; Buffer-wide commands
3174 (define-key map (kbd "C-c C-c m") 'markdown-other-window)
3175 (define-key map (kbd "C-c C-c p") 'markdown-preview)
3176 (define-key map (kbd "C-c C-c e") 'markdown-export)
3177 (define-key map (kbd "C-c C-c v") 'markdown-export-and-preview)
3178 (define-key map (kbd "C-c C-c o") 'markdown-open)
3179 (define-key map (kbd "C-c C-c w") 'markdown-kill-ring-save)
3180 (define-key map (kbd "C-c C-c c") 'markdown-check-refs)
3181 (define-key map (kbd "C-c C-c n") 'markdown-cleanup-list-numbers)
3182 (define-key map (kbd "C-c C-c ]") 'markdown-complete-buffer)
3183 ;; List editing
3184 (define-key map (kbd "M-<up>") 'markdown-move-up)
3185 (define-key map (kbd "M-<down>") 'markdown-move-down)
3186 (define-key map (kbd "M-<left>") 'markdown-promote)
3187 (define-key map (kbd "M-<right>") 'markdown-demote)
3188 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
3189 ;; Movement
3190 (define-key map (kbd "M-[") 'markdown-beginning-of-block)
3191 (define-key map (kbd "M-]") 'markdown-end-of-block)
3192 (define-key map (kbd "M-n") 'markdown-next-link)
3193 (define-key map (kbd "M-p") 'markdown-previous-link)
3194 ;; Alternative keys (in case of problems with the arrow keys)
3195 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
3196 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
3197 (define-key map (kbd "C-c C-x l") 'markdown-promote)
3198 (define-key map (kbd "C-c C-x r") 'markdown-demote)
3199 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item)
3200 map)
3201 "Keymap for Markdown major mode.")
3203 (defvar gfm-mode-map
3204 (let ((map (make-sparse-keymap)))
3205 (set-keymap-parent map markdown-mode-map)
3206 (define-key map (kbd "C-c C-s P") 'markdown-insert-gfm-code-block)
3207 map)
3208 "Keymap for `gfm-mode'.
3209 See also `markdown-mode-map'.")
3212 ;;; Menu ==================================================================
3214 (easy-menu-define markdown-mode-menu markdown-mode-map
3215 "Menu for Markdown mode"
3216 '("Markdown"
3217 ("Show/Hide"
3218 ["Cycle visibility" markdown-cycle (outline-on-heading-p)]
3219 ["Cycle global visibility" markdown-shifttab])
3220 "---"
3221 ["Compile" markdown-other-window]
3222 ["Preview" markdown-preview]
3223 ["Export" markdown-export]
3224 ["Export & View" markdown-export-and-preview]
3225 ["Open" markdown-open]
3226 ["Kill ring save" markdown-kill-ring-save]
3227 "---"
3228 ("Headings"
3229 ["Automatic" markdown-insert-header-dwim]
3230 ["Automatic (prefer setext)" markdown-insert-header-setext-dwim]
3231 "---"
3232 ["First level setext" markdown-insert-header-setext-1]
3233 ["Second level setext" markdown-insert-header-setext-2]
3234 "---"
3235 ["First level atx" markdown-insert-header-atx-1]
3236 ["Second level atx" markdown-insert-header-atx-2]
3237 ["Third level atx" markdown-insert-header-atx-3]
3238 ["Fourth level atx" markdown-insert-header-atx-4]
3239 ["Fifth level atx" markdown-insert-header-atx-5]
3240 ["Sixth level atx" markdown-insert-header-atx-6])
3241 "---"
3242 ["Bold" markdown-insert-bold]
3243 ["Italic" markdown-insert-italic]
3244 ["Blockquote" markdown-insert-blockquote]
3245 ["Preformatted" markdown-insert-pre]
3246 ["Code" markdown-insert-code]
3247 "---"
3248 ["Insert inline link" markdown-insert-link]
3249 ["Insert reference link" markdown-insert-reference-link-dwim]
3250 ["Insert URL" markdown-insert-uri]
3251 ["Insert inline image" markdown-insert-image]
3252 ["Insert reference image" markdown-insert-reference-image]
3253 ["Insert list item" markdown-insert-list-item]
3254 ["Insert horizontal rule" markdown-insert-hr]
3255 ["Insert footnote" markdown-insert-footnote]
3256 ["Kill element" markdown-kill-thing-at-point]
3257 "---"
3258 ["Jump" markdown-jump]
3259 ["Follow link" markdown-follow-thing-at-point]
3260 ("Outline"
3261 ["Next visible heading" outline-next-visible-heading]
3262 ["Previous visible heading" outline-previous-visible-heading]
3263 ["Forward same level" outline-forward-same-level]
3264 ["Backward same level" outline-backward-same-level]
3265 ["Up to parent heading" outline-up-heading])
3266 "---"
3267 ("Completion and Cycling"
3268 ["Complete" markdown-complete]
3269 ["Promote" markdown-promote]
3270 ["Demote" markdown-demote])
3271 ("List editing"
3272 ["Indent list item" markdown-demote]
3273 ["Exdent list item" markdown-promote])
3274 ("Region shifting"
3275 ["Indent region" markdown-indent-region]
3276 ["Exdent region" markdown-exdent-region])
3277 "---"
3278 ["Check references" markdown-check-refs]
3279 ["Clean up list numbering" markdown-cleanup-list-numbers]
3280 ["Complete markup" markdown-complete-buffer]
3281 "---"
3282 ["Version" markdown-show-version]
3286 ;;; imenu =====================================================================
3288 (defun markdown-imenu-create-index ()
3289 "Create and return an imenu index alist for the current buffer.
3290 See `imenu-create-index-function' and `imenu--index-alist' for details."
3291 (let* ((root '(nil . nil))
3292 cur-alist
3293 (cur-level 0)
3294 (empty-heading "-")
3295 (self-heading ".")
3296 hashes pos level heading)
3297 (save-excursion
3298 (goto-char (point-min))
3299 (while (re-search-forward markdown-regex-header (point-max) t)
3300 (cond
3301 ((setq heading (match-string-no-properties 1))
3302 (setq pos (match-beginning 1)
3303 level 1))
3304 ((setq heading (match-string-no-properties 3))
3305 (setq pos (match-beginning 3)
3306 level 2))
3307 ((setq hashes (match-string-no-properties 5))
3308 (setq heading (match-string-no-properties 6)
3309 pos (match-beginning 5)
3310 level (length hashes))))
3311 (let ((alist (list (cons heading pos))))
3312 (cond
3313 ((= cur-level level) ; new sibling
3314 (setcdr cur-alist alist)
3315 (setq cur-alist alist))
3316 ((< cur-level level) ; first child
3317 (dotimes (i (- level cur-level 1))
3318 (setq alist (list (cons empty-heading alist))))
3319 (if cur-alist
3320 (let* ((parent (car cur-alist))
3321 (self-pos (cdr parent)))
3322 (setcdr parent (cons (cons self-heading self-pos) alist)))
3323 (setcdr root alist)) ; primogenitor
3324 (setq cur-alist alist)
3325 (setq cur-level level))
3326 (t ; new sibling of an ancestor
3327 (let ((sibling-alist (last (cdr root))))
3328 (dotimes (i (1- level))
3329 (setq sibling-alist (last (cdar sibling-alist))))
3330 (setcdr sibling-alist alist)
3331 (setq cur-alist alist))
3332 (setq cur-level level)))))
3333 (cdr root))))
3336 ;;; References ================================================================
3338 (defun markdown-insert-reference-definition (ref &optional buffer)
3339 "Add blank REF definition to the end of BUFFER.
3340 REF is a Markdown reference in square brackets, like \"[lisp-history]\"."
3341 (or buffer (setq buffer (current-buffer)))
3342 (with-current-buffer buffer
3343 (goto-char (point-max))
3344 (indent-new-comment-line)
3345 (insert (concat ref ": "))))
3347 (defun markdown-reference-goto-definition ()
3348 "Jump to the definition of the reference at point or create it."
3349 (interactive)
3350 (when (thing-at-point-looking-at markdown-regex-link-reference)
3351 (let* ((text (match-string-no-properties 2))
3352 (reference (match-string-no-properties 4))
3353 (target (downcase (if (string= reference "[]") text reference)))
3354 (loc (cadr (markdown-reference-definition target))))
3355 (if loc
3356 (goto-char loc)
3357 (markdown-insert-reference-definition target (current-buffer))))))
3359 (defun markdown-reference-find-links (reference)
3360 "Return a list of all links for REFERENCE.
3361 REFERENCE should include the surrounding square brackets like [this].
3362 Elements of the list have the form (text start line), where
3363 text is the link text, start is the location at the beginning of
3364 the link, and line is the line number on which the link appears."
3365 (let* ((ref-quote (regexp-quote (substring reference 1 -1)))
3366 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
3367 ref-quote ref-quote))
3368 links)
3369 (save-excursion
3370 (goto-char (point-min))
3371 (while (re-search-forward regexp nil t)
3372 (let* ((text (or (match-string-no-properties 1)
3373 (match-string-no-properties 2)))
3374 (start (match-beginning 0))
3375 (line (markdown-line-number-at-pos)))
3376 (add-to-list 'links (list text start line)))))
3377 links))
3379 (defun markdown-get-undefined-refs ()
3380 "Return a list of undefined Markdown references.
3381 Result is an alist of pairs (reference . occurrences), where
3382 occurrences is itself another alist of pairs (label . line-number).
3383 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
3384 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
3385 \((\"[emacs]\" (\"[Nice editor]\" . 12) (\"[GNU Emacs]\" . 45)) (\"[elisp]\" (\"[manual]\" . 127)))."
3386 (let ((missing))
3387 (save-excursion
3388 (goto-char (point-min))
3389 (while
3390 (re-search-forward markdown-regex-link-reference nil t)
3391 (let* ((text (match-string-no-properties 2))
3392 (reference (match-string-no-properties 4))
3393 (target (downcase (if (string= reference "[]") text reference))))
3394 (unless (markdown-reference-definition target)
3395 (let ((entry (assoc target missing)))
3396 (if (not entry)
3397 (add-to-list 'missing (cons target
3398 (list (cons text (markdown-line-number-at-pos)))) t)
3399 (setcdr entry
3400 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
3401 missing)))
3403 (defconst markdown-reference-check-buffer
3404 "*Undefined references for %buffer%*"
3405 "Pattern for name of buffer for listing undefined references.
3406 The string %buffer% will be replaced by the corresponding
3407 `markdown-mode' buffer name.")
3409 (defun markdown-reference-check-buffer (&optional buffer-name)
3410 "Name and return buffer for reference checking.
3411 BUFFER-NAME is the name of the main buffer being visited."
3412 (or buffer-name (setq buffer-name (buffer-name)))
3413 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
3414 "%buffer%" buffer-name
3415 markdown-reference-check-buffer))))
3416 (with-current-buffer refbuf
3417 (when view-mode
3418 (View-exit-and-edit))
3419 (use-local-map button-buffer-map)
3420 (erase-buffer))
3421 refbuf))
3423 (defconst markdown-reference-links-buffer
3424 "*Reference links for %buffer%*"
3425 "Pattern for name of buffer for listing references.
3426 The string %buffer% will be replaced by the corresponding buffer name.")
3428 (defun markdown-reference-links-buffer (&optional buffer-name)
3429 "Name, setup, and return a buffer for listing links.
3430 BUFFER-NAME is the name of the main buffer being visited."
3431 (or buffer-name (setq buffer-name (buffer-name)))
3432 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
3433 "%buffer%" buffer-name
3434 markdown-reference-links-buffer))))
3435 (with-current-buffer linkbuf
3436 (when view-mode
3437 (View-exit-and-edit))
3438 (use-local-map button-buffer-map)
3439 (erase-buffer))
3440 linkbuf))
3442 (when (markdown-use-buttons-p)
3443 ;; Add an empty Markdown reference definition to the end of buffer
3444 ;; specified in the 'target-buffer property. The reference name is
3445 ;; the button's label.
3446 (define-button-type 'markdown-undefined-reference-button
3447 'help-echo "mouse-1, RET: create definition for undefined reference"
3448 'follow-link t
3449 'face 'bold
3450 'action (lambda (b)
3451 (let ((buffer (button-get b 'target-buffer)))
3452 (markdown-insert-reference-definition (button-label b) buffer)
3453 (switch-to-buffer-other-window buffer)
3454 (goto-char (point-max))
3455 (markdown-check-refs t))))
3457 ;; Jump to line in buffer specified by 'target-buffer property.
3458 ;; Line number is button's 'line property.
3459 (define-button-type 'markdown-goto-line-button
3460 'help-echo "mouse-1, RET: go to line"
3461 'follow-link t
3462 'face 'italic
3463 'action (lambda (b)
3464 (message (button-get b 'buffer))
3465 (switch-to-buffer-other-window (button-get b 'target-buffer))
3466 ;; use call-interactively to silence compiler
3467 (let ((current-prefix-arg (button-get b 'target-line)))
3468 (call-interactively 'goto-line))))
3470 ;; Jumps to a particular link at location given by 'target-char
3471 ;; property in buffer given by 'target-buffer property.
3472 (define-button-type 'markdown-link-button
3473 'help-echo "mouse-1, RET: jump to location of link"
3474 'follow-link t
3475 'face 'bold
3476 'action (lambda (b)
3477 (let ((target (button-get b 'target-buffer))
3478 (loc (button-get b 'target-char)))
3479 (kill-buffer-and-window)
3480 (switch-to-buffer target)
3481 (goto-char loc)))))
3483 (defun markdown-insert-undefined-reference-button (reference oldbuf)
3484 "Insert a button for creating REFERENCE in buffer OLDBUF.
3485 REFERENCE should be a list of the form (reference . occurrences),
3486 as by `markdown-get-undefined-refs'."
3487 (let ((label (car reference)))
3488 (if (markdown-use-buttons-p)
3489 ;; Create a reference button in Emacs 22
3490 (insert-button label
3491 :type 'markdown-undefined-reference-button
3492 'target-buffer oldbuf)
3493 ;; Insert reference as text in Emacs < 22
3494 (insert label))
3495 (insert " (")
3496 (dolist (occurrence (cdr reference))
3497 (let ((line (cdr occurrence)))
3498 (if (markdown-use-buttons-p)
3499 ;; Create a line number button in Emacs 22
3500 (insert-button (number-to-string line)
3501 :type 'markdown-goto-line-button
3502 'target-buffer oldbuf
3503 'target-line line)
3504 ;; Insert line number as text in Emacs < 22
3505 (insert (number-to-string line)))
3506 (insert " ")))
3507 (delete-char -1)
3508 (insert ")")
3509 (newline)))
3511 (defun markdown-insert-link-button (link oldbuf)
3512 "Insert a button for jumping to LINK in buffer OLDBUF.
3513 LINK should be a list of the form (text char line) containing
3514 the link text, location, and line number."
3515 (let ((label (first link))
3516 (char (second link))
3517 (line (third link)))
3518 (if (markdown-use-buttons-p)
3519 ;; Create a reference button in Emacs 22
3520 (insert-button label
3521 :type 'markdown-link-button
3522 'target-buffer oldbuf
3523 'target-char char)
3524 ;; Insert reference as text in Emacs < 22
3525 (insert label))
3526 (insert (format " (line %d)\n" line))))
3528 (defun markdown-reference-goto-link (&optional reference)
3529 "Jump to the location of the first use of REFERENCE."
3530 (interactive)
3531 (unless reference
3532 (if (thing-at-point-looking-at markdown-regex-reference-definition)
3533 (setq reference (match-string-no-properties 1))
3534 (error "No reference definition at point")))
3535 (let ((links (markdown-reference-find-links reference)))
3536 (cond ((= (length links) 1)
3537 (goto-char (cadr (car links))))
3538 ((> (length links) 1)
3539 (let ((oldbuf (current-buffer))
3540 (linkbuf (markdown-reference-links-buffer)))
3541 (with-current-buffer linkbuf
3542 (insert "Links using reference " reference ":\n\n")
3543 (dolist (link (reverse links))
3544 (markdown-insert-link-button link oldbuf)))
3545 (view-buffer-other-window linkbuf)
3546 (goto-char (point-min))
3547 (forward-line 2)))
3549 (error "No links for reference %s" reference)))))
3551 (defun markdown-check-refs (&optional silent)
3552 "Show all undefined Markdown references in current `markdown-mode' buffer.
3553 If SILENT is non-nil, do not message anything when no undefined
3554 references found.
3555 Links which have empty reference definitions are considered to be
3556 defined."
3557 (interactive "P")
3558 (when (not (eq major-mode 'markdown-mode))
3559 (error "Not available in current mode"))
3560 (let ((oldbuf (current-buffer))
3561 (refs (markdown-get-undefined-refs))
3562 (refbuf (markdown-reference-check-buffer)))
3563 (if (null refs)
3564 (progn
3565 (when (not silent)
3566 (message "No undefined references found"))
3567 (kill-buffer refbuf))
3568 (with-current-buffer refbuf
3569 (insert "The following references are undefined:\n\n")
3570 (dolist (ref refs)
3571 (markdown-insert-undefined-reference-button ref oldbuf))
3572 (view-buffer-other-window refbuf)
3573 (goto-char (point-min))
3574 (forward-line 2)))))
3577 ;;; Lists =====================================================================
3579 (defun markdown-insert-list-item (&optional arg)
3580 "Insert a new list item.
3581 If the point is inside unordered list, insert a bullet mark. If
3582 the point is inside ordered list, insert the next number followed
3583 by a period. Use the previous list item to determine the amount
3584 of whitespace to place before and after list markers.
3586 With a \\[universal-argument] prefix (i.e., when ARG is 4),
3587 decrease the indentation by one level.
3589 With two \\[universal-argument] prefixes (i.e., when ARG is 16),
3590 increase the indentation by one level."
3591 (interactive "p")
3592 (let (bounds item-indent marker indent new-indent new-loc)
3593 (save-match-data
3594 ;; Look for a list item on current or previous non-blank line
3595 (save-excursion
3596 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
3597 (not (bobp))
3598 (markdown-cur-line-blank-p))
3599 (forward-line -1)))
3600 (when bounds
3601 (cond ((save-excursion
3602 (skip-chars-backward " \t")
3603 (looking-at markdown-regex-list))
3604 (beginning-of-line)
3605 (insert "\n")
3606 (forward-line -1))
3607 ((not (markdown-cur-line-blank-p))
3608 (newline)))
3609 (setq new-loc (point)))
3610 ;; Look ahead for a list item on next non-blank line
3611 (unless bounds
3612 (save-excursion
3613 (while (and (null bounds)
3614 (not (eobp))
3615 (markdown-cur-line-blank-p))
3616 (forward-line)
3617 (setq bounds (markdown-cur-list-item-bounds))))
3618 (when bounds
3619 (setq new-loc (point))
3620 (unless (markdown-cur-line-blank-p)
3621 (newline))))
3622 (if (not bounds)
3623 ;; When not in a list, start a new unordered one
3624 (progn
3625 (unless (markdown-cur-line-blank-p)
3626 (insert "\n"))
3627 (insert "* "))
3628 ;; Compute indentation for a new list item
3629 (setq item-indent (nth 2 bounds))
3630 (setq marker (nth 4 bounds))
3631 (setq indent (cond
3632 ((= arg 4) (max (- item-indent 4) 0))
3633 ((= arg 16) (+ item-indent 4))
3634 (t item-indent)))
3635 (setq new-indent (make-string indent 32))
3636 (goto-char new-loc)
3637 (cond
3638 ;; Ordered list
3639 ((string-match "[0-9]" marker)
3640 (if (= arg 16) ;; starting a new column indented one more level
3641 (insert (concat new-indent "1. "))
3642 ;; travel up to the last item and pick the correct number. If
3643 ;; the argument was nil, "new-indent = item-indent" is the same,
3644 ;; so we don't need special treatment. Neat.
3645 (save-excursion
3646 (while (not (looking-at (concat new-indent "\\([0-9]+\\)\\.")))
3647 (forward-line -1)))
3648 (insert (concat new-indent
3649 (int-to-string (1+ (string-to-number (match-string 1))))
3650 ". "))))
3651 ;; Unordered list
3652 ((string-match "[\\*\\+-]" marker)
3653 (insert new-indent marker)))))))
3655 (defun markdown-move-list-item-up ()
3656 "Move the current list item up in the list when possible."
3657 (interactive)
3658 (let (cur prev old)
3659 (when (setq cur (markdown-cur-list-item-bounds))
3660 (setq old (point))
3661 (goto-char (nth 0 cur))
3662 (if (markdown-prev-list-item (nth 3 cur))
3663 (progn
3664 (setq prev (markdown-cur-list-item-bounds))
3665 (condition-case nil
3666 (progn
3667 (transpose-regions (nth 0 prev) (nth 1 prev)
3668 (nth 0 cur) (nth 1 cur) t)
3669 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
3670 ;; Catch error in case regions overlap.
3671 (error (goto-char old))))
3672 (goto-char old)))))
3674 (defun markdown-move-list-item-down ()
3675 "Move the current list item down in the list when possible."
3676 (interactive)
3677 (let (cur next old)
3678 (when (setq cur (markdown-cur-list-item-bounds))
3679 (setq old (point))
3680 (if (markdown-next-list-item (nth 3 cur))
3681 (progn
3682 (setq next (markdown-cur-list-item-bounds))
3683 (condition-case nil
3684 (progn
3685 (transpose-regions (nth 0 cur) (nth 1 cur)
3686 (nth 0 next) (nth 1 next) nil)
3687 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
3688 ;; Catch error in case regions overlap.
3689 (error (goto-char old))))
3690 (goto-char old)))))
3692 (defun markdown-demote-list-item (&optional bounds)
3693 "Indent (or demote) the current list item.
3694 Optionally, BOUNDS of the current list item may be provided if available."
3695 (interactive)
3696 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
3697 (save-excursion
3698 (save-match-data
3699 (let* ((end-marker (make-marker))
3700 (end-marker (set-marker end-marker (nth 1 bounds))))
3701 (goto-char (nth 0 bounds))
3702 (while (< (point) end-marker)
3703 (unless (markdown-cur-line-blank-p)
3704 (insert " "))
3705 (forward-line)))))))
3707 (defun markdown-promote-list-item (&optional bounds)
3708 "Unindent (or promote) the current list item.
3709 Optionally, BOUNDS of the current list item may be provided if available."
3710 (interactive)
3711 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
3712 (save-excursion
3713 (save-match-data
3714 (let* ((end-marker (make-marker))
3715 (end-marker (set-marker end-marker (nth 1 bounds)))
3716 num regexp)
3717 (goto-char (nth 0 bounds))
3718 (when (looking-at "^[ ]\\{1,4\\}")
3719 (setq num (- (match-end 0) (match-beginning 0)))
3720 (setq regexp (format "^[ ]\\{1,%d\\}" num))
3721 (while (and (< (point) end-marker)
3722 (re-search-forward regexp end-marker t))
3723 (replace-match "" nil nil)
3724 (forward-line))))))))
3726 (defun markdown-cleanup-list-numbers-level (&optional pfx)
3727 "Update the numbering for level PFX (as a string of spaces).
3729 Assume that the previously found match was for a numbered item in
3730 a list."
3731 (let ((cpfx pfx)
3732 (idx 0)
3733 (continue t)
3734 (step t)
3735 (sep nil))
3736 (while (and continue (not (eobp)))
3737 (setq step t)
3738 (cond
3739 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
3740 (setq cpfx (match-string-no-properties 1))
3741 (cond
3742 ((string= cpfx pfx)
3743 (replace-match
3744 (concat pfx (number-to-string (setq idx (1+ idx))) ". "))
3745 (setq sep nil))
3746 ;; indented a level
3747 ((string< pfx cpfx)
3748 (setq sep (markdown-cleanup-list-numbers-level cpfx))
3749 (setq step nil))
3750 ;; exit the loop
3752 (setq step nil)
3753 (setq continue nil))))
3755 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
3756 (setq cpfx (match-string-no-properties 1))
3757 (cond
3758 ;; reset if separated before
3759 ((string= cpfx pfx) (when sep (setq idx 0)))
3760 ((string< cpfx pfx)
3761 (setq step nil)
3762 (setq continue nil))))
3763 (t (setq sep t)))
3765 (when step
3766 (beginning-of-line)
3767 (setq continue (= (forward-line) 0))))
3768 sep))
3770 (defun markdown-cleanup-list-numbers ()
3771 "Update the numbering of ordered lists."
3772 (interactive)
3773 (save-excursion
3774 (goto-char (point-min))
3775 (markdown-cleanup-list-numbers-level "")))
3778 ;;; Outline ===================================================================
3780 (defvar markdown-cycle-global-status 1)
3781 (defvar markdown-cycle-subtree-status nil)
3783 (defun markdown-end-of-subtree (&optional invisible-OK)
3784 "Move to the end of the current subtree.
3785 Only visible heading lines are considered, unless INVISIBLE-OK is
3786 non-nil.
3787 Derived from `org-end-of-subtree'."
3788 (outline-back-to-heading invisible-OK)
3789 (let ((first t)
3790 (level (funcall outline-level)))
3791 (while (and (not (eobp))
3792 (or first (> (funcall outline-level) level)))
3793 (setq first nil)
3794 (outline-next-heading))
3795 (if (memq (preceding-char) '(?\n ?\^M))
3796 (progn
3797 ;; Go to end of line before heading
3798 (forward-char -1)
3799 (if (memq (preceding-char) '(?\n ?\^M))
3800 ;; leave blank line before heading
3801 (forward-char -1)))))
3802 (point))
3804 (defun markdown-cycle (&optional arg)
3805 "Visibility cycling for Markdown mode.
3806 If ARG is t, perform global visibility cycling. If the point is
3807 at an atx-style header, cycle visibility of the corresponding
3808 subtree. Otherwise, insert a tab using `indent-relative'.
3809 Derived from `org-cycle'."
3810 (interactive "P")
3811 (cond
3812 ((eq arg t) ;; Global cycling
3813 (cond
3814 ((and (eq last-command this-command)
3815 (eq markdown-cycle-global-status 2))
3816 ;; Move from overview to contents
3817 (hide-sublevels 1)
3818 (message "CONTENTS")
3819 (setq markdown-cycle-global-status 3))
3821 ((and (eq last-command this-command)
3822 (eq markdown-cycle-global-status 3))
3823 ;; Move from contents to all
3824 (show-all)
3825 (message "SHOW ALL")
3826 (setq markdown-cycle-global-status 1))
3829 ;; Defaults to overview
3830 (hide-body)
3831 (message "OVERVIEW")
3832 (setq markdown-cycle-global-status 2))))
3834 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3835 ;; At a heading: rotate between three different views
3836 (outline-back-to-heading)
3837 (let ((goal-column 0) eoh eol eos)
3838 ;; Determine boundaries
3839 (save-excursion
3840 (outline-back-to-heading)
3841 (save-excursion
3842 (beginning-of-line 2)
3843 (while (and (not (eobp)) ;; this is like `next-line'
3844 (get-char-property (1- (point)) 'invisible))
3845 (beginning-of-line 2)) (setq eol (point)))
3846 (outline-end-of-heading) (setq eoh (point))
3847 (markdown-end-of-subtree t)
3848 (skip-chars-forward " \t\n")
3849 (beginning-of-line 1) ; in case this is an item
3850 (setq eos (1- (point))))
3851 ;; Find out what to do next and set `this-command'
3852 (cond
3853 ((= eos eoh)
3854 ;; Nothing is hidden behind this heading
3855 (message "EMPTY ENTRY")
3856 (setq markdown-cycle-subtree-status nil))
3857 ((>= eol eos)
3858 ;; Entire subtree is hidden in one line: open it
3859 (show-entry)
3860 (show-children)
3861 (message "CHILDREN")
3862 (setq markdown-cycle-subtree-status 'children))
3863 ((and (eq last-command this-command)
3864 (eq markdown-cycle-subtree-status 'children))
3865 ;; We just showed the children, now show everything.
3866 (show-subtree)
3867 (message "SUBTREE")
3868 (setq markdown-cycle-subtree-status 'subtree))
3870 ;; Default action: hide the subtree.
3871 (hide-subtree)
3872 (message "FOLDED")
3873 (setq markdown-cycle-subtree-status 'folded)))))
3876 (indent-for-tab-command))))
3878 (defun markdown-shifttab ()
3879 "Global visibility cycling.
3880 Calls `markdown-cycle' with argument t."
3881 (interactive)
3882 (markdown-cycle t))
3884 (defun markdown-outline-level ()
3885 "Return the depth to which a statement is nested in the outline."
3886 (cond
3887 ((match-end 1) 1)
3888 ((match-end 3) 2)
3889 ((- (match-end 5) (match-beginning 5)))))
3892 ;;; Movement ==================================================================
3894 (defun markdown-beginning-of-defun (&optional arg)
3895 "`beginning-of-defun-function' for Markdown.
3896 Move backward to the beginning of the current or previous section.
3897 When ARG is non-nil, repeat that many times. When ARG is negative,
3898 move forward to the ARG-th following section."
3899 (interactive "P")
3900 (or arg (setq arg 1))
3901 (or (re-search-backward markdown-regex-header nil t arg)
3902 (goto-char (point-min))))
3904 (defun markdown-end-of-defun (&optional arg)
3905 "`end-of-defun-function' for Markdown.
3906 Move forward to the end of the current or following section.
3907 When ARG is non-nil, repeat that many times. When ARG is negative,
3908 move back to the ARG-th preceding section."
3909 (interactive "P")
3910 (or arg (setq arg 1))
3911 (when (looking-at markdown-regex-header)
3912 (goto-char (match-beginning 0))
3913 (forward-char 1))
3914 (if (re-search-forward markdown-regex-header nil t arg)
3915 (goto-char (match-beginning 0))
3916 (goto-char (point-max)))
3917 (skip-syntax-backward "-"))
3919 (defun markdown-beginning-of-block ()
3920 "Move the point to the start of the previous text block."
3921 (interactive)
3922 (if (re-search-backward markdown-regex-block-separator nil t)
3923 (goto-char (or (match-end 2) (match-end 0)))
3924 (goto-char (point-min))))
3926 (defun markdown-end-of-block ()
3927 "Move the point to the start of the next text block."
3928 (interactive)
3929 (beginning-of-line)
3930 (skip-syntax-forward "-")
3931 (when (= (point) (point-min))
3932 (forward-char))
3933 (if (re-search-forward markdown-regex-block-separator nil t)
3934 (goto-char (or (match-end 2) (match-end 0)))
3935 (goto-char (point-max)))
3936 (skip-syntax-backward "-")
3937 (forward-line))
3939 (defun markdown-end-of-block-element ()
3940 "Move the point to the start of the next block unit.
3941 Stops at blank lines, list items, headers, and horizontal rules."
3942 (interactive)
3943 (forward-line)
3944 (while (and (or (not (markdown-prev-line-blank-p))
3945 (markdown-cur-line-blank-p))
3946 (not (or (looking-at markdown-regex-list)
3947 (looking-at markdown-regex-header)
3948 (looking-at markdown-regex-hr)))
3949 (not (eobp)))
3950 (forward-line)))
3952 (defun markdown-next-link ()
3953 "Jump to next inline, reference, or wiki link.
3954 If successful, return point. Otherwise, return nil.
3955 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
3956 (interactive)
3957 (let ((opoint (point)))
3958 (when (or (markdown-link-p) (markdown-wiki-link-p))
3959 ;; At a link already, move past it.
3960 (goto-char (+ (match-end 0) 1)))
3961 ;; Search for the next wiki link and move to the beginning.
3962 (if (re-search-forward markdown-regex-link-generic nil t)
3963 ;; Group 1 will move past non-escape character in wiki link regexp.
3964 ;; Go to beginning of group zero for all other link types.
3965 (goto-char (or (match-beginning 1) (match-beginning 0)))
3966 (goto-char opoint)
3967 nil)))
3969 (defun markdown-previous-link ()
3970 "Jump to previous wiki link.
3971 If successful, return point. Otherwise, return nil.
3972 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
3973 (interactive)
3974 (if (re-search-backward markdown-regex-link-generic nil t)
3975 (goto-char (or (match-beginning 1) (match-beginning 0)))
3976 nil))
3979 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
3981 (defun markdown-move-up ()
3982 "Move list item up.
3983 Calls `markdown-move-list-item-up'."
3984 (interactive)
3985 (markdown-move-list-item-up))
3987 (defun markdown-move-down ()
3988 "Move list item down.
3989 Calls `markdown-move-list-item-down'."
3990 (interactive)
3991 (markdown-move-list-item-down))
3993 (defun markdown-promote ()
3994 "Either promote header or list item at point or cycle markup.
3995 See `markdown-cycle-atx', `markdown-cycle-setext', and
3996 `markdown-promote-list-item'."
3997 (interactive)
3998 (let (bounds)
3999 (cond
4000 ;; Promote atx header
4001 ((thing-at-point-looking-at markdown-regex-header-atx)
4002 (markdown-cycle-atx -1))
4003 ;; Promote setext header
4004 ((thing-at-point-looking-at markdown-regex-header-setext)
4005 (markdown-cycle-setext -1))
4006 ;; Promote horizonal rule
4007 ((thing-at-point-looking-at markdown-regex-hr)
4008 (markdown-cycle-hr -1))
4009 ;; Promote list item
4010 ((setq bounds (markdown-cur-list-item-bounds))
4011 (markdown-promote-list-item))
4012 ;; Promote bold
4013 ((thing-at-point-looking-at markdown-regex-bold)
4014 (markdown-cycle-bold))
4015 ;; Promote italic
4016 ((thing-at-point-looking-at markdown-regex-italic)
4017 (markdown-cycle-italic))
4019 (error "Nothing to promote at point")))))
4021 (defun markdown-demote ()
4022 "Either demote header or list item at point or cycle or remove markup.
4023 See `markdown-cycle-atx', `markdown-cycle-setext', and
4024 `markdown-demote-list-item'."
4025 (interactive)
4026 (let (bounds)
4027 (cond
4028 ;; Demote atx header
4029 ((thing-at-point-looking-at markdown-regex-header-atx)
4030 (markdown-cycle-atx 1))
4031 ;; Demote setext header
4032 ((thing-at-point-looking-at markdown-regex-header-setext)
4033 (markdown-cycle-setext 1))
4034 ;; Demote horizonal rule
4035 ((thing-at-point-looking-at markdown-regex-hr)
4036 (markdown-cycle-hr 1))
4037 ;; Demote list item
4038 ((setq bounds (markdown-cur-list-item-bounds))
4039 (markdown-demote-list-item))
4040 ;; Demote bold
4041 ((thing-at-point-looking-at markdown-regex-bold)
4042 (markdown-cycle-bold))
4043 ;; Demote italic
4044 ((thing-at-point-looking-at markdown-regex-italic)
4045 (markdown-cycle-italic))
4047 (error "Nothing to demote at point")))))
4050 ;;; Commands ==================================================================
4052 (defun markdown (&optional output-buffer-name)
4053 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
4054 The output buffer name defaults to `markdown-output-buffer-name'.
4055 Return the name of the output buffer used."
4056 (interactive)
4057 (save-window-excursion
4058 (let ((begin-region)
4059 (end-region))
4060 (if (markdown-use-region-p)
4061 (setq begin-region (region-beginning)
4062 end-region (region-end))
4063 (setq begin-region (point-min)
4064 end-region (point-max)))
4066 (unless output-buffer-name
4067 (setq output-buffer-name markdown-output-buffer-name))
4069 (cond
4070 ;; Handle case when `markdown-command' does not read from stdin
4071 (markdown-command-needs-filename
4072 (if (not buffer-file-name)
4073 (error "Must be visiting a file")
4074 (shell-command (concat markdown-command " "
4075 (shell-quote-argument buffer-file-name))
4076 output-buffer-name)))
4077 ;; Pass region to `markdown-command' via stdin
4079 (shell-command-on-region begin-region end-region markdown-command
4080 output-buffer-name))))
4081 output-buffer-name))
4083 (defun markdown-standalone (&optional output-buffer-name)
4084 "Special function to provide standalone HTML output.
4085 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
4086 (interactive)
4087 (setq output-buffer-name (markdown output-buffer-name))
4088 (with-current-buffer output-buffer-name
4089 (set-buffer output-buffer-name)
4090 (goto-char (point-min))
4091 (unless (markdown-output-standalone-p)
4092 (markdown-add-xhtml-header-and-footer output-buffer-name))
4093 (html-mode))
4094 output-buffer-name)
4096 (defun markdown-other-window (&optional output-buffer-name)
4097 "Run `markdown-command' on current buffer and display in other window.
4098 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
4099 that name."
4100 (interactive)
4101 (display-buffer (markdown-standalone output-buffer-name)))
4103 (defun markdown-output-standalone-p ()
4104 "Determine whether `markdown-command' output is standalone XHTML.
4105 Standalone XHTML output is identified by an occurrence of
4106 `markdown-xhtml-standalone-regexp' in the first five lines of output."
4107 (re-search-forward
4108 markdown-xhtml-standalone-regexp
4109 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
4112 (defun markdown-add-xhtml-header-and-footer (title)
4113 "Wrap XHTML header and footer with given TITLE around current buffer."
4114 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
4115 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
4116 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
4117 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
4118 "<head>\n<title>")
4119 (insert title)
4120 (insert "</title>\n")
4121 (when (> (length markdown-content-type) 0)
4122 (insert
4123 (format
4124 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
4125 markdown-content-type
4126 (or (and markdown-coding-system
4127 (fboundp 'coding-system-get)
4128 (coding-system-get markdown-coding-system
4129 'mime-charset))
4130 (and (fboundp 'coding-system-get)
4131 (coding-system-get buffer-file-coding-system
4132 'mime-charset))
4133 "iso-8859-1"))))
4134 (if (> (length markdown-css-path) 0)
4135 (insert "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
4136 markdown-css-path
4137 "\" />\n"))
4138 (when (> (length markdown-xhtml-header-content) 0)
4139 (insert markdown-xhtml-header-content))
4140 (insert "\n</head>\n\n"
4141 "<body>\n\n")
4142 (goto-char (point-max))
4143 (insert "\n"
4144 "</body>\n"
4145 "</html>\n"))
4147 (defun markdown-preview (&optional output-buffer-name)
4148 "Run `markdown-command' on the current buffer and view output in browser.
4149 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
4150 that name."
4151 (interactive)
4152 (browse-url-of-buffer (markdown markdown-output-buffer-name)))
4154 (defun markdown-export-file-name (&optional extension)
4155 "Attempt to generate a filename for Markdown output.
4156 The file extension will be EXTENSION if given, or .html by default.
4157 If the current buffer is visiting a file, we construct a new
4158 output filename based on that filename. Otherwise, return nil."
4159 (when (buffer-file-name)
4160 (unless extension
4161 (setq extension ".html"))
4162 (concat
4163 (cond
4164 ((buffer-file-name)
4165 (file-name-sans-extension (buffer-file-name)))
4166 (t (buffer-name)))
4167 extension)))
4169 (defun markdown-export (&optional output-file)
4170 "Run Markdown on the current buffer, save to file, and return the filename.
4171 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
4172 generated by `markdown-export-file-name', which will be constructed using the
4173 current filename, but with the extension removed and replaced with .html."
4174 (interactive)
4175 (unless output-file
4176 (setq output-file (markdown-export-file-name ".html")))
4177 (when output-file
4178 (let* ((init-buf (current-buffer))
4179 (init-point (point))
4180 (init-buf-string (buffer-string))
4181 (output-buffer (find-file-noselect output-file))
4182 (output-buffer-name (buffer-name output-buffer)))
4183 (run-hooks 'markdown-before-export-hook)
4184 (markdown-standalone output-buffer-name)
4185 (with-current-buffer output-buffer
4186 (run-hooks 'markdown-after-export-hook)
4187 (save-buffer))
4188 ;; if modified, restore initial buffer
4189 (when (buffer-modified-p init-buf)
4190 (erase-buffer)
4191 (insert init-buf-string)
4192 (save-buffer)
4193 (goto-char init-point))
4194 output-file)))
4196 (defun markdown-export-and-preview ()
4197 "Export to XHTML using `markdown-export' and browse the resulting file."
4198 (interactive)
4199 (browse-url (markdown-export)))
4201 (defun markdown-open ()
4202 "Open file for the current buffer with `markdown-open-command'."
4203 (interactive)
4204 (if (not markdown-open-command)
4205 (error "Variable `markdown-open-command' must be set")
4206 (if (not buffer-file-name)
4207 (error "Must be visiting a file")
4208 (call-process markdown-open-command
4209 nil nil nil buffer-file-name))))
4211 (defun markdown-kill-ring-save ()
4212 "Run Markdown on file and store output in the kill ring."
4213 (interactive)
4214 (save-window-excursion
4215 (markdown)
4216 (with-current-buffer markdown-output-buffer-name
4217 (kill-ring-save (point-min) (point-max)))))
4220 ;;; Links =====================================================================
4222 (require 'thingatpt)
4224 (defun markdown-link-p ()
4225 "Return non-nil when `point' is at a non-wiki link.
4226 See `markdown-wiki-link-p' for more information."
4227 (let ((case-fold-search nil))
4228 (and (not (markdown-wiki-link-p))
4229 (or (thing-at-point-looking-at markdown-regex-link-inline)
4230 (thing-at-point-looking-at markdown-regex-link-reference)
4231 (thing-at-point-looking-at markdown-regex-uri)
4232 (thing-at-point-looking-at markdown-regex-angle-uri)))))
4234 (defun markdown-link-link ()
4235 "Return the link part of the regular (non-wiki) link at point.
4236 Works with both inline and reference style links. If point is
4237 not at a link or the link reference is not defined returns nil."
4238 (cond
4239 ((thing-at-point-looking-at markdown-regex-link-inline)
4240 (match-string-no-properties 5))
4241 ((thing-at-point-looking-at markdown-regex-link-reference)
4242 (let* ((text (match-string-no-properties 2))
4243 (reference (match-string-no-properties 4))
4244 (target (downcase (if (string= reference "[]") text reference))))
4245 (car (markdown-reference-definition target))))
4246 ((thing-at-point-looking-at markdown-regex-uri)
4247 (match-string-no-properties 0))
4248 ((thing-at-point-looking-at markdown-regex-angle-uri)
4249 (match-string-no-properties 2))
4250 (t nil)))
4252 (defun markdown-follow-link-at-point ()
4253 "Open the current non-wiki link in a browser."
4254 (interactive)
4255 (if (markdown-link-p) (browse-url (markdown-link-link))
4256 (error "Point is not at a Markdown link or URI")))
4259 ;;; WikiLink Following/Markup =================================================
4261 (defun markdown-wiki-link-p ()
4262 "Return non-nil when `point' is at a true wiki link.
4263 A true wiki link name matches `markdown-regex-wiki-link' but does not
4264 match the current file name after conversion. This modifies the data
4265 returned by `match-data'. Note that the potential wiki link name must
4266 be available via `match-string'."
4267 (let ((case-fold-search nil))
4268 (and (thing-at-point-looking-at markdown-regex-wiki-link)
4269 (or (not buffer-file-name)
4270 (not (string-equal (buffer-file-name)
4271 (markdown-convert-wiki-link-to-filename
4272 (markdown-wiki-link-link)))))
4273 (not (save-match-data
4274 (save-excursion))))))
4276 (defun markdown-wiki-link-link ()
4277 "Return the link part of the wiki link using current match data.
4278 The location of the link component depends on the value of
4279 `markdown-wiki-link-alias-first'."
4280 (if markdown-wiki-link-alias-first
4281 (or (match-string-no-properties 4) (match-string-no-properties 2))
4282 (match-string-no-properties 2)))
4284 (defun markdown-wiki-link-alias ()
4285 "Return the alias or text part of the wiki link using current match data.
4286 The location of the alias component depends on the value of
4287 `markdown-wiki-link-alias-first'."
4288 (if markdown-wiki-link-alias-first
4289 (match-string-no-properties 2)
4290 (or (match-string-no-properties 4) (match-string-no-properties 2))))
4292 (defun markdown-convert-wiki-link-to-filename (name)
4293 "Generate a filename from the wiki link NAME.
4294 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
4295 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
4296 and [[test test]] both map to Test-test.ext."
4297 (let ((basename (markdown-replace-regexp-in-string
4298 "[[:space:]\n]" markdown-link-space-sub-char name)))
4299 (when (eq major-mode 'gfm-mode)
4300 (setq basename (concat (upcase (substring basename 0 1))
4301 (downcase (substring basename 1 nil)))))
4302 (concat basename
4303 (if (buffer-file-name)
4304 (concat "."
4305 (file-name-extension (buffer-file-name)))))))
4307 (defun markdown-follow-wiki-link (name &optional other)
4308 "Follow the wiki link NAME.
4309 Convert the name to a file name and call `find-file'. Ensure that
4310 the new buffer remains in `markdown-mode'. Open the link in another
4311 window when OTHER is non-nil."
4312 (let ((filename (markdown-convert-wiki-link-to-filename name))
4313 (wp (file-name-directory buffer-file-name)))
4314 (when other (other-window 1))
4315 (find-file (concat wp filename)))
4316 (when (not (eq major-mode 'markdown-mode))
4317 (markdown-mode)))
4319 (defun markdown-follow-wiki-link-at-point (&optional arg)
4320 "Find Wiki Link at point.
4321 With prefix argument ARG, open the file in other window.
4322 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
4323 (interactive "P")
4324 (if (markdown-wiki-link-p)
4325 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
4326 (error "Point is not at a Wiki Link")))
4328 (defun markdown-highlight-wiki-link (from to face)
4329 "Highlight the wiki link in the region between FROM and TO using FACE."
4330 (put-text-property from to 'font-lock-face face))
4332 (defun markdown-unfontify-region-wiki-links (from to)
4333 "Remove wiki link faces from the region specified by FROM and TO."
4334 (interactive "nfrom: \nnto: ")
4335 (remove-text-properties from to '(font-lock-face markdown-link-face))
4336 (remove-text-properties from to '(font-lock-face markdown-missing-link-face)))
4338 (defun markdown-fontify-region-wiki-links (from to)
4339 "Search region given by FROM and TO for wiki links and fontify them.
4340 If a wiki link is found check to see if the backing file exists
4341 and highlight accordingly."
4342 (goto-char from)
4343 (save-match-data
4344 (while (re-search-forward markdown-regex-wiki-link to t)
4345 (let ((highlight-beginning (match-beginning 1))
4346 (highlight-end (match-end 1))
4347 (file-name
4348 (markdown-convert-wiki-link-to-filename
4349 (markdown-wiki-link-link))))
4350 (if (file-exists-p file-name)
4351 (markdown-highlight-wiki-link
4352 highlight-beginning highlight-end markdown-link-face)
4353 (markdown-highlight-wiki-link
4354 highlight-beginning highlight-end markdown-link-face)
4355 (markdown-highlight-wiki-link
4356 highlight-beginning highlight-end markdown-missing-link-face))))))
4358 (defun markdown-extend-changed-region (from to)
4359 "Extend region given by FROM and TO so that we can fontify all links.
4360 The region is extended to the first newline before and the first
4361 newline after."
4362 ;; start looking for the first new line before 'from
4363 (goto-char from)
4364 (re-search-backward "\n" nil t)
4365 (let ((new-from (point-min))
4366 (new-to (point-max)))
4367 (if (not (= (point) from))
4368 (setq new-from (point)))
4369 ;; do the same thing for the first new line after 'to
4370 (goto-char to)
4371 (re-search-forward "\n" nil t)
4372 (if (not (= (point) to))
4373 (setq new-to (point)))
4374 (values new-from new-to)))
4376 (defun markdown-check-change-for-wiki-link (from to change)
4377 "Check region between FROM and TO for wiki links and re-fontfy as needed.
4378 Designed to be used with the `after-change-functions' hook.
4379 CHANGE is the number of bytes of pre-change text replaced by the
4380 given range."
4381 (interactive "nfrom: \nnto: \nnchange: ")
4382 (let* ((modified (buffer-modified-p))
4383 (buffer-undo-list t)
4384 (inhibit-read-only t)
4385 (inhibit-point-motion-hooks t)
4386 deactivate-mark
4387 buffer-file-truename)
4388 (unwind-protect
4389 (save-excursion
4390 (save-match-data
4391 (save-restriction
4392 ;; Extend the region to fontify so that it starts
4393 ;; and ends at safe places.
4394 (multiple-value-bind (new-from new-to)
4395 (markdown-extend-changed-region from to)
4396 ;; Unfontify existing fontification (start from scratch)
4397 (markdown-unfontify-region-wiki-links new-from new-to)
4398 ;; Now do the fontification.
4399 (markdown-fontify-region-wiki-links new-from new-to)))))
4400 (and (not modified)
4401 (buffer-modified-p)
4402 (set-buffer-modified-p nil)))))
4404 (defun markdown-fontify-buffer-wiki-links ()
4405 "Refontify all wiki links in the buffer."
4406 (interactive)
4407 (markdown-check-change-for-wiki-link (point-min) (point-max) 0))
4410 ;;; Following and Jumping =====================================================
4412 (defun markdown-follow-thing-at-point (arg)
4413 "Follow thing at point if possible, such as a reference link or wiki link.
4414 Opens inline and reference links in a browser. Opens wiki links
4415 to other files in the current window, or the another window if
4416 ARG is non-nil.
4417 See `markdown-follow-link-at-point' and
4418 `markdown-follow-wiki-link-at-point'."
4419 (interactive "P")
4420 (cond ((markdown-link-p)
4421 (markdown-follow-link-at-point))
4422 ((markdown-wiki-link-p)
4423 (markdown-follow-wiki-link-at-point arg))
4425 (error "Nothing to follow at point"))))
4427 (defun markdown-jump ()
4428 "Jump to another location based on context at point.
4429 Jumps between reference links and definitions; between footnote
4430 markers and footnote text."
4431 (interactive)
4432 (cond ((markdown-footnote-text-positions)
4433 (markdown-footnote-return))
4434 ((markdown-footnote-marker-positions)
4435 (markdown-footnote-goto-text))
4436 ((thing-at-point-looking-at markdown-regex-link-reference)
4437 (markdown-reference-goto-definition))
4438 ((thing-at-point-looking-at markdown-regex-reference-definition)
4439 (markdown-reference-goto-link (match-string-no-properties 1)))
4441 (error "Nothing to jump to from context at point"))))
4444 ;;; Miscellaneous =============================================================
4446 (defun markdown-compress-whitespace-string (str)
4447 "Compress whitespace in STR and return result.
4448 Leading and trailing whitespace is removed. Sequences of multiple
4449 spaces, tabs, and newlines are replaced with single spaces."
4450 (replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
4451 (replace-regexp-in-string "[ \t\n]+" " " str)))
4453 (defun markdown-line-number-at-pos (&optional pos)
4454 "Return (narrowed) buffer line number at position POS.
4455 If POS is nil, use current buffer location.
4456 This is an exact copy of `line-number-at-pos' for use in emacs21."
4457 (let ((opoint (or pos (point))) start)
4458 (save-excursion
4459 (goto-char (point-min))
4460 (setq start (point))
4461 (goto-char opoint)
4462 (forward-line 0)
4463 (1+ (count-lines start (point))))))
4465 (defun markdown-nobreak-p ()
4466 "Return nil if it is acceptable to break the current line at the point."
4467 ;; inside in square brackets (e.g., link anchor text)
4468 (looking-back "\\[[^]]*"))
4470 (defun markdown-adaptive-fill-function ()
4471 "Return prefix for filling paragraph or nil if not determined."
4472 (cond
4473 ;; List item inside blockquote
4474 ((looking-at "^[ \t]*>[ \t]*\\([0-9]+\\.\\|[*+-]\\)[ \t]+")
4475 (replace-regexp-in-string
4476 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
4477 ;; Blockquote
4478 ((looking-at "^[ \t]*>[ \t]*")
4479 (match-string-no-properties 0))
4480 ;; List items
4481 ((looking-at markdown-regex-list)
4482 (match-string-no-properties 0))
4483 ;; No match
4484 (t nil)))
4487 ;;; Extensions ================================================================
4489 (defun markdown-reload-extensions ()
4490 "Check settings, update font-lock keywords, and re-fontify buffer."
4491 (interactive)
4492 (when (eq major-mode 'markdown-mode)
4493 (setq markdown-mode-font-lock-keywords
4494 (append
4495 (when markdown-enable-math
4496 markdown-mode-font-lock-keywords-math)
4497 markdown-mode-font-lock-keywords-basic
4498 markdown-mode-font-lock-keywords-core))
4499 (setq font-lock-defaults '(markdown-mode-font-lock-keywords))
4500 (font-lock-refresh-defaults)))
4502 (defun markdown-enable-math (&optional arg)
4503 "Toggle support for inline and display LaTeX math expressions.
4504 With a prefix argument ARG, enable math mode if ARG is positive,
4505 and disable it otherwise. If called from Lisp, enable the mode
4506 if ARG is omitted or nil."
4507 (interactive (list (or current-prefix-arg 'toggle)))
4508 (setq markdown-enable-math
4509 (if (eq arg 'toggle)
4510 (not markdown-enable-math)
4511 (> (prefix-numeric-value arg) 0)))
4512 (if markdown-enable-math
4513 (message "markdown-mode math support enabled")
4514 (message "markdown-mode math support disabled"))
4515 (markdown-reload-extensions))
4518 ;;; Mode Definition ==========================================================
4520 (defun markdown-show-version ()
4521 "Show the version number in the minibuffer."
4522 (interactive)
4523 (message "markdown-mode, version %s" markdown-mode-version))
4525 ;;;###autoload
4526 (define-derived-mode markdown-mode text-mode "Markdown"
4527 "Major mode for editing Markdown files."
4528 ;; Natural Markdown tab width
4529 (setq tab-width 4)
4530 ;; Comments
4531 (make-local-variable 'comment-start)
4532 (setq comment-start "<!-- ")
4533 (make-local-variable 'comment-end)
4534 (setq comment-end " -->")
4535 (make-local-variable 'comment-start-skip)
4536 (setq comment-start-skip "<!--[ \t]*")
4537 (make-local-variable 'comment-column)
4538 (setq comment-column 0)
4539 ;; Font lock.
4540 (set (make-local-variable 'markdown-mode-font-lock-keywords) nil)
4541 (set (make-local-variable 'font-lock-defaults) nil)
4542 (set (make-local-variable 'font-lock-multiline) t)
4543 (markdown-reload-extensions)
4544 ;; Extensions
4545 (make-local-variable 'markdown-enable-math)
4546 (add-hook 'hack-local-variables-hook 'markdown-reload-extensions)
4547 ;; For imenu support
4548 (setq imenu-create-index-function 'markdown-imenu-create-index)
4549 ;; For menu support in XEmacs
4550 (easy-menu-add markdown-mode-menu markdown-mode-map)
4551 ;; Defun movement
4552 (set (make-local-variable 'beginning-of-defun-function)
4553 'markdown-beginning-of-defun)
4554 (set (make-local-variable 'end-of-defun-function)
4555 'markdown-end-of-defun)
4556 ;; Paragraph filling
4557 (set (make-local-variable 'paragraph-start)
4558 "\f\\|[ \t]*$\\|[ \t]*[*+-] \\|[ \t]*[0-9]+\\.\\|[ \t]*: ")
4559 (set (make-local-variable 'paragraph-separate)
4560 "\\(?:[ \t\f]\\|.* \\)*$")
4561 (set (make-local-variable 'adaptive-fill-first-line-regexp)
4562 "\\`[ \t]*>[ \t]*?\\'")
4563 (set (make-local-variable 'adaptive-fill-function)
4564 'markdown-adaptive-fill-function)
4565 ;; Outline mode
4566 (make-local-variable 'outline-regexp)
4567 (setq outline-regexp markdown-regex-header)
4568 (make-local-variable 'outline-level)
4569 (setq outline-level 'markdown-outline-level)
4570 ;; Cause use of ellipses for invisible text.
4571 (add-to-invisibility-spec '(outline . t))
4572 ;; Indentation and filling
4573 (make-local-variable 'fill-nobreak-predicate)
4574 (add-hook 'fill-nobreak-predicate 'markdown-nobreak-p)
4575 (setq indent-line-function markdown-indent-function)
4577 ;; Prepare hooks for XEmacs compatibility
4578 (when (featurep 'xemacs)
4579 (make-local-hook 'after-change-functions)
4580 (make-local-hook 'font-lock-extend-region-functions)
4581 (make-local-hook 'window-configuration-change-hook))
4583 ;; Multiline font lock
4584 (add-hook 'font-lock-extend-region-functions
4585 'markdown-font-lock-extend-region)
4587 ;; Anytime text changes make sure it gets fontified correctly
4588 (add-hook 'after-change-functions 'markdown-check-change-for-wiki-link t t)
4590 ;; If we left the buffer there is a really good chance we were
4591 ;; creating one of the wiki link documents. Make sure we get
4592 ;; refontified when we come back.
4593 (add-hook 'window-configuration-change-hook
4594 'markdown-fontify-buffer-wiki-links t t)
4596 ;; do the initial link fontification
4597 (markdown-fontify-buffer-wiki-links))
4599 ;;(add-to-list 'auto-mode-alist '("\\.text$" . markdown-mode))
4602 ;;; GitHub Flavored Markdown Mode ============================================
4604 (defvar gfm-font-lock-keywords
4605 (append
4606 ;; GFM features to match first
4607 (list
4608 (cons 'markdown-match-gfm-code-blocks '((1 markdown-pre-face)
4609 (2 markdown-language-keyword-face)
4610 (3 markdown-pre-face)
4611 (4 markdown-pre-face))))
4612 ;; Basic Markdown features (excluding possibly overridden ones)
4613 markdown-mode-font-lock-keywords-basic
4614 ;; GFM features to match last
4615 (list
4616 (cons markdown-regex-gfm-italic '(2 markdown-italic-face))))
4617 "Default highlighting expressions for GitHub-flavored Markdown mode.")
4619 ;;;###autoload
4620 (define-derived-mode gfm-mode markdown-mode "GFM"
4621 "Major mode for editing GitHub Flavored Markdown files."
4622 (setq markdown-link-space-sub-char "-")
4623 (set (make-local-variable 'font-lock-defaults)
4624 '(gfm-font-lock-keywords))
4625 (auto-fill-mode 0)
4626 ;; Use visual-line-mode if available, fall back to longlines-mode:
4627 (if (fboundp 'visual-line-mode)
4628 (visual-line-mode 1)
4629 (longlines-mode 1))
4630 ;; do the initial link fontification
4631 (markdown-fontify-buffer-wiki-links))
4634 (provide 'markdown-mode)
4636 ;;; markdown-mode.el ends here