forked from cdominik/cdlatex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cdlatex.el
2246 lines (2075 loc) · 77.6 KB
/
cdlatex.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
;;; cdlatex.el --- Fast input methods for LaTeX environments and math
;; Copyright (c) 2010, 2011, 2012, 2014, 2019, 2020 Free Software Foundation, Inc.
;;
;; Author: Carsten Dominik <carsten.dominik@gmail.com>
;; Keywords: tex
;; Version: 4.11
;;
;; This file is not part of GNU Emacs.
;;
;; GNUTHis file 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.
;; cdlatex.el 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 cdlatex.el. If not, see <http://www.gnu.org/licenses/>.
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;;; Commentary:
;;
;; CDLaTeX is a minor mode supporting fast insertion of environment
;; templates and math stuff in LaTeX.
;;
;; To turn CDLaTeX Minor Mode on and off in a particular buffer, use
;; `M-x cdlatex-mode'.
;;
;; To turn on CDLaTeX Minor Mode for all LaTeX files, add one of the
;; following lines to your .emacs file:
;;
;; (add-hook 'LaTeX-mode-hook 'turn-on-cdlatex) ; with AUCTeX LaTeX mode
;; (add-hook 'latex-mode-hook 'turn-on-cdlatex) ; with Emacs latex mode
;;
;; For key bindings, see further down in this documentation.
;;
;; CDLaTeX requires texmathp.el which is distributed with AUCTeX.
;; Starting with Emacs 21.3, texmathp.el will be part of Emacs.
;;
;;--------------------------------------------------------------------------
;;
;; OVERVIEW
;; ========
;;
;; CDLaTeX is a minor mode supporting mainly mathematical and scientific
;; text development with LaTeX. CDLaTeX is really about speed. AUCTeX
;; (the major mode I recommend for editing LaTeX files) does have a hook
;; based system for inserting environments and macros - but while this is
;; useful and general, it is sometimes slow to use. CDLaTeX tries to be
;; quick, with very few and easy to remember keys, and intelligent
;; on-the-fly help.
;;
;; 1. ABBREVIATIONS.
;; -------------
;; CDLaTeX has an abbrev-like mechanism to insert full LaTeX
;; environments and other templates into the buffer. Abbreviation
;; expansion is triggered with the TAB key only, not with SPC or RET.
;; For example, typing "ite<TAB>" inserts an itemize environment. A
;; full list of defined abbreviations is available with the command
;; `C-c ?' (`cdlatex-command-help').
;;
;; 1a. ENVIRONMENT TEMPLATES
;; ---------------------
;; Typing `C-c {' (`cdlatex-environment') uses the minibuffer to
;; complete the name of a LaTeX environment and inserts a template
;; for this environment into the buffer. These environment
;; templates also contain labels created with RefTeX. In a
;; template, text needs to be filled in at various places, which we
;; call "points of interest". You can use the TAB key to jump to
;; the next point of interest in the template. If there is an
;; active region, the region will be wrappend into the environment,
;; ignoring the template content.
;;
;; For many frequently used LaTeX environments, abbreviations are
;; available. Most of the time, the abbreviation consists of the
;; first three letters of the environment name: `equ<TAB>' expands
;; into
;; \begin{equation}
;; \label{eq:1}
;;
;; \end{equation}
;;
;; Similarly, `ali<TAB>' inserts an AMS-LaTeX align environment
;; template etc. For a full list of environment abbreviations, use
;; `C-c ?'.
;;
;; Use the command `C-c -' (`cdlatex-item') to insert a generalized
;; new "item" in any "list"-like environment. For example, in an
;; itemize environment, this inserts "\item", in an enumerate
;; environment it inserts "\item\label{item:25}" and in an eqnarray
;; environment, it inserts "\label{eq:25} \n & &". When
;; appropriate, newlines are inserted, and the previous item is also
;; closed with "\\". `cdlatex-item' can also be invoked with the
;; abbreviation "it<TAB>".
;;
;; 1b. MATH TEMPLATES
;; --------------
;; Abbreviations are also used to insert simple math templates
;; into the buffer. The cursor will be positioned properly. For
;; example, typing `fr<TAB>' will insert "\frac{}{}" with the
;; cursor in the first pair of parenthesis. Typing `lr(<TAB>'
;; will insert a "\left( \right)" pair and position the cursor in
;; between, etc. Again, the TAB key can be used to jump to the
;; points in the template where additional text has to be
;; inserted. For example in the `\frac{}{}' template, it will
;; move you from the first argument to the second and then out of
;; the second. For a list of available templates, type `C-c ?'.
;;
;; 2. MATHEMATICAL SYMBOLS
;; --------------------
;; This feature is similar to the functionality in the Math minor mode
;; of AUCTeX, and to the input methods of the X-Symbol package. It is
;; introduced by the backquote character. Backquote followed by any
;; character inserts a LaTeX math macro into the buffer. If
;; necessary, a pair of "$" is inserted to switch to math mode. For
;; example, typing "`a" inserts "$\alpha$". Since LaTeX defines many
;; more mathematical symbols than the alphabet has letters, different
;; sets of math macros are provided. We call the different sets
;; "levels". On each level, another LaTeX macro is assigned to a
;; given letter. To select the different levels, simply press the
;; backquote character several times before pressing the letter. For
;; example, typing "`d" inserts "\delta" (level 1), and typing "``d"
;; inserts "\partial" (level 2). Similarly, "`e" inserts "\epsilon"
;; and "``e" inserts "\vareppsilon".
;;
;; On each level, on-thy-fly help will pop up automatically if you
;; hesitate to press the next key. The help screen is a window which
;; lists all math macros available on the current level. Initially,
;; when you type slowly, this window will pop up each time you press
;; backquote. However, after you have learned the different keys, you
;; will type more quickly and the help window is not shown. Try it
;; out: First press "`" (backquote), wait for the help window and then
;; press "a" to get "\alpha". Then press "`" and "b" as a quick
;; sequence to get "\beta", without the help window.
;;
;; The LaTeX macros available through this mechanism are fully
;; configurable - see the variable `cdlatex-math-symbol-alist'.
;;
;; 3. ACCENTS AND FONTS
;; -----------------
;; Putting accents on mathematical characters and/or changing the font
;; of a character uses key combinations with the quote character "'"
;; as a prefix. The accent or font change is applied to the character
;; or LaTeX macro *before* point. For example
;;
;; Keys Result
;; --------------------------------------------------------------------
;; a'~ ERROR % in text mode
;; $a'~ \tilde{a} % in math mode
;; a': \ddot{a}
;; ab'b \textbf{ab} % in text mode
;; $ab'b a\mathbf{b} % in math mode
;; \alpha'. \dot{\alpha}
;; r_{dust}'r r_\mathrm{dust} % in math mode
;; <SPC> 'e \emph{}
;; this is important M-2 'b this \textbf{is important}
;;
;; As you can see:
;; - using math accents like ~ outside math mode will throw an error.
;; - the font change used automatically adapts to math mode.
;; - if the item before point is a LaTeX macro, the change applies to
;; the whole macro.
;; - in text mode, the change applies to the entire word before point,
;; while in math mode only the last character is modified.
;; - if the character before point is white space, a dollar or an
;; opening parenthesis, this command just opens an empty template
;; and positions the cursor inside.
;; - when a numeric prefix argument is supplied, the command acts on
;; whole words before the cursor.
;;
;; In order to insert a normal quote, you can press the quote
;; character twice. Also, if the key character is not associated with
;; an accent or font, the quote will be inserted. For example, "'t"
;; and "'s" insert just that, so that normal text typing will not be
;; disturbed. Just like during the insertion of math macros (see above
;; under (4.)), automatic on-the-fly help will pop up when you pause
;; after hitting the quote character, but will be suppressed when you
;; continue quickly. The available accents and also the prefix key
;; can be can be configured - see documentation of the variables
;; `cdlatex-math-modify-alist' and `cdlatex-math-modify-prefix'.
;;
;; 4. PAIR INSERTION of (), [], {}, and $$
;; ------------------------------------
;; Dollars and parens can be inserted as pairs. When you type the
;; opening delimiter, the closing delimiter will be inserted as well,
;; and the cursor positioned between them. You can configure which
;; delimiter are inserted pairwise by configuring the variable
;; `cdlatex-paired-parens'.
;;
;; Also, the keys `_' and `^' will insert "_{}" and "^{}",
;; respectively, and, if necessary, also a pair of dollar signs to
;; switch to math mode. You can use TAB to exit paired parenthesis.
;; As a special case, when you use TAB to exit a pair of braces that
;; belong to a subscript or superscript, CDLaTeX removes the braces if
;; the sub/superscript consists of a single character. For example
;; typing "$10^3<TAB>" inserts "$10^3$", but typing "$10^34<TAB>"
;; inserts "$10^{34}$".
;;
;; If you press `_' or `^' twice, the template inserted will be
;; `_{\rm }' or `^{\rm }', respectively, to insert a roman
;; sub/super-script. Style guides require that all sub and
;; superscipts that are descriptive (so not a mathematical or
;; physical quantity themselves) need to be roman. So $x_i$ is i
;; is an index, but $x_{\rm max}$ to indicate the maximum value. You
;; can disable this behavior through the variable
;; `cdlatex-make-sub-superscript-roman-if-pressed-twice'.
;;
;; 5. THE OVERLOADED TAB KEY
;; ----------------------
;; You may have noticed that we use the TAB key for many different
;; purposes in this package. While this may seem confusing, I have
;; gotten used to this very much. Hopefully this will work for you as
;; well: "when in doubt, press TAB". Here is a summary of what happens
;; when you press the TAB key:
;;
;; The function first tries to expand any abbreviation before point.
;;
;; If there is none, it cleans up short subscripts and superscripts at
;; point. I.e., is the cursor is just before the closing brace in
;; "a^{2}", it changes it to "a^2", since this is more readable. If
;; you want to keep the braces also for simple superscripts and
;; subscripts, set the variable `cdlatex-simplify-sub-super-scripts'
;; to nil.
;;
;; After that, the TAB function jumps to the next point of interest in
;; a LaTeX text where one would reasonably expect that more input can
;; be put in. This does *not* use special markers in the template,
;; but a heuristic method which works quite well. For the detailed
;; rules which govern this feature, check the documentation of the
;; function `cdlatex-tab'.
;;
;;-----------------------------------------------------------------------------
;;
;; CONFIGURATION EXAMPLES
;; ======================
;;
;; Check out the documentation of the variables in the configuration
;; section. The variables must be set before cdlatex-mode is turned on,
;; or, at the latext, in `cdlatex-mode-hook', in order to be effective.
;; When changing the variables, toggle the mode off and on to make sure
;; that everything is up to date.
;;
;; Here is how you might configure CDLaTeX to provide environment templates
;; (including automatic labels) for two theorem-like environments.
;;
;; (setq cdlatex-env-alist
;; '(("axiom" "\\begin{axiom}\nAUTOLABEL\n?\n\\end{axiom}\n" nil)
;; ("theorem" "\\begin{theorem}\nAUTOLABEL\n?\n\\end{theorem}\n" nil)))
;;
;; The "AUTOLABEL" indicates the place where an automatic label should be
;; inserted, using RefTeX. The question mark defines the position of the
;; cursor after the template has been inserted into the buffer.
;;
;; You could also define your own keyword commands "axm" and "thr" to make
;; the template insertion quicker (e.g. `axm<TAB>' and `thm<TAB>'):
;;
;; (setq cdlatex-command-alist
;; '(("axm" "Insert axiom env" "" cdlatex-environment ("axiom") t nil)
;; ("thr" "Insert theorem env" "" cdlatex-environment ("theorem") t nil)))
;;
;; Here is how to add new math symbols to CDLaTeX's list: In order to put
;; all rightarrow commands onto `>, ``>, ```>, and ````> (i.e. several
;; backquotes followed by >) and all leftarrow commands onto '<, ``<, ```<,
;; and ````<, you could do this in .emacs:
;;
;; (setq cdlatex-math-symbol-alist
;; '((?< ("\\leftarrow" "\\Leftarrow" "\\longleftarrow" "\\Longleftarrow"))
;; (?> ("\\rightarrow" "\\Rightarrow" "\\longrightarrow" "\\Longrightarrow"))
;; ))
;;
;; To change the prefix key for math accents and font switching, you could
;; do something like
;;
;; (setq cdlatex-math-modify-prefix [f7])
;;-----------------------------------------------------------------------------
;;
;; KEY BINDINGS
;;
;; Here is the default set of keybindings from CDLaTeX. A menu is also
;; installed.
;;
;; $ cdlatex-dollar
;; ( cdlatex-pbb
;; { cdlatex-pbb
;; [ cdlatex-pbb
;; | cdlatex-pbb
;; < cdlatex-pbb
;; ^ cdlatex-sub-superscript
;; _ cdlatex-sub-superscript
;;
;; TAB cdlatex-tab
;; C-c ? cdlatex-command-help
;; C-c { cdlatex-environment
;; C-c - cdlatex-item
;; ` cdlatex-math-symbol
;; ' cdlatex-math-modify
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; FAQ
;;
;; - Some people find it disturbing that the quote character (') is active
;; for math accents and font switching. I have tried to avoid any letters
;; which are frequently following ' in normal text. For example, 's and 't
;; insert just this. If you still prefer a different prefix key, just
;; configure the variable `cdlatex-math-modify-prefix'.
;;
;; - To insert a backquote into the buffer, use C-q `
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;;;;;;
;;; Code:
(eval-when-compile (require 'cl-lib))
;;; Begin of Configuration Section ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Configuration Variables and User Options for CDLaTeX ------------------
(defgroup cdlatex nil
"LaTeX label and citation support."
:tag "CDLaTeX"
:link '(url-link :tag "Home Page" "http://zon.astro.uva.nl/~dominik/Tools/")
:prefix "cdlatex-"
:group 'tex)
(defun cdlatex-customize ()
"Call the customize function with cdlatex as argument."
(interactive)
(cond
((fboundp 'customize-browse)
(customize-browse 'cdlatex))
((fboundp 'customize-group)
(customize-group 'cdlatex))
(t (error "No customization available"))))
(defun cdlatex-create-customize-menu ()
"Create a full customization menu for CDLaTeX."
(interactive)
(if (fboundp 'customize-menu-create)
(progn
(easy-menu-change
'("CDLTX") "Customize"
`(["Browse CDLaTeX group" cdlatex-customize t]
"---"
,(customize-menu-create 'cdlatex)
["Set" Custom-set t]
["Save" Custom-save t]
["Reset to Current" Custom-reset-current t]
["Reset to Saved" Custom-reset-saved t]
["Reset to Standard Settings" Custom-reset-standard t]))
(message "\"CDLTX\"-menu now contains full customization menu"))
(error "Cannot expand menu (outdated version of cus-edit.el)")))
;; Configuration of KEYWORD commands ------------------------------------
(defgroup cdlatex-keyword-commands nil
"How to type a keyword in the buffer and hit TAB to execute."
:group 'cdlatex)
(defcustom cdlatex-command-alist nil
"List of abbrev-like commands, available with keyword and TAB.
See `cdlatex-command-alist-default' for examples. This list only
defines additons to the defaults. For a full list of active commands,
press \\[cdlatex-command-help].
Each element of this list is again a list with the following items:
0. KEYWORD The key that has to be typed into the text.
1. DOCSTRING A documentation string, less than 60 characters long.
2. REPLACE The text to be substituted for the keyword, if any.
3. HOOK A function to be called.
4. ARGS Optional list of arguments to the function.
5. TEXTFLAG non-nil means this keyword command is active in textmode.
6. MATHFLAG non-nil means this keyword command is active in math mode."
:group 'cdlatex-keyword-commands
:type '(repeat
(list (string :tag "Keyword ")
(string :tag "Docstring ")
(string :tag "Replacement")
(function :tag "Hook ")
(sexp :tag "Arguments ")
(boolean :tag "Available in Text mode")
(boolean :tag "Available in Math mode"))))
(defcustom cdlatex-tab-hook nil
"List of functions called by TAB before the default command is executed.
These functions are called each time TAB is pressed. They may parse the
environment and take an action. The function should return t when it
successful executed an action and other TAB actions should *not* be tried.
When a return value is nil, other hook functions are tried, followed by the
default action of TAB (see documentation of the command `cdlatex-tab'."
:group 'cdlatex-keyword-commands
:type '(repeat (function :tag "Function" :value nil)))
;; Configuration of environment templates -------------------------------
(defgroup cdlatex-environment-support nil
"Template-based insertion of LaTeX environments."
:group 'cdlatex)
(defcustom cdlatex-env-alist nil
"Association list of LaTeX environments and the corresponding templates.
The car of the list is a keyword to identify the environment.
the two following items in the list are the templates for environment
and item. See `cdlatex-env-alist-default' for examples. Any entries
in this variable will be added to the default definitions."
:group 'cdlatex-environment-support
:type '(repeat
(list :tag ""
(string :format "ENVIRONMENT %v" "")
(text :format "ENVIRONMENT TEMPLATE\n%v" "")
(choice :tag "ITEM"
(const :tag "none" nil)
(text :tag "template" :format "TEMPLATE\n%v" "")))))
(defcustom cdlatex-insert-auto-labels-in-env-templates t
"*Non-nil means the environment templates CDLaTeX will contain labels.
This variable may be set to t, nil, or a string of label type letters
indicating the label types for which it should be true."
:group 'cdlatex-making-and-inserting-labels
:type '(choice :tag "Insert labels in templates"
(const :tag "always" t)
(const :tag "never" nil)
(string :tag "selected label types" "")))
;; Configuration of Math character insertion and accents ----------------
(defgroup cdlatex-math-support nil
"Support for mathematical symbols and accents in CDLaTeX."
:group 'cdlatex)
(defcustom cdlatex-math-symbol-prefix ?`
"Prefix key for `cdlatex-math-symbol'.
This may be a character, a string readable with read-kbd-macro, or a
lisp vector."
:group 'cdlatex-math-support
:type '(choice
(character)
(string :value "" :tag "kbd readable string")
(sexp :value [] :tag "a lisp vector")))
(defcustom cdlatex-math-symbol-direct-bindings '(nil nil nil)
"How to bind the math symbols directly.
This is a list of key binding descriptions for different levels of
math symbols. First entry for level 1 etc.
Each entry consists of a prefix key and a list of modifiers for the
character. The prefix key can be nil, or any of a character, a
read-kbd-macro readable string or a vector.
Examples:
`((nil alt))' bind `\\delta' to `A-d'.
`((\"C-c C-f\"))' bind `\\delta' to `C-c C-f d'.
`((nil alt) (nil alt control))' bind `\\delta' to `A-d' and
`\\partial' (which is on level 2)
to `A-C-d'"
:group 'cdlatex-math-support
:type '(repeat
(choice
(const :tag "No binding of this level" nil)
(cons
:tag "Specify a binding"
:value (nil alt)
(choice
(const :tag "No prefix" nil)
(character :value ?@)
(string :value "" :tag "kbd readable string")
(sexp :value [] :tag "a lisp vector"))
(set :tag "Modifiers for the final character" :greedy t
(const control)
(const meta)
(const alt)
(const super)
(const hyper))))))
(defcustom cdlatex-math-symbol-alist nil
"Key characters and math symbols for fast access with the prefix key.
First element is a character, followed by a number of strings attached to
this key. When the string contains a question mark, this is where the
cursor will be positioned after insertion of the string into the buffer.
See `cdlatex-math-symbol-alist-default' for an example. Any entry defined
here will replace the corresponding entry of the default list. The
defaults implement 3 levels of symbols so far: Level 1 for greek letters
and standard symbols, level 2 for variations of level 1, and level 3 for
functions and opperators."
:group 'cdlatex-math-support
:type '(repeat
(list
(character ?a)
(repeat (string :tag "macro" "")))))
(defcustom cdlatex-math-modify-prefix ?'
"Prefix key for `cdlatex-math-modify'.
It can be a character, a string interpretable with `read-kbd-macro',
or a lisp vector."
:group 'cdlatex-math-support
:type '(choice
(character)
(string :value "" :tag "kbd readable string")
(sexp :value [] :tag "a lisp vector")))
(defcustom cdlatex-modify-backwards t
"*Non-nil means, `cdlatex-math-modify' modifies char before point.
Nil means, always insert only an empty modification form. This is also
the case if the character before point is white or some punctuation. "
:group 'cdlatex-math-support
:type 'boolean)
(defcustom cdlatex-math-modify-alist nil
"List description of the LaTeX math accents.
See `cdlatex-math-modify-alist-default' for an example. Any entries in this
variable will be added to the default.
Each element contains 6 items:
0. key: The character that is the key for a the accent.
1. mathcmd: The LaTeX command associated with the accent in math mode
2. textcmd: The LaTeX command associated with the accent in text mode
3. type: t if command with argument (e.g. \\tilde{a}).
nil if style (e.g. {\\cal a}).
4. rmdot: t if the dot on i and j has to be removed.
5. it t if italic correction is required."
:group 'cdlatex-math-support
:type '(repeat
(list (character :tag "Key character ")
(choice :tag "TeX macro inside math mode"
(string "")
(const :tag "none" nil))
(choice :tag "TeX macro outside math mode"
(string "")
(const :tag "none" nil))
(boolean :tag "Type " :on "Command" :off "Style")
(boolean :tag "Remove dot in i/j")
(boolean :tag "Italic correction"))))
(defcustom cdlatex-make-sub-superscript-roman-if-pressed-twice nil
"*Non-nil means, pressing `^` or `_' twice inserts roman sub/superscript."
:group 'cdlatex-math-support
:type 'boolean)
(defcustom cdlatex-use-dollar-to-ensure-math t
"*Non-nil means, use $...$ to force a math mode setting where needed.
When nil, use \\(...\\) instead."
:group 'cdlatex-math-support
:type '(boolean))
;; Miscellaneous configurations -----------------------------------------
(defgroup cdlatex-miscellaneous-configurations nil
"Collection of further configurations."
:group 'cdlatex)
(defcustom cdlatex-use-fonts t
"*Non-nil means, use fonts in label menu and on-the-fly help.
Font-lock must be loaded as well to actually get fontified display."
:group 'cdlatex-miscellaneous-configurations
:type '(boolean))
(defcustom cdlatex-takeover-parenthesis t
"*Non-nil means, cdlatex is allowed to take over the parenthesis insertion.
THis means it will redefine the `(', `{', and `[' keys."
:group 'cdlatex-miscellaneous-configurations
:type '(boolean))
(defcustom cdlatex-takeover-dollar t
"*Non-nil means, cdlatex is allowed to take over the $.
THis means it will redefine the `$' keys."
:group 'cdlatex-miscellaneous-configurations
:type '(boolean))
(defcustom cdlatex-takeover-subsuperscript t
"*Non-nil means, cdlatex is allowed to take over the ^ and _ keys."
:group 'cdlatex-miscellaneous-configurations
:type '(boolean))
(defcustom cdlatex-paired-parens "$[{"
"*String with the opening parens you want to have inserted paired.
The following parens are allowed here: `$([{|<'.
I recommend to set this to '$[{' as these have syntactical meaning in
TeX and are required to be paired. TAB is a good way to move out of paired
parens."
:group 'cdlatex-miscellaneous-configurations
:type '(string :tag "Opening delimiters"))
(defcustom cdlatex-simplify-sub-super-scripts t
"*Non-nil means, TAB will simplify sub- and superscripts at point.
When you use TAB to exit from a sub- or superscript which is a single
letter, the parenthesis will be removed."
:group 'cdlatex-miscellaneous-configurations
:type '(boolean))
(defcustom cdlatex-sub-super-scripts-outside-math-mode t
"*Non-nil means, inserting ^ or _ will add dollars outside math environment.
So in text mode surrounding dollars and braces will be added with `_' and `^'.
When nil, `_' and `^' will just self-insert."
:group 'cdlatex-miscellaneous-configurations
:type '(boolean))
(defcustom cdlatex-auto-help-delay 1.5
"Number of idle seconds before display of auto-help.
When executing cdlatex-math-symbol or cdlatex-math-modify, display
automatic help when idle for more than this amount of time."
:group 'cdlatex-miscellaneous-configurations
:type 'number)
(require 'texmathp)
;;;============================================================================
;;;
;;; Define the formal stuff for a minor mode named CDLaTeX.
;;;
(defun cdlatex-show-commentary ()
"Use the finder to view the file documentation from `cdlatex.el'."
(interactive)
(require 'finder)
(finder-commentary "cdlatex.el"))
(defconst cdlatex-version "4.6"
"Version string for CDLaTeX.")
(defvar cdlatex-mode nil
"Determines if CDLaTeX minor mode is active.")
(make-variable-buffer-local 'cdlatex-mode)
(defvar cdlatex-mode-map (make-sparse-keymap)
"Keymap for CDLaTeX minor mode.")
(defvar cdlatex-mode-menu nil)
;;;###autoload
(defun turn-on-cdlatex ()
"Turn on CDLaTeX minor mode."
(cdlatex-mode t))
;;;###autoload
(defun cdlatex-mode (&optional arg)
"Minor mode for editing scientific LaTeX documents. Here is a
list of features: \\<cdlatex-mode-map>
KEYWORD COMMANDS
----------------
Many CDLaTeX commands are activated with an abbrev-like mechanism.
When a keyword is typed followed `\\[cdlatex-tab]', the keyword is deleted
from the buffer and a command is executed. You can get a full list
of these commands with `\\[cdlatex-command-help]'.
For example, when you type `fr<TAB>', CDLaTeX will insert `\\frac{}{}'.
When inserting templates like '\\frac{}{}', the cursor is positioned
properly. Use `\\[cdlatex-tab]' to move through templates. `\\[cdlatex-tab]' also kills
unnecessary braces around subscripts and superscripts at point.
MATH CHARACTERS AND ACCENTS
---------------------------
\\[cdlatex-math-symbol] followed by any character inserts a LaTeX math character
e.g. \\[cdlatex-math-symbol]e => \\epsilon
\\[cdlatex-math-symbol]\\[cdlatex-math-symbol] followed by any character inserts other LaTeX math character
e.g. \\[cdlatex-math-symbol]\\[cdlatex-math-symbol]e => \\varepsilon
\\[cdlatex-math-modify] followed by character puts a math accent on a letter or symbol
e.g. \\[cdlatex-math-symbol]a\\[cdlatex-math-modify]~ => \\tilde{\\alpha}
CDLaTeX is aware of the math environments in LaTeX and modifies the
workings of some functions according to the current status.
ONLINE HELP
-----------
After pressing \\[cdlatex-math-symbol] or \\[cdlatex-math-modify], CDLaTeX waits for a short time for the second character.
If that does not come, it will pop up a window displaying the available
characters and their meanings.
KEY BINDINGS
------------
\\{cdlatex-mode-map}
Under X, many functions will be available also in a menu on the menu bar.
Entering cdlatex-mode calls the hook cdlatex-mode-hook.
------------------------------------------------------------------------------"
(interactive "P")
(setq cdlatex-mode (not (or (and (null arg) cdlatex-mode)
(<= (prefix-numeric-value arg) 0))))
; Add or remove the menu, and run the hook
(if cdlatex-mode
(progn
(easy-menu-add cdlatex-mode-menu)
(run-hooks 'cdlatex-mode-hook)
(cdlatex-compute-tables))
(easy-menu-remove cdlatex-mode-menu)))
(or (assoc 'cdlatex-mode minor-mode-alist)
(setq minor-mode-alist
(cons '(cdlatex-mode " CDL") minor-mode-alist)))
(or (assoc 'cdlatex-mode minor-mode-map-alist)
(setq minor-mode-map-alist
(cons (cons 'cdlatex-mode cdlatex-mode-map)
minor-mode-map-alist)))
;;; ===========================================================================
;;;
;;; Functions that check out the surroundings
(defun cdlatex-dollars-balanced-to-here (&optional from)
;; Return t if the dollars are balanced between start of paragraph and point.
(save-excursion
(let ((answer t) (pos (point)))
(if from
(goto-char from)
(backward-paragraph 1))
(if (not (bobp)) (backward-char 1))
(while (re-search-forward "[^\\]\\$+" pos t)
(if (/= (char-after (match-beginning 0)) ?\\)
(setq answer (not answer))))
(setq answer answer))))
(defun cdlatex-number-of-backslashes-is-odd ()
;; Count backslashes before point and return t if number is odd.
(let ((odd nil))
(save-excursion
(while (equal (preceding-char) ?\\)
(progn
(forward-char -1)
(setq odd (not odd)))))
(setq odd odd)))
;; ============================================================================
;;
;; Some generally useful functions
(defun cdlatex-get-kbd-vector (obj)
(cond ((vectorp obj) obj)
((integerp obj) (vector obj))
((stringp obj) (read-kbd-macro obj))
((and (fboundp 'characterp) (characterp obj))
(vector obj)) ; XEmacs only
(t nil)))
(defun cdlatex-uniquify (alist &optional keep-list)
;; Return a list of all elements in ALIST, but each car only once.
;; Elements of KEEP-LIST are not removed even if duplicate.
(let (new elm)
(while alist
(setq elm (car alist)
alist (cdr alist))
(if (or (member (car elm) keep-list)
(not (assoc (car elm) new)))
(setq new (cons elm new))))
(setq new (nreverse new))
new))
(defun cdlatex-use-fonts ()
;; Return t if we can and want to use fonts.
(and window-system
cdlatex-use-fonts
(boundp 'font-lock-keyword-face)))
;;; ---------------------------------------------------------------------------
;;;
;;; Insert pairs of $$ (), etc.
;; Alist connection opening with closing delimiters
(defconst cdlatex-parens-pairs '(("(".")") ("["."]") ("{"."}")
("|"."|") ("<".">")))
(defun cdlatex-pbb ()
"Insert a pair of parens, brackets or braces."
(interactive)
(let ((paren (char-to-string (event-basic-type last-command-event))))
(if (and (stringp cdlatex-paired-parens)
(string-match (regexp-quote paren) cdlatex-paired-parens)
(not (cdlatex-number-of-backslashes-is-odd)))
(progn
(insert paren)
(insert (cdr (assoc paren cdlatex-parens-pairs)))
(forward-char -1))
(insert paren))))
(defun cdlatex-ensure-math ()
;; Make sure we are in math
(unless (texmathp)
(if cdlatex-use-dollar-to-ensure-math
(cdlatex-dollar)
(insert "\\(\\)")
(backward-char 2))))
(defun cdlatex-dollar (&optional arg)
"Insert a pair of dollars unless number of backslashes before point is odd.
With arg, insert pair of double dollars."
(interactive "P")
(if (cdlatex-number-of-backslashes-is-odd)
(insert "$")
(if (texmathp)
(if (and (stringp (car texmathp-why))
(equal (substring (car texmathp-why) 0 1) "\$"))
(progn
(insert (car texmathp-why))
(save-excursion
(goto-char (cdr texmathp-why))
(if (pos-visible-in-window-p)
(sit-for 1))))
(message "No dollars inside a math environment!")
(ding))
(if (and (stringp cdlatex-paired-parens)
(string-match "\\$" cdlatex-paired-parens))
(if arg
(if (bolp)
(progn (insert "\$\$\n\n\$\$\n") (backward-char 4))
(insert "\$\$ \$\$") (backward-char 3))
(insert "$$") (backward-char 1))
(if arg
(if (bolp) (insert "$$\n") (insert "$$"))
(insert "$"))))))
(defun cdlatex-sub-superscript ()
"Insert ^{} or _{} unless the number of backslashes before point is odd.
When not in LaTeX math environment, _{} and ^{} will have dollars.
When pressed twice, make the sub/superscript roman."
(interactive)
(if (and cdlatex-make-sub-superscript-roman-if-pressed-twice
(equal this-command last-command))
(insert "\\rm ")
(if (cdlatex-number-of-backslashes-is-odd)
;; Quoted
(insert (event-basic-type last-command-event))
;; Check if we are in math mode, if not switch to or only add _ or ^
(if (and (not (texmathp))
(not cdlatex-sub-super-scripts-outside-math-mode))
(insert (event-basic-type last-command-event))
(if (not (texmathp)) (cdlatex-ensure-math))
;; Insert the normal template.
(insert (event-basic-type last-command-event))
(insert "{}")
(forward-char -1)))))
(defun cdlatex-lr-pair ()
"Insert a \\left-\\right pair of parens."
(interactive)
(let* ((paren (char-to-string (preceding-char)))
(close (cdr (assoc paren cdlatex-parens-pairs)))
(paren1 paren)
(close1 close))
(if (string= paren "<") (setq paren1 "\\langle" close1 "\\rangle"))
(if (string= paren "{") (setq paren1 "\\{" close1 "\\}"))
(backward-delete-char 1)
(if (and (stringp cdlatex-paired-parens)
(string-match (regexp-quote paren) cdlatex-paired-parens)
(string= close (char-to-string (following-char))))
; parens are inserted paired, and there is already a closing parenthesis
(delete-char 1))
(insert "\\left" paren1 " ? \\right" close1)
(cdlatex-position-cursor)))
;;; ===========================================================================
;;;
;;; Keyword controlled commands and cursor movement
(defvar cdlatex-command-alist-comb nil)
(defun cdlatex-tab ()
"This function is intended to do many cursor movements.
It is bound to the tab key since tab does nothing useful in a TeX file.
This function first calls all functions in `cdlatex-tab-hook', which see.
If none of those functions returns t, the command first tries to expand
any command keyword before point.
If there is none, it cleans up short subscripts and superscripts at point.
I.e. it changes a^{2} into a^2, since this is more readable. This feature
can be disabled by setting `cdlatex-simplify-sub-super-scripts' to nil.
Then it jumps to the next point in a LaTeX text where one would reasonably
expect that more input can be put in.
To do that, the cursor is moved according to the following rules:
The cursor stops...
- before closing brackets if preceding-char is any of -({[]})
- after closing brackets, but not if following-char is any of ({[_^
- just after $, if the cursor was before that $.
- at end of non-empty lines
- at the beginning of empty lines
- before a SPACE at beginning of line
- after first of several SPACE
Sounds strange? Try it out!"
(interactive)
(catch 'stop
;; try hook stuff
(let ((funcs cdlatex-tab-hook))
(while funcs (if (funcall (pop funcs)) (throw 'stop t))))
;; try command expansion
(let ((pos (point)) exp math-mode)
(backward-word 1)
(while (eq (following-char) ?$) (forward-char 1))
(setq exp (buffer-substring-no-properties (point) pos))
(setq exp (assoc exp cdlatex-command-alist-comb))
(when exp
(setq math-mode (texmathp))
(when (or (and (not math-mode) (nth 5 exp))
(and math-mode (nth 6 exp)))
(delete-char (- pos (point)))
(insert (nth 2 exp))
;; call the function if there is one defined
(and (nth 3 exp)
(if (nth 4 exp)
(apply (nth 3 exp) (nth 4 exp))
(funcall (nth 3 exp))))
(throw 'stop t)))
(goto-char pos))
;; Check for simplification of sub and superscripts
(cond
((looking-at "}\\|\\]\\|)")
(forward-char -3)
(if (and (looking-at "[_^]{[-+0-9a-zA-Z]}")
cdlatex-simplify-sub-super-scripts)
;; simplify sub/super script
(progn (forward-char 1)
(delete-char 1)
(forward-char 1)
(delete-char 1))
(forward-char 4))
(if (looking-at "[^_^({[]")
;; stop after closing bracket, unless ^_[{( follow
(throw 'stop t)))
((= (following-char) ?$)
(while (= (following-char) ?$) (forward-char 1))
(throw 'stop t))
((= (following-char) ?\ )
;; stop after first of many spaces
(forward-char 1)
(re-search-forward "[^ ]")
(if (/= (preceding-char) ?\n) (forward-char -1)))
(t
(forward-char 1)))
;; move to next possible stopping site and check out the place
(while (re-search-forward "[ )}\n]\\|\\]" (point-max) t)
(forward-char -1)
(cond
((= (following-char) ?\ )
;; stop at first space or b-o-l
(if (not (bolp)) (forward-char 1)) (throw 'stop t))
((= (following-char) ?\n)
;; stop at line end, but not after \\
(if (and (bolp) (not (eobp)))
(throw 'stop t)
(if (equal "\\\\" (buffer-substring-no-properties
(- (point) 2) (point)))
(forward-char 1)
(throw 'stop t))))
(t
;; Stop before )}] if preceding-char is any parenthesis
(if (or (= (char-syntax (preceding-char)) ?\()
(= (char-syntax (preceding-char)) ?\))
(= (preceding-char) ?-))
(throw 'stop t)
(forward-char 1)
(if (looking-at "[^_\\^({\\[]")
;; stop after closing bracket, unless ^_[{( follow
(throw 'stop t))))))))
(defun cdlatex-command-help (&optional arg)
"Show the available cdlatex commands in the help buffer."
(interactive "P")
(if arg
(call-interactively 'TeX-documentation-texdoc)
(with-output-to-temp-buffer " *CDLaTeX Help*"
(princ " AVAILABLE KEYWORD COMMANDS WITH CDLaTeX\n")
(princ " --------------------------------------\n")
(princ "To execute, type keyword into buffer followed by TAB.\n\n")
(let ((cmdlist cdlatex-command-alist-comb) item key doc text math)
(while cmdlist
(setq item (car cmdlist)
cmdlist (cdr cmdlist)
key (car item)
doc (nth 1 item)
text (nth 5 item)
math (nth 6 item))
(princ (format "%-10.10s %-58.58s %4s/%4s\n" key
(if (> (length doc) 59)
(substring doc 0 59)
doc)
(if text "TEXT" "")
(if math "MATH" ""))))))))
;;; ---------------------------------------------------------------------------
;;;
;;; Cursor position after insertion of forms
(defun cdlatex-position-cursor ()
;; Search back to question mark, delete it, leave point there
(if (search-backward "\?" (- (point) 100) t)
(delete-char 1)))