Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
9695 lines (8816 sloc) 397 KB
;;; markdown-mode.el --- Major mode for Markdown-formatted text -*- lexical-binding: t; -*-
;; Copyright (C) 2007-2017 Jason R. Blevins and markdown-mode
;; contributors (see the commit log for details).
;; Author: Jason R. Blevins <jblevins@xbeta.org>
;; Maintainer: Jason R. Blevins <jblevins@xbeta.org>
;; Created: May 24, 2007
;; Version: 2.4-dev
;; Package-Requires: ((emacs "24.4") (cl-lib "0.5"))
;; Keywords: Markdown, GitHub Flavored Markdown, itex
;; URL: https://jblevins.org/projects/markdown-mode/
;; This file is not part of GNU Emacs.
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; See the README.md file for details.
;;; Code:
(require 'easymenu)
(require 'outline)
(require 'thingatpt)
(require 'cl-lib)
(require 'url-parse)
(require 'button)
(require 'color)
(require 'rx)
(defvar jit-lock-start)
(defvar jit-lock-end)
(defvar flyspell-generic-check-word-predicate)
(declare-function eww-open-file "eww")
(declare-function url-path-and-query "url-parse")
;;; Constants =================================================================
(defconst markdown-mode-version "2.4-dev"
"Markdown mode version number.")
(defconst markdown-output-buffer-name "*markdown-output*"
"Name of temporary buffer for markdown command output.")
;;; Global Variables ==========================================================
(defvar markdown-reference-label-history nil
"History of used reference labels.")
(defvar markdown-live-preview-mode nil
"Sentinel variable for command `markdown-live-preview-mode'.")
(defvar markdown-gfm-language-history nil
"History list of languages used in the current buffer in GFM code blocks.")
;;; Customizable Variables ====================================================
(defvar markdown-mode-hook nil
"Hook run when entering Markdown mode.")
(defvar markdown-before-export-hook nil
"Hook run before running Markdown to export XHTML output.
The hook may modify the buffer, which will be restored to it's
original state after exporting is complete.")
(defvar markdown-after-export-hook nil
"Hook run after XHTML output has been saved.
Any changes to the output buffer made by this hook will be saved.")
(defgroup markdown nil
"Major mode for editing text files in Markdown format."
:prefix "markdown-"
:group 'text
:link '(url-link "https://jblevins.org/projects/markdown-mode/"))
(defcustom markdown-command "markdown"
"Command to run markdown."
:group 'markdown
:type '(choice (string :tag "Shell command") function))
(defcustom markdown-command-needs-filename nil
"Set to non-nil if `markdown-command' does not accept input from stdin.
Instead, it will be passed a filename as the final command line
option. As a result, you will only be able to run Markdown from
buffers which are visiting a file."
:group 'markdown
:type 'boolean)
(defcustom markdown-open-command nil
"Command used for opening Markdown files directly.
For example, a standalone Markdown previewer. This command will
be called with a single argument: the filename of the current
buffer. It can also be a function, which will be called without
arguments."
:group 'markdown
:type '(choice file function (const :tag "None" nil)))
(defcustom markdown-hr-strings
'("-------------------------------------------------------------------------------"
"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
"---------------------------------------"
"* * * * * * * * * * * * * * * * * * * *"
"---------"
"* * * * *")
"Strings to use when inserting horizontal rules.
The first string in the list will be the default when inserting a
horizontal rule. Strings should be listed in decreasing order of
prominence (as in headings from level one to six) for use with
promotion and demotion functions."
:group 'markdown
:type '(repeat string))
(defcustom markdown-bold-underscore nil
"Use two underscores when inserting bold text instead of two asterisks."
:group 'markdown
:type 'boolean)
(defcustom markdown-italic-underscore nil
"Use underscores when inserting italic text instead of asterisks."
:group 'markdown
:type 'boolean)
(defcustom markdown-marginalize-headers nil
"When non-nil, put opening atx header markup in a left margin.
This setting goes well with `markdown-asymmetric-header'. But
sadly it conflicts with `linum-mode' since they both use the
same margin."
:group 'markdown
:type 'boolean
:safe 'booleanp
:package-version '(markdown-mode . "2.4"))
(defcustom markdown-marginalize-headers-margin-width 6
"Character width of margin used for marginalized headers.
The default value is based on there being six heading levels
defined by Markdown and HTML. Increasing this produces extra
whitespace on the left. Decreasing it may be preferred when
fewer than six nested heading levels are used."
:group 'markdown
:type 'natnump
:safe 'natnump
:package-version '(markdown-mode . "2.4"))
(defcustom markdown-asymmetric-header nil
"Determines if atx header style will be asymmetric.
Set to a non-nil value to use asymmetric header styling, placing
header markup only at the beginning of the line. By default,
balanced markup will be inserted at the beginning and end of the
line around the header title."
:group 'markdown
:type 'boolean)
(defcustom markdown-indent-function 'markdown-indent-line
"Function to use to indent."
:group 'markdown
:type 'function)
(defcustom markdown-indent-on-enter t
"Determines indentation behavior when pressing \\[newline].
Possible settings are nil, t, and 'indent-and-new-item.
When non-nil, pressing \\[newline] will call `newline-and-indent'
to indent the following line according to the context using
`markdown-indent-function'. In this case, note that
\\[electric-newline-and-maybe-indent] can still be used to insert
a newline without indentation.
When set to 'indent-and-new-item and the point is in a list item
when \\[newline] is pressed, the list will be continued on the next
line, where a new item will be inserted.
When set to nil, simply call `newline' as usual. In this case,
you can still indent lines using \\[markdown-cycle] and continue
lists with \\[markdown-insert-list-item].
Note that this assumes the variable `electric-indent-mode' is
non-nil (enabled). When it is *disabled*, the behavior of
\\[newline] and `\\[electric-newline-and-maybe-indent]' are
reversed."
:group 'markdown
:type '(choice (const :tag "Don't automatically indent" nil)
(const :tag "Automatically indent" t)
(const :tag "Automatically indent and insert new list items" indent-and-new-item)))
(defcustom markdown-enable-wiki-links nil
"Syntax highlighting for wiki links.
Set this to a non-nil value to turn on wiki link support by default.
Support can be toggled later using the `markdown-toggle-wiki-links'
function or \\[markdown-toggle-wiki-links]."
:group 'markdown
:type 'boolean
:safe 'booleanp
:package-version '(markdown-mode . "2.2"))
(defcustom markdown-wiki-link-alias-first t
"When non-nil, treat aliased wiki links like [[alias text|PageName]].
Otherwise, they will be treated as [[PageName|alias text]]."
:group 'markdown
:type 'boolean
:safe 'booleanp)
(defcustom markdown-wiki-link-search-subdirectories nil
"When non-nil, search for wiki link targets in subdirectories.
This is the default search behavior for GitHub and is
automatically set to t in `gfm-mode'."
:group 'markdown
:type 'boolean
:safe 'booleanp
:package-version '(markdown-mode . "2.2"))
(defcustom markdown-wiki-link-search-parent-directories nil
"When non-nil, search for wiki link targets in parent directories.
This is the default search behavior of Ikiwiki."
:group 'markdown
:type 'boolean
:safe 'booleanp
:package-version '(markdown-mode . "2.2"))
(defcustom markdown-wiki-link-fontify-missing nil
"When non-nil, change wiki link face according to existence of target files.
This is expensive because it requires checking for the file each time the buffer
changes or the user switches windows. It is disabled by default because it may
cause lag when typing on slower machines."
:group 'markdown
:type 'boolean
:safe 'booleanp
:package-version '(markdown-mode . "2.2"))
(defcustom markdown-uri-types
'("acap" "cid" "data" "dav" "fax" "file" "ftp"
"gopher" "http" "https" "imap" "ldap" "mailto"
"mid" "message" "modem" "news" "nfs" "nntp"
"pop" "prospero" "rtsp" "service" "sip" "tel"
"telnet" "tip" "urn" "vemmi" "wais")
"Link types for syntax highlighting of URIs."
:group 'markdown
:type '(repeat (string :tag "URI scheme")))
(defcustom markdown-url-compose-char
'(?∞ ?… ?⋯ ?# ?★ ?⚓)
"Placeholder character for hidden URLs.
This may be a single character or a list of characters. In case
of a list, the first one that satisfies `char-displayable-p' will
be used."
:type '(choice
(character :tag "Single URL replacement character")
(repeat :tag "List of possible URL replacement characters"
character))
:package-version '(markdown-mode . "2.3"))
(defcustom markdown-blockquote-display-char
'("" "" ">")
"String to display when hiding blockquote markup.
This may be a single string or a list of string. In case of a
list, the first one that satisfies `char-displayable-p' will be
used."
:type 'string
:type '(choice
(string :tag "Single blockquote display string")
(repeat :tag "List of possible blockquote display strings" string))
:package-version '(markdown-mode . "2.3"))
(defcustom markdown-hr-display-char
'(?─ ?━ ?-)
"Character for hiding horizontal rule markup.
This may be a single character or a list of characters. In case
of a list, the first one that satisfies `char-displayable-p' will
be used."
:group 'markdown
:type '(choice
(character :tag "Single HR display character")
(repeat :tag "List of possible HR display characters" character))
:package-version '(markdown-mode . "2.3"))
(defcustom markdown-definition-display-char
'(?⁘ ?⁙ ?≡ ?⌑ ?◊ ?:)
"Character for replacing definition list markup.
This may be a single character or a list of characters. In case
of a list, the first one that satisfies `char-displayable-p' will
be used."
:type '(choice
(character :tag "Single definition list character")
(repeat :tag "List of possible definition list characters" character))
:package-version '(markdown-mode . "2.3"))
(defcustom markdown-enable-math nil
"Syntax highlighting for inline LaTeX and itex expressions.
Set this to a non-nil value to turn on math support by default.
Math support can be enabled, disabled, or toggled later using
`markdown-toggle-math' or \\[markdown-toggle-math]."
:group 'markdown
:type 'boolean
:safe 'booleanp)
(make-variable-buffer-local 'markdown-enable-math)
(defcustom markdown-enable-html t
"Enable font-lock support for HTML tags and attributes."
:group 'markdown
:type 'boolean
:safe 'booleanp
:package-version '(markdown-mode . "2.4"))
(defcustom markdown-css-paths nil
"URL of CSS file to link to in the output XHTML."
:group 'markdown
:type '(repeat (string :tag "CSS File Path")))
(defcustom markdown-content-type "text/html"
"Content type string for the http-equiv header in XHTML output.
When set to an empty string, this attribute is omitted. Defaults to
`text/html'."
:group 'markdown
:type 'string)
(defcustom markdown-coding-system nil
"Character set string for the http-equiv header in XHTML output.
Defaults to `buffer-file-coding-system' (and falling back to
`utf-8' when not available). Common settings are `iso-8859-1'
and `iso-latin-1'. Use `list-coding-systems' for more choices."
:group 'markdown
:type 'coding-system)
(defcustom markdown-export-kill-buffer t
"Kill output buffer after HTML export.
When non-nil, kill the HTML output buffer after
exporting with `markdown-export'."
:group 'markdown
:type 'boolean
:safe 'booleanp
:package-version '(markdown-mode . "2.4"))
(defcustom markdown-xhtml-header-content ""
"Additional content to include in the XHTML <head> block."
:group 'markdown
:type 'string)
(defcustom markdown-xhtml-body-preamble ""
"Content to include in the XHTML <body> block, before the output."
:group 'markdown
:type 'string
:safe 'stringp
:package-version '(markdown-mode . "2.4"))
(defcustom markdown-xhtml-body-epilogue ""
"Content to include in the XHTML <body> block, after the output."
:group 'markdown
:type 'string
:safe 'stringp
:package-version '(markdown-mode . "2.4"))
(defcustom markdown-xhtml-standalone-regexp
"^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
"Regexp indicating whether `markdown-command' output is standalone XHTML."
:group 'markdown
:type 'regexp)
(defcustom markdown-link-space-sub-char "_"
"Character to use instead of spaces when mapping wiki links to filenames."
:group 'markdown
:type 'string)
(defcustom markdown-reference-location 'header
"Position where new reference definitions are inserted in the document."
:group 'markdown
:type '(choice (const :tag "At the end of the document" end)
(const :tag "Immediately after the current block" immediately)
(const :tag "At the end of the subtree" subtree)
(const :tag "Before next header" header)))
(defcustom markdown-footnote-location 'end
"Position where new footnotes are inserted in the document."
:group 'markdown
:type '(choice (const :tag "At the end of the document" end)
(const :tag "Immediately after the current block" immediately)
(const :tag "At the end of the subtree" subtree)
(const :tag "Before next header" header)))
(defcustom markdown-footnote-display '((raise 0.2) (height 0.8))
"Display specification for footnote markers and inline footnotes.
By default, footnote text is reduced in size and raised. Set to
nil to disable this."
:group 'markdown
:type '(choice (sexp :tag "Display specification")
(const :tag "Don't set display property" nil))
:package-version '(markdown-mode . "2.4"))
(defcustom markdown-sub-superscript-display
'(((raise -0.3) (height 0.7)) . ((raise 0.3) (height 0.7)))
"Display specification for subscript and superscripts.
The car is used for subscript, the cdr is used for superscripts."
:group 'markdown
:type '(cons (choice (sexp :tag "Subscript form")
(const :tag "No lowering" nil))
(choice (sexp :tag "Superscript form")
(const :tag "No raising" nil)))
:package-version '(markdown-mode . "2.4"))
(defcustom markdown-unordered-list-item-prefix " * "
"String inserted before unordered list items."
:group 'markdown
:type 'string)
(defcustom markdown-nested-imenu-heading-index t
"Use nested or flat imenu heading index.
A nested index may provide more natural browsing from the menu,
but a flat list may allow for faster keyboard navigation via tab
completion."
:group 'markdown
:type 'boolean
:safe 'booleanp
:package-version '(markdown-mode . "2.2"))
(defcustom markdown-add-footnotes-to-imenu t
"Add footnotes to end of imenu heading index."
:group 'markdown
:type 'boolean
:safe 'booleanp
:package-version '(markdown-mode . "2.4"))
(defcustom markdown-make-gfm-checkboxes-buttons t
"When non-nil, make GFM checkboxes into buttons."
:group 'markdown
:type 'boolean)
(defcustom markdown-use-pandoc-style-yaml-metadata nil
"When non-nil, allow YAML metadata anywhere in the document."
:group 'markdown
:type 'boolean)
(defcustom markdown-split-window-direction 'any
"Preference for splitting windows for static and live preview.
The default value is 'any, which instructs Emacs to use
`split-window-sensibly' to automatically choose how to split
windows based on the values of `split-width-threshold' and
`split-height-threshold' and the available windows. To force
vertically split (left and right) windows, set this to 'vertical
or 'right. To force horizontally split (top and bottom) windows,
set this to 'horizontal or 'below."
:group 'markdown
:type '(choice (const :tag "Automatic" any)
(const :tag "Right (vertical)" right)
(const :tag "Below (horizontal)" below))
:package-version '(markdown-mode . "2.2"))
(defcustom markdown-live-preview-window-function
'markdown-live-preview-window-eww
"Function to display preview of Markdown output within Emacs.
Function must update the buffer containing the preview and return
the buffer."
:group 'markdown
:type 'function)
(defcustom markdown-live-preview-delete-export 'delete-on-destroy
"Delete exported HTML file when using `markdown-live-preview-export'.
If set to 'delete-on-export, delete on every export. When set to
'delete-on-destroy delete when quitting from command
`markdown-live-preview-mode'. Never delete if set to nil."
:group 'markdown
:type '(choice
(const :tag "Delete on every export" delete-on-export)
(const :tag "Delete when quitting live preview" delete-on-destroy)
(const :tag "Never delete" nil)))
(defcustom markdown-list-indent-width 4
"Depth of indentation for markdown lists.
Used in `markdown-demote-list-item' and
`markdown-promote-list-item'."
:group 'markdown
:type 'integer)
(defcustom markdown-enable-prefix-prompts t
"Display prompts for certain prefix commands.
Set to nil to disable these prompts."
:group 'markdown
:type 'boolean
:safe 'booleanp
:package-version '(markdown-mode . "2.3"))
(defcustom markdown-gfm-additional-languages nil
"Extra languages made available when inserting GFM code blocks.
Language strings must have be trimmed of whitespace and not
contain any curly braces. They may be of arbitrary
capitalization, though."
:group 'markdown
:type '(repeat (string :validate markdown-validate-language-string)))
(defcustom markdown-gfm-use-electric-backquote t
"Use `markdown-electric-backquote' when backquote is hit three times."
:group 'markdown
:type 'boolean)
(defcustom markdown-gfm-downcase-languages t
"If non-nil, downcase suggested languages.
This applies to insertions done with
`markdown-electric-backquote'."
:group 'markdown
:type 'boolean)
(defcustom markdown-edit-code-block-default-mode 'normal-mode
"Default mode to use for editing code blocks.
This mode is used when automatic detection fails, such as for GFM
code blocks with no language specified."
:group 'markdown
:type '(choice function (const :tag "None" nil))
:package-version '(markdown-mode . "2.4"))
(defcustom markdown-gfm-uppercase-checkbox nil
"If non-nil, use [X] for completed checkboxes, [x] otherwise."
:group 'markdown
:type 'boolean
:safe 'booleanp)
(defcustom markdown-hide-urls nil
"Hide URLs of inline links and reference tags of reference links.
Such URLs will be replaced by a single customizable
character, defined by `markdown-url-compose-char', but are still part
of the buffer. Links can be edited interactively with
\\[markdown-insert-link] or, for example, by deleting the final
parenthesis to remove the invisibility property. You can also
hover your mouse pointer over the link text to see the URL.
Set this to a non-nil value to turn this feature on by default.
You can interactively set the value of this variable by calling
`markdown-toggle-url-hiding', pressing \\[markdown-toggle-url-hiding],
or from the menu Markdown > Links & Images menu."
:group 'markdown
:type 'boolean
:safe 'booleanp
:package-version '(markdown-mode . "2.3"))
(make-variable-buffer-local 'markdown-hide-urls)
(defcustom markdown-translate-filename-function #'identity
"Function to use to translate filenames when following links.
\\<markdown-mode-map>\\[markdown-follow-thing-at-point] and \\[markdown-follow-link-at-point]
call this function with the filename as only argument whenever
they encounter a filename (instead of a URL) to be visited and
use its return value instead of the filename in the link. For
example, if absolute filenames are actually relative to a server
root directory, you can set
`markdown-translate-filename-function' to a function that
prepends the root directory to the given filename."
:group 'markdown
:type 'function
:risky t
:package-version '(markdown-mode . "2.4"))
(defcustom markdown-max-image-size nil
"Maximum width and height for displayed inline images.
This variable may be nil or a cons cell (MAX-WIDTH . MAX-HEIGHT).
When nil, use the actual size. Otherwise, use ImageMagick to
resize larger images to be of the given maximum dimensions. This
requires Emacs to be built with ImageMagick support."
:group 'markdown
:package-version '(markdown-mode . "2.4")
:type '(choice
(const :tag "Use actual image width" nil)
(cons (choice (sexp :tag "Maximum width in pixels")
(const :tag "No maximum width" nil))
(choice (sexp :tag "Maximum height in pixels")
(const :tag "No maximum height" nil)))))
;;; Markdown-Specific `rx' Macro ==============================================
;; Based on python-rx from python.el.
(eval-and-compile
(defconst markdown-rx-constituents
`((newline . ,(rx "\n"))
(indent . ,(rx (or (repeat 4 " ") "\t")))
(block-end . ,(rx (and (or (one-or-more (zero-or-more blank) "\n") line-end))))
(numeral . ,(rx (and (one-or-more (any "0-9#")) ".")))
(bullet . ,(rx (any "*+:-")))
(list-marker . ,(rx (or (and (one-or-more (any "0-9#")) ".")
(any "*+:-"))))
(checkbox . ,(rx "[" (any " xX") "]")))
"Markdown-specific sexps for `markdown-rx'")
(defun markdown-rx-to-string (form &optional no-group)
"Markdown mode specialized `rx-to-string' function.
This variant supports named Markdown expressions in FORM.
NO-GROUP non-nil means don't put shy groups around the result."
(let ((rx-constituents (append markdown-rx-constituents rx-constituents)))
(rx-to-string form no-group)))
(defmacro markdown-rx (&rest regexps)
"Markdown mode specialized rx macro.
This variant of `rx' supports common Markdown named REGEXPS."
(cond ((null regexps)
(error "No regexp"))
((cdr regexps)
(markdown-rx-to-string `(and ,@regexps) t))
(t
(markdown-rx-to-string (car regexps) t)))))
;;; Regular Expressions =======================================================
(defconst markdown-regex-comment-start
"<!--"
"Regular expression matches HTML comment opening.")
(defconst markdown-regex-comment-end
"--[ \t]*>"
"Regular expression matches HTML comment closing.")
(defconst markdown-regex-link-inline
"\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)\\((\\)\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?\\()\\)"
"Regular expression for a [text](file) or an image link ![text](file).
Group 1 matches the leading exclamation point (optional).
Group 2 matches the opening square bracket.
Group 3 matches the text inside the square brackets.
Group 4 matches the closing square bracket.
Group 5 matches the opening parenthesis.
Group 6 matches the URL.
Group 7 matches the title (optional).
Group 8 matches the closing parenthesis.")
(defconst markdown-regex-link-reference
"\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)[ ]?\\(\\[\\)\\([^]]*?\\)\\(\\]\\)"
"Regular expression for a reference link [text][id].
Group 1 matches the leading exclamation point (optional).
Group 2 matches the opening square bracket for the link text.
Group 3 matches the text inside the square brackets.
Group 4 matches the closing square bracket for the link text.
Group 5 matches the opening square bracket for the reference label.
Group 6 matches the reference label.
Group 7 matches the closing square bracket for the reference label.")
(defconst markdown-regex-reference-definition
"^ \\{0,3\\}\\(\\[\\)\\([^]\n]+?\\)\\(\\]\\)\\(:\\)\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
"Regular expression for a reference definition.
Group 1 matches the opening square bracket.
Group 2 matches the reference label.
Group 3 matches the closing square bracket.
Group 4 matches the colon.
Group 5 matches the URL.
Group 6 matches the title attribute (optional).")
(defconst markdown-regex-footnote
"\\(\\[\\^\\)\\(.+?\\)\\(\\]\\)"
"Regular expression for a footnote marker [^fn].
Group 1 matches the opening square bracket and carat.
Group 2 matches only the label, without the surrounding markup.
Group 3 matches the closing square bracket.")
(defconst markdown-regex-header
"^\\(?:\\([^\r\n\t -].*\\)\n\\(?:\\(=+\\)\\|\\(-+\\)\\)\\|\\(#+[ \t]+\\)\\(.*?\\)\\([ \t]*#*\\)\\)$"
"Regexp identifying Markdown headings.
Group 1 matches the text of a setext heading.
Group 2 matches the underline of a level-1 setext heading.
Group 3 matches the underline of a level-2 setext heading.
Group 4 matches the opening hash marks of an atx heading and whitespace.
Group 5 matches the text, without surrounding whitespace, of an atx heading.
Group 6 matches the closing whitespace and hash marks of an atx heading.")
(defconst markdown-regex-header-setext
"^\\([^\r\n\t -].*\\)\n\\(=+\\|-+\\)$"
"Regular expression for generic setext-style (underline) headers.")
(defconst markdown-regex-header-atx
"^\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
"Regular expression for generic atx-style (hash mark) headers.")
(defconst markdown-regex-hr
(rx line-start
(group (or (and (repeat 3 (and "*" (? " "))) (* (any "* ")))
(and (repeat 3 (and "-" (? " "))) (* (any "- ")))
(and (repeat 3 (and "_" (? " "))) (* (any "_ ")))))
line-end)
"Regular expression for matching Markdown horizontal rules.")
(defconst markdown-regex-code
"\\(?:\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(?:.\\|\n[^\n]\\)*?[^`]\\)\\(\\2\\)\\)\\(?:[^`]\\|\\'\\)"
"Regular expression for matching inline code fragments.
Group 1 matches the entire code fragment including the backquotes.
Group 2 matches the opening backquotes.
Group 3 matches the code fragment itself, without backquotes.
Group 4 matches the closing backquotes.
The leading, unnumbered group ensures that the leading backquote
character is not escaped.
The last group, also unnumbered, requires that the character
following the code fragment is not a backquote.
Note that \\(?:.\\|\n[^\n]\\) matches any character, including newlines,
but not two newlines in a row.")
(defconst markdown-regex-kbd
"\\(<kbd>\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(</kbd>\\)"
"Regular expression for matching <kbd> tags.
Groups 1 and 3 match the opening and closing tags.
Group 2 matches the key sequence.")
(defconst markdown-regex-gfm-code-block-open
"^[[:blank:]]*\\(```\\)\\([[:blank:]]*{?[[:blank:]]*\\)\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$"
"Regular expression matching opening of GFM code blocks.
Group 1 matches the opening three backquotes and any following whitespace.
Group 2 matches the opening brace (optional) and surrounding whitespace.
Group 3 matches the language identifier (optional).
Group 4 matches the info string (optional).
Group 5 matches the closing brace (optional), whitespace, and newline.
Groups need to agree with `markdown-regex-tilde-fence-begin'.")
(defconst markdown-regex-gfm-code-block-close
"^[[:blank:]]*\\(```\\)\\(\\s *?\\)$"
"Regular expression matching closing of GFM code blocks.
Group 1 matches the closing three backquotes.
Group 2 matches any whitespace and the final newline.")
(defconst markdown-regex-pre
"^\\( \\|\t\\).*$"
"Regular expression for matching preformatted text sections.")
(defconst markdown-regex-list
(markdown-rx line-start
;; 1. Leading whitespace
(group (* blank))
;; 2. List marker: a numeral, bullet, or colon
(group list-marker)
;; 3. Trailing whitespace
(group (+ blank))
;; 4. Optional checkbox for GFM task list items
(opt (group (and checkbox (* blank)))))
"Regular expression for matching list items.")
(defconst markdown-regex-bold
"\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
"Regular expression for matching bold text.
Group 1 matches the character before the opening asterisk or
underscore, if any, ensuring that it is not a backslash escape.
Group 2 matches the entire expression, including delimiters.
Groups 3 and 5 matches the opening and closing delimiters.
Group 4 matches the text inside the delimiters.")
(defconst markdown-regex-italic
"\\(?:^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t*]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
"Regular expression for matching italic text.
The leading unnumbered matches the character before the opening
asterisk or underscore, if any, ensuring that it is not a
backslash escape.
Group 1 matches the entire expression, including delimiters.
Groups 2 and 4 matches the opening and closing delimiters.
Group 3 matches the text inside the delimiters.")
(defconst markdown-regex-strike-through
"\\(^\\|[^\\]\\)\\(\\(~~\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(~~\\)\\)"
"Regular expression for matching strike-through text.
Group 1 matches the character before the opening tilde, if any,
ensuring that it is not a backslash escape.
Group 2 matches the entire expression, including delimiters.
Groups 3 and 5 matches the opening and closing delimiters.
Group 4 matches the text inside the delimiters.")
(defconst markdown-regex-gfm-italic
"\\(?:^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\2\\|[^ ]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
"Regular expression for matching italic text in GitHub Flavored Markdown.
Underscores in words are not treated as special.
Group 1 matches the entire expression, including delimiters.
Groups 2 and 4 matches the opening and closing delimiters.
Group 3 matches the text inside the delimiters.")
(defconst markdown-regex-blockquote
"^[ \t]*\\([A-Z]?>\\)\\([ \t]*\\)\\(.*\\)$"
"Regular expression for matching blockquote lines.
Also accounts for a potential capital letter preceding the angle
bracket, for use with Leanpub blocks (asides, warnings, info
blocks, etc.).
Group 1 matches the leading angle bracket.
Group 2 matches the separating whitespace.
Group 3 matches the text.")
(defconst markdown-regex-line-break
"[^ \n\t][ \t]*\\( \\)$"
"Regular expression for matching line breaks.")
(defconst markdown-regex-wiki-link
"\\(?:^\\|[^\\]\\)\\(\\(\\[\\[\\)\\([^]|]+\\)\\(?:\\(|\\)\\([^]]+\\)\\)?\\(\\]\\]\\)\\)"
"Regular expression for matching wiki links.
This matches typical bracketed [[WikiLinks]] as well as 'aliased'
wiki links of the form [[PageName|link text]].
The meanings of the first and second components depend
on the value of `markdown-wiki-link-alias-first'.
Group 1 matches the entire link.
Group 2 matches the opening square brackets.
Group 3 matches the first component of the wiki link.
Group 4 matches the pipe separator, when present.
Group 5 matches the second component of the wiki link, when present.
Group 6 matches the closing square brackets.")
(defconst markdown-regex-uri
(concat "\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+\\)")
"Regular expression for matching inline URIs.")
(defconst markdown-regex-angle-uri
(concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
"Regular expression for matching inline URIs in angle brackets.")
(defconst markdown-regex-email
"<\\(\\(?:\\sw\\|\\s_\\|\\s.\\)+@\\(?:\\sw\\|\\s_\\|\\s.\\)+\\)>"
"Regular expression for matching inline email addresses.")
(defsubst markdown-make-regex-link-generic ()
"Make regular expression for matching any recognized link."
(concat "\\(?:" markdown-regex-link-inline
(when markdown-enable-wiki-links
(concat "\\|" markdown-regex-wiki-link))
"\\|" markdown-regex-link-reference
"\\|" markdown-regex-angle-uri "\\)"))
(defconst markdown-regex-gfm-checkbox
" \\(\\[[ xX]\\]\\) "
"Regular expression for matching GFM checkboxes.
Group 1 matches the text to become a button.")
(defconst markdown-regex-blank-line
"^[[:blank:]]*$"
"Regular expression that matches a blank line.")
(defconst markdown-regex-block-separator
"\n[\n\t\f ]*\n"
"Regular expression for matching block boundaries.")
(defconst markdown-regex-block-separator-noindent
(concat "\\(\\`\\|\\(" markdown-regex-block-separator "\\)[^\n\t\f ]\\)")
"Regexp for block separators before lines with no indentation.")
(defconst markdown-regex-math-inline-single
"\\(?:^\\|[^\\]\\)\\(\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\)"
"Regular expression for itex $..$ math mode expressions.
Groups 1 and 3 match the opening and closing dollar signs.
Group 2 matches the mathematical expression contained within.")
(defconst markdown-regex-math-inline-double
"\\(?:^\\|[^\\]\\)\\(\\$\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\$\\)"
"Regular expression for itex $$..$$ math mode expressions.
Groups 1 and 3 match opening and closing dollar signs.
Group 2 matches the mathematical expression contained within.")
(defconst markdown-regex-math-display
(rx line-start (* blank)
(group (group (repeat 1 2 "\\")) "[")
(group (*? anything))
(group (backref 2) "]")
line-end)
"Regular expression for \[..\] or \\[..\\] display math.
Groups 1 and 4 match the opening and closing markup.
Group 3 matches the mathematical expression contained within.
Group 2 matches the opening slashes, and is used internally to
match the closing slashes.")
(defsubst markdown-make-tilde-fence-regex (num-tildes &optional end-of-line)
"Return regexp matching a tilde code fence at least NUM-TILDES long.
END-OF-LINE is the regexp construct to indicate end of line; $ if
missing."
(format "%s%d%s%s" "^[[:blank:]]*\\([~]\\{" num-tildes ",\\}\\)"
(or end-of-line "$")))
(defconst markdown-regex-tilde-fence-begin
(markdown-make-tilde-fence-regex
3 "\\([[:blank:]]*{?\\)[[:blank:]]*\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$")
"Regular expression for matching tilde-fenced code blocks.
Group 1 matches the opening tildes.
Group 2 matches (optional) opening brace and surrounding whitespace.
Group 3 matches the language identifier (optional).
Group 4 matches the info string (optional).
Group 5 matches the closing brace (optional) and any surrounding whitespace.
Groups need to agree with `markdown-regex-gfm-code-block-open'.")
(defconst markdown-regex-declarative-metadata
"^\\([[:alpha:]][[:alpha:] _-]*?\\)\\([:=][ \t]*\\)\\(.*\\)$"
"Regular expression for matching declarative metadata statements.
This matches MultiMarkdown metadata as well as YAML and TOML
assignments such as the following:
variable: value
or
variable = value")
(defconst markdown-regex-pandoc-metadata
"^\\(%\\)\\([ \t]*\\)\\(.*\\(?:\n[ \t]+.*\\)*\\)"
"Regular expression for matching Pandoc metadata.")
(defconst markdown-regex-yaml-metadata-border
"\\(-\\{3\\}\\)$"
"Regular expression for matching YAML metadata.")
(defconst markdown-regex-yaml-pandoc-metadata-end-border
"^\\(\\.\\{3\\}\\|\\-\\{3\\}\\)$"
"Regular expression for matching YAML metadata end borders.")
(defsubst markdown-get-yaml-metadata-start-border ()
"Return YAML metadata start border depending upon whether Pandoc is used."
(concat
(if markdown-use-pandoc-style-yaml-metadata "^" "\\`")
markdown-regex-yaml-metadata-border))
(defsubst markdown-get-yaml-metadata-end-border (_)
"Return YAML metadata end border depending upon whether Pandoc is used."
(if markdown-use-pandoc-style-yaml-metadata
markdown-regex-yaml-pandoc-metadata-end-border
markdown-regex-yaml-metadata-border))
(defconst markdown-regex-inline-attributes
"[ \t]*\\({:?\\)[ \t]*\\(\\(#[[:alpha:]_.:-]+\\|\\.[[:alpha:]_.:-]+\\|\\w+=['\"]?[^\n'\"]*['\"]?\\),?[ \t]*\\)+\\(}\\)[ \t]*$"
"Regular expression for matching inline identifiers or attribute lists.
Compatible with Pandoc, Python Markdown, PHP Markdown Extra, and Leanpub.")
(defconst markdown-regex-leanpub-sections
(concat
"^\\({\\)\\("
(regexp-opt '("frontmatter" "mainmatter" "backmatter" "appendix" "pagebreak"))
"\\)\\(}\\)[ \t]*\n")
"Regular expression for Leanpub section markers and related syntax.")
(defconst markdown-regex-sub-superscript
"\\(?:^\\|[^\\~^]\\)\\(\\([~^]\\)\\([[:alnum:]]+\\)\\(\\2\\)\\)"
"The regular expression matching a sub- or superscript.
The leading un-numbered group matches the character before the
opening tilde or carat, if any, ensuring that it is not a
backslash escape, carat, or tilde.
Group 1 matches the entire expression, including markup.
Group 2 matches the opening markup--a tilde or carat.
Group 3 matches the text inside the delimiters.
Group 4 matches the closing markup--a tilde or carat.")
(defconst markdown-regex-include
"^\\(<<\\)\\(?:\\(\\[\\)\\(.*\\)\\(\\]\\)\\)?\\(?:\\((\\)\\(.*\\)\\()\\)\\)?\\(?:\\({\\)\\(.*\\)\\(}\\)\\)?$"
"Regular expression matching common forms of include syntax.
Marked 2, Leanpub, and other processors support some of these forms:
<<[sections/section1.md]
<<(folder/filename)
<<[Code title](folder/filename)
<<{folder/raw_file.html}
Group 1 matches the opening two angle brackets.
Groups 2-4 match the opening square bracket, the text inside,
and the closing square bracket, respectively.
Groups 5-7 match the opening parenthesis, the text inside, and
the closing parenthesis.
Groups 8-10 match the opening brace, the text inside, and the brace.")
(defconst markdown-regex-pandoc-inline-footnote
"\\(\\^\\)\\(\\[\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(\\]\\)"
"Regular expression for Pandoc inline footnote^[footnote text].
Group 1 matches the opening caret.
Group 2 matches the opening square bracket.
Group 3 matches the footnote text, without the surrounding markup.
Group 4 matches the closing square bracket.")
(defconst markdown-regex-html-attr
"\\(\\<[[:alpha:]:-]+\\>\\)\\(\\s-*\\(=\\)\\s-*\\(\".*?\"\\|'.*?'\\|[^'\">[:space:]]+\\)?\\)?"
"Regular expression for matching HTML attributes and values.
Group 1 matches the attribute name.
Group 2 matches the following whitespace, equals sign, and value, if any.
Group 3 matches the equals sign, if any.
Group 4 matches single-, double-, or un-quoted attribute values.")
(defconst markdown-regex-html-tag
(concat "\\(</?\\)\\(\\w+\\)\\(\\(\\s-+" markdown-regex-html-attr
"\\)+\\s-*\\|\\s-*\\)\\(/?>\\)")
"Regular expression for matching HTML tags.
Groups 1 and 9 match the beginning and ending angle brackets and slashes.
Group 2 matches the tag name.
Group 3 matches all attributes and whitespace following the tag name.")
(defconst markdown-regex-html-entity
"\\(&#?[[:alnum:]]+;\\)"
"Regular expression for matching HTML entities.")
;;; Syntax ====================================================================
(defvar markdown--syntax-properties
(list 'markdown-tilde-fence-begin nil
'markdown-tilde-fence-end nil
'markdown-fenced-code nil
'markdown-yaml-metadata-begin nil
'markdown-yaml-metadata-end nil
'markdown-yaml-metadata-section nil
'markdown-gfm-block-begin nil
'markdown-gfm-block-end nil
'markdown-gfm-code nil
'markdown-list-item nil
'markdown-pre nil
'markdown-blockquote nil
'markdown-hr nil
'markdown-comment nil
'markdown-heading nil
'markdown-heading-1-setext nil
'markdown-heading-2-setext nil
'markdown-heading-1-atx nil
'markdown-heading-2-atx nil
'markdown-heading-3-atx nil
'markdown-heading-4-atx nil
'markdown-heading-5-atx nil
'markdown-heading-6-atx nil
'markdown-metadata-key nil
'markdown-metadata-value nil
'markdown-metadata-markup nil)
"Property list of all Markdown syntactic properties.")
(defsubst markdown-in-comment-p (&optional pos)
"Return non-nil if POS is in a comment.
If POS is not given, use point instead."
(get-text-property (or pos (point)) 'markdown-comment))
(defun markdown-syntax-propertize-extend-region (start end)
"Extend START to END region to include an entire block of text.
This helps improve syntax analysis for block constructs.
Returns a cons (NEW-START . NEW-END) or nil if no adjustment should be made.
Function is called repeatedly until it returns nil. For details, see
`syntax-propertize-extend-region-functions'."
(save-match-data
(save-excursion
(let* ((new-start (progn (goto-char start)
(skip-chars-forward "\n")
(if (re-search-backward "\n\n" nil t)
(min start (match-end 0))
(point-min))))
(new-end (progn (goto-char end)
(skip-chars-backward "\n")
(if (re-search-forward "\n\n" nil t)
(max end (match-beginning 0))
(point-max))))
(code-match (markdown-code-block-at-pos new-start))
(new-start (or (and code-match (cl-first code-match)) new-start))
(code-match (and (< end (point-max)) (markdown-code-block-at-pos end)))
(new-end (or (and code-match (cl-second code-match)) new-end)))
(unless (and (eq new-start start) (eq new-end end))
(cons new-start (min new-end (point-max))))))))
(defun markdown-font-lock-extend-region-function (start end _)
"Used in `jit-lock-after-change-extend-region-functions'.
Delegates to `markdown-syntax-propertize-extend-region'. START
and END are the previous region to refontify."
(let ((res (markdown-syntax-propertize-extend-region start end)))
(when res
;; syntax-propertize-function is not called when character at
;; (point-max) is deleted, but font-lock-extend-region-functions
;; are called. Force a syntax property update in that case.
(when (= end (point-max))
;; This function is called in a buffer modification hook.
;; `markdown-syntax-propertize' doesn't save the match data,
;; so we have to do it here.
(save-match-data
(markdown-syntax-propertize (car res) (cdr res))))
(setq jit-lock-start (car res)
jit-lock-end (cdr res)))))
(defun markdown--cur-list-item-bounds ()
"Return a list describing the list item at point.
Assumes that match data is set for `markdown-regex-list'. See the
documentation for `markdown-cur-list-item-bounds' for the format of
the returned list."
(save-excursion
(let* ((begin (match-beginning 0))
(indent (length (match-string-no-properties 1)))
(nonlist-indent (- (match-end 3) (match-beginning 0)))
(marker (buffer-substring-no-properties
(match-beginning 2) (match-end 3)))
(checkbox (match-string-no-properties 4))
(match (butlast (match-data t)))
(end (markdown-cur-list-item-end nonlist-indent)))
(list begin end indent nonlist-indent marker checkbox match))))
(defun markdown--append-list-item-bounds (marker indent cur-bounds bounds)
"Update list item BOUNDS given list MARKER, block INDENT, and CUR-BOUNDS.
Here, MARKER is a string representing the type of list and INDENT
is an integer giving the indentation, in spaces, of the current
block. CUR-BOUNDS is a list of the form returned by
`markdown-cur-list-item-bounds' and BOUNDS is a list of bounds
values for parent list items. When BOUNDS is nil, it means we are
at baseline (not inside of a nested list)."
(let ((prev-indent (or (cl-third (car bounds)) 0)))
(cond
;; New list item at baseline.
((and marker (null bounds))
(list cur-bounds))
;; List item with greater indentation (four or more spaces).
;; Increase list level by consing CUR-BOUNDS onto BOUNDS.
((and marker (>= indent (+ prev-indent 4)))
(cons cur-bounds bounds))
;; List item with greater or equal indentation (less than four spaces).
;; Keep list level the same by replacing the car of BOUNDS.
((and marker (>= indent prev-indent))
(cons cur-bounds (cdr bounds)))
;; Lesser indentation level.
;; Pop appropriate number of elements off BOUNDS list (e.g., lesser
;; indentation could move back more than one list level). Note
;; that this block need not be the beginning of list item.
((< indent prev-indent)
(while (and (> (length bounds) 1)
(setq prev-indent (cl-third (cadr bounds)))
(< indent (+ prev-indent 4)))
(setq bounds (cdr bounds)))
(cons cur-bounds bounds))
;; Otherwise, do nothing.
(t bounds))))
(defun markdown-syntax-propertize-list-items (start end)
"Propertize list items from START to END.
Stores nested list item information in the `markdown-list-item'
text property to make later syntax analysis easier. The value of
this property is a list with elements of the form (begin . end)
giving the bounds of the current and parent list items."
(save-excursion
(goto-char start)
(let (bounds level pre-regexp)
;; Find a baseline point with zero list indentation
(markdown-search-backward-baseline)
;; Search for all list items between baseline and END
(while (and (< (point) end)
(re-search-forward markdown-regex-list end 'limit))
;; Level of list nesting
(setq level (length bounds))
;; Pre blocks need to be indented one level past the list level
(setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ level)))
(beginning-of-line)
(cond
;; Reset at headings, horizontal rules, and top-level blank lines.
;; Propertize baseline when in range.
((markdown-new-baseline)
(setq bounds nil))
;; Make sure this is not a line from a pre block
((looking-at-p pre-regexp))
;; If not, then update levels and propertize list item when in range.
(t
(let* ((indent (current-indentation))
(cur-bounds (markdown--cur-list-item-bounds))
(first (cl-first cur-bounds))
(last (cl-second cur-bounds))
(marker (cl-fifth cur-bounds)))
(setq bounds (markdown--append-list-item-bounds
marker indent cur-bounds bounds))
(when (and (<= start (point)) (<= (point) end))
(put-text-property first last 'markdown-list-item bounds)))))
(end-of-line)))))
(defun markdown-syntax-propertize-pre-blocks (start end)
"Match preformatted text blocks from START to END."
(save-excursion
(goto-char start)
(let ((levels (markdown-calculate-list-levels))
indent pre-regexp close-regexp open close)
(while (and (< (point) end) (not close))
;; Search for a region with sufficient indentation
(if (null levels)
(setq indent 1)
(setq indent (1+ (length levels))))
(setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
(setq close-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
(cond
;; If not at the beginning of a line, move forward
((not (bolp)) (forward-line))
;; Move past blank lines
((markdown-cur-line-blank-p) (forward-line))
;; At headers and horizontal rules, reset levels
((markdown-new-baseline) (forward-line) (setq levels nil))
;; If the current line has sufficient indentation, mark out pre block
;; The opening should be preceded by a blank line.
((and (markdown-prev-line-blank) (looking-at pre-regexp))
(setq open (match-beginning 0))
(while (and (or (looking-at-p pre-regexp) (markdown-cur-line-blank-p))
(not (eobp)))
(forward-line))
(skip-syntax-backward "-")
(setq close (point)))
;; If current line has a list marker, update levels, move to end of block
((looking-at markdown-regex-list)
(setq levels (markdown-update-list-levels
(match-string 2) (current-indentation) levels))
(markdown-end-of-text-block))
;; If this is the end of the indentation level, adjust levels accordingly.
;; Only match end of indentation level if levels is not the empty list.
((and (car levels) (looking-at-p close-regexp))
(setq levels (markdown-update-list-levels
nil (current-indentation) levels))
(markdown-end-of-text-block))
(t (markdown-end-of-text-block))))
(when (and open close)
;; Set text property data
(put-text-property open close 'markdown-pre (list open close))
;; Recursively search again
(markdown-syntax-propertize-pre-blocks (point) end)))))
(defconst markdown-fenced-block-pairs
`(((,markdown-regex-tilde-fence-begin markdown-tilde-fence-begin)
(markdown-make-tilde-fence-regex markdown-tilde-fence-end)
markdown-fenced-code)
((markdown-get-yaml-metadata-start-border markdown-yaml-metadata-begin)
(markdown-get-yaml-metadata-end-border markdown-yaml-metadata-end)
markdown-yaml-metadata-section)
((,markdown-regex-gfm-code-block-open markdown-gfm-block-begin)
(,markdown-regex-gfm-code-block-close markdown-gfm-block-end)
markdown-gfm-code))
"Mapping of regular expressions to \"fenced-block\" constructs.
These constructs are distinguished by having a distinctive start
and end pattern, both of which take up an entire line of text,
but no special pattern to identify text within the fenced
blocks (unlike blockquotes and indented-code sections).
Each element within this list takes the form:
((START-REGEX-OR-FUN START-PROPERTY)
(END-REGEX-OR-FUN END-PROPERTY)
MIDDLE-PROPERTY)
Each *-REGEX-OR-FUN element can be a regular expression as a string, or a
function which evaluates to same. Functions for START-REGEX-OR-FUN accept no
arguments, but functions for END-REGEX-OR-FUN accept a single numerical argument
which is the length of the first group of the START-REGEX-OR-FUN match, which
can be ignored if unnecessary. `markdown-maybe-funcall-regexp' is used to
evaluate these into \"real\" regexps.
The *-PROPERTY elements are the text properties applied to each part of the
block construct when it is matched using
`markdown-syntax-propertize-fenced-block-constructs'. START-PROPERTY is applied
to the text matching START-REGEX-OR-FUN, END-PROPERTY to END-REGEX-OR-FUN, and
MIDDLE-PROPERTY to the text in between the two. The value of *-PROPERTY is the
`match-data' when the regexp was matched to the text. In the case of
MIDDLE-PROPERTY, the value is a false match data of the form '(begin end), with
begin and end set to the edges of the \"middle\" text. This makes fontification
easier.")
(defun markdown-text-property-at-point (prop)
(get-text-property (point) prop))
(defsubst markdown-maybe-funcall-regexp (object &optional arg)
(cond ((functionp object)
(if arg (funcall object arg) (funcall object)))
((stringp object) object)
(t (error "Object cannot be turned into regex"))))
(defsubst markdown-get-start-fence-regexp ()
"Return regexp to find all \"start\" sections of fenced block constructs.
Which construct is actually contained in the match must be found separately."
(mapconcat
#'identity
(mapcar (lambda (entry) (markdown-maybe-funcall-regexp (caar entry)))
markdown-fenced-block-pairs)
"\\|"))
(defun markdown-get-fenced-block-begin-properties ()
(cl-mapcar (lambda (entry) (cl-cadar entry)) markdown-fenced-block-pairs))
(defun markdown-get-fenced-block-end-properties ()
(cl-mapcar (lambda (entry) (cl-cadadr entry)) markdown-fenced-block-pairs))
(defun markdown-get-fenced-block-middle-properties ()
(cl-mapcar #'cl-third markdown-fenced-block-pairs))
(defun markdown-find-previous-prop (prop &optional lim)
"Find previous place where property PROP is non-nil, up to LIM.
Return a cons of (pos . property). pos is point if point contains
non-nil PROP."
(let ((res
(if (get-text-property (point) prop) (point)
(previous-single-property-change
(point) prop nil (or lim (point-min))))))
(when (and (not (get-text-property res prop))
(> res (point-min))
(get-text-property (1- res) prop))
(cl-decf res))
(when (and res (get-text-property res prop)) (cons res prop))))
(defun markdown-find-next-prop (prop &optional lim)
"Find next place where property PROP is non-nil, up to LIM.
Return a cons of (POS . PROPERTY) where POS is point if point
contains non-nil PROP."
(let ((res
(if (get-text-property (point) prop) (point)
(next-single-property-change
(point) prop nil (or lim (point-max))))))
(when (and res (get-text-property res prop)) (cons res prop))))
(defun markdown-min-of-seq (map-fn seq)
"Apply MAP-FN to SEQ and return element of SEQ with minimum value of MAP-FN."
(cl-loop for el in seq
with min = 1.0e+INF ; infinity
with min-el = nil
do (let ((res (funcall map-fn el)))
(when (< res min)
(setq min res)
(setq min-el el)))
finally return min-el))
(defun markdown-max-of-seq (map-fn seq)
"Apply MAP-FN to SEQ and return element of SEQ with maximum value of MAP-FN."
(cl-loop for el in seq
with max = -1.0e+INF ; negative infinity
with max-el = nil
do (let ((res (funcall map-fn el)))
(when (and res (> res max))
(setq max res)
(setq max-el el)))
finally return max-el))
(defun markdown-find-previous-block ()
"Find previous block.
Detect whether `markdown-syntax-propertize-fenced-block-constructs' was
unable to propertize the entire block, but was able to propertize the beginning
of the block. If so, return a cons of (pos . property) where the beginning of
the block was propertized."
(let ((start-pt (point))
(closest-open
(markdown-max-of-seq
#'car
(cl-remove-if
#'null
(cl-mapcar
#'markdown-find-previous-prop
(markdown-get-fenced-block-begin-properties))))))
(when closest-open
(let* ((length-of-open-match
(let ((match-d
(get-text-property (car closest-open) (cdr closest-open))))
(- (cl-fourth match-d) (cl-third match-d))))
(end-regexp
(markdown-maybe-funcall-regexp
(cl-caadr
(cl-find-if
(lambda (entry) (eq (cl-cadar entry) (cdr closest-open)))
markdown-fenced-block-pairs))
length-of-open-match))
(end-prop-loc
(save-excursion
(save-match-data
(goto-char (car closest-open))
(and (re-search-forward end-regexp start-pt t)
(match-beginning 0))))))
(and (not end-prop-loc) closest-open)))))
(defun markdown-get-fenced-block-from-start (prop)
"Return limits of an enclosing fenced block from its start, using PROP.
Return value is a list usable as `match-data'."
(catch 'no-rest-of-block
(let* ((correct-entry
(cl-find-if
(lambda (entry) (eq (cl-cadar entry) prop))
markdown-fenced-block-pairs))
(begin-of-begin (cl-first (markdown-text-property-at-point prop)))
(middle-prop (cl-third correct-entry))
(end-prop (cl-cadadr correct-entry))
(end-of-end
(save-excursion
(goto-char (match-end 0)) ; end of begin
(unless (eobp) (forward-char))
(let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
(if (not mid-prop-v) ; no middle
(progn
;; try to find end by advancing one
(let ((end-prop-v
(markdown-text-property-at-point end-prop)))
(if end-prop-v (cl-second end-prop-v)
(throw 'no-rest-of-block nil))))
(set-match-data mid-prop-v)
(goto-char (match-end 0)) ; end of middle
(beginning-of-line) ; into end
(cl-second (markdown-text-property-at-point end-prop)))))))
(list begin-of-begin end-of-end))))
(defun markdown-get-fenced-block-from-middle (prop)
"Return limits of an enclosing fenced block from its middle, using PROP.
Return value is a list usable as `match-data'."
(let* ((correct-entry
(cl-find-if
(lambda (entry) (eq (cl-third entry) prop))
markdown-fenced-block-pairs))
(begin-prop (cl-cadar correct-entry))
(begin-of-begin
(save-excursion
(goto-char (match-beginning 0))
(unless (bobp) (forward-line -1))
(beginning-of-line)
(cl-first (markdown-text-property-at-point begin-prop))))
(end-prop (cl-cadadr correct-entry))
(end-of-end
(save-excursion
(goto-char (match-end 0))
(beginning-of-line)
(cl-second (markdown-text-property-at-point end-prop)))))
(list begin-of-begin end-of-end)))
(defun markdown-get-fenced-block-from-end (prop)
"Return limits of an enclosing fenced block from its end, using PROP.
Return value is a list usable as `match-data'."
(let* ((correct-entry
(cl-find-if
(lambda (entry) (eq (cl-cadadr entry) prop))
markdown-fenced-block-pairs))
(end-of-end (cl-second (markdown-text-property-at-point prop)))
(middle-prop (cl-third correct-entry))
(begin-prop (cl-cadar correct-entry))
(begin-of-begin
(save-excursion
(goto-char (match-beginning 0)) ; beginning of end
(unless (bobp) (backward-char)) ; into middle
(let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
(if (not mid-prop-v)
(progn
(beginning-of-line)
(cl-first (markdown-text-property-at-point begin-prop)))
(set-match-data mid-prop-v)
(goto-char (match-beginning 0)) ; beginning of middle
(unless (bobp) (forward-line -1)) ; into beginning
(beginning-of-line)
(cl-first (markdown-text-property-at-point begin-prop)))))))
(list begin-of-begin end-of-end)))
(defun markdown-get-enclosing-fenced-block-construct (&optional pos)
"Get \"fake\" match data for block enclosing POS.
Returns fake match data which encloses the start, middle, and end
of the block construct enclosing POS, if it exists. Used in
`markdown-code-block-at-pos'."
(save-excursion
(when pos (goto-char pos))
(beginning-of-line)
(car
(cl-remove-if
#'null
(cl-mapcar
(lambda (fun-and-prop)
(cl-destructuring-bind (fun prop) fun-and-prop
(when prop
(save-match-data
(set-match-data (markdown-text-property-at-point prop))
(funcall fun prop)))))
`((markdown-get-fenced-block-from-start
,(cl-find-if
#'markdown-text-property-at-point
(markdown-get-fenced-block-begin-properties)))
(markdown-get-fenced-block-from-middle
,(cl-find-if
#'markdown-text-property-at-point
(markdown-get-fenced-block-middle-properties)))
(markdown-get-fenced-block-from-end
,(cl-find-if
#'markdown-text-property-at-point
(markdown-get-fenced-block-end-properties)))))))))
(defun markdown-propertize-end-match (reg end fence-spec middle-begin)
"Get match for REG up to END, if exists, and propertize appropriately.
FENCE-SPEC is an entry in `markdown-fenced-block-pairs' and
MIDDLE-BEGIN is the start of the \"middle\" section of the block."
(when (re-search-forward reg end t)
(let ((close-begin (match-beginning 0)) ; Start of closing line.
(close-end (match-end 0)) ; End of closing line.
(close-data (match-data t))) ; Match data for closing line.
;; Propertize middle section of fenced block.
(put-text-property middle-begin close-begin
(cl-third fence-spec)
(list middle-begin close-begin))
;; If the block is a YAML block, propertize the declarations inside
(markdown-syntax-propertize-yaml-metadata middle-begin close-begin)
;; Propertize closing line of fenced block.
(put-text-property close-begin close-end
(cl-cadadr fence-spec) close-data))))
(defun markdown-syntax-propertize-fenced-block-constructs (start end)
"Propertize according to `markdown-fenced-block-pairs' from START to END.
If unable to propertize an entire block (if the start of a block is within START
and END, but the end of the block is not), propertize the start section of a
block, then in a subsequent call propertize both middle and end by finding the
start which was previously propertized."
(let ((start-reg (markdown-get-start-fence-regexp)))
(save-excursion
(goto-char start)
;; start from previous unclosed block, if exists
(let ((prev-begin-block (markdown-find-previous-block)))
(when prev-begin-block
(let* ((correct-entry
(cl-find-if (lambda (entry)
(eq (cdr prev-begin-block) (cl-cadar entry)))
markdown-fenced-block-pairs))
(enclosed-text-start (1+ (car prev-begin-block)))
(start-length
(save-excursion
(goto-char (car prev-begin-block))
(string-match
(markdown-maybe-funcall-regexp
(caar correct-entry))
(buffer-substring
(point-at-bol) (point-at-eol)))
(- (match-end 1) (match-beginning 1))))
(end-reg (markdown-maybe-funcall-regexp
(cl-caadr correct-entry) start-length)))
(markdown-propertize-end-match
end-reg end correct-entry enclosed-text-start))))
;; find all new blocks within region
(while (re-search-forward start-reg end t)
;; we assume the opening constructs take up (only) an entire line,
;; so we re-check the current line
(let* ((cur-line (buffer-substring (point-at-bol) (point-at-eol)))
;; find entry in `markdown-fenced-block-pairs' corresponding
;; to regex which was matched
(correct-entry
(cl-find-if
(lambda (fenced-pair)
(string-match-p
(markdown-maybe-funcall-regexp (caar fenced-pair))
cur-line))
markdown-fenced-block-pairs))
(enclosed-text-start
(save-excursion (1+ (point-at-eol))))
(end-reg
(markdown-maybe-funcall-regexp
(cl-caadr correct-entry)
(if (and (match-beginning 1) (match-end 1))
(- (match-end 1) (match-beginning 1))
0))))
;; get correct match data
(save-excursion
(beginning-of-line)
(re-search-forward
(markdown-maybe-funcall-regexp (caar correct-entry))
(point-at-eol)))
;; mark starting, even if ending is outside of region
(put-text-property (match-beginning 0) (match-end 0)
(cl-cadar correct-entry) (match-data t))
(markdown-propertize-end-match
end-reg end correct-entry enclosed-text-start))))))
(defun markdown-syntax-propertize-blockquotes (start end)
"Match blockquotes from START to END."
(save-excursion
(goto-char start)
(while (and (re-search-forward markdown-regex-blockquote end t)
(not (markdown-code-block-at-pos (match-beginning 0))))
(put-text-property (match-beginning 0) (match-end 0)
'markdown-blockquote
(match-data t)))))
(defun markdown-syntax-propertize-hrs (start end)
"Match horizontal rules from START to END."
(save-excursion
(goto-char start)
(while (re-search-forward markdown-regex-hr end t)
(let ((beg (match-beginning 0))
(end (match-end 0)))
(goto-char beg)
(unless (or (markdown-on-heading-p)
(markdown-code-block-at-point-p))
(put-text-property beg end 'markdown-hr (match-data t)))
(goto-char end)))))
(defun markdown-syntax-propertize-yaml-metadata (start end)
"Propertize elements inside YAML metadata blocks from START to END.
Assumes region from START and END is already known to be the interior
region of a YAML metadata block as propertized by
`markdown-syntax-propertize-fenced-block-constructs'."
(save-excursion
(goto-char start)
(cl-loop
while (re-search-forward markdown-regex-declarative-metadata end t)
do (progn
(put-text-property (match-beginning 1) (match-end 1)
'markdown-metadata-key (match-data t))
(put-text-property (match-beginning 2) (match-end 2)
'markdown-metadata-markup (match-data t))
(put-text-property (match-beginning 3) (match-end 3)
'markdown-metadata-value (match-data t))))))
(defun markdown-syntax-propertize-headings (start end)
"Match headings of type SYMBOL with REGEX from START to END."
(goto-char start)
(while (re-search-forward markdown-regex-header end t)
(unless (markdown-code-block-at-pos (match-beginning 0))
(put-text-property
(match-beginning 0) (match-end 0) 'markdown-heading
(match-data t))
(put-text-property
(match-beginning 0) (match-end 0)
(cond ((match-string-no-properties 2) 'markdown-heading-1-setext)
((match-string-no-properties 3) 'markdown-heading-2-setext)
(t (let ((atx-level (length (markdown-trim-whitespace
(match-string-no-properties 4)))))
(intern (format "markdown-heading-%d-atx" atx-level)))))
(match-data t)))))
(defun markdown-syntax-propertize-comments (start end)
"Match HTML comments from the START to END."
(let* ((in-comment (nth 4 (syntax-ppss)))
(comment-begin (nth 8 (syntax-ppss))))
(goto-char start)
(cond
;; Comment start
((and (not in-comment)
(re-search-forward markdown-regex-comment-start end t)
(not (markdown-inline-code-at-point-p))
(not (markdown-code-block-at-point-p)))
(let ((open-beg (match-beginning 0)))
(put-text-property open-beg (1+ open-beg)
'syntax-table (string-to-syntax "<"))
(markdown-syntax-propertize-comments
(min (1+ (match-end 0)) end (point-max)) end)))
;; Comment end
((and in-comment comment-begin
(re-search-forward markdown-regex-comment-end end t))
(let ((comment-end (match-end 0)))
(put-text-property (1- comment-end) comment-end
'syntax-table (string-to-syntax ">"))
;; Remove any other text properties inside the comment
(remove-text-properties comment-begin comment-end
markdown--syntax-properties)
(put-text-property comment-begin comment-end
'markdown-comment (list comment-begin comment-end))
(markdown-syntax-propertize-comments
(min (1+ comment-end) end (point-max)) end)))
;; Nothing found
(t nil))))
(defun markdown-syntax-propertize (start end)
"Function used as `syntax-propertize-function'.
START and END delimit region to propertize."
(with-silent-modifications
(save-excursion
(remove-text-properties start end markdown--syntax-properties)
(markdown-syntax-propertize-fenced-block-constructs start end)
(markdown-syntax-propertize-list-items start end)
(markdown-syntax-propertize-pre-blocks start end)
(markdown-syntax-propertize-blockquotes start end)
(markdown-syntax-propertize-headings start end)
(markdown-syntax-propertize-hrs start end)
(markdown-syntax-propertize-comments start end))))
;;; Markup Hiding =============================================================
(defconst markdown-markup-properties
'(face markdown-markup-face invisible markdown-markup)
"List of properties and values to apply to markup.")
(defconst markdown-language-keyword-properties
'(face markdown-language-keyword-face invisible markdown-markup)
"List of properties and values to apply to code block language names.")
(defconst markdown-language-info-properties
'(face markdown-language-info-face invisible markdown-markup)
"List of properties and values to apply to code block language info strings.")
(defconst markdown-include-title-properties
'(face markdown-link-title-face invisible markdown-markup)
"List of properties and values to apply to included code titles.")
(defcustom markdown-hide-markup nil
"Determines whether markup in the buffer will be hidden.
When set to nil, all markup is displayed in the buffer as it
appears in the file. An exception is when `markdown-hide-urls'
is non-nil.
Set this to a non-nil value to turn this feature on by default.
You can interactively toggle the value of this variable with
`markdown-toggle-markup-hiding', \\[markdown-toggle-markup-hiding],
or from the Markdown > Show & Hide menu.
Markup hiding works by adding text properties to positions in the
buffer---either the `invisible' property or the `display' property
in cases where alternative glyphs are used (e.g., list bullets).
This does not, however, affect printing or other output.
Functions such as `htmlfontify-buffer' and `ps-print-buffer' will
not honor these text properties. For printing, it would be better
to first convert to HTML or PDF (e.g,. using Pandoc)."
:group 'markdown
:type 'boolean
:safe 'booleanp
:package-version '(markdown-mode . "2.3"))
(make-variable-buffer-local 'markdown-hide-markup)
(defun markdown-toggle-markup-hiding (&optional arg)
"Toggle the display or hiding of markup.
With a prefix argument ARG, enable markup hiding if ARG is positive,
and disable it otherwise.
See `markdown-hide-markup' for additional details."
(interactive (list (or current-prefix-arg 'toggle)))
(setq markdown-hide-markup
(if (eq arg 'toggle)
(not markdown-hide-markup)
(> (prefix-numeric-value arg) 0)))
(if markdown-hide-markup
(progn (add-to-invisibility-spec 'markdown-markup)
(message "markdown-mode markup hiding enabled"))
(progn (remove-from-invisibility-spec 'markdown-markup)
(message "markdown-mode markup hiding disabled")))
(markdown-reload-extensions))
;;; Font Lock =================================================================
(require 'font-lock)
(defvar markdown-italic-face 'markdown-italic-face
"Face name to use for italic text.")
(defvar markdown-bold-face 'markdown-bold-face
"Face name to use for bold text.")
(defvar markdown-strike-through-face 'markdown-strike-through-face
"Face name to use for strike-through text.")
(defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
"Face name to use as a base for header delimiters.")
(defvar markdown-header-rule-face 'markdown-header-rule-face
"Face name to use as a base for header rules.")
(defvar markdown-header-face 'markdown-header-face
"Face name to use as a base for headers.")
(defvar markdown-header-face-1 'markdown-header-face-1
"Face name to use for level-1 headers.")
(defvar markdown-header-face-2 'markdown-header-face-2
"Face name to use for level-2 headers.")
(defvar markdown-header-face-3 'markdown-header-face-3
"Face name to use for level-3 headers.")
(defvar markdown-header-face-4 'markdown-header-face-4
"Face name to use for level-4 headers.")
(defvar markdown-header-face-5 'markdown-header-face-5
"Face name to use for level-5 headers.")
(defvar markdown-header-face-6 'markdown-header-face-6
"Face name to use for level-6 headers.")
(defvar markdown-inline-code-face 'markdown-inline-code-face
"Face name to use for inline code.")
(defvar markdown-list-face 'markdown-list-face
"Face name to use for list markers.")
(defvar markdown-blockquote-face 'markdown-blockquote-face
"Face name to use for blockquote.")
(defvar markdown-pre-face 'markdown-pre-face
"Face name to use for preformatted text.")
(defvar markdown-language-keyword-face 'markdown-language-keyword-face
"Face name to use for programming language identifiers.")
(defvar markdown-language-info-face 'markdown-language-info-face
"Face name to use for programming info strings.")
(defvar markdown-link-face 'markdown-link-face
"Face name to use for links.")
(defvar markdown-missing-link-face 'markdown-missing-link-face
"Face name to use for links where the linked file does not exist.")
(defvar markdown-reference-face 'markdown-reference-face
"Face name to use for reference.")
(defvar markdown-footnote-marker-face 'markdown-footnote-marker-face
"Face name to use for footnote markers.")
(defvar markdown-url-face 'markdown-url-face
"Face name to use for URLs.")
(defvar markdown-link-title-face 'markdown-link-title-face
"Face name to use for reference link titles.")
(defvar markdown-line-break-face 'markdown-line-break-face
"Face name to use for hard line breaks.")
(defvar markdown-comment-face 'markdown-comment-face
"Face name to use for HTML comments.")
(defvar markdown-math-face 'markdown-math-face
"Face name to use for LaTeX expressions.")
(defvar markdown-metadata-key-face 'markdown-metadata-key-face
"Face name to use for metadata keys.")
(defvar markdown-metadata-value-face 'markdown-metadata-value-face
"Face name to use for metadata values.")
(defvar markdown-gfm-checkbox-face 'markdown-gfm-checkbox-face
"Face name to use for GFM checkboxes.")
(defvar markdown-highlight-face 'markdown-highlight-face
"Face name to use for mouse highlighting.")
(defvar markdown-markup-face 'markdown-markup-face
"Face name to use for markup elements.")
(make-obsolete-variable 'markdown-italic-face "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-bold-face "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-strike-through-face "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-header-delimiter-face "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-header-rule-face "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-header-face "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-header-face-1 "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-header-face-2 "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-header-face-3 "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-header-face-4 "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-header-face-5 "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-header-face-6 "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-inline-code-face "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-list-face "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-blockquote-face "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-pre-face "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-language-keyword-face "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-language-info-face "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-link-face "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-missing-link-face "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-reference-face "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-footnote-marker-face "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-url-face "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-link-title-face "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-line-break-face "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-comment-face "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-math-face "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-metadata-key-face "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-metadata-value-face "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-gfm-checkbox-face "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-highlight-face "Use face name directly" "v2.4")
(make-obsolete-variable 'markdown-markup-face "Use face name directly" "v2.4")
(defgroup markdown-faces nil
"Faces used in Markdown Mode"
:group 'markdown
:group 'faces)
(defface markdown-italic-face
'((t (:inherit italic)))
"Face for italic text."
:group 'markdown-faces)
(defface markdown-bold-face
'((t (:inherit bold)))
"Face for bold text."
:group 'markdown-faces)
(defface markdown-strike-through-face
'((t (:strike-through t)))
"Face for strike-through text."
:group 'markdown-faces)
(defface markdown-markup-face
'((t (:inherit shadow :slant normal :weight normal)))
"Face for markup elements."
:group 'markdown-faces)
(defface markdown-header-rule-face
'((t (:inherit markdown-markup-face)))
"Base face for headers rules."
:group 'markdown-faces)
(defface markdown-header-delimiter-face
'((t (:inherit markdown-markup-face)))
"Base face for headers hash delimiter."
:group 'markdown-faces)
(defface markdown-list-face
'((t (:inherit markdown-markup-face)))
"Face for list item markers."
:group 'markdown-faces)
(defface markdown-blockquote-face
'((t (:inherit font-lock-doc-face)))
"Face for blockquote sections."
:group 'markdown-faces)
(defface markdown-code-face
'((t (:inherit fixed-pitch)))
"Face for inline code, pre blocks, and fenced code blocks.
This may be used, for example, to add a contrasting background to
inline code fragments and code blocks."
:group 'markdown-faces)
(defface markdown-inline-code-face
'((t (:inherit (markdown-code-face font-lock-constant-face))))
"Face for inline code."
:group 'markdown-faces)
(defface markdown-pre-face
'((t (:inherit (markdown-code-face font-lock-constant-face))))
"Face for preformatted text."
:group 'markdown-faces)
(defface markdown-table-face
'((t (:inherit (markdown-code-face))))
"Face for tables."
:group 'markdown-faces)
(defface markdown-language-keyword-face
'((t (:inherit font-lock-type-face)))
"Face for programming language identifiers."
:group 'markdown-faces)
(defface markdown-language-info-face
'((t (:inherit font-lock-string-face)))
"Face for programming language info strings."
:group 'markdown-faces)
(defface markdown-link-face
'((t (:inherit link)))
"Face for links."
:group 'markdown-faces)
(defface markdown-missing-link-face
'((t (:inherit font-lock-warning-face)))
"Face for missing links."
:group 'markdown-faces)
(defface markdown-reference-face
'((t (:inherit markdown-markup-face)))
"Face for link references."
:group 'markdown-faces)
(define-obsolete-face-alias 'markdown-footnote-face
'markdown-footnote-marker-face "v2.3")
(defface markdown-footnote-marker-face
'((t (:inherit markdown-markup-face)))
"Face for footnote markers."
:group 'markdown-faces)
(defface markdown-footnote-text-face
'((t (:inherit font-lock-comment-face)))
"Face for footnote text."
:group 'markdown-faces)
(defface markdown-url-face
'((t (:inherit font-lock-string-face)))
"Face for URLs that are part of markup.
For example, this applies to URLs in inline links:
[link text](http://example.com/)."
:group 'markdown-faces)
(defface markdown-plain-url-face
'((t (:inherit markdown-link-face)))
"Face for URLs that are also links.
For example, this applies to plain angle bracket URLs:
<http://example.com/>."
:group 'markdown-faces)
(defface markdown-link-title-face
'((t (:inherit font-lock-comment-face)))
"Face for reference link titles."
:group 'markdown-faces)
(defface markdown-line-break-face
'((t (:inherit font-lock-constant-face :underline t)))
"Face for hard line breaks."
:group 'markdown-faces)
(defface markdown-comment-face
'((t (:inherit font-lock-comment-face)))
"Face for HTML comments."
:group 'markdown-faces)
(defface markdown-math-face
'((t (:inherit font-lock-string-face)))
"Face for LaTeX expressions."
:group 'markdown-faces)
(defface markdown-metadata-key-face
'((t (:inherit font-lock-variable-name-face)))
"Face for metadata keys."
:group 'markdown-faces)
(defface markdown-metadata-value-face
'((t (:inherit font-lock-string-face)))
"Face for metadata values."
:group 'markdown-faces)
(defface markdown-gfm-checkbox-face
'((t (:inherit font-lock-builtin-face)))
"Face for GFM checkboxes."
:group 'markdown-faces)
(defface markdown-highlight-face
'((t (:inherit highlight)))
"Face for mouse highlighting."
:group 'markdown-faces)
(defface markdown-hr-face
'((t (:inherit markdown-markup-face)))
"Face for horizontal rules."
:group 'markdown-faces)
(defface markdown-html-tag-name-face
'((t (:inherit font-lock-type-face)))
"Face for HTML tag names."
:group 'markdown-faces)
(defface markdown-html-tag-delimiter-face
'((t (:inherit markdown-markup-face)))
"Face for HTML tag delimiters."
:group 'markdown-faces)
(defface markdown-html-attr-name-face
'((t (:inherit font-lock-variable-name-face)))
"Face for HTML attribute names."
:group 'markdown-faces)
(defface markdown-html-attr-value-face
'((t (:inherit font-lock-string-face)))
"Face for HTML attribute values."
:group 'markdown-faces)
(defface markdown-html-entity-face
'((t (:inherit font-lock-variable-name-face)))
"Face for HTML entities."
:group 'markdown-faces)
(defcustom markdown-header-scaling nil
"Whether to use variable-height faces for headers.
When non-nil, `markdown-header-face' will inherit from
`variable-pitch' and the scaling values in
`markdown-header-scaling-values' will be applied to
headers of levels one through six respectively."
:type 'boolean
:initialize 'custom-initialize-default
:set (lambda (symbol value)
(set-default symbol value)
(markdown-update-header-faces value))
:group 'markdown-faces
:package-version '(markdown-mode . "2.2"))
(defcustom markdown-header-scaling-values
'(2.0 1.7 1.4 1.1 1.0 1.0)
"List of scaling values for headers of level one through six.
Used when `markdown-header-scaling' is non-nil."
:type 'list
:initialize 'custom-initialize-default
:set (lambda (symbol value)
(set-default symbol value)
(markdown-update-header-faces markdown-header-scaling value))
:group 'markdown-faces)
(defun markdown-make-header-faces ()
"Build the faces used for Markdown headers."
(let ((inherit-faces '(font-lock-function-name-face)))
(when markdown-header-scaling
(setq inherit-faces (cons 'variable-pitch inherit-faces)))
(defface markdown-header-face
`((t (:inherit ,inherit-faces :weight bold)))
"Base face for headers."
:group 'markdown-faces))
(dotimes (num 6)
(let* ((num1 (1+ num))
(face-name (intern (format "markdown-header-face-%s" num1)))
(scale (if markdown-header-scaling
(float (nth num markdown-header-scaling-values))
1.0)))
(eval
`(defface ,face-name
'((t (:inherit markdown-header-face :height ,scale)))
(format "Face for level %s headers.
You probably don't want to customize this face directly. Instead
you can customize the base face `markdown-header-face' or the
variable-height variable `markdown-header-scaling'." ,num1)
:group 'markdown-faces)))))
(markdown-make-header-faces)
(defun markdown-update-header-faces (&optional scaling scaling-values)
"Update header faces, depending on if header SCALING is desired.
If so, use given list of SCALING-VALUES relative to the baseline
size of `markdown-header-face'."
(dotimes (num 6)
(let* ((face-name (intern (format "markdown-header-face-%s" (1+ num))))
(scale (cond ((not scaling) 1.0)
(scaling-values (float (nth num scaling-values)))
(t (float (nth num markdown-header-scaling-values))))))
(unless (get face-name 'saved-face) ; Don't update customized faces
(set-face-attribute face-name nil :height scale)))))
(defun markdown-syntactic-face (state)
"Return font-lock face for characters with given STATE.
See `font-lock-syntactic-face-function' for details."
(let ((in-comment (nth 4 state)))
(cond
(in-comment 'markdown-comment-face)
(t nil))))
(defcustom markdown-list-item-bullets
'("" "" "" "" "" "" "")
"List of bullets to use for unordered lists.
It can contain any number of symbols, which will be repeated.
Depending on your font, some reasonable choices are:
♥ ● ◇ ✚ ✜ ☯ ◆ ♠ ♣ ♦ ❀ ◆ ◖ ▶ ► • ★ ▸."
:group 'markdown
:type '(repeat (string :tag "Bullet character"))
:package-version '(markdown-mode . "2.3"))
(defun markdown--footnote-marker-properties ()
"Return a font-lock facespec expression for footnote marker text."
`(face markdown-footnote-marker-face
,@(when markdown-hide-markup
`(display ,markdown-footnote-display))))
(defun markdown--pandoc-inline-footnote-properties ()
"Return a font-lock facespec expression for Pandoc inline footnote text."
`(face markdown-footnote-text-face
,@(when markdown-hide-markup
`(display ,markdown-footnote-display))))
(defvar markdown-mode-font-lock-keywords
`((markdown-match-yaml-metadata-begin . ((1 'markdown-markup-face)))
(markdown-match-yaml-metadata-end . ((1 'markdown-markup-face)))
(markdown-match-yaml-metadata-key . ((1 'markdown-metadata-key-face)
(2 'markdown-markup-face)
(3 'markdown-metadata-value-face)))
(markdown-match-gfm-open-code-blocks . ((1 markdown-markup-properties)
(2 markdown-markup-properties nil t)
(3 markdown-language-keyword-properties nil t)
(4 markdown-language-info-properties nil t)
(5 markdown-markup-properties nil t)))
(markdown-match-gfm-close-code-blocks . ((0 markdown-markup-properties)))
(markdown-fontify-gfm-code-blocks)
(markdown-fontify-tables)
(markdown-match-fenced-start-code-block . ((1 markdown-markup-properties)
(2 markdown-markup-properties nil t)
(3 markdown-language-keyword-properties nil t)
(4 markdown-language-info-properties nil t)
(5 markdown-markup-properties nil t)))
(markdown-match-fenced-end-code-block . ((0 markdown-markup-properties)))
(markdown-fontify-fenced-code-blocks)
(markdown-match-pre-blocks . ((0 'markdown-pre-face)))
(markdown-fontify-headings)
(markdown-match-declarative-metadata . ((1 'markdown-metadata-key-face)
(2 'markdown-markup-face)
(3 'markdown-metadata-value-face)))
(markdown-match-pandoc-metadata . ((1 'markdown-markup-face)
(2 'markdown-markup-face)
(3 'markdown-metadata-value-face)))
(markdown-fontify-hrs)
(markdown-match-code . ((1 markdown-markup-properties prepend)
(2 'markdown-inline-code-face prepend)
(3 markdown-markup-properties prepend)))
(,markdown-regex-kbd . ((1 markdown-markup-properties)
(2 'markdown-inline-code-face)
(3 markdown-markup-properties)))
(markdown-fontify-angle-uris)
(,markdown-regex-email . 'markdown-plain-url-face)
(markdown-match-html-tag . ((1 'markdown-html-tag-delimiter-face t)
(2 'markdown-html-tag-name-face t)
(3 'markdown-html-tag-delimiter-face t)
;; Anchored matcher for HTML tag attributes
(,markdown-regex-html-attr
;; Before searching, move past tag
;; name; set limit at tag close.
(progn
(goto-char (match-end 2)) (match-end 3))
nil
. ((1 'markdown-html-attr-name-face)
(3 'markdown-html-tag-delimiter-face nil t)
(4 'markdown-html-attr-value-face nil t)))))
(,markdown-regex-html-entity . 'markdown-html-entity-face)
(markdown-fontify-list-items)
(,markdown-regex-footnote . ((1 markdown-markup-properties) ; [^
(2 (markdown--footnote-marker-properties)) ; label
(3 markdown-markup-properties))) ; ]
(,markdown-regex-pandoc-inline-footnote . ((1 markdown-markup-properties) ; ^
(2 markdown-markup-properties) ; [
(3 (markdown--pandoc-inline-footnote-properties)) ; text
(4 markdown-markup-properties))) ; ]
(markdown-match-includes . ((1 markdown-markup-properties)
(2 markdown-markup-properties nil t)
(3 markdown-include-title-properties nil t)
(4 markdown-markup-properties nil t)
(5 markdown-markup-properties)
(6 'markdown-url-face)
(7 markdown-markup-properties)))
(markdown-fontify-inline-links)
(markdown-fontify-reference-links)
(,markdown-regex-reference-definition . ((1 'markdown-markup-face) ; [
(2 'markdown-reference-face) ; label
(3 'markdown-markup-face) ; ]
(4 'markdown-markup-face) ; :
(5 'markdown-url-face) ; url
(6 'markdown-link-title-face))) ; "title" (optional)
(markdown-fontify-plain-uris)
;; Math mode $..$
(markdown-match-math-single . ((1 'markdown-markup-face prepend)
(2 'markdown-math-face append)
(3 'markdown-markup-face prepend)))
;; Math mode $$..$$
(markdown-match-math-double . ((1 'markdown-markup-face prepend)
(2 'markdown-math-face append)
(3 'markdown-markup-face prepend)))
;; Math mode \[..\] and \\[..\\]
(markdown-match-math-display . ((1 'markdown-markup-face prepend)
(3 'markdown-math-face append)
(4 'markdown-markup-face prepend)))
(markdown-match-bold . ((1 markdown-markup-properties prepend)
(2 'markdown-bold-face append)
(3 markdown-markup-properties prepend)))
(markdown-match-italic . ((1 markdown-markup-properties prepend)
(2 'markdown-italic-face append)
(3 markdown-markup-properties prepend)))
(,markdown-regex-strike-through . ((3 markdown-markup-properties)
(4 'markdown-strike-through-face)
(5 markdown-markup-properties)))
(,markdown-regex-line-break . (1 'markdown-line-break-face prepend))
(markdown-fontify-sub-superscripts)
(markdown-match-inline-attributes . ((0 markdown-markup-properties prepend)))
(markdown-match-leanpub-sections . ((0 markdown-markup-properties)))
(markdown-fontify-blockquotes)
(markdown-match-wiki-link . ((0 'markdown-link-face prepend))))
"Syntax highlighting for Markdown files.")
(define-obsolete-variable-alias
'markdown-mode-font-lock-keywords-basic
'markdown-mode-font-lock-keywords "v2.4")
;; Footnotes
(defvar markdown-footnote-counter 0
"Counter for footnote numbers.")
(make-variable-buffer-local 'markdown-footnote-counter)
(defconst markdown-footnote-chars
"[[:alnum:]-]"
"Regular expression matching any character that is allowed in a footnote identifier.")
(defconst markdown-regex-footnote-definition
(concat "^ \\{0,3\\}\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:\\(?:[ \t]+\\|$\\)")
"Regular expression matching a footnote definition, capturing the label.")
;;; Compatibility =============================================================
(defun markdown-replace-regexp-in-string (regexp rep string)
"Replace ocurrences of REGEXP with REP in STRING.
This is a compatibility wrapper to provide `replace-regexp-in-string'
in XEmacs 21."
(if (featurep 'xemacs)
(replace-in-string string regexp rep)
(replace-regexp-in-string regexp rep string)))
;; `markdown-use-region-p' is a compatibility function which checks
;; for an active region, with fallbacks for older Emacsen and XEmacs.
(eval-and-compile
(cond
;; Emacs 24 and newer
((fboundp 'use-region-p)
(defalias 'markdown-use-region-p 'use-region-p))
;; XEmacs
((fboundp 'region-active-p)
(defalias 'markdown-use-region-p 'region-active-p))))
;; Use new names for outline-mode functions in Emacs 25 and later.
(eval-and-compile
(defalias 'markdown-hide-sublevels
(if (fboundp 'outline-hide-sublevels)
'outline-hide-sublevels
'hide-sublevels))
(defalias 'markdown-show-all
(if (fboundp 'outline-show-all)
'outline-show-all
'show-all))
(defalias 'markdown-hide-body
(if (fboundp 'outline-hide-body)
'outline-hide-body
'hide-body))
(defalias 'markdown-show-children
(if (fboundp 'outline-show-children)
'outline-show-children
'show-children))
(defalias 'markdown-show-subtree
(if (fboundp 'outline-show-subtree)
'outline-show-subtree
'show-subtree))
(defalias 'markdown-hide-subtree
(if (fboundp 'outline-hide-subtree)
'outline-hide-subtree
'hide-subtree)))
;; Provide directory-name-p to Emacs 24
(defsubst markdown-directory-name-p (name)
"Return non-nil if NAME ends with a directory separator character.
Taken from `directory-name-p' from Emacs 25 and provided here for
backwards compatibility."
(let ((len (length name))
(lastc ?.))
(if (> len 0)
(setq lastc (aref name (1- len))))
(or (= lastc ?/)
(and (memq system-type '(windows-nt ms-dos))
(= lastc ?\\)))))
;; Provide a function to find files recursively in Emacs 24.
(defalias 'markdown-directory-files-recursively
(if (fboundp 'directory-files-recursively)
'directory-files-recursively
(lambda (dir regexp)
"Return list of all files under DIR that have file names matching REGEXP.
This function works recursively. Files are returned in \"depth first\"
order, and files from each directory are sorted in alphabetical order.
Each file name appears in the returned list in its absolute form.
Based on `directory-files-recursively' from Emacs 25 and provided
here for backwards compatibility."
(let ((result nil)
(files nil)
;; When DIR is "/", remote file names like "/method:" could
;; also be offered. We shall suppress them.
(tramp-mode (and tramp-mode (file-remote-p (expand-file-name dir)))))
(dolist (file (sort (file-name-all-completions "" dir)
'string<))
(unless (member file '("./" "../"))
(if (markdown-directory-name-p file)
(let* ((leaf (substring file 0 (1- (length file))))
(full-file (expand-file-name leaf dir)))
(setq result
(nconc result (markdown-directory-files-recursively
full-file regexp))))
(when (string-match-p regexp file)
(push (expand-file-name file dir) files)))))
(nconc result (nreverse files))))))
(defun markdown-flyspell-check-word-p ()
"Return t if `flyspell' should check word just before point.
Used for `flyspell-generic-check-word-predicate'."
(save-excursion
(goto-char (1- (point)))
(not (or (markdown-code-block-at-point-p)
(markdown-inline-code-at-point-p)
(markdown-in-comment-p)
(let ((faces (get-text-property (point) 'face)))
(if (listp faces)
(or (memq 'markdown-reference-face faces)
(memq 'markdown-markup-face faces)
(memq 'markdown-plain-url-face faces)
(memq 'markdown-inline-code-face faces)
(memq 'markdown-url-face faces))
(memq faces '(markdown-reference-face
markdown-markup-face
markdown-plain-url-face
markdown-inline-code-face
markdown-url-face))))))))
(defun markdown-font-lock-ensure ()
"Provide `font-lock-ensure' in Emacs 24."
(if (fboundp 'font-lock-ensure)
(font-lock-ensure)
(with-no-warnings
;; Suppress warning about non-interactive use of
;; `font-lock-fontify-buffer' in Emacs 25.
(font-lock-fontify-buffer))))
;;; Markdown Parsing Functions ================================================
(define-obsolete-function-alias
'markdown-cur-line-blank 'markdown-cur-line-blank-p "v2.4")
(define-obsolete-function-alias
'markdown-next-line-blank 'markdown-next-line-blank-p "v2.4")
(defun markdown-cur-line-blank-p ()
"Return t if the current line is blank and nil otherwise."
(save-excursion
(beginning-of-line)
(looking-at-p markdown-regex-blank-line)))
(defun markdown-prev-line-blank ()
"Return t if the previous line is blank and nil otherwise.
If we are at the first line, then consider the previous line to be blank."
(or (= (line-beginning-position) (point-min))
(save-excursion
(forward-line -1)
(looking-at markdown-regex-blank-line))))
(defun markdown-prev-line-blank-p ()
"Like `markdown-prev-line-blank', but preserve `match-data'."
(save-match-data (markdown-prev-line-blank)))
(defun markdown-next-line-blank-p ()
"Return t if the next line is blank and nil otherwise.
If we are at the last line, then consider the next line to be blank."
(or (= (line-end-position) (point-max))
(save-excursion
(forward-line 1)
(markdown-cur-line-blank-p))))
(defun markdown-prev-line-indent ()
"Return the number of leading whitespace characters in the previous line.
Return 0 if the current line is the first line in the buffer."
(save-excursion
(if (= (line-beginning-position) (point-min))
0
(forward-line -1)
(current-indentation))))
(defun markdown-next-line-indent ()
"Return the number of leading whitespace characters in the next line.
Return 0 if line is the last line in the buffer."
(save-excursion
(if (= (line-end-position) (point-max))
0
(forward-line 1)
(current-indentation))))
(defun markdown-new-baseline ()
"Determine if the current line begins a new baseline level.
Assume point is positioned at beginning of line."
(or (looking-at markdown-regex-header)
(looking-at markdown-regex-hr)
(and (= (current-indentation) 0)
(not (looking-at markdown-regex-list))
(markdown-prev-line-blank))))
(defun markdown-search-backward-baseline ()
"Search backward baseline point with no indentation and not a list item."
(end-of-line)
(let (stop)
(while (not (or stop (bobp)))
(re-search-backward markdown-regex-block-separator-noindent nil t)
(when (match-end 2)
(goto-char (match-end 2))
(cond
((markdown-new-baseline)
(setq stop t))
((looking-at-p markdown-regex-list)
(setq stop nil))
(t (setq stop t)))))))
(defun markdown-update-list-levels (marker indent levels)
"Update list levels given list MARKER, block INDENT, and current LEVELS.
Here, MARKER is a string representing the type of list, INDENT is an integer
giving the indentation, in spaces, of the current block, and LEVELS is a
list of the indentation levels of parent list items. When LEVELS is nil,
it means we are at baseline (not inside of a nested list)."
(cond
;; New list item at baseline.
((and marker (null levels))
(setq levels (list indent)))
;; List item with greater indentation (four or more spaces).
;; Increase list level.
((and marker (>= indent (+ (car levels) 4)))
(setq levels (cons indent levels)))
;; List item with greater or equal indentation (less than four spaces).
;; Do not increase list level.
((and marker (>= indent (car levels)))
levels)
;; Lesser indentation level.
;; Pop appropriate number of elements off LEVELS list (e.g., lesser
;; indentation could move back more than one list level). Note
;; that this block need not be the beginning of list item.
((< indent (car levels))
(while (and (> (length levels) 1)
(< indent (+ (cadr levels) 4)))
(setq levels (cdr levels)))
levels)
;; Otherwise, do nothing.
(t levels)))
(defun markdown-calculate-list-levels ()
"Calculate list levels at point.
Return a list of the form (n1 n2 n3 ...) where n1 is the
indentation of the deepest nested list item in the branch of
the list at the point, n2 is the indentation of the parent
list item, and so on. The depth of the list item is therefore
the length of the returned list. If the point is not at or
immediately after a list item, return nil."
(save-excursion
(let ((first (point)) levels indent pre-regexp)
;; Find a baseline point with zero list indentation
(markdown-search-backward-baseline)
;; Search for all list items between baseline and LOC
(while (and (< (point) first)
(re-search-forward markdown-regex-list first t))
(setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
(beginning-of-line)
(cond
;; Make sure this is not a header or hr
((markdown-new-baseline) (setq levels nil))
;; Make sure this is not a line from a pre block
((looking-at-p pre-regexp))
;; If not, then update levels
(t
(setq indent (current-indentation))
(setq levels (markdown-update-list-levels (match-string 2)
indent levels))))
(end-of-line))
levels)))
(defun markdown-prev-list-item (level)
"Search backward from point for a list item with indentation LEVEL.
Set point to the beginning of the item, and return point, or nil
upon failure."
(let (bounds indent prev)
(setq prev (point))
(forward-line -1)
(setq indent (current-indentation))
(while
(cond
;; List item
((and (looking-at-p markdown-regex-list)
(setq bounds (markdown-cur-list-item-bounds)))
(cond
;; Stop and return point at item of equal indentation
((= (nth 3 bounds) level)
(setq prev (point))
nil)
;; Stop and return nil at item with lesser indentation
((< (nth 3 bounds) level)
(setq prev nil)
nil)
;; Stop at beginning of buffer
((bobp) (setq prev nil))
;; Continue at item with greater indentation
((> (nth 3 bounds) level) t)))
;; Stop at beginning of buffer
((bobp) (setq prev nil))
;; Continue if current line is blank
((markdown-cur-line-blank-p) t)
;; Continue while indentation is the same or greater
((>= indent level) t)
;; Stop if current indentation is less than list item
;; and the next is blank
((and (< indent level)
(markdown-next-line-blank-p))
(setq prev nil))
;; Stop at a header
((looking-at-p markdown-regex-header) (setq prev nil))
;; Stop at a horizontal rule
((looking-at-p markdown-regex-hr) (setq prev nil))
;; Otherwise, continue.
(t t))
(forward-line -1)
(setq indent (current-indentation)))
prev))
(defun markdown-next-list-item (level)
"Search forward from point for the next list item with indentation LEVEL.
Set point to the beginning of the item, and return point, or nil
upon failure."
(let (bounds indent next)
(setq next (point))
(if (looking-at markdown-regex-header-setext)
(goto-char (match-end 0)))
(forward-line)
(setq indent (current-indentation))
(while
(cond
;; Stop at end of the buffer.
((eobp) nil)
;; Continue if the current line is blank
((markdown-cur-line-blank-p) t)
;; List item
((and (looking-at-p markdown-regex-list)
(setq bounds (markdown-cur-list-item-bounds)))
(cond
;; Continue at item with greater indentation
((> (nth 3 bounds) level) t)
;; Stop and return point at item of equal indentation
((= (nth 3 bounds) level)
(setq next (point))
nil)
;; Stop and return nil at item with lesser indentation
((< (nth 3 bounds) level)
(setq next nil)
nil)))
;; Continue while indentation is the same or greater
((>= indent level) t)
;; Stop if current indentation is less than list item
;; and the previous line was blank.
((and (< indent level)
(markdown-prev-line-blank-p))
(setq next nil))
;; Stop at a header
((looking-at-p markdown-regex-header) (setq next nil))
;; Stop at a horizontal rule
((looking-at-p markdown-regex-hr) (setq next nil))
;; Otherwise, continue.
(t t))
(forward-line)
(setq indent (current-indentation)))
next))
(defun markdown-cur-list-item-end (level)
"Move to end of list item with pre-marker indentation LEVEL.
Return the point at the end when a list item was found at the
original point. If the point is not in a list item, do nothing."
(let (indent)
(forward-line)
(setq indent (current-indentation))
(while
(cond
;; Stop at end of the buffer.
((eobp) nil)
;; Continue while indentation is the same or greater
((>= indent level) t)
;; Continue if the current line is blank
((looking-at markdown-regex-blank-line) t)
;; Stop if current indentation is less than list item
;; and the previous line was blank.
((and (< indent level)
(markdown-prev-line-blank))
nil)
;; Stop at a new list items of the same or lesser
;; indentation, headings, and horizontal rules.
((looking-at (concat "\\(?:" markdown-regex-list
"\\|" markdown-regex-header
"\\|" markdown-regex-hr "\\)"))
nil)
;; Otherwise, continue.
(t t))
(forward-line)
(setq indent (current-indentation)))
;; Don't skip over whitespace for empty list items (marker and
;; whitespace only), just move to end of whitespace.
(if (save-excursion
(beginning-of-line)
(looking-at (concat markdown-regex-list "[ \t]*$")))
(goto-char (match-end 3))
(skip-chars-backward " \t\n"))
(end-of-line)
(point)))
(defun markdown-cur-list-item-bounds ()
"Return bounds for list item at point.
Return a list of the following form:
(begin end indent nonlist-indent marker checkbox match)
The named components are:
- begin: Position of beginning of list item, including leading indentation.
- end: Position of the end of the list item, including list item text.
- indent: Number of characters of indentation before list marker (an integer).
- nonlist-indent: Number characters of indentation, list
marker, and whitespace following list marker (an integer).
- marker: String containing the list marker and following whitespace
(e.g., \"- \" or \"* \").
- checkbox: String containing the GFM checkbox portion, if any,
including any trailing whitespace before the text
begins (e.g., \"[x] \").
- match: match data for markdown-regex-list
As an example, for the following unordered list item
- item
the returned list would be
(1 14 3 5 \"- \" nil (1 6 1 4 4 5 5 6))
If the point is not inside a list item, return nil."
(car (get-text-property (point-at-bol) 'markdown-list-item)))
(defun markdown-list-item-at-point-p ()
"Return t if there is a list item at the point and nil otherwise."
(save-match-data (markdown-cur-list-item-bounds)))
(defun markdown-prev-list-item-bounds ()
"Return bounds of previous item in the same list of any level.
The return value has the same form as that of
`markdown-cur-list-item-bounds'."
(save-excursion
(let ((cur-bounds (markdown-cur-list-item-bounds))
(beginning-of-list (save-excursion (markdown-beginning-of-list)))
stop)
(when cur-bounds
(goto-char (nth 0 cur-bounds))
(while (and (not stop) (not (bobp))
(re-search-backward markdown-regex-list
beginning-of-list t))
(unless (or (looking-at markdown-regex-hr)
(markdown-code-block-at-point-p))
(setq stop (point))))
(markdown-cur-list-item-bounds)))))
(defun markdown-next-list-item-bounds ()
"Return bounds of next item in the same list of any level.
The return value has the same form as that of
`markdown-cur-list-item-bounds'."
(save-excursion
(let ((cur-bounds (markdown-cur-list-item-bounds))
(end-of-list (save-excursion (markdown-end-of-list)))
stop)
(when cur-bounds
(goto-char (nth 0 cur-bounds))
(end-of-line)
(while (and (not stop) (not (eobp))
(re-search-forward markdown-regex-list
end-of-list t))
(unless (or (looking-at markdown-regex-hr)
(markdown-code-block-at-point-p))
(setq stop (point))))
(when stop
(markdown-cur-list-item-bounds))))))
(defun markdown-beginning-of-list ()
"Move point to beginning of list at point, if any."
(interactive)
(let ((orig-point (point))
(list-begin (save-excursion
(markdown-search-backward-baseline)
;; Stop at next list item, regardless of the indentation.
(markdown-next-list-item (point-max))
(when (looking-at markdown-regex-list)
(point)))))
(when (and list-begin (<= list-begin orig-point))
(goto-char list-begin))))
(defun markdown-end-of-list ()
"Move point to end of list at point, if any."
(interactive)
(let ((start (point))
(end (save-excursion
(when (markdown-beginning-of-list)
;; Items can't have nonlist-indent <= 1, so this
;; moves past all list items.
(markdown-next-list-item 1)
(skip-syntax-backward "-")
(unless (eobp) (forward-char 1))
(point)))))
(when (and end (>= end start))
(goto-char end))))
(defun markdown-up-list ()
"Move point to beginning of parent list item."
(interactive)
(let ((cur-bounds (markdown-cur-list-item-bounds)))
(when cur-bounds
(markdown-prev-list-item (1- (nth 3 cur-bounds)))
(let ((up-bounds (markdown-cur-list-item-bounds)))
(when (and up-bounds (< (nth 3 up-bounds) (nth 3 cur-bounds)))
(point))))))
(defun markdown-bounds-of-thing-at-point (thing)
"Call `bounds-of-thing-at-point' for THING with slight modifications.
Does not include trailing newlines when THING is 'line. Handles the
end of buffer case by setting both endpoints equal to the value of
`point-max', since an empty region will trigger empty markup insertion.
Return bounds of form (beg . end) if THING is found, or nil otherwise."
(let* ((bounds (bounds-of-thing-at-point thing))
(a (car bounds))
(b (cdr bounds)))
(when bounds
(when (eq thing 'line)
(cond ((and (eobp) (markdown-cur-line-blank-p))
(setq a b))
((char-equal (char-before b) ?\^J)
(setq b (1- b)))))
(cons a b))))
(defun markdown-reference-definition (reference)
"Find out whether Markdown REFERENCE is defined.
REFERENCE should not include the square brackets.
When REFERENCE is defined, return a list of the form (text start end)
containing the definition text itself followed by the start and end
locations of the text. Otherwise, return nil.
Leave match data for `markdown-regex-reference-definition'
intact additional processing."
(let ((reference (downcase reference)))
(save-excursion
(goto-char (point-min))
(catch 'found
(while (re-search-forward markdown-regex-reference-definition nil t)
(when (string= reference (downcase (match-string-no-properties 2)))
(throw 'found
(list (match-string-no-properties 5)
(match-beginning 5) (match-end 5)))))))))
(defun markdown-get-defined-references ()
"Return all defined reference labels and their line numbers (not including square brackets)."
(save-excursion
(goto-char (point-min))
(let (refs)
(while (re-search-forward markdown-regex-reference-definition nil t)
(let ((target (match-string-no-properties 2)))
(cl-pushnew
(cons (downcase target)
(markdown-line-number-at-pos (match-beginning 2)))
refs :test #'equal :key #'car)))
(reverse refs))))
(defun markdown-get-used-uris ()
"Return a list of all used URIs in the buffer."
(save-excursion
(goto-char (point-min))
(let (uris)
(while (re-search-forward
(concat "\\(?:" markdown-regex-link-inline
"\\|" markdown-regex-angle-uri
"\\|" markdown-regex-uri
"\\|" markdown-regex-email
"\\)")
nil t)
(unless (or (markdown-inline-code-at-point-p)
(markdown-code-block-at-point-p))
(cl-pushnew (or (match-string-no-properties 6)
(match-string-no-properties 10)
(match-string-no-properties 12)
(match-string-no-properties 13))
uris :test #'equal)))
(reverse uris))))
(defun markdown-inline-code-at-pos (pos)
"Return non-nil if there is an inline code fragment at POS.
Return nil otherwise. Set match data according to
`markdown-match-code' upon success.
This function searches the block for a code fragment that
contains the point using `markdown-match-code'. We do this
because `thing-at-point-looking-at' does not work reliably with
`markdown-regex-code'.
The match data is set as follows:
Group 1 matches the opening backquotes.
Group 2 matches the code fragment itself, without backquotes.
Group 3 matches the closing backquotes."
(save-excursion
(goto-char pos)
(let ((old-point (point))
(end-of-block (progn (markdown-end-of-text-block) (point)))
found)
(markdown-beginning-of-text-block)
(while (and (markdown-match-code end-of-block)
(setq found t)
(< (match-end 0) old-point)))
(and found ; matched something
(<= (match-beginning 0) old-point) ; match contains old-point
(> (match-end 0) old-point)))))
(defun markdown-inline-code-at-pos-p (pos)
"Return non-nil if there is an inline code fragment at POS.
Like `markdown-inline-code-at-pos`, but preserves match data."
(save-match-data (markdown-inline-code-at-pos pos)))
(defun markdown-inline-code-at-point ()
"Return non-nil if the point is at an inline code fragment.
See `markdown-inline-code-at-pos' for details."
(markdown-inline-code-at-pos (point)))
(defun markdown-inline-code-at-point-p (&optional pos)
"Return non-nil if there is inline code at the POS.
This is a predicate function counterpart to
`markdown-inline-code-at-point' which does not modify the match
data. See `markdown-code-block-at-point-p' for code blocks."
(save-match-data (markdown-inline-code-at-pos (or pos (point)))))
(make-obsolete 'markdown-code-at-point-p 'markdown-inline-code-at-point-p "v2.2")
(defun markdown-code-block-at-pos (pos)
"Return match data list if there is a code block at POS.
Uses text properties at the beginning of the line position.
This includes pre blocks, tilde-fenced code blocks, and GFM
quoted code blocks. Return nil otherwise."
(let ((bol (save-excursion (goto-char pos) (point-at-bol))))
(or (get-text-property bol 'markdown-pre)
(let* ((bounds (markdown-get-enclosing-fenced-block-construct pos))
(second (cl-second bounds)))
(if second
;; chunks are right open
(when (< pos second)
bounds)
bounds)))))
;; Function was renamed to emphasize that it does not modify match-data.
(defalias 'markdown-code-block-at-point 'markdown-code-block-at-point-p)
(defun markdown-code-block-at-point-p (&optional pos)
"Return non-nil if there is a code block at the POS.
This includes pre blocks, tilde-fenced code blocks, and GFM
quoted code blocks. This function does not modify the match
data. See `markdown-inline-code-at-point-p' for inline code."
(save-match-data (markdown-code-block-at-pos (or pos (point)))))
(defun markdown-heading-at-point (&optional pos)
"Return non-nil if there is a heading at the POS.
Set match data for `markdown-regex-header'."
(let ((match-data (get-text-property (or pos (point)) 'markdown-heading)))
(when match-data
(set-match-data match-data)
t)))
(defun markdown-pipe-at-bol-p ()
"Return non-nil if the line begins with a pipe symbol.
This may be useful for tables and Pandoc's line_blocks extension."
(char-equal (char-after (point-at-bol)) ?|))
;;; Markdown Font Lock Matching Functions =====================================
(defun markdown-range-property-any (begin end prop prop-values)
"Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
Also returns t if PROP is a list containing one of the PROP-VALUES.
Return nil otherwise."
(let (props)
(catch 'found
(dolist (loc (number-sequence begin end))
(when (setq props (get-text-property loc prop))
(cond ((listp props)
;; props is a list, check for membership
(dolist (val prop-values)
(when (memq val props) (throw 'found loc))))
(t
;; props is a scalar, check for equality
(dolist (val prop-values)
(when (eq val props) (throw 'found loc))))))))))
(defun markdown-range-properties-exist (begin end props)
(cl-loop
for loc in (number-sequence begin end)
with result = nil
while (not
(setq result
(cl-some (lambda (prop) (get-text-property loc prop)) props)))
finally return result))
(defun markdown-match-inline-generic (regex last &optional faceless)
"Match inline REGEX from the point to LAST.
When FACELESS is non-nil, do not return matches where faces have been applied."
(when (re-search-forward regex last t)
(let ((bounds (markdown-code-block-at-pos (match-beginning 1)))
(face (and faceless (text-property-not-all
(match-beginning 0) (match-end 0) 'face nil))))
(cond
;; In code block: move past it and recursively search again
(bounds
(when (< (goto-char (cl-second bounds)) last)
(markdown-match-inline-generic regex last faceless)))
;; When faces are found in the match range, skip over the match and
;; recursively search again.
(face
(when (< (goto-char (match-end 0)) last)
(markdown-match-inline-generic regex last faceless)))
;; Keep match data and return t when in bounds.
(t
(<= (match-end 0) last))))))
(defun markdown-match-code (last)
"Match inline code fragments from point to LAST."
(unless (bobp)
(backward-char 1))
(when (markdown-search-until-condition
(lambda ()
(and
;; Advance point in case of failure, but without exceeding last.
(goto-char (min (1+ (match-beginning 1)) last))
(not (markdown-in-comment-p (match-beginning 1)))
(not (markdown-in-comment-p (match-end 1)))
(not (markdown-code-block-at-pos (match-beginning 1)))))
markdown-regex-code last t)
(set-match-data (list (match-beginning 1) (match-end 1)
(match-beginning 2) (match-end 2)
(match-beginning 3) (match-end 3)
(match-beginning 4) (match-end 4)))
(goto-char (min (1+ (match-end 0)) last (point-max)))
t))
(defun markdown-match-bold (last)
"Match inline bold from the point to LAST."
(when (markdown-match-inline-generic markdown-regex-bold last)
(let ((begin (match-beginning 2))
(end (match-end 2)))
(if (or (markdown-inline-code-at-pos-p begin)
(markdown-inline-code-at-pos-p end)
(markdown-in-comment-p)
(markdown-range-property-any
begin begin 'face '(markdown-url-face
markdown-plain-url-face))
(markdown-range-property-any
begin end 'face '(markdown-hr-face
markdown-math-face)))
(progn (goto-char (min (1+ begin) last))
(when (< (point) last)
(markdown-match-italic last)))
(set-match-data (list (match-beginning 2) (match-end 2)
(match-beginning 3) (match-end 3)
(match-beginning 4) (match-end 4)
(match-beginning 5) (match-end 5)))
t))))
(defun markdown-match-italic (last)
"Match inline italics from the point to LAST."
(let ((regex (if (memq major-mode '(gfm-mode gfm-view-mode))
markdown-regex-gfm-italic markdown-regex-italic)))
(when (markdown-match-inline-generic regex last)
(let ((begin (match-beginning 1))
(end (match-end 1)))
(if (or (markdown-inline-code-at-pos-p begin)
(markdown-inline-code-at-pos-p end)
(markdown-in-comment-p)
(markdown-range-property-any
begin begin 'face '(markdown-url-face
markdown-plain-url-face))
(markdown-range-property-any
begin end 'face '(markdown-bold-face
markdown-list-face
markdown-hr-face
markdown-math-face)))
(progn (goto-char (min (1+ begin) last))
(when (< (point) last)
(markdown-match-italic last)))
(set-match-data (list (match-beginning 1) (match-end 1)
(match-beginning 2) (match-end 2)
(match-beginning 3) (match-end 3)
(match-beginning 4) (match-end 4)))
t)))))
(defun markdown-match-math-generic (regex last)
"Match REGEX from point to LAST.
REGEX is either `markdown-regex-math-inline-single' for matching
$..$ or `markdown-regex-math-inline-double' for matching $$..$$."
(when (and markdown-enable-math (markdown-match-inline-generic regex last))
(let ((begin (match-beginning 1)) (end (match-end 1)))
(prog1
(if (or (markdown-range-property-any
begin end 'face
'(markdown-inline-code-face markdown-bold-face))
(markdown-range-properties-exist
begin end
(markdown-get-fenced-block-middle-properties)))
(markdown-match-math-generic regex last)
t)
(goto-char (1+ (match-end 0)))))))
(defun markdown-match-list-items (last)
"Match list items from point to LAST."
(let* ((first (point))
(pos first)
(prop 'markdown-list-item)
(bounds (car (get-text-property pos prop))))
(while
(and (or (null (setq bounds (car (get-text-property pos prop))))
(< (cl-first bounds) pos))
(< (point) last)
(setq pos (next-single-property-change pos prop nil last))
(goto-char pos)))
(when bounds
(set-match-data (cl-seventh bounds))
;; Step at least one character beyond point. Otherwise
;; `font-lock-fontify-keywords-region' infloops.
(goto-char (min (1+ (max (point-at-eol) first))
(point-max)))
t)))
(defun markdown-match-math-single (last)
"Match single quoted $..$ math from point to LAST."
(markdown-match-math-generic markdown-regex-math-inline-single last))
(defun markdown-match-math-double (last)
"Match double quoted $$..$$ math from point to LAST."
(markdown-match-math-generic markdown-regex-math-inline-double last))
(defun markdown-match-math-display (last)
"Match bracketed display math \[..\] and \\[..\\] from point to LAST."
(markdown-match-math-generic markdown-regex-math-display last))
(defun markdown-match-propertized-text (property last)
"Match text with PROPERTY from point to LAST.
Restore match data previously stored in PROPERTY."
(let ((saved (get-text-property (point) property))
pos)
(unless saved
(setq pos (next-single-property-change (point) property nil last))
(unless (= pos last)
(setq saved (get-text-property pos property))))
(when saved
(set-match-data saved)
;; Step at least one character beyond point. Otherwise
;; `font-lock-fontify-keywords-region' infloops.
(goto-char (min (1+ (max (match-end 0) (point)))
(point-max)))
saved)))
(defun markdown-match-pre-blocks (last)
"Match preformatted blocks from point to LAST.
Use data stored in 'markdown-pre text property during syntax
analysis."
(markdown-match-propertized-text 'markdown-pre last))
(defun markdown-match-gfm-code-blocks (last)
"Match GFM quoted code blocks from point to LAST.
Use data stored in 'markdown-gfm-code text property during syntax
analysis."
(markdown-match-propertized-text 'markdown-gfm-code last))
(defun markdown-match-gfm-open-code-blocks (last)
(markdown-match-propertized-text 'markdown-gfm-block-begin last))
(defun markdown-match-gfm-close-code-blocks (last)
(markdown-match-propertized-text 'markdown-gfm-block-end last))
(defun markdown-match-fenced-code-blocks (last)
"Match fenced code blocks from the point to LAST."
(markdown-match-propertized-text 'markdown-fenced-code last))
(defun markdown-match-fenced-start-code-block (last)
(markdown-match-propertized-text 'markdown-tilde-fence-begin last))
(defun markdown-match-fenced-end-code-block (last)
(markdown-match-propertized-text 'markdown-tilde-fence-end last))
(defun markdown-match-blockquotes (last)
"Match blockquotes from point to LAST.
Use data stored in 'markdown-blockquote text property during syntax
analysis."
(markdown-match-propertized-text 'markdown-blockquote last))
(defun markdown-match-hr (last)
"Match horizontal rules comments from the point to LAST."
(markdown-match-propertized-text 'markdown-hr last))
(defun markdown-match-comments (last)
"Match HTML comments from the point to LAST."
(when (and (skip-syntax-forward "^<" last))
(let ((beg (point)))
(when (and (skip-syntax-forward "^>" last) (< (point) last))
(forward-char)
(set-match-data (list beg (point)))
t))))
(defun markdown-match-generic-links (last ref)
"Match inline links from point to LAST.
When REF is non-nil, match reference links instead of standard
links with URLs.
This function should only be used during font-lock, as it
determines syntax based on the presence of faces for previously
processed elements."
;; Search for the next potential link (not in a code block).
(let ((prohibited-faces '(markdown-pre-face
markdown-code-face
markdown-inline-code-face
markdown-comment-face))
found)
(while
(and (not found) (< (point) last)
(progn
;; Clear match data to test for a match after functions returns.
(set-match-data nil)
;; Preliminary regular expression search so we can return
;; quickly upon failure. This doesn't handle malformed links
;; or nested square brackets well, so if it passes we back up
;; continue with a more precise search.
(re-search-forward
(if ref
markdown-regex-link-reference
markdown-regex-link-inline)
last 'limit)))
;; Keep searching if this is in a code block, inline code, or a
;; comment, or if it is include syntax. The link text portion
;; (group 3) may contain inline code or comments, but the
;; markup, URL, and title should not be part of such elements.
(if (or (markdown-range-property-any
(match-beginning 0) (match-end 2) 'face prohibited-faces)
(markdown-range-property-any
(match-beginning 4) (match-end 0) 'face prohibited-faces)
(and (char-equal (char-after (point-at-bol)) ?<)
(char-equal (char-after (1+ (point-at-bol))) ?<)))
(set-match-data nil)
(setq found t))))
;; Match opening exclamation point (optional) and left bracket.
(when (match-beginning 2)
(let* ((bang (match-beginning 1))
(first-begin (match-beginning 2))
;; Find end of block to prevent matching across blocks.
(end-of-block (save-excursion
(progn
(goto-char (match-beginning 2))
(markdown-end-of-text-block)
(point))))
;; Move over balanced expressions to closing right bracket.
;; Catch unbalanced expression errors and return nil.
(first-end (condition-case nil
(and (goto-char first-begin)
(scan-sexps (point) 1))
(error nil)))
;; Continue with point at CONT-POINT upon failure.
(cont-point (min (1+ first-begin) last))
second-begin second-end url-begin url-end
title-begin title-end)
;; When bracket found, in range, and followed by a left paren/bracket...
(when (and first-end (< first-end end-of-block) (goto-char first-end)
(char-equal (char-after (point)) (if ref ?\[ ?\()))
;; Scan across balanced expressions for closing parenthesis/bracket.
(setq second-begin (point)
second-end (condition-case nil
(scan-sexps (point) 1)
(error nil)))
;; Check that closing parenthesis/bracket is in range.
(if (and second-end (<= second-end end-of-block) (<= second-end last))
(progn
;; Search for (optional) title inside closing parenthesis
(when (and (not ref) (search-forward "\"" second-end t))
(setq title-begin (1- (point))
title-end (and (goto-char second-end)
(search-backward "\"" (1+ title-begin) t))
title-end (and title-end (1+ title-end))))
;; Store URL/reference range
(setq url-begin (1+ second-begin)
url-end (1- (or title-begin second-end)))
;; Set match data, move point beyond link, and return
(set-match-data
(list (or bang first-begin) second-end ; 0 - all
bang (and bang (1+ bang)) ; 1 - bang
first-begin (1+ first-begin) ; 2 - markup
(1+ first-begin) (1- first-end) ; 3 - link text
(1- first-end) first-end ; 4 - markup
second-begin (1+ second-begin) ; 5 - markup
url-begin url-end ; 6 - url/reference
title-begin title-end ; 7 - title
(1- second-end) second-end)) ; 8 - markup
;; Nullify cont-point and leave point at end and
(setq cont-point nil)
(goto-char second-end))
;; If no closing parenthesis in range, update continuation point
(setq cont-point (min end-of-block second-begin))))
(cond
;; On failure, continue searching at cont-point
((and cont-point (< cont-point last))
(goto-char cont-point)
(markdown-match-generic-links last ref))
;; No more text, return nil
((and cont-point (= cont-point last))
nil)
;; Return t if a match occurred
(t t)))))
(defun markdown-match-angle-uris (last)
"Match angle bracket URIs from point to LAST."
(when (markdown-match-inline-generic markdown-regex-angle-uri last)
(goto-char (1+ (match-end 0)))))
(defun markdown-match-plain-uris (last)
"Match plain URIs from point to LAST."
(when (markdown-match-inline-generic markdown-regex-uri last t)
(goto-char (1+ (match-end 0)))))
(defvar markdown-conditional-search-function #'re-search-forward
"Conditional search function used in `markdown-search-until-condition'.
Made into a variable to allow for dynamic let-binding.")
(defun markdown-search-until-condition (condition &rest args)
(let (ret)
(while (and (not ret) (apply markdown-conditional-search-function args))
(setq ret (funcall condition)))
ret))
(defun markdown-match-generic-metadata (regexp last)
"Match metadata declarations specified by REGEXP from point to LAST.
These declarations must appear inside a metadata block that begins at
the beginning of the buffer and ends with a blank line (or the end of
the buffer)."
(let* ((first (point))
(end-re "\n[ \t]*\n\\|\n\\'\\|\\'")
(block-begin (goto-char 1))
(block-end (re-search-forward end-re nil t)))
(if (and block-end (> first block-end))
;; Don't match declarations if there is no metadata block or if
;; the point is beyond the block. Move point to point-max to
;; prevent additional searches and return return nil since nothing
;; was found.
(progn (goto-char (point-max)) nil)
;; If a block was found that begins before LAST and ends after
;; point, search for declarations inside it. If the starting is
;; before the beginning of the block, start there. Otherwise,
;; move back to FIRST.
(goto-char (if (< first block-begin) block-begin first))
(if (re-search-forward regexp (min last block-end) t)
;; If a metadata declaration is found, set match-data and return t.
(let ((key-beginning (match-beginning 1))
(key-end (match-end 1))
(markup-begin (match-beginning 2))
(markup-end (match-end 2))
(value-beginning (match-beginning 3)))
(set-match-data (list key-beginning (point) ; complete metadata
key-beginning key-end ; key
markup-begin markup-end ; markup
value-beginning (point))) ; value
t)
;; Otherwise, move the point to last and return nil
(goto-char last)
nil))))
(defun markdown-match-declarative-metadata (last)
"Match declarative metadata from the point to LAST."
(markdown-match-generic-metadata markdown-regex-declarative-metadata last))
(defun markdown-match-pandoc-metadata (last)
"Match Pandoc metadata from the point to LAST."
(markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
(defun markdown-match-yaml-metadata-begin (last)
(markdown-match-propertized-text 'markdown-yaml-metadata-begin last))
(defun markdown-match-yaml-metadata-end (last)
(markdown-match-propertized-text 'markdown-yaml-metadata-end last))
(defun markdown-match-yaml-metadata-key (last)
(markdown-match-propertized-text 'markdown-metadata-key last))
(defun markdown-match-wiki-link (last)
"Match wiki links from point to LAST."
(when (and markdown-enable-wiki-links
(not markdown-wiki-link-fontify-missing)
(markdown-match-inline-generic markdown-regex-wiki-link last))
(let ((begin (match-beginning 1)) (end (match-end 1)))
(if (or (markdown-in-comment-p begin)
(markdown-in-comment-p end)
(markdown-inline-code-at-pos-p begin)
(markdown-inline-code-at-pos-p end)
(markdown-code-block-at-pos begin))
(progn (goto-char (min (1+ begin) last))
(when (< (point) last)
(markdown-match-wiki-link last)))
(set-match-data (list begin end))
t))))
(defun markdown-match-inline-attributes (last)
"Match inline attributes from point to LAST."
(when (markdown-match-inline-generic markdown-regex-inline-attributes last)
(unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
(markdown-inline-code-at-pos-p (match-end 0))
(markdown-in-comment-p))
t)))
(defun markdown-match-leanpub-sections (last)
"Match Leanpub section markers from point to LAST."
(when (markdown-match-inline-generic markdown-regex-leanpub-sections last)
(unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
(markdown-inline-code-at-pos-p (match-end 0))
(markdown-in-comment-p))
t)))
(defun markdown-match-includes (last)
"Match include statements from point to LAST.
Sets match data for the following seven groups:
Group 1: opening two angle brackets
Group 2: opening title delimiter (optional)
Group 3: title text (optional)
Group 4: closing title delimiter (optional)
Group 5: opening filename delimiter
Group 6: filename
Group 7: closing filename delimiter"
(when (markdown-match-inline-generic markdown-regex-include last)
(let ((valid (not (or (markdown-in-comment-p (match-beginning 0))
(markdown-in-comment-p (match-end 0))
(markdown-code-block-at-pos (match-beginning 0))))))
(cond
;; Parentheses and maybe square brackets, but no curly braces:
;; match optional title in square brackets and file in parentheses.
((and valid (match-beginning 5)
(not (match-beginning 8)))
(set-match-data (list (match-beginning 1) (match-end 7)
(match-beginning 1) (match-end 1)
(match-beginning 2) (match-end 2)
(match-beginning 3) (match-end 3)
(match-beginning 4) (match-end 4)
(match-beginning 5) (match-end 5)
(match-beginning 6) (match-end 6)
(match-beginning 7) (match-end 7))))
;; Only square brackets present: match file in square brackets.
((and valid (match-beginning 2)
(not (match-beginning 5))
(not (match-beginning 7)))
(set-match-data (list (match-beginning 1) (match-end 4)
(match-beginning 1) (match-end 1)
nil nil
nil nil
nil nil
(match-beginning 2) (match-end 2)
(match-beginning 3) (match-end 3)
(match-beginning 4) (match-end 4))))
;; Only curly braces present: match file in curly braces.
((and valid (match-beginning 8)
(not (match-beginning 2))
(not (match-beginning 5)))
(set-match-data (list (match-beginning 1) (match-end 10)
(match-beginning 1) (match-end 1)
nil nil
nil nil
nil nil
(match-beginning 8) (match-end 8)
(match-beginning 9) (match-end 9)
(match-beginning 10) (match-end 10))))
(t
;; Not a valid match, move to next line and search again.
(forward-line)
(when (< (point) last)
(setq valid (markdown-match-includes last)))))
valid)))
(defun markdown-match-html-tag (last)
"Match HTML tags from point to LAST."
(when (and markdown-enable-html
(markdown-match-inline-generic markdown-regex-html-tag last t))
(set-match-data (list (match-beginning 0) (match-end 0)
(match-beginning 1) (match-end 1)
(match-beginning 2) (match-end 2)
(match-beginning 9) (match-end 9)))
t))
;;; Markdown Font Fontification Functions =====================================
(defun markdown--first-displayable (seq)
"Return the first displayable character or string in SEQ.
SEQ may be an atom or a sequence."
(let ((seq (if (listp seq) seq (list seq))))
(cond ((stringp (car seq))
(cl-find-if
(lambda (str)
(and (mapcar #'char-displayable-p (string-to-list str))))
seq))
((characterp (car seq))
(cl-find-if #'char-displayable-p seq)))))
(defun markdown--marginalize-string (level)
"Generate atx markup string of given LEVEL for left margin."
(let ((margin-left-space-count
(- markdown-marginalize-headers-margin-width level)))
(concat (make-string margin-left-space-count ? )
(make-string level ?#))))
(defun markdown-marginalize-update-current ()