Merge branch 'master' into comment-cache
[emacs.git] / lisp / textmodes / sgml-mode.el
blobe148b06aa7b209a02f6459efe3087c6f92712df9
1 ;;; sgml-mode.el --- SGML- and HTML-editing modes -*- lexical-binding:t -*-
3 ;; Copyright (C) 1992, 1995-1996, 1998, 2001-2017 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 <http://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 (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 (defconst sgml-syntax-propertize-function
345 (syntax-propertize-rules
346 ;; Use the `b' style of comments to avoid interference with the -- ... --
347 ;; comments recognized when `sgml-specials' includes ?-.
348 ;; FIXME: beware of <!--> blabla <!--> !!
349 ("\\(<\\)!--" (1 "< b"))
350 ("--[ \t\n]*\\(>\\)" (1 "> b"))
351 ;; Double quotes outside of tags should not introduce strings.
352 ;; Be careful to call `syntax-ppss' on a position before the one we're
353 ;; going to change, so as not to need to flush the data we just computed.
354 ("\"" (0 (if (prog1 (zerop (car (syntax-ppss (match-beginning 0))))
355 (goto-char (match-end 0)))
356 (string-to-syntax ".")))))
357 "Syntactic keywords for `sgml-mode'.")
359 ;; internal
360 (defvar sgml-face-tag-alist ()
361 "Alist of face and tag name for facemenu.")
363 (defvar sgml-tag-face-alist ()
364 "Tag names and face or list of faces to fontify with when invisible.
365 When `font-lock-maximum-decoration' is 1 this is always used for fontifying.
366 When more these are fontified together with `sgml-font-lock-keywords'.")
368 (defvar sgml-display-text ()
369 "Tag names as lowercase symbols, and display string when invisible.")
371 ;; internal
372 (defvar sgml-tags-invisible nil)
374 (defcustom sgml-tag-alist
375 '(("![" ("ignore" t) ("include" t))
376 ("!attlist")
377 ("!doctype")
378 ("!element")
379 ("!entity"))
380 "Alist of tag names for completing read and insertion rules.
381 This alist is made up as
383 ((\"tag\" . TAGRULE)
384 ...)
386 TAGRULE is a list of optionally t (no endtag) or `\\n' (separate endtag by
387 newlines) or a skeleton with nil, t or `\\n' in place of the interactor
388 followed by an ATTRIBUTERULE (for an always present attribute) or an
389 attribute alist.
391 The attribute alist is made up as
393 ((\"attribute\" . ATTRIBUTERULE)
394 ...)
396 ATTRIBUTERULE is a list of optionally t (no value when no input) followed by
397 an optional alist of possible values."
398 :type '(repeat (cons (string :tag "Tag Name")
399 (repeat :tag "Tag Rule" sexp)))
400 :group 'sgml)
401 (put 'sgml-tag-alist 'risky-local-variable t)
403 (defcustom sgml-tag-help
404 '(("!" . "Empty declaration for comment")
405 ("![" . "Embed declarations with parser directive")
406 ("!attlist" . "Tag attributes declaration")
407 ("!doctype" . "Document type (DTD) declaration")
408 ("!element" . "Tag declaration")
409 ("!entity" . "Entity (macro) declaration"))
410 "Alist of tag name and short description."
411 :type '(repeat (cons (string :tag "Tag Name")
412 (string :tag "Description")))
413 :group 'sgml)
415 (defvar sgml-empty-tags nil
416 "List of tags whose !ELEMENT definition says EMPTY.")
418 (defvar sgml-unclosed-tags nil
419 "List of tags whose !ELEMENT definition says the end-tag is optional.")
421 (defun sgml-xml-guess ()
422 "Guess whether the current buffer is XML. Return non-nil if so."
423 (save-excursion
424 (goto-char (point-min))
425 (or (string= "xml" (file-name-extension (or buffer-file-name "")))
426 ;; Maybe the buffer-size check isn't needed, I don't know.
427 (and (zerop (buffer-size))
428 (string= "xhtml" (file-name-extension (or buffer-file-name ""))))
429 (looking-at "\\s-*<\\?xml")
430 (when (re-search-forward
431 (eval-when-compile
432 (mapconcat 'identity
433 '("<!DOCTYPE" "\\(\\w+\\)" "\\(\\w+\\)"
434 "\"\\([^\"]+\\)\"" "\"\\([^\"]+\\)\"")
435 "\\s-+"))
436 nil t)
437 (string-match "X\\(HT\\)?ML" (match-string 3))))))
439 (defvar v2) ; free for skeleton
441 (defun sgml-comment-indent-new-line (&optional soft)
442 (let ((comment-start "-- ")
443 (comment-start-skip "\\(<!\\)?--[ \t]*")
444 (comment-end " --")
445 (comment-style 'plain))
446 (comment-indent-new-line soft)))
448 (defun sgml-mode-facemenu-add-face-function (face _end)
449 (let ((tag-face (cdr (assq face sgml-face-tag-alist))))
450 (cond (tag-face
451 (setq tag-face (funcall skeleton-transformation-function tag-face))
452 (setq facemenu-end-add-face (concat "</" tag-face ">"))
453 (concat "<" tag-face ">"))
454 ((and (consp face)
455 (consp (car face))
456 (null (cdr face))
457 (memq (caar face) '(:foreground :background)))
458 (setq facemenu-end-add-face "</span>")
459 (format "<span style=\"%s:%s\">"
460 (if (eq (caar face) :foreground)
461 "color"
462 "background-color")
463 (cadr (car face))))
465 (error "Face not configured for %s mode"
466 (format-mode-line mode-name))))))
468 (defun sgml-fill-nobreak ()
469 "Don't break between a tag name and its first argument.
470 This function is designed for use in `fill-nobreak-predicate'.
472 <a href=\"some://where\" type=\"text/plain\">
474 | no break here | but still allowed here"
475 (save-excursion
476 (skip-chars-backward " \t")
477 (and (not (zerop (skip-syntax-backward "w_")))
478 (skip-chars-backward "/?!")
479 (eq (char-before) ?<))))
481 (defvar tildify-space-string)
482 (defvar tildify-foreach-region-function)
484 ;;;###autoload
485 (define-derived-mode sgml-mode text-mode '(sgml-xml-mode "XML" "SGML")
486 "Major mode for editing SGML documents.
487 Makes > match <.
488 Keys <, &, SPC within <>, \", / and \\=' can be electric depending on
489 `sgml-quick-keys'.
491 An argument of N to a tag-inserting command means to wrap it around
492 the next N words. In Transient Mark mode, when the mark is active,
493 N defaults to -1, which means to wrap it around the current region.
495 If you like upcased tags, put (setq sgml-transformation-function \\='upcase)
496 in your init file.
498 Use \\[sgml-validate] to validate your document with an SGML parser.
500 Do \\[describe-variable] sgml- SPC to see available variables.
501 Do \\[describe-key] on the following bindings to discover what they do.
502 \\{sgml-mode-map}"
503 (make-local-variable 'sgml-saved-validate-command)
504 (make-local-variable 'facemenu-end-add-face)
505 ;; If encoding does not allow non-break space character, use reference.
506 ;; FIXME: Perhaps use &nbsp; if possible (e.g. when we know its HTML)?
507 (setq-local tildify-space-string
508 (if (equal (decode-coding-string
509 (encode-coding-string " " buffer-file-coding-system)
510 buffer-file-coding-system) " ")
511 " " "&#160;"))
512 ;; FIXME: Use the fact that we're parsing the document already
513 ;; rather than using regex-based filtering.
514 (setq-local tildify-foreach-region-function
515 (apply-partially
516 'tildify-foreach-ignore-environments
517 `((,(eval-when-compile
518 (concat
519 "<\\("
520 (regexp-opt '("pre" "dfn" "code" "samp" "kbd" "var"
521 "PRE" "DFN" "CODE" "SAMP" "KBD" "VAR"))
522 "\\)\\>[^>]*>"))
523 . ("</" 1 ">"))
524 ("<! *--" . "-- *>")
525 ("<" . ">"))))
526 ;;(make-local-variable 'facemenu-remove-face-function)
527 ;; A start or end tag by itself on a line separates a paragraph.
528 ;; This is desirable because SGML discards a newline that appears
529 ;; immediately after a start tag or immediately before an end tag.
530 (setq-local paragraph-start (concat "[ \t]*$\\|\
531 [ \t]*</?\\(" sgml-name-re sgml-attrs-re "\\)?>"))
532 (setq-local paragraph-separate (concat paragraph-start "$"))
533 (setq-local adaptive-fill-regexp "[ \t]*")
534 (add-hook 'fill-nobreak-predicate 'sgml-fill-nobreak nil t)
535 (setq-local indent-line-function 'sgml-indent-line)
536 (setq-local comment-start "<!-- ")
537 (setq-local comment-end " -->")
538 (setq-local comment-indent-function 'sgml-comment-indent)
539 (setq-local comment-line-break-function 'sgml-comment-indent-new-line)
540 (setq-local skeleton-further-elements '((completion-ignore-case t)))
541 (setq-local skeleton-end-hook
542 (lambda ()
543 (or (eolp)
544 (not (or (eq v2 '\n) (eq (car-safe v2) '\n)))
545 (newline-and-indent))))
546 (setq font-lock-defaults '((sgml-font-lock-keywords
547 sgml-font-lock-keywords-1
548 sgml-font-lock-keywords-2)
549 nil t))
550 (setq-local syntax-propertize-function sgml-syntax-propertize-function)
551 (setq-local facemenu-add-face-function 'sgml-mode-facemenu-add-face-function)
552 (setq-local sgml-xml-mode (sgml-xml-guess))
553 (unless sgml-xml-mode
554 (setq-local skeleton-transformation-function sgml-transformation-function))
555 ;; This will allow existing comments within declarations to be
556 ;; recognized.
557 ;; I can't find a clear description of SGML/XML comments, but it seems that
558 ;; the only reliable ones are <!-- ... --> although it's not clear what
559 ;; "..." can contain. It used to accept -- ... -- as well, but that was
560 ;; apparently a mistake.
561 (setq-local comment-start-skip "<!--[ \t]*")
562 (setq-local comment-end-skip "[ \t]*--[ \t\n]*>")
563 ;; This definition has an HTML leaning but probably fits well for other modes.
564 (setq imenu-generic-expression
565 `((nil
566 ,(concat "<!\\(element\\|entity\\)[ \t\n]+%?[ \t\n]*\\("
567 sgml-name-re "\\)")
569 ("Id"
570 ,(concat "<[^>]+[ \t\n]+[Ii][Dd]=\\(['\"]"
571 (if sgml-xml-mode "" "?")
572 "\\)\\(" sgml-name-re "\\)\\1")
574 ("Name"
575 ,(concat "<[^>]+[ \t\n]+[Nn][Aa][Mm][Ee]=\\(['\"]"
576 (if sgml-xml-mode "" "?")
577 "\\)\\(" sgml-name-re "\\)\\1")
578 2))))
580 (defun sgml-comment-indent ()
581 (if (looking-at "--") comment-column 0))
583 (defun sgml-slash (arg)
584 "Insert ARG slash characters.
585 Behaves electrically if `sgml-quick-keys' is non-nil."
586 (interactive "p")
587 (cond
588 ((not (and (eq (char-before) ?<) (= arg 1)))
589 (sgml-slash-matching arg))
590 ((eq sgml-quick-keys 'indent)
591 (insert-char ?/ 1)
592 (indent-according-to-mode))
593 ((eq sgml-quick-keys 'close)
594 (delete-char -1)
595 (sgml-close-tag))
597 (sgml-slash-matching arg))))
599 (defun sgml-slash-matching (arg)
600 "Insert `/' and display any previous matching `/'.
601 Two `/'s are treated as matching if the first `/' ends a net-enabling
602 start tag, and the second `/' is the corresponding null end tag."
603 (interactive "p")
604 (insert-char ?/ arg)
605 (if (> arg 0)
606 (let ((oldpos (point))
607 (blinkpos)
608 (level 0))
609 (save-excursion
610 (save-restriction
611 (if sgml-slash-distance
612 (narrow-to-region (max (point-min)
613 (- (point) sgml-slash-distance))
614 oldpos))
615 (if (and (re-search-backward sgml-start-tag-regex (point-min) t)
616 (eq (match-end 0) (1- oldpos)))
618 (goto-char (1- oldpos))
619 (while (and (not blinkpos)
620 (search-backward "/" (point-min) t))
621 (let ((tagend (save-excursion
622 (if (re-search-backward sgml-start-tag-regex
623 (point-min) t)
624 (match-end 0)
625 nil))))
626 (if (eq tagend (point))
627 (if (eq level 0)
628 (setq blinkpos (point))
629 (setq level (1- level)))
630 (setq level (1+ level)))))))
631 (when blinkpos
632 (goto-char blinkpos)
633 (if (pos-visible-in-window-p)
634 (sit-for 1)
635 (message "Matches %s"
636 (buffer-substring (line-beginning-position)
637 (1+ blinkpos)))))))))
639 ;; Why doesn't this use the iso-cvt table or, preferably, generate the
640 ;; inverse of the extensive table in the SGML Quail input method? -- fx
641 ;; I guess that's moot since it only works with Latin-1 anyhow.
642 (defun sgml-name-char (&optional char)
643 "Insert a symbolic character name according to `sgml-char-names'.
644 Non-ASCII chars may be inserted either with the meta key, as in M-SPC for
645 no-break space or M-- for a soft hyphen; or via an input method or
646 encoded keyboard operation."
647 (interactive "*")
648 (insert ?&)
649 (or char
650 (setq char (read-quoted-char "Enter char or octal number")))
651 (delete-char -1)
652 (insert char)
653 (undo-boundary)
654 (sgml-namify-char))
656 (defun sgml-namify-char ()
657 "Change the char before point into its `&name;' equivalent.
658 Uses `sgml-char-names'."
659 (interactive)
660 (let* ((char (char-before))
661 (name
662 (cond
663 ((null char) (error "No char before point"))
664 ((< char 256) (or (aref sgml-char-names char) char))
665 ((aref sgml-char-names-table char))
666 ((encode-char char 'ucs)))))
667 (if (not name)
668 (error "Don't know the name of `%c'" char)
669 (delete-char -1)
670 (insert (format (if (numberp name) "&#%d;" "&%s;") name)))))
672 (defun sgml-name-self ()
673 "Insert a symbolic character name according to `sgml-char-names'."
674 (interactive "*")
675 (sgml-name-char last-command-event))
677 (defun sgml-maybe-name-self ()
678 "Insert a symbolic character name according to `sgml-char-names'."
679 (interactive "*")
680 (if sgml-name-8bit-mode
681 (sgml-name-char last-command-event)
682 (self-insert-command 1)))
684 (defun sgml-name-8bit-mode ()
685 "Toggle whether to insert named entities instead of non-ASCII characters.
686 This only works for Latin-1 input."
687 (interactive)
688 (setq sgml-name-8bit-mode (not sgml-name-8bit-mode))
689 (message "sgml name entity mode is now %s"
690 (if sgml-name-8bit-mode "ON" "OFF")))
692 ;; When an element of a skeleton is a string "str", it is passed
693 ;; through `skeleton-transformation-function' and inserted.
694 ;; If "str" is to be inserted literally, one should obtain it as
695 ;; the return value of a function, e.g. (identity "str").
697 (defvar sgml-tag-last nil)
698 (defvar sgml-tag-history nil)
699 (define-skeleton sgml-tag
700 "Prompt for a tag and insert it, optionally with attributes.
701 Completion and configuration are done according to `sgml-tag-alist'.
702 If you like tags and attributes in uppercase, customize
703 `sgml-transformation-function' to `upcase'."
704 (funcall (or skeleton-transformation-function 'identity)
705 (setq sgml-tag-last
706 (completing-read
707 (if (> (length sgml-tag-last) 0)
708 (format "Tag (default %s): " sgml-tag-last)
709 "Tag: ")
710 sgml-tag-alist nil nil nil 'sgml-tag-history sgml-tag-last)))
711 ?< str |
712 (("") -1 '(undo-boundary) (identity "&lt;")) | ; see comment above
713 `(("") '(setq v2 (sgml-attributes ,str t)) ?>
714 (cond
715 ((string= "![" ,str)
716 (backward-char)
717 '(("") " [ " _ " ]]"))
718 ((and (eq v2 t) sgml-xml-mode (member ,str sgml-empty-tags))
719 '(("") -1 " />"))
720 ((or (and (eq v2 t) (not sgml-xml-mode)) (string-match "^[/!?]" ,str))
721 nil)
722 ((symbolp v2)
723 ;; Make sure we don't fall into an infinite loop.
724 ;; For xhtml's `tr' tag, we should maybe use \n instead.
725 (if (eq v2 t) (setq v2 nil))
726 ;; We use `identity' to prevent skeleton from passing
727 ;; `str' through `skeleton-transformation-function' a second time.
728 '(("") v2 _ v2 "</" (identity ',str) ?> >))
729 ((eq (car v2) t)
730 (cons '("") (cdr v2)))
732 (append '(("") (car v2))
733 (cdr v2)
734 '(resume: (car v2) _ "</" (identity ',str) ?> >))))))
736 (autoload 'skeleton-read "skeleton")
738 (defun sgml-attributes (tag &optional quiet)
739 "When at top level of a tag, interactively insert attributes.
741 Completion and configuration of TAG are done according to `sgml-tag-alist'.
742 If QUIET, do not print a message when there are no attributes for TAG."
743 (interactive (list (save-excursion (sgml-beginning-of-tag t))))
744 (or (stringp tag) (error "Wrong context for adding attribute"))
745 (if tag
746 (let ((completion-ignore-case t)
747 (alist (cdr (assoc (downcase tag) sgml-tag-alist)))
748 car attribute i)
749 (if (or (symbolp (car alist))
750 (symbolp (car (car alist))))
751 (setq car (car alist)
752 alist (cdr alist)))
753 (or quiet
754 (message "No attributes configured."))
755 (if (stringp (car alist))
756 (progn
757 (insert (if (eq (preceding-char) ?\s) "" ?\s)
758 (funcall skeleton-transformation-function (car alist)))
759 (sgml-value alist))
760 (setq i (length alist))
761 (while (> i 0)
762 (insert ?\s)
763 (insert (funcall skeleton-transformation-function
764 (setq attribute
765 (skeleton-read (lambda ()
766 (completing-read
767 "Attribute: "
768 alist))))))
769 (if (string= "" attribute)
770 (setq i 0)
771 (sgml-value (assoc (downcase attribute) alist))
772 (setq i (1- i))))
773 (if (eq (preceding-char) ?\s)
774 (delete-char -1)))
775 car)))
777 (defun sgml-auto-attributes (arg)
778 "Self insert the character typed; at top level of tag, prompt for attributes.
779 With prefix argument, only self insert."
780 (interactive "*P")
781 (let ((point (point))
782 tag)
783 (if (or arg
784 (not sgml-tag-alist) ; no message when nothing configured
785 (symbolp (setq tag (save-excursion (sgml-beginning-of-tag t))))
786 (eq (aref tag 0) ?/))
787 (self-insert-command (prefix-numeric-value arg))
788 (sgml-attributes tag)
789 (setq last-command-event ?\s)
790 (or (> (point) point)
791 (self-insert-command 1)))))
793 (defun sgml-tag-help (&optional tag)
794 "Display description of tag TAG. If TAG is omitted, use the tag at point."
795 (interactive
796 (list (let ((def (save-excursion
797 (if (eq (following-char) ?<) (forward-char))
798 (sgml-beginning-of-tag))))
799 (completing-read (if def
800 (format "Tag (default %s): " def)
801 "Tag: ")
802 sgml-tag-alist nil nil nil
803 'sgml-tag-history def))))
804 (or (and tag (> (length tag) 0))
805 (save-excursion
806 (if (eq (following-char) ?<)
807 (forward-char))
808 (setq tag (sgml-beginning-of-tag))))
809 (or (stringp tag)
810 (error "No tag selected"))
811 (setq tag (downcase tag))
812 (message "%s"
813 (or (cdr (assoc (downcase tag) sgml-tag-help))
814 (and (eq (aref tag 0) ?/)
815 (cdr (assoc (downcase (substring tag 1)) sgml-tag-help)))
816 "No description available")))
818 (defun sgml-maybe-end-tag (&optional arg)
819 "Name self unless in position to end a tag or a prefix ARG is given."
820 (interactive "P")
821 (if (or arg (eq (car (sgml-lexical-context)) 'tag))
822 (self-insert-command (prefix-numeric-value arg))
823 (sgml-name-self)))
825 (defun sgml-skip-tag-backward (arg)
826 "Skip to beginning of tag or matching opening tag if present.
827 With prefix argument ARG, repeat this ARG times.
828 Return non-nil if we skipped over matched tags."
829 (interactive "p")
830 ;; FIXME: use sgml-get-context or something similar.
831 (let ((return t))
832 (while (>= arg 1)
833 (search-backward "<" nil t)
834 (if (looking-at "</\\([^ \n\t>]+\\)")
835 ;; end tag, skip any nested pairs
836 (let ((case-fold-search t)
837 (re (concat "</?" (regexp-quote (match-string 1))
838 ;; Ignore empty tags like <foo/>.
839 "\\([^>]*[^/>]\\)?>")))
840 (while (and (re-search-backward re nil t)
841 (eq (char-after (1+ (point))) ?/))
842 (forward-char 1)
843 (sgml-skip-tag-backward 1)))
844 (setq return nil))
845 (setq arg (1- arg)))
846 return))
848 (defun sgml-forward-sexp (n)
849 ;; This function is needed in major-modes such as nxml-mode where
850 ;; forward-sexp-function is used to give a more dwimish behavior to
851 ;; the `forward-sexp' command.
852 ;; Without it, we can end up with backtraces like:
853 ;; "get-text-property" (0xffffc0f0)
854 ;; "nxml-token-after" (0xffffc2ac)
855 ;; "nxml-forward-single-balanced-item" (0xffffc46c)
856 ;; "nxml-forward-balanced-item" (0xffffc61c)
857 ;; "forward-sexp" (0xffffc7f8)
858 ;; "sgml-parse-tag-backward" (0xffffc9c8)
859 ;; "sgml-lexical-context" (0xffffcba8)
860 ;; "sgml-mode-flyspell-verify" (0xffffcd74)
861 ;; "flyspell-word" (0xffffcf3c)
862 ;; "flyspell-post-command-hook" (0xffffd108)
863 ;; FIXME: should we also set the sgml-tag-syntax-table?
864 (let ((forward-sexp-function nil))
865 (forward-sexp n)))
867 (defvar sgml-electric-tag-pair-overlays nil)
868 (defvar sgml-electric-tag-pair-timer nil)
870 (defun sgml-electric-tag-pair-before-change-function (_beg end)
871 (condition-case err
872 (save-excursion
873 (goto-char end)
874 (skip-chars-backward "[:alnum:]-_.:")
875 (if (and ;; (<= (point) beg) ; This poses problems for downcase-word.
876 (or (eq (char-before) ?<)
877 (and (eq (char-before) ?/)
878 (eq (char-before (1- (point))) ?<)))
879 (null (get-char-property (point) 'text-clones)))
880 (let* ((endp (eq (char-before) ?/))
881 (cl-start (point))
882 (cl-end (progn (skip-chars-forward "[:alnum:]-_.:") (point)))
883 (match
884 (if endp
885 (when (sgml-skip-tag-backward 1) (forward-char 1) t)
886 (with-syntax-table sgml-tag-syntax-table
887 (let ((forward-sexp-function nil))
888 (up-list -1)
889 (when (sgml-skip-tag-forward 1)
890 (backward-sexp 1)
891 (forward-char 2)
892 t)))))
893 (clones (get-char-property (point) 'text-clones)))
894 (when (and match
895 (/= cl-end cl-start)
896 (equal (buffer-substring cl-start cl-end)
897 (buffer-substring (point)
898 (save-excursion
899 (skip-chars-forward "[:alnum:]-_.:")
900 (point))))
901 (or (not endp) (eq (char-after cl-end) ?>)))
902 (when clones
903 (message "sgml-electric-tag-pair-before-change-function: deleting old OLs")
904 (mapc 'delete-overlay clones))
905 (message "sgml-electric-tag-pair-before-change-function: new clone")
906 (text-clone-create cl-start cl-end 'spread "[[:alnum:]-_.:]+")
907 (setq sgml-electric-tag-pair-overlays
908 (append (get-char-property (point) 'text-clones)
909 sgml-electric-tag-pair-overlays))))))
910 (scan-error nil)
911 (error (message "Error in sgml-electric-pair-mode: %s" err))))
913 (defun sgml-electric-tag-pair-flush-overlays ()
914 (while sgml-electric-tag-pair-overlays
915 (delete-overlay (pop sgml-electric-tag-pair-overlays))))
917 (define-minor-mode sgml-electric-tag-pair-mode
918 "Toggle SGML Electric Tag Pair mode.
919 With a prefix argument ARG, enable the mode if ARG is positive,
920 and disable it otherwise. If called from Lisp, enable the mode
921 if ARG is omitted or nil.
923 SGML Electric Tag Pair mode is a buffer-local minor mode for use
924 with `sgml-mode' and related major modes. When enabled, editing
925 an opening markup tag automatically updates the closing tag."
926 :lighter "/e"
927 (if sgml-electric-tag-pair-mode
928 (progn
929 (add-hook 'before-change-functions
930 'sgml-electric-tag-pair-before-change-function
931 nil t)
932 (unless sgml-electric-tag-pair-timer
933 (setq sgml-electric-tag-pair-timer
934 (run-with-idle-timer 5 'repeat 'sgml-electric-tag-pair-flush-overlays))))
935 (remove-hook 'before-change-functions
936 'sgml-electric-tag-pair-before-change-function
938 ;; We leave the timer running for other buffers.
942 (defun sgml-skip-tag-forward (arg)
943 "Skip to end of tag or matching closing tag if present.
944 With prefix argument ARG, repeat this ARG times.
945 Return t if after a closing tag."
946 (interactive "p")
947 ;; FIXME: Use sgml-get-context or something similar.
948 ;; It currently might jump to an unrelated </P> if the <P>
949 ;; we're skipping has no matching </P>.
950 (let ((return t))
951 (with-syntax-table sgml-tag-syntax-table
952 (while (>= arg 1)
953 (skip-chars-forward "^<>")
954 (if (eq (following-char) ?>)
955 (up-list -1))
956 (if (looking-at "<\\([^/ \n\t>]+\\)\\([^>]*[^/>]\\)?>")
957 ;; start tag, skip any nested same pairs _and_ closing tag
958 (let ((case-fold-search t)
959 (re (concat "</?" (regexp-quote (match-string 1))
960 ;; Ignore empty tags like <foo/>.
961 "\\([^>]*[^/>]\\)?>"))
962 point close)
963 (forward-list 1)
964 (setq point (point))
965 ;; FIXME: This re-search-forward will mistakenly match
966 ;; tag-like text inside attributes.
967 (while (and (re-search-forward re nil t)
968 (not (setq close
969 (eq (char-after (1+ (match-beginning 0))) ?/)))
970 (goto-char (match-beginning 0))
971 (sgml-skip-tag-forward 1))
972 (setq close nil))
973 (unless close
974 (goto-char point)
975 (setq return nil)))
976 (forward-list 1))
977 (setq arg (1- arg)))
978 return)))
980 (defsubst sgml-looking-back-at (str)
981 "Return t if the test before point matches STR."
982 (let ((start (- (point) (length str))))
983 (and (>= start (point-min))
984 (equal str (buffer-substring-no-properties start (point))))))
986 (defun sgml-delete-tag (arg)
987 ;; FIXME: Should be called sgml-kill-tag or should not touch the kill-ring.
988 "Delete tag on or after cursor, and matching closing or opening tag.
989 With prefix argument ARG, repeat this ARG times."
990 (interactive "p")
991 (while (>= arg 1)
992 (save-excursion
993 (let* (close open)
994 (if (looking-at "[ \t\n]*<")
995 ;; just before tag
996 (if (eq (char-after (match-end 0)) ?/)
997 ;; closing tag
998 (progn
999 (setq close (point))
1000 (goto-char (match-end 0))))
1001 ;; on tag?
1002 (or (save-excursion (setq close (sgml-beginning-of-tag)
1003 close (and (stringp close)
1004 (eq (aref close 0) ?/)
1005 (point))))
1006 ;; not on closing tag
1007 (let ((point (point)))
1008 (sgml-skip-tag-backward 1)
1009 (if (or (not (eq (following-char) ?<))
1010 (save-excursion
1011 (forward-list 1)
1012 (<= (point) point)))
1013 (error "Not on or before tag")))))
1014 (if close
1015 (progn
1016 (sgml-skip-tag-backward 1)
1017 (setq open (point))
1018 (goto-char close)
1019 (kill-sexp 1))
1020 (setq open (point))
1021 (when (and (sgml-skip-tag-forward 1)
1022 (not (sgml-looking-back-at "/>")))
1023 (kill-sexp -1)))
1024 ;; Delete any resulting empty line. If we didn't kill-sexp,
1025 ;; this *should* do nothing, because we're right after the tag.
1026 (if (progn (forward-line 0) (looking-at "\\(?:[ \t]*$\\)\n?"))
1027 (delete-region (match-beginning 0) (match-end 0)))
1028 (goto-char open)
1029 (kill-sexp 1)
1030 (if (progn (forward-line 0) (looking-at "\\(?:[ \t]*$\\)\n?"))
1031 (delete-region (match-beginning 0) (match-end 0)))))
1032 (setq arg (1- arg))))
1035 ;; Put read-only last to enable setting this even when read-only enabled.
1036 (or (get 'sgml-tag 'invisible)
1037 (setplist 'sgml-tag
1038 (append '(invisible t
1039 cursor-sensor-functions (sgml-cursor-sensor)
1040 rear-nonsticky t
1041 read-only t)
1042 (symbol-plist 'sgml-tag))))
1044 (defun sgml-tags-invisible (arg)
1045 "Toggle visibility of existing tags."
1046 (interactive "P")
1047 (let ((inhibit-read-only t)
1048 string)
1049 (with-silent-modifications
1050 (save-excursion
1051 (goto-char (point-min))
1052 (if (setq-local sgml-tags-invisible
1053 (if arg
1054 (>= (prefix-numeric-value arg) 0)
1055 (not sgml-tags-invisible)))
1056 (while (re-search-forward sgml-tag-name-re nil t)
1057 (setq string
1058 (cdr (assq (intern-soft (downcase (match-string 1)))
1059 sgml-display-text)))
1060 (goto-char (match-beginning 0))
1061 (and (stringp string)
1062 (not (overlays-at (point)))
1063 (let ((ol (make-overlay (point) (match-beginning 1))))
1064 (overlay-put ol 'before-string string)
1065 (overlay-put ol 'sgml-tag t)))
1066 (put-text-property (point)
1067 (progn (forward-list) (point))
1068 'category 'sgml-tag))
1069 (let ((pos (point-min)))
1070 (while (< (setq pos (next-overlay-change pos)) (point-max))
1071 (dolist (ol (overlays-at pos))
1072 (if (overlay-get ol 'sgml-tag)
1073 (delete-overlay ol)))))
1074 (remove-text-properties (point-min) (point-max) '(category nil)))))
1075 (cursor-sensor-mode (if sgml-tags-invisible 1 -1))
1076 (run-hooks 'sgml-tags-invisible-hook)
1077 (message "")))
1079 (defun sgml-cursor-sensor (window x dir)
1080 ;; Show preceding or following hidden tag, depending of cursor direction (and
1081 ;; `dir' is not the direction in this sense).
1082 (when (eq dir 'entered)
1083 (ignore-errors
1084 (let* ((y (window-point window))
1085 (otherend
1086 (save-excursion
1087 (goto-char y)
1088 (cond
1089 ((and (eq (char-before) ?>)
1090 (or (not (eq (char-after) ?<))
1091 (> x y)))
1092 (sgml-forward-sexp -1))
1093 ((eq (char-after y) ?<)
1094 (sgml-forward-sexp 1)))
1095 (point))))
1096 (message "Invisible tag: %s"
1097 ;; Strip properties, otherwise, the text is invisible.
1098 (buffer-substring-no-properties
1099 y otherend))))))
1102 (defun sgml-validate (command)
1103 "Validate an SGML document.
1104 Runs COMMAND, a shell command, in a separate process asynchronously
1105 with output going to the buffer `*compilation*'.
1106 You can then use the command \\[next-error] to find the next error message
1107 and move to the line in the SGML document that caused it."
1108 (interactive
1109 (list (read-string "Validate command: "
1110 (or sgml-saved-validate-command
1111 (concat sgml-validate-command
1113 (shell-quote-argument
1114 (let ((name (buffer-file-name)))
1115 (and name
1116 (file-name-nondirectory name)))))))))
1117 (setq sgml-saved-validate-command command)
1118 (save-some-buffers (not compilation-ask-about-save) nil)
1119 (compilation-start command))
1121 (defsubst sgml-at-indentation-p ()
1122 "Return true if point is at the first non-whitespace character on the line."
1123 (save-excursion
1124 (skip-chars-backward " \t")
1125 (bolp)))
1127 (defun sgml-lexical-context (&optional limit)
1128 "Return the lexical context at point as (TYPE . START).
1129 START is the location of the start of the lexical element.
1130 TYPE is one of `string', `comment', `tag', `cdata', `pi', or `text'.
1132 Optional argument LIMIT is the position to start parsing from.
1133 If nil, start from a preceding tag at indentation."
1134 (save-excursion
1135 (let ((pos (point))
1136 text-start state)
1137 (if limit
1138 (goto-char limit)
1139 ;; Skip tags backwards until we find one at indentation
1140 (while (and (ignore-errors (sgml-parse-tag-backward))
1141 (not (sgml-at-indentation-p)))))
1142 (with-syntax-table sgml-tag-syntax-table
1143 (while (< (point) pos)
1144 ;; When entering this loop we're inside text.
1145 (setq text-start (point))
1146 (skip-chars-forward "^<" pos)
1147 (setq state
1148 (cond
1149 ((= (point) pos)
1150 ;; We got to the end without seeing a tag.
1151 nil)
1152 ((looking-at "<!\\[[A-Z]+\\[")
1153 ;; We've found a CDATA section or similar.
1154 (let ((cdata-start (point)))
1155 (unless (search-forward "]]>" pos 'move)
1156 (list 0 nil nil 'cdata nil nil nil nil cdata-start))))
1157 ((looking-at comment-start-skip)
1158 ;; parse-partial-sexp doesn't handle <!-- comments -->,
1159 ;; or only if ?- is in sgml-specials, so match explicitly
1160 (let ((start (point)))
1161 (unless (re-search-forward comment-end-skip pos 'move)
1162 (list 0 nil nil nil t nil nil nil start))))
1163 ((and sgml-xml-mode (looking-at "<\\?"))
1164 ;; Processing Instructions.
1165 ;; In SGML, it's basically a normal tag of the form
1166 ;; <?NAME ...> but in XML, it takes the form <? ... ?>.
1167 (let ((pi-start (point)))
1168 (unless (search-forward "?>" pos 'move)
1169 (list 0 nil nil 'pi nil nil nil nil pi-start))))
1171 ;; We've reached a tag. Parse it.
1172 ;; FIXME: Handle net-enabling start-tags
1173 (parse-partial-sexp (point) pos 0))))))
1174 (cond
1175 ((memq (nth 3 state) '(cdata pi)) (cons (nth 3 state) (nth 8 state)))
1176 ((nth 3 state) (cons 'string (nth 8 state)))
1177 ((nth 4 state) (cons 'comment (nth 8 state)))
1178 ((and state (> (nth 0 state) 0)) (cons 'tag (nth 1 state)))
1179 (t (cons 'text text-start))))))
1181 (defun sgml-beginning-of-tag (&optional only-immediate)
1182 "Skip to beginning of tag and return its name.
1183 If this can't be done, return nil."
1184 (let ((context (sgml-lexical-context)))
1185 (if (eq (car context) 'tag)
1186 (progn
1187 (goto-char (cdr context))
1188 (when (looking-at sgml-tag-name-re)
1189 (match-string-no-properties 1)))
1190 (if only-immediate nil
1191 (when (not (eq (car context) 'text))
1192 (goto-char (cdr context))
1193 (sgml-beginning-of-tag t))))))
1195 (defun sgml-value (alist)
1196 "Interactively insert value taken from attribute-rule ALIST.
1197 See `sgml-tag-alist' for info about attribute rules."
1198 (setq alist (cdr alist))
1199 (if (stringp (car alist))
1200 (insert "=\"" (car alist) ?\")
1201 (if (and (eq (car alist) t) (not sgml-xml-mode))
1202 (when (cdr alist)
1203 (insert "=\"")
1204 (setq alist (skeleton-read (lambda ()
1205 (completing-read
1206 "Value: " (cdr alist)))))
1207 (if (string< "" alist)
1208 (insert alist ?\")
1209 (delete-char -2)))
1210 (insert "=\"")
1211 (if (cdr alist)
1212 (insert (skeleton-read (lambda ()
1213 (completing-read "Value: " alist))))
1214 (when (null alist)
1215 (insert (skeleton-read '(read-string "Value: ")))))
1216 (insert ?\"))))
1218 (defun sgml-quote (start end &optional unquotep)
1219 "Quote SGML text in region START ... END.
1220 Only &, < and > are quoted, the rest is left untouched.
1221 With prefix argument UNQUOTEP, unquote the region."
1222 (interactive "r\nP")
1223 (save-restriction
1224 (narrow-to-region start end)
1225 (goto-char (point-min))
1226 (if unquotep
1227 ;; FIXME: We should unquote other named character references as well.
1228 (while (re-search-forward
1229 "\\(&\\(amp\\|\\(l\\|\\(g\\)\\)t\\)\\)[][<>&;\n\t \"%!'(),/=?]"
1230 nil t)
1231 (replace-match (if (match-end 4) ">" (if (match-end 3) "<" "&")) t t
1232 nil (if (eq (char-before (match-end 0)) ?\;) 0 1)))
1233 (while (re-search-forward "[&<>]" nil t)
1234 (replace-match (cdr (assq (char-before) '((?& . "&amp;")
1235 (?< . "&lt;")
1236 (?> . "&gt;"))))
1237 t t)))))
1239 (defun sgml-pretty-print (beg end)
1240 "Simple-minded pretty printer for SGML.
1241 Re-indents the code and inserts newlines between BEG and END.
1242 You might want to turn on `auto-fill-mode' to get better results."
1243 ;; TODO:
1244 ;; - insert newline between some start-tag and text.
1245 ;; - don't insert newline in front of some end-tags.
1246 (interactive "r")
1247 (save-excursion
1248 (if (< beg end)
1249 (goto-char beg)
1250 (goto-char end)
1251 (setq end beg)
1252 (setq beg (point)))
1253 ;; Don't use narrowing because it screws up auto-indent.
1254 (setq end (copy-marker end t))
1255 (with-syntax-table sgml-tag-syntax-table
1256 (while (re-search-forward "<" end t)
1257 (goto-char (match-beginning 0))
1258 (unless (or ;;(looking-at "</")
1259 (progn (skip-chars-backward " \t") (bolp)))
1260 (reindent-then-newline-and-indent))
1261 (sgml-forward-sexp 1)))
1262 ;; (indent-region beg end)
1266 ;; Parsing
1268 (cl-defstruct (sgml-tag
1269 (:constructor sgml-make-tag (type start end name)))
1270 type start end name)
1272 (defsubst sgml-parse-tag-name ()
1273 "Skip past a tag-name, and return the name."
1274 (buffer-substring-no-properties
1275 (point) (progn (skip-syntax-forward "w_") (point))))
1277 (defun sgml-tag-text-p (start end)
1278 "Return non-nil if text between START and END is a tag.
1279 Checks among other things that the tag does not contain spurious
1280 unquoted < or > chars inside, which would indicate that it
1281 really isn't a tag after all."
1282 (save-excursion
1283 (with-syntax-table sgml-tag-syntax-table
1284 (let ((pps (parse-partial-sexp start end 2)))
1285 (and (= (nth 0 pps) 0))))))
1287 (defun sgml-parse-tag-backward (&optional limit)
1288 "Parse an SGML tag backward, and return information about the tag.
1289 Assume that parsing starts from within a textual context.
1290 Leave point at the beginning of the tag."
1291 (catch 'found
1292 (let (tag-type tag-start tag-end name)
1293 (or (re-search-backward "[<>]" limit 'move)
1294 (error "No tag found"))
1295 (when (eq (char-after) ?<)
1296 ;; Oops!! Looks like we were not in a textual context after all!.
1297 ;; Let's try to recover.
1298 ;; Remember the tag-start so we don't need to look for it later.
1299 ;; This is not just an optimization but also makes sure we don't get
1300 ;; stuck in infloops in cases where "looking back for <" would not go
1301 ;; back far enough.
1302 (setq tag-start (point))
1303 (with-syntax-table sgml-tag-syntax-table
1304 (let ((pos (point)))
1305 (condition-case nil
1306 ;; FIXME: This does not correctly skip over PI an CDATA tags.
1307 (sgml-forward-sexp 1)
1308 (scan-error
1309 ;; This < seems to be just a spurious one, let's ignore it.
1310 (goto-char pos)
1311 (throw 'found (sgml-parse-tag-backward limit))))
1312 ;; Check it is really a tag, without any extra < or > inside.
1313 (unless (sgml-tag-text-p pos (point))
1314 (goto-char pos)
1315 (throw 'found (sgml-parse-tag-backward limit)))
1316 (forward-char -1))))
1317 (setq tag-end (1+ (point)))
1318 (cond
1319 ((sgml-looking-back-at "--") ; comment
1320 (setq tag-type 'comment
1321 tag-start (or tag-start (search-backward "<!--" nil t))))
1322 ((sgml-looking-back-at "]]") ; cdata
1323 (setq tag-type 'cdata
1324 tag-start (or tag-start
1325 (re-search-backward "<!\\[[A-Z]+\\[" nil t))))
1326 ((sgml-looking-back-at "?") ; XML processing-instruction
1327 (setq tag-type 'pi
1328 ;; IIUC: SGML processing instructions take the form <?foo ...>
1329 ;; i.e. a "normal" tag, handled below. In XML this is changed
1330 ;; to <?foo ... ?> where "..." can contain < and > and even <?
1331 ;; but not ?>. This means that when parsing backward, there's
1332 ;; no easy way to make sure that we find the real beginning of
1333 ;; the PI.
1334 tag-start (or tag-start (search-backward "<?" nil t))))
1336 (unless tag-start
1337 (setq tag-start
1338 (with-syntax-table sgml-tag-syntax-table
1339 (goto-char tag-end)
1340 (condition-case nil
1341 (sgml-forward-sexp -1)
1342 (scan-error
1343 ;; This > isn't really the end of a tag. Skip it.
1344 (goto-char (1- tag-end))
1345 (throw 'found (sgml-parse-tag-backward limit))))
1346 (point))))
1347 (goto-char (1+ tag-start))
1348 (pcase (char-after)
1349 (?! (setq tag-type 'decl)) ; declaration
1350 (?? (setq tag-type 'pi)) ; processing-instruction
1351 (?% (setq tag-type 'jsp)) ; JSP tags
1352 (?/ ; close-tag
1353 (forward-char 1)
1354 (setq tag-type 'close
1355 name (sgml-parse-tag-name)))
1356 (_ ; open or empty tag
1357 (setq tag-type 'open
1358 name (sgml-parse-tag-name))
1359 (if (or (eq ?/ (char-before (- tag-end 1)))
1360 (sgml-empty-tag-p name))
1361 (setq tag-type 'empty))))))
1362 (goto-char tag-start)
1363 (sgml-make-tag tag-type tag-start tag-end name))))
1365 (defun sgml-get-context (&optional until)
1366 "Determine the context of the current position.
1367 By default, parse until we find a start-tag as the first thing on a line.
1368 If UNTIL is `empty', return even if the context is empty (i.e.
1369 we just skipped over some element and got to a beginning of line).
1371 The context is a list of tag-info structures. The last one is the tag
1372 immediately enclosing the current position.
1374 Point is assumed to be outside of any tag. If we discover that it's
1375 not the case, the first tag returned is the one inside which we are."
1376 (let ((here (point))
1377 (stack nil)
1378 (ignore nil)
1379 (context nil)
1380 tag-info)
1381 ;; CONTEXT keeps track of the tag-stack
1382 ;; STACK keeps track of the end tags we've seen (and thus the start-tags
1383 ;; we'll have to ignore) when skipping over matching open..close pairs.
1384 ;; IGNORE is a list of tags that can be ignored because they have been
1385 ;; closed implicitly.
1386 (skip-chars-backward " \t\n") ; Make sure we're not at indentation.
1387 (while
1388 (and (not (eq until 'now))
1389 (or stack
1390 (not (if until (eq until 'empty) context))
1391 (not (sgml-at-indentation-p))
1392 (and context
1393 (/= (point) (sgml-tag-start (car context)))
1394 (sgml-unclosed-tag-p (sgml-tag-name (car context)))))
1395 (setq tag-info (ignore-errors (sgml-parse-tag-backward))))
1397 ;; This tag may enclose things we thought were tags. If so,
1398 ;; discard them.
1399 (while (and context
1400 (> (sgml-tag-end tag-info)
1401 (sgml-tag-end (car context))))
1402 (setq context (cdr context)))
1404 (cond
1405 ((> (sgml-tag-end tag-info) here)
1406 ;; Oops!! Looks like we were not outside of any tag, after all.
1407 (push tag-info context)
1408 (setq until 'now))
1410 ;; start-tag
1411 ((eq (sgml-tag-type tag-info) 'open)
1412 (cond
1413 ((null stack)
1414 (if (assoc-string (sgml-tag-name tag-info) ignore t)
1415 ;; There was an implicit end-tag.
1417 (push tag-info context)
1418 ;; We're changing context so the tags implicitly closed inside
1419 ;; the previous context aren't implicitly closed here any more.
1420 ;; [ Well, actually it depends, but we don't have the info about
1421 ;; when it doesn't and when it does. --Stef ]
1422 (setq ignore nil)))
1423 ((eq t (compare-strings (sgml-tag-name tag-info) nil nil
1424 (car stack) nil nil t))
1425 (setq stack (cdr stack)))
1427 ;; The open and close tags don't match.
1428 (if (not sgml-xml-mode)
1429 (unless (sgml-unclosed-tag-p (sgml-tag-name tag-info))
1430 (message "Unclosed tag <%s>" (sgml-tag-name tag-info))
1431 (let ((tmp stack))
1432 ;; We could just assume that the tag is simply not closed
1433 ;; but it's a bad assumption when tags *are* closed but
1434 ;; not properly nested.
1435 (while (and (cdr tmp)
1436 (not (eq t (compare-strings
1437 (sgml-tag-name tag-info) nil nil
1438 (cadr tmp) nil nil t))))
1439 (setq tmp (cdr tmp)))
1440 (if (cdr tmp) (setcdr tmp (cddr tmp)))))
1441 (message "Unmatched tags <%s> and </%s>"
1442 (sgml-tag-name tag-info) (pop stack)))))
1444 (if (and (null stack) (sgml-unclosed-tag-p (sgml-tag-name tag-info)))
1445 ;; This is a top-level open of an implicitly closed tag, so any
1446 ;; occurrence of such an open tag at the same level can be ignored
1447 ;; because it's been implicitly closed.
1448 (push (sgml-tag-name tag-info) ignore)))
1450 ;; end-tag
1451 ((eq (sgml-tag-type tag-info) 'close)
1452 (if (sgml-empty-tag-p (sgml-tag-name tag-info))
1453 (message "Spurious </%s>: empty tag" (sgml-tag-name tag-info))
1454 (push (sgml-tag-name tag-info) stack)))
1457 ;; return context
1458 context))
1460 (defun sgml-show-context (&optional full)
1461 "Display the current context.
1462 If FULL is non-nil, parse back to the beginning of the buffer."
1463 (interactive "P")
1464 (with-output-to-temp-buffer "*XML Context*"
1465 (save-excursion
1466 (let ((context (sgml-get-context)))
1467 (when full
1468 (let ((more nil))
1469 (while (setq more (sgml-get-context))
1470 (setq context (nconc more context)))))
1471 (pp context)))))
1474 ;; Editing shortcuts
1476 (defun sgml-close-tag ()
1477 "Close current element.
1478 Depending on context, inserts a matching close-tag, or closes
1479 the current start-tag or the current comment or the current cdata, ..."
1480 (interactive)
1481 (pcase (car (sgml-lexical-context))
1482 (`comment (insert " -->"))
1483 (`cdata (insert "]]>"))
1484 (`pi (insert " ?>"))
1485 (`jsp (insert " %>"))
1486 (`tag (insert " />"))
1487 (`text
1488 (let ((context (save-excursion (sgml-get-context))))
1489 (if context
1490 (progn
1491 (insert "</" (sgml-tag-name (car (last context))) ">")
1492 (indent-according-to-mode)))))
1494 (error "Nothing to close"))))
1496 (defun sgml-empty-tag-p (tag-name)
1497 "Return non-nil if TAG-NAME is an implicitly empty tag."
1498 (and (not sgml-xml-mode)
1499 (assoc-string tag-name sgml-empty-tags 'ignore-case)))
1501 (defun sgml-unclosed-tag-p (tag-name)
1502 "Return non-nil if TAG-NAME is a tag for which an end-tag is optional."
1503 (and (not sgml-xml-mode)
1504 (assoc-string tag-name sgml-unclosed-tags 'ignore-case)))
1507 (defun sgml-calculate-indent (&optional lcon)
1508 "Calculate the column to which this line should be indented.
1509 LCON is the lexical context, if any."
1510 (unless lcon (setq lcon (sgml-lexical-context)))
1512 ;; Indent comment-start markers inside <!-- just like comment-end markers.
1513 (if (and (eq (car lcon) 'tag)
1514 (looking-at "--")
1515 (save-excursion (goto-char (cdr lcon)) (looking-at "<!--")))
1516 (setq lcon (cons 'comment (+ (cdr lcon) 2))))
1518 (pcase (car lcon)
1520 (`string
1521 ;; Go back to previous non-empty line.
1522 (while (and (> (point) (cdr lcon))
1523 (zerop (forward-line -1))
1524 (looking-at "[ \t]*$")))
1525 (if (> (point) (cdr lcon))
1526 ;; Previous line is inside the string.
1527 (current-indentation)
1528 (goto-char (cdr lcon))
1529 (1+ (current-column))))
1531 (`comment
1532 (let ((mark (looking-at "--")))
1533 ;; Go back to previous non-empty line.
1534 (while (and (> (point) (cdr lcon))
1535 (zerop (forward-line -1))
1536 (or (looking-at "[ \t]*$")
1537 (if mark (not (looking-at "[ \t]*--"))))))
1538 (if (> (point) (cdr lcon))
1539 ;; Previous line is inside the comment.
1540 (skip-chars-forward " \t")
1541 (goto-char (cdr lcon))
1542 ;; Skip `<!' to get to the `--' with which we want to align.
1543 (search-forward "--")
1544 (goto-char (match-beginning 0)))
1545 (when (and (not mark) (looking-at "--"))
1546 (forward-char 2) (skip-chars-forward " \t"))
1547 (current-column)))
1549 ;; We don't know how to indent it. Let's be honest about it.
1550 (`cdata nil)
1551 ;; We don't know how to indent it. Let's be honest about it.
1552 (`pi nil)
1554 (`tag
1555 (goto-char (+ (cdr lcon) sgml-attribute-offset))
1556 (skip-chars-forward "^ \t\n") ;Skip tag name.
1557 (skip-chars-forward " \t")
1558 (if (not (eolp))
1559 (current-column)
1560 ;; This is the first attribute: indent.
1561 (goto-char (+ (cdr lcon) sgml-attribute-offset))
1562 (+ (current-column) sgml-basic-offset)))
1564 (`text
1565 (while (looking-at "</")
1566 (sgml-forward-sexp 1)
1567 (skip-chars-forward " \t"))
1568 (let* ((here (point))
1569 (unclosed (and ;; (not sgml-xml-mode)
1570 (looking-at sgml-tag-name-re)
1571 (assoc-string (match-string 1)
1572 sgml-unclosed-tags 'ignore-case)
1573 (match-string 1)))
1574 (context
1575 ;; If possible, align on the previous non-empty text line.
1576 ;; Otherwise, do a more serious parsing to find the
1577 ;; tag(s) relative to which we should be indenting.
1578 (if (and (not unclosed) (skip-chars-backward " \t")
1579 (< (skip-chars-backward " \t\n") 0)
1580 (back-to-indentation)
1581 (> (point) (cdr lcon)))
1583 (goto-char here)
1584 (nreverse (sgml-get-context (if unclosed nil 'empty)))))
1585 (there (point)))
1586 ;; Ignore previous unclosed start-tag in context.
1587 (while (and context unclosed
1588 (eq t (compare-strings
1589 (sgml-tag-name (car context)) nil nil
1590 unclosed nil nil t)))
1591 (setq context (cdr context)))
1592 ;; Indent to reflect nesting.
1593 (cond
1594 ;; If we were not in a text context after all, let's try again.
1595 ((and context (> (sgml-tag-end (car context)) here))
1596 (goto-char here)
1597 (sgml-calculate-indent
1598 (cons (if (memq (sgml-tag-type (car context)) '(comment cdata))
1599 (sgml-tag-type (car context)) 'tag)
1600 (sgml-tag-start (car context)))))
1601 ;; Align on the first element after the nearest open-tag, if any.
1602 ((and context
1603 (goto-char (sgml-tag-end (car context)))
1604 (skip-chars-forward " \t\n")
1605 (< (point) here) (sgml-at-indentation-p))
1606 (current-column))
1607 ;; ;; If the parsing failed, try to recover.
1608 ;; ((and (null context) (bobp)
1609 ;; (not (eq (char-after here) ?<)))
1610 ;; (goto-char here)
1611 ;; (if (and (looking-at "--[ \t\n]*>")
1612 ;; (re-search-backward "<!--" nil t))
1613 ;; ;; No wonder parsing failed: we're in a comment.
1614 ;; (sgml-calculate-indent (prog2 (goto-char (match-end 0))
1615 ;; (sgml-lexical-context)
1616 ;; (goto-char here)))
1617 ;; ;; We have no clue what's going on, let's be honest about it.
1618 ;; nil))
1619 ;; Otherwise, just follow the rules.
1621 (goto-char there)
1622 (+ (current-column)
1623 (* sgml-basic-offset (length context)))))))
1626 (error "Unrecognized context %s" (car lcon)))
1630 (defun sgml-indent-line ()
1631 "Indent the current line as SGML."
1632 (interactive)
1633 (let* ((savep (point))
1634 (indent-col
1635 (save-excursion
1636 (back-to-indentation)
1637 (if (>= (point) savep) (setq savep nil))
1638 (sgml-calculate-indent))))
1639 (if (null indent-col)
1640 'noindent
1641 (if savep
1642 (save-excursion (indent-line-to indent-col))
1643 (indent-line-to indent-col)))))
1645 (defun sgml-guess-indent ()
1646 "Guess an appropriate value for `sgml-basic-offset'.
1647 Base the guessed indentation level on the first indented tag in the buffer.
1648 Add this to `sgml-mode-hook' for convenience."
1649 (interactive)
1650 (save-excursion
1651 (goto-char (point-min))
1652 (if (re-search-forward "^\\([ \t]+\\)<" 500 'noerror)
1653 (progn
1654 (setq-local sgml-basic-offset (1- (current-column)))
1655 (message "Guessed sgml-basic-offset = %d"
1656 sgml-basic-offset)
1657 ))))
1659 (defun sgml-parse-dtd ()
1660 "Simplistic parse of the current buffer as a DTD.
1661 Currently just returns (EMPTY-TAGS UNCLOSED-TAGS)."
1662 (goto-char (point-min))
1663 (let ((empty nil)
1664 (unclosed nil))
1665 (while (re-search-forward "<!ELEMENT[ \t\n]+\\([^ \t\n]+\\)[ \t\n]+[-O][ \t\n]+\\([-O]\\)[ \t\n]+\\([^ \t\n]+\\)" nil t)
1666 (cond
1667 ((string= (match-string 3) "EMPTY")
1668 (push (match-string-no-properties 1) empty))
1669 ((string= (match-string 2) "O")
1670 (push (match-string-no-properties 1) unclosed))))
1671 (setq empty (sort (mapcar 'downcase empty) 'string<))
1672 (setq unclosed (sort (mapcar 'downcase unclosed) 'string<))
1673 (list empty unclosed)))
1675 ;;; HTML mode
1677 (defcustom html-mode-hook nil
1678 "Hook run by command `html-mode'.
1679 `text-mode-hook' and `sgml-mode-hook' are run first."
1680 :group 'sgml
1681 :type 'hook
1682 :options '(html-autoview-mode))
1684 (defvar html-quick-keys sgml-quick-keys
1685 "Use C-c X combinations for quick insertion of frequent tags when non-nil.
1686 This defaults to `sgml-quick-keys'.
1687 This takes effect when first loading the library.")
1689 (defvar html-mode-map
1690 (let ((map (make-sparse-keymap))
1691 (menu-map (make-sparse-keymap "HTML")))
1692 (set-keymap-parent map sgml-mode-map)
1693 (define-key map "\C-c6" 'html-headline-6)
1694 (define-key map "\C-c5" 'html-headline-5)
1695 (define-key map "\C-c4" 'html-headline-4)
1696 (define-key map "\C-c3" 'html-headline-3)
1697 (define-key map "\C-c2" 'html-headline-2)
1698 (define-key map "\C-c1" 'html-headline-1)
1699 (define-key map "\C-c\r" 'html-paragraph)
1700 (define-key map "\C-c\n" 'html-line)
1701 (define-key map "\C-c\C-c-" 'html-horizontal-rule)
1702 (define-key map "\C-c\C-co" 'html-ordered-list)
1703 (define-key map "\C-c\C-cu" 'html-unordered-list)
1704 (define-key map "\C-c\C-cr" 'html-radio-buttons)
1705 (define-key map "\C-c\C-cc" 'html-checkboxes)
1706 (define-key map "\C-c\C-cl" 'html-list-item)
1707 (define-key map "\C-c\C-ch" 'html-href-anchor)
1708 (define-key map "\C-c\C-cn" 'html-name-anchor)
1709 (define-key map "\C-c\C-ci" 'html-image)
1710 (when html-quick-keys
1711 (define-key map "\C-c-" 'html-horizontal-rule)
1712 (define-key map "\C-co" 'html-ordered-list)
1713 (define-key map "\C-cu" 'html-unordered-list)
1714 (define-key map "\C-cr" 'html-radio-buttons)
1715 (define-key map "\C-cc" 'html-checkboxes)
1716 (define-key map "\C-cl" 'html-list-item)
1717 (define-key map "\C-ch" 'html-href-anchor)
1718 (define-key map "\C-cn" 'html-name-anchor)
1719 (define-key map "\C-ci" 'html-image))
1720 (define-key map "\C-c\C-s" 'html-autoview-mode)
1721 (define-key map "\C-c\C-v" 'browse-url-of-buffer)
1722 (define-key map [menu-bar html] (cons "HTML" menu-map))
1723 (define-key menu-map [html-autoview-mode]
1724 '("Toggle Autoviewing" . html-autoview-mode))
1725 (define-key menu-map [browse-url-of-buffer]
1726 '("View Buffer Contents" . browse-url-of-buffer))
1727 (define-key menu-map [nil] '("--"))
1728 ;;(define-key menu-map "6" '("Heading 6" . html-headline-6))
1729 ;;(define-key menu-map "5" '("Heading 5" . html-headline-5))
1730 ;;(define-key menu-map "4" '("Heading 4" . html-headline-4))
1731 (define-key menu-map "3" '("Heading 3" . html-headline-3))
1732 (define-key menu-map "2" '("Heading 2" . html-headline-2))
1733 (define-key menu-map "1" '("Heading 1" . html-headline-1))
1734 (define-key menu-map "l" '("Radio Buttons" . html-radio-buttons))
1735 (define-key menu-map "c" '("Checkboxes" . html-checkboxes))
1736 (define-key menu-map "l" '("List Item" . html-list-item))
1737 (define-key menu-map "u" '("Unordered List" . html-unordered-list))
1738 (define-key menu-map "o" '("Ordered List" . html-ordered-list))
1739 (define-key menu-map "-" '("Horizontal Rule" . html-horizontal-rule))
1740 (define-key menu-map "\n" '("Line Break" . html-line))
1741 (define-key menu-map "\r" '("Paragraph" . html-paragraph))
1742 (define-key menu-map "i" '("Image" . html-image))
1743 (define-key menu-map "h" '("Href Anchor" . html-href-anchor))
1744 (define-key menu-map "n" '("Name Anchor" . html-name-anchor))
1745 map)
1746 "Keymap for commands for use in HTML mode.")
1748 (defvar html-face-tag-alist
1749 '((bold . "b")
1750 (italic . "i")
1751 (underline . "u")
1752 (mode-line . "rev"))
1753 "Value of `sgml-face-tag-alist' for HTML mode.")
1755 (defvar html-tag-face-alist
1756 '(("b" . bold)
1757 ("big" . bold)
1758 ("blink" . highlight)
1759 ("cite" . italic)
1760 ("em" . italic)
1761 ("h1" bold underline)
1762 ("h2" bold-italic underline)
1763 ("h3" italic underline)
1764 ("h4" . underline)
1765 ("h5" . underline)
1766 ("h6" . underline)
1767 ("i" . italic)
1768 ("rev" . mode-line)
1769 ("s" . underline)
1770 ("small" . default)
1771 ("strong" . bold)
1772 ("title" bold underline)
1773 ("tt" . default)
1774 ("u" . underline)
1775 ("var" . italic))
1776 "Value of `sgml-tag-face-alist' for HTML mode.")
1778 (defvar html-display-text
1779 '((img . "[/]")
1780 (hr . "----------")
1781 (li . "o "))
1782 "Value of `sgml-display-text' for HTML mode.")
1785 (defvar html-tag-alist
1786 (let* ((1-7 '(("1") ("2") ("3") ("4") ("5") ("6") ("7")))
1787 (1-9 `(,@1-7 ("8") ("9")))
1788 (align '(("align" ("left") ("center") ("right"))))
1789 (ialign '(("align" ("top") ("middle") ("bottom") ("left")
1790 ("right"))))
1791 (valign '(("top") ("middle") ("bottom") ("baseline")))
1792 (rel '(("next") ("previous") ("parent") ("subdocument") ("made")))
1793 (href '("href" ("ftp:") ("file:") ("finger:") ("gopher:") ("http:")
1794 ("mailto:") ("news:") ("rlogin:") ("telnet:") ("tn3270:")
1795 ("wais:") ("/cgi-bin/")))
1796 (name '("name"))
1797 (link `(,href
1798 ("rel" ,@rel)
1799 ("rev" ,@rel)
1800 ("title")))
1801 (list '((nil \n ("List item: " "<li>" str
1802 (if sgml-xml-mode "</li>") \n))))
1803 (shape '(("shape" ("rect") ("circle") ("poly") ("default"))))
1804 (cell `(t
1805 ,@align
1806 ("valign" ,@valign)
1807 ("colspan" ,@1-9)
1808 ("rowspan" ,@1-9)
1809 ("nowrap" t)))
1810 (cellhalign '(("align" ("left") ("center") ("right")
1811 ("justify") ("char"))
1812 ("char") ("charoff")))
1813 (cellvalign '(("valign" ("top") ("middle") ("bottom")
1814 ("baseline")))))
1815 ;; put ,-expressions first, else byte-compile chokes (as of V19.29)
1816 ;; and like this it's more efficient anyway
1817 `(("a" ,name ,@link)
1818 ("area" t ,@shape ("coords") ("href") ("nohref" "nohref") ("alt")
1819 ("tabindex") ("accesskey") ("onfocus") ("onblur"))
1820 ("base" t ,@href)
1821 ("col" t ,@cellhalign ,@cellvalign ("span") ("width"))
1822 ("colgroup" \n ,@cellhalign ,@cellvalign ("span") ("width"))
1823 ("dir" ,@list)
1824 ("figcaption")
1825 ("figure" \n)
1826 ("font" nil "size" ("-1") ("+1") ("-2") ("+2") ,@1-7)
1827 ("form" (\n _ \n "<input type=\"submit\" value=\"\""
1828 (if sgml-xml-mode " />" ">"))
1829 ("action" ,@(cdr href)) ("method" ("get") ("post")))
1830 ("h1" ,@align)
1831 ("h2" ,@align)
1832 ("h3" ,@align)
1833 ("h4" ,@align)
1834 ("h5" ,@align)
1835 ("h6" ,@align)
1836 ("hr" t ("size" ,@1-9) ("width") ("noshade" t) ,@align)
1837 ("iframe" \n ,@ialign ("longdesc") ("name") ("src")
1838 ("frameborder" ("1") ("0")) ("marginwidth") ("marginheight")
1839 ("scrolling" ("yes") ("no") ("auto")) ("height") ("width"))
1840 ("img" t ("align" ,@valign ("texttop") ("absmiddle") ("absbottom"))
1841 ("src") ("alt") ("width" "1") ("height" "1")
1842 ("border" "1") ("vspace" "1") ("hspace" "1") ("ismap" t))
1843 ("input" t ,name ("accept") ("alt") ("autocomplete" ("on") ("off"))
1844 ("autofocus" t) ("checked" t) ("dirname") ("disabled" t) ("form")
1845 ("formaction")
1846 ("formenctype" ("application/x-www-form-urlencoded")
1847 ("multipart/form-data") ("text/plain"))
1848 ("formmethod" ("get") ("post"))
1849 ("formnovalidate" t)
1850 ("formtarget" ("_blank") ("_self") ("_parent") ("_top"))
1851 ("height") ("inputmode") ("list") ("max") ("maxlength") ("min")
1852 ("minlength") ("multiple" t) ("pattern") ("placeholder")
1853 ("readonly" t) ("required" t) ("size") ("src") ("step")
1854 ("type" ("hidden") ("text") ("search") ("tel") ("url") ("email")
1855 ("password") ("date") ("time") ("number") ("range") ("color")
1856 ("checkbox") ("radio") ("file") ("submit") ("image") ("reset")
1857 ("button"))
1858 ("value") ("width"))
1859 ("link" t ,@link)
1860 ("menu" ,@list)
1861 ("ol" ,@list ("type" ("A") ("a") ("I") ("i") ("1")))
1862 ("p" t ,@align)
1863 ("select" (nil \n
1864 ("Text: "
1865 "<option>" str (if sgml-xml-mode "</option>") \n))
1866 ,name ("size" ,@1-9) ("multiple" t))
1867 ("table" (nil \n
1868 ((completing-read "Cell kind: " '(("td") ("th"))
1869 nil t "t")
1870 "<tr><" str ?> _
1871 (if sgml-xml-mode (concat "<" str "></tr>")) \n))
1872 ("border" t ,@1-9) ("width" "10") ("cellpadding"))
1873 ("tbody" \n ,@cellhalign ,@cellvalign)
1874 ("td" ,@cell)
1875 ("textarea" ,name ("rows" ,@1-9) ("cols" ,@1-9))
1876 ("tfoot" \n ,@cellhalign ,@cellvalign)
1877 ("th" ,@cell)
1878 ("thead" \n ,@cellhalign ,@cellvalign)
1879 ("ul" ,@list ("type" ("disc") ("circle") ("square")))
1881 ,@sgml-tag-alist
1883 ("abbr")
1884 ("acronym")
1885 ("address")
1886 ("array" (nil \n
1887 ("Item: " "<item>" str (if sgml-xml-mode "</item>") \n))
1888 "align")
1889 ("article" \n)
1890 ("aside" \n)
1891 ("au")
1892 ("audio" \n
1893 ("src") ("crossorigin" ("anonymous") ("use-credentials"))
1894 ("preload" ("none") ("metadata") ("auto"))
1895 ("autoplay" "autoplay") ("mediagroup") ("loop" "loop")
1896 ("muted" "muted") ("controls" "controls"))
1897 ("b")
1898 ("bdi")
1899 ("bdo" nil ("lang") ("dir" ("ltr") ("rtl")))
1900 ("big")
1901 ("blink")
1902 ("blockquote" \n ("cite"))
1903 ("body" \n ("background" ".gif") ("bgcolor" "#") ("text" "#")
1904 ("link" "#") ("alink" "#") ("vlink" "#"))
1905 ("box" (nil _ "<over>" _ (if sgml-xml-mode "</over>")))
1906 ("br" t ("clear" ("left") ("right")))
1907 ("button" nil ("name") ("value")
1908 ("type" ("submit") ("reset") ("button"))
1909 ("disabled" "disabled")
1910 ("tabindex") ("accesskey") ("onfocus") ("onblur"))
1911 ("canvas" \n ("width") ("height"))
1912 ("caption" ("valign" ("top") ("bottom")))
1913 ("center" \n)
1914 ("cite")
1915 ("code" \n)
1916 ("datalist" \n)
1917 ("dd" ,(not sgml-xml-mode))
1918 ("del" nil ("cite") ("datetime"))
1919 ("dfn")
1920 ("div")
1921 ("dl" (nil \n
1922 ( "Term: "
1923 "<dt>" str (if sgml-xml-mode "</dt>")
1924 "<dd>" _ (if sgml-xml-mode "</dd>") \n)))
1925 ("dt" (t _ (if sgml-xml-mode "</dt>")
1926 "<dd>" (if sgml-xml-mode "</dd>") \n))
1927 ("em")
1928 ("embed" t ("src") ("type") ("width") ("height"))
1929 ("fieldset" \n)
1930 ("fn" "id" "fn") ;; Footnotes were deprecated in HTML 3.2
1931 ("footer" \n)
1932 ("frame" t ("longdesc") ("name") ("src")
1933 ("frameborder" ("1") ("0")) ("marginwidth") ("marginheight")
1934 ("noresize" "noresize") ("scrolling" ("yes") ("no") ("auto")))
1935 ("frameset" \n ("rows") ("cols") ("onload") ("onunload"))
1936 ("head" \n)
1937 ("header" \n)
1938 ("hgroup" \n)
1939 ("html" (\n
1940 "<head>\n"
1941 "<title>" (setq str (read-string "Title: ")) "</title>\n"
1942 "</head>\n"
1943 "<body>\n<h1>" str "</h1>\n" _
1944 "\n<address>\n<a href=\"mailto:"
1945 user-mail-address
1946 "\">" (user-full-name) "</a>\n</address>\n"
1947 "</body>"
1949 ("i")
1950 ("ins" nil ("cite") ("datetime"))
1951 ("isindex" t ("action") ("prompt"))
1952 ("kbd")
1953 ("label" nil ("for") ("accesskey") ("onfocus") ("onblur"))
1954 ("lang")
1955 ("legend" nil ("accesskey"))
1956 ("li" ,(not sgml-xml-mode))
1957 ("main" \n)
1958 ("map" \n ("name"))
1959 ("mark")
1960 ("math" \n)
1961 ("meta" t ("http-equiv") ("name") ("content") ("scheme"))
1962 ("meter" nil ("value") ("min") ("max") ("low") ("high")
1963 ("optimum"))
1964 ("nav" \n)
1965 ("nobr")
1966 ("noframes" \n)
1967 ("noscript" \n)
1968 ("object" \n ("declare" "declare") ("classid") ("codebase")
1969 ("data") ("type") ("codetype") ("archive") ("standby")
1970 ("height") ("width") ("usemap") ("name") ("tabindex"))
1971 ("optgroup" \n ("name") ("size") ("multiple" "multiple")
1972 ("disabled" "disabled") ("tabindex") ("onfocus") ("onblur")
1973 ("onchange"))
1974 ("option" t ("value") ("label") ("selected" t))
1975 ("output" nil ("for") ("form") ("name"))
1976 ("over" t)
1977 ("param" t ("name") ("value")
1978 ("valuetype" ("data") ("ref") ("object")) ("type"))
1979 ("person") ;; Tag for person's name tag deprecated in HTML 3.2
1980 ("pre" \n)
1981 ("progress" nil ("value") ("max"))
1982 ("q" nil ("cite"))
1983 ("rev")
1984 ("rp" t)
1985 ("rt" t)
1986 ("ruby")
1987 ("s")
1988 ("samp")
1989 ("script" nil ("charset") ("type") ("src") ("defer" "defer"))
1990 ("section" \n)
1991 ("small")
1992 ("source" t ("src") ("type") ("media"))
1993 ("span" nil
1994 ("class"
1995 ("builtin")
1996 ("comment")
1997 ("constant")
1998 ("function-name")
1999 ("keyword")
2000 ("string")
2001 ("type")
2002 ("variable-name")
2003 ("warning")))
2004 ("strong")
2005 ("style" \n ("type") ("media") ("title"))
2006 ("sub")
2007 ("summary")
2008 ("sup")
2009 ("time" nil ("datetime"))
2010 ("title")
2011 ("tr" t)
2012 ("track" t
2013 ("kind" ("subtitles") ("captions") ("descriptions")
2014 ("chapters") ("metadata"))
2015 ("src") ("srclang") ("label") ("default"))
2016 ("tt")
2017 ("u")
2018 ("var")
2019 ("video" \n
2020 ("src") ("crossorigin" ("anonymous") ("use-credentials"))
2021 ("poster") ("preload" ("none") ("metadata") ("auto"))
2022 ("autoplay" "autoplay") ("mediagroup") ("loop" "loop")
2023 ("muted" "muted") ("controls" "controls") ("width") ("height"))
2024 ("wbr" t)))
2025 "Value of `sgml-tag-alist' for HTML mode.")
2027 (defvar html-tag-help
2028 `(,@sgml-tag-help
2029 ("a" . "Anchor of point or link elsewhere")
2030 ("abbr" . "Abbreviation")
2031 ("acronym" . "Acronym")
2032 ("address" . "Formatted mail address")
2033 ("area" . "Region of an image map")
2034 ("array" . "Math array")
2035 ("article" . "An independent part of document or site")
2036 ("aside" . "Secondary content related to surrounding content (e.g. page or article)")
2037 ("au" . "Author")
2038 ("audio" . "Sound or audio stream")
2039 ("b" . "Bold face")
2040 ("base" . "Base address for URLs")
2041 ("bdi" . "Text isolated for bidirectional formatting")
2042 ("bdo" . "Override text directionality")
2043 ("big" . "Font size")
2044 ("blink" . "Blinking text")
2045 ("blockquote" . "Indented quotation")
2046 ("body" . "Document body")
2047 ("box" . "Math fraction")
2048 ("br" . "Line break")
2049 ("button" . "Clickable button")
2050 ("canvas" . "Script generated graphics canvas")
2051 ("caption" . "Table caption")
2052 ("center" . "Centered text")
2053 ("changed" . "Change bars")
2054 ("cite" . "Citation of a document")
2055 ("code" . "Formatted source code")
2056 ("col" . "Group of attribute specifications for table columns")
2057 ("colgroup" . "Group of columns")
2058 ("datalist" . "A set of predefined options")
2059 ("dd" . "Definition of term")
2060 ("del" . "Deleted text")
2061 ("dfn" . "Defining instance of a term")
2062 ("dir" . "Directory list (obsolete)")
2063 ("div" . "Generic block-level container")
2064 ("dl" . "Definition list")
2065 ("dt" . "Term to be defined")
2066 ("em" . "Emphasized")
2067 ("embed" . "Embedded data in foreign format")
2068 ("fieldset" . "Group of related controls and labels")
2069 ("fig" . "Figure")
2070 ("figa" . "Figure anchor")
2071 ("figcaption" . "Caption for a figure")
2072 ("figd" . "Figure description")
2073 ("figt" . "Figure text")
2074 ("figure" . "Self-contained content, often with a caption")
2075 ("fn" . "Footnote") ;; No one supports special footnote rendering.
2076 ("font" . "Font size")
2077 ("footer" . "Footer of a section")
2078 ("form" . "Form with input fields")
2079 ("frame" . "Frame in which another HTML document can be displayed")
2080 ("frameset" . "Container for frames")
2081 ("group" . "Document grouping")
2082 ("h1" . "Most important section headline")
2083 ("h2" . "Important section headline")
2084 ("h3" . "Section headline")
2085 ("h4" . "Minor section headline")
2086 ("h5" . "Unimportant section headline")
2087 ("h6" . "Least important section headline")
2088 ("head" . "Document header")
2089 ("header" . "Header of a section")
2090 ("hgroup" . "Group of headings - h1-h6 elements")
2091 ("hr" . "Horizontal rule")
2092 ("html" . "HTML Document")
2093 ("i" . "Italic face")
2094 ("iframe" . "Inline frame with a nested browsing context")
2095 ("img" . "Graphic image")
2096 ("input" . "Form input field")
2097 ("ins" . "Inserted text")
2098 ("isindex" . "Input field for index search")
2099 ("kbd" . "Keyboard example face")
2100 ("label" . "Caption for a user interface item")
2101 ("lang" . "Natural language")
2102 ("legend" . "Caption for a fieldset")
2103 ("li" . "List item")
2104 ("link" . "Link relationship")
2105 ("main" . "Main content of the document body")
2106 ("map" . "Image map (a clickable link area")
2107 ("mark" . "Highlighted text")
2108 ("math" . "Math formula")
2109 ("menu" . "List of commands")
2110 ("meta" . "Document properties")
2111 ("meter" . "Scalar measurement within a known range")
2112 ("mh" . "Form mail header")
2113 ("nav" . "Group of navigational links")
2114 ("nextid" . "Allocate new id")
2115 ("nobr" . "Text without line break")
2116 ("noframes" . "Content for user agents that don't support frames")
2117 ("noscript" . "Alternate content for when a script isn't executed")
2118 ("object" . "External resource")
2119 ("ol" . "Ordered list")
2120 ("optgroup" . "Group of options")
2121 ("option" . "Selection list item")
2122 ("output" . "Result of a calculation or user action")
2123 ("over" . "Math fraction rule")
2124 ("p" . "Paragraph start")
2125 ("panel" . "Floating panel")
2126 ("param" . "Parameters for an object")
2127 ("person" . "Person's name")
2128 ("pre" . "Preformatted fixed width text")
2129 ("progress" . "Completion progress of a task")
2130 ("q" . "Quotation")
2131 ("rev" . "Reverse video")
2132 ("rp" . "Fallback text for when ruby annotations aren't supported")
2133 ("rt" . "Ruby text component of a ruby annotation")
2134 ("ruby" . "Ruby annotation")
2135 ("s" . "Strikeout")
2136 ("samp" . "Sample text")
2137 ("script" . "Executable script within a document")
2138 ("section" . "Section of a document")
2139 ("select" . "Selection list")
2140 ("small" . "Font size")
2141 ("source" . "Media resource for media elements")
2142 ("sp" . "Nobreak space")
2143 ("span" . "Generic inline container")
2144 ("strong" . "Standout text")
2145 ("style" . "Style information")
2146 ("sub" . "Subscript")
2147 ("summary" . "Summary, caption, or legend")
2148 ("sup" . "Superscript")
2149 ("table" . "Table with rows and columns")
2150 ("tb" . "Table vertical break")
2151 ("tbody" . "Table body")
2152 ("td" . "Table data cell")
2153 ("textarea" . "Form multiline edit area")
2154 ("tfoot" . "Table foot")
2155 ("th" . "Table header cell")
2156 ("thead" . "Table head")
2157 ("time" . "Content with optional machine-readable timestamp")
2158 ("title" . "Document title")
2159 ("tr" . "Table row separator")
2160 ("track" . "Timed text track for media elements")
2161 ("tt" . "Typewriter face")
2162 ("u" . "Underlined text")
2163 ("ul" . "Unordered list")
2164 ("var" . "Math variable face")
2165 ("video" . "Video or movie")
2166 ("wbr" . "Enable <br> within <nobr>"))
2167 "Value of variable `sgml-tag-help' for HTML mode.")
2169 (defvar outline-regexp)
2170 (defvar outline-heading-end-regexp)
2171 (defvar outline-level)
2173 (defun html-current-defun-name ()
2174 "Return the name of the last HTML title or heading, or nil."
2175 (save-excursion
2176 (if (re-search-backward
2177 (concat
2178 "<[ \t\r\n]*"
2179 "\\(?:[hH][0-6]\\|title\\|TITLE\\|Title\\)"
2180 "[^>]*>"
2181 "[ \t\r\n]*"
2182 "\\([^<\r\n]*[^ <\t\r\n]+\\)")
2183 nil t)
2184 (match-string-no-properties 1))))
2186 (defvar html--buffer-classes-cache nil
2187 "Cache for `html-current-buffer-classes'.
2188 When set, this should be a cons cell where the CAR is the
2189 buffer's tick counter (as produced by `buffer-modified-tick'),
2190 and the CDR is the list of class names found in the buffer.")
2191 (make-variable-buffer-local 'html--buffer-classes-cache)
2193 (defvar html--buffer-ids-cache nil
2194 "Cache for `html-current-buffer-ids'.
2195 When set, this should be a cons cell where the CAR is the
2196 buffer's tick counter (as produced by `buffer-modified-tick'),
2197 and the CDR is the list of class names found in the buffer.")
2198 (make-variable-buffer-local 'html--buffer-ids-cache)
2200 (defun html-current-buffer-classes ()
2201 "Return a list of class names used in the current buffer.
2202 The result is cached in `html--buffer-classes-cache'."
2203 (let ((tick (buffer-modified-tick)))
2204 (if (eq (car html--buffer-classes-cache) tick)
2205 (cdr html--buffer-classes-cache)
2206 (let* ((dom (libxml-parse-html-region (point-min) (point-max)))
2207 (classes
2208 (seq-mapcat
2209 (lambda (el)
2210 (when-let (class-list
2211 (cdr (assq 'class (dom-attributes el))))
2212 (split-string class-list)))
2213 (dom-by-class dom ""))))
2214 (setq-local html--buffer-classes-cache (cons tick classes))
2215 classes))))
2217 (defun html-current-buffer-ids ()
2218 "Return a list of IDs used in the current buffer.
2219 The result is cached in `html--buffer-ids-cache'."
2220 (let ((tick (buffer-modified-tick)))
2221 (if (eq (car html--buffer-ids-cache) tick)
2222 (cdr html--buffer-ids-cache)
2223 (let* ((dom
2224 (libxml-parse-html-region (point-min) (point-max)))
2225 (ids
2226 (seq-mapcat
2227 (lambda (el)
2228 (when-let (id-list
2229 (cdr (assq 'id (dom-attributes el))))
2230 (split-string id-list)))
2231 (dom-by-id dom ""))))
2232 (setq-local html--buffer-ids-cache (cons tick ids))
2233 ids))))
2236 ;;;###autoload
2237 (define-derived-mode html-mode sgml-mode '(sgml-xml-mode "XHTML" "HTML")
2238 "Major mode based on SGML mode for editing HTML documents.
2239 This allows inserting skeleton constructs used in hypertext documents with
2240 completion. See below for an introduction to HTML. Use
2241 \\[browse-url-of-buffer] to see how this comes out. See also `sgml-mode' on
2242 which this is based.
2244 Do \\[describe-variable] html- SPC and \\[describe-variable] sgml- SPC to see available variables.
2246 To write fairly well formatted pages you only need to know few things. Most
2247 browsers have a function to read the source code of the page being seen, so
2248 you can imitate various tricks. Here's a very short HTML primer which you
2249 can also view with a browser to see what happens:
2251 <title>A Title Describing Contents</title> should be on every page. Pages can
2252 have <h1>Very Major Headlines</h1> through <h6>Very Minor Headlines</h6>
2253 <hr> Parts can be separated with horizontal rules.
2255 <p>Paragraphs only need an opening tag. Line breaks and multiple spaces are
2256 ignored unless the text is <pre>preformatted.</pre> Text can be marked as
2257 <b>bold</b>, <i>italic</i> or <u>underlined</u> using the normal M-o or
2258 Edit/Text Properties/Face commands.
2260 Pages can have <a name=\"SOMENAME\">named points</a> and can link other points
2261 to them with <a href=\"#SOMENAME\">see also somename</a>. In the same way <a
2262 href=\"URL\">see also URL</a> where URL is a filename relative to current
2263 directory, or absolute as in `http://www.cs.indiana.edu/elisp/w3/docs.html'.
2265 Images in many formats can be inlined with <img src=\"URL\">.
2267 If you mainly create your own documents, `sgml-specials' might be
2268 interesting. But note that some HTML 2 browsers can't handle `&apos;'.
2269 To work around that, do:
2270 (eval-after-load \"sgml-mode\" \\='(aset sgml-char-names ?\\=' nil))
2272 \\{html-mode-map}"
2273 (setq-local sgml-display-text html-display-text)
2274 (setq-local sgml-tag-face-alist html-tag-face-alist)
2275 (setq-local sgml-tag-alist html-tag-alist)
2276 (setq-local sgml-face-tag-alist html-face-tag-alist)
2277 (setq-local sgml-tag-help html-tag-help)
2278 (setq-local outline-regexp "^.*<[Hh][1-6]\\>")
2279 (setq-local outline-heading-end-regexp "</[Hh][1-6]>")
2280 (setq-local outline-level
2281 (lambda () (char-before (match-end 0))))
2282 (setq-local add-log-current-defun-function #'html-current-defun-name)
2283 (setq-local sentence-end-base "[.?!][]\"'”)}]*\\(<[^>]*>\\)*")
2285 (when (fboundp 'libxml-parse-html-region)
2286 (defvar css-class-list-function)
2287 (setq-local css-class-list-function #'html-current-buffer-classes)
2288 (defvar css-id-list-function)
2289 (setq-local css-id-list-function #'html-current-buffer-ids))
2291 (setq imenu-create-index-function 'html-imenu-index)
2293 (setq-local sgml-empty-tags
2294 ;; From HTML-4.01's loose.dtd, parsed with
2295 ;; `sgml-parse-dtd', plus manual addition of "wbr".
2296 '("area" "base" "basefont" "br" "col" "frame" "hr" "img" "input"
2297 "isindex" "link" "meta" "param" "wbr"))
2298 (setq-local sgml-unclosed-tags
2299 ;; From HTML-4.01's loose.dtd, parsed with `sgml-parse-dtd'.
2300 '("body" "colgroup" "dd" "dt" "head" "html" "li" "option"
2301 "p" "tbody" "td" "tfoot" "th" "thead" "tr"))
2302 ;; It's for the user to decide if it defeats it or not -stef
2303 ;; (make-local-variable 'imenu-sort-function)
2304 ;; (setq imenu-sort-function nil) ; sorting the menu defeats the purpose
2307 (defvar html-imenu-regexp
2308 "\\s-*<h\\([1-9]\\)[^\n<>]*>\\(<[^\n<>]*>\\)*\\s-*\\([^\n<>]*\\)"
2309 "A regular expression matching a head line to be added to the menu.
2310 The first `match-string' should be a number from 1-9.
2311 The second `match-string' matches extra tags and is ignored.
2312 The third `match-string' will be the used in the menu.")
2314 (defun html-imenu-index ()
2315 "Return a table of contents for an HTML buffer for use with Imenu."
2316 (let (toc-index)
2317 (save-excursion
2318 (goto-char (point-min))
2319 (while (re-search-forward html-imenu-regexp nil t)
2320 (setq toc-index
2321 (cons (cons (concat (make-string
2322 (* 2 (1- (string-to-number (match-string 1))))
2323 ?\s)
2324 (match-string 3))
2325 (line-beginning-position))
2326 toc-index))))
2327 (nreverse toc-index)))
2329 (define-minor-mode html-autoview-mode
2330 "Toggle viewing of HTML files on save (HTML Autoview mode).
2331 With a prefix argument ARG, enable HTML Autoview mode if ARG is
2332 positive, and disable it otherwise. If called from Lisp, enable
2333 the mode if ARG is omitted or nil.
2335 HTML Autoview mode is a buffer-local minor mode for use with
2336 `html-mode'. If enabled, saving the file automatically runs
2337 `browse-url-of-buffer' to view it."
2338 nil nil nil
2339 :group 'sgml
2340 (if html-autoview-mode
2341 (add-hook 'after-save-hook 'browse-url-of-buffer nil t)
2342 (remove-hook 'after-save-hook 'browse-url-of-buffer t)))
2345 (define-skeleton html-href-anchor
2346 "HTML anchor tag with href attribute."
2347 "URL: "
2348 ;; '(setq input "http:")
2349 "<a href=\"" str "\">" _ "</a>")
2351 (define-skeleton html-name-anchor
2352 "HTML anchor tag with name attribute."
2353 "Name: "
2354 "<a name=\"" str "\""
2355 (if sgml-xml-mode (concat " id=\"" str "\""))
2356 ">" _ "</a>")
2358 (define-skeleton html-headline-1
2359 "HTML level 1 headline tags."
2361 "<h1>" _ "</h1>")
2363 (define-skeleton html-headline-2
2364 "HTML level 2 headline tags."
2366 "<h2>" _ "</h2>")
2368 (define-skeleton html-headline-3
2369 "HTML level 3 headline tags."
2371 "<h3>" _ "</h3>")
2373 (define-skeleton html-headline-4
2374 "HTML level 4 headline tags."
2376 "<h4>" _ "</h4>")
2378 (define-skeleton html-headline-5
2379 "HTML level 5 headline tags."
2381 "<h5>" _ "</h5>")
2383 (define-skeleton html-headline-6
2384 "HTML level 6 headline tags."
2386 "<h6>" _ "</h6>")
2388 (define-skeleton html-horizontal-rule
2389 "HTML horizontal rule tag."
2391 (if sgml-xml-mode "<hr />" "<hr>") \n)
2393 (define-skeleton html-image
2394 "HTML image tag."
2395 "Image URL: "
2396 "<img src=\"" str "\" alt=\"" _ "\""
2397 (if sgml-xml-mode " />" ">"))
2399 (define-skeleton html-line
2400 "HTML line break tag."
2402 (if sgml-xml-mode "<br />" "<br>") \n)
2404 (define-skeleton html-ordered-list
2405 "HTML ordered list tags."
2407 "<ol>" \n
2408 "<li>" _ (if sgml-xml-mode "</li>") \n
2409 "</ol>")
2411 (define-skeleton html-unordered-list
2412 "HTML unordered list tags."
2414 "<ul>" \n
2415 "<li>" _ (if sgml-xml-mode "</li>") \n
2416 "</ul>")
2418 (define-skeleton html-list-item
2419 "HTML list item tag."
2421 (if (bolp) nil '\n)
2422 "<li>" _ (if sgml-xml-mode "</li>"))
2424 (define-skeleton html-paragraph
2425 "HTML paragraph tag."
2427 (if (bolp) nil ?\n)
2428 "<p>" _ (if sgml-xml-mode "</p>"))
2430 (define-skeleton html-checkboxes
2431 "Group of connected checkbox inputs."
2433 '(setq v1 nil
2434 v2 nil)
2435 ("Value: "
2436 "<input type=\"" (identity "checkbox") ; see comment above about identity
2437 "\" name=\"" (or v1 (setq v1 (skeleton-read "Name: ")))
2438 "\" value=\"" str ?\"
2439 (when (y-or-n-p "Set \"checked\" attribute? ")
2440 (funcall skeleton-transformation-function
2441 (if sgml-xml-mode " checked=\"checked\"" " checked")))
2442 (if sgml-xml-mode " />" ">")
2443 (skeleton-read "Text: " (capitalize str))
2444 (or v2 (setq v2 (if (y-or-n-p "Newline after text? ")
2445 (funcall skeleton-transformation-function
2446 (if sgml-xml-mode "<br />" "<br>"))
2447 "")))
2448 \n))
2450 (define-skeleton html-radio-buttons
2451 "Group of connected radio button inputs."
2453 '(setq v1 nil
2454 v2 (cons nil nil))
2455 ("Value: "
2456 "<input type=\"" (identity "radio") ; see comment above about identity
2457 "\" name=\"" (or (car v2) (setcar v2 (skeleton-read "Name: ")))
2458 "\" value=\"" str ?\"
2459 (when (and (not v1) (setq v1 (y-or-n-p "Set \"checked\" attribute? ")))
2460 (funcall skeleton-transformation-function
2461 (if sgml-xml-mode " checked=\"checked\"" " checked")))
2462 (if sgml-xml-mode " />" ">")
2463 (skeleton-read "Text: " (capitalize str))
2464 (or (cdr v2) (setcdr v2 (if (y-or-n-p "Newline after text? ")
2465 (funcall skeleton-transformation-function
2466 (if sgml-xml-mode "<br />" "<br>"))
2467 "")))
2468 \n))
2470 (define-skeleton html-navigational-links
2471 "Group of navigational links."
2473 "<nav>" \n
2474 "<ul>" \n
2475 "<li><a href=\"" (skeleton-read "URL: " "#") "\">"
2476 (skeleton-read "Title: ") "</a>"
2477 (if sgml-xml-mode (if sgml-xml-mode "</li>")) \n
2478 "</ul>" \n
2479 "</nav>")
2481 (define-skeleton html-html5-template
2482 "Initial HTML5 template"
2484 "<!DOCTYPE html>" \n
2485 "<html lang=\"en\">" \n
2486 "<head>" \n
2487 "<meta charset=\"utf-8\">" \n
2488 "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">" \n
2489 "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">" \n
2490 "<title>" (skeleton-read "Page Title: ") "</title>" \n
2491 "</head>" \n
2492 "<body>" \n
2493 "<div id=\"app\"></div>" \n
2494 "</body>" \n
2495 "</html>")
2497 (provide 'sgml-mode)
2499 ;;; sgml-mode.el ends here