-
-
Notifications
You must be signed in to change notification settings - Fork 34.5k
Expand file tree
/
Copy pathpython-mode.el
More file actions
2472 lines (2171 loc) · 92.4 KB
/
python-mode.el
File metadata and controls
2472 lines (2171 loc) · 92.4 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-1997 Barry A. Warsaw
;; 1992-1994 Tim Peters
;; Maintainer: [email protected]
;; Created: Feb 1992
;; Version: $Revision$
;; Last Modified: $Date$
;; Keywords: python languages oop
;; 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 after an original idea by Michael A. Guravage. Tim
;; subsequently left the net; in 1995, Barry Warsaw inherited the
;; mode and is the current maintainer.
;; At some point this mode will undergo a rewrite to bring it more in
;; line with GNU Emacs Lisp coding standards, and to wax all the Emacs
;; 18 support. But all in all, the mode works exceedingly well, and
;; I've simply been tweaking it as I go along. Ain't it wonderful
;; that Python has a much more sane syntax than C? (or <shudder> C++?!
;; :-). I can say that; I maintain cc-mode!
;; 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))
;;
;; If you want font-lock support for Python source code (a.k.a. syntax
;; coloring, highlighting), add this to your .emacs file:
;;
;; (add-hook 'python-mode-hook 'turn-on-font-lock)
;;
;; But you better be sure you're version of Emacs supports
;; font-lock-mode! As of this writing, the latest Emacs and XEmacs
;; 19's do.
;; Here's a brief list of recent additions/improvements/changes:
;;
;; - Wrapping and indentation within triple quote strings now works.
;; - `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 (X)Emacs 19
;; - proper interaction with pending-del and del-sel modes.
;; - Better support for outdenting: py-electric-colon (:) and
;; py-indent-line (TAB) improvements; one level of outdentation
;; added after a return, raise, break, pass, or continue statement.
;; Defeated by prefixing command with C-u.
;; - New py-electric-colon (:) command for improved outdenting Also
;; py-indent-line (TAB) should handle outdented lines better
;; - improved (I think) C-c > and C-c <
;; - py-(forward|backward)-into-nomenclature, not bound, but useful on
;; M-f and M-b respectively.
;; - integration with imenu by Perry A. Stoll <[email protected]>
;; - py-indent-offset now defaults to 4
;; - new variable py-honor-comment-indentation
;; - comment-region bound to C-c #
;; - py-delete-char obeys numeric arguments
;; - Small modification to rule for "indenting comment lines", such
;; lines must now also be indented less than or equal to the
;; indentation of the previous statement.
;; Here's a brief to do list:
;;
;; - Better integration with gud-mode for debugging.
;; - Rewrite according to GNU Emacs Lisp standards.
;; - possibly force indent-tabs-mode == nil, and add a
;; write-file-hooks that runs untabify on the whole buffer (to work
;; around potential tab/space mismatch problems). In practice this
;; hasn't been a problem... yet.
;; - have py-execute-region on indented code act as if the region is
;; left justified. Avoids syntax errors.
;; - Add a py-goto-error or some such that would scan an exception in
;; the py-shell buffer, and pop you to that line in the file.
;; 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 19 and to some degree on
;; Emacs 19. If you port stuff to FSF Emacs 19, or Emacs 18, please
;; send me your patches. Byte compiler complaints can probably be
;; safely ignored.
;;; Code:
;; user definable variables
;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
(defvar py-python-command "python"
"*Shell command used to start Python interpreter.")
(defvar py-indent-offset 4
"*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-align-multiline-strings-p t
"*Flag describing how multiline triple quoted strings are aligned.
When this flag is non-nil, continuation lines are lined up under the
preceding line's indentation. When this flag is nil, continuation
lines are aligned to column zero.")
(defvar py-block-comment-prefix "## "
"*String used by \\[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-honor-comment-indentation t
"*Controls how comment lines influence subsequent indentation.
When nil, all comment lines are skipped for indentation purposes, and
in Emacs 19, a faster algorithm is used.
When t, lines that begin with a single `#' are a hint to subsequent
line indentation. If the previous line is such a comment line (as
opposed to one that starts with `py-block-comment-prefix'), then it's
indentation is used as a hint for this line's indentation. Lines that
begin with `py-block-comment-prefix' are ignored for indentation
purposes.
When not nil or t, comment lines that begin with a `#' are used as
indentation hints, unless the comment character is in column zero.")
(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
(let* ((keywords '("and" "break" "class"
"continue" "def" "del" "elif"
"else:" "except" "except:" "exec"
"finally:" "for" "from" "global"
"if" "import" "in" "is"
"lambda" "not" "or" "pass"
"print" "raise" "return" "try:"
"while"
))
(kwregex (mapconcat 'identity keywords "\\|")))
(list
;; keywords not at beginning of line
(cons (concat "\\s-\\(" kwregex "\\)[ \n\t(]") 1)
;; keywords at beginning of line. i don't think regexps are
;; powerful enough to handle these two cases in one regexp.
;; prove me wrong!
(cons (concat "^\\(" kwregex "\\)[ \n\t(]") 1)
;; classes
'("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
1 font-lock-type-face)
;; functions
'("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
1 font-lock-function-name-face)
))
"Additional expressions to highlight in Python mode.")
(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
(defvar imenu-example--python-show-method-args-p nil
"*Controls echoing of arguments of functions & methods in the imenu buffer.
When non-nil, arguments are printed.")
;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
(make-variable-buffer-local 'py-indent-offset)
;; 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-delete-function 'backward-delete-char-untabify
"*Function called by `py-delete-char' when deleting characters.")
(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\C-l" . py-shift-region-left)
("\C-c\C-r" . py-shift-region-right)
("\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
( ?\$ . "." ) ( ?\% . "." ) ( ?\& . "." )
( ?\* . "." ) ( ?\+ . "." ) ( ?\- . "." )
( ?\/ . "." ) ( ?\< . "." ) ( ?\= . "." )
( ?\> . "." ) ( ?\| . "." )
;; for historical reasons, underscore is word class
;; instead of symbol class. it should be symbol class,
;; but if you're tempted to change it, try binding M-f and
;; M-b to py-forward-into-nomenclature and
;; py-backward-into-nomenclature instead. -baw
( ?\_ . "w" ) ; underscore is legit in words
( ?\' . "\"") ; 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:"
"except\\(\\s +.*\\)?:"
"while\\s +.*:"
"for\\s +.*:"
"if\\s +.*:"
"elif\\s +.*:"
"\\(return\\|break\\|raise\\|continue\\)[ \t\n]"
)
"\\|")
"\\)")
"Regexp matching lines to not outdent after.")
(defvar py-defun-start-re
"^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*="
"Regexp matching a function, method or variable assignment.
If you change this, you probably have to change `py-current-defun' as well.
This is only used by `py-current-defun' to find the name for add-log.el.")
(defvar py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)"
"Regexp for finding a class name.
If you change this, you probably have to change `py-current-defun' as well.
This is only used by `py-current-defun' to find the name for add-log.el.")
;; As of 30-Jan-1997, Emacs 19.34 works but XEmacs 19.15b90 and
;; previous does not. It is suspected that Emacsen before 19.34 are
;; also broken.
(defvar py-parse-partial-sexp-works-p
(let ((buf (get-buffer-create " ---*---pps---*---"))
state status)
(save-excursion
(set-buffer buf)
(erase-buffer)
(insert "(line1\n line2)\nline3")
(lisp-mode)
(goto-char (point-min))
(setq state (parse-partial-sexp (point) (save-excursion
(forward-line 1)
(point))))
(parse-partial-sexp (point) (point-max) 0 nil state)
(setq status (not (= (point) (point-max))))
(kill-buffer buf)
status))
"Does `parse-partial-sexp' work in this Emacs?")
;; Menu definitions, only relevent if you have the easymenu.el package
;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
(defvar py-menu nil
"Menu for Python Mode.
This menu will get created automatically if you have the easymenu
package. Note that the latest XEmacs 19 and Emacs 19 versions contain
this package.")
(if (condition-case nil
(require 'easymenu)
(error nil))
(easy-menu-define
py-menu py-mode-map "Python Mode menu"
'("Python"
["Comment Out Region" py-comment-region (mark)]
["Uncomment Region" (py-comment-region (point) (mark) '(4)) (mark)]
"-"
["Mark current block" py-mark-block t]
["Mark current def" mark-python-def-or-class t]
["Mark current class" (mark-python-def-or-class t) t]
"-"
["Shift region left" py-shift-region-left (mark)]
["Shift region right" py-shift-region-right (mark)]
"-"
["Execute buffer" py-execute-buffer t]
["Execute region" py-execute-region (mark)]
["Start interpreter..." py-shell t]
"-"
["Go to start of block" py-goto-block-up t]
["Go to start of class" (beginning-of-python-def-or-class t) t]
["Move to end of class" (end-of-python-def-or-class t) t]
["Move to start of def" beginning-of-python-def-or-class t]
["Move to end of def" end-of-python-def-or-class t]
"-"
["Describe mode" py-describe-mode t]
)))
;; imenu definitions, courtesy of Perry A. Stoll <[email protected]>
(defvar imenu-example--python-class-regexp
(concat ; <<classes>>
"\\(" ;
"^[ \t]*" ; newline and maybe whitespace
"\\(class[ \t]+[a-zA-Z0-9_]+\\)" ; class name
; possibly multiple superclasses
"\\([ \t]*\\((\\([a-zA-Z0-9_, \t\n]\\)*)\\)?\\)"
"[ \t]*:" ; and the final :
"\\)" ; >>classes<<
)
"Regexp for Python classes for use with the imenu package."
)
(defvar imenu-example--python-method-regexp
(concat ; <<methods and functions>>
"\\(" ;
"^[ \t]*" ; new line and maybe whitespace
"\\(def[ \t]+" ; function definitions start with def
"\\([a-zA-Z0-9_]+\\)" ; name is here
; function arguments...
"[ \t]*(\\([a-zA-Z0-9_=,\* \t\n]*\\))"
"\\)" ; end of def
"[ \t]*:" ; and then the :
"\\)" ; >>methods and functions<<
)
"Regexp for Python methods/functions for use with the imenu package."
)
(defvar imenu-example--python-method-no-arg-parens '(2 8)
"Indicies into groups of the Python regexp for use with imenu.
Using these values will result in smaller imenu lists, as arguments to
functions are not listed.
See the variable `imenu-example--python-show-method-args-p' for more
information.")
(defvar imenu-example--python-method-arg-parens '(2 7)
"Indicies into groups of the Python regexp for use with imenu.
Using these values will result in large imenu lists, as arguments to
functions are listed.
See the variable `imenu-example--python-show-method-args-p' for more
information.")
;; Note that in this format, this variable can still be used with the
;; imenu--generic-function. Otherwise, there is no real reason to have
;; it.
(defvar imenu-example--generic-python-expression
(cons
(concat
imenu-example--python-class-regexp
"\\|" ; or...
imenu-example--python-method-regexp
)
imenu-example--python-method-no-arg-parens)
"Generic Python expression which may be used directly with imenu.
Used by setting the variable `imenu-generic-expression' to this value.
Also, see the function \\[imenu-example--create-python-index] for a
better alternative for finding the index.")
;; These next two variables are used when searching for the python
;; class/definitions. Just saving some time in accessing the
;; generic-python-expression, really.
(defvar imenu-example--python-generic-regexp nil)
(defvar imenu-example--python-generic-parens nil)
;;;###autoload
(eval-when-compile
;; Imenu isn't used in XEmacs, so just ignore load errors
(condition-case ()
(progn
(require 'cl)
(require 'imenu))
(error nil)))
(defun imenu-example--create-python-index ()
"Python interface function for imenu package.
Finds all python classes and functions/methods. Calls function
\\[imenu-example--create-python-index-engine]. See that function for
the details of how this works."
(setq imenu-example--python-generic-regexp
(car imenu-example--generic-python-expression))
(setq imenu-example--python-generic-parens
(if imenu-example--python-show-method-args-p
imenu-example--python-method-arg-parens
imenu-example--python-method-no-arg-parens))
(goto-char (point-min))
(imenu-example--create-python-index-engine nil))
(defun imenu-example--create-python-index-engine (&optional start-indent)
"Function for finding imenu definitions in Python.
Finds all definitions (classes, methods, or functions) in a Python
file for the imenu package.
Returns a possibly nested alist of the form
(INDEX-NAME . INDEX-POSITION)
The second element of the alist may be an alist, producing a nested
list as in
(INDEX-NAME . INDEX-ALIST)
This function should not be called directly, as it calls itself
recursively and requires some setup. Rather this is the engine for
the function \\[imenu-example--create-python-index].
It works recursively by looking for all definitions at the current
indention level. When it finds one, it adds it to the alist. If it
finds a definition at a greater indentation level, it removes the
previous definition from the alist. In it's place it adds all
definitions found at the next indentation level. When it finds a
definition that is less indented then the current level, it retuns the
alist it has created thus far.
The optional argument START-INDENT indicates the starting indentation
at which to continue looking for Python classes, methods, or
functions. If this is not supplied, the function uses the indentation
of the first definition found."
(let ((index-alist '())
(sub-method-alist '())
looking-p
def-name prev-name
cur-indent def-pos
(class-paren (first imenu-example--python-generic-parens))
(def-paren (second imenu-example--python-generic-parens)))
(setq looking-p
(re-search-forward imenu-example--python-generic-regexp
(point-max) t))
(while looking-p
(save-excursion
;; used to set def-name to this value but generic-extract-name is
;; new to imenu-1.14. this way it still works with imenu-1.11
;;(imenu--generic-extract-name imenu-example--python-generic-parens))
(let ((cur-paren (if (match-beginning class-paren)
class-paren def-paren)))
(setq def-name
(buffer-substring (match-beginning cur-paren)
(match-end cur-paren))))
(beginning-of-line)
(setq cur-indent (current-indentation)))
;; HACK: want to go to the next correct definition location. we
;; explicitly list them here. would be better to have them in a
;; list.
(setq def-pos
(or (match-beginning class-paren)
(match-beginning def-paren)))
;; if we don't have a starting indent level, take this one
(or start-indent
(setq start-indent cur-indent))
;; if we don't have class name yet, take this one
(or prev-name
(setq prev-name def-name))
;; what level is the next definition on? must be same, deeper
;; or shallower indentation
(cond
;; at the same indent level, add it to the list...
((= start-indent cur-indent)
;; if we don't have push, use the following...
;;(setf index-alist (cons (cons def-name def-pos) index-alist))
(push (cons def-name def-pos) index-alist))
;; deeper indented expression, recur...
((< start-indent cur-indent)
;; the point is currently on the expression we're supposed to
;; start on, so go back to the last expression. The recursive
;; call will find this place again and add it to the correct
;; list
(re-search-backward imenu-example--python-generic-regexp
(point-min) 'move)
(setq sub-method-alist (imenu-example--create-python-index-engine
cur-indent))
(if sub-method-alist
;; we put the last element on the index-alist on the start
;; of the submethod alist so the user can still get to it.
(let ((save-elmt (pop index-alist)))
(push (cons (imenu-create-submenu-name prev-name)
(cons save-elmt sub-method-alist))
index-alist))))
;; found less indented expression, we're done.
(t
(setq looking-p nil)
(re-search-backward imenu-example--python-generic-regexp
(point-min) t)))
(setq prev-name def-name)
(and looking-p
(setq looking-p
(re-search-forward imenu-example--python-generic-regexp
(point-max) 'move))))
(nreverse index-alist)))
;;;###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\t\tindentation increment
py-block-comment-prefix\t\tcomment string used by comment-region
py-python-command\t\tshell command to invoke Python interpreter
py-scroll-process-buffer\t\talways scroll Python process buffer
py-temp-directory\t\tdirectory used for temp files (if needed)
py-beep-if-tab-change\t\tring the bell if tab-width is changed"
(interactive)
;; set up local variables
(kill-all-local-variables)
(make-local-variable 'font-lock-defaults)
(make-local-variable 'paragraph-separate)
(make-local-variable 'paragraph-start)
(make-local-variable 'require-final-newline)
(make-local-variable 'comment-start)
(make-local-variable 'comment-end)
(make-local-variable 'comment-start-skip)
(make-local-variable 'comment-column)
(make-local-variable 'indent-region-function)
(make-local-variable 'indent-line-function)
(make-local-variable 'add-log-current-defun-function)
;;
(set-syntax-table py-mode-syntax-table)
(setq major-mode 'python-mode
mode-name "Python"
local-abbrev-table python-mode-abbrev-table
paragraph-separate "^[ \t]*$"
paragraph-start "^[ \t]*$"
require-final-newline t
comment-start "# "
comment-end ""
comment-start-skip "# *"
comment-column 40
indent-region-function 'py-indent-region
indent-line-function 'py-indent-line
;; tell add-log.el how to find the current function/method/variable
add-log-current-defun-function 'py-current-defun
)
(use-local-map py-mode-map)
;; add the menu
(if py-menu
(easy-menu-add py-menu))
;; Emacs 19 requires this
(if (or py-this-is-lucid-emacs-p py-this-is-emacs-19-p)
(setq comment-multi-line nil))
;; 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))
;; install imenu
(setq imenu-create-index-function
(function imenu-example--create-python-index))
(if (fboundp 'imenu-add-to-menubar)
(imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
;; run the mode hook. py-mode-hook use is deprecated
(if python-mode-hook
(run-hooks 'python-mode-hook)
(run-hooks 'py-mode-hook)))
(defun py-keep-region-active ()
;; do whatever is necessary to keep the region active in XEmacs.
;; Ignore byte-compiler warnings you might see. Also note that
;; FSF's Emacs 19 does it differently and doesn't its policy doesn't
;; require us to take explicit action.
(and (boundp 'zmacs-region-stays)
(setq zmacs-region-stays t)))
;; electric characters
(defun py-outdent-p ()
;; returns non-nil if the current line should outdent one level
(save-excursion
(and (progn (back-to-indentation)
(looking-at py-outdent-re))
(progn (backward-to-indentation 1)
(while (or (looking-at py-blank-or-comment-re)
(bobp))
(backward-to-indentation 1))
(not (looking-at py-no-outdent-re)))
)))
(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.
Electric behavior is inhibited inside a string or comment."
(interactive "P")
(self-insert-command (prefix-numeric-value arg))
;; are we in a string or comment?
(if (save-excursion
(let ((pps (parse-partial-sexp (save-excursion
(beginning-of-python-def-or-class)
(point))
(point))))
(not (or (nth 3 pps) (nth 4 pps)))))
(save-excursion
(let ((here (point))
(outdent 0)
(indent (py-compute-indentation t)))
(if (and (not arg)
(py-outdent-p)
(= indent (save-excursion
(py-next-statement -1)
(py-compute-indentation t)))
)
(setq outdent py-indent-offset))
;; Don't indent, only outdent. This assumes that any lines that
;; are already outdented relative to py-compute-indentation were
;; put there on purpose. Its highly annoying to have `:' indent
;; for you. Use TAB, C-c C-l or C-c C-r to adjust. TBD: Is
;; there a better way to determine this???
(if (< (current-indentation) indent) nil
(goto-char here)
(beginning-of-line)
(delete-horizontal-space)
(indent-to (- indent outdent))
)))))
;;; Functions that execute Python commands in a subprocess
;;;###autoload
(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)
(require 'comint)
(switch-to-buffer-other-window (make-comint "Python" py-python-command))
(make-local-variable 'comint-prompt-regexp)
(setq comint-prompt-regexp "^>>> \\|^[.][.][.] ")
(set-process-filter (get-buffer-process (current-buffer)) 'py-process-filter)
(set-syntax-table py-mode-syntax-table)
(local-set-key [tab] 'self-insert-command))
(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 ...
(unwind-protect
;; make sure current buffer is restored
;; BAW - we want to check to see if this still applies
(progn
;; mysterious ugly hack
(if (eq curbuf pbuf)
(set-buffer (get-buffer-create "*scratch*")))
(set-buffer pbuf)
(let* ((start (point))
(goback (< start pmark))
(goend (and (not goback) (= start (point-max))))
(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)))))
(and goend
(progn (set-buffer pbuf)
(goto-char (point-max))))
))
(set-buffer curbuf))))
(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.