1;;; yatex.el --- Yet Another tex-mode for emacs //�쒹// -*- coding: sjis -*-
2;;; (c)1991-2019 by HIROSE Yuuji.[yuuji@yatex.org]
3;;; Last modified Thu Dec 26 12:46:41 2019 on firestorm
4;;; $Id: yatex.el,v 4dad5f91b26c 2019-12-26 12:50 +0859 yuuji $
5;;; The latest version of this software is always available at;
6;;; https://www.yatex.org/
7
8;;;   This  program  is  distributed  as   a  free  software.   You  can
9;;; use/copy/modify/redistribute  this  software   freely  but  with  NO
10;;; warranty to anything  as a result of using  this software.  Adopting
11;;; code from  this program is also  free.  But I would  not do contract
12;;; act.
13;;;
14;;;   This software can be treated with: ``The 2-Clause BSD License''
15;;; (since 2017-09-09, yatex 1.80).
16
17;;; Code:
18(require 'yatexlib)
19(defconst YaTeX-revision-number "1.82"
20  "Revision number of running yatex.el")
21
22;---------- Local variables ----------
23(defvar YaTeX-prefix "\C-c"
24  "*Prefix key to call YaTeX functions.
25You can select favorite prefix key by setq in your ~/.emacs.")
26
27(defvar YaTeX-environment-indent 1
28  "*Indentation depth at column width in LaTeX environments.")
29
30(defvar YaTeX-fill-prefix nil
31  "*fill-prefix used for auto-fill-mode.
32The default value is nil.")
33
34(defvar YaTeX-fill-column 72
35  "*fill-column used for auto-fill-mode.")
36
37(defvar YaTeX-comment-prefix "%"
38  "TeX comment prefix.")
39
40(defvar YaTeX-current-position-register ?3
41  "*Position register to keep where the last completion was done.
42All of YaTeX completing input store the current position into
43the register YaTeX-current-position-register.  So every time you
44make a trip to any other part of text other than you are writing, you can
45return to the editing paragraph by calling register-to-point with argument
46YaTeX-current-position-register.")
47
48(defvar YaTeX-use-LaTeX2e t "*Use LaTeX2e or not.  Nil means latex 2.09")
49
50(defvar tex-command
51  (cond
52   (YaTeX-use-LaTeX2e "platex -kanji=%k")
53   (YaTeX-japan "jlatex")
54   (t "latex"))
55  "*Default command for typesetting LaTeX text.
56Overridden with `%#! CommandLine...' in the buffer.
57`%'s followed by a character are replaced as follows:
58%f -> Parent(main) document file name
59%r -> %f without extension
60%k -> One of Kanji code mnemonic: euc, jis, sjis, utf8
61")
62
63(defvar bibtex-command (if YaTeX-japan "pbibtex -kanji=%k" "bibtex")
64  "*Default command of BibTeX.
65Overridden with `%#BIBTEX CommandLine...' in the buffer.
66Pettern `%k' in a string will be replaced with Kanji-code mnemonic of ptex.")
67
68(defvar dvi2-command		;previewer command for your site
69  (cond (YaTeX-dos	"dviout -wait=0")
70	(YaTeX-macos	"open -a Preview")
71	(t		"xdvi -geo +0+0 -s 4"))
72  "*Default previewer command including its option.
73Overridden with `%#PREVIEW CommandLine...' in the buffer.")
74
75(defvar YaTeX-cmd-gimp "gimp")
76(defvar YaTeX-cmd-tgif "tgif")
77(defvar YaTeX-cmd-inkscape "inkscape")
78(defvar YaTeX-cmd-dia "dia")
79(defvar YaTeX-cmd-ooo "soffice")
80(defvar YaTeX-cmd-gs "gs")
81(defvar YaTeX-cmd-dvips
82  (if (YaTeX-executable-find "pdvips") "pdvips" "dvips"))
83(defvar YaTeX-cmd-displayline
84  "/Applications/Skim.app/Contents/SharedSupport/displayline")
85(defvar YaTeX-cmd-edit-ps YaTeX-cmd-gimp)
86(defvar YaTeX-cmd-edit-pdf YaTeX-cmd-ooo)
87(defvar YaTeX-cmd-edit-ai YaTeX-cmd-inkscape)
88(defvar YaTeX-cmd-edit-svg YaTeX-cmd-inkscape)
89(defvar YaTeX-cmd-edit-images YaTeX-cmd-gimp)
90(defvar YaTeX-cmd-view-images "display -geometry +0+0")
91
92(defvar tex-pdfview-command	;previewer command for your site
93  (cond
94   (YaTeX-dos	"acroread")
95   (YaTeX-macos	(cond
96		 ((file-executable-p YaTeX-cmd-displayline) "open -a Skim")
97		 (t "open")))
98   ((YaTeX-executable-find "evince")		"evince")
99   ((YaTeX-executable-find "xreader")		"xreader")
100   ((YaTeX-executable-find "atril")		"atril")
101   ((YaTeX-executable-find "okular")		"okular")
102   ((YaTeX-executable-find "kpdf")		"kpdf")
103   ((YaTeX-executable-find "xpdf")		"xpdf")
104   ((YaTeX-executable-find "mupdf")		"mupdf")
105   (t		"acroread"))
106  "*Default PDF viewer command including its option.
107Overridden with `%#PDFVIEW CommandLine...' in the buffer.")
108
109(defvar makeindex-command (if YaTeX-dos "makeind" "makeindex")
110  "*Default makeindex command.
111Overridden with `%#MAKEINDEX CommandLine...' in the buffer.")
112
113(defvar dviprint-command-format
114  (if YaTeX-dos "dviprt %s %f%t"
115      "dvi2ps %f %t %s | lpr")
116  "*Command line string to print out current file.
117Overridden with `%#LPR CommandLine...' in the buffer.
118Format string %s will be replaced by the filename.  Do not forget to
119specify the `from usage' and `to usage' with their option by format string
120%f and %t.
121  See also documentation of dviprint-from-format and dviprint-to-format.")
122
123(defvar dviprint-from-format
124  (if YaTeX-dos "%b-" "-f %b")
125  "*`From' page format of dvi filter.  %b will turn to beginning page number.")
126
127(defvar dviprint-to-format
128  (if YaTeX-dos "%e" "-t %e")
129  "*`To' page format of dvi filter.  %e will turn to end page number.")
130
131(defvar YaTeX-dvipdf-command
132  "dvipdfmx"
133  "*Command name to convert dvi file to PDF.
134Overridden with `%#DVIPDF CommandLine...' in the buffer.")
135
136(defvar YaTeX-default-document-style
137  (concat (if YaTeX-japan "js") "article")
138  "*Default LaTeX Documentstyle for YaTeX-typeset-region.")
139
140(defvar YaTeX-need-nonstop nil
141  "*T for adding `\\nonstopmode{}' to text before invoking latex command.")
142
143(defvar latex-warning-regexp "line.* [0-9]*"
144  "*Regular expression of line number of warning message by latex command.")
145
146(defvar latex-error-regexp "l\\.[1-9][0-9]*"
147  "*Regular expression of line number of latex error.
148Perhaps your latex command stops at this error message with line number of
149LaTeX source text.")
150
151(defvar latex-dos-emergency-message
152  "Emergency stop"      ;<- for Micro tex, ASCII-pTeX 1.6
153  "Message pattern of emergency stop of typesetting.
154Because Demacs (GNU Emacs on DOS) cannot have concurrent process, the
155latex command which is stopping on a LaTeX error, is terminated by Demacs.
156Many latex command on DOS display some messages when it is terminated by
157other process, user or OS.  Define to this variable a message string of your
158latex command on DOS shown at abnormal termination.
159  Remember Demacs's call-process function is not oriented for interactive
160process.")
161
162(defvar NTT-jTeX nil
163  "*T for using NTT-jTeX for latex command.
164More precisely, setting t to this variables inhibits inter-word break on
165typeset document by line-break of source text.  That is, YaTeX automatically
166put % after each line at filling.
167���s+�C���f���g�ɂ���āA�^�C�v�Z�b�g��̎��Ԃ����Ă��܂��̂�}������ꍇ��
168t�ɂ���(�Â�NTT-jTeX�Ō����Ɍ����)�B��̓I�ɂ́Afill����Ƃ��Ɋe�s�̏I����
169%��t������B")
170
171
172(defvar YaTeX-item-regexp
173  (concat (regexp-quote "\\") "\\(sub\\|bib\\)*item")
174  "*Regular expression of item command.")
175
176(defvar YaTeX-sectioning-regexp
177  "\\(part\\|chapter\\*?\\|\\(sub\\)*\\(section\\|paragraph\\)\\)\\(\\*\\|\\b\\)"
178  "*LaTeX sectioning commands regexp.")
179
180(defvar YaTeX-paragraph-start
181  (concat "^[ \t]*%\\|^[ \t]*$\\|\\'\\|^\C-l\\|\\\\\\\\$\\|^[ \t]*\\\\\\("
182	  YaTeX-sectioning-regexp		;sectioning commands
183	  "\\|[A-z]*item\\|begin{\\|end{"	;special declaration
184	  "\\|\\[\\|\\]"
185	  "\\|newpage\\b\\|vspace\\b"
186	  "\\)")
187  "*Paragraph starting regexp of common LaTeX source.  Use this value
188for YaTeX-uncomment-paragraph.")
189
190(defvar YaTeX-paragraph-separate
191  (concat "^[ \t]*%\\|^[ \t]*$\\|^\C-l\\|\\\\\\\\$\\|^[ \t]*\\\\\\("
192	  YaTeX-sectioning-regexp		;sectioning commands
193	  "\\|begin{\\|end{"			;special declaration
194	  "\\|\\[\\|\\]"
195	  "\\|newpage\\b\\|vspace\\b"
196	  "\\)")
197  "*Paragraph delimiter regexp of common LaTeX source.  Use this value
198for YaTeX-uncomment-paragraph.")
199
200(defvar YaTeX-verbatim-environments
201  '("verbatim" "verbatim*" "alltt")
202  "*Assume these environments of this variable disable LaTeX commands.")
203(defvar YaTeX-verb-regexp "verb\\*?\\|path"
204  "*Regexp of verb family.  Do not contain preceding \\\\ nor \\(\\).")
205(defvar YaTeX-fill-inhibit-environments
206  (append '("tabular" "tabular*" "array" "picture" "eqnarray" "eqnarray*"
207	    "longtable" "tabularx"
208	    "equation" "equation*" "math" "displaymath")
209	  YaTeX-verbatim-environments)
210  "*In these environments, YaTeX inhibits fill-paragraph from formatting.
211Define those environments as a form of list.")
212
213(defvar YaTeX-itemizing-env-regexp
214  "itemize\\|enumerate\\|description\\|list\\|thebibliography"
215  "*Regexp of itemizing environments")
216(defvar YaTeX-equation-env-regexp
217  "array\\*?\\|equation\\*?"
218  "*Regexp of environments for equations")
219(defvar YaTeX-array-env-regexp
220  (concat
221   "array\\*?\\|eqnarray\\*?\\|tabbing\\|tabularx?\\*?\\|"	;LaTeX
222   "longtable\\|"						;LaTeX2e
223   "matrix\\|pmatrix\\|bmatrix\\|vmatrix\\|Vmatrix\\|"		;AMS-LaTeX
224   "align\\*?\\|split\\*?\\|aligned\\*?\\|alignat\\*?\\|"	;AMS-LaTeX
225   "[bpvV]?matrix\\|smallmatrix\\|cases\\|"			;AMS-LaTeX
226   "xalignat\\*?\\|xxalignat\\*?")				;AMS-LaTeX
227  "*Regexp of environments where `&' becomes field delimiter.")
228(defvar YaTeX-uncomment-once t
229  "*T for removing all continuous commenting character(%).
230Nil for removing only one commenting character at the beginning-of-line.")
231
232(defvar YaTeX-close-paren-always t
233  "*Close parenthesis always when YaTeX-modify-mode is nil.")
234
235(defvar YaTeX-greek-by-maketitle-completion nil
236  "*T for greek letters completion by maketitle-type completion.")
237
238(defvar YaTeX-auto-math-mode t
239  "*T for changing YaTeX-math mode automatically.")
240(defvar YaTeX-use-AMS-LaTeX t
241  "*T for using AMS-LaTeX")
242
243(defvar yatex-mode-hook nil
244  "*List of functions to be called at the end of yatex-mode initializations.")
245
246(defvar YaTeX-search-file-from-top-directory t
247  "*Non-nil means to search input-files from the directory where main file exists.")
248
249(defvar YaTeX-use-font-lock (and (featurep 'font-lock)
250				 (fboundp 'x-color-values)
251				 (fboundp 'font-lock-fontify-region))
252  "*Use font-lock to fontify buffer or not.")
253
254(defvar YaTeX-use-hilit19 (and (featurep 'hilit19) (fboundp 'x-color-values)
255			       (fboundp 'hilit-translate)
256			       (not YaTeX-use-font-lock))
257  "*Use hilit19 to highlight buffer or not.")
258
259(defvar YaTeX-tabular-indentation 4
260  "*Indentation column-depth of continueing line in tabular environment.")
261
262(defvar YaTeX-electric-indent-mode -1
263  "*(for Emacs 24.4+) Pass this value to electric-indent-local-mode.
264-1 means `off'.")
265
266;;-- Math mode values --
267
268(defvar YaTeX-math-key-list-default
269  '((";" . YaTeX-math-sign-alist)
270    (":" . YaTeX-greek-key-alist))
271  "Default key sequence to invoke math-mode's image completion.")
272
273(defvar YaTeX-math-key-list-private nil
274  "*User defined alist, math-mode-prefix vs completion alist.")
275
276(defvar YaTeX-math-key-list
277  (append YaTeX-math-key-list-private YaTeX-math-key-list-default)
278  "Key sequence to invoke math-mode's image completion.")
279
280(defvar YaTeX-skip-default-reader nil
281  "Non-nil skips default argument reader of section-type completion.")
282
283(defvar YaTeX-simple-messages nil
284  "Non-nil makes minibuffer messages simpler.")
285
286(defvar YaTeX-template-file "~/work/template.tex"
287  "*Template TeX source file.  This will be inserted to empty file.")
288
289(defvar YaTeX-addin-prefix "YaTeX:")
290
291(defvar yatex-mode-abbrev-table nil
292  "*Abbrev table in use in yatex-mode buffers.")
293(define-abbrev-table 'yatex-mode-abbrev-table ())
294
295
296;------------ Completion table ------------
297; Set tex-section-like command possible completion
298(defvar section-table
299  (append
300   '(("part") ("chapter") ("chapter*") ("section") ("section*")
301     ("subsection") ("subsection*")
302     ("subsubsection") ("paragraph") ("subparagraph")
303     ("author") ("thanks") ("documentstyle") ("pagestyle") ("thispagestyle")
304     ("title") ("underline") ("label") ("makebox")
305     ("footnote") ("footnotetext") ("index")
306     ("hspace*") ("vspace*")
307     ("bibliography") ("bibliographystyle") ("bibitem") ("cite")
308     ("input") ("include") ("includeonly") ("mbox") ("hbox") ("caption")
309     ("arabic") ("centering") ("uline")
310     ("newcounter")
311     ("newlength") ("setlength" 2) ("addtolength" 2) ("settowidth" 2)
312     ("setcounter" 2) ("addtocounter" 2) ("stepcounter" 2)
313     ("newcommand" 2) ("renewcommand" 2)
314     ("newenvironment" 3) ("newtheorem" 2)
315     ("cline") ("framebox") ("savebox" 2) ("sbox" 2) ("newsavebox") ("usebox")
316     ("date") ("put") ("ref") ("pageref") ("tabref") ("figref") ("raisebox" 2)
317     ("multicolumn" 3) ("shortstack") ("parbox" 2)
318     ;; for mathmode accent
319     ("tilde") ("hat") ("check") ("bar") ("dot") ("ddot") ("vec")
320     ("widetilde") ("widehat") ("overline") ("overrightarrow")
321     ;; section types in mathmode
322     ("frac" 2) ("sqrt") ("mathrm") ("mathbf") ("mathit") ("mathbb")
323     ("mathscr") ("mathrsfs")
324     ;;cleveref
325     ("cref") ("crefrange") ("cpageref") ("labelcref") ("labelcpageref")
326     ("frametitle") ("framesubtitle") 				;; beamer
327     ("subfigure")						;; subfigure
328     ("ruby" 2) ("kenten")					;; okumacro
329     ("geometry") ("path")
330     )
331   (if YaTeX-use-LaTeX2e
332       '(("documentclass") ("usepackage")
333	 ("textbf") ("textgt") ("textit") ("textmc") ("textmd") ("textnormal")
334	 ("textrm") ("textsc") ("textsf") ("textsl") ("texttt") ("textup")
335	 ("mathbf") ("mathcal") ("mathit") ("mathnormal") ("mathrm")
336	 ("mathsf") ("mathtt") ("text")
337	 ("textcircled")
338	 ("scalebox" 1) ;is faking of argument position
339	 ("rotatebox" 2) ("resizebox" 3) ("reflectbox")
340	 ("colorbox" 2) ("fcolorbox" 3) ("textcolor" 2) ("color") ("pagecolor")
341	 ("includegraphics") ("includegraphics*")
342	 ("includesvg")
343	 ("bou")			;defined in plext
344	 ("url")			;defined in url
345	 ("shadowbox") ("doublebox") ("ovalbox") ("Ovalbox")
346	 ("fancyoval")			;defined in fancybox
347	 ("keytop") ("mask" 2) ("maskbox" 5) ;defined in ascmac
348	 ("bm")				;deined in bm
349	 ("verbfile") ("listing")	;defined in misc
350	 ("slashbox" 2) ("backslashbox" 2) ;defined in slashbox
351	 ))
352   (if YaTeX-use-AMS-LaTeX
353       '(("DeclareMathOperator" 2) ("boldsymbol") ("pmb") ("eqref")
354	 ("tag") ("tag*"))))
355  "Default completion table for section-type completion.")
356
357(defvar user-section-table nil)
358(defvar tmp-section-table nil)
359(defvar YaTeX-ams-math-begin-alist
360  '(("align") ("align*") ("multline") ("multline*") ("gather") ("gather*")
361    ("alignat") ("alignat*") ("xalignat") ("xalignat*")
362    ("xxalignat") ("xxalignat*") ("flalign") ("flalign*") ("equation*")))
363(defvar YaTeX-ams-math-gathering-alist
364  '(("matrix") ("pmatrix") ("bmatrix") ("Bmatrix") ("vmatrix") ("Vmatrix")
365    ("split") ("split*") ("aligned") ("aligned*") ("alignedat") ("gathered")
366    ("smallmatrix") ("cases") ("subequations")))
367;; Prepare list(not alist) for YaTeX::ref in yatexadd.el
368(defvar YaTeX-math-other-env-alist-default
369  '(("numcases") ("subnumcases"))
370  "Default alist of additional environments for equations")
371(defvar YaTeX-math-other-env-alist-private nil
372  "*User defined alist of additional environments for equations")
373(defvar YaTeX-math-other-env-alist
374  (append YaTeX-math-other-env-alist-default
375	  YaTeX-math-other-env-alist-private)
376  "Alist of additional environments for equations")
377(defvar YaTeX-math-other-env-list
378  (mapcar 'car YaTeX-math-other-env-alist))
379
380(defvar YaTeX-math-begin-list
381  (mapcar 'car YaTeX-ams-math-begin-alist))
382(defvar YaTeX-math-gathering-list	;used in yatexadd.el#yatex::ref
383  (mapcar 'car YaTeX-ams-math-gathering-alist))
384
385(defvar YaTeX-ams-env-table
386  (append YaTeX-ams-math-begin-alist YaTeX-ams-math-gathering-alist)
387  "*Standard AMS-LaTeX(2e) environment completion table.")
388
389(defvar YaTeX-use-dot-env-extension t
390  "*Use YaTeX's dot-env filter special environment.")
391
392; Set tex-environment possible completion
393(defvar env-table
394  (append
395   '(("quote") ("quotation") ("center") ("verse") ("document")
396     ("verbatim") ("itemize") ("enumerate") ("description")
397     ("list") ("tabular") ("tabular*") ("table") ("tabbing") ("titlepage")
398     ("sloppypar") ("picture") ("displaymath")
399     ("eqnarray") ("eqnarray*") ("figure") ("equation") ("equation*")
400     ("abstract") ("array")
401     ("thebibliography") ("theindex") ("flushleft") ("flushright")
402     ("minipage") ("landscape")
403     ("supertabular") ("floatingfigure") ("wrapfigure") ("wraptable")
404     ("frame") ("block") ("example") ("columns") ("column")	;beamer
405     ("tabularx")
406     )
407   (if YaTeX-use-LaTeX2e
408       '(("comment")			;defined in version
409	 ("longtable")			;defined in longtable
410	 ("screen") ("boxnote") ("shadebox") ;; ("itembox") ;in ascmac
411	 ("alltt")			;defined in alltt
412	 ("multicols")			;defined in multicol
413	 ("breakbox")))			;defined in eclbkbox
414   (if YaTeX-use-AMS-LaTeX YaTeX-ams-env-table)
415   YaTeX-math-other-env-alist
416   (and YaTeX-use-dot-env-extension
417	(require 'yatexflt)
418	YaTeX-filter-special-env-alist))
419  "Default completion table for begin-type completion.")
420
421(defvar user-env-table nil)
422(defvar tmp-env-table nil)
423
424; Set {\Large }-like completion
425(defvar fontsize-table
426  '(("rm") ("em") ("bf") ("boldmath") ("it") ("sl") ("sf") ("sc") ("tt")
427    ("dg") ("dm")
428    ("tiny") ("scriptsize") ("footnotesize") ("small")("normalsize")
429    ("large") ("Large") ("LARGE") ("huge") ("Huge")
430    ("rmfamily") ("sffamily") ("ttfamily")
431    ("mdseries") ("bfseries") ("upshape")
432    ("itshape") ("slshape") ("scshape")
433    )
434  "Default completion table for large-type completion.")
435
436(defvar LaTeX2e-fontstyle-alist
437  '(("rm" . "rmfamily")
438    ("sf" . "sffamily")
439    ("tt" . "ttfamily")
440    ("md" . "mdseries")
441    ("bf" . "bfseries")
442    ("up" . "upshape")
443    ("it" . "itshape")
444    ("sl" . "slshape")
445    ("sc" . "scshape")))
446
447(defvar user-fontsize-table nil)
448(defvar tmp-fontsize-table nil)
449
450(defvar singlecmd-table
451  (append
452   '(("maketitle") ("makeindex") ("sloppy") ("protect") ("par") ("and")
453     ("LaTeX") ("TeX") ("item") ("item[]") ("appendix") ("hline") ("kill")
454     ;;("rightarrow") ("Rightarrow") ("leftarrow") ("Leftarrow")
455     ("onecolumn") ("twocolumn")
456     ("pagebreak") ("nopagebreak") ("tableofcontents")
457     ("newpage") ("clearpage") ("cleardoublepage")
458     ("footnotemark") ("verb") ("verb*")
459     ("linebreak") ("pagebreak") ("noindent") ("indent")
460     ("raggedright") ("raggedleft") ("centering")
461     ("left") ("right") ("dots") ("smallskip") ("medskip") ("bigskip")
462     ("displaystyle")
463     ("onslide") ("pause")		;beamer
464     )
465   (if YaTeX-greek-by-maketitle-completion
466       '(("alpha") ("beta") ("gamma") ("delta") ("epsilon")
467	 ("varepsilon") ("zeta") ("eta") ("theta")("vartheta")
468	 ("iota") ("kappa") ("lambda") ("mu") ("nu") ("xi") ("pi")
469	 ("varpi") ("rho") ("varrho") ("sigma") ("varsigma") ("tau")
470	 ("upsilon") ("phi") ("varphi") ("chi") ("psi") ("omega")
471	 ("Gamma") ("Delta") ("Theta") ("Lambda")("Xi") ("Pi")
472	 ("Sigma") ("Upsilon") ("Phi") ("Psi") ("Omega")))
473   (if YaTeX-use-LaTeX2e
474       '(("return") ("Return") ("yen")))	;defined in ascmac
475   (if YaTeX-use-AMS-LaTeX
476       '(("nonumber")))
477   )
478  "Default completion table for maketitle-type completion.")
479
480(defvar user-singlecmd-table nil)
481(defvar tmp-singlecmd-table nil)
482
483;---------- Key mode map ----------
484;;;
485;; Create new key map: YaTeX-mode-map
486;; Do not change this section.
487;;;
488(defvar YaTeX-mode-map nil
489  "Keymap used in YaTeX mode")
490
491(defvar YaTeX-prefix-map nil
492  "Keymap used when YaTeX-prefix key pushed")
493
494(defvar YaTeX-user-extensional-map (make-sparse-keymap)
495  "*Keymap used for the user's customization")
496(defvar YaTeX-current-completion-type nil
497  "Has current completion type.  This may be used in YaTeX addin functions.")
498
499(defvar YaTeX-modify-mode nil
500  "*Current editing mode.
501When non-nil, each opening parentheses only opens,
502nil enters both open/close parentheses when opening parentheses key pressed.")
503
504(defvar YaTeX-math-mode nil
505  "Holds whether current mode is math-mode.")
506;;;
507;; Define key table
508;;;
509(if YaTeX-mode-map
510    nil
511  (setq YaTeX-mode-map (make-sparse-keymap))
512  (setq YaTeX-prefix-map (make-sparse-keymap))
513  (define-key YaTeX-mode-map "\"" 'YaTeX-insert-quote)
514  (define-key YaTeX-mode-map "{" 'YaTeX-insert-braces)
515  (define-key YaTeX-mode-map "(" 'YaTeX-insert-parens)
516  (define-key YaTeX-mode-map "$" 'YaTeX-insert-dollar)
517  (define-key YaTeX-mode-map "|" 'YaTeX-insert-bar)
518  (define-key YaTeX-mode-map "&" 'YaTeX-insert-amper)
519  (define-key YaTeX-mode-map "[" 'YaTeX-insert-brackets)
520  (define-key YaTeX-mode-map YaTeX-prefix YaTeX-prefix-map)
521  (define-key YaTeX-mode-map "\M-\C-@" 'YaTeX-mark-environment)
522  (define-key YaTeX-mode-map "\M-\C-a" 'YaTeX-beginning-of-environment)
523  (define-key YaTeX-mode-map "\M-\C-e" 'YaTeX-end-of-environment)
524  (define-key YaTeX-mode-map "\M-\C-m" 'YaTeX-intelligent-newline)
525  (define-key YaTeX-mode-map "\C-i" 'YaTeX-indent-line)
526  (YaTeX-define-key "%" 'YaTeX-%-menu)
527  (YaTeX-define-key "t" 'YaTeX-typeset-menu)
528  (YaTeX-define-key "w" 'YaTeX-switch-mode-menu)
529  (YaTeX-define-key "'" 'YaTeX-prev-error)
530  (YaTeX-define-key "^" 'YaTeX-visit-main)
531  (YaTeX-define-key "4^" 'YaTeX-visit-main-other-window)
532  (YaTeX-define-key "4g" 'YaTeX-goto-corresponding-*-other-window)
533  (YaTeX-define-key "44" 'YaTeX-switch-to-window)
534  (and YaTeX-emacs-19 window-system
535       (progn
536	 (YaTeX-define-key "5^" 'YaTeX-visit-main-other-frame)
537	 (YaTeX-define-key "5g" 'YaTeX-goto-corresponding-*-other-frame)
538	 (YaTeX-define-key "55" 'YaTeX-switch-to-window)))
539  (YaTeX-define-key " " 'YaTeX-do-completion)
540  (YaTeX-define-key "v" 'YaTeX-version)
541
542  (YaTeX-define-key "}" 'YaTeX-insert-braces-region)
543  (YaTeX-define-key "]" 'YaTeX-insert-brackets-region)
544  (YaTeX-define-key ")" 'YaTeX-insert-parens-region)
545  (YaTeX-define-key "$" 'YaTeX-insert-dollars-region)
546  (YaTeX-define-key "i" 'YaTeX-fill-item)
547  (YaTeX-define-key "\\"
548   (function(lambda () (interactive)
549      (insert (if (YaTeX-in-math-mode-p) "\\backslash" "\\textbackslash")))))
550  (if YaTeX-no-begend-shortcut
551      (progn
552	(YaTeX-define-key "B" 'YaTeX-make-begin-end-region)
553	(YaTeX-define-key "b" 'YaTeX-make-begin-end))
554    (YaTeX-define-begend-key "bc" "center")
555    (YaTeX-define-begend-key "bd" "document")
556    (YaTeX-define-begend-key "bD" "description")
557    (YaTeX-define-begend-key "be" "enumerate")
558    (YaTeX-define-begend-key "bE" "equation")
559    (YaTeX-define-begend-key "bf" "figure")
560    (YaTeX-define-begend-key "bi" "itemize")
561    (YaTeX-define-begend-key "bl" "flushleft")
562    (YaTeX-define-begend-key "bm" "minipage")
563    (YaTeX-define-begend-key "bt" "tabbing")
564    (YaTeX-define-begend-key "bT" "tabular")
565    (YaTeX-define-begend-key "b\^t" "table")
566    (YaTeX-define-begend-key "bp" "picture")
567    (YaTeX-define-begend-key "bq" "quote")
568    (YaTeX-define-begend-key "bQ" "quotation")
569    (YaTeX-define-begend-key "br" "flushright")
570    (YaTeX-define-begend-key "bv" "verbatim")
571    (YaTeX-define-begend-key "bV" "verse")
572    (YaTeX-define-key "B " 'YaTeX-make-begin-end-region)
573    (YaTeX-define-key "b " 'YaTeX-make-begin-end))
574  (YaTeX-define-key "e" 'YaTeX-end-environment)
575  (YaTeX-define-key "S" 'YaTeX-make-section-region)
576  (YaTeX-define-key "s" 'YaTeX-make-section)
577  (YaTeX-define-key "L" 'YaTeX-make-fontsize-region)
578  (YaTeX-define-key "l" 'YaTeX-make-fontsize)
579  (YaTeX-define-key "m" 'YaTeX-make-singlecmd)
580  (YaTeX-define-key "." 'YaTeX-comment-paragraph)
581  (YaTeX-define-key "," 'YaTeX-uncomment-paragraph)
582  (YaTeX-define-key ">" 'YaTeX-comment-region)
583  (YaTeX-define-key "<" 'YaTeX-uncomment-region)
584  (YaTeX-define-key "g" 'YaTeX-goto-corresponding-*)
585  (YaTeX-define-key "k" 'YaTeX-kill-*)
586  (YaTeX-define-key "c" 'YaTeX-change-*)
587  (YaTeX-define-key "a" 'YaTeX-make-accent)
588  (YaTeX-define-key "?" 'YaTeX-help)
589  (YaTeX-define-key "/" 'YaTeX-apropos)
590  (YaTeX-define-key "&" 'YaTeX-what-column)
591  (YaTeX-define-key "d" 'YaTeX-display-hierarchy)
592  (YaTeX-define-key "x" YaTeX-user-extensional-map)
593  (YaTeX-define-key "n"
594    (function(lambda () (interactive)
595       (insert "\\" (if (YaTeX-on-section-command-p "o?oalign") "crcr" "\\")))))
596  (if YaTeX-dos
597      (define-key YaTeX-prefix-map "\C-r"
598	(function(lambda () (interactive)
599	   (YaTeX-set-screen-height YaTeX-saved-screen-height) (recenter))))))
600
601(defvar YaTeX-section-completion-map nil
602  "*Key map used at YaTeX completion in the minibuffer.")
603(if YaTeX-section-completion-map nil
604  (setq YaTeX-section-completion-map
605	(copy-keymap (or (and (boundp 'gmhist-completion-map)
606			      gmhist-completion-map)
607			 minibuffer-local-completion-map)))
608  (define-key YaTeX-section-completion-map
609    " " 'YaTeX-minibuffer-complete)
610  (define-key YaTeX-section-completion-map
611    "\C-i" 'YaTeX-minibuffer-complete)
612  (define-key YaTeX-section-completion-map
613    "\C-v" 'YaTeX-read-section-with-overview))
614
615(defvar YaTeX-recursive-map nil
616  "*Key map used at YaTeX reading arguments in the minibuffer.")
617(if YaTeX-recursive-map nil
618  (setq YaTeX-recursive-map (copy-keymap global-map))
619  (define-key YaTeX-recursive-map YaTeX-prefix YaTeX-prefix-map)
620  (mapcar
621   (function
622    (lambda (key)
623      (define-key YaTeX-mode-map (car key) 'YaTeX-math-insert-sequence)
624      (define-key YaTeX-recursive-map (car key) 'YaTeX-math-insert-sequence)))
625   YaTeX-math-key-list))
626;---------- Define other variable ----------
627(defvar YaTeX-env-name "document" "*Initial tex-environment completion")
628(defvar YaTeX-section-name
629  (if YaTeX-use-LaTeX2e "documentclass" "documentstyle")
630  "*Initial tex-section completion")
631(defvar YaTeX-fontsize-name "large" "*Initial fontsize completion")
632(defvar YaTeX-single-command "maketitle" "*Initial LaTeX single command")
633(defvar YaTeX-kanji-code nil
634  "*File kanji code used by Japanese TeX.
635nil: Do not care (Preserve coding-system)
6360: no-conversion (mule)
6371: Shift JIS
6382: JIS
6393: EUC
6404: UTF-8")
641
642(defvar YaTeX-coding-system nil "File coding system used by Japanese TeX.")
643(cond
644 (YaTeX-emacs-20
645  (setq YaTeX-coding-system
646	(cdr (assoc YaTeX-kanji-code YaTeX-kanji-code-alist))))
647 ((boundp 'MULE)
648  (setq YaTeX-coding-system
649	(symbol-value (cdr (assoc YaTeX-kanji-code YaTeX-kanji-code-alist))))))
650
651(defvar YaTeX-mode-syntax-table nil
652  "*Syntax table for yatex-mode")
653
654(if YaTeX-mode-syntax-table nil
655  (setq YaTeX-mode-syntax-table (make-syntax-table (standard-syntax-table)))
656  (modify-syntax-entry ?\n " " YaTeX-mode-syntax-table)
657  (modify-syntax-entry ?\{ "(}" YaTeX-mode-syntax-table)
658  (modify-syntax-entry ?\} "){" YaTeX-mode-syntax-table)
659  (modify-syntax-entry ?\t " " YaTeX-mode-syntax-table)
660  (modify-syntax-entry ?\f ">" YaTeX-mode-syntax-table)
661  (modify-syntax-entry ?\n ">" YaTeX-mode-syntax-table)
662  (modify-syntax-entry ?$ "$$" YaTeX-mode-syntax-table)
663  (modify-syntax-entry ?% "<" YaTeX-mode-syntax-table)
664  (modify-syntax-entry ?\\ "/" YaTeX-mode-syntax-table)
665  (modify-syntax-entry ?~ " " YaTeX-mode-syntax-table))
666
667(defvar YaTeX-mode-syntax-table-nonparen nil
668  "Syntax table for yatex-mode with normal parentheses treated white spaces")
669(if YaTeX-mode-syntax-table-nonparen nil
670  (setq YaTeX-mode-syntax-table-nonparen
671	(make-syntax-table YaTeX-mode-syntax-table))
672  (let ((zenparens "()�i�j�u�v�w�x�y�z�m�n�o�p�s�t�q�r�k�l") (i 0) s)
673    (while (string-match "." zenparens i)
674      (setq s (substring zenparens (match-beginning 0) (match-end 0))
675	    i (1+ i))
676      (modify-syntax-entry
677       (string-to-char s) " " YaTeX-mode-syntax-table-nonparen))))
678
679;---------- Provide YaTeX-mode ----------
680;;;
681;; Major mode definition
682;;;
683(defun yatex-mode ()
684  "  Yet Another LaTeX mode: Major mode for editing input files of LaTeX.
685-You can invoke processes concerning LaTeX typesetting by
686 		\\[YaTeX-typeset-menu]
687-Complete LaTeX environment form of `\\begin{env} ... \\end{env}' by
688		\\[YaTeX-make-begin-end]
689-Enclose region into some environment by
690		\\[universal-argument] \\[YaTeX-make-begin-end]
691-Complete LaTeX command which takes argument like `\\section{}' by
692		\\[YaTeX-make-section]
693-Put LaTeX command which takes no arguments like `\\maketitle' by
694		\\[YaTeX-make-singlecmd]
695-Complete font or character size descriptor like `{\\large }' by
696		\\[YaTeX-make-fontsize]
697-Enclose region into those descriptors above by
698		\\[universal-argument] \\[YaTeX-make-fontsize]
699-Enter European accent notations by
700		\\[YaTeX-make-accent]
701-Toggle various modes of YaTeX by
702		\\[YaTeX-switch-mode-menu]
703-Change environt name (on the begin/end line) by
704		\\[YaTeX-change-*]
705-Kill LaTeX command/environment sequences by
706		\\[YaTeX-kill-*]
707-Kill LaTeX command/environment with its contents
708		\\[universal-argument] \\[YaTeX-kill-*]
709-Go to corresponding object (begin/end, file, labels) by
710		\\[YaTeX-goto-corresponding-*]   or
711		\\[YaTeX-goto-corresponding-*-other-window]   (in other window)
712		\\[YaTeX-goto-corresponding-*-other-frame]   (in other frame)
713-Go to main LaTeX source text by
714		\\[YaTeX-visit-main]   or
715		\\[YaTeX-visit-main-other-window]   (in other window)
716		\\[YaTeX-visit-main-other-frame]   (in other frame)
717-Comment out or uncomment region by
718		\\[YaTeX-comment-region]  or  \\[YaTeX-uncomment-region]
719-Comment out or uncomment paragraph by
720		\\[YaTeX-comment-paragraph]  or  \\[YaTeX-uncomment-paragraph]
721-Make an \\item entry hang-indented by
722		\\[YaTeX-fill-item]
723-Enclose the region with parentheses by
724		\\[YaTeX-insert-parens-region]
725		\\[YaTeX-insert-braces-region]
726		\\[YaTeX-insert-brackets-region]
727		\\[YaTeX-insert-dollars-region]
728-Look up the corresponding column header of tabular environment by
729		\\[YaTeX-what-column]
730-Enter a newline and an entry suitable for environment by
731		\\[YaTeX-intelligent-newline]
732-View the structure of file inclusion by
733		\\[YaTeX-display-hierarchy]
734-Refer the online help of popular LaTeX commands by
735		\\[YaTeX-help]   (help)
736		\\[YaTeX-apropos]   (apropos)
737-Edit `%# notation' by
738		\\[YaTeX-%-menu]
739
740  Those are enough for fastening your editing of LaTeX source.  But further
741more features are available and they are documented in the manual.
742"
743  (interactive)
744  (kill-all-local-variables)
745  (setq major-mode 'yatex-mode)
746  (setq mode-name (if YaTeX-japan "���" "YaTeX"))
747  (mapcar 'make-local-variable
748	  '(dvi2-command fill-column fill-prefix
749	    tmp-env-table tmp-section-table tmp-fontsize-table
750	    tmp-singlecmd-table paragraph-start paragraph-separate
751	    YaTeX-math-mode indent-line-function comment-line-break-function
752	    comment-start comment-start-skip
753	    ))
754  (YaTeX-set-file-coding-system YaTeX-kanji-code YaTeX-coding-system)
755  (setq fill-column YaTeX-fill-column
756	fill-prefix YaTeX-fill-prefix
757	paragraph-start    YaTeX-paragraph-start
758	paragraph-separate YaTeX-paragraph-separate
759	indent-line-function 'YaTeX-indent-line
760	comment-start YaTeX-comment-prefix
761	comment-end ""
762	comment-start-skip "[^\\\\]%+[ \t]*"
763	local-abbrev-table yatex-mode-abbrev-table)
764  (if (fboundp 'comment-indent-new-line) ;for Emacs21
765      (setq comment-line-break-function 'YaTeX-comment-line-break))
766  ;; +dnd for X11 w/ emacs23+
767  (and window-system (featurep 'dnd) (require 'yatex23 nil t)
768       (set (make-local-variable 'dnd-protocol-alist)
769	    (cons (cons "^file:" 'YaTeX-dnd-handler) dnd-protocol-alist)))
770
771  (if (and YaTeX-use-font-lock (featurep 'font-lock))
772      (progn
773	(require 'yatex19)
774	(YaTeX-font-lock-set-default-keywords)
775	(or  (featurep 'xemacs)
776	     (set (make-local-variable 'font-lock-defaults)
777		  (get 'yatex-mode 'font-lock-defaults)))
778	;;(font-lock-mode 1)
779	))
780  (use-local-map YaTeX-mode-map)
781  (set-syntax-table YaTeX-mode-syntax-table)
782  (if YaTeX-dos (setq YaTeX-saved-screen-height (YaTeX-screen-height)))
783  (YaTeX-read-user-completion-table)
784  (and (fboundp 'YaTeX-hilit-setup-alist) (YaTeX-hilit-setup-alist))
785  (makunbound 'inenv)
786  ;(turn-on-auto-fill)			;1.63 -> 1.79off
787  (if (fboundp 'electric-indent-local-mode)
788      (electric-indent-local-mode YaTeX-electric-indent-mode))
789  (and (= 0 (buffer-size)) (file-exists-p YaTeX-template-file)
790       (y-or-n-p (format "Insert %s?" YaTeX-template-file))
791       (insert-file-contents (expand-file-name YaTeX-template-file)))
792  (run-hooks 'text-mode-hook 'yatex-mode-hook))
793
794;---------- Define YaTeX-mode functions ----------
795(defvar YaTeX-ec "\\" "Escape character of current mark-up language.")
796(defvar YaTeX-ec-regexp (regexp-quote YaTeX-ec))
797(defvar YaTeX-struct-begin
798  (concat YaTeX-ec "begin{%1}%2")
799  "Keyword format of begin-environment.")
800(defvar YaTeX-struct-end
801  (concat YaTeX-ec "end{%1}")
802  "Keyword format of end-environment.")
803(defvar YaTeX-struct-name-regexp "[^}]*"
804  "Environment name regexp.")
805(defvar YaTeX-TeX-token-regexp
806  (cond (YaTeX-japan "[A-Za-z*��-��-�]+")
807	(t "[A-Za-z*]+"))
808  "Regexp of characters which can be a member of TeX command's name.")
809(defvar YaTeX-kanji-regexp "[��-��-�]"
810  "Generic regexp of Japanese Kanji (and symbol) characters.")
811(defvar YaTeX-command-token-regexp YaTeX-TeX-token-regexp
812  "Regexp of characters which can be a member of current mark up language's command name.")
813
814;;(defvar YaTeX-struct-section
815;;  (concat YaTeX-ec "%1{%2}")
816;;  "Keyword to make section.")
817
818;;;
819;; autoload section
820;;;
821
822;;autoload from yatexprc.el
823(autoload 'YaTeX-visit-main "yatexprc" "Visit main LaTeX file." t)
824(autoload 'YaTeX-visit-main-other-window "yatexprc"
825  "Visit main other window." t)
826(autoload 'YaTeX-main-file-p "yatexprc" "Check if the file is main." t)
827(autoload 'YaTeX-get-builtin "yatexprc" "Get %# built-in." t)
828(autoload 'YaTeX-system "yatexprc" "Call system command" t)
829(autoload 'YaTeX-save-buffers "yatexprc" "Save buffers of same major mode" t)
830(autoload 'YaTeX-goto-corresponding-viewer "yatexprc" "Viewer jump line" t)
831
832;;autoload from yatexmth.el
833(autoload 'YaTeX-math-insert-sequence "yatexmth" "Image input." t)
834(autoload 'YaTeX-in-math-mode-p "yatexmth" "Check if in math-env." t)
835(autoload 'YaTeX-toggle-math-mode "yatexmth" "YaTeX math-mode interfaces." t)
836(autoload 'YaTeX-math-member-p "yatexmth" "Check if a word is math command." t)
837(autoload 'YaTeX-insert-amsparens-region "yatexmth" "AMS parens region" t)
838(autoload 'YaTeX-insert-amsbraces-region "yatexmth" "AMS braces region" t)
839(autoload 'YaTeX-insert-amsbrackets-region "yatexmth" "AMS brackets region" t)
840(autoload 'YaTeX-on-parenthesis-p "yatexmth" "Check if on math-parens" t)
841(autoload 'YaTeX-goto-open-paren "yatexmth" "Goto opening paren" t)
842(autoload 'YaTeX-change-parentheses "yatexmth" "Change corresponding parens" t)
843(autoload 'YaTeX-goto-corresponding-paren "yatexmth" "\bigl\bigr jumps" t)
844(autoload 'YaTeX-typeset-math-region "yatexmth" "Typeset math-region" t)
845
846;;autoload from yatexhlp.el
847(autoload 'YaTeX-help "yatexhlp" "YaTeX helper with LaTeX commands." t)
848(autoload 'YaTeX-apropos "yatexhlp" "Apropos for (La)TeX commands." t)
849
850;;autoload from yatexgen.el
851(autoload 'YaTeX-generate "yatexgen" "YaTeX add-in function generator." t)
852(autoload 'YaTeX-generate-simple "yatexgen" "YaTeX add-in support." t)
853
854;;autoload from yatexsec.el
855(autoload 'YaTeX-section-overview "yatexsec" "YaTeX sectioning(view)" t)
856(autoload 'YaTeX-read-section-in-minibuffer "yatexsec" "YaTeX sectioning" t)
857(autoload 'YaTeX-make-section-with-overview "yatexsec" "YaTeX sectioning" t)
858
859;;autoload from yatexenv.el
860(autoload 'YaTeX-what-column "yatexenv" "YaTeX env. specific funcs" t)
861(autoload 'YaTeX-intelligent-newline "yatexenv" "YaTeX env. specific funcs" t)
862(autoload 'YaTeX-indent-line-equation "yatexenv" "Indent equation lines." t)
863(autoload 'YaTeX-goto-corresponding-leftright "yatexenv" "\left\right jumps" t)
864
865;;autoload from yatexhie.el
866(autoload 'YaTeX-display-hierarchy "yatexhie"
867  "YaTeX document hierarchy browser" t)
868(autoload 'YaTeX-display-hierarchy-directly "yatexhie"
869  "Same as YaTeX-display-hierarchy.  Call from mouse." t)
870
871;;autoload from yatexpkg.el
872(autoload 'YaTeX-package-auto-usepackage "yatexpkg" "Auto \\usepackage" t)
873
874;;autoload from yatexflt.el
875(autoload 'YaTeX-filter-goto-source "yatexflt" "Go to graphic source file" t)
876
877;;;
878;; YaTeX-mode functions
879;;;
880(defun YaTeX-insert-begin-end (env region-mode)
881  "Insert \\begin{mode-name} and \\end{mode-name}.
882This works also for other defined begin/end tokens to define the structure."
883  (setq YaTeX-current-completion-type 'begin)
884  (let*((ccol (current-column)) beg beg2 exchange
885	(arg region-mode)		;for old compatibility
886	(indent-column (+ ccol YaTeX-environment-indent))(i 1) func)
887    (if (and region-mode (> (point) (mark)))
888	(progn (exchange-point-and-mark)
889	       (setq exchange t
890		     ccol (current-column)
891		     indent-column (+ ccol YaTeX-environment-indent))))
892    ;;VER2 (insert "\\begin{" env "}" (YaTeX-addin env))
893    (setq beg (point))
894    (YaTeX-insert-struc 'begin env)
895    (setq beg2 (point))
896    (insert "\n")
897    (indent-to indent-column)
898    (save-excursion
899      ;;indent optional argument of \begin{env}, if any
900      (while (> (point-beginning-of-line) beg)
901	(skip-chars-forward "\\s " (point-end-of-line))
902	(indent-to indent-column)
903	(forward-line -1)))
904    (require 'yatexenv)
905    (if region-mode
906	  ;;if region-mode, indent all text in the region
907	(save-excursion
908	  (if (fboundp (intern-soft (concat "YaTeX-enclose-" env)))
909	      (funcall (intern-soft (concat "YaTeX-enclose-" env))
910		       (point) (mark))
911	    (while (< (progn (forward-line 1) (point)) (mark))
912	      (if (eolp) nil
913		(skip-chars-forward " \t\n")
914		(indent-to indent-column))))))
915    (if region-mode (exchange-point-and-mark))
916    (indent-to ccol)
917    ;;VER2 (insert "\\end{" env "}\n")
918    (YaTeX-insert-struc 'end env)
919    (YaTeX-reindent ccol)
920    (if region-mode
921	(progn
922	  (insert "\n")
923	  (or exchange (exchange-point-and-mark)))
924      (goto-char beg2)
925      (YaTeX-intelligent-newline nil)
926      (if (fboundp (intern-soft (concat "YaTeX-intelligent-newline-" env)))
927	  (progn
928	    (message
929	     (cond
930	      (YaTeX-japan "%s �Ŏ��̍s�̓��͂ɐi�݂܂��B")
931	      (t "`%s' produces the next line's template."))
932	     (key-description
933	      (car (where-is-internal 'YaTeX-intelligent-newline))))))
934      (YaTeX-indent-line))
935    (YaTeX-package-auto-usepackage env 'env)
936    (if YaTeX-current-position-register
937	(point-to-register YaTeX-current-position-register))))
938
939(defun YaTeX-make-begin-end (arg)
940  "Make LaTeX environment command of \\begin{env.} ... \\end{env.}
941by completing read.
942 If you invoke this command with universal argument,
943\(key binding for universal-argument is \\[universal-argument]\)
944you can put REGION into that environment between \\begin and \\end.
945If the environment name begins with `.'(dot),
946that environment will be treated as `special environment', which
947enables special feature such as text conversion."
948  (interactive "P")
949  (let*
950      ((region-p (or arg (YaTeX-region-active-p)))
951       (mode (if region-p " region" ""))
952       (env
953	(save-excursion		;for Emacs24 work-around to avoid point warp
954	  (YaTeX-read-environment
955	   (format "Begin environment%s(default %s): " mode YaTeX-env-name))))
956       special)
957    (if (string= env "")
958	(setq env YaTeX-env-name))
959    (setq special (assoc env YaTeX-filter-special-env-alist)
960	  YaTeX-env-name env)
961    (YaTeX-update-table
962     (list YaTeX-env-name) 'env-table 'user-env-table 'tmp-env-table)
963    (if special
964	(YaTeX-insert-filter-special YaTeX-env-name (cdr special) region-p)
965      (YaTeX-insert-begin-end YaTeX-env-name region-p))))
966
967(defun YaTeX-make-begin-end-region ()
968  "Call YaTeX-make-begin-end with ARG to specify region mode."
969  (interactive)
970  (YaTeX-make-begin-end t))
971
972(defun YaTeX-guess-section-type ()
973  (if (eq major-mode 'yatex-mode)
974      (save-excursion
975	(cond
976	 ((save-excursion (not (search-backward YaTeX-ec nil t)))
977	  (if YaTeX-use-LaTeX2e "documentclass" "documentstyle"))
978	 ((progn
979	    (if (= (char-after (1- (point))) ?~) (forward-char -1))
980	    (forward-char -1) (looking-at "�\\\|�}\\|��\\|��"))
981	  "ref")
982	 ((and (looking-at "[a-z \t]")
983	       (progn (skip-chars-backward "a-z \t")
984		      (looking-at "table\\|figure\\|formula\\|eq\\(\\.\\|uation\\)")))
985	  "ref")
986	 ((save-excursion
987	    (skip-chars-backward "[^�A-��]")
988	    (looking-at "�v���O����\\|���X�g"))
989	  "ref")
990	 ((YaTeX-re-search-active-backward
991	   (concat YaTeX-ec-regexp "begin{\\([^}]+\\)}")
992	   (regexp-quote YaTeX-comment-prefix)
993	   (save-excursion (forward-line -1) (point))
994	   t)
995	  (let ((env (YaTeX-match-string 1)))
996	    (cdr (assoc env
997			'(("table" . "caption"))))))
998	 ))))
999
1000(defun YaTeX-make-section (arg &optional beg end cmd)
1001  "Make LaTeX \\section{} type command with completing read.
1002With numeric ARG, you can specify the number of arguments of
1003LaTeX command.
1004  For example, if you want to produce LaTeX command
1005
1006	\\addtolength{\\topmargin}{8mm}
1007
1008which has two arguments.  You can produce that sequence by typing...
1009	ESC 2 C-c s add SPC RET \\topm SPC RET 8mm RET
1010\(by default\)
1011Then yatex will automatically complete `addtolength' with two arguments
1012next time.
1013  You can complete symbol at LaTeX command and the 1st argument.
1014
1015If the optional 2nd and 3rd argument BEG END are specified, enclose
1016the region from BEG to END into the first argument of the LaTeX sequence.
1017Optional 4th arg CMD is LaTeX command name, for non-interactive use."
1018  (interactive "P")
1019  (setq YaTeX-current-completion-type 'section)
1020  (if (or (equal arg '(4)) (YaTeX-region-active-p))
1021      (setq beg (region-beginning) end (region-end)))
1022  (unwind-protect
1023      (let*
1024	  ((source-window (selected-window))
1025	   guess
1026	   (section
1027	    (or cmd
1028		(progn
1029		  (setq guess
1030			(or (YaTeX-guess-section-type) YaTeX-section-name))
1031		  (YaTeX-read-section
1032		   (if YaTeX-simple-messages
1033		       (format "Section-type (default %s): " guess)
1034		     (if (> (minibuffer-depth) 0)
1035			 (format "%s???{} (default %s)%s: "
1036				 YaTeX-ec guess
1037				 (format "[level:%d]" (minibuffer-depth)))
1038		       (format "(C-v for view-section) %s???{%s} (default %s): "
1039			       YaTeX-ec (if beg "region" "") guess)))
1040		   nil))))
1041	   (section (if (string= section "") guess section))
1042	   (numarg	;; The number of section-type command's argument
1043	    (or (and (numberp arg) arg)
1044		(nth 1 (YaTeX-lookup-table section 'section))
1045		1))
1046	   (arg-reader (intern-soft (concat "YaTeX::" section)))
1047	   (addin-args (and arg-reader (fboundp arg-reader)))
1048	   (title "")
1049	   (j 1)
1050	   (after-change-functions nil)	;inhibit font-locking temporarily
1051	   (enable-recursive-minibuffers t)
1052	   (mkarg-func
1053	    (function
1054	     (lambda (n)
1055	       (while (<= j n)
1056		 (unwind-protect
1057		     (setq title
1058			   (cond
1059			    (addin-args (funcall arg-reader j))
1060			    (YaTeX-skip-default-reader "")
1061			    (t
1062			     (read-string-with-history
1063			      (format "Argument %d of %s: " j section)))))
1064		   (insert
1065		    (concat		;to allow nil return value
1066		     "{" title "}")))
1067		 (setq j (1+ j))))))
1068	   );;let
1069	(setq YaTeX-section-name section)
1070	(if beg
1071	    (let*((e (make-marker))
1072		  (ar2 (intern-soft (concat "YaTeX::" section "-region")))
1073		  (arp (and ar2 (fboundp ar2))))
1074	      (goto-char end)
1075	      (insert "}")
1076	      (set-marker e (point))
1077	      (goto-char beg)
1078	      (unwind-protect
1079		  (progn
1080		    (insert YaTeX-ec YaTeX-section-name
1081			    (YaTeX-addin YaTeX-section-name))
1082		    (if (> numarg 1) (funcall mkarg-func (1- numarg))))
1083		(insert "{"))
1084	      (if arp (funcall ar2 (point) e))
1085	      (goto-char e)
1086	      (set-marker e nil))
1087	  (use-global-map YaTeX-recursive-map)
1088	  (if (= numarg 0) (YaTeX-make-singlecmd YaTeX-section-name)
1089	    (progn (insert YaTeX-ec YaTeX-section-name)
1090		   (insert (YaTeX-addin YaTeX-section-name))))
1091	  ;;read arguments with add-in
1092	  (funcall mkarg-func numarg))
1093	(YaTeX-update-table
1094	 (if (/= numarg 1) (list section numarg)
1095	   (list section))
1096	 'section-table 'user-section-table 'tmp-section-table)
1097	(if YaTeX-current-position-register
1098	    (point-to-register YaTeX-current-position-register))
1099	(if (string= (YaTeX-buffer-substring (- (point) 2) (point))
1100		     "{}")
1101	    (forward-char -1))
1102	(while (string= (YaTeX-buffer-substring (- (point) 3) (1- (point)))
1103			"{}")
1104	  (forward-char -2))
1105	(YaTeX-package-auto-usepackage section 'section))
1106    (if (<= (minibuffer-depth) 0) (use-global-map global-map))
1107    (insert "")))		;insert dummy string to fontify(Emacs20)
1108
1109(defun YaTeX-make-section-region (args beg end)
1110  "Call YaTeX-make-section with arguments to specify region mode."
1111 (interactive "P\nr")
1112 (YaTeX-make-section args beg end))
1113
1114(defun YaTeX-make-fontsize (arg &optional fontsize)
1115  "Make completion like {\\large ...} or {\\slant ...} in minibuffer.
1116If you invoke this command with universal argument, you can put region
1117into {\\xxx } braces.
1118\(key binding for universal-argument is \\[universal-argument]\)"
1119  (interactive "P")
1120  (YaTeX-sync-local-table 'tmp-fontsize-table)
1121  (let* ((region-p (if (or arg (YaTeX-region-active-p))
1122		       (cons (region-beginning) (region-end))))
1123	 (mode (if region-p "region" ""))
1124	 (fontsize
1125	  (or fontsize
1126	      (YaTeX-read-fontsize
1127	       (if YaTeX-simple-messages
1128		   (format "Font or size (default %s): " YaTeX-fontsize-name)
1129		 (format "{\\??? %s} (default %s)%s: " mode YaTeX-fontsize-name
1130			 (if (> (minibuffer-depth) 0)
1131			     (format "[level:%d]" (minibuffer-depth)) "")))
1132	       nil nil))))
1133    (if (string= fontsize "")
1134	(setq fontsize YaTeX-fontsize-name))
1135    (setq YaTeX-current-completion-type 'large)
1136    (setq YaTeX-fontsize-name fontsize)
1137    (YaTeX-update-table
1138     (list YaTeX-fontsize-name)
1139     'fontsize-table 'user-fontsize-table 'tmp-fontsize-table)
1140    (and YaTeX-use-LaTeX2e
1141	 (YaTeX-latex2e-p)
1142	 (setq fontsize
1143	       (cdr (assoc YaTeX-fontsize-name LaTeX2e-fontstyle-alist)))
1144	 (setq YaTeX-fontsize-name fontsize))
1145    (if region-p
1146	(let ((b (car region-p))
1147	      (e (set-marker (make-marker) (cdr region-p))))
1148	  (goto-char b)
1149	  (insert "{\\" YaTeX-fontsize-name " ")
1150 	  (goto-char e)
1151	  (insert "}")
1152	  (set-marker e nil))
1153      (insert (concat "{\\" YaTeX-fontsize-name " }"))
1154      (forward-char -1)
1155      (if YaTeX-current-position-register
1156	  (point-to-register YaTeX-current-position-register))
1157      (save-excursion
1158	(insert (YaTeX-addin YaTeX-fontsize-name)))
1159      (YaTeX-package-auto-usepackage YaTeX-fontsize-name 'large))))
1160
1161(defun YaTeX-make-fontsize-region ()
1162  "Call function:YaTeX-make-fontsize with ARG to specify region mode."
1163  (interactive)
1164  (YaTeX-make-fontsize t))
1165
1166(defvar YaTeX-singlecmd-suffix "" "*Suffix for maketitle-type commands.")
1167(defvar YaTeX-read-singlecmd-history nil "Holds maketitle-type history.")
1168(put 'YaTeX-read-singlecmd-history 'no-default t)
1169(defun YaTeX-make-singlecmd (single)
1170  (interactive
1171   (list (YaTeX-cplread-with-learning
1172	  (if YaTeX-simple-messages
1173	      (format "maketitle-type (default %s): " YaTeX-single-command)
1174	    (format "%s??? (default %s)%s: " YaTeX-ec YaTeX-single-command
1175		    (if (> (minibuffer-depth) 0)
1176			(format "[level:%d]" (minibuffer-depth)) "")))
1177	  'singlecmd-table 'user-singlecmd-table 'tmp-singlecmd-table
1178	  nil nil nil 'YaTeX-read-singlecmd-history)))
1179  (if (string= single "")
1180      (setq single YaTeX-single-command))
1181  (setq YaTeX-single-command single)
1182  (setq YaTeX-current-completion-type 'maketitle)
1183  (let ((dollar (and (not (YaTeX-in-math-mode-p))
1184		     (YaTeX-math-member-p YaTeX-single-command)))
1185	p q)
1186    (if dollar (insert "$"))
1187    (insert YaTeX-ec YaTeX-single-command)
1188    (setq p (point))
1189    (insert (YaTeX-addin single) YaTeX-singlecmd-suffix)
1190    (if dollar (insert "$"))
1191    (setq q (point))
1192    (goto-char p)
1193    (forward-char -2)
1194    (if (looking-at "\\[\\]") (forward-char 1) (goto-char q)))
1195  (YaTeX-package-auto-usepackage YaTeX-single-command 'maketitle)
1196  (if YaTeX-current-position-register
1197      (point-to-register YaTeX-current-position-register)))
1198
1199(defvar YaTeX-completion-begin-regexp "[{\\]"
1200  "Regular expression of limit where LaTeX command's completion begins.")
1201
1202(defun YaTeX-do-completion ()
1203  "Try completion on LaTeX command preceding point."
1204  (interactive)
1205  (if
1206      (or (eq (preceding-char) ? )
1207	  (eq (preceding-char) ?\t)
1208	  (eq (preceding-char) ?\n)
1209	  (bobp))
1210      (message "Nothing to complete.")   ;Do not complete
1211    (let* ((end (point))
1212	   (limit (point-beginning-of-line))
1213	   (completion-begin
1214	    (progn (re-search-backward "[ \t\n]" limit 1) (point)))
1215	   (begin (progn
1216		    (goto-char end)
1217		    (if (re-search-backward YaTeX-completion-begin-regexp
1218					    completion-begin t)
1219			(1+ (point))
1220		      nil))))
1221      (goto-char end)
1222      (cond
1223       ((null begin)
1224	(message "I think it is not a LaTeX sequence."))
1225       (t
1226	(mapcar 'YaTeX-sync-local-table
1227		'(tmp-section-table tmp-env-table tmp-singlecmd-table))
1228	(let*((pattern (YaTeX-buffer-substring begin end))
1229	      (all-table
1230	       (append
1231		section-table user-section-table tmp-section-table
1232		env-table     user-env-table     tmp-env-table
1233		singlecmd-table user-singlecmd-table tmp-singlecmd-table))
1234	      ;; First,
1235	      ;; search completion without backslash.
1236	      (completion (try-completion pattern all-table)))
1237	  (if
1238	      (eq completion nil)
1239	      ;; Next,
1240	      ;; search completion with backslash
1241	      (setq completion
1242		    (try-completion
1243		     (YaTeX-buffer-substring (1- begin) end)
1244		     all-table nil)
1245		    begin (1- begin)))
1246	  (cond
1247	   ((null completion)
1248	    (message (concat "Can't find completion for '" pattern "'"))
1249	    (ding))
1250	   ((eq completion t) (message "Sole completion."))
1251	   ((not (string= completion pattern))
1252	    (delete-region begin end)
1253	    (insert completion)
1254	    )
1255	   (t
1256	    (message "Making completion list...")
1257	    (with-output-to-temp-buffer "*Help*"
1258	      (display-completion-list
1259	       (all-completions pattern all-table)))))))))))
1260
1261(defun YaTeX-toggle-modify-mode (&optional arg)
1262  (interactive "P")
1263  (or (memq 'YaTeX-modify-mode mode-line-format)
1264      (setq mode-line-format
1265	    (append (list "" 'YaTeX-modify-mode) mode-line-format)))
1266  (if (or arg (null YaTeX-modify-mode))
1267      (progn
1268	(setq YaTeX-modify-mode "*m*")
1269	(message "Modify mode"))
1270    (setq YaTeX-modify-mode nil)
1271    (message "Cancel modify mode."))
1272  (set-buffer-modified-p (buffer-modified-p)))	;redraw mode-line
1273
1274(defun YaTeX-switch-mode-menu (arg &optional char)
1275  (interactive "P")
1276  (message "Toggle: (M)odify-mode ma(T)h-mode")
1277  (let ((c (or char (read-char))))
1278    (cond
1279     ((= c ?m) (YaTeX-toggle-modify-mode arg))
1280     ((or (= c ?$) (= c ?t))
1281      (if YaTeX-auto-math-mode
1282	  (message "Makes no sense in YaTeX-auto-math-mode.")
1283	(YaTeX-toggle-math-mode arg))))))
1284
1285(defun YaTeX-insert-quote ()
1286  (interactive)
1287  (insert
1288   (cond
1289    ((YaTeX-literal-p) ?\")
1290    ((= (preceding-char) ?\\ ) ?\")
1291    ;((= (preceding-char) ?\( ) ?\")
1292    ((save-excursion (beginning-of-line)
1293		     (skip-chars-forward "\t ")
1294		     (looking-at "%#"))
1295     ?\")
1296    ((let ((ovl (overlays-at (point))))
1297       (and ovl
1298	    (catch 'found
1299	      (while ovl
1300		(if (overlay-get (car ovl) 'filter-input) (throw 'found t))
1301		(setq ovl (cdr ovl))))))
1302     ?\")
1303    ((or (= (preceding-char) 32)
1304	 (= (preceding-char) 9)
1305	 (= (preceding-char) ?\n)
1306	 (bobp)
1307	 (string-match
1308	  (regexp-quote (char-to-string (preceding-char)))
1309	  "ABCDHIuvwxyz()"))
1310     "``")
1311    (t  "''"))))
1312
1313(defun YaTeX-closable-p ()
1314  (and (not YaTeX-modify-mode)
1315       (not (eq YaTeX-close-paren-always 'never))
1316       (or YaTeX-close-paren-always (eolp))
1317       (not (input-pending-p))
1318       (not (YaTeX-literal-p)))
1319  ;;(or YaTeX-modify-mode
1320  ;;    (and (not YaTeX-close-paren-always) (not (eolp)))
1321  ;;    (input-pending-p)
1322  ;;    (YaTeX-quick-in-environment-p "verbatim"))
1323  )
1324
1325(defun YaTeX-insert-braces-region (beg end &optional open close)
1326  (interactive "r")
1327  (save-excursion
1328    (goto-char end)
1329    (YaTeX-insert-inherit (or close "}"))
1330    (goto-char beg)
1331    (YaTeX-insert-inherit (or open "{"))))
1332
1333(defun YaTeX-get-macro-at-point (&optional p)
1334  "Get (La)TeX macro around point P."
1335  (interactive "d")
1336  (save-excursion
1337    (goto-char (setq p (or p (point))))
1338    (let ((token (substring (substring YaTeX-TeX-token-regexp 1) 0 -2))
1339	  bsend)
1340      (and (not (bobp))
1341	   (or (looking-at YaTeX-TeX-token-regexp)
1342	       (string-match
1343		YaTeX-TeX-token-regexp (char-to-string (preceding-char))))
1344	   (progn
1345	     (skip-chars-backward token)
1346	     (equal (preceding-char) ?\\))
1347	   (save-excursion
1348	     (setq bsend (point))
1349	     (skip-chars-backward "\\\\") ;emacs18 doesn't return distance
1350	     (/= (% (- bsend (point)) 2) 0)) ;consider \\
1351	   (looking-at YaTeX-TeX-token-regexp)
1352	   (YaTeX-match-string 0)))))
1353
1354(defun YaTeX-insert-braces (arg &optional open close)
1355  (interactive "p")
1356  (let ((begend-guide
1357	 (function
1358	  (lambda ()
1359	    (if (equal (get 'YaTeX-insert-braces 'begend-guide) 2)
1360		nil			;if triggered thrice, do nothing
1361	      (momentary-string-display
1362	       (format
1363		(cond
1364		 (YaTeX-japan "begin/end���͂ɂ� %s ���g���܂��傤")
1365		 (t "You don't understand Zen of `%s'!"))
1366		(key-description
1367		 (car (where-is-internal 'YaTeX-make-begin-end))))
1368	       (point))
1369	      (put 'YaTeX-insert-braces 'begend-guide
1370		   (+ 1 (YaTeX-str2int ;increment counter of beg-end guidance
1371			 (prin1-to-string
1372			  (get 'YaTeX-insert-braces 'begend-guide)))))))))
1373	env macro not-literal b e)
1374    (cond
1375     ((YaTeX-region-active-p)
1376      (YaTeX-insert-braces-region (region-beginning) (region-end)))
1377     ((YaTeX-jmode) (YaTeX-self-insert arg))
1378     ((not (YaTeX-closable-p)) (YaTeX-self-insert arg))
1379     ((save-excursion
1380	(and (> (- (point) (point-min)) 6)
1381	     (condition-case () (forward-char -6) (error nil)))
1382	(looking-at "\\\\left\\\\"))
1383      (insert "{\\right\\}")
1384      (forward-char -8))
1385     ((save-excursion			;from matsu<at>math.s.chiba-u.ac.jp
1386	(and (> (- (point) (point-min)) 6) (forward-char -6))
1387	(looking-at "\\\\[bB]igl\\\\"))
1388      (insert
1389       (concat
1390	"{" (buffer-substring (match-beginning 0) (- (match-end 0) 2)) "r\\}"))
1391      (forward-char -7))
1392     ((save-excursion
1393	(and (> (- (point) (point-min)) 7)
1394	     (condition-case () (forward-char -7) (error nil)))
1395	(looking-at "\\\\[bB]iggl\\\\"))
1396      (insert
1397       (concat
1398	"{" (buffer-substring (match-beginning 0) (- (match-end 0) 2)) "r\\}"))
1399      (forward-char -8))
1400     ((= (preceding-char) ?\\ )
1401      (insert "{\\}")
1402      (forward-char -2))		;matsu's hack ends here
1403     ((and (setq not-literal (not (YaTeX-literal-p)))
1404	   (equal "end" (setq macro (YaTeX-get-macro-at-point)))
1405	   (setq env (YaTeX-inner-environment)))
1406      (funcall begend-guide)
1407      (insert "{" env "}"))
1408     ((and not-literal (equal "begin" macro))
1409      (insert "{")
1410      (save-excursion
1411	(indent-to (prog1 (- (current-column) 7) (insert "}\n")))
1412	(insert "\\end{}")
1413	(setq e (point)))
1414      (setq env
1415	    (YaTeX-read-environment
1416	     (format "Begin environment(default %s): " YaTeX-env-name)))
1417      (if (string= "" env) (setq env YaTeX-env-name))
1418      (setq YaTeX-env-name env)
1419      (funcall begend-guide)
1420      (delete-region (- (point) 7) e)
1421      (YaTeX-insert-begin-end env nil))
1422     (t
1423      (insert (or open "{") (or close "}"))
1424      (forward-char -1)
1425      (if (and (eq (char-after (point)) ?\}) ;; the case `\\{}'
1426	       (eq (char-after (- (point) 2)) ?\\ ))
1427	  (progn (insert "\\") (forward-char -1)))
1428      ))))
1429
1430(defun YaTeX-jmode ()
1431  (or (and (boundp 'canna:*japanese-mode*) canna:*japanese-mode*)
1432      (and (boundp 'egg:*mode-on*) egg:*mode-on* egg:*input-mode*)
1433      (and (boundp 'skk-mode) skk-mode (not skk-latin-mode))
1434      (and (boundp 'default-input-method) default-input-method
1435	   current-input-method)))
1436
1437(defun YaTeX-jmode-off ()
1438  (if (cond
1439       ((and (boundp 'canna:*japanese-mode*) canna:*japanese-mode*)
1440	(canna-toggle-japanese-mode) t)
1441       ((and (boundp 'egg:*mode-on*) egg:*mode-on* egg:*input-mode*)
1442	(egg:toggle-egg-mode-on-off) t)
1443       ((and (fboundp 'skk-mode) (boundp 'skk-mode) skk-mode)
1444	(cond
1445	 ((fboundp 'skk-latin-mode)
1446	  (or (and (boundp 'skk-henkan-mode) skk-henkan-mode)
1447	      (and (boundp 'skk-henkan-on)
1448		   (or skk-henkan-mode skk-henkan-active))
1449	      (and (boundp 'j-henkan-on)
1450		   (or j-henkan-on j-henkan-active))
1451	      ;; Deactivate jmode if henkan-mode is not running.
1452	      ;; Suggested by tt.tetsuo.tsukamoto.
1453	      (progn
1454		(put 'YaTeX-jmode-on 'skkkata skk-katakana)
1455		(skk-latin-mode t))))
1456	 ((fboundp 'skk-mode-off)	(skk-mode-off))
1457	 (t (j-mode-off)))
1458	t)
1459       ((and (fboundp 'toggle-input-method) current-input-method)
1460	(toggle-input-method) t)
1461       ((and (fboundp 'fep-force-off) (fep-force-off))))
1462      (put 'YaTeX-jmode 'jmode t)))
1463
1464(defun YaTeX-jmode-on ()
1465  (cond
1466   ((boundp 'canna:*japanese-mode*)
1467    (if (not canna:*japanese-mode*) (canna-toggle-japanese-mode)))
1468   ((boundp 'egg:*mode-on*)
1469    (and (not egg:*mode-on*) (not egg:*input-mode*)
1470	 (egg:toggle-egg-mode-on-off)))
1471   ((and (fboundp 'skk-mode) (boundp 'skk-mode))
1472    (if (get 'YaTeX-jmode-on 'skkkata)
1473	(skk-j-mode-on t)
1474      (skk-mode 1))
1475    (put 'YaTeX-jmode-on 'skkkata nil))
1476   ((fboundp 'toggle-input-method)
1477    (if (not current-input-method) (toggle-input-method)))
1478   ((and (fboundp 'fep-force-on) (fep-force-on)))))
1479
1480(defun YaTeX-jmode-back ()
1481  (if (get 'YaTeX-jmode 'jmode)
1482      (YaTeX-jmode-on))
1483  (setplist 'YaTeX-jmode nil))
1484
1485(defun YaTeX-self-insert (arg)
1486  (call-interactively (global-key-binding (char-to-string (YaTeX-last-key)))))
1487(defun YaTeX-insert-inherit (&rest args)
1488  (apply (if (fboundp 'insert-and-inherit) 'insert-and-inherit 'insert)
1489	   args))
1490
1491(defun YaTeX-insert-brackets (arg)
1492  "Insert Kagi-kakko or \\ [ \\] pair or simply \[."
1493  (interactive "p")
1494  (let ((col (1- (current-column))))
1495    (cond
1496     ((YaTeX-region-active-p)
1497      (YaTeX-insert-brackets-region (region-beginning) (region-end)))
1498     ((YaTeX-jmode) (YaTeX-self-insert arg))
1499     ((not (YaTeX-closable-p))
1500      (YaTeX-self-insert arg))
1501     ((save-excursion
1502	(and (> (- (point) (point-min)) 5) (forward-char -5))
1503	(looking-at "\\\\left"))
1504      (YaTeX-insert-inherit "[\\right]")
1505      (forward-char -7))
1506     ((save-excursion			;from matsu<at>math.s.chiba-u.ac.jp
1507	(and (> (- (point) (point-min)) 5) (forward-char -5))
1508	(looking-at "\\\\[bB]igl"))
1509      (YaTeX-insert-inherit
1510       (concat
1511	"[" (buffer-substring (match-beginning 0) (- (match-end 0) 1)) "r]"))
1512      (forward-char -6))
1513     ((save-excursion
1514	(and (> (- (point) (point-min)) 6) (forward-char -6))
1515	(looking-at "\\\\[bB]iggl"))
1516      (YaTeX-insert-inherit
1517       (concat
1518	"[" (buffer-substring (match-beginning 0) (- (match-end 0) 1)) "r]"))
1519      (forward-char -7))		;matsu's hack ends here
1520     ((and (= (preceding-char) ?\\ )
1521	   (/= (char-after (- (point) 2)) ?\\ )
1522	   (not (YaTeX-in-math-mode-p)))
1523      (YaTeX-insert-inherit (YaTeX-last-key) "\n")
1524      (indent-to (max 0 col))
1525      (YaTeX-insert-inherit "\\]")
1526      (beginning-of-line)
1527      (open-line 1)
1528      (delete-region (point) (progn (beginning-of-line) (point)))
1529      (indent-to (+ YaTeX-environment-indent (max 0 col)))
1530      (or YaTeX-auto-math-mode YaTeX-math-mode (YaTeX-toggle-math-mode 1)))
1531     ((YaTeX-closable-p)
1532      (YaTeX-insert-inherit "[]")
1533      (backward-char 1))
1534     (t (YaTeX-self-insert arg)))))
1535
1536(defun YaTeX-insert-brackets-region (beg end)
1537  (interactive "r")
1538  (YaTeX-insert-braces-region beg end "[" "]"))
1539
1540(defun YaTeX-insert-parens (arg)
1541  "Insert parenthesis pair."
1542  (interactive "p")
1543  (cond
1544   ((YaTeX-region-active-p)
1545    (YaTeX-insert-parens-region (region-beginning) (region-end)))
1546   ((YaTeX-jmode) (YaTeX-self-insert arg))
1547   ((not (YaTeX-closable-p)) (YaTeX-self-insert arg))
1548   ((save-excursion
1549      (and (> (- (point) (point-min)) 5) (forward-char -5))
1550      (looking-at "\\\\left"))
1551    (YaTeX-insert-inherit "(\\right)")
1552    (forward-char -7))
1553   ((save-excursion			;from matsu<at>math.s.chiba-u.ac.jp
1554      (and (> (- (point) (point-min)) 5) (forward-char -5))
1555      (looking-at "\\\\[bB]igl"))
1556    (YaTeX-insert-inherit
1557     (concat
1558      "(" (buffer-substring (match-beginning 0) (- (match-end 0) 1)) "r)"))
1559     (forward-char -6))
1560   ((save-excursion
1561      (and (> (- (point) (point-min)) 6) (forward-char -6))
1562      (looking-at "\\\\[bB]iggl"))
1563    (YaTeX-insert-inherit
1564     (concat
1565      "(" (buffer-substring (match-beginning 0) (- (match-end 0) 1)) "r)"))
1566     (forward-char -7))
1567   ((= (preceding-char) ?\\ )		;matsu's hack ends here
1568    (YaTeX-insert-inherit "(\\)")
1569    (backward-char 2))
1570   ((YaTeX-closable-p)
1571    (YaTeX-insert-inherit "()")
1572    (backward-char 1))
1573   (t (YaTeX-self-insert arg))))
1574
1575(defun YaTeX-insert-parens-region (beg end)
1576  (interactive "r")
1577  (YaTeX-insert-braces-region beg end "(" ")"))
1578
1579(defun YaTeX-insert-bar (arg)
1580  "Insert bar pair."
1581  (interactive "p")
1582  (cond
1583   ((YaTeX-jmode) (YaTeX-self-insert arg))
1584   ((not (YaTeX-closable-p)) (YaTeX-self-insert arg))
1585   ((save-excursion
1586      (and (> (- (point) (point-min)) 5) (forward-char -5))
1587      (looking-at "\\\\left"))
1588    (YaTeX-insert-inherit "|\\right|")
1589    (forward-char -7))
1590   ((save-excursion			;from matsu<at>math.s.chiba-u.ac.jp
1591      (and (> (- (point) (point-min)) 5) (forward-char -5))
1592      (looking-at "\\\\[bB]igl"))
1593    (insert
1594     (concat
1595      "|" (buffer-substring (match-beginning 0) (- (match-end 0) 1)) "r|"))
1596     (forward-char -6))
1597   ((save-excursion
1598      (and (> (- (point) (point-min)) 6) (forward-char -6))
1599      (looking-at "\\\\[bB]iggl"))
1600    (insert
1601     (concat
1602      "|" (buffer-substring (match-beginning 0) (- (match-end 0) 1)) "r|"))
1603     (forward-char -7))
1604   ((save-excursion		; added by Jin <MAF01011<at>nifty.ne.jp>
1605      (and (> (- (point) (point-min)) 6) (forward-char -6))
1606      (looking-at "\\\\left\\\\"))
1607    (YaTeX-insert-inherit "|\\right\\|")
1608    (forward-char -8))
1609   ((save-excursion
1610      (and (> (- (point) (point-min)) 6) (forward-char -6))
1611      (looking-at "\\\\[bB]igl\\\\"))
1612    (insert
1613     (concat
1614      "|" (buffer-substring (match-beginning 0) (- (match-end 0) 2)) "r\\|"))
1615     (forward-char -7))
1616   ((save-excursion
1617      (and (> (- (point) (point-min)) 7) (forward-char -7))
1618      (looking-at "\\\\[bB]iggl\\\\"))
1619    (insert
1620     (concat
1621      "|" (buffer-substring (match-beginning 0) (- (match-end 0) 2)) "r\\|"))
1622     (forward-char -8))		; added by Jin up to here.
1623   ((= (preceding-char) ?\\ )
1624    (YaTeX-insert-inherit "|\\|")
1625    (backward-char 2))
1626;   ((and (YaTeX-closable-p)
1627;	 (/= (preceding-char) ?|)
1628;	 (/= (following-char) ?|))
1629;    (YaTeX-insert-inherit "||")
1630;    (backward-char 1))
1631   (t (YaTeX-self-insert arg))))
1632
1633(defvar YaTeX-use-jmode-hook
1634  (and (featurep 'canna) (boundp 'canna:*initialized*) canna:*initialized*)
1635  ;; (not (and (fboundp 'skk-mode) (boundp 'skk-mode)))
1636  "*Non-nil means activate automatic jmode switcher within/out math mode.
1637Hopefully, change default to t in the next version of 1.75.")
1638(defun YaTeX-jmode-hook (old new)
1639  "A hook controling jmode on/off."
1640  ;; This function is called via point-entered/leave hook, so that
1641  ;; codes in it is evaluated on such emacsen as having text-properties.
1642  (let ((inhibit-point-motion-hooks t)
1643	(oldp (plist-get (text-properties-at old) 'point-left))
1644	(newp (plist-get (text-properties-at new) 'point-left))
1645	(lnew (plist-get (text-properties-at new) 'last-new))
1646	(mjmode (plist-get (text-properties-at new) 'mjmode))
1647	(bmp (buffer-modified-p))
1648	(jm (YaTeX-jmode)) b e)
1649    (unwind-protect
1650	(cond
1651	 ((eq lnew new) nil)		;Do nothing if continuous entry
1652	 ((and (not (eq newp 'YaTeX-jmode-hook))
1653	       (eq oldp 'YaTeX-jmode-hook)
1654	       (plist-get (text-properties-at old) 'entered))
1655	  ;; leave
1656	  (remove-text-properties
1657	   (setq b (1+ (or (previous-single-property-change old 'point-left)
1658			   (1- (point)))))
1659	   (setq e (1- (or (next-single-property-change old 'point-left)
1660			   (1+ (point)))))
1661	   (list 'last-new nil 'entered nil))
1662	  (add-text-properties b e (list 'mjmode jm))
1663	  (if (boundp 'skk-katakana)
1664	      (put 'YaTeX-jmode-on 'skkkata skk-katakana))
1665	  (if (plist-get (text-properties-at old) 'jmode)
1666	      (YaTeX-jmode-on)))
1667	 ((and (not (eq oldp 'YaTeX-jmode-hook))
1668	       (eq newp 'YaTeX-jmode-hook)
1669	       (not (plist-get (text-properties-at new) 'entered)))
1670	  ;; enter
1671	  (add-text-properties
1672	   (1+ (or (previous-single-property-change new 'point-left)
1673		   (1- (point))))
1674	   (1- (or (next-single-property-change new 'point-left)
1675		   (1+ (point))))
1676	   (list 'jmode jm 'last-new new 'entered t))
1677	  (if (boundp 'skk-katakana)	;care for skk katakana mode
1678	      (put 'YaTeX-jmode-on 'skkkata skk-katakana))
1679	  (if mjmode (YaTeX-jmode-on) (YaTeX-jmode-off))))
1680      ;;unwind job
1681      (set-buffer-modified-p bmp))))
1682
1683(defun YaTeX-insert-dollar ()
1684  (interactive)
1685  (if (or (not (YaTeX-closable-p))
1686	  (= (preceding-char) 92)
1687	  (and (YaTeX-in-math-mode-p)
1688	       (or (/= (preceding-char) ?$) (/= (following-char) ?$))))
1689      (insert "$")
1690    (insert "$$")
1691    (forward-char -1)
1692    (and YaTeX-use-jmode-hook
1693	 (fboundp 'add-text-properties)
1694	 (add-text-properties
1695	  (1- (point)) (1+ (point))
1696	  (list 'point-left 'YaTeX-jmode-hook
1697		'point-entered 'YaTeX-jmode-hook
1698		'front-sticky t
1699		'rear-nonsticky t
1700		'mjmode nil
1701		'jmode (YaTeX-jmode))))
1702    (YaTeX-jmode-off)
1703    (or YaTeX-auto-math-mode YaTeX-math-mode (YaTeX-toggle-math-mode 1))))
1704
1705(defun YaTeX-insert-dollars-region (beg end)
1706  (interactive "r")
1707  (YaTeX-insert-braces-region beg end "$" "$"))
1708
1709(defun YaTeX-insert-amper ()
1710  (interactive)
1711  (if (or (string-match YaTeX-array-env-regexp
1712			(or (YaTeX-inner-environment t) "document"))
1713	  (= (preceding-char) 92)
1714	  (YaTeX-literal-p)
1715	  (YaTeX-in-math-mode-p))
1716      (insert "&")
1717    (insert "\\&")))
1718
1719(defun YaTeX-version ()
1720  "Return string of the version of running YaTeX."
1721  (interactive)
1722  (message
1723   (concat "Yet Another tex-mode "
1724	   (if YaTeX-japan "u�쒹�v" "`Wild Bird'")
1725	   " Revision "
1726	   YaTeX-revision-number)))
1727
1728(defun YaTeX-typeset-menu (arg &optional char)
1729  "Typeset, preview, visit error and miscellaneous convenient menu.
1730Optional second argument CHAR is for non-interactive call from menu."
1731  (interactive "P")
1732  (message
1733   (concat "J)latex R)egion E)nv B)ibtex mk(I)dx "
1734	   "latex+p(D)f "
1735	   (if (fboundp 'start-process) "K)ill ")
1736	   "P)review "
1737	   (and (boundp 'window-system) window-system "S)earch ")
1738	   "V)iewErr L)pr"))
1739  (let ((sw (selected-window)) (c (or char (read-char))))
1740    (require 'yatexprc)			;for Nemacs's bug
1741    (select-window sw)
1742    (cond
1743     ((memq c '(?j ?\C-j)) (YaTeX-typeset-buffer) ; memq for usability test
1744      (put 'dvi2-command 'format 'dvi))
1745     ((= c ?r) (YaTeX-typeset-region))
1746     ((= c ?e) (YaTeX-typeset-environment))
1747     ((= c ?b) (YaTeX-call-builtin-on-file
1748		"BIBTEX" bibtex-command arg))
1749     ((= c ?i) (YaTeX-call-builtin-on-file
1750		"MAKEINDEX" makeindex-command arg))
1751     ((= c ?k) (YaTeX-kill-typeset-process YaTeX-typeset-process))
1752     ((= c ?p) (call-interactively 'YaTeX-preview))
1753     ((= c ?q) (YaTeX-system "lpq" "Printer queue"))
1754     ((= c ?d) (YaTeX-typeset-buffer
1755		(or (YaTeX-get-builtin "DVIPDF") YaTeX-dvipdf-command))
1756      (put 'dvi2-command 'format 'pdf))
1757     ((= c ?v) (YaTeX-view-error))
1758     ((= c ?l) (YaTeX-lpr arg))
1759     ((= c ?m) (YaTeX-switch-mode-menu arg))
1760     ((= c ?s) (YaTeX-xdvi-remote-search arg)))))
1761
1762(if (fboundp 'wrap-function-to-control-ime)
1763    (wrap-function-to-control-ime 'YaTeX-typeset-menu t "P"))
1764
1765
1766(defun YaTeX-%-menu (&optional beg end char)
1767  "Operate %# notation."
1768  ;;Do not use interactive"r" for the functions which require no mark
1769  (interactive)
1770  (message "!)Edit-%%#! D)VIPDF B)EGIN-END P)review pdf(V)iew L)PR M)akeidx b)ibtex dp(I)")
1771  (let ((c (or char (read-char))) (string "") key
1772	(b (make-marker)) (e (make-marker)))
1773    (save-excursion
1774      (cond
1775       ((rindex "!plmibdv" c)		;Edit %#xxx
1776	(setq key (cdr (assq c '((?! . "!")
1777				 (?p . "PREVIEW")
1778				 (?l . "LPR")
1779				 (?m . "MAKEINDEX")
1780				 (?d . "DVIPDF")
1781				 (?v . "PDFVIEW")
1782				 (?i . "IMAGEDPI")
1783				 (?b . "BIBTEX")))))
1784	(YaTeX-getset-builtin key t))
1785
1786       ((= c ?B)			;%#BEGIN %#END region
1787	(or end (setq beg (min (point) (mark)) end (max (point) (mark))))
1788	(set-marker b beg)
1789	(set-marker e end)
1790	(goto-char (point-min))
1791	(while (re-search-forward "^%#\\(BEGIN\\)\\|\\(END\\)$" nil t)
1792	  (beginning-of-line)
1793	  (delete-region (point) (progn (forward-line 1) (point))))
1794	(goto-char b)
1795	(open-line 1)
1796	(delete-region (point) (progn (beginning-of-line)(point)));for 19 :-<
1797	(insert "%#BEGIN")
1798	(goto-char e)
1799	(insert "%#END\n")
1800	(set-marker b nil)
1801	(set-marker e nil))))))
1802
1803(defvar YaTeX-refcommand-def-regexp-default
1804  "label\\|bibitem")
1805(defvar YaTeX-refcommand-def-regexp-private nil
1806  "*Regexp of defining label commands")
1807(defvar YaTeX-refcommand-def-regexp
1808  (concat (if YaTeX-refcommand-def-regexp-private
1809	      (concat YaTeX-refcommand-def-regexp-private "\\|"))
1810	  YaTeX-refcommand-def-regexp-default))
1811
1812(defvar YaTeX-refcommand-ref-regexp-default
1813  "\\(page\\|eq\\|fig\\)?ref\\|cite"
1814  "Regexp of LaTeX's label-referring macros.
1815Searching for this will be done without `\\\\'.
1816So you need not add patterns if new referring macro ends with \"ref\".")
1817(defvar YaTeX-refcommand-ref-regexp-private nil
1818  "*Regexp of referring label commands.
1819See documentation of `YaTeX-refcommand-ref-regexp-default'.")
1820(defvar YaTeX-refcommand-ref-regexp
1821  (concat (if YaTeX-refcommand-ref-regexp-private
1822	      (concat YaTeX-refcommand-ref-regexp-private "\\|"))
1823	  YaTeX-refcommand-ref-regexp-default))
1824
1825(defvar YaTeX-refcommand-regexp
1826  (concat YaTeX-refcommand-def-regexp
1827	  "\\|" YaTeX-refcommand-ref-regexp)
1828  "Regexp of label defining/referring command name.")
1829
1830(defun YaTeX-goto-corresponding-label (reverse &optional otherwin)
1831  "Jump to corresponding \\label{} and \\ref{} or \\cite and \\bibitem.
1832  The default search direction depends on the command at the cursor position.
1833When the cursor is on \\ref(\\cite), YaTeX will try to search the
1834corresponding \\label(\\bibitem) backward,
1835and if it fails search forward again.  And when the cursor is
1836on \\label(\\bibitem), YaTeX will search the corresponding \\ref(\\cite)
1837forward at first and secondary backward.
1838  Argument REVERSE non-nil makes the default
1839direction rule reverse.  Since Search string is automatically set in
1840search-last-string, you can repeat search the same label/ref by typing
1841\\[isearch-forward] or \\[isearch-backward].
1842  If optional second argument OTHERWIN is non-nil, move to other window."
1843
1844  (let ((scmd "") label direc string blist (p (point)) (cb (current-buffer))
1845	(refcommands YaTeX-refcommand-regexp)
1846	(foundmsg (format "Type %s %c to return to original position."
1847			  (key-description
1848			   (car
1849			    (or (where-is-internal 'register-to-point)
1850				(where-is-internal 'jump-to-register))))
1851			  YaTeX-current-position-register))
1852	(func (function (lambda (string sfunc)
1853			  (or
1854			   (funcall sfunc string nil t)
1855			   (funcall (if (eq sfunc 're-search-forward)
1856					're-search-backward 're-search-forward)
1857				    string nil t))))))
1858    (cond
1859     ((YaTeX-on-section-command-p refcommands)
1860      (setq scmd
1861	    (cdr
1862	     (assoc
1863	      (YaTeX-match-string 1)
1864	      '(("label" . "\\\\\\(page\\|eq\\)?ref{%k}")
1865		("ref" . "\\\\label{%k}")
1866		("eqref" . "\\\\label{%k}")
1867		("pageref" . "\\\\label{%k}")
1868		("cite" .
1869		 "\\\\bibitem\\(\\[[^]]+\\]\\)?{%k}\\|^\\s *@[a-z]+{%k,")
1870		("bibitem" . "\\\\cite\\(\\[[^]]+\\]\\)?")))))
1871      (goto-char (match-end 0))
1872      (let ((label (YaTeX-buffer-substring
1873		    (1- (point)) (progn (backward-list 1) (1+ (point)))))
1874	    (fp (make-marker))fl fn
1875	    (goother (function (lambda (buffer point)
1876				 (goto-char point)
1877				 (if (one-window-p)
1878				     (split-window-calculate-height
1879				      YaTeX-default-pop-window-height))
1880				 (select-window (get-lru-window))
1881				 (switch-to-buffer buffer)))))
1882	;(setq string (concat "\\" scmd "{" label "}"))
1883	;(setq string (concat "\\\\" scmd "{" (regexp-quote label) "}"))
1884	(setq string (YaTeX-replace-format scmd "k" (regexp-quote label)))
1885	(setq direc (if (string-match "ref\\|cite" scmd)
1886			're-search-forward 're-search-backward))
1887	(if YaTeX-current-position-register
1888	    (point-to-register YaTeX-current-position-register))
1889	(if reverse (setq direc (if (eq direc 're-search-forward)
1890				    're-search-backward 're-search-forward)))
1891	(if (funcall func string direc)	;label/ref found!
1892	    (progn
1893	      (if otherwin (funcall goother cb p))
1894	      (goto-char (match-beginning 0))
1895	      (push-mark p))
1896	  ;;if label/ref not found, search through all yatex buffers.
1897	  (goto-char p)			;resume position of current buffer
1898	  (catch 'found
1899	    (setq blist (YaTeX-yatex-buffer-list))
1900	    (while blist
1901	      ;; search for corresponding keyword
1902	      (set-buffer (car blist))
1903	      (if (YaTeX-on-section-command-p refcommands)
1904		  (goto-char (match-beginning 0)))
1905	      (cond
1906	       ; cond1
1907	       ((funcall func string direc)
1908		(cond
1909		 (otherwin
1910		  (set-buffer cb)
1911		  (funcall goother (car blist) p))
1912		 ((or (get-buffer-window (car blist))
1913		      (and YaTeX-emacs-19
1914			   (get-buffer-window (car blist) t)))
1915		  (goto-buffer-window (car blist)))
1916		 (t
1917		  (switch-to-buffer (car blist))
1918		  (message foundmsg)))
1919		(goto-char (match-beginning 0))
1920		(throw 'found t))
1921	       ; cond2
1922	       ((and
1923		 (string-match "bibitem" scmd)
1924		 (catch 'found2
1925		   (save-excursion
1926		     (goto-char (point-min))
1927		     (while (YaTeX-re-search-active-forward
1928			     "\\\\bibliography{\\([^}]*\\)}" "%" nil t)
1929		       (setq fl (YaTeX-split-string (YaTeX-match-string 1) ","))
1930		       (while fl
1931			 (if (or (file-exists-p (setq fn (car fl)))
1932				 (file-exists-p (setq fn (concat fn ".bib"))))
1933			     (progn
1934			       (set-buffer (find-file-noselect fn))
1935			       (save-excursion
1936				 (goto-char (point-min))
1937				 (if (YaTeX-re-search-active-forward
1938				      string "%" nil t)
1939				     (throw 'found2
1940					    (set-marker fp (point)))))))
1941			 (setq fl (cdr fl)))))))
1942		(if otherwin
1943		    (funcall goother (marker-buffer fp) fp)
1944		  (switch-to-buffer (marker-buffer fp))
1945		  (goto-char fp))
1946		(set-marker fp nil)
1947		(message foundmsg)
1948		(throw 'found t)))
1949	      (setq blist (cdr blist)))
1950	    ;; search for bibliography
1951	    )))
1952      (if YaTeX-emacs-19
1953	  (setq regexp-search-ring
1954		(cons string (delete string regexp-search-ring)))
1955	(setq search-last-regexp string)))
1956     (t nil))))
1957
1958;;YaTeX-goto-corresponding-environment was moved to yatexlib
1959
1960(defun YaTeX-goto-corresponding-file (&optional other)
1961  "Visit or switch buffer of corresponding file,
1962looking at \\input or \\include or \\includeonly or %#SRC{} on current line."
1963  (cond
1964   ((YaTeX-on-includes-p)
1965    (let ((parent buffer-file-name) input-file b)
1966      (save-excursion
1967	(if (and (re-search-forward "[{%]" (point-end-of-line) t)
1968		 (= ?{ (char-after (match-beginning 0))))
1969	    nil
1970	  (skip-chars-backward "^,{"))
1971	(setq input-file
1972	      (YaTeX-buffer-substring
1973	       (point) (progn (skip-chars-forward "^ ,}") (point))))
1974	(if (not (string-match "\\.\\(tex\\|sty\\)$" input-file))
1975	    (setq input-file (concat input-file ".tex"))))
1976      (cond
1977       (other (YaTeX-switch-to-buffer-other-window input-file))
1978       ((setq b (YaTeX-get-file-buffer input-file))
1979	(goto-buffer-window b))
1980       (t (YaTeX-switch-to-buffer input-file)))
1981      (or (YaTeX-get-builtin "!")
1982	  YaTeX-parent-file
1983	  (setq YaTeX-parent-file parent))))
1984   ;; On %#SRC{somefilters.src}
1985   ((YaTeX-on-SRC-p)
1986    (let ((src (YaTeX-match-string 1)))
1987      (if other (YaTeX-switch-to-buffer-other-window src)
1988	(goto-buffer-window (find-file-noselect src)))))))
1989
1990(defun YaTeX-goto-corresponding-BEGIN-END ()
1991  (if (not (YaTeX-on-BEGIN-END-p)) nil
1992    (if (cond
1993	 ((equal (match-beginning 0) (match-beginning 1)) ;if on %#BEGIN
1994	  (not (search-forward "%#END" nil t)))
1995	 (t ; if on %#END
1996	  (not (search-backward "%#BEGIN" nil t))))
1997	(error "Corresponding %%#BEGIN/END not found."))
1998    (beginning-of-line)
1999    t))
2000
2001(defvar YaTeX-processed-file-regexp-alist nil
2002  "Alist of regexp of processed file regexp vs. its file name part;
2003For example, if you include image file with `\\epsfile{file=FILE}' where
2004`FILE' is processed file.  You might want to view FILE with other previewer
2005such as ghostview, or want to preview its source which was drawn with
2006other drawing tool, tgif for example.  Then you should set entire regexp
2007of including expression and enclose its file name part with \\\\( and \\\\).
2008
2009 Ex. (\"\\\\\\\\epsfile{[^}]*file=\\\\([^,} ]+\\\\)\\\\(\\\\.e?ps\\\\)?[^}]*}\" 1)
2010
2011Where the first group surrounded by \\\\( and \\\\) is the file name part
2012of expression.  So you should set 1 to second element.  And the first
2013matching group is sent to (image) processor defined by the variable
2014YaTeX-file-processor-alist. See also the documentation of
2015YaTeX-file-processor-alist.
2016
2017������ǂ��킩��Ȃ����ˁB�Ⴆ�� tgif hoge.obj ���� hoge.eps ��
2018\\epsfile{file=hoge.eps} �ŃC���N���[�h���Ă���Ƃ��悤�B���̍s��
2019\[prefix\] g ������������ tgif ���N�����ė~����������A�܂���̂悤��
2020���K�\����ݒ肷��B\\\\(��\\\\)�ň͂��Ƃ��낪�t�@�C�����ɂȂ�悤��
2021���ӂ���B�Ńt�@�C�������������Ԗڂ�\\\\(\\\\)�ɂȂ邩�����X�g��2�Ԗڂɏ����B
2022����ƁA���̕������ϐ� YaTeX-file-processor-alist �Œ�`���ꂽ
2023�����v���O�����ɓn�����B�Ƃ����킯�B
2024��`����ς�ނ��������ˁB������Ȃ����ׂ͗� Lisper �ɕ������A
2025fj�쒹�̉�ŕ�����!
2026")
2027
2028(defvar YaTeX-processed-file-regexp-alist-default
2029  '(("\\\\epsfile\\(\\[[^]]+\\]\\)?{[^},]*file=\\(\\([^,} ]*/\\)?[^,}. ]+\\)\\(\\.e?ps\\)?[^}]*}" 2)
2030    ("\\\\epsfig{[^},]*fi\\(le\\|gure\\)=\\(\\([^,} ]*/\\)?[^,}. ]+\\)\\(\\.e?ps\\)?[^}]*}" 2)
2031    ("\\\\postscriptbox{[^}]*}{[^}]*}{\\(\\([^,} ]*/\\)?[^}. ]+\\)\\(\\.e?ps\\)?}" 1)
2032    ("\\\\\\(epsfbox\\|epsfig\\)\\*?{\\(\\([^,} ]*/\\)?[^}. ]+\\)\\(\\.e?ps\\)?}" 2) ;\epsfbox{hoge.ps}
2033    ("\\\\includegraphics\\*?\\(.*\\]\\|\\s \\)?{\\(.*\\)\\(\\.ai\\|\\.pdf\\|\\.svg\\|\\.png\\|\\.jpe?g\\|\\.e?ps\\)}" 2) ;\includegraphics[options...]{hoge.eps}
2034    ("\\\\\\(psbox\\)\\(\\[[^]]+\\]\\)?{\\(\\([^,} ]*/\\)?[^} ]+\\)\\(\\.e?ps\\)}" 3) ;\psbox[options...]{hoge.eps} (97/1/11)
2035    ("\\\\input{\\([^} ]+\\)\\(\\.tps\\)}" 1) ;tgif2tex (1998/9/16)
2036    )
2037  "See the documentation of YaTeX-processed-file-regexp-alist.")
2038
2039(defvar YaTeX-file-processor-alist nil
2040  "*Alist of files' processor vs. its extension;
2041See also the documentation of YaTeX-processed-file-regexp-alist.")
2042
2043(defvar YaTeX-file-processor-alist-default
2044  (list (cons YaTeX-cmd-tgif ".obj")
2045	(cons YaTeX-cmd-gimp ".xcf")
2046	(cons YaTeX-cmd-gimp ".xcf.gz")
2047	(cons YaTeX-cmd-gimp ".xcf.bz2")
2048	(cons YaTeX-cmd-edit-svg ".svg")
2049	(cons YaTeX-cmd-edit-svg ".svgz")
2050	(cons YaTeX-cmd-edit-ai ".ai")
2051	'("dia" . ".dia")
2052	(cons YaTeX-cmd-ooo ".odg")
2053	(cons 'YaTeX-filter-goto-source ".diag")
2054	(cons 'YaTeX-filter-goto-source ".dot")
2055	;; List of target file itself below...
2056	(cons YaTeX-cmd-edit-images ".jpeg")
2057	(cons YaTeX-cmd-edit-images ".jpg")
2058	(cons YaTeX-cmd-edit-images ".png")
2059	(cons YaTeX-cmd-edit-ps ".ps")
2060	(cons YaTeX-cmd-edit-ps ".eps")
2061	(cons YaTeX-cmd-edit-pdf ".pdf")
2062	'(t . ".tex")
2063	'(t . ".sty")
2064	'(t . ""))
2065  "See the documentation of YaTeX-file-processor-alist.")
2066
2067(defun YaTeX-goto-corresponding-file-processor (&optional other)
2068  "Execute corresponding file processor."
2069  (save-excursion
2070    (or (looking-at YaTeX-ec-regexp)
2071	(skip-chars-backward (concat "^" YaTeX-ec) (point-beginning-of-line)))
2072    (let ((list (append YaTeX-processed-file-regexp-alist
2073			YaTeX-processed-file-regexp-alist-default))
2074	  (p (point)) flist file
2075	  (peol (point-end-of-line))
2076	  (basedir
2077	   (if YaTeX-search-file-from-top-directory
2078	       (save-excursion (YaTeX-visit-main t) default-directory)
2079	     ".")))
2080      (setq flist (catch 'found
2081		    (while list
2082		      (goto-char p)
2083		      (if (re-search-forward (car (car list)) peol t)
2084			  (progn
2085			    (setq file (YaTeX-match-string
2086					(car (cdr (car list)))))
2087			    (throw 'found (cdr (car list)))))
2088		      (setq list (cdr list)))))
2089      (if flist				;if pattern and file name found
2090	  (let*((plist (append YaTeX-file-processor-alist
2091			       YaTeX-file-processor-alist-default))
2092		(plist0 plist)
2093		ext cmd src buf (alt (car (cdr flist))))
2094	    (if (and (re-search-forward
2095		      (concat YaTeX-comment-prefix "\\s *\\(.*\\)$") peol t)
2096		     (assoc (setq cmd (YaTeX-match-string 1))
2097			    YaTeX-file-processor-alist))
2098		(setq src		;if processor is specified
2099		      (concat file
2100			      (cdr (assoc cmd YaTeX-file-processor-alist))))
2101	      (while plist		;if processor is not specified
2102		(setq ext (cdr (car plist)))
2103		(if (and (string< "" (concat file ext))
2104			 (file-exists-p
2105			  (expand-file-name (concat file ext) basedir)))
2106		    (setq cmd (car (car plist))
2107			  src (concat file ext) plist nil))
2108		(setq plist (cdr plist)))
2109	      (if (and (null src) alt YaTeX-create-file-prefix-g)
2110		  (setq cmd alt
2111			src (concat file (cdr (assoc alt plist0))))))
2112	    (if src			;if processor and src file found
2113		(let ((default-directory basedir))
2114		  (cond
2115		   ((stringp cmd)
2116		    (YaTeX-system (concat cmd " " src) cmd)
2117		    t)
2118		   ((eq t cmd)
2119		    (let ((parent buffer-file-name))
2120		      (funcall
2121		       (cond
2122			(other 'YaTeX-switch-to-buffer-other-window)
2123			((get-file-buffer src) 'goto-buffer-window)
2124			(t 'YaTeX-switch-to-buffer))
2125		       src)
2126		      (or (YaTeX-get-builtin "!")
2127			  YaTeX-parent-file
2128			  (setq YaTeX-parent-file parent))
2129		      t))
2130		   ((symbolp cmd)
2131		    (cond
2132		     ((symbol-function cmd)
2133		      (funcall cmd src other)))
2134		    t)))))))))
2135
2136(defun YaTeX-on-section-command-p (command)
2137  "Check if point is on the LaTeX command: COMMAND(regexp).
2138Return nil if point is not on it.  Otherwise return the
2139number of argument position.
2140Section command name is stored in match-data #1.
2141Parsing information is stored to plist.
2142Macros name stored to propname 'command.
2143Macro's argument number stored to propname 'argc."
2144  (let ((p (point)) md (parg 0) (argc 1) word (grouping 0) (i 0)
2145	(ec+command (concat YaTeX-ec-regexp "\\(" command "\\)")))
2146    (setplist 'YaTeX-on-section-command-p nil)
2147    (while (setq i (string-match "\\\\(" command i))
2148      (setq grouping (1+ grouping) i (+ i 2)))
2149    (save-excursion
2150      (if (looking-at ec+command) nil
2151	(catch 'found			;caught value has no meaning
2152	  ;;(1) looking at current position
2153	  (and (looking-at command)
2154	       (save-excursion
2155		 (while (and (not (bobp)) (looking-at command))
2156		   (forward-char -1))
2157		 (looking-at ec+command))
2158	       (goto-char (match-beginning 0))
2159	       (throw 'found t))
2160	  ;;If inside of parentheses, try to escape.
2161	  (unwind-protect
2162	      (progn
2163		(set-syntax-table YaTeX-mode-syntax-table-nonparen)
2164		(while (and (not (= (preceding-char) ?\])) ;skip optional arg
2165			    (condition-case err
2166				(progn (up-list -1) t)
2167			      (error nil)))))
2168	    (set-syntax-table YaTeX-mode-syntax-table))
2169	  (while (equal (preceding-char) ?\]) (backward-list))
2170	  ;;(2) search command directly
2171	  (skip-chars-forward "^{}[]")
2172	  (and (YaTeX-re-search-active-backward
2173		ec+command
2174		YaTeX-comment-prefix nil t)
2175	       (>= p (match-beginning 0))
2176	       (throw 'found (goto-char (match-beginning 0))))
2177	  ;;(3) search token
2178	  (goto-char p)
2179	  (while t
2180	    (if (bobp) (throw 'found nil))
2181	    (cond
2182	     ((looking-at YaTeX-ec-regexp) (throw 'found t))
2183	     ((looking-at "[[{]") nil)
2184	     ((looking-at "[]}]")(condition-case nil (up-list -1) (error nil)))
2185	     (t (skip-chars-backward " \t\r\n")))
2186	    (skip-chars-backward (concat "^ \t\r\n{}[]" YaTeX-ec-regexp))
2187	    (or (bobp) (forward-char -1)))))
2188      (if (and
2189	   (looking-at (concat ec+command
2190			       "\\(\\(\\[[^]]+\\]\\|([0-9,]+)\\)*\\)"	;optional arg
2191			       ;"[ \t\n\r]*{[^}]+}")) ;arg braces
2192			       "[ \t\n\r]*{[^}]*}")) ;arg braces
2193	   (not (YaTeX-lookup-table
2194		 (setq word (YaTeX-match-string 1)) 'singlecmd)))
2195	  (progn
2196	    (setq md (match-data))
2197	    (skip-chars-forward "^{")
2198	    (if (<= (point) p) (setq parg (1+ parg)))
2199	    (setq argc
2200		  (or (car (cdr (YaTeX-lookup-table word 'section)))
2201		      argc))
2202	    (put 'YaTeX-on-section-command-p 'argc argc)
2203	    (put 'YaTeX-on-section-command-p 'command argc)
2204	    (while (and (>= (setq argc (1- argc)) 0)
2205			(progn (skip-chars-forward " \t\n\r")
2206			       (looking-at "{")))
2207	      (forward-list 1)
2208	      (if (<= (point) p) (setq parg (1+ parg))))
2209	    (store-match-data md)
2210	    (setq i (+ 2 grouping))
2211	    (if (and (match-beginning i)
2212		     (>= p (match-beginning i)) (< p (match-end i)))
2213		-1			;return -1 if point is on optional arg
2214	      (if (< p (point)) parg))
2215	    )))))
2216
2217(defun YaTeX-on-maketitle-p ()
2218  "Check if point is on maketitle type commands.
2219Call this function after YaTeX-on-section-command-p."
2220  (let ((p (point)))
2221    (save-excursion
2222      (or (= (char-after (point)) ?\\ )
2223	  (progn
2224	    (skip-chars-backward
2225	     (concat "^" YaTeX-ec-regexp) (point-beginning-of-line))
2226	    (or (bobp) (bolp) (backward-char 1))))
2227      (and (looking-at (concat YaTeX-ec-regexp YaTeX-TeX-token-regexp))
2228	   (<= (match-beginning 0) p)
2229	   (> (match-end 0) p)))))
2230
2231(defun YaTeX-on-begin-end-p ()
2232  (save-excursion
2233    (if (and (boundp 'in-leftright-p) in-leftright-p)
2234	;; Dirty workaround for YaTeX-goto-corresponding-leftright 2003/3/28
2235	(let ((md (match-data)))	; for safety
2236	  (if (looking-at YaTeX-ec-regexp)
2237	      nil			; stay here
2238	    (cond
2239	     ((looking-at "\\w")		(skip-chars-backward "A-Za-z"))
2240	     ((looking-at "\\.()\\[\\]|")	(forward-char -1)))
2241	    (if (equal (char-after (1- (point)))
2242		       (string-to-char YaTeX-ec))
2243		(forward-char -1))))
2244      ;(beginning-of-line)
2245      (if (equal (char-after (point)) ?\\) nil	;stay here
2246	(skip-chars-backward "^\n\\\\")
2247	(or (bolp) (forward-char -1))))
2248    (re-search-forward
2249     ;;"\\\\begin{\\([^}]+\\)}\\|\\\\end{\\([^}]+\\)}"
2250     (concat
2251      (YaTeX-replace-format-args
2252       (regexp-quote YaTeX-struct-begin)
2253       (concat "\\(" YaTeX-struct-name-regexp "\\)") "" "" "")
2254      "\\|"
2255      (YaTeX-replace-format-args
2256       (regexp-quote YaTeX-struct-end)
2257       (concat "\\(" YaTeX-struct-name-regexp "\\)") "" "" "")
2258      "\\|\\("
2259      YaTeX-ec-regexp  ;;"[][()]\\)"
2260      "[\\]\\[]\\)"
2261      )
2262     (point-end-of-line) t)))
2263
2264(defun YaTeX-on-includes-p ()
2265  (save-excursion
2266    (beginning-of-line)
2267    (re-search-forward "\\(\\(include[^}]*\\)\\|\\(input\\)\\){[^}]*}"
2268		       (point-end-of-line) t)))
2269
2270(defun YaTeX-on-comment-p (&optional sw)
2271  "Return t if current line is commented out.
2272Optional argument SW t to treat all `%' lines as comment,
2273even if on `%#' notation."
2274  (save-excursion
2275    (beginning-of-line)
2276    (skip-chars-forward "\\s ")
2277    (looking-at (if sw "%" "%[^#]"))))
2278
2279(defun YaTeX-on-BEGIN-END-p ()
2280  (save-excursion
2281    (let ((case-fold-search nil))
2282      (beginning-of-line)
2283      (re-search-forward
2284       "\\(%#BEGIN\\)\\|\\(%#END\\)" (point-end-of-line) t))))
2285
2286(defun YaTeX-on-SRC-p ()
2287  (save-excursion
2288    (let ((case-fold-search nil))
2289      (beginning-of-line)
2290      (re-search-forward
2291       "%#SRC{\\([^}]+\\)}" (point-end-of-line) t))))
2292
2293(defun YaTeX-goto-corresponding-* (arg)
2294  "Parse current line and call suitable function."
2295  (interactive "P")
2296  (let (mm)
2297    (cond
2298     ((YaTeX-goto-corresponding-label arg))
2299     ((YaTeX-goto-corresponding-environment))
2300     ((YaTeX-goto-corresponding-file-processor arg))
2301     ((YaTeX-goto-corresponding-file arg))
2302     ((YaTeX-goto-corresponding-BEGIN-END))
2303     ((and (setq mm (YaTeX-in-math-mode-p))
2304	   (YaTeX-goto-corresponding-leftright)))
2305     ((and ;;mm YaTeX-use-AMS-LaTeX
2306	   (YaTeX-goto-corresponding-paren)))
2307     ;;((and (string-match
2308     ;;	  YaTeX-equation-env-regexp	;to delay loading
2309     ;;	  (or (YaTeX-inner-environment t) "document"))
2310     ;;	 (YaTeX-goto-corresponding-leftright)))
2311     ((YaTeX-goto-corresponding-viewer))
2312     (t (message "I don't know where to go.")))))
2313
2314(defun YaTeX-goto-corresponding-*-other-window (arg)
2315  "Parse current line and call suitable function."
2316  (interactive "P")
2317  (YaTeX-goto-corresponding-* t))
2318
2319(defun YaTeX-comment-region (alt-prefix)
2320  "Comment out region by '%'.
2321If you call this function on the 'begin{}' or 'end{}' line,
2322it comments out whole environment"
2323  (interactive "P")
2324  (if (not (YaTeX-on-begin-end-p))
2325      (YaTeX-comment-region-sub
2326       (if alt-prefix
2327	   (read-string-with-history "Insert prefix: ")
2328	 YaTeX-comment-prefix))
2329    (YaTeX-comment-uncomment-env 'YaTeX-comment-region-sub)))
2330
2331(defun YaTeX-uncomment-region (alt-prefix)
2332  "Uncomment out region by '%'."
2333  (interactive "P")
2334  (if (not (YaTeX-on-begin-end-p))
2335      (YaTeX-uncomment-region-sub
2336       (if alt-prefix (read-string-with-history "Remove prefix: ")
2337	 YaTeX-comment-prefix)
2338       (region-beginning) (region-end) YaTeX-uncomment-once)
2339    (YaTeX-comment-uncomment-env 'YaTeX-uncomment-region-sub)))
2340
2341(defun YaTeX-comment-uncomment-env (func)
2342  "Comment or uncomment out one LaTeX environment switching function by FUNC."
2343  (let (beg beg2 (p (point)))
2344    (save-excursion
2345	(beginning-of-line)
2346	(setq beg (point))
2347	(save-match-data
2348	  (while (and (not (eobp))
2349		      (not (eolp))
2350		      (looking-at YaTeX-comment-prefix))
2351	    (goto-char (match-end 0))))
2352	(setq beg2 (point))
2353	(YaTeX-goto-corresponding-environment)
2354	(beginning-of-line)
2355	(if (> p (point)) (setq beg (1+ beg2)) (forward-char 1))
2356	(funcall func YaTeX-comment-prefix beg (point) YaTeX-uncomment-once)))
2357  (message "%sommented out current environment."
2358	   (if (string-match "uncom" (symbol-name func)) "Un-c" "C")))
2359
2360(defun YaTeX-comment-paragraph ()
2361  "Comment out current paragraph."
2362  (interactive)
2363  (save-excursion
2364    (cond
2365     ((YaTeX-on-begin-end-p)
2366      (beginning-of-line)
2367      (insert YaTeX-comment-prefix)
2368      (YaTeX-goto-corresponding-environment)
2369      (beginning-of-line)
2370      (insert YaTeX-comment-prefix))
2371     ((YaTeX-on-comment-p)
2372      (message "Already commented out."))
2373     (t
2374      (mark-paragraph)
2375      (if (looking-at paragraph-separate) (forward-line 1))
2376      (YaTeX-comment-region-sub "%")))))
2377
2378(defun YaTeX-uncomment-paragraph ()
2379  "Uncomment current paragraph."
2380  (interactive)
2381  (save-excursion
2382    (if (YaTeX-on-begin-end-p)
2383	(let ((p (point-marker)))
2384	  (YaTeX-goto-corresponding-environment)
2385	  (YaTeX-remove-prefix YaTeX-comment-prefix YaTeX-uncomment-once)
2386	  (goto-char p)
2387	  (YaTeX-remove-prefix YaTeX-comment-prefix YaTeX-uncomment-once)
2388	  (set-marker p nil))
2389      (if (YaTeX-on-comment-p)
2390	  (let*((fill-prefix "")
2391		;;append `^%' to head of paragraph delimiter.
2392		(paragraph-start
2393		 (concat
2394		  "^$\\|^%\\(" YaTeX-paragraph-separate "\\)"))
2395		(paragraph-separate paragraph-start))
2396	    (mark-paragraph)
2397	    (if (not (bobp)) (forward-line 1))
2398	    (YaTeX-uncomment-region-sub "%" nil nil YaTeX-uncomment-once))
2399	(message "This line is not a comment line.")))))
2400
2401(defun YaTeX-remove-prefix (prefix &optional once)
2402  "Remove prefix on current line as far as prefix detected. But
2403optional argument ONCE makes deletion once."
2404  (interactive "sPrefix:")
2405  (beginning-of-line)
2406  (while (re-search-forward (concat "^" prefix) (point-end-of-line) t)
2407    (replace-match "")
2408    (if once (end-of-line))))
2409
2410(defun YaTeX-kill-some-pairs (predicate gofunc kill-contents)
2411  "Kill some matching pair.
2412This function assumes that pairs occupy whole of each line where they resid."
2413  (if (not (funcall predicate)) nil
2414    (let ((b1 (match-beginning 0)) (e1 (match-end 0))
2415	  b2 e2)
2416      (save-excursion
2417	(funcall gofunc)
2418	(funcall predicate)		;get match data
2419	(if (< (point) e1)		;if currently on begin-line
2420	    (progn
2421	      (setq b2 b1 e2 e1
2422		    b1 (match-beginning 0) e1 (match-end 0))
2423	      (goto-char e2))		;goto end-line's end
2424	  (setq b2 (match-beginning 0)
2425		e2 (match-end 0))
2426	  (goto-char e2))	;now e2 has surely end-line's end
2427	(skip-chars-forward " \t")
2428	(and (eolp)
2429	     (not (eobp))
2430	     (setq e2 (1+ (point))))
2431	(if (not kill-contents)
2432	    (kill-region
2433	     (progn
2434	       (goto-char b2)
2435	       (skip-chars-backward " \t%")
2436	       (if (bolp) (point) b2))
2437	     e2))
2438	(goto-char b1)
2439	(skip-chars-backward " \t%")
2440	(if (not kill-contents)
2441	    (progn
2442	      (kill-append
2443	       (buffer-substring
2444		(setq b1 (if (bolp) (point) b1))
2445		(setq e1
2446		      (progn
2447			(goto-char e1)
2448			(while (looking-at "{\\| \t")
2449			  (forward-list 1))
2450			(skip-chars-forward " \t")
2451			(if (and (eolp) (not (eobp)))
2452			    (1+ (point))
2453			  (point)))))
2454	       t)
2455	      (delete-region b1 e1))
2456	  (kill-region
2457	   (if (bolp) (point) b1)
2458	   e2)))
2459      t)))
2460
2461(defun YaTeX-kill-section-command (point kill-all)
2462  "Kill section-type command at POINT leaving its last argument.
2463Non-nil for the second argument kill its last argument too."
2464  (let ((cmd (get 'YaTeX-on-section-command-p 'command))
2465	(argc (get 'YaTeX-on-section-command-p 'argc))
2466	beg (end (make-marker)))
2467    (save-excursion
2468      (goto-char point)
2469      (or (looking-at YaTeX-ec-regexp)
2470	  (progn
2471	    (skip-chars-backward (concat "^" YaTeX-ec-regexp))
2472	    (forward-char -1)))
2473      (setq beg (point))
2474      (skip-chars-forward "^{")
2475      (while (> (setq argc (1- argc)) 0)
2476	(skip-chars-forward "^{")
2477	(forward-list 1))
2478      (kill-region beg (point))
2479      (forward-list 1)
2480      (set-marker end (point))
2481      (if kill-all
2482	  (progn
2483	    (kill-append (buffer-substring beg end) nil)
2484	    (delete-region beg end))
2485	(goto-char beg)
2486	(kill-append
2487	 (buffer-substring
2488	  (point) (progn (skip-chars-forward "^{" end) (1+ (point))))
2489	 nil)
2490	(delete-region beg (1+ (point)))
2491	(goto-char end)
2492	(set-marker end nil)
2493	(kill-append (buffer-substring (point) (1- (point))) nil)
2494	(delete-backward-char 1)))))
2495
2496(defun YaTeX-kill-paren (kill-contents)
2497  "Kill parentheses leaving its contents.
2498But kill its contents if the argument KILL-CONTENTS is non-nil."
2499  (interactive "P")
2500  (let (p bsl (backslash-syntax (char-to-string (char-syntax ?\\)))
2501	  (md (match-data)))
2502    (unwind-protect
2503	(save-excursion
2504	  (modify-syntax-entry ?\\ " ")
2505	  (if (looking-at "\\s(\\|\\(\\s)\\)")
2506	      (progn
2507		(if (match-beginning 1)
2508		    (up-list -1))
2509		(if (and (> (point) (point-min))
2510			 (= (char-after (1- (point))) ?\\ ))
2511		    (setq p (1- (point)) bsl t)
2512		  (setq p (point)))
2513		(forward-list 1)
2514					;(YaTeX-goto-open-paren t)
2515		(if kill-contents (delete-region p (point))
2516		  (backward-delete-char 1)
2517		  (cond
2518		   ((save-excursion
2519		      (forward-char -2)
2520		      (looking-at (concat YaTeX-ec-regexp "/")))
2521		    (backward-delete-char 2))
2522		   ((= (char-after (1- (point))) ?\\)
2523		    (backward-delete-char 1)))
2524		  (goto-char p)
2525		  (if (looking-at
2526		       (concat "{" YaTeX-ec-regexp
2527			       YaTeX-command-token-regexp "+"
2528			       "\\s +"))
2529		      (delete-region (point) (match-end 0))
2530		    (delete-char 1)
2531		    (if bsl (delete-char 1))))
2532		t)))
2533      (modify-syntax-entry ?\\ backslash-syntax)
2534      (store-match-data md))))
2535
2536(defvar YaTeX-read-environment-history nil "Holds history of environments.")
2537(put 'YaTeX-read-environment-history 'no-default t)
2538(defun YaTeX-read-environment (prompt &optional predicate must-match initial)
2539  "Read a LaTeX environment name with completion."
2540  (YaTeX-sync-local-table 'tmp-env-table)
2541  (completing-read-with-history
2542   prompt
2543   (append tmp-env-table user-env-table env-table)
2544   predicate must-match initial
2545   'YaTeX-read-environment-history))
2546
2547(defvar YaTeX-read-section-history nil "Holds history of section-types.")
2548(put 'YaTeX-read-section-history 'no-default t)
2549(defun YaTeX-read-section (prompt &optional predicate initial)
2550  "Read a LaTeX section-type command with completion."
2551  (YaTeX-sync-local-table 'tmp-section-table)
2552  (let ((minibuffer-completion-table
2553	 (append tmp-section-table user-section-table section-table)))
2554    (read-from-minibuffer-with-history
2555     prompt initial YaTeX-section-completion-map nil
2556     'YaTeX-read-section-history)))
2557
2558(defun YaTeX-read-section-with-overview ()
2559  "Read sectioning command with overview.
2560This function refers a local variable `source-window' in YaTeX-make-section,
2561because this function is called with no argument."
2562  (interactive)
2563  (require 'yatexsec)			;some case needs this
2564  (if (> (minibuffer-depth) 1)
2565      (error "Too many minibuffer levels for overview."))
2566  (let ((sw (selected-window))
2567	(minibuffer-max-depth nil) ; for XEmacs20
2568	(enable-recursive-minibuffers t) sect)
2569    (unwind-protect
2570	(progn
2571	  (select-window source-window)
2572	  (setq sect (YaTeX-read-section-in-minibuffer
2573		      "Sectioning(Up=C-p, Down=C-n, Help=?): "
2574		      YaTeX-sectioning-level (YaTeX-section-overview))))
2575      (select-window sw))
2576    (YaTeX-minibuffer-erase)
2577    (insert sect)
2578    (exit-minibuffer)))
2579
2580(defvar YaTeX-read-fontsize-history nil "Holds history of font designator.")
2581(put 'YaTeX-read-fontsize-history 'no-default t)
2582(defun YaTeX-read-fontsize (prompt &optional predicate must-match initial)
2583  "Read a LaTeX font changing command with completion."
2584  (YaTeX-sync-local-table 'tmp-fontsize-table)
2585  (completing-read-with-history
2586   prompt (append tmp-fontsize-table user-fontsize-table fontsize-table)
2587   predicate must-match initial 'YaTeX-read-fontsize-history))
2588
2589(defun YaTeX-change-environment ()
2590  "Change the name of environment."
2591  (interactive)
2592  (if (not (YaTeX-on-begin-end-p)) nil
2593    (save-excursion
2594      (let (p env newenv (m1 (match-beginning 1)) (m2 (match-beginning 2)))
2595	(setq env (if m1 (YaTeX-buffer-substring m1 (match-end 1))
2596		    (YaTeX-buffer-substring m2 (match-end 2))))
2597	(goto-char (match-beginning 0))
2598	(set-mark-command nil)
2599	(YaTeX-goto-corresponding-environment)
2600	(setq newenv (YaTeX-read-environment
2601		      (format "Change environment `%s' to: " env)))
2602	(cond
2603	 ((string= newenv "")	(message "Change environment cancelled."))
2604	 ((string= newenv env)	(message "No need to change."))
2605	 (t
2606	  (search-forward (concat "{" env) (point-end-of-line) t)
2607	  (replace-match (concat "{" newenv) t)
2608	  (exchange-point-and-mark)
2609	  (search-forward (concat "{" env) (point-end-of-line) t)
2610	  (replace-match (concat "{" newenv) t)))
2611	t))))
2612
2613(defun YaTeX-change-section ()
2614  "Change section-type command."
2615  (interactive)
2616  (let*((where (YaTeX-on-section-command-p YaTeX-command-token-regexp))
2617	(p (point)) (cmd (YaTeX-match-string 1))
2618	(beg (make-marker)) (end (make-marker)) old new)
2619    (if (null where) nil
2620      (unwind-protect
2621	  (let ((source-window (selected-window)))
2622	    (cond
2623	     ((equal where 0);;if point is on section command
2624	      (set-marker beg (match-beginning 1))
2625	      (set-marker end (match-end 1))
2626	      (goto-char beg)		;beginning of the command
2627	      (setq new (YaTeX-read-section
2628			 (format "Change `%s' to: " cmd) nil)
2629		    old cmd))
2630
2631	     ((= where -1);;if point is on a optional parameter
2632	      (set-marker beg (match-beginning 2))
2633	      (skip-chars-forward "^{")
2634	      (set-marker end (point))
2635	      (goto-char p)
2636	      (setq new
2637		    (if (fboundp (intern-soft (concat YaTeX-addin-prefix cmd)))
2638			(YaTeX-addin cmd)
2639		      (concat "["
2640			      (read-string
2641			       (format "Change `%s' to: "
2642				       (setq old (YaTeX-buffer-substring
2643						  (1+ beg) (1- end)))))
2644			      "]"))))
2645
2646	     ((> where 0);;if point is in arguments' braces
2647	      (or (looking-at "{")
2648		  (progn (skip-chars-backward "^{") (forward-char -1)))
2649	      (set-marker beg (1+ (point)))
2650	      (forward-list 1)
2651	      (forward-char -1)
2652	      (set-marker end (point))
2653	      (setq old (YaTeX-buffer-substring beg end))
2654	      (goto-char p)
2655	      (if (> (length old) 40)
2656		  (setq old (concat (substring old 0 12) "..."
2657				    (substring old -12))))
2658	      (setq new
2659		    (if (intern-soft (concat "YaTeX::" cmd))
2660			(funcall (intern-soft (concat "YaTeX::" cmd)) where)
2661		      (read-string (format "Change `%s' to: " old)))))
2662	     )				;cond
2663	    (if (string= old new)
2664		nil			;do not replace
2665	      (delete-region beg end)
2666	      (goto-char beg)
2667	      (insert-before-markers new)))
2668	(set-marker beg nil)
2669	(set-marker end nil))
2670      ;;(goto-char (marker-position p))
2671      new)))
2672
2673(defun YaTeX-change-fontsize ()
2674  "Change large-type command."
2675  (let ((lt (append tmp-fontsize-table user-fontsize-table fontsize-table))
2676	(p (point)) large old new beg end)
2677    ;;(and (looking-at "}") (up-list -1))
2678    ;;(and (looking-at "{") (forward-char 1))
2679    ;;Is above convenient?
2680    (save-excursion
2681      (or (looking-at YaTeX-ec-regexp)
2682	  (progn
2683	    (skip-chars-backward (concat "^" YaTeX-ec-regexp))
2684	    (forward-char -1)))
2685      (cond
2686       ((and
2687	 (looking-at
2688	  (concat YaTeX-ec-regexp "\\(" YaTeX-TeX-token-regexp "\\)"))
2689	 (< p (match-end 0))
2690	 (assoc (setq old (YaTeX-match-string 1)) lt))
2691	(goto-char p)
2692	(setq beg (match-beginning 1) end (match-end 1) ;save match position
2693	      new (completing-read
2694		   (format "Change font/size `%s' to : " old) lt))
2695	(delete-region beg end)
2696	(goto-char beg)
2697	(insert-before-markers new)
2698	new)
2699       (t nil)
2700       ))))
2701
2702(defun YaTeX-change-math-image ()
2703  "Change with image completion."
2704  (let (maketitle memberp beg end)
2705    (if (and (YaTeX-on-maketitle-p)
2706	     (progn
2707	       (setq maketitle (substring (YaTeX-match-string 0) 1))
2708	       (setq memberp (YaTeX-math-member-p maketitle))))
2709	(let*((last-command-char (string-to-char (car memberp)))
2710	      (last-command-event last-command-char))
2711	  (setq beg (match-beginning 0) end (match-end 0))
2712	  (delete-region beg end)
2713	  (YaTeX-math-insert-sequence t (cdr memberp))))))
2714
2715(defun YaTeX-kill-* (&optional arg)
2716  "Parse current line and call suitable function.
2717Non-nil for ARG kills its contents too."
2718  (interactive "P")
2719  (cond
2720   ((YaTeX-kill-some-pairs 'YaTeX-on-begin-end-p
2721			   'YaTeX-goto-corresponding-environment arg))
2722   ((YaTeX-kill-some-pairs 'YaTeX-on-BEGIN-END-p
2723			   'YaTeX-goto-corresponding-BEGIN-END arg))
2724   ((YaTeX-on-section-command-p YaTeX-command-token-regexp);on any command
2725    (YaTeX-kill-section-command (match-beginning 0) arg))
2726   ((YaTeX-kill-paren arg))
2727   ((and (fboundp 'overlays-at)
2728	 (member YaTeX-on-the-fly-overlay (overlays-at (point))))
2729    (YaTeX-on-the-fly-cancel))
2730   (t (message "I don't know what to kill."))))
2731
2732(defun YaTeX-change-* ()
2733  "Parse current line and call suitable function."
2734  (interactive)
2735  (cond
2736   ((YaTeX-change-parentheses))
2737   ((YaTeX-change-environment))
2738   ((YaTeX-change-section))
2739   ((YaTeX-change-fontsize))
2740   ((YaTeX-change-math-image))
2741   (t (message "I don't know what to change."))))
2742
2743;;;
2744;Check availability of add-in functions
2745;;;
2746(cond
2747 ((featurep 'yatexadd) nil)		;Already provided.
2748 ((progn (load "yatexadd" t) (featurep 'yatexadd)) nil)
2749 (t (message "YaTeX add-in functions not supplied.")))
2750
2751(defun YaTeX-addin (name)
2752  "Check availability of addin function and call it if exists."
2753  (if (and (not (get 'YaTeX-generate 'disabled))
2754	   (intern-soft (concat YaTeX-addin-prefix name))
2755	   (fboundp (intern-soft (concat YaTeX-addin-prefix name))))
2756      (let ((s (funcall (intern (concat YaTeX-addin-prefix name)))))
2757	(if (stringp s) s ""))
2758    "")) ;Add in function is not bound.
2759
2760
2761(defun YaTeX-on-item-p (&optional point)
2762  "Return t if POINT (default is (point)) is on \\item."
2763  (let ((p (or point (point))))
2764    (save-excursion
2765      (goto-char p)
2766      (end-of-line)
2767      (setq p (point))
2768      (re-search-backward YaTeX-paragraph-delimiter nil t)
2769      (re-search-forward YaTeX-item-regexp p t))))
2770
2771(defun YaTeX-in-verb-p (&optional point)
2772  "Check if POINT is in verb or verb*.  Default of POINT is (point)."
2773  (setq point (or point (point)))
2774  (save-excursion
2775    (let ((md (match-data)))
2776      (goto-char point)
2777      (unwind-protect
2778	  (if (not (re-search-backward
2779		    (concat YaTeX-ec-regexp
2780			    "\\(" YaTeX-verb-regexp "\\)"
2781			    "\\([^-A-Za-z_*]\\)")
2782		    (point-beginning-of-line) t))
2783	      nil
2784	    (goto-char (match-end 2))
2785	    (skip-chars-forward
2786	     (concat "^" (YaTeX-buffer-substring
2787			  (match-beginning 2) (match-end 2))))
2788	    (and (< (match-beginning 2) point) (< (1- point) (point))))
2789	(store-match-data md)))))
2790
2791(defun YaTeX-literal-p (&optional point)
2792  "Check if POINT is in verb or verb* or verbatime environment family.
2793Default of POINT is (point)."
2794  (let ((md (match-data)))
2795    (unwind-protect
2796	(cond
2797	 ((equal YaTeX-ec "\\")		;maybe LaTeX
2798	  (save-excursion
2799	    (and point (goto-char point))
2800	    (or (YaTeX-in-verb-p (point))
2801		(and (not (looking-at "\\\\end{verb"))
2802		     (YaTeX-quick-in-environment-p
2803		      YaTeX-verbatim-environments))))))
2804      (store-match-data md))))
2805
2806;; Filling \item
2807(defun YaTeX-remove-trailing-comment (start end)
2808  "Remove trailing comment from START to end."
2809  (save-excursion
2810    (let ((trcom (concat YaTeX-comment-prefix "$")))
2811      (goto-char start)
2812      (while (re-search-forward trcom end t)
2813	(if (/= (char-after (1- (match-beginning 0))) ?\\ )
2814	    (replace-match "\\1"))))))
2815
2816(defvar YaTeX-itemize-withlabel-max-indent-depth 8)
2817(defun YaTeX-get-item-info (&optional recent thisenv)
2818  "Return the list of the beginning of \\item and column of its item.
2819If it seems to be outside of itemizing environment, just return nil.
2820Non-nil for optional argument RECENT refers recent \\item.
2821Optional second argument THISENV omits calling YaTeX-inner-environment."
2822  (save-excursion
2823    (let* ((p (point)) env e0 c cc md
2824	   (bndry (and (setq env (or thisenv (YaTeX-inner-environment t)))
2825		       (get 'YaTeX-inner-environment 'point))))
2826      (end-of-line)
2827      (if (if recent
2828	      (catch 'found
2829		(while (YaTeX-re-search-active-backward
2830			YaTeX-item-regexp YaTeX-comment-prefix bndry t)
2831		  (setq md (match-data))
2832		  (YaTeX-inner-environment t)
2833		  (store-match-data md)
2834		  (if (= bndry (get 'YaTeX-inner-environment 'point))
2835		      (throw 'found t))))
2836	    (goto-char bndry)
2837	    (YaTeX-re-search-active-forward
2838	     YaTeX-item-regexp YaTeX-comment-prefix p t))
2839	  (progn
2840	    (goto-char (match-end 0))
2841	    ;(setq c (current-column))
2842	    (if (string-match "desc" env)
2843		(setq c 6)
2844	      (setq cc (current-column))
2845	      (if (equal (following-char) ?\[) (forward-list 1))
2846	      (if (< (- (current-column) cc)
2847		     YaTeX-itemize-withlabel-max-indent-depth)
2848		  (setq c 0)
2849		(move-to-column cc)
2850		(setq c YaTeX-itemize-withlabel-max-indent-depth)))
2851	    (skip-chars-forward " \t" (point-end-of-line))
2852	    (list (point-beginning-of-line) (+ c (current-column))))))))
2853
2854(defun YaTeX-fill-item ()
2855  "Fill item in itemize environment."
2856  (interactive)
2857  (save-excursion
2858    (let* ((p (point))
2859	   (item-term (concat
2860		       "\\(^[ \t]*$\\)\\|" YaTeX-item-regexp "\\|\\("
2861		       YaTeX-ec-regexp "\\(begin\\|end\\)\\)"))
2862	   ;;This value depends on LaTeX.
2863	   fill-prefix start col
2864	   (info (YaTeX-get-item-info t)))
2865      (if (null info) nil		;not on \item, do nothing
2866	(setq start (car info)
2867	      col (car (cdr info)))
2868	(save-excursion
2869	  (if (re-search-backward "^\\s *$" start t)
2870	      ;;if separated from \item line, isolate this block
2871	      (progn
2872		(setq start (1+ (match-end 0)))
2873		(goto-char start)
2874		(skip-chars-forward " \t")
2875		(delete-region (point) start) ;is this your favor???
2876		(indent-to col))))
2877	(beginning-of-line)
2878	(if (<= (save-excursion
2879		 (re-search-forward
2880		  (concat "\\\\end{\\|\\\\begin{\\|^[ \t]*$") nil t)
2881		 (match-beginning 0))
2882	       p)
2883	    (progn  (message "Not on itemize.") nil)
2884	  (end-of-line)
2885	  (newline)
2886	  (indent-to col)
2887	  (setq fill-prefix
2888		(YaTeX-buffer-substring (point-beginning-of-line)(point)))
2889	  (beginning-of-line)
2890	  (delete-region (point) (progn (forward-line 1) (point)))
2891	  (re-search-forward item-term nil 1)
2892	  (YaTeX-remove-trailing-comment start (point))
2893	  (beginning-of-line)
2894	  (push-mark (point) t)
2895	  (goto-char start)
2896	  (forward-line 1)
2897	  (while (< (point) (mark))
2898	    (delete-region (point) (progn (skip-chars-forward " \t") (point)))
2899	    (forward-line 1))
2900	  (fill-region-as-paragraph start (mark))
2901	  (if NTT-jTeX
2902	      (while (progn(forward-line -1)(end-of-line) (> (point) start))
2903		(insert ?%)))
2904	  (pop-mark))))))
2905
2906(defun YaTeX-fill-paragraph (arg)
2907  "YaTeX adjustment function for fill-paragraph.
2908*Protect \\verb from unexpected broken up."
2909  (interactive "P")
2910  (cond
2911   ((not (eq major-mode 'yatex-mode)) (fill-paragraph arg))
2912   ((YaTeX-quick-in-environment-p YaTeX-fill-inhibit-environments) nil)
2913   ((YaTeX-in-math-mode-p) nil)
2914   (t
2915    (save-excursion
2916      (let*((verbrex (concat YaTeX-ec-regexp
2917			     "\\(" YaTeX-verb-regexp "\\)" ;match#1
2918			     "\\(.\\).*\\(\\2\\)")) ;match #2 and #3
2919	    (tilderex (concat "\\("
2920			      YaTeX-kanji-regexp "~"
2921			      "\\)" YaTeX-ec-regexp
2922			      "\\|\\("
2923			      "~" YaTeX-kanji-regexp
2924			      "\\)"))
2925	    (p (point)) ii end poslist spacelist lenlist b e n
2926	    (fill-prefix fill-prefix)
2927	    (inenv (or (YaTeX-inner-environment t) "document"))
2928	    (border (get 'YaTeX-inner-environment 'point)))
2929	(cond
2930	 ((save-excursion (beginning-of-line) ;if point is on the first
2931			  (setq end (point))  ;non-whitespace char
2932			  (skip-chars-forward " \t")
2933			  (equal (point) p))
2934	  (setq fill-prefix (YaTeX-buffer-substring p end)))
2935	 ((and ;;(not YaTeX-emacs-19)
2936	       (string-match YaTeX-itemizing-env-regexp inenv)
2937	       (setq ii (YaTeX-get-item-info)))
2938	  (save-excursion
2939	    (beginning-of-line)
2940	    (indent-to-column (car (cdr ii)))
2941	    (setq fill-prefix
2942		  (YaTeX-buffer-substring (point) (point-beginning-of-line)))
2943	    (delete-region (point) (progn (beginning-of-line) (point))))))
2944	(cond
2945	 ((string-match "tabular" inenv)
2946	  (let ((b (point-beginning-of-line))
2947		(e (point-end-of-line)))
2948	    (if (re-search-backward
2949		 "&\\|\\\\\\\\\\|\\\\\\(begin\\|end\\){" border t)
2950		(setq b (if (match-beginning 1)
2951			    (progn (forward-line 1) (point))
2952			  (point-beginning-of-line))))
2953	    (goto-char p)
2954	    (if (re-search-forward
2955		 "&\\|\\\\\\\\\\|\\\\\\(end\\|begin\\){" nil t)
2956		(setq e (if (match-beginning 1)
2957			    (progn (forward-line -1)
2958				   (point-end-of-line))
2959			  (match-beginning 0))))
2960	    (set-mark e)
2961	    (goto-char b)))
2962	 (t
2963	  (mark-paragraph)))
2964	(save-restriction
2965	  (narrow-to-region (region-beginning) (region-end))
2966	  (YaTeX-remove-trailing-comment (point-min) (point-max))
2967	  ;; First, replace spaces in verb to _ temporarily.
2968	  (goto-char (point-min))
2969	  (while (YaTeX-re-search-active-forward
2970		  verbrex YaTeX-comment-prefix (point-max) t)
2971	    (setq end (match-beginning 3))
2972	    (goto-char (match-beginning 2))
2973	    (while (re-search-forward "\\s " end t)
2974	      (setq poslist (cons (make-marker) poslist)
2975		    spacelist (cons (preceding-char) spacelist)
2976		    lenlist (cons 1 lenlist))
2977	      (replace-match "_")
2978	      (set-marker (car poslist) (match-beginning 0))))
2979	  ;; Second, replace "�\~\ref{...}" to "\\\ref{...}"
2980	  (goto-char (point-min))
2981	  (while (YaTeX-re-search-active-forward
2982		  tilderex YaTeX-comment-prefix (point-max) t)
2983	    (if (match-beginning 1)
2984		(setq b (match-beginning 1) e (match-end 1) n 1)
2985	      (setq b (match-beginning 2) e (match-end 2) n 2))
2986	    (setq poslist (cons (make-marker) poslist)
2987		  spacelist (cons (YaTeX-match-string n) spacelist)
2988		  lenlist (cons 2 lenlist))
2989	    (goto-char (match-beginning 0))
2990	    (delete-region (point) e)
2991	    (insert YaTeX-ec YaTeX-ec)	;set-marker should be here
2992	    (set-marker (car poslist) b))
2993	  ;;(fill-paragraph arg)
2994	  (fill-region-as-paragraph (point-min) (point-max) arg)
2995	  (while spacelist
2996	    (goto-char (car poslist))
2997	    (set-marker (car poslist) nil)
2998	    (and (eolp) (skip-chars-forward "\n\t "))
2999	    (delete-char (car lenlist))
3000	    (insert (car spacelist))
3001	    (setq spacelist (cdr spacelist)
3002		  poslist (cdr poslist)
3003		  lenlist (cdr lenlist)))
3004	  (goto-char (point-min))
3005	  (forward-word 1)
3006	  (beginning-of-line)
3007	  (while (re-search-forward "\\\\\\([a-z]*ref\\|cite\\){" nil t)
3008	    (if (< (point-end-of-line)
3009		   (save-excursion (forward-char -1) (forward-list 1) (point)))
3010		(progn (end-of-line)
3011		       (if (save-excursion
3012			     (backward-word 1)
3013			     (looking-at "[^0-9A-z!-)]"))
3014			   (insert YaTeX-comment-prefix)))))
3015	  ;; Nonbreak space `~'
3016	  (goto-char (point-min))
3017	  (while (YaTeX-re-search-active-forward
3018		  "~\\(\\s *\\)$" YaTeX-comment-prefix (point-max) t)
3019	    (delete-region (match-beginning 1) (match-end 1))
3020	    (insert YaTeX-comment-prefix))
3021	  (goto-char (point-min))
3022	  (if (and NTT-jTeX (looking-at "[ \t]\\|^$"))
3023	      (progn
3024		(goto-char (point-min))
3025		(while (not (eobp))
3026		  (end-of-line)
3027		  (or (bolp)
3028		      (save-excursion
3029			(backward-word 1)
3030			(looking-at "[0-9A-z!-)]")) ;is not japanese string
3031		      (progn (setq p (point)) (insert YaTeX-comment-prefix)))
3032		  (forward-line 1))
3033		(goto-char p)
3034		(if (looking-at "%") (delete-char 1)) ;remove last inserted `%'
3035		))))))))
3036
3037(if (fboundp 'YaTeX-saved-indent-new-comment-line) nil
3038  (fset 'YaTeX-saved-indent-new-comment-line
3039	(symbol-function 'indent-new-comment-line))
3040  (fset 'indent-new-comment-line 'YaTeX-indent-new-comment-line))
3041
3042(defun YaTeX-indent-new-comment-line (&optional soft)
3043  "Tuned `indent-new-comment-line' function for yatex.
3044See the documentation of `YaTeX-saved-indent-new-comment-line'."
3045  (interactive)
3046  (cond
3047   ((or (not (memq major-mode '(yatex-mode yahtml-mode)))
3048	(string-match
3049	 "document"
3050	 (or (and (boundp 'inenv) inenv)
3051	     (or (YaTeX-inner-environment t) "document"))))
3052    (apply 'YaTeX-saved-indent-new-comment-line (if soft (list soft))))
3053;   ((and (eq major-mode 'yahtml-mode)
3054;	 (string-match
3055;	  "^[Pp][Rr][Ee]" (yahtml-inner-environment-but "^[Aa]\\b" t)))
3056;    (yahtml-indent-new-commnet-line))
3057   ((and (eq major-mode 'yatex-mode)	;1997/2/4
3058	 (YaTeX-in-math-mode-p)) nil)		;1996/12/30
3059   (t (let (fill-prefix)
3060	(apply 'YaTeX-saved-indent-new-comment-line (if soft (list soft)))))))
3061
3062(defun YaTeX-fill-* ()
3063  "Fill paragraph according to its condition."
3064  (interactive)
3065  (cond
3066   ((YaTeX-fill-item))
3067   ))
3068
3069;; Accent completion
3070(defun YaTeX-read-accent-char (x)
3071  "Read char in accent braces."
3072  (let ((c (read-char)))
3073    (concat
3074     (if (and (or (= c ?i) (= c ?j))
3075	      (not (string-match (regexp-quote x) "cdb")))
3076	 "\\" "")
3077     (char-to-string c))))
3078
3079(defun YaTeX-make-accent ()
3080  "Make accent usage."
3081  (interactive)
3082  (message "1:` 2:' 3:^ 4:\" 5:~ 6:= 7:. u v H t c d b")
3083  (let ((c (read-char))(case-fold-search nil))
3084    (setq c (cond ((and (> c ?0) (< c ?8))
3085		   (substring "`'^\"~=." (1- (- c ?0)) (- c ?0)))
3086		  ((= c ?h) "H")
3087		  (t (char-to-string c))))
3088    (if (not (string-match c "`'^\"~=.uvHtcdb")) nil
3089      (insert "\\" c "{}")
3090      (backward-char 1)
3091      (insert (YaTeX-read-accent-char c))
3092      (if (string= c "t") (insert (YaTeX-read-accent-char c)))
3093      (forward-char 1))))
3094
3095;; Field skip in tabular
3096(defun YaTeX-forward-field (arg)
3097  "Move forward to the ARGth next column field of table."
3098  (interactive "p")
3099  (if (< arg 0)
3100      (YaTeX-backward-field (- arg))
3101    (let ((ep (save-excursion (YaTeX-end-of-environment) (point)))
3102	  (wc (car (YaTeX-array-what-column-internal))))
3103      (while (>= (setq arg (1- arg)) 0)
3104	(skip-chars-forward "^&\\\\")
3105	(while (and (not (eobp))
3106		    (> ep (point))
3107		    (looking-at "\\&\\|\\\\")
3108		    (= wc (car (YaTeX-array-what-column-internal))))
3109	  (skip-chars-forward "&" ep)
3110	  (while (looking-at "[\n\t ]+\\|\\\\\\\\\\|\\\\.line\\>")
3111	    (goto-char (match-end 0))
3112	    ))))))
3113
3114(defun YaTeX-backward-field (arg)
3115  "Move backward to the ARGth next column field of table."
3116  (interactive "p")
3117  (if (< arg 0)
3118      (YaTeX-forward-field (- arg))
3119    (let ((bp (save-excursion
3120		(YaTeX-beginning-of-environment)
3121		(point-end-of-line)))
3122	  (wc (car (YaTeX-array-what-column-internal))))
3123      (while (>= (setq arg (1- arg)) 0)
3124	(skip-chars-backward "^&\\\\" bp)
3125	(while (and (not (bobp))
3126		    (< bp (point))
3127		    (memq (preceding-char) '(?& ?\\))
3128		    (= wc (car (YaTeX-array-what-column-internal))))
3129	  (skip-chars-backward "&\\\\" bp)
3130	  (skip-chars-backward "\n\t " bp))
3131	(if (eolp) (skip-chars-forward "^&\\\\"))))))
3132
3133;; Indentation
3134(defun YaTeX-current-indentation ()
3135  "Return the indentation of current environment."
3136  (save-excursion
3137    ;;(beginning-of-line)
3138    (if (YaTeX-beginning-of-environment t)
3139	(goto-char (get 'YaTeX-inner-environment 'point))
3140      (forward-line -1)
3141      (beginning-of-line)
3142      (skip-chars-forward " \t"))
3143    (current-column)))
3144
3145(defun YaTeX-previous-line-indentation ()
3146  (save-excursion
3147    (forward-line -1)
3148    (skip-chars-forward " \t")
3149    (current-column)))
3150
3151(defvar YaTeX-noindent-env-regexp "verbatim\\*?\\|alltt"
3152  "*Regexp of environment names that should begin with no indentation.
3153All verbatime-like environment name should match with.")
3154(defun YaTeX-indent-line ()
3155  "Indent corrent line referrin current environment."
3156  (interactive)
3157  (let ((indent-relative
3158	 (function
3159	  (lambda (&optional additional)
3160	    (YaTeX-reindent
3161	     (+ (YaTeX-current-indentation)
3162		(or additional 0)
3163		YaTeX-environment-indent)))))
3164	sect depth iteminfo (p (point)) pp (peol (point-end-of-line)) begend
3165	;;inenv below is sometimes defined in YaTeX-indent-new-comment-line
3166	(inenv (or (and (boundp 'inenv) inenv) (YaTeX-inner-environment t))))
3167    ;;(if NTT-jTeX		;;Do you need this section?
3168    ;;	(save-excursion
3169    ;;  (end-of-line)
3170    ;;  (let ((p (point)))
3171    ;;    (forward-line -1)
3172    ;;    (end-of-line)
3173    ;;    (or (= p (point))
3174    ;;	(progn (backward-char (length YaTeX-comment-prefix))
3175    ;;	       (not (looking-at (regexp-quote YaTeX-comment-prefix))))
3176    ;;	(progn
3177    ;;	  (skip-chars-backward YaTeX-comment-prefix)
3178    ;;	  (kill-line))))))
3179    (or inenv (setq inenv "document"))	;is the default environment
3180    (cond
3181     ((and
3182       (prog1 (YaTeX-on-begin-end-p)
3183	 (setq begend (match-beginning 0)))
3184       (or (match-beginning 2)		;if \end
3185	   (and (match-beginning 3)	;if \) \]
3186		(= (char-syntax (char-after (1+ (match-beginning 3)))) ?\)))))
3187      (YaTeX-reindent
3188       (save-excursion
3189	 (YaTeX-goto-corresponding-environment)
3190	 (current-column))))
3191     ;; on the begining of verbatime line, remove all indentation
3192     ((and begend ;; match-beginning 0 of \begin
3193	   YaTeX-noindent-env-regexp
3194	   (stringp YaTeX-noindent-env-regexp)
3195	   (save-excursion
3196	     (and ;; if the \begin is the first declaration of this line
3197	      (progn (beginning-of-line) (skip-chars-forward " \t")
3198		     (= begend (point)))
3199	      (progn
3200		(goto-char begend)
3201		(looking-at
3202		 (concat YaTeX-ec-regexp
3203			 "begin{\\(" YaTeX-noindent-env-regexp "\\)}"))))))
3204      (save-excursion
3205	(goto-char begend)
3206	(delete-region (point) (point-beginning-of-line))))
3207     ((string-match YaTeX-equation-env-regexp inenv)
3208      (YaTeX-indent-line-equation))	;autoload-ed from yatexenv
3209     (;(YaTeX-in-environment-p '("itemize" "enumerate" "description" "list"))
3210      (string-match YaTeX-itemizing-env-regexp inenv)
3211      ;;(YaTeX-on-item-p) ??
3212      ;;(setq iteminfo (YaTeX-get-item-info t))
3213      (if (save-excursion
3214	    (beginning-of-line)
3215	    (re-search-forward YaTeX-item-regexp peol t))
3216	  (progn
3217	    (save-excursion
3218	      (goto-char (1+ (match-beginning 0)))
3219	      (setq depth
3220		    (* YaTeX-environment-indent
3221		       (cond
3222			((looking-at "subsubsub")	3)
3223			((looking-at "subsub")	2)
3224			((looking-at "sub")	1)
3225			(t			0)))))
3226	    (funcall indent-relative depth))
3227	(YaTeX-reindent (or (car (cdr (YaTeX-get-item-info t inenv)))
3228			    (+ (save-excursion
3229				 (beginning-of-line)
3230				 (YaTeX-current-indentation))
3231			       YaTeX-environment-indent))))
3232      )
3233     ((YaTeX-literal-p)			;verbatims
3234      (tab-to-tab-stop))
3235     ((string-match "\\(tabular\\|array\\)" inenv) ;1.73
3236      (let ((n 1) (cc (current-column)) (p (point)))
3237	(condition-case err
3238	    (save-excursion
3239	      (beginning-of-line)
3240	      (skip-chars-forward "[ \t]")
3241	      ;;(if (looking-at "&") (forward-char 1))
3242	      (require 'yatexenv)
3243	      (setq n (car (YaTeX-array-what-column-internal))))
3244	  (error nil))
3245	(YaTeX-reindent
3246	 (+ (YaTeX-current-indentation)
3247	    YaTeX-environment-indent
3248	    (* (1- n) YaTeX-tabular-indentation)))
3249	(and (= cc (current-column))
3250	     (= p (point))
3251	     (equal last-command 'YaTeX-indent-line)
3252	     ;; if NO indent action occured, move to the next column
3253	     (YaTeX-forward-field 1))))
3254     ((and inenv (not (equal "document" inenv)))
3255      (funcall indent-relative))
3256     ((YaTeX-on-section-command-p YaTeX-sectioning-regexp)
3257      (require 'yatexsec)		;to know YaTeX-sectioning-level
3258      (setq sect (YaTeX-match-string 1))
3259      (if (string-match "\\*$" sect)
3260	  (setq sect (substring sect 0 -1)))
3261      (YaTeX-reindent
3262       (* (max
3263	   (1-				;I want chapter to have indentation 0
3264	    (or (cdr (assoc sect YaTeX-sectioning-level))
3265		0))
3266	   0)
3267	  YaTeX-environment-indent)))
3268     ;;Default movement
3269     ((and (bolp) fill-prefix) (insert fill-prefix))
3270     (t (save-excursion
3271	  (beginning-of-line)
3272	  (if fill-prefix
3273	      (progn
3274		(delete-region (point)
3275			       (progn (skip-chars-forward " \t")
3276				      (point)))
3277		(insert fill-prefix))
3278	    (skip-chars-forward " \t")
3279	    (if (bobp)
3280		nil
3281	      (indent-relative-maybe))))
3282	(skip-chars-forward " \t")))
3283    ;;if current line is \begin, re-indent \end too
3284    (if (and (YaTeX-on-begin-end-p) (match-beginning 1))
3285	(save-excursion
3286	  ;;(beginning-of-line)
3287	  ;;(search-forward "\\begin")
3288	  (goto-char (match-beginning 0))
3289	  (setq depth (current-column))
3290	  (YaTeX-goto-corresponding-environment)
3291	  (YaTeX-reindent depth)))
3292    (if (or
3293	 (and NTT-jTeX
3294	      (save-excursion (beginning-of-line) (looking-at "[ \t]")))
3295	 (save-excursion
3296	   (beginning-of-line)
3297	   (and
3298	    (not (bobp))
3299	    (progn
3300	      (backward-char 1)
3301	      (re-search-backward
3302	       "\\\\\\(\\(page\\)?ref\\|cite\\){" (point-beginning-of-line) t))
3303	    (goto-char (1- (match-end 0)))
3304	    (> (save-excursion
3305		 (condition-case ()
3306		     (progn (forward-list 1) (point))
3307		   (error (point-max))))
3308	       (point-end-of-line)))))
3309	(save-excursion
3310	  (end-of-line)
3311	  (let ((p (point)))
3312	    (forward-line -1)
3313	    (end-of-line)
3314	    (or (= p (point))
3315		(looking-at (regexp-quote YaTeX-comment-prefix))
3316		(bobp) (bolp)
3317		(save-excursion
3318		  (backward-word 1)
3319		  (looking-at "\\sw+")) ;is not japanese string
3320		(insert YaTeX-comment-prefix)))))))
3321
3322(defun YaTeX-comment-line-break (&optional soft)
3323  "Call comment-indent-new-line and YaTeX-indent-line"
3324  (comment-indent-new-line soft)
3325  (YaTeX-indent-line))
3326
3327(defun YaTeX-latex2e-p ()
3328  (let ((b (current-buffer))
3329	(ptn (concat YaTeX-ec "documentclass")))
3330    (unwind-protect
3331	(or (save-excursion (search-backward ptn nil t))
3332	    (progn
3333	      (YaTeX-visit-main t)
3334	      (save-excursion (search-backward ptn nil t))))
3335      (set-buffer b))))
3336
3337(provide 'yatex)
3338(defvar yatex-mode-load-hook nil
3339  "*List of functions to be called when yatex.el is loaded.")
3340(if (and YaTeX-emacs-19 YaTeX-display-color-p (not (featurep 'yatex19)))
3341    (load "yatex19"))
3342(load "yatexhks" t)
3343
3344;;-------------------- Final hook jobs --------------------
3345(substitute-all-key-definition
3346 'fill-paragraph 'YaTeX-fill-paragraph YaTeX-mode-map)
3347(substitute-all-key-definition
3348 'kill-buffer 'YaTeX-kill-buffer YaTeX-mode-map)
3349(run-hooks 'yatex-mode-load-hook)
3350
3351;; `History' was moved to ChangeLog
3352;----------------------------- End of yatex.el -----------------------------
3353