-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
sage-shell-mode.el
5617 lines (5024 loc) · 221 KB
/
sage-shell-mode.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; sage-shell-mode.el --- A front-end for Sage Math -*- lexical-binding: t -*-
;; Copyright (C) 2012 - 2018 Sho Takemori.
;; Author: Sho Takemori <stakemorii@gmail.com>
;; URL: https://github.com/sagemath/sage-shell-mode
;; Package-Requires: ((cl-lib "0.6.1") (emacs "24.4") (let-alist "1.0.5") (deferred "0.5.1"))
;; Keywords: Sage, math
;; Version: 0.3
;;; License
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This package provides a front end for Sage (http://www.sagemath.org/)
;; and a major mode derived from python-mode (sage-shell:sage-mode).
;; To use this package, check the return value of (executable-find "sage").
;; If (executable-find "sage") is a string, you are ready to use this package.
;; If not, put the following line to ~/.emacs.d/init.el
;; (setq sage-shell:sage-root "/path/to/sage/root_directory")
;; And replace /path/to/sage/root_directory to the path to $SAGE_ROOT.
;; Then you can run Sage process in Emacs by M-x sage-shell:run-sage.
;; You can run multiple Sage processes by M-x sage-shell:run-new-sage.
;; By putting the following line to ~/.emacs.d/init.el,
;; (sage-shell:define-alias)
;; you can run Sage by M-x run-sage instead of M-x sage-shell:run-sage.
;; Please visit https://github.com/sagemath/sage-shell-mode for more
;; information.
;;; Code:
;; TODO
;; 1. Disabel auto indent (cf. IPython's issue #9888).
;; 2. Fix sage-shell-edit:exec-command-base when the line is not empty.
;; 3. Add support for simple prompt.
;; 4. Fix sage-shell-edit:exec-command-base when insert-command-p is non-nil.
;; Requiring cl-lib when compile time is necessary in Emacs 24.1 and 24.2
(require 'md5)
(eval-and-compile (require 'cl-lib)
(require 'let-alist))
(require 'deferred)
(require 'pcomplete)
(require 'eldoc)
(require 'info)
;;; Global variables for users
(defgroup sage-shell
nil "Run Sage process in a buffer."
:group 'languages)
(defgroup sage-shell-sagetex
nil "Group for SageTeX."
:group 'sage-shell)
(defcustom sage-shell:sage-root nil
"SAGE_ROOT directory. If the Sage executable in your PATH
and (executable-find \"sage\") is non-nil, then you do not have
to set this variable."
:group 'sage-shell
:type '(choice (directory :tag "Directory")
(const :tag "Not specified" nil)))
(defcustom sage-shell:sage-executable nil
"Name of the Sage executable. If the Sage executable in your
PATH and (exeutable-find \"sage\") is non-nil, then you do not
have to set this variable."
:group 'sage-shell
:type '(choice (string :tag "Executable file of Sage")
(const :tag "Not specified" nil)))
;;;###autoload
(defvaralias 'sage-shell:command 'sage-shell:sage-executable)
(defcustom sage-shell:input-history-cache-file
nil
"If non nil, then `comint-input-ring' is saved to this file
when the Sage process exits."
:group 'sage-shell
:type '(choice (file :tag "file")
(const :tag "Off" nil)))
(defcustom sage-shell:completion-function 'completion-at-point
"Function used for `sage-shell:complete'."
:group 'sage-shell
:type '(choice (const :tag "default" completion-at-point)
(const :tag "pcomplete" pcomplete)
(const :tag "auto-complete" auto-complete)
(const :tag "anything" anything-sage-shell)
(const :tag "helm" helm-sage-shell)))
(defcustom sage-shell:help-completion-function 'sage-shell:help1
"Completion function used for `sage-shell:help'."
:group 'sage-shell
:type '(choice
(const :tag "default" sage-shell:help1)
(const :tag "anything" anything-sage-shell-describe-object-at-point)
(const :tag "helm" helm-sage-shell-describe-object-at-point)))
(defcustom sage-shell:use-unicode-banner t
"Non-nil means use unicode character in Sage's banner."
:type 'boolean
:group 'sage-shell)
(defcustom sage-shell:completion-ignore-case nil
"Non-nil means don't consider case significant in completion."
:type 'boolean
:group 'sage-shell)
(defcustom sage-shell:completion-candidate-regexp (rx (1+ (or alnum "_")))
"Regexp used for collect completions when completion-at-point is called."
:type 'regexp
:group 'sage-shell)
(defcustom sage-shell:make-error-link-p t
"If non-nil and the output contains an error line,
output-filter-function creates a link to the file where the error
is raised."
:type 'boolean
:group 'sage-shell)
(defcustom sage-shell:prefer-development-file-p t
"If non nil, prefer a source file in src directory rather than
site-packages directory."
:group 'sage-shell
:type 'boolean)
(defcustom sage-shell-pdb:activate t
"Non-nil makes Sage shell enable pdbtracking."
:type 'boolean
:group 'sage-shell)
;;; Borrowed from esh-mode.el (eshell).
(defcustom sage-shell:scroll-show-maximum-output t
"Controls how interpreter output causes window to scroll.
If non-nil, then show the maximum output when the window is scrolled."
:type 'boolean
:group 'sage-shell)
(defcustom sage-shell:scroll-to-the-bottom nil
"Non nil means scrolling to the bottom when sending the input."
:type 'boolean
:group 'sage-shell)
(defcustom sage-shell:list-outputs-max-line-num 5
"Max number of lines of the outputs displayed in the buffer created
by `sage-shell:list-outputs' and other related commands.
Nil means it does not truncate the outputs."
:type 'integer
:group 'sage-shell)
(defcustom sage-shell:list-outputs-reversed-order-p t
"Non nil means outputs ordered by the reversed order."
:type 'boolean
:group 'sage-shell)
(defcustom sage-shell-edit:display-function nil
"This variable handles how the process buffer will be
displayed. If non-nil, this function will be called after sending
the contents of a buffer, a region or a file to the Sage
process."
:type '(choice (const :tag "default" nil)
(const :tag "display-buffer" 'display-buffer)
(const :tag "pop-to-buffer" 'pop-to-buffer))
:group 'sage-shell)
(defcustom sage-shell:inspect-ingnore-classes nil
"If non-nil, this should be a list of strings.
Each string should be a class of Sage. When non-nil instances or methods
of these classes are ignored by `ac-quick-help' and `eldoc'.
If the value is equal to '(\"\"), then it does not ignore anything."
:group 'sage-shell
:type '(repeat string))
(defcustom sage-shell-edit:temp-file-header "# -*- coding: utf-8 -*-\n"
"`sage-shell-edit:send-region', `sage-shell-edit:send-buffer' and related
commands use a temporary file.
This string will be inserted to the temporary file before evaluating code."
:type 'string
:group 'sage-shell)
(defcustom sage-shell:use-prompt-toolkit nil
"Non `nil' means the Sage process uses the new prompt of IPython 5 and 6.
Must be disabled for Ipython >=7, which is incompatible"
:type 'boolean
:group 'sage-shell)
;; (make-variable-buffer-local 'sage-shell:use-prompt-toolkit)
(defcustom sage-shell:use-simple-prompt t
"Non `nil' means the Sage process must be started with the `simple-prompt'
option and use `readline' to interact with IPython >=7."
:type 'boolean
:group 'sage-shell)
(defcustom sage-shell:check-ipython-version-on-startup t
"Non `nil' means check if `sage-shell:use-prompt-toolkit' and
`sage-shell:simple-prompt' are correctly set when starting the Sage process.
The checking is done asyncally."
:type 'boolean
:group 'sage-shell)
(defcustom sage-shell:set-ipython-version-on-startup t
"Non `nil' means set `sage-shell:use-prompt-toolkit' and
`sage-shell:simple-prompt' according to the available IPython version.
This (synchronous) setting can be replaced by setting variables in the init file.")
(defcustom sage-shell-sagetex:pre-latex-command
"latex -interaction=nonstopmode"
"This LaTeX command will be called by
`sage-shell-sagetex:compile-file' before loading a .sagetex.sage
file."
:group 'sage-shell-sagetex
:type 'string)
(defcustom sage-shell-sagetex:latex-command "latex -interaction=nonstopmode"
"If `sage-shell-sagetex:auctex-command-name' is nil (by default
it is nil), then this variable is used for
`sage-shell-sagetex:compile-file' after loading a .sagetex.sage
file. It should be a LaTeX command without a file
name. `sage-shell-sagetex:compile-file' will call the LaTeX
command after loading a .sagetex.sage file."
:group 'sage-shell-sagetex
:type 'string)
(defcustom sage-shell-sagetex:auctex-command-name nil
"This variable is for AUCTeX users. If non-nil, it should be a
name of an element of `TeX-command-list', i.e. the first element
of an element of the list. Then the corresponding LaTeX command
will be called after loading a .sagetex.sage file by
`sage-shell-sagetex:compile-file'. If this value is
non-nil, then the value of `sage-shell-sagetex:latex-command'
will be ignored."
:group 'sage-shell-sagetex
:type '(choice (const :tag "Not Specified" nil)
(string :tag "LaTeX command")))
(defcustom sage-shell-sagetex:add-to-texinputs-p t
"Non-nil means sage-shell-mode adds
$SAGE_ROOT/local/share/texmf/tex/generic/sagetex/ to TEXINPUTS."
:type 'boolean
:group 'sage-shell-sagetex)
;;;###autoload
(defvaralias 'sage-shell:add-to-texinputs-p
'sage-shell-sagetex:add-to-texinputs-p)
(defcustom sage-shell-sagetex:pop-to-error-buffer t
"Non-nil means pop to the SageTeX error buffer."
:type 'boolean
:group 'sage-shell-sagetex)
(eval-and-compile
(cond ((fboundp 'setq-local)
(defmacro sage-shell:setq-local (var val)
(list 'setq-local var val)))
(t (defmacro sage-shell:setq-local (var val)
"Set variable VAR to value VAL in current buffer."
;; Can't use backquote here, it's too early in the bootstrap.
(list 'set (list 'make-local-variable (list 'quote var)) val)))))
;;; Anaphoric macros
(defmacro sage-shell:aand (&rest args)
"`it' is binded to the last evaluated argument"
(declare (indent 0) (debug t))
(cond ((null args) t)
((null (cdr args)) (car args))
(t `(sage-shell:aif ,(car args) (sage-shell:aand ,@(cdr args))))))
(defmacro sage-shell:aif (test-form then-form &rest else-forms)
" Temporary variable `it' is the result of test-form."
(declare (indent 2) (debug t))
`(let ((it ,test-form))
(if it ,then-form ,@else-forms)))
(defmacro sage-shell:awhen (test-form &rest then-forms)
" Temporary variable `it' is the result of test-form."
(declare (indent 1) (debug t))
`(let ((it ,test-form))
(when it ,@then-forms)))
;; utilities
(eval-when-compile
(defvar sage-shell:gensym-counter 0))
(defvar sage-shell:gensym-counter 0)
(defsubst sage-shell:gensym (&optional prefix)
"Generate a new uninterned symbol.
The name is made by appending a number to PREFIX, default
\"sage-shell-gensym-\"."
(if (fboundp 'cl-gensym)
(cl-gensym prefix)
(let ((pfix (if (stringp prefix) prefix "sage-shell-gensym-"))
(num (if (integerp prefix) prefix
(prog1 sage-shell:gensym-counter
(cl-incf sage-shell:gensym-counter)))))
(make-symbol (format "%s%d" pfix num)))))
(defsubst sage-shell:in (elt seq)
(if (member elt seq) elt))
(defun sage-shell:remove-if (pred seq)
(if (fboundp 'cl-remove-if)
(cl-remove-if pred seq)
(cl-loop for a in seq
unless (funcall pred a)
collect a)))
(defsubst sage-shell:nthcar-and-rest (m l)
(cl-loop for i from 0 to (1- m)
for a on l
collect (car a) into x
finally return (cons x a)))
(defsubst sage-shell:group (l &optional n)
(let ((r l)
(a nil)
(n (or n 2))
(res nil))
(while r
(setq a (sage-shell:nthcar-and-rest n r)
r (cdr a))
(push (car a) res))
(nreverse res)))
(defmacro sage-shell:if-let* (varlist test-form then-form &rest else-forms)
"VARLIST is like varlist of let*."
(declare (indent 3) (debug t))
`(let* ,varlist
(if ,test-form
,then-form
,@else-forms)))
(defmacro sage-shell:when-let* (varlist test-form &rest then-forms)
"VARLIST is like varlist of let*."
(declare (indent 2) (debug t))
`(let* ,varlist
(when ,test-form
,@then-forms)))
(defmacro sage-shell:unless-let* (varlist test-form &rest then-forms)
"VARLIST is like varlist of let*."
(declare (indent 2) (debug t))
`(let* ,varlist
(unless ,test-form
,@then-forms)))
(defmacro sage-shell:acond (&rest clauses)
(if (null clauses)
nil
(let ((cl1 (car clauses))
(sym (sage-shell:gensym "sage-shell")))
`(let ((,sym ,(car cl1)))
(if ,sym
(let ((it ,sym)) ,@(cdr cl1))
(sage-shell:acond ,@(cdr clauses)))))))
(cl-defmacro sage-shell:with-gensym ((&rest names) &rest body)
(declare (indent 1) (debug t))
`(let ,(cl-loop for n in names collect `(,n (sage-shell:gensym "sage-shell")))
,@body))
(defmacro sage-shell:define-keys (keymap &rest defs)
(declare (indent 1))
(append (list 'progn)
(cl-loop for i from 0 to (1- (/ (length defs) 2))
collect
`(define-key
,keymap
(kbd ,(nth (* 2 i) defs))
,(nth (1+ (* 2 i)) defs)))))
(defmacro sage-shell:as-soon-as (form &rest body)
(declare (indent 1))
(let ((sym (sage-shell:gensym "sage-shell")))
`(cond (,form (progn ,@body))
(t (let ((,sym nil))
(setq ,sym
(run-with-timer
0.01 0.01
(lambda () (condition-case err-var
(when ,form
(unwind-protect
(progn ,@body)
(cancel-timer ,sym)))
(error (cancel-timer ,sym)
(signal (car err-var)
(cdr err-var))))))))))))
(defmacro sage-shell:substitute-key-def (old-command new-command
search-keymap
def-keymap
&rest default-keys)
`(sage-shell:aif (where-is-internal ',old-command ,search-keymap)
(cl-loop for key in it
do (define-key ,def-keymap key ',new-command))
(cl-loop for key in (list ,@default-keys)
do (define-key ,def-keymap key ',new-command))))
(defun sage-shell:get-value (value-or-func &rest args)
"If VALUE-OR-FUNC is a function, then this returns the value
returned from the function, otherwise, this returns it self. "
(if (functionp value-or-func)
(apply value-or-func args)
value-or-func))
(defsubst sage-shell:line-beginning-position ()
(let ((inhibit-field-text-motion t))
(line-beginning-position)))
(defmacro sage-shell:with-current-buffer-safe (buf-maybe &rest body)
(declare (indent 1))
`(when (and (buffer-live-p ,buf-maybe)
(get-buffer ,buf-maybe))
(with-current-buffer (get-buffer ,buf-maybe)
,@body)))
(defmacro sage-shell:if-process-alive (then-form &optional else-form)
(declare (indent 0))
`(if (and sage-shell:process-buffer
(get-buffer-process sage-shell:process-buffer))
,then-form
,else-form))
(defmacro sage-shell:when-process-alive (&rest body)
(declare (indent 0))
`(sage-shell:if-process-alive
(progn
,@body)))
(defsubst sage-shell:goto-line (n)
(goto-char (point-min))
(forward-line (1- n)))
(defun sage-shell:trim-right (s)
(if (string-match (rx (1+ (or whitespace "\n")) buffer-end) s)
(replace-match "" t t s)
s))
(defun sage-shell:trim-left (s)
(if (string-match (rx buffer-start (1+ (or whitespace "\n"))) s)
(replace-match "" t t s)
s))
(defmacro sage-shell:labels (bindings &rest body)
(declare (indent 1) (debug cl-flet))
(let ((labels-sym (if (string< emacs-version "24.3")
'labels
'cl-labels)))
`(,labels-sym ,bindings
,@body)))
(defmacro sage-shell:->> (x form &rest forms)
(if (not forms)
(if (sequencep form)
(append form (list x))
(list form x))
`(sage-shell:->> (sage-shell:->> ,x ,form) ,@forms)))
(defmacro sage-shell:with-default-directory (directory &rest body)
(declare (indent 1) (debug t))
`(let ((default-directory (or (and ,directory
(file-name-as-directory ,directory))
default-directory)))
,@body))
(defvar sage-shell:sage-modes '(sage-shell:sage-mode sage-shell-mode))
(defmacro sage-shell:push-elmts (state &rest attributes-values)
"Push elements and returns new STATE."
(declare (indent 1))
`(setq ,state
(append ,(cons 'list
(cl-loop for (a b) in
(sage-shell:group attributes-values)
collect (list 'cons a b)))
,state)))
(defmacro sage-shell:chain (var &rest forms)
(declare (indent 1))
(append '(progn)
(cl-loop for f in forms
collect
`(setq ,var ,f))))
(defmacro sage-shell:with-selected-window-if-possible (win &rest forms)
(declare (indent 1))
`(save-selected-window
(when (and (windowp ,win)
(window-live-p ,win))
(select-window win))
,@forms))
;; cl-every raise warnings in Emacs 24.1 and 24.2
(defsubst sage-shell-every (f l)
(cl-loop for x in l always (funcall f x)))
(defmacro sage-shell-when-emacs25-or-later (&rest body)
(declare (indent 0))
(unless (version< emacs-version "25.1")
`(progn ,@body)))
;; Copied from pdf-tools
(cl-deftype sage-shell-list-of (type)
`(satisfies
(lambda (l)
(and (listp l)
(sage-shell-every
(lambda (x)
;; Calling cl-typep raises warning in Emacs 24.
(with-no-warnings
(cl-typep x ',type)))
l)))))
(cl-deftype sage-shell-alist-of (key-type val-type)
`(satisfies
(lambda (l)
(and (listp l)
(sage-shell-every
(lambda (x)
(with-no-warnings
(and (cl-typep (car x) ',key-type)
(cl-typep (cdr x) ',val-type))))
l)))))
;;; sage-shell
(defvar sage-shell-interfaces:other-interfaces
'("axiom"
"gap"
"gap3"
"giac"
"gp"
"mathematica"
"gnuplot"
"kash"
"magma"
"maple"
"maxima"
"matlab"
"mathematica"
"mwrank"
"octave"
"pari"
"r"
"singular"))
(defvar sage-shell:exec-path-error-msg
(concat "Please set `sage-shell:sage-root' or"
" `sage-shell:sage-executable' correctly."))
(defvar sage-shell:sage-root--cached nil)
(defun sage-shell:sage-root ()
(or (sage-shell:aif sage-shell:sage-root
(file-name-as-directory (expand-file-name it)))
sage-shell:sage-root--cached
(setq sage-shell:sage-root--cached
(sage-shell:aif (and (sage-shell:sage-executable)
(executable-find (sage-shell:sage-executable)))
(sage-shell:->> it
file-truename
file-name-directory)))))
(defun sage-shell:sage-executable ()
(or sage-shell:sage-executable
(if (stringp sage-shell:sage-root)
(expand-file-name "sage" sage-shell:sage-root)
(sage-shell:aif (executable-find "sage")
(file-truename it)))))
(defvar sage-shell:output-finished-regexp-rx
`(or (and (1+ (and (or "sage:" "sage0:" ">>>" "....:"
"(Pdb)" "ipdb>" "(gdb)") (1+ " ")))
line-end)
(and (or ,@sage-shell-interfaces:other-interfaces)
": " line-end)))
(defvar sage-shell:output-finished-regexp
(rx-to-string
`(and line-start ,sage-shell:output-finished-regexp-rx)))
(defvar sage-shell:process-buffer nil)
(make-variable-buffer-local 'sage-shell:process-buffer)
(defvar sage-shell:prompt-regexp
(rx line-start
(1+ (and (or "sage:" "sage0:" ">>>" "....:"
"(Pdb)" "ipdb>" "(gdb)") " ")))
"Regular expression matching the Sage prompt.")
(defvar sage-shell:-prompt-regexp-no-eol-rx
`(and (or
(1+ (and (or "sage:" "sage0:" ">>>" "....:"
"(Pdb)" "ipdb>" "(gdb)") " "))
(and (or ,@sage-shell-interfaces:other-interfaces)
": "))))
(defvar sage-shell:-prompt-regexp-no-eol
(rx-to-string
`(and line-start ,sage-shell:-prompt-regexp-no-eol-rx)))
;; cache buffers
(defvar sage-shell-indent:indenting-buffer-name " *sage-indent*")
(defvar sage-shell:output--buffer nil "The output buffer associated
to a process buffer.")
(make-variable-buffer-local 'sage-shell:output--buffer)
(defvar sage-shell:output-filter-finished-hook nil
"Run after output finished.")
(make-variable-buffer-local 'sage-shell:output-filter-finished-hook)
(defvar sage-shell:redirect-filter-finished-hook nil
"Run after redirect finished.")
(make-variable-buffer-local 'sage-shell:redirect-filter-finished-hook)
;;; Menu
(defvar sage-shell:in-out-menu-spec
'("In/Out"
["Expand History Before Point" comint-replace-by-expanded-history t]
["List Input History" comint-dynamic-list-input-ring t]
["Previous Input" comint-previous-input t]
["Next Input" sage-shell:next-input t]
["Previous Matching Current Input"
comint-previous-matching-input-from-input t]
["Next Matching Current Input" comint-next-matching-input-from-input t]
["Previous Matching Input..." comint-previous-matching-input t]
["Next Matching Input..." comint-next-matching-input t]
["Backward Matching Input..." comint-backward-matching-input t]
["Forward Matching Input..." comint-forward-matching-input t]
["Isearch Input String Backward..." comint-history-isearch-backward t]
["Isearch Input Regexp Backward..."
comint-history-isearch-backward-regexp t]
["Copy Old Input" comint-copy-old-input t]
["Kill Current Input" comint-kill-input t]
["Show Current Output Group" comint-show-output t]
["Show Maximum Output" comint-show-maximum-output t]
["Backward Output Group" comint-previous-prompt t]
["Forward Output Group" comint-next-prompt t]
["Write Current Output Group to File" comint-write-output t]
["Append Current Output Group to File" comint-append-output-to-file t]
["Delete Current Output Group" comint-delete-output t]))
(defvar sage-shell:singal-menu-spec
'("Signals"
["EOF" sage-shell:send-eof t]
["KILL" comint-kill-subjob t]
["QUIT" comint-quit-subjob t]
["CONT" comint-continue-subjob t]
["STOP" comint-stop-subjob t]
["BREAK" comint-interrupt-subjob t]))
(defvar sage-shell:menu-spec
`("Sage"
,sage-shell:in-out-menu-spec
,sage-shell:singal-menu-spec
"----"
["Toggle inline typesetting" sage-shell-view-toggle-inline-output]
["Toggle inline plots" sage-shell-view-toggle-inline-plots]))
(defvar sage-shell:output-finished-p nil)
(make-variable-buffer-local 'sage-shell:output-finished-p)
(cl-defun sage-shell:output-finished-p
(&optional (buffer sage-shell:process-buffer))
(buffer-local-value 'sage-shell:output-finished-p buffer))
(defun sage-shell:output-buffer ()
"The output buffer associated to the process buffer"
(sage-shell:with-current-buffer-safe sage-shell:process-buffer
(cond ((and (bufferp sage-shell:output--buffer)
(buffer-live-p sage-shell:output--buffer))
sage-shell:output--buffer)
(t (setq sage-shell:output--buffer
(get-buffer-create (format " *sage-output-%s*" (buffer-name))))))))
;;; Borrowed from Gallina's python.el.
(defvar sage-shell-mode-syntax-table
(let ((table (make-syntax-table)))
;; Give punctuation syntax to ASCII that normally has symbol
;; syntax or has word syntax and isn't a letter.
(let ((symbol (string-to-syntax "_"))
(sst (standard-syntax-table)))
(dotimes (i 128)
(unless (= i ?_)
(if (equal symbol (aref sst i))
(modify-syntax-entry i "." table)))))
(modify-syntax-entry ?$ "." table)
(modify-syntax-entry ?% "." table)
;; exceptions
(modify-syntax-entry ?# "<" table)
(modify-syntax-entry ?\n ">" table)
(modify-syntax-entry ?' "\"" table)
(modify-syntax-entry ?` "$" table)
table))
(defvar sage-shell:delete-temp-dir-p t)
(define-derived-mode sage-shell-mode comint-mode
"Sage-repl" "Execute Sage commands interactively."
(set-syntax-table sage-shell-mode-syntax-table)
(set (make-local-variable 'completion-ignore-case)
sage-shell:completion-ignore-case)
(setq font-lock-defaults '(sage-shell:font-lock-keywords
nil nil nil beginning-of-line))
(setq sage-shell:process-buffer (current-buffer))
(setq comint-prompt-regexp
(concat "^"
(regexp-opt
(append (mapcar (lambda (x) (concat x ":"))
sage-shell-interfaces:other-interfaces)
'("sage:" "sage0:" ">>>" "....:"
"(Pdb)" "ipdb>" "(gdb)"))))
comint-prompt-read-only t
comint-input-ring-file-name sage-shell:input-history-cache-file)
(set (make-local-variable 'comint-redirect-finished-regexp)
comint-prompt-regexp)
(comint-read-input-ring t)
(set (make-local-variable 'comint-redirect-completed) t)
(set (make-local-variable 'parse-sexp-lookup-properties) t)
(set (make-local-variable 'font-lock-syntactic-face-function)
(lambda (state)
(cond ((nth 3 state) font-lock-string-face)
((get-text-property (point) 'field) 'default)
((save-excursion
(beginning-of-line)
(re-search-forward "#" (line-end-position) t))
font-lock-comment-face)
(t 'default))))
(set (make-local-variable 'comint-use-prompt-regexp) t)
(set (make-local-variable 'comment-start) "# ")
(set (make-local-variable 'comment-start-skip) "^[ \t]*#+ *")
(set (make-local-variable 'comint-output-filter-functions)
(remove 'comint-postoutput-scroll-to-bottom
comint-output-filter-functions))
(set (make-local-variable 'eldoc-documentation-function)
#'sage-shell:eldoc-function)
(set (make-local-variable 'yank-excluded-properties)
(cons 'syntax-table yank-excluded-properties))
(when sage-shell:scroll-show-maximum-output
(set (make-local-variable 'scroll-conservatively) 1000))
;; Ignore duplicates in command history
(setq comint-input-ignoredups t)
(add-hook 'completion-at-point-functions
'sage-shell:completion-at-point-func nil t)
;; Run init functions after Sage loaded.
(add-to-list 'sage-shell:output-filter-finished-hook
(lambda () (sage-shell:after-init-function
sage-shell:process-buffer)))
(sage-shell:pcomplete-setup)
;; ansi-color-process-output may cause an error.
(remove-hook 'comint-output-filter-functions
'ansi-color-process-output t)
(add-hook 'sage-shell:process-exit-hook
#'sage-shell:-after-send-eof-func nil t)
(add-hook 'kill-buffer-hook
#'sage-shell:-kill-buffer-func nil t)
(when sage-shell:delete-temp-dir-p
(add-hook 'sage-shell:process-exit-hook
#'sage-shell-edit:delete-temp-dir)))
(easy-menu-define sage-shell-menu
sage-shell-mode-map "sage-shell menu"
sage-shell:menu-spec)
(defvar sage-shell-mode-hook nil "Hook run when entering Sage Shell mode.")
(defun sage-shell:interrupt-subjob ()
"Interrupt the current subjob."
(interactive)
(unless comint-redirect-completed
(sage-shell:redirect-cleanup)
(setq comint-redirect-completed t))
(sage-shell:prepare-for-send)
(if sage-shell:use-prompt-toolkit
(progn
(let* ((bol (line-beginning-position))
(eol (line-end-position))
(line (buffer-substring-no-properties bol eol))
(proc (get-buffer-process (current-buffer))))
(add-hook 'sage-shell:-pre-output-filter-hook
(lambda () (let ((inhibit-redisplay t))
(delete-region bol eol))))
(process-send-string proc (concat line ""))
;; Delete whitespaces
(add-hook 'sage-shell:-post-output-filter-hook
(lambda ()
(delete-region (point) (point-max))))))
(comint-interrupt-subjob)))
(sage-shell:define-keys sage-shell-mode-map
"TAB" 'sage-shell-tab-command
"C-d" 'sage-shell:delchar-or-maybe-eof
"RET" 'sage-shell:send-input
"C-c C-i" 'sage-shell:complete
"C-c C-h" 'sage-shell:help
"C-c C-l" 'sage-shell:load-file
"C-c M-o" 'sage-shell:clear-current-buffer
"C-c o" 'sage-shell:list-outputs
"C-c M-w" 'sage-shell:copy-previous-output-to-kill-ring)
(define-key sage-shell-mode-map [remap comint-next-input]
'sage-shell:next-input)
(define-key sage-shell-mode-map [remap comint-delete-output]
'sage-shell:delete-output)
(define-key sage-shell-mode-map [remap comint-interrupt-subjob]
'sage-shell:interrupt-subjob)
(defun sage-shell:delchar-or-maybe-eof (arg)
"Delete ARG characters forward or send an EOF to Sage process.
Sends an EOF only if point is at the end of the buffer and there is no input. "
(interactive "p")
(let ((proc (get-buffer-process (current-buffer))))
(if (and proc (eobp) (= (point) (marker-position (process-mark proc)))
(sage-shell:redirect-finished-p))
(sage-shell:send-eof)
(delete-char arg))))
(defun sage-shell:send-eof ()
"Send an EOF to the current buffer's process."
(interactive)
(sage-shell:comint-send-input t t)
(process-send-eof))
(defun sage-shell:-after-send-eof-func ()
;; kill cache buffes
(cl-loop for bufn in (list (sage-shell:output-buffer)
sage-shell-indent:indenting-buffer-name)
if (get-buffer bufn)
do (kill-buffer bufn))
;; write comint-input-ring
(comint-write-input-ring))
(defun sage-shell:ido-input-history ()
(interactive)
(insert (ido-completing-read "Input history: "
(ring-elements comint-input-ring))))
;; comint.el uses comint-input-ring-index for the input history, but
;; comint-send-input sets it to nil. So we need another global variable.
(defvar sage-shell:input-ring-index nil)
(make-variable-buffer-local 'sage-shell:input-ring-index)
(defun sage-shell:next-input (arg)
"Cycles through forward input history. This command enables inserting
successive lines in history."
(interactive "*p")
(cond
(comint-input-ring-index (comint-next-input arg))
((not sage-shell:input-ring-index))
(t (comint-previous-input (+ (- arg) 2 sage-shell:input-ring-index))
(setq comint-input-ring-index
(+ (- arg) 1 sage-shell:input-ring-index)))))
(defun sage-shell:-make-buf-if-needed (buf-maybe)
(cond ((or (stringp buf-maybe) (bufferp buf-maybe))
(get-buffer-create buf-maybe))
(t (sage-shell:output-buffer))))
(defun sage-shell:send-command-sync
(command &optional process-buffer output-buffer to-string raw)
"internal function"
(sage-shell:run-cell-raw-output
command :sync t
:process-buffer process-buffer
:output-buffer output-buffer
:to-string to-string
:raw raw))
(defun sage-shell:wait-for-redirection-to-complete
(&optional msec process-buffer)
(let ((msec (or msec 1))
(proc-buf (or process-buffer sage-shell:process-buffer)))
(sage-shell:awhen (get-buffer proc-buf)
(with-current-buffer it
(while (null comint-redirect-completed)
(accept-process-output nil 0 msec))))))
(cl-defstruct sage-shell:output-stct
output success)
(defun sage-shell:eval-state (raw-output)
"Parse output of run_cell_and_print_state."
(let* ((success-str (substring-no-properties raw-output -2 -1))
(output (substring-no-properties raw-output 0 -2))
(success (cond ((string= success-str "0")
t)
((string= success-str "1")
nil)
(t (error "Invalid output.")))))
(make-sage-shell:output-stct
:success success
:output output)))
(defun sage-shell--error-callback (res)
(unless (sage-shell:output-stct-success res)
(error (sage-shell:output-stct-output res))))
(cl-defun sage-shell:run-cell (cell &key callback
output-buffer
process-buffer
sync)
(cl-check-type callback (or null function))
(cl-check-type process-buffer (or null string buffer))
(cl-check-type output-buffer (or null string buffer))
(cl-check-type cell string)
(let ((evaluator (sage-shell:py-mod-func "run_cell_and_print_state"))
(callback (when (functionp callback)
(lambda (output)
(funcall callback (sage-shell:eval-state output))))))
(sage-shell:run-cell-raw-output cell
:output-buffer output-buffer
:process-buffer process-buffer
:sync sync
:evaluator evaluator
:callback callback)))
(defmacro sage-shell:after-redirect-finished (&rest body)
(declare (indent 0))
`(cond ((sage-shell:redirect-finished-p)
(with-current-buffer sage-shell:process-buffer
(progn ,@body)))
(t (with-current-buffer sage-shell:process-buffer
(add-to-list 'sage-shell:redirect-filter-finished-hook
(lambda () ,@body))))))
(defmacro sage-shell:push-to-redirect-finished-hook (&rest body)
(declare (indent 0))
`(with-current-buffer sage-shell:process-buffer
(push (lambda () ,@body)
sage-shell:redirect-filter-finished-hook)))
(cl-defun sage-shell:run-cell-raw-output (cell &key callback
process-buffer
output-buffer
sync
raw
evaluator
evaluator-key-args
to-string)
"CELL is a string which will be sent to the process buffer,
When non-nil, CALLBACK should be a function and will be called if the
evaluation completes. The output will be passed as its argument.
If RAW is non-nil, CELL will be sent by process-send-string directly.
Otherwise return value of `sage-shell:-make-exec-cmd' is used.
If EVALUATOR is non-nil, it should be a Python function
which is similar to emacs_sage_shell.run_cell_and_print_msg_id."
(cl-check-type cell string)
(cl-check-type callback (or null function))
(cl-check-type process-buffer (or null string buffer))
(cl-check-type output-buffer (or null string buffer))
(cl-check-type evaluator (or null string))
(sage-shell-when-emacs25-or-later
(cl-check-type evaluator-key-args (sage-shell-alist-of string string)))
(unless (and (bufferp sage-shell:process-buffer)
(buffer-live-p sage-shell:process-buffer)
(get-buffer-process sage-shell:process-buffer))
(setq sage-shell:process-buffer (get-buffer process-buffer)))
(let ((proc-buf sage-shell:process-buffer)
(out-buf (sage-shell:-make-buf-if-needed output-buffer))
;; If to-string is non-nil sync should be non-nil
(sync (if to-string t sync)))
(with-current-buffer proc-buf
(sage-shell:wait-for-redirection-to-complete))
(with-current-buffer out-buf
(erase-buffer))
(when (functionp callback)
(sage-shell:push-to-redirect-finished-hook
(let ((raw-output
(sage-shell:-redirect-get-buffer-string out-buf)))
(funcall callback raw-output))))