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 <https://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.
37 (eval-when-compile (require 'subr-x
))
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'.")
345 (defconst sgml-syntax-propertize-rules
346 (syntax-propertize-precompile-rules
347 ;; Use the `b' style of comments to avoid interference with the -- ... --
348 ;; comments recognized when `sgml-specials' includes ?-.
349 ;; FIXME: beware of <!--> blabla <!--> !!
350 ("\\(<\\)!--" (1 "< b"))
351 ("--[ \t\n]*\\(>\\)" (1 "> b"))
352 ("\\(<\\)[?!]" (1 (prog1 "|>"
353 (sgml-syntax-propertize-inside end
))))
354 ;; Double quotes outside of tags should not introduce strings.
355 ;; Be careful to call `syntax-ppss' on a position before the one we're
356 ;; going to change, so as not to need to flush the data we just computed.
357 ("\"" (0 (if (prog1 (zerop (car (syntax-ppss (match-beginning 0))))
358 (goto-char (match-end 0)))
359 (string-to-syntax ".")))))))
361 (defun sgml-syntax-propertize (start end
)
362 "Syntactic keywords for `sgml-mode'."
364 (sgml-syntax-propertize-inside end
)
366 (syntax-propertize-rules sgml-syntax-propertize-rules
)
369 (defun sgml-syntax-propertize-inside (end)
370 (let ((ppss (syntax-ppss)))
373 (let ((endre (save-excursion
374 (goto-char (nth 8 ppss
))
376 ((looking-at-p "<!\\[CDATA\\[") "]]>")
377 ((looking-at-p "<\\?") (if sgml-xml-mode
"\\?>" ">"))
379 (when (re-search-forward endre end
'move
)
380 (put-text-property (1- (point)) (point)
381 'syntax-table
(string-to-syntax "|<"))))))))
384 (defvar sgml-face-tag-alist
()
385 "Alist of face and tag name for facemenu.")
387 (defvar sgml-tag-face-alist
()
388 "Tag names and face or list of faces to fontify with when invisible.
389 When `font-lock-maximum-decoration' is 1 this is always used for fontifying.
390 When more these are fontified together with `sgml-font-lock-keywords'.")
392 (defvar sgml-display-text
()
393 "Tag names as lowercase symbols, and display string when invisible.")
396 (defvar sgml-tags-invisible nil
)
398 (defcustom sgml-tag-alist
399 '(("![" ("ignore" t
) ("include" t
))
404 "Alist of tag names for completing read and insertion rules.
405 This alist is made up as
410 TAGRULE is a list of optionally t (no endtag) or `\\n' (separate endtag by
411 newlines) or a skeleton with nil, t or `\\n' in place of the interactor
412 followed by an ATTRIBUTERULE (for an always present attribute) or an
415 The attribute alist is made up as
417 ((\"attribute\" . ATTRIBUTERULE)
420 ATTRIBUTERULE is a list of optionally t (no value when no input) followed by
421 an optional alist of possible values."
422 :type
'(repeat (cons (string :tag
"Tag Name")
423 (repeat :tag
"Tag Rule" sexp
)))
425 (put 'sgml-tag-alist
'risky-local-variable t
)
427 (defcustom sgml-tag-help
428 '(("!" .
"Empty declaration for comment")
429 ("![" .
"Embed declarations with parser directive")
430 ("!attlist" .
"Tag attributes declaration")
431 ("!doctype" .
"Document type (DTD) declaration")
432 ("!element" .
"Tag declaration")
433 ("!entity" .
"Entity (macro) declaration"))
434 "Alist of tag name and short description."
435 :type
'(repeat (cons (string :tag
"Tag Name")
436 (string :tag
"Description")))
439 (defvar sgml-empty-tags nil
440 "List of tags whose !ELEMENT definition says EMPTY.")
442 (defvar sgml-unclosed-tags nil
443 "List of tags whose !ELEMENT definition says the end-tag is optional.")
445 (defun sgml-xml-guess ()
446 "Guess whether the current buffer is XML. Return non-nil if so."
448 (goto-char (point-min))
449 (or (string= "xml" (file-name-extension (or buffer-file-name
"")))
450 ;; Maybe the buffer-size check isn't needed, I don't know.
451 (and (zerop (buffer-size))
452 (string= "xhtml" (file-name-extension (or buffer-file-name
""))))
453 (looking-at "\\s-*<\\?xml")
454 (when (re-search-forward
457 '("<!DOCTYPE" "\\(\\w+\\)" "\\(\\w+\\)"
458 "\"\\([^\"]+\\)\"" "\"\\([^\"]+\\)\"")
461 (string-match "X\\(HT\\)?ML" (match-string 3))))))
463 (defvar v2
) ; free for skeleton
465 (defun sgml-comment-indent-new-line (&optional soft
)
466 (let ((comment-start "-- ")
467 (comment-start-skip "\\(<!\\)?--[ \t]*")
469 (comment-style 'plain
))
470 (comment-indent-new-line soft
)))
472 (defun sgml-mode-facemenu-add-face-function (face _end
)
473 (let ((tag-face (cdr (assq face sgml-face-tag-alist
))))
475 (setq tag-face
(funcall skeleton-transformation-function tag-face
))
476 (setq facemenu-end-add-face
(concat "</" tag-face
">"))
477 (concat "<" tag-face
">"))
481 (memq (caar face
) '(:foreground
:background
)))
482 (setq facemenu-end-add-face
"</span>")
483 (format "<span style=\"%s:%s\">"
484 (if (eq (caar face
) :foreground
)
489 (error "Face not configured for %s mode"
490 (format-mode-line mode-name
))))))
492 (defun sgml-fill-nobreak ()
493 "Don't break between a tag name and its first argument.
494 This function is designed for use in `fill-nobreak-predicate'.
496 <a href=\"some://where\" type=\"text/plain\">
498 | no break here | but still allowed here"
500 (skip-chars-backward " \t")
501 (and (not (zerop (skip-syntax-backward "w_")))
502 (skip-chars-backward "/?!")
503 (eq (char-before) ?
<))))
505 (defvar tildify-space-string
)
506 (defvar tildify-foreach-region-function
)
509 (define-derived-mode sgml-mode text-mode
'(sgml-xml-mode "XML" "SGML")
510 "Major mode for editing SGML documents.
512 Keys <, &, SPC within <>, \", / and \\=' can be electric depending on
515 An argument of N to a tag-inserting command means to wrap it around
516 the next N words. In Transient Mark mode, when the mark is active,
517 N defaults to -1, which means to wrap it around the current region.
519 If you like upcased tags, put (setq sgml-transformation-function \\='upcase)
522 Use \\[sgml-validate] to validate your document with an SGML parser.
524 Do \\[describe-variable] sgml- SPC to see available variables.
525 Do \\[describe-key] on the following bindings to discover what they do.
527 (make-local-variable 'sgml-saved-validate-command
)
528 (make-local-variable 'facemenu-end-add-face
)
529 ;; If encoding does not allow non-break space character, use reference.
530 ;; FIXME: Perhaps use if possible (e.g. when we know its HTML)?
531 (setq-local tildify-space-string
532 (if (equal (decode-coding-string
533 (encode-coding-string " " buffer-file-coding-system
)
534 buffer-file-coding-system
) " ")
536 ;; FIXME: Use the fact that we're parsing the document already
537 ;; rather than using regex-based filtering.
538 (setq-local tildify-foreach-region-function
540 'tildify-foreach-ignore-environments
541 `((,(eval-when-compile
544 (regexp-opt '("pre" "dfn" "code" "samp" "kbd" "var"
545 "PRE" "DFN" "CODE" "SAMP" "KBD" "VAR"))
550 ;;(make-local-variable 'facemenu-remove-face-function)
551 ;; A start or end tag by itself on a line separates a paragraph.
552 ;; This is desirable because SGML discards a newline that appears
553 ;; immediately after a start tag or immediately before an end tag.
554 (setq-local paragraph-start
(concat "[ \t]*$\\|\
555 [ \t]*</?\\(" sgml-name-re sgml-attrs-re
"\\)?>"))
556 (setq-local paragraph-separate
(concat paragraph-start
"$"))
557 (setq-local adaptive-fill-regexp
"[ \t]*")
558 (add-hook 'fill-nobreak-predicate
'sgml-fill-nobreak nil t
)
559 (setq-local indent-line-function
'sgml-indent-line
)
560 (setq-local comment-start
"<!-- ")
561 (setq-local comment-end
" -->")
562 (setq-local comment-indent-function
'sgml-comment-indent
)
563 (setq-local comment-line-break-function
'sgml-comment-indent-new-line
)
564 (setq-local skeleton-further-elements
'((completion-ignore-case t
)))
565 (setq-local skeleton-end-hook
568 (not (or (eq v2
'\n) (eq (car-safe v2
) '\n)))
569 (newline-and-indent))))
570 (setq font-lock-defaults
'((sgml-font-lock-keywords
571 sgml-font-lock-keywords-1
572 sgml-font-lock-keywords-2
)
574 (setq-local syntax-propertize-function
#'sgml-syntax-propertize
)
575 (setq-local facemenu-add-face-function
'sgml-mode-facemenu-add-face-function
)
576 (setq-local sgml-xml-mode
(sgml-xml-guess))
577 (unless sgml-xml-mode
578 (setq-local skeleton-transformation-function sgml-transformation-function
))
579 ;; This will allow existing comments within declarations to be
581 ;; I can't find a clear description of SGML/XML comments, but it seems that
582 ;; the only reliable ones are <!-- ... --> although it's not clear what
583 ;; "..." can contain. It used to accept -- ... -- as well, but that was
584 ;; apparently a mistake.
585 (setq-local comment-start-skip
"<!--[ \t]*")
586 (setq-local comment-end-skip
"[ \t]*--[ \t\n]*>")
587 ;; This definition has an HTML leaning but probably fits well for other modes.
588 (setq imenu-generic-expression
590 ,(concat "<!\\(element\\|entity\\)[ \t\n]+%?[ \t\n]*\\("
594 ,(concat "<[^>]+[ \t\n]+[Ii][Dd]=\\(['\"]"
595 (if sgml-xml-mode
"" "?")
596 "\\)\\(" sgml-name-re
"\\)\\1")
599 ,(concat "<[^>]+[ \t\n]+[Nn][Aa][Mm][Ee]=\\(['\"]"
600 (if sgml-xml-mode
"" "?")
601 "\\)\\(" sgml-name-re
"\\)\\1")
604 (defun sgml-comment-indent ()
605 (if (looking-at "--") comment-column
0))
607 (defun sgml-slash (arg)
608 "Insert ARG slash characters.
609 Behaves electrically if `sgml-quick-keys' is non-nil."
612 ((not (and (eq (char-before) ?
<) (= arg
1)))
613 (sgml-slash-matching arg
))
614 ((eq sgml-quick-keys
'indent
)
616 (indent-according-to-mode))
617 ((eq sgml-quick-keys
'close
)
621 (sgml-slash-matching arg
))))
623 (defun sgml-slash-matching (arg)
624 "Insert `/' and display any previous matching `/'.
625 Two `/'s are treated as matching if the first `/' ends a net-enabling
626 start tag, and the second `/' is the corresponding null end tag."
630 (let ((oldpos (point))
635 (if sgml-slash-distance
636 (narrow-to-region (max (point-min)
637 (- (point) sgml-slash-distance
))
639 (if (and (re-search-backward sgml-start-tag-regex
(point-min) t
)
640 (eq (match-end 0) (1- oldpos
)))
642 (goto-char (1- oldpos
))
643 (while (and (not blinkpos
)
644 (search-backward "/" (point-min) t
))
645 (let ((tagend (save-excursion
646 (if (re-search-backward sgml-start-tag-regex
650 (if (eq tagend
(point))
652 (setq blinkpos
(point))
653 (setq level
(1- level
)))
654 (setq level
(1+ level
)))))))
657 (if (pos-visible-in-window-p)
659 (message "Matches %s"
660 (buffer-substring (line-beginning-position)
661 (1+ blinkpos
)))))))))
663 ;; Why doesn't this use the iso-cvt table or, preferably, generate the
664 ;; inverse of the extensive table in the SGML Quail input method? -- fx
665 ;; I guess that's moot since it only works with Latin-1 anyhow.
666 (defun sgml-name-char (&optional char
)
667 "Insert a symbolic character name according to `sgml-char-names'.
668 Non-ASCII chars may be inserted either with the meta key, as in M-SPC for
669 no-break space or M-- for a soft hyphen; or via an input method or
670 encoded keyboard operation."
674 (setq char
(read-quoted-char "Enter char or octal number")))
680 (defun sgml-namify-char ()
681 "Change the char before point into its `&name;' equivalent.
682 Uses `sgml-char-names'."
684 (let* ((char (char-before))
687 ((null char
) (error "No char before point"))
688 ((< char
256) (or (aref sgml-char-names char
) char
))
689 ((aref sgml-char-names-table char
))
690 ((encode-char char
'ucs
)))))
692 (error "Don't know the name of `%c'" char
)
694 (insert (format (if (numberp name
) "&#%d;" "&%s;") name
)))))
696 (defun sgml-name-self ()
697 "Insert a symbolic character name according to `sgml-char-names'."
699 (sgml-name-char last-command-event
))
701 (defun sgml-maybe-name-self ()
702 "Insert a symbolic character name according to `sgml-char-names'."
704 (if sgml-name-8bit-mode
705 (sgml-name-char last-command-event
)
706 (self-insert-command 1)))
708 (defun sgml-name-8bit-mode ()
709 "Toggle whether to insert named entities instead of non-ASCII characters.
710 This only works for Latin-1 input."
712 (setq sgml-name-8bit-mode
(not sgml-name-8bit-mode
))
713 (message "sgml name entity mode is now %s"
714 (if sgml-name-8bit-mode
"ON" "OFF")))
716 ;; When an element of a skeleton is a string "str", it is passed
717 ;; through `skeleton-transformation-function' and inserted.
718 ;; If "str" is to be inserted literally, one should obtain it as
719 ;; the return value of a function, e.g. (identity "str").
721 (defvar sgml-tag-last nil
)
722 (defvar sgml-tag-history nil
)
723 (define-skeleton sgml-tag
724 "Prompt for a tag and insert it, optionally with attributes.
725 Completion and configuration are done according to `sgml-tag-alist'.
726 If you like tags and attributes in uppercase, customize
727 `sgml-transformation-function' to `upcase'."
728 (funcall (or skeleton-transformation-function
'identity
)
731 (if (> (length sgml-tag-last
) 0)
732 (format "Tag (default %s): " sgml-tag-last
)
734 sgml-tag-alist nil nil nil
'sgml-tag-history sgml-tag-last
)))
736 (("") -
1 '(undo-boundary) (identity "<")) |
; see comment above
737 `(("") '(setq v2
(sgml-attributes ,str t
)) ?
>
741 '(("") " [ " _
" ]]"))
742 ((and (eq v2 t
) sgml-xml-mode
(member ,str sgml-empty-tags
))
744 ((or (and (eq v2 t
) (not sgml-xml-mode
)) (string-match "^[/!?]" ,str
))
747 ;; Make sure we don't fall into an infinite loop.
748 ;; For xhtml's `tr' tag, we should maybe use \n instead.
749 (if (eq v2 t
) (setq v2 nil
))
750 ;; We use `identity' to prevent skeleton from passing
751 ;; `str' through `skeleton-transformation-function' a second time.
752 '(("") v2 _ v2
"</" (identity ',str
) ?
> >))
754 (cons '("") (cdr v2
)))
756 (append '(("") (car v2
))
758 '(resume: (car v2
) _
"</" (identity ',str
) ?
> >))))))
760 (autoload 'skeleton-read
"skeleton")
762 (defun sgml-attributes (tag &optional quiet
)
763 "When at top level of a tag, interactively insert attributes.
765 Completion and configuration of TAG are done according to `sgml-tag-alist'.
766 If QUIET, do not print a message when there are no attributes for TAG."
767 (interactive (list (save-excursion (sgml-beginning-of-tag t
))))
768 (or (stringp tag
) (error "Wrong context for adding attribute"))
770 (let ((completion-ignore-case t
)
771 (alist (cdr (assoc (downcase tag
) sgml-tag-alist
)))
773 (if (or (symbolp (car alist
))
774 (symbolp (car (car alist
))))
775 (setq car
(car alist
)
778 (message "No attributes configured."))
779 (if (stringp (car alist
))
781 (insert (if (eq (preceding-char) ?\s
) "" ?\s
)
782 (funcall skeleton-transformation-function
(car alist
)))
784 (setq i
(length alist
))
787 (insert (funcall skeleton-transformation-function
789 (skeleton-read (lambda ()
793 (if (string= "" attribute
)
795 (sgml-value (assoc (downcase attribute
) alist
))
797 (if (eq (preceding-char) ?\s
)
801 (defun sgml-auto-attributes (arg)
802 "Self insert the character typed; at top level of tag, prompt for attributes.
803 With prefix argument, only self insert."
805 (let ((point (point))
808 (not sgml-tag-alist
) ; no message when nothing configured
809 (symbolp (setq tag
(save-excursion (sgml-beginning-of-tag t
))))
810 (eq (aref tag
0) ?
/))
811 (self-insert-command (prefix-numeric-value arg
))
812 (sgml-attributes tag
)
813 (setq last-command-event ?\s
)
814 (or (> (point) point
)
815 (self-insert-command 1)))))
817 (defun sgml-tag-help (&optional tag
)
818 "Display description of tag TAG. If TAG is omitted, use the tag at point."
820 (list (let ((def (save-excursion
821 (if (eq (following-char) ?
<) (forward-char))
822 (sgml-beginning-of-tag))))
823 (completing-read (if def
824 (format "Tag (default %s): " def
)
826 sgml-tag-alist nil nil nil
827 'sgml-tag-history def
))))
828 (or (and tag
(> (length tag
) 0))
830 (if (eq (following-char) ?
<)
832 (setq tag
(sgml-beginning-of-tag))))
834 (error "No tag selected"))
835 (setq tag
(downcase tag
))
837 (or (cdr (assoc (downcase tag
) sgml-tag-help
))
838 (and (eq (aref tag
0) ?
/)
839 (cdr (assoc (downcase (substring tag
1)) sgml-tag-help
)))
840 "No description available")))
842 (defun sgml-maybe-end-tag (&optional arg
)
843 "Name self unless in position to end a tag or a prefix ARG is given."
845 (if (or arg
(eq (car (sgml-lexical-context)) 'tag
))
846 (self-insert-command (prefix-numeric-value arg
))
849 (defun sgml-skip-tag-backward (arg)
850 "Skip to beginning of tag or matching opening tag if present.
851 With prefix argument ARG, repeat this ARG times.
852 Return non-nil if we skipped over matched tags."
854 ;; FIXME: use sgml-get-context or something similar.
857 (search-backward "<" nil t
)
858 (if (looking-at "</\\([^ \n\t>]+\\)")
859 ;; end tag, skip any nested pairs
860 (let ((case-fold-search t
)
861 (re (concat "</?" (regexp-quote (match-string 1))
862 ;; Ignore empty tags like <foo/>.
863 "\\([^>]*[^/>]\\)?>")))
864 (while (and (re-search-backward re nil t
)
865 (eq (char-after (1+ (point))) ?
/))
867 (sgml-skip-tag-backward 1)))
872 (defun sgml-forward-sexp (n)
873 ;; This function is needed in major-modes such as nxml-mode where
874 ;; forward-sexp-function is used to give a more dwimish behavior to
875 ;; the `forward-sexp' command.
876 ;; Without it, we can end up with backtraces like:
877 ;; "get-text-property" (0xffffc0f0)
878 ;; "nxml-token-after" (0xffffc2ac)
879 ;; "nxml-forward-single-balanced-item" (0xffffc46c)
880 ;; "nxml-forward-balanced-item" (0xffffc61c)
881 ;; "forward-sexp" (0xffffc7f8)
882 ;; "sgml-parse-tag-backward" (0xffffc9c8)
883 ;; "sgml-lexical-context" (0xffffcba8)
884 ;; "sgml-mode-flyspell-verify" (0xffffcd74)
885 ;; "flyspell-word" (0xffffcf3c)
886 ;; "flyspell-post-command-hook" (0xffffd108)
887 ;; FIXME: should we also set the sgml-tag-syntax-table?
888 (let ((forward-sexp-function nil
))
891 (defvar sgml-electric-tag-pair-overlays nil
)
892 (defvar sgml-electric-tag-pair-timer nil
)
894 (defun sgml-electric-tag-pair-before-change-function (_beg end
)
898 (skip-chars-backward "[:alnum:]-_.:")
899 (if (and ;; (<= (point) beg) ; This poses problems for downcase-word.
900 (or (eq (char-before) ?
<)
901 (and (eq (char-before) ?
/)
902 (eq (char-before (1- (point))) ?
<)))
903 (null (get-char-property (point) 'text-clones
)))
904 (let* ((endp (eq (char-before) ?
/))
906 (cl-end (progn (skip-chars-forward "[:alnum:]-_.:") (point)))
909 (when (sgml-skip-tag-backward 1) (forward-char 1) t
)
910 (with-syntax-table sgml-tag-syntax-table
911 (let ((forward-sexp-function nil
))
913 (when (sgml-skip-tag-forward 1)
917 (clones (get-char-property (point) 'text-clones
)))
920 (equal (buffer-substring cl-start cl-end
)
921 (buffer-substring (point)
923 (skip-chars-forward "[:alnum:]-_.:")
925 (or (not endp
) (eq (char-after cl-end
) ?
>)))
927 (message "sgml-electric-tag-pair-before-change-function: deleting old OLs")
928 (mapc 'delete-overlay clones
))
929 (message "sgml-electric-tag-pair-before-change-function: new clone")
930 (text-clone-create cl-start cl-end
'spread
"[[:alnum:]-_.:]+")
931 (setq sgml-electric-tag-pair-overlays
932 (append (get-char-property (point) 'text-clones
)
933 sgml-electric-tag-pair-overlays
))))))
935 (error (message "Error in sgml-electric-pair-mode: %s" err
))))
937 (defun sgml-electric-tag-pair-flush-overlays ()
938 (while sgml-electric-tag-pair-overlays
939 (delete-overlay (pop sgml-electric-tag-pair-overlays
))))
941 (define-minor-mode sgml-electric-tag-pair-mode
942 "Toggle SGML Electric Tag Pair mode.
943 With a prefix argument ARG, enable the mode if ARG is positive,
944 and disable it otherwise. If called from Lisp, enable the mode
945 if ARG is omitted or nil.
947 SGML Electric Tag Pair mode is a buffer-local minor mode for use
948 with `sgml-mode' and related major modes. When enabled, editing
949 an opening markup tag automatically updates the closing tag."
951 (if sgml-electric-tag-pair-mode
953 (add-hook 'before-change-functions
954 'sgml-electric-tag-pair-before-change-function
956 (unless sgml-electric-tag-pair-timer
957 (setq sgml-electric-tag-pair-timer
958 (run-with-idle-timer 5 'repeat
'sgml-electric-tag-pair-flush-overlays
))))
959 (remove-hook 'before-change-functions
960 'sgml-electric-tag-pair-before-change-function
962 ;; We leave the timer running for other buffers.
966 (defun sgml-skip-tag-forward (arg)
967 "Skip to end of tag or matching closing tag if present.
968 With prefix argument ARG, repeat this ARG times.
969 Return t if after a closing tag."
971 ;; FIXME: Use sgml-get-context or something similar.
972 ;; It currently might jump to an unrelated </P> if the <P>
973 ;; we're skipping has no matching </P>.
975 (with-syntax-table sgml-tag-syntax-table
977 (skip-chars-forward "^<>")
978 (if (eq (following-char) ?
>)
980 (if (looking-at "<\\([^/ \n\t>]+\\)\\([^>]*[^/>]\\)?>")
981 ;; start tag, skip any nested same pairs _and_ closing tag
982 (let ((case-fold-search t
)
983 (re (concat "</?" (regexp-quote (match-string 1))
984 ;; Ignore empty tags like <foo/>.
985 "\\([^>]*[^/>]\\)?>"))
989 ;; FIXME: This re-search-forward will mistakenly match
990 ;; tag-like text inside attributes.
991 (while (and (re-search-forward re nil t
)
993 (eq (char-after (1+ (match-beginning 0))) ?
/)))
994 (goto-char (match-beginning 0))
995 (sgml-skip-tag-forward 1))
1001 (setq arg
(1- arg
)))
1004 (defsubst sgml-looking-back-at
(str)
1005 "Return t if the test before point matches STR."
1006 (let ((start (- (point) (length str
))))
1007 (and (>= start
(point-min))
1008 (equal str
(buffer-substring-no-properties start
(point))))))
1010 (defun sgml-delete-tag (arg)
1011 ;; FIXME: Should be called sgml-kill-tag or should not touch the kill-ring.
1012 "Delete tag on or after cursor, and matching closing or opening tag.
1013 With prefix argument ARG, repeat this ARG times."
1018 (if (looking-at "[ \t\n]*<")
1020 (if (eq (char-after (match-end 0)) ?
/)
1023 (setq close
(point))
1024 (goto-char (match-end 0))))
1026 (or (save-excursion (setq close
(sgml-beginning-of-tag)
1027 close
(and (stringp close
)
1028 (eq (aref close
0) ?
/)
1030 ;; not on closing tag
1031 (let ((point (point)))
1032 (sgml-skip-tag-backward 1)
1033 (if (or (not (eq (following-char) ?
<))
1036 (<= (point) point
)))
1037 (error "Not on or before tag")))))
1040 (sgml-skip-tag-backward 1)
1045 (when (and (sgml-skip-tag-forward 1)
1046 (not (sgml-looking-back-at "/>")))
1048 ;; Delete any resulting empty line. If we didn't kill-sexp,
1049 ;; this *should* do nothing, because we're right after the tag.
1050 (if (progn (forward-line 0) (looking-at "\\(?:[ \t]*$\\)\n?"))
1051 (delete-region (match-beginning 0) (match-end 0)))
1054 (if (progn (forward-line 0) (looking-at "\\(?:[ \t]*$\\)\n?"))
1055 (delete-region (match-beginning 0) (match-end 0)))))
1056 (setq arg
(1- arg
))))
1059 ;; Put read-only last to enable setting this even when read-only enabled.
1060 (or (get 'sgml-tag
'invisible
)
1062 (append '(invisible t
1063 cursor-sensor-functions
(sgml-cursor-sensor)
1066 (symbol-plist 'sgml-tag
))))
1068 (defun sgml-tags-invisible (arg)
1069 "Toggle visibility of existing tags."
1071 (let ((inhibit-read-only t
)
1073 (with-silent-modifications
1075 (goto-char (point-min))
1076 (if (setq-local sgml-tags-invisible
1078 (>= (prefix-numeric-value arg
) 0)
1079 (not sgml-tags-invisible
)))
1080 (while (re-search-forward sgml-tag-name-re nil t
)
1082 (cdr (assq (intern-soft (downcase (match-string 1)))
1083 sgml-display-text
)))
1084 (goto-char (match-beginning 0))
1085 (and (stringp string
)
1086 (not (overlays-at (point)))
1087 (let ((ol (make-overlay (point) (match-beginning 1))))
1088 (overlay-put ol
'before-string string
)
1089 (overlay-put ol
'sgml-tag t
)))
1090 (put-text-property (point)
1091 (progn (forward-list) (point))
1092 'category
'sgml-tag
))
1093 (let ((pos (point-min)))
1094 (while (< (setq pos
(next-overlay-change pos
)) (point-max))
1095 (dolist (ol (overlays-at pos
))
1096 (if (overlay-get ol
'sgml-tag
)
1097 (delete-overlay ol
)))))
1098 (remove-text-properties (point-min) (point-max) '(category nil
)))))
1099 (cursor-sensor-mode (if sgml-tags-invisible
1 -
1))
1100 (run-hooks 'sgml-tags-invisible-hook
)
1103 (defun sgml-cursor-sensor (window x dir
)
1104 ;; Show preceding or following hidden tag, depending of cursor direction (and
1105 ;; `dir' is not the direction in this sense).
1106 (when (eq dir
'entered
)
1108 (let* ((y (window-point window
))
1113 ((and (eq (char-before) ?
>)
1114 (or (not (eq (char-after) ?
<))
1116 (sgml-forward-sexp -
1))
1117 ((eq (char-after y
) ?
<)
1118 (sgml-forward-sexp 1)))
1120 (message "Invisible tag: %s"
1121 ;; Strip properties, otherwise, the text is invisible.
1122 (buffer-substring-no-properties
1126 (defun sgml-validate (command)
1127 "Validate an SGML document.
1128 Runs COMMAND, a shell command, in a separate process asynchronously
1129 with output going to the buffer `*compilation*'.
1130 You can then use the command \\[next-error] to find the next error message
1131 and move to the line in the SGML document that caused it."
1133 (list (read-string "Validate command: "
1134 (or sgml-saved-validate-command
1135 (concat sgml-validate-command
1137 (shell-quote-argument
1138 (let ((name (buffer-file-name)))
1140 (file-name-nondirectory name
)))))))))
1141 (setq sgml-saved-validate-command command
)
1142 (save-some-buffers (not compilation-ask-about-save
) nil
)
1143 (compilation-start command
))
1145 (defsubst sgml-at-indentation-p
()
1146 "Return true if point is at the first non-whitespace character on the line."
1148 (skip-chars-backward " \t")
1151 (defun sgml-lexical-context (&optional limit
)
1152 "Return the lexical context at point as (TYPE . START).
1153 START is the location of the start of the lexical element.
1154 TYPE is one of `string', `comment', `tag', `cdata', `pi', or `text'.
1156 Optional argument LIMIT is the position to start parsing from.
1157 If nil, start from a preceding tag at indentation."
1163 ;; Skip tags backwards until we find one at indentation
1164 (while (and (ignore-errors (sgml-parse-tag-backward))
1165 (not (sgml-at-indentation-p)))))
1166 (with-syntax-table sgml-tag-syntax-table
1167 (while (< (point) pos
)
1168 ;; When entering this loop we're inside text.
1169 (setq text-start
(point))
1170 (skip-chars-forward "^<" pos
)
1174 ;; We got to the end without seeing a tag.
1176 ((looking-at "<!\\[[A-Z]+\\[")
1177 ;; We've found a CDATA section or similar.
1178 (let ((cdata-start (point)))
1179 (unless (search-forward "]]>" pos
'move
)
1180 (list 0 nil nil
'cdata nil nil nil nil cdata-start
))))
1181 ((looking-at comment-start-skip
)
1182 ;; parse-partial-sexp doesn't handle <!-- comments -->,
1183 ;; or only if ?- is in sgml-specials, so match explicitly
1184 (let ((start (point)))
1185 (unless (re-search-forward comment-end-skip pos
'move
)
1186 (list 0 nil nil nil t nil nil nil start
))))
1187 ((and sgml-xml-mode
(looking-at "<\\?"))
1188 ;; Processing Instructions.
1189 ;; In SGML, it's basically a normal tag of the form
1190 ;; <?NAME ...> but in XML, it takes the form <? ... ?>.
1191 (let ((pi-start (point)))
1192 (unless (search-forward "?>" pos
'move
)
1193 (list 0 nil nil
'pi nil nil nil nil pi-start
))))
1195 ;; We've reached a tag. Parse it.
1196 ;; FIXME: Handle net-enabling start-tags
1197 (parse-partial-sexp (point) pos
0))))))
1199 ((memq (nth 3 state
) '(cdata pi
)) (cons (nth 3 state
) (nth 8 state
)))
1200 ((nth 3 state
) (cons 'string
(nth 8 state
)))
1201 ((nth 4 state
) (cons 'comment
(nth 8 state
)))
1202 ((and state
(> (nth 0 state
) 0)) (cons 'tag
(nth 1 state
)))
1203 (t (cons 'text text-start
))))))
1205 (defun sgml-beginning-of-tag (&optional only-immediate
)
1206 "Skip to beginning of tag and return its name.
1207 If this can't be done, return nil."
1208 (let ((context (sgml-lexical-context)))
1209 (if (eq (car context
) 'tag
)
1211 (goto-char (cdr context
))
1212 (when (looking-at sgml-tag-name-re
)
1213 (match-string-no-properties 1)))
1214 (if only-immediate nil
1215 (when (not (eq (car context
) 'text
))
1216 (goto-char (cdr context
))
1217 (sgml-beginning-of-tag t
))))))
1219 (defun sgml-value (alist)
1220 "Interactively insert value taken from attribute-rule ALIST.
1221 See `sgml-tag-alist' for info about attribute rules."
1222 (setq alist
(cdr alist
))
1223 (if (stringp (car alist
))
1224 (insert "=\"" (car alist
) ?
\")
1225 (if (and (eq (car alist
) t
) (not sgml-xml-mode
))
1228 (setq alist
(skeleton-read (lambda ()
1230 "Value: " (cdr alist
)))))
1231 (if (string< "" alist
)
1236 (insert (skeleton-read (lambda ()
1237 (completing-read "Value: " alist
))))
1239 (insert (skeleton-read '(read-string "Value: ")))))
1242 (defun sgml-quote (start end
&optional unquotep
)
1243 "Quote SGML text in region START ... END.
1244 Only &, < and > are quoted, the rest is left untouched.
1245 With prefix argument UNQUOTEP, unquote the region."
1246 (interactive "r\nP")
1248 (narrow-to-region start end
)
1249 (goto-char (point-min))
1251 ;; FIXME: We should unquote other named character references as well.
1252 (while (re-search-forward
1253 "\\(&\\(amp\\|\\(l\\|\\(g\\)\\)t\\)\\)[][<>&;\n\t \"%!'(),/=?]"
1255 (replace-match (if (match-end 4) ">" (if (match-end 3) "<" "&")) t t
1256 nil
(if (eq (char-before (match-end 0)) ?\
;) 0 1)))
1257 (while (re-search-forward "[&<>]" nil t
)
1258 (replace-match (cdr (assq (char-before) '((?
& .
"&")
1263 (defun sgml-pretty-print (beg end
)
1264 "Simple-minded pretty printer for SGML.
1265 Re-indents the code and inserts newlines between BEG and END.
1266 You might want to turn on `auto-fill-mode' to get better results."
1268 ;; - insert newline between some start-tag and text.
1269 ;; - don't insert newline in front of some end-tags.
1277 ;; Don't use narrowing because it screws up auto-indent.
1278 (setq end
(copy-marker end t
))
1279 (with-syntax-table sgml-tag-syntax-table
1280 (while (re-search-forward "<" end t
)
1281 (goto-char (match-beginning 0))
1282 (unless (or ;;(looking-at "</")
1283 (progn (skip-chars-backward " \t") (bolp)))
1284 (reindent-then-newline-and-indent))
1285 (sgml-forward-sexp 1)))
1286 ;; (indent-region beg end)
1292 (cl-defstruct (sgml-tag
1293 (:constructor sgml-make-tag
(type start end name
)))
1294 type start end name
)
1296 (defsubst sgml-parse-tag-name
()
1297 "Skip past a tag-name, and return the name."
1298 (buffer-substring-no-properties
1299 (point) (progn (skip-syntax-forward "w_") (point))))
1301 (defun sgml-tag-text-p (start end
)
1302 "Return non-nil if text between START and END is a tag.
1303 Checks among other things that the tag does not contain spurious
1304 unquoted < or > chars inside, which would indicate that it
1305 really isn't a tag after all."
1307 (with-syntax-table sgml-tag-syntax-table
1308 (let ((pps (parse-partial-sexp start end
2)))
1309 (and (= (nth 0 pps
) 0))))))
1311 (defun sgml--find-<>-backward
(limit)
1312 "Search backward for a '<' or '>' character.
1313 The character must have open or close syntax.
1314 Returns t if found, nil otherwise."
1316 (while (re-search-backward "[<>]" limit
'move
)
1317 ;; If this character has "open" or "close" syntax, then we've
1318 ;; found the one we want.
1319 (when (memq (syntax-class (syntax-after (point))) '(4 5))
1320 (throw 'found t
)))))
1322 (defun sgml-parse-tag-backward (&optional limit
)
1323 "Parse an SGML tag backward, and return information about the tag.
1324 Assume that parsing starts from within a textual context.
1325 Leave point at the beginning of the tag."
1327 (let (tag-type tag-start tag-end name
)
1328 (or (sgml--find-<>-backward limit
)
1329 (error "No tag found"))
1330 (when (eq (char-after) ?
<)
1331 ;; Oops!! Looks like we were not in a textual context after all!.
1332 ;; Let's try to recover.
1333 ;; Remember the tag-start so we don't need to look for it later.
1334 ;; This is not just an optimization but also makes sure we don't get
1335 ;; stuck in infloops in cases where "looking back for <" would not go
1337 (setq tag-start
(point))
1338 (with-syntax-table sgml-tag-syntax-table
1339 (let ((pos (point)))
1341 ;; FIXME: This does not correctly skip over PI an CDATA tags.
1342 (sgml-forward-sexp 1)
1344 ;; This < seems to be just a spurious one, let's ignore it.
1346 (throw 'found
(sgml-parse-tag-backward limit
))))
1347 ;; Check it is really a tag, without any extra < or > inside.
1348 (unless (sgml-tag-text-p pos
(point))
1350 (throw 'found
(sgml-parse-tag-backward limit
)))
1351 (forward-char -
1))))
1352 (setq tag-end
(1+ (point)))
1354 ((sgml-looking-back-at "--") ; comment
1355 (setq tag-type
'comment
1356 tag-start
(or tag-start
(search-backward "<!--" nil t
))))
1357 ((sgml-looking-back-at "]]") ; cdata
1358 (setq tag-type
'cdata
1359 tag-start
(or tag-start
1360 (re-search-backward "<!\\[[A-Z]+\\[" nil t
))))
1361 ((sgml-looking-back-at "?") ; XML processing-instruction
1363 ;; IIUC: SGML processing instructions take the form <?foo ...>
1364 ;; i.e. a "normal" tag, handled below. In XML this is changed
1365 ;; to <?foo ... ?> where "..." can contain < and > and even <?
1366 ;; but not ?>. This means that when parsing backward, there's
1367 ;; no easy way to make sure that we find the real beginning of
1369 tag-start
(or tag-start
(search-backward "<?" nil t
))))
1373 (with-syntax-table sgml-tag-syntax-table
1376 (sgml-forward-sexp -
1)
1378 ;; This > isn't really the end of a tag. Skip it.
1379 (goto-char (1- tag-end
))
1380 (throw 'found
(sgml-parse-tag-backward limit
))))
1382 (goto-char (1+ tag-start
))
1384 (?
! (setq tag-type
'decl
)) ; declaration
1385 (??
(setq tag-type
'pi
)) ; processing-instruction
1386 (?%
(setq tag-type
'jsp
)) ; JSP tags
1389 (setq tag-type
'close
1390 name
(sgml-parse-tag-name)))
1391 (_ ; open or empty tag
1392 (setq tag-type
'open
1393 name
(sgml-parse-tag-name))
1394 (if (or (eq ?
/ (char-before (- tag-end
1)))
1395 (sgml-empty-tag-p name
))
1396 (setq tag-type
'empty
))))))
1397 (goto-char tag-start
)
1398 (sgml-make-tag tag-type tag-start tag-end name
))))
1400 (defun sgml-get-context (&optional until
)
1401 "Determine the context of the current position.
1402 By default, parse until we find a start-tag as the first thing on a line.
1403 If UNTIL is `empty', return even if the context is empty (i.e.
1404 we just skipped over some element and got to a beginning of line).
1406 The context is a list of tag-info structures. The last one is the tag
1407 immediately enclosing the current position.
1409 Point is assumed to be outside of any tag. If we discover that it's
1410 not the case, the first tag returned is the one inside which we are."
1411 (let ((here (point))
1416 ;; CONTEXT keeps track of the tag-stack
1417 ;; STACK keeps track of the end tags we've seen (and thus the start-tags
1418 ;; we'll have to ignore) when skipping over matching open..close pairs.
1419 ;; IGNORE is a list of tags that can be ignored because they have been
1420 ;; closed implicitly.
1421 (skip-chars-backward " \t\n") ; Make sure we're not at indentation.
1423 (and (not (eq until
'now
))
1425 (not (if until
(eq until
'empty
) context
))
1426 (not (sgml-at-indentation-p))
1428 (/= (point) (sgml-tag-start (car context
)))
1429 (sgml-unclosed-tag-p (sgml-tag-name (car context
)))))
1430 (setq tag-info
(ignore-errors (sgml-parse-tag-backward))))
1432 ;; This tag may enclose things we thought were tags. If so,
1435 (> (sgml-tag-end tag-info
)
1436 (sgml-tag-end (car context
))))
1437 (setq context
(cdr context
)))
1440 ((> (sgml-tag-end tag-info
) here
)
1441 ;; Oops!! Looks like we were not outside of any tag, after all.
1442 (push tag-info context
)
1446 ((eq (sgml-tag-type tag-info
) 'open
)
1449 (if (assoc-string (sgml-tag-name tag-info
) ignore t
)
1450 ;; There was an implicit end-tag.
1452 (push tag-info context
)
1453 ;; We're changing context so the tags implicitly closed inside
1454 ;; the previous context aren't implicitly closed here any more.
1455 ;; [ Well, actually it depends, but we don't have the info about
1456 ;; when it doesn't and when it does. --Stef ]
1458 ((eq t
(compare-strings (sgml-tag-name tag-info
) nil nil
1459 (car stack
) nil nil t
))
1460 (setq stack
(cdr stack
)))
1462 ;; The open and close tags don't match.
1463 (if (not sgml-xml-mode
)
1464 (unless (sgml-unclosed-tag-p (sgml-tag-name tag-info
))
1465 (message "Unclosed tag <%s>" (sgml-tag-name tag-info
))
1467 ;; We could just assume that the tag is simply not closed
1468 ;; but it's a bad assumption when tags *are* closed but
1469 ;; not properly nested.
1470 (while (and (cdr tmp
)
1471 (not (eq t
(compare-strings
1472 (sgml-tag-name tag-info
) nil nil
1473 (cadr tmp
) nil nil t
))))
1474 (setq tmp
(cdr tmp
)))
1475 (if (cdr tmp
) (setcdr tmp
(cddr tmp
)))))
1476 (message "Unmatched tags <%s> and </%s>"
1477 (sgml-tag-name tag-info
) (pop stack
)))))
1479 (if (and (null stack
) (sgml-unclosed-tag-p (sgml-tag-name tag-info
)))
1480 ;; This is a top-level open of an implicitly closed tag, so any
1481 ;; occurrence of such an open tag at the same level can be ignored
1482 ;; because it's been implicitly closed.
1483 (push (sgml-tag-name tag-info
) ignore
)))
1486 ((eq (sgml-tag-type tag-info
) 'close
)
1487 (if (sgml-empty-tag-p (sgml-tag-name tag-info
))
1488 (message "Spurious </%s>: empty tag" (sgml-tag-name tag-info
))
1489 (push (sgml-tag-name tag-info
) stack
)))
1495 (defun sgml-show-context (&optional full
)
1496 "Display the current context.
1497 If FULL is non-nil, parse back to the beginning of the buffer."
1499 (with-output-to-temp-buffer "*XML Context*"
1501 (let ((context (sgml-get-context)))
1504 (while (setq more
(sgml-get-context))
1505 (setq context
(nconc more context
)))))
1509 ;; Editing shortcuts
1511 (defun sgml-close-tag ()
1512 "Close current element.
1513 Depending on context, inserts a matching close-tag, or closes
1514 the current start-tag or the current comment or the current cdata, ..."
1516 (pcase (car (sgml-lexical-context))
1517 (`comment
(insert " -->"))
1518 (`cdata
(insert "]]>"))
1519 (`pi
(insert " ?>"))
1520 (`jsp
(insert " %>"))
1521 (`tag
(insert " />"))
1523 (let ((context (save-excursion (sgml-get-context))))
1526 (insert "</" (sgml-tag-name (car (last context
))) ">")
1527 (indent-according-to-mode)))))
1529 (error "Nothing to close"))))
1531 (defun sgml-empty-tag-p (tag-name)
1532 "Return non-nil if TAG-NAME is an implicitly empty tag."
1533 (and (not sgml-xml-mode
)
1534 (assoc-string tag-name sgml-empty-tags
'ignore-case
)))
1536 (defun sgml-unclosed-tag-p (tag-name)
1537 "Return non-nil if TAG-NAME is a tag for which an end-tag is optional."
1538 (and (not sgml-xml-mode
)
1539 (assoc-string tag-name sgml-unclosed-tags
'ignore-case
)))
1542 (defun sgml-calculate-indent (&optional lcon
)
1543 "Calculate the column to which this line should be indented.
1544 LCON is the lexical context, if any."
1545 (unless lcon
(setq lcon
(sgml-lexical-context)))
1547 ;; Indent comment-start markers inside <!-- just like comment-end markers.
1548 (if (and (eq (car lcon
) 'tag
)
1550 (save-excursion (goto-char (cdr lcon
)) (looking-at "<!--")))
1551 (setq lcon
(cons 'comment
(+ (cdr lcon
) 2))))
1556 ;; Go back to previous non-empty line.
1557 (while (and (> (point) (cdr lcon
))
1558 (zerop (forward-line -
1))
1559 (looking-at "[ \t]*$")))
1560 (if (> (point) (cdr lcon
))
1561 ;; Previous line is inside the string.
1562 (current-indentation)
1563 (goto-char (cdr lcon
))
1564 (1+ (current-column))))
1567 (let ((mark (looking-at "--")))
1568 ;; Go back to previous non-empty line.
1569 (while (and (> (point) (cdr lcon
))
1570 (zerop (forward-line -
1))
1571 (or (looking-at "[ \t]*$")
1572 (if mark
(not (looking-at "[ \t]*--"))))))
1573 (if (> (point) (cdr lcon
))
1574 ;; Previous line is inside the comment.
1575 (skip-chars-forward " \t")
1576 (goto-char (cdr lcon
))
1577 ;; Skip `<!' to get to the `--' with which we want to align.
1578 (search-forward "--")
1579 (goto-char (match-beginning 0)))
1580 (when (and (not mark
) (looking-at "--"))
1581 (forward-char 2) (skip-chars-forward " \t"))
1584 ;; We don't know how to indent it. Let's be honest about it.
1586 ;; We don't know how to indent it. Let's be honest about it.
1590 (goto-char (+ (cdr lcon
) sgml-attribute-offset
))
1591 (skip-chars-forward "^ \t\n") ;Skip tag name.
1592 (skip-chars-forward " \t")
1595 ;; This is the first attribute: indent.
1596 (goto-char (+ (cdr lcon
) sgml-attribute-offset
))
1597 (+ (current-column) sgml-basic-offset
)))
1600 (while (looking-at "</")
1601 (sgml-forward-sexp 1)
1602 (skip-chars-forward " \t"))
1603 (let* ((here (point))
1604 (unclosed (and ;; (not sgml-xml-mode)
1605 (looking-at sgml-tag-name-re
)
1606 (assoc-string (match-string 1)
1607 sgml-unclosed-tags
'ignore-case
)
1610 ;; If possible, align on the previous non-empty text line.
1611 ;; Otherwise, do a more serious parsing to find the
1612 ;; tag(s) relative to which we should be indenting.
1613 (if (and (not unclosed
) (skip-chars-backward " \t")
1614 (< (skip-chars-backward " \t\n") 0)
1615 (back-to-indentation)
1616 (> (point) (cdr lcon
)))
1619 (nreverse (sgml-get-context (if unclosed nil
'empty
)))))
1621 ;; Ignore previous unclosed start-tag in context.
1622 (while (and context unclosed
1623 (eq t
(compare-strings
1624 (sgml-tag-name (car context
)) nil nil
1625 unclosed nil nil t
)))
1626 (setq context
(cdr context
)))
1627 ;; Indent to reflect nesting.
1629 ;; If we were not in a text context after all, let's try again.
1630 ((and context
(> (sgml-tag-end (car context
)) here
))
1632 (sgml-calculate-indent
1633 (cons (if (memq (sgml-tag-type (car context
)) '(comment cdata
))
1634 (sgml-tag-type (car context
)) 'tag
)
1635 (sgml-tag-start (car context
)))))
1636 ;; Align on the first element after the nearest open-tag, if any.
1638 (goto-char (sgml-tag-end (car context
)))
1639 (skip-chars-forward " \t\n")
1640 (< (point) here
) (sgml-at-indentation-p))
1642 ;; ;; If the parsing failed, try to recover.
1643 ;; ((and (null context) (bobp)
1644 ;; (not (eq (char-after here) ?<)))
1646 ;; (if (and (looking-at "--[ \t\n]*>")
1647 ;; (re-search-backward "<!--" nil t))
1648 ;; ;; No wonder parsing failed: we're in a comment.
1649 ;; (sgml-calculate-indent (prog2 (goto-char (match-end 0))
1650 ;; (sgml-lexical-context)
1651 ;; (goto-char here)))
1652 ;; ;; We have no clue what's going on, let's be honest about it.
1654 ;; Otherwise, just follow the rules.
1658 (* sgml-basic-offset
(length context
)))))))
1661 (error "Unrecognized context %s" (car lcon
)))
1665 (defun sgml-indent-line ()
1666 "Indent the current line as SGML."
1668 (let* ((savep (point))
1671 (back-to-indentation)
1672 (if (>= (point) savep
) (setq savep nil
))
1673 (sgml-calculate-indent))))
1674 (if (null indent-col
)
1677 (save-excursion (indent-line-to indent-col
))
1678 (indent-line-to indent-col
)))))
1680 (defun sgml-guess-indent ()
1681 "Guess an appropriate value for `sgml-basic-offset'.
1682 Base the guessed indentation level on the first indented tag in the buffer.
1683 Add this to `sgml-mode-hook' for convenience."
1686 (goto-char (point-min))
1687 (if (re-search-forward "^\\([ \t]+\\)<" 500 'noerror
)
1689 (setq-local sgml-basic-offset
(1- (current-column)))
1690 (message "Guessed sgml-basic-offset = %d"
1694 (defun sgml-parse-dtd ()
1695 "Simplistic parse of the current buffer as a DTD.
1696 Currently just returns (EMPTY-TAGS UNCLOSED-TAGS)."
1697 (goto-char (point-min))
1700 (while (re-search-forward "<!ELEMENT[ \t\n]+\\([^ \t\n]+\\)[ \t\n]+[-O][ \t\n]+\\([-O]\\)[ \t\n]+\\([^ \t\n]+\\)" nil t
)
1702 ((string= (match-string 3) "EMPTY")
1703 (push (match-string-no-properties 1) empty
))
1704 ((string= (match-string 2) "O")
1705 (push (match-string-no-properties 1) unclosed
))))
1706 (setq empty
(sort (mapcar 'downcase empty
) 'string
<))
1707 (setq unclosed
(sort (mapcar 'downcase unclosed
) 'string
<))
1708 (list empty unclosed
)))
1712 (defcustom html-mode-hook nil
1713 "Hook run by command `html-mode'.
1714 `text-mode-hook' and `sgml-mode-hook' are run first."
1717 :options
'(html-autoview-mode))
1719 (defvar html-quick-keys sgml-quick-keys
1720 "Use C-c X combinations for quick insertion of frequent tags when non-nil.
1721 This defaults to `sgml-quick-keys'.
1722 This takes effect when first loading the library.")
1724 (defvar html-mode-map
1725 (let ((map (make-sparse-keymap))
1726 (menu-map (make-sparse-keymap "HTML")))
1727 (set-keymap-parent map sgml-mode-map
)
1728 (define-key map
"\C-c6" 'html-headline-6
)
1729 (define-key map
"\C-c5" 'html-headline-5
)
1730 (define-key map
"\C-c4" 'html-headline-4
)
1731 (define-key map
"\C-c3" 'html-headline-3
)
1732 (define-key map
"\C-c2" 'html-headline-2
)
1733 (define-key map
"\C-c1" 'html-headline-1
)
1734 (define-key map
"\C-c\r" 'html-paragraph
)
1735 (define-key map
"\C-c\n" 'html-line
)
1736 (define-key map
"\C-c\C-c-" 'html-horizontal-rule
)
1737 (define-key map
"\C-c\C-co" 'html-ordered-list
)
1738 (define-key map
"\C-c\C-cu" 'html-unordered-list
)
1739 (define-key map
"\C-c\C-cr" 'html-radio-buttons
)
1740 (define-key map
"\C-c\C-cc" 'html-checkboxes
)
1741 (define-key map
"\C-c\C-cl" 'html-list-item
)
1742 (define-key map
"\C-c\C-ch" 'html-href-anchor
)
1743 (define-key map
"\C-c\C-cn" 'html-name-anchor
)
1744 (define-key map
"\C-c\C-ci" 'html-image
)
1745 (when html-quick-keys
1746 (define-key map
"\C-c-" 'html-horizontal-rule
)
1747 (define-key map
"\C-co" 'html-ordered-list
)
1748 (define-key map
"\C-cu" 'html-unordered-list
)
1749 (define-key map
"\C-cr" 'html-radio-buttons
)
1750 (define-key map
"\C-cc" 'html-checkboxes
)
1751 (define-key map
"\C-cl" 'html-list-item
)
1752 (define-key map
"\C-ch" 'html-href-anchor
)
1753 (define-key map
"\C-cn" 'html-name-anchor
)
1754 (define-key map
"\C-ci" 'html-image
))
1755 (define-key map
"\C-c\C-s" 'html-autoview-mode
)
1756 (define-key map
"\C-c\C-v" 'browse-url-of-buffer
)
1757 (define-key map
[menu-bar html
] (cons "HTML" menu-map
))
1758 (define-key menu-map
[html-autoview-mode
]
1759 '("Toggle Autoviewing" . html-autoview-mode
))
1760 (define-key menu-map
[browse-url-of-buffer
]
1761 '("View Buffer Contents" . browse-url-of-buffer
))
1762 (define-key menu-map
[nil] '("--"))
1763 ;;(define-key menu-map "6" '("Heading 6" . html-headline-6))
1764 ;;(define-key menu-map "5" '("Heading 5" . html-headline-5))
1765 ;;(define-key menu-map "4" '("Heading 4" . html-headline-4))
1766 (define-key menu-map "3" '("Heading 3" . html-headline-3))
1767 (define-key menu-map "2" '("Heading 2" . html-headline-2))
1768 (define-key menu-map "1" '("Heading 1" . html-headline-1))
1769 (define-key menu-map "l" '("Radio Buttons" . html-radio-buttons))
1770 (define-key menu-map "c" '("Checkboxes" . html-checkboxes))
1771 (define-key menu-map "l" '("List Item" . html-list-item))
1772 (define-key menu-map "u" '("Unordered List" . html-unordered-list))
1773 (define-key menu-map "o" '("Ordered List" . html-ordered-list))
1774 (define-key menu-map "-" '("Horizontal Rule" . html-horizontal-rule))
1775 (define-key menu-map "\n" '("Line Break" . html-line))
1776 (define-key menu-map "\r" '("Paragraph" . html-paragraph))
1777 (define-key menu-map "i" '("Image" . html-image))
1778 (define-key menu-map "h" '("Href Anchor" . html-href-anchor))
1779 (define-key menu-map "n" '("Name Anchor" . html-name-anchor))
1781 "Keymap for commands for use in HTML mode.")
1783 (defvar html-face-tag-alist
1787 (mode-line . "rev"))
1788 "Value of `sgml-face-tag-alist' for HTML mode.")
1790 (defvar html-tag-face-alist
1793 ("blink" . highlight)
1796 ("h1" bold underline)
1797 ("h2" bold-italic underline)
1798 ("h3" italic underline)
1807 ("title" bold underline)
1811 "Value of `sgml-tag-face-alist' for HTML mode.")
1813 (defvar html-display-text
1817 "Value of `sgml-display-text' for HTML mode.")
1820 (defvar html-tag-alist
1821 (let* ((1-7 '(("1") ("2") ("3") ("4") ("5") ("6") ("7")))
1822 (1-9 `(,@1-7 ("8") ("9")))
1823 (align '(("align" ("left") ("center") ("right"))))
1824 (ialign '(("align" ("top") ("middle") ("bottom") ("left")
1826 (valign '(("top") ("middle") ("bottom") ("baseline")))
1827 (rel '(("next") ("previous") ("parent") ("subdocument") ("made")))
1828 (href '("href" ("ftp:") ("file:") ("finger:") ("gopher:") ("http:")
1829 ("mailto:") ("news:") ("rlogin:") ("telnet:") ("tn3270:")
1830 ("wais:") ("/cgi-bin/")))
1836 (list '((nil \n ("List item: " "<li>" str
1837 (if sgml-xml-mode "</li>") \n))))
1838 (shape '(("shape" ("rect") ("circle") ("poly") ("default"))))
1845 (cellhalign '(("align" ("left") ("center") ("right")
1846 ("justify") ("char"))
1847 ("char") ("charoff")))
1848 (cellvalign '(("valign" ("top") ("middle") ("bottom")
1850 ;; put ,-expressions first, else byte-compile chokes (as of V19.29)
1851 ;; and like this it's more efficient anyway
1852 `(("a" ,name ,@link)
1853 ("area" t ,@shape ("coords") ("href") ("nohref" "nohref") ("alt")
1854 ("tabindex") ("accesskey") ("onfocus") ("onblur"))
1856 ("col" t ,@cellhalign ,@cellvalign ("span") ("width"))
1857 ("colgroup" \n ,@cellhalign ,@cellvalign ("span") ("width"))
1861 ("font" nil "size" ("-1") ("+1") ("-2") ("+2") ,@1-7)
1862 ("form" (\n _ \n "<input type=\"submit\" value=\"\""
1863 (if sgml-xml-mode " />" ">"))
1864 ("action" ,@(cdr href)) ("method" ("get") ("post")))
1871 ("hr" t ("size" ,@1-9) ("width") ("noshade" t) ,@align)
1872 ("iframe" \n ,@ialign ("longdesc") ("name") ("src")
1873 ("frameborder" ("1") ("0")) ("marginwidth") ("marginheight")
1874 ("scrolling" ("yes") ("no") ("auto")) ("height") ("width"))
1875 ("img" t ("align" ,@valign ("texttop") ("absmiddle") ("absbottom"))
1876 ("src") ("alt") ("width" "1") ("height" "1")
1877 ("border" "1") ("vspace" "1") ("hspace" "1") ("ismap" t))
1878 ("input" t ,name ("accept") ("alt") ("autocomplete" ("on") ("off"))
1879 ("autofocus" t) ("checked" t) ("dirname") ("disabled" t) ("form")
1881 ("formenctype" ("application/x-www-form-urlencoded")
1882 ("multipart/form-data") ("text/plain"))
1883 ("formmethod" ("get") ("post"))
1884 ("formnovalidate" t)
1885 ("formtarget" ("_blank") ("_self") ("_parent") ("_top"))
1886 ("height") ("inputmode") ("list") ("max") ("maxlength") ("min")
1887 ("minlength") ("multiple" t) ("pattern") ("placeholder")
1888 ("readonly" t) ("required" t) ("size") ("src") ("step")
1889 ("type" ("hidden") ("text") ("search") ("tel") ("url") ("email")
1890 ("password") ("date") ("time") ("number") ("range") ("color")
1891 ("checkbox") ("radio") ("file") ("submit") ("image") ("reset")
1893 ("value") ("width"))
1896 ("ol" ,@list ("type" ("A") ("a") ("I") ("i") ("1")))
1900 "<option>" str (if sgml-xml-mode "</option>") \n))
1901 ,name ("size" ,@1-9) ("multiple" t))
1903 ((completing-read "Cell kind: " '(("td") ("th"))
1906 (if sgml-xml-mode (concat "<" str "></tr>")) \n))
1907 ("border" t ,@1-9) ("width" "10") ("cellpadding"))
1908 ("tbody" \n ,@cellhalign ,@cellvalign)
1910 ("textarea" ,name ("rows" ,@1-9) ("cols" ,@1-9))
1911 ("tfoot" \n ,@cellhalign ,@cellvalign)
1913 ("thead" \n ,@cellhalign ,@cellvalign)
1914 ("ul" ,@list ("type" ("disc") ("circle") ("square")))
1922 ("Item: " "<item>" str (if sgml-xml-mode "</item>") \n))
1928 ("src") ("crossorigin" ("anonymous") ("use-credentials"))
1929 ("preload" ("none") ("metadata") ("auto"))
1930 ("autoplay" "autoplay") ("mediagroup") ("loop" "loop")
1931 ("muted" "muted") ("controls" "controls"))
1934 ("bdo" nil ("lang") ("dir" ("ltr") ("rtl")))
1937 ("blockquote" \n ("cite"))
1938 ("body" \n ("background" ".gif") ("bgcolor" "#") ("text" "#")
1939 ("link" "#") ("alink" "#") ("vlink" "#"))
1940 ("box" (nil _ "<over>" _ (if sgml-xml-mode "</over>")))
1941 ("br" t ("clear" ("left") ("right")))
1942 ("button" nil ("name") ("value")
1943 ("type" ("submit") ("reset") ("button"))
1944 ("disabled" "disabled")
1945 ("tabindex") ("accesskey") ("onfocus") ("onblur"))
1946 ("canvas" \n ("width") ("height"))
1947 ("caption" ("valign" ("top") ("bottom")))
1952 ("dd" ,(not sgml-xml-mode))
1953 ("del" nil ("cite") ("datetime"))
1958 "<dt>" str (if sgml-xml-mode "</dt>")
1959 "<dd>" _ (if sgml-xml-mode "</dd>") \n)))
1960 ("dt" (t _ (if sgml-xml-mode "</dt>")
1961 "<dd>" (if sgml-xml-mode "</dd>") \n))
1963 ("embed" t ("src") ("type") ("width") ("height"))
1965 ("fn" "id" "fn") ;; Footnotes were deprecated in HTML 3.2
1967 ("frame" t ("longdesc") ("name") ("src")
1968 ("frameborder" ("1") ("0")) ("marginwidth") ("marginheight")
1969 ("noresize" "noresize") ("scrolling" ("yes") ("no") ("auto")))
1970 ("frameset" \n ("rows") ("cols") ("onload") ("onunload"))
1976 "<title>" (setq str (read-string "Title: ")) "</title>\n"
1978 "<body>\n<h1>" str "</h1>\n" _
1979 "\n<address>\n<a href=\"mailto:"
1981 "\">" (user-full-name) "</a>\n</address>\n"
1985 ("ins" nil ("cite") ("datetime"))
1986 ("isindex" t ("action") ("prompt"))
1988 ("label" nil ("for") ("accesskey") ("onfocus") ("onblur"))
1990 ("legend" nil ("accesskey"))
1991 ("li" ,(not sgml-xml-mode))
1996 ("meta" t ("http-equiv") ("name") ("content") ("scheme"))
1997 ("meter" nil ("value") ("min") ("max") ("low") ("high")
2003 ("object" \n ("declare" "declare") ("classid") ("codebase")
2004 ("data") ("type") ("codetype") ("archive") ("standby")
2005 ("height") ("width") ("usemap") ("name") ("tabindex"))
2006 ("optgroup" \n ("name") ("size") ("multiple" "multiple")
2007 ("disabled" "disabled") ("tabindex") ("onfocus") ("onblur")
2009 ("option" t ("value") ("label") ("selected" t))
2010 ("output" nil ("for") ("form") ("name"))
2012 ("param" t ("name") ("value")
2013 ("valuetype" ("data") ("ref") ("object")) ("type"))
2014 ("person") ;; Tag for person's name tag deprecated in HTML 3.2
2016 ("progress" nil ("value") ("max"))
2024 ("script" nil ("charset") ("type") ("src") ("defer" "defer"))
2027 ("source" t ("src") ("type") ("media"))
2040 ("style" \n ("type") ("media") ("title"))
2044 ("time" nil ("datetime"))
2048 ("kind" ("subtitles") ("captions") ("descriptions")
2049 ("chapters") ("metadata"))
2050 ("src") ("srclang") ("label") ("default"))
2055 ("src") ("crossorigin" ("anonymous") ("use-credentials"))
2056 ("poster") ("preload" ("none") ("metadata") ("auto"))
2057 ("autoplay" "autoplay") ("mediagroup") ("loop" "loop")
2058 ("muted" "muted") ("controls" "controls") ("width") ("height"))
2060 "Value of `sgml-tag-alist' for HTML mode.")
2062 (defvar html-tag-help
2064 ("a" . "Anchor of point or link elsewhere")
2065 ("abbr" . "Abbreviation")
2066 ("acronym" . "Acronym")
2067 ("address" . "Formatted mail address")
2068 ("area" . "Region of an image map")
2069 ("array" . "Math array")
2070 ("article" . "An independent part of document or site")
2071 ("aside" . "Secondary content related to surrounding content (e.g. page or article)")
2073 ("audio" . "Sound or audio stream")
2075 ("base" . "Base address for URLs")
2076 ("bdi" . "Text isolated for bidirectional formatting")
2077 ("bdo" . "Override text directionality")
2078 ("big" . "Font size")
2079 ("blink" . "Blinking text")
2080 ("blockquote" . "Indented quotation")
2081 ("body" . "Document body")
2082 ("box" . "Math fraction")
2083 ("br" . "Line break")
2084 ("button" . "Clickable button")
2085 ("canvas" . "Script generated graphics canvas")
2086 ("caption" . "Table caption")
2087 ("center" . "Centered text")
2088 ("changed" . "Change bars")
2089 ("cite" . "Citation of a document")
2090 ("code" . "Formatted source code")
2091 ("col" . "Group of attribute specifications for table columns")
2092 ("colgroup" . "Group of columns")
2093 ("datalist" . "A set of predefined options")
2094 ("dd" . "Definition of term")
2095 ("del" . "Deleted text")
2096 ("dfn" . "Defining instance of a term")
2097 ("dir" . "Directory list (obsolete)")
2098 ("div" . "Generic block-level container")
2099 ("dl" . "Definition list")
2100 ("dt" . "Term to be defined")
2101 ("em" . "Emphasized")
2102 ("embed" . "Embedded data in foreign format")
2103 ("fieldset" . "Group of related controls and labels")
2105 ("figa" . "Figure anchor")
2106 ("figcaption" . "Caption for a figure")
2107 ("figd" . "Figure description")
2108 ("figt" . "Figure text")
2109 ("figure" . "Self-contained content, often with a caption")
2110 ("fn" . "Footnote") ;; No one supports special footnote rendering.
2111 ("font" . "Font size")
2112 ("footer" . "Footer of a section")
2113 ("form" . "Form with input fields")
2114 ("frame" . "Frame in which another HTML document can be displayed")
2115 ("frameset" . "Container for frames")
2116 ("group" . "Document grouping")
2117 ("h1" . "Most important section headline")
2118 ("h2" . "Important section headline")
2119 ("h3" . "Section headline")
2120 ("h4" . "Minor section headline")
2121 ("h5" . "Unimportant section headline")
2122 ("h6" . "Least important section headline")
2123 ("head" . "Document header")
2124 ("header" . "Header of a section")
2125 ("hgroup" . "Group of headings - h1-h6 elements")
2126 ("hr" . "Horizontal rule")
2127 ("html" . "HTML Document")
2128 ("i" . "Italic face")
2129 ("iframe" . "Inline frame with a nested browsing context")
2130 ("img" . "Graphic image")
2131 ("input" . "Form input field")
2132 ("ins" . "Inserted text")
2133 ("isindex" . "Input field for index search")
2134 ("kbd" . "Keyboard example face")
2135 ("label" . "Caption for a user interface item")
2136 ("lang" . "Natural language")
2137 ("legend" . "Caption for a fieldset")
2138 ("li" . "List item")
2139 ("link" . "Link relationship")
2140 ("main" . "Main content of the document body")
2141 ("map" . "Image map (a clickable link area")
2142 ("mark" . "Highlighted text")
2143 ("math" . "Math formula")
2144 ("menu" . "List of commands")
2145 ("meta" . "Document properties")
2146 ("meter" . "Scalar measurement within a known range")
2147 ("mh" . "Form mail header")
2148 ("nav" . "Group of navigational links")
2149 ("nextid" . "Allocate new id")
2150 ("nobr" . "Text without line break")
2151 ("noframes" . "Content for user agents that don't support frames")
2152 ("noscript" . "Alternate content for when a script isn't executed")
2153 ("object" . "External resource")
2154 ("ol" . "Ordered list")
2155 ("optgroup" . "Group of options")
2156 ("option" . "Selection list item")
2157 ("output" . "Result of a calculation or user action")
2158 ("over" . "Math fraction rule")
2159 ("p" . "Paragraph start")
2160 ("panel" . "Floating panel")
2161 ("param" . "Parameters for an object")
2162 ("person" . "Person's name")
2163 ("pre" . "Preformatted fixed width text")
2164 ("progress" . "Completion progress of a task")
2166 ("rev" . "Reverse video")
2167 ("rp" . "Fallback text for when ruby annotations aren't supported")
2168 ("rt" . "Ruby text component of a ruby annotation")
2169 ("ruby" . "Ruby annotation")
2171 ("samp" . "Sample text")
2172 ("script" . "Executable script within a document")
2173 ("section" . "Section of a document")
2174 ("select" . "Selection list")
2175 ("small" . "Font size")
2176 ("source" . "Media resource for media elements")
2177 ("sp" . "Nobreak space")
2178 ("span" . "Generic inline container")
2179 ("strong" . "Standout text")
2180 ("style" . "Style information")
2181 ("sub" . "Subscript")
2182 ("summary" . "Summary, caption, or legend")
2183 ("sup" . "Superscript")
2184 ("table" . "Table with rows and columns")
2185 ("tb" . "Table vertical break")
2186 ("tbody" . "Table body")
2187 ("td" . "Table data cell")
2188 ("textarea" . "Form multiline edit area")
2189 ("tfoot" . "Table foot")
2190 ("th" . "Table header cell")
2191 ("thead" . "Table head")
2192 ("time" . "Content with optional machine-readable timestamp")
2193 ("title" . "Document title")
2194 ("tr" . "Table row separator")
2195 ("track" . "Timed text track for media elements")
2196 ("tt" . "Typewriter face")
2197 ("u" . "Underlined text")
2198 ("ul" . "Unordered list")
2199 ("var" . "Math variable face")
2200 ("video" . "Video or movie")
2201 ("wbr" . "Enable <br> within <nobr>"))
2202 "Value of variable `sgml-tag-help' for HTML mode.")
2204 (defvar outline-regexp)
2205 (defvar outline-heading-end-regexp)
2206 (defvar outline-level)
2208 (defun html-current-defun-name ()
2209 "Return the name of the last HTML title or heading, or nil."
2211 (if (re-search-backward
2214 "\\(?:[hH][0-6]\\|title\\|TITLE\\|Title\\)"
2217 "\\([^<\r\n]*[^ <\t\r\n]+\\)")
2219 (match-string-no-properties 1))))
2221 (defvar html--buffer-classes-cache nil
2222 "Cache for `html-current-buffer-classes'.
2223 When set, this should be a cons cell where the CAR is the
2224 buffer's tick counter (as produced by `buffer-modified-tick'),
2225 and the CDR is the list of class names found in the buffer.")
2226 (make-variable-buffer-local 'html--buffer-classes-cache)
2228 (defvar html--buffer-ids-cache nil
2229 "Cache for `html-current-buffer-ids'.
2230 When set, this should be a cons cell where the CAR is the
2231 buffer's tick counter (as produced by `buffer-modified-tick'),
2232 and the CDR is the list of class names found in the buffer.")
2233 (make-variable-buffer-local 'html--buffer-ids-cache)
2235 (defun html-current-buffer-classes ()
2236 "Return a list of class names used in the current buffer.
2237 The result is cached in `html--buffer-classes-cache'."
2238 (let ((tick (buffer-modified-tick)))
2239 (if (eq (car html--buffer-classes-cache) tick)
2240 (cdr html--buffer-classes-cache)
2241 (let* ((dom (libxml-parse-html-region (point-min) (point-max)))
2245 (when-let* ((class-list
2246 (cdr (assq 'class (dom-attributes el)))))
2247 (split-string class-list)))
2248 (dom-by-class dom ""))))
2249 (setq-local html--buffer-classes-cache (cons tick classes))
2252 (defun html-current-buffer-ids ()
2253 "Return a list of IDs used in the current buffer.
2254 The result is cached in `html--buffer-ids-cache'."
2255 (let ((tick (buffer-modified-tick)))
2256 (if (eq (car html--buffer-ids-cache) tick)
2257 (cdr html--buffer-ids-cache)
2259 (libxml-parse-html-region (point-min) (point-max)))
2263 (when-let* ((id-list
2264 (cdr (assq 'id (dom-attributes el)))))
2265 (split-string id-list)))
2266 (dom-by-id dom ""))))
2267 (setq-local html--buffer-ids-cache (cons tick ids))
2272 (define-derived-mode html-mode sgml-mode '(sgml-xml-mode "XHTML" "HTML")
2273 "Major mode based on SGML mode for editing HTML documents.
2274 This allows inserting skeleton constructs used in hypertext documents with
2275 completion. See below for an introduction to HTML. Use
2276 \\[browse-url-of-buffer] to see how this comes out. See also `sgml-mode' on
2277 which this is based.
2279 Do \\[describe-variable] html- SPC and \\[describe-variable] sgml- SPC to see available variables.
2281 To write fairly well formatted pages you only need to know few things. Most
2282 browsers have a function to read the source code of the page being seen, so
2283 you can imitate various tricks. Here's a very short HTML primer which you
2284 can also view with a browser to see what happens:
2286 <title>A Title Describing Contents</title> should be on every page. Pages can
2287 have <h1>Very Major Headlines</h1> through <h6>Very Minor Headlines</h6>
2288 <hr> Parts can be separated with horizontal rules.
2290 <p>Paragraphs only need an opening tag. Line breaks and multiple spaces are
2291 ignored unless the text is <pre>preformatted.</pre> Text can be marked as
2292 <b>bold</b>, <i>italic</i> or <u>underlined</u> using the normal M-o or
2293 Edit/Text Properties/Face commands.
2295 Pages can have <a name=\"SOMENAME\">named points</a> and can link other points
2296 to them with <a href=\"#SOMENAME\">see also somename</a>. In the same way <a
2297 href=\"URL\">see also URL</a> where URL is a filename relative to current
2298 directory, or absolute as in `http://www.cs.indiana.edu/elisp/w3/docs.html'.
2300 Images in many formats can be inlined with <img src=\"URL\">.
2302 If you mainly create your own documents, `sgml-specials' might be
2303 interesting. But note that some HTML 2 browsers can't handle `''.
2304 To work around that, do:
2305 (eval-after-load \"sgml-mode\" \\='(aset sgml-char-names ?\\=' nil))
2308 (setq-local sgml-display-text html-display-text)
2309 (setq-local sgml-tag-face-alist html-tag-face-alist)
2310 (setq-local sgml-tag-alist html-tag-alist)
2311 (setq-local sgml-face-tag-alist html-face-tag-alist)
2312 (setq-local sgml-tag-help html-tag-help)
2313 (setq-local outline-regexp "^.*<[Hh][1-6]\\>")
2314 (setq-local outline-heading-end-regexp "</[Hh][1-6]>")
2315 (setq-local outline-level
2316 (lambda () (char-before (match-end 0))))
2317 (setq-local add-log-current-defun-function #'html-current-defun-name)
2318 (setq-local sentence-end-base "[.?!][]\"'”)}]*\\(<[^>]*>\\)*")
2320 (when (fboundp 'libxml-parse-html-region)
2321 (defvar css-class-list-function)
2322 (setq-local css-class-list-function #'html-current-buffer-classes)
2323 (defvar css-id-list-function)
2324 (setq-local css-id-list-function #'html-current-buffer-ids))
2326 (setq imenu-create-index-function 'html-imenu-index)
2328 (setq-local sgml-empty-tags
2329 ;; From HTML-4.01's loose.dtd, parsed with
2330 ;; `sgml-parse-dtd', plus manual addition of "wbr".
2331 '("area" "base" "basefont" "br" "col" "frame" "hr" "img" "input"
2332 "isindex" "link" "meta" "param" "wbr"))
2333 (setq-local sgml-unclosed-tags
2334 ;; From HTML-4.01's loose.dtd, parsed with `sgml-parse-dtd'.
2335 '("body" "colgroup" "dd" "dt" "head" "html" "li" "option"
2336 "p" "tbody" "td" "tfoot" "th" "thead" "tr"))
2337 ;; It's for the user to decide if it defeats it or not -stef
2338 ;; (make-local-variable 'imenu-sort-function)
2339 ;; (setq imenu-sort-function nil) ; sorting the menu defeats the purpose
2342 (defvar html-imenu-regexp
2343 "\\s-*<h\\([1-9]\\)[^\n<>]*>\\(<[^\n<>]*>\\)*\\s-*\\([^\n<>]*\\)"
2344 "A regular expression matching a head line to be added to the menu.
2345 The first `match-string' should be a number from 1-9.
2346 The second `match-string' matches extra tags and is ignored.
2347 The third `match-string' will be the used in the menu.")
2349 (defun html-imenu-index ()
2350 "Return a table of contents for an HTML buffer for use with Imenu."
2353 (goto-char (point-min))
2354 (while (re-search-forward html-imenu-regexp nil t)
2356 (cons (cons (concat (make-string
2357 (* 2 (1- (string-to-number (match-string 1))))
2360 (line-beginning-position))
2362 (nreverse toc-index)))
2364 (define-minor-mode html-autoview-mode
2365 "Toggle viewing of HTML files on save (HTML Autoview mode).
2366 With a prefix argument ARG, enable HTML Autoview mode if ARG is
2367 positive, and disable it otherwise. If called from Lisp, enable
2368 the mode if ARG is omitted or nil.
2370 HTML Autoview mode is a buffer-local minor mode for use with
2371 `html-mode'. If enabled, saving the file automatically runs
2372 `browse-url-of-buffer' to view it."
2375 (if html-autoview-mode
2376 (add-hook 'after-save-hook 'browse-url-of-buffer nil t)
2377 (remove-hook 'after-save-hook 'browse-url-of-buffer t)))
2380 (define-skeleton html-href-anchor
2381 "HTML anchor tag with href attribute."
2383 ;; '(setq input "http:")
2384 "<a href=\"" str "\">" _ "</a>")
2386 (define-skeleton html-name-anchor
2387 "HTML anchor tag with name attribute."
2389 "<a name=\"" str "\""
2390 (if sgml-xml-mode (concat " id=\"" str "\""))
2393 (define-skeleton html-headline-1
2394 "HTML level 1 headline tags."
2398 (define-skeleton html-headline-2
2399 "HTML level 2 headline tags."
2403 (define-skeleton html-headline-3
2404 "HTML level 3 headline tags."
2408 (define-skeleton html-headline-4
2409 "HTML level 4 headline tags."
2413 (define-skeleton html-headline-5
2414 "HTML level 5 headline tags."
2418 (define-skeleton html-headline-6
2419 "HTML level 6 headline tags."
2423 (define-skeleton html-horizontal-rule
2424 "HTML horizontal rule tag."
2426 (if sgml-xml-mode "<hr />" "<hr>") \n)
2428 (define-skeleton html-image
2431 "<img src=\"" str "\" alt=\"" _ "\""
2432 (if sgml-xml-mode " />" ">"))
2434 (define-skeleton html-line
2435 "HTML line break tag."
2437 (if sgml-xml-mode "<br />" "<br>") \n)
2439 (define-skeleton html-ordered-list
2440 "HTML ordered list tags."
2443 "<li>" _ (if sgml-xml-mode "</li>") \n
2446 (define-skeleton html-unordered-list
2447 "HTML unordered list tags."
2450 "<li>" _ (if sgml-xml-mode "</li>") \n
2453 (define-skeleton html-list-item
2454 "HTML list item tag."
2457 "<li>" _ (if sgml-xml-mode "</li>"))
2459 (define-skeleton html-paragraph
2460 "HTML paragraph tag."
2463 "<p>" _ (if sgml-xml-mode "</p>"))
2465 (define-skeleton html-checkboxes
2466 "Group of connected checkbox inputs."
2471 "<input type=\"" (identity "checkbox") ; see comment above about identity
2472 "\" name=\"" (or v1 (setq v1 (skeleton-read "Name: ")))
2473 "\" value=\"" str ?\"
2474 (when (y-or-n-p "Set \"checked\" attribute? ")
2475 (funcall skeleton-transformation-function
2476 (if sgml-xml-mode " checked=\"checked\"" " checked")))
2477 (if sgml-xml-mode " />" ">")
2478 (skeleton-read "Text: " (capitalize str))
2479 (or v2 (setq v2 (if (y-or-n-p "Newline after text? ")
2480 (funcall skeleton-transformation-function
2481 (if sgml-xml-mode "<br />" "<br>"))
2485 (define-skeleton html-radio-buttons
2486 "Group of connected radio button inputs."
2491 "<input type=\"" (identity "radio") ; see comment above about identity
2492 "\" name=\"" (or (car v2) (setcar v2 (skeleton-read "Name: ")))
2493 "\" value=\"" str ?\"
2494 (when (and (not v1) (setq v1 (y-or-n-p "Set \"checked\" attribute? ")))
2495 (funcall skeleton-transformation-function
2496 (if sgml-xml-mode " checked=\"checked\"" " checked")))
2497 (if sgml-xml-mode " />" ">")
2498 (skeleton-read "Text: " (capitalize str))
2499 (or (cdr v2) (setcdr v2 (if (y-or-n-p "Newline after text? ")
2500 (funcall skeleton-transformation-function
2501 (if sgml-xml-mode "<br />" "<br>"))
2505 (define-skeleton html-navigational-links
2506 "Group of navigational links."
2510 "<li><a href=\"" (skeleton-read "URL: " "#") "\">"
2511 (skeleton-read "Title: ") "</a>"
2512 (if sgml-xml-mode (if sgml-xml-mode "</li>")) \n
2516 (define-skeleton html-html5-template
2517 "Initial HTML5 template"
2519 "<!DOCTYPE html>" \n
2520 "<html lang=\"en\">" \n
2522 "<meta charset=\"utf-8\">" \n
2523 "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">" \n
2524 "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">" \n
2525 "<title>" (skeleton-read "Page Title: ") "</title>" \n
2528 "<div id=\"app\"></div>" \n
2532 (provide 'sgml-mode)
2534 ;;; sgml-mode.el ends here