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