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
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)
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.
51 ;; markdown-mode is a major mode for editing [Markdown][]-formatted
52 ;; text files in GNU Emacs. markdown-mode is free software, licensed
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][]
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][]
73 ;; * MacPorts: [markdown-mode.el][macports-package] ([pending][macports-ticket])
75 ;; [emacs-goodies-el]: http://packages.debian.org/emacs-goodies-el
76 ;; [emacs-goodies]: https://admin.fedoraproject.org/pkgdb/acls/name/emacs-goodies
77 ;; [textproc/markdown-mode]: http://pkgsrc.se/textproc/markdown-mode
78 ;; [emacs-markdown-mode-git]: http://aur.archlinux.org/packages.php?ID=30389
79 ;; [macports-package]: https://trac.macports.org/browser/trunk/dports/editors/markdown-mode.el/Portfile
80 ;; [macports-ticket]: http://trac.macports.org/ticket/35716
82 ;; The latest development version can be downloaded directly
83 ;; ([markdown-mode.el][devel.el]) or it can be obtained from the
84 ;; (browsable and clonable) Git repository at
85 ;; <http://jblevins.org/git/markdown-mode.git>. The entire repository,
86 ;; including the full project history, can be cloned via the Git protocol
89 ;; git clone git://jblevins.org/git/markdown-mode.git
91 ;; [devel.el]: http://jblevins.org/git/markdown-mode.git/plain/markdown-mode.el
95 ;; markdown-mode requires easymenu, a standard package since GNU Emacs
96 ;; 19 and XEmacs 19, which provides a uniform interface for creating
97 ;; menus in GNU Emacs and XEmacs.
101 ;; Make sure to place `markdown-mode.el` somewhere in the load-path and add
102 ;; the following lines to your `.emacs` file to associate markdown-mode
103 ;; with `.text` files:
105 ;; (autoload 'markdown-mode "markdown-mode"
106 ;; "Major mode for editing Markdown files" t)
107 ;; (add-to-list 'auto-mode-alist '("\\.text\\'" . markdown-mode))
109 ;; There is no consensus on an official file extension so change `.text` to
110 ;; `.mdwn`, `.md`, `.mdt`, or whatever you call your markdown files.
114 ;; Although no configuration is *necessary* there are a few things
115 ;; that can be customized. The `M-x customize-mode` command
116 ;; provides an interface to all of the possible customizations:
118 ;; * `markdown-command' - the command used to run Markdown (default:
119 ;; `markdown'). This variable may be customized to pass
120 ;; command-line options to your Markdown processor of choice, but
121 ;; this command must accept input from `stdin`. If it does not, a
122 ;; simple wrapper script can be used to write `stdin` to a file
123 ;; and then pass that file to your Markdown interpreter. Ideally,
124 ;; this command will produce an XHTML fragment around which
125 ;; markdown-mode will wrap a header and footer (which can be
126 ;; further customized). However, it attempts to detect whether
127 ;; the command produces standalone XHTML output (via
128 ;; `markdown-xhtml-standalone-regexp'), in which case no header
129 ;; and footer content will be added.
131 ;; * `markdown-command-needs-filename' - set to non-nil if
132 ;; `markdown-command' does not accept input from stdin (default: nil).
133 ;; Instead, it will be passed a filename as the final command-line
134 ;; option. As a result, you will only be able to run Markdown
135 ;; from buffers which are visiting a file.
137 ;; * `markdown-open-command' - the command used for calling a standalone
138 ;; Markdown previewer which is capable of opening Markdown source files
139 ;; directly (default: `nil'). This command will be called
140 ;; with a single argument, the filename of the current buffer.
141 ;; A representative program is the Mac app [Marked][], a
142 ;; live-updating MultiMarkdown previewer which has a command line
143 ;; utility at `/usr/local/bin/mark`.
145 ;; * `markdown-hr-string' - string to use when inserting horizontal
146 ;; rules (default: `* * * * *').
148 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
149 ;; underscores for bold instead of two asterisks (default: `nil').
151 ;; * `markdown-italic-underscore' - set to a non-nil value to use
152 ;; underscores for italic instead of asterisks (default: `nil').
154 ;; * `markdown-indent-function' - the function to use for automatic
155 ;; indentation (default: `markdown-indent-line').
157 ;; * `markdown-indent-on-enter' - set to a non-nil value to
158 ;; automatically indent new lines when the enter key is pressed
161 ;; * `markdown-follow-wiki-link-on-enter' - set to a non-nil value
162 ;; to automatically open a linked document in a new buffer if the
163 ;; cursor is an wiki link
166 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
167 ;; treat aliased wiki links like `[[link text|PageName]]`.
168 ;; When set to nil, they will be treated as `[[PageName|link text]]'.
170 ;; * `markdown-uri-types' - a list of protocols for URIs that
171 ;; `markdown-mode' should highlight.
173 ;; * `markdown-enable-math' - syntax highlighting for
174 ;; LaTeX fragments (default: `nil').
176 ;; * `markdown-css-path' - CSS file to link to in XHTML output.
178 ;; * `markdown-content-type' - when set to a nonempty string, an
179 ;; `http-equiv` attribute will be included in the XHTML `<head>`
180 ;; block. If needed, the suggested values are
181 ;; `application/xhtml+xml` or `text/html`.
183 ;; * `markdown-coding-system' - used for specifying the character
184 ;; set identifier in the `http-equiv` attribute (see
185 ;; `markdown-content-type'). When set to `nil',
186 ;; `buffer-file-coding-system' will be used (and falling back to
187 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
188 ;; and `iso-latin-1'.
190 ;; * `markdown-xhtml-header-content' - additional content to include
191 ;; in the XHTML `<head>` block.
193 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
194 ;; indicates whether the output of `markdown-command' is standalone
195 ;; XHTML (default: `^\\(\<\?xml\\|\<!DOCTYPE\\|\<html\\)`). If
196 ;; this is not matched, we assume this output is a fragment and add
197 ;; our own header and footer.
199 ;; * `markdown-link-space-sub-char' - a character to replace spaces
200 ;; when mapping wiki links to filenames (default: `_`).
201 ;; For example, use an underscore for compatibility with the
202 ;; Python Markdown WikiLinks extension or a hyphen for compatibility
203 ;; with Github wiki links.
205 ;; Additionally, the faces used for syntax highlighting can be modified to
206 ;; your liking by issuing `M-x customize-group RET markdown-faces`
207 ;; or by using the "Markdown Faces" link at the bottom of the mode
208 ;; customization screen.
210 ;; [Marked]: https://itunes.apple.com/us/app/marked/id448925439?ls=1&mt=12&partnerId=30&siteID=GpHp3Acs1Yo
214 ;; Keybindings are grouped by prefixes based on their function. For
215 ;; example, commands dealing with headers begin with `C-c C-t`. The
216 ;; primary commands in each group will are described below. You can
217 ;; obtain a list of all keybindings by pressing `C-c C-h`.
219 ;; * Anchors: `C-c C-a`
221 ;; `C-c C-a l` inserts inline links of the form `[text](url)`.
222 ;; `C-c C-a r` inserts reference links of the form `[text][label]`.
223 ;; The label definition will be placed at the end of the current
224 ;; block. `C-c C-a w` acts similarly for wiki links of the form
225 ;; `[[WikiLink]]`. In all cases, if there is an active region, the
226 ;; text in the region is used as the link text.
228 ;; * Commands: `C-c C-c`
230 ;; *Compile:* `C-c C-c m` will run Markdown on the current buffer
231 ;; and show the output in another buffer. *Preview*: `C-c C-c p`
232 ;; runs Markdown on the current buffer and previews, stores the
233 ;; output in a temporary file, and displays the file in a browser.
234 ;; *Export:* `C-c C-c e` will run Markdown on the current buffer
235 ;; and save the result in the file `basename.html`, where
236 ;; `basename` is the name of the Markdown file with the extension
237 ;; removed. *Export and View:* press `C-c C-c v` to export the
238 ;; file and view it in a browser. **For both export commands, the
239 ;; output file will be overwritten without notice.**
240 ;; *Open:* `C-c C-c o` will open the Markdown source file directly
241 ;; using `markdown-open-command'.
245 ;; - `C-c C-c m`: `markdown-command' > `*markdown-output*` buffer.
246 ;; - `C-c C-c p`: `markdown-command' > temporary file > browser.
247 ;; - `C-c C-c e`: `markdown-command' > `basename.html`.
248 ;; - `C-c C-c v`: `markdown-command' > `basename.html` > browser.
249 ;; - `C-c C-c o`: `markdown-open-command'.
251 ;; `C-c C-c c` will check for undefined references. If there are
252 ;; any, a small buffer will open with a list of undefined
253 ;; references and the line numbers on which they appear. In Emacs
254 ;; 22 and greater, selecting a reference from this list and
255 ;; pressing `RET` will insert an empty reference definition at the
256 ;; end of the buffer. Similarly, selecting the line number will
257 ;; jump to the corresponding line.
259 ;; `C-c C-c n` will clean up the numbering of ordered lists.
261 ;; * Images: `C-c C-i`
263 ;; `C-c C-i i` inserts an image, using the active region (if any)
266 ;; * Physical styles: `C-c C-p`
268 ;; These commands all act on text in the active region, if any,
269 ;; and insert empty markup fragments otherwise. `C-c C-p b` makes
270 ;; the selected text bold, `C-c C-p f` formats the region as
271 ;; fixed-width text, and `C-c C-p i` is used for italic text.
273 ;; * Logical styles: `C-c C-s`
275 ;; These commands all act on text in the active region, if any,
276 ;; and insert empty markup fragments otherwise. Logical styles
277 ;; include blockquote (`C-c C-s b`), preformatted (`C-c C-s p`),
278 ;; code (`C-c C-s c`), emphasis (`C-c C-s e`), and strong
281 ;; * Headers: `C-c C-t`
283 ;; All header commands use text in the active region, if any, as
284 ;; the header text. To insert an atx or hash style level-n
285 ;; header, press `C-c C-t n` where n is between 1 and 6. For a
286 ;; top-level setext or underline style header press `C-c C-t t`
287 ;; (mnemonic: title) and for a second-level underline-style header
288 ;; press `C-c C-t s` (mnemonic: section).
290 ;; * Footnotes: `C-c C-f`
292 ;; To create a new footnote at the point, press `C-c C-f n`.
293 ;; Press `C-c C-f g` with the point at a footnote to jump to the
294 ;; location where the footnote text is defined. Then, press
295 ;; `C-c C-f b` to return to the footnote marker in the main text.
296 ;; When the point is at a footnote marker or in the body of a
297 ;; footnote, press `C-c C-f k` to kill the footnote and add the
298 ;; text to the kill ring.
302 ;; `C-c -` inserts a horizontal rule.
306 ;; Press `C-c C-o` when the point is on an inline or reference
307 ;; link to open the URL in a browser.
309 ;; * Wiki-Link Navigation:
311 ;; Use `M-p` and `M-n` to quickly jump to the previous and next
312 ;; wiki links, respectively.
314 ;; * Outline Navigation:
316 ;; Navigation between headings is possible using `outline-mode'.
317 ;; Use `C-M-n` and `C-M-p` to move between the next and previous
318 ;; visible headings. Similarly, `C-M-f` and `C-M-b` move to the
319 ;; next and previous visible headings at the same level as the one
320 ;; at the point. Finally, `C-M-u` will move up to a lower-level
321 ;; (more inclusive) visible heading.
323 ;; Many of the commands described above behave differently depending on
324 ;; whether Transient Mark mode is enabled or not. When it makes sense,
325 ;; if Transient Mark mode is on and a region is active, the command
326 ;; applies to the text in the region (e.g., `C-c C-p b` makes the region
327 ;; bold). For users who prefer to work outside of Transient Mark mode,
328 ;; in Emacs 22 it can be enabled temporarily by pressing `C-SPC C-SPC`.
330 ;; When applicable, commands that specifically act on the region even
331 ;; outside of Transient Mark mode have the same keybinding as the with
332 ;; the exception of an additional `C-` prefix. For example,
333 ;; `markdown-insert-blockquote' is bound to `C-c C-s b` and only acts on
334 ;; the region in Transient Mark mode while `markdown-blockquote-region'
335 ;; is bound to `C-c C-s C-b` and always applies to the region (when
338 ;; markdown-mode attempts to be flexible in how it handles
339 ;; indentation. When you press `TAB` repeatedly, the point will cycle
340 ;; through several possible indentation levels corresponding to things
341 ;; you might have in mind when you press `RET` at the end of a line or
342 ;; `TAB`. For example, you may want to start a new list item,
343 ;; continue a list item with hanging indentation, indent for a nested
344 ;; pre block, and so on.
346 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
347 ;; visibility cycling for atx- or hash-style headers. There are two
348 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
349 ;; the table of contents view (headers only), outline view (top-level
350 ;; headers only), and the full document view. Pressing `TAB` while the
351 ;; point is at a header will cycle through levels of visibility for the
352 ;; subtree: completely folded, visible children, and fully visible.
353 ;; Note that mixing hash and underline style headers will give undesired
358 ;; Besides supporting the basic Markdown syntax, markdown-mode also
359 ;; includes syntax highlighting for `[[Wiki Links]]` by default. Wiki
360 ;; links may be followed automatically by hitting the enter key when
361 ;; your curser is on a wiki link or by hitting `C-c C-w`. The
362 ;; autofollowing on enter key may be controlled with the
363 ;; `markdown-follow-wiki-link-on-enter' customization. Use `M-p` and
364 ;; `M-n` to quickly jump to the previous and next wiki links,
365 ;; respectively. Aliased or piped wiki links of the form
366 ;; `[[link text|PageName]]` are also supported. Since some wikis
367 ;; reverse these components, set `markdown-wiki-link-alias-first'
368 ;; to nil to treat them as `[[PageName|link text]]`.
370 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
371 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
372 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
373 ;; You can do this either by using `M-x customize-group markdown`
374 ;; or by placing the following in your `.emacs` file:
376 ;; (defun markdown-custom ()
377 ;; "markdown-mode-hook"
378 ;; (setq markdown-command "markdown | smartypants"))
379 ;; (add-hook 'markdown-mode-hook '(lambda() (markdown-custom)))
381 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
383 ;; Experimental syntax highlighting for mathematical expressions written
384 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
385 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
386 ;; either via customize or by placing `(setq markdown-enable-itex t)`
387 ;; in `.emacs`, and restarting Emacs.
389 ;; A [GitHub Flavored Markdown](http://github.github.com/github-flavored-markdown/)
390 ;; mode, `gfm-mode', is also available. The GitHub implementation of
391 ;; differs slightly from standard Markdown. Most importantly, newlines are
392 ;; significant and trigger hard line breaks. As such, `gfm-mode' turns off
393 ;; `auto-fill-mode' and turns on `visual-line-mode' (or `longlines-mode' if
394 ;; `visual-line-mode' is not available). Wiki links in this mode will be
395 ;; treated as on GitHub, with hyphens replacing spaces in filenames and
396 ;; where the first letter of the filename capitalized. For example,
397 ;; `[[wiki link]]' will map to a file named `Wiki-link` with the same
398 ;; extension as the current file.
402 ;; markdown-mode has benefited greatly from the efforts of the
405 ;; * Cyril Brulebois <cyril.brulebois@enst-bretagne.fr> for Debian packaging.
406 ;; * Conal Elliott <conal@conal.net> for a font-lock regexp patch.
407 ;; * Edward O'Connor <hober0@gmail.com> for a font-lock regexp fix and
408 ;; GitHub Flavored Markdown mode (`gfm-mode').
409 ;; * Greg Bognar <greg_bognar@hms.harvard.edu> for menus and running
410 ;; `markdown' with an active region.
411 ;; * Daniel Burrows <dburrows@debian.org> for filing Debian bug #456592.
412 ;; * Peter S. Galbraith <psg@debian.org> for maintaining emacs-goodies-el.
413 ;; * Dmitry Dzhus <mail@sphinx.net.ru> for reference checking functions.
414 ;; * Bryan Kyle <bryan.kyle@gmail.com> for indentation code.
415 ;; * Ben Voui <intrigeri@boum.org> for font-lock face customizations.
416 ;; * Ankit Solanki <ankit.solanki@gmail.com> for longlines.el
417 ;; compatibility and custom CSS.
418 ;; * Hilko Bengen <bengen@debian.org> for proper XHTML output.
419 ;; * Jose A. Ortega Ruiz <jao@gnu.org> for Emacs 23 fixes.
420 ;; * Alec Resnick <alec@sproutward.org> for bug reports.
421 ;; * Joost Kremers <joostkremers@fastmail.fm> for footnote-handling
422 ;; functions and bug reports regarding indentation.
423 ;; * Peter Williams <pezra@barelyenough.org> for fill-paragraph
425 ;; * George Ogata <george.ogata@gmail.com> for fixing several
426 ;; byte-compilation warnings.
427 ;; * Eric Merritt <ericbmerritt@gmail.com> for wiki link features.
428 ;; * Philippe Ivaldi <pivaldi@sfr.fr> for XHTML preview
429 ;; customizations and XHTML export.
430 ;; * Jeremiah Dodds <jeremiah.dodds@gmail.com> for supporting
431 ;; Markdown processors which do not accept input from stdin.
432 ;; * Werner Dittmann <werner.dittmann@t-online.de> for bug reports
433 ;; regarding the cl dependency and auto-fill-mode and indentation.
434 ;; * Scott Pfister <scott.pfister@gmail.com> for generalizing the space
435 ;; substitution character for mapping wiki links to filenames.
436 ;; * Marcin Kasperski <marcin.kasperski@mekk.waw.pl> for a patch to
437 ;; escape shell commands.
438 ;; * Christopher J. Madsen <cjm@cjmweb.net> for patches to fix a match
439 ;; data bug and to prefer `visual-line-mode' in `gfm-mode'.
440 ;; * Shigeru Fukaya <shigeru.fukaya@gmail.com> for better adherence to
441 ;; Emacs Lisp coding conventions.
442 ;; * Donald Ephraim Curtis <dcurtis@milkbox.net> for fixing the `paragraph-fill'
443 ;; regexp, refactoring the compilation and preview functions,
444 ;; heading font-lock generalizations, list renumbering,
445 ;; and kill ring save.
446 ;; * Kevin Porter <kportertx@gmail.com> for wiki link handling in `gfm-mode'.
447 ;; * Max Penet <max.penet@gmail.com> and Peter Eisentraut <peter_e@gmx.net>
448 ;; for an autoload token for `gfm-mode'.
449 ;; * Ian Yang <me@iany.me> for improving the reference definition regex.
450 ;; * Akinori Musha <knu@idaemons.org> for an imenu index function.
451 ;; * Michael Sperber <sperber@deinprogramm.de> for XEmacs fixes.
452 ;; * Francois Gannaz <francois.gannaz@free.fr> for suggestingcharset
453 ;; declaration in XHTML output.
454 ;; * Zhenlei Jia <zhenlei.jia@gmail.com> for smart (dedention)
455 ;; un-indentation function.
456 ;; * Matus Goljer <dota.keys@gmail.com> for improved wiki link following.
457 ;; * Peter Jones <pjones@pmade.com> for link following functions.
458 ;; * Bryan Fink <bryan.fink@gmail.com> for a bug report regarding
459 ;; externally modified files.
460 ;; * Vegard Vesterheim <vegard.vesterheim@uninett.no> and Carsten Dominik
461 ;; for a bug fix related to orgtbl-mode.
465 ;; Although markdown-mode is developed and tested primarily using
466 ;; GNU Emacs 24, compatibility with earlier Emacsen is also a
469 ;; If you find any bugs in markdown-mode, please construct a test case
470 ;; or a patch and email me at <jrblevin@sdf.org>.
474 ;; markdown-mode was written and is maintained by Jason Blevins. The
475 ;; first version was released on May 24, 2007.
477 ;; * 2007-05-24: Version 1.1
478 ;; * 2007-05-25: Version 1.2
479 ;; * 2007-06-05: [Version 1.3][]
480 ;; * 2007-06-29: Version 1.4
481 ;; * 2008-05-24: [Version 1.5][]
482 ;; * 2008-06-04: [Version 1.6][]
483 ;; * 2009-10-01: [Version 1.7][]
484 ;; * 2011-08-12: [Version 1.8][]
485 ;; * 2011-08-15: [Version 1.8.1][]
487 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
488 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
489 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
490 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
491 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
492 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
499 (eval-when-compile (require 'cl
))
501 ;;; Constants =================================================================
503 (defconst markdown-mode-version
"1.8.1"
504 "Markdown mode version number.")
506 (defconst markdown-output-buffer-name
"*markdown-output*"
507 "Name of temporary buffer for markdown command output.")
509 ;;; Customizable variables ====================================================
511 (defvar markdown-mode-hook nil
512 "Hook run when entering Markdown mode.")
514 (defgroup markdown nil
515 "Major mode for editing text files in Markdown format."
518 :link
'(url-link "http://jblevins.org/projects/markdown-mode/"))
520 (defcustom markdown-command
"markdown"
521 "Command to run markdown."
525 (defcustom markdown-command-needs-filename nil
526 "Set to non-nil if `markdown-command' does not accept input from stdin.
527 Instead, it will be passed a filename as the final command-line
528 option. As a result, you will only be able to run Markdown from
529 buffers which are visiting a file."
533 (defcustom markdown-open-command nil
534 "Command used for opening Markdown files directly.
535 For example, a standalone Markdown previewer. This command will
536 be called with a single argument: the filename of the current
541 (defcustom markdown-hr-string
"* * * * *"
542 "String to use for horizonal rules."
546 (defcustom markdown-bold-underscore nil
547 "Use two underscores for bold instead of two asterisks."
551 (defcustom markdown-italic-underscore nil
552 "Use underscores for italic instead of asterisks."
556 (defcustom markdown-indent-function
'markdown-indent-line
557 "Function to use to indent."
561 (defcustom markdown-indent-on-enter t
562 "Automatically indent new lines when enter key is pressed."
566 (defcustom markdown-follow-wiki-link-on-enter t
567 "Follow wiki link at point (if any) when the enter key is pressed."
571 (defcustom markdown-wiki-link-alias-first t
572 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
573 Otherwise, they will be treated as [[PageName|alias text]]."
577 (defcustom markdown-uri-types
578 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
579 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
580 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
581 "Link types for syntax highlighting of URIs."
585 (defcustom markdown-enable-math nil
586 "Syntax highlighting for inline LaTeX expressions.
587 This will not take effect until Emacs is restarted."
591 (defcustom markdown-css-path
""
592 "URL of CSS file to link to in the output XHTML."
596 (defcustom markdown-content-type
""
597 "Content type string for the http-equiv header in XHTML output.
598 When set to a non-empty string, insert the http-equiv attribute.
599 Otherwise, this attribute is omitted."
603 (defcustom markdown-coding-system nil
604 "Character set string for the http-equiv header in XHTML output.
605 Defaults to `buffer-file-coding-system' (and falling back to
606 `iso-8859-1' when not available). Common settings are `utf-8'
607 and `iso-latin-1'. Use `list-coding-systems' for more choices."
609 :type
'coding-system
)
611 (defcustom markdown-xhtml-header-content
""
612 "Additional content to include in the XHTML <head> block."
616 (defcustom markdown-xhtml-standalone-regexp
617 "^\\(\<\?xml\\|\<!DOCTYPE\\|\<html\\)"
618 "Regexp indicating whether `markdown-command' output is standalone XHTML."
622 (defcustom markdown-link-space-sub-char
624 "Character to use instead of spaces when mapping wiki links to filenames."
628 (defcustom markdown-footnote-location
'end
629 "Position where new footnotes are inserted in the document."
631 :type
'(choice (const :tag
"At the end of the document" end
)
632 (const :tag
"Immediately after the paragraph" immediately
)
633 (const :tag
"Before next header" header
)))
635 ;;; Font lock =================================================================
639 (defvar markdown-italic-face
'markdown-italic-face
640 "Face name to use for italic text.")
642 (defvar markdown-bold-face
'markdown-bold-face
643 "Face name to use for bold text.")
645 (defvar markdown-header-delimiter-face
'markdown-header-delimiter-face
646 "Face name to use as a base for header delimiters.")
648 (defvar markdown-header-rule-face
'markdown-header-rule-face
649 "Face name to use as a base for header rules.")
651 (defvar markdown-header-face
'markdown-header-face
652 "Face name to use as a base for headers.")
654 (defvar markdown-header-face-1
'markdown-header-face-1
655 "Face name to use for level-1 headers.")
657 (defvar markdown-header-face-2
'markdown-header-face-2
658 "Face name to use for level-2 headers.")
660 (defvar markdown-header-face-3
'markdown-header-face-3
661 "Face name to use for level-3 headers.")
663 (defvar markdown-header-face-4
'markdown-header-face-4
664 "Face name to use for level-4 headers.")
666 (defvar markdown-header-face-5
'markdown-header-face-5
667 "Face name to use for level-5 headers.")
669 (defvar markdown-header-face-6
'markdown-header-face-6
670 "Face name to use for level-6 headers.")
672 (defvar markdown-inline-code-face
'markdown-inline-code-face
673 "Face name to use for inline code.")
675 (defvar markdown-list-face
'markdown-list-face
676 "Face name to use for list markers.")
678 (defvar markdown-blockquote-face
'markdown-blockquote-face
679 "Face name to use for blockquote.")
681 (defvar markdown-pre-face
'markdown-pre-face
682 "Face name to use for preformatted text.")
684 (defvar markdown-link-face
'markdown-link-face
685 "Face name to use for links.")
687 (defvar markdown-missing-link-face
'markdown-missing-link-face
688 "Face name to use for links where the linked file does not exist.")
690 (defvar markdown-reference-face
'markdown-reference-face
691 "Face name to use for reference.")
693 (defvar markdown-footnote-face
'markdown-footnote-face
694 "Face name to use for footnote identifiers.")
696 (defvar markdown-url-face
'markdown-url-face
697 "Face name to use for URLs.")
699 (defvar markdown-link-title-face
'markdown-link-title-face
700 "Face name to use for reference link titles.")
702 (defvar markdown-comment-face
'markdown-comment-face
703 "Face name to use for HTML comments.")
705 (defvar markdown-math-face
'markdown-math-face
706 "Face name to use for LaTeX expressions.")
708 (defgroup markdown-faces nil
709 "Faces used in Markdown Mode"
713 (defface markdown-italic-face
714 '((t (:inherit font-lock-variable-name-face
:slant italic
)))
715 "Face for italic text."
716 :group
'markdown-faces
)
718 (defface markdown-bold-face
719 '((t (:inherit font-lock-variable-name-face
:weight bold
)))
720 "Face for bold text."
721 :group
'markdown-faces
)
723 (defface markdown-header-rule-face
724 '((t (:inherit font-lock-function-name-face
:weight bold
)))
725 "Base face for headers rules."
726 :group
'markdown-faces
)
728 (defface markdown-header-delimiter-face
729 '((t (:inherit font-lock-function-name-face
:weight bold
)))
730 "Base face for headers hash delimiter."
731 :group
'markdown-faces
)
733 (defface markdown-header-face
734 '((t (:inherit font-lock-function-name-face
:weight bold
)))
735 "Base face for headers."
736 :group
'markdown-faces
)
738 (defface markdown-header-face-1
739 '((t (:inherit markdown-header-face
)))
740 "Face for level-1 headers."
741 :group
'markdown-faces
)
743 (defface markdown-header-face-2
744 '((t (:inherit markdown-header-face
)))
745 "Face for level-2 headers."
746 :group
'markdown-faces
)
748 (defface markdown-header-face-3
749 '((t (:inherit markdown-header-face
)))
750 "Face for level-3 headers."
751 :group
'markdown-faces
)
753 (defface markdown-header-face-4
754 '((t (:inherit markdown-header-face
)))
755 "Face for level-4 headers."
756 :group
'markdown-faces
)
758 (defface markdown-header-face-5
759 '((t (:inherit markdown-header-face
)))
760 "Face for level-5 headers."
761 :group
'markdown-faces
)
763 (defface markdown-header-face-6
764 '((t (:inherit markdown-header-face
)))
765 "Face for level-6 headers."
766 :group
'markdown-faces
)
768 (defface markdown-inline-code-face
769 '((t (:inherit font-lock-constant-face
)))
770 "Face for inline code."
771 :group
'markdown-faces
)
773 (defface markdown-list-face
774 '((t (:inherit font-lock-builtin-face
)))
775 "Face for list item markers."
776 :group
'markdown-faces
)
778 (defface markdown-blockquote-face
779 '((t (:inherit font-lock-doc-face
)))
780 "Face for blockquote sections."
781 :group
'markdown-faces
)
783 (defface markdown-pre-face
784 '((t (:inherit font-lock-constant-face
)))
785 "Face for preformatted text."
786 :group
'markdown-faces
)
788 (defface markdown-link-face
789 '((t (:inherit font-lock-keyword-face
)))
791 :group
'markdown-faces
)
793 (defface markdown-missing-link-face
794 '((t (:inherit font-lock-warning-face
)))
795 "Face for missing links."
796 :group
'markdown-faces
)
798 (defface markdown-reference-face
799 '((t (:inherit font-lock-type-face
)))
800 "Face for link references."
801 :group
'markdown-faces
)
803 (defface markdown-footnote-face
804 '((t (:inherit font-lock-keyword-face
)))
805 "Face for footnote markers."
806 :group
'markdown-faces
)
808 (defface markdown-url-face
809 '((t (:inherit font-lock-string-face
)))
811 :group
'markdown-faces
)
813 (defface markdown-link-title-face
814 '((t (:inherit font-lock-comment-face
)))
815 "Face for reference link titles."
816 :group
'markdown-faces
)
818 (defface markdown-comment-face
819 '((t (:inherit font-lock-comment-face
)))
820 "Face for HTML comments."
821 :group
'markdown-faces
)
823 (defface markdown-math-face
824 '((t (:inherit font-lock-string-face
)))
825 "Face for LaTeX expressions."
826 :group
'markdown-faces
)
828 (defconst markdown-regex-link-inline
829 "\\(!?\\[[^]]*?\\]\\)\\(([^\\)]*)\\)"
830 "Regular expression for a [text](file) or an image link ![text](file).")
832 (defconst markdown-regex-link-reference
833 "\\(!?\\[[^]]+?\\]\\)[ ]?\\(\\[[^]]*?\\]\\)"
834 "Regular expression for a reference link [text][id].")
836 (defconst markdown-regex-reference-definition
837 "^ \\{0,3\\}\\(\\[[^^\n]+?\\]\\):\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
838 "Regular expression for a link definition [id]: ...")
840 (defconst markdown-regex-footnote
842 "Regular expression for a footnote marker [^fn].")
844 (defconst markdown-regex-header
845 "#+\\|\\S-.*\n\\(?:\\(===+\\)\\|\\(---+\\)\\)$"
846 "Regexp identifying Markdown headers.")
848 (defconst markdown-regex-header-1-atx
849 "^\\(# \\)\\(.*?\\)\\($\\| #+$\\)"
850 "Regular expression for level 1 atx-style (hash mark) headers.")
852 (defconst markdown-regex-header-2-atx
853 "^\\(## \\)\\(.*?\\)\\($\\| #+$\\)"
854 "Regular expression for level 2 atx-style (hash mark) headers.")
856 (defconst markdown-regex-header-3-atx
857 "^\\(### \\)\\(.*?\\)\\($\\| #+$\\)"
858 "Regular expression for level 3 atx-style (hash mark) headers.")
860 (defconst markdown-regex-header-4-atx
861 "^\\(#### \\)\\(.*?\\)\\($\\| #+$\\)"
862 "Regular expression for level 4 atx-style (hash mark) headers.")
864 (defconst markdown-regex-header-5-atx
865 "^\\(##### \\)\\(.*?\\)\\($\\| #+$\\)"
866 "Regular expression for level 5 atx-style (hash mark) headers.")
868 (defconst markdown-regex-header-6-atx
869 "^\\(###### \\)\\(.*?\\)\\($\\| #+$\\)"
870 "Regular expression for level 6 atx-style (hash mark) headers.")
872 (defconst markdown-regex-header-1-setext
873 "^\\(.*\\)\n\\(===+\\)$"
874 "Regular expression for level 1 setext-style (underline) headers.")
876 (defconst markdown-regex-header-2-setext
877 "^\\(.*\\)\n\\(---+\\)$"
878 "Regular expression for level 2 setext-style (underline) headers.")
880 (defconst markdown-regex-hr
881 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
882 "Regular expression for matching Markdown horizontal rules.")
884 (defconst markdown-regex-code
885 "\\(^\\|[^\\]\\)\\(\\(`\\{1,2\\}\\)\\([^ \\]\\|[^ ]\\(.\\|\n[^\n]\\)*?[^ \\]\\)\\3\\)"
886 "Regular expression for matching inline code fragments.")
888 (defconst markdown-regex-pre
890 "Regular expression for matching preformatted text sections.")
892 (defconst markdown-regex-list
893 "^[ \t]*\\([0-9]+\\.\\|[\\*\\+-]\\) "
894 "Regular expression for matching list markers.")
896 (defconst markdown-regex-bold
897 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\(.\\|\n[^\n]\\)*?[^\\ ]\\3\\)"
898 "Regular expression for matching bold text.")
900 (defconst markdown-regex-italic
901 "\\(^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \\]\\3\\|[^ ]\\(.\\|\n[^\n]\\)*?[^\\ ]\\3\\)\\)"
902 "Regular expression for matching italic text.")
904 (defconst markdown-regex-blockquote
906 "Regular expression for matching blockquote lines.")
908 (defconst markdown-regex-line-break
910 "Regular expression for matching line breaks.")
912 (defconst markdown-regex-wiki-link
913 "\\[\\[\\([^]|]+\\)\\(|\\([^]]+\\)\\)?\\]\\]"
914 "Regular expression for matching wiki links.
915 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
916 wiki links of the form [[PageName|link text]]. In this regular
917 expression, #1 matches the page name and #3 matches the link
920 (defconst markdown-regex-uri
922 "\\(" (mapconcat 'identity markdown-uri-types
"\\|")
923 "\\):[^]\t\n\r<>,;() ]+")
924 "Regular expression for matching inline URIs.")
926 (defconst markdown-regex-angle-uri
929 (mapconcat 'identity markdown-uri-types
"\\|")
930 "\\):[^]\t\n\r<>,;()]+\\(>\\)")
931 "Regular expression for matching inline URIs in angle brackets.")
933 (defconst markdown-regex-email
934 "<\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+>"
935 "Regular expression for matching inline email addresses.")
937 (defconst markdown-regex-latex-expression
938 "\\(^\\|[^\\]\\)\\(\\$\\($\\([^\\$]\\|\\\\.\\)*\\$\\|\\([^\\$]\\|\\\\.\\)*\\)\\$\\)"
939 "Regular expression for itex $..$ or $$..$$ math mode expressions.")
941 (defconst markdown-regex-latex-display
942 "^\\\\\\[\\(.\\|\n\\)*?\\\\\\]$"
943 "Regular expression for itex \[..\] display mode expressions.")
945 (defconst markdown-regex-list-indent
946 "^\\(\\s *\\)\\([0-9]+\\.\\|[\\*\\+-]\\)\\(\\s +\\)"
947 "Regular expression for matching indentation of list items.")
949 (defvar markdown-mode-font-lock-keywords-basic
951 '(markdown-match-pre-blocks 0 markdown-pre-face t t
)
952 '(markdown-match-fenced-code-blocks 0 markdown-pre-face t t
)
953 (cons markdown-regex-blockquote
'markdown-blockquote-face
)
954 (cons markdown-regex-header-1-setext
'((1 markdown-header-face-1
)
955 (2 markdown-header-rule-face
)))
956 (cons markdown-regex-header-2-setext
'((1 markdown-header-face-2
)
957 (2 markdown-header-rule-face
)))
958 (cons markdown-regex-header-1-atx
'((1 markdown-header-delimiter-face
)
959 (2 markdown-header-face-1
)
960 (3 markdown-header-delimiter-face
)))
961 (cons markdown-regex-header-2-atx
'((1 markdown-header-delimiter-face
)
962 (2 markdown-header-face-2
)
963 (3 markdown-header-delimiter-face
)))
964 (cons markdown-regex-header-3-atx
'((1 markdown-header-delimiter-face
)
965 (2 markdown-header-face-3
)
966 (3 markdown-header-delimiter-face
)))
967 (cons markdown-regex-header-4-atx
'((1 markdown-header-delimiter-face
)
968 (2 markdown-header-face-4
)
969 (3 markdown-header-delimiter-face
)))
970 (cons markdown-regex-header-5-atx
'((1 markdown-header-delimiter-face
)
971 (2 markdown-header-face-5
)
972 (3 markdown-header-delimiter-face
)))
973 (cons markdown-regex-header-6-atx
'((1 markdown-header-delimiter-face
)
974 (2 markdown-header-face-6
)
975 (3 markdown-header-delimiter-face
)))
976 (cons markdown-regex-hr
'markdown-header-face
)
977 '(markdown-match-comments 0 markdown-comment-face t t
)
978 (cons markdown-regex-code
'(2 markdown-inline-code-face
))
979 (cons markdown-regex-angle-uri
'markdown-link-face
)
980 (cons markdown-regex-uri
'markdown-link-face
)
981 (cons markdown-regex-email
'markdown-link-face
)
982 (cons markdown-regex-list
'markdown-list-face
)
983 (cons markdown-regex-link-inline
984 '((1 markdown-link-face t
)
985 (2 markdown-url-face t
)))
986 (cons markdown-regex-link-reference
987 '((1 markdown-link-face t
)
988 (2 markdown-reference-face t
)))
989 (cons markdown-regex-reference-definition
990 '((1 markdown-reference-face t
)
991 (2 markdown-url-face t
)
992 (3 markdown-link-title-face t
)))
993 (cons markdown-regex-footnote
'markdown-footnote-face
)
994 (cons markdown-regex-bold
'(2 markdown-bold-face
))
995 (cons markdown-regex-italic
'(2 markdown-italic-face
))
997 "Syntax highlighting for Markdown files.")
999 (defconst markdown-mode-font-lock-keywords-latex
1001 ;; Math mode $..$ or $$..$$
1002 (cons markdown-regex-latex-expression
'(2 markdown-math-face
))
1003 ;; Display mode equations with brackets: \[ \]
1004 (cons markdown-regex-latex-display
'markdown-math-face
)
1005 ;; Equation reference (eq:foo)
1006 (cons "(eq:\\w+)" 'markdown-reference-face
)
1007 ;; Equation reference \eqref{foo}
1008 (cons "\\\\eqref{\\w+}" 'markdown-reference-face
))
1009 "Syntax highlighting for LaTeX fragments.")
1011 (defvar markdown-mode-font-lock-keywords
1013 (if markdown-enable-math
1014 markdown-mode-font-lock-keywords-latex
)
1015 markdown-mode-font-lock-keywords-basic
)
1016 "Default highlighting expressions for Markdown mode.")
1019 (defvar markdown-footnote-counter
0
1020 "Counter for footnote numbers.")
1021 (make-variable-buffer-local 'markdown-footnote-counter
)
1023 (defconst markdown-footnote-chars
1025 "Regular expression maching any character that is allowed in a footnote identifier.")
1029 ;;; Compatibility =============================================================
1031 ;; Handle replace-regexp-in-string in XEmacs 21
1032 (defun markdown-replace-regexp-in-string (regexp rep string
)
1033 "Compatibility wrapper to provide `replace-regexp-in-string'."
1034 (if (featurep 'xemacs
)
1035 (replace-in-string string regexp rep
)
1036 (replace-regexp-in-string regexp rep string
)))
1039 (if (boundp 'mark-active
)
1040 (defun markdown-mark-active () ; Emacs
1042 (defalias 'markdown-mark-active
'region-exists-p
))) ; XEmacs
1044 (defun markdown-transient-mark-mode-active ()
1046 ((boundp 'transient-mark-mode
)
1047 (and transient-mark-mode
(markdown-mark-active)))
1048 ((boundp 'zmacs-regions
)
1049 (and zmacs-regions
(markdown-mark-active)))))
1053 ;;; Markdown parsing functions ================================================
1055 (defun markdown-cur-line-blank-p ()
1056 "Return t if the current line is blank and nil otherwise."
1059 (re-search-forward "^\\s *$" (point-at-eol) t
)))
1061 (defun markdown-prev-line-blank-p ()
1062 "Return t if the previous line is blank and nil otherwise.
1063 If we are at the first line, then consider the previous line to be blank."
1065 (if (= (point-at-bol) (point-min))
1068 (markdown-cur-line-blank-p))))
1070 (defun markdown-next-line-blank-p ()
1071 "Return t if the next line is blank and nil otherwise.
1072 If we are at the last line, then consider the next line to be blank."
1074 (if (= (point-at-bol) (point-max))
1077 (markdown-cur-line-blank-p))))
1079 (defun markdown-prev-line-indent-p ()
1080 "Return t if the previous line is indented and nil otherwise."
1083 (goto-char (point-at-bol))
1084 (if (re-search-forward "^\\s " (point-at-eol) t
) t
)))
1086 (defun markdown-cur-line-indent ()
1087 "Return the number of leading whitespace characters in the current line."
1089 (goto-char (point-at-bol))
1090 (re-search-forward "^\\s +" (point-at-eol) t
)
1093 (defun markdown-prev-line-indent ()
1094 "Return the number of leading whitespace characters in the previous line."
1097 (markdown-cur-line-indent)))
1099 (defun markdown-next-line-indent ()
1100 "Return the number of leading whitespace characters in the next line."
1103 (markdown-cur-line-indent)))
1105 (defun markdown-cur-non-list-indent ()
1106 "Return the number of leading whitespace characters in the current line."
1109 (when (re-search-forward markdown-regex-list-indent
(point-at-eol) t
)
1112 (defun markdown-prev-non-list-indent ()
1113 "Return position of the first non-list-marker on the previous line."
1116 (markdown-cur-non-list-indent)))
1118 (defun markdown--next-block ()
1119 "Move the point to the start of the next text block."
1121 (while (and (or (not (markdown-prev-line-blank-p))
1122 (markdown-cur-line-blank-p))
1126 (defun markdown--end-of-level (level)
1127 "Move the point to the end of region with indentation at least LEVEL."
1129 (while (and (not (< (setq indent
(markdown-cur-line-indent)) level
))
1130 (not (>= indent
(+ level
4)))
1132 (markdown--next-block))
1134 ;; Move back before any trailing blank lines
1135 (while (and (markdown-prev-line-blank-p)
1141 ;; From html-helper-mode
1142 (defun markdown-match-comments (last)
1143 "Match HTML comments from the point to LAST."
1144 (cond ((search-forward "<!--" last t
)
1146 (let ((beg (point)))
1147 (cond ((search-forward-regexp "--[ \t]*>" last t
)
1148 (set-match-data (list beg
(point)))
1153 (defun markdown-match-pre-blocks (last)
1154 "Match Markdown pre blocks from point to LAST.
1155 A region matches as if it is indented at least four spaces
1156 relative to the nearest previous block of lesser non-list-marker
1159 (let (cur-begin cur-end cur-indent prev-indent prev-list stop match found
)
1160 ;; Don't start in the middle of a block
1162 (markdown-prev-line-blank-p)
1163 (not (markdown-cur-line-blank-p)))
1164 (markdown--next-block))
1166 ;; Move to the first full block in the region with indent 4 or more
1167 (while (and (not (>= (setq cur-indent
(markdown-cur-line-indent)) 4))
1168 (not (>= (point) last
)))
1169 (markdown--next-block))
1170 (setq cur-begin
(point))
1171 (markdown--end-of-level cur-indent
)
1172 (setq cur-end
(point))
1174 (setq stop
(> cur-begin cur-end
))
1176 (while (and (<= cur-end last
) (not stop
) (not match
))
1177 ;; Move to the nearest preceding block of lesser (non-marker) indentation
1178 (setq prev-indent
(+ cur-indent
1))
1179 (goto-char cur-begin
)
1181 (while (and (>= prev-indent cur-indent
)
1183 (eq prev-indent cur-indent
)))
1186 ;; Move point to the last line of the previous block.
1188 (while (and (markdown-cur-line-blank-p)
1192 ;; Update the indentation level using either the
1193 ;; non-list-marker indentation, if the previous line is the
1194 ;; start of a list, or the actual indentation.
1195 (setq prev-list
(markdown-cur-non-list-indent))
1196 (setq prev-indent
(or prev-list
1197 (markdown-cur-line-indent)))
1200 ;; If the loop didn't execute
1202 (setq prev-indent
0))
1204 ;; Compare with prev-indent minus its remainder mod 4
1205 (setq prev-indent
(- prev-indent
(mod prev-indent
4)))
1207 ;; Set match data and return t if we have a match
1208 (if (>= cur-indent
(+ prev-indent
4))
1212 (set-match-data (list cur-begin cur-end
))
1213 ;; Leave point at end of block
1217 ;; Move to the next block (if possible)
1219 (markdown--next-block)
1220 (setq cur-begin
(point))
1221 (setq cur-indent
(markdown-cur-line-indent))
1222 (markdown--end-of-level cur-indent
)
1223 (setq cur-end
(point))
1224 (setq stop
(equal cur-begin cur-end
))))
1227 (defun markdown-match-fenced-code-blocks (last)
1228 "Match fenced code blocks from the point to LAST."
1229 (cond ((search-forward-regexp "^\\([~]\\{3,\\}\\)" last t
)
1231 (let ((beg (point)))
1233 (cond ((search-forward-regexp
1234 (concat "^" (match-string 1) "~*") last t
)
1235 (set-match-data (list beg
(point)))
1240 (defun markdown-font-lock-extend-region ()
1241 "Extend the search region to include an entire block of text.
1242 This helps improve font locking for block constructs such as pre blocks."
1243 ;; Avoid compiler warnings about these global variables from font-lock.el.
1244 ;; See the documentation for variable `font-lock-extend-region-functions'.
1245 (eval-when-compile (defvar font-lock-beg
) (defvar font-lock-end
))
1247 (goto-char font-lock-beg
)
1248 (let ((found (re-search-backward "\n\n" nil t
)))
1250 (goto-char font-lock-end
)
1251 (when (re-search-forward "\n\n" nil t
)
1253 (setq font-lock-end
(point)))
1254 (setq font-lock-beg found
)))))
1258 ;;; Syntax Table ==============================================================
1260 (defvar markdown-mode-syntax-table
1261 (let ((markdown-mode-syntax-table (make-syntax-table)))
1262 (modify-syntax-entry ?
\" "w" markdown-mode-syntax-table
)
1263 markdown-mode-syntax-table
)
1264 "Syntax table for `markdown-mode'.")
1268 ;;; Element Insertion =========================================================
1270 (defun markdown-wrap-or-insert (s1 s2
)
1271 "Insert the strings S1 and S2.
1272 If Transient Mark mode is on and a region is active, wrap the strings S1
1273 and S2 around the region."
1274 (if (markdown-transient-mark-mode-active)
1275 (let ((a (region-beginning)) (b (region-end)))
1278 (goto-char (+ b
(length s1
)))
1282 (defun markdown-insert-hr ()
1283 "Insert a horizonal rule using `markdown-hr-string'."
1285 ;; Leading blank line
1286 (when (and (>= (point) (+ (point-min) 2))
1287 (not (looking-back "\n\n" 2)))
1289 ;; Insert custom HR string
1290 (insert (concat markdown-hr-string
"\n"))
1291 ;; Following blank line
1293 (unless (looking-at "\n\n")
1296 (defun markdown-insert-bold ()
1297 "Insert markup for a bold word or phrase.
1298 If Transient Mark mode is on and a region is active, it is made bold."
1300 (if markdown-bold-underscore
1301 (markdown-wrap-or-insert "__" "__")
1302 (markdown-wrap-or-insert "**" "**"))
1305 (defun markdown-insert-italic ()
1306 "Insert markup for an italic word or phrase.
1307 If Transient Mark mode is on and a region is active, it is made italic."
1309 (if markdown-italic-underscore
1310 (markdown-wrap-or-insert "_" "_")
1311 (markdown-wrap-or-insert "*" "*"))
1314 (defun markdown-insert-code ()
1315 "Insert markup for an inline code fragment.
1316 If Transient Mark mode is on and a region is active, it is marked
1319 (markdown-wrap-or-insert "`" "`")
1322 (defun markdown-insert-link ()
1323 "Insert an inline link of the form []().
1324 If Transient Mark mode is on and a region is active, it is used
1327 (markdown-wrap-or-insert "[" "]")
1331 (defun markdown-insert-reference-link-dwim ()
1332 "Insert a reference link of the form [text][label] at point.
1333 If Transient Mark mode is on and a region is active, the region
1334 is used as the link text. Otherwise, the link text will be read
1335 from the minibuffer. The link URL, label, and title will be read
1336 from the minibuffer. The link label definition is placed at the
1337 end of the current paragraph."
1339 (if (markdown-transient-mark-mode-active)
1340 (call-interactively 'markdown-insert-reference-link-region
)
1341 (call-interactively 'markdown-insert-reference-link
)))
1343 (defun markdown-insert-reference-link-region (url label title
)
1344 "Insert a reference link at point using the region as the link text."
1345 (interactive "sLink URL: \nsLink Label (optional): \nsLink Title (optional): ")
1346 (let ((text (buffer-substring (region-beginning) (region-end))))
1347 (delete-region (region-beginning) (region-end))
1348 (markdown-insert-reference-link text url label title
)))
1350 (defun markdown-insert-reference-link (text url label title
)
1351 "Insert a reference link at point.
1352 The link label definition is placed at the end of the current
1354 (interactive "sLink Text: \nsLink URL: \nsLink Label (optional): \nsLink Title (optional): ")
1356 (insert (concat "[" text
"][" label
"]"))
1360 (if (> (length label
) 0)
1363 (insert (concat "]: " url
))
1364 (unless (> (length url
) 0)
1366 (when (> (length title
) 0)
1367 (insert (concat " \"" title
"\"")))
1369 (unless (looking-at "\n")
1373 (defun markdown-insert-wiki-link ()
1374 "Insert a wiki link of the form [[WikiLink]].
1375 If Transient Mark mode is on and a region is active, it is used
1378 (markdown-wrap-or-insert "[[" "]]")
1381 (defun markdown-insert-image ()
1382 "Insert an inline image tag of the form ![]().
1383 If Transient Mark mode is on and a region is active, it is used
1384 as the alt text of the image."
1386 (markdown-wrap-or-insert "![" "]")
1390 (defun markdown-insert-header-1 ()
1391 "Insert a first level atx-style (hash mark) header.
1392 If Transient Mark mode is on and a region is active, it is used
1393 as the header text."
1395 (markdown-insert-header 1))
1397 (defun markdown-insert-header-2 ()
1398 "Insert a second level atx-style (hash mark) header.
1399 If Transient Mark mode is on and a region is active, it is used
1400 as the header text."
1402 (markdown-insert-header 2))
1404 (defun markdown-insert-header-3 ()
1405 "Insert a third level atx-style (hash mark) header.
1406 If Transient Mark mode is on and a region is active, it is used
1407 as the header text."
1409 (markdown-insert-header 3))
1411 (defun markdown-insert-header-4 ()
1412 "Insert a fourth level atx-style (hash mark) header.
1413 If Transient Mark mode is on and a region is active, it is used
1414 as the header text."
1416 (markdown-insert-header 4))
1418 (defun markdown-insert-header-5 ()
1419 "Insert a fifth level atx-style (hash mark) header.
1420 If Transient Mark mode is on and a region is active, it is used
1421 as the header text."
1423 (markdown-insert-header 5))
1425 (defun markdown-insert-header-6 ()
1426 "Insert a sixth level atx-style (hash mark) header.
1427 If Transient Mark mode is on and a region is active, it is used
1428 as the header text."
1430 (markdown-insert-header 6))
1432 (defun markdown-insert-header (n)
1433 "Insert an atx-style (hash mark) header.
1434 With no prefix argument, insert a level-1 header. With prefix N,
1435 insert a level-N header. If Transient Mark mode is on and the
1436 region is active, it is used as the header text."
1438 (unless n
; Test to see if n is defined
1439 (setq n
1)) ; Default to level 1 header
1440 (let (hdr hdrl hdrr
)
1441 (dotimes (count n hdr
)
1442 (setq hdr
(concat "#" hdr
))) ; Build a hash mark header string
1443 (setq hdrl
(concat hdr
" "))
1444 (setq hdrr
(concat " " hdr
))
1445 (markdown-wrap-or-insert hdrl hdrr
))
1446 (backward-char (+ 1 n
)))
1448 (defun markdown-insert-title ()
1449 "Insert a setext-style (underline) first level header.
1450 If Transient Mark mode is on and a region is active, it is used
1451 as the header text."
1453 (if (markdown-transient-mark-mode-active)
1454 (let ((a (region-beginning))
1459 (dotimes (count len hdr
)
1460 (setq hdr
(concat "=" hdr
))) ; Build a === title underline
1462 (insert "\n" hdr
"\n"))
1463 (insert "\n==========\n")
1464 (backward-char 12)))
1466 (defun markdown-insert-section ()
1467 "Insert a setext-style (underline) second level header.
1468 If Transient Mark mode is on and a region is active, it is used
1469 as the header text."
1471 (if (markdown-transient-mark-mode-active)
1472 (let ((a (region-beginning))
1477 (dotimes (count len hdr
)
1478 (setq hdr
(concat "-" hdr
))) ; Build a --- section underline
1480 (insert "\n" hdr
"\n"))
1481 (insert "\n----------\n")
1482 (backward-char 12)))
1484 (defun markdown-insert-blockquote ()
1485 "Start a blockquote section (or blockquote the region).
1486 If Transient Mark mode is on and a region is active, it is used as
1487 the blockquote text."
1489 (if (markdown-transient-mark-mode-active)
1490 (markdown-blockquote-region (region-beginning) (region-end))
1493 (defun markdown-block-region (beg end prefix
)
1494 "Format the region using a block prefix.
1495 Arguments BEG and END specify the beginning and end of the
1496 region. The characters PREFIX will appear at the beginning
1500 ;; Ensure that there is a leading blank line
1502 (when (and (>= (point) (+ (point-min) 2))
1503 (not (looking-back "\n\n" 2)))
1506 (setq end
(1+ end
)))
1507 ;; Move back before any blank lines at the end
1509 (while (and (looking-back "\n" 1)
1510 (not (equal (point) (point-min))))
1512 (setq end
(1- end
)))
1513 ;; Ensure that there is a trailing blank line
1515 (if (not (or (looking-at "\n\n")
1516 (and (equal (1+ end
) (point-max)) (looking-at "\n"))))
1521 (while (< (point-at-bol) end
)
1523 (setq end
(+ (length prefix
) end
))
1526 (defun markdown-blockquote-region (beg end
)
1527 "Blockquote the region.
1528 Arguments BEG and END specify the beginning and end of the region."
1530 (markdown-block-region beg end
"> "))
1532 (defun markdown-insert-pre ()
1533 "Start a preformatted section (or apply to the region).
1534 If Transient Mark mode is on and a region is active, it is marked
1535 as preformatted text."
1537 (if (markdown-transient-mark-mode-active)
1538 (markdown-pre-region (region-beginning) (region-end))
1541 (defun markdown-pre-region (beg end
)
1542 "Format the region as preformatted text.
1543 Arguments BEG and END specify the beginning and end of the region."
1545 (markdown-block-region beg end
" "))
1547 ;;; Footnotes ======================================================================
1549 (defun markdown-footnote-counter-inc ()
1550 "Increment markdown-footnote-counter and return the new value."
1551 (when (= markdown-footnote-counter
0) ; hasn't been updated in this buffer yet.
1553 (goto-char (point-min))
1554 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars
"*?\\)\\]:")
1556 (let ((fn (string-to-number (match-string 1))))
1557 (when (> fn markdown-footnote-counter
)
1558 (setq markdown-footnote-counter fn
))))))
1559 (incf markdown-footnote-counter
))
1561 (defun markdown-footnote-new ()
1562 "Insert a footnote with a new number and jump to a position to enter the
1565 (let ((fn (markdown-footnote-counter-inc)))
1566 (insert (format "[^%d]" fn
))
1567 (markdown-footnote-text-find-new-location)
1568 (insert (format "[^%d]: " fn
))))
1570 (defun markdown-footnote-text-find-new-location ()
1571 "Position the cursor at the proper location for a new footnote text."
1573 ((eq markdown-footnote-location
'end
) (goto-char (point-max)))
1574 ((eq markdown-footnote-location
'immediately
) (forward-paragraph))
1575 ((eq markdown-footnote-location
'header
)
1576 ;; search for a header. if none is found, go to the end of the document.
1580 (unless (re-search-forward markdown-regex-header nil t
)
1582 (backward-paragraph)
1583 (not (looking-at (concat "\n" markdown-regex-header
))))))))
1584 ;; make sure we're on an empty line:
1585 (unless (markdown-cur-line-blank-p)
1587 ;; and make sure the previous line is empty:
1588 (unless (markdown-prev-line-blank-p)
1590 ;; then make sure there's an empty line following the footnote:
1591 (unless (markdown-next-line-blank-p)
1595 (defun markdown-footnote-kill ()
1596 "Kill the footnote at point.
1597 The footnote text is killed (and added to the kill ring), the
1598 footnote marker is deleted. Point has to be either at the
1599 footnote marker or in the footnote text."
1602 (when (markdown-footnote-text-positions) ; if we're in a footnote text
1603 (markdown-footnote-return) ; we first move to the marker
1604 (setq return-pos
'text
)) ; and remember our return position
1605 (let ((marker (markdown-footnote-delete-marker)))
1607 (error "Not at a footnote"))
1608 (let ((text-pos (markdown-footnote-find-text (car marker
))))
1610 (error "No text for footnote `%s'" (car marker
)))
1611 (goto-char text-pos
)
1612 (let ((pos (markdown-footnote-kill-text)))
1614 (if (and pos
(eq return-pos
'text
))
1617 (goto-char return-pos
)))
1619 (defun markdown-footnote-delete-marker ()
1620 "Delete a footnote marker at point.
1621 Returns a list (ID START) containing the footnote ID and the
1622 start position of the marker before deletion. If no footnote
1623 marker was deleted, this function returns NIL."
1624 (let ((marker (markdown-footnote-marker-positions)))
1626 (delete-region (second marker
) (third marker
))
1629 (defun markdown-footnote-kill-text ()
1630 "Kill footnote text at point.
1631 Returns the start position of the footnote text before deletion,
1632 or NIL if point was not inside a footnote text.
1634 The killed text is placed in the kill ring (without the footnote
1636 (let ((fn (markdown-footnote-text-positions)))
1638 (let ((text (delete-and-extract-region (second fn
) (third fn
))))
1639 (string-match (concat "\\[\\" (first fn
) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text
)
1640 (kill-new (match-string 1 text
))
1643 (defun markdown-footnote-goto-text ()
1644 "Jump to the text of the footnote at point."
1646 (let ((fn (car (markdown-footnote-marker-positions))))
1648 (error "Not at a footnote marker"))
1649 (let ((new-pos (markdown-footnote-find-text fn
)))
1651 (error "No definition found for footnote `%s'" fn
))
1652 (goto-char new-pos
))))
1654 (defun markdown-footnote-return ()
1655 "Return from a footnote to its footnote number in the main text."
1657 (let ((fn (save-excursion
1658 (car (markdown-footnote-text-positions)))))
1660 (error "Not in a footnote"))
1661 (let ((new-pos (markdown-footnote-find-marker fn
)))
1663 (error "Footnote marker `%s' not found" fn
))
1664 (goto-char new-pos
))))
1666 (defun markdown-footnote-find-marker (id)
1667 "Find the location of the footnote marker with ID.
1668 The actual buffer position returned is the position directly
1669 following the marker's closing bracket. If no marker is found,
1672 (goto-char (point-min))
1673 (when (re-search-forward (concat "\\[" id
"\\]\\([^:]\\|\\'\\)") nil t
)
1674 (skip-chars-backward "^]")
1677 (defun markdown-footnote-find-text (id)
1678 "Find the location of the text of footnote ID.
1679 The actual buffer position returned is the position of the first
1680 character of the text, after the footnote's identifier. If no
1681 footnote text is found, NIL is returned."
1683 (goto-char (point-min))
1684 (when (re-search-forward (concat "^\\[" id
"\\]:") nil t
)
1685 (skip-chars-forward "[:space:]")
1688 (defun markdown-footnote-marker-positions ()
1689 "Return the position and ID of the footnote marker point is on.
1690 The return value is a list (ID START END). If point is not on a
1691 footnote, NIL is returned."
1692 ;; first make sure we're at a footnote marker
1693 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars
"*\\]?") (point-at-bol))
1694 (looking-at (concat "\\[?\\^" markdown-footnote-chars
"*?\\]")))
1696 ;; move point between [ and ^:
1697 (if (looking-at "\\[")
1699 (skip-chars-backward "^["))
1700 (looking-at (concat "\\(\\^" markdown-footnote-chars
"*?\\)\\]"))
1701 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
1703 (defun markdown-footnote-text-positions ()
1704 "Return the start and end positions of the footnote text point is in.
1705 The exact return value is a list of three elements: (ID START
1706 END). The start position is the position of the opening bracket
1707 of the footnote id. The end position is directly after the
1708 newline that ends the footnote. If point is not in a footnote,
1709 NIL is returned instead."
1712 (backward-paragraph)
1713 ;; if we're in a multiparagraph footnote, we need to back up further
1714 (while (>= (markdown-next-line-indent) 4)
1715 (backward-paragraph))
1717 (if (looking-at (concat "^\\[\\(\\^" markdown-footnote-chars
"*?\\)\\]:"))
1718 (list (match-string 1) (point))))))
1722 (>= (markdown-next-line-indent) 4)))
1723 (append fn
(list (point)))))))
1725 ;;; Indentation ====================================================================
1727 (defun markdown-indent-find-next-position (cur-pos positions
)
1728 "Return the position after the index of CUR-POS in POSITIONS."
1729 (while (and positions
1730 (not (equal cur-pos
(car positions
))))
1731 (setq positions
(cdr positions
)))
1732 (or (cadr positions
) 0))
1734 (defun markdown-indent-line ()
1735 "Indent the current line using some heuristics.
1736 If the _previous_ command was either `markdown-enter-key' or
1737 `markdown-cycle', then we should cycle to the next
1738 reasonable indentation position. Otherwise, we could have been
1739 called directly by `markdown-enter-key', by an initial call of
1740 `markdown-cycle', or indirectly by `auto-fill-mode'. In
1741 these cases, indent to the default position."
1743 (let ((positions (markdown-calc-indents))
1744 (cur-pos (current-column)))
1745 (if (not (equal this-command
'markdown-cycle
))
1746 (indent-line-to (car positions
))
1747 (setq positions
(sort (delete-dups positions
) '<))
1749 (markdown-indent-find-next-position cur-pos positions
)))))
1751 (defun markdown-calc-indents ()
1752 "Return a list of indentation columns to cycle through.
1753 The first element in the returned list should be considered the
1754 default indentation level."
1755 (let (pos prev-line-pos positions
)
1757 ;; Previous line indent
1758 (setq prev-line-pos
(markdown-prev-line-indent))
1759 (setq positions
(cons prev-line-pos positions
))
1761 ;; Previous non-list-marker indent
1762 (setq pos
(markdown-prev-non-list-indent))
1764 (setq positions
(cons pos positions
))
1765 (setq positions
(cons (+ pos tab-width
) positions
)))
1767 ;; Indentation of the previous line + tab-width
1770 (setq positions
(cons (+ prev-line-pos tab-width
) positions
)))
1772 (setq positions
(cons tab-width positions
))))
1774 ;; Indentation of the previous line - tab-width
1775 (if (and prev-line-pos
1776 (> prev-line-pos tab-width
))
1777 (setq positions
(cons (- prev-line-pos tab-width
) positions
)))
1779 ;; Indentation of preceeding list item
1784 (while (not (equal (point) (point-min)))
1786 (goto-char (point-at-bol))
1787 (when (re-search-forward markdown-regex-list-indent
(point-at-eol) t
)
1788 (throw 'break
(length (match-string 1)))))
1790 (if (and pos
(not (eq pos prev-line-pos
)))
1791 (setq positions
(cons pos positions
)))
1794 (setq positions
(cons 0 positions
))
1796 (reverse positions
)))
1798 (defun markdown-do-normal-return ()
1799 "Insert a newline and optionally indent the next line."
1801 (if markdown-indent-on-enter
1802 (funcall indent-line-function
)))
1804 (defun markdown-enter-key ()
1805 "Handle RET according to context.
1806 If there is a wiki link at the point, follow it unless
1807 `markdown-follow-wiki-link-on-enter' is nil. Otherwise, process
1808 it in the usual way."
1810 (if (and markdown-follow-wiki-link-on-enter
(markdown-wiki-link-p))
1811 (markdown-follow-wiki-link-at-point)
1812 (markdown-do-normal-return)))
1814 (defun markdown-dedent-or-delete (arg)
1815 "Handle BACKSPACE by cycling through indentation points.
1816 When BACKSPACE is pressed, if there is only whitespace
1817 before the current point, then dedent the line one level.
1818 Otherwise, do normal delete by repeating
1819 `backward-delete-char-untabify' ARG times."
1821 (let ((cur-pos (current-column))
1822 (start-of-indention (save-excursion
1823 (back-to-indentation)
1825 (if (and (> cur-pos
0) (= cur-pos start-of-indention
))
1827 (dolist (i (markdown-calc-indents))
1829 (setq result
(max result i
))))
1830 (indent-line-to result
))
1831 (backward-delete-char-untabify arg
))))
1835 ;;; Keymap ====================================================================
1837 (defvar markdown-mode-map
1838 (let ((map (make-keymap)))
1839 ;; Element insertion
1840 (define-key map
"\C-c\C-al" 'markdown-insert-link
)
1841 (define-key map
"\C-c\C-ar" 'markdown-insert-reference-link-dwim
)
1842 (define-key map
"\C-c\C-aw" 'markdown-insert-wiki-link
)
1843 (define-key map
"\C-c\C-ii" 'markdown-insert-image
)
1844 (define-key map
"\C-c\C-t1" 'markdown-insert-header-1
)
1845 (define-key map
"\C-c\C-t2" 'markdown-insert-header-2
)
1846 (define-key map
"\C-c\C-t3" 'markdown-insert-header-3
)
1847 (define-key map
"\C-c\C-t4" 'markdown-insert-header-4
)
1848 (define-key map
"\C-c\C-t5" 'markdown-insert-header-5
)
1849 (define-key map
"\C-c\C-t6" 'markdown-insert-header-6
)
1850 (define-key map
"\C-c\C-pb" 'markdown-insert-bold
)
1851 (define-key map
"\C-c\C-ss" 'markdown-insert-bold
)
1852 (define-key map
"\C-c\C-pi" 'markdown-insert-italic
)
1853 (define-key map
"\C-c\C-se" 'markdown-insert-italic
)
1854 (define-key map
"\C-c\C-pf" 'markdown-insert-code
)
1855 (define-key map
"\C-c\C-sc" 'markdown-insert-code
)
1856 (define-key map
"\C-c\C-sb" 'markdown-insert-blockquote
)
1857 (define-key map
"\C-c\C-s\C-b" 'markdown-blockquote-region
)
1858 (define-key map
"\C-c\C-sp" 'markdown-insert-pre
)
1859 (define-key map
"\C-c\C-s\C-p" 'markdown-pre-region
)
1860 (define-key map
"\C-c-" 'markdown-insert-hr
)
1861 (define-key map
"\C-c\C-tt" 'markdown-insert-title
)
1862 (define-key map
"\C-c\C-ts" 'markdown-insert-section
)
1864 (define-key map
"\C-c\C-fn" 'markdown-footnote-new
)
1865 (define-key map
"\C-c\C-fg" 'markdown-footnote-goto-text
)
1866 (define-key map
"\C-c\C-fb" 'markdown-footnote-return
)
1867 (define-key map
"\C-c\C-fk" 'markdown-footnote-kill
)
1868 ;; Regular Link Following
1869 (define-key map
"\C-c\C-o" 'markdown-follow-link-at-point
)
1870 ;; WikiLink Following
1871 (define-key map
"\C-c\C-w" 'markdown-follow-wiki-link-at-point
)
1872 (define-key map
"\M-n" 'markdown-next-wiki-link
)
1873 (define-key map
"\M-p" 'markdown-previous-wiki-link
)
1875 (define-key map
"\C-m" 'markdown-enter-key
)
1876 (define-key map
(kbd "<backspace>") 'markdown-dedent-or-delete
)
1877 ;; Visibility cycling
1878 (define-key map
(kbd "<tab>") 'markdown-cycle
)
1879 (define-key map
(kbd "<S-iso-lefttab>") 'markdown-shifttab
)
1880 (define-key map
(kbd "<S-tab>") 'markdown-shifttab
)
1881 (define-key map
(kbd "<backtab>") 'markdown-shifttab
)
1882 ;; Header navigation
1883 (define-key map
(kbd "C-M-n") 'outline-next-visible-heading
)
1884 (define-key map
(kbd "C-M-p") 'outline-previous-visible-heading
)
1885 (define-key map
(kbd "C-M-f") 'outline-forward-same-level
)
1886 (define-key map
(kbd "C-M-b") 'outline-backward-same-level
)
1887 (define-key map
(kbd "C-M-u") 'outline-up-heading
)
1888 ;; Markdown functions
1889 (define-key map
"\C-c\C-cm" 'markdown-other-window
)
1890 (define-key map
"\C-c\C-cp" 'markdown-preview
)
1891 (define-key map
"\C-c\C-ce" 'markdown-export
)
1892 (define-key map
"\C-c\C-cv" 'markdown-export-and-preview
)
1893 (define-key map
"\C-c\C-co" 'markdown-open
)
1894 (define-key map
"\C-c\C-cw" 'markdown-kill-ring-save
)
1896 (define-key map
"\C-c\C-cc" 'markdown-check-refs
)
1898 (define-key map
"\C-c\C-cn" 'markdown-cleanup-list-numbers
)
1900 "Keymap for Markdown major mode.")
1902 ;;; Menu ==================================================================
1904 (easy-menu-define markdown-mode-menu markdown-mode-map
1905 "Menu for Markdown mode"
1908 ["Cycle visibility" markdown-cycle
(outline-on-heading-p)]
1909 ["Cycle global visibility" markdown-shifttab
])
1911 ["Compile" markdown-other-window
]
1912 ["Preview" markdown-preview
]
1913 ["Export" markdown-export
]
1914 ["Export & View" markdown-export-and-preview
]
1915 ["Open" markdown-open
]
1916 ["Kill ring save" markdown-kill-ring-save
]
1919 ["Insert Title" markdown-insert-title
]
1920 ["Insert Section" markdown-insert-section
])
1922 ["First level" markdown-insert-header-1
]
1923 ["Second level" markdown-insert-header-2
]
1924 ["Third level" markdown-insert-header-3
]
1925 ["Fourth level" markdown-insert-header-4
]
1926 ["Fifth level" markdown-insert-header-5
]
1927 ["Sixth level" markdown-insert-header-6
])
1929 ["Bold" markdown-insert-bold
]
1930 ["Italic" markdown-insert-italic
]
1931 ["Blockquote" markdown-insert-blockquote
]
1932 ["Preformatted" markdown-insert-pre
]
1933 ["Code" markdown-insert-code
]
1935 ["Insert inline link" markdown-insert-link
]
1936 ["Insert reference link" markdown-insert-reference-link-dwim
]
1937 ["Insert image" markdown-insert-image
]
1938 ["Insert horizontal rule" markdown-insert-hr
]
1941 ["Insert footnote" markdown-footnote-new
]
1942 ["Jump to footnote text" markdown-footnote-goto-text
]
1943 ["Return from footnote" markdown-footnote-return
])
1945 ["Check references" markdown-check-refs
]
1946 ["Clean up list numbering" markdown-cleanup-list-numbers
]
1948 ["Version" markdown-show-version
]
1953 ;;; imenu =====================================================================
1955 (defun markdown-imenu-create-index ()
1956 (let* ((root '(nil . nil
))
1959 (pattern "^\\(\\(#+\\)[ \t]*\\(.+\\)\\|\\([^# \t\n=-].*\\)\n===+\\|\\([^# \t\n=-].*\\)\n---+\\)$")
1962 hashes pos level heading
)
1964 (goto-char (point-min))
1965 (while (re-search-forward pattern
(point-max) t
)
1967 ((setq hashes
(match-string-no-properties 2))
1968 (setq heading
(match-string-no-properties 3)
1969 pos
(match-beginning 1)
1970 level
(length hashes
)))
1971 ((setq heading
(match-string-no-properties 4))
1972 (setq pos
(match-beginning 4)
1974 ((setq heading
(match-string-no-properties 5))
1975 (setq pos
(match-beginning 5)
1977 (let ((alist (list (cons heading pos
))))
1979 ((= cur-level level
) ; new sibling
1980 (setcdr cur-alist alist
)
1981 (setq cur-alist alist
))
1982 ((< cur-level level
) ; first child
1983 (dotimes (i (- level cur-level
1))
1984 (setq alist
(list (cons empty-heading alist
))))
1986 (let* ((parent (car cur-alist
))
1987 (self-pos (cdr parent
)))
1988 (setcdr parent
(cons (cons self-heading self-pos
) alist
)))
1989 (setcdr root alist
)) ; primogenitor
1990 (setq cur-alist alist
)
1991 (setq cur-level level
))
1992 (t ; new sibling of an ancestor
1993 (let ((sibling-alist (last (cdr root
))))
1994 (dotimes (i (1- level
))
1995 (setq sibling-alist
(last (cdar sibling-alist
))))
1996 (setcdr sibling-alist alist
)
1997 (setq cur-alist alist
))
1998 (setq cur-level level
)))))
2001 ;;; References ================================================================
2003 ;;; Undefined reference checking code by Dmitry Dzhus <mail@sphinx.net.ru>.
2005 (defconst markdown-refcheck-buffer
2006 "*Undefined references for %buffer%*"
2007 "Pattern for name of buffer for listing undefined references.
2008 The string %buffer% will be replaced by the corresponding
2009 `markdown-mode' buffer name.")
2011 (defun markdown-has-reference-definition (reference)
2012 "Find out whether Markdown REFERENCE is defined.
2014 REFERENCE should include the square brackets, like [this]."
2015 (let ((reference (downcase reference
)))
2017 (goto-char (point-min))
2019 (while (re-search-forward markdown-regex-reference-definition nil t
)
2020 (when (string= reference
(downcase (match-string-no-properties 1)))
2021 (throw 'found
(match-string-no-properties 2))))))))
2023 (defun markdown-get-undefined-refs ()
2024 "Return a list of undefined Markdown references.
2026 Result is an alist of pairs (reference . occurencies), where
2027 occurencies is itself another alist of pairs (label .
2030 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
2031 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
2032 \((\"[emacs]\" (\"[Nice editor]\" . 12) (\"[GNU Emacs]\" . 45)) (\"[elisp]\" (\"[manual]\" . 127)))."
2035 (goto-char (point-min))
2037 (re-search-forward markdown-regex-link-reference nil t
)
2038 (let* ((label (match-string-no-properties 1))
2039 (reference (match-string-no-properties 2))
2040 (target (downcase (if (string= reference
"[]") label reference
))))
2041 (unless (markdown-has-reference-definition target
)
2042 (let ((entry (assoc target missing
)))
2044 (add-to-list 'missing
(cons target
2045 (list (cons label
(markdown-line-number-at-pos)))) t
)
2047 (append (cdr entry
) (list (cons label
(markdown-line-number-at-pos))))))))))
2050 (defun markdown-add-missing-ref-definition (ref buffer
&optional recheck
)
2051 "Add blank REF definition to the end of BUFFER.
2053 REF is a Markdown reference in square brackets, like \"[lisp-history]\".
2055 When RECHECK is non-nil, BUFFER gets rechecked for undefined
2056 references so that REF disappears from the list of those links."
2057 (with-current-buffer buffer
2058 (when (not (eq major-mode
'markdown-mode
))
2059 (error "Not available in current mode"))
2060 (goto-char (point-max))
2061 (indent-new-comment-line)
2062 (insert (concat ref
": ")))
2063 (switch-to-buffer-other-window buffer
)
2064 (goto-char (point-max))
2066 (markdown-check-refs t
)))
2068 ;; Button which adds an empty Markdown reference definition to the end
2069 ;; of buffer specified as its 'target-buffer property. Reference name
2070 ;; is button's label
2071 (when (>= emacs-major-version
22)
2072 (define-button-type 'markdown-ref-button
2073 'help-echo
"Push to create an empty reference definition"
2076 (markdown-add-missing-ref-definition
2077 (button-label b
) (button-get b
'target-buffer
) t
))))
2079 ;; Button jumping to line in buffer specified as its 'target-buffer
2080 ;; property. Line number is button's 'line property.
2081 (when (>= emacs-major-version
22)
2082 (define-button-type 'goto-line-button
2083 'help-echo
"Push to go to this line"
2086 (message (button-get b
'buffer
))
2087 (switch-to-buffer-other-window (button-get b
'target-buffer
))
2088 ;; use call-interactively to silence compiler
2089 (call-interactively 'goto-line
(button-get b
'target-line
)))))
2091 (defun markdown-check-refs (&optional silent
)
2092 "Show all undefined Markdown references in current `markdown-mode' buffer.
2094 If SILENT is non-nil, do not message anything when no undefined
2097 Links which have empty reference definitions are considered to be
2100 (when (not (eq major-mode
'markdown-mode
))
2101 (error "Not available in current mode"))
2102 (let ((oldbuf (current-buffer))
2103 (refs (markdown-get-undefined-refs))
2104 (refbuf (get-buffer-create (markdown-replace-regexp-in-string
2105 "%buffer%" (buffer-name)
2106 markdown-refcheck-buffer
))))
2110 (message "No undefined references found"))
2111 (kill-buffer refbuf
))
2112 (with-current-buffer refbuf
2114 (View-exit-and-edit))
2116 (insert "Following references lack definitions:")
2119 (let ((button-label (format "%s" (car ref
))))
2120 (if (>= emacs-major-version
22)
2121 ;; Create a reference button in Emacs 22
2122 (insert-text-button button-label
2123 :type
'markdown-ref-button
2124 'target-buffer oldbuf
)
2125 ;; Insert reference as text in Emacs < 22
2126 (insert button-label
)))
2128 (dolist (occurency (cdr ref
))
2129 (let ((line (cdr occurency
)))
2130 (if (>= emacs-major-version
22)
2131 ;; Create a line number button in Emacs 22
2132 (insert-button (number-to-string line
)
2133 :type
'goto-line-button
2134 'target-buffer oldbuf
2136 ;; Insert line number as text in Emacs < 22
2137 (insert (number-to-string line
)))
2138 (insert " "))) (delete-char -
1)
2141 (view-buffer-other-window refbuf
)
2142 (goto-char (point-min))
2143 (forward-line 2)))))
2146 ;;; Lists =====================================================================
2148 (defun markdown--cleanup-list-numbers-level (&optional pfx
)
2149 "Update the numbering for level PFX (as a string of spaces).
2151 Assume that the previously found match was for a numbered item in
2158 (while (and continue
(not (eobp)))
2161 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
2162 (setq cpfx
(match-string-no-properties 1))
2166 (concat pfx
(number-to-string (setq idx
(1+ idx
))) ". "))
2170 (setq sep
(markdown--cleanup-list-numbers-level cpfx
))
2175 (setq continue nil
))))
2177 ((looking-at "^\\([\s-]*\\)[^ \n\r].*$")
2178 (setq cpfx
(match-string-no-properties 1))
2180 ;; reset if separated before
2181 ((string= cpfx pfx
) (when sep
(setq idx
0)))
2184 (setq continue nil
))))
2189 (setq continue
(= (forward-line) 0))))
2193 (defun markdown-cleanup-list-numbers ()
2194 "Update the numbering of ordered lists."
2197 (goto-char (point-min))
2198 (markdown--cleanup-list-numbers-level "")))
2201 ;;; Outline ===================================================================
2203 ;; The following visibility cycling code was taken from org-mode
2204 ;; by Carsten Dominik and adapted for markdown-mode.
2206 (defvar markdown-cycle-global-status
1)
2207 (defvar markdown-cycle-subtree-status nil
)
2209 ;; Based on org-end-of-subtree from org.el
2210 (defun markdown-end-of-subtree (&optional invisible-OK
)
2211 "Move to the end of the current subtree.
2212 Only visible heading lines are considered, unless INVISIBLE-OK is
2214 (outline-back-to-heading invisible-OK
)
2216 (level (funcall outline-level
)))
2217 (while (and (not (eobp))
2218 (or first
(> (funcall outline-level
) level
)))
2220 (outline-next-heading))
2221 (if (memq (preceding-char) '(?
\n ?\^M
))
2223 ;; Go to end of line before heading
2225 (if (memq (preceding-char) '(?
\n ?\^M
))
2226 ;; leave blank line before heading
2227 (forward-char -
1)))))
2230 ;; Based on org-cycle from org.el.
2231 (defun markdown-cycle (&optional arg
)
2232 "Visibility cycling for Markdown mode.
2233 If ARG is t, perform global visibility cycling. If the point is
2234 at an atx-style header, cycle visibility of the corresponding
2235 subtree. Otherwise, insert a tab using `indent-relative'."
2238 ((eq arg t
) ;; Global cycling
2240 ((and (eq last-command this-command
)
2241 (eq markdown-cycle-global-status
2))
2242 ;; Move from overview to contents
2244 (message "CONTENTS")
2245 (setq markdown-cycle-global-status
3))
2247 ((and (eq last-command this-command
)
2248 (eq markdown-cycle-global-status
3))
2249 ;; Move from contents to all
2251 (message "SHOW ALL")
2252 (setq markdown-cycle-global-status
1))
2255 ;; Defaults to overview
2257 (message "OVERVIEW")
2258 (setq markdown-cycle-global-status
2))))
2260 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp
))
2261 ;; At a heading: rotate between three different views
2262 (outline-back-to-heading)
2263 (let ((goal-column 0) eoh eol eos
)
2264 ;; Determine boundaries
2266 (outline-back-to-heading)
2268 (beginning-of-line 2)
2269 (while (and (not (eobp)) ;; this is like `next-line'
2270 (get-char-property (1- (point)) 'invisible
))
2271 (beginning-of-line 2)) (setq eol
(point)))
2272 (outline-end-of-heading) (setq eoh
(point))
2273 (markdown-end-of-subtree t
)
2274 (skip-chars-forward " \t\n")
2275 (beginning-of-line 1) ; in case this is an item
2276 (setq eos
(1- (point))))
2277 ;; Find out what to do next and set `this-command'
2280 ;; Nothing is hidden behind this heading
2281 (message "EMPTY ENTRY")
2282 (setq markdown-cycle-subtree-status nil
))
2284 ;; Entire subtree is hidden in one line: open it
2287 (message "CHILDREN")
2288 (setq markdown-cycle-subtree-status
'children
))
2289 ((and (eq last-command this-command
)
2290 (eq markdown-cycle-subtree-status
'children
))
2291 ;; We just showed the children, now show everything.
2294 (setq markdown-cycle-subtree-status
'subtree
))
2296 ;; Default action: hide the subtree.
2299 (setq markdown-cycle-subtree-status
'folded
)))))
2302 (indent-for-tab-command))))
2304 ;; Based on org-shifttab from org.el.
2305 (defun markdown-shifttab ()
2306 "Global visibility cycling.
2307 Calls `markdown-cycle' with argument t."
2311 (defun markdown-outline-level ()
2312 "Return the depth to which a statement is nested in the outline."
2316 ((- (match-end 0) (match-beginning 0)))))
2318 ;;; Commands ==================================================================
2320 (defun markdown (&optional output-buffer-name
)
2321 "Run `markdown' on current buffer and insert output in buffer given by
2322 `output-buffer-name' (defaults to `markdown-output-buffer-name'). Return the
2323 OUTPUT-BUFFER used."
2325 (save-window-excursion
2326 (let ((begin-region)
2328 (if (markdown-transient-mark-mode-active)
2329 (setq begin-region
(region-beginning)
2330 end-region
(region-end))
2331 (setq begin-region
(point-min)
2332 end-region
(point-max)))
2334 (unless output-buffer-name
2335 (setq output-buffer-name markdown-output-buffer-name
))
2338 ;; Handle case when `markdown-command' does not read from stdin
2339 (markdown-command-needs-filename
2340 (if (not buffer-file-name
)
2341 (error "Must be visiting a file")
2342 (shell-command (concat markdown-command
" "
2343 (shell-quote-argument buffer-file-name
))
2344 output-buffer-name
)))
2345 ;; Pass region to `markdown-command' via stdin
2347 (shell-command-on-region begin-region end-region markdown-command
2348 output-buffer-name
))))
2349 output-buffer-name
))
2351 (defun markdown-standalone (&optional output-buffer-name
)
2352 "special function to provide html standalone output"
2354 (setq output-buffer-name
(markdown output-buffer-name
))
2355 (with-current-buffer output-buffer-name
2356 (set-buffer output-buffer-name
)
2357 (goto-char (point-min))
2358 (unless (markdown-output-standalone-p)
2359 (markdown-add-xhtml-header-and-footer output-buffer-name
))
2363 (defun markdown-other-window (&optional output-buffer-name
)
2364 " Run `markdown' on current buffer and display in other window"
2366 (display-buffer (markdown-standalone output-buffer-name
)))
2368 (defun markdown-output-standalone-p ()
2369 "Determine whether `markdown-command' output is standalone XHTML.
2370 Standalone XHTML output is identified by an occurrence of
2371 `markdown-xhtml-standalone-regexp' in the first five lines of output."
2373 markdown-xhtml-standalone-regexp
2374 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
2377 (defun markdown-add-xhtml-header-and-footer (title)
2378 "Wrap XHTML header and footer with given TITLE around current buffer."
2379 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
2380 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
2381 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
2382 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
2385 (insert "</title>\n")
2386 (when (> (length markdown-content-type
) 0)
2389 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
2390 markdown-content-type
2391 (or (and markdown-coding-system
2392 (fboundp 'coding-system-get
)
2393 (coding-system-get markdown-coding-system
2395 (and (fboundp 'coding-system-get
)
2396 (coding-system-get buffer-file-coding-system
2399 (if (> (length markdown-css-path
) 0)
2400 (insert "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
2403 (when (> (length markdown-xhtml-header-content
) 0)
2404 (insert markdown-xhtml-header-content
))
2405 (insert "\n</head>\n\n"
2407 (goto-char (point-max))
2412 (defun markdown-preview (&optional output-buffer-name
)
2413 "Run `markdown' on the current buffer and preview the output in a browser."
2415 (browse-url-of-buffer (markdown markdown-output-buffer-name
)))
2417 (defun markdown-export-file-name (&optional extension
)
2418 "Attempt to generate a filename for Markdown output.
2419 If the current buffer is visiting a file, we construct a new
2420 output filename based on that filename. Otherwise, return nil."
2421 (when (buffer-file-name)
2423 (setq extension
".html"))
2427 (file-name-sans-extension (buffer-file-name)))
2431 (defun markdown-export (&optional output-file
)
2432 "Run Markdown on the current buffer, save to a file, and return the filename.
2433 The resulting filename will be constructed using the current filename, but
2434 with the extension removed and replaced with .html."
2437 (setq output-file
(markdown-export-file-name ".html")))
2439 (let ((output-buffer-name))
2440 (setq output-buffer-name
(buffer-name (find-file-noselect output-file
)))
2441 (markdown-standalone output-buffer-name
)
2442 (with-current-buffer output-buffer-name
2446 (defun markdown-export-and-preview ()
2447 "Export to XHTML using `markdown-export' and browse the resulting file."
2449 (browse-url (markdown-export)))
2451 (defun markdown-open ()
2452 "Open file for the current buffer with `markdown-open-command'."
2454 (if (not markdown-open-command
)
2455 (error "Variable `markdown-open-command' must be set")
2456 (if (not buffer-file-name
)
2457 (error "Must be visiting a file")
2458 (call-process markdown-open-command
2459 nil nil nil buffer-file-name
))))
2461 (defun markdown-kill-ring-save ()
2462 "Run Markdown on file and store output in the kill ring."
2464 (save-window-excursion
2466 (with-current-buffer markdown-output-buffer-name
2467 (kill-ring-save (point-min) (point-max)))))
2470 ;;; Links =====================================================================
2472 (require 'thingatpt
)
2474 (defun markdown-link-p ()
2475 "Return non-nil when `point' is at a non-wiki link.
2476 See `markdown-wiki-link-p' for more information."
2477 (let ((case-fold-search nil
))
2478 (and (not (markdown-wiki-link-p))
2479 (or (thing-at-point-looking-at markdown-regex-link-inline
)
2480 (thing-at-point-looking-at markdown-regex-link-reference
)))))
2482 (defun markdown-link-link ()
2483 "Return the link part of the regular (non-wiki) link at point.
2484 Works with both inline and reference style links. If point is
2485 not at a link or the link reference is not defined returns nil."
2487 ((thing-at-point-looking-at markdown-regex-link-inline
)
2488 (substring-no-properties (match-string 2) 1 -
1))
2489 ((thing-at-point-looking-at markdown-regex-link-reference
)
2490 (let* ((label (match-string-no-properties 1))
2491 (reference (match-string-no-properties 2))
2492 (target (downcase (if (string= reference
"[]") label reference
))))
2493 (markdown-has-reference-definition target
)))
2494 (t (error "Not on a markdown link"))))
2496 (defun markdown-follow-link-at-point ()
2497 "Open the current non-wiki link in a browser."
2499 (if (markdown-link-p) (browse-url (markdown-link-link))))
2502 ;;; WikiLink Following/Markup =================================================
2504 (defun markdown-wiki-link-p ()
2505 "Return non-nil when `point' is at a true wiki link.
2506 A true wiki link name matches `markdown-regex-wiki-link' but does not
2507 match the current file name after conversion. This modifies the data
2508 returned by `match-data'. Note that the potential wiki link name must
2509 be available via `match-string'."
2510 (let ((case-fold-search nil
))
2511 (and (thing-at-point-looking-at markdown-regex-wiki-link
)
2512 (or (not buffer-file-name
)
2513 (not (string-equal (buffer-file-name)
2514 (markdown-convert-wiki-link-to-filename
2515 (markdown-wiki-link-link)))))
2516 (not (save-match-data
2517 (save-excursion))))))
2519 (defun markdown-wiki-link-link ()
2520 "Return the link part of the wiki link using current match data.
2521 The location of the link component depends on the value of
2522 `markdown-wiki-link-alias-first'."
2523 (if markdown-wiki-link-alias-first
2524 (or (match-string 3) (match-string 1))
2527 (defun markdown-convert-wiki-link-to-filename (name)
2528 "Generate a filename from the wiki link NAME.
2529 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
2530 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
2531 and [[test test]] both map to Test-test.ext."
2532 (let ((basename (markdown-replace-regexp-in-string
2533 "[[:space:]\n]" markdown-link-space-sub-char name
)))
2534 (when (eq major-mode
'gfm-mode
)
2535 (setq basename
(concat (upcase (substring basename
0 1))
2536 (downcase (substring basename
1 nil
)))))
2538 (if (buffer-file-name)
2540 (file-name-extension (buffer-file-name)))))))
2542 (defun markdown-follow-wiki-link (name &optional other
)
2543 "Follow the wiki link NAME.
2544 Convert the name to a file name and call `find-file'. Ensure that
2545 the new buffer remains in `markdown-mode'."
2546 (let ((filename (markdown-convert-wiki-link-to-filename name
))
2547 (wp (file-name-directory buffer-file-name
)))
2548 (when other
(other-window 1))
2549 (find-file (concat wp filename
)))
2550 (when (not (eq major-mode
'markdown-mode
))
2553 (defun markdown-follow-wiki-link-at-point (&optional arg
)
2554 "Find Wiki Link at point.
2555 With prefix argument C-u open the file in other window.
2557 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
2559 (if (markdown-wiki-link-p)
2560 (markdown-follow-wiki-link (markdown-wiki-link-link) arg
)
2561 (error "Point is not at a Wiki Link")))
2563 (defun markdown-next-wiki-link ()
2564 "Jump to next wiki link.
2565 See `markdown-wiki-link-p'."
2567 (if (markdown-wiki-link-p)
2568 ;; At a wiki link already, move past it.
2569 (goto-char (+ 1 (match-end 0))))
2571 ;; Search for the next wiki link and move to the beginning.
2572 (re-search-forward markdown-regex-wiki-link nil t
)
2573 (goto-char (match-beginning 0))))
2575 (defun markdown-previous-wiki-link ()
2576 "Jump to previous wiki link.
2577 See `markdown-wiki-link-p'."
2579 (re-search-backward markdown-regex-wiki-link nil t
))
2581 (defun markdown-highlight-wiki-link (from to face
)
2582 "Highlight the wiki link in the region between FROM and TO using FACE."
2583 (put-text-property from to
'font-lock-face face
))
2585 (defun markdown-unfontify-region-wiki-links (from to
)
2586 "Remove wiki link faces from the region specified by FROM and TO."
2587 (interactive "nfrom: \nnto: ")
2588 (remove-text-properties from to
'(font-lock-face markdown-link-face
))
2589 (remove-text-properties from to
'(font-lock-face markdown-missing-link-face
)))
2591 (defun markdown-fontify-region-wiki-links (from to
)
2592 "Search region given by FROM and TO for wiki links and fontify them.
2593 If a wiki link is found check to see if the backing file exists
2594 and highlight accordingly."
2597 (while (re-search-forward markdown-regex-wiki-link to t
)
2598 (let ((highlight-beginning (match-beginning 0))
2599 (highlight-end (match-end 0))
2601 (markdown-convert-wiki-link-to-filename (match-string 1))))
2602 (if (file-exists-p file-name
)
2603 (markdown-highlight-wiki-link
2604 highlight-beginning highlight-end markdown-link-face
)
2605 (markdown-highlight-wiki-link
2606 highlight-beginning highlight-end markdown-link-face
)
2607 (markdown-highlight-wiki-link
2608 highlight-beginning highlight-end markdown-missing-link-face
))))))
2610 (defun markdown-extend-changed-region (from to
)
2611 "Extend region given by FROM and TO so that we can fontify all links.
2612 The region is extended to the first newline before and the first
2614 ;; start looking for the first new line before 'from
2616 (re-search-backward "\n" nil t
)
2617 (let ((new-from (point-min))
2618 (new-to (point-max)))
2619 (if (not (= (point) from
))
2620 (setq new-from
(point)))
2621 ;; do the same thing for the first new line after 'to
2623 (re-search-forward "\n" nil t
)
2624 (if (not (= (point) to
))
2625 (setq new-to
(point)))
2626 (values new-from new-to
)))
2628 (defun markdown-check-change-for-wiki-link (from to change
)
2629 "Check region between FROM and TO for wiki links and re-fontfy as needed.
2630 Designed to be used with the `after-change-functions' hook.
2631 CHANGE is the number of bytes of pre-change text replaced by the
2633 (interactive "nfrom: \nnto: \nnchange: ")
2634 (let* ((modified (buffer-modified-p))
2635 (buffer-undo-list t
)
2636 (inhibit-read-only t
)
2637 (inhibit-point-motion-hooks t
)
2639 buffer-file-truename
)
2644 ;; Extend the region to fontify so that it starts
2645 ;; and ends at safe places.
2646 (multiple-value-bind (new-from new-to
)
2647 (markdown-extend-changed-region from to
)
2648 ;; Unfontify existing fontification (start from scratch)
2649 (markdown-unfontify-region-wiki-links new-from new-to
)
2650 ;; Now do the fontification.
2651 (markdown-fontify-region-wiki-links new-from new-to
)))))
2654 (set-buffer-modified-p nil
)))))
2656 (defun markdown-fontify-buffer-wiki-links ()
2657 "Refontify all wiki links in the buffer."
2659 (markdown-check-change-for-wiki-link (point-min) (point-max) 0))
2661 ;;; Miscellaneous =============================================================
2663 (defun markdown-line-number-at-pos (&optional pos
)
2664 "Return (narrowed) buffer line number at position POS.
2665 If POS is nil, use current buffer location.
2666 This is an exact copy of `line-number-at-pos' for use in emacs21."
2667 (let ((opoint (or pos
(point))) start
)
2669 (goto-char (point-min))
2670 (setq start
(point))
2673 (1+ (count-lines start
(point))))))
2675 (defun markdown-nobreak-p ()
2676 "Return nil if it is acceptable to break the current line at the point."
2677 ;; inside in square brackets (e.g., link anchor text)
2678 (looking-back "\\[[^]]*"))
2682 ;;; Mode definition ==========================================================
2684 (defun markdown-show-version ()
2685 "Show the version number in the minibuffer."
2687 (message "markdown-mode, version %s" markdown-mode-version
))
2690 (define-derived-mode markdown-mode text-mode
"Markdown"
2691 "Major mode for editing Markdown files."
2692 ;; Natural Markdown tab width
2695 (make-local-variable 'comment-start
)
2696 (setq comment-start
"<!-- ")
2697 (make-local-variable 'comment-end
)
2698 (setq comment-end
" -->")
2699 (make-local-variable 'comment-start-skip
)
2700 (setq comment-start-skip
"<!--[ \t]*")
2701 (make-local-variable 'comment-column
)
2702 (setq comment-column
0)
2704 (set (make-local-variable 'font-lock-defaults
)
2705 '(markdown-mode-font-lock-keywords))
2706 (set (make-local-variable 'font-lock-multiline
) t
)
2707 ;; For imenu support
2708 (setq imenu-create-index-function
'markdown-imenu-create-index
)
2709 ;; For menu support in XEmacs
2710 (easy-menu-add markdown-mode-menu markdown-mode-map
)
2711 ;; Make filling work with lists (unordered, ordered, and definition)
2712 (set (make-local-variable 'paragraph-start
)
2713 "\f\\|[ \t]*$\\|^[ \t]*[*+-] \\|^[ \t]*[0-9]+\\.\\|^[ \t]*: ")
2715 (make-local-variable 'outline-regexp
)
2716 (setq outline-regexp markdown-regex-header
)
2717 (make-local-variable 'outline-level
)
2718 (setq outline-level
'markdown-outline-level
)
2719 ;; Cause use of ellipses for invisible text.
2720 (add-to-invisibility-spec '(outline . t
))
2721 ;; Indentation and filling
2722 (make-local-variable 'fill-nobreak-predicate
)
2723 (add-hook 'fill-nobreak-predicate
'markdown-nobreak-p
)
2724 (setq indent-line-function markdown-indent-function
)
2726 ;; Prepare hooks for XEmacs compatibility
2727 (when (featurep 'xemacs
)
2728 (make-local-hook 'after-change-functions
)
2729 (make-local-hook 'font-lock-extend-region-functions
)
2730 (make-local-hook 'window-configuration-change-hook
))
2732 ;; Multiline font lock
2733 (add-hook 'font-lock-extend-region-functions
2734 'markdown-font-lock-extend-region
)
2736 ;; Anytime text changes make sure it gets fontified correctly
2737 (add-hook 'after-change-functions
'markdown-check-change-for-wiki-link t t
)
2739 ;; If we left the buffer there is a really good chance we were
2740 ;; creating one of the wiki link documents. Make sure we get
2741 ;; refontified when we come back.
2742 (add-hook 'window-configuration-change-hook
2743 'markdown-fontify-buffer-wiki-links t t
)
2745 ;; do the initial link fontification
2746 (markdown-fontify-buffer-wiki-links))
2748 ;;(add-to-list 'auto-mode-alist '("\\.text$" . markdown-mode))
2750 ;;; GitHub Flavored Markdown Mode ============================================
2753 (define-derived-mode gfm-mode markdown-mode
"GFM"
2754 "Major mode for editing GitHub Flavored Markdown files."
2755 (setq markdown-link-space-sub-char
"-")
2757 ;; Use visual-line-mode if available, fall back to longlines-mode:
2758 (if (fboundp 'visual-line-mode
)
2759 (visual-line-mode 1)
2761 ;; do the initial link fontification
2762 (markdown-fontify-buffer-wiki-links))
2765 (provide 'markdown-mode
)
2767 ;;; markdown-mode.el ends here