aboutsummaryrefslogtreecommitdiffstats
path: root/lisp/progmodes
diff options
context:
space:
mode:
Diffstat (limited to 'lisp/progmodes')
-rw-r--r--lisp/progmodes/gdb-ui.el278
-rw-r--r--lisp/progmodes/grep.el122
-rw-r--r--lisp/progmodes/gud.el10
-rw-r--r--lisp/progmodes/python.el1540
-rw-r--r--lisp/progmodes/sh-script.el13
-rw-r--r--lisp/progmodes/vhdl-mode.el6
6 files changed, 1290 insertions, 679 deletions
diff --git a/lisp/progmodes/gdb-ui.el b/lisp/progmodes/gdb-ui.el
index dca6fa16df0..f45bb2fe524 100644
--- a/lisp/progmodes/gdb-ui.el
+++ b/lisp/progmodes/gdb-ui.el
@@ -115,6 +115,7 @@ address for root variables.")
115(defvar gdb-main-file nil "Source file from which program execution begins.") 115(defvar gdb-main-file nil "Source file from which program execution begins.")
116(defvar gud-old-arrow nil) 116(defvar gud-old-arrow nil)
117(defvar gdb-overlay-arrow-position nil) 117(defvar gdb-overlay-arrow-position nil)
118(defvar gdb-stack-position nil)
118(defvar gdb-server-prefix nil) 119(defvar gdb-server-prefix nil)
119(defvar gdb-flush-pending-output nil) 120(defvar gdb-flush-pending-output nil)
120(defvar gdb-location-alist nil 121(defvar gdb-location-alist nil
@@ -314,14 +315,14 @@ Also display the main routine in the disassembly buffer if present."
314 "Nil means just pop up the GUD buffer unless `gdb-show-main' is t. 315 "Nil means just pop up the GUD buffer unless `gdb-show-main' is t.
315In this case it starts with two windows: one displaying the GUD 316In this case it starts with two windows: one displaying the GUD
316buffer and the other with the source file with the main routine 317buffer and the other with the source file with the main routine
317of the inferior. Non-nil means display the layout shown for 318of the debugged program. Non-nil means display the layout shown for
318`gdba'." 319`gdba'."
319 :type 'boolean 320 :type 'boolean
320 :group 'gud 321 :group 'gud
321 :version "22.1") 322 :version "22.1")
322 323
323(defcustom gdb-use-separate-io-buffer nil 324(defcustom gdb-use-separate-io-buffer nil
324 "Non-nil means display output from the inferior in a separate buffer." 325 "Non-nil means display output from the debugged program in a separate buffer."
325 :type 'boolean 326 :type 'boolean
326 :group 'gud 327 :group 'gud
327 :version "22.1") 328 :version "22.1")
@@ -353,14 +354,14 @@ With arg, display additional buffers iff arg is positive."
353 (error nil)))) 354 (error nil))))
354 355
355(defun gdb-use-separate-io-buffer (arg) 356(defun gdb-use-separate-io-buffer (arg)
356 "Toggle separate IO for inferior. 357 "Toggle separate IO for debugged program.
357With arg, use separate IO iff arg is positive." 358With arg, use separate IO iff arg is positive."
358 (interactive "P") 359 (interactive "P")
359 (setq gdb-use-separate-io-buffer 360 (setq gdb-use-separate-io-buffer
360 (if (null arg) 361 (if (null arg)
361 (not gdb-use-separate-io-buffer) 362 (not gdb-use-separate-io-buffer)
362 (> (prefix-numeric-value arg) 0))) 363 (> (prefix-numeric-value arg) 0)))
363 (message (format "Separate inferior IO %sabled" 364 (message (format "Separate IO %sabled"
364 (if gdb-use-separate-io-buffer "en" "dis"))) 365 (if gdb-use-separate-io-buffer "en" "dis")))
365 (if (and gud-comint-buffer 366 (if (and gud-comint-buffer
366 (buffer-name gud-comint-buffer)) 367 (buffer-name gud-comint-buffer))
@@ -383,8 +384,7 @@ With arg, use separate IO iff arg is positive."
383 (list t nil) nil "-c" 384 (list t nil) nil "-c"
384 (concat gdb-cpp-define-alist-program " " 385 (concat gdb-cpp-define-alist-program " "
385 gdb-cpp-define-alist-flags))))) 386 gdb-cpp-define-alist-flags)))))
386 (define-list (split-string output "\n" t)) 387 (define-list (split-string output "\n" t)) (name))
387 (name))
388 (setq gdb-define-alist nil) 388 (setq gdb-define-alist nil)
389 (dolist (define define-list) 389 (dolist (define define-list)
390 (setq name (nth 1 (split-string define "[( ]"))) 390 (setq name (nth 1 (split-string define "[( ]")))
@@ -1030,7 +1030,7 @@ The key should be one of the cars in `gdb-buffer-rules-assoc'."
1030 (minibuffer . nil))) 1030 (minibuffer . nil)))
1031 1031
1032(defun gdb-frame-separate-io-buffer () 1032(defun gdb-frame-separate-io-buffer ()
1033 "Display IO of inferior in a new frame." 1033 "Display IO of debugged program in a new frame."
1034 (interactive) 1034 (interactive)
1035 (if gdb-use-separate-io-buffer 1035 (if gdb-use-separate-io-buffer
1036 (let ((special-display-regexps (append special-display-regexps '(".*"))) 1036 (let ((special-display-regexps (append special-display-regexps '(".*")))
@@ -1290,12 +1290,14 @@ not GDB."
1290 (progn 1290 (progn
1291 (setq gud-running t) 1291 (setq gud-running t)
1292 (setq gdb-inferior-status "running") 1292 (setq gdb-inferior-status "running")
1293 (setq gdb-signalled nil)
1293 (gdb-force-mode-line-update 1294 (gdb-force-mode-line-update
1294 (propertize gdb-inferior-status 'face font-lock-type-face)) 1295 (propertize gdb-inferior-status 'face font-lock-type-face))
1295 (gdb-remove-text-properties) 1296 (gdb-remove-text-properties)
1296 (setq gud-old-arrow gud-overlay-arrow-position) 1297 (setq gud-old-arrow gud-overlay-arrow-position)
1297 (setq gud-overlay-arrow-position nil) 1298 (setq gud-overlay-arrow-position nil)
1298 (setq gdb-overlay-arrow-position nil) 1299 (setq gdb-overlay-arrow-position nil)
1300 (setq gdb-stack-position nil)
1299 (if gdb-use-separate-io-buffer 1301 (if gdb-use-separate-io-buffer
1300 (setq gdb-output-sink 'inferior)))) 1302 (setq gdb-output-sink 'inferior))))
1301 (t 1303 (t
@@ -1330,6 +1332,7 @@ directives."
1330 (setq gdb-active-process nil) 1332 (setq gdb-active-process nil)
1331 (setq gud-overlay-arrow-position nil) 1333 (setq gud-overlay-arrow-position nil)
1332 (setq gdb-overlay-arrow-position nil) 1334 (setq gdb-overlay-arrow-position nil)
1335 (setq gdb-stack-position nil)
1333 (setq gud-old-arrow nil) 1336 (setq gud-old-arrow nil)
1334 (setq gdb-inferior-status "exited") 1337 (setq gdb-inferior-status "exited")
1335 (gdb-force-mode-line-update 1338 (gdb-force-mode-line-update
@@ -1358,6 +1361,23 @@ directives."
1358 :type 'boolean 1361 :type 'boolean
1359 :version "22.1") 1362 :version "22.1")
1360 1363
1364(defcustom gdb-find-source-frame nil
1365 "Non-nil means try to find a source frame further up stack e.g after signal."
1366 :group 'gud
1367 :type 'boolean
1368 :version "22.1")
1369
1370(defun gdb-find-source-frame (arg)
1371 "Toggle trying to find a source frame further up stack.
1372With arg, look for a source frame further up stack iff arg is positive."
1373 (interactive "P")
1374 (setq gdb-find-source-frame
1375 (if (null arg)
1376 (not gdb-find-source-frame)
1377 (> (prefix-numeric-value arg) 0)))
1378 (message (format "Looking for source frame %sabled"
1379 (if gdb-find-source-frame "en" "dis"))))
1380
1361(defun gdb-stopped (ignored) 1381(defun gdb-stopped (ignored)
1362 "An annotation handler for `stopped'. 1382 "An annotation handler for `stopped'.
1363It is just like `gdb-stopping', except that if we already set the output 1383It is just like `gdb-stopping', except that if we already set the output
@@ -1371,14 +1391,15 @@ sink to `user' in `gdb-stopping', that is fine."
1371 (if gdb-same-frame 1391 (if gdb-same-frame
1372 (gdb-display-gdb-buffer) 1392 (gdb-display-gdb-buffer)
1373 (gdb-frame-gdb-buffer)) 1393 (gdb-frame-gdb-buffer))
1394 (if gdb-find-source-frame
1374 ;;Try to find source further up stack e.g after signal. 1395 ;;Try to find source further up stack e.g after signal.
1375 (setq gdb-look-up-stack 1396 (setq gdb-look-up-stack
1376 (if (gdb-get-buffer 'gdb-stack-buffer) 1397 (if (gdb-get-buffer 'gdb-stack-buffer)
1377 'keep 1398 'keep
1378 (progn 1399 (progn
1379 (gdb-get-buffer-create 'gdb-stack-buffer) 1400 (gdb-get-buffer-create 'gdb-stack-buffer)
1380 (gdb-invalidate-frames) 1401 (gdb-invalidate-frames)
1381 'delete))))) 1402 'delete))))))
1382 (unless (member gdb-inferior-status '("exited" "signal")) 1403 (unless (member gdb-inferior-status '("exited" "signal"))
1383 (setq gdb-inferior-status "stopped") 1404 (setq gdb-inferior-status "stopped")
1384 (gdb-force-mode-line-update 1405 (gdb-force-mode-line-update
@@ -1754,52 +1775,69 @@ static char *magick[] = {
1754 (gdb-remove-breakpoint-icons (point-min) (point-max))))) 1775 (gdb-remove-breakpoint-icons (point-min) (point-max)))))
1755 (with-current-buffer (gdb-get-buffer 'gdb-breakpoints-buffer) 1776 (with-current-buffer (gdb-get-buffer 'gdb-breakpoints-buffer)
1756 (save-excursion 1777 (save-excursion
1778 (let ((buffer-read-only nil))
1757 (goto-char (point-min)) 1779 (goto-char (point-min))
1758 (while (< (point) (- (point-max) 1)) 1780 (while (< (point) (- (point-max) 1))
1759 (forward-line 1) 1781 (forward-line 1)
1760 (if (looking-at "[^\t].*?breakpoint") 1782 (if (looking-at gdb-breakpoint-regexp)
1761 (progn 1783 (progn
1762 (looking-at "\\([0-9]+\\)\\s-+\\S-+\\s-+\\S-+\\s-+\\(.\\)")
1763 (setq bptno (match-string 1)) 1784 (setq bptno (match-string 1))
1764 (setq flag (char-after (match-beginning 2))) 1785 (setq flag (char-after (match-beginning 2)))
1765 (beginning-of-line) 1786 (add-text-properties
1766 (if (re-search-forward " in \\(.*\\) at\\s-+" nil t) 1787 (match-beginning 2) (match-end 2)
1767 (progn 1788 (if (eq flag ?y)
1768 (let ((buffer-read-only nil)) 1789 '(face font-lock-warning-face)
1769 (add-text-properties (match-beginning 1) (match-end 1) 1790 '(face font-lock-type-face)))
1770 '(face font-lock-function-name-face))) 1791 (let ((bl (point))
1771 (looking-at "\\(\\S-+\\):\\([0-9]+\\)") 1792 (el (line-end-position)))
1772 (let ((line (match-string 2)) (buffer-read-only nil) 1793 (if (re-search-forward " in \\(.*\\) at\\s-+" el t)
1773 (file (match-string 1))) 1794 (progn
1774 (add-text-properties (line-beginning-position) 1795 (add-text-properties
1775 (line-end-position) 1796 (match-beginning 1) (match-end 1)
1776 '(mouse-face highlight 1797 '(face font-lock-function-name-face))
1777 help-echo "mouse-2, RET: visit breakpoint")) 1798 (looking-at "\\(\\S-+\\):\\([0-9]+\\)")
1778 (unless (file-exists-p file) 1799 (let ((line (match-string 2))
1779 (setq file (cdr (assoc bptno gdb-location-alist)))) 1800 (file (match-string 1)))
1780 (if (and file 1801 (add-text-properties bl el
1781 (not (string-equal file "File not found"))) 1802 '(mouse-face highlight
1782 (with-current-buffer 1803 help-echo "mouse-2, RET: visit breakpoint"))
1783 (find-file-noselect file 'nowarn) 1804 (unless (file-exists-p file)
1784 (set (make-local-variable 'gud-minor-mode) 1805 (setq file (cdr (assoc bptno gdb-location-alist))))
1785 'gdba) 1806 (if (and file
1786 (set (make-local-variable 'tool-bar-map) 1807 (not (string-equal file "File not found")))
1787 gud-tool-bar-map) 1808 (with-current-buffer
1788 ;; Only want one breakpoint icon at each 1809 (find-file-noselect file 'nowarn)
1789 ;; location. 1810 (set (make-local-variable 'gud-minor-mode)
1790 (save-excursion 1811 'gdba)
1791 (goto-line (string-to-number line)) 1812 (set (make-local-variable 'tool-bar-map)
1792 (gdb-put-breakpoint-icon (eq flag ?y) bptno))) 1813 gud-tool-bar-map)
1793 (gdb-enqueue-input 1814 ;; Only want one breakpoint icon at each
1794 (list 1815 ;; location.
1795 (concat gdb-server-prefix "list " 1816 (save-excursion
1796 (match-string-no-properties 1) ":1\n") 1817 (goto-line (string-to-number line))
1797 'ignore)) 1818 (gdb-put-breakpoint-icon (eq flag ?y) bptno)))
1798 (gdb-enqueue-input 1819 (gdb-enqueue-input
1799 (list (concat gdb-server-prefix "info source\n") 1820 (list
1800 `(lambda () (gdb-get-location 1821 (concat gdb-server-prefix "list "
1801 ,bptno ,line ,flag)))))))))) 1822 (match-string-no-properties 1) ":1\n")
1802 (end-of-line))))) 1823 'ignore))
1824 (gdb-enqueue-input
1825 (list (concat gdb-server-prefix "info source\n")
1826 `(lambda () (gdb-get-location
1827 ,bptno ,line ,flag)))))))
1828 (if (re-search-forward
1829 "<\\(\\(\\sw\\|[_.]\\)+\\)\\(\\+[0-9]+\\)?>"
1830 el t)
1831 (add-text-properties
1832 (match-beginning 1) (match-end 1)
1833 '(face font-lock-function-name-face))
1834 (end-of-line)
1835 (re-search-backward "\\s-\\(\\S-*\\)"
1836 bl t)
1837 (add-text-properties
1838 (match-beginning 1) (match-end 1)
1839 '(face font-lock-variable-name-face)))))))
1840 (end-of-line))))))
1803 (if (gdb-get-buffer 'gdb-assembler-buffer) (gdb-assembler-custom))) 1841 (if (gdb-get-buffer 'gdb-assembler-buffer) (gdb-assembler-custom)))
1804 1842
1805(defun gdb-mouse-set-clear-breakpoint (event) 1843(defun gdb-mouse-set-clear-breakpoint (event)
@@ -2002,8 +2040,14 @@ static char *magick[] = {
2002 (goto-char bl) 2040 (goto-char bl)
2003 (when (looking-at "^#\\([0-9]+\\)") 2041 (when (looking-at "^#\\([0-9]+\\)")
2004 (when (string-equal (match-string 1) gdb-frame-number) 2042 (when (string-equal (match-string 1) gdb-frame-number)
2005 (put-text-property bl (+ bl 4) 2043 (if (> (car (window-fringes)) 0)
2006 'face '(:inverse-video t))) 2044 (progn
2045 (or gdb-stack-position
2046 (setq gdb-stack-position (make-marker)))
2047 (set-marker gdb-stack-position (point)))
2048 (set-marker gdb-stack-position nil)
2049 (put-text-property bl (+ bl 4)
2050 'face '(:inverse-video t))))
2007 (when (re-search-forward 2051 (when (re-search-forward
2008 (concat 2052 (concat
2009 (if (string-equal (match-string 1) "0") "" " in ") 2053 (if (string-equal (match-string 1) "0") "" " in ")
@@ -2036,9 +2080,10 @@ static char *magick[] = {
2036 (setq gdb-look-up-stack nil)) 2080 (setq gdb-look-up-stack nil))
2037 2081
2038(defun gdb-set-hollow () 2082(defun gdb-set-hollow ()
2039 (with-current-buffer (gud-find-file (car gud-last-last-frame)) 2083 (if gud-last-last-frame
2040 (setq fringe-indicator-alist 2084 (with-current-buffer (gud-find-file (car gud-last-last-frame))
2041 '((overlay-arrow . hollow-right-triangle))))) 2085 (setq fringe-indicator-alist
2086 '((overlay-arrow . hollow-right-triangle))))))
2042 2087
2043(defun gdb-stack-buffer-name () 2088(defun gdb-stack-buffer-name ()
2044 (with-current-buffer gud-comint-buffer 2089 (with-current-buffer gud-comint-buffer
@@ -2073,6 +2118,8 @@ static char *magick[] = {
2073 (kill-all-local-variables) 2118 (kill-all-local-variables)
2074 (setq major-mode 'gdb-frames-mode) 2119 (setq major-mode 'gdb-frames-mode)
2075 (setq mode-name "Frames") 2120 (setq mode-name "Frames")
2121 (setq gdb-stack-position nil)
2122 (add-to-list 'overlay-arrow-variable-list 'gdb-stack-position)
2076 (setq buffer-read-only t) 2123 (setq buffer-read-only t)
2077 (use-local-map gdb-frames-mode-map) 2124 (use-local-map gdb-frames-mode-map)
2078 (run-mode-hooks 'gdb-frames-mode-hook) 2125 (run-mode-hooks 'gdb-frames-mode-hook)
@@ -2524,18 +2571,18 @@ corresponding to the mode line clicked."
2524 'local-map 2571 'local-map
2525 (gdb-make-header-line-mouse-map 2572 (gdb-make-header-line-mouse-map
2526 'mouse-1 2573 'mouse-1
2527 #'(lambda () (interactive) 2574 (lambda () (interactive)
2528 (let ((gdb-memory-address 2575 (let ((gdb-memory-address
2529 ;; Let GDB do the arithmetic. 2576 ;; Let GDB do the arithmetic.
2530 (concat 2577 (concat
2531 gdb-memory-address " - " 2578 gdb-memory-address " - "
2532 (number-to-string 2579 (number-to-string
2533 (* gdb-memory-repeat-count 2580 (* gdb-memory-repeat-count
2534 (cond ((string= gdb-memory-unit "b") 1) 2581 (cond ((string= gdb-memory-unit "b") 1)
2535 ((string= gdb-memory-unit "h") 2) 2582 ((string= gdb-memory-unit "h") 2)
2536 ((string= gdb-memory-unit "w") 4) 2583 ((string= gdb-memory-unit "w") 4)
2537 ((string= gdb-memory-unit "g") 8))))))) 2584 ((string= gdb-memory-unit "g") 8)))))))
2538 (gdb-invalidate-memory))))) 2585 (gdb-invalidate-memory)))))
2539 "|" 2586 "|"
2540 (propertize "+" 2587 (propertize "+"
2541 'face font-lock-warning-face 2588 'face font-lock-warning-face
@@ -2543,9 +2590,9 @@ corresponding to the mode line clicked."
2543 'mouse-face 'mode-line-highlight 2590 'mouse-face 'mode-line-highlight
2544 'local-map (gdb-make-header-line-mouse-map 2591 'local-map (gdb-make-header-line-mouse-map
2545 'mouse-1 2592 'mouse-1
2546 #'(lambda () (interactive) 2593 (lambda () (interactive)
2547 (let ((gdb-memory-address nil)) 2594 (let ((gdb-memory-address nil))
2548 (gdb-invalidate-memory))))) 2595 (gdb-invalidate-memory)))))
2549 "]: " 2596 "]: "
2550 (propertize gdb-memory-address 2597 (propertize gdb-memory-address
2551 'face font-lock-warning-face 2598 'face font-lock-warning-face
@@ -2592,8 +2639,11 @@ corresponding to the mode line clicked."
2592(defun gdb-frame-memory-buffer () 2639(defun gdb-frame-memory-buffer ()
2593 "Display memory contents in a new frame." 2640 "Display memory contents in a new frame."
2594 (interactive) 2641 (interactive)
2595 (let ((special-display-regexps (append special-display-regexps '(".*"))) 2642 (let* ((special-display-regexps (append special-display-regexps '(".*")))
2596 (special-display-frame-alist gdb-frame-parameters)) 2643 (special-display-frame-alist
2644 (cons '(left-fringe . 0)
2645 (cons '(right-fringe . 0)
2646 (cons '(width . 83) gdb-frame-parameters)))))
2597 (display-buffer (gdb-get-buffer-create 'gdb-memory-buffer)))) 2647 (display-buffer (gdb-get-buffer-create 'gdb-memory-buffer))))
2598 2648
2599 2649
@@ -2610,13 +2660,14 @@ corresponding to the mode line clicked."
2610 2660
2611(defvar gdb-locals-watch-map 2661(defvar gdb-locals-watch-map
2612 (let ((map (make-sparse-keymap))) 2662 (let ((map (make-sparse-keymap)))
2613 (define-key map "\r" '(lambda () (interactive) 2663 (suppress-keymap map)
2614 (beginning-of-line) 2664 (define-key map "\r" (lambda () (interactive)
2615 (gud-watch))) 2665 (beginning-of-line)
2616 (define-key map [mouse-2] '(lambda (event) (interactive "e") 2666 (gud-watch)))
2617 (mouse-set-point event) 2667 (define-key map [mouse-2] (lambda (event) (interactive "e")
2618 (beginning-of-line) 2668 (mouse-set-point event)
2619 (gud-watch))) 2669 (beginning-of-line)
2670 (gud-watch)))
2620 map) 2671 map)
2621 "Keymap to create watch expression of a complex data type local variable.") 2672 "Keymap to create watch expression of a complex data type local variable.")
2622 2673
@@ -2739,7 +2790,7 @@ corresponding to the mode line clicked."
2739 (define-key menu [gdb] '("Gdb" . gdb-display-gdb-buffer)) 2790 (define-key menu [gdb] '("Gdb" . gdb-display-gdb-buffer))
2740 (define-key menu [threads] '("Threads" . gdb-display-threads-buffer)) 2791 (define-key menu [threads] '("Threads" . gdb-display-threads-buffer))
2741 (define-key menu [inferior] 2792 (define-key menu [inferior]
2742 '(menu-item "Inferior IO" gdb-display-separate-io-buffer 2793 '(menu-item "Separate IO" gdb-display-separate-io-buffer
2743 :enable gdb-use-separate-io-buffer)) 2794 :enable gdb-use-separate-io-buffer))
2744 (define-key menu [memory] '("Memory" . gdb-display-memory-buffer)) 2795 (define-key menu [memory] '("Memory" . gdb-display-memory-buffer))
2745 (define-key menu [registers] '("Registers" . gdb-display-registers-buffer)) 2796 (define-key menu [registers] '("Registers" . gdb-display-registers-buffer))
@@ -2758,7 +2809,7 @@ corresponding to the mode line clicked."
2758 (define-key menu [threads] '("Threads" . gdb-frame-threads-buffer)) 2809 (define-key menu [threads] '("Threads" . gdb-frame-threads-buffer))
2759 (define-key menu [memory] '("Memory" . gdb-frame-memory-buffer)) 2810 (define-key menu [memory] '("Memory" . gdb-frame-memory-buffer))
2760 (define-key menu [inferior] 2811 (define-key menu [inferior]
2761 '(menu-item "Inferior IO" gdb-frame-separate-io-buffer 2812 '(menu-item "Separate IO" gdb-frame-separate-io-buffer
2762 :enable gdb-use-separate-io-buffer)) 2813 :enable gdb-use-separate-io-buffer))
2763 (define-key menu [registers] '("Registers" . gdb-frame-registers-buffer)) 2814 (define-key menu [registers] '("Registers" . gdb-frame-registers-buffer))
2764 (define-key menu [disassembly] '("Disassembly" . gdb-frame-assembler-buffer)) 2815 (define-key menu [disassembly] '("Disassembly" . gdb-frame-assembler-buffer))
@@ -2771,10 +2822,15 @@ corresponding to the mode line clicked."
2771 (define-key gud-menu-map [ui] 2822 (define-key gud-menu-map [ui]
2772 `(menu-item (if (eq gud-minor-mode 'gdba) "GDB-UI" "GDB-MI") 2823 `(menu-item (if (eq gud-minor-mode 'gdba) "GDB-UI" "GDB-MI")
2773 ,menu :visible (memq gud-minor-mode '(gdbmi gdba)))) 2824 ,menu :visible (memq gud-minor-mode '(gdbmi gdba))))
2825 (define-key menu [gdb-find-source-frame]
2826 '(menu-item "Look For Source Frame" gdb-find-source-frame
2827 :visible (eq gud-minor-mode 'gdba)
2828 :help "Toggle look for source frame."
2829 :button (:toggle . gdb-find-source-frame)))
2774 (define-key menu [gdb-use-separate-io] 2830 (define-key menu [gdb-use-separate-io]
2775 '(menu-item "Separate inferior IO" gdb-use-separate-io-buffer 2831 '(menu-item "Separate IO" gdb-use-separate-io-buffer
2776 :visible (eq gud-minor-mode 'gdba) 2832 :visible (eq gud-minor-mode 'gdba)
2777 :help "Toggle separate IO for inferior." 2833 :help "Toggle separate IO for debugged program."
2778 :button (:toggle . gdb-use-separate-io-buffer))) 2834 :button (:toggle . gdb-use-separate-io-buffer)))
2779 (define-key menu [gdb-many-windows] 2835 (define-key menu [gdb-many-windows]
2780 '(menu-item "Display Other Windows" gdb-many-windows 2836 '(menu-item "Display Other Windows" gdb-many-windows
@@ -2871,12 +2927,13 @@ Kills the gdb buffers, and resets variables and the source buffers."
2871 (setq gud-minor-mode nil) 2927 (setq gud-minor-mode nil)
2872 (kill-local-variable 'tool-bar-map) 2928 (kill-local-variable 'tool-bar-map)
2873 (kill-local-variable 'gdb-define-alist)))))) 2929 (kill-local-variable 'gdb-define-alist))))))
2874 (when (markerp gdb-overlay-arrow-position) 2930 (setq gdb-overlay-arrow-position nil)
2875 (move-marker gdb-overlay-arrow-position nil)
2876 (setq gdb-overlay-arrow-position nil))
2877 (setq overlay-arrow-variable-list 2931 (setq overlay-arrow-variable-list
2878 (delq 'gdb-overlay-arrow-position overlay-arrow-variable-list)) 2932 (delq 'gdb-overlay-arrow-position overlay-arrow-variable-list))
2879 (setq fringe-indicator-alist '((overlay-arrow . right-triangle))) 2933 (setq fringe-indicator-alist '((overlay-arrow . right-triangle)))
2934 (setq gdb-stack-position nil)
2935 (setq overlay-arrow-variable-list
2936 (delq 'gdb-stack-position overlay-arrow-variable-list))
2880 (if (boundp 'speedbar-frame) (speedbar-timer-fn)) 2937 (if (boundp 'speedbar-frame) (speedbar-timer-fn))
2881 (setq gud-running nil) 2938 (setq gud-running nil)
2882 (setq gdb-active-process nil) 2939 (setq gdb-active-process nil)
@@ -3098,8 +3155,7 @@ BUFFER nil or omitted means use the current buffer."
3098 '((overlay-arrow . hollow-right-triangle)))) 3155 '((overlay-arrow . hollow-right-triangle))))
3099 (or gdb-overlay-arrow-position 3156 (or gdb-overlay-arrow-position
3100 (setq gdb-overlay-arrow-position (make-marker))) 3157 (setq gdb-overlay-arrow-position (make-marker)))
3101 (set-marker gdb-overlay-arrow-position 3158 (set-marker gdb-overlay-arrow-position (point))))))
3102 (point) (current-buffer))))))
3103 ;; remove all breakpoint-icons in assembler buffer before updating. 3159 ;; remove all breakpoint-icons in assembler buffer before updating.
3104 (gdb-remove-breakpoint-icons (point-min) (point-max)))) 3160 (gdb-remove-breakpoint-icons (point-min) (point-max))))
3105 (with-current-buffer (gdb-get-buffer 'gdb-breakpoints-buffer) 3161 (with-current-buffer (gdb-get-buffer 'gdb-breakpoints-buffer)
@@ -3460,10 +3516,32 @@ in_scope=\"\\(.*?\\)\".*?}")
3460 3516
3461(defvar gdb-locals-watch-map-1 3517(defvar gdb-locals-watch-map-1
3462 (let ((map (make-sparse-keymap))) 3518 (let ((map (make-sparse-keymap)))
3519 (suppress-keymap map)
3520 (define-key map "\r" 'gud-watch)
3463 (define-key map [mouse-2] 'gud-watch) 3521 (define-key map [mouse-2] 'gud-watch)
3464 map) 3522 map)
3465 "Keymap to create watch expression of a complex data type local variable.") 3523 "Keymap to create watch expression of a complex data type local variable.")
3466 3524
3525(defvar gdb-edit-locals-map-1
3526 (let ((map (make-sparse-keymap)))
3527 (suppress-keymap map)
3528 (define-key map "\r" 'gdb-edit-locals-value)
3529 (define-key map [mouse-2] 'gdb-edit-locals-value)
3530 map)
3531 "Keymap to edit value of a simple data type local variable.")
3532
3533(defun gdb-edit-locals-value (&optional event)
3534 "Assign a value to a variable displayed in the locals buffer."
3535 (interactive (list last-input-event))
3536 (save-excursion
3537 (if event (posn-set-point (event-end event)))
3538 (beginning-of-line)
3539 (let* ((var (current-word))
3540 (value (read-string (format "New value (%s): " var))))
3541 (gdb-enqueue-input
3542 (list (concat gdb-server-prefix"set variable " var " = " value "\n")
3543 'ignore)))))
3544
3467;; Dont display values of arrays or structures. 3545;; Dont display values of arrays or structures.
3468;; These can be expanded using gud-watch. 3546;; These can be expanded using gud-watch.
3469(defun gdb-stack-list-locals-handler () 3547(defun gdb-stack-list-locals-handler ()
@@ -3491,20 +3569,26 @@ in_scope=\"\\(.*?\\)\".*?}")
3491 (let* ((window (get-buffer-window buf 0)) 3569 (let* ((window (get-buffer-window buf 0))
3492 (start (window-start window)) 3570 (start (window-start window))
3493 (p (window-point window)) 3571 (p (window-point window))
3494 (buffer-read-only nil)) 3572 (buffer-read-only nil) (name) (value))
3495 (erase-buffer) 3573 (erase-buffer)
3496 (dolist (local locals-list) 3574 (dolist (local locals-list)
3497 (setq name (car local)) 3575 (setq name (car local))
3498 (if (or (not (nth 2 local)) 3576 (setq value (nth 2 local))
3499 (string-match "^\\0x" (nth 2 local))) 3577 (if (or (not value)
3578 (string-match "^\\0x" value))
3500 (add-text-properties 0 (length name) 3579 (add-text-properties 0 (length name)
3501 `(mouse-face highlight 3580 `(mouse-face highlight
3502 help-echo "mouse-2: create watch expression" 3581 help-echo "mouse-2: create watch expression"
3503 local-map ,gdb-locals-watch-map-1) 3582 local-map ,gdb-locals-watch-map-1)
3504 name)) 3583 name)
3584 (add-text-properties 0 (length value)
3585 `(mouse-face highlight
3586 help-echo "mouse-2: edit value"
3587 local-map ,gdb-edit-locals-map-1)
3588 value))
3505 (insert 3589 (insert
3506 (concat name "\t" (nth 1 local) 3590 (concat name "\t" (nth 1 local)
3507 "\t" (nth 2 local) "\n"))) 3591 "\t" value "\n")))
3508 (set-window-start window start) 3592 (set-window-start window start)
3509 (set-window-point window p)))))))) 3593 (set-window-point window p))))))))
3510 3594
diff --git a/lisp/progmodes/grep.el b/lisp/progmodes/grep.el
index e7d85910a63..48692f9742f 100644
--- a/lisp/progmodes/grep.el
+++ b/lisp/progmodes/grep.el
@@ -335,7 +335,7 @@ This variable's value takes effect when `grep-compute-defaults' is called.")
335(defvar grep-find-use-xargs nil 335(defvar grep-find-use-xargs nil
336 "Whether \\[grep-find] uses the `xargs' utility by default. 336 "Whether \\[grep-find] uses the `xargs' utility by default.
337 337
338If nil, it uses `find -exec'; if `gnu', it uses `find -print0' and `xargs -0'; 338If `exec', it uses `find -exec'; if `gnu', it uses `find -print0' and `xargs -0';
339if not nil and not `gnu', it uses `find -print' and `xargs'. 339if not nil and not `gnu', it uses `find -print' and `xargs'.
340 340
341This variable's value takes effect when `grep-compute-defaults' is called.") 341This variable's value takes effect when `grep-compute-defaults' is called.")
@@ -419,21 +419,29 @@ Set up `compilation-exit-message-function' and run `grep-setup-hook'."
419 (format "%s <C> %s <R> <F>" grep-program grep-options))) 419 (format "%s <C> %s <R> <F>" grep-program grep-options)))
420 (unless grep-find-use-xargs 420 (unless grep-find-use-xargs
421 (setq grep-find-use-xargs 421 (setq grep-find-use-xargs
422 (if (and 422 (cond
423 (grep-probe find-program `(nil nil nil ,null-device "-print0")) 423 ((and
424 (grep-probe "xargs" `(nil nil nil "-0" "-e" "echo"))) 424 (grep-probe find-program `(nil nil nil ,null-device "-print0"))
425 'gnu))) 425 (grep-probe "xargs" `(nil nil nil "-0" "-e" "echo")))
426 'gnu)
427 (t
428 'exec))))
426 (unless grep-find-command 429 (unless grep-find-command
427 (setq grep-find-command 430 (setq grep-find-command
428 (cond ((eq grep-find-use-xargs 'gnu) 431 (cond ((eq grep-find-use-xargs 'gnu)
429 (format "%s . -type f -print0 | xargs -0 -e %s" 432 (format "%s . -type f -print0 | xargs -0 -e %s"
430 find-program grep-command)) 433 find-program grep-command))
431 (grep-find-use-xargs 434 ((eq grep-find-use-xargs 'exec)
435 (let ((cmd0 (format "%s . -type f -exec %s"
436 find-program grep-command)))
437 (cons
438 (format "%s {} %s %s"
439 cmd0 null-device
440 (shell-quote-argument ";"))
441 (1+ (length cmd0)))))
442 (t
432 (format "%s . -type f -print | xargs %s" 443 (format "%s . -type f -print | xargs %s"
433 find-program grep-command)) 444 find-program grep-command)))))
434 (t (cons (format "%s . -type f -exec %s {} %s \\;"
435 find-program grep-command null-device)
436 (+ 22 (length grep-command)))))))
437 (unless grep-find-template 445 (unless grep-find-template
438 (setq grep-find-template 446 (setq grep-find-template
439 (let ((gcmd (format "%s <C> %s <R>" 447 (let ((gcmd (format "%s <C> %s <R>"
@@ -441,11 +449,13 @@ Set up `compilation-exit-message-function' and run `grep-setup-hook'."
441 (cond ((eq grep-find-use-xargs 'gnu) 449 (cond ((eq grep-find-use-xargs 'gnu)
442 (format "%s . <X> -type f <F> -print0 | xargs -0 -e %s" 450 (format "%s . <X> -type f <F> -print0 | xargs -0 -e %s"
443 find-program gcmd)) 451 find-program gcmd))
444 (grep-find-use-xargs 452 ((eq grep-find-use-xargs 'exec)
453 (format "%s . <X> -type f <F> -exec %s {} %s %s"
454 find-program gcmd null-device
455 (shell-quote-argument ";")))
456 (t
445 (format "%s . <X> -type f <F> -print | xargs %s" 457 (format "%s . <X> -type f <F> -print | xargs %s"
446 find-program gcmd)) 458 find-program gcmd))))))))
447 (t (format "%s . <X> -type f <F> -exec %s {} %s \\;"
448 find-program gcmd null-device))))))))
449 (unless (or (not grep-highlight-matches) (eq grep-highlight-matches t)) 459 (unless (or (not grep-highlight-matches) (eq grep-highlight-matches t))
450 (setq grep-highlight-matches 460 (setq grep-highlight-matches
451 (with-temp-buffer 461 (with-temp-buffer
@@ -455,34 +465,48 @@ Set up `compilation-exit-message-function' and run `grep-setup-hook'."
455 (search-forward "--color" nil t)) 465 (search-forward "--color" nil t))
456 t))))) 466 t)))))
457 467
468(defun grep-tag-default ()
469 (or (and transient-mark-mode mark-active
470 (/= (point) (mark))
471 (buffer-substring-no-properties (point) (mark)))
472 (funcall (or find-tag-default-function
473 (get major-mode 'find-tag-default-function)
474 'find-tag-default))
475 ""))
476
458(defun grep-default-command () 477(defun grep-default-command ()
459 (let ((tag-default 478 "Compute the default grep command for C-u M-x grep to offer."
460 (shell-quote-argument 479 (let ((tag-default (shell-quote-argument (grep-tag-default)))
461 (or (funcall (or find-tag-default-function 480 ;; This a regexp to match single shell arguments.
462 (get major-mode 'find-tag-default-function) 481 ;; Could someone please add comments explaining it?
463 'find-tag-default))
464 "")))
465 (sh-arg-re "\\(\\(?:\"\\(?:[^\"]\\|\\\\\"\\)+\"\\|'[^']+'\\|[^\"' \t\n]\\)+\\)") 482 (sh-arg-re "\\(\\(?:\"\\(?:[^\"]\\|\\\\\"\\)+\"\\|'[^']+'\\|[^\"' \t\n]\\)+\\)")
466 (grep-default (or (car grep-history) grep-command))) 483 (grep-default (or (car grep-history) grep-command)))
467 ;; Replace the thing matching for with that around cursor. 484 ;; In the default command, find the arg that specifies the pattern.
468 (when (or (string-match 485 (when (or (string-match
469 (concat "[^ ]+\\s +\\(?:-[^ ]+\\s +\\)*" 486 (concat "[^ ]+\\s +\\(?:-[^ ]+\\s +\\)*"
470 sh-arg-re "\\(\\s +\\(\\S +\\)\\)?") 487 sh-arg-re "\\(\\s +\\(\\S +\\)\\)?")
471 grep-default) 488 grep-default)
472 ;; If the string is not yet complete. 489 ;; If the string is not yet complete.
473 (string-match "\\(\\)\\'" grep-default)) 490 (string-match "\\(\\)\\'" grep-default))
474 (unless (or (not (stringp buffer-file-name)) 491 ;; Maybe we will replace the pattern with the default tag.
475 (when (match-beginning 2) 492 ;; But first, maybe replace the file name pattern.
476 (save-match-data 493 (condition-case nil
477 (string-match 494 (unless (or (not (stringp buffer-file-name))
478 (wildcard-to-regexp 495 (when (match-beginning 2)
479 (file-name-nondirectory 496 (save-match-data
480 (match-string 3 grep-default))) 497 (string-match
481 (file-name-nondirectory buffer-file-name))))) 498 (wildcard-to-regexp
482 (setq grep-default (concat (substring grep-default 499 (file-name-nondirectory
483 0 (match-beginning 2)) 500 (match-string 3 grep-default)))
484 " *." 501 (file-name-nondirectory buffer-file-name)))))
485 (file-name-extension buffer-file-name)))) 502 (setq grep-default (concat (substring grep-default
503 0 (match-beginning 2))
504 " *."
505 (file-name-extension buffer-file-name))))
506 ;; In case wildcard-to-regexp gets an error
507 ;; from invalid data.
508 (error nil))
509 ;; Now replace the pattern with the default tag.
486 (replace-match tag-default t t grep-default 1)))) 510 (replace-match tag-default t t grep-default 1))))
487 511
488 512
@@ -590,15 +614,11 @@ substitution string. Note dynamic scoping of variables.")
590 614
591(defun grep-read-regexp () 615(defun grep-read-regexp ()
592 "Read regexp arg for interactive grep." 616 "Read regexp arg for interactive grep."
593 (let ((default 617 (let ((default (grep-tag-default)))
594 (or (funcall (or find-tag-default-function
595 (get major-mode 'find-tag-default-function)
596 'find-tag-default))
597 "")))
598 (read-string 618 (read-string
599 (concat "Search for" 619 (concat "Search for"
600 (if (and default (> (length default) 0)) 620 (if (and default (> (length default) 0))
601 (format " (default %s): " default) ": ")) 621 (format " (default \"%s\"): " default) ": "))
602 nil 'grep-regexp-history default))) 622 nil 'grep-regexp-history default)))
603 623
604(defun grep-read-files (regexp) 624(defun grep-read-files (regexp)
@@ -620,7 +640,9 @@ substitution string. Note dynamic scoping of variables.")
620 (cdr alias))) 640 (cdr alias)))
621 (and fn 641 (and fn
622 (let ((ext (file-name-extension fn))) 642 (let ((ext (file-name-extension fn)))
623 (and ext (concat "*." ext)))))) 643 (and ext (concat "*." ext))))
644 (car grep-files-history)
645 (car (car grep-files-aliases))))
624 (files (read-string 646 (files (read-string
625 (concat "Search for \"" regexp 647 (concat "Search for \"" regexp
626 "\" in files" 648 "\" in files"
@@ -724,18 +746,26 @@ This command shares argument histories with \\[lgrep] and \\[grep-find]."
724 (let ((command (grep-expand-template 746 (let ((command (grep-expand-template
725 grep-find-template 747 grep-find-template
726 regexp 748 regexp
727 (concat "\\( -name " 749 (concat (shell-quote-argument "(")
750 " -name "
728 (mapconcat #'shell-quote-argument 751 (mapconcat #'shell-quote-argument
729 (split-string files) 752 (split-string files)
730 " -o -name ") 753 " -o -name ")
731 " \\)") 754 " "
755 (shell-quote-argument ")"))
732 dir 756 dir
733 (and grep-find-ignored-directories 757 (and grep-find-ignored-directories
734 (concat "\\( -path '*/" 758 (concat (shell-quote-argument "(")
735 (mapconcat #'identity 759 ;; we should use shell-quote-argument here
760 " -path "
761 (mapconcat #'(lambda (dir)
762 (shell-quote-argument
763 (concat "*/" dir)))
736 grep-find-ignored-directories 764 grep-find-ignored-directories
737 "' -o -path '*/") 765 " -o -path ")
738 "' \\) -prune -o "))))) 766 " "
767 (shell-quote-argument ")")
768 " -prune -o ")))))
739 (when command 769 (when command
740 (if current-prefix-arg 770 (if current-prefix-arg
741 (setq command 771 (setq command
diff --git a/lisp/progmodes/gud.el b/lisp/progmodes/gud.el
index 97e54135a6f..84b40e8ba80 100644
--- a/lisp/progmodes/gud.el
+++ b/lisp/progmodes/gud.el
@@ -3180,7 +3180,15 @@ class of the file (using s to separate nested class ids)."
3180(defvar gdb-script-font-lock-syntactic-keywords 3180(defvar gdb-script-font-lock-syntactic-keywords
3181 '(("^document\\s-.*\\(\n\\)" (1 "< b")) 3181 '(("^document\\s-.*\\(\n\\)" (1 "< b"))
3182 ;; It would be best to change the \n in front, but it's more difficult. 3182 ;; It would be best to change the \n in front, but it's more difficult.
3183 ("^en\\(d\\)\\>" (1 "> b")))) 3183 ("^end\\>"
3184 (0 (progn
3185 (unless (eq (match-beginning 0) (point-min))
3186 (put-text-property (1- (match-beginning 0)) (match-beginning 0)
3187 'syntax-table (eval-when-compile
3188 (string-to-syntax "> b")))
3189 (put-text-property (1- (match-beginning 0)) (match-end 0)
3190 'font-lock-multiline t)
3191 nil))))))
3184 3192
3185(defun gdb-script-font-lock-syntactic-face (state) 3193(defun gdb-script-font-lock-syntactic-face (state)
3186 (cond 3194 (cond
diff --git a/lisp/progmodes/python.el b/lisp/progmodes/python.el
index 9636f7eaeae..c38a6e82f83 100644
--- a/lisp/progmodes/python.el
+++ b/lisp/progmodes/python.el
@@ -9,19 +9,19 @@
9 9
10;; This file is part of GNU Emacs. 10;; This file is part of GNU Emacs.
11 11
12;; This file is free software; you can redistribute it and/or modify 12;; GNU Emacs is free software; you can redistribute it and/or modify
13;; it under the terms of the GNU General Public License as published by 13;; it under the terms of the GNU General Public License as published by
14;; the Free Software Foundation; either version 2, or (at your option) 14;; the Free Software Foundation; either version 2, or (at your option)
15;; any later version. 15;; any later version.
16 16
17;; This file is distributed in the hope that it will be useful, 17;; GNU Emacs is distributed in the hope that it will be useful,
18;; but WITHOUT ANY WARRANTY; without even the implied warranty of 18;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20;; GNU General Public License for more details. 20;; GNU General Public License for more details.
21 21
22;; You should have received a copy of the GNU General Public License 22;; You should have received a copy of the GNU General Public License
23;; along with GNU Emacs; see the file COPYING. If not, write to 23;; along with GNU Emacs; see the file COPYING. If not, write to the
24;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, 24;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25;; Boston, MA 02110-1301, USA. 25;; Boston, MA 02110-1301, USA.
26 26
27;;; Commentary: 27;;; Commentary:
@@ -32,41 +32,44 @@
32;; maintained with Python. That isn't covered by an FSF copyright 32;; maintained with Python. That isn't covered by an FSF copyright
33;; assignment, unlike this code, and seems not to be well-maintained 33;; assignment, unlike this code, and seems not to be well-maintained
34;; for Emacs (though I've submitted fixes). This mode is rather 34;; for Emacs (though I've submitted fixes). This mode is rather
35;; simpler and is, perhaps, better in other ways. In particular, 35;; simpler and is better in other ways. In particular, using the
36;; using the syntax functions with text properties maintained by 36;; syntax functions with text properties maintained by font-lock makes
37;; font-lock should make it more correct with arbitrary string and 37;; it more correct with arbitrary string and comment contents.
38;; comment contents.
39 38
40;; This doesn't implement all the facilities of python-mode.el. Some 39;; This doesn't implement all the facilities of python-mode.el. Some
41;; just need doing, e.g. catching exceptions in the inferior Python 40;; just need doing, e.g. catching exceptions in the inferior Python
42;; buffer (but see M-x pdb for debugging). [Actually, the use of 41;; buffer (but see M-x pdb for debugging). [Actually, the use of
43;; `compilation-minor-mode' now is probably enough for that.] Others 42;; `compilation-shell-minor-mode' now is probably enough for that.]
44;; don't seem appropriate. For instance, `forward-into-nomenclature' 43;; Others don't seem appropriate. For instance,
45;; should be done separately, since it's not specific to Python, and 44;; `forward-into-nomenclature' should be done separately, since it's
46;; I've installed a minor mode to do the job properly in Emacs 22. 45;; not specific to Python, and I've installed a minor mode to do the
46;; job properly in Emacs 23. [CC mode 5.31 contains an incompatible
47;; feature, `c-subword-mode' which is intended to have a similar
48;; effect, but actually only affects word-oriented keybindings.]
49
47;; Other things seem more natural or canonical here, e.g. the 50;; Other things seem more natural or canonical here, e.g. the
48;; {beginning,end}-of-defun implementation dealing with nested 51;; {beginning,end}-of-defun implementation dealing with nested
49;; definitions, and the inferior mode following `cmuscheme'. The 52;; definitions, and the inferior mode following `cmuscheme'. (The
50;; inferior mode can find the source of errors from 53;; inferior mode can find the source of errors from
51;; `python-send-region' & al via `compilation-minor-mode'. Successive 54;; `python-send-region' & al via `compilation-shell-minor-mode'.)
52;; TABs cycle between possible indentations for the line. There is 55;; There is (limited) symbol completion using lookup in Python and
53;; symbol completion using lookup in Python. 56;; Eldoc support also using the inferior process. Successive TABs
57;; cycle between possible indentations for the line.
54 58
55;; Even where it has similar facilities, this is incompatible with 59;; Even where it has similar facilities, this mode is incompatible
56;; python-mode.el in various respects. For instance, various key 60;; with python-mode.el in some respects. For instance, various key
57;; bindings are changed to obey Emacs conventions, and things like 61;; bindings are changed to obey Emacs conventions.
58;; marking blocks and `beginning-of-defun' behave differently.
59 62
60;; TODO: See various Fixmes below. 63;; TODO: See various Fixmes below.
61 64
62;;; Code: 65;;; Code:
63 66
64;; It's messy to autoload the relevant comint functions so that comint
65;; is only required when inferior Python is used.
66(require 'comint)
67(eval-when-compile 67(eval-when-compile
68 (require 'cl)
68 (require 'compile) 69 (require 'compile)
69 (autoload 'info-lookup-maybe-add-help "info-look")) 70 (require 'comint))
71
72(autoload 'comint-mode "comint")
70 73
71(defgroup python nil 74(defgroup python nil
72 "Silly walks in the Python language." 75 "Silly walks in the Python language."
@@ -84,31 +87,37 @@
84;;;; Font lock 87;;;; Font lock
85 88
86(defvar python-font-lock-keywords 89(defvar python-font-lock-keywords
87 `(,(rx (and word-start 90 `(,(rx symbol-start
88 ;; From v 2.3 reference. 91 ;; From v 2.4 reference.
89 ;; def and class dealt with separately below 92 ;; def and class dealt with separately below
90 (or "and" "assert" "break" "continue" "del" "elif" "else" 93 (or "and" "assert" "break" "continue" "del" "elif" "else"
91 "except" "exec" "finally" "for" "from" "global" "if" 94 "except" "exec" "finally" "for" "from" "global" "if"
92 "import" "in" "is" "lambda" "not" "or" "pass" "print" 95 "import" "in" "is" "lambda" "not" "or" "pass" "print"
93 "raise" "return" "try" "while" "yield" 96 "raise" "return" "try" "while" "yield"
94 ;; Future keywords 97 ;; Future keywords
95 "as" "None") 98 "as" "None")
96 word-end)) 99 symbol-end)
97 (,(rx (and word-start (group "class") (1+ space) (group (1+ word)))) 100 ;; Definitions
98 (1 font-lock-keyword-face) (2 font-lock-type-face)) 101 (,(rx symbol-start (group "class") (1+ space) (group (1+ (or word ?_))))
99 (,(rx (and word-start (group "def") (1+ space) (group (1+ word)))) 102 (1 font-lock-keyword-face) (2 font-lock-type-face))
100 (1 font-lock-keyword-face) (2 font-lock-function-name-face)))) 103 (,(rx symbol-start (group "def") (1+ space) (group (1+ (or word ?_))))
104 (1 font-lock-keyword-face) (2 font-lock-function-name-face))
105 ;; Top-level assignments are worth highlighting.
106 (,(rx line-start (group (1+ (or word ?_))) (0+ space) "=")
107 (1 font-lock-variable-name-face))
108 (,(rx "@" (1+ (or word ?_))) ; decorators
109 (0 font-lock-preprocessor-face))))
101 110
102(defconst python-font-lock-syntactic-keywords 111(defconst python-font-lock-syntactic-keywords
103 ;; Make outer chars of matching triple-quote sequences into generic 112 ;; Make outer chars of matching triple-quote sequences into generic
104 ;; string delimiters. Fixme: Is there a better way? 113 ;; string delimiters. Fixme: Is there a better way?
105 `((,(rx (and (or line-start buffer-start (not (syntax escape))) ; avoid escaped 114 `((,(rx (or line-start buffer-start
106 ; leading quote 115 (not (syntax escape))) ; avoid escaped leading quote
107 (group (optional (any "uUrR"))) ; prefix gets syntax property 116 (group (optional (any "uUrR"))) ; prefix gets syntax property
108 (optional (any "rR")) ; possible second prefix 117 (optional (any "rR")) ; possible second prefix
109 (group (syntax string-quote)) ; maybe gets property 118 (group (syntax string-quote)) ; maybe gets property
110 (backref 2) ; per first quote 119 (backref 2) ; per first quote
111 (group (backref 2)))) ; maybe gets property 120 (group (backref 2))) ; maybe gets property
112 (1 (python-quote-syntax 1)) 121 (1 (python-quote-syntax 1))
113 (2 (python-quote-syntax 2)) 122 (2 (python-quote-syntax 2))
114 (3 (python-quote-syntax 3))) 123 (3 (python-quote-syntax 3)))
@@ -132,6 +141,8 @@ Used for syntactic keywords. N is the match number (1, 2 or 3)."
132 ;; x = ''' """ ' a 141 ;; x = ''' """ ' a
133 ;; ''' 142 ;; '''
134 ;; x '"""' x """ \"""" x 143 ;; x '"""' x """ \"""" x
144 ;; Fixme: """""" goes wrong (due to syntax-ppss not getting the string
145 ;; fence context).
135 (save-excursion 146 (save-excursion
136 (goto-char (match-beginning 0)) 147 (goto-char (match-beginning 0))
137 (cond 148 (cond
@@ -140,19 +151,17 @@ Used for syntactic keywords. N is the match number (1, 2 or 3)."
140 (let ((syntax (syntax-ppss))) 151 (let ((syntax (syntax-ppss)))
141 (when (eq t (nth 3 syntax)) ; after unclosed fence 152 (when (eq t (nth 3 syntax)) ; after unclosed fence
142 (goto-char (nth 8 syntax)) ; fence position 153 (goto-char (nth 8 syntax)) ; fence position
143 ;; Skip any prefix. 154 (skip-chars-forward "uUrR") ; skip any prefix
144 (if (memq (char-after) '(?u ?U ?R ?r))
145 (skip-chars-forward "uUrR"))
146 ;; Is it a matching sequence? 155 ;; Is it a matching sequence?
147 (if (eq (char-after) (char-after (match-beginning 2))) 156 (if (eq (char-after) (char-after (match-beginning 2)))
148 (eval-when-compile (string-to-syntax "|")))))) 157 (eval-when-compile (string-to-syntax "|"))))))
149 ;; Consider property for initial char, accounting for prefixes. 158 ;; Consider property for initial char, accounting for prefixes.
150 ((or (and (= n 2) ; not prefix 159 ((or (and (= n 2) ; leading quote (not prefix)
151 (= (match-beginning 1) (match-end 1))) ; prefix is null 160 (= (match-beginning 1) (match-end 1))) ; prefix is null
152 (and (= n 1) ; prefix 161 (and (= n 1) ; prefix
153 (/= (match-beginning 1) (match-end 1)))) ; non-empty 162 (/= (match-beginning 1) (match-end 1)))) ; non-empty
154 (unless (eq 'string (syntax-ppss-context (syntax-ppss))) 163 (unless (eq 'string (syntax-ppss-context (syntax-ppss)))
155 (eval-when-compile (string-to-syntax "|")))) 164 (eval-when-compile (string-to-syntax "|"))))
156 ;; Otherwise (we're in a non-matching string) the property is 165 ;; Otherwise (we're in a non-matching string) the property is
157 ;; nil, which is OK. 166 ;; nil, which is OK.
158 ))) 167 )))
@@ -204,23 +213,37 @@ Used for syntactic keywords. N is the match number (1, 2 or 3)."
204 (define-key map "\C-c\C-l" 'python-load-file) ; a la cmuscheme 213 (define-key map "\C-c\C-l" 'python-load-file) ; a la cmuscheme
205 (substitute-key-definition 'complete-symbol 'python-complete-symbol 214 (substitute-key-definition 'complete-symbol 'python-complete-symbol
206 map global-map) 215 map global-map)
207 ;; Fixme: Add :help to menu. 216 (define-key map "\C-c\C-i" 'python-find-imports)
217 (define-key map "\C-c\C-t" 'python-expand-template)
208 (easy-menu-define python-menu map "Python Mode menu" 218 (easy-menu-define python-menu map "Python Mode menu"
209 '("Python" 219 `("Python"
210 ["Shift region left" python-shift-left :active mark-active] 220 :help "Python-specific Features"
211 ["Shift region right" python-shift-right :active mark-active] 221 ["Shift region left" python-shift-left :active mark-active
222 :help "Shift by a single indentation step"]
223 ["Shift region right" python-shift-right :active mark-active
224 :help "Shift by a single indentation step"]
212 "-" 225 "-"
213 ["Mark block" python-mark-block] 226 ["Mark block" python-mark-block
227 :help "Mark innermost block around point"]
214 ["Mark def/class" mark-defun 228 ["Mark def/class" mark-defun
215 :help "Mark innermost definition around point"] 229 :help "Mark innermost definition around point"]
216 "-" 230 "-"
217 ["Start of block" python-beginning-of-block] 231 ["Start of block" python-beginning-of-block
218 ["End of block" python-end-of-block] 232 :help "Go to start of innermost definition around point"]
233 ["End of block" python-end-of-block
234 :help "Go to end of innermost definition around point"]
219 ["Start of def/class" beginning-of-defun 235 ["Start of def/class" beginning-of-defun
220 :help "Go to start of innermost definition around point"] 236 :help "Go to start of innermost definition around point"]
221 ["End of def/class" end-of-defun 237 ["End of def/class" end-of-defun
222 :help "Go to end of innermost definition around point"] 238 :help "Go to end of innermost definition around point"]
223 "-" 239 "-"
240 ("Templates..."
241 :help "Expand templates for compound statements"
242 :filter (lambda (&rest junk)
243 (mapcar (lambda (elt)
244 (vector (car elt) (cdr elt) t))
245 python-skeletons))) ; defined later
246 "-"
224 ["Start interpreter" run-python 247 ["Start interpreter" run-python
225 :help "Run `inferior' Python in separate buffer"] 248 :help "Run `inferior' Python in separate buffer"]
226 ["Import/reload file" python-load-file 249 ["Import/reload file" python-load-file
@@ -233,12 +256,23 @@ Used for syntactic keywords. N is the match number (1, 2 or 3)."
233 :help "Evaluate current definition in inferior Python session"] 256 :help "Evaluate current definition in inferior Python session"]
234 ["Switch to interpreter" python-switch-to-python 257 ["Switch to interpreter" python-switch-to-python
235 :help "Switch to inferior Python buffer"] 258 :help "Switch to inferior Python buffer"]
259 ["Set default process" python-set-proc
260 :help "Make buffer's inferior process the default"
261 :active (buffer-live-p python-buffer)]
236 ["Check file" python-check :help "Run pychecker"] 262 ["Check file" python-check :help "Run pychecker"]
237 ["Debugger" pdb :help "Run pdb under GUD"] 263 ["Debugger" pdb :help "Run pdb under GUD"]
238 "-" 264 "-"
239 ["Help on symbol" python-describe-symbol 265 ["Help on symbol" python-describe-symbol
240 :help "Use pydoc on symbol at point"])) 266 :help "Use pydoc on symbol at point"]
267 ["Complete symbol" python-complete-symbol
268 :help "Complete (qualified) symbol before point"]
269 ["Update imports" python-find-imports
270 :help "Update list of top-level imports for completion"]))
241 map)) 271 map))
272;; Fixme: add toolbar stuff for useful things like symbol help, send
273;; region, at least. (Shouldn't be specific to Python, obviously.)
274;; eric has items including: (un)indent, (un)comment, restart script,
275;; run script, debug script; also things for profiling, unit testing.
242 276
243(defvar python-mode-syntax-table 277(defvar python-mode-syntax-table
244 (let ((table (make-syntax-table))) 278 (let ((table (make-syntax-table)))
@@ -263,7 +297,8 @@ Used for syntactic keywords. N is the match number (1, 2 or 3)."
263 297
264(defsubst python-in-string/comment () 298(defsubst python-in-string/comment ()
265 "Return non-nil if point is in a Python literal (a comment or string)." 299 "Return non-nil if point is in a Python literal (a comment or string)."
266 (syntax-ppss-context (syntax-ppss))) 300 ;; We don't need to save the match data.
301 (nth 8 (syntax-ppss)))
267 302
268(defconst python-space-backslash-table 303(defconst python-space-backslash-table
269 (let ((table (copy-syntax-table python-mode-syntax-table))) 304 (let ((table (copy-syntax-table python-mode-syntax-table)))
@@ -273,13 +308,21 @@ Used for syntactic keywords. N is the match number (1, 2 or 3)."
273 308
274(defun python-skip-comments/blanks (&optional backward) 309(defun python-skip-comments/blanks (&optional backward)
275 "Skip comments and blank lines. 310 "Skip comments and blank lines.
276BACKWARD non-nil means go backwards, otherwise go forwards. Backslash is 311BACKWARD non-nil means go backwards, otherwise go forwards.
277treated as whitespace so that continued blank lines are skipped. 312Backslash is treated as whitespace so that continued blank lines
278Doesn't move out of comments -- should be outside or at end of line." 313are skipped. Doesn't move out of comments -- should be outside
279 (with-syntax-table python-space-backslash-table 314or at end of line."
280 (forward-comment (if backward 315 (let ((arg (if backward
281 most-negative-fixnum 316 ;; If we're in a comment (including on the trailing
282 most-positive-fixnum)))) 317 ;; newline), forward-comment doesn't move backwards out
318 ;; of it. Don't set the syntax table round this bit!
319 (let ((syntax (syntax-ppss)))
320 (if (nth 4 syntax)
321 (goto-char (nth 8 syntax)))
322 (- (point-max)))
323 (point-max))))
324 (with-syntax-table python-space-backslash-table
325 (forward-comment arg))))
283 326
284(defun python-backslash-continuation-line-p () 327(defun python-backslash-continuation-line-p ()
285 "Non-nil if preceding line ends with backslash that is not in a comment." 328 "Non-nil if preceding line ends with backslash that is not in a comment."
@@ -289,12 +332,17 @@ Doesn't move out of comments -- should be outside or at end of line."
289(defun python-continuation-line-p () 332(defun python-continuation-line-p ()
290 "Return non-nil if current line continues a previous one. 333 "Return non-nil if current line continues a previous one.
291The criteria are that the previous line ends in a backslash outside 334The criteria are that the previous line ends in a backslash outside
292comments and strings, or that the bracket/paren nesting depth is nonzero." 335comments and strings, or that point is within brackets/parens."
293 (or (and (eq ?\\ (char-before (line-end-position 0))) 336 (or (python-backslash-continuation-line-p)
294 (not (syntax-ppss-context (syntax-ppss)))) 337 (let ((depth (syntax-ppss-depth
295 (< 0 (syntax-ppss-depth 338 (save-excursion ; syntax-ppss with arg changes point
296 (save-excursion ; syntax-ppss with arg changes point 339 (syntax-ppss (line-beginning-position))))))
297 (syntax-ppss (line-beginning-position))))))) 340 (or (> depth 0)
341 (if (< depth 0) ; Unbalanced brackets -- act locally
342 (save-excursion
343 (condition-case ()
344 (progn (backward-up-list) t) ; actually within brackets
345 (error nil))))))))
298 346
299(defun python-comment-line-p () 347(defun python-comment-line-p ()
300 "Return non-nil iff current line has only a comment." 348 "Return non-nil iff current line has only a comment."
@@ -304,6 +352,12 @@ comments and strings, or that the bracket/paren nesting depth is nonzero."
304 (back-to-indentation) 352 (back-to-indentation)
305 (looking-at (rx (or (syntax comment-start) line-end)))))) 353 (looking-at (rx (or (syntax comment-start) line-end))))))
306 354
355(defun python-blank-line-p ()
356 "Return non-nil iff current line is blank."
357 (save-excursion
358 (beginning-of-line)
359 (looking-at "\\s-*$")))
360
307(defun python-beginning-of-string () 361(defun python-beginning-of-string ()
308 "Go to beginning of string around point. 362 "Go to beginning of string around point.
309Do nothing if not in string." 363Do nothing if not in string."
@@ -316,83 +370,70 @@ Do nothing if not in string."
316BOS non-nil means point is known to be at beginning of statement." 370BOS non-nil means point is known to be at beginning of statement."
317 (save-excursion 371 (save-excursion
318 (unless bos (python-beginning-of-statement)) 372 (unless bos (python-beginning-of-statement))
319 (and (not (python-comment-line-p)) 373 (looking-at (rx (and (or "if" "else" "elif" "while" "for" "def"
320 (re-search-forward (rx (and ?: (0+ space) 374 "class" "try" "except" "finally")
321 (optional (and (syntax comment-start) 375 symbol-end)))))
322 (0+ not-newline)))
323 line-end))
324 (save-excursion (python-end-of-statement))
325 t)
326 (not (progn (goto-char (match-beginning 0))
327 (python-in-string/comment))))))
328 376
329(defun python-close-block-statement-p (&optional bos) 377(defun python-close-block-statement-p (&optional bos)
330 "Return non-nil if current line is a statement closing a block. 378 "Return non-nil if current line is a statement closing a block.
331BOS non-nil means point is at beginning of statement. 379BOS non-nil means point is at beginning of statement.
332The criteria are that the line isn't a comment or in string and starts with 380The criteria are that the line isn't a comment or in string and
333keyword `raise', `break', `continue' or `pass'." 381 starts with keyword `raise', `break', `continue' or `pass'."
334 (save-excursion 382 (save-excursion
335 (unless bos (python-beginning-of-statement)) 383 (unless bos (python-beginning-of-statement))
336 (back-to-indentation) 384 (back-to-indentation)
337 (looking-at (rx (and (or "return" "raise" "break" "continue" "pass") 385 (looking-at (rx (or "return" "raise" "break" "continue" "pass")
338 symbol-end))))) 386 symbol-end))))
339 387
340(defun python-outdent-p () 388(defun python-outdent-p ()
341 "Return non-nil if current line should outdent a level." 389 "Return non-nil if current line should outdent a level."
342 (save-excursion 390 (save-excursion
343 (back-to-indentation) 391 (back-to-indentation)
344 (and (looking-at (rx (and (or (and (or "else" "finally") symbol-end) 392 (and (looking-at (rx (and (or "else" "finally" "except" "elif")
345 (and (or "except" "elif") symbol-end 393 symbol-end)))
346 (1+ (not (any ?:))))) 394 (not (python-in-string/comment))
347 (optional space) ":" (optional space)
348 (or (syntax comment-start) line-end))))
349 (progn (end-of-line)
350 (not (python-in-string/comment)))
351 ;; Ensure there's a previous statement and move to it. 395 ;; Ensure there's a previous statement and move to it.
352 (zerop (python-previous-statement)) 396 (zerop (python-previous-statement))
353 (not (python-close-block-statement-p t)) 397 (not (python-close-block-statement-p t))
354 ;; Fixme: check this 398 ;; Fixme: check this
355 (not (looking-at (rx (and (or (and (or "if" "elif" "except" 399 (not (python-open-block-statement-p)))))
356 "for" "while")
357 symbol-end (1+ (not (any ?:))))
358 (and "try" symbol-end))
359 (optional space) ":" (optional space)
360 (or (syntax comment-start) line-end)))))
361 (progn (end-of-line)
362 (not (python-in-string/comment))))))
363 400
364;;;; Indentation. 401;;;; Indentation.
365 402
366(defcustom python-indent 4 403(defcustom python-indent 4
367 "*Number of columns for a unit of indentation in Python mode. 404 "Number of columns for a unit of indentation in Python mode.
368See also `\\[python-guess-indent]'" 405See also `\\[python-guess-indent]'"
369 :group 'python 406 :group 'python
370 :type 'integer) 407 :type 'integer)
371 408
372(defcustom python-guess-indent t 409(defcustom python-guess-indent t
373 "*Non-nil means Python mode guesses `python-indent' for the buffer." 410 "Non-nil means Python mode guesses `python-indent' for the buffer."
374 :type 'boolean 411 :type 'boolean
375 :group 'python) 412 :group 'python)
376 413
377(defcustom python-indent-string-contents t 414(defcustom python-indent-string-contents t
378 "*Non-nil means indent contents of multi-line strings together. 415 "Non-nil means indent contents of multi-line strings together.
379This means indent them the same as the preceding non-blank line. 416This means indent them the same as the preceding non-blank line.
380Otherwise indent them to column zero." 417Otherwise preserve their indentation.
418
419This only applies to `doc' strings, i.e. those that form statements;
420the indentation is preserved in others."
381 :type '(choice (const :tag "Align with preceding" t) 421 :type '(choice (const :tag "Align with preceding" t)
382 (const :tag "Indent to column 0" nil)) 422 (const :tag "Preserve indentation" nil))
383 :group 'python) 423 :group 'python)
384 424
385(defcustom python-honour-comment-indentation nil 425(defcustom python-honour-comment-indentation nil
386 "Non-nil means indent relative to preceding comment line. 426 "Non-nil means indent relative to preceding comment line.
387Only do this for comments where the leading comment character is followed 427Only do this for comments where the leading comment character is
388by space. This doesn't apply to comment lines, which are always indented 428followed by space. This doesn't apply to comment lines, which
389in lines with preceding comments." 429are always indented in lines with preceding comments."
390 :type 'boolean 430 :type 'boolean
391 :group 'python) 431 :group 'python)
392 432
393(defcustom python-continuation-offset 4 433(defcustom python-continuation-offset 4
394 "*Number of columns of additional indentation for continuation lines. 434 "Number of columns of additional indentation for continuation lines.
395Continuation lines follow a backslash-terminated line starting a statement." 435Continuation lines follow a backslash-terminated line starting a
436statement."
396 :group 'python 437 :group 'python
397 :type 'integer) 438 :type 'integer)
398 439
@@ -406,9 +447,9 @@ Set `python-indent' locally to the value guessed."
406 (goto-char (point-min)) 447 (goto-char (point-min))
407 (let (done indent) 448 (let (done indent)
408 (while (and (not done) (not (eobp))) 449 (while (and (not done) (not (eobp)))
409 (when (and (re-search-forward (rx (and ?: (0+ space) 450 (when (and (re-search-forward (rx ?: (0+ space)
410 (or (syntax comment-start) 451 (or (syntax comment-start)
411 line-end))) 452 line-end))
412 nil 'move) 453 nil 'move)
413 (python-open-block-statement-p)) 454 (python-open-block-statement-p))
414 (save-excursion 455 (save-excursion
@@ -425,8 +466,21 @@ Set `python-indent' locally to the value guessed."
425 (setq indent-tabs-mode nil))) 466 (setq indent-tabs-mode nil)))
426 indent))))) 467 indent)))))
427 468
469;; Alist of possible indentations and start of statement they would
470;; close. Used in indentation cycling (below).
471(defvar python-indent-list nil
472 "Internal use.")
473;; Length of the above
474(defvar python-indent-list-length nil
475 "Internal use.")
476;; Current index into the alist.
477(defvar python-indent-index nil
478 "Internal use.")
479
428(defun python-calculate-indentation () 480(defun python-calculate-indentation ()
429 "Calculate Python indentation for line at point." 481 "Calculate Python indentation for line at point."
482 (setq python-indent-list nil
483 python-indent-list-length 1)
430 (save-excursion 484 (save-excursion
431 (beginning-of-line) 485 (beginning-of-line)
432 (let ((syntax (syntax-ppss)) 486 (let ((syntax (syntax-ppss))
@@ -434,17 +488,25 @@ Set `python-indent' locally to the value guessed."
434 (cond 488 (cond
435 ((eq 'string (syntax-ppss-context syntax)) ; multi-line string 489 ((eq 'string (syntax-ppss-context syntax)) ; multi-line string
436 (if (not python-indent-string-contents) 490 (if (not python-indent-string-contents)
437 0 491 (current-indentation)
438 (save-excursion 492 ;; Only respect `python-indent-string-contents' in doc
493 ;; strings (defined as those which form statements).
494 (if (not (save-excursion
495 (python-beginning-of-statement)
496 (looking-at (rx (or (syntax string-delimiter)
497 (syntax string-quote))))))
498 (current-indentation)
439 ;; Find indentation of preceding non-blank line within string. 499 ;; Find indentation of preceding non-blank line within string.
440 (setq start (nth 8 syntax)) 500 (setq start (nth 8 syntax))
441 (forward-line -1) 501 (forward-line -1)
442 (while (and (< start (point)) (looking-at "\\s-*$")) 502 (while (and (< start (point)) (looking-at "\\s-*$"))
443 (forward-line -1)) 503 (forward-line -1))
444 (current-indentation)))) 504 (current-indentation))))
445 ((python-continuation-line-p) 505 ((python-continuation-line-p) ; after backslash, or bracketed
446 (let ((point (point)) 506 (let ((point (point))
447 (open-start (cadr syntax))) 507 (open-start (cadr syntax))
508 (backslash (python-backslash-continuation-line-p))
509 (colon (eq ?: (char-before (1- (line-beginning-position))))))
448 (if open-start 510 (if open-start
449 ;; Inside bracketed expression. 511 ;; Inside bracketed expression.
450 (progn 512 (progn
@@ -458,7 +520,11 @@ Set `python-indent' locally to the value guessed."
458 (backward-sexp) 520 (backward-sexp)
459 (< (point) point)) 521 (< (point) point))
460 (error nil)))) 522 (error nil))))
461 (current-column) 523 ;; Extra level if we're backslash-continued or
524 ;; following a key.
525 (if (or backslash colon)
526 (+ python-indent (current-column))
527 (current-column))
462 ;; Otherwise indent relative to statement start, one 528 ;; Otherwise indent relative to statement start, one
463 ;; level per bracketing level. 529 ;; level per bracketing level.
464 (goto-char (1+ open-start)) 530 (goto-char (1+ open-start))
@@ -472,112 +538,153 @@ Set `python-indent' locally to the value guessed."
472 (current-indentation) 538 (current-indentation)
473 ;; First continuation line. Indent one step, with an 539 ;; First continuation line. Indent one step, with an
474 ;; extra one if statement opens a block. 540 ;; extra one if statement opens a block.
475 (save-excursion 541 (python-beginning-of-statement)
476 (python-beginning-of-statement) 542 (+ (current-indentation) python-continuation-offset
477 (+ (current-indentation) python-continuation-offset 543 (if (python-open-block-statement-p t)
478 (if (python-open-block-statement-p t) 544 python-indent
479 python-indent 545 0))))))
480 0)))))))
481 ((bobp) 0) 546 ((bobp) 0)
482 ;; Fixme: Like python-mode.el; not convinced by this. 547 ;; Fixme: Like python-mode.el; not convinced by this.
483 ((looking-at (rx (and (0+ space) (syntax comment-start) 548 ((looking-at (rx (0+ space) (syntax comment-start)
484 (not (any " \t\n"))))) ; non-indentable comment 549 (not (any " \t\n")))) ; non-indentable comment
485 (current-indentation)) 550 (current-indentation))
486 (t (let ((point (point))) 551 (t (if python-honour-comment-indentation
487 (if python-honour-comment-indentation 552 ;; Back over whitespace, newlines, non-indentable comments.
488 ;; Back over whitespace, newlines, non-indentable comments. 553 (catch 'done
489 (catch 'done 554 (while t
490 (while t 555 (if (cond ((bobp))
491 (if (cond ((bobp)) 556 ;; not at comment start
492 ;; not at comment start 557 ((not (forward-comment -1))
493 ((not (forward-comment -1)) 558 (python-beginning-of-statement)
494 (python-beginning-of-statement) 559 t)
495 t) 560 ;; trailing comment
496 ;; trailing comment 561 ((/= (current-column) (current-indentation))
497 ((/= (current-column) (current-indentation)) 562 (python-beginning-of-statement)
498 (python-beginning-of-statement) 563 t)
499 t) 564 ;; indentable comment like python-mode.el
500 ;; indentable comment like python-mode.el 565 ((and (looking-at (rx (syntax comment-start)
501 ((and (looking-at (rx (and (syntax comment-start) 566 (or space line-end)))
502 (or space line-end)))) 567 (/= 0 (current-column)))))
503 (/= 0 (current-column))))) 568 (throw 'done t)))))
504 (throw 'done t)))) 569 (python-indentation-levels)
505 ;; Else back over all comments. 570 ;; Prefer to indent comments with an immediately-following
506 (python-skip-comments/blanks t) 571 ;; statement, e.g.
507 (python-beginning-of-statement)) 572 ;; ...
508 ;; don't lose on bogus outdent 573 ;; # ...
509 (max 0 (+ (current-indentation) 574 ;; def ...
510 (or (cond ((python-open-block-statement-p t) 575 (when (and (> python-indent-list-length 1)
511 python-indent) 576 (python-comment-line-p))
512 ((python-close-block-statement-p t) 577 (forward-line)
513 (- python-indent))) 578 (unless (python-comment-line-p)
514 (progn (goto-char point) 579 (let ((elt (assq (current-indentation) python-indent-list)))
515 (if (python-outdent-p) 580 (setq python-indent-list
516 (- python-indent))) 581 (nconc (delete elt python-indent-list)
517 0))))))))) 582 (list elt))))))
518 583 (caar (last python-indent-list)))))))
519(defun python-comment-indent ()
520 "`comment-indent-function' for Python."
521 ;; If previous non-blank line was a comment, use its indentation.
522 ;; FIXME: This seems unnecessary since the default code delegates to
523 ;; indent-according-to-mode. --Stef
524 (unless (bobp)
525 (save-excursion
526 (forward-comment -1)
527 (if (eq ?# (char-after)) (current-column)))))
528 584
529;;;; Cycling through the possible indentations with successive TABs. 585;;;; Cycling through the possible indentations with successive TABs.
530 586
531;; These don't need to be buffer-local since they're only relevant 587;; These don't need to be buffer-local since they're only relevant
532;; during a cycle. 588;; during a cycle.
533 589
534;; Alist of possible indentations and start of statement they would close.
535(defvar python-indent-list nil
536 "Internal use.")
537;; Length of the above
538(defvar python-indent-list-length nil
539 "Internal use.")
540;; Current index into the alist.
541(defvar python-indent-index nil
542 "Internal use.")
543
544(defun python-initial-text () 590(defun python-initial-text ()
545 "Text of line following indentation and ignoring any trailing comment." 591 "Text of line following indentation and ignoring any trailing comment."
546 (buffer-substring (+ (line-beginning-position) (current-indentation)) 592 (save-excursion
547 (save-excursion 593 (buffer-substring (progn
548 (end-of-line) 594 (back-to-indentation)
549 (forward-comment -1) 595 (point))
550 (point)))) 596 (progn
597 (end-of-line)
598 (forward-comment -1)
599 (point)))))
600
601(defconst python-block-pairs
602 '(("else" "if" "elif" "while" "for" "try" "except")
603 ("elif" "if" "elif")
604 ("except" "try" "except")
605 ("finally" "try"))
606 "Alist of keyword matches.
607The car of an element is a keyword introducing a statement which
608can close a block opened by a keyword in the cdr.")
609
610(defun python-first-word ()
611 "Return first word (actually symbol) on the line."
612 (save-excursion
613 (back-to-indentation)
614 (current-word t)))
551 615
552(defun python-indentation-levels () 616(defun python-indentation-levels ()
553 "Return a list of possible indentations for this line. 617 "Return a list of possible indentations for this line.
618It is assumed not to be a continuation line or in a multi-line string.
554Includes the default indentation and those which would close all 619Includes the default indentation and those which would close all
555enclosing blocks. Assumes the line has already been indented per 620enclosing blocks. Elements of the list are actually pairs:
556`python-indent-line'. Elements of the list are actually pairs:
557\(INDENTATION . TEXT), where TEXT is the initial text of the 621\(INDENTATION . TEXT), where TEXT is the initial text of the
558corresponding block opening (or nil)." 622corresponding block opening (or nil)."
559 (save-excursion 623 (save-excursion
560 (let ((levels (list (cons (current-indentation) 624 (let ((initial "")
561 (save-excursion 625 levels indent)
562 (if (python-beginning-of-block) 626 ;; Only one possibility immediately following a block open
563 (python-initial-text))))))) 627 ;; statement, assuming it doesn't have a `suite' on the same line.
564 ;; Only one possibility if we immediately follow a block open or 628 (cond
565 ;; are in a continuation line. 629 ((save-excursion (and (python-previous-statement)
566 (unless (or (python-continuation-line-p) 630 (python-open-block-statement-p t)
567 (save-excursion (and (python-previous-statement) 631 (setq indent (current-indentation))
568 (python-open-block-statement-p t)))) 632 ;; Check we don't have something like:
569 (while (python-beginning-of-block) 633 ;; if ...: ...
570 (push (cons (current-indentation) (python-initial-text)) 634 (if (progn (python-end-of-statement)
571 levels))) 635 (python-skip-comments/blanks t)
572 levels))) 636 (eq ?: (char-before)))
637 (setq indent (+ python-indent indent)))))
638 (push (cons indent initial) levels))
639 ;; Only one possibility for comment line immediately following
640 ;; another.
641 ((save-excursion
642 (when (python-comment-line-p)
643 (forward-line -1)
644 (if (python-comment-line-p)
645 (push (cons (current-indentation) initial) levels)))))
646 ;; Fixme: Maybe have a case here which indents (only) first
647 ;; line after a lambda.
648 (t
649 (let ((start (car (assoc (python-first-word) python-block-pairs))))
650 (python-previous-statement)
651 ;; Is this a valid indentation for the line of interest?
652 (unless (or (if start ; potentially only outdentable
653 ;; Check for things like:
654 ;; if ...: ...
655 ;; else ...:
656 ;; where the second line need not be outdented.
657 (not (member (python-first-word)
658 (cdr (assoc start
659 python-block-pairs)))))
660 ;; Not sensible to indent to the same level as
661 ;; previous `return' &c.
662 (python-close-block-statement-p))
663 (push (cons (current-indentation) (python-initial-text))
664 levels))
665 (while (python-beginning-of-block)
666 (when (or (not start)
667 (member (python-first-word)
668 (cdr (assoc start python-block-pairs))))
669 (push (cons (current-indentation) (python-initial-text))
670 levels))))))
671 (prog1 (or levels (setq levels '((0 . ""))))
672 (setq python-indent-list levels
673 python-indent-list-length (length python-indent-list))))))
573 674
574;; This is basically what `python-indent-line' would be if we didn't 675;; This is basically what `python-indent-line' would be if we didn't
575;; do the cycling. 676;; do the cycling.
576(defun python-indent-line-1 () 677(defun python-indent-line-1 (&optional leave)
577 "Subroutine of `python-indent-line'." 678 "Subroutine of `python-indent-line'.
679Does non-repeated indentation. LEAVE non-nil means leave
680indentation if it is valid, i.e. one of the positions returned by
681`python-calculate-indentation'."
578 (let ((target (python-calculate-indentation)) 682 (let ((target (python-calculate-indentation))
579 (pos (- (point-max) (point)))) 683 (pos (- (point-max) (point))))
580 (if (= target (current-indentation)) 684 (if (or (= target (current-indentation))
685 ;; Maybe keep a valid indentation.
686 (and leave python-indent-list
687 (assq (current-indentation) python-indent-list)))
581 (if (< (current-column) (current-indentation)) 688 (if (< (current-column) (current-indentation))
582 (back-to-indentation)) 689 (back-to-indentation))
583 (beginning-of-line) 690 (beginning-of-line)
@@ -589,29 +696,41 @@ corresponding block opening (or nil)."
589(defun python-indent-line () 696(defun python-indent-line ()
590 "Indent current line as Python code. 697 "Indent current line as Python code.
591When invoked via `indent-for-tab-command', cycle through possible 698When invoked via `indent-for-tab-command', cycle through possible
592indentations for current line. The cycle is broken by a command different 699indentations for current line. The cycle is broken by a command
593from `indent-for-tab-command', i.e. successive TABs do the cycling." 700different from `indent-for-tab-command', i.e. successive TABs do
701the cycling."
594 (interactive) 702 (interactive)
595 ;; Don't do extra work if invoked via `indent-region', for instance. 703 (if (and (eq this-command 'indent-for-tab-command)
596 (if (not (eq this-command 'indent-for-tab-command)) 704 (eq last-command this-command))
597 (python-indent-line-1) 705 (if (= 1 python-indent-list-length)
598 (if (eq last-command this-command) 706 (message "Sole indentation")
599 (if (= 1 python-indent-list-length) 707 (progn (setq python-indent-index
600 (message "Sole indentation") 708 (% (1+ python-indent-index) python-indent-list-length))
601 (progn (setq python-indent-index (% (1+ python-indent-index) 709 (beginning-of-line)
602 python-indent-list-length)) 710 (delete-horizontal-space)
603 (beginning-of-line) 711 (indent-to (car (nth python-indent-index python-indent-list)))
604 (delete-horizontal-space) 712 (if (python-block-end-p)
605 (indent-to (car (nth python-indent-index python-indent-list))) 713 (let ((text (cdr (nth python-indent-index
606 (if (python-block-end-p) 714 python-indent-list))))
607 (let ((text (cdr (nth python-indent-index 715 (if text
608 python-indent-list)))) 716 (message "Closes: %s" text))))))
609 (if text 717 (python-indent-line-1)
610 (message "Closes: %s" text)))))) 718 (setq python-indent-index (1- python-indent-list-length))))
611 (python-indent-line-1) 719
612 (setq python-indent-list (python-indentation-levels) 720(defun python-indent-region (start end)
613 python-indent-list-length (length python-indent-list) 721 "`indent-region-function' for Python.
614 python-indent-index (1- python-indent-list-length))))) 722Leaves validly-indented lines alone, i.e. doesn't indent to
723another valid position."
724 (save-excursion
725 (goto-char end)
726 (setq end (point-marker))
727 (goto-char start)
728 (or (bolp) (forward-line 1))
729 (while (< (point) end)
730 (or (and (bolp) (eolp))
731 (python-indent-line-1 t))
732 (forward-line 1))
733 (move-marker end nil)))
615 734
616(defun python-block-end-p () 735(defun python-block-end-p ()
617 "Non-nil if this is a line in a statement closing a block, 736 "Non-nil if this is a line in a statement closing a block,
@@ -622,40 +741,41 @@ or a blank line indented to where it would close a block."
622 (save-excursion 741 (save-excursion
623 (python-previous-statement) 742 (python-previous-statement)
624 (current-indentation)))))) 743 (current-indentation))))))
625
626;; Fixme: Define an indent-region-function. It should probably leave
627;; lines alone if the indentation is already at one of the allowed
628;; levels. Otherwise, M-C-\ typically keeps indenting more deeply
629;; down a function.
630 744
631;;;; Movement. 745;;;; Movement.
632 746
747;; Fixme: Define {for,back}ward-sexp-function? Maybe skip units like
748;; block, statement, depending on context.
749
633(defun python-beginning-of-defun () 750(defun python-beginning-of-defun ()
634 "`beginning-of-defun-function' for Python. 751 "`beginning-of-defun-function' for Python.
635Finds beginning of innermost nested class or method definition. 752Finds beginning of innermost nested class or method definition.
636Returns the name of the definition found at the end, or nil if reached 753Returns the name of the definition found at the end, or nil if
637start of buffer." 754reached start of buffer."
638 (let ((ci (current-indentation)) 755 (let ((ci (current-indentation))
639 (def-re (rx (and line-start (0+ space) (or "def" "class") 756 (def-re (rx line-start (0+ space) (or "def" "class") (1+ space)
640 (1+ space) 757 (group (1+ (or word (syntax symbol))))))
641 (group (1+ (or word (syntax symbol))))))) 758 found lep) ;; def-line
642 found lep def-line)
643 (if (python-comment-line-p) 759 (if (python-comment-line-p)
644 (setq ci most-positive-fixnum)) 760 (setq ci most-positive-fixnum))
645 (while (and (not (bobp)) (not found)) 761 (while (and (not (bobp)) (not found))
646 ;; Treat bol at beginning of function as outside function so 762 ;; Treat bol at beginning of function as outside function so
647 ;; that successive C-M-a makes progress backwards. 763 ;; that successive C-M-a makes progress backwards.
648 (setq def-line (looking-at def-re)) 764 ;;(setq def-line (looking-at def-re))
649 (unless (bolp) (end-of-line)) 765 (unless (bolp) (end-of-line))
650 (setq lep (line-end-position)) 766 (setq lep (line-end-position))
651 (if (and (re-search-backward def-re nil 'move) 767 (if (and (re-search-backward def-re nil 'move)
652 ;; Must be less indented or matching top level, or 768 ;; Must be less indented or matching top level, or
653 ;; equally indented if we started on a definition line. 769 ;; equally indented if we started on a definition line.
654 (let ((in (current-indentation))) 770 (let ((in (current-indentation)))
655 (or (and (zerop ci) (zerop in)) 771 (or (and (zerop ci) (zerop in))
656 (= lep (line-end-position)) ; on initial line 772 (= lep (line-end-position)) ; on initial line
657 (and def-line (= in ci)) 773 ;; Not sure why it was like this -- fails in case of
658 (< in ci))) 774 ;; last internal function followed by first
775 ;; non-def statement of the main body.
776 ;;(and def-line (= in ci))
777 (= in ci)
778 (< in ci)))
659 (not (python-in-string/comment))) 779 (not (python-in-string/comment)))
660 (setq found t))))) 780 (setq found t)))))
661 781
@@ -663,7 +783,7 @@ start of buffer."
663 "`end-of-defun-function' for Python. 783 "`end-of-defun-function' for Python.
664Finds end of innermost nested class or method definition." 784Finds end of innermost nested class or method definition."
665 (let ((orig (point)) 785 (let ((orig (point))
666 (pattern (rx (and line-start (0+ space) (or "def" "class") space)))) 786 (pattern (rx line-start (0+ space) (or "def" "class") space)))
667 ;; Go to start of current block and check whether it's at top 787 ;; Go to start of current block and check whether it's at top
668 ;; level. If it is, and not a block start, look forward for 788 ;; level. If it is, and not a block start, look forward for
669 ;; definition statement. 789 ;; definition statement.
@@ -692,8 +812,9 @@ Finds end of innermost nested class or method definition."
692 (python-end-of-block) 812 (python-end-of-block)
693 ;; Count trailing space in defun (but not trailing comments). 813 ;; Count trailing space in defun (but not trailing comments).
694 (skip-syntax-forward " >") 814 (skip-syntax-forward " >")
695 (beginning-of-line)) 815 (unless (eobp) ; e.g. missing final newline
696 ;; Catch pathological case like this, where the beginning-of-defun 816 (beginning-of-line)))
817 ;; Catch pathological cases like this, where the beginning-of-defun
697 ;; skips to a definition we're not in: 818 ;; skips to a definition we're not in:
698 ;; if ...: 819 ;; if ...:
699 ;; ... 820 ;; ...
@@ -706,26 +827,43 @@ Finds end of innermost nested class or method definition."
706 827
707(defun python-beginning-of-statement () 828(defun python-beginning-of-statement ()
708 "Go to start of current statement. 829 "Go to start of current statement.
709Accounts for continuation lines, multi-line strings, and multi-line bracketed 830Accounts for continuation lines, multi-line strings, and
710expressions." 831multi-line bracketed expressions."
711 (beginning-of-line) 832 (beginning-of-line)
712 (python-beginning-of-string) 833 (python-beginning-of-string)
713 (catch 'foo 834 (while (python-continuation-line-p)
714 (while (python-continuation-line-p) 835 (beginning-of-line)
715 (beginning-of-line) 836 (if (python-backslash-continuation-line-p)
716 (if (python-backslash-continuation-line-p) 837 (progn
838 (forward-line -1)
717 (while (python-backslash-continuation-line-p) 839 (while (python-backslash-continuation-line-p)
718 (forward-line -1)) 840 (forward-line -1)))
719 (python-beginning-of-string) 841 (python-beginning-of-string)
720 ;; Skip forward out of nested brackets. 842 (python-skip-out)))
721 (condition-case () ; beware invalid syntax
722 (let ((depth (syntax-ppss-depth (syntax-ppss))))
723 ;; Beware negative depths.
724 (if (> depth 0) (backward-up-list depth))
725 t)
726 (error (throw 'foo nil))))))
727 (back-to-indentation)) 843 (back-to-indentation))
728 844
845(defun python-skip-out (&optional forward syntax)
846 "Skip out of any nested brackets.
847Skip forward if FORWARD is non-nil, else backward.
848If SYNTAX is non-nil it is the state returned by `syntax-ppss' at point.
849Return non-nil iff skipping was done."
850 (let ((depth (syntax-ppss-depth (or syntax (syntax-ppss))))
851 (forward (if forward -1 1)))
852 (unless (zerop depth)
853 (if (> depth 0)
854 ;; Skip forward out of nested brackets.
855 (condition-case () ; beware invalid syntax
856 (progn (backward-up-list (* forward depth)) t)
857 (error nil))
858 ;; Invalid syntax (too many closed brackets).
859 ;; Skip out of as many as possible.
860 (let (done)
861 (while (condition-case ()
862 (progn (backward-up-list forward)
863 (setq done t))
864 (error nil)))
865 done)))))
866
729(defun python-end-of-statement () 867(defun python-end-of-statement ()
730 "Go to the end of the current statement and return point. 868 "Go to the end of the current statement and return point.
731Usually this is the start of the next line, but if this is a 869Usually this is the start of the next line, but if this is a
@@ -745,13 +883,7 @@ On a comment line, go to end of line."
745 (condition-case () ; beware invalid syntax 883 (condition-case () ; beware invalid syntax
746 (progn (forward-sexp) t) 884 (progn (forward-sexp) t)
747 (error (end-of-line)))) 885 (error (end-of-line))))
748 ((> (syntax-ppss-depth s) 0) 886 ((python-skip-out t s))))
749 ;; Skip forward out of nested brackets.
750 (condition-case () ; beware invalid syntax
751 (progn (backward-up-list
752 (- (syntax-ppss-depth s)))
753 t)
754 (error (end-of-line))))))
755 (end-of-line)) 887 (end-of-line))
756 (unless comment 888 (unless comment
757 (eq ?\\ (char-before)))) ; Line continued? 889 (eq ?\\ (char-before)))) ; Line continued?
@@ -785,7 +917,8 @@ Return count of statements left to move."
785 (while (and (> count 0) (not (eobp))) 917 (while (and (> count 0) (not (eobp)))
786 (python-end-of-statement) 918 (python-end-of-statement)
787 (python-skip-comments/blanks) 919 (python-skip-comments/blanks)
788 (setq count (1- count))) 920 (unless (eobp)
921 (setq count (1- count))))
789 count)) 922 count))
790 923
791(defun python-beginning-of-block (&optional arg) 924(defun python-beginning-of-block (&optional arg)
@@ -802,7 +935,8 @@ Otherwise return non-nil."
802 ((< arg 0) (python-end-of-block (- arg))) 935 ((< arg 0) (python-end-of-block (- arg)))
803 (t 936 (t
804 (let ((point (point))) 937 (let ((point (point)))
805 (if (python-comment-line-p) 938 (if (or (python-comment-line-p)
939 (python-blank-line-p))
806 (python-skip-comments/blanks t)) 940 (python-skip-comments/blanks t))
807 (python-beginning-of-statement) 941 (python-beginning-of-statement)
808 (let ((ci (current-indentation))) 942 (let ((ci (current-indentation)))
@@ -830,32 +964,31 @@ Otherwise return non-nil."
830 964
831(defun python-end-of-block (&optional arg) 965(defun python-end-of-block (&optional arg)
832 "Go to end of current block. 966 "Go to end of current block.
833With numeric arg, do it that many times. If ARG is negative, call 967With numeric arg, do it that many times. If ARG is negative,
834`python-beginning-of-block' instead. 968call `python-beginning-of-block' instead.
835If current statement is in column zero and doesn't open a block, don't 969If current statement is in column zero and doesn't open a block,
836move and return nil. Otherwise return t." 970don't move and return nil. Otherwise return t."
837 (interactive "p") 971 (interactive "p")
838 (unless arg (setq arg 1)) 972 (unless arg (setq arg 1))
839 (if (< arg 0) 973 (if (< arg 0)
840 (python-beginning-of-block (- arg))) 974 (python-beginning-of-block (- arg))
841 (while (and (> arg 0) 975 (while (and (> arg 0)
842 (let* ((point (point)) 976 (let* ((point (point))
843 (_ (if (python-comment-line-p) 977 (_ (if (python-comment-line-p)
844 (python-skip-comments/blanks t))) 978 (python-skip-comments/blanks t)))
845 (ci (current-indentation)) 979 (ci (current-indentation))
846 (open (python-open-block-statement-p))) 980 (open (python-open-block-statement-p)))
847 (if (and (zerop ci) (not open)) 981 (if (and (zerop ci) (not open))
848 (not (goto-char point)) 982 (not (goto-char point))
849 (catch 'done 983 (catch 'done
850 (while (zerop (python-next-statement)) 984 (while (zerop (python-next-statement))
851 (when (or (and open (<= (current-indentation) ci)) 985 (when (or (and open (<= (current-indentation) ci))
852 (< (current-indentation) ci)) 986 (< (current-indentation) ci))
853 (python-skip-comments/blanks t) 987 (python-skip-comments/blanks t)
854 (beginning-of-line 2) 988 (beginning-of-line 2)
855 (throw 'done t))) 989 (throw 'done t)))))))
856 (not (goto-char point)))))) 990 (setq arg (1- arg)))
857 (setq arg (1- arg))) 991 (zerop arg)))
858 (zerop arg))
859 992
860;;;; Imenu. 993;;;; Imenu.
861 994
@@ -868,14 +1001,23 @@ The nested menus are headed by an item referencing the outer
868definition; it has a space prepended to the name so that it sorts 1001definition; it has a space prepended to the name so that it sorts
869first with `imenu--sort-by-name' (though, unfortunately, sub-menus 1002first with `imenu--sort-by-name' (though, unfortunately, sub-menus
870precede it)." 1003precede it)."
871 (unless (boundp 'python-recursing) ; dynamically bound below 1004 (unless (boundp 'python-recursing) ; dynamically bound below
872 (goto-char (point-min))) ; normal call from Imenu 1005 ;; Normal call from Imenu.
873 (let (index-alist ; accumulated value to return 1006 (goto-char (point-min))
874 name) 1007 ;; Without this, we can get an infloop if the buffer isn't all
1008 ;; fontified. I guess this is really a bug in syntax.el. OTOH,
1009 ;; _with_ this, imenu doesn't immediately work; I can't figure out
1010 ;; what's going on, but it must be something to do with timers in
1011 ;; font-lock.
1012 ;; This can't be right, especially not when jit-lock is not used. --Stef
1013 ;; (unless (get-text-property (1- (point-max)) 'fontified)
1014 ;; (font-lock-fontify-region (point-min) (point-max)))
1015 )
1016 (let (index-alist) ; accumulated value to return
875 (while (re-search-forward 1017 (while (re-search-forward
876 (rx (and line-start (0+ space) ; leading space 1018 (rx line-start (0+ space) ; leading space
877 (or (group "def") (group "class")) ; type 1019 (or (group "def") (group "class")) ; type
878 (1+ space) (group (1+ (or word ?_))))) ; name 1020 (1+ space) (group (1+ (or word ?_)))) ; name
879 nil t) 1021 nil t)
880 (unless (python-in-string/comment) 1022 (unless (python-in-string/comment)
881 (let ((pos (match-beginning 0)) 1023 (let ((pos (match-beginning 0))
@@ -890,7 +1032,22 @@ precede it)."
890 (progn (push (cons (concat " " name) pos) sublist) 1032 (progn (push (cons (concat " " name) pos) sublist)
891 (push (cons name sublist) index-alist)) 1033 (push (cons name sublist) index-alist))
892 (push (cons name pos) index-alist))))))) 1034 (push (cons name pos) index-alist)))))))
893 (nreverse index-alist))) 1035 (unless (boundp 'python-recursing)
1036 ;; Look for module variables.
1037 (let (vars)
1038 (goto-char (point-min))
1039 (while (re-search-forward
1040 (rx line-start (group (1+ (or word ?_))) (0+ space) "=")
1041 nil t)
1042 (unless (python-in-string/comment)
1043 (push (cons (match-string 1) (match-beginning 1))
1044 vars)))
1045 (setq index-alist (nreverse index-alist))
1046 (if vars
1047 (push (cons "Module variables"
1048 (nreverse vars))
1049 index-alist))))
1050 index-alist))
894 1051
895;;;; `Electric' commands. 1052;;;; `Electric' commands.
896 1053
@@ -910,20 +1067,26 @@ just insert a single colon."
910 1067
911(defun python-backspace (arg) 1068(defun python-backspace (arg)
912 "Maybe delete a level of indentation on the current line. 1069 "Maybe delete a level of indentation on the current line.
913If not at the end of line's indentation, or on a comment line, just call 1070Do so if point is at the end of the line's indentation.
914`backward-delete-char-untabify'. With ARG, repeat that many times." 1071Otherwise just call `backward-delete-char-untabify'.
1072Repeat ARG times."
915 (interactive "*p") 1073 (interactive "*p")
916 (if (or (/= (current-indentation) (current-column)) 1074 (if (or (/= (current-indentation) (current-column))
917 (bolp) 1075 (bolp)
918 (python-continuation-line-p)) 1076 (python-continuation-line-p))
919 (backward-delete-char-untabify arg) 1077 (backward-delete-char-untabify arg)
920 (let ((indent 0)) 1078 ;; Look for the largest valid indentation which is smaller than
921 (save-excursion 1079 ;; the current indentation.
922 (while (and (> arg 0) (python-beginning-of-block)) 1080 (let ((indent 0)
923 (setq arg (1- arg))) 1081 (ci (current-indentation))
924 (when (zerop arg) 1082 (indents (python-indentation-levels))
925 (setq indent (current-indentation)) 1083 initial)
926 (message "Closes %s" (python-initial-text)))) 1084 (dolist (x indents)
1085 (if (< (car x) ci)
1086 (setq indent (max indent (car x)))))
1087 (setq initial (cdr (assq indent indents)))
1088 (if (> (length initial) 0)
1089 (message "Closes %s" initial))
927 (delete-horizontal-space) 1090 (delete-horizontal-space)
928 (indent-to indent)))) 1091 (indent-to indent))))
929(put 'python-backspace 'delete-selection 'supersede) 1092(put 'python-backspace 'delete-selection 'supersede)
@@ -931,7 +1094,7 @@ If not at the end of line's indentation, or on a comment line, just call
931;;;; pychecker 1094;;;; pychecker
932 1095
933(defcustom python-check-command "pychecker --stdlib" 1096(defcustom python-check-command "pychecker --stdlib"
934 "*Command used to check a Python file." 1097 "Command used to check a Python file."
935 :type 'string 1098 :type 'string
936 :group 'python) 1099 :group 'python)
937 1100
@@ -963,66 +1126,54 @@ See `python-check-command' for the default."
963;; Fixme: Make sure we can work with IPython. 1126;; Fixme: Make sure we can work with IPython.
964 1127
965(defcustom python-python-command "python" 1128(defcustom python-python-command "python"
966 "*Shell command to run Python interpreter. 1129 "Shell command to run Python interpreter.
967Any arguments can't contain whitespace. 1130Any arguments can't contain whitespace.
968Note that IPython may not work properly; it must at least be used with the 1131Note that IPython may not work properly; it must at least be used
969`-cl' flag, i.e. use `ipython -cl'." 1132with the `-cl' flag, i.e. use `ipython -cl'."
970 :group 'python 1133 :group 'python
971 :type 'string) 1134 :type 'string)
972 1135
973(defcustom python-jython-command "jython" 1136(defcustom python-jython-command "jython"
974 "*Shell command to run Jython interpreter. 1137 "Shell command to run Jython interpreter.
975Any arguments can't contain whitespace." 1138Any arguments can't contain whitespace."
976 :group 'python 1139 :group 'python
977 :type 'string) 1140 :type 'string)
978 1141
979(defvar python-command python-python-command 1142(defvar python-command python-python-command
980 "Actual command used to run Python. 1143 "Actual command used to run Python.
981May be `python-python-command' or `python-jython-command'. 1144May be `python-python-command' or `python-jython-command', possibly
982Additional arguments are added when the command is used by `run-python' 1145modified by the user. Additional arguments are added when the command
983et al.") 1146is used by `run-python' et al.")
984 1147
985(defvar python-buffer nil 1148(defvar python-buffer nil
986 "The current python process buffer." 1149 "*The current python process buffer.
987 ;; Fixme: a single process is currently assumed, so that this doc 1150
988 ;; is misleading. 1151Commands that send text from source buffers to Python processes have
989 1152to choose a process to send to. This is determined by buffer-local
990;; "*The current python process buffer. 1153value of `python-buffer'. If its value in the current buffer,
991;; To run multiple Python processes, start the first with \\[run-python]. 1154i.e. both any local value and the default one, is nil, `run-python'
992;; It will be in a buffer named *Python*. Rename that with 1155and commands that send to the Python process will start a new process.
993;; \\[rename-buffer]. Now start a new process with \\[run-python]. It 1156
994;; will be in a new buffer, named *Python*. Switch between the different 1157Whenever \\[run-python] starts a new process, it resets the default
995;; process buffers with \\[switch-to-buffer]. 1158value of `python-buffer' to be the new process's buffer and sets the
996 1159buffer-local value similarly if the current buffer is in Python mode
997;; Commands that send text from source buffers to Python processes have 1160or Inferior Python mode, so that source buffer stays associated with a
998;; to choose a process to send to. This is determined by global variable 1161specific sub-process.
999;; `python-buffer'. Suppose you have three inferior Pythons running: 1162
1000;; Buffer Process 1163Use \\[python-set-proc] to set the default value from a buffer with a
1001;; foo python 1164local value.")
1002;; bar python<2> 1165(make-variable-buffer-local 'python-buffer)
1003;; *Python* python<3>
1004;; If you do a \\[python-send-region-and-go] command on some Python source
1005;; code, what process does it go to?
1006
1007;; - In a process buffer (foo, bar, or *Python*), send it to that process.
1008;; - In some other buffer (e.g. a source file), send it to the process
1009;; attached to `python-buffer'.
1010;; Process selection is done by function `python-proc'.
1011
1012;; Whenever \\[run-python] starts a new process, it resets `python-buffer'
1013;; to be the new process's buffer. If you only run one process, this will
1014;; do the right thing. If you run multiple processes, you can change
1015;; `python-buffer' to another process buffer with \\[set-variable]."
1016 )
1017 1166
1018(defconst python-compilation-regexp-alist 1167(defconst python-compilation-regexp-alist
1019 ;; FIXME: maybe these should move to compilation-error-regexp-alist-alist. 1168 ;; FIXME: maybe these should move to compilation-error-regexp-alist-alist.
1020 `((,(rx (and line-start (1+ (any " \t")) "File \"" 1169 ;; The first already is (for CAML), but the second isn't. Anyhow,
1021 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c 1170 ;; these are specific to the inferior buffer. -- fx
1022 "\", line " (group (1+ digit)))) 1171 `((,(rx line-start (1+ (any " \t")) "File \""
1172 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1173 "\", line " (group (1+ digit)))
1023 1 2) 1174 1 2)
1024 (,(rx (and " in file " (group (1+ not-newline)) " on line " 1175 (,(rx " in file " (group (1+ not-newline)) " on line "
1025 (group (1+ digit)))) 1176 (group (1+ digit)))
1026 1 2)) 1177 1 2))
1027 "`compilation-error-regexp-alist' for inferior Python.") 1178 "`compilation-error-regexp-alist' for inferior Python.")
1028 1179
@@ -1040,9 +1191,9 @@ et al.")
1040 ;; (define-key map "\C-c\C-f" 'python-describe-symbol) 1191 ;; (define-key map "\C-c\C-f" 'python-describe-symbol)
1041 map)) 1192 map))
1042 1193
1043;; Fixme: This should inherit some stuff from python-mode, but I'm not 1194;; Fixme: This should inherit some stuff from `python-mode', but I'm
1044;; sure how much: at least some keybindings, like C-c C-f; syntax?; 1195;; not sure how much: at least some keybindings, like C-c C-f;
1045;; font-locking, e.g. for triple-quoted strings? 1196;; syntax?; font-locking, e.g. for triple-quoted strings?
1046(define-derived-mode inferior-python-mode comint-mode "Inferior Python" 1197(define-derived-mode inferior-python-mode comint-mode "Inferior Python"
1047 "Major mode for interacting with an inferior Python process. 1198 "Major mode for interacting with an inferior Python process.
1048A Python process can be started with \\[run-python]. 1199A Python process can be started with \\[run-python].
@@ -1050,14 +1201,15 @@ A Python process can be started with \\[run-python].
1050Hooks `comint-mode-hook' and `inferior-python-mode-hook' are run in 1201Hooks `comint-mode-hook' and `inferior-python-mode-hook' are run in
1051that order. 1202that order.
1052 1203
1053You can send text to the inferior Python process from other buffers containing 1204You can send text to the inferior Python process from other buffers
1054Python source. 1205containing Python source.
1055 * `python-switch-to-python' switches the current buffer to the Python 1206 * \\[python-switch-to-python] switches the current buffer to the Python
1056 process buffer. 1207 process buffer.
1057 * `python-send-region' sends the current region to the Python process. 1208 * \\[python-send-region] sends the current region to the Python process.
1058 * `python-send-region-and-go' switches to the Python process buffer 1209 * \\[python-send-region-and-go] switches to the Python process buffer
1059 after sending the text. 1210 after sending the text.
1060For running multiple processes in multiple buffers, see `python-buffer'. 1211For running multiple processes in multiple buffers, see `run-python' and
1212`python-buffer'.
1061 1213
1062\\{inferior-python-mode-map}" 1214\\{inferior-python-mode-map}"
1063 :group 'python 1215 :group 'python
@@ -1069,13 +1221,13 @@ For running multiple processes in multiple buffers, see `python-buffer'.
1069 ;; Still required by `comint-redirect-send-command', for instance 1221 ;; Still required by `comint-redirect-send-command', for instance
1070 ;; (and we need to match things like `>>> ... >>> '): 1222 ;; (and we need to match things like `>>> ... >>> '):
1071 (set (make-local-variable 'comint-prompt-regexp) 1223 (set (make-local-variable 'comint-prompt-regexp)
1072 (rx (and line-start (1+ (and (repeat 3 (any ">.")) ?\s))))) 1224 (rx line-start (1+ (and (repeat 3 (any ">.")) " "))))
1073 (set (make-local-variable 'compilation-error-regexp-alist) 1225 (set (make-local-variable 'compilation-error-regexp-alist)
1074 python-compilation-regexp-alist) 1226 python-compilation-regexp-alist)
1075 (compilation-shell-minor-mode 1)) 1227 (compilation-shell-minor-mode 1))
1076 1228
1077(defcustom inferior-python-filter-regexp "\\`\\s-*\\S-?\\S-?\\s-*\\'" 1229(defcustom inferior-python-filter-regexp "\\`\\s-*\\S-?\\S-?\\s-*\\'"
1078 "*Input matching this regexp is not saved on the history list. 1230 "Input matching this regexp is not saved on the history list.
1079Default ignores all inputs of 0, 1, or 2 non-blank characters." 1231Default ignores all inputs of 0, 1, or 2 non-blank characters."
1080 :type 'regexp 1232 :type 'regexp
1081 :group 'python) 1233 :group 'python)
@@ -1098,98 +1250,134 @@ Don't save anything for STR matching `inferior-python-filter-regexp'."
1098(defvar python-preoutput-result nil 1250(defvar python-preoutput-result nil
1099 "Data from last `_emacs_out' line seen by the preoutput filter.") 1251 "Data from last `_emacs_out' line seen by the preoutput filter.")
1100 1252
1101(defvar python-preoutput-continuation nil
1102 "If non-nil, funcall this when `python-preoutput-filter' sees `_emacs_ok'.")
1103
1104(defvar python-preoutput-leftover nil) 1253(defvar python-preoutput-leftover nil)
1254(defvar python-preoutput-skip-next-prompt nil)
1105 1255
1106;; Using this stops us getting lines in the buffer like 1256;; Using this stops us getting lines in the buffer like
1107;; >>> ... ... >>> 1257;; >>> ... ... >>>
1108;; Also look for (and delete) an `_emacs_ok' string and call
1109;; `python-preoutput-continuation' if we get it.
1110(defun python-preoutput-filter (s) 1258(defun python-preoutput-filter (s)
1111 "`comint-preoutput-filter-functions' function: ignore prompts not at bol." 1259 "`comint-preoutput-filter-functions' function: ignore prompts not at bol."
1112 (when python-preoutput-leftover 1260 (when python-preoutput-leftover
1113 (setq s (concat python-preoutput-leftover s)) 1261 (setq s (concat python-preoutput-leftover s))
1114 (setq python-preoutput-leftover nil)) 1262 (setq python-preoutput-leftover nil))
1115 (cond ((and (string-match (rx (and string-start (repeat 3 (any ".>")) 1263 (let ((start 0)
1116 " " string-end)) 1264 (res ""))
1117 s) 1265 ;; First process whole lines.
1118 (/= (let ((inhibit-field-text-motion t)) 1266 (while (string-match "\n" s start)
1119 (line-beginning-position)) 1267 (let ((line (substring s start (setq start (match-end 0)))))
1120 (point))) 1268 ;; Skip prompt if needed.
1121 "") 1269 (when (and python-preoutput-skip-next-prompt
1122 ((string= s "_emacs_ok\n") 1270 (string-match comint-prompt-regexp line))
1123 (when python-preoutput-continuation 1271 (setq python-preoutput-skip-next-prompt nil)
1124 (funcall python-preoutput-continuation) 1272 (setq line (substring line (match-end 0))))
1125 (setq python-preoutput-continuation nil)) 1273 ;; Recognize special _emacs_out lines.
1126 "") 1274 (if (and (string-match "\\`_emacs_out \\(.*\\)\n\\'" line)
1127 ((string-match "_emacs_out \\(.*\\)\n" s) 1275 (local-variable-p 'python-preoutput-result))
1128 (setq python-preoutput-result (match-string 1 s)) 1276 (progn
1129 "") 1277 (setq python-preoutput-result (match-string 1 line))
1130 ((string-match ".*\n" s) 1278 (set (make-local-variable 'python-preoutput-skip-next-prompt) t))
1131 s) 1279 (setq res (concat res line)))))
1132 ((or (eq t (compare-strings s nil nil "_emacs_ok\n" nil (length s))) 1280 ;; Then process the remaining partial line.
1133 (let ((end (min (length "_emacs_out ") (length s)))) 1281 (unless (zerop start) (setq s (substring s start)))
1134 (eq t (compare-strings s nil end "_emacs_out " nil end)))) 1282 (cond ((and (string-match comint-prompt-regexp s)
1135 (setq python-preoutput-leftover s) 1283 ;; Drop this prompt if it follows an _emacs_out...
1136 "") 1284 (or python-preoutput-skip-next-prompt
1137 (t s))) 1285 ;; ... or if it's not gonna be inserted at BOL.
1286 ;; Maybe we could be more selective here.
1287 (if (zerop (length res))
1288 (not (bolp))
1289 (string-match res ".\\'"))))
1290 ;; The need for this seems to be system-dependent:
1291 ;; What is this all about, exactly? --Stef
1292 ;; (if (and (eq ?. (aref s 0)))
1293 ;; (accept-process-output (get-buffer-process (current-buffer)) 1))
1294 (setq python-preoutput-skip-next-prompt nil)
1295 res)
1296 ((let ((end (min (length "_emacs_out ") (length s))))
1297 (eq t (compare-strings s nil end "_emacs_out " nil end)))
1298 ;; The leftover string is a prefix of _emacs_out so we don't know
1299 ;; yet whether it's an _emacs_out or something else: wait until we
1300 ;; get more output so we can resolve this ambiguity.
1301 (set (make-local-variable 'python-preoutput-leftover) s)
1302 res)
1303 (t (concat res s)))))
1304
1305(autoload 'comint-check-proc "comint")
1138 1306
1139;;;###autoload 1307;;;###autoload
1140(defun run-python (&optional cmd noshow) 1308(defun run-python (&optional cmd noshow new)
1141 "Run an inferior Python process, input and output via buffer *Python*. 1309 "Run an inferior Python process, input and output via buffer *Python*.
1142CMD is the Python command to run. NOSHOW non-nil means don't show the 1310CMD is the Python command to run. NOSHOW non-nil means don't show the
1143buffer automatically. 1311buffer automatically.
1144If there is a process already running in `*Python*', switch to 1312
1145that buffer. Interactively, a prefix arg allows you to edit the initial 1313Normally, if there is a process already running in `python-buffer',
1146command line (default is `python-command'); `-i' etc. args will be added 1314switch to that buffer. Interactively, a prefix arg allows you to edit
1147to this as appropriate. Runs the hook `inferior-python-mode-hook' 1315the initial command line (default is `python-command'); `-i' etc. args
1148\(after the `comint-mode-hook' is run). 1316will be added to this as appropriate. A new process is started if:
1149\(Type \\[describe-mode] in the process buffer for a list of commands.)" 1317one isn't running attached to `python-buffer', or interactively the
1150 (interactive (list (if current-prefix-arg 1318default `python-command', or argument NEW is non-nil. See also the
1151 (read-string "Run Python: " python-command) 1319documentation for `python-buffer'.
1152 python-command))) 1320
1321Runs the hook `inferior-python-mode-hook' \(after the
1322`comint-mode-hook' is run). \(Type \\[describe-mode] in the process
1323buffer for a list of commands.)"
1324 (interactive (if current-prefix-arg
1325 (list (read-string "Run Python: " python-command) nil t)
1326 (list python-command)))
1153 (unless cmd (setq cmd python-python-command)) 1327 (unless cmd (setq cmd python-python-command))
1154 (setq python-command cmd) 1328 (setq python-command cmd)
1155 ;; Fixme: Consider making `python-buffer' buffer-local as a buffer 1329 ;; Fixme: Consider making `python-buffer' buffer-local as a buffer
1156 ;; (not a name) in Python buffers from which `run-python' &c is 1330 ;; (not a name) in Python buffers from which `run-python' &c is
1157 ;; invoked. Would support multiple processes better. 1331 ;; invoked. Would support multiple processes better.
1158 (unless (comint-check-proc python-buffer) 1332 (when (or new (not (comint-check-proc python-buffer)))
1159 (let* ((cmdlist (append (python-args-to-list cmd) '("-i"))) 1333 (save-current-buffer
1160 (path (getenv "PYTHONPATH")) 1334 (let* ((cmdlist (append (python-args-to-list cmd) '("-i")))
1161 (process-environment ; to import emacs.py 1335 (path (getenv "PYTHONPATH"))
1162 (cons (concat "PYTHONPATH=" data-directory 1336 (process-environment ; to import emacs.py
1163 (if path (concat ":" path))) 1337 (cons (concat "PYTHONPATH=" data-directory
1164 process-environment))) 1338 (if path (concat ":" path)))
1165 (set-buffer (apply 'make-comint "Python" (car cmdlist) nil 1339 process-environment)))
1166 (cdr cmdlist))) 1340 (set-buffer (apply 'make-comint-in-buffer "Python"
1167 (setq python-buffer (buffer-name))) 1341 (generate-new-buffer "*Python*")
1168 (inferior-python-mode) 1342 (car cmdlist) nil (cdr cmdlist)))
1169 ;; Load function defintions we need. 1343 (setq-default python-buffer (current-buffer))
1170 ;; Before the preoutput function was used, this was done via -c in 1344 (setq python-buffer (current-buffer)))
1171 ;; cmdlist, but that loses the banner and doesn't run the startup 1345 (accept-process-output (get-buffer-process python-buffer) 5)
1172 ;; file. The code might be inline here, but there's enough that it 1346 (inferior-python-mode)))
1173 ;; seems worth putting in a separate file, and it's probably cleaner 1347 (if (derived-mode-p 'python-mode)
1174 ;; to put it in a module. 1348 (setq python-buffer (default-value 'python-buffer))) ; buffer-local
1175 (python-send-string "import emacs")) 1349 ;; Load function definitions we need.
1176 (unless noshow (pop-to-buffer python-buffer))) 1350 ;; Before the preoutput function was used, this was done via -c in
1351 ;; cmdlist, but that loses the banner and doesn't run the startup
1352 ;; file. The code might be inline here, but there's enough that it
1353 ;; seems worth putting in a separate file, and it's probably cleaner
1354 ;; to put it in a module.
1355 ;; Ensure we're at a prompt before doing anything else.
1356 (python-send-receive "import emacs; print '_emacs_out ()'")
1357 ;; Without this, help output goes into the inferior python buffer if
1358 ;; the process isn't already running.
1359 (sit-for 1 t) ;Should we use accept-process-output instead? --Stef
1360 (unless noshow (pop-to-buffer python-buffer t)))
1177 1361
1178;; Fixme: We typically lose if the inferior isn't in the normal REPL, 1362;; Fixme: We typically lose if the inferior isn't in the normal REPL,
1179;; e.g. prompt is `help> '. Probably raise an error if the form of 1363;; e.g. prompt is `help> '. Probably raise an error if the form of
1180;; the prompt is unexpected; actually, it needs to be `>>> ', not 1364;; the prompt is unexpected. Actually, it needs to be `>>> ', not
1181;; `... ', i.e. we're not inputting a block &c. However, this may not 1365;; `... ', i.e. we're not inputting a block &c. However, this may not
1182;; be the place to do it, e.g. we might actually want to send commands 1366;; be the place to check it, e.g. we might actually want to send
1183;; having set up such a state. 1367;; commands having set up such a state.
1184 1368
1185(defun python-send-command (command) 1369(defun python-send-command (command)
1186 "Like `python-send-string' but resets `compilation-minor-mode'." 1370 "Like `python-send-string' but resets `compilation-shell-minor-mode'.
1187 (goto-char (point-max)) 1371COMMAND should be a single statement."
1372 (assert (not (string-match "\n" command)))
1188 (let ((end (marker-position (process-mark (python-proc))))) 1373 (let ((end (marker-position (process-mark (python-proc)))))
1374 (with-current-buffer python-buffer (goto-char (point-max)))
1189 (compilation-forget-errors) 1375 (compilation-forget-errors)
1190 (python-send-string command) 1376 ;; Must wait until this has completed before re-setting variables below.
1191 (set-marker compilation-parsing-end end) 1377 (python-send-receive (concat command "; print '_emacs_out ()'"))
1192 (setq compilation-last-buffer (current-buffer)))) 1378 (with-current-buffer python-buffer
1379 (set-marker compilation-parsing-end end)
1380 (setq compilation-last-buffer (current-buffer)))))
1193 1381
1194(defun python-send-region (start end) 1382(defun python-send-region (start end)
1195 "Send the region to the inferior Python process." 1383 "Send the region to the inferior Python process."
@@ -1202,8 +1390,8 @@ to this as appropriate. Runs the hook `inferior-python-mode-hook'
1202 ;; filter). This function also catches exceptions and truncates 1390 ;; filter). This function also catches exceptions and truncates
1203 ;; tracebacks not to mention the frame of the function itself. 1391 ;; tracebacks not to mention the frame of the function itself.
1204 ;; 1392 ;;
1205 ;; The compilation-minor-mode parsing takes care of relating the 1393 ;; The `compilation-shell-minor-mode' parsing takes care of relating
1206 ;; reference to the temporary file to the source. 1394 ;; the reference to the temporary file to the source.
1207 ;; 1395 ;;
1208 ;; Fixme: Write a `coding' header to the temp file if the region is 1396 ;; Fixme: Write a `coding' header to the temp file if the region is
1209 ;; non-ASCII. 1397 ;; non-ASCII.
@@ -1220,18 +1408,22 @@ to this as appropriate. Runs the hook `inferior-python-mode-hook'
1220 (set-marker orig-start (line-beginning-position 0))) 1408 (set-marker orig-start (line-beginning-position 0)))
1221 (write-region "if True:\n" nil f nil 'nomsg)) 1409 (write-region "if True:\n" nil f nil 'nomsg))
1222 (write-region start end f t 'nomsg) 1410 (write-region start end f t 'nomsg)
1223 (with-current-buffer (process-buffer (python-proc)) ;Runs python if needed. 1411 (python-send-command command)
1224 (python-send-command command) 1412 (with-current-buffer (process-buffer (python-proc))
1225 ;; Tell compile.el to redirect error locations in file `f' to 1413 ;; Tell compile.el to redirect error locations in file `f' to
1226 ;; positions past marker `orig-start'. It has to be done *after* 1414 ;; positions past marker `orig-start'. It has to be done *after*
1227 ;; python-send-command's call to compilation-forget-errors. 1415 ;; `python-send-command''s call to `compilation-forget-errors'.
1228 (compilation-fake-loc orig-start f)))) 1416 (compilation-fake-loc orig-start f))))
1229 1417
1230(defun python-send-string (string) 1418(defun python-send-string (string)
1231 "Evaluate STRING in inferior Python process." 1419 "Evaluate STRING in inferior Python process."
1232 (interactive "sPython command: ") 1420 (interactive "sPython command: ")
1233 (comint-send-string (python-proc) string) 1421 (comint-send-string (python-proc) string)
1234 (comint-send-string (python-proc) "\n\n")) 1422 (comint-send-string (python-proc)
1423 ;; If the string is single-line or if it ends with \n,
1424 ;; only add a single \n, otherwise add 2, so as to
1425 ;; make sure we terminate the multiline instruction.
1426 (if (string-match "\n.+\\'" string) "\n\n" "\n")))
1235 1427
1236(defun python-send-buffer () 1428(defun python-send-buffer ()
1237 "Send the current buffer to the inferior Python process." 1429 "Send the current buffer to the inferior Python process."
@@ -1247,10 +1439,10 @@ to this as appropriate. Runs the hook `inferior-python-mode-hook'
1247 (progn (end-of-defun) (point))))) 1439 (progn (end-of-defun) (point)))))
1248 1440
1249(defun python-switch-to-python (eob-p) 1441(defun python-switch-to-python (eob-p)
1250 "Switch to the Python process buffer. 1442 "Switch to the Python process buffer, maybe starting new process.
1251With prefix arg, position cursor at end of buffer." 1443With prefix arg, position cursor at end of buffer."
1252 (interactive "P") 1444 (interactive "P")
1253 (pop-to-buffer (process-buffer (python-proc))) ;Runs python if needed. 1445 (pop-to-buffer (process-buffer (python-proc)) t) ;Runs python if needed.
1254 (when eob-p 1446 (when eob-p
1255 (push-mark) 1447 (push-mark)
1256 (goto-char (point-max)))) 1448 (goto-char (point-max))))
@@ -1263,10 +1455,10 @@ Then switch to the process buffer."
1263 (python-switch-to-python t)) 1455 (python-switch-to-python t))
1264 1456
1265(defcustom python-source-modes '(python-mode jython-mode) 1457(defcustom python-source-modes '(python-mode jython-mode)
1266 "*Used to determine if a buffer contains Python source code. 1458 "Used to determine if a buffer contains Python source code.
1267If it's loaded into a buffer that is in one of these major modes, it's 1459If a file is loaded into a buffer that is in one of these major modes,
1268considered a Python source file by `python-load-file'. 1460it is considered Python source by `python-load-file', which uses the
1269Used by these commands to determine defaults." 1461value to determine defaults."
1270 :type '(repeat function) 1462 :type '(repeat function)
1271 :group 'python) 1463 :group 'python)
1272 1464
@@ -1274,6 +1466,8 @@ Used by these commands to determine defaults."
1274 "Caches (directory . file) pair used in the last `python-load-file' command. 1466 "Caches (directory . file) pair used in the last `python-load-file' command.
1275Used for determining the default in the next one.") 1467Used for determining the default in the next one.")
1276 1468
1469(autoload 'comint-get-source "comint")
1470
1277(defun python-load-file (file-name) 1471(defun python-load-file (file-name)
1278 "Load a Python file FILE-NAME into the inferior Python process. 1472 "Load a Python file FILE-NAME into the inferior Python process.
1279If the file has extension `.py' import or reload it as a module. 1473If the file has extension `.py' import or reload it as a module.
@@ -1297,17 +1491,27 @@ module-qualified names."
1297 (format "execfile(%S)" file-name))) 1491 (format "execfile(%S)" file-name)))
1298 (message "%s loaded" file-name))) 1492 (message "%s loaded" file-name)))
1299 1493
1300;; Fixme: If we need to start the process, wait until we've got the OK
1301;; from the startup.
1302(defun python-proc () 1494(defun python-proc ()
1303 "Return the current Python process. 1495 "Return the current Python process.
1304See variable `python-buffer'. Starts a new process if necessary." 1496See variable `python-buffer'. Starts a new process if necessary."
1305 (or (if python-buffer 1497 ;; Fixme: Maybe should look for another active process if there
1306 (get-buffer-process (if (eq major-mode 'inferior-python-mode) 1498 ;; isn't one for `python-buffer'.
1307 (current-buffer) 1499 (unless (comint-check-proc python-buffer)
1308 python-buffer))) 1500 (run-python nil t))
1309 (progn (run-python nil t) 1501 (get-buffer-process (or (if (derived-mode-p 'inferior-python-mode)
1310 (python-proc)))) 1502 (current-buffer)
1503 python-buffer))))
1504
1505(defun python-set-proc ()
1506 "Set the default value of `python-buffer' to correspond to this buffer.
1507If the current buffer has a local value of `python-buffer', set the
1508default (global) value to that. The associated Python process is
1509the one that gets input from \\[python-send-region] et al when used
1510in a buffer that doesn't have a local value of `python-buffer'."
1511 (interactive)
1512 (if (local-variable-p 'python-buffer)
1513 (setq-default python-buffer python-buffer)
1514 (error "No local value of `python-buffer'")))
1311 1515
1312;;;; Context-sensitive help. 1516;;;; Context-sensitive help.
1313 1517
@@ -1322,16 +1526,22 @@ Otherwise inherits from `python-mode-syntax-table'.")
1322(defvar view-return-to-alist) 1526(defvar view-return-to-alist)
1323(eval-when-compile (autoload 'help-buffer "help-fns")) 1527(eval-when-compile (autoload 'help-buffer "help-fns"))
1324 1528
1529(defvar python-imports) ; forward declaration
1530
1325;; Fixme: Should this actually be used instead of info-look, i.e. be 1531;; Fixme: Should this actually be used instead of info-look, i.e. be
1326;; bound to C-h S? Can we use other pydoc stuff before python 2.2? 1532;; bound to C-h S? [Probably not, since info-look may work in cases
1533;; where this doesn't.]
1327(defun python-describe-symbol (symbol) 1534(defun python-describe-symbol (symbol)
1328 "Get help on SYMBOL using `help'. 1535 "Get help on SYMBOL using `help'.
1329Interactively, prompt for symbol. 1536Interactively, prompt for symbol.
1330 1537
1331Symbol may be anything recognized by the interpreter's `help' command -- 1538Symbol may be anything recognized by the interpreter's `help'
1332e.g. `CALLS' -- not just variables in scope. 1539command -- e.g. `CALLS' -- not just variables in scope in the
1333This only works for Python version 2.2 or newer since earlier interpreters 1540interpreter. This only works for Python version 2.2 or newer
1334don't support `help'." 1541since earlier interpreters don't support `help'.
1542
1543In some cases where this doesn't find documentation, \\[info-lookup-symbol]
1544will."
1335 ;; Note that we do this in the inferior process, not a separate one, to 1545 ;; Note that we do this in the inferior process, not a separate one, to
1336 ;; ensure the environment is appropriate. 1546 ;; ensure the environment is appropriate.
1337 (interactive 1547 (interactive
@@ -1343,53 +1553,65 @@ don't support `help'."
1343 "Describe symbol: ") 1553 "Describe symbol: ")
1344 nil nil symbol)))) 1554 nil nil symbol))))
1345 (if (equal symbol "") (error "No symbol")) 1555 (if (equal symbol "") (error "No symbol"))
1346 (let* ((func `(lambda () 1556 ;; Ensure we have a suitable help buffer.
1347 (comint-redirect-send-command 1557 ;; Fixme: Maybe process `Related help topics' a la help xrefs and
1348 (format "emacs.ehelp(%S, globals(), locals())\n" ,symbol) 1558 ;; allow C-c C-f in help buffer.
1349 "*Help*" nil)))) 1559 (let ((temp-buffer-show-hook ; avoid xref stuff
1350 ;; Ensure we have a suitable help buffer. 1560 (lambda ()
1351 ;; Fixme: Maybe process `Related help topics' a la help xrefs and 1561 (toggle-read-only 1)
1352 ;; allow C-c C-f in help buffer. 1562 (setq view-return-to-alist
1353 (let ((temp-buffer-show-hook ; avoid xref stuff 1563 (list (cons (selected-window) help-return-method))))))
1354 (lambda () 1564 (with-output-to-temp-buffer (help-buffer)
1355 (toggle-read-only 1) 1565 (with-current-buffer standard-output
1356 (setq view-return-to-alist 1566 ;; Fixme: Is this actually useful?
1357 (list (cons (selected-window) help-return-method)))))) 1567 (help-setup-xref (list 'python-describe-symbol symbol) (interactive-p))
1358 (help-setup-xref (list 'python-describe-symbol symbol) (interactive-p)) 1568 (set (make-local-variable 'comint-redirect-subvert-readonly) t)
1359 (with-output-to-temp-buffer (help-buffer) 1569 (print-help-return-message))))
1360 (with-current-buffer standard-output 1570 (comint-redirect-send-command-to-process (format "emacs.ehelp(%S, %s)"
1361 (set (make-local-variable 'comint-redirect-subvert-readonly) t) 1571 symbol python-imports)
1362 (print-help-return-message)))) 1572 "*Help*" (python-proc) nil nil))
1363 (if (and python-buffer (get-buffer python-buffer))
1364 (with-current-buffer python-buffer
1365 (funcall func))
1366 (setq python-preoutput-continuation func)
1367 (run-python nil t))))
1368 1573
1369(add-to-list 'debug-ignored-errors "^No symbol") 1574(add-to-list 'debug-ignored-errors "^No symbol")
1370 1575
1371(defun python-send-receive (string) 1576(defun python-send-receive (string)
1372 "Send STRING to inferior Python (if any) and return result. 1577 "Send STRING to inferior Python (if any) and return result.
1373The result is what follows `_emacs_out' in the output (or nil)." 1578The result is what follows `_emacs_out' in the output."
1579 (python-send-string string)
1374 (let ((proc (python-proc))) 1580 (let ((proc (python-proc)))
1375 (python-send-string string) 1581 (with-current-buffer (process-buffer proc)
1376 (setq python-preoutput-result nil) 1582 (set (make-local-variable 'python-preoutput-result) nil)
1377 (while (progn 1583 (while (progn
1378 (accept-process-output proc 5) 1584 (accept-process-output proc 5)
1379 python-preoutput-leftover)) 1585 (null python-preoutput-result)))
1380 python-preoutput-result)) 1586 (prog1 python-preoutput-result
1381 1587 (kill-local-variable 'python-preoutput-result)))))
1382;; Fixme: try to make it work with point in the arglist. Also, is 1588
1383;; there anything reasonable we can do with random methods? 1589;; Fixme: Is there anything reasonable we can do with random methods?
1384;; (Currently only works with functions.) 1590;; (Currently only works with functions.)
1385(defun python-eldoc-function () 1591(defun python-eldoc-function ()
1386 "`eldoc-print-current-symbol-info' for Python. 1592 "`eldoc-print-current-symbol-info' for Python.
1387Only works when point is in a function name, not its arglist, for instance. 1593Only works when point is in a function name, not its arg list, for
1388Assumes an inferior Python is running." 1594instance. Assumes an inferior Python is running."
1389 (let ((symbol (with-syntax-table python-dotty-syntax-table 1595 (let ((symbol (with-syntax-table python-dotty-syntax-table
1390 (current-word)))) 1596 (current-word))))
1391 (when symbol 1597 ;; First try the symbol we're on.
1392 (python-send-receive (format "emacs.eargs(%S)" symbol))))) 1598 (or (and symbol
1599 (python-send-receive (format "emacs.eargs(%S, %s)"
1600 symbol python-imports)))
1601 ;; Try moving to symbol before enclosing parens.
1602 (let ((s (syntax-ppss)))
1603 (unless (zerop (car s))
1604 (when (eq ?\( (char-after (nth 1 s)))
1605 (save-excursion
1606 (goto-char (nth 1 s))
1607 (skip-syntax-backward "-")
1608 (let ((point (point)))
1609 (skip-chars-backward "a-zA-Z._")
1610 (if (< (point) point)
1611 (python-send-receive
1612 (format "emacs.eargs(%S, %s)"
1613 (buffer-substring-no-properties (point) point)
1614 python-imports)))))))))))
1393 1615
1394;;;; Info-look functionality. 1616;;;; Info-look functionality.
1395 1617
@@ -1443,7 +1665,7 @@ Used with `eval-after-load'."
1443 ("(python-lib)Miscellaneous Index" nil "")))))) 1665 ("(python-lib)Miscellaneous Index" nil ""))))))
1444(eval-after-load "info-look" '(python-after-info-look)) 1666(eval-after-load "info-look" '(python-after-info-look))
1445 1667
1446;;;; Miscellancy. 1668;;;; Miscellany.
1447 1669
1448(defcustom python-jython-packages '("java" "javax" "org" "com") 1670(defcustom python-jython-packages '("java" "javax" "org" "com")
1449 "Packages implying `jython-mode'. 1671 "Packages implying `jython-mode'.
@@ -1473,8 +1695,8 @@ The criterion is either a match for `jython-mode' via
1473 (jython-mode) 1695 (jython-mode)
1474 (if (catch 'done 1696 (if (catch 'done
1475 (while (re-search-forward 1697 (while (re-search-forward
1476 (rx (and line-start (or "import" "from") (1+ space) 1698 (rx line-start (or "import" "from") (1+ space)
1477 (group (1+ (not (any " \t\n.")))))) 1699 (group (1+ (not (any " \t\n.")))))
1478 (+ (point-min) 10000) ; Probably not worth customizing. 1700 (+ (point-min) 10000) ; Probably not worth customizing.
1479 t) 1701 t)
1480 (if (member (match-string 1) python-jython-packages) 1702 (if (member (match-string 1) python-jython-packages)
@@ -1562,7 +1784,7 @@ END lie."
1562 "`outline-level' function for Python mode. 1784 "`outline-level' function for Python mode.
1563The level is the number of `python-indent' steps of indentation 1785The level is the number of `python-indent' steps of indentation
1564of current line." 1786of current line."
1565 (/ (current-indentation) python-indent)) 1787 (1+ (/ (current-indentation) python-indent)))
1566 1788
1567;; Fixme: Consider top-level assignments, imports, &c. 1789;; Fixme: Consider top-level assignments, imports, &c.
1568(defun python-current-defun () 1790(defun python-current-defun ()
@@ -1577,10 +1799,8 @@ of current line."
1577 (python-beginning-of-block) 1799 (python-beginning-of-block)
1578 (end-of-line) 1800 (end-of-line)
1579 (beginning-of-defun) 1801 (beginning-of-defun)
1580 (if (looking-at (rx (and (0+ space) (or "def" "class") (1+ space) 1802 (if (looking-at (rx (0+ space) (or "def" "class") (1+ space)
1581 (group (1+ (or word (syntax symbol)))) 1803 (group (1+ (or word (syntax symbol))))))
1582 ;; Greediness makes this unnecessary? --Stef
1583 symbol-end)))
1584 (push (match-string 1) accum))) 1804 (push (match-string 1) accum)))
1585 (if accum (mapconcat 'identity accum "."))))) 1805 (if accum (mapconcat 'identity accum ".")))))
1586 1806
@@ -1593,17 +1813,68 @@ Uses `python-beginning-of-block', `python-end-of-block'."
1593 (push-mark (point) nil t) 1813 (push-mark (point) nil t)
1594 (python-end-of-block) 1814 (python-end-of-block)
1595 (exchange-point-and-mark)) 1815 (exchange-point-and-mark))
1816
1817;; Fixme: Provide a find-function-like command to find source of a
1818;; definition (separate from BicycleRepairMan). Complicated by
1819;; finding the right qualified name.
1596 1820
1597;;;; Completion. 1821;;;; Completion.
1598 1822
1823(defvar python-imports nil
1824 "String of top-level import statements updated by `python-find-imports'.")
1825(make-variable-buffer-local 'python-imports)
1826
1827;; Fixme: Should font-lock try to run this when it deals with an import?
1828;; Maybe not a good idea if it gets run multiple times when the
1829;; statement is being edited, and is more likely to end up with
1830;; something syntactically incorrect.
1831;; However, what we should do is to trundle up the block tree from point
1832;; to extract imports that appear to be in scope, and add those.
1833(defun python-find-imports ()
1834 "Find top-level imports, updating `python-imports'."
1835 (interactive)
1836 (save-excursion
1837 (let (lines)
1838 (goto-char (point-min))
1839 (while (re-search-forward "^import\\>\\|^from\\>" nil t)
1840 (unless (syntax-ppss-context (syntax-ppss))
1841 (push (buffer-substring (line-beginning-position)
1842 (line-beginning-position 2))
1843 lines)))
1844 (setq python-imports
1845 (if lines
1846 (apply #'concat
1847;; This is probably best left out since you're unlikely to need the
1848;; doc for a function in the buffer and the import will lose if the
1849;; Python sub-process' working directory isn't the same as the
1850;; buffer's.
1851;; (if buffer-file-name
1852;; (concat
1853;; "import "
1854;; (file-name-sans-extension
1855;; (file-name-nondirectory buffer-file-name))))
1856 (nreverse lines))
1857 "None"))
1858 (when lines
1859 (set-text-properties 0 (length python-imports) nil python-imports)
1860 ;; The output ends up in the wrong place if the string we
1861 ;; send contains newlines (from the imports).
1862 (setq python-imports
1863 (replace-regexp-in-string "\n" "\\n"
1864 (format "%S" python-imports) t t))))))
1865
1866;; Fixme: This fails the first time if the sub-process isn't already
1867;; running. Presumably a timing issue with i/o to the process.
1599(defun python-symbol-completions (symbol) 1868(defun python-symbol-completions (symbol)
1600 "Return a list of completions of the string SYMBOL from Python process. 1869 "Return a list of completions of the string SYMBOL from Python process.
1601The list is sorted." 1870The list is sorted.
1871Uses `python-imports' to load modules against which to complete."
1602 (when symbol 1872 (when symbol
1603 (let ((completions 1873 (let ((completions
1604 (condition-case () 1874 (condition-case ()
1605 (car (read-from-string (python-send-receive 1875 (car (read-from-string
1606 (format "emacs.complete(%S)" symbol)))) 1876 (python-send-receive
1877 (format "emacs.complete(%S,%s)" symbol python-imports))))
1607 (error nil)))) 1878 (error nil))))
1608 (sort 1879 (sort
1609 ;; We can get duplicates from the above -- don't know why. 1880 ;; We can get duplicates from the above -- don't know why.
@@ -1615,15 +1886,12 @@ The list is sorted."
1615 (let ((end (point)) 1886 (let ((end (point))
1616 (start (save-excursion 1887 (start (save-excursion
1617 (and (re-search-backward 1888 (and (re-search-backward
1618 (rx (and (or buffer-start (regexp "[^[:alnum:]._]")) 1889 (rx (or buffer-start (regexp "[^[:alnum:]._]"))
1619 (group (1+ (regexp "[[:alnum:]._]"))) 1890 (group (1+ (regexp "[[:alnum:]._]"))) point)
1620 point))
1621 nil t) 1891 nil t)
1622 (match-beginning 1))))) 1892 (match-beginning 1)))))
1623 (if start (buffer-substring-no-properties start end)))) 1893 (if start (buffer-substring-no-properties start end))))
1624 1894
1625;; Fixme: We should have an abstraction of this sort of thing in the
1626;; core.
1627(defun python-complete-symbol () 1895(defun python-complete-symbol ()
1628 "Perform completion on the Python symbol preceding point. 1896 "Perform completion on the Python symbol preceding point.
1629Repeating the command scrolls the completion window." 1897Repeating the command scrolls the completion window."
@@ -1658,11 +1926,9 @@ Repeating the command scrolls the completion window."
1658 (display-completion-list completions symbol)) 1926 (display-completion-list completions symbol))
1659 (message "Making completion list...%s" "done")))))))) 1927 (message "Making completion list...%s" "done"))))))))
1660 1928
1661(eval-when-compile (require 'hippie-exp))
1662
1663(defun python-try-complete (old) 1929(defun python-try-complete (old)
1664 "Completion function for Python for use with `hippie-expand'." 1930 "Completion function for Python for use with `hippie-expand'."
1665 (when (eq major-mode 'python-mode) ; though we only add it locally 1931 (when (derived-mode-p 'python-mode) ; though we only add it locally
1666 (unless old 1932 (unless old
1667 (let ((symbol (python-partial-symbol))) 1933 (let ((symbol (python-partial-symbol)))
1668 (he-init-string (- (point) (length symbol)) (point)) 1934 (he-init-string (- (point) (length symbol)) (point))
@@ -1680,16 +1946,212 @@ Repeating the command scrolls the completion window."
1680 (if old (he-reset-string)) 1946 (if old (he-reset-string))
1681 nil))) 1947 nil)))
1682 1948
1949;;;; FFAP support
1950
1951(defun python-module-path (module)
1952 "Function for `ffap-alist' to return path to MODULE."
1953 (python-send-receive (format "emacs.modpath (%S)" module)))
1954
1955(eval-after-load "ffap"
1956 '(push '(python-mode . python-module-path) ffap-alist))
1957
1958;;;; Skeletons
1959
1960(defvar python-skeletons nil
1961 "Alist of named skeletons for Python mode.
1962Elements are of the form (NAME . EXPANDER-FUNCTION).")
1963
1964(defvar python-mode-abbrev-table nil
1965 "Abbrev table for Python mode.
1966The default contents correspond to the elements of `python-skeletons'.")
1967(define-abbrev-table 'python-mode-abbrev-table ())
1968
1969(eval-when-compile
1970 ;; Define a user-level skeleton and add it to `python-skeletons' and
1971 ;; the abbrev table.
1972(defmacro def-python-skeleton (name &rest elements)
1973 (let* ((name (symbol-name name))
1974 (function (intern (concat "python-insert-" name))))
1975 `(progn
1976 (add-to-list 'python-skeletons ',(cons name function))
1977 (define-abbrev python-mode-abbrev-table ,name "" ',function nil t)
1978 (define-skeleton ,function
1979 ,(format "Insert Python \"%s\" template." name)
1980 ,@elements)))))
1981(put 'def-python-skeleton 'lisp-indent-function 2)
1982
1983;; From `skeleton-further-elements':
1984;; `<': outdent a level;
1985;; `^': delete indentation on current line and also previous newline.
1986;; Not quote like `delete-indentation'. Assumes point is at
1987;; beginning of indentation.
1988
1989(def-python-skeleton if
1990 "Condition: "
1991 "if " str ":" \n
1992 > _ \n
1993 ("other condition, %s: "
1994 < ; Avoid wrong indentation after block opening.
1995 "elif " str ":" \n
1996 > _ \n nil)
1997 (python-else) | ^)
1998
1999(define-skeleton python-else
2000 "Auxiliary skeleton."
2001 nil
2002 (unless (eq ?y (read-char "Add `else' clause? (y for yes or RET for no) "))
2003 (signal 'quit t))
2004 < "else:" \n
2005 > _ \n)
2006
2007(def-python-skeleton while
2008 "Condition: "
2009 "while " str ":" \n
2010 > _ \n
2011 (python-else) | ^)
2012
2013(def-python-skeleton for
2014 "Target, %s: "
2015 "for " str " in " (skeleton-read "Expression, %s: ") ":" \n
2016 > _ \n
2017 (python-else) | ^)
2018
2019(def-python-skeleton try/except
2020 nil
2021 "try:" \n
2022 > _ \n
2023 ("Exception, %s: "
2024 < "except " str (python-target) ":" \n
2025 > _ \n nil)
2026 < "except:" \n
2027 > _ \n
2028 (python-else) | ^)
2029
2030(define-skeleton python-target
2031 "Auxiliary skeleton."
2032 "Target, %s: " ", " str | -2)
2033
2034(def-python-skeleton try/finally
2035 nil
2036 "try:" \n
2037 > _ \n
2038 < "finally:" \n
2039 > _ \n)
2040
2041(def-python-skeleton def
2042 "Name: "
2043 "def " str " (" ("Parameter, %s: " (unless (equal ?\( (char-before)) ", ")
2044 str) "):" \n
2045 "\"\"\"" @ " \"\"\"" \n ; Fixme: syntaxification wrong for """"""
2046 > _ \n)
2047
2048(def-python-skeleton class
2049 "Name: "
2050 "class " str " (" ("Inheritance, %s: "
2051 (unless (equal ?\( (char-before)) ", ")
2052 str)
2053 & ")" | -2 ; close list or remove opening
2054 ":" \n
2055 "\"\"\"" @ " \"\"\"" \n
2056 > _ \n)
2057
2058(defvar python-default-template "if"
2059 "Default template to expand by `python-insert-template'.
2060Updated on each expansion.")
2061
2062(defun python-expand-template (name)
2063 "Expand template named NAME.
2064Interactively, prompt for the name with completion."
2065 (interactive
2066 (list (completing-read (format "Template to expand (default %s): "
2067 python-default-template)
2068 python-skeletons nil t)))
2069 (if (equal "" name)
2070 (setq name python-default-template)
2071 (setq python-default-template name))
2072 (let ((func (cdr (assoc name python-skeletons))))
2073 (if func
2074 (funcall func)
2075 (error "Undefined template: %s" name))))
2076
2077;;;; Bicycle Repair Man support
2078
2079(autoload 'pymacs-load "pymacs" nil t)
2080(autoload 'brm-init "bikemacs")
2081
2082;; I'm not sure how useful BRM really is, and it's certainly dangerous
2083;; the way it modifies files outside Emacs... Also note that the
2084;; current BRM loses with tabs used for indentation -- I submitted a
2085;; fix <URL:http://www.loveshack.ukfsn.org/emacs/bikeemacs.py.diff>.
2086(defun python-setup-brm ()
2087 "Set up Bicycle Repair Man refactoring tool (if available).
2088
2089Note that the `refactoring' features change files independently of
2090Emacs and may modify and save the contents of the current buffer
2091without confirmation."
2092 (interactive)
2093 (condition-case data
2094 (unless (fboundp 'brm-rename)
2095 (pymacs-load "bikeemacs" "brm-") ; first line of normal recipe
2096 (let ((py-mode-map (make-sparse-keymap)) ; it assumes this
2097 (features (cons 'python-mode features))) ; and requires this
2098 (brm-init)) ; second line of normal recipe
2099 (remove-hook 'python-mode-hook ; undo this from `brm-init'
2100 '(lambda () (easy-menu-add brm-menu)))
2101 (easy-menu-define
2102 python-brm-menu python-mode-map
2103 "Bicycle Repair Man"
2104 '("BicycleRepairMan"
2105 :help "Interface to navigation and refactoring tool"
2106 "Queries"
2107 ["Find References" brm-find-references
2108 :help "Find references to name at point in compilation buffer"]
2109 ["Find Definition" brm-find-definition
2110 :help "Find definition of name at point"]
2111 "-"
2112 "Refactoring"
2113 ["Rename" brm-rename
2114 :help "Replace name at point with a new name everywhere"]
2115 ["Extract Method" brm-extract-method
2116 :active (and mark-active (not buffer-read-only))
2117 :help "Replace statements in region with a method"]
2118 ["Extract Local Variable" brm-extract-local-variable
2119 :active (and mark-active (not buffer-read-only))
2120 :help "Replace expression in region with an assignment"]
2121 ["Inline Local Variable" brm-inline-local-variable
2122 :help
2123 "Substitute uses of variable at point with its definition"]
2124 ;; Fixme: Should check for anything to revert.
2125 ["Undo Last Refactoring" brm-undo :help ""])))
2126 (error (error "Bicyclerepairman setup failed: %s" data))))
2127
1683;;;; Modes. 2128;;;; Modes.
1684 2129
1685(defvar outline-heading-end-regexp) 2130(defvar outline-heading-end-regexp)
1686(defvar eldoc-documentation-function) 2131(defvar eldoc-documentation-function)
1687 2132
2133;; Stuff to allow expanding abbrevs with non-word constituents.
2134(defun python-abbrev-pc-hook ()
2135 "Set the syntax table before possibly expanding abbrevs."
2136 (remove-hook 'post-command-hook 'python-abbrev-pc-hook t)
2137 (set-syntax-table python-mode-syntax-table))
2138
2139(defvar python-abbrev-syntax-table
2140 (copy-syntax-table python-mode-syntax-table)
2141 "Syntax table used when expanding abbrevs.")
2142
2143(defun python-pea-hook ()
2144 "Reset the syntax table after possibly expanding abbrevs."
2145 (set-syntax-table python-abbrev-syntax-table)
2146 (add-hook 'post-command-hook 'python-abbrev-pc-hook nil t))
2147(modify-syntax-entry ?/ "w" python-abbrev-syntax-table)
2148
2149(defvar python-mode-running) ;Dynamically scoped var.
2150
1688;;;###autoload 2151;;;###autoload
1689(define-derived-mode python-mode fundamental-mode "Python" 2152(define-derived-mode python-mode fundamental-mode "Python"
1690 "Major mode for editing Python files. 2153 "Major mode for editing Python files.
1691Turns on Font Lock mode unconditionally since it is required for correct 2154Font Lock mode is currently required for correct parsing of the source.
1692parsing of the source.
1693See also `jython-mode', which is actually invoked if the buffer appears to 2155See also `jython-mode', which is actually invoked if the buffer appears to
1694contain Jython code. See also `run-python' and associated Python mode 2156contain Jython code. See also `run-python' and associated Python mode
1695commands for running Python under Emacs. 2157commands for running Python under Emacs.
@@ -1703,21 +2165,27 @@ the end of definitions at that level, when they move up a level.
1703Colon is electric: it outdents the line if appropriate, e.g. for 2165Colon is electric: it outdents the line if appropriate, e.g. for
1704an else statement. \\[python-backspace] at the beginning of an indented statement 2166an else statement. \\[python-backspace] at the beginning of an indented statement
1705deletes a level of indentation to close the current block; otherwise it 2167deletes a level of indentation to close the current block; otherwise it
1706deletes a charcter backward. TAB indents the current line relative to 2168deletes a character backward. TAB indents the current line relative to
1707the preceding code. Successive TABs, with no intervening command, cycle 2169the preceding code. Successive TABs, with no intervening command, cycle
1708through the possibilities for indentation on the basis of enclosing blocks. 2170through the possibilities for indentation on the basis of enclosing blocks.
1709 2171
1710\\[fill-paragraph] fills comments and multiline strings appropriately, but has no 2172\\[fill-paragraph] fills comments and multi-line strings appropriately, but has no
1711effect outside them. 2173effect outside them.
1712 2174
1713Supports Eldoc mode (only for functions, using a Python process), 2175Supports Eldoc mode (only for functions, using a Python process),
1714Info-Look and Imenu. In Outline minor mode, `class' and `def' 2176Info-Look and Imenu. In Outline minor mode, `class' and `def'
1715lines count as headers. 2177lines count as headers. Symbol completion is available in the
2178same way as in the Python shell using the `rlcompleter' module
2179and this is added to the Hippie Expand functions locally if
2180Hippie Expand mode is turned on. Completion of symbols of the
2181form x.y only works if the components are literal
2182module/attribute names, not variables. An abbrev table is set up
2183with skeleton expansions for compound statement templates.
1716 2184
1717\\{python-mode-map}" 2185\\{python-mode-map}"
1718 :group 'python 2186 :group 'python
1719 (set (make-local-variable 'font-lock-defaults) 2187 (set (make-local-variable 'font-lock-defaults)
1720 '(python-font-lock-keywords nil nil ((?_ . "w")) nil 2188 '(python-font-lock-keywords nil nil nil nil
1721 (font-lock-syntactic-keywords 2189 (font-lock-syntactic-keywords
1722 . python-font-lock-syntactic-keywords) 2190 . python-font-lock-syntactic-keywords)
1723 ;; This probably isn't worth it. 2191 ;; This probably isn't worth it.
@@ -1726,15 +2194,17 @@ lines count as headers.
1726 )) 2194 ))
1727 (set (make-local-variable 'parse-sexp-lookup-properties) t) 2195 (set (make-local-variable 'parse-sexp-lookup-properties) t)
1728 (set (make-local-variable 'comment-start) "# ") 2196 (set (make-local-variable 'comment-start) "# ")
1729 (set (make-local-variable 'comment-indent-function) #'python-comment-indent)
1730 (set (make-local-variable 'indent-line-function) #'python-indent-line) 2197 (set (make-local-variable 'indent-line-function) #'python-indent-line)
2198 (set (make-local-variable 'indent-region-function) #'python-indent-region)
1731 (set (make-local-variable 'paragraph-start) "\\s-*$") 2199 (set (make-local-variable 'paragraph-start) "\\s-*$")
1732 (set (make-local-variable 'fill-paragraph-function) 'python-fill-paragraph) 2200 (set (make-local-variable 'fill-paragraph-function) 'python-fill-paragraph)
1733 (set (make-local-variable 'require-final-newline) mode-require-final-newline) 2201 (set (make-local-variable 'require-final-newline) mode-require-final-newline)
1734 (set (make-local-variable 'add-log-current-defun-function) 2202 (set (make-local-variable 'add-log-current-defun-function)
1735 #'python-current-defun) 2203 #'python-current-defun)
1736 ;; Fixme: Generalize to do all blocks? 2204 (set (make-local-variable 'outline-regexp)
1737 (set (make-local-variable 'outline-regexp) "\\s-*\\(def\\|class\\)\\>") 2205 (rx (* space) (or "class" "def" "elif" "else" "except" "finally"
2206 "for" "if" "try" "while")
2207 symbol-end))
1738 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n") 2208 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
1739 (set (make-local-variable 'outline-level) #'python-outline-level) 2209 (set (make-local-variable 'outline-level) #'python-outline-level)
1740 (set (make-local-variable 'open-paren-in-column-0-is-defun-start) nil) 2210 (set (make-local-variable 'open-paren-in-column-0-is-defun-start) nil)
@@ -1746,30 +2216,45 @@ lines count as headers.
1746 (set (make-local-variable 'eldoc-documentation-function) 2216 (set (make-local-variable 'eldoc-documentation-function)
1747 #'python-eldoc-function) 2217 #'python-eldoc-function)
1748 (add-hook 'eldoc-mode-hook 2218 (add-hook 'eldoc-mode-hook
1749 '(lambda () (run-python nil t)) nil t) ; need it running 2219 (lambda () (run-python nil t)) ; need it running
1750 (unless (assoc 'python-mode hs-special-modes-alist) 2220 nil t)
1751 (setq 2221 ;; Fixme: should be in hideshow. This seems to be of limited use
1752 hs-special-modes-alist 2222 ;; since it isn't (can't be) indentation-based. Also hide-level
1753 (cons (list 2223 ;; doesn't seem to work properly.
1754 'python-mode "^\\s-*def\\>" nil "#" 2224 (add-to-list 'hs-special-modes-alist
1755 (lambda (arg)(python-end-of-defun)(skip-chars-backward " \t\n")) 2225 `(python-mode "^\\s-*def\\>" nil "#"
1756 nil) 2226 ,(lambda (arg)
1757 hs-special-modes-alist))) 2227 (python-end-of-defun)
2228 (skip-chars-backward " \t\n"))
2229 nil))
2230 (set (make-local-variable 'skeleton-further-elements)
2231 '((< '(backward-delete-char-untabify (min python-indent
2232 (current-column))))
2233 (^ '(- (1+ (current-indentation))))))
2234 (add-hook 'pre-abbrev-expand-hook 'python-pea-hook nil t)
1758 (if (featurep 'hippie-exp) 2235 (if (featurep 'hippie-exp)
1759 (set (make-local-variable 'hippie-expand-try-functions-list) 2236 (set (make-local-variable 'hippie-expand-try-functions-list)
1760 (cons 'python-try-complete hippie-expand-try-functions-list))) 2237 (cons 'python-try-complete hippie-expand-try-functions-list)))
2238 ;; Python defines TABs as being 8-char wide.
2239 (set (make-local-variable 'tab-width) 8)
1761 (when python-guess-indent (python-guess-indent)) 2240 (when python-guess-indent (python-guess-indent))
2241 ;; Let's make it harder for the user to shoot himself in the foot.
2242 (unless (= tab-width python-indent)
2243 (setq indent-tabs-mode nil))
1762 (set (make-local-variable 'python-command) python-python-command) 2244 (set (make-local-variable 'python-command) python-python-command)
2245 (python-find-imports)
1763 (unless (boundp 'python-mode-running) ; kill the recursion from jython-mode 2246 (unless (boundp 'python-mode-running) ; kill the recursion from jython-mode
1764 (let ((python-mode-running t)) 2247 (let ((python-mode-running t))
1765 (python-maybe-jython)))) 2248 (python-maybe-jython))))
1766 2249
1767(custom-add-option 'python-mode-hook 'imenu-add-menubar-index) 2250(custom-add-option 'python-mode-hook 'imenu-add-menubar-index)
1768(custom-add-option 'python-mode-hook 2251(custom-add-option 'python-mode-hook
1769 '(lambda () 2252 (lambda ()
1770 "Turn on Indent Tabs mode." 2253 "Turn off Indent Tabs mode."
1771 (set (make-local-variable 'indent-tabs-mode) t))) 2254 (set (make-local-variable 'indent-tabs-mode) nil)))
1772(custom-add-option 'python-mode-hook 'turn-on-eldoc-mode) 2255(custom-add-option 'python-mode-hook 'turn-on-eldoc-mode)
2256(custom-add-option 'python-mode-hook 'abbrev-mode)
2257(custom-add-option 'python-mode-hook 'python-setup-brm)
1773 2258
1774;;;###autoload 2259;;;###autoload
1775(define-derived-mode jython-mode python-mode "Jython" 2260(define-derived-mode jython-mode python-mode "Jython"
@@ -1780,5 +2265,6 @@ Runs `jython-mode-hook' after `python-mode-hook'."
1780 (set (make-local-variable 'python-command) python-jython-command)) 2265 (set (make-local-variable 'python-command) python-jython-command))
1781 2266
1782(provide 'python) 2267(provide 'python)
2268(provide 'python-21)
1783;; arch-tag: 6fce1d99-a704-4de9-ba19-c6e4912b0554 2269;; arch-tag: 6fce1d99-a704-4de9-ba19-c6e4912b0554
1784;;; python.el ends here 2270;;; python.el ends here
diff --git a/lisp/progmodes/sh-script.el b/lisp/progmodes/sh-script.el
index 6098c8be067..f828c36917b 100644
--- a/lisp/progmodes/sh-script.el
+++ b/lisp/progmodes/sh-script.el
@@ -986,7 +986,9 @@ subshells can nest."
986 ;; FIXME: This can (and often does) match multiple lines, yet it makes no 986 ;; FIXME: This can (and often does) match multiple lines, yet it makes no
987 ;; effort to handle multiline cases correctly, so it ends up being 987 ;; effort to handle multiline cases correctly, so it ends up being
988 ;; rather flakey. 988 ;; rather flakey.
989 (when (re-search-forward "\"\\(?:\\(?:.\\|\n\\)*?[^\\]\\(?:\\\\\\\\\\)*\\)??\\(\\$(\\|`\\)" limit t) 989 (when (and (re-search-forward "\"\\(?:\\(?:.\\|\n\\)*?[^\\]\\(?:\\\\\\\\\\)*\\)??\\(\\$(\\|`\\)" limit t)
990 ;; Make sure the " we matched is an opening quote.
991 (eq ?\" (nth 3 (syntax-ppss))))
990 ;; bingo we have a $( or a ` inside a "" 992 ;; bingo we have a $( or a ` inside a ""
991 (let ((char (char-after (point))) 993 (let ((char (char-after (point)))
992 (continue t) 994 (continue t)
@@ -1081,9 +1083,6 @@ This is used to flag quote characters in subshell constructs inside strings
1081 ("\\(\\\\\\)'" 1 ,sh-st-punc) 1083 ("\\(\\\\\\)'" 1 ,sh-st-punc)
1082 ;; Make sure $@ and @? are correctly recognized as sexps. 1084 ;; Make sure $@ and @? are correctly recognized as sexps.
1083 ("\\$\\([?@]\\)" 1 ,sh-st-symbol) 1085 ("\\$\\([?@]\\)" 1 ,sh-st-symbol)
1084 ;; highlight (possibly nested) subshells inside "" quoted regions correctly.
1085 (sh-quoted-subshell
1086 (1 (sh-apply-quoted-subshell) t t))
1087 ;; Find HEREDOC starters and add a corresponding rule for the ender. 1086 ;; Find HEREDOC starters and add a corresponding rule for the ender.
1088 (sh-font-lock-here-doc 1087 (sh-font-lock-here-doc
1089 (2 (sh-font-lock-open-heredoc 1088 (2 (sh-font-lock-open-heredoc
@@ -1093,7 +1092,11 @@ This is used to flag quote characters in subshell constructs inside strings
1093 (and (match-beginning 3) (/= (match-beginning 3) (match-end 3)))) 1092 (and (match-beginning 3) (/= (match-beginning 3) (match-end 3))))
1094 nil t)) 1093 nil t))
1095 ;; Distinguish the special close-paren in `case'. 1094 ;; Distinguish the special close-paren in `case'.
1096 (")" 0 (sh-font-lock-paren (match-beginning 0))))) 1095 (")" 0 (sh-font-lock-paren (match-beginning 0)))
1096 ;; highlight (possibly nested) subshells inside "" quoted regions correctly.
1097 ;; This should be at the very end because it uses syntax-ppss.
1098 (sh-quoted-subshell
1099 (1 (sh-apply-quoted-subshell) t t))))
1097 1100
1098(defun sh-font-lock-syntactic-face-function (state) 1101(defun sh-font-lock-syntactic-face-function (state)
1099 (let ((q (nth 3 state))) 1102 (let ((q (nth 3 state)))
diff --git a/lisp/progmodes/vhdl-mode.el b/lisp/progmodes/vhdl-mode.el
index 987b37cf2c2..cf887394e6b 100644
--- a/lisp/progmodes/vhdl-mode.el
+++ b/lisp/progmodes/vhdl-mode.el
@@ -14112,8 +14112,8 @@ if required."
14112(defun vhdl-speedbar-display-directory (directory depth &optional rescan) 14112(defun vhdl-speedbar-display-directory (directory depth &optional rescan)
14113 "Display directory and hierarchy information in speedbar." 14113 "Display directory and hierarchy information in speedbar."
14114 (setq vhdl-speedbar-show-projects nil) 14114 (setq vhdl-speedbar-show-projects nil)
14115 (setq speedbar-ignored-path-regexp 14115 (setq speedbar-ignored-directory-regexp
14116 (speedbar-extension-list-to-regex speedbar-ignored-path-expressions)) 14116 (speedbar-extension-list-to-regex speedbar-ignored-directory-expressions))
14117 (setq directory (abbreviate-file-name (file-name-as-directory directory))) 14117 (setq directory (abbreviate-file-name (file-name-as-directory directory)))
14118 (setq speedbar-last-selected-file nil) 14118 (setq speedbar-last-selected-file nil)
14119 (speedbar-with-writable 14119 (speedbar-with-writable
@@ -14133,7 +14133,7 @@ if required."
14133(defun vhdl-speedbar-display-projects (project depth &optional rescan) 14133(defun vhdl-speedbar-display-projects (project depth &optional rescan)
14134 "Display projects and hierarchy information in speedbar." 14134 "Display projects and hierarchy information in speedbar."
14135 (setq vhdl-speedbar-show-projects t) 14135 (setq vhdl-speedbar-show-projects t)
14136 (setq speedbar-ignored-path-regexp ".") 14136 (setq speedbar-ignored-directory-regexp ".")
14137 (setq speedbar-last-selected-file nil) 14137 (setq speedbar-last-selected-file nil)
14138 (setq vhdl-speedbar-last-selected-project nil) 14138 (setq vhdl-speedbar-last-selected-project nil)
14139 (speedbar-with-writable 14139 (speedbar-with-writable