1 ;;; sgml-mode.el --- SGML- and HTML-editing modes -*- lexical-binding:t -*-
3 ;; Copyright (C) 1992, 1995-1996, 1998, 2001-2017 Free Software
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/>.
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.
44 :link
'(custom-group-link :tag
"Font Lock Faces group" font-lock-faces
)
47 (defcustom sgml-basic-offset
2
48 "Specifies the basic indentation level for `sgml-indent-line'."
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:
61 When 2, attribute indentation looks like this:
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."
79 (defcustom sgml-transformation-function
'identity
80 "Default value for `skeleton-transformation-function' in SGML mode."
82 :initialize
'custom-initialize-default
83 :set
(lambda (sym val
)
86 (with-current-buffer buff
87 (and (derived-mode-p 'sgml-mode
)
89 (setq skeleton-transformation-function val
))))
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."
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
)))
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
))
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
))
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
))
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."
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
))
258 (setq elt
(aref sgml-char-names i
))
259 (if elt
(aset table
(make-char 'latin-iso8859-1 i
) elt
))
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'.
275 ((executable-find "onsgmls")
276 ;; onsgmls is the community version of `nsgmls'
277 ;; hosted on http://openjade.sourceforge.net/
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."
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
)
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."
309 (defvar sgml-namespace-face
'sgml-namespace
)
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
331 sgml-font-lock-keywords-1
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
))
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 (defun sgml-syntax-propertize (start end
)
345 "Syntactic keywords for `sgml-mode'."
347 (sgml-syntax-propertize-inside end
)
349 (syntax-propertize-rules
350 ;; Use the `b' style of comments to avoid interference with the -- ... --
351 ;; comments recognized when `sgml-specials' includes ?-.
352 ;; FIXME: beware of <!--> blabla <!--> !!
353 ("\\(<\\)!--" (1 "< b"))
354 ("--[ \t\n]*\\(>\\)" (1 "> b"))
355 ("\\(<\\)[?!]" (1 (prog1 "|>"
356 (sgml-syntax-propertize-inside end
))))
357 ;; Double quotes outside of tags should not introduce strings.
358 ;; Be careful to call `syntax-ppss' on a position before the one we're
359 ;; going to change, so as not to need to flush the data we just computed.
360 ("\"" (0 (if (prog1 (zerop (car (syntax-ppss (match-beginning 0))))
361 (goto-char (match-end 0)))
362 (string-to-syntax ".")))))
365 (defun sgml-syntax-propertize-inside (end)
366 (let ((ppss (syntax-ppss)))
369 (let ((endre (save-excursion
370 (goto-char (nth 8 ppss
))
372 ((looking-at-p "<!\\[CDATA\\[") "]]>")
373 ((looking-at-p "<\\?") (if sgml-xml-mode
"\\?>" ">"))
375 (when (re-search-forward endre end
'move
)
376 (put-text-property (1- (point)) (point)
377 'syntax-table
(string-to-syntax "|<"))))))))
380 (defvar sgml-face-tag-alist
()
381 "Alist of face and tag name for facemenu.")
383 (defvar sgml-tag-face-alist
()
384 "Tag names and face or list of faces to fontify with when invisible.
385 When `font-lock-maximum-decoration' is 1 this is always used for fontifying.
386 When more these are fontified together with `sgml-font-lock-keywords'.")
388 (defvar sgml-display-text
()
389 "Tag names as lowercase symbols, and display string when invisible.")
392 (defvar sgml-tags-invisible nil
)
394 (defcustom sgml-tag-alist
395 '(("![" ("ignore" t
) ("include" t
))
400 "Alist of tag names for completing read and insertion rules.
401 This alist is made up as
406 TAGRULE is a list of optionally t (no endtag) or `\\n' (separate endtag by
407 newlines) or a skeleton with nil, t or `\\n' in place of the interactor
408 followed by an ATTRIBUTERULE (for an always present attribute) or an
411 The attribute alist is made up as
413 ((\"attribute\" . ATTRIBUTERULE)
416 ATTRIBUTERULE is a list of optionally t (no value when no input) followed by
417 an optional alist of possible values."
418 :type
'(repeat (cons (string :tag
"Tag Name")
419 (repeat :tag
"Tag Rule" sexp
)))
421 (put 'sgml-tag-alist
'risky-local-variable t
)
423 (defcustom sgml-tag-help
424 '(("!" .
"Empty declaration for comment")
425 ("![" .
"Embed declarations with parser directive")
426 ("!attlist" .
"Tag attributes declaration")
427 ("!doctype" .
"Document type (DTD) declaration")
428 ("!element" .
"Tag declaration")
429 ("!entity" .
"Entity (macro) declaration"))
430 "Alist of tag name and short description."
431 :type
'(repeat (cons (string :tag
"Tag Name")
432 (string :tag
"Description")))
435 (defvar sgml-empty-tags nil
436 "List of tags whose !ELEMENT definition says EMPTY.")
438 (defvar sgml-unclosed-tags nil
439 "List of tags whose !ELEMENT definition says the end-tag is optional.")
441 (defun sgml-xml-guess ()
442 "Guess whether the current buffer is XML. Return non-nil if so."
444 (goto-char (point-min))
445 (or (string= "xml" (file-name-extension (or buffer-file-name
"")))
446 ;; Maybe the buffer-size check isn't needed, I don't know.
447 (and (zerop (buffer-size))
448 (string= "xhtml" (file-name-extension (or buffer-file-name
""))))
449 (looking-at "\\s-*<\\?xml")
450 (when (re-search-forward
453 '("<!DOCTYPE" "\\(\\w+\\)" "\\(\\w+\\)"
454 "\"\\([^\"]+\\)\"" "\"\\([^\"]+\\)\"")
457 (string-match "X\\(HT\\)?ML" (match-string 3))))))
459 (defvar v2
) ; free for skeleton
461 (defun sgml-comment-indent-new-line (&optional soft
)
462 (let ((comment-start "-- ")
463 (comment-start-skip "\\(<!\\)?--[ \t]*")
465 (comment-style 'plain
))
466 (comment-indent-new-line soft
)))
468 (defun sgml-mode-facemenu-add-face-function (face _end
)
469 (let ((tag-face (cdr (assq face sgml-face-tag-alist
))))
471 (setq tag-face
(funcall skeleton-transformation-function tag-face
))
472 (setq facemenu-end-add-face
(concat "</" tag-face
">"))
473 (concat "<" tag-face
">"))
477 (memq (caar face
) '(:foreground
:background
)))
478 (setq facemenu-end-add-face
"</span>")
479 (format "<span style=\"%s:%s\">"
480 (if (eq (caar face
) :foreground
)
485 (error "Face not configured for %s mode"
486 (format-mode-line mode-name
))))))
488 (defun sgml-fill-nobreak ()
489 "Don't break between a tag name and its first argument.
490 This function is designed for use in `fill-nobreak-predicate'.
492 <a href=\"some://where\" type=\"text/plain\">
494 | no break here | but still allowed here"
496 (skip-chars-backward " \t")
497 (and (not (zerop (skip-syntax-backward "w_")))
498 (skip-chars-backward "/?!")
499 (eq (char-before) ?
<))))
501 (defvar tildify-space-string
)
502 (defvar tildify-foreach-region-function
)
505 (define-derived-mode sgml-mode text-mode
'(sgml-xml-mode "XML" "SGML")
506 "Major mode for editing SGML documents.
508 Keys <, &, SPC within <>, \", / and \\=' can be electric depending on
511 An argument of N to a tag-inserting command means to wrap it around
512 the next N words. In Transient Mark mode, when the mark is active,
513 N defaults to -1, which means to wrap it around the current region.
515 If you like upcased tags, put (setq sgml-transformation-function \\='upcase)
518 Use \\[sgml-validate] to validate your document with an SGML parser.
520 Do \\[describe-variable] sgml- SPC to see available variables.
521 Do \\[describe-key] on the following bindings to discover what they do.
523 (make-local-variable 'sgml-saved-validate-command
)
524 (make-local-variable 'facemenu-end-add-face
)
525 ;; If encoding does not allow non-break space character, use reference.
526 ;; FIXME: Perhaps use if possible (e.g. when we know its HTML)?
527 (setq-local tildify-space-string
528 (if (equal (decode-coding-string
529 (encode-coding-string " " buffer-file-coding-system
)
530 buffer-file-coding-system
) " ")
532 ;; FIXME: Use the fact that we're parsing the document already
533 ;; rather than using regex-based filtering.
534 (setq-local tildify-foreach-region-function
536 'tildify-foreach-ignore-environments
537 `((,(eval-when-compile
540 (regexp-opt '("pre" "dfn" "code" "samp" "kbd" "var"
541 "PRE" "DFN" "CODE" "SAMP" "KBD" "VAR"))
546 ;;(make-local-variable 'facemenu-remove-face-function)
547 ;; A start or end tag by itself on a line separates a paragraph.
548 ;; This is desirable because SGML discards a newline that appears
549 ;; immediately after a start tag or immediately before an end tag.
550 (setq-local paragraph-start
(concat "[ \t]*$\\|\
551 [ \t]*</?\\(" sgml-name-re sgml-attrs-re
"\\)?>"))
552 (setq-local paragraph-separate
(concat paragraph-start
"$"))
553 (setq-local adaptive-fill-regexp
"[ \t]*")
554 (add-hook 'fill-nobreak-predicate
'sgml-fill-nobreak nil t
)
555 (setq-local indent-line-function
'sgml-indent-line
)
556 (setq-local comment-start
"<!-- ")
557 (setq-local comment-end
" -->")
558 (setq-local comment-indent-function
'sgml-comment-indent
)
559 (setq-local comment-line-break-function
'sgml-comment-indent-new-line
)
560 (setq-local skeleton-further-elements
'((completion-ignore-case t
)))
561 (setq-local skeleton-end-hook
564 (not (or (eq v2
'\n) (eq (car-safe v2
) '\n)))
565 (newline-and-indent))))
566 (setq font-lock-defaults
'((sgml-font-lock-keywords
567 sgml-font-lock-keywords-1
568 sgml-font-lock-keywords-2
)
570 (setq-local syntax-propertize-function
#'sgml-syntax-propertize
)
571 (setq-local facemenu-add-face-function
'sgml-mode-facemenu-add-face-function
)
572 (setq-local sgml-xml-mode
(sgml-xml-guess))
573 (unless sgml-xml-mode
574 (setq-local skeleton-transformation-function sgml-transformation-function
))
575 ;; This will allow existing comments within declarations to be
577 ;; I can't find a clear description of SGML/XML comments, but it seems that
578 ;; the only reliable ones are <!-- ... --> although it's not clear what
579 ;; "..." can contain. It used to accept -- ... -- as well, but that was
580 ;; apparently a mistake.
581 (setq-local comment-start-skip
"<!--[ \t]*")
582 (setq-local comment-end-skip
"[ \t]*--[ \t\n]*>")
583 ;; This definition has an HTML leaning but probably fits well for other modes.
584 (setq imenu-generic-expression
586 ,(concat "<!\\(element\\|entity\\)[ \t\n]+%?[ \t\n]*\\("
590 ,(concat "<[^>]+[ \t\n]+[Ii][Dd]=\\(['\"]"
591 (if sgml-xml-mode
"" "?")
592 "\\)\\(" sgml-name-re
"\\)\\1")
595 ,(concat "<[^>]+[ \t\n]+[Nn][Aa][Mm][Ee]=\\(['\"]"
596 (if sgml-xml-mode
"" "?")
597 "\\)\\(" sgml-name-re
"\\)\\1")
600 (defun sgml-comment-indent ()
601 (if (looking-at "--") comment-column
0))
603 (defun sgml-slash (arg)
604 "Insert ARG slash characters.
605 Behaves electrically if `sgml-quick-keys' is non-nil."
608 ((not (and (eq (char-before) ?
<) (= arg
1)))
609 (sgml-slash-matching arg
))
610 ((eq sgml-quick-keys
'indent
)
612 (indent-according-to-mode))
613 ((eq sgml-quick-keys
'close
)
617 (sgml-slash-matching arg
))))
619 (defun sgml-slash-matching (arg)
620 "Insert `/' and display any previous matching `/'.
621 Two `/'s are treated as matching if the first `/' ends a net-enabling
622 start tag, and the second `/' is the corresponding null end tag."
626 (let ((oldpos (point))
631 (if sgml-slash-distance
632 (narrow-to-region (max (point-min)
633 (- (point) sgml-slash-distance
))
635 (if (and (re-search-backward sgml-start-tag-regex
(point-min) t
)
636 (eq (match-end 0) (1- oldpos
)))
638 (goto-char (1- oldpos
))
639 (while (and (not blinkpos
)
640 (search-backward "/" (point-min) t
))
641 (let ((tagend (save-excursion
642 (if (re-search-backward sgml-start-tag-regex
646 (if (eq tagend
(point))
648 (setq blinkpos
(point))
649 (setq level
(1- level
)))
650 (setq level
(1+ level
)))))))
653 (if (pos-visible-in-window-p)
655 (message "Matches %s"
656 (buffer-substring (line-beginning-position)
657 (1+ blinkpos
)))))))))
659 ;; Why doesn't this use the iso-cvt table or, preferably, generate the
660 ;; inverse of the extensive table in the SGML Quail input method? -- fx
661 ;; I guess that's moot since it only works with Latin-1 anyhow.
662 (defun sgml-name-char (&optional char
)
663 "Insert a symbolic character name according to `sgml-char-names'.
664 Non-ASCII chars may be inserted either with the meta key, as in M-SPC for
665 no-break space or M-- for a soft hyphen; or via an input method or
666 encoded keyboard operation."
670 (setq char
(read-quoted-char "Enter char or octal number")))
676 (defun sgml-namify-char ()
677 "Change the char before point into its `&name;' equivalent.
678 Uses `sgml-char-names'."
680 (let* ((char (char-before))
683 ((null char
) (error "No char before point"))
684 ((< char
256) (or (aref sgml-char-names char
) char
))
685 ((aref sgml-char-names-table char
))
686 ((encode-char char
'ucs
)))))
688 (error "Don't know the name of `%c'" char
)
690 (insert (format (if (numberp name
) "&#%d;" "&%s;") name
)))))
692 (defun sgml-name-self ()
693 "Insert a symbolic character name according to `sgml-char-names'."
695 (sgml-name-char last-command-event
))
697 (defun sgml-maybe-name-self ()
698 "Insert a symbolic character name according to `sgml-char-names'."
700 (if sgml-name-8bit-mode
701 (sgml-name-char last-command-event
)
702 (self-insert-command 1)))
704 (defun sgml-name-8bit-mode ()
705 "Toggle whether to insert named entities instead of non-ASCII characters.
706 This only works for Latin-1 input."
708 (setq sgml-name-8bit-mode
(not sgml-name-8bit-mode
))
709 (message "sgml name entity mode is now %s"
710 (if sgml-name-8bit-mode
"ON" "OFF")))
712 ;; When an element of a skeleton is a string "str", it is passed
713 ;; through `skeleton-transformation-function' and inserted.
714 ;; If "str" is to be inserted literally, one should obtain it as
715 ;; the return value of a function, e.g. (identity "str").
717 (defvar sgml-tag-last nil
)
718 (defvar sgml-tag-history nil
)
719 (define-skeleton sgml-tag
720 "Prompt for a tag and insert it, optionally with attributes.
721 Completion and configuration are done according to `sgml-tag-alist'.
722 If you like tags and attributes in uppercase, customize
723 `sgml-transformation-function' to `upcase'."
724 (funcall (or skeleton-transformation-function
'identity
)
727 (if (> (length sgml-tag-last
) 0)
728 (format "Tag (default %s): " sgml-tag-last
)
730 sgml-tag-alist nil nil nil
'sgml-tag-history sgml-tag-last
)))
732 (("") -
1 '(undo-boundary) (identity "<")) |
; see comment above
733 `(("") '(setq v2
(sgml-attributes ,str t
)) ?
>
737 '(("") " [ " _
" ]]"))
738 ((and (eq v2 t
) sgml-xml-mode
(member ,str sgml-empty-tags
))
740 ((or (and (eq v2 t
) (not sgml-xml-mode
)) (string-match "^[/!?]" ,str
))
743 ;; Make sure we don't fall into an infinite loop.
744 ;; For xhtml's `tr' tag, we should maybe use \n instead.
745 (if (eq v2 t
) (setq v2 nil
))
746 ;; We use `identity' to prevent skeleton from passing
747 ;; `str' through `skeleton-transformation-function' a second time.
748 '(("") v2 _ v2
"</" (identity ',str
) ?
> >))
750 (cons '("") (cdr v2
)))
752 (append '(("") (car v2
))
754 '(resume: (car v2
) _
"</" (identity ',str
) ?
> >))))))
756 (autoload 'skeleton-read
"skeleton")
758 (defun sgml-attributes (tag &optional quiet
)
759 "When at top level of a tag, interactively insert attributes.
761 Completion and configuration of TAG are done according to `sgml-tag-alist'.
762 If QUIET, do not print a message when there are no attributes for TAG."
763 (interactive (list (save-excursion (sgml-beginning-of-tag t
))))
764 (or (stringp tag
) (error "Wrong context for adding attribute"))
766 (let ((completion-ignore-case t
)
767 (alist (cdr (assoc (downcase tag
) sgml-tag-alist
)))
769 (if (or (symbolp (car alist
))
770 (symbolp (car (car alist
))))
771 (setq car
(car alist
)
774 (message "No attributes configured."))
775 (if (stringp (car alist
))
777 (insert (if (eq (preceding-char) ?\s
) "" ?\s
)
778 (funcall skeleton-transformation-function
(car alist
)))
780 (setq i
(length alist
))
783 (insert (funcall skeleton-transformation-function
785 (skeleton-read (lambda ()
789 (if (string= "" attribute
)
791 (sgml-value (assoc (downcase attribute
) alist
))
793 (if (eq (preceding-char) ?\s
)
797 (defun sgml-auto-attributes (arg)
798 "Self insert the character typed; at top level of tag, prompt for attributes.
799 With prefix argument, only self insert."
801 (let ((point (point))
804 (not sgml-tag-alist
) ; no message when nothing configured
805 (symbolp (setq tag
(save-excursion (sgml-beginning-of-tag t
))))
806 (eq (aref tag
0) ?
/))
807 (self-insert-command (prefix-numeric-value arg
))
808 (sgml-attributes tag
)
809 (setq last-command-event ?\s
)
810 (or (> (point) point
)
811 (self-insert-command 1)))))
813 (defun sgml-tag-help (&optional tag
)
814 "Display description of tag TAG. If TAG is omitted, use the tag at point."
816 (list (let ((def (save-excursion
817 (if (eq (following-char) ?
<) (forward-char))
818 (sgml-beginning-of-tag))))
819 (completing-read (if def
820 (format "Tag (default %s): " def
)
822 sgml-tag-alist nil nil nil
823 'sgml-tag-history def
))))
824 (or (and tag
(> (length tag
) 0))
826 (if (eq (following-char) ?
<)
828 (setq tag
(sgml-beginning-of-tag))))
830 (error "No tag selected"))
831 (setq tag
(downcase tag
))
833 (or (cdr (assoc (downcase tag
) sgml-tag-help
))
834 (and (eq (aref tag
0) ?
/)
835 (cdr (assoc (downcase (substring tag
1)) sgml-tag-help
)))
836 "No description available")))
838 (defun sgml-maybe-end-tag (&optional arg
)
839 "Name self unless in position to end a tag or a prefix ARG is given."
841 (if (or arg
(eq (car (sgml-lexical-context)) 'tag
))
842 (self-insert-command (prefix-numeric-value arg
))
845 (defun sgml-skip-tag-backward (arg)
846 "Skip to beginning of tag or matching opening tag if present.
847 With prefix argument ARG, repeat this ARG times.
848 Return non-nil if we skipped over matched tags."
850 ;; FIXME: use sgml-get-context or something similar.
853 (search-backward "<" nil t
)
854 (if (looking-at "</\\([^ \n\t>]+\\)")
855 ;; end tag, skip any nested pairs
856 (let ((case-fold-search t
)
857 (re (concat "</?" (regexp-quote (match-string 1))
858 ;; Ignore empty tags like <foo/>.
859 "\\([^>]*[^/>]\\)?>")))
860 (while (and (re-search-backward re nil t
)
861 (eq (char-after (1+ (point))) ?
/))
863 (sgml-skip-tag-backward 1)))
868 (defun sgml-forward-sexp (n)
869 ;; This function is needed in major-modes such as nxml-mode where
870 ;; forward-sexp-function is used to give a more dwimish behavior to
871 ;; the `forward-sexp' command.
872 ;; Without it, we can end up with backtraces like:
873 ;; "get-text-property" (0xffffc0f0)
874 ;; "nxml-token-after" (0xffffc2ac)
875 ;; "nxml-forward-single-balanced-item" (0xffffc46c)
876 ;; "nxml-forward-balanced-item" (0xffffc61c)
877 ;; "forward-sexp" (0xffffc7f8)
878 ;; "sgml-parse-tag-backward" (0xffffc9c8)
879 ;; "sgml-lexical-context" (0xffffcba8)
880 ;; "sgml-mode-flyspell-verify" (0xffffcd74)
881 ;; "flyspell-word" (0xffffcf3c)
882 ;; "flyspell-post-command-hook" (0xffffd108)
883 ;; FIXME: should we also set the sgml-tag-syntax-table?
884 (let ((forward-sexp-function nil
))
887 (defvar sgml-electric-tag-pair-overlays nil
)
888 (defvar sgml-electric-tag-pair-timer nil
)
890 (defun sgml-electric-tag-pair-before-change-function (_beg end
)
894 (skip-chars-backward "[:alnum:]-_.:")
895 (if (and ;; (<= (point) beg) ; This poses problems for downcase-word.
896 (or (eq (char-before) ?
<)
897 (and (eq (char-before) ?
/)
898 (eq (char-before (1- (point))) ?
<)))
899 (null (get-char-property (point) 'text-clones
)))
900 (let* ((endp (eq (char-before) ?
/))
902 (cl-end (progn (skip-chars-forward "[:alnum:]-_.:") (point)))
905 (when (sgml-skip-tag-backward 1) (forward-char 1) t
)
906 (with-syntax-table sgml-tag-syntax-table
907 (let ((forward-sexp-function nil
))
909 (when (sgml-skip-tag-forward 1)
913 (clones (get-char-property (point) 'text-clones
)))
916 (equal (buffer-substring cl-start cl-end
)
917 (buffer-substring (point)
919 (skip-chars-forward "[:alnum:]-_.:")
921 (or (not endp
) (eq (char-after cl-end
) ?
>)))
923 (message "sgml-electric-tag-pair-before-change-function: deleting old OLs")
924 (mapc 'delete-overlay clones
))
925 (message "sgml-electric-tag-pair-before-change-function: new clone")
926 (text-clone-create cl-start cl-end
'spread
"[[:alnum:]-_.:]+")
927 (setq sgml-electric-tag-pair-overlays
928 (append (get-char-property (point) 'text-clones
)
929 sgml-electric-tag-pair-overlays
))))))
931 (error (message "Error in sgml-electric-pair-mode: %s" err
))))
933 (defun sgml-electric-tag-pair-flush-overlays ()
934 (while sgml-electric-tag-pair-overlays
935 (delete-overlay (pop sgml-electric-tag-pair-overlays
))))
937 (define-minor-mode sgml-electric-tag-pair-mode
938 "Toggle SGML Electric Tag Pair mode.
939 With a prefix argument ARG, enable the mode if ARG is positive,
940 and disable it otherwise. If called from Lisp, enable the mode
941 if ARG is omitted or nil.
943 SGML Electric Tag Pair mode is a buffer-local minor mode for use
944 with `sgml-mode' and related major modes. When enabled, editing
945 an opening markup tag automatically updates the closing tag."
947 (if sgml-electric-tag-pair-mode
949 (add-hook 'before-change-functions
950 'sgml-electric-tag-pair-before-change-function
952 (unless sgml-electric-tag-pair-timer
953 (setq sgml-electric-tag-pair-timer
954 (run-with-idle-timer 5 'repeat
'sgml-electric-tag-pair-flush-overlays
))))
955 (remove-hook 'before-change-functions
956 'sgml-electric-tag-pair-before-change-function
958 ;; We leave the timer running for other buffers.
962 (defun sgml-skip-tag-forward (arg)
963 "Skip to end of tag or matching closing tag if present.
964 With prefix argument ARG, repeat this ARG times.
965 Return t if after a closing tag."
967 ;; FIXME: Use sgml-get-context or something similar.
968 ;; It currently might jump to an unrelated </P> if the <P>
969 ;; we're skipping has no matching </P>.
971 (with-syntax-table sgml-tag-syntax-table
973 (skip-chars-forward "^<>")
974 (if (eq (following-char) ?
>)
976 (if (looking-at "<\\([^/ \n\t>]+\\)\\([^>]*[^/>]\\)?>")
977 ;; start tag, skip any nested same pairs _and_ closing tag
978 (let ((case-fold-search t
)
979 (re (concat "</?" (regexp-quote (match-string 1))
980 ;; Ignore empty tags like <foo/>.
981 "\\([^>]*[^/>]\\)?>"))
985 ;; FIXME: This re-search-forward will mistakenly match
986 ;; tag-like text inside attributes.
987 (while (and (re-search-forward re nil t
)
989 (eq (char-after (1+ (match-beginning 0))) ?
/)))
990 (goto-char (match-beginning 0))
991 (sgml-skip-tag-forward 1))
1000 (defsubst sgml-looking-back-at
(str)
1001 "Return t if the test before point matches STR."
1002 (let ((start (- (point) (length str
))))
1003 (and (>= start
(point-min))
1004 (equal str
(buffer-substring-no-properties start
(point))))))
1006 (defun sgml-delete-tag (arg)
1007 ;; FIXME: Should be called sgml-kill-tag or should not touch the kill-ring.
1008 "Delete tag on or after cursor, and matching closing or opening tag.
1009 With prefix argument ARG, repeat this ARG times."
1014 (if (looking-at "[ \t\n]*<")
1016 (if (eq (char-after (match-end 0)) ?
/)
1019 (setq close
(point))
1020 (goto-char (match-end 0))))
1022 (or (save-excursion (setq close
(sgml-beginning-of-tag)
1023 close
(and (stringp close
)
1024 (eq (aref close
0) ?
/)
1026 ;; not on closing tag
1027 (let ((point (point)))
1028 (sgml-skip-tag-backward 1)
1029 (if (or (not (eq (following-char) ?
<))
1032 (<= (point) point
)))
1033 (error "Not on or before tag")))))
1036 (sgml-skip-tag-backward 1)
1041 (when (and (sgml-skip-tag-forward 1)
1042 (not (sgml-looking-back-at "/>")))
1044 ;; Delete any resulting empty line. If we didn't kill-sexp,
1045 ;; this *should* do nothing, because we're right after the tag.
1046 (if (progn (forward-line 0) (looking-at "\\(?:[ \t]*$\\)\n?"))
1047 (delete-region (match-beginning 0) (match-end 0)))
1050 (if (progn (forward-line 0) (looking-at "\\(?:[ \t]*$\\)\n?"))
1051 (delete-region (match-beginning 0) (match-end 0)))))
1052 (setq arg
(1- arg
))))
1055 ;; Put read-only last to enable setting this even when read-only enabled.
1056 (or (get 'sgml-tag
'invisible
)
1058 (append '(invisible t
1059 cursor-sensor-functions
(sgml-cursor-sensor)
1062 (symbol-plist 'sgml-tag
))))
1064 (defun sgml-tags-invisible (arg)
1065 "Toggle visibility of existing tags."
1067 (let ((inhibit-read-only t
)
1069 (with-silent-modifications
1071 (goto-char (point-min))
1072 (if (setq-local sgml-tags-invisible
1074 (>= (prefix-numeric-value arg
) 0)
1075 (not sgml-tags-invisible
)))
1076 (while (re-search-forward sgml-tag-name-re nil t
)
1078 (cdr (assq (intern-soft (downcase (match-string 1)))
1079 sgml-display-text
)))
1080 (goto-char (match-beginning 0))
1081 (and (stringp string
)
1082 (not (overlays-at (point)))
1083 (let ((ol (make-overlay (point) (match-beginning 1))))
1084 (overlay-put ol
'before-string string
)
1085 (overlay-put ol
'sgml-tag t
)))
1086 (put-text-property (point)
1087 (progn (forward-list) (point))
1088 'category
'sgml-tag
))
1089 (let ((pos (point-min)))
1090 (while (< (setq pos
(next-overlay-change pos
)) (point-max))
1091 (dolist (ol (overlays-at pos
))
1092 (if (overlay-get ol
'sgml-tag
)
1093 (delete-overlay ol
)))))
1094 (remove-text-properties (point-min) (point-max) '(category nil
)))))
1095 (cursor-sensor-mode (if sgml-tags-invisible
1 -
1))
1096 (run-hooks 'sgml-tags-invisible-hook
)
1099 (defun sgml-cursor-sensor (window x dir
)
1100 ;; Show preceding or following hidden tag, depending of cursor direction (and
1101 ;; `dir' is not the direction in this sense).
1102 (when (eq dir
'entered
)
1104 (let* ((y (window-point window
))
1109 ((and (eq (char-before) ?
>)
1110 (or (not (eq (char-after) ?
<))
1112 (sgml-forward-sexp -
1))
1113 ((eq (char-after y
) ?
<)
1114 (sgml-forward-sexp 1)))
1116 (message "Invisible tag: %s"
1117 ;; Strip properties, otherwise, the text is invisible.
1118 (buffer-substring-no-properties
1122 (defun sgml-validate (command)
1123 "Validate an SGML document.
1124 Runs COMMAND, a shell command, in a separate process asynchronously
1125 with output going to the buffer `*compilation*'.
1126 You can then use the command \\[next-error] to find the next error message
1127 and move to the line in the SGML document that caused it."
1129 (list (read-string "Validate command: "
1130 (or sgml-saved-validate-command
1131 (concat sgml-validate-command
1133 (shell-quote-argument
1134 (let ((name (buffer-file-name)))
1136 (file-name-nondirectory name
)))))))))
1137 (setq sgml-saved-validate-command command
)
1138 (save-some-buffers (not compilation-ask-about-save
) nil
)
1139 (compilation-start command
))
1141 (defsubst sgml-at-indentation-p
()
1142 "Return true if point is at the first non-whitespace character on the line."
1144 (skip-chars-backward " \t")
1147 (defun sgml-lexical-context (&optional limit
)
1148 "Return the lexical context at point as (TYPE . START).
1149 START is the location of the start of the lexical element.
1150 TYPE is one of `string', `comment', `tag', `cdata', `pi', or `text'.
1152 Optional argument LIMIT is the position to start parsing from.
1153 If nil, start from a preceding tag at indentation."
1159 ;; Skip tags backwards until we find one at indentation
1160 (while (and (ignore-errors (sgml-parse-tag-backward))
1161 (not (sgml-at-indentation-p)))))
1162 (with-syntax-table sgml-tag-syntax-table
1163 (while (< (point) pos
)
1164 ;; When entering this loop we're inside text.
1165 (setq text-start
(point))
1166 (skip-chars-forward "^<" pos
)
1170 ;; We got to the end without seeing a tag.
1172 ((looking-at "<!\\[[A-Z]+\\[")
1173 ;; We've found a CDATA section or similar.
1174 (let ((cdata-start (point)))
1175 (unless (search-forward "]]>" pos
'move
)
1176 (list 0 nil nil
'cdata nil nil nil nil cdata-start
))))
1177 ((looking-at comment-start-skip
)
1178 ;; parse-partial-sexp doesn't handle <!-- comments -->,
1179 ;; or only if ?- is in sgml-specials, so match explicitly
1180 (let ((start (point)))
1181 (unless (re-search-forward comment-end-skip pos
'move
)
1182 (list 0 nil nil nil t nil nil nil start
))))
1183 ((and sgml-xml-mode
(looking-at "<\\?"))
1184 ;; Processing Instructions.
1185 ;; In SGML, it's basically a normal tag of the form
1186 ;; <?NAME ...> but in XML, it takes the form <? ... ?>.
1187 (let ((pi-start (point)))
1188 (unless (search-forward "?>" pos
'move
)
1189 (list 0 nil nil
'pi nil nil nil nil pi-start
))))
1191 ;; We've reached a tag. Parse it.
1192 ;; FIXME: Handle net-enabling start-tags
1193 (parse-partial-sexp (point) pos
0))))))
1195 ((memq (nth 3 state
) '(cdata pi
)) (cons (nth 3 state
) (nth 8 state
)))
1196 ((nth 3 state
) (cons 'string
(nth 8 state
)))
1197 ((nth 4 state
) (cons 'comment
(nth 8 state
)))
1198 ((and state
(> (nth 0 state
) 0)) (cons 'tag
(nth 1 state
)))
1199 (t (cons 'text text-start
))))))
1201 (defun sgml-beginning-of-tag (&optional only-immediate
)
1202 "Skip to beginning of tag and return its name.
1203 If this can't be done, return nil."
1204 (let ((context (sgml-lexical-context)))
1205 (if (eq (car context
) 'tag
)
1207 (goto-char (cdr context
))
1208 (when (looking-at sgml-tag-name-re
)
1209 (match-string-no-properties 1)))
1210 (if only-immediate nil
1211 (when (not (eq (car context
) 'text
))
1212 (goto-char (cdr context
))
1213 (sgml-beginning-of-tag t
))))))
1215 (defun sgml-value (alist)
1216 "Interactively insert value taken from attribute-rule ALIST.
1217 See `sgml-tag-alist' for info about attribute rules."
1218 (setq alist
(cdr alist
))
1219 (if (stringp (car alist
))
1220 (insert "=\"" (car alist
) ?
\")
1221 (if (and (eq (car alist
) t
) (not sgml-xml-mode
))
1224 (setq alist
(skeleton-read (lambda ()
1226 "Value: " (cdr alist
)))))
1227 (if (string< "" alist
)
1232 (insert (skeleton-read (lambda ()
1233 (completing-read "Value: " alist
))))
1235 (insert (skeleton-read '(read-string "Value: ")))))
1238 (defun sgml-quote (start end
&optional unquotep
)
1239 "Quote SGML text in region START ... END.
1240 Only &, < and > are quoted, the rest is left untouched.
1241 With prefix argument UNQUOTEP, unquote the region."
1242 (interactive "r\nP")
1244 (narrow-to-region start end
)
1245 (goto-char (point-min))
1247 ;; FIXME: We should unquote other named character references as well.
1248 (while (re-search-forward
1249 "\\(&\\(amp\\|\\(l\\|\\(g\\)\\)t\\)\\)[][<>&;\n\t \"%!'(),/=?]"
1251 (replace-match (if (match-end 4) ">" (if (match-end 3) "<" "&")) t t
1252 nil
(if (eq (char-before (match-end 0)) ?\
;) 0 1)))
1253 (while (re-search-forward "[&<>]" nil t
)
1254 (replace-match (cdr (assq (char-before) '((?
& .
"&")
1259 (defun sgml-pretty-print (beg end
)
1260 "Simple-minded pretty printer for SGML.
1261 Re-indents the code and inserts newlines between BEG and END.
1262 You might want to turn on `auto-fill-mode' to get better results."
1264 ;; - insert newline between some start-tag and text.
1265 ;; - don't insert newline in front of some end-tags.
1273 ;; Don't use narrowing because it screws up auto-indent.
1274 (setq end
(copy-marker end t
))
1275 (with-syntax-table sgml-tag-syntax-table
1276 (while (re-search-forward "<" end t
)
1277 (goto-char (match-beginning 0))
1278 (unless (or ;;(looking-at "</")
1279 (progn (skip-chars-backward " \t") (bolp)))
1280 (reindent-then-newline-and-indent))
1281 (sgml-forward-sexp 1)))
1282 ;; (indent-region beg end)
1288 (cl-defstruct (sgml-tag
1289 (:constructor sgml-make-tag
(type start end name
)))
1290 type start end name
)
1292 (defsubst sgml-parse-tag-name
()
1293 "Skip past a tag-name, and return the name."
1294 (buffer-substring-no-properties
1295 (point) (progn (skip-syntax-forward "w_") (point))))
1297 (defun sgml-tag-text-p (start end
)
1298 "Return non-nil if text between START and END is a tag.
1299 Checks among other things that the tag does not contain spurious
1300 unquoted < or > chars inside, which would indicate that it
1301 really isn't a tag after all."
1303 (with-syntax-table sgml-tag-syntax-table
1304 (let ((pps (parse-partial-sexp start end
2)))
1305 (and (= (nth 0 pps
) 0))))))
1307 (defun sgml-parse-tag-backward (&optional limit
)
1308 "Parse an SGML tag backward, and return information about the tag.
1309 Assume that parsing starts from within a textual context.
1310 Leave point at the beginning of the tag."
1312 (let (tag-type tag-start tag-end name
)
1313 (or (re-search-backward "[<>]" limit
'move
)
1314 (error "No tag found"))
1315 (when (eq (char-after) ?
<)
1316 ;; Oops!! Looks like we were not in a textual context after all!.
1317 ;; Let's try to recover.
1318 ;; Remember the tag-start so we don't need to look for it later.
1319 ;; This is not just an optimization but also makes sure we don't get
1320 ;; stuck in infloops in cases where "looking back for <" would not go
1322 (setq tag-start
(point))
1323 (with-syntax-table sgml-tag-syntax-table
1324 (let ((pos (point)))
1326 ;; FIXME: This does not correctly skip over PI an CDATA tags.
1327 (sgml-forward-sexp 1)
1329 ;; This < seems to be just a spurious one, let's ignore it.
1331 (throw 'found
(sgml-parse-tag-backward limit
))))
1332 ;; Check it is really a tag, without any extra < or > inside.
1333 (unless (sgml-tag-text-p pos
(point))
1335 (throw 'found
(sgml-parse-tag-backward limit
)))
1336 (forward-char -
1))))
1337 (setq tag-end
(1+ (point)))
1339 ((sgml-looking-back-at "--") ; comment
1340 (setq tag-type
'comment
1341 tag-start
(or tag-start
(search-backward "<!--" nil t
))))
1342 ((sgml-looking-back-at "]]") ; cdata
1343 (setq tag-type
'cdata
1344 tag-start
(or tag-start
1345 (re-search-backward "<!\\[[A-Z]+\\[" nil t
))))
1346 ((sgml-looking-back-at "?") ; XML processing-instruction
1348 ;; IIUC: SGML processing instructions take the form <?foo ...>
1349 ;; i.e. a "normal" tag, handled below. In XML this is changed
1350 ;; to <?foo ... ?> where "..." can contain < and > and even <?
1351 ;; but not ?>. This means that when parsing backward, there's
1352 ;; no easy way to make sure that we find the real beginning of
1354 tag-start
(or tag-start
(search-backward "<?" nil t
))))
1358 (with-syntax-table sgml-tag-syntax-table
1361 (sgml-forward-sexp -
1)
1363 ;; This > isn't really the end of a tag. Skip it.
1364 (goto-char (1- tag-end
))
1365 (throw 'found
(sgml-parse-tag-backward limit
))))
1367 (goto-char (1+ tag-start
))
1369 (?
! (setq tag-type
'decl
)) ; declaration
1370 (??
(setq tag-type
'pi
)) ; processing-instruction
1371 (?%
(setq tag-type
'jsp
)) ; JSP tags
1374 (setq tag-type
'close
1375 name
(sgml-parse-tag-name)))
1376 (_ ; open or empty tag
1377 (setq tag-type
'open
1378 name
(sgml-parse-tag-name))
1379 (if (or (eq ?
/ (char-before (- tag-end
1)))
1380 (sgml-empty-tag-p name
))
1381 (setq tag-type
'empty
))))))
1382 (goto-char tag-start
)
1383 (sgml-make-tag tag-type tag-start tag-end name
))))
1385 (defun sgml-get-context (&optional until
)
1386 "Determine the context of the current position.
1387 By default, parse until we find a start-tag as the first thing on a line.
1388 If UNTIL is `empty', return even if the context is empty (i.e.
1389 we just skipped over some element and got to a beginning of line).
1391 The context is a list of tag-info structures. The last one is the tag
1392 immediately enclosing the current position.
1394 Point is assumed to be outside of any tag. If we discover that it's
1395 not the case, the first tag returned is the one inside which we are."
1396 (let ((here (point))
1401 ;; CONTEXT keeps track of the tag-stack
1402 ;; STACK keeps track of the end tags we've seen (and thus the start-tags
1403 ;; we'll have to ignore) when skipping over matching open..close pairs.
1404 ;; IGNORE is a list of tags that can be ignored because they have been
1405 ;; closed implicitly.
1406 (skip-chars-backward " \t\n") ; Make sure we're not at indentation.
1408 (and (not (eq until
'now
))
1410 (not (if until
(eq until
'empty
) context
))
1411 (not (sgml-at-indentation-p))
1413 (/= (point) (sgml-tag-start (car context
)))
1414 (sgml-unclosed-tag-p (sgml-tag-name (car context
)))))
1415 (setq tag-info
(ignore-errors (sgml-parse-tag-backward))))
1417 ;; This tag may enclose things we thought were tags. If so,
1420 (> (sgml-tag-end tag-info
)
1421 (sgml-tag-end (car context
))))
1422 (setq context
(cdr context
)))
1425 ((> (sgml-tag-end tag-info
) here
)
1426 ;; Oops!! Looks like we were not outside of any tag, after all.
1427 (push tag-info context
)
1431 ((eq (sgml-tag-type tag-info
) 'open
)
1434 (if (assoc-string (sgml-tag-name tag-info
) ignore t
)
1435 ;; There was an implicit end-tag.
1437 (push tag-info context
)
1438 ;; We're changing context so the tags implicitly closed inside
1439 ;; the previous context aren't implicitly closed here any more.
1440 ;; [ Well, actually it depends, but we don't have the info about
1441 ;; when it doesn't and when it does. --Stef ]
1443 ((eq t
(compare-strings (sgml-tag-name tag-info
) nil nil
1444 (car stack
) nil nil t
))
1445 (setq stack
(cdr stack
)))
1447 ;; The open and close tags don't match.
1448 (if (not sgml-xml-mode
)
1449 (unless (sgml-unclosed-tag-p (sgml-tag-name tag-info
))
1450 (message "Unclosed tag <%s>" (sgml-tag-name tag-info
))
1452 ;; We could just assume that the tag is simply not closed
1453 ;; but it's a bad assumption when tags *are* closed but
1454 ;; not properly nested.
1455 (while (and (cdr tmp
)
1456 (not (eq t
(compare-strings
1457 (sgml-tag-name tag-info
) nil nil
1458 (cadr tmp
) nil nil t
))))
1459 (setq tmp
(cdr tmp
)))
1460 (if (cdr tmp
) (setcdr tmp
(cddr tmp
)))))
1461 (message "Unmatched tags <%s> and </%s>"
1462 (sgml-tag-name tag-info
) (pop stack
)))))
1464 (if (and (null stack
) (sgml-unclosed-tag-p (sgml-tag-name tag-info
)))
1465 ;; This is a top-level open of an implicitly closed tag, so any
1466 ;; occurrence of such an open tag at the same level can be ignored
1467 ;; because it's been implicitly closed.
1468 (push (sgml-tag-name tag-info
) ignore
)))
1471 ((eq (sgml-tag-type tag-info
) 'close
)
1472 (if (sgml-empty-tag-p (sgml-tag-name tag-info
))
1473 (message "Spurious </%s>: empty tag" (sgml-tag-name tag-info
))
1474 (push (sgml-tag-name tag-info
) stack
)))
1480 (defun sgml-show-context (&optional full
)
1481 "Display the current context.
1482 If FULL is non-nil, parse back to the beginning of the buffer."
1484 (with-output-to-temp-buffer "*XML Context*"
1486 (let ((context (sgml-get-context)))
1489 (while (setq more
(sgml-get-context))
1490 (setq context
(nconc more context
)))))
1494 ;; Editing shortcuts
1496 (defun sgml-close-tag ()
1497 "Close current element.
1498 Depending on context, inserts a matching close-tag, or closes
1499 the current start-tag or the current comment or the current cdata, ..."
1501 (pcase (car (sgml-lexical-context))
1502 (`comment
(insert " -->"))
1503 (`cdata
(insert "]]>"))
1504 (`pi
(insert " ?>"))
1505 (`jsp
(insert " %>"))
1506 (`tag
(insert " />"))
1508 (let ((context (save-excursion (sgml-get-context))))
1511 (insert "</" (sgml-tag-name (car (last context
))) ">")
1512 (indent-according-to-mode)))))
1514 (error "Nothing to close"))))
1516 (defun sgml-empty-tag-p (tag-name)
1517 "Return non-nil if TAG-NAME is an implicitly empty tag."
1518 (and (not sgml-xml-mode
)
1519 (assoc-string tag-name sgml-empty-tags
'ignore-case
)))
1521 (defun sgml-unclosed-tag-p (tag-name)
1522 "Return non-nil if TAG-NAME is a tag for which an end-tag is optional."
1523 (and (not sgml-xml-mode
)
1524 (assoc-string tag-name sgml-unclosed-tags
'ignore-case
)))
1527 (defun sgml-calculate-indent (&optional lcon
)
1528 "Calculate the column to which this line should be indented.
1529 LCON is the lexical context, if any."
1530 (unless lcon
(setq lcon
(sgml-lexical-context)))
1532 ;; Indent comment-start markers inside <!-- just like comment-end markers.
1533 (if (and (eq (car lcon
) 'tag
)
1535 (save-excursion (goto-char (cdr lcon
)) (looking-at "<!--")))
1536 (setq lcon
(cons 'comment
(+ (cdr lcon
) 2))))
1541 ;; Go back to previous non-empty line.
1542 (while (and (> (point) (cdr lcon
))
1543 (zerop (forward-line -
1))
1544 (looking-at "[ \t]*$")))
1545 (if (> (point) (cdr lcon
))
1546 ;; Previous line is inside the string.
1547 (current-indentation)
1548 (goto-char (cdr lcon
))
1549 (1+ (current-column))))
1552 (let ((mark (looking-at "--")))
1553 ;; Go back to previous non-empty line.
1554 (while (and (> (point) (cdr lcon
))
1555 (zerop (forward-line -
1))
1556 (or (looking-at "[ \t]*$")
1557 (if mark
(not (looking-at "[ \t]*--"))))))
1558 (if (> (point) (cdr lcon
))
1559 ;; Previous line is inside the comment.
1560 (skip-chars-forward " \t")
1561 (goto-char (cdr lcon
))
1562 ;; Skip `<!' to get to the `--' with which we want to align.
1563 (search-forward "--")
1564 (goto-char (match-beginning 0)))
1565 (when (and (not mark
) (looking-at "--"))
1566 (forward-char 2) (skip-chars-forward " \t"))
1569 ;; We don't know how to indent it. Let's be honest about it.
1571 ;; We don't know how to indent it. Let's be honest about it.
1575 (goto-char (+ (cdr lcon
) sgml-attribute-offset
))
1576 (skip-chars-forward "^ \t\n") ;Skip tag name.
1577 (skip-chars-forward " \t")
1580 ;; This is the first attribute: indent.
1581 (goto-char (+ (cdr lcon
) sgml-attribute-offset
))
1582 (+ (current-column) sgml-basic-offset
)))
1585 (while (looking-at "</")
1586 (sgml-forward-sexp 1)
1587 (skip-chars-forward " \t"))
1588 (let* ((here (point))
1589 (unclosed (and ;; (not sgml-xml-mode)
1590 (looking-at sgml-tag-name-re
)
1591 (assoc-string (match-string 1)
1592 sgml-unclosed-tags
'ignore-case
)
1595 ;; If possible, align on the previous non-empty text line.
1596 ;; Otherwise, do a more serious parsing to find the
1597 ;; tag(s) relative to which we should be indenting.
1598 (if (and (not unclosed
) (skip-chars-backward " \t")
1599 (< (skip-chars-backward " \t\n") 0)
1600 (back-to-indentation)
1601 (> (point) (cdr lcon
)))
1604 (nreverse (sgml-get-context (if unclosed nil
'empty
)))))
1606 ;; Ignore previous unclosed start-tag in context.
1607 (while (and context unclosed
1608 (eq t
(compare-strings
1609 (sgml-tag-name (car context
)) nil nil
1610 unclosed nil nil t
)))
1611 (setq context
(cdr context
)))
1612 ;; Indent to reflect nesting.
1614 ;; If we were not in a text context after all, let's try again.
1615 ((and context
(> (sgml-tag-end (car context
)) here
))
1617 (sgml-calculate-indent
1618 (cons (if (memq (sgml-tag-type (car context
)) '(comment cdata
))
1619 (sgml-tag-type (car context
)) 'tag
)
1620 (sgml-tag-start (car context
)))))
1621 ;; Align on the first element after the nearest open-tag, if any.
1623 (goto-char (sgml-tag-end (car context
)))
1624 (skip-chars-forward " \t\n")
1625 (< (point) here
) (sgml-at-indentation-p))
1627 ;; ;; If the parsing failed, try to recover.
1628 ;; ((and (null context) (bobp)
1629 ;; (not (eq (char-after here) ?<)))
1631 ;; (if (and (looking-at "--[ \t\n]*>")
1632 ;; (re-search-backward "<!--" nil t))
1633 ;; ;; No wonder parsing failed: we're in a comment.
1634 ;; (sgml-calculate-indent (prog2 (goto-char (match-end 0))
1635 ;; (sgml-lexical-context)
1636 ;; (goto-char here)))
1637 ;; ;; We have no clue what's going on, let's be honest about it.
1639 ;; Otherwise, just follow the rules.
1643 (* sgml-basic-offset
(length context
)))))))
1646 (error "Unrecognized context %s" (car lcon
)))
1650 (defun sgml-indent-line ()
1651 "Indent the current line as SGML."
1653 (let* ((savep (point))
1656 (back-to-indentation)
1657 (if (>= (point) savep
) (setq savep nil
))
1658 (sgml-calculate-indent))))
1659 (if (null indent-col
)
1662 (save-excursion (indent-line-to indent-col
))
1663 (indent-line-to indent-col
)))))
1665 (defun sgml-guess-indent ()
1666 "Guess an appropriate value for `sgml-basic-offset'.
1667 Base the guessed indentation level on the first indented tag in the buffer.
1668 Add this to `sgml-mode-hook' for convenience."
1671 (goto-char (point-min))
1672 (if (re-search-forward "^\\([ \t]+\\)<" 500 'noerror
)
1674 (setq-local sgml-basic-offset
(1- (current-column)))
1675 (message "Guessed sgml-basic-offset = %d"
1679 (defun sgml-parse-dtd ()
1680 "Simplistic parse of the current buffer as a DTD.
1681 Currently just returns (EMPTY-TAGS UNCLOSED-TAGS)."
1682 (goto-char (point-min))
1685 (while (re-search-forward "<!ELEMENT[ \t\n]+\\([^ \t\n]+\\)[ \t\n]+[-O][ \t\n]+\\([-O]\\)[ \t\n]+\\([^ \t\n]+\\)" nil t
)
1687 ((string= (match-string 3) "EMPTY")
1688 (push (match-string-no-properties 1) empty
))
1689 ((string= (match-string 2) "O")
1690 (push (match-string-no-properties 1) unclosed
))))
1691 (setq empty
(sort (mapcar 'downcase empty
) 'string
<))
1692 (setq unclosed
(sort (mapcar 'downcase unclosed
) 'string
<))
1693 (list empty unclosed
)))
1697 (defcustom html-mode-hook nil
1698 "Hook run by command `html-mode'.
1699 `text-mode-hook' and `sgml-mode-hook' are run first."
1702 :options
'(html-autoview-mode))
1704 (defvar html-quick-keys sgml-quick-keys
1705 "Use C-c X combinations for quick insertion of frequent tags when non-nil.
1706 This defaults to `sgml-quick-keys'.
1707 This takes effect when first loading the library.")
1709 (defvar html-mode-map
1710 (let ((map (make-sparse-keymap))
1711 (menu-map (make-sparse-keymap "HTML")))
1712 (set-keymap-parent map sgml-mode-map
)
1713 (define-key map
"\C-c6" 'html-headline-6
)
1714 (define-key map
"\C-c5" 'html-headline-5
)
1715 (define-key map
"\C-c4" 'html-headline-4
)
1716 (define-key map
"\C-c3" 'html-headline-3
)
1717 (define-key map
"\C-c2" 'html-headline-2
)
1718 (define-key map
"\C-c1" 'html-headline-1
)
1719 (define-key map
"\C-c\r" 'html-paragraph
)
1720 (define-key map
"\C-c\n" 'html-line
)
1721 (define-key map
"\C-c\C-c-" 'html-horizontal-rule
)
1722 (define-key map
"\C-c\C-co" 'html-ordered-list
)
1723 (define-key map
"\C-c\C-cu" 'html-unordered-list
)
1724 (define-key map
"\C-c\C-cr" 'html-radio-buttons
)
1725 (define-key map
"\C-c\C-cc" 'html-checkboxes
)
1726 (define-key map
"\C-c\C-cl" 'html-list-item
)
1727 (define-key map
"\C-c\C-ch" 'html-href-anchor
)
1728 (define-key map
"\C-c\C-cn" 'html-name-anchor
)
1729 (define-key map
"\C-c\C-ci" 'html-image
)
1730 (when html-quick-keys
1731 (define-key map
"\C-c-" 'html-horizontal-rule
)
1732 (define-key map
"\C-co" 'html-ordered-list
)
1733 (define-key map
"\C-cu" 'html-unordered-list
)
1734 (define-key map
"\C-cr" 'html-radio-buttons
)
1735 (define-key map
"\C-cc" 'html-checkboxes
)
1736 (define-key map
"\C-cl" 'html-list-item
)
1737 (define-key map
"\C-ch" 'html-href-anchor
)
1738 (define-key map
"\C-cn" 'html-name-anchor
)
1739 (define-key map
"\C-ci" 'html-image
))
1740 (define-key map
"\C-c\C-s" 'html-autoview-mode
)
1741 (define-key map
"\C-c\C-v" 'browse-url-of-buffer
)
1742 (define-key map
[menu-bar html
] (cons "HTML" menu-map
))
1743 (define-key menu-map
[html-autoview-mode
]
1744 '("Toggle Autoviewing" . html-autoview-mode
))
1745 (define-key menu-map
[browse-url-of-buffer
]
1746 '("View Buffer Contents" . browse-url-of-buffer
))
1747 (define-key menu-map
[nil] '("--"))
1748 ;;(define-key menu-map "6" '("Heading 6" . html-headline-6))
1749 ;;(define-key menu-map "5" '("Heading 5" . html-headline-5))
1750 ;;(define-key menu-map "4" '("Heading 4" . html-headline-4))
1751 (define-key menu-map "3" '("Heading 3" . html-headline-3))
1752 (define-key menu-map "2" '("Heading 2" . html-headline-2))
1753 (define-key menu-map "1" '("Heading 1" . html-headline-1))
1754 (define-key menu-map "l" '("Radio Buttons" . html-radio-buttons))
1755 (define-key menu-map "c" '("Checkboxes" . html-checkboxes))
1756 (define-key menu-map "l" '("List Item" . html-list-item))
1757 (define-key menu-map "u" '("Unordered List" . html-unordered-list))
1758 (define-key menu-map "o" '("Ordered List" . html-ordered-list))
1759 (define-key menu-map "-" '("Horizontal Rule" . html-horizontal-rule))
1760 (define-key menu-map "\n" '("Line Break" . html-line))
1761 (define-key menu-map "\r" '("Paragraph" . html-paragraph))
1762 (define-key menu-map "i" '("Image" . html-image))
1763 (define-key menu-map "h" '("Href Anchor" . html-href-anchor))
1764 (define-key menu-map "n" '("Name Anchor" . html-name-anchor))
1766 "Keymap for commands for use in HTML mode.")
1768 (defvar html-face-tag-alist
1772 (mode-line . "rev"))
1773 "Value of `sgml-face-tag-alist' for HTML mode.")
1775 (defvar html-tag-face-alist
1778 ("blink" . highlight)
1781 ("h1" bold underline)
1782 ("h2" bold-italic underline)
1783 ("h3" italic underline)
1792 ("title" bold underline)
1796 "Value of `sgml-tag-face-alist' for HTML mode.")
1798 (defvar html-display-text
1802 "Value of `sgml-display-text' for HTML mode.")
1805 (defvar html-tag-alist
1806 (let* ((1-7 '(("1") ("2") ("3") ("4") ("5") ("6") ("7")))
1807 (1-9 `(,@1-7 ("8") ("9")))
1808 (align '(("align" ("left") ("center") ("right"))))
1809 (ialign '(("align" ("top") ("middle") ("bottom") ("left")
1811 (valign '(("top") ("middle") ("bottom") ("baseline")))
1812 (rel '(("next") ("previous") ("parent") ("subdocument") ("made")))
1813 (href '("href" ("ftp:") ("file:") ("finger:") ("gopher:") ("http:")
1814 ("mailto:") ("news:") ("rlogin:") ("telnet:") ("tn3270:")
1815 ("wais:") ("/cgi-bin/")))
1821 (list '((nil \n ("List item: " "<li>" str
1822 (if sgml-xml-mode "</li>") \n))))
1823 (shape '(("shape" ("rect") ("circle") ("poly") ("default"))))
1830 (cellhalign '(("align" ("left") ("center") ("right")
1831 ("justify") ("char"))
1832 ("char") ("charoff")))
1833 (cellvalign '(("valign" ("top") ("middle") ("bottom")
1835 ;; put ,-expressions first, else byte-compile chokes (as of V19.29)
1836 ;; and like this it's more efficient anyway
1837 `(("a" ,name ,@link)
1838 ("area" t ,@shape ("coords") ("href") ("nohref" "nohref") ("alt")
1839 ("tabindex") ("accesskey") ("onfocus") ("onblur"))
1841 ("col" t ,@cellhalign ,@cellvalign ("span") ("width"))
1842 ("colgroup" \n ,@cellhalign ,@cellvalign ("span") ("width"))
1846 ("font" nil "size" ("-1") ("+1") ("-2") ("+2") ,@1-7)
1847 ("form" (\n _ \n "<input type=\"submit\" value=\"\""
1848 (if sgml-xml-mode " />" ">"))
1849 ("action" ,@(cdr href)) ("method" ("get") ("post")))
1856 ("hr" t ("size" ,@1-9) ("width") ("noshade" t) ,@align)
1857 ("iframe" \n ,@ialign ("longdesc") ("name") ("src")
1858 ("frameborder" ("1") ("0")) ("marginwidth") ("marginheight")
1859 ("scrolling" ("yes") ("no") ("auto")) ("height") ("width"))
1860 ("img" t ("align" ,@valign ("texttop") ("absmiddle") ("absbottom"))
1861 ("src") ("alt") ("width" "1") ("height" "1")
1862 ("border" "1") ("vspace" "1") ("hspace" "1") ("ismap" t))
1863 ("input" t ,name ("accept") ("alt") ("autocomplete" ("on") ("off"))
1864 ("autofocus" t) ("checked" t) ("dirname") ("disabled" t) ("form")
1866 ("formenctype" ("application/x-www-form-urlencoded")
1867 ("multipart/form-data") ("text/plain"))
1868 ("formmethod" ("get") ("post"))
1869 ("formnovalidate" t)
1870 ("formtarget" ("_blank") ("_self") ("_parent") ("_top"))
1871 ("height") ("inputmode") ("list") ("max") ("maxlength") ("min")
1872 ("minlength") ("multiple" t) ("pattern") ("placeholder")
1873 ("readonly" t) ("required" t) ("size") ("src") ("step")
1874 ("type" ("hidden") ("text") ("search") ("tel") ("url") ("email")
1875 ("password") ("date") ("time") ("number") ("range") ("color")
1876 ("checkbox") ("radio") ("file") ("submit") ("image") ("reset")
1878 ("value") ("width"))
1881 ("ol" ,@list ("type" ("A") ("a") ("I") ("i") ("1")))
1885 "<option>" str (if sgml-xml-mode "</option>") \n))
1886 ,name ("size" ,@1-9) ("multiple" t))
1888 ((completing-read "Cell kind: " '(("td") ("th"))
1891 (if sgml-xml-mode (concat "<" str "></tr>")) \n))
1892 ("border" t ,@1-9) ("width" "10") ("cellpadding"))
1893 ("tbody" \n ,@cellhalign ,@cellvalign)
1895 ("textarea" ,name ("rows" ,@1-9) ("cols" ,@1-9))
1896 ("tfoot" \n ,@cellhalign ,@cellvalign)
1898 ("thead" \n ,@cellhalign ,@cellvalign)
1899 ("ul" ,@list ("type" ("disc") ("circle") ("square")))
1907 ("Item: " "<item>" str (if sgml-xml-mode "</item>") \n))
1913 ("src") ("crossorigin" ("anonymous") ("use-credentials"))
1914 ("preload" ("none") ("metadata") ("auto"))
1915 ("autoplay" "autoplay") ("mediagroup") ("loop" "loop")
1916 ("muted" "muted") ("controls" "controls"))
1919 ("bdo" nil ("lang") ("dir" ("ltr") ("rtl")))
1922 ("blockquote" \n ("cite"))
1923 ("body" \n ("background" ".gif") ("bgcolor" "#") ("text" "#")
1924 ("link" "#") ("alink" "#") ("vlink" "#"))
1925 ("box" (nil _ "<over>" _ (if sgml-xml-mode "</over>")))
1926 ("br" t ("clear" ("left") ("right")))
1927 ("button" nil ("name") ("value")
1928 ("type" ("submit") ("reset") ("button"))
1929 ("disabled" "disabled")
1930 ("tabindex") ("accesskey") ("onfocus") ("onblur"))
1931 ("canvas" \n ("width") ("height"))
1932 ("caption" ("valign" ("top") ("bottom")))
1937 ("dd" ,(not sgml-xml-mode))
1938 ("del" nil ("cite") ("datetime"))
1943 "<dt>" str (if sgml-xml-mode "</dt>")
1944 "<dd>" _ (if sgml-xml-mode "</dd>") \n)))
1945 ("dt" (t _ (if sgml-xml-mode "</dt>")
1946 "<dd>" (if sgml-xml-mode "</dd>") \n))
1948 ("embed" t ("src") ("type") ("width") ("height"))
1950 ("fn" "id" "fn") ;; Footnotes were deprecated in HTML 3.2
1952 ("frame" t ("longdesc") ("name") ("src")
1953 ("frameborder" ("1") ("0")) ("marginwidth") ("marginheight")
1954 ("noresize" "noresize") ("scrolling" ("yes") ("no") ("auto")))
1955 ("frameset" \n ("rows") ("cols") ("onload") ("onunload"))
1961 "<title>" (setq str (read-string "Title: ")) "</title>\n"
1963 "<body>\n<h1>" str "</h1>\n" _
1964 "\n<address>\n<a href=\"mailto:"
1966 "\">" (user-full-name) "</a>\n</address>\n"
1970 ("ins" nil ("cite") ("datetime"))
1971 ("isindex" t ("action") ("prompt"))
1973 ("label" nil ("for") ("accesskey") ("onfocus") ("onblur"))
1975 ("legend" nil ("accesskey"))
1976 ("li" ,(not sgml-xml-mode))
1981 ("meta" t ("http-equiv") ("name") ("content") ("scheme"))
1982 ("meter" nil ("value") ("min") ("max") ("low") ("high")
1988 ("object" \n ("declare" "declare") ("classid") ("codebase")
1989 ("data") ("type") ("codetype") ("archive") ("standby")
1990 ("height") ("width") ("usemap") ("name") ("tabindex"))
1991 ("optgroup" \n ("name") ("size") ("multiple" "multiple")
1992 ("disabled" "disabled") ("tabindex") ("onfocus") ("onblur")
1994 ("option" t ("value") ("label") ("selected" t))
1995 ("output" nil ("for") ("form") ("name"))
1997 ("param" t ("name") ("value")
1998 ("valuetype" ("data") ("ref") ("object")) ("type"))
1999 ("person") ;; Tag for person's name tag deprecated in HTML 3.2
2001 ("progress" nil ("value") ("max"))
2009 ("script" nil ("charset") ("type") ("src") ("defer" "defer"))
2012 ("source" t ("src") ("type") ("media"))
2025 ("style" \n ("type") ("media") ("title"))
2029 ("time" nil ("datetime"))
2033 ("kind" ("subtitles") ("captions") ("descriptions")
2034 ("chapters") ("metadata"))
2035 ("src") ("srclang") ("label") ("default"))
2040 ("src") ("crossorigin" ("anonymous") ("use-credentials"))
2041 ("poster") ("preload" ("none") ("metadata") ("auto"))
2042 ("autoplay" "autoplay") ("mediagroup") ("loop" "loop")
2043 ("muted" "muted") ("controls" "controls") ("width") ("height"))
2045 "Value of `sgml-tag-alist' for HTML mode.")
2047 (defvar html-tag-help
2049 ("a" . "Anchor of point or link elsewhere")
2050 ("abbr" . "Abbreviation")
2051 ("acronym" . "Acronym")
2052 ("address" . "Formatted mail address")
2053 ("area" . "Region of an image map")
2054 ("array" . "Math array")
2055 ("article" . "An independent part of document or site")
2056 ("aside" . "Secondary content related to surrounding content (e.g. page or article)")
2058 ("audio" . "Sound or audio stream")
2060 ("base" . "Base address for URLs")
2061 ("bdi" . "Text isolated for bidirectional formatting")
2062 ("bdo" . "Override text directionality")
2063 ("big" . "Font size")
2064 ("blink" . "Blinking text")
2065 ("blockquote" . "Indented quotation")
2066 ("body" . "Document body")
2067 ("box" . "Math fraction")
2068 ("br" . "Line break")
2069 ("button" . "Clickable button")
2070 ("canvas" . "Script generated graphics canvas")
2071 ("caption" . "Table caption")
2072 ("center" . "Centered text")
2073 ("changed" . "Change bars")
2074 ("cite" . "Citation of a document")
2075 ("code" . "Formatted source code")
2076 ("col" . "Group of attribute specifications for table columns")
2077 ("colgroup" . "Group of columns")
2078 ("datalist" . "A set of predefined options")
2079 ("dd" . "Definition of term")
2080 ("del" . "Deleted text")
2081 ("dfn" . "Defining instance of a term")
2082 ("dir" . "Directory list (obsolete)")
2083 ("div" . "Generic block-level container")
2084 ("dl" . "Definition list")
2085 ("dt" . "Term to be defined")
2086 ("em" . "Emphasized")
2087 ("embed" . "Embedded data in foreign format")
2088 ("fieldset" . "Group of related controls and labels")
2090 ("figa" . "Figure anchor")
2091 ("figcaption" . "Caption for a figure")
2092 ("figd" . "Figure description")
2093 ("figt" . "Figure text")
2094 ("figure" . "Self-contained content, often with a caption")
2095 ("fn" . "Footnote") ;; No one supports special footnote rendering.
2096 ("font" . "Font size")
2097 ("footer" . "Footer of a section")
2098 ("form" . "Form with input fields")
2099 ("frame" . "Frame in which another HTML document can be displayed")
2100 ("frameset" . "Container for frames")
2101 ("group" . "Document grouping")
2102 ("h1" . "Most important section headline")
2103 ("h2" . "Important section headline")
2104 ("h3" . "Section headline")
2105 ("h4" . "Minor section headline")
2106 ("h5" . "Unimportant section headline")
2107 ("h6" . "Least important section headline")
2108 ("head" . "Document header")
2109 ("header" . "Header of a section")
2110 ("hgroup" . "Group of headings - h1-h6 elements")
2111 ("hr" . "Horizontal rule")
2112 ("html" . "HTML Document")
2113 ("i" . "Italic face")
2114 ("iframe" . "Inline frame with a nested browsing context")
2115 ("img" . "Graphic image")
2116 ("input" . "Form input field")
2117 ("ins" . "Inserted text")
2118 ("isindex" . "Input field for index search")
2119 ("kbd" . "Keyboard example face")
2120 ("label" . "Caption for a user interface item")
2121 ("lang" . "Natural language")
2122 ("legend" . "Caption for a fieldset")
2123 ("li" . "List item")
2124 ("link" . "Link relationship")
2125 ("main" . "Main content of the document body")
2126 ("map" . "Image map (a clickable link area")
2127 ("mark" . "Highlighted text")
2128 ("math" . "Math formula")
2129 ("menu" . "List of commands")
2130 ("meta" . "Document properties")
2131 ("meter" . "Scalar measurement within a known range")
2132 ("mh" . "Form mail header")
2133 ("nav" . "Group of navigational links")
2134 ("nextid" . "Allocate new id")
2135 ("nobr" . "Text without line break")
2136 ("noframes" . "Content for user agents that don't support frames")
2137 ("noscript" . "Alternate content for when a script isn't executed")
2138 ("object" . "External resource")
2139 ("ol" . "Ordered list")
2140 ("optgroup" . "Group of options")
2141 ("option" . "Selection list item")
2142 ("output" . "Result of a calculation or user action")
2143 ("over" . "Math fraction rule")
2144 ("p" . "Paragraph start")
2145 ("panel" . "Floating panel")
2146 ("param" . "Parameters for an object")
2147 ("person" . "Person's name")
2148 ("pre" . "Preformatted fixed width text")
2149 ("progress" . "Completion progress of a task")
2151 ("rev" . "Reverse video")
2152 ("rp" . "Fallback text for when ruby annotations aren't supported")
2153 ("rt" . "Ruby text component of a ruby annotation")
2154 ("ruby" . "Ruby annotation")
2156 ("samp" . "Sample text")
2157 ("script" . "Executable script within a document")
2158 ("section" . "Section of a document")
2159 ("select" . "Selection list")
2160 ("small" . "Font size")
2161 ("source" . "Media resource for media elements")
2162 ("sp" . "Nobreak space")
2163 ("span" . "Generic inline container")
2164 ("strong" . "Standout text")
2165 ("style" . "Style information")
2166 ("sub" . "Subscript")
2167 ("summary" . "Summary, caption, or legend")
2168 ("sup" . "Superscript")
2169 ("table" . "Table with rows and columns")
2170 ("tb" . "Table vertical break")
2171 ("tbody" . "Table body")
2172 ("td" . "Table data cell")
2173 ("textarea" . "Form multiline edit area")
2174 ("tfoot" . "Table foot")
2175 ("th" . "Table header cell")
2176 ("thead" . "Table head")
2177 ("time" . "Content with optional machine-readable timestamp")
2178 ("title" . "Document title")
2179 ("tr" . "Table row separator")
2180 ("track" . "Timed text track for media elements")
2181 ("tt" . "Typewriter face")
2182 ("u" . "Underlined text")
2183 ("ul" . "Unordered list")
2184 ("var" . "Math variable face")
2185 ("video" . "Video or movie")
2186 ("wbr" . "Enable <br> within <nobr>"))
2187 "Value of variable `sgml-tag-help' for HTML mode.")
2189 (defvar outline-regexp)
2190 (defvar outline-heading-end-regexp)
2191 (defvar outline-level)
2193 (defun html-current-defun-name ()
2194 "Return the name of the last HTML title or heading, or nil."
2196 (if (re-search-backward
2199 "\\(?:[hH][0-6]\\|title\\|TITLE\\|Title\\)"
2202 "\\([^<\r\n]*[^ <\t\r\n]+\\)")
2204 (match-string-no-properties 1))))
2206 (defvar html--buffer-classes-cache nil
2207 "Cache for `html-current-buffer-classes'.
2208 When set, this should be a cons cell where the CAR is the
2209 buffer's tick counter (as produced by `buffer-modified-tick'),
2210 and the CDR is the list of class names found in the buffer.")
2211 (make-variable-buffer-local 'html--buffer-classes-cache)
2213 (defvar html--buffer-ids-cache nil
2214 "Cache for `html-current-buffer-ids'.
2215 When set, this should be a cons cell where the CAR is the
2216 buffer's tick counter (as produced by `buffer-modified-tick'),
2217 and the CDR is the list of class names found in the buffer.")
2218 (make-variable-buffer-local 'html--buffer-ids-cache)
2220 (defun html-current-buffer-classes ()
2221 "Return a list of class names used in the current buffer.
2222 The result is cached in `html--buffer-classes-cache'."
2223 (let ((tick (buffer-modified-tick)))
2224 (if (eq (car html--buffer-classes-cache) tick)
2225 (cdr html--buffer-classes-cache)
2226 (let* ((dom (libxml-parse-html-region (point-min) (point-max)))
2230 (when-let (class-list
2231 (cdr (assq 'class (dom-attributes el))))
2232 (split-string class-list)))
2233 (dom-by-class dom ""))))
2234 (setq-local html--buffer-classes-cache (cons tick classes))
2237 (defun html-current-buffer-ids ()
2238 "Return a list of IDs used in the current buffer.
2239 The result is cached in `html--buffer-ids-cache'."
2240 (let ((tick (buffer-modified-tick)))
2241 (if (eq (car html--buffer-ids-cache) tick)
2242 (cdr html--buffer-ids-cache)
2244 (libxml-parse-html-region (point-min) (point-max)))
2249 (cdr (assq 'id (dom-attributes el))))
2250 (split-string id-list)))
2251 (dom-by-id dom ""))))
2252 (setq-local html--buffer-ids-cache (cons tick ids))
2257 (define-derived-mode html-mode sgml-mode '(sgml-xml-mode "XHTML" "HTML")
2258 "Major mode based on SGML mode for editing HTML documents.
2259 This allows inserting skeleton constructs used in hypertext documents with
2260 completion. See below for an introduction to HTML. Use
2261 \\[browse-url-of-buffer] to see how this comes out. See also `sgml-mode' on
2262 which this is based.
2264 Do \\[describe-variable] html- SPC and \\[describe-variable] sgml- SPC to see available variables.
2266 To write fairly well formatted pages you only need to know few things. Most
2267 browsers have a function to read the source code of the page being seen, so
2268 you can imitate various tricks. Here's a very short HTML primer which you
2269 can also view with a browser to see what happens:
2271 <title>A Title Describing Contents</title> should be on every page. Pages can
2272 have <h1>Very Major Headlines</h1> through <h6>Very Minor Headlines</h6>
2273 <hr> Parts can be separated with horizontal rules.
2275 <p>Paragraphs only need an opening tag. Line breaks and multiple spaces are
2276 ignored unless the text is <pre>preformatted.</pre> Text can be marked as
2277 <b>bold</b>, <i>italic</i> or <u>underlined</u> using the normal M-o or
2278 Edit/Text Properties/Face commands.
2280 Pages can have <a name=\"SOMENAME\">named points</a> and can link other points
2281 to them with <a href=\"#SOMENAME\">see also somename</a>. In the same way <a
2282 href=\"URL\">see also URL</a> where URL is a filename relative to current
2283 directory, or absolute as in `http://www.cs.indiana.edu/elisp/w3/docs.html'.
2285 Images in many formats can be inlined with <img src=\"URL\">.
2287 If you mainly create your own documents, `sgml-specials' might be
2288 interesting. But note that some HTML 2 browsers can't handle `''.
2289 To work around that, do:
2290 (eval-after-load \"sgml-mode\" \\='(aset sgml-char-names ?\\=' nil))
2293 (setq-local sgml-display-text html-display-text)
2294 (setq-local sgml-tag-face-alist html-tag-face-alist)
2295 (setq-local sgml-tag-alist html-tag-alist)
2296 (setq-local sgml-face-tag-alist html-face-tag-alist)
2297 (setq-local sgml-tag-help html-tag-help)
2298 (setq-local outline-regexp "^.*<[Hh][1-6]\\>")
2299 (setq-local outline-heading-end-regexp "</[Hh][1-6]>")
2300 (setq-local outline-level
2301 (lambda () (char-before (match-end 0))))
2302 (setq-local add-log-current-defun-function #'html-current-defun-name)
2303 (setq-local sentence-end-base "[.?!][]\"'”)}]*\\(<[^>]*>\\)*")
2305 (when (fboundp 'libxml-parse-html-region)
2306 (defvar css-class-list-function)
2307 (setq-local css-class-list-function #'html-current-buffer-classes)
2308 (defvar css-id-list-function)
2309 (setq-local css-id-list-function #'html-current-buffer-ids))
2311 (setq imenu-create-index-function 'html-imenu-index)
2313 (setq-local sgml-empty-tags
2314 ;; From HTML-4.01's loose.dtd, parsed with
2315 ;; `sgml-parse-dtd', plus manual addition of "wbr".
2316 '("area" "base" "basefont" "br" "col" "frame" "hr" "img" "input"
2317 "isindex" "link" "meta" "param" "wbr"))
2318 (setq-local sgml-unclosed-tags
2319 ;; From HTML-4.01's loose.dtd, parsed with `sgml-parse-dtd'.
2320 '("body" "colgroup" "dd" "dt" "head" "html" "li" "option"
2321 "p" "tbody" "td" "tfoot" "th" "thead" "tr"))
2322 ;; It's for the user to decide if it defeats it or not -stef
2323 ;; (make-local-variable 'imenu-sort-function)
2324 ;; (setq imenu-sort-function nil) ; sorting the menu defeats the purpose
2327 (defvar html-imenu-regexp
2328 "\\s-*<h\\([1-9]\\)[^\n<>]*>\\(<[^\n<>]*>\\)*\\s-*\\([^\n<>]*\\)"
2329 "A regular expression matching a head line to be added to the menu.
2330 The first `match-string' should be a number from 1-9.
2331 The second `match-string' matches extra tags and is ignored.
2332 The third `match-string' will be the used in the menu.")
2334 (defun html-imenu-index ()
2335 "Return a table of contents for an HTML buffer for use with Imenu."
2338 (goto-char (point-min))
2339 (while (re-search-forward html-imenu-regexp nil t)
2341 (cons (cons (concat (make-string
2342 (* 2 (1- (string-to-number (match-string 1))))
2345 (line-beginning-position))
2347 (nreverse toc-index)))
2349 (define-minor-mode html-autoview-mode
2350 "Toggle viewing of HTML files on save (HTML Autoview mode).
2351 With a prefix argument ARG, enable HTML Autoview mode if ARG is
2352 positive, and disable it otherwise. If called from Lisp, enable
2353 the mode if ARG is omitted or nil.
2355 HTML Autoview mode is a buffer-local minor mode for use with
2356 `html-mode'. If enabled, saving the file automatically runs
2357 `browse-url-of-buffer' to view it."
2360 (if html-autoview-mode
2361 (add-hook 'after-save-hook 'browse-url-of-buffer nil t)
2362 (remove-hook 'after-save-hook 'browse-url-of-buffer t)))
2365 (define-skeleton html-href-anchor
2366 "HTML anchor tag with href attribute."
2368 ;; '(setq input "http:")
2369 "<a href=\"" str "\">" _ "</a>")
2371 (define-skeleton html-name-anchor
2372 "HTML anchor tag with name attribute."
2374 "<a name=\"" str "\""
2375 (if sgml-xml-mode (concat " id=\"" str "\""))
2378 (define-skeleton html-headline-1
2379 "HTML level 1 headline tags."
2383 (define-skeleton html-headline-2
2384 "HTML level 2 headline tags."
2388 (define-skeleton html-headline-3
2389 "HTML level 3 headline tags."
2393 (define-skeleton html-headline-4
2394 "HTML level 4 headline tags."
2398 (define-skeleton html-headline-5
2399 "HTML level 5 headline tags."
2403 (define-skeleton html-headline-6
2404 "HTML level 6 headline tags."
2408 (define-skeleton html-horizontal-rule
2409 "HTML horizontal rule tag."
2411 (if sgml-xml-mode "<hr />" "<hr>") \n)
2413 (define-skeleton html-image
2416 "<img src=\"" str "\" alt=\"" _ "\""
2417 (if sgml-xml-mode " />" ">"))
2419 (define-skeleton html-line
2420 "HTML line break tag."
2422 (if sgml-xml-mode "<br />" "<br>") \n)
2424 (define-skeleton html-ordered-list
2425 "HTML ordered list tags."
2428 "<li>" _ (if sgml-xml-mode "</li>") \n
2431 (define-skeleton html-unordered-list
2432 "HTML unordered list tags."
2435 "<li>" _ (if sgml-xml-mode "</li>") \n
2438 (define-skeleton html-list-item
2439 "HTML list item tag."
2442 "<li>" _ (if sgml-xml-mode "</li>"))
2444 (define-skeleton html-paragraph
2445 "HTML paragraph tag."
2448 "<p>" _ (if sgml-xml-mode "</p>"))
2450 (define-skeleton html-checkboxes
2451 "Group of connected checkbox inputs."
2456 "<input type=\"" (identity "checkbox") ; see comment above about identity
2457 "\" name=\"" (or v1 (setq v1 (skeleton-read "Name: ")))
2458 "\" value=\"" str ?\"
2459 (when (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 v2 (setq v2 (if (y-or-n-p "Newline after text? ")
2465 (funcall skeleton-transformation-function
2466 (if sgml-xml-mode "<br />" "<br>"))
2470 (define-skeleton html-radio-buttons
2471 "Group of connected radio button inputs."
2476 "<input type=\"" (identity "radio") ; see comment above about identity
2477 "\" name=\"" (or (car v2) (setcar v2 (skeleton-read "Name: ")))
2478 "\" value=\"" str ?\"
2479 (when (and (not v1) (setq v1 (y-or-n-p "Set \"checked\" attribute? ")))
2480 (funcall skeleton-transformation-function
2481 (if sgml-xml-mode " checked=\"checked\"" " checked")))
2482 (if sgml-xml-mode " />" ">")
2483 (skeleton-read "Text: " (capitalize str))
2484 (or (cdr v2) (setcdr v2 (if (y-or-n-p "Newline after text? ")
2485 (funcall skeleton-transformation-function
2486 (if sgml-xml-mode "<br />" "<br>"))
2490 (define-skeleton html-navigational-links
2491 "Group of navigational links."
2495 "<li><a href=\"" (skeleton-read "URL: " "#") "\">"
2496 (skeleton-read "Title: ") "</a>"
2497 (if sgml-xml-mode (if sgml-xml-mode "</li>")) \n
2501 (define-skeleton html-html5-template
2502 "Initial HTML5 template"
2504 "<!DOCTYPE html>" \n
2505 "<html lang=\"en\">" \n
2507 "<meta charset=\"utf-8\">" \n
2508 "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">" \n
2509 "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">" \n
2510 "<title>" (skeleton-read "Page Title: ") "</title>" \n
2513 "<div id=\"app\"></div>" \n
2517 (provide 'sgml-mode)
2519 ;;; sgml-mode.el ends here