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