-
Notifications
You must be signed in to change notification settings - Fork 1
/
matlab-shell.el
2508 lines (2189 loc) · 101 KB
/
matlab-shell.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
;;; matlab-shell.el --- Run MATLAB in an inferior process -*- lexical-binding: t -*-
;;
;; Copyright 2019-2024 Eric Ludlam
;;
;; Author: Eric Ludlam <[email protected]>
;;
;; 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 https://www.gnu.org/licenses/.
;;; Commentary:
;;
;; This library supports a MATLAB shell buffer, which runs MATLAB in
;; an inferior shell. Supports working with the MATLAB command line,
;; and the MATLAB debugger.
;;
;;; Code:
(require 'matlab)
(require 'matlab-compat)
(require 'comint)
(require 'server)
(eval-and-compile
(require 'mlgud)
(require 'shell))
;; Silence warnings from company.el
(declare-function company-mode "company")
(defvar company-idle-delay)
(defvar company-mode)
;; Key entry points for matlab-shell-gud
(declare-function matlab-shell-mode-gud-enable-bindings "matlab-shell-gud")
(declare-function matlab-shell-gud-startup "matlab-shell-gud")
;;; Customizations
;;
;; Options to configure using matlab-shell
(defgroup matlab-shell nil
"MATLAB shell mode."
:prefix "matlab-shell-"
:group 'matlab)
;;
;; Shell Startup
(defcustom matlab-shell-mode-hook nil
"*List of functions to call on entry to MATLAB shell mode."
:group 'matlab-shell
:type 'hook)
(defcustom matlab-shell-command "matlab"
"*The name of the command to be run which will start the MATLAB process."
:group 'matlab-shell
:type 'string)
(defcustom matlab-shell-command-switches '("-nodesktop")
"*Command line parameters run with `matlab-shell-command'.
Command switches are a list of strings. Each entry is one switch."
:group 'matlab-shell
:type '(list :tag "Switch: "))
(defface matlab-shell-error-face
(list
(list t
(list :background 'unspecified
:foreground "red1"
:bold t)))
"*Face to use when errors occur in MATLAB shell."
:group 'matlab-shell)
(defcustom matlab-custom-startup-command nil
"Custom MATLAB command to be run at startup."
:group 'matlab-shell
:type 'string)
(defcustom matlab-shell-echoes t
"*If `matlab-shell-command' echoes input."
:group 'matlab-shell
:type 'boolean)
(defcustom matlab-shell-history-file "~/.matlab/%s/history.m"
"*Location of the history file.
A %s is replaced with the MATLAB version release number, such as R12.
This file is read to initialize the comint input ring."
:group 'matlab-shell
:type 'filename)
(defcustom matlab-shell-history-ignore "^%\\|%%$\\|emacs.set"
"Regular expression matching items from history to ignore.
This expression should ignore comments (between sessions) and any command
that ends in 2 or more %%, added to automatic commands."
:group 'matlab-shell
:type 'filename)
(defcustom matlab-shell-autostart-netshell nil
"Use the netshell side-channel for communicating with MATLAB."
:group 'matlab-shell
:type 'boolean)
;;
;; Edit from MATLAB
(defcustom matlab-shell-emacsclient-command
(matlab-find-emacsclient)
"*The command to use as an external editor for MATLAB.
Using emacsclient allows the currently running Emacs to also be the
external editor for MATLAB. Setting this to the empty string
will disable use emacsclient as the external editor."
:group 'matlab-shell
:type 'integer)
;;
;; Run from Emacs
(defcustom matlab-shell-run-region-function 'auto
"Technique to use for running a line, region, or code-section.
There are different benefits to different kinds of commands.
Use `auto to guess which to use by looking at the environment.
auto - guess which to use
`matlab-shell-region->commandline'
- Extract region, and generate 1 line of ML code.
`matlab-shell-region->script'
- Extract region and any local fcns, and write to
tmp script. Call that from MATLAB.
`matlab-shell-region->internal'
- Send region location to MATLAB, and have ML
extract and run that region. Customize
`matlab-shell-emacsrunregion' to specify what ML
function to use for this."
:group 'matlab-shell
:type '(choice (const :tag "Auto" auto)
(const :tag "Extract Line" matlab-shell-region->commandline)
(const :tag "Extract Script" matlab-shell-region->script)
(const :tag "Matlab Extract" matlab-shell-region->internal)))
(defcustom matlab-shell-internal-emacsrunregion "emacsrunregion"
"The MATLAB command to use for running a region.
This command is used when `matlab-shell-run-region-function' is set
to auto, or `matlab-shell-region->internal'"
:group 'matlab-shell
:type 'string)
;;
;; Features in an active shell
(defcustom matlab-shell-input-ring-size 32
"*Number of history elements to keep."
:group 'matlab-shell
:type 'integer)
;;
;; Completion handling
(defcustom matlab-shell-ask-MATLAB-for-completions t
"When Non-nil, ask MATLAB for a completion list.
When nil, complete against file names."
:group 'matlab-shell
:type 'boolean)
(defcustom matlab-shell-tab-use-company t
"*Use `company' (complete anything) for TAB completions in `matlab-shell'.
Only effective when when `company' is installed. Note, when you type to
narrow completions, you may find the responses slow and if so,
you can try turning this off."
:group 'matlab-shell
:type 'boolean)
(defvar matlab-shell-tab-company-available (if (locate-library "company") t nil)
"Non-nil if we have `company' installed.
Use this to override initial check.")
(defvar matlab-shell-errorscanning-syntax-table
(let ((st (copy-syntax-table matlab-mode-syntax-table)))
;; Make \n be whitespace when scanning output.
(modify-syntax-entry ?\n " " st)
st)
"Syntax table used when scanning MATLAB output.
In this case, comment and \n are not special, as word wrap can get in the way.")
(defvar matlab-shell-prompt-appears-hook nil
"Hooks run each time a prompt is seen and sent to display.
If multiple prompts are seen together, only call this once.")
(defvar matlab-shell-prompt-hook-cookie nil
"Cookie used to transfer info about detected prompts from inner filter to outer.")
(make-variable-buffer-local 'matlab-shell-prompt-hook-cookie)
(defvar matlab-shell-suppress-prompt-hooks nil
"Non-nil to suppress running prompt hooks.")
(defvar matlab-shell-cco-testing nil
"Non nil when testing `matlab-shell'.")
(defvar matlab-shell-io-testing nil
"Non-nil to display process output and input log.")
;;; Font Lock
;;
;; Extra font lock keywords for the MATLAB shell.
(defconst matlab-shell-font-lock-keywords
(list
;; How about Errors?
'("^\\(Error in\\|Syntax error in\\)\\s-+==>\\s-+\\(.+\\)$"
(1 font-lock-comment-face) (2 font-lock-string-face))
;; and line numbers
'("^\\(\\(On \\)?line [0-9]+\\)" 1 font-lock-comment-face)
;; User beep things
'("\\(\\?\\?\\?[^\n]+\\)" 1 font-lock-comment-face)
)
"Additional keywords used by MATLAB when reporting errors in interactive\
mode.")
(defconst matlab-shell-font-lock-keywords-1
(append matlab-basic-font-lock-keywords
matlab-shell-font-lock-keywords)
"Keyword symbol used for basic font-lock for MATLAB shell.")
(defconst matlab-shell-object-output-font-lock-keywords
(list
;; Startup notices
'(" M A T L A B " 0 'underline)
'("All Rights Reserved" 0 'italic)
'("\\(\\(?:(c)\\)?\\s-+Copyright[^\n]+\\)" 1 font-lock-comment-face)
'("\\(Version\\)\\s-+\\([^\n]+\\)"
(1 font-lock-function-name-face) (2 font-lock-variable-name-face))
'("\\(R[0-9]+[ab]\\(?: Update [0-9]+\\)\\) \\([^\n]+\\)"
(1 font-lock-function-name-face) (2 font-lock-variable-name-face))
'("^To get started, type doc.$" 0 font-lock-comment-face prepend)
'("For product information, [^\n]+" 0 font-lock-comment-face)
;; Useful user commands, but not useful programming constructs
'("\\<\\(demo\\|whatsnew\\|info\\|subscribe\\|help\\|doc\\|lookfor\\|what\
\\|whos?\\|cd\\|clear\\|load\\|save\\|helpdesk\\|helpwin\\)\\>"
1 font-lock-keyword-face)
;; disp of objects usually looks like this:
'("^\\s-*\\(\\w+\\) with properties:" (1 font-lock-type-face))
;; object output - highlight property names after 'with properties:' indicator
;; NOTE: Normally a block like this would require us to use `font-lock-multiline' feature
;; but since this is shell output, and not a thing you edit, we can skip it and rely
;; on matlab-shell dumping the text as a unit.
'("^\\s-*\\(\\w+ with properties:\\)\n\\s-*\n"
("^\\s-*\\(\\w+\\):[^\n]+$" ;; match the property before the :
;; Extend search region across lines.
(save-excursion (re-search-forward "\n\\s-*\n" nil t)
(beginning-of-line)
(point))
nil
(1 font-lock-variable-name-face)))
'("[[{]\\([0-9]+\\(?:x[0-9]+\\)+ \\w+\\)[]}]" (1 font-lock-comment-face))
)
"Highlight various extra outputs that are typical for MATLAB.")
(defconst matlab-shell-font-lock-keywords-2
(append matlab-shell-font-lock-keywords-1
matlab-function-font-lock-keywords
matlab-shell-object-output-font-lock-keywords)
"Keyword symbol used for gaudy font-lock for MATLAB shell.")
(defconst matlab-shell-font-lock-keywords-3
(append matlab-shell-font-lock-keywords-2
matlab-really-gaudy-font-lock-keywords)
"Keyword symbol used for really gaudy font-lock for MATLAB shell.")
;;; ROOT
;;
;;;###autoload
(defun matlab-mode-determine-matlabroot ()
"Return the MATLABROOT for the `matlab-shell-command'."
(let ((path (file-name-directory matlab-shell-command)))
;; if we don't have a path, find the MATLAB executable on our path.
(when (not path)
(setq path (matlab-find-executable-directory matlab-shell-command)))
(when path
;; When we find the path, we need to massage it to identify where
;; the M files are that we need for our completion lists.
(if (string-match "/bin/?$" path)
(setq path (substring path 0 (match-beginning 0)))))
path))
;;; Keymaps & Menus
;;
(defvar matlab-shell-mode-map
(let ((km (make-sparse-keymap 'matlab-shell-mode-map)))
;; Mostly use comint mode's map.
(set-keymap-parent km comint-mode-map)
;; We can jump to errors, so take over this keybinding.
(substitute-key-definition 'next-error 'matlab-shell-last-error
km global-map)
;; Interrupt
(define-key km [(control c) (control c)] 'matlab-shell-interrupt-subjob)
;; Help system
(define-key km [(control h) (control m)] matlab-help-map)
;; Completion
(define-key km (kbd "TAB") 'matlab-shell-tab)
(define-key km "\C-i" 'matlab-shell-tab)
(define-key km (kbd "<C-tab>") 'matlab-shell-c-tab)
;; Command history
(define-key km [(control up)] 'comint-previous-matching-input-from-input)
(define-key km [(control down)] 'comint-next-matching-input-from-input)
(define-key km [up] 'matlab-shell-previous-matching-input-from-input)
(define-key km [down] 'matlab-shell-next-matching-input-from-input)
;; Editing
(define-key km [(control return)] 'comint-kill-input)
(define-key km [(backspace)] 'matlab-shell-delete-backwards-no-prompt)
;; Files
(define-key km "\C-c." 'matlab-shell-locate-fcn)
;; matlab-shell actions
(define-key km "\C-c/" 'matlab-shell-sync-buffer-directory)
km)
"Keymap used in `matlab-shell-mode'.")
(easy-menu-define matlab-shell-menu
matlab-shell-mode-map
"MATLAB shell menu."
'("MATLAB"
["Goto last error" matlab-shell-last-error t]
"----"
["Stop On Errors" matlab-shell-dbstop-error t]
["Don't Stop On Errors" matlab-shell-dbclear-error t]
"----"
["Locate MATLAB function" matlab-shell-locate-fcn
:help "Run 'which FCN' in matlab-shell, then open the file in Emacs"]
["Run Command" matlab-shell-run-command t]
["Describe Variable" matlab-shell-describe-variable t]
["Describe Command" matlab-shell-describe-command t]
["Lookfor Command" matlab-shell-apropos t]
"----"
["Complete command" matlab-shell-tab t]
"----"
["Demos" matlab-shell-demos t]
["Close Current Figure" matlab-shell-close-current-figure t]
["Close Figures" matlab-shell-close-figures t]
"----"
["Sync buffer directory (emacscd)" matlab-shell-sync-buffer-directory
:help "Sync the matlab-shell buffer `default-directory' with MATLAB's pwd.\n\
These will differ when MATLAB code changes directory without notifying Emacs."]
["Customize" (customize-group 'matlab-shell)
(and (featurep 'custom) (fboundp 'custom-declare-variable))
]
["Exit" matlab-shell-exit t]))
;;; MODE
;;
;; The Emacs major mode for interacting with the matlab shell process.
(defvar matlab-shell-last-error-anchor) ;; Quiet compiler warning
(defun matlab-shell-mode ()
"Run MATLAB as a subprocess in an Emacs buffer.
This mode will allow standard Emacs shell commands/completion to occur
with MATLAB running as an inferior process. Additionally, this shell
mode is integrated with `matlab-mode', a major mode for editing M
code.
> From an M file buffer:
\\<matlab-mode-map>
\\[matlab-shell-save-and-go] - Save the current M file, and run it in a \
MATLAB shell.
> From Shell mode:
\\<matlab-shell-mode-map>
\\[matlab-shell-last-error] - find location of last MATLAB runtime error \
in the offending M file.
> From an M file, or from Shell mode:
\\<matlab-mode-map>
\\[matlab-shell-run-command] - Run COMMAND and show result in a popup buffer.
\\[matlab-shell-describe-variable] - Show variable contents in a popup buffer.
\\[matlab-shell-describe-command] - Show online documentation for a command \
in a popup buffer.
\\[matlab-shell-apropos] - Show output from LOOKFOR command in a popup buffer.
> Keymap:
\\{matlab-mode-map}"
(setq major-mode 'matlab-shell-mode
mode-name "M-Shell"
comint-prompt-regexp "^\\(K\\|EDU\\)?>> *"
comint-delimiter-argument-list (list [ 59 ]) ; semi colon
comint-dynamic-complete-functions '(comint-replace-by-expanded-history)
comint-process-echoes matlab-shell-echoes
comint-get-old-input #'matlab-comint-get-old-input
)
;; Shell Setup
(require 'shell)
;; COMINT History Setup
(set (make-local-variable 'comint-input-ring-size)
matlab-shell-input-ring-size)
(set (make-local-variable 'comint-input-ring-file-name)
(format matlab-shell-history-file "R12"))
(if (fboundp 'comint-read-input-ring)
(comint-read-input-ring t))
;;; MODE Settings
(make-local-variable 'comment-start)
(setq comment-start "%")
(use-local-map matlab-shell-mode-map)
(set-syntax-table matlab-mode-syntax-table)
(make-local-variable 'font-lock-defaults)
(setq font-lock-defaults '((matlab-shell-font-lock-keywords-1
matlab-shell-font-lock-keywords-2
matlab-shell-font-lock-keywords-3)
t nil ((?_ . "w"))))
;; GUD support
(matlab-shell-mode-gud-enable-bindings)
;; Company mode can be used to display completions for MATLAB in matlab-shell.
;; This block enables company mode for this shell, and turns off the idle timer
;; so users must press TAB to get the menu.
(when (and matlab-shell-tab-use-company
matlab-shell-tab-company-available)
;; Only do popup when users presses TAB
(set (make-local-variable 'company-idle-delay) nil)
(company-mode))
;; Hooks, etc
(run-hooks 'matlab-shell-mode-hook)
(matlab-show-version)
)
;;; NETSHELL integration
;;
(declare-function matlab-netshell-client "matlab-netshell")
(declare-function matlab-netshell-server-start "matlab-netshell")
(declare-function matlab-netshell-server-active-p "matlab-netshell")
(declare-function matlab-netshell-eval "matlab-netshell")
(defun matlab-netshell-active-p ()
"Return t if the MATLAB netshell is active."
(when (featurep 'matlab-netshell)
(matlab-netshell-client)))
(defun matlab-any-shell-active-p ()
"Return non-nil of any of the matlab connections are active."
(or (matlab-netshell-active-p) (matlab-shell-active-p)))
;;; MATLAB SHELL
;;
;; Core shell state handling & startup function.
(defvar matlab-shell-buffer-name "MATLAB"
"Name used to create `matlab-shell' mode buffers.
This name will have *'s surrounding it.")
(defvar matlab-prompt-seen nil
"Track visibility of MATLAB prompt in MATLAB Shell.")
(defun matlab-shell-active-p ()
"Return the MATLAB shell buffer if it active, else nil."
(let ((msbn (get-buffer (concat "*" matlab-shell-buffer-name "*"))))
(if msbn
(with-current-buffer msbn
(if (comint-check-proc (current-buffer))
(current-buffer))))))
;;;###autoload
(defun matlab-shell ()
"Create a buffer with MATLAB running as a subprocess.
MATLAB shell cannot work on the MS Windows platform because MATLAB is not
a console application."
(interactive)
;; MATLAB shell does not work by default on the Windows platform. Only
;; permit it's operation when the shell command string is different from
;; the default value. (True when the engine program is running.)
(when (and (or (eq window-system 'pc) (eq window-system 'w32))
(string= matlab-shell-command "matlab"))
(error "MATLAB cannot be run as a inferior process. \
Try C-h f matlab-shell RET"))
(require 'shell)
(require 'matlab-shell-gud)
;; Make sure netshell is started if it is wanted.
(when (and matlab-shell-autostart-netshell
(not (matlab-netshell-server-active-p)))
(matlab-netshell-server-start))
;; Show the shell buffer
(switch-to-buffer (concat "*" matlab-shell-buffer-name "*"))
;; If the shell isn't active yet, start it.
(when (not (matlab-shell-active-p))
;; Clean up crufty state
(kill-all-local-variables)
;; Thx David Chappaz for reminding me about this patch.
(let* ((windowid (frame-parameter (selected-frame) 'outer-window-id))
(newvar (concat "WINDOWID=" windowid))
(process-environment (cons newvar process-environment)))
(apply #'make-comint matlab-shell-buffer-name matlab-shell-command
nil matlab-shell-command-switches))
;; Enable GUD
(matlab-shell-gud-startup)
;; Init our filter and sentinel
(set-process-filter (get-buffer-process (current-buffer))
'matlab-shell-wrapper-filter)
(set-process-sentinel (get-buffer-process (current-buffer))
'matlab-shell-wrapper-sentinel)
;; XEmacs has problems w/ this variable. Set it here.
(set-marker comint-last-output-start (point-max))
(make-local-variable 'matlab-prompt-seen)
(setq matlab-prompt-seen nil)
;; FILTERS
;;
;; Add hook for finding the very first prompt - so we know when the buffer is ready to use.
(add-hook 'matlab-shell-prompt-appears-hook #'matlab-shell-first-prompt-fcn)
;; Track current directories when user types cd
(add-hook 'comint-input-filter-functions 'shell-directory-tracker nil t) ;; patch Eli Merriam
;; Add a version scraping logo identification filter.
(add-hook 'comint-output-filter-functions 'matlab-shell-version-scrape nil t)
;; Add pseudo html-renderer
(add-hook 'comint-output-filter-functions 'matlab-shell-render-html-anchor nil t)
;; Scroll to bottom after running code-section/region
(add-hook 'comint-output-filter-functions 'comint-postoutput-scroll-to-bottom nil t)
;; Add error renderer to prompt hook so the prompt is available for resolving names.
(make-local-variable 'matlab-shell-last-error-anchor)
(setq matlab-shell-last-error-anchor nil)
(add-hook 'matlab-shell-prompt-appears-hook 'matlab-shell-render-errors-as-anchor nil t)
(add-hook 'matlab-shell-prompt-appears-hook 'matlab-shell-colorize-errors nil t)
;; Comint and GUD both try to set the mode. Now reset it to
;; matlab mode.
(matlab-shell-mode))
)
;;; PROCESS FILTERS & SENTINEL
;;
;; These are wrappers around the GUD filters so we can pre and post process
;; decisions by comint and mlgud.
(defvar matlab-shell-capturetext-start-text "<EMACSCAP>"
"Text used as simple signal for text that should be captured.")
(defvar matlab-shell-capturetext-end-text "</EMACSCAP>"
"Text used as simple signal for text that should be captured.")
(defvar matlab-shell-accumulator ""
"Accumulate text that is being captured.")
(make-variable-buffer-local 'matlab-shell-accumulator)
(defvar matlab-shell-flush-accumulation-buffer nil
"When non-nil, flush the accumulation buffer.")
(defvar matlab-shell-in-process-filter nil
"Non-nil when inside `matlab-shell-wrapper-filter'.")
(defun matlab-shell-wrapper-filter (proc string)
"MATLAB Shell's process filter. This wraps the GUD and COMINT filters.
PROC is the process with input to this filter.
STRING is the recent output from PROC to be filtered."
;; A few words about process sentinel's in the MATLAB shell buffer:
;; Our filter calls the GUD filter.
;; The GUD filter calls the COMINT filter.
;; The COMINT filter writes output to the buffer and runs filters.
;; We need to run our error anchor commands AFTER all of the above is done,
;; but ONLY when we have an empty prompt and can ask MATLAB more questions.
;; We need this filter to provide a hook on prompt display when everything
;; has been processed.
(let ((buff (process-buffer proc))
(captext nil)
(matlab-shell-in-process-filter t))
;; Cleanup garbage before sending it along to the other filters.
(let ((garbage (concat "\\(" (regexp-quote "\C-g") "\\|"
(regexp-quote "\033[H0") "\\|"
(regexp-quote "\033[H\033[2J") "\\|"
(regexp-quote "\033H\033[2J") "\\)")))
(while (string-match garbage string)
;;(if (= (aref string (match-beginning 0)) ?\C-g)
;;(beep t))
(setq string (replace-match "" t t string))))
;; Engage the accumulator
(setq matlab-shell-accumulator (concat matlab-shell-accumulator string)
string "")
;; STARTCAP - push preceeding text to output.
(if (and (not matlab-shell-flush-accumulation-buffer)
(string-match (regexp-quote matlab-shell-capturetext-start-text) matlab-shell-accumulator))
(progn
(setq string (substring matlab-shell-accumulator 0 (match-beginning 0))
matlab-shell-accumulator (substring matlab-shell-accumulator
(match-beginning 0)))
;; START and ENDCAP - save captured text, and push trailing text to output
(when (string-match (concat (regexp-quote matlab-shell-capturetext-end-text)
"\\(:?\n\\)?")
matlab-shell-accumulator)
;; If no end, then send anything before the CAP, and accumulate everything
;; else.
(setq string (concat string (substring matlab-shell-accumulator (match-end 0)))
captext (substring matlab-shell-accumulator
0 (match-end 0))
matlab-shell-accumulator "")))
;; No start capture, or an ended capture, everything goes back to String
(setq string (concat string matlab-shell-accumulator)
matlab-shell-accumulator ""
matlab-shell-flush-accumulation-buffer nil))
(with-current-buffer buff
(mlgud-filter proc string))
;; In case things get switched around on us
(with-current-buffer buff
(when matlab-shell-prompt-hook-cookie
(setq matlab-shell-prompt-hook-cookie nil)
(run-hooks 'matlab-shell-prompt-appears-hook))
)
;; If there was some captext, process it, but only after doing all the other important
;; stuff.
(when captext
(matlab-shell-process-capture-text captext))
))
(defun matlab-shell-wrapper-sentinel (proc string)
"MATLAB Shell's process sentinel. This wraps the GUD and COMINT filters.
PROC is the function which experienced a change in state.
STRING is a description of what happened."
(let ((buff (process-buffer proc)))
(with-current-buffer buff
(mlgud-sentinel proc string))))
;;; COMINT support fcns
;;
(defun matlab-comint-get-old-input ()
"Compute text from the current line to evaluate with MATLAB.
This function checks to make sure the line is on a prompt. If not,
it returns empty string"
(let ((inhibit-field-text-motion t))
(save-excursion
(beginning-of-line)
(save-match-data
(if (looking-at comint-prompt-regexp)
;; We'll send this line.
(buffer-substring-no-properties (match-end 0) (line-end-position))
;; Otherwise, it's probably junk that is useless. Don't do it.
"")))))
;;; STARTUP / VERSION
;;
;; Handlers for startup output / version scraping
;;
;; TODO - these scraped values aren't used anywhere. Do we care?
(defvar matlab-shell-running-matlab-version nil
"The version of MATLAB running in the current `matlab-shell' buffer.")
(defvar matlab-shell-running-matlab-release nil
"The release of MATLAB running in the current `matlab-shell' buffer.")
(defun matlab-shell-version-scrape (str)
"Scrape the MATLAB Version from the MATLAB startup text.
Argument STR is the string to examine for version information."
(if (string-match "\\(Version\\)\\s-+\\([.0-9]+\\)\\s-+(\\(R[.0-9]+[ab]?\\))" str)
;; OLDER MATLAB'S
(setq matlab-shell-running-matlab-version
(match-string 2 str)
matlab-shell-running-matlab-release
(match-string 3 str))
;; NEWER MATLAB'S
(if (string-match "\\(R[0-9]+[ab]\\)\\s-+\\(?:Update\\s-+[0-9]+\\s-+\\|Prerelease\\s-+\\)?(\\([0-9]+\\.[0-9]+\\)\\." str)
(setq matlab-shell-running-matlab-version
(match-string 2 str)
matlab-shell-running-matlab-release
(match-string 1 str))))
;; Notice that this worked.
(when matlab-shell-running-matlab-version
;; Remove the scrape from our list of things to do. We are done getting the version.
(remove-hook 'comint-output-filter-functions
'matlab-shell-version-scrape t)
(message "Detected MATLAB %s (%s) -- Loading history file" matlab-shell-running-matlab-release
matlab-shell-running-matlab-version)
;; Now get our history loaded
(setq comint-input-ring-file-name
(format matlab-shell-history-file matlab-shell-running-matlab-release)
comint-input-history-ignore matlab-shell-history-ignore)
(if (fboundp 'comint-read-input-ring)
(comint-read-input-ring t))
))
;;; ANCHORS
;;
;; Scan output for text, and turn into navigable links.
(defvar gud-matlab-marker-regexp-prefix "error:\\|opentoline\\|dbhot"
"A prefix to scan for to know if output might be scarfed later.")
(defvar matlab-shell-html-map
(let ((km (make-sparse-keymap)))
(if (string-match "XEmacs" emacs-version)
(define-key km [button2] 'matlab-shell-html-click)
(define-key km [mouse-2] 'matlab-shell-html-click)
(define-key km [mouse-1] 'matlab-shell-html-click))
(define-key km [return] 'matlab-shell-html-go)
km)
"Keymap used on overlays that represent errors.")
;; Anchor expressions.
(defvar matlab-anchor-beg "<a href=\"\\(\\(?:matlab:\\)?[^\"]+\\)\">"
"Beginning of html anchor.")
(defvar matlab-anchor-end "</a>"
"End of html anchor.")
(defun matlab-shell-render-html-anchor (str)
"Render html anchors inserted into the MATLAB shell buffer.
Argument STR is the text for the anchor."
(when (string-match matlab-anchor-end str)
(save-excursion
(with-syntax-table matlab-shell-errorscanning-syntax-table
(while (re-search-backward matlab-anchor-beg
;; Arbitrary back-buffer. We don't
;; usually get text in such huge chunks
(max (point-min) (- (point-max) 8192))
t)
(let* ((anchor-beg-start (match-beginning 0))
(anchor-beg-finish (match-end 0))
(anchor-text (match-string 1))
(anchor-end-finish (search-forward matlab-anchor-end))
(anchor-end-start (match-beginning 0))
(o (make-overlay anchor-beg-finish anchor-end-start)))
(overlay-put o 'mouse-face 'highlight)
(overlay-put o 'face 'underline)
(overlay-put o 'matlab-url anchor-text)
(overlay-put o 'keymap matlab-shell-html-map)
(overlay-put o 'help-echo anchor-text)
(delete-region anchor-end-start anchor-end-finish)
(delete-region anchor-beg-start anchor-beg-finish)
))))))
;;; ERROR HANDLING
;;
;; The regular expression covers to forms in tests/erroexamples.shell.m
;;
(defvar matlab-shell-error-anchor-expression
(concat "^>?\\s-*\\(\\(Error \\(in\\|using\\)\\s-+\\|Syntax error in \\)\\(?:==> \\)?\\|"
"In\\s-+\\(?:workspace belonging to\\s-+\\)?\\|Error:\\s-+File:\\s-+\\|Warning:\\s-+[^\n]+\n\\)")
"Expressions used to find errors in MATLAB process output.
This variable contains the anchor, or starting text before
a typical error. See `matlab-shell-error-location-expression' for
a list of expressions for identifying where the error is
after this anchor.")
(defvar matlab-shell-error-location-expression
(list
;; Pulled from R2019b
"\\(?:^> In\\s-+\\)?\\([-+>@.a-zA-Z_0-9/ \\\\:]+\\)\\s-+(line \\([0-9]+\\))"
"\\([-+>@.a-zA-Z_0-9/ \\\\:]+\\)\\s-+Line:\\s-+\\([0-9]+\\)\\s-+Column:\\s-+\\([0-9]+\\)"
;; Oldest I have examples for:
(concat "\\([-+>@.a-zA-Z_0-9/ \\\\:]+\\)\\(?:>[^ ]+\\)?.*[\n ]"
"\\(?:On\\|at\\)\\(?: line\\)? \\([0-9]+\\) ?")
)
"List of Expressions to search for after an error anchor is found.
These expressions are listed as matching from newer MATLAB versions
to older MATLAB's.
Each expression should have the following match strings:
1 - The matlab function
2 - The line number
3 - The column number (if available)")
;; (global-set-key [f7] 'matlab-shell-scan-for-error-test)
(defun matlab-shell-scan-for-error-test ()
"Interactively try out the error scanning feature."
(interactive)
(let ((ans (matlab-shell-scan-for-error (point-min))))
(when ans
(pulse-momentary-highlight-region (car ans) (car (cdr ans))))
(message "Found: %S" ans)))
(defun matlab-shell-scan-for-error (limit)
"Scan backward for a MATLAB error in the current buffer until LIMIT.
Uses `matlab-shell-error-anchor-expression' to find the error.
Uses `matlab-shell-error-location-expression' to find where the error is.
Returns a list of the form:
( STARTPT ENDPT FILE LINE COLUMN )"
(with-syntax-table matlab-shell-errorscanning-syntax-table
(let ((ans nil)
(beginning nil))
(when (re-search-backward matlab-shell-error-anchor-expression
limit
t)
(save-excursion
(setq beginning (save-excursion (goto-char (match-beginning 0))
(back-to-indentation)
(point)))
(goto-char (match-end 0))
(dolist (EXP matlab-shell-error-location-expression)
(when (looking-at EXP)
(setq ans (list beginning
(match-end 0)
(match-string-no-properties 1)
(match-string-no-properties 2)
(match-string-no-properties 3)
)))))
)
ans)))
(defvar matlab-shell-last-error-anchor nil
"Last point where an error anchor was set.")
(defvar matlab-shell-last-anchor-as-frame nil
;; NOTE: this isn't being used yet.
"The last error anchor saved, represented as a debugger frame.")
(defun matlab-shell-render-errors-as-anchor (&optional str)
"Hook function run when process filter sees a prompt.
Detect non-url errors, and treat them as if they were url anchors.
Input STR is provided by comint but is unused."
(ignore str)
(save-excursion
;; Move to end to make sure we are scanning the new stuff.
(goto-char (point-max))
;; We have found an error stack to investigate.
(let ((first nil)
(ans nil)
(overlaystack nil)
(starting-anchor matlab-shell-last-error-anchor)
(newest-anchor matlab-shell-last-error-anchor)
)
(while (setq ans (matlab-shell-scan-for-error
(or starting-anchor (point-min))))
(let* ((err-start (nth 0 ans))
(err-end (nth 1 ans))
(err-file (string-trim (nth 2 ans)))
(err-line (nth 3 ans))
;; note (nth 4 ans) is err-col
(o (make-overlay err-start err-end))
(err-mref-deref (matlab-shell-mref-to-filename err-file))
(err-full-file (when err-mref-deref (expand-file-name err-mref-deref)))
(url (concat "opentoline('" (or err-full-file err-file) "'," err-line ",0)"))
)
;; Setup the overlay with the URL.
(overlay-put o 'mouse-face 'highlight)
(overlay-put o 'face 'underline)
;; The url will recycle opentoline code.
(overlay-put o 'matlab-url url)
(overlay-put o 'matlab-fullfile err-full-file)
(overlay-put o 'keymap matlab-shell-html-map)
(overlay-put o 'help-echo (concat "Jump to error at " (or err-full-file err-file) "."))
(setq first url)
(push o overlaystack)
;; Save as a frame
(setq matlab-shell-last-anchor-as-frame
(cons err-file err-line))
(setq newest-anchor (max (or newest-anchor (point-min)) err-end))
))
;; Keep track of the very first error in this error stack.
;; It will represent the "place to go" for "go-to-last-error".
(dolist (O overlaystack)
(overlay-put O 'first-in-error-stack first))
;; Once we've found something, don't scan it again.
(when overlaystack
(setq matlab-shell-last-error-anchor (save-excursion
(goto-char newest-anchor)
(point-marker)))))))
(defvar matlab-shell-errortext-start-text "<ERRORTXT>\n"
"Text used as a signal for errors.")
(defvar matlab-shell-errortext-end-text "</ERRORTXT>"
"Text used as a signal for errors.")
(defun matlab-shell-colorize-errors (&optional str)
"Hook function run to colorize MATLAB errors.
The filter replaces indicators with <ERRORTXT> text </ERRORTXT>.
This strips out that text, and colorizes the region red.
STR is provided by COMINT but is unused."
(ignore str)
(save-excursion
(let ((start nil) (end nil)
)
(goto-char (point-max))
(while (re-search-backward (regexp-quote matlab-shell-errortext-end-text) nil t)
;; Start w/ end text to make sure everything is in the buffer already.
;; Then scan for the beginning, and start there. As we delete text, locations will move,
;; so move downward after this.
(if (not (re-search-backward (regexp-quote matlab-shell-errortext-start-text) nil t))
(error "Mismatched error text tokens from MATLAB")
;; Save off where we start, and delete the indicator.
(setq start (match-beginning 0))
(delete-region start (match-end 0))
;; Find the end.
(if (not (re-search-forward (regexp-quote matlab-shell-errortext-end-text) nil t))
(error "Internal error scanning for error text tokens")
(setq end (match-beginning 0))
(delete-region end (match-end 0))
;; Now colorize the text. Use overlay because font-lock messes with font properties.
(let ((o (make-overlay start end (current-buffer) nil nil))
)
(overlay-put o 'shellerror t)
(overlay-put o 'face 'matlab-shell-error-face)
)))
;; Setup for next loop
(goto-char (point-max))))))
;;; Shell Startup
(defun matlab-shell--get-emacsclient-command ()
"Compute how to call emacsclient so MATLAB will connect to this Emacs.
Handles case of multiple Emacsen from different users running on the same
system."
(when (not (server-running-p))
;; We need an Emacs server for ">> edit foo.m" which leverages to
;; emacsclient to open the file in the current Emacs session. Be
;; safe and start a server with a unique name. This ensures that
;; we don't have multiple emacs sessions stealing the server from
;; each other.
(setq server-name (format "server-%d" (emacs-pid)))
(message "matlab-shell: starting server with name %s" server-name)
(server-start)
(when (not (server-running-p))
(user-error "Unable to start server with name %s" server-name)))
(let ((iq (if (eq system-type 'windows-nt)
;; Probably on Windows, probably in "Program Files" -
;; we need to quote this thing.
;; SADLY - emacs Edit command also wraps the command in
;; quotes - but we have to include arguments - so we need
;; to add internal quotes so the quotes land in the right place
;; when MATLAB adds external quotes.
"\"" "")))
(concat
matlab-shell-emacsclient-command
iq " -n"
(if server-use-tcp
(concat " -f " iq (expand-file-name server-name server-auth-dir))
(concat " -s " iq (expand-file-name server-name server-socket-dir))))))
(defvar matlab-shell-use-emacs-toolbox
;; matlab may not be on path. (Name change, explicit load, etc)
(let* ((mlfile (locate-library "matlab"))
(dir (expand-file-name "toolbox/emacsinit.m"
(file-name-directory (or mlfile "")))))
(and mlfile (file-exists-p dir)))
"Add the `matlab-shell' MATLAB toolbox to the MATLAB path on startup.")
(defun matlab-shell-first-prompt-fcn ()
"Hook run when the first prompt is seen.
Sends commands to the MATLAB shell to initialize the MATLAB process."
;; Don't do this again
(remove-hook 'matlab-shell-prompt-appears-hook #'matlab-shell-first-prompt-fcn)
;; Init this session of MATLAB.
(if matlab-shell-use-emacs-toolbox
;; Use our local toolbox directory.
(let* ((path (expand-file-name "toolbox" (file-name-directory
(locate-library "matlab"))))