Document reserved keys
[emacs.git] / lisp / textmodes / sgml-mode.el
blobeb6ebf5280731721b1bdc4514430c2618d252d9a
1 ;;; sgml-mode.el --- SGML- and HTML-editing modes -*- lexical-binding:t -*-
3 ;; Copyright (C) 1992, 1995-1996, 1998, 2001-2018 Free Software
4 ;; Foundation, Inc.
6 ;; Author: James Clark <jjc@jclark.com>
7 ;; Maintainer: emacs-devel@gnu.org
8 ;; Adapted-By: ESR, Daniel Pfeiffer <occitan@esperanto.org>,
9 ;; F.Potorti@cnuce.cnr.it
10 ;; Keywords: wp, hypermedia, comm, languages
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
27 ;;; Commentary:
29 ;; Configurable major mode for editing document in the SGML standard general
30 ;; markup language. As an example contains a mode for editing the derived
31 ;; HTML hypertext markup language.
33 ;;; Code:
35 (require 'dom)
36 (require 'seq)
37 (eval-when-compile (require 'subr-x))
38 (eval-when-compile
39 (require 'skeleton)
40 (require 'cl-lib))
42 (defgroup sgml nil
43 "SGML editing mode."
44 :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
45 :group 'languages)
47 (defcustom sgml-basic-offset 2
48 "Specifies the basic indentation level for `sgml-indent-line'."
49 :type 'integer
50 :group 'sgml)
52 (defcustom sgml-attribute-offset 0
53 "Specifies a delta for attribute indentation in `sgml-indent-line'.
55 When 0, attribute indentation looks like this:
57 <element
58 attribute=\"value\">
59 </element>
61 When 2, attribute indentation looks like this:
63 <element
64 attribute=\"value\">
65 </element>"
66 :version "25.1"
67 :type 'integer
68 :safe 'integerp
69 :group 'sgml)
71 (defcustom sgml-xml-mode nil
72 "When non-nil, tag insertion functions will be XML-compliant.
73 It is set to be buffer-local when the file has
74 a DOCTYPE or an XML declaration."
75 :type 'boolean
76 :version "22.1"
77 :group 'sgml)
79 (defcustom sgml-transformation-function 'identity
80 "Default value for `skeleton-transformation-function' in SGML mode."
81 :type 'function
82 :initialize 'custom-initialize-default
83 :set (lambda (sym val)
84 (set-default sym val)
85 (mapc (lambda (buff)
86 (with-current-buffer buff
87 (and (derived-mode-p 'sgml-mode)
88 (not sgml-xml-mode)
89 (setq skeleton-transformation-function val))))
90 (buffer-list)))
91 :group 'sgml)
93 (put 'sgml-transformation-function 'variable-interactive
94 "aTransformation function: ")
95 (defvaralias 'sgml-transformation 'sgml-transformation-function)
97 (defcustom sgml-mode-hook nil
98 "Hook run by command `sgml-mode'.
99 `text-mode-hook' is run first."
100 :group 'sgml
101 :type 'hook)
103 ;; As long as Emacs's syntax can't be complemented with predicates to context
104 ;; sensitively confirm the syntax of characters, we have to live with this
105 ;; kludgy kind of tradeoff.
106 (defvar sgml-specials '(?\")
107 "List of characters that have a special meaning for SGML mode.
108 This list is used when first loading the `sgml-mode' library.
109 The supported characters and potential disadvantages are:
111 ?\\\" Makes \" in text start a string.
112 ?\\=' Makes \\=' in text start a string.
113 ?- Makes -- in text start a comment.
115 When only one of ?\\\" or ?\\=' are included, \"\\='\" or \\='\"\\=', as can be found in
116 DTDs, start a string. To partially avoid this problem this also makes these
117 self insert as named entities depending on `sgml-quick-keys'.
119 Including ?- has the problem of affecting dashes that have nothing to do
120 with comments, so we normally turn it off.")
122 (defvar sgml-quick-keys nil
123 "Use <, >, &, /, SPC and `sgml-specials' keys \"electrically\" when non-nil.
124 This takes effect when first loading the `sgml-mode' library.")
126 (defvar sgml-mode-map
127 (let ((map (make-keymap)) ;`sparse' doesn't allow binding to charsets.
128 (menu-map (make-sparse-keymap "SGML")))
129 (define-key map "\C-c\C-i" 'sgml-tags-invisible)
130 (define-key map "/" 'sgml-slash)
131 (define-key map "\C-c\C-n" 'sgml-name-char)
132 (define-key map "\C-c\C-t" 'sgml-tag)
133 (define-key map "\C-c\C-a" 'sgml-attributes)
134 (define-key map "\C-c\C-b" 'sgml-skip-tag-backward)
135 (define-key map [?\C-c left] 'sgml-skip-tag-backward)
136 (define-key map "\C-c\C-f" 'sgml-skip-tag-forward)
137 (define-key map [?\C-c right] 'sgml-skip-tag-forward)
138 (define-key map "\C-c\C-d" 'sgml-delete-tag)
139 (define-key map "\C-c\^?" 'sgml-delete-tag)
140 (define-key map "\C-c?" 'sgml-tag-help)
141 (define-key map "\C-c]" 'sgml-close-tag)
142 (define-key map "\C-c/" 'sgml-close-tag)
144 ;; Redundant keybindings, for consistency with TeX mode.
145 (define-key map "\C-c\C-o" 'sgml-tag)
146 (define-key map "\C-c\C-e" 'sgml-close-tag)
148 (define-key map "\C-c8" 'sgml-name-8bit-mode)
149 (define-key map "\C-c\C-v" 'sgml-validate)
150 (when sgml-quick-keys
151 (define-key map "&" 'sgml-name-char)
152 (define-key map "<" 'sgml-tag)
153 (define-key map " " 'sgml-auto-attributes)
154 (define-key map ">" 'sgml-maybe-end-tag)
155 (when (memq ?\" sgml-specials)
156 (define-key map "\"" 'sgml-name-self))
157 (when (memq ?' sgml-specials)
158 (define-key map "'" 'sgml-name-self)))
159 (let ((c 127)
160 (map (nth 1 map)))
161 (while (< (setq c (1+ c)) 256)
162 (aset map c 'sgml-maybe-name-self)))
163 (define-key map [menu-bar sgml] (cons "SGML" menu-map))
164 (define-key menu-map [sgml-validate] '("Validate" . sgml-validate))
165 (define-key menu-map [sgml-name-8bit-mode]
166 '("Toggle 8 Bit Insertion" . sgml-name-8bit-mode))
167 (define-key menu-map [sgml-tags-invisible]
168 '("Toggle Tag Visibility" . sgml-tags-invisible))
169 (define-key menu-map [sgml-tag-help]
170 '("Describe Tag" . sgml-tag-help))
171 (define-key menu-map [sgml-delete-tag]
172 '("Delete Tag" . sgml-delete-tag))
173 (define-key menu-map [sgml-skip-tag-forward]
174 '("Forward Tag" . sgml-skip-tag-forward))
175 (define-key menu-map [sgml-skip-tag-backward]
176 '("Backward Tag" . sgml-skip-tag-backward))
177 (define-key menu-map [sgml-attributes]
178 '("Insert Attributes" . sgml-attributes))
179 (define-key menu-map [sgml-tag] '("Insert Tag" . sgml-tag))
180 map)
181 "Keymap for SGML mode. See also `sgml-specials'.")
183 (defun sgml-make-syntax-table (specials)
184 (let ((table (make-syntax-table text-mode-syntax-table)))
185 (modify-syntax-entry ?< "(>" table)
186 (modify-syntax-entry ?> ")<" table)
187 (modify-syntax-entry ?: "_" table)
188 (modify-syntax-entry ?_ "_" table)
189 (modify-syntax-entry ?. "_" table)
190 (if (memq ?- specials)
191 (modify-syntax-entry ?- "_ 1234" table))
192 (if (memq ?\" specials)
193 (modify-syntax-entry ?\" "\"\"" table))
194 (if (memq ?' specials)
195 (modify-syntax-entry ?\' "\"'" table))
196 table))
198 (defvar sgml-mode-syntax-table (sgml-make-syntax-table sgml-specials)
199 "Syntax table used in SGML mode. See also `sgml-specials'.")
201 (defconst sgml-tag-syntax-table
202 (let ((table (sgml-make-syntax-table sgml-specials)))
203 (dolist (char '(?\( ?\) ?\{ ?\} ?\[ ?\] ?$ ?% ?& ?* ?+ ?/))
204 (modify-syntax-entry char "." table))
205 (unless (memq ?' sgml-specials)
206 ;; Avoid that skipping a tag backwards skips any "'" prefixing it.
207 (modify-syntax-entry ?' "w" table))
208 table)
209 "Syntax table used to parse SGML tags.")
211 (defcustom sgml-name-8bit-mode nil
212 "When non-nil, insert non-ASCII characters as named entities."
213 :type 'boolean
214 :group 'sgml)
216 (defvar sgml-char-names
217 [nil nil nil nil nil nil nil nil
218 nil nil nil nil nil nil nil nil
219 nil nil nil nil nil nil nil nil
220 nil nil nil nil nil nil nil nil
221 "nbsp" "excl" "quot" "num" "dollar" "percnt" "amp" "apos"
222 "lpar" "rpar" "ast" "plus" "comma" "hyphen" "period" "sol"
223 nil nil nil nil nil nil nil nil
224 nil nil "colon" "semi" "lt" "eq" "gt" "quest"
225 "commat" nil nil nil nil nil nil nil
226 nil nil nil nil nil nil nil nil
227 nil nil nil nil nil nil nil nil
228 nil nil nil "lsqb" nil "rsqb" "uarr" "lowbar"
229 "lsquo" nil nil nil nil nil nil nil
230 nil nil nil nil nil nil nil nil
231 nil nil nil nil nil nil nil nil
232 nil nil nil "lcub" "verbar" "rcub" "tilde" nil
233 nil nil nil nil nil nil nil nil
234 nil nil nil nil nil nil nil nil
235 nil nil nil nil nil nil nil nil
236 nil nil nil nil nil nil nil nil
237 "nbsp" "iexcl" "cent" "pound" "curren" "yen" "brvbar" "sect"
238 "uml" "copy" "ordf" "laquo" "not" "shy" "reg" "macr"
239 "ring" "plusmn" "sup2" "sup3" "acute" "micro" "para" "middot"
240 "cedil" "sup1" "ordm" "raquo" "frac14" "frac12" "frac34" "iquest"
241 "Agrave" "Aacute" "Acirc" "Atilde" "Auml" "Aring" "AElig" "Ccedil"
242 "Egrave" "Eacute" "Ecirc" "Euml" "Igrave" "Iacute" "Icirc" "Iuml"
243 "ETH" "Ntilde" "Ograve" "Oacute" "Ocirc" "Otilde" "Ouml" nil
244 "Oslash" "Ugrave" "Uacute" "Ucirc" "Uuml" "Yacute" "THORN" "szlig"
245 "agrave" "aacute" "acirc" "atilde" "auml" "aring" "aelig" "ccedil"
246 "egrave" "eacute" "ecirc" "euml" "igrave" "iacute" "icirc" "iuml"
247 "eth" "ntilde" "ograve" "oacute" "ocirc" "otilde" "ouml" "divide"
248 "oslash" "ugrave" "uacute" "ucirc" "uuml" "yacute" "thorn" "yuml"]
249 "Vector of symbolic character names without `&' and `;'.")
251 (put 'sgml-table 'char-table-extra-slots 0)
253 (defvar sgml-char-names-table
254 (let ((table (make-char-table 'sgml-table))
255 (i 32)
256 elt)
257 (while (< i 128)
258 (setq elt (aref sgml-char-names i))
259 (if elt (aset table (make-char 'latin-iso8859-1 i) elt))
260 (setq i (1+ i)))
261 table)
262 "A table for mapping non-ASCII characters into SGML entity names.
263 Currently, only Latin-1 characters are supported.")
265 (defcustom sgml-validate-command
266 ;; prefer tidy because (o)nsgmls is often built without --enable-http
267 ;; which makes it next to useless
268 (cond ((executable-find "tidy")
269 ;; tidy is available from http://tidy.sourceforge.net/
270 "tidy --gnu-emacs yes -utf8 -e -q")
271 ((executable-find "nsgmls")
272 ;; nsgmls is a free SGML parser in the SP suite available from
273 ;; ftp.jclark.com, replaced old `sgmls'.
274 "nsgmls -s")
275 ((executable-find "onsgmls")
276 ;; onsgmls is the community version of `nsgmls'
277 ;; hosted on http://openjade.sourceforge.net/
278 "onsgmls -s")
279 (t "Install (o)nsgmls, tidy, or some other SGML validator, and set `sgml-validate-command'"))
280 "The command to validate an SGML document.
281 The file name of current buffer file name will be appended to this,
282 separated by a space."
283 :type 'string
284 :version "21.1"
285 :group 'sgml)
287 (defvar sgml-saved-validate-command nil
288 "The command last used to validate in this buffer.")
290 ;; I doubt that null end tags are used much for large elements,
291 ;; so use a small distance here.
292 (defcustom sgml-slash-distance 1000
293 "If non-nil, is the maximum distance to search for matching `/'."
294 :type '(choice (const nil) integer)
295 :group 'sgml)
297 (defconst sgml-namespace-re "[_[:alpha:]][-_.[:alnum:]]*")
298 (defconst sgml-name-re "[_:[:alpha:]][-_.:[:alnum:]]*")
299 (defconst sgml-tag-name-re (concat "<\\([!/?]?" sgml-name-re "\\)"))
300 (defconst sgml-attrs-re "\\(?:[^\"'/><]\\|\"[^\"]*\"\\|'[^']*'\\)*")
301 (defconst sgml-start-tag-regex (concat "<" sgml-name-re sgml-attrs-re)
302 "Regular expression that matches a non-empty start tag.
303 Any terminating `>' or `/' is not matched.")
305 (defface sgml-namespace
306 '((t (:inherit font-lock-builtin-face)))
307 "`sgml-mode' face used to highlight the namespace part of identifiers."
308 :group 'sgml)
309 (defvar sgml-namespace-face 'sgml-namespace)
311 ;; internal
312 (defconst sgml-font-lock-keywords-1
313 `((,(concat "<\\([!?]" sgml-name-re "\\)") 1 font-lock-keyword-face)
314 ;; We could use the simpler "\\(" sgml-namespace-re ":\\)?" instead,
315 ;; but it would cause a bit more backtracking in the re-matcher.
316 (,(concat "</?\\(" sgml-namespace-re "\\)\\(?::\\(" sgml-name-re "\\)\\)?")
317 (1 (if (match-end 2) sgml-namespace-face font-lock-function-name-face))
318 (2 font-lock-function-name-face nil t))
319 ;; FIXME: this doesn't cover the variables using a default value.
320 ;; The first shy-group is an important anchor: it prevents an O(n^2)
321 ;; pathological case where we otherwise keep retrying a failing match
322 ;; against a very long word at every possible position within the word.
323 (,(concat "\\(?:^\\|[ \t]\\)\\(" sgml-namespace-re "\\)\\(?::\\("
324 sgml-name-re "\\)\\)?=[\"']")
325 (1 (if (match-end 2) sgml-namespace-face font-lock-variable-name-face))
326 (2 font-lock-variable-name-face nil t))
327 (,(concat "[&%]" sgml-name-re ";?") . font-lock-variable-name-face)))
329 (defconst sgml-font-lock-keywords-2
330 (append
331 sgml-font-lock-keywords-1
332 '((eval
333 . (cons (concat "<"
334 (regexp-opt (mapcar 'car sgml-tag-face-alist) t)
335 "\\([ \t][^>]*\\)?>\\([^<]+\\)</\\1>")
336 '(3 (cdr (assoc-string (match-string 1) sgml-tag-face-alist t))
337 prepend))))))
339 ;; for font-lock, but must be defvar'ed after
340 ;; sgml-font-lock-keywords-1 and sgml-font-lock-keywords-2 above
341 (defvar sgml-font-lock-keywords sgml-font-lock-keywords-1
342 "Rules for highlighting SGML code. See also `sgml-tag-face-alist'.")
344 (eval-and-compile
345 (defconst sgml-syntax-propertize-rules
346 (syntax-propertize-precompile-rules
347 ;; Use the `b' style of comments to avoid interference with the -- ... --
348 ;; comments recognized when `sgml-specials' includes ?-.
349 ;; FIXME: beware of <!--> blabla <!--> !!
350 ("\\(<\\)!--" (1 "< b"))
351 ("--[ \t\n]*\\(>\\)" (1 "> b"))
352 ("\\(<\\)[?!]" (1 (prog1 "|>"
353 (sgml-syntax-propertize-inside end))))
354 ;; Double quotes outside of tags should not introduce strings.
355 ;; Be careful to call `syntax-ppss' on a position before the one we're
356 ;; going to change, so as not to need to flush the data we just computed.
357 ("\"" (0 (if (prog1 (zerop (car (syntax-ppss (match-beginning 0))))
358 (goto-char (match-end 0)))
359 (string-to-syntax ".")))))))
361 (defun sgml-syntax-propertize (start end)
362 "Syntactic keywords for `sgml-mode'."
363 (goto-char start)
364 (sgml-syntax-propertize-inside end)
365 (funcall
366 (syntax-propertize-rules sgml-syntax-propertize-rules)
367 start end))
369 (defun sgml-syntax-propertize-inside (end)
370 (let ((ppss (syntax-ppss)))
371 (cond
372 ((eq (nth 3 ppss) t)
373 (let ((endre (save-excursion
374 (goto-char (nth 8 ppss))
375 (cond
376 ((looking-at-p "<!\\[CDATA\\[") "]]>")
377 ((looking-at-p "<\\?") (if sgml-xml-mode "\\?>" ">"))
378 (t ">")))))
379 (when (re-search-forward endre end 'move)
380 (put-text-property (1- (point)) (point)
381 'syntax-table (string-to-syntax "|<"))))))))
383 ;; internal
384 (defvar sgml-face-tag-alist ()
385 "Alist of face and tag name for facemenu.")
387 (defvar sgml-tag-face-alist ()
388 "Tag names and face or list of faces to fontify with when invisible.
389 When `font-lock-maximum-decoration' is 1 this is always used for fontifying.
390 When more these are fontified together with `sgml-font-lock-keywords'.")
392 (defvar sgml-display-text ()
393 "Tag names as lowercase symbols, and display string when invisible.")
395 ;; internal
396 (defvar sgml-tags-invisible nil)
398 (defcustom sgml-tag-alist
399 '(("![" ("ignore" t) ("include" t))
400 ("!attlist")
401 ("!doctype")
402 ("!element")
403 ("!entity"))
404 "Alist of tag names for completing read and insertion rules.
405 This alist is made up as
407 ((\"tag\" . TAGRULE)
408 ...)
410 TAGRULE is a list of optionally t (no endtag) or `\\n' (separate endtag by
411 newlines) or a skeleton with nil, t or `\\n' in place of the interactor
412 followed by an ATTRIBUTERULE (for an always present attribute) or an
413 attribute alist.
415 The attribute alist is made up as
417 ((\"attribute\" . ATTRIBUTERULE)
418 ...)
420 ATTRIBUTERULE is a list of optionally t (no value when no input) followed by
421 an optional alist of possible values."
422 :type '(repeat (cons (string :tag "Tag Name")
423 (repeat :tag "Tag Rule" sexp)))
424 :group 'sgml)
425 (put 'sgml-tag-alist 'risky-local-variable t)
427 (defcustom sgml-tag-help
428 '(("!" . "Empty declaration for comment")
429 ("![" . "Embed declarations with parser directive")
430 ("!attlist" . "Tag attributes declaration")
431 ("!doctype" . "Document type (DTD) declaration")
432 ("!element" . "Tag declaration")
433 ("!entity" . "Entity (macro) declaration"))
434 "Alist of tag name and short description."
435 :type '(repeat (cons (string :tag "Tag Name")
436 (string :tag "Description")))
437 :group 'sgml)
439 (defvar sgml-empty-tags nil
440 "List of tags whose !ELEMENT definition says EMPTY.")
442 (defvar sgml-unclosed-tags nil
443 "List of tags whose !ELEMENT definition says the end-tag is optional.")
445 (defun sgml-xml-guess ()
446 "Guess whether the current buffer is XML. Return non-nil if so."
447 (save-excursion
448 (goto-char (point-min))
449 (or (string= "xml" (file-name-extension (or buffer-file-name "")))
450 ;; Maybe the buffer-size check isn't needed, I don't know.
451 (and (zerop (buffer-size))
452 (string= "xhtml" (file-name-extension (or buffer-file-name ""))))
453 (looking-at "\\s-*<\\?xml")
454 (when (re-search-forward
455 (eval-when-compile
456 (mapconcat 'identity
457 '("<!DOCTYPE" "\\(\\w+\\)" "\\(\\w+\\)"
458 "\"\\([^\"]+\\)\"" "\"\\([^\"]+\\)\"")
459 "\\s-+"))
460 nil t)
461 (string-match "X\\(HT\\)?ML" (match-string 3))))))
463 (defvar v2) ; free for skeleton
465 (defun sgml-comment-indent-new-line (&optional soft)
466 (let ((comment-start "-- ")
467 (comment-start-skip "\\(<!\\)?--[ \t]*")
468 (comment-end " --")
469 (comment-style 'plain))
470 (comment-indent-new-line soft)))
472 (defun sgml-mode-facemenu-add-face-function (face _end)
473 (let ((tag-face (cdr (assq face sgml-face-tag-alist))))
474 (cond (tag-face
475 (setq tag-face (funcall skeleton-transformation-function tag-face))
476 (setq facemenu-end-add-face (concat "</" tag-face ">"))
477 (concat "<" tag-face ">"))
478 ((and (consp face)
479 (consp (car face))
480 (null (cdr face))
481 (memq (caar face) '(:foreground :background)))
482 (setq facemenu-end-add-face "</span>")
483 (format "<span style=\"%s:%s\">"
484 (if (eq (caar face) :foreground)
485 "color"
486 "background-color")
487 (cadr (car face))))
489 (error "Face not configured for %s mode"
490 (format-mode-line mode-name))))))
492 (defun sgml-fill-nobreak ()
493 "Don't break between a tag name and its first argument.
494 This function is designed for use in `fill-nobreak-predicate'.
496 <a href=\"some://where\" type=\"text/plain\">
498 | no break here | but still allowed here"
499 (save-excursion
500 (skip-chars-backward " \t")
501 (and (not (zerop (skip-syntax-backward "w_")))
502 (skip-chars-backward "/?!")
503 (eq (char-before) ?<))))
505 (defvar tildify-space-string)
506 (defvar tildify-foreach-region-function)
508 ;;;###autoload
509 (define-derived-mode sgml-mode text-mode '(sgml-xml-mode "XML" "SGML")
510 "Major mode for editing SGML documents.
511 Makes > match <.
512 Keys <, &, SPC within <>, \", / and \\=' can be electric depending on
513 `sgml-quick-keys'.
515 An argument of N to a tag-inserting command means to wrap it around
516 the next N words. In Transient Mark mode, when the mark is active,
517 N defaults to -1, which means to wrap it around the current region.
519 If you like upcased tags, put (setq sgml-transformation-function \\='upcase)
520 in your init file.
522 Use \\[sgml-validate] to validate your document with an SGML parser.
524 Do \\[describe-variable] sgml- SPC to see available variables.
525 Do \\[describe-key] on the following bindings to discover what they do.
526 \\{sgml-mode-map}"
527 (make-local-variable 'sgml-saved-validate-command)
528 (make-local-variable 'facemenu-end-add-face)
529 ;; If encoding does not allow non-break space character, use reference.
530 ;; FIXME: Perhaps use &nbsp; if possible (e.g. when we know its HTML)?
531 (setq-local tildify-space-string
532 (if (equal (decode-coding-string
533 (encode-coding-string " " buffer-file-coding-system)
534 buffer-file-coding-system) " ")
535 " " "&#160;"))
536 ;; FIXME: Use the fact that we're parsing the document already
537 ;; rather than using regex-based filtering.
538 (setq-local tildify-foreach-region-function
539 (apply-partially
540 'tildify-foreach-ignore-environments
541 `((,(eval-when-compile
542 (concat
543 "<\\("
544 (regexp-opt '("pre" "dfn" "code" "samp" "kbd" "var"
545 "PRE" "DFN" "CODE" "SAMP" "KBD" "VAR"))
546 "\\)\\>[^>]*>"))
547 . ("</" 1 ">"))
548 ("<! *--" . "-- *>")
549 ("<" . ">"))))
550 ;;(make-local-variable 'facemenu-remove-face-function)
551 ;; A start or end tag by itself on a line separates a paragraph.
552 ;; This is desirable because SGML discards a newline that appears
553 ;; immediately after a start tag or immediately before an end tag.
554 (setq-local paragraph-start (concat "[ \t]*$\\|\
555 [ \t]*</?\\(" sgml-name-re sgml-attrs-re "\\)?>"))
556 (setq-local paragraph-separate (concat paragraph-start "$"))
557 (setq-local adaptive-fill-regexp "[ \t]*")
558 (add-hook 'fill-nobreak-predicate 'sgml-fill-nobreak nil t)
559 (setq-local indent-line-function 'sgml-indent-line)
560 (setq-local comment-start "<!-- ")
561 (setq-local comment-end " -->")
562 (setq-local comment-indent-function 'sgml-comment-indent)
563 (setq-local comment-line-break-function 'sgml-comment-indent-new-line)
564 (setq-local skeleton-further-elements '((completion-ignore-case t)))
565 (setq-local skeleton-end-hook
566 (lambda ()
567 (or (eolp)
568 (not (or (eq v2 '\n) (eq (car-safe v2) '\n)))
569 (newline-and-indent))))
570 (setq font-lock-defaults '((sgml-font-lock-keywords
571 sgml-font-lock-keywords-1
572 sgml-font-lock-keywords-2)
573 nil t))
574 (setq-local syntax-propertize-function #'sgml-syntax-propertize)
575 (setq-local facemenu-add-face-function 'sgml-mode-facemenu-add-face-function)
576 (setq-local sgml-xml-mode (sgml-xml-guess))
577 (unless sgml-xml-mode
578 (setq-local skeleton-transformation-function sgml-transformation-function))
579 ;; This will allow existing comments within declarations to be
580 ;; recognized.
581 ;; I can't find a clear description of SGML/XML comments, but it seems that
582 ;; the only reliable ones are <!-- ... --> although it's not clear what
583 ;; "..." can contain. It used to accept -- ... -- as well, but that was
584 ;; apparently a mistake.
585 (setq-local comment-start-skip "<!--[ \t]*")
586 (setq-local comment-end-skip "[ \t]*--[ \t\n]*>")
587 ;; This definition has an HTML leaning but probably fits well for other modes.
588 (setq imenu-generic-expression
589 `((nil
590 ,(concat "<!\\(element\\|entity\\)[ \t\n]+%?[ \t\n]*\\("
591 sgml-name-re "\\)")
593 ("Id"
594 ,(concat "<[^>]+[ \t\n]+[Ii][Dd]=\\(['\"]"
595 (if sgml-xml-mode "" "?")
596 "\\)\\(" sgml-name-re "\\)\\1")
598 ("Name"
599 ,(concat "<[^>]+[ \t\n]+[Nn][Aa][Mm][Ee]=\\(['\"]"
600 (if sgml-xml-mode "" "?")
601 "\\)\\(" sgml-name-re "\\)\\1")
602 2))))
604 (defun sgml-comment-indent ()
605 (if (looking-at "--") comment-column 0))
607 (defun sgml-slash (arg)
608 "Insert ARG slash characters.
609 Behaves electrically if `sgml-quick-keys' is non-nil."
610 (interactive "p")
611 (cond
612 ((not (and (eq (char-before) ?<) (= arg 1)))
613 (sgml-slash-matching arg))
614 ((eq sgml-quick-keys 'indent)
615 (insert-char ?/ 1)
616 (indent-according-to-mode))
617 ((eq sgml-quick-keys 'close)
618 (delete-char -1)
619 (sgml-close-tag))
621 (sgml-slash-matching arg))))
623 (defun sgml-slash-matching (arg)
624 "Insert `/' and display any previous matching `/'.
625 Two `/'s are treated as matching if the first `/' ends a net-enabling
626 start tag, and the second `/' is the corresponding null end tag."
627 (interactive "p")
628 (insert-char ?/ arg)
629 (if (> arg 0)
630 (let ((oldpos (point))
631 (blinkpos)
632 (level 0))
633 (save-excursion
634 (save-restriction
635 (if sgml-slash-distance
636 (narrow-to-region (max (point-min)
637 (- (point) sgml-slash-distance))
638 oldpos))
639 (if (and (re-search-backward sgml-start-tag-regex (point-min) t)
640 (eq (match-end 0) (1- oldpos)))
642 (goto-char (1- oldpos))
643 (while (and (not blinkpos)
644 (search-backward "/" (point-min) t))
645 (let ((tagend (save-excursion
646 (if (re-search-backward sgml-start-tag-regex
647 (point-min) t)
648 (match-end 0)
649 nil))))
650 (if (eq tagend (point))
651 (if (eq level 0)
652 (setq blinkpos (point))
653 (setq level (1- level)))
654 (setq level (1+ level)))))))
655 (when blinkpos
656 (goto-char blinkpos)
657 (if (pos-visible-in-window-p)
658 (sit-for 1)
659 (message "Matches %s"
660 (buffer-substring (line-beginning-position)
661 (1+ blinkpos)))))))))
663 ;; Why doesn't this use the iso-cvt table or, preferably, generate the
664 ;; inverse of the extensive table in the SGML Quail input method? -- fx
665 ;; I guess that's moot since it only works with Latin-1 anyhow.
666 (defun sgml-name-char (&optional char)
667 "Insert a symbolic character name according to `sgml-char-names'.
668 Non-ASCII chars may be inserted either with the meta key, as in M-SPC for
669 no-break space or M-- for a soft hyphen; or via an input method or
670 encoded keyboard operation."
671 (interactive "*")
672 (insert ?&)
673 (or char
674 (setq char (read-quoted-char "Enter char or octal number")))
675 (delete-char -1)
676 (insert char)
677 (undo-boundary)
678 (sgml-namify-char))
680 (defun sgml-namify-char ()
681 "Change the char before point into its `&name;' equivalent.
682 Uses `sgml-char-names'."
683 (interactive)
684 (let* ((char (char-before))
685 (name
686 (cond
687 ((null char) (error "No char before point"))
688 ((< char 256) (or (aref sgml-char-names char) char))
689 ((aref sgml-char-names-table char))
690 ((encode-char char 'ucs)))))
691 (if (not name)
692 (error "Don't know the name of `%c'" char)
693 (delete-char -1)
694 (insert (format (if (numberp name) "&#%d;" "&%s;") name)))))
696 (defun sgml-name-self ()
697 "Insert a symbolic character name according to `sgml-char-names'."
698 (interactive "*")
699 (sgml-name-char last-command-event))
701 (defun sgml-maybe-name-self ()
702 "Insert a symbolic character name according to `sgml-char-names'."
703 (interactive "*")
704 (if sgml-name-8bit-mode
705 (sgml-name-char last-command-event)
706 (self-insert-command 1)))
708 (defun sgml-name-8bit-mode ()
709 "Toggle whether to insert named entities instead of non-ASCII characters.
710 This only works for Latin-1 input."
711 (interactive)
712 (setq sgml-name-8bit-mode (not sgml-name-8bit-mode))
713 (message "sgml name entity mode is now %s"
714 (if sgml-name-8bit-mode "ON" "OFF")))
716 ;; When an element of a skeleton is a string "str", it is passed
717 ;; through `skeleton-transformation-function' and inserted.
718 ;; If "str" is to be inserted literally, one should obtain it as
719 ;; the return value of a function, e.g. (identity "str").
721 (defvar sgml-tag-last nil)
722 (defvar sgml-tag-history nil)
723 (define-skeleton sgml-tag
724 "Prompt for a tag and insert it, optionally with attributes.
725 Completion and configuration are done according to `sgml-tag-alist'.
726 If you like tags and attributes in uppercase, customize
727 `sgml-transformation-function' to `upcase'."
728 (funcall (or skeleton-transformation-function 'identity)
729 (setq sgml-tag-last
730 (completing-read
731 (if (> (length sgml-tag-last) 0)
732 (format "Tag (default %s): " sgml-tag-last)
733 "Tag: ")
734 sgml-tag-alist nil nil nil 'sgml-tag-history sgml-tag-last)))
735 ?< str |
736 (("") -1 '(undo-boundary) (identity "&lt;")) | ; see comment above
737 `(("") '(setq v2 (sgml-attributes ,str t)) ?>
738 (cond
739 ((string= "![" ,str)
740 (backward-char)
741 '(("") " [ " _ " ]]"))
742 ((and (eq v2 t) sgml-xml-mode (member ,str sgml-empty-tags))
743 '(("") -1 " />"))
744 ((or (and (eq v2 t) (not sgml-xml-mode)) (string-match "^[/!?]" ,str))
745 nil)
746 ((symbolp v2)
747 ;; Make sure we don't fall into an infinite loop.
748 ;; For xhtml's `tr' tag, we should maybe use \n instead.
749 (if (eq v2 t) (setq v2 nil))
750 ;; We use `identity' to prevent skeleton from passing
751 ;; `str' through `skeleton-transformation-function' a second time.
752 '(("") v2 _ v2 "</" (identity ',str) ?> >))
753 ((eq (car v2) t)
754 (cons '("") (cdr v2)))
756 (append '(("") (car v2))
757 (cdr v2)
758 '(resume: (car v2) _ "</" (identity ',str) ?> >))))))
760 (autoload 'skeleton-read "skeleton")
762 (defun sgml-attributes (tag &optional quiet)
763 "When at top level of a tag, interactively insert attributes.
765 Completion and configuration of TAG are done according to `sgml-tag-alist'.
766 If QUIET, do not print a message when there are no attributes for TAG."
767 (interactive (list (save-excursion (sgml-beginning-of-tag t))))
768 (or (stringp tag) (error "Wrong context for adding attribute"))
769 (if tag
770 (let ((completion-ignore-case t)
771 (alist (cdr (assoc (downcase tag) sgml-tag-alist)))
772 car attribute i)
773 (if (or (symbolp (car alist))
774 (symbolp (car (car alist))))
775 (setq car (car alist)
776 alist (cdr alist)))
777 (or quiet
778 (message "No attributes configured."))
779 (if (stringp (car alist))
780 (progn
781 (insert (if (eq (preceding-char) ?\s) "" ?\s)
782 (funcall skeleton-transformation-function (car alist)))
783 (sgml-value alist))
784 (setq i (length alist))
785 (while (> i 0)
786 (insert ?\s)
787 (insert (funcall skeleton-transformation-function
788 (setq attribute
789 (skeleton-read (lambda ()
790 (completing-read
791 "Attribute: "
792 alist))))))
793 (if (string= "" attribute)
794 (setq i 0)
795 (sgml-value (assoc (downcase attribute) alist))
796 (setq i (1- i))))
797 (if (eq (preceding-char) ?\s)
798 (delete-char -1)))
799 car)))
801 (defun sgml-auto-attributes (arg)
802 "Self insert the character typed; at top level of tag, prompt for attributes.
803 With prefix argument, only self insert."
804 (interactive "*P")
805 (let ((point (point))
806 tag)
807 (if (or arg
808 (not sgml-tag-alist) ; no message when nothing configured
809 (symbolp (setq tag (save-excursion (sgml-beginning-of-tag t))))
810 (eq (aref tag 0) ?/))
811 (self-insert-command (prefix-numeric-value arg))
812 (sgml-attributes tag)
813 (setq last-command-event ?\s)
814 (or (> (point) point)
815 (self-insert-command 1)))))
817 (defun sgml-tag-help (&optional tag)
818 "Display description of tag TAG. If TAG is omitted, use the tag at point."
819 (interactive
820 (list (let ((def (save-excursion
821 (if (eq (following-char) ?<) (forward-char))
822 (sgml-beginning-of-tag))))
823 (completing-read (if def
824 (format "Tag (default %s): " def)
825 "Tag: ")
826 sgml-tag-alist nil nil nil
827 'sgml-tag-history def))))
828 (or (and tag (> (length tag) 0))
829 (save-excursion
830 (if (eq (following-char) ?<)
831 (forward-char))
832 (setq tag (sgml-beginning-of-tag))))
833 (or (stringp tag)
834 (error "No tag selected"))
835 (setq tag (downcase tag))
836 (message "%s"
837 (or (cdr (assoc (downcase tag) sgml-tag-help))
838 (and (eq (aref tag 0) ?/)
839 (cdr (assoc (downcase (substring tag 1)) sgml-tag-help)))
840 "No description available")))
842 (defun sgml-maybe-end-tag (&optional arg)
843 "Name self unless in position to end a tag or a prefix ARG is given."
844 (interactive "P")
845 (if (or arg (eq (car (sgml-lexical-context)) 'tag))
846 (self-insert-command (prefix-numeric-value arg))
847 (sgml-name-self)))
849 (defun sgml-skip-tag-backward (arg)
850 "Skip to beginning of tag or matching opening tag if present.
851 With prefix argument ARG, repeat this ARG times.
852 Return non-nil if we skipped over matched tags."
853 (interactive "p")
854 ;; FIXME: use sgml-get-context or something similar.
855 (let ((return t))
856 (while (>= arg 1)
857 (search-backward "<" nil t)
858 (if (looking-at "</\\([^ \n\t>]+\\)")
859 ;; end tag, skip any nested pairs
860 (let ((case-fold-search t)
861 (re (concat "</?" (regexp-quote (match-string 1))
862 ;; Ignore empty tags like <foo/>.
863 "\\([^>]*[^/>]\\)?>")))
864 (while (and (re-search-backward re nil t)
865 (eq (char-after (1+ (point))) ?/))
866 (forward-char 1)
867 (sgml-skip-tag-backward 1)))
868 (setq return nil))
869 (setq arg (1- arg)))
870 return))
872 (defun sgml-forward-sexp (n)
873 ;; This function is needed in major-modes such as nxml-mode where
874 ;; forward-sexp-function is used to give a more dwimish behavior to
875 ;; the `forward-sexp' command.
876 ;; Without it, we can end up with backtraces like:
877 ;; "get-text-property" (0xffffc0f0)
878 ;; "nxml-token-after" (0xffffc2ac)
879 ;; "nxml-forward-single-balanced-item" (0xffffc46c)
880 ;; "nxml-forward-balanced-item" (0xffffc61c)
881 ;; "forward-sexp" (0xffffc7f8)
882 ;; "sgml-parse-tag-backward" (0xffffc9c8)
883 ;; "sgml-lexical-context" (0xffffcba8)
884 ;; "sgml-mode-flyspell-verify" (0xffffcd74)
885 ;; "flyspell-word" (0xffffcf3c)
886 ;; "flyspell-post-command-hook" (0xffffd108)
887 ;; FIXME: should we also set the sgml-tag-syntax-table?
888 (let ((forward-sexp-function nil))
889 (forward-sexp n)))
891 (defvar sgml-electric-tag-pair-overlays nil)
892 (defvar sgml-electric-tag-pair-timer nil)
894 (defun sgml-electric-tag-pair-before-change-function (_beg end)
895 (condition-case err
896 (save-excursion
897 (goto-char end)
898 (skip-chars-backward "[:alnum:]-_.:")
899 (if (and ;; (<= (point) beg) ; This poses problems for downcase-word.
900 (or (eq (char-before) ?<)
901 (and (eq (char-before) ?/)
902 (eq (char-before (1- (point))) ?<)))
903 (null (get-char-property (point) 'text-clones)))
904 (let* ((endp (eq (char-before) ?/))
905 (cl-start (point))
906 (cl-end (progn (skip-chars-forward "[:alnum:]-_.:") (point)))
907 (match
908 (if endp
909 (when (sgml-skip-tag-backward 1) (forward-char 1) t)
910 (with-syntax-table sgml-tag-syntax-table
911 (let ((forward-sexp-function nil))
912 (up-list -1)
913 (when (sgml-skip-tag-forward 1)
914 (backward-sexp 1)
915 (forward-char 2)
916 t)))))
917 (clones (get-char-property (point) 'text-clones)))
918 (when (and match
919 (/= cl-end cl-start)
920 (equal (buffer-substring cl-start cl-end)
921 (buffer-substring (point)
922 (save-excursion
923 (skip-chars-forward "[:alnum:]-_.:")
924 (point))))
925 (or (not endp) (eq (char-after cl-end) ?>)))
926 (when clones
927 (message "sgml-electric-tag-pair-before-change-function: deleting old OLs")
928 (mapc 'delete-overlay clones))
929 (message "sgml-electric-tag-pair-before-change-function: new clone")
930 (text-clone-create cl-start cl-end 'spread "[[:alnum:]-_.:]+")
931 (setq sgml-electric-tag-pair-overlays
932 (append (get-char-property (point) 'text-clones)
933 sgml-electric-tag-pair-overlays))))))
934 (scan-error nil)
935 (error (message "Error in sgml-electric-pair-mode: %s" err))))
937 (defun sgml-electric-tag-pair-flush-overlays ()
938 (while sgml-electric-tag-pair-overlays
939 (delete-overlay (pop sgml-electric-tag-pair-overlays))))
941 (define-minor-mode sgml-electric-tag-pair-mode
942 "Toggle SGML Electric Tag Pair mode.
943 With a prefix argument ARG, enable the mode if ARG is positive,
944 and disable it otherwise. If called from Lisp, enable the mode
945 if ARG is omitted or nil.
947 SGML Electric Tag Pair mode is a buffer-local minor mode for use
948 with `sgml-mode' and related major modes. When enabled, editing
949 an opening markup tag automatically updates the closing tag."
950 :lighter "/e"
951 (if sgml-electric-tag-pair-mode
952 (progn
953 (add-hook 'before-change-functions
954 'sgml-electric-tag-pair-before-change-function
955 nil t)
956 (unless sgml-electric-tag-pair-timer
957 (setq sgml-electric-tag-pair-timer
958 (run-with-idle-timer 5 'repeat 'sgml-electric-tag-pair-flush-overlays))))
959 (remove-hook 'before-change-functions
960 'sgml-electric-tag-pair-before-change-function
962 ;; We leave the timer running for other buffers.
966 (defun sgml-skip-tag-forward (arg)
967 "Skip to end of tag or matching closing tag if present.
968 With prefix argument ARG, repeat this ARG times.
969 Return t if after a closing tag."
970 (interactive "p")
971 ;; FIXME: Use sgml-get-context or something similar.
972 ;; It currently might jump to an unrelated </P> if the <P>
973 ;; we're skipping has no matching </P>.
974 (let ((return t))
975 (with-syntax-table sgml-tag-syntax-table
976 (while (>= arg 1)
977 (skip-chars-forward "^<>")
978 (if (eq (following-char) ?>)
979 (up-list -1))
980 (if (looking-at "<\\([^/ \n\t>]+\\)\\([^>]*[^/>]\\)?>")
981 ;; start tag, skip any nested same pairs _and_ closing tag
982 (let ((case-fold-search t)
983 (re (concat "</?" (regexp-quote (match-string 1))
984 ;; Ignore empty tags like <foo/>.
985 "\\([^>]*[^/>]\\)?>"))
986 point close)
987 (forward-list 1)
988 (setq point (point))
989 ;; FIXME: This re-search-forward will mistakenly match
990 ;; tag-like text inside attributes.
991 (while (and (re-search-forward re nil t)
992 (not (setq close
993 (eq (char-after (1+ (match-beginning 0))) ?/)))
994 (goto-char (match-beginning 0))
995 (sgml-skip-tag-forward 1))
996 (setq close nil))
997 (unless close
998 (goto-char point)
999 (setq return nil)))
1000 (forward-list 1))
1001 (setq arg (1- arg)))
1002 return)))
1004 (defsubst sgml-looking-back-at (str)
1005 "Return t if the test before point matches STR."
1006 (let ((start (- (point) (length str))))
1007 (and (>= start (point-min))
1008 (equal str (buffer-substring-no-properties start (point))))))
1010 (defun sgml-delete-tag (arg)
1011 ;; FIXME: Should be called sgml-kill-tag or should not touch the kill-ring.
1012 "Delete tag on or after cursor, and matching closing or opening tag.
1013 With prefix argument ARG, repeat this ARG times."
1014 (interactive "p")
1015 (while (>= arg 1)
1016 (save-excursion
1017 (let* (close open)
1018 (if (looking-at "[ \t\n]*<")
1019 ;; just before tag
1020 (if (eq (char-after (match-end 0)) ?/)
1021 ;; closing tag
1022 (progn
1023 (setq close (point))
1024 (goto-char (match-end 0))))
1025 ;; on tag?
1026 (or (save-excursion (setq close (sgml-beginning-of-tag)
1027 close (and (stringp close)
1028 (eq (aref close 0) ?/)
1029 (point))))
1030 ;; not on closing tag
1031 (let ((point (point)))
1032 (sgml-skip-tag-backward 1)
1033 (if (or (not (eq (following-char) ?<))
1034 (save-excursion
1035 (forward-list 1)
1036 (<= (point) point)))
1037 (error "Not on or before tag")))))
1038 (if close
1039 (progn
1040 (sgml-skip-tag-backward 1)
1041 (setq open (point))
1042 (goto-char close)
1043 (kill-sexp 1))
1044 (setq open (point))
1045 (when (and (sgml-skip-tag-forward 1)
1046 (not (sgml-looking-back-at "/>")))
1047 (kill-sexp -1)))
1048 ;; Delete any resulting empty line. If we didn't kill-sexp,
1049 ;; this *should* do nothing, because we're right after the tag.
1050 (if (progn (forward-line 0) (looking-at "\\(?:[ \t]*$\\)\n?"))
1051 (delete-region (match-beginning 0) (match-end 0)))
1052 (goto-char open)
1053 (kill-sexp 1)
1054 (if (progn (forward-line 0) (looking-at "\\(?:[ \t]*$\\)\n?"))
1055 (delete-region (match-beginning 0) (match-end 0)))))
1056 (setq arg (1- arg))))
1059 ;; Put read-only last to enable setting this even when read-only enabled.
1060 (or (get 'sgml-tag 'invisible)
1061 (setplist 'sgml-tag
1062 (append '(invisible t
1063 cursor-sensor-functions (sgml-cursor-sensor)
1064 rear-nonsticky t
1065 read-only t)
1066 (symbol-plist 'sgml-tag))))
1068 (defun sgml-tags-invisible (arg)
1069 "Toggle visibility of existing tags."
1070 (interactive "P")
1071 (let ((inhibit-read-only t)
1072 string)
1073 (with-silent-modifications
1074 (save-excursion
1075 (goto-char (point-min))
1076 (if (setq-local sgml-tags-invisible
1077 (if arg
1078 (>= (prefix-numeric-value arg) 0)
1079 (not sgml-tags-invisible)))
1080 (while (re-search-forward sgml-tag-name-re nil t)
1081 (setq string
1082 (cdr (assq (intern-soft (downcase (match-string 1)))
1083 sgml-display-text)))
1084 (goto-char (match-beginning 0))
1085 (and (stringp string)
1086 (not (overlays-at (point)))
1087 (let ((ol (make-overlay (point) (match-beginning 1))))
1088 (overlay-put ol 'before-string string)
1089 (overlay-put ol 'sgml-tag t)))
1090 (put-text-property (point)
1091 (progn (forward-list) (point))
1092 'category 'sgml-tag))
1093 (let ((pos (point-min)))
1094 (while (< (setq pos (next-overlay-change pos)) (point-max))
1095 (dolist (ol (overlays-at pos))
1096 (if (overlay-get ol 'sgml-tag)
1097 (delete-overlay ol)))))
1098 (remove-text-properties (point-min) (point-max) '(category nil)))))
1099 (cursor-sensor-mode (if sgml-tags-invisible 1 -1))
1100 (run-hooks 'sgml-tags-invisible-hook)
1101 (message "")))
1103 (defun sgml-cursor-sensor (window x dir)
1104 ;; Show preceding or following hidden tag, depending of cursor direction (and
1105 ;; `dir' is not the direction in this sense).
1106 (when (eq dir 'entered)
1107 (ignore-errors
1108 (let* ((y (window-point window))
1109 (otherend
1110 (save-excursion
1111 (goto-char y)
1112 (cond
1113 ((and (eq (char-before) ?>)
1114 (or (not (eq (char-after) ?<))
1115 (> x y)))
1116 (sgml-forward-sexp -1))
1117 ((eq (char-after y) ?<)
1118 (sgml-forward-sexp 1)))
1119 (point))))
1120 (message "Invisible tag: %s"
1121 ;; Strip properties, otherwise, the text is invisible.
1122 (buffer-substring-no-properties
1123 y otherend))))))
1126 (defun sgml-validate (command)
1127 "Validate an SGML document.
1128 Runs COMMAND, a shell command, in a separate process asynchronously
1129 with output going to the buffer `*compilation*'.
1130 You can then use the command \\[next-error] to find the next error message
1131 and move to the line in the SGML document that caused it."
1132 (interactive
1133 (list (read-string "Validate command: "
1134 (or sgml-saved-validate-command
1135 (concat sgml-validate-command
1137 (shell-quote-argument
1138 (let ((name (buffer-file-name)))
1139 (and name
1140 (file-name-nondirectory name)))))))))
1141 (setq sgml-saved-validate-command command)
1142 (save-some-buffers (not compilation-ask-about-save) nil)
1143 (compilation-start command))
1145 (defsubst sgml-at-indentation-p ()
1146 "Return true if point is at the first non-whitespace character on the line."
1147 (save-excursion
1148 (skip-chars-backward " \t")
1149 (bolp)))
1151 (defun sgml-lexical-context (&optional limit)
1152 "Return the lexical context at point as (TYPE . START).
1153 START is the location of the start of the lexical element.
1154 TYPE is one of `string', `comment', `tag', `cdata', `pi', or `text'.
1156 Optional argument LIMIT is the position to start parsing from.
1157 If nil, start from a preceding tag at indentation."
1158 (save-excursion
1159 (let ((pos (point))
1160 text-start state)
1161 (if limit
1162 (goto-char limit)
1163 ;; Skip tags backwards until we find one at indentation
1164 (while (and (ignore-errors (sgml-parse-tag-backward))
1165 (not (sgml-at-indentation-p)))))
1166 (with-syntax-table sgml-tag-syntax-table
1167 (while (< (point) pos)
1168 ;; When entering this loop we're inside text.
1169 (setq text-start (point))
1170 (skip-chars-forward "^<" pos)
1171 (setq state
1172 (cond
1173 ((= (point) pos)
1174 ;; We got to the end without seeing a tag.
1175 nil)
1176 ((looking-at "<!\\[[A-Z]+\\[")
1177 ;; We've found a CDATA section or similar.
1178 (let ((cdata-start (point)))
1179 (unless (search-forward "]]>" pos 'move)
1180 (list 0 nil nil 'cdata nil nil nil nil cdata-start))))
1181 ((looking-at comment-start-skip)
1182 ;; parse-partial-sexp doesn't handle <!-- comments -->,
1183 ;; or only if ?- is in sgml-specials, so match explicitly
1184 (let ((start (point)))
1185 (unless (re-search-forward comment-end-skip pos 'move)
1186 (list 0 nil nil nil t nil nil nil start))))
1187 ((and sgml-xml-mode (looking-at "<\\?"))
1188 ;; Processing Instructions.
1189 ;; In SGML, it's basically a normal tag of the form
1190 ;; <?NAME ...> but in XML, it takes the form <? ... ?>.
1191 (let ((pi-start (point)))
1192 (unless (search-forward "?>" pos 'move)
1193 (list 0 nil nil 'pi nil nil nil nil pi-start))))
1195 ;; We've reached a tag. Parse it.
1196 ;; FIXME: Handle net-enabling start-tags
1197 (parse-partial-sexp (point) pos 0))))))
1198 (cond
1199 ((memq (nth 3 state) '(cdata pi)) (cons (nth 3 state) (nth 8 state)))
1200 ((nth 3 state) (cons 'string (nth 8 state)))
1201 ((nth 4 state) (cons 'comment (nth 8 state)))
1202 ((and state (> (nth 0 state) 0)) (cons 'tag (nth 1 state)))
1203 (t (cons 'text text-start))))))
1205 (defun sgml-beginning-of-tag (&optional only-immediate)
1206 "Skip to beginning of tag and return its name.
1207 If this can't be done, return nil."
1208 (let ((context (sgml-lexical-context)))
1209 (if (eq (car context) 'tag)
1210 (progn
1211 (goto-char (cdr context))
1212 (when (looking-at sgml-tag-name-re)
1213 (match-string-no-properties 1)))
1214 (if only-immediate nil
1215 (when (not (eq (car context) 'text))
1216 (goto-char (cdr context))
1217 (sgml-beginning-of-tag t))))))
1219 (defun sgml-value (alist)
1220 "Interactively insert value taken from attribute-rule ALIST.
1221 See `sgml-tag-alist' for info about attribute rules."
1222 (setq alist (cdr alist))
1223 (if (stringp (car alist))
1224 (insert "=\"" (car alist) ?\")
1225 (if (and (eq (car alist) t) (not sgml-xml-mode))
1226 (when (cdr alist)
1227 (insert "=\"")
1228 (setq alist (skeleton-read (lambda ()
1229 (completing-read
1230 "Value: " (cdr alist)))))
1231 (if (string< "" alist)
1232 (insert alist ?\")
1233 (delete-char -2)))
1234 (insert "=\"")
1235 (if (cdr alist)
1236 (insert (skeleton-read (lambda ()
1237 (completing-read "Value: " alist))))
1238 (when (null alist)
1239 (insert (skeleton-read '(read-string "Value: ")))))
1240 (insert ?\"))))
1242 (defun sgml-quote (start end &optional unquotep)
1243 "Quote SGML text in region START ... END.
1244 Only &, < and > are quoted, the rest is left untouched.
1245 With prefix argument UNQUOTEP, unquote the region."
1246 (interactive "r\nP")
1247 (save-restriction
1248 (narrow-to-region start end)
1249 (goto-char (point-min))
1250 (if unquotep
1251 ;; FIXME: We should unquote other named character references as well.
1252 (while (re-search-forward
1253 "\\(&\\(amp\\|\\(l\\|\\(g\\)\\)t\\)\\)[][<>&;\n\t \"%!'(),/=?]"
1254 nil t)
1255 (replace-match (if (match-end 4) ">" (if (match-end 3) "<" "&")) t t
1256 nil (if (eq (char-before (match-end 0)) ?\;) 0 1)))
1257 (while (re-search-forward "[&<>]" nil t)
1258 (replace-match (cdr (assq (char-before) '((?& . "&amp;")
1259 (?< . "&lt;")
1260 (?> . "&gt;"))))
1261 t t)))))
1263 (defun sgml-pretty-print (beg end)
1264 "Simple-minded pretty printer for SGML.
1265 Re-indents the code and inserts newlines between BEG and END.
1266 You might want to turn on `auto-fill-mode' to get better results."
1267 ;; TODO:
1268 ;; - insert newline between some start-tag and text.
1269 ;; - don't insert newline in front of some end-tags.
1270 (interactive "r")
1271 (save-excursion
1272 (if (< beg end)
1273 (goto-char beg)
1274 (goto-char end)
1275 (setq end beg)
1276 (setq beg (point)))
1277 ;; Don't use narrowing because it screws up auto-indent.
1278 (setq end (copy-marker end t))
1279 (with-syntax-table sgml-tag-syntax-table
1280 (while (re-search-forward "<" end t)
1281 (goto-char (match-beginning 0))
1282 (unless (or ;;(looking-at "</")
1283 (progn (skip-chars-backward " \t") (bolp)))
1284 (reindent-then-newline-and-indent))
1285 (sgml-forward-sexp 1)))
1286 ;; (indent-region beg end)
1290 ;; Parsing
1292 (cl-defstruct (sgml-tag
1293 (:constructor sgml-make-tag (type start end name)))
1294 type start end name)
1296 (defsubst sgml-parse-tag-name ()
1297 "Skip past a tag-name, and return the name."
1298 (buffer-substring-no-properties
1299 (point) (progn (skip-syntax-forward "w_") (point))))
1301 (defun sgml-tag-text-p (start end)
1302 "Return non-nil if text between START and END is a tag.
1303 Checks among other things that the tag does not contain spurious
1304 unquoted < or > chars inside, which would indicate that it
1305 really isn't a tag after all."
1306 (save-excursion
1307 (with-syntax-table sgml-tag-syntax-table
1308 (let ((pps (parse-partial-sexp start end 2)))
1309 (and (= (nth 0 pps) 0))))))
1311 (defun sgml--find-<>-backward (limit)
1312 "Search backward for a '<' or '>' character.
1313 The character must have open or close syntax.
1314 Returns t if found, nil otherwise."
1315 (catch 'found
1316 (while (re-search-backward "[<>]" limit 'move)
1317 ;; If this character has "open" or "close" syntax, then we've
1318 ;; found the one we want.
1319 (when (memq (syntax-class (syntax-after (point))) '(4 5))
1320 (throw 'found t)))))
1322 (defun sgml-parse-tag-backward (&optional limit)
1323 "Parse an SGML tag backward, and return information about the tag.
1324 Assume that parsing starts from within a textual context.
1325 Leave point at the beginning of the tag."
1326 (catch 'found
1327 (let (tag-type tag-start tag-end name)
1328 (or (sgml--find-<>-backward limit)
1329 (error "No tag found"))
1330 (when (eq (char-after) ?<)
1331 ;; Oops!! Looks like we were not in a textual context after all!.
1332 ;; Let's try to recover.
1333 ;; Remember the tag-start so we don't need to look for it later.
1334 ;; This is not just an optimization but also makes sure we don't get
1335 ;; stuck in infloops in cases where "looking back for <" would not go
1336 ;; back far enough.
1337 (setq tag-start (point))
1338 (with-syntax-table sgml-tag-syntax-table
1339 (let ((pos (point)))
1340 (condition-case nil
1341 ;; FIXME: This does not correctly skip over PI an CDATA tags.
1342 (sgml-forward-sexp 1)
1343 (scan-error
1344 ;; This < seems to be just a spurious one, let's ignore it.
1345 (goto-char pos)
1346 (throw 'found (sgml-parse-tag-backward limit))))
1347 ;; Check it is really a tag, without any extra < or > inside.
1348 (unless (sgml-tag-text-p pos (point))
1349 (goto-char pos)
1350 (throw 'found (sgml-parse-tag-backward limit)))
1351 (forward-char -1))))
1352 (setq tag-end (1+ (point)))
1353 (cond
1354 ((sgml-looking-back-at "--") ; comment
1355 (setq tag-type 'comment
1356 tag-start (or tag-start (search-backward "<!--" nil t))))
1357 ((sgml-looking-back-at "]]") ; cdata
1358 (setq tag-type 'cdata
1359 tag-start (or tag-start
1360 (re-search-backward "<!\\[[A-Z]+\\[" nil t))))
1361 ((sgml-looking-back-at "?") ; XML processing-instruction
1362 (setq tag-type 'pi
1363 ;; IIUC: SGML processing instructions take the form <?foo ...>
1364 ;; i.e. a "normal" tag, handled below. In XML this is changed
1365 ;; to <?foo ... ?> where "..." can contain < and > and even <?
1366 ;; but not ?>. This means that when parsing backward, there's
1367 ;; no easy way to make sure that we find the real beginning of
1368 ;; the PI.
1369 tag-start (or tag-start (search-backward "<?" nil t))))
1371 (unless tag-start
1372 (setq tag-start
1373 (with-syntax-table sgml-tag-syntax-table
1374 (goto-char tag-end)
1375 (condition-case nil
1376 (sgml-forward-sexp -1)
1377 (scan-error
1378 ;; This > isn't really the end of a tag. Skip it.
1379 (goto-char (1- tag-end))
1380 (throw 'found (sgml-parse-tag-backward limit))))
1381 (point))))
1382 (goto-char (1+ tag-start))
1383 (pcase (char-after)
1384 (?! (setq tag-type 'decl)) ; declaration
1385 (?? (setq tag-type 'pi)) ; processing-instruction
1386 (?% (setq tag-type 'jsp)) ; JSP tags
1387 (?/ ; close-tag
1388 (forward-char 1)
1389 (setq tag-type 'close
1390 name (sgml-parse-tag-name)))
1391 (_ ; open or empty tag
1392 (setq tag-type 'open
1393 name (sgml-parse-tag-name))
1394 (if (or (eq ?/ (char-before (- tag-end 1)))
1395 (sgml-empty-tag-p name))
1396 (setq tag-type 'empty))))))
1397 (goto-char tag-start)
1398 (sgml-make-tag tag-type tag-start tag-end name))))
1400 (defun sgml-get-context (&optional until)
1401 "Determine the context of the current position.
1402 By default, parse until we find a start-tag as the first thing on a line.
1403 If UNTIL is `empty', return even if the context is empty (i.e.
1404 we just skipped over some element and got to a beginning of line).
1406 The context is a list of tag-info structures. The last one is the tag
1407 immediately enclosing the current position.
1409 Point is assumed to be outside of any tag. If we discover that it's
1410 not the case, the first tag returned is the one inside which we are."
1411 (let ((here (point))
1412 (stack nil)
1413 (ignore nil)
1414 (context nil)
1415 tag-info)
1416 ;; CONTEXT keeps track of the tag-stack
1417 ;; STACK keeps track of the end tags we've seen (and thus the start-tags
1418 ;; we'll have to ignore) when skipping over matching open..close pairs.
1419 ;; IGNORE is a list of tags that can be ignored because they have been
1420 ;; closed implicitly.
1421 (skip-chars-backward " \t\n") ; Make sure we're not at indentation.
1422 (while
1423 (and (not (eq until 'now))
1424 (or stack
1425 (not (if until (eq until 'empty) context))
1426 (not (sgml-at-indentation-p))
1427 (and context
1428 (/= (point) (sgml-tag-start (car context)))
1429 (sgml-unclosed-tag-p (sgml-tag-name (car context)))))
1430 (setq tag-info (ignore-errors (sgml-parse-tag-backward))))
1432 ;; This tag may enclose things we thought were tags. If so,
1433 ;; discard them.
1434 (while (and context
1435 (> (sgml-tag-end tag-info)
1436 (sgml-tag-end (car context))))
1437 (setq context (cdr context)))
1439 (cond
1440 ((> (sgml-tag-end tag-info) here)
1441 ;; Oops!! Looks like we were not outside of any tag, after all.
1442 (push tag-info context)
1443 (setq until 'now))
1445 ;; start-tag
1446 ((eq (sgml-tag-type tag-info) 'open)
1447 (cond
1448 ((null stack)
1449 (if (assoc-string (sgml-tag-name tag-info) ignore t)
1450 ;; There was an implicit end-tag.
1452 (push tag-info context)
1453 ;; We're changing context so the tags implicitly closed inside
1454 ;; the previous context aren't implicitly closed here any more.
1455 ;; [ Well, actually it depends, but we don't have the info about
1456 ;; when it doesn't and when it does. --Stef ]
1457 (setq ignore nil)))
1458 ((eq t (compare-strings (sgml-tag-name tag-info) nil nil
1459 (car stack) nil nil t))
1460 (setq stack (cdr stack)))
1462 ;; The open and close tags don't match.
1463 (if (not sgml-xml-mode)
1464 (unless (sgml-unclosed-tag-p (sgml-tag-name tag-info))
1465 (message "Unclosed tag <%s>" (sgml-tag-name tag-info))
1466 (let ((tmp stack))
1467 ;; We could just assume that the tag is simply not closed
1468 ;; but it's a bad assumption when tags *are* closed but
1469 ;; not properly nested.
1470 (while (and (cdr tmp)
1471 (not (eq t (compare-strings
1472 (sgml-tag-name tag-info) nil nil
1473 (cadr tmp) nil nil t))))
1474 (setq tmp (cdr tmp)))
1475 (if (cdr tmp) (setcdr tmp (cddr tmp)))))
1476 (message "Unmatched tags <%s> and </%s>"
1477 (sgml-tag-name tag-info) (pop stack)))))
1479 (if (and (null stack) (sgml-unclosed-tag-p (sgml-tag-name tag-info)))
1480 ;; This is a top-level open of an implicitly closed tag, so any
1481 ;; occurrence of such an open tag at the same level can be ignored
1482 ;; because it's been implicitly closed.
1483 (push (sgml-tag-name tag-info) ignore)))
1485 ;; end-tag
1486 ((eq (sgml-tag-type tag-info) 'close)
1487 (if (sgml-empty-tag-p (sgml-tag-name tag-info))
1488 (message "Spurious </%s>: empty tag" (sgml-tag-name tag-info))
1489 (push (sgml-tag-name tag-info) stack)))
1492 ;; return context
1493 context))
1495 (defun sgml-show-context (&optional full)
1496 "Display the current context.
1497 If FULL is non-nil, parse back to the beginning of the buffer."
1498 (interactive "P")
1499 (with-output-to-temp-buffer "*XML Context*"
1500 (save-excursion
1501 (let ((context (sgml-get-context)))
1502 (when full
1503 (let ((more nil))
1504 (while (setq more (sgml-get-context))
1505 (setq context (nconc more context)))))
1506 (pp context)))))
1509 ;; Editing shortcuts
1511 (defun sgml-close-tag ()
1512 "Close current element.
1513 Depending on context, inserts a matching close-tag, or closes
1514 the current start-tag or the current comment or the current cdata, ..."
1515 (interactive)
1516 (pcase (car (sgml-lexical-context))
1517 (`comment (insert " -->"))
1518 (`cdata (insert "]]>"))
1519 (`pi (insert " ?>"))
1520 (`jsp (insert " %>"))
1521 (`tag (insert " />"))
1522 (`text
1523 (let ((context (save-excursion (sgml-get-context))))
1524 (if context
1525 (progn
1526 (insert "</" (sgml-tag-name (car (last context))) ">")
1527 (indent-according-to-mode)))))
1529 (error "Nothing to close"))))
1531 (defun sgml-empty-tag-p (tag-name)
1532 "Return non-nil if TAG-NAME is an implicitly empty tag."
1533 (and (not sgml-xml-mode)
1534 (assoc-string tag-name sgml-empty-tags 'ignore-case)))
1536 (defun sgml-unclosed-tag-p (tag-name)
1537 "Return non-nil if TAG-NAME is a tag for which an end-tag is optional."
1538 (and (not sgml-xml-mode)
1539 (assoc-string tag-name sgml-unclosed-tags 'ignore-case)))
1542 (defun sgml-calculate-indent (&optional lcon)
1543 "Calculate the column to which this line should be indented.
1544 LCON is the lexical context, if any."
1545 (unless lcon (setq lcon (sgml-lexical-context)))
1547 ;; Indent comment-start markers inside <!-- just like comment-end markers.
1548 (if (and (eq (car lcon) 'tag)
1549 (looking-at "--")
1550 (save-excursion (goto-char (cdr lcon)) (looking-at "<!--")))
1551 (setq lcon (cons 'comment (+ (cdr lcon) 2))))
1553 (pcase (car lcon)
1555 (`string
1556 ;; Go back to previous non-empty line.
1557 (while (and (> (point) (cdr lcon))
1558 (zerop (forward-line -1))
1559 (looking-at "[ \t]*$")))
1560 (if (> (point) (cdr lcon))
1561 ;; Previous line is inside the string.
1562 (current-indentation)
1563 (goto-char (cdr lcon))
1564 (1+ (current-column))))
1566 (`comment
1567 (let ((mark (looking-at "--")))
1568 ;; Go back to previous non-empty line.
1569 (while (and (> (point) (cdr lcon))
1570 (zerop (forward-line -1))
1571 (or (looking-at "[ \t]*$")
1572 (if mark (not (looking-at "[ \t]*--"))))))
1573 (if (> (point) (cdr lcon))
1574 ;; Previous line is inside the comment.
1575 (skip-chars-forward " \t")
1576 (goto-char (cdr lcon))
1577 ;; Skip `<!' to get to the `--' with which we want to align.
1578 (search-forward "--")
1579 (goto-char (match-beginning 0)))
1580 (when (and (not mark) (looking-at "--"))
1581 (forward-char 2) (skip-chars-forward " \t"))
1582 (current-column)))
1584 ;; We don't know how to indent it. Let's be honest about it.
1585 (`cdata nil)
1586 ;; We don't know how to indent it. Let's be honest about it.
1587 (`pi nil)
1589 (`tag
1590 (goto-char (+ (cdr lcon) sgml-attribute-offset))
1591 (skip-chars-forward "^ \t\n") ;Skip tag name.
1592 (skip-chars-forward " \t")
1593 (if (not (eolp))
1594 (current-column)
1595 ;; This is the first attribute: indent.
1596 (goto-char (+ (cdr lcon) sgml-attribute-offset))
1597 (+ (current-column) sgml-basic-offset)))
1599 (`text
1600 (while (looking-at "</")
1601 (sgml-forward-sexp 1)
1602 (skip-chars-forward " \t"))
1603 (let* ((here (point))
1604 (unclosed (and ;; (not sgml-xml-mode)
1605 (looking-at sgml-tag-name-re)
1606 (assoc-string (match-string 1)
1607 sgml-unclosed-tags 'ignore-case)
1608 (match-string 1)))
1609 (context
1610 ;; If possible, align on the previous non-empty text line.
1611 ;; Otherwise, do a more serious parsing to find the
1612 ;; tag(s) relative to which we should be indenting.
1613 (if (and (not unclosed) (skip-chars-backward " \t")
1614 (< (skip-chars-backward " \t\n") 0)
1615 (back-to-indentation)
1616 (> (point) (cdr lcon)))
1618 (goto-char here)
1619 (nreverse (sgml-get-context (if unclosed nil 'empty)))))
1620 (there (point)))
1621 ;; Ignore previous unclosed start-tag in context.
1622 (while (and context unclosed
1623 (eq t (compare-strings
1624 (sgml-tag-name (car context)) nil nil
1625 unclosed nil nil t)))
1626 (setq context (cdr context)))
1627 ;; Indent to reflect nesting.
1628 (cond
1629 ;; If we were not in a text context after all, let's try again.
1630 ((and context (> (sgml-tag-end (car context)) here))
1631 (goto-char here)
1632 (sgml-calculate-indent
1633 (cons (if (memq (sgml-tag-type (car context)) '(comment cdata))
1634 (sgml-tag-type (car context)) 'tag)
1635 (sgml-tag-start (car context)))))
1636 ;; Align on the first element after the nearest open-tag, if any.
1637 ((and context
1638 (goto-char (sgml-tag-end (car context)))
1639 (skip-chars-forward " \t\n")
1640 (< (point) here) (sgml-at-indentation-p))
1641 (current-column))
1642 ;; ;; If the parsing failed, try to recover.
1643 ;; ((and (null context) (bobp)
1644 ;; (not (eq (char-after here) ?<)))
1645 ;; (goto-char here)
1646 ;; (if (and (looking-at "--[ \t\n]*>")
1647 ;; (re-search-backward "<!--" nil t))
1648 ;; ;; No wonder parsing failed: we're in a comment.
1649 ;; (sgml-calculate-indent (prog2 (goto-char (match-end 0))
1650 ;; (sgml-lexical-context)
1651 ;; (goto-char here)))
1652 ;; ;; We have no clue what's going on, let's be honest about it.
1653 ;; nil))
1654 ;; Otherwise, just follow the rules.
1656 (goto-char there)
1657 (+ (current-column)
1658 (* sgml-basic-offset (length context)))))))
1661 (error "Unrecognized context %s" (car lcon)))
1665 (defun sgml-indent-line ()
1666 "Indent the current line as SGML."
1667 (interactive)
1668 (let* ((savep (point))
1669 (indent-col
1670 (save-excursion
1671 (back-to-indentation)
1672 (if (>= (point) savep) (setq savep nil))
1673 (sgml-calculate-indent))))
1674 (if (null indent-col)
1675 'noindent
1676 (if savep
1677 (save-excursion (indent-line-to indent-col))
1678 (indent-line-to indent-col)))))
1680 (defun sgml-guess-indent ()
1681 "Guess an appropriate value for `sgml-basic-offset'.
1682 Base the guessed indentation level on the first indented tag in the buffer.
1683 Add this to `sgml-mode-hook' for convenience."
1684 (interactive)
1685 (save-excursion
1686 (goto-char (point-min))
1687 (if (re-search-forward "^\\([ \t]+\\)<" 500 'noerror)
1688 (progn
1689 (setq-local sgml-basic-offset (1- (current-column)))
1690 (message "Guessed sgml-basic-offset = %d"
1691 sgml-basic-offset)
1692 ))))
1694 (defun sgml-parse-dtd ()
1695 "Simplistic parse of the current buffer as a DTD.
1696 Currently just returns (EMPTY-TAGS UNCLOSED-TAGS)."
1697 (goto-char (point-min))
1698 (let ((empty nil)
1699 (unclosed nil))
1700 (while (re-search-forward "<!ELEMENT[ \t\n]+\\([^ \t\n]+\\)[ \t\n]+[-O][ \t\n]+\\([-O]\\)[ \t\n]+\\([^ \t\n]+\\)" nil t)
1701 (cond
1702 ((string= (match-string 3) "EMPTY")
1703 (push (match-string-no-properties 1) empty))
1704 ((string= (match-string 2) "O")
1705 (push (match-string-no-properties 1) unclosed))))
1706 (setq empty (sort (mapcar 'downcase empty) 'string<))
1707 (setq unclosed (sort (mapcar 'downcase unclosed) 'string<))
1708 (list empty unclosed)))
1710 ;;; HTML mode
1712 (defcustom html-mode-hook nil
1713 "Hook run by command `html-mode'.
1714 `text-mode-hook' and `sgml-mode-hook' are run first."
1715 :group 'sgml
1716 :type 'hook
1717 :options '(html-autoview-mode))
1719 (defvar html-quick-keys sgml-quick-keys
1720 "Use C-c X combinations for quick insertion of frequent tags when non-nil.
1721 This defaults to `sgml-quick-keys'.
1722 This takes effect when first loading the library.")
1724 (defvar html-mode-map
1725 (let ((map (make-sparse-keymap))
1726 (menu-map (make-sparse-keymap "HTML")))
1727 (set-keymap-parent map sgml-mode-map)
1728 (define-key map "\C-c6" 'html-headline-6)
1729 (define-key map "\C-c5" 'html-headline-5)
1730 (define-key map "\C-c4" 'html-headline-4)
1731 (define-key map "\C-c3" 'html-headline-3)
1732 (define-key map "\C-c2" 'html-headline-2)
1733 (define-key map "\C-c1" 'html-headline-1)
1734 (define-key map "\C-c\r" 'html-paragraph)
1735 (define-key map "\C-c\n" 'html-line)
1736 (define-key map "\C-c\C-c-" 'html-horizontal-rule)
1737 (define-key map "\C-c\C-co" 'html-ordered-list)
1738 (define-key map "\C-c\C-cu" 'html-unordered-list)
1739 (define-key map "\C-c\C-cr" 'html-radio-buttons)
1740 (define-key map "\C-c\C-cc" 'html-checkboxes)
1741 (define-key map "\C-c\C-cl" 'html-list-item)
1742 (define-key map "\C-c\C-ch" 'html-href-anchor)
1743 (define-key map "\C-c\C-cn" 'html-name-anchor)
1744 (define-key map "\C-c\C-ci" 'html-image)
1745 (when html-quick-keys
1746 (define-key map "\C-c-" 'html-horizontal-rule)
1747 (define-key map "\C-co" 'html-ordered-list)
1748 (define-key map "\C-cu" 'html-unordered-list)
1749 (define-key map "\C-cr" 'html-radio-buttons)
1750 (define-key map "\C-cc" 'html-checkboxes)
1751 (define-key map "\C-cl" 'html-list-item)
1752 (define-key map "\C-ch" 'html-href-anchor)
1753 (define-key map "\C-cn" 'html-name-anchor)
1754 (define-key map "\C-ci" 'html-image))
1755 (define-key map "\C-c\C-s" 'html-autoview-mode)
1756 (define-key map "\C-c\C-v" 'browse-url-of-buffer)
1757 (define-key map [menu-bar html] (cons "HTML" menu-map))
1758 (define-key menu-map [html-autoview-mode]
1759 '("Toggle Autoviewing" . html-autoview-mode))
1760 (define-key menu-map [browse-url-of-buffer]
1761 '("View Buffer Contents" . browse-url-of-buffer))
1762 (define-key menu-map [nil] '("--"))
1763 ;;(define-key menu-map "6" '("Heading 6" . html-headline-6))
1764 ;;(define-key menu-map "5" '("Heading 5" . html-headline-5))
1765 ;;(define-key menu-map "4" '("Heading 4" . html-headline-4))
1766 (define-key menu-map "3" '("Heading 3" . html-headline-3))
1767 (define-key menu-map "2" '("Heading 2" . html-headline-2))
1768 (define-key menu-map "1" '("Heading 1" . html-headline-1))
1769 (define-key menu-map "l" '("Radio Buttons" . html-radio-buttons))
1770 (define-key menu-map "c" '("Checkboxes" . html-checkboxes))
1771 (define-key menu-map "l" '("List Item" . html-list-item))
1772 (define-key menu-map "u" '("Unordered List" . html-unordered-list))
1773 (define-key menu-map "o" '("Ordered List" . html-ordered-list))
1774 (define-key menu-map "-" '("Horizontal Rule" . html-horizontal-rule))
1775 (define-key menu-map "\n" '("Line Break" . html-line))
1776 (define-key menu-map "\r" '("Paragraph" . html-paragraph))
1777 (define-key menu-map "i" '("Image" . html-image))
1778 (define-key menu-map "h" '("Href Anchor" . html-href-anchor))
1779 (define-key menu-map "n" '("Name Anchor" . html-name-anchor))
1780 map)
1781 "Keymap for commands for use in HTML mode.")
1783 (defvar html-face-tag-alist
1784 '((bold . "b")
1785 (italic . "i")
1786 (underline . "u")
1787 (mode-line . "rev"))
1788 "Value of `sgml-face-tag-alist' for HTML mode.")
1790 (defvar html-tag-face-alist
1791 '(("b" . bold)
1792 ("big" . bold)
1793 ("blink" . highlight)
1794 ("cite" . italic)
1795 ("em" . italic)
1796 ("h1" bold underline)
1797 ("h2" bold-italic underline)
1798 ("h3" italic underline)
1799 ("h4" . underline)
1800 ("h5" . underline)
1801 ("h6" . underline)
1802 ("i" . italic)
1803 ("rev" . mode-line)
1804 ("s" . underline)
1805 ("small" . default)
1806 ("strong" . bold)
1807 ("title" bold underline)
1808 ("tt" . default)
1809 ("u" . underline)
1810 ("var" . italic))
1811 "Value of `sgml-tag-face-alist' for HTML mode.")
1813 (defvar html-display-text
1814 '((img . "[/]")
1815 (hr . "----------")
1816 (li . "o "))
1817 "Value of `sgml-display-text' for HTML mode.")
1820 (defvar html-tag-alist
1821 (let* ((1-7 '(("1") ("2") ("3") ("4") ("5") ("6") ("7")))
1822 (1-9 `(,@1-7 ("8") ("9")))
1823 (align '(("align" ("left") ("center") ("right"))))
1824 (ialign '(("align" ("top") ("middle") ("bottom") ("left")
1825 ("right"))))
1826 (valign '(("top") ("middle") ("bottom") ("baseline")))
1827 (rel '(("next") ("previous") ("parent") ("subdocument") ("made")))
1828 (href '("href" ("ftp:") ("file:") ("finger:") ("gopher:") ("http:")
1829 ("mailto:") ("news:") ("rlogin:") ("telnet:") ("tn3270:")
1830 ("wais:") ("/cgi-bin/")))
1831 (name '("name"))
1832 (link `(,href
1833 ("rel" ,@rel)
1834 ("rev" ,@rel)
1835 ("title")))
1836 (list '((nil \n ("List item: " "<li>" str
1837 (if sgml-xml-mode "</li>") \n))))
1838 (shape '(("shape" ("rect") ("circle") ("poly") ("default"))))
1839 (cell `(t
1840 ,@align
1841 ("valign" ,@valign)
1842 ("colspan" ,@1-9)
1843 ("rowspan" ,@1-9)
1844 ("nowrap" t)))
1845 (cellhalign '(("align" ("left") ("center") ("right")
1846 ("justify") ("char"))
1847 ("char") ("charoff")))
1848 (cellvalign '(("valign" ("top") ("middle") ("bottom")
1849 ("baseline")))))
1850 ;; put ,-expressions first, else byte-compile chokes (as of V19.29)
1851 ;; and like this it's more efficient anyway
1852 `(("a" ,name ,@link)
1853 ("area" t ,@shape ("coords") ("href") ("nohref" "nohref") ("alt")
1854 ("tabindex") ("accesskey") ("onfocus") ("onblur"))
1855 ("base" t ,@href)
1856 ("col" t ,@cellhalign ,@cellvalign ("span") ("width"))
1857 ("colgroup" \n ,@cellhalign ,@cellvalign ("span") ("width"))
1858 ("dir" ,@list)
1859 ("figcaption")
1860 ("figure" \n)
1861 ("font" nil "size" ("-1") ("+1") ("-2") ("+2") ,@1-7)
1862 ("form" (\n _ \n "<input type=\"submit\" value=\"\""
1863 (if sgml-xml-mode " />" ">"))
1864 ("action" ,@(cdr href)) ("method" ("get") ("post")))
1865 ("h1" ,@align)
1866 ("h2" ,@align)
1867 ("h3" ,@align)
1868 ("h4" ,@align)
1869 ("h5" ,@align)
1870 ("h6" ,@align)
1871 ("hr" t ("size" ,@1-9) ("width") ("noshade" t) ,@align)
1872 ("iframe" \n ,@ialign ("longdesc") ("name") ("src")
1873 ("frameborder" ("1") ("0")) ("marginwidth") ("marginheight")
1874 ("scrolling" ("yes") ("no") ("auto")) ("height") ("width"))
1875 ("img" t ("align" ,@valign ("texttop") ("absmiddle") ("absbottom"))
1876 ("src") ("alt") ("width" "1") ("height" "1")
1877 ("border" "1") ("vspace" "1") ("hspace" "1") ("ismap" t))
1878 ("input" t ,name ("accept") ("alt") ("autocomplete" ("on") ("off"))
1879 ("autofocus" t) ("checked" t) ("dirname") ("disabled" t) ("form")
1880 ("formaction")
1881 ("formenctype" ("application/x-www-form-urlencoded")
1882 ("multipart/form-data") ("text/plain"))
1883 ("formmethod" ("get") ("post"))
1884 ("formnovalidate" t)
1885 ("formtarget" ("_blank") ("_self") ("_parent") ("_top"))
1886 ("height") ("inputmode") ("list") ("max") ("maxlength") ("min")
1887 ("minlength") ("multiple" t) ("pattern") ("placeholder")
1888 ("readonly" t) ("required" t) ("size") ("src") ("step")
1889 ("type" ("hidden") ("text") ("search") ("tel") ("url") ("email")
1890 ("password") ("date") ("time") ("number") ("range") ("color")
1891 ("checkbox") ("radio") ("file") ("submit") ("image") ("reset")
1892 ("button"))
1893 ("value") ("width"))
1894 ("link" t ,@link)
1895 ("menu" ,@list)
1896 ("ol" ,@list ("type" ("A") ("a") ("I") ("i") ("1")))
1897 ("p" t ,@align)
1898 ("select" (nil \n
1899 ("Text: "
1900 "<option>" str (if sgml-xml-mode "</option>") \n))
1901 ,name ("size" ,@1-9) ("multiple" t))
1902 ("table" (nil \n
1903 ((completing-read "Cell kind: " '(("td") ("th"))
1904 nil t "t")
1905 "<tr><" str ?> _
1906 (if sgml-xml-mode (concat "<" str "></tr>")) \n))
1907 ("border" t ,@1-9) ("width" "10") ("cellpadding"))
1908 ("tbody" \n ,@cellhalign ,@cellvalign)
1909 ("td" ,@cell)
1910 ("textarea" ,name ("rows" ,@1-9) ("cols" ,@1-9))
1911 ("tfoot" \n ,@cellhalign ,@cellvalign)
1912 ("th" ,@cell)
1913 ("thead" \n ,@cellhalign ,@cellvalign)
1914 ("ul" ,@list ("type" ("disc") ("circle") ("square")))
1916 ,@sgml-tag-alist
1918 ("abbr")
1919 ("acronym")
1920 ("address")
1921 ("array" (nil \n
1922 ("Item: " "<item>" str (if sgml-xml-mode "</item>") \n))
1923 "align")
1924 ("article" \n)
1925 ("aside" \n)
1926 ("au")
1927 ("audio" \n
1928 ("src") ("crossorigin" ("anonymous") ("use-credentials"))
1929 ("preload" ("none") ("metadata") ("auto"))
1930 ("autoplay" "autoplay") ("mediagroup") ("loop" "loop")
1931 ("muted" "muted") ("controls" "controls"))
1932 ("b")
1933 ("bdi")
1934 ("bdo" nil ("lang") ("dir" ("ltr") ("rtl")))
1935 ("big")
1936 ("blink")
1937 ("blockquote" \n ("cite"))
1938 ("body" \n ("background" ".gif") ("bgcolor" "#") ("text" "#")
1939 ("link" "#") ("alink" "#") ("vlink" "#"))
1940 ("box" (nil _ "<over>" _ (if sgml-xml-mode "</over>")))
1941 ("br" t ("clear" ("left") ("right")))
1942 ("button" nil ("name") ("value")
1943 ("type" ("submit") ("reset") ("button"))
1944 ("disabled" "disabled")
1945 ("tabindex") ("accesskey") ("onfocus") ("onblur"))
1946 ("canvas" \n ("width") ("height"))
1947 ("caption" ("valign" ("top") ("bottom")))
1948 ("center" \n)
1949 ("cite")
1950 ("code" \n)
1951 ("datalist" \n)
1952 ("dd" ,(not sgml-xml-mode))
1953 ("del" nil ("cite") ("datetime"))
1954 ("dfn")
1955 ("div")
1956 ("dl" (nil \n
1957 ( "Term: "
1958 "<dt>" str (if sgml-xml-mode "</dt>")
1959 "<dd>" _ (if sgml-xml-mode "</dd>") \n)))
1960 ("dt" (t _ (if sgml-xml-mode "</dt>")
1961 "<dd>" (if sgml-xml-mode "</dd>") \n))
1962 ("em")
1963 ("embed" t ("src") ("type") ("width") ("height"))
1964 ("fieldset" \n)
1965 ("fn" "id" "fn") ;; Footnotes were deprecated in HTML 3.2
1966 ("footer" \n)
1967 ("frame" t ("longdesc") ("name") ("src")
1968 ("frameborder" ("1") ("0")) ("marginwidth") ("marginheight")
1969 ("noresize" "noresize") ("scrolling" ("yes") ("no") ("auto")))
1970 ("frameset" \n ("rows") ("cols") ("onload") ("onunload"))
1971 ("head" \n)
1972 ("header" \n)
1973 ("hgroup" \n)
1974 ("html" (\n
1975 "<head>\n"
1976 "<title>" (setq str (read-string "Title: ")) "</title>\n"
1977 "</head>\n"
1978 "<body>\n<h1>" str "</h1>\n" _
1979 "\n<address>\n<a href=\"mailto:"
1980 user-mail-address
1981 "\">" (user-full-name) "</a>\n</address>\n"
1982 "</body>"
1984 ("i")
1985 ("ins" nil ("cite") ("datetime"))
1986 ("isindex" t ("action") ("prompt"))
1987 ("kbd")
1988 ("label" nil ("for") ("accesskey") ("onfocus") ("onblur"))
1989 ("lang")
1990 ("legend" nil ("accesskey"))
1991 ("li" ,(not sgml-xml-mode))
1992 ("main" \n)
1993 ("map" \n ("name"))
1994 ("mark")
1995 ("math" \n)
1996 ("meta" t ("http-equiv") ("name") ("content") ("scheme"))
1997 ("meter" nil ("value") ("min") ("max") ("low") ("high")
1998 ("optimum"))
1999 ("nav" \n)
2000 ("nobr")
2001 ("noframes" \n)
2002 ("noscript" \n)
2003 ("object" \n ("declare" "declare") ("classid") ("codebase")
2004 ("data") ("type") ("codetype") ("archive") ("standby")
2005 ("height") ("width") ("usemap") ("name") ("tabindex"))
2006 ("optgroup" \n ("name") ("size") ("multiple" "multiple")
2007 ("disabled" "disabled") ("tabindex") ("onfocus") ("onblur")
2008 ("onchange"))
2009 ("option" t ("value") ("label") ("selected" t))
2010 ("output" nil ("for") ("form") ("name"))
2011 ("over" t)
2012 ("param" t ("name") ("value")
2013 ("valuetype" ("data") ("ref") ("object")) ("type"))
2014 ("person") ;; Tag for person's name tag deprecated in HTML 3.2
2015 ("pre" \n)
2016 ("progress" nil ("value") ("max"))
2017 ("q" nil ("cite"))
2018 ("rev")
2019 ("rp" t)
2020 ("rt" t)
2021 ("ruby")
2022 ("s")
2023 ("samp")
2024 ("script" nil ("charset") ("type") ("src") ("defer" "defer"))
2025 ("section" \n)
2026 ("small")
2027 ("source" t ("src") ("type") ("media"))
2028 ("span" nil
2029 ("class"
2030 ("builtin")
2031 ("comment")
2032 ("constant")
2033 ("function-name")
2034 ("keyword")
2035 ("string")
2036 ("type")
2037 ("variable-name")
2038 ("warning")))
2039 ("strong")
2040 ("style" \n ("type") ("media") ("title"))
2041 ("sub")
2042 ("summary")
2043 ("sup")
2044 ("time" nil ("datetime"))
2045 ("title")
2046 ("tr" t)
2047 ("track" t
2048 ("kind" ("subtitles") ("captions") ("descriptions")
2049 ("chapters") ("metadata"))
2050 ("src") ("srclang") ("label") ("default"))
2051 ("tt")
2052 ("u")
2053 ("var")
2054 ("video" \n
2055 ("src") ("crossorigin" ("anonymous") ("use-credentials"))
2056 ("poster") ("preload" ("none") ("metadata") ("auto"))
2057 ("autoplay" "autoplay") ("mediagroup") ("loop" "loop")
2058 ("muted" "muted") ("controls" "controls") ("width") ("height"))
2059 ("wbr" t)))
2060 "Value of `sgml-tag-alist' for HTML mode.")
2062 (defvar html-tag-help
2063 `(,@sgml-tag-help
2064 ("a" . "Anchor of point or link elsewhere")
2065 ("abbr" . "Abbreviation")
2066 ("acronym" . "Acronym")
2067 ("address" . "Formatted mail address")
2068 ("area" . "Region of an image map")
2069 ("array" . "Math array")
2070 ("article" . "An independent part of document or site")
2071 ("aside" . "Secondary content related to surrounding content (e.g. page or article)")
2072 ("au" . "Author")
2073 ("audio" . "Sound or audio stream")
2074 ("b" . "Bold face")
2075 ("base" . "Base address for URLs")
2076 ("bdi" . "Text isolated for bidirectional formatting")
2077 ("bdo" . "Override text directionality")
2078 ("big" . "Font size")
2079 ("blink" . "Blinking text")
2080 ("blockquote" . "Indented quotation")
2081 ("body" . "Document body")
2082 ("box" . "Math fraction")
2083 ("br" . "Line break")
2084 ("button" . "Clickable button")
2085 ("canvas" . "Script generated graphics canvas")
2086 ("caption" . "Table caption")
2087 ("center" . "Centered text")
2088 ("changed" . "Change bars")
2089 ("cite" . "Citation of a document")
2090 ("code" . "Formatted source code")
2091 ("col" . "Group of attribute specifications for table columns")
2092 ("colgroup" . "Group of columns")
2093 ("datalist" . "A set of predefined options")
2094 ("dd" . "Definition of term")
2095 ("del" . "Deleted text")
2096 ("dfn" . "Defining instance of a term")
2097 ("dir" . "Directory list (obsolete)")
2098 ("div" . "Generic block-level container")
2099 ("dl" . "Definition list")
2100 ("dt" . "Term to be defined")
2101 ("em" . "Emphasized")
2102 ("embed" . "Embedded data in foreign format")
2103 ("fieldset" . "Group of related controls and labels")
2104 ("fig" . "Figure")
2105 ("figa" . "Figure anchor")
2106 ("figcaption" . "Caption for a figure")
2107 ("figd" . "Figure description")
2108 ("figt" . "Figure text")
2109 ("figure" . "Self-contained content, often with a caption")
2110 ("fn" . "Footnote") ;; No one supports special footnote rendering.
2111 ("font" . "Font size")
2112 ("footer" . "Footer of a section")
2113 ("form" . "Form with input fields")
2114 ("frame" . "Frame in which another HTML document can be displayed")
2115 ("frameset" . "Container for frames")
2116 ("group" . "Document grouping")
2117 ("h1" . "Most important section headline")
2118 ("h2" . "Important section headline")
2119 ("h3" . "Section headline")
2120 ("h4" . "Minor section headline")
2121 ("h5" . "Unimportant section headline")
2122 ("h6" . "Least important section headline")
2123 ("head" . "Document header")
2124 ("header" . "Header of a section")
2125 ("hgroup" . "Group of headings - h1-h6 elements")
2126 ("hr" . "Horizontal rule")
2127 ("html" . "HTML Document")
2128 ("i" . "Italic face")
2129 ("iframe" . "Inline frame with a nested browsing context")
2130 ("img" . "Graphic image")
2131 ("input" . "Form input field")
2132 ("ins" . "Inserted text")
2133 ("isindex" . "Input field for index search")
2134 ("kbd" . "Keyboard example face")
2135 ("label" . "Caption for a user interface item")
2136 ("lang" . "Natural language")
2137 ("legend" . "Caption for a fieldset")
2138 ("li" . "List item")
2139 ("link" . "Link relationship")
2140 ("main" . "Main content of the document body")
2141 ("map" . "Image map (a clickable link area")
2142 ("mark" . "Highlighted text")
2143 ("math" . "Math formula")
2144 ("menu" . "List of commands")
2145 ("meta" . "Document properties")
2146 ("meter" . "Scalar measurement within a known range")
2147 ("mh" . "Form mail header")
2148 ("nav" . "Group of navigational links")
2149 ("nextid" . "Allocate new id")
2150 ("nobr" . "Text without line break")
2151 ("noframes" . "Content for user agents that don't support frames")
2152 ("noscript" . "Alternate content for when a script isn't executed")
2153 ("object" . "External resource")
2154 ("ol" . "Ordered list")
2155 ("optgroup" . "Group of options")
2156 ("option" . "Selection list item")
2157 ("output" . "Result of a calculation or user action")
2158 ("over" . "Math fraction rule")
2159 ("p" . "Paragraph start")
2160 ("panel" . "Floating panel")
2161 ("param" . "Parameters for an object")
2162 ("person" . "Person's name")
2163 ("pre" . "Preformatted fixed width text")
2164 ("progress" . "Completion progress of a task")
2165 ("q" . "Quotation")
2166 ("rev" . "Reverse video")
2167 ("rp" . "Fallback text for when ruby annotations aren't supported")
2168 ("rt" . "Ruby text component of a ruby annotation")
2169 ("ruby" . "Ruby annotation")
2170 ("s" . "Strikeout")
2171 ("samp" . "Sample text")
2172 ("script" . "Executable script within a document")
2173 ("section" . "Section of a document")
2174 ("select" . "Selection list")
2175 ("small" . "Font size")
2176 ("source" . "Media resource for media elements")
2177 ("sp" . "Nobreak space")
2178 ("span" . "Generic inline container")
2179 ("strong" . "Standout text")
2180 ("style" . "Style information")
2181 ("sub" . "Subscript")
2182 ("summary" . "Summary, caption, or legend")
2183 ("sup" . "Superscript")
2184 ("table" . "Table with rows and columns")
2185 ("tb" . "Table vertical break")
2186 ("tbody" . "Table body")
2187 ("td" . "Table data cell")
2188 ("textarea" . "Form multiline edit area")
2189 ("tfoot" . "Table foot")
2190 ("th" . "Table header cell")
2191 ("thead" . "Table head")
2192 ("time" . "Content with optional machine-readable timestamp")
2193 ("title" . "Document title")
2194 ("tr" . "Table row separator")
2195 ("track" . "Timed text track for media elements")
2196 ("tt" . "Typewriter face")
2197 ("u" . "Underlined text")
2198 ("ul" . "Unordered list")
2199 ("var" . "Math variable face")
2200 ("video" . "Video or movie")
2201 ("wbr" . "Enable <br> within <nobr>"))
2202 "Value of variable `sgml-tag-help' for HTML mode.")
2204 (defvar outline-regexp)
2205 (defvar outline-heading-end-regexp)
2206 (defvar outline-level)
2208 (defun html-current-defun-name ()
2209 "Return the name of the last HTML title or heading, or nil."
2210 (save-excursion
2211 (if (re-search-backward
2212 (concat
2213 "<[ \t\r\n]*"
2214 "\\(?:[hH][0-6]\\|title\\|TITLE\\|Title\\)"
2215 "[^>]*>"
2216 "[ \t\r\n]*"
2217 "\\([^<\r\n]*[^ <\t\r\n]+\\)")
2218 nil t)
2219 (match-string-no-properties 1))))
2221 (defvar html--buffer-classes-cache nil
2222 "Cache for `html-current-buffer-classes'.
2223 When set, this should be a cons cell where the CAR is the
2224 buffer's tick counter (as produced by `buffer-modified-tick'),
2225 and the CDR is the list of class names found in the buffer.")
2226 (make-variable-buffer-local 'html--buffer-classes-cache)
2228 (defvar html--buffer-ids-cache nil
2229 "Cache for `html-current-buffer-ids'.
2230 When set, this should be a cons cell where the CAR is the
2231 buffer's tick counter (as produced by `buffer-modified-tick'),
2232 and the CDR is the list of class names found in the buffer.")
2233 (make-variable-buffer-local 'html--buffer-ids-cache)
2235 (defun html-current-buffer-classes ()
2236 "Return a list of class names used in the current buffer.
2237 The result is cached in `html--buffer-classes-cache'."
2238 (let ((tick (buffer-modified-tick)))
2239 (if (eq (car html--buffer-classes-cache) tick)
2240 (cdr html--buffer-classes-cache)
2241 (let* ((dom (libxml-parse-html-region (point-min) (point-max)))
2242 (classes
2243 (seq-mapcat
2244 (lambda (el)
2245 (when-let* ((class-list
2246 (cdr (assq 'class (dom-attributes el)))))
2247 (split-string class-list)))
2248 (dom-by-class dom ""))))
2249 (setq-local html--buffer-classes-cache (cons tick classes))
2250 classes))))
2252 (defun html-current-buffer-ids ()
2253 "Return a list of IDs used in the current buffer.
2254 The result is cached in `html--buffer-ids-cache'."
2255 (let ((tick (buffer-modified-tick)))
2256 (if (eq (car html--buffer-ids-cache) tick)
2257 (cdr html--buffer-ids-cache)
2258 (let* ((dom
2259 (libxml-parse-html-region (point-min) (point-max)))
2260 (ids
2261 (seq-mapcat
2262 (lambda (el)
2263 (when-let* ((id-list
2264 (cdr (assq 'id (dom-attributes el)))))
2265 (split-string id-list)))
2266 (dom-by-id dom ""))))
2267 (setq-local html--buffer-ids-cache (cons tick ids))
2268 ids))))
2271 ;;;###autoload
2272 (define-derived-mode html-mode sgml-mode '(sgml-xml-mode "XHTML" "HTML")
2273 "Major mode based on SGML mode for editing HTML documents.
2274 This allows inserting skeleton constructs used in hypertext documents with
2275 completion. See below for an introduction to HTML. Use
2276 \\[browse-url-of-buffer] to see how this comes out. See also `sgml-mode' on
2277 which this is based.
2279 Do \\[describe-variable] html- SPC and \\[describe-variable] sgml- SPC to see available variables.
2281 To write fairly well formatted pages you only need to know few things. Most
2282 browsers have a function to read the source code of the page being seen, so
2283 you can imitate various tricks. Here's a very short HTML primer which you
2284 can also view with a browser to see what happens:
2286 <title>A Title Describing Contents</title> should be on every page. Pages can
2287 have <h1>Very Major Headlines</h1> through <h6>Very Minor Headlines</h6>
2288 <hr> Parts can be separated with horizontal rules.
2290 <p>Paragraphs only need an opening tag. Line breaks and multiple spaces are
2291 ignored unless the text is <pre>preformatted.</pre> Text can be marked as
2292 <b>bold</b>, <i>italic</i> or <u>underlined</u> using the normal M-o or
2293 Edit/Text Properties/Face commands.
2295 Pages can have <a name=\"SOMENAME\">named points</a> and can link other points
2296 to them with <a href=\"#SOMENAME\">see also somename</a>. In the same way <a
2297 href=\"URL\">see also URL</a> where URL is a filename relative to current
2298 directory, or absolute as in `http://www.cs.indiana.edu/elisp/w3/docs.html'.
2300 Images in many formats can be inlined with <img src=\"URL\">.
2302 If you mainly create your own documents, `sgml-specials' might be
2303 interesting. But note that some HTML 2 browsers can't handle `&apos;'.
2304 To work around that, do:
2305 (eval-after-load \"sgml-mode\" \\='(aset sgml-char-names ?\\=' nil))
2307 \\{html-mode-map}"
2308 (setq-local sgml-display-text html-display-text)
2309 (setq-local sgml-tag-face-alist html-tag-face-alist)
2310 (setq-local sgml-tag-alist html-tag-alist)
2311 (setq-local sgml-face-tag-alist html-face-tag-alist)
2312 (setq-local sgml-tag-help html-tag-help)
2313 (setq-local outline-regexp "^.*<[Hh][1-6]\\>")
2314 (setq-local outline-heading-end-regexp "</[Hh][1-6]>")
2315 (setq-local outline-level
2316 (lambda () (char-before (match-end 0))))
2317 (setq-local add-log-current-defun-function #'html-current-defun-name)
2318 (setq-local sentence-end-base "[.?!][]\"'”)}]*\\(<[^>]*>\\)*")
2320 (when (fboundp 'libxml-parse-html-region)
2321 (defvar css-class-list-function)
2322 (setq-local css-class-list-function #'html-current-buffer-classes)
2323 (defvar css-id-list-function)
2324 (setq-local css-id-list-function #'html-current-buffer-ids))
2326 (setq imenu-create-index-function 'html-imenu-index)
2328 (setq-local sgml-empty-tags
2329 ;; From HTML-4.01's loose.dtd, parsed with
2330 ;; `sgml-parse-dtd', plus manual addition of "wbr".
2331 '("area" "base" "basefont" "br" "col" "frame" "hr" "img" "input"
2332 "isindex" "link" "meta" "param" "wbr"))
2333 (setq-local sgml-unclosed-tags
2334 ;; From HTML-4.01's loose.dtd, parsed with `sgml-parse-dtd'.
2335 '("body" "colgroup" "dd" "dt" "head" "html" "li" "option"
2336 "p" "tbody" "td" "tfoot" "th" "thead" "tr"))
2337 ;; It's for the user to decide if it defeats it or not -stef
2338 ;; (make-local-variable 'imenu-sort-function)
2339 ;; (setq imenu-sort-function nil) ; sorting the menu defeats the purpose
2342 (defvar html-imenu-regexp
2343 "\\s-*<h\\([1-9]\\)[^\n<>]*>\\(<[^\n<>]*>\\)*\\s-*\\([^\n<>]*\\)"
2344 "A regular expression matching a head line to be added to the menu.
2345 The first `match-string' should be a number from 1-9.
2346 The second `match-string' matches extra tags and is ignored.
2347 The third `match-string' will be the used in the menu.")
2349 (defun html-imenu-index ()
2350 "Return a table of contents for an HTML buffer for use with Imenu."
2351 (let (toc-index)
2352 (save-excursion
2353 (goto-char (point-min))
2354 (while (re-search-forward html-imenu-regexp nil t)
2355 (setq toc-index
2356 (cons (cons (concat (make-string
2357 (* 2 (1- (string-to-number (match-string 1))))
2358 ?\s)
2359 (match-string 3))
2360 (line-beginning-position))
2361 toc-index))))
2362 (nreverse toc-index)))
2364 (define-minor-mode html-autoview-mode
2365 "Toggle viewing of HTML files on save (HTML Autoview mode).
2366 With a prefix argument ARG, enable HTML Autoview mode if ARG is
2367 positive, and disable it otherwise. If called from Lisp, enable
2368 the mode if ARG is omitted or nil.
2370 HTML Autoview mode is a buffer-local minor mode for use with
2371 `html-mode'. If enabled, saving the file automatically runs
2372 `browse-url-of-buffer' to view it."
2373 nil nil nil
2374 :group 'sgml
2375 (if html-autoview-mode
2376 (add-hook 'after-save-hook 'browse-url-of-buffer nil t)
2377 (remove-hook 'after-save-hook 'browse-url-of-buffer t)))
2380 (define-skeleton html-href-anchor
2381 "HTML anchor tag with href attribute."
2382 "URL: "
2383 ;; '(setq input "http:")
2384 "<a href=\"" str "\">" _ "</a>")
2386 (define-skeleton html-name-anchor
2387 "HTML anchor tag with name attribute."
2388 "Name: "
2389 "<a name=\"" str "\""
2390 (if sgml-xml-mode (concat " id=\"" str "\""))
2391 ">" _ "</a>")
2393 (define-skeleton html-headline-1
2394 "HTML level 1 headline tags."
2396 "<h1>" _ "</h1>")
2398 (define-skeleton html-headline-2
2399 "HTML level 2 headline tags."
2401 "<h2>" _ "</h2>")
2403 (define-skeleton html-headline-3
2404 "HTML level 3 headline tags."
2406 "<h3>" _ "</h3>")
2408 (define-skeleton html-headline-4
2409 "HTML level 4 headline tags."
2411 "<h4>" _ "</h4>")
2413 (define-skeleton html-headline-5
2414 "HTML level 5 headline tags."
2416 "<h5>" _ "</h5>")
2418 (define-skeleton html-headline-6
2419 "HTML level 6 headline tags."
2421 "<h6>" _ "</h6>")
2423 (define-skeleton html-horizontal-rule
2424 "HTML horizontal rule tag."
2426 (if sgml-xml-mode "<hr />" "<hr>") \n)
2428 (define-skeleton html-image
2429 "HTML image tag."
2430 "Image URL: "
2431 "<img src=\"" str "\" alt=\"" _ "\""
2432 (if sgml-xml-mode " />" ">"))
2434 (define-skeleton html-line
2435 "HTML line break tag."
2437 (if sgml-xml-mode "<br />" "<br>") \n)
2439 (define-skeleton html-ordered-list
2440 "HTML ordered list tags."
2442 "<ol>" \n
2443 "<li>" _ (if sgml-xml-mode "</li>") \n
2444 "</ol>")
2446 (define-skeleton html-unordered-list
2447 "HTML unordered list tags."
2449 "<ul>" \n
2450 "<li>" _ (if sgml-xml-mode "</li>") \n
2451 "</ul>")
2453 (define-skeleton html-list-item
2454 "HTML list item tag."
2456 (if (bolp) nil '\n)
2457 "<li>" _ (if sgml-xml-mode "</li>"))
2459 (define-skeleton html-paragraph
2460 "HTML paragraph tag."
2462 (if (bolp) nil ?\n)
2463 "<p>" _ (if sgml-xml-mode "</p>"))
2465 (define-skeleton html-checkboxes
2466 "Group of connected checkbox inputs."
2468 '(setq v1 nil
2469 v2 nil)
2470 ("Value: "
2471 "<input type=\"" (identity "checkbox") ; see comment above about identity
2472 "\" name=\"" (or v1 (setq v1 (skeleton-read "Name: ")))
2473 "\" value=\"" str ?\"
2474 (when (y-or-n-p "Set \"checked\" attribute? ")
2475 (funcall skeleton-transformation-function
2476 (if sgml-xml-mode " checked=\"checked\"" " checked")))
2477 (if sgml-xml-mode " />" ">")
2478 (skeleton-read "Text: " (capitalize str))
2479 (or v2 (setq v2 (if (y-or-n-p "Newline after text? ")
2480 (funcall skeleton-transformation-function
2481 (if sgml-xml-mode "<br />" "<br>"))
2482 "")))
2483 \n))
2485 (define-skeleton html-radio-buttons
2486 "Group of connected radio button inputs."
2488 '(setq v1 nil
2489 v2 (cons nil nil))
2490 ("Value: "
2491 "<input type=\"" (identity "radio") ; see comment above about identity
2492 "\" name=\"" (or (car v2) (setcar v2 (skeleton-read "Name: ")))
2493 "\" value=\"" str ?\"
2494 (when (and (not v1) (setq v1 (y-or-n-p "Set \"checked\" attribute? ")))
2495 (funcall skeleton-transformation-function
2496 (if sgml-xml-mode " checked=\"checked\"" " checked")))
2497 (if sgml-xml-mode " />" ">")
2498 (skeleton-read "Text: " (capitalize str))
2499 (or (cdr v2) (setcdr v2 (if (y-or-n-p "Newline after text? ")
2500 (funcall skeleton-transformation-function
2501 (if sgml-xml-mode "<br />" "<br>"))
2502 "")))
2503 \n))
2505 (define-skeleton html-navigational-links
2506 "Group of navigational links."
2508 "<nav>" \n
2509 "<ul>" \n
2510 "<li><a href=\"" (skeleton-read "URL: " "#") "\">"
2511 (skeleton-read "Title: ") "</a>"
2512 (if sgml-xml-mode (if sgml-xml-mode "</li>")) \n
2513 "</ul>" \n
2514 "</nav>")
2516 (define-skeleton html-html5-template
2517 "Initial HTML5 template"
2519 "<!DOCTYPE html>" \n
2520 "<html lang=\"en\">" \n
2521 "<head>" \n
2522 "<meta charset=\"utf-8\">" \n
2523 "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">" \n
2524 "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">" \n
2525 "<title>" (skeleton-read "Page Title: ") "</title>" \n
2526 "</head>" \n
2527 "<body>" \n
2528 "<div id=\"app\"></div>" \n
2529 "</body>" \n
2530 "</html>")
2532 (provide 'sgml-mode)
2534 ;;; sgml-mode.el ends here