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