-
Notifications
You must be signed in to change notification settings - Fork 0
/
sgml-mode.el
2171 lines (1987 loc) · 77.6 KB
/
sgml-mode.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
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
850
851
852
853
854
855
856
857
858
859
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
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
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
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; sgml-mode.el --- SGML- and HTML-editing modes -*- coding: utf-8 -*-
;; Copyright (C) 1992, 1995-1996, 1998, 2001-2013 Free Software
;; Foundation, Inc.
;; Author: James Clark <[email protected]>
;; Maintainer: FSF
;; Adapted-By: ESR, Daniel Pfeiffer <[email protected]>,
;; Keywords: wp, hypermedia, comm, languages
;; This file is part of GNU Emacs.
;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; 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
;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; 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.
;;; Code:
(eval-when-compile
(require 'skeleton)
(require 'cl-lib))
(defgroup sgml nil
"SGML editing mode."
:link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
:group 'languages)
(defcustom sgml-basic-offset 2
"Specifies the basic indentation level for `sgml-indent-line'."
:type 'integer
:group 'sgml)
(defcustom sgml-xml-mode nil
"When non-nil, tag insertion functions will be XML-compliant.
It is set to be buffer-local when the file has
a DOCTYPE or an XML declaration."
:type 'boolean
:version "22.1"
:group 'sgml)
(defcustom sgml-transformation-function 'identity
"Default value for `skeleton-transformation-function' in SGML mode."
:type 'function
:initialize 'custom-initialize-default
:set (lambda (sym val)
(set-default sym val)
(mapc (lambda (buff)
(with-current-buffer buff
(and (derived-mode-p 'sgml-mode)
(not sgml-xml-mode)
(setq skeleton-transformation-function val))))
(buffer-list)))
:group 'sgml)
(put 'sgml-transformation-function 'variable-interactive
"aTransformation function: ")
(defvaralias 'sgml-transformation 'sgml-transformation-function)
(defcustom sgml-mode-hook nil
"Hook run by command `sgml-mode'.
`text-mode-hook' is run first."
:group 'sgml
:type 'hook)
;; As long as Emacs's 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.
(defvar sgml-specials '(?\" ?')
"List of characters that have a special meaning for SGML mode.
This list is used when first loading the `sgml-mode' library.
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.
When only one of ?\\\" or ?' are included, \"'\" or '\"', as can be found in
DTDs, start a string. To partially avoid this problem this also makes these
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.")
(defvar sgml-quick-keys nil
"Use <, >, &, /, SPC and `sgml-specials' keys \"electrically\" when non-nil.
This takes effect when first loading the `sgml-mode' library.")
(defvar sgml-mode-map
(let ((map (make-keymap)) ;`sparse' doesn't allow binding to charsets.
(menu-map (make-sparse-keymap "SGML")))
(define-key map "\C-c\C-i" 'sgml-tags-invisible)
(define-key map "/" 'sgml-slash)
(define-key map "\C-c\C-n" 'sgml-name-char)
(define-key map "\C-c\C-t" 'sgml-tag)
(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)
(define-key map "\C-c]" 'sgml-close-tag)
(define-key map "\C-c/" 'sgml-close-tag)
(define-key map "\C-cf" 'sgml-fold-tag)
;; 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)
(define-key map "\C-c8" 'sgml-name-8bit-mode)
(define-key map "\C-c\C-v" 'sgml-validate)
(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)))
(let ((c 127)
(map (nth 1 map)))
(while (< (setq c (1+ c)) 256)
(aset map c 'sgml-maybe-name-self)))
(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'.")
(defun sgml-make-syntax-table (specials)
(let ((table (make-syntax-table text-mode-syntax-table)))
(modify-syntax-entry ?< "(>" table)
(modify-syntax-entry ?> ")<" table)
(modify-syntax-entry ?: "_" table)
(modify-syntax-entry ?_ "_" table)
(modify-syntax-entry ?. "_" table)
(if (memq ?- specials)
(modify-syntax-entry ?- "_ 1234" table))
(if (memq ?\" specials)
(modify-syntax-entry ?\" "\"\"" table))
(if (memq ?' specials)
(modify-syntax-entry ?' "\"'" table))
table))
(defvar sgml-mode-syntax-table (sgml-make-syntax-table sgml-specials)
"Syntax table used in SGML mode. See also `sgml-specials'.")
(defconst sgml-tag-syntax-table
(let ((table (sgml-make-syntax-table sgml-specials)))
(dolist (char '(?\( ?\) ?\{ ?\} ?\[ ?\] ?$ ?% ?& ?* ?+ ?/))
(modify-syntax-entry char "." table))
(unless (memq ?' sgml-specials)
;; Avoid that skipping a tag backwards skips any "'" prefixing it.
(modify-syntax-entry ?' "w" table))
table)
"Syntax table used to parse SGML tags.")
(defcustom sgml-name-8bit-mode nil
"When non-nil, insert non-ASCII characters as named entities."
:type 'boolean
:group 'sgml)
(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
"nbsp" "excl" "quot" "num" "dollar" "percnt" "amp" "apos"
"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"
"cedil" "sup1" "ordm" "raquo" "frac14" "frac12" "frac34" "iquest"
"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 `;'.")
(put 'sgml-table 'char-table-extra-slots 0)
(defvar sgml-char-names-table
(let ((table (make-char-table 'sgml-table))
(i 32)
elt)
(while (< i 128)
(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.")
;; nsgmls is a free SGML parser in the SP suite available from
;; ftp.jclark.com and otherwise packaged for GNU systems.
;; Its error messages can be parsed by next-error.
;; The -s option suppresses output.
(defcustom sgml-validate-command "nsgmls -s" ; replaced old `sgmls'
"The command to validate an SGML document.
The file name of current buffer file name will be appended to this,
separated by a space."
:type 'string
:version "21.1"
:group 'sgml)
(defvar sgml-saved-validate-command nil
"The command last used to validate in this buffer.")
;; I doubt that null end tags are used much for large elements,
;; so use a small distance here.
(defcustom sgml-slash-distance 1000
"If non-nil, is the maximum distance to search for matching `/'."
:type '(choice (const nil) integer)
:group 'sgml)
(defconst sgml-namespace-re "[_[:alpha:]][-_.[:alnum:]]*")
(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)
"Regular expression that matches a non-empty start tag.
Any terminating `>' or `/' is not matched.")
(defface sgml-namespace
'((t (:inherit font-lock-builtin-face)))
"`sgml-mode' face used to highlight the namespace part of identifiers."
:group 'sgml)
(defvar sgml-namespace-face 'sgml-namespace)
;; internal
(defconst sgml-font-lock-keywords-1
`((,(concat "<\\([!?]" sgml-name-re "\\)") 1 font-lock-keyword-face)
;; 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))
;; FIXME: this doesn't cover the variables using a default value.
;; 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 "\\)\\(?::\\("
sgml-name-re "\\)\\)?=[\"']")
(1 (if (match-end 2) sgml-namespace-face font-lock-variable-name-face))
(2 font-lock-variable-name-face nil t))
(,(concat "[&%]" sgml-name-re ";?") . font-lock-variable-name-face)))
(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>")
'(3 (cdr (assoc-string (match-string 1) sgml-tag-face-alist t))
prepend))))))
;; 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
"Rules for highlighting SGML code. See also `sgml-tag-face-alist'.")
(defconst sgml-syntax-propertize-function
(syntax-propertize-rules
;; Use the `b' style of comments to avoid interference with the -- ... --
;; comments recognized when `sgml-specials' includes ?-.
;; FIXME: beware of <!--> blabla <!--> !!
("\\(<\\)!--" (1 "< b"))
("--[ \t\n]*\\(>\\)" (1 "> b"))
;; Quotes outside of tags should not introduce strings.
;; 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)))
(string-to-syntax "."))))
("'" (0 (if (prog1 (zerop (car (syntax-ppss (match-beginning 0))))
(goto-char (match-end 0)))
(string-to-syntax ".")))))
"Syntactic keywords for `sgml-mode'.")
;; 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)
(defcustom sgml-tag-alist
'(("![" ("ignore" t) ("include" t))
("!attlist")
("!doctype")
("!element")
("!entity"))
"Alist of tag names for completing read and insertion rules.
This alist is made up as
((\"tag\" . TAGRULE)
...)
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
followed by an ATTRIBUTERULE (for an always present attribute) or an
attribute alist.
The attribute alist is made up as
((\"attribute\" . ATTRIBUTERULE)
...)
ATTRIBUTERULE is a list of optionally t (no value when no input) followed by
an optional alist of possible values."
:type '(repeat (cons (string :tag "Tag Name")
(repeat :tag "Tag Rule" sexp)))
:group 'sgml)
(put 'sgml-tag-alist 'risky-local-variable t)
(defcustom sgml-tag-help
'(("!" . "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"))
"Alist of tag name and short description."
:type '(repeat (cons (string :tag "Tag Name")
(string :tag "Description")))
:group 'sgml)
(defvar sgml-empty-tags nil
"List of tags whose !ELEMENT definition says EMPTY.")
(defvar sgml-unclosed-tags nil
"List of tags whose !ELEMENT definition says the end-tag is optional.")
(defun sgml-xml-guess ()
"Guess whether the current buffer is XML. Return non-nil if so."
(save-excursion
(goto-char (point-min))
(or (string= "xml" (file-name-extension (or buffer-file-name "")))
;; Maybe the buffer-size check isn't needed, I don't know.
(and (zerop (buffer-size))
(string= "xhtml" (file-name-extension (or buffer-file-name ""))))
(looking-at "\\s-*<\\?xml")
(when (re-search-forward
(eval-when-compile
(mapconcat 'identity
'("<!DOCTYPE" "\\(\\w+\\)" "\\(\\w+\\)"
"\"\\([^\"]+\\)\"" "\"\\([^\"]+\\)\"")
"\\s-+"))
nil t)
(string-match "X\\(HT\\)?ML" (match-string 3))))))
(defvar v2) ; free for skeleton
(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)))
(defun sgml-mode-facemenu-add-face-function (face end)
(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))))))
(defun sgml-fill-nobreak ()
"Don't break between a tag name and its first argument.
This function is designed for use in `fill-nobreak-predicate'.
<a href=\"some://where\" type=\"text/plain\">
^ ^
| no break here | but still allowed here"
(save-excursion
(skip-chars-backward " \t")
(and (not (zerop (skip-syntax-backward "w_")))
(skip-chars-backward "/?!")
(eq (char-before) ?<))))
;;;###autoload
(define-derived-mode sgml-mode text-mode '(sgml-xml-mode "XML" "SGML")
"Major mode for editing SGML documents.
Makes > match <.
Keys <, &, SPC within <>, \", / and ' can be electric depending on
`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.
If you like upcased tags, put (setq sgml-transformation-function 'upcase)
in your init file.
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}"
(make-local-variable 'sgml-saved-validate-command)
(make-local-variable 'facemenu-end-add-face)
;;(make-local-variable 'facemenu-remove-face-function)
;; 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.
(setq-local paragraph-start (concat "[ \t]*$\\|\
\[ \t]*</?\\(" sgml-name-re sgml-attrs-re "\\)?>"))
(setq-local paragraph-separate (concat paragraph-start "$"))
(setq-local adaptive-fill-regexp "[ \t]*")
(add-hook 'fill-nobreak-predicate 'sgml-fill-nobreak nil t)
(setq-local indent-line-function 'sgml-indent-line)
(setq-local comment-start "<!-- ")
(setq-local comment-end " -->")
(setq-local comment-indent-function 'sgml-comment-indent)
(setq-local comment-line-break-function 'sgml-comment-indent-new-line)
(setq-local skeleton-further-elements '((completion-ignore-case t)))
(setq-local skeleton-end-hook
(lambda ()
(or (eolp)
(not (or (eq v2 '\n) (eq (car-safe v2) '\n)))
(newline-and-indent))))
(setq font-lock-defaults '((sgml-font-lock-keywords
sgml-font-lock-keywords-1
sgml-font-lock-keywords-2)
nil t))
(setq-local syntax-propertize-function sgml-syntax-propertize-function)
(setq-local facemenu-add-face-function 'sgml-mode-facemenu-add-face-function)
(setq-local sgml-xml-mode (sgml-xml-guess))
(unless sgml-xml-mode
(setq-local skeleton-transformation-function sgml-transformation-function))
;; This will allow existing comments within declarations to be
;; recognized.
;; 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.
(setq-local comment-start-skip "<!--[ \t]*")
(setq-local comment-end-skip "[ \t]*--[ \t\n]*>")
;; 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))))
(defun sgml-comment-indent ()
(if (looking-at "--") comment-column 0))
(defun sgml-slash (arg)
"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)
(delete-char -1)
(sgml-close-tag))
(t
(sgml-slash-matching arg))))
(defun sgml-slash-matching (arg)
"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."
(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)))))))
(when blinkpos
(goto-char blinkpos)
(if (pos-visible-in-window-p)
(sit-for 1)
(message "Matches %s"
(buffer-substring (line-beginning-position)
(1+ blinkpos)))))))))
;; 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.
(defun sgml-name-char (&optional char)
"Insert a symbolic character name according to `sgml-char-names'.
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."
(interactive "*")
(insert ?&)
(or char
(setq char (read-quoted-char "Enter char or octal number")))
(delete-char -1)
(insert char)
(undo-boundary)
(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)
(delete-char -1)
(insert (format (if (numberp name) "&#%d;" "&%s;") name)))))
(defun sgml-name-self ()
"Insert a symbolic character name according to `sgml-char-names'."
(interactive "*")
(sgml-name-char last-command-event))
(defun sgml-maybe-name-self ()
"Insert a symbolic character name according to `sgml-char-names'."
(interactive "*")
(if sgml-name-8bit-mode
(sgml-name-char last-command-event)
(self-insert-command 1)))
(defun sgml-name-8bit-mode ()
"Toggle whether to insert named entities instead of non-ASCII characters.
This only works for Latin-1 input."
(interactive)
(setq sgml-name-8bit-mode (not sgml-name-8bit-mode))
(message "sgml name entity mode is now %s"
(if sgml-name-8bit-mode "ON" "OFF")))
;; When an element of a skeleton is a string "str", it is passed
;; 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").
(defvar sgml-tag-last nil)
(defvar sgml-tag-history nil)
(define-skeleton sgml-tag
"Prompt for a tag and insert it, optionally with attributes.
Completion and configuration are done according to `sgml-tag-alist'.
If you like tags and attributes in uppercase, customize
`sgml-transformation-function' to 'upcase."
(funcall (or skeleton-transformation-function 'identity)
(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)))
?< str |
(("") -1 '(undo-boundary) (identity "<")) | ; see comment above
`(("") '(setq v2 (sgml-attributes ,str t)) ?>
(cond
((string= "![" ,str)
(backward-char)
'(("") " [ " _ " ]]"))
((and (eq v2 t) sgml-xml-mode (member ,str sgml-empty-tags))
'(("") -1 " />"))
((or (and (eq v2 t) (not sgml-xml-mode)) (string-match "^[/!?]" ,str))
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
;; `str' through `skeleton-transformation-function' a second time.
'(("") v2 _ v2 "</" (identity ',str) ?> >))
((eq (car v2) t)
(cons '("") (cdr v2)))
(t
(append '(("") (car v2))
(cdr v2)
'(resume: (car v2) _ "</" (identity ',str) ?> >))))))
(autoload 'skeleton-read "skeleton")
(defun sgml-attributes (tag &optional quiet)
"When at top level of a tag, interactively insert attributes.
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."
(interactive (list (save-excursion (sgml-beginning-of-tag t))))
(or (stringp tag) (error "Wrong context for adding attribute"))
(if tag
(let ((completion-ignore-case t)
(alist (cdr (assoc (downcase tag) sgml-tag-alist)))
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
(insert (if (eq (preceding-char) ?\s) "" ?\s)
(funcall skeleton-transformation-function (car alist)))
(sgml-value alist))
(setq i (length alist))
(while (> i 0)
(insert ?\s)
(insert (funcall skeleton-transformation-function
(setq attribute
(skeleton-read '(completing-read
"Attribute: "
alist)))))
(if (string= "" attribute)
(setq i 0)
(sgml-value (assoc (downcase attribute) alist))
(setq i (1- i))))
(if (eq (preceding-char) ?\s)
(delete-char -1)))
car)))
(defun sgml-auto-attributes (arg)
"Self insert the character typed; at top level of tag, prompt for attributes.
With prefix argument, only self insert."
(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)
(setq last-command-event ?\s)
(or (> (point) point)
(self-insert-command 1)))))
(defun sgml-tag-help (&optional tag)
"Display description of tag TAG. If TAG is omitted, use the tag at point."
(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))
(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))
(message "%s"
(or (cdr (assoc (downcase tag) sgml-tag-help))
(and (eq (aref tag 0) ?/)
(cdr (assoc (downcase (substring tag 1)) sgml-tag-help)))
"No description available")))
(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)))
(defun sgml-skip-tag-backward (arg)
"Skip to beginning of tag or matching opening tag if present.
With prefix argument ARG, repeat this ARG times.
Return non-nil if we skipped over matched tags."
(interactive "p")
;; FIXME: use sgml-get-context or something similar.
(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
"Toggle SGML Electric Tag Pair mode.
With a prefix argument ARG, enable the mode if ARG is positive,
and disable it otherwise. If called from Lisp, enable the mode
if ARG is omitted or nil.
SGML Electric Tag Pair mode is a buffer-local minor mode for use
with `sgml-mode' and related major modes. When enabled, editing
an opening markup tag automatically updates the closing tag."
: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.
))
(defun sgml-skip-tag-forward (arg)
"Skip to end of tag or matching closing tag if present.
With prefix argument ARG, repeat this ARG times.
Return t if after a closing tag."
(interactive "p")
;; 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>.
(let ((return t))
(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)))
(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))))))
(defun sgml-delete-tag (arg)
;; FIXME: Should be called sgml-kill-tag or should not touch the kill-ring.
"Delete tag on or after cursor, and matching closing or opening tag.
With prefix argument ARG, repeat this ARG times."
(interactive "p")
(while (>= arg 1)
(save-excursion
(let* (close open)
(if (looking-at "[ \t\n]*<")
;; 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))
(when (and (sgml-skip-tag-forward 1)
(not (sgml-looking-back-at "/>")))
(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)))
(goto-char open)
(kill-sexp 1)
(if (progn (forward-line 0) (looking-at "\\(?:[ \t]*$\\)\n?"))
(delete-region (match-beginning 0) (match-end 0)))))
(setq arg (1- arg))))
;; 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))))
(defun sgml-tags-invisible (arg)
"Toggle visibility of existing tags."
(interactive "P")
(let ((modified (buffer-modified-p))
(inhibit-read-only t)
(inhibit-modification-hooks t)
;; Avoid spurious the `file-locked' checks.
(buffer-file-name nil)
;; This is needed in case font lock gets called,
;; since it moves point and might call sgml-point-entered.
;; How could it get called? -stef
(inhibit-point-motion-hooks t)
string)
(unwind-protect
(save-excursion
(goto-char (point-min))
(if (setq-local sgml-tags-invisible
(if arg
(>= (prefix-numeric-value arg) 0)
(not sgml-tags-invisible)))
(while (re-search-forward sgml-tag-name-re nil t)
(setq string
(cdr (assq (intern-soft (downcase (match-string 1)))
sgml-display-text)))
(goto-char (match-beginning 0))
(and (stringp string)
(not (overlays-at (point)))
(let ((ol (make-overlay (point) (match-beginning 1))))
(overlay-put ol 'before-string string)
(overlay-put ol 'sgml-tag t)))