tex-mode.el 108 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879
  1. ;;; tex-mode.el --- TeX, LaTeX, and SliTeX mode commands -*- coding: utf-8 -*-
  2. ;; Copyright (C) 1985-1986, 1989, 1992, 1994-1999, 2001-2012
  3. ;; Free Software Foundation, Inc.
  4. ;; Maintainer: FSF
  5. ;; Keywords: tex
  6. ;; Contributions over the years by William F. Schelter, Dick King,
  7. ;; Stephen Gildea, Michael Prange, Jacob Gore, and Edward M. Reingold.
  8. ;; This file is part of GNU Emacs.
  9. ;; GNU Emacs is free software: you can redistribute it and/or modify
  10. ;; it under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation, either version 3 of the License, or
  12. ;; (at your option) any later version.
  13. ;; GNU Emacs is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;; You should have received a copy of the GNU General Public License
  18. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  19. ;;; Commentary:
  20. ;;; Code:
  21. ;; Pacify the byte-compiler
  22. (eval-when-compile
  23. (require 'compare-w)
  24. (require 'cl)
  25. (require 'skeleton))
  26. (defvar font-lock-comment-face)
  27. (defvar font-lock-doc-face)
  28. (require 'shell)
  29. (require 'compile)
  30. (defgroup tex-file nil
  31. "TeX files and directories."
  32. :prefix "tex-"
  33. :group 'tex)
  34. (defgroup tex-run nil
  35. "Running external commands from TeX mode."
  36. :prefix "tex-"
  37. :group 'tex)
  38. (defgroup tex-view nil
  39. "Viewing and printing TeX files."
  40. :prefix "tex-"
  41. :group 'tex)
  42. ;;;###autoload
  43. (defcustom tex-shell-file-name nil
  44. "If non-nil, the shell file name to run in the subshell used to run TeX."
  45. :type '(choice (const :tag "None" nil)
  46. string)
  47. :group 'tex-run)
  48. ;;;###autoload
  49. (defcustom tex-directory (purecopy ".")
  50. "Directory in which temporary files are written.
  51. You can make this `/tmp' if your TEXINPUTS has no relative directories in it
  52. and you don't try to apply \\[tex-region] or \\[tex-buffer] when there are
  53. `\\input' commands with relative directories."
  54. :type 'directory
  55. :group 'tex-file)
  56. ;;;###autoload
  57. (defcustom tex-first-line-header-regexp nil
  58. "Regexp for matching a first line which `tex-region' should include.
  59. If this is non-nil, it should be a regular expression string;
  60. if it matches the first line of the file,
  61. `tex-region' always includes the first line in the TeX run."
  62. :type '(choice (const :tag "None" nil)
  63. regexp)
  64. :group 'tex-file)
  65. ;;;###autoload
  66. (defcustom tex-main-file nil
  67. "The main TeX source file which includes this buffer's file.
  68. The command `tex-file' runs TeX on the file specified by `tex-main-file'
  69. if the variable is non-nil."
  70. :type '(choice (const :tag "None" nil)
  71. file)
  72. :group 'tex-file)
  73. ;;;###autoload
  74. (defcustom tex-offer-save t
  75. "If non-nil, ask about saving modified buffers before \\[tex-file] is run."
  76. :type 'boolean
  77. :group 'tex-file)
  78. ;;;###autoload
  79. (defcustom tex-run-command (purecopy "tex")
  80. "Command used to run TeX subjob.
  81. TeX Mode sets `tex-command' to this string.
  82. See the documentation of that variable."
  83. :type 'string
  84. :group 'tex-run)
  85. ;;;###autoload
  86. (defcustom latex-run-command (purecopy "latex")
  87. "Command used to run LaTeX subjob.
  88. LaTeX Mode sets `tex-command' to this string.
  89. See the documentation of that variable."
  90. :type 'string
  91. :group 'tex-run)
  92. ;;;###autoload
  93. (defcustom slitex-run-command (purecopy "slitex")
  94. "Command used to run SliTeX subjob.
  95. SliTeX Mode sets `tex-command' to this string.
  96. See the documentation of that variable."
  97. :type 'string
  98. :group 'tex-run)
  99. ;;;###autoload
  100. (defcustom tex-start-options (purecopy "")
  101. "TeX options to use when starting TeX.
  102. These immediately precede the commands in `tex-start-commands'
  103. and the input file name, with no separating space and are not shell-quoted.
  104. If nil, TeX runs with no options. See the documentation of `tex-command'."
  105. :type 'string
  106. :group 'tex-run
  107. :version "22.1")
  108. ;;;###autoload
  109. (defcustom tex-start-commands (purecopy "\\nonstopmode\\input")
  110. "TeX commands to use when starting TeX.
  111. They are shell-quoted and precede the input file name, with a separating space.
  112. If nil, no commands are used. See the documentation of `tex-command'."
  113. :type '(radio (const :tag "Interactive \(nil\)" nil)
  114. (const :tag "Nonstop \(\"\\nonstopmode\\input\"\)"
  115. "\\nonstopmode\\input")
  116. (string :tag "String at your choice"))
  117. :group 'tex-run
  118. :version "22.1")
  119. (defvar latex-standard-block-names
  120. '("abstract" "array" "center" "description"
  121. "displaymath" "document" "enumerate" "eqnarray"
  122. "eqnarray*" "equation" "figure" "figure*"
  123. "flushleft" "flushright" "itemize" "letter"
  124. "list" "minipage" "picture" "quotation"
  125. "quote" "slide" "sloppypar" "tabbing"
  126. "table" "table*" "tabular" "tabular*"
  127. "thebibliography" "theindex*" "titlepage" "trivlist"
  128. "verbatim" "verbatim*" "verse" "math")
  129. "Standard LaTeX block names.")
  130. ;;;###autoload
  131. (defcustom latex-block-names nil
  132. "User defined LaTeX block names.
  133. Combined with `latex-standard-block-names' for minibuffer completion."
  134. :type '(repeat string)
  135. :group 'tex-run)
  136. ;;;###autoload
  137. (defcustom tex-bibtex-command (purecopy "bibtex")
  138. "Command used by `tex-bibtex-file' to gather bibliographic data.
  139. If this string contains an asterisk (`*'), that is replaced by the file name;
  140. otherwise, the file name, preceded by blank, is added at the end."
  141. :type 'string
  142. :group 'tex-run)
  143. ;;;###autoload
  144. (defcustom tex-dvi-print-command (purecopy "lpr -d")
  145. "Command used by \\[tex-print] to print a .dvi file.
  146. If this string contains an asterisk (`*'), that is replaced by the file name;
  147. otherwise, the file name, preceded by blank, is added at the end."
  148. :type 'string
  149. :group 'tex-view)
  150. ;;;###autoload
  151. (defcustom tex-alt-dvi-print-command (purecopy "lpr -d")
  152. "Command used by \\[tex-print] with a prefix arg to print a .dvi file.
  153. If this string contains an asterisk (`*'), that is replaced by the file name;
  154. otherwise, the file name, preceded by blank, is added at the end.
  155. If two printers are not enough of a choice, you can set the variable
  156. `tex-alt-dvi-print-command' to an expression that asks what you want;
  157. for example,
  158. (setq tex-alt-dvi-print-command
  159. '(format \"lpr -P%s\" (read-string \"Use printer: \")))
  160. would tell \\[tex-print] with a prefix argument to ask you which printer to
  161. use."
  162. :type '(choice (string :tag "Command")
  163. (sexp :tag "Expression"))
  164. :group 'tex-view)
  165. ;;;###autoload
  166. (defcustom tex-dvi-view-command
  167. `(cond
  168. ((eq window-system 'x) ,(purecopy "xdvi"))
  169. ((eq window-system 'w32) ,(purecopy "yap"))
  170. (t ,(purecopy "dvi2tty * | cat -s")))
  171. "Command used by \\[tex-view] to display a `.dvi' file.
  172. If it is a string, that specifies the command directly.
  173. If this string contains an asterisk (`*'), that is replaced by the file name;
  174. otherwise, the file name, preceded by a space, is added at the end.
  175. If the value is a form, it is evaluated to get the command to use."
  176. :type '(choice (const nil) string sexp)
  177. :group 'tex-view)
  178. ;;;###autoload
  179. (defcustom tex-show-queue-command (purecopy "lpq")
  180. "Command used by \\[tex-show-print-queue] to show the print queue.
  181. Should show the queue(s) that \\[tex-print] puts jobs on."
  182. :type 'string
  183. :group 'tex-view)
  184. ;;;###autoload
  185. (defcustom tex-default-mode 'latex-mode
  186. "Mode to enter for a new file that might be either TeX or LaTeX.
  187. This variable is used when it can't be determined whether the file
  188. is plain TeX or LaTeX or what because the file contains no commands.
  189. Normally set to either `plain-tex-mode' or `latex-mode'."
  190. :type 'function
  191. :group 'tex)
  192. ;;;###autoload
  193. (defcustom tex-open-quote (purecopy "``")
  194. "String inserted by typing \\[tex-insert-quote] to open a quotation."
  195. :type 'string
  196. :options '("``" "\"<" "\"`" "<<" "«")
  197. :group 'tex)
  198. ;;;###autoload
  199. (defcustom tex-close-quote (purecopy "''")
  200. "String inserted by typing \\[tex-insert-quote] to close a quotation."
  201. :type 'string
  202. :options '("''" "\">" "\"'" ">>" "»")
  203. :group 'tex)
  204. (defcustom tex-fontify-script t
  205. "If non-nil, fontify subscript and superscript strings."
  206. :type 'boolean
  207. :group 'tex
  208. :version "23.1")
  209. (put 'tex-fontify-script 'safe-local-variable 'booleanp)
  210. (defcustom tex-font-script-display '(-0.2 0.2)
  211. "How much to lower and raise subscript and superscript content.
  212. This is a list of two floats. The first is negative and
  213. specifies how much subscript is lowered, the second is positive
  214. and specifies how much superscript is raised. Heights are
  215. measured relative to that of the normal text."
  216. :group 'tex
  217. :type '(list (float :tag "Subscript")
  218. (float :tag "Superscript"))
  219. :version "23.1")
  220. (defvar tex-last-temp-file nil
  221. "Latest temporary file generated by \\[tex-region] and \\[tex-buffer].
  222. Deleted when the \\[tex-region] or \\[tex-buffer] is next run, or when the
  223. tex shell terminates.")
  224. (defvar tex-command "tex"
  225. "*Command to run TeX.
  226. If this string contains an asterisk \(`*'\), that is replaced by the file name;
  227. otherwise the value of `tex-start-options', the \(shell-quoted\)
  228. value of `tex-start-commands', and the file name are added at the end
  229. with blanks as separators.
  230. In TeX, LaTeX, and SliTeX Mode this variable becomes buffer local.
  231. In these modes, use \\[set-variable] if you want to change it for the
  232. current buffer.")
  233. (defvar tex-trailer nil
  234. "String appended after the end of a region sent to TeX by \\[tex-region].")
  235. (defvar tex-start-of-header nil
  236. "Regular expression used by \\[tex-region] to find start of file's header.")
  237. (defvar tex-end-of-header nil
  238. "Regular expression used by \\[tex-region] to find end of file's header.")
  239. (defvar tex-shell-cd-command "cd"
  240. "Command to give to shell running TeX to change directory.
  241. The value of `tex-directory' is appended to this, separated by a space.")
  242. (defvar tex-zap-file nil
  243. "Temporary file name used for text being sent as input to TeX.
  244. Should be a simple file name with no extension or directory specification.")
  245. (defvar tex-last-buffer-texed nil
  246. "Buffer which was last TeXed.")
  247. (defvar tex-print-file nil
  248. "File name that \\[tex-print] prints.
  249. Set by \\[tex-region], \\[tex-buffer], and \\[tex-file].")
  250. (defvar tex-mode-syntax-table
  251. (let ((st (make-syntax-table)))
  252. (modify-syntax-entry ?% "<" st)
  253. (modify-syntax-entry ?\n ">" st)
  254. (modify-syntax-entry ?\f ">" st)
  255. (modify-syntax-entry ?\C-@ "w" st)
  256. (modify-syntax-entry ?' "w" st)
  257. (modify-syntax-entry ?@ "_" st)
  258. (modify-syntax-entry ?* "_" st)
  259. (modify-syntax-entry ?\t " " st)
  260. ;; ~ is printed by TeX as a space, but it's semantics in the syntax
  261. ;; of TeX is not `whitespace' (i.e. it's just like \hspace{foo}).
  262. (modify-syntax-entry ?~ "." st)
  263. (modify-syntax-entry ?$ "$$" st)
  264. (modify-syntax-entry ?\\ "/" st)
  265. (modify-syntax-entry ?\" "." st)
  266. (modify-syntax-entry ?& "." st)
  267. (modify-syntax-entry ?_ "." st)
  268. (modify-syntax-entry ?^ "." st)
  269. st)
  270. "Syntax table used while in TeX mode.")
  271. ;;;;
  272. ;;;; Imenu support
  273. ;;;;
  274. (defcustom latex-imenu-indent-string ". "
  275. "String to add repeated in front of nested sectional units for Imenu.
  276. An alternative value is \" . \", if you use a font with a narrow period."
  277. :type 'string
  278. :group 'tex)
  279. (defvar latex-section-alist
  280. '(("part" . 0) ("chapter" . 1)
  281. ("section" . 2) ("subsection" . 3)
  282. ("subsubsection" . 4)
  283. ("paragraph" . 5) ("subparagraph" . 6)))
  284. (defvar latex-metasection-list
  285. '("documentstyle" "documentclass"
  286. "begin{document}" "end{document}"
  287. "appendix" "frontmatter" "mainmatter" "backmatter"))
  288. (defun latex-imenu-create-index ()
  289. "Generate an alist for imenu from a LaTeX buffer."
  290. (let ((section-regexp
  291. (concat "\\\\" (regexp-opt (mapcar 'car latex-section-alist) t)
  292. "\\*?[ \t]*{"))
  293. (metasection-regexp
  294. (concat "\\\\" (regexp-opt latex-metasection-list t)))
  295. i0 menu case-fold-search)
  296. (save-excursion
  297. ;; Find the top-most level in this file but don't allow it to be
  298. ;; any deeper than "section" (which is top-level in an article).
  299. (goto-char (point-min))
  300. (if (search-forward-regexp "\\\\part\\*?[ \t]*{" nil t)
  301. (setq i0 0)
  302. (if (search-forward-regexp "\\\\chapter\\*?[ \t]*{" nil t)
  303. (setq i0 1)
  304. (setq i0 2)))
  305. ;; Look for chapters and sections.
  306. (goto-char (point-min))
  307. (while (search-forward-regexp section-regexp nil t)
  308. (let ((start (match-beginning 0))
  309. (here (point))
  310. (i (cdr (assoc (buffer-substring-no-properties
  311. (match-beginning 1)
  312. (match-end 1))
  313. latex-section-alist))))
  314. (backward-char 1)
  315. (condition-case err
  316. (progn
  317. ;; Using sexps allows some use of matching {...} inside
  318. ;; titles.
  319. (forward-sexp 1)
  320. (push (cons (concat (apply 'concat
  321. (make-list
  322. (max 0 (- i i0))
  323. latex-imenu-indent-string))
  324. (buffer-substring-no-properties
  325. here (1- (point))))
  326. start)
  327. menu))
  328. (error nil))))
  329. ;; Look for included material.
  330. (goto-char (point-min))
  331. (while (search-forward-regexp
  332. "\\\\\\(include\\|input\\|verbatiminput\\|bibliography\\)\
  333. \[ \t]*{\\([^}\n]+\\)}"
  334. nil t)
  335. (push (cons (concat "<<" (buffer-substring-no-properties
  336. (match-beginning 2)
  337. (match-end 2))
  338. (if (= (char-after (match-beginning 1)) ?b)
  339. ".bbl"
  340. ".tex"))
  341. (match-beginning 0))
  342. menu))
  343. ;; Look for \frontmatter, \mainmatter, \backmatter, and \appendix.
  344. (goto-char (point-min))
  345. (while (search-forward-regexp metasection-regexp nil t)
  346. (push (cons "--" (match-beginning 0)) menu))
  347. ;; Sort in increasing buffer position order.
  348. (sort menu (function (lambda (a b) (< (cdr a) (cdr b))))))))
  349. ;;;;
  350. ;;;; Outline support
  351. ;;;;
  352. (defvar latex-outline-regexp
  353. (concat "\\\\"
  354. (regexp-opt (append latex-metasection-list
  355. (mapcar 'car latex-section-alist)) t)))
  356. (defun latex-outline-level ()
  357. (if (looking-at latex-outline-regexp)
  358. (1+ (or (cdr (assoc (match-string 1) latex-section-alist)) -1))
  359. 1000))
  360. ;;;;
  361. ;;;; Font-Lock support
  362. ;;;;
  363. ;(defvar tex-font-lock-keywords
  364. ; ;; Regexps updated with help from Ulrik Dickow <dickow@nbi.dk>.
  365. ; '(("\\\\\\(begin\\|end\\|newcommand\\){\\([a-zA-Z0-9\\*]+\\)}"
  366. ; 2 font-lock-function-name-face)
  367. ; ("\\\\\\(cite\\|label\\|pageref\\|ref\\){\\([^} \t\n]+\\)}"
  368. ; 2 font-lock-constant-face)
  369. ; ;; It seems a bit dubious to use `bold' and `italic' faces since we might
  370. ; ;; not be able to display those fonts.
  371. ; ("{\\\\bf\\([^}]+\\)}" 1 'bold keep)
  372. ; ("{\\\\\\(em\\|it\\|sl\\)\\([^}]+\\)}" 2 'italic keep)
  373. ; ("\\\\\\([a-zA-Z@]+\\|.\\)" . font-lock-keyword-face)
  374. ; ("^[ \t\n]*\\\\def[\\\\@]\\(\\w+\\)" 1 font-lock-function-name-face keep))
  375. ; ;; Rewritten and extended for LaTeX2e by Ulrik Dickow <dickow@nbi.dk>.
  376. ; '(("\\\\\\(begin\\|end\\|newcommand\\){\\([a-zA-Z0-9\\*]+\\)}"
  377. ; 2 font-lock-function-name-face)
  378. ; ("\\\\\\(cite\\|label\\|pageref\\|ref\\){\\([^} \t\n]+\\)}"
  379. ; 2 font-lock-constant-face)
  380. ; ("^[ \t]*\\\\def\\\\\\(\\(\\w\\|@\\)+\\)" 1 font-lock-function-name-face)
  381. ; "\\\\\\([a-zA-Z@]+\\|.\\)"
  382. ; ;; It seems a bit dubious to use `bold' and `italic' faces since we might
  383. ; ;; not be able to display those fonts.
  384. ; ;; LaTeX2e: \emph{This is emphasized}.
  385. ; ("\\\\emph{\\([^}]+\\)}" 1 'italic keep)
  386. ; ;; LaTeX2e: \textbf{This is bold}, \textit{...}, \textsl{...}
  387. ; ("\\\\text\\(\\(bf\\)\\|it\\|sl\\){\\([^}]+\\)}"
  388. ; 3 (if (match-beginning 2) 'bold 'italic) keep)
  389. ; ;; Old-style bf/em/it/sl. Stop at `\\' and un-escaped `&', for tables.
  390. ; ("\\\\\\(\\(bf\\)\\|em\\|it\\|sl\\)\\>\\(\\([^}&\\]\\|\\\\[^\\]\\)+\\)"
  391. ; 3 (if (match-beginning 2) 'bold 'italic) keep))
  392. ;; Rewritten with the help of Alexandra Bac <abac@welcome.disi.unige.it>.
  393. (defconst tex-font-lock-keywords-1
  394. (eval-when-compile
  395. (let* (;; Names of commands whose arg should be fontified as heading, etc.
  396. (headings (regexp-opt
  397. '("title" "begin" "end" "chapter" "part"
  398. "section" "subsection" "subsubsection"
  399. "paragraph" "subparagraph" "subsubparagraph"
  400. "newcommand" "renewcommand" "providecommand"
  401. "newenvironment" "renewenvironment"
  402. "newtheorem" "renewtheorem")
  403. t))
  404. (variables (regexp-opt
  405. '("newcounter" "newcounter*" "setcounter" "addtocounter"
  406. "setlength" "addtolength" "settowidth")
  407. t))
  408. (includes (regexp-opt
  409. '("input" "include" "includeonly" "bibliography"
  410. "epsfig" "psfig" "epsf" "nofiles" "usepackage"
  411. "documentstyle" "documentclass" "verbatiminput"
  412. "includegraphics" "includegraphics*"
  413. "url" "nolinkurl")
  414. t))
  415. ;; Miscellany.
  416. (slash "\\\\")
  417. (opt " *\\(\\[[^]]*\\] *\\)*")
  418. ;; This would allow highlighting \newcommand\CMD but requires
  419. ;; adapting subgroup numbers below.
  420. ;; (arg "\\(?:{\\(\\(?:[^{}\\]+\\|\\\\.\\|{[^}]*}\\)+\\)\\|\\\\[a-z*]+\\)"))
  421. (arg "{\\(\\(?:[^{}\\]+\\|\\\\.\\|{[^}]*}\\)+\\)"))
  422. (list
  423. ;; display $$ math $$
  424. ;; We only mark the match between $$ and $$ because the $$ delimiters
  425. ;; themselves have already been marked (along with $..$) by syntactic
  426. ;; fontification. Also this is done at the very beginning so as to
  427. ;; interact with the other keywords in the same way as $...$ does.
  428. (list "\\$\\$\\([^$]+\\)\\$\\$" 1 'tex-math-face)
  429. ;; Heading args.
  430. (list (concat slash headings "\\*?" opt arg)
  431. ;; If ARG ends up matching too much (if the {} don't match, e.g.)
  432. ;; jit-lock will do funny things: when updating the buffer
  433. ;; the re-highlighting is only done locally so it will just
  434. ;; match the local line, but defer-contextually will
  435. ;; match more lines at a time, so ARG will end up matching
  436. ;; a lot more, which might suddenly include a comment
  437. ;; so you get things highlighted bold when you type them
  438. ;; but they get turned back to normal a little while later
  439. ;; because "there's already a face there".
  440. ;; Using `keep' works around this un-intuitive behavior as well
  441. ;; as improves the behavior in the very rare case where you do
  442. ;; have a comment in ARG.
  443. 3 'font-lock-function-name-face 'keep)
  444. (list (concat slash "\\(?:provide\\|\\(?:re\\)?new\\)command\\** *\\(\\\\[A-Za-z@]+\\)")
  445. 1 'font-lock-function-name-face 'keep)
  446. ;; Variable args.
  447. (list (concat slash variables " *" arg) 2 'font-lock-variable-name-face)
  448. ;; Include args.
  449. (list (concat slash includes opt arg) 3 'font-lock-builtin-face)
  450. ;; Definitions. I think.
  451. '("^[ \t]*\\\\def *\\\\\\(\\(\\w\\|@\\)+\\)"
  452. 1 font-lock-function-name-face))))
  453. "Subdued expressions to highlight in TeX modes.")
  454. (defun tex-font-lock-append-prop (prop)
  455. (unless (memq (get-text-property (match-end 1) 'face)
  456. '(font-lock-comment-face tex-verbatim))
  457. prop))
  458. (defconst tex-font-lock-keywords-2
  459. (append tex-font-lock-keywords-1
  460. (eval-when-compile
  461. (let* (;;
  462. ;; Names of commands whose arg should be fontified with fonts.
  463. (bold (regexp-opt '("textbf" "textsc" "textup"
  464. "boldsymbol" "pmb") t))
  465. (italic (regexp-opt '("textit" "textsl" "emph") t))
  466. ;; FIXME: unimplemented yet.
  467. ;; (type (regexp-opt '("texttt" "textmd" "textrm" "textsf") t))
  468. ;;
  469. ;; Names of commands whose arg should be fontified as a citation.
  470. (citations (regexp-opt
  471. '("label" "ref" "pageref" "vref" "eqref"
  472. "cite" "nocite" "index" "glossary" "bibitem"
  473. ;; natbib's two variants of \cite:
  474. "citep" "citet"
  475. ;; These are text, rather than citations.
  476. ;; "caption" "footnote" "footnotemark" "footnotetext"
  477. )
  478. t))
  479. ;;
  480. ;; Names of commands that should be fontified.
  481. (specials-1 (regexp-opt '("\\" "\\*") t)) ;; "-"
  482. (specials-2 (regexp-opt
  483. '("linebreak" "nolinebreak" "pagebreak" "nopagebreak"
  484. "newline" "newpage" "clearpage" "cleardoublepage"
  485. "displaybreak" "allowdisplaybreaks"
  486. "enlargethispage") t))
  487. (general "\\([a-zA-Z@]+\\**\\|[^ \t\n]\\)")
  488. ;;
  489. ;; Miscellany.
  490. (slash "\\\\")
  491. (opt " *\\(\\[[^]]*\\] *\\)*")
  492. (args "\\(\\(?:[^{}&\\]+\\|\\\\.\\|{[^}]*}\\)+\\)")
  493. (arg "{\\(\\(?:[^{}\\]+\\|\\\\.\\|{[^}]*}\\)+\\)"))
  494. (list
  495. ;;
  496. ;; Citation args.
  497. (list (concat slash citations opt arg) 3 'font-lock-constant-face)
  498. ;;
  499. ;; Text between `` quotes ''.
  500. (cons (concat (regexp-opt `("``" "\"<" "\"`" "<<" "«") t)
  501. "[^'\">{]+" ;a bit pessimistic
  502. (regexp-opt `("''" "\">" "\"'" ">>" "»") t))
  503. 'font-lock-string-face)
  504. ;;
  505. ;; Command names, special and general.
  506. (cons (concat slash specials-1) 'font-lock-warning-face)
  507. (list (concat "\\(" slash specials-2 "\\)\\([^a-zA-Z@]\\|\\'\\)")
  508. 1 'font-lock-warning-face)
  509. (concat slash general)
  510. ;;
  511. ;; Font environments. It seems a bit dubious to use `bold' etc. faces
  512. ;; since we might not be able to display those fonts.
  513. (list (concat slash bold " *" arg) 2
  514. '(tex-font-lock-append-prop 'bold) 'append)
  515. (list (concat slash italic " *" arg) 2
  516. '(tex-font-lock-append-prop 'italic) 'append)
  517. ;; (list (concat slash type arg) 2 '(quote bold-italic) 'append)
  518. ;;
  519. ;; Old-style bf/em/it/sl. Stop at `\\' and un-escaped `&', for tables.
  520. (list (concat "\\\\\\(em\\|it\\|sl\\)\\>" args)
  521. 2 '(tex-font-lock-append-prop 'italic) 'append)
  522. ;; This is separate from the previous one because of cases like
  523. ;; {\em foo {\bf bar} bla} where both match.
  524. (list (concat "\\\\\\(bf\\(series\\)?\\)\\>" args)
  525. 3 '(tex-font-lock-append-prop 'bold) 'append)))))
  526. "Gaudy expressions to highlight in TeX modes.")
  527. (defun tex-font-lock-suscript (pos)
  528. (unless (or (memq (get-text-property pos 'face)
  529. '(font-lock-constant-face font-lock-builtin-face
  530. font-lock-comment-face tex-verbatim))
  531. ;; Check for backslash quoting
  532. (let ((odd nil)
  533. (pos pos))
  534. (while (eq (char-before pos) ?\\)
  535. (setq pos (1- pos) odd (not odd)))
  536. odd))
  537. (if (eq (char-after pos) ?_)
  538. `(face subscript display (raise ,(car tex-font-script-display)))
  539. `(face superscript display (raise ,(cadr tex-font-script-display))))))
  540. (defun tex-font-lock-match-suscript (limit)
  541. "Match subscript and superscript patterns up to LIMIT."
  542. (when (and tex-fontify-script
  543. (re-search-forward "[_^] *\\([^\n\\{}]\\|\
  544. \\\\\\([a-zA-Z@]+\\|[^ \t\n]\\)\\|\\({\\)\\)" limit t))
  545. (when (match-end 3)
  546. (let ((beg (match-beginning 3))
  547. (end (save-restriction
  548. (narrow-to-region (point-min) limit)
  549. (condition-case nil (scan-lists (point) 1 1) (error nil)))))
  550. (store-match-data (if end
  551. (list (match-beginning 0) end beg end)
  552. (list beg beg beg beg)))))
  553. t))
  554. (defconst tex-font-lock-keywords-3
  555. (append tex-font-lock-keywords-2
  556. '((tex-font-lock-match-suscript
  557. (1 (tex-font-lock-suscript (match-beginning 0)) append))))
  558. "Experimental expressions to highlight in TeX modes.")
  559. (defvar tex-font-lock-keywords tex-font-lock-keywords-1
  560. "Default expressions to highlight in TeX modes.")
  561. (defvar tex-verbatim-environments
  562. '("verbatim" "verbatim*"))
  563. (put 'tex-verbatim-environments 'safe-local-variable
  564. (lambda (x) (null (delq t (mapcar 'stringp x)))))
  565. (eval-when-compile
  566. (defconst tex-syntax-propertize-rules
  567. (syntax-propertize-precompile-rules
  568. ("\\\\verb\\**\\([^a-z@*]\\)"
  569. (1 (prog1 "\""
  570. (tex-font-lock-verb
  571. (match-beginning 0) (char-after (match-beginning 1))))))))
  572. (defconst latex-syntax-propertize-rules
  573. (syntax-propertize-precompile-rules
  574. tex-syntax-propertize-rules
  575. ("\\\\\\(?:end\\|begin\\) *\\({[^\n{}]*}\\)"
  576. (1 (ignore
  577. (tex-env-mark (match-beginning 0)
  578. (match-beginning 1) (match-end 1))))))))
  579. (defun tex-env-mark (cmd start end)
  580. (when (= cmd (line-beginning-position))
  581. (let ((arg (buffer-substring-no-properties (1+ start) (1- end))))
  582. (when (member arg tex-verbatim-environments)
  583. (if (eq ?b (char-after (1+ cmd)))
  584. ;; \begin
  585. (put-text-property (line-end-position)
  586. (line-beginning-position 2)
  587. 'syntax-table (string-to-syntax "< c"))
  588. ;; In the case of an empty verbatim env, the \n after the \begin is
  589. ;; the same as the \n before the \end. Lucky for us, the "> c"
  590. ;; property associated to the \end will be placed afterwards, so it
  591. ;; will override the "< c".
  592. (put-text-property (1- cmd) cmd
  593. 'syntax-table (string-to-syntax "> c"))
  594. ;; The text between \end{verbatim} and \n is ignored, so we'll treat
  595. ;; it as a comment.
  596. (put-text-property end (min (1+ end) (line-end-position))
  597. 'syntax-table (string-to-syntax "<"))))))
  598. ;; Mark env args for possible electric pairing.
  599. (unless (get-char-property (1+ start) 'text-clones) ;Already paired-up.
  600. (put-text-property start end 'latex-env-pair t)))
  601. (define-minor-mode latex-electric-env-pair-mode
  602. "Toggle Latex Electric Env Pair mode.
  603. With a prefix argument ARG, enable the mode if ARG is positive,
  604. and disable it otherwise. If called from Lisp, enable it if ARG
  605. is omitted or nil.
  606. Latex Electric Env Pair mode is a buffer-local minor mode for use
  607. with `latex-mode'. When enabled, typing a \\begin or \\end tag
  608. automatically inserts its partner."
  609. :lighter "/e"
  610. (if latex-electric-env-pair-mode
  611. (add-hook 'before-change-functions
  612. #'latex-env-before-change nil 'local)
  613. (remove-hook 'before-change-functions
  614. #'latex-env-before-change 'local)))
  615. (defun latex-env-before-change (start end)
  616. (when (get-text-property start 'latex-env-pair)
  617. (condition-case err
  618. (with-silent-modifications
  619. ;; Remove properties even if don't find a pair.
  620. (remove-text-properties
  621. (previous-single-property-change (1+ start) 'latex-env-pair)
  622. (next-single-property-change start 'latex-env-pair)
  623. '(latex-env-pair))
  624. (unless (or (get-char-property start 'text-clones)
  625. (get-char-property (1+ start) 'text-clones)
  626. (save-excursion
  627. (goto-char start)
  628. (not (re-search-backward
  629. "\\\\\\(?:end\\|begi\\(n\\)\\) *{"
  630. (line-beginning-position) t))))
  631. (let ((cmd-start (match-beginning 0))
  632. (type (match-end 1)) ;nil for \end, else \begin.
  633. (arg-start (1- (match-end 0))))
  634. (save-excursion
  635. (goto-char (match-end 0))
  636. (when (and (looking-at "[^\n{}]*}")
  637. (> (match-end 0) end))
  638. (let ((arg-end (match-end 0)))
  639. (if (null type) ;\end
  640. (progn (goto-char arg-end)
  641. (latex-forward-sexp -1) (forward-word 1))
  642. (goto-char cmd-start)
  643. (latex-forward-sexp 1)
  644. (let (forward-sexp-function) (backward-sexp)))
  645. (when (looking-at
  646. (regexp-quote (buffer-substring arg-start arg-end)))
  647. (text-clone-create arg-start arg-end))))))))
  648. (scan-error nil)
  649. (error (message "Error in latex-env-before-change: %s" err)))))
  650. (defun tex-font-lock-unfontify-region (beg end)
  651. (font-lock-default-unfontify-region beg end)
  652. (while (< beg end)
  653. (let ((next (next-single-property-change beg 'display nil end))
  654. (prop (get-text-property beg 'display)))
  655. (if (and (eq (car-safe prop) 'raise)
  656. (member (car-safe (cdr prop)) tex-font-script-display)
  657. (null (cddr prop)))
  658. (put-text-property beg next 'display nil))
  659. (setq beg next))))
  660. (defcustom tex-suscript-height-ratio 0.8
  661. "Ratio of subscript/superscript height to that of the preceding text.
  662. In nested subscript/superscript, this factor is applied repeatedly,
  663. subject to the limit set by `tex-suscript-height-minimum'."
  664. :type 'float
  665. :group 'tex
  666. :version "23.1")
  667. (defcustom tex-suscript-height-minimum 0.0
  668. "Integer or float limiting the minimum size of subscript/superscript text.
  669. An integer is an absolute height in units of 1/10 point, a float
  670. is a height relative to that of the default font. Zero means no minimum."
  671. :type '(choice (integer :tag "Integer height in 1/10 point units")
  672. (float :tag "Fraction of default font height"))
  673. :group 'tex
  674. :version "23.1")
  675. (defun tex-suscript-height (height)
  676. "Return the integer height of subscript/superscript font in 1/10 points.
  677. Not smaller than the value set by `tex-suscript-height-minimum'."
  678. (ceiling (max (if (integerp tex-suscript-height-minimum)
  679. tex-suscript-height-minimum
  680. ;; For bootstrapping.
  681. (condition-case nil
  682. (* tex-suscript-height-minimum
  683. (face-attribute 'default :height))
  684. (error 0)))
  685. ;; NB assumes height is integer.
  686. (* height tex-suscript-height-ratio))))
  687. (defface superscript
  688. '((t :height tex-suscript-height)) ;; :raise 0.2
  689. "Face used for superscripts."
  690. :group 'tex)
  691. (defface subscript
  692. '((t :height tex-suscript-height)) ;; :raise -0.2
  693. "Face used for subscripts."
  694. :group 'tex)
  695. (defface tex-math
  696. '((t :inherit font-lock-string-face))
  697. "Face used to highlight TeX math expressions."
  698. :group 'tex)
  699. (define-obsolete-face-alias 'tex-math-face 'tex-math "22.1")
  700. (defvar tex-math-face 'tex-math)
  701. (defface tex-verbatim
  702. ;; '((t :inherit font-lock-string-face))
  703. '((t :family "courier"))
  704. "Face used to highlight TeX verbatim environments."
  705. :group 'tex)
  706. (define-obsolete-face-alias 'tex-verbatim-face 'tex-verbatim "22.1")
  707. (defvar tex-verbatim-face 'tex-verbatim)
  708. (defun tex-font-lock-verb (start delim)
  709. "Place syntax table properties on the \verb construct.
  710. START is the position of the \\ and DELIM is the delimiter char."
  711. ;; Do nothing if the \verb construct is itself inside a comment or
  712. ;; verbatim env.
  713. (unless (nth 8 (save-excursion (syntax-ppss start)))
  714. ;; Let's find the end and mark it.
  715. (let ((afterdelim (point)))
  716. (skip-chars-forward (string ?^ delim) (line-end-position))
  717. (if (eolp)
  718. ;; "LaTeX Error: \verb ended by end of line."
  719. ;; Remove the syntax-table property we've just put on the
  720. ;; start-delimiter, so it doesn't spill over subsequent lines.
  721. (put-text-property (1- afterdelim) afterdelim
  722. 'syntax-table nil)
  723. (when (eq (char-syntax (preceding-char)) ?/)
  724. (put-text-property (1- (point)) (point)
  725. 'syntax-table (string-to-syntax ".")))
  726. (put-text-property (point) (1+ (point))
  727. 'syntax-table (string-to-syntax "\""))))))
  728. ;; Use string syntax but math face for $...$.
  729. (defun tex-font-lock-syntactic-face-function (state)
  730. (let ((char (nth 3 state)))
  731. (cond
  732. ((not char)
  733. (if (eq 2 (nth 7 state)) tex-verbatim-face font-lock-comment-face))
  734. ((eq char ?$) tex-math-face)
  735. ;; A \verb element.
  736. (t tex-verbatim-face))))
  737. (defun tex-define-common-keys (keymap)
  738. "Define the keys that we want defined both in TeX mode and in the TeX shell."
  739. (define-key keymap "\C-c\C-k" 'tex-kill-job)
  740. (define-key keymap "\C-c\C-l" 'tex-recenter-output-buffer)
  741. (define-key keymap "\C-c\C-q" 'tex-show-print-queue)
  742. (define-key keymap "\C-c\C-p" 'tex-print)
  743. (define-key keymap "\C-c\C-v" 'tex-view)
  744. (define-key keymap [menu-bar tex] (cons "TeX" (make-sparse-keymap "TeX")))
  745. (define-key keymap [menu-bar tex tex-kill-job]
  746. '(menu-item "Tex Kill" tex-kill-job :enable (tex-shell-running)))
  747. (define-key keymap [menu-bar tex tex-recenter-output-buffer]
  748. '(menu-item "Tex Recenter" tex-recenter-output-buffer
  749. :enable (get-buffer "*tex-shell*")))
  750. (define-key keymap [menu-bar tex tex-show-print-queue]
  751. '("Show Print Queue" . tex-show-print-queue))
  752. (define-key keymap [menu-bar tex tex-alt-print]
  753. '(menu-item "Tex Print (alt printer)" tex-alt-print
  754. :enable (stringp tex-print-file)))
  755. (define-key keymap [menu-bar tex tex-print]
  756. '(menu-item "Tex Print" tex-print :enable (stringp tex-print-file)))
  757. (define-key keymap [menu-bar tex tex-view]
  758. '(menu-item "Tex View" tex-view :enable (stringp tex-print-file))))
  759. (defvar tex-mode-map
  760. (let ((map (make-sparse-keymap)))
  761. (set-keymap-parent map text-mode-map)
  762. (tex-define-common-keys map)
  763. (define-key map "\"" 'tex-insert-quote)
  764. (define-key map "(" 'skeleton-pair-insert-maybe)
  765. (define-key map "{" 'skeleton-pair-insert-maybe)
  766. (define-key map "[" 'skeleton-pair-insert-maybe)
  767. (define-key map "$" 'skeleton-pair-insert-maybe)
  768. (define-key map "\n" 'tex-terminate-paragraph)
  769. (define-key map "\M-\r" 'latex-insert-item)
  770. (define-key map "\C-c}" 'up-list)
  771. (define-key map "\C-c{" 'tex-insert-braces)
  772. (define-key map "\C-c\C-r" 'tex-region)
  773. (define-key map "\C-c\C-b" 'tex-buffer)
  774. (define-key map "\C-c\C-f" 'tex-file)
  775. (define-key map "\C-c\C-c" 'tex-compile)
  776. (define-key map "\C-c\C-i" 'tex-bibtex-file)
  777. (define-key map "\C-c\C-o" 'latex-insert-block)
  778. ;; Redundant keybindings, for consistency with SGML mode.
  779. (define-key map "\C-c\C-t" 'latex-insert-block)
  780. (define-key map "\C-c]" 'latex-close-block)
  781. (define-key map "\C-c/" 'latex-close-block)
  782. (define-key map "\C-c\C-e" 'latex-close-block)
  783. (define-key map "\C-c\C-u" 'tex-goto-last-unclosed-latex-block)
  784. (define-key map "\C-c\C-m" 'tex-feed-input)
  785. (define-key map [(control return)] 'tex-feed-input)
  786. (define-key map [menu-bar tex tex-bibtex-file]
  787. '("BibTeX File" . tex-bibtex-file))
  788. (define-key map [menu-bar tex tex-validate-region]
  789. '(menu-item "Validate Region" tex-validate-region :enable mark-active))
  790. (define-key map [menu-bar tex tex-validate-buffer]
  791. '("Validate Buffer" . tex-validate-buffer))
  792. (define-key map [menu-bar tex tex-region]
  793. '(menu-item "TeX Region" tex-region :enable mark-active))
  794. (define-key map [menu-bar tex tex-buffer]
  795. '("TeX Buffer" . tex-buffer))
  796. (define-key map [menu-bar tex tex-file] '("TeX File" . tex-file))
  797. map)
  798. "Keymap shared by TeX modes.")
  799. (defvar latex-mode-map
  800. (let ((map (make-sparse-keymap)))
  801. (set-keymap-parent map tex-mode-map)
  802. (define-key map "\C-c\C-s" 'latex-split-block)
  803. map)
  804. "Keymap for `latex-mode'. See also `tex-mode-map'.")
  805. (defvar plain-tex-mode-map
  806. (let ((map (make-sparse-keymap)))
  807. (set-keymap-parent map tex-mode-map)
  808. map)
  809. "Keymap for `plain-tex-mode'. See also `tex-mode-map'.")
  810. (defvar tex-shell-map
  811. (let ((m (make-sparse-keymap)))
  812. (set-keymap-parent m shell-mode-map)
  813. (tex-define-common-keys m)
  814. m)
  815. "Keymap for the TeX shell.
  816. Inherits `shell-mode-map' with a few additions.")
  817. (defvar tex-face-alist
  818. '((bold . "{\\bf ")
  819. (italic . "{\\it ")
  820. (bold-italic . "{\\bi ") ; hypothetical
  821. (underline . "\\underline{")
  822. (default . "{\\rm "))
  823. "Alist of face and TeX font name for facemenu.")
  824. (defvar tex-latex-face-alist
  825. `((italic . "{\\em ")
  826. ,@tex-face-alist)
  827. "Alist of face and LaTeX font name for facemenu.")
  828. (defun tex-facemenu-add-face-function (face end)
  829. (or (cdr (assq face tex-face-alist))
  830. (or (and (consp face)
  831. (consp (car face))
  832. (null (cdr face))
  833. (eq major-mode 'latex-mode)
  834. ;; This actually requires the `color' LaTeX package.
  835. (cond ((eq (caar face) :foreground)
  836. (format "{\\color{%s} " (cadr (car face))))
  837. ((eq (caar face) :background)
  838. (format "\\colorbox{%s}{" (cadr (car face))))))
  839. (error "Face %s not configured for %s mode" face mode-name))))
  840. ;; This would be a lot simpler if we just used a regexp search,
  841. ;; but then it would be too slow.
  842. (defun tex-guess-mode ()
  843. (let ((mode tex-default-mode) slash comment)
  844. (save-excursion
  845. (goto-char (point-min))
  846. (while (and (setq slash (search-forward "\\" nil t))
  847. (setq comment (let ((search-end (point)))
  848. (save-excursion
  849. (beginning-of-line)
  850. (search-forward "%" search-end t))))))
  851. (when (and slash (not comment))
  852. (setq mode
  853. (if (looking-at
  854. (eval-when-compile
  855. (concat
  856. (regexp-opt '("documentstyle" "documentclass"
  857. "begin" "subsection" "section"
  858. "part" "chapter" "newcommand"
  859. "renewcommand" "RequirePackage") 'words)
  860. "\\|NeedsTeXFormat{LaTeX")))
  861. (if (and (looking-at
  862. "document\\(style\\|class\\)\\(\\[.*\\]\\)?{slides}")
  863. ;; SliTeX is almost never used any more nowadays.
  864. (tex-executable-exists-p slitex-run-command))
  865. 'slitex-mode
  866. 'latex-mode)
  867. 'plain-tex-mode))))
  868. (funcall mode)))
  869. ;; `tex-mode' plays two roles: it's the parent of several sub-modes
  870. ;; but it's also the function that chooses between those submodes.
  871. ;; To tell the difference between those two cases where the function
  872. ;; might be called, we check `delay-mode-hooks'.
  873. (define-derived-mode tex-mode text-mode "generic-TeX"
  874. (tex-common-initialization))
  875. ;; We now move the function and define it again. This gives a warning
  876. ;; in the byte-compiler :-( but it's difficult to avoid because
  877. ;; `define-derived-mode' will necessarily define the function once
  878. ;; and we need to define it a second time for `autoload' to get the
  879. ;; proper docstring.
  880. (defalias 'tex-mode-internal (symbol-function 'tex-mode))
  881. ;; Suppress the byte-compiler warning about multiple definitions.
  882. ;; This is a) ugly, and b) cheating, but this was the last
  883. ;; remaining warning from byte-compiling all of Emacs...
  884. (eval-when-compile
  885. (setq byte-compile-function-environment
  886. (delq (assq 'tex-mode byte-compile-function-environment)
  887. byte-compile-function-environment)))
  888. ;;;###autoload
  889. (defun tex-mode ()
  890. "Major mode for editing files of input for TeX, LaTeX, or SliTeX.
  891. Tries to determine (by looking at the beginning of the file) whether
  892. this file is for plain TeX, LaTeX, or SliTeX and calls `plain-tex-mode',
  893. `latex-mode', or `slitex-mode', respectively. If it cannot be determined,
  894. such as if there are no commands in the file, the value of `tex-default-mode'
  895. says which mode to use."
  896. (interactive)
  897. (if delay-mode-hooks
  898. ;; We're called from one of the children already.
  899. (tex-mode-internal)
  900. (tex-guess-mode)))
  901. ;; The following three autoloaded aliases appear to conflict with
  902. ;; AUCTeX. However, even though AUCTeX uses the mixed case variants
  903. ;; for all mode relevant variables and hooks, the invocation function
  904. ;; and setting of `major-mode' themselves need to be lowercase for
  905. ;; AUCTeX to provide a fully functional user-level replacement. So
  906. ;; these aliases should remain as they are, in particular since AUCTeX
  907. ;; users are likely to use them.
  908. ;;;###autoload
  909. (defalias 'TeX-mode 'tex-mode)
  910. ;;;###autoload
  911. (defalias 'plain-TeX-mode 'plain-tex-mode)
  912. ;;;###autoload
  913. (defalias 'LaTeX-mode 'latex-mode)
  914. ;;;###autoload
  915. (define-derived-mode plain-tex-mode tex-mode "TeX"
  916. "Major mode for editing files of input for plain TeX.
  917. Makes $ and } display the characters they match.
  918. Makes \" insert `` when it seems to be the beginning of a quotation,
  919. and '' when it appears to be the end; it inserts \" only after a \\.
  920. Use \\[tex-region] to run TeX on the current region, plus a \"header\"
  921. copied from the top of the file (containing macro definitions, etc.),
  922. running TeX under a special subshell. \\[tex-buffer] does the whole buffer.
  923. \\[tex-file] saves the buffer and then processes the file.
  924. \\[tex-print] prints the .dvi file made by any of these.
  925. \\[tex-view] previews the .dvi file made by any of these.
  926. \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
  927. Use \\[tex-validate-buffer] to check buffer for paragraphs containing
  928. mismatched $'s or braces.
  929. Special commands:
  930. \\{plain-tex-mode-map}
  931. Mode variables:
  932. tex-run-command
  933. Command string used by \\[tex-region] or \\[tex-buffer].
  934. tex-directory
  935. Directory in which to create temporary files for TeX jobs
  936. run by \\[tex-region] or \\[tex-buffer].
  937. tex-dvi-print-command
  938. Command string used by \\[tex-print] to print a .dvi file.
  939. tex-alt-dvi-print-command
  940. Alternative command string used by \\[tex-print] (when given a prefix
  941. argument) to print a .dvi file.
  942. tex-dvi-view-command
  943. Command string used by \\[tex-view] to preview a .dvi file.
  944. tex-show-queue-command
  945. Command string used by \\[tex-show-print-queue] to show the print
  946. queue that \\[tex-print] put your job on.
  947. Entering Plain-tex mode runs the hook `text-mode-hook', then the hook
  948. `tex-mode-hook', and finally the hook `plain-tex-mode-hook'. When the
  949. special subshell is initiated, the hook `tex-shell-hook' is run."
  950. (set (make-local-variable 'tex-command) tex-run-command)
  951. (set (make-local-variable 'tex-start-of-header) "%\\*\\*start of header")
  952. (set (make-local-variable 'tex-end-of-header) "%\\*\\*end of header")
  953. (set (make-local-variable 'tex-trailer) "\\bye\n"))
  954. ;;;###autoload
  955. (define-derived-mode latex-mode tex-mode "LaTeX"
  956. "Major mode for editing files of input for LaTeX.
  957. Makes $ and } display the characters they match.
  958. Makes \" insert `` when it seems to be the beginning of a quotation,
  959. and '' when it appears to be the end; it inserts \" only after a \\.
  960. Use \\[tex-region] to run LaTeX on the current region, plus the preamble
  961. copied from the top of the file (containing \\documentstyle, etc.),
  962. running LaTeX under a special subshell. \\[tex-buffer] does the whole buffer.
  963. \\[tex-file] saves the buffer and then processes the file.
  964. \\[tex-print] prints the .dvi file made by any of these.
  965. \\[tex-view] previews the .dvi file made by any of these.
  966. \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
  967. Use \\[tex-validate-buffer] to check buffer for paragraphs containing
  968. mismatched $'s or braces.
  969. Special commands:
  970. \\{latex-mode-map}
  971. Mode variables:
  972. latex-run-command
  973. Command string used by \\[tex-region] or \\[tex-buffer].
  974. tex-directory
  975. Directory in which to create temporary files for LaTeX jobs
  976. run by \\[tex-region] or \\[tex-buffer].
  977. tex-dvi-print-command
  978. Command string used by \\[tex-print] to print a .dvi file.
  979. tex-alt-dvi-print-command
  980. Alternative command string used by \\[tex-print] (when given a prefix
  981. argument) to print a .dvi file.
  982. tex-dvi-view-command
  983. Command string used by \\[tex-view] to preview a .dvi file.
  984. tex-show-queue-command
  985. Command string used by \\[tex-show-print-queue] to show the print
  986. queue that \\[tex-print] put your job on.
  987. Entering Latex mode runs the hook `text-mode-hook', then
  988. `tex-mode-hook', and finally `latex-mode-hook'. When the special
  989. subshell is initiated, `tex-shell-hook' is run."
  990. (set (make-local-variable 'tex-command) latex-run-command)
  991. (set (make-local-variable 'tex-start-of-header)
  992. "\\\\document\\(style\\|class\\)")
  993. (set (make-local-variable 'tex-end-of-header) "\\\\begin\\s-*{document}")
  994. (set (make-local-variable 'tex-trailer) "\\end{document}\n")
  995. ;; A line containing just $$ is treated as a paragraph separator.
  996. ;; A line starting with $$ starts a paragraph,
  997. ;; but does not separate paragraphs if it has more stuff on it.
  998. (setq paragraph-start
  999. (concat "[ \t]*\\(\\$\\$\\|"
  1000. "\\\\[][]\\|"
  1001. "\\\\" (regexp-opt (append
  1002. (mapcar 'car latex-section-alist)
  1003. '("begin" "label" "end"
  1004. "item" "bibitem" "newline" "noindent"
  1005. "newpage" "footnote" "marginpar"
  1006. "parbox" "caption")) t)
  1007. "\\>\\|\\\\[a-z]*" (regexp-opt '("space" "skip" "page") t)
  1008. "\\>\\)"))
  1009. (setq paragraph-separate
  1010. (concat "[\f%]\\|[ \t]*\\($\\|"
  1011. "\\\\[][]\\|"
  1012. "\\\\" (regexp-opt (append
  1013. (mapcar 'car latex-section-alist)
  1014. '("begin" "label" "end" )) t)
  1015. "\\>\\|\\\\\\(" (regexp-opt '("item" "bibitem" "newline"
  1016. "noindent" "newpage" "footnote"
  1017. "marginpar" "parbox" "caption"))
  1018. "\\|\\$\\$\\|[a-z]*\\(space\\|skip\\|page[a-z]*\\)"
  1019. "\\>\\)[ \t]*\\($\\|%\\)\\)"))
  1020. (set (make-local-variable 'imenu-create-index-function)
  1021. 'latex-imenu-create-index)
  1022. (set (make-local-variable 'tex-face-alist) tex-latex-face-alist)
  1023. (add-hook 'fill-nobreak-predicate 'latex-fill-nobreak-predicate nil t)
  1024. (set (make-local-variable 'indent-line-function) 'latex-indent)
  1025. (set (make-local-variable 'fill-indent-according-to-mode) t)
  1026. (add-hook 'completion-at-point-functions
  1027. 'latex-complete-data nil 'local)
  1028. (set (make-local-variable 'outline-regexp) latex-outline-regexp)
  1029. (set (make-local-variable 'outline-level) 'latex-outline-level)
  1030. (set (make-local-variable 'forward-sexp-function) 'latex-forward-sexp)
  1031. (set (make-local-variable 'skeleton-end-hook) nil))
  1032. ;;;###autoload
  1033. (define-derived-mode slitex-mode latex-mode "SliTeX"
  1034. "Major mode for editing files of input for SliTeX.
  1035. Makes $ and } display the characters they match.
  1036. Makes \" insert `` when it seems to be the beginning of a quotation,
  1037. and '' when it appears to be the end; it inserts \" only after a \\.
  1038. Use \\[tex-region] to run SliTeX on the current region, plus the preamble
  1039. copied from the top of the file (containing \\documentstyle, etc.),
  1040. running SliTeX under a special subshell. \\[tex-buffer] does the whole buffer.
  1041. \\[tex-file] saves the buffer and then processes the file.
  1042. \\[tex-print] prints the .dvi file made by any of these.
  1043. \\[tex-view] previews the .dvi file made by any of these.
  1044. \\[tex-bibtex-file] runs bibtex on the file of the current buffer.
  1045. Use \\[tex-validate-buffer] to check buffer for paragraphs containing
  1046. mismatched $'s or braces.
  1047. Special commands:
  1048. \\{slitex-mode-map}
  1049. Mode variables:
  1050. slitex-run-command
  1051. Command string used by \\[tex-region] or \\[tex-buffer].
  1052. tex-directory
  1053. Directory in which to create temporary files for SliTeX jobs
  1054. run by \\[tex-region] or \\[tex-buffer].
  1055. tex-dvi-print-command
  1056. Command string used by \\[tex-print] to print a .dvi file.
  1057. tex-alt-dvi-print-command
  1058. Alternative command string used by \\[tex-print] (when given a prefix
  1059. argument) to print a .dvi file.
  1060. tex-dvi-view-command
  1061. Command string used by \\[tex-view] to preview a .dvi file.
  1062. tex-show-queue-command
  1063. Command string used by \\[tex-show-print-queue] to show the print
  1064. queue that \\[tex-print] put your job on.
  1065. Entering SliTeX mode runs the hook `text-mode-hook', then the hook
  1066. `tex-mode-hook', then the hook `latex-mode-hook', and finally the hook
  1067. `slitex-mode-hook'. When the special subshell is initiated, the hook
  1068. `tex-shell-hook' is run."
  1069. (setq tex-command slitex-run-command)
  1070. (setq tex-start-of-header "\\\\documentstyle{slides}\\|\\\\documentclass{slides}"))
  1071. (defun tex-common-initialization ()
  1072. ;; Regexp isearch should accept newline and formfeed as whitespace.
  1073. (set (make-local-variable 'search-whitespace-regexp) "[ \t\r\n\f]+")
  1074. ;; A line containing just $$ is treated as a paragraph separator.
  1075. (set (make-local-variable 'paragraph-start)
  1076. "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$")
  1077. ;; A line starting with $$ starts a paragraph,
  1078. ;; but does not separate paragraphs if it has more stuff on it.
  1079. (set (make-local-variable 'paragraph-separate)
  1080. "[ \t]*$\\|[\f\\\\%]\\|[ \t]*\\$\\$[ \t]*$")
  1081. (set (make-local-variable 'comment-start) "%")
  1082. (set (make-local-variable 'comment-add) 1)
  1083. (set (make-local-variable 'comment-start-skip)
  1084. "\\(\\(^\\|[^\\\n]\\)\\(\\\\\\\\\\)*\\)\\(%+ *\\)")
  1085. (set (make-local-variable 'parse-sexp-ignore-comments) t)
  1086. (set (make-local-variable 'compare-windows-whitespace)
  1087. 'tex-categorize-whitespace)
  1088. (set (make-local-variable 'facemenu-add-face-function)
  1089. 'tex-facemenu-add-face-function)
  1090. (set (make-local-variable 'facemenu-end-add-face) "}")
  1091. (set (make-local-variable 'facemenu-remove-face-function) t)
  1092. (set (make-local-variable 'font-lock-defaults)
  1093. '((tex-font-lock-keywords tex-font-lock-keywords-1
  1094. tex-font-lock-keywords-2 tex-font-lock-keywords-3)
  1095. nil nil ((?$ . "\"")) nil
  1096. ;; Who ever uses that anyway ???
  1097. (font-lock-mark-block-function . mark-paragraph)
  1098. (font-lock-syntactic-face-function
  1099. . tex-font-lock-syntactic-face-function)
  1100. (font-lock-unfontify-region-function
  1101. . tex-font-lock-unfontify-region)))
  1102. (set (make-local-variable 'syntax-propertize-function)
  1103. (syntax-propertize-rules latex-syntax-propertize-rules))
  1104. ;; TABs in verbatim environments don't do what you think.
  1105. (set (make-local-variable 'indent-tabs-mode) nil)
  1106. ;; Other vars that should be buffer-local.
  1107. (make-local-variable 'tex-command)
  1108. (make-local-variable 'tex-start-of-header)
  1109. (make-local-variable 'tex-end-of-header)
  1110. (make-local-variable 'tex-trailer))
  1111. (defun tex-categorize-whitespace (backward-limit)
  1112. ;; compare-windows-whitespace is set to this.
  1113. ;; This is basically a finite-state machine.
  1114. ;; Returns a symbol telling how TeX would treat
  1115. ;; the whitespace we are looking at: null, space, or par.
  1116. (let ((category 'null)
  1117. (not-finished t))
  1118. (skip-chars-backward " \t\n\f" backward-limit)
  1119. (while not-finished
  1120. (cond ((looking-at "[ \t]+")
  1121. (goto-char (match-end 0))
  1122. (if (eq category 'null)
  1123. (setq category 'space)))
  1124. ((looking-at "\n")
  1125. (cond ((eq category 'newline)
  1126. (setq category 'par)
  1127. (setq not-finished nil))
  1128. (t
  1129. (setq category 'newline) ;a strictly internal state
  1130. (goto-char (match-end 0)))))
  1131. ((looking-at "\f+")
  1132. (setq category 'par)
  1133. (setq not-finished nil))
  1134. (t
  1135. (setq not-finished nil))))
  1136. (skip-chars-forward " \t\n\f")
  1137. (if (eq category 'newline)
  1138. 'space ;TeX doesn't distinguish
  1139. category)))
  1140. (defun tex-insert-quote (arg)
  1141. "Insert the appropriate quote marks for TeX.
  1142. Inserts the value of `tex-open-quote' (normally ``) or `tex-close-quote'
  1143. \(normally '') depending on the context. With prefix argument, always
  1144. inserts \" characters."
  1145. (interactive "*P")
  1146. (if (or arg (memq (char-syntax (preceding-char)) '(?/ ?\\))
  1147. (eq (get-text-property (point) 'face) 'tex-verbatim)
  1148. (save-excursion
  1149. (backward-char (length tex-open-quote))
  1150. (when (or (looking-at (regexp-quote tex-open-quote))
  1151. (looking-at (regexp-quote tex-close-quote)))
  1152. (delete-char (length tex-open-quote))
  1153. t)))
  1154. (self-insert-command (prefix-numeric-value arg))
  1155. (insert (if (memq (char-syntax (preceding-char)) '(?\( ?> ?\s))
  1156. tex-open-quote tex-close-quote))))
  1157. (defun tex-validate-buffer ()
  1158. "Check current buffer for paragraphs containing mismatched braces or $s.
  1159. Their positions are recorded in the buffer `*Occur*'.
  1160. To find a particular invalidity from `*Occur*', switch to that buffer
  1161. and type C-c C-c or click with mouse-2
  1162. on the line for the invalidity you want to see."
  1163. (interactive)
  1164. (let ((buffer (current-buffer))
  1165. (prevpos (point-min))
  1166. (linenum nil)
  1167. (num-matches 0))
  1168. (with-output-to-temp-buffer "*Occur*"
  1169. (princ "Mismatches:\n")
  1170. (with-current-buffer standard-output
  1171. (occur-mode)
  1172. ;; This won't actually work...Really, this whole thing should
  1173. ;; be rewritten instead of being a hack on top of occur.
  1174. (setq occur-revert-arguments (list nil 0 (list buffer))))
  1175. (save-excursion
  1176. (goto-char (point-max))
  1177. ;; Do a little shimmy to place point at the end of the last
  1178. ;; "real" paragraph. Need to avoid validating across an \end,
  1179. ;; because that blows up latex-forward-sexp.
  1180. (backward-paragraph)
  1181. (forward-paragraph)
  1182. (while (not (bobp))
  1183. ;; Scan the previous paragraph for invalidities.
  1184. (backward-paragraph)
  1185. (save-excursion
  1186. (or (tex-validate-region (point) (save-excursion
  1187. (forward-paragraph)
  1188. (point)))
  1189. (let ((end (line-beginning-position 2))
  1190. start tem)
  1191. (beginning-of-line)
  1192. (setq start (point))
  1193. ;; Keep track of line number as we scan,
  1194. ;; in a cumulative fashion.
  1195. (if linenum
  1196. (setq linenum (- linenum
  1197. (count-lines prevpos (point))))
  1198. (setq linenum (1+ (count-lines 1 start))))
  1199. (setq prevpos (point))
  1200. ;; Mention this mismatch in *Occur*.
  1201. ;; Since we scan from end of buffer to beginning,
  1202. ;; add each mismatch at the beginning of *Occur*.
  1203. (save-excursion
  1204. (setq tem (point-marker))
  1205. (set-buffer standard-output)
  1206. (goto-char (point-min))
  1207. ;; Skip "Mismatches:" header line.
  1208. (forward-line 1)
  1209. (setq num-matches (1+ num-matches))
  1210. (insert-buffer-substring buffer start end)
  1211. (let (text-beg (text-end (point-marker)))
  1212. (forward-char (- start end))
  1213. (setq text-beg (point-marker))
  1214. (insert (format "%3d: " linenum))
  1215. (add-text-properties
  1216. text-beg (- text-end 1)
  1217. '(mouse-face highlight
  1218. help-echo
  1219. "mouse-2: go to this invalidity"))
  1220. (put-text-property text-beg (- text-end 1)
  1221. 'occur-target tem))))))))
  1222. (with-current-buffer standard-output
  1223. (let ((no-matches (zerop num-matches)))
  1224. (if no-matches
  1225. (insert "None!\n"))
  1226. (if (called-interactively-p 'interactive)
  1227. (message (cond (no-matches "No mismatches found")
  1228. ((= num-matches 1) "1 mismatch found")
  1229. (t "%d mismatches found"))
  1230. num-matches)))))))
  1231. (defun tex-validate-region (start end)
  1232. "Check for mismatched braces or $'s in region.
  1233. Returns t if no mismatches. Returns nil and moves point to suspect
  1234. area if a mismatch is found."
  1235. (interactive "r")
  1236. (let ((failure-point nil) (max-possible-sexps (- end start)))
  1237. (save-excursion
  1238. (condition-case ()
  1239. (save-restriction
  1240. (narrow-to-region start end)
  1241. ;; First check that the open and close parens balance in numbers.
  1242. (goto-char start)
  1243. (while (and (not (eobp))
  1244. (<= 0 (setq max-possible-sexps
  1245. (1- max-possible-sexps))))
  1246. (forward-sexp 1))
  1247. ;; Now check that like matches like.
  1248. (goto-char start)
  1249. (while (re-search-forward "\\s(" nil t)
  1250. (save-excursion
  1251. (let ((pos (match-beginning 0)))
  1252. (goto-char pos)
  1253. (skip-chars-backward "\\\\") ; escaped parens
  1254. (forward-sexp 1)
  1255. (or (eq (preceding-char) (cdr (syntax-after pos)))
  1256. (eq (char-after pos) (cdr (syntax-after (1- (point)))))
  1257. (error "Mismatched parentheses"))))))
  1258. (error
  1259. (skip-syntax-forward " .>")
  1260. (setq failure-point (point)))))
  1261. (if failure-point (goto-char failure-point))
  1262. (not failure-point)))
  1263. (defun tex-terminate-paragraph (inhibit-validation)
  1264. "Insert two newlines, breaking a paragraph for TeX.
  1265. Check for mismatched braces or $s in paragraph being terminated.
  1266. A prefix arg inhibits the checking."
  1267. (interactive "*P")
  1268. (or inhibit-validation
  1269. (save-excursion
  1270. ;; For the purposes of this, a "paragraph" is a block of text
  1271. ;; wherein all the brackets etc are expected to be balanced. It
  1272. ;; may start after a blank line (ie a "proper" paragraph), or
  1273. ;; a begin{} or end{} block, etc.
  1274. (tex-validate-region
  1275. (save-excursion
  1276. (backward-paragraph)
  1277. (point))
  1278. (point)))
  1279. (message "Paragraph being closed appears to contain a mismatch"))
  1280. (insert "\n\n"))
  1281. (define-skeleton tex-insert-braces
  1282. "Make a pair of braces and be poised to type inside of them."
  1283. nil
  1284. ?\{ _ ?})
  1285. ;; This function is used as the value of fill-nobreak-predicate
  1286. ;; in LaTeX mode. Its job is to prevent line-breaking inside
  1287. ;; of a \verb construct.
  1288. (defun latex-fill-nobreak-predicate ()
  1289. (save-excursion
  1290. (skip-chars-backward " ")
  1291. ;; Don't break after \ since `\ ' has special meaning.
  1292. (or (and (not (bobp)) (memq (char-syntax (char-before)) '(?\\ ?/)))
  1293. (let ((opoint (point))
  1294. inside)
  1295. (beginning-of-line)
  1296. (while (re-search-forward "\\\\verb\\(.\\)" opoint t)
  1297. (unless (re-search-forward (regexp-quote (match-string 1)) opoint t)
  1298. (setq inside t)))
  1299. inside))))
  1300. (defvar latex-block-default "enumerate")
  1301. (defvar latex-block-args-alist
  1302. '(("array" nil ?\{ (skeleton-read "Format: ") ?\})
  1303. ("tabular" nil ?\{ (skeleton-read "Format: ") ?\})
  1304. ("minipage" nil ?\{ (skeleton-read "Size: ") ?\})
  1305. ("picture" nil ?\( (skeleton-read "SizeX,SizeY: ") ?\))
  1306. ;; FIXME: This is right for Prosper, but not for seminar.
  1307. ;; ("slide" nil ?\{ (skeleton-read "Title: ") ?\})
  1308. )
  1309. "Skeleton element to use for arguments to particular environments.
  1310. Every element of the list has the form (NAME . SKEL-ELEM) where NAME is
  1311. the name of the environment and SKEL-ELEM is an element to use in
  1312. a skeleton (see `skeleton-insert').")
  1313. (defvar latex-block-body-alist
  1314. '(("enumerate" nil '(latex-insert-item) > _)
  1315. ("itemize" nil '(latex-insert-item) > _)
  1316. ("table" nil "\\caption{" > (skeleton-read "Caption: ") "}" > \n
  1317. '(if (and (boundp 'reftex-mode) reftex-mode) (reftex-label "table"))
  1318. \n _)
  1319. ("figure" nil > _ \n "\\caption{" > (skeleton-read "Caption: ") "}" > \n
  1320. '(if (and (boundp 'reftex-mode) reftex-mode) (reftex-label "table"))))
  1321. "Skeleton element to use for the body of particular environments.
  1322. Every element of the list has the form (NAME . SKEL-ELEM) where NAME is
  1323. the name of the environment and SKEL-ELEM is an element to use in
  1324. a skeleton (see `skeleton-insert').")
  1325. ;; Like tex-insert-braces, but for LaTeX.
  1326. (defalias 'tex-latex-block 'latex-insert-block)
  1327. (define-skeleton latex-insert-block
  1328. "Create a matching pair of lines \\begin{NAME} and \\end{NAME} at point.
  1329. Puts point on a blank line between them."
  1330. (let ((choice (completing-read (format "LaTeX block name [%s]: "
  1331. latex-block-default)
  1332. (append latex-block-names
  1333. latex-standard-block-names)
  1334. nil nil nil nil latex-block-default)))
  1335. (setq latex-block-default choice)
  1336. (unless (or (member choice latex-standard-block-names)
  1337. (member choice latex-block-names))
  1338. ;; Remember new block names for later completion.
  1339. (push choice latex-block-names))
  1340. choice)
  1341. \n "\\begin{" str "}"
  1342. (cdr (assoc str latex-block-args-alist))
  1343. > \n (or (cdr (assoc str latex-block-body-alist)) '(nil > _))
  1344. (unless (bolp) '\n)
  1345. "\\end{" str "}" > \n)
  1346. (define-skeleton latex-insert-item
  1347. "Insert a \item macro."
  1348. nil
  1349. \n "\\item " >)
  1350. ;;;; LaTeX completion.
  1351. (defvar latex-complete-bibtex-cache nil)
  1352. (defun latex-string-prefix-p (str1 str2)
  1353. (eq t (compare-strings str1 nil nil str2 0 (length str1))))
  1354. (defvar bibtex-reference-key)
  1355. (declare-function reftex-get-bibfile-list "reftex-cite.el" ())
  1356. (defun latex-complete-bibtex-keys ()
  1357. (when (bound-and-true-p reftex-mode)
  1358. (lambda (key pred action)
  1359. (let ((re (concat "^[ \t]*@\\([a-zA-Z]+\\)[ \t\n]*\\([{(][ \t\n]*\\)"
  1360. (regexp-quote key)))
  1361. (files (reftex-get-bibfile-list))
  1362. keys)
  1363. (if (and (eq (car latex-complete-bibtex-cache)
  1364. (reftex-get-bibfile-list))
  1365. (latex-string-prefix-p (nth 1 latex-complete-bibtex-cache)
  1366. key))
  1367. ;; Use the cache.
  1368. (setq keys (nth 2 latex-complete-bibtex-cache))
  1369. (dolist (file files)
  1370. (with-current-buffer (find-file-noselect file)
  1371. (goto-char (point-min))
  1372. (while (re-search-forward re nil t)
  1373. (goto-char (match-end 2))
  1374. (when (and (not (member-ignore-case (match-string 1)
  1375. '("c" "comment" "string")))
  1376. (looking-at bibtex-reference-key))
  1377. (push (match-string-no-properties 0) keys)))))
  1378. ;; Fill the cache.
  1379. (set (make-local-variable 'latex-complete-bibtex-cache)
  1380. (list files key keys)))
  1381. (complete-with-action action keys key pred)))))
  1382. (defun latex-complete-envnames ()
  1383. (append latex-block-names latex-standard-block-names))
  1384. (defun latex-complete-refkeys ()
  1385. (when (boundp 'reftex-docstruct-symbol)
  1386. (symbol-value reftex-docstruct-symbol)))
  1387. (defvar latex-complete-alist
  1388. ;; TODO: Add \begin, \end, \ref, ...
  1389. '(("\\`\\\\\\(short\\)?cite\\'" . latex-complete-bibtex-keys)
  1390. ("\\`\\\\\\(begin\\|end\\)\\'" . latex-complete-envnames)
  1391. ("\\`\\\\[vf]?ref\\'" . latex-complete-refkeys)))
  1392. (defun latex-complete-data ()
  1393. "Get completion-data at point."
  1394. (save-excursion
  1395. (let ((pt (point)))
  1396. (skip-chars-backward "^ {}\n\t\\\\")
  1397. (case (char-before)
  1398. ((nil ?\s ?\n ?\t ?\}) nil)
  1399. (?\\
  1400. ;; TODO: Complete commands.
  1401. nil)
  1402. (?\{
  1403. ;; Complete args to commands.
  1404. (let* ((cmd
  1405. (save-excursion
  1406. (forward-char -1)
  1407. (skip-chars-backward " \n")
  1408. (buffer-substring (point)
  1409. (progn
  1410. (skip-chars-backward "a-zA-Z@*")
  1411. (let ((n (skip-chars-backward "\\\\")))
  1412. (forward-char (* 2 (/ n 2))))
  1413. (point)))))
  1414. (start (point))
  1415. (_ (progn (goto-char pt) (skip-chars-backward "^," start)))
  1416. (comp-beg (point))
  1417. (_ (progn (goto-char pt) (skip-chars-forward "^, {}\n\t\\\\")))
  1418. (comp-end (point))
  1419. (table
  1420. (funcall
  1421. (let ((f (lambda () t)))
  1422. (dolist (comp latex-complete-alist)
  1423. (if (string-match (car comp) cmd)
  1424. (setq f (cdr comp))))
  1425. f))))
  1426. (if (eq table t)
  1427. ;; Unknown command.
  1428. nil
  1429. (list comp-beg comp-end table))))))))
  1430. ;;;;
  1431. ;;;; LaTeX syntax navigation
  1432. ;;;;
  1433. (defmacro tex-search-noncomment (&rest body)
  1434. "Execute BODY as long as it return non-nil and point is in a comment.
  1435. Return the value returned by the last execution of BODY."
  1436. (declare (debug t))
  1437. (let ((res-sym (make-symbol "result")))
  1438. `(let (,res-sym)
  1439. (while
  1440. (and (setq ,res-sym (progn ,@body))
  1441. (save-excursion (skip-chars-backward "^\n%") (not (bolp)))))
  1442. ,res-sym)))
  1443. (defun tex-last-unended-begin ()
  1444. "Leave point at the beginning of the last `\\begin{...}' that is unended."
  1445. (condition-case nil
  1446. (while (and (tex-search-noncomment
  1447. (re-search-backward "\\\\\\(begin\\|end\\)\\s *{"))
  1448. (looking-at "\\\\end"))
  1449. (tex-last-unended-begin))
  1450. (search-failed (error "Couldn't find unended \\begin"))))
  1451. (defun tex-next-unmatched-end ()
  1452. "Leave point at the end of the next `\\end' that is unmatched."
  1453. (while (and (tex-search-noncomment
  1454. (re-search-forward "\\\\\\(begin\\|end\\)\\s *{[^}]+}"))
  1455. (save-excursion (goto-char (match-beginning 0))
  1456. (looking-at "\\\\begin")))
  1457. (tex-next-unmatched-end)))
  1458. (defun tex-next-unmatched-eparen (otype)
  1459. "Leave point after the next unmatched escaped closing parenthesis.
  1460. The string OTYPE is an opening parenthesis type: `(', `{', or `['."
  1461. (condition-case nil
  1462. (let ((ctype (char-to-string (cdr (aref (syntax-table)
  1463. (string-to-char otype))))))
  1464. (while (and (tex-search-noncomment
  1465. (re-search-forward (format "\\\\[%s%s]" ctype otype)))
  1466. (save-excursion
  1467. (goto-char (match-beginning 0))
  1468. (looking-at (format "\\\\%s" (regexp-quote otype)))))
  1469. (tex-next-unmatched-eparen otype)))
  1470. (wrong-type-argument (error "Unknown opening parenthesis type: %s" otype))
  1471. (search-failed (error "Couldn't find closing escaped paren"))))
  1472. (defun tex-last-unended-eparen (ctype)
  1473. "Leave point at the start of the last unended escaped opening parenthesis.
  1474. The string CTYPE is a closing parenthesis type: `)', `}', or `]'."
  1475. (condition-case nil
  1476. (let ((otype (char-to-string (cdr (aref (syntax-table)
  1477. (string-to-char ctype))))))
  1478. (while (and (tex-search-noncomment
  1479. (re-search-backward (format "\\\\[%s%s]" ctype otype)))
  1480. (looking-at (format "\\\\%s" (regexp-quote ctype))))
  1481. (tex-last-unended-eparen ctype)))
  1482. (wrong-type-argument (error "Unknown opening parenthesis type: %s" ctype))
  1483. (search-failed (error "Couldn't find unended escaped paren"))))
  1484. (defun tex-goto-last-unclosed-latex-block ()
  1485. "Move point to the last unclosed \\begin{...}.
  1486. Mark is left at original location."
  1487. (interactive)
  1488. (let ((spot))
  1489. (save-excursion
  1490. (tex-last-unended-begin)
  1491. (setq spot (point)))
  1492. (push-mark)
  1493. (goto-char spot)))
  1494. (defvar latex-handle-escaped-parens t)
  1495. ;; Don't think this one actually _needs_ (for the purposes of
  1496. ;; tex-mode) to handle escaped parens.
  1497. ;; Does not handle escaped parens when latex-handle-escaped-parens is nil.
  1498. (defun latex-backward-sexp-1 ()
  1499. "Like (backward-sexp 1) but aware of multi-char elements and escaped parens."
  1500. (let ((pos (point))
  1501. (forward-sexp-function))
  1502. (backward-sexp 1)
  1503. (cond ((looking-at
  1504. (if latex-handle-escaped-parens
  1505. "\\\\\\(begin\\>\\|[[({]\\)"
  1506. "\\\\begin\\>"))
  1507. (signal 'scan-error
  1508. (list "Containing expression ends prematurely"
  1509. (point) (prog1 (point) (goto-char pos)))))
  1510. ((and latex-handle-escaped-parens
  1511. (looking-at "\\\\\\([])}]\\)"))
  1512. (tex-last-unended-eparen (match-string 1)))
  1513. ((eq (char-after) ?{)
  1514. (let ((newpos (point)))
  1515. (when (ignore-errors (backward-sexp 1) t)
  1516. (if (or (looking-at "\\\\end\\>")
  1517. ;; In case the \\ ends a verbatim section.
  1518. (and (looking-at "end\\>") (eq (char-before) ?\\)))
  1519. (tex-last-unended-begin)
  1520. (goto-char newpos))))))))
  1521. ;; Note this does not handle things like mismatched brackets inside
  1522. ;; begin/end blocks.
  1523. ;; Needs to handle escaped parens for tex-validate-*.
  1524. ;; http://lists.gnu.org/archive/html/bug-gnu-emacs/2007-09/msg00038.html
  1525. ;; Does not handle escaped parens when latex-handle-escaped-parens is nil.
  1526. (defun latex-forward-sexp-1 ()
  1527. "Like (forward-sexp 1) but aware of multi-char elements and escaped parens."
  1528. (let ((pos (point))
  1529. (forward-sexp-function))
  1530. (forward-sexp 1)
  1531. (let ((newpos (point)))
  1532. (skip-syntax-backward "/w")
  1533. (cond
  1534. ((looking-at "\\\\end\\>")
  1535. (signal 'scan-error
  1536. (list "Containing expression ends prematurely"
  1537. (point)
  1538. (prog1
  1539. (progn (ignore-errors (forward-sexp 2)) (point))
  1540. (goto-char pos)))))
  1541. ((looking-at "\\\\begin\\>")
  1542. (goto-char (match-end 0))
  1543. (tex-next-unmatched-end))
  1544. ;; A better way to handle this, \( .. \) etc, is probably to
  1545. ;; temporarily change the syntax of the \ in \( to punctuation.
  1546. ((and latex-handle-escaped-parens
  1547. (looking-back "\\\\[])}]"))
  1548. (signal 'scan-error
  1549. (list "Containing expression ends prematurely"
  1550. (- (point) 2) (prog1 (point)
  1551. (goto-char pos)))))
  1552. ((and latex-handle-escaped-parens
  1553. (looking-back "\\\\\\([({[]\\)"))
  1554. (tex-next-unmatched-eparen (match-string 1)))
  1555. (t (goto-char newpos))))))
  1556. (defun latex-forward-sexp (&optional arg)
  1557. "Like `forward-sexp' but aware of multi-char elements and escaped parens."
  1558. (interactive "P")
  1559. (unless arg (setq arg 1))
  1560. (let ((pos (point)))
  1561. (condition-case err
  1562. (while (/= arg 0)
  1563. (setq arg
  1564. (if (> arg 0)
  1565. (progn (latex-forward-sexp-1) (1- arg))
  1566. (progn (latex-backward-sexp-1) (1+ arg)))))
  1567. (scan-error
  1568. (goto-char pos)
  1569. (signal (car err) (cdr err))))))
  1570. (defun latex-syntax-after ()
  1571. "Like (char-syntax (char-after)) but aware of multi-char elements."
  1572. (if (looking-at "\\\\end\\>") ?\) (char-syntax (following-char))))
  1573. (defun latex-skip-close-parens ()
  1574. "Like (skip-syntax-forward \" )\") but aware of multi-char elements."
  1575. (let ((forward-sexp-function nil))
  1576. (while (progn (skip-syntax-forward " )")
  1577. (looking-at "\\\\end\\>"))
  1578. (forward-sexp 2))))
  1579. (defun latex-down-list ()
  1580. "Like (down-list 1) but aware of multi-char elements."
  1581. (forward-comment (point-max))
  1582. (let ((forward-sexp-function nil))
  1583. (if (not (looking-at "\\\\begin\\>"))
  1584. (down-list 1)
  1585. (forward-sexp 1)
  1586. ;; Skip arguments.
  1587. (while (looking-at "[ \t]*[[{(]")
  1588. (with-syntax-table tex-mode-syntax-table
  1589. (forward-sexp))))))
  1590. (defalias 'tex-close-latex-block 'latex-close-block)
  1591. (define-skeleton latex-close-block
  1592. "Create an \\end{...} to match the last unclosed \\begin{...}."
  1593. (save-excursion
  1594. (tex-last-unended-begin)
  1595. (if (not (looking-at "\\\\begin\\(\\s *{[^}\n]*}\\)")) '("{" _ "}")
  1596. (match-string 1)))
  1597. \n "\\end" str > \n)
  1598. (define-skeleton latex-split-block
  1599. "Split the enclosing environment by inserting \\end{..}\\begin{..} at point."
  1600. (save-excursion
  1601. (tex-last-unended-begin)
  1602. (if (not (looking-at "\\\\begin\\(\\s *{[^}\n]*}\\)")) '("{" _ "}")
  1603. (prog1 (match-string 1)
  1604. (goto-char (match-end 1))
  1605. (setq v1 (buffer-substring (point)
  1606. (progn
  1607. (while (looking-at "[ \t]*[[{]")
  1608. (forward-sexp 1))
  1609. (point)))))))
  1610. \n "\\end" str > \n _ \n "\\begin" str v1 > \n)
  1611. (defconst tex-discount-args-cmds
  1612. '("begin" "end" "input" "special" "cite" "ref" "include" "includeonly"
  1613. "documentclass" "usepackage" "label")
  1614. "TeX commands whose arguments should not be counted as text.")
  1615. (defun tex-count-words (begin end)
  1616. "Count the number of words in the buffer."
  1617. (interactive
  1618. (if (and transient-mark-mode mark-active)
  1619. (list (region-beginning) (region-end))
  1620. (list (point-min) (point-max))))
  1621. ;; TODO: skip comments and math and maybe some environments.
  1622. (save-excursion
  1623. (goto-char begin)
  1624. (let ((count 0))
  1625. (while (and (< (point) end) (re-search-forward "\\<" end t))
  1626. (if (not (eq (char-syntax (preceding-char)) ?/))
  1627. (progn
  1628. ;; Don't count single-char words.
  1629. (unless (looking-at ".\\>") (incf count))
  1630. (forward-char 1))
  1631. (let ((cmd
  1632. (buffer-substring-no-properties
  1633. (point) (progn (when (zerop (skip-chars-forward "a-zA-Z@"))
  1634. (forward-char 1))
  1635. (point)))))
  1636. (when (member cmd tex-discount-args-cmds)
  1637. (skip-chars-forward "*")
  1638. (forward-comment (point-max))
  1639. (when (looking-at "\\[")
  1640. (forward-sexp 1)
  1641. (forward-comment (point-max)))
  1642. (if (not (looking-at "{"))
  1643. (forward-char 1)
  1644. (forward-sexp 1))))))
  1645. (message "%s words" count))))
  1646. ;;; Invoking TeX in an inferior shell.
  1647. ;; Why use a shell instead of running TeX directly? Because if TeX
  1648. ;; gets stuck, the user can switch to the shell window and type at it.
  1649. (defvar tex-error-parse-syntax-table
  1650. (let ((st (make-syntax-table)))
  1651. (modify-syntax-entry ?\( "()" st)
  1652. (modify-syntax-entry ?\) ")(" st)
  1653. (modify-syntax-entry ?\\ "\\" st)
  1654. (modify-syntax-entry ?\{ "_" st)
  1655. (modify-syntax-entry ?\} "_" st)
  1656. (modify-syntax-entry ?\[ "_" st)
  1657. (modify-syntax-entry ?\] "_" st)
  1658. ;; Single quotations may appear in errors
  1659. (modify-syntax-entry ?\" "_" st)
  1660. st)
  1661. "Syntax-table used while parsing TeX error messages.")
  1662. (defun tex-old-error-file-name ()
  1663. ;; This is unreliable, partly because we don't try very hard, and
  1664. ;; partly because TeX's output format is eminently ambiguous and unfriendly
  1665. ;; to automation.
  1666. (save-excursion
  1667. (save-match-data
  1668. (with-syntax-table tex-error-parse-syntax-table
  1669. (beginning-of-line)
  1670. (backward-up-list 1)
  1671. (skip-syntax-forward "(_")
  1672. (while (not (let ((try-filename (thing-at-point 'filename)))
  1673. (and try-filename
  1674. (not (string= "" try-filename))
  1675. (file-readable-p try-filename))))
  1676. (skip-syntax-backward "(_")
  1677. (backward-up-list 1)
  1678. (skip-syntax-forward "(_"))
  1679. (thing-at-point 'filename)))))
  1680. (defconst tex-error-regexp-alist
  1681. ;; First alternative handles the newer --file-line-error style:
  1682. ;; ./test2.tex:14: Too many }'s.
  1683. '(gnu
  1684. ;; Second handles the old-style, which spans two lines but doesn't include
  1685. ;; any file info:
  1686. ;; ! Too many }'s.
  1687. ;; l.396 toto}
  1688. ("^l\\.\\([1-9][0-9]*\\) \\(?:\\.\\.\\.\\)?\\(.*\\)$"
  1689. tex-old-error-file-name 1 nil nil nil
  1690. ;; Since there's no filename to highlight, let's highlight the message.
  1691. (2 compilation-error-face))
  1692. ;; A few common warning messages.
  1693. ("^\\(?:Und\\|Ov\\)erfull \\\\[hv]box .* at lines? \\(\\([1-9][0-9]*\\)\\(?:--\\([1-9][0-9]*\\)\\)?\\)$"
  1694. tex-old-error-file-name (2 . 3) nil 1 nil
  1695. (1 compilation-warning-face))
  1696. ("^(Font) *\\([^ \n].* on input line \\([1-9][0-9]*\\)\\)\\.$"
  1697. tex-old-error-file-name 2 nil 1 1
  1698. (2 compilation-warning-face))
  1699. ;; Included files get output as (<file> ...).
  1700. ;; FIXME: there tend to be a boatload of them at the beginning of the
  1701. ;; output which aren't that interesting. Maybe we should filter out
  1702. ;; all the file name that start with /usr/share?
  1703. ;; ("(\\.?/\\([^() \n]+\\)" 1 nil nil 0)
  1704. ))
  1705. ;; The utility functions:
  1706. (define-derived-mode tex-shell shell-mode "TeX-Shell"
  1707. (set (make-local-variable 'compilation-error-regexp-alist)
  1708. tex-error-regexp-alist)
  1709. (compilation-shell-minor-mode t))
  1710. ;;;###autoload
  1711. (defun tex-start-shell ()
  1712. (with-current-buffer
  1713. (make-comint
  1714. "tex-shell"
  1715. (or tex-shell-file-name (getenv "ESHELL") shell-file-name)
  1716. nil
  1717. ;; Specify an interactive shell, to make sure it prompts.
  1718. "-i")
  1719. (let ((proc (get-process "tex-shell")))
  1720. (set-process-sentinel proc 'tex-shell-sentinel)
  1721. (set-process-query-on-exit-flag proc nil)
  1722. (tex-shell)
  1723. (while (zerop (buffer-size))
  1724. (sleep-for 1)))))
  1725. (defun tex-feed-input ()
  1726. "Send input to the tex shell process.
  1727. In the tex buffer this can be used to continue an interactive tex run.
  1728. In the tex shell buffer this command behaves like `comint-send-input'."
  1729. (interactive)
  1730. (set-buffer (tex-shell-buf))
  1731. (comint-send-input)
  1732. (tex-recenter-output-buffer nil))
  1733. (defun tex-display-shell ()
  1734. "Make the TeX shell buffer visible in a window."
  1735. (display-buffer (tex-shell-buf))
  1736. (tex-recenter-output-buffer nil))
  1737. (defun tex-shell-sentinel (proc msg)
  1738. (cond ((null (buffer-name (process-buffer proc)))
  1739. ;; buffer killed
  1740. (set-process-buffer proc nil)
  1741. (tex-delete-last-temp-files))
  1742. ((memq (process-status proc) '(signal exit))
  1743. (tex-delete-last-temp-files))))
  1744. (defun tex-set-buffer-directory (buffer directory)
  1745. "Set BUFFER's default directory to be DIRECTORY."
  1746. (setq directory (file-name-as-directory (expand-file-name directory)))
  1747. (if (not (file-directory-p directory))
  1748. (error "%s is not a directory" directory)
  1749. (with-current-buffer buffer
  1750. (setq default-directory directory))))
  1751. (defvar tex-send-command-modified-tick 0)
  1752. (make-variable-buffer-local 'tex-send-command-modified-tick)
  1753. (defun tex-shell-proc ()
  1754. (or (tex-shell-running) (error "No TeX subprocess")))
  1755. (defun tex-shell-buf ()
  1756. (process-buffer (tex-shell-proc)))
  1757. (defun tex-shell-buf-no-error ()
  1758. (let ((proc (tex-shell-running)))
  1759. (and proc (process-buffer proc))))
  1760. (defun tex-send-command (command &optional file background)
  1761. "Send COMMAND to TeX shell process, substituting optional FILE for *.
  1762. Do this in background if optional BACKGROUND is t. If COMMAND has no *,
  1763. FILE will be appended, preceded by a blank, to COMMAND. If FILE is nil, no
  1764. substitution will be made in COMMAND. COMMAND can be any expression that
  1765. evaluates to a command string.
  1766. Return the process in which TeX is running."
  1767. (save-excursion
  1768. (let* ((cmd (eval command))
  1769. (proc (tex-shell-proc))
  1770. (buf (process-buffer proc))
  1771. (star (string-match "\\*" cmd))
  1772. (string
  1773. (concat
  1774. (if (null file)
  1775. cmd
  1776. (if (file-name-absolute-p file)
  1777. (setq file (convert-standard-filename file)))
  1778. (if star (concat (substring cmd 0 star)
  1779. (shell-quote-argument file)
  1780. (substring cmd (1+ star)))
  1781. (concat cmd " " (shell-quote-argument file))))
  1782. (if background "&" ""))))
  1783. ;; Switch to buffer before checking for subproc output in it.
  1784. (set-buffer buf)
  1785. ;; If text is unchanged since previous tex-send-command,
  1786. ;; we haven't got any output. So wait for output now.
  1787. (if (= (buffer-modified-tick buf) tex-send-command-modified-tick)
  1788. (accept-process-output proc))
  1789. (goto-char (process-mark proc))
  1790. (insert string)
  1791. (comint-send-input)
  1792. (setq tex-send-command-modified-tick (buffer-modified-tick buf))
  1793. proc)))
  1794. (defun tex-delete-last-temp-files (&optional not-all)
  1795. "Delete any junk files from last temp file.
  1796. If NOT-ALL is non-nil, save the `.dvi' file."
  1797. (if tex-last-temp-file
  1798. (let* ((dir (file-name-directory tex-last-temp-file))
  1799. (list (and (file-directory-p dir)
  1800. (file-name-all-completions
  1801. (file-name-sans-extension
  1802. (file-name-nondirectory tex-last-temp-file))
  1803. dir))))
  1804. (while list
  1805. (if not-all
  1806. (and
  1807. ;; If arg is non-nil, don't delete the .dvi file.
  1808. (not (string-match "\\.dvi$" (car list)))
  1809. (delete-file (concat dir (car list))))
  1810. (delete-file (concat dir (car list))))
  1811. (setq list (cdr list))))))
  1812. (add-hook 'kill-emacs-hook 'tex-delete-last-temp-files)
  1813. ;;
  1814. ;; Machinery to guess the command that the user wants to execute.
  1815. ;;
  1816. (defvar tex-compile-history nil)
  1817. (defvar tex-input-files-re
  1818. (eval-when-compile
  1819. (concat "\\." (regexp-opt '("tex" "texi" "texinfo"
  1820. "bbl" "ind" "sty" "cls") t)
  1821. ;; Include files with no dots (for directories).
  1822. "\\'\\|\\`[^.]+\\'")))
  1823. (defcustom tex-use-reftex t
  1824. "If non-nil, use RefTeX's list of files to determine what command to use."
  1825. :type 'boolean
  1826. :group 'tex)
  1827. (defvar tex-compile-commands
  1828. '(((concat "pdf" tex-command
  1829. " " (if (< 0 (length tex-start-commands))
  1830. (shell-quote-argument tex-start-commands)) " %f")
  1831. t "%r.pdf")
  1832. ((concat tex-command
  1833. " " (if (< 0 (length tex-start-commands))
  1834. (shell-quote-argument tex-start-commands)) " %f")
  1835. t "%r.dvi")
  1836. ("xdvi %r &" "%r.dvi")
  1837. ("\\doc-view \"%r.pdf\"" "%r.pdf")
  1838. ("xpdf %r.pdf &" "%r.pdf")
  1839. ("gv %r.ps &" "%r.ps")
  1840. ("yap %r &" "%r.dvi")
  1841. ("advi %r &" "%r.dvi")
  1842. ("gv %r.pdf &" "%r.pdf")
  1843. ("bibtex %r" "%r.aux" "%r.bbl")
  1844. ("makeindex %r" "%r.idx" "%r.ind")
  1845. ("texindex %r.??")
  1846. ("dvipdfm %r" "%r.dvi" "%r.pdf")
  1847. ("dvipdf %r" "%r.dvi" "%r.pdf")
  1848. ("dvips -o %r.ps %r" "%r.dvi" "%r.ps")
  1849. ("ps2pdf %r.ps" "%r.ps" "%r.pdf")
  1850. ("lpr %r.ps" "%r.ps"))
  1851. "List of commands for `tex-compile'.
  1852. Each element should be of the form (FORMAT IN OUT) where
  1853. FORMAT is an expression that evaluates to a string that can contain
  1854. - `%r' the main file name without extension.
  1855. - `%f' the main file name.
  1856. IN can be either a string (with the same % escapes in it) indicating
  1857. the name of the input file, or t to indicate that the input is all
  1858. the TeX files of the document, or nil if we don't know.
  1859. OUT describes the output file and is either a %-escaped string
  1860. or nil to indicate that there is no output file.")
  1861. ;; defsubst* gives better byte-code than defsubst.
  1862. (defsubst* tex-string-prefix-p (str1 str2)
  1863. "Return non-nil if STR1 is a prefix of STR2"
  1864. (eq t (compare-strings str2 nil (length str1) str1 nil nil)))
  1865. (defun tex-guess-main-file (&optional all)
  1866. "Find a likely `tex-main-file'.
  1867. Looks for hints in other buffers in the same directory or in
  1868. ALL other buffers. If ALL is `sub' only look at buffers in parent directories
  1869. of the current buffer."
  1870. (let ((dir default-directory)
  1871. (header-re tex-start-of-header))
  1872. (catch 'found
  1873. ;; Look for a buffer with `tex-main-file' set.
  1874. (dolist (buf (if (consp all) all (buffer-list)))
  1875. (with-current-buffer buf
  1876. (when (and (cond
  1877. ((null all) (equal dir default-directory))
  1878. ((eq all 'sub) (tex-string-prefix-p default-directory dir))
  1879. (t))
  1880. (stringp tex-main-file))
  1881. (throw 'found (expand-file-name tex-main-file)))))
  1882. ;; Look for a buffer containing the magic `tex-start-of-header'.
  1883. (dolist (buf (if (consp all) all (buffer-list)))
  1884. (with-current-buffer buf
  1885. (when (and (cond
  1886. ((null all) (equal dir default-directory))
  1887. ((eq all 'sub) (tex-string-prefix-p default-directory dir))
  1888. (t))
  1889. buffer-file-name
  1890. ;; (or (easy-mmode-derived-mode-p 'latex-mode)
  1891. ;; (easy-mmode-derived-mode-p 'plain-tex-mode))
  1892. (save-excursion
  1893. (save-restriction
  1894. (widen)
  1895. (goto-char (point-min))
  1896. (re-search-forward
  1897. header-re (+ (point) 10000) t))))
  1898. (throw 'found (expand-file-name buffer-file-name))))))))
  1899. (defun tex-main-file ()
  1900. "Return the relative name of the main file."
  1901. (let* ((file (or tex-main-file
  1902. ;; Compatibility with AUCTeX.
  1903. (with-no-warnings
  1904. (when (boundp 'TeX-master)
  1905. (cond ((stringp TeX-master)
  1906. (make-local-variable 'tex-main-file)
  1907. (setq tex-main-file TeX-master))
  1908. ((and (eq TeX-master t) buffer-file-name)
  1909. (file-relative-name buffer-file-name)))))
  1910. ;; Try to guess the main file.
  1911. (if (not buffer-file-name)
  1912. (error "Buffer is not associated with any file")
  1913. (file-relative-name
  1914. (if (save-excursion
  1915. (goto-char (point-min))
  1916. (re-search-forward tex-start-of-header
  1917. (+ (point) 10000) t))
  1918. ;; This is the main file.
  1919. buffer-file-name
  1920. ;; This isn't the main file, let's try to find better,
  1921. (or (tex-guess-main-file)
  1922. (tex-guess-main-file 'sub)
  1923. ;; (tex-guess-main-file t)
  1924. buffer-file-name)))))))
  1925. (if (or (file-exists-p file) (string-match "\\.tex\\'" file))
  1926. file (concat file ".tex"))))
  1927. (defun tex-summarize-command (cmd)
  1928. (if (not (stringp cmd)) ""
  1929. (mapconcat 'identity
  1930. (mapcar (lambda (s) (car (split-string s)))
  1931. (split-string cmd "\\s-*\\(?:;\\|&&\\)\\s-*"))
  1932. "&")))
  1933. (defun tex-uptodate-p (file)
  1934. "Return non-nil if FILE is not uptodate w.r.t the document source files.
  1935. FILE is typically the output DVI or PDF file."
  1936. ;; We should check all the files included !!!
  1937. (and
  1938. ;; Clearly, the target must exist.
  1939. (file-exists-p file)
  1940. ;; And the last run must not have asked for a rerun.
  1941. ;; FIXME: this should check that the last run was done on the same file.
  1942. (let ((buf (condition-case nil (tex-shell-buf) (error nil))))
  1943. (when buf
  1944. (with-current-buffer buf
  1945. (save-excursion
  1946. (goto-char (point-max))
  1947. (and (re-search-backward
  1948. (concat "(see the transcript file for additional information)"
  1949. "\\|^Output written on .*"
  1950. (regexp-quote (file-name-nondirectory file))
  1951. " (.*)\\.")
  1952. nil t)
  1953. (> (save-excursion
  1954. ;; Usually page numbers are output as [N], but
  1955. ;; I've already seen things like
  1956. ;; [1{/var/lib/texmf/fonts/map/pdftex/updmap/pdftex.map}]
  1957. (or (re-search-backward "\\[[0-9]+\\({[^}]*}\\)?\\]"
  1958. nil t)
  1959. (point-min)))
  1960. (save-excursion
  1961. (or (re-search-backward "Rerun" nil t)
  1962. (point-min)))))))))
  1963. ;; And the input files must not have been changed in the meantime.
  1964. (let ((files (if (and tex-use-reftex
  1965. (fboundp 'reftex-scanning-info-available-p)
  1966. (reftex-scanning-info-available-p))
  1967. (reftex-all-document-files)
  1968. (list (file-name-directory (expand-file-name file)))))
  1969. (ignored-dirs-re
  1970. (concat
  1971. (regexp-opt
  1972. (delq nil (mapcar (lambda (s) (if (eq (aref s (1- (length s))) ?/)
  1973. (substring s 0 (1- (length s)))))
  1974. completion-ignored-extensions))
  1975. t) "\\'"))
  1976. (uptodate t))
  1977. (while (and files uptodate)
  1978. (let ((f (pop files)))
  1979. (if (and (file-directory-p f)
  1980. ;; Avoid infinite loops.
  1981. (not (file-symlink-p f)))
  1982. (unless (string-match ignored-dirs-re f)
  1983. (setq files (nconc
  1984. (ignore-errors ;Not readable or something.
  1985. (directory-files f t tex-input-files-re))
  1986. files)))
  1987. (when (file-newer-than-file-p f file)
  1988. (setq uptodate nil)))))
  1989. uptodate)))
  1990. (autoload 'format-spec "format-spec")
  1991. (defvar tex-executable-cache nil)
  1992. (defun tex-executable-exists-p (name)
  1993. "Like `executable-find' but with a cache."
  1994. (let ((f (and (string-match "^\\\\\\([^ \t\n]+\\)" name)
  1995. (intern-soft (concat "tex-cmd-" (match-string 1 name))))))
  1996. (if (fboundp f)
  1997. f
  1998. (let ((cache (assoc name tex-executable-cache)))
  1999. (if cache (cdr cache)
  2000. (let ((executable (executable-find name)))
  2001. (push (cons name executable) tex-executable-cache)
  2002. executable))))))
  2003. (defun tex-command-executable (cmd)
  2004. (let ((s (if (stringp cmd) cmd (eval (car cmd)))))
  2005. (substring s 0 (string-match "[ \t]\\|\\'" s))))
  2006. (defun tex-command-active-p (cmd fspec)
  2007. "Return non-nil if the CMD spec might need to be run."
  2008. (let ((in (nth 1 cmd))
  2009. (out (nth 2 cmd)))
  2010. (if (stringp in)
  2011. (let ((file (format-spec in fspec)))
  2012. (when (file-exists-p file)
  2013. (or (not out)
  2014. (file-newer-than-file-p
  2015. file (format-spec out fspec)))))
  2016. (when (and (eq in t) (stringp out))
  2017. (not (tex-uptodate-p (format-spec out fspec)))))))
  2018. (defcustom tex-cmd-bibtex-args "--min-crossref=100"
  2019. "Extra args to pass to `bibtex' by default."
  2020. :type 'string
  2021. :version "23.1"
  2022. :group 'tex-run)
  2023. (defun tex-format-cmd (format fspec)
  2024. "Like `format-spec' but adds user-specified args to the command.
  2025. Only applies the FSPEC to the args part of FORMAT."
  2026. (if (not (string-match "\\([^ /\\]+\\) " format))
  2027. (format-spec format fspec)
  2028. (let* ((prefix (substring format 0 (match-beginning 0)))
  2029. (cmd (match-string 1 format))
  2030. (args (substring format (match-end 0)))
  2031. (sym (intern-soft (format "tex-cmd-%s-args" cmd)))
  2032. (extra-args (and sym (symbol-value sym))))
  2033. (concat prefix cmd
  2034. (if extra-args (concat " " extra-args))
  2035. " " (format-spec args fspec)))))
  2036. (defun tex-compile-default (fspec)
  2037. "Guess a default command given the `format-spec' FSPEC."
  2038. ;; TODO: Learn to do latex+dvips!
  2039. (let ((cmds nil)
  2040. (unchanged-in nil))
  2041. ;; Only consider active commands.
  2042. (dolist (cmd tex-compile-commands)
  2043. (when (tex-executable-exists-p (tex-command-executable cmd))
  2044. (if (tex-command-active-p cmd fspec)
  2045. (push cmd cmds)
  2046. (push (nth 1 cmd) unchanged-in))))
  2047. ;; If no command seems to be applicable, arbitrarily pick the first one.
  2048. (setq cmds (if cmds (nreverse cmds) (list (car tex-compile-commands))))
  2049. ;; Remove those commands whose input was considered stable for
  2050. ;; some other command (typically if (t . "%.pdf") is inactive
  2051. ;; then we're using pdflatex and the fact that the dvi file
  2052. ;; is nonexistent doesn't matter).
  2053. (let ((tmp nil))
  2054. (dolist (cmd cmds)
  2055. (unless (member (nth 1 cmd) unchanged-in)
  2056. (push cmd tmp)))
  2057. ;; Only remove if there's something left.
  2058. (if tmp (setq cmds (nreverse tmp))))
  2059. ;; Remove commands whose input is not uptodate either.
  2060. (let ((outs (delq nil (mapcar (lambda (x) (nth 2 x)) cmds)))
  2061. (tmp nil))
  2062. (dolist (cmd cmds)
  2063. (unless (member (nth 1 cmd) outs)
  2064. (push cmd tmp)))
  2065. ;; Only remove if there's something left.
  2066. (if tmp (setq cmds (nreverse tmp))))
  2067. ;; Select which file we're going to operate on (the latest).
  2068. (let ((latest (nth 1 (car cmds))))
  2069. (dolist (cmd (prog1 (cdr cmds) (setq cmds (list (car cmds)))))
  2070. (if (equal latest (nth 1 cmd))
  2071. (push cmd cmds)
  2072. (unless (eq latest t) ;Can't beat that!
  2073. (if (or (not (stringp latest))
  2074. (eq (nth 1 cmd) t)
  2075. (and (stringp (nth 1 cmd))
  2076. (file-newer-than-file-p
  2077. (format-spec (nth 1 cmd) fspec)
  2078. (format-spec latest fspec))))
  2079. (setq latest (nth 1 cmd) cmds (list cmd)))))))
  2080. ;; Expand the command spec into the actual text.
  2081. (dolist (cmd (prog1 cmds (setq cmds nil)))
  2082. (push (cons (eval (car cmd)) (cdr cmd)) cmds))
  2083. ;; Select the favorite command from the history.
  2084. (let ((hist tex-compile-history)
  2085. re hist-cmd)
  2086. (while hist
  2087. (setq hist-cmd (pop hist))
  2088. (setq re (concat "\\`"
  2089. (regexp-quote (tex-command-executable hist-cmd))
  2090. "\\([ \t]\\|\\'\\)"))
  2091. (dolist (cmd cmds)
  2092. ;; If the hist entry uses the same command and applies to a file
  2093. ;; of the same type (e.g. `gv %r.pdf' vs `gv %r.ps'), select cmd.
  2094. (and (string-match re (car cmd))
  2095. (or (not (string-match "%[fr]\\([-._[:alnum:]]+\\)" (car cmd)))
  2096. (string-match (regexp-quote (match-string 1 (car cmd)))
  2097. hist-cmd))
  2098. (setq hist nil cmds (list cmd)))))
  2099. ;; Substitute and return.
  2100. (if (and hist-cmd
  2101. (string-match (concat "[' \t\"]" (format-spec "%r" fspec)
  2102. "\\([;&' \t\"]\\|\\'\\)") hist-cmd))
  2103. ;; The history command was already applied to the same file,
  2104. ;; so just reuse it.
  2105. hist-cmd
  2106. (if cmds (tex-format-cmd (caar cmds) fspec))))))
  2107. (defun tex-cmd-doc-view (file)
  2108. (pop-to-buffer (find-file-noselect file)))
  2109. (defun tex-compile (dir cmd)
  2110. "Run a command CMD on current TeX buffer's file in DIR."
  2111. ;; FIXME: Use time-stamps on files to decide the next op.
  2112. (interactive
  2113. (let* ((file (tex-main-file))
  2114. (default-directory
  2115. (prog1 (file-name-directory (expand-file-name file))
  2116. (setq file (file-name-nondirectory file))))
  2117. (root (file-name-sans-extension file))
  2118. (fspec (list (cons ?r (shell-quote-argument root))
  2119. (cons ?f (shell-quote-argument file))))
  2120. (default (tex-compile-default fspec)))
  2121. (list default-directory
  2122. (completing-read
  2123. (format "Command [%s]: " (tex-summarize-command default))
  2124. (mapcar (lambda (x)
  2125. (list (tex-format-cmd (eval (car x)) fspec)))
  2126. tex-compile-commands)
  2127. nil nil nil 'tex-compile-history default))))
  2128. (save-some-buffers (not compilation-ask-about-save) nil)
  2129. (let ((f (and (string-match "^\\\\\\([^ \t\n]+\\)" cmd)
  2130. (intern-soft (concat "tex-cmd-" (match-string 1 cmd))))))
  2131. (if (functionp f)
  2132. (condition-case nil
  2133. (let ((default-directory dir))
  2134. (apply f (split-string-and-unquote
  2135. (substring cmd (match-end 0)))))
  2136. (wrong-number-of-arguments
  2137. (error "Wrong number of arguments to %s"
  2138. (substring (symbol-name f) 8))))
  2139. (if (tex-shell-running)
  2140. (tex-kill-job)
  2141. (tex-start-shell))
  2142. (tex-send-tex-command cmd dir))))
  2143. (defun tex-start-tex (command file &optional dir)
  2144. "Start a TeX run, using COMMAND on FILE."
  2145. (let* ((star (string-match "\\*" command))
  2146. (compile-command
  2147. (if star
  2148. (concat (substring command 0 star)
  2149. (shell-quote-argument file)
  2150. (substring command (1+ star)))
  2151. (concat command " "
  2152. tex-start-options
  2153. (if (< 0 (length tex-start-commands))
  2154. (concat
  2155. (shell-quote-argument tex-start-commands) " "))
  2156. (shell-quote-argument file)))))
  2157. (tex-send-tex-command compile-command dir)))
  2158. (defun tex-send-tex-command (cmd &optional dir)
  2159. (unless (or (equal dir (let ((buf (tex-shell-buf-no-error)))
  2160. (and buf (with-current-buffer buf
  2161. default-directory))))
  2162. (not dir))
  2163. (let (shell-dirtrack-verbose)
  2164. (tex-send-command tex-shell-cd-command dir)))
  2165. (with-current-buffer (process-buffer (tex-send-command cmd))
  2166. (setq compilation-last-buffer (current-buffer))
  2167. (compilation-forget-errors)
  2168. ;; Don't parse previous compilations.
  2169. (set-marker compilation-parsing-end (1- (point-max))))
  2170. (tex-display-shell)
  2171. (setq tex-last-buffer-texed (current-buffer)))
  2172. ;;; The commands:
  2173. (defun tex-region (beg end)
  2174. "Run TeX on the current region, via a temporary file.
  2175. The file's name comes from the variable `tex-zap-file' and the
  2176. variable `tex-directory' says where to put it.
  2177. If the buffer has a header, the header is given to TeX before the
  2178. region itself. The buffer's header is all lines between the strings
  2179. defined by `tex-start-of-header' and `tex-end-of-header' inclusive.
  2180. The header must start in the first 100 lines of the buffer.
  2181. The value of `tex-trailer' is given to TeX as input after the region.
  2182. The value of `tex-command' specifies the command to use to run TeX."
  2183. (interactive "r")
  2184. (if (tex-shell-running)
  2185. (tex-kill-job)
  2186. (tex-start-shell))
  2187. (or tex-zap-file
  2188. (setq tex-zap-file (tex-generate-zap-file-name)))
  2189. ;; Temp file will be written and TeX will be run in zap-directory.
  2190. ;; If the TEXINPUTS file has relative directories or if the region has
  2191. ;; \input of files, this must be the same directory as the file for
  2192. ;; TeX to access the correct inputs. That's why it's safest if
  2193. ;; tex-directory is ".".
  2194. (let* ((zap-directory
  2195. (file-name-as-directory (expand-file-name tex-directory)))
  2196. (tex-out-file (expand-file-name (concat tex-zap-file ".tex")
  2197. zap-directory))
  2198. (main-file (expand-file-name (tex-main-file)))
  2199. (ismain (string-equal main-file (buffer-file-name)))
  2200. already-output)
  2201. ;; Don't delete temp files if we do the same buffer twice in a row.
  2202. (or (eq (current-buffer) tex-last-buffer-texed)
  2203. (tex-delete-last-temp-files t))
  2204. (let ((default-directory zap-directory)) ; why?
  2205. ;; We assume the header is fully contained in tex-main-file.
  2206. ;; We use f-f-ns so we get prompted about any changes on disk.
  2207. (with-current-buffer (find-file-noselect main-file)
  2208. (setq already-output (tex-region-header tex-out-file
  2209. (and ismain beg))))
  2210. ;; Write out the specified region (but don't repeat anything
  2211. ;; already written in the header).
  2212. (write-region (if ismain
  2213. (max beg already-output)
  2214. beg)
  2215. end tex-out-file (not (zerop already-output)))
  2216. ;; Write the trailer, if any.
  2217. ;; Precede it with a newline to make sure it
  2218. ;; is not hidden in a comment.
  2219. (if tex-trailer
  2220. (write-region (concat "\n" tex-trailer) nil
  2221. tex-out-file t)))
  2222. ;; Record the file name to be deleted afterward.
  2223. (setq tex-last-temp-file tex-out-file)
  2224. ;; Use a relative file name here because (1) the proper dir
  2225. ;; is already current, and (2) the abs file name is sometimes
  2226. ;; too long and can make tex crash.
  2227. (tex-start-tex tex-command (concat tex-zap-file ".tex") zap-directory)
  2228. (setq tex-print-file tex-out-file)))
  2229. (defun tex-region-header (file &optional beg)
  2230. "If there is a TeX header in the current buffer, write it to FILE.
  2231. Return point at the end of the region so written, or zero. If
  2232. the optional buffer position BEG is specified, then the region
  2233. written out starts at BEG, if this lies before the start of the header.
  2234. If the first line matches `tex-first-line-header-regexp', it is
  2235. also written out. The variables `tex-start-of-header' and
  2236. `tex-end-of-header' are used to locate the header. Note that the
  2237. start of the header is required to be within the first 100 lines."
  2238. (save-excursion
  2239. (save-restriction
  2240. (widen)
  2241. (goto-char (point-min))
  2242. (let ((search-end (save-excursion
  2243. (forward-line 100)
  2244. (point)))
  2245. (already-output 0)
  2246. hbeg hend)
  2247. ;; Maybe copy first line, such as `\input texinfo', to temp file.
  2248. (and tex-first-line-header-regexp
  2249. (looking-at tex-first-line-header-regexp)
  2250. (write-region (point)
  2251. (progn (forward-line 1)
  2252. (setq already-output (point)))
  2253. file))
  2254. ;; Write out the header, if there is one, and any of the
  2255. ;; specified region which extends before it. But don't repeat
  2256. ;; anything already written.
  2257. (and tex-start-of-header
  2258. (re-search-forward tex-start-of-header search-end t)
  2259. (progn
  2260. (beginning-of-line)
  2261. (setq hbeg (point)) ; mark beginning of header
  2262. (when (re-search-forward tex-end-of-header nil t)
  2263. (forward-line 1)
  2264. (setq hend (point)) ; mark end of header
  2265. (write-region
  2266. (max (if beg
  2267. (min hbeg beg)
  2268. hbeg)
  2269. already-output)
  2270. hend file (not (zerop already-output)))
  2271. (setq already-output hend))))
  2272. already-output))))
  2273. (defun tex-buffer ()
  2274. "Run TeX on current buffer. See \\[tex-region] for more information.
  2275. Does not save the buffer, so it's useful for trying experimental versions.
  2276. See \\[tex-file] for an alternative."
  2277. (interactive)
  2278. (tex-region (point-min) (point-max)))
  2279. (defun tex-file ()
  2280. "Prompt to save all buffers and run TeX (or LaTeX) on current buffer's file.
  2281. This function is more useful than \\[tex-buffer] when you need the
  2282. `.aux' file of LaTeX to have the correct name."
  2283. (interactive)
  2284. (when tex-offer-save
  2285. (save-some-buffers))
  2286. (let* ((source-file (tex-main-file))
  2287. (file-dir (file-name-directory (expand-file-name source-file))))
  2288. (if (tex-shell-running)
  2289. (tex-kill-job)
  2290. (tex-start-shell))
  2291. (tex-start-tex tex-command source-file file-dir)
  2292. (setq tex-print-file (expand-file-name source-file))))
  2293. (defun tex-generate-zap-file-name ()
  2294. "Generate a unique name suitable for use as a file name."
  2295. ;; Include the shell process number and host name
  2296. ;; in case there are multiple shells (for same or different user).
  2297. ;; Dec 1998: There is a report that some versions of xdvi
  2298. ;; don't work with file names that start with #.
  2299. (format "_TZ_%d-%s"
  2300. (process-id (get-buffer-process "*tex-shell*"))
  2301. (subst-char-in-string ?. ?- (system-name))))
  2302. ;; This will perhaps be useful for modifying TEXINPUTS.
  2303. ;; Expand each file name, separated by colons, in the string S.
  2304. (defun tex-expand-files (s)
  2305. (let (elts (start 0))
  2306. (while (string-match ":" s start)
  2307. (setq elts (cons (substring s start (match-beginning 0)) elts))
  2308. (setq start (match-end 0)))
  2309. (or (= start 0)
  2310. (setq elts (cons (substring s start) elts)))
  2311. (mapconcat (lambda (elt)
  2312. (if (= (length elt) 0) elt (expand-file-name elt)))
  2313. (nreverse elts) ":")))
  2314. (defun tex-shell-running ()
  2315. (let ((proc (get-process "tex-shell")))
  2316. (when proc
  2317. (if (and (eq (process-status proc) 'run)
  2318. (buffer-live-p (process-buffer proc)))
  2319. ;; return the TeX process on success
  2320. proc
  2321. ;; get rid of the process permanently
  2322. ;; this should get rid of the annoying w32 problem with
  2323. ;; dead tex-shell buffer and live process
  2324. (delete-process proc)))))
  2325. (defun tex-kill-job ()
  2326. "Kill the currently running TeX job."
  2327. (interactive)
  2328. ;; `quit-process' leads to core dumps of the tex process (except if
  2329. ;; coredumpsize has limit 0kb as on many environments). One would
  2330. ;; like to use (kill-process proc 'lambda), however that construct
  2331. ;; does not work on some systems and kills the shell itself.
  2332. (let ((proc (get-process "tex-shell")))
  2333. (when proc (quit-process proc t))))
  2334. (defun tex-recenter-output-buffer (linenum)
  2335. "Redisplay buffer of TeX job output so that most recent output can be seen.
  2336. The last line of the buffer is displayed on
  2337. line LINE of the window, or centered if LINE is nil."
  2338. (interactive "P")
  2339. (let ((tex-shell (get-buffer "*tex-shell*"))
  2340. (window))
  2341. (if (null tex-shell)
  2342. (message "No TeX output buffer")
  2343. (setq window (display-buffer tex-shell))
  2344. (save-selected-window
  2345. (select-window window)
  2346. (bury-buffer tex-shell)
  2347. (goto-char (point-max))
  2348. (recenter (if linenum
  2349. (prefix-numeric-value linenum)
  2350. (/ (window-height) 2)))))))
  2351. (defun tex-print (&optional alt)
  2352. "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
  2353. Runs the shell command defined by `tex-dvi-print-command'. If prefix argument
  2354. is provided, use the alternative command, `tex-alt-dvi-print-command'."
  2355. (interactive "P")
  2356. (let ((print-file-name-dvi (tex-append tex-print-file ".dvi"))
  2357. test-name)
  2358. (if (and (not (equal (current-buffer) tex-last-buffer-texed))
  2359. (buffer-file-name)
  2360. ;; Check that this buffer's printed file is up to date.
  2361. (file-newer-than-file-p
  2362. (setq test-name (tex-append (buffer-file-name) ".dvi"))
  2363. (buffer-file-name)))
  2364. (setq print-file-name-dvi test-name))
  2365. (if (not (file-exists-p print-file-name-dvi))
  2366. (error "No appropriate `.dvi' file could be found")
  2367. (if (tex-shell-running)
  2368. (tex-kill-job)
  2369. (tex-start-shell))
  2370. (tex-send-command
  2371. (if alt tex-alt-dvi-print-command tex-dvi-print-command)
  2372. print-file-name-dvi
  2373. t))))
  2374. (defun tex-alt-print ()
  2375. "Print the .dvi file made by \\[tex-region], \\[tex-buffer] or \\[tex-file].
  2376. Runs the shell command defined by `tex-alt-dvi-print-command'."
  2377. (interactive)
  2378. (tex-print t))
  2379. (defun tex-view ()
  2380. "Preview the last `.dvi' file made by running TeX under Emacs.
  2381. This means, made using \\[tex-region], \\[tex-buffer] or \\[tex-file].
  2382. The variable `tex-dvi-view-command' specifies the shell command for preview.
  2383. You must set that variable yourself before using this command,
  2384. because there is no standard value that would generally work."
  2385. (interactive)
  2386. (or tex-dvi-view-command
  2387. (error "You must set `tex-dvi-view-command'"))
  2388. ;; Restart the TeX shell if necessary.
  2389. (or (tex-shell-running)
  2390. (tex-start-shell))
  2391. (let ((tex-dvi-print-command (eval tex-dvi-view-command)))
  2392. (tex-print)))
  2393. (defun tex-append (file-name suffix)
  2394. "Append to FILENAME the suffix SUFFIX, using same algorithm TeX uses.
  2395. Pascal-based TeX scans for the first period, C TeX uses the last.
  2396. No period is retained immediately before SUFFIX,
  2397. so normally SUFFIX starts with one."
  2398. (if (stringp file-name)
  2399. (let ((file (file-name-nondirectory file-name))
  2400. trial-name)
  2401. ;; Try splitting on last period.
  2402. ;; The first-period split can get fooled when two files
  2403. ;; named a.tex and a.b.tex are both tex'd;
  2404. ;; the last-period split must be right if it matches at all.
  2405. (setq trial-name
  2406. (concat (file-name-directory file-name)
  2407. (substring file 0
  2408. (string-match "\\.[^.]*$" file))
  2409. suffix))
  2410. (if (or (file-exists-p trial-name)
  2411. (file-exists-p (concat trial-name ".aux"))) ;for BibTeX files
  2412. trial-name
  2413. ;; Not found, so split on first period.
  2414. (concat (file-name-directory file-name)
  2415. (substring file 0
  2416. (string-match "\\." file))
  2417. suffix)))
  2418. " "))
  2419. (defun tex-show-print-queue ()
  2420. "Show the print queue that \\[tex-print] put your job on.
  2421. Runs the shell command defined by `tex-show-queue-command'."
  2422. (interactive)
  2423. (if (tex-shell-running)
  2424. (tex-kill-job)
  2425. (tex-start-shell))
  2426. (tex-send-command tex-show-queue-command)
  2427. (tex-display-shell))
  2428. (defun tex-bibtex-file ()
  2429. "Run BibTeX on the current buffer's file."
  2430. (interactive)
  2431. (if (tex-shell-running)
  2432. (tex-kill-job)
  2433. (tex-start-shell))
  2434. (let* (shell-dirtrack-verbose
  2435. (source-file (expand-file-name (tex-main-file)))
  2436. (tex-out-file
  2437. (tex-append (file-name-nondirectory source-file) ""))
  2438. (file-dir (file-name-directory source-file)))
  2439. (tex-send-command tex-shell-cd-command file-dir)
  2440. (tex-send-command tex-bibtex-command tex-out-file))
  2441. (tex-display-shell))
  2442. ;;;;
  2443. ;;;; LaTeX indentation
  2444. ;;;;
  2445. (defvar tex-indent-allhanging t)
  2446. (defvar tex-indent-arg 4)
  2447. (defvar tex-indent-basic 2)
  2448. (defvar tex-indent-item tex-indent-basic)
  2449. (defvar tex-indent-item-re "\\\\\\(bib\\)?item\\>")
  2450. (defvar latex-noindent-environments '("document"))
  2451. (defvar tex-latex-indent-syntax-table
  2452. (let ((st (make-syntax-table tex-mode-syntax-table)))
  2453. (modify-syntax-entry ?$ "." st)
  2454. (modify-syntax-entry ?\( "." st)
  2455. (modify-syntax-entry ?\) "." st)
  2456. st)
  2457. "Syntax table used while computing indentation.")
  2458. (defun latex-indent (&optional arg)
  2459. (if (and (eq (get-text-property (line-beginning-position) 'face)
  2460. 'tex-verbatim))
  2461. 'noindent
  2462. (with-syntax-table tex-latex-indent-syntax-table
  2463. ;; TODO: Rather than ignore $, we should try to be more clever about it.
  2464. (let ((indent
  2465. (save-excursion
  2466. (beginning-of-line)
  2467. (latex-find-indent))))
  2468. (if (< indent 0) (setq indent 0))
  2469. (if (<= (current-column) (current-indentation))
  2470. (indent-line-to indent)
  2471. (save-excursion (indent-line-to indent)))))))
  2472. (defcustom latex-indent-within-escaped-parens nil
  2473. "Non-nil means add extra indent to text within escaped parens.
  2474. When this is non-nil, text within matching pairs of escaped
  2475. parens is indented at the column following the open paren. The
  2476. default value does not add any extra indent thus providing the
  2477. behavior of Emacs 22 and earlier."
  2478. :type 'boolean
  2479. :group 'tex
  2480. :version "23.1")
  2481. (defun latex-find-indent (&optional virtual)
  2482. "Find the proper indentation of text after point.
  2483. VIRTUAL if non-nil indicates that we're only trying to find the indentation
  2484. in order to determine the indentation of something else.
  2485. There might be text before point."
  2486. (let ((latex-handle-escaped-parens latex-indent-within-escaped-parens))
  2487. (save-excursion
  2488. (skip-chars-forward " \t")
  2489. (or
  2490. ;; Stick the first line at column 0.
  2491. (and (= (point-min) (line-beginning-position)) 0)
  2492. ;; Trust the current indentation, if such info is applicable.
  2493. (and virtual (save-excursion (skip-chars-backward " \t&") (bolp))
  2494. (current-column))
  2495. ;; Stick verbatim environments to the left margin.
  2496. (and (looking-at "\\\\\\(begin\\|end\\) *{\\([^\n}]+\\)")
  2497. (member (match-string 2) tex-verbatim-environments)
  2498. 0)
  2499. ;; Put leading close-paren where the matching open paren would be.
  2500. (let (escaped)
  2501. (and (or (eq (latex-syntax-after) ?\))
  2502. ;; Try to handle escaped close parens but keep
  2503. ;; original position if it doesn't work out.
  2504. (and latex-handle-escaped-parens
  2505. (setq escaped (looking-at "\\\\\\([])}]\\)"))))
  2506. (ignore-errors
  2507. (save-excursion
  2508. (when escaped
  2509. (goto-char (match-beginning 1)))
  2510. (latex-skip-close-parens)
  2511. (latex-backward-sexp-1)
  2512. (latex-find-indent 'virtual)))))
  2513. ;; Default (maybe an argument)
  2514. (let ((pos (point))
  2515. ;; Outdent \item if necessary.
  2516. (indent (if (looking-at tex-indent-item-re) (- tex-indent-item) 0))
  2517. up-list-pos)
  2518. ;; Find the previous point which determines our current indentation.
  2519. (condition-case err
  2520. (progn
  2521. (latex-backward-sexp-1)
  2522. (while (> (current-column) (current-indentation))
  2523. (latex-backward-sexp-1)))
  2524. (scan-error
  2525. (setq up-list-pos (nth 2 err))))
  2526. (cond
  2527. ((= (point-min) pos) 0) ; We're really just indenting the first line.
  2528. ((integerp up-list-pos)
  2529. ;; Have to indent relative to the open-paren.
  2530. (goto-char up-list-pos)
  2531. (if (and (not tex-indent-allhanging)
  2532. (save-excursion
  2533. ;; Make sure we're an argument to a macro and
  2534. ;; that the macro is at the beginning of a line.
  2535. (condition-case nil
  2536. (progn
  2537. (while (eq (char-syntax (char-after)) ?\()
  2538. (forward-sexp -1))
  2539. (and (eq (char-syntax (char-after)) ?/)
  2540. (progn (skip-chars-backward " \t&")
  2541. (bolp))))
  2542. (scan-error nil)))
  2543. (> pos (progn (latex-down-list)
  2544. (forward-comment (point-max))
  2545. (point))))
  2546. ;; Align with the first element after the open-paren.
  2547. (current-column)
  2548. ;; We're the first element after a hanging brace.
  2549. (goto-char up-list-pos)
  2550. (+ (if (and (looking-at "\\\\begin *{\\([^\n}]+\\)")
  2551. (member (match-string 1)
  2552. latex-noindent-environments))
  2553. 0 tex-indent-basic)
  2554. indent (latex-find-indent 'virtual))))
  2555. ;; We're now at the "beginning" of a line.
  2556. ((not (and (not virtual) (eq (char-after) ?\\)))
  2557. ;; Nothing particular here: just keep the same indentation.
  2558. (+ indent (current-column)))
  2559. ;; We're now looking at a macro call.
  2560. ((looking-at tex-indent-item-re)
  2561. ;; Indenting relative to an item, have to re-add the outdenting.
  2562. (+ indent (current-column) tex-indent-item))
  2563. (t
  2564. (let ((col (current-column)))
  2565. (if (or (not (eq (char-syntax (or (char-after pos) ?\s)) ?\())
  2566. ;; Can't be an arg if there's an empty line inbetween.
  2567. (save-excursion (re-search-forward "^[ \t]*$" pos t)))
  2568. ;; If the first char was not an open-paren, there's
  2569. ;; a risk that this is really not an argument to the
  2570. ;; macro at all.
  2571. (+ indent col)
  2572. (forward-sexp 1)
  2573. (if (< (line-end-position)
  2574. (save-excursion (forward-comment (point-max))
  2575. (point)))
  2576. ;; we're indenting the first argument.
  2577. (min (current-column) (+ tex-indent-arg col))
  2578. (skip-syntax-forward " ")
  2579. (current-column)))))))))))
  2580. ;;; DocTeX support
  2581. (defun doctex-font-lock-^^A ()
  2582. (if (eq (char-after (line-beginning-position)) ?\%)
  2583. (progn
  2584. (put-text-property
  2585. (1- (match-beginning 1)) (match-beginning 1)
  2586. 'syntax-table
  2587. (if (= (1+ (line-beginning-position)) (match-beginning 1))
  2588. ;; The `%' is a single-char comment, which Emacs
  2589. ;; syntax-table can't deal with. We could turn it
  2590. ;; into a non-comment, or use `\n%' or `%^' as the comment.
  2591. ;; Instead, we include it in the ^^A comment.
  2592. (string-to-syntax "< b")
  2593. (string-to-syntax ">")))
  2594. (let ((end (line-end-position)))
  2595. (if (< end (point-max))
  2596. (put-text-property
  2597. end (1+ end)
  2598. 'syntax-table
  2599. (string-to-syntax "> b"))))
  2600. (string-to-syntax "< b"))))
  2601. (defun doctex-font-lock-syntactic-face-function (state)
  2602. ;; Mark DocTeX documentation, which is parsed as a style A comment
  2603. ;; starting in column 0.
  2604. (if (or (nth 3 state) (nth 7 state)
  2605. (not (memq (char-before (nth 8 state))
  2606. '(?\n nil))))
  2607. ;; Anything else is just as for LaTeX.
  2608. (tex-font-lock-syntactic-face-function state)
  2609. font-lock-doc-face))
  2610. (eval-when-compile
  2611. (defconst doctex-syntax-propertize-rules
  2612. (syntax-propertize-precompile-rules
  2613. latex-syntax-propertize-rules
  2614. ;; For DocTeX comment-in-doc.
  2615. ("\\(\\^\\)\\^A" (1 (doctex-font-lock-^^A))))))
  2616. (defvar doctex-font-lock-keywords
  2617. (append tex-font-lock-keywords
  2618. '(("^%<[^>]*>" (0 font-lock-preprocessor-face t)))))
  2619. ;;;###autoload
  2620. (define-derived-mode doctex-mode latex-mode "DocTeX"
  2621. "Major mode to edit DocTeX files."
  2622. (setq font-lock-defaults
  2623. (cons (append (car font-lock-defaults) '(doctex-font-lock-keywords))
  2624. (mapcar
  2625. (lambda (x)
  2626. (case (car-safe x)
  2627. (font-lock-syntactic-face-function
  2628. (cons (car x) 'doctex-font-lock-syntactic-face-function))
  2629. (t x)))
  2630. (cdr font-lock-defaults))))
  2631. (set (make-local-variable 'syntax-propertize-function)
  2632. (syntax-propertize-rules doctex-syntax-propertize-rules)))
  2633. (run-hooks 'tex-mode-load-hook)
  2634. (provide 'tex-mode)
  2635. ;;; tex-mode.el ends here