source: git/emacs/singular.el @ 6e3bdda

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