switch on show-paren-mode unconditionally
[hemmecke/mathematica-el.git] / mathematica.el
1 ;; mathematica.el for GNU emacs 21.2.1 -- two modes for Mathematica.
2 ;; Version: June 2004
3
4 ;; Author:     Burkhard Zimmermann
5 ;; Maintainer: Burkhard Zimmermann <B.Zimmermann@risc.uni-linz.ac.at>
6 ;; Credits:
7 ;;    mathematica.el is derived from Tim Wichmann's mode mma.el.
8 ;;    In particular, it takes its font-lock support from there.
9
10 ;; This program is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2 of the License, or
13 ;; (at your option) any later version.
14 ;;
15 ;; This program is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19 ;;
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with this program; if not, write to the Free Software
22 ;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23
24 ;; This file is not part of GNU Emacs but the same permissions apply.
25
26 ;; Note: Mathematica is a registered trademark of Wolfram Research, Inc.
27
28
29 ;; declares two modes:
30
31 ;; mathematica-m-mode       , for editing *.m packages.
32 ;; mathematica-comint-mode  , for interaction with the Matheamtica kernel (math).
33
34 ;; the modes are meant to be used together, they interact smoothly.
35
36 ;;; Commentary:
37
38 ;;; Installation:
39
40 ;; To use mathematica-m-mode you should add the following to your .emacs file:
41 ;;   (autoload 'mathematica-m-mode "mathematica.el" "Mathematica package file mode" t)
42 ;;   (setq auto-mode-alist (cons '("\\.m\\'" . mathematica-m-mode) auto-mode-alist))
43
44
45 ;;; Use:
46
47 ;; Trick: In the Mathematica buffer, type ?* to initialize an improved dabbrev completion.
48
49 ;;;; Customization:
50
51 ;; Optionally, you may configure it using mathematica-m-mode-hook. For instance, activating
52 ;; the show-paren-mode for Mathematica buffers can be done as follows:
53
54 ;;   (setq mathematica-m-mode-hook (function (lambda () (interactive)
55 ;;          (setq mathematica-m-mode-hook-done 1)
56 ;;          (show-paren-mode)
57 ;;          )))
58
59
60 ;;;; Notes to the Maintainer:
61
62 ;; bugs/todo:
63
64 ;; change history:
65
66 ;; June 21, 2004: fix for (goto-char eline); I moved it after the pop-to-buffer command.
67
68 ;; June 17, 2004:
69 ;;    fix to get the rigth window-width for the Mathematica process buffer.
70 ;;
71 ;; June 16, 2004:
72
73 ;;    3. respects the window layout of the user:
74 ;;       uses pop-to-buffer, and no longer switch-to-buffer.
75 ;;       we set pop-up-windows, a configuration variable for pop-to-buffer, to nil.
76
77 ;;    2. dabbrev friend buffers configured
78
79 ;;    1. indentation modified
80
81 ;;    0.
82 ;;    changed to dabbrev-expand,
83 ;;    since dabbrev-completion bugs the user with a list of possible completions in a new window.
84 ;; May 24, 2004: write a mode help text (appears with C-h m).
85 ;; May 24, 2004: dabbrev support in the *mathematica* shell buffer, too.
86 ;; Feb 1, 2003: add indentation support.
87
88 ;; Jan 30, 2003:
89 ;; support Mathematica's nested comments.
90 ;; comment delims in strings, ie " (* ", don't count.
91
92 ;; Jan 28, 2003: removed debug support.
93 ;;         removed indentation support.
94
95 ;; Jan 27, 2003: Started from mma.el,v 1.32 2000/06/27 16:05:19
96 ;; Author: Tim Wichmann <wichmann@itwm.uni-kl.de>
97
98
99 ;;;; Code:
100
101 (defconst mathematica-m-version "June 2004"
102   "The version of mathematica.el.
103 You should add this number when reporting bugs.")
104
105 (defgroup mathematica-m nil
106   "Emacs interface for editing Mathematica *.m files."
107   :group 'languages)
108
109 (defvar mathematica-m-mode-syntax-table nil
110   "Syntax table used in mathematica-m mode.")
111
112 (if mathematica-m-mode-syntax-table
113     ()
114   (setq mathematica-m-mode-syntax-table (make-syntax-table (standard-syntax-table)))
115 ; %, &, ... are used for punctuation, ie they may not appear in identifiers.
116   (modify-syntax-entry ?% "." mathematica-m-mode-syntax-table)
117   (modify-syntax-entry ?& "." mathematica-m-mode-syntax-table)
118   (modify-syntax-entry ?+ "." mathematica-m-mode-syntax-table)
119   (modify-syntax-entry ?- "." mathematica-m-mode-syntax-table)
120   (modify-syntax-entry ?/ "." mathematica-m-mode-syntax-table)
121   (modify-syntax-entry ?^ "." mathematica-m-mode-syntax-table)
122   (modify-syntax-entry ?< "." mathematica-m-mode-syntax-table)
123   (modify-syntax-entry ?= "." mathematica-m-mode-syntax-table)
124   (modify-syntax-entry ?> "." mathematica-m-mode-syntax-table)
125   (modify-syntax-entry ?| "." mathematica-m-mode-syntax-table)
126   (modify-syntax-entry ?_ "." mathematica-m-mode-syntax-table)
127 ; ' is used for mathematica "contexts".
128 ; following wichmann, we consider it punctuation.
129   (modify-syntax-entry ?\' "." mathematica-m-mode-syntax-table)
130 ; $ is allowed in identifiers
131   (modify-syntax-entry ?$ "_" mathematica-m-mode-syntax-table)
132 ; \ is an escape
133   (modify-syntax-entry ?\\ "\\" mathematica-m-mode-syntax-table)
134 ; " is a string quote
135 ; ...
136 ; the properties of ( are:
137 ;   (: it is an open-parenthesis character.
138 ;   ): its matching anticharacter is ).
139 ;   1: it is the first character of the comment delimiters "(**)",
140 ;   n:   such comments may [n]est.
141 ; (bug in Wichmann's mode: "n" is missing).
142   (modify-syntax-entry ?( "()1n" mathematica-m-mode-syntax-table)
143
144 ; the properties of ) are:
145 ;   ): it is a close-parenthesis character.
146 ;   (: its matching anticharacter is (.
147 ;   4: it is the fourth character of the "(**)"
148 ;   n:   such comments may [n]est.
149   (modify-syntax-entry ?) ")(4n" mathematica-m-mode-syntax-table)
150
151 ; * has two functions:
152 ; 1. punctuation
153 ; 2. characters 2 and 3 in the comment delimiters "(**)"
154 ;   n:   such comments may [n]est.
155   (modify-syntax-entry ?* ". 23n" mathematica-m-mode-syntax-table)
156
157 ; the properties of [ are:
158 ;   (: it is an open-parenthesis character.
159 ;   ]: its matching anticharacter is ].
160   (modify-syntax-entry ?\[ "(]" mathematica-m-mode-syntax-table)
161
162 ; the properties of ] are:
163 ;   ): it is a close-parenthesis character.
164 ;   [: its matching anticharacter is [.
165   (modify-syntax-entry ?\] ")[" mathematica-m-mode-syntax-table)
166
167 ; the properties of { are:
168 ;   (: it is an open-parenthesis character.
169 ;   }: its matching anticharacter is }.
170   (modify-syntax-entry ?\{ "(}" mathematica-m-mode-syntax-table)
171
172 ; the properties of } are:
173 ;   ): it is a close-parenthesis character.
174 ;   {: its matching anticharacter is {.
175   (modify-syntax-entry ?\] ")[" mathematica-m-mode-syntax-table)
176 )
177
178 (defvar mathematica-m-mode-map ()
179   "Key map to use in mathematica-m mode.")
180
181 ;(if mathematica-m-mode-map
182 ;    ()
183 (setq mathematica-m-mode-map (make-sparse-keymap))
184 ; the order is upside-down, to get a nice text in the mode help,
185 ; i.e., the most importand command comes last.
186 (define-key mathematica-m-mode-map [tab] 'mathematica-m-tab-command)
187 (define-key mathematica-m-mode-map [M-right] 'indent-selection-rigidly)
188 (define-key mathematica-m-mode-map [M-left]  'dedent-selection-rigidly)
189 (define-key mathematica-m-mode-map [C-tab] 'switch-to-mathematica-comint)
190 (define-key mathematica-m-mode-map [f3] 'mathematica-comint-start-process)
191 (define-key mathematica-m-mode-map [f2] 'mathematica-comint-load)
192 ;)
193
194 ; just for testing mathematica.el:
195 ;(define-key mathematica-m-mode-map [f4] 'indent-relative-maybe)
196
197 ; Ctrl-tab in *.m
198 (defun switch-to-mathematica-comint ()
199   ""
200   (interactive)
201   (pop-to-buffer "*mathematica*"))
202
203 ; Ctrl-tab in comint
204 (defun switch-to-mathematica-m ()
205   ""
206   (interactive)
207   (pop-to-buffer mathematica-comint-last-buffer))
208
209 ; tab is bound by
210 ;    (define-key mathematica-m-mode-map [tab] 'mathematica-m-tab-command)
211 ; to this:
212
213 (defun mathematica-m-tab-command ()
214   ""
215   (interactive)
216   (if (or (bolp) nil) ; (empty-line-p)) ; if at an empty line or at the beginning of a line,
217 ; note: statt bolp haette ich lieber: wenn links vom cursor nur whitespace ist.
218      (indent-relative-maybe) ; then: indent;     ;(indent-for-tab-command)
219      (dabbrev-expand nil) ;  otherwise: expand word.
220                           ; the argument nil is needed. I don't know what it means.
221   )
222 )
223
224 ; debug code: (global-set-key [f5] 'mathematica-m-tab-command)
225
226         
227         
228 ; does not work the way it should.
229 ;(defun empty-line-p ()
230 ;  "Checks if the current line is empty."
231 ;  (save-excursion
232 ;    (beginning-of-line)
233 ;    (looking-at "[ \t]*$")))
234
235 (defun indent-selection-rigidly-by (n)
236   (let ((start (point))
237         (end   (mark) ))
238     (indent-rigidly (min start end) (max start end) n) ; min and max are indeed needed here.
239     ;"preserves the shape" of the affected region, moving it as a rigid unit
240 ))
241
242 (defun indent-selection-rigidly ()
243   ""
244   (interactive)
245   (indent-selection-rigidly-by 1))
246
247 (defun dedent-selection-rigidly ()
248   ""
249   (interactive)
250   (indent-selection-rigidly-by -1))
251
252
253
254
255
256
257 ;;;(make-regexp '("If" "While" "Print" "Module" "With" "Block" "Switch"
258 ;;;               "Return""Begin" "End" "BeginPackage" "EndPackage"
259 ;;;               "Which" "Do" "For" "Throw" "Catch" "Check" "Break"
260 ;;;               "Continue" "Goto" "Label" "Abort" "Message"))
261 ;;;;;;;;
262
263 ;;;(make-regexp '("If" "While")) "Print" "Module" "With" "Block" "Switch"
264 ;;;               "Return""Begin" "End" "BeginPackage" "EndPackage"
265 ;;;               "Which" "Do" "For" "Throw" "Catch" "Check" "Break"
266 ;;;               "Continue" "Goto" "Label" "Abort" "Message"))
267 ;;;;;;;;
268
269
270 ; built using:
271 ; ?* (in mathematica) followed by (make-regexp).
272 ;(defvar mathematica-m-font-lock-keywords-1
273 ;  (list
274 ;   '("\\(^[a-zA-Z]\\w*\\)\\([ \t]*=[ \t]*Compile\\|\\[\\([ \t]*\\]\\|.*\\(_\\|:\\)\\)\\)"
275 ;     1 font-lock-function-name-face)
276 ;   '("\\<\\(\\$\\(Aborted\\|B\\(atch\\(Input\\|Output\\)\\|yteOrdering\\)\\|C\\(haracterEncoding\\|o\\(mmandLine\\|ntext\\(Path\\)?\\)\\|reationDate\\|urrentLink\\)\\|Display\\(Function\\)?\\|E\\(cho\\|pilog\\|xportFormats\\)\\|F\\(ailed\\|ormatType\\|rontEnd\\)\\|H\\(istoryLength\\|omeDirectory\\)\\|I\\(gnoreEOF\\|mportFormats\\|n\\(itialDirectory\\|put\\|s\\(pector\\|tallationDate\\)\\)\\|terationLimit\\)\\|L\\(a\\(nguage\\|unchDirectory\\)\\|in\\(e\\|ked\\)\\)\\|M\\(a\\(chine\\(Domain\\|Epsilon\\|ID\\|Name\\|Precision\\|Type\\)\\|x\\(ExtraPrecision\\|MachineNumber\\|Number\\|Precision\\)\\)\\|essage\\(List\\|PrePrint\\|s\\)\\|in\\(MachineNumber\\|Number\\|Precision\\)\\|oduleNumber\\)\\|N\\(ew\\(Message\\|Symbol\\)\\|otebooks\\|umberMarks\\)\\|O\\(peratingSystem\\|utput\\)\\|P\\(a\\(ckages\\|rent\\(Link\\|ProcessID\\)\\|th\\)\\|ost\\|r\\(e\\(Print\\|Read\\)?\\|ocess\\(ID\\|orType\\)\\)\\)\\|R\\(andomState\\|e\\(cursionLimit\\|leaseNumber\\)\\)\\|S\\(essionID\\|oundDisplayFunction\\|y\\(ntaxHandler\\|stem\\(CharacterEncoding\\|ID\\)?\\)\\)\\|T\\(extStyle\\|imeUnit\\|opDirectory\\)\\|U\\(rgent\\|serName\\)\\|Version\\(Number\\)?\\)\\|A\\(b\\(ort\\(Protect\\)?\\|s\\(olute\\(Dashing\\|Options\\|PointSize\\|T\\(hickness\\|ime\\)\\)\\)?\\)\\|c\\(c\\(ountingForm\\|uracy\\(Goal\\)?\\)\\|tive\\)\\|d\\(dTo\\|justmentBox\\)\\|iry\\(Ai\\(Prime\\)?\\|Bi\\(Prime\\)?\\)\\|l\\(gebraics\\|l\\|ternatives\\)\\|mbientLight\\|n\\(choredSearch\\|d\\|imationDi\\(rection\\|splayTime\\)\\)\\|p\\(art\\|p\\(e\\(llF1\\|nd\\(To\\)?\\)\\|ly\\)\\)\\|r\\(c\\(C\\(o\\(sh\\|th\\|[st]\\)\\|sch?\\)\\|S\\(ech?\\|inh?\\)\\|Tanh?\\)\\|g\\|ithmeticGeometricMean\\|ray\\)\\|s\\(pectRatio\\(Fixed\\)?\\|sumptions\\)\\|t\\(omQ\\|tributes\\)\\|uto\\(I\\(ndent\\|talicWords\\)\\|Spacing\\|matic\\)\\|xes\\(Edge\\|Label\\|Origin\\|Style\\)?\\)\\|B\\(a\\(ckground\\|seForm\\)\\|e\\(gin\\(Package\\)?\\|rnoulliB\\|ssel[IJKY]\\|ta\\(Regularized\\)?\\)\\|i\\(nomial\\|t\\(And\\|Not\\|Or\\|Xor\\)\\)\\|l\\(ank\\(NullSequence\\|Sequence\\)?\\|ock\\)\\|o\\(oleans\\|x\\(Ratios\\|Style\\|ed\\)\\)\\|reak\\|utton\\(Box\\|Data\\|E\\(valuator\\|xpandable\\)\\|F\\(rame\\|unction\\)\\|M\\(argins\\|inHeight\\)\\|Note\\(book\\)?\\|S\\(ource\\|tyle\\)\\)\\|yte\\(Count\\)?\\)\\|C\\(Form\\|MYKColor\\|a\\(ncel\\|rmichaelLambda\\|ses\\|t\\(alan\\|ch\\)\\)\\|e\\(iling\\|ll\\(AutoOverwrite\\|Baseline\\|Dingbat\\|E\\(ditDuplicate\\|valuationDuplicate\\)\\|Frame\\(Margins\\)?\\|Group\\(Data\\|ing\\)\\|Label\\(AutoDelete\\)?\\|Margins\\|Open\\|Print\\|Tags\\)?\\)\\|h\\(aracter\\(Encoding\\|Range\\|s\\)?\\|e\\(byshev[TU]\\|ck\\(Abort\\)?\\)\\|op\\)\\|ircle\\|l\\(e\\(ar\\(A\\(ll\\|ttributes\\)\\)?\\|bschGordan\\)\\|ipFill\\|ose\\)\\|o\\(efficient\\(List\\)?\\|l\\(lect\\|or\\(Function\\(Scaling\\)?\\|Output\\)\\|umn\\(Alignments\\|Form\\|Lines\\|Spacings\\|Widths\\|sEqual\\)\\)\\|mp\\(ile\\(d\\(Function\\)?\\)?\\|le\\(ment\\|x\\(Expand\\|Infinity\\|es\\|ityFunction\\)?\\)\\|o\\(s\\(e\\(List\\|Series\\)\\|ition\\)\\|undExpression\\)\\)\\|n\\(dition\\|jugate\\|st\\(ants?\\|rainedM\\(ax\\|in\\)\\)\\|t\\(exts?\\|inue\\(dFraction\\)?\\|our\\(Graphics\\|Lines\\|Plot\\|S\\(hading\\|tyle\\)\\|s\\)\\)\\|versionRules\\)\\|py\\(Directory\\|File\\|able\\)\\|s\\(Integral\\|h\\(Integral\\)?\\)\\|th\\|unt\\|[st]\\)\\|r\\(eateDirectory\\|oss\\)\\|sch?\\|uboid\\|yclotomic\\)\\|D\\(Solve\\|a\\(shing\\|te\\)\\|e\\(c\\(larePackage\\|ompose\\|rement\\)\\|dekindEta\\|f\\(ault\\(Color\\|DuplicateCellStyle\\|NewCellStyle\\)?\\|inition\\)\\|gree\\|l\\(et\\(able\\|e\\(Cases\\|Directory\\|File\\)?\\)\\|imiterFlashTime\\)\\|n\\(ominator\\|sity\\(Graphics\\|Plot\\)\\)\\|pth\\|rivative\\|t\\)\\|i\\(a\\(gonalMatrix\\|log\\(Prolog\\|Symbols\\)?\\)\\|git\\(Block\\|Count\\|Q\\)\\|mensions\\|r\\(acDelta\\|ect\\(edInfinity\\|ory\\(Name\\|Stack\\)?\\)\\)\\|s\\(creteDelta\\|k\\|p\\(atch\\|lay\\(F\\(orm\\|unction\\)\\|String\\)?\\)\\|tribute\\)\\|vi\\(de\\(By\\)?\\|sor\\(Sigma\\|s\\)\\)\\)\\|o\\(t\\|wnValues\\)\\|r\\(agAndDrop\\|op\\)\\|umpSave\\|[ot]\\)\\|E\\(d\\(geForm\\|itable\\)\\|igen\\(system\\|v\\(alues\\|ectors\\)\\)\\|l\\(ement\\|iminate\\|liptic\\(Exp\\|Log\\|NomeQ\\|Pi\\|Theta\\(Prime\\)?\\|[EFK]\\)\\)\\|n\\(code\\|d\\(OfFile\\|Package\\)?\\|gineeringForm\\|vironment\\)\\|pilog\\|qual\\|r\\(f[ci]?\\|rorBox\\)\\|uler\\(E\\|Gamma\\|Phi\\)\\|v\\(aluat\\(able\\|e\\|ionNotebook\\|or\\)\\|enQ\\)\\|x\\(cludedForms\\|it\\|p\\(IntegralEi?\\|ToTrig\\|and\\(All\\|Denominator\\|Numerator\\)?\\|o\\(nent\\(Function\\)?\\|rt\\(String\\)?\\)\\|ression\\)?\\|t\\(en\\(dedGCD\\|sion\\)\\|ract\\)\\)\\)\\|F\\(a\\(c\\(e\\(Form\\|Grids\\)\\|tor\\(Integer\\|List\\|SquareFree\\(List\\)?\\|Terms\\(List\\)?\\|ial2?\\)?\\)\\|lse\\)\\|i\\(bonacci\\|le\\(ByteCount\\|Date\\|Names\\|Type\\)\\|nd\\(List\\|Minimum\\|Root\\)?\\|rst\\|t\\|xedPoint\\(List\\)?\\)\\|l\\(at\\(ten\\(At\\)?\\)?\\|oor\\)\\|o\\(ld\\(List\\)?\\|nt\\(Color\\|Family\\|S\\(ize\\|lant\\|ubstitutions\\)\\|Tracking\\|Weight\\)\\|r\\(m\\(Box\\|at\\(Type\\)?\\)\\|tranForm\\)?\\|urier\\(CosTransform\\|SinTransform\\|Transform\\)?\\)\\|r\\(a\\(ction\\(Box\\|alPart\\)\\|me\\(Box\\|Label\\|Style\\|Ticks\\)?\\)\\|e\\(eQ\\|snel[CS]\\)\\|o\\(m\\(C\\(haracterCode\\|ontinuedFraction\\)\\|D\\(ate\\|igits\\)\\)\\|ntEndExecute\\)\\)\\|u\\(ll\\(Definition\\|Form\\|Graphics\\|Simplify\\)\\|nction\\(Expand\\|Interpolation\\)?\\)\\)\\|G\\(CD\\|a\\(mma\\(Regularized\\)?\\|ussianIntegers\\)\\|e\\(genbauerC\\|nera\\(l\\|te\\(Conditions\\|dCell\\)\\)\\|t\\)\\|laisher\\|o\\(ldenRatio\\|to\\)\\|r\\(a\\(phics\\(3D\\|Array\\|Spacing\\)?\\|yLevel\\)\\|eater\\(Equal\\)?\\|id\\(B\\(aseline\\|ox\\)\\|DefaultElement\\|Lines\\)\\|o\\(ebnerBasis\\|upPageBreakWithin\\)\\)\\)\\|H\\(TMLSave\\|armonicNumber\\|e\\(ads?\\|rmiteH\\)\\|iddenSurface\\|old\\(All\\(Complete\\)?\\|Complete\\|F\\(irst\\|orm\\)\\|Pattern\\|Rest\\)?\\|ue\\|yp\\(ergeometric\\(0F1\\(Regularized\\)?\\|1F1\\(Regularized\\)?\\|2F1\\(Regularized\\)?\\|PFQ\\(Regularized\\)?\\|U\\)\\|henation\\)\\)\\|I\\(dentity\\(Matrix\\)?\\|gnoreCase\\|m\\(age\\(Margins\\|R\\(esolution\\|otated\\)\\|Size\\)\\|p\\(lies\\|ort\\(String\\)?\\)\\)\\|n\\(String\\|crement\\|determinate\\|f\\(i\\(nity\\|x\\)\\|ormation\\)\\|itializationCell\\|ner\\|put\\(A\\(liases\\|utoReplacements\\)\\|Form\\|Notebook\\|Str\\(eam\\|ing\\)\\)?\\|s\\(ert\\|tall\\)\\|te\\(g\\(er\\(Digits\\|Exponent\\|Part\\|[Qs]\\)?\\|rate\\)\\|r\\(p\\(olati\\(ng\\(Function\\|Polynomial\\)\\|on\\)\\|retationBox\\)\\|rupt\\|section\\|val\\(Intersection\\|MemberQ\\|Union\\)?\\)\\)\\|verse\\(BetaRegularized\\|E\\(llipticNomeQ\\|rfc?\\)\\|F\\(ourier\\(CosTransform\\|SinTransform\\|Transform\\)?\\|unctions?\\)\\|GammaRegularized\\|LaplaceTransform\\|Series\\|WeierstrassP\\|ZTransform\\)?\\)\\|[fmn]\\)\\|J\\(acobi\\(Amplitude\\|P\\|Symbol\\|Zeta\\)\\|o\\(in\\|rdanDecomposition\\)\\)\\|K\\(hinchin\\|leinInvariantJ\\|roneckerDelta\\)\\|L\\(CM\\|U\\(BackSubstitution\\|Decomposition\\)\\|a\\(bel\\|guerreL\\|nguageCategory\\|placeTransform\\|st\\|tticeReduce\\)\\|e\\(afCount\\|gendre[PQ]\\|ngth\\|rchPhi\\|ss\\(Equal\\)?\\|tterQ\\|vel\\)\\|i\\(ght\\(Sources\\|ing\\)\\|mit\\(sPositioning\\)?\\|n\\(e\\(Indent\\(MaxFraction\\)?\\|Spacing\\|ar\\(Programming\\|Solve\\)\\)?\\|k\\(C\\(lose\\|onnect\\|reate\\)\\|Interrupt\\|Launch\\|Object\\|P\\(atterns\\|rotocol\\)\\|Read\\(yQ\\)?\\|Write\\|s\\)\\)\\|st\\(Co\\(n\\(tourPlot\\|volve\\)\\|rrelate\\)\\|DensityPlot\\|Interpolation\\|Pl\\(ay\\|ot\\(3D\\)?\\)\\|able\\)?\\)\\|o\\(cked\\|g\\(Gamma\\|Integral\\|icalExpand\\)?\\|werCaseQ\\)\\)\\|M\\(a\\(chineNumberQ\\|gnification\\|ke\\(Boxes\\|Expression\\)\\|ntissaExponent\\|p\\(A\\(ll\\|t\\)\\|Indexed\\|Thread\\)\\|t\\(ch\\(LocalNames\\|Q\\)\\|hieu\\(C\\(Prime\\|haracteristic\\(Exponent\\|[AB]\\)\\)\\|SPrime\\|[CS]\\)\\|rix\\(Exp\\|Form\\|Power\\|Q\\)\\)\\|x\\(Bend\\|MemoryUsed\\)\\|[px]\\)\\|e\\(ijerG\\|m\\(berQ\\|ory\\(Constrained\\|InUse\\)\\)\\|s\\(h\\(Range\\|Style\\)?\\|sage\\(List\\|Name\\|s\\)?\\)\\)\\|in\\(ors\\|us\\)?\\|o\\(d\\(ul\\(arLambda\\|e\\|us\\)\\)?\\|ebiusMu\\)\\|ulti\\(nomial\\|plicativeOrder\\)\\)\\|N\\(DSolve\\|Hold\\(All\\|First\\|Rest\\)\\|Integrate\\|Product\\|S\\(olve\\|um\\)\\|ame[Qs]\\|e\\(eds\\|gative\\|st\\(List\\|While\\(List\\)?\\)?\\)\\|o\\(n\\(Co\\(mmutativeMultiply\\|nstants\\)\\|Negative\\|Positive\\|e\\)\\|rmal\\|t\\(ebook\\(A\\(pply\\|utoSave\\)\\|C\\(lose\\|reate\\)\\|Delete\\|Find\\|Get\\|Locate\\|O\\(bject\\|pen\\)\\|P\\(rint\\|ut\\)\\|Read\\|S\\(ave\\|election\\)\\|Write\\|s\\)?\\)?\\)\\|u\\(ll\\(Records\\|Space\\|Words\\)?\\|m\\(ber\\(Form\\(at\\)?\\|M\\(arks\\|ultiplier\\)\\|P\\(adding\\|oint\\)\\|Q\\|S\\(eparator\\|igns\\)\\)?\\|er\\(ator\\|ic\\(Function\\|Q\\)\\)\\)\\)\\)\\|O\\(ddQ\\|ff\\(set\\)?\\|neIdentity\\|p\\(e\\(n\\(Append\\|Read\\|Temporary\\|Write\\)\\|rate\\)\\|tion\\(al\\|s\\)\\)\\|rder\\(edQ\\|less\\)?\\|ut\\(er\\|put\\(Form\\|Stream\\)\\)?\\|verscriptBox\\|[nr]\\)\\|P\\(a\\(d\\(Left\\|Right\\|dedForm\\)\\|ge\\(Break\\(Above\\|Below\\|Within\\)\\|Width\\)\\|r\\(a\\(graph\\(Indent\\|Spacing\\)\\|metricPlot\\(3D\\)?\\)\\|entDirectory\\|t\\(ition\\(s[PQ]\\)?\\)?\\)\\|t\\(h\\|tern\\(Test\\)?\\)\\|use\\)\\|ermutations\\|i\\|l\\(ay\\(Range\\)?\\|ot\\(3D\\|Division\\|Joined\\|Label\\|Points\\|R\\(ange\\|egion\\)\\|Style\\)?\\|us\\)\\|o\\(chhammer\\|int\\(Size\\)?\\|ly\\(Gamma\\|Log\\|gon\\(Intersections\\)?\\|nomial\\(GCD\\|LCM\\|Mod\\|Q\\(uotient\\)?\\|Re\\(duce\\|mainder\\)\\)\\)\\|s\\(iti\\(on\\|ve\\)\\|t\\(Script\\|fix\\)\\)\\|wer\\(Expand\\|Mod\\)?\\)\\|r\\(e\\(Decrement\\|Increment\\|c\\(edenceForm\\|ision\\(Goal\\)?\\)\\|fix\\|pend\\(To\\)?\\)\\|i\\(me\\(Pi\\|[Qs]\\)?\\|n\\(cipalValue\\|t\\(ingStyleEnvironment\\)?\\)\\)\\|o\\(duct\\(Log\\)?\\|log\\|tect\\(ed\\)?\\)\\)\\|seudoInverse\\|ut\\(Append\\)?\\)\\|Q\\(RDecomposition\\|u\\(it\\|otient\\)\\)\\|R\\(GBColor\\|a\\(dicalBox\\|n\\(dom\\|ge\\)\\|ster\\(Array\\)?\\|tional\\(ize\\|s\\)?\\|w\\)\\|e\\(a\\(d\\(List\\|Protected\\)\\|l\\(Digits\\|s\\)\\|[dl]\\)\\|c\\(ord\\(Lists\\|Separators\\)?\\|tangle\\)\\|duce\\|leaseHold\\|move\\|n\\(ame\\(Directory\\|File\\)\\|derAll\\)\\|p\\(eated\\(Null\\)?\\|lace\\(All\\|List\\|Part\\|Repeated\\)?\\)\\|s\\(etDirectory\\|idue\\|t\\|ultant\\)\\|turn\\|verse\\)?\\|iemannSiegel\\(Theta\\|Z\\)\\|o\\(ot\\(Reduce\\|Sum\\|s\\)?\\|tate\\(L\\(abel\\|eft\\)\\|Right\\)\\|und\\|w\\(Alignments\\|Box\\|Lines\\|MinHeight\\|Reduce\\|Spacings\\|sEqual\\)\\)\\|u\\(le\\(Delayed\\)?\\|n\\(Through\\)?\\)\\)\\|S\\(a\\(m\\(eQ\\|ple\\(Depth\\|Rate\\|dSound\\(Function\\|List\\)\\)\\)\\|ve\\)\\|c\\(a\\(led\\|n\\)\\|hurDecomposition\\|ientificForm\\|r\\(eenStyleEnvironment\\|ipt\\(BaselineShifts\\|MinSize\\|SizeMultipliers\\)\\)\\)\\|e\\(ch\\|edRandom\\|lect\\(able\\|edNotebook\\|ion\\(Animate\\|CreateCell\\|Evaluate\\(CreateCell\\)?\\|Move\\)\\)?\\|quence\\(Form\\|Hold\\)?\\|ries\\(Coefficient\\|Data\\)?\\|ssionTime\\|t\\(A\\(ccuracy\\|ttributes\\)\\|D\\(elayed\\|irectory\\)\\|FileDate\\|Options\\|Precision\\|S\\(electedNotebook\\|treamPosition\\)\\)\\|[ct]\\)\\|h\\(a\\(ding\\|llow\\|re\\)\\|o\\(rt\\|w\\(AutoStyles\\|C\\(ell\\(Bracket\\|Label\\|Tags\\)\\|ursorTracker\\)\\|PageBreaks\\|S\\(election\\|pecialCharacters\\|tringCharacters\\)\\)?\\)\\)\\|i\\(gn\\(Padding\\|ature\\)?\\|mplify\\|n\\(Integral\\|g\\(leLetterItalics\\|ularValues\\)\\|h\\(Integral\\)?\\)?\\|xJSymbol\\)\\|k\\(eleton\\|ip\\)\\|lot\\(Sequence\\)?\\|o\\(lve\\(Always\\)?\\|rt\\|und\\)\\|p\\(ellingCorrection\\|herical\\(HarmonicY\\|Region\\)\\|li\\(ce\\|t\\)\\)\\|qrt\\(Box\\)?\\|t\\(a\\(ck\\(Begin\\|Complete\\|Inhibit\\)?\\|ndardForm\\)\\|i\\(eltjesGamma\\|rlingS[12]\\)\\|r\\(eam\\(Position\\|s\\)\\|ing\\(Drop\\|Form\\|Insert\\|Join\\|Length\\|MatchQ\\|Position\\|Re\\(place\\(Part\\)?\\|verse\\)\\|Skeleton\\|T\\(ake\\|oStream\\)\\)?\\|u\\(cturedSelection\\|ve[HL]\\)\\)\\|ub\\|yle\\(Box\\|Definitions\\|Form\\|Print\\)\\)\\|u\\(b\\(resultants\\|s\\(criptBox\\|uperscriptBox\\)\\|tract\\(From\\)?\\)\\|m\\|perscriptBox\\|rface\\(Color\\|Graphics\\)\\)\\|witch\\|y\\(mbol\\(Name\\)?\\|ntax\\(Length\\|Q\\)\\)\\)\\|T\\(a\\(ble\\(Alignments\\|D\\(epth\\|irections\\)\\|Form\\|Headings\\|Spacing\\)?\\|g\\(Box\\|Set\\(Delayed\\)?\\|Unset\\)\\|ke\\|nh?\\)\\|e\\(X\\(Form\\|Save\\)\\|mporary\\|nsorRank\\|xt\\(Alignment\\|Justification\\|Style\\)?\\)\\|h\\(ickness\\|r\\(e\\(ad\\|eJSymbol\\)\\|o\\(ugh\\|w\\)\\)\\)\\|i\\(cks\\|m\\(e\\(Constrain\\(ed\\|t\\)\\|Used\\|Zone\\|s\\(By\\)?\\)\\|ing\\)\\)\\|o\\(Boxes\\|CharacterCode\\|Date\\|Expression\\|FileName\\|LowerCase\\|R\\(adicals\\|ules\\)\\|String\\|UpperCase\\|gether\\|kenWords\\|talWidth\\)\\|r\\(a\\(ce\\(Above\\|Backward\\|D\\(epth\\|ialog\\)\\|Forward\\|O\\(ff\\|n\\|riginal\\)\\|Print\\|Scan\\)?\\|ditionalForm\\|ns\\(formationFunctions\\|pose\\)\\)\\|eeForm\\|ig\\(Expand\\|Factor\\(List\\)?\\|Reduce\\|ToExp\\)\\|ueQ?\\)?\\)\\|U\\(n\\(der\\(overscriptBox\\|scriptBox\\)\\|e\\(qual\\|valuated\\)\\|i\\(nstall\\|on\\|que\\|tStep\\)\\|protect\\|s\\(ameQ\\|et\\)\\)\\|p\\(Set\\(Delayed\\)?\\|Values\\|date\\|perCaseQ\\)\\)\\|V\\(a\\(lueQ\\|riables\\)\\|e\\(ctorQ\\|rbatim\\)\\|i\\(ew\\(Center\\|Point\\|Vertical\\)\\|sible\\)\\)\\|W\\(eierstrass\\(HalfPeriods\\|Invariants\\|P\\(Prime\\)?\\|Sigma\\|Zeta\\)\\|hi\\(ch\\|le\\)\\|i\\(ndow\\(ClickSelect\\|Elements\\|F\\(loating\\|rame\\)\\|M\\(argins\\|ovable\\)\\|Size\\|T\\(itle\\|oolbars\\)\\)\\|th\\)\\|or\\(d\\(Se\\(arch\\|parators\\)\\)?\\|kingPrecision\\)\\|rite\\(String\\)?\\)\\|Xor\\|Z\\(Transform\\|eta\\)\\|[CDEINO]\\)\\>" 1 font-lock-keyword-face)
277
278 ;   '("\\<\\(Abort\\|B\\(egin\\(\\|Package\\)\\|lock\\|reak\\)\\|C\\(atch\\|heck\\|ontinue\\)\\|Do\\|End\\(\\|Package\\)\\|For\\|Goto\\|If\\|Label\\|M\\(essage\\|odule\\)\\|Print\\|Return\\|Switch\\|Throw\\|W\\(hi\\(ch\\|le\\)\\|ith\\)\\)\\>" 1 font-lock-keyword-face)
279    ;; a missing `;' in Mathematica code may cause magic effects. So
280    ;; highlight it:
281 ;   '("\\(;\\)" 1 font-lock-keyword-face))
282 ;  "Subdued level highlighting for mathematica-m mode.")
283
284 (defvar mathematica-m-font-lock-keywords-1
285   (list
286    '("\\(^[a-zA-Z]\\w*\\)\\([ \t]*=[ \t]*Compile\\|\\[\\([ \t]*\\]\\|.*\\(_\\|:\\)\\)\\)"
287      1 font-lock-function-name-face)
288 ;; and no keywords.
289    ))
290
291 (defvar mathematica-m-font-lock-keywords-2
292   (append
293    mathematica-m-font-lock-keywords-1
294    '(
295      ("\\(\\(-\\|:\\)>\\|//[.@]?\\|/[.@;:]\\|@@\\|#\\(#\\|[0-9]*\\)\\|&\\)" 1 font-lock-keyword-face append)
296      ("([*]:[a-zA-Z-]*:[*])" 0 font-lock-keyword-face t)
297 ;;; This pattern is just for internal use...
298 ;;;     ("([*]\\(:FILE-ID:\\).*:[*])" 1 font-lock-keyword-face t)
299      ("\\(!=\\|=\\(!=\\|==?\\)\\)" 1 font-lock-reference-face)))
300    "Gaudy level highlighting for mathematica-m mode.")
301
302 (defvar mathematica-m-font-lock-keywords mathematica-m-font-lock-keywords-1
303   "Default expressions to highlight in mathematica-m mode.")
304
305
306
307 ;;;; - mathematica-m-mode
308 (defun mathematica-m-mode ()
309   "Mathematica-Mode.
310 Programming mode for writing Mathematica package files.
311 Turning on mathematica-m-mode runs the hook `mathematica-m-mode-hook'.
312 \\{mathematica-m-mode-map}"
313   (interactive)
314   ; kill all (non-permanent) buffer-local variables.
315   (kill-all-local-variables)
316   (use-local-map mathematica-m-mode-map)
317   (setq mode-name "mathematica-m")
318   (setq major-mode 'mathematica-m-mode)
319
320   (set-syntax-table mathematica-m-mode-syntax-table)
321
322   ; don't split the frame unless it is already split.
323   ; use C-x 2 or C-x 3 to split the frame.
324   (set (make-local-variable 'pop-up-windows) nil)
325
326   ; i don't understand the following six lines
327   (set (make-local-variable 'paragraph-start) (concat "$\\|" page-delimiter))
328   (set (make-local-variable 'paragraph-separate) paragraph-start)
329   (set (make-local-variable 'comment-start) "(* ")
330   (set (make-local-variable 'comment-end) " *)")
331   (set (make-local-variable 'comment-start-skip) "(\\*+ *")
332   (set (make-local-variable 'comment-column) 48)
333
334   (setq indent-tabs-mode nil) ; use space, not tab.
335   (setq tab-width 2)
336
337
338   ;; how to indent:
339   (make-local-variable 'indent-line-function)
340   (setq indent-line-function 'indent-relative-maybe)
341
342 ;  (make-local-variable 'indent-region-function)
343 ;  (setq indent-region-function 'mathematica-indent-region)
344
345   ;; dabbrev configuration:
346   ;; case matters in mathematica. tell dabbrev about this.
347   (set (make-local-variable 'dabbrev-case-fold-search) nil)
348   (set (make-local-variable 'dabbrev-case-replace)     nil)
349   ;; look in other mathematica-m-mode buffers for completions, too.
350   (set (make-local-variable 'dabbrev-friend-buffer-function)
351       (lambda (buffer)
352          (save-excursion
353            (set-buffer buffer)
354            (memq major-mode '(mathematica-m-mode)))))
355
356
357   ;; parse-sexp-ignore-comments should be set to nil. Otherwise matching
358   ;; paren highlighting does not work properly.
359   (set (make-local-variable 'parse-sexp-ignore-comments) nil)
360 ;  (set (make-local-variable 'indent-line-function) 'mathematica-m-indent-line)
361
362   (make-local-variable 'font-lock-defaults)
363   (setq font-lock-defaults
364         '((mathematica-m-font-lock-keywords
365            mathematica-m-font-lock-keywords-1
366            mathematica-m-font-lock-keywords-2)
367           nil nil ((?_ . "w")) beginning-of-defun
368           (font-lock-comment-start-regexp . "^([*]\\|[ \t]([*]")))
369
370   ;; if on Emacs, initialize imenu index creation function
371   (run-hooks 'mathematica-m-mode-hook)
372   ;(message "(run-hooks 'mathematica-m-mode-hook)")
373
374   (show-paren-mode 1)           ; show matching parentheses in color.
375   ; it seems, that it doesn't work for me: I have to call it interactively.
376   (setq debug-flag 1)
377 )
378
379 ; add 'mathematica to the global variable features.
380 (provide 'mathematica)
381
382
383
384
385
386 ;; Purpose:
387 ;;
388 ;; To send a buffer to another buffer running Mathematica.
389 ;;
390 ;; Installation:
391 ;;
392 ;; add this to .emacs:
393 ;;
394 ;;    (add-hook mathematica-comint-mode-hook 'turn-on-mathematica)
395 ;;
396 ;; Customisation:
397 ;;       The name of the mathematica interpreter is in variable
398 ;;          mathematica-comint-program-name
399 ;;       Arguments can be sent to the Mathematica interpreter when it is called
400 ;;       by setting the value of the variable
401 ;;          mathematica-comint-program-args
402 ;;
403 ;;       If the command does not seem to respond, see the
404 ;;          content of the `comint-prompt-regexp' variable
405 ;;          to check that it waits for the appropriate Mathematica prompt
406 ;;          the current value is appropriate for Mathematica 1.0 - 4.2
407 ;;
408 ;;    `mathematica-comint-hook' is invoked in the *mathematica* once it is started.
409 ;;
410 ;;; All functions/variables start with
411 ;;; `(turn-(on/off)-)mathematica' or `mathematica-comint-'.
412
413 (defgroup mathematica nil
414   "Major mode for interacting with an inferior Mathematica session."
415   :group 'mathematica
416   :prefix "mathematica-comint-")
417
418
419 ; makes the current buffer a mathematica mode buffer.
420 ; do i lose any comint defaults by this?
421 (defun mathematica-comint-mode ()
422   "Major mode for interacting with an inferior Mathematica session.
423
424
425 \\<mathematica-comint-mode-map>
426 Commands:
427 Return at end of buffer sends line as input.
428 Return not at end copies rest of line to end and sends it.
429 \\[mathematica-comint-find-error] jumps to the error line in the corresponding *.m file,
430 \\[switch-to-mathematica-m] switches to  the corresponding *.m file,
431 \\[dabbrev-expand] expands a word,
432 \\[comint-interrupt-subjob] interrups Mathematica,
433 \\[comint-quit-subjob] sends Mathematica the QUIT signal,
434 \\[comint-kill-input] and \\[backward-kill-word] are kill commands,
435 imitating normal Unix input editing.
436 \\[comint-interrupt-subjob] interrupts the comint or its current
437 subjob if any.
438 \\[comint-stop-subjob] stops, likewise.
439  \\[comint-quit-subjob] sends quit signal."
440   (interactive)
441   (comint-mode)
442   (setq major-mode 'mathematica-comint-mode)
443   (setq mode-name "Mathematica")
444
445 ;;   (if mathematica-comint-mode-map
446 ;;       nil
447 ;;     (setq mathematica-comint-mode-map (copy-keymap comint-mode-map))
448 ;;     )
449   (setq mathematica-comint-mode-map (copy-keymap comint-mode-map))
450   (define-key mathematica-comint-mode-map [f2] 'mathematica-comint-find-error)
451   (define-key mathematica-comint-mode-map [C-tab] 'switch-to-mathematica-m)
452   (define-key mathematica-comint-mode-map [pause] 'comint-interrupt-subjob)
453   (define-key mathematica-comint-mode-map [C-pause] 'comint-quit-subjob)
454   (define-key mathematica-comint-mode-map [tab] 'dabbrev-expand)
455   (define-key mathematica-comint-mode-map [C-up] 'comint-previous-matching-input-from-input)
456   (use-local-map mathematica-comint-mode-map)
457
458   ; don't split the frame unless it is already split.
459   ; use C-x 2 or C-x 3 to split the frame.
460   (set (make-local-variable 'pop-up-windows) nil)
461
462   ;; case matters in mathematica. tell dabbrev about this.
463   (set (make-local-variable 'dabbrev-case-fold-search) nil)
464   (set (make-local-variable 'dabbrev-case-replace)     nil)
465   ;; look in the associated mathematica-m-mode buffer for completions, too.
466   (set (make-local-variable 'dabbrev-friend-buffer-function)
467       (lambda (buffer) (eq buffer mathematica-comint-last-buffer)))
468
469   ; experimental: reuse mathematica-m-mode syntax highlighting here.
470   (set-syntax-table mathematica-m-mode-syntax-table)
471   (set (make-local-variable 'paragraph-start) (concat "$\\|" page-delimiter))
472   (set (make-local-variable 'paragraph-separate) paragraph-start)
473   (set (make-local-variable 'comment-start) "(* ")
474   (set (make-local-variable 'comment-end) " *)")
475   (set (make-local-variable 'comment-start-skip) "(\\*+ *")
476   (set (make-local-variable 'comment-column) 48)
477   (make-local-variable 'font-lock-defaults)
478   (setq font-lock-defaults
479         '((mathematica-m-font-lock-keywords
480            mathematica-m-font-lock-keywords-1
481            mathematica-m-font-lock-keywords-2)
482           nil nil ((?_ . "w")) beginning-of-defun
483           (font-lock-comment-start-regexp . "^([*]\\|[ \t]([*]")))
484   ; /experimental: reuse mathematica-m-mode syntax highlighting here.
485
486
487   )
488
489 ;; Mathematica-interface
490
491 (require 'comint)
492 ; not needed?:
493 ;(require 'shell)
494
495 ; I doubt: "...corresponding to current buffer.";
496 ;    it seems to have the same value in any buffer.
497 ;
498 (defvar mathematica-comint-process nil
499   "The active Mathematica subprocess corresponding to current buffer.")
500
501 (defvar mathematica-comint-process-buffer nil
502   "*Buffer used for communication with Mathematica subprocess for current buffer.")
503
504 ; not needed?
505 (defvar mathematica-comint-last-loaded-file nil
506   "The last file loaded into the Mathematica process.")
507
508 ; !!! has to be configured by the user !!!
509 (defcustom mathematica-comint-program-name "math"
510   "*The name of the command to start the Mathematica interpreter."
511   :type 'string
512   :group 'mathematica)
513
514 (defcustom mathematica-comint-program-args '("")
515   "*A list of string args to send to the mathematica process."
516   :type '(repeat string)
517   :group 'mathematica)
518
519 ;(defvar mathematica-comint-load-end nil
520 ;  "Position of the end of the last load command.")
521
522 ;(defvar mathematica-comint-send-end nil
523 ;  "Position of the end of the last send command.")
524
525 (defun mathematica-comint-load ()
526   ""
527   (interactive)
528
529   ; save the current buffer.
530   ; load its contents into mathematica.
531   (save-excursion (mathematica-comint-execute-get))
532
533   ; (set-buffer mathematica-comint-process-buffer) + making it visible:
534   (pop-to-buffer mathematica-comint-process-buffer)
535
536   ; (mathematica-comint-wait-for-output)
537 )
538
539 ; bad: moves the point.
540 (defun mathematica-comint-wait-for-output ()
541   "Wait until output arrives and go to the last input."
542   (while (progn 
543            (sleep-for 0 200) ; 200 milliseconds
544            (message "waiting for the prompt.")          
545            (goto-char comint-last-input-end)
546            (not (re-search-forward comint-prompt-regexp nil t)))
547     (accept-process-output mathematica-comint-process)))
548
549 ;(defun comint-kill-subjob ()
550
551 ; may be called when mathematica is already running.
552 ; may be called even several times in a row; this does not matter.
553 (defun mathematica-comint-start-process ()
554   "Start a Mathematica process and invokes `mathematica-comint-hook' if not nil.
555 Prompts for a list of args if called with an argument."
556   (interactive "P")
557   (message "Starting `mathematica-comint-process' %s" mathematica-comint-program-name)
558   (setq mathematica-comint-process-buffer
559   ; "mathematica" means: buffername becomes *mathematica*
560     (make-comint "mathematica" mathematica-comint-program-name))
561   (setq mathematica-comint-process
562         (get-buffer-process mathematica-comint-process-buffer))
563   ;; Select Mathematica buffer temporarily
564   ; was:(set-buffer mathematica-comint-process-buffer)
565   ; is:
566   ; (set-buffer mathematica-comint-process-buffer) + making it visible:
567   ; This function makes buffer-or-name the current buffer and switches to it in some window,
568   ; preferably not the window previously selected. The "popped-to" window becomes the selected
569   ; window within its frame.
570   (pop-to-buffer mathematica-comint-process-buffer)
571   ; reason: to make (window-width), for Mathematicas PageWidth option, work.
572
573   ;; Set the keymap (and the modename):
574   (mathematica-comint-mode)
575 ;  (setq comint-prompt-regexp  "^\? \\|^[A-Z][_a-zA-Z0-9]*> ")
576   (setq comint-prompt-regexp  "^In\[[0-9]+\]:= ")
577     ;; comint's history syntax conflicts with Mathematica syntax, eg. !!
578 ;  (setq comint-input-autoexpand nil)
579   (run-hooks 'mathematica-comint-hook)
580   (message "mathematica-comint-start-process terminated.")
581 ;  (message "")
582   )
583
584 ; (save-excursion (mathematica-comint-execute-get))
585 ; Get[...]; main[];
586 (defun mathematica-comint-execute-get ();(load-command cd)
587   "Save the current buffer and load its file into the Mathematica process."
588   (let (file)
589     ;?
590     ;(hack-local-variables);; In case they've changed
591     (save-buffer)
592     (setq file (buffer-file-name))
593
594     ; remember this in order to jump back to it, eg after an error.
595     ; (we cannot read off the filename from the error message, due to //Short in the message)
596     (setq mathematica-comint-last-file (buffer-file-name))
597     (setq mathematica-comint-last-buffer (current-buffer))
598
599     ; make sure the process is there.
600     ; why not simply call mathematica-comint-start-process in any case?
601     (mathematica-comint-start-process)
602
603 ;;     (if (and mathematica-comint-process-buffer
604 ;;              (eq (process-status mathematica-comint-process) 'run))
605 ;;        ;; Ensure the Mathematica buffer is selected.
606 ;;      (set-buffer mathematica-comint-process-buffer)
607 ;;         ;; Start Mathematica process.
608 ;;         (mathematica-comint-start-process))
609
610     ;; why?:
611     ;; Wait until output arrives and go to the last input.
612 ;    (mathematica-comint-wait-for-output)
613
614 ; Here's a workaround for the problem with // Short:
615 ;SetOptions[$Output, PageWidth-> Infinity];Block[{Short=Identity},Get["c:/Documents and Settings/burki/My Documents/systems/Mathematica/BurkisMathematicaToolsAdditions_Backup1.m"]];SetOptions[$Output, PageWidth-> 78];
616
617     (mathematica-comint-send
618      (format "SetOptions[$Output, PageWidth-> Infinity]; Block[{Short=Identity},Get[\"%s\"]]; SetOptions[$Output, PageWidth-> %d];" (mathematica-comint-quote-filename file) (- (window-width) 1)))
619 ; the necessity for -1 was found by experimentation.
620 ; trouble: it takes the window-width of the *.m buffer, not of the *mathematica* comint buffer.
621
622 ;; if the user wants to execute main[] indeed, then he can add such a call to his source file.
623 ;    (mathematica-comint-send "main[];")
624
625
626     ;; Wait until output arrives and go to the last input.
627 ;    (mathematica-comint-wait-for-output)
628   )
629 )
630
631
632 (defun mathematica-comint-send (&rest string)
633   "Send `mathematica-comint-process' the arguments (one or more strings).
634 A newline is sent after the strings and they are inserted into the
635 current buffer after the last output."
636 ;  (mathematica-comint-wait-for-output)
637   (accept-process-output mathematica-comint-process 0 100)
638   (goto-char (point-max))               
639   (apply 'insert string)
640   (comint-send-input)
641   (goto-char (point-max))
642 )
643
644
645
646 ; (marker-insertion-type comint-last-input-end)
647 ; to do, not implemented yet.
648 ; to do: find the name of elisp's string-quoting function.
649 (defun mathematica-comint-quote-filename (filename)
650   "quote special characters in filenames."
651   filename)
652
653 ;(mathematica-comint-quote-filename "")
654 ;(mathematica-comint-quote-filename "My Documents\\mathematica.hs")
655
656
657 ; (mathematica-comint-show-errors)
658 (defun mathematica-comint-find-error ()
659   "If there is an error, set the cursor at the
660 error line, otherwise show the Mathematica buffer."
661   (interactive)
662   (set-buffer mathematica-comint-process-buffer)
663   (goto-char comint-last-input-start)
664   (if (re-search-forward
665        ; eg: Syntax::sntx: Syntax error in or before "SetAttributes[BatchResult, HoldAllComplete[; ".
666        ; eg: (line 1 of "c:/examples/test.m")
667        "^\\(.*\\)(line \\([0-9]+\\) of \"\\(.*\\)\")" nil t)
668       (let ( ; Unfortunately, Mathematica applies //Short to the filename.
669              ; so efile is often nonsense like
670              ; "c:/Documents and Settin<<42>>rki/mathematica.el"
671             (efile (buffer-substring (match-beginning 3)
672                                      (match-end 3)))
673             (eline (string-to-int (buffer-substring (match-beginning 2)
674                                      (match-end 2))))
675             (emesg (buffer-substring (match-beginning 1)
676                                      (match-end 1)))
677            )
678
679         ; is this a kind of clean-up?
680         ;(pop-to-buffer  mathematica-comint-process-buffer)
681         (goto-char (point-max))
682         ;(recenter)
683
684         (message "%s, line %d: %s" (file-name-nondirectory efile) eline emesg)
685         ;(message "%s" emesg)
686
687         ; jump to the error.
688
689         ; this is a reasonable guess, but not necessary the right file:
690         (set-buffer mathematica-comint-last-buffer)
691         (pop-to-buffer mathematica-comint-last-buffer)
692         (goto-line eline)
693
694         ; maybe that would be better in case of several files.
695         ; difficulty: to resolve efile in the same way as Matheamtica does.
696         ; we should call Mathematica for doing the resolving.
697 ;         (if (file-exists-p efile)
698 ;             (progn (find-file-other-window efile)
699 ;                    (if eline (goto-line eline))
700 ;                    (recenter)))
701
702
703         ) ; let
704
705 ; else
706     (progn
707      ;(pop-to-buffer  mathematica-comint-process-buffer) ; show *mathematica* buffer
708      (goto-char (point-max))
709 ;     (message "There were no errors.")
710      ; even if there were no errors, we switch back to the source code.
711      (pop-to-buffer mathematica-comint-last-buffer)
712      ;(recenter 2)                        ; show only the end...
713     )
714 ))
715
716 ;; ; (mathematica-comint-show-mathematica-buffer)
717 ;; (defun mathematica-comint-show-mathematica-buffer ()
718 ;;   "Goes to the Mathematica buffer."
719 ;;   (interactive)
720 ;;   (if (or (not mathematica-comint-process-buffer)
721 ;;           (not (buffer-live-p mathematica-comint-process-buffer)))
722 ;;       (mathematica-comint-start-process))
723 ;;   (pop-to-buffer  mathematica-comint-process-buffer)
724 ;;   )