Automatic header insertion
[markdown-mode.git] / markdown-mode.el
bloba1a651b2982523887b6d5876b921a0cac4e4d620
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 ;;; Dependencies:
101 ;; markdown-mode requires easymenu, a standard package since GNU Emacs
102 ;; 19 and XEmacs 19, which provides a uniform interface for creating
103 ;; menus in GNU Emacs and XEmacs.
105 ;;; Installation:
107 ;; Make sure to place `markdown-mode.el` somewhere in the load-path and add
108 ;; the following lines to your `.emacs` file to associate markdown-mode
109 ;; with `.text` files:
111 ;; (autoload 'markdown-mode "markdown-mode"
112 ;; "Major mode for editing Markdown files" t)
113 ;; (add-to-list 'auto-mode-alist '("\\.text\\'" . markdown-mode))
115 ;; There is no consensus on an official file extension so change `.text` to
116 ;; `.mdwn`, `.md`, `.mdt`, or whatever you call your markdown files.
118 ;;; Customization:
120 ;; Although no configuration is *necessary* there are a few things
121 ;; that can be customized. The `M-x customize-mode` command
122 ;; provides an interface to all of the possible customizations:
124 ;; * `markdown-command' - the command used to run Markdown (default:
125 ;; `markdown'). This variable may be customized to pass
126 ;; command-line options to your Markdown processor of choice, but
127 ;; this command must accept input from `stdin`. If it does not, a
128 ;; simple wrapper script can be used to write `stdin` to a file
129 ;; and then pass that file to your Markdown interpreter. Ideally,
130 ;; this command will produce an XHTML fragment around which
131 ;; markdown-mode will wrap a header and footer (which can be
132 ;; further customized). However, it attempts to detect whether
133 ;; the command produces standalone XHTML output (via
134 ;; `markdown-xhtml-standalone-regexp'), in which case no header
135 ;; and footer content will be added.
137 ;; * `markdown-command-needs-filename' - set to non-nil if
138 ;; `markdown-command' does not accept input from stdin (default: nil).
139 ;; Instead, it will be passed a filename as the final command-line
140 ;; option. As a result, you will only be able to run Markdown
141 ;; from buffers which are visiting a file.
143 ;; * `markdown-open-command' - the command used for calling a standalone
144 ;; Markdown previewer which is capable of opening Markdown source files
145 ;; directly (default: `nil'). This command will be called
146 ;; with a single argument, the filename of the current buffer.
147 ;; A representative program is the Mac app [Marked][], a
148 ;; live-updating MultiMarkdown previewer which has a command line
149 ;; utility at `/usr/local/bin/mark`.
151 ;; * `markdown-hr-strings' - list of strings to use when inserting
152 ;; horizontal rules, in decreasing order of priority.
154 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
155 ;; underscores for bold instead of two asterisks (default: `nil').
157 ;; * `markdown-italic-underscore' - set to a non-nil value to use
158 ;; underscores for italic instead of asterisks (default: `nil').
160 ;; * `markdown-indent-function' - the function to use for automatic
161 ;; indentation (default: `markdown-indent-line').
163 ;; * `markdown-indent-on-enter' - set to a non-nil value to
164 ;; automatically indent new lines when the enter key is pressed
165 ;; (default: `t')
167 ;; * `markdown-follow-wiki-link-on-enter' - set to a non-nil value
168 ;; to automatically open a linked document in a new buffer if the
169 ;; cursor is an wiki link
170 ;; (default: `t')
172 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
173 ;; treat aliased wiki links like `[[link text|PageName]]`.
174 ;; When set to nil, they will be treated as `[[PageName|link text]]'.
176 ;; * `markdown-uri-types' - a list of protocols for URIs that
177 ;; `markdown-mode' should highlight.
179 ;; * `markdown-enable-math' - syntax highlighting for
180 ;; LaTeX fragments (default: `nil').
182 ;; * `markdown-css-path' - CSS file to link to in XHTML output.
184 ;; * `markdown-content-type' - when set to a nonempty string, an
185 ;; `http-equiv` attribute will be included in the XHTML `<head>`
186 ;; block. If needed, the suggested values are
187 ;; `application/xhtml+xml` or `text/html`.
189 ;; * `markdown-coding-system' - used for specifying the character
190 ;; set identifier in the `http-equiv` attribute (see
191 ;; `markdown-content-type'). When set to `nil',
192 ;; `buffer-file-coding-system' will be used (and falling back to
193 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
194 ;; and `iso-latin-1'.
196 ;; * `markdown-xhtml-header-content' - additional content to include
197 ;; in the XHTML `<head>` block.
199 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
200 ;; indicates whether the output of `markdown-command' is standalone
201 ;; XHTML (default: `^\\(\<\?xml\\|\<!DOCTYPE\\|\<html\\)`). If
202 ;; this is not matched, we assume this output is a fragment and add
203 ;; our own header and footer.
205 ;; * `markdown-link-space-sub-char' - a character to replace spaces
206 ;; when mapping wiki links to filenames (default: `_`).
207 ;; For example, use an underscore for compatibility with the
208 ;; Python Markdown WikiLinks extension or a hyphen for compatibility
209 ;; with Github wiki links.
211 ;; Additionally, the faces used for syntax highlighting can be modified to
212 ;; your liking by issuing `M-x customize-group RET markdown-faces`
213 ;; or by using the "Markdown Faces" link at the bottom of the mode
214 ;; customization screen.
216 ;; [Marked]: https://itunes.apple.com/us/app/marked/id448925439?ls=1&mt=12&partnerId=30&siteID=GpHp3Acs1Yo
218 ;;; Usage:
220 ;; Keybindings are grouped by prefixes based on their function. For
221 ;; example, commands dealing with headers begin with `C-c C-t`. The
222 ;; primary commands in each group will are described below. You can
223 ;; obtain a list of all keybindings by pressing `C-c C-h`.
225 ;; * Anchors: `C-c C-a`
227 ;; `C-c C-a l` inserts inline links of the form `[text](url)`.
228 ;; `C-c C-a r` inserts reference links of the form `[text][label]`.
229 ;; The label definition will be placed at the end of the current
230 ;; block. `C-c C-a w` acts similarly for wiki links of the form
231 ;; `[[WikiLink]]`. In all cases, if there is an active region, the
232 ;; text in the region is used as the link text.
234 ;; * Commands: `C-c C-c`
236 ;; *Compile:* `C-c C-c m` will run Markdown on the current buffer
237 ;; and show the output in another buffer. *Preview*: `C-c C-c p`
238 ;; runs Markdown on the current buffer and previews, stores the
239 ;; output in a temporary file, and displays the file in a browser.
240 ;; *Export:* `C-c C-c e` will run Markdown on the current buffer
241 ;; and save the result in the file `basename.html`, where
242 ;; `basename` is the name of the Markdown file with the extension
243 ;; removed. *Export and View:* press `C-c C-c v` to export the
244 ;; file and view it in a browser. **For both export commands, the
245 ;; output file will be overwritten without notice.**
246 ;; *Open:* `C-c C-c o` will open the Markdown source file directly
247 ;; using `markdown-open-command'.
249 ;; To summarize:
251 ;; - `C-c C-c m`: `markdown-command' > `*markdown-output*` buffer.
252 ;; - `C-c C-c p`: `markdown-command' > temporary file > browser.
253 ;; - `C-c C-c e`: `markdown-command' > `basename.html`.
254 ;; - `C-c C-c v`: `markdown-command' > `basename.html` > browser.
255 ;; - `C-c C-c w`: `markdown-command' > kill ring.
256 ;; - `C-c C-c o`: `markdown-open-command'.
258 ;; `C-c C-c c` will check for undefined references. If there are
259 ;; any, a small buffer will open with a list of undefined
260 ;; references and the line numbers on which they appear. In Emacs
261 ;; 22 and greater, selecting a reference from this list and
262 ;; pressing `RET` will insert an empty reference definition at the
263 ;; end of the buffer. Similarly, selecting the line number will
264 ;; jump to the corresponding line.
266 ;; `C-c C-c n` will clean up the numbering of ordered lists.
268 ;; * Images: `C-c C-i`
270 ;; `C-c C-i i` inserts an image, using the active region (if any)
271 ;; as the alt text.
273 ;; * Physical styles: `C-c C-p`
275 ;; These commands all act on text in the active region, if any,
276 ;; and insert empty markup fragments otherwise. `C-c C-p b` makes
277 ;; the selected text bold, `C-c C-p f` formats the region as
278 ;; fixed-width text, and `C-c C-p i` is used for italic text.
280 ;; * Logical styles: `C-c C-s`
282 ;; These commands all act on text in the active region, if any,
283 ;; and insert empty markup fragments otherwise. Logical styles
284 ;; include blockquote (`C-c C-s b`), preformatted (`C-c C-s p`),
285 ;; code (`C-c C-s c`), emphasis (`C-c C-s e`), and strong
286 ;; (`C-c C-s s`).
288 ;; * Headers: `C-c C-t`
290 ;; All header commands use text in the active region, if any, as
291 ;; the header text. Otherwise, if the current line is not blank,
292 ;; use the text on the current line. Finally, prompt for header
293 ;; text if there is no active region and the current line is
294 ;; blank. To insert an atx or hash style level-n
295 ;; header, press `C-c C-t n` where n is between 1 and 6. For a
296 ;; top-level setext or underline style header press `C-c C-t t`
297 ;; (mnemonic: title) and for a second-level underline-style header
298 ;; press `C-c C-t s` (mnemonic: section).
300 ;; If the point is at a header, these commands will replace the
301 ;; existing markup in order to update the level and/or type of the
302 ;; header. To remove the markup of the header at the point, press
303 ;; `C-c C-t 0`.
305 ;; * Footnotes: `C-c C-f`
307 ;; To create a new footnote at the point, press `C-c C-f n`.
308 ;; Press `C-c C-f g` with the point at a footnote to jump to the
309 ;; location where the footnote text is defined. Then, press
310 ;; `C-c C-f b` to return to the footnote marker in the main text.
311 ;; When the point is at a footnote marker or in the body of a
312 ;; footnote, press `C-c C-f k` to kill the footnote and add the
313 ;; text to the kill ring.
315 ;; * Other elements:
317 ;; `C-c -` inserts a horizontal rule.
319 ;; * Links:
321 ;; Press `C-c C-o` when the point is on an inline or reference
322 ;; link to open the URL in a browser.
324 ;; * Wiki-Link Navigation:
326 ;; Use `M-p` and `M-n` to quickly jump to the previous and next
327 ;; wiki links, respectively.
329 ;; * Outline Navigation:
331 ;; Navigation between headings is possible using `outline-mode'.
332 ;; Use `C-M-n` and `C-M-p` to move between the next and previous
333 ;; visible headings. Similarly, `C-M-f` and `C-M-b` move to the
334 ;; next and previous visible headings at the same level as the one
335 ;; at the point. Finally, `C-M-u` will move up to a lower-level
336 ;; (more inclusive) visible heading.
338 ;; * Movement by Block:
340 ;; markdown-mode supports the usual Emacs paragraph movement with
341 ;; `M-{` and `M-}`. These commands treat list items as
342 ;; paragraphs, so they will stop at each line within a block of
343 ;; list items. Additionally, markdown-mode includes movement
344 ;; commands, `M-[` and `M-]` for jumping to the beginning or end
345 ;; of an entire block of text (with blocks being separated by at
346 ;; least one blank line).
348 ;; * Movement by Defun:
350 ;; The usual Emacs commands can be used to move by defuns
351 ;; (top-level major definitions). In markdown-mode, a defun
352 ;; is a section. As usual, `C-M-a` will move the point to
353 ;; the beginning of the current or preceding defun, `C-M-e`
354 ;; will move to the end of the current or following defun,
355 ;; and `C-M-h` will put the region around the entire defun.
357 ;; Many of the commands described above behave differently depending on
358 ;; whether Transient Mark mode is enabled or not. When it makes sense,
359 ;; if Transient Mark mode is on and a region is active, the command
360 ;; applies to the text in the region (e.g., `C-c C-p b` makes the region
361 ;; bold). For users who prefer to work outside of Transient Mark mode,
362 ;; in Emacs 22 it can be enabled temporarily by pressing `C-SPC C-SPC`.
364 ;; When applicable, commands that specifically act on the region even
365 ;; outside of Transient Mark mode have the same keybinding as the with
366 ;; the exception of an additional `C-` prefix. For example,
367 ;; `markdown-insert-blockquote' is bound to `C-c C-s b` and only acts on
368 ;; the region in Transient Mark mode while `markdown-blockquote-region'
369 ;; is bound to `C-c C-s C-b` and always applies to the region (when
370 ;; nonempty).
372 ;; markdown-mode attempts to be flexible in how it handles
373 ;; indentation. When you press `TAB` repeatedly, the point will cycle
374 ;; through several possible indentation levels corresponding to things
375 ;; you might have in mind when you press `RET` at the end of a line or
376 ;; `TAB`. For example, you may want to start a new list item,
377 ;; continue a list item with hanging indentation, indent for a nested
378 ;; pre block, and so on.
380 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
381 ;; visibility cycling for atx- or hash-style headers. There are two
382 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
383 ;; the table of contents view (headers only), outline view (top-level
384 ;; headers only), and the full document view. Pressing `TAB` while the
385 ;; point is at a header will cycle through levels of visibility for the
386 ;; subtree: completely folded, visible children, and fully visible.
387 ;; Note that mixing hash and underline style headers will give undesired
388 ;; results.
390 ;;; Extensions:
392 ;; Besides supporting the basic Markdown syntax, markdown-mode also
393 ;; includes syntax highlighting for `[[Wiki Links]]` by default. Wiki
394 ;; links may be followed automatically by hitting the enter key when
395 ;; your curser is on a wiki link or by hitting `C-c C-w`. The
396 ;; autofollowing on enter key may be controlled with the
397 ;; `markdown-follow-wiki-link-on-enter' customization. Use `M-p` and
398 ;; `M-n` to quickly jump to the previous and next wiki links,
399 ;; respectively. Aliased or piped wiki links of the form
400 ;; `[[link text|PageName]]` are also supported. Since some wikis
401 ;; reverse these components, set `markdown-wiki-link-alias-first'
402 ;; to nil to treat them as `[[PageName|link text]]`.
404 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
405 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
406 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
407 ;; You can do this either by using `M-x customize-group markdown`
408 ;; or by placing the following in your `.emacs` file:
410 ;; (defun markdown-custom ()
411 ;; "markdown-mode-hook"
412 ;; (setq markdown-command "markdown | smartypants"))
413 ;; (add-hook 'markdown-mode-hook '(lambda() (markdown-custom)))
415 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
417 ;; Experimental syntax highlighting for mathematical expressions written
418 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
419 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
420 ;; either via customize or by placing `(setq markdown-enable-itex t)`
421 ;; in `.emacs`, and restarting Emacs.
423 ;; A [GitHub Flavored Markdown](http://github.github.com/github-flavored-markdown/)
424 ;; mode, `gfm-mode', is also available. The GitHub implementation of
425 ;; differs slightly from standard Markdown. Most importantly, newlines are
426 ;; significant and trigger hard line breaks. As such, `gfm-mode' turns off
427 ;; `auto-fill-mode' and turns on `visual-line-mode' (or `longlines-mode' if
428 ;; `visual-line-mode' is not available). Wiki links in this mode will be
429 ;; treated as on GitHub, with hyphens replacing spaces in filenames and
430 ;; where the first letter of the filename capitalized. For example,
431 ;; `[[wiki link]]' will map to a file named `Wiki-link` with the same
432 ;; extension as the current file. GFM code blocks, with optional
433 ;; programming language keywords, will be highlighted. They can be inserted
434 ;; with `C-c C-s l`. If there is an active region, the text in the region
435 ;; will be placed inside the code block. You will be prompted for the name
436 ;; of the language, but may press enter to continue without naming a language.
438 ;;; Acknowledgments:
440 ;; markdown-mode has benefited greatly from the efforts of the
441 ;; following people:
443 ;; * Cyril Brulebois <cyril.brulebois@enst-bretagne.fr> for Debian packaging.
444 ;; * Conal Elliott <conal@conal.net> for a font-lock regexp patch.
445 ;; * Edward O'Connor <hober0@gmail.com> for a font-lock regexp fix and
446 ;; GitHub Flavored Markdown mode (`gfm-mode').
447 ;; * Greg Bognar <greg_bognar@hms.harvard.edu> for menus and running
448 ;; `markdown' with an active region.
449 ;; * Daniel Burrows <dburrows@debian.org> for filing Debian bug #456592.
450 ;; * Peter S. Galbraith <psg@debian.org> for maintaining emacs-goodies-el.
451 ;; * Dmitry Dzhus <mail@sphinx.net.ru> for undefined reference checking.
452 ;; * Carsten Dominik <carsten@orgmode.org> for org-mode, from which the
453 ;; visibility cycling functionality was derived, and for a bug fix
454 ;; related to orgtbl-mode.
455 ;; * Bryan Kyle <bryan.kyle@gmail.com> for indentation code.
456 ;; * Ben Voui <intrigeri@boum.org> for font-lock face customizations.
457 ;; * Ankit Solanki <ankit.solanki@gmail.com> for longlines.el
458 ;; compatibility and custom CSS.
459 ;; * Hilko Bengen <bengen@debian.org> for proper XHTML output.
460 ;; * Jose A. Ortega Ruiz <jao@gnu.org> for Emacs 23 fixes.
461 ;; * Nelson Minar <nelson@santafe.edu> for html-helper-mode, from which
462 ;; comment matching functions were derived.
463 ;; * Alec Resnick <alec@sproutward.org> for bug reports.
464 ;; * Joost Kremers <joostkremers@fastmail.fm> for footnote-handling
465 ;; functions, bug reports regarding indentation, and
466 ;; fixes for byte-compilation warnings.
467 ;; * Peter Williams <pezra@barelyenough.org> for fill-paragraph
468 ;; enhancements.
469 ;; * George Ogata <george.ogata@gmail.com> for fixing several
470 ;; byte-compilation warnings.
471 ;; * Eric Merritt <ericbmerritt@gmail.com> for wiki link features.
472 ;; * Philippe Ivaldi <pivaldi@sfr.fr> for XHTML preview
473 ;; customizations and XHTML export.
474 ;; * Jeremiah Dodds <jeremiah.dodds@gmail.com> for supporting
475 ;; Markdown processors which do not accept input from stdin.
476 ;; * Werner Dittmann <werner.dittmann@t-online.de> for bug reports
477 ;; regarding the cl dependency and auto-fill-mode and indentation.
478 ;; * Scott Pfister <scott.pfister@gmail.com> for generalizing the space
479 ;; substitution character for mapping wiki links to filenames.
480 ;; * Marcin Kasperski <marcin.kasperski@mekk.waw.pl> for a patch to
481 ;; escape shell commands.
482 ;; * Christopher J. Madsen <cjm@cjmweb.net> for patches to fix a match
483 ;; data bug and to prefer `visual-line-mode' in `gfm-mode'.
484 ;; * Shigeru Fukaya <shigeru.fukaya@gmail.com> for better adherence to
485 ;; Emacs Lisp coding conventions.
486 ;; * Donald Ephraim Curtis <dcurtis@milkbox.net> for fixing the `paragraph-fill'
487 ;; regexp, refactoring the compilation and preview functions,
488 ;; heading font-lock generalizations, list renumbering,
489 ;; and kill ring save.
490 ;; * Kevin Porter <kportertx@gmail.com> for wiki link handling in `gfm-mode'.
491 ;; * Max Penet <max.penet@gmail.com> and Peter Eisentraut <peter_e@gmx.net>
492 ;; for an autoload token for `gfm-mode'.
493 ;; * Ian Yang <me@iany.me> for improving the reference definition regex.
494 ;; * Akinori Musha <knu@idaemons.org> for an imenu index function.
495 ;; * Michael Sperber <sperber@deinprogramm.de> for XEmacs fixes.
496 ;; * Francois Gannaz <francois.gannaz@free.fr> for suggesting charset
497 ;; declaration in XHTML output.
498 ;; * Zhenlei Jia <zhenlei.jia@gmail.com> for smart (dedention)
499 ;; un-indentation function.
500 ;; * Matus Goljer <dota.keys@gmail.com> for improved wiki link following
501 ;; and GFM code block insertion.
502 ;; * Peter Jones <pjones@pmade.com> for link following functions.
503 ;; * Bryan Fink <bryan.fink@gmail.com> for a bug report regarding
504 ;; externally modified files.
505 ;; * Vegard Vesterheim <vegard.vesterheim@uninett.no> for a bug fix
506 ;; related to orgtbl-mode.
507 ;; * Makoto Motohashi <mkt.motohashi@gmail.com> for before- and after-
508 ;; export hooks and unit test improvements.
510 ;;; Bugs:
512 ;; Although markdown-mode is developed and tested primarily using
513 ;; GNU Emacs 24, compatibility with earlier Emacsen is also a
514 ;; priority.
516 ;; If you find any bugs in markdown-mode, please construct a test case
517 ;; or a patch and email me at <jrblevin@sdf.org>.
519 ;;; History:
521 ;; markdown-mode was written and is maintained by Jason Blevins. The
522 ;; first version was released on May 24, 2007.
524 ;; * 2007-05-24: Version 1.1
525 ;; * 2007-05-25: Version 1.2
526 ;; * 2007-06-05: [Version 1.3][]
527 ;; * 2007-06-29: Version 1.4
528 ;; * 2008-05-24: [Version 1.5][]
529 ;; * 2008-06-04: [Version 1.6][]
530 ;; * 2009-10-01: [Version 1.7][]
531 ;; * 2011-08-12: [Version 1.8][]
532 ;; * 2011-08-15: [Version 1.8.1][]
533 ;; * 2013-01-25: [Version 1.9][]
535 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
536 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
537 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
538 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
539 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
540 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
541 ;; [Version 1.9]: http://jblevins.org/projects/markdown-mode/rev-1-9
544 ;;; Code:
546 (require 'easymenu)
547 (require 'outline)
548 (eval-when-compile (require 'cl))
551 ;;; Constants =================================================================
553 (defconst markdown-mode-version "1.9"
554 "Markdown mode version number.")
556 (defconst markdown-output-buffer-name "*markdown-output*"
557 "Name of temporary buffer for markdown command output.")
560 ;;; Customizable Variables ====================================================
562 (defvar markdown-mode-hook nil
563 "Hook run when entering Markdown mode.")
565 (defvar markdown-before-export-hooks nil
566 "Hook run before output XHTML.
567 This hook is abnormal and registered functions are given an argument that is output filename.")
569 (defvar markdown-after-export-hooks nil
570 "Hook run after output XHTML.
571 This hook is abnormal and registered functions are given an argument that is output filename.")
573 (defgroup markdown nil
574 "Major mode for editing text files in Markdown format."
575 :prefix "markdown-"
576 :group 'wp
577 :link '(url-link "http://jblevins.org/projects/markdown-mode/"))
579 (defcustom markdown-command "markdown"
580 "Command to run markdown."
581 :group 'markdown
582 :type 'string)
584 (defcustom markdown-command-needs-filename nil
585 "Set to non-nil if `markdown-command' does not accept input from stdin.
586 Instead, it will be passed a filename as the final command line
587 option. As a result, you will only be able to run Markdown from
588 buffers which are visiting a file."
589 :group 'markdown
590 :type 'boolean)
592 (defcustom markdown-open-command nil
593 "Command used for opening Markdown files directly.
594 For example, a standalone Markdown previewer. This command will
595 be called with a single argument: the filename of the current
596 buffer."
597 :group 'markdown
598 :type 'string)
600 (defcustom markdown-hr-strings
601 '("* * * * *"
602 "---------"
603 "* * * * * * * * * * * * * * * * * * * *"
604 "---------------------------------------"
605 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
606 "-------------------------------------------------------------------------------")
607 "Strings to use when inserting horizontal rules.
608 The first string in the list will be the default when inserting a
609 horizontal rule. Strings should be listed in increasing order of
610 prominence for use with promotion and demotion functions."
611 :group 'markdown
612 :type 'list)
614 (defcustom markdown-bold-underscore nil
615 "Use two underscores for bold instead of two asterisks."
616 :group 'markdown
617 :type 'boolean)
619 (defcustom markdown-italic-underscore nil
620 "Use underscores for italic instead of asterisks."
621 :group 'markdown
622 :type 'boolean)
624 (defcustom markdown-indent-function 'markdown-indent-line
625 "Function to use to indent."
626 :group 'markdown
627 :type 'function)
629 (defcustom markdown-indent-on-enter t
630 "Automatically indent new lines when enter key is pressed."
631 :group 'markdown
632 :type 'boolean)
634 (defcustom markdown-follow-wiki-link-on-enter t
635 "Follow wiki link at point (if any) when the enter key is pressed."
636 :group 'markdown
637 :type 'boolean)
639 (defcustom markdown-wiki-link-alias-first t
640 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
641 Otherwise, they will be treated as [[PageName|alias text]]."
642 :group 'markdown
643 :type 'boolean)
645 (defcustom markdown-uri-types
646 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
647 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
648 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
649 "Link types for syntax highlighting of URIs."
650 :group 'markdown
651 :type 'list)
653 (defcustom markdown-enable-math nil
654 "Syntax highlighting for inline LaTeX expressions.
655 This will not take effect until Emacs is restarted."
656 :group 'markdown
657 :type 'boolean)
659 (defcustom markdown-css-path ""
660 "URL of CSS file to link to in the output XHTML."
661 :group 'markdown
662 :type 'string)
664 (defcustom markdown-content-type ""
665 "Content type string for the http-equiv header in XHTML output.
666 When set to a non-empty string, insert the http-equiv attribute.
667 Otherwise, this attribute is omitted."
668 :group 'markdown
669 :type 'string)
671 (defcustom markdown-coding-system nil
672 "Character set string for the http-equiv header in XHTML output.
673 Defaults to `buffer-file-coding-system' (and falling back to
674 `iso-8859-1' when not available). Common settings are `utf-8'
675 and `iso-latin-1'. Use `list-coding-systems' for more choices."
676 :group 'markdown
677 :type 'coding-system)
679 (defcustom markdown-xhtml-header-content ""
680 "Additional content to include in the XHTML <head> block."
681 :group 'markdown
682 :type 'string)
684 (defcustom markdown-xhtml-standalone-regexp
685 "^\\(\<\?xml\\|\<!DOCTYPE\\|\<html\\)"
686 "Regexp indicating whether `markdown-command' output is standalone XHTML."
687 :group 'markdown
688 :type 'regexp)
690 (defcustom markdown-link-space-sub-char
692 "Character to use instead of spaces when mapping wiki links to filenames."
693 :group 'markdown
694 :type 'string)
696 (defcustom markdown-footnote-location 'end
697 "Position where new footnotes are inserted in the document."
698 :group 'markdown
699 :type '(choice (const :tag "At the end of the document" end)
700 (const :tag "Immediately after the paragraph" immediately)
701 (const :tag "Before next header" header)))
704 ;;; Font Lock =================================================================
706 (require 'font-lock)
708 (defvar markdown-italic-face 'markdown-italic-face
709 "Face name to use for italic text.")
711 (defvar markdown-bold-face 'markdown-bold-face
712 "Face name to use for bold text.")
714 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
715 "Face name to use as a base for header delimiters.")
717 (defvar markdown-header-rule-face 'markdown-header-rule-face
718 "Face name to use as a base for header rules.")
720 (defvar markdown-header-face 'markdown-header-face
721 "Face name to use as a base for headers.")
723 (defvar markdown-header-face-1 'markdown-header-face-1
724 "Face name to use for level-1 headers.")
726 (defvar markdown-header-face-2 'markdown-header-face-2
727 "Face name to use for level-2 headers.")
729 (defvar markdown-header-face-3 'markdown-header-face-3
730 "Face name to use for level-3 headers.")
732 (defvar markdown-header-face-4 'markdown-header-face-4
733 "Face name to use for level-4 headers.")
735 (defvar markdown-header-face-5 'markdown-header-face-5
736 "Face name to use for level-5 headers.")
738 (defvar markdown-header-face-6 'markdown-header-face-6
739 "Face name to use for level-6 headers.")
741 (defvar markdown-inline-code-face 'markdown-inline-code-face
742 "Face name to use for inline code.")
744 (defvar markdown-list-face 'markdown-list-face
745 "Face name to use for list markers.")
747 (defvar markdown-blockquote-face 'markdown-blockquote-face
748 "Face name to use for blockquote.")
750 (defvar markdown-pre-face 'markdown-pre-face
751 "Face name to use for preformatted text.")
753 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
754 "Face name to use for programming language identifiers.")
756 (defvar markdown-link-face 'markdown-link-face
757 "Face name to use for links.")
759 (defvar markdown-missing-link-face 'markdown-missing-link-face
760 "Face name to use for links where the linked file does not exist.")
762 (defvar markdown-reference-face 'markdown-reference-face
763 "Face name to use for reference.")
765 (defvar markdown-footnote-face 'markdown-footnote-face
766 "Face name to use for footnote identifiers.")
768 (defvar markdown-url-face 'markdown-url-face
769 "Face name to use for URLs.")
771 (defvar markdown-link-title-face 'markdown-link-title-face
772 "Face name to use for reference link titles.")
774 (defvar markdown-comment-face 'markdown-comment-face
775 "Face name to use for HTML comments.")
777 (defvar markdown-math-face 'markdown-math-face
778 "Face name to use for LaTeX expressions.")
780 (defgroup markdown-faces nil
781 "Faces used in Markdown Mode"
782 :group 'markdown
783 :group 'faces)
785 (defface markdown-italic-face
786 '((t (:inherit font-lock-variable-name-face :slant italic)))
787 "Face for italic text."
788 :group 'markdown-faces)
790 (defface markdown-bold-face
791 '((t (:inherit font-lock-variable-name-face :weight bold)))
792 "Face for bold text."
793 :group 'markdown-faces)
795 (defface markdown-header-rule-face
796 '((t (:inherit font-lock-function-name-face :weight bold)))
797 "Base face for headers rules."
798 :group 'markdown-faces)
800 (defface markdown-header-delimiter-face
801 '((t (:inherit font-lock-function-name-face :weight bold)))
802 "Base face for headers hash delimiter."
803 :group 'markdown-faces)
805 (defface markdown-header-face
806 '((t (:inherit font-lock-function-name-face :weight bold)))
807 "Base face for headers."
808 :group 'markdown-faces)
810 (defface markdown-header-face-1
811 '((t (:inherit markdown-header-face)))
812 "Face for level-1 headers."
813 :group 'markdown-faces)
815 (defface markdown-header-face-2
816 '((t (:inherit markdown-header-face)))
817 "Face for level-2 headers."
818 :group 'markdown-faces)
820 (defface markdown-header-face-3
821 '((t (:inherit markdown-header-face)))
822 "Face for level-3 headers."
823 :group 'markdown-faces)
825 (defface markdown-header-face-4
826 '((t (:inherit markdown-header-face)))
827 "Face for level-4 headers."
828 :group 'markdown-faces)
830 (defface markdown-header-face-5
831 '((t (:inherit markdown-header-face)))
832 "Face for level-5 headers."
833 :group 'markdown-faces)
835 (defface markdown-header-face-6
836 '((t (:inherit markdown-header-face)))
837 "Face for level-6 headers."
838 :group 'markdown-faces)
840 (defface markdown-inline-code-face
841 '((t (:inherit font-lock-constant-face)))
842 "Face for inline code."
843 :group 'markdown-faces)
845 (defface markdown-list-face
846 '((t (:inherit font-lock-builtin-face)))
847 "Face for list item markers."
848 :group 'markdown-faces)
850 (defface markdown-blockquote-face
851 '((t (:inherit font-lock-doc-face)))
852 "Face for blockquote sections."
853 :group 'markdown-faces)
855 (defface markdown-pre-face
856 '((t (:inherit font-lock-constant-face)))
857 "Face for preformatted text."
858 :group 'markdown-faces)
860 (defface markdown-language-keyword-face
861 '((t (:inherit font-lock-type-face)))
862 "Face for programming language identifiers."
863 :group 'markdown-faces)
865 (defface markdown-link-face
866 '((t (:inherit font-lock-keyword-face)))
867 "Face for links."
868 :group 'markdown-faces)
870 (defface markdown-missing-link-face
871 '((t (:inherit font-lock-warning-face)))
872 "Face for missing links."
873 :group 'markdown-faces)
875 (defface markdown-reference-face
876 '((t (:inherit font-lock-type-face)))
877 "Face for link references."
878 :group 'markdown-faces)
880 (defface markdown-footnote-face
881 '((t (:inherit font-lock-keyword-face)))
882 "Face for footnote markers."
883 :group 'markdown-faces)
885 (defface markdown-url-face
886 '((t (:inherit font-lock-string-face)))
887 "Face for URLs."
888 :group 'markdown-faces)
890 (defface markdown-link-title-face
891 '((t (:inherit font-lock-comment-face)))
892 "Face for reference link titles."
893 :group 'markdown-faces)
895 (defface markdown-comment-face
896 '((t (:inherit font-lock-comment-face)))
897 "Face for HTML comments."
898 :group 'markdown-faces)
900 (defface markdown-math-face
901 '((t (:inherit font-lock-string-face)))
902 "Face for LaTeX expressions."
903 :group 'markdown-faces)
905 (defconst markdown-regex-link-inline
906 "\\(!?\\[[^]]*?\\]\\)\\(([^\\)]*)\\)"
907 "Regular expression for a [text](file) or an image link ![text](file).")
909 (defconst markdown-regex-link-reference
910 "\\(!?\\[[^]]+?\\]\\)[ ]?\\(\\[[^]]*?\\]\\)"
911 "Regular expression for a reference link [text][id].")
913 (defconst markdown-regex-reference-definition
914 "^ \\{0,3\\}\\(\\[[^\n]+?\\]\\):\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
915 "Regular expression for a link definition [id]: ...")
917 (defconst markdown-regex-footnote
918 "\\(\\[\\^.+?\\]\\)"
919 "Regular expression for a footnote marker [^fn].")
921 (defconst markdown-regex-header
922 "^\\(?:\\(.+\\)\n\\(=+\\)\\|\\(.+\\)\n\\(-+\\)\\|\\(#+\\)\\s-*\\(.*?\\)\\s-*?\\(#*\\)\\)$"
923 "Regexp identifying Markdown headers.")
925 (defconst markdown-regex-header-1-atx
926 "^\\(# \\)\\(.*?\\)\\($\\| #+$\\)"
927 "Regular expression for level 1 atx-style (hash mark) headers.")
929 (defconst markdown-regex-header-2-atx
930 "^\\(## \\)\\(.*?\\)\\($\\| #+$\\)"
931 "Regular expression for level 2 atx-style (hash mark) headers.")
933 (defconst markdown-regex-header-3-atx
934 "^\\(### \\)\\(.*?\\)\\($\\| #+$\\)"
935 "Regular expression for level 3 atx-style (hash mark) headers.")
937 (defconst markdown-regex-header-4-atx
938 "^\\(#### \\)\\(.*?\\)\\($\\| #+$\\)"
939 "Regular expression for level 4 atx-style (hash mark) headers.")
941 (defconst markdown-regex-header-5-atx
942 "^\\(##### \\)\\(.*?\\)\\($\\| #+$\\)"
943 "Regular expression for level 5 atx-style (hash mark) headers.")
945 (defconst markdown-regex-header-6-atx
946 "^\\(###### \\)\\(.*?\\)\\($\\| #+$\\)"
947 "Regular expression for level 6 atx-style (hash mark) headers.")
949 (defconst markdown-regex-header-1-setext
950 "^\\(.*\\)\n\\(=+\\)$"
951 "Regular expression for level 1 setext-style (underline) headers.")
953 (defconst markdown-regex-header-2-setext
954 "^\\(.*\\)\n\\(-+\\)$"
955 "Regular expression for level 2 setext-style (underline) headers.")
957 (defconst markdown-regex-header-setext
958 "^\\(.+\\)\n\\(\\(?:=\\|-\\)+\\)$"
959 "Regular expression for generic setext-style (underline) headers.")
961 (defconst markdown-regex-header-atx
962 "^\\(#+\\)[ \t]*\\(.*?\\)[ \t]*\\(#*\\)$"
963 "Regular expression for generic atx-style (hash mark) headers.")
965 (defconst markdown-regex-hr
966 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
967 "Regular expression for matching Markdown horizontal rules.")
969 (defconst markdown-regex-code
970 "\\(\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(.\\|\n[^\n]\\)*?[^`]\\)\\3\\)\\([^`]\\|\\'\\)"
971 "Regular expression for matching inline code fragments.
973 The first group ensures that the leading backquote character
974 is not escaped. The group \\(.\\|\n[^\n]\\) matches any
975 character, including newlines, but not two newlines in a row.
976 The final group requires that the character following the code
977 fragment is not a backquote.")
979 (defconst markdown-regex-pre
980 "^\\( \\|\t\\).*$"
981 "Regular expression for matching preformatted text sections.")
983 (defconst markdown-regex-list
984 "^\\([ \t]*\\)\\([0-9]+\\.\\|[\\*\\+-]\\)\\([ \t]+\\)"
985 "Regular expression for matching list items.")
987 (defconst markdown-regex-bold
988 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
989 "Regular expression for matching bold text.
990 Group 1 matches the character before the opening asterisk or
991 underscore, if any, ensuring that it is not a backslash escape.
992 Group 2 matches the entire expression, including delimiters.
993 Groups 3 and 5 matches the opening and closing delimiters.
994 Group 4 matches the text inside the delimiters.")
996 (defconst markdown-regex-italic
997 "\\(^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
998 "Regular expression for matching italic text.
999 Group 1 matches the character before the opening asterisk or
1000 underscore, if any, ensuring that it is not a backslash escape.
1001 Group 2 matches the entire expression, including delimiters.
1002 Groups 3 and 5 matches the opening and closing delimiters.
1003 Group 4 matches the text inside the delimiters.")
1005 (defconst markdown-regex-blockquote
1006 "^[ \t]*\\(>\\).*$"
1007 "Regular expression for matching blockquote lines.")
1009 (defconst markdown-regex-line-break
1010 " $"
1011 "Regular expression for matching line breaks.")
1013 (defconst markdown-regex-wiki-link
1014 "\\(?:^\\|[^\\]\\)\\(\\[\\[\\([^]|]+\\)\\(|\\([^]]+\\)\\)?\\]\\]\\)"
1015 "Regular expression for matching wiki links.
1016 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1017 wiki links of the form [[PageName|link text]]. In this regular
1018 expression, #1 matches the page name and #3 matches the link
1019 text.")
1021 (defconst markdown-regex-uri
1022 (concat
1023 "\\(" (mapconcat 'identity markdown-uri-types "\\|")
1024 "\\):[^]\t\n\r<>,;() ]+")
1025 "Regular expression for matching inline URIs.")
1027 (defconst markdown-regex-angle-uri
1028 (concat
1029 "\\(<\\)\\(\\(?:"
1030 (mapconcat 'identity markdown-uri-types "\\|")
1031 "\\):[^]\t\n\r<>,;()]+\\)\\(>\\)")
1032 "Regular expression for matching inline URIs in angle brackets.")
1034 (defconst markdown-regex-email
1035 "<\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+>"
1036 "Regular expression for matching inline email addresses.")
1038 (defconst markdown-regex-block-separator
1039 "\\(\\`\\|\\(\n[ \t]*\n\\)[^\n \t]\\)"
1040 "Regular expression for matching block boundaries.")
1042 (defconst markdown-regex-latex-expression
1043 "\\(^\\|[^\\]\\)\\(\\$\\($\\([^\\$]\\|\\\\.\\)*\\$\\|\\([^\\$]\\|\\\\.\\)*\\)\\$\\)"
1044 "Regular expression for itex $..$ or $$..$$ math mode expressions.")
1046 (defconst markdown-regex-latex-display
1047 "^\\\\\\[\\(.\\|\n\\)*?\\\\\\]$"
1048 "Regular expression for itex \[..\] display mode expressions.")
1050 (defvar markdown-mode-font-lock-keywords-basic
1051 (list
1052 (cons 'markdown-match-pre-blocks '((0 markdown-pre-face)))
1053 (cons 'markdown-match-fenced-code-blocks '((0 markdown-pre-face)))
1054 (cons 'markdown-match-gfm-code-blocks '((1 markdown-pre-face)
1055 (2 markdown-language-keyword-face nil t)
1056 (3 markdown-pre-face)
1057 (4 markdown-pre-face)))
1058 (cons markdown-regex-blockquote 'markdown-blockquote-face)
1059 (cons markdown-regex-header-1-setext '((1 markdown-header-face-1)
1060 (2 markdown-header-rule-face)))
1061 (cons markdown-regex-header-2-setext '((1 markdown-header-face-2)
1062 (2 markdown-header-rule-face)))
1063 (cons markdown-regex-header-1-atx '((1 markdown-header-delimiter-face)
1064 (2 markdown-header-face-1)
1065 (3 markdown-header-delimiter-face)))
1066 (cons markdown-regex-header-2-atx '((1 markdown-header-delimiter-face)
1067 (2 markdown-header-face-2)
1068 (3 markdown-header-delimiter-face)))
1069 (cons markdown-regex-header-3-atx '((1 markdown-header-delimiter-face)
1070 (2 markdown-header-face-3)
1071 (3 markdown-header-delimiter-face)))
1072 (cons markdown-regex-header-4-atx '((1 markdown-header-delimiter-face)
1073 (2 markdown-header-face-4)
1074 (3 markdown-header-delimiter-face)))
1075 (cons markdown-regex-header-5-atx '((1 markdown-header-delimiter-face)
1076 (2 markdown-header-face-5)
1077 (3 markdown-header-delimiter-face)))
1078 (cons markdown-regex-header-6-atx '((1 markdown-header-delimiter-face)
1079 (2 markdown-header-face-6)
1080 (3 markdown-header-delimiter-face)))
1081 (cons markdown-regex-hr 'markdown-header-face)
1082 (cons 'markdown-match-comments '((0 markdown-comment-face t t)))
1083 (cons markdown-regex-code '(2 markdown-inline-code-face))
1084 (cons markdown-regex-angle-uri 'markdown-link-face)
1085 (cons markdown-regex-uri 'markdown-link-face)
1086 (cons markdown-regex-email 'markdown-link-face)
1087 (cons markdown-regex-list '(2 markdown-list-face))
1088 (cons markdown-regex-link-inline '((1 markdown-link-face t)
1089 (2 markdown-url-face t)))
1090 (cons markdown-regex-link-reference '((1 markdown-link-face t)
1091 (2 markdown-reference-face t)))
1092 (cons markdown-regex-reference-definition '((1 markdown-reference-face t)
1093 (2 markdown-url-face t)
1094 (3 markdown-link-title-face t)))
1095 (cons markdown-regex-footnote 'markdown-footnote-face)
1096 (cons markdown-regex-bold '(2 markdown-bold-face))
1097 (cons markdown-regex-italic '(2 markdown-italic-face))
1099 "Syntax highlighting for Markdown files.")
1101 (defconst markdown-mode-font-lock-keywords-latex
1102 (list
1103 ;; Math mode $..$ or $$..$$
1104 (cons markdown-regex-latex-expression '(2 markdown-math-face))
1105 ;; Display mode equations with brackets: \[ \]
1106 (cons markdown-regex-latex-display 'markdown-math-face)
1107 ;; Equation reference (eq:foo)
1108 (cons "(eq:\\w+)" 'markdown-reference-face)
1109 ;; Equation reference \eqref{foo}
1110 (cons "\\\\eqref{\\w+}" 'markdown-reference-face))
1111 "Syntax highlighting for LaTeX fragments.")
1113 (defvar markdown-mode-font-lock-keywords
1114 (append
1115 (if markdown-enable-math
1116 markdown-mode-font-lock-keywords-latex)
1117 markdown-mode-font-lock-keywords-basic)
1118 "Default highlighting expressions for Markdown mode.")
1120 ;; Footnotes
1121 (defvar markdown-footnote-counter 0
1122 "Counter for footnote numbers.")
1123 (make-variable-buffer-local 'markdown-footnote-counter)
1125 (defconst markdown-footnote-chars
1126 "[[:alnum:]-]"
1127 "Regular expression maching any character that is allowed in a footnote identifier.")
1130 ;;; Compatibility =============================================================
1132 (defun markdown-replace-regexp-in-string (regexp rep string)
1133 "Replace all matches for REGEXP with REP in STRING.
1134 This is a compatibility wrapper to provide `replace-regexp-in-string'
1135 in XEmacs 21."
1136 (if (featurep 'xemacs)
1137 (replace-in-string string regexp rep)
1138 (replace-regexp-in-string regexp rep string)))
1140 ;; `markdown-use-region-p' is a compatibility function which checks
1141 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
1142 (eval-and-compile
1143 (cond
1144 ;; Emacs 23 and newer
1145 ((fboundp 'use-region-p)
1146 (defalias 'markdown-use-region-p 'use-region-p))
1147 ;; Older Emacsen
1148 ((and (boundp 'transient-mark-mode) (boundp 'mark-active))
1149 (defun markdown-use-region-p ()
1150 "Compatibility wrapper to provide `use-region-p'."
1151 (and transient-mark-mode mark-active)))
1152 ;; XEmacs
1153 ((fboundp 'region-active-p)
1154 (defalias 'markdown-use-region-p 'region-active-p))))
1157 ;;; Markdown Parsing Functions ================================================
1159 (defun markdown-cur-line-blank-p ()
1160 "Return t if the current line is blank and nil otherwise."
1161 (save-excursion
1162 (beginning-of-line)
1163 (re-search-forward "^\\s *$" (point-at-eol) t)))
1165 (defun markdown-prev-line-blank-p ()
1166 "Return t if the previous line is blank and nil otherwise.
1167 If we are at the first line, then consider the previous line to be blank."
1168 (or (= (point-at-bol) (point-min))
1169 (save-excursion
1170 (forward-line -1)
1171 (markdown-cur-line-blank-p))))
1173 (defun markdown-next-line-blank-p ()
1174 "Return t if the next line is blank and nil otherwise.
1175 If we are at the last line, then consider the next line to be blank."
1176 (or (= (point-at-eol) (point-max))
1177 (save-excursion
1178 (forward-line 1)
1179 (markdown-cur-line-blank-p))))
1181 (defun markdown-prev-line-indent-p ()
1182 "Return t if the previous line is indented and nil otherwise."
1183 (save-excursion
1184 (forward-line -1)
1185 (goto-char (point-at-bol))
1186 (if (re-search-forward "^\\s " (point-at-eol) t) t)))
1188 (defun markdown-cur-line-indent ()
1189 "Return the number of leading whitespace characters in the current line."
1190 (save-match-data
1191 (save-excursion
1192 (goto-char (point-at-bol))
1193 (re-search-forward "^[ \t]+" (point-at-eol) t)
1194 (current-column))))
1196 (defun markdown-prev-line-indent ()
1197 "Return the number of leading whitespace characters in the previous line."
1198 (save-excursion
1199 (forward-line -1)
1200 (markdown-cur-line-indent)))
1202 (defun markdown-next-line-indent ()
1203 "Return the number of leading whitespace characters in the next line."
1204 (save-excursion
1205 (forward-line 1)
1206 (markdown-cur-line-indent)))
1208 (defun markdown-cur-non-list-indent ()
1209 "Return beginning position of list item text (not including the list marker).
1210 Return nil if the current line is not the beginning of a list item."
1211 (save-match-data
1212 (save-excursion
1213 (beginning-of-line)
1214 (when (re-search-forward markdown-regex-list (point-at-eol) t)
1215 (current-column)))))
1217 (defun markdown-prev-non-list-indent ()
1218 "Return position of the first non-list-marker on the previous line."
1219 (save-excursion
1220 (forward-line -1)
1221 (markdown-cur-non-list-indent)))
1223 (defun markdown-new-baseline-p ()
1224 "Determine if the current line begins a new baseline level."
1225 (save-excursion
1226 (beginning-of-line)
1227 (save-match-data
1228 (or (looking-at markdown-regex-header)
1229 (looking-at markdown-regex-hr)
1230 (and (null (markdown-cur-non-list-indent))
1231 (= (markdown-cur-line-indent) 0)
1232 (markdown-prev-line-blank-p))))))
1234 (defun markdown-search-backward-baseline ()
1235 "Search backward baseline point with no indentation and not a list item."
1236 (end-of-line)
1237 (let (stop)
1238 (while (not (or stop (bobp)))
1239 (re-search-backward markdown-regex-block-separator nil t)
1240 (when (match-end 2)
1241 (goto-char (match-end 2))
1242 (cond
1243 ((markdown-new-baseline-p)
1244 (setq stop t))
1245 ((looking-at markdown-regex-list)
1246 (setq stop nil))
1247 (t (setq stop t)))))))
1249 (defun markdown-update-list-levels (marker indent levels)
1250 "Update list levels given list MARKER, block INDENT, and current LEVELS.
1251 Here, MARKER is a string representing the type of list, INDENT is an integer
1252 giving the indentation, in spaces, of the current block, and LEVELS is a
1253 list of the indentation levels of parent list items. When LEVELS is nil,
1254 it means we are at baseline (not inside of a nested list)."
1255 (cond
1256 ;; New list item at baseline.
1257 ((and marker (null levels))
1258 (setq levels (list indent)))
1259 ;; List item with greater indentation (four or more spaces).
1260 ;; Increase list level.
1261 ((and marker (>= indent (+ (car levels) 4)))
1262 (setq levels (cons indent levels)))
1263 ;; List item with greater or equal indentation (less than four spaces).
1264 ;; Do not increase list level.
1265 ((and marker (>= indent (car levels)))
1266 levels)
1267 ;; Lesser indentation level.
1268 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
1269 ;; indentation could move back more than one list level). Note
1270 ;; that this block need not be the beginning of list item.
1271 ((< indent (car levels))
1272 (while (and (> (length levels) 1)
1273 (< indent (+ (cadr levels) 4)))
1274 (setq levels (cdr levels)))
1275 levels)
1276 ;; Otherwise, do nothing.
1277 (t levels)))
1279 (defun markdown-calculate-list-levels ()
1280 "Calculate list levels at point.
1281 Return a list of the form (n1 n2 n3 ...) where n1 is the
1282 indentation of the deepest nested list item in the branch of
1283 the list at the point, n2 is the indentation of the parent
1284 list item, and so on. The depth of the list item is therefore
1285 the length of the returned list. If the point is not at or
1286 immediately after a list item, return nil."
1287 (save-excursion
1288 (let ((first (point)) levels indent pre-regexp)
1289 ;; Find a baseline point with zero list indentation
1290 (markdown-search-backward-baseline)
1291 ;; Search for all list items between baseline and LOC
1292 (while (re-search-forward markdown-regex-list first t)
1293 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
1294 (beginning-of-line)
1295 (cond
1296 ;; Make sure this is not a header or hr
1297 ((markdown-new-baseline-p) (setq levels nil))
1298 ;; Make sure this is not a line from a pre block
1299 ((looking-at pre-regexp))
1300 ;; If not, then update levels
1302 (setq indent (markdown-cur-line-indent))
1303 (setq levels (markdown-update-list-levels (match-string 2)
1304 indent levels))))
1305 (end-of-line))
1306 levels)))
1308 (defun markdown-prev-list-item (level)
1309 "Search backward from point for a list item with indentation LEVEL.
1310 Set point to the beginning of the item, and return point, or nil
1311 upon failure."
1312 (let (bounds indent prev)
1313 (setq prev (point))
1314 (forward-line -1)
1315 (setq indent (markdown-cur-line-indent))
1316 (while
1317 (cond
1318 ;; Stop at beginning of buffer
1319 ((bobp) (setq prev nil))
1320 ;; Continue if current line is blank
1321 ((markdown-cur-line-blank-p) t)
1322 ;; List item
1323 ((and (looking-at markdown-regex-list)
1324 (setq bounds (markdown-cur-list-item-bounds)))
1325 (cond
1326 ;; Continue at item with greater indentation
1327 ((> (nth 3 bounds) level) t)
1328 ;; Stop and return point at item of equal indentation
1329 ((= (nth 3 bounds) level)
1330 (setq prev (point))
1331 nil)
1332 ;; Stop and return nil at item with lesser indentation
1333 ((< (nth 3 bounds) level)
1334 (setq prev nil)
1335 nil)))
1336 ;; Continue while indentation is the same or greater
1337 ((>= indent level) t)
1338 ;; Stop if current indentation is less than list item
1339 ;; and the next is blank
1340 ((and (< indent level)
1341 (markdown-next-line-blank-p))
1342 (setq prev nil))
1343 ;; Stop at a header
1344 ((looking-at markdown-regex-header) (setq prev nil))
1345 ;; Stop at a horizontal rule
1346 ((looking-at markdown-regex-hr) (setq prev nil))
1347 ;; Otherwise, continue.
1348 (t t))
1349 (forward-line -1)
1350 (setq indent (markdown-cur-line-indent)))
1351 prev))
1353 (defun markdown-next-list-item (level)
1354 "Search forward from point for the next list item with indentation LEVEL.
1355 Set point to the beginning of the item, and return point, or nil
1356 upon failure."
1357 (let (bounds indent prev next)
1358 (setq next (point))
1359 (forward-line)
1360 (setq indent (markdown-cur-line-indent))
1361 (while
1362 (cond
1363 ;; Stop at end of the buffer.
1364 ((eobp) (setq prev nil))
1365 ;; Continue if the current line is blank
1366 ((markdown-cur-line-blank-p) t)
1367 ;; List item
1368 ((and (looking-at markdown-regex-list)
1369 (setq bounds (markdown-cur-list-item-bounds)))
1370 (cond
1371 ;; Continue at item with greater indentation
1372 ((> (nth 3 bounds) level) t)
1373 ;; Stop and return point at item of equal indentation
1374 ((= (nth 3 bounds) level)
1375 (setq next (point))
1376 nil)
1377 ;; Stop and return nil at item with lesser indentation
1378 ((< (nth 3 bounds) level)
1379 (setq next nil)
1380 nil)))
1381 ;; Continue while indentation is the same or greater
1382 ((>= indent level) t)
1383 ;; Stop if current indentation is less than list item
1384 ;; and the previous line was blank.
1385 ((and (< indent level)
1386 (markdown-prev-line-blank-p))
1387 (setq next nil))
1388 ;; Stop at a header
1389 ((looking-at markdown-regex-header) (setq next nil))
1390 ;; Stop at a horizontal rule
1391 ((looking-at markdown-regex-hr) (setq next nil))
1392 ;; Otherwise, continue.
1393 (t t))
1394 (forward-line)
1395 (setq indent (markdown-cur-line-indent)))
1396 next))
1398 (defun markdown-cur-list-item-end (level)
1399 "Move to the end of the current list item with nonlist indentation LEVEL.
1400 If the point is not in a list item, do nothing."
1401 (let (indent)
1402 (forward-line)
1403 (setq indent (markdown-cur-line-indent))
1404 (while
1405 (cond
1406 ;; Stop at end of the buffer.
1407 ((eobp) nil)
1408 ;; Continue if the current line is blank
1409 ((markdown-cur-line-blank-p) t)
1410 ;; Continue while indentation is the same or greater
1411 ((>= indent level) t)
1412 ;; Stop if current indentation is less than list item
1413 ;; and the previous line was blank.
1414 ((and (< indent level)
1415 (markdown-prev-line-blank-p))
1416 nil)
1417 ;; Stop at a new list item of the same or lesser indentation
1418 ((looking-at markdown-regex-list) nil)
1419 ;; Stop at a header
1420 ((looking-at markdown-regex-header) nil)
1421 ;; Stop at a horizontal rule
1422 ((looking-at markdown-regex-hr) nil)
1423 ;; Otherwise, continue.
1424 (t t))
1425 (forward-line)
1426 (setq indent (markdown-cur-line-indent)))
1427 ;; Don't skip over whitespace for empty list items (marker and
1428 ;; whitespace only), just move to end of whitespace.
1429 (if (looking-back (concat markdown-regex-list "\\s-*"))
1430 (goto-char (match-end 3))
1431 (skip-syntax-backward "-"))))
1433 (defun markdown-cur-list-item-bounds ()
1434 "Return bounds and indentation of the current list item.
1435 Return a list of the form (begin end indent nonlist-indent).
1436 If the point is not inside a list item, return nil.
1437 Leave match data intact for `markdown-regex-list'."
1438 (let (cur prev-begin prev-end indent nonlist-indent)
1439 ;; Store current location
1440 (setq cur (point))
1441 ;; Verify that cur is between beginning and end of item
1442 (save-excursion
1443 (end-of-line)
1444 (when (re-search-backward markdown-regex-list nil t)
1445 (setq prev-begin (match-beginning 0))
1446 (setq indent (length (match-string 1)))
1447 (setq nonlist-indent (length (match-string 0)))
1448 (save-match-data
1449 (markdown-cur-list-item-end nonlist-indent)
1450 (setq prev-end (point)))
1451 (when (and (>= cur prev-begin)
1452 (<= cur prev-end)
1453 nonlist-indent)
1454 (list prev-begin prev-end indent nonlist-indent))))))
1456 (defun markdown-bounds-of-thing-at-point (thing)
1457 "Calls `bounds-of-thing-at-point' for THING with slight modifications.
1458 Does not include trailing newlines when THING is 'line. Handles the
1459 end of buffer case by setting both endpoints equal to the value of
1460 `point-max', since an empty region will trigger empty markup insertion.
1461 Return bounds of form (beg . end) if THING is found, or nil otherwise."
1462 (let* ((bounds (bounds-of-thing-at-point thing))
1463 (a (car bounds))
1464 (b (cdr bounds)))
1465 (when bounds
1466 (when (eq thing 'line)
1467 (cond ((and (eobp) (markdown-cur-line-blank-p))
1468 (setq a b))
1469 ((char-equal (char-before b) ?\^J)
1470 (setq b (1- b)))))
1471 (cons a b))))
1474 ;;; Markdown Font Lock Matching Functions =====================================
1476 (defun markdown-match-comments (last)
1477 "Match HTML comments from the point to LAST."
1478 (cond ((search-forward "<!--" last t)
1479 (backward-char 4)
1480 (let ((beg (point)))
1481 (cond ((search-forward-regexp "--[ \t]*>" last t)
1482 (set-match-data (list beg (point)))
1484 (t nil))))
1485 (t nil)))
1487 (defun markdown-match-pre-blocks (last)
1488 "Match Markdown pre blocks from point to LAST."
1489 (let ((levels (markdown-calculate-list-levels))
1490 indent pre-regexp end-regexp begin end stop)
1491 (while (and (< (point) last) (not end))
1492 ;; Search for a region with sufficient indentation
1493 (if (null levels)
1494 (setq indent 1)
1495 (setq indent (1+ (length levels))))
1496 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1497 (setq end-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1499 (cond
1500 ;; If not at the beginning of a line, move forward
1501 ((not (bolp)) (forward-line))
1502 ;; Move past blank lines
1503 ((markdown-cur-line-blank-p) (forward-line))
1504 ;; At headers and horizontal rules, reset levels
1505 ((markdown-new-baseline-p) (forward-line) (setq levels nil))
1506 ;; If the current line has sufficient indentation, mark out pre block
1507 ((looking-at pre-regexp)
1508 (setq begin (match-beginning 0))
1509 (while (and (or (looking-at pre-regexp) (markdown-cur-line-blank-p))
1510 (not (eobp)))
1511 (forward-line))
1512 (setq end (point)))
1513 ;; If current line has a list marker, update levels, move to end of block
1514 ((looking-at markdown-regex-list)
1515 (setq levels (markdown-update-list-levels
1516 (match-string 2) (markdown-cur-line-indent) levels))
1517 (markdown-end-of-block-element))
1518 ;; If this is the end of the indentation level, adjust levels accordingly.
1519 ;; Only match end of indentation level if levels is not the empty list.
1520 ((and (car levels) (looking-at end-regexp))
1521 (setq levels (markdown-update-list-levels
1522 nil (markdown-cur-line-indent) levels))
1523 (markdown-end-of-block-element))
1524 (t (markdown-end-of-block-element))))
1526 (if (not (and begin end))
1527 ;; Return nil if no pre block was found
1529 ;; Set match data and return t upon success
1530 (set-match-data (list begin end))
1531 t)))
1533 (defun markdown-match-fenced-code-blocks (last)
1534 "Match fenced code blocks from the point to LAST."
1535 (cond ((search-forward-regexp "^\\([~]\\{3,\\}\\)" last t)
1536 (beginning-of-line)
1537 (let ((beg (point)))
1538 (forward-line)
1539 (cond ((search-forward-regexp
1540 (concat "^" (match-string 1) "~*") last t)
1541 (set-match-data (list beg (point)))
1543 (t nil))))
1544 (t nil)))
1546 (defun markdown-match-gfm-code-blocks (last)
1547 "Match GFM quoted code blocks from point to LAST."
1548 (let (open lang body close all)
1549 (cond ((and (eq major-mode 'gfm-mode)
1550 (search-forward-regexp "^\\(```\\)\\(\\w+\\)?$" last t))
1551 (beginning-of-line)
1552 (setq open (list (match-beginning 1) (match-end 1))
1553 lang (list (match-beginning 2) (match-end 2)))
1554 (forward-line)
1555 (setq body (list (point)))
1556 (cond ((search-forward-regexp "^```$" last t)
1557 (setq body (reverse (cons (1- (match-beginning 0)) body))
1558 close (list (match-beginning 0) (match-end 0))
1559 all (list (car open) (match-end 0)))
1560 (set-match-data (append all open lang body close))
1562 (t nil)))
1563 (t nil))))
1565 (defun markdown-font-lock-extend-region ()
1566 "Extend the search region to include an entire block of text.
1567 This helps improve font locking for block constructs such as pre blocks."
1568 ;; Avoid compiler warnings about these global variables from font-lock.el.
1569 ;; See the documentation for variable `font-lock-extend-region-functions'.
1570 (eval-when-compile (defvar font-lock-beg) (defvar font-lock-end))
1571 (save-excursion
1572 (goto-char font-lock-beg)
1573 (let ((found (or (re-search-backward "\n\n" nil t) (point-min))))
1574 (goto-char font-lock-end)
1575 (when (re-search-forward "\n\n" nil t)
1576 (beginning-of-line)
1577 (setq font-lock-end (point)))
1578 (setq font-lock-beg found))))
1581 ;;; Syntax Table ==============================================================
1583 (defvar markdown-mode-syntax-table
1584 (let ((tab (make-syntax-table text-mode-syntax-table)))
1585 (modify-syntax-entry ?\" "." tab)
1586 tab)
1587 "Syntax table for `markdown-mode'.")
1590 ;;; Element Insertion =========================================================
1592 (defun markdown-ensure-blank-line-before ()
1593 "If previous line is not already blank, insert a blank line before point."
1594 (unless (bolp) (insert "\n"))
1595 (unless (or (bobp) (looking-back "\n\\s-*\n")) (insert "\n")))
1597 (defun markdown-ensure-blank-line-after ()
1598 "If following line is not already blank, insert a blank line after point.
1599 Return the point where it was originally."
1600 (save-excursion
1601 (unless (eolp) (insert "\n"))
1602 (unless (or (eobp) (looking-at "\n\\s-*\n")) (insert "\n"))))
1604 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
1605 "Insert the strings S1 and S2, wrapping around region or THING.
1606 If a region is specified by the optional BEG and END arguments,
1607 wrap the strings S1 and S2 around that region.
1608 If there is an active region, wrap the strings S1 and S2 around
1609 the region. If there is not an active region but the point is at
1610 THING, wrap that thing (which defaults to word). Otherwise, just
1611 insert S1 and S2 and place the cursor in between. Return the
1612 bounds of the entire wrapped string, or nil if nothing was wrapped
1613 and S1 and S2 were only inserted."
1614 (let (a b bounds new-point)
1615 (cond
1616 ;; Given region
1617 ((and beg end)
1618 (setq a beg
1619 b end
1620 new-point (+ (point) (length s1))))
1621 ;; Active region
1622 ((markdown-use-region-p)
1623 (setq a (region-beginning)
1624 b (region-end)
1625 new-point (+ (point) (length s1))))
1626 ;; Thing (word) at point
1627 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
1628 (setq a (car bounds)
1629 b (cdr bounds)
1630 new-point (+ (point) (length s1))))
1631 ;; No active region and no word
1633 (setq a (point)
1634 b (point))))
1635 (goto-char b)
1636 (insert s2)
1637 (goto-char a)
1638 (insert s1)
1639 (when new-point (goto-char new-point))
1640 (if (= a b)
1642 (setq b (+ b (length s1) (length s2)))
1643 (cons a b))))
1645 (defun markdown-point-after-unwrap (cur prefix suffix)
1646 "Return desired position of point after an unwrapping operation.
1647 Two cons cells must be provided. PREFIX gives the bounds of the
1648 prefix string and SUFFIX gives the bounds of the suffix string."
1649 (cond ((< cur (cdr prefix)) (car prefix))
1650 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
1651 ((<= cur (cdr suffix))
1652 (- cur (+ (- (cdr prefix) (car prefix))
1653 (- cur (car suffix)))))
1654 (t cur)))
1656 (defun markdown-unwrap-thing-at-point (regexp all text)
1657 "Remove prefix and suffix of thing at point and reposition the point.
1658 When the thing at point matches REGEXP, replace the subexpression
1659 ALL with the string in subexpression TEXT. Reposition the point
1660 in an appropriate location accounting for the removal of prefix
1661 and suffix strings. Return new bounds of string from group TEXT.
1662 When REGEXP is nil, assumes match data is already set."
1663 (when (or (null regexp)
1664 (thing-at-point-looking-at regexp))
1665 (let ((cur (point))
1666 (prefix (cons (match-beginning all) (match-beginning text)))
1667 (suffix (cons (match-end text) (match-end all)))
1668 (bounds (cons (match-beginning text) (match-end text))))
1669 ;; Replace the thing at point
1670 (replace-match (match-string text) t t nil all)
1671 ;; Reposition the point
1672 (goto-char (markdown-point-after-unwrap cur prefix suffix))
1673 ;; Adjust bounds
1674 (setq bounds (cons (car prefix)
1675 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
1677 (defun markdown-unwrap-things-in-region (beg end regexp all text)
1678 "Remove prefix and suffix of all things in region.
1679 When a thing in the region matches REGEXP, replace the
1680 subexpression ALL with the string in subexpression TEXT.
1681 Return a cons cell containing updated bounds for the region."
1682 (save-excursion
1683 (goto-char beg)
1684 (let ((removed 0) len-all len-text)
1685 (while (re-search-forward regexp end t)
1686 (setq len-all (length (match-string-no-properties all)))
1687 (setq len-text (length (match-string-no-properties text)))
1688 (setq removed (+ removed (- len-all len-text)))
1689 (replace-match (match-string text) t t nil all))
1690 (cons beg (- end removed)))))
1692 (defun markdown-insert-hr (arg)
1693 "Insert or replace a horizonal rule.
1694 By default, use the first element of `markdown-hr-strings'. When
1695 prefixed with C-u, use the last element of `markdown-hr-strings'
1696 instead. When prefixed with an integer from 1 to the length of
1697 `markdown-hr-strings', use the element in that position instead."
1698 (interactive "*P")
1699 (when (thing-at-point-looking-at markdown-regex-hr)
1700 (delete-region (match-beginning 0) (match-end 0)))
1701 (markdown-ensure-blank-line-before)
1702 (cond ((equal arg '(4))
1703 (insert (car (reverse markdown-hr-strings))))
1704 ((and (integerp arg) (> arg 0)
1705 (<= arg (length markdown-hr-strings)))
1706 (insert (nth (1- arg) markdown-hr-strings)))
1708 (insert (car markdown-hr-strings))))
1709 (markdown-ensure-blank-line-after))
1711 (defun markdown-insert-bold ()
1712 "Insert markup to make a region or word bold.
1713 If there is an active region, make the region bold. If the point
1714 is at a non-bold word, make the word bold. If the point is at a
1715 bold word or phrase, remove the bold markup. Otherwise, simply
1716 insert bold delimiters and place the cursor in between them."
1717 (interactive)
1718 (let ((delim (if markdown-bold-underscore "__" "**")))
1719 (if (markdown-use-region-p)
1720 ;; Active region
1721 (let ((bounds (markdown-unwrap-things-in-region
1722 (region-beginning) (region-end)
1723 markdown-regex-bold 2 4)))
1724 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
1725 ;; Bold markup removal, bold word at point, or empty markup insertion
1726 (if (thing-at-point-looking-at markdown-regex-bold)
1727 (markdown-unwrap-thing-at-point nil 2 4)
1728 (markdown-wrap-or-insert delim delim 'word nil nil)))))
1730 (defun markdown-insert-italic ()
1731 "Insert markup to make a region or word italic.
1732 If there is an active region, make the region italic. If the point
1733 is at a non-italic word, make the word italic. If the point is at an
1734 italic word or phrase, remove the italic markup. Otherwise, simply
1735 insert italic delimiters and place the cursor in between them."
1736 (interactive)
1737 (let ((delim (if markdown-italic-underscore "_" "*")))
1738 (if (markdown-use-region-p)
1739 ;; Active region
1740 (let ((bounds (markdown-unwrap-things-in-region
1741 (region-beginning) (region-end)
1742 markdown-regex-italic 2 4)))
1743 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
1744 ;; Italic markup removal, italic word at point, or empty markup insertion
1745 (if (thing-at-point-looking-at markdown-regex-italic)
1746 (markdown-unwrap-thing-at-point nil 2 4)
1747 (markdown-wrap-or-insert delim delim 'word nil nil)))))
1749 (defun markdown-insert-code ()
1750 "Insert markup to make a region or word an inline code fragment.
1751 If there is an active region, make the region an inline code
1752 fragment. If the point is at a word, make the word an inline
1753 code fragment. Otherwise, simply insert code delimiters and
1754 place the cursor in between them."
1755 (interactive)
1756 (if (markdown-use-region-p)
1757 ;; Active region
1758 (let ((bounds (markdown-unwrap-things-in-region
1759 (region-beginning) (region-end)
1760 markdown-regex-code 2 4)))
1761 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
1762 ;; Code markup removal, code markup for word, or empty markup insertion
1763 (if (thing-at-point-looking-at markdown-regex-code)
1764 (markdown-unwrap-thing-at-point nil 2 4)
1765 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
1767 (defun markdown-insert-link ()
1768 "Insert an inline link, using region or word as link text if possible.
1769 If there is an active region, use the region as the link text. If the
1770 point is at a word, use the word as the link text. In these cases, the
1771 point will be left at the position for inserting a URL. If there is no
1772 active region and the point is not at word, simply insert link markup and
1773 place the point in the position to enter link text."
1774 (interactive)
1775 (let ((bounds (markdown-wrap-or-insert "[" "]()")))
1776 (when bounds
1777 (goto-char (- (cdr bounds) 1)))))
1779 (defun markdown-insert-reference-link-dwim ()
1780 "Insert a reference link of the form [text][label] at point.
1781 If Transient Mark mode is on and a region is active, the region
1782 is used as the link text. Otherwise, the link text will be read
1783 from the minibuffer. The link URL, label, and title will be read
1784 from the minibuffer. The link label definition is placed at the
1785 end of the current paragraph."
1786 (interactive)
1787 (if (markdown-use-region-p)
1788 (call-interactively 'markdown-insert-reference-link-region)
1789 (call-interactively 'markdown-insert-reference-link)))
1791 (defun markdown-insert-reference-link-region (url label title)
1792 "Insert a reference link at point using the region as the link text.
1793 The link will point to URL, will be referenced as LABEL, and will have the
1794 optional title text given by TITLE."
1795 (interactive "sLink URL: \nsLink Label (optional): \nsLink Title (optional): ")
1796 (let ((text (delete-and-extract-region (region-beginning) (region-end))))
1797 (markdown-insert-reference-link text url label title)))
1799 (defun markdown-insert-reference-link (text url label title)
1800 "Insert a reference link at point.
1801 The link TEXT will point to the given URL and may be referenced using
1802 LABEL. The link TITLE is optional and will be used to populate the
1803 title attribute when converted to XHTML."
1804 (interactive "sLink Text: \nsLink URL: \nsLink Label (optional): \nsLink Title (optional): ")
1805 (let (end)
1806 (insert (concat "[" text "][" label "]"))
1807 (setq end (point))
1808 (forward-paragraph)
1809 (insert "\n[")
1810 (if (> (length label) 0)
1811 (insert label)
1812 (insert text))
1813 (insert (concat "]: " url))
1814 (unless (> (length url) 0)
1815 (setq end (point)))
1816 (when (> (length title) 0)
1817 (insert (concat " \"" title "\"")))
1818 (insert "\n")
1819 (unless (looking-at "\n")
1820 (insert "\n"))
1821 (goto-char end)))
1823 (defun markdown-insert-wiki-link ()
1824 "Insert a wiki link of the form [[WikiLink]].
1825 If Transient Mark mode is on and a region is active, it is used
1826 as the link text."
1827 (interactive)
1828 (markdown-wrap-or-insert "[[" "]]")
1829 (backward-char 2))
1831 (defun markdown-insert-image ()
1832 "Insert inline image markup using region or word as alt text if possible.
1833 If there is an active region, use the region as the alt text. If the
1834 point is at a word, use the word as the alt text. In these cases, the
1835 point will be left at the position for inserting a URL. If there is no
1836 active region and the point is not at word, simply insert image markup and
1837 place the point in the position to enter alt text."
1838 (interactive)
1839 (let ((bounds (markdown-wrap-or-insert "![" "]()")))
1840 (when bounds
1841 (goto-char (- (cdr bounds) 1)))))
1843 (defun markdown-remove-header ()
1844 "Remove header markup if point is at a header.
1845 Return bounds of remaining header text if a header was removed
1846 and nil otherwise."
1847 (interactive "*")
1848 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
1849 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
1851 (defun markdown-insert-header (&optional level text setext)
1852 "Insert or replace header markup.
1853 The level of the header is specified by LEVEL and header text is
1854 given by TEXT. LEVEL must be an integer from 1 and 6, and the
1855 default value is 1.
1856 When TEXT is nil, the header text is obtained as follows.
1857 If there is an active region, it is used as the header text.
1858 Otherwise, the current line will be used as the header text.
1859 If there is not an active region and the point is at a header,
1860 remove the header markup and replace with level N header.
1861 Otherwise, insert empty header markup and place the cursor in
1862 between.
1863 The style of the header will be atx (hash marks) unless
1864 SETEXT is non-nil, in which case a setext-style (underlined)
1865 header will be inserted."
1866 (interactive "p\nsHeader text: ")
1867 (setq level (min (max (or level 1) 1) (if setext 2 6)))
1868 ;; Determine header text if not given
1869 (when (null text)
1870 (if (markdown-use-region-p)
1871 ;; Active region
1872 (setq text (delete-and-extract-region (region-beginning) (region-end)))
1873 ;; No active region
1874 (markdown-remove-header)
1875 (setq text (delete-and-extract-region
1876 (line-beginning-position) (line-end-position)))
1877 (when (and setext (string-match "^[ \t]*$" text))
1878 (setq text (read-string "Header text: "))))
1879 (setq text (markdown-compress-whitespace-string text)))
1880 ;; Insertion with given text
1881 (markdown-ensure-blank-line-before)
1882 (if setext
1883 ;; setext
1884 (progn
1885 (insert text "\n")
1886 (dotimes (n (length text))
1887 (insert (if (= level 2) "-" "="))))
1888 ;; atx
1889 (dotimes (count level) (insert "#"))
1890 (insert " " text " ")
1891 (dotimes (count level) (insert "#")))
1892 (markdown-ensure-blank-line-after)
1893 ;; Leave point at end of text
1894 (if setext
1895 (backward-char (1+ (length text)))
1896 (backward-char (1+ level))))
1898 (defun markdown-insert-header-dwim (&optional arg)
1899 "Insert or replace header markup.
1900 The level of the header is determined by the numerical argument,
1901 if present, or the level of the previous header.
1902 The type of the header is determined by the type of the previous header.
1903 See `markdown-insert-header' for details about how the header text
1904 is determined."
1905 (interactive "*P")
1906 (let (level setext)
1907 (save-excursion
1908 (when (re-search-backward markdown-regex-header nil t)
1909 (setq level (markdown-outline-level))
1910 (setq setext (or (match-end 1) (match-end 3)))))
1911 ;; use prefix if given, or level of previous header
1912 (setq level (if arg (prefix-numeric-value arg) level))
1913 ;; match groups 1 and 2 indicate setext headers
1914 (setq setext (and level (<= level 2) setext))
1915 (markdown-insert-header level nil setext)))
1917 (defun markdown-insert-header-atx-1 ()
1918 "Insert a first level atx-style (hash mark) header.
1919 See `markdown-insert-header'."
1920 (interactive "*")
1921 (markdown-insert-header 1 nil nil))
1923 (defun markdown-insert-header-atx-2 ()
1924 "Insert a level two atx-style (hash mark) header.
1925 See `markdown-insert-header'."
1926 (interactive "*")
1927 (markdown-insert-header 2 nil nil))
1929 (defun markdown-insert-header-atx-3 ()
1930 "Insert a level three atx-style (hash mark) header.
1931 See `markdown-insert-header'."
1932 (interactive "*")
1933 (markdown-insert-header 3 nil nil))
1935 (defun markdown-insert-header-atx-4 ()
1936 "Insert a level four atx-style (hash mark) header.
1937 See `markdown-insert-header'."
1938 (interactive "*")
1939 (markdown-insert-header 4 nil nil))
1941 (defun markdown-insert-header-atx-5 ()
1942 "Insert a level five atx-style (hash mark) header.
1943 See `markdown-insert-header'."
1944 (interactive "*")
1945 (markdown-insert-header 5 nil nil))
1947 (defun markdown-insert-header-atx-6 ()
1948 "Insert a sixth level atx-style (hash mark) header.
1949 See `markdown-insert-header'."
1950 (interactive "*")
1951 (markdown-insert-header 6 nil nil))
1953 (defun markdown-insert-header-setext-1 ()
1954 "Insert a setext-style (underlined) first-level header.
1955 See `markdown-insert-header'."
1956 (interactive "*")
1957 (markdown-insert-header 1 nil t))
1959 (defun markdown-insert-header-setext-2 ()
1960 "Insert a setext-style (underlined) second-level header.
1961 See `markdown-insert-header'."
1962 (interactive "*")
1963 (markdown-insert-header 2 nil t))
1965 (defun markdown-blockquote-indentation (loc)
1966 "Return string containing necessary indentation for a blockquote at LOC.
1967 Also see `markdown-pre-indentation'."
1968 (save-excursion
1969 (goto-char loc)
1970 (let* ((list-level (length (markdown-calculate-list-levels)))
1971 (indent ""))
1972 (dotimes (count list-level indent)
1973 (setq indent (concat indent " "))))))
1975 (defun markdown-insert-blockquote ()
1976 "Start a blockquote section (or blockquote the region).
1977 If Transient Mark mode is on and a region is active, it is used as
1978 the blockquote text."
1979 (interactive)
1980 (if (markdown-use-region-p)
1981 (markdown-blockquote-region (region-beginning) (region-end))
1982 (markdown-ensure-blank-line-before)
1983 (insert (markdown-blockquote-indentation (point)) "> ")
1984 (markdown-ensure-blank-line-after)))
1986 (defun markdown-block-region (beg end prefix)
1987 "Format the region using a block prefix.
1988 Arguments BEG and END specify the beginning and end of the
1989 region. The characters PREFIX will appear at the beginning
1990 of each line."
1991 (save-excursion
1992 ;; Ensure that there is a leading blank line
1993 (goto-char beg)
1994 (when (and (>= (point) (+ (point-min) 2))
1995 (not (looking-back "\n\n" 2)))
1996 (insert "\n")
1997 (setq beg (1+ beg))
1998 (setq end (1+ end)))
1999 ;; Move back before any blank lines at the end
2000 (goto-char end)
2001 (while (and (looking-back "\n" 1)
2002 (not (equal (point) (point-min))))
2003 (backward-char)
2004 (setq end (1- end)))
2005 ;; Ensure that there is a trailing blank line
2006 (goto-char end)
2007 (if (not (or (looking-at "\n\n")
2008 (and (equal (1+ end) (point-max)) (looking-at "\n"))))
2009 (insert "\n"))
2010 ;; Insert PREFIX
2011 (goto-char beg)
2012 (beginning-of-line)
2013 (while (< (point-at-bol) end)
2014 (insert prefix)
2015 (setq end (+ (length prefix) end))
2016 (forward-line))))
2018 (defun markdown-blockquote-region (beg end)
2019 "Blockquote the region.
2020 Arguments BEG and END specify the beginning and end of the region."
2021 (interactive "*r")
2022 (markdown-block-region
2023 beg end (concat (markdown-blockquote-indentation
2024 (max (point-min) (1- beg))) "> ")))
2026 (defun markdown-pre-indentation (loc)
2027 "Return string containing necessary whitespace for a pre block at LOC.
2028 Also see `markdown-blockquote-indentation'."
2029 (save-excursion
2030 (goto-char loc)
2031 (let* ((list-level (length (markdown-calculate-list-levels)))
2032 indent)
2033 (dotimes (count (1+ list-level) indent)
2034 (setq indent (concat indent " "))))))
2036 (defun markdown-insert-pre ()
2037 "Start a preformatted section (or apply to the region).
2038 If Transient Mark mode is on and a region is active, it is marked
2039 as preformatted text."
2040 (interactive)
2041 (if (markdown-use-region-p)
2042 (markdown-pre-region (region-beginning) (region-end))
2043 (markdown-ensure-blank-line-before)
2044 (insert (markdown-pre-indentation (point)))
2045 (markdown-ensure-blank-line-after)))
2047 (defun markdown-pre-region (beg end)
2048 "Format the region as preformatted text.
2049 Arguments BEG and END specify the beginning and end of the region."
2050 (interactive "*r")
2051 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
2052 (markdown-block-region beg end indent)))
2054 (defun markdown-insert-gfm-code-block (&optional lang)
2055 "Insert GFM code block for language LANG.
2056 If LANG is nil, the language will be queried from user. If a
2057 region is active, wrap this region with the markup instead. If
2058 the region boundaries are not on empty lines, these are added
2059 automatically in order to have the correct markup."
2060 (interactive "sProgramming language: ")
2061 (if (markdown-use-region-p)
2062 (let ((b (region-beginning)) (e (region-end)))
2063 (goto-char b)
2064 ;; if we're on a blank line, insert the quotes here, otherwise
2065 ;; add a new line first
2066 (unless (looking-at "\n")
2067 (newline)
2068 (forward-line -1)
2069 (setq e (1+ e)))
2070 (insert "```" lang)
2071 (goto-char (+ e 3 (length lang)))
2072 ;; if we're on a blank line, don't newline, otherwise the ```
2073 ;; should go on its own line
2074 (unless (looking-back "\n")
2075 (newline))
2076 (insert "```"))
2077 (insert "```" lang)
2078 (newline 2)
2079 (insert "```")
2080 (forward-line -1)))
2083 ;;; Footnotes ======================================================================
2085 (defun markdown-footnote-counter-inc ()
2086 "Increment `markdown-footnote-counter' and return the new value."
2087 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
2088 (save-excursion
2089 (goto-char (point-min))
2090 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
2091 (point-max) t)
2092 (let ((fn (string-to-number (match-string 1))))
2093 (when (> fn markdown-footnote-counter)
2094 (setq markdown-footnote-counter fn))))))
2095 (incf markdown-footnote-counter))
2097 (defun markdown-footnote-new ()
2098 "Insert footnote with a new number and move point to footnote definition."
2099 (interactive)
2100 (let ((fn (markdown-footnote-counter-inc)))
2101 (insert (format "[^%d]" fn))
2102 (markdown-footnote-text-find-new-location)
2103 (markdown-ensure-blank-line-before)
2104 (unless (markdown-cur-line-blank-p)
2105 (insert "\n"))
2106 (insert (format "[^%d]: " fn))
2107 (markdown-ensure-blank-line-after)))
2109 (defun markdown-footnote-text-find-new-location ()
2110 "Position the cursor at the proper location for a new footnote text."
2111 (cond
2112 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
2113 ((eq markdown-footnote-location 'immediately) (forward-paragraph))
2114 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
2116 (defun markdown-footnote-kill ()
2117 "Kill the footnote at point.
2118 The footnote text is killed (and added to the kill ring), the
2119 footnote marker is deleted. Point has to be either at the
2120 footnote marker or in the footnote text."
2121 (interactive)
2122 (let (return-pos)
2123 (when (markdown-footnote-text-positions) ; if we're in a footnote text
2124 (markdown-footnote-return) ; we first move to the marker
2125 (setq return-pos 'text)) ; and remember our return position
2126 (let ((marker (markdown-footnote-delete-marker)))
2127 (unless marker
2128 (error "Not at a footnote"))
2129 (let ((text-pos (markdown-footnote-find-text (car marker))))
2130 (unless text-pos
2131 (error "No text for footnote `%s'" (car marker)))
2132 (goto-char text-pos)
2133 (let ((pos (markdown-footnote-kill-text)))
2134 (setq return-pos
2135 (if (and pos (eq return-pos 'text))
2137 (cadr marker))))))
2138 (goto-char return-pos)))
2140 (defun markdown-footnote-delete-marker ()
2141 "Delete a footnote marker at point.
2142 Returns a list (ID START) containing the footnote ID and the
2143 start position of the marker before deletion. If no footnote
2144 marker was deleted, this function returns NIL."
2145 (let ((marker (markdown-footnote-marker-positions)))
2146 (when marker
2147 (delete-region (second marker) (third marker))
2148 (butlast marker))))
2150 (defun markdown-footnote-kill-text ()
2151 "Kill footnote text at point.
2152 Returns the start position of the footnote text before deletion,
2153 or NIL if point was not inside a footnote text.
2155 The killed text is placed in the kill ring (without the footnote
2156 number)."
2157 (let ((fn (markdown-footnote-text-positions)))
2158 (when fn
2159 (let ((text (delete-and-extract-region (second fn) (third fn))))
2160 (string-match (concat "\\[\\" (first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
2161 (kill-new (match-string 1 text))
2162 (when (and (markdown-cur-line-blank-p)
2163 (markdown-prev-line-blank-p))
2164 (delete-region (1- (point)) (point)))
2165 (second fn)))))
2167 (defun markdown-footnote-goto-text ()
2168 "Jump to the text of the footnote at point."
2169 (interactive)
2170 (let ((fn (car (markdown-footnote-marker-positions))))
2171 (unless fn
2172 (error "Not at a footnote marker"))
2173 (let ((new-pos (markdown-footnote-find-text fn)))
2174 (unless new-pos
2175 (error "No definition found for footnote `%s'" fn))
2176 (goto-char new-pos))))
2178 (defun markdown-footnote-return ()
2179 "Return from a footnote to its footnote number in the main text."
2180 (interactive)
2181 (let ((fn (save-excursion
2182 (car (markdown-footnote-text-positions)))))
2183 (unless fn
2184 (error "Not in a footnote"))
2185 (let ((new-pos (markdown-footnote-find-marker fn)))
2186 (unless new-pos
2187 (error "Footnote marker `%s' not found" fn))
2188 (goto-char new-pos))))
2190 (defun markdown-footnote-find-marker (id)
2191 "Find the location of the footnote marker with ID.
2192 The actual buffer position returned is the position directly
2193 following the marker's closing bracket. If no marker is found,
2194 NIL is returned."
2195 (save-excursion
2196 (goto-char (point-min))
2197 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
2198 (skip-chars-backward "^]")
2199 (point))))
2201 (defun markdown-footnote-find-text (id)
2202 "Find the location of the text of footnote ID.
2203 The actual buffer position returned is the position of the first
2204 character of the text, after the footnote's identifier. If no
2205 footnote text is found, NIL is returned."
2206 (save-excursion
2207 (goto-char (point-min))
2208 (when (re-search-forward (concat "^\\[" id "\\]:") nil t)
2209 (skip-chars-forward "[ \t]")
2210 (point))))
2212 (defun markdown-footnote-marker-positions ()
2213 "Return the position and ID of the footnote marker point is on.
2214 The return value is a list (ID START END). If point is not on a
2215 footnote, NIL is returned."
2216 ;; first make sure we're at a footnote marker
2217 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (point-at-bol))
2218 (looking-at (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
2219 (save-excursion
2220 ;; move point between [ and ^:
2221 (if (looking-at "\\[")
2222 (forward-char 1)
2223 (skip-chars-backward "^["))
2224 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
2225 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
2227 (defun markdown-footnote-text-positions ()
2228 "Return the start and end positions of the footnote text point is in.
2229 The exact return value is a list of three elements: (ID START END).
2230 The start position is the position of the opening bracket
2231 of the footnote id. The end position is directly after the
2232 newline that ends the footnote. If point is not in a footnote,
2233 NIL is returned instead."
2234 (save-excursion
2235 (let ((fn (progn
2236 (backward-paragraph)
2237 ;; if we're in a multiparagraph footnote, we need to back up further
2238 (while (>= (markdown-next-line-indent) 4)
2239 (backward-paragraph))
2240 (forward-line)
2241 (if (looking-at (concat "^\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:"))
2242 (list (match-string 1) (point))))))
2243 (when fn
2244 (while (progn
2245 (forward-paragraph)
2246 (>= (markdown-next-line-indent) 4)))
2247 (append fn (list (point)))))))
2250 ;;; Indentation ====================================================================
2252 (defun markdown-indent-find-next-position (cur-pos positions)
2253 "Return the position after the index of CUR-POS in POSITIONS.
2254 Positions are calculated by `markdown-calc-indents'."
2255 (while (and positions
2256 (not (equal cur-pos (car positions))))
2257 (setq positions (cdr positions)))
2258 (or (cadr positions) 0))
2260 (defun markdown-indent-line ()
2261 "Indent the current line using some heuristics.
2262 If the _previous_ command was either `markdown-enter-key' or
2263 `markdown-cycle', then we should cycle to the next
2264 reasonable indentation position. Otherwise, we could have been
2265 called directly by `markdown-enter-key', by an initial call of
2266 `markdown-cycle', or indirectly by `auto-fill-mode'. In
2267 these cases, indent to the default position.
2268 Positions are calculated by `markdown-calc-indents'."
2269 (interactive)
2270 (let ((positions (markdown-calc-indents))
2271 (cur-pos (current-column)))
2272 (if (not (equal this-command 'markdown-cycle))
2273 (indent-line-to (car positions))
2274 (setq positions (sort (delete-dups positions) '<))
2275 (indent-line-to
2276 (markdown-indent-find-next-position cur-pos positions)))))
2278 (defun markdown-calc-indents ()
2279 "Return a list of indentation columns to cycle through.
2280 The first element in the returned list should be considered the
2281 default indentation level. This function does not worry about
2282 duplicate positions, which are handled up by calling functions."
2283 (let (pos prev-line-pos positions)
2285 ;; Indentation of previous line
2286 (setq prev-line-pos (markdown-prev-line-indent))
2287 (setq positions (cons prev-line-pos positions))
2289 ;; Indentation of previous non-list-marker text
2290 (when (setq pos (markdown-prev-non-list-indent))
2291 (setq positions (cons pos positions)))
2293 ;; Indentation required for a pre block in current context
2294 (setq pos (length (markdown-pre-indentation (point))))
2295 (setq positions (cons pos positions))
2297 ;; Indentation of the previous line + tab-width
2298 (if prev-line-pos
2299 (setq positions (cons (+ prev-line-pos tab-width) positions))
2300 (setq positions (cons tab-width positions)))
2302 ;; Indentation of the previous line - tab-width
2303 (if (and prev-line-pos (> prev-line-pos tab-width))
2304 (setq positions (cons (- prev-line-pos tab-width) positions)))
2306 ;; Indentation of all preceeding list markers (when in a list)
2307 (when (setq pos (markdown-calculate-list-levels))
2308 (setq positions (append pos positions)))
2310 ;; First column
2311 (setq positions (cons 0 positions))
2313 ;; Return reversed list
2314 (reverse positions)))
2316 (defun markdown-do-normal-return ()
2317 "Insert a newline and optionally indent the next line."
2318 (newline)
2319 (if markdown-indent-on-enter
2320 (funcall indent-line-function)))
2322 (defun markdown-enter-key ()
2323 "Handle RET according to context.
2324 If there is a wiki link at the point, follow it unless
2325 `markdown-follow-wiki-link-on-enter' is nil. Otherwise, process
2326 it in the usual way."
2327 (interactive)
2328 (if (and markdown-follow-wiki-link-on-enter (markdown-wiki-link-p))
2329 (markdown-follow-wiki-link-at-point)
2330 (markdown-do-normal-return)))
2332 (defun markdown-dedent-or-delete (arg)
2333 "Handle BACKSPACE by cycling through indentation points.
2334 When BACKSPACE is pressed, if there is only whitespace
2335 before the current point, then dedent the line one level.
2336 Otherwise, do normal delete by repeating
2337 `backward-delete-char-untabify' ARG times."
2338 (interactive "*p")
2339 (let ((cur-pos (current-column))
2340 (start-of-indention (save-excursion
2341 (back-to-indentation)
2342 (current-column))))
2343 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
2344 (let ((result 0))
2345 (dolist (i (markdown-calc-indents))
2346 (when (< i cur-pos)
2347 (setq result (max result i))))
2348 (indent-line-to result))
2349 (backward-delete-char-untabify arg))))
2352 ;;; Markup Completion =========================================================
2354 (defconst markdown-complete-alist
2355 '((markdown-regex-header-atx . markdown-complete-atx)
2356 (markdown-regex-header-setext . markdown-complete-setext)
2357 (markdown-regex-hr . markdown-complete-hr))
2358 "Association list of form (regexp . function) for markup completion.")
2360 (defun markdown-incomplete-atx-p ()
2361 "Return t if ATX header markup is incomplete and nil otherwise.
2362 Assumes match data is available for `markdown-regex-header-atx'.
2363 Checks that the number of trailing hash marks equals the number of leading
2364 hash marks, that there is only a single space before and after the text,
2365 and that there is no extraneous whitespace in the text."
2366 (save-match-data
2367 (or (not (= (length (match-string 1)) (length (match-string 3))))
2368 (not (= (match-beginning 2) (1+ (match-end 1))))
2369 (not (= (match-beginning 3) (1+ (match-end 2))))
2370 (string-match "[ \t\n]\\{2\\}" (match-string 2)))))
2372 (defun markdown-complete-atx ()
2373 "Complete and normalize ATX headers.
2374 Add or remove hash marks to the end of the header to match the
2375 beginning. Ensure that there is only a single space between hash
2376 marks and header text. Removes extraneous whitespace from header text.
2377 Assumes match data is available for `markdown-regex-header-atx'."
2378 (when (markdown-incomplete-atx-p)
2379 (let* ((new-marker (make-marker))
2380 (new-marker (set-marker new-marker (match-end 2))))
2381 ;; Hash marks and spacing at end
2382 (goto-char (match-end 2))
2383 (delete-region (match-end 2) (match-end 3))
2384 (insert " " (match-string 1))
2385 ;; Remove extraneous whitespace from title
2386 (replace-match (markdown-compress-whitespace-string (match-string 2))
2387 t t nil 2)
2388 ;; Spacing at beginning
2389 (goto-char (match-end 1))
2390 (delete-region (match-end 1) (match-beginning 2))
2391 (insert " ")
2392 ;; Leave point at end of text
2393 (goto-char new-marker))))
2395 (defun markdown-incomplete-setext-p ()
2396 "Return t if setext header markup is incomplete and nil otherwise.
2397 Assumes match data is available for `markdown-regex-header-setext'.
2398 Checks that length of underline matches text and that there is no
2399 extraneous whitespace in the text."
2400 (save-match-data
2401 (or (not (= (length (match-string 1)) (length (match-string 2))))
2402 (string-match "[ \t\n]\\{2\\}" (match-string 1)))))
2404 (defun markdown-complete-setext ()
2405 "Complete and normalize setext headers.
2406 Add or remove underline characters to match length of header
2407 text. Removes extraneous whitespace from header text. Assumes
2408 match data is available for `markdown-regex-header-setext'."
2409 (when (markdown-incomplete-setext-p)
2410 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
2411 (char (char-after (match-beginning 2)))
2412 (level (if (char-equal char ?-) 2 1)))
2413 (goto-char (match-beginning 0))
2414 (delete-region (match-beginning 0) (match-end 0))
2415 (markdown-insert-header level text t))))
2417 (defun markdown-incomplete-hr-p ()
2418 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
2419 Assumes match data is available for `markdown-regex-hr'."
2420 (not (member (match-string 0) markdown-hr-strings)))
2422 (defun markdown-complete-hr ()
2423 "Complete horizontal rules.
2424 If horizontal rule string is a member of `markdown-hr-strings',
2425 do nothing. Otherwise, replace with the car of
2426 `markdown-hr-strings'.
2427 Assumes match data is available for `markdown-regex-hr'."
2428 (replace-match (car markdown-hr-strings)))
2430 (defun markdown-complete ()
2431 "Complete markup of object near point or in region when active.
2432 Handle all objects in `markdown-complete-alist', in order.
2433 See `markdown-complete-at-point' and `markdown-complete-region'."
2434 (interactive "*")
2435 (if (markdown-use-region-p)
2436 (markdown-complete-region (region-beginning) (region-end))
2437 (markdown-complete-at-point)))
2439 (defun markdown-complete-at-point ()
2440 "Complete markup of object near point.
2441 Handle all objects in `markdown-complete-alist', in
2442 order."
2443 (interactive "*")
2444 (loop for (regexp . function) in markdown-complete-alist
2445 until (thing-at-point-looking-at (eval regexp))
2446 finally (funcall function)))
2448 (defun markdown-complete-region (beg end)
2449 "Complete markup of object near point.
2450 Handle all objects in `markdown-complete-alist', in
2451 order."
2452 (interactive "*r")
2453 (let* ((end-marker (make-marker))
2454 (end-marker (set-marker end-marker end)))
2455 (loop for (regexp . function) in markdown-complete-alist
2456 do (save-excursion
2457 (goto-char beg)
2458 (while (re-search-forward (eval regexp) end-marker t)
2459 (funcall function))))))
2461 (defun markdown-complete-buffer ()
2462 "Complete markup for all objects in the current buffer."
2463 (interactive "*")
2464 (markdown-complete-region (point-min) (point-max)))
2467 ;;; Markup Cycling ============================================================
2469 (defun markdown-cycle-atx (arg &optional remove)
2470 "Cycle ATX header markup.
2471 Promote header (decrease level) when ARG is 1 and demote
2472 header (increase level) if arg is -1. When REMOVE is non-nil,
2473 remove the header when the level reaches zero and stop cycling
2474 when it reaches six. Otherwise, perform a proper cycling through
2475 levels one through six. Assumes match data is available for
2476 `markdown-regex-header-atx'."
2477 (let* ((old-level (length (match-string 1)))
2478 (new-level (+ old-level arg))
2479 (text (match-string 2)))
2480 (when (not remove)
2481 (setq new-level (% new-level 6))
2482 (setq new-level (cond ((= new-level 0) 6)
2483 ((< new-level 0) (+ new-level 6))
2484 (t new-level))))
2485 (cond
2486 ((= new-level 0)
2487 (markdown-unwrap-thing-at-point nil 0 2))
2488 ((<= new-level 6)
2489 (goto-char (match-beginning 0))
2490 (delete-region (match-beginning 0) (match-end 0))
2491 (markdown-insert-header new-level text nil)))))
2493 (defun markdown-cycle-setext (arg &optional remove)
2494 "Cycle setext header markup.
2495 Promote header (increase level) when ARG is 1 and demote
2496 header (decrease level or remove) if arg is -1. When demoting a
2497 level-two setext header, replace with a level-three atx header.
2498 When REMOVE is non-nil, remove the header when the level reaches
2499 zero. Otherwise, cycle back to a level six atx header. Assumes
2500 match data is available for `markdown-regex-header-setext'."
2501 (let* ((char (char-after (match-beginning 2)))
2502 (old-level (if (char-equal char ?=) 1 2))
2503 (new-level (+ old-level arg))
2504 (text (match-string 1)))
2505 (when (and (not remove) (= new-level 0))
2506 (setq new-level 6))
2507 (cond
2508 ((= new-level 0)
2509 (markdown-unwrap-thing-at-point nil 0 1))
2510 ((<= new-level 2)
2511 (markdown-insert-header new-level nil t))
2512 ((<= new-level 6)
2513 (markdown-insert-header new-level nil nil)))))
2515 (defun markdown-cycle-hr (arg &optional remove)
2516 "Cycle string used for horizontal rule from `markdown-hr-strings'.
2517 When ARG is 1, cycle forward (promote), and when ARG is -1, cycle
2518 backwards (demote). When REMOVE is non-nil, remove the hr instead
2519 of cycling when the end of the list is reached.
2520 Assumes match data is available for `markdown-regex-hr'."
2521 (let* ((strings (if (= arg 1)
2522 (reverse markdown-hr-strings)
2523 markdown-hr-strings))
2524 (tail (member (match-string 0) strings))
2525 (new (or (cadr tail)
2526 (if remove
2527 (if (= arg 1)
2529 (car tail))
2530 (car strings)))))
2531 (replace-match new)))
2533 (defun markdown-cycle-bold ()
2534 "Cycle bold markup between underscores and asterisks.
2535 Assumes match data is available for `markdown-regex-bold'."
2536 (save-excursion
2537 (let* ((old-delim (match-string 3))
2538 (new-delim (if (string-equal old-delim "**") "__" "**")))
2539 (replace-match new-delim t t nil 3)
2540 (replace-match new-delim t t nil 5))))
2542 (defun markdown-cycle-italic ()
2543 "Cycle italic markup between underscores and asterisks.
2544 Assumes match data is available for `markdown-regex-italic'."
2545 (save-excursion
2546 (let* ((old-delim (match-string 3))
2547 (new-delim (if (string-equal old-delim "*") "_" "*")))
2548 (replace-match new-delim t t nil 3)
2549 (replace-match new-delim t t nil 5))))
2552 ;;; Keymap ====================================================================
2554 (defvar markdown-mode-map
2555 (let ((map (make-keymap)))
2556 ;; Element insertion
2557 (define-key map "\C-c\C-al" 'markdown-insert-link)
2558 (define-key map "\C-c\C-ar" 'markdown-insert-reference-link-dwim)
2559 (define-key map "\C-c\C-aw" 'markdown-insert-wiki-link)
2560 (define-key map "\C-c\C-ii" 'markdown-insert-image)
2561 (define-key map "\C-c\C-t0" 'markdown-remove-header)
2562 (define-key map "\C-c\C-t1" 'markdown-insert-header-atx-1)
2563 (define-key map "\C-c\C-t2" 'markdown-insert-header-atx-2)
2564 (define-key map "\C-c\C-t3" 'markdown-insert-header-atx-3)
2565 (define-key map "\C-c\C-t4" 'markdown-insert-header-atx-4)
2566 (define-key map "\C-c\C-t5" 'markdown-insert-header-atx-5)
2567 (define-key map "\C-c\C-t6" 'markdown-insert-header-atx-6)
2568 (define-key map "\C-c\C-th" 'markdown-insert-header-dwim)
2569 (define-key map "\C-c\C-pb" 'markdown-insert-bold)
2570 (define-key map "\C-c\C-ss" 'markdown-insert-bold)
2571 (define-key map "\C-c\C-pi" 'markdown-insert-italic)
2572 (define-key map "\C-c\C-se" 'markdown-insert-italic)
2573 (define-key map "\C-c\C-pf" 'markdown-insert-code)
2574 (define-key map "\C-c\C-sc" 'markdown-insert-code)
2575 (define-key map "\C-c\C-sb" 'markdown-insert-blockquote)
2576 (define-key map "\C-c\C-s\C-b" 'markdown-blockquote-region)
2577 (define-key map "\C-c\C-sp" 'markdown-insert-pre)
2578 (define-key map "\C-c\C-s\C-p" 'markdown-pre-region)
2579 (define-key map "\C-c-" 'markdown-insert-hr)
2580 (define-key map "\C-c\C-tt" 'markdown-insert-header-setext-1)
2581 (define-key map "\C-c\C-ts" 'markdown-insert-header-setext-2)
2582 ;; Footnotes
2583 (define-key map "\C-c\C-fn" 'markdown-footnote-new)
2584 (define-key map "\C-c\C-fg" 'markdown-footnote-goto-text)
2585 (define-key map "\C-c\C-fb" 'markdown-footnote-return)
2586 (define-key map "\C-c\C-fk" 'markdown-footnote-kill)
2587 ;; Promotion, Demotion, Completion, and Cycling
2588 (define-key map (kbd "M-<left>") 'markdown-promote)
2589 (define-key map (kbd "M-<right>") 'markdown-demote)
2590 (define-key map (kbd "C-c C-l") 'markdown-promote)
2591 (define-key map (kbd "C-c C-r") 'markdown-demote)
2592 (define-key map (kbd "C-c C-=") 'markdown-complete-or-cycle)
2593 (define-key map (kbd "C-c C-c =") 'markdown-complete-buffer)
2594 ;; Regular Link Following
2595 (define-key map "\C-c\C-o" 'markdown-follow-link-at-point)
2596 ;; WikiLink Following
2597 (define-key map "\C-c\C-w" 'markdown-follow-wiki-link-at-point)
2598 (define-key map "\M-n" 'markdown-next-wiki-link)
2599 (define-key map "\M-p" 'markdown-previous-wiki-link)
2600 ;; Indentation
2601 (define-key map "\C-m" 'markdown-enter-key)
2602 (define-key map (kbd "<backspace>") 'markdown-dedent-or-delete)
2603 ;; Visibility cycling
2604 (define-key map (kbd "<tab>") 'markdown-cycle)
2605 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
2606 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
2607 (define-key map (kbd "<backtab>") 'markdown-shifttab)
2608 ;; Header navigation
2609 (define-key map (kbd "C-M-n") 'outline-next-visible-heading)
2610 (define-key map (kbd "C-M-p") 'outline-previous-visible-heading)
2611 (define-key map (kbd "C-M-f") 'outline-forward-same-level)
2612 (define-key map (kbd "C-M-b") 'outline-backward-same-level)
2613 (define-key map (kbd "C-M-u") 'outline-up-heading)
2614 ;; Markdown functions
2615 (define-key map "\C-c\C-cm" 'markdown-other-window)
2616 (define-key map "\C-c\C-cp" 'markdown-preview)
2617 (define-key map "\C-c\C-ce" 'markdown-export)
2618 (define-key map "\C-c\C-cv" 'markdown-export-and-preview)
2619 (define-key map "\C-c\C-co" 'markdown-open)
2620 (define-key map "\C-c\C-cw" 'markdown-kill-ring-save)
2621 ;; References
2622 (define-key map "\C-c\C-cc" 'markdown-check-refs)
2623 ;; Lists
2624 (define-key map "\C-c\C-cn" 'markdown-cleanup-list-numbers)
2625 (define-key map (kbd "M-<up>") 'markdown-move-up)
2626 (define-key map (kbd "M-<down>") 'markdown-move-down)
2627 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
2628 ;; Movement
2629 (define-key map (kbd "M-[") 'markdown-beginning-of-block)
2630 (define-key map (kbd "M-]") 'markdown-end-of-block)
2631 map)
2632 "Keymap for Markdown major mode.")
2634 (defvar gfm-mode-map
2635 (let ((map (make-sparse-keymap)))
2636 (set-keymap-parent map markdown-mode-map)
2637 (define-key map "\C-c\C-sl" 'markdown-insert-gfm-code-block)
2638 map)
2639 "Keymap for `gfm-mode'.
2640 See also `markdown-mode-map'.")
2643 ;;; Menu ==================================================================
2645 (easy-menu-define markdown-mode-menu markdown-mode-map
2646 "Menu for Markdown mode"
2647 '("Markdown"
2648 ("Show/Hide"
2649 ["Cycle visibility" markdown-cycle (outline-on-heading-p)]
2650 ["Cycle global visibility" markdown-shifttab])
2651 "---"
2652 ["Compile" markdown-other-window]
2653 ["Preview" markdown-preview]
2654 ["Export" markdown-export]
2655 ["Export & View" markdown-export-and-preview]
2656 ["Open" markdown-open]
2657 ["Kill ring save" markdown-kill-ring-save]
2658 "---"
2659 ("Headers (setext)"
2660 ["First level" markdown-insert-setext-header-1]
2661 ["Second level" markdown-insert-setext-header-2])
2662 ("Headers (atx)"
2663 ["First level" markdown-insert-header-atx-1]
2664 ["Second level" markdown-insert-header-atx-2]
2665 ["Third level" markdown-insert-header-atx-3]
2666 ["Fourth level" markdown-insert-header-atx-4]
2667 ["Fifth level" markdown-insert-header-atx-5]
2668 ["Sixth level" markdown-insert-header-atx-6])
2669 "---"
2670 ["Bold" markdown-insert-bold]
2671 ["Italic" markdown-insert-italic]
2672 ["Blockquote" markdown-insert-blockquote]
2673 ["Preformatted" markdown-insert-pre]
2674 ["Code" markdown-insert-code]
2675 "---"
2676 ["Insert inline link" markdown-insert-link]
2677 ["Insert reference link" markdown-insert-reference-link-dwim]
2678 ["Insert image" markdown-insert-image]
2679 ["Insert horizontal rule" markdown-insert-hr]
2680 "---"
2681 ("Footnotes"
2682 ["Insert footnote" markdown-footnote-new]
2683 ["Jump to footnote text" markdown-footnote-goto-text]
2684 ["Return from footnote" markdown-footnote-return])
2685 "---"
2686 ["Check references" markdown-check-refs]
2687 ["Clean up list numbering" markdown-cleanup-list-numbers]
2688 "---"
2689 ["Version" markdown-show-version]
2693 ;;; imenu =====================================================================
2695 (defun markdown-imenu-create-index ()
2696 "Create and return an imenu index alist for the current buffer.
2697 See `imenu-create-index-function' and `imenu--index-alist' for details."
2698 (let* ((root '(nil . nil))
2699 cur-alist
2700 (cur-level 0)
2701 (empty-heading "-")
2702 (self-heading ".")
2703 hashes pos level heading)
2704 (save-excursion
2705 (goto-char (point-min))
2706 (while (re-search-forward markdown-regex-header (point-max) t)
2707 (cond
2708 ((setq heading (match-string-no-properties 1))
2709 (setq pos (match-beginning 1)
2710 level 1))
2711 ((setq heading (match-string-no-properties 3))
2712 (setq pos (match-beginning 3)
2713 level 2))
2714 ((setq hashes (match-string-no-properties 5))
2715 (setq heading (match-string-no-properties 6)
2716 pos (match-beginning 5)
2717 level (length hashes))))
2718 (let ((alist (list (cons heading pos))))
2719 (cond
2720 ((= cur-level level) ; new sibling
2721 (setcdr cur-alist alist)
2722 (setq cur-alist alist))
2723 ((< cur-level level) ; first child
2724 (dotimes (i (- level cur-level 1))
2725 (setq alist (list (cons empty-heading alist))))
2726 (if cur-alist
2727 (let* ((parent (car cur-alist))
2728 (self-pos (cdr parent)))
2729 (setcdr parent (cons (cons self-heading self-pos) alist)))
2730 (setcdr root alist)) ; primogenitor
2731 (setq cur-alist alist)
2732 (setq cur-level level))
2733 (t ; new sibling of an ancestor
2734 (let ((sibling-alist (last (cdr root))))
2735 (dotimes (i (1- level))
2736 (setq sibling-alist (last (cdar sibling-alist))))
2737 (setcdr sibling-alist alist)
2738 (setq cur-alist alist))
2739 (setq cur-level level)))))
2740 (cdr root))))
2743 ;;; Reference Checking ========================================================
2745 (defconst markdown-refcheck-buffer
2746 "*Undefined references for %buffer%*"
2747 "Pattern for name of buffer for listing undefined references.
2748 The string %buffer% will be replaced by the corresponding
2749 `markdown-mode' buffer name.")
2751 (defun markdown-has-reference-definition (reference)
2752 "Find out whether Markdown REFERENCE is defined.
2753 REFERENCE should include the square brackets, like [this]."
2754 (let ((reference (downcase reference)))
2755 (save-excursion
2756 (goto-char (point-min))
2757 (catch 'found
2758 (while (re-search-forward markdown-regex-reference-definition nil t)
2759 (when (string= reference (downcase (match-string-no-properties 1)))
2760 (throw 'found (match-string-no-properties 2))))))))
2762 (defun markdown-get-undefined-refs ()
2763 "Return a list of undefined Markdown references.
2764 Result is an alist of pairs (reference . occurrences), where
2765 occurrences is itself another alist of pairs (label . line-number).
2766 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
2767 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
2768 \((\"[emacs]\" (\"[Nice editor]\" . 12) (\"[GNU Emacs]\" . 45)) (\"[elisp]\" (\"[manual]\" . 127)))."
2769 (let ((missing))
2770 (save-excursion
2771 (goto-char (point-min))
2772 (while
2773 (re-search-forward markdown-regex-link-reference nil t)
2774 (let* ((label (match-string-no-properties 1))
2775 (reference (match-string-no-properties 2))
2776 (target (downcase (if (string= reference "[]") label reference))))
2777 (unless (markdown-has-reference-definition target)
2778 (let ((entry (assoc target missing)))
2779 (if (not entry)
2780 (add-to-list 'missing (cons target
2781 (list (cons label (markdown-line-number-at-pos)))) t)
2782 (setcdr entry
2783 (append (cdr entry) (list (cons label (markdown-line-number-at-pos))))))))))
2784 missing)))
2786 (defun markdown-add-missing-ref-definition (ref buffer &optional recheck)
2787 "Add blank REF definition to the end of BUFFER.
2788 REF is a Markdown reference in square brackets, like \"[lisp-history]\".
2789 When RECHECK is non-nil, BUFFER gets rechecked for undefined
2790 references so that REF disappears from the list of those links."
2791 (with-current-buffer buffer
2792 (when (not (eq major-mode 'markdown-mode))
2793 (error "Not available in current mode"))
2794 (goto-char (point-max))
2795 (indent-new-comment-line)
2796 (insert (concat ref ": ")))
2797 (switch-to-buffer-other-window buffer)
2798 (goto-char (point-max))
2799 (when recheck
2800 (markdown-check-refs t)))
2802 ;; Button which adds an empty Markdown reference definition to the end
2803 ;; of buffer specified as its 'target-buffer property. Reference name
2804 ;; is button's label
2805 (when (>= emacs-major-version 22)
2806 (define-button-type 'markdown-ref-button
2807 'help-echo "Push to create an empty reference definition"
2808 'face 'bold
2809 'action (lambda (b)
2810 (markdown-add-missing-ref-definition
2811 (button-label b) (button-get b 'target-buffer) t))))
2813 ;; Button jumping to line in buffer specified as its 'target-buffer
2814 ;; property. Line number is button's 'line property.
2815 (when (>= emacs-major-version 22)
2816 (define-button-type 'goto-line-button
2817 'help-echo "Push to go to this line"
2818 'face 'italic
2819 'action (lambda (b)
2820 (message (button-get b 'buffer))
2821 (switch-to-buffer-other-window (button-get b 'target-buffer))
2822 ;; use call-interactively to silence compiler
2823 (call-interactively 'goto-line (button-get b 'target-line)))))
2825 (defun markdown-check-refs (&optional silent)
2826 "Show all undefined Markdown references in current `markdown-mode' buffer.
2827 If SILENT is non-nil, do not message anything when no undefined
2828 references found.
2829 Links which have empty reference definitions are considered to be
2830 defined."
2831 (interactive "P")
2832 (when (not (eq major-mode 'markdown-mode))
2833 (error "Not available in current mode"))
2834 (let ((oldbuf (current-buffer))
2835 (refs (markdown-get-undefined-refs))
2836 (refbuf (get-buffer-create (markdown-replace-regexp-in-string
2837 "%buffer%" (buffer-name)
2838 markdown-refcheck-buffer))))
2839 (if (null refs)
2840 (progn
2841 (when (not silent)
2842 (message "No undefined references found"))
2843 (kill-buffer refbuf))
2844 (with-current-buffer refbuf
2845 (when view-mode
2846 (View-exit-and-edit))
2847 (erase-buffer)
2848 (insert "Following references lack definitions:")
2849 (newline 2)
2850 (dolist (ref refs)
2851 (let ((button-label (format "%s" (car ref))))
2852 (if (>= emacs-major-version 22)
2853 ;; Create a reference button in Emacs 22
2854 (insert-text-button button-label
2855 :type 'markdown-ref-button
2856 'target-buffer oldbuf)
2857 ;; Insert reference as text in Emacs < 22
2858 (insert button-label)))
2859 (insert " (")
2860 (dolist (occurrence (cdr ref))
2861 (let ((line (cdr occurrence)))
2862 (if (>= emacs-major-version 22)
2863 ;; Create a line number button in Emacs 22
2864 (insert-button (number-to-string line)
2865 :type 'goto-line-button
2866 'target-buffer oldbuf
2867 'target-line line)
2868 ;; Insert line number as text in Emacs < 22
2869 (insert (number-to-string line)))
2870 (insert " "))) (delete-char -1)
2871 (insert ")")
2872 (newline))
2873 (view-buffer-other-window refbuf)
2874 (goto-char (point-min))
2875 (forward-line 2)))))
2878 ;;; Lists =====================================================================
2880 (defun markdown-insert-list-item (&optional arg)
2881 "Insert a new list item.
2882 If the point is inside unordered list, insert a bullet mark. If
2883 the point is inside ordered list, insert the next number followed
2884 by a period. Use the previous list item to determine the amount
2885 of whitespace to place before and after list markers.
2887 With a \\[universal-argument] prefix (i.e., when ARG is 4),
2888 decrease the indentation by one level.
2890 With two \\[universal-argument] prefixes (i.e., when ARG is 16),
2891 increase the indentation by one level."
2892 (interactive "p")
2893 (let (bounds item-indent marker indent new-indent end)
2894 (save-match-data
2895 (setq bounds (markdown-cur-list-item-bounds))
2896 (if (not bounds)
2897 ;; When not in a list, start a new unordered one
2898 (progn
2899 (unless (markdown-cur-line-blank-p)
2900 (insert "\n"))
2901 (insert "* "))
2902 ;; Compute indentation for a new list item
2903 (setq item-indent (nth 2 bounds))
2904 (setq marker (concat (match-string 2) (match-string 3)))
2905 (setq indent (cond
2906 ((= arg 4) (max (- item-indent 4) 0))
2907 ((= arg 16) (+ item-indent 4))
2908 (t item-indent)))
2909 (setq new-indent (make-string indent 32))
2910 (goto-char (nth 1 bounds))
2911 (newline)
2912 (cond
2913 ;; Ordered list
2914 ((string-match "[0-9]" marker)
2915 (if (= arg 16) ;; starting a new column indented one more level
2916 (insert (concat new-indent "1. "))
2917 ;; travel up to the last item and pick the correct number. If
2918 ;; the argument was nil, "new-indent = item-indent" is the same,
2919 ;; so we don't need special treatment. Neat.
2920 (save-excursion
2921 (while (not (looking-at (concat new-indent "\\([0-9]+\\)\\.")))
2922 (forward-line -1)))
2923 (insert (concat new-indent
2924 (int-to-string (1+ (string-to-number (match-string 1))))
2925 ". "))))
2926 ;; Unordered list
2927 ((string-match "[\\*\\+-]" marker)
2928 (insert (concat new-indent marker))))))))
2930 (defun markdown-move-list-item-up ()
2931 "Move the current list item up in the list when possible."
2932 (interactive)
2933 (let (cur prev old)
2934 (when (setq cur (markdown-cur-list-item-bounds))
2935 (setq old (point))
2936 (goto-char (nth 0 cur))
2937 (if (markdown-prev-list-item (nth 3 cur))
2938 (progn
2939 (setq prev (markdown-cur-list-item-bounds))
2940 (condition-case nil
2941 (progn
2942 (transpose-regions (nth 0 prev) (nth 1 prev)
2943 (nth 0 cur) (nth 1 cur) t)
2944 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
2945 ;; Catch error in case regions overlap.
2946 (error (goto-char old))))
2947 (goto-char old)))))
2949 (defun markdown-move-list-item-down ()
2950 "Move the current list item down in the list when possible."
2951 (interactive)
2952 (let (cur next old)
2953 (when (setq cur (markdown-cur-list-item-bounds))
2954 (setq old (point))
2955 (if (markdown-next-list-item (nth 3 cur))
2956 (progn
2957 (setq next (markdown-cur-list-item-bounds))
2958 (condition-case nil
2959 (progn
2960 (transpose-regions (nth 0 cur) (nth 1 cur)
2961 (nth 0 next) (nth 1 next) nil)
2962 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
2963 ;; Catch error in case regions overlap.
2964 (error (goto-char old))))
2965 (goto-char old)))))
2967 (defun markdown-demote-list-item (&optional bounds)
2968 "Indent (or demote) the current list item.
2969 Optionally, BOUNDS of the current list item may be provided if available."
2970 (interactive)
2971 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
2972 (save-excursion
2973 (save-match-data
2974 (let* ((end-marker (make-marker))
2975 (end-marker (set-marker end-marker (nth 1 bounds))))
2976 (goto-char (nth 0 bounds))
2977 (while (< (point) end-marker)
2978 (unless (markdown-cur-line-blank-p)
2979 (insert " "))
2980 (forward-line)))))))
2982 (defun markdown-promote-list-item (&optional bounds)
2983 "Unindent (or promote) the current list item.
2984 Optionally, BOUNDS of the current list item may be provided if available."
2985 (interactive)
2986 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
2987 (save-excursion
2988 (save-match-data
2989 (let* ((end-marker (make-marker))
2990 (end-marker (set-marker end-marker (nth 1 bounds)))
2991 num regexp)
2992 (goto-char (nth 0 bounds))
2993 (when (looking-at "^[ ]\\{1,4\\}")
2994 (setq num (- (match-end 0) (match-beginning 0)))
2995 (setq regexp (format "^[ ]\\{1,%d\\}" num))
2996 (while (and (< (point) end-marker)
2997 (re-search-forward regexp end-marker t))
2998 (replace-match "" nil nil)
2999 (forward-line))))))))
3001 (defun markdown--cleanup-list-numbers-level (&optional pfx)
3002 "Update the numbering for level PFX (as a string of spaces).
3004 Assume that the previously found match was for a numbered item in
3005 a list."
3006 (let ((cpfx pfx)
3007 (idx 0)
3008 (continue t)
3009 (step t)
3010 (sep nil))
3011 (while (and continue (not (eobp)))
3012 (setq step t)
3013 (cond
3014 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
3015 (setq cpfx (match-string-no-properties 1))
3016 (cond
3017 ((string= cpfx pfx)
3018 (replace-match
3019 (concat pfx (number-to-string (setq idx (1+ idx))) ". "))
3020 (setq sep nil))
3021 ;; indented a level
3022 ((string< pfx cpfx)
3023 (setq sep (markdown--cleanup-list-numbers-level cpfx))
3024 (setq step nil))
3025 ;; exit the loop
3027 (setq step nil)
3028 (setq continue nil))))
3030 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
3031 (setq cpfx (match-string-no-properties 1))
3032 (cond
3033 ;; reset if separated before
3034 ((string= cpfx pfx) (when sep (setq idx 0)))
3035 ((string< cpfx pfx)
3036 (setq step nil)
3037 (setq continue nil))))
3038 (t (setq sep t)))
3040 (when step
3041 (beginning-of-line)
3042 (setq continue (= (forward-line) 0))))
3043 sep))
3045 (defun markdown-cleanup-list-numbers ()
3046 "Update the numbering of ordered lists."
3047 (interactive)
3048 (save-excursion
3049 (goto-char (point-min))
3050 (markdown--cleanup-list-numbers-level "")))
3053 ;;; Outline ===================================================================
3055 (defvar markdown-cycle-global-status 1)
3056 (defvar markdown-cycle-subtree-status nil)
3058 (defun markdown-end-of-subtree (&optional invisible-OK)
3059 "Move to the end of the current subtree.
3060 Only visible heading lines are considered, unless INVISIBLE-OK is
3061 non-nil.
3062 Derived from `org-end-of-subtree'."
3063 (outline-back-to-heading invisible-OK)
3064 (let ((first t)
3065 (level (funcall outline-level)))
3066 (while (and (not (eobp))
3067 (or first (> (funcall outline-level) level)))
3068 (setq first nil)
3069 (outline-next-heading))
3070 (if (memq (preceding-char) '(?\n ?\^M))
3071 (progn
3072 ;; Go to end of line before heading
3073 (forward-char -1)
3074 (if (memq (preceding-char) '(?\n ?\^M))
3075 ;; leave blank line before heading
3076 (forward-char -1)))))
3077 (point))
3079 (defun markdown-cycle (&optional arg)
3080 "Visibility cycling for Markdown mode.
3081 If ARG is t, perform global visibility cycling. If the point is
3082 at an atx-style header, cycle visibility of the corresponding
3083 subtree. Otherwise, insert a tab using `indent-relative'.
3084 Derived from `org-cycle'."
3085 (interactive "P")
3086 (cond
3087 ((eq arg t) ;; Global cycling
3088 (cond
3089 ((and (eq last-command this-command)
3090 (eq markdown-cycle-global-status 2))
3091 ;; Move from overview to contents
3092 (hide-sublevels 1)
3093 (message "CONTENTS")
3094 (setq markdown-cycle-global-status 3))
3096 ((and (eq last-command this-command)
3097 (eq markdown-cycle-global-status 3))
3098 ;; Move from contents to all
3099 (show-all)
3100 (message "SHOW ALL")
3101 (setq markdown-cycle-global-status 1))
3104 ;; Defaults to overview
3105 (hide-body)
3106 (message "OVERVIEW")
3107 (setq markdown-cycle-global-status 2))))
3109 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3110 ;; At a heading: rotate between three different views
3111 (outline-back-to-heading)
3112 (let ((goal-column 0) eoh eol eos)
3113 ;; Determine boundaries
3114 (save-excursion
3115 (outline-back-to-heading)
3116 (save-excursion
3117 (beginning-of-line 2)
3118 (while (and (not (eobp)) ;; this is like `next-line'
3119 (get-char-property (1- (point)) 'invisible))
3120 (beginning-of-line 2)) (setq eol (point)))
3121 (outline-end-of-heading) (setq eoh (point))
3122 (markdown-end-of-subtree t)
3123 (skip-chars-forward " \t\n")
3124 (beginning-of-line 1) ; in case this is an item
3125 (setq eos (1- (point))))
3126 ;; Find out what to do next and set `this-command'
3127 (cond
3128 ((= eos eoh)
3129 ;; Nothing is hidden behind this heading
3130 (message "EMPTY ENTRY")
3131 (setq markdown-cycle-subtree-status nil))
3132 ((>= eol eos)
3133 ;; Entire subtree is hidden in one line: open it
3134 (show-entry)
3135 (show-children)
3136 (message "CHILDREN")
3137 (setq markdown-cycle-subtree-status 'children))
3138 ((and (eq last-command this-command)
3139 (eq markdown-cycle-subtree-status 'children))
3140 ;; We just showed the children, now show everything.
3141 (show-subtree)
3142 (message "SUBTREE")
3143 (setq markdown-cycle-subtree-status 'subtree))
3145 ;; Default action: hide the subtree.
3146 (hide-subtree)
3147 (message "FOLDED")
3148 (setq markdown-cycle-subtree-status 'folded)))))
3151 (indent-for-tab-command))))
3153 (defun markdown-shifttab ()
3154 "Global visibility cycling.
3155 Calls `markdown-cycle' with argument t."
3156 (interactive)
3157 (markdown-cycle t))
3159 (defun markdown-outline-level ()
3160 "Return the depth to which a statement is nested in the outline."
3161 (cond
3162 ((match-end 1) 1)
3163 ((match-end 3) 2)
3164 ((- (match-end 5) (match-beginning 5)))))
3167 ;;; Movement ==================================================================
3169 (defun markdown-beginning-of-defun (&optional arg)
3170 "`beginning-of-defun-function' for Markdown.
3171 Move backward to the beginning of the current or previous section."
3172 (interactive "P")
3173 (or arg (setq arg 1))
3174 (or (re-search-backward markdown-regex-header nil t arg)
3175 (goto-char (point-min))))
3177 (defun markdown-end-of-defun (&optional arg)
3178 "`end-of-defun-function' for Markdown.
3179 Move forward to the end of the current or following section."
3180 (interactive "P")
3181 (or arg (setq arg 1))
3182 (when (looking-at markdown-regex-header)
3183 (goto-char (match-beginning 0))
3184 (forward-char 1))
3185 (if (re-search-forward markdown-regex-header nil t arg)
3186 (goto-char (match-beginning 0))
3187 (goto-char (point-max)))
3188 (skip-syntax-backward "-"))
3190 (defun markdown-beginning-of-block ()
3191 "Move the point to the start of the previous text block."
3192 (interactive)
3193 (if (re-search-backward markdown-regex-block-separator nil t)
3194 (goto-char (or (match-end 2) (match-end 0)))
3195 (goto-char (point-min))))
3197 (defun markdown-end-of-block ()
3198 "Move the point to the start of the next text block."
3199 (interactive)
3200 (beginning-of-line)
3201 (skip-syntax-forward "-")
3202 (when (= (point) (point-min))
3203 (forward-char))
3204 (if (re-search-forward markdown-regex-block-separator nil t)
3205 (goto-char (or (match-end 2) (match-end 0)))
3206 (goto-char (point-max)))
3207 (skip-syntax-backward "-")
3208 (forward-line))
3210 (defun markdown-end-of-block-element ()
3211 "Move the point to the start of the next block unit.
3212 Stops at blank lines, list items, headers, and horizontal rules."
3213 (interactive)
3214 (forward-line)
3215 (while (and (or (not (markdown-prev-line-blank-p))
3216 (markdown-cur-line-blank-p))
3217 (not (or (looking-at markdown-regex-list)
3218 (looking-at markdown-regex-header)
3219 (looking-at markdown-regex-hr)))
3220 (not (eobp)))
3221 (forward-line)))
3224 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
3226 (defun markdown-move-up ()
3227 "Move list item up.
3228 Calls `markdown-move-list-item-up'."
3229 (interactive)
3230 (markdown-move-list-item-up))
3232 (defun markdown-move-down ()
3233 "Move list item down.
3234 Calls `markdown-move-list-item-down'."
3235 (interactive)
3236 (markdown-move-list-item-down))
3238 (defun markdown-promote ()
3239 "Either promote header or list item at point or cycle markup.
3240 See `markdown-cycle-atx', `markdown-cycle-setext', and
3241 `markdown-demote-list-item'."
3242 (interactive)
3243 (let (bounds)
3244 (cond
3245 ;; Promote atx header
3246 ((thing-at-point-looking-at markdown-regex-header-atx)
3247 (markdown-cycle-atx -1 t))
3248 ;; Promote setext header
3249 ((thing-at-point-looking-at markdown-regex-header-setext)
3250 (markdown-cycle-setext -1 t))
3251 ;; Promote horizonal rule
3252 ((thing-at-point-looking-at markdown-regex-hr)
3253 (markdown-cycle-hr -1 t))
3254 ;; Promote list item
3255 ((setq bounds (markdown-cur-list-item-bounds))
3256 (markdown-promote-list-item)))))
3258 (defun markdown-demote ()
3259 "Either demote header or list item at point or cycle or remove markup.
3260 See `markdown-cycle-atx', `markdown-cycle-setext', and
3261 `markdown-demote-list-item'."
3262 (interactive)
3263 (let (bounds)
3264 (cond
3265 ;; Demote atx header
3266 ((thing-at-point-looking-at markdown-regex-header-atx)
3267 (markdown-cycle-atx 1 t))
3268 ;; Demote setext header
3269 ((thing-at-point-looking-at markdown-regex-header-setext)
3270 (markdown-cycle-setext 1 t))
3271 ;; Demote horizonal rule
3272 ((thing-at-point-looking-at markdown-regex-hr)
3273 (markdown-cycle-hr 1 t))
3274 ;; Promote list item
3275 ((setq bounds (markdown-cur-list-item-bounds))
3276 (markdown-demote-list-item))
3277 ;; Create a new level one ATX header
3279 (markdown-insert-header-atx-1)))))
3281 (defun markdown-complete-or-cycle (arg)
3282 "Complete or cycle markup of object at point or complete objects in region.
3283 If there is an active region, complete markup in region.
3284 Otherwise, complete or cycle markup of object near point.
3285 When ARG is non-nil, cycle backwards when cycling."
3286 (interactive "*P")
3287 (if (markdown-use-region-p)
3288 ;; Complete markup in region
3289 (markdown-complete-region (region-beginning) (region-end))
3290 ;; Complete or cycle markup at point
3291 (let ((dir (if arg -1 1))
3292 bounds)
3293 (cond
3294 ;; atx header
3295 ((thing-at-point-looking-at markdown-regex-header-atx)
3296 (if (markdown-incomplete-atx-p)
3297 (markdown-complete-atx)
3298 (markdown-cycle-atx dir)))
3299 ;; setext header
3300 ((thing-at-point-looking-at markdown-regex-header-setext)
3301 (if (markdown-incomplete-setext-p)
3302 (markdown-complete-setext)
3303 (markdown-cycle-setext dir)))
3304 ;; horizonal rule
3305 ((thing-at-point-looking-at markdown-regex-hr)
3306 (if (markdown-incomplete-hr-p)
3307 (markdown-complete-hr)
3308 (markdown-cycle-hr dir)))
3309 ;; bold
3310 ((thing-at-point-looking-at markdown-regex-bold)
3311 (markdown-cycle-bold))
3312 ;; italic
3313 ((thing-at-point-looking-at markdown-regex-italic)
3314 (markdown-cycle-italic))))))
3317 ;;; Commands ==================================================================
3319 (defun markdown (&optional output-buffer-name)
3320 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
3321 The output buffer name defaults to `markdown-output-buffer-name'.
3322 Return the name of the output buffer used."
3323 (interactive)
3324 (save-window-excursion
3325 (let ((begin-region)
3326 (end-region))
3327 (if (markdown-use-region-p)
3328 (setq begin-region (region-beginning)
3329 end-region (region-end))
3330 (setq begin-region (point-min)
3331 end-region (point-max)))
3333 (unless output-buffer-name
3334 (setq output-buffer-name markdown-output-buffer-name))
3336 (cond
3337 ;; Handle case when `markdown-command' does not read from stdin
3338 (markdown-command-needs-filename
3339 (if (not buffer-file-name)
3340 (error "Must be visiting a file")
3341 (shell-command (concat markdown-command " "
3342 (shell-quote-argument buffer-file-name))
3343 output-buffer-name)))
3344 ;; Pass region to `markdown-command' via stdin
3346 (shell-command-on-region begin-region end-region markdown-command
3347 output-buffer-name))))
3348 output-buffer-name))
3350 (defun markdown-standalone (&optional output-buffer-name)
3351 "Special function to provide standalone HTML output.
3352 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
3353 (interactive)
3354 (setq output-buffer-name (markdown output-buffer-name))
3355 (with-current-buffer output-buffer-name
3356 (set-buffer output-buffer-name)
3357 (goto-char (point-min))
3358 (unless (markdown-output-standalone-p)
3359 (markdown-add-xhtml-header-and-footer output-buffer-name))
3360 (html-mode))
3361 output-buffer-name)
3363 (defun markdown-other-window (&optional output-buffer-name)
3364 "Run `markdown-command' on current buffer and display in other window.
3365 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
3366 that name."
3367 (interactive)
3368 (display-buffer (markdown-standalone output-buffer-name)))
3370 (defun markdown-output-standalone-p ()
3371 "Determine whether `markdown-command' output is standalone XHTML.
3372 Standalone XHTML output is identified by an occurrence of
3373 `markdown-xhtml-standalone-regexp' in the first five lines of output."
3374 (re-search-forward
3375 markdown-xhtml-standalone-regexp
3376 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
3379 (defun markdown-add-xhtml-header-and-footer (title)
3380 "Wrap XHTML header and footer with given TITLE around current buffer."
3381 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
3382 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
3383 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
3384 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
3385 "<head>\n<title>")
3386 (insert title)
3387 (insert "</title>\n")
3388 (when (> (length markdown-content-type) 0)
3389 (insert
3390 (format
3391 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
3392 markdown-content-type
3393 (or (and markdown-coding-system
3394 (fboundp 'coding-system-get)
3395 (coding-system-get markdown-coding-system
3396 'mime-charset))
3397 (and (fboundp 'coding-system-get)
3398 (coding-system-get buffer-file-coding-system
3399 'mime-charset))
3400 "iso-8859-1"))))
3401 (if (> (length markdown-css-path) 0)
3402 (insert "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
3403 markdown-css-path
3404 "\" />\n"))
3405 (when (> (length markdown-xhtml-header-content) 0)
3406 (insert markdown-xhtml-header-content))
3407 (insert "\n</head>\n\n"
3408 "<body>\n\n")
3409 (goto-char (point-max))
3410 (insert "\n"
3411 "</body>\n"
3412 "</html>\n"))
3414 (defun markdown-preview (&optional output-buffer-name)
3415 "Run `markdown-command' on the current buffer and view output in browser.
3416 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
3417 that name."
3418 (interactive)
3419 (browse-url-of-buffer (markdown markdown-output-buffer-name)))
3421 (defun markdown-export-file-name (&optional extension)
3422 "Attempt to generate a filename for Markdown output.
3423 The file extension will be EXTENSION if given, or .html by default.
3424 If the current buffer is visiting a file, we construct a new
3425 output filename based on that filename. Otherwise, return nil."
3426 (when (buffer-file-name)
3427 (unless extension
3428 (setq extension ".html"))
3429 (concat
3430 (cond
3431 ((buffer-file-name)
3432 (file-name-sans-extension (buffer-file-name)))
3433 (t (buffer-name)))
3434 extension)))
3436 (defun markdown-export (&optional output-file)
3437 "Run Markdown on the current buffer, save to file, and return the filename.
3438 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
3439 generated by `markdown-export-file-name', which will be constructed using the
3440 current filename, but with the extension removed and replaced with .html."
3441 (interactive)
3442 (unless output-file
3443 (setq output-file (markdown-export-file-name ".html")))
3444 (when output-file
3445 (let ((output-buffer-name))
3446 (setq output-buffer-name (buffer-name (find-file-noselect output-file)))
3447 (run-hook-with-args 'markdown-before-export-hooks output-file)
3448 (markdown-standalone output-buffer-name)
3449 (with-current-buffer output-buffer-name
3450 (save-buffer))
3451 (run-hook-with-args 'markdown-after-export-hooks output-file)
3452 output-file)))
3454 (defun markdown-export-and-preview ()
3455 "Export to XHTML using `markdown-export' and browse the resulting file."
3456 (interactive)
3457 (browse-url (markdown-export)))
3459 (defun markdown-open ()
3460 "Open file for the current buffer with `markdown-open-command'."
3461 (interactive)
3462 (if (not markdown-open-command)
3463 (error "Variable `markdown-open-command' must be set")
3464 (if (not buffer-file-name)
3465 (error "Must be visiting a file")
3466 (call-process markdown-open-command
3467 nil nil nil buffer-file-name))))
3469 (defun markdown-kill-ring-save ()
3470 "Run Markdown on file and store output in the kill ring."
3471 (interactive)
3472 (save-window-excursion
3473 (markdown)
3474 (with-current-buffer markdown-output-buffer-name
3475 (kill-ring-save (point-min) (point-max)))))
3478 ;;; Links =====================================================================
3480 (require 'thingatpt)
3482 (defun markdown-link-p ()
3483 "Return non-nil when `point' is at a non-wiki link.
3484 See `markdown-wiki-link-p' for more information."
3485 (let ((case-fold-search nil))
3486 (and (not (markdown-wiki-link-p))
3487 (or (thing-at-point-looking-at markdown-regex-link-inline)
3488 (thing-at-point-looking-at markdown-regex-link-reference)
3489 (thing-at-point-looking-at markdown-regex-uri)
3490 (thing-at-point-looking-at markdown-regex-angle-uri)))))
3492 (defun markdown-link-link ()
3493 "Return the link part of the regular (non-wiki) link at point.
3494 Works with both inline and reference style links. If point is
3495 not at a link or the link reference is not defined returns nil."
3496 (cond
3497 ((thing-at-point-looking-at markdown-regex-link-inline)
3498 (substring-no-properties (match-string 2) 1 -1))
3499 ((thing-at-point-looking-at markdown-regex-link-reference)
3500 (let* ((label (match-string-no-properties 1))
3501 (reference (match-string-no-properties 2))
3502 (target (downcase (if (string= reference "[]") label reference))))
3503 (markdown-has-reference-definition target)))
3504 ((thing-at-point-looking-at markdown-regex-uri)
3505 (match-string-no-properties 0))
3506 ((thing-at-point-looking-at markdown-regex-angle-uri)
3507 (match-string-no-properties 2))
3508 (t nil)))
3510 (defun markdown-follow-link-at-point ()
3511 "Open the current non-wiki link in a browser."
3512 (interactive)
3513 (if (markdown-link-p) (browse-url (markdown-link-link))
3514 (error "Point is not at a Markdown link or URI")))
3517 ;;; WikiLink Following/Markup =================================================
3519 (defun markdown-wiki-link-p ()
3520 "Return non-nil when `point' is at a true wiki link.
3521 A true wiki link name matches `markdown-regex-wiki-link' but does not
3522 match the current file name after conversion. This modifies the data
3523 returned by `match-data'. Note that the potential wiki link name must
3524 be available via `match-string'."
3525 (let ((case-fold-search nil))
3526 (and (thing-at-point-looking-at markdown-regex-wiki-link)
3527 (or (not buffer-file-name)
3528 (not (string-equal (buffer-file-name)
3529 (markdown-convert-wiki-link-to-filename
3530 (markdown-wiki-link-link)))))
3531 (not (save-match-data
3532 (save-excursion))))))
3534 (defun markdown-wiki-link-link ()
3535 "Return the link part of the wiki link using current match data.
3536 The location of the link component depends on the value of
3537 `markdown-wiki-link-alias-first'."
3538 (if markdown-wiki-link-alias-first
3539 (or (match-string-no-properties 4) (match-string-no-properties 2))
3540 (match-string-no-properties 2)))
3542 (defun markdown-convert-wiki-link-to-filename (name)
3543 "Generate a filename from the wiki link NAME.
3544 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
3545 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
3546 and [[test test]] both map to Test-test.ext."
3547 (let ((basename (markdown-replace-regexp-in-string
3548 "[[:space:]\n]" markdown-link-space-sub-char name)))
3549 (when (eq major-mode 'gfm-mode)
3550 (setq basename (concat (upcase (substring basename 0 1))
3551 (downcase (substring basename 1 nil)))))
3552 (concat basename
3553 (if (buffer-file-name)
3554 (concat "."
3555 (file-name-extension (buffer-file-name)))))))
3557 (defun markdown-follow-wiki-link (name &optional other)
3558 "Follow the wiki link NAME.
3559 Convert the name to a file name and call `find-file'. Ensure that
3560 the new buffer remains in `markdown-mode'. Open the link in another
3561 window when OTHER is non-nil."
3562 (let ((filename (markdown-convert-wiki-link-to-filename name))
3563 (wp (file-name-directory buffer-file-name)))
3564 (when other (other-window 1))
3565 (find-file (concat wp filename)))
3566 (when (not (eq major-mode 'markdown-mode))
3567 (markdown-mode)))
3569 (defun markdown-follow-wiki-link-at-point (&optional arg)
3570 "Find Wiki Link at point.
3571 With prefix argument ARG, open the file in other window.
3572 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
3573 (interactive "P")
3574 (if (markdown-wiki-link-p)
3575 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
3576 (error "Point is not at a Wiki Link")))
3578 (defun markdown-next-wiki-link ()
3579 "Jump to next wiki link.
3580 If successful, return point. Otherwise, return nil.
3581 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
3582 (interactive)
3583 (let ((opoint (point)))
3584 (when (markdown-wiki-link-p)
3585 ;; At a wiki link already, move past it.
3586 (goto-char (+ (match-end 0) 1)))
3587 ;; Search for the next wiki link and move to the beginning.
3588 (if (re-search-forward markdown-regex-wiki-link nil t)
3589 (goto-char (match-beginning 1))
3590 (goto-char opoint)
3591 nil)))
3593 (defun markdown-previous-wiki-link ()
3594 "Jump to previous wiki link.
3595 If successful, return point. Otherwise, return nil.
3596 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
3597 (interactive)
3598 (if (re-search-backward markdown-regex-wiki-link nil t)
3599 (goto-char (match-beginning 1))
3600 nil))
3602 (defun markdown-highlight-wiki-link (from to face)
3603 "Highlight the wiki link in the region between FROM and TO using FACE."
3604 (put-text-property from to 'font-lock-face face))
3606 (defun markdown-unfontify-region-wiki-links (from to)
3607 "Remove wiki link faces from the region specified by FROM and TO."
3608 (interactive "nfrom: \nnto: ")
3609 (remove-text-properties from to '(font-lock-face markdown-link-face))
3610 (remove-text-properties from to '(font-lock-face markdown-missing-link-face)))
3612 (defun markdown-fontify-region-wiki-links (from to)
3613 "Search region given by FROM and TO for wiki links and fontify them.
3614 If a wiki link is found check to see if the backing file exists
3615 and highlight accordingly."
3616 (goto-char from)
3617 (save-match-data
3618 (while (re-search-forward markdown-regex-wiki-link to t)
3619 (let ((highlight-beginning (match-beginning 1))
3620 (highlight-end (match-end 1))
3621 (file-name
3622 (markdown-convert-wiki-link-to-filename
3623 (markdown-wiki-link-link))))
3624 (if (file-exists-p file-name)
3625 (markdown-highlight-wiki-link
3626 highlight-beginning highlight-end markdown-link-face)
3627 (markdown-highlight-wiki-link
3628 highlight-beginning highlight-end markdown-link-face)
3629 (markdown-highlight-wiki-link
3630 highlight-beginning highlight-end markdown-missing-link-face))))))
3632 (defun markdown-extend-changed-region (from to)
3633 "Extend region given by FROM and TO so that we can fontify all links.
3634 The region is extended to the first newline before and the first
3635 newline after."
3636 ;; start looking for the first new line before 'from
3637 (goto-char from)
3638 (re-search-backward "\n" nil t)
3639 (let ((new-from (point-min))
3640 (new-to (point-max)))
3641 (if (not (= (point) from))
3642 (setq new-from (point)))
3643 ;; do the same thing for the first new line after 'to
3644 (goto-char to)
3645 (re-search-forward "\n" nil t)
3646 (if (not (= (point) to))
3647 (setq new-to (point)))
3648 (values new-from new-to)))
3650 (defun markdown-check-change-for-wiki-link (from to change)
3651 "Check region between FROM and TO for wiki links and re-fontfy as needed.
3652 Designed to be used with the `after-change-functions' hook.
3653 CHANGE is the number of bytes of pre-change text replaced by the
3654 given range."
3655 (interactive "nfrom: \nnto: \nnchange: ")
3656 (let* ((modified (buffer-modified-p))
3657 (buffer-undo-list t)
3658 (inhibit-read-only t)
3659 (inhibit-point-motion-hooks t)
3660 deactivate-mark
3661 buffer-file-truename)
3662 (unwind-protect
3663 (save-excursion
3664 (save-match-data
3665 (save-restriction
3666 ;; Extend the region to fontify so that it starts
3667 ;; and ends at safe places.
3668 (multiple-value-bind (new-from new-to)
3669 (markdown-extend-changed-region from to)
3670 ;; Unfontify existing fontification (start from scratch)
3671 (markdown-unfontify-region-wiki-links new-from new-to)
3672 ;; Now do the fontification.
3673 (markdown-fontify-region-wiki-links new-from new-to)))))
3674 (and (not modified)
3675 (buffer-modified-p)
3676 (set-buffer-modified-p nil)))))
3678 (defun markdown-fontify-buffer-wiki-links ()
3679 "Refontify all wiki links in the buffer."
3680 (interactive)
3681 (markdown-check-change-for-wiki-link (point-min) (point-max) 0))
3684 ;;; Miscellaneous =============================================================
3686 (defun markdown-compress-whitespace-string (str)
3687 "Compress whitespace in STR and return result.
3688 Leading and trailing whitespace is removed. Sequences of multiple
3689 spaces, tabs, and newlines are replaced with single spaces."
3690 (replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
3691 (replace-regexp-in-string "[ \t\n]+" " " str)))
3693 (defun markdown-line-number-at-pos (&optional pos)
3694 "Return (narrowed) buffer line number at position POS.
3695 If POS is nil, use current buffer location.
3696 This is an exact copy of `line-number-at-pos' for use in emacs21."
3697 (let ((opoint (or pos (point))) start)
3698 (save-excursion
3699 (goto-char (point-min))
3700 (setq start (point))
3701 (goto-char opoint)
3702 (forward-line 0)
3703 (1+ (count-lines start (point))))))
3705 (defun markdown-nobreak-p ()
3706 "Return nil if it is acceptable to break the current line at the point."
3707 ;; inside in square brackets (e.g., link anchor text)
3708 (looking-back "\\[[^]]*"))
3711 ;;; Mode Definition ==========================================================
3713 (defun markdown-show-version ()
3714 "Show the version number in the minibuffer."
3715 (interactive)
3716 (message "markdown-mode, version %s" markdown-mode-version))
3718 ;;;###autoload
3719 (define-derived-mode markdown-mode text-mode "Markdown"
3720 "Major mode for editing Markdown files."
3721 ;; Natural Markdown tab width
3722 (setq tab-width 4)
3723 ;; Comments
3724 (make-local-variable 'comment-start)
3725 (setq comment-start "<!-- ")
3726 (make-local-variable 'comment-end)
3727 (setq comment-end " -->")
3728 (make-local-variable 'comment-start-skip)
3729 (setq comment-start-skip "<!--[ \t]*")
3730 (make-local-variable 'comment-column)
3731 (setq comment-column 0)
3732 ;; Font lock.
3733 (set (make-local-variable 'font-lock-defaults)
3734 '(markdown-mode-font-lock-keywords))
3735 (set (make-local-variable 'font-lock-multiline) t)
3736 ;; For imenu support
3737 (setq imenu-create-index-function 'markdown-imenu-create-index)
3738 ;; For menu support in XEmacs
3739 (easy-menu-add markdown-mode-menu markdown-mode-map)
3740 ;; Defun movement
3741 (set (make-local-variable 'beginning-of-defun-function)
3742 'markdown-beginning-of-defun)
3743 (set (make-local-variable 'end-of-defun-function)
3744 'markdown-end-of-defun)
3745 ;; Make filling work with lists (unordered, ordered, and definition)
3746 (set (make-local-variable 'paragraph-start)
3747 "\f\\|[ \t]*$\\|^[ \t]*[*+-] \\|^[ \t]*[0-9]+\\.\\|^[ \t]*: ")
3748 ;; Outline mode
3749 (make-local-variable 'outline-regexp)
3750 (setq outline-regexp markdown-regex-header)
3751 (make-local-variable 'outline-level)
3752 (setq outline-level 'markdown-outline-level)
3753 ;; Cause use of ellipses for invisible text.
3754 (add-to-invisibility-spec '(outline . t))
3755 ;; Indentation and filling
3756 (make-local-variable 'fill-nobreak-predicate)
3757 (add-hook 'fill-nobreak-predicate 'markdown-nobreak-p)
3758 (setq indent-line-function markdown-indent-function)
3760 ;; Prepare hooks for XEmacs compatibility
3761 (when (featurep 'xemacs)
3762 (make-local-hook 'after-change-functions)
3763 (make-local-hook 'font-lock-extend-region-functions)
3764 (make-local-hook 'window-configuration-change-hook))
3766 ;; Multiline font lock
3767 (add-hook 'font-lock-extend-region-functions
3768 'markdown-font-lock-extend-region)
3770 ;; Anytime text changes make sure it gets fontified correctly
3771 (add-hook 'after-change-functions 'markdown-check-change-for-wiki-link t t)
3773 ;; If we left the buffer there is a really good chance we were
3774 ;; creating one of the wiki link documents. Make sure we get
3775 ;; refontified when we come back.
3776 (add-hook 'window-configuration-change-hook
3777 'markdown-fontify-buffer-wiki-links t t)
3779 ;; do the initial link fontification
3780 (markdown-fontify-buffer-wiki-links))
3782 ;;(add-to-list 'auto-mode-alist '("\\.text$" . markdown-mode))
3785 ;;; GitHub Flavored Markdown Mode ============================================
3787 ;;;###autoload
3788 (define-derived-mode gfm-mode markdown-mode "GFM"
3789 "Major mode for editing GitHub Flavored Markdown files."
3790 (setq markdown-link-space-sub-char "-")
3791 (auto-fill-mode 0)
3792 ;; Use visual-line-mode if available, fall back to longlines-mode:
3793 (if (fboundp 'visual-line-mode)
3794 (visual-line-mode 1)
3795 (longlines-mode 1))
3796 ;; do the initial link fontification
3797 (markdown-fontify-buffer-wiki-links))
3800 (provide 'markdown-mode)
3802 ;;; markdown-mode.el ends here