Personal emacs config
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

490 lines
18 KiB

  1. ;;; yaml-mode.el --- Major mode for editing YAML files
  2. ;; Copyright (C) 2010-2014 Yoshiki Kurihara
  3. ;; Author: Yoshiki Kurihara <clouder@gmail.com>
  4. ;; Marshall T. Vandegrift <llasram@gmail.com>
  5. ;; Maintainer: Vasilij Schneidermann <mail@vasilij.de>
  6. ;; Package-Requires: ((emacs "24.1"))
  7. ;; Package-Version: 0.0.15
  8. ;; Package-Commit: fc5e1c58f94472944c4aa838f00f6adcac6fa992
  9. ;; Keywords: data yaml
  10. ;; Version: 0.0.15
  11. ;; This file is not part of Emacs
  12. ;; This file is free software; you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation; either version 2, or (at your option)
  15. ;; any later version.
  16. ;; This file is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License along
  21. ;; with this program; if not, write to the Free Software Foundation, Inc.,
  22. ;; 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  23. ;;; Commentary:
  24. ;; This is a major mode for editing files in the YAML data
  25. ;; serialization format. It was initially developed by Yoshiki
  26. ;; Kurihara and many features were added by Marshall Vandegrift. As
  27. ;; YAML and Python share the fact that indentation determines
  28. ;; structure, this mode provides indentation and indentation command
  29. ;; behavior very similar to that of python-mode.
  30. ;;; Installation:
  31. ;; To install, just drop this file into a directory in your
  32. ;; `load-path' and (optionally) byte-compile it. To automatically
  33. ;; handle files ending in '.yml', add something like:
  34. ;;
  35. ;; (require 'yaml-mode)
  36. ;; (add-to-list 'auto-mode-alist '("\\.yml\\'" . yaml-mode))
  37. ;;
  38. ;; to your .emacs file.
  39. ;;
  40. ;; Unlike python-mode, this mode follows the Emacs convention of not
  41. ;; binding the ENTER key to `newline-and-indent'. To get this
  42. ;; behavior, add the key definition to `yaml-mode-hook':
  43. ;;
  44. ;; (add-hook 'yaml-mode-hook
  45. ;; '(lambda ()
  46. ;; (define-key yaml-mode-map "\C-m" 'newline-and-indent)))
  47. ;;; Known Bugs:
  48. ;; YAML is easy to write but complex to parse, and this mode doesn't
  49. ;; even really try. Indentation and highlighting will break on
  50. ;; abnormally complicated structures.
  51. ;;; Code:
  52. ;; User definable variables
  53. ;;;###autoload
  54. (defgroup yaml nil
  55. "Support for the YAML serialization format"
  56. :group 'languages
  57. :prefix "yaml-")
  58. (defcustom yaml-mode-hook nil
  59. "*Hook run by `yaml-mode'."
  60. :type 'hook
  61. :group 'yaml)
  62. (defcustom yaml-indent-offset 2
  63. "*Amount of offset per level of indentation."
  64. :type 'integer
  65. :safe 'natnump
  66. :group 'yaml)
  67. (defcustom yaml-backspace-function 'backward-delete-char-untabify
  68. "*Function called by `yaml-electric-backspace' when deleting backwards.
  69. It will receive one argument, the numeric prefix value."
  70. :type 'function
  71. :group 'yaml)
  72. (defcustom yaml-block-literal-search-lines 100
  73. "*Maximum number of lines to search for start of block literals."
  74. :type 'integer
  75. :group 'yaml)
  76. (defcustom yaml-block-literal-electric-alist
  77. '((?| . "") (?> . "-"))
  78. "*Characters for which to provide electric behavior.
  79. The association list key should be a key code and the associated value
  80. should be a string containing additional characters to insert when
  81. that key is pressed to begin a block literal."
  82. :type 'alist
  83. :group 'yaml)
  84. (defface yaml-tab-face
  85. '((((class color)) (:background "red" :foreground "red" :bold t))
  86. (t (:reverse-video t)))
  87. "Face to use for highlighting tabs in YAML files."
  88. :group 'faces
  89. :group 'yaml)
  90. (defcustom yaml-imenu-generic-expression
  91. '((nil "^\\(:?[a-zA-Z_-]+\\):" 1))
  92. "The imenu regex to parse an outline of the yaml file."
  93. :type 'string
  94. :group 'yaml)
  95. ;; Constants
  96. (defconst yaml-mode-version "0.0.15" "Version of `yaml-mode'.")
  97. (defconst yaml-blank-line-re "^ *$"
  98. "Regexp matching a line containing only (valid) whitespace.")
  99. (defconst yaml-directive-re "^\\(?:--- \\)? *%\\(\\w+\\)"
  100. "Regexp matching a line contatining a YAML directive.")
  101. (defconst yaml-document-delimiter-re "^\\(?:---\\|[.][.][.]\\)"
  102. "Rexexp matching a YAML document delimiter line.")
  103. (defconst yaml-node-anchor-alias-re "[&*][a-zA-Z0-9_-]+"
  104. "Regexp matching a YAML node anchor or alias.")
  105. (defconst yaml-tag-re "!!?[^ \n]+"
  106. "Rexexp matching a YAML tag.")
  107. (defconst yaml-bare-scalar-re
  108. "\\(?:[^-:,#!\n{\\[ ]\\|[^#!\n{\\[ ]\\S-\\)[^#\n]*?"
  109. "Rexexp matching a YAML bare scalar.")
  110. (defconst yaml-hash-key-re
  111. (concat "\\(?:^\\(?:--- \\)?\\|{\\|\\(?:[-,] +\\)+\\) *"
  112. "\\(?:" yaml-tag-re " +\\)?"
  113. "\\(" yaml-bare-scalar-re "\\) *:"
  114. "\\(?: +\\|$\\)")
  115. "Regexp matching a single YAML hash key.")
  116. (defconst yaml-scalar-context-re
  117. (concat "\\(?:^\\(?:--- \\)?\\|{\\|\\(?: *[-,] +\\)+\\) *"
  118. "\\(?:" yaml-bare-scalar-re " *: \\)?")
  119. "Regexp indicating the beginning of a scalar context.")
  120. (defconst yaml-nested-map-re
  121. (concat "[^#\n]*: *\\(?:&.*\\|{ *\\|" yaml-tag-re " *\\)?$")
  122. "Regexp matching a line beginning a YAML nested structure.")
  123. (defconst yaml-block-literal-base-re " *[>|][-+0-9]* *\\(?:\n\\|\\'\\)"
  124. "Regexp matching the substring start of a block literal.")
  125. (defconst yaml-block-literal-re
  126. (concat yaml-scalar-context-re
  127. "\\(?:" yaml-tag-re "\\)?"
  128. yaml-block-literal-base-re)
  129. "Regexp matching a line beginning a YAML block literal.")
  130. (defconst yaml-nested-sequence-re
  131. (concat "^\\(?:\\(?: *- +\\)+\\|\\(:? *-$\\)\\)"
  132. "\\(?:" yaml-bare-scalar-re " *:\\(?: +.*\\)?\\)?$")
  133. "Regexp matching a line containing one or more nested YAML sequences.")
  134. (defconst yaml-constant-scalars-re
  135. (concat "\\(?:^\\|\\(?::\\|-\\|,\\|{\\|\\[\\) +\\) *"
  136. (regexp-opt
  137. '("~" "null" "Null" "NULL"
  138. ".nan" ".NaN" ".NAN"
  139. ".inf" ".Inf" ".INF"
  140. "-.inf" "-.Inf" "-.INF"
  141. "y" "Y" "yes" "Yes" "YES" "n" "N" "no" "No" "NO"
  142. "true" "True" "TRUE" "false" "False" "FALSE"
  143. "on" "On" "ON" "off" "Off" "OFF") t)
  144. " *$")
  145. "Regexp matching certain scalar constants in scalar context.")
  146. ;; Mode setup
  147. (defvar yaml-mode-map
  148. (let ((map (make-sparse-keymap)))
  149. (define-key map "|" 'yaml-electric-bar-and-angle)
  150. (define-key map ">" 'yaml-electric-bar-and-angle)
  151. (define-key map "-" 'yaml-electric-dash-and-dot)
  152. (define-key map "." 'yaml-electric-dash-and-dot)
  153. (define-key map (kbd "DEL") 'yaml-electric-backspace)
  154. map)
  155. "Keymap used in `yaml-mode' buffers.")
  156. (defvar yaml-mode-syntax-table
  157. (let ((syntax-table (make-syntax-table)))
  158. (modify-syntax-entry ?\' "\"" syntax-table)
  159. (modify-syntax-entry ?\" "\"" syntax-table)
  160. (modify-syntax-entry ?# "<" syntax-table)
  161. (modify-syntax-entry ?\n ">" syntax-table)
  162. (modify-syntax-entry ?\\ "\\" syntax-table)
  163. (modify-syntax-entry ?- "_" syntax-table)
  164. (modify-syntax-entry ?_ "_" syntax-table)
  165. (modify-syntax-entry ?& "." syntax-table)
  166. (modify-syntax-entry ?* "." syntax-table)
  167. (modify-syntax-entry ?\( "." syntax-table)
  168. (modify-syntax-entry ?\) "." syntax-table)
  169. (modify-syntax-entry ?\{ "(}" syntax-table)
  170. (modify-syntax-entry ?\} "){" syntax-table)
  171. (modify-syntax-entry ?\[ "(]" syntax-table)
  172. (modify-syntax-entry ?\] ")[" syntax-table)
  173. syntax-table)
  174. "Syntax table in use in `yaml-mode' buffers.")
  175. ;;;###autoload
  176. (define-derived-mode yaml-mode text-mode "YAML"
  177. "Simple mode to edit YAML.
  178. \\{yaml-mode-map}"
  179. :syntax-table yaml-mode-syntax-table
  180. (set (make-local-variable 'comment-start) "# ")
  181. (set (make-local-variable 'comment-start-skip) "#+ *")
  182. (set (make-local-variable 'indent-line-function) 'yaml-indent-line)
  183. (set (make-local-variable 'indent-tabs-mode) nil)
  184. (set (make-local-variable 'fill-paragraph-function) 'yaml-fill-paragraph)
  185. (set (make-local-variable 'syntax-propertize-function)
  186. 'yaml-mode-syntax-propertize-function)
  187. (setq font-lock-defaults '(yaml-font-lock-keywords)))
  188. ;; Font-lock support
  189. (defvar yaml-font-lock-keywords
  190. `((yaml-font-lock-block-literals 0 font-lock-string-face)
  191. (,yaml-constant-scalars-re . (1 font-lock-constant-face))
  192. (,yaml-tag-re . (0 font-lock-type-face))
  193. (,yaml-node-anchor-alias-re . (0 font-lock-function-name-face))
  194. (,yaml-hash-key-re . (1 font-lock-variable-name-face))
  195. (,yaml-document-delimiter-re . (0 font-lock-comment-face))
  196. (,yaml-directive-re . (1 font-lock-builtin-face))
  197. ("^[\t]+" 0 'yaml-tab-face t))
  198. "Additional expressions to highlight in YAML mode.")
  199. (defun yaml-mode-syntax-propertize-function (beg end)
  200. "Override buffer's syntax table for special syntactic constructs."
  201. ;; Unhighlight foo#bar tokens between BEG and END.
  202. (save-excursion
  203. (goto-char beg)
  204. (while (search-forward "#" end t)
  205. (save-excursion
  206. (forward-char -1)
  207. ;; both ^# and [ \t]# are comments
  208. (when (and (not (bolp))
  209. (not (memq (preceding-char) '(?\s ?\t))))
  210. (put-text-property (point) (1+ (point))
  211. 'syntax-table (string-to-syntax "_"))))))
  212. (save-excursion
  213. (goto-char beg)
  214. (while (and
  215. (> end (point))
  216. (re-search-forward "['\"]" end t))
  217. (when (get-text-property (point) 'yaml-block-literal)
  218. (put-text-property (1- (point)) (point)
  219. 'syntax-table (string-to-syntax "w")))
  220. (let* ((pt (point))
  221. (sps (save-excursion (syntax-ppss (1- pt)))))
  222. (when (not (nth 8 sps))
  223. (cond
  224. ((and (char-equal ?' (char-before (1- pt)))
  225. (char-equal ?' (char-before pt)))
  226. (put-text-property (- pt 2) pt
  227. 'syntax-table (string-to-syntax "w"))
  228. ;; Workaround for https://debbugs.gnu.org/41195.
  229. (let ((syntax-propertize--done syntax-propertize--done))
  230. ;; Carefully invalidate the last cached ppss.
  231. (syntax-ppss-flush-cache (- pt 2))))
  232. ;; If quote is detected as a syntactic string start but appeared
  233. ;; after a non-whitespace character, then mark it as syntactic word.
  234. ((and (char-before (1- pt))
  235. (char-equal ?w (char-syntax (char-before (1- pt)))))
  236. (put-text-property (1- pt) pt
  237. 'syntax-table (string-to-syntax "w")))
  238. (t
  239. ;; We're right after a quote that opens a string literal.
  240. ;; Skip over it (big speedup for long JSON strings).
  241. (goto-char (1- pt))
  242. (condition-case nil
  243. (forward-sexp)
  244. (scan-error
  245. (goto-char end))))))))))
  246. (defun yaml-font-lock-block-literals (bound)
  247. "Find lines within block literals.
  248. Find the next line of the first (if any) block literal after point and
  249. prior to BOUND. Returns the beginning and end of the block literal
  250. line in the match data, as consumed by `font-lock-keywords' matcher
  251. functions. The function begins by searching backwards to determine
  252. whether or not the current line is within a block literal. This could
  253. be time-consuming in large buffers, so the number of lines searched is
  254. artificially limited to the value of
  255. `yaml-block-literal-search-lines'."
  256. (if (eolp) (goto-char (1+ (point))))
  257. (unless (or (eobp) (>= (point) bound))
  258. (let ((begin (point))
  259. (end (min (1+ (point-at-eol)) bound)))
  260. (goto-char (point-at-bol))
  261. (while (and (looking-at yaml-blank-line-re)
  262. (not (bobp)))
  263. (forward-line -1))
  264. (let ((nlines yaml-block-literal-search-lines)
  265. (min-level (current-indentation)))
  266. (forward-line -1)
  267. (while (and (/= nlines 0)
  268. (/= min-level 0)
  269. (not (looking-at yaml-block-literal-re))
  270. (not (bobp)))
  271. (setq nlines (1- nlines))
  272. (unless (looking-at yaml-blank-line-re)
  273. (setq min-level (min min-level (current-indentation))))
  274. (forward-line -1))
  275. (when (looking-at-p " *- ")
  276. (setq min-level (- min-level 2)))
  277. (cond
  278. ((and (< (current-indentation) min-level)
  279. (looking-at yaml-block-literal-re))
  280. (goto-char end)
  281. (put-text-property begin end 'yaml-block-literal t)
  282. (set-match-data (list begin end))
  283. t)
  284. ((progn
  285. (goto-char begin)
  286. (re-search-forward (concat yaml-block-literal-re
  287. " *\\(.*\\)\n")
  288. bound t))
  289. (let ((range (nthcdr 2 (match-data))))
  290. (put-text-property (car range) (cadr range) 'yaml-block-literal t)
  291. (set-match-data range))
  292. t))))))
  293. ;; Indentation and electric keys
  294. (defun yaml-compute-indentation ()
  295. "Calculate the maximum sensible indentation for the current line."
  296. (save-excursion
  297. (beginning-of-line)
  298. (if (looking-at yaml-document-delimiter-re) 0
  299. (forward-line -1)
  300. (while (and (looking-at yaml-blank-line-re)
  301. (> (point) (point-min)))
  302. (forward-line -1))
  303. (+ (current-indentation)
  304. (if (looking-at yaml-nested-map-re) yaml-indent-offset 0)
  305. (if (looking-at yaml-nested-sequence-re) yaml-indent-offset 0)
  306. (if (looking-at yaml-block-literal-re) yaml-indent-offset 0)))))
  307. (defun yaml-indent-line ()
  308. "Indent the current line.
  309. The first time this command is used, the line will be indented to the
  310. maximum sensible indentation. Each immediately subsequent usage will
  311. back-dent the line by `yaml-indent-offset' spaces. On reaching column
  312. 0, it will cycle back to the maximum sensible indentation."
  313. (interactive "*")
  314. (let ((ci (current-indentation))
  315. (cc (current-column))
  316. (need (yaml-compute-indentation)))
  317. (save-excursion
  318. (beginning-of-line)
  319. (delete-horizontal-space)
  320. (if (and (equal last-command this-command) (/= ci 0))
  321. (indent-to (* (/ (- ci 1) yaml-indent-offset) yaml-indent-offset))
  322. (indent-to need)))
  323. (if (< (current-column) (current-indentation))
  324. (forward-to-indentation 0))))
  325. (defun yaml-electric-backspace (arg)
  326. "Delete characters or back-dent the current line.
  327. If invoked following only whitespace on a line, will back-dent to the
  328. immediately previous multiple of `yaml-indent-offset' spaces."
  329. (interactive "*p")
  330. (if (or (/= (current-indentation) (current-column)) (bolp))
  331. (funcall yaml-backspace-function arg)
  332. (let ((ci (current-column)))
  333. (beginning-of-line)
  334. (delete-horizontal-space)
  335. (indent-to (* (/ (- ci (* arg yaml-indent-offset))
  336. yaml-indent-offset)
  337. yaml-indent-offset)))))
  338. (defun yaml-electric-bar-and-angle (arg)
  339. "Insert the bound key and possibly begin a block literal.
  340. Inserts the bound key. If inserting the bound key causes the current
  341. line to match the initial line of a block literal, then inserts the
  342. matching string from `yaml-block-literal-electric-alist', a newline,
  343. and indents appropriately."
  344. (interactive "*P")
  345. (self-insert-command (prefix-numeric-value arg))
  346. (let ((extra-chars
  347. (assoc last-command-event
  348. yaml-block-literal-electric-alist)))
  349. (cond
  350. ((and extra-chars (not arg) (eolp)
  351. (save-excursion
  352. (beginning-of-line)
  353. (looking-at yaml-block-literal-re)))
  354. (insert (cdr extra-chars))
  355. (newline-and-indent)))))
  356. (defun yaml-electric-dash-and-dot (arg)
  357. "Insert the bound key and possibly de-dent line.
  358. Inserts the bound key. If inserting the bound key causes the current
  359. line to match a document delimiter, de-dent the line to the left
  360. margin."
  361. (interactive "*P")
  362. (self-insert-command (prefix-numeric-value arg))
  363. (save-excursion
  364. (beginning-of-line)
  365. (when (and (not arg) (looking-at yaml-document-delimiter-re))
  366. (delete-horizontal-space))))
  367. (defun yaml-narrow-to-block-literal ()
  368. "Narrow the buffer to block literal if the point is in it,
  369. otherwise do nothing."
  370. (interactive)
  371. (save-excursion
  372. (goto-char (point-at-bol))
  373. (while (and (looking-at-p yaml-blank-line-re) (not (bobp)))
  374. (forward-line -1))
  375. (let ((nlines yaml-block-literal-search-lines)
  376. (min-level (current-indentation))
  377. beg)
  378. (forward-line -1)
  379. (while (and (/= nlines 0)
  380. (/= min-level 0)
  381. (not (looking-at-p yaml-block-literal-re))
  382. (not (bobp)))
  383. (setq nlines (1- nlines))
  384. (unless (looking-at-p yaml-blank-line-re)
  385. (setq min-level (min min-level (current-indentation))))
  386. (forward-line -1))
  387. (when (and (< (current-indentation) min-level)
  388. (looking-at-p yaml-block-literal-re))
  389. (setq min-level (current-indentation))
  390. (forward-line)
  391. (setq beg (point))
  392. (while (and (not (eobp))
  393. (or (looking-at-p yaml-blank-line-re)
  394. (> (current-indentation) min-level)))
  395. (forward-line))
  396. (narrow-to-region beg (point))))))
  397. (defun yaml-fill-paragraph (&optional justify region)
  398. "Fill paragraph.
  399. Outside of comments, this behaves as `fill-paragraph' except that
  400. filling does not cross boundaries of block literals. Inside comments,
  401. this will do usual adaptive fill behaviors."
  402. (interactive "*P")
  403. (save-restriction
  404. (yaml-narrow-to-block-literal)
  405. (let ((fill-paragraph-function nil))
  406. (or (fill-comment-paragraph justify)
  407. (fill-paragraph justify region)))))
  408. (defun yaml-set-imenu-generic-expression ()
  409. (make-local-variable 'imenu-generic-expression)
  410. (make-local-variable 'imenu-create-index-function)
  411. (setq imenu-create-index-function 'imenu-default-create-index-function)
  412. (setq imenu-generic-expression yaml-imenu-generic-expression))
  413. (add-hook 'yaml-mode-hook 'yaml-set-imenu-generic-expression)
  414. (defun yaml-mode-version ()
  415. "Display version of `yaml-mode'."
  416. (interactive)
  417. (message "yaml-mode %s" yaml-mode-version)
  418. yaml-mode-version)
  419. ;;;###autoload
  420. (add-to-list 'auto-mode-alist '("\\.\\(e?ya?\\|ra\\)ml\\'" . yaml-mode))
  421. (provide 'yaml-mode)
  422. ;;; yaml-mode.el ends here