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