-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpython-mode.el
5478 lines (4907 loc) · 213 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-2011 https://launchpad.net/python-mode
;; 1995-2002 Barry A. Warsaw
;; 1992-1994 Tim Peters
;; Maintainer: [email protected]
;; Created: Feb 1992
;; Keywords: python languages oop
(defconst py-version "6.0.2"
"`python-mode' version number.")
;; This file is part of python-mode.el.
;;
;; python-mode.el is free software: you can redistribute it and/or modify it
;; under the terms of the GNU General Public License as published by the Free
;; Software Foundation, either version 3 of the License, or (at your option)
;; any later version.
;;
;; python-mode.el is distributed in the hope that it will be useful, but
;; WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
;; for more details.
;;
;; You should have received a copy of the GNU General Public License along
;; with python-mode.el. If not, see <http://www.gnu.org/licenses/>.
;;; 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 came back
;; but disavowed all responsibility for the mode. In fact, we suspect he
;; doesn't even use Emacs any more <wink>. In 2003, python-mode.el was moved
;; to its own SourceForge project apart from the Python project, and in 2008
;; it was moved to Launchpad for all project administration. python-mode.el
;; is maintained by the volunteers at the [email protected] mailing
;; list.
;; python-mode.el is different than, and pre-dates by many years, the
;; python.el that comes with FSF Emacs. We'd like to merge the two modes but
;; have few cycles to do so. Volunteers are welcome.
;; pdbtrack support contributed by Ken Manheimer, April 2001. Skip Montanaro
;; has also contributed significantly to python-mode's development.
;; Please use Launchpad to submit bugs or patches:
;;
;; https://launchpad.net/python-mode
;; 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 to your emacs init file
;;
;; GNU Emacs: ~/.emacs, ~/.emacs.el, or ~/.emacs.d/init.el
;;
;; XEmacs: ~/.xemacs/init.el
;;
;; the following code:
;;
;; (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 init file:
;;
;; (global-font-lock-mode t)
;; (setq font-lock-maximum-decoration t)
;; BUG REPORTING:
;; As mentioned above, please use the Launchpad python-mode 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 our inboxes. Please include a complete, but concise code sample and a
;; recipe for reproducing the bug. Send suggestions and other comments to
;; 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,
;; we'll certainly accept it!
;;; ToDo
;; Question calls of `py-guess-indent-offset', as
;; required indent may change throughout the buffer.
;; Rather may it be called by argument
;;; Code:
(require 'comint)
(require 'custom)
(require 'compile)
(require 'ansi-color)
(when (featurep 'xemacs)
(require 'highlight-indentation))
(eval-when-compile (require 'cl))
;; 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-electric-comment-p t
"If \"#\" should call `py-electric-comment'. Default is `t'. "
:type 'boolean
:group 'python)
(defcustom py-electric-comment-add-space-p nil
"If py-electric-comment should add a space. Default is `nil'. "
:type 'boolean
:group 'python)
(defcustom py-indent-honors-multiline-listing nil
"If `t', indents to 1+ column of opening delimiter. If `nil', indent adds one level to the beginning of statement. Default is `nil'. "
:type 'boolean
:group 'python)
(defcustom py-closing-list-dedents-bos nil
"If non-nil, closing parentesis dedents onto column of statement, otherwise keeps additional `py-indent-offset', default is nil "
:type 'boolean
:group 'python)
;; Execute stuff start
(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 nil)
(defcustom py-jython-command "jython"
"*Shell command used to start the Jython interpreter."
:type 'string
:group 'python
:tag "Jython Command")
(defcustom py-encoding-string " # -*- coding: utf-8 -*-"
"Default string specifying encoding in the heading of file. "
:type 'string
:group 'python)
(defcustom py-shebang-startstring "#! /bin/env"
"Detecting the shell in head of file. "
:type 'string
:group 'python)
(defcustom py-shebang-regexp "#![ \t]?\\([^ \t\n]*[ \t]\\)?[^ \t\n]*\\([pj]ython[^ \t\n]*\\)"
"Detecting the shell in head of file. "
:type 'regexp
:group 'python)
(defcustom py-default-interpreter "python"
"*Which Python interpreter is used by default.
The value for this variable can be any installed Python'.
When the value containes `python', the variables `py-python-command' and
`py-python-command-args' are consulted to determine the interpreter
and arguments to use.
When the value containes `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 'string
: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-variable-buffer-local 'py-python-command-args)
(set-default 'py-python-command-args '("-i"))
(make-obsolete-variable 'py-jpython-command-args 'py-jython-command-args nil)
(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-cleanup-temporary nil
"If temporary buffers and files used by functions executing region should be deleted afterwards. "
:type 'boolean
:group 'python
)
;; Execute stuff end
;; Output stuff start
(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)
(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)
(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)
(make-variable-buffer-local 'py-indent-offset)
(defcustom py-backslashed-continuation-indent 2
"Indent of continuation-lines realised by backslashes. "
:type 'integer
:group 'python)
(make-variable-buffer-local 'py-indent-in-delimiter)
(defcustom py-lhs-inbound-indent 1
"When line starts a multiline-assignement: How many colums indent should be more than opening bracket, brace or parenthesis. "
:type 'integer
:group 'python)
(make-variable-buffer-local 'py-lhs-inbound-indent)
(defcustom py-rhs-inbound-indent 1
"When inside a multiline-assignement: How many colums indent should be more than opening bracket, brace or parenthesis. "
:type 'integer
:group 'python)
(make-variable-buffer-local 'py-rhs-inbound-indent)
(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. "
: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-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-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 nil)
(defcustom py-jython-packages
'("java" "javax")
"Imported packages that imply `jython-mode'."
:type '(repeat string)
:group 'python)
(defcustom py-current-defun-show t
"If `py-current-defun' should jump to the definition, highlight it while waiting PY-WHICH-FUNC-DELAY seconds, before returning to previous position.
Default is `t'."
:type 'boolean
:group 'python)
(defcustom py-current-defun-delay 2
"When called interactively, `py-current-defun' should wait PY-WHICH-FUNC-DELAY seconds at the definition name found, before returning to previous position. "
:type 'number
:group 'python)
(defcustom py-send-receive-delay 5
"Seconds to wait for output, used by `python-send-receive'. "
:type 'number
:group 'python)
;; Not customizable
(defvar py-exec-command nil
"Mode commands will set this. ")
(make-variable-buffer-local 'py-exec-command)
(defcustom py-master-file nil
"If non-nil, \\[py-execute-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.
Beside you may set this variable in the file's local
variable section, e.g.:
# Local Variables:
# py-master-file: \"master.py\"
# End:
"
:type 'string
:group 'python)
(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")
(defcustom py-hide-show-keywords
'(
"class" "def" "elif" "else" "except"
"for" "if" "while" "finally" "try"
"with"
)
"*Keywords that can be hidden by hide-show"
:type '(repeat string)
:group 'python)
(defcustom py-hide-show-hide-docstrings t
"*Controls if doc strings can be hidden by hide-show"
:type 'boolean
:group 'python)
(defcustom py-mark-decorators nil
"If py-mark-def-or-class functions should mark decorators too. Default is `nil'. "
:type 'boolean
:group 'python)
;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
(defvar py-expression-skip-regexp "^ =:#\t\r\n\f"
"py-expression assumes chars indicated possible composing a py-expression, skip it. ")
;; (setq py-expression-skip-regexp "^ =:#\t\r\n\f")
(defvar py-expression-looking-regexp "[^ =:#\t\r\n\f)]"
"py-expression assumes chars indicated possible composing a py-expression, when looking-at or -back. ")
;; (setq py-expression-looking-regexp "[^ =:#\t\r\n\f)]")
(defvar py-not-expression-regexp "[ .=:#\t\r\n\f)]"
"py-expression assumes chars indicated probably will not compose a py-expression. ")
;; (setq py-not-expression-regexp "[ .=:#\t\r\n\f)]")
(defvar py-minor-expression-skip-regexp "^ .()[]{}=:#\t\r\n\f"
"py-minor-expression assumes chars indicated possible composing a py-minor-expression, skip it. ")
;; (setq py-minor-expression-skip-regexp "^ .(){}=:#\t\r\n\f")
(defvar py-minor-expression-forward-regexp "^ .)}=:#\t\r\n\f"
"py-minor-expression assumes chars indicated possible composing a py-minor-expression, skip it. ")
(defvar py-minor-expression-backward-regexp "^ .({=:#\t\r\n\f"
"py-minor-expression assumes chars indicated possible composing a py-minor-expression, skip it. ")
(defvar py-not-minor-expression-skip-regexp " \\.=:#\t\r\n\f"
"py-minor-expression assumes chars indicated may not compose a py-minor-expression, skip it. ")
(defvar py-minor-expression-looking-regexp "[^ .=:#\t\r\n\f)]"
"py-minor-expression assumes chars indicated possible composing a py-minor-expression, when looking-at or -back. ")
;; (setq py-minor-expression-looking-regexp "[^ .=:#\t\r\n\f)]")
(defvar py-not-minor-expression-regexp "[ .=:#\t\r\n\f)]"
"py-minor-expression assumes chars indicated probably will not compose a py-minor-expression. ")
;; (setq py-not-minor-expression-regexp "[ .=:#\t\r\n\f)]")
(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.")
;; Skip's XE workaround
(unless (functionp 'string-to-syntax)
(defun string-to-syntax (s)
(cond
((equal s "|") '(15))
((equal s "_") '(3))
(t (error "Unhandled string: %s" s))))
)
;; GNU's syntax-ppss-context
(unless (functionp 'syntax-ppss-context)
(defsubst syntax-ppss-context (ppss)
(cond
((nth 3 ppss) 'string)
((nth 4 ppss) 'comment)
(t nil))))
(defvar empty-line-p-chars "^[ \t\r\f]*$"
"Empty-line-p-chars.")
;;;###autoload
(defun empty-line-p (&optional iact)
"Returns t if cursor is at an empty line, nil otherwise."
(interactive "p")
(save-excursion
(let ((erg (progn
(beginning-of-line)
(looking-at empty-line-p-chars))))
(when iact
(message "%s" erg))
erg)))
(defconst py-font-lock-syntactic-keywords
'(("[^\\]\\\\\\(?:\\\\\\\\\\)*\\(\\s\"\\)\\1\\(\\1\\)"
(2
(7)))
("\\([RUBrub]?\\)[Rr]?\\(\\s\"\\)\\2\\(\\2\\)"
(1
(python-quote-syntax 1))
(2
(python-quote-syntax 2))
(3
(python-quote-syntax 3)))))
(defun python-quote-syntax (n)
"Put `syntax-table' property correctly on triple quote.
Used for syntactic keywords. N is the match number (1, 2 or 3)."
;; Given a triple quote, we have to check the context to know
;; whether this is an opening or closing triple or whether it's
;; quoted anyhow, and should be ignored. (For that we need to do
;; the same job as `syntax-ppss' to be correct and it seems to be OK
;; to use it here despite initial worries.) We also have to sort
;; out a possible prefix -- well, we don't _have_ to, but I think it
;; should be treated as part of the string.
;; Test cases:
;; ur"""ar""" x='"' # """
;; x = ''' """ ' a
;; '''
;; x '"""' x """ \"""" x
(save-excursion
(goto-char (match-beginning 0))
(cond
;; Consider property for the last char if in a fenced string.
((= n 3)
(let* ((font-lock-syntactic-keywords nil)
(syntax (if (featurep 'xemacs)
(parse-partial-sexp (point-min) (point))
(syntax-ppss))))
(when (eq t (nth 3 syntax)) ; after unclosed fence
(goto-char (nth 8 syntax)) ; fence position
(skip-chars-forward "uUrRbB") ; skip any prefix
;; Is it a matching sequence?
(if (eq (char-after) (char-after (match-beginning 2)))
(eval-when-compile (string-to-syntax "|"))))))
;; Consider property for initial char, accounting for prefixes.
((or (and (= n 2) ; leading quote (not prefix)
(= (match-beginning 1) (match-end 1))) ; prefix is null
(and (= n 1) ; prefix
(/= (match-beginning 1) (match-end 1)))) ; non-empty
(let ((font-lock-syntactic-keywords nil))
(unless (eq 'string (syntax-ppss-context (if (featurep 'xemacs)
(parse-partial-sexp (point-min) (point))
(syntax-ppss))))
;; (eval-when-compile (string-to-syntax "|"))
(eval-when-compile (string-to-syntax "|")))))
;; Otherwise (we're in a non-matching string) the property is
;; nil, which is OK.
)))
(defvar py-mode-syntax-table nil)
(setq py-mode-syntax-table
(let ((table (make-syntax-table))
(tablelookup (if (featurep 'xemacs)
'get-char-table
'aref)))
;; Give punctuation syntax to ASCII that normally has symbol
;; syntax or has word syntax and isn't a letter.
(if (featurep 'xemacs)
(setq table (standard-syntax-table))
(let ((symbol (string-to-syntax "_"))
;; (symbol (string-to-syntax "_"))
(sst (standard-syntax-table)))
(dotimes (i 128)
(unless (= i ?_)
(if (equal symbol (funcall tablelookup sst i))
(modify-syntax-entry i "." table))))))
(modify-syntax-entry ?$ "." table)
(modify-syntax-entry ?% "." table)
;; exceptions
(modify-syntax-entry ?# "<" table)
(modify-syntax-entry ?\n ">" table)
(modify-syntax-entry ?' "\"" table)
(modify-syntax-entry ?` "$" table)
(modify-syntax-entry ?\_ "w" table)
table))
(defconst python-space-backslash-table
(let ((table (copy-syntax-table py-mode-syntax-table)))
(modify-syntax-entry ?\\ " " table)
table)
"`python-mode-syntax-table' with backslash given whitespace syntax.")
(defface py-variable-name-face
'((t (:inherit font-lock-variable-name-face)))
"Face method decorators."
:group 'python)
(defvar py-variable-name-face 'py-variable-name-face)
;; ;; Face for None, True, False, self, and Ellipsis
(defface py-pseudo-keyword-face
'((t (:inherit font-lock-keyword-face)))
"Face for pseudo keywords in Python mode, like self, True, False, Ellipsis."
:group 'python)
(defvar py-pseudo-keyword-face 'py-pseudo-keyword-face)
(defface py-XXX-tag-face
'((t (:inherit font-lock-string-face)))
"XXX\\|TODO\\|FIXME "
:group 'python)
(defvar py-XXX-tag-face 'py-XXX-tag-face)
;; PEP 318 decorators
(defface py-decorators-face
'((t (:inherit font-lock-keyword-face)))
"Face method decorators."
:group 'python)
(defvar py-decorators-face 'py-decorators-face)
;; Face for builtins
(defface py-builtins-face
'((t (:inherit font-lock-builtin-face)))
"Face for builtins like TypeError, object, open, and exec."
:group 'python)
(defvar py-builtins-face 'py-builtins-face)
(defface py-class-name-face
'((t (:inherit font-lock-type-face)))
"Face for builtins like TypeError, object, open, and exec."
:group 'python)
(defvar py-class-name-face 'py-class-name-face)
;; XXX, TODO, and FIXME comments and such
(defface py-exception-name-face
'((t (:inherit font-lock-builtin-face)))
"."
:group 'python)
(defvar py-exception-name-face 'py-exception-name-face)
(defvar py-font-lock-keywords
(let ((kw1 (mapconcat 'identity
'("and" "assert" "break" "class"
"continue" "def" "del" "elif"
"else" "except" "for" "from"
"global" "if" "import" "in"
"is" "lambda" "not" "or"
"pass" "raise" "as" "return"
"while" "with" "yield"
)
"\\|"))
(kw2 (mapconcat 'identity
'("else:" "except:" "finally:" "try:" "lambda:")
"\\|"))
(kw3 (mapconcat 'identity
;; Don't include Ellipsis in this list, since it is already defined as a pseudo keyword.
'("_" "__debug__" "__doc__" "__import__" "__name__" "__package__"
"abs" "all" "any" "apply"
"basestring" "bin" "bool" "buffer" "bytearray"
"callable" "chr" "classmethod" "cmp" "coerce"
"compile" "complex" "copyright" "credits"
"delattr" "dict" "dir" "divmod" "enumerate" "eval"
"exec" "execfile" "exit" "file" "filter" "float"
"format" "getattr" "globals" "hasattr" "hash" "help"
"hex" "id" "input" "int" "intern" "isinstance"
"issubclass" "iter" "len" "license" "list" "locals"
"long" "map" "max" "memoryview" "min" "next"
"object" "oct" "open" "ord" "pow" "print" "property"
"quit" "range" "raw_input" "reduce" "reload" "repr"
"round" "set" "setattr" "slice" "sorted"
"staticmethod" "str" "sum" "super" "tuple" "type"
"unichr" "unicode" "vars" "xrange" "zip"
"bin" "bytearray" "bytes" "format"
"memoryview" "next" "print")
"\\|"))
(kw4 (mapconcat 'identity
;; Exceptions and warnings
'("ArithmeticError" "AssertionError"
"AttributeError" "BaseException" "BufferError"
"BytesWarning" "DeprecationWarning" "EOFError"
"EnvironmentError" "Exception"
"FloatingPointError" "FutureWarning" "GeneratorExit"
"IOError" "ImportError" "ImportWarning"
"IndentationError" "IndexError"
"KeyError" "KeyboardInterrupt" "LookupError"
"MemoryError" "NameError" "NotImplemented"
"NotImplementedError" "OSError" "OverflowError"
"PendingDeprecationWarning" "ReferenceError"
"RuntimeError" "RuntimeWarning" "StandardError"
"StopIteration" "SyntaxError" "SyntaxWarning"
"SystemError" "SystemExit" "TabError" "TypeError"
"UnboundLocalError" "UnicodeDecodeError"
"UnicodeEncodeError" "UnicodeError"
"UnicodeTranslateError" "UnicodeWarning"
"UserWarning" "ValueError" "Warning"
"ZeroDivisionError" "WindowsError")
"\\|"))
)
(list
;; decorators
'("^[ \t]*\\(@[a-zA-Z_][a-zA-Z_0-9.]+\\)\\((.+)\\)?" 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-exception-name-face)
;; raise stmts
'("\\<raise[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_.]*\\)" 1 py-exception-name-face)
;; except clauses
'("\\<except[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_.]*\\)" 1 py-exception-name-face)
;; classes
'("\\<class[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)" 1 py-class-name-face)
;; functions
'("\\<def[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
1 font-lock-function-name-face)
;; pseudo-keywords
'("\\<\\(self\\|cls\\|Ellipsis\\|True\\|False\\|None\\)\\>"
1 py-pseudo-keyword-face)
'("^[ \t]*\\(_\\{0,2\\}[a-zA-Z][a-zA-Z_0-9.]+_\\{0,2\\}\\) *\\(+\\|-\\|*\\|**\\|/\\|//\\|&\\|%\\||\\|^\\|>>\\|<<\\)? ?="
1 py-variable-name-face)
;; XXX, TODO, and FIXME tags
'("XXX\\|TODO\\|FIXME" 0 py-XXX-tag-face t)
;; special marking for string escapes and percent substitutes;
;; loops adapted from lisp-mode in font-lock.el
;; '((lambda (bound)
;; (catch 'found
;; (while (re-search-forward
;; (concat
;; "\\(\\\\\\\\\\|\\\\x..\\|\\\\u....\\|\\\\U........\\|"
;; "\\\\[0-9][0-9]*\\|\\\\[abfnrtv\"']\\)") bound t)
;; (let ((face (get-text-property (1- (point)) 'face)))
;; (when (or (and (listp face) (memq 'font-lock-string-face face))
;; (eq 'font-lock-string-face face))
;; (throw 'found t))))))
;; (1 'font-lock-regexp-grouping-backslash prepend))
;; '((lambda (bound)
;; (catch 'found
;; (while (re-search-forward "\\(%[^(]\\|%([^)]*).\\)" bound t)
;; (let ((face (get-text-property (1- (point)) 'face)))
;; (when (or (and (listp face) (memq 'font-lock-string-face face))
;; (eq 'font-lock-string-face face))
;; (throw 'found t))))))
;; (1 'font-lock-regexp-grouping-construct prepend))
))
"Additional expressions to highlight in Python mode.")
;; 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-assignement-re "\\<\\w+\\>[ \t]*\\(=\\|+=\\|*=\\|%=\\|&=\\|^=\\|<<=\\|-=\\|/=\\|**=\\||=\\|>>=\\|//=\\)"
"If looking at the beginning of an assignement. ")
(defconst py-block-re "[ \t]*\\<\\(class\\|def\\|for\\|if\\|try\\|while\\|with\\)\\>"
"Matches the beginning of a class, method or compound statement. ")
(defconst py-return-re
"[ \t]*\\<\\(return\\)\\>"
"Regular expression matching keyword which typically closes a function. ")
(defconst py-closing-re
"[ \t]*\\_<)\\_>"
"Regular expression matching keyword which typically closes a function. ")
(defconst py-class-re "[ \t]*\\<\\(class\\)\\>"
"Matches the beginning of a class definition. ")
(defconst py-def-or-class-re "[ \t]*\\<\\(def\\|class\\)\\>"
"Matches the beginning of a class- or functions definition. ")
(defconst py-def-re "[ \t]*\\<\\(def\\)\\>"
"Matches the beginning of a functions definition. ")
(defconst py-if-clause-re "[ \t]*\\<\\elif\\>"
"Matches the beginning of a compound statement's clause. ")
(defconst py-try-clause-re
(concat "\\(" (mapconcat 'identity
'("except\\(\\s +.*\\)?:"
"finally:")
"\\|")
"\\)")
"Matches the beginning of a try-statement's clause. ")
(defconst py-if-block-re "[ \t]*\\<if\\>"
"Matches the beginning of a compound statement saying `if'. ")
(defconst py-try-block-re "[ \t]*\\<try\\>"
"Matches the beginning of a compound statement saying `try'. " )
(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
"[rRuUbB]?'''[^']*\\(\\('[^']\\|''[^']\\)[^']*\\)*'''"
"\\|"
;; (maybe raw), long double quoted triple quoted strings (DQTQ),
;; with potential embedded double quotes
"[rRuUbB]?\"\"\"[^\"]*\\(\\(\"[^\"]\\|\"\"[^\"]\\)[^\"]*\\)*\"\"\""
"\\|"
"[rRuUbB]?'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
"\\|" ; or
"[rRuUbB]?\"\\([^\"\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-block-or-clause-re "[ \t]*\\<\\(if\\|else\\|elif\\|while\\|for\\|def\\|class\\|try\\|except\\|finally\\|with\\)\\>"
"Matches the beginning of a compound statement or it's clause. ")
(defconst py-clause-re "[ \t]*\\<\\(else\\|except\\|finally\\|elif\\)\\>"
"Matches the beginning of a compound statement's clause. ")
(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.")
(defconst 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 py-mode-abbrev-table nil
"Abbrev table in use in `python-mode' buffers.")
(define-abbrev-table 'py-mode-abbrev-table nil)
(defvar inferior-python-mode-abbrev-table nil
"Abbrev table in use in `python-mode' buffers.")
(define-abbrev-table 'inferior-python-mode-abbrev-table nil)
(defvar jython-mode-abbrev-table nil
"Abbrev table in use in `python-mode' buffers.")
(define-abbrev-table 'jython-mode-abbrev-table nil)
(defcustom python-mode-hook nil
"Hook run when entering Python mode."
:group 'python
:type 'hook)
(custom-add-option 'python-mode-hook 'py-imenu-create-index-new)
(custom-add-option 'python-mode-hook
(lambda ()
"Turn off Indent Tabs mode."
(setq indent-tabs-mode nil)))
(custom-add-option 'python-mode-hook 'turn-on-eldoc-mode)
(custom-add-option 'python-mode-hook 'abbrev-mode)
;; (custom-add-option 'python-mode-hook 'python-setup-brm)
(make-obsolete-variable 'jpython-mode-hook 'jython-mode-hook nil)
(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 nil))
;; 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.")
(defvar py-mode-map nil)
(setq py-mode-map
(let ((map (make-sparse-keymap)))