1 ;;; sgml-mode.el --- SGML- and HTML-editing modes -*- coding: iso-2022-7bit -*-
3 ;; Copyright (C) 1992, 1995, 1996, 1998, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007 Free Software Foundation, Inc.
6 ;; Author: James Clark <jjc@jclark.com>
8 ;; Adapted-By: ESR, Daniel Pfeiffer <occitan@esperanto.org>,
9 ;; F.Potorti@cnuce.cnr.it
10 ;; Keywords: wp, hypermedia, comm, languages
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software; you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation; either version 2, or (at your option)
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.
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.
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.
44 :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
47 (defcustom sgml-basic-offset 2
48 "*Specifies the basic indentation level for `sgml-indent-line'."
52 (defcustom sgml-transformation-function 'identity
53 "*Default value for `skeleton-transformation-function' in SGML mode."
57 (put 'sgml-transformation-function 'variable-interactive
58 "aTransformation function: ")
59 (defvaralias 'sgml-transformation 'sgml-transformation-function)
61 (defcustom sgml-mode-hook nil
62 "Hook run by command `sgml-mode'.
63 `text-mode-hook' is run first."
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:
75 ?\\\" Makes \" in text start a string.
76 ?' Makes ' in text start a string.
77 ?- Makes -- in text start a comment.
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'.
83 Including ?- has the problem of affecting dashes that have nothing to do
84 with comments, so we normally turn it off.")
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.")
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)))
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))
139 "Keymap for SGML mode. See also `sgml-specials'.")
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))
156 (defvar sgml-mode-syntax-table (sgml-make-syntax-table sgml-specials)
157 "Syntax table used in SGML mode. See also `sgml-specials'.")
159 (defconst sgml-tag-syntax-table
160 (let ((table (sgml-make-syntax-table '(?- ?\" ?\'))))
161 (dolist (char '(?\( ?\) ?\{ ?\} ?\[ ?\] ?$ ?% ?& ?* ?+ ?/))
162 (modify-syntax-entry char "." table))
164 "Syntax table used to parse SGML tags.")
166 (defcustom sgml-name-8bit-mode nil
167 "*When non-nil, insert non-ASCII characters as named entities."
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 `;'.")
206 (put 'sgml-table 'char-table-extra-slots 0)
208 (defvar sgml-char-names-table
209 (let ((table (make-char-table 'sgml-table))
213 (setq elt (aref sgml-char-names i))
214 (if elt (aset table (make-char 'latin-iso8859-1 i) elt))
217 "A table for mapping non-ASCII characters into SGML entity names.
218 Currently, only Latin-1 characters are supported.")
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.
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."
233 (defvar sgml-saved-validate-command nil
234 "The command last used to validate in this buffer.")
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)
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.")
251 (defface sgml-namespace
252 '((t (:inherit font-lock-builtin-face)))
253 "`sgml-mode' face used to highlight the namespace part of identifiers."
255 (defvar sgml-namespace-face 'sgml-namespace)
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)))
275 (defconst sgml-font-lock-keywords-2
277 sgml-font-lock-keywords-1
280 (regexp-opt (mapcar 'car sgml-tag-face-alist) t)
281 "\\([ \t][^>]*\\)?>\\([^<]+\\)</\\1>")
282 '(3 (cdr (assoc (downcase (match-string 1))
283 sgml-tag-face-alist)) prepend))))))
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'.")
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'.")
299 (defvar sgml-face-tag-alist ()
300 "Alist of face and tag name for facemenu.")
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'.")
307 (defvar sgml-display-text ()
308 "Tag names as lowercase symbols, and display string when invisible.")
311 (defvar sgml-tags-invisible nil)
313 (defcustom sgml-tag-alist
314 '(("![" ("ignore" t) ("include" t))
319 "*Alist of tag names for completing read and insertion rules.
320 This alist is made up as
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
330 The attribute alist is made up as
332 ((\"attribute\" . ATTRIBUTERULE)
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)))
340 (put 'sgml-tag-alist 'risky-local-variable t)
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")))
354 (defcustom sgml-xml-mode nil
355 "*When non-nil, tag insertion functions will be XML-compliant.
356 If this variable is customized, the custom value is used always.
357 Otherwise, it is set to be buffer-local when the file has
358 a DOCTYPE or an XML declaration."
363 (defvar sgml-empty-tags nil
364 "List of tags whose !ELEMENT definition says EMPTY.")
366 (defvar sgml-unclosed-tags nil
367 "List of tags whose !ELEMENT definition says the end-tag is optional.")
369 (defun sgml-xml-guess ()
370 "Guess whether the current buffer is XML."
372 (goto-char (point-min))
373 (when (or (string= "xml" (file-name-extension (or buffer-file-name "")))
374 (looking-at "\\s-*<\\?xml")
375 (when (re-search-forward
378 '("<!DOCTYPE" "\\(\\w+\\)" "\\(\\w+\\)"
379 "\"\\([^\"]+\\)\"" "\"\\([^\"]+\\)\"")
382 (string-match "X\\(HT\\)?ML" (match-string 3))))
383 (set (make-local-variable 'sgml-xml-mode) t))))
385 (defvar v2) ; free for skeleton
387 (defun sgml-comment-indent-new-line (&optional soft)
388 (let ((comment-start "-- ")
389 (comment-start-skip "\\(<!\\)?--[ \t]*")
391 (comment-style 'plain))
392 (comment-indent-new-line soft)))
394 (defun sgml-mode-facemenu-add-face-function (face end)
395 (if (setq face (cdr (assq face sgml-face-tag-alist)))
397 (setq face (funcall skeleton-transformation-function face))
398 (setq facemenu-end-add-face (concat "</" face ">"))
399 (concat "<" face ">"))
400 (error "Face not configured for %s mode" mode-name)))
402 (defun sgml-fill-nobreak ()
403 ;; Don't break between a tag name and its first argument.
405 (skip-chars-backward " \t")
406 (and (not (zerop (skip-syntax-backward "w_")))
407 (skip-chars-backward "/?!")
408 (eq (char-before) ?<))))
411 (define-derived-mode sgml-mode text-mode "SGML"
412 "Major mode for editing SGML documents.
414 Keys <, &, SPC within <>, \", / and ' can be electric depending on
417 An argument of N to a tag-inserting command means to wrap it around
418 the next N words. In Transient Mark mode, when the mark is active,
419 N defaults to -1, which means to wrap it around the current region.
421 If you like upcased tags, put (setq sgml-transformation-function 'upcase)
422 in your `.emacs' file.
424 Use \\[sgml-validate] to validate your document with an SGML parser.
426 Do \\[describe-variable] sgml- SPC to see available variables.
427 Do \\[describe-key] on the following bindings to discover what they do.
429 (make-local-variable 'sgml-saved-validate-command)
430 (make-local-variable 'facemenu-end-add-face)
431 ;;(make-local-variable 'facemenu-remove-face-function)
432 ;; A start or end tag by itself on a line separates a paragraph.
433 ;; This is desirable because SGML discards a newline that appears
434 ;; immediately after a start tag or immediately before an end tag.
435 (set (make-local-variable 'paragraph-start) (concat "[ \t]*$\\|\
436 \[ \t]*</?\\(" sgml-name-re sgml-attrs-re "\\)?>"))
437 (set (make-local-variable 'paragraph-separate)
438 (concat paragraph-start "$"))
439 (set (make-local-variable 'adaptive-fill-regexp) "[ \t]*")
440 (add-hook 'fill-nobreak-predicate 'sgml-fill-nobreak nil t)
441 (set (make-local-variable 'indent-line-function) 'sgml-indent-line)
442 (set (make-local-variable 'comment-start) "<!-- ")
443 (set (make-local-variable 'comment-end) " -->")
444 (set (make-local-variable 'comment-indent-function) 'sgml-comment-indent)
445 (set (make-local-variable 'comment-line-break-function)
446 'sgml-comment-indent-new-line)
447 (set (make-local-variable 'skeleton-further-elements)
448 '((completion-ignore-case t)))
449 (set (make-local-variable 'skeleton-end-hook)
452 (not (or (eq v2 '\n) (eq (car-safe v2) '\n)))
453 (newline-and-indent))))
454 (set (make-local-variable 'font-lock-defaults)
455 '((sgml-font-lock-keywords
456 sgml-font-lock-keywords-1
457 sgml-font-lock-keywords-2)
459 (font-lock-syntactic-keywords
460 . sgml-font-lock-syntactic-keywords)))
461 (set (make-local-variable 'facemenu-add-face-function)
462 'sgml-mode-facemenu-add-face-function)
465 (setq mode-name "XML")
466 (set (make-local-variable 'skeleton-transformation-function)
467 sgml-transformation-function))
468 ;; This will allow existing comments within declarations to be
470 (set (make-local-variable 'comment-start-skip) "\\(?:<!\\)?--[ \t]*")
471 (set (make-local-variable 'comment-end-skip) "[ \t]*--\\([ \t\n]*>\\)?")
472 ;; This definition has an HTML leaning but probably fits well for other modes.
473 (setq imenu-generic-expression
475 ,(concat "<!\\(element\\|entity\\)[ \t\n]+%?[ \t\n]*\\("
479 ,(concat "<[^>]+[ \t\n]+[Ii][Dd]=\\(['\"]"
480 (if sgml-xml-mode "" "?")
481 "\\)\\(" sgml-name-re "\\)\\1")
484 ,(concat "<[^>]+[ \t\n]+[Nn][Aa][Mm][Ee]=\\(['\"]"
485 (if sgml-xml-mode "" "?")
486 "\\)\\(" sgml-name-re "\\)\\1")
489 ;; Some programs (such as Glade 2) generate XML which has
490 ;; -*- mode: xml -*-.
492 (defalias 'xml-mode 'sgml-mode)
494 (defun sgml-comment-indent ()
495 (if (looking-at "--") comment-column 0))
497 (defun sgml-slash (arg)
498 "Insert ARG slash characters.
499 Behaves electrically if `sgml-quick-keys' is non-nil."
502 ((not (and (eq (char-before) ?<) (= arg 1)))
503 (sgml-slash-matching arg))
504 ((eq sgml-quick-keys 'indent)
506 (indent-according-to-mode))
507 ((eq sgml-quick-keys 'close)
508 (delete-backward-char 1)
511 (sgml-slash-matching arg))))
513 (defun sgml-slash-matching (arg)
514 "Insert `/' and display any previous matching `/'.
515 Two `/'s are treated as matching if the first `/' ends a net-enabling
516 start tag, and the second `/' is the corresponding null end tag."
520 (let ((oldpos (point))
525 (if sgml-slash-distance
526 (narrow-to-region (max (point-min)
527 (- (point) sgml-slash-distance))
529 (if (and (re-search-backward sgml-start-tag-regex (point-min) t)
530 (eq (match-end 0) (1- oldpos)))
532 (goto-char (1- oldpos))
533 (while (and (not blinkpos)
534 (search-backward "/" (point-min) t))
535 (let ((tagend (save-excursion
536 (if (re-search-backward sgml-start-tag-regex
540 (if (eq tagend (point))
542 (setq blinkpos (point))
543 (setq level (1- level)))
544 (setq level (1+ level)))))))
547 (if (pos-visible-in-window-p)
549 (message "Matches %s"
550 (buffer-substring (line-beginning-position)
551 (1+ blinkpos)))))))))
553 ;; Why doesn't this use the iso-cvt table or, preferably, generate the
554 ;; inverse of the extensive table in the SGML Quail input method? -- fx
555 ;; I guess that's moot since it only works with Latin-1 anyhow.
556 (defun sgml-name-char (&optional char)
557 "Insert a symbolic character name according to `sgml-char-names'.
558 Non-ASCII chars may be inserted either with the meta key, as in M-SPC for
559 no-break space or M-- for a soft hyphen; or via an input method or
560 encoded keyboard operation."
564 (setq char (read-quoted-char "Enter char or octal number")))
565 (delete-backward-char 1)
570 (defun sgml-namify-char ()
571 "Change the char before point into its `&name;' equivalent.
572 Uses `sgml-char-names'."
574 (let* ((char (char-before))
577 ((null char) (error "No char before point"))
578 ((< char 256) (or (aref sgml-char-names char) char))
579 ((aref sgml-char-names-table char))
580 ((encode-char char 'ucs)))))
582 (error "Don't know the name of `%c'" char)
583 (delete-backward-char 1)
584 (insert (format (if (numberp name) "&#%d;" "&%s;") name)))))
586 (defun sgml-name-self ()
587 "Insert a symbolic character name according to `sgml-char-names'."
589 (sgml-name-char last-command-char))
591 (defun sgml-maybe-name-self ()
592 "Insert a symbolic character name according to `sgml-char-names'."
594 (if sgml-name-8bit-mode
595 (let ((mc last-command-char))
597 (setq mc (unibyte-char-to-multibyte mc)))
598 (or mc (setq mc last-command-char))
600 (self-insert-command 1)))
602 (defun sgml-name-8bit-mode ()
603 "Toggle whether to insert named entities instead of non-ASCII characters.
604 This only works for Latin-1 input."
606 (setq sgml-name-8bit-mode (not sgml-name-8bit-mode))
607 (message "sgml name entity mode is now %s"
608 (if sgml-name-8bit-mode "ON" "OFF")))
610 ;; When an element of a skeleton is a string "str", it is passed
611 ;; through `skeleton-transformation-function' and inserted.
612 ;; If "str" is to be inserted literally, one should obtain it as
613 ;; the return value of a function, e.g. (identity "str").
615 (defvar sgml-tag-last nil)
616 (defvar sgml-tag-history nil)
617 (define-skeleton sgml-tag
618 "Prompt for a tag and insert it, optionally with attributes.
619 Completion and configuration are done according to `sgml-tag-alist'.
620 If you like tags and attributes in uppercase do \\[set-variable]
621 `skeleton-transformation-function' RET `upcase' RET, or put this
623 (setq sgml-transformation-function 'upcase)"
624 (funcall (or skeleton-transformation-function 'identity)
627 (if (> (length sgml-tag-last) 0)
628 (format "Tag (default %s): " sgml-tag-last)
630 sgml-tag-alist nil nil nil 'sgml-tag-history sgml-tag-last)))
632 (("") -1 '(undo-boundary) (identity "<")) | ; see comment above
633 `(("") '(setq v2 (sgml-attributes ,str t)) ?>
637 '(("") " [ " _ " ]]"))
638 ((and (eq v2 t) sgml-xml-mode (member ,str sgml-empty-tags))
640 ((or (and (eq v2 t) (not sgml-xml-mode)) (string-match "^[/!?]" ,str))
643 ;; Make sure we don't fall into an infinite loop.
644 ;; For xhtml's `tr' tag, we should maybe use \n instead.
645 (if (eq v2 t) (setq v2 nil))
646 ;; We use `identity' to prevent skeleton from passing
647 ;; `str' through `skeleton-transformation-function' a second time.
648 '(("") v2 _ v2 "</" (identity ',str) ?>))
650 (cons '("") (cdr v2)))
652 (append '(("") (car v2))
654 '(resume: (car v2) _ "</" (identity ',str) ?>))))))
656 (autoload 'skeleton-read "skeleton")
658 (defun sgml-attributes (tag &optional quiet)
659 "When at top level of a tag, interactively insert attributes.
661 Completion and configuration of TAG are done according to `sgml-tag-alist'.
662 If QUIET, do not print a message when there are no attributes for TAG."
663 (interactive (list (save-excursion (sgml-beginning-of-tag t))))
664 (or (stringp tag) (error "Wrong context for adding attribute"))
666 (let ((completion-ignore-case t)
667 (alist (cdr (assoc (downcase tag) sgml-tag-alist)))
669 (if (or (symbolp (car alist))
670 (symbolp (car (car alist))))
671 (setq car (car alist)
674 (message "No attributes configured."))
675 (if (stringp (car alist))
677 (insert (if (eq (preceding-char) ?\s) "" ?\s)
678 (funcall skeleton-transformation-function (car alist)))
680 (setq i (length alist))
683 (insert (funcall skeleton-transformation-function
685 (skeleton-read '(completing-read
688 (if (string= "" attribute)
690 (sgml-value (assoc (downcase attribute) alist))
692 (if (eq (preceding-char) ?\s)
693 (delete-backward-char 1)))
696 (defun sgml-auto-attributes (arg)
697 "Self insert the character typed; at top level of tag, prompt for attributes.
698 With prefix argument, only self insert."
700 (let ((point (point))
703 (not sgml-tag-alist) ; no message when nothing configured
704 (symbolp (setq tag (save-excursion (sgml-beginning-of-tag t))))
705 (eq (aref tag 0) ?/))
706 (self-insert-command (prefix-numeric-value arg))
707 (sgml-attributes tag)
708 (setq last-command-char ?\s)
709 (or (> (point) point)
710 (self-insert-command 1)))))
712 (defun sgml-tag-help (&optional tag)
713 "Display description of tag TAG. If TAG is omitted, use the tag at point."
717 (if (eq (following-char) ?<)
719 (setq tag (sgml-beginning-of-tag))))
721 (error "No tag selected"))
722 (setq tag (downcase tag))
724 (or (cdr (assoc (downcase tag) sgml-tag-help))
725 (and (eq (aref tag 0) ?/)
726 (cdr (assoc (downcase (substring tag 1)) sgml-tag-help)))
727 "No description available")))
729 (defun sgml-maybe-end-tag (&optional arg)
730 "Name self unless in position to end a tag or a prefix ARG is given."
732 (if (or arg (eq (car (sgml-lexical-context)) 'tag))
733 (self-insert-command (prefix-numeric-value arg))
736 (defun sgml-skip-tag-backward (arg)
737 "Skip to beginning of tag or matching opening tag if present.
738 With prefix argument ARG, repeat this ARG times."
740 ;; FIXME: use sgml-get-context or something similar.
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))) ?/))
752 (sgml-skip-tag-backward 1))))
753 (setq arg (1- arg))))
755 (defun sgml-skip-tag-forward (arg)
756 "Skip to end of tag or matching closing tag if present.
757 With prefix argument ARG, repeat this ARG times.
758 Return t iff after a closing tag."
760 ;; FIXME: Use sgml-get-context or something similar.
761 ;; It currently might jump to an unrelated </P> if the <P>
762 ;; we're skipping has no matching </P>.
764 (with-syntax-table sgml-tag-syntax-table
766 (skip-chars-forward "^<>")
767 (if (eq (following-char) ?>)
769 (if (looking-at "<\\([^/ \n\t>]+\\)\\([^>]*[^/>]\\)?>")
770 ;; start tag, skip any nested same pairs _and_ closing tag
771 (let ((case-fold-search t)
772 (re (concat "</?" (regexp-quote (match-string 1))
773 ;; Ignore empty tags like <foo/>.
774 "\\([^>]*[^/>]\\)?>"))
778 ;; FIXME: This re-search-forward will mistakenly match
779 ;; tag-like text inside attributes.
780 (while (and (re-search-forward re nil t)
782 (eq (char-after (1+ (match-beginning 0))) ?/)))
783 (goto-char (match-beginning 0))
784 (sgml-skip-tag-forward 1))
793 (defun sgml-delete-tag (arg)
794 ;; FIXME: Should be called sgml-kill-tag or should not touch the kill-ring.
795 "Delete tag on or after cursor, and matching closing or opening tag.
796 With prefix argument ARG, repeat this ARG times."
801 (if (looking-at "[ \t\n]*<")
803 (if (eq (char-after (match-end 0)) ?/)
807 (goto-char (match-end 0))))
809 (or (save-excursion (setq close (sgml-beginning-of-tag)
810 close (and (stringp close)
811 (eq (aref close 0) ?/)
813 ;; not on closing tag
814 (let ((point (point)))
815 (sgml-skip-tag-backward 1)
816 (if (or (not (eq (following-char) ?<))
820 (error "Not on or before tag")))))
823 (sgml-skip-tag-backward 1)
828 (when (and (sgml-skip-tag-forward 1)
829 (not (looking-back "/>")))
831 ;; Delete any resulting empty line. If we didn't kill-sexp,
832 ;; this *should* do nothing, because we're right after the tag.
833 (if (progn (forward-line 0) (looking-at "\\(?:[ \t]*$\\)\n?"))
834 (delete-region (match-beginning 0) (match-end 0)))
837 (if (progn (forward-line 0) (looking-at "\\(?:[ \t]*$\\)\n?"))
838 (delete-region (match-beginning 0) (match-end 0)))))
839 (setq arg (1- arg))))
842 ;; Put read-only last to enable setting this even when read-only enabled.
843 (or (get 'sgml-tag 'invisible)
845 (append '(invisible t
846 point-entered sgml-point-entered
849 (symbol-plist 'sgml-tag))))
851 (defun sgml-tags-invisible (arg)
852 "Toggle visibility of existing tags."
854 (let ((modified (buffer-modified-p))
855 (inhibit-read-only t)
856 (inhibit-modification-hooks t)
857 ;; Avoid spurious the `file-locked' checks.
858 (buffer-file-name nil)
859 ;; This is needed in case font lock gets called,
860 ;; since it moves point and might call sgml-point-entered.
861 ;; How could it get called? -stef
862 (inhibit-point-motion-hooks t)
866 (goto-char (point-min))
867 (if (set (make-local-variable 'sgml-tags-invisible)
869 (>= (prefix-numeric-value arg) 0)
870 (not sgml-tags-invisible)))
871 (while (re-search-forward sgml-tag-name-re nil t)
873 (cdr (assq (intern-soft (downcase (match-string 1)))
875 (goto-char (match-beginning 0))
876 (and (stringp string)
877 (not (overlays-at (point)))
878 (let ((ol (make-overlay (point) (match-beginning 1))))
879 (overlay-put ol 'before-string string)
880 (overlay-put ol 'sgml-tag t)))
881 (put-text-property (point)
882 (progn (forward-list) (point))
883 'category 'sgml-tag))
884 (let ((pos (point-min)))
885 (while (< (setq pos (next-overlay-change pos)) (point-max))
886 (dolist (ol (overlays-at pos))
887 (if (overlay-get ol 'sgml-tag)
888 (delete-overlay ol)))))
889 (remove-text-properties (point-min) (point-max) '(category nil))))
890 (restore-buffer-modified-p modified))
891 (run-hooks 'sgml-tags-invisible-hook)
894 (defun sgml-point-entered (x y)
895 ;; Show preceding or following hidden tag, depending of cursor direction.
896 (let ((inhibit-point-motion-hooks t))
898 (message "Invisible tag: %s"
899 ;; Strip properties, otherwise, the text is invisible.
900 (buffer-substring-no-properties
903 (not (eq (following-char) ?<)))
905 (eq (preceding-char) ?>)))
910 (defun sgml-validate (command)
911 "Validate an SGML document.
912 Runs COMMAND, a shell command, in a separate process asynchronously
913 with output going to the buffer `*compilation*'.
914 You can then use the command \\[next-error] to find the next error message
915 and move to the line in the SGML document that caused it."
917 (list (read-string "Validate command: "
918 (or sgml-saved-validate-command
919 (concat sgml-validate-command
921 (let ((name (buffer-file-name)))
923 (file-name-nondirectory name))))))))
924 (setq sgml-saved-validate-command command)
925 (save-some-buffers (not compilation-ask-about-save) nil)
926 (compilation-start command))
928 (defsubst sgml-at-indentation-p ()
929 "Return true if point is at the first non-whitespace character on the line."
931 (skip-chars-backward " \t")
934 (defun sgml-lexical-context (&optional limit)
935 "Return the lexical context at point as (TYPE . START).
936 START is the location of the start of the lexical element.
937 TYPE is one of `string', `comment', `tag', `cdata', or `text'.
939 Optional argument LIMIT is the position to start parsing from.
940 If nil, start from a preceding tag at indentation."
946 ;; Skip tags backwards until we find one at indentation
947 (while (and (ignore-errors (sgml-parse-tag-backward))
948 (not (sgml-at-indentation-p)))))
949 (with-syntax-table sgml-tag-syntax-table
950 (while (< (point) pos)
951 ;; When entering this loop we're inside text.
952 (setq text-start (point))
953 (skip-chars-forward "^<" pos)
957 ;; We got to the end without seeing a tag.
959 ((looking-at "<!\\[[A-Z]+\\[")
960 ;; We've found a CDATA section or similar.
961 (let ((cdata-start (point)))
962 (unless (search-forward "]]>" pos 'move)
963 (list 0 nil nil 'cdata nil nil nil nil cdata-start))))
965 ;; We've reached a tag. Parse it.
966 ;; FIXME: Handle net-enabling start-tags
967 (parse-partial-sexp (point) pos 0))))))
969 ((eq (nth 3 state) 'cdata) (cons 'cdata (nth 8 state)))
970 ((nth 3 state) (cons 'string (nth 8 state)))
971 ((nth 4 state) (cons 'comment (nth 8 state)))
972 ((and state (> (nth 0 state) 0)) (cons 'tag (nth 1 state)))
973 (t (cons 'text text-start))))))
975 (defun sgml-beginning-of-tag (&optional top-level)
976 "Skip to beginning of tag and return its name.
977 If this can't be done, return nil."
978 (let ((context (sgml-lexical-context)))
979 (if (eq (car context) 'tag)
981 (goto-char (cdr context))
982 (when (looking-at sgml-tag-name-re)
983 (match-string-no-properties 1)))
985 (when (not (eq (car context) 'text))
986 (goto-char (cdr context))
987 (sgml-beginning-of-tag t))))))
989 (defun sgml-value (alist)
990 "Interactively insert value taken from attribute-rule ALIST.
991 See `sgml-tag-alist' for info about attribute rules."
992 (setq alist (cdr alist))
993 (if (stringp (car alist))
994 (insert "=\"" (car alist) ?\")
995 (if (and (eq (car alist) t) (not sgml-xml-mode))
998 (setq alist (skeleton-read '(completing-read "Value: " (cdr alist))))
999 (if (string< "" alist)
1001 (delete-backward-char 2)))
1004 (insert (skeleton-read '(completing-read "Value: " alist))))
1007 (defun sgml-quote (start end &optional unquotep)
1008 "Quote SGML text in region START ... END.
1009 Only &, < and > are quoted, the rest is left untouched.
1010 With prefix argument UNQUOTEP, unquote the region."
1011 (interactive "r\nP")
1013 (narrow-to-region start end)
1014 (goto-char (point-min))
1016 ;; FIXME: We should unquote other named character references as well.
1017 (while (re-search-forward
1018 "\\(&\\(amp\\|\\(l\\|\\(g\\)\\)t\\)\\)[][<>&;\n\t \"%!'(),/=?]"
1020 (replace-match (if (match-end 4) ">" (if (match-end 3) "<" "&")) t t
1021 nil (if (eq (char-before (match-end 0)) ?\;) 0 1)))
1022 (while (re-search-forward "[&<>]" nil t)
1023 (replace-match (cdr (assq (char-before) '((?& . "&")
1028 (defun sgml-pretty-print (beg end)
1029 "Simple-minded pretty printer for SGML.
1030 Re-indents the code and inserts newlines between BEG and END.
1031 You might want to turn on `auto-fill-mode' to get better results."
1033 ;; - insert newline between some start-tag and text.
1034 ;; - don't insert newline in front of some end-tags.
1042 ;; Don't use narrowing because it screws up auto-indent.
1043 (setq end (copy-marker end t))
1044 (with-syntax-table sgml-tag-syntax-table
1045 (while (re-search-forward "<" end t)
1046 (goto-char (match-beginning 0))
1047 (unless (or ;;(looking-at "</")
1048 (progn (skip-chars-backward " \t") (bolp)))
1049 (reindent-then-newline-and-indent))
1051 ;; (indent-region beg end)
1057 (defstruct (sgml-tag
1058 (:constructor sgml-make-tag (type start end name)))
1059 type start end name)
1061 (defsubst sgml-parse-tag-name ()
1062 "Skip past a tag-name, and return the name."
1063 (buffer-substring-no-properties
1064 (point) (progn (skip-syntax-forward "w_") (point))))
1066 (defsubst sgml-looking-back-at (str)
1067 "Return t if the test before point matches STR."
1068 (let ((start (- (point) (length str))))
1069 (and (>= start (point-min))
1070 (equal str (buffer-substring-no-properties start (point))))))
1072 (defun sgml-tag-text-p (start end)
1073 "Return non-nil if text between START and END is a tag.
1074 Checks among other things that the tag does not contain spurious
1075 unquoted < or > chars inside, which would indicate that it
1076 really isn't a tag after all."
1078 (with-syntax-table sgml-tag-syntax-table
1079 (let ((pps (parse-partial-sexp start end 2)))
1080 (and (= (nth 0 pps) 0))))))
1082 (defun sgml-parse-tag-backward (&optional limit)
1083 "Parse an SGML tag backward, and return information about the tag.
1084 Assume that parsing starts from within a textual context.
1085 Leave point at the beginning of the tag."
1087 (let (tag-type tag-start tag-end name)
1088 (or (re-search-backward "[<>]" limit 'move)
1089 (error "No tag found"))
1090 (when (eq (char-after) ?<)
1091 ;; Oops!! Looks like we were not in a textual context after all!.
1092 ;; Let's try to recover.
1093 (with-syntax-table sgml-tag-syntax-table
1094 (let ((pos (point)))
1098 ;; This < seems to be just a spurious one, let's ignore it.
1100 (throw 'found (sgml-parse-tag-backward limit))))
1101 ;; Check it is really a tag, without any extra < or > inside.
1102 (unless (sgml-tag-text-p pos (point))
1104 (throw 'found (sgml-parse-tag-backward limit)))
1105 (forward-char -1))))
1106 (setq tag-end (1+ (point)))
1108 ((sgml-looking-back-at "--") ; comment
1109 (setq tag-type 'comment
1110 tag-start (search-backward "<!--" nil t)))
1111 ((sgml-looking-back-at "]]") ; cdata
1112 (setq tag-type 'cdata
1113 tag-start (re-search-backward "<!\\[[A-Z]+\\[" nil t)))
1116 (with-syntax-table sgml-tag-syntax-table
1121 ;; This > isn't really the end of a tag. Skip it.
1122 (goto-char (1- tag-end))
1123 (throw 'found (sgml-parse-tag-backward limit))))
1125 (goto-char (1+ tag-start))
1128 (setq tag-type 'decl))
1129 (?? ; processing-instruction
1130 (setq tag-type 'pi))
1133 (setq tag-type 'close
1134 name (sgml-parse-tag-name)))
1136 (setq tag-type 'jsp))
1137 (t ; open or empty tag
1138 (setq tag-type 'open
1139 name (sgml-parse-tag-name))
1140 (if (or (eq ?/ (char-before (- tag-end 1)))
1141 (sgml-empty-tag-p name))
1142 (setq tag-type 'empty))))))
1143 (goto-char tag-start)
1144 (sgml-make-tag tag-type tag-start tag-end name))))
1146 (defun sgml-get-context (&optional until)
1147 "Determine the context of the current position.
1148 By default, parse until we find a start-tag as the first thing on a line.
1149 If UNTIL is `empty', return even if the context is empty (i.e.
1150 we just skipped over some element and got to a beginning of line).
1152 The context is a list of tag-info structures. The last one is the tag
1153 immediately enclosing the current position.
1155 Point is assumed to be outside of any tag. If we discover that it's
1156 not the case, the first tag returned is the one inside which we are."
1157 (let ((here (point))
1162 ;; CONTEXT keeps track of the tag-stack
1163 ;; STACK keeps track of the end tags we've seen (and thus the start-tags
1164 ;; we'll have to ignore) when skipping over matching open..close pairs.
1165 ;; IGNORE is a list of tags that can be ignored because they have been
1166 ;; closed implicitly.
1167 (skip-chars-backward " \t\n") ; Make sure we're not at indentation.
1169 (and (not (eq until 'now))
1171 (not (if until (eq until 'empty) context))
1172 (not (sgml-at-indentation-p))
1174 (/= (point) (sgml-tag-start (car context)))
1175 (sgml-unclosed-tag-p (sgml-tag-name (car context)))))
1176 (setq tag-info (ignore-errors (sgml-parse-tag-backward))))
1178 ;; This tag may enclose things we thought were tags. If so,
1181 (> (sgml-tag-end tag-info)
1182 (sgml-tag-end (car context))))
1183 (setq context (cdr context)))
1186 ((> (sgml-tag-end tag-info) here)
1187 ;; Oops!! Looks like we were not outside of any tag, after all.
1188 (push tag-info context)
1192 ((eq (sgml-tag-type tag-info) 'open)
1195 (if (member-ignore-case (sgml-tag-name tag-info) ignore)
1196 ;; There was an implicit end-tag.
1198 (push tag-info context)
1199 ;; We're changing context so the tags implicitly closed inside
1200 ;; the previous context aren't implicitly closed here any more.
1201 ;; [ Well, actually it depends, but we don't have the info about
1202 ;; when it doesn't and when it does. --Stef ]
1204 ((eq t (compare-strings (sgml-tag-name tag-info) nil nil
1205 (car stack) nil nil t))
1206 (setq stack (cdr stack)))
1208 ;; The open and close tags don't match.
1209 (if (not sgml-xml-mode)
1210 (unless (sgml-unclosed-tag-p (sgml-tag-name tag-info))
1211 (message "Unclosed tag <%s>" (sgml-tag-name tag-info))
1213 ;; We could just assume that the tag is simply not closed
1214 ;; but it's a bad assumption when tags *are* closed but
1215 ;; not properly nested.
1216 (while (and (cdr tmp)
1217 (not (eq t (compare-strings
1218 (sgml-tag-name tag-info) nil nil
1219 (cadr tmp) nil nil t))))
1220 (setq tmp (cdr tmp)))
1221 (if (cdr tmp) (setcdr tmp (cddr tmp)))))
1222 (message "Unmatched tags <%s> and </%s>"
1223 (sgml-tag-name tag-info) (pop stack)))))
1225 (if (and (null stack) (sgml-unclosed-tag-p (sgml-tag-name tag-info)))
1226 ;; This is a top-level open of an implicitly closed tag, so any
1227 ;; occurrence of such an open tag at the same level can be ignored
1228 ;; because it's been implicitly closed.
1229 (push (sgml-tag-name tag-info) ignore)))
1232 ((eq (sgml-tag-type tag-info) 'close)
1233 (if (sgml-empty-tag-p (sgml-tag-name tag-info))
1234 (message "Spurious </%s>: empty tag" (sgml-tag-name tag-info))
1235 (push (sgml-tag-name tag-info) stack)))
1241 (defun sgml-show-context (&optional full)
1242 "Display the current context.
1243 If FULL is non-nil, parse back to the beginning of the buffer."
1245 (with-output-to-temp-buffer "*XML Context*"
1247 (let ((context (sgml-get-context)))
1250 (while (setq more (sgml-get-context))
1251 (setq context (nconc more context)))))
1255 ;; Editing shortcuts
1257 (defun sgml-close-tag ()
1258 "Close current element.
1259 Depending on context, inserts a matching close-tag, or closes
1260 the current start-tag or the current comment or the current cdata, ..."
1262 (case (car (sgml-lexical-context))
1263 (comment (insert " -->"))
1264 (cdata (insert "]]>"))
1266 (jsp (insert " %>"))
1267 (tag (insert " />"))
1269 (let ((context (save-excursion (sgml-get-context))))
1272 (insert "</" (sgml-tag-name (car (last context))) ">")
1273 (indent-according-to-mode)))))
1275 (error "Nothing to close"))))
1277 (defun sgml-empty-tag-p (tag-name)
1278 "Return non-nil if TAG-NAME is an implicitly empty tag."
1279 (and (not sgml-xml-mode)
1280 (member-ignore-case tag-name sgml-empty-tags)))
1282 (defun sgml-unclosed-tag-p (tag-name)
1283 "Return non-nil if TAG-NAME is a tag for which an end-tag is optional."
1284 (and (not sgml-xml-mode)
1285 (member-ignore-case tag-name sgml-unclosed-tags)))
1287 (defun sgml-calculate-indent (&optional lcon)
1288 "Calculate the column to which this line should be indented.
1289 LCON is the lexical context, if any."
1290 (unless lcon (setq lcon (sgml-lexical-context)))
1292 ;; Indent comment-start markers inside <!-- just like comment-end markers.
1293 (if (and (eq (car lcon) 'tag)
1295 (save-excursion (goto-char (cdr lcon)) (looking-at "<!--")))
1296 (setq lcon (cons 'comment (+ (cdr lcon) 2))))
1301 ;; Go back to previous non-empty line.
1302 (while (and (> (point) (cdr lcon))
1303 (zerop (forward-line -1))
1304 (looking-at "[ \t]*$")))
1305 (if (> (point) (cdr lcon))
1306 ;; Previous line is inside the string.
1307 (current-indentation)
1308 (goto-char (cdr lcon))
1309 (1+ (current-column))))
1312 (let ((mark (looking-at "--")))
1313 ;; Go back to previous non-empty line.
1314 (while (and (> (point) (cdr lcon))
1315 (zerop (forward-line -1))
1316 (or (looking-at "[ \t]*$")
1317 (if mark (not (looking-at "[ \t]*--"))))))
1318 (if (> (point) (cdr lcon))
1319 ;; Previous line is inside the comment.
1320 (skip-chars-forward " \t")
1321 (goto-char (cdr lcon))
1322 ;; Skip `<!' to get to the `--' with which we want to align.
1323 (search-forward "--")
1324 (goto-char (match-beginning 0)))
1325 (when (and (not mark) (looking-at "--"))
1326 (forward-char 2) (skip-chars-forward " \t"))
1329 ;; We don't know how to indent it. Let's be honest about it.
1333 (goto-char (1+ (cdr lcon)))
1334 (skip-chars-forward "^ \t\n") ;Skip tag name.
1335 (skip-chars-forward " \t")
1338 ;; This is the first attribute: indent.
1339 (goto-char (1+ (cdr lcon)))
1340 (+ (current-column) sgml-basic-offset)))
1343 (while (looking-at "</")
1345 (skip-chars-forward " \t"))
1346 (let* ((here (point))
1347 (unclosed (and ;; (not sgml-xml-mode)
1348 (looking-at sgml-tag-name-re)
1349 (member-ignore-case (match-string 1)
1353 ;; If possible, align on the previous non-empty text line.
1354 ;; Otherwise, do a more serious parsing to find the
1355 ;; tag(s) relative to which we should be indenting.
1356 (if (and (not unclosed) (skip-chars-backward " \t")
1357 (< (skip-chars-backward " \t\n") 0)
1358 (back-to-indentation)
1359 (> (point) (cdr lcon)))
1362 (nreverse (sgml-get-context (if unclosed nil 'empty)))))
1364 ;; Ignore previous unclosed start-tag in context.
1365 (while (and context unclosed
1366 (eq t (compare-strings
1367 (sgml-tag-name (car context)) nil nil
1368 unclosed nil nil t)))
1369 (setq context (cdr context)))
1370 ;; Indent to reflect nesting.
1372 ;; If we were not in a text context after all, let's try again.
1373 ((and context (> (sgml-tag-end (car context)) here))
1375 (sgml-calculate-indent
1376 (cons (if (memq (sgml-tag-type (car context)) '(comment cdata))
1377 (sgml-tag-type (car context)) 'tag)
1378 (sgml-tag-start (car context)))))
1379 ;; Align on the first element after the nearest open-tag, if any.
1381 (goto-char (sgml-tag-end (car context)))
1382 (skip-chars-forward " \t\n")
1383 (< (point) here) (sgml-at-indentation-p))
1388 (* sgml-basic-offset (length context)))))))
1391 (error "Unrecognized context %s" (car lcon)))
1395 (defun sgml-indent-line ()
1396 "Indent the current line as SGML."
1398 (let* ((savep (point))
1401 (back-to-indentation)
1402 (if (>= (point) savep) (setq savep nil))
1403 (sgml-calculate-indent))))
1404 (if (null indent-col)
1407 (save-excursion (indent-line-to indent-col))
1408 (indent-line-to indent-col)))))
1410 (defun sgml-guess-indent ()
1411 "Guess an appropriate value for `sgml-basic-offset'.
1412 Base the guessed identation level on the first indented tag in the buffer.
1413 Add this to `sgml-mode-hook' for convenience."
1416 (goto-char (point-min))
1417 (if (re-search-forward "^\\([ \t]+\\)<" 500 'noerror)
1419 (set (make-local-variable 'sgml-basic-offset)
1420 (1- (current-column)))
1421 (message "Guessed sgml-basic-offset = %d"
1425 (defun sgml-parse-dtd ()
1426 "Simplistic parse of the current buffer as a DTD.
1427 Currently just returns (EMPTY-TAGS UNCLOSED-TAGS)."
1428 (goto-char (point-min))
1431 (while (re-search-forward "<!ELEMENT[ \t\n]+\\([^ \t\n]+\\)[ \t\n]+[-O][ \t\n]+\\([-O]\\)[ \t\n]+\\([^ \t\n]+\\)" nil t)
1433 ((string= (match-string 3) "EMPTY")
1434 (push (match-string-no-properties 1) empty))
1435 ((string= (match-string 2) "O")
1436 (push (match-string-no-properties 1) unclosed))))
1437 (setq empty (sort (mapcar 'downcase empty) 'string<))
1438 (setq unclosed (sort (mapcar 'downcase unclosed) 'string<))
1439 (list empty unclosed)))
1443 (defcustom html-mode-hook nil
1444 "Hook run by command `html-mode'.
1445 `text-mode-hook' and `sgml-mode-hook' are run first."
1448 :options '(html-autoview-mode))
1450 (defvar html-quick-keys sgml-quick-keys
1451 "Use C-c X combinations for quick insertion of frequent tags when non-nil.
1452 This defaults to `sgml-quick-keys'.
1453 This takes effect when first loading the library.")
1455 (defvar html-mode-map
1456 (let ((map (make-sparse-keymap))
1457 (menu-map (make-sparse-keymap "HTML")))
1458 (set-keymap-parent map sgml-mode-map)
1459 (define-key map "\C-c6" 'html-headline-6)
1460 (define-key map "\C-c5" 'html-headline-5)
1461 (define-key map "\C-c4" 'html-headline-4)
1462 (define-key map "\C-c3" 'html-headline-3)
1463 (define-key map "\C-c2" 'html-headline-2)
1464 (define-key map "\C-c1" 'html-headline-1)
1465 (define-key map "\C-c\r" 'html-paragraph)
1466 (define-key map "\C-c\n" 'html-line)
1467 (define-key map "\C-c\C-c-" 'html-horizontal-rule)
1468 (define-key map "\C-c\C-co" 'html-ordered-list)
1469 (define-key map "\C-c\C-cu" 'html-unordered-list)
1470 (define-key map "\C-c\C-cr" 'html-radio-buttons)
1471 (define-key map "\C-c\C-cc" 'html-checkboxes)
1472 (define-key map "\C-c\C-cl" 'html-list-item)
1473 (define-key map "\C-c\C-ch" 'html-href-anchor)
1474 (define-key map "\C-c\C-cn" 'html-name-anchor)
1475 (define-key map "\C-c\C-ci" 'html-image)
1476 (when html-quick-keys
1477 (define-key map "\C-c-" 'html-horizontal-rule)
1478 (define-key map "\C-co" 'html-ordered-list)
1479 (define-key map "\C-cu" 'html-unordered-list)
1480 (define-key map "\C-cr" 'html-radio-buttons)
1481 (define-key map "\C-cc" 'html-checkboxes)
1482 (define-key map "\C-cl" 'html-list-item)
1483 (define-key map "\C-ch" 'html-href-anchor)
1484 (define-key map "\C-cn" 'html-name-anchor)
1485 (define-key map "\C-ci" 'html-image))
1486 (define-key map "\C-c\C-s" 'html-autoview-mode)
1487 (define-key map "\C-c\C-v" 'browse-url-of-buffer)
1488 (define-key map [menu-bar html] (cons "HTML" menu-map))
1489 (define-key menu-map [html-autoview-mode]
1490 '("Toggle Autoviewing" . html-autoview-mode))
1491 (define-key menu-map [browse-url-of-buffer]
1492 '("View Buffer Contents" . browse-url-of-buffer))
1493 (define-key menu-map [nil] '("--"))
1494 ;;(define-key menu-map "6" '("Heading 6" . html-headline-6))
1495 ;;(define-key menu-map "5" '("Heading 5" . html-headline-5))
1496 ;;(define-key menu-map "4" '("Heading 4" . html-headline-4))
1497 (define-key menu-map "3" '("Heading 3" . html-headline-3))
1498 (define-key menu-map "2" '("Heading 2" . html-headline-2))
1499 (define-key menu-map "1" '("Heading 1" . html-headline-1))
1500 (define-key menu-map "l" '("Radio Buttons" . html-radio-buttons))
1501 (define-key menu-map "c" '("Checkboxes" . html-checkboxes))
1502 (define-key menu-map "l" '("List Item" . html-list-item))
1503 (define-key menu-map "u" '("Unordered List" . html-unordered-list))
1504 (define-key menu-map "o" '("Ordered List" . html-ordered-list))
1505 (define-key menu-map "-" '("Horizontal Rule" . html-horizontal-rule))
1506 (define-key menu-map "\n" '("Line Break" . html-line))
1507 (define-key menu-map "\r" '("Paragraph" . html-paragraph))
1508 (define-key menu-map "i" '("Image" . html-image))
1509 (define-key menu-map "h" '("Href Anchor" . html-href-anchor))
1510 (define-key menu-map "n" '("Name Anchor" . html-name-anchor))
1512 "Keymap for commands for use in HTML mode.")
1514 (defvar html-face-tag-alist
1519 "Value of `sgml-face-tag-alist' for HTML mode.")
1521 (defvar html-tag-face-alist
1524 ("blink" . highlight)
1527 ("h1" bold underline)
1528 ("h2" bold-italic underline)
1529 ("h3" italic underline)
1538 ("title" bold underline)
1542 "Value of `sgml-tag-face-alist' for HTML mode.")
1544 (defvar html-display-text
1548 "Value of `sgml-display-text' for HTML mode.")
1551 ;; should code exactly HTML 3 here when that is finished
1552 (defvar html-tag-alist
1553 (let* ((1-7 '(("1") ("2") ("3") ("4") ("5") ("6") ("7")))
1554 (1-9 `(,@1-7 ("8") ("9")))
1555 (align '(("align" ("left") ("center") ("right"))))
1556 (valign '(("top") ("middle") ("bottom") ("baseline")))
1557 (rel '(("next") ("previous") ("parent") ("subdocument") ("made")))
1558 (href '("href" ("ftp:") ("file:") ("finger:") ("gopher:") ("http:")
1559 ("mailto:") ("news:") ("rlogin:") ("telnet:") ("tn3270:")
1560 ("wais:") ("/cgi-bin/")))
1566 (list '((nil \n ("List item: " "<li>" str
1567 (if sgml-xml-mode "</li>") \n))))
1574 ;; put ,-expressions first, else byte-compile chokes (as of V19.29)
1575 ;; and like this it's more efficient anyway
1576 `(("a" ,name ,@link)
1579 ("font" nil "size" ("-1") ("+1") ("-2") ("+2") ,@1-7)
1580 ("form" (\n _ \n "<input type=\"submit\" value=\"\""
1581 (if sgml-xml-mode " />" ">"))
1582 ("action" ,@(cdr href)) ("method" ("get") ("post")))
1589 ("hr" t ("size" ,@1-9) ("width") ("noshade" t) ,@align)
1590 ("img" t ("align" ,@valign ("texttop") ("absmiddle") ("absbottom"))
1591 ("src") ("alt") ("width" "1") ("height" "1")
1592 ("border" "1") ("vspace" "1") ("hspace" "1") ("ismap" t))
1593 ("input" t ("size" ,@1-9) ("maxlength" ,@1-9) ("checked" t) ,name
1594 ("type" ("text") ("password") ("checkbox") ("radio")
1595 ("submit") ("reset"))
1599 ("ol" ,@list ("type" ("A") ("a") ("I") ("i") ("1")))
1603 "<option>" str (if sgml-xml-mode "</option>") \n))
1604 ,name ("size" ,@1-9) ("multiple" t))
1606 ((completing-read "Cell kind: " '(("td") ("th"))
1609 (if sgml-xml-mode (concat "<" str "></tr>")) \n))
1610 ("border" t ,@1-9) ("width" "10") ("cellpadding"))
1612 ("textarea" ,name ("rows" ,@1-9) ("cols" ,@1-9))
1614 ("ul" ,@list ("type" ("disc") ("circle") ("square")))
1622 ("Item: " "<item>" str (if sgml-xml-mode "</item>") \n))
1629 ("body" \n ("background" ".gif") ("bgcolor" "#") ("text" "#")
1630 ("link" "#") ("alink" "#") ("vlink" "#"))
1631 ("box" (nil _ "<over>" _ (if sgml-xml-mode "</over>")))
1632 ("br" t ("clear" ("left") ("right")))
1633 ("caption" ("valign" ("top") ("bottom")))
1637 ("dd" ,(not sgml-xml-mode))
1643 "<dt>" str (if sgml-xml-mode "</dt>")
1644 "<dd>" _ (if sgml-xml-mode "</dd>") \n)))
1645 ("dt" (t _ (if sgml-xml-mode "</dt>")
1646 "<dd>" (if sgml-xml-mode "</dd>") \n))
1648 ;("fn" "id" "fn") ; ???
1652 "<title>" (setq str (read-input "Title: ")) "</title>\n"
1654 "<body>\n<h1>" str "</h1>\n" _
1655 "\n<address>\n<a href=\"mailto:"
1657 "\">" (user-full-name) "</a>\n</address>\n"
1662 ("isindex" t ("action") ("prompt"))
1665 ("li" ,(not sgml-xml-mode))
1668 ("option" t ("value") ("label") ("selected" t))
1697 "*Value of `sgml-tag-alist' for HTML mode.")
1699 (defvar html-tag-help
1701 ("a" . "Anchor of point or link elsewhere")
1704 ("address" . "Formatted mail address")
1705 ("array" . "Math array")
1708 ("base" . "Base address for URLs")
1709 ("big" . "Font size")
1710 ("blink" . "Blinking text")
1711 ("blockquote" . "Indented quotation")
1712 ("body" . "Document body")
1713 ("box" . "Math fraction")
1714 ("br" . "Line break")
1715 ("caption" . "Table caption")
1716 ("center" . "Centered text")
1717 ("changed" . "Change bars")
1718 ("cite" . "Citation of a document")
1719 ("code" . "Formatted source code")
1720 ("dd" . "Definition of term")
1723 ("dir" . "Directory list (obsolete)")
1724 ("dl" . "Definition list")
1725 ("dt" . "Term to be definined")
1726 ("em" . "Emphasized")
1727 ("embed" . "Embedded data in foreign format")
1729 ("figa" . "Figure anchor")
1730 ("figd" . "Figure description")
1731 ("figt" . "Figure text")
1733 ("font" . "Font size")
1734 ("form" . "Form with input fields")
1735 ("group" . "Document grouping")
1736 ("h1" . "Most important section headline")
1737 ("h2" . "Important section headline")
1738 ("h3" . "Section headline")
1739 ("h4" . "Minor section headline")
1740 ("h5" . "Unimportant section headline")
1741 ("h6" . "Least important section headline")
1742 ("head" . "Document header")
1743 ("hr" . "Horizontal rule")
1744 ("html" . "HTML Document")
1745 ("i" . "Italic face")
1746 ("img" . "Graphic image")
1747 ("input" . "Form input field")
1749 ("isindex" . "Input field for index search")
1750 ("kbd" . "Keybard example face")
1751 ("lang" . "Natural language")
1752 ("li" . "List item")
1753 ("link" . "Link relationship")
1754 ("math" . "Math formula")
1755 ("menu" . "Menu list (obsolete)")
1756 ("mh" . "Form mail header")
1757 ("nextid" . "Allocate new id")
1758 ("nobr" . "Text without line break")
1759 ("ol" . "Ordered list")
1760 ("option" . "Selection list item")
1761 ("over" . "Math fraction rule")
1762 ("p" . "Paragraph start")
1763 ("panel" . "Floating panel")
1765 ("pre" . "Preformatted fixed width text")
1767 ("rev" . "Reverse video")
1769 ("samp" . "Sample text")
1770 ("select" . "Selection list")
1771 ("small" . "Font size")
1772 ("sp" . "Nobreak space")
1773 ("strong" . "Standout text")
1774 ("sub" . "Subscript")
1775 ("sup" . "Superscript")
1776 ("table" . "Table with rows and columns")
1777 ("tb" . "Table vertical break")
1778 ("td" . "Table data cell")
1779 ("textarea" . "Form multiline edit area")
1780 ("th" . "Table header cell")
1781 ("title" . "Document title")
1782 ("tr" . "Table row separator")
1783 ("tt" . "Typewriter face")
1784 ("u" . "Underlined text")
1785 ("ul" . "Unordered list")
1786 ("var" . "Math variable face")
1787 ("wbr" . "Enable <br> within <nobr>"))
1788 "*Value of `sgml-tag-help' for HTML mode.")
1792 (define-derived-mode html-mode sgml-mode "HTML"
1793 "Major mode based on SGML mode for editing HTML documents.
1794 This allows inserting skeleton constructs used in hypertext documents with
1795 completion. See below for an introduction to HTML. Use
1796 \\[browse-url-of-buffer] to see how this comes out. See also `sgml-mode' on
1797 which this is based.
1799 Do \\[describe-variable] html- SPC and \\[describe-variable] sgml- SPC to see available variables.
1801 To write fairly well formatted pages you only need to know few things. Most
1802 browsers have a function to read the source code of the page being seen, so
1803 you can imitate various tricks. Here's a very short HTML primer which you
1804 can also view with a browser to see what happens:
1806 <title>A Title Describing Contents</title> should be on every page. Pages can
1807 have <h1>Very Major Headlines</h1> through <h6>Very Minor Headlines</h6>
1808 <hr> Parts can be separated with horizontal rules.
1810 <p>Paragraphs only need an opening tag. Line breaks and multiple spaces are
1811 ignored unless the text is <pre>preformatted.</pre> Text can be marked as
1812 <b>bold</b>, <i>italic</i> or <u>underlined</u> using the normal M-o or
1813 Edit/Text Properties/Face commands.
1815 Pages can have <a name=\"SOMENAME\">named points</a> and can link other points
1816 to them with <a href=\"#SOMENAME\">see also somename</a>. In the same way <a
1817 href=\"URL\">see also URL</a> where URL is a filename relative to current
1818 directory, or absolute as in `http://www.cs.indiana.edu/elisp/w3/docs.html'.
1820 Images in many formats can be inlined with <img src=\"URL\">.
1822 If you mainly create your own documents, `sgml-specials' might be
1823 interesting. But note that some HTML 2 browsers can't handle `''.
1824 To work around that, do:
1825 (eval-after-load \"sgml-mode\" '(aset sgml-char-names ?' nil))
1828 (set (make-local-variable 'sgml-display-text) html-display-text)
1829 (set (make-local-variable 'sgml-tag-face-alist) html-tag-face-alist)
1830 (make-local-variable 'sgml-tag-alist)
1831 (make-local-variable 'sgml-face-tag-alist)
1832 (make-local-variable 'sgml-tag-help)
1833 (make-local-variable 'outline-regexp)
1834 (make-local-variable 'outline-heading-end-regexp)
1835 (make-local-variable 'outline-level)
1836 (make-local-variable 'sentence-end-base)
1837 (setq sentence-end-base "[.?!][]\"'
\e$B!I
\e$,1r}
\e(B)}]*\\(<[^>]*>\\)*"
1838 sgml-tag-alist html-tag-alist
1839 sgml-face-tag-alist html-face-tag-alist
1840 sgml-tag-help html-tag-help
1841 outline-regexp "^.*<[Hh][1-6]\\>"
1842 outline-heading-end-regexp "</[Hh][1-6]>"
1843 outline-level (lambda ()
1844 (char-before (match-end 0))))
1845 (setq imenu-create-index-function 'html-imenu-index)
1846 (when sgml-xml-mode (setq mode-name "XHTML"))
1847 (set (make-local-variable 'sgml-empty-tags)
1848 ;; From HTML-4.01's loose.dtd, parsed with `sgml-parse-dtd',
1849 ;; plus manual addition of "wbr".
1850 '("area" "base" "basefont" "br" "col" "frame" "hr" "img" "input"
1851 "isindex" "link" "meta" "param" "wbr"))
1852 (set (make-local-variable 'sgml-unclosed-tags)
1853 ;; From HTML-4.01's loose.dtd, parsed with `sgml-parse-dtd'.
1854 '("body" "colgroup" "dd" "dt" "head" "html" "li" "option"
1855 "p" "tbody" "td" "tfoot" "th" "thead" "tr"))
1856 ;; It's for the user to decide if it defeats it or not -stef
1857 ;; (make-local-variable 'imenu-sort-function)
1858 ;; (setq imenu-sort-function nil) ; sorting the menu defeats the purpose
1861 (defvar html-imenu-regexp
1862 "\\s-*<h\\([1-9]\\)[^\n<>]*>\\(<[^\n<>]*>\\)*\\s-*\\([^\n<>]*\\)"
1863 "*A regular expression matching a head line to be added to the menu.
1864 The first `match-string' should be a number from 1-9.
1865 The second `match-string' matches extra tags and is ignored.
1866 The third `match-string' will be the used in the menu.")
1868 (defun html-imenu-index ()
1869 "Return a table of contents for an HTML buffer for use with Imenu."
1872 (goto-char (point-min))
1873 (while (re-search-forward html-imenu-regexp nil t)
1875 (cons (cons (concat (make-string
1876 (* 2 (1- (string-to-number (match-string 1))))
1879 (line-beginning-position))
1881 (nreverse toc-index)))
1883 (define-minor-mode html-autoview-mode
1884 "Toggle automatic viewing via `browse-url-of-buffer' upon saving buffer.
1885 With positive prefix ARG always turns viewing on, with negative ARG always off.
1886 Can be used as a value for `html-mode-hook'."
1889 (if html-autoview-mode
1890 (add-hook 'after-save-hook 'browse-url-of-buffer nil t)
1891 (remove-hook 'after-save-hook 'browse-url-of-buffer t)))
1894 (define-skeleton html-href-anchor
1895 "HTML anchor tag with href attribute."
1897 ;; '(setq input "http:")
1898 "<a href=\"" str "\">" _ "</a>")
1900 (define-skeleton html-name-anchor
1901 "HTML anchor tag with name attribute."
1903 "<a name=\"" str "\""
1904 (if sgml-xml-mode (concat " id=\"" str "\""))
1907 (define-skeleton html-headline-1
1908 "HTML level 1 headline tags."
1912 (define-skeleton html-headline-2
1913 "HTML level 2 headline tags."
1917 (define-skeleton html-headline-3
1918 "HTML level 3 headline tags."
1922 (define-skeleton html-headline-4
1923 "HTML level 4 headline tags."
1927 (define-skeleton html-headline-5
1928 "HTML level 5 headline tags."
1932 (define-skeleton html-headline-6
1933 "HTML level 6 headline tags."
1937 (define-skeleton html-horizontal-rule
1938 "HTML horizontal rule tag."
1940 (if sgml-xml-mode "<hr />" "<hr>") \n)
1942 (define-skeleton html-image
1945 "<img src=\"" str "\" alt=\"" _ "\""
1946 (if sgml-xml-mode " />" ">"))
1948 (define-skeleton html-line
1949 "HTML line break tag."
1951 (if sgml-xml-mode "<br />" "<br>") \n)
1953 (define-skeleton html-ordered-list
1954 "HTML ordered list tags."
1957 "<li>" _ (if sgml-xml-mode "</li>") \n
1960 (define-skeleton html-unordered-list
1961 "HTML unordered list tags."
1964 "<li>" _ (if sgml-xml-mode "</li>") \n
1967 (define-skeleton html-list-item
1968 "HTML list item tag."
1971 "<li>" _ (if sgml-xml-mode "</li>"))
1973 (define-skeleton html-paragraph
1974 "HTML paragraph tag."
1977 "<p>" _ (if sgml-xml-mode "</p>"))
1979 (define-skeleton html-checkboxes
1980 "Group of connected checkbox inputs."
1985 "<input type=\"" (identity "checkbox") ; see comment above about identity
1986 "\" name=\"" (or v1 (setq v1 (skeleton-read "Name: ")))
1987 "\" value=\"" str ?\"
1988 (when (y-or-n-p "Set \"checked\" attribute? ")
1989 (funcall skeleton-transformation-function
1990 (if sgml-xml-mode " checked=\"checked\"" " checked")))
1991 (if sgml-xml-mode " />" ">")
1992 (skeleton-read "Text: " (capitalize str))
1993 (or v2 (setq v2 (if (y-or-n-p "Newline after text? ")
1994 (funcall skeleton-transformation-function
1995 (if sgml-xml-mode "<br />" "<br>"))
1999 (define-skeleton html-radio-buttons
2000 "Group of connected radio button inputs."
2005 "<input type=\"" (identity "radio") ; see comment above about identity
2006 "\" name=\"" (or (car v2) (setcar v2 (skeleton-read "Name: ")))
2007 "\" value=\"" str ?\"
2008 (when (and (not v1) (setq v1 (y-or-n-p "Set \"checked\" attribute? ")))
2009 (funcall skeleton-transformation-function
2010 (if sgml-xml-mode " checked=\"checked\"" " checked")))
2011 (if sgml-xml-mode " />" ">")
2012 (skeleton-read "Text: " (capitalize str))
2013 (or (cdr v2) (setcdr v2 (if (y-or-n-p "Newline after text? ")
2014 (funcall skeleton-transformation-function
2015 (if sgml-xml-mode "<br />" "<br>"))
2019 (provide 'sgml-mode)
2021 ;; arch-tag: 9675da94-b7f9-4bda-ad19-73ed7b4fb401
2022 ;;; sgml-mode.el ends here