1 ;;; markdown-mode.el --- Emacs Major mode for Markdown-formatted text files
3 ;; Copyright (C) 2007-2013 Jason R. Blevins <jrblevin@sdf.org>
4 ;; Copyright (C) 2007, 2009 Edward O'Connor <ted@oconnor.cx>
5 ;; Copyright (C) 2007 Conal Elliott <conal@conal.net>
6 ;; Copyright (C) 2008 Greg Bognar <greg_bognar@hms.harvard.edu>
7 ;; Copyright (C) 2008 Dmitry Dzhus <mail@sphinx.net.ru>
8 ;; Copyright (C) 2008 Bryan Kyle <bryan.kyle@gmail.com>
9 ;; Copyright (C) 2008 Ben Voui <intrigeri@boum.org>
10 ;; Copyright (C) 2009 Ankit Solanki <ankit.solanki@gmail.com>
11 ;; Copyright (C) 2009 Hilko Bengen <bengen@debian.org>
12 ;; Copyright (C) 2009 Peter Williams <pezra@barelyenough.org>
13 ;; Copyright (C) 2010 George Ogata <george.ogata@gmail.com>
14 ;; Copyright (C) 2011 Eric Merritt <ericbmerritt@gmail.com>
15 ;; Copyright (C) 2011 Philippe Ivaldi <pivaldi@sfr.fr>
16 ;; Copyright (C) 2011 Jeremiah Dodds <jeremiah.dodds@gmail.com>
17 ;; Copyright (C) 2011 Christopher J. Madsen <cjm@cjmweb.net>
18 ;; Copyright (C) 2011 Shigeru Fukaya <shigeru.fukaya@gmail.com>
19 ;; Copyright (C) 2011 Joost Kremers <joostkremers@fastmail.fm>
20 ;; Copyright (C) 2011-2012 Donald Ephraim Curtis <dcurtis@milkbox.net>
21 ;; Copyright (C) 2012 Akinori Musha <knu@idaemons.org>
22 ;; Copyright (C) 2012 Zhenlei Jia <zhenlei.jia@gmail.com>
23 ;; Copyright (C) 2012 Peter Jones <pjones@pmade.com>
24 ;; Copyright (C) 2013 Matus Goljer <dota.keys@gmail.com>
26 ;; Author: Jason R. Blevins <jrblevin@sdf.org>
27 ;; Maintainer: Jason R. Blevins <jrblevin@sdf.org>
28 ;; Created: May 24, 2007
30 ;; Keywords: Markdown, GitHub Flavored Markdown, itex
31 ;; URL: http://jblevins.org/projects/markdown-mode/
33 ;; This file is not part of GNU Emacs.
35 ;; This program is free software; you can redistribute it and/or modify
36 ;; it under the terms of the GNU General Public License as published by
37 ;; the Free Software Foundation; either version 2, or (at your option)
40 ;; This program is distributed in the hope that it will be useful,
41 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
42 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
43 ;; GNU General Public License for more details.
45 ;; You should have received a copy of the GNU General Public License
46 ;; along with this program; if not, write to the Free Software
47 ;; Foundation, Inc., 51 Franklin Street, Fifth Floor,
48 ;; Boston, MA 02110-1301, USA.
52 ;; markdown-mode is a major mode for editing [Markdown][]-formatted
53 ;; text files in GNU Emacs. markdown-mode is free software, licensed
56 ;; [Markdown]: http://daringfireball.net/projects/markdown/
58 ;; The latest stable version is markdown-mode 1.9, released on January 25, 2013:
60 ;; * [markdown-mode.el][]
61 ;; * [Screenshot][][^theme]
62 ;; * [Release notes][]
64 ;; [markdown-mode.el]: http://jblevins.org/projects/markdown-mode/markdown-mode.el
65 ;; [screenshot]: http://jblevins.org/projects/markdown-mode/screenshots/20110812-001.png
66 ;; [release notes]: http://jblevins.org/projects/markdown-mode/rev-1-9
68 ;; [^theme]: The theme used in the screenshot is
69 ;; [color-theme-twilight](https://github.com/crafterm/twilight-emacs).
71 ;; markdown-mode is also available in several package managers, including:
73 ;; * Debian and Ubuntu Linux: [emacs-goodies-el][]
74 ;; * RedHat and Fedora Linux: [emacs-goodies][]
75 ;; * OpenBSD: [textproc/markdown-mode][]
76 ;; * Arch Linux (AUR): [emacs-markdown-mode-git][]
77 ;; * MacPorts: [markdown-mode.el][macports-package] ([pending][macports-ticket])
78 ;; * FreeBSD: [textproc/markdown-mode.el][freebsd-port]
80 ;; [emacs-goodies-el]: http://packages.debian.org/emacs-goodies-el
81 ;; [emacs-goodies]: https://admin.fedoraproject.org/pkgdb/acls/name/emacs-goodies
82 ;; [textproc/markdown-mode]: http://pkgsrc.se/textproc/markdown-mode
83 ;; [emacs-markdown-mode-git]: http://aur.archlinux.org/packages.php?ID=30389
84 ;; [macports-package]: https://trac.macports.org/browser/trunk/dports/editors/markdown-mode.el/Portfile
85 ;; [macports-ticket]: http://trac.macports.org/ticket/35716
86 ;; [freebsd-port]: http://svnweb.freebsd.org/ports/head/textproc/markdown-mode.el
88 ;; The latest development version can be downloaded directly
89 ;; ([markdown-mode.el][devel.el]) or it can be obtained from the
90 ;; (browsable and clonable) Git repository at
91 ;; <http://jblevins.org/git/markdown-mode.git>. The entire repository,
92 ;; including the full project history, can be cloned via the Git protocol
95 ;; git clone git://jblevins.org/git/markdown-mode.git
97 ;; [devel.el]: http://jblevins.org/git/markdown-mode.git/plain/markdown-mode.el
101 ;; markdown-mode requires easymenu, a standard package since GNU Emacs
102 ;; 19 and XEmacs 19, which provides a uniform interface for creating
103 ;; menus in GNU Emacs and XEmacs.
107 ;; Make sure to place `markdown-mode.el` somewhere in the load-path and add
108 ;; the following lines to your `.emacs` file to associate markdown-mode
109 ;; with `.text` files:
111 ;; (autoload 'markdown-mode "markdown-mode"
112 ;; "Major mode for editing Markdown files" t)
113 ;; (add-to-list 'auto-mode-alist '("\\.text\\'" . markdown-mode))
115 ;; There is no consensus on an official file extension so change `.text` to
116 ;; `.mdwn`, `.md`, `.mdt`, or whatever you call your markdown files.
120 ;; Although no configuration is *necessary* there are a few things
121 ;; that can be customized. The `M-x customize-mode` command
122 ;; provides an interface to all of the possible customizations:
124 ;; * `markdown-command' - the command used to run Markdown (default:
125 ;; `markdown'). This variable may be customized to pass
126 ;; command-line options to your Markdown processor of choice, but
127 ;; this command must accept input from `stdin`. If it does not, a
128 ;; simple wrapper script can be used to write `stdin` to a file
129 ;; and then pass that file to your Markdown interpreter. Ideally,
130 ;; this command will produce an XHTML fragment around which
131 ;; markdown-mode will wrap a header and footer (which can be
132 ;; further customized). However, it attempts to detect whether
133 ;; the command produces standalone XHTML output (via
134 ;; `markdown-xhtml-standalone-regexp'), in which case no header
135 ;; and footer content will be added.
137 ;; * `markdown-command-needs-filename' - set to non-nil if
138 ;; `markdown-command' does not accept input from stdin (default: nil).
139 ;; Instead, it will be passed a filename as the final command-line
140 ;; option. As a result, you will only be able to run Markdown
141 ;; from buffers which are visiting a file.
143 ;; * `markdown-open-command' - the command used for calling a standalone
144 ;; Markdown previewer which is capable of opening Markdown source files
145 ;; directly (default: `nil'). This command will be called
146 ;; with a single argument, the filename of the current buffer.
147 ;; A representative program is the Mac app [Marked][], a
148 ;; live-updating MultiMarkdown previewer which has a command line
149 ;; utility at `/usr/local/bin/mark`.
151 ;; * `markdown-hr-strings' - list of strings to use when inserting
152 ;; horizontal rules, in decreasing order of priority.
154 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
155 ;; underscores for bold instead of two asterisks (default: `nil').
157 ;; * `markdown-italic-underscore' - set to a non-nil value to use
158 ;; underscores for italic instead of asterisks (default: `nil').
160 ;; * `markdown-indent-function' - the function to use for automatic
161 ;; indentation (default: `markdown-indent-line').
163 ;; * `markdown-indent-on-enter' - set to a non-nil value to
164 ;; automatically indent new lines when the enter key is pressed
167 ;; * `markdown-follow-wiki-link-on-enter' - set to a non-nil value
168 ;; to automatically open a linked document in a new buffer if the
169 ;; cursor is an wiki link
172 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
173 ;; treat aliased wiki links like `[[link text|PageName]]`.
174 ;; When set to nil, they will be treated as `[[PageName|link text]]'.
176 ;; * `markdown-uri-types' - a list of protocols for URIs that
177 ;; `markdown-mode' should highlight.
179 ;; * `markdown-enable-math' - syntax highlighting for
180 ;; LaTeX fragments (default: `nil').
182 ;; * `markdown-css-path' - CSS file to link to in XHTML output.
184 ;; * `markdown-content-type' - when set to a nonempty string, an
185 ;; `http-equiv` attribute will be included in the XHTML `<head>`
186 ;; block. If needed, the suggested values are
187 ;; `application/xhtml+xml` or `text/html`.
189 ;; * `markdown-coding-system' - used for specifying the character
190 ;; set identifier in the `http-equiv` attribute (see
191 ;; `markdown-content-type'). When set to `nil',
192 ;; `buffer-file-coding-system' will be used (and falling back to
193 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
194 ;; and `iso-latin-1'.
196 ;; * `markdown-xhtml-header-content' - additional content to include
197 ;; in the XHTML `<head>` block.
199 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
200 ;; indicates whether the output of `markdown-command' is standalone
201 ;; XHTML (default: `^\\(\<\?xml\\|\<!DOCTYPE\\|\<html\\)`). If
202 ;; this is not matched, we assume this output is a fragment and add
203 ;; our own header and footer.
205 ;; * `markdown-link-space-sub-char' - a character to replace spaces
206 ;; when mapping wiki links to filenames (default: `_`).
207 ;; For example, use an underscore for compatibility with the
208 ;; Python Markdown WikiLinks extension or a hyphen for compatibility
209 ;; with Github wiki links.
211 ;; Additionally, the faces used for syntax highlighting can be modified to
212 ;; your liking by issuing `M-x customize-group RET markdown-faces`
213 ;; or by using the "Markdown Faces" link at the bottom of the mode
214 ;; customization screen.
216 ;; [Marked]: https://itunes.apple.com/us/app/marked/id448925439?ls=1&mt=12&partnerId=30&siteID=GpHp3Acs1Yo
220 ;; Keybindings are grouped by prefixes based on their function. For
221 ;; example, commands dealing with headers begin with `C-c C-t`. The
222 ;; primary commands in each group will are described below. You can
223 ;; obtain a list of all keybindings by pressing `C-c C-h`.
225 ;; * Anchors: `C-c C-a`
227 ;; `C-c C-a l` inserts inline links of the form `[text](url)`.
228 ;; `C-c C-a r` inserts reference links of the form `[text][label]`.
229 ;; The label definition will be placed at the end of the current
230 ;; block. `C-c C-a w` acts similarly for wiki links of the form
231 ;; `[[WikiLink]]`. In all cases, if there is an active region, the
232 ;; text in the region is used as the link text.
234 ;; * Commands: `C-c C-c`
236 ;; *Compile:* `C-c C-c m` will run Markdown on the current buffer
237 ;; and show the output in another buffer. *Preview*: `C-c C-c p`
238 ;; runs Markdown on the current buffer and previews, stores the
239 ;; output in a temporary file, and displays the file in a browser.
240 ;; *Export:* `C-c C-c e` will run Markdown on the current buffer
241 ;; and save the result in the file `basename.html`, where
242 ;; `basename` is the name of the Markdown file with the extension
243 ;; removed. *Export and View:* press `C-c C-c v` to export the
244 ;; file and view it in a browser. **For both export commands, the
245 ;; output file will be overwritten without notice.**
246 ;; *Open:* `C-c C-c o` will open the Markdown source file directly
247 ;; using `markdown-open-command'.
251 ;; - `C-c C-c m`: `markdown-command' > `*markdown-output*` buffer.
252 ;; - `C-c C-c p`: `markdown-command' > temporary file > browser.
253 ;; - `C-c C-c e`: `markdown-command' > `basename.html`.
254 ;; - `C-c C-c v`: `markdown-command' > `basename.html` > browser.
255 ;; - `C-c C-c w`: `markdown-command' > kill ring.
256 ;; - `C-c C-c o`: `markdown-open-command'.
258 ;; `C-c C-c c` will check for undefined references. If there are
259 ;; any, a small buffer will open with a list of undefined
260 ;; references and the line numbers on which they appear. In Emacs
261 ;; 22 and greater, selecting a reference from this list and
262 ;; pressing `RET` will insert an empty reference definition at the
263 ;; end of the buffer. Similarly, selecting the line number will
264 ;; jump to the corresponding line.
266 ;; `C-c C-c n` will clean up the numbering of ordered lists.
268 ;; * Images: `C-c C-i`
270 ;; `C-c C-i i` inserts an image, using the active region (if any)
273 ;; * Physical styles: `C-c C-p`
275 ;; These commands all act on text in the active region, if any,
276 ;; and insert empty markup fragments otherwise. `C-c C-p b` makes
277 ;; the selected text bold, `C-c C-p f` formats the region as
278 ;; fixed-width text, and `C-c C-p i` is used for italic text.
280 ;; * Logical styles: `C-c C-s`
282 ;; These commands all act on text in the active region, if any,
283 ;; and insert empty markup fragments otherwise. Logical styles
284 ;; include blockquote (`C-c C-s b`), preformatted (`C-c C-s p`),
285 ;; code (`C-c C-s c`), emphasis (`C-c C-s e`), and strong
288 ;; * Headers: `C-c C-t`
290 ;; All header commands use text in the active region, if any, as
291 ;; the header text. Otherwise, if the current line is not blank,
292 ;; use the text on the current line. Finally, prompt for header
293 ;; text if there is no active region and the current line is
294 ;; blank. To insert an atx or hash style level-n
295 ;; header, press `C-c C-t n` where n is between 1 and 6. For a
296 ;; top-level setext or underline style header press `C-c C-t t`
297 ;; (mnemonic: title) and for a second-level underline-style header
298 ;; press `C-c C-t s` (mnemonic: section).
300 ;; If the point is at a header, these commands will replace the
301 ;; existing markup in order to update the level and/or type of the
302 ;; header. To remove the markup of the header at the point, press
305 ;; * Footnotes: `C-c C-f`
307 ;; To create a new footnote at the point, press `C-c C-f n`.
308 ;; Press `C-c C-f g` with the point at a footnote to jump to the
309 ;; location where the footnote text is defined. Then, press
310 ;; `C-c C-f b` to return to the footnote marker in the main text.
311 ;; When the point is at a footnote marker or in the body of a
312 ;; footnote, press `C-c C-f k` to kill the footnote and add the
313 ;; text to the kill ring.
317 ;; `C-c -` inserts a horizontal rule.
321 ;; Press `C-c C-o` when the point is on an inline or reference
322 ;; link to open the URL in a browser.
324 ;; * Wiki-Link Navigation:
326 ;; Use `M-p` and `M-n` to quickly jump to the previous and next
327 ;; wiki links, respectively.
329 ;; * Outline Navigation:
331 ;; Navigation between headings is possible using `outline-mode'.
332 ;; Use `C-M-n` and `C-M-p` to move between the next and previous
333 ;; visible headings. Similarly, `C-M-f` and `C-M-b` move to the
334 ;; next and previous visible headings at the same level as the one
335 ;; at the point. Finally, `C-M-u` will move up to a lower-level
336 ;; (more inclusive) visible heading.
338 ;; * Movement by Block:
340 ;; markdown-mode supports the usual Emacs paragraph movement with
341 ;; `M-{` and `M-}`. These commands treat list items as
342 ;; paragraphs, so they will stop at each line within a block of
343 ;; list items. Additionally, markdown-mode includes movement
344 ;; commands, `M-[` and `M-]` for jumping to the beginning or end
345 ;; of an entire block of text (with blocks being separated by at
346 ;; least one blank line).
348 ;; * Movement by Defun:
350 ;; The usual Emacs commands can be used to move by defuns
351 ;; (top-level major definitions). In markdown-mode, a defun
352 ;; is a section. As usual, `C-M-a` will move the point to
353 ;; the beginning of the current or preceding defun, `C-M-e`
354 ;; will move to the end of the current or following defun,
355 ;; and `C-M-h` will put the region around the entire defun.
357 ;; Many of the commands described above behave differently depending on
358 ;; whether Transient Mark mode is enabled or not. When it makes sense,
359 ;; if Transient Mark mode is on and a region is active, the command
360 ;; applies to the text in the region (e.g., `C-c C-p b` makes the region
361 ;; bold). For users who prefer to work outside of Transient Mark mode,
362 ;; in Emacs 22 it can be enabled temporarily by pressing `C-SPC C-SPC`.
364 ;; When applicable, commands that specifically act on the region even
365 ;; outside of Transient Mark mode have the same keybinding as the with
366 ;; the exception of an additional `C-` prefix. For example,
367 ;; `markdown-insert-blockquote' is bound to `C-c C-s b` and only acts on
368 ;; the region in Transient Mark mode while `markdown-blockquote-region'
369 ;; is bound to `C-c C-s C-b` and always applies to the region (when
372 ;; markdown-mode attempts to be flexible in how it handles
373 ;; indentation. When you press `TAB` repeatedly, the point will cycle
374 ;; through several possible indentation levels corresponding to things
375 ;; you might have in mind when you press `RET` at the end of a line or
376 ;; `TAB`. For example, you may want to start a new list item,
377 ;; continue a list item with hanging indentation, indent for a nested
378 ;; pre block, and so on.
380 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
381 ;; visibility cycling for atx- or hash-style headers. There are two
382 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
383 ;; the table of contents view (headers only), outline view (top-level
384 ;; headers only), and the full document view. Pressing `TAB` while the
385 ;; point is at a header will cycle through levels of visibility for the
386 ;; subtree: completely folded, visible children, and fully visible.
387 ;; Note that mixing hash and underline style headers will give undesired
392 ;; Besides supporting the basic Markdown syntax, markdown-mode also
393 ;; includes syntax highlighting for `[[Wiki Links]]` by default. Wiki
394 ;; links may be followed automatically by hitting the enter key when
395 ;; your curser is on a wiki link or by hitting `C-c C-w`. The
396 ;; autofollowing on enter key may be controlled with the
397 ;; `markdown-follow-wiki-link-on-enter' customization. Use `M-p` and
398 ;; `M-n` to quickly jump to the previous and next wiki links,
399 ;; respectively. Aliased or piped wiki links of the form
400 ;; `[[link text|PageName]]` are also supported. Since some wikis
401 ;; reverse these components, set `markdown-wiki-link-alias-first'
402 ;; to nil to treat them as `[[PageName|link text]]`.
404 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
405 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
406 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
407 ;; You can do this either by using `M-x customize-group markdown`
408 ;; or by placing the following in your `.emacs` file:
410 ;; (defun markdown-custom ()
411 ;; "markdown-mode-hook"
412 ;; (setq markdown-command "markdown | smartypants"))
413 ;; (add-hook 'markdown-mode-hook '(lambda() (markdown-custom)))
415 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
417 ;; Experimental syntax highlighting for mathematical expressions written
418 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
419 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
420 ;; either via customize or by placing `(setq markdown-enable-itex t)`
421 ;; in `.emacs`, and restarting Emacs.
423 ;; A [GitHub Flavored Markdown](http://github.github.com/github-flavored-markdown/)
424 ;; mode, `gfm-mode', is also available. The GitHub implementation of
425 ;; differs slightly from standard Markdown. Most importantly, newlines are
426 ;; significant and trigger hard line breaks. As such, `gfm-mode' turns off
427 ;; `auto-fill-mode' and turns on `visual-line-mode' (or `longlines-mode' if
428 ;; `visual-line-mode' is not available). Wiki links in this mode will be
429 ;; treated as on GitHub, with hyphens replacing spaces in filenames and
430 ;; where the first letter of the filename capitalized. For example,
431 ;; `[[wiki link]]' will map to a file named `Wiki-link` with the same
432 ;; extension as the current file. GFM code blocks, with optional
433 ;; programming language keywords, will be highlighted. They can be inserted
434 ;; with `C-c C-s l`. If there is an active region, the text in the region
435 ;; will be placed inside the code block. You will be prompted for the name
436 ;; of the language, but may press enter to continue without naming a language.
440 ;; markdown-mode has benefited greatly from the efforts of the
443 ;; * Cyril Brulebois <cyril.brulebois@enst-bretagne.fr> for Debian packaging.
444 ;; * Conal Elliott <conal@conal.net> for a font-lock regexp patch.
445 ;; * Edward O'Connor <hober0@gmail.com> for a font-lock regexp fix and
446 ;; GitHub Flavored Markdown mode (`gfm-mode').
447 ;; * Greg Bognar <greg_bognar@hms.harvard.edu> for menus and running
448 ;; `markdown' with an active region.
449 ;; * Daniel Burrows <dburrows@debian.org> for filing Debian bug #456592.
450 ;; * Peter S. Galbraith <psg@debian.org> for maintaining emacs-goodies-el.
451 ;; * Dmitry Dzhus <mail@sphinx.net.ru> for undefined reference checking.
452 ;; * Carsten Dominik <carsten@orgmode.org> for org-mode, from which the
453 ;; visibility cycling functionality was derived, and for a bug fix
454 ;; related to orgtbl-mode.
455 ;; * Bryan Kyle <bryan.kyle@gmail.com> for indentation code.
456 ;; * Ben Voui <intrigeri@boum.org> for font-lock face customizations.
457 ;; * Ankit Solanki <ankit.solanki@gmail.com> for longlines.el
458 ;; compatibility and custom CSS.
459 ;; * Hilko Bengen <bengen@debian.org> for proper XHTML output.
460 ;; * Jose A. Ortega Ruiz <jao@gnu.org> for Emacs 23 fixes.
461 ;; * Nelson Minar <nelson@santafe.edu> for html-helper-mode, from which
462 ;; comment matching functions were derived.
463 ;; * Alec Resnick <alec@sproutward.org> for bug reports.
464 ;; * Joost Kremers <joostkremers@fastmail.fm> for footnote-handling
465 ;; functions, bug reports regarding indentation, and
466 ;; fixes for byte-compilation warnings.
467 ;; * Peter Williams <pezra@barelyenough.org> for fill-paragraph
469 ;; * George Ogata <george.ogata@gmail.com> for fixing several
470 ;; byte-compilation warnings.
471 ;; * Eric Merritt <ericbmerritt@gmail.com> for wiki link features.
472 ;; * Philippe Ivaldi <pivaldi@sfr.fr> for XHTML preview
473 ;; customizations and XHTML export.
474 ;; * Jeremiah Dodds <jeremiah.dodds@gmail.com> for supporting
475 ;; Markdown processors which do not accept input from stdin.
476 ;; * Werner Dittmann <werner.dittmann@t-online.de> for bug reports
477 ;; regarding the cl dependency and auto-fill-mode and indentation.
478 ;; * Scott Pfister <scott.pfister@gmail.com> for generalizing the space
479 ;; substitution character for mapping wiki links to filenames.
480 ;; * Marcin Kasperski <marcin.kasperski@mekk.waw.pl> for a patch to
481 ;; escape shell commands.
482 ;; * Christopher J. Madsen <cjm@cjmweb.net> for patches to fix a match
483 ;; data bug and to prefer `visual-line-mode' in `gfm-mode'.
484 ;; * Shigeru Fukaya <shigeru.fukaya@gmail.com> for better adherence to
485 ;; Emacs Lisp coding conventions.
486 ;; * Donald Ephraim Curtis <dcurtis@milkbox.net> for fixing the `paragraph-fill'
487 ;; regexp, refactoring the compilation and preview functions,
488 ;; heading font-lock generalizations, list renumbering,
489 ;; and kill ring save.
490 ;; * Kevin Porter <kportertx@gmail.com> for wiki link handling in `gfm-mode'.
491 ;; * Max Penet <max.penet@gmail.com> and Peter Eisentraut <peter_e@gmx.net>
492 ;; for an autoload token for `gfm-mode'.
493 ;; * Ian Yang <me@iany.me> for improving the reference definition regex.
494 ;; * Akinori Musha <knu@idaemons.org> for an imenu index function.
495 ;; * Michael Sperber <sperber@deinprogramm.de> for XEmacs fixes.
496 ;; * Francois Gannaz <francois.gannaz@free.fr> for suggesting charset
497 ;; declaration in XHTML output.
498 ;; * Zhenlei Jia <zhenlei.jia@gmail.com> for smart (dedention)
499 ;; un-indentation function.
500 ;; * Matus Goljer <dota.keys@gmail.com> for improved wiki link following
501 ;; and GFM code block insertion.
502 ;; * Peter Jones <pjones@pmade.com> for link following functions.
503 ;; * Bryan Fink <bryan.fink@gmail.com> for a bug report regarding
504 ;; externally modified files.
505 ;; * Vegard Vesterheim <vegard.vesterheim@uninett.no> for a bug fix
506 ;; related to orgtbl-mode.
507 ;; * Makoto Motohashi <mkt.motohashi@gmail.com> for before- and after-
508 ;; export hooks and unit test improvements.
512 ;; Although markdown-mode is developed and tested primarily using
513 ;; GNU Emacs 24, compatibility with earlier Emacsen is also a
516 ;; If you find any bugs in markdown-mode, please construct a test case
517 ;; or a patch and email me at <jrblevin@sdf.org>.
521 ;; markdown-mode was written and is maintained by Jason Blevins. The
522 ;; first version was released on May 24, 2007.
524 ;; * 2007-05-24: Version 1.1
525 ;; * 2007-05-25: Version 1.2
526 ;; * 2007-06-05: [Version 1.3][]
527 ;; * 2007-06-29: Version 1.4
528 ;; * 2008-05-24: [Version 1.5][]
529 ;; * 2008-06-04: [Version 1.6][]
530 ;; * 2009-10-01: [Version 1.7][]
531 ;; * 2011-08-12: [Version 1.8][]
532 ;; * 2011-08-15: [Version 1.8.1][]
533 ;; * 2013-01-25: [Version 1.9][]
535 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
536 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
537 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
538 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
539 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
540 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
541 ;; [Version 1.9]: http://jblevins.org/projects/markdown-mode/rev-1-9
548 (eval-when-compile (require 'cl
))
551 ;;; Constants =================================================================
553 (defconst markdown-mode-version
"1.9"
554 "Markdown mode version number.")
556 (defconst markdown-output-buffer-name
"*markdown-output*"
557 "Name of temporary buffer for markdown command output.")
560 ;;; Customizable Variables ====================================================
562 (defvar markdown-mode-hook nil
563 "Hook run when entering Markdown mode.")
565 (defvar markdown-before-export-hooks nil
566 "Hook run before output XHTML.
567 This hook is abnormal and registered functions are given an argument that is output filename.")
569 (defvar markdown-after-export-hooks nil
570 "Hook run after output XHTML.
571 This hook is abnormal and registered functions are given an argument that is output filename.")
573 (defgroup markdown nil
574 "Major mode for editing text files in Markdown format."
577 :link
'(url-link "http://jblevins.org/projects/markdown-mode/"))
579 (defcustom markdown-command
"markdown"
580 "Command to run markdown."
584 (defcustom markdown-command-needs-filename nil
585 "Set to non-nil if `markdown-command' does not accept input from stdin.
586 Instead, it will be passed a filename as the final command line
587 option. As a result, you will only be able to run Markdown from
588 buffers which are visiting a file."
592 (defcustom markdown-open-command nil
593 "Command used for opening Markdown files directly.
594 For example, a standalone Markdown previewer. This command will
595 be called with a single argument: the filename of the current
600 (defcustom markdown-hr-strings
603 "* * * * * * * * * * * * * * * * * * * *"
604 "---------------------------------------"
605 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
606 "-------------------------------------------------------------------------------")
607 "Strings to use when inserting horizontal rules.
608 The first string in the list will be the default when inserting a
609 horizontal rule. Strings should be listed in increasing order of
610 prominence for use with promotion and demotion functions."
614 (defcustom markdown-bold-underscore nil
615 "Use two underscores for bold instead of two asterisks."
619 (defcustom markdown-italic-underscore nil
620 "Use underscores for italic instead of asterisks."
624 (defcustom markdown-indent-function
'markdown-indent-line
625 "Function to use to indent."
629 (defcustom markdown-indent-on-enter t
630 "Automatically indent new lines when enter key is pressed."
634 (defcustom markdown-follow-wiki-link-on-enter t
635 "Follow wiki link at point (if any) when the enter key is pressed."
639 (defcustom markdown-wiki-link-alias-first t
640 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
641 Otherwise, they will be treated as [[PageName|alias text]]."
645 (defcustom markdown-uri-types
646 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
647 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
648 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
649 "Link types for syntax highlighting of URIs."
653 (defcustom markdown-enable-math nil
654 "Syntax highlighting for inline LaTeX expressions.
655 This will not take effect until Emacs is restarted."
659 (defcustom markdown-css-path
""
660 "URL of CSS file to link to in the output XHTML."
664 (defcustom markdown-content-type
""
665 "Content type string for the http-equiv header in XHTML output.
666 When set to a non-empty string, insert the http-equiv attribute.
667 Otherwise, this attribute is omitted."
671 (defcustom markdown-coding-system nil
672 "Character set string for the http-equiv header in XHTML output.
673 Defaults to `buffer-file-coding-system' (and falling back to
674 `iso-8859-1' when not available). Common settings are `utf-8'
675 and `iso-latin-1'. Use `list-coding-systems' for more choices."
677 :type
'coding-system
)
679 (defcustom markdown-xhtml-header-content
""
680 "Additional content to include in the XHTML <head> block."
684 (defcustom markdown-xhtml-standalone-regexp
685 "^\\(\<\?xml\\|\<!DOCTYPE\\|\<html\\)"
686 "Regexp indicating whether `markdown-command' output is standalone XHTML."
690 (defcustom markdown-link-space-sub-char
692 "Character to use instead of spaces when mapping wiki links to filenames."
696 (defcustom markdown-footnote-location
'end
697 "Position where new footnotes are inserted in the document."
699 :type
'(choice (const :tag
"At the end of the document" end
)
700 (const :tag
"Immediately after the paragraph" immediately
)
701 (const :tag
"Before next header" header
)))
704 ;;; Font Lock =================================================================
708 (defvar markdown-italic-face
'markdown-italic-face
709 "Face name to use for italic text.")
711 (defvar markdown-bold-face
'markdown-bold-face
712 "Face name to use for bold text.")
714 (defvar markdown-header-delimiter-face
'markdown-header-delimiter-face
715 "Face name to use as a base for header delimiters.")
717 (defvar markdown-header-rule-face
'markdown-header-rule-face
718 "Face name to use as a base for header rules.")
720 (defvar markdown-header-face
'markdown-header-face
721 "Face name to use as a base for headers.")
723 (defvar markdown-header-face-1
'markdown-header-face-1
724 "Face name to use for level-1 headers.")
726 (defvar markdown-header-face-2
'markdown-header-face-2
727 "Face name to use for level-2 headers.")
729 (defvar markdown-header-face-3
'markdown-header-face-3
730 "Face name to use for level-3 headers.")
732 (defvar markdown-header-face-4
'markdown-header-face-4
733 "Face name to use for level-4 headers.")
735 (defvar markdown-header-face-5
'markdown-header-face-5
736 "Face name to use for level-5 headers.")
738 (defvar markdown-header-face-6
'markdown-header-face-6
739 "Face name to use for level-6 headers.")
741 (defvar markdown-inline-code-face
'markdown-inline-code-face
742 "Face name to use for inline code.")
744 (defvar markdown-list-face
'markdown-list-face
745 "Face name to use for list markers.")
747 (defvar markdown-blockquote-face
'markdown-blockquote-face
748 "Face name to use for blockquote.")
750 (defvar markdown-pre-face
'markdown-pre-face
751 "Face name to use for preformatted text.")
753 (defvar markdown-language-keyword-face
'markdown-language-keyword-face
754 "Face name to use for programming language identifiers.")
756 (defvar markdown-link-face
'markdown-link-face
757 "Face name to use for links.")
759 (defvar markdown-missing-link-face
'markdown-missing-link-face
760 "Face name to use for links where the linked file does not exist.")
762 (defvar markdown-reference-face
'markdown-reference-face
763 "Face name to use for reference.")
765 (defvar markdown-footnote-face
'markdown-footnote-face
766 "Face name to use for footnote identifiers.")
768 (defvar markdown-url-face
'markdown-url-face
769 "Face name to use for URLs.")
771 (defvar markdown-link-title-face
'markdown-link-title-face
772 "Face name to use for reference link titles.")
774 (defvar markdown-comment-face
'markdown-comment-face
775 "Face name to use for HTML comments.")
777 (defvar markdown-math-face
'markdown-math-face
778 "Face name to use for LaTeX expressions.")
780 (defgroup markdown-faces nil
781 "Faces used in Markdown Mode"
785 (defface markdown-italic-face
786 '((t (:inherit font-lock-variable-name-face
:slant italic
)))
787 "Face for italic text."
788 :group
'markdown-faces
)
790 (defface markdown-bold-face
791 '((t (:inherit font-lock-variable-name-face
:weight bold
)))
792 "Face for bold text."
793 :group
'markdown-faces
)
795 (defface markdown-header-rule-face
796 '((t (:inherit font-lock-function-name-face
:weight bold
)))
797 "Base face for headers rules."
798 :group
'markdown-faces
)
800 (defface markdown-header-delimiter-face
801 '((t (:inherit font-lock-function-name-face
:weight bold
)))
802 "Base face for headers hash delimiter."
803 :group
'markdown-faces
)
805 (defface markdown-header-face
806 '((t (:inherit font-lock-function-name-face
:weight bold
)))
807 "Base face for headers."
808 :group
'markdown-faces
)
810 (defface markdown-header-face-1
811 '((t (:inherit markdown-header-face
)))
812 "Face for level-1 headers."
813 :group
'markdown-faces
)
815 (defface markdown-header-face-2
816 '((t (:inherit markdown-header-face
)))
817 "Face for level-2 headers."
818 :group
'markdown-faces
)
820 (defface markdown-header-face-3
821 '((t (:inherit markdown-header-face
)))
822 "Face for level-3 headers."
823 :group
'markdown-faces
)
825 (defface markdown-header-face-4
826 '((t (:inherit markdown-header-face
)))
827 "Face for level-4 headers."
828 :group
'markdown-faces
)
830 (defface markdown-header-face-5
831 '((t (:inherit markdown-header-face
)))
832 "Face for level-5 headers."
833 :group
'markdown-faces
)
835 (defface markdown-header-face-6
836 '((t (:inherit markdown-header-face
)))
837 "Face for level-6 headers."
838 :group
'markdown-faces
)
840 (defface markdown-inline-code-face
841 '((t (:inherit font-lock-constant-face
)))
842 "Face for inline code."
843 :group
'markdown-faces
)
845 (defface markdown-list-face
846 '((t (:inherit font-lock-builtin-face
)))
847 "Face for list item markers."
848 :group
'markdown-faces
)
850 (defface markdown-blockquote-face
851 '((t (:inherit font-lock-doc-face
)))
852 "Face for blockquote sections."
853 :group
'markdown-faces
)
855 (defface markdown-pre-face
856 '((t (:inherit font-lock-constant-face
)))
857 "Face for preformatted text."
858 :group
'markdown-faces
)
860 (defface markdown-language-keyword-face
861 '((t (:inherit font-lock-type-face
)))
862 "Face for programming language identifiers."
863 :group
'markdown-faces
)
865 (defface markdown-link-face
866 '((t (:inherit font-lock-keyword-face
)))
868 :group
'markdown-faces
)
870 (defface markdown-missing-link-face
871 '((t (:inherit font-lock-warning-face
)))
872 "Face for missing links."
873 :group
'markdown-faces
)
875 (defface markdown-reference-face
876 '((t (:inherit font-lock-type-face
)))
877 "Face for link references."
878 :group
'markdown-faces
)
880 (defface markdown-footnote-face
881 '((t (:inherit font-lock-keyword-face
)))
882 "Face for footnote markers."
883 :group
'markdown-faces
)
885 (defface markdown-url-face
886 '((t (:inherit font-lock-string-face
)))
888 :group
'markdown-faces
)
890 (defface markdown-link-title-face
891 '((t (:inherit font-lock-comment-face
)))
892 "Face for reference link titles."
893 :group
'markdown-faces
)
895 (defface markdown-comment-face
896 '((t (:inherit font-lock-comment-face
)))
897 "Face for HTML comments."
898 :group
'markdown-faces
)
900 (defface markdown-math-face
901 '((t (:inherit font-lock-string-face
)))
902 "Face for LaTeX expressions."
903 :group
'markdown-faces
)
905 (defconst markdown-regex-link-inline
906 "\\(!?\\[[^]]*?\\]\\)\\(([^\\)]*)\\)"
907 "Regular expression for a [text](file) or an image link ![text](file).")
909 (defconst markdown-regex-link-reference
910 "\\(!?\\[[^]]+?\\]\\)[ ]?\\(\\[[^]]*?\\]\\)"
911 "Regular expression for a reference link [text][id].")
913 (defconst markdown-regex-reference-definition
914 "^ \\{0,3\\}\\(\\[[^\n]+?\\]\\):\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
915 "Regular expression for a link definition [id]: ...")
917 (defconst markdown-regex-footnote
919 "Regular expression for a footnote marker [^fn].")
921 (defconst markdown-regex-header
922 "^\\(?:\\(.+\\)\n\\(=+\\)\\|\\(.+\\)\n\\(-+\\)\\|\\(#+\\)\\s-*\\(.*?\\)\\s-*?\\(#*\\)\\)$"
923 "Regexp identifying Markdown headers.")
925 (defconst markdown-regex-header-1-atx
926 "^\\(# \\)\\(.*?\\)\\($\\| #+$\\)"
927 "Regular expression for level 1 atx-style (hash mark) headers.")
929 (defconst markdown-regex-header-2-atx
930 "^\\(## \\)\\(.*?\\)\\($\\| #+$\\)"
931 "Regular expression for level 2 atx-style (hash mark) headers.")
933 (defconst markdown-regex-header-3-atx
934 "^\\(### \\)\\(.*?\\)\\($\\| #+$\\)"
935 "Regular expression for level 3 atx-style (hash mark) headers.")
937 (defconst markdown-regex-header-4-atx
938 "^\\(#### \\)\\(.*?\\)\\($\\| #+$\\)"
939 "Regular expression for level 4 atx-style (hash mark) headers.")
941 (defconst markdown-regex-header-5-atx
942 "^\\(##### \\)\\(.*?\\)\\($\\| #+$\\)"
943 "Regular expression for level 5 atx-style (hash mark) headers.")
945 (defconst markdown-regex-header-6-atx
946 "^\\(###### \\)\\(.*?\\)\\($\\| #+$\\)"
947 "Regular expression for level 6 atx-style (hash mark) headers.")
949 (defconst markdown-regex-header-1-setext
950 "^\\(.*\\)\n\\(=+\\)$"
951 "Regular expression for level 1 setext-style (underline) headers.")
953 (defconst markdown-regex-header-2-setext
954 "^\\(.*\\)\n\\(-+\\)$"
955 "Regular expression for level 2 setext-style (underline) headers.")
957 (defconst markdown-regex-header-setext
958 "^\\(.+\\)\n\\(\\(?:=\\|-\\)+\\)$"
959 "Regular expression for generic setext-style (underline) headers.")
961 (defconst markdown-regex-header-atx
962 "^\\(#+\\)[ \t]*\\(.*?\\)[ \t]*\\(#*\\)$"
963 "Regular expression for generic atx-style (hash mark) headers.")
965 (defconst markdown-regex-hr
966 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
967 "Regular expression for matching Markdown horizontal rules.")
969 (defconst markdown-regex-code
970 "\\(\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(.\\|\n[^\n]\\)*?[^`]\\)\\3\\)\\([^`]\\|\\'\\)"
971 "Regular expression for matching inline code fragments.
973 The first group ensures that the leading backquote character
974 is not escaped. The group \\(.\\|\n[^\n]\\) matches any
975 character, including newlines, but not two newlines in a row.
976 The final group requires that the character following the code
977 fragment is not a backquote.")
979 (defconst markdown-regex-pre
981 "Regular expression for matching preformatted text sections.")
983 (defconst markdown-regex-list
984 "^\\([ \t]*\\)\\([0-9]+\\.\\|[\\*\\+-]\\)\\([ \t]+\\)"
985 "Regular expression for matching list items.")
987 (defconst markdown-regex-bold
988 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
989 "Regular expression for matching bold text.
990 Group 1 matches the character before the opening asterisk or
991 underscore, if any, ensuring that it is not a backslash escape.
992 Group 2 matches the entire expression, including delimiters.
993 Groups 3 and 5 matches the opening and closing delimiters.
994 Group 4 matches the text inside the delimiters.")
996 (defconst markdown-regex-italic
997 "\\(^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
998 "Regular expression for matching italic text.
999 Group 1 matches the character before the opening asterisk or
1000 underscore, if any, ensuring that it is not a backslash escape.
1001 Group 2 matches the entire expression, including delimiters.
1002 Groups 3 and 5 matches the opening and closing delimiters.
1003 Group 4 matches the text inside the delimiters.")
1005 (defconst markdown-regex-blockquote
1007 "Regular expression for matching blockquote lines.")
1009 (defconst markdown-regex-line-break
1011 "Regular expression for matching line breaks.")
1013 (defconst markdown-regex-wiki-link
1014 "\\(?:^\\|[^\\]\\)\\(\\[\\[\\([^]|]+\\)\\(|\\([^]]+\\)\\)?\\]\\]\\)"
1015 "Regular expression for matching wiki links.
1016 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1017 wiki links of the form [[PageName|link text]]. In this regular
1018 expression, #1 matches the page name and #3 matches the link
1021 (defconst markdown-regex-uri
1023 "\\(" (mapconcat 'identity markdown-uri-types
"\\|")
1024 "\\):[^]\t\n\r<>,;() ]+")
1025 "Regular expression for matching inline URIs.")
1027 (defconst markdown-regex-angle-uri
1030 (mapconcat 'identity markdown-uri-types
"\\|")
1031 "\\):[^]\t\n\r<>,;()]+\\)\\(>\\)")
1032 "Regular expression for matching inline URIs in angle brackets.")
1034 (defconst markdown-regex-email
1035 "<\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+>"
1036 "Regular expression for matching inline email addresses.")
1038 (defconst markdown-regex-block-separator
1039 "\\(\\`\\|\\(\n[ \t]*\n\\)[^\n \t]\\)"
1040 "Regular expression for matching block boundaries.")
1042 (defconst markdown-regex-latex-expression
1043 "\\(^\\|[^\\]\\)\\(\\$\\($\\([^\\$]\\|\\\\.\\)*\\$\\|\\([^\\$]\\|\\\\.\\)*\\)\\$\\)"
1044 "Regular expression for itex $..$ or $$..$$ math mode expressions.")
1046 (defconst markdown-regex-latex-display
1047 "^\\\\\\[\\(.\\|\n\\)*?\\\\\\]$"
1048 "Regular expression for itex \[..\] display mode expressions.")
1050 (defvar markdown-mode-font-lock-keywords-basic
1052 (cons 'markdown-match-pre-blocks
'((0 markdown-pre-face
)))
1053 (cons 'markdown-match-fenced-code-blocks
'((0 markdown-pre-face
)))
1054 (cons 'markdown-match-gfm-code-blocks
'((1 markdown-pre-face
)
1055 (2 markdown-language-keyword-face nil t
)
1056 (3 markdown-pre-face
)
1057 (4 markdown-pre-face
)))
1058 (cons markdown-regex-blockquote
'markdown-blockquote-face
)
1059 (cons markdown-regex-header-1-setext
'((1 markdown-header-face-1
)
1060 (2 markdown-header-rule-face
)))
1061 (cons markdown-regex-header-2-setext
'((1 markdown-header-face-2
)
1062 (2 markdown-header-rule-face
)))
1063 (cons markdown-regex-header-1-atx
'((1 markdown-header-delimiter-face
)
1064 (2 markdown-header-face-1
)
1065 (3 markdown-header-delimiter-face
)))
1066 (cons markdown-regex-header-2-atx
'((1 markdown-header-delimiter-face
)
1067 (2 markdown-header-face-2
)
1068 (3 markdown-header-delimiter-face
)))
1069 (cons markdown-regex-header-3-atx
'((1 markdown-header-delimiter-face
)
1070 (2 markdown-header-face-3
)
1071 (3 markdown-header-delimiter-face
)))
1072 (cons markdown-regex-header-4-atx
'((1 markdown-header-delimiter-face
)
1073 (2 markdown-header-face-4
)
1074 (3 markdown-header-delimiter-face
)))
1075 (cons markdown-regex-header-5-atx
'((1 markdown-header-delimiter-face
)
1076 (2 markdown-header-face-5
)
1077 (3 markdown-header-delimiter-face
)))
1078 (cons markdown-regex-header-6-atx
'((1 markdown-header-delimiter-face
)
1079 (2 markdown-header-face-6
)
1080 (3 markdown-header-delimiter-face
)))
1081 (cons markdown-regex-hr
'markdown-header-face
)
1082 (cons 'markdown-match-comments
'((0 markdown-comment-face t t
)))
1083 (cons markdown-regex-code
'(2 markdown-inline-code-face
))
1084 (cons markdown-regex-angle-uri
'markdown-link-face
)
1085 (cons markdown-regex-uri
'markdown-link-face
)
1086 (cons markdown-regex-email
'markdown-link-face
)
1087 (cons markdown-regex-list
'(2 markdown-list-face
))
1088 (cons markdown-regex-link-inline
'((1 markdown-link-face t
)
1089 (2 markdown-url-face t
)))
1090 (cons markdown-regex-link-reference
'((1 markdown-link-face t
)
1091 (2 markdown-reference-face t
)))
1092 (cons markdown-regex-reference-definition
'((1 markdown-reference-face t
)
1093 (2 markdown-url-face t
)
1094 (3 markdown-link-title-face t
)))
1095 (cons markdown-regex-footnote
'markdown-footnote-face
)
1096 (cons markdown-regex-bold
'(2 markdown-bold-face
))
1097 (cons markdown-regex-italic
'(2 markdown-italic-face
))
1099 "Syntax highlighting for Markdown files.")
1101 (defconst markdown-mode-font-lock-keywords-latex
1103 ;; Math mode $..$ or $$..$$
1104 (cons markdown-regex-latex-expression
'(2 markdown-math-face
))
1105 ;; Display mode equations with brackets: \[ \]
1106 (cons markdown-regex-latex-display
'markdown-math-face
)
1107 ;; Equation reference (eq:foo)
1108 (cons "(eq:\\w+)" 'markdown-reference-face
)
1109 ;; Equation reference \eqref{foo}
1110 (cons "\\\\eqref{\\w+}" 'markdown-reference-face
))
1111 "Syntax highlighting for LaTeX fragments.")
1113 (defvar markdown-mode-font-lock-keywords
1115 (if markdown-enable-math
1116 markdown-mode-font-lock-keywords-latex
)
1117 markdown-mode-font-lock-keywords-basic
)
1118 "Default highlighting expressions for Markdown mode.")
1121 (defvar markdown-footnote-counter
0
1122 "Counter for footnote numbers.")
1123 (make-variable-buffer-local 'markdown-footnote-counter
)
1125 (defconst markdown-footnote-chars
1127 "Regular expression maching any character that is allowed in a footnote identifier.")
1130 ;;; Compatibility =============================================================
1132 (defun markdown-replace-regexp-in-string (regexp rep string
)
1133 "Replace all matches for REGEXP with REP in STRING.
1134 This is a compatibility wrapper to provide `replace-regexp-in-string'
1136 (if (featurep 'xemacs
)
1137 (replace-in-string string regexp rep
)
1138 (replace-regexp-in-string regexp rep string
)))
1140 ;; `markdown-use-region-p' is a compatibility function which checks
1141 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
1144 ;; Emacs 23 and newer
1145 ((fboundp 'use-region-p
)
1146 (defalias 'markdown-use-region-p
'use-region-p
))
1148 ((and (boundp 'transient-mark-mode
) (boundp 'mark-active
))
1149 (defun markdown-use-region-p ()
1150 "Compatibility wrapper to provide `use-region-p'."
1151 (and transient-mark-mode mark-active
)))
1153 ((fboundp 'region-active-p
)
1154 (defalias 'markdown-use-region-p
'region-active-p
))))
1157 ;;; Markdown Parsing Functions ================================================
1159 (defun markdown-cur-line-blank-p ()
1160 "Return t if the current line is blank and nil otherwise."
1163 (re-search-forward "^\\s *$" (point-at-eol) t
)))
1165 (defun markdown-prev-line-blank-p ()
1166 "Return t if the previous line is blank and nil otherwise.
1167 If we are at the first line, then consider the previous line to be blank."
1169 (if (= (point-at-bol) (point-min))
1172 (markdown-cur-line-blank-p))))
1174 (defun markdown-next-line-blank-p ()
1175 "Return t if the next line is blank and nil otherwise.
1176 If we are at the last line, then consider the next line to be blank."
1178 (if (= (point-at-bol) (point-max))
1181 (markdown-cur-line-blank-p))))
1183 (defun markdown-prev-line-indent-p ()
1184 "Return t if the previous line is indented and nil otherwise."
1187 (goto-char (point-at-bol))
1188 (if (re-search-forward "^\\s " (point-at-eol) t
) t
)))
1190 (defun markdown-cur-line-indent ()
1191 "Return the number of leading whitespace characters in the current line."
1194 (goto-char (point-at-bol))
1195 (re-search-forward "^[ \t]+" (point-at-eol) t
)
1198 (defun markdown-prev-line-indent ()
1199 "Return the number of leading whitespace characters in the previous line."
1202 (markdown-cur-line-indent)))
1204 (defun markdown-next-line-indent ()
1205 "Return the number of leading whitespace characters in the next line."
1208 (markdown-cur-line-indent)))
1210 (defun markdown-cur-non-list-indent ()
1211 "Return beginning position of list item text (not including the list marker).
1212 Return nil if the current line is not the beginning of a list item."
1216 (when (re-search-forward markdown-regex-list
(point-at-eol) t
)
1217 (current-column)))))
1219 (defun markdown-prev-non-list-indent ()
1220 "Return position of the first non-list-marker on the previous line."
1223 (markdown-cur-non-list-indent)))
1225 (defun markdown-new-baseline-p ()
1226 "Determine if the current line begins a new baseline level."
1230 (or (looking-at markdown-regex-header
)
1231 (looking-at markdown-regex-hr
)
1232 (and (null (markdown-cur-non-list-indent))
1233 (= (markdown-cur-line-indent) 0)
1234 (markdown-prev-line-blank-p))))))
1236 (defun markdown-search-backward-baseline ()
1237 "Search backward baseline point with no indentation and not a list item."
1240 (while (not (or stop
(bobp)))
1241 (re-search-backward markdown-regex-block-separator nil t
)
1243 (goto-char (match-end 2))
1245 ((markdown-new-baseline-p)
1247 ((looking-at markdown-regex-list
)
1249 (t (setq stop t
)))))))
1251 (defun markdown-update-list-levels (marker indent levels
)
1252 "Update list levels given list MARKER, block INDENT, and current LEVELS.
1253 Here, MARKER is a string representing the type of list, INDENT is an integer
1254 giving the indentation, in spaces, of the current block, and LEVELS is a
1255 list of the indentation levels of parent list items. When LEVELS is nil,
1256 it means we are at baseline (not inside of a nested list)."
1258 ;; New list item at baseline.
1259 ((and marker
(null levels
))
1260 (setq levels
(list indent
)))
1261 ;; List item with greater indentation (four or more spaces).
1262 ;; Increase list level.
1263 ((and marker
(>= indent
(+ (car levels
) 4)))
1264 (setq levels
(cons indent levels
)))
1265 ;; List item with greater or equal indentation (less than four spaces).
1266 ;; Do not increase list level.
1267 ((and marker
(>= indent
(car levels
)))
1269 ;; Lesser indentation level.
1270 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
1271 ;; indentation could move back more than one list level). Note
1272 ;; that this block need not be the beginning of list item.
1273 ((< indent
(car levels
))
1274 (while (and (> (length levels
) 1)
1275 (< indent
(+ (car (cdr levels
)) 4)))
1276 (setq levels
(cdr levels
)))
1278 ;; Otherwise, do nothing.
1281 (defun markdown-calculate-list-levels ()
1282 "Calculate list levels at point.
1283 Return a list of the form (n1 n2 n3 ...) where n1 is the
1284 indentation of the deepest nested list item in the branch of
1285 the list at the point, n2 is the indentation of the parent
1286 list item, and so on. The depth of the list item is therefore
1287 the length of the returned list. If the point is not at or
1288 immediately after a list item, return nil."
1290 (let ((first (point)) levels indent pre-regexp
)
1291 ;; Find a baseline point with zero list indentation
1292 (markdown-search-backward-baseline)
1293 ;; Search for all list items between baseline and LOC
1294 (while (re-search-forward markdown-regex-list first t
)
1295 (setq pre-regexp
(format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels
))))
1298 ;; Make sure this is not a header or hr
1299 ((markdown-new-baseline-p) (setq levels nil
))
1300 ;; Make sure this is not a line from a pre block
1301 ((looking-at pre-regexp
))
1302 ;; If not, then update levels
1304 (setq indent
(markdown-cur-line-indent))
1305 (setq levels
(markdown-update-list-levels (match-string 2)
1310 (defun markdown-prev-list-item (level)
1311 "Search backward from point for a list item with indentation LEVEL.
1312 Set point to the beginning of the item, and return point, or nil
1314 (let (bounds indent prev
)
1317 (setq indent
(markdown-cur-line-indent))
1320 ;; Stop at beginning of buffer
1321 ((bobp) (setq prev nil
))
1322 ;; Continue if current line is blank
1323 ((markdown-cur-line-blank-p) t
)
1325 ((and (looking-at markdown-regex-list
)
1326 (setq bounds
(markdown-cur-list-item-bounds)))
1328 ;; Continue at item with greater indentation
1329 ((> (nth 3 bounds
) level
) t
)
1330 ;; Stop and return point at item of equal indentation
1331 ((= (nth 3 bounds
) level
)
1334 ;; Stop and return nil at item with lesser indentation
1335 ((< (nth 3 bounds
) level
)
1338 ;; Continue while indentation is the same or greater
1339 ((>= indent level
) t
)
1340 ;; Stop if current indentation is less than list item
1341 ;; and the next is blank
1342 ((and (< indent level
)
1343 (markdown-next-line-blank-p))
1346 ((looking-at markdown-regex-header
) (setq prev nil
))
1347 ;; Stop at a horizontal rule
1348 ((looking-at markdown-regex-hr
) (setq prev nil
))
1349 ;; Otherwise, continue.
1352 (setq indent
(markdown-cur-line-indent)))
1355 (defun markdown-next-list-item (level)
1356 "Search forward from point for the next list item with indentation LEVEL.
1357 Set point to the beginning of the item, and return point, or nil
1359 (let (bounds indent prev next
)
1362 (setq indent
(markdown-cur-line-indent))
1365 ;; Stop at end of the buffer.
1366 ((eobp) (setq prev nil
))
1367 ;; Continue if the current line is blank
1368 ((markdown-cur-line-blank-p) t
)
1370 ((and (looking-at markdown-regex-list
)
1371 (setq bounds
(markdown-cur-list-item-bounds)))
1373 ;; Continue at item with greater indentation
1374 ((> (nth 3 bounds
) level
) t
)
1375 ;; Stop and return point at item of equal indentation
1376 ((= (nth 3 bounds
) level
)
1379 ;; Stop and return nil at item with lesser indentation
1380 ((< (nth 3 bounds
) level
)
1383 ;; Continue while indentation is the same or greater
1384 ((>= indent level
) t
)
1385 ;; Stop if current indentation is less than list item
1386 ;; and the previous line was blank.
1387 ((and (< indent level
)
1388 (markdown-prev-line-blank-p))
1391 ((looking-at markdown-regex-header
) (setq next nil
))
1392 ;; Stop at a horizontal rule
1393 ((looking-at markdown-regex-hr
) (setq next nil
))
1394 ;; Otherwise, continue.
1397 (setq indent
(markdown-cur-line-indent)))
1400 (defun markdown-cur-list-item-end (level)
1401 "Move to the end of the current list item with nonlist indentation LEVEL.
1402 If the point is not in a list item, do nothing."
1405 (setq indent
(markdown-cur-line-indent))
1408 ;; Stop at end of the buffer.
1410 ;; Continue if the current line is blank
1411 ((markdown-cur-line-blank-p) t
)
1412 ;; Continue while indentation is the same or greater
1413 ((>= indent level
) t
)
1414 ;; Stop if current indentation is less than list item
1415 ;; and the previous line was blank.
1416 ((and (< indent level
)
1417 (markdown-prev-line-blank-p))
1419 ;; Stop at a new list item of the same or lesser indentation
1420 ((looking-at markdown-regex-list
) nil
)
1422 ((looking-at markdown-regex-header
) nil
)
1423 ;; Stop at a horizontal rule
1424 ((looking-at markdown-regex-hr
) nil
)
1425 ;; Otherwise, continue.
1428 (setq indent
(markdown-cur-line-indent)))
1429 ;; Don't skip over whitespace for empty list items (marker and
1430 ;; whitespace only), just move to end of whitespace.
1431 (if (looking-back (concat markdown-regex-list
"\\s-*"))
1432 (goto-char (match-end 3))
1433 (skip-syntax-backward "-"))))
1435 (defun markdown-cur-list-item-bounds ()
1436 "Return bounds and indentation of the current list item.
1437 Return a list of the form (begin end indent nonlist-indent).
1438 If the point is not inside a list item, return nil.
1439 Leave match data intact for `markdown-regex-list'."
1440 (let (cur prev-begin prev-end indent nonlist-indent
)
1441 ;; Store current location
1443 ;; Verify that cur is between beginning and end of item
1446 (when (re-search-backward markdown-regex-list nil t
)
1447 (setq prev-begin
(match-beginning 0))
1448 (setq indent
(length (match-string 1)))
1449 (setq nonlist-indent
(length (match-string 0)))
1451 (markdown-cur-list-item-end nonlist-indent
)
1452 (setq prev-end
(point)))
1453 (when (and (>= cur prev-begin
)
1456 (list prev-begin prev-end indent nonlist-indent
))))))
1458 (defun markdown-bounds-of-thing-at-point (thing)
1459 "Calls `bounds-of-thing-at-point' for THING with slight modifications.
1460 Does not include trailing newlines when THING is 'line. Handles the
1461 end of buffer case by setting both endpoints equal to the value of
1462 `point-max', since an empty region will trigger empty markup insertion.
1463 Return bounds of form (beg . end) if THING is found, or nil otherwise."
1464 (let* ((bounds (bounds-of-thing-at-point thing
))
1468 (when (eq thing
'line
)
1469 (cond ((and (eobp) (markdown-cur-line-blank-p))
1471 ((char-equal (char-before b
) ?\^J
)
1476 ;;; Markdown Font Lock Matching Functions =====================================
1478 (defun markdown-match-comments (last)
1479 "Match HTML comments from the point to LAST."
1480 (cond ((search-forward "<!--" last t
)
1482 (let ((beg (point)))
1483 (cond ((search-forward-regexp "--[ \t]*>" last t
)
1484 (set-match-data (list beg
(point)))
1489 (defun markdown-match-pre-blocks (last)
1490 "Match Markdown pre blocks from point to LAST."
1491 (let ((levels (markdown-calculate-list-levels))
1492 indent pre-regexp end-regexp begin end stop
)
1493 (while (and (< (point) last
) (not end
))
1494 ;; Search for a region with sufficient indentation
1497 (setq indent
(1+ (length levels
))))
1498 (setq pre-regexp
(format "^\\( \\|\t\\)\\{%d\\}" indent
))
1499 (setq end-regexp
(format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent
)))
1502 ;; If not at the beginning of a line, move forward
1503 ((not (bolp)) (forward-line))
1504 ;; Move past blank lines
1505 ((markdown-cur-line-blank-p) (forward-line))
1506 ;; At headers and horizontal rules, reset levels
1507 ((markdown-new-baseline-p) (forward-line) (setq levels nil
))
1508 ;; If the current line has sufficient indentation, mark out pre block
1509 ((looking-at pre-regexp
)
1510 (setq begin
(match-beginning 0))
1511 (while (and (or (looking-at pre-regexp
) (markdown-cur-line-blank-p))
1515 ;; If current line has a list marker, update levels, move to end of block
1516 ((looking-at markdown-regex-list
)
1517 (setq levels
(markdown-update-list-levels
1518 (match-string 2) (markdown-cur-line-indent) levels
))
1519 (markdown-end-of-block-element))
1520 ;; If this is the end of the indentation level, adjust levels accordingly.
1521 ;; Only match end of indentation level if levels is not the empty list.
1522 ((and (car levels
) (looking-at end-regexp
))
1523 (setq levels
(markdown-update-list-levels
1524 nil
(markdown-cur-line-indent) levels
))
1525 (markdown-end-of-block-element))
1526 (t (markdown-end-of-block-element))))
1528 (if (not (and begin end
))
1529 ;; Return nil if no pre block was found
1531 ;; Set match data and return t upon success
1532 (set-match-data (list begin end
))
1535 (defun markdown-match-fenced-code-blocks (last)
1536 "Match fenced code blocks from the point to LAST."
1537 (cond ((search-forward-regexp "^\\([~]\\{3,\\}\\)" last t
)
1539 (let ((beg (point)))
1541 (cond ((search-forward-regexp
1542 (concat "^" (match-string 1) "~*") last t
)
1543 (set-match-data (list beg
(point)))
1548 (defun markdown-match-gfm-code-blocks (last)
1549 "Match GFM quoted code blocks from point to LAST."
1550 (let (open lang body close all
)
1551 (cond ((and (eq major-mode
'gfm-mode
)
1552 (search-forward-regexp "^\\(```\\)\\(\\w+\\)?$" last t
))
1554 (setq open
(list (match-beginning 1) (match-end 1))
1555 lang
(list (match-beginning 2) (match-end 2)))
1557 (setq body
(list (point)))
1558 (cond ((search-forward-regexp "^```$" last t
)
1559 (setq body
(reverse (cons (1- (match-beginning 0)) body
))
1560 close
(list (match-beginning 0) (match-end 0))
1561 all
(list (car open
) (match-end 0)))
1562 (set-match-data (append all open lang body close
))
1567 (defun markdown-font-lock-extend-region ()
1568 "Extend the search region to include an entire block of text.
1569 This helps improve font locking for block constructs such as pre blocks."
1570 ;; Avoid compiler warnings about these global variables from font-lock.el.
1571 ;; See the documentation for variable `font-lock-extend-region-functions'.
1572 (eval-when-compile (defvar font-lock-beg
) (defvar font-lock-end
))
1574 (goto-char font-lock-beg
)
1575 (let ((found (or (re-search-backward "\n\n" nil t
) (point-min))))
1576 (goto-char font-lock-end
)
1577 (when (re-search-forward "\n\n" nil t
)
1579 (setq font-lock-end
(point)))
1580 (setq font-lock-beg found
))))
1583 ;;; Syntax Table ==============================================================
1585 (defvar markdown-mode-syntax-table
1586 (let ((tab (make-syntax-table text-mode-syntax-table
)))
1587 (modify-syntax-entry ?
\" "." tab
)
1589 "Syntax table for `markdown-mode'.")
1592 ;;; Element Insertion =========================================================
1594 (defun markdown-ensure-blank-line-before ()
1595 "If previous line is not already blank, insert a blank line before point."
1596 (unless (bolp) (insert "\n"))
1597 (unless (or (bobp) (looking-back "\n\\s-*\n")) (insert "\n")))
1599 (defun markdown-ensure-blank-line-after ()
1600 "If following line is not already blank, insert a blank line after point.
1601 Return the point where it was originally."
1603 (unless (eolp) (insert "\n"))
1604 (unless (or (eobp) (looking-at "\n\\s-*\n")) (insert "\n"))))
1606 (defun markdown-wrap-or-insert (s1 s2
&optional thing beg end
)
1607 "Insert the strings S1 and S2, wrapping around region or THING.
1608 If a region is specified by the optional BEG and END arguments,
1609 wrap the strings S1 and S2 around that region.
1610 If there is an active region, wrap the strings S1 and S2 around
1611 the region. If there is not an active region but the point is at
1612 THING, wrap that thing (which defaults to word). Otherwise, just
1613 insert S1 and S2 and place the cursor in between. Return the
1614 bounds of the entire wrapped string, or nil if nothing was wrapped
1615 and S1 and S2 were only inserted."
1616 (let (a b bounds new-point
)
1622 new-point
(+ (point) (length s1
))))
1624 ((markdown-use-region-p)
1625 (setq a
(region-beginning)
1627 new-point
(+ (point) (length s1
))))
1628 ;; Thing (word) at point
1629 ((setq bounds
(markdown-bounds-of-thing-at-point (or thing
'word
)))
1630 (setq a
(car bounds
)
1632 new-point
(+ (point) (length s1
))))
1633 ;; No active region and no word
1641 (when new-point
(goto-char new-point
))
1644 (setq b
(+ b
(length s1
) (length s2
)))
1647 (defun markdown-point-after-unwrap (cur prefix suffix
)
1648 "Return desired position of point after an unwrapping operation.
1649 Two cons cells must be provided. PREFIX gives the bounds of the
1650 prefix string and SUFFIX gives the bounds of the suffix string."
1651 (cond ((< cur
(cdr prefix
)) (car prefix
))
1652 ((< cur
(car suffix
)) (- cur
(- (cdr prefix
) (car prefix
))))
1653 ((<= cur
(cdr suffix
))
1654 (- cur
(+ (- (cdr prefix
) (car prefix
))
1655 (- cur
(car suffix
)))))
1658 (defun markdown-unwrap-thing-at-point (regexp all text
)
1659 "Remove prefix and suffix of thing at point and reposition the point.
1660 When the thing at point matches REGEXP, replace the subexpression
1661 ALL with the string in subexpression TEXT. Reposition the point
1662 in an appropriate location accounting for the removal of prefix
1663 and suffix strings. Return new bounds of string from group TEXT.
1664 When REGEXP is nil, assumes match data is already set."
1665 (when (or (null regexp
)
1666 (thing-at-point-looking-at regexp
))
1668 (prefix (cons (match-beginning all
) (match-beginning text
)))
1669 (suffix (cons (match-end text
) (match-end all
)))
1670 (bounds (cons (match-beginning text
) (match-end text
))))
1671 ;; Replace the thing at point
1672 (replace-match (match-string text
) t t nil all
)
1673 ;; Reposition the point
1674 (goto-char (markdown-point-after-unwrap cur prefix suffix
))
1676 (setq bounds
(cons (car prefix
)
1677 (- (cdr bounds
) (- (cdr prefix
) (car prefix
))))))))
1679 (defun markdown-unwrap-things-in-region (beg end regexp all text
)
1680 "Remove prefix and suffix of all things in region.
1681 When a thing in the region matches REGEXP, replace the
1682 subexpression ALL with the string in subexpression TEXT.
1683 Return a cons cell containing updated bounds for the region."
1686 (let ((removed 0) len-all len-text
)
1687 (while (re-search-forward regexp end t
)
1688 (setq len-all
(length (match-string-no-properties all
)))
1689 (setq len-text
(length (match-string-no-properties text
)))
1690 (setq removed
(+ removed
(- len-all len-text
)))
1691 (replace-match (match-string text
) t t nil all
))
1692 (cons beg
(- end removed
)))))
1694 (defun markdown-insert-hr (arg)
1695 "Insert or replace a horizonal rule.
1696 By default, use the first element of `markdown-hr-strings'. When
1697 prefixed with C-u, use the last element of `markdown-hr-strings'
1698 instead. When prefixed with an integer from 1 to the length of
1699 `markdown-hr-strings', use the element in that position instead."
1701 (when (thing-at-point-looking-at markdown-regex-hr
)
1702 (delete-region (match-beginning 0) (match-end 0)))
1703 (markdown-ensure-blank-line-before)
1704 (cond ((equal arg
'(4))
1705 (insert (car (reverse markdown-hr-strings
))))
1706 ((and (integerp arg
) (> arg
0)
1707 (<= arg
(length markdown-hr-strings
)))
1708 (insert (nth (1- arg
) markdown-hr-strings
)))
1710 (insert (car markdown-hr-strings
))))
1711 (markdown-ensure-blank-line-after))
1713 (defun markdown-insert-bold ()
1714 "Insert markup to make a region or word bold.
1715 If there is an active region, make the region bold. If the point
1716 is at a non-bold word, make the word bold. If the point is at a
1717 bold word or phrase, remove the bold markup. Otherwise, simply
1718 insert bold delimiters and place the cursor in between them."
1720 (let ((delim (if markdown-bold-underscore
"__" "**")))
1721 (if (markdown-use-region-p)
1723 (let ((bounds (markdown-unwrap-things-in-region
1724 (region-beginning) (region-end)
1725 markdown-regex-bold
2 4)))
1726 (markdown-wrap-or-insert delim delim nil
(car bounds
) (cdr bounds
)))
1727 ;; Bold markup removal, bold word at point, or empty markup insertion
1728 (if (thing-at-point-looking-at markdown-regex-bold
)
1729 (markdown-unwrap-thing-at-point nil
2 4)
1730 (markdown-wrap-or-insert delim delim
'word nil nil
)))))
1732 (defun markdown-insert-italic ()
1733 "Insert markup to make a region or word italic.
1734 If there is an active region, make the region italic. If the point
1735 is at a non-italic word, make the word italic. If the point is at an
1736 italic word or phrase, remove the italic markup. Otherwise, simply
1737 insert italic delimiters and place the cursor in between them."
1739 (let ((delim (if markdown-italic-underscore
"_" "*")))
1740 (if (markdown-use-region-p)
1742 (let ((bounds (markdown-unwrap-things-in-region
1743 (region-beginning) (region-end)
1744 markdown-regex-italic
2 4)))
1745 (markdown-wrap-or-insert delim delim nil
(car bounds
) (cdr bounds
)))
1746 ;; Italic markup removal, italic word at point, or empty markup insertion
1747 (if (thing-at-point-looking-at markdown-regex-italic
)
1748 (markdown-unwrap-thing-at-point nil
2 4)
1749 (markdown-wrap-or-insert delim delim
'word nil nil
)))))
1751 (defun markdown-insert-code ()
1752 "Insert markup to make a region or word an inline code fragment.
1753 If there is an active region, make the region an inline code
1754 fragment. If the point is at a word, make the word an inline
1755 code fragment. Otherwise, simply insert code delimiters and
1756 place the cursor in between them."
1758 (if (markdown-use-region-p)
1760 (let ((bounds (markdown-unwrap-things-in-region
1761 (region-beginning) (region-end)
1762 markdown-regex-code
2 4)))
1763 (markdown-wrap-or-insert "`" "`" nil
(car bounds
) (cdr bounds
)))
1764 ;; Code markup removal, code markup for word, or empty markup insertion
1765 (if (thing-at-point-looking-at markdown-regex-code
)
1766 (markdown-unwrap-thing-at-point nil
2 4)
1767 (markdown-wrap-or-insert "`" "`" 'word nil nil
))))
1769 (defun markdown-insert-link ()
1770 "Insert an inline link, using region or word as link text if possible.
1771 If there is an active region, use the region as the link text. If the
1772 point is at a word, use the word as the link text. In these cases, the
1773 point will be left at the position for inserting a URL. If there is no
1774 active region and the point is not at word, simply insert link markup and
1775 place the point in the position to enter link text."
1777 (let ((bounds (markdown-wrap-or-insert "[" "]()")))
1779 (goto-char (- (cdr bounds
) 1)))))
1781 (defun markdown-insert-reference-link-dwim ()
1782 "Insert a reference link of the form [text][label] at point.
1783 If Transient Mark mode is on and a region is active, the region
1784 is used as the link text. Otherwise, the link text will be read
1785 from the minibuffer. The link URL, label, and title will be read
1786 from the minibuffer. The link label definition is placed at the
1787 end of the current paragraph."
1789 (if (markdown-use-region-p)
1790 (call-interactively 'markdown-insert-reference-link-region
)
1791 (call-interactively 'markdown-insert-reference-link
)))
1793 (defun markdown-insert-reference-link-region (url label title
)
1794 "Insert a reference link at point using the region as the link text.
1795 The link will point to URL, will be referenced as LABEL, and will have the
1796 optional title text given by TITLE."
1797 (interactive "sLink URL: \nsLink Label (optional): \nsLink Title (optional): ")
1798 (let ((text (buffer-substring (region-beginning) (region-end))))
1799 (delete-region (region-beginning) (region-end))
1800 (markdown-insert-reference-link text url label title
)))
1802 (defun markdown-insert-reference-link (text url label title
)
1803 "Insert a reference link at point.
1804 The link TEXT will point to the given URL and may be referenced using
1805 LABEL. The link TITLE is optional and will be used to populate the
1806 title attribute when converted to XHTML."
1807 (interactive "sLink Text: \nsLink URL: \nsLink Label (optional): \nsLink Title (optional): ")
1809 (insert (concat "[" text
"][" label
"]"))
1813 (if (> (length label
) 0)
1816 (insert (concat "]: " url
))
1817 (unless (> (length url
) 0)
1819 (when (> (length title
) 0)
1820 (insert (concat " \"" title
"\"")))
1822 (unless (looking-at "\n")
1826 (defun markdown-insert-wiki-link ()
1827 "Insert a wiki link of the form [[WikiLink]].
1828 If Transient Mark mode is on and a region is active, it is used
1831 (markdown-wrap-or-insert "[[" "]]")
1834 (defun markdown-insert-image ()
1835 "Insert inline image markup using region or word as alt text if possible.
1836 If there is an active region, use the region as the alt text. If the
1837 point is at a word, use the word as the alt text. In these cases, the
1838 point will be left at the position for inserting a URL. If there is no
1839 active region and the point is not at word, simply insert image markup and
1840 place the point in the position to enter alt text."
1842 (let ((bounds (markdown-wrap-or-insert "![" "]()")))
1844 (goto-char (- (cdr bounds
) 1)))))
1846 (defun markdown-remove-header ()
1847 "Remove header markup if point is at a header.
1848 Return bounds of remaining header text if a header was removed
1851 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx
0 2)
1852 (markdown-unwrap-thing-at-point markdown-regex-header-setext
0 1)))
1854 (defun markdown-insert-header (&optional level text setext
)
1855 "Insert or replace header markup.
1856 The level of the header is specified by LEVEL and header text is
1857 given by TEXT. LEVEL must be an integer from 1 and 6, and the
1859 When TEXT is nil, the header text is obtained as follows.
1860 If there is an active region, it is used as the header text.
1861 Otherwise, the current line will be used as the header text.
1862 If there is not an active region and the point is at a header,
1863 remove the header markup and replace with level N header.
1864 Otherwise, insert empty header markup and place the cursor in
1866 The style of the header will be atx (hash marks) unless
1867 SETEXT is non-nil, in which case a setext-style (underlined)
1868 header will be inserted."
1869 (interactive "p\nsHeader text: ")
1870 (setq level
(min (max (or level
1) 1) (if setext
2 6)))
1871 ;; Determine header text if not given
1873 (if (markdown-use-region-p)
1876 (setq text
(buffer-substring (region-beginning) (region-end)))
1877 (delete-region (region-beginning) (region-end)))
1879 (markdown-remove-header)
1880 (setq text
(buffer-substring (line-beginning-position) (line-end-position)))
1881 (delete-region (line-beginning-position) (line-end-position))
1882 (when (and setext
(string-match "^[ \t]*$" text
))
1883 (setq text
(read-string "Header text: "))))
1884 (setq text
(markdown-compress-whitespace-string text
)))
1885 ;; Insertion with given text
1886 (markdown-ensure-blank-line-before)
1891 (dotimes (n (length text
))
1892 (insert (if (= level
2) "-" "="))))
1894 (dotimes (count level
) (insert "#"))
1895 (insert " " text
" ")
1896 (dotimes (count level
) (insert "#")))
1897 (markdown-ensure-blank-line-after)
1898 ;; Leave point at end of text
1900 (backward-char (1+ (length text
)))
1901 (backward-char (1+ level
))))
1903 (defun markdown-insert-header-atx-1 ()
1904 "Insert a first level atx-style (hash mark) header.
1905 See `markdown-insert-header'."
1907 (markdown-insert-header 1 nil nil
))
1909 (defun markdown-insert-header-atx-2 ()
1910 "Insert a level two atx-style (hash mark) header.
1911 See `markdown-insert-header'."
1913 (markdown-insert-header 2 nil nil
))
1915 (defun markdown-insert-header-atx-3 ()
1916 "Insert a level three atx-style (hash mark) header.
1917 See `markdown-insert-header'."
1919 (markdown-insert-header 3 nil nil
))
1921 (defun markdown-insert-header-atx-4 ()
1922 "Insert a level four atx-style (hash mark) header.
1923 See `markdown-insert-header'."
1925 (markdown-insert-header 4 nil nil
))
1927 (defun markdown-insert-header-atx-5 ()
1928 "Insert a level five atx-style (hash mark) header.
1929 See `markdown-insert-header'."
1931 (markdown-insert-header 5 nil nil
))
1933 (defun markdown-insert-header-atx-6 ()
1934 "Insert a sixth level atx-style (hash mark) header.
1935 See `markdown-insert-header'."
1937 (markdown-insert-header 6 nil nil
))
1939 (defun markdown-insert-header-setext-1 ()
1940 "Insert a setext-style (underlined) first-level header.
1941 See `markdown-insert-header'."
1943 (markdown-insert-header 1 nil t
))
1945 (defun markdown-insert-header-setext-2 ()
1946 "Insert a setext-style (underlined) second-level header.
1947 See `markdown-insert-header'."
1949 (markdown-insert-header 2 nil t
))
1951 (defun markdown-insert-blockquote ()
1952 "Start a blockquote section (or blockquote the region).
1953 If Transient Mark mode is on and a region is active, it is used as
1954 the blockquote text."
1956 (if (markdown-use-region-p)
1957 (markdown-blockquote-region (region-beginning) (region-end))
1960 (defun markdown-block-region (beg end prefix
)
1961 "Format the region using a block prefix.
1962 Arguments BEG and END specify the beginning and end of the
1963 region. The characters PREFIX will appear at the beginning
1966 ;; Ensure that there is a leading blank line
1968 (when (and (>= (point) (+ (point-min) 2))
1969 (not (looking-back "\n\n" 2)))
1972 (setq end
(1+ end
)))
1973 ;; Move back before any blank lines at the end
1975 (while (and (looking-back "\n" 1)
1976 (not (equal (point) (point-min))))
1978 (setq end
(1- end
)))
1979 ;; Ensure that there is a trailing blank line
1981 (if (not (or (looking-at "\n\n")
1982 (and (equal (1+ end
) (point-max)) (looking-at "\n"))))
1987 (while (< (point-at-bol) end
)
1989 (setq end
(+ (length prefix
) end
))
1992 (defun markdown-blockquote-region (beg end
)
1993 "Blockquote the region.
1994 Arguments BEG and END specify the beginning and end of the region."
1996 (markdown-block-region beg end
"> "))
1998 (defun markdown-pre-indentation (loc)
1999 "Return string containing necessary whitespace for a pre block at LOC."
2002 (let* ((list-level (length (markdown-calculate-list-levels)))
2004 (dotimes (count (1+ list-level
) indent
)
2005 (setq indent
(concat indent
" "))))))
2007 (defun markdown-insert-pre ()
2008 "Start a preformatted section (or apply to the region).
2009 If Transient Mark mode is on and a region is active, it is marked
2010 as preformatted text."
2012 (if (markdown-use-region-p)
2013 (markdown-pre-region (region-beginning) (region-end))
2014 (markdown-ensure-blank-line-before)
2015 (insert (markdown-pre-indentation (point)))
2016 (markdown-ensure-blank-line-after)))
2018 (defun markdown-pre-region (beg end
)
2019 "Format the region as preformatted text.
2020 Arguments BEG and END specify the beginning and end of the region."
2022 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg
)))))
2023 (markdown-block-region beg end indent
)))
2025 (defun markdown-insert-gfm-code-block (&optional lang
)
2026 "Insert GFM code block for language LANG.
2027 If LANG is nil, the language will be queried from user. If a
2028 region is active, wrap this region with the markup instead. If
2029 the region boundaries are not on empty lines, these are added
2030 automatically in order to have the correct markup."
2031 (interactive "sProgramming language: ")
2032 (if (markdown-use-region-p)
2033 (let ((b (region-beginning)) (e (region-end)))
2035 ;; if we're on a blank line, insert the quotes here, otherwise
2036 ;; add a new line first
2037 (unless (looking-at "\n")
2042 (goto-char (+ e
3 (length lang
)))
2043 ;; if we're on a blank line, don't newline, otherwise the ```
2044 ;; should go on its own line
2045 (unless (looking-back "\n")
2054 ;;; Footnotes ======================================================================
2056 (defun markdown-footnote-counter-inc ()
2057 "Increment `markdown-footnote-counter' and return the new value."
2058 (when (= markdown-footnote-counter
0) ; hasn't been updated in this buffer yet.
2060 (goto-char (point-min))
2061 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars
"*?\\)\\]:")
2063 (let ((fn (string-to-number (match-string 1))))
2064 (when (> fn markdown-footnote-counter
)
2065 (setq markdown-footnote-counter fn
))))))
2066 (incf markdown-footnote-counter
))
2068 (defun markdown-footnote-new ()
2069 "Insert footnote with a new number and move point to footnote definition."
2071 (let ((fn (markdown-footnote-counter-inc)))
2072 (insert (format "[^%d]" fn
))
2073 (markdown-footnote-text-find-new-location)
2074 (insert (format "[^%d]: " fn
))))
2076 (defun markdown-footnote-text-find-new-location ()
2077 "Position the cursor at the proper location for a new footnote text."
2079 ((eq markdown-footnote-location
'end
) (goto-char (point-max)))
2080 ((eq markdown-footnote-location
'immediately
) (forward-paragraph))
2081 ((eq markdown-footnote-location
'header
)
2082 ;; search for a header. if none is found, go to the end of the document.
2086 (unless (re-search-forward markdown-regex-header nil t
)
2088 (backward-paragraph)
2090 (not (looking-at markdown-regex-header
)))))))
2092 ;; make sure we're on an empty line:
2093 (unless (markdown-cur-line-blank-p)
2095 ;; and make sure the previous line is empty:
2096 (unless (markdown-prev-line-blank-p)
2098 ;; then make sure there's an empty line following the footnote:
2099 (unless (markdown-next-line-blank-p)
2103 (defun markdown-footnote-kill ()
2104 "Kill the footnote at point.
2105 The footnote text is killed (and added to the kill ring), the
2106 footnote marker is deleted. Point has to be either at the
2107 footnote marker or in the footnote text."
2110 (when (markdown-footnote-text-positions) ; if we're in a footnote text
2111 (markdown-footnote-return) ; we first move to the marker
2112 (setq return-pos
'text
)) ; and remember our return position
2113 (let ((marker (markdown-footnote-delete-marker)))
2115 (error "Not at a footnote"))
2116 (let ((text-pos (markdown-footnote-find-text (car marker
))))
2118 (error "No text for footnote `%s'" (car marker
)))
2119 (goto-char text-pos
)
2120 (let ((pos (markdown-footnote-kill-text)))
2122 (if (and pos
(eq return-pos
'text
))
2125 (goto-char return-pos
)))
2127 (defun markdown-footnote-delete-marker ()
2128 "Delete a footnote marker at point.
2129 Returns a list (ID START) containing the footnote ID and the
2130 start position of the marker before deletion. If no footnote
2131 marker was deleted, this function returns NIL."
2132 (let ((marker (markdown-footnote-marker-positions)))
2134 (delete-region (second marker
) (third marker
))
2137 (defun markdown-footnote-kill-text ()
2138 "Kill footnote text at point.
2139 Returns the start position of the footnote text before deletion,
2140 or NIL if point was not inside a footnote text.
2142 The killed text is placed in the kill ring (without the footnote
2144 (let ((fn (markdown-footnote-text-positions)))
2146 (let ((text (delete-and-extract-region (second fn
) (third fn
))))
2147 (string-match (concat "\\[\\" (first fn
) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text
)
2148 (kill-new (match-string 1 text
))
2151 (defun markdown-footnote-goto-text ()
2152 "Jump to the text of the footnote at point."
2154 (let ((fn (car (markdown-footnote-marker-positions))))
2156 (error "Not at a footnote marker"))
2157 (let ((new-pos (markdown-footnote-find-text fn
)))
2159 (error "No definition found for footnote `%s'" fn
))
2160 (goto-char new-pos
))))
2162 (defun markdown-footnote-return ()
2163 "Return from a footnote to its footnote number in the main text."
2165 (let ((fn (save-excursion
2166 (car (markdown-footnote-text-positions)))))
2168 (error "Not in a footnote"))
2169 (let ((new-pos (markdown-footnote-find-marker fn
)))
2171 (error "Footnote marker `%s' not found" fn
))
2172 (goto-char new-pos
))))
2174 (defun markdown-footnote-find-marker (id)
2175 "Find the location of the footnote marker with ID.
2176 The actual buffer position returned is the position directly
2177 following the marker's closing bracket. If no marker is found,
2180 (goto-char (point-min))
2181 (when (re-search-forward (concat "\\[" id
"\\]\\([^:]\\|\\'\\)") nil t
)
2182 (skip-chars-backward "^]")
2185 (defun markdown-footnote-find-text (id)
2186 "Find the location of the text of footnote ID.
2187 The actual buffer position returned is the position of the first
2188 character of the text, after the footnote's identifier. If no
2189 footnote text is found, NIL is returned."
2191 (goto-char (point-min))
2192 (when (re-search-forward (concat "^\\[" id
"\\]:") nil t
)
2193 (skip-chars-forward "[:space:]")
2196 (defun markdown-footnote-marker-positions ()
2197 "Return the position and ID of the footnote marker point is on.
2198 The return value is a list (ID START END). If point is not on a
2199 footnote, NIL is returned."
2200 ;; first make sure we're at a footnote marker
2201 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars
"*\\]?") (point-at-bol))
2202 (looking-at (concat "\\[?\\^" markdown-footnote-chars
"*?\\]")))
2204 ;; move point between [ and ^:
2205 (if (looking-at "\\[")
2207 (skip-chars-backward "^["))
2208 (looking-at (concat "\\(\\^" markdown-footnote-chars
"*?\\)\\]"))
2209 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
2211 (defun markdown-footnote-text-positions ()
2212 "Return the start and end positions of the footnote text point is in.
2213 The exact return value is a list of three elements: (ID START END).
2214 The start position is the position of the opening bracket
2215 of the footnote id. The end position is directly after the
2216 newline that ends the footnote. If point is not in a footnote,
2217 NIL is returned instead."
2220 (backward-paragraph)
2221 ;; if we're in a multiparagraph footnote, we need to back up further
2222 (while (>= (markdown-next-line-indent) 4)
2223 (backward-paragraph))
2225 (if (looking-at (concat "^\\[\\(\\^" markdown-footnote-chars
"*?\\)\\]:"))
2226 (list (match-string 1) (point))))))
2230 (>= (markdown-next-line-indent) 4)))
2231 (append fn
(list (point)))))))
2234 ;;; Indentation ====================================================================
2236 (defun markdown-indent-find-next-position (cur-pos positions
)
2237 "Return the position after the index of CUR-POS in POSITIONS.
2238 Positions are calculated by `markdown-calc-indents'."
2239 (while (and positions
2240 (not (equal cur-pos
(car positions
))))
2241 (setq positions
(cdr positions
)))
2242 (or (cadr positions
) 0))
2244 (defun markdown-indent-line ()
2245 "Indent the current line using some heuristics.
2246 If the _previous_ command was either `markdown-enter-key' or
2247 `markdown-cycle', then we should cycle to the next
2248 reasonable indentation position. Otherwise, we could have been
2249 called directly by `markdown-enter-key', by an initial call of
2250 `markdown-cycle', or indirectly by `auto-fill-mode'. In
2251 these cases, indent to the default position.
2252 Positions are calculated by `markdown-calc-indents'."
2254 (let ((positions (markdown-calc-indents))
2255 (cur-pos (current-column)))
2256 (if (not (equal this-command
'markdown-cycle
))
2257 (indent-line-to (car positions
))
2258 (setq positions
(sort (delete-dups positions
) '<))
2260 (markdown-indent-find-next-position cur-pos positions
)))))
2262 (defun markdown-calc-indents ()
2263 "Return a list of indentation columns to cycle through.
2264 The first element in the returned list should be considered the
2265 default indentation level. This function does not worry about
2266 duplicate positions, which are handled up by calling functions."
2267 (let (pos prev-line-pos positions
)
2269 ;; Indentation of previous line
2270 (setq prev-line-pos
(markdown-prev-line-indent))
2271 (setq positions
(cons prev-line-pos positions
))
2273 ;; Indentation of previous non-list-marker text
2274 (when (setq pos
(markdown-prev-non-list-indent))
2275 (setq positions
(cons pos positions
)))
2277 ;; Indentation required for a pre block in current context
2278 (setq pos
(length (markdown-pre-indentation (point))))
2279 (setq positions
(cons pos positions
))
2281 ;; Indentation of the previous line + tab-width
2283 (setq positions
(cons (+ prev-line-pos tab-width
) positions
))
2284 (setq positions
(cons tab-width positions
)))
2286 ;; Indentation of the previous line - tab-width
2287 (if (and prev-line-pos
(> prev-line-pos tab-width
))
2288 (setq positions
(cons (- prev-line-pos tab-width
) positions
)))
2290 ;; Indentation of all preceeding list markers (when in a list)
2291 (when (setq pos
(markdown-calculate-list-levels))
2292 (setq positions
(append pos positions
)))
2295 (setq positions
(cons 0 positions
))
2297 ;; Return reversed list
2298 (reverse positions
)))
2300 (defun markdown-do-normal-return ()
2301 "Insert a newline and optionally indent the next line."
2303 (if markdown-indent-on-enter
2304 (funcall indent-line-function
)))
2306 (defun markdown-enter-key ()
2307 "Handle RET according to context.
2308 If there is a wiki link at the point, follow it unless
2309 `markdown-follow-wiki-link-on-enter' is nil. Otherwise, process
2310 it in the usual way."
2312 (if (and markdown-follow-wiki-link-on-enter
(markdown-wiki-link-p))
2313 (markdown-follow-wiki-link-at-point)
2314 (markdown-do-normal-return)))
2316 (defun markdown-dedent-or-delete (arg)
2317 "Handle BACKSPACE by cycling through indentation points.
2318 When BACKSPACE is pressed, if there is only whitespace
2319 before the current point, then dedent the line one level.
2320 Otherwise, do normal delete by repeating
2321 `backward-delete-char-untabify' ARG times."
2323 (let ((cur-pos (current-column))
2324 (start-of-indention (save-excursion
2325 (back-to-indentation)
2327 (if (and (> cur-pos
0) (= cur-pos start-of-indention
))
2329 (dolist (i (markdown-calc-indents))
2331 (setq result
(max result i
))))
2332 (indent-line-to result
))
2333 (backward-delete-char-untabify arg
))))
2336 ;;; Markup Completion =========================================================
2338 (defconst markdown-complete-alist
2339 '((markdown-regex-header-atx . markdown-complete-atx
)
2340 (markdown-regex-header-setext . markdown-complete-setext
)
2341 (markdown-regex-hr . markdown-complete-hr
))
2342 "Association list of form (regexp . function) for markup completion.")
2344 (defun markdown-incomplete-atx-p ()
2345 "Return t if ATX header markup is incomplete and nil otherwise.
2346 Assumes match data is available for `markdown-regex-header-atx'.
2347 Checks that the number of trailing hash marks equals the number of leading
2348 hash marks, that there is only a single space before and after the text,
2349 and that there is no extraneous whitespace in the text."
2351 (or (not (= (length (match-string 1)) (length (match-string 3))))
2352 (not (= (match-beginning 2) (1+ (match-end 1))))
2353 (not (= (match-beginning 3) (1+ (match-end 2))))
2354 (string-match "[ \t\n]\\{2\\}" (match-string 2)))))
2356 (defun markdown-complete-atx ()
2357 "Complete and normalize ATX headers.
2358 Add or remove hash marks to the end of the header to match the
2359 beginning. Ensure that there is only a single space between hash
2360 marks and header text. Removes extraneous whitespace from header text.
2361 Assumes match data is available for `markdown-regex-header-atx'."
2362 (when (markdown-incomplete-atx-p)
2363 (let* ((new-marker (make-marker))
2364 (new-marker (set-marker new-marker
(match-end 2))))
2365 ;; Hash marks and spacing at end
2366 (goto-char (match-end 2))
2367 (delete-region (match-end 2) (match-end 3))
2368 (insert " " (match-string 1))
2369 ;; Remove extraneous whitespace from title
2370 (replace-match (markdown-compress-whitespace-string (match-string 2))
2372 ;; Spacing at beginning
2373 (goto-char (match-end 1))
2374 (delete-region (match-end 1) (match-beginning 2))
2376 ;; Leave point at end of text
2377 (goto-char new-marker
))))
2379 (defun markdown-incomplete-setext-p ()
2380 "Return t if setext header markup is incomplete and nil otherwise.
2381 Assumes match data is available for `markdown-regex-header-setext'.
2382 Checks that length of underline matches text and that there is no
2383 extraneous whitespace in the text."
2385 (or (not (= (length (match-string 1)) (length (match-string 2))))
2386 (string-match "[ \t\n]\\{2\\}" (match-string 1)))))
2388 (defun markdown-complete-setext ()
2389 "Complete and normalize setext headers.
2390 Add or remove underline characters to match length of header
2391 text. Removes extraneous whitespace from header text. Assumes
2392 match data is available for `markdown-regex-header-setext'."
2393 (when (markdown-incomplete-setext-p)
2394 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
2395 (char (char-after (match-beginning 2)))
2396 (level (if (char-equal char ?-
) 2 1)))
2397 (goto-char (match-beginning 0))
2398 (delete-region (match-beginning 0) (match-end 0))
2399 (markdown-insert-header level text t
))))
2401 (defun markdown-incomplete-hr-p ()
2402 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
2403 Assumes match data is available for `markdown-regex-hr'."
2404 (not (member (match-string 0) markdown-hr-strings
)))
2406 (defun markdown-complete-hr ()
2407 "Complete horizontal rules.
2408 If horizontal rule string is a member of `markdown-hr-strings',
2409 do nothing. Otherwise, replace with the car of
2410 `markdown-hr-strings'.
2411 Assumes match data is available for `markdown-regex-hr'."
2412 (replace-match (car markdown-hr-strings
)))
2414 (defun markdown-complete ()
2415 "Complete markup of object near point or in region when active.
2416 Handle all objects in `markdown-complete-alist', in order.
2417 See `markdown-complete-at-point' and `markdown-complete-region'."
2419 (if (markdown-use-region-p)
2420 (markdown-complete-region (region-beginning) (region-end))
2421 (markdown-complete-at-point)))
2423 (defun markdown-complete-at-point ()
2424 "Complete markup of object near point.
2425 Handle all objects in `markdown-complete-alist', in
2428 (loop for
(regexp . function
) in markdown-complete-alist
2429 until
(thing-at-point-looking-at (eval regexp
))
2430 finally
(funcall function
)))
2432 (defun markdown-complete-region (beg end
)
2433 "Complete markup of object near point.
2434 Handle all objects in `markdown-complete-alist', in
2437 (let* ((end-marker (make-marker))
2438 (end-marker (set-marker end-marker end
)))
2439 (loop for
(regexp . function
) in markdown-complete-alist
2442 (while (re-search-forward (eval regexp
) end-marker t
)
2443 (funcall function
))))))
2445 (defun markdown-complete-buffer ()
2446 "Complete markup for all objects in the current buffer."
2448 (markdown-complete-region (point-min) (point-max)))
2451 ;;; Markup Cycling ============================================================
2453 (defun markdown-cycle-atx (arg &optional remove
)
2454 "Cycle ATX header markup.
2455 Promote header (decrease level) when ARG is 1 and demote
2456 header (increase level) if arg is -1. When REMOVE is non-nil,
2457 remove the header when the level reaches zero and stop cycling
2458 when it reaches six. Otherwise, perform a proper cycling through
2459 levels one through six. Assumes match data is available for
2460 `markdown-regex-header-atx'."
2461 (let* ((old-level (length (match-string 1)))
2462 (new-level (+ old-level arg
))
2463 (text (match-string 2)))
2465 (setq new-level
(% new-level
6))
2466 (setq new-level
(cond ((= new-level
0) 6)
2467 ((< new-level
0) (+ new-level
6))
2471 (markdown-unwrap-thing-at-point nil
0 2))
2473 (goto-char (match-beginning 0))
2474 (delete-region (match-beginning 0) (match-end 0))
2475 (markdown-insert-header new-level text nil
)))))
2477 (defun markdown-cycle-setext (arg &optional remove
)
2478 "Cycle setext header markup.
2479 Promote header (increase level) when ARG is 1 and demote
2480 header (decrease level or remove) if arg is -1. When demoting a
2481 level-two setext header, replace with a level-three atx header.
2482 When REMOVE is non-nil, remove the header when the level reaches
2483 zero. Otherwise, cycle back to a level six atx header. Assumes
2484 match data is available for `markdown-regex-header-setext'."
2485 (let* ((char (char-after (match-beginning 2)))
2486 (old-level (if (char-equal char ?
=) 1 2))
2487 (new-level (+ old-level arg
))
2488 (text (match-string 1)))
2489 (when (and (not remove
) (= new-level
0))
2493 (markdown-unwrap-thing-at-point nil
0 1))
2495 (markdown-insert-header new-level nil t
))
2497 (markdown-insert-header new-level nil nil
)))))
2499 (defun markdown-cycle-hr (arg &optional remove
)
2500 "Cycle string used for horizontal rule from `markdown-hr-strings'.
2501 When ARG is 1, cycle forward (promote), and when ARG is -1, cycle
2502 backwards (demote). When REMOVE is non-nil, remove the hr instead
2503 of cycling when the end of the list is reached.
2504 Assumes match data is available for `markdown-regex-hr'."
2505 (let* ((strings (if (= arg
1)
2506 (reverse markdown-hr-strings
)
2507 markdown-hr-strings
))
2508 (tail (member (match-string 0) strings
))
2509 (new (or (car (cdr tail
))
2515 (replace-match new
)))
2517 (defun markdown-cycle-bold ()
2518 "Cycle bold markup between underscores and asterisks.
2519 Assumes match data is available for `markdown-regex-bold'."
2521 (let* ((old-delim (match-string 3))
2522 (new-delim (if (string-equal old-delim
"**") "__" "**")))
2523 (replace-match new-delim t t nil
3)
2524 (replace-match new-delim t t nil
5))))
2526 (defun markdown-cycle-italic ()
2527 "Cycle italic markup between underscores and asterisks.
2528 Assumes match data is available for `markdown-regex-italic'."
2530 (let* ((old-delim (match-string 3))
2531 (new-delim (if (string-equal old-delim
"*") "_" "*")))
2532 (replace-match new-delim t t nil
3)
2533 (replace-match new-delim t t nil
5))))
2536 ;;; Keymap ====================================================================
2538 (defvar markdown-mode-map
2539 (let ((map (make-keymap)))
2540 ;; Element insertion
2541 (define-key map
"\C-c\C-al" 'markdown-insert-link
)
2542 (define-key map
"\C-c\C-ar" 'markdown-insert-reference-link-dwim
)
2543 (define-key map
"\C-c\C-aw" 'markdown-insert-wiki-link
)
2544 (define-key map
"\C-c\C-ii" 'markdown-insert-image
)
2545 (define-key map
"\C-c\C-t0" 'markdown-remove-header
)
2546 (define-key map
"\C-c\C-t1" 'markdown-insert-header-atx-1
)
2547 (define-key map
"\C-c\C-t2" 'markdown-insert-header-atx-2
)
2548 (define-key map
"\C-c\C-t3" 'markdown-insert-header-atx-3
)
2549 (define-key map
"\C-c\C-t4" 'markdown-insert-header-atx-4
)
2550 (define-key map
"\C-c\C-t5" 'markdown-insert-header-atx-5
)
2551 (define-key map
"\C-c\C-t6" 'markdown-insert-header-atx-6
)
2552 (define-key map
"\C-c\C-pb" 'markdown-insert-bold
)
2553 (define-key map
"\C-c\C-ss" 'markdown-insert-bold
)
2554 (define-key map
"\C-c\C-pi" 'markdown-insert-italic
)
2555 (define-key map
"\C-c\C-se" 'markdown-insert-italic
)
2556 (define-key map
"\C-c\C-pf" 'markdown-insert-code
)
2557 (define-key map
"\C-c\C-sc" 'markdown-insert-code
)
2558 (define-key map
"\C-c\C-sb" 'markdown-insert-blockquote
)
2559 (define-key map
"\C-c\C-s\C-b" 'markdown-blockquote-region
)
2560 (define-key map
"\C-c\C-sp" 'markdown-insert-pre
)
2561 (define-key map
"\C-c\C-s\C-p" 'markdown-pre-region
)
2562 (define-key map
"\C-c-" 'markdown-insert-hr
)
2563 (define-key map
"\C-c\C-tt" 'markdown-insert-header-setext-1
)
2564 (define-key map
"\C-c\C-ts" 'markdown-insert-header-setext-2
)
2566 (define-key map
"\C-c\C-fn" 'markdown-footnote-new
)
2567 (define-key map
"\C-c\C-fg" 'markdown-footnote-goto-text
)
2568 (define-key map
"\C-c\C-fb" 'markdown-footnote-return
)
2569 (define-key map
"\C-c\C-fk" 'markdown-footnote-kill
)
2570 ;; Promotion, Demotion, Completion, and Cycling
2571 (define-key map
(kbd "M-<left>") 'markdown-promote
)
2572 (define-key map
(kbd "M-<right>") 'markdown-demote
)
2573 (define-key map
(kbd "C-c C-l") 'markdown-promote
)
2574 (define-key map
(kbd "C-c C-r") 'markdown-demote
)
2575 (define-key map
(kbd "C-c C-=") 'markdown-complete-or-cycle
)
2576 (define-key map
(kbd "C-c C-c =") 'markdown-complete-buffer
)
2577 ;; Regular Link Following
2578 (define-key map
"\C-c\C-o" 'markdown-follow-link-at-point
)
2579 ;; WikiLink Following
2580 (define-key map
"\C-c\C-w" 'markdown-follow-wiki-link-at-point
)
2581 (define-key map
"\M-n" 'markdown-next-wiki-link
)
2582 (define-key map
"\M-p" 'markdown-previous-wiki-link
)
2584 (define-key map
"\C-m" 'markdown-enter-key
)
2585 (define-key map
(kbd "<backspace>") 'markdown-dedent-or-delete
)
2586 ;; Visibility cycling
2587 (define-key map
(kbd "<tab>") 'markdown-cycle
)
2588 (define-key map
(kbd "<S-iso-lefttab>") 'markdown-shifttab
)
2589 (define-key map
(kbd "<S-tab>") 'markdown-shifttab
)
2590 (define-key map
(kbd "<backtab>") 'markdown-shifttab
)
2591 ;; Header navigation
2592 (define-key map
(kbd "C-M-n") 'outline-next-visible-heading
)
2593 (define-key map
(kbd "C-M-p") 'outline-previous-visible-heading
)
2594 (define-key map
(kbd "C-M-f") 'outline-forward-same-level
)
2595 (define-key map
(kbd "C-M-b") 'outline-backward-same-level
)
2596 (define-key map
(kbd "C-M-u") 'outline-up-heading
)
2597 ;; Markdown functions
2598 (define-key map
"\C-c\C-cm" 'markdown-other-window
)
2599 (define-key map
"\C-c\C-cp" 'markdown-preview
)
2600 (define-key map
"\C-c\C-ce" 'markdown-export
)
2601 (define-key map
"\C-c\C-cv" 'markdown-export-and-preview
)
2602 (define-key map
"\C-c\C-co" 'markdown-open
)
2603 (define-key map
"\C-c\C-cw" 'markdown-kill-ring-save
)
2605 (define-key map
"\C-c\C-cc" 'markdown-check-refs
)
2607 (define-key map
"\C-c\C-cn" 'markdown-cleanup-list-numbers
)
2608 (define-key map
(kbd "M-<up>") 'markdown-move-up
)
2609 (define-key map
(kbd "M-<down>") 'markdown-move-down
)
2610 (define-key map
(kbd "M-<return>") 'markdown-insert-list-item
)
2612 (define-key map
(kbd "M-[") 'markdown-beginning-of-block
)
2613 (define-key map
(kbd "M-]") 'markdown-end-of-block
)
2615 "Keymap for Markdown major mode.")
2617 (defvar gfm-mode-map
2618 (let ((map (make-sparse-keymap)))
2619 (set-keymap-parent map markdown-mode-map
)
2620 (define-key map
"\C-c\C-sl" 'markdown-insert-gfm-code-block
)
2622 "Keymap for `gfm-mode'.
2623 See also `markdown-mode-map'.")
2626 ;;; Menu ==================================================================
2628 (easy-menu-define markdown-mode-menu markdown-mode-map
2629 "Menu for Markdown mode"
2632 ["Cycle visibility" markdown-cycle
(outline-on-heading-p)]
2633 ["Cycle global visibility" markdown-shifttab
])
2635 ["Compile" markdown-other-window
]
2636 ["Preview" markdown-preview
]
2637 ["Export" markdown-export
]
2638 ["Export & View" markdown-export-and-preview
]
2639 ["Open" markdown-open
]
2640 ["Kill ring save" markdown-kill-ring-save
]
2643 ["First level" markdown-insert-setext-header-1
]
2644 ["Second level" markdown-insert-setext-header-2
])
2646 ["First level" markdown-insert-header-atx-1
]
2647 ["Second level" markdown-insert-header-atx-2
]
2648 ["Third level" markdown-insert-header-atx-3
]
2649 ["Fourth level" markdown-insert-header-atx-4
]
2650 ["Fifth level" markdown-insert-header-atx-5
]
2651 ["Sixth level" markdown-insert-header-atx-6
])
2653 ["Bold" markdown-insert-bold
]
2654 ["Italic" markdown-insert-italic
]
2655 ["Blockquote" markdown-insert-blockquote
]
2656 ["Preformatted" markdown-insert-pre
]
2657 ["Code" markdown-insert-code
]
2659 ["Insert inline link" markdown-insert-link
]
2660 ["Insert reference link" markdown-insert-reference-link-dwim
]
2661 ["Insert image" markdown-insert-image
]
2662 ["Insert horizontal rule" markdown-insert-hr
]
2665 ["Insert footnote" markdown-footnote-new
]
2666 ["Jump to footnote text" markdown-footnote-goto-text
]
2667 ["Return from footnote" markdown-footnote-return
])
2669 ["Check references" markdown-check-refs
]
2670 ["Clean up list numbering" markdown-cleanup-list-numbers
]
2672 ["Version" markdown-show-version
]
2676 ;;; imenu =====================================================================
2678 (defun markdown-imenu-create-index ()
2679 "Create and return an imenu index alist for the current buffer.
2680 See `imenu-create-index-function' and `imenu--index-alist' for details."
2681 (let* ((root '(nil . nil
))
2686 hashes pos level heading
)
2688 (goto-char (point-min))
2689 (while (re-search-forward markdown-regex-header
(point-max) t
)
2691 ((setq heading
(match-string-no-properties 1))
2692 (setq pos
(match-beginning 1)
2694 ((setq heading
(match-string-no-properties 3))
2695 (setq pos
(match-beginning 3)
2697 ((setq hashes
(match-string-no-properties 5))
2698 (setq heading
(match-string-no-properties 6)
2699 pos
(match-beginning 5)
2700 level
(length hashes
))))
2701 (let ((alist (list (cons heading pos
))))
2703 ((= cur-level level
) ; new sibling
2704 (setcdr cur-alist alist
)
2705 (setq cur-alist alist
))
2706 ((< cur-level level
) ; first child
2707 (dotimes (i (- level cur-level
1))
2708 (setq alist
(list (cons empty-heading alist
))))
2710 (let* ((parent (car cur-alist
))
2711 (self-pos (cdr parent
)))
2712 (setcdr parent
(cons (cons self-heading self-pos
) alist
)))
2713 (setcdr root alist
)) ; primogenitor
2714 (setq cur-alist alist
)
2715 (setq cur-level level
))
2716 (t ; new sibling of an ancestor
2717 (let ((sibling-alist (last (cdr root
))))
2718 (dotimes (i (1- level
))
2719 (setq sibling-alist
(last (cdar sibling-alist
))))
2720 (setcdr sibling-alist alist
)
2721 (setq cur-alist alist
))
2722 (setq cur-level level
)))))
2726 ;;; Reference Checking ========================================================
2728 (defconst markdown-refcheck-buffer
2729 "*Undefined references for %buffer%*"
2730 "Pattern for name of buffer for listing undefined references.
2731 The string %buffer% will be replaced by the corresponding
2732 `markdown-mode' buffer name.")
2734 (defun markdown-has-reference-definition (reference)
2735 "Find out whether Markdown REFERENCE is defined.
2736 REFERENCE should include the square brackets, like [this]."
2737 (let ((reference (downcase reference
)))
2739 (goto-char (point-min))
2741 (while (re-search-forward markdown-regex-reference-definition nil t
)
2742 (when (string= reference
(downcase (match-string-no-properties 1)))
2743 (throw 'found
(match-string-no-properties 2))))))))
2745 (defun markdown-get-undefined-refs ()
2746 "Return a list of undefined Markdown references.
2747 Result is an alist of pairs (reference . occurrences), where
2748 occurrences is itself another alist of pairs (label . line-number).
2749 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
2750 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
2751 \((\"[emacs]\" (\"[Nice editor]\" . 12) (\"[GNU Emacs]\" . 45)) (\"[elisp]\" (\"[manual]\" . 127)))."
2754 (goto-char (point-min))
2756 (re-search-forward markdown-regex-link-reference nil t
)
2757 (let* ((label (match-string-no-properties 1))
2758 (reference (match-string-no-properties 2))
2759 (target (downcase (if (string= reference
"[]") label reference
))))
2760 (unless (markdown-has-reference-definition target
)
2761 (let ((entry (assoc target missing
)))
2763 (add-to-list 'missing
(cons target
2764 (list (cons label
(markdown-line-number-at-pos)))) t
)
2766 (append (cdr entry
) (list (cons label
(markdown-line-number-at-pos))))))))))
2769 (defun markdown-add-missing-ref-definition (ref buffer
&optional recheck
)
2770 "Add blank REF definition to the end of BUFFER.
2771 REF is a Markdown reference in square brackets, like \"[lisp-history]\".
2772 When RECHECK is non-nil, BUFFER gets rechecked for undefined
2773 references so that REF disappears from the list of those links."
2774 (with-current-buffer buffer
2775 (when (not (eq major-mode
'markdown-mode
))
2776 (error "Not available in current mode"))
2777 (goto-char (point-max))
2778 (indent-new-comment-line)
2779 (insert (concat ref
": ")))
2780 (switch-to-buffer-other-window buffer
)
2781 (goto-char (point-max))
2783 (markdown-check-refs t
)))
2785 ;; Button which adds an empty Markdown reference definition to the end
2786 ;; of buffer specified as its 'target-buffer property. Reference name
2787 ;; is button's label
2788 (when (>= emacs-major-version
22)
2789 (define-button-type 'markdown-ref-button
2790 'help-echo
"Push to create an empty reference definition"
2793 (markdown-add-missing-ref-definition
2794 (button-label b
) (button-get b
'target-buffer
) t
))))
2796 ;; Button jumping to line in buffer specified as its 'target-buffer
2797 ;; property. Line number is button's 'line property.
2798 (when (>= emacs-major-version
22)
2799 (define-button-type 'goto-line-button
2800 'help-echo
"Push to go to this line"
2803 (message (button-get b
'buffer
))
2804 (switch-to-buffer-other-window (button-get b
'target-buffer
))
2805 ;; use call-interactively to silence compiler
2806 (call-interactively 'goto-line
(button-get b
'target-line
)))))
2808 (defun markdown-check-refs (&optional silent
)
2809 "Show all undefined Markdown references in current `markdown-mode' buffer.
2810 If SILENT is non-nil, do not message anything when no undefined
2812 Links which have empty reference definitions are considered to be
2815 (when (not (eq major-mode
'markdown-mode
))
2816 (error "Not available in current mode"))
2817 (let ((oldbuf (current-buffer))
2818 (refs (markdown-get-undefined-refs))
2819 (refbuf (get-buffer-create (markdown-replace-regexp-in-string
2820 "%buffer%" (buffer-name)
2821 markdown-refcheck-buffer
))))
2825 (message "No undefined references found"))
2826 (kill-buffer refbuf
))
2827 (with-current-buffer refbuf
2829 (View-exit-and-edit))
2831 (insert "Following references lack definitions:")
2834 (let ((button-label (format "%s" (car ref
))))
2835 (if (>= emacs-major-version
22)
2836 ;; Create a reference button in Emacs 22
2837 (insert-text-button button-label
2838 :type
'markdown-ref-button
2839 'target-buffer oldbuf
)
2840 ;; Insert reference as text in Emacs < 22
2841 (insert button-label
)))
2843 (dolist (occurrence (cdr ref
))
2844 (let ((line (cdr occurrence
)))
2845 (if (>= emacs-major-version
22)
2846 ;; Create a line number button in Emacs 22
2847 (insert-button (number-to-string line
)
2848 :type
'goto-line-button
2849 'target-buffer oldbuf
2851 ;; Insert line number as text in Emacs < 22
2852 (insert (number-to-string line
)))
2853 (insert " "))) (delete-char -
1)
2856 (view-buffer-other-window refbuf
)
2857 (goto-char (point-min))
2858 (forward-line 2)))))
2861 ;;; Lists =====================================================================
2863 (defun markdown-insert-list-item (&optional arg
)
2864 "Insert a new list item.
2865 If the point is inside unordered list, insert a bullet mark. If
2866 the point is inside ordered list, insert the next number followed
2867 by a period. Use the previous list item to determine the amount
2868 of whitespace to place before and after list markers.
2870 With a \\[universal-argument] prefix (i.e., when ARG is 4),
2871 decrease the indentation by one level.
2873 With two \\[universal-argument] prefixes (i.e., when ARG is 16),
2874 increase the indentation by one level."
2876 (let (bounds item-indent marker indent new-indent end
)
2878 (setq bounds
(markdown-cur-list-item-bounds))
2880 ;; When not in a list, start a new unordered one
2882 (unless (markdown-cur-line-blank-p)
2885 ;; Compute indentation for a new list item
2886 (setq item-indent
(nth 2 bounds
))
2887 (setq marker
(concat (match-string 2) (match-string 3)))
2889 ((= arg
4) (max (- item-indent
4) 0))
2890 ((= arg
16) (+ item-indent
4))
2892 (setq new-indent
(make-string indent
32))
2893 (goto-char (nth 1 bounds
))
2897 ((string-match "[0-9]" marker
)
2898 (if (= arg
16) ;; starting a new column indented one more level
2899 (insert (concat new-indent
"1. "))
2900 ;; travel up to the last item and pick the correct number. If
2901 ;; the argument was nil, "new-indent = item-indent" is the same,
2902 ;; so we don't need special treatment. Neat.
2904 (while (not (looking-at (concat new-indent
"\\([0-9]+\\)\\.")))
2906 (insert (concat new-indent
2907 (int-to-string (1+ (string-to-number (match-string 1))))
2910 ((string-match "[\\*\\+-]" marker
)
2911 (insert (concat new-indent marker
))))))))
2913 (defun markdown-move-list-item-up ()
2914 "Move the current list item up in the list when possible."
2917 (when (setq cur
(markdown-cur-list-item-bounds))
2919 (goto-char (nth 0 cur
))
2920 (if (markdown-prev-list-item (nth 3 cur
))
2922 (setq prev
(markdown-cur-list-item-bounds))
2925 (transpose-regions (nth 0 prev
) (nth 1 prev
)
2926 (nth 0 cur
) (nth 1 cur
) t
)
2927 (goto-char (+ (nth 0 prev
) (- old
(nth 0 cur
)))))
2928 ;; Catch error in case regions overlap.
2929 (error (goto-char old
))))
2932 (defun markdown-move-list-item-down ()
2933 "Move the current list item down in the list when possible."
2936 (when (setq cur
(markdown-cur-list-item-bounds))
2938 (if (markdown-next-list-item (nth 3 cur
))
2940 (setq next
(markdown-cur-list-item-bounds))
2943 (transpose-regions (nth 0 cur
) (nth 1 cur
)
2944 (nth 0 next
) (nth 1 next
) nil
)
2945 (goto-char (+ old
(- (nth 1 next
) (nth 1 cur
)))))
2946 ;; Catch error in case regions overlap.
2947 (error (goto-char old
))))
2950 (defun markdown-demote-list-item (&optional bounds
)
2951 "Indent (or demote) the current list item.
2952 Optionally, BOUNDS of the current list item may be provided if available."
2954 (when (or bounds
(setq bounds
(markdown-cur-list-item-bounds)))
2957 (let* ((end-marker (make-marker))
2958 (end-marker (set-marker end-marker
(nth 1 bounds
))))
2959 (goto-char (nth 0 bounds
))
2960 (while (< (point) end-marker
)
2961 (unless (markdown-cur-line-blank-p)
2963 (forward-line)))))))
2965 (defun markdown-promote-list-item (&optional bounds
)
2966 "Unindent (or promote) the current list item.
2967 Optionally, BOUNDS of the current list item may be provided if available."
2969 (when (or bounds
(setq bounds
(markdown-cur-list-item-bounds)))
2972 (let* ((end-marker (make-marker))
2973 (end-marker (set-marker end-marker
(nth 1 bounds
)))
2975 (goto-char (nth 0 bounds
))
2976 (when (looking-at "^[ ]\\{1,4\\}")
2977 (setq num
(- (match-end 0) (match-beginning 0)))
2978 (setq regexp
(format "^[ ]\\{1,%d\\}" num
))
2979 (while (and (< (point) end-marker
)
2980 (re-search-forward regexp end-marker t
))
2981 (replace-match "" nil nil
)
2982 (forward-line))))))))
2984 (defun markdown--cleanup-list-numbers-level (&optional pfx
)
2985 "Update the numbering for level PFX (as a string of spaces).
2987 Assume that the previously found match was for a numbered item in
2994 (while (and continue
(not (eobp)))
2997 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
2998 (setq cpfx
(match-string-no-properties 1))
3002 (concat pfx
(number-to-string (setq idx
(1+ idx
))) ". "))
3006 (setq sep
(markdown--cleanup-list-numbers-level cpfx
))
3011 (setq continue nil
))))
3013 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
3014 (setq cpfx
(match-string-no-properties 1))
3016 ;; reset if separated before
3017 ((string= cpfx pfx
) (when sep
(setq idx
0)))
3020 (setq continue nil
))))
3025 (setq continue
(= (forward-line) 0))))
3028 (defun markdown-cleanup-list-numbers ()
3029 "Update the numbering of ordered lists."
3032 (goto-char (point-min))
3033 (markdown--cleanup-list-numbers-level "")))
3036 ;;; Outline ===================================================================
3038 (defvar markdown-cycle-global-status
1)
3039 (defvar markdown-cycle-subtree-status nil
)
3041 (defun markdown-end-of-subtree (&optional invisible-OK
)
3042 "Move to the end of the current subtree.
3043 Only visible heading lines are considered, unless INVISIBLE-OK is
3045 Derived from `org-end-of-subtree'."
3046 (outline-back-to-heading invisible-OK
)
3048 (level (funcall outline-level
)))
3049 (while (and (not (eobp))
3050 (or first
(> (funcall outline-level
) level
)))
3052 (outline-next-heading))
3053 (if (memq (preceding-char) '(?
\n ?\^M
))
3055 ;; Go to end of line before heading
3057 (if (memq (preceding-char) '(?
\n ?\^M
))
3058 ;; leave blank line before heading
3059 (forward-char -
1)))))
3062 (defun markdown-cycle (&optional arg
)
3063 "Visibility cycling for Markdown mode.
3064 If ARG is t, perform global visibility cycling. If the point is
3065 at an atx-style header, cycle visibility of the corresponding
3066 subtree. Otherwise, insert a tab using `indent-relative'.
3067 Derived from `org-cycle'."
3070 ((eq arg t
) ;; Global cycling
3072 ((and (eq last-command this-command
)
3073 (eq markdown-cycle-global-status
2))
3074 ;; Move from overview to contents
3076 (message "CONTENTS")
3077 (setq markdown-cycle-global-status
3))
3079 ((and (eq last-command this-command
)
3080 (eq markdown-cycle-global-status
3))
3081 ;; Move from contents to all
3083 (message "SHOW ALL")
3084 (setq markdown-cycle-global-status
1))
3087 ;; Defaults to overview
3089 (message "OVERVIEW")
3090 (setq markdown-cycle-global-status
2))))
3092 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp
))
3093 ;; At a heading: rotate between three different views
3094 (outline-back-to-heading)
3095 (let ((goal-column 0) eoh eol eos
)
3096 ;; Determine boundaries
3098 (outline-back-to-heading)
3100 (beginning-of-line 2)
3101 (while (and (not (eobp)) ;; this is like `next-line'
3102 (get-char-property (1- (point)) 'invisible
))
3103 (beginning-of-line 2)) (setq eol
(point)))
3104 (outline-end-of-heading) (setq eoh
(point))
3105 (markdown-end-of-subtree t
)
3106 (skip-chars-forward " \t\n")
3107 (beginning-of-line 1) ; in case this is an item
3108 (setq eos
(1- (point))))
3109 ;; Find out what to do next and set `this-command'
3112 ;; Nothing is hidden behind this heading
3113 (message "EMPTY ENTRY")
3114 (setq markdown-cycle-subtree-status nil
))
3116 ;; Entire subtree is hidden in one line: open it
3119 (message "CHILDREN")
3120 (setq markdown-cycle-subtree-status
'children
))
3121 ((and (eq last-command this-command
)
3122 (eq markdown-cycle-subtree-status
'children
))
3123 ;; We just showed the children, now show everything.
3126 (setq markdown-cycle-subtree-status
'subtree
))
3128 ;; Default action: hide the subtree.
3131 (setq markdown-cycle-subtree-status
'folded
)))))
3134 (indent-for-tab-command))))
3136 (defun markdown-shifttab ()
3137 "Global visibility cycling.
3138 Calls `markdown-cycle' with argument t."
3142 (defun markdown-outline-level ()
3143 "Return the depth to which a statement is nested in the outline."
3147 ((- (match-end 5) (match-beginning 5)))))
3150 ;;; Movement ==================================================================
3152 (defun markdown-beginning-of-defun (&optional arg
)
3153 "`beginning-of-defun-function' for Markdown.
3154 Move backward to the beginning of the current or previous section."
3156 (or arg
(setq arg
1))
3157 (or (re-search-backward markdown-regex-header nil t arg
)
3158 (goto-char (point-min))))
3160 (defun markdown-end-of-defun (&optional arg
)
3161 "`end-of-defun-function' for Markdown.
3162 Move forward to the end of the current or following section."
3164 (or arg
(setq arg
1))
3165 (when (looking-at markdown-regex-header
)
3166 (goto-char (match-beginning 0))
3168 (if (re-search-forward markdown-regex-header nil t arg
)
3169 (goto-char (match-beginning 0))
3170 (goto-char (point-max)))
3171 (skip-syntax-backward "-"))
3173 (defun markdown-beginning-of-block ()
3174 "Move the point to the start of the previous text block."
3176 (if (re-search-backward markdown-regex-block-separator nil t
)
3177 (goto-char (or (match-end 2) (match-end 0)))
3178 (goto-char (point-min))))
3180 (defun markdown-end-of-block ()
3181 "Move the point to the start of the next text block."
3184 (skip-syntax-forward "-")
3185 (when (= (point) (point-min))
3187 (if (re-search-forward markdown-regex-block-separator nil t
)
3188 (goto-char (or (match-end 2) (match-end 0)))
3189 (goto-char (point-max)))
3190 (skip-syntax-backward "-")
3193 (defun markdown-end-of-block-element ()
3194 "Move the point to the start of the next block unit.
3195 Stops at blank lines, list items, headers, and horizontal rules."
3198 (while (and (or (not (markdown-prev-line-blank-p))
3199 (markdown-cur-line-blank-p))
3200 (not (or (looking-at markdown-regex-list
)
3201 (looking-at markdown-regex-header
)
3202 (looking-at markdown-regex-hr
)))
3207 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
3209 (defun markdown-move-up ()
3211 Calls `markdown-move-list-item-up'."
3213 (markdown-move-list-item-up))
3215 (defun markdown-move-down ()
3216 "Move list item down.
3217 Calls `markdown-move-list-item-down'."
3219 (markdown-move-list-item-down))
3221 (defun markdown-promote ()
3222 "Either promote header or list item at point or cycle markup.
3223 See `markdown-cycle-atx', `markdown-cycle-setext', and
3224 `markdown-demote-list-item'."
3228 ;; Promote atx header
3229 ((thing-at-point-looking-at markdown-regex-header-atx
)
3230 (markdown-cycle-atx -
1 t
))
3231 ;; Promote setext header
3232 ((thing-at-point-looking-at markdown-regex-header-setext
)
3233 (markdown-cycle-setext -
1 t
))
3234 ;; Promote horizonal rule
3235 ((thing-at-point-looking-at markdown-regex-hr
)
3236 (markdown-cycle-hr -
1 t
))
3237 ;; Promote list item
3238 ((setq bounds
(markdown-cur-list-item-bounds))
3239 (markdown-promote-list-item)))))
3241 (defun markdown-demote ()
3242 "Either demote header or list item at point or cycle or remove markup.
3243 See `markdown-cycle-atx', `markdown-cycle-setext', and
3244 `markdown-demote-list-item'."
3248 ;; Demote atx header
3249 ((thing-at-point-looking-at markdown-regex-header-atx
)
3250 (markdown-cycle-atx 1 t
))
3251 ;; Demote setext header
3252 ((thing-at-point-looking-at markdown-regex-header-setext
)
3253 (markdown-cycle-setext 1 t
))
3254 ;; Demote horizonal rule
3255 ((thing-at-point-looking-at markdown-regex-hr
)
3256 (markdown-cycle-hr 1 t
))
3257 ;; Promote list item
3258 ((setq bounds
(markdown-cur-list-item-bounds))
3259 (markdown-demote-list-item))
3260 ;; Create a new level one ATX header
3262 (markdown-insert-header-atx-1)))))
3264 (defun markdown-complete-or-cycle (arg)
3265 "Complete or cycle markup of object at point or complete objects in region.
3266 If there is an active region, complete markup in region.
3267 Otherwise, complete or cycle markup of object near point.
3268 When ARG is non-nil, cycle backwards when cycling."
3270 (if (markdown-use-region-p)
3271 ;; Complete markup in region
3272 (markdown-complete-region (region-beginning) (region-end))
3273 ;; Complete or cycle markup at point
3274 (let ((dir (if arg -
1 1))
3278 ((thing-at-point-looking-at markdown-regex-header-atx
)
3279 (if (markdown-incomplete-atx-p)
3280 (markdown-complete-atx)
3281 (markdown-cycle-atx dir
)))
3283 ((thing-at-point-looking-at markdown-regex-header-setext
)
3284 (if (markdown-incomplete-setext-p)
3285 (markdown-complete-setext)
3286 (markdown-cycle-setext dir
)))
3288 ((thing-at-point-looking-at markdown-regex-hr
)
3289 (if (markdown-incomplete-hr-p)
3290 (markdown-complete-hr)
3291 (markdown-cycle-hr dir
)))
3293 ((thing-at-point-looking-at markdown-regex-bold
)
3294 (markdown-cycle-bold))
3296 ((thing-at-point-looking-at markdown-regex-italic
)
3297 (markdown-cycle-italic))))))
3300 ;;; Commands ==================================================================
3302 (defun markdown (&optional output-buffer-name
)
3303 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
3304 The output buffer name defaults to `markdown-output-buffer-name'.
3305 Return the name of the output buffer used."
3307 (save-window-excursion
3308 (let ((begin-region)
3310 (if (markdown-use-region-p)
3311 (setq begin-region
(region-beginning)
3312 end-region
(region-end))
3313 (setq begin-region
(point-min)
3314 end-region
(point-max)))
3316 (unless output-buffer-name
3317 (setq output-buffer-name markdown-output-buffer-name
))
3320 ;; Handle case when `markdown-command' does not read from stdin
3321 (markdown-command-needs-filename
3322 (if (not buffer-file-name
)
3323 (error "Must be visiting a file")
3324 (shell-command (concat markdown-command
" "
3325 (shell-quote-argument buffer-file-name
))
3326 output-buffer-name
)))
3327 ;; Pass region to `markdown-command' via stdin
3329 (shell-command-on-region begin-region end-region markdown-command
3330 output-buffer-name
))))
3331 output-buffer-name
))
3333 (defun markdown-standalone (&optional output-buffer-name
)
3334 "Special function to provide standalone HTML output.
3335 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
3337 (setq output-buffer-name
(markdown output-buffer-name
))
3338 (with-current-buffer output-buffer-name
3339 (set-buffer output-buffer-name
)
3340 (goto-char (point-min))
3341 (unless (markdown-output-standalone-p)
3342 (markdown-add-xhtml-header-and-footer output-buffer-name
))
3346 (defun markdown-other-window (&optional output-buffer-name
)
3347 "Run `markdown-command' on current buffer and display in other window.
3348 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
3351 (display-buffer (markdown-standalone output-buffer-name
)))
3353 (defun markdown-output-standalone-p ()
3354 "Determine whether `markdown-command' output is standalone XHTML.
3355 Standalone XHTML output is identified by an occurrence of
3356 `markdown-xhtml-standalone-regexp' in the first five lines of output."
3358 markdown-xhtml-standalone-regexp
3359 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
3362 (defun markdown-add-xhtml-header-and-footer (title)
3363 "Wrap XHTML header and footer with given TITLE around current buffer."
3364 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
3365 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
3366 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
3367 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
3370 (insert "</title>\n")
3371 (when (> (length markdown-content-type
) 0)
3374 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
3375 markdown-content-type
3376 (or (and markdown-coding-system
3377 (fboundp 'coding-system-get
)
3378 (coding-system-get markdown-coding-system
3380 (and (fboundp 'coding-system-get
)
3381 (coding-system-get buffer-file-coding-system
3384 (if (> (length markdown-css-path
) 0)
3385 (insert "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
3388 (when (> (length markdown-xhtml-header-content
) 0)
3389 (insert markdown-xhtml-header-content
))
3390 (insert "\n</head>\n\n"
3392 (goto-char (point-max))
3397 (defun markdown-preview (&optional output-buffer-name
)
3398 "Run `markdown-command' on the current buffer and view output in browser.
3399 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
3402 (browse-url-of-buffer (markdown markdown-output-buffer-name
)))
3404 (defun markdown-export-file-name (&optional extension
)
3405 "Attempt to generate a filename for Markdown output.
3406 The file extension will be EXTENSION if given, or .html by default.
3407 If the current buffer is visiting a file, we construct a new
3408 output filename based on that filename. Otherwise, return nil."
3409 (when (buffer-file-name)
3411 (setq extension
".html"))
3415 (file-name-sans-extension (buffer-file-name)))
3419 (defun markdown-export (&optional output-file
)
3420 "Run Markdown on the current buffer, save to file, and return the filename.
3421 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
3422 generated by `markdown-export-file-name', which will be constructed using the
3423 current filename, but with the extension removed and replaced with .html."
3426 (setq output-file
(markdown-export-file-name ".html")))
3428 (let ((output-buffer-name))
3429 (setq output-buffer-name
(buffer-name (find-file-noselect output-file
)))
3430 (run-hook-with-args 'markdown-before-export-hooks output-file
)
3431 (markdown-standalone output-buffer-name
)
3432 (with-current-buffer output-buffer-name
3434 (run-hook-with-args 'markdown-after-export-hooks output-file
)
3437 (defun markdown-export-and-preview ()
3438 "Export to XHTML using `markdown-export' and browse the resulting file."
3440 (browse-url (markdown-export)))
3442 (defun markdown-open ()
3443 "Open file for the current buffer with `markdown-open-command'."
3445 (if (not markdown-open-command
)
3446 (error "Variable `markdown-open-command' must be set")
3447 (if (not buffer-file-name
)
3448 (error "Must be visiting a file")
3449 (call-process markdown-open-command
3450 nil nil nil buffer-file-name
))))
3452 (defun markdown-kill-ring-save ()
3453 "Run Markdown on file and store output in the kill ring."
3455 (save-window-excursion
3457 (with-current-buffer markdown-output-buffer-name
3458 (kill-ring-save (point-min) (point-max)))))
3461 ;;; Links =====================================================================
3463 (require 'thingatpt
)
3465 (defun markdown-link-p ()
3466 "Return non-nil when `point' is at a non-wiki link.
3467 See `markdown-wiki-link-p' for more information."
3468 (let ((case-fold-search nil
))
3469 (and (not (markdown-wiki-link-p))
3470 (or (thing-at-point-looking-at markdown-regex-link-inline
)
3471 (thing-at-point-looking-at markdown-regex-link-reference
)
3472 (thing-at-point-looking-at markdown-regex-uri
)
3473 (thing-at-point-looking-at markdown-regex-angle-uri
)))))
3475 (defun markdown-link-link ()
3476 "Return the link part of the regular (non-wiki) link at point.
3477 Works with both inline and reference style links. If point is
3478 not at a link or the link reference is not defined returns nil."
3480 ((thing-at-point-looking-at markdown-regex-link-inline
)
3481 (substring-no-properties (match-string 2) 1 -
1))
3482 ((thing-at-point-looking-at markdown-regex-link-reference
)
3483 (let* ((label (match-string-no-properties 1))
3484 (reference (match-string-no-properties 2))
3485 (target (downcase (if (string= reference
"[]") label reference
))))
3486 (markdown-has-reference-definition target
)))
3487 ((thing-at-point-looking-at markdown-regex-uri
)
3488 (match-string-no-properties 0))
3489 ((thing-at-point-looking-at markdown-regex-angle-uri
)
3490 (match-string-no-properties 2))
3493 (defun markdown-follow-link-at-point ()
3494 "Open the current non-wiki link in a browser."
3496 (if (markdown-link-p) (browse-url (markdown-link-link))
3497 (error "Point is not at a Markdown link or URI")))
3500 ;;; WikiLink Following/Markup =================================================
3502 (defun markdown-wiki-link-p ()
3503 "Return non-nil when `point' is at a true wiki link.
3504 A true wiki link name matches `markdown-regex-wiki-link' but does not
3505 match the current file name after conversion. This modifies the data
3506 returned by `match-data'. Note that the potential wiki link name must
3507 be available via `match-string'."
3508 (let ((case-fold-search nil
))
3509 (and (thing-at-point-looking-at markdown-regex-wiki-link
)
3510 (or (not buffer-file-name
)
3511 (not (string-equal (buffer-file-name)
3512 (markdown-convert-wiki-link-to-filename
3513 (markdown-wiki-link-link)))))
3514 (not (save-match-data
3515 (save-excursion))))))
3517 (defun markdown-wiki-link-link ()
3518 "Return the link part of the wiki link using current match data.
3519 The location of the link component depends on the value of
3520 `markdown-wiki-link-alias-first'."
3521 (if markdown-wiki-link-alias-first
3522 (or (match-string-no-properties 4) (match-string-no-properties 2))
3523 (match-string-no-properties 2)))
3525 (defun markdown-convert-wiki-link-to-filename (name)
3526 "Generate a filename from the wiki link NAME.
3527 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
3528 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
3529 and [[test test]] both map to Test-test.ext."
3530 (let ((basename (markdown-replace-regexp-in-string
3531 "[[:space:]\n]" markdown-link-space-sub-char name
)))
3532 (when (eq major-mode
'gfm-mode
)
3533 (setq basename
(concat (upcase (substring basename
0 1))
3534 (downcase (substring basename
1 nil
)))))
3536 (if (buffer-file-name)
3538 (file-name-extension (buffer-file-name)))))))
3540 (defun markdown-follow-wiki-link (name &optional other
)
3541 "Follow the wiki link NAME.
3542 Convert the name to a file name and call `find-file'. Ensure that
3543 the new buffer remains in `markdown-mode'. Open the link in another
3544 window when OTHER is non-nil."
3545 (let ((filename (markdown-convert-wiki-link-to-filename name
))
3546 (wp (file-name-directory buffer-file-name
)))
3547 (when other
(other-window 1))
3548 (find-file (concat wp filename
)))
3549 (when (not (eq major-mode
'markdown-mode
))
3552 (defun markdown-follow-wiki-link-at-point (&optional arg
)
3553 "Find Wiki Link at point.
3554 With prefix argument ARG, open the file in other window.
3555 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
3557 (if (markdown-wiki-link-p)
3558 (markdown-follow-wiki-link (markdown-wiki-link-link) arg
)
3559 (error "Point is not at a Wiki Link")))
3561 (defun markdown-next-wiki-link ()
3562 "Jump to next wiki link.
3563 If successful, return point. Otherwise, return nil.
3564 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
3566 (let ((opoint (point)))
3567 (when (markdown-wiki-link-p)
3568 ;; At a wiki link already, move past it.
3569 (goto-char (+ (match-end 0) 1)))
3570 ;; Search for the next wiki link and move to the beginning.
3571 (if (re-search-forward markdown-regex-wiki-link nil t
)
3572 (goto-char (match-beginning 1))
3576 (defun markdown-previous-wiki-link ()
3577 "Jump to previous wiki link.
3578 If successful, return point. Otherwise, return nil.
3579 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
3581 (if (re-search-backward markdown-regex-wiki-link nil t
)
3582 (goto-char (match-beginning 1))
3585 (defun markdown-highlight-wiki-link (from to face
)
3586 "Highlight the wiki link in the region between FROM and TO using FACE."
3587 (put-text-property from to
'font-lock-face face
))
3589 (defun markdown-unfontify-region-wiki-links (from to
)
3590 "Remove wiki link faces from the region specified by FROM and TO."
3591 (interactive "nfrom: \nnto: ")
3592 (remove-text-properties from to
'(font-lock-face markdown-link-face
))
3593 (remove-text-properties from to
'(font-lock-face markdown-missing-link-face
)))
3595 (defun markdown-fontify-region-wiki-links (from to
)
3596 "Search region given by FROM and TO for wiki links and fontify them.
3597 If a wiki link is found check to see if the backing file exists
3598 and highlight accordingly."
3601 (while (re-search-forward markdown-regex-wiki-link to t
)
3602 (let ((highlight-beginning (match-beginning 1))
3603 (highlight-end (match-end 1))
3605 (markdown-convert-wiki-link-to-filename
3606 (markdown-wiki-link-link))))
3607 (if (file-exists-p file-name
)
3608 (markdown-highlight-wiki-link
3609 highlight-beginning highlight-end markdown-link-face
)
3610 (markdown-highlight-wiki-link
3611 highlight-beginning highlight-end markdown-link-face
)
3612 (markdown-highlight-wiki-link
3613 highlight-beginning highlight-end markdown-missing-link-face
))))))
3615 (defun markdown-extend-changed-region (from to
)
3616 "Extend region given by FROM and TO so that we can fontify all links.
3617 The region is extended to the first newline before and the first
3619 ;; start looking for the first new line before 'from
3621 (re-search-backward "\n" nil t
)
3622 (let ((new-from (point-min))
3623 (new-to (point-max)))
3624 (if (not (= (point) from
))
3625 (setq new-from
(point)))
3626 ;; do the same thing for the first new line after 'to
3628 (re-search-forward "\n" nil t
)
3629 (if (not (= (point) to
))
3630 (setq new-to
(point)))
3631 (values new-from new-to
)))
3633 (defun markdown-check-change-for-wiki-link (from to change
)
3634 "Check region between FROM and TO for wiki links and re-fontfy as needed.
3635 Designed to be used with the `after-change-functions' hook.
3636 CHANGE is the number of bytes of pre-change text replaced by the
3638 (interactive "nfrom: \nnto: \nnchange: ")
3639 (let* ((modified (buffer-modified-p))
3640 (buffer-undo-list t
)
3641 (inhibit-read-only t
)
3642 (inhibit-point-motion-hooks t
)
3644 buffer-file-truename
)
3649 ;; Extend the region to fontify so that it starts
3650 ;; and ends at safe places.
3651 (multiple-value-bind (new-from new-to
)
3652 (markdown-extend-changed-region from to
)
3653 ;; Unfontify existing fontification (start from scratch)
3654 (markdown-unfontify-region-wiki-links new-from new-to
)
3655 ;; Now do the fontification.
3656 (markdown-fontify-region-wiki-links new-from new-to
)))))
3659 (set-buffer-modified-p nil
)))))
3661 (defun markdown-fontify-buffer-wiki-links ()
3662 "Refontify all wiki links in the buffer."
3664 (markdown-check-change-for-wiki-link (point-min) (point-max) 0))
3667 ;;; Miscellaneous =============================================================
3669 (defun markdown-compress-whitespace-string (str)
3670 "Compress whitespace in STR and return result.
3671 Leading and trailing whitespace is removed. Sequences of multiple
3672 spaces, tabs, and newlines are replaced with single spaces."
3673 (replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
3674 (replace-regexp-in-string "[ \t\n]+" " " str
)))
3676 (defun markdown-line-number-at-pos (&optional pos
)
3677 "Return (narrowed) buffer line number at position POS.
3678 If POS is nil, use current buffer location.
3679 This is an exact copy of `line-number-at-pos' for use in emacs21."
3680 (let ((opoint (or pos
(point))) start
)
3682 (goto-char (point-min))
3683 (setq start
(point))
3686 (1+ (count-lines start
(point))))))
3688 (defun markdown-nobreak-p ()
3689 "Return nil if it is acceptable to break the current line at the point."
3690 ;; inside in square brackets (e.g., link anchor text)
3691 (looking-back "\\[[^]]*"))
3694 ;;; Mode Definition ==========================================================
3696 (defun markdown-show-version ()
3697 "Show the version number in the minibuffer."
3699 (message "markdown-mode, version %s" markdown-mode-version
))
3702 (define-derived-mode markdown-mode text-mode
"Markdown"
3703 "Major mode for editing Markdown files."
3704 ;; Natural Markdown tab width
3707 (make-local-variable 'comment-start
)
3708 (setq comment-start
"<!-- ")
3709 (make-local-variable 'comment-end
)
3710 (setq comment-end
" -->")
3711 (make-local-variable 'comment-start-skip
)
3712 (setq comment-start-skip
"<!--[ \t]*")
3713 (make-local-variable 'comment-column
)
3714 (setq comment-column
0)
3716 (set (make-local-variable 'font-lock-defaults
)
3717 '(markdown-mode-font-lock-keywords))
3718 (set (make-local-variable 'font-lock-multiline
) t
)
3719 ;; For imenu support
3720 (setq imenu-create-index-function
'markdown-imenu-create-index
)
3721 ;; For menu support in XEmacs
3722 (easy-menu-add markdown-mode-menu markdown-mode-map
)
3724 (set (make-local-variable 'beginning-of-defun-function
)
3725 'markdown-beginning-of-defun
)
3726 (set (make-local-variable 'end-of-defun-function
)
3727 'markdown-end-of-defun
)
3728 ;; Make filling work with lists (unordered, ordered, and definition)
3729 (set (make-local-variable 'paragraph-start
)
3730 "\f\\|[ \t]*$\\|^[ \t]*[*+-] \\|^[ \t]*[0-9]+\\.\\|^[ \t]*: ")
3732 (make-local-variable 'outline-regexp
)
3733 (setq outline-regexp markdown-regex-header
)
3734 (make-local-variable 'outline-level
)
3735 (setq outline-level
'markdown-outline-level
)
3736 ;; Cause use of ellipses for invisible text.
3737 (add-to-invisibility-spec '(outline . t
))
3738 ;; Indentation and filling
3739 (make-local-variable 'fill-nobreak-predicate
)
3740 (add-hook 'fill-nobreak-predicate
'markdown-nobreak-p
)
3741 (setq indent-line-function markdown-indent-function
)
3743 ;; Prepare hooks for XEmacs compatibility
3744 (when (featurep 'xemacs
)
3745 (make-local-hook 'after-change-functions
)
3746 (make-local-hook 'font-lock-extend-region-functions
)
3747 (make-local-hook 'window-configuration-change-hook
))
3749 ;; Multiline font lock
3750 (add-hook 'font-lock-extend-region-functions
3751 'markdown-font-lock-extend-region
)
3753 ;; Anytime text changes make sure it gets fontified correctly
3754 (add-hook 'after-change-functions
'markdown-check-change-for-wiki-link t t
)
3756 ;; If we left the buffer there is a really good chance we were
3757 ;; creating one of the wiki link documents. Make sure we get
3758 ;; refontified when we come back.
3759 (add-hook 'window-configuration-change-hook
3760 'markdown-fontify-buffer-wiki-links t t
)
3762 ;; do the initial link fontification
3763 (markdown-fontify-buffer-wiki-links))
3765 ;;(add-to-list 'auto-mode-alist '("\\.text$" . markdown-mode))
3768 ;;; GitHub Flavored Markdown Mode ============================================
3771 (define-derived-mode gfm-mode markdown-mode
"GFM"
3772 "Major mode for editing GitHub Flavored Markdown files."
3773 (setq markdown-link-space-sub-char
"-")
3775 ;; Use visual-line-mode if available, fall back to longlines-mode:
3776 (if (fboundp 'visual-line-mode
)
3777 (visual-line-mode 1)
3779 ;; do the initial link fontification
3780 (markdown-fontify-buffer-wiki-links))
3783 (provide 'markdown-mode
)
3785 ;;; markdown-mode.el ends here