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