sgml-mode.el 76.3 KB
Newer Older
1
;;; sgml-mode.el --- SGML- and HTML-editing modes -*- coding: utf-8 -*-
Eric S. Raymond's avatar
Eric S. Raymond committed
2

3
;; Copyright (C) 1992, 1995, 1996, 1998, 2001, 2002, 2003, 2004,
Glenn Morris's avatar
Glenn Morris committed
4
;;   2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
Eric S. Raymond's avatar
Eric S. Raymond committed
5

6
;; Author: James Clark <jjc@jclark.com>
Stefan Monnier's avatar
Stefan Monnier committed
7
;; Maintainer: FSF
Karl Heuer's avatar
Karl Heuer committed
8
;; Adapted-By: ESR, Daniel Pfeiffer <occitan@esperanto.org>,
9
;;             F.Potorti@cnuce.cnr.it
10
;; Keywords: wp, hypermedia, comm, languages
Eric S. Raymond's avatar
Eric S. Raymond committed
11 12 13

;; This file is part of GNU Emacs.

14
;; GNU Emacs is free software: you can redistribute it and/or modify
Eric S. Raymond's avatar
Eric S. Raymond committed
15
;; it under the terms of the GNU General Public License as published by
16 17
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
Eric S. Raymond's avatar
Eric S. Raymond committed
18 19 20 21 22 23 24

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
25
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
Eric S. Raymond's avatar
Eric S. Raymond committed
26 27 28

;;; Commentary:

29 30 31
;; Configurable major mode for editing document in the SGML standard general
;; markup language.  As an example contains a mode for editing the derived
;; HTML hypertext markup language.
Eric S. Raymond's avatar
Eric S. Raymond committed
32 33 34

;;; Code:

Dave Love's avatar
Dave Love committed
35 36
(eval-when-compile
  (require 'skeleton)
Mike Williams's avatar
Mike Williams committed
37 38
  (require 'outline)
  (require 'cl))
Dave Love's avatar
Dave Love committed
39

40
(defgroup sgml nil
41
  "SGML editing mode."
42
  :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
43 44
  :group 'languages)

Stefan Monnier's avatar
Stefan Monnier committed
45
(defcustom sgml-basic-offset 2
46
  "Specifies the basic indentation level for `sgml-indent-line'."
Stefan Monnier's avatar
Stefan Monnier committed
47 48 49
  :type 'integer
  :group 'sgml)

50
(defcustom sgml-transformation-function 'identity
51
  "Default value for `skeleton-transformation-function' in SGML mode."
52
  :type 'function
53
  :group 'sgml)
54

55
(put 'sgml-transformation-function 'variable-interactive
56
     "aTransformation function: ")
57
(defvaralias 'sgml-transformation 'sgml-transformation-function)
58

Dave Love's avatar
Dave Love committed
59 60 61 62 63 64
(defcustom sgml-mode-hook nil
  "Hook run by command `sgml-mode'.
`text-mode-hook' is run first."
  :group 'sgml
  :type 'hook)

65 66 67
;; As long as Emacs' syntax can't be complemented with predicates to context
;; sensitively confirm the syntax of characters, we have to live with this
;; kludgy kind of tradeoff.
68
(defvar sgml-specials '(?\")
Richard M. Stallman's avatar
Richard M. Stallman committed
69
  "List of characters that have a special meaning for SGML mode.
70
This list is used when first loading the `sgml-mode' library.
71 72 73 74 75 76
The supported characters and potential disadvantages are:

  ?\\\"	Makes \" in text start a string.
  ?'	Makes ' in text start a string.
  ?-	Makes -- in text start a comment.

77
When only one of ?\\\" or ?' are included, \"'\" or '\"', as can be found in
78
DTDs, start a string.  To partially avoid this problem this also makes these
79 80 81 82
self insert as named entities depending on `sgml-quick-keys'.

Including ?- has the problem of affecting dashes that have nothing to do
with comments, so we normally turn it off.")
83 84

(defvar sgml-quick-keys nil
85
  "Use <, >, &, /, SPC and `sgml-specials' keys \"electrically\" when non-nil.
86
This takes effect when first loading the `sgml-mode' library.")
87 88

(defvar sgml-mode-map
89
  (let ((map (make-keymap))	;`sparse' doesn't allow binding to charsets.
90 91 92
	(menu-map (make-sparse-keymap "SGML")))
    (define-key map "\C-c\C-i" 'sgml-tags-invisible)
    (define-key map "/" 'sgml-slash)
93 94
    (define-key map "\C-c\C-n" 'sgml-name-char)
    (define-key map "\C-c\C-t" 'sgml-tag)
95 96 97 98 99 100 101 102
    (define-key map "\C-c\C-a" 'sgml-attributes)
    (define-key map "\C-c\C-b" 'sgml-skip-tag-backward)
    (define-key map [?\C-c left] 'sgml-skip-tag-backward)
    (define-key map "\C-c\C-f" 'sgml-skip-tag-forward)
    (define-key map [?\C-c right] 'sgml-skip-tag-forward)
    (define-key map "\C-c\C-d" 'sgml-delete-tag)
    (define-key map "\C-c\^?" 'sgml-delete-tag)
    (define-key map "\C-c?" 'sgml-tag-help)
Mike Williams's avatar
Mike Williams committed
103
    (define-key map "\C-c/" 'sgml-close-tag)
104 105 106 107 108

    ;; Redundant keybindings, for consistency with TeX mode.
    (define-key map "\C-c\C-o" 'sgml-tag)
    (define-key map "\C-c\C-e" 'sgml-close-tag)

109 110
    (define-key map "\C-c8" 'sgml-name-8bit-mode)
    (define-key map "\C-c\C-v" 'sgml-validate)
111 112 113 114 115 116 117 118 119
    (when sgml-quick-keys
      (define-key map "&" 'sgml-name-char)
      (define-key map "<" 'sgml-tag)
      (define-key map " " 'sgml-auto-attributes)
      (define-key map ">" 'sgml-maybe-end-tag)
      (when (memq ?\" sgml-specials)
        (define-key map "\"" 'sgml-name-self))
      (when (memq ?' sgml-specials)
        (define-key map "'" 'sgml-name-self)))
120 121 122 123
    (let ((c 127)
	  (map (nth 1 map)))
      (while (< (setq c (1+ c)) 256)
	(aset map c 'sgml-maybe-name-self)))
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
    (define-key map [menu-bar sgml] (cons "SGML" menu-map))
    (define-key menu-map [sgml-validate] '("Validate" . sgml-validate))
    (define-key menu-map [sgml-name-8bit-mode]
      '("Toggle 8 Bit Insertion" . sgml-name-8bit-mode))
    (define-key menu-map [sgml-tags-invisible]
      '("Toggle Tag Visibility" . sgml-tags-invisible))
    (define-key menu-map [sgml-tag-help]
      '("Describe Tag" . sgml-tag-help))
    (define-key menu-map [sgml-delete-tag]
      '("Delete Tag" . sgml-delete-tag))
    (define-key menu-map [sgml-skip-tag-forward]
      '("Forward Tag" . sgml-skip-tag-forward))
    (define-key menu-map [sgml-skip-tag-backward]
      '("Backward Tag" . sgml-skip-tag-backward))
    (define-key menu-map [sgml-attributes]
      '("Insert Attributes" . sgml-attributes))
    (define-key menu-map [sgml-tag] '("Insert Tag" . sgml-tag))
    map)
  "Keymap for SGML mode.  See also `sgml-specials'.")

144 145
(defun sgml-make-syntax-table (specials)
  (let ((table (make-syntax-table text-mode-syntax-table)))
146 147
    (modify-syntax-entry ?< "(>" table)
    (modify-syntax-entry ?> ")<" table)
148 149 150 151
    (modify-syntax-entry ?: "_" table)
    (modify-syntax-entry ?_ "_" table)
    (modify-syntax-entry ?. "_" table)
    (if (memq ?- specials)
152
	(modify-syntax-entry ?- "_ 1234" table))
153
    (if (memq ?\" specials)
154
	(modify-syntax-entry ?\" "\"\"" table))
155
    (if (memq ?' specials)
156
	(modify-syntax-entry ?\' "\"'" table))
157 158 159
    table))

(defvar sgml-mode-syntax-table (sgml-make-syntax-table sgml-specials)
160 161
  "Syntax table used in SGML mode.  See also `sgml-specials'.")

162
(defconst sgml-tag-syntax-table
163
  (let ((table (sgml-make-syntax-table sgml-specials)))
164 165
    (dolist (char '(?\( ?\) ?\{ ?\} ?\[ ?\] ?$ ?% ?& ?* ?+ ?/))
      (modify-syntax-entry char "." table))
166 167 168
    (unless (memq ?' sgml-specials)
      ;; Avoid that skipping a tag backwards skips any "'" prefixing it.
      (modify-syntax-entry ?' "w" table))
169 170 171
    table)
  "Syntax table used to parse SGML tags.")

172
(defcustom sgml-name-8bit-mode nil
173
  "When non-nil, insert non-ASCII characters as named entities."
174 175
  :type 'boolean
  :group 'sgml)
Eric S. Raymond's avatar
Eric S. Raymond committed
176

177 178 179 180 181
(defvar sgml-char-names
  [nil nil nil nil nil nil nil nil
   nil nil nil nil nil nil nil nil
   nil nil nil nil nil nil nil nil
   nil nil nil nil nil nil nil nil
182
   "nbsp" "excl" "quot" "num" "dollar" "percnt" "amp" "apos"
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
   "lpar" "rpar" "ast" "plus" "comma" "hyphen" "period" "sol"
   nil nil nil nil nil nil nil nil
   nil nil "colon" "semi" "lt" "eq" "gt" "quest"
   "commat" nil nil nil nil nil nil nil
   nil nil nil nil nil nil nil nil
   nil nil nil nil nil nil nil nil
   nil nil nil "lsqb" nil "rsqb" "uarr" "lowbar"
   "lsquo" nil nil nil nil nil nil nil
   nil nil nil nil nil nil nil nil
   nil nil nil nil nil nil nil nil
   nil nil nil "lcub" "verbar" "rcub" "tilde" nil
   nil nil nil nil nil nil nil nil
   nil nil nil nil nil nil nil nil
   nil nil nil nil nil nil nil nil
   nil nil nil nil nil nil nil nil
   "nbsp" "iexcl" "cent" "pound" "curren" "yen" "brvbar" "sect"
   "uml" "copy" "ordf" "laquo" "not" "shy" "reg" "macr"
   "ring" "plusmn" "sup2" "sup3" "acute" "micro" "para" "middot"
201
   "cedil" "sup1" "ordm" "raquo" "frac14" "frac12" "frac34" "iquest"
202 203 204 205 206 207 208 209 210 211
   "Agrave" "Aacute" "Acirc" "Atilde" "Auml" "Aring" "AElig" "Ccedil"
   "Egrave" "Eacute" "Ecirc" "Euml" "Igrave" "Iacute" "Icirc" "Iuml"
   "ETH" "Ntilde" "Ograve" "Oacute" "Ocirc" "Otilde" "Ouml" nil
   "Oslash" "Ugrave" "Uacute" "Ucirc" "Uuml" "Yacute" "THORN" "szlig"
   "agrave" "aacute" "acirc" "atilde" "auml" "aring" "aelig" "ccedil"
   "egrave" "eacute" "ecirc" "euml" "igrave" "iacute" "icirc" "iuml"
   "eth" "ntilde" "ograve" "oacute" "ocirc" "otilde" "ouml" "divide"
   "oslash" "ugrave" "uacute" "ucirc" "uuml" "yacute" "thorn" "yuml"]
  "Vector of symbolic character names without `&' and `;'.")

212 213 214 215 216 217
(put 'sgml-table 'char-table-extra-slots 0)

(defvar sgml-char-names-table
  (let ((table (make-char-table 'sgml-table))
	(i 32)
	elt)
218
    (while (< i 128)
219 220 221 222 223 224 225
      (setq elt (aref sgml-char-names i))
      (if elt (aset table (make-char 'latin-iso8859-1 i) elt))
      (setq i (1+ i)))
    table)
  "A table for mapping non-ASCII characters into SGML entity names.
Currently, only Latin-1 characters are supported.")

226 227
;; nsgmls is a free SGML parser in the SP suite available from
;; ftp.jclark.com and otherwise packaged for GNU systems.
228 229 230
;; Its error messages can be parsed by next-error.
;; The -s option suppresses output.

231
(defcustom sgml-validate-command "nsgmls -s" ; replaced old `sgmls'
232
  "The command to validate an SGML document.
Eric S. Raymond's avatar
Eric S. Raymond committed
233
The file name of current buffer file name will be appended to this,
234 235
separated by a space."
  :type 'string
Dave Love's avatar
Dave Love committed
236
  :version "21.1"
237
  :group 'sgml)
Eric S. Raymond's avatar
Eric S. Raymond committed
238 239 240 241

(defvar sgml-saved-validate-command nil
  "The command last used to validate in this buffer.")

242 243
;; I doubt that null end tags are used much for large elements,
;; so use a small distance here.
244
(defcustom sgml-slash-distance 1000
245
  "If non-nil, is the maximum distance to search for matching `/'."
246 247
  :type '(choice (const nil) integer)
  :group 'sgml)
Eric S. Raymond's avatar
Eric S. Raymond committed
248

249
(defconst sgml-namespace-re "[_[:alpha:]][-_.[:alnum:]]*")
Stefan Monnier's avatar
Stefan Monnier committed
250 251 252 253
(defconst sgml-name-re "[_:[:alpha:]][-_.:[:alnum:]]*")
(defconst sgml-tag-name-re (concat "<\\([!/?]?" sgml-name-re "\\)"))
(defconst sgml-attrs-re "\\(?:[^\"'/><]\\|\"[^\"]*\"\\|'[^']*'\\)*")
(defconst sgml-start-tag-regex (concat "<" sgml-name-re sgml-attrs-re)
254
  "Regular expression that matches a non-empty start tag.
Richard M. Stallman's avatar
Richard M. Stallman committed
255
Any terminating `>' or `/' is not matched.")
256

257
(defface sgml-namespace
258
  '((t (:inherit font-lock-builtin-face)))
259 260
  "`sgml-mode' face used to highlight the namespace part of identifiers."
  :group 'sgml)
261
(defvar sgml-namespace-face 'sgml-namespace)
262

263 264
;; internal
(defconst sgml-font-lock-keywords-1
Stefan Monnier's avatar
Stefan Monnier committed
265
  `((,(concat "<\\([!?]" sgml-name-re "\\)") 1 font-lock-keyword-face)
266 267 268 269 270
    ;; We could use the simpler "\\(" sgml-namespace-re ":\\)?" instead,
    ;; but it would cause a bit more backtracking in the re-matcher.
    (,(concat "</?\\(" sgml-namespace-re "\\)\\(?::\\(" sgml-name-re "\\)\\)?")
     (1 (if (match-end 2) sgml-namespace-face font-lock-function-name-face))
     (2 font-lock-function-name-face nil t))
271
    ;; FIXME: this doesn't cover the variables using a default value.
272 273 274 275
    ;; The first shy-group is an important anchor: it prevents an O(n^2)
    ;; pathological case where we otherwise keep retrying a failing match
    ;; against a very long word at every possible position within the word.
    (,(concat "\\(?:^\\|[ \t]\\)\\(" sgml-namespace-re "\\)\\(?::\\("
276 277 278
	      sgml-name-re "\\)\\)?=[\"']")
     (1 (if (match-end 2) sgml-namespace-face font-lock-variable-name-face))
     (2 font-lock-variable-name-face nil t))
Stefan Monnier's avatar
Stefan Monnier committed
279
    (,(concat "[&%]" sgml-name-re ";?") . font-lock-variable-name-face)))
280 281 282 283 284 285 286 287

(defconst sgml-font-lock-keywords-2
  (append
   sgml-font-lock-keywords-1
   '((eval
      . (cons (concat "<"
		      (regexp-opt (mapcar 'car sgml-tag-face-alist) t)
		      "\\([ \t][^>]*\\)?>\\([^<]+\\)</\\1>")
288 289
	      '(3 (cdr (assoc-string (match-string 1) sgml-tag-face-alist t))
		prepend))))))
290 291 292 293

;; for font-lock, but must be defvar'ed after
;; sgml-font-lock-keywords-1 and sgml-font-lock-keywords-2 above
(defvar sgml-font-lock-keywords sgml-font-lock-keywords-1
294 295
  "*Rules for highlighting SGML code.  See also `sgml-tag-face-alist'.")

296 297 298 299 300
(defvar sgml-font-lock-syntactic-keywords
  ;; Use the `b' style of comments to avoid interference with the -- ... --
  ;; comments recognized when `sgml-specials' includes ?-.
  ;; FIXME: beware of <!--> blabla <!--> !!
  '(("\\(<\\)!--" (1 "< b"))
301 302
    ("--[ \t\n]*\\(>\\)" (1 "> b"))
    ;; Double quotes outside of tags should not introduce strings.
303 304 305 306 307
    ;; Be careful to call `syntax-ppss' on a position before the one we're
    ;; going to change, so as not to need to flush the data we just computed.
    ("\"" (0 (if (prog1 (zerop (car (syntax-ppss (match-beginning 0))))
                   (goto-char (match-end 0)))
                 "."))))
308 309
  "Syntactic keywords for `sgml-mode'.")

310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
;; internal
(defvar sgml-face-tag-alist ()
  "Alist of face and tag name for facemenu.")

(defvar sgml-tag-face-alist ()
  "Tag names and face or list of faces to fontify with when invisible.
When `font-lock-maximum-decoration' is 1 this is always used for fontifying.
When more these are fontified together with `sgml-font-lock-keywords'.")

(defvar sgml-display-text ()
  "Tag names as lowercase symbols, and display string when invisible.")

;; internal
(defvar sgml-tags-invisible nil)

325
(defcustom sgml-tag-alist
326 327
  '(("![" ("ignore" t) ("include" t))
    ("!attlist")
328 329 330
    ("!doctype")
    ("!element")
    ("!entity"))
331
  "Alist of tag names for completing read and insertion rules.
332 333 334 335 336
This alist is made up as

  ((\"tag\" . TAGRULE)
   ...)

Mike Williams's avatar
Mike Williams committed
337 338
TAGRULE is a list of optionally t (no endtag) or `\\n' (separate endtag by
newlines) or a skeleton with nil, t or `\\n' in place of the interactor
339 340 341 342 343 344 345 346
followed by an ATTRIBUTERULE (for an always present attribute) or an
attribute alist.

The attribute alist is made up as

  ((\"attribute\" . ATTRIBUTERULE)
   ...)

Mike Williams's avatar
Mike Williams committed
347
ATTRIBUTERULE is a list of optionally t (no value when no input) followed by
348 349 350 351
an optional alist of possible values."
  :type '(repeat (cons (string :tag "Tag Name")
		       (repeat :tag "Tag Rule" sexp)))
  :group 'sgml)
352
(put 'sgml-tag-alist 'risky-local-variable t)
353

354
(defcustom sgml-tag-help
355 356 357 358 359 360
  '(("!" . "Empty declaration for comment")
    ("![" . "Embed declarations with parser directive")
    ("!attlist" . "Tag attributes declaration")
    ("!doctype" . "Document type (DTD) declaration")
    ("!element" . "Tag declaration")
    ("!entity" . "Entity (macro) declaration"))
361
  "Alist of tag name and short description."
362 363 364
  :type '(repeat (cons (string :tag "Tag Name")
		       (string :tag "Description")))
  :group 'sgml)
365

366
(defcustom sgml-xml-mode nil
367 368
  "When non-nil, tag insertion functions will be XML-compliant.
It is set to be buffer-local when the file has
Juri Linkov's avatar
Juri Linkov committed
369
a DOCTYPE or an XML declaration."
370
  :type 'boolean
371
  :version "22.1"
372 373
  :group 'sgml)

Stefan Monnier's avatar
Stefan Monnier committed
374 375 376
(defvar sgml-empty-tags nil
  "List of tags whose !ELEMENT definition says EMPTY.")

Stefan Monnier's avatar
Stefan Monnier committed
377 378 379
(defvar sgml-unclosed-tags nil
  "List of tags whose !ELEMENT definition says the end-tag is optional.")

380
(defun sgml-xml-guess ()
381
  "Guess whether the current buffer is XML.  Return non-nil if so."
382 383
  (save-excursion
    (goto-char (point-min))
384 385 386 387
    (or (string= "xml" (file-name-extension (or buffer-file-name "")))
	(looking-at "\\s-*<\\?xml")
	(when (re-search-forward
	       (eval-when-compile
388 389
		 (mapconcat 'identity
			    '("<!DOCTYPE" "\\(\\w+\\)" "\\(\\w+\\)"
390 391 392 393
			      "\"\\([^\"]+\\)\"" "\"\\([^\"]+\\)\"")
			    "\\s-+"))
	       nil t)
	  (string-match "X\\(HT\\)?ML" (match-string 3))))))
394

Dave Love's avatar
Dave Love committed
395 396
(defvar v2)				; free for skeleton

397 398 399 400 401 402 403
(defun sgml-comment-indent-new-line (&optional soft)
  (let ((comment-start "-- ")
	(comment-start-skip "\\(<!\\)?--[ \t]*")
	(comment-end " --")
	(comment-style 'plain))
    (comment-indent-new-line soft)))

404
(defun sgml-mode-facemenu-add-face-function (face end)
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
  (let ((tag-face (cdr (assq face sgml-face-tag-alist))))
    (cond (tag-face
	   (setq tag-face (funcall skeleton-transformation-function tag-face))
	   (setq facemenu-end-add-face (concat "</" tag-face ">"))
	   (concat "<" tag-face ">"))
	  ((and (consp face)
		(consp (car face))
		(null  (cdr face))
		(memq (caar face) '(:foreground :background)))
	   (setq facemenu-end-add-face "</span>")
	   (format "<span style=\"%s:%s\">"
		   (if (eq (caar face) :foreground)
		       "color"
		     "background-color")
		   (cadr (car face))))
	  (t
	   (error "Face not configured for %s mode"
		  (format-mode-line mode-name))))))
423

Stefan Monnier's avatar
Stefan Monnier committed
424 425 426 427 428 429 430 431
(defun sgml-fill-nobreak ()
  ;; Don't break between a tag name and its first argument.
  (save-excursion
    (skip-chars-backward " \t")
    (and (not (zerop (skip-syntax-backward "w_")))
	 (skip-chars-backward "/?!")
	 (eq (char-before) ?<))))

432
;;;###autoload
433
(define-derived-mode sgml-mode text-mode '(sgml-xml-mode "XML" "SGML")
434 435
  "Major mode for editing SGML documents.
Makes > match <.
436
Keys <, &, SPC within <>, \", / and ' can be electric depending on
437 438 439 440 441 442
`sgml-quick-keys'.

An argument of N to a tag-inserting command means to wrap it around
the next N words.  In Transient Mark mode, when the mark is active,
N defaults to -1, which means to wrap it around the current region.

443 444
If you like upcased tags, put (setq sgml-transformation-function 'upcase)
in your `.emacs' file.
445 446 447 448 449 450

Use \\[sgml-validate] to validate your document with an SGML parser.

Do \\[describe-variable] sgml- SPC to see available variables.
Do \\[describe-key] on the following bindings to discover what they do.
\\{sgml-mode-map}"
Eric S. Raymond's avatar
Eric S. Raymond committed
451
  (make-local-variable 'sgml-saved-validate-command)
452 453
  (make-local-variable 'facemenu-end-add-face)
  ;;(make-local-variable 'facemenu-remove-face-function)
454 455 456
  ;; A start or end tag by itself on a line separates a paragraph.
  ;; This is desirable because SGML discards a newline that appears
  ;; immediately after a start tag or immediately before an end tag.
Stefan Monnier's avatar
Stefan Monnier committed
457 458 459 460
  (set (make-local-variable 'paragraph-start) (concat "[ \t]*$\\|\
\[ \t]*</?\\(" sgml-name-re sgml-attrs-re "\\)?>"))
  (set (make-local-variable 'paragraph-separate)
       (concat paragraph-start "$"))
461
  (set (make-local-variable 'adaptive-fill-regexp) "[ \t]*")
Stefan Monnier's avatar
Stefan Monnier committed
462
  (add-hook 'fill-nobreak-predicate 'sgml-fill-nobreak nil t)
463
  (set (make-local-variable 'indent-line-function) 'sgml-indent-line)
464 465 466
  (set (make-local-variable 'comment-start) "<!-- ")
  (set (make-local-variable 'comment-end) " -->")
  (set (make-local-variable 'comment-indent-function) 'sgml-comment-indent)
467 468
  (set (make-local-variable 'comment-line-break-function)
       'sgml-comment-indent-new-line)
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
  (set (make-local-variable 'skeleton-further-elements)
       '((completion-ignore-case t)))
  (set (make-local-variable 'skeleton-end-hook)
       (lambda ()
         (or (eolp)
             (not (or (eq v2 '\n) (eq (car-safe v2) '\n)))
             (newline-and-indent))))
  (set (make-local-variable 'font-lock-defaults)
       '((sgml-font-lock-keywords
          sgml-font-lock-keywords-1
          sgml-font-lock-keywords-2)
         nil t nil nil
         (font-lock-syntactic-keywords
          . sgml-font-lock-syntactic-keywords)))
  (set (make-local-variable 'facemenu-add-face-function)
       'sgml-mode-facemenu-add-face-function)
485
  (set (make-local-variable 'sgml-xml-mode) (sgml-xml-guess))
486
  (if sgml-xml-mode
487
      ()
488 489
    (set (make-local-variable 'skeleton-transformation-function)
         sgml-transformation-function))
490 491
  ;; This will allow existing comments within declarations to be
  ;; recognized.
492 493 494 495 496 497
  ;; I can't find a clear description of SGML/XML comments, but it seems that
  ;; the only reliable ones are <!-- ... --> although it's not clear what
  ;; "..." can contain.  It used to accept -- ... -- as well, but that was
  ;; apparently a mistake.
  (set (make-local-variable 'comment-start-skip) "<!--[ \t]*")
  (set (make-local-variable 'comment-end-skip) "[ \t]*--[ \t\n]*>")
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
  ;; This definition has an HTML leaning but probably fits well for other modes.
  (setq imenu-generic-expression
	`((nil
	   ,(concat "<!\\(element\\|entity\\)[ \t\n]+%?[ \t\n]*\\("
		    sgml-name-re "\\)")
	   2)
	  ("Id"
	   ,(concat "<[^>]+[ \t\n]+[Ii][Dd]=\\(['\"]"
		    (if sgml-xml-mode "" "?")
		    "\\)\\(" sgml-name-re "\\)\\1")
	   2)
	  ("Name"
	   ,(concat "<[^>]+[ \t\n]+[Nn][Aa][Mm][Ee]=\\(['\"]"
		    (if sgml-xml-mode "" "?")
		    "\\)\\(" sgml-name-re "\\)\\1")
	   2))))
514

Eric S. Raymond's avatar
Eric S. Raymond committed
515
(defun sgml-comment-indent ()
516
  (if (looking-at "--") comment-column 0))
Eric S. Raymond's avatar
Eric S. Raymond committed
517 518

(defun sgml-slash (arg)
519 520 521 522 523 524 525 526 527 528
  "Insert ARG slash characters.
Behaves electrically if `sgml-quick-keys' is non-nil."
  (interactive "p")
  (cond
   ((not (and (eq (char-before) ?<) (= arg 1)))
    (sgml-slash-matching arg))
   ((eq sgml-quick-keys 'indent)
    (insert-char ?/ 1)
    (indent-according-to-mode))
   ((eq sgml-quick-keys 'close)
529
    (delete-char -1)
Mike Williams's avatar
Mike Williams committed
530
    (sgml-close-tag))
531 532 533 534
   (t
    (sgml-slash-matching arg))))

(defun sgml-slash-matching (arg)
Richard M. Stallman's avatar
Richard M. Stallman committed
535 536 537
  "Insert `/' and display any previous matching `/'.
Two `/'s are treated as matching if the first `/' ends a net-enabling
start tag, and the second `/' is the corresponding null end tag."
Eric S. Raymond's avatar
Eric S. Raymond committed
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
  (interactive "p")
  (insert-char ?/ arg)
  (if (> arg 0)
      (let ((oldpos (point))
	    (blinkpos)
	    (level 0))
	(save-excursion
	  (save-restriction
	    (if sgml-slash-distance
		(narrow-to-region (max (point-min)
				       (- (point) sgml-slash-distance))
				  oldpos))
	    (if (and (re-search-backward sgml-start-tag-regex (point-min) t)
		     (eq (match-end 0) (1- oldpos)))
		()
	      (goto-char (1- oldpos))
	      (while (and (not blinkpos)
			  (search-backward "/" (point-min) t))
		(let ((tagend (save-excursion
				(if (re-search-backward sgml-start-tag-regex
							(point-min) t)
				    (match-end 0)
				  nil))))
		  (if (eq tagend (point))
		      (if (eq level 0)
			  (setq blinkpos (point))
			(setq level (1- level)))
		    (setq level (1+ level)))))))
566 567 568 569 570 571 572
	  (when blinkpos
            (goto-char blinkpos)
            (if (pos-visible-in-window-p)
                (sit-for 1)
              (message "Matches %s"
                       (buffer-substring (line-beginning-position)
                                         (1+ blinkpos)))))))))
Eric S. Raymond's avatar
Eric S. Raymond committed
573

Stefan Monnier's avatar
Stefan Monnier committed
574 575 576
;; Why doesn't this use the iso-cvt table or, preferably, generate the
;; inverse of the extensive table in the SGML Quail input method?  -- fx
;; I guess that's moot since it only works with Latin-1 anyhow.
577 578
(defun sgml-name-char (&optional char)
  "Insert a symbolic character name according to `sgml-char-names'.
579 580 581
Non-ASCII chars may be inserted either with the meta key, as in M-SPC for
no-break space or M-- for a soft hyphen; or via an input method or
encoded keyboard operation."
582 583 584
  (interactive "*")
  (insert ?&)
  (or char
585
      (setq char (read-quoted-char "Enter char or octal number")))
586
  (delete-char -1)
587 588
  (insert char)
  (undo-boundary)
Stefan Monnier's avatar
Stefan Monnier committed
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
  (sgml-namify-char))

(defun sgml-namify-char ()
  "Change the char before point into its `&name;' equivalent.
Uses `sgml-char-names'."
  (interactive)
  (let* ((char (char-before))
	 (name
	  (cond
	   ((null char) (error "No char before point"))
	   ((< char 256) (or (aref sgml-char-names char) char))
	   ((aref sgml-char-names-table char))
	   ((encode-char char 'ucs)))))
    (if (not name)
	(error "Don't know the name of `%c'" char)
604
      (delete-char -1)
Stefan Monnier's avatar
Stefan Monnier committed
605
      (insert (format (if (numberp name) "&#%d;" "&%s;") name)))))
606 607 608 609

(defun sgml-name-self ()
  "Insert a symbolic character name according to `sgml-char-names'."
  (interactive "*")
610
  (sgml-name-char last-command-event))
611 612 613 614 615

(defun sgml-maybe-name-self ()
  "Insert a symbolic character name according to `sgml-char-names'."
  (interactive "*")
  (if sgml-name-8bit-mode
616
      (sgml-name-char last-command-event)
617 618 619
    (self-insert-command 1)))

(defun sgml-name-8bit-mode ()
Stefan Monnier's avatar
Stefan Monnier committed
620 621
  "Toggle whether to insert named entities instead of non-ASCII characters.
This only works for Latin-1 input."
622
  (interactive)
623
  (setq sgml-name-8bit-mode (not sgml-name-8bit-mode))
624
  (message "sgml name entity mode is now %s"
625
	   (if sgml-name-8bit-mode "ON" "OFF")))
626

Richard M. Stallman's avatar
Richard M. Stallman committed
627
;; When an element of a skeleton is a string "str", it is passed
628 629 630
;; through `skeleton-transformation-function' and inserted.
;; If "str" is to be inserted literally, one should obtain it as
;; the return value of a function, e.g. (identity "str").
631

Stefan Monnier's avatar
Stefan Monnier committed
632 633
(defvar sgml-tag-last nil)
(defvar sgml-tag-history nil)
634
(define-skeleton sgml-tag
Richard M. Stallman's avatar
Richard M. Stallman committed
635 636
  "Prompt for a tag and insert it, optionally with attributes.
Completion and configuration are done according to `sgml-tag-alist'.
637
If you like tags and attributes in uppercase do \\[set-variable]
638 639 640 641
`skeleton-transformation-function' RET `upcase' RET, or put this
in your `.emacs':
  (setq sgml-transformation-function 'upcase)"
  (funcall (or skeleton-transformation-function 'identity)
Stefan Monnier's avatar
Stefan Monnier committed
642 643 644 645 646 647
           (setq sgml-tag-last
		 (completing-read
		  (if (> (length sgml-tag-last) 0)
		      (format "Tag (default %s): " sgml-tag-last)
		    "Tag: ")
		  sgml-tag-alist nil nil nil 'sgml-tag-history sgml-tag-last)))
648
  ?< str |
649
  (("") -1 '(undo-boundary) (identity "&lt;")) |	; see comment above
Stefan Monnier's avatar
Stefan Monnier committed
650 651 652 653 654
  `(("") '(setq v2 (sgml-attributes ,str t)) ?>
    (cond
     ((string= "![" ,str)
      (backward-char)
      '(("") " [ " _ " ]]"))
655
     ((and (eq v2 t) sgml-xml-mode (member ,str sgml-empty-tags))
Juri Linkov's avatar
Juri Linkov committed
656
      '(("") -1 " />"))
657
     ((or (and (eq v2 t) (not sgml-xml-mode)) (string-match "^[/!?]" ,str))
Stefan Monnier's avatar
Stefan Monnier committed
658 659 660 661 662 663
      nil)
     ((symbolp v2)
      ;; Make sure we don't fall into an infinite loop.
      ;; For xhtml's `tr' tag, we should maybe use \n instead.
      (if (eq v2 t) (setq v2 nil))
      ;; We use `identity' to prevent skeleton from passing
664
      ;; `str' through `skeleton-transformation-function' a second time.
Stefan Monnier's avatar
Stefan Monnier committed
665 666 667 668 669 670 671
      '(("") v2 _ v2 "</" (identity ',str) ?>))
     ((eq (car v2) t)
      (cons '("") (cdr v2)))
     (t
      (append '(("") (car v2))
	      (cdr v2)
	      '(resume: (car v2) _ "</" (identity ',str) ?>))))))
672 673 674

(autoload 'skeleton-read "skeleton")

675
(defun sgml-attributes (tag &optional quiet)
Richard M. Stallman's avatar
Richard M. Stallman committed
676
  "When at top level of a tag, interactively insert attributes.
677

Richard M. Stallman's avatar
Richard M. Stallman committed
678 679
Completion and configuration of TAG are done according to `sgml-tag-alist'.
If QUIET, do not print a message when there are no attributes for TAG."
680
  (interactive (list (save-excursion (sgml-beginning-of-tag t))))
681 682
  (or (stringp tag) (error "Wrong context for adding attribute"))
  (if tag
683
      (let ((completion-ignore-case t)
684
	    (alist (cdr (assoc (downcase tag) sgml-tag-alist)))
685 686 687 688 689 690 691 692 693
	    car attribute i)
	(if (or (symbolp (car alist))
		(symbolp (car (car alist))))
	    (setq car (car alist)
		  alist (cdr alist)))
	(or quiet
	    (message "No attributes configured."))
	(if (stringp (car alist))
	    (progn
694
	      (insert (if (eq (preceding-char) ?\s) "" ?\s)
695
		      (funcall skeleton-transformation-function (car alist)))
696 697 698
	      (sgml-value alist))
	  (setq i (length alist))
	  (while (> i 0)
699
	    (insert ?\s)
700
	    (insert (funcall skeleton-transformation-function
701 702
			     (setq attribute
				   (skeleton-read '(completing-read
703
						    "Attribute: "
704 705 706
						    alist)))))
	    (if (string= "" attribute)
		(setq i 0)
707
	      (sgml-value (assoc (downcase attribute) alist))
708
	      (setq i (1- i))))
709
	  (if (eq (preceding-char) ?\s)
710
	      (delete-char -1)))
711 712 713
	car)))

(defun sgml-auto-attributes (arg)
Richard M. Stallman's avatar
Richard M. Stallman committed
714 715
  "Self insert the character typed; at top level of tag, prompt for attributes.
With prefix argument, only self insert."
716 717 718 719 720 721 722 723 724
  (interactive "*P")
  (let ((point (point))
	tag)
    (if (or arg
	    (not sgml-tag-alist)	; no message when nothing configured
	    (symbolp (setq tag (save-excursion (sgml-beginning-of-tag t))))
	    (eq (aref tag 0) ?/))
	(self-insert-command (prefix-numeric-value arg))
      (sgml-attributes tag)
725
      (setq last-command-event ?\s)
726 727 728 729
      (or (> (point) point)
	  (self-insert-command 1)))))

(defun sgml-tag-help (&optional tag)
Richard M. Stallman's avatar
Richard M. Stallman committed
730
  "Display description of tag TAG.  If TAG is omitted, use the tag at point."
731 732 733 734 735 736 737 738 739 740
  (interactive
   (list (let ((def (save-excursion
		      (if (eq (following-char) ?<) (forward-char))
		      (sgml-beginning-of-tag))))
	   (completing-read (if def
				(format "Tag (default %s): " def)
			      "Tag: ")
			    sgml-tag-alist nil nil nil
			    'sgml-tag-history def))))
  (or (and tag (> (length tag) 0))
741 742 743 744 745 746 747
      (save-excursion
	(if (eq (following-char) ?<)
	    (forward-char))
	(setq tag (sgml-beginning-of-tag))))
  (or (stringp tag)
      (error "No tag selected"))
  (setq tag (downcase tag))
748
  (message "%s"
749
	   (or (cdr (assoc (downcase tag) sgml-tag-help))
750
	       (and (eq (aref tag 0) ?/)
751
		    (cdr (assoc (downcase (substring tag 1)) sgml-tag-help)))
752 753
	       "No description available")))

754 755 756 757 758 759
(defun sgml-maybe-end-tag (&optional arg)
  "Name self unless in position to end a tag or a prefix ARG is given."
  (interactive "P")
  (if (or arg (eq (car (sgml-lexical-context)) 'tag))
      (self-insert-command (prefix-numeric-value arg))
    (sgml-name-self)))
760 761 762

(defun sgml-skip-tag-backward (arg)
  "Skip to beginning of tag or matching opening tag if present.
763 764
With prefix argument ARG, repeat this ARG times.
Return non-nil if we skipped over matched tags."
765
  (interactive "p")
Stefan Monnier's avatar
Stefan Monnier committed
766
  ;; FIXME: use sgml-get-context or something similar.
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
  (let ((return t))
    (while (>= arg 1)
      (search-backward "<" nil t)
      (if (looking-at "</\\([^ \n\t>]+\\)")
          ;; end tag, skip any nested pairs
          (let ((case-fold-search t)
                (re (concat "</?" (regexp-quote (match-string 1))
                            ;; Ignore empty tags like <foo/>.
                            "\\([^>]*[^/>]\\)?>")))
            (while (and (re-search-backward re nil t)
                        (eq (char-after (1+ (point))) ?/))
              (forward-char 1)
              (sgml-skip-tag-backward 1)))
        (setq return nil))
      (setq arg (1- arg)))
    return))

(defvar sgml-electric-tag-pair-overlays nil)
(defvar sgml-electric-tag-pair-timer nil)

(defun sgml-electric-tag-pair-before-change-function (beg end)
  (condition-case err
  (save-excursion
    (goto-char end)
    (skip-chars-backward "[:alnum:]-_.:")
    (if (and ;; (<= (point) beg) ; This poses problems for downcase-word.
             (or (eq (char-before) ?<)
                 (and (eq (char-before) ?/)
                      (eq (char-before (1- (point))) ?<)))
             (null (get-char-property (point) 'text-clones)))
        (let* ((endp (eq (char-before) ?/))
               (cl-start (point))
               (cl-end (progn (skip-chars-forward "[:alnum:]-_.:") (point)))
               (match
                (if endp
                    (when (sgml-skip-tag-backward 1) (forward-char 1) t)
                  (with-syntax-table sgml-tag-syntax-table
                    (up-list -1)
                    (when (sgml-skip-tag-forward 1)
                      (backward-sexp 1)
                      (forward-char 2)
                      t))))
               (clones (get-char-property (point) 'text-clones)))
          (when (and match
                     (/= cl-end cl-start)
                     (equal (buffer-substring cl-start cl-end)
                            (buffer-substring (point)
                                              (save-excursion
                                                (skip-chars-forward "[:alnum:]-_.:")
                                                (point))))
                     (or (not endp) (eq (char-after cl-end) ?>)))
            (when clones
              (message "sgml-electric-tag-pair-before-change-function: deleting old OLs")
              (mapc 'delete-overlay clones))
            (message "sgml-electric-tag-pair-before-change-function: new clone")
            (text-clone-create cl-start cl-end 'spread "[[:alnum:]-_.:]+")
            (setq sgml-electric-tag-pair-overlays
                  (append (get-char-property (point) 'text-clones)
                          sgml-electric-tag-pair-overlays))))))
  (scan-error nil)
  (error (message "Error in sgml-electric-pair-mode: %s" err))))

(defun sgml-electric-tag-pair-flush-overlays ()
  (while sgml-electric-tag-pair-overlays
    (delete-overlay (pop sgml-electric-tag-pair-overlays))))

(define-minor-mode sgml-electric-tag-pair-mode
  "Automatically update the closing tag when editing the opening one."
  :lighter "/e"
  (if sgml-electric-tag-pair-mode
      (progn
        (add-hook 'before-change-functions
                  'sgml-electric-tag-pair-before-change-function
                  nil t)
        (unless sgml-electric-tag-pair-timer
          (setq sgml-electric-tag-pair-timer
                (run-with-idle-timer 5 'repeat 'sgml-electric-tag-pair-flush-overlays))))
    (remove-hook 'before-change-functions
                 'sgml-electric-tag-pair-before-change-function
                 t)
    ;; We leave the timer running for other buffers.
    ))

850

851
(defun sgml-skip-tag-forward (arg)
852
  "Skip to end of tag or matching closing tag if present.
Richard M. Stallman's avatar
Richard M. Stallman committed
853
With prefix argument ARG, repeat this ARG times.
854
Return t if after a closing tag."
855
  (interactive "p")
Stefan Monnier's avatar
Stefan Monnier committed
856 857 858
  ;; FIXME: Use sgml-get-context or something similar.
  ;; It currently might jump to an unrelated </P> if the <P>
  ;; we're skipping has no matching </P>.
859
  (let ((return t))
Stefan Monnier's avatar
Stefan Monnier committed
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
    (with-syntax-table sgml-tag-syntax-table
      (while (>= arg 1)
	(skip-chars-forward "^<>")
	(if (eq (following-char) ?>)
	    (up-list -1))
	(if (looking-at "<\\([^/ \n\t>]+\\)\\([^>]*[^/>]\\)?>")
	    ;; start tag, skip any nested same pairs _and_ closing tag
	    (let ((case-fold-search t)
		  (re (concat "</?" (regexp-quote (match-string 1))
			      ;; Ignore empty tags like <foo/>.
			      "\\([^>]*[^/>]\\)?>"))
		  point close)
	      (forward-list 1)
	      (setq point (point))
	      ;; FIXME: This re-search-forward will mistakenly match
	      ;; tag-like text inside attributes.
	      (while (and (re-search-forward re nil t)
			  (not (setq close
				     (eq (char-after (1+ (match-beginning 0))) ?/)))
			  (goto-char (match-beginning 0))
			  (sgml-skip-tag-forward 1))
		(setq close nil))
	      (unless close
		(goto-char point)
		(setq return nil)))
	  (forward-list 1))
	(setq arg (1- arg)))
      return)))
888

889 890 891 892 893 894
(defsubst sgml-looking-back-at (str)
  "Return t if the test before point matches STR."
  (let ((start (- (point) (length str))))
    (and (>= start (point-min))
         (equal str (buffer-substring-no-properties start (point))))))

895
(defun sgml-delete-tag (arg)
Stefan Monnier's avatar
Stefan Monnier committed
896
  ;; FIXME: Should be called sgml-kill-tag or should not touch the kill-ring.
897
  "Delete tag on or after cursor, and matching closing or opening tag.
Richard M. Stallman's avatar
Richard M. Stallman committed
898
With prefix argument ARG, repeat this ARG times."
899 900 901 902
  (interactive "p")
  (while (>= arg 1)
    (save-excursion
      (let* (close open)
903
	(if (looking-at "[ \t\n]*<")
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
	    ;; just before tag
	    (if (eq (char-after (match-end 0)) ?/)
		;; closing tag
		(progn
		  (setq close (point))
		  (goto-char (match-end 0))))
	  ;; on tag?
	  (or (save-excursion (setq close (sgml-beginning-of-tag)
				    close (and (stringp close)
					       (eq (aref close 0) ?/)
					       (point))))
	      ;; not on closing tag
	      (let ((point (point)))
		(sgml-skip-tag-backward 1)
		(if (or (not (eq (following-char) ?<))
			(save-excursion
			  (forward-list 1)
			  (<= (point) point)))
		    (error "Not on or before tag")))))
	(if close
	    (progn
	      (sgml-skip-tag-backward 1)
	      (setq open (point))
	      (goto-char close)
	      (kill-sexp 1))
	  (setq open (point))
Juri Linkov's avatar
Juri Linkov committed
930
	  (when (and (sgml-skip-tag-forward 1)
931
		     (not (sgml-looking-back-at "/>")))
Stefan Monnier's avatar
Stefan Monnier committed
932 933 934 935 936
	    (kill-sexp -1)))
	;; Delete any resulting empty line.  If we didn't kill-sexp,
	;; this *should* do nothing, because we're right after the tag.
	(if (progn (forward-line 0) (looking-at "\\(?:[ \t]*$\\)\n?"))
	    (delete-region (match-beginning 0) (match-end 0)))
937
	(goto-char open)
Stefan Monnier's avatar
Stefan Monnier committed
938 939 940
	(kill-sexp 1)
	(if (progn (forward-line 0) (looking-at "\\(?:[ \t]*$\\)\n?"))
	    (delete-region (match-beginning 0) (match-end 0)))))
941
    (setq arg (1- arg))))
Mike Williams's avatar
Mike Williams committed
942

943 944 945 946 947 948 949 950 951

;; Put read-only last to enable setting this even when read-only enabled.
(or (get 'sgml-tag 'invisible)
    (setplist 'sgml-tag
	      (append '(invisible t
			point-entered sgml-point-entered
			rear-nonsticky t
			read-only t)
		      (symbol-plist 'sgml-tag))))
952 953 954 955 956 957

(defun sgml-tags-invisible (arg)
  "Toggle visibility of existing tags."
  (interactive "P")
  (let ((modified (buffer-modified-p))
	(inhibit-read-only t)
958 959 960
	(inhibit-modification-hooks t)
	;; Avoid spurious the `file-locked' checks.
	(buffer-file-name nil)
961 962
	;; This is needed in case font lock gets called,
	;; since it moves point and might call sgml-point-entered.
963
	;; How could it get called?  -stef
964
	(inhibit-point-motion-hooks t)
965
	string)
966 967 968
    (unwind-protect
	(save-excursion
	  (goto-char (point-min))
Stefan Monnier's avatar
Stefan Monnier committed
969 970 971 972
	  (if (set (make-local-variable 'sgml-tags-invisible)
		   (if arg
		       (>= (prefix-numeric-value arg) 0)
		     (not sgml-tags-invisible)))
973
	      (while (re-search-forward sgml-tag-name-re nil t)
974 975 976
		(setq string
		      (cdr (assq (intern-soft (downcase (match-string 1)))
				 sgml-display-text)))
977
		(goto-char (match-beginning 0))
978
		(and (stringp string)
979
		     (not (overlays-at (point)))
Stefan Monnier's avatar
Stefan Monnier committed
980 981 982
		     (let ((ol (make-overlay (point) (match-beginning 1))))
		       (overlay-put ol 'before-string string)
		       (overlay-put ol 'sgml-tag t)))
983 984 985
		(put-text-property (point)
				   (progn (forward-list) (point))
				   'category 'sgml-tag))
986
	    (let ((pos (point-min)))
987
	      (while (< (setq pos (next-overlay-change pos)) (point-max))
Stefan Monnier's avatar
Stefan Monnier committed
988
		(dolist (ol (overlays-at pos))
Stefan Monnier's avatar
Stefan Monnier committed
989
		  (if (overlay-get ol 'sgml-tag)
Stefan Monnier's avatar
Stefan Monnier committed
990
		      (delete-overlay ol)))))
991
	    (remove-text-properties (point-min) (point-max) '(category nil))))
992
      (restore-buffer-modified-p modified))
993 994 995 996 997 998 999
    (run-hooks 'sgml-tags-invisible-hook)
    (message "")))

(defun sgml-point-entered (x y)
  ;; Show preceding or following hidden tag, depending of cursor direction.
  (let ((inhibit-point-motion-hooks t))
    (save-excursion
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
      (condition-case nil
	  (message "Invisible tag: %s"
		   ;; Strip properties, otherwise, the text is invisible.
		   (buffer-substring-no-properties
		    (point)
		    (if (or (and (> x y)
				 (not (eq (following-char) ?<)))
			    (and (< x y)
				 (eq (preceding-char) ?>)))
			(backward-list)
		      (forward-list))))
	(error nil)))))

Mike Williams's avatar
Mike Williams committed
1013

1014

Eric S. Raymond's avatar
Eric S. Raymond committed
1015 1016 1017
(defun sgml-validate (command)
  "Validate an SGML document.
Runs COMMAND, a shell command, in a separate process asynchronously
Richard M. Stallman's avatar
Richard M. Stallman committed
1018
with output going to the buffer `*compilation*'.
Eric S. Raymond's avatar
Eric S. Raymond committed
1019 1020 1021 1022 1023 1024 1025
You can then use the command \\[next-error] to find the next error message
and move to the line in the SGML document that caused it."
  (interactive
   (list (read-string "Validate command: "
		      (or sgml-saved-validate-command
			  (concat sgml-validate-command
				  " "