-
Notifications
You must be signed in to change notification settings - Fork 0
/
python-mode.el
3910 lines (3439 loc) · 144 KB
/
python-mode.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; python-mode.el --- Major mode for editing Python programs
;; Copyright (C) 1992,1993,1994 Tim Peters
;; Author: 2003-2004 http://sf.net/projects/python-mode
;; 1995-2002 Barry A. Warsaw
;; 1992-1994 Tim Peters
;; Maintainer: [email protected]
;; Created: Feb 1992
;; Keywords: python languages oop
(defconst py-version "$Revision: 4.75 $"
"`python-mode' version number.")
;; 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 and in 1995, Barry Warsaw inherited the mode. Tim's now back
;; but disavows all responsibility for the mode. In fact, we suspect he
;; doesn't even use Emacs any more. In 2003, python-mode.el was moved to its
;; own SourceForge project apart from the Python project, and now is
;; maintained by the volunteers at the [email protected] mailing list.
;; pdbtrack support contributed by Ken Manheimer, April 2001. Skip Montanaro
;; has also contributed significantly to python-mode's development.
;; Please use the SourceForge Python project to submit bugs or
;; patches:
;;
;; http://sourceforge.net/projects/python
;; INSTALLATION:
;; To install, just drop this file into a directory on your load-path and
;; byte-compile it. To set up Emacs to automatically edit files ending in
;; ".py" using python-mode add the following to your ~/.emacs file (GNU
;; Emacs) or ~/.xemacs/init.el file (XEmacs):
;; (setq auto-mode-alist (cons '("\\.py$" . python-mode) auto-mode-alist))
;; (setq interpreter-mode-alist (cons '("python" . python-mode)
;; interpreter-mode-alist))
;; (autoload 'python-mode "python-mode" "Python editing mode." t)
;;
;; In XEmacs syntax highlighting should be enabled automatically. In GNU
;; Emacs you may have to add these lines to your ~/.emacs file:
;; (global-font-lock-mode t)
;; (setq font-lock-maximum-decoration t)
;; FOR MORE INFORMATION:
;; There is some information on python-mode.el at
;; http://www.python.org/emacs/python-mode/
;;
;; It does contain links to other packages that you might find useful,
;; such as pdb interfaces, OO-Browser links, etc.
;; BUG REPORTING:
;; As mentioned above, please use the SourceForge Python project for
;; submitting bug reports or patches. The old recommendation, to use
;; C-c C-b will still work, but those reports have a higher chance of
;; getting buried in my mailbox. Please include a complete, but
;; concise code sample and a recipe for reproducing the bug. Send
;; suggestions and other comments to [email protected].
;; When in a Python mode buffer, do a C-h m for more help. It's
;; doubtful that a texinfo manual would be very useful, but if you
;; want to contribute one, I'll certainly accept it!
;;; Code:
(require 'comint)
(require 'custom)
(require 'cl)
(require 'compile)
(require 'ansi-color)
;; user definable variables
;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
(defgroup python nil
"Support for the Python programming language, <http://www.python.org/>"
:group 'languages
:prefix "py-")
(defcustom py-tab-always-indent t
"*Non-nil means TAB in Python mode should always reindent the current line,
regardless of where in the line point is when the TAB command is used."
:type 'boolean
:group 'python)
(defcustom py-python-command "python"
"*Shell command used to start Python interpreter."
:type 'string
:group 'python)
(make-obsolete-variable 'py-jpython-command 'py-jython-command)
(defcustom py-jython-command "jython"
"*Shell command used to start the Jython interpreter."
:type 'string
:group 'python
:tag "Jython Command")
(defcustom py-default-interpreter 'cpython
"*Which Python interpreter is used by default.
The value for this variable can be either `cpython' or `jython'.
When the value is `cpython', the variables `py-python-command' and
`py-python-command-args' are consulted to determine the interpreter
and arguments to use.
When the value is `jython', the variables `py-jython-command' and
`py-jython-command-args' are consulted to determine the interpreter
and arguments to use.
Note that this variable is consulted only the first time that a Python
mode buffer is visited during an Emacs session. After that, use
\\[py-toggle-shells] to change the interpreter shell."
:type '(choice (const :tag "Python (a.k.a. CPython)" cpython)
(const :tag "Jython" jython))
:group 'python)
(defcustom py-python-command-args '("-i")
"*List of string arguments to be used when starting a Python shell."
:type '(repeat string)
:group 'python)
(make-obsolete-variable 'py-jpython-command-args 'py-jython-command-args)
(defcustom py-jython-command-args '("-i")
"*List of string arguments to be used when starting a Jython shell."
:type '(repeat string)
:group 'python
:tag "Jython Command Args")
(defcustom py-indent-offset 4
"*Amount of offset per level of indentation.
`\\[py-guess-indent-offset]' can usually guess a good value when
you're editing someone else's Python code."
:type 'integer
:group 'python)
(defcustom py-continuation-offset 4
"*Additional amount of offset to give for some continuation lines.
Continuation lines are those that immediately follow a backslash
terminated line. Only those continuation lines for a block opening
statement are given this extra offset."
:type 'integer
:group 'python)
(defcustom py-smart-indentation t
"*Should `python-mode' try to automagically set some indentation variables?
When this variable is non-nil, two things happen when a buffer is set
to `python-mode':
1. `py-indent-offset' is guessed from existing code in the buffer.
Only guessed values between 2 and 8 are considered. If a valid
guess can't be made (perhaps because you are visiting a new
file), then the value in `py-indent-offset' is used.
2. `indent-tabs-mode' is turned off if `py-indent-offset' does not
equal `tab-width' (`indent-tabs-mode' is never turned on by
Python mode). This means that for newly written code, tabs are
only inserted in indentation if one tab is one indentation
level, otherwise only spaces are used.
Note that both these settings occur *after* `python-mode-hook' is run,
so if you want to defeat the automagic configuration, you must also
set `py-smart-indentation' to nil in your `python-mode-hook'."
:type 'boolean
:group 'python)
(defcustom py-align-multiline-strings-p t
"*Flag describing how multi-line 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."
:type '(choice (const :tag "Align under preceding line" t)
(const :tag "Align to column zero" nil))
:group 'python)
(defcustom 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). However, this string should not end in whitespace."
:type 'string
:group 'python)
(defcustom py-honor-comment-indentation t
"*Controls how comment lines influence subsequent indentation.
When nil, all comment lines are skipped for indentation purposes, and
if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
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 its
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 single `#' are used
as indentation hints, unless the comment character is in column zero."
:type '(choice
(const :tag "Skip all comment lines (fast)" nil)
(const :tag "Single # `sets' indentation for next line" t)
(const :tag "Single # `sets' indentation except at column zero"
other)
)
:group 'python)
(defcustom 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 "/var/tmp")
(funcall ok ".")
(error
"Couldn't find a usable temp directory -- set `py-temp-directory'")))
"*Directory used for temporary 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, /var/tmp, or the current directory."
:type 'string
:group 'python)
(defcustom 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."
:type 'boolean
:group 'python)
(defcustom py-jump-on-exception t
"*Jump to innermost exception frame in *Python Output* buffer.
When this variable is non-nil and an exception occurs when running
Python code synchronously in a subprocess, jump immediately to the
source code of the innermost traceback frame."
:type 'boolean
:group 'python)
(defcustom py-ask-about-save t
"If not nil, ask about which buffers to save before executing some code.
Otherwise, all modified buffers are saved without asking."
:type 'boolean
:group 'python)
(defcustom py-backspace-function 'backward-delete-char-untabify
"*Function called by `py-electric-backspace' when deleting backwards."
:type 'function
:group 'python)
(defcustom py-delete-function 'delete-char
"*Function called by `py-electric-delete' when deleting forwards."
:type 'function
:group 'python)
(defcustom py-imenu-show-method-args-p nil
"*Controls echoing of arguments of functions & methods in the Imenu buffer.
When non-nil, arguments are printed."
:type 'boolean
:group 'python)
(make-variable-buffer-local 'py-indent-offset)
(defcustom py-pdbtrack-do-tracking-p t
"*Controls whether the pdbtrack feature is enabled or not.
When non-nil, pdbtrack is enabled in all comint-based buffers,
e.g. shell buffers and the *Python* buffer. When using pdb to debug a
Python program, pdbtrack notices the pdb prompt and displays the
source file and line that the program is stopped at, much the same way
as gud-mode does for debugging C programs with gdb."
:type 'boolean
:group 'python)
(make-variable-buffer-local 'py-pdbtrack-do-tracking-p)
(defcustom py-pdbtrack-minor-mode-string " PDB"
"*String to use in the minor mode list when pdbtrack is enabled."
:type 'string
:group 'python)
(defcustom py-import-check-point-max
20000
"Maximum number of characters to search for a Java-ish import statement.
When `python-mode' tries to calculate the shell to use (either a
CPython or a Jython shell), it looks at the so-called `shebang' line
-- i.e. #! line. If that's not available, it looks at some of the
file heading imports to see if they look Java-like."
:type 'integer
:group 'python
)
(make-obsolete-variable 'py-jpython-packages 'py-jython-packages)
(defcustom py-jython-packages
'("java" "javax" "org" "com")
"Imported packages that imply `jython-mode'."
:type '(repeat string)
:group 'python)
;; Not customizable
(defvar py-master-file nil
"If non-nil, execute the named file instead of the buffer's file.
The intent is to allow you to set this variable in the file's local
variable section, e.g.:
# Local Variables:
# py-master-file: \"master.py\"
# End:
so that typing \\[py-execute-buffer] in that buffer executes the named
master file instead of the buffer's file. If the file name has a
relative path, the value of variable `default-directory' for the
buffer is prepended to come up with a file name.")
(make-variable-buffer-local 'py-master-file)
(defcustom py-pychecker-command "pychecker"
"*Shell command used to run Pychecker."
:type 'string
:group 'python
:tag "Pychecker Command")
(defcustom py-pychecker-command-args '("--stdlib")
"*List of string arguments to be passed to pychecker."
:type '(repeat string)
:group 'python
:tag "Pychecker Command Args")
(defvar py-shell-alist
'(("jython" . 'jython)
("python" . 'cpython))
"*Alist of interpreters and python shells. Used by `py-choose-shell'
to select the appropriate python interpreter mode for a file.")
(defcustom py-shell-input-prompt-1-regexp "^>>> "
"*A regular expression to match the input prompt of the shell."
:type 'string
:group 'python)
(defcustom py-shell-input-prompt-2-regexp "^[.][.][.] "
"*A regular expression to match the input prompt of the shell after the
first line of input."
:type 'string
:group 'python)
(defcustom py-shell-switch-buffers-on-execute t
"*Controls switching to the Python buffer where commands are
executed. When non-nil the buffer switches to the Python buffer, if
not no switching occurs."
:type 'boolean
:group 'python)
;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
(defvar py-line-number-offset 0
"When an exception occurs as a result of py-execute-region, a
subsequent py-up-exception needs the line number where the region
started, in order to jump to the correct file line. This variable is
set in py-execute-region and used in py-jump-to-exception.")
(defconst py-emacs-features
(let (features)
features)
"A list of features extant in the Emacs you are using.
There are many flavors of Emacs out there, with different levels of
support for features needed by `python-mode'.")
;; Face for None, True, False, self, and Ellipsis
(defvar py-pseudo-keyword-face 'py-pseudo-keyword-face
"Face for pseudo keywords in Python mode, like self, True, False, Ellipsis.")
(make-face 'py-pseudo-keyword-face)
;; PEP 318 decorators
(defvar py-decorators-face 'py-decorators-face
"Face method decorators.")
(make-face 'py-decorators-face)
;; Face for builtins
(defvar py-builtins-face 'py-builtins-face
"Face for builtins like TypeError, object, open, and exec.")
(make-face 'py-builtins-face)
(defun py-font-lock-mode-hook ()
(or (face-differs-from-default-p 'py-pseudo-keyword-face)
(copy-face 'font-lock-keyword-face 'py-pseudo-keyword-face))
(or (face-differs-from-default-p 'py-builtins-face)
(copy-face 'font-lock-keyword-face 'py-builtins-face))
(or (face-differs-from-default-p 'py-decorators-face)
(copy-face 'py-pseudo-keyword-face 'py-decorators-face))
)
(add-hook 'font-lock-mode-hook 'py-font-lock-mode-hook)
(defvar python-font-lock-keywords
(let ((kw1 (mapconcat 'identity
'("and" "assert" "break" "class"
"continue" "def" "del" "elif"
"else" "except" "exec" "for"
"from" "global" "if" "import"
"in" "is" "lambda" "not"
"or" "pass" "print" "raise"
"return" "while" "yield"
)
"\\|"))
(kw2 (mapconcat 'identity
'("else:" "except:" "finally:" "try:")
"\\|"))
(kw3 (mapconcat 'identity
;; Don't include True, False, None, or
;; Ellipsis in this list, since they are
;; already defined as pseudo keywords.
'("__debug__"
"__import__" "__name__" "abs" "apply" "basestring"
"bool" "buffer" "callable" "chr" "classmethod"
"cmp" "coerce" "compile" "complex" "copyright"
"delattr" "dict" "dir" "divmod"
"enumerate" "eval" "execfile" "exit" "file"
"filter" "float" "getattr" "globals" "hasattr"
"hash" "hex" "id" "input" "int" "intern"
"isinstance" "issubclass" "iter" "len" "license"
"list" "locals" "long" "map" "max" "min" "object"
"oct" "open" "ord" "pow" "property" "range"
"raw_input" "reduce" "reload" "repr" "round"
"setattr" "slice" "staticmethod" "str" "sum"
"super" "tuple" "type" "unichr" "unicode" "vars"
"xrange" "zip")
"\\|"))
(kw4 (mapconcat 'identity
;; Exceptions and warnings
'("ArithmeticError" "AssertionError"
"AttributeError" "DeprecationWarning" "EOFError"
"EnvironmentError" "Exception"
"FloatingPointError" "FutureWarning" "IOError"
"ImportError" "IndentationError" "IndexError"
"KeyError" "KeyboardInterrupt" "LookupError"
"MemoryError" "NameError" "NotImplemented"
"NotImplementedError" "OSError" "OverflowError"
"OverflowWarning" "PendingDeprecationWarning"
"ReferenceError" "RuntimeError" "RuntimeWarning"
"StandardError" "StopIteration" "SyntaxError"
"SyntaxWarning" "SystemError" "SystemExit"
"TabError" "TypeError" "UnboundLocalError"
"UnicodeDecodeError" "UnicodeEncodeError"
"UnicodeError" "UnicodeTranslateError"
"UserWarning" "ValueError" "Warning"
"ZeroDivisionError")
"\\|"))
)
(list
'("^[ \t]*\\(@.+\\)" 1 'py-decorators-face)
;; keywords
(cons (concat "\\<\\(" kw1 "\\)\\>[ \n\t(]") 1)
;; builtins when they don't appear as object attributes
(list (concat "\\([^. \t]\\|^\\)[ \t]*\\<\\(" kw3 "\\)\\>[ \n\t(]") 2
'py-builtins-face)
;; block introducing keywords with immediately following colons.
;; Yes "except" is in both lists.
(cons (concat "\\<\\(" kw2 "\\)[ \n\t(]") 1)
;; Exceptions
(list (concat "\\<\\(" kw4 "\\)[ \n\t:,(]") 1 'py-builtins-face)
;; `as' but only in "import foo as bar"
'("[ \t]*\\(\\<from\\>.*\\)?\\<import\\>.*\\<\\(as\\)\\>" . 2)
;; classes
'("\\<class[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)" 1 font-lock-type-face)
;; functions
'("\\<def[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
1 font-lock-function-name-face)
;; pseudo-keywords
'("\\<\\(self\\|None\\|True\\|False\\|Ellipsis\\)\\>"
1 py-pseudo-keyword-face)
))
"Additional expressions to highlight in Python mode.")
(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
;; 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.")
(defvar py-pdbtrack-is-tracking-p nil)
(defvar py-pychecker-history nil)
;; Constants
(defconst py-stringlit-re
(concat
;; These fail if backslash-quote ends the string (not worth
;; fixing?). They precede the short versions so that the first two
;; quotes don't look like an empty short string.
;;
;; (maybe raw), long single quoted triple quoted strings (SQTQ),
;; with potential embedded single quotes
"[rR]?'''[^']*\\(\\('[^']\\|''[^']\\)[^']*\\)*'''"
"\\|"
;; (maybe raw), long double quoted triple quoted strings (DQTQ),
;; with potential embedded double quotes
"[rR]?\"\"\"[^\"]*\\(\\(\"[^\"]\\|\"\"[^\"]\\)[^\"]*\\)*\"\"\""
"\\|"
"[rR]?'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
"\\|" ; or
"[rR]?\"\\([^\"\n\\]\\|\\\\.\\)*\"" ; double-quoted
)
"Regular expression matching a Python string literal.")
(defconst py-continued-re
;; This is tricky because a trailing backslash does not mean
;; continuation if it's in a comment
(concat
"\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
"\\\\$")
"Regular expression matching Python backslash continuation lines.")
(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
"Regular expression matching a blank or comment line.")
(defconst py-outdent-re
(concat "\\(" (mapconcat 'identity
'("else:"
"except\\(\\s +.*\\)?:"
"finally:"
"elif\\s +.*:")
"\\|")
"\\)")
"Regular expression matching statements to be dedented one level.")
(defconst py-block-closing-keywords-re
"\\(return\\|raise\\|break\\|continue\\|pass\\)"
"Regular expression matching keywords which typically close a block.")
(defconst py-no-outdent-re
(concat
"\\("
(mapconcat 'identity
(list "try:"
"except\\(\\s +.*\\)?:"
"while\\s +.*:"
"for\\s +.*:"
"if\\s +.*:"
"elif\\s +.*:"
(concat py-block-closing-keywords-re "[ \t\n]")
)
"\\|")
"\\)")
"Regular expression matching lines not to dedent after.")
(defvar py-traceback-line-re
"[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)"
"Regular expression that describes tracebacks.")
;; pdbtrack constants
(defconst py-pdbtrack-stack-entry-regexp
; "^> \\([^(]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_]+\\)()"
"^> \\(.*\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_]+\\)()"
"Regular expression pdbtrack uses to find a stack trace entry.")
(defconst py-pdbtrack-input-prompt "\n[(<]*[Pp]db[>)]+ "
"Regular expression pdbtrack uses to recognize a pdb prompt.")
(defconst py-pdbtrack-track-range 10000
"Max number of characters from end of buffer to search for stack entry.")
;; Major mode boilerplate
;; 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'.")
(make-obsolete-variable 'jpython-mode-hook 'jython-mode-hook)
(defvar jython-mode-hook nil
"*Hook called by `jython-mode'. `jython-mode' also calls
`python-mode-hook'.")
(defvar py-shell-hook nil
"*Hook called by `py-shell'.")
;; 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
nil
(setq py-mode-map (make-sparse-keymap))
;; electric keys
(define-key py-mode-map ":" 'py-electric-colon)
;; indentation level modifiers
(define-key py-mode-map "\C-c\C-l" 'py-shift-region-left)
(define-key py-mode-map "\C-c\C-r" 'py-shift-region-right)
(define-key py-mode-map "\C-c<" 'py-shift-region-left)
(define-key py-mode-map "\C-c>" 'py-shift-region-right)
;; subprocess commands
(define-key py-mode-map "\C-c\C-c" 'py-execute-buffer)
(define-key py-mode-map "\C-c\C-m" 'py-execute-import-or-reload)
(define-key py-mode-map "\C-c\C-s" 'py-execute-string)
(define-key py-mode-map "\C-c|" 'py-execute-region)
(define-key py-mode-map "\e\C-x" 'py-execute-def-or-class)
(define-key py-mode-map "\C-c!" 'py-shell)
(define-key py-mode-map "\C-c\C-t" 'py-toggle-shells)
;; Caution! Enter here at your own risk. We are trying to support
;; several behaviors and it gets disgusting. :-( This logic ripped
;; largely from CC Mode.
;;
;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
;; backwards deletion behavior to DEL, which both Delete and
;; Backspace get translated to. There's no way to separate this
;; behavior in a clean way, so deal with it! Besides, it's been
;; this way since the dawn of time.
(if (not (boundp 'delete-key-deletes-forward))
(define-key py-mode-map "\177" 'py-electric-backspace)
;; However, XEmacs 20 actually achieved enlightenment. It is
;; possible to sanely define both backward and forward deletion
;; behavior under X separately (TTYs are forever beyond hope, but
;; who cares? XEmacs 20 does the right thing with these too).
(define-key py-mode-map [delete] 'py-electric-delete)
(define-key py-mode-map [backspace] 'py-electric-backspace))
;; Separate M-BS from C-M-h. The former should remain
;; backward-kill-word.
(define-key py-mode-map [(control meta h)] 'py-mark-def-or-class)
(define-key py-mode-map "\C-c\C-k" 'py-mark-block)
;; Miscellaneous
(define-key py-mode-map "\C-c:" 'py-guess-indent-offset)
(define-key py-mode-map "\C-c\t" 'py-indent-region)
(define-key py-mode-map "\C-c\C-d" 'py-pdbtrack-toggle-stack-tracking)
(define-key py-mode-map "\C-c\C-n" 'py-next-statement)
(define-key py-mode-map "\C-c\C-p" 'py-previous-statement)
(define-key py-mode-map "\C-c\C-u" 'py-goto-block-up)
(define-key py-mode-map "\C-c#" 'py-comment-region)
(define-key py-mode-map "\C-c?" 'py-describe-mode)
(define-key py-mode-map "\C-c\C-h" 'py-help-at-point)
(define-key py-mode-map "\e\C-a" 'py-beginning-of-def-or-class)
(define-key py-mode-map "\e\C-e" 'py-end-of-def-or-class)
(define-key py-mode-map "\C-c-" 'py-up-exception)
(define-key py-mode-map "\C-c=" 'py-down-exception)
;; stuff that is `standard' but doesn't interface well with
;; python-mode, which forces us to rebind to special commands
(define-key py-mode-map "\C-xnd" 'py-narrow-to-defun)
;; information
(define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
(define-key py-mode-map "\C-c\C-v" 'py-version)
(define-key py-mode-map "\C-c\C-w" 'py-pychecker-run)
;; 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 #'(lambda (key)
(define-key py-mode-map key 'py-newline-and-indent))
(where-is-internal 'newline-and-indent))
;; Force RET to be py-newline-and-indent even if it didn't get
;; mapped by the above code. motivation: Emacs' default binding for
;; RET is `newline' and C-j is `newline-and-indent'. Most Pythoneers
;; expect RET to do a `py-newline-and-indent' and any Emacsers who
;; dislike this are probably knowledgeable enough to do a rebind.
;; However, we do *not* change C-j since many Emacsers have already
;; swapped RET and C-j and they don't want C-j bound to `newline' to
;; change.
(define-key py-mode-map "\C-m" 'py-newline-and-indent)
)
(defvar py-mode-output-map nil
"Keymap used in *Python Output* buffers.")
(if py-mode-output-map
nil
(setq py-mode-output-map (make-sparse-keymap))
(define-key py-mode-output-map [button2] 'py-mouseto-exception)
(define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
;; TBD: Disable all self-inserting keys. This is bogus, we should
;; really implement this as *Python Output* buffer being read-only
(mapcar #' (lambda (key)
(define-key py-mode-output-map key
#'(lambda () (interactive) (beep))))
(where-is-internal 'self-insert-command))
)
(defvar py-shell-map nil
"Keymap used in *Python* shell buffers.")
(if py-shell-map
nil
(setq py-shell-map (copy-keymap comint-mode-map))
(define-key py-shell-map [tab] 'tab-to-tab-stop)
(define-key py-shell-map "\C-c-" 'py-up-exception)
(define-key py-shell-map "\C-c=" 'py-down-exception)
)
(defvar py-mode-syntax-table nil
"Syntax table used in `python-mode' buffers.")
(when (not py-mode-syntax-table)
(setq py-mode-syntax-table (make-syntax-table))
(modify-syntax-entry ?\( "()" py-mode-syntax-table)
(modify-syntax-entry ?\) ")(" py-mode-syntax-table)
(modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
(modify-syntax-entry ?\] ")[" py-mode-syntax-table)
(modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
(modify-syntax-entry ?\} "){" py-mode-syntax-table)
;; Add operator symbols misassigned in the std table
(modify-syntax-entry ?\$ "." py-mode-syntax-table)
(modify-syntax-entry ?\% "." py-mode-syntax-table)
(modify-syntax-entry ?\& "." py-mode-syntax-table)
(modify-syntax-entry ?\* "." py-mode-syntax-table)
(modify-syntax-entry ?\+ "." py-mode-syntax-table)
(modify-syntax-entry ?\- "." py-mode-syntax-table)
(modify-syntax-entry ?\/ "." py-mode-syntax-table)
(modify-syntax-entry ?\< "." py-mode-syntax-table)
(modify-syntax-entry ?\= "." py-mode-syntax-table)
(modify-syntax-entry ?\> "." py-mode-syntax-table)
(modify-syntax-entry ?\| "." py-mode-syntax-table)
;; For historical reasons, underscore is word class instead of
;; symbol class. GNU conventions say it should be symbol class, but
;; there's a natural conflict between what major mode authors want
;; and what users expect from `forward-word' and `backward-word'.
;; Guido and I have hashed this out and have decided to keep
;; underscore in word class. 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. This doesn't help in all
;; situations where you'd want the different behavior
;; (e.g. backward-kill-word).
(modify-syntax-entry ?\_ "w" py-mode-syntax-table)
;; Both single quote and double quote are string delimiters
(modify-syntax-entry ?\' "\"" py-mode-syntax-table)
(modify-syntax-entry ?\" "\"" py-mode-syntax-table)
;; backquote is open and close paren
(modify-syntax-entry ?\` "$" py-mode-syntax-table)
;; comment delimiters
(modify-syntax-entry ?\# "<" py-mode-syntax-table)
(modify-syntax-entry ?\n ">" py-mode-syntax-table)
)
;; An auxiliary syntax table which places underscore and dot in the
;; symbol class for simplicity
(defvar py-dotted-expression-syntax-table nil
"Syntax table used to identify Python dotted expressions.")
(when (not py-dotted-expression-syntax-table)
(setq py-dotted-expression-syntax-table
(copy-syntax-table py-mode-syntax-table))
(modify-syntax-entry ?_ "_" py-dotted-expression-syntax-table)
(modify-syntax-entry ?. "_" py-dotted-expression-syntax-table))
;; Utilities
(defmacro py-safe (&rest body)
"Safely execute BODY, return nil if an error occurred."
(` (condition-case nil
(progn (,@ body))
(error nil))))
(defsubst py-keep-region-active ()
"Keep the region active in XEmacs."
;; Ignore byte-compiler warnings you might see. Also note that
;; FSF's Emacs 19 does it differently; its policy doesn't require us
;; to take explicit action.
(and (boundp 'zmacs-region-stays)
(setq zmacs-region-stays t)))
(defsubst py-point (position)
"Returns the value of point at certain commonly referenced POSITIONs.
POSITION can be one of the following symbols:
bol -- beginning of line
eol -- end of line
bod -- beginning of def or class
eod -- end of def or class
bob -- beginning of buffer
eob -- end of buffer
boi -- back to indentation
bos -- beginning of statement
This function does not modify point or mark."
(let ((here (point)))
(cond
((eq position 'bol) (beginning-of-line))
((eq position 'eol) (end-of-line))
((eq position 'bod) (py-beginning-of-def-or-class 'either))
((eq position 'eod) (py-end-of-def-or-class 'either))
;; Kind of funny, I know, but useful for py-up-exception.
((eq position 'bob) (beginning-of-buffer))
((eq position 'eob) (end-of-buffer))
((eq position 'boi) (back-to-indentation))
((eq position 'bos) (py-goto-initial-line))
(t (error "Unknown buffer position requested: %s" position))
)
(prog1
(point)
(goto-char here))))
(defsubst py-highlight-line (from to file line)
(cond
((fboundp 'make-extent)
;; XEmacs
(let ((e (make-extent from to)))
(set-extent-property e 'mouse-face 'highlight)
(set-extent-property e 'py-exc-info (cons file line))
(set-extent-property e 'keymap py-mode-output-map)))
(t
;; Emacs -- Please port this!
)
))
(defun py-in-literal (&optional lim)
"Return non-nil if point is in a Python literal (a comment or string).
Optional argument LIM indicates the beginning of the containing form,
i.e. the limit on how far back to scan."
;; This is the version used for non-XEmacs, which has a nicer
;; interface.
;;
;; WARNING: Watch out for infinite recursion.
(let* ((lim (or lim (py-point 'bod)))
(state (parse-partial-sexp lim (point))))
(cond
((nth 3 state) 'string)
((nth 4 state) 'comment)
(t nil))))
;; XEmacs has a built-in function that should make this much quicker.
;; In this case, lim is ignored
(defun py-fast-in-literal (&optional lim)
"Fast version of `py-in-literal', used only by XEmacs.
Optional LIM is ignored."
;; don't have to worry about context == 'block-comment
(buffer-syntactic-context))
(if (fboundp 'buffer-syntactic-context)
(defalias 'py-in-literal 'py-fast-in-literal))
;; 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 X/Emacs releases contain this package.")
(and (py-safe (require 'easymenu) t)
(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" py-mark-def-or-class t]
["Mark current class" (py-mark-def-or-class t) t]
"-"
["Shift region left" py-shift-region-left (mark)]
["Shift region right" py-shift-region-right (mark)]
"-"
["Import/reload file" py-execute-import-or-reload t]
["Execute buffer" py-execute-buffer t]
["Execute region" py-execute-region (mark)]
["Execute def or class" py-execute-def-or-class (mark)]
["Execute string" py-execute-string t]
["Start interpreter..." py-shell t]
"-"
["Go to start of block" py-goto-block-up t]
["Go to start of class" (py-beginning-of-def-or-class t) t]
["Move to end of class" (py-end-of-def-or-class t) t]
["Move to start of def" py-beginning-of-def-or-class t]
["Move to end of def" py-end-of-def-or-class t]
"-"
["Describe mode" py-describe-mode t]
)))
;; Imenu definitions
(defvar py-imenu-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 py-imenu-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.()\"'#]*\\))"
"[ \t]*(\\([^:#]*\\))"
"\\)" ; end of def
"[ \t]*:" ; and then the :
"\\)" ; >>methods and functions<<
)
"Regexp for Python methods/functions for use with the Imenu package."
)
(defvar py-imenu-method-no-arg-parens '(2 8)
"Indices 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 `py-imenu-show-method-args-p' for more
information.")
(defvar py-imenu-method-arg-parens '(2 7)
"Indices 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 `py-imenu-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 py-imenu-generic-expression
(cons
(concat
py-imenu-class-regexp
"\\|" ; or...
py-imenu-method-regexp
)
py-imenu-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 \\[py-imenu-create-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 py-imenu-generic-regexp nil)
(defvar py-imenu-generic-parens nil)
(defun py-imenu-create-index-function ()
"Python interface function for the Imenu package.
Finds all Python classes and functions/methods. Calls function
\\[py-imenu-create-index-engine]. See that function for the details
of how this works."
(setq py-imenu-generic-regexp (car py-imenu-generic-expression)
py-imenu-generic-parens (if py-imenu-show-method-args-p
py-imenu-method-arg-parens
py-imenu-method-no-arg-parens))
(goto-char (point-min))
;; Warning: When the buffer has no classes or functions, this will
;; return nil, which seems proper according to the Imenu API, but
;; causes an error in the XEmacs port of Imenu. Sigh.
(py-imenu-create-index-engine nil))
(defun py-imenu-create-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 \\[py-imenu-create-index-function].