forked from python/cpython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
python-mode.el
2794 lines (2453 loc) · 104 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: 1995-1998 Barry A. Warsaw
;; 1992-1994 Tim Peters
;; Maintainer: [email protected]
;; Created: Feb 1992
;; Keywords: python languages oop
(defconst py-version "$Revision$"
"`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; in 1995, Barry Warsaw inherited the
;; mode and is the current maintainer.
;; COMPATIBILITY:
;; This version of python-mode.el is no longer compatible with Emacs
;; 18. For a gabazillion reasons, I highly recommend upgrading to
;; X/Emacs 19 or X/Emacs 20. I recommend at least Emacs 19.34 or
;; XEmacs 19.15. Any of the v20 X/Emacsen should be fine.
;; NOTE TO FSF EMACS USERS:
;; You may need to acquire the Custom library -- this applies to users
;; of Emacs 19.34 and NTEmacs based on 19.34, but not to Emacs 20
;; users. You must also byte-compile this file before use -- this
;; applies to FSF's Emacs 19.34, 20.x, and NTEmacs based on 19.34.
;; None of this applies to XEmacs (although byte compilation is still
;; recommended). You will also need to add the following to your
;; .emacs file so that the .py files come up in python-mode:
;;
;; (autoload 'python-mode "python-mode" "Python editing mode." t)
;; (setq auto-mode-alist
;; (cons '("\\.py$" . python-mode) auto-mode-alist))
;; (setq interpreter-mode-alist
;; (cons '("python" . python-mode) interpreter-mode-alist))
;;
;; Assuming python-mode.el is on your load-path, it will be invoked
;; when you visit a .py file, or a file with a first line that looks
;; like:
;;
;; #! /usr/bin/env python
;; NOTE TO XEMACS USERS:
;; An older version of this file was distributed with XEmacs 19.15,
;; 19.16 and 20.3. By default, in XEmacs when you visit a .py file,
;; the buffer is put in Python mode. Likewise for executable scripts
;; with the word `python' on the first line. You shouldn't need to do
;; much except make sure this new version is earlier in your
;; load-path, and byte-compile this file.
;; FOR MORE INFORMATION:
;; Please see <http://www.python.org/ftp/emacs/pmdetails.html> for the
;; latest information and compatibility notes.
;; BUG REPORTING:
;; To submit bug reports, use C-c C-b. 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!
;; If you are using XEmacs, you may also want to check out OO-Browser
;; that comes bundled with it, including documentation in the info
;; pages. For GNU Emacs you have to install it yourself. To read
;; more about OO-Browser, follow these links:
;; http://www.python.org/workshops/1996-06/papers/h.pasanen/oobr_contents.html
;; http://www.infodock.com/manuals/alt-oobr-cover.html
;; You may also want to take a look at Harri Pasanen's "Python Library
;; Reference Hot-Key Help System for XEmacs (or PLRHKHSX for short ;),
;; version 1.0"
;;
;; <http://www.iki.fi/hpa/>
;; TO DO LIST:
;; - Better integration with pdb.py and 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-block-down, bound to C-c C-d
;;; Code:
(require 'custom)
(eval-when-compile
(require 'cl)
(require 'custom)
;; Stock Emacs 19.34 has a broken/old Custom library that does more
;; harm than good
(or (fboundp 'defcustom)
(error "STOP! STOP! STOP! STOP!
The Custom library was not found or is out of date. A more current
version is required. Please download and install the latest version
of the Custom library from:
<http://www.dina.kvl.dk/~abraham/custom/>
See the Python Mode home page for details:
<http://www.python.org/ftp/emacs/>
")))
;; user definable variables
;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
(defgroup python nil
"Support for the Python programming language, <http://www.python.org/>"
:group 'languages)
(defcustom py-python-command "python"
"*Shell command used to start Python interpreter."
: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)
(defcustom py-indent-offset 4
"*Amount of offset per level of indentation
Note that `\\[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-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 guess 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 set as follows: if `py-indent-offset'
equals `tab-width' then `indent-tabs-mode' is set to t,
otherwise it is set to nil. This means that for newly written
code, tabs are only inserted in indentation if a 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 set either of these values explicitly, and 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)."
: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 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."
: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-scroll-process-buffer nil
"*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>."
:type 'boolean
: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 ".")
(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."
: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 ane exception occurs when running
Python code synchronously in a subprocess, jump immediately to the
source code of the innermost frame.")
(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)
;; 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. Note that if the file
name has a relative path, the `default-directory' for the buffer is
prepended to come up with a file name.")
(make-variable-buffer-local 'py-master-file)
;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
(defconst py-emacs-features
(let (features)
;; NTEmacs 19.34.6 has a broken make-temp-name; it always returns
;; the same string.
(let ((tmp1 (make-temp-name ""))
(tmp2 (make-temp-name "")))
(if (string-equal tmp1 tmp2)
(push 'broken-temp-names features)))
;; return the 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'.")
(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"
)
"\\|"))
(kw2 (mapconcat 'identity
'("else:" "except:" "finally:" "try:")
"\\|"))
)
(list
;; keywords
(cons (concat "\\b\\(" kw1 "\\)\\b[ \n\t(]") 1)
;; block introducing keywords with immediately following colons.
;; Yes "except" is in both lists.
(cons (concat "\\b\\(" kw2 "\\)[ \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.")
(make-variable-buffer-local 'py-indent-offset)
;; 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.")
;; Constants
;; Regexp matching a Python string literal
(defconst py-stringlit-re
(concat
"'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
"\\|" ; or
"\"\\([^\"\n\\]\\|\\\\.\\)*\"")) ; double-quoted
;; Regexp matching Python lines that are continued via backslash.
;; 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 blank or comment lines.
(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)")
;; Regexp matching clauses to be outdented one level.
(defconst py-outdent-re
(concat "\\(" (mapconcat 'identity
'("else:"
"except\\(\\s +.*\\)?:"
"finally:"
"elif\\s +.*:")
"\\|")
"\\)"))
;; Regexp matching keywords which typically close a block
(defconst py-block-closing-keywords-re
"\\(return\\|raise\\|break\\|continue\\|pass\\)")
;; Regexp matching lines to not outdent after.
(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]")
)
"\\|")
"\\)"))
;; 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.
(defconst py-defun-start-re
"^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*=")
;; 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.
(defconst py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)")
;; Regexp that describes tracebacks
(defconst py-traceback-line-re
"[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)")
;; 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 ()
;; 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; 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 defun
;; boi -- back to indentation
;;
;; 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) (beginning-of-python-def-or-class))
((eq position 'bob) (beginning-of-buffer))
((eq position 'eob) (end-of-buffer))
((eq position 'boi) (back-to-indentation))
(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!
)
))
;; 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'.")
;; 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|" 'py-execute-region)
(define-key py-mode-map "\C-c!" 'py-shell)
;; 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-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-hm" 'py-describe-mode)
(define-key py-mode-map "\e\C-a" 'beginning-of-python-def-or-class)
(define-key py-mode-map "\e\C-e" 'end-of-python-def-or-class)
(define-key py-mode-map "\C-c-" 'py-up-exception)
(define-key py-mode-map "\C-c=" 'py-down-exception)
;; 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)
;; py-newline-and-indent mappings
(define-key py-mode-map "\n" 'py-newline-and-indent)
(define-key py-mode-map "\C-m" 'py-newline-and-indent)
;; 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))
)
(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-mode-syntax-table nil
"Syntax table used in `python-mode' buffers.")
(if py-mode-syntax-table
nil
(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.
(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)
)
;; 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)]
"-"
["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)
(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-no-properties (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 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
font-lock-defaults '(python-font-lock-keywords)
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 (boundp 'comment-multi-line)
(setq comment-multi-line nil))
;; Install Imenu, only works for Emacs.
(when (py-safe (require 'imenu))
(make-variable-buffer-local 'imenu-create-index-function)
(setq imenu-create-index-function
(function imenu-example--create-python-index))
(setq imenu-generic-expression
imenu-example--generic-python-expression)
(if (fboundp 'imenu-add-to-menubar)
(imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
)
;; Run the mode hook. Note that py-mode-hook is deprecated.
(if python-mode-hook
(run-hooks 'python-mode-hook)
(run-hooks 'py-mode-hook))
;; Now do the automagical guessing
(if py-smart-indentation
(let ((offset py-indent-offset))
;; Its okay if this fails to guess a good value
(if (and (py-safe (py-guess-indent-offset))
(<= py-indent-offset 8)
(>= py-indent-offset 2))
(setq offset py-indent-offset))
(setq py-indent-offset offset)
(setq indent-tabs-mode (= tab-width py-indent-offset))
)))
;; 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 (forward-line -1)
(py-goto-initial-line)
(back-to-indentation)
(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)))