-
-
Notifications
You must be signed in to change notification settings - Fork 34.5k
Expand file tree
/
Copy pathpython-mode.el
More file actions
1928 lines (1697 loc) · 72 KB
/
python-mode.el
File metadata and controls
1928 lines (1697 loc) · 72 KB
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
;;; python-mode.el --- Major mode for editing Python programs
;; Copyright (C) 1992,1993,1994 Tim Peters
;; Author: 1995 Barry A. Warsaw <[email protected]>
;; 1992-1994 Tim Peters <[email protected]>
;; Maintainer: [email protected]
;; Created: Feb 1992
;; Version: $Revision$
;; Last Modified: $Date$
;; Keywords: python editing language major-mode
;; This software is provided as-is, without express or implied
;; warranty. Permission to use, copy, modify, distribute or sell this
;; software, without fee, for any purpose and by any individual or
;; organization, is hereby granted, provided that the above copyright
;; notice and this paragraph appear in all copies.
;;; Commentary:
;;
;; This is a major mode for editing Python programs. It was developed
;; by Tim Peters <[email protected]> after an original idea by Michael
;; A. Guravage. Tim doesn't appear to be on the 'net any longer so I
;; have undertaken maintenance of the mode.
;; At some point this mode will undergo a rewrite to bring it more in
;; line with GNU Emacs Lisp coding standards. But all in all, the
;; mode works exceedingly well.
;; The following statements, placed in your .emacs file or
;; site-init.el, will cause this file to be autoloaded, and
;; python-mode invoked, when visiting .py files (assuming this file is
;; in your load-path):
;;
;; (autoload 'python-mode "python-mode" "Python editing mode." t)
;; (setq auto-mode-alist
;; (cons '("\\.py$" . python-mode) auto-mode-alist))
;; Here's a brief list of recent additions/improvements:
;;
;; - Wrapping and indentation within triple quote strings should work
;; properly now.
;; - `Standard' bug reporting mechanism (use C-c C-b)
;; - py-mark-block was moved to C-c C-m
;; - C-c C-v shows you the python-mode version
;; - a basic python-font-lock-keywords has been added for Emacs 19
;; font-lock colorizations.
;; - proper interaction with pending-del and del-sel modes.
;; - New py-electric-colon (:) command for improved outdenting. Also
;; py-indent-line (TAB) should handle outdented lines better.
;; Here's a brief to do list:
;;
;; - Better integration with gud-mode for debugging.
;; - Rewrite according to GNU Emacs Lisp standards.
;; - py-delete-char should obey numeric arguments.
;; - even better support for outdenting. Guido suggests outdents of
;; at least one level after a return, raise, break, or continue
;; statement.
;; If you can think of more things you'd like to see, drop me a line.
;; If you want to report bugs, use py-submit-bug-report (C-c C-b).
;;
;; Note that I only test things on XEmacs (currently 19.11). If you
;; port stuff to FSF Emacs 19, or Emacs 18, please send me your
;; patches.
;; LCD Archive Entry:
;; python-mode|Barry A. Warsaw|[email protected]
;; |Major mode for editing Python programs
;; |$Date$|$Revision$|
;;; Code:
;; user definable variables
;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
(defvar py-python-command "python"
"*Shell command used to start Python interpreter.")
(defvar py-indent-offset 8 ; argue with Guido <grin>
"*Indentation increment.
Note that `\\[py-guess-indent-offset]' can usually guess a good value
when you're editing someone else's Python code.")
(defvar py-block-comment-prefix "##"
"*String used by `py-comment-region' to comment out a block of code.
This should follow the convention for non-indenting comment lines so
that the indentation commands won't get confused (i.e., the string
should be of the form `#x...' where `x' is not a blank or a tab, and
`...' is arbitrary).")
(defvar py-scroll-process-buffer t
"*Scroll Python process buffer as output arrives.
If nil, the Python process buffer acts, with respect to scrolling, like
Shell-mode buffers normally act. This is surprisingly complicated and
so won't be explained here; in fact, you can't get the whole story
without studying the Emacs C code.
If non-nil, the behavior is different in two respects (which are
slightly inaccurate in the interest of brevity):
- If the buffer is in a window, and you left point at its end, the
window will scroll as new output arrives, and point will move to the
buffer's end, even if the window is not the selected window (that
being the one the cursor is in). The usual behavior for shell-mode
windows is not to scroll, and to leave point where it was, if the
buffer is in a window other than the selected window.
- If the buffer is not visible in any window, and you left point at
its end, the buffer will be popped into a window as soon as more
output arrives. This is handy if you have a long-running
computation and don't want to tie up screen area waiting for the
output. The usual behavior for a shell-mode buffer is to stay
invisible until you explicitly visit it.
Note the `and if you left point at its end' clauses in both of the
above: you can `turn off' the special behaviors while output is in
progress, by visiting the Python buffer and moving point to anywhere
besides the end. Then the buffer won't scroll, point will remain where
you leave it, and if you hide the buffer it will stay hidden until you
visit it again. You can enable and disable the special behaviors as
often as you like, while output is in progress, by (respectively) moving
point to, or away from, the end of the buffer.
Warning: If you expect a large amount of output, you'll probably be
happier setting this option to nil.
Obscure: `End of buffer' above should really say `at or beyond the
process mark', but if you know what that means you didn't need to be
told <grin>.")
(defvar py-temp-directory
(let ((ok '(lambda (x)
(and x
(setq x (expand-file-name x)) ; always true
(file-directory-p x)
(file-writable-p x)
x))))
(or (funcall ok (getenv "TMPDIR"))
(funcall ok "/usr/tmp")
(funcall ok "/tmp")
(funcall ok ".")
(error
"Couldn't find a usable temp directory -- set py-temp-directory")))
"*Directory used for temp files created by a *Python* process.
By default, the first directory from this list that exists and that you
can write into: the value (if any) of the environment variable TMPDIR,
/usr/tmp, /tmp, or the current directory.")
(defvar py-beep-if-tab-change t
"*Ring the bell if tab-width is changed.
If a comment of the form
\t# vi:set tabsize=<number>:
is found before the first code line when the file is entered, and the
current value of (the general Emacs variable) `tab-width' does not
equal <number>, `tab-width' is set to <number>, a message saying so is
displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
the Emacs bell is also rung as a warning.")
(defvar python-font-lock-keywords
(list
(cons
(concat
"\\<\\("
(mapconcat
'identity
'("access" "and" "break" "continue"
"del" "elif" "else" "except"
"exec" "finally" "for" "from"
"global" "if" "import" "in"
"is" "lambda" "not" "or"
"pass" "print" "raise" "return"
"try" "while" "def" "class"
)
"\\|")
"\\)\\>")
1)
;; functions
'("\\bdef\\s +\\(\\sw+\\)(" 1 font-lock-function-name-face)
;; classes
'("\\bclass\\s +\\(\\sw+\\)[(:]" 1 font-lock-function-name-face)
)
"*Additional keywords to highlight `python-mode' buffers.")
;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
;; Differentiate between Emacs 18, Lucid Emacs, and Emacs 19. This
;; seems to be the standard way of checking this.
;; BAW - This is *not* the right solution. When at all possible,
;; instead of testing for the version of Emacs, use feature tests.
(setq py-this-is-lucid-emacs-p (string-match "Lucid\\|XEmacs" emacs-version))
(setq py-this-is-emacs-19-p
(and
(not py-this-is-lucid-emacs-p)
(string-match "^19\\." emacs-version)))
;; have to bind py-file-queue before installing the kill-emacs hook
(defvar py-file-queue nil
"Queue of Python temp files awaiting execution.
Currently-active file is at the head of the list.")
;; define a mode-specific abbrev table for those who use such things
(defvar python-mode-abbrev-table nil
"Abbrev table in use in `python-mode' buffers.")
(define-abbrev-table 'python-mode-abbrev-table nil)
(defvar python-mode-hook nil
"*Hook called by `python-mode'.")
;; in previous version of python-mode.el, the hook was incorrectly
;; called py-mode-hook, and was not defvar'd. deprecate its use.
(and (fboundp 'make-obsolete-variable)
(make-obsolete-variable 'py-mode-hook 'python-mode-hook))
(defvar py-mode-map ()
"Keymap used in `python-mode' buffers.")
(if py-mode-map
()
(setq py-mode-map (make-sparse-keymap))
;; shadow global bindings for newline-and-indent w/ the py- version.
;; BAW - this is extremely bad form, but I'm not going to change it
;; for now.
(mapcar (function (lambda (key)
(define-key
py-mode-map key 'py-newline-and-indent)))
(where-is-internal 'newline-and-indent))
;; BAW - you could do it this way, but its not considered proper
;; major-mode form.
(mapcar (function
(lambda (x)
(define-key py-mode-map (car x) (cdr x))))
'((":" . py-electric-colon)
("\C-c\C-c" . py-execute-buffer)
("\C-c|" . py-execute-region)
("\C-c!" . py-shell)
("\177" . py-delete-char)
("\n" . py-newline-and-indent)
("\C-c:" . py-guess-indent-offset)
("\C-c\t" . py-indent-region)
("\C-c<" . py-shift-region-left)
("\C-c>" . py-shift-region-right)
("\C-c\C-n" . py-next-statement)
("\C-c\C-p" . py-previous-statement)
("\C-c\C-u" . py-goto-block-up)
("\C-c\C-m" . py-mark-block)
("\C-c#" . py-comment-region)
("\C-c?" . py-describe-mode)
("\C-c\C-hm" . py-describe-mode)
("\e\C-a" . beginning-of-python-def-or-class)
("\e\C-e" . end-of-python-def-or-class)
( "\e\C-h" . mark-python-def-or-class)))
;; should do all keybindings this way
(define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
(define-key py-mode-map "\C-c\C-v" 'py-version)
)
(defvar py-mode-syntax-table nil
"Syntax table used in `python-mode' buffers.")
(if py-mode-syntax-table
()
(setq py-mode-syntax-table (make-syntax-table))
;; BAW - again, blech.
(mapcar (function
(lambda (x) (modify-syntax-entry
(car x) (cdr x) py-mode-syntax-table)))
'(( ?\( . "()" ) ( ?\) . ")(" )
( ?\[ . "(]" ) ( ?\] . ")[" )
( ?\{ . "(}" ) ( ?\} . "){" )
;; fix operator symbols misassigned in the std table
( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." )
( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." )
( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." )
( ?\> . "." ) ( ?\| . "." )
( ?\_ . "w" ) ; underscore is legit in names
( ?\' . "\"") ; single quote is string quote
( ?\" . "\"" ) ; double quote is string quote too
( ?\` . "$") ; backquote is open and close paren
( ?\# . "<") ; hash starts comment
( ?\n . ">")))) ; newline ends comment
(defconst py-stringlit-re
(concat
"'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
"\\|" ; or
"\"\\([^\"\n\\]\\|\\\\.\\)*\"") ; double-quoted
"Regexp matching a Python string literal.")
;; this is tricky because a trailing backslash does not mean
;; continuation if it's in a comment
(defconst py-continued-re
(concat
"\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
"\\\\$")
"Regexp matching Python lines that are continued via backslash.")
(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
"Regexp matching blank or comment lines.")
(defconst py-outdent-re
(concat "\\(" (mapconcat 'identity
'("else:"
"except\\(\\s +.*\\)?:"
"finally:"
"elif\\s +.*:")
"\\|")
"\\)")
"Regexp matching clauses to be outdented one level.")
(defconst py-no-outdent-re
(concat "\\(" (mapconcat 'identity
'("try\\s +.*:"
"except\\(\\s +.*\\)?:"
"while\\s +.*:"
"for\\s +.*:"
"if\\s +.*:"
"elif\\s +.*:")
"\\|")
"\\)")
"Regexp matching lines to not outdent after.")
;;;###autoload
(defun python-mode ()
"Major mode for editing Python files.
To submit a problem report, enter `\\[py-submit-bug-report]' from a
`python-mode' buffer. Do `\\[py-describe-mode]' for detailed
documentation. To see what version of `python-mode' you are running,
enter `\\[py-version]'.
This mode knows about Python indentation, tokens, comments and
continuation lines. Paragraphs are separated by blank lines only.
COMMANDS
\\{py-mode-map}
VARIABLES
py-indent-offset\tindentation increment
py-block-comment-prefix\tcomment string used by py-comment-region
py-python-command\tshell command to invoke Python interpreter
py-scroll-process-buffer\talways scroll Python process buffer
py-temp-directory\tdirectory used for temp files (if needed)
py-beep-if-tab-change\tring the bell if tab-width is changed"
(interactive)
(kill-all-local-variables)
(set-syntax-table py-mode-syntax-table)
(setq major-mode 'python-mode
mode-name "Python"
local-abbrev-table python-mode-abbrev-table)
(use-local-map py-mode-map)
;; BAW -- style...
(mapcar (function (lambda (x)
(make-local-variable (car x))
(set (car x) (cdr x))))
'((paragraph-separate . "^[ \t]*$")
(paragraph-start . "^[ \t]*$")
(require-final-newline . t)
(comment-start . "# ")
(comment-start-skip . "# *")
(comment-column . 40)
(indent-region-function . py-indent-region)
(indent-line-function . py-indent-line)))
;; hack to allow overriding the tabsize in the file (see tokenizer.c)
;;
;; not sure where the magic comment has to be; to save time
;; searching for a rarity, we give up if it's not found prior to the
;; first executable statement.
;;
;; BAW - on first glance, this seems like complete hackery. Why was
;; this necessary, and is it still necessary?
(let ((case-fold-search nil)
(start (point))
new-tab-width)
(if (re-search-forward
"^[ \t]*#[ \t]*vi:set[ \t]+tabsize=\\([0-9]+\\):"
(prog2 (py-next-statement 1) (point) (goto-char 1))
t)
(progn
(setq new-tab-width
(string-to-int
(buffer-substring (match-beginning 1) (match-end 1))))
(if (= tab-width new-tab-width)
nil
(setq tab-width new-tab-width)
(message "Caution: tab-width changed to %d" new-tab-width)
(if py-beep-if-tab-change (beep)))))
(goto-char start))
;; run the mode hook. py-mode-hook use is deprecated
(if python-mode-hook
(run-hooks 'python-mode-hook)
(run-hooks 'py-mode-hook)))
;; electric characters
(defun py-electric-colon (arg)
"Insert a colon.
In certain cases the line is outdented appropriately. If a numeric
argument is provided, that many colons are inserted non-electrically."
(interactive "P")
(self-insert-command (prefix-numeric-value arg))
(save-excursion
(let ((here (point))
(outdent 0)
(indent (py-compute-indentation)))
(if (and (not arg)
(progn
(back-to-indentation)
(looking-at py-outdent-re))
(prog2
(backward-to-indentation 1)
(not (looking-at py-no-outdent-re))
(goto-char here))
(= indent (progn
(forward-line -1)
(py-compute-indentation)))
)
(setq outdent py-indent-offset))
(goto-char here)
(beginning-of-line)
(delete-horizontal-space)
(indent-to (- indent outdent))
)))
;;; Functions that execute Python commands in a subprocess
(defun py-shell ()
"Start an interactive Python interpreter in another window.
This is like Shell mode, except that Python is running in the window
instead of a shell. See the `Interactive Shell' and `Shell Mode'
sections of the Emacs manual for details, especially for the key
bindings active in the `*Python*' buffer.
See the docs for variable `py-scroll-buffer' for info on scrolling
behavior in the process window.
Warning: Don't use an interactive Python if you change sys.ps1 or
sys.ps2 from their default values, or if you're running code that
prints `>>> ' or `... ' at the start of a line. `python-mode' can't
distinguish your output from Python's output, and assumes that `>>> '
at the start of a line is a prompt from Python. Similarly, the Emacs
Shell mode code assumes that both `>>> ' and `... ' at the start of a
line are Python prompts. Bad things can happen if you fool either
mode.
Warning: If you do any editing *in* the process buffer *while* the
buffer is accepting output from Python, do NOT attempt to `undo' the
changes. Some of the output (nowhere near the parts you changed!) may
be lost if you do. This appears to be an Emacs bug, an unfortunate
interaction between undo and process filters; the same problem exists in
non-Python process buffers using the default (Emacs-supplied) process
filter."
;; BAW - should undo be disabled in the python process buffer, if
;; this bug still exists?
(interactive)
(if py-this-is-emacs-19-p
(progn
(require 'comint)
(switch-to-buffer-other-window
(make-comint "Python" py-python-command)))
(progn
(require 'shell)
(switch-to-buffer-other-window
(make-shell "Python" py-python-command))))
(make-local-variable 'shell-prompt-pattern)
(setq shell-prompt-pattern "^>>> \\|^\\.\\.\\. ")
(set-process-filter (get-buffer-process (current-buffer))
'py-process-filter)
(set-syntax-table py-mode-syntax-table))
(defun py-execute-region (start end)
"Send the region between START and END to a Python interpreter.
If there is a *Python* process it is used.
Hint: If you want to execute part of a Python file several times
\(e.g., perhaps you're developing a function and want to flesh it out
a bit at a time), use `\\[narrow-to-region]' to restrict the buffer to
the region of interest, and send the code to a *Python* process via
`\\[py-execute-buffer]' instead.
Following are subtleties to note when using a *Python* process:
If a *Python* process is used, the region is copied into a temporary
file (in directory `py-temp-directory'), and an `execfile' command is
sent to Python naming that file. If you send regions faster than
Python can execute them, `python-mode' will save them into distinct
temp files, and execute the next one in the queue the next time it
sees a `>>> ' prompt from Python. Each time this happens, the process
buffer is popped into a window (if it's not already in some window) so
you can see it, and a comment of the form
\t## working on region in file <name> ...
is inserted at the end.
Caution: No more than 26 regions can be pending at any given time.
This limit is (indirectly) inherited from libc's mktemp(3).
`python-mode' does not try to protect you from exceeding the limit.
It's extremely unlikely that you'll get anywhere close to the limit in
practice, unless you're trying to be a jerk <grin>.
See the `\\[py-shell]' docs for additional warnings."
(interactive "r")
(or (< start end) (error "Region is empty"))
(let ((pyproc (get-process "Python"))
fname)
(if (null pyproc)
(shell-command-on-region start end py-python-command)
;; else feed it thru a temp file
(setq fname (py-make-temp-name))
(write-region start end fname nil 'no-msg)
(setq py-file-queue (append py-file-queue (list fname)))
(if (cdr py-file-queue)
(message "File %s queued for execution" fname)
;; else
(py-execute-file pyproc fname)))))
(defun py-execute-file (pyproc fname)
(py-append-to-process-buffer
pyproc
(format "## working on region in file %s ...\n" fname))
(process-send-string pyproc (format "execfile('%s')\n" fname)))
(defun py-process-filter (pyproc string)
(let ((curbuf (current-buffer))
(pbuf (process-buffer pyproc))
(pmark (process-mark pyproc))
file-finished)
;; make sure we switch to a different buffer at least once. if we
;; *don't* do this, then if the process buffer is in the selected
;; window, and point is before the end, and lots of output is
;; coming at a fast pace, then (a) simple cursor-movement commands
;; like C-p, C-n, C-f, C-b, C-a, C-e take an incredibly long time
;; to have a visible effect (the window just doesn't get updated,
;; sometimes for minutes(!)), and (b) it takes about 5x longer to
;; get all the process output (until the next python prompt).
;;
;; #b makes no sense to me at all. #a almost makes sense: unless
;; we actually change buffers, set_buffer_internal in buffer.c
;; doesn't set windows_or_buffers_changed to 1, & that in turn
;; seems to make the Emacs command loop reluctant to update the
;; display. Perhaps the default process filter in process.c's
;; read_process_output has update_mode_lines++ for a similar
;; reason? beats me ...
;; BAW - we want to check to see if this still applies
(if (eq curbuf pbuf) ; mysterious ugly hack
(set-buffer (get-buffer-create "*scratch*")))
(set-buffer pbuf)
(let* ((start (point))
(goback (< start pmark))
(buffer-read-only nil))
(goto-char pmark)
(insert string)
(move-marker pmark (point))
(setq file-finished
(and py-file-queue
(equal ">>> "
(buffer-substring
(prog2 (beginning-of-line) (point)
(goto-char pmark))
(point)))))
(if goback (goto-char start)
;; else
(if py-scroll-process-buffer
(let* ((pop-up-windows t)
(pwin (display-buffer pbuf)))
(set-window-point pwin (point))))))
(set-buffer curbuf)
(if file-finished
(progn
(py-delete-file-silently (car py-file-queue))
(setq py-file-queue (cdr py-file-queue))
(if py-file-queue
(py-execute-file pyproc (car py-file-queue)))))))
(defun py-execute-buffer ()
"Send the contents of the buffer to a Python interpreter.
If there is a *Python* process buffer it is used. If a clipping
restriction is in effect, only the accessible portion of the buffer is
sent. A trailing newline will be supplied if needed.
See the `\\[py-execute-region]' docs for an account of some subtleties."
(interactive)
(py-execute-region (point-min) (point-max)))
;; Functions for Python style indentation
(defun py-delete-char ()
"Reduce indentation or delete character.
If point is at the leftmost column, deletes the preceding newline.
Else if point is at the leftmost non-blank character of a line that is
neither a continuation line nor a non-indenting comment line, or if
point is at the end of a blank line, reduces the indentation to match
that of the line that opened the current block of code. The line that
opened the block is displayed in the echo area to help you keep track
of where you are.
Else the preceding character is deleted, converting a tab to spaces if
needed so that only a single column position is deleted."
(interactive "*")
(if (or (/= (current-indentation) (current-column))
(bolp)
(py-continuation-line-p)
(looking-at "#[^ \t\n]")) ; non-indenting #
(backward-delete-char-untabify 1)
;; else indent the same as the colon line that opened the block
;; force non-blank so py-goto-block-up doesn't ignore it
(insert-char ?* 1)
(backward-char)
(let ((base-indent 0) ; indentation of base line
(base-text "") ; and text of base line
(base-found-p nil))
(condition-case nil ; in case no enclosing block
(save-excursion
(py-goto-block-up 'no-mark)
(setq base-indent (current-indentation)
base-text (py-suck-up-leading-text)
base-found-p t))
(error nil))
(delete-char 1) ; toss the dummy character
(delete-horizontal-space)
(indent-to base-indent)
(if base-found-p
(message "Closes block: %s" base-text)))))
;; required for pending-del and delsel modes
(put 'py-delete-char 'delete-selection 'supersede)
(put 'py-delete-char 'pending-delete 'supersede)
(defun py-indent-line ()
"Fix the indentation of the current line according to Python rules."
(interactive)
(let* ((ci (current-indentation))
(move-to-indentation-p (<= (current-column) ci))
(need (py-compute-indentation)))
;; see if we need to outdent
(if (save-excursion
(and (progn (back-to-indentation)
(looking-at py-outdent-re))
(progn (backward-to-indentation 1)
(not (looking-at py-no-outdent-re)))))
(setq need (- need py-indent-offset)))
(if (/= ci need)
(save-excursion
(beginning-of-line)
(delete-horizontal-space)
(indent-to need)))
(if move-to-indentation-p (back-to-indentation))))
(defun py-newline-and-indent ()
"Strives to act like the Emacs `newline-and-indent'.
This is just `strives to' because correct indentation can't be computed
from scratch for Python code. In general, deletes the whitespace before
point, inserts a newline, and takes an educated guess as to how you want
the new line indented."
(interactive)
(let ((ci (current-indentation)))
(if (< ci (current-column)) ; if point beyond indentation
(newline-and-indent)
;; else try to act like newline-and-indent "normally" acts
(beginning-of-line)
(insert-char ?\n 1)
(move-to-column ci))))
(defun py-compute-indentation ()
(save-excursion
(beginning-of-line)
(cond
;; are we on a continuation line?
((py-continuation-line-p)
(let ((startpos (point))
(open-bracket-pos (py-nesting-level))
endpos searching found)
(if open-bracket-pos
(progn
;; align with first item in list; else a normal
;; indent beyond the line with the open bracket
(goto-char (1+ open-bracket-pos)) ; just beyond bracket
;; is the first list item on the same line?
(skip-chars-forward " \t")
(if (null (memq (following-char) '(?\n ?# ?\\)))
; yes, so line up with it
(current-column)
;; first list item on another line, or doesn't exist yet
(forward-line 1)
(while (and (< (point) startpos)
(looking-at "[ \t]*[#\n\\\\]")) ; skip noise
(forward-line 1))
(if (< (point) startpos)
;; again mimic the first list item
(current-indentation)
;; else they're about to enter the first item
(goto-char open-bracket-pos)
(+ (current-indentation) py-indent-offset))))
;; else on backslash continuation line
(forward-line -1)
(if (py-continuation-line-p) ; on at least 3rd line in block
(current-indentation) ; so just continue the pattern
;; else started on 2nd line in block, so indent more.
;; if base line is an assignment with a start on a RHS,
;; indent to 2 beyond the leftmost "="; else skip first
;; chunk of non-whitespace characters on base line, + 1 more
;; column
(end-of-line)
(setq endpos (point) searching t)
(back-to-indentation)
(setq startpos (point))
;; look at all "=" from left to right, stopping at first
;; one not nested in a list or string
(while searching
(skip-chars-forward "^=" endpos)
(if (= (point) endpos)
(setq searching nil)
(forward-char 1)
(setq state (parse-partial-sexp startpos (point)))
(if (and (zerop (car state)) ; not in a bracket
(null (nth 3 state))) ; & not in a string
(progn
(setq searching nil) ; done searching in any case
(setq found
(not (or
(eq (following-char) ?=)
(memq (char-after (- (point) 2))
'(?< ?> ?!)))))))))
(if (or (not found) ; not an assignment
(looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
(progn
(goto-char startpos)
(skip-chars-forward "^ \t\n")))
(1+ (current-column))))))
;; not on a continuation line
;; if at start of restriction, or on a non-indenting comment line,
;; assume they intended whatever's there
((or (bobp) (looking-at "[ \t]*#[^ \t\n]"))
(current-indentation))
;; else indentation based on that of the statement that precedes
;; us; use the first line of that statement to establish the base,
;; in case the user forced a non-std indentation for the
;; continuation lines (if any)
(t
;; skip back over blank & non-indenting comment lines
;; note: will skip a blank or non-indenting comment line that
;; happens to be a continuation line too
(re-search-backward "^[ \t]*\\([^ \t\n#]\\|#[ \t\n]\\)"
nil 'move)
;; if we landed inside a string, go to the beginning of that
;; string. this handles triple quoted, multi-line spanning
;; strings.
(let ((state (parse-partial-sexp
(save-excursion (beginning-of-python-def-or-class)
(point))
(point))))
(if (nth 3 state)
(goto-char (nth 2 state))))
(py-goto-initial-line)
(if (py-statement-opens-block-p)
(+ (current-indentation) py-indent-offset)
(current-indentation))))))
(defun py-guess-indent-offset (&optional global)
"Guess a good value for, and change, `py-indent-offset'.
By default (without a prefix arg), makes a buffer-local copy of
`py-indent-offset' with the new value. This will not affect any other
Python buffers. With a prefix arg, changes the global value of
`py-indent-offset'. This affects all Python buffers (that don't have
their own buffer-local copy), both those currently existing and those
created later in the Emacs session.
Some people use a different value for `py-indent-offset' than you use.
There's no excuse for such foolishness, but sometimes you have to deal
with their ugly code anyway. This function examines the file and sets
`py-indent-offset' to what it thinks it was when they created the
mess.
Specifically, it searches forward from the statement containing point,
looking for a line that opens a block of code. `py-indent-offset' is
set to the difference in indentation between that line and the Python
statement following it. If the search doesn't succeed going forward,
it's tried again going backward."
(interactive "P") ; raw prefix arg
(let (new-value
(start (point))
restart
(found nil)
colon-indent)
(py-goto-initial-line)
(while (not (or found (eobp)))
(if (re-search-forward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
(progn
(setq restart (point))
(py-goto-initial-line)
(if (py-statement-opens-block-p)
(setq found t)
(goto-char restart)))))
(if found
()
(goto-char start)
(py-goto-initial-line)
(while (not (or found (bobp)))
(setq found
(and
(re-search-backward ":[ \t]*\\($\\|[#\\]\\)" nil 'move)
(or (py-goto-initial-line) t) ; always true -- side effect
(py-statement-opens-block-p)))))
(setq colon-indent (current-indentation)
found (and found (zerop (py-next-statement 1)))
new-value (- (current-indentation) colon-indent))
(goto-char start)
(if found
(progn
(funcall (if global 'kill-local-variable 'make-local-variable)
'py-indent-offset)
(setq py-indent-offset new-value)
(message "%s value of py-indent-offset set to %d"
(if global "Global" "Local")
py-indent-offset))
(error "Sorry, couldn't guess a value for py-indent-offset"))))
(defun py-shift-region (start end count)
(save-excursion
(goto-char end) (beginning-of-line) (setq end (point))
(goto-char start) (beginning-of-line) (setq start (point))
(indent-rigidly start end count)))
(defun py-shift-region-left (start end &optional count)
"Shift region of Python code to the left.
The lines from the line containing the start of the current region up
to (but not including) the line containing the end of the region are
shifted to the left, by `py-indent-offset' columns.
If a prefix argument is given, the region is instead shifted by that
many columns."
(interactive "*r\nP") ; region; raw prefix arg
(py-shift-region start end
(- (prefix-numeric-value
(or count py-indent-offset)))))
(defun py-shift-region-right (start end &optional count)
"Shift region of Python code to the right.
The lines from the line containing the start of the current region up
to (but not including) the line containing the end of the region are
shifted to the right, by `py-indent-offset' columns.
If a prefix argument is given, the region is instead shifted by that
many columns."
(interactive "*r\nP") ; region; raw prefix arg
(py-shift-region start end (prefix-numeric-value
(or count py-indent-offset))))
(defun py-indent-region (start end &optional indent-offset)
"Reindent a region of Python code.
The lines from the line containing the start of the current region up
to (but not including) the line containing the end of the region are
reindented. If the first line of the region has a non-whitespace
character in the first column, the first line is left alone and the
rest of the region is reindented with respect to it. Else the entire
region is reindented with respect to the (closest code or
indenting-comment) statement immediately preceding the region.
This is useful when code blocks are moved or yanked, when enclosing
control structures are introduced or removed, or to reformat code
using a new value for the indentation offset.
If a numeric prefix argument is given, it will be used as the value of
the indentation offset. Else the value of `py-indent-offset' will be
used.
Warning: The region must be consistently indented before this function
is called! This function does not compute proper indentation from
scratch (that's impossible in Python), it merely adjusts the existing
indentation to be correct in context.
Warning: This function really has no idea what to do with
non-indenting comment lines, and shifts them as if they were indenting
comment lines. Fixing this appears to require telepathy.
Special cases: whitespace is deleted from blank lines; continuation
lines are shifted by the same amount their initial line was shifted,
in order to preserve their relative indentation with respect to their
initial line; and comment lines beginning in column 1 are ignored."
(interactive "*r\nP") ; region; raw prefix arg
(save-excursion
(goto-char end) (beginning-of-line) (setq end (point-marker))
(goto-char start) (beginning-of-line)
(let ((py-indent-offset (prefix-numeric-value
(or indent-offset py-indent-offset)))
(indents '(-1)) ; stack of active indent levels
(target-column 0) ; column to which to indent
(base-shifted-by 0) ; amount last base line was shifted
(indent-base (if (looking-at "[ \t\n]")
(py-compute-indentation)
0))
ci)
(while (< (point) end)
(setq ci (current-indentation))
;; figure out appropriate target column
(cond
((or (eq (following-char) ?#) ; comment in column 1
(looking-at "[ \t]*$")) ; entirely blank
(setq target-column 0))
((py-continuation-line-p) ; shift relative to base line
(setq target-column (+ ci base-shifted-by)))
(t ; new base line
(if (> ci (car indents)) ; going deeper; push it
(setq indents (cons ci indents))
;; else we should have seen this indent before
(setq indents (memq ci indents)) ; pop deeper indents
(if (null indents)
(error "Bad indentation in region, at line %d"
(save-restriction
(widen)
(1+ (count-lines 1 (point)))))))
(setq target-column (+ indent-base
(* py-indent-offset
(- (length indents) 2))))
(setq base-shifted-by (- target-column ci))))
;; shift as needed
(if (/= ci target-column)
(progn
(delete-horizontal-space)
(indent-to target-column)))
(forward-line 1))))
(set-marker end nil))
;; Functions for moving point
(defun py-previous-statement (count)
"Go to the start of previous Python statement.
If the statement at point is the i'th Python statement, goes to the
start of statement i-COUNT. If there is no such statement, goes to the
first statement. Returns count of statements left to move.
`Statements' do not include blank, comment, or continuation lines."
(interactive "p") ; numeric prefix arg
(if (< count 0) (py-next-statement (- count))
(py-goto-initial-line)
(let (start)
(while (and
(setq start (point)) ; always true -- side effect
(> count 0)
(zerop (forward-line -1))
(py-goto-statement-at-or-above))
(setq count (1- count)))
(if (> count 0) (goto-char start)))
count))
(defun py-next-statement (count)
"Go to the start of next Python statement.
If the statement at point is the i'th Python statement, goes to the
start of statement i+COUNT. If there is no such statement, goes to the
last statement. Returns count of statements left to move. `Statements'
do not include blank, comment, or continuation lines."
(interactive "p") ; numeric prefix arg
(if (< count 0) (py-previous-statement (- count))
(beginning-of-line)
(let (start)
(while (and
(setq start (point)) ; always true -- side effect
(> count 0)
(py-goto-statement-below))
(setq count (1- count)))
(if (> count 0) (goto-char start)))
count))
(defun py-goto-block-up (&optional nomark)
"Move up to start of current block.
Go to the statement that starts the smallest enclosing block; roughly
speaking, this will be the closest preceding statement that ends with a
colon and is indented less than the statement you started on. If
successful, also sets the mark to the starting point.
`\\[py-mark-block]' can be used afterward to mark the whole code
block, if desired.
If called from a program, the mark will not be set if optional argument
NOMARK is not nil."
(interactive)
(let ((start (point))
(found nil)
initial-indent)
(py-goto-initial-line)