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