Link following for implicit reference links
[markdown-mode.git] / markdown-mode.el
blob474483cba3d33115d6b94f55668bfd7ad4bc7d26
1 ;;; markdown-mode.el --- Emacs Major mode for Markdown-formatted text files
3 ;; Copyright (C) 2007-2011 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>
25 ;; Author: Jason R. Blevins <jrblevin@sdf.org>
26 ;; Maintainer: Jason R. Blevins <jrblevin@sdf.org>
27 ;; Created: May 24, 2007
28 ;; Version: 1.8.1
29 ;; Keywords: Markdown, GitHub Flavored Markdown, itex
30 ;; URL: http://jblevins.org/projects/markdown-mode/
32 ;; This file is not part of GNU Emacs.
34 ;; This program is free software; you can redistribute it and/or modify
35 ;; it under the terms of the GNU General Public License as published by
36 ;; the Free Software Foundation; either version 2, or (at your option)
37 ;; any later version.
39 ;; This program is distributed in the hope that it will be useful,
40 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
41 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
42 ;; GNU General Public License for more details.
44 ;; You should have received a copy of the GNU General Public License
45 ;; along with this program; if not, write to the Free Software
46 ;; Foundation, Inc., 51 Franklin Street, Fifth Floor,
47 ;; Boston, MA 02110-1301, USA.
49 ;;; Commentary:
51 ;; markdown-mode is a major mode for editing [Markdown][]-formatted
52 ;; text files in GNU Emacs. markdown-mode is free software, licensed
53 ;; under the GNU GPL.
55 ;; [Markdown]: http://daringfireball.net/projects/markdown/
57 ;; The latest stable version is markdown-mode 1.8.1, released on August 15, 2011:
59 ;; * [markdown-mode.el][]
60 ;; * [Screenshot][]
61 ;; * [Release notes][]
63 ;; [markdown-mode.el]: http://jblevins.org/projects/markdown-mode/markdown-mode.el
64 ;; [screenshot]: http://jblevins.org/projects/markdown-mode/screenshots/20110812-001.png
65 ;; [release notes]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
67 ;; markdown-mode is also available in several package managers, including:
69 ;; * Debian and Ubuntu Linux: [emacs-goodies-el][]
70 ;; * RedHat and Fedora Linux: [emacs-goodies][]
71 ;; * OpenBSD: [textproc/markdown-mode][]
72 ;; * Arch Linux (AUR): [emacs-markdown-mode-git][]
74 ;; [emacs-goodies-el]: http://packages.debian.org/emacs-goodies-el
75 ;; [emacs-goodies]: https://admin.fedoraproject.org/pkgdb/acls/name/emacs-goodies
76 ;; [textproc/markdown-mode]: http://pkgsrc.se/textproc/markdown-mode
77 ;; [emacs-markdown-mode-git]: http://aur.archlinux.org/packages.php?ID=30389
79 ;; The latest development version can be downloaded directly
80 ;; ([markdown-mode.el][devel.el]) or it can be obtained from the
81 ;; (browsable and clonable) Git repository at
82 ;; <http://jblevins.org/git/markdown-mode.git>. The entire repository,
83 ;; including the full project history, can be cloned via the Git protocol
84 ;; by running
86 ;; git clone git://jblevins.org/git/markdown-mode.git
88 ;; [devel.el]: http://jblevins.org/git/markdown-mode.git/plain/markdown-mode.el
90 ;;; Dependencies:
92 ;; markdown-mode requires easymenu, a standard package since GNU Emacs
93 ;; 19 and XEmacs 19, which provides a uniform interface for creating
94 ;; menus in GNU Emacs and XEmacs.
96 ;;; Installation:
98 ;; Make sure to place `markdown-mode.el` somewhere in the load-path and add
99 ;; the following lines to your `.emacs` file to associate markdown-mode
100 ;; with `.text` files:
102 ;; (autoload 'markdown-mode "markdown-mode"
103 ;; "Major mode for editing Markdown files" t)
104 ;; (setq auto-mode-alist
105 ;; (cons '("\\.text" . markdown-mode) auto-mode-alist))
107 ;; There is no consensus on an official file extension so change `.text` to
108 ;; `.mdwn`, `.md`, `.mdt`, or whatever you call your markdown files.
110 ;;; Customization:
112 ;; Although no configuration is *necessary* there are a few things
113 ;; that can be customized. The `M-x customize-mode` command
114 ;; provides an interface to all of the possible customizations:
116 ;; * `markdown-command' - the command used to run Markdown (default:
117 ;; `markdown'). This variable may be customized to pass
118 ;; command-line options to your Markdown processor of choice, but
119 ;; this command must accept input from `stdin`. If it does not, a
120 ;; simple wrapper script can be used to write `stdin` to a file
121 ;; and then pass that file to your Markdown interpreter. Ideally,
122 ;; this command will produce an XHTML fragment around which
123 ;; markdown-mode will wrap a header and footer (which can be
124 ;; further customized). However, it attempts to detect whether
125 ;; the command produces standalone XHTML output (via
126 ;; `markdown-xhtml-standalone-regexp'), in which case no header
127 ;; and footer content will be added.
129 ;; * `markdown-command-needs-filename' - set to non-nil if
130 ;; `markdown-command' does not accept input from stdin (default: nil).
131 ;; Instead, it will be passed a filename as the final command-line
132 ;; option. As a result, you will only be able to run Markdown
133 ;; from buffers which are visiting a file.
135 ;; * `markdown-hr-string' - string to use when inserting horizontal
136 ;; rules (default: `* * * * *').
138 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
139 ;; underscores for bold instead of two asterisks (default: `nil').
141 ;; * `markdown-italic-underscore' - set to a non-nil value to use
142 ;; underscores for italic instead of asterisks (default: `nil').
144 ;; * `markdown-indent-function' - the function to use for automatic
145 ;; indentation (default: `markdown-indent-line').
147 ;; * `markdown-indent-on-enter' - set to a non-nil value to
148 ;; automatically indent new lines when the enter key is pressed
149 ;; (default: `t')
151 ;; * `markdown-follow-wiki-link-on-enter' - set to a non-nil value
152 ;; to automatically open a linked document in a new buffer if the
153 ;; cursor is an wiki link
154 ;; (default: `t')
156 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
157 ;; treat aliased wiki links like `[[link text|PageName]]`.
158 ;; When set to nil, they will be treated as `[[PageName|link text]]'.
160 ;; * `markdown-uri-types' - a list of protocols for URIs that
161 ;; `markdown-mode' should highlight.
163 ;; * `markdown-enable-math' - syntax highlighting for
164 ;; LaTeX fragments (default: `nil').
166 ;; * `markdown-css-path' - CSS file to link to in XHTML output.
168 ;; * `markdown-content-type' - when set to a nonempty string, an
169 ;; `http-equiv` attribute will be included in the XHTML `<head>`
170 ;; block. If needed, the suggested values are
171 ;; `application/xhtml+xml` or `text/html`.
173 ;; * `markdown-coding-system' - used for specifying the character
174 ;; set identifier in the `http-equiv` attribute (see
175 ;; `markdown-content-type'). When set to `nil',
176 ;; `buffer-file-coding-system' will be used (and falling back to
177 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
178 ;; and `iso-latin-1'.
180 ;; * `markdown-xhtml-header-content' - additional content to include
181 ;; in the XHTML `<head>` block.
183 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
184 ;; indicates whether the output of `markdown-command' is standalone
185 ;; XHTML (default: `^\\(\<\?xml\\|\<!DOCTYPE\\|\<html\\)`). If
186 ;; this is not matched, we assume this output is a fragment and add
187 ;; our own header and footer.
189 ;; * `markdown-link-space-sub-char' - a character to replace spaces
190 ;; when mapping wiki links to filenames (default: `_`).
191 ;; For example, use an underscore for compatibility with the
192 ;; Python Markdown WikiLinks extension or a hyphen for compatibility
193 ;; with Github wiki links.
195 ;; Additionally, the faces used for syntax highlighting can be modified to
196 ;; your liking by issuing `M-x customize-group RET markdown-faces`
197 ;; or by using the "Markdown Faces" link at the bottom of the mode
198 ;; customization screen.
200 ;;; Usage:
202 ;; Keybindings are grouped by prefixes based on their function. For
203 ;; example, commands dealing with headers begin with `C-c C-t`. The
204 ;; primary commands in each group will are described below. You can
205 ;; obtain a list of all keybindings by pressing `C-c C-h`.
207 ;; * Anchors: `C-c C-a`
209 ;; `C-c C-a l` inserts inline links of the form `[text](url)`.
210 ;; `C-c C-a r` inserts reference links of the form `[text][label]`.
211 ;; The label definition will be placed at the end of the current
212 ;; block. `C-c C-a w` acts similarly for wiki links of the form
213 ;; `[[WikiLink]]`. In all cases, if there is an active region, the
214 ;; text in the region is used as the link text.
216 ;; * Commands: `C-c C-c`
218 ;; `C-c C-c m` will run Markdown on the current buffer and preview
219 ;; the output in another buffer while `C-c C-c p` runs Markdown on
220 ;; the current buffer and previews the output in a browser.
221 ;; `C-c C-c e` will run Markdown on the current buffer and save
222 ;; the result in the file `basename.html`, where `basename` is the
223 ;; name of the Markdown file with the extension removed. **This
224 ;; file will be overwritten without notice.** Press `C-c C-c v`
225 ;; to view the exported file in a browser.
227 ;; `C-c C-c c` will check for undefined references. If there are
228 ;; any, a small buffer will open with a list of undefined
229 ;; references and the line numbers on which they appear. In Emacs
230 ;; 22 and greater, selecting a reference from this list and
231 ;; pressing `RET` will insert an empty reference definition at the
232 ;; end of the buffer. Similarly, selecting the line number will
233 ;; jump to the corresponding line.
235 ;; * Images: `C-c C-i`
237 ;; `C-c C-i i` inserts an image, using the active region (if any)
238 ;; as the alt text.
240 ;; * Physical styles: `C-c C-p`
242 ;; These commands all act on text in the active region, if any,
243 ;; and insert empty markup fragments otherwise. `C-c C-p b` makes
244 ;; the selected text bold, `C-c C-p f` formats the region as
245 ;; fixed-width text, and `C-c C-p i` is used for italic text.
247 ;; * Logical styles: `C-c C-s`
249 ;; These commands all act on text in the active region, if any,
250 ;; and insert empty markup fragments otherwise. Logical styles
251 ;; include blockquote (`C-c C-s b`), preformatted (`C-c C-s p`),
252 ;; code (`C-c C-s c`), emphasis (`C-c C-s e`), and strong
253 ;; (`C-c C-s s`).
255 ;; * Headers: `C-c C-t`
257 ;; All header commands use text in the active region, if any, as
258 ;; the header text. To insert an atx or hash style level-n
259 ;; header, press `C-c C-t n` where n is between 1 and 6. For a
260 ;; top-level setext or underline style header press `C-c C-t t`
261 ;; (mnemonic: title) and for a second-level underline-style header
262 ;; press `C-c C-t s` (mnemonic: section).
264 ;; * Footnotes: `C-c C-f`
266 ;; To create a new footnote at the point, press `C-c C-f n`.
267 ;; Press `C-c C-f g` with the point at a footnote to jump to the
268 ;; location where the footnote text is defined. Then, press
269 ;; `C-c C-f b` to return to the footnote marker in the main text.
270 ;; When the point is at a footnote marker or in the body of a
271 ;; footnote, press `C-c C-f k` to kill the footnote and add the
272 ;; text to the kill ring.
274 ;; * Other elements:
276 ;; `C-c -` inserts a horizontal rule.
278 ;; * Links:
280 ;; Press `C-c C-o` when the point is on an inline or reference
281 ;; link to open the URL in a browser.
283 ;; * Wiki-Link Navigation:
285 ;; Use `M-p` and `M-n` to quickly jump to the previous and next
286 ;; wiki links, respectively.
288 ;; * Outline Navigation:
290 ;; Navigation between headings is possible using `outline-mode'.
291 ;; Use `C-M-n` and `C-M-p` to move between the next and previous
292 ;; visible headings. Similarly, `C-M-f` and `C-M-b` move to the
293 ;; next and previous visible headings at the same level as the one
294 ;; at the point. Finally, `C-M-u` will move up to a lower-level
295 ;; (more inclusive) visible heading.
297 ;; Many of the commands described above behave differently depending on
298 ;; whether Transient Mark mode is enabled or not. When it makes sense,
299 ;; if Transient Mark mode is on and a region is active, the command
300 ;; applies to the text in the region (e.g., `C-c C-p b` makes the region
301 ;; bold). For users who prefer to work outside of Transient Mark mode,
302 ;; in Emacs 22 it can be enabled temporarily by pressing `C-SPC C-SPC`.
304 ;; When applicable, commands that specifically act on the region even
305 ;; outside of Transient Mark mode have the same keybinding as the with
306 ;; the exception of an additional `C-` prefix. For example,
307 ;; `markdown-insert-blockquote' is bound to `C-c C-s b` and only acts on
308 ;; the region in Transient Mark mode while `markdown-blockquote-region'
309 ;; is bound to `C-c C-s C-b` and always applies to the region (when
310 ;; nonempty).
312 ;; markdown-mode attempts to be flexible in how it handles
313 ;; indentation. When you press `TAB` repeatedly, the point will cycle
314 ;; through several possible indentation levels corresponding to things
315 ;; you might have in mind when you press `RET` at the end of a line or
316 ;; `TAB`. For example, you may want to start a new list item,
317 ;; continue a list item with hanging indentation, indent for a nested
318 ;; pre block, and so on.
320 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
321 ;; visibility cycling for atx- or hash-style headers. There are two
322 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
323 ;; the table of contents view (headers only), outline view (top-level
324 ;; headers only), and the full document view. Pressing `TAB` while the
325 ;; point is at a header will cycle through levels of visibility for the
326 ;; subtree: completely folded, visible children, and fully visible.
327 ;; Note that mixing hash and underline style headers will give undesired
328 ;; results.
330 ;;; Extensions:
332 ;; Besides supporting the basic Markdown syntax, markdown-mode also
333 ;; includes syntax highlighting for `[[Wiki Links]]` by default. Wiki
334 ;; links may be followed automatically by hitting the enter key when
335 ;; your curser is on a wiki link or by hitting `C-c C-w`. The
336 ;; autofollowing on enter key may be controlled with the
337 ;; `markdown-follow-wiki-link-on-enter' customization. Use `M-p` and
338 ;; `M-n` to quickly jump to the previous and next wiki links,
339 ;; respectively. Aliased or piped wiki links of the form
340 ;; `[[link text|PageName]]` are also supported. Since some wikis
341 ;; reverse these components, set `markdown-wiki-link-alias-first'
342 ;; to nil to treat them as `[[PageName|link text]]`.
344 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
345 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
346 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
347 ;; You can do this either by using `M-x customize-group markdown`
348 ;; or by placing the following in your `.emacs` file:
350 ;; (defun markdown-custom ()
351 ;; "markdown-mode-hook"
352 ;; (setq markdown-command "markdown | smartypants"))
353 ;; (add-hook 'markdown-mode-hook '(lambda() (markdown-custom)))
355 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
357 ;; Experimental syntax highlighting for mathematical expressions written
358 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
359 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
360 ;; either via customize or by placing `(setq markdown-enable-itex t)`
361 ;; in `.emacs`, and restarting Emacs.
363 ;; A [GitHub Flavored Markdown](http://github.github.com/github-flavored-markdown/)
364 ;; mode, `gfm-mode', is also available. The GitHub implementation of
365 ;; differs slightly from standard Markdown. Most importantly, newlines are
366 ;; significant and trigger hard line breaks. As such, `gfm-mode' turns off
367 ;; `auto-fill-mode' and turns on `visual-line-mode' (or `longlines-mode' if
368 ;; `visual-line-mode' is not available). Wiki links in this mode will be
369 ;; treated as on GitHub, with hyphens replacing spaces in filenames and
370 ;; where the first letter of the filename capitalized. For example,
371 ;; `[[wiki link]]' will map to a file named `Wiki-link` with the same
372 ;; extension as the current file.
374 ;;; Acknowledgments:
376 ;; markdown-mode has benefited greatly from the efforts of the
377 ;; following people:
379 ;; * Cyril Brulebois <cyril.brulebois@enst-bretagne.fr> for Debian packaging.
380 ;; * Conal Elliott <conal@conal.net> for a font-lock regexp patch.
381 ;; * Edward O'Connor <hober0@gmail.com> for a font-lock regexp fix and
382 ;; GitHub Flavored Markdown mode (`gfm-mode').
383 ;; * Greg Bognar <greg_bognar@hms.harvard.edu> for menus and running
384 ;; `markdown' with an active region.
385 ;; * Daniel Burrows <dburrows@debian.org> for filing Debian bug #456592.
386 ;; * Peter S. Galbraith <psg@debian.org> for maintaining emacs-goodies-el.
387 ;; * Dmitry Dzhus <mail@sphinx.net.ru> for reference checking functions.
388 ;; * Bryan Kyle <bryan.kyle@gmail.com> for indentation code.
389 ;; * Ben Voui <intrigeri@boum.org> for font-lock face customizations.
390 ;; * Ankit Solanki <ankit.solanki@gmail.com> for longlines.el
391 ;; compatibility and custom CSS.
392 ;; * Hilko Bengen <bengen@debian.org> for proper XHTML output.
393 ;; * Jose A. Ortega Ruiz <jao@gnu.org> for Emacs 23 fixes.
394 ;; * Alec Resnick <alec@sproutward.org> for bug reports.
395 ;; * Joost Kremers <joostkremers@fastmail.fm> for footnote-handling
396 ;; functions and bug reports regarding indentation.
397 ;; * Peter Williams <pezra@barelyenough.org> for fill-paragraph
398 ;; enhancements.
399 ;; * George Ogata <george.ogata@gmail.com> for fixing several
400 ;; byte-compilation warnings.
401 ;; * Eric Merritt <ericbmerritt@gmail.com> for wiki link features.
402 ;; * Philippe Ivaldi <pivaldi@sfr.fr> for XHTML preview
403 ;; customizations and XHTML export.
404 ;; * Jeremiah Dodds <jeremiah.dodds@gmail.com> for supporting
405 ;; Markdown processors which do not accept input from stdin.
406 ;; * Werner Dittmann <werner.dittmann@t-online.de> for bug reports
407 ;; regarding the cl dependency and auto-fill-mode and indentation.
408 ;; * Scott Pfister <scott.pfister@gmail.com> for generalizing the space
409 ;; substitution character for mapping wiki links to filenames.
410 ;; * Marcin Kasperski <marcin.kasperski@mekk.waw.pl> for a patch to
411 ;; escape shell commands.
412 ;; * Christopher J. Madsen <cjm@cjmweb.net> for patches to fix a match
413 ;; data bug and to prefer `visual-line-mode' in `gfm-mode'.
414 ;; * Shigeru Fukaya <shigeru.fukaya@gmail.com> for better adherence to
415 ;; Emacs Lisp coding conventions.
416 ;; * Donald Ephraim Curtis <dcurtis@milkbox.net> for fixing the `paragraph-fill'
417 ;; regexp, refactoring the compilation and preview functions,
418 ;; heading font-lock generalizations, and imenu support.
419 ;; * Kevin Porter <kportertx@gmail.com> for wiki link handling in `gfm-mode'.
420 ;; * Max Penet <max.penet@gmail.com> and Peter Eisentraut <peter_e@gmx.net>
421 ;; for an autoload token for `gfm-mode'.
422 ;; * Ian Yang <me@iany.me> for improving the reference definition regex.
423 ;; * Akinori Musha <knu@idaemons.org> for an imenu index function.
424 ;; * Michael Sperber <sperber@deinprogramm.de> for XEmacs fixes.
425 ;; * Francois Gannaz <francois.gannaz@free.fr> for suggestingcharset
426 ;; declaration in XHTML output.
427 ;; * Zhenlei Jia <zhenlei.jia@gmail.com> for smart (dedention)
428 ;; un-indentation function.
429 ;; * Matus Goljer <dota.keys@gmail.com> for improved wiki link following.
430 ;; * Peter Jones <pjones@pmade.com> for link following functions.
432 ;;; Bugs:
434 ;; Although markdown-mode is developed and tested primarily using
435 ;; GNU Emacs 24, compatibility with earlier Emacsen is also a
436 ;; priority.
438 ;; If you find any bugs in markdown-mode, please construct a test case
439 ;; or a patch and email me at <jrblevin@sdf.org>.
441 ;;; History:
443 ;; markdown-mode was written and is maintained by Jason Blevins. The
444 ;; first version was released on May 24, 2007.
446 ;; * 2007-05-24: Version 1.1
447 ;; * 2007-05-25: Version 1.2
448 ;; * 2007-06-05: [Version 1.3][]
449 ;; * 2007-06-29: Version 1.4
450 ;; * 2008-05-24: [Version 1.5][]
451 ;; * 2008-06-04: [Version 1.6][]
452 ;; * 2009-10-01: [Version 1.7][]
453 ;; * 2011-08-12: [Version 1.8][]
454 ;; * 2011-08-15: [Version 1.8.1][]
456 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
457 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
458 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
459 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
460 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
461 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
464 ;;; Code:
466 (require 'easymenu)
467 (require 'outline)
468 (eval-when-compile (require 'cl))
470 ;;; Constants =================================================================
472 (defconst markdown-mode-version "1.8.1"
473 "Markdown mode version number.")
475 (defconst markdown-output-buffer-name "*markdown-output*"
476 "Name of temporary buffer for markdown command output.")
478 ;;; Customizable variables ====================================================
480 (defvar markdown-mode-hook nil
481 "Hook run when entering Markdown mode.")
483 (defgroup markdown nil
484 "Major mode for editing text files in Markdown format."
485 :prefix "markdown-"
486 :group 'wp
487 :link '(url-link "http://jblevins.org/projects/markdown-mode/"))
489 (defcustom markdown-command "markdown"
490 "Command to run markdown."
491 :group 'markdown
492 :type 'string)
494 (defcustom markdown-command-needs-filename nil
495 "Set to non-nil if `markdown-command' does not accept input from stdin.
496 Instead, it will be passed a filename as the final command-line
497 option. As a result, you will only be able to run Markdown from
498 buffers which are visiting a file."
499 :group 'markdown
500 :type 'boolean)
502 (defcustom markdown-hr-string "* * * * *"
503 "String to use for horizonal rules."
504 :group 'markdown
505 :type 'string)
507 (defcustom markdown-bold-underscore nil
508 "Use two underscores for bold instead of two asterisks."
509 :group 'markdown
510 :type 'boolean)
512 (defcustom markdown-italic-underscore nil
513 "Use underscores for italic instead of asterisks."
514 :group 'markdown
515 :type 'boolean)
517 (defcustom markdown-indent-function 'markdown-indent-line
518 "Function to use to indent."
519 :group 'markdown
520 :type 'function)
522 (defcustom markdown-indent-on-enter t
523 "Automatically indent new lines when enter key is pressed."
524 :group 'markdown
525 :type 'boolean)
527 (defcustom markdown-follow-wiki-link-on-enter t
528 "Follow wiki link at point (if any) when the enter key is pressed."
529 :group 'markdown
530 :type 'boolean)
532 (defcustom markdown-wiki-link-alias-first t
533 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
534 Otherwise, they will be treated as [[PageName|alias text]]."
535 :group 'markdown
536 :type 'boolean)
538 (defcustom markdown-uri-types
539 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
540 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
541 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
542 "Link types for syntax highlighting of URIs."
543 :group 'markdown
544 :type 'list)
546 (defcustom markdown-enable-math nil
547 "Syntax highlighting for inline LaTeX expressions.
548 This will not take effect until Emacs is restarted."
549 :group 'markdown
550 :type 'boolean)
552 (defcustom markdown-css-path ""
553 "URL of CSS file to link to in the output XHTML."
554 :group 'markdown
555 :type 'string)
557 (defcustom markdown-content-type ""
558 "Content type string for the http-equiv header in XHTML output.
559 When set to a non-empty string, insert the http-equiv attribute.
560 Otherwise, this attribute is omitted."
561 :group 'markdown
562 :type 'string)
564 (defcustom markdown-coding-system nil
565 "Character set string for the http-equiv header in XHTML output.
566 Defaults to `buffer-file-coding-system' (and falling back to
567 `iso-8859-1' when not available). Common settings are `utf-8'
568 and `iso-latin-1'. Use `list-coding-systems' for more choices."
569 :group 'markdown
570 :type 'coding-system)
572 (defcustom markdown-xhtml-header-content ""
573 "Additional content to include in the XHTML <head> block."
574 :group 'markdown
575 :type 'string)
577 (defcustom markdown-xhtml-standalone-regexp
578 "^\\(\<\?xml\\|\<!DOCTYPE\\|\<html\\)"
579 "Regexp indicating whether `markdown-command' output is standalone XHTML."
580 :group 'markdown
581 :type 'regexp)
583 (defcustom markdown-link-space-sub-char
585 "Character to use instead of spaces when mapping wiki links to filenames."
586 :group 'markdown
587 :type 'string)
589 (defcustom markdown-footnote-location 'end
590 "Position where new footnotes are inserted in the document."
591 :group 'markdown
592 :type '(choice (const :tag "At the end of the document" end)
593 (const :tag "Immediately after the paragraph" immediately)
594 (const :tag "Before next header" header)))
596 ;;; Font lock =================================================================
598 (require 'font-lock)
600 (defvar markdown-italic-face 'markdown-italic-face
601 "Face name to use for italic text.")
603 (defvar markdown-bold-face 'markdown-bold-face
604 "Face name to use for bold text.")
606 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
607 "Face name to use as a base for header delimiters.")
609 (defvar markdown-header-rule-face 'markdown-header-rule-face
610 "Face name to use as a base for header rules.")
612 (defvar markdown-header-face 'markdown-header-face
613 "Face name to use as a base for headers.")
615 (defvar markdown-header-face-1 'markdown-header-face-1
616 "Face name to use for level-1 headers.")
618 (defvar markdown-header-face-2 'markdown-header-face-2
619 "Face name to use for level-2 headers.")
621 (defvar markdown-header-face-3 'markdown-header-face-3
622 "Face name to use for level-3 headers.")
624 (defvar markdown-header-face-4 'markdown-header-face-4
625 "Face name to use for level-4 headers.")
627 (defvar markdown-header-face-5 'markdown-header-face-5
628 "Face name to use for level-5 headers.")
630 (defvar markdown-header-face-6 'markdown-header-face-6
631 "Face name to use for level-6 headers.")
633 (defvar markdown-inline-code-face 'markdown-inline-code-face
634 "Face name to use for inline code.")
636 (defvar markdown-list-face 'markdown-list-face
637 "Face name to use for list markers.")
639 (defvar markdown-blockquote-face 'markdown-blockquote-face
640 "Face name to use for blockquote.")
642 (defvar markdown-pre-face 'markdown-pre-face
643 "Face name to use for preformatted text.")
645 (defvar markdown-link-face 'markdown-link-face
646 "Face name to use for links.")
648 (defvar markdown-missing-link-face 'markdown-missing-link-face
649 "Face name to use for links where the linked file does not exist.")
651 (defvar markdown-reference-face 'markdown-reference-face
652 "Face name to use for reference.")
654 (defvar markdown-footnote-face 'markdown-footnote-face
655 "Face name to use for footnote identifiers.")
657 (defvar markdown-url-face 'markdown-url-face
658 "Face name to use for URLs.")
660 (defvar markdown-link-title-face 'markdown-link-title-face
661 "Face name to use for reference link titles.")
663 (defvar markdown-comment-face 'markdown-comment-face
664 "Face name to use for HTML comments.")
666 (defvar markdown-math-face 'markdown-math-face
667 "Face name to use for LaTeX expressions.")
669 (defgroup markdown-faces nil
670 "Faces used in Markdown Mode"
671 :group 'markdown
672 :group 'faces)
674 (defface markdown-italic-face
675 '((t (:inherit font-lock-variable-name-face :slant italic)))
676 "Face for italic text."
677 :group 'markdown-faces)
679 (defface markdown-bold-face
680 '((t (:inherit font-lock-variable-name-face :weight bold)))
681 "Face for bold text."
682 :group 'markdown-faces)
684 (defface markdown-header-rule-face
685 '((t (:inherit font-lock-function-name-face :weight bold)))
686 "Base face for headers rules."
687 :group 'markdown-faces)
689 (defface markdown-header-delimiter-face
690 '((t (:inherit font-lock-function-name-face :weight bold)))
691 "Base face for headers hash delimiter."
692 :group 'markdown-faces)
694 (defface markdown-header-face
695 '((t (:inherit font-lock-function-name-face :weight bold)))
696 "Base face for headers."
697 :group 'markdown-faces)
699 (defface markdown-header-face-1
700 '((t (:inherit markdown-header-face)))
701 "Face for level-1 headers."
702 :group 'markdown-faces)
704 (defface markdown-header-face-2
705 '((t (:inherit markdown-header-face)))
706 "Face for level-2 headers."
707 :group 'markdown-faces)
709 (defface markdown-header-face-3
710 '((t (:inherit markdown-header-face)))
711 "Face for level-3 headers."
712 :group 'markdown-faces)
714 (defface markdown-header-face-4
715 '((t (:inherit markdown-header-face)))
716 "Face for level-4 headers."
717 :group 'markdown-faces)
719 (defface markdown-header-face-5
720 '((t (:inherit markdown-header-face)))
721 "Face for level-5 headers."
722 :group 'markdown-faces)
724 (defface markdown-header-face-6
725 '((t (:inherit markdown-header-face)))
726 "Face for level-6 headers."
727 :group 'markdown-faces)
729 (defface markdown-inline-code-face
730 '((t (:inherit font-lock-constant-face)))
731 "Face for inline code."
732 :group 'markdown-faces)
734 (defface markdown-list-face
735 '((t (:inherit font-lock-builtin-face)))
736 "Face for list item markers."
737 :group 'markdown-faces)
739 (defface markdown-blockquote-face
740 '((t (:inherit font-lock-doc-face)))
741 "Face for blockquote sections."
742 :group 'markdown-faces)
744 (defface markdown-pre-face
745 '((t (:inherit font-lock-constant-face)))
746 "Face for preformatted text."
747 :group 'markdown-faces)
749 (defface markdown-link-face
750 '((t (:inherit font-lock-keyword-face)))
751 "Face for links."
752 :group 'markdown-faces)
754 (defface markdown-missing-link-face
755 '((t (:inherit font-lock-warning-face)))
756 "Face for missing links."
757 :group 'markdown-faces)
759 (defface markdown-reference-face
760 '((t (:inherit font-lock-type-face)))
761 "Face for link references."
762 :group 'markdown-faces)
764 (defface markdown-footnote-face
765 '((t (:inherit font-lock-keyword-face)))
766 "Face for footnote markers."
767 :group 'markdown-faces)
769 (defface markdown-url-face
770 '((t (:inherit font-lock-string-face)))
771 "Face for URLs."
772 :group 'markdown-faces)
774 (defface markdown-link-title-face
775 '((t (:inherit font-lock-comment-face)))
776 "Face for reference link titles."
777 :group 'markdown-faces)
779 (defface markdown-comment-face
780 '((t (:inherit font-lock-comment-face)))
781 "Face for HTML comments."
782 :group 'markdown-faces)
784 (defface markdown-math-face
785 '((t (:inherit font-lock-string-face)))
786 "Face for LaTeX expressions."
787 :group 'markdown-faces)
789 (defconst markdown-regex-link-inline
790 "\\(!?\\[[^]]*?\\]\\)\\(([^\\)]*)\\)"
791 "Regular expression for a [text](file) or an image link ![text](file).")
793 (defconst markdown-regex-link-reference
794 "\\(!?\\[[^]]+?\\]\\)[ ]?\\(\\[[^]]*?\\]\\)"
795 "Regular expression for a reference link [text][id].")
797 (defconst markdown-regex-reference-definition
798 "^ \\{0,3\\}\\(\\[[^^\n]+?\\]\\):\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
799 "Regular expression for a link definition [id]: ...")
801 (defconst markdown-regex-footnote
802 "\\(\\[\\^.+?\\]\\)"
803 "Regular expression for a footnote marker [^fn].")
805 (defconst markdown-regex-header
806 "#+\\|\\S-.*\n\\(?:\\(===+\\)\\|\\(---+\\)\\)$"
807 "Regexp identifying Markdown headers.")
809 (defconst markdown-regex-header-1-atx
810 "^\\(# \\)\\(.*?\\)\\($\\| #+$\\)"
811 "Regular expression for level 1 atx-style (hash mark) headers.")
813 (defconst markdown-regex-header-2-atx
814 "^\\(## \\)\\(.*?\\)\\($\\| #+$\\)"
815 "Regular expression for level 2 atx-style (hash mark) headers.")
817 (defconst markdown-regex-header-3-atx
818 "^\\(### \\)\\(.*?\\)\\($\\| #+$\\)"
819 "Regular expression for level 3 atx-style (hash mark) headers.")
821 (defconst markdown-regex-header-4-atx
822 "^\\(#### \\)\\(.*?\\)\\($\\| #+$\\)"
823 "Regular expression for level 4 atx-style (hash mark) headers.")
825 (defconst markdown-regex-header-5-atx
826 "^\\(##### \\)\\(.*?\\)\\($\\| #+$\\)"
827 "Regular expression for level 5 atx-style (hash mark) headers.")
829 (defconst markdown-regex-header-6-atx
830 "^\\(###### \\)\\(.*?\\)\\($\\| #+$\\)"
831 "Regular expression for level 6 atx-style (hash mark) headers.")
833 (defconst markdown-regex-header-1-setext
834 "^\\(.*\\)\n\\(===+\\)$"
835 "Regular expression for level 1 setext-style (underline) headers.")
837 (defconst markdown-regex-header-2-setext
838 "^\\(.*\\)\n\\(---+\\)$"
839 "Regular expression for level 2 setext-style (underline) headers.")
841 (defconst markdown-regex-hr
842 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
843 "Regular expression for matching Markdown horizontal rules.")
845 (defconst markdown-regex-code
846 "\\(^\\|[^\\]\\)\\(\\(`\\{1,2\\}\\)\\([^ \\]\\|[^ ]\\(.\\|\n[^\n]\\)*?[^ \\]\\)\\3\\)"
847 "Regular expression for matching inline code fragments.")
849 (defconst markdown-regex-pre
850 "^\\( \\|\t\\).*$"
851 "Regular expression for matching preformatted text sections.")
853 (defconst markdown-regex-list
854 "^[ \t]*\\([0-9]+\\.\\|[\\*\\+-]\\) "
855 "Regular expression for matching list markers.")
857 (defconst markdown-regex-bold
858 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\(.\\|\n[^\n]\\)*?[^\\ ]\\3\\)"
859 "Regular expression for matching bold text.")
861 (defconst markdown-regex-italic
862 "\\(^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \\]\\3\\|[^ ]\\(.\\|\n[^\n]\\)*?[^\\ ]\\3\\)\\)"
863 "Regular expression for matching italic text.")
865 (defconst markdown-regex-blockquote
866 "^>.*$"
867 "Regular expression for matching blockquote lines.")
869 (defconst markdown-regex-line-break
870 " $"
871 "Regular expression for matching line breaks.")
873 (defconst markdown-regex-wiki-link
874 "\\[\\[\\([^]|]+\\)\\(|\\([^]]+\\)\\)?\\]\\]"
875 "Regular expression for matching wiki links.
876 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
877 wiki links of the form [[PageName|link text]]. In this regular
878 expression, #1 matches the page name and #3 matches the link
879 text.")
881 (defconst markdown-regex-uri
882 (concat
883 "\\(" (mapconcat 'identity markdown-uri-types "\\|")
884 "\\):[^]\t\n\r<>,;() ]+")
885 "Regular expression for matching inline URIs.")
887 (defconst markdown-regex-angle-uri
888 (concat
889 "\\(<\\)\\("
890 (mapconcat 'identity markdown-uri-types "\\|")
891 "\\):[^]\t\n\r<>,;()]+\\(>\\)")
892 "Regular expression for matching inline URIs in angle brackets.")
894 (defconst markdown-regex-email
895 "<\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+>"
896 "Regular expression for matching inline email addresses.")
898 (defconst markdown-regex-latex-expression
899 "\\(^\\|[^\\]\\)\\(\\$\\($\\([^\\$]\\|\\\\.\\)*\\$\\|\\([^\\$]\\|\\\\.\\)*\\)\\$\\)"
900 "Regular expression for itex $..$ or $$..$$ math mode expressions.")
902 (defconst markdown-regex-latex-display
903 "^\\\\\\[\\(.\\|\n\\)*?\\\\\\]$"
904 "Regular expression for itex \[..\] display mode expressions.")
906 (defconst markdown-regex-list-indent
907 "^\\(\\s *\\)\\([0-9]+\\.\\|[\\*\\+-]\\)\\(\\s +\\)"
908 "Regular expression for matching indentation of list items.")
910 (defvar markdown-mode-font-lock-keywords-basic
911 (list
912 '(markdown-match-pre-blocks 0 markdown-pre-face t t)
913 '(markdown-match-fenced-code-blocks 0 markdown-pre-face t t)
914 (cons markdown-regex-blockquote 'markdown-blockquote-face)
915 (cons markdown-regex-header-1-setext '((1 markdown-header-face-1)
916 (2 markdown-header-rule-face)))
917 (cons markdown-regex-header-2-setext '((1 markdown-header-face-2)
918 (2 markdown-header-rule-face)))
919 (cons markdown-regex-header-1-atx '((1 markdown-header-delimiter-face)
920 (2 markdown-header-face-1)
921 (3 markdown-header-delimiter-face)))
922 (cons markdown-regex-header-2-atx '((1 markdown-header-delimiter-face)
923 (2 markdown-header-face-2)
924 (3 markdown-header-delimiter-face)))
925 (cons markdown-regex-header-3-atx '((1 markdown-header-delimiter-face)
926 (2 markdown-header-face-3)
927 (3 markdown-header-delimiter-face)))
928 (cons markdown-regex-header-4-atx '((1 markdown-header-delimiter-face)
929 (2 markdown-header-face-4)
930 (3 markdown-header-delimiter-face)))
931 (cons markdown-regex-header-5-atx '((1 markdown-header-delimiter-face)
932 (2 markdown-header-face-5)
933 (3 markdown-header-delimiter-face)))
934 (cons markdown-regex-header-6-atx '((1 markdown-header-delimiter-face)
935 (2 markdown-header-face-6)
936 (3 markdown-header-delimiter-face)))
937 (cons markdown-regex-hr 'markdown-header-face)
938 '(markdown-match-comments 0 markdown-comment-face t t)
939 (cons markdown-regex-code '(2 markdown-inline-code-face))
940 (cons markdown-regex-angle-uri 'markdown-link-face)
941 (cons markdown-regex-uri 'markdown-link-face)
942 (cons markdown-regex-email 'markdown-link-face)
943 (cons markdown-regex-list 'markdown-list-face)
944 (cons markdown-regex-link-inline
945 '((1 markdown-link-face t)
946 (2 markdown-url-face t)))
947 (cons markdown-regex-link-reference
948 '((1 markdown-link-face t)
949 (2 markdown-reference-face t)))
950 (cons markdown-regex-reference-definition
951 '((1 markdown-reference-face t)
952 (2 markdown-url-face t)
953 (3 markdown-link-title-face t)))
954 (cons markdown-regex-footnote 'markdown-footnote-face)
955 (cons markdown-regex-bold '(2 markdown-bold-face))
956 (cons markdown-regex-italic '(2 markdown-italic-face))
958 "Syntax highlighting for Markdown files.")
960 (defconst markdown-mode-font-lock-keywords-latex
961 (list
962 ;; Math mode $..$ or $$..$$
963 (cons markdown-regex-latex-expression '(2 markdown-math-face))
964 ;; Display mode equations with brackets: \[ \]
965 (cons markdown-regex-latex-display 'markdown-math-face)
966 ;; Equation reference (eq:foo)
967 (cons "(eq:\\w+)" 'markdown-reference-face)
968 ;; Equation reference \eqref{foo}
969 (cons "\\\\eqref{\\w+}" 'markdown-reference-face))
970 "Syntax highlighting for LaTeX fragments.")
972 (defvar markdown-mode-font-lock-keywords
973 (append
974 (if markdown-enable-math
975 markdown-mode-font-lock-keywords-latex)
976 markdown-mode-font-lock-keywords-basic)
977 "Default highlighting expressions for Markdown mode.")
979 ;; Footnotes
980 (defvar markdown-footnote-counter 0
981 "Counter for footnote numbers.")
982 (make-variable-buffer-local 'markdown-footnote-counter)
984 (defconst markdown-footnote-chars
985 "[[:alnum:]-]"
986 "Regular expression maching any character that is allowed in a footnote identifier.")
990 ;;; Compatibility =============================================================
992 ;; Handle replace-regexp-in-string in XEmacs 21
993 (defun markdown-replace-regexp-in-string (regexp rep string)
994 "Compatibility wrapper to provide `replace-regexp-in-string'."
995 (if (featurep 'xemacs)
996 (replace-in-string string regexp rep)
997 (replace-regexp-in-string regexp rep string)))
999 (eval-and-compile
1000 (if (boundp 'mark-active)
1001 (defun markdown-mark-active () ; Emacs
1002 mark-active)
1003 (defalias 'markdown-mark-active 'region-exists-p))) ; XEmacs
1005 (defun markdown-transient-mark-mode-active ()
1006 (cond
1007 ((boundp 'transient-mark-mode)
1008 (and transient-mark-mode (markdown-mark-active)))
1009 ((boundp 'zmacs-regions)
1010 (and zmacs-regions (markdown-mark-active)))))
1014 ;;; Markdown parsing functions ================================================
1016 (defun markdown-cur-line-blank-p ()
1017 "Return t if the current line is blank and nil otherwise."
1018 (save-excursion
1019 (beginning-of-line)
1020 (re-search-forward "^\\s *$" (point-at-eol) t)))
1022 (defun markdown-prev-line-blank-p ()
1023 "Return t if the previous line is blank and nil otherwise.
1024 If we are at the first line, then consider the previous line to be blank."
1025 (save-excursion
1026 (if (= (point-at-bol) (point-min))
1028 (forward-line -1)
1029 (markdown-cur-line-blank-p))))
1031 (defun markdown-next-line-blank-p ()
1032 "Return t if the next line is blank and nil otherwise.
1033 If we are at the last line, then consider the next line to be blank."
1034 (save-excursion
1035 (if (= (point-at-bol) (point-max))
1037 (forward-line 1)
1038 (markdown-cur-line-blank-p))))
1040 (defun markdown-prev-line-indent-p ()
1041 "Return t if the previous line is indented and nil otherwise."
1042 (save-excursion
1043 (forward-line -1)
1044 (goto-char (point-at-bol))
1045 (if (re-search-forward "^\\s " (point-at-eol) t) t)))
1047 (defun markdown-cur-line-indent ()
1048 "Return the number of leading whitespace characters in the current line."
1049 (save-excursion
1050 (goto-char (point-at-bol))
1051 (re-search-forward "^\\s +" (point-at-eol) t)
1052 (current-column)))
1054 (defun markdown-prev-line-indent ()
1055 "Return the number of leading whitespace characters in the previous line."
1056 (save-excursion
1057 (forward-line -1)
1058 (markdown-cur-line-indent)))
1060 (defun markdown-next-line-indent ()
1061 "Return the number of leading whitespace characters in the next line."
1062 (save-excursion
1063 (forward-line 1)
1064 (markdown-cur-line-indent)))
1066 (defun markdown-cur-non-list-indent ()
1067 "Return the number of leading whitespace characters in the current line."
1068 (save-excursion
1069 (beginning-of-line)
1070 (when (re-search-forward markdown-regex-list-indent (point-at-eol) t)
1071 (current-column))))
1073 (defun markdown-prev-non-list-indent ()
1074 "Return position of the first non-list-marker on the previous line."
1075 (save-excursion
1076 (forward-line -1)
1077 (markdown-cur-non-list-indent)))
1079 (defun markdown--next-block ()
1080 "Move the point to the start of the next text block."
1081 (forward-line)
1082 (while (and (or (not (markdown-prev-line-blank-p))
1083 (markdown-cur-line-blank-p))
1084 (not (eobp)))
1085 (forward-line)))
1087 (defun markdown--end-of-level (level)
1088 "Move the point to the end of region with indentation at least LEVEL."
1089 (let (indent)
1090 (while (and (not (< (setq indent (markdown-cur-line-indent)) level))
1091 (not (>= indent (+ level 4)))
1092 (not (eobp)))
1093 (markdown--next-block))
1094 (unless (eobp)
1095 ;; Move back before any trailing blank lines
1096 (while (and (markdown-prev-line-blank-p)
1097 (not (bobp)))
1098 (forward-line -1))
1099 (forward-line -1)
1100 (end-of-line))))
1102 ;; From html-helper-mode
1103 (defun markdown-match-comments (last)
1104 "Match HTML comments from the point to LAST."
1105 (cond ((search-forward "<!--" last t)
1106 (backward-char 4)
1107 (let ((beg (point)))
1108 (cond ((search-forward-regexp "--[ \t]*>" last t)
1109 (set-match-data (list beg (point)))
1111 (t nil))))
1112 (t nil)))
1114 (defun markdown-match-pre-blocks (last)
1115 "Match Markdown pre blocks from point to LAST.
1116 A region matches as if it is indented at least four spaces
1117 relative to the nearest previous block of lesser non-list-marker
1118 indentation."
1120 (let (cur-begin cur-end cur-indent prev-indent prev-list stop match found)
1121 ;; Don't start in the middle of a block
1122 (unless (and (bolp)
1123 (markdown-prev-line-blank-p)
1124 (not (markdown-cur-line-blank-p)))
1125 (markdown--next-block))
1127 ;; Move to the first full block in the region with indent 4 or more
1128 (while (and (not (>= (setq cur-indent (markdown-cur-line-indent)) 4))
1129 (not (>= (point) last)))
1130 (markdown--next-block))
1131 (setq cur-begin (point))
1132 (markdown--end-of-level cur-indent)
1133 (setq cur-end (point))
1134 (setq match nil)
1135 (setq stop (> cur-begin cur-end))
1137 (while (and (<= cur-end last) (not stop) (not match))
1138 ;; Move to the nearest preceding block of lesser (non-marker) indentation
1139 (setq prev-indent (+ cur-indent 1))
1140 (goto-char cur-begin)
1141 (setq found nil)
1142 (while (and (>= prev-indent cur-indent)
1143 (not (and prev-list
1144 (eq prev-indent cur-indent)))
1145 (not (bobp)))
1147 ;; Move point to the last line of the previous block.
1148 (forward-line -1)
1149 (while (and (markdown-cur-line-blank-p)
1150 (not (bobp)))
1151 (forward-line -1))
1153 ;; Update the indentation level using either the
1154 ;; non-list-marker indentation, if the previous line is the
1155 ;; start of a list, or the actual indentation.
1156 (setq prev-list (markdown-cur-non-list-indent))
1157 (setq prev-indent (or prev-list
1158 (markdown-cur-line-indent)))
1159 (setq found t))
1161 ;; If the loop didn't execute
1162 (unless found
1163 (setq prev-indent 0))
1165 ;; Compare with prev-indent minus its remainder mod 4
1166 (setq prev-indent (- prev-indent (mod prev-indent 4)))
1168 ;; Set match data and return t if we have a match
1169 (if (>= cur-indent (+ prev-indent 4))
1170 ;; Match
1171 (progn
1172 (setq match t)
1173 (set-match-data (list cur-begin cur-end))
1174 ;; Leave point at end of block
1175 (goto-char cur-end)
1176 (forward-line))
1178 ;; Move to the next block (if possible)
1179 (goto-char cur-end)
1180 (markdown--next-block)
1181 (setq cur-begin (point))
1182 (setq cur-indent (markdown-cur-line-indent))
1183 (markdown--end-of-level cur-indent)
1184 (setq cur-end (point))
1185 (setq stop (equal cur-begin cur-end))))
1186 match))
1188 (defun markdown-match-fenced-code-blocks (last)
1189 "Match fenced code blocks from the point to LAST."
1190 (cond ((search-forward-regexp "^\\([~]\\{3,\\}\\)" last t)
1191 (beginning-of-line)
1192 (let ((beg (point)))
1193 (forward-line)
1194 (cond ((search-forward-regexp
1195 (concat "^" (match-string 1) "~*") last t)
1196 (set-match-data (list beg (point)))
1198 (t nil))))
1199 (t nil)))
1201 (defun markdown-font-lock-extend-region ()
1202 "Extend the search region to include an entire block of text.
1203 This helps improve font locking for block constructs such as pre blocks."
1204 ;; Avoid compiler warnings about these global variables from font-lock.el.
1205 ;; See the documentation for variable `font-lock-extend-region-functions'.
1206 (eval-when-compile (defvar font-lock-beg) (defvar font-lock-end))
1207 (save-excursion
1208 (goto-char font-lock-beg)
1209 (let ((found (re-search-backward "\n\n" nil t)))
1210 (when found
1211 (goto-char font-lock-end)
1212 (when (re-search-forward "\n\n" nil t)
1213 (beginning-of-line)
1214 (setq font-lock-end (point)))
1215 (setq font-lock-beg found)))))
1219 ;;; Syntax Table ==============================================================
1221 (defvar markdown-mode-syntax-table
1222 (let ((markdown-mode-syntax-table (make-syntax-table)))
1223 (modify-syntax-entry ?\" "w" markdown-mode-syntax-table)
1224 markdown-mode-syntax-table)
1225 "Syntax table for `markdown-mode'.")
1229 ;;; Element Insertion =========================================================
1231 (defun markdown-wrap-or-insert (s1 s2)
1232 "Insert the strings S1 and S2.
1233 If Transient Mark mode is on and a region is active, wrap the strings S1
1234 and S2 around the region."
1235 (if (markdown-transient-mark-mode-active)
1236 (let ((a (region-beginning)) (b (region-end)))
1237 (goto-char a)
1238 (insert s1)
1239 (goto-char (+ b (length s1)))
1240 (insert s2))
1241 (insert s1 s2)))
1243 (defun markdown-insert-hr ()
1244 "Insert a horizonal rule using `markdown-hr-string'."
1245 (interactive)
1246 ;; Leading blank line
1247 (when (and (>= (point) (+ (point-min) 2))
1248 (not (looking-back "\n\n" 2)))
1249 (insert "\n"))
1250 ;; Insert custom HR string
1251 (insert (concat markdown-hr-string "\n"))
1252 ;; Following blank line
1253 (backward-char)
1254 (unless (looking-at "\n\n")
1255 (insert "\n")))
1257 (defun markdown-insert-bold ()
1258 "Insert markup for a bold word or phrase.
1259 If Transient Mark mode is on and a region is active, it is made bold."
1260 (interactive)
1261 (if markdown-bold-underscore
1262 (markdown-wrap-or-insert "__" "__")
1263 (markdown-wrap-or-insert "**" "**"))
1264 (backward-char 2))
1266 (defun markdown-insert-italic ()
1267 "Insert markup for an italic word or phrase.
1268 If Transient Mark mode is on and a region is active, it is made italic."
1269 (interactive)
1270 (if markdown-italic-underscore
1271 (markdown-wrap-or-insert "_" "_")
1272 (markdown-wrap-or-insert "*" "*"))
1273 (backward-char 1))
1275 (defun markdown-insert-code ()
1276 "Insert markup for an inline code fragment.
1277 If Transient Mark mode is on and a region is active, it is marked
1278 as inline code."
1279 (interactive)
1280 (markdown-wrap-or-insert "`" "`")
1281 (backward-char 1))
1283 (defun markdown-insert-link ()
1284 "Insert an inline link of the form []().
1285 If Transient Mark mode is on and a region is active, it is used
1286 as the link text."
1287 (interactive)
1288 (markdown-wrap-or-insert "[" "]")
1289 (insert "()")
1290 (backward-char 1))
1292 (defun markdown-insert-reference-link-dwim ()
1293 "Insert a reference link of the form [text][label] at point.
1294 If Transient Mark mode is on and a region is active, the region
1295 is used as the link text. Otherwise, the link text will be read
1296 from the minibuffer. The link URL, label, and title will be read
1297 from the minibuffer. The link label definition is placed at the
1298 end of the current paragraph."
1299 (interactive)
1300 (if (markdown-transient-mark-mode-active)
1301 (call-interactively 'markdown-insert-reference-link-region)
1302 (call-interactively 'markdown-insert-reference-link)))
1304 (defun markdown-insert-reference-link-region (url label title)
1305 "Insert a reference link at point using the region as the link text."
1306 (interactive "sLink URL: \nsLink Label (optional): \nsLink Title (optional): ")
1307 (let ((text (buffer-substring (region-beginning) (region-end))))
1308 (delete-region (region-beginning) (region-end))
1309 (markdown-insert-reference-link text url label title)))
1311 (defun markdown-insert-reference-link (text url label title)
1312 "Insert a reference link at point.
1313 The link label definition is placed at the end of the current
1314 paragraph."
1315 (interactive "sLink Text: \nsLink URL: \nsLink Label (optional): \nsLink Title (optional): ")
1316 (let (end)
1317 (insert (concat "[" text "][" label "]"))
1318 (setq end (point))
1319 (forward-paragraph)
1320 (insert "\n[")
1321 (if (> (length label) 0)
1322 (insert label)
1323 (insert text))
1324 (insert (concat "]: " url))
1325 (unless (> (length url) 0)
1326 (setq end (point)))
1327 (when (> (length title) 0)
1328 (insert (concat " \"" title "\"")))
1329 (insert "\n")
1330 (unless (looking-at "\n")
1331 (insert "\n"))
1332 (goto-char end)))
1334 (defun markdown-insert-wiki-link ()
1335 "Insert a wiki link of the form [[WikiLink]].
1336 If Transient Mark mode is on and a region is active, it is used
1337 as the link text."
1338 (interactive)
1339 (markdown-wrap-or-insert "[[" "]]")
1340 (backward-char 2))
1342 (defun markdown-insert-image ()
1343 "Insert an inline image tag of the form ![]().
1344 If Transient Mark mode is on and a region is active, it is used
1345 as the alt text of the image."
1346 (interactive)
1347 (markdown-wrap-or-insert "![" "]")
1348 (insert "()")
1349 (backward-char 1))
1351 (defun markdown-insert-header-1 ()
1352 "Insert a first level atx-style (hash mark) header.
1353 If Transient Mark mode is on and a region is active, it is used
1354 as the header text."
1355 (interactive)
1356 (markdown-insert-header 1))
1358 (defun markdown-insert-header-2 ()
1359 "Insert a second level atx-style (hash mark) header.
1360 If Transient Mark mode is on and a region is active, it is used
1361 as the header text."
1362 (interactive)
1363 (markdown-insert-header 2))
1365 (defun markdown-insert-header-3 ()
1366 "Insert a third level atx-style (hash mark) header.
1367 If Transient Mark mode is on and a region is active, it is used
1368 as the header text."
1369 (interactive)
1370 (markdown-insert-header 3))
1372 (defun markdown-insert-header-4 ()
1373 "Insert a fourth level atx-style (hash mark) header.
1374 If Transient Mark mode is on and a region is active, it is used
1375 as the header text."
1376 (interactive)
1377 (markdown-insert-header 4))
1379 (defun markdown-insert-header-5 ()
1380 "Insert a fifth level atx-style (hash mark) header.
1381 If Transient Mark mode is on and a region is active, it is used
1382 as the header text."
1383 (interactive)
1384 (markdown-insert-header 5))
1386 (defun markdown-insert-header-6 ()
1387 "Insert a sixth level atx-style (hash mark) header.
1388 If Transient Mark mode is on and a region is active, it is used
1389 as the header text."
1390 (interactive)
1391 (markdown-insert-header 6))
1393 (defun markdown-insert-header (n)
1394 "Insert an atx-style (hash mark) header.
1395 With no prefix argument, insert a level-1 header. With prefix N,
1396 insert a level-N header. If Transient Mark mode is on and the
1397 region is active, it is used as the header text."
1398 (interactive "p")
1399 (unless n ; Test to see if n is defined
1400 (setq n 1)) ; Default to level 1 header
1401 (let (hdr hdrl hdrr)
1402 (dotimes (count n hdr)
1403 (setq hdr (concat "#" hdr))) ; Build a hash mark header string
1404 (setq hdrl (concat hdr " "))
1405 (setq hdrr (concat " " hdr))
1406 (markdown-wrap-or-insert hdrl hdrr))
1407 (backward-char (+ 1 n)))
1409 (defun markdown-insert-title ()
1410 "Insert a setext-style (underline) first level header.
1411 If Transient Mark mode is on and a region is active, it is used
1412 as the header text."
1413 (interactive)
1414 (if (markdown-transient-mark-mode-active)
1415 (let ((a (region-beginning))
1416 (b (region-end))
1417 (len 0)
1418 (hdr))
1419 (setq len (- b a))
1420 (dotimes (count len hdr)
1421 (setq hdr (concat "=" hdr))) ; Build a === title underline
1422 (end-of-line)
1423 (insert "\n" hdr "\n"))
1424 (insert "\n==========\n")
1425 (backward-char 12)))
1427 (defun markdown-insert-section ()
1428 "Insert a setext-style (underline) second level header.
1429 If Transient Mark mode is on and a region is active, it is used
1430 as the header text."
1431 (interactive)
1432 (if (markdown-transient-mark-mode-active)
1433 (let ((a (region-beginning))
1434 (b (region-end))
1435 (len 0)
1436 (hdr))
1437 (setq len (- b a))
1438 (dotimes (count len hdr)
1439 (setq hdr (concat "-" hdr))) ; Build a --- section underline
1440 (end-of-line)
1441 (insert "\n" hdr "\n"))
1442 (insert "\n----------\n")
1443 (backward-char 12)))
1445 (defun markdown-insert-blockquote ()
1446 "Start a blockquote section (or blockquote the region).
1447 If Transient Mark mode is on and a region is active, it is used as
1448 the blockquote text."
1449 (interactive)
1450 (if (markdown-transient-mark-mode-active)
1451 (markdown-blockquote-region (region-beginning) (region-end))
1452 (insert "> ")))
1454 (defun markdown-block-region (beg end prefix)
1455 "Format the region using a block prefix.
1456 Arguments BEG and END specify the beginning and end of the
1457 region. The characters PREFIX will appear at the beginning
1458 of each line."
1459 (if mark-active
1460 (save-excursion
1461 ;; Ensure that there is a leading blank line
1462 (goto-char beg)
1463 (when (and (>= (point) (+ (point-min) 2))
1464 (not (looking-back "\n\n" 2)))
1465 (insert "\n")
1466 (setq beg (1+ beg))
1467 (setq end (1+ end)))
1468 ;; Move back before any blank lines at the end
1469 (goto-char end)
1470 (while (and (looking-back "\n" 1)
1471 (not (equal (point) (point-min))))
1472 (backward-char)
1473 (setq end (1- end)))
1474 ;; Ensure that there is a trailing blank line
1475 (goto-char end)
1476 (if (not (or (looking-at "\n\n")
1477 (and (equal (1+ end) (point-max)) (looking-at "\n"))))
1478 (insert "\n"))
1479 ;; Insert PREFIX
1480 (goto-char beg)
1481 (beginning-of-line)
1482 (while (< (point-at-bol) end)
1483 (insert prefix)
1484 (setq end (+ (length prefix) end))
1485 (forward-line)))))
1487 (defun markdown-blockquote-region (beg end)
1488 "Blockquote the region.
1489 Arguments BEG and END specify the beginning and end of the region."
1490 (interactive "*r")
1491 (markdown-block-region beg end "> "))
1493 (defun markdown-insert-pre ()
1494 "Start a preformatted section (or apply to the region).
1495 If Transient Mark mode is on and a region is active, it is marked
1496 as preformatted text."
1497 (interactive)
1498 (if (markdown-transient-mark-mode-active)
1499 (markdown-pre-region (region-beginning) (region-end))
1500 (insert " ")))
1502 (defun markdown-pre-region (beg end)
1503 "Format the region as preformatted text.
1504 Arguments BEG and END specify the beginning and end of the region."
1505 (interactive "*r")
1506 (markdown-block-region beg end " "))
1508 ;;; Footnotes ======================================================================
1510 (defun markdown-footnote-counter-inc ()
1511 "Increment markdown-footnote-counter and return the new value."
1512 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
1513 (save-excursion
1514 (goto-char (point-min))
1515 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
1516 (point-max) t)
1517 (let ((fn (string-to-number (match-string 1))))
1518 (when (> fn markdown-footnote-counter)
1519 (setq markdown-footnote-counter fn))))))
1520 (incf markdown-footnote-counter))
1522 (defun markdown-footnote-new ()
1523 "Insert a footnote with a new number and jump to a position to enter the
1524 footnote text."
1525 (interactive)
1526 (let ((fn (markdown-footnote-counter-inc)))
1527 (insert (format "[^%d]" fn))
1528 (markdown-footnote-text-find-new-location)
1529 (insert (format "[^%d]: " fn))))
1531 (defun markdown-footnote-text-find-new-location ()
1532 "Position the cursor at the proper location for a new footnote text."
1533 (cond
1534 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
1535 ((eq markdown-footnote-location 'immediately) (forward-paragraph))
1536 ((eq markdown-footnote-location 'header)
1537 ;; search for a header. if none is found, go to the end of the document.
1538 (catch 'eof
1539 (while (progn
1540 (forward-paragraph)
1541 (unless (re-search-forward markdown-regex-header nil t)
1542 (throw 'eof nil))
1543 (backward-paragraph)
1544 (not (looking-at (concat "\n" markdown-regex-header))))))))
1545 ;; make sure we're on an empty line:
1546 (unless (markdown-cur-line-blank-p)
1547 (insert "\n"))
1548 ;; and make sure the previous line is empty:
1549 (unless (markdown-prev-line-blank-p)
1550 (insert "\n"))
1551 ;; then make sure there's an empty line following the footnote:
1552 (unless (markdown-next-line-blank-p)
1553 (insert "\n")
1554 (forward-line -1)))
1556 (defun markdown-footnote-kill ()
1557 "Kill the footnote at point.
1558 The footnote text is killed (and added to the kill ring), the
1559 footnote marker is deleted. Point has to be either at the
1560 footnote marker or in the footnote text."
1561 (interactive)
1562 (let (return-pos)
1563 (when (markdown-footnote-text-positions) ; if we're in a footnote text
1564 (markdown-footnote-return) ; we first move to the marker
1565 (setq return-pos 'text)) ; and remember our return position
1566 (let ((marker (markdown-footnote-delete-marker)))
1567 (unless marker
1568 (error "Not at a footnote"))
1569 (let ((text-pos (markdown-footnote-find-text (car marker))))
1570 (unless text-pos
1571 (error "No text for footnote `%s'" (car marker)))
1572 (goto-char text-pos)
1573 (let ((pos (markdown-footnote-kill-text)))
1574 (setq return-pos
1575 (if (and pos (eq return-pos 'text))
1577 (cadr marker))))))
1578 (goto-char return-pos)))
1580 (defun markdown-footnote-delete-marker ()
1581 "Delete a footnote marker at point.
1582 Returns a list (ID START) containing the footnote ID and the
1583 start position of the marker before deletion. If no footnote
1584 marker was deleted, this function returns NIL."
1585 (let ((marker (markdown-footnote-marker-positions)))
1586 (when marker
1587 (delete-region (second marker) (third marker))
1588 (butlast marker))))
1590 (defun markdown-footnote-kill-text ()
1591 "Kill footnote text at point.
1592 Returns the start position of the footnote text before deletion,
1593 or NIL if point was not inside a footnote text.
1595 The killed text is placed in the kill ring (without the footnote
1596 number)."
1597 (let ((fn (markdown-footnote-text-positions)))
1598 (when fn
1599 (let ((text (delete-and-extract-region (second fn) (third fn))))
1600 (string-match (concat "\\[\\" (first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
1601 (kill-new (match-string 1 text))
1602 (second fn)))))
1604 (defun markdown-footnote-goto-text ()
1605 "Jump to the text of the footnote at point."
1606 (interactive)
1607 (let ((fn (car (markdown-footnote-marker-positions))))
1608 (unless fn
1609 (error "Not at a footnote marker"))
1610 (let ((new-pos (markdown-footnote-find-text fn)))
1611 (unless new-pos
1612 (error "No definition found for footnote `%s'" fn))
1613 (goto-char new-pos))))
1615 (defun markdown-footnote-return ()
1616 "Return from a footnote to its footnote number in the main text."
1617 (interactive)
1618 (let ((fn (save-excursion
1619 (car (markdown-footnote-text-positions)))))
1620 (unless fn
1621 (error "Not in a footnote"))
1622 (let ((new-pos (markdown-footnote-find-marker fn)))
1623 (unless new-pos
1624 (error "Footnote marker `%s' not found" fn))
1625 (goto-char new-pos))))
1627 (defun markdown-footnote-find-marker (id)
1628 "Find the location of the footnote marker with ID.
1629 The actual buffer position returned is the position directly
1630 following the marker's closing bracket. If no marker is found,
1631 NIL is returned."
1632 (save-excursion
1633 (goto-char (point-min))
1634 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
1635 (skip-chars-backward "^]")
1636 (point))))
1638 (defun markdown-footnote-find-text (id)
1639 "Find the location of the text of footnote ID.
1640 The actual buffer position returned is the position of the first
1641 character of the text, after the footnote's identifier. If no
1642 footnote text is found, NIL is returned."
1643 (save-excursion
1644 (goto-char (point-min))
1645 (when (re-search-forward (concat "^\\[" id "\\]:") nil t)
1646 (skip-chars-forward "[:space:]")
1647 (point))))
1649 (defun markdown-footnote-marker-positions ()
1650 "Return the position and ID of the footnote marker point is on.
1651 The return value is a list (ID START END). If point is not on a
1652 footnote, NIL is returned."
1653 ;; first make sure we're at a footnote marker
1654 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (point-at-bol))
1655 (looking-at (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
1656 (save-excursion
1657 ;; move point between [ and ^:
1658 (if (looking-at "\\[")
1659 (forward-char 1)
1660 (skip-chars-backward "^["))
1661 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
1662 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
1664 (defun markdown-footnote-text-positions ()
1665 "Return the start and end positions of the footnote text point is in.
1666 The exact return value is a list of three elements: (ID START
1667 END). The start position is the position of the opening bracket
1668 of the footnote id. The end position is directly after the
1669 newline that ends the footnote. If point is not in a footnote,
1670 NIL is returned instead."
1671 (save-excursion
1672 (let ((fn (progn
1673 (backward-paragraph)
1674 ;; if we're in a multiparagraph footnote, we need to back up further
1675 (while (>= (markdown-next-line-indent) 4)
1676 (backward-paragraph))
1677 (forward-line)
1678 (if (looking-at (concat "^\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:"))
1679 (list (match-string 1) (point))))))
1680 (when fn
1681 (while (progn
1682 (forward-paragraph)
1683 (>= (markdown-next-line-indent) 4)))
1684 (append fn (list (point)))))))
1686 ;;; Indentation ====================================================================
1688 (defun markdown-indent-find-next-position (cur-pos positions)
1689 "Return the position after the index of CUR-POS in POSITIONS."
1690 (while (and positions
1691 (not (equal cur-pos (car positions))))
1692 (setq positions (cdr positions)))
1693 (or (cadr positions) 0))
1695 (defun markdown-indent-line ()
1696 "Indent the current line using some heuristics.
1697 If the _previous_ command was either `markdown-enter-key' or
1698 `markdown-cycle', then we should cycle to the next
1699 reasonable indentation position. Otherwise, we could have been
1700 called directly by `markdown-enter-key', by an initial call of
1701 `markdown-cycle', or indirectly by `auto-fill-mode'. In
1702 these cases, indent to the default position."
1703 (interactive)
1704 (let ((positions (markdown-calc-indents))
1705 (cur-pos (current-column)))
1706 (if (not (equal this-command 'markdown-cycle))
1707 (indent-line-to (car positions))
1708 (setq positions (sort (delete-dups positions) '<))
1709 (indent-line-to
1710 (markdown-indent-find-next-position cur-pos positions)))))
1712 (defun markdown-calc-indents ()
1713 "Return a list of indentation columns to cycle through.
1714 The first element in the returned list should be considered the
1715 default indentation level."
1716 (let (pos prev-line-pos positions)
1718 ;; Previous line indent
1719 (setq prev-line-pos (markdown-prev-line-indent))
1720 (setq positions (cons prev-line-pos positions))
1722 ;; Previous non-list-marker indent
1723 (setq pos (markdown-prev-non-list-indent))
1724 (when pos
1725 (setq positions (cons pos positions))
1726 (setq positions (cons (+ pos tab-width) positions)))
1728 ;; Indentation of the previous line + tab-width
1729 (cond
1730 (prev-line-pos
1731 (setq positions (cons (+ prev-line-pos tab-width) positions)))
1733 (setq positions (cons tab-width positions))))
1735 ;; Indentation of the previous line - tab-width
1736 (if (and prev-line-pos
1737 (> prev-line-pos tab-width))
1738 (setq positions (cons (- prev-line-pos tab-width) positions)))
1740 ;; Indentation of preceeding list item
1741 (setq pos
1742 (save-excursion
1743 (forward-line -1)
1744 (catch 'break
1745 (while (not (equal (point) (point-min)))
1746 (forward-line -1)
1747 (goto-char (point-at-bol))
1748 (when (re-search-forward markdown-regex-list-indent (point-at-eol) t)
1749 (throw 'break (length (match-string 1)))))
1750 nil)))
1751 (if (and pos (not (eq pos prev-line-pos)))
1752 (setq positions (cons pos positions)))
1754 ;; First column
1755 (setq positions (cons 0 positions))
1757 (reverse positions)))
1759 (defun markdown-do-normal-return ()
1760 "Insert a newline and optionally indent the next line."
1761 (newline)
1762 (if markdown-indent-on-enter
1763 (funcall indent-line-function)))
1765 (defun markdown-enter-key ()
1766 "Handle RET according to context.
1767 If there is a wiki link at the point, follow it unless
1768 `markdown-follow-wiki-link-on-enter' is nil. Otherwise, process
1769 it in the usual way."
1770 (interactive)
1771 (if (and markdown-follow-wiki-link-on-enter (markdown-wiki-link-p))
1772 (markdown-follow-wiki-link-at-point)
1773 (markdown-do-normal-return)))
1775 (defun markdown-dedent-or-delete ()
1776 "Handle BACKSPACE by cycling through indentation points.
1777 When BACKSPACE is pressed, if there is only whitespace
1778 before the current point, then dedent the line one level.
1779 Otherwise, do normal delete."
1780 (interactive)
1781 (let ((cur-pos (current-column))
1782 (start-of-indention (save-excursion
1783 (back-to-indentation)
1784 (current-column))))
1785 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
1786 (let ((result 0))
1787 (dolist (i (markdown-calc-indents))
1788 (when (< i cur-pos)
1789 (setq result (max result i))))
1790 (indent-line-to result))
1791 (delete-backward-char 1))))
1795 ;;; Keymap ====================================================================
1797 (defvar markdown-mode-map
1798 (let ((map (make-keymap)))
1799 ;; Element insertion
1800 (define-key map "\C-c\C-al" 'markdown-insert-link)
1801 (define-key map "\C-c\C-ar" 'markdown-insert-reference-link-dwim)
1802 (define-key map "\C-c\C-aw" 'markdown-insert-wiki-link)
1803 (define-key map "\C-c\C-ii" 'markdown-insert-image)
1804 (define-key map "\C-c\C-t1" 'markdown-insert-header-1)
1805 (define-key map "\C-c\C-t2" 'markdown-insert-header-2)
1806 (define-key map "\C-c\C-t3" 'markdown-insert-header-3)
1807 (define-key map "\C-c\C-t4" 'markdown-insert-header-4)
1808 (define-key map "\C-c\C-t5" 'markdown-insert-header-5)
1809 (define-key map "\C-c\C-t6" 'markdown-insert-header-6)
1810 (define-key map "\C-c\C-pb" 'markdown-insert-bold)
1811 (define-key map "\C-c\C-ss" 'markdown-insert-bold)
1812 (define-key map "\C-c\C-pi" 'markdown-insert-italic)
1813 (define-key map "\C-c\C-se" 'markdown-insert-italic)
1814 (define-key map "\C-c\C-pf" 'markdown-insert-code)
1815 (define-key map "\C-c\C-sc" 'markdown-insert-code)
1816 (define-key map "\C-c\C-sb" 'markdown-insert-blockquote)
1817 (define-key map "\C-c\C-s\C-b" 'markdown-blockquote-region)
1818 (define-key map "\C-c\C-sp" 'markdown-insert-pre)
1819 (define-key map "\C-c\C-s\C-p" 'markdown-pre-region)
1820 (define-key map "\C-c-" 'markdown-insert-hr)
1821 (define-key map "\C-c\C-tt" 'markdown-insert-title)
1822 (define-key map "\C-c\C-ts" 'markdown-insert-section)
1823 ;; Footnotes
1824 (define-key map "\C-c\C-fn" 'markdown-footnote-new)
1825 (define-key map "\C-c\C-fg" 'markdown-footnote-goto-text)
1826 (define-key map "\C-c\C-fb" 'markdown-footnote-return)
1827 (define-key map "\C-c\C-fk" 'markdown-footnote-kill)
1828 ;; Regular Link Following
1829 (define-key map "\C-c\C-o" 'markdown-follow-link-at-point)
1830 ;; WikiLink Following
1831 (define-key map "\C-c\C-w" 'markdown-follow-wiki-link-at-point)
1832 (define-key map "\M-n" 'markdown-next-wiki-link)
1833 (define-key map "\M-p" 'markdown-previous-wiki-link)
1834 ;; Indentation
1835 (define-key map "\C-m" 'markdown-enter-key)
1836 (define-key map (kbd "<backspace>") 'markdown-dedent-or-delete)
1837 ;; Visibility cycling
1838 (define-key map (kbd "<tab>") 'markdown-cycle)
1839 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
1840 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
1841 (define-key map (kbd "<backtab>") 'markdown-shifttab)
1842 ;; Header navigation
1843 (define-key map (kbd "C-M-n") 'outline-next-visible-heading)
1844 (define-key map (kbd "C-M-p") 'outline-previous-visible-heading)
1845 (define-key map (kbd "C-M-f") 'outline-forward-same-level)
1846 (define-key map (kbd "C-M-b") 'outline-backward-same-level)
1847 (define-key map (kbd "C-M-u") 'outline-up-heading)
1848 ;; Markdown functions
1849 (define-key map "\C-c\C-cm" 'markdown-other-window)
1850 (define-key map "\C-c\C-cp" 'markdown-preview)
1851 (define-key map "\C-c\C-ce" 'markdown-export)
1852 (define-key map "\C-c\C-cv" 'markdown-export-and-preview)
1853 ;; References
1854 (define-key map "\C-c\C-cc" 'markdown-check-refs)
1855 map)
1856 "Keymap for Markdown major mode.")
1858 ;;; Menu ==================================================================
1860 (easy-menu-define markdown-mode-menu markdown-mode-map
1861 "Menu for Markdown mode"
1862 '("Markdown"
1863 ("Show/Hide"
1864 ["Cycle visibility" markdown-cycle (outline-on-heading-p)]
1865 ["Cycle global visibility" markdown-shifttab])
1866 "---"
1867 ["Compile" markdown-other-window]
1868 ["Preview" markdown-preview]
1869 ["Export" markdown-export]
1870 ["Export & View" markdown-export-and-preview]
1871 "---"
1872 ("Headers (setext)"
1873 ["Insert Title" markdown-insert-title]
1874 ["Insert Section" markdown-insert-section])
1875 ("Headers (atx)"
1876 ["First level" markdown-insert-header-1]
1877 ["Second level" markdown-insert-header-2]
1878 ["Third level" markdown-insert-header-3]
1879 ["Fourth level" markdown-insert-header-4]
1880 ["Fifth level" markdown-insert-header-5]
1881 ["Sixth level" markdown-insert-header-6])
1882 "---"
1883 ["Bold" markdown-insert-bold]
1884 ["Italic" markdown-insert-italic]
1885 ["Blockquote" markdown-insert-blockquote]
1886 ["Preformatted" markdown-insert-pre]
1887 ["Code" markdown-insert-code]
1888 "---"
1889 ["Insert inline link" markdown-insert-link]
1890 ["Insert reference link" markdown-insert-reference-link-dwim]
1891 ["Insert image" markdown-insert-image]
1892 ["Insert horizontal rule" markdown-insert-hr]
1893 "---"
1894 ("Footnotes"
1895 ["Insert footnote" markdown-footnote-new]
1896 ["Jump to footnote text" markdown-footnote-goto-text]
1897 ["Return from footnote" markdown-footnote-return])
1898 "---"
1899 ["Check references" markdown-check-refs]
1900 "---"
1901 ["Version" markdown-show-version]
1906 ;;; imenu =====================================================================
1908 (defun markdown-imenu-create-index ()
1909 (let* ((root '(nil . nil))
1910 cur-alist
1911 (cur-level 0)
1912 (pattern "^\\(\\(#+\\)[ \t]*\\(.+\\)\\|\\([^# \t\n=-].*\\)\n===+\\|\\([^# \t\n=-].*\\)\n---+\\)$")
1913 (empty-heading "-")
1914 (self-heading ".")
1915 hashes pos level heading)
1916 (save-excursion
1917 (goto-char (point-min))
1918 (while (re-search-forward pattern (point-max) t)
1919 (cond
1920 ((setq hashes (match-string-no-properties 2))
1921 (setq heading (match-string-no-properties 3)
1922 pos (match-beginning 1)
1923 level (length hashes)))
1924 ((setq heading (match-string-no-properties 4))
1925 (setq pos (match-beginning 4)
1926 level 1))
1927 ((setq heading (match-string-no-properties 5))
1928 (setq pos (match-beginning 5)
1929 level 2)))
1930 (let ((alist (list (cons heading pos))))
1931 (cond
1932 ((= cur-level level) ; new sibling
1933 (setcdr cur-alist alist)
1934 (setq cur-alist alist))
1935 ((< cur-level level) ; first child
1936 (dotimes (i (- level cur-level 1))
1937 (setq alist (list (cons empty-heading alist))))
1938 (if cur-alist
1939 (let* ((parent (car cur-alist))
1940 (self-pos (cdr parent)))
1941 (setcdr parent (cons (cons self-heading self-pos) alist)))
1942 (setcdr root alist)) ; primogenitor
1943 (setq cur-alist alist)
1944 (setq cur-level level))
1945 (t ; new sibling of an ancestor
1946 (let ((sibling-alist (last (cdr root))))
1947 (dotimes (i (1- level))
1948 (setq sibling-alist (last (cdar sibling-alist))))
1949 (setcdr sibling-alist alist)
1950 (setq cur-alist alist))
1951 (setq cur-level level)))))
1952 (cdr root))))
1954 ;;; References ================================================================
1956 ;;; Undefined reference checking code by Dmitry Dzhus <mail@sphinx.net.ru>.
1958 (defconst markdown-refcheck-buffer
1959 "*Undefined references for %buffer%*"
1960 "Pattern for name of buffer for listing undefined references.
1961 The string %buffer% will be replaced by the corresponding
1962 `markdown-mode' buffer name.")
1964 (defun markdown-has-reference-definition (reference)
1965 "Find out whether Markdown REFERENCE is defined.
1967 REFERENCE should include the square brackets, like [this]."
1968 (let ((reference (downcase reference)))
1969 (save-excursion
1970 (goto-char (point-min))
1971 (catch 'found
1972 (while (re-search-forward markdown-regex-reference-definition nil t)
1973 (when (string= reference (downcase (match-string-no-properties 1)))
1974 (throw 'found (match-string-no-properties 2))))))))
1976 (defun markdown-get-undefined-refs ()
1977 "Return a list of undefined Markdown references.
1979 Result is an alist of pairs (reference . occurencies), where
1980 occurencies is itself another alist of pairs (label .
1981 line-number).
1983 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
1984 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
1985 \((\"[emacs]\" (\"[Nice editor]\" . 12) (\"[GNU Emacs]\" . 45)) (\"[elisp]\" (\"[manual]\" . 127)))."
1986 (let ((missing))
1987 (save-excursion
1988 (goto-char (point-min))
1989 (while
1990 (re-search-forward markdown-regex-link-reference nil t)
1991 (let* ((label (match-string-no-properties 1))
1992 (reference (match-string-no-properties 2))
1993 (target (downcase (if (string= reference "[]") label reference))))
1994 (unless (markdown-has-reference-definition target)
1995 (let ((entry (assoc target missing)))
1996 (if (not entry)
1997 (add-to-list 'missing (cons target
1998 (list (cons label (markdown-line-number-at-pos)))) t)
1999 (setcdr entry
2000 (append (cdr entry) (list (cons label (markdown-line-number-at-pos))))))))))
2001 missing)))
2003 (defun markdown-add-missing-ref-definition (ref buffer &optional recheck)
2004 "Add blank REF definition to the end of BUFFER.
2006 REF is a Markdown reference in square brackets, like \"[lisp-history]\".
2008 When RECHECK is non-nil, BUFFER gets rechecked for undefined
2009 references so that REF disappears from the list of those links."
2010 (with-current-buffer buffer
2011 (when (not (eq major-mode 'markdown-mode))
2012 (error "Not available in current mode"))
2013 (goto-char (point-max))
2014 (indent-new-comment-line)
2015 (insert (concat ref ": ")))
2016 (switch-to-buffer-other-window buffer)
2017 (goto-char (point-max))
2018 (when recheck
2019 (markdown-check-refs t)))
2021 ;; Button which adds an empty Markdown reference definition to the end
2022 ;; of buffer specified as its 'target-buffer property. Reference name
2023 ;; is button's label
2024 (when (>= emacs-major-version 22)
2025 (define-button-type 'markdown-ref-button
2026 'help-echo "Push to create an empty reference definition"
2027 'face 'bold
2028 'action (lambda (b)
2029 (markdown-add-missing-ref-definition
2030 (button-label b) (button-get b 'target-buffer) t))))
2032 ;; Button jumping to line in buffer specified as its 'target-buffer
2033 ;; property. Line number is button's 'line property.
2034 (when (>= emacs-major-version 22)
2035 (define-button-type 'goto-line-button
2036 'help-echo "Push to go to this line"
2037 'face 'italic
2038 'action (lambda (b)
2039 (message (button-get b 'buffer))
2040 (switch-to-buffer-other-window (button-get b 'target-buffer))
2041 ;; use call-interactively to silence compiler
2042 (call-interactively 'goto-line (button-get b 'target-line)))))
2044 (defun markdown-check-refs (&optional silent)
2045 "Show all undefined Markdown references in current `markdown-mode' buffer.
2047 If SILENT is non-nil, do not message anything when no undefined
2048 references found.
2050 Links which have empty reference definitions are considered to be
2051 defined."
2052 (interactive "P")
2053 (when (not (eq major-mode 'markdown-mode))
2054 (error "Not available in current mode"))
2055 (let ((oldbuf (current-buffer))
2056 (refs (markdown-get-undefined-refs))
2057 (refbuf (get-buffer-create (markdown-replace-regexp-in-string
2058 "%buffer%" (buffer-name)
2059 markdown-refcheck-buffer))))
2060 (if (null refs)
2061 (progn
2062 (when (not silent)
2063 (message "No undefined references found"))
2064 (kill-buffer refbuf))
2065 (with-current-buffer refbuf
2066 (when view-mode
2067 (View-exit-and-edit))
2068 (erase-buffer)
2069 (insert "Following references lack definitions:")
2070 (newline 2)
2071 (dolist (ref refs)
2072 (let ((button-label (format "%s" (car ref))))
2073 (if (>= emacs-major-version 22)
2074 ;; Create a reference button in Emacs 22
2075 (insert-text-button button-label
2076 :type 'markdown-ref-button
2077 'target-buffer oldbuf)
2078 ;; Insert reference as text in Emacs < 22
2079 (insert button-label)))
2080 (insert " (")
2081 (dolist (occurency (cdr ref))
2082 (let ((line (cdr occurency)))
2083 (if (>= emacs-major-version 22)
2084 ;; Create a line number button in Emacs 22
2085 (insert-button (number-to-string line)
2086 :type 'goto-line-button
2087 'target-buffer oldbuf
2088 'target-line line)
2089 ;; Insert line number as text in Emacs < 22
2090 (insert (number-to-string line)))
2091 (insert " "))) (delete-char -1)
2092 (insert ")")
2093 (newline))
2094 (view-buffer-other-window refbuf)
2095 (goto-char (point-min))
2096 (forward-line 2)))))
2098 ;;; Outline ===================================================================
2100 ;; The following visibility cycling code was taken from org-mode
2101 ;; by Carsten Dominik and adapted for markdown-mode.
2103 (defvar markdown-cycle-global-status 1)
2104 (defvar markdown-cycle-subtree-status nil)
2106 ;; Based on org-end-of-subtree from org.el
2107 (defun markdown-end-of-subtree (&optional invisible-OK)
2108 "Move to the end of the current subtree.
2109 Only visible heading lines are considered, unless INVISIBLE-OK is
2110 non-nil."
2111 (outline-back-to-heading invisible-OK)
2112 (let ((first t)
2113 (level (funcall outline-level)))
2114 (while (and (not (eobp))
2115 (or first (> (funcall outline-level) level)))
2116 (setq first nil)
2117 (outline-next-heading))
2118 (if (memq (preceding-char) '(?\n ?\^M))
2119 (progn
2120 ;; Go to end of line before heading
2121 (forward-char -1)
2122 (if (memq (preceding-char) '(?\n ?\^M))
2123 ;; leave blank line before heading
2124 (forward-char -1)))))
2125 (point))
2127 ;; Based on org-cycle from org.el.
2128 (defun markdown-cycle (&optional arg)
2129 "Visibility cycling for Markdown mode.
2130 If ARG is t, perform global visibility cycling. If the point is
2131 at an atx-style header, cycle visibility of the corresponding
2132 subtree. Otherwise, insert a tab using `indent-relative'."
2133 (interactive "P")
2134 (cond
2135 ((eq arg t) ;; Global cycling
2136 (cond
2137 ((and (eq last-command this-command)
2138 (eq markdown-cycle-global-status 2))
2139 ;; Move from overview to contents
2140 (hide-sublevels 1)
2141 (message "CONTENTS")
2142 (setq markdown-cycle-global-status 3))
2144 ((and (eq last-command this-command)
2145 (eq markdown-cycle-global-status 3))
2146 ;; Move from contents to all
2147 (show-all)
2148 (message "SHOW ALL")
2149 (setq markdown-cycle-global-status 1))
2152 ;; Defaults to overview
2153 (hide-body)
2154 (message "OVERVIEW")
2155 (setq markdown-cycle-global-status 2))))
2157 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2158 ;; At a heading: rotate between three different views
2159 (outline-back-to-heading)
2160 (let ((goal-column 0) eoh eol eos)
2161 ;; Determine boundaries
2162 (save-excursion
2163 (outline-back-to-heading)
2164 (save-excursion
2165 (beginning-of-line 2)
2166 (while (and (not (eobp)) ;; this is like `next-line'
2167 (get-char-property (1- (point)) 'invisible))
2168 (beginning-of-line 2)) (setq eol (point)))
2169 (outline-end-of-heading) (setq eoh (point))
2170 (markdown-end-of-subtree t)
2171 (skip-chars-forward " \t\n")
2172 (beginning-of-line 1) ; in case this is an item
2173 (setq eos (1- (point))))
2174 ;; Find out what to do next and set `this-command'
2175 (cond
2176 ((= eos eoh)
2177 ;; Nothing is hidden behind this heading
2178 (message "EMPTY ENTRY")
2179 (setq markdown-cycle-subtree-status nil))
2180 ((>= eol eos)
2181 ;; Entire subtree is hidden in one line: open it
2182 (show-entry)
2183 (show-children)
2184 (message "CHILDREN")
2185 (setq markdown-cycle-subtree-status 'children))
2186 ((and (eq last-command this-command)
2187 (eq markdown-cycle-subtree-status 'children))
2188 ;; We just showed the children, now show everything.
2189 (show-subtree)
2190 (message "SUBTREE")
2191 (setq markdown-cycle-subtree-status 'subtree))
2193 ;; Default action: hide the subtree.
2194 (hide-subtree)
2195 (message "FOLDED")
2196 (setq markdown-cycle-subtree-status 'folded)))))
2199 (indent-for-tab-command))))
2201 ;; Based on org-shifttab from org.el.
2202 (defun markdown-shifttab ()
2203 "Global visibility cycling.
2204 Calls `markdown-cycle' with argument t."
2205 (interactive)
2206 (markdown-cycle t))
2208 (defun markdown-outline-level ()
2209 "Return the depth to which a statement is nested in the outline."
2210 (cond
2211 ((match-end 1) 1)
2212 ((match-end 2) 2)
2213 ((- (match-end 0) (match-beginning 0)))))
2215 ;;; Commands ==================================================================
2217 (defun markdown (&optional output-buffer-name)
2218 "Run `markdown' on current buffer and insert output in buffer given by
2219 `output-buffer-name' (defaults to `markdown-output-buffer-name'). Return the
2220 OUTPUT-BUFFER used."
2221 (interactive)
2222 (save-window-excursion
2223 (let ((begin-region)
2224 (end-region))
2225 (if (markdown-transient-mark-mode-active)
2226 (setq begin-region (region-beginning)
2227 end-region (region-end))
2228 (setq begin-region (point-min)
2229 end-region (point-max)))
2231 (unless output-buffer-name
2232 (setq output-buffer-name markdown-output-buffer-name))
2234 (cond
2235 ;; Handle case when `markdown-command' does not read from stdin
2236 (markdown-command-needs-filename
2237 (if (not buffer-file-name)
2238 (error "Must be visiting a file")
2239 (shell-command (concat markdown-command " "
2240 (shell-quote-argument buffer-file-name))
2241 output-buffer-name)))
2242 ;; Pass region to `markdown-command' via stdin
2244 (shell-command-on-region begin-region end-region markdown-command
2245 output-buffer-name))))
2246 output-buffer-name))
2248 (defun markdown-standalone (&optional output-buffer-name)
2249 "special function to provide html standalone output"
2250 (interactive)
2251 (setq output-buffer-name (markdown output-buffer-name))
2252 (with-current-buffer output-buffer-name
2253 (set-buffer output-buffer-name)
2254 (goto-char (point-min))
2255 (unless (markdown-output-standalone-p)
2256 (markdown-add-xhtml-header-and-footer output-buffer-name))
2257 (html-mode))
2258 output-buffer-name)
2260 (defun markdown-other-window (&optional output-buffer-name)
2261 " Run `markdown' on current buffer and display in other window"
2262 (interactive)
2263 (display-buffer (markdown-standalone output-buffer-name)))
2265 (defun markdown-output-standalone-p ()
2266 "Determine whether `markdown-command' output is standalone XHTML.
2267 Standalone XHTML output is identified by an occurrence of
2268 `markdown-xhtml-standalone-regexp' in the first five lines of output."
2269 (re-search-forward
2270 markdown-xhtml-standalone-regexp
2271 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
2274 (defun markdown-add-xhtml-header-and-footer (title)
2275 "Wrap XHTML header and footer with given TITLE around current buffer."
2276 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
2277 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
2278 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
2279 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
2280 "<head>\n<title>")
2281 (insert title)
2282 (insert "</title>\n")
2283 (when (> (length markdown-content-type) 0)
2284 (insert
2285 (format
2286 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
2287 markdown-content-type
2288 (or (and markdown-coding-system
2289 (fboundp 'coding-system-get)
2290 (coding-system-get markdown-coding-system
2291 'mime-charset))
2292 (and (fboundp 'coding-system-get)
2293 (coding-system-get buffer-file-coding-system
2294 'mime-charset))
2295 "iso-8859-1"))))
2296 (if (> (length markdown-css-path) 0)
2297 (insert "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
2298 markdown-css-path
2299 "\" />\n"))
2300 (when (> (length markdown-xhtml-header-content) 0)
2301 (insert markdown-xhtml-header-content))
2302 (insert "\n</head>\n\n"
2303 "<body>\n\n")
2304 (goto-char (point-max))
2305 (insert "\n"
2306 "</body>\n"
2307 "</html>\n"))
2309 (defun markdown-preview (&optional output-buffer-name)
2310 "Run `markdown' on the current buffer and preview the output in a browser."
2311 (interactive)
2312 (browse-url-of-buffer (markdown markdown-output-buffer-name)))
2314 (defun markdown-export-file-name (&optional extension)
2315 "Attempt to generate a filename for Markdown output.
2316 If the current buffer is visiting a file, we construct a new
2317 output filename based on that filename. Otherwise, return nil."
2318 (when (buffer-file-name)
2319 (unless extension
2320 (setq extension ".html"))
2321 (concat
2322 (cond
2323 ((buffer-file-name)
2324 (file-name-sans-extension (buffer-file-name)))
2325 (t (buffer-name)))
2326 extension)))
2328 (defun markdown-export (&optional output-file)
2329 "Run Markdown on the current buffer, save to a file, and return the filename.
2330 The resulting filename will be constructed using the current filename, but
2331 with the extension removed and replaced with .html."
2332 (interactive)
2333 (unless output-file
2334 (setq output-file (markdown-export-file-name ".html")))
2335 (when output-file
2336 (let ((output-buffer-name))
2337 (setq output-buffer-name (buffer-name (find-file-noselect output-file)))
2338 (markdown-standalone output-buffer-name)
2339 (with-current-buffer output-buffer-name
2340 (save-buffer))
2341 output-file)))
2343 (defun markdown-export-and-preview ()
2344 "Export to XHTML using `markdown-export' and browse the resulting file."
2345 (interactive)
2346 (browse-url (markdown-export)))
2349 ;;; Links =====================================================================
2351 (require 'thingatpt)
2353 (defun markdown-link-p ()
2354 "Return non-nil when `point' is at a non-wiki link.
2355 See `markdown-wiki-link-p' for more information."
2356 (let ((case-fold-search nil))
2357 (and (not (markdown-wiki-link-p))
2358 (or (thing-at-point-looking-at markdown-regex-link-inline)
2359 (thing-at-point-looking-at markdown-regex-link-reference)))))
2361 (defun markdown-link-link ()
2362 "Return the link part of the regular (non-wiki) link at point.
2363 Works with both inline and reference style links. If point is
2364 not at a link or the link reference is not defined returns nil."
2365 (cond
2366 ((thing-at-point-looking-at markdown-regex-link-inline)
2367 (substring-no-properties (match-string 2) 1 -1))
2368 ((thing-at-point-looking-at markdown-regex-link-reference)
2369 (let* ((label (match-string-no-properties 1))
2370 (reference (match-string-no-properties 2))
2371 (target (downcase (if (string= reference "[]") label reference))))
2372 (markdown-has-reference-definition target)))
2373 (t (error "Not on a markdown link"))))
2375 (defun markdown-follow-link-at-point ()
2376 "Open the current non-wiki link in a browser."
2377 (interactive)
2378 (if (markdown-link-p) (browse-url (markdown-link-link))))
2381 ;;; WikiLink Following/Markup =================================================
2383 (defun markdown-wiki-link-p ()
2384 "Return non-nil when `point' is at a true wiki link.
2385 A true wiki link name matches `markdown-regex-wiki-link' but does not
2386 match the current file name after conversion. This modifies the data
2387 returned by `match-data'. Note that the potential wiki link name must
2388 be available via `match-string'."
2389 (let ((case-fold-search nil))
2390 (and (thing-at-point-looking-at markdown-regex-wiki-link)
2391 (or (not buffer-file-name)
2392 (not (string-equal (buffer-file-name)
2393 (markdown-convert-wiki-link-to-filename
2394 (markdown-wiki-link-link)))))
2395 (not (save-match-data
2396 (save-excursion))))))
2398 (defun markdown-wiki-link-link ()
2399 "Return the link part of the wiki link using current match data.
2400 The location of the link component depends on the value of
2401 `markdown-wiki-link-alias-first'."
2402 (if markdown-wiki-link-alias-first
2403 (or (match-string 3) (match-string 1))
2404 (match-string 1)))
2406 (defun markdown-convert-wiki-link-to-filename (name)
2407 "Generate a filename from the wiki link NAME.
2408 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
2409 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
2410 and [[test test]] both map to Test-test.ext."
2411 (let ((basename (markdown-replace-regexp-in-string
2412 "[[:space:]\n]" markdown-link-space-sub-char name)))
2413 (when (eq major-mode 'gfm-mode)
2414 (setq basename (concat (upcase (substring basename 0 1))
2415 (downcase (substring basename 1 nil)))))
2416 (concat basename
2417 (if (buffer-file-name)
2418 (concat "."
2419 (file-name-extension (buffer-file-name)))))))
2421 (defun markdown-follow-wiki-link (name &optional other)
2422 "Follow the wiki link NAME.
2423 Convert the name to a file name and call `find-file'. Ensure that
2424 the new buffer remains in `markdown-mode'."
2425 (let ((filename (markdown-convert-wiki-link-to-filename name))
2426 (wp (file-name-directory buffer-file-name)))
2427 (when other (other-window 1))
2428 (find-file (concat wp filename)))
2429 (when (not (eq major-mode 'markdown-mode))
2430 (markdown-mode)))
2432 (defun markdown-follow-wiki-link-at-point (&optional arg)
2433 "Find Wiki Link at point.
2434 With prefix argument C-u open the file in other window.
2436 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
2437 (interactive "P")
2438 (if (markdown-wiki-link-p)
2439 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
2440 (error "Point is not at a Wiki Link")))
2442 (defun markdown-next-wiki-link ()
2443 "Jump to next wiki link.
2444 See `markdown-wiki-link-p'."
2445 (interactive)
2446 (if (markdown-wiki-link-p)
2447 ;; At a wiki link already, move past it.
2448 (goto-char (+ 1 (match-end 0))))
2449 (save-match-data
2450 ;; Search for the next wiki link and move to the beginning.
2451 (re-search-forward markdown-regex-wiki-link nil t)
2452 (goto-char (match-beginning 0))))
2454 (defun markdown-previous-wiki-link ()
2455 "Jump to previous wiki link.
2456 See `markdown-wiki-link-p'."
2457 (interactive)
2458 (re-search-backward markdown-regex-wiki-link nil t))
2460 (defun markdown-highlight-wiki-link (from to face)
2461 "Highlight the wiki link in the region between FROM and TO using FACE."
2462 (put-text-property from to 'font-lock-face face))
2464 (defun markdown-unfontify-region-wiki-links (from to)
2465 "Remove wiki link faces from the region specified by FROM and TO."
2466 (interactive "nfrom: \nnto: ")
2467 (remove-text-properties from to '(font-lock-face markdown-link-face))
2468 (remove-text-properties from to '(font-lock-face markdown-missing-link-face)))
2470 (defun markdown-fontify-region-wiki-links (from to)
2471 "Search region given by FROM and TO for wiki links and fontify them.
2472 If a wiki link is found check to see if the backing file exists
2473 and highlight accordingly."
2474 (goto-char from)
2475 (while (re-search-forward markdown-regex-wiki-link to t)
2476 (let ((highlight-beginning (match-beginning 0))
2477 (highlight-end (match-end 0))
2478 (file-name
2479 (markdown-convert-wiki-link-to-filename
2480 (markdown-wiki-link-link))))
2481 (if (file-exists-p file-name)
2482 (markdown-highlight-wiki-link
2483 highlight-beginning highlight-end markdown-link-face)
2484 (markdown-highlight-wiki-link
2485 highlight-beginning highlight-end markdown-missing-link-face)))))
2487 (defun markdown-extend-changed-region (from to)
2488 "Extend region given by FROM and TO so that we can fontify all links.
2489 The region is extended to the first newline before and the first
2490 newline after."
2491 ;; start looking for the first new line before 'from
2492 (goto-char from)
2493 (re-search-backward "\n" nil t)
2494 (let ((new-from (point-min))
2495 (new-to (point-max)))
2496 (if (not (= (point) from))
2497 (setq new-from (point)))
2498 ;; do the same thing for the first new line after 'to
2499 (goto-char to)
2500 (re-search-forward "\n" nil t)
2501 (if (not (= (point) to))
2502 (setq new-to (point)))
2503 (values new-from new-to)))
2505 (defun markdown-check-change-for-wiki-link (from to change)
2506 "Check region between FROM and TO for wiki links and re-fontfy as needed.
2507 Designed to be used with the `after-change-functions' hook.
2508 CHANGE is the number of bytes of pre-change text replaced by the
2509 given range."
2510 (interactive "nfrom: \nnto: \nnchange: ")
2511 (let* ((inhibit-quit t)
2512 (modified (buffer-modified-p))
2513 (buffer-undo-list t)
2514 (inhibit-read-only t)
2515 (inhibit-point-motion-hooks t)
2516 (inhibit-modification-hooks t)
2517 (current-point (point))
2518 deactivate-mark)
2519 (unwind-protect
2520 (save-match-data
2521 (save-restriction
2522 ;; Extend the region to fontify so that it starts
2523 ;; and ends at safe places.
2524 (multiple-value-bind (new-from new-to)
2525 (markdown-extend-changed-region from to)
2526 ;; Unfontify existing fontification (start from scratch)
2527 (markdown-unfontify-region-wiki-links new-from new-to)
2528 ;; Now do the fontification.
2529 (markdown-fontify-region-wiki-links new-from new-to)))
2530 (unless modified
2531 (if (fboundp 'restore-buffer-modified-p)
2532 (restore-buffer-modified-p nil)
2533 (set-buffer-modified-p nil))))
2534 (goto-char current-point))))
2536 (defun markdown-fontify-buffer-wiki-links ()
2537 "Refontify all wiki links in the buffer."
2538 (interactive)
2539 (markdown-check-change-for-wiki-link (point-min) (point-max) 0))
2541 ;;; Miscellaneous =============================================================
2543 (defun markdown-line-number-at-pos (&optional pos)
2544 "Return (narrowed) buffer line number at position POS.
2545 If POS is nil, use current buffer location.
2546 This is an exact copy of `line-number-at-pos' for use in emacs21."
2547 (let ((opoint (or pos (point))) start)
2548 (save-excursion
2549 (goto-char (point-min))
2550 (setq start (point))
2551 (goto-char opoint)
2552 (forward-line 0)
2553 (1+ (count-lines start (point))))))
2555 (defun markdown-nobreak-p ()
2556 "Return nil if it is acceptable to break the current line at the point."
2557 ;; inside in square brackets (e.g., link anchor text)
2558 (looking-back "\\[[^]]*"))
2562 ;;; Mode definition ==========================================================
2564 (defun markdown-show-version ()
2565 "Show the version number in the minibuffer."
2566 (interactive)
2567 (message "markdown-mode, version %s" markdown-mode-version))
2569 ;;;###autoload
2570 (define-derived-mode markdown-mode text-mode "Markdown"
2571 "Major mode for editing Markdown files."
2572 ;; Natural Markdown tab width
2573 (setq tab-width 4)
2574 ;; Comments
2575 (make-local-variable 'comment-start)
2576 (setq comment-start "<!-- ")
2577 (make-local-variable 'comment-end)
2578 (setq comment-end " -->")
2579 (make-local-variable 'comment-start-skip)
2580 (setq comment-start-skip "<!--[ \t]*")
2581 (make-local-variable 'comment-column)
2582 (setq comment-column 0)
2583 ;; Font lock.
2584 (set (make-local-variable 'font-lock-defaults)
2585 '(markdown-mode-font-lock-keywords))
2586 (set (make-local-variable 'font-lock-multiline) t)
2587 ;; For imenu support
2588 (setq imenu-create-index-function 'markdown-imenu-create-index)
2589 ;; For menu support in XEmacs
2590 (easy-menu-add markdown-mode-menu markdown-mode-map)
2591 ;; Make filling work with lists (unordered, ordered, and definition)
2592 (set (make-local-variable 'paragraph-start)
2593 "\f\\|[ \t]*$\\|^[ \t]*[*+-] \\|^[ \t]*[0-9]+\\.\\|^[ \t]*: ")
2594 ;; Outline mode
2595 (make-local-variable 'outline-regexp)
2596 (setq outline-regexp markdown-regex-header)
2597 (make-local-variable 'outline-level)
2598 (setq outline-level 'markdown-outline-level)
2599 ;; Cause use of ellipses for invisible text.
2600 (add-to-invisibility-spec '(outline . t))
2601 ;; Indentation and filling
2602 (make-local-variable 'fill-nobreak-predicate)
2603 (add-hook 'fill-nobreak-predicate 'markdown-nobreak-p)
2604 (setq indent-line-function markdown-indent-function)
2606 ;; Prepare hooks for XEmacs compatibility
2607 (when (featurep 'xemacs)
2608 (make-local-hook 'after-change-functions)
2609 (make-local-hook 'font-lock-extend-region-functions)
2610 (make-local-hook 'window-configuration-change-hook))
2612 ;; Multiline font lock
2613 (add-hook 'font-lock-extend-region-functions
2614 'markdown-font-lock-extend-region)
2616 ;; Anytime text changes make sure it gets fontified correctly
2617 (add-hook 'after-change-functions 'markdown-check-change-for-wiki-link t t)
2619 ;; If we left the buffer there is a really good chance we were
2620 ;; creating one of the wiki link documents. Make sure we get
2621 ;; refontified when we come back.
2622 (add-hook 'window-configuration-change-hook
2623 'markdown-fontify-buffer-wiki-links t t)
2625 ;; do the initial link fontification
2626 (markdown-fontify-buffer-wiki-links))
2628 ;;(add-to-list 'auto-mode-alist '("\\.text$" . markdown-mode))
2630 ;;; GitHub Flavored Markdown Mode ============================================
2632 ;;;###autoload
2633 (define-derived-mode gfm-mode markdown-mode "GFM"
2634 "Major mode for editing GitHub Flavored Markdown files."
2635 (setq markdown-link-space-sub-char "-")
2636 (auto-fill-mode 0)
2637 ;; Use visual-line-mode if available, fall back to longlines-mode:
2638 (if (fboundp 'visual-line-mode)
2639 (visual-line-mode 1)
2640 (longlines-mode 1))
2641 ;; do the initial link fontification
2642 (markdown-fontify-buffer-wiki-links))
2645 (provide 'markdown-mode)
2647 ;;; markdown-mode.el ends here