Initial Commit
[packages] / xemacs-packages / ess / lisp / ess-inf.el
1 ;;; ess-inf.el --- Support for running S as an inferior Emacs process
2
3 ;; Copyright (C) 1989-1994 Bates, Kademan, Ritter and Smith
4 ;; Copyright (C) 1997-1999 A.J. Rossini <rossini@u.washington.edu>,
5 ;; Martin Maechler <maechler@stat.math.ethz.ch>.
6 ;; Copyright (C) 2000--2005 A.J. Rossini, Rich M. Heiberger, Martin
7 ;;      Maechler, Kurt Hornik, Rodney Sparapani, and Stephen Eglen.
8
9 ;; Original Author: David Smith <dsmith@stats.adelaide.edu.au>
10 ;; Created: 7 Jan 1994
11 ;; Maintainers: ESS-core <ESS-core@stat.math.ethz.ch>
12
13 ;; This file is part of ESS
14
15 ;; This file is free software; you can redistribute it and/or modify
16 ;; it under the terms of the GNU General Public License as published by
17 ;; the Free Software Foundation; either version 2, or (at your option)
18 ;; any later version.
19
20 ;; This file is distributed in the hope that it will be useful,
21 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
22 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 ;; GNU General Public License for more details.
24
25 ;; You should have received a copy of the GNU General Public License
26 ;; along with GNU Emacs; see the file COPYING.  If not, write to
27 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
28
29 ;;; Commentary:
30
31 ;; Code for handling running ESS processes.
32
33 ;;; Code:
34
35 \f ; Requires and autoloads
36
37 ;;*;; Requires
38 (require 'ess-site)
39
40 ;; Byte-compiler, SHUT-UP!
41 (eval-and-compile
42   (require 'comint)
43   (require 'ess-utils))
44
45 ;;*;; Autoloads
46 (autoload 'ess-parse-errors                 "ess-mode"  "(autoload)." t)
47 (autoload 'ess-dump-object-into-edit-buffer "ess-mode"  "(autoload)." t)
48 (autoload 'ess-beginning-of-function        "ess-mode"  "(autoload)." t)
49 (autoload 'ess-end-of-function              "ess-mode"  "(autoload)." t)
50 (autoload 'ess-extract-word-name            "ess-utils" "(autoload)." t)
51 (autoload 'ess-uniq-list                    "ess-utils" "(autoload)." t)
52
53 (autoload 'ess-transcript-send-command-and-move "ess-trns" "(autoload)." t)
54
55 \f ;;*;; Process handling
56
57 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
58 ;;;; In this section:
59 ;;;;
60 ;;;; * User commands for starting an ESS process
61 ;;;; * Functions called at startup
62 ;;;; * Process handling code
63 ;;;; * Multiple process implementation
64 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
65
66
67 ;;*;; Starting a process
68
69 (defun ess-proc-name (n name)
70   "Return name of process N, as a string, with NAME prepended."
71   (if ess-plain-first-buffername
72       (if (> n 1)
73           (concat name ":" (number-to-string n))
74         (concat name))
75     (concat name ":" (number-to-string n))))
76
77 (defun inferior-ess (&optional ess-start-args)
78   "Start inferior ESS process.
79
80 Without a prefix argument, starts a new ESS process, or switches
81   to the ESS process associated with the current buffer.
82 With a prefix, starts the process with those args.
83 The current buffer is used if it is an `inferior-ess-mode'
84 or `ess-transcript-mode' buffer.
85
86 If `ess-ask-about-transfile' is non-nil, you will be asked for a
87 transcript file to use. If there is no transcript file, the buffer
88 name will be like *S* or *S2*.
89
90 Takes the program name from the variable `inferior-ess-program'.
91 An initialization file (dumped into the process) is specified by
92 `inferior-ess-start-file', and `inferior-ess-start-args' is used to
93 accompany the call for `inferior-ess-program'.
94
95 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
96
97   ;; Use the current buffer if it is in inferior-ess-mode or ess-trans-mode
98   ;; If not, maybe ask about starting directory and/or transcript file.
99   ;; If no transfile, use buffer *S*
100   ;;
101   ;; This function is primarily used to figure out the Process and
102   ;; buffer names to use for inferior-ess.
103
104   ;; Once, long ago, it was used for switching buffers, but we don't
105   ;; do that any more (at least not from here).
106
107   (interactive)
108
109   (ess-write-to-dribble-buffer
110      (format "(inferior-ess 0): ess-start-args=%s \n" ess-start-args))
111
112   ;; set up for current language (need here, to get ess-language, etc).
113
114   ;; Couldn't we rather set all the default values or Local values now ?
115   ;;>>> (ess-setq-vars-default ess-customize-alist (current-buffer))
116   ;;>>> (ess-setq-vars-local   ess-customize-alist (current-buffer))
117   ;;; AJR sez: I think we should set them later; don't want to nuke if
118   ;;; I don't have to.
119   ;;- MM: We shouldn't have to use  ess-setq-vars-default _at all_ ;
120   ;;      only do the buffer local ...-vars-local ones
121   (let ((temp-ess-dialect (eval (cdr (assoc 'ess-dialect
122                                        ess-customize-alist))))
123         (temp-ess-lang (eval (cdr (assoc 'ess-language
124                                        ess-customize-alist)))))
125     (save-excursion
126       ;;- Is this needed? (no, but it's useful to see them there [MM])
127       (set-buffer ess-dribble-buffer)
128       ;; Hack to work around the following "default" (global) setting of vars:
129       ;; make sure our comint-... hack doesn't affect anything else
130       (make-variable-buffer-local 'comint-use-prompt-regexp-instead-of-fields)
131       ;; now the abomination:
132       (ess-setq-vars-default ess-customize-alist)
133
134       (setq-default comint-use-prompt-regexp-instead-of-fields nil); re set HACK!
135       ;;>> Doesn't set ess-language,
136       ;;>> => comint-input-sender is not set to 'ess-input-  ==> no input echo!
137       ;;>> => that's why things fail:
138       ;;>> (ess-setq-vars-local ess-customize-alist (current-buffer))
139       ;;                 ======
140       ;;MM --- why set them here again when already "(let ..)" above ?
141       ;;   --> trying without (comment the following 4 lines):
142       ;; (setq temp-ess-dialect
143       ;;    (eval(cdr(assoc 'ess-dialect ess-customize-alist))))
144       ;; (setq temp-ess-lang
145       ;;    (eval(cdr(assoc 'ess-language ess-customize-alist))))
146       )
147
148     ;; run hooks now, to overwrite the above!
149     (run-hooks 'ess-pre-run-hook)
150     (ess-write-to-dribble-buffer
151      (format "(inf-ess 1): lang=%s, dialect=%s, tmp-dialect=%s, buf=%s\n"
152              ess-language ess-dialect temp-ess-dialect (current-buffer)))
153     (let* ((process-environment process-environment)
154            (defdir (or (and ess-directory-function (funcall ess-directory-function))
155                        ess-directory default-directory))
156            (temp-dialect temp-ess-dialect)
157            (temp-lang temp-ess-lang)
158            (procname (let ((ntry 0) ;; find a non-existent process
159                            (done nil))
160                        (while (not done)
161                          (setq ntry (1+ ntry)
162                                done (not
163                                      (get-process (ess-proc-name
164                                                    ntry
165                                                    temp-dialect)))))
166                        (ess-proc-name ntry temp-dialect)))
167            (startdir nil)
168            (buf nil)
169            (buf-name-str  (concat "*" procname "*")))
170
171       (ess-write-to-dribble-buffer
172        (format "(inf-ess 1.1): procname=%s temp-dialect=%s, buf-name=%s \n"
173                procname
174                temp-dialect
175                buf-name-str))
176       (cond
177        ;; Since it's a new or terminated process, try to use current buffer
178        ((and (not buf)
179              (not (comint-check-proc (current-buffer)))
180              (memq major-mode '(inferior-ess-mode)))
181         (setq startdir
182               (if ess-ask-for-ess-directory
183                   (ess-get-directory (directory-file-name defdir))
184                   defdir))
185         (setq buf (current-buffer))
186         (ess-write-to-dribble-buffer
187          (format "(inferior-ess) Method #1 start=%s buf=%s\n" startdir buf)))
188
189        ;;  Not an ESS buffer yet
190        ((and (not buf)
191              (get-buffer buf-name-str))
192         (setq buf (get-buffer buf-name-str))
193         (ess-write-to-dribble-buffer
194          (format "(inferior-ess) Method #2 buf=%s\n" buf)))
195
196        ;; Ask for transcript file and startdir
197        ;; FIXME -- this should be in ess-get-transfile
198        ;; AJR: Why?  I'm not clear about the logic, i.e. when would it
199        ;;      be used again, to justify?
200        ((not buf)
201         (setq startdir
202               (if ess-ask-for-ess-directory
203                   (ess-get-directory (directory-file-name defdir))
204                   defdir))
205         (if ess-ask-about-transfile
206             (let ((transfilename (read-file-name
207                                   "Use transcript file (default none):"
208                                   startdir "")))
209               (setq buf (if (string= transfilename "")
210                             (get-buffer-create buf-name-str)
211                           (find-file-noselect (expand-file-name
212                                                transfilename)))))
213           (setq buf (get-buffer-create buf-name-str)))
214         (ess-write-to-dribble-buffer
215          (format "(inferior-ess) Method #3 start=%s buf=%s\n" startdir buf))))
216
217       (set-buffer buf)
218       ;; Now that we have the buffer, set buffer-local variables.
219       (ess-setq-vars-local ess-customize-alist); buf)
220       (if ess-start-args (setq inferior-ess-start-args ess-start-args))
221       ;; Was:  if not, set to null.
222       ;;(setq inferior-ess-start-args "")) ;; AJR: Errors with XLS?
223       ;; I think I might have solved this?
224
225       ;; Write out debug info
226       (ess-write-to-dribble-buffer
227        (format "(inf-ess 2.1): ess-language=%s, ess-dialect=%s buf=%s \n"
228                ess-language
229                ess-dialect
230                (current-buffer)))
231       (ess-write-to-dribble-buffer
232        (format "(inf-ess 2.2): start args = %s, inf-ess-start-args=%s \n"
233                ess-start-args
234                inferior-ess-start-args))
235       (ess-write-to-dribble-buffer
236        (format "(inf-ess finish [%s(%s), %s(%s,%s)]\n"
237                ess-language
238                ess-dialect
239                inferior-ess-program
240                ess-current-process-name
241                ess-local-process-name))
242
243       ;; Start from the "right" directory
244       (if startdir (setq default-directory startdir))
245       ;; Set up history
246       (setq-default ess-history-file
247                     (concat "." ess-dialect "history"))
248       ;; initialize.
249       (let ((ess-directory (if startdir default-directory ess-directory)))
250         (ess-multi procname buf inferior-ess-start-args)))))
251
252
253 (defvar inferior-ess-objects-command nil
254   "The language/dialect specific command for listing objects.
255 It is initialized from the corresponding inferior-<lang>-objects-command
256 and then made buffer local."); and the *-<lang>-* ones are customized!
257 (make-variable-buffer-local 'inferior-ess-objects-command)
258
259 (defvar ess-save-lastvalue-command nil
260   "The command to save the last value.  See S section for more details.
261 Default depends on the ESS language/dialect and hence made buffer local")
262 (make-variable-buffer-local 'ess-save-lastvalue-command)
263
264 (defvar ess-retr-lastvalue-command nil
265   "The command to retrieve the last value.  See S section for more details.
266 Default depends on the ESS language/dialect and hence made buffer local")
267 (make-variable-buffer-local 'ess-retr-lastvalue-command)
268
269 ;;; A note on multiple processes: the following variables
270 ;;;     ess-local-process-name
271 ;;;     ess-search-list
272 ;;;     ess-sl-modtime-alist
273 ;;;     ess-sp-change
274 ;;;     ess-prev-load-dir/file
275 ;;;     ess-directory
276 ;;;     ess-object-list
277 ;;; are specific to each ess-process and are buffer-local variables
278 ;;; local to the ESS process buffer. If required, these variables should
279 ;;; be accessed with the function ess-get-process-variable
280
281 (defun ess-multi (name &optional buffer inf-ess-start-args)
282   "Start or switch to ESS process named NAME in the buffer BUFFER.
283 BUFFER is only needed if process NAME is not running. BUFFER must
284 exist.  Default-directory is the ESS starting directory. BUFFER may be
285 visiting a file.
286
287 If ess-process NAME is running, switch to it.  If not, use COMINT to
288 start up a new process, using NAME and BUFFER (which is needed if
289 there is no process NAME)."
290
291   (let* ((proc-name name)
292          (special-display-regexps nil)
293          (special-display-frame-alist inferior-ess-frame-alist)
294          (proc (get-process proc-name)))
295     (if inferior-ess-own-frame
296         (setq special-display-regexps '(".")))
297     ;; If ESS process NAME is running, switch to it
298     (if (and proc (comint-check-proc (process-buffer proc)))
299         (pop-to-buffer (process-buffer proc))
300       ;; Otherwise, crank up a new process
301       (let* ((symbol-string
302               (concat "inferior-" inferior-ess-program "-args"))
303              (switches-symbol (intern-soft symbol-string))
304              (switches
305               (if (and switches-symbol (boundp switches-symbol))
306                   (symbol-value switches-symbol)))
307              (buf-name-str (buffer-name buffer)))
308         (ess-write-to-dribble-buffer
309          (format "(ess-multi 0):  inf-ess-start-args=%s, comint-..echoes=%s\n"
310                inf-ess-start-args comint-process-echoes))
311         (set-buffer buffer)
312         (inferior-ess-mode)
313         (ess-write-to-dribble-buffer
314          (format "(ess-multi post inf-ess: start-args=%s, comint-echoes=%s\n"
315                inf-ess-start-args comint-process-echoes))
316         (setq ess-local-process-name proc-name)
317         (goto-char (point-max))
318         ;; load past history
319         (setq comint-input-ring-file-name
320               (expand-file-name ess-history-file ess-directory))
321         (comint-read-input-ring)
322         ;; create and run process.
323         (ess-write-to-dribble-buffer
324          (format "(ess-multi 1):  start-args=%s \n"
325                inf-ess-start-args))
326         (set-buffer
327          (if switches
328              (inferior-ess-make-comint buf-name-str
329                                        proc-name
330                                        inf-ess-start-args
331                                        switches)
332            (inferior-ess-make-comint buf-name-str
333                                      proc-name
334                                      inf-ess-start-args)))
335         ;; Set the process sentinel to save the history
336         (set-process-sentinel (get-process proc-name) 'ess-process-sentinel)
337         ;; Add this process to ess-process-name-list, if needed
338         (let ((conselt (assoc proc-name ess-process-name-list)))
339           (if conselt nil
340             (setq ess-process-name-list
341                   (cons (cons proc-name nil) ess-process-name-list))))
342         (ess-make-buffer-current)
343         (inferior-ess-wait-for-prompt)
344         (goto-char (point-max))
345         (setq ess-sl-modtime-alist nil)
346         ;; Get search list when needed
347         (setq ess-sp-change t)
348
349         ;; Add the process filter to catch certain output.
350         (set-process-filter (get-process proc-name)
351                             'inferior-ess-output-filter)
352         
353         (run-hooks 'ess-post-run-hook))
354       (if (and inferior-ess-same-window (not inferior-ess-own-frame))
355           (switch-to-buffer (process-buffer (get-process proc-name)))
356         (pop-to-buffer (process-buffer (get-process proc-name)))))))
357
358 (defun inferior-ess-output-filter (proc string)
359   "Standard output filter for the inferior ESS process.
360 Ring Emacs bell if process output starts with an ASCII bell, and pass
361 the rest to `comint-output-filter'.
362 Taken from octave-mod.el."
363   (comint-output-filter proc (inferior-ess-strip-ctrl-g string)))
364
365 (defun inferior-ess-strip-ctrl-g (string)
366   "Strip leading `^G' character.
367 If STRING starts with a `^G', ring the Emacs bell and strip it.
368 Depending on the value of `visible-bell', either the frame will
369 flash or you'll hear a beep.  Taken from octave-mod.el."
370   (if (string-match "^\a" string)
371       (progn
372         (ding)
373         (setq string (substring string 1))))
374   string)
375
376
377 (defun ess-process-sentinel (proc message)
378   "Sentinel for use with ESS processes.
379 This marks the process with a message, at a particular time point."
380   (save-excursion
381     (setq message (substring message 0 -1)) ; strip newline
382     (set-buffer (process-buffer proc))
383     (comint-write-input-ring)
384     (goto-char (point-max))
385     (insert-before-markers
386      (format "\nProcess %s %s at %s\n"
387              (process-name proc) message (current-time-string)))))
388
389 (defun inferior-ess-make-comint (bufname
390                                  procname
391                                  inferior-ess-start-args
392                                  &rest switches)
393   "Make an S comint process in buffer BUFNAME with process PROCNAME.
394 This was rewritten by KH in April 1996."
395 ;;; This function is a modification of make-comint from the comint.el
396 ;;; code of Olin Shivers.
397   (let*  ((buffer (get-buffer-create bufname))
398           (proc (get-process procname)))
399     ;; If no process, or nuked process, crank up a new one and put buffer in
400     ;; comint mode. Otherwise, leave buffer and existing process alone.
401     (cond ((or (not proc) (not (memq (process-status proc) '(run stop))))
402            (save-excursion
403              (set-buffer buffer)
404              (if ess-directory (setq default-directory ess-directory))
405              (if (eq (buffer-size) 0) nil
406                (goto-char (point-max))
407                (insert "\^L\n")))    ; page boundaries = Interactive sessions
408            (let ((process-environment
409                   (nconc
410                    (list "STATATERM=emacs"
411                          (format "PAGER=%s" inferior-ess-pager))
412                    process-environment)))
413              (ess-write-to-dribble-buffer "Making Process...")
414              (ess-write-to-dribble-buffer
415               (format "Buf %s, Proc %s, Prog %s\n Start File=%s, Args= %s.\n"
416                       buffer
417                       procname
418                       inferior-ess-program
419                       inferior-ess-start-file
420                       inferior-ess-start-args))
421              (comint-exec buffer
422                           procname
423                           inferior-ess-program
424                           inferior-ess-start-file
425                           (ess-line-to-list-of-words
426                            inferior-ess-start-args)))))
427     buffer))
428
429
430 ;;*;; Requester functions called at startup
431
432 ;(defun ess-get-directory-ORIG (default)
433 ;  "Request and return S starting directory."
434 ;  (let ((the-dir
435 ;        (expand-file-name
436 ;         (file-name-as-directory
437 ;          (read-file-name
438 ;           (format "ESS [%s(%s): %s] starting data directory? "
439 ;                   ess-language ess-dialect inferior-ess-program)
440 ;           (file-name-as-directory default)
441 ;           (file-name-as-directory default) t nil)))))
442 ;    (if (file-directory-p the-dir) nil
443 ;      (error "%s is not a valid directory" the-dir))
444 ;    the-dir))
445
446 (defun ess-get-directory (default)
447   (ess-prompt-for-directory
448         default
449         (format "ESS [%s(%s): %s] starting data directory? "
450                 ess-language ess-dialect inferior-ess-program)))
451
452 (defun ess-prompt-for-directory (default prompt)
453   "`prompt' for a directory, using `default' as the usual."
454   (let ((the-dir
455          (expand-file-name
456           (file-name-as-directory
457            (if (fboundp 'read-directory-name)
458                ;; use XEmacs' read-directory-name if exists.
459                (read-directory-name prompt
460                                     (file-name-as-directory default)
461                                     (file-name-as-directory default) t nil)
462            (read-file-name prompt
463                            (file-name-as-directory default)
464                              (file-name-as-directory default) t nil))))))
465     (if (file-directory-p the-dir) nil
466       (error "%s is not a valid directory" the-dir))
467     the-dir))
468
469
470 ;;*;; General process handling code
471
472 (defun get-ess-process (name)
473   "Return the ESS process named by NAME."
474   (update-ess-process-name-list)
475   (if (null name)
476       (error "No ESS process is associated with this buffer now.")
477     (if (assoc name ess-process-name-list)
478         (get-process name)
479       (error "Process %s is not running." name))))
480
481 (defun inferior-ess-wait-for-prompt ()
482   "Wait until the ESS process is ready for input."
483   (let* ((cbuffer (current-buffer))
484          (sprocess (get-ess-process ess-current-process-name))
485          (sbuffer (process-buffer sprocess))
486          (r nil)
487          (timeout 0))
488     (set-buffer sbuffer)
489     (while (progn
490              (if (not (eq (process-status sprocess) 'run))
491                  (ess-error "ESS process has died unexpectedly.")
492                (if (> (setq timeout (1+ timeout)) ess-loop-timeout)
493                    (ess-error "Timeout waiting for prompt. Check inferior-ess-prompt or ess-loop-timeout."))
494                (accept-process-output)
495                (goto-char (point-max))
496                (beginning-of-line); bol ==> no need for "^" in *-prompt! (MM?)
497                ;; above, except for Stata, which has "broken" i/o,
498                ;; sigh... (AJR)
499                (setq r (looking-at inferior-ess-prompt))
500                (not (or r (looking-at ".*\\?\\s *"))))))
501     (goto-char (point-max))
502     (set-buffer cbuffer)
503     (symbol-value r)))
504
505 ;;--- Unfinished idea (ESS-help / R-help ) -- probably not worth it...
506 ;;- (defun ess-set-inferior-program-name (filename)
507 ;;-   "Allows to set or change `inferior-ess-program', the program (file)name."
508 ;;-   (interactive "fR executable (script) file: ")
509 ;;-   ;; "f" : existing file {file name completion} !
510 ;;-   (setq inferior-ess-program filename))
511 ;; the inferior-ess-program is initialized in the customize..alist,
512 ;; e.g. from  inferior-R-program-name ... --> should change rather these.
513 ;; However these really depend on the current ess-language!
514 ;; Plan: 1) must know and use ess-language
515 ;;       2) change the appropriate  inferior-<ESSlang>-program-name
516 ;; (how?) in R/S : assign(paste("inferior-",ESSlang,"-p...."),  filename))
517
518 ;;*;; Multiple process handling code
519
520 (defun ess-make-buffer-current nil
521   "Make the process associated with the current buffer the current ESS process.
522 Returns the name of the process, or nil if the current buffer has none."
523   (update-ess-process-name-list)
524   (if ess-local-process-name
525       (setq ess-current-process-name ess-local-process-name))
526   ess-local-process-name)
527
528 (defun ess-get-process-variable (name var)
529   "Return the variable VAR (symbol) local to ESS process called NAME (string)."
530   (save-excursion
531     (set-buffer (process-buffer (get-ess-process name)))
532     (symbol-value var)))
533
534 (defun ess-set-process-variable (name var val)
535   "Set variable VAR (symbol) local to ESS process called NAME (string) to VAL."
536   (save-excursion
537     (set-buffer (process-buffer (get-ess-process name)))
538     (set var val)))
539
540 (defun ess-request-a-process (message &optional noswitch)
541   "Ask for a process, and make it the current ESS process.
542 Also switches to the process buffer unless NOSWITCH is non-nil.  Interactively,
543 NOSWITCH can be set by giving a prefix argument.
544 Returns the name of the selected process."
545   (interactive
546    (list "Switch to which ESS process? " current-prefix-arg)) ;prefix sets 'noswitch
547   (update-ess-process-name-list)
548   (if (eq (length ess-process-name-list) 0)
549       (error "No ESS processes running."))
550   (let ((proc (completing-read message
551                                ess-process-name-list
552                                nil ; predicate
553                                'require-match
554                                ;; If in S buffer, don't offer current process
555                                (if (eq major-mode 'inferior-ess-mode)
556                                    ess-language
557                                  ess-current-process-name
558                                  ;; maybe ess-local-process-name IF exists?
559                                  ))))
560     (save-excursion
561       (set-buffer (process-buffer (get-process proc)))
562       (ess-make-buffer-current))
563     (if noswitch
564         nil
565       (ess-show-buffer (buffer-name (process-buffer (get-process proc))) t))
566     proc))
567
568 (defun ess-force-buffer-current (prompt &optional force)
569   "Make sure the current buffer is attached to an ESS process.
570 If not, or  FORCE (prefix argument) is non-nil,
571 prompt for a process name with PROMPT.
572 `ess-local-process-name' is set to the name of the process selected.
573 `ess-dialect' is set to the dialect associated with the process selected."
574   (interactive
575    (list (concat ess-dialect " process to use: ") current-prefix-arg))
576   (if (and (not force) (ess-make-buffer-current))
577       nil ; do nothing
578     ;; Make sure the source buffer is attached to a process
579     (if (and ess-local-process-name (not force))
580         (error "Process %s has died." ess-local-process-name)
581       ;; ess-local-process-name is nil -- which process to attach to
582       (save-excursion
583         (let ((proc (ess-request-a-process prompt 'no-switch))
584               dialect)
585           (save-excursion
586             (set-buffer (process-buffer (get-process proc)))
587             (setq dialect ess-dialect))
588           (setq ess-local-process-name proc)
589           (setq ess-dialect dialect))))))
590
591 (defun ess-switch-process ()
592   "Force a switch to a new underlying process."
593   (interactive)
594   (ess-force-buffer-current "Process to use: " t))
595
596 ;;*;;; Commands for switching to the process buffer
597
598 (defun ess-switch-to-ESS (eob-p)
599   "Switch to the current inferior ESS process buffer.
600 With (prefix) EOB-P non-nil, positions cursor at end of buffer.
601 This function should follow the description in `ess-show-buffer'
602 for showing the iESS buffer, except that the iESS buffer is also
603 made current."
604   (interactive "P")
605   (ess-make-buffer-current)
606   (if (and ess-current-process-name (get-process ess-current-process-name))
607       (progn
608         ;; Display the buffer, but don't select it yet.
609         (ess-show-buffer
610          (buffer-name (process-buffer (get-process ess-current-process-name)))
611          t)
612         (if eob-p (goto-char (point-max))))
613     (message "No inferior ESS process")
614     (ding)))
615
616 (defun ess-switch-to-end-of-ESS ()
617   "Switch to the end of the inferior ESS process buffer."
618   (interactive)
619   (ess-switch-to-ESS t))
620
621 (defun get-ess-buffer (name)
622   "Return the buffer associated with the ESS process named by NAME."
623   (process-buffer (get-ess-process name)))
624
625 (defun update-ess-process-name-list ()
626   "Remove names with no process."
627   (let (defunct)
628     (mapcar
629      '(lambda (conselt)
630         (let ((proc (get-process (car conselt))))
631           (if (and proc (eq (process-status proc) 'run)) nil
632             (setq defunct (cons conselt defunct)))))
633      ess-process-name-list)
634     (mapcar
635      '(lambda (pointer)
636         (setq ess-process-name-list (delq pointer ess-process-name-list)))
637      defunct))
638   (if (eq (length ess-process-name-list) 0)
639       (setq ess-current-process-name nil)))
640
641 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
642 ;; ess-show-buffer
643 ;; Something like this almost works, but problems with XEmacs and Emacs
644 ;; differing implementations of the args to display-buffer make this
645 ;; too tough to pursue.  The longer version below works.
646 ;; (defun ess-show-buffer (buf)
647 ;;   "Display the buffer BUF, a string, but do not select it.
648 ;; Returns the window corresponding to the buffer."
649 ;;   ;; On XEmacs, I get an error if third arg to display-buffer is t and
650 ;;   ;; the BUF is in another frame.  Emacs does not have this problem.
651 ;;   (if (featurep 'xemacs)
652 ;;       (display-buffer buf nil (get-frame-for-buffer buf))
653 ;;     (display-buffer buf nil t)))
654 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
655 (defun ess-show-buffer (buf &optional visit)
656   "Ensure the ESS buffer BUF is visible.
657 The buffer, specified as a string, is typically an iESS (e.g. *R*) buffer.
658
659 This handles several cases:
660
661 1. If BUF is visible in the current frame, nothing is done.
662 2. If BUF is visible in another frame, then we ensure that frame is
663 visible (it may have been iconified).
664 3. If buffer is not visible in any frame, simply show it in another window
665 in the current frame.
666
667 Iff VISIT is non-nil, as well as making BUF visible, we also select it
668 as the current buffer."
669   (let ( (frame))
670     (if (ess-buffer-visible-this-frame buf)
671         ;;1. Nothing to do, BUF visible in this frame; just return window
672         ;; where this buffer is.
673         t
674
675       ;; 2. Maybe BUF visible in another frame.
676       (setq frame (ess-buffer-visible-other-frame buf))
677       (if frame
678           ;; BUF is visible in frame, so just check frame is raised.
679           (if (not (eq (frame-visible-p frame) t))
680               ;; frame is not yet visible, so raise it.
681               (raise-frame frame))
682         ;; 3. else BUF not visible in any frame, so show it (but do
683         ;; not select it) in another window in current frame.
684         (display-buffer buf)))
685     ;; At this stage, the buffer should now be visible on screen,
686     ;; although it won't have been made current.
687     (if visit
688         (progn
689           ;; Need to select the buffer.
690           ;;
691           ;; First of all, check case 2 if buffer is in another frame
692           ;; but that frame may not be selected.
693           (if (and frame (not (featurep 'xemacs)))
694               (progn
695                 ;; need to select the frame
696                 (select-frame frame)
697                 ;; reposition mouse to make frame active.
698                 (set-mouse-position (selected-frame) (1- (frame-width)) 0)))
699           (select-window (get-buffer-window buf 0))))))
700
701
702 ;; The next few functions are copied from my (SJE) iswitchb library.
703 (defun ess-get-bufname (win)
704   "Used by `ess-get-buffers-in-frames' to walk through all windows."
705   (let ((buf (buffer-name (window-buffer win))))
706     (if (not (member buf ess-bufs-in-frame))
707         ;; Only add buf if it is not already in list.
708         ;; This prevents same buf in two different windows being
709         ;; put into the list twice.
710         (setq ess-bufs-in-frame
711               (cons buf ess-bufs-in-frame)))))
712
713 (defun ess-get-buffers-in-frames (&optional current)
714  "Return the list of buffers that are visible in the current frame.
715 If optional argument CURRENT is given, restrict searching to the
716 current frame, rather than all frames."
717  (let ((ess-bufs-in-frame nil))
718    (walk-windows 'ess-get-bufname nil (if current nil 0))
719    ess-bufs-in-frame))
720
721 (defun ess-buffer-visible-this-frame (buf)
722  "Return t if BUF is visible in current frame."
723  (member buf (ess-get-buffers-in-frames t)))
724
725 (defun ess-buffer-visible-other-frame (buf)
726  "Return t if BUF is visible in another frame.
727 Assumes that buffer has not already been in found in current frame."
728  (if (member buf (ess-get-buffers-in-frames))
729      (window-frame (get-buffer-window buf 0))
730    nil))
731
732
733 \f ; Functions for evaluating code
734
735 (defun ess-ddeclient-p ()
736   "Returns t if the ess-local-process-name is associated with an
737 inferior-ess-ddeclient, and nil if the ess-process is running as an
738 ordinary inferior process.  Alway nil on Unix machines."
739   (interactive)
740   (if ess-microsoft-p
741       (not (equal (ess-get-process-variable
742                    ess-local-process-name 'inferior-ess-ddeclient)
743                   (default-value 'inferior-ess-ddeclient)))))
744
745 (defun ess-prompt-wait (proc &optional start-of-output sleep)
746   "Wait for a prompt to appear at BOL of current buffer.
747 PROC is the ESS process. Does not change point"
748   (if sleep (sleep-for sleep)); we sleep here, *and* wait below
749   (if start-of-output nil (setq start-of-output (point-min)))
750   (save-excursion
751     (while (progn
752              ;; get output if there is some ready
753
754 ;;           (if (and ess-microsoft-p ess-ms-slow)
755 ;;               (accept-process-output proc 0 1500) ; Microsoft is slow
756                (accept-process-output proc 0 500)
757 ;;             )
758              (goto-char (marker-position (process-mark proc)))
759              (beginning-of-line)
760              (if (< (point) start-of-output) (goto-char start-of-output))
761              (not (looking-at inferior-ess-primary-prompt))))))
762
763 (defun ordinary-insertion-filter (proc string)
764   (let ((old-buffer (current-buffer)))
765     (unwind-protect
766         (let (moving)
767           (set-buffer (process-buffer proc))
768           (setq moving (= (point) (process-mark proc)))
769           (save-excursion
770             ;; Insert the text, moving the process-marker.
771             (goto-char (process-mark proc))
772             (insert string)
773             (set-marker (process-mark proc) (point)))
774           (if moving (goto-char (process-mark proc))))
775       (set-buffer old-buffer))))
776
777 (defun ess-command (com &optional buf sleep)
778   "Send the ESS process command COM and delete the output
779 from the ESS process buffer.  If an optional second argument BUF exists
780 save the output in that buffer. BUF is erased before use.
781 COM should have a terminating newline.
782 Guarantees that the value of .Last.value will be preserved.
783 When optional third arg SLEEP is non-nil, `(sleep-for (* a SLEEP))'
784 will be used in a few places where `a' is proportional to `ess-cmd-delay'."
785   ;; Use this function when you need to evaluate some S code, and the
786   ;; result is needed immediately. Waits until the output is ready
787   (let* ((sprocess (get-ess-process ess-current-process-name))
788          sbuffer
789          do-sleep end-of-output
790          oldpb oldpf oldpm
791          my-retr-cmd my-save-cmd)
792     (if sprocess nil
793       (error "Process %s is not running!" ess-current-process-name))
794     (setq sbuffer (process-buffer sprocess))
795     (save-excursion
796       (set-buffer sbuffer)
797       (setq do-sleep                ; only now when in sprocess buffer
798             (progn
799               (if sleep (if (numberp sleep) nil (setq sleep 1))); t means 1
800               (and ess-cmd-delay sleep)))
801       (if do-sleep (setq sleep (* sleep ess-cmd-delay)))
802       (save-excursion
803         (goto-char (marker-position (process-mark sprocess)))
804         (beginning-of-line)
805         (if (looking-at inferior-ess-primary-prompt) nil
806           (ess-error
807            "ESS process not ready. Finish your command before trying again.")))
808       (if buf nil (setq buf (get-buffer-create " *ess-command-output*")))
809       (setq oldpf (process-filter sprocess))
810       (setq oldpb (process-buffer sprocess))
811       (setq oldpm (marker-position (process-mark sprocess)))
812       ;; need the buffer-local values in result buffer "buf":
813       (setq my-retr-cmd ess-retr-lastvalue-command)
814       (setq my-save-cmd ess-save-lastvalue-command)
815       (unwind-protect
816           (progn
817             (set-process-buffer sprocess buf)
818             (set-process-filter sprocess 'ordinary-insertion-filter)
819             ;; Output is now going to BUF:
820             (save-excursion
821               (set-buffer buf)
822               (erase-buffer)
823               (set-marker (process-mark sprocess) (point-min))
824               (process-send-string sprocess my-save-cmd)
825
826               (ess-prompt-wait sprocess nil (and do-sleep (* 0.05 sleep)))
827               (erase-buffer)
828               (process-send-string sprocess com)
829
830               ;; need time for ess-create-object-name-db on PC
831               (ess-prompt-wait sprocess nil (and do-sleep (* 0.4 sleep)));MS: 4
832               ;;(if do-sleep (sleep-for (* 0.0 sleep))); microsoft: 0.5
833               (goto-char (point-max))
834               (save-excursion
835                 (beginning-of-line)     ; so prompt will be deleted
836                 (setq end-of-output (point)))
837               (process-send-string sprocess my-retr-cmd)
838
839               (ess-prompt-wait sprocess end-of-output
840                                (and do-sleep (* 0.05 sleep))); microsoft: 0.5)
841
842               ;; Get rid out output from last assign
843               (delete-region end-of-output (point-max))))
844         ;; Restore old values for process filter
845         (set-process-buffer sprocess oldpb)
846         (set-process-filter sprocess oldpf)
847         (set-marker (process-mark sprocess) oldpm)))))
848
849 (defun ess-replace-in-string (str regexp newtext &optional literal)
850   "Replace all matches in STR for REGEXP with NEWTEXT string.
851 Optional LITERAL non-nil means do a literal replacement.
852 Otherwise treat \\ in NEWTEXT string as special:
853   \\& means substitute original matched text,
854   \\N means substitute match for \(...\) number N,
855   \\\\ means insert one \\."
856   (if (not (stringp str))
857       (error "(replace-in-string): First argument must be a string: %s" str))
858   (if (stringp newtext)
859       nil
860     (error "(replace-in-string): 3rd arg must be a string: %s"
861            newtext))
862   (let ((rtn-str "")
863         (start 0)
864         (special)
865         match prev-start)
866     (while (setq match (string-match regexp str start))
867       (setq prev-start start
868             start (match-end 0)
869             rtn-str
870             (concat
871               rtn-str
872               (substring str prev-start match)
873               (cond (literal newtext)
874                     (t (mapconcat
875                          (function
876                            (lambda (c)
877                              (if special
878                                  (progn
879                                    (setq special nil)
880                                    (cond ((eq c ?\\) "\\")
881                                          ((eq c ?&)
882                                           (substring str
883                                                      (match-beginning 0)
884                                                      (match-end 0)))
885                                          ((and (>= c ?0) (<= c ?9))
886                                           (if (> c (+ ?0 (length
887                                                            (match-data))))
888                                               ;; Invalid match num
889                                               (error "(replace-in-string) Invalid match num: %c" c)
890                                             (setq c (- c ?0))
891                                             (substring str
892                                                        (match-beginning c)
893                                                        (match-end c))))
894                                          (t (char-to-string c))))
895                                (if (eq c ?\\) (progn (setq special t) nil)
896                                  (char-to-string c)))))
897                          newtext ""))))))
898     (concat rtn-str (substring str start))))
899
900
901
902 ;;*;;  Evaluating lines, paragraphs, regions, and buffers.
903
904 ;;--- The two basic building blocks [called by all other ess-eval..] are
905 ;;      (ess-eval-linewise ....)
906 ;; and
907 ;;      (ess-eval-region   ....)
908
909 (defun ess-eval-linewise (text-withtabs &optional invisibly eob even-empty)
910 ;; RDB 28/8/92 added optional arg eob
911 ;; AJR 971022:   text-withtabs was text.
912   "Evaluate TEXT-WITHTABS in the ESS process buffer as if typed in w/o tabs.
913 Waits for prompt after each line of input, so won't break on large texts.
914
915 If optional second arg INVISIBLY is non-nil, don't echo commands.  If it
916 is a string, just include that string.  If optional third arg
917 EOB is non-nil go to end of ESS process buffer after evaluation.  If optional
918 4th arg EVEN-EMPTY is non-nil, also send empty text (e.g. an empty line)."
919   ;; Use this to evaluate some code, but don't wait for output.
920   (let* ((cbuffer (current-buffer))
921          (sprocess (get-ess-process ess-current-process-name))
922          (sbuffer (process-buffer sprocess))
923          (text (ess-replace-in-string text-withtabs "\t" " "))
924          start-of-output
925          com pos txt-gt-0)
926
927     ;;(message "'ess-eval-linewise: sbuffer = %s" sbuffer)
928     (set-buffer sbuffer)
929
930     ;; the following is required to make sure things work!
931     (if (string= ess-language "STA")
932         (setq invisibly t))
933     ;; dbg:
934     ;; dbg(ess-write-to-dribble-buffer
935     ;; dbg (format "(eval-visibly 1): lang %s (invis=%s, eob=%s, even-empty=%s)\n"
936     ;; dbg     ess-language invisibly eob even-empty))
937
938     (goto-char (marker-position (process-mark sprocess)))
939     (if (stringp invisibly)
940         (insert-before-markers (concat "*** " invisibly " ***\n")))
941     ;; dbg:
942     ;; dbg (ess-write-to-dribble-buffer
943     ;; dbg  (format "(eval-visibly 2): text[%d]= '%s'\n" (length text) text))
944     (while (or (setq txt-gt-0 (> (length text) 0))
945                even-empty)
946       (if even-empty (setq even-empty nil))
947       (if txt-gt-0
948           (progn
949             (setq pos (string-match "\n\\|$" text))
950             (setq com (concat (substring text 0 pos) "\n"))
951             (setq text (substring text (min (length text) (1+ pos)))))
952         ;; else 0-length text
953         (setq com "\n")
954         )
955       (goto-char (marker-position (process-mark sprocess)))
956       (if (not invisibly)
957           ;; Terrible kludge -- need to insert after all markers *except*`
958           ;; the process mark
959           (let ((dokludge (eq (point)
960                               (marker-position (process-mark sprocess)))))
961             (insert com)
962             (if dokludge (set-marker (process-mark sprocess) (point)))))
963       (setq start-of-output (marker-position (process-mark sprocess)))
964       ;; A kludge to prevent the delay between insert and process output
965       ;; affecting the display.  A case for a comint-send-input-hook?
966       ;; (save-excursion
967       ;;   ;; comint-postoutput-scroll-to-bottom can change
968       ;;   ;; current-buffer. Argh.
969       ;;   (let ((functions comint-output-filter-functions))
970       ;;     (while functions
971       ;;       (funcall (car functions) com)
972       ;;       (setq functions (cdr functions)))))
973       (process-send-string sprocess com)
974       ;; Don't hang around waiting for the prompt after the last
975       ;; line of input
976       (if (eq (length text) 0)
977           nil
978         (while (progn
979                  (accept-process-output nil 0 100)
980                  (goto-char (marker-position (process-mark sprocess)))
981                  (beginning-of-line)
982                  (if (< (point) start-of-output)
983                      (goto-char start-of-output))
984                  (not (looking-at inferior-ess-prompt))))))
985     (goto-char (marker-position (process-mark sprocess)))
986     (if eob
987         (progn
988           (ess-show-buffer (buffer-name sbuffer) nil)
989           ;; Once SBUFFER is visible, we can then move the point in that
990           ;; window to the end of the buffer.
991           (set-window-point (get-buffer-window sbuffer t)
992                             (with-current-buffer sbuffer (point-max))))
993       (set-buffer cbuffer))
994     ))
995
996 ;;;*;;; Evaluate only
997
998 (defun ess-eval-region (start end toggle &optional message)
999   "Send the current region to the inferior ESS process.
1000 With prefix argument, toggle meaning of `ess-eval-visibly-p'."
1001   (interactive "r\nP")
1002   ;;(untabify (point-min) (point-max))
1003   ;;(untabify start end); do we really need to save-excursion?
1004   (ess-force-buffer-current "Process to load into: ")
1005   (message "Starting evaluation...")
1006   (let ((visibly (if toggle (not ess-eval-visibly-p) ess-eval-visibly-p)))
1007     (if visibly
1008         (ess-eval-linewise (buffer-substring start end))
1009       (if ess-synchronize-evals
1010           (ess-eval-linewise (buffer-substring start end)
1011                              (or message "Eval region"))
1012         ;; else [almost always!]
1013         (let ((sprocess (get-ess-process ess-current-process-name)))
1014           (process-send-region sprocess start end)
1015           (process-send-string sprocess "\n")))))
1016   (message "Finished evaluation"))
1017
1018 (defun ess-eval-buffer (vis)
1019   "Send the current buffer to the inferior ESS process.
1020 Arg has same meaning as for `ess-eval-region'."
1021   (interactive "P")
1022   ;; already in eval-region:
1023   ;;    (ess-force-buffer-current "Process to load into: ")
1024   (ess-eval-region (point-min) (point-max) vis "Eval buffer"))
1025
1026 (defun ess-eval-function (vis)
1027   "Send the current function to the inferior ESS process.
1028 Arg has same meaning as for `ess-eval-region'."
1029   (interactive "P")
1030   ;; already in eval-region:
1031   ;;     (ess-force-buffer-current "Process to load into: ")
1032   (save-excursion
1033     (let* ((beg-end (ess-end-of-function))
1034            (beg (nth 0 beg-end))
1035            (end (nth 1 beg-end))
1036            name)
1037       (goto-char beg)
1038       (setq name (ess-extract-word-name))
1039       (princ (concat "Loading: " name) t)
1040       (ess-eval-region beg end vis
1041                        (concat "Eval function " name)))))
1042
1043 ;; This is from  Mary Lindstrom <lindstro@Biostat.Wisc.Edu>
1044 ;; 31 Aug 1995 14:11:43         To: S-mode@stat.math.ethz.ch
1045 (defun ess-eval-paragraph (vis)
1046   "Send the current paragraph to the inferior ESS process.
1047 Prefix arg VIS toggles visibility of ess-code as for `ess-eval-region'."
1048   (interactive "P")
1049   (ess-force-buffer-current "Process to load into: ")
1050   (save-excursion
1051     (forward-paragraph)
1052     (let ((end (point)))
1053       (backward-paragraph)
1054       (ess-eval-region (point) end vis "Eval paragraph"))))
1055
1056 (defun ess-eval-line (vis)
1057   "Send the current line to the inferior ESS process.
1058 Arg has same meaning as for `ess-eval-region'."
1059   (interactive "P")
1060   (ess-force-buffer-current "Process to load into: ")
1061   (save-excursion
1062     (end-of-line)
1063     (let ((end (point)))
1064       (beginning-of-line)
1065       (princ (concat "Loading line: " (ess-extract-word-name) " ...") t)
1066       (ess-eval-region (point) end vis "Eval line"))))
1067
1068
1069
1070 ;; Contributed by  Stephen Eglen <stephen@anc.ed.ac.uk> {idea from octave int.}
1071 (defun ess-next-code-line (&optional arg)
1072   "Move ARG lines of code forward (backward if ARG is negative).
1073 Skips past all empty and comment lines.  Default for ARG is 1.
1074
1075 On success, return 0.  Otherwise, go as far as possible and return -1."
1076   (interactive "p")
1077   (or arg (setq arg 1))
1078   (beginning-of-line)
1079   (let ((n 0)
1080         (inc (if (> arg 0) 1 -1)))
1081     (while (and (/= arg 0) (= n 0))
1082       (setq n (forward-line inc)); n=0 is success
1083       (while (and (= n 0)
1084                   (looking-at "\\s-*\\($\\|\\s<\\)"))
1085         (setq n (forward-line inc)))
1086       (setq arg (- arg inc)))
1087     n))
1088
1089 (defun ess-eval-line-and-step (&optional simple-next even-empty invisibly)
1090   "Evaluate the current line visibly and step to the \"next\" line.
1091 \"next\" = the next line with non-comment code _unless_ SIMPLE-NEXT is non-nil,
1092 possibly via prefix arg.  If 2nd arg EVEN-EMPTY [prefix as well],
1093 also send empty lines.  When the variable `ess-eval-empty' is non-nil
1094 both SIMPLE-NEXT and EVEN-EMPTY are interpreted as true."
1095   ;; From an idea by Rod Ball (rod@marcam.dsir.govt.nz)
1096   (interactive "P\nP"); prefix sets BOTH !
1097   (ess-force-buffer-current "Process to load into: ")
1098   (save-excursion
1099     (end-of-line)
1100     (let ((end (point)))
1101       (beginning-of-line)
1102       ;; go to end of process buffer so user can see result
1103       (ess-eval-linewise (buffer-substring (point) end)
1104                          invisibly 'eob (or even-empty ess-eval-empty))))
1105   (if (or simple-next ess-eval-empty)
1106       (forward-line 1)
1107     (ess-next-code-line 1)))
1108
1109 (defun ess-eval-line-and-step-invisibly (&optional simple-next even-empty)
1110    "Evaluate the current line invisibly and step to the next line.
1111 Evaluate all comments and empty lines."
1112   (interactive)
1113   (ess-eval-line-and-step t t t))
1114
1115 ;; goes to the real front, in case you do double function definition
1116 ;; 29-Jul-92 -FER
1117 ;; don't know why David changed it.
1118
1119 ;; FER's versions don't work properly with nested functions. Replaced
1120 ;; mine. DMS 16 Nov 92
1121
1122 ;;;*;;; Evaluate and switch to S
1123
1124 (defun ess-eval-region-and-go (start end vis)
1125   "Send the current region to the inferior S and switch to the process buffer.
1126 Arg has same meaning as for `ess-eval-region'."
1127   (interactive "r\nP")
1128   (ess-eval-region start end vis)
1129   (ess-switch-to-ESS t))
1130
1131 (defun ess-eval-buffer-and-go (vis)
1132   "Send the current buffer to the inferior S and switch to the process buffer.
1133 Arg has same meaning as for `ess-eval-region'."
1134   (interactive "P")
1135   (ess-eval-buffer vis)
1136   (ess-switch-to-ESS t))
1137
1138 (defun ess-eval-function-and-go (vis)
1139   "Send the current function to the inferior ESS process and switch to
1140 the process buffer. Arg has same meaning as for `ess-eval-region'."
1141   (interactive "P")
1142   (ess-eval-function vis)
1143   (ess-switch-to-ESS t))
1144
1145 (defun ess-eval-line-and-go (vis)
1146   "Send the current line to the inferior ESS process and switch to the
1147 process buffer. Arg has same meaning as for `ess-eval-region'."
1148   (interactive "P")
1149   (ess-eval-line vis)
1150   (ess-switch-to-ESS t))
1151
1152 ;;; Related to the ess-eval-* commands, there are the ess-load
1153 ;;; commands.   Need to add appropriate stuff...
1154
1155 (defun ess-load-file (filename)
1156   "Load an S source file into an inferior ESS process."
1157   (interactive (list
1158                 (or
1159                  (and (eq major-mode 'ess-mode)
1160                       (buffer-file-name))
1161                  (expand-file-name
1162                   (read-file-name "Load S file: " nil nil t)))))
1163   (ess-make-buffer-current)
1164   (let ((source-buffer (get-file-buffer filename)))
1165     (if (ess-check-source filename)
1166         (error "Buffer %s has not been saved" (buffer-name source-buffer))
1167       ;; Find the process to load into
1168       (if source-buffer
1169           (save-excursion
1170             (set-buffer source-buffer)
1171     (ess-force-buffer-current "Process to load into: ")
1172             (ess-check-modifications))))
1173     (let ((errbuffer (ess-create-temp-buffer ess-error-buffer-name))
1174           error-occurred nomessage)
1175       (ess-command (format inferior-ess-load-command filename) errbuffer);sleep ?
1176       (save-excursion
1177         (set-buffer errbuffer)
1178         (goto-char (point-max))
1179         (setq error-occurred (re-search-backward ess-dump-error-re nil t))
1180         (setq nomessage (= (buffer-size) 0)))
1181       (if error-occurred
1182           (message "Errors: Use %s to find error."
1183                    (substitute-command-keys
1184                     "\\<inferior-ess-mode-map>\\[ess-parse-errors]"))
1185         ;; Load did not cause an error
1186         (if nomessage (message "Load successful.")
1187           ;; There was a warning message from S
1188           (ess-display-temp-buffer errbuffer))
1189         ;; Consider deleting the file
1190         (let ((skdf (if source-buffer
1191                         (save-excursion
1192                           (set-buffer source-buffer)
1193                           ess-keep-dump-files)
1194                       ess-keep-dump-files))) ;; global value
1195           (cond
1196            ((null skdf)
1197             (delete-file filename))
1198            ((memq skdf '(check ask))
1199             (let ((doit (y-or-n-p (format "Delete %s " filename))))
1200               (if doit (delete-file filename))
1201               (and source-buffer
1202                    (local-variable-p 'ess-keep-dump-files source-buffer)
1203                    (save-excursion
1204                      (set-buffer source-buffer)
1205                      (setq ess-keep-dump-files doit)))))))
1206         (ess-switch-to-ESS t)))))
1207
1208 \f ; Inferior S mode
1209 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1210 ;;;; In this section:
1211 ;;;;
1212 ;;;; * The major mode inferior-ess-mode
1213 ;;;; * Process handling code
1214 ;;;; * Completion code
1215 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1216
1217 ;;*;; Major mode definition
1218
1219 (if inferior-ess-mode-map
1220     nil
1221
1222   (cond ((featurep 'xemacs)
1223          ;; Code for XEmacs
1224          (setq inferior-ess-mode-map (make-keymap))
1225          (set-keymap-parent inferior-ess-mode-map comint-mode-map))
1226         ((not (featurep 'xemacs))
1227          ;; Code for GNU Emacs
1228          (setq inferior-ess-mode-map (cons 'keymap comint-mode-map))))
1229
1230   ;; Use syntax valid *both* for GNU emacs and XEmacs :
1231   (define-key inferior-ess-mode-map "\r"       'inferior-ess-send-input)
1232   (define-key inferior-ess-mode-map "\C-a"     'comint-bol)
1233   (define-key inferior-ess-mode-map "\M-\r"    'ess-transcript-send-command-and-move)
1234   (define-key inferior-ess-mode-map "\C-c\C-l" 'ess-load-file)
1235   ;; the above OVERRIDES  comint-dynamic-list-input-ring --> re-assign:
1236   (define-key inferior-ess-mode-map "\C-c\M-l" 'comint-dynamic-list-input-ring)
1237   (define-key inferior-ess-mode-map "\C-c`"    'ess-parse-errors)
1238   (define-key inferior-ess-mode-map "\C-c\C-d" 'ess-dump-object-into-edit-buffer)
1239   (define-key inferior-ess-mode-map "\C-c\C-v" 'ess-display-help-on-object)
1240   (define-key inferior-ess-mode-map "\C-c\C-q" 'ess-quit)
1241   (define-key inferior-ess-mode-map "\C-c\C-t" 'ess-execute)
1242   (define-key inferior-ess-mode-map "\C-c\C-s" 'ess-execute-search)
1243   (define-key inferior-ess-mode-map "\C-c\C-x" 'ess-execute-objects)
1244   ;;(define-key inferior-ess-mode-map "\C-c\C-a" 'ess-execute-attach)
1245   (define-key inferior-ess-mode-map "\C-c\034" 'ess-abort) ; \C-c\C-backslash
1246   (define-key inferior-ess-mode-map "\C-c\C-z" 'ess-abort) ; mask comint map
1247   (define-key inferior-ess-mode-map "\C-d"     'delete-char)   ; EOF no good in S
1248   (define-key inferior-ess-mode-map "\t"       'comint-dynamic-complete)
1249   (define-key inferior-ess-mode-map "\C-c\t"   'ess-complete-object-name)
1250   (define-key inferior-ess-mode-map "\M-\t"    'comint-replace-by-expanded-filename)
1251   (define-key inferior-ess-mode-map "\M-?"     'ess-list-object-completions)
1252   (define-key inferior-ess-mode-map "\C-c\C-k" 'ess-request-a-process))
1253
1254 (easy-menu-define
1255  inferior-ess-mode-menu inferior-ess-mode-map
1256  "Menu for use in Inferior S mode"
1257  '("iESS"
1258    ["What is this? (beta)"    ess-mouse-me                      t]
1259    ["Resynch S completions"  ess-resynch                   t]
1260    ["Quit S"                 ess-quit                      t]
1261    ["Display search list"    ess-execute-search            t]
1262    ["Display object list"    ess-execute-objects           t]
1263    ["Get help on S object"   ess-display-help-on-object    t]
1264    ["Enter S command"        ess-execute                   t]
1265    ["Attach directory"       ess-execute-attach            t]
1266    "------"
1267    ["Send and move"  ess-transcript-send-command-and-move  t]
1268    ["Copy command"   comint-copy-old-input                 t]
1269    ["Send command"   inferior-ess-send-input               t]
1270    "------"
1271    ["Jump to Error"  ess-parse-errors                      t]
1272    ;; need a toggle switch for above, AJR.
1273    ["Load source file"  ess-load-file                      t]
1274    ["Edit S Object"     ess-dump-object-into-edit-buffer   t]
1275    "------"
1276    ["Describe"         describe-mode                       t]
1277    ["About"            (ess-goto-info "Entering Commands") t]
1278    ["Send bug report"  ess-submit-bug-report               t]
1279    ))
1280
1281
1282 (defun inferior-ess-mode-xemacs-menu ()
1283   "Hook to install `ess-mode' menu for XEmacs (w/ easymenu)."
1284   (if 'inferior-ess-mode
1285         (easy-menu-add inferior-ess-mode-menu)
1286     (easy-menu-remove inferior-ess-mode-menu)))
1287
1288 (if (string-match "XEmacs" emacs-version)
1289     (add-hook 'inferior-ess-mode-hook 'inferior-ess-mode-xemacs-menu))
1290
1291 (if ess-mode-minibuffer-map  nil
1292
1293   (cond ((featurep 'xemacs)
1294          ;; Code for XEmacs
1295          (setq ess-mode-minibuffer-map (make-keymap))
1296          (set-keymap-parent ess-mode-minibuffer-map minibuffer-local-map)))
1297
1298   (cond ((not (featurep 'xemacs))
1299          ;; Code for Emacs
1300          (setq ess-mode-minibuffer-map (cons 'keymap minibuffer-local-map))))
1301
1302   (define-key ess-mode-minibuffer-map "\t" 'ess-complete-object-name)
1303   (define-key ess-mode-minibuffer-map "\C-c\C-s" 'ess-execute-search)
1304   (define-key ess-mode-minibuffer-map "\C-c\C-x" 'ess-execute-objects))
1305
1306 (defun inferior-ess-mode ()
1307   "Major mode for interacting with an inferior ESS process.
1308 Runs an S interactive job as a subprocess of Emacs, with I/O through an
1309 Emacs buffer.  Variable `inferior-ess-program' controls which S
1310 is run.
1311
1312 Commands are sent to the ESS process by typing them, and pressing
1313 \\[inferior-ess-send-input].  Pressing \\[complete-dynamic-complete]
1314 completes known object names or filenames, as appropriate.  Other
1315 keybindings for this mode are:
1316
1317 \\{inferior-ess-mode-map}
1318
1319 When editing S objects, the use of \\[ess-load-file] is advocated.
1320 `ess-load-file' keeps source files (if `ess-keep-dump-files' is non-nil) in
1321 the directory specified by `ess-source-directory', with the
1322 filename chosen according to `ess-dump-filename-template'. When a file is
1323 loaded, `ess-mode' parses error messages and jumps to the appropriate file
1324 if errors occur. The ess-eval- commands do not do this.
1325
1326 Customization: Entry to this mode runs the hooks on `comint-mode-hook' and
1327 `inferior-ess-mode-hook' (in that order).
1328
1329 You can send text to the inferior ESS process from other buffers containing
1330 S source. The key bindings of these commands can be found by typing
1331 C-h m (help for mode) in the other buffers.
1332     `ess-eval-region' sends the current region to the ESS process.
1333     `ess-eval-buffer' sends the current buffer to the ESS process.
1334     `ess-eval-function' sends the current function to the ESS process.
1335     `ess-eval-line' sends the current line to the ESS process.
1336     `ess-beginning-of-function' and `ess-end-of-function' move the point to
1337         the beginning and end of the current S function.
1338     `ess-switch-to-ESS' switches the current buffer to the ESS process buffer.
1339     `ess-switch-to-end-of-ESS' switches the current buffer to the ESS process
1340         buffer and puts point at the end of it.
1341
1342     `ess-eval-region-and-go', `ess-eval-buffer-and-go',
1343         `ess-eval-function-and-go', and `ess-eval-line-and-go' switch to the S
1344         process buffer after sending their text.
1345     `ess-dump-object-into-edit-buffer' moves an S object into a temporary file
1346         and buffer for editing
1347     `ess-load-file' sources a file of commands to the ESS process.
1348
1349 Commands:
1350 Return after the end of the process' output sends the text from the
1351     end of process to point.
1352 Return before the end of the process' output copies the sexp ending at point
1353     to the end of the process' output, and sends it.
1354 Delete converts tabs to spaces as it moves back.
1355 C-M-q does Tab on each line starting within following expression.
1356 Paragraphs are separated only by blank lines.  Crosshatches start comments.
1357 If you accidentally suspend your process, use \\[comint-continue-subjob]
1358 to continue it."
1359   (interactive)
1360   ;;(message " at very beg. of (inferior-ess-mode): inf.-ess-prompt= %s"
1361   ;;       inferior-ess-prompt)
1362   (comint-mode)
1363   ;;
1364
1365   ;; SJE: is this the proper place for setting inferior-ess-prompt,
1366   ;; rather than within ess-multi?  Tony - have you remembered yet
1367
1368   ;; about the setq-default, as I changed it back to setq.
1369   (setq inferior-ess-prompt
1370         ;; shouldn't be setq-default!  And I've
1371         ;; forgotten why!   (AJR)
1372         ;; Do not anchor to bol with `^'
1373         (concat "\\("
1374                 inferior-ess-primary-prompt
1375                 "\\|"
1376                 inferior-ess-secondary-prompt
1377                 "\\)"))
1378   (setq comint-prompt-regexp (concat "^" inferior-ess-prompt))
1379   (setq major-mode 'inferior-ess-mode)
1380   (setq mode-name "iESS") ;(concat "iESS:" ess-dialect))
1381   (setq mode-line-process
1382         '(" [" ess-local-process-name "]: %s"))
1383   (use-local-map inferior-ess-mode-map)
1384   (if ess-mode-syntax-table
1385       (set-syntax-table ess-mode-syntax-table)
1386     ; FIXME: need to do something if not set!  Get from the proper place!
1387     )
1388   (add-hook 'comint-input-filter-functions 'ess-search-path-tracker)
1389   (setq comint-get-old-input 'inferior-ess-get-old-input)
1390
1391   (ess-write-to-dribble-buffer
1392    (format "(i-ess 1): buf=%s, lang=%s, comint..echo=%s, comint..sender=%s,\n"
1393            (current-buffer) ess-language
1394            comint-process-echoes comint-input-sender))
1395
1396   (make-local-variable 'comint-process-echoes)
1397   (make-local-variable 'comint-input-sender)
1398   (make-local-variable 'process-connection-type)
1399   (setq process-connection-type t)
1400
1401   ;; Configuration for SAS/XLispStat input handling
1402   ;; We set comint-process-echoes to t because inferior-ess-input-sender
1403   ;; recopies the input. If comint-process-echoes was *meant* to be t ...
1404   ;;
1405   ;; except that XLS doesn't like it.  This is an ugly hack that ought
1406   ;; to go into the dialect configuration...
1407   (if (or (string= ess-language "SAS")
1408           (string= ess-language "XLS"))
1409       (setq comint-process-echoes nil)
1410     (setq comint-process-echoes t))
1411
1412   ;; Configuration for S/R input handling
1413   ;; AJR: add KH's fix.  This is ugly, change to do it right.
1414   ;; i.e. put it as a buffer local var, in S or R defuns...
1415   (if (or (string= ess-language "S"))
1416       (cond
1417        ((string= ess-dialect "R")
1418         (setq comint-input-sender 'inferior-R-input-sender))
1419        ((or (string= ess-dialect "S3") ;; S dialects
1420             (string= ess-dialect "S4")
1421             (string= ess-dialect "S+3")
1422             (string= ess-dialect "S+4")
1423             (string= ess-dialect "S+5")
1424             (string= ess-dialect "S+6")
1425             (string= ess-dialect "S"))
1426         (setq comint-input-sender 'inferior-ess-input-sender))))
1427
1428   ;; Configuration for Stata input handling
1429   ;; AJR: Stata is hell.   This is the primary configuration point.
1430   (if (string= ess-language "STA")
1431       (progn
1432         (setq comint-input-sender 'inferior-ess-input-sender) ; was STA
1433         (setq comint-process-echoes t)))
1434
1435   ;; Configuration for Omegahat input handling
1436   (if (string= ess-language "OMG")
1437       (progn
1438         ; the following doesn't exist (until needed?)
1439         ;(setq comint-input-sender 'inferior-OMG-input-sender)
1440         (setq comint-process-echoes nil)))
1441
1442   (ess-write-to-dribble-buffer
1443    (format "(i-ess 2): buf=%s, lang=%s, comint..echo=%s, comint..sender=%s,\n"
1444            (current-buffer) ess-language
1445            comint-process-echoes comint-input-sender))
1446   ;; Font-lock support
1447   ;; AJR: This (the following local-var is already the case!
1448   ;; KH sez: only in XEmacs :-(.
1449   (make-local-variable 'font-lock-defaults)
1450   (setq font-lock-defaults
1451         '(inferior-ess-font-lock-keywords nil nil ((?' . "."))))
1452
1453   (ess-setq-vars-local ess-customize-alist); (current-buffer))
1454
1455   (ess-write-to-dribble-buffer
1456    (format "(i-ess 3): curr-buf=%s, comint..echo=%s, comint..sender=%s,\n"
1457            (current-buffer) comint-process-echoes comint-input-sender))
1458
1459   ;; Completion support
1460   ;; SJE: comint-dynamic-complete-functions is regarded as a hook, rather
1461   ;; than a regular variable.
1462   (add-hook 'comint-dynamic-complete-functions
1463             'ess-complete-object-name nil 'local)
1464   (add-hook 'comint-dynamic-complete-functions
1465              'comint-replace-by-expanded-history 'append 'local)
1466   (add-hook 'comint-dynamic-complete-functions
1467             'ess-complete-filename 'append 'local)
1468
1469
1470
1471   ;; (setq comint-completion-addsuffix nil) ; To avoid spaces after filenames
1472   ;; KH: next 2 lines solve.
1473   (make-local-variable 'comint-completion-addsuffix)
1474   (setq comint-completion-addsuffix (cons "/" ""))
1475
1476   (setq comint-input-autoexpand t) ; Only for completion, not on input.
1477
1478   ;;; Keep <tabs> out of the code.
1479   (make-local-variable 'indent-tabs-mode)
1480   (setq indent-tabs-mode nil)
1481
1482   (make-local-variable 'paragraph-start)
1483   (setq paragraph-start (concat inferior-ess-primary-prompt "\\|\^L"))
1484   (make-local-variable 'paragraph-separate)
1485   (setq paragraph-separate "\^L")
1486
1487   ;; SJE Tue 28 Dec 2004: do not attempt to load object name db.
1488   ;; (ess-load-object-name-db-file)
1489   ;; (sleep-for 0.5)
1490   (make-local-variable 'kill-buffer-hook)
1491   (add-hook 'kill-buffer-hook 'ess-kill-buffer-function)
1492   (run-hooks 'inferior-ess-mode-hook)
1493   (message
1494    (concat (substitute-command-keys
1495             "Type \\[describe-mode] for help on ESS version ")
1496            ess-version)))
1497
1498 ;;*;; Commands used exclusively in inferior-ess-mode
1499
1500 ;;;*;;; Main user commands
1501
1502 (defun inferior-ess-input-sender (proc string)
1503   (ess-eval-linewise (concat string "\n") nil nil ess-eval-empty))
1504
1505 (defun inferior-STA-input-sender (proc string)
1506   (ess-eval-linewise (concat string "\n") t t))
1507
1508 ;;> <PD writes>:
1509 ;;> Also, invoking help() from the command line may lead to confusing
1510 ;;> output, somewhat worse with R than with S. You're not really supposed
1511 ;;> to do that (use C-c C-v to invoke ess-display-help-on-object), but it's
1512 ;;> an obvious newcomer's mistake.
1513 ;;>
1514 ;;> (I wonder: could the elisp-code not quite easily recognize help
1515 ;;> calls (at least in the ?xxx form) and do the right thing automagically?)
1516 ;;>
1517 ;;> As promised, here is a quick hack:
1518 ;;  ___hack much improved by MM___ , both help(.) and ?... now work
1519 ;; FIXME: Note that  '??' nicely works in *R*, but
1520 ;;        'type ? topic' doesn't use ess-help {but display in *R*}
1521 (defconst inferior-R-1-input-help (format "help *(%s)" ess-help-arg-regexp))
1522 (defconst inferior-R-2-input-help (format "^ *\\? *%s" ess-help-arg-regexp))
1523 (defconst inferior-R-page         (format "^ *page *(%s)" ess-help-arg-regexp))
1524
1525 (defun inferior-R-input-sender (proc string)
1526   ;; REALLY only for debugging: this S_L_O_W_S D_O_W_N   [here AND below]
1527   ;;(ess-write-to-dribble-buffer (format "(inf..-R-..): string='%s'; " string))
1528   ;; rmh: 2002-01-12 catch page() in R
1529   (let ((help-string (or (string-match inferior-R-1-input-help string)
1530                          (string-match inferior-R-2-input-help string)))
1531         (page-string     (string-match inferior-R-page         string)))
1532     (if (or help-string page-string)
1533         (let* ((string2 (match-string 2 string))
1534                (string2-rt (concat string2 ".rt")))
1535           ;; (ess-write-to-dribble-buffer (format " new string='%s'\n" string2))
1536           (beginning-of-line)
1537           (if (looking-at inferior-ess-primary-prompt)
1538               (progn
1539                 (end-of-line)
1540                 (insert-before-markers string)) ;; emacs 21.0.105 and older
1541             (delete-backward-char 1))           ;; emacs 21.0.106 and newer
1542           (if page-string
1543               (progn          
1544                 (ess-command (concat string2 "\n")
1545                              (get-buffer-create (concat string2 ".rt")))
1546                 (ess-eval-linewise "\n")
1547                 (switch-to-buffer-other-window string2-rt)
1548                 (R-transcript-mode))
1549             (ess-display-help-on-object
1550              (if (string= string2 "") "help" string2))
1551             (ess-eval-linewise "\n")))
1552       ;; else:  normal command
1553       (inferior-ess-input-sender proc string))))
1554
1555
1556 (defun inferior-ess-send-input ()
1557   "Sends the command on the current line to the ESS process."
1558   (interactive)
1559   (ess-make-buffer-current)
1560   (run-hooks 'ess-send-input-hook)
1561   (comint-send-input)
1562   (setq ess-object-list nil)) ;; Will be reconstructed from cache if needs be
1563
1564 (defun inferior-ess-get-old-input ()
1565   "Return the ESS command surrounding point."
1566   (save-excursion
1567     (beginning-of-line)
1568     (if (not (looking-at inferior-ess-prompt))
1569         (ess-error "No command on this line."))
1570     (if (looking-at inferior-ess-primary-prompt) nil
1571         (re-search-backward (concat "^" inferior-ess-primary-prompt)))
1572     (comint-skip-prompt)
1573     (let (command
1574            (beg (point)))
1575       (end-of-line)
1576       (setq command (buffer-substring beg (point)))
1577       (forward-line 1)
1578       (while (looking-at inferior-ess-secondary-prompt)
1579         (comint-skip-prompt)
1580         (setq beg (point))
1581         (end-of-line)
1582         (setq command (concat command "\n" (buffer-substring beg (point))))
1583         (forward-line 1))
1584       (forward-line -1)
1585       (setq ess-temp-point (point))
1586       command)))
1587
1588 ;;;*;;; Hot key commands
1589
1590 (defun ess-execute-objects (posn)
1591   "Send the objects() command to the ESS process.
1592 By default, gives the objects at position 1.
1593 A prefix argument toggles the meaning of `ess-execute-in-process-buffer'.
1594 A prefix argument of 2 or more means get objects for that position.
1595 A negative prefix argument gets the objects for that position
1596   and toggles `ess-execute-in-process-buffer' as well."
1597   (interactive "P")
1598   (ess-make-buffer-current)
1599   (let* ((num-arg (if (listp posn)
1600                       (if posn -1 1)
1601                     (prefix-numeric-value posn)))
1602         (the-posn (if (< num-arg 0) (- num-arg) num-arg))
1603         (invert (< num-arg 0))
1604         (the-command (format inferior-ess-objects-command the-posn ".*"))
1605         (the-message (concat ">>> Position "
1606                              (number-to-string the-posn)
1607                              " ("
1608                              (nth (1- the-posn) (ess-search-list))
1609                              ")\n")))
1610     (ess-execute the-command invert "S objects" the-message)))
1611
1612 ;;;; S4 Version
1613 ;;;; soup-up the interactive usage: allow modifications to a default pattern
1614 ;;(defun ess-execute-objects (posn)
1615 ;;  "Send the `inferior-ess-objects-command' to the ESS process.
1616 ;;No prefix argument uses position 1 and pattern inferior-ess-objects-pattern.
1617 ;;A nonnegative prefix gets objects for that position and prompts for
1618 ;;  the pattern.
1619 ;;A negative prefix also toggles ess-execute-in-process-buffer."
1620 ;;  (interactive "P")
1621 ;;  (ess-make-buffer-current)
1622 ;;  (let* ((num-arg (if (listp posn) 1
1623 ;;                  (prefix-numeric-value posn)))
1624 ;;       (the-posn (if (< num-arg 0) (- num-arg) num-arg))
1625 ;;       (invert (< num-arg 0))
1626 ;;       (pattern (if current-prefix-arg (read-string "Pattern (.*): ")
1627 ;;                  inferior-ess-objects-pattern))
1628 ;;       (pattern (if (string= pattern "") ".*" pattern))
1629 ;;       (the-command (format inferior-ess-objects-command the-posn pattern))
1630 ;;       (the-message (concat ">>> Position "
1631 ;;                            the-posn
1632 ;;                            " ("
1633 ;;                            (nth (1- the-posn) (ess-search-list))
1634 ;;                            ") (pattern = "
1635 ;;                            pattern
1636 ;;                            ")\n")))
1637 ;;    (ess-execute the-command invert "S objects" the-message)))
1638
1639 (defun ess-execute-search (invert)
1640   "Send the `inferior-ess-search-list-command' command to the `ess-language' process.
1641 [search(..) in S]"
1642   (interactive "P")
1643   (ess-execute inferior-ess-search-list-command  invert "S search list"))
1644
1645 (defun ess-execute-attach (dir &optional posn)
1646   "Attach a directory in the `ess-language' process with the attach() command.
1647 When used interactively, user is prompted for DIR to attach and
1648 prefix argument is used for POSN (or 2, if absent.)
1649 Doesn't work for data frames."
1650   (interactive "DAttach directory: \nP")
1651   (ess-execute (concat "attach(\""
1652                      (directory-file-name (expand-file-name dir))
1653                      "\""
1654                      (if posn (concat "," (number-to-string
1655                                            (prefix-numeric-value posn))))
1656                      ")") 'buffer)
1657   (setq ess-sp-change t))
1658
1659 (defun ess-execute-screen-options ()
1660   "Cause S to set the \"width\" option to 1 less than the frame width.
1661 Also sets the \"length\" option to 99999.
1662 This is a good thing to put in `ess-post-run-hook' --- for the S dialects."
1663   (interactive)
1664   (if (string= ess-language "S")
1665       (ess-eval-linewise (format "options(width=%d,length=99999)"
1666                                  (1- (frame-width))))))
1667
1668 (defun ess-execute (command &optional invert buff message)
1669   "Send a command to the ESS process.
1670 A newline is automatically added to COMMAND.  Prefix arg (or second arg
1671 INVERT) means invert the meaning of
1672 `ess-execute-in-process-buffer'.  If INVERT is 'buffer, output is
1673 forced to go to the process buffer.  If the output is going to a
1674 buffer, name it *BUFF*.  This buffer is erased before use.  Optional
1675 fourth arg MESSAGE is text to print at the top of the buffer (defaults
1676 to the command if BUFF is not given.)"
1677   (interactive (list
1678                 (read-from-minibuffer "Execute> "
1679                                       nil
1680                                       ess-mode-minibuffer-map)
1681                 current-prefix-arg))
1682   (ess-make-buffer-current)
1683   (let ((the-command (concat command "\n"))
1684         (buff-name (concat "*" (or buff "ess-output") "*"))
1685         (in-pbuff (if invert (or (eq invert 'buffer)
1686                                  (not ess-execute-in-process-buffer))
1687                     ess-execute-in-process-buffer)))
1688     (if in-pbuff
1689         (ess-eval-linewise the-command)
1690       (let ((buff (ess-create-temp-buffer buff-name)))
1691         (save-excursion
1692           (set-buffer buff)
1693           (ess-command the-command (get-buffer buff-name));; sleep?
1694           (goto-char (point-min))
1695           (if message (insert message)
1696             (if buff nil
1697               ;; Print the command in the buffer if it has not been
1698               ;; given a special name
1699               (insert "> " the-command)))
1700           ;;(make-local-variable 'ess-local-process-name)
1701           (setq ess-local-process-name ess-current-process-name))
1702         (ess-display-temp-buffer buff)))))
1703
1704 ;;;*;;; Quitting
1705
1706 (defun ess-quit ()
1707   "Issue an exiting command to the inferior process, additionally
1708 also running \\[ess-cleanup].  For R, runs \\[ess-quit-r], see there."
1709   (interactive)
1710   (if (string-equal ess-dialect "R")
1711       (ess-quit-r)
1712   (ess-force-buffer-current "Process to quit: ")
1713   (ess-make-buffer-current)
1714   (let ((sprocess (get-ess-process ess-current-process-name)))
1715     (if (not sprocess) (error "No ESS process running."))
1716       (when (yes-or-no-p (format "Really quit ESS process %s? " sprocess))
1717           (ess-cleanup)
1718           (goto-char (marker-position (process-mark sprocess)))
1719           (insert inferior-ess-exit-command)
1720         (process-send-string sprocess inferior-ess-exit-command)
1721         ;;SJE - suggest no need to rename buffer upon exit.
1722         ;;(rename-buffer (concat (buffer-name) "-exited") t)
1723         ))))
1724
1725 (defun ess-quit-r ()
1726   "Issue an exiting command to an inferior R process, and optionally clean up.
1727 This version is for killing *R* processes; it asks the extra question
1728 regarding whether the workspace image should be saved."
1729   (ess-force-buffer-current "Process to quit: ")
1730   (ess-make-buffer-current)
1731   (let (cmd
1732 ;;Q     response
1733         (sprocess (get-ess-process ess-current-process-name)))
1734     (if (not sprocess) (error "No ESS process running."))
1735 ;;Q     (setq response (completing-read "Save workspace image? "
1736 ;;Q                                 '( ( "yes".1) ("no" . 1) ("cancel" . 1))
1737 ;;Q                                 nil t))
1738 ;;Q     (if (string-equal response "")
1739 ;;Q     (setq response "default")); which will ask again (in most situations)
1740 ;;Q     (unless (string-equal response "cancel")
1741       (ess-cleanup)
1742 ;;Q   (setq cmd (format "q(\"%s\")\n" response))
1743       (setq cmd "q()\n")
1744       (goto-char (marker-position (process-mark sprocess)))
1745       (process-send-string sprocess cmd)
1746       ;;(rename-buffer (concat (buffer-name) "-exited") t)
1747 ;;Q      )
1748   ))
1749
1750 (defun ess-abort ()
1751   "Kill the ESS process, without executing .Last or terminating devices.
1752 If you want to finish your session, use \\[ess-quit] instead."
1753 ;;; Provided as a safety measure over the default binding of C-c C-z in
1754 ;;; comint-mode-map.
1755   (interactive)
1756   (ding)
1757   (message "WARNING: \\[inferior-ess-exit-command] will not be executed and graphics devices won't finish properly!")
1758   (sit-for 2)
1759   (if (yes-or-no-p "Still abort? ")
1760       (comint-quit-subjob)
1761     (message "Good move.")))
1762
1763 (defun ess-cleanup ()
1764   "Possibly kill or offer to kill, depending on the value of
1765 `ess-S-quit-kill-buffers-p', all buffers associated with this ESS process.
1766 Leaves you in the ESS process buffer.  It's a good idea to run this
1767 before you quit.  It is run automatically by \\[ess-quit]."
1768   (interactive)
1769   (let ((the-procname (or (ess-make-buffer-current) ess-local-process-name)))
1770     (if the-procname nil
1771       (error "I don't know which ESS process to clean up after!"))
1772     (if
1773         (or (eq ess-S-quit-kill-buffers-p t)
1774             (and
1775              (eq ess-S-quit-kill-buffers-p 'ask)
1776              (y-or-n-p
1777          (format
1778                "Delete all buffers associated with process %s? " the-procname))))
1779           (save-excursion
1780           (mapcar '(lambda (buf)
1781                      (set-buffer buf)
1782                      ;; Consider buffers for which
1783                      ;; ess-local-process-name is the same as
1784                      ;; the-procname
1785                      (if (and (not (get-buffer-process buf))
1786                               ess-local-process-name
1787                               (equal ess-local-process-name the-procname))
1788                          (kill-buffer buf)))
1789                   (buffer-list))))
1790     (ess-switch-to-ESS nil)))
1791
1792 (defun ess-kill-buffer-function nil
1793   "Function run just before an ESS process buffer is killed."
1794   ;; This simply deletes the buffers process to avoid an Emacs bug
1795   ;; where the sentinel is run *after* the buffer is deleted
1796   (let ((proc (get-buffer-process (current-buffer))))
1797     (if proc (delete-process proc))))
1798
1799 ;;*;; Object name completion
1800
1801 ;;;*;;; The user completion command
1802 (defun ess-complete-object-name (&optional listcomp)
1803   "Perform completion on `ess-language' object preceding point.
1804 The object is compared against those objects known by
1805 `ess-get-object-list' and any additional characters up to ambiguity are
1806 inserted.  Completion only works on globally-known objects (including
1807 elements of attached data frames), and thus is most suitable for
1808 interactive command-line entry, and not so much for function editing
1809 since local objects (e.g. argument names) aren't known.
1810
1811 Use \\[ess-resynch] to re-read the names of the attached directories.
1812 This is done automatically (and transparently) if a directory is
1813 modified (S only!), so the most up-to-date list of object names is always
1814 available.  However attached dataframes are *not* updated, so this
1815 command may be necessary if you modify an attached dataframe.
1816
1817 If ARG is non-nil, no completion is attempted, but the available
1818 completions are listed [__UNIMPLEMENTED__]."
1819   (interactive "P");; FIXME : the `listcomp' argument is NOT used
1820   (ess-make-buffer-current)
1821   (if (memq (char-syntax (preceding-char)) '(?w ?_))
1822       (let* ((comint-completion-addsuffix nil)
1823              (end (point))
1824              (buffer-syntax (syntax-table))
1825              (beg (unwind-protect
1826                       (save-excursion
1827                         (set-syntax-table ess-mode-syntax-table)
1828                         (backward-sexp 1)
1829                         (point))
1830                     (set-syntax-table buffer-syntax)))
1831              (full-prefix (buffer-substring beg end))
1832              (pattern full-prefix)
1833              ;; See if we're indexing a list with `$'
1834              (listname (if (string-match "\\(.+\\)\\$\\(\\(\\sw\\|\\s_\\)*\\)$"
1835                                          full-prefix)
1836                            (progn
1837                              (setq pattern
1838                                    (if (not (match-beginning 2)) ""
1839                                      (substring full-prefix
1840                                                 (match-beginning 2)
1841                                                 (match-end 2))))
1842                              (substring full-prefix (match-beginning 1)
1843                                         (match-end 1)))))
1844              ;; are we trying to get a slot via `@' ?
1845              (classname (if (string-match "\\(.+\\)@\\(\\(\\sw\\|\\s_\\)*\\)$"
1846                                          full-prefix)
1847                            (progn
1848                              (setq pattern
1849                                    (if (not (match-beginning 2)) ""
1850                                      (substring full-prefix
1851                                                 (match-beginning 2)
1852                                                 (match-end 2))))
1853                              (ess-write-to-dribble-buffer
1854                               (format "(ess-C-O-Name : slots..) : patt=%s"
1855                                       pattern))
1856                              (substring full-prefix (match-beginning 1)
1857                                         (match-end 1)))))
1858              (components (if listname
1859                              (ess-object-names listname)
1860                            (if classname
1861                                (ess-slot-names classname)
1862                              (ess-get-object-list ess-current-process-name)))))
1863         ;; always return a non-nil value to prevent history expansions
1864         (or (comint-dynamic-simple-complete  pattern components) 'none))))
1865
1866 (defun ess-list-object-completions nil
1867   "List all possible completions of the object name at point."
1868   (interactive)
1869   (ess-complete-object-name t));; FIXME: NOT WORKING since argument is unused!
1870
1871 ;;;*;;; Support functions
1872 (defun ess-extract-onames-from-alist (alist posn &optional force)
1873   "Return the object names in position POSN of ALIST.
1874 ALIST is an alist like `ess-sl-modtime-alist'. POSN should be in 1 .. (length
1875 ALIST).  If optional third arg FORCE is t, the corresponding element
1876 of the search list is re-read. Otherwise it is only re-read if it's a
1877 directory and has been modified since it was last read."
1878   (let* ((entry (nth (1- posn) alist))
1879          (dir (car entry))
1880          (timestamp (car (cdr entry)))
1881          (new-modtime (ess-dir-modtime dir)))
1882     ;; Refresh the object listing if necessary
1883     (if (or force (not (equal new-modtime timestamp)))
1884       (setcdr (cdr entry) (ess-object-names dir posn)))
1885     (cdr (cdr entry))))
1886
1887 (defun ess-dir-modtime (dir)
1888   "Return the last modtime if DIR is a directory, and nil otherwise."
1889   (and ess-filenames-map
1890        (file-directory-p dir)
1891        (nth 5 (file-attributes dir))))
1892
1893 (defun ess-object-modtime (object)
1894   "Return the modtime of the S object OBJECT (a string).
1895 Searches along the search list for a file named OBJECT and returns its modtime
1896 Returns nil if that file cannot be found, i.e., for R or any non-S language!"
1897   (let ((path (ess-search-list))
1898         result)
1899     (while (and (not result) path)
1900       (setq result (file-attributes
1901                     (concat (file-name-as-directory (car path))
1902                             object)))
1903       (setq path (cdr path)))
1904     (nth 5 result)))
1905
1906 (defun ess-modtime-gt (mod1 mod2)
1907   "Return t if MOD1 is later than MOD2."
1908   (and mod1
1909        (or (> (car mod1) (car mod2))
1910            (and (= (car mod1) (car mod2))
1911                 (> (car (cdr mod1)) (car (cdr mod2)))))))
1912
1913 (defun ess-get-object-list (name)
1914   "Return a list of current S object names associated with process NAME,
1915 using `ess-object-list' if that is non-nil."
1916   (or ess-object-list
1917       (save-excursion
1918         (set-buffer (process-buffer (get-ess-process name)))
1919         (ess-make-buffer-current)
1920         (ess-write-to-dribble-buffer (format "(get-object-list %s) .." name))
1921         (if (or (not ess-sl-modtime-alist) ess-sp-change)
1922             (progn (ess-write-to-dribble-buffer "--> (ess-get-modtime-list)\n")
1923             (ess-get-modtime-list))
1924           ;;else
1925           (ess-write-to-dribble-buffer " using existing ess-*-alist\n")
1926           )
1927         (let* ((alist ess-sl-modtime-alist)
1928                (i 2)
1929                (n (length alist))
1930                result)
1931           ;; Always force a re-read of position 1 :
1932           (setq result (ess-extract-onames-from-alist alist 1 'force))
1933           ;; Re-read remaining directories if necessary.
1934           (while (<= i n)
1935             (setq result
1936                   (append result
1937                           (ess-extract-onames-from-alist alist i)))
1938             (setq i (1+ i)))
1939           (setq ess-object-list (ess-uniq-list result))))))
1940
1941 (defun ess-get-words-from-vector (command)
1942   "Evaluate the S command COMMAND, which returns a character vector.
1943 Return the elements of the result of COMMAND as an alist of strings.
1944 A newline is automatically added to COMMAND."
1945   (let ((tbuffer (get-buffer-create
1946                   " *ess-names-list*")); initial space: disable-undo
1947         names)
1948     (save-excursion
1949       (set-buffer tbuffer)
1950       (ess-command command tbuffer 'sleep)
1951       (goto-char (point-min))
1952       (if ess-verbose (ess-write-to-dribble-buffer "ess-get-words-.. "))
1953       (if (not (looking-at "\\s-*\\[1\\]"))
1954           (progn (if ess-verbose
1955                      (ess-write-to-dribble-buffer "not seeing \"[1]\".. "))
1956           (setq names nil)
1957           )
1958         (goto-char (point-max))
1959         (while (re-search-backward "\"\\([^\"]*\\)\"" nil t)
1960           (setq names (cons (buffer-substring (match-beginning 1)
1961                                               (match-end 1)) names))))
1962       ;;DBG, do *not* (i.e., comment):
1963       (kill-buffer tbuffer)
1964       )
1965     (if ess-verbose
1966         (ess-write-to-dribble-buffer
1967          (if (> (length names) 5)
1968              (format " |-> (length names)= %d\n" (length names))
1969            (format " |-> names= '%s'\n" names))))
1970     names))
1971
1972 (defun ess-compiled-dir (dir)
1973   "Return non-nil if DIR is an S object directory with special files.
1974 I.e. if the filenames in DIR are not representative of the objects in DIR."
1975   (or (file-exists-p (concat (file-name-as-directory dir) "___nonfile"))
1976       (file-exists-p (concat (file-name-as-directory dir) "__BIGIN"))
1977       (file-exists-p (concat (file-name-as-directory dir) "___NONFI"))))
1978
1979 (defun ess-object-names (obj &optional pos)
1980   "Return alist of S object names in directory (or object) OBJ.
1981 If OBJ is a directory name (begins with `/') returns a listing of that dir.
1982    This may use the search list position POS if necessary.
1983 If OBJ is an object name, returns result of S command names(OBJ).
1984 If OBJ is nil or not a directory, POS must be supplied, and objects(POS) is returned.
1985 In all cases, the value is an list of object names."
1986
1987 ;; FIXME: in both cases below, use the same fallback "objects(POS)" -- merge!
1988   (if (and obj (file-accessible-directory-p obj))
1989       ;; Check the pre-compiled object list in ess-object-name-db first
1990
1991       ;; FIXME: If used at all, ess-object-name-db should not only
1992       ;; -----  be used in the directory case !!
1993       (or (cdr-safe (assoc obj ess-object-name-db))
1994           ;; Take a directory listing
1995           (and ess-filenames-map
1996                ;; first try .Data subdirectory:
1997                ;;FIXME: move ".Data" or ``this function'' to essd-sp6.el etc:
1998                (let ((dir (concat (file-name-as-directory obj) ".Data")))
1999                  (if (not (file-accessible-directory-p dir))
2000                      (setq dir obj))
2001                  (and (not (ess-compiled-dir dir))
2002                       (directory-files dir))))
2003           ;; Get objects(pos) instead
2004           (and (or (ess-write-to-dribble-buffer
2005                     (format "(ess-object-names ..): directory %s not used\n" obj))
2006                    t)
2007                pos
2008           (ess-get-words-from-vector
2009                 (format inferior-ess-objects-command pos))))
2010           ;; "else" should really give an error!
2011           ;; would need  pos = which(obj = search())
2012
2013     ;; else
2014     (or (and obj  ;; want names(obj)
2015              (or (ess-write-to-dribble-buffer
2016                   (format "(ess-object-names obj=%s): no directory - trying names\n"
2017                           obj))
2018                  t)
2019              (ess-get-words-from-vector
2020                   (format inferior-ess-names-command obj)))
2021         (and nil; must return nil
2022              (ess-write-to-dribble-buffer
2023               (format "(ess-object-names obj=%s): no dir.; -> objects()\n" obj)))
2024         ;; get objects(pos)
2025         (ess-get-words-from-vector
2026          (format inferior-ess-objects-command pos))))) ; had 2nd arg ".*"
2027                                         ; s4 needs 2
2028                                         ; args, rest only need 1 ?
2029                                         ; changes needed to allow for
2030                                         ; pattern argument to
2031                                         ; .SmodeObs
2032
2033 (defun ess-slot-names (obj)
2034   "Return alist of S4 slot names of S4 object OBJ."
2035   (ess-get-words-from-vector (format "slotNames(%s)\n" obj)))
2036
2037
2038 ;;; SJE: Wed 29 Dec 2004 --- remove this function.
2039 ;;; rmh: Wed 5 Jan 2005 --- bring it back for use on Windows
2040 (defun ess-create-object-name-db ()
2041   "Create a database of object names in standard S directories.  This
2042 database is saved in the file specified by `ess-object-name-db-file',
2043 and is loaded when `ess-mode' is loaded. It defines the variable
2044 `ess-object-name-db', which is used for completions.
2045
2046 Before you call this function, modify the S search list so that it contains
2047 all the non-changing (i.e. system) S directories.  All positions of the search
2048 list except for position 1 are searched and stored in the database.
2049
2050 After running this command, you should move ess-namedb.el to a directory in
2051 the `load-path'."
2052   (interactive)
2053   (setq ess-object-name-db nil)
2054   (let ((search-list (cdr (ess-search-list)))
2055         (pos 2)
2056         name
2057         (buffer (get-buffer-create " *ess-db*"))
2058         (temp-object-name-db nil)
2059         (temp-object-name-db-file ess-object-name-db-file))
2060
2061     (ess-write-to-dribble-buffer
2062      (format "(object db): search-list=%s \n " search-list))
2063     (while search-list
2064       (message "Searching %s" (car search-list))
2065       (setq temp-object-name-db (cons (cons (car search-list)
2066                                             (ess-object-names nil pos))
2067                                       temp-object-name-db))
2068       (setq search-list (cdr search-list))
2069       (ess-write-to-dribble-buffer
2070        (format "(object db): temp-obj-name-db=%s \n pos=%s"
2071                temp-object-name-db pos))
2072       (setq pos (1+ pos)))
2073
2074     (save-excursion
2075       (set-buffer buffer)
2076       (erase-buffer)
2077       (insert "(setq ess-object-name-db '")
2078       (prin1 temp-object-name-db (current-buffer))
2079       (insert ")\n")
2080       (setq name (expand-file-name ess-object-name-db-file))
2081       (write-region (point-min) (point-max) name)
2082       (message "Wrote %s" name))
2083     (kill-buffer buffer)
2084     (setq ess-object-name-db temp-object-name-db)))
2085
2086 (defun ess-resynch nil
2087   "Reread all directories/objects in variable `ess-search-list' to
2088 form completions."
2089  (interactive)
2090  (if (ess-make-buffer-current) nil
2091    (error "Not an ESS process buffer"))
2092  (setq ess-sl-modtime-alist nil)
2093  (setq ess-object-list nil)
2094  (setq ess-object-name-db nil)          ; perhaps it would be better to reload?
2095  (setq ess-sp-change t)
2096  (ess-get-modtime-list))
2097
2098
2099 (defun ess-complete-filename nil
2100   ;; Do file completion only within strings, or when the ! call is being used
2101   (if (comint-within-quotes
2102        (1- (process-mark (get-buffer-process (current-buffer)))) (point))
2103       ;; (- comint-last-input-start 1) (point))  <- from S4 modeadds.
2104       ;; changed on 4/12/96 (dxsun)
2105       ;; This is sensible, but makes it hard to use history refs
2106       ;; (or
2107       ;;  (save-excursion
2108       ;;    (goto-char comint-last-input-start)
2109       ;;    (looking-at "\\s-*!"))
2110       ;;  (comint-within-quotes comint-last-input-start (point)))
2111       (progn
2112         (comint-replace-by-expanded-filename)
2113         ;; always return t if in a string
2114         t)))
2115
2116 (defun ess-after-pathname-p nil
2117   ;; Heuristic: after partial pathname if it looks like we're in a
2118   ;; string, and that string looks like a pathname. Not the best for
2119   ;; use with unix() (or it's alias, !). Oh well.
2120   (save-excursion
2121     (save-match-data
2122       (let ((opoint (point)))
2123         (and (re-search-backward "\\(\"\\|'\\)[~/#$.a-zA-Z0-9][^ \t\n\"']*"
2124                                  nil t)
2125              (eq opoint (match-end 0)))))))
2126
2127 ;;*;; Functions handling the search list
2128
2129 (defun ess-search-list ()
2130   "Return the current search list as a list of strings.
2131 Elements which are apparently directories are expanded to full dirnames.
2132 Is *NOT* used by \\[ess-execute-search],
2133 but by \\[ess-resynch], \\[ess-get-object-list], \\[ess-get-modtime-list],
2134 \\[ess-execute-objects], \\[ess-object-modtime], \\[ess-create-object-name-db],
2135 and (indirectly) by \\[ess-get-help-files-list]."
2136   (save-excursion
2137     (let ((result nil))
2138       (set-buffer (get-ess-buffer ess-current-process-name));to get *its* local vars
2139       (if (and ess-search-list (not ess-sp-change))
2140           ;; use cache:
2141           ess-search-list
2142         ;; else, re-compute:
2143         (let ((tbuffer (get-buffer-create " *search-list*"))
2144               (homedir ess-directory)
2145               (my-search-cmd inferior-ess-search-list-command); from ess-buffer
2146               elt)
2147           (save-excursion
2148             (set-buffer tbuffer)
2149             ;; guaranteed by the initial space in its name: (buffer-disable-undo)
2150             (ess-command my-search-cmd tbuffer 0.2); <- sleep; does (erase-buffer)
2151             (goto-char (point-min))
2152             (while (re-search-forward "\"\\([^\"]*\\)\"" nil t)
2153               (setq elt (buffer-substring (match-beginning 1) (match-end 1)))
2154               ;;Dbg: (ess-write-to-dribble-buffer (format "  .. elt= %s \t" elt))
2155               (if (and (string-match "^[^/]" elt)
2156                        (file-directory-p (concat ess-directory elt)))
2157                   (progn
2158                     ;;Dbg: (ess-write-to-dribble-buffer "*IS* directory\n")
2159                     (setq elt (concat homedir elt)))
2160                 ;;else
2161                 ;;dbg
2162                 ;;-             (ess-write-to-dribble-buffer "not dir.\n")
2163                 )
2164               (setq result (append result (list elt))))
2165             (kill-buffer tbuffer)))
2166         (setq ess-search-list result)
2167         (setq ess-sp-change nil)
2168         result))))
2169
2170 ;;; ess-sl-modtime-alist is a list with elements as follows:
2171 ;;;  * key             (directory or object name)
2172 ;;;  * modtime         (list of 2 integers)
2173 ;;;  * name, name ...  (accessible objects in search list posn labeled by key)
2174 ;;; It is a buffer-local variable (belonging to e.g. *R*, *S+6*, .. etc)
2175 ;;; and has the same number of elements and is in the same order as the
2176 ;;; S search list
2177
2178 (defun ess-get-modtime-list ()
2179   "Record the modification times of the directories in the search list,
2180 and the objects in those directories.
2181 The result is stored in `ess-sl-modtime-alist'."
2182   ;; Operation applies to process of current buffer
2183   (let* ((searchlist (ess-search-list))
2184          (index 1)
2185          posn
2186          newalist)
2187     (while searchlist
2188       (setq posn (car searchlist))
2189       (setq newalist
2190             (append
2191              newalist
2192              (list (or (assoc posn ess-sl-modtime-alist)
2193                        (append
2194                         (list posn (ess-dir-modtime posn))
2195                         (prog2
2196                             (message "Forming completions for %s..." posn)
2197                             (ess-object-names posn index)
2198                           (message "Forming completions for %s...done" posn)
2199                           ))))))
2200       (setq index (1+ index))
2201       (setq searchlist (cdr searchlist)))
2202     ;;DBG:
2203     (ess-write-to-dribble-buffer
2204      (format "ess-get-modtime-list: new alist of length %d\n"
2205              (length newalist)));; todo : also give length of components!
2206
2207     (setq ess-sl-modtime-alist newalist)))
2208
2209
2210 (defun ess-search-path-tracker (str)
2211   "Check if input STR changed the search path.
2212 This function monitors user input to the inferior ESS process so that
2213 Emacs can keep the variable `ess-search-list' up to date. `completing-read' in
2214 \\[ess-read-object-name] uses this list indirectly when it prompts for help or
2215 for an object to dump."
2216   (if (string-match ess-change-sp-regexp str)
2217       (setq ess-sp-change t)))
2218
2219 \f ; Miscellaneous routines
2220
2221 ;;;*;;; Routines for reading object names
2222
2223 (defun ess-read-object-name (p-string)
2224   "Read an S object name from the minibuffer with completion, and return it.
2225 P-STRING is the prompt string."
2226   (let* ((default (ess-read-object-name-dump))
2227          (prompt-string (if default
2228                             (format "%s(default %s) " p-string default)
2229                           p-string))
2230          (object-list (mapcar 'list (ess-get-object-list ess-local-process-name)))
2231          (spec (completing-read prompt-string object-list)))
2232     (list (cond
2233            ((string= spec "") default)
2234            (t spec)))))
2235
2236 (defun ess-read-object-name-default ()
2237   "Return the object name at point, or nil if none."
2238   (condition-case ()
2239       (save-excursion
2240         ;; The following line circumvents an 18.57 bug in following-char
2241         (if (eobp) (backward-char 1)) ; Hopefully buffer is not empty!
2242         ;; Get onto a symbol
2243         (catch 'nosym ; bail out if there's no symbol at all before point
2244           (while (/= (char-syntax (following-char)) ?w)
2245             (if (bobp) (throw 'nosym nil) (backward-char 1)))
2246           (let*
2247               ((end (progn (forward-sexp 1) (point)))
2248                (beg (progn (backward-sexp 1) (point))))
2249             (buffer-substring beg end))))
2250     (error nil)))
2251
2252 (defun ess-read-object-name-dump ()
2253   "Return the object name at point, or \"Temporary\" if none."
2254   (condition-case ()
2255       (save-excursion
2256         ;; The following line circumvents an 18.57 bug in following-char
2257         (if (eobp) (backward-char 1)) ; Hopefully buffer is not empty!
2258         ;; Get onto a symbol
2259         (catch 'nosym ; bail out if there's no symbol at all before point
2260           (while (/= (char-syntax (following-char)) ?w)
2261             (if (bobp) (throw 'nosym nil) (backward-char 1)))
2262           (let*
2263               ((end (progn (forward-sexp 1) (point)))
2264                (beg (progn (backward-sexp 1) (point)))
2265                (object-name (buffer-substring beg end)))
2266             (or object-name "Temporary"))))
2267     (error nil)))
2268
2269
2270 ;;*;; Temporary buffer handling
2271
2272 ;(defun ess-create-temp-buffer (name)
2273 ;  "Create an empty buffer called NAME, but doesn't display it."
2274 ;  (let ((buff (get-buffer-create name)))
2275 ;    (save-excursion
2276 ;      (set-buffer buff)
2277 ;      (erase-buffer))
2278 ;    buff))
2279
2280
2281 ;; Ed Kademan's version:
2282 ;From: Ed Kademan <kademan@phz.com>
2283 ;Subject: Re: ess-mode 5.1.16; search list
2284 ;To: rossini@biostat.washington.edu (A.J. Rossini)
2285 ;Cc: Martin Maechler <maechler@stat.math.ethz.ch>, ess-bugs@stat.math.ethz.ch
2286 ;Date: 26 Jul 2000 16:12:12 -0400
2287 ;
2288 ;Dear Tony Rossini,
2289 ;
2290 ;I was having trouble looking at the search list under ess.  When I
2291 ;started up multiple inferior processes---each for a different
2292 ;dialect---ess-mode would issue the wrong variant of the "search"
2293 ;command when I typed C-c C-s.  In case it is useful let me tell you
2294 ;what I did to get it to work for me.
2295 ;
2296 ;I added the component:
2297 ;  (inferior-ess-search-list-command . "search()\n")
2298 ;to S+3-customize-alist and R-customize-alist, and then I redefined the
2299 ;ess-create-temp-buffer function as follows:
2300 (defun ess-create-temp-buffer (name)
2301   "Create an empty buffer called NAME."
2302   (let ((buff (get-buffer-create name))
2303         (elca (eval ess-local-customize-alist)))
2304     (save-excursion
2305       (set-buffer buff)
2306       (erase-buffer)
2307       (ess-setq-vars-local elca buff))
2308     buff))
2309 ;;These two steps seem to insure that the temporary buffer in which the
2310 ;;search results appear has the correct version of the local variables.
2311 ;;I am not that well acquainted with the ess code and don't know whether
2312 ;;this is a good fundamental way of fixing the problem, or even whether
2313 ;;or not this breaks some other feature of ess-mode that I never use.
2314 ;;Thanks for listening.
2315 ;;Ed K.
2316 ;;--
2317 ;;Ed Kademan              508.651.3700
2318 ;;PHZ Capital Partners    508.653.1745 (fax)
2319 ;;321 Commonwealth Road   <kademan@phz.com>
2320 ;;Wayland, MA 01778
2321
2322
2323
2324 (defun ess-display-temp-buffer (buff)
2325   "Display the buffer BUFF using `temp-buffer-show-function'."
2326   (funcall (or temp-buffer-show-function 'display-buffer) buff))
2327
2328 ;;*;; Error messages
2329
2330 (defun ess-error (msg)
2331   "Something bad has happened.
2332 Display the S buffer, and cause an error displaying MSG."
2333   (display-buffer (process-buffer (get-ess-process ess-current-process-name)))
2334   (error msg))
2335
2336 \f ; Provide package
2337
2338 (provide 'ess-inf)
2339
2340 \f ; Local variables section
2341
2342 ;;; This file is automatically placed in Outline minor mode.
2343 ;;; The file is structured as follows:
2344 ;;; Chapters:     ^L ;
2345 ;;; Sections:    ;;*;;
2346 ;;; Subsections: ;;;*;;;
2347 ;;; Components:  defuns, defvars, defconsts
2348 ;;;              Random code beginning with a ;;;;* comment
2349
2350 ;;; Local variables:
2351 ;;; mode: emacs-lisp
2352 ;;; outline-minor-mode: nil
2353 ;;; mode: outline-minor
2354 ;;; outline-regexp: "\^L\\|\\`;\\|;;\\*\\|;;;\\*\\|(def[cvu]\\|(setq\\|;;;;\\*"
2355 ;;; End:
2356
2357 ;;; ess-inf.el ends here