source: git/emacs/singular.el @ ff3a4f

spielwiese
Last change on this file since ff3a4f was 61100b, checked in by Hans Schoenemann <hannes@…>, 14 years ago
tr 258 git-svn-id: file:///usr/local/Singular/svn/trunk@13177 2c84dea3-7e68-4137-9b89-c4e89433aadc
  • Property mode set to 100644
File size: 171.2 KB
Line 
1;;; singular.el --- Emacs support for Computer Algebra System Singular
2
3;; $Id$
4
5;;; Commentary:
6
7
8;;; Code:
9
10;;{{{ Style and coding conventions
11
12;; Style and coding conventions:
13;;
14;; - "Singular" is written with an upper-case `S' in comments, doc
15;;   strings, and messages.  As part of symbols, it is written with
16;;   a lower-case `s'.
17;; - When referring to the Singular interactive mode, do it in that
18;;   wording.  Use the notation `singular-interactive-mode' only when
19;;   really referring to the lisp object.
20;; - use a `fill-column' of 75 for doc strings and comments
21;; - mark incomplete doc strings or code with `NOT READY' optionally
22;;   followed by an explanation what exactly is missing
23;;
24;; - use foldings to structure the source code but try not to exceed a
25;;   maximum depth of two foldings
26;; - use lowercase folding titles except for first word
27;; - folding-marks are `;;{{{' and `;;}}}' resp., for sake of standard
28;;   conformity
29;; - use the foldings to modularize code.  That is, each folding should be,
30;;   as far as possible, self-content.  Define a function `singular-*-init'
31;;   in the folding to do the initialization of the module contained in
32;;   that folding.  Call that function from `singular-interactive-mode',
33;;   for example, instead of initializing the module directly from
34;;   `singular-interactive-mode'.  Look at the code how it is done for the
35;;   simple section or for the folding stuff.
36;;
37;; - use `singular' as prefix for all global symbols
38;; - use `singular-debug' as prefix for all global symbols concerning
39;;   debugging.
40;; - use, whenever possible without names becoming too clumsy, some unique
41;;   prefix inside a folding
42;;
43;; - mark dependencies on Emacs flavor/version with a comment of the form
44;;   `;; Emacs[ <version> ]'     resp.
45;;   `;; XEmacs[ <version> ][ <nasty comment> ]'
46;;   specified in that order, if possible
47;; - use a `cond' statement to execute Emacs flavor/version-dependent code,
48;;   not `if'.  This is to make such checks more extensible.
49;; - try to define different functions for different flavors/version and
50;;   use `singular-fset' at library-loading time to set the function you
51;;   really need.  If the function is named `singular-<basename>', the
52;;   flavor/version-dependent functions should be named
53;;   `singular-<flavor>[-<version>]-<basename>'.
54;;
55;; - use `singular-debug' for debugging output/actions
56;; - to switch between buffer and process names, use the functions
57;;   `singular-process-name-to-buffer-name' and
58;;   `singular-buffer-name-to-process-name'
59;; - call the function `singular-keep-region-active' as last statement in
60;;   an interactive function that should keep the region active (for
61;;   example, in functions that move the point).  This is necessary to keep
62;;   XEmacs' zmacs regions active.
63;; - to get the process of the current buffer, use `singular-process'.  To
64;;   get the current process mark, use `singular-process-mark'.  Both
65;;   functions check whether Singular is alive and throw an error if not,
66;;   so you do not have to care about that yourself.  If you do not want an
67;;   error specify non-nil argument NO-ERROR.  But use them anyway.
68;; - we assume that the buffer is *not* read-only
69;; - use `=' instead of `eq' when comparing buffer locations.  Even if you
70;;   are sure that both operands are integers.
71
72;;}}}
73
74;;{{{ Code common to both modes
75;;{{{ Customizing
76(defgroup singular nil
77  "Emacs interface to Singular.
78By now, the Emacs interface to Singular consists of Singular interactive
79mode only.  Singular interactive mode provides a convenient front end to
80interactive Singular sessions running inside Emacs.
81In far future maybe there will be a mode for editing Singular source code
82such as libraries or procedures."
83  :group 'external)
84
85(defgroup singular-faces nil
86  "Faces in Singular mode and Singular interactive mode."
87  :group 'faces
88  :group 'singular-interactive)
89;;}}}
90
91;;{{{ Debugging stuff
92(defvar singular-debug nil
93  "List of modes to debug or t to debug all modes.
94Currently, the following modes are supported:
95  `interactive',
96  `interactive-filter'.")
97
98(defun singular-debug-format (string)
99  "Return STRING in a nicer format."
100  (save-match-data
101    (while (string-match "\n" string)
102      (setq string (replace-match "^J" nil nil string)))
103
104    (if (> (length string) 16)
105        (concat "<" (substring string 0 7) ">...<" (substring string -8) ">")
106      (concat "<" string ">"))))
107
108(defmacro singular-debug (mode form &optional else-form)
109  "Major debugging hook for singular.el.
110Evaluates FORM if `singular-debug' equals t or if MODE is an element
111of `singular-debug', othwerwise ELSE-FORM."
112  `(if (or (eq singular-debug t)
113           (memq ,mode singular-debug))
114       ,form
115     ,else-form))
116;;}}}
117
118;;{{{ Determining version
119(defvar singular-emacs-flavor nil
120  "A symbol describing the current Emacs.
121Currently, only Emacs \(`emacs') and XEmacs \(`xemacs') are supported.")
122
123(defvar singular-emacs-major-version nil
124  "An integer describing the major version of the current emacs.")
125
126(defvar singular-emacs-minor-version nil
127  "An integer describing the minor version of the current emacs.")
128
129(defun singular-fset (real-function emacs-function xemacs-function)
130  "Set REAL-FUNCTION to one of the functions, in dependency on Emacs flavor and version.
131Sets REAL-FUNCTION to XEMACS-FUNCTION if `singular-emacs-flavor' is
132`xemacs', otherwise sets REAL-FUNCTION to EMACS-FUNCTION.
133
134This is not as common as it would be desirable.  But it is sufficient so
135far."
136  (cond
137   ;; XEmacs
138   ((eq singular-emacs-flavor 'xemacs)
139    (fset real-function xemacs-function))
140   ;; Emacs
141   (t
142    (fset real-function emacs-function))))
143
144(defun singular-set-version ()
145  "Determine flavor, major version, and minor version of current emacs.
146singular.el is guaranteed to run on Emacs 20.3 and XEmacs 20.3.
147It should run on newer version and on slightly older ones, too.
148
149This function is called exactly once when singular.el is loaded."
150  ;; get major and minor versions first
151  (if (and (boundp 'emacs-major-version)
152           (boundp 'emacs-minor-version))
153      (setq singular-emacs-major-version emacs-major-version
154            singular-emacs-minor-version emacs-minor-version)
155    (with-output-to-temp-buffer "*singular warnings*"
156      (princ
157"You seem to have quite an old Emacs or XEmacs version.  Some of the
158features from singular.el will not work properly.  Consider upgrading to a
159more recent version of Emacs or XEmacs.  singular.el is guaranteed to run
160on Emacs 20.3 and XEmacs 20.3."))
161    ;; assume the oldest version we support
162    (setq singular-emacs-major-version 20
163          singular-emacs-minor-version 3))
164
165  ;; get flavor
166  (if (string-match "XEmacs\\|Lucid" emacs-version)
167      (setq singular-emacs-flavor 'xemacs)
168    (setq singular-emacs-flavor 'emacs)))
169
170(singular-set-version)
171;;}}}
172
173;;{{{ Syntax table
174(defvar singular-mode-syntax-table nil
175  "Syntax table for `singular-interactive-mode' resp. `singular-mode'.")
176
177(if singular-mode-syntax-table
178    ()
179  (setq singular-mode-syntax-table (make-syntax-table))
180  ;; stolen from cc-mode.el except for back-tics which are special to Singular
181  (modify-syntax-entry ?_  "_"          singular-mode-syntax-table)
182  (modify-syntax-entry ?\\ "\\"         singular-mode-syntax-table)
183  (modify-syntax-entry ?+  "."          singular-mode-syntax-table)
184  (modify-syntax-entry ?-  "."          singular-mode-syntax-table)
185  (modify-syntax-entry ?=  "."          singular-mode-syntax-table)
186  (modify-syntax-entry ?%  "."          singular-mode-syntax-table)
187  (modify-syntax-entry ?<  "."          singular-mode-syntax-table)
188  (modify-syntax-entry ?>  "."          singular-mode-syntax-table)
189  (modify-syntax-entry ?&  "."          singular-mode-syntax-table)
190  (modify-syntax-entry ?|  "."          singular-mode-syntax-table)
191  (modify-syntax-entry ?\' "\""         singular-mode-syntax-table)
192  (modify-syntax-entry ?\` "\""         singular-mode-syntax-table)
193  ;; block and line-oriented comments
194  (cond
195   ;; Emacs
196   ((eq singular-emacs-flavor 'emacs)
197    (modify-syntax-entry ?/  ". 124b"   singular-mode-syntax-table)
198    (modify-syntax-entry ?*  ". 23"     singular-mode-syntax-table))
199   ;; XEmacs
200   (t
201    (modify-syntax-entry ?/  ". 1456"   singular-mode-syntax-table)
202    (modify-syntax-entry ?*  ". 23"     singular-mode-syntax-table)))
203  (modify-syntax-entry ?\n "> b"        singular-mode-syntax-table)
204  (modify-syntax-entry ?\^m "> b"       singular-mode-syntax-table))
205
206(defun singular-mode-syntax-table-init ()
207  "Initialize syntax table of current buffer.
208
209This function is called at mode initialization time."
210  (set-syntax-table singular-mode-syntax-table))
211;;}}}
212
213;;{{{ Miscellaneous
214(defsubst singular-keep-region-active ()
215  "Do whatever is necessary to keep the region active in XEmacs.
216Ignore byte-compiler warnings you might see.  This is not needed for
217Emacs."
218  ;; XEmacs.  We do not use the standard way here to test for flavor
219  ;; because it is presumably faster with that test on `boundp'.
220  (and (boundp 'zmacs-region-stays)
221       (setq zmacs-region-stays t)))
222;;}}}
223;;}}}
224
225;;{{{ Singular interactive mode
226;;{{{ Customizing
227
228;; Note:
229;;
230;; Some notes on Customize:
231;;
232;; - The documentation states that for the `:initialize' option of
233;;   `defcustom' the default value is `custom-initialize-set'.  However, in
234;;   the source code of Customize `custom-initialize-reset' is used.  So
235;;   better always specify the `:initialize' option explicitly.
236;; - Customize is bad at setting buffer-local variables or properties.
237;;   This is quite natural since Customize itself uses its own buffer.  So
238;;   changing buffer-local variables and properties with Customize is
239;;   possible only at a "Singular-global" level.  That is, for all buffers
240;;   currently having Singular interactive mode as major mode.  The function
241;;   `singular-map-buffer' helps to do such customization.
242;; - Important note: Customizable variables are not automatically marked as
243;;   user options.  This has to be done as usual by marking them with a '*'
244;;   as first character of the documentation string.  Without that, the
245;;   variables are not accessible to, for example, `set-variable'.
246;;
247;; Some common customizing patterns:
248;;
249;; - How to customize buffer-local properties?
250;;   First, the `defcustom' itself must not set anything buffer-local since
251;;   at time of its definition (most likely) no Singular buffers will be
252;;   around.  If there are Singular buffers we do not care about them.  But
253;;   anyhow, at definition of the `defcustom' the global default has to be
254;;   set.  Hence, the `:initialize' option should be set to
255;;   `custom-initialize-default'.
256;;   The buffer-local initialization has to be done at mode initialization
257;;   time.  The global default value should then be used to set the local
258;;   properties.
259;;   At last, the function specified with the `:set' option should set the
260;;   local properties in all Singular buffers to the new, customized value.
261;;   Most likely, the function `singular-map-buffer' may be used for that.
262;;   In addition, the function should, of course, set the global value via
263;;   `set-default'.
264;;   For an example, see `singular-folding-line-move-ignore-folding'.
265;;
266;; - How to encapsulate other mode's global variables into Singular
267;;   interactive mode variables?
268;;   Set them always.  That is, set them if the `defcustom' is evaluated
269;;   (use `custom-initialize-reset' as `:initial' function) and set them
270;;   when the Singular interactive mode variable is customized (by means
271;;   of an appropriate `:set' function).
272;;   For an example, see `singular-section-face-alist' (which does not
273;;   encapsulate another mode's variable, but Singular interactive mode's
274;;   own variable `singular-simple-sec-clear-type').
275
276(defgroup singular-interactive nil
277  "Running interactive Singular sessions inside Emacs."
278  :group 'singular
279  :group 'processes)
280
281(defgroup singular-sections-and-foldings nil
282  "Sections and foldings in Singular interactive mode."
283  :group 'singular-interactive)
284
285(defgroup singular-interactive-miscellaneous nil
286  "Miscellaneous settings for Singular interactive mode."
287  :group 'singular-interactive)
288
289(defgroup singular-demo-mode nil
290  "Settings concerning Singular demo mode."
291  :group 'singular-interactive)
292
293(defun singular-map-buffer (func &rest args)
294  "Apply FUNC to ARGS in all existing Singular buffers.
295That is, in all buffers having Singular interactive major mode.  The
296function is executed in the context of the buffer.  This is a must-have for
297the customizing stuff to change buffer-local properties."
298  (save-excursion
299    (mapcar (function
300             (lambda (buffer)
301               (set-buffer buffer)
302               (if (eq major-mode 'singular-interactive-mode)
303                   (apply func args))))
304            (buffer-list))))
305;;}}}
306
307;;{{{ Comint
308
309;; Note:
310;;
311;; We require Comint, but we really do not use it too much.  One may argue
312;; that this is bad since Comint is a standardized way to communicate with
313;; external processes.  One may argue further that many experienced Emacs
314;; users are forced now to re-do their Comint customization for Singular
315;; interactive mode.  However, we believe that the intersection between
316;; experienced Emacs users and users of Singular interactive mode is almost
317;; empty.
318;;
319;; In fact, we used Comint really much in the beginning of this project.
320;; Later during development it turned at that using Comint's input and
321;; output processing is to inflexible and not appropriate for Singular
322;; interactive mode with its input and output sections.  So we begun to
323;; rewrite large portions of Comint to adapt it to our needs.  At some
324;; point it came clear that it would be best to throw out Comint
325;; alltogether, would not have been there some auxilliary functions which
326;; are really useful but annoying to rewrite.  These are, for example, the
327;; command line history functions or the completion stuff offered by
328;; Comint.
329;;
330;; Our policy with regard to these remainders of Comint is: Use the
331;; functions to bind them to keys, but do not use them internally.
332;; Encapsulate Comint customization into Singular interactive mode
333;; customization.  In particular, do not take care about Comint settings
334;; which already may be present, overwrite them.  Hide Comint from the
335;; user.
336;;
337;; Here is how exactly we use Comint:
338;;
339;; - All variables necessary to use Comint's input ring are properly
340;;   initialized.  One may find this in the `History' folding.
341;; - `comint-prompt-regexp' is initialized since it is used in some
342;;   of the functions regarding input ring handling.  Furthermore, its
343;;   initialization enables us to use functions as `comint-bol', etc.
344;;   Initialization is done in the `Skipping and stripping prompts ...'
345;;   folding.
346;; - We call `comint-mode' as first step in `singular-interactive-mode'.
347;;   Most of the work done there is to initialize the local variables as
348;;   necessary.  Besides that, the function does nothing that interferes
349;;   with Singular interactive mode.  To be consequent we set
350;;   `comint-mode-hook' temporarily to nil when calling `comint-mode'.
351;; - In `singular-exec', we use `comint-exec-1' to fire up the process.
352;;   Furthermore, we set `comint-ptyp' there as it is used in the signal
353;;   sending commands of Comint.  All that `comint-exec-1' does is that it
354;;   sets up the process environment (it adds or modifies the setting of
355;;   the 'TERM' variable), sets the execution directory, and does some
356;;   magic with the process coding stuff.
357;; - One more time the most important point: we do *not* use Comint's
358;;   output and input processing.  In particular, we do not run any of
359;;   Comint's hooks on input or output.  Anyway, we do better, don't we?
360
361(require 'comint)
362
363(defun singular-comint-init ()
364  "Initialize comint stuff for Singular interactive mode.
365
366This function is called at mode initialization time."
367  (setq comint-completion-addsuffix '("/" . "")))
368;;}}}
369
370;;{{{ Font-locking
371(defvar singular-font-lock-error-face 'singular-font-lock-error-face
372  "Face name to use for Singular errors.")
373
374(defvar singular-font-lock-warning-face 'singular-font-lock-warning-face
375  "Face name to use for Singular warnings.")
376
377(defvar singular-font-lock-prompt-face 'singular-font-lock-prompt-face
378  "Face name to use for Singular prompts.")
379
380(defface singular-font-lock-error-face
381  '((((class color)) (:foreground "Red" :bold t))
382    (t (:inverse-video t :bold t)))
383  "*Font Lock mode face used to highlight Singular errors."
384  :group 'singular-faces)
385
386(defface singular-font-lock-warning-face
387  '((((class color)) (:foreground "OrangeRed" :bold nil))
388    (t (:inverse-video t :bold t)))
389  "*Font Lock mode face used to highlight Singular warnings."
390  :group 'singular-faces)
391
392(defface singular-font-lock-prompt-face
393  '((((class color) (background light)) (:foreground "Blue" :bold t))
394    (((class color) (background dark)) (:foreground "LightSkyBlue" :bold t))
395    (t (:inverse-video t :bold t)))
396  "*Font Lock mode face used to highlight Singular prompts."
397  :group 'singular-faces)
398
399(defconst singular-font-lock-singular-types nil
400  "List of Singular types.")
401
402(eval-when-compile
403  (setq singular-font-lock-singular-types
404        '("def" "bigint" "ideal" "int" "intmat" "intvec" "link" "list" "map"
405          "matrix" "module" "number" "poly" "proc" "qring" "resolution" "ring"
406          "string" "vector")))
407
408(defconst singular-interactive-font-lock-keywords-1
409  '(
410    ("^\\([>.]\\) " 1 singular-font-lock-prompt-face t)
411    ("^   [\\?].*" 0 singular-font-lock-error-face t)
412    ("^// \\*\\*.*" 0 singular-font-lock-warning-face t)
413    )
414  "Subdued level highlighting for Singular interactive mode")
415
416(defconst singular-interactive-font-lock-keywords-2
417  (append
418   singular-interactive-font-lock-keywords-1
419   (eval-when-compile
420     (list
421      (cons
422       (concat "\\<" (regexp-opt singular-font-lock-singular-types t) "\\>")
423       'font-lock-type-face))))
424  "Medium level highlighting for Singular interactive mode")
425
426(defconst singular-interactive-font-lock-keywords-3
427  (append
428   singular-interactive-font-lock-keywords-2
429   '(
430     ;; note: we use font-lock-reference-face here even Emacs says that
431     ;; this face is obsolete and suggests to use font-lock-constant-face,
432     ;; since XEmacs20/21 does not know the constant-face but the
433     ;; reference-face.
434     ("^   [\\?].*`\\(\\sw\\sw+;?\\)`" 1 font-lock-reference-face t)
435     ))
436  "Gaudy level highlighting for Singular interactive mode.")
437
438(defconst singular-interactive-font-lock-keywords singular-interactive-font-lock-keywords-1
439  "Default highlighting for Singular interactive mode.")
440
441(defconst singular-interactive-font-lock-defaults
442  '((singular-interactive-font-lock-keywords
443     singular-interactive-font-lock-keywords-1
444     singular-interactive-font-lock-keywords-2
445     singular-interactive-font-lock-keywords-3)
446    ;; KEYWORDS-ONLY (do not fontify strings & comments if non-nil)
447    nil
448    ;; CASE-FOLD (ignore case if non-nil)
449    nil
450    ;; SYNTAX-ALIST (add this to Font Lock's syntax table)
451    ((?_ . "w"))
452    ;; SYNTAX-BEGIN
453    singular-section-goto-beginning)
454  "Default expressions to highlight in Singular interactive mode.")
455
456(defun singular-interactive-font-lock-init ()
457  "Initialize Font Lock mode for Singular interactive mode.
458
459For XEmacs, this function is called exactly once when singular.el is
460loaded.
461For Emacs, this function is called  at mode initialization time."
462  (cond 
463   ;; Emacs
464   ((eq singular-emacs-flavor 'emacs)
465    (singular-debug 'interactive (message "Setting up Font Lock mode for Emacs"))
466    (set (make-local-variable 'font-lock-defaults)
467         singular-interactive-font-lock-defaults))
468   ;; XEmacs
469   ((eq singular-emacs-flavor 'xemacs)
470    (singular-debug 'interactive (message "Setting up Font Lock mode for XEmacs"))
471    (put 'singular-interactive-mode
472         'font-lock-defaults singular-interactive-font-lock-defaults))))
473
474;; XEmacs Font Lock mode initialization
475(cond
476 ;; XEmacs
477 ((eq singular-emacs-flavor 'xemacs)
478  (singular-interactive-font-lock-init)))
479;;}}}
480
481;;{{{ Key map
482(defvar singular-interactive-mode-map nil
483  "Key map to use in Singular interactive mode.")
484
485(if singular-interactive-mode-map
486    ()
487  ;; create empty keymap first
488  (cond
489   ;; Emacs
490   ((eq singular-emacs-flavor 'emacs)
491    (setq singular-interactive-mode-map (make-sparse-keymap)))
492   ;; XEmacs
493   (t
494    (setq singular-interactive-mode-map (make-keymap))
495    (set-keymap-name singular-interactive-mode-map
496                     'singular-interactive-mode-map)))
497
498  ;; global settings
499  (define-key help-map [?\C-s]                                'singular-help)
500
501  ;; settings for `singular-interactive-map'
502  (substitute-key-definition 'beginning-of-line 'singular-beginning-of-line
503                             singular-interactive-mode-map global-map)
504
505  (define-key singular-interactive-mode-map "\t"              'singular-dynamic-complete)
506  (define-key singular-interactive-mode-map [?\C-m]           'singular-send-or-copy-input)
507  (define-key singular-interactive-mode-map [?\C-l]           'singular-recenter)
508
509  ;; Comint functions
510  (define-key singular-interactive-mode-map [?\M-r]           'comint-previous-matching-input)
511  (define-key singular-interactive-mode-map [?\M-s]           'comint-next-matching-input)
512
513  ;; C-c prefix
514  (define-key singular-interactive-mode-map [?\C-c ?\C-e]     'singular-example)
515  (define-key singular-interactive-mode-map [?\C-c ?\C-t]     'singular-toggle-truncate-lines)
516
517  (define-key singular-interactive-mode-map [?\C-c ?\C-f]     'singular-folding-toggle-fold-at-point-or-all)
518  (define-key singular-interactive-mode-map [?\C-c ?\C-o]     'singular-folding-toggle-fold-latest-output)
519  (define-key singular-interactive-mode-map [?\C-c ?\C-w]     'singular-section-kill)
520
521  (define-key singular-interactive-mode-map [?\C-c ?\C-d]     'singular-demo-load)
522  (define-key singular-interactive-mode-map [?\C-c ?\C-l]     'singular-load-library)
523  (define-key singular-interactive-mode-map [(control c) (<)] 'singular-load-file)
524
525  (define-key singular-interactive-mode-map [?\C-c ?\C-r]     'singular-restart)
526  (define-key singular-interactive-mode-map [?\C-c ?\$] 'singular-exit-singular)
527  (define-key singular-interactive-mode-map [?\C-c ?\C-c] 'singular-control-c))
528
529(defun singular-cursor-key-model-set (key-model)
530  "Set keys according to KEY-MODEL.
531KEY-MODEL should be one of the valid values of `singular-cursor-key-model'."
532  ;; convert symbols to list
533  (cond ((eq key-model 'emacs)
534         (setq key-model '(cursor cursor history)))
535        ((eq key-model 'terminal)
536         (setq key-model '(history history cursor))))
537
538  ;; work through list
539  (mapcar (function (lambda (spec)
540                      (let ((key-description (nth 0 spec))
541                            (prev-key (nth 1 spec))
542                            (next-key (nth 2 spec)))
543                        (cond ((eq key-description 'cursor)
544                               (define-key singular-interactive-mode-map prev-key 'previous-line)
545                               (define-key singular-interactive-mode-map next-key 'next-line))
546                              ((eq key-description 'history)
547                               (define-key singular-interactive-mode-map prev-key 'comint-previous-input)
548                               (define-key singular-interactive-mode-map next-key 'comint-next-input))
549                              (t
550                               (define-key singular-interactive-mode-map prev-key nil)
551                               (define-key singular-interactive-mode-map next-key nil))))))
552                             
553          ;; here is where list position are mapped to keys
554          (list (list (nth 0 key-model) [up] [down])
555                (list (nth 1 key-model) [?\C-p] [?\C-n])
556                (list (nth 2 key-model) [?\M-p] [?\M-n]))))
557
558(defcustom singular-cursor-key-model 'emacs
559  "*Keys to use for cursor movement and history access, respectively.
560An experienced Emacs user would prefer setting `singular-cursor-key-model'
561to `emacs'.  This means that C-p, C-n, and the cursor keys move the cursor,
562whereas M-p and M-n scroll through the history of Singular commands.
563
564On the other hand, an user used to running Singular in a, say, xterm, would
565prefer setting `singular-cursor-key-model' to `terminal'.  This means that
566C-p, C-n, and the cursor keys scroll through the history of Singular
567commands, whereas M-p and M-n move the cursor.
568
569For those who do not like neither standard setting, there is the
570possibility to set this variable to a list of three elements where
571- the first element specifies the key bindings for the cursor keys,
572- the second element specifies the key bindings for C-p and C-n, and
573- the third element specifies the key bindings for M-p and M-n.
574Each list element should be one of
575- `cursor', meaning that the corresponding keys are bound to cursor movement,
576- `history', meaning that the corresponding keys are bound to history access,
577  or
578- nil, meaning that the corresponding keys are not bound at all.
579
580Changing this variable has an immediate effect only if one uses
581\\[customize] to do so."
582  :type '(choice (const :tag "Emacs-like" emacs)
583                 (const :tag "Terminal-like" terminal)
584                 (list :tag "User-defined"
585                      (choice :format "Cursor keys: %[Value Menu%] %v"
586                              :value cursor
587                              (const :tag "Cursor movement" cursor)
588                              (const :tag "History access" history)
589                              (const :tag "No binding" nil))
590                      (choice :format "C-p, C-n:    %[Value Menu%] %v"
591                              :value cursor
592                              (const :tag "Cursor movement" cursor)
593                              (const :tag "History access" history)
594                              (const :tag "No binding" nil))
595                      (choice :format "M-p, M-n:    %[Value Menu%] %v"
596                              :value history
597                              (const :tag "Cursor movement" cursor)
598                              (const :tag "History access" history)
599                              (const :tag "No binding" nil))))
600  :initialize 'custom-initialize-reset
601  :set (function
602        (lambda (var value)
603          (singular-cursor-key-model-set value)
604          (set-default var value)))
605  :group 'singular-interactive-miscellaneous)
606
607(defun singular-interactive-mode-map-init ()
608  "Initialize key map for Singular interactive mode.
609
610This function is called  at mode initialization time."
611  (use-local-map singular-interactive-mode-map))
612;;}}}
613
614;;{{{ Menus and logos
615(defvar singular-interactive-mode-menu-1 nil
616  "NOT READY [docu]")
617
618(defvar singular-interactive-mode-menu-2 nil
619  "NOT READY [docu]")
620
621(defconst singular-menu-initial-library-menu
622  '(["other..." (singular-load-library t) t])
623  "Menu definition for the inital library sub menu.
624This should be a list of vectors.")
625
626(defun singular-menu-build-libraries-menu (definition)
627  "Given a description of the libraries and their categories, builds up a
628menu definition including submenus which can be given to
629`easy-menu-change'.  By side effect sets the variable
630`singular-standard-libraries-alist' to the alist of all library names.
631This alist can be used for completion."
632  (let ((menudef ())
633        (libs definition)
634        elem)
635    (while libs
636      (setq elem (car libs))
637      (if (> (length elem) 1)
638          (setq menudef
639                (append 
640                 (list 
641                  (append (list (car elem))
642                          (singular-menu-build-libraries-menu (cdr elem))))
643                 menudef))
644        (setq menudef 
645              (append (list (vector (car elem)
646                                    (list 'singular-load-library nil
647                                          (car elem))
648                                    t))
649                      menudef))
650        (setq singular-standard-libraries-alist 
651              (append (list elem) singular-standard-libraries-alist)))
652      (setq libs (cdr libs)))
653    menudef))
654
655(defun singular-menu-install-libraries ()
656  "Update the singular command menu with libraries.
657Scans the variable `singular-standard-libraries-with-categories' and builds
658up a menu with submenues for each category in the submenu (\"Commands\"
659\"Libraries\")."
660  (singular-debug 'interactive (message "Installing library menu"))
661  ;; To be compatible with older versions of singular.el (resp. of lib-cmpl.el)
662  ;; we check whether the variable
663  ;; `singular-standard-libraries-with-categories' is set.  If not, we use the
664  ;; value of `singular-standard-libraries-alist' instead.
665  (if (not singular-standard-libraries-with-categories)
666      (setq singular-standard-libraries-with-categories
667            singular-standard-libraries-alist))
668  (easy-menu-change '("Commands")
669                    "Libraries"
670                    (append 
671                     (singular-menu-build-libraries-menu
672                      singular-standard-libraries-with-categories)
673                     (append '("---") singular-menu-initial-library-menu))))
674
675(defun singular-menu-init ()
676  "Initialize menu stuff for Singular interactive mode.
677
678This function is called by `singular-exec'."
679  (singular-debug 'interactive (message "Initializing menue stuff"))
680  (make-local-variable 'singular-standard-libraries-alist)
681  (make-local-variable 'singular-standard-libraries-with-categories))
682
683(defun singular-menu-deinstall-libraries ()
684  "Initialize library submenu from singular command menu.
685Sets the submenu (\"Commands\" \"Libraries\") to the value of
686`singular-menu-initial-library-menu'."
687  (singular-debug 'interactive 
688                  (message "Removing libraries from menu"))
689  (easy-menu-change '("Commands") "Libraries" singular-menu-initial-library-menu))
690
691;; For some reasons emacs inserts new menus in the oppsite order.
692;; Defining menu-2 prior to menu-1 will result in the follwoing menu:
693;;   Singular   Commands
694;; That's what we want. So DO NOT exchange both (or ..) statements!
695(or singular-interactive-mode-menu-2
696    (easy-menu-define 
697     singular-interactive-mode-menu-2
698     singular-interactive-mode-map ""
699     (list 
700      "Commands"
701      ["Fold/Unfold Latest Output" singular-folding-toggle-fold-latest-output t]
702      ["Fold/Unfold At Point" singular-folding-toggle-fold-at-point-or-all t]
703      ["Fold All Output" singular-folding-fold-all-output t]
704      ["Unfold All Output" singular-folding-unfold-all-output t]
705      "---"
706      ["Truncate Lines" singular-toggle-truncate-lines
707       :style toggle :selected truncate-lines]
708      "--"
709      (append
710       '("Libraries")
711       singular-menu-initial-library-menu)
712      ["Load File..." singular-load-file t]
713      "---"
714      ["Load Demo..." singular-demo-load (or singular-demo-exit-on-load
715                                             (not singular-demo-mode))]
716      ["Exit Demo" singular-demo-exit singular-demo-mode]
717      )))
718
719(or singular-interactive-mode-menu-1
720    (easy-menu-define singular-interactive-mode-menu-1
721                      singular-interactive-mode-map ""
722                      '("Singular"
723                        ["Start Default" singular t]
724                        ["Start..." singular-other t]
725                        ["Restart" singular-restart t]
726                        "---"
727                        ["Interrupt" singular-control-c t]
728                        ["Exit" singular-exit-singular t]
729                        "---"
730                        ["Preferences" (customize-group 'singular-interactive) t]
731                        ["Singular Example" singular-example t]
732                        ["Singular Help" singular-help t])))
733
734(defun customize-singular-interactive ()
735  (interactive)
736  (customize-group 'singular-interactive))
737
738(defun singular-interactive-mode-menu-init ()
739  "Initialize menus for Singular interactive mode.
740
741This function is called  at mode initialization time."
742  ;; Remove any potential menu which comint-mode might has added.
743  (cond 
744   ;; Emacs
745   ((eq singular-emacs-flavor 'emacs)
746    ;; Note that easy-menu-remove is a nop in emacs.
747    (define-key comint-mode-map [menu-bar signals] nil)
748    (define-key comint-mode-map [menu-bar inout] nil)
749    (define-key comint-mode-map [menu-bar completion] nil))
750   ;;Xemacs
751   (t
752    (easy-menu-remove '("Singular"))
753    (easy-menu-remove '("Comint1"))     ; XEmacs 20
754    (easy-menu-remove '("Comint2"))     ; XEmacs 20
755    (easy-menu-remove '("History"))     ; XEmacs 20
756    (easy-menu-remove '("Complete"))    ; XEmacs 21
757    (easy-menu-remove '("In/Out"))      ; XEmacs 21
758    (easy-menu-remove '("Signals"))))   ; XEmacs 21
759
760  ;; Note: easy-menu-add is not necessary in emacs, since the menu
761  ;; is added automatically with the keymap.
762  ;; See help on `easy-menu-add'
763  (easy-menu-add singular-interactive-mode-menu-1)
764  (easy-menu-add singular-interactive-mode-menu-2))
765;;}}}
766
767;;{{{ Skipping and stripping prompts and whitespace and other things
768
769;; Note:
770;;
771;; Most of these functions handle prompt recognition, prompt skipping,
772;; prompt stripping, and so on.  It turned out that it would be very
773;; inefficient to use one generic regular expression to do so.  Hence, we
774;; decided to hardcode the prompt skipping and stripping in an API.  If one
775;; decides to use some other prompt the whole API has to be changed.
776;; Hopefully, the Singular prompt does not change in near future ...
777;;
778;; In addition to the API, the Comint mode variable `comint-mode-regexp' is
779;; set on initialization of Singular interactive mode.  Singular
780;; interactive mode seems to do quite well without that, but for safety the
781;; variable is set nonetheless.
782
783(defsubst singular-prompt-skip-forward ()
784  "Skip forward over prompts."
785  (if (looking-at "\\([>.] \\)+")
786      (goto-char (match-end 0))))
787
788(defsubst singular-prompt-skip-backward ()
789  "Skip backward over prompts."
790  ;; is that really the simplest and fastest method?  The problem is that
791  ;; `re-search-backward' is not greedy so on an regexp as "\\([>.] \\)+"
792  ;; it stops right after the first occurence of the sub-expression.
793  ;; Anyway, the `(- (point) 2)' expression is OK, even at bob.
794  (while (re-search-backward "[>.] " (- (point) 2) t)))
795
796(defun singular-prompt-remove-string (string)
797  "Remove all prompts from STRING."
798  (while (string-match "^\\([>.] \\)+" string)
799    (setq string (replace-match "" t t string)))
800  string)
801
802(defun singular-prompt-remove-region (beg end)
803  "Remove all superfluous prompts from region between BEG and END.
804Removes only sequences of prompts that start at beginning of line.  Removes
805all but the last prompt of a sequence if that sequence ends at END,
806otherwise removes all prompts.
807The region between BEG and END should be accessible.  BEG should be less
808than or equal to END.
809Leaves point at the position of the last sequence of prompts which has been
810deleted or at BEG if nothing has been deleted."
811  ;; we cannot exclude this case, I think
812  (if (/= beg end)
813      ;; that's a nice trick to keep the last prompt if it ends at END: we
814      ;; set `(1- END)' as search limit.  Since BEG /= END there can be no
815      ;; problems with the `1-'.
816      (let ((end (copy-marker (1- end))))
817        (goto-char beg)
818        (while (re-search-forward "^\\([>.] \\)+" end t)
819          (delete-region (match-beginning 0) (match-end 0)))
820        (set-marker end nil))))
821
822(defun singular-prompt-remove-filter (beg end simple-sec-start)
823  "Remove all superfluous prompts from text inserted into buffer."
824  (cond (;; if a new simple section has been created remove all
825         ;; prompts from that simple section
826         simple-sec-start
827         (singular-prompt-remove-region simple-sec-start end))
828        (;; if no simple section has been created check whether maybe the
829         ;; region between beg and end consists of prompts only.  This in
830         ;; case that the user issued a command that did not output any
831         ;; text.
832         (and (goto-char beg)
833              (re-search-forward "\\([>.] \\)+" end t)
834              (= (match-end 0) end))
835         (singular-prompt-remove-region (progn (beginning-of-line) (point))
836                                        end))))
837
838(defun singular-white-space-strip (string &optional trailing leading)
839  "Strip off trailing or leading whitespace from STRING.
840Strips off trailing whitespace if optional argument TRAILING is non-nil.
841Strips off leading whitespace if optional argument LEADING is non-nil."
842  (let (beg end)
843    (and leading
844         (string-match "\\`[ \t\n\r\f]+" string)
845         (setq beg (match-end 0)))
846    (and trailing
847         (string-match "[ \t\n\r\f]+\\'" string)
848         (setq end (match-beginning 0)))
849    (if (or beg end)
850        (substring string (or beg 0) (or end (length string)))
851      string)))
852
853(defconst singular-comint-prompt-regexp "^\\([>.] \\)+"
854  "Regexp to match prompt patterns in Singular.
855This variable is used to initialize `comint-prompt-regexp' when Singular
856interactive mode starts up.  It is not used in Singular interactive mode
857itself!  One should refer to the source code for more information on how to
858adapt Singular interactive mode to some other prompt.")
859
860(defun singular-prompt-init ()
861  "Initialize prompt skipping and stripping for Singular interactive mode.
862
863This function is called at mode initialization time."
864  ;; remove superfluous prompts in singular output
865  (add-hook 'singular-post-output-filter-functions 'singular-prompt-remove-filter nil t)
866
867  ;; some relict from Comint mode
868  (setq comint-prompt-regexp singular-comint-prompt-regexp))
869  ;; required to use prompt-regexp
870  (setq comint-use-prompt-regexp t)
871;;}}}
872
873;;{{{ Miscellaneous
874
875;; Note:
876;;
877;; We assume a one-to-one correspondence between Singular buffers and
878;; Singular processes.  We always have (equal buffer-name (concat "*"
879;; process-name "*")).
880
881(defsubst singular-buffer-name-to-process-name (buffer-name)
882  "Create the process name for BUFFER-NAME.
883The process name is the buffer name with surrounding `*' stripped off."
884  (substring buffer-name 1 -1))
885
886(defsubst singular-process-name-to-buffer-name (process-name)
887  "Create the buffer name for PROCESS-NAME.
888The buffer name is the process name with surrounding `*'."
889  (concat "*" process-name "*"))
890
891(defsubst singular-run-hook-with-arg-and-value (hook value)
892  "Call functions on HOOK.
893Provides argument VALUE to the functions.  If a function returns a non-nil
894value it replaces VALUE as new argument to the remaining functions.
895Returns final VALUE."
896  (while hook
897    (setq value (or (funcall (car hook) value) value)
898          hook (cdr hook)))
899  value)
900
901(defsubst singular-process (&optional no-error)
902  "Return process of current buffer.
903If no process is active this function silently returns nil if optional
904argument NO-ERROR is non-nil, otherwise it throws an error."
905  (cond ((get-buffer-process (current-buffer)))
906        (no-error nil)
907        (t (error "No Singular running in this buffer"))))
908
909(defsubst singular-process-mark (&optional no-error)
910  "Return process mark of current buffer.
911If no process is active this function silently returns nil if optional
912argument NO-ERROR is non-nil, otherwise it throws an error."
913  (let ((process (singular-process no-error)))
914    (and process
915         (process-mark process))))
916
917(defun singular-time-stamp-difference (new-time-stamp old-time-stamp)
918  "Return the number of seconds between NEW-TIME-STAMP and OLD-TIME-STAMP.
919Both NEW-TIME-STAMP and OLD-TIME-STAMP should be in the format
920that is returned, for example, by `current-time'.
921Does not return a difference larger than 2^17 seconds."
922  (let ((high-difference (min 1 (- (car new-time-stamp) (car old-time-stamp))))
923        (low-difference (- (cadr new-time-stamp) (cadr old-time-stamp))))
924    (+ (* high-difference 131072) low-difference)))
925
926(defun singular-error (&rest message-args)
927  "Apply `message' on MESSAGE-ARGS and do a `ding'.
928This function should be used instead of `error' in hooks where calling
929`error' is not a good idea."
930  (apply 'message message-args)
931  (ding))
932
933(defun singular-pop-to-buffer (same-window &rest pop-to-buffer-args)
934  "Pop to buffer in same or other window.
935Pops to buffer in same window if SAME-WINDOW equals t.  Pops to buffer in
936other window if SAME-WINDOW equals nil.  If SAME-WINDOW equals neither t
937nor nil the default behaviour of `pop-to-buffer' is used.  The rest of the
938arguments is passed unchanged to `pop-to-buffer'."
939  (let ((same-window-buffer-names
940         (cond
941          ((null same-window)
942           nil)
943          ((eq same-window t)
944           (let* ((buffer-or-name (car pop-to-buffer-args))
945                  (buffer-name (if (bufferp buffer-or-name)
946                                   (buffer-name buffer-or-name)
947                                 buffer-or-name)))
948             (list buffer-name)))
949          (t
950           same-window-buffer-names))))
951    (apply 'pop-to-buffer pop-to-buffer-args)))
952;;}}}
953
954;;{{{ Miscellaneous interactive
955(defun singular-recenter (&optional arg)
956  "Center point in window and redisplay frame.  With ARG, put point on line ARG.
957The desired position of point is always relative to the current window.
958Just C-u as prefix means put point in the center of the window.
959If ARG is omitted or nil, erases the entire frame and then redraws with
960point in the center of the current window.
961Scrolls window to the left margin and moves point to beginning of line."
962  (interactive "P")
963  (singular-reposition-point-and-window)
964  (recenter arg))
965
966(defun singular-reposition-point-and-window ()
967  "Scroll window to the left margin and move point to beginning of line."
968  (interactive)
969  (set-window-hscroll (selected-window) 0)
970  (move-to-column 0)
971  ;; be careful where to place point
972  (singular-prompt-skip-forward))
973
974(defun singular-toggle-truncate-lines ()
975  "Toggle `truncate-lines'.
976A non-nil value of `truncate-lines' means do not display continuation
977lines\; give each line of text one screen line.
978Repositions window and point after toggling `truncate-lines'."
979  (interactive)
980  (setq truncate-lines (not truncate-lines))
981  ;; reposition so that user does not get confused
982  (singular-reposition-point-and-window)
983  ;; avoid calling `recenter' since it changes window layout more than
984  ;; necessary
985  (redraw-frame (selected-frame)))
986
987;; this is not a buffer-local variable even if at first glance it seems
988;; that it should be one.  But if one changes buffer the contents of this
989;; variable becomes irrelevant since the last command is no longer a
990;; horizontal scroll command.  The same is true for the initial value, so
991;; we set it to nil.
992(defvar singular-scroll-previous-amount nil
993  "Amount of previous horizontal scroll command.")
994
995(defun singular-scroll-right (&optional scroll-amount)
996  "Scroll selected window SCROLL-AMOUNT columns right.
997SCROLL-AMOUNT defaults to amount of previous horizontal scroll command.  If
998the command immediately preceding this command has not been a horizontal
999scroll command SCROLL-AMOUNT defaults to window width minus 2.
1000Moves point to leftmost visible column."
1001  (interactive "P")
1002
1003  ;; get amount to scroll
1004  (setq singular-scroll-previous-amount
1005        (cond (scroll-amount (prefix-numeric-value scroll-amount))
1006              ((eq last-command 'singular-scroll-horizontal)
1007               singular-scroll-previous-amount)
1008              (t (- (frame-width) 2)))
1009        this-command 'singular-scroll-horizontal)
1010
1011  ;; scroll
1012  (scroll-right singular-scroll-previous-amount)
1013  (move-to-column (window-hscroll))
1014  ;; be careful where to place point.  But what if `(current-column)'
1015  ;; equals, say, one?  Well, we simply do not care about that case.
1016  ;; Should not happen to often.
1017  (if (eq (current-column) 0)
1018      (singular-prompt-skip-forward)))
1019
1020(defun singular-scroll-left (&optional scroll-amount)
1021  "Scroll selected window SCROLL-AMOUNT columns left.
1022SCROLL-AMOUNT defaults to amount of previous horizontal scroll command.  If
1023the command immediately preceding this command has not been a horizontal
1024scroll command SCROLL-AMOUNT defaults to window width minus 2.
1025Moves point to leftmost visible column."
1026  (interactive "P")
1027
1028  ;; get amount to scroll
1029  (setq singular-scroll-previous-amount
1030        (cond (scroll-amount (prefix-numeric-value scroll-amount))
1031              ((eq last-command 'singular-scroll-horizontal)
1032               singular-scroll-previous-amount)
1033              (t (- (frame-width) 2)))
1034        this-command 'singular-scroll-horizontal)
1035
1036  ;; scroll
1037  (scroll-left singular-scroll-previous-amount)
1038  (move-to-column (window-hscroll))
1039  ;; be careful where to place point.  But what if `(current-column)'
1040  ;; equals, say, one?  Well, we simply do not care about that case.
1041  ;; Should not happen to often.
1042  (if (eq (current-column) 0)
1043      (singular-prompt-skip-forward)))
1044
1045(defun singular-beginning-of-line  (arg)
1046  "Move point to the beginning of line, then skip past prompt, if any.
1047If prefix argument is given the prompt is not skipped."
1048  (interactive "P")
1049  (beginning-of-line)
1050  (if (not arg) (singular-prompt-skip-forward)))
1051
1052(defun singular-load-file (file &optional noexpand)
1053  "Read a file into Singular (via '< \"FILE\";').
1054If optional argument NOEXPAND is non-nil, FILE is left as it is entered by
1055the user, otherwise it is expanded using `expand-file-name'."
1056  (interactive "fLoad file: ")
1057  (let* ((filename (if noexpand file (expand-file-name file)))
1058         (string (concat "< \"" filename "\";"))
1059         (process (singular-process)))
1060    (singular-input-filter process string)
1061    (singular-send-string process string)))
1062
1063(defvar singular-load-library-history nil
1064  "History list for loading of Singular libraries.
1065Is used by `singular-load-library'.")
1066
1067(defun singular-load-library (nonstdlib &optional file)
1068  "Read a Singular library (via 'LIB \"FILE\";').
1069If called interactively asks for the name of a standard Singular
1070library. If called interactively with a prefix argument asks for a file
1071name of a Singular library."
1072  (interactive "P")
1073  (let ((string (or file
1074                    (if nonstdlib
1075                        (read-file-name "Library file: ")
1076                      (completing-read "Library: " singular-standard-libraries-alist
1077                                       nil nil nil 'singular-load-library-history))))
1078        (process (singular-process)))
1079    (setq string (concat "LIB \"" string "\";"))
1080    (singular-input-filter process string)
1081    (singular-send-string process string)))
1082;;}}}
1083
1084;;{{{ History
1085(defcustom singular-history-ignoredups t
1086  "*If non-nil, do not add input matching the last on the input history."
1087  :type 'boolean
1088  :initialize 'custom-initialize-default
1089  :group 'singular-interactive-miscellaneous)
1090
1091;; this variable is used to set Comint's `comint-input-ring-size'
1092(defcustom singular-history-size 64
1093  "*Size of the input history.
1094
1095Changing this variable has no immediate effect even if one uses
1096\\[customize] to do so.  The new value will be used only in new Singular
1097interactive mode buffers."
1098  :type 'integer
1099  :initialize 'custom-initialize-default
1100  :group 'singular-interactive-miscellaneous)
1101
1102(defcustom singular-history-filter-regexp "\\`\\(..?\\|\\s *\\)\\'"
1103  "*Regular expression to filter strings *not* to insert in the input history.
1104By default, input consisting of less than three characters and input
1105consisting of white-space only is not inserted into the input history."
1106  :type 'regexp
1107  :initialize 'custom-initialize-default
1108  :group 'singular-interactive-miscellaneous)
1109
1110(defcustom singular-history-explicit-file-name nil
1111  "*If non-nil, use this as file name to load and save the input history.
1112If this variable equals nil, the `SINGULARHIST' environment variable is
1113used to determine the file name.
1114One should note that the input history is saved to file only on regular
1115termination of Singular; that is, if one leaves Singular using the commands
1116`quit\;' or `exit\;'."
1117  :type '(choice (const nil) file)
1118  :initialize 'custom-initialize-default
1119  :group 'singular-interactive-miscellaneous)
1120
1121(defun singular-history-read ()
1122  "Read the input history from file.
1123If `singular-history-explicit-file-name' is non-nil, uses that as file
1124name, otherwise tries environment variable `SINGULARHIST'.
1125This function is called from `singular-exec' every time a new Singular
1126process is started."
1127  (singular-debug 'interactive (message "Reading input ring"))
1128  (let ((comint-input-ring-file-name (or singular-history-explicit-file-name
1129                                         (getenv "SINGULARHIST"))))
1130    ;; `comint-read-input-ring' does nothing if
1131    ;; `comint-input-ring-file-name' equals nil
1132    (comint-read-input-ring t)))
1133
1134(defun singular-history-write ()
1135  "Write back the input history to file.
1136If `singular-history-explicit-file-name' is non-nil, uses that as file
1137name, otherwise tries environment variable `SINGULARHIST'.
1138This function is called either by `singular-exit-singular' or by
1139`singular-exit-sentinel' every time a Singular process terminates
1140regularly."
1141  (singular-debug 'interactive (message "Writing input ring back"))
1142  (let ((comint-input-ring-file-name (or singular-history-explicit-file-name
1143                                         (getenv "SINGULARHIST"))))
1144    ;; `comint-write-input-ring' does nothing if
1145    ;; `comint-input-ring-file-name' equals nil
1146    (comint-write-input-ring)))
1147
1148(defun singular-history-insert (input)
1149  "Insert string INPUT into the input history if necessary."
1150  (if (and (not (string-match singular-history-filter-regexp input))
1151           (or (not singular-history-ignoredups)
1152               (not (ring-p comint-input-ring))
1153               (ring-empty-p comint-input-ring)
1154               (not (string-equal (ring-ref comint-input-ring 0) input))))
1155      (ring-insert comint-input-ring input))
1156  (setq comint-input-ring-index nil))
1157
1158(defun singular-history-init ()
1159  "Initialize variables concerning the input history.
1160
1161This function is called at mode initialization time."
1162  (setq comint-input-ring-size singular-history-size))
1163;;}}}
1164
1165;;{{{ Simple section API for both Emacs and XEmacs
1166
1167;; Note:
1168;;
1169;; Sections and simple sections are used to mark Singular's input and
1170;; output for further access.  Here are some general notes on simple
1171;; sections.  Sections are explained in the respective folding.
1172;;
1173;; In general, simple sections are more or less Emacs' overlays or XEmacs
1174;; extents, resp.  But they are more than simply an interface to overlays
1175;; or extents.
1176;;
1177;; - Simple sections are non-empty portions of text.  They are interpreted
1178;;   as left-closed, right-opened intervals, i.e., the start point of a
1179;;   simple sections belongs to it whereas the end point does not.
1180;; - Simple sections start and end at line borders only.
1181;; - Simple sections do not overlap.  Thus, any point in the buffer may be
1182;;   covered by at most one simple section.
1183;; - Besides from their start and their end, simple sections have some type
1184;;   associated.
1185;; - Simple sections are realized using overlays (extents for XEmacs)
1186;;   which define the start and, end, and type (via properties) of the
1187;;   simple section.  Actually, as a lisp object a simple section is
1188;;   nothing else but the underlying overlay.
1189;; - There may be so-called clear simple sections.  Clear simple sections
1190;;   have not an underlying overlay.  Instead, they start at the end of the
1191;;   preceding non-clear simple section, end at the beginning of the next
1192;;   non-clear simple section, and have the type defined by
1193;;   `singular-simple-sec-clear-type'.  Clear simple sections are
1194;;   represented by nil.
1195;; - Buffer narrowing does not restrict the extent of completely or
1196;;   partially inaccessible simple sections.  But one should note that
1197;;   some of the functions assume that there is no narrowing in
1198;;   effect.
1199;; - After creation, simple sections are not modified any further.
1200;; - There is one nasty little corner case: what if a non-clear simple
1201;;   section spans up to end of buffer?  By definition, eob is not included
1202;;   in that section since they are right-opened intervals.  Most of the
1203;;   functions react as if there is an imagenary empty clear simple section
1204;;   at eob.
1205;; - Even though by now there are only two types of different simple
1206;;   sections there may be an arbitrary number of them.  Furthermore,
1207;;   simple sections of different types may appear in arbitrary order.
1208;;
1209;; - In `singular-interactive-mode', the whole buffer is covered with
1210;;   simple sections from the very beginning of the file up to the
1211;;   beginning of the line containing the last input or output.  The
1212;;   remaining text up to `(point-max)' may be interpreted as covered by
1213;;   one clear simple section.  Thus, it is most reasonable to define
1214;;   `input' to be the type of clear simple sections.
1215
1216(defvar singular-simple-sec-clear-type 'input
1217  "Type of clear simple sections.
1218If nil no clear simple sections are used.
1219
1220One should not set this variable directly.  Rather, one should customize
1221`singular-section-face-alist'.")
1222
1223(defvar singular-simple-sec-last-end nil
1224  "Marker at the end of the last simple section.
1225Should be initialized by `singular-simple-sec-init' before any calls to
1226`singular-simple-sec-create' are done.  Instead of accessing this variable
1227directly one should use the macro `singular-simple-sec-last-end-position'.
1228
1229This variable is buffer-local.")
1230
1231(defun singular-simple-sec-init (pos)
1232  "Initialize variables belonging to simple section management.
1233Creates the buffer-local marker `singular-simple-sec-last-end' and
1234initializes it to POS.  POS should be at beginning of a line.
1235
1236This function is called every time a new Singular session is started."
1237  (make-local-variable 'singular-simple-sec-last-end)
1238  (if (not (markerp singular-simple-sec-last-end))
1239      (setq singular-simple-sec-last-end (make-marker)))
1240  (set-marker singular-simple-sec-last-end pos))
1241
1242(defmacro singular-simple-sec-last-end-position ()
1243  "Return the marker position of `singular-simple-sec-last-end'.
1244This macro exists more or less for purposes of information hiding only."
1245  '(marker-position singular-simple-sec-last-end))
1246
1247(defsubst singular-simple-sec-lookup-face (type)
1248  "Return the face to use for simple sections of type TYPE.
1249This accesses the `singular-section-type-alist'.  It does not harm if nil
1250is associated with TYPE in that alist: In this case, this function will
1251never be called for that TYPE."
1252  (cdr (assq type singular-section-face-alist)))
1253
1254;; Note:
1255;;
1256;; The rest of the folding is either marked as
1257;; Emacs
1258;; or
1259;; XEmacs
1260
1261(singular-fset 'singular-simple-sec-create
1262               'singular-emacs-simple-sec-create
1263               'singular-xemacs-simple-sec-create)
1264
1265(singular-fset 'singular-simple-sec-at
1266               'singular-emacs-simple-sec-at
1267               'singular-xemacs-simple-sec-at)
1268
1269(singular-fset 'singular-simple-sec-start
1270               'singular-emacs-simple-sec-start
1271               'singular-xemacs-simple-sec-start)
1272
1273(singular-fset 'singular-simple-sec-end
1274               'singular-emacs-simple-sec-end
1275               'singular-xemacs-simple-sec-end)
1276
1277(singular-fset 'singular-simple-sec-type
1278               'singular-emacs-simple-sec-type
1279               'singular-xemacs-simple-sec-type)
1280
1281(singular-fset 'singular-simple-sec-before
1282               'singular-emacs-simple-sec-before
1283               'singular-xemacs-simple-sec-before)
1284
1285(singular-fset 'singular-simple-sec-start-at
1286               'singular-emacs-simple-sec-start-at
1287               'singular-xemacs-simple-sec-start-at)
1288
1289(singular-fset 'singular-simple-sec-end-at
1290               'singular-emacs-simple-sec-end-at
1291               'singular-xemacs-simple-sec-end-at)
1292
1293(singular-fset 'singular-simple-sec-in
1294               'singular-emacs-simple-sec-in
1295               'singular-xemacs-simple-sec-in)
1296;;}}}
1297
1298;;{{{ Simple section API for Emacs
1299(defsubst singular-emacs-simple-sec-start (simple-sec)
1300  "Return start of non-clear simple section SIMPLE-SEC.
1301Narrowing has no effect on this function."
1302  (overlay-start simple-sec))
1303
1304(defsubst singular-emacs-simple-sec-end (simple-sec)
1305  "Return end of non-clear simple section SIMPLE-SEC.
1306Narrowing has no effect on this function."
1307  (overlay-end simple-sec))
1308
1309(defsubst singular-emacs-simple-sec-type (simple-sec)
1310  "Return type of SIMPLE-SEC.
1311Returns nil if SIMPLE-SEC happens to be an overlay but not a simple
1312section.
1313Narrowing has no effect on this function."
1314  (if simple-sec
1315      (overlay-get simple-sec 'singular-type)
1316    singular-simple-sec-clear-type))
1317
1318(defsubst singular-emacs-simple-sec-before (pos)
1319  "Return simple section before buffer position POS.
1320This is the same as `singular-simple-sec-at' except if POS falls on a
1321section border.  In this case `singular-simple-section-before' returns the
1322previous simple section instead of the current one.  If POS falls on
1323beginning of buffer, the simple section at beginning of buffer is returned.
1324Narrowing has no effect on this function."
1325  (singular-emacs-simple-sec-at (max 1 (1- pos))))
1326
1327(defun singular-emacs-simple-sec-create (type end)
1328  "Create a new simple section of type TYPE.
1329Creates the section from end of previous simple section up to the first
1330beginning of line before END.  That position should be larger than or equal
1331to `singular-simple-sec-last-end'.  Updates `singular-simple-sec-last-end'.
1332Returns the new simple section or `empty' if no simple section has been
1333created.
1334Assumes that no narrowing is in effect."
1335  (let ((last-end (singular-simple-sec-last-end-position))
1336        ;; `simple-sec' is the new simple section or `empty'
1337        simple-sec)
1338
1339    ;; get beginning of line before END.  At this point we need that there
1340    ;; are no restrictions.
1341    (setq end (let ((old-point (point)))
1342                (goto-char end) (beginning-of-line)
1343                (prog1 (point) (goto-char old-point))))
1344
1345    (cond
1346     ;; do not create empty sections
1347     ((eq end last-end)
1348      'empty)
1349     ;; non-clear simple sections
1350     ((not (eq type singular-simple-sec-clear-type))
1351      ;; if type has not changed we only have to extend the previous simple
1352      ;; section.  If `last-end' happens to be 1 (meaning that we are
1353      ;; creating the first non-clear simple section in the buffer), then
1354      ;; `singular-simple-sec-before' returns nil,
1355      ;; `singular-simple-sec-type' returns the type of clear simple
1356      ;; sections that definitely does not equal TYPE, and a new simple
1357      ;; section is created as necessary.
1358      (setq simple-sec (singular-emacs-simple-sec-before last-end))
1359      (if (eq type (singular-emacs-simple-sec-type simple-sec))
1360          ;; move existing overlay
1361          (setq simple-sec (move-overlay simple-sec (overlay-start simple-sec) end))
1362        ;; create new overlay
1363        (setq simple-sec (make-overlay last-end end))
1364        ;; set type property
1365        (overlay-put simple-sec 'singular-type type)
1366        ;; set face
1367        (overlay-put simple-sec 'face (singular-simple-sec-lookup-face type))
1368        ;; evaporate empty sections
1369        (overlay-put simple-sec 'evaporate t))
1370      ;; update `singular-simple-sec-last-end' and return new simple
1371      ;; section
1372      (set-marker singular-simple-sec-last-end end)
1373      simple-sec)
1374     ;; clear simple sections
1375     (t
1376      ;; update `singular-simple-sec-last-end' and return nil
1377      (set-marker singular-simple-sec-last-end end)
1378      nil))))
1379
1380(defun singular-emacs-simple-sec-start-at (pos)
1381  "Return start of clear simple section at position POS.
1382Assumes the existence of an imagenary empty clear simple section if POS is
1383at end of buffer and there is non-clear simple section immediately ending
1384at POS.
1385Assumes that no narrowing is in effect (since `previous-overlay-change'
1386imlicitly does so)."
1387  ;; yes, this `(1+ pos)' is OK at eob for
1388  ;; `singular-emacs-simple-sec-before' as well as
1389  ;; `previous-overlay-change'
1390  (let ((previous-overlay-change-pos (1+ pos)))
1391    ;; this `while' loop at last will run into the end of the next
1392    ;; non-clear simple section or stop at bob.  Since POS may be right at
1393    ;; the end of a previous non-clear location, we have to search at least
1394    ;; one time from POS+1 backwards.
1395    (while (not (or (singular-emacs-simple-sec-before previous-overlay-change-pos)
1396                    (eq previous-overlay-change-pos 1)))
1397      (setq previous-overlay-change-pos
1398            (previous-overlay-change previous-overlay-change-pos)))
1399    previous-overlay-change-pos))
1400
1401(defun singular-emacs-simple-sec-end-at (pos)
1402  "Return end of clear simple section at position POS.
1403Assumes the existence of an imagenary empty clear simple section if POS is
1404at end of buffer and there is non-clear simple section immediately ending
1405at POS.
1406Assumes that no narrowing is in effect (since `next-overlay-change'
1407imlicitly does so)."
1408  (let ((next-overlay-change-pos (next-overlay-change pos)))
1409    ;; this `while' loop at last will run into the beginning of the next
1410    ;; non-clear simple section or stop at eob.  Since POS may not be at
1411    ;; the beginning of a non-clear simple section we may start searching
1412    ;; immediately.
1413    (while (not (or (singular-emacs-simple-sec-at next-overlay-change-pos)
1414                    (eq next-overlay-change-pos (point-max))))
1415      (setq next-overlay-change-pos
1416            (next-overlay-change next-overlay-change-pos)))
1417    next-overlay-change-pos))
1418
1419(defun singular-emacs-simple-sec-at (pos)
1420  "Return simple section at buffer position POS.
1421Assumes the existence of an imagenary empty clear simple section if POS is
1422at end of buffer and there is non-clear simple section immediately ending
1423at POS.
1424Narrowing has no effect on this function."
1425  ;; at eob, `overlays-at' always returns nil so everything is OK for this
1426  ;; case, too
1427  (let ((overlays (overlays-at pos)) simple-sec)
1428    ;; be careful, there may be other overlays!
1429    (while (and overlays (not simple-sec))
1430      (if (singular-emacs-simple-sec-type (car overlays))
1431          (setq simple-sec (car overlays)))
1432      (setq overlays (cdr overlays)))
1433    simple-sec))
1434
1435(defun singular-emacs-simple-sec-in (beg end)
1436  "Return a list of all simple sections intersecting with the region from BEG to END.
1437A simple section intersects the region if the section and the region have
1438at least one character in common.  The sections are returned with
1439startpoints in increasing order and clear simple sections (that is, nil's)
1440inserted as necessary.  BEG is assumed to be less than or equal to END.
1441The imagenary empty clear simple section at end of buffer is never included
1442in the result.
1443Narrowing has no effect on this function."
1444  (let (overlays overlay-cursor)
1445    (if (= beg end)
1446        ;; `overlays-in' seems not be correct with respect to this case
1447        nil
1448      ;; go to END since chances are good that the overlays come in correct
1449      ;; order, then
1450      (setq overlays (let ((old-point (point)))
1451                       (goto-char end)
1452                       (prog1 (overlays-in beg end)
1453                         (goto-char old-point)))
1454
1455      ;; now, turn overlays that are not simple sections into nils
1456            overlays (mapcar (function
1457                              (lambda (overlay)
1458                                (and (singular-emacs-simple-sec-type overlay)
1459                                     overlay)))
1460                             overlays)
1461      ;; then, remove nils from list
1462            overlays (delq nil overlays)
1463      ;; now, we have to sort the list since documentation of `overlays-in'
1464      ;; does not state anything about the order the overlays are returned in
1465            overlays
1466            (sort overlays
1467                  (function
1468                   (lambda (a b)
1469                     (< (overlay-start a) (overlay-start b))))))
1470
1471      ;; at last, we have the list of non-clear simple sections.  Now, go and
1472      ;; insert clear simple sections as necessary.
1473      (if (null overlays)
1474          ;; if there are no non-clear simple sections at all there can be
1475          ;; only one large clear simple section
1476          '(nil)
1477        ;; we care about inside clear simple section first
1478        (setq overlay-cursor overlays)
1479        (while (cdr overlay-cursor)
1480          (if (eq (overlay-end (car overlay-cursor))
1481                  (overlay-start (cadr overlay-cursor)))
1482              (setq overlay-cursor (cdr overlay-cursor))
1483            ;; insert nil
1484            (setcdr overlay-cursor
1485                    (cons nil (cdr overlay-cursor)))
1486            (setq overlay-cursor (cddr overlay-cursor))))
1487        ;; now, check BEG and END for clear simple sections
1488        (if (> (overlay-start (car overlays)) beg)
1489            (setq overlays (cons nil overlays)))
1490        ;; `overlay-cursor' still points to the end
1491        (if (< (overlay-end (car overlay-cursor)) end)
1492            (setcdr overlay-cursor (cons nil nil)))
1493        overlays))))
1494;;}}}
1495
1496;;{{{ Simple section API for XEmacs
1497(defsubst singular-xemacs-simple-sec-start (simple-sec)
1498  "Return start of non-clear simple section SIMPLE-SEC.
1499Narrowing has no effect on this function."
1500  (extent-start-position simple-sec))
1501
1502(defsubst singular-xemacs-simple-sec-end (simple-sec)
1503  "Return end of non-clear simple section SIMPLE-SEC.
1504Narrowing has no effect on this function."
1505  (extent-end-position simple-sec))
1506
1507(defsubst singular-xemacs-simple-sec-type (simple-sec)
1508  "Return type of SIMPLE-SEC.
1509Returns nil if SIMPLE-SEC happens to be an extent but not a simple
1510section.
1511Narrowing has no effect on this function."
1512  (if simple-sec
1513      (extent-property simple-sec 'singular-type)
1514    singular-simple-sec-clear-type))
1515
1516(defsubst singular-xemacs-simple-sec-before (pos)
1517  "Return simple section before buffer position POS.
1518This is the same as `singular-simple-sec-at' except if POS falls on a
1519section border.  In this case `singular-simple-section-before' returns the
1520previous simple section instead of the current one.  If POS falls on
1521beginning of buffer, the simple section at beginning of buffer is returned.
1522Narrowing has no effect on this function."
1523  (singular-xemacs-simple-sec-at (max 1 (1- pos))))
1524
1525(defun singular-xemacs-simple-sec-create (type end)
1526  "Create a new simple section of type TYPE.
1527Creates the section from end of previous simple section up to the first
1528beginning of line before END.  That position should be larger than or equal
1529to `singular-simple-sec-last-end'.  Updates `singular-simple-sec-last-end'.
1530Returns the new simple section or `empty' if no simple section has been
1531created.
1532Assumes that no narrowing is in effect."
1533  (let ((last-end (singular-simple-sec-last-end-position))
1534        ;; `simple-sec' is the new simple section or `empty'
1535        simple-sec)
1536
1537    ;; get beginning of line before END.  At this point we need that there
1538    ;; are no restrictions.
1539    (setq end (let ((old-point (point)))
1540                (goto-char end) (beginning-of-line)
1541                (prog1 (point) (goto-char old-point))))
1542
1543    (cond
1544     ;; do not create empty sections
1545     ((eq end last-end)
1546      'empty)
1547     ;; non-clear simple sections
1548     ((not (eq type singular-simple-sec-clear-type))
1549      ;; if type has not changed we only have to extend the previous simple
1550      ;; section.  If `last-end' happens to be 1 (meaning that we are
1551      ;; creating the first non-clear simple section in the buffer), then
1552      ;; `singular-simple-sec-before' returns nil,
1553      ;; `singular-simple-sec-type' returns the type of clear simple
1554      ;; sections that definitely does not equal TYPE, and a new simple
1555      ;; section is created as necessary.
1556      (setq simple-sec (singular-xemacs-simple-sec-before last-end))
1557      (if (eq type (singular-xemacs-simple-sec-type simple-sec))
1558          ;; move existing extent
1559          (setq simple-sec (set-extent-endpoints simple-sec 
1560                                                 (extent-start-position simple-sec) end))
1561        ;; create new extent
1562        (setq simple-sec (make-extent last-end end))
1563        ;; set type property
1564        (set-extent-property simple-sec 'singular-type type)
1565        ;; set face.  In contrast to Emacs, we do not need to set somethin
1566        ;; like `evaporate'.  `detachable' is set by XEmacs by default.
1567        (set-extent-property simple-sec 'face (singular-simple-sec-lookup-face type)))
1568      ;; update `singular-simple-sec-last-end' and return new simple
1569      ;; section
1570      (set-marker singular-simple-sec-last-end end)
1571      simple-sec)
1572     ;; clear simple sections
1573     (t
1574      ;; update `singular-simple-sec-last-end' and return nil
1575      (set-marker singular-simple-sec-last-end end)
1576      nil))))
1577
1578(defun singular-xemacs-simple-sec-start-at (pos)
1579  "Return start of clear simple section at position POS.
1580Assumes the existence of an imagenary empty clear simple section if POS is
1581at end of buffer and there is non-clear simple section immediately ending
1582at POS.
1583Assumes that no narrowing is in effect (since `previous-extent-change'
1584imlicitly does so)."
1585  ;; get into some hairy details at end of buffer.  Look if there is a
1586  ;; non-clear simple section immediately ending at end of buffer and
1587  ;; return the start of the imagenary empty clear simple section in that
1588  ;; case.  If buffer is empty this test fails since
1589  ;; `singular-xemacs-simple-sec-before' (corretly) returns nil.  But in
1590  ;; that case the following loop returns the correct result.
1591  (if (and (eq pos (point-max))
1592           (singular-xemacs-simple-sec-before pos))
1593      pos
1594    (let ((previous-extent-change-pos (min (1+ pos) (point-max))))
1595      ;; this `while' loop at last will run into the end of the next
1596      ;; non-clear simple section or stop at bob.  Since POS may be right at
1597      ;; the end of a previous non-clear location, we have to search at least
1598      ;; one time from POS+1 backwards.
1599      (while (not (or (singular-xemacs-simple-sec-before previous-extent-change-pos)
1600                      (eq previous-extent-change-pos 1)))
1601        (setq previous-extent-change-pos
1602              (previous-extent-change previous-extent-change-pos)))
1603      previous-extent-change-pos)))
1604
1605(defun singular-xemacs-simple-sec-end-at (pos)
1606  "Return end of clear simple section at position POS.
1607Assumes the existence of an imagenary empty clear simple section if POS is
1608at end of buffer and there is non-clear simple section immediately ending
1609at POS.
1610Assumes that no narrowing is in effect (since `next-extent-change'
1611imlicitly does so)."
1612  (let ((next-extent-change-pos (next-extent-change pos)))
1613    ;; this `while' loop at last will run into the beginning of the next
1614    ;; non-clear simple section or stop at eob.  Since POS may not be at
1615    ;; the beginning of a non-clear simple section we may start searching
1616    ;; immediately.
1617    (while (not (or (singular-xemacs-simple-sec-at next-extent-change-pos)
1618                    (eq next-extent-change-pos (point-max))))
1619      (setq next-extent-change-pos
1620            (next-extent-change next-extent-change-pos)))
1621    next-extent-change-pos))
1622
1623(defun singular-xemacs-simple-sec-at (pos)
1624  "Return simple section at buffer position POS.
1625Assumes the existence of an imagenary empty clear simple section if POS is
1626at end of buffer and there is non-clear simple section immediately ending
1627at POS.
1628Narrowing has no effect on this function."
1629  ;; at eob, `map-extent' always returns nil so everything is OK for this
1630  ;; case, too.  Do not try to use `extent-at' at this point.  `extent-at'
1631  ;; does not return extents outside narrowed text.
1632  (map-extents (function (lambda (ext args) ext))
1633               nil pos pos nil nil 'singular-type))
1634
1635(defun singular-xemacs-simple-sec-in (beg end)
1636  "Return a list of all simple sections intersecting with the region from BEG to END.
1637A simple section intersects the region if the section and the region have
1638at least one character in common.  The sections are returned with
1639startpoints in increasing order and clear simple sections (that is, nil's)
1640inserted as necessary.  BEG is assumed to be less than or equal to END.
1641The imagenary empty clear simple section at end of buffer is never included
1642in the result.
1643Narrowing has no effect on this function."
1644  (let (extents extent-cursor)
1645    (if (= beg end)
1646        ;; `mapcar-extents' may return some extents in this case, so
1647        ;; exclude it
1648        nil
1649      ;; OK, that's a little bit easier than for Emacs ...
1650      (setq extents (mapcar-extents 'identity nil nil beg end nil 'singular-type))
1651
1652      ;; now we have the list of non-clear simple sections.  Go and
1653      ;; insert clear simple sections as necessary.
1654      (if (null extents)
1655          ;; if there are no non-clear simple sections at all there can be
1656          ;; only one large clear simple section
1657          '(nil)
1658        ;; we care about inside clear simple section first
1659        (setq extent-cursor extents)
1660        (while (cdr extent-cursor)
1661          (if (eq (extent-end-position (car extent-cursor))
1662                  (extent-start-position (cadr extent-cursor)))
1663              (setq extent-cursor (cdr extent-cursor))
1664            ;; insert nil
1665            (setcdr extent-cursor
1666                    (cons nil (cdr extent-cursor)))
1667            (setq extent-cursor (cddr extent-cursor))))
1668        ;; now, check BEG and END for clear simple sections
1669        (if (> (extent-start-position (car extents)) beg)
1670            (setq extents (cons nil extents)))
1671        ;; `extent-cursor' still points to the end
1672        (if (< (extent-end-position (car extent-cursor)) end)
1673            (setcdr extent-cursor (cons nil nil)))
1674        extents))))
1675;;}}}
1676
1677;;{{{ Section API
1678
1679;; Note:
1680;;
1681;; Sections are built on simple sections.  Their purpose is to cover the
1682;; difference between clear and non-clear simple sections.
1683;;
1684;; - Sections consist of a simple section, its type, and its start and end
1685;;   points.  This is redundant information only in the case of non-clear
1686;;   simple section.
1687;; - Sections are read-only objects, neither are they modified nor are they
1688;;   created.
1689;; - Buffer narrowing does not restrict the extent of completely or
1690;;   partially inaccessible sections.  In contrast to simple sections the
1691;;   functions concerning sections do not assume that there is no narrowing
1692;;   in effect.  However, most functions provide an optional argument
1693;;   RESTRICTED that restricts the start and end point of the returned
1694;;   sections to the currently active restrictions.  Of course, that does
1695;;   not affect the range of the underlying simple sections, only the
1696;;   additional start and end points being returned.  One should note that
1697;;   by restricting sections one may get empty sections, that is, sections
1698;;   for which the additional start and end point are equal.
1699;; - In many cases it is not desirable that the user operates on sections
1700;;   which are not completely accessible.  To check that a section is
1701;;   completely accessible the `singular-section-check' function should be
1702;;   used.
1703;; - Sections are independent from implementation dependencies.  There are
1704;;   no different versions of the functions for Emacs and XEmacs.
1705;; - Whenever possible, one should not access simple section directly.
1706;;   Instead, one should use the section API.
1707
1708(defcustom singular-section-face-alist '((input . nil)
1709                                         (output . singular-section-output-face))
1710  "*Alist that maps section types to faces.
1711Should be a list consisting of elements (SECTION-TYPE . FACE-OR-NIL), where
1712SECTION-TYPE is either `input' or `output'.
1713
1714At any time, the Singular interactive mode buffer is completely covered by
1715sections of two different types: input sections and output sections.  This
1716variable determines which faces are used to display the different sections.
1717
1718If for type SECTION-TYPE the value FACE-OR-NIL is a face it is used to
1719display the contents of all sections of that particular type.
1720If instead FACE-OR-NIL equals nil sections of that type become so-called
1721clear sections.  The content of clear sections is displayed as regular
1722text, with no faces at all attached to them.
1723
1724Some notes and restrictions on this variable (believe them or not):
1725o Changing this variable during a Singular session may cause unexpected
1726  results (but not too serious ones, though).
1727o There may be only one clear section type defined at a time.
1728o Choosing clear input sections is a good idea.
1729o Choosing clear output sections is a bad idea.
1730o Consequence: Not to change this variable is a good idea."
1731  ;; to add new section types, simply extend the `list' widget.
1732  ;; The rest should work unchanged.  Do not forget to update docu.
1733  :type '(list (cons :tag "Input sections"
1734                     (const :format "" input)
1735                     (choice :format
1736"Choose either clear or non-clear input sections.  For non-clear sections,
1737select or modify a face (preferably `singular-section-input-face') used to
1738display the sections.
1739%[Choice%]
1740%v
1741"
1742                             (const :tag "Clear sections" nil)
1743                             (face :tag "Non-clear sections")))
1744               (cons :tag "Output sections"
1745                     (const :format "" output)
1746                     (choice :format
1747"Choose either clear or non-clear ouput sections.  For non-clear sections,
1748select or modify a face (preferably `singular-section-output-face') used to
1749display the sections.
1750%[Choice%]
1751%v
1752"
1753                             (const :tag "Clear sections" nil)
1754                             (face :tag "Non-clear sections"))))
1755  :initialize 'custom-initialize-reset
1756  ;; this function checks for validity (only one clear section
1757  ;; type) and sets `singular-simple-sec-clear-type' accordingly.
1758  ;; In case of an error, nothing is set or modified.
1759  :set (function (lambda (var value)
1760                   (let* ((cdrs-with-nils (mapcar 'cdr value))
1761                          (cdrs-without-nils (delq nil (copy-sequence cdrs-with-nils))))
1762                     (if (> (- (length cdrs-with-nils) (length cdrs-without-nils)) 1)
1763                         (error "Only one clear section type allowed (see `singular-section-face-alist')")
1764                       (set-default var value)
1765                       (setq singular-simple-sec-clear-type (car (rassq nil value)))))))
1766  :group 'singular-faces
1767  :group 'singular-sections-and-foldings)
1768
1769(defface singular-section-input-face '((t nil))
1770  "*Face to use for input sections.
1771It may be not sufficient to modify this face to change the appearance of
1772input sections.  See `singular-section-face-alist' for more information."
1773  :group 'singular-faces
1774  :group 'singular-sections-and-foldings)
1775
1776(defface singular-section-output-face '((t (:bold t)))
1777  "*Face to use for output sections.
1778It may be not sufficient to modify this face to change the appearance of
1779output sections.  See `singular-section-face-alist' for more information."
1780  :group 'singular-faces
1781  :group 'singular-sections-and-foldings)
1782
1783(defsubst singular-section-create (simple-sec type start end)
1784  "Create and return a new section."
1785  (vector simple-sec type start end))
1786
1787(defsubst singular-section-simple-sec (section)
1788  "Return underlying simple section of SECTION."
1789  (aref section 0))
1790
1791(defsubst singular-section-type (section)
1792  "Return type of SECTION."
1793  (aref section 1))
1794
1795(defsubst singular-section-start (section)
1796  "Return start of SECTION."
1797  (aref section 2))
1798
1799(defsubst singular-section-end (section)
1800  "Return end of SECTION."
1801  (aref section 3))
1802
1803(defun singular-section-at (pos &optional restricted)
1804  "Return section at position POS.
1805Returns section intersected with current restriction if RESTRICTED is
1806non-nil."
1807  (let* ((simple-sec (singular-simple-sec-at pos))
1808         (type (singular-simple-sec-type simple-sec))
1809         start end)
1810    (if simple-sec
1811        (setq start (singular-simple-sec-start simple-sec)
1812              end  (singular-simple-sec-end simple-sec))
1813      (save-restriction
1814        (widen)
1815        (setq start (singular-simple-sec-start-at pos)
1816              end (singular-simple-sec-end-at pos))))
1817    (cond
1818     ;; not restricted first
1819     ((not restricted)
1820      (singular-section-create simple-sec type start end))
1821     ;; restricted and degenerated
1822     ((and restricted
1823           (< end (point-min)))
1824      (singular-section-create simple-sec type (point-min) (point-min)))
1825     ;; restricted and degenerated
1826     ((and restricted
1827           (> start (point-max)))
1828      (singular-section-create simple-sec type (point-max) (point-max)))
1829     ;; restricted but not degenrated
1830     (t
1831      (singular-section-create simple-sec type
1832                               (max start (point-min))
1833                               (min end (point-max)))))))
1834
1835(defun singular-section-before (pos &optional restricted)
1836  "Return section before position POS.
1837This is the same as `singular-section-at' except if POS falls on a section
1838border.  In this case `singular-section-before' returns the previous
1839section instead of the current one.  If POS falls on beginning of buffer,
1840the section at beginning of buffer is returned.
1841Returns section intersected with current restriction if RESTRICTED is
1842non-nil."
1843  (singular-section-at (max 1 (1- pos)) restricted))
1844
1845(defun singular-section-in (beg end &optional restricted)
1846  "Return a list of all sections intersecting with the region from BEG to END.
1847A section intersects with the region if the section and the region have at
1848least one character in common.  The sections are returned in increasing
1849order.
1850If optional argument RESTRICTED is non-nil only sections which are
1851completely in the intersection of the region and the current restriction
1852are returned."
1853  ;; exchange BEG and END if necessary as a special service to our users
1854  (let* ((reg-beg (min beg end))
1855         (reg-end (max beg end))
1856         ;; we need these since we widen the buffer later on
1857         (point-min (point-min))
1858         (point-max (point-max))
1859         simple-sections)
1860    (if (and restricted
1861             (or (> reg-beg point-max) (< reg-end point-min)))
1862        ;; degenerate restrictions
1863        nil
1864      ;; do the intersection if necessary and get simple sections
1865      (setq reg-beg (if restricted (max reg-beg point-min) reg-beg)
1866            reg-end (if restricted (min reg-end point-max) reg-end)
1867            simple-sections (singular-simple-sec-in reg-beg reg-end))
1868      ;; we still have REG-BEG <= REG-END in any case.  SIMPLE-SECTIONS
1869      ;; contains the list of simple sections intersecting with the region
1870      ;; from REG-BEG and REG-END.
1871
1872      (if (null simple-sections)
1873          nil
1874        ;; and here we even have REG-BEG < REG-END
1875        (save-restriction
1876          (widen)
1877          ;; get sections intersecting with the region from REG-BEG to
1878          ;; REG-END
1879          (let* ((sections (singular-section-in-internal simple-sections
1880                                                         reg-beg reg-end))
1881                 first-section-start last-section-end)
1882            (if (not restricted)
1883                sections
1884              (setq first-section-start (singular-section-start (car sections))
1885                    last-section-end (singular-section-end (car (last sections))))
1886              ;; popping off first element is easy ...
1887              (if (< first-section-start point-min)
1888                  (setq sections (cdr sections)))
1889              ;; ... but last element is harder to pop off
1890              (cond
1891               (;; no elements left
1892                (null sections)
1893                nil)
1894               (;; one element left
1895                (null (cdr sections))
1896                (if (> last-section-end point-max)
1897                    nil
1898                  sections))
1899               (;; more than one element left
1900                t
1901                (if (> last-section-end point-max)
1902                    (setcdr (last sections 2) nil))
1903                sections)))))))))
1904
1905(defun singular-section-in-internal (simple-sections reg-beg reg-end)
1906  "Create a list of sections from SIMPLE-SECTIONS.
1907This is the back-end for `singular-section-in'.
1908First simple section should be such that it contains REG-BEG, last simple
1909section should be such that it contains or ends at REG-END.  These
1910arguments are used to find the start resp. end of clear simple sections of
1911terminal clear simple sections in SIMPLE-SECTIONS.
1912Assumes that REG-BEG < REG-END.
1913Assumes that SIMPLE-SECTIONS is not empty.
1914Assumes that no narrowing is in effect."
1915  (let* (;; we pop off the extra nil at the end of the loop
1916         (sections (cons nil nil))
1917         (sections-end sections)
1918         (simple-section (car simple-sections))
1919         type start end)
1920
1921    ;; first, get unrestricted start
1922    (setq start (if simple-section
1923                    (singular-simple-sec-start simple-section)
1924                  ;; here we need that no narrowing is in effect
1925                  (singular-simple-sec-start-at reg-beg)))
1926
1927    ;; loop through all simple sections but last
1928    (while (cdr simple-sections)
1929      (setq simple-section (car simple-sections)
1930            type (singular-simple-sec-type simple-section)
1931            end (if simple-section
1932                    (singular-simple-sec-end simple-section)
1933                  (singular-simple-sec-start (cadr simple-sections)))
1934
1935            ;; append the new section to `sections-end'
1936            sections-end
1937            (setcdr sections-end
1938                    (cons (singular-section-create simple-section type start end) nil))
1939
1940            ;; get next simple section and its start
1941            simple-sections (cdr simple-sections)
1942            start end))
1943
1944    ;; care about last simple section
1945    (setq simple-section (car simple-sections)
1946          type (singular-simple-sec-type simple-section)
1947          end (if simple-section
1948                  (singular-simple-sec-end simple-section)
1949                ;; the `1-' is OK since REG-BEG < REG-END.
1950                ;; here we need that no narrowing is in effect
1951                (singular-simple-sec-end-at (1- reg-end))))
1952    (setcdr sections-end
1953            (cons (singular-section-create simple-section type start end) nil))
1954
1955    ;; we should not forget to pop off our auxilliary cons-cell
1956    (cdr sections)))
1957
1958(defun singular-section-mapsection (func sections &optional type-filter negate-filter)
1959  "Apply FUNC to each section in SECTIONS, and make a list of the results.
1960If optional argument TYPE-FILTER is non-nil it should be a list of section
1961types.  FUNC is then applied only to those sections with type occuring in
1962TYPE-FILTER.  If in addition optional argument NEGATE-FILTER is non-nil
1963FUNC is applied only to those sections with type not occuring in
1964TYPE-FILTER.
1965
1966In any case the length of the list this function returns equals the
1967number of sections actually processed."
1968  (if (not type-filter)
1969      (mapcar func sections)
1970    ;; copy the list first
1971    (let ((sections (copy-sequence sections)))
1972      ;; filter elements and turn them to t's
1973      (setq sections
1974            (mapcar (function
1975                     (lambda (section)
1976                       ;; that strange expression evaluates to t iff the
1977                       ;; section should be removed.  The `not' is to
1978                       ;; canonize boolean values to t or nil, resp.
1979                       (or (eq (not (memq (singular-section-type section) type-filter))
1980                               (not negate-filter))
1981                           section)))
1982                    sections)
1983
1984      ;; remove t's now
1985            sections (delq t sections))
1986
1987      ;; call function for remaining sections
1988      (mapcar func sections))))
1989;;}}}
1990
1991;;{{{ Section miscellaneous
1992(defun singular-section-check (section &optional no-error)
1993  "Check whether SECTION is completely accessible and return t if so.
1994If otherwise SECTION is restricted either in part or as a whole, this
1995function fails with an error or returns nil if optional argument NO-ERROR
1996is non-nil."
1997  (cond ((and (>= (singular-section-start section) (point-min))
1998              (<= (singular-section-end section) (point-max))) t)
1999        (no-error nil)
2000        (t (error "section is restricted either in part or as a whole"))))
2001
2002(defun singular-section-to-string (section &optional raw)
2003  "Get contents of SECTION as a string.
2004Returns text between start and end of SECTION.
2005Removes prompts from section contents unless optional argument RAW is
2006non-nil.
2007Narrowing has no effect on this function."
2008  (save-restriction
2009    (widen)
2010    (let ((string (buffer-substring (singular-section-start section)
2011                                    (singular-section-end section))))
2012      (if raw
2013          string
2014        (singular-prompt-remove-string string)))))
2015;;}}}
2016
2017;;{{{ Section miscellaneous interactive
2018(defun singular-section-goto-beginning ()
2019  "Move point to beginning of current section."
2020  (interactive)
2021  (goto-char (singular-section-start (singular-section-at (point))))
2022  (singular-keep-region-active))
2023
2024(defun singular-section-goto-end ()
2025  "Move point to end of current section."
2026  (interactive)
2027  (goto-char (singular-section-end (singular-section-at (point))))
2028  (singular-keep-region-active))
2029
2030(defun singular-section-backward (n)
2031  "Move backward until encountering the beginning of a section.
2032With argument, do this that many times.  With N less than zero, call
2033`singular-section-forward' with argument -N."
2034  (interactive "p")
2035  (while (> n 0)
2036    (goto-char (singular-section-start (singular-section-before (point))))
2037    (setq n (1- n)))
2038  (if (< n 0)
2039      (singular-section-forward (- n))
2040    (singular-keep-region-active)))
2041
2042(defun singular-section-forward (n)
2043  "Move forward until encountering the end of a section.
2044With argument, do this that many times.  With N less than zero, call
2045`singular-section-backward' with argument -N."
2046  (interactive "p")
2047  (while (> n 0)
2048    (goto-char (singular-section-end (singular-section-at (point))))
2049    (setq n (1- n)))
2050  (if (< n 0)
2051      (singular-section-backward (- n))
2052    (singular-keep-region-active)))
2053
2054(defun singular-section-kill (section &optional raw no-error)
2055  "Kill SECTION.
2056Puts the contents of SECTION into the kill ring.  Removes prompts from
2057contents unless optional argument RAW is non-nil.
2058If called interactively, kills section point currently is in.  Does a raw
2059section kill if called with a prefix argument, otherwise strips prompts.
2060Does not kill sections that are restricted either in part or as a whole.
2061Rather fails with an error in such cases or silently fails if optional
2062argument NO-ERROR is non-nil."
2063  (interactive (list (singular-section-at (point))
2064                     current-prefix-arg nil))
2065  (when (singular-section-check section no-error)
2066    (kill-new (singular-section-to-string section raw))
2067    (delete-region (singular-section-start section)
2068                   (singular-section-end section))))
2069;;}}}
2070
2071;;{{{ Folding sections for both Emacs and XEmacs
2072(defcustom singular-folding-ellipsis "Singular I/O ..."
2073  "*Ellipsis to show for folded input or output.
2074Changing this variable has an immediate effect only if one uses
2075\\[customize] to do so.
2076However, even then it may be necessary to refresh display completely (using
2077\\[recenter], for example) for the new settings to be visible."
2078  :type 'string
2079  :initialize 'custom-initialize-default
2080  :set (function
2081        (lambda (var value)
2082          ;; set in all singular buffers
2083          (singular-map-buffer 'singular-folding-set-ellipsis value)
2084          (set-default var value)))
2085  :group 'singular-sections-and-foldings)
2086
2087(defcustom singular-folding-line-move-ignore-folding t
2088  "*If non-nil, ignore folded sections when moving point up or down.
2089This variable is used to initialize `line-move-ignore-invisible'.  However,
2090documentation states that setting `line-move-ignore-invisible' to a non-nil
2091value may result in a slow-down when moving the point up or down.  One
2092should try to set this variable to nil if point motion seems too slow.
2093
2094Changing this variable has an immediate effect only if one uses
2095\\[customize] to do so."
2096  :type 'boolean
2097  :initialize 'custom-initialize-default
2098  :set (function
2099        (lambda (var value)
2100          ;; set in all singular buffers
2101          (singular-map-buffer 'set 'line-move-ignore-invisible value)
2102          (set-default var value)))
2103  :group 'singular-sections-and-foldings)
2104
2105(defun singular-folding-set-ellipsis (ellipsis)
2106  "Set ellipsis to show for folded input or output in current buffer."
2107  (cond
2108   ;; Emacs
2109   ((eq singular-emacs-flavor 'emacs)
2110    (setq buffer-display-table (or (copy-sequence standard-display-table)
2111                                   (make-display-table)))
2112    (set-display-table-slot buffer-display-table
2113                            'selective-display (vconcat ellipsis)))
2114   ;; XEmacs
2115   (t
2116    (set-glyph-image invisible-text-glyph ellipsis (current-buffer)))))
2117
2118(defun singular-folding-init ()
2119  "Initializes folding of sections for the current buffer.
2120That includes setting `buffer-invisibility-spec' and the ellipsis to show
2121for hidden text.
2122
2123This function is called at mode initialization time."
2124  ;; initialize `buffer-invisibility-spec' first
2125  (let ((singular-invisibility-spec (cons 'singular-interactive-mode t)))
2126    (if (and (listp buffer-invisibility-spec)
2127             (not (member singular-invisibility-spec buffer-invisibility-spec)))
2128        (setq buffer-invisibility-spec
2129              (cons singular-invisibility-spec buffer-invisibility-spec))
2130      (setq buffer-invisibility-spec (list singular-invisibility-spec))))
2131  ;; ignore invisible lines on movements
2132  (set (make-local-variable 'line-move-ignore-invisible)
2133       singular-folding-line-move-ignore-folding)
2134  ;; now for the ellipsis
2135  (singular-folding-set-ellipsis singular-folding-ellipsis))
2136
2137(defun singular-folding-fold (section &optional no-error)
2138  "Fold section SECTION if it is not already folded.
2139Does not fold sections that do not end in a newline or that are restricted
2140either in part or as a whole.  Rather fails with an error in such cases
2141or silently fails if optional argument NO-ERROR is non-nil.
2142This is for safety only: In both cases the result may be confusing to the
2143user."
2144  (let* ((start (singular-section-start section))
2145         (end (singular-section-end section)))
2146    (cond ((not (singular-section-check section no-error))
2147           nil)
2148          ((not (eq (char-before end) ?\n))
2149           (unless no-error
2150             (error "Section does not end in a newline")))
2151          ((not (singular-folding-foldedp section))
2152           ;; fold but only if not already folded
2153           (singular-folding-fold-internal section)))))
2154
2155(defun singular-folding-unfold (section &optional no-error invisibility-overlay-or-extent)
2156  "Unfold section SECTION if it is not already unfolded.
2157Does not unfold sections that are restricted either in part or as a whole.
2158Rather fails with an error in such cases or silently fails if optional
2159argument NO-ERROR is non-nil.
2160This is for safety only: The result may be confusing to the user.
2161If optional argument INVISIBILITY-OVERLAY-OR-EXTENT is non-nil it should be
2162the invisibility overlay or extent, respectively, of the section to
2163unfold."
2164  (let* ((start (singular-section-start section))
2165         (end (singular-section-end section)))
2166    (cond ((not (singular-section-check section no-error))
2167           nil)
2168          ((or invisibility-overlay-or-extent
2169               (setq invisibility-overlay-or-extent (singular-folding-foldedp section)))
2170           ;; unfold but only if not already unfolded
2171           (singular-folding-unfold-internal section invisibility-overlay-or-extent)))))
2172
2173(defun singular-folding-fold-at-point ()
2174  "Fold section point currently is in.
2175Does not fold sections that do not end in a newline or that are restricted
2176either in part or as a whole.  Rather fails with an error in such cases."
2177  (interactive)
2178  (singular-folding-fold (singular-section-at (point))))
2179
2180(defun singular-folding-unfold-at-point ()
2181  "Unfold section point currently is in.
2182Does not unfold sections that are restricted either in part or as a whole.
2183Rather fails with an error in such cases."
2184  (interactive)
2185  (singular-folding-unfold (singular-section-at (point))))
2186
2187(defun singular-folding-fold-latest-output ()
2188  "Fold latest output section.
2189Does not fold sections that do not end in a newline or that are restricted
2190either in part or as a whole.  Rather fails with an error in such cases."
2191  (interactive)
2192  (singular-folding-fold (singular-latest-output-section)))
2193
2194(defun singular-folding-unfold-latest-output ()
2195  "Unfolds latest output section.
2196Does not unfold sections that are restricted either in part or as a whole.
2197Rather fails with an error in such cases."
2198  (interactive)
2199  (singular-folding-unfold (singular-latest-output-section)))
2200
2201(defun singular-folding-fold-all-output ()
2202  "Fold all complete, unfolded output sections.
2203That is, all output sections that are not restricted in part or as a whole
2204and that end in a newline."
2205  (interactive)
2206  (singular-section-mapsection (function (lambda (section) (singular-folding-fold section t)))
2207                               (singular-section-in (point-min) (point-max) t)
2208                               '(output)))
2209
2210(defun singular-folding-unfold-all-output ()
2211  "Unfold all complete, folded output sections.
2212That is, all output sections that are not restricted in part or as a whole."
2213  (interactive)
2214  (singular-section-mapsection (function (lambda (section) (singular-folding-unfold section t)))
2215                               (singular-section-in (point-min) (point-max) t)
2216                               '(output)))
2217
2218(defun singular-folding-toggle-fold-at-point-or-all (&optional arg)
2219  "Fold or unfold section point currently is in or all output sections.
2220Without prefix argument, folds unfolded sections and unfolds folded
2221sections.  With prefix argument, folds all output sections if argument is
2222positive, otherwise unfolds all output sections.
2223Does neither fold nor unfold sections that do not end in a newline or that
2224are restricted either in part or as a whole.  Rather fails with an error in
2225such cases."
2226  (interactive "P")
2227    (cond ((not arg)
2228           ;; fold or unfold section at point
2229           (let* ((section (singular-section-at (point)))
2230                  (invisibility-overlay-or-extent (singular-folding-foldedp section)))
2231             (if invisibility-overlay-or-extent
2232                 (singular-folding-unfold section nil invisibility-overlay-or-extent)
2233               (singular-folding-fold section))))
2234          ((> (prefix-numeric-value arg) 0)
2235           (singular-folding-fold-all-output))
2236          (t
2237           (singular-folding-unfold-all-output))))
2238
2239(defun singular-folding-toggle-fold-latest-output (&optional arg)
2240  "Fold or unfold latest output section.
2241Folds unfolded sections and unfolds folded sections.
2242Does neither fold nor unfold sections that do not end in a newline or that
2243are restricted either in part or as a whole.  Rather fails with an error in
2244such cases."
2245  (interactive)
2246  (let* ((section (singular-latest-output-section))
2247         (invisibility-overlay-or-extent (singular-folding-foldedp section)))
2248    (if invisibility-overlay-or-extent
2249        (singular-folding-unfold section nil invisibility-overlay-or-extent)
2250      (singular-folding-fold section))))
2251
2252;; Note:
2253;;
2254;; The rest of the folding is either marked as
2255;; Emacs
2256;; or
2257;; XEmacs
2258
2259(singular-fset 'singular-folding-fold-internal
2260               'singular-emacs-folding-fold-internal
2261               'singular-xemacs-folding-fold-internal)
2262
2263(singular-fset 'singular-folding-unfold-internal
2264               'singular-emacs-folding-unfold-internal
2265               'singular-xemacs-folding-unfold-internal)
2266
2267(singular-fset 'singular-folding-foldedp
2268               'singular-emacs-folding-foldedp-internal
2269               'singular-xemacs-folding-foldedp-internal)
2270;;}}}
2271
2272;;{{{ Folding sections for Emacs
2273
2274;; Note:
2275;;
2276;; For Emacs, we use overlays to hide text (so-called "invisibility
2277;; overlays").  In addition to their `invisible' property, they have the
2278;; `singular-invisible' property set.  Setting the intangible property does
2279;; not work very well for Emacs.  We use the variable
2280;; `line-move-ignore-invisible' which works quite well.
2281
2282(defun singular-emacs-folding-fold-internal (section)
2283  "Fold section SECTION.
2284SECTION should end in a newline.  That terminal newline is not
2285folded or otherwise ellipsis does not appear.
2286SECTION should be unfolded."
2287  (let* ((start (singular-section-start section))
2288         ;; do not make trailing newline invisible
2289         (end (1- (singular-section-end section)))
2290         invisibility-overlay)
2291    ;; create new overlay and add properties
2292    (setq invisibility-overlay (make-overlay start end))
2293    ;; mark them as invisibility overlays
2294    (overlay-put invisibility-overlay 'singular-invisible t)
2295    ;; set invisible properties
2296    (overlay-put invisibility-overlay 'invisible 'singular-interactive-mode)
2297    ;; evaporate empty invisibility overlays
2298    (overlay-put invisibility-overlay 'evaporate t)))
2299
2300(defun singular-emacs-folding-unfold-internal (section &optional invisibility-overlay)
2301  "Unfold section SECTION.
2302SECTION should be folded.
2303If optional argument INVISIBILITY-OVERLAY is non-nil it should be the
2304invisibility overlay of the section to unfold."
2305  (let ((invisibility-overlay
2306         (or invisibility-overlay
2307             (singular-emacs-folding-foldedp-internal section))))
2308    ;; to keep number of overlays low we delete it
2309    (delete-overlay invisibility-overlay)))
2310
2311(defun singular-emacs-folding-foldedp-internal (section)
2312  "Returns non-nil iff SECTION is folded.
2313More specifically, returns the invisibility overlay if there is one.
2314Narrowing has no effect on this function."
2315  (let* ((start (singular-section-start section))
2316         (overlays (overlays-at start))
2317         invisibility-overlay)
2318    ;; check for invisibility overlay
2319    (while (and overlays (not invisibility-overlay))
2320      (if (overlay-get (car overlays) 'singular-invisible)
2321          (setq invisibility-overlay (car overlays))
2322        (setq overlays (cdr overlays))))
2323    invisibility-overlay))
2324;;}}}
2325
2326;;{{{ Folding sections for XEmacs
2327
2328;; Note:
2329;;
2330;; For XEmacs, we use extents to hide text (so-called "invisibility
2331;; extents").  In addition to their `invisible' property, they have the
2332;; `singular-invisible' property set.  To ignore invisible text we use the
2333;; variable `line-move-ignore-invisible' which works quite well.
2334
2335(defun singular-xemacs-folding-fold-internal (section)
2336  "Fold section SECTION.
2337SECTION should end in a newline.  That terminal newline is not
2338folded or otherwise ellipsis does not appear.
2339SECTION should be unfolded."
2340  (let* ((start (singular-section-start section))
2341         ;; do not make trailing newline invisible
2342         (end (1- (singular-section-end section)))
2343         invisibility-extent)
2344    ;; create new extent and add properties
2345    (setq invisibility-extent (make-extent start end))
2346    ;; mark them as invisibility extents
2347    (set-extent-property invisibility-extent 'singular-invisible t)
2348    ;; set invisible properties
2349    (set-extent-property invisibility-extent 'invisible 'singular-interactive-mode)))
2350
2351(defun singular-xemacs-folding-unfold-internal (section &optional invisibility-extent)
2352  "Unfold section SECTION.
2353SECTION should be folded.
2354If optional argument INVISIBILITY-EXTENT is non-nil it should be the
2355invisibility extent of the section to unfold."
2356  (let ((invisibility-extent
2357         (or invisibility-extent
2358             (singular-xemacs-folding-foldedp-internal section))))
2359    ;; to keep number of extents low we delete it
2360    (delete-extent invisibility-extent)))
2361
2362(defun singular-xemacs-folding-foldedp-internal (section)
2363  "Returns non-nil iff SECTION is folded.
2364More specifically, returns the invisibility extent if there is one.
2365Narrowing has no effect on this function."
2366  ;; do not try to use `extent-at' at this point.  `extent-at' does not
2367  ;; return extents outside narrowed text.
2368  (let* ((start (singular-section-start section))
2369         (invisibility-extent (map-extents
2370                            (function (lambda (ext args) ext))
2371                            nil start start nil nil 'singular-invisible)))
2372    invisibility-extent))
2373;;}}}
2374
2375;;{{{ Online help
2376
2377;; Note:
2378;;
2379;; Catching user's help commands to Singular and translating them to calls
2380;; to `info' is quite a difficult task due to the asynchronous nature of
2381;; communication with Singular.  We use an heuristic approach which should
2382;; work in most cases:
2383;;
2384;; - `singular-help-pre-input-filter' scans user's input for help commands.
2385;;   If user issues a help command the filter sets a time stamp and passes
2386;;   the input unchanged to Singular.
2387;; - Singular receives the help command and barfs that it could not process
2388;;   it.  We call that error message "Singular's response".  That response
2389;;   in particular contains the help topic the user requested.  If the
2390;;   response for some reasons is not recognized and filtered in the later
2391;;   steps the user gets some reasonable response on her command that way.
2392;; - `singular-help-pre-output-filter' on each output from Singular checks
2393;;   (using the time stamp set by `singular-help-pre-input-filter') whether
2394;;   the user issued a help command at most one second ago.  If so,
2395;;   `singular-help-pre-output-filter' starts checking Singular's output
2396;;   for the response on the help command.  If it finds one it remembers
2397;;   the help topic in `singular-help-topic' and removes the response from
2398;;   Singular's output.
2399;;   There is some extra magic built into the filter to handle responses
2400;;   from Singular which are received by emacs not in one string but in
2401;;   more than one piece (we call that pending output).
2402;; - As the last step step of this procedure, `singular-post-output-filter'
2403;;   fires up an Info buffer using `singular-help' if the variable
2404;;   `singular-help-topic' is non-nil.  This step is separated from the
2405;;   previous one since joining both leads to some trouble in point
2406;;   management.  This is mainly due to the fact that `singular-help' opens
2407;;   a new window.
2408;;
2409;; To show some online help, the online help manual has to be available, of
2410;; course.  There is a number of possibilites for the user to set the file
2411;; name of the manual explicitly, as described in the documentation string
2412;; to `singular-help'.  But in general the file name should be recognized
2413;; automatically by Singular interactive mode.  For that to work, Singular
2414;; prints the file name when it comes up and option `--emacs' is specified.
2415;; This is recognized by `singular-scan-header-pre-output-filter' which
2416;; sets the variable `singular-help-file-name' accordingly.  For more
2417;; information one should refer to the `Header scanning ...' folding.
2418;;
2419;; Another variable which needs to be set for proper operation is
2420;; `singular-help-topics-alist' for completion of help topics and for
2421;; recognition of help topics around point.  It is no error for this
2422;; variable not to be set: simply the features do not work then.
2423
2424;; this `require' is necessary since we use functions from the Info package
2425;; which are not declared as `autoload'
2426(require 'info)
2427
2428(defcustom singular-help-same-window 'default
2429  "*Specifies how to open the window for Singular online help.
2430If this variable equals t, Singular online help comes up in the selected
2431window.
2432If this variable equals nil, Singular online help comes up in another
2433window.
2434If this variable equals neither t nor nil, the standard Emacs behaviour to
2435open the Info buffer is adopted (which very much depends on the settings of
2436`same-window-buffer-names')."
2437  :initialize 'custom-initialize-default
2438  :type '(choice (const :tag "This window" t)
2439                 (const :tag "Other window" nil)
2440                 (const :tag "Default" default))
2441  :group 'singular-interactive-miscellaneous)
2442
2443(defcustom singular-help-explicit-file-name nil
2444  "*Specifies the file name of the Singular online manual.
2445If non-nil, used as file name of the Singular online manual.
2446
2447This variable should be customized only if all other attempts of Singular
2448interactive mode fail to determine the file name of the Singular online
2449manual.  For more information one should refer to the `singular-help'
2450function."
2451  :initialize 'custom-initialize-default
2452  :type '(choice (const nil) file)
2453  :group 'singular-interactive-miscellaneous)
2454
2455(defvar singular-help-file-name nil
2456  "File name of the Singular online manual.
2457This variable should not be modified by the user.
2458
2459This variable is buffer-local.")
2460
2461(defconst singular-help-fall-back-file-name "singular.hlp"
2462  "Fall-back file name of the Singular online manual.
2463This variable is used if the file name of the Singular online manual cannot
2464be determined otherwise.")
2465
2466(defvar singular-help-time-stamp '(0 0)
2467  "The time stamp that is set when the user issues a help command.
2468
2469This variable is buffer-local.")
2470
2471(defvar singular-help-response-pending nil
2472  "If non-nil, Singular's response has not been completely received.
2473
2474This variable is buffer-local.")
2475
2476(defvar singular-help-topic nil
2477  "If non-nil, contains help topic to show in post output filter.
2478
2479This variable is buffer-local.")
2480
2481(defconst singular-help-command-regexp "^\\s-*\\(help\\|\?\\)"
2482  "Regular expression to match Singular help commands.")
2483
2484(defconst singular-help-response-line-1
2485  "^// \\*\\* Your help command could not be executed\\. Use\n"
2486  "Regular expression that matches the first line of Singular's response.")
2487
2488(defconst singular-help-response-line-2
2489  "^// \\*\\* C-h C-s \\(.*\\)\n"
2490  "Regular expression that matches the second line of Singular's response.
2491First subexpression matches help topic.")
2492
2493(defconst singular-help-response-line-3
2494  "^// \\*\\* to enter the Singular online help\\. For general\n"
2495  "Regular expression that matches the third line of Singular's response.")
2496
2497(defconst singular-help-response-line-4
2498  "^// \\*\\* information on Singular running under Emacs, type C-h m\\.\n"
2499  "Regular expression that matches the fourth line of Singular's response.")
2500
2501(defun singular-help-pre-input-filter (input)
2502  "Check user's input for help commands.
2503Sets time stamp if one is found.  Passes user's input on to Singular
2504unchanged."
2505  (if (string-match singular-help-command-regexp input)
2506      (setq singular-help-time-stamp (current-time)))
2507  ;; return nil so that input passes unchanged
2508  nil)
2509
2510(defun singular-help-pre-output-filter (output)
2511  "Check for Singular's response on a help command.
2512Removes it and sets `singular-help-topic' accordingly."
2513  ;; check first
2514  ;; - whether a help statement has been issued at most one second ago, or
2515  ;; - whether there is a pending response.
2516  ;; Only if one of these conditions is met we go on and check text for a
2517  ;; response on a help command.  Checking uncoditionally every piece of
2518  ;; output would be far too expensive.
2519  ;; If check fails nil is returned, what is exactly what we need for the
2520  ;; filter.
2521  (if (or (= (cadr (current-time)) (cadr singular-help-time-stamp))
2522          singular-help-response-pending)
2523      ;; if response is pending for more than five seconds, give up
2524      (if (and singular-help-response-pending
2525               (> (singular-time-stamp-difference (current-time) singular-help-time-stamp) 5))
2526          ;; this command returns nil, what is exactly what we need for the filter
2527          (setq singular-help-response-pending nil)
2528        ;; go through output, removing the response.  If there is a
2529        ;; pending response we nevertheless check for all lines, not only
2530        ;; for the pending one.  At last, pending responses should not
2531        ;; occur to often.
2532        (when (string-match singular-help-response-line-1 output)
2533          (setq output (replace-match "" t t output))
2534          (setq singular-help-response-pending t))
2535        (when (string-match singular-help-response-line-2 output)
2536          ;; after all, we found what we are looking for
2537          (setq singular-help-topic (substring output (match-beginning 1) (match-end 1)))
2538          (setq output (replace-match "" t t output))
2539          (setq singular-help-response-pending t))
2540        (when (string-match singular-help-response-line-3 output)
2541          (setq output (replace-match "" t t output))
2542          (setq singular-help-response-pending t))
2543        (when (string-match singular-help-response-line-4 output)
2544          (setq output (replace-match "" t t output))
2545          ;; we completely removed the help from output!
2546          (setq singular-help-response-pending nil))
2547
2548        ;; return modified OUTPUT
2549        output)))
2550
2551(defun singular-help-post-output-filter (&rest ignore)
2552  "Call `singular-help' if `singular-help-topic' is non-nil."
2553  (when singular-help-topic
2554    (save-excursion 
2555      (singular-help singular-help-topic))
2556    (setq singular-help-topic nil)))
2557
2558(defvar singular-help-topic-history nil
2559  "History of help topics used as arguments to `singular-help'.")
2560
2561(defun singular-help (&optional help-topic)
2562  "Show help on HELP-TOPIC in Singular online manual.
2563
2564The file name of the Singular online manual is determined in the following
2565manner:
2566o if the \(customizable) variable `singular-help-explicit-file-name' is
2567  non-nil, it is used as file name;
2568o otherwise, if the variable `singular-help-file-name' is non-nil, is is
2569  used as file name.  This variable should be set by Singular interactive
2570  mode itself, but there may be instances where this fails.  Anyway, it
2571  should be not set by the user.
2572o otherwise, if the environment variable SINGULAR_INFO_FILE is set, it is
2573  used as file name;
2574o otherwise, the constant `singular-help-fall-back-file-name' is used
2575  as file name."
2576  (interactive
2577   (list (completing-read "Help topic: " singular-help-topics-alist
2578                          nil nil nil 'singular-help-topic-history)))
2579
2580  ;; get help file and topic
2581  (let ((help-file-name (or singular-help-explicit-file-name
2582                            singular-help-file-name
2583                            (getenv "SINGULAR_INFO_FILE")
2584                            singular-help-fall-back-file-name))
2585        (help-topic (cond ((or (null help-topic)
2586                               (string= help-topic ""))
2587                           "Top")
2588                          ;; try to get the real topic from the alist.
2589                          ;; It's OK if the alist is empty.
2590                          ((cdr (assoc help-topic
2591                                       singular-help-topics-alist)))
2592                          (t help-topic)))
2593        (continue t))
2594
2595    ;; pop to Info buffer
2596    (singular-pop-to-buffer singular-help-same-window "*info*")
2597
2598    ;; test whether we are already in Singular's online manual
2599    (unless (and (boundp 'Info-current-file)
2600                 (equal Info-current-file help-file-name))
2601      ;; jump to Singular's top node
2602      (condition-case signal
2603          (Info-find-node help-file-name "Top")
2604        ;; in case of an error jump to info directory
2605        (error
2606         (Info-directory)
2607         ;; if we have been called interactively we pass the error down,
2608         ;; otherwise we assumes that we have been called from a hook and
2609         ;; call `singular-error'
2610         (if (interactive-p)
2611             (signal (car signal) (cdr signal))
2612           (singular-error "Singular online manual %s not found"
2613                           help-file-name))
2614         ;; do not continue
2615         (setq continue nil))))
2616
2617    (when continue
2618      ;; jump to desired node
2619      (condition-case signal
2620          (Info-goto-node help-topic)
2621        ;; in case of an error jump to Singular's top node
2622        (error
2623         (Info-goto-node "Top")
2624         ;; if we have been called interactively we pass the error down,
2625         ;; otherwise we assumes that we have been called from a hook and
2626         ;; call `singular-error'
2627         (if (interactive-p)
2628             (signal (car signal) (cdr signal))
2629           (singular-error "Singular help topic %s not found"
2630                           help-topic)))))))
2631
2632;; This might not be the best place for singular-example, but this function
2633;; is some kind of singular help, so the place is not too bad.
2634;; Note: We use singular-help-topic-history for singular-example, too
2635(defun singular-example (&optional command)
2636  "Show Singular example on COMMAND."
2637  (interactive 
2638   (list (completing-read "Example for: " singular-examples-alist
2639                          nil nil nil 'singular-help-topic-history)))
2640  (let ((process (singular-process))
2641        (string (concat "example " command ";")))
2642    (singular-input-filter process string)
2643    (singular-send-string process string)))
2644
2645(defun singular-help-init ()
2646  "Initialize online help support for Singular interactive mode.
2647
2648This function is called at mode initialization time."
2649  (make-local-variable 'singular-help-file-name)
2650  (make-local-variable 'singular-help-time-stamp)
2651  (make-local-variable 'singular-help-response-pending)
2652  (make-local-variable 'singular-help-topic)
2653  (add-hook 'singular-pre-input-filter-functions 'singular-help-pre-input-filter)
2654  (add-hook 'singular-pre-output-filter-functions 'singular-help-pre-output-filter)
2655  (add-hook 'singular-post-output-filter-functions 'singular-help-post-output-filter))
2656;;}}}
2657
2658;;{{{ Singular commands, help topics and standard libraries alists
2659(defvar singular-commands-alist nil 
2660  "An alist containing all Singular commands to complete.
2661
2662This variable is buffer-local.")
2663
2664(defvar singular-help-topics-alist nil
2665  "An alist containg all Singular help topics to complete.
2666
2667This variable is buffer-local.")
2668
2669(defvar singular-standard-libraries-with-categories nil
2670  "A list containing all Singular standard library names and their category.
2671
2672This variable is buffer-local.")
2673
2674(defvar singular-standard-libraries-alist nil
2675  "An alist containing all Singular standard library names.
2676This variable is set automatically by `singular-menu-install-libraries'
2677using the value of `singular-standard-libraries-with-categories'.
2678
2679This variable is buffer-local.")
2680;;}}}
2681
2682;;{{{ Scanning of header and handling of emacs home directory
2683;;
2684;; Scanning of header
2685;;
2686(defconst singular-scan-header-emacs-home-regexp "^// \\*\\* EmacsDir: \\(.+\\)\n"
2687  "Regular expression matching the location of emacs home in Singular
2688header.")
2689
2690(defconst singular-scan-header-info-file-regexp "^// \\*\\* InfoFile: \\(.+\\)\n"
2691  "Regular expression matching the location of Singular info file in
2692Singular header.")
2693
2694(defconst singular-scan-header-time-stamp 0
2695  "A time stamp set by singular-scan-header.
2696
2697This variable is buffer-local.")
2698
2699(defvar singular-scan-header-scan-for '()
2700  "List of things to scan for in Singular header.
2701If `singular-scan-header-pre-output-filter' finds one thing in the current
2702output, it removes the corresponding value from the list.
2703If this variable gets nil, `singular-scan-header-pre-output-filter' is
2704removed from the pre-output-filter.
2705This variable is initialized in `singular-scan-header-init'. Possible
2706values of this list are up to now `help-file' and `emacs-home'.
2707
2708This variable is buffer-local.")
2709
2710(defun singular-scan-header-got-emacs-home ()
2711  "Load Singular completion and libraries files.
2712Assumes that `singular-emacs-home-directory' is set to the appropriate
2713value and loads the files \"cmd-cmpl.el\", \"hlp-cmpl.el\", \"ex-cmpl.el\",
2714and \"lib-cmpl.el\".
2715On success calls `singular-menu-install-libraries'."
2716  (or (load (singular-expand-emacs-file-name "cmd-cmpl.el" t) t t t)
2717      (message "Can't find command completion file! Command completion disabled."))
2718  (or (load (singular-expand-emacs-file-name "hlp-cmpl.el" t) t t t)
2719      (message "Can't find help topic completion file! Help completion disabled."))
2720  (or (load (singular-expand-emacs-file-name "ex-cmpl.el" t) t t t)
2721      (message "Can't find examples completion file! Examples completion disabled."))
2722  (if (load (singular-expand-emacs-file-name "lib-cmpl.el" t) t t t)
2723      (singular-menu-install-libraries)
2724    (message "Can't find library index file!")))
2725 
2726
2727(defun singular-scan-header-pre-output-filter (output)
2728  "Filter function for hook `singular-pro-output-filter-functions'.
2729Scans the Singular header for special markers using the regexps
2730`singular-scan-header-info-file-regexp' and
2731`singular-scan-header-emacs-home-regexp', removes them, loads the
2732completion files, the library-list file, calls
2733`singular-menu-install-libraries' and sets `singular-help-file-name'.
2734Removes itself from the hook if all special markers were found or if it has
2735been searching for more than 20 seconds."
2736  (singular-debug 'interactive (message "scanning header"))
2737  (let ((changed nil))
2738
2739    ;; Search for emacs home directory
2740    (when (string-match singular-scan-header-emacs-home-regexp output)
2741      (let ((emacs-home (substring output (match-beginning 1) (match-end 1))))
2742        (singular-debug 'interactive 
2743                        (message "scan header: emacs home path found"))
2744        ;; in any case, remove marker from output
2745        (setq output (replace-match "" t t output))
2746        (setq changed t)
2747        ;; if not already done, do action an singular-emacs-home
2748        (when (memq 'emacs-home singular-scan-header-scan-for)
2749          (singular-debug 'interactive (message "scan header: initializing emacs-home-directory"))
2750          (setq singular-scan-header-scan-for (delq 'emacs-home singular-scan-header-scan-for))
2751          (setq singular-emacs-home-directory emacs-home)
2752          (singular-scan-header-got-emacs-home))))
2753
2754    ;; Search for Singular info file
2755    (when (string-match singular-scan-header-info-file-regexp output)
2756      (let ((file-name (substring output (match-beginning 1) (match-end 1))))
2757        (singular-debug 'interactive 
2758                        (message "scan header: singular.hlp path found"))
2759        ;; in any case, remove marker from output
2760        (setq output (replace-match "" t t output))
2761        (setq changed t)
2762        ;; if not already done, do action on help-file-name
2763        (when (memq 'info-file singular-scan-header-scan-for)
2764          (singular-debug 'interactive (message "scan header: initializing help-file-name"))
2765          (setq singular-scan-header-scan-for (delq 'info-file singular-scan-header-scan-for))
2766          (setq singular-help-file-name file-name))))
2767
2768    ;; Remove from hook if everything is found or if we already waited
2769    ;; too long.
2770    (if (or (eq singular-scan-header-scan-for nil) 
2771            (> (singular-time-stamp-difference (current-time) singular-scan-header-time-stamp) 20))
2772        (remove-hook 'singular-pre-output-filter-functions 'singular-scan-header-pre-output-filter))
2773
2774    ;; Return new output string if we changed it, nil otherwise
2775    (and changed output)))
2776
2777(defun singular-scan-header-init ()
2778  "Initialize scanning of header for Singular interactive mode.
2779
2780This function is called by `singular-exec'."
2781  (singular-debug 'interactive (message "Initializing scan-header"))
2782  (set (make-local-variable 'singular-scan-header-time-stamp) (current-time))
2783  (set (make-local-variable 'singular-scan-header-scan-for) '())
2784
2785  (make-local-variable 'singular-emacs-home-directory)
2786  ;; if singular-emacs-home is set try to load the completion files.
2787  ;; Otherwise set marker that we still have to search for it.
2788  (if singular-emacs-home-directory
2789      (singular-scan-header-got-emacs-home)
2790    (setq singular-scan-header-scan-for (append singular-scan-header-scan-for '(emacs-home))))
2791
2792  ;; Up to now this seems to be the best place to initialize
2793  ;; `singular-help-file-name' since singular-help gets initialized
2794  ;; only on mode start-up, not on Singular start-up
2795  ;;
2796  ;; if singular-help-file-name is not set, mark, that we have to scan for it
2797  (make-local-variable 'singular-help-file-name)
2798  (or singular-help-file-name
2799      (setq singular-scan-header-scan-for (append singular-scan-header-scan-for '(info-file))))
2800
2801  (add-hook 'singular-pre-output-filter-functions 'singular-scan-header-pre-output-filter))
2802
2803(defun singular-scan-header-exit ()
2804  "Reinitialize scanning of header for Singular interactive mode.
2805
2806This function is called by `singular-exit-sentinel'."
2807  ;; unset variables so that all subsequent calls of Singular will
2808  ;; scan the header.
2809  (singular-debug 'interactive (message "Deinitializing scan-header"))
2810  (setq singular-emacs-home-directory nil)
2811  (setq singular-help-file-name nil))
2812
2813;;
2814;; handling of emacs home directory
2815;;
2816;; A note on `singular-emacs-home-directory': If this variable is set
2817;; before singular.el is evaluated, the header of the first Singular
2818;; started is NOT searched for the singular-emacs-home-directory.
2819;; Anyhow, all subsequent calls of Singular will scan the header
2820;; regardless of the initial state of this variable. (The exit-sentinel
2821;; will set this variable back to nil.)
2822;; See also `singular-scan-header-exit'.
2823(defvar singular-emacs-home-directory nil
2824  "Path to the emacs sub-directory of Singular as string.
2825`singular-scan-header-pre-output-filter' searches the Singular header for
2826the path and sets this variable to the corresponding value.
2827Its value is redifined on every start of Singular.
2828
2829This variable is buffer-local.")
2830
2831(defun singular-expand-emacs-file-name (file &optional noerror)
2832  "Add absolute path of emacs home directory.
2833Adds the content of `singular-emacs-home-directory' to the string FILE.
2834If `singular-emacs-home-directory' is nil, return nil and signal
2835an error unless optional argument NOERROR is not nil."
2836  (if singular-emacs-home-directory
2837      (concat singular-emacs-home-directory
2838              (if (memq (aref singular-emacs-home-directory
2839                              (1- (length singular-emacs-home-directory)))
2840                        '(?/ ?\\))
2841                  "" "/")
2842              file)
2843    (if noerror
2844        nil
2845      (error "Variable singular-emacs-home-directory not set"))))
2846;;}}}
2847
2848;;{{{ Filename, Command, and Help Completion
2849(defun singular-completion-init ()
2850  "Initialize completion for Singular interactive mode.
2851Initializes completion of file names, commands, examples, and help topics.
2852
2853This function is called by `singular-exec'."
2854  (singular-debug 'interactive (message "Initializing completion"))
2855  (set (make-local-variable 'singular-commands-alist) nil)
2856  (set (make-local-variable 'singular-examples-alist) nil)
2857  (set (make-local-variable 'singular-help-topics-alist) nil))
2858
2859(defun singular-completion-do (pattern beg end completion-alist)
2860  "Try completion on string PATTERN using alist COMPLETION-ALIST.
2861Inserts completed version of PATTERN as new text between BEG and END.
2862Assumes the COMPLETION-ALIST is not nil."
2863  (let ((completion (try-completion pattern completion-alist)))
2864    (cond ((eq completion t)
2865           (message "[Sole completion]"))  ;; nothing to complete
2866          ((null completion)               ;; no completion found
2867           (message "Can't find completion for \"%s\"" pattern)
2868           (ding))
2869          ((not (string= pattern completion))
2870           (delete-region beg end)
2871           (insert completion))
2872          (t
2873           (message "Making completion list...")
2874           (let ((list (all-completions pattern 
2875                                        completion-alist)))
2876             (with-output-to-temp-buffer "*Completions*"
2877               (display-completion-list list)))
2878           (message "Making completion list...%s" "done")))))
2879
2880(defun singular-dynamic-complete ()
2881  "Dynamic complete word before point.
2882Performs file name completion if point is inside a string.
2883Performs completion of Singular help topics if point is at the end of a
2884help command (\"help\" or \"?\").
2885Performs completion of Singular examples if point is at the end of an
2886example command (\"example\").
2887Otherwise performs completion of Singular commands."
2888  (interactive)
2889  ;; Check if we are inside a string.  The search is done back to the
2890  ;; process-mark which should be the beginning of the current input.
2891  ;; No check at this point whether there is a process!
2892  (if (save-excursion
2893        (nth 3 (parse-partial-sexp (singular-process-mark) (point))))
2894      ;; then: inside string, thus expand filename
2895      (comint-dynamic-complete-as-filename)
2896    ;; else: expand command or help
2897    (let ((end (point))
2898          (post-prompt (save-excursion
2899                         (beginning-of-line)
2900                         (singular-prompt-skip-forward)))
2901          beg)
2902      (cond
2903       ((save-excursion
2904          (goto-char post-prompt)
2905          (looking-at "[ \t]*\\([\\?]\\|help \\)[ \t]*\\(.*\\)"))
2906        ;; then: help completion
2907        (if singular-help-topics-alist
2908            (singular-completion-do (match-string 2) (match-beginning 2)
2909                                    end singular-help-topics-alist)
2910          (message "Completion of Singular help topics disabled.")
2911          (ding)))
2912       ((save-excursion
2913          (goto-char post-prompt)
2914          (looking-at "[ \t]*\\(example \\)[ \t]*\\(.*\\)"))
2915        ;; then: example completion
2916        (if singular-examples-alist
2917            (singular-completion-do (match-string 2) (match-beginning 2)
2918                                    end singular-examples-alist)
2919          (message "Completion of Singular examples disabled.")
2920          (ding)))
2921       (t
2922        ;; else: command completion
2923        (save-excursion
2924          (skip-chars-backward "a-zA-Z0-9")
2925          (setq beg (point)))
2926        (if singular-commands-alist
2927            (singular-completion-do (buffer-substring beg end) beg
2928                                    end singular-commands-alist)
2929          (message "Completion of Singular commands disabled.")
2930          (ding)))))))
2931;;}}}
2932
2933;;{{{ Debugging filters
2934(defun singular-debug-pre-input-filter (string)
2935  "Display STRING and some markers in mini-buffer."
2936  (singular-debug 'interactive-filter
2937                  (message "Pre-input filter: %s (li %S ci %S lo %S co %S)"
2938                           (singular-debug-format string)
2939                           (marker-position singular-last-input-section-start)
2940                           (marker-position singular-current-input-section-start)
2941                           (marker-position singular-last-output-section-start)
2942                           (marker-position singular-current-output-section-start)))
2943  nil)
2944
2945(defun singular-debug-post-input-filter (beg end)
2946  "Display BEG, END, and some markers in mini-buffer."
2947  (singular-debug 'interactive-filter
2948                  (message "Post-input filter: (beg %S end %S) (li %S ci %S lo %S co %S)"
2949                           beg end
2950                           (marker-position singular-last-input-section-start)
2951                           (marker-position singular-current-input-section-start)
2952                           (marker-position singular-last-output-section-start)
2953                           (marker-position singular-current-output-section-start))))
2954
2955(defun singular-debug-pre-output-filter (string)
2956  "Display STRING and some markers in mini-buffer."
2957  (singular-debug 'interactive-filter
2958                  (message "Pre-output filter: %s (li %S ci %S lo %S co %S)"
2959                           (singular-debug-format string)
2960                           (marker-position singular-last-input-section-start)
2961                           (marker-position singular-current-input-section-start)
2962                           (marker-position singular-last-output-section-start)
2963                           (marker-position singular-current-output-section-start)))
2964  nil)
2965
2966(defun singular-debug-post-output-filter (beg end simple-sec-start)
2967  "Display BEG, END, SIMPLE-SEC-START, and some markers in mini-buffer."
2968  (singular-debug 'interactive-filter
2969                  (message "Post-output filter: (beg %S end %S sss %S) (li %S ci %S lo %S co %S)"
2970                           beg end simple-sec-start
2971                           (marker-position singular-last-input-section-start)
2972                           (marker-position singular-current-input-section-start)
2973                           (marker-position singular-last-output-section-start)
2974                           (marker-position singular-current-output-section-start))))
2975
2976(defun singular-debug-filter-init ()
2977  "Add debug filters to the necessary hooks.
2978
2979This function is called at mode initialization time."
2980  (add-hook 'singular-pre-input-filter-functions
2981            'singular-debug-pre-input-filter nil t)
2982  (add-hook 'singular-post-input-filter-functions
2983            'singular-debug-post-input-filter nil t)
2984  (add-hook 'singular-pre-output-filter-functions
2985            'singular-debug-pre-output-filter nil t)
2986  (add-hook 'singular-post-output-filter-functions
2987            'singular-debug-post-output-filter nil t))
2988;;}}}
2989
2990;;{{{ Demo mode
2991
2992;; Note:
2993;;
2994;; For documentation on Singular demo mode one should refer to the doc
2995;; string of `singular-demo-load'.
2996;; Singular demo mode should have been implemented as a minor mode but it
2997;; did not seem worth it.
2998
2999(defcustom singular-demo-chunk-regexp "\\(\n\\s *\n\\)"
3000  "*Regular expressions to recognize chunks of a demo file.
3001If there is a subexpression specified its contents is removed after the
3002chunk has been displayed.
3003The default value is \"\\\\(\\n\\\\s *\\n\\\\)\" which means that chunks are
3004separated by one blank line which is removed after the chunks have been
3005displayed."
3006  :type 'regexp
3007  :initialize 'custom-initialize-default
3008  :group 'singular-demo-mode)
3009
3010(defcustom singular-demo-print-messages t
3011  "*If non-nil, print message on how to continue demo mode."
3012  :type 'boolean
3013  :initialize 'custom-initialize-default
3014  :group 'singular-demo-mode)
3015
3016(defcustom singular-demo-exit-on-load t
3017  "*If non-nil, an active demo is automatically discarded when a new one is loaded.
3018Otherwise, the load is aborted with an error."
3019  :type 'boolean
3020  :initialize 'custom-initialize-default
3021  :group 'singular-demo-mode)
3022
3023(defcustom singular-demo-load-directory nil
3024  "*Directory where demo files usually reside.
3025If non-nil, this directory is offered as a starting point to search for
3026demo files when `singular-demo-load' is called interactively for the first
3027time.  (In further calls, `singular-demo-load' offers the directory where
3028the last demo file has been loaded from as starting point).
3029
3030If this variable equals nil whatever Emacs offers by default is used as
3031first-time starting point.  In general, this is the directory where
3032Singular has been started in."
3033  :type '(choice (const nil) (file))
3034  :initialize 'custom-initialize-default
3035  :group 'singular-demo-mode)
3036
3037(defvar singular-demo-mode nil
3038  "Non-nil if Singular demo mode is on.
3039
3040This variable is buffer-local.")
3041
3042(defvar singular-demo-old-mode-name nil
3043  "Used to store previous `mode-name' before switching to demo mode.
3044
3045This variable is buffer-local.")
3046
3047(defvar singular-demo-end nil
3048  "Marker pointing to end of demo file.
3049
3050This variable is buffer-local.")
3051
3052(defvar singular-demo-last-directory nil
3053  "If non-nil, directory from which the last demo file has been loaded.
3054
3055This variable is buffer-local.")
3056
3057(defun singular-demo-load (demo-file)
3058  "Load demo file DEMO-FILE and enter Singular demo mode.
3059
3060The Singular demo mode allows to step conveniently through a prepared demo
3061file.  The contents of the demo file is made visible and executed in
3062portions called chunks.  How the chunks have to be marked in the demo file
3063is described below.
3064
3065After loading the demo file with this function, \\[singular-send-or-copy-input] displays the first
3066chunk of the demo file at the Singular prompt.  This chunk may be modified
3067\(or even deleted) and then sent to Singular entering \\[singular-send-or-copy-input] as any command
3068would have been sent to Singular.  The next time \\[singular-send-or-copy-input] is entered, the next
3069chunk of the demo file is displayed, and so on.
3070
3071One may interrupt this sequence and enter commands at the Singular input
3072prompt as usual.  As soon as \\[singular-send-or-copy-input] is entered directly after the input
3073prompt, the next chunk of the demo file is displayed.  Here is the exact
3074algorithm how this magic works: If point is located at the very end of the
3075buffer *and* immediately after Singular's last input prompt, the next chunk
3076of the demo file is displayed.  In particular, if there is any text after
3077the last input prompt that text is sent to Singular as usual and no new
3078chunks are displayed.
3079
3080After displaying the last chunk of DEMO-FILE, Singular demo mode
3081automatically terminates and normal operation is resumed.  To prematurely
3082exit Singular demo mode \\[singular-demo-exit] may be used.
3083
3084DEMO-FILE should consist of regular Singular commands.  Portions of text
3085separated by a blank line are taken to be the chunks of the demo file.
3086
3087There is a number of variables to configure Singular demo mode.  Refer to
3088the `singular-demo-mode' customization group for more information.
3089
3090Important note: The unprocessed contents of DEMO-FILE is hidden using
3091buffer narrowing.  Emacs gets terribly confused when during demo mode the
3092buffer is either narrowed to some other region or if the buffer is widened.
3093The safest thing to do if that happens by accident is to explicitly exit
3094the demo by means of \\[singular-demo-exit] and to try to resume somehow
3095normal operation.
3096
3097`singular-demo-load' runs the functions on `singular-demo-mode-enter-hook'
3098just after demo mode has been entered.  The functions on
3099`singular-demo-mode-exit-hook' are executed after Singular demo mode has
3100been exited, either prematurely or due to the end of the demo file.
3101However, it its important to note that in the latter case the last chunk of
3102the demo file is still waiting to be sent to Singular."
3103  (interactive
3104   (list
3105    (let ((demo-file-name
3106           (cond
3107            ;; Emacs
3108            ((eq singular-emacs-flavor 'emacs)
3109             (read-file-name "Load demo file: "
3110                             (or singular-demo-last-directory
3111                                 singular-demo-load-directory)
3112                             nil t))
3113            ;; XEmacs
3114            (t
3115             ;; there are some problems with the window being popped up when this
3116             ;; function is called from a menu.  It does not display the contents
3117             ;; of `singular-demo-load-directory' but of `default-directory'.
3118             (let ((default-directory (or singular-demo-last-directory
3119                                          singular-demo-load-directory
3120                                          default-directory)))
3121               (read-file-name "Load demo file: "
3122                               (or singular-demo-last-directory
3123                                   singular-demo-load-directory)
3124                               nil t))))))
3125     
3126      (setq singular-demo-last-directory (file-name-directory demo-file-name))
3127      demo-file-name)))
3128
3129  ;; check for running demo
3130  (if singular-demo-mode
3131      (if singular-demo-exit-on-load
3132          ;; silently exit running demo
3133          (singular-demo-exit t)
3134        (error "There already is a demo running, exit with `singular-demo-exit' first")))
3135
3136  ;; load new demo
3137  (let ((old-point-min (point-min)))
3138    (unwind-protect
3139        (progn
3140          (goto-char (point-max))
3141          (widen)
3142          (cond
3143           ;; XEmacs
3144           ((eq singular-emacs-flavor 'xemacs)
3145            ;; load file and remember its end
3146            (set-marker singular-demo-end
3147                        (+ (point) (nth 1 (insert-file-contents-literally demo-file)))))
3148           ;; Emacs
3149           (t
3150            ;; Emacs does something like an `insert-before-markers' so
3151            ;; save all essential markers
3152            (let ((pmark-pos (marker-position (singular-process-mark)))
3153                  (sliss-pos (marker-position singular-last-input-section-start))
3154                  (sciss-pos (marker-position singular-current-input-section-start))
3155                  (sloss-pos (marker-position singular-last-output-section-start))
3156                  (scoss-pos (marker-position singular-current-output-section-start)))
3157
3158              (unwind-protect
3159                  ;; load file and remember its end
3160                  (set-marker singular-demo-end
3161                              (+ (point) (nth 1 (insert-file-contents-literally demo-file))))
3162
3163                ;; restore markers.
3164                ;; This is unwind-protected.
3165                (set-marker (singular-process-mark) pmark-pos)
3166                (set-marker singular-last-input-section-start sliss-pos)
3167                (set-marker singular-current-input-section-start sciss-pos)
3168                (set-marker singular-last-output-section-start sloss-pos)
3169                (set-marker singular-current-output-section-start scoss-pos))))))
3170
3171      ;; completely hide demo file.
3172      ;; This is unwind-protected.
3173      (narrow-to-region old-point-min (point))))
3174
3175  ;; switch demo mode on
3176  (setq singular-demo-old-mode-name mode-name
3177        mode-name "Singular Demo"
3178        singular-demo-mode t)
3179  (run-hooks 'singular-demo-mode-enter-hook)
3180  (if singular-demo-print-messages (message "Hit RET to start demo"))
3181  (force-mode-line-update))
3182
3183(defun singular-demo-exit-internal ()
3184  "Exit Singular demo mode.
3185Recovers the old mode name, sets `singular-demo-mode' to nil, runs
3186the hooks on `singular-demo-mode-exit-hook'."
3187  (setq mode-name singular-demo-old-mode-name
3188        singular-demo-mode nil)
3189  (run-hooks 'singular-demo-mode-exit-hook)
3190  (force-mode-line-update))
3191
3192(defun singular-demo-exit (&optional no-message)
3193  "Prematurely exit Singular demo mode.
3194Cleans up everything that is left from the demo.
3195Runs the hooks on `singular-demo-mode-exit-hook'.
3196Does nothing when Singular demo mode is not active."
3197  (interactive)
3198  (when singular-demo-mode
3199    ;; clean up hidden rest of demo file
3200    (let ((old-point-min (point-min))
3201          (old-point-max (point-max)))
3202      (unwind-protect
3203          (progn
3204            (widen)
3205            (delete-region old-point-max singular-demo-end))
3206        ;; this is unwind-protected
3207        (narrow-to-region old-point-min old-point-max)))
3208    (singular-demo-exit-internal)
3209    (or no-message
3210        (if singular-demo-print-messages (message "Demo exited")))))
3211
3212(defun singular-demo-show-next-chunk ()
3213  "Show next chunk of demo file at input prompt.
3214Assumes that Singular demo mode is active.
3215Moves point to end of buffer and widenes the buffer such that the next
3216chunk of the demo file becomes visible.
3217Finds and removes chunk separators as specified by
3218`singular-demo-chunk-regexp'.
3219Leaves demo mode after showing last chunk.  In that case runs hooks on
3220`singular-demo-mode-exit-hook'."
3221  (let ((old-point-min (point-min)))
3222    (unwind-protect
3223        (progn
3224          (goto-char (point-max))
3225          (widen)
3226          (if (re-search-forward singular-demo-chunk-regexp singular-demo-end 'limit)
3227              (if (match-beginning 1)
3228                  (delete-region (match-beginning 1) (match-end 1)))
3229            ;; remove trailing white-space.  We may not use
3230            ;; `(skip-syntax-backward "-")' since newline is has no white
3231            ;; space syntax.  The solution down below should suffice in
3232            ;; almost all cases ...
3233            (skip-chars-backward " \t\n\r\f")
3234            (delete-region (point) singular-demo-end)
3235            (singular-demo-exit-internal)))
3236
3237      ;; this is unwind-protected
3238      (narrow-to-region old-point-min (point)))))
3239
3240(defun singular-demo-mode-init ()
3241  "Initialize variables belonging to Singular demo mode.
3242Creates some buffer-local variables and the buffer-local marker
3243`singular-demo-end'.
3244
3245This function is called  at mode initialization time."
3246  (make-local-variable 'singular-demo-mode)
3247  (make-local-variable 'singular-demo-mode-old-name)
3248  (make-local-variable 'singular-demo-mode-end)
3249  (if (not (and (boundp 'singular-demo-end)
3250                singular-demo-end))
3251      (setq singular-demo-end (make-marker)))
3252  (make-local-variable 'singular-demo-last-directory))
3253;;}}}
3254     
3255;;{{{ Some lengthy notes on input and output
3256
3257;; NOT READY[so sorry]!
3258
3259;;}}}
3260
3261;;{{{ Last input and output section
3262(defun singular-last-input-section (&optional no-error)
3263  "Return last input section.
3264Returns nil if optional argument NO-ERROR is non-nil and there is no
3265last input section defined, throws an error otherwise."
3266  (let ((last-input-start (marker-position singular-last-input-section-start))
3267        (last-input-end (marker-position singular-current-output-section-start)))
3268    (cond ((and last-input-start last-input-end)
3269           (singular-section-create (singular-simple-sec-at last-input-start) 'input
3270                                    last-input-start last-input-end))
3271          (no-error nil)
3272          (t (error "No last input section defined")))))
3273
3274(defun singular-current-output-section (&optional no-error)
3275  "Return current output section.
3276Returns nil if optional argument NO-ERROR is non-nil and there is no
3277current output section defined, throws an error otherwise."
3278  (let ((current-output-start (marker-position singular-current-output-section-start))
3279        (current-output-end (save-excursion
3280                              (save-restriction
3281                                (widen)
3282                                (goto-char (singular-process-mark))
3283                                (singular-prompt-skip-backward)
3284                                (and (bolp) (point))))))
3285    (cond ((and current-output-start current-output-end)
3286           (singular-section-create (singular-simple-sec-at current-output-start) 'output
3287                                    current-output-start current-output-end))
3288          (no-error nil)
3289          (t (error "No current output section defined")))))
3290
3291(defun singular-last-output-section (&optional no-error)
3292  "Return last output section.
3293Returns nil if optional argument NO-ERROR is non-nil and there is no
3294last output section defined, throws an error otherwise."
3295  (let ((last-output-start (marker-position singular-last-output-section-start))
3296        (last-output-end (marker-position singular-last-input-section-start)))
3297    (cond ((and last-output-start last-output-end)
3298           (singular-section-create (singular-simple-sec-at last-output-start) 'output
3299                                    last-output-start last-output-end))
3300          (no-error nil)
3301          (t (error "No last output section defined")))))
3302
3303(defun singular-latest-output-section (&optional no-error)
3304  "Return latest output section.
3305This is the current output section if it is defined, otherwise the
3306last output section.
3307Returns nil if optional argument NO-ERROR is non-nil and there is no
3308latest output section defined, throws an error otherwise."
3309  (or (singular-current-output-section t)
3310      (singular-last-output-section t)
3311      (if no-error
3312          nil
3313        (error "No latest output section defined"))))
3314;;}}}
3315
3316;;{{{ Sending input
3317(defvar singular-pre-input-filter-functions nil
3318  "Functions to call before input is sent to process.
3319These functions get one argument, a string containing the text which
3320is to be sent to process.  The functions should return either nil
3321or a string.  In the latter case the returned string replaces the
3322string to be sent to process.
3323
3324This is a buffer-local variable, not a buffer-local hook!
3325
3326`singular-run-hook-with-arg-and-value' is used to run the functions in
3327the list.")
3328
3329(defvar singular-post-input-filter-functions nil
3330  "Functions to call after input is sent to process.
3331These functions get two arguments BEG and END.
3332If `singular-input-filter' has been called with a string as argument
3333BEG and END gives the position of this string after insertion into the
3334buffer.
3335If `singular-input-filter' has been called with a position as argument
3336BEG and END equal process mark and that position, resp.
3337The functions may assume that no narrowing is in effect and may change
3338point at will.
3339
3340This hook is buffer-local.")
3341
3342(defvar singular-current-input-section-start nil
3343  "Marker to the start of the current input section.
3344This marker points nowhere on startup or if there is no current input
3345section.
3346
3347This variable is buffer-local.")
3348
3349(defvar singular-last-input-section-start nil
3350  "Marker to the start of the last input section.
3351This marker points nowhere on startup.
3352
3353This variable is buffer-local.")
3354
3355(defun singular-input-filter-init (pos)
3356  "Initialize all variables concerning input.
3357POS is the position of the process mark."
3358  ;; localize variables not yet localized in `singular-interactive-mode'
3359  (make-local-variable 'singular-current-input-section-start)
3360  (make-local-variable 'singular-last-input-section-start)
3361
3362  ;; initialize markers
3363  (if (not (markerp singular-current-input-section-start))
3364      (setq singular-current-input-section-start (make-marker)))
3365  (if (not (markerp singular-last-input-section-start))
3366      (setq singular-last-input-section-start (make-marker))))
3367
3368(defun singular-send-string (process string)
3369  "Send newline terminated STRING to to process PROCESS.
3370Runs the hooks on `singular-pre-input-filter-functions' in the buffer
3371associated to PROCESS.  The functions get the non-terminated string."
3372  (let ((process-buffer (process-buffer process)))
3373
3374    ;; check whether buffer is still alive
3375    (if (and process-buffer (buffer-name process-buffer))
3376        (save-excursion
3377          (set-buffer process-buffer)
3378          (process-send-string
3379           process
3380           (concat (singular-run-hook-with-arg-and-value
3381                    singular-pre-input-filter-functions string)
3382                   "\n"))))))
3383
3384(defun singular-input-filter (process string-or-pos)
3385  "Insert/update input from user in buffer associated to PROCESS.
3386Inserts STRING-OR-POS followed by a newline at process mark if it is a
3387string.
3388Assumes that the input is already inserted and that it is placed
3389between process mark and STRING-OR-POS if the latter is a position.
3390Inserts a newline after STRING-OR-POS.
3391
3392Takes care off:
3393- current buffer as well as point and restriction in buffer associated
3394  with process, even against non-local exits.
3395Updates:
3396- process mark;
3397- current and last sections;
3398- simple sections;
3399- mode line.
3400
3401Runs the hooks on `singular-pre-input-filter-functions' and
3402`singular-post-input-filter-functions'.
3403
3404For a more detailed descriptions of the input filter, the markers it
3405sets, and input filter functions refer to the section \"Some lengthy
3406notes on input and output\" in singular.el."
3407  (let ((process-buffer (process-buffer process)))
3408
3409    ;; check whether buffer is still alive
3410    (if (and process-buffer (buffer-name process-buffer))
3411        (let ((old-buffer (current-buffer))
3412              (old-pmark (marker-position (process-mark process)))
3413              old-point old-point-min old-point-max)
3414          (unwind-protect
3415              (let (simple-sec-start)
3416                (set-buffer process-buffer)
3417                ;; the following lines are not protected since the
3418                ;; unwind-forms refer the variables being set here
3419                (setq old-point (point-marker)
3420                      old-point-min (point-min-marker)
3421                      old-point-max (point-max-marker)
3422
3423                ;; get end of last simple section (equals start of
3424                ;; current)
3425                      simple-sec-start (singular-simple-sec-last-end-position))
3426
3427                ;; prepare for insertion
3428                (widen)
3429                (set-marker-insertion-type old-point t)
3430                (set-marker-insertion-type old-point-max t)
3431
3432                ;; insert string at process mark and advance process
3433                ;; mark after insertion.  If it not a string simply
3434                ;; jump to desired position and insrt a newline.
3435                (if (stringp string-or-pos)
3436                    (progn
3437                      (goto-char old-pmark)
3438                      (insert string-or-pos))
3439                  (goto-char string-or-pos))
3440                (insert ?\n)
3441                (set-marker (process-mark process) (point))
3442
3443                ;; create new simple section and update section markers
3444                (cond
3445                 ((eq (singular-simple-sec-create 'input (point)) 'empty)
3446                  nil)
3447                 ;; a new simple section has been created ...
3448                 ((null (marker-position singular-current-input-section-start))
3449                  ;; ... and even a new input section has been created!
3450                  (set-marker singular-current-input-section-start
3451                              simple-sec-start)
3452                  (set-marker singular-last-output-section-start
3453                              singular-current-output-section-start)
3454                  (set-marker singular-current-output-section-start nil)))
3455
3456                ;; run post-output hooks and force mode-line update
3457                (run-hook-with-args 'singular-post-input-filter-functions
3458                                    old-pmark (point)))
3459
3460            ;; restore buffer, restrictions and point
3461            (narrow-to-region old-point-min old-point-max)
3462            (set-marker old-point-min nil)
3463            (set-marker old-point-max nil)
3464            (goto-char old-point)
3465            (set-marker old-point nil)
3466            (set-buffer old-buffer))))))
3467;;}}}
3468
3469;;{{{ Sending input interactive
3470(defcustom singular-move-on-send 'eob
3471  "*Where to move point before sending input to Singular.
3472Should be one of:
3473`eob' which means to move point to end of buffer,
3474`eol' which means to move point to end of line, or
3475 nil  which means to not move point at all."
3476  :type '(choice (const :tag "End of buffer" eob)
3477                 (const :tag "End of line" eol)
3478                 (const :tag "Do not move" nil))
3479  :initialize 'custom-initialize-default
3480  :group 'singular-interactive-miscellaneous)
3481
3482(defun singular-get-old-input (get-section)
3483  "Get and return old input.
3484Retrivies on a per-section base if GET-SECTION is non-nil, otherwise on a
3485per-line base."
3486  (if get-section
3487      ;; get input from input section
3488      (let ((section (singular-section-at (point))))
3489        (if (eq (singular-section-type section) 'input)
3490            (singular-white-space-strip (singular-section-to-string section) t)
3491          (error "Not on an input section")))
3492    ;; get input from line
3493    (save-excursion
3494      (beginning-of-line)
3495      (singular-prompt-skip-forward)
3496      (let ((old-point (point)))
3497        (end-of-line)
3498        (buffer-substring old-point (point))))))
3499
3500(defun singular-send-or-copy-input (get-section)
3501  "Send input to Singular.
3502
3503The behavior of this function very much depends on the current position of
3504point relative to the process mark, that is, the position, where Singular
3505expects next input.
3506
3507If point is located before process mark, old input is copied to the process
3508mark.  With prefix argument, the whole input section point currently is in
3509is copied, without prefix argument only the current line.  One should note
3510that the input is *not* sent to Singular, it is only copied to the process
3511mark.  Another time entering \\[singular-send-or-copy-input] sends it to Singular.
3512
3513If point is located after process mark, point is moved as determined by the
3514`singular-move-on-send' variable: either it is moved to the end of the
3515current line, or to the end of the buffer, or it is not moved at all.  The
3516default is to move point to the end of the buffer which most closely
3517resembles regular terminal behaviour.  At last, the text of the region
3518between process mark and point is sent to Singular.
3519
3520Any input to Singular is stored in an input history where it may be
3521retrieved with \\[comint-previous-input] or \\[comint-next-input], respectively.  For more information on the input
3522history one should refer to the documentation of
3523`singular-interactive-mode'.
3524
3525If Singular demo mode is active and point is at process mark and if that
3526position is at the end of the buffer the next chunk of the demo file is
3527displayed.  One should refer to the documentation of `singular-demo-load'
3528for more information on Singular demo mode.
3529
3530The Singular process should be running."
3531  (interactive "P")
3532  (let ((process (singular-process))
3533        (pmark (singular-process-mark)))
3534    (cond
3535     (;; check for demo mode and show next chunk if necessary
3536      (and singular-demo-mode
3537           (= (point) pmark)
3538           (= pmark (point-max)))
3539      (singular-demo-show-next-chunk))
3540
3541     (;; get old input
3542      (< (point) pmark)
3543      (let ((old-input (singular-get-old-input get-section)))
3544        (goto-char pmark)
3545        (insert old-input)))
3546
3547     (;; send input from pmark to point
3548      t
3549      ;; print message if demo mode is active.  We print it before we do
3550      ;; anything else so that the message will not hide any further
3551      ;; (error) messages.
3552      (and singular-demo-mode
3553           singular-demo-print-messages
3554           (message "Hit RET to continue demo"))
3555
3556      ;; go to desired position
3557      (cond ((eq singular-move-on-send 'eol)
3558             (end-of-line))
3559            ((eq singular-move-on-send 'eob)
3560             (goto-char (point-max))))
3561
3562      (let* ((input (buffer-substring pmark (point))))
3563        ;; insert string into history
3564        (singular-history-insert input)
3565        ;; send string to process
3566        (singular-send-string process input)
3567        ;; "insert" it into buffer
3568        (singular-input-filter process (point)))))))
3569;;}}}
3570
3571;;{{{ Receiving output
3572(defvar singular-pre-output-filter-functions nil
3573  "Functions to call before output is inserted into the buffer.
3574These functions get one argument, a string containing the text sent
3575from process.  The functions should return either nil or a string.
3576In the latter case the returned string replaces the string sent from
3577process.
3578
3579This is a buffer-local variable, not a buffer-local hook!
3580
3581`singular-run-hook-with-arg-and-value' is used to run the functions in
3582this list.")
3583
3584(defvar singular-post-output-filter-functions nil
3585  "Functions to call after output is inserted into the buffer.
3586These functions get three arguments BEG, END, and SIMPLE-SEC-START.
3587The region between BEG and END is what has been inserted into the
3588buffer.
3589SIMPLE-SEC-START is the start of the simple section which has been
3590created on insertion or nil if no simple section has been created.
3591The functions may assume that no narrowing is in effect and may change
3592point at will.
3593
3594This hook is buffer-local.")
3595
3596(defvar singular-current-output-section-start nil
3597  "Marker to the start of the current output section.
3598This marker points nowhere on startup or if there is no current output
3599section.
3600
3601This variable is buffer-local.")
3602
3603(defvar singular-last-output-section-start nil
3604  "Marker to the start of the last output section.
3605This marker points nowhere on startup.
3606
3607This variable is buffer-local.")
3608
3609(defun singular-output-filter-init (pos)
3610  "Initialize all variables concerning output including process mark.
3611Set process mark to POS."
3612
3613  ;; localize variables not yet localized in `singular-interactive-mode'
3614  (make-local-variable 'singular-current-output-section-start)
3615  (make-local-variable 'singular-last-output-section-start)
3616
3617  ;; initialize markers
3618  (if (not (markerp singular-current-output-section-start))
3619      (setq singular-current-output-section-start (make-marker)))
3620  (if (not (markerp singular-last-output-section-start))
3621      (setq singular-last-output-section-start (make-marker)))
3622  (set-marker (singular-process-mark) pos))
3623
3624(defun singular-output-filter (process string)
3625  "Insert STRING containing output from PROCESS into its associated buffer.
3626Takes care off:
3627- current buffer as well as point and restriction in buffer associated
3628  with process, even against non-local exits.
3629Updates:
3630- process mark;
3631- current and last sections;
3632- simple sections;
3633- mode line.
3634Runs the hooks on `singular-pre-output-filter-functions' and
3635`singular-post-output-filter-functions'.
3636
3637For a more detailed descriptions of the output filter, the markers it
3638sets, and output filter functions refer to the section \"Some lengthy
3639notes on input and output\" in singular.el."
3640  (let ((process-buffer (process-buffer process)))
3641
3642    ;; check whether buffer is still alive
3643    (if (and process-buffer (buffer-name process-buffer))
3644        (let ((old-buffer (current-buffer))
3645              (old-pmark (marker-position (process-mark process)))
3646              old-point old-point-min old-point-max)
3647          (unwind-protect
3648              (let (simple-sec-start)
3649                (set-buffer process-buffer)
3650                ;; the following lines are not protected since the
3651                ;; unwind-forms refer the variables being set here
3652                (setq old-point (point-marker)
3653                      old-point-min (point-min-marker)
3654                      old-point-max (point-max-marker)
3655
3656                ;; get end of last simple section (equals start of
3657                ;; current)
3658                      simple-sec-start (singular-simple-sec-last-end-position)
3659
3660                ;; get string to insert
3661                      string (singular-run-hook-with-arg-and-value
3662                              singular-pre-output-filter-functions
3663                              string))
3664
3665                ;; prepare for insertion
3666                (widen)
3667                (set-marker-insertion-type old-point t)
3668                (set-marker-insertion-type old-point-max t)
3669
3670                ;; insert string at process mark and advance process
3671                ;; mark after insertion
3672                (goto-char old-pmark)
3673                (insert string)
3674                (set-marker (process-mark process) (point))
3675
3676                ;; create new simple section and update section markers
3677                (cond
3678                 ((eq (singular-simple-sec-create 'output (point)) 'empty)
3679                  (setq simple-sec-start nil))
3680                 ;; a new simple section has been created ...
3681                 ((null (marker-position singular-current-output-section-start))
3682                  ;; ... and even a new output section has been created!
3683                  (set-marker singular-current-output-section-start
3684                              simple-sec-start)
3685                  (set-marker singular-last-input-section-start
3686                              singular-current-input-section-start)
3687                  (set-marker singular-current-input-section-start nil)))
3688
3689                ;; run post-output hooks and force mode-line update
3690                (run-hook-with-args 'singular-post-output-filter-functions
3691                                    old-pmark (point) simple-sec-start)
3692                (force-mode-line-update))
3693
3694            ;; restore buffer, restrictions and point
3695            (narrow-to-region old-point-min old-point-max)
3696            (set-marker old-point-min nil)
3697            (set-marker old-point-max nil)
3698            (goto-char old-point)
3699            (set-marker old-point nil)
3700            (set-buffer old-buffer))))))
3701;;}}}
3702
3703;;{{{ Singular interactive mode
3704(defun singular-interactive-mode ()
3705  "Major mode for interacting with Singular.
3706
3707NOT READY [how to send input]!
3708NOT READY [in particular: input history!]
3709
3710NOT READY [multiple Singulars]!
3711
3712\\{singular-interactive-mode-map}
3713
3714
3715For \"backward compatibility\" with the terminal version of Singular there
3716is some extra magic built into Singular interactive mode which catches help
3717commands issued at the command prompt and executes this function instead.
3718However, this magic is really not too magic and easily may be fooled.  If
3719this magic if fooled Singular prints some error message starting like this:
3720
3721// ** Your help command could not be executed. ...
3722
3723However, the most common case should be recognized: If one issues a help
3724command to a non-busy Singular, where the help command comes on one line
3725and is properly terminated with a semicolon.  Like that:
3726
3727help ring;
3728
3729Customization: Entry to this mode runs the hooks on
3730`singular-interactive-mode-hook'.
3731
3732NOT READY [much more to come.  See shell.el.]!"
3733  (interactive)
3734
3735  ;; uh-oh, we have to set `comint-input-ring-size' before we call
3736  ;; `comint-mode'
3737  (singular-history-init)
3738
3739  ;; run comint mode and do basic mode setup
3740  (let (comint-mode-hook)
3741    (comint-mode)
3742    (singular-comint-init))
3743  (setq major-mode 'singular-interactive-mode)
3744  (setq mode-name "Singular Interaction")
3745
3746  ;; some other initialization found in no folding
3747  (setq comment-start "// ")
3748  (setq comment-start-skip "// *")
3749  (setq comment-end "")
3750
3751  ;; initialize singular input and output filters.  This should be done
3752  ;; first as the filters are accessed in the following initialization
3753  ;; functions.  NOT READY [should be moved to the respective foldings]
3754  (make-local-variable 'singular-pre-input-filter-functions)
3755  (make-local-hook 'singular-post-input-filter-functions)
3756  (make-local-variable 'singular-pre-output-filter-functions)
3757  (make-local-hook 'singular-post-output-filter-functions)
3758
3759  (singular-interactive-mode-map-init)
3760  (singular-mode-syntax-table-init)
3761  (singular-interactive-mode-menu-init)
3762  (singular-demo-mode-init)
3763  (singular-folding-init)
3764  (singular-help-init)
3765  (singular-prompt-init)
3766  (singular-exec-init)
3767
3768  ;; Font Lock mode initialization for Emacs.  For XEmacs, it is done at
3769  ;; singular.el loading time.
3770  (cond
3771   ;; Emacs
3772   ((eq singular-emacs-flavor 'emacs)
3773    (singular-interactive-font-lock-init)))
3774
3775  ;; debugging filter initialization
3776  (singular-debug 'interactive-filter
3777   (singular-debug-filter-init))
3778
3779  (run-hooks 'singular-interactive-mode-hook))
3780;;}}}
3781
3782;;{{{ Starting singular
3783(defcustom singular-same-window t
3784  "*Specifies how to open the window for Singular sessions.
3785If this variable equals t, Singular comes up in the selected window.
3786If this variable equals nil, Singular comes up in another window.
3787If this variable equals neither t nor nil, the standard Emacs behaviour to
3788open the window is adopted (which very much depends on the settings of
3789`same-window-buffer-names')."
3790  :initialize 'custom-initialize-default
3791  :type '(choice (const :tag "This window" t)
3792                 (const :tag "Other window" nil)
3793                 (const :tag "Default" default))
3794  :group 'singular-interactive-miscellaneous)
3795
3796(defcustom singular-start-file "~/.emacs_singularrc"
3797  "*Name of start-up file to pass to Singular.
3798If the file named by this variable exists it is given as initial input
3799to any Singular process being started.  Note that this may lose due to
3800a timing error if Singular discards input when it starts up."
3801  :type 'file
3802  :initialize 'custom-initialize-default
3803  :group 'singular-interactive-miscellaneous)
3804
3805(defcustom singular-executable-default "Singular"
3806  "*Default name of Singular executable.
3807Used by `singular' when new Singular processes are started.
3808If the name is given without path the executable is searched using the
3809`PATH' environment variable."
3810  :type 'file
3811  :initialize 'custom-initialize-default
3812  :group 'singular-interactive-miscellaneous)
3813
3814(defvar singular-executable-last singular-executable-default
3815  "Singular executable name of the last Singular command used.
3816
3817This variable is buffer-local.")
3818
3819(defcustom singular-directory-default nil
3820  "*Default working directory of Singular buffer.
3821Should be either nil (which means do not set the default directory) or an
3822existing directory."
3823  :type '(choice (const nil) (directory :value "~/"))
3824  :initialize 'custom-initialize-default
3825  :group 'singular-interactive-miscellaneous)
3826
3827(defvar singular-directory-last singular-directory-default
3828  "Working directory of last Singular command used.
3829
3830This variable is buffer-local.")
3831
3832;; no singular-directory-history here. Usual file history is used.
3833
3834(defcustom singular-switches-default '()
3835  "*List of default switches for Singular processes.
3836Should be a list of strings, one string for each switch.
3837Used by `singular' when new Singular processes are started."
3838  :type '(repeat string)
3839  :initialize 'custom-initialize-default
3840  :group 'singular-interactive-miscellaneous)
3841
3842(defvar singular-switches-last singular-switches-default
3843  "Switches of last Singular command used.
3844
3845This variable is buffer-local.")
3846
3847(defvar singular-switches-history nil
3848  "History list of Singular switches.")
3849
3850; (defvar singular-switches-magic '("-t" "--exec" "if (system(\"version\") > 1304){system(\"--emacs\", 1);};")
3851(defvar singular-switches-magic '("-t" "--emacs")
3852  "Additional magic switches for Singular process.
3853List of switch-strings which are automagically added when new Singular
3854processes are started, one string for each command line argument.
3855This list should at least contain the options \"--emacs\" and \"-t\". If
3856you are running a Singular with version < 1.2 , remove option \"--exec\"
3857from the list.")
3858
3859(defcustom singular-name-default "singular"
3860  "*Default process name for Singular process.
3861Used by `singular' when new Singular processes are started.
3862This string surrounded by \"*\" will also be the buffer name."
3863  :type 'string
3864  :initialize 'custom-initialize-default
3865  :group 'singular-interactive-miscellaneous)
3866
3867(defvar singular-name-last singular-name-default
3868  "process name of the last Singular command used.
3869
3870This variable is buffer-local.")
3871
3872(defvar singular-name-history nil
3873  "History list of Singular process names.")
3874
3875(defun singular-exec-init ()
3876  "Initialize defaults for starting Singular.
3877
3878This function is called at mode initialization time."
3879  (singular-debug 'interactive (message "Initializing exec"))
3880  (set (make-local-variable 'singular-executable-last) 
3881       singular-executable-default)
3882  (set (make-local-variable 'singular-directory-last) 
3883       singular-directory-default)
3884  (set (make-local-variable 'singular-name-last) 
3885       singular-name-default)
3886  (set (make-local-variable 'singular-switches-last)
3887       singular-switches-default)
3888  (set (make-local-variable 'singular-exit-insert-killed-marker) 
3889       nil)
3890  (set (make-local-variable 'singular-exit-cleanup-done) 
3891       nil))
3892
3893(defvar singular-exit-cleanup-done nil
3894  "Switch indicating if cleanup after Singular exit is already done.
3895Initial value is nil. Is set to t by `singular-exit-cleanup' and to nil by
3896`singular-exit-sentinel'.
3897
3898This variable is buffer-local.")
3899
3900(defun singular-exit-cleanup ()
3901  "Clean up after termination of Singular.
3902Writes back input ring after regular termination of Singular if process
3903buffer is still alive, deinstalls the library menu und calls several other
3904exit procedures.
3905Assumes that the current buffer is a Singular buffer.
3906Sets the variable `singular-exit-cleanup-done' to t.
3907
3908This function is called by `singular-kill-singular' or by
3909`singular-exit-sentinel'."
3910  (singular-debug 'interactive
3911                  (message "exit-cleanup called"))
3912  (singular-demo-exit t)
3913  (singular-scan-header-exit)
3914  (singular-menu-deinstall-libraries)
3915  (singular-history-write)
3916  (setq singular-exit-cleanup-done t))
3917
3918(defun singular-exit-sentinel (process message)
3919  "Clean up after termination of Singular.
3920Calls `singular-exit-cleanup' if `singular-exit-cleanup-done' is nil."
3921  (save-excursion
3922    (singular-debug 'interactive
3923                    (message "Sentinel: %s" (substring message 0 -1)))
3924
3925    (if (string-match "finished\\|exited\\|killed" message)
3926        (let ((process-buffer (process-buffer process)))
3927          (if (and (not singular-exit-cleanup-done)
3928                   process-buffer
3929                   (buffer-name process-buffer)
3930                   (set-buffer process-buffer))
3931              (singular-exit-cleanup))))
3932    (setq singular-exit-cleanup-done nil)))
3933
3934(defun singular-kill-singular ()
3935  "Delete the Singular process running in the current buffer.
3936Calls `singular-exit-cleanup' and deletes the Singular process.
3937Inserts a string indicating that the Singular process is killed."
3938  (let* ((process (singular-process))
3939         (mark (marker-position (process-mark process))))
3940    (singular-exit-cleanup)
3941    (delete-process process)
3942    (save-excursion
3943      ;; Because of timing problems it would be better if
3944      ;; singular-exit-sentinel would insert this string (see Version 1.41)
3945      ;; but this is not possible for XEmacs: The function (process-mark)
3946      ;; called within singular-exit-sentinel returns a mark with no
3947      ;; associated buffer!
3948      (goto-char mark)
3949      (insert "// ** Singular process killed **\n"))))
3950
3951(defun singular-control-c (mode)
3952  "Interrupt the Singular process running in the current buffer.
3953If called interactiveley, asks whether to (a)bort the current Singular
3954command, (q)uit or (r) restart the current Singular process, or (c)ontinue
3955without doing anything (default).
3956
3957If called non-interactiveley, MODE should be one of 'abort, 'quit, 'restart,
3958or 'continue."
3959  (interactive
3960   (let (answer)
3961     (while (not answer) 
3962       (setq answer (read-from-minibuffer
3963                   "(a)bort current command, (q)uit, (r)estart Singular or (c)ontinue? "))
3964       (setq answer
3965             (cond ((equal answer "a") 'abort)
3966                   ((equal answer "c") 'continue)
3967                   ((equal answer "r") 'restart)
3968                   ((equal answer "q") 'quit)
3969                   ((equal answer "") 'continue) ; default: continue
3970                   (t nil))))
3971     (list answer)))
3972   (cond
3973    ((eq mode 'quit) (singular-kill-singular))
3974    ((eq mode 'restart) (singular-restart))
3975    ((eq mode 'abort) (interrupt-process (singular-process)))))
3976
3977(defun singular-exec (buffer name executable start-file switches)
3978  "Start a new Singular process NAME in BUFFER, running EXECUTABLE.
3979EXECUTABLE should be a string denoting an executable program.
3980SWITCHES should be a list of strings that are passed as command line
3981switches.  START-FILE should be the name of a file which contents is
3982sent to the process.
3983
3984Deletes any old processes running in that buffer.
3985Removes any empty string in SWITCHES befor passing to Singular.
3986Moves point to the end of BUFFER.
3987Initializes all important markers and the simple sections.
3988Runs the hooks on `singular-exec-hook'.
3989Returns BUFFER."
3990  (let ((old-buffer (current-buffer)))
3991    (unwind-protect
3992        (progn
3993          (set-buffer buffer)
3994
3995          ;; delete any old processes
3996          (let ((process (get-buffer-process buffer)))
3997            (if process (delete-process process)))
3998
3999          ;; create new process
4000          (singular-debug 'interactive
4001                          (message "Starting new Singular: %s %s"
4002                                   executable switches))
4003          ;; before passing SWITCHES to Singuar we remove any empty strings
4004          ;; because otherwise Singular tries to open a file with an empty
4005          ;; file name.
4006          (let ((process (comint-exec-1 name buffer
4007                                        executable (delete "" switches))))
4008            ;; set process filter and sentinel
4009            (set-process-filter process 'singular-output-filter)
4010            (set-process-sentinel process 'singular-exit-sentinel)
4011            (make-local-variable 'comint-ptyp)
4012            (setq comint-ptyp process-connection-type) ; T if pty, NIL if pipe.
4013
4014            ;; go to the end of the buffer, initialize I/O and simple
4015            ;; sections
4016            (goto-char (point-max))
4017            (singular-input-filter-init (point))
4018            (singular-output-filter-init (point))
4019            (singular-simple-sec-init (point))
4020           
4021            ;; completion should be initialized before scan header!
4022            (singular-completion-init)
4023            (singular-scan-header-init)
4024            (singular-menu-init)
4025
4026            ;; feed process with start file and read input ring.  Take
4027            ;; care about the undo information.
4028            (if start-file
4029                (let ((buffer-undo-list t) start-string)
4030                  (singular-debug 'interactive (message "Feeding start file"))
4031                  (sleep-for 1)                 ; try to avoid timing errors
4032                  (insert-file-contents start-file)
4033                  (setq start-string (buffer-substring (point) (point-max)))
4034                  (delete-region (point) (point-max))
4035                  (process-send-string process start-string)))
4036
4037            ;; read history if present
4038            (singular-history-read)
4039
4040            ;; execute hooks
4041            (run-hooks 'singular-exec-hook))
4042         
4043          buffer)
4044      ;; this code is unwide-protected
4045      (set-buffer old-buffer))))
4046
4047
4048;; TODO: Documentation!
4049;; Note:
4050;;
4051;; In contrast to shell.el, `singular' does not run
4052;; `singular-interactive-mode' every time a new Singular process is
4053;; started, but only when a new buffer is created.  This behaviour seems
4054;; more intuitive w.r.t. local variables and hooks.
4055
4056(defun singular-internal (executable directory switches name)
4057  "Run an inferior Singular process, with I/O through an Emacs buffer.
4058
4059Appends `singular-switches-magic' to switches.
4060Sets default-directory if directory is not-nil.
4061Sets singular-*-last values."
4062  (singular-debug 'interactive
4063                  (message "singular-internal: %s %s %s %s"
4064                           executable directory name switches))
4065  (let* ((buffer-name (singular-process-name-to-buffer-name name))
4066         ;; buffer associated with Singular, nil if there is none
4067         (buffer (get-buffer buffer-name)))
4068   
4069    ;; If directory is set, make sure that it ends in a "/" at the end.
4070    ;; The check is done on both slash and backslash, but we unconditionally
4071    ;; insert a slash. Hopefully that works on NT, too.
4072    (and directory
4073         (not (memq (aref directory (1- (length directory))) '(?/ ?\\)))
4074         (setq directory (concat directory "/")))
4075   
4076    (if (not buffer)
4077        (progn
4078          ;; create new buffer and call `singular-interactive-mode'
4079          (singular-debug 'interactive (message "Creating new buffer"))
4080          (setq buffer (get-buffer-create buffer-name))
4081          (set-buffer buffer)
4082          (and directory
4083               (setq default-directory directory))
4084         
4085          (singular-debug 'interactive (message "Calling `singular-interactive-mode'"))
4086          (singular-interactive-mode)))
4087   
4088    (if (not (comint-check-proc buffer))
4089        ;; create new process if there is none
4090        (singular-exec buffer name executable
4091                       (if (file-exists-p singular-start-file)
4092                           singular-start-file)
4093                       (append switches singular-switches-magic)))
4094   
4095    ;; pop to buffer
4096    (singular-debug 'interactive (message "Calling `pop-to-buffer'"))
4097    (singular-pop-to-buffer singular-same-window buffer))
4098
4099  ;; Set buffer local singular-*-last-values
4100  (setq singular-executable-last executable)
4101  (setq singular-directory-last directory)
4102  (setq singular-switches-last switches)
4103  (setq singular-name-last name)
4104  ;; Set global values, too
4105  (set-default 'singular-executable-last executable)
4106  (set-default 'singular-directory-last directory)
4107  (set-default 'singular-switches-last switches)
4108  (set-default 'singular-name-last name))
4109
4110(defun singular-generate-new-buffer-name (name)
4111  "Generate a unique buffer name for a singular interactive buffer.
4112The string NAME is the desired name for the singular interactive
4113buffer, without surrounding stars.
4114The string returned is surrounded by stars.
4115
4116If no buffer with name \"*NAME*\" exists, return \"*NAME*\".
4117Otherwise check for buffer called \"*NAME<n>*\" where n is a
4118increasing number and return \"*NAME<n>*\" if no such buffer
4119exists."
4120  (let ((new-name (singular-process-name-to-buffer-name name)) 
4121        (count 2))
4122    (while (get-buffer new-name)
4123      (setq new-name (singular-process-name-to-buffer-name
4124                      (concat name "<" (format "%d" count) ">")))
4125      (setq count (1+ count)))
4126    new-name))
4127
4128(defun singular ()
4129  "Run an inferior Singular process using default arguments. 
4130Starts a Singular process, with I/O through an Emacs buffer, using the
4131values of `singular-executable-default', `singular-directory-default',
4132`singular-switches-default', and `singular-name-default'.
4133
4134For more information on starting a Singular process and on the arguments
4135see the documentation of `singular-other'. To restart a previously started
4136Singular process use `singular-restart'.
4137
4138Every time `singular' starts a new Singular process it runs the hooks
4139on `singular-exec-hook'.
4140
4141Type \\[describe-mode] in the Singular buffer for a list of commands."
4142  (interactive)
4143  (singular-internal singular-executable-default
4144                     singular-directory-default
4145                     singular-switches-default
4146                     singular-name-default))
4147
4148(defun singular-restart ()
4149  "Run an inferior Singular process using the last arguments used.
4150Starts a Singular process, with I/O through an Emacs buffer, using the
4151previously used arguments.
4152If called within a Singular buffer, uses the arguments of the most recent
4153Singular process started in this buffer. If there is a Singular process
4154running in this buffer, it is deleted without warning!
4155If called outside a Singular buffer, uses the arguments of the most recent
4156Singular process started in any Singular buffer (and does not delete any
4157Singular process).
4158If no last values are available, uses the default values (see documentation
4159of `singular').
4160
4161For more information on starting a Singular process and on the arguments
4162see the documentation of `singular-other'.
4163
4164Every time `singular-restarts' starts a new Singular process it runs the
4165hooks on `singular-exec-hook'.
4166
4167Type \\[describe-mode] in the Singular buffer for a list of commands."
4168  (interactive)
4169
4170  (if (singular-process t)
4171      (singular-kill-singular))
4172     
4173  (singular-internal singular-executable-last
4174                     singular-directory-last
4175                     singular-switches-last
4176                     singular-name-last))
4177
4178(defun singular-other (executable directory switches name)
4179  "Run an inferior Singular process.
4180Starts a Singular process, with I/O through an Emacs buffer.
4181
4182If called interactively, the user is asked in the minibuffer area for an
4183existing executable (with or without path), an exisiting directory or nil
4184(if non-nil, sets the buffers default directory to this directory), the
4185complete command line arguments to be passed to Singular (as a single
4186string) and the buffer name of the singular buffer, which is surrounded by
4187\"*\", if not already. (The process name of the singular process is then
4188given by the buffer name with the surrounding stars stripped.)
4189
4190If called non-interactiveley, EXECUTABLE is the name of an existing
4191Singular executable (with or without path), DIRECTORY is the name of an
4192existing directory or nil. If non-nil, sets the buffers default directory
4193to DIRECTORY. SWITCHES is a list of strings where each string contains one
4194command line argument which is passed to Singular, and NAME is the process
4195name of the Singular process (that is, the singular buffer name is given by
4196NAME surrounded by \"*\").
4197
4198If buffer exists but Singular is not running, starts new Singular.
4199If buffer exists and Singular is running, just switches to buffer.
4200If a file `~/.emacs_singularrc' exists, it is given as initial input.
4201Note that this may lose due to a timing error if Singular discards
4202input when it starts up.
4203
4204If a new buffer is created it is put in Singular interactive mode,
4205giving commands for sending input and handling output of Singular.  See
4206`singular-interactive-mode'.
4207
4208Every time `singular-other' starts a new Singular process it runs the hooks
4209on `singular-exec-hook'.
4210
4211Type \\[describe-mode] in the Singular buffer for a list of commands."
4212  (interactive 
4213   (let* ((exec (read-file-name "Singular executable: "))
4214         ;; Remark: Do NOT call `expand-file-name' after the
4215         ;; above read-file-name! It has to be possible to enter a command
4216         ;; without path which should be searched for in $PATH.
4217         ;; `start-process' is intelligent enough to start commands with
4218         ;; not-expanded name.
4219          (dir (file-name-directory (read-file-name "Default directory: "
4220                                                    nil 
4221                                                    (or singular-directory-default
4222                                                        default-directory)
4223                                                    t)))
4224         (switch "")
4225         (bufname (singular-generate-new-buffer-name 
4226                   (downcase (file-name-nondirectory exec)))))
4227
4228     ;; Get command line arguments and append magic switches
4229     ;; TODO: Think about default value: Up to now:
4230     ;; Use singular-switches-default as init value for read-from-minibuffer
4231     (let ((switches-default singular-switches-default))
4232       (while switches-default
4233         (setq switch (concat switch (car switches-default) " "))
4234         (setq switches-default (cdr switches-default))))
4235     ;; note: magic switches are appended by `singular-internal'
4236     (setq switch (split-string (read-from-minibuffer "Singular options: "
4237                                                      switch nil nil 
4238                                                      singular-switches-history)
4239                                " "))
4240     ;; Generate new buffer name
4241     (let (done)
4242       (while (not done)
4243         (setq bufname (read-from-minibuffer "Singular buffer name: " bufname))
4244         (setq done (or (not (get-buffer bufname))
4245                        (y-or-n-p "Buffer exists. Switch to that buffer? ")))))
4246     (if (string-match "^\\*\\(.*\\)\\*$" bufname)
4247         (setq bufname (substring bufname (match-beginning 1) (match-end 1))))
4248     (list exec dir switch bufname)))
4249
4250  (singular-internal executable directory switches name))
4251
4252(defun singular-exit-singular (&optional kill-singular-buffer)
4253  "Delete Singular process and kill Singular buffer.
4254Deletes the buffers Singular process without warning and writes back the input
4255history to file.
4256If called with prefix argument, kills the Singular buffer."
4257  (interactive "P")
4258  (singular-debug 'interactive
4259                  (message "exit singular called"))
4260 
4261  (singular-kill-singular)
4262  (if kill-singular-buffer
4263      (kill-buffer (current-buffer))))
4264;;}}}
4265;;}}}
4266
4267(provide 'singular)
4268
4269;;; Local Variables:
4270;;; fill-column: 75
4271;;; End:
4272
4273;;; singular.el ends here.
Note: See TracBrowser for help on using the repository browser.