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